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; /** Вызывается по простою перед закрытием (например, ход «сведи память»); после него процесс закрывается в любом случае. */ onIdle?: (cwd: string) => Promise; /** Пауза после старта процесса перед первым промтом: за это время поднимаются коннекторы 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; /** * Переназначает простой живого процесса: через ms без новых ходов вызовется onIdle и процесс закроется. * Агент сам решает, сколько ждать (диалог закрыт - коротко, ждём ответ - долго). */ scheduleIdle(cwd: string, ms: number): void; /** * Ход `/compact`: claude сжимает контекст сессии (резюме вместо истории), следующий resume читает короткий контекст. * null - процесса нет, он занят, не простаивал minIdleMs или claude не подтвердил сжатие (нет compact_boundary). */ compact(cwd: string, minIdleMs?: number): Promise<(ClaudeResult & { idleMs: number }) | null>; } interface Turn { startMs: number; toolCalls: number; firstEventMs: number | null; resolve(r: ClaudeResult): void; reject(e: Error): void; timer: NodeJS.Timeout; startedAt: number; compact?: { preTokens: number; postTokens: number; durationMs: 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; /** Когда закончился последний ход (для проверки «действительно простаивал»). */ lastResultAt: number; /** Простой, назначенный агентом на следующую паузу (scheduleIdle); null - opts.idleMs. */ idleMs: number | null; } /** * Долгоживущий агент: один процесс `claude -p --input-format stream-json` на менеджера. Ответ на ход - событие `result`; * после него процесс не завершается и ждёт следующее сообщение в stdin. Закрывается через idleMs без новых ходов. * Если процесса нет (первый ход, простой, падение), стартует новый с --resume/--session-id и ждёт warmupMs. */ export function createLiveRunner(opts: LiveRunnerOptions): LiveRunner { const procs = new Map(); const clearIdle = (p: Proc) => { if (p.idle) clearTimeout(p.idle); p.idle = null; }; const armIdle = (p: Proc, ms?: number) => { clearIdle(p); if (ms !== undefined) p.idleMs = ms; p.idle = setTimeout(() => { if (p.exited || p.turn) return; const closeNow = () => { if (p.exited) return; opts.onEvent?.({ kind: "idle_close", cwd: p.cwd, sessionId: p.sessionId }); clearIdle(p); p.child.stdin.end(); // агент завершается сам (код 0) }; if (!opts.onIdle) return closeNow(); opts.onIdle(p.cwd).catch(() => undefined).finally(closeNow); }, p.idleMs ?? opts.idleMs); p.idle.unref?.(); }; function onLine(p: Proc, line: string): void { let o: Record; try { o = JSON.parse(line) as Record; } catch { return; } if (o.type === "system" && o.subtype === "init" && typeof o.session_id === "string") p.sessionId = o.session_id; if (o.type === "system" && o.subtype === "compact_boundary" && p.turn) { const m = (o.compact_metadata ?? {}) as { pre_tokens?: number; post_tokens?: number; duration_ms?: number }; p.turn.compact = { preTokens: Number(m.pre_tokens ?? 0), postTokens: Number(m.post_tokens ?? 0), durationMs: Number(m.duration_ms ?? 0) }; } 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; p.lastResultAt = Date.now(); p.idleMs = null; // назначенный простой действует на одну паузу 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, compact: t.compact, 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(), lastResultAt: Date.now(), idleMs: null }; 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 sendTurn(proc, call.cwd, call.prompt, tCall); }; function sendTurn(proc: Proc, cwd: string, text: string, tCall: number): Promise { return new Promise((resolve, reject) => { const timer = setTimeout(() => { proc.turn = null; kill(proc, "таймаут хода"); procs.delete(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: text } }) + "\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, scheduleIdle: (cwd, ms) => { const p = procs.get(cwd); if (!p || p.exited || p.turn) return; armIdle(p, ms); }, compact: async (cwd, minIdleMs = 0) => { const p = procs.get(cwd); if (!p || p.exited || p.turn) return null; const idleMs = Date.now() - p.lastResultAt; if (idleMs < minIdleMs) return null; // с тех пор был новый ход: процесс не простаивал clearIdle(p); const r = await sendTurn(p, cwd, "/compact", Date.now()); return r.compact ? { ...r, idleMs } : null; }, }; }