Files
khb_microservices/packages/khbuild_assistant_prep/src/agents/live-runner.ts
Yuri Yaryshev bc6697834a
All checks were successful
ci / test (push) Successful in 27s
ci / deploy (push) Successful in 2m18s
Агенты: учёт токенов (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>
2026-10-30 10:41:10 +03:00

225 lines
9.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 {
bin: string;
/** Аргументы перед флагами claude (тесты запускают node + фейковый скрипт). */
prefixArgs?: string[];
model?: string;
/** Таймаут одного хода (сообщение -> результат). */
timeoutMs: number;
/** Через сколько мс после последнего результата процесс закрывается (stdin закрывается, агент завершается сам). */
idleMs: number;
/** Пауза после старта процесса перед первым промтом: за это время поднимаются коннекторы claude.ai (JobTread и др.). */
warmupMs: number;
onEvent?: (e: { kind: "start" | "idle_close" | "exit" | "kill"; cwd: string; sessionId: string; info?: string }) => void;
}
export interface LiveRunner {
run: ClaudeRunner;
/** Есть ли живой процесс агента в этой папке (т.е. агент уже в диалоге и помнит инструкции). */
isActive(cwd: string): boolean;
/** id сессии живого процесса в этой папке (null - процесса нет). Нужен, чтобы не слать короткий промт в новую сессию после сброса. */
activeSession(cwd: string): string | null;
/** Закрыть процесс агента (следующий ход стартует новый процесс с --resume). */
close(cwd: string): void;
closeAll(): void;
activeCount(): number;
}
interface Turn {
startMs: number;
toolCalls: number;
firstEventMs: number | null;
resolve(r: ClaudeResult): void;
reject(e: Error): void;
timer: NodeJS.Timeout;
startedAt: number;
}
interface Proc {
cwd: string;
sessionId: string;
child: ChildProcessWithoutNullStreams;
buf: string;
stderr: string;
turn: Turn | null;
idle: NodeJS.Timeout | null;
exited: boolean;
/** Накопительные счётчики claude на прошлом ходе; null - процесс продолжает старую сессию и первый ход посчитать нельзя (счётчики включают историю сессии). */
lastApiMs: number | null;
ready: Promise<void>;
}
/**
* Долгоживущий агент: один процесс `claude -p --input-format stream-json` на менеджера. Ответ на ход - событие `result`;
* после него процесс не завершается и ждёт следующее сообщение в stdin. Закрывается через idleMs без новых ходов.
* Если процесса нет (первый ход, простой, падение), стартует новый с --resume/--session-id и ждёт warmupMs.
*/
export function createLiveRunner(opts: LiveRunnerOptions): LiveRunner {
const procs = new Map<string, Proc>();
const clearIdle = (p: Proc) => {
if (p.idle) clearTimeout(p.idle);
p.idle = null;
};
const armIdle = (p: Proc) => {
clearIdle(p);
p.idle = setTimeout(() => {
if (p.exited || p.turn) return;
opts.onEvent?.({ kind: "idle_close", cwd: p.cwd, sessionId: p.sessionId });
p.child.stdin.end(); // агент завершается сам (код 0)
}, opts.idleMs);
p.idle.unref?.();
};
function onLine(p: Proc, line: string): void {
let o: Record<string, unknown>;
try {
o = JSON.parse(line) as Record<string, unknown>;
} catch {
return;
}
if (o.type === "system" && o.subtype === "init" && typeof o.session_id === "string") p.sessionId = o.session_id;
if (p.turn) {
if (p.turn.firstEventMs === null) p.turn.firstEventMs = Date.now() - p.turn.startedAt;
if (o.type === "assistant") {
const content = (o.message as { content?: Array<{ type?: string }> } | undefined)?.content;
if (Array.isArray(content)) p.turn.toolCalls += content.filter((b) => b.type === "tool_use").length;
}
}
if (o.type !== "result" || !p.turn) return;
const t = p.turn;
p.turn = null;
clearTimeout(t.timer);
if (typeof o.session_id === "string") p.sessionId = o.session_id;
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, 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,
toolCalls: t.toolCalls, firstEventMs: t.firstEventMs ?? undefined,
},
});
}
function spawnProc(call: ClaudeCall): Proc {
mkdirSync(call.cwd, { recursive: true });
const args = [
...(opts.prefixArgs ?? []),
"-p", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose",
call.resume ? "--resume" : "--session-id", call.sessionId,
];
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, lastApiMs: call.resume ? null : 0, ready: Promise.resolve() };
child.stdout.on("data", (d) => {
p.buf += d;
let i: number;
while ((i = p.buf.indexOf("\n")) >= 0) {
const line = p.buf.slice(0, i).trim();
p.buf = p.buf.slice(i + 1);
if (line) onLine(p, line);
}
});
child.stderr.on("data", (d) => (p.stderr = (p.stderr + d).slice(-2000)));
child.stdin.on("error", () => undefined);
const fail = (e: ClaudeError) => {
if (!p.turn) return;
const t = p.turn;
p.turn = null;
clearTimeout(t.timer);
t.reject(e);
};
child.on("error", (e) => {
p.exited = true;
clearIdle(p);
if (procs.get(p.cwd) === p) procs.delete(p.cwd);
fail(new ClaudeError(`не удалось запустить ${opts.bin}: ${e.message}`, "failed"));
});
child.on("close", (code) => {
p.exited = true;
clearIdle(p);
if (procs.get(p.cwd) === p) procs.delete(p.cwd);
opts.onEvent?.({ kind: "exit", cwd: p.cwd, sessionId: p.sessionId, info: `code=${code}` });
const msg = `${p.stderr}${p.buf}`.slice(0, 500);
fail(new ClaudeError(`claude завершился (exit=${code}) до ответа: ${msg}`, /No conversation found/i.test(msg) ? "no_session" : "failed"));
});
opts.onEvent?.({ kind: "start", cwd: p.cwd, sessionId: p.sessionId });
// коннекторы claude.ai поднимаются отдельно от старта процесса: даём им время до первого промта
p.ready = new Promise((r) => setTimeout(r, opts.warmupMs));
return p;
}
const kill = (p: Proc, why: string) => {
clearIdle(p);
if (!p.exited) {
opts.onEvent?.({ kind: "kill", cwd: p.cwd, sessionId: p.sessionId, info: why });
p.child.kill("SIGKILL");
}
};
const run: ClaudeRunner = async (call) => {
const tCall = Date.now();
let p = procs.get(call.cwd);
if (p && (p.exited || p.sessionId !== call.sessionId)) {
kill(p, "смена сессии");
procs.delete(call.cwd);
p = undefined;
}
if (p?.turn) throw new ClaudeError("предыдущий ход агента ещё не завершён", "failed");
if (!p) {
p = spawnProc(call);
procs.set(call.cwd, p);
}
clearIdle(p);
const proc = p;
await proc.ready;
if (proc.exited) throw new ClaudeError(`агент завершился до первого промта: ${proc.stderr.slice(0, 300)}`, /No conversation found/i.test(proc.stderr) ? "no_session" : "failed");
return new Promise<ClaudeResult>((resolve, reject) => {
const timer = setTimeout(() => {
proc.turn = null;
kill(proc, "таймаут хода");
procs.delete(call.cwd);
reject(new ClaudeError(`таймаут ${opts.timeoutMs} мс`, "timeout"));
}, opts.timeoutMs);
proc.turn = { resolve, reject, timer, startedAt: Date.now(), startMs: Date.now() - tCall, toolCalls: 0, firstEventMs: null };
proc.child.stdin.write(JSON.stringify({ type: "user", message: { role: "user", content: call.prompt } }) + "\n");
});
};
return {
run,
activeSession: (cwd) => {
const p = procs.get(cwd);
return p && !p.exited ? p.sessionId : null;
},
isActive: (cwd) => {
const p = procs.get(cwd);
return !!p && !p.exited;
},
close: (cwd) => {
const p = procs.get(cwd);
if (p) {
procs.delete(cwd);
kill(p, "закрыт по запросу");
}
},
closeAll: () => {
for (const [cwd, p] of procs) {
procs.delete(cwd);
kill(p, "остановка сервиса");
}
},
activeCount: () => procs.size,
};
}