@aliou/pi-neuralwatt 0.19.3 → 0.21.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,21 @@
1
1
  # @aliou/pi-extension-template
2
2
 
3
+ ## 0.21.0
4
+
5
+ ### Minor Changes
6
+
7
+ - ebddddb: Add `/neuralwatt:flex` to toggle between standard and flex model variants, including models routed through a virtual model.
8
+
9
+ ### Patch Changes
10
+
11
+ - ed3cf03: Seed System One classifier models in the offline fallback table and verify them in the model drift check, sharing the provider's served-model filter.
12
+
13
+ ## 0.20.0
14
+
15
+ ### Minor Changes
16
+
17
+ - 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.
18
+
3
19
  ## 0.19.3
4
20
 
5
21
  ### 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"
@@ -712,6 +718,20 @@ const NEURALWATT_MODELS = [
712
718
  costMultiplier: .65
713
719
  }]]
714
720
  ].flatMap(([family, variants]) => buildNeuralwattFamily(family, variants));
721
+ const NEURALWATT_CLASSIFIERS = [{
722
+ type: "classifier",
723
+ api: NEURALWATT_SYSTEM_ONE_API,
724
+ id: "mammoth-1",
725
+ name: "mammoth-1",
726
+ input: ["text"],
727
+ cost: {
728
+ input: .18,
729
+ output: 0,
730
+ cacheRead: .018,
731
+ cacheWrite: 0
732
+ },
733
+ contextWindow: 32753
734
+ }];
715
735
  // src/models/catalog.ts
716
736
  function isNeuralwattClassifierModel(model) {
717
737
  return model.type === "classifier";
@@ -779,15 +799,20 @@ function apiModelToProviderModel(model) {
779
799
  }
780
800
  return result;
781
801
  }
802
+ const SERVED_TASKS = [
803
+ "chat",
804
+ "completions",
805
+ "decision"
806
+ ];
807
+ function isServedApiModel(model) {
808
+ const meta = model.metadata;
809
+ return !!meta && !meta.deprecated && !meta.pricing.pricing_tbd && (!meta.capabilities.task || SERVED_TASKS.includes(meta.capabilities.task));
810
+ }
782
811
  function buildNeuralwattProviderModels() {
783
- return NEURALWATT_MODELS.map((model) => ({ ...model }));
812
+ return [...NEURALWATT_MODELS.map((model) => ({ ...model })), ...NEURALWATT_CLASSIFIERS.map((model) => ({ ...model }))];
784
813
  }
785
814
  function buildNeuralwattProviderModelsFromApi(apiModels) {
786
- return apiModels.filter((m) => m.metadata && !m.metadata.deprecated && !m.metadata.pricing.pricing_tbd && !(m.metadata.capabilities.task && ![
787
- "chat",
788
- "completions",
789
- "decision"
790
- ].includes(m.metadata.capabilities.task))).map((m) => m.metadata?.capabilities.task === "decision" ? apiModelToClassifierModel(m) : apiModelToProviderModel(m));
815
+ return apiModels.filter(isServedApiModel).map((m) => m.metadata?.capabilities.task === "decision" ? apiModelToClassifierModel(m) : apiModelToProviderModel(m));
791
816
  }
792
817
  function buildNeuralwattProviderModelsFromStore(storedModels) {
793
818
  return storedModels.map((model) => ({ ...model }));
@@ -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
+ }
@@ -0,0 +1,35 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { toggleFlexMode } from "./flex-mode";
3
+
4
+ export function registerFlexModeCommand(pi: ExtensionAPI): void {
5
+ pi.registerCommand("neuralwatt:flex", {
6
+ description: "Toggle the Neuralwatt flex variant of the current model",
7
+ handler: async (_args, ctx) => {
8
+ const result = await toggleFlexMode(pi, ctx);
9
+ switch (result.status) {
10
+ case "toggled":
11
+ ctx.ui.notify(
12
+ `Neuralwatt: flex mode ${result.enabled ? "enabled" : "disabled"}`,
13
+ "info",
14
+ );
15
+ return;
16
+ case "requires-neuralwatt":
17
+ ctx.ui.notify(
18
+ result.virtual
19
+ ? "Neuralwatt: flex mode is unavailable until the virtual model routes to a Neuralwatt model"
20
+ : "Neuralwatt: flex mode requires a Neuralwatt model",
21
+ "error",
22
+ );
23
+ return;
24
+ case "missing-variant":
25
+ ctx.ui.notify(
26
+ `Neuralwatt: ${result.variant} variant is unavailable for ${result.modelName}`,
27
+ "error",
28
+ );
29
+ return;
30
+ case "switch-failed":
31
+ ctx.ui.notify("Neuralwatt: could not switch models", "error");
32
+ }
33
+ },
34
+ });
35
+ }
@@ -0,0 +1,84 @@
1
+ import type { Api, AssistantMessage, Model } from "@earendil-works/pi-ai";
2
+ import type {
3
+ ExtensionAPI,
4
+ ExtensionContext,
5
+ SessionEntry,
6
+ } from "@earendil-works/pi-coding-agent";
7
+
8
+ const FLEX_MODEL_SUFFIX = "-flex";
9
+
10
+ export type FlexModeResult =
11
+ | { status: "toggled"; enabled: boolean }
12
+ | { status: "requires-neuralwatt"; virtual: boolean }
13
+ | {
14
+ status: "missing-variant";
15
+ modelName: string;
16
+ variant: "standard" | "flex";
17
+ }
18
+ | { status: "switch-failed" };
19
+
20
+ function isVirtualModel(model: { api: string } | undefined): boolean {
21
+ return model?.api === "pi-virtual";
22
+ }
23
+
24
+ function isFlexModelId(modelId: string): boolean {
25
+ return modelId.endsWith(FLEX_MODEL_SUFFIX);
26
+ }
27
+
28
+ function flexVariantId(modelId: string): string {
29
+ return isFlexModelId(modelId)
30
+ ? modelId.slice(0, -FLEX_MODEL_SUFFIX.length)
31
+ : `${modelId}${FLEX_MODEL_SUFFIX}`;
32
+ }
33
+
34
+ function latestResponse(
35
+ branch: readonly SessionEntry[],
36
+ ): AssistantMessage | undefined {
37
+ for (let i = branch.length - 1; i >= 0; i--) {
38
+ const entry = branch[i];
39
+ if (entry.type !== "message") continue;
40
+ const message = entry.message;
41
+ if (message.role !== "assistant") continue;
42
+ if (message.stopReason === "error" || message.stopReason === "aborted")
43
+ continue;
44
+ return message;
45
+ }
46
+ return undefined;
47
+ }
48
+
49
+ function resolveModel(ctx: ExtensionContext): Model<Api> | undefined {
50
+ const selected = ctx.model;
51
+ if (selected && !isVirtualModel(selected)) {
52
+ return selected.provider === "neuralwatt" ? selected : undefined;
53
+ }
54
+ const routed = latestResponse(ctx.sessionManager.getBranch());
55
+ return routed?.provider === "neuralwatt"
56
+ ? ctx.modelRegistry.find("neuralwatt", routed.model)
57
+ : undefined;
58
+ }
59
+
60
+ export async function toggleFlexMode(
61
+ pi: ExtensionAPI,
62
+ ctx: ExtensionContext,
63
+ ): Promise<FlexModeResult> {
64
+ const model = resolveModel(ctx);
65
+ if (!model) {
66
+ return {
67
+ status: "requires-neuralwatt",
68
+ virtual: isVirtualModel(ctx.model),
69
+ };
70
+ }
71
+
72
+ const target = ctx.modelRegistry.find("neuralwatt", flexVariantId(model.id));
73
+ if (!target) {
74
+ return {
75
+ status: "missing-variant",
76
+ modelName: model.name,
77
+ variant: isFlexModelId(model.id) ? "standard" : "flex",
78
+ };
79
+ }
80
+
81
+ const switched = await pi.setModel(target);
82
+ if (!switched) return { status: "switch-failed" };
83
+ return { status: "toggled", enabled: isFlexModelId(target.id) };
84
+ }
@@ -0,0 +1,11 @@
1
+ import { bindProjectConfig } from "@aliou/pi-utils-settings";
2
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
+ import { configLoader } from "../_shared/config";
4
+ import { registerFlexModeCommand } from "./command";
5
+
6
+ export default async function (pi: ExtensionAPI) {
7
+ await configLoader.load();
8
+ bindProjectConfig(pi, configLoader);
9
+
10
+ registerFlexModeCommand(pi);
11
+ }
@@ -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.21.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "private": false,
@@ -23,6 +23,7 @@
23
23
  "pi": {
24
24
  "extensions": [
25
25
  "./extensions/provider/index.ts",
26
+ "./extensions/flex-mode/index.ts",
26
27
  "./extensions/command-quotas/index.ts",
27
28
  "./extensions/quota-warnings/index.ts"
28
29
  ],
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: {
@@ -8,7 +8,7 @@ import {
8
8
  resolveMaxTokens,
9
9
  type ThinkingLevelMap,
10
10
  } from "./build";
11
- import { NEURALWATT_MODELS } from "./public-models";
11
+ import { NEURALWATT_CLASSIFIERS, NEURALWATT_MODELS } from "./public-models";
12
12
 
13
13
  export type NeuralwattChatModel = NeuralwattCompiledModel;
14
14
 
@@ -125,26 +125,35 @@ function apiModelToProviderModel(
125
125
  return result;
126
126
  }
127
127
 
128
+ const SERVED_TASKS = ["chat", "completions", "decision"] as const;
129
+
130
+ export function isServedApiModel(
131
+ model: NeuralwattApiModel,
132
+ ): model is NeuralwattApiModel & {
133
+ metadata: NonNullable<NeuralwattApiModel["metadata"]>;
134
+ } {
135
+ const meta = model.metadata;
136
+ return (
137
+ !!meta &&
138
+ !meta.deprecated &&
139
+ !meta.pricing.pricing_tbd &&
140
+ (!meta.capabilities.task ||
141
+ (SERVED_TASKS as readonly string[]).includes(meta.capabilities.task))
142
+ );
143
+ }
144
+
128
145
  export function buildNeuralwattProviderModels(): NeuralwattModel[] {
129
- return NEURALWATT_MODELS.map((model) => ({ ...model }));
146
+ return [
147
+ ...NEURALWATT_MODELS.map((model) => ({ ...model })),
148
+ ...NEURALWATT_CLASSIFIERS.map((model) => ({ ...model })),
149
+ ];
130
150
  }
131
151
 
132
152
  export function buildNeuralwattProviderModelsFromApi(
133
153
  apiModels: readonly NeuralwattApiModel[],
134
154
  ): NeuralwattModel[] {
135
155
  const models = apiModels
136
- .filter(
137
- (m) =>
138
- m.metadata &&
139
- !m.metadata.deprecated &&
140
- !m.metadata.pricing.pricing_tbd &&
141
- !(
142
- m.metadata.capabilities.task &&
143
- !["chat", "completions", "decision"].includes(
144
- m.metadata.capabilities.task,
145
- )
146
- ),
147
- )
156
+ .filter(isServedApiModel)
148
157
  .map((m) =>
149
158
  m.metadata?.capabilities.task === "decision"
150
159
  ? apiModelToClassifierModel(m)
@@ -2,9 +2,10 @@ export {
2
2
  buildNeuralwattProviderModels,
3
3
  buildNeuralwattProviderModelsFromApi,
4
4
  buildNeuralwattProviderModelsFromStore,
5
+ isServedApiModel,
5
6
  type NeuralwattModel,
6
7
  } from "./catalog";
7
- export { NEURALWATT_MODELS } from "./public-models";
8
+ export { NEURALWATT_CLASSIFIERS, NEURALWATT_MODELS } from "./public-models";
8
9
  export {
9
10
  createNeuralwattRefreshModels,
10
11
  type FetchNeuralwattApiModels,
@@ -1,5 +1,7 @@
1
1
  import {
2
2
  buildNeuralwattFamily,
3
+ NEURALWATT_SYSTEM_ONE_API,
4
+ type NeuralwattClassifierModel,
3
5
  type NeuralwattModelFamily,
4
6
  type NeuralwattVariantSpec,
5
7
  type ProviderChatModelConfig,
@@ -412,3 +414,17 @@ const FAMILIES: [NeuralwattModelFamily, NeuralwattVariantSpec[]][] = [
412
414
  export const NEURALWATT_MODELS: ProviderChatModelConfig[] = FAMILIES.flatMap(
413
415
  ([family, variants]) => buildNeuralwattFamily(family, variants),
414
416
  );
417
+
418
+ // System One classifier models (`metadata.capabilities.task === "decision"`).
419
+ // Served on POST /v1/systemone; no reasoning, compat, or output tokens.
420
+ export const NEURALWATT_CLASSIFIERS: NeuralwattClassifierModel[] = [
421
+ {
422
+ type: "classifier",
423
+ api: NEURALWATT_SYSTEM_ONE_API,
424
+ id: "mammoth-1",
425
+ name: "mammoth-1",
426
+ input: ["text"],
427
+ cost: { input: 0.18, output: 0, cacheRead: 0.018, cacheWrite: 0 },
428
+ contextWindow: 32753,
429
+ },
430
+ ];
@@ -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
+ }