Озвучивание ответов (Google Chirp 3 HD): режим и голос на чат, миграция 007, загрузка аудио в Slack; docs
All checks were successful
ci / test (push) Successful in 15s
ci / deploy (push) Successful in 1m5s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-13 22:01:47 +03:00
parent 0c4fb2df99
commit d8f3ddee37
15 changed files with 316 additions and 11 deletions

View File

@@ -10,7 +10,8 @@ import { createSlackApi, startSocketMode } from "./slack/api.js";
import { handleManagerMessages, type ChatDeps, type ManagerInfo } from "./slack/chat.js";
import { createRcloneDrive } from "./slack/drive.js";
import { DriveInbox } from "./slack/drive-inbox.js";
import { SlackIntake } from "./slack/intake.js";
import { SlackIntake, rowToManager } from "./slack/intake.js";
import { createGoogleTts } from "./slack/tts.js";
const { common, service } = loadServiceSettings("khbuild_assistant_prep", assistantPrepSchema);
const log = createLogger("khbuild_assistant_prep", common.logLevel);
@@ -30,18 +31,18 @@ const ctx: AgentContext = {
const slackApi = service.slack ? createSlackApi(service.slack.botToken) : undefined;
const chatDeps: ChatDeps | undefined = slackApi
? { ctx, slack: slackApi, drive: service.drive ? createRcloneDrive(service.drive) : undefined, timezone: common.timezone }
? { ctx, slack: slackApi, drive: service.drive ? createRcloneDrive(service.drive) : undefined, tts: service.tts ? createGoogleTts(service.tts) : undefined, defaultVoice: service.tts?.defaultVoice, timezone: common.timezone }
: undefined;
async function managers(modes: string[]): Promise<ManagerInfo[]> {
const { rows } = await pool.query(
`select distinct cm.person_id, p.display_name, cm.slack_user_id, cm.slack_channel_id
`select distinct cm.person_id, p.display_name, cm.slack_user_id, cm.slack_channel_id, cm.reply_mode, cm.tts_voice
from construction_manager cm join person p on p.id = cm.person_id
join assistant_project ap on ap.manager_person_id = cm.person_id and ap.is_enabled and ap.mode = any($1)
where cm.is_active and p.is_active`,
[modes],
);
return rows.map((r) => ({ personId: r.person_id, name: r.display_name, slackUserId: r.slack_user_id, slackChannelId: r.slack_channel_id }));
return rows.map(rowToManager);
}
const EVENT_TEXT: Record<string, string> = {

View File

@@ -37,6 +37,15 @@ export const driveSchema = z.object({
inboxScanSeconds: z.number().default(10),
});
export const ttsSchema = z.object({
/** Ключ API Google Cloud Text-to-Speech (Chirp 3 HD). Без ключа аудиоответы отключены (всегда только текст). */
apiKey: z.string().min(1),
languageCode: z.string().default("en-US"),
/** Голос по умолчанию, если у чата не задан свой (короткое имя Chirp 3 HD). */
defaultVoice: z.string().default("Aoede"),
speakingRate: z.number().min(0.25).max(2).optional(),
});
export const assistantPrepSchema = z.object({
http: z.object({ host: z.string().default("127.0.0.1"), port: z.number(), token: z.string().min(1) }),
lookaheadWorkDays: z.number().default(10),
@@ -46,5 +55,6 @@ export const assistantPrepSchema = z.object({
agent: agentSchema.default({}),
slack: slackSchema.optional(),
drive: driveSchema.optional(),
tts: ttsSchema.optional(),
});
export type AssistantPrepSettings = z.infer<typeof assistantPrepSchema>;

View File

@@ -13,6 +13,8 @@ export interface SlackApi {
postMessage(channel: string, text: string, threadTs?: string): Promise<boolean>;
fileInfo(fileId: string): Promise<SlackFile | null>;
download(file: SlackFile, toPath: string): Promise<number>;
/** Загружает файл в канал (нужен scope files:write). */
uploadFile?(channel: string, filename: string, data: Buffer, title?: string): Promise<void>;
}
/** Web API Slack под токеном бота (отправка сообщений и скачивание вложений). */
@@ -38,6 +40,19 @@ export function createSlackApi(botToken: string, fetchFn: typeof fetch = fetch):
if (!j.ok || !f || typeof f.url_private_download !== "string") return null;
return { id: String(f.id), name: String(f.name ?? f.id), mimetype: String(f.mimetype ?? ""), size: Number(f.size ?? 0), urlPrivateDownload: f.url_private_download };
},
async uploadFile(channel, filename, data, title) {
const form = new URLSearchParams({ filename, length: String(data.length) });
const start = (await (await fetchFn("https://slack.com/api/files.getUploadURLExternal", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded", authorization: `Bearer ${botToken}` },
body: form,
})).json()) as { ok?: boolean; error?: string; upload_url?: string; file_id?: string };
if (!start.ok || !start.upload_url || !start.file_id) throw new Error(`Slack files.getUploadURLExternal: ${start.error ?? "нет upload_url"}`);
const up = await fetchFn(start.upload_url, { method: "POST", body: new Uint8Array(data) });
if (!up.ok) throw new Error(`Slack upload: HTTP ${up.status}`);
const done = await call("files.completeUploadExternal", { files: [{ id: start.file_id, title: title ?? filename }], channel_id: channel });
if (!done.ok) throw new Error(`Slack files.completeUploadExternal: ${done.error}`);
},
async download(file, toPath) {
const res = await fetchFn(file.urlPrivateDownload, { headers: { authorization: `Bearer ${botToken}` } });
if (!res.ok) throw new Error(`скачивание ${file.name}: HTTP ${res.status}`);

View File

@@ -6,12 +6,17 @@ 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 { 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;
}
export interface IncomingMessage {
@@ -25,7 +30,10 @@ export interface IncomingMessage {
export interface ChatDeps {
ctx: AgentContext;
slack: Pick<SlackApi, "postMessage" | "fileInfo" | "download">;
slack: Pick<SlackApi, "postMessage" | "fileInfo" | "download" | "uploadFile">;
/** Синтез речи; без него ответы всегда текстовые. */
tts?: Tts;
defaultVoice?: string;
drive?: DriveSync;
timezone: string;
now?: () => Date;
@@ -36,6 +44,8 @@ export interface ChatDeps {
export interface ChatResult {
reply: string | null;
published: boolean;
/** Аудиоответ отправлен. */
audioSent?: boolean;
attachments: { name: string; path: string; mimetype: string; size: number; link?: string }[];
}
@@ -164,7 +174,8 @@ export async function handleManagerMessages(
const replyRaw = out.sections.get("ответ менеджеру")!;
const reply = /^\(без ответа\)\.?$/i.test(replyRaw) ? null : replyRaw;
let published = false;
if (reply && channel && !deps.dryPublish) published = await deps.slack.postMessage(channel, reply);
let audioSent = false;
if (reply && channel && !deps.dryPublish) ({ published, audioSent } = await publishReply(deps, manager, channel, reply));
if (reply && opts.systemEvent) {
// напоминание ассистента по событию - в историю напоминаний (вход 7)
await ctx.pool.query(
@@ -176,5 +187,25 @@ export async function handleManagerMessages(
// 6. транскрипты и итоговые файлы -> Drive
if (deps.drive && attachments.length) await deps.drive.upload(mediaDir, sub).catch((e) => ctx.log.warn({ err: String(e) }, "повторная выгрузка в Drive не удалась"));
return { reply, published, attachments };
return { reply, published, audioSent, attachments };
}
/** Публикует ответ по настройке чата: текст / текст и аудио / только аудио. Любой сбой аудио - ответ уходит текстом, ИТ видит проблему в логе. */
export async function publishReply(deps: ChatDeps, manager: ManagerInfo, channel: string, reply: string): Promise<{ published: boolean; audioSent: boolean }> {
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;
const published = needText ? await deps.slack.postMessage(channel, reply) : false;
return { published: published || audioSent, audioSent };
}

View File

@@ -1,4 +1,5 @@
import type { Pool } from "khb_common";
import { isReplyMode } from "./tts.js";
import { handleManagerMessages, type ChatDeps, type IncomingMessage, type ManagerInfo } from "./chat.js";
interface Pending {
@@ -7,6 +8,17 @@ interface Pending {
timer: NodeJS.Timeout;
}
export function rowToManager(r: Record<string, unknown>): ManagerInfo {
return {
personId: String(r.person_id),
name: String(r.display_name),
slackUserId: (r.slack_user_id as string | null) ?? null,
slackChannelId: (r.slack_channel_id as string | null) ?? null,
replyMode: isReplyMode(r.reply_mode) ? r.reply_mode : "text",
ttsVoice: (r.tts_voice as string | null) ?? null,
};
}
const ACCEPTED_SUBTYPES = new Set([undefined, "file_share", "thread_broadcast"]);
/** Приём сообщений Slack: фильтр, журнал (защита от дублей), накопление сообщений менеджера (debounce) и запуск шага 4. */
@@ -27,13 +39,13 @@ export class SlackIntake {
async findManagerBySlackUser(slackUserId: string): Promise<ManagerInfo | null> {
const { rows } = await this.pool.query(
`select cm.person_id, p.display_name, cm.slack_user_id, cm.slack_channel_id
`select cm.person_id, p.display_name, cm.slack_user_id, cm.slack_channel_id, cm.reply_mode, cm.tts_voice
from construction_manager cm join person p on p.id = cm.person_id
where cm.slack_user_id = $1 and cm.is_active and p.is_active`,
[slackUserId],
);
const r = rows[0];
return r ? { personId: r.person_id, name: r.display_name, slackUserId: r.slack_user_id, slackChannelId: r.slack_channel_id } : null;
return r ? rowToManager(r) : null;
}
private chain: Promise<void> = Promise.resolve();
@@ -60,13 +72,13 @@ export class SlackIntake {
/** Менеджер чата (по slack_channel_id или единственный активный менеджер для каналов из настроек). */
async findManagerByChannel(channel: string): Promise<ManagerInfo | null> {
const { rows } = await this.pool.query(
`select cm.person_id, p.display_name, cm.slack_user_id, cm.slack_channel_id
`select cm.person_id, p.display_name, cm.slack_user_id, cm.slack_channel_id, cm.reply_mode, cm.tts_voice
from construction_manager cm join person p on p.id = cm.person_id
where cm.slack_channel_id = $1 and cm.is_active and p.is_active order by cm.person_id limit 1`,
[channel],
);
const r = rows[0];
return r ? { personId: r.person_id, name: r.display_name, slackUserId: r.slack_user_id, slackChannelId: r.slack_channel_id } : null;
return r ? rowToManager(r) : null;
}
/** Файл из папки приёма на Drive = сообщение менеджера в чате (текстовые файлы - текст сообщения). */

View File

@@ -0,0 +1,104 @@
/** Голоса Google Cloud Text-to-Speech Chirp 3 HD (англоязычные; полное имя - `en-US-Chirp3-HD-<голос>`). */
export const CHIRP3_VOICES = [
"Achernar", "Achird", "Algenib", "Algieba", "Alnilam", "Aoede", "Autonoe", "Callirrhoe", "Charon", "Despina",
"Enceladus", "Erinome", "Fenrir", "Gacrux", "Iapetus", "Kore", "Laomedeia", "Leda", "Orus", "Pulcherrima",
"Puck", "Rasalgethi", "Sadachbia", "Sadaltager", "Schedar", "Sulafat", "Umbriel", "Vindemiatrix", "Zephyr", "Zubenelgenubi",
] as const;
export type ReplyMode = "text" | "both" | "audio";
export function isReplyMode(v: unknown): v is ReplyMode {
return v === "text" || v === "both" || v === "audio";
}
/** Приводит имя голоса (`aoede`, `Aoede`, `en-US-Chirp3-HD-Aoede`) к короткому виду или возвращает null. */
export function normalizeVoice(v: string | null | undefined): string | null {
if (!v) return null;
const short = v.trim().replace(/^en-US-Chirp3-HD-/i, "");
return CHIRP3_VOICES.find((x) => x.toLowerCase() === short.toLowerCase()) ?? null;
}
/** Текст ответа для озвучивания: без Markdown, ссылок и эмодзи-оформления. */
export function speechText(md: string): string {
return md
.replace(/```[\s\S]*?```/g, " ")
.replace(/<(https?:[^|>]+)\|([^>]+)>/g, "$2") // ссылка Slack <url|текст>
.replace(/<https?:[^>]+>/g, " ")
.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
.replace(/https?:\/\/\S+/g, " ")
.replace(/[*_`~>#]+/g, "")
.replace(/^\s*[-•]\s+/gm, "")
.replace(/\p{Extended_Pictographic}/gu, "")
.replace(/[ \t]+/g, " ")
.replace(/\n{2,}/g, "\n")
.trim();
}
/** Делит текст на части до maxBytes (лимит API - 5000 байт на запрос) по границам предложений/строк. */
export function splitForTts(text: string, maxBytes = 4000): string[] {
const parts: string[] = [];
let cur = "";
const flush = () => {
if (cur.trim()) parts.push(cur.trim());
cur = "";
};
for (const piece of text.split(/(?<=[.!?\n])\s+/)) {
if (Buffer.byteLength(piece) > maxBytes) {
flush();
let rest = piece;
while (Buffer.byteLength(rest) > maxBytes) {
let cut = Math.min(rest.length, maxBytes);
while (Buffer.byteLength(rest.slice(0, cut)) > maxBytes) cut--;
const sp = rest.lastIndexOf(" ", cut);
cut = sp > cut / 2 ? sp : cut;
parts.push(rest.slice(0, cut).trim());
rest = rest.slice(cut);
}
cur = rest;
continue;
}
if (Buffer.byteLength(cur) + Buffer.byteLength(piece) + 1 > maxBytes) flush();
cur += (cur ? " " : "") + piece;
}
flush();
return parts;
}
export interface Tts {
/** Озвучивает текст голосом (короткое имя Chirp 3 HD); возвращает MP3. */
synthesize(text: string, voice: string): Promise<Buffer>;
}
export interface TtsConfig {
apiKey: string;
languageCode: string;
speakingRate?: number;
}
/** Google Cloud Text-to-Speech (REST, ключ API): `texttospeech.googleapis.com/v1/text:synthesize`. */
export function createGoogleTts(cfg: TtsConfig, fetchFn: typeof fetch = fetch): Tts {
return {
async synthesize(text, voice) {
const name = normalizeVoice(voice);
if (!name) throw new Error(`неизвестный голос Chirp 3 HD: ${voice}`);
const chunks = splitForTts(speechText(text));
if (!chunks.length) throw new Error("нечего озвучивать");
const out: Buffer[] = [];
for (const chunk of chunks) {
const res = await fetchFn(`https://texttospeech.googleapis.com/v1/text:synthesize?key=${encodeURIComponent(cfg.apiKey)}`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
input: { text: chunk },
voice: { languageCode: cfg.languageCode, name: `${cfg.languageCode}-Chirp3-HD-${name}` },
audioConfig: { audioEncoding: "MP3", ...(cfg.speakingRate ? { speakingRate: cfg.speakingRate } : {}) },
}),
});
const j = (await res.json()) as { audioContent?: string; error?: { message?: string } };
if (!res.ok || !j.audioContent) throw new Error(`Google TTS: ${j.error?.message ?? `HTTP ${res.status}`}`);
out.push(Buffer.from(j.audioContent, "base64"));
}
return Buffer.concat(out);
},
};
}

View File

@@ -0,0 +1,115 @@
import { describe, expect, it } from "vitest";
import { publishReply, type ChatDeps, type ManagerInfo } from "./slack/chat.js";
import { createSlackApi } from "./slack/api.js";
import { createGoogleTts, normalizeVoice, speechText, splitForTts } from "./slack/tts.js";
describe("синтез речи Chirp 3 HD", () => {
it("имена голосов нормализуются, неизвестные отвергаются", () => {
expect(normalizeVoice("aoede")).toBe("Aoede");
expect(normalizeVoice("en-US-Chirp3-HD-Puck")).toBe("Puck");
expect(normalizeVoice("Nobody")).toBeNull();
expect(normalizeVoice(null)).toBeNull();
});
it("из ответа убирается разметка Slack/Markdown", () => {
const t = speechText("*Done* ✅\n• item <https://x.io/a|link text> and `code`\n```\nblock\n```\nSee https://x.io now");
expect(t).not.toMatch(/[*`<>✅]|https?:/);
expect(t).toContain("Done");
expect(t).toContain("link text");
});
it("длинный текст делится на части до лимита байт", () => {
const text = Array.from({ length: 400 }, (_, i) => `Sentence number ${i}.`).join(" ");
const parts = splitForTts(text, 1000);
expect(parts.length).toBeGreaterThan(5);
for (const p of parts) expect(Buffer.byteLength(p)).toBeLessThanOrEqual(1000);
expect(parts.join(" ").replace(/\s+/g, " ")).toBe(text);
});
it("запрос к Google TTS: голос, язык, MP3; части склеиваются", async () => {
const reqs: { url: string; body: any }[] = [];
const fake = (async (url: string, init: { body: string }) => {
reqs.push({ url, body: JSON.parse(init.body) });
return { ok: true, status: 200, json: async () => ({ audioContent: Buffer.from(`mp3-${reqs.length}`).toString("base64") }) };
}) as unknown as typeof fetch;
const tts = createGoogleTts({ apiKey: "K", languageCode: "en-US" }, fake);
const out = await tts.synthesize("Hello there. " + "Long sentence here. ".repeat(300), "Kore");
expect(reqs.length).toBeGreaterThan(1);
expect(reqs[0]!.url).toContain("texttospeech.googleapis.com/v1/text:synthesize?key=K");
expect(reqs[0]!.body.voice).toEqual({ languageCode: "en-US", name: "en-US-Chirp3-HD-Kore" });
expect(reqs[0]!.body.audioConfig.audioEncoding).toBe("MP3");
expect(out.toString()).toMatch(/^mp3-1mp3-2/);
await expect(tts.synthesize("x", "Bogus")).rejects.toThrow(/неизвестный голос/);
});
it("ошибка API превращается в исключение с текстом Google", async () => {
const fake = (async () => ({ ok: false, status: 403, json: async () => ({ error: { message: "billing disabled" } }) })) as unknown as typeof fetch;
await expect(createGoogleTts({ apiKey: "K", languageCode: "en-US" }, fake).synthesize("Hi", "Aoede")).rejects.toThrow(/billing disabled/);
});
});
describe("режим ответов чата", () => {
const manager = (mode?: ManagerInfo["replyMode"], voice?: string): ManagerInfo => ({ personId: "m", name: "M", slackUserId: "U", slackChannelId: "C", replyMode: mode, ttsVoice: voice });
function setup(opts: { ttsFails?: boolean; noUpload?: boolean } = {}) {
const events: string[] = [];
const problems: string[] = [];
const deps = {
ctx: { pool: { query: async (_s: string, p: unknown[]) => void problems.push(String(p[1])) }, log: { warn: () => undefined } },
slack: {
postMessage: async (_c: string, t: string) => (events.push(`text:${t}`), true),
uploadFile: opts.noUpload ? undefined : async (_c: string, name: string) => void events.push(`audio:${name}`),
},
tts: { synthesize: async (_t: string, v: string) => (opts.ttsFails ? Promise.reject(new Error("billing disabled")) : (events.push(`voice:${v}`), Buffer.from("x"))) },
defaultVoice: "Aoede",
} as unknown as ChatDeps;
return { deps, events, problems };
}
it("по умолчанию - только текст, синтез не вызывается", async () => {
const s = setup();
expect(await publishReply(s.deps, manager(), "C", "Hi")).toEqual({ published: true, audioSent: false });
expect(s.events).toEqual(["text:Hi"]);
});
it("both - и аудио (голос чата), и текст", async () => {
const s = setup();
expect(await publishReply(s.deps, manager("both", "Puck"), "C", "Hi")).toEqual({ published: true, audioSent: true });
expect(s.events).toEqual(["voice:Puck", "audio:assistant-reply.mp3", "text:Hi"]);
});
it("audio - только аудио, голос по умолчанию из настроек", async () => {
const s = setup();
expect(await publishReply(s.deps, manager("audio"), "C", "Hi")).toEqual({ published: true, audioSent: true });
expect(s.events).toEqual(["voice:Aoede", "audio:assistant-reply.mp3"]);
});
it("сбой синтеза или загрузки: ответ уходит текстом, проблема пишется в лог", async () => {
for (const o of [{ ttsFails: true }, { noUpload: true }]) {
const s = setup(o);
const r = await publishReply(s.deps, manager("audio"), "C", "Hi");
expect(r.audioSent).toBe(false);
expect(s.events).toContain("text:Hi");
}
const s = setup({ ttsFails: true });
await publishReply(s.deps, manager("audio"), "C", "Hi");
expect(s.problems[0]).toMatch(/billing disabled/);
});
});
describe("загрузка аудио в Slack", () => {
it("трёхшаговая внешняя загрузка: адрес -> байты -> завершение с каналом", async () => {
const calls: string[] = [];
const fake = (async (url: string, init: { body?: unknown }) => {
calls.push(url.replace("https://slack.com/api/", ""));
if (url.endsWith("getUploadURLExternal")) return { ok: true, json: async () => ({ ok: true, upload_url: "https://up.slack/x", file_id: "F1" }) };
if (url === "https://up.slack/x") return { ok: true, status: 200 };
return { ok: true, json: async () => ({ ok: true, _body: JSON.parse(String(init.body)) }) };
}) as unknown as typeof fetch;
await createSlackApi("xoxb", fake).uploadFile!("C1", "a.mp3", Buffer.from("abc"), "Voice");
expect(calls).toEqual(["files.getUploadURLExternal", "https://up.slack/x", "files.completeUploadExternal"]);
});
it("отсутствие scope - исключение", async () => {
const fake = (async () => ({ ok: true, json: async () => ({ ok: false, error: "missing_scope" }) })) as unknown as typeof fetch;
await expect(createSlackApi("xoxb", fake).uploadFile!("C1", "a.mp3", Buffer.from("a"))).rejects.toThrow(/missing_scope/);
});
});