Google Drive под ключами сервисных аккаунтов вместо rclone: клиент Drive API, папка приёма и выгрузка материалов; команда khb-drive для агентов (builder - строителям и проектным чатам, полный - руководителю); rclone удалён; промты; тесты
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -51,6 +51,8 @@ export interface ChatDeps {
|
||||
tts?: Tts;
|
||||
defaultVoice?: string;
|
||||
drive?: DriveSync;
|
||||
/** Ключи сервисных аккаунтов Google (JSON) для агентов: full - руководитель, builder - строители и проектные чаты. */
|
||||
driveKeys?: { full?: string; builder?: string };
|
||||
timezone: string;
|
||||
now?: () => Date;
|
||||
/** Тест: не слать ответ в Slack. */
|
||||
@@ -251,7 +253,12 @@ export async function handleManagerMessages(
|
||||
const isCeo = manager.chatKind === "ceo";
|
||||
// чтение зеркала Supabase: агент менеджера - роль khb_agent, руководитель - khb_agent_ceo (команда khb-sql, Bash)
|
||||
const sqlCfg = ctx.settings.sql;
|
||||
const sqlEnv = sqlCfg ? { KHB_SQL_URL: isCeo ? (sqlCfg.ceoUrl ?? sqlCfg.agentUrl) : sqlCfg.agentUrl } : undefined;
|
||||
const driveKey = isCeo ? deps.driveKeys?.full : deps.driveKeys?.builder; // Google Drive: руководитель - полный ключ, остальные (включая проектные чаты) - builder
|
||||
const agentEnv: Record<string, string> = {
|
||||
...(sqlCfg ? { KHB_SQL_URL: isCeo ? (sqlCfg.ceoUrl ?? sqlCfg.agentUrl) : sqlCfg.agentUrl } : {}),
|
||||
...(driveKey ? { KHB_DRIVE_KEY: driveKey } : {}),
|
||||
};
|
||||
const sqlEnv = Object.keys(agentEnv).length ? agentEnv : undefined;
|
||||
const replyKey = isCeo ? "ответ arthur" : "ответ менеджеру";
|
||||
const listText = isCeo ? "" : await todayList(ctx, manager.personId, today);
|
||||
const buildPrompt = (dialog: boolean): string => [
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { mkdirSync, readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import { defaultExec, type ExecFn } from "./drive.js";
|
||||
import { FOLDER_MIME, type DriveClient } from "../gdrive/client.js";
|
||||
|
||||
export interface InboxFile {
|
||||
channel: string;
|
||||
@@ -16,29 +16,26 @@ export interface InboxFile {
|
||||
}
|
||||
|
||||
export interface DriveInboxOpts {
|
||||
rcloneBin: string;
|
||||
remote: string;
|
||||
folder: string;
|
||||
client: DriveClient;
|
||||
/** Папка builder_assistant: внутри неё папки приёма `<channel_id>`. */
|
||||
rootFolderId: 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: новые файлы воспринимаются как сообщения менеджера в этом чате. */
|
||||
/** Опрос папки `builder_assistant/<channel_id>` на Google Drive: новые файлы воспринимаются как сообщения менеджера в этом чате. */
|
||||
export class DriveInbox {
|
||||
private timer?: NodeJS.Timeout;
|
||||
private busy = false;
|
||||
private exec: ExecFn;
|
||||
private channelFolders = new Map<string, string>();
|
||||
|
||||
constructor(private o: DriveInboxOpts) {
|
||||
this.exec = o.exec ?? defaultExec;
|
||||
}
|
||||
constructor(private o: DriveInboxOpts) {}
|
||||
|
||||
start(intervalMs: number): void {
|
||||
this.timer = setInterval(() => void this.scan().catch((e) => this.o.onError?.(e)), intervalMs);
|
||||
@@ -61,30 +58,34 @@ export class DriveInbox {
|
||||
}
|
||||
}
|
||||
|
||||
private async channelFolder(channel: string): Promise<string | null> {
|
||||
const known = this.channelFolders.get(channel);
|
||||
if (known) return known;
|
||||
const f = await this.o.client.findChild(this.o.rootFolderId, channel, FOLDER_MIME);
|
||||
if (f) this.channelFolders.set(channel, f.id);
|
||||
return f?.id ?? null; // папка канала ещё не создана
|
||||
}
|
||||
|
||||
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("."));
|
||||
const { client } = this.o;
|
||||
const folderId = await this.channelFolder(channel);
|
||||
if (!folderId) return 0;
|
||||
const listing = await client.children(folderId, { orderBy: "modifiedTime" });
|
||||
const files = listing.filter((f) => f.mimeType !== FOLDER_MIME && !f.name.startsWith("_") && !f.name.startsWith("."));
|
||||
if (!files.length) return 0;
|
||||
const local = join(this.o.localRoot, channel);
|
||||
mkdirSync(local, { recursive: true });
|
||||
const processed = await client.ensureFolder(folderId, "_processed");
|
||||
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++;
|
||||
for (const f of files) {
|
||||
const localPath = join(local, `${f.id.slice(0, 8)}_${f.name.replace(/[^\w.\- ]/g, "_")}`);
|
||||
await client.downloadTo(f.id, localPath);
|
||||
const frac = createHash("sha1").update(f.id).digest().readUInt32BE(0) % 1_000_000;
|
||||
const ts = `${Math.floor(Date.parse(f.modifiedTime ?? "") / 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}`]);
|
||||
await client.move(f.id, processed.id, `${f.id.slice(0, 8)}_${f.name}`);
|
||||
}
|
||||
return accepted;
|
||||
}
|
||||
|
||||
@@ -1,26 +1,34 @@
|
||||
import { execFile } from "node:child_process";
|
||||
|
||||
export type ExecFn = (cmd: string, args: string[]) => Promise<string>;
|
||||
|
||||
export const defaultExec: ExecFn = (cmd, args) =>
|
||||
new Promise((resolve, reject) =>
|
||||
execFile(cmd, args, { timeout: 10 * 60_000, maxBuffer: 20 * 1024 * 1024 }, (err, stdout, stderr) => (err ? reject(new Error(`${cmd} ${args[0]}: ${stderr || err.message}`)) : resolve(stdout))),
|
||||
);
|
||||
import { readdirSync, statSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { fileLink, type DriveClient } from "../gdrive/client.js";
|
||||
|
||||
export interface DriveSync {
|
||||
/** Копирует локальную папку в `<folder>/<subdir>` на Drive; возвращает ссылки по имени файла. */
|
||||
/** Копирует локальную папку в `<корень материалов>/<subdir>` на Drive; возвращает ссылки по имени файла. */
|
||||
upload(localDir: string, subdir: string): Promise<Record<string, string>>;
|
||||
}
|
||||
|
||||
/** Выгрузка исходников и транскриптов в Google Drive через rclone (remote настроен под пользователем сервиса). */
|
||||
export function createRcloneDrive(cfg: { rcloneBin: string; remote: string; folder: string }, exec: ExecFn = defaultExec): DriveSync {
|
||||
const MIME: Record<string, string> = {
|
||||
".txt": "text/plain", ".md": "text/markdown", ".json": "application/json", ".pdf": "application/pdf",
|
||||
".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png", ".heic": "image/heic",
|
||||
".mp4": "video/mp4", ".mov": "video/quicktime", ".m4a": "audio/mp4", ".mp3": "audio/mpeg", ".wav": "audio/wav", ".ogg": "audio/ogg",
|
||||
};
|
||||
const mimeOf = (name: string): string => MIME[name.slice(name.lastIndexOf(".")).toLowerCase()] ?? "application/octet-stream";
|
||||
|
||||
/**
|
||||
* Выгрузка исходников и транскриптов в Google Drive под ключом сервисного аккаунта (папка `rootFolderId` - builder_assistant).
|
||||
* Повторная выгрузка той же папки обновляет изменившиеся файлы (транскрипты) и пропускает неизменившиеся.
|
||||
*/
|
||||
export function createGoogleDrive(client: DriveClient, rootFolderId: string): DriveSync {
|
||||
return {
|
||||
async upload(localDir, subdir) {
|
||||
const dest = `${cfg.remote}:${cfg.folder}/${subdir}`;
|
||||
await exec(cfg.rcloneBin, ["copy", localDir, dest]);
|
||||
const listing = JSON.parse(await exec(cfg.rcloneBin, ["lsjson", dest])) as { Name: string; ID?: string; IsDir?: boolean }[];
|
||||
const folder = await client.ensureFolder(rootFolderId, subdir);
|
||||
const links: Record<string, string> = {};
|
||||
for (const f of listing) if (!f.IsDir && f.ID) links[f.Name] = `https://drive.google.com/file/d/${f.ID}/view`;
|
||||
for (const name of readdirSync(localDir)) {
|
||||
const path = join(localDir, name);
|
||||
if (!statSync(path).isFile()) continue;
|
||||
const { file } = await client.upsertFile(path, folder.id, name, mimeOf(name));
|
||||
links[name] = fileLink(file.id);
|
||||
}
|
||||
return links;
|
||||
},
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user