Долгоживущий агент чата (только для managerIds, тестовый менеджер) и тайминг чата (chat_timing, миграция 016); тесты; docs
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -11,6 +11,8 @@ export interface SlackFile {
|
||||
|
||||
export interface SlackApi {
|
||||
postMessage(channel: string, text: string, threadTs?: string): Promise<boolean>;
|
||||
/** То же, но возвращает ts отправленного сообщения (null - не отправлено): по нему считается время ответа для chat_timing. */
|
||||
postMessageTs?(channel: string, text: string, threadTs?: string): Promise<string | null>;
|
||||
fileInfo(fileId: string): Promise<SlackFile | null>;
|
||||
download(file: SlackFile, toPath: string): Promise<number>;
|
||||
/** Загружает файл в канал (нужен scope files:write). */
|
||||
@@ -25,13 +27,17 @@ export function createSlackApi(botToken: string, fetchFn: typeof fetch = fetch):
|
||||
headers: { "content-type": "application/json; charset=utf-8", authorization: `Bearer ${botToken}` },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
return (await res.json()) as { ok?: boolean; error?: string; file?: Record<string, unknown> };
|
||||
return (await res.json()) as { ok?: boolean; error?: string; ts?: string; file?: Record<string, unknown> };
|
||||
};
|
||||
const postTs = async (channel: string, text: string, threadTs?: string): Promise<string | null> => {
|
||||
// Slack ограничивает текст ~40000 символов; режем с запасом
|
||||
const r = await call("chat.postMessage", { channel, text: text.slice(0, 35000), ...(threadTs ? { thread_ts: threadTs } : {}) });
|
||||
return r.ok === true ? (typeof r.ts === "string" ? r.ts : "") : null;
|
||||
};
|
||||
return {
|
||||
postMessageTs: postTs,
|
||||
async postMessage(channel, text, threadTs) {
|
||||
// Slack ограничивает текст ~40000 символов; режем с запасом
|
||||
const r = await call("chat.postMessage", { channel, text: text.slice(0, 35000), ...(threadTs ? { thread_ts: threadTs } : {}) });
|
||||
return r.ok === true;
|
||||
return (await postTs(channel, text, threadTs)) !== null;
|
||||
},
|
||||
async fileInfo(fileId) {
|
||||
const res = await fetchFn(`https://slack.com/api/files.info?file=${encodeURIComponent(fileId)}`, { headers: { authorization: `Bearer ${botToken}` } });
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
|
||||
65
packages/khbuild_assistant_prep/src/slack/timing.ts
Normal file
65
packages/khbuild_assistant_prep/src/slack/timing.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import type { Pool } from "khb_common";
|
||||
import type { AgentTiming } from "../agents/session.js";
|
||||
|
||||
/** Тайминг обработки пакета сообщений (поля соответствуют таблице chat_timing). */
|
||||
export interface ChatTiming {
|
||||
managerId: string;
|
||||
channel: string | null;
|
||||
kind: "message" | "event";
|
||||
agentVersion: "classic" | "live";
|
||||
startedAt: Date;
|
||||
messageTs?: string;
|
||||
receivedAt?: Date | null;
|
||||
replySlackTs?: string | null;
|
||||
inputsMs?: number;
|
||||
driveMs?: number;
|
||||
promptMs?: number;
|
||||
promptChars?: number;
|
||||
postMs?: number;
|
||||
publishMs?: number;
|
||||
finalMs?: number;
|
||||
processingMs?: number;
|
||||
agent?: AgentTiming;
|
||||
status: "ok" | "failed";
|
||||
error?: string;
|
||||
}
|
||||
|
||||
const int = (v: number | null | undefined): number | null => (typeof v === "number" && Number.isFinite(v) ? Math.max(0, Math.round(v)) : null);
|
||||
const sum = (xs: Array<number | undefined>): number | null => {
|
||||
const v = xs.filter((x): x is number => typeof x === "number");
|
||||
return v.length ? v.reduce((a, b) => a + b, 0) : null;
|
||||
};
|
||||
|
||||
/** Секунды Slack ts ("1791741165.045849") -> Date. */
|
||||
export const slackTsToDate = (ts: string | null | undefined): Date | null => {
|
||||
const n = Number(ts);
|
||||
return Number.isFinite(n) && n > 1e9 ? new Date(Math.round(n * 1000)) : null;
|
||||
};
|
||||
|
||||
/** Сохраняет тайминг; сбой записи диагностики не должен ломать обработку чата. */
|
||||
export async function saveChatTiming(pool: Pool, t: ChatTiming, log?: { warn(o: object, m: string): void }): Promise<void> {
|
||||
try {
|
||||
const runs = t.agent?.runs ?? [];
|
||||
const messageAt = slackTsToDate(t.messageTs);
|
||||
const replyAt = slackTsToDate(t.replySlackTs);
|
||||
const modelMs = sum(runs.map((r) => r.timing?.turnMs ?? r.wallMs));
|
||||
await pool.query(
|
||||
`insert into chat_timing (manager_person_id, channel_id, kind, agent_version, status, error, message_ts, message_at, received_at, started_at, reply_slack_ts, reply_at,
|
||||
slack_in_ms, debounce_ms, inputs_ms, drive_ms, prompt_ms, prompt_chars, queue_ms, start_ms, model_ms, api_ms, first_event_ms, tool_calls, num_turns, attempts, cost_usd,
|
||||
post_ms, publish_ms, final_ms, processing_ms, total_ms, steps)
|
||||
values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$30,$31,$32,$33)`,
|
||||
[
|
||||
t.managerId, t.channel, t.kind, t.agentVersion, t.status, t.error?.slice(0, 500) ?? null, t.messageTs ?? null, messageAt, t.receivedAt ?? null, t.startedAt, t.replySlackTs ?? null, replyAt,
|
||||
int(messageAt && t.receivedAt ? t.receivedAt.getTime() - messageAt.getTime() : null),
|
||||
int(t.receivedAt ? t.startedAt.getTime() - t.receivedAt.getTime() : null),
|
||||
int(t.inputsMs), int(t.driveMs), int(t.promptMs), int(t.promptChars), int(t.agent?.queueMs),
|
||||
int(sum(runs.map((r) => r.timing?.startMs))), int(modelMs), int(sum(runs.map((r) => r.timing?.apiMs))), int(runs[0]?.timing?.firstEventMs),
|
||||
int(sum(runs.map((r) => r.timing?.toolCalls))), int(sum(runs.map((r) => r.timing?.numTurns))), runs.length || null, sum(runs.map((r) => r.costUsd)),
|
||||
int(t.postMs), int(t.publishMs), int(t.finalMs), int(t.processingMs), int(messageAt && replyAt ? replyAt.getTime() - messageAt.getTime() : null),
|
||||
JSON.stringify({ runs }),
|
||||
],
|
||||
);
|
||||
} catch (e) {
|
||||
log?.warn({ err: String(e) }, "не удалось сохранить тайминг чата");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user