feat(quota): add Crof and NeuralWatt quota providers (#2415)

This commit is contained in:
pablogonzalez
2026-07-26 17:57:53 +03:00
committed by GitHub
parent 023ec2362e
commit e2b0a113b8
13 changed files with 1330 additions and 1 deletions
@@ -19,6 +19,7 @@ These provider IDs are currently dispatchable via `fetchQuotaForProvider(provide
| `claude` | Claude | `providers/claude.js` | `anthropic`, `claude` |
| `codex` | Codex | `providers/codex.js` | `openai`, `codex`, `chatgpt` |
| `cursor` | Cursor | `providers/cursor.js` | Environment/token files, OpenChamber-managed credentials, or explicit one-time Cursor import |
| `crof` | CrofAI | `providers/crof.js` | `crof` (API key under `key` or `token`) |
| `google` | Google | `providers/google/index.js` | `google`, `google.oauth`, Antigravity accounts file |
| `github-copilot` | GitHub Copilot | `providers/copilot.js` | `github-copilot`, `copilot` |
| `github-copilot-addon` | GitHub Copilot Add-on | `providers/copilot.js` | `github-copilot`, `copilot` |
@@ -32,6 +33,7 @@ These provider IDs are currently dispatchable via `fetchQuotaForProvider(provide
| `ollama-cloud` | Ollama Cloud | `providers/ollama-cloud.js` | Manual cookie stored under `~/.config/openchamber/quota/` |
| `wafer` | Wafer.ai | `providers/wafer.js` | `wafer`, `wafer-ai`, `wafer_ai`, `wafer.ai` |
| `opencode-go` | OpenCode Go | `providers/opencode-go.js` | Manual workspace ID and auth cookie stored under `~/.config/openchamber/quota/` |
| `neuralwatt` | NeuralWatt | `providers/neuralwatt.js` | `neuralwatt` (API key under `key` or `token`) |
## Internal-only provider module
- `providers/openai.js` exists for logic parity/reuse but is intentionally not registered for dispatcher ID routing.
@@ -0,0 +1,96 @@
import { readAuthFile } from '../../opencode/auth.js';
import {
getAuthEntry,
normalizeAuthEntry,
buildResult,
toUsageWindow,
toNumber,
formatMoney
} from '../utils/index.js';
export const providerId = 'crof';
export const providerName = 'CrofAI';
const aliases = ['crof'];
const CROF_USAGE_URL = 'https://crof.ai/usage_api/';
export const isConfigured = () => {
const auth = readAuthFile();
const entry = normalizeAuthEntry(getAuthEntry(auth, aliases));
return Boolean(entry?.key || entry?.token);
};
export const fetchQuota = async () => {
const auth = readAuthFile();
const entry = normalizeAuthEntry(getAuthEntry(auth, aliases));
const apiKey = entry?.key ?? entry?.token;
if (!apiKey) {
return buildResult({
providerId,
providerName,
ok: false,
configured: false,
error: 'Not configured'
});
}
const timeoutSignal = AbortSignal.timeout(15_000);
try {
const response = await fetch(CROF_USAGE_URL, {
method: 'GET',
headers: {
Authorization: `Bearer ${apiKey}`,
'Accept-Encoding': 'identity'
},
signal: timeoutSignal
});
if (!response.ok) {
return buildResult({
providerId,
providerName,
ok: false,
configured: true,
error: response.status === 401
? 'Session expired — please re-authenticate with CrofAI'
: `API error: ${response.status}`
});
}
const payload = await response.json();
const credits = toNumber(payload?.credits);
const valueLabel = credits !== null ? `$${formatMoney(credits)}` : null;
const windows = {
credits: toUsageWindow({
usedPercent: null,
windowSeconds: null,
resetAt: null,
valueLabel
})
};
return buildResult({
providerId,
providerName,
ok: true,
configured: true,
usage: { windows }
});
} catch (error) {
const isTimeout = error instanceof DOMException && error.name === 'AbortError' && timeoutSignal.aborted;
const isParseError = error instanceof SyntaxError;
return buildResult({
providerId,
providerName,
ok: false,
configured: true,
error: isTimeout
? 'Request timed out'
: isParseError
? 'Invalid response from provider'
: (error instanceof Error ? error.message : 'Request failed')
});
}
};
@@ -0,0 +1,98 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
vi.mock('../../opencode/auth.js', () => ({
readAuthFile: () => ({ crof: { key: 'test-token' } }),
}));
import { fetchQuota } from './crof.js';
afterEach(() => {
vi.unstubAllGlobals();
});
const mockResponse = (body, init = {}) => ({
ok: true,
status: 200,
json: async () => body,
...init,
});
describe('Crof quota provider', () => {
it('reports credits balance as valueLabel with null percent', async () => {
// Documented /usage_api/ response from https://crof.ai/docs.md
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(
mockResponse({ usable_requests: 450, credits: 12.3456 }),
));
const result = await fetchQuota();
expect(result.ok).toBe(true);
expect(result.providerId).toBe('crof');
expect(result.usage.windows.credits.usedPercent).toBeNull();
expect(result.usage.windows.credits.valueLabel).toBe('$12.35');
expect(result.usage.windows.credits.windowSeconds).toBeNull();
expect(result.usage.windows.credits.resetAt).toBeNull();
});
it('tolerates missing credits field', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(
mockResponse({ usable_requests: 0 }),
));
const result = await fetchQuota();
expect(result.ok).toBe(true);
expect(result.usage.windows.credits.valueLabel).toBeUndefined();
expect(result.usage.windows.credits.usedPercent).toBeNull();
});
it('parses numeric-string credits', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(
mockResponse({ credits: '99.5' }),
));
const result = await fetchQuota();
expect(result.usage.windows.credits.valueLabel).toBe('$99.50');
});
it('maps 401 to session-expired error', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: false,
status: 401,
json: async () => ({}),
}));
const result = await fetchQuota();
expect(result.ok).toBe(false);
expect(result.configured).toBe(true);
expect(result.error).toBe('Session expired — please re-authenticate with CrofAI');
});
it('surfaces non-401 API errors with status', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: false,
status: 503,
json: async () => ({}),
}));
const result = await fetchQuota();
expect(result.ok).toBe(false);
expect(result.error).toBe('API error: 503');
});
it('reports invalid-response on JSON parse failure', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
status: 200,
json: async () => { throw new SyntaxError('Unexpected token'); },
}));
const result = await fetchQuota();
expect(result.ok).toBe(false);
expect(result.error).toBe('Invalid response from provider');
});
});
@@ -10,6 +10,7 @@ import { buildResult } from '../utils/index.js';
import * as claude from './claude.js';
import * as codex from './codex.js';
import * as copilot from './copilot.js';
import * as crof from './crof.js';
import * as cursor from './cursor.js';
import * as google from './google/index.js';
import * as kimi from './kimi.js';
@@ -20,6 +21,7 @@ import * as zai from './zai.js';
import * as zhipuaiCodingPlan from './zhipuai-coding-plan.js';
import * as minimaxCodingPlan from './minimax-coding-plan.js';
import * as minimaxCnCodingPlan from './minimax-cn-coding-plan.js';
import * as neuralwatt from './neuralwatt.js';
import * as ollamaCloud from './ollama-cloud.js';
import * as wafer from './wafer.js';
import * as opencodeGo from './opencode-go.js';
@@ -37,6 +39,12 @@ const registry = {
isConfigured: codex.isConfigured,
fetchQuota: codex.fetchQuota
},
crof: {
providerId: crof.providerId,
providerName: crof.providerName,
isConfigured: crof.isConfigured,
fetchQuota: crof.fetchQuota
},
cursor: {
providerId: cursor.providerId,
providerName: cursor.providerName,
@@ -120,6 +128,12 @@ const registry = {
providerName: opencodeGo.providerName,
isConfigured: opencodeGo.isConfigured,
fetchQuota: opencodeGo.fetchQuota
},
neuralwatt: {
providerId: neuralwatt.providerId,
providerName: neuralwatt.providerName,
isConfigured: neuralwatt.isConfigured,
fetchQuota: neuralwatt.fetchQuota
}
};
@@ -0,0 +1,174 @@
import { readAuthFile } from '../../opencode/auth.js';
import {
getAuthEntry,
normalizeAuthEntry,
buildResult,
toUsageWindow,
toNumber,
toTimestamp,
formatMoney,
asNonEmptyString
} from '../utils/index.js';
export const providerId = 'neuralwatt';
export const providerName = 'NeuralWatt';
const aliases = ['neuralwatt'];
const NEURALWATT_QUOTA_URL = 'https://api.neuralwatt.com/v1/quota';
// 30d month / 365d year are fixed approximations; real calendars vary but the
// window is for the UI's progress bar label, not billing decisions.
const periodToWindowSeconds = (period) => {
if (period === 'daily') return 86400;
if (period === 'weekly') return 604800;
if (period === 'monthly' || period === 'month') return 30 * 86400;
if (period === 'yearly' || period === 'year') return 365 * 86400;
return null;
};
export const isConfigured = () => {
const auth = readAuthFile();
const entry = normalizeAuthEntry(getAuthEntry(auth, aliases));
return Boolean(entry?.key || entry?.token);
};
export const fetchQuota = async () => {
const auth = readAuthFile();
const entry = normalizeAuthEntry(getAuthEntry(auth, aliases));
const apiKey = entry?.key ?? entry?.token;
if (!apiKey) {
return buildResult({
providerId,
providerName,
ok: false,
configured: false,
error: 'Not configured'
});
}
const timeoutSignal = AbortSignal.timeout(15_000);
try {
const response = await fetch(NEURALWATT_QUOTA_URL, {
method: 'GET',
headers: {
Authorization: `Bearer ${apiKey}`,
'Accept-Encoding': 'identity'
},
signal: timeoutSignal
});
if (!response.ok) {
return buildResult({
providerId,
providerName,
ok: false,
configured: true,
error: response.status === 401
? 'Session expired — please re-authenticate with NeuralWatt'
: `API error: ${response.status}`
});
}
const payload = await response.json();
const subscription = payload?.subscription ?? null;
const inOverage = Boolean(subscription?.in_overage);
const allowance = payload?.key?.allowance ?? null;
const keyName = payload?.key?.name ?? null;
const creditsRemaining = toNumber(payload?.balance?.credits_remaining_usd);
const windows = {};
if (subscription) {
const kwhIncluded = toNumber(subscription.kwh_included);
const kwhUsed = toNumber(subscription.kwh_used);
const plan = asNonEmptyString(subscription.plan);
// Subscription window title is the plan name; subscription limits reset
// monthly even on annual billing plans, but the API exposes no kWh window
// start to derive windowSeconds — pass null rather than fabricating a guess.
const subKey = plan ?? 'plan_limit';
const usedPercent = inOverage
? 100
: (kwhIncluded !== null && kwhIncluded > 0 && kwhUsed !== null
? Math.max(0, Math.min(100, (kwhUsed / kwhIncluded) * 100))
: null);
const subResetAt = toTimestamp(subscription.kwh_reset_date) ?? toTimestamp(subscription.current_period_end);
windows[subKey] = toUsageWindow({
usedPercent,
windowSeconds: null,
resetAt: subResetAt
});
}
if (allowance) {
const spent = toNumber(allowance.spent_usd);
const limit = toNumber(allowance.limit_usd);
// Credits wallet is reduced by each period's spend before the allowance cap
// bites, so the real ceiling is min(limit, creditsRemaining + spent).
const effectiveSpent = spent ?? 0;
const effectiveLimit = limit !== null && creditsRemaining !== null
? Math.min(limit, creditsRemaining + effectiveSpent)
: (limit ?? creditsRemaining);
const period = asNonEmptyString(allowance.period);
const blocked = Boolean(allowance.blocked);
const usedPercent = blocked
? 100
: (spent !== null && effectiveLimit !== null && effectiveLimit > 0
? Math.max(0, Math.min(100, (spent / effectiveLimit) * 100))
: null);
// Window title is the localized period label (daily/weekly/monthly); key
// name is attached via valueLabel for identification (wafer precedent).
const periodKey = (period === 'daily' || period === 'weekly' || period === 'monthly' || period === 'month')
? (period === 'month' ? 'monthly' : period)
: 'billing_cycle';
const labelName = asNonEmptyString(keyName);
const resetAt = toTimestamp(allowance.reset_at);
const windowSeconds = period ? periodToWindowSeconds(period) : null;
windows[periodKey] = toUsageWindow({
usedPercent,
windowSeconds,
resetAt,
...(labelName ? { valueLabel: labelName } : {})
});
} else if (creditsRemaining !== null) {
windows.credits_balance = toUsageWindow({
usedPercent: null,
windowSeconds: null,
resetAt: null,
valueLabel: `$${formatMoney(creditsRemaining)}`
});
}
if (Object.keys(windows).length === 0) {
return buildResult({
providerId,
providerName,
ok: false,
configured: true,
error: 'No quota data in response'
});
}
return buildResult({
providerId,
providerName,
ok: true,
configured: true,
usage: { windows }
});
} catch (error) {
const isTimeout = error instanceof DOMException && error.name === 'AbortError' && timeoutSignal.aborted;
const isParseError = error instanceof SyntaxError;
return buildResult({
providerId,
providerName,
ok: false,
configured: true,
error: isTimeout
? 'Request timed out'
: isParseError
? 'Invalid response from provider'
: (error instanceof Error ? error.message : 'Request failed')
});
}
};
@@ -0,0 +1,287 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
vi.mock('../../opencode/auth.js', () => ({
readAuthFile: () => ({ neuralwatt: { key: 'test-token' } }),
}));
import { fetchQuota } from './neuralwatt.js';
afterEach(() => {
vi.unstubAllGlobals();
});
const mockResponse = (body, init = {}) => ({
ok: true,
status: 200,
json: async () => body,
...init,
});
// Documented payload shape from https://portal.neuralwatt.com/docs/api/quota
// Subscription has kwh_included=20.0, kwh_used=13.9023, plan="standard".
const DOCUMENTED_SUBSCRIPTION_PAYLOAD = {
snapshot_at: '2026-04-16T18:30:00Z',
balance: { credits_remaining_usd: 32.6774, total_credits_usd: 52.34, credits_used_usd: 19.6626, accounting_method: 'energy' },
usage: { lifetime: { cost_usd: 243.9145, requests: 37801, tokens: 1235477176, energy_kwh: 15.6009 }, current_month: { cost_usd: 160.1463, requests: 23902, tokens: 1116658995, energy_kwh: 9.7278 } },
limits: { overage_limit_usd: null, rate_limit_tier: 'standard' },
subscription: {
plan: 'standard',
status: 'active',
billing_interval: 'year',
current_period_start: '2026-04-11T05:05:25Z',
current_period_end: '2027-04-11T05:05:25Z',
auto_renew: true,
kwh_included: 20.0,
kwh_used: 13.9023,
kwh_remaining: 6.0977,
in_overage: false,
},
key: { name: 'my-production-key', allowance: null },
};
describe('NeuralWatt quota provider', () => {
it('builds subscription window from documented payload (keyed by plan name)', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(mockResponse(DOCUMENTED_SUBSCRIPTION_PAYLOAD)));
const result = await fetchQuota();
expect(result.ok).toBe(true);
expect(result.providerId).toBe('neuralwatt');
// Subscription window is keyed by the plan name; windowSeconds is null
// because the API exposes no kWh window start to derive duration from.
const window = result.usage.windows.standard;
expect(window).toBeDefined();
expect(window.usedPercent).toBeCloseTo((13.9023 / 20.0) * 100, 4);
expect(window.windowSeconds).toBeNull();
expect(window.resetAt).toBe(Date.parse('2027-04-11T05:05:25Z'));
// allowance is null, so the credits_balance window is *also* surfaced.
expect(result.usage.windows.credits_balance).toBeDefined();
expect(result.usage.windows.credits_balance.valueLabel).toBe('$32.68');
});
it('falls back to plan_limit title when plan is missing', async () => {
const payload = {
...DOCUMENTED_SUBSCRIPTION_PAYLOAD,
subscription: { ...DOCUMENTED_SUBSCRIPTION_PAYLOAD.subscription, plan: null },
};
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(mockResponse(payload)));
const result = await fetchQuota();
expect(result.usage.windows.plan_limit).toBeDefined();
expect(result.usage.windows.plan_limit.usedPercent).toBeCloseTo((13.9023 / 20.0) * 100, 4);
});
it('marks in-overage subscription as 100%, still shows credits', async () => {
const payload = {
...DOCUMENTED_SUBSCRIPTION_PAYLOAD,
subscription: { ...DOCUMENTED_SUBSCRIPTION_PAYLOAD.subscription, in_overage: true, kwh_used: 25.0 },
};
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(mockResponse(payload)));
const result = await fetchQuota();
const window = result.usage.windows.standard;
expect(window).toBeDefined();
expect(window.usedPercent).toBe(100);
expect(result.usage.windows.credits_balance.valueLabel).toBe('$32.68');
});
it('surfaces subscription and allowance windows (allowance keyed by period, key name in valueLabel)', async () => {
const payload = {
...DOCUMENTED_SUBSCRIPTION_PAYLOAD,
balance: { credits_remaining_usd: 200 },
key: {
name: 'Prod',
allowance: { limit_usd: 100, period: 'monthly', spent_usd: 25, blocked: false, reset_at: '2026-08-01T00:00:00Z' },
},
};
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(mockResponse(payload)));
const result = await fetchQuota();
const subWindow = result.usage.windows.standard;
expect(subWindow).toBeDefined();
expect(subWindow.usedPercent).toBeCloseTo((13.9023 / 20.0) * 100, 4);
// Allowance window is keyed by the localized period label ("monthly");
// key name flows through valueLabel for identification.
const allowWindow = result.usage.windows.monthly;
expect(allowWindow).toBeDefined();
expect(allowWindow.usedPercent).toBe(25);
expect(allowWindow.valueLabel).toBe('Prod');
expect(allowWindow.resetAt).toBe(Date.parse('2026-08-01T00:00:00Z'));
// credits_balance suppressed because allowance is present
expect(result.usage.windows.credits_balance).toBeUndefined();
});
it('uses allowance effective limit = min(limit, credits_remaining + spent)', async () => {
const payload = {
balance: { credits_remaining_usd: 30 },
subscription: null,
key: {
name: 'prod-key',
allowance: { limit_usd: 100, period: 'monthly', spent_usd: 25, blocked: false, reset_at: '2026-08-01T00:00:00Z' },
},
};
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(mockResponse(payload)));
const result = await fetchQuota();
const window = result.usage.windows.monthly;
expect(window).toBeDefined();
// effectiveLimit = min(100, 30+25) = 55; usedPercent = 25/55 * 100 ≈ 45.4545
expect(window.usedPercent).toBeCloseTo((25 / 55) * 100, 4);
expect(window.windowSeconds).toBe(30 * 86400);
expect(window.resetAt).toBe(Date.parse('2026-08-01T00:00:00Z'));
expect(window.valueLabel).toBe('prod-key');
expect(result.usage.windows.credits_balance).toBeUndefined();
});
it('binds allowance ceiling to limit when limit < credits_remaining + spent', async () => {
const payload = {
balance: { credits_remaining_usd: 200 },
subscription: null,
key: {
name: 'prod-key',
allowance: { limit_usd: 100, period: 'monthly', spent_usd: 25, blocked: false, reset_at: '2026-08-01T00:00:00Z' },
},
};
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(mockResponse(payload)));
const result = await fetchQuota();
const window = result.usage.windows.monthly;
expect(window).toBeDefined();
expect(window.usedPercent).toBe(25);
});
it('uses weekly as the allowance key when period is weekly', async () => {
const payload = {
balance: { credits_remaining_usd: 200 },
subscription: null,
key: {
name: 'Prod',
allowance: { limit_usd: 100, period: 'weekly', spent_usd: 20, blocked: false, reset_at: '2026-07-04T00:00:00Z' },
},
};
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(mockResponse(payload)));
const result = await fetchQuota();
const window = result.usage.windows.weekly;
expect(window).toBeDefined();
expect(window.windowSeconds).toBe(604800);
expect(window.resetAt).toBe(Date.parse('2026-07-04T00:00:00Z'));
expect(window.valueLabel).toBe('Prod');
});
it('uses daily as the allowance key when period is daily', async () => {
const payload = {
balance: { credits_remaining_usd: 200 },
subscription: null,
key: {
name: 'Prod',
allowance: { limit_usd: 10, period: 'daily', spent_usd: 2, blocked: false, reset_at: '2026-07-04T00:00:00Z' },
},
};
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(mockResponse(payload)));
const result = await fetchQuota();
const window = result.usage.windows.daily;
expect(window).toBeDefined();
expect(window.windowSeconds).toBe(86400);
expect(window.resetAt).toBe(Date.parse('2026-07-04T00:00:00Z'));
});
it('falls back to billing_cycle when allowance period is missing or unknown', async () => {
const payload = {
balance: { credits_remaining_usd: 200 },
subscription: null,
key: {
name: 'Prod',
allowance: { limit_usd: 100, period: 'fortnightly', spent_usd: 25, blocked: false, reset_at: '2026-08-01T00:00:00Z' },
},
};
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(mockResponse(payload)));
const result = await fetchQuota();
const window = result.usage.windows.billing_cycle;
expect(window).toBeDefined();
expect(window.usedPercent).toBe(25);
});
it('marks blocked allowance as 100% with valueLabel set', async () => {
const payload = {
balance: { credits_remaining_usd: 30 },
subscription: null,
key: {
name: 'sample',
allowance: { limit_usd: 50, period: 'monthly', spent_usd: 10, blocked: true, reset_at: '2026-08-01T00:00:00Z' },
},
};
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(mockResponse(payload)));
const result = await fetchQuota();
const window = result.usage.windows.monthly;
expect(window.usedPercent).toBe(100);
expect(window.valueLabel).toBe('sample');
});
it('falls back to credits_balance when neither subscription nor allowance exists', async () => {
const payload = {
balance: { credits_remaining_usd: 32.6774 },
subscription: null,
key: { name: 'sample', allowance: null },
};
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(mockResponse(payload)));
const result = await fetchQuota();
expect(result.usage.windows.credits_balance.valueLabel).toBe('$32.68');
expect(result.usage.windows.credits_balance.usedPercent).toBeNull();
});
it('maps 401 to session-expired error', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, status: 401, json: async () => ({}) }));
const result = await fetchQuota();
expect(result.ok).toBe(false);
expect(result.error).toBe('Session expired — please re-authenticate with NeuralWatt');
});
it('reports invalid-response on JSON parse failure', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
status: 200,
json: async () => { throw new SyntaxError('Unexpected token'); },
}));
const result = await fetchQuota();
expect(result.ok).toBe(false);
expect(result.error).toBe('Invalid response from provider');
});
it('returns no-quota-data on a 200 payload with no usable windows', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(mockResponse({
balance: { credits_remaining_usd: null },
subscription: null,
key: { name: 'sample', allowance: null },
})));
const result = await fetchQuota();
expect(result.ok).toBe(false);
expect(result.configured).toBe(true);
expect(result.error).toBe('No quota data in response');
expect(result.usage).toBeNull();
});
});