Шаг 4: история напоминаний, запрос "что-то ещё" по таймеру, язык ответа; тесты; docs/proposed
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -144,6 +144,38 @@ d("консольные агенты (временная БД, фейковый
|
||||
expect(run.rows[0].changes).toContain("createDailyLog");
|
||||
});
|
||||
|
||||
it("событие ассистента: напоминание пишется в историю, ответ менеджера закрывает его; через followup агент спрашивает `что-то ещё`", async () => {
|
||||
calls = [];
|
||||
const posted: string[] = [];
|
||||
script = [
|
||||
ok("## Ответ менеджеру\nПривет! Как дела на объекте? llmtest\n## Память\nм6"),
|
||||
ok("## Ответ менеджеру\nСпасибо! llmtest\n## Память\nм7"),
|
||||
ok("## Ответ менеджеру\nЧто-то ещё по llmtest-job?\n## Память\nм8"),
|
||||
];
|
||||
const deps = {
|
||||
ctx: ctx(), timezone: "America/New_York",
|
||||
slack: { postMessage: async (_c: string, t: string) => { posted.push(t); return true; }, fileInfo: async () => null, download: async () => 0 },
|
||||
};
|
||||
const mgr = { personId: MGR, name: "llmtest-Manager", slackUserId: "ULLMTEST", slackChannelId: "CLLMTEST" };
|
||||
await handleManagerMessages(deps, mgr, [], { systemEvent: "12:00" });
|
||||
const r1 = await db.pool.query("select reminder_text, reply_at from reminder_history where reminder_text like '%llmtest%'");
|
||||
expect(r1.rows).toHaveLength(1);
|
||||
expect(r1.rows[0].reply_at).toBeNull();
|
||||
expect(calls[0]!.prompt).toContain("# Системное событие");
|
||||
|
||||
const intake = new SlackIntake(deps, { channelIds: ["CLLMTEST"], debounceMs: 600_000, followupMs: 300 });
|
||||
await intake.onEvent({ type: "message", channel: "CLLMTEST", user: "ULLMTEST", ts: "2.1", text: "делаю, всё идёт хорошо" });
|
||||
await intake.flush(MGR);
|
||||
const r2 = await db.pool.query("select reply_summary, reply_outcome from reminder_history where reminder_text like '%llmtest%'");
|
||||
expect(r2.rows[0]).toEqual({ reply_summary: "делаю, всё идёт хорошо", reply_outcome: "other" });
|
||||
await new Promise((r) => setTimeout(r, 1500)); // сработал followup
|
||||
await intake.idle();
|
||||
intake.stop();
|
||||
expect(calls).toHaveLength(3);
|
||||
expect(calls[2]!.prompt).toContain("Что-то ещё по");
|
||||
expect(posted[posted.length - 1]).toContain("Что-то ещё");
|
||||
});
|
||||
|
||||
it("приём события Slack: фильтры, дубли, накопление и запуск шага 4", async () => {
|
||||
calls = [];
|
||||
const posted: string[] = [];
|
||||
|
||||
@@ -89,6 +89,6 @@ await app.listen({ host: service.http.host, port: service.http.port });
|
||||
log.info({ port: service.http.port }, "khbuild_assistant_prep запущен");
|
||||
|
||||
if (service.slack && chatDeps) {
|
||||
const intake = new SlackIntake(chatDeps, { channelIds: service.slack.channelIds, debounceMs: service.slack.debounceSeconds * 1000 });
|
||||
const intake = new SlackIntake(chatDeps, { channelIds: service.slack.channelIds, debounceMs: service.slack.debounceSeconds * 1000, followupMs: service.slack.followupMinutes * 60_000 });
|
||||
startSocketMode({ appToken: service.slack.appToken, log, onEvent: (ev) => void intake.onEvent(ev).catch((e) => log.error({ err: String(e) }, "ошибка приёма события Slack")) });
|
||||
}
|
||||
|
||||
@@ -23,6 +23,8 @@ export const slackSchema = z.object({
|
||||
channelIds: z.array(z.string()).default([]),
|
||||
/** Пауза накопления сообщений менеджера перед запуском агента. */
|
||||
debounceSeconds: z.number().default(8),
|
||||
/** Через сколько минут после последнего сообщения менеджера агент спрашивает "Что-то ещё?" (0 - отключено). */
|
||||
followupMinutes: z.number().default(8),
|
||||
});
|
||||
export type SlackSettings = z.infer<typeof slackSchema>;
|
||||
|
||||
|
||||
@@ -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