Агенты: учёт токенов (agent_usage, буфер в памяти + пачки в БД), globals с лимитами аккаунта, доллары убраны
All checks were successful
ci / test (push) Successful in 27s
ci / deploy (push) Successful in 2m18s

Расчётная стоимость из ответов claude не является списанием (тариф Team, 0 из 10 USD), поэтому результаты, API и записи больше её не ведут.
Токены каждого вызова модели - в agent_usage; проценты 5-часового и недельного окон читаются у claude в globals (одна строка, check),
предупреждение ИТ на 80% и 95%, сводка GET /agent/usage.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-30 10:41:10 +03:00
parent dd7de01f62
commit bc6697834a
20 changed files with 587 additions and 37 deletions

View File

@@ -7,6 +7,7 @@ import { KeyedMutex, Semaphore } from "./pool.js";
import { loadFragment, type PromptSide } from "./prompts.js";
import { missingSections, parseSections } from "./sections.js";
import type { AgentSettings } from "../settings.js";
import type { UsageLog } from "../usage.js";
export interface AgentContext {
pool: Pool;
@@ -15,6 +16,8 @@ export interface AgentContext {
runner: ClaudeRunner;
/** Новая версия агента чата: долгоживущие процессы (только для менеджеров из agent.live.managerIds). */
liveRunner?: LiveRunner;
/** Учёт токенов каждого вызова модели (в память, пачками в БД); без него учёт не ведётся. */
usageLog?: UsageLog;
gate: Semaphore;
locks: KeyedMutex;
/** Сообщение ИТ-команде (Slack); ошибки отправки не должны ломать обработку. */
@@ -25,7 +28,7 @@ export interface AgentContext {
export interface AgentTiming {
queueMs: number;
live: boolean;
runs: Array<{ wallMs: number; timing?: TurnTiming; costUsd?: number; error?: string }>;
runs: Array<{ wallMs: number; timing?: TurnTiming; inputTokens?: number; outputTokens?: number; cacheReadTokens?: number; cacheCreationTokens?: number; error?: string }>;
}
/** Агент сообщил, что коннектор JobTread недоступен (ответ при этом не годится для менеджера). */
@@ -71,10 +74,10 @@ async function startRun(ctx: AgentContext, managerId: string, step: string, atte
return rows[0].id as string;
}
async function finishRun(ctx: AgentContext, id: string, ok: boolean, info: { durationMs?: number; costUsd?: number; error?: string; changes?: string }): Promise<void> {
async function finishRun(ctx: AgentContext, id: string, ok: boolean, info: { durationMs?: number; error?: string; changes?: string }): Promise<void> {
await ctx.pool.query(
"update agent_run set status = $2, finished_at = now(), duration_ms = $3, cost_usd = $4, error = $5, changes = $6 where id = $1",
[id, ok ? "ok" : "failed", info.durationMs ?? null, info.costUsd ?? null, info.error ?? null, info.changes ?? null],
"update agent_run set status = $2, finished_at = now(), duration_ms = $3, error = $4, changes = $5 where id = $1",
[id, ok ? "ok" : "failed", info.durationMs ?? null, info.error ?? null, info.changes ?? null],
);
}
@@ -100,7 +103,7 @@ export async function closeOrphanRuns(ctx: AgentContext): Promise<number> {
*/
export function runManagerAgent(
ctx: AgentContext,
opts: { managerId: string; step: "step2" | "step4"; tools: ToolSet; prompt: string; /** Полный промт для повтора в новой сессии, если prompt - короткий. */ fullPrompt?: string; /** Переменные окружения агента (KHB_SQL_URL и т.п.). */ env?: Record<string, string>; required: string[] },
opts: { managerId: string; step: "step2" | "step4"; /** Операция для учёта токенов (chat:manager, chat:project, chat:event, step2); по умолчанию - шаг. */ op?: string; tools: ToolSet; prompt: string; /** Полный промт для повтора в новой сессии, если prompt - короткий. */ fullPrompt?: string; /** Переменные окружения агента (KHB_SQL_URL и т.п.). */ env?: Record<string, string>; required: string[] },
): Promise<AgentOutcome> {
const tEnter = Date.now();
return ctx.locks.run(opts.managerId, () =>
@@ -110,14 +113,19 @@ export function runManagerAgent(
const live = opts.tools === "chat" && useLive(ctx, opts.managerId);
timing.live = live;
const base: ClaudeRunner = live ? ctx.liveRunner!.run : ctx.runner;
const op = opts.op ?? opts.step;
const run: ClaudeRunner = async (c) => {
const t = Date.now();
try {
const r = await base(opts.env ? { ...c, env: opts.env } : c);
timing.runs.push({ wallMs: Date.now() - t, timing: r.timing, costUsd: r.costUsd });
timing.runs.push({ wallMs: Date.now() - t, timing: r.timing, inputTokens: r.usage?.inputTokens, outputTokens: r.usage?.outputTokens, cacheReadTokens: r.usage?.cacheReadTokens, cacheCreationTokens: r.usage?.cacheCreationTokens });
ctx.usageLog?.record({
managerId: opts.managerId, op, sessionId: r.sessionId, resumed: c.resume, live, ...r.usage, numTurns: r.timing?.numTurns, durationMs: r.timing?.turnMs ?? Date.now() - t, ok: true,
});
return r;
} catch (e) {
timing.runs.push({ wallMs: Date.now() - t, error: String(e).slice(0, 200) });
ctx.usageLog?.record({ managerId: opts.managerId, op, sessionId: c.sessionId, resumed: c.resume, live, durationMs: Date.now() - t, ok: false, error: String(e).slice(0, 300) });
throw e;
}
};
@@ -166,7 +174,7 @@ export function runManagerAgent(
if (live) ctx.liveRunner!.close(cwd);
if (opts.tools === "chat" && (Date.now() - tFirst) / 1000 + retryCfg.pauseSeconds < retryCfg.windowSeconds) {
// повтор: ответ этой попытки менеджеру не уходит
await finishRun(ctx, runId, false, { durationMs: res.durationMs, costUsd: res.costUsd, error: "коннектор JobTread недоступен - повтор запуска", changes: sections.get("изменения jobtread") });
await finishRun(ctx, runId, false, { durationMs: res.durationMs, error: "коннектор JobTread недоступен - повтор запуска", changes: sections.get("изменения jobtread") });
connectorRetries++;
ctx.log.warn({ managerId: opts.managerId, retry: connectorRetries }, "коннектор JobTread недоступен - повторяем запуск в новой сессии");
await new Promise((r) => setTimeout(r, retryCfg.pauseSeconds * 1000));
@@ -180,11 +188,11 @@ export function runManagerAgent(
const missing = missingSections(sections, opts.required);
const changes = sections.get("изменения jobtread");
if (!missing.length) {
await finishRun(ctx, runId, true, { durationMs: res.durationMs, costUsd: res.costUsd, changes });
await finishRun(ctx, runId, true, { durationMs: res.durationMs, changes });
return { text: res.text, sections, sessionId, attempts: attempt, timing };
}
lastErr = `в ответе нет разделов: ${missing.map((m) => `## ${m}`).join(", ")}`;
await finishRun(ctx, runId, false, { durationMs: res.durationMs, costUsd: res.costUsd, error: lastErr, changes });
await finishRun(ctx, runId, false, { durationMs: res.durationMs, error: lastErr, changes });
resume = true;
prompt = loadFragment("p-result-validator.md", "Исправь формат ответа", { error: lastErr }, promptSideFor(ctx, opts.managerId));
}