Агенты: учёт токенов (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, 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;
|
||||
|
||||
Reference in New Issue
Block a user