Агенты: учёт токенов (agent_usage, буфер в памяти + пачки в БД), globals с лимитами аккаунта, доллары убраны
Расчётная стоимость из ответов 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:
@@ -1,5 +1,6 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { mkdirSync } from "node:fs";
|
||||
import { parseUsage, type TokenUsage } from "../usage.js";
|
||||
|
||||
export type ToolSet = "none" | "chat";
|
||||
|
||||
@@ -32,7 +33,8 @@ export interface TurnTiming {
|
||||
export interface ClaudeResult {
|
||||
text: string;
|
||||
sessionId: string;
|
||||
costUsd?: number;
|
||||
/** Токены вызова (деньги не ведём: total_cost_usd - расчётная цена по тарифам API, а не списание). */
|
||||
usage?: TokenUsage;
|
||||
durationMs?: number;
|
||||
timing?: TurnTiming;
|
||||
}
|
||||
@@ -57,7 +59,7 @@ export interface CliRunnerOptions {
|
||||
/** Инструменты шага 4: Bash (ffmpeg, whisper, exiftool, khb-sql, khb-drive), ToolSearch и запросы JobTread через коннектор claude.ai. */
|
||||
export const CHAT_TOOLS = ["--tools", "Bash,ToolSearch", "--allowedTools", "Bash", "ToolSearch", "mcp__claude_ai_JobTread__query", "--permission-mode", "acceptEdits"];
|
||||
|
||||
/** Запуск консольного агента `claude -p`: промт через stdin, ответ - JSON (result, session_id, total_cost_usd). */
|
||||
/** Запуск консольного агента `claude -p`: промт через stdin, ответ - JSON (result, session_id, usage). */
|
||||
export function createCliRunner(opts: CliRunnerOptions): ClaudeRunner {
|
||||
return (call) =>
|
||||
new Promise<ClaudeResult>((resolve, reject) => {
|
||||
@@ -88,10 +90,10 @@ export function createCliRunner(opts: CliRunnerOptions): ClaudeRunner {
|
||||
return reject(new ClaudeError(`claude exit=${code}: ${msg}`, /No conversation found/i.test(msg) ? "no_session" : "failed"));
|
||||
}
|
||||
try {
|
||||
const j = JSON.parse(out) as { result?: string; session_id?: string; total_cost_usd?: number; duration_ms?: number; duration_api_ms?: number; num_turns?: number; is_error?: boolean };
|
||||
const j = JSON.parse(out) as { result?: string; session_id?: string; duration_ms?: number; duration_api_ms?: number; num_turns?: number; is_error?: boolean };
|
||||
if (j.is_error) return reject(new ClaudeError(`claude вернул ошибку: ${String(j.result).slice(0, 300)}`, "failed"));
|
||||
resolve({
|
||||
text: j.result ?? "", sessionId: j.session_id ?? call.sessionId, costUsd: j.total_cost_usd, durationMs: j.duration_ms,
|
||||
text: j.result ?? "", sessionId: j.session_id ?? call.sessionId, usage: parseUsage(j), durationMs: j.duration_ms,
|
||||
timing: { turnMs: Date.now() - tStart, apiMs: j.duration_api_ms, claudeMs: j.duration_ms, numTurns: j.num_turns },
|
||||
});
|
||||
} catch {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import { mkdirSync } from "node:fs";
|
||||
import { parseUsage } from "../usage.js";
|
||||
import { ClaudeError, CHAT_TOOLS, type ClaudeCall, type ClaudeResult, type ClaudeRunner } from "./cli-runner.js";
|
||||
|
||||
export interface LiveRunnerOptions {
|
||||
@@ -48,7 +49,6 @@ interface Proc {
|
||||
idle: NodeJS.Timeout | null;
|
||||
exited: boolean;
|
||||
/** Накопительные счётчики claude на прошлом ходе; null - процесс продолжает старую сессию и первый ход посчитать нельзя (счётчики включают историю сессии). */
|
||||
lastCost: number | null;
|
||||
lastApiMs: number | null;
|
||||
ready: Promise<void>;
|
||||
}
|
||||
@@ -95,16 +95,13 @@ export function createLiveRunner(opts: LiveRunnerOptions): LiveRunner {
|
||||
p.turn = null;
|
||||
clearTimeout(t.timer);
|
||||
if (typeof o.session_id === "string") p.sessionId = o.session_id;
|
||||
const total = typeof o.total_cost_usd === "number" ? o.total_cost_usd : undefined;
|
||||
const cost = total === undefined || p.lastCost === null ? undefined : Math.max(0, total - p.lastCost);
|
||||
if (total !== undefined) p.lastCost = total;
|
||||
const apiTotal = typeof o.duration_api_ms === "number" ? o.duration_api_ms : undefined;
|
||||
const apiMs = apiTotal === undefined || p.lastApiMs === null ? undefined : Math.max(0, apiTotal - p.lastApiMs);
|
||||
if (apiTotal !== undefined) p.lastApiMs = apiTotal;
|
||||
armIdle(p);
|
||||
if (o.is_error === true) return t.reject(new ClaudeError(`claude вернул ошибку: ${String(o.result).slice(0, 300)}`, "failed"));
|
||||
t.resolve({
|
||||
text: String(o.result ?? ""), sessionId: p.sessionId, costUsd: cost, durationMs: typeof o.duration_ms === "number" ? o.duration_ms : Date.now() - t.startedAt,
|
||||
text: String(o.result ?? ""), sessionId: p.sessionId, usage: parseUsage(o), durationMs: typeof o.duration_ms === "number" ? o.duration_ms : Date.now() - t.startedAt,
|
||||
timing: {
|
||||
startMs: t.startMs, turnMs: Date.now() - t.startedAt, apiMs,
|
||||
claudeMs: typeof o.duration_ms === "number" ? o.duration_ms : undefined, numTurns: typeof o.num_turns === "number" ? o.num_turns : undefined,
|
||||
@@ -123,7 +120,7 @@ export function createLiveRunner(opts: LiveRunnerOptions): LiveRunner {
|
||||
if (opts.model) args.push("--model", opts.model);
|
||||
args.push(...CHAT_TOOLS);
|
||||
const child = spawn(opts.bin, args, { cwd: call.cwd, stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, ANTHROPIC_API_KEY: "", ...call.env } });
|
||||
const p: Proc = { cwd: call.cwd, sessionId: call.sessionId, child, buf: "", stderr: "", turn: null, idle: null, exited: false, lastCost: call.resume ? null : 0, lastApiMs: call.resume ? null : 0, ready: Promise.resolve() };
|
||||
const p: Proc = { cwd: call.cwd, sessionId: call.sessionId, child, buf: "", stderr: "", turn: null, idle: null, exited: false, lastApiMs: call.resume ? null : 0, ready: Promise.resolve() };
|
||||
child.stdout.on("data", (d) => {
|
||||
p.buf += d;
|
||||
let i: number;
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user