Проектные каналы: тихий режим, recap для Daily Log; Huddle через message_changed; короткие напоминания
All checks were successful
ci / test (push) Successful in 27s
ci / deploy (push) Successful in 2m13s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-22 21:12:07 +03:00
parent 12147fc3eb
commit 4a32a08b6d
18 changed files with 613 additions and 32 deletions

View File

@@ -9,12 +9,30 @@ export interface SlackFile {
urlPrivateDownload: string;
}
/** Сообщение из истории канала (для контекста агента проектного канала). */
export interface SlackHistoryMessage {
ts: string;
userId: string | null;
botId: string | null;
text: string;
threadTs: string | null;
fileNames: string[];
}
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>;
/** История канала с момента oldest (unix-секунды) по возрастанию времени, вместе с ответами в тредах. */
history?(channel: string, oldest: number): Promise<SlackHistoryMessage[]>;
/** Отображаемое имя пользователя Slack (кэшируется); null - не удалось узнать. */
userName?(userId: string): Promise<string | null>;
/** Ставит эмодзи-реакцию на сообщение (нужен scope reactions:write); ошибка already_reacted не считается сбоем. */
addReaction?(channel: string, ts: string, emoji: string): Promise<boolean>;
/** Slack id самого бота (чтобы пометить его сообщения в истории). */
botUserId?(): Promise<string | null>;
/** Загружает файл в канал (нужен scope files:write). */
uploadFile?(channel: string, filename: string, data: Buffer, title?: string): Promise<void>;
}
@@ -34,8 +52,55 @@ export function createSlackApi(botToken: string, fetchFn: typeof fetch = fetch):
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;
};
const get = async (method: string, params: Record<string, string>) => {
const res = await fetchFn(`https://slack.com/api/${method}?${new URLSearchParams(params)}`, { headers: { authorization: `Bearer ${botToken}` } });
return (await res.json()) as { ok?: boolean; error?: string; messages?: Record<string, unknown>[]; user?: Record<string, unknown>; user_id?: string; response_metadata?: { next_cursor?: string } };
};
const toMsg = (m: Record<string, unknown>): SlackHistoryMessage => ({
ts: String(m.ts),
userId: typeof m.user === "string" ? m.user : null,
botId: typeof m.bot_id === "string" ? m.bot_id : null,
text: String(m.text ?? ""),
threadTs: typeof m.thread_ts === "string" ? m.thread_ts : null,
fileNames: ((m.files as { name?: string }[] | undefined) ?? []).map((f) => String(f.name ?? "file")),
});
const names = new Map<string, string | null>();
let botId: string | null | undefined;
return {
postMessageTs: postTs,
async history(channel, oldest) {
const out = new Map<string, SlackHistoryMessage>();
let cursor = "";
for (let page = 0; page < 10; page++) {
const r = await get("conversations.history", { channel, oldest: String(oldest), limit: "200", ...(cursor ? { cursor } : {}) });
if (!r.ok) throw new Error(`Slack conversations.history: ${r.error}`);
for (const m of r.messages ?? []) out.set(String(m.ts), toMsg(m));
cursor = r.response_metadata?.next_cursor ?? "";
if (!cursor) break;
}
// ответы в тредах (в history только родители)
for (const m of [...out.values()].filter((x) => x.threadTs === x.ts).slice(0, 20)) {
const r = await get("conversations.replies", { channel, ts: m.ts, oldest: String(oldest), limit: "100" });
if (r.ok) for (const x of r.messages ?? []) out.set(String(x.ts), toMsg(x));
}
return [...out.values()].sort((a, b) => Number(a.ts) - Number(b.ts));
},
async userName(userId) {
if (names.has(userId)) return names.get(userId)!;
const r = await get("users.info", { user: userId });
const u = r.user as { real_name?: string; name?: string; profile?: { display_name?: string; real_name?: string } } | undefined;
const n = r.ok && u ? u.profile?.display_name || u.real_name || u.profile?.real_name || u.name || null : null;
names.set(userId, n);
return n;
},
async addReaction(channel, ts, emoji) {
const r = await call("reactions.add", { channel, timestamp: ts, name: emoji.replace(/:/g, "") });
return r.ok === true || r.error === "already_reacted";
},
async botUserId() {
if (botId === undefined) botId = (await get("auth.test", {})).user_id ?? null;
return botId;
},
async postMessage(channel, text, threadTs) {
return (await postTs(channel, text, threadTs)) !== null;
},

View File

@@ -6,6 +6,7 @@ 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";
@@ -46,7 +47,7 @@ export interface IncomingMessage {
export interface ChatDeps {
ctx: AgentContext;
slack: Pick<SlackApi, "postMessage" | "postMessageTs" | "fileInfo" | "download" | "uploadFile">;
slack: Pick<SlackApi, "postMessage" | "postMessageTs" | "fileInfo" | "download" | "uploadFile" | "history" | "userName" | "botUserId" | "addReaction">;
/** Синтез речи; без него ответы всегда текстовые. */
tts?: Tts;
defaultVoice?: string;
@@ -87,7 +88,7 @@ export async function handleManagerMessages(
deps: ChatDeps,
manager: ManagerInfo,
messages: IncomingMessage[],
opts: { systemEvent?: string } = {},
opts: { systemEvent?: string; project?: ProjectContext; channel?: string } = {},
): Promise<ChatResult> {
const { ctx } = deps;
const t0 = Date.now();
@@ -100,7 +101,7 @@ export async function handleManagerMessages(
};
const now = (deps.now ?? (() => new Date()))();
const today = localDate(now, deps.timezone);
const channel = messages[0]?.channel ?? manager.slackChannelId;
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 });
@@ -192,7 +193,7 @@ export async function handleManagerMessages(
const attBlock = attachments.length
? attachments.map((a) => `- ${a.path} (${a.mimetype || "?"}, ${a.size} байт)${a.link ? ` | Drive: ${a.link}` : ""}`).join("\n")
: "(вложений нет)";
const proj = messages.find((m) => m.project)?.project;
const proj = opts.project ?? messages.find((m) => m.project)?.project;
// Новая версия (долгоживущий агент) читает промты из proposed, прежняя (остальные менеджеры) - из approved
const live = useLive(ctx, manager.personId);
const side: PromptSide = live ? "proposed" : "approved";
@@ -261,6 +262,16 @@ export async function handleManagerMessages(
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", "Продолжение диалога")}`]
@@ -270,6 +281,7 @@ export async function handleManagerMessages(
...freqBlocks,
...(opts.systemEvent ? ["", `# Системное событие\n${opts.systemEvent}`] : []),
...projectBlock,
...channelBlocks,
...(dialog
? []
: isCeo
@@ -309,6 +321,11 @@ export async function handleManagerMessages(
// 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;

View File

@@ -3,6 +3,7 @@ import { isReplyMode } from "./tts.js";
import { loadFragment } from "../agents/prompts.js";
import { pauseState } from "../pause.js";
import { promptSideFor } from "../agents/session.js";
import { getRecapState, recapDelayMs } from "./recap.js";
import { handleManagerMessages, type ChatDeps, type IncomingMessage, type ManagerInfo, type ProjectContext } from "./chat.js";
interface Pending {
@@ -25,16 +26,32 @@ export function rowToManager(r: Record<string, unknown>): ManagerInfo {
const ACCEPTED_SUBTYPES = new Set([undefined, "file_share", "thread_broadcast"]);
type SlackFileRef = { id?: string; name?: string; mimetype?: string; filetype?: string };
const huddleFilesOf = (ev: Record<string, unknown>): SlackFileRef[] =>
((ev.files as SlackFileRef[] | undefined) ?? []).filter((f) => /huddle|vnd\.slack-docs/i.test(`${f.name ?? ""} ${f.mimetype ?? ""} ${f.filetype ?? ""}`));
/**
* Заметки Huddle Slack прикрепляет к родительскому сообщению (subtype huddle_thread) правкой - приходит message_changed.
* Правка с файлами заметок превращается в обычное сообщение того же ts (дубли отсекает журнал); прочие правки не обрабатываются.
*/
export function normalizeHuddleEvent(ev: Record<string, unknown>): Record<string, unknown> | null {
if (ev.subtype !== "message_changed") return ev;
const inner = ev.message as Record<string, unknown> | undefined;
if (!inner || !huddleFilesOf(inner).length) return null;
return { ...inner, type: "message", channel: ev.channel };
}
/** Приём сообщений Slack: фильтр, журнал (защита от дублей), накопление сообщений менеджера (debounce) и запуск шага 4. */
export class SlackIntake {
private pending = new Map<string, Pending>();
private inflight = new Set<Promise<void>>();
private followups = new Map<string, NodeJS.Timeout>();
private recapTimers = new Map<string, NodeJS.Timeout>();
constructor(
private deps: ChatDeps,
private opts: { channelIds: string[]; debounceMs: number; followupMs?: number },
private opts: { channelIds: string[]; debounceMs: number; followupMs?: number; recapSilenceMs?: number; recapFromHour?: number; recapToHour?: number },
) {}
private get pool(): Pool {
@@ -62,19 +79,26 @@ export class SlackIntake {
private async handle(ev: Record<string, unknown>): Promise<void> {
if (ev.type !== "message") return;
const norm = normalizeHuddleEvent(ev);
if (!norm) return;
ev = norm;
const channel = String(ev.channel ?? "");
const user = String(ev.user ?? "");
const ts = String(ev.ts ?? "");
if (!channel || !ts) return;
const project = await this.findProjectByChannel(channel);
if (project) return this.handleProjectEvent(ev, project);
if (ev.bot_id || !user || !ACCEPTED_SUBTYPES.has(ev.subtype as string | undefined)) return;
const huddle = ev.subtype === "huddle_thread" || huddleFilesOf(ev).length > 0;
if (huddle) {
// заметки Huddle от Slackbot: принимаются только с вложениями; "AI huddle notes are ready" без файлов и прочие сообщения Slackbot - нет
if (!((ev.files as unknown[] | undefined)?.length)) return;
} else if (ev.bot_id || !user || user === "USLACKBOT" || !ACCEPTED_SUBTYPES.has(ev.subtype as string | undefined)) return;
// чат менеджера: пишет любой участник канала, обрабатывается как сообщение менеджера (отправитель сохраняется в журнале)
let manager = await this.findManagerByChannel(channel);
if (!manager && this.opts.channelIds.includes(channel)) manager = await this.findManagerBySlackUser(user);
if (!manager && this.opts.channelIds.includes(channel) && user) manager = await this.findManagerBySlackUser(user);
if (!manager) return;
const files = ((ev.files as { id?: string }[] | undefined) ?? []).map((f) => String(f.id)).filter(Boolean);
await this.accept(manager, { channel, ts, text: String(ev.text ?? ""), fileIds: files, senderUserId: user });
await this.accept(manager, { channel, ts, text: (huddle ? "[Slack huddle: заметки и расшифровка во вложениях] " : "") + String(ev.text ?? ""), fileIds: files, senderUserId: user || undefined });
}
/** Проектный канал: проект определяется каналом (таблица project_channel). */
@@ -97,7 +121,7 @@ export class SlackIntake {
const rawFiles = (ev.files as { id?: string; name?: string; mimetype?: string; filetype?: string }[] | undefined) ?? [];
const huddleFiles = rawFiles.filter((f) => /huddle|vnd\.slack-docs/i.test(`${f.name ?? ""} ${f.mimetype ?? ""} ${f.filetype ?? ""}`));
const isHuddle = ev.subtype === "huddle_thread" || huddleFiles.length > 0;
if (ev.bot_id && !isHuddle) return; // собственные ответы и прочие боты
if ((ev.bot_id || user === "USLACKBOT") && !isHuddle) return; // собственные ответы, прочие боты и служебные сообщения Slackbot ("AI huddle notes are ready")
if (!isHuddle && !ACCEPTED_SUBTYPES.has(ev.subtype as string | undefined)) return;
if (isHuddle && !rawFiles.length) return; // "A huddle started" без материалов
const sender = user ? (await this.pool.query("select id, display_name from person where slack_user_id = $1 and is_active", [user])).rows[0] : undefined;
@@ -115,7 +139,57 @@ export class SlackIntake {
const manager = (await this.findManagerByPerson(String(owner.id))) ?? { personId: String(owner.id), name: String(owner.display_name), slackUserId: null, slackChannelId: channel };
const ctx: ProjectContext = { jobId: project.jobId, jobName: project.jobName, channel, senderName: (sender?.display_name as string | undefined) ?? null, isHuddle };
const text = (isHuddle ? "[Slack huddle: заметки и расшифровка во вложениях] " : "") + String(ev.text ?? "");
await this.accept({ ...manager, slackChannelId: channel }, { channel, ts, text, fileIds: rawFiles.map((f) => String(f.id)).filter(Boolean), senderUserId: user || undefined, project: ctx });
const accepted = await this.accept({ ...manager, slackChannelId: channel }, { channel, ts, text, fileIds: rawFiles.map((f) => String(f.id)).filter(Boolean), senderUserId: user || undefined, project: ctx });
if (accepted) this.scheduleRecap(channel, { ...manager, slackChannelId: channel }, ctx);
}
/** Проектный канал: через recapSilenceMinutes после последнего сообщения людей агент решает, спрашивать ли про Daily Log. */
scheduleRecap(channel: string, manager: ManagerInfo, ctx: ProjectContext, delayMs?: number): void {
const silence = this.opts.recapSilenceMs;
if (!silence) return;
clearTimeout(this.recapTimers.get(channel));
const t = setTimeout(() => {
this.recapTimers.delete(channel);
this.track(this.runRecap(channel, manager, ctx).catch((e) => this.deps.ctx.log.error({ channel, err: String(e) }, "recap проектного канала не удался")));
}, delayMs ?? silence);
this.recapTimers.set(channel, t);
}
private async runRecap(channel: string, manager: ManagerInfo, ctx: ProjectContext): Promise<void> {
const now = (this.deps.now ?? (() => new Date()))();
const st = await getRecapState(this.pool, channel);
if (!st || st.status === "asked" || !st.notes.trim()) return;
if (promptSideFor(this.deps.ctx, manager.personId) !== "proposed") return; // recap - только у новой версии агента
if (now.getTime() - st.lastHumanAt.getTime() > 36 * 3600_000) {
await this.pool.query("delete from channel_recap_state where channel_id = $1", [channel]); // устарело: молча сбрасываем, не тревожим людей
return;
}
if ((await pauseState(this.pool, manager.personId)).paused) return;
const wait = recapDelayMs(now, this.deps.timezone, this.opts.recapFromHour, this.opts.recapToHour);
if (wait > 0) return this.scheduleRecap(channel, manager, ctx, wait + 1000);
await handleManagerMessages(this.deps, manager, [], {
systemEvent: loadFragment("p-chat-events.md", "Беседа в проектном канале затихла", {}, promptSideFor(this.deps.ctx, manager.personId)),
project: ctx,
channel,
});
const after = await getRecapState(this.pool, channel);
if (after && after.status === "collecting") {
// агент решил подождать (например, последняя реплика - вопрос к кому-то): ещё до трёх попыток через тот же интервал
if (after.attempts >= 3) return;
await this.pool.query("update channel_recap_state set attempts = attempts + 1 where channel_id = $1", [channel]);
this.scheduleRecap(channel, manager, ctx);
}
}
/** После перезапуска сервиса: восстанавливает таймеры recap для каналов с накопленным. */
async restoreRecapTimers(): Promise<void> {
const { rows } = await this.pool.query("select channel_id, job_id, manager_person_id from channel_recap_state where status = 'collecting' and notes <> ''");
for (const r of rows) {
const proj = await this.findProjectByChannel(String(r.channel_id));
const mgr = r.manager_person_id ? await this.findManagerByPerson(String(r.manager_person_id)) : null;
if (!proj || !mgr) continue;
this.scheduleRecap(String(r.channel_id), { ...mgr, slackChannelId: String(r.channel_id) }, { jobId: proj.jobId, jobName: proj.jobName, channel: String(r.channel_id), senderName: null, isHuddle: false });
}
}
async findManagerByPerson(personId: string): Promise<ManagerInfo | null> {
@@ -238,5 +312,7 @@ export class SlackIntake {
this.pending.clear();
for (const t of this.followups.values()) clearTimeout(t);
this.followups.clear();
for (const t of this.recapTimers.values()) clearTimeout(t);
this.recapTimers.clear();
}
}

View File

@@ -0,0 +1,161 @@
import type { Pool } from "khb_common";
import type { SlackApi, SlackHistoryMessage } from "./api.js";
/**
* Проектные каналы: ассистент молчит, пока люди общаются между собой, копит факты для Daily Log (таблица channel_recap_state)
* и по тишине (или после заметок Huddle) одним сообщением спрашивает "Should I add this to the Daily Log?".
*/
export type RecapStatus = "collecting" | "asked";
export interface RecapState {
channelId: string;
jobId: string | null;
notes: string;
status: RecapStatus;
lastHumanAt: Date;
askedAt: Date | null;
attempts: number;
}
/** Время в формате "10/21 14:05" по часовому поясу tz. */
export function stampLocal(d: Date, tz: string): string {
const p = new Intl.DateTimeFormat("en-US", { timeZone: tz, month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hourCycle: "h23", weekday: "short" }).formatToParts(d);
const g = (k: string) => p.find((x) => x.type === k)?.value ?? "";
return `${g("weekday")} ${g("month")}/${g("day")} ${g("hour")}:${g("minute")}`;
}
/** Диалог канала для агента: время по Тампе, автор, текст; упоминания заменены именами; сообщения бота помечены. */
export function formatChannelDialog(
msgs: SlackHistoryMessage[],
opts: { tz: string; botUserId: string | null; names: Map<string, string> },
): string {
if (!msgs.length) return "(за последние сутки сообщений нет)";
const who = (id: string | null) => (id ? (opts.names.get(id) ?? id) : "?");
const resolve = (t: string) => t.replace(/<@([UW][A-Z0-9]+)>/g, (_m, id: string) => `@${who(id)}`).replace(/<!channel>|<!here>|<!everyone>/g, "@channel");
return msgs
.map((m) => {
const fromBot = (m.userId && m.userId === opts.botUserId) || (m.botId && !m.userId);
const author = fromBot ? "ASSISTANT (ты)" : m.botId && m.userId ? `${who(m.userId)} (бот)` : who(m.userId);
const thread = m.threadTs && m.threadTs !== m.ts ? " (в треде)" : "";
const files = m.fileNames.length ? ` [файлы: ${m.fileNames.join(", ")}]` : "";
return `- [${stampLocal(new Date(Number(m.ts) * 1000), opts.tz)}] (ts ${m.ts}) ${author}${thread}: ${resolve(m.text).replace(/\n/g, " ⏎ ").trim() || "(без текста)"}${files}`;
})
.join("\n");
}
/** Загружает диалог канала за последние hours часов (по умолчанию сутки). Сбой Slack - пустая строка-заглушка, обработка не останавливается. */
export async function loadChannelDialog(
slack: Pick<SlackApi, "history" | "userName" | "botUserId">,
channel: string,
now: Date,
tz: string,
hours = 24,
): Promise<string> {
if (!slack.history) return "(история канала недоступна)";
try {
const msgs = await slack.history(channel, Math.floor(now.getTime() / 1000) - hours * 3600);
const names = new Map<string, string>();
if (slack.userName) {
const ids = new Set<string>();
for (const m of msgs) {
if (m.userId) ids.add(m.userId);
for (const x of m.text.matchAll(/<@([UW][A-Z0-9]+)>/g)) ids.add(x[1]!);
}
for (const id of ids) {
const n = await slack.userName(id);
if (n) names.set(id, n);
}
}
return formatChannelDialog(msgs, { tz, botUserId: (await slack.botUserId?.()) ?? null, names });
} catch (e) {
return `(история канала не загрузилась: ${e instanceof Error ? e.message : String(e)})`;
}
}
export async function getRecapState(pool: Pool, channel: string): Promise<RecapState | null> {
const { rows } = await pool.query("select channel_id, job_id, notes, status, last_human_at, asked_at, attempts from channel_recap_state where channel_id = $1", [channel]);
const r = rows[0];
return r
? { channelId: String(r.channel_id), jobId: (r.job_id as string | null) ?? null, notes: String(r.notes), status: r.status === "asked" ? "asked" : "collecting", lastHumanAt: new Date(r.last_human_at as string), askedAt: r.asked_at ? new Date(r.asked_at as string) : null, attempts: Number(r.attempts) }
: null;
}
/** Раздел `## Реакции`: строки `<ts> <эмодзи>` (например `1729612345.000100 memo`). */
export function parseReactions(v: string | undefined): { ts: string; emoji: string }[] {
const out: { ts: string; emoji: string }[] = [];
for (const line of sectionText(v).split(/\r?\n/)) {
const m = line.match(/(\d{9,11}\.\d{3,6})\s+:?([a-z0-9_+\-]+):?/i);
if (m) out.push({ ts: m[1]!, emoji: m[2]!.toLowerCase() });
}
return out.slice(0, 20);
}
/** Блок входа агента: что накоплено и спрошено в этом канале. */
export function recapBlock(st: RecapState | null, tz: string): string {
if (!st || !st.notes.trim()) return "(ничего не накоплено, вопрос про Daily Log не задавался)";
const head =
st.status === "asked"
? `Вопрос про Daily Log уже задан (${stampLocal(st.askedAt ?? st.lastHumanAt, tz)}), ждём ответ участников.`
: `Вопрос про Daily Log ещё не задавался. Последнее сообщение людей: ${stampLocal(st.lastHumanAt, tz)}.`;
return `${head}\nНакопленное:\n${st.notes.trim()}`;
}
const EMPTY = /^\(?\s*(нет|none|-|—|пусто|nothing)\s*\)?\.?$/i;
/** Значение раздела вывода агента: пустые варианты («нет», «(нет)») считаются отсутствием. */
export function sectionText(v: string | undefined): string {
const t = (v ?? "").trim();
return !t || EMPTY.test(t) ? "" : t;
}
export type RecapOutcome = "asked" | "recorded" | "discarded" | "collecting";
/** Разбор раздела `## Статус recap`: asked / recorded / discarded / collecting (по первому слову, русские варианты тоже). */
export function parseRecapStatus(v: string | undefined): RecapOutcome | null {
const t = sectionText(v).toLowerCase();
if (!t) return null;
if (/^(asked|спрошено|вопрос задан)/.test(t)) return "asked";
if (/^(recorded|written|записано|записан)/.test(t)) return "recorded";
if (/^(discarded|отброшено|отклонено|declined)/.test(t)) return "discarded";
if (/^(collecting|копим|накоплен|ждём|ждем|wait)/.test(t)) return "collecting";
return null;
}
/** Применяет разделы `## Накопить для Daily Log` и `## Статус recap` ответа агента к состоянию канала. */
export async function applyRecapOutput(
pool: Pool,
p: { channel: string; managerId: string; jobId: string; sections: Map<string, string>; humanMessage: boolean; now: Date },
): Promise<{ outcome: RecapOutcome | null; hasNotes: boolean }> {
const add = sectionText(p.sections.get("накопить для daily log"));
const outcome = parseRecapStatus(p.sections.get("статус recap"));
if (outcome === "recorded" || outcome === "discarded") {
await pool.query("delete from channel_recap_state where channel_id = $1", [p.channel]);
return { outcome, hasNotes: false };
}
const cur = await getRecapState(pool, p.channel);
if (!add && !cur) return { outcome, hasNotes: false };
// новые факты после вопроса про Daily Log - снова сбор (вопрос задаётся заново позже), если агент не сказал asked
const status: RecapStatus = outcome === "asked" ? "asked" : add ? "collecting" : (cur?.status ?? "collecting");
const notes = [cur?.notes.trim(), add].filter(Boolean).join("\n");
await pool.query(
`insert into channel_recap_state (channel_id, manager_person_id, job_id, notes, status, last_human_at, asked_at, attempts, updated_at)
values ($1,$2,$3,$4,$5,$6,$7,0,now())
on conflict (channel_id) do update set manager_person_id = $2, job_id = $3, notes = $4, status = $5,
last_human_at = case when $8 then $6 else channel_recap_state.last_human_at end,
asked_at = case when $5 = 'asked' then coalesce($7, channel_recap_state.asked_at) else null end,
attempts = case when $5 = 'asked' or $8 then 0 else channel_recap_state.attempts end, updated_at = now()`,
[p.channel, p.managerId, p.jobId, notes, status, p.now, status === "asked" ? p.now : null, p.humanMessage],
);
return { outcome, hasNotes: true };
}
/** Окно, когда можно задавать вопрос про Daily Log: 7:00-19:00 по Тампе. Возвращает задержку (мс) до ближайшего разрешённого момента (0 - можно сейчас). */
export function recapDelayMs(now: Date, tz: string, fromHour = 7, toHour = 19): number {
const p = new Intl.DateTimeFormat("en-US", { timeZone: tz, hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23" }).formatToParts(now);
const g = (k: string) => Number(p.find((x) => x.type === k)?.value ?? 0);
const secOfDay = g("hour") * 3600 + g("minute") * 60 + g("second");
if (secOfDay >= fromHour * 3600 && secOfDay < toHour * 3600) return 0;
const target = secOfDay < fromHour * 3600 ? fromHour * 3600 : 24 * 3600 + fromHour * 3600;
return (target - secOfDay) * 1000;
}