From d4eefb08d3b274a6523cac4dc9dfe3ab051289dc Mon Sep 17 00:00:00 2001 From: Yuri Yaryshev Date: Fri, 16 Oct 2026 12:59:29 +0300 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=BB=D0=B3=D0=BE=D0=B6=D0=B8?= =?UTF-8?q?=D0=B2=D1=83=D1=89=D0=B8=D0=B9=20=D0=B0=D0=B3=D0=B5=D0=BD=D1=82?= =?UTF-8?q?:=20=D1=81=D1=82=D0=BE=D0=B8=D0=BC=D0=BE=D1=81=D1=82=D1=8C=20?= =?UTF-8?q?=D0=B8=20=D0=B2=D1=80=D0=B5=D0=BC=D1=8F=20API=20=D0=BF=D0=BE=20?= =?UTF-8?q?=D1=85=D0=BE=D0=B4=D0=B0=D0=BC=20(=D1=80=D0=B0=D0=B7=D0=BD?= =?UTF-8?q?=D0=B8=D1=86=D0=B0=20=D0=BD=D0=B0=D0=BA=D0=BE=D0=BF=D0=B8=D1=82?= =?UTF-8?q?=D0=B5=D0=BB=D1=8C=D0=BD=D1=8B=D1=85=20=D1=81=D1=87=D1=91=D1=82?= =?UTF-8?q?=D1=87=D0=B8=D0=BA=D0=BE=D0=B2)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- docs/proposed/data_objects/chat_timing.md | 2 ++ .../src/agents/live-runner.ts | 13 +++++++++---- .../khbuild_assistant_prep/src/live-runner.test.ts | 1 + 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/docs/proposed/data_objects/chat_timing.md b/docs/proposed/data_objects/chat_timing.md index 7a7cdb8..6d475fc 100644 --- a/docs/proposed/data_objects/chat_timing.md +++ b/docs/proposed/data_objects/chat_timing.md @@ -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` и стоимость. diff --git a/packages/khbuild_assistant_prep/src/agents/live-runner.ts b/packages/khbuild_assistant_prep/src/agents/live-runner.ts index ee7b6f7..4eeae49 100644 --- a/packages/khbuild_assistant_prep/src/agents/live-runner.ts +++ b/packages/khbuild_assistant_prep/src/agents/live-runner.ts @@ -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; } @@ -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; diff --git a/packages/khbuild_assistant_prep/src/live-runner.test.ts b/packages/khbuild_assistant_prep/src/live-runner.test.ts index 9ec56c8..ff45e36 100644 --- a/packages/khbuild_assistant_prep/src/live-runner.test.ts +++ b/packages/khbuild_assistant_prep/src/live-runner.test.ts @@ -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 () => {