Долгоживущий агент чата (только для 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

@@ -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);
}),
);
}