peppa/packages/core/src/usage.ts
peppa-bot f3d10a4c25 PEP-243: платформа называется FORGE — название во всех текстах для людей и подсказках агентам, адрес forge.telecom.quest
«Peppa FACTORY» → «FORGE» в экранах, сообщениях, словарях en/kk, шаблоне и тестах; «Пеппа» → «FORGE» в подсказках
агентам и правилах; логотип, значок, версия кэша service worker; в словаре старые названия — в «Нельзя».
Внутренние имена (CLI peppa, PEPPA_*, MCP-сервер peppa, ключи PEP-N) не меняются. Второй адрес — в mac-route.sh.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 11:18:49 +05:00

406 lines
20 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// PEP-5: what agents spend and how much of the subscription limits is left.
// Sources: Claude Code's statusLine command (cost, context window, 5h/7d limit windows) and
// the session transcript (token usage of every assistant message). Codex/OpenCode report
// neither — the UI says «нет данных» rather than inventing numbers.
import { m as tr } from "@peppa/shared/i18n";
import { readFileSync } from "node:fs";
import { projects, sessions, settings, subscriptionPoolMembers, subscriptions, type Db, type SessionUsage, type UsageTokens, keyPrefix } from "@peppa/db";
import { and, eq, inArray, like, notInArray } from "drizzle-orm";
import type { User } from "./users.ts";
import { userProjectIds } from "./users.ts";
import { isSuperadmin } from "./monitor.ts";
import { visibleSubscriptionName } from "./subscription-names.ts";
export type { SessionUsage, UsageTokens };
export interface UsageWindow {
/** Used share of the window, 0..100. */
pct: number;
resetsAt: number | null;
}
export interface AccountWindows {
fiveHour?: UsageWindow;
sevenDay?: UsageWindow;
at: number;
sessionId?: number;
}
export interface StatusLineData {
costUsd?: number;
context?: { used: number; size: number; pct: number };
tokens?: { input: number; output: number };
windows: { fiveHour?: UsageWindow; sevenDay?: UsageWindow };
model?: string;
}
const num = (v: unknown): number | undefined => (typeof v === "number" && Number.isFinite(v) ? v : typeof v === "string" && v.trim() !== "" && Number.isFinite(Number(v)) ? Number(v) : undefined);
const obj = (v: unknown): Record<string, unknown> | undefined => (v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : undefined);
/** ISO string, epoch seconds or epoch ms → ms. */
function toMs(v: unknown): number | null {
if (typeof v === "string" && !/^\d+(\.\d+)?$/.test(v.trim())) {
const t = Date.parse(v);
return Number.isNaN(t) ? null : t;
}
const n = num(v);
if (n == null) return null;
return n < 1e12 ? Math.round(n * 1000) : Math.round(n);
}
function parseWindow(v: unknown): UsageWindow | undefined {
const o = obj(v);
if (!o) return undefined;
let pct = num(o.used_percentage ?? o.usedPercentage ?? o.percent ?? o.used_percent ?? o.pct);
if (pct == null) {
const u = num(o.utilization);
if (u != null) pct = u <= 1 ? u * 100 : u;
}
if (pct == null) return undefined;
return { pct: Math.max(0, Math.min(100, Math.round(pct * 10) / 10)), resetsAt: toMs(o.resets_at ?? o.resetsAt ?? o.reset_at ?? o.resets) };
}
/**
* Claude Code statusLine JSON → what Peppa keeps. Checked against live 2.1.323 (PEP-3, fixture
* `packages/testkit/fixtures/claude-live/statusline.json`); still tolerant to field name variants.
*/
export function parseStatusLine(input: unknown): StatusLineData {
const j = obj(input) ?? {};
const cost = obj(j.cost);
const cw = obj(j.context_window ?? j.contextWindow);
const rl = obj(j.rate_limits ?? j.rateLimits ?? j.usage_limits);
const out: StatusLineData = { windows: {} };
const c = num(cost?.total_cost_usd ?? cost?.totalCostUsd);
if (c != null) out.costUsd = c;
if (cw) {
const size = num(cw.context_window_size ?? cw.size);
const cur = obj(cw.current_usage);
const used = cur ? (num(cur.input_tokens) ?? 0) + (num(cur.cache_read_input_tokens) ?? 0) + (num(cur.cache_creation_input_tokens) ?? 0) : num(cw.used_tokens);
const pct = num(cw.used_percentage) ?? (used != null && size ? (used / size) * 100 : undefined);
if (size && (used != null || pct != null)) out.context = { used: used ?? Math.round(((pct ?? 0) / 100) * size), size, pct: Math.round((pct ?? 0) * 10) / 10 };
// PEP-3 (live 2.1.323): `total_input_tokens` / `total_output_tokens` are the LAST request
// (= current_usage input+cache / output), not session totals — tokens come from the transcript.
}
if (rl) {
const five = parseWindow(rl.five_hour ?? rl.fiveHour ?? rl["5h"] ?? rl.session);
const seven = parseWindow(rl.seven_day ?? rl.sevenDay ?? rl["7d"] ?? rl.weekly);
if (five) out.windows.fiveHour = five;
if (seven) out.windows.sevenDay = seven;
}
const model = obj(j.model);
const m = typeof model?.id === "string" ? model.id : typeof j.model === "string" ? j.model : undefined;
if (m) out.model = m;
return out;
}
const zero = (): UsageTokens => ({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0 });
/** Sums `message.usage` of assistant entries in a Claude transcript (deduplicated by message id). */
export function transcriptUsage(path: string | undefined | null): { tokens: UsageTokens; model?: string } | null {
if (!path) return null;
let text: string;
try {
text = readFileSync(path, "utf8");
} catch {
return null;
}
const byId = new Map<string, UsageTokens>();
let model: string | undefined;
let anon = 0;
for (const line of text.split("\n")) {
if (!line.includes('"usage"')) continue;
let e: { type?: string; message?: { id?: string; model?: string; usage?: Record<string, unknown> } };
try {
e = JSON.parse(line);
} catch {
continue;
}
const u = e.type === "assistant" ? e.message?.usage : undefined;
if (!u) continue;
if (e.message?.model && e.message.model !== "<synthetic>") model = e.message.model;
byId.set(e.message?.id ?? `anon-${anon++}`, {
input: num(u.input_tokens) ?? 0,
output: num(u.output_tokens) ?? 0,
cacheRead: num(u.cache_read_input_tokens) ?? 0,
cacheWrite: num(u.cache_creation_input_tokens) ?? 0,
});
}
if (!byId.size) return null;
const tokens = zero();
for (const t of byId.values()) addTokens(tokens, t);
return { tokens, model };
}
function addTokens(a: UsageTokens, b: Partial<UsageTokens>) {
a.input += b.input ?? 0;
a.output += b.output ?? 0;
a.cacheRead += b.cacheRead ?? 0;
a.cacheWrite += b.cacheWrite ?? 0;
}
/** API list prices, $ per million tokens — only for an estimate («≈») when Claude reported no cost. */
const PRICES: Array<[RegExp, number, number]> = [
[/opus/i, 5, 25],
[/haiku/i, 1, 5],
[/sonnet|claude/i, 3, 15],
];
export function estimateCost(t: UsageTokens, model?: string): number {
const [, inP, outP] = PRICES.find(([re]) => re.test(model ?? "")) ?? PRICES[2]!;
return (t.input * inP + t.output * outP + t.cacheRead * inP * 0.1 + t.cacheWrite * inP * 1.25) / 1e6;
}
export const totalTokens = (t: UsageTokens) => t.input + t.output + t.cacheRead + t.cacheWrite;
export interface UsageTotals {
hasData: boolean;
tokens: UsageTokens;
/** input + output + cache. */
total: number;
costUsd: number | null;
/** The cost is an estimate from list prices, not reported by the agent. */
estimated: boolean;
context: SessionUsage["context"] | null;
}
export function usageTotals(u: SessionUsage | null | undefined): UsageTotals {
const tokens = zero();
const convs = Object.values(u?.convs ?? {});
for (const c of convs) addTokens(tokens, c);
if (!convs.length) for (const g of Object.values(u?.tokensByGen ?? {})) addTokens(tokens, g);
const costs = Object.values(u?.costByGen ?? {});
const total = totalTokens(tokens);
let costUsd: number | null = costs.length ? costs.reduce((a, b) => a + b, 0) : null;
let estimated = false;
if (costUsd == null && total > 0) {
costUsd = convs.length ? convs.reduce((a, c) => a + estimateCost(c, c.model), 0) : estimateCost(tokens, u?.model);
estimated = true;
}
return { hasData: total > 0 || costUsd != null || !!u?.context, tokens, total, costUsd, estimated, context: u?.context ?? null };
}
export function sumTotals(list: UsageTotals[]): UsageTotals {
const tokens = zero();
let cost: number | null = null;
let estimated = false;
for (const t of list) {
addTokens(tokens, t.tokens);
if (t.costUsd != null) cost = (cost ?? 0) + t.costUsd;
estimated ||= t.estimated;
}
return { hasData: list.some((t) => t.hasData), tokens, total: totalTokens(tokens), costUsd: cost, estimated, context: null };
}
/** Applies `fn` to the session's usage inside one write transaction (statusLine and Stop hooks race). */
function mutateUsage(db: Db, sessionId: number, fn: (u: SessionUsage) => boolean) {
db.transaction(
(tx) => {
const row = tx.select({ usage: sessions.usage }).from(sessions).where(eq(sessions.id, sessionId)).get();
if (!row) return;
const u: SessionUsage = structuredClone(row.usage ?? {});
if (fn(u)) tx.update(sessions).set({ usage: u }).where(eq(sessions.id, sessionId)).run();
},
{ behavior: "immediate" },
);
}
const STATUS_WRITE_MS = 20_000;
/** statusLine fired: cost and context on the session, limit windows on its account. Throttled. */
export async function recordStatusLine(
db: Db,
s: { id: number; generation: number; subscriptionId: number | null },
data: StatusLineData,
now = Date.now(),
): Promise<boolean> {
let wrote = false;
mutateUsage(db, s.id, (u) => {
const gen = String(s.generation);
const prevCost = u.costByGen?.[gen];
const changed =
(data.costUsd != null && Math.abs((prevCost ?? -1) - data.costUsd) >= 0.01) ||
(data.context != null && Math.abs((u.context?.pct ?? -100) - data.context.pct) >= 1) ||
(data.tokens != null && u.tokensByGen?.[gen]?.output !== data.tokens.output);
if (!changed && now - (u.at ?? 0) < STATUS_WRITE_MS) return false;
if (data.costUsd != null) u.costByGen = { ...u.costByGen, [gen]: data.costUsd };
if (data.tokens) u.tokensByGen = { ...u.tokensByGen, [gen]: data.tokens };
if (data.context) u.context = data.context;
if (data.model) u.model = data.model;
u.at = now;
wrote = true;
return true;
});
if (data.windows.fiveHour || data.windows.sevenDay) {
const key = accountKey(s.subscriptionId);
const prev = await getAccountWindows(db, key);
const same = (a?: UsageWindow, b?: UsageWindow) => (a?.pct ?? null) === (b?.pct ?? null) && (a?.resetsAt ?? null) === (b?.resetsAt ?? null);
if (!prev || !same(prev.fiveHour, data.windows.fiveHour) || !same(prev.sevenDay, data.windows.sevenDay) || now - prev.at >= STATUS_WRITE_MS) {
const next: AccountWindows = { fiveHour: data.windows.fiveHour ?? prev?.fiveHour, sevenDay: data.windows.sevenDay ?? prev?.sevenDay, at: now, sessionId: s.id };
await db
.insert(settings)
.values({ key, value: next })
.onConflictDoUpdate({ target: settings.key, set: { value: next, updatedAt: new Date(now) } });
wrote = true;
}
}
return wrote;
}
/** Turn ended: token totals of the conversation from its transcript. */
export function recordTranscriptUsage(db: Db, sessionId: number, conversationId: string, usage: { tokens: UsageTokens; model?: string }, now = Date.now()) {
mutateUsage(db, sessionId, (u) => {
u.convs = { ...u.convs, [conversationId]: { ...usage.tokens, ...(usage.model ? { model: usage.model } : {}) } };
if (usage.model) u.model = usage.model;
u.at = now;
return true;
});
}
// ── accounts (subscription or this machine's login) ───────────────────────────────
export const accountKey = (subscriptionId: number | null | undefined) => `usage.account:${subscriptionId ? `sub:${subscriptionId}` : "machine"}`;
export async function getAccountWindows(db: Db, key: string): Promise<AccountWindows | null> {
const [row] = await db.select().from(settings).where(eq(settings.key, key));
return (row?.value as AccountWindows | undefined) ?? null;
}
export const STALE_USAGE_MS = 6 * 3_600_000;
export interface WindowView {
/** null once the reset time has passed. */
pct: number | null;
resetsAt: Date | null;
reset: boolean;
}
export function windowView(w: UsageWindow | undefined, now = Date.now()): WindowView | null {
if (!w) return null;
const reset = w.resetsAt != null && w.resetsAt <= now;
return { pct: reset ? null : w.pct, resetsAt: w.resetsAt ? new Date(w.resetsAt) : null, reset };
}
export interface AccountUsage {
key: string;
subscriptionId: number | null;
name: string;
provider: string;
/** Who connected the subscription (null — unknown or this machine's login). */
createdBy: number | null;
fiveHour: WindowView | null;
sevenDay: WindowView | null;
at: Date | null;
stale: boolean;
/** PEP-56/67: the subscription is marked limited until this time. */
limitedUntil: Date | null;
}
/** Highest current window share of an account (for sorting / the top bar). */
export const accountPeak = (a: AccountUsage) => Math.max(a.fiveHour?.pct ?? -1, a.sevenDay?.pct ?? -1);
/**
* Accounts a user should see: a superadmin — all; others — the subscriptions of their
* projects' pools, plus this machine's login when one of their projects has no pool.
* PEP-121: names of subscriptions connected by others are replaced with neutral ones.
*/
export async function accountUsageForUser(db: Db, user: Pick<User, "id" | "login">, now = Date.now()): Promise<AccountUsage[]> {
const admin = await isSuperadmin(db, user);
let subIds: number[] | null = null; // null = all
let machine = true;
if (!admin) {
const ids = await userProjectIds(db, user.id);
const ps = ids.length ? await db.select({ poolId: projects.subscriptionPoolId }).from(projects).where(inArray(projects.id, ids)) : [];
const poolIds = [...new Set(ps.map((p) => p.poolId).filter((x): x is number => x != null))];
machine = ps.some((p) => p.poolId == null);
subIds = poolIds.length
? (await db.select({ id: subscriptionPoolMembers.subscriptionId }).from(subscriptionPoolMembers).where(inArray(subscriptionPoolMembers.poolId, poolIds))).map((r) => r.id)
: [];
}
const list = await listAccountUsage(db, { subscriptionIds: subIds, machine, now });
if (admin) return list;
const viewer = { admin, userId: user.id };
return list.map((a) => ({ ...a, name: a.subscriptionId == null ? "Подписка FORGE" : visibleSubscriptionName(a, viewer) }));
}
/** PEP-121: the whole limits strip for a product manager — agents work, or when they go on. */
export type AgentsLine = { state: "working" } | { state: "paused"; until: Date };
/**
* «Агенты работают» unless every agent of the user's projects waits for a limit reset (or
* nobody runs and every subscription of their pools is in a limit) — then when they go on.
*/
export async function agentsLine(db: Db, user: Pick<User, "id" | "login">, now = Date.now()): Promise<AgentsLine> {
const earliest = (ds: Array<Date | null | undefined>) => ds.filter((d): d is Date => !!d && d.getTime() > now).sort((a, b) => a.getTime() - b.getTime())[0];
const ids = await userProjectIds(db, user.id);
if (!ids.length) return { state: "working" };
const live = await db
.select({ status: sessions.status, resumeAt: sessions.resumeAt, subscriptionId: sessions.subscriptionId })
.from(sessions)
.where(and(inArray(sessions.projectId, ids), notInArray(sessions.status, ["done", "failed"])));
const ps = await db.select({ poolId: projects.subscriptionPoolId }).from(projects).where(inArray(projects.id, ids));
const poolIds = [...new Set(ps.map((p) => p.poolId).filter((x): x is number => x != null))];
const subs = poolIds.length
? await db
.select({ id: subscriptions.id, status: subscriptions.status, limitedUntil: subscriptions.limitedUntil })
.from(subscriptions)
.innerJoin(subscriptionPoolMembers, eq(subscriptionPoolMembers.subscriptionId, subscriptions.id))
.where(inArray(subscriptionPoolMembers.poolId, poolIds))
: [];
const limited = (s: (typeof subs)[number]) => s.status === "limited" && !!s.limitedUntil && s.limitedUntil.getTime() > now;
const waiting = live.filter((s) => s.status === "rate_limited");
if (waiting.length && waiting.length === live.length) {
const until = earliest(waiting.map((s) => s.resumeAt)) ?? earliest(subs.filter(limited).map((s) => s.limitedUntil));
return until ? { state: "paused", until } : { state: "working" };
}
// A project on this machine's login (no pool) is not held by the pools' limits.
if (!live.length && subs.length && ps.every((p) => p.poolId != null) && subs.every(limited)) {
const until = earliest(subs.map((s) => s.limitedUntil));
if (until) return { state: "paused", until };
}
return { state: "working" };
}
export async function listAccountUsage(db: Db, o: { subscriptionIds?: number[] | null; machine?: boolean; now?: number } = {}): Promise<AccountUsage[]> {
const now = o.now ?? Date.now();
const rows = await db.select().from(settings).where(keyPrefix(settings.key, "usage.account:"));
const byKey = new Map(rows.map((r) => [r.key, r.value as AccountWindows]));
const subs = o.subscriptionIds === undefined || o.subscriptionIds === null ? await db.select().from(subscriptions) : o.subscriptionIds.length ? await db.select().from(subscriptions).where(inArray(subscriptions.id, o.subscriptionIds)) : [];
const view = (key: string, base: Omit<AccountUsage, "key" | "fiveHour" | "sevenDay" | "at" | "stale">): AccountUsage => {
const w = byKey.get(key);
return { key, ...base, fiveHour: windowView(w?.fiveHour, now), sevenDay: windowView(w?.sevenDay, now), at: w ? new Date(w.at) : null, stale: !!w && now - w.at > STALE_USAGE_MS };
};
const out = subs.map((s) =>
view(accountKey(s.id), { subscriptionId: s.id, name: s.name, provider: s.provider, createdBy: s.createdBy, limitedUntil: s.status === "limited" && s.limitedUntil && s.limitedUntil.getTime() > now ? s.limitedUntil : null }),
);
if (o.machine !== false && (byKey.has(accountKey(null)) || !out.length)) {
out.push(view(accountKey(null), { subscriptionId: null, name: tr("Вход машины"), provider: "claude", createdBy: null, limitedUntil: null }));
}
return out.sort((a, b) => accountPeak(b) - accountPeak(a));
}
const hhmm = (d: Date) => d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
/** «5 ч 42% (сброс 14:30) · 7 д 18%» — one line for the bot and MCP. */
export function describeAccount(a: AccountUsage): string {
// A key per window, so each " · " piece of the line translates on its own.
const w = (five: boolean, v: WindowView | null) => {
if (!v) return null;
const vars = { pct: Math.round(v.pct ?? 0), time: v.resetsAt ? hhmm(v.resetsAt) : "" };
if (v.reset) return five ? tr("5 ч сброшено") : tr("7 д сброшено");
if (v.resetsAt) return five ? tr("5 ч {pct}% (сброс {time})", vars) : tr("7 д {pct}% (сброс {time})", vars);
return five ? tr("5 ч {pct}%", vars) : tr("7 д {pct}%", vars);
};
const parts = [w(true, a.fiveHour), w(false, a.sevenDay)].filter(Boolean);
const limited = a.limitedUntil ? ` · ${tr("лимит до {time}", { time: hhmm(a.limitedUntil) })}` : "";
if (!parts.length) return `${tr("{name}: нет данных", { name: a.name })}${limited}`;
const stale = a.stale && a.at ? ` · ${tr("устарело ({n} ч назад)", { n: Math.round((Date.now() - a.at.getTime()) / 3_600_000) })}` : "";
return `${a.name}: ${parts.join(" · ")}${limited}${stale}`;
}
export const fmtTokens = (n: number) => (n >= 1e6 ? tr("{n} млн", { n: (n / 1e6).toFixed(1) }) : n >= 1e4 ? tr("{n} тыс.", { n: Math.round(n / 1e3) }) : n.toLocaleString("ru-RU"));
export const fmtCost = (t: Pick<UsageTotals, "costUsd" | "estimated">) => (t.costUsd == null ? "—" : `${t.estimated ? "≈ " : ""}$${t.costUsd.toFixed(2)}`);
/** «1,5 млн токенов · ≈ $3.20 · контекст 34%» — or «нет данных». */
export function describeUsage(u: SessionUsage | null | undefined): string {
const t = usageTotals(u);
if (!t.hasData) return tr("нет данных");
// glossary-ignore: расход показан только в виде «Инженер»
return [t.total ? tr("{n} токенов", { n: fmtTokens(t.total) }) : null, t.costUsd != null ? fmtCost(t) : null, t.context ? tr("контекст {pct}%", { pct: Math.round(t.context.pct) }) : null].filter(Boolean).join(" · ");
}