feat(quota): add OpenCode Go usage tracking (#2155)
* feat(quota): add OpenCode Go usage tracking * fix(quota): align OpenCode Go VS Code parsing
This commit is contained in:
committed by
GitHub
parent
b4f50e0a01
commit
3d90eddcaf
@@ -31,6 +31,7 @@ These provider IDs are currently dispatchable via `fetchQuotaForProvider(provide
|
||||
| `minimax-cn-coding-plan` | MiniMax Coding Plan (minimaxi.com) | `providers/minimax-cn-coding-plan.js` / `providers/minimax-shared.js` | `minimax-cn-coding-plan` |
|
||||
| `ollama-cloud` | Ollama Cloud | `providers/ollama-cloud.js` | Cookie file at `~/.config/ollama-quota/cookie` (raw session cookie string) |
|
||||
| `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/` |
|
||||
|
||||
## Internal-only provider module
|
||||
- `providers/openai.js` exists for logic parity/reuse but is intentionally not registered for dispatcher ID routing.
|
||||
@@ -44,6 +45,8 @@ All providers should return results via shared helpers to preserve API shape:
|
||||
Provider modules must export `providerId`, `providerName`, `aliases`, `isConfigured(auth?)`, and `fetchQuota()`.
|
||||
`fetchQuota()` should return a quota result with `usage.windows` keyed by window name (for example `5h`, `7d`, `daily`) and optional provider-specific `usage.models` data.
|
||||
|
||||
OpenCode Go credentials are explicitly supplied by the user through Settings. OpenChamber never scans browser cookie stores. The server validates the credential before an atomic `0600` write and never returns the cookie through its API.
|
||||
|
||||
## Add a new provider (quick steps)
|
||||
1. Choose module shape based on complexity:
|
||||
- Simple providers: create `packages/web/server/lib/quota/providers/<provider>.js`.
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
const credentialsPath = () => path.join(
|
||||
process.env.OPENCHAMBER_DATA_DIR
|
||||
? path.resolve(process.env.OPENCHAMBER_DATA_DIR)
|
||||
: path.join(os.homedir(), '.config', 'openchamber'),
|
||||
'quota',
|
||||
'opencode-go.json',
|
||||
);
|
||||
|
||||
export const normalizeOpenCodeGoCredential = (value) => {
|
||||
const workspaceId = typeof value?.workspaceId === 'string' ? value.workspaceId.trim() : '';
|
||||
let authCookie = typeof value?.authCookie === 'string' ? value.authCookie.trim() : '';
|
||||
if (authCookie.startsWith('auth=')) authCookie = authCookie.slice(5).trim();
|
||||
if (!workspaceId || !authCookie || /[\r\n]/.test(workspaceId) || /[\r\n]/.test(authCookie)) {
|
||||
return null;
|
||||
}
|
||||
return { workspaceId, authCookie };
|
||||
};
|
||||
|
||||
export const readOpenCodeGoCredential = () => {
|
||||
try {
|
||||
const parsed = JSON.parse(fs.readFileSync(credentialsPath(), 'utf8'));
|
||||
return normalizeOpenCodeGoCredential(parsed);
|
||||
} catch (error) {
|
||||
if (error?.code !== 'ENOENT') console.warn('Failed to read OpenCode Go credentials');
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export const getOpenCodeGoCredentialStatus = () => {
|
||||
const credential = readOpenCodeGoCredential();
|
||||
return credential ? { configured: true, workspaceId: credential.workspaceId, authCookieMasked: '••••••••' } : { configured: false };
|
||||
};
|
||||
|
||||
export const writeOpenCodeGoCredential = (value) => {
|
||||
const credential = normalizeOpenCodeGoCredential(value);
|
||||
if (!credential) throw new Error('Workspace ID and auth cookie are required');
|
||||
const target = credentialsPath();
|
||||
const directory = path.dirname(target);
|
||||
const temporary = `${target}.${process.pid}.${Date.now()}.tmp`;
|
||||
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
||||
try {
|
||||
fs.writeFileSync(temporary, `${JSON.stringify(credential, null, 2)}\n`, { mode: 0o600 });
|
||||
fs.chmodSync(temporary, 0o600);
|
||||
fs.renameSync(temporary, target);
|
||||
fs.chmodSync(target, 0o600);
|
||||
} finally {
|
||||
try { fs.unlinkSync(temporary); } catch {}
|
||||
}
|
||||
return getOpenCodeGoCredentialStatus();
|
||||
};
|
||||
|
||||
export const deleteOpenCodeGoCredential = () => {
|
||||
try { fs.unlinkSync(credentialsPath()); } catch (error) {
|
||||
if (error?.code !== 'ENOENT') throw error;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,32 @@
|
||||
import { afterAll, afterEach, describe, expect, it } from 'bun:test';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { deleteOpenCodeGoCredential, getOpenCodeGoCredentialStatus, readOpenCodeGoCredential, writeOpenCodeGoCredential } from './opencode-go-credentials.js';
|
||||
|
||||
const previousDataDir = process.env.OPENCHAMBER_DATA_DIR;
|
||||
const temporaryDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'openchamber-go-'));
|
||||
process.env.OPENCHAMBER_DATA_DIR = temporaryDirectory;
|
||||
|
||||
afterEach(() => deleteOpenCodeGoCredential());
|
||||
|
||||
describe('OpenCode Go credential store', () => {
|
||||
it('normalizes, masks, and stores credentials with owner-only permissions', () => {
|
||||
const status = writeOpenCodeGoCredential({ workspaceId: ' wrk_test ', authCookie: ' auth=secret ' });
|
||||
expect(status).toEqual({ configured: true, workspaceId: 'wrk_test', authCookieMasked: '••••••••' });
|
||||
expect(readOpenCodeGoCredential()).toEqual({ workspaceId: 'wrk_test', authCookie: 'secret' });
|
||||
expect(fs.statSync(path.join(temporaryDirectory, 'quota', 'opencode-go.json')).mode & 0o777).toBe(0o600);
|
||||
});
|
||||
|
||||
it('removes credentials without exposing prior values', () => {
|
||||
writeOpenCodeGoCredential({ workspaceId: 'wrk_test', authCookie: 'secret' });
|
||||
deleteOpenCodeGoCredential();
|
||||
expect(getOpenCodeGoCredentialStatus()).toEqual({ configured: false });
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
if (previousDataDir === undefined) delete process.env.OPENCHAMBER_DATA_DIR;
|
||||
else process.env.OPENCHAMBER_DATA_DIR = previousDataDir;
|
||||
fs.rmSync(temporaryDirectory, { recursive: true, force: true });
|
||||
});
|
||||
@@ -22,6 +22,7 @@ import * as minimaxCodingPlan from './minimax-coding-plan.js';
|
||||
import * as minimaxCnCodingPlan from './minimax-cn-coding-plan.js';
|
||||
import * as ollamaCloud from './ollama-cloud.js';
|
||||
import * as wafer from './wafer.js';
|
||||
import * as opencodeGo from './opencode-go.js';
|
||||
|
||||
const registry = {
|
||||
claude: {
|
||||
@@ -113,6 +114,12 @@ const registry = {
|
||||
providerName: wafer.providerName,
|
||||
isConfigured: wafer.isConfigured,
|
||||
fetchQuota: wafer.fetchQuota
|
||||
},
|
||||
'opencode-go': {
|
||||
providerId: opencodeGo.providerId,
|
||||
providerName: opencodeGo.providerName,
|
||||
isConfigured: opencodeGo.isConfigured,
|
||||
fetchQuota: opencodeGo.fetchQuota
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { readOpenCodeGoCredential } from '../opencode-go-credentials.js';
|
||||
import { buildResult, toUsageWindow } from '../utils/index.js';
|
||||
|
||||
export const providerId = 'opencode-go';
|
||||
export const providerName = 'OpenCode Go';
|
||||
export const aliases = ['opencode-go'];
|
||||
|
||||
const patterns = {
|
||||
'5h': 'rollingUsage',
|
||||
weekly: 'weeklyUsage',
|
||||
monthly: 'monthlyUsage',
|
||||
};
|
||||
|
||||
const captureNumber = (name, body) => {
|
||||
const match = body.match(new RegExp(`["']?${name}["']?\\s*:\\s*["']?(-?\\d+(?:\\.\\d+)?)`));
|
||||
const value = match ? Number(match[1]) : null;
|
||||
return Number.isFinite(value) ? value : null;
|
||||
};
|
||||
|
||||
export const parseOpenCodeGoUsage = (html, now = Date.now()) => {
|
||||
if (typeof html !== 'string') return {};
|
||||
const normalized = html.replaceAll('"', '"').replaceAll('"', '"').replaceAll('\\u0022', '"').replaceAll('\\"', '"');
|
||||
const windows = {};
|
||||
for (const [key, field] of Object.entries(patterns)) {
|
||||
const escaped = field.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const match = normalized.match(new RegExp(`["']?${escaped}["']?\\s*:\\s*(?:\\$R\\[\\d+\\]\\s*=\\s*)?\\{([^{}]*)\\}`, 's'));
|
||||
if (!match) continue;
|
||||
const usedPercent = captureNumber('usagePercent', match[1]);
|
||||
const resetInSec = captureNumber('resetInSec', match[1]);
|
||||
if (usedPercent === null || resetInSec === null) continue;
|
||||
windows[key] = toUsageWindow({
|
||||
usedPercent: Math.min(100, Math.max(0, usedPercent)),
|
||||
resetAt: now + Math.max(0, resetInSec) * 1000,
|
||||
windowSeconds: null,
|
||||
});
|
||||
}
|
||||
return windows;
|
||||
};
|
||||
|
||||
export const fetchOpenCodeGoUsage = async (credential, fetchImpl = fetch) => {
|
||||
const response = await fetchImpl(`https://opencode.ai/workspace/${encodeURIComponent(credential.workspaceId)}/go`, {
|
||||
headers: {
|
||||
Accept: 'text/html,application/xhtml+xml',
|
||||
Cookie: `auth=${credential.authCookie}`,
|
||||
'User-Agent': 'OpenChamber quota provider',
|
||||
},
|
||||
signal: AbortSignal.timeout(15_000),
|
||||
});
|
||||
if (response.status === 401 || response.status === 403 || (response.redirected && /\/auth(?:\/|$|\?)/.test(new URL(response.url).pathname))) {
|
||||
throw new Error('OpenCode Go authentication failed');
|
||||
}
|
||||
if (!response.ok) throw new Error(`OpenCode Go dashboard returned HTTP ${response.status}`);
|
||||
const windows = parseOpenCodeGoUsage(await response.text());
|
||||
if (Object.keys(windows).length === 0) throw new Error('OpenCode Go usage data could not be parsed');
|
||||
return windows;
|
||||
};
|
||||
|
||||
export const isConfigured = () => Boolean(readOpenCodeGoCredential());
|
||||
|
||||
export const fetchQuota = async () => {
|
||||
const credential = readOpenCodeGoCredential();
|
||||
if (!credential) return buildResult({ providerId, providerName, ok: false, configured: false, error: 'Not configured' });
|
||||
try {
|
||||
const windows = await fetchOpenCodeGoUsage(credential);
|
||||
return buildResult({ providerId, providerName, ok: true, configured: true, usage: { windows } });
|
||||
} catch (error) {
|
||||
return buildResult({ providerId, providerName, ok: false, configured: true, error: error instanceof Error ? error.message : 'Request failed' });
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,17 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
import { fetchOpenCodeGoUsage, parseOpenCodeGoUsage } from './opencode-go.js';
|
||||
|
||||
describe('OpenCode Go quota provider', () => {
|
||||
it('parses partial SSR usage windows in either field order', () => {
|
||||
const windows = parseOpenCodeGoUsage('rollingUsage:$R[1]={usagePercent:25,resetInSec:60} weeklyUsage:$R[2]={resetInSec:120,usagePercent:40}', 1_000);
|
||||
expect(windows['5h'].usedPercent).toBe(25);
|
||||
expect(windows['5h'].resetAt).toBe(61_000);
|
||||
expect(windows.weekly.usedPercent).toBe(40);
|
||||
expect(windows.monthly).toBeUndefined();
|
||||
});
|
||||
|
||||
it('does not expose credentials in authentication errors', async () => {
|
||||
const credential = { workspaceId: 'wrk_test', authCookie: 'secret' };
|
||||
await expect(fetchOpenCodeGoUsage(credential, async () => new Response('', { status: 403 }))).rejects.toThrow('authentication failed');
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,13 @@
|
||||
import express from 'express';
|
||||
import {
|
||||
deleteOpenCodeGoCredential,
|
||||
getOpenCodeGoCredentialStatus,
|
||||
normalizeOpenCodeGoCredential,
|
||||
readOpenCodeGoCredential,
|
||||
writeOpenCodeGoCredential,
|
||||
} from './opencode-go-credentials.js';
|
||||
import { fetchOpenCodeGoUsage } from './providers/opencode-go.js';
|
||||
|
||||
export function registerQuotaRoutes(app, { getQuotaProviders }) {
|
||||
app.get('/api/quota/providers', async (_req, res) => {
|
||||
try {
|
||||
@@ -10,6 +20,37 @@ export function registerQuotaRoutes(app, { getQuotaProviders }) {
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/quota/credentials/opencode-go', (_req, res) => {
|
||||
res.json(getOpenCodeGoCredentialStatus());
|
||||
});
|
||||
|
||||
app.put('/api/quota/credentials/opencode-go', express.json({ limit: '16kb' }), async (req, res) => {
|
||||
try {
|
||||
const credential = normalizeOpenCodeGoCredential(req.body);
|
||||
if (!credential) return res.status(400).json({ error: 'Workspace ID and auth cookie are required' });
|
||||
await fetchOpenCodeGoUsage(credential);
|
||||
res.json(writeOpenCodeGoCredential(credential));
|
||||
} catch (error) {
|
||||
res.status(400).json({ error: error instanceof Error ? error.message : 'Credential validation failed' });
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/quota/credentials/opencode-go/validate', async (_req, res) => {
|
||||
try {
|
||||
const credential = readOpenCodeGoCredential();
|
||||
if (!credential) return res.status(404).json({ error: 'Not configured' });
|
||||
await fetchOpenCodeGoUsage(credential);
|
||||
res.json({ valid: true });
|
||||
} catch (error) {
|
||||
res.status(400).json({ valid: false, error: error instanceof Error ? error.message : 'Credential validation failed' });
|
||||
}
|
||||
});
|
||||
|
||||
app.delete('/api/quota/credentials/opencode-go', (_req, res) => {
|
||||
deleteOpenCodeGoCredential();
|
||||
res.json({ configured: false });
|
||||
});
|
||||
|
||||
app.get('/api/quota/:providerId', async (req, res) => {
|
||||
try {
|
||||
const { providerId } = req.params;
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { afterAll, describe, expect, it, mock } from 'bun:test';
|
||||
import express from 'express';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { registerQuotaRoutes } from './routes.js';
|
||||
|
||||
const previousDataDir = process.env.OPENCHAMBER_DATA_DIR;
|
||||
const temporaryDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'openchamber-go-routes-'));
|
||||
process.env.OPENCHAMBER_DATA_DIR = temporaryDirectory;
|
||||
|
||||
afterAll(() => {
|
||||
if (previousDataDir === undefined) delete process.env.OPENCHAMBER_DATA_DIR;
|
||||
else process.env.OPENCHAMBER_DATA_DIR = previousDataDir;
|
||||
fs.rmSync(temporaryDirectory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('OpenCode Go credential routes', () => {
|
||||
it('parses a JSON credential payload before validation', async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = mock(async () => new Response('rollingUsage:$R[1]={usagePercent:25,resetInSec:60}'));
|
||||
const app = express();
|
||||
registerQuotaRoutes(app, { getQuotaProviders: async () => ({}) });
|
||||
const server = app.listen(0);
|
||||
try {
|
||||
const address = server.address();
|
||||
if (!address || typeof address === 'string') throw new Error('Test server did not start');
|
||||
const response = await originalFetch(`http://127.0.0.1:${address.port}/api/quota/credentials/opencode-go`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ workspaceId: 'wrk_test', authCookie: 'auth=secret' }),
|
||||
});
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.json()).toEqual({ configured: true, workspaceId: 'wrk_test', authCookieMasked: '••••••••' });
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user