@aliou/pi-neuralwatt 0.19.3 → 0.20.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/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @aliou/pi-extension-template
2
2
 
3
+ ## 0.20.0
4
+
5
+ ### Minor Changes
6
+
7
+ - ab5888b: Track daily free energy from the new `daily_free_energy` block on `/v1/quota`: a Daily Free Energy bar in the Subscription tab with a per-billing-period total, a quota-warning stage when the day's allowance runs low (re-arms at UTC rollover, configurable via `quotaWarnings.freeEnergy.{enabled,warningPct}`), and a debounced quota refetch after covered-model responses. Closes #144.
8
+
3
9
  ## 0.19.3
4
10
 
5
11
  ### Patch Changes
@@ -270,7 +270,13 @@ function stampClassifierModels(models, baseUrl = NEURALWATT_BASE_URL) {
270
270
  }
271
271
  const DEFAULT_CONFIG = {
272
272
  quotaCommand: { enabled: true },
273
- quotaWarnings: { enabled: true },
273
+ quotaWarnings: {
274
+ enabled: true,
275
+ freeEnergy: {
276
+ enabled: true,
277
+ warningPct: 20
278
+ }
279
+ },
274
280
  provider: {
275
281
  api: "openai-completions",
276
282
  apiBaseUrl: "https://api.neuralwatt.com/v1"
@@ -25,6 +25,18 @@ function normalizeResolvedConfig(
25
25
  quotaWarnings: {
26
26
  enabled:
27
27
  config.quotaWarnings?.enabled ?? DEFAULT_CONFIG.quotaWarnings.enabled,
28
+ freeEnergy: {
29
+ enabled:
30
+ config.quotaWarnings?.freeEnergy?.enabled ??
31
+ DEFAULT_CONFIG.quotaWarnings.freeEnergy.enabled,
32
+ warningPct:
33
+ config.quotaWarnings?.freeEnergy?.warningPct === undefined
34
+ ? DEFAULT_CONFIG.quotaWarnings.freeEnergy.warningPct
35
+ : Math.max(
36
+ 0,
37
+ Math.min(100, config.quotaWarnings.freeEnergy.warningPct),
38
+ ),
39
+ },
28
40
  },
29
41
  hostedTools: config.hostedTools,
30
42
  provider: {
@@ -7,6 +7,7 @@ import { fetchQuotas } from "../../src/lib/neuralwatt-api";
7
7
  import { getNeuralwattApiKey } from "../_shared/auth";
8
8
  import { configuredApiBaseUrl } from "../_shared/config/loader";
9
9
  import { QuotasComponent } from "./components/quotas-display";
10
+ import { recordFreeEnergyDay } from "./free-energy-history";
10
11
 
11
12
  function missingAuthMessage(): string {
12
13
  const authPath = join(getAgentDir(), "auth.json");
@@ -52,6 +53,7 @@ export function registerQuotasCommand(
52
53
  );
53
54
  if (controller.signal.aborted) return;
54
55
  if (fetchResult.success) {
56
+ recordFreeEnergyDay(fetchResult.data.quotas);
55
57
  component.setState({
56
58
  type: "loaded",
57
59
  quotas: fetchResult.data.quotas,
@@ -2,8 +2,10 @@ import { truncateToWidth } from "@aliou/pi-utils-ui";
2
2
  import type { Theme } from "@earendil-works/pi-coding-agent";
3
3
  import type { NeuralwattQuotas } from "../../../src/types/quota-api";
4
4
  import {
5
+ isFreeEnergyStale,
5
6
  percentCreditsRemaining,
6
7
  percentEnergyRemaining,
8
+ percentFreeEnergyRemaining,
7
9
  severityFromPercent,
8
10
  } from "../../../src/utils/quota-bar";
9
11
  import {
@@ -78,6 +80,43 @@ export function renderSubscriptionTab(
78
80
  );
79
81
  }
80
82
 
83
+ // --- Daily free energy ---
84
+ const freeBlock = quotas.daily_free_energy;
85
+ if (freeBlock && !isFreeEnergyStale(freeBlock)) {
86
+ lines.push("");
87
+ lines.push(
88
+ truncateToWidth(
89
+ ` ${theme.fg("accent", theme.bold("Daily Free Energy"))}`,
90
+ maxWidth,
91
+ ),
92
+ );
93
+ const freePct = percentFreeEnergyRemaining(freeBlock);
94
+ const freeColor = severityFromPercent(freePct);
95
+ const freeBar = renderProgressBar(freePct, barWidth, theme, freeColor);
96
+ lines.push(
97
+ truncateToWidth(
98
+ ` ${freeBar} ${theme.fg(freeColor, `${freePct}%`)}`,
99
+ maxWidth,
100
+ ),
101
+ );
102
+ lines.push(
103
+ labelValue(
104
+ "Remaining",
105
+ `${formatKwh(freeBlock.kwh_remaining)} of ${formatKwh(freeBlock.kwh_included)}`,
106
+ maxWidth,
107
+ theme,
108
+ ),
109
+ );
110
+ lines.push(
111
+ labelValue(
112
+ "Resets",
113
+ freeEnergyResetLabel(freeBlock.reset_at),
114
+ maxWidth,
115
+ theme,
116
+ ),
117
+ );
118
+ }
119
+
81
120
  // --- Billing period ---
82
121
  lines.push("");
83
122
  lines.push(
@@ -95,7 +134,9 @@ export function renderSubscriptionTab(
95
134
  }
96
135
 
97
136
  /**
98
- * Credits tab — credit balance only.
137
+ * Credits tab — credit balance only. With energy accounting the balance is a
138
+ * top-up pool drawn only on demand, so it has no meaningful percentage against
139
+ * lifetime grants; it is shown as a plain balance in that case.
99
140
  */
100
141
  export function renderCreditsTab(
101
142
  quotas: NeuralwattQuotas,
@@ -104,13 +145,33 @@ export function renderCreditsTab(
104
145
  theme: Theme,
105
146
  ): string[] {
106
147
  const lines: string[] = [];
107
- const barWidth = Math.min(40, Math.max(20, contentWidth - 30));
108
148
 
109
- // --- Credit balance ---
110
149
  lines.push("");
111
150
  lines.push(
112
151
  truncateToWidth(` ${theme.fg("accent", theme.bold("Credits"))}`, maxWidth),
113
152
  );
153
+
154
+ if (quotas.balance.accounting_method === "energy") {
155
+ lines.push(
156
+ labelValue(
157
+ "Balance",
158
+ formatUsd(quotas.balance.credits_remaining_usd),
159
+ maxWidth,
160
+ theme,
161
+ ),
162
+ );
163
+ lines.push(
164
+ labelValue(
165
+ "Accounting",
166
+ quotas.balance.accounting_method,
167
+ maxWidth,
168
+ theme,
169
+ ),
170
+ );
171
+ return lines;
172
+ }
173
+
174
+ const barWidth = Math.min(40, Math.max(20, contentWidth - 30));
114
175
  const creditsPct = percentCreditsRemaining(quotas);
115
176
  const creditsColor = severityFromPercent(creditsPct);
116
177
  const creditsBar = renderProgressBar(
@@ -154,6 +215,7 @@ export function renderCreditsTab(
154
215
  */
155
216
  export function renderUsageKeyTab(
156
217
  quotas: NeuralwattQuotas,
218
+ periodFreeKwh: number,
157
219
  _contentWidth: number,
158
220
  maxWidth: number,
159
221
  theme: Theme,
@@ -178,6 +240,13 @@ export function renderUsageKeyTab(
178
240
  labelValue("Energy", formatKwh(usage.energy_kwh), maxWidth, theme),
179
241
  );
180
242
 
243
+ const freeBlock = quotas.daily_free_energy;
244
+ if (freeBlock && !isFreeEnergyStale(freeBlock)) {
245
+ lines.push(
246
+ labelValue("Free energy", formatKwh(periodFreeKwh), maxWidth, theme),
247
+ );
248
+ }
249
+
181
250
  // --- API Key ---
182
251
  lines.push("");
183
252
  lines.push(
@@ -238,6 +307,19 @@ export function renderUsageKeyTab(
238
307
  return lines;
239
308
  }
240
309
 
310
+ function freeEnergyResetLabel(resetAt: string): string {
311
+ const reset = new Date(resetAt);
312
+ const hhmm = `${String(reset.getHours()).padStart(2, "0")}:${String(reset.getMinutes()).padStart(2, "0")}`;
313
+ const minutes = Math.max(
314
+ 0,
315
+ Math.round((reset.getTime() - Date.now()) / 60_000),
316
+ );
317
+ const h = Math.floor(minutes / 60);
318
+ const m = minutes % 60;
319
+ const remaining = h > 0 ? `${h}h ${m}m` : `${m}m`;
320
+ return `${hhmm} local (${remaining} until reset)`;
321
+ }
322
+
241
323
  /** Format a label: value pair with aligned labels. */
242
324
  function labelValue(
243
325
  label: string,
@@ -4,6 +4,7 @@ import { DynamicBorder } from "@earendil-works/pi-coding-agent";
4
4
  import type { Component, TUI } from "@earendil-works/pi-tui";
5
5
  import { Loader, matchesKey } from "@earendil-works/pi-tui";
6
6
  import type { NeuralwattQuotas } from "../../../src/types/quota-api";
7
+ import { freeEnergyPeriodKwh } from "../free-energy-history";
7
8
  import {
8
9
  renderCreditsTab,
9
10
  renderSubscriptionTab,
@@ -175,7 +176,13 @@ export class QuotasComponent implements Component {
175
176
  return renderCreditsTab(quotas, contentWidth, maxWidth, this.theme);
176
177
  }
177
178
  // "Usage & Key"
178
- return renderUsageKeyTab(quotas, contentWidth, maxWidth, this.theme);
179
+ return renderUsageKeyTab(
180
+ quotas,
181
+ freeEnergyPeriodKwh(quotas),
182
+ contentWidth,
183
+ maxWidth,
184
+ this.theme,
185
+ );
179
186
  });
180
187
 
181
188
  // Equalize tab heights so switching doesn't cause layout jumps
@@ -0,0 +1,83 @@
1
+ import { readFileSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
4
+ import type { NeuralwattQuotas } from "../../src/types/quota-api";
5
+
6
+ const MAX_DAYS_NO_SUBSCRIPTION = 40;
7
+
8
+ interface FreeEnergyHistory {
9
+ days: Record<string, number>;
10
+ }
11
+
12
+ interface PeriodRange {
13
+ start: string;
14
+ end: string;
15
+ inclusiveEnd: boolean;
16
+ }
17
+
18
+ function historyPath(): string {
19
+ return join(getAgentDir(), "neuralwatt-free-energy-history.json");
20
+ }
21
+
22
+ function readHistory(): FreeEnergyHistory {
23
+ try {
24
+ return JSON.parse(readFileSync(historyPath(), "utf8")) as FreeEnergyHistory;
25
+ } catch {
26
+ return { days: {} };
27
+ }
28
+ }
29
+
30
+ function currentPeriodRange(quotas: NeuralwattQuotas): PeriodRange | undefined {
31
+ const sub = quotas.subscription;
32
+ if (!sub) return;
33
+ const start = sub.current_period_start.slice(0, 10);
34
+ const end = sub.current_period_end.slice(0, 10);
35
+ const inclusiveEnd =
36
+ Date.parse(sub.current_period_end) > Date.parse(`${end}T00:00:00Z`);
37
+ return { start, end, inclusiveEnd };
38
+ }
39
+
40
+ function inRange(day: string, range: PeriodRange): boolean {
41
+ if (day < range.start) return false;
42
+ return range.inclusiveEnd ? day <= range.end : day < range.end;
43
+ }
44
+
45
+ function writeHistory(history: FreeEnergyHistory): void {
46
+ writeFileSync(historyPath(), JSON.stringify(history));
47
+ }
48
+
49
+ /** Record the latest daily free-energy usage for today, pruning out-of-period days. */
50
+ export function recordFreeEnergyDay(quotas: NeuralwattQuotas): void {
51
+ const block = quotas.daily_free_energy;
52
+ if (!block) return;
53
+
54
+ const day = new Date().toISOString().slice(0, 10);
55
+ const history = readHistory();
56
+ history.days[day] = block.kwh_used;
57
+
58
+ const range = currentPeriodRange(quotas);
59
+ if (range) {
60
+ history.days = Object.fromEntries(
61
+ Object.entries(history.days).filter(([d]) => inRange(d, range)),
62
+ );
63
+ } else {
64
+ const cutoff = new Date(Date.now() - MAX_DAYS_NO_SUBSCRIPTION * 86_400_000)
65
+ .toISOString()
66
+ .slice(0, 10);
67
+ history.days = Object.fromEntries(
68
+ Object.entries(history.days).filter(([d]) => d >= cutoff),
69
+ );
70
+ }
71
+
72
+ writeHistory(history);
73
+ }
74
+
75
+ /** Sum the recorded daily free-energy usage across the current billing period. */
76
+ export function freeEnergyPeriodKwh(quotas: NeuralwattQuotas): number {
77
+ const range = currentPeriodRange(quotas);
78
+ if (!range) return 0;
79
+ const { days } = readHistory();
80
+ return Object.entries(days)
81
+ .filter(([d]) => inRange(d, range))
82
+ .reduce((sum, [, used]) => sum + used, 0);
83
+ }
@@ -155,6 +155,26 @@ export function registerNeuralwattSettings(
155
155
  ),
156
156
  loaded.has("quotaWarnings"),
157
157
  ),
158
+ {
159
+ id: "freeEnergyWarnings",
160
+ label: "Free-energy warnings",
161
+ description:
162
+ "Toggle notifications when the daily free-energy allowance runs low",
163
+ currentValue: resolved.quotaWarnings.freeEnergy.enabled
164
+ ? "enabled"
165
+ : "disabled",
166
+ values: ["enabled", "disabled"],
167
+ },
168
+ {
169
+ id: "freeEnergyWarningPct",
170
+ label: "Free-energy threshold",
171
+ description:
172
+ "Remaining percentage at which the free-energy warning fires",
173
+ currentValue: String(
174
+ resolved.quotaWarnings.freeEnergy.warningPct,
175
+ ),
176
+ values: ["10", "20", "30"],
177
+ },
158
178
  ],
159
179
  },
160
180
  ];
@@ -187,6 +207,35 @@ export function registerNeuralwattSettings(
187
207
  return updated;
188
208
  }
189
209
 
210
+ if (id === "freeEnergyWarnings") {
211
+ if (newValue !== "enabled" && newValue !== "disabled") return null;
212
+ return {
213
+ ...config,
214
+ quotaWarnings: {
215
+ ...config.quotaWarnings,
216
+ freeEnergy: {
217
+ ...config.quotaWarnings?.freeEnergy,
218
+ enabled: newValue === "enabled",
219
+ },
220
+ },
221
+ };
222
+ }
223
+
224
+ if (id === "freeEnergyWarningPct") {
225
+ const warningPct = Number(newValue);
226
+ if (!Number.isFinite(warningPct)) return null;
227
+ return {
228
+ ...config,
229
+ quotaWarnings: {
230
+ ...config.quotaWarnings,
231
+ freeEnergy: {
232
+ ...config.quotaWarnings?.freeEnergy,
233
+ warningPct,
234
+ },
235
+ },
236
+ };
237
+ }
238
+
190
239
  if (!getLoadedFeatures().has(id as NeuralwattFeatureId)) {
191
240
  return null;
192
241
  }
@@ -44,6 +44,7 @@ import { normalizeNeuralwattContextOverflowError } from "./context-overflow";
44
44
  import { buildQuotasFromHeaders, fetchRequestedQuotas } from "./quota-store";
45
45
 
46
46
  const HEADER_EMIT_THROTTLE_MS = 5_000;
47
+ const FREE_ENERGY_REFETCH_MS = 60_000;
47
48
 
48
49
  function emitConfigUpdated(pi: ExtensionAPI): void {
49
50
  pi.events.emit(NEURALWATT_CONFIG_UPDATED_EVENT, {
@@ -137,6 +138,36 @@ export default async function (pi: ExtensionAPI) {
137
138
 
138
139
  let lastHeaderEmitAt = 0;
139
140
  let quotaRequestInFlight = false;
141
+ let lastFreeEnergyRefetchAt = 0;
142
+
143
+ function isCoveredFreeEnergyModel(
144
+ provider: string,
145
+ modelId: string,
146
+ labels: string[],
147
+ ): boolean {
148
+ if (labels.length === 0) return false;
149
+ const name = currentModelRegistry?.find(provider, modelId)?.name;
150
+ return name !== undefined && labels.includes(name);
151
+ }
152
+
153
+ function refetchQuotasDebounced(): void {
154
+ const now = Date.now();
155
+ if (now - lastFreeEnergyRefetchAt < FREE_ENERGY_REFETCH_MS) return;
156
+ if (quotaRequestInFlight) return;
157
+ lastFreeEnergyRefetchAt = now;
158
+ void (async () => {
159
+ quotaRequestInFlight = true;
160
+ try {
161
+ const apiKey = currentModelRegistry
162
+ ? await getNeuralwattApiKey(currentModelRegistry)
163
+ : undefined;
164
+ const quotas = await fetchRequestedQuotas(apiKey);
165
+ if (quotas) emitQuotas(quotas, "api");
166
+ } finally {
167
+ quotaRequestInFlight = false;
168
+ }
169
+ })();
170
+ }
140
171
 
141
172
  function emitQuotas(
142
173
  quotas: NeuralwattQuotas,
@@ -220,9 +251,21 @@ export default async function (pi: ExtensionAPI) {
220
251
  pendingRateLimitInfo = undefined;
221
252
  }
222
253
 
254
+ const freeEnergyLabels =
255
+ latestQuotas?.daily_free_energy?.model_labels ?? [];
223
256
  const quotas = buildQuotasFromHeaders(event.headers);
224
257
  if (!quotas) return;
225
258
  emitQuotas(quotas, "header");
259
+
260
+ if (
261
+ isCoveredFreeEnergyModel(
262
+ ctx.model.provider,
263
+ ctx.model.id,
264
+ freeEnergyLabels,
265
+ )
266
+ ) {
267
+ refetchQuotasDebounced();
268
+ }
226
269
  });
227
270
 
228
271
  pi.events.on(NEURALWATT_QUOTAS_REQUEST_EVENT, async () => {
@@ -44,7 +44,7 @@ export default async function (pi: ExtensionAPI) {
44
44
  if (currentProvider !== "neuralwatt") return;
45
45
 
46
46
  const { quotas } = data as NeuralwattQuotasUpdatedPayload;
47
- checkQuotas(ctx, quotas);
47
+ checkQuotas(ctx, quotas, configLoader.getConfig().quotaWarnings.freeEnergy);
48
48
  }
49
49
 
50
50
  pi.on("session_start", async (_event, ctx) => {
@@ -1,5 +1,9 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import type { NeuralwattQuotas } from "../../src/types/quota-api";
3
+ import {
4
+ isFreeEnergyStale,
5
+ percentFreeEnergyRemaining,
6
+ } from "../../src/utils/quota-bar";
3
7
  import { formatKwh, formatUsd } from "../../src/utils/quota-format";
4
8
 
5
9
  export type WarningSeverity = "warning" | "critical";
@@ -166,6 +170,36 @@ function overageWarning(progress: OverageProgress): PendingWarning {
166
170
  };
167
171
  }
168
172
 
173
+ export interface FreeEnergyWarningsConfig {
174
+ enabled: boolean;
175
+ warningPct: number;
176
+ }
177
+
178
+ /**
179
+ * Daily free-energy allowance. The earliest stage: while the promo block is
180
+ * present and running low, it reports the day's allowance instead of the
181
+ * subscription pool it feeds. The UTC date in the key re-arms the alert at
182
+ * rollover, after a fresh fetch supplies the new day's block.
183
+ */
184
+ function freeEnergyWarning(
185
+ quotas: NeuralwattQuotas,
186
+ config: FreeEnergyWarningsConfig,
187
+ ): PendingWarning | undefined {
188
+ if (!config.enabled) return;
189
+ const block = quotas.daily_free_energy;
190
+ if (!block || isFreeEnergyStale(block)) return;
191
+ const pct = percentFreeEnergyRemaining(block);
192
+ if (pct > config.warningPct) return;
193
+ return {
194
+ key: `freeEnergy:${new Date().toISOString().slice(0, 10)}`,
195
+ severity: pct <= 0 ? "critical" : "warning",
196
+ message:
197
+ pct <= 0
198
+ ? "Daily free energy exhausted — covered models bill your plan until 00:00 UTC"
199
+ : `Daily free energy: ${pct}% remaining (${formatKwh(block.kwh_remaining)} of ${formatKwh(block.kwh_included)})`,
200
+ };
201
+ }
202
+
169
203
  /**
170
204
  * Warning progression mirrors Neuralwatt's billing order. Each stage uses its
171
205
  * own alert key, so once a later stage starts the earlier one stops — the
@@ -191,13 +225,17 @@ function overageWarning(progress: OverageProgress): PendingWarning {
191
225
  export function checkQuotas(
192
226
  ctx: ExtensionContext,
193
227
  quotas: NeuralwattQuotas,
228
+ freeEnergy: FreeEnergyWarningsConfig,
194
229
  ): void {
195
230
  if (!ctx.hasUI) return;
196
231
 
197
232
  const pending: PendingWarning[] = [];
198
233
  const sub = quotas.subscription;
199
234
 
200
- if (sub?.in_overage) {
235
+ const fw = freeEnergyWarning(quotas, freeEnergy);
236
+ if (fw) {
237
+ pending.push(fw);
238
+ } else if (sub?.in_overage) {
201
239
  const cap = quotas.limits.overage_limit_usd;
202
240
  if (cap !== null && cap > 0) {
203
241
  const progress = computeOverageProgress(quotas);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aliou/pi-neuralwatt",
3
- "version": "0.19.3",
3
+ "version": "0.20.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "private": false,
package/schema.json CHANGED
@@ -56,6 +56,23 @@
56
56
  "enabled": {
57
57
  "type": "boolean",
58
58
  "description": "Show quota warnings when credits or energy are low."
59
+ },
60
+ "freeEnergy": {
61
+ "$ref": "#/definitions/NeuralwattFreeEnergyWarningsConfig"
62
+ }
63
+ },
64
+ "additionalProperties": false
65
+ },
66
+ "NeuralwattFreeEnergyWarningsConfig": {
67
+ "type": "object",
68
+ "properties": {
69
+ "enabled": {
70
+ "type": "boolean",
71
+ "description": "Warn when the daily free-energy allowance runs low."
72
+ },
73
+ "warningPct": {
74
+ "type": "number",
75
+ "description": "Remaining-percentage threshold for the first warning."
59
76
  }
60
77
  },
61
78
  "additionalProperties": false
@@ -8,6 +8,10 @@ export const DEFAULT_CONFIG: ResolvedNeuralwattConfig = {
8
8
  },
9
9
  quotaWarnings: {
10
10
  enabled: true,
11
+ freeEnergy: {
12
+ enabled: true,
13
+ warningPct: 20,
14
+ },
11
15
  },
12
16
  provider: {
13
17
  api: "openai-completions",
@@ -3,9 +3,17 @@ export interface NeuralwattQuotaCommandConfig {
3
3
  enabled?: boolean;
4
4
  }
5
5
 
6
+ export interface NeuralwattFreeEnergyWarningsConfig {
7
+ /** Warn when the daily free-energy allowance runs low. */
8
+ enabled?: boolean;
9
+ /** Remaining-percentage threshold for the first warning. */
10
+ warningPct?: number;
11
+ }
12
+
6
13
  export interface NeuralwattQuotaWarningsConfig {
7
14
  /** Show quota warnings when credits or energy are low. */
8
15
  enabled?: boolean;
16
+ freeEnergy?: NeuralwattFreeEnergyWarningsConfig;
9
17
  }
10
18
 
11
19
  /**
@@ -58,6 +66,10 @@ export interface ResolvedNeuralwattConfig {
58
66
  };
59
67
  quotaWarnings: {
60
68
  enabled: boolean;
69
+ freeEnergy: {
70
+ enabled: boolean;
71
+ warningPct: number;
72
+ };
61
73
  };
62
74
  hostedTools?: NeuralwattHostedToolsConfig;
63
75
  provider: {
@@ -21,8 +21,18 @@ export interface NeuralwattSubscription {
21
21
  in_overage: boolean;
22
22
  }
23
23
 
24
+ /** Daily free-energy allowance block from /v1/quota. */
25
+ export interface NeuralwattDailyFreeEnergy {
26
+ kwh_included: number;
27
+ kwh_used: number;
28
+ kwh_remaining: number;
29
+ reset_at: string;
30
+ model_labels: string[];
31
+ }
32
+
24
33
  export interface NeuralwattQuotas {
25
34
  snapshot_at: string;
35
+ daily_free_energy?: NeuralwattDailyFreeEnergy;
26
36
  balance: {
27
37
  credits_remaining_usd: number;
28
38
  total_credits_usd: number;
@@ -1,3 +1,5 @@
1
+ import type { NeuralwattDailyFreeEnergy } from "../types/quota-api";
2
+
1
3
  export type Severity = "success" | "warning" | "error";
2
4
 
3
5
  export function severityFromPercent(pct: number): Severity {
@@ -21,3 +23,18 @@ export function percentEnergyRemaining(sub: {
21
23
  if (sub.kwh_included === 0) return 0;
22
24
  return Math.round((sub.kwh_remaining / sub.kwh_included) * 100);
23
25
  }
26
+
27
+ export function percentFreeEnergyRemaining(
28
+ block: Pick<NeuralwattDailyFreeEnergy, "kwh_included" | "kwh_remaining">,
29
+ ): number {
30
+ if (block.kwh_included === 0) return 0;
31
+ return Math.round((block.kwh_remaining / block.kwh_included) * 100);
32
+ }
33
+
34
+ /** True when the block's reset instant has passed without a refresh. */
35
+ export function isFreeEnergyStale(
36
+ block: Pick<NeuralwattDailyFreeEnergy, "reset_at">,
37
+ now: number = Date.now(),
38
+ ): boolean {
39
+ return Date.parse(block.reset_at) <= now;
40
+ }