Долгоживущий агент чата (только для 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,11 +1,12 @@
import { copyFileSync, mkdirSync } from "node:fs";
import { basename, join } from "node:path";
import { localDate } from "khb_common";
import { AgentFailure, loadMemory, managerWorkDir, runManagerAgent, saveMemory, type AgentContext } from "../agents/session.js";
import { AgentFailure, loadMemory, managerWorkDir, runManagerAgent, saveMemory, useLive, type AgentContext } from "../agents/session.js";
import { loadPrompt } from "../agents/prompts.js";
import { saveProblems } from "../agents/step2.js";
import type { DriveSync } from "./drive.js";
import type { SlackApi } from "./api.js";
import { saveChatTiming, type ChatTiming } from "./timing.js";
import { normalizeVoice, speechText, type ReplyMode, type Tts } from "./tts.js";
export interface ManagerInfo {
@@ -43,7 +44,7 @@ export interface IncomingMessage {
export interface ChatDeps {
ctx: AgentContext;
slack: Pick<SlackApi, "postMessage" | "fileInfo" | "download" | "uploadFile">;
slack: Pick<SlackApi, "postMessage" | "postMessageTs" | "fileInfo" | "download" | "uploadFile">;
/** Синтез речи; без него ответы всегда текстовые. */
tts?: Tts;
defaultVoice?: string;
@@ -77,6 +78,14 @@ export async function handleManagerMessages(
opts: { systemEvent?: string } = {},
): Promise<ChatResult> {
const { ctx } = deps;
const t0 = Date.now();
let mark = t0;
const lap = () => {
const n = Date.now();
const d = n - mark;
mark = n;
return d;
};
const now = (deps.now ?? (() => new Date()))();
const today = localDate(now, deps.timezone);
const channel = messages[0]?.channel ?? manager.slackChannelId;
@@ -84,6 +93,17 @@ export async function handleManagerMessages(
const mediaDir = join(managerWorkDir(ctx.settings, manager.personId), "media", sub);
mkdirSync(mediaDir, { recursive: true });
// тайминг запроса (таблица chat_timing): от сообщения в Slack до ответа в Slack
const receivedAt =
messages.length && !opts.systemEvent
? (((await ctx.pool.query("select min(received_at) as r from slack_message_log where channel_id = $1 and message_ts = any($2)", [channel ?? null, messages.map((m) => m.ts)])).rows[0]?.r as Date | null | undefined) ?? null)
: null;
const tm: ChatTiming = {
managerId: manager.personId, channel: channel ?? null, kind: opts.systemEvent ? "event" : "message", agentVersion: useLive(ctx, manager.personId) ? "live" : "classic",
startedAt: new Date(t0), messageTs: opts.systemEvent ? undefined : messages[0]?.ts, receivedAt, status: "ok",
};
mark = Date.now();
// история напоминаний (вход 7): ответ менеджера закрывает последнее неотвеченное напоминание
if (messages.length && !opts.systemEvent) {
await ctx.pool.query(
@@ -123,6 +143,8 @@ export async function handleManagerMessages(
perMessage.set(m.ts, lines);
}
tm.inputsMs = lap();
// 2. копии исходников в Drive (сбой не останавливает обработку)
let links: Record<string, string> = {};
if (deps.drive && attachments.length) {
@@ -135,6 +157,8 @@ export async function handleManagerMessages(
}
}
tm.driveMs = lap();
// 3. промт
const mem = await loadMemory(ctx.pool, manager.personId);
const todayCount = (
@@ -165,16 +189,23 @@ export async function handleManagerMessages(
}`,
]
: [];
// Новая версия (долгоживущий агент): если процесс уже в диалоге, инструкции, список задач и память не повторяются - только новое
const live = useLive(ctx, manager.personId);
const inDialog = live && ctx.liveRunner!.isActive(managerWorkDir(ctx.settings, manager.personId));
const liveRules = live
? "\nСессия долгоживущая: после ответа ты остаёшься в диалоге, следующие сообщения придут как продолжение. Перед записью в JobTread вызови ToolSearch с запросом select:mcp__claude_ai_JobTread__query (если инструмента ещё нет - подожди несколько секунд и повтори, до 3 раз). Только после этого можно считать коннектор недоступным. Никогда не пиши менеджеру, что ИТ что-то исправили или починили, если тебе об этом не сообщали."
: "";
const prompt = [
loadPrompt(proj ? "project_channel.md" : "step4_manager_chat.md", { media_dir: mediaDir }),
...(inDialog
? ["# Продолжение диалога\nСессия продолжается: инструкции, формат ответа и память выше остаются в силе. Ответь в том же формате разделов (`## Ответ менеджеру`, `## Память` - обновлённая память целиком, `## Изменения JobTread`, `## Обращение в ИТ`, `## Лог проблем`)."]
: [loadPrompt(proj ? "project_channel.md" : "step4_manager_chat.md", { media_dir: mediaDir })]),
"",
`# Дата и время\n${now.toISOString()} (UTC); дата по Тампе: ${today}; сообщений менеджера за последние сутки: ${todayCount}`,
...(opts.systemEvent ? ["", `# Системное событие\n${opts.systemEvent}`] : []),
...projectBlock,
"",
`# Список задач на сегодня\n${await todayList(ctx, manager.personId, today)}`,
"",
`# Память\n${mem.memoryText.trim() || "(пусто)"}`,
...(inDialog
? []
: ["", `# Список задач на сегодня\n${await todayList(ctx, manager.personId, today)}`, "", `# Память\n${mem.memoryText.trim() || "(пусто)"}`]),
"",
`# Ограничения среды\nМенеджер: ${manager.name}. ${
writableJobs.length
@@ -188,17 +219,27 @@ export async function handleManagerMessages(
disabled.length
? `\nОТКЛЮЧЁННЫЕ проекты менеджера (ассистент по ним не работает): ${disabled.map((d) => `${d.name ?? d.jt_job_id} (${d.jt_job_id})`).join("; ")}. Не обсуждай их, не пиши в них и не напоминай о них, даже если задачи этих проектов есть в списке на сегодня. Если менеджер пишет об отключённом проекте - коротко ответь, что по этому проекту ассистент сейчас отключён, и ничего не записывай.`
: ""
}`,
}${liveRules}`,
"",
`# Новые сообщения менеджера\n${msgBlock}\n\nВложения (локальные пути):\n${attBlock}`,
].join("\n");
tm.promptMs = lap();
tm.promptChars = prompt.length;
// 4. агент
let out;
try {
out = await runManagerAgent(ctx, { managerId: manager.personId, step: "step4", tools: "chat", prompt, required: ["ответ менеджеру", "память"] });
tm.agent = out.timing;
mark = Date.now();
} catch (e) {
const err = e instanceof AgentFailure || e instanceof Error ? e.message : String(e);
tm.status = "failed";
tm.error = err;
tm.agent = e instanceof AgentFailure ? e.timing : undefined;
tm.processingMs = Date.now() - t0;
await saveChatTiming(ctx.pool, tm, ctx.log);
ctx.log.error({ manager: manager.personId, err }, "шаг 4 не удался");
await ctx.notifyIt(`:warning: khbuild_assistant_prep: шаг 4 (общение) для ${manager.name} не выполнен: ${err.slice(0, 500)}`);
if (!deps.dryPublish && channel) await deps.slack.postMessage(channel, "Не смог обработать сообщение - уже сообщил ИТ-команде, скоро разберёмся.");
@@ -212,7 +253,13 @@ export async function handleManagerMessages(
const reply = /^\(без ответа\)\.?$/i.test(replyRaw) ? null : replyRaw;
let published = false;
let audioSent = false;
if (reply && channel && !deps.dryPublish) ({ published, audioSent } = await publishReply(deps, manager, channel, reply));
if (reply && channel && !deps.dryPublish) {
const tp = Date.now();
const pr = await publishReply(deps, manager, channel, reply);
({ published, audioSent } = pr);
tm.replySlackTs = pr.replyTs;
tm.publishMs = Date.now() - tp;
}
if (reply && opts.systemEvent) {
// напоминание ассистента по событию - в историю напоминаний (вход 7)
await ctx.pool.query(
@@ -222,13 +269,18 @@ export async function handleManagerMessages(
);
}
tm.postMs = Math.max(0, lap() - (tm.publishMs ?? 0));
// 6. транскрипты и итоговые файлы -> Drive
if (deps.drive && attachments.length) await deps.drive.upload(mediaDir, sub).catch((e) => ctx.log.warn({ err: String(e) }, "повторная выгрузка в Drive не удалась"));
tm.finalMs = lap();
tm.processingMs = Date.now() - t0;
await saveChatTiming(ctx.pool, tm, ctx.log);
return { reply, published, audioSent, attachments };
}
/** Публикует ответ по настройке чата: текст / текст и аудио / только аудио. Любой сбой аудио - ответ уходит текстом, ИТ видит проблему в логе. */
export async function publishReply(deps: ChatDeps, manager: ManagerInfo, channel: string, reply: string): Promise<{ published: boolean; audioSent: boolean }> {
export async function publishReply(deps: ChatDeps, manager: ManagerInfo, channel: string, reply: string): Promise<{ published: boolean; audioSent: boolean; replyTs: string | null }> {
const mode = manager.replyMode ?? "text";
const voice = normalizeVoice(manager.ttsVoice) ?? normalizeVoice(deps.defaultVoice) ?? "Aoede";
let audioSent = false;
@@ -243,6 +295,13 @@ export async function publishReply(deps: ChatDeps, manager: ManagerInfo, channel
}
}
const needText = mode === "text" || mode === "both" || !audioSent;
const published = needText ? await deps.slack.postMessage(channel, reply) : false;
return { published: published || audioSent, audioSent };
let published = false;
let replyTs: string | null = null;
if (needText) {
if (deps.slack.postMessageTs) {
replyTs = await deps.slack.postMessageTs(channel, reply);
published = replyTs !== null;
} else published = await deps.slack.postMessage(channel, reply);
}
return { published: published || audioSent, audioSent, replyTs: replyTs || null };
}