Записи еженедельных встреч с Drive: расшифровка whisper, итоги (Daily Log и todo) ассистенту Arthur на согласование
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
19
packages/khb_common/migrations/081_meeting_recording.sql
Normal file
19
packages/khb_common/migrations/081_meeting_recording.sql
Normal file
@@ -0,0 +1,19 @@
|
||||
-- Записи еженедельных встреч с Google Drive (khbuild_assistant_prep): что найдено, расшифровано и передано ассистенту Arthur на согласование итогов.
|
||||
create table if not exists meeting_recording (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
unit_key text not null unique,
|
||||
title text not null,
|
||||
folder_link text,
|
||||
recorded_on date,
|
||||
status text not null default 'new' check (status in ('new', 'transcribing', 'transcribed', 'delivered', 'skipped', 'failed')),
|
||||
duration_min numeric,
|
||||
transcript_path text,
|
||||
transcript_source text,
|
||||
attempts integer not null default 0,
|
||||
note text,
|
||||
error text,
|
||||
created_at timestamptz not null default now(),
|
||||
updated_at timestamptz not null default now(),
|
||||
delivered_at timestamptz
|
||||
);
|
||||
alter table meeting_recording enable row level security;
|
||||
@@ -22,6 +22,7 @@ import { summaryContextFor } from "./slack/daily-summary.js";
|
||||
import { runMissedAudit } from "./slack/audit.js";
|
||||
import { SlackIntake, rowToManager } from "./slack/intake.js";
|
||||
import { TodoEventPoller } from "./slack/todo-events.js";
|
||||
import { MeetingWatcher } from "./slack/meetings.js";
|
||||
import { createGoogleTts } from "./slack/tts.js";
|
||||
import { LimitsPoller, UsageLog } from "./usage.js";
|
||||
import { GmailSender } from "./mail/gmail.js";
|
||||
@@ -169,6 +170,19 @@ if (service.slack && chatDeps) {
|
||||
inbox.start(d.inboxScanSeconds * 1000);
|
||||
log.info({ everySeconds: d.inboxScanSeconds }, "опрос папок приёма Drive запущен");
|
||||
}
|
||||
// записи еженедельных встреч: расшифровка (whisper) и итоги на согласование ассистенту руководителя
|
||||
if (service.meetings && service.meetings.scanSeconds > 0 && driveClient) {
|
||||
const m = service.meetings;
|
||||
new MeetingWatcher(chatDeps, {
|
||||
drive: driveClient, folderId: m.folderId, workRoot: service.agent.workRoot, whisperModel: m.whisperModel, whisperModelDir: m.whisperModelDir,
|
||||
minMinutes: m.minMinutes, glossary: m.glossary, scanMs: m.scanSeconds * 1000, fromHour: service.slack.recapFromHour, toHour: service.slack.recapToHour,
|
||||
loadCeo: async () => {
|
||||
const { rows } = await pool.query("select person_id from construction_manager where chat_kind = 'ceo' and is_active order by person_id limit 1");
|
||||
return rows[0] ? intake.findManagerByPerson(String(rows[0].person_id)) : null;
|
||||
},
|
||||
}).start();
|
||||
log.info({ everySeconds: m.scanSeconds }, "разбор записей встреч запущен");
|
||||
}
|
||||
}
|
||||
|
||||
// Лимиты аккаунта агентов (проценты окон -> globals, предупреждение ИТ на 80% и 95%) и чистка старых записей учёта токенов (раз в сутки, храним 180 дней)
|
||||
|
||||
@@ -120,6 +120,21 @@ export const accountingSchema = z.object({
|
||||
tokenSecret: z.string().min(16),
|
||||
});
|
||||
|
||||
/** Записи еженедельных встреч на Google Drive: расшифровка и итоги на согласование ассистенту руководителя (chat_kind = ceo). */
|
||||
export const meetingsSchema = z.object({
|
||||
/** id папки с записями (Google Drive, «30. IT / Meeting recordings»); разбираются все подпапки. */
|
||||
folderId: z.string().min(1),
|
||||
/** Период опроса папки (секунды); 0 - отключено. */
|
||||
scanSeconds: z.number().default(300),
|
||||
/** Модель whisper (локально, пока нет платного распознавания речи). */
|
||||
whisperModel: z.string().default("small"),
|
||||
whisperModelDir: z.string().default("/opt/khb-whisper/models"),
|
||||
/** Записи короче (минуты) пропускаются: тестовые запуски Zoom. */
|
||||
minMinutes: z.number().default(3),
|
||||
/** Дополнительные слова для подсказки распознавания (подрядчики, поставщики). */
|
||||
glossary: z.array(z.string()).default([]),
|
||||
});
|
||||
|
||||
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),
|
||||
@@ -129,6 +144,7 @@ export const assistantPrepSchema = z.object({
|
||||
agent: agentSchema.default({}),
|
||||
slack: slackSchema.optional(),
|
||||
drive: driveSchema.optional(),
|
||||
meetings: meetingsSchema.optional(),
|
||||
tts: ttsSchema.optional(),
|
||||
mail: mailSchema.optional(),
|
||||
accounting: accountingSchema.optional(),
|
||||
|
||||
@@ -471,10 +471,14 @@ export async function publishReply(deps: ChatDeps, manager: ManagerInfo, channel
|
||||
let published = false;
|
||||
let replyTs: string | null = null;
|
||||
if (needText) {
|
||||
if (deps.slack.postMessageTs) {
|
||||
replyTs = await deps.slack.postMessageTs(channel, reply, threadTs);
|
||||
published = replyTs !== null;
|
||||
} else published = await deps.slack.postMessage(channel, reply, threadTs);
|
||||
// ответ из нескольких сообщений: агент разделяет их строкой «=== NEXT MESSAGE ===» (например, итоги встречи: сначала Daily Log, затем поручения)
|
||||
const parts = reply.split(/^[ \t]*=== NEXT MESSAGE ===[ \t]*$/m).map((p) => p.trim()).filter(Boolean);
|
||||
for (const part of parts.length ? parts : [reply]) {
|
||||
if (deps.slack.postMessageTs) {
|
||||
replyTs = await deps.slack.postMessageTs(channel, part, threadTs);
|
||||
published = published || replyTs !== null;
|
||||
} else published = (await deps.slack.postMessage(channel, part, threadTs)) || published;
|
||||
}
|
||||
}
|
||||
return { published: published || audioSent, audioSent, replyTs: replyTs || null };
|
||||
}
|
||||
|
||||
30
packages/khbuild_assistant_prep/src/slack/meetings.test.ts
Normal file
30
packages/khbuild_assistant_prep/src/slack/meetings.test.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { findMeetingUnits, meetingEvent, pickAudio, recordedOn, vttToText } from "./meetings.js";
|
||||
|
||||
const f = (name: string, id = name, mimeType = "application/octet-stream", modifiedTime = "2026-11-10T21:40:00Z") => ({ id, name, mimeType, modifiedTime });
|
||||
|
||||
describe("записи встреч", () => {
|
||||
it("находит папки с записями на любой глубине и пропускает служебные", async () => {
|
||||
const tree: Record<string, ReturnType<typeof f>[]> = {
|
||||
root: [f("Recorded Input", "ri", "application/vnd.google-apps.folder"), f("readme.pdf")],
|
||||
ri: [f("2026-11-10 13.27.55 Room", "m1", "application/vnd.google-apps.folder"), f("_processed", "p", "application/vnd.google-apps.folder"), f("2026", "y", "application/vnd.google-apps.folder")],
|
||||
m1: [f("audio1.m4a"), f("audio2.m4a"), f("video1.mp4"), f("recording.conf")],
|
||||
y: [f("zoom", "z", "application/vnd.google-apps.folder")],
|
||||
z: [f("1-shared_screen.mp4"), f("2-audio_transcript.vtt", "t", "text/vtt")],
|
||||
};
|
||||
const units = await findMeetingUnits({ children: async (id: string) => tree[id] ?? [] }, "root");
|
||||
expect(units.map((u) => u.key).sort()).toEqual(["m1", "z"]);
|
||||
expect(pickAudio(units.find((u) => u.key === "m1")!.media).map((x) => x.name)).toEqual(["audio1.m4a", "audio2.m4a"]);
|
||||
expect(pickAudio(units.find((u) => u.key === "z")!.media).map((x) => x.name)).toEqual(["1-shared_screen.mp4"]);
|
||||
});
|
||||
|
||||
it("разбирает дату, vtt и подставляет значения в событие", () => {
|
||||
expect(recordedOn("2026-11-10 13.27.55 Artur Atanoff's Personal Meeting Room", 0)).toBe("2026-11-10");
|
||||
expect(recordedOn("Weekly", Date.parse("2026-12-01T10:00:00Z"))).toBe("2026-12-01");
|
||||
expect(vttToText("WEBVTT\n\n1\n00:00:01.000 --> 00:00:03.000\nHello there\n\n2\n00:00:04.000 --> 00:00:05.000\nNext")).toBe("Hello there\nNext");
|
||||
const t = meetingEvent({ title: "Weekly", date: "2026-11-10", minutes: "45", path: "/w/transcript.txt", source: "whisper", link: "https://x", projects: "408 161st - Greg" }, "proposed");
|
||||
expect(t).toContain("/w/transcript.txt");
|
||||
expect(t).toContain("=== NEXT MESSAGE ===");
|
||||
expect(t).not.toContain("{{");
|
||||
});
|
||||
});
|
||||
295
packages/khbuild_assistant_prep/src/slack/meetings.ts
Normal file
295
packages/khbuild_assistant_prep/src/slack/meetings.ts
Normal file
@@ -0,0 +1,295 @@
|
||||
/**
|
||||
* Записи еженедельных встреч на Google Drive (папка «30. IT / Meeting recordings», любые подпапки и даты).
|
||||
* Новая запись -> расшифровка (готовая .vtt Zoom, иначе локальный whisper) -> событие ассистенту Arthur (chat_kind = ceo):
|
||||
* он присылает черновики Daily Log по проектам и список поручений, Arthur подтверждает или правит в диалоге, запись делает агент.
|
||||
* Состояние - таблица meeting_recording; вне окна 7:00-19:00 по Тампе и при pause_mode = off события не отправляются.
|
||||
*/
|
||||
|
||||
import { spawn } from "node:child_process";
|
||||
import { copyFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { loadFragment, type PromptSide } from "../agents/prompts.js";
|
||||
import { managerWorkDir, promptSideFor } from "../agents/session.js";
|
||||
import { FOLDER_MIME, type DriveClient, type DriveFile } from "../gdrive/client.js";
|
||||
import { pauseState } from "../pause.js";
|
||||
import { handleManagerMessages, type ChatDeps, type ManagerInfo } from "./chat.js";
|
||||
import { recapDelayMs } from "./recap.js";
|
||||
|
||||
const MEDIA = /\.(m4a|mp3|wav|aac|ogg|mp4|mov|webm)$/i;
|
||||
const AUDIO = /\.(m4a|mp3|wav|aac|ogg)$/i;
|
||||
const MAX_DEPTH = 6;
|
||||
/** Файлы новее этого возраста ещё догружаются (Zoom заливает части записи по очереди) - запись не трогаем. */
|
||||
const SETTLE_MS = 10 * 60_000;
|
||||
/** Расшифровка встречи длиннее часа с запасом: whisper small на 4 ядрах считает около трети длины записи. */
|
||||
const WHISPER_TIMEOUT_MS = 3 * 3600_000;
|
||||
|
||||
export interface MeetingUnit {
|
||||
/** Устойчивый ключ записи: id папки (или id файла, если запись лежит без папки). */
|
||||
key: string;
|
||||
folderId: string;
|
||||
title: string;
|
||||
media: DriveFile[];
|
||||
transcripts: DriveFile[];
|
||||
newestModified: number;
|
||||
oldestModified: number;
|
||||
}
|
||||
|
||||
const isTranscript = (f: DriveFile): boolean => /transcript/i.test(f.name) && (/\.vtt$/i.test(f.name) || f.mimeType === "text/vtt");
|
||||
|
||||
/** Расшифровка Zoom (.vtt) -> текст без служебных строк и временных меток. */
|
||||
export function vttToText(vtt: string): string {
|
||||
return vtt
|
||||
.replace(/\r/g, "")
|
||||
.split("\n")
|
||||
.filter((l) => l.trim() && l.trim() !== "WEBVTT" && !/^\d+$/.test(l.trim()) && !/-->/.test(l))
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
/** Записи в папке: любая папка, где лежит аудио/видео (или готовая расшифровка), - отдельная встреча. */
|
||||
export async function findMeetingUnits(client: Pick<DriveClient, "children">, rootId: string): Promise<MeetingUnit[]> {
|
||||
const out: MeetingUnit[] = [];
|
||||
const walk = async (folderId: string, title: string, depth: number): Promise<void> => {
|
||||
const list = await client.children(folderId);
|
||||
const media = list.filter((f) => f.mimeType !== FOLDER_MIME && MEDIA.test(f.name) && !f.name.startsWith("_"));
|
||||
const transcripts = list.filter(isTranscript);
|
||||
if (media.length || transcripts.length) {
|
||||
const times = [...media, ...transcripts].map((f) => Date.parse(f.modifiedTime ?? "") || 0);
|
||||
out.push({ key: folderId, folderId, title, media, transcripts, newestModified: Math.max(...times), oldestModified: Math.min(...times) });
|
||||
}
|
||||
if (depth >= MAX_DEPTH) return;
|
||||
for (const d of list.filter((f) => f.mimeType === FOLDER_MIME && !f.name.startsWith("_"))) await walk(d.id, d.name, depth + 1);
|
||||
};
|
||||
await walk(rootId, "root", 0);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Файлы для расшифровки: отдельные аудиодорожки, иначе видео; по имени (части одной записи идут по порядку). */
|
||||
export function pickAudio(media: DriveFile[]): DriveFile[] {
|
||||
const audio = media.filter((f) => AUDIO.test(f.name));
|
||||
return [...(audio.length ? audio : media)].sort((a, b) => a.name.localeCompare(b.name, "en", { numeric: true }));
|
||||
}
|
||||
|
||||
/** Дата встречи: из названия папки (2026-11-10 ...), иначе дата самого раннего файла. */
|
||||
export function recordedOn(title: string, oldestModified: number): string {
|
||||
const m = /(\d{4})-(\d{2})-(\d{2})/.exec(title);
|
||||
return m ? `${m[1]}-${m[2]}-${m[3]}` : new Date(oldestModified || Date.now()).toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
function run(cmd: string, args: string[], timeoutMs: number): Promise<{ code: number; out: string }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const p = spawn("nice", ["-n", "10", cmd, ...args], { stdio: ["ignore", "pipe", "pipe"] });
|
||||
let out = "";
|
||||
p.stdout.on("data", (d) => (out += String(d)));
|
||||
p.stderr.on("data", (d) => (out += String(d)));
|
||||
const t = setTimeout(() => p.kill("SIGKILL"), timeoutMs);
|
||||
p.on("error", (e) => (clearTimeout(t), reject(e)));
|
||||
p.on("close", (code) => (clearTimeout(t), resolve({ code: code ?? -1, out: out.slice(-2000) })));
|
||||
});
|
||||
}
|
||||
|
||||
export interface MeetingOpts {
|
||||
drive: Pick<DriveClient, "children" | "downloadTo" | "downloadText">;
|
||||
folderId: string;
|
||||
workRoot: string;
|
||||
whisperModel: string;
|
||||
whisperModelDir: string;
|
||||
minMinutes: number;
|
||||
glossary: string[];
|
||||
scanMs: number;
|
||||
fromHour: number;
|
||||
toHour: number;
|
||||
/** Ассистент руководителя (chat_kind = ceo): кому уходят итоги на согласование. */
|
||||
loadCeo: () => Promise<ManagerInfo | null>;
|
||||
/** Тест: подмена запуска внешних команд (ffprobe/ffmpeg/whisper). */
|
||||
exec?: typeof run;
|
||||
}
|
||||
|
||||
export class MeetingWatcher {
|
||||
private timer: NodeJS.Timeout | null = null;
|
||||
private running = false;
|
||||
|
||||
constructor(private deps: ChatDeps, private o: MeetingOpts) {}
|
||||
|
||||
start(): void {
|
||||
if (!this.o.scanMs || this.timer) return;
|
||||
this.timer = setInterval(() => void this.tick().catch((e) => this.deps.ctx.log.error({ err: String(e) }, "разбор записей встреч не удался")), this.o.scanMs);
|
||||
void this.tick().catch((e) => this.deps.ctx.log.error({ err: String(e) }, "разбор записей встреч не удался"));
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if (this.timer) clearInterval(this.timer);
|
||||
this.timer = null;
|
||||
}
|
||||
|
||||
/** Один проход: найти новые записи, расшифровать одну, передать готовые. Возвращает краткий отчёт (для тестов и ручного запуска). */
|
||||
async tick(): Promise<{ found: number; transcribed: number; delivered: number }> {
|
||||
if (this.running) return { found: 0, transcribed: 0, delivered: 0 };
|
||||
this.running = true;
|
||||
const { pool } = this.deps.ctx;
|
||||
const res = { found: 0, transcribed: 0, delivered: 0 };
|
||||
try {
|
||||
const now = Date.now();
|
||||
const units = await findMeetingUnits(this.o.drive, this.o.folderId);
|
||||
for (const u of units) {
|
||||
const ins = await pool.query(
|
||||
"insert into meeting_recording (unit_key, title, folder_link, recorded_on) values ($1,$2,$3,$4) on conflict (unit_key) do nothing returning id",
|
||||
[u.key, u.title, `https://drive.google.com/drive/folders/${u.folderId}`, recordedOn(u.title, u.oldestModified)],
|
||||
);
|
||||
if (ins.rowCount) res.found++;
|
||||
}
|
||||
// расшифровка: одна запись за проход (долгая и нагружает процессор); только устоявшиеся файлы
|
||||
const byKey = new Map(units.map((u) => [u.key, u]));
|
||||
const { rows: fresh } = await pool.query("select id, unit_key from meeting_recording where status = 'new' order by recorded_on, created_at");
|
||||
for (const r of fresh) {
|
||||
const u = byKey.get(String(r.unit_key));
|
||||
if (!u || now - u.newestModified < SETTLE_MS) continue;
|
||||
await this.transcribe(String(r.id), u);
|
||||
res.transcribed++;
|
||||
break;
|
||||
}
|
||||
res.delivered = await this.deliver();
|
||||
} finally {
|
||||
this.running = false;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
private async setStatus(id: string, status: string, extra: { note?: string; error?: string | null; durationMin?: number; transcriptPath?: string; source?: string } = {}): Promise<void> {
|
||||
await this.deps.ctx.pool.query(
|
||||
`update meeting_recording set status = $2, note = coalesce($3, note), error = $4, duration_min = coalesce($5, duration_min), transcript_path = coalesce($6, transcript_path), transcript_source = coalesce($7, transcript_source), updated_at = now() where id = $1`,
|
||||
[id, status, extra.note ?? null, extra.error ?? null, extra.durationMin ?? null, extra.transcriptPath ?? null, extra.source ?? null],
|
||||
);
|
||||
}
|
||||
|
||||
private async glossaryPrompt(): Promise<string> {
|
||||
const { rows } = await this.deps.ctx.pool.query(
|
||||
`select distinct j.name, p.display_name from assistant_project ap join jt_job j on j.id = ap.jt_job_id join person p on p.id = ap.manager_person_id where ap.is_enabled and j.name !~* '^test'`,
|
||||
);
|
||||
const projects = rows.map((r) => String(r.name).replace(/^\s*\d+\.\s*/, "").trim());
|
||||
const people = [...new Set(rows.flatMap((r) => String(r.display_name).split(/\s+/)))];
|
||||
const text = `Weekly construction meeting. People: Arthur, ${people.join(", ")}. Projects: ${projects.join(", ")}. ${this.o.glossary.join(", ")}.`;
|
||||
return text.slice(0, 900);
|
||||
}
|
||||
|
||||
private async transcribe(id: string, u: MeetingUnit): Promise<void> {
|
||||
const exec = this.o.exec ?? run;
|
||||
await this.setStatus(id, "transcribing");
|
||||
const dir = join(this.o.workRoot, "_meetings", id);
|
||||
mkdirSync(dir, { recursive: true });
|
||||
try {
|
||||
let text = "";
|
||||
let source = "whisper";
|
||||
let minutes = 0;
|
||||
const vtt = u.transcripts.find((f) => /\.vtt$/i.test(f.name) || f.mimeType === "text/vtt");
|
||||
if (vtt) {
|
||||
const t = vttToText(await this.o.drive.downloadText(vtt.id));
|
||||
if (t.length >= 2000) {
|
||||
text = t;
|
||||
source = "zoom-vtt";
|
||||
minutes = Math.round(t.split(/\s+/).length / 130);
|
||||
}
|
||||
}
|
||||
if (!text) {
|
||||
const files = pickAudio(u.media);
|
||||
if (!files.length) {
|
||||
await this.setStatus(id, "skipped", { note: "нет аудио и расшифровки достаточной длины" });
|
||||
return;
|
||||
}
|
||||
const parts: string[] = [];
|
||||
let seconds = 0;
|
||||
const prompt = await this.glossaryPrompt();
|
||||
let n = 0;
|
||||
for (const f of files) {
|
||||
n++;
|
||||
const src = join(dir, `part${n}_${f.id.slice(0, 6)}${f.name.match(/\.[^.]+$/)?.[0] ?? ""}`);
|
||||
await this.o.drive.downloadTo(f.id, src);
|
||||
const probe = await exec("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", src], 60_000);
|
||||
seconds += Number.parseFloat(probe.out) || 0;
|
||||
const wav = join(dir, `part${n}.wav`);
|
||||
const ff = await exec("ffmpeg", ["-y", "-i", src, "-vn", "-ac", "1", "-ar", "16000", wav], 600_000);
|
||||
if (ff.code !== 0) throw new Error(`ffmpeg: ${ff.out.slice(-300)}`);
|
||||
if (seconds < 60 * this.o.minMinutes && n === files.length) break; // короткая запись - не расшифровываем
|
||||
const w = await exec(
|
||||
"whisper-ctranslate2",
|
||||
["--model", this.o.whisperModel, "--model_dir", this.o.whisperModelDir, "--language", "en", "--vad_filter", "True", "--beam_size", "1", "--initial_prompt", prompt, "--output_format", "txt", "--output_dir", dir, wav],
|
||||
WHISPER_TIMEOUT_MS,
|
||||
);
|
||||
if (w.code !== 0) throw new Error(`whisper: ${w.out.slice(-300)}`);
|
||||
parts.push(readFileSync(join(dir, `part${n}.txt`), "utf8").trim());
|
||||
}
|
||||
minutes = Math.round(seconds / 60);
|
||||
if (seconds < 60 * this.o.minMinutes) {
|
||||
await this.setStatus(id, "skipped", { note: `запись короче ${this.o.minMinutes} мин (${minutes} мин)`, durationMin: minutes });
|
||||
return;
|
||||
}
|
||||
text = parts.map((p, i) => (parts.length > 1 ? `--- part ${i + 1} of ${parts.length} ---\n${p}` : p)).join("\n\n");
|
||||
}
|
||||
const path = join(dir, "transcript.txt");
|
||||
writeFileSync(path, text, "utf8");
|
||||
await this.setStatus(id, "transcribed", { transcriptPath: path, durationMin: minutes, source });
|
||||
} catch (e) {
|
||||
const { rows } = await this.deps.ctx.pool.query("update meeting_recording set attempts = attempts + 1 where id = $1 returning attempts", [id]);
|
||||
const attempts = Number(rows[0]?.attempts ?? 1);
|
||||
await this.setStatus(id, attempts >= 3 ? "failed" : "new", { error: String(e).slice(0, 500) });
|
||||
if (attempts >= 3) await this.deps.ctx.notifyIt(`:warning: khbuild_assistant_prep: запись встречи «${u.title}» не расшифрована (${attempts} попытки): ${String(e).slice(0, 300)}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Передаёт расшифрованные встречи ассистенту Arthur (по одной, самая ранняя первой). */
|
||||
private async deliver(): Promise<number> {
|
||||
const { ctx } = this.deps;
|
||||
const now = (this.deps.now ?? (() => new Date()))();
|
||||
if (recapDelayMs(now, this.deps.timezone, this.o.fromHour, this.o.toHour) > 0) return 0;
|
||||
const { rows } = await ctx.pool.query("select id, title, folder_link, recorded_on, duration_min, transcript_path, transcript_source from meeting_recording where status = 'transcribed' order by recorded_on, created_at limit 1");
|
||||
const r = rows[0];
|
||||
if (!r) return 0;
|
||||
const ceo = await this.o.loadCeo();
|
||||
if (!ceo) return 0;
|
||||
const st = await pauseState(ctx.pool, ceo.personId, now);
|
||||
if (st.paused && st.mode === "off") return 0; // passive допустим: Arthur сам просил разбирать встречи
|
||||
const id = String(r.id);
|
||||
const dest = join(managerWorkDir(ctx.settings, ceo.personId), "meetings", id);
|
||||
mkdirSync(dest, { recursive: true });
|
||||
const local = join(dest, "transcript.txt");
|
||||
copyFileSync(String(r.transcript_path), local);
|
||||
const date = String(r.recorded_on instanceof Date ? r.recorded_on.toISOString().slice(0, 10) : r.recorded_on).slice(0, 10);
|
||||
const projects = await ctx.pool.query(
|
||||
`select distinct j.name, p.display_name from assistant_project ap join jt_job j on j.id = ap.jt_job_id join person p on p.id = ap.manager_person_id where ap.is_enabled and j.name !~* '^test' order by j.name`,
|
||||
);
|
||||
const systemEvent = meetingEvent(
|
||||
{ title: String(r.title), date, minutes: String(r.duration_min ?? "?"), path: local, source: String(r.transcript_source ?? ""), link: String(r.folder_link ?? ""), projects: projects.rows.map((p) => `${p.name} - ${p.display_name}`).join("\n") },
|
||||
promptSideFor(ctx, ceo.personId),
|
||||
);
|
||||
try {
|
||||
await handleManagerMessages(this.deps, ceo, [], { systemEvent });
|
||||
await this.setStatus(id, "delivered");
|
||||
await ctx.pool.query("update meeting_recording set delivered_at = now() where id = $1", [id]);
|
||||
return 1;
|
||||
} catch (e) {
|
||||
const { rows: a } = await ctx.pool.query("update meeting_recording set attempts = attempts + 1 where id = $1 returning attempts", [id]);
|
||||
await this.setStatus(id, Number(a[0]?.attempts ?? 1) >= 3 ? "failed" : "transcribed", { error: String(e).slice(0, 500) });
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export interface MeetingEventVars {
|
||||
title: string;
|
||||
date: string;
|
||||
minutes: string;
|
||||
path: string;
|
||||
source: string;
|
||||
link: string;
|
||||
projects: string;
|
||||
}
|
||||
|
||||
/** Текст системного события «разбор встречи» (фрагмент p-meeting-review.md; до согласования промтов берётся из proposed). */
|
||||
export function meetingEvent(v: MeetingEventVars, side: PromptSide): string {
|
||||
const vars = { title: v.title, date: v.date, minutes: v.minutes, transcript_path: v.path, transcript_source: v.source, folder_link: v.link, projects: v.projects };
|
||||
try {
|
||||
return loadFragment("p-meeting-review.md", "Разбор встречи", vars, side);
|
||||
} catch (e) {
|
||||
if (side === "proposed") throw e;
|
||||
return loadFragment("p-meeting-review.md", "Разбор встречи", vars, "proposed");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user