Шаг 4: история напоминаний, запрос "что-то ещё" по таймеру, язык ответа; тесты; docs/proposed
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -61,6 +61,17 @@ export async function handleManagerMessages(
|
||||
const mediaDir = join(managerWorkDir(ctx.settings, manager.personId), "media", sub);
|
||||
mkdirSync(mediaDir, { recursive: true });
|
||||
|
||||
// история напоминаний (вход 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[]>();
|
||||
@@ -154,6 +165,14 @@ export async function handleManagerMessages(
|
||||
const reply = /^\(без ответа\)\.?$/i.test(replyRaw) ? null : replyRaw;
|
||||
let published = false;
|
||||
if (reply && channel && !deps.dryPublish) published = await deps.slack.postMessage(channel, reply);
|
||||
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],
|
||||
);
|
||||
}
|
||||
|
||||
// 6. транскрипты и итоговые файлы -> Drive
|
||||
if (deps.drive && attachments.length) await deps.drive.upload(mediaDir, sub).catch((e) => ctx.log.warn({ err: String(e) }, "повторная выгрузка в Drive не удалась"));
|
||||
|
||||
@@ -14,9 +14,11 @@ export class SlackIntake {
|
||||
private pending = new Map<string, Pending>();
|
||||
private inflight = new Set<Promise<void>>();
|
||||
|
||||
private followups = new Map<string, NodeJS.Timeout>();
|
||||
|
||||
constructor(
|
||||
private deps: ChatDeps,
|
||||
private opts: { channelIds: string[]; debounceMs: number },
|
||||
private opts: { channelIds: string[]; debounceMs: number; followupMs?: number },
|
||||
) {}
|
||||
|
||||
private get pool(): Pool {
|
||||
@@ -60,6 +62,8 @@ export class SlackIntake {
|
||||
const msg: IncomingMessage = { channel, ts, text: String(ev.text ?? ""), fileIds: files };
|
||||
const cur = this.pending.get(manager.personId);
|
||||
if (cur) clearTimeout(cur.timer);
|
||||
clearTimeout(this.followups.get(manager.personId)); // новое сообщение отменяет ожидающий запрос "что-то ещё?"
|
||||
this.followups.delete(manager.personId);
|
||||
const messages = [...(cur?.messages ?? []), msg];
|
||||
const timer = setTimeout(() => this.track(this.flush(manager.personId)), this.opts.debounceMs);
|
||||
this.pending.set(manager.personId, { manager, messages, timer });
|
||||
@@ -83,12 +87,32 @@ export class SlackIntake {
|
||||
try {
|
||||
await handleManagerMessages(this.deps, p.manager, p.messages);
|
||||
await setStatus("done");
|
||||
this.scheduleFollowup(p.manager);
|
||||
} catch (e) {
|
||||
this.deps.ctx.log.error({ manager: managerId, err: String(e) }, "обработка сообщений менеджера не удалась");
|
||||
await setStatus("failed");
|
||||
}
|
||||
}
|
||||
|
||||
/** Через followupMs без новых сообщений агент проверяет, всё ли менеджер сказал, и при необходимости спрашивает "Что-то ещё?". */
|
||||
private scheduleFollowup(manager: ManagerInfo): void {
|
||||
if (!this.opts.followupMs) return;
|
||||
clearTimeout(this.followups.get(manager.personId));
|
||||
const t = setTimeout(() => {
|
||||
this.followups.delete(manager.personId);
|
||||
this.track(
|
||||
handleManagerMessages(this.deps, manager, [], {
|
||||
systemEvent:
|
||||
"Прошло несколько минут после последнего сообщения менеджера, новых сообщений нет. Если из его сообщений не следует явного окончания и он упомянул не все важные задачи из списка - задай ОДИН короткий вопрос `Что-то ещё по <название объекта>?` и добавь вопрос по 1-2 неупомянутым задачам. Иначе ответ `(без ответа)`.",
|
||||
}).then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
),
|
||||
);
|
||||
}, this.opts.followupMs);
|
||||
this.followups.set(manager.personId, t);
|
||||
}
|
||||
|
||||
/** Дождаться текущих обработок (тесты, остановка). */
|
||||
async idle(): Promise<void> {
|
||||
while (this.inflight.size) await Promise.allSettled([...this.inflight]);
|
||||
@@ -97,5 +121,7 @@ export class SlackIntake {
|
||||
stop(): void {
|
||||
for (const p of this.pending.values()) clearTimeout(p.timer);
|
||||
this.pending.clear();
|
||||
for (const t of this.followups.values()) clearTimeout(t);
|
||||
this.followups.clear();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user