397 lines
24 KiB
TypeScript
397 lines
24 KiB
TypeScript
import { copyFileSync, mkdirSync } from "node:fs";
|
||
import { basename, join } from "node:path";
|
||
import { localDate } from "khb_common";
|
||
import { AgentFailure, loadMemory, managerWorkDir, runManagerAgent, saveMemory, useLive, type AgentContext } from "../agents/session.js";
|
||
import { loadFragment, loadPrompt, type PromptSide } from "../agents/prompts.js";
|
||
import { saveProblems } from "../agents/step2.js";
|
||
import type { DriveSync } from "./drive.js";
|
||
import type { SlackApi } from "./api.js";
|
||
import { applyRecapOutput, getRecapState, loadChannelDialog, parseReactions, recapBlock } from "./recap.js";
|
||
import { saveChatTiming, type ChatTiming } from "./timing.js";
|
||
import { normalizeVoice, speechText, type ReplyMode, type Tts } from "./tts.js";
|
||
|
||
export interface ManagerInfo {
|
||
personId: string;
|
||
name: string;
|
||
slackUserId: string | null;
|
||
slackChannelId: string | null;
|
||
/** Режим ответов в чате: text (по умолчанию) / both / audio. */
|
||
replyMode?: ReplyMode;
|
||
/** Голос Chirp 3 HD для чата; null - по умолчанию. */
|
||
ttsVoice?: string | null;
|
||
/** manager - чат менеджера; ceo - личный чат руководителя (свой промт, ответ в разделе `## Ответ Arthur`, без списка задач на день). */
|
||
chatKind?: "manager" | "ceo";
|
||
}
|
||
|
||
/** Проектный канал Slack: проект задан каналом, уточнять его у пользователя не нужно. */
|
||
export interface ProjectContext {
|
||
jobId: string;
|
||
jobName: string | null;
|
||
channel: string;
|
||
senderName: string | null;
|
||
isHuddle: boolean;
|
||
}
|
||
|
||
export interface IncomingMessage {
|
||
/** Контекст проектного канала (если сообщение пришло из него). */
|
||
project?: ProjectContext;
|
||
channel: string;
|
||
ts: string;
|
||
text: string;
|
||
fileIds: string[];
|
||
/** Slack-пользователь, приславший сообщение (любой участник чата; null - папка Drive). */
|
||
senderUserId?: string;
|
||
/** Локальные файлы, уже лежащие на диске (тесты, симуляция); копируются в папку материалов. */
|
||
localFiles?: string[];
|
||
}
|
||
|
||
export interface ChatDeps {
|
||
ctx: AgentContext;
|
||
slack: Pick<SlackApi, "postMessage" | "postMessageTs" | "fileInfo" | "download" | "uploadFile" | "history" | "userName" | "botUserId" | "addReaction">;
|
||
/** Синтез речи; без него ответы всегда текстовые. */
|
||
tts?: Tts;
|
||
defaultVoice?: string;
|
||
drive?: DriveSync;
|
||
/** Ключи сервисных аккаунтов Google (JSON) для агентов: full - руководитель, builder - строители и проектные чаты. */
|
||
driveKeys?: { full?: string; builder?: string };
|
||
timezone: string;
|
||
now?: () => Date;
|
||
/** Тест: не слать ответ в Slack. */
|
||
dryPublish?: boolean;
|
||
}
|
||
|
||
export interface ChatResult {
|
||
reply: string | null;
|
||
published: boolean;
|
||
/** Аудиоответ отправлен. */
|
||
audioSent?: boolean;
|
||
attachments: { name: string; path: string; mimetype: string; size: number; link?: string }[];
|
||
}
|
||
|
||
/** Начало текущих суток (полночь) в часовом поясе tz, как момент времени. */
|
||
export function startOfLocalDay(now: Date, tz: string): Date {
|
||
const parts = new Intl.DateTimeFormat("en-CA", { timeZone: tz, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23" }).formatToParts(now);
|
||
const g = (k: string) => Number(parts.find((p) => p.type === k)?.value ?? 0);
|
||
const sinceMidnightMs = ((g("hour") * 60 + g("minute")) * 60 + g("second")) * 1000 + now.getMilliseconds();
|
||
return new Date(now.getTime() - sinceMidnightMs);
|
||
}
|
||
|
||
const isoStamp = (d: Date) => d.toISOString().replace(/[:.]/g, "-");
|
||
|
||
async function todayList(ctx: AgentContext, managerId: string, date: string): Promise<string> {
|
||
const { rows } = await ctx.pool.query("select list_text from manager_day_list where manager_person_id = $1 and list_date = $2 and is_current order by created_at desc limit 1", [managerId, date]);
|
||
return (rows[0]?.list_text as string | undefined) ?? "(список на сегодня ещё не сформирован)";
|
||
}
|
||
|
||
/** Шаг 4: пакет сообщений менеджера -> один запуск агента -> ответ в Slack, запись в JobTread делает агент после подтверждения. */
|
||
export async function handleManagerMessages(
|
||
deps: ChatDeps,
|
||
manager: ManagerInfo,
|
||
messages: IncomingMessage[],
|
||
opts: { systemEvent?: string; project?: ProjectContext; channel?: 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 = opts.channel ?? messages[0]?.channel ?? manager.slackChannelId;
|
||
const sub = `${isoStamp(now)}_${channel ?? "nochannel"}`;
|
||
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(
|
||
`update reminder_history set reply_at = now(), reply_summary = left($2, 500), reply_outcome = 'other'
|
||
where id = (select r.id from reminder_history r join assistant_project ap on ap.id = r.assistant_project_id
|
||
where ap.manager_person_id = $1 and r.reply_at is null and r.reminded_at > now() - interval '1 day'
|
||
order by r.reminded_at desc limit 1)`,
|
||
[manager.personId, messages.map((m) => m.text).join(" ").trim() || "(вложения)"],
|
||
);
|
||
}
|
||
|
||
// 1. вложения -> локальная папка
|
||
const attachments: ChatResult["attachments"] = [];
|
||
const perMessage = new Map<string, string[]>();
|
||
for (const m of messages) {
|
||
const lines: string[] = [];
|
||
for (const id of m.fileIds) {
|
||
const info = await deps.slack.fileInfo(id);
|
||
if (!info) {
|
||
lines.push(` - вложение ${id}: не удалось получить информацию (возможно, не подгрузилось)`);
|
||
continue;
|
||
}
|
||
const name = `slack_${info.id}_${info.name.replace(/[^\w.\- ]/g, "_")}`;
|
||
const path = join(mediaDir, name);
|
||
try {
|
||
const size = await deps.slack.download(info, path);
|
||
attachments.push({ name, path, mimetype: info.mimetype, size });
|
||
} catch (e) {
|
||
lines.push(` - вложение ${info.name}: ошибка скачивания (${e instanceof Error ? e.message : e})`);
|
||
}
|
||
}
|
||
for (const lf of m.localFiles ?? []) {
|
||
const path = join(mediaDir, basename(lf));
|
||
copyFileSync(lf, path);
|
||
attachments.push({ name: basename(lf), path, mimetype: "", size: 0 });
|
||
}
|
||
perMessage.set(m.ts, lines);
|
||
}
|
||
|
||
tm.inputsMs = lap();
|
||
|
||
// 2. копии исходников в Drive (сбой не останавливает обработку)
|
||
let links: Record<string, string> = {};
|
||
if (deps.drive && attachments.length) {
|
||
try {
|
||
links = await deps.drive.upload(mediaDir, sub);
|
||
for (const a of attachments) a.link = links[a.name];
|
||
} catch (e) {
|
||
ctx.log.warn({ err: String(e) }, "выгрузка исходников в Drive не удалась");
|
||
await ctx.pool.query("insert into agent_problem_log (manager_person_id, step, severity, body) values ($1,'step4','log',$2)", [manager.personId, `Drive: ${String(e).slice(0, 500)}`]);
|
||
}
|
||
}
|
||
|
||
tm.driveMs = lap();
|
||
|
||
// 3. промт
|
||
const mem = await loadMemory(ctx.pool, manager.personId);
|
||
const todayCount = (
|
||
await ctx.pool.query("select count(*)::int as n from slack_message_log where manager_person_id = $1 and received_at >= $2", [manager.personId, new Date(now.getTime() - 24 * 3600_000)])
|
||
).rows[0].n as number;
|
||
const { rows: aps } = await ctx.pool.query(
|
||
"select ap.jt_job_id, ap.is_enabled, j.name from assistant_project ap left join jt_job j on j.id = ap.jt_job_id where ap.manager_person_id = $1",
|
||
[manager.personId],
|
||
);
|
||
const disabled = aps.filter((r) => !r.is_enabled) as { jt_job_id: string; name: string | null }[];
|
||
const writableJobs = ctx.settings.allowedJobIds.filter((id) => !disabled.some((d) => d.jt_job_id === id));
|
||
// автор каждого сообщения: ответ адресуется тому, кто написал (в чате могут писать и другие, не только менеджер)
|
||
const senderNames = new Map<string, string>();
|
||
for (const id of new Set(messages.map((m) => m.senderUserId).filter((x): x is string => !!x))) {
|
||
const row = (await ctx.pool.query("select display_name from person where slack_user_id = $1 and is_active limit 1", [id])).rows[0];
|
||
const name = (row?.display_name as string | undefined) ?? (await deps.slack.userName?.(id).catch(() => null)) ?? null;
|
||
if (name) senderNames.set(id, name);
|
||
}
|
||
const authorOf = (m: IncomingMessage): string => {
|
||
if (!m.senderUserId) return "";
|
||
const n = senderNames.get(m.senderUserId);
|
||
return ` ${n ? `${n} (<@${m.senderUserId}>)` : `<@${m.senderUserId}>`}${m.senderUserId === manager.slackUserId ? " [менеджер]" : ""}:`;
|
||
};
|
||
const msgBlock = messages.length
|
||
? messages
|
||
.map((m) => {
|
||
return [`- [${new Date(Number(m.ts) * 1000).toISOString()}]${authorOf(m)} ${m.text || "(без текста)"}`, ...(perMessage.get(m.ts) ?? [])].join("\n");
|
||
})
|
||
.join("\n")
|
||
: "(новых сообщений нет)";
|
||
const attBlock = attachments.length
|
||
? attachments.map((a) => `- ${a.path} (${a.mimetype || "?"}, ${a.size} байт)${a.link ? ` | Drive: ${a.link}` : ""}`).join("\n")
|
||
: "(вложений нет)";
|
||
const proj = opts.project ?? messages.find((m) => m.project)?.project;
|
||
// Новая версия (долгоживущий агент) читает промты из proposed, прежняя (остальные менеджеры) - из approved
|
||
const live = useLive(ctx, manager.personId);
|
||
const side: PromptSide = live ? "proposed" : "approved";
|
||
const fragment = (file: string, title: string, vars: Record<string, string> = {}) => loadFragment(file, title, vars, side);
|
||
// блоки, которые согласованные промты могут ожидать у всех версий агента; если на этой стороне фрагмента ещё нет - блок пропускается
|
||
const optFragment = (file: string, title: string, vars: Record<string, string> = {}): string | null => {
|
||
try {
|
||
return loadFragment(file, title, vars, side);
|
||
} catch {
|
||
return null;
|
||
}
|
||
};
|
||
const projectBlock = proj
|
||
? [
|
||
"",
|
||
`# Проектный канал\n${fragment("p-project-channel-context.md", "Контекст проектного канала", {
|
||
job: proj.jobName ?? proj.jobId,
|
||
job_id: proj.jobId,
|
||
senders: [...new Set(messages.map((m) => m.senderUserId).filter((x): x is string => !!x))].map((id) => senderNames.get(id) ?? id).join(", ") || "неизвестны",
|
||
last_sender: proj.senderName ? ` (последний: ${proj.senderName})` : "",
|
||
})}${writableJobs.includes(proj.jobId) ? "" : `\n${fragment("p-project-channel-context.md", "Запись в проект не разрешена")}`}`,
|
||
]
|
||
: [];
|
||
// Новая версия (долгоживущий агент): если процесс уже в диалоге, инструкции, список задач и память не повторяются - только новое
|
||
// короткий промт - только если живой процесс продолжает ту же сессию, что записана для менеджера (после сброса сессии нужны полные инструкции)
|
||
const inDialog = live && mem.sessionId !== null && ctx.liveRunner!.activeSession(managerWorkDir(ctx.settings, manager.personId)) === mem.sessionId;
|
||
// Новая версия: todo самого менеджера можно закрывать и менять в любом проекте и на уровне организации (обращение ИТ 16.10.2026: todo без проекта агент не трогал)
|
||
const membershipId = (((await ctx.pool.query("select jt_membership_id from person where id = $1", [manager.personId])).rows[0]?.jt_membership_id as string | null | undefined) ?? null);
|
||
const todoText = optFragment("p-long-living-agents.md", "Todo менеджера", { membership: membershipId ? `; его membership в JobTread: ${membershipId}` : "" });
|
||
const todoRules = todoText ? `\n${todoText}` : "";
|
||
const liveRules = live ? `\n${fragment("p-long-living-agents.md", "Правила долгоживущего агента")}` : "";
|
||
const testJobs = ctx.settings.testJobIds ?? [];
|
||
const writeRules = writableJobs.length
|
||
? `${fragment("p-chat-environment.md", "Запись в JobTread разрешена", { jobs: writableJobs.join(", ") })}${
|
||
testJobs.some((id) => writableJobs.includes(id)) ? ` ${fragment("p-chat-environment.md", "Тестовые проекты", { test_jobs: testJobs.join(", ") })}` : ""
|
||
}`
|
||
: fragment("p-chat-environment.md", "Запись в JobTread запрещена");
|
||
const disabledRules = disabled.length
|
||
? `\n${fragment("p-chat-environment.md", "Отключённые проекты", { projects: disabled.map((d) => `${d.name ?? d.jt_job_id} (${d.jt_job_id})`).join("; ") })}`
|
||
: "";
|
||
// Новая версия: упоминание менеджера и частота сообщений ассистента (правило «не чаще раза в час»)
|
||
const iso = (v: unknown) => (v ? new Date(v as string).toISOString() : "нет");
|
||
const freqBlocks: string[] = [];
|
||
{
|
||
const { rows: fr } = await ctx.pool.query(
|
||
`select (select max(reply_at) from chat_timing where manager_person_id = $1) as last_assistant,
|
||
(select max(received_at) from slack_message_log where manager_person_id = $1) as last_human,
|
||
(select count(*)::int from chat_timing where manager_person_id = $1 and reply_at >= $2::timestamptz) as assistant_today,
|
||
exists(select 1 from slack_message_log where manager_person_id = $1 and received_at >= $2::timestamptz) as replied_today,
|
||
(select count(*)::int from chat_timing where manager_person_id = $1 and reply_at > coalesce((select max(received_at) from slack_message_log where manager_person_id = $1), '-infinity')) as unanswered`,
|
||
[manager.personId, startOfLocalDay(now, deps.timezone)],
|
||
);
|
||
const mgrText = optFragment("p-chat-environment.md", "Менеджер", { name: manager.name, mention: manager.slackUserId ? `<@${manager.slackUserId}>` : manager.name });
|
||
const freqText = optFragment("p-chat-environment.md", "Частота сообщений", { last_assistant: iso(fr[0]?.last_assistant), last_human: iso(fr[0]?.last_human), unanswered: String(fr[0]?.unanswered ?? 0), assistant_today: String(fr[0]?.assistant_today ?? 0), replied_today: fr[0]?.replied_today ? "да" : "нет" });
|
||
if (mgrText) freqBlocks.push("", `# Менеджер\n${mgrText}`);
|
||
if (freqText) freqBlocks.push("", `# Частота сообщений\n${freqText}`);
|
||
}
|
||
const isCeo = manager.chatKind === "ceo";
|
||
// чтение зеркала Supabase: агент менеджера - роль khb_agent, руководитель - khb_agent_ceo (команда khb-sql, Bash)
|
||
const sqlCfg = ctx.settings.sql;
|
||
const driveKey = isCeo ? deps.driveKeys?.full : deps.driveKeys?.builder; // Google Drive: руководитель - полный ключ, остальные (включая проектные чаты) - builder
|
||
const agentEnv: Record<string, string> = {
|
||
...(sqlCfg ? { KHB_SQL_URL: isCeo ? (sqlCfg.ceoUrl ?? sqlCfg.agentUrl) : sqlCfg.agentUrl } : {}),
|
||
...(driveKey ? { KHB_DRIVE_KEY: driveKey } : {}),
|
||
};
|
||
const sqlEnv = Object.keys(agentEnv).length ? agentEnv : undefined;
|
||
const replyKey = isCeo ? "ответ arthur" : "ответ менеджеру";
|
||
const listText = isCeo ? "" : await todayList(ctx, manager.personId, today);
|
||
// проектный канал: диалог за сутки с временем (по Тампе) и накопленное для Daily Log
|
||
const channelBlocks: string[] = [];
|
||
const recapOn = !!proj && !!channel && live; // тихий режим и recap - только новая версия агента (промты proposed)
|
||
if (recapOn && proj && channel) {
|
||
const dialogText = await loadChannelDialog(deps.slack, channel, now, deps.timezone);
|
||
const st = await getRecapState(ctx.pool, channel);
|
||
channelBlocks.push("", `# Диалог канала за последние сутки (время по Тампе)
|
||
${dialogText}`, "", `# Накопленное для Daily Log
|
||
${recapBlock(st, deps.timezone)}`);
|
||
}
|
||
const buildPrompt = (dialog: boolean): string => [
|
||
...(dialog
|
||
? [`# Продолжение диалога\n${fragment("p-long-living-agents.md", "Продолжение диалога")}`]
|
||
: [loadPrompt(isCeo ? "p-ceo-assistant.md" : proj ? "p-project-channel.md" : "p-manager-dialog.md", { media_dir: mediaDir }, side)]),
|
||
"",
|
||
`# Дата и время\n${now.toISOString()} (UTC); дата по Тампе: ${today}; сообщений менеджера за последние сутки: ${todayCount}`,
|
||
...freqBlocks,
|
||
...(opts.systemEvent ? ["", `# Системное событие\n${opts.systemEvent}`] : []),
|
||
...projectBlock,
|
||
...channelBlocks,
|
||
...(dialog
|
||
? []
|
||
: isCeo
|
||
? ["", `# Память\n${mem.memoryText.trim() || "(пусто)"}`]
|
||
: ["", `# Список задач на сегодня\n${listText}`, "", `# Память\n${mem.memoryText.trim() || "(пусто)"}`]),
|
||
"",
|
||
`# Ограничения среды\nМенеджер: ${manager.name}. ${writeRules}${disabledRules}${liveRules}${todoRules}`,
|
||
"",
|
||
`# Новые сообщения менеджера\n${msgBlock}\n\nВложения (локальные пути):\n${attBlock}`,
|
||
].join("\n");
|
||
const prompt = buildPrompt(inDialog);
|
||
// полный промт нужен для повтора в новой сессии (коннектор JobTread не поднялся), когда рабочий промт - короткий "продолжение диалога"
|
||
const fullPrompt = inDialog ? buildPrompt(false) : undefined;
|
||
|
||
tm.promptMs = lap();
|
||
tm.promptChars = prompt.length;
|
||
|
||
// 4. агент
|
||
let out;
|
||
try {
|
||
out = await runManagerAgent(ctx, { managerId: manager.personId, step: "step4", tools: "chat", prompt, fullPrompt, env: sqlEnv, required: [replyKey, "память"] });
|
||
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, "Не смог обработать сообщение - уже сообщил ИТ-команде, скоро разберёмся.");
|
||
throw e;
|
||
}
|
||
|
||
// 5. результат
|
||
await saveMemory(ctx.pool, manager.personId, out.sections.get("память")!);
|
||
await saveProblems(ctx, manager.personId, "step4", out.sections);
|
||
if (recapOn && proj && channel) {
|
||
await applyRecapOutput(ctx.pool, { channel, managerId: manager.personId, jobId: proj.jobId, sections: out.sections, humanMessage: messages.length > 0, now });
|
||
if (!deps.dryPublish && deps.slack.addReaction)
|
||
for (const r of parseReactions(out.sections.get("реакции"))) await deps.slack.addReaction(channel, r.ts, r.emoji).catch((e) => ctx.log.warn({ err: String(e) }, "реакция не поставлена"));
|
||
}
|
||
const replyRaw = out.sections.get(replyKey)!;
|
||
const reply = /^\(без ответа\)\.?$/i.test(replyRaw) ? null : replyRaw;
|
||
let published = false;
|
||
let audioSent = false;
|
||
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(
|
||
`insert into reminder_history (assistant_project_id, reminded_at, reminder_text)
|
||
select ap.id, now(), left($2, 1000) from assistant_project ap where ap.manager_person_id = $1 and ap.is_enabled order by ap.created_at limit 1`,
|
||
[manager.personId, reply],
|
||
);
|
||
}
|
||
|
||
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; replyTs: string | null }> {
|
||
const mode = manager.replyMode ?? "text";
|
||
const voice = normalizeVoice(manager.ttsVoice) ?? normalizeVoice(deps.defaultVoice) ?? "Aoede";
|
||
let audioSent = false;
|
||
if (mode !== "text" && deps.tts && deps.slack.uploadFile && speechText(reply)) {
|
||
try {
|
||
const mp3 = await deps.tts.synthesize(reply, voice);
|
||
await deps.slack.uploadFile(channel, "assistant-reply.mp3", mp3, "Voice reply");
|
||
audioSent = true;
|
||
} catch (e) {
|
||
deps.ctx.log.warn({ manager: manager.personId, err: String(e) }, "аудиоответ не отправлен, отправляю текстом");
|
||
await deps.ctx.pool.query("insert into agent_problem_log (manager_person_id, step, severity, body) values ($1,'step4','log',$2)", [manager.personId, `Аудиоответ (Chirp 3 HD, ${voice}) не отправлен: ${String(e).slice(0, 400)}`]);
|
||
}
|
||
}
|
||
const needText = mode === "text" || mode === "both" || !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 };
|
||
}
|