Долгоживущий агент чата (только для managerIds, тестовый менеджер) и тайминг чата (chat_timing, миграция 016); тесты; docs
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
216
packages/khbuild_assistant_prep/src/agents/live-runner.ts
Normal file
216
packages/khbuild_assistant_prep/src/agents/live-runner.ts
Normal file
@@ -0,0 +1,216 @@
|
||||
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import { mkdirSync } from "node:fs";
|
||||
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;
|
||||
/** Закрыть процесс агента (следующий ход стартует новый процесс с --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;
|
||||
lastCost: number;
|
||||
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 total = typeof o.total_cost_usd === "number" ? o.total_cost_usd : undefined;
|
||||
const cost = total === undefined ? undefined : Math.max(0, total - p.lastCost);
|
||||
if (total !== undefined) p.lastCost = total;
|
||||
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,
|
||||
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: "" } });
|
||||
const p: Proc = { cwd: call.cwd, sessionId: call.sessionId, child, buf: "", stderr: "", turn: null, idle: null, exited: false, lastCost: 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,
|
||||
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,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user