Долгоживущий агент чата (только для managerIds, тестовый менеджер) и тайминг чата (chat_timing, миграция 016); тесты; docs
All checks were successful
ci / test (push) Successful in 23s
ci / deploy (push) Successful in 1m46s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-16 12:55:18 +03:00
parent 81634fbfa9
commit 65ab75d378
17 changed files with 733 additions and 29 deletions

View File

@@ -12,11 +12,27 @@ export interface ClaudeCall {
tools: ToolSet;
}
/** Тайминг одного хода агента (для диагностики медленных ответов). */
export interface TurnTiming {
/** Старт процесса агента и прогрев до отправки промта (0 - процесс уже работал; undefined - классика, не измеряется отдельно). */
startMs?: number;
/** От отправки промта до результата (для классики - весь запуск процесса). */
turnMs?: number;
/** Время запросов к API модели по данным claude (duration_api_ms) и общее время хода по данным claude (duration_ms). */
apiMs?: number;
claudeMs?: number;
numTurns?: number;
/** Число вызовов инструментов и время до первого события хода (только долгоживущий агент). */
toolCalls?: number;
firstEventMs?: number;
}
export interface ClaudeResult {
text: string;
sessionId: string;
costUsd?: number;
durationMs?: number;
timing?: TurnTiming;
}
export type ClaudeRunner = (call: ClaudeCall) => Promise<ClaudeResult>;
@@ -37,7 +53,7 @@ export interface CliRunnerOptions {
}
/** Инструменты шага 4: Bash (ffmpeg, whisper, exiftool, rclone), ToolSearch и запросы JobTread через коннектор claude.ai. */
const CHAT_TOOLS = ["--tools", "Bash,ToolSearch", "--allowedTools", "Bash", "ToolSearch", "mcp__claude_ai_JobTread__query", "--permission-mode", "acceptEdits"];
export const CHAT_TOOLS = ["--tools", "Bash,ToolSearch", "--allowedTools", "Bash", "ToolSearch", "mcp__claude_ai_JobTread__query", "--permission-mode", "acceptEdits"];
/** Запуск консольного агента `claude -p`: промт через stdin, ответ - JSON (result, session_id, total_cost_usd). */
export function createCliRunner(opts: CliRunnerOptions): ClaudeRunner {
@@ -48,6 +64,7 @@ export function createCliRunner(opts: CliRunnerOptions): ClaudeRunner {
if (opts.model) args.push("--model", opts.model);
args.push(...(call.tools === "chat" ? CHAT_TOOLS : ["--tools", ""]));
const child = spawn(opts.bin, args, { cwd: call.cwd, stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, ANTHROPIC_API_KEY: "" } });
const tStart = Date.now();
let out = "";
let err = "";
let timedOut = false;
@@ -69,9 +86,12 @@ export function createCliRunner(opts: CliRunnerOptions): ClaudeRunner {
return reject(new ClaudeError(`claude exit=${code}: ${msg}`, /No conversation found/i.test(msg) ? "no_session" : "failed"));
}
try {
const j = JSON.parse(out) as { result?: string; session_id?: string; total_cost_usd?: number; duration_ms?: number; is_error?: boolean };
const j = JSON.parse(out) as { result?: string; session_id?: string; total_cost_usd?: number; duration_ms?: number; duration_api_ms?: number; num_turns?: number; is_error?: boolean };
if (j.is_error) return reject(new ClaudeError(`claude вернул ошибку: ${String(j.result).slice(0, 300)}`, "failed"));
resolve({ text: j.result ?? "", sessionId: j.session_id ?? call.sessionId, costUsd: j.total_cost_usd, durationMs: j.duration_ms });
resolve({
text: j.result ?? "", sessionId: j.session_id ?? call.sessionId, costUsd: j.total_cost_usd, durationMs: j.duration_ms,
timing: { turnMs: Date.now() - tStart, apiMs: j.duration_api_ms, claudeMs: j.duration_ms, numTurns: j.num_turns },
});
} catch {
reject(new ClaudeError(`не удалось разобрать ответ claude: ${out.slice(0, 200)}`, "failed"));
}

View 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,
};
}

View File

@@ -1,7 +1,8 @@
import { randomUUID } from "node:crypto";
import { join } from "node:path";
import type { Logger, Pool } from "khb_common";
import { ClaudeError, type ClaudeResult, type ClaudeRunner, type ToolSet } from "./cli-runner.js";
import { ClaudeError, type ClaudeResult, type ClaudeRunner, type ToolSet, type TurnTiming } from "./cli-runner.js";
import type { LiveRunner } from "./live-runner.js";
import { KeyedMutex, Semaphore } from "./pool.js";
import { missingSections, parseSections } from "./sections.js";
import type { AgentSettings } from "../settings.js";
@@ -11,21 +12,37 @@ export interface AgentContext {
log: Logger;
settings: AgentSettings;
runner: ClaudeRunner;
/** Новая версия агента чата: долгоживущие процессы (только для менеджеров из agent.live.managerIds). */
liveRunner?: LiveRunner;
gate: Semaphore;
locks: KeyedMutex;
/** Сообщение ИТ-команде (Slack); ошибки отправки не должны ломать обработку. */
notifyIt(text: string): Promise<void>;
}
export class AgentFailure extends Error {}
/** Тайминг запуска агента: ожидание очереди и каждый вызов модели (с повторами формата). */
export interface AgentTiming {
queueMs: number;
live: boolean;
runs: Array<{ wallMs: number; timing?: TurnTiming; costUsd?: number; error?: string }>;
}
export class AgentFailure extends Error {
timing?: AgentTiming;
}
export interface AgentOutcome {
text: string;
sections: Map<string, string>;
sessionId: string;
attempts: number;
timing: AgentTiming;
}
/** Работает ли для менеджера новая (долгоживущая) версия агента чата. */
export const useLive = (ctx: Pick<AgentContext, "liveRunner" | "settings">, managerId: string): boolean =>
!!ctx.liveRunner && (ctx.settings.live?.managerIds ?? []).includes(managerId);
export const managerWorkDir = (s: AgentSettings, managerId: string) => join(s.workRoot, managerId);
/** Текущая память менеджера (создаёт пустую запись при первом обращении). */
@@ -78,9 +95,26 @@ export function runManagerAgent(
ctx: AgentContext,
opts: { managerId: string; step: "step2" | "step4"; tools: ToolSet; prompt: string; required: string[] },
): Promise<AgentOutcome> {
const tEnter = Date.now();
return ctx.locks.run(opts.managerId, () =>
ctx.gate.run(async () => {
const timing: AgentTiming = { queueMs: Date.now() - tEnter, live: false, runs: [] };
const cwd = managerWorkDir(ctx.settings, opts.managerId);
const live = opts.tools === "chat" && useLive(ctx, opts.managerId);
timing.live = live;
const base: ClaudeRunner = live ? ctx.liveRunner!.run : ctx.runner;
const run: ClaudeRunner = async (c) => {
const t = Date.now();
try {
const r = await base(c);
timing.runs.push({ wallMs: Date.now() - t, timing: r.timing, costUsd: r.costUsd });
return r;
} catch (e) {
timing.runs.push({ wallMs: Date.now() - t, error: String(e).slice(0, 200) });
throw e;
}
};
const fail = (msg: string) => Object.assign(new AgentFailure(msg), { timing });
const mem = await loadMemory(ctx.pool, opts.managerId);
let sessionId = mem.sessionId ?? randomUUID();
let resume = mem.sessionId !== null;
@@ -91,7 +125,7 @@ export function runManagerAgent(
let res: ClaudeResult;
try {
try {
res = await ctx.runner({ prompt, cwd, sessionId, resume, tools: opts.tools });
res = await run({ prompt, cwd, sessionId, resume, tools: opts.tools });
} catch (e) {
if (!(e instanceof ClaudeError) || e.kind !== "no_session") throw e;
// сессия потеряна: новая сессия, инструкции и память подаются заново (они в промте шага; при исправлении формата - исходный промт)
@@ -101,12 +135,12 @@ export function runManagerAgent(
resume = false;
prompt = opts.prompt;
runId = await startRun(ctx, opts.managerId, opts.step, attempt, sessionId, false);
res = await ctx.runner({ prompt, cwd, sessionId, resume, tools: opts.tools });
res = await run({ prompt, cwd, sessionId, resume, tools: opts.tools });
}
} catch (e) {
lastErr = e instanceof Error ? e.message : String(e);
await finishRun(ctx, runId, false, { error: lastErr });
throw new AgentFailure(lastErr);
throw fail(lastErr);
}
sessionId = res.sessionId;
await ctx.pool.query("update agent_manager_memory set claude_session_id = $2, updated_at = now() where manager_person_id = $1", [opts.managerId, sessionId]);
@@ -117,19 +151,20 @@ export function runManagerAgent(
if (/коннектор[^.\n]{0,60}(недоступ|удал|пропал|отключ)/i.test(connectorText)) {
await ctx.pool.query("update agent_manager_memory set claude_session_id = null, updated_at = now() where manager_person_id = $1", [opts.managerId]);
ctx.log.warn({ managerId: opts.managerId }, "агент сообщил о недоступности коннектора - сессия claude сброшена");
if (live) ctx.liveRunner!.close(cwd);
}
const missing = missingSections(sections, opts.required);
const changes = sections.get("изменения jobtread");
if (!missing.length) {
await finishRun(ctx, runId, true, { durationMs: res.durationMs, costUsd: res.costUsd, changes });
return { text: res.text, sections, sessionId, attempts: attempt };
return { text: res.text, sections, sessionId, attempts: attempt, timing };
}
lastErr = `в ответе нет разделов: ${missing.map((m) => `## ${m}`).join(", ")}`;
await finishRun(ctx, runId, false, { durationMs: res.durationMs, costUsd: res.costUsd, error: lastErr, changes });
resume = true;
prompt = `Твой предыдущий ответ не принят: ${lastErr}. Исправь и выведи ответ ЦЕЛИКОМ в требуемом формате (разделы \`## Название\`), без пояснений вне разделов. Ничего повторно не выполняй в системах (JobTread и др.), только поправь формат.`;
}
throw new AgentFailure(lastErr);
throw fail(lastErr);
}),
);
}