Долгоживущий агент: стоимость и время API по ходам (разница накопительных счётчиков)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -34,3 +34,5 @@
|
||||
| steps | jsonb | подробности: `runs[]` - каждый вызов модели (wallMs, timing, costUsd, error) |
|
||||
|
||||
Где теряется время: `total_ms` = `slack_in_ms` + `debounce_ms` + (`processing_ms` минус часть после ответа). Внутри `processing_ms`: `inputs_ms`, `drive_ms`, `prompt_ms`, `queue_ms`, `start_ms`, `model_ms` (из него `api_ms` - сама модель, остальное - инструменты, коннекторы, запуск), `post_ms`, `publish_ms`.
|
||||
|
||||
Примечание: счётчики стоимости и времени API у claude накопительные за сессию; для долгоживущего агента считается разница между ходами. Первый ход процесса, продолжающего старую сессию (`--resume`), даёт пустые `api_ms` и стоимость.
|
||||
|
||||
@@ -45,7 +45,9 @@ interface Proc {
|
||||
turn: Turn | null;
|
||||
idle: NodeJS.Timeout | null;
|
||||
exited: boolean;
|
||||
lastCost: number;
|
||||
/** Накопительные счётчики claude на прошлом ходе; null - процесс продолжает старую сессию и первый ход посчитать нельзя (счётчики включают историю сессии). */
|
||||
lastCost: number | null;
|
||||
lastApiMs: number | null;
|
||||
ready: Promise<void>;
|
||||
}
|
||||
|
||||
@@ -92,14 +94,17 @@ export function createLiveRunner(opts: LiveRunnerOptions): LiveRunner {
|
||||
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 ? undefined : Math.max(0, total - p.lastCost);
|
||||
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,
|
||||
timing: {
|
||||
startMs: t.startMs, turnMs: Date.now() - t.startedAt, apiMs: typeof o.duration_api_ms === "number" ? o.duration_api_ms : undefined,
|
||||
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,
|
||||
toolCalls: t.toolCalls, firstEventMs: t.firstEventMs ?? undefined,
|
||||
},
|
||||
@@ -116,7 +121,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: "" } });
|
||||
const p: Proc = { cwd: call.cwd, sessionId: call.sessionId, child, buf: "", stderr: "", turn: null, idle: null, exited: false, lastCost: 0, ready: Promise.resolve() };
|
||||
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() };
|
||||
child.stdout.on("data", (d) => {
|
||||
p.buf += d;
|
||||
let i: number;
|
||||
|
||||
@@ -62,6 +62,7 @@ describe("долгоживущий агент (фейковый claude)", () =>
|
||||
expect(events).toContain("idle_close");
|
||||
const b = await r.run(call(cwd, "два", "11111111-1111-4111-8111-111111111111", true));
|
||||
expect(pid(b.text)).not.toBe(pid(a.text));
|
||||
expect(b.costUsd).toBeUndefined(); // процесс продолжил старую сессию: накопительный счётчик включает историю, первый ход не считаем
|
||||
});
|
||||
|
||||
it("новый ход сбрасывает таймер простоя", async () => {
|
||||
|
||||
Reference in New Issue
Block a user