Папка приёма Google Drive <id чата>: опрос раз в 10 секунд, файлы = сообщения менеджера; swap 32 ГБ; docs
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -3,6 +3,7 @@
|
||||
1. шаг 1 - сбор входов (1)-(5), (7) по зеркалам, пакеты на проект, сравнение 06:00 и 11:50;
|
||||
2. шаги 2-3 - по одному агенту на менеджера: ранжированный список задач и память (текстовый ответ), проверка формата с повторами, уведомление ИТ при сбое;
|
||||
3. шаг 4 - приём сообщений менеджера из Slack (Socket Mode), вложения, транскрибация и запись в JobTread делает агент (Bash + коннектор JobTread), ответ в Slack публикует бот.
|
||||
Папка приёма Drive `builder_assistant/<id чата>` опрашивается каждые 10 секунд, файлы = сообщения менеджера (`drive.inboxScanSeconds`).
|
||||
Промты - `promts/step2_prepare.md`, `promts/step4_manager_chat.md` (копируются в образ).
|
||||
|
||||
## Endpoints и доступ
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { createLogger, createTestDb, testDatabaseUrl, type TestDb } from "khb_common";
|
||||
@@ -7,6 +9,7 @@ import { parseSections } from "./agents/sections.js";
|
||||
import { AgentFailure, runManagerAgent, type AgentContext } from "./agents/session.js";
|
||||
import { runStep2 } from "./agents/step2.js";
|
||||
import { handleManagerMessages } from "./slack/chat.js";
|
||||
import { DriveInbox } from "./slack/drive-inbox.js";
|
||||
import { SlackIntake } from "./slack/intake.js";
|
||||
|
||||
describe("разбор разделов ответа агента", () => {
|
||||
@@ -203,4 +206,40 @@ d("консольные агенты (временная БД, фейковый
|
||||
const log = await db.pool.query("select message_ts, status from slack_message_log where message_ts like '1.%' order by message_ts");
|
||||
expect(log.rows).toEqual([{ message_ts: "1.5", status: "done" }, { message_ts: "1.6", status: "done" }]);
|
||||
});
|
||||
it("папка приёма Drive: файлы и текст из <folder>/<channel> становятся сообщениями чата", async () => {
|
||||
calls = [];
|
||||
const posted: string[] = [];
|
||||
script = [ok("## Ответ менеджеру\nответ drive llmtest\n## Память\nм6")];
|
||||
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 intake = new SlackIntake(deps, { channelIds: [], debounceMs: 600_000 });
|
||||
const moved: string[] = [];
|
||||
let listed = [
|
||||
{ Name: "note.txt", ID: "idnote0001xx", ModTime: "2026-01-01T10:00:00Z" },
|
||||
{ Name: "voice.m4a", ID: "idvoice002xx", ModTime: "2026-01-01T10:00:05Z" },
|
||||
{ Name: "_processed", ID: "x", IsDir: true },
|
||||
];
|
||||
const exec = async (_bin: string, args: string[]) => {
|
||||
if (args[0] === "lsjson") return JSON.stringify(listed);
|
||||
if (args[0] === "copyto") { writeFileSync(args[2]!, args[1]!.endsWith(".txt") ? "llmtest drive text message" : "audio"); return ""; }
|
||||
if (args[0] === "moveto") { moved.push(args[1]!); listed = []; return ""; }
|
||||
return "";
|
||||
};
|
||||
const inbox = new DriveInbox({
|
||||
rcloneBin: "rclone", remote: "gd", folder: "ba", localRoot: join(tmpdir(), "llmtest-inbox"),
|
||||
channels: async () => ["CLLMTEST"], accept: (f) => intake.onDriveFile(f), exec,
|
||||
});
|
||||
expect(await inbox.scan()).toBe(2);
|
||||
expect(moved).toHaveLength(2);
|
||||
expect(await inbox.scan()).toBe(0);
|
||||
await intake.flush(MGR);
|
||||
await intake.idle();
|
||||
intake.stop();
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0]!.prompt).toContain("llmtest drive text message");
|
||||
expect(calls[0]!.prompt).toContain("voice.m4a");
|
||||
expect(posted).toEqual(["ответ drive llmtest"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { join } from "node:path";
|
||||
import { createLogger, createPool, itNotify, loadServiceSettings } from "khb_common";
|
||||
import { createCliRunner } from "./agents/cli-runner.js";
|
||||
import { KeyedMutex, Semaphore } from "./agents/pool.js";
|
||||
@@ -8,6 +9,7 @@ import { assistantPrepSchema } from "./settings.js";
|
||||
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";
|
||||
|
||||
const { common, service } = loadServiceSettings("khbuild_assistant_prep", assistantPrepSchema);
|
||||
@@ -91,4 +93,20 @@ 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, 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")) });
|
||||
if (service.drive && service.drive.inboxScanSeconds > 0) {
|
||||
const d = service.drive;
|
||||
const slackChannels = service.slack.channelIds;
|
||||
const inbox = new DriveInbox({
|
||||
rcloneBin: d.rcloneBin, remote: d.remote, folder: d.folder,
|
||||
localRoot: join(service.agent.workRoot, "_drive_inbox"),
|
||||
channels: async () => {
|
||||
const { rows } = await pool.query("select distinct slack_channel_id from construction_manager where is_active and slack_channel_id is not null");
|
||||
return [...new Set([...slackChannels, ...rows.map((r) => String(r.slack_channel_id))])];
|
||||
},
|
||||
accept: (f) => intake.onDriveFile(f),
|
||||
onError: (e) => log.error({ err: String(e) }, "ошибка опроса папки приёма Drive"),
|
||||
});
|
||||
inbox.start(d.inboxScanSeconds * 1000);
|
||||
log.info({ everySeconds: d.inboxScanSeconds }, "опрос папок приёма Drive запущен");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,6 +33,8 @@ export const driveSchema = z.object({
|
||||
remote: z.string().default("gdrive"),
|
||||
/** Папка относительно корня remote; внутри - <iso>_<channel>/ . */
|
||||
folder: z.string().default("builder_assistant"),
|
||||
/** Период опроса папок приёма `<folder>/<channel_id>` (0 - отключено). */
|
||||
inboxScanSeconds: z.number().default(10),
|
||||
});
|
||||
|
||||
export const assistantPrepSchema = z.object({
|
||||
|
||||
91
packages/khbuild_assistant_prep/src/slack/drive-inbox.ts
Normal file
91
packages/khbuild_assistant_prep/src/slack/drive-inbox.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import { mkdirSync, readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import { defaultExec, type ExecFn } from "./drive.js";
|
||||
|
||||
export interface InboxFile {
|
||||
channel: string;
|
||||
name: string;
|
||||
id: string;
|
||||
/** Локальный путь скачанного файла. */
|
||||
localPath: string;
|
||||
/** Для текстовых файлов (.txt/.md) - содержимое, воспринимается как текст сообщения. */
|
||||
text?: string;
|
||||
/** Псевдо-ts сообщения (секунды.дробь), уникален по id файла. */
|
||||
ts: string;
|
||||
}
|
||||
|
||||
export interface DriveInboxOpts {
|
||||
rcloneBin: string;
|
||||
remote: string;
|
||||
folder: string;
|
||||
/** Локальная папка для скачанных файлов: <localRoot>/<channel>/ . */
|
||||
localRoot: string;
|
||||
channels: () => Promise<string[]>;
|
||||
/** Принять файл как сообщение чата; true - принят (не дубль). */
|
||||
accept: (f: InboxFile) => Promise<boolean>;
|
||||
exec?: ExecFn;
|
||||
onError?: (e: unknown) => void;
|
||||
}
|
||||
|
||||
const TEXT_EXT = /\.(txt|md)$/i;
|
||||
|
||||
/** Опрос папки `<folder>/<channel_id>` на Google Drive: новые файлы воспринимаются как сообщения менеджера в этом чате. */
|
||||
export class DriveInbox {
|
||||
private timer?: NodeJS.Timeout;
|
||||
private busy = false;
|
||||
private exec: ExecFn;
|
||||
|
||||
constructor(private o: DriveInboxOpts) {
|
||||
this.exec = o.exec ?? defaultExec;
|
||||
}
|
||||
|
||||
start(intervalMs: number): void {
|
||||
this.timer = setInterval(() => void this.scan().catch((e) => this.o.onError?.(e)), intervalMs);
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
clearInterval(this.timer);
|
||||
}
|
||||
|
||||
/** Один проход по всем каналам; возвращает число принятых файлов. */
|
||||
async scan(): Promise<number> {
|
||||
if (this.busy) return 0;
|
||||
this.busy = true;
|
||||
try {
|
||||
let accepted = 0;
|
||||
for (const channel of await this.o.channels()) accepted += await this.scanChannel(channel).catch((e) => (this.o.onError?.(e), 0));
|
||||
return accepted;
|
||||
} finally {
|
||||
this.busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async scanChannel(channel: string): Promise<number> {
|
||||
const { rcloneBin: bin, remote, folder } = this.o;
|
||||
const dir = `${remote}:${folder}/${channel}`;
|
||||
let listing: { Name: string; ID?: string; IsDir?: boolean; ModTime?: string }[];
|
||||
try {
|
||||
listing = JSON.parse(await this.exec(bin, ["lsjson", dir]));
|
||||
} catch (e) {
|
||||
if (/directory not found|not found/i.test(String(e))) return 0; // папка канала ещё не создана
|
||||
throw e;
|
||||
}
|
||||
const files = listing.filter((f) => !f.IsDir && f.ID && !f.Name.startsWith("_") && !f.Name.startsWith("."));
|
||||
if (!files.length) return 0;
|
||||
const local = join(this.o.localRoot, channel);
|
||||
mkdirSync(local, { recursive: true });
|
||||
let accepted = 0;
|
||||
for (const f of files.sort((a, b) => (a.ModTime ?? "").localeCompare(b.ModTime ?? ""))) {
|
||||
const localPath = join(local, `${f.ID!.slice(0, 8)}_${f.Name.replace(/[^\w.\- ]/g, "_")}`);
|
||||
await this.exec(bin, ["copyto", `${dir}/${f.Name}`, localPath]);
|
||||
const frac = createHash("sha1").update(f.ID!).digest().readUInt32BE(0) % 1_000_000;
|
||||
const ts = `${Math.floor(Date.parse(f.ModTime ?? "") / 1000) || Math.floor(Date.now() / 1000)}.${String(frac).padStart(6, "0")}`;
|
||||
const text = TEXT_EXT.test(f.Name) ? readFileSync(localPath, "utf8").trim() : undefined;
|
||||
if (await this.o.accept({ channel, name: f.Name, id: f.ID!, localPath, text, ts })) accepted++;
|
||||
// обработанное убираем из папки приёма, чтобы не читать повторно
|
||||
await this.exec(bin, ["moveto", `${dir}/${f.Name}`, `${dir}/_processed/${f.ID!.slice(0, 8)}_${f.Name}`]);
|
||||
}
|
||||
return accepted;
|
||||
}
|
||||
}
|
||||
@@ -54,12 +54,35 @@ export class SlackIntake {
|
||||
if (!manager) return;
|
||||
if (!this.opts.channelIds.includes(channel) && manager.slackChannelId !== channel) 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 });
|
||||
}
|
||||
|
||||
/** Менеджер чата (по 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
|
||||
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;
|
||||
}
|
||||
|
||||
/** Файл из папки приёма на Drive = сообщение менеджера в чате (текстовые файлы - текст сообщения). */
|
||||
async onDriveFile(f: { channel: string; name: string; id: string; localPath: string; text?: string; ts: string }): Promise<boolean> {
|
||||
const manager = await this.findManagerByChannel(f.channel);
|
||||
if (!manager) return false;
|
||||
return this.accept(manager, { channel: f.channel, ts: f.ts, text: f.text ?? "", fileIds: [], localFiles: f.text === undefined ? [f.localPath] : [] });
|
||||
}
|
||||
|
||||
/** Журнал (защита от дублей) + накопление в debounce-пакет менеджера. */
|
||||
private async accept(manager: ManagerInfo, msg: IncomingMessage): Promise<boolean> {
|
||||
const ins = await this.pool.query(
|
||||
"insert into slack_message_log (channel_id, message_ts, manager_person_id, has_files, status) values ($1,$2,$3,$4,'received') on conflict do nothing returning message_ts",
|
||||
[channel, ts, manager.personId, files.length > 0],
|
||||
[msg.channel, msg.ts, manager.personId, msg.fileIds.length > 0 || (msg.localFiles?.length ?? 0) > 0],
|
||||
);
|
||||
if (!ins.rowCount) return; // дубль события
|
||||
const msg: IncomingMessage = { channel, ts, text: String(ev.text ?? ""), fileIds: files };
|
||||
if (!ins.rowCount) return false; // дубль
|
||||
const cur = this.pending.get(manager.personId);
|
||||
if (cur) clearTimeout(cur.timer);
|
||||
clearTimeout(this.followups.get(manager.personId)); // новое сообщение отменяет ожидающий запрос "что-то ещё?"
|
||||
@@ -67,6 +90,7 @@ export class SlackIntake {
|
||||
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 });
|
||||
return true;
|
||||
}
|
||||
|
||||
private track(p: Promise<void>): void {
|
||||
|
||||
Reference in New Issue
Block a user