src/security/budget.ts
3 KB - Открыть исходный файл
// The spending ledger and the daily cap (lab 12).
//
// An always-on assistant spends money while you sleep: scheduled jobs, sub-agents, a loop that
// keeps retrying. The ledger records the cost of every completed turn, across all sessions, in
// <dataDir>/spend.jsonl. Before a turn starts, the gateway asks `exceeded()`; once today's spend
// reaches `limits.dailyUsd`, new turns are refused until midnight in the owner's time zone.
import { appendFile, mkdir, readFile } from 'node:fs/promises';
import path from 'node:path';
import type { StewardConfig } from '../config/config.ts';
import { costOfTurn } from '../context/usage.ts';
import type { TurnUsage } from '../core/turn-loop.ts';
import { dateInZone } from '../tools/time-tools.ts';
interface LedgerEntry {
ts: string;
day: string;
session: string;
model: string;
usd: number;
}
export class SpendLedger {
readonly file: string;
private readonly pricing: StewardConfig['pricing'];
private readonly timezone: string;
private readonly now: () => Date;
private readonly byDay = new Map<string, number>();
private loaded = false;
constructor(
dataDir: string,
pricing: StewardConfig['pricing'],
timezone: string,
now: () => Date = () => new Date(),
) {
this.file = path.join(dataDir, 'spend.jsonl');
this.pricing = pricing;
this.timezone = timezone;
this.now = now;
}
async record(session: string, model: string, usage: TurnUsage): Promise<number> {
await this.load();
// Each request at the price of the model that served it (a fallback model may answer).
const usd = costOfTurn(usage, model, this.pricing) ?? 0;
const now = this.now();
const entry: LedgerEntry = {
ts: now.toISOString(),
day: dateInZone(now, this.timezone),
session,
model,
usd,
};
await mkdir(path.dirname(this.file), { recursive: true });
await appendFile(this.file, JSON.stringify(entry) + '\n', 'utf8');
this.byDay.set(entry.day, (this.byDay.get(entry.day) ?? 0) + usd);
return usd;
}
async today(): Promise<number> {
await this.load();
return this.byDay.get(dateInZone(this.now(), this.timezone)) ?? 0;
}
/** True when a cap is set and today's spend has reached it. */
async exceeded(dailyUsd: number): Promise<boolean> {
return dailyUsd > 0 && (await this.today()) >= dailyUsd;
}
private async load(): Promise<void> {
if (this.loaded) return;
this.loaded = true;
let text = '';
try {
text = await readFile(this.file, 'utf8');
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;
}
for (const line of text.split('\n')) {
if (!line.trim()) continue;
try {
const entry = JSON.parse(line) as LedgerEntry;
this.byDay.set(entry.day, (this.byDay.get(entry.day) ?? 0) + entry.usd);
} catch {
// A torn last line (crash during a write) is skipped.
}
}
}
}