import { randomUUID } from "node:crypto"; import Fastify, { type FastifyInstance } from "fastify"; import type { Pool } from "khb_common"; import { registerAgentRoutes } from "./agents-api.js"; import { usageSummary, type UsageLog } from "./usage.js"; import type { PrepJob, PrepResult } from "./jobs.js"; import { checkMailAuth } from "./mail/auth.js"; import { resolveForManager, sendForManager, type MailDeps } from "./mail/service.js"; export interface ChatApi { /** Имитация входящего сообщения менеджера (без Slack): текст и локальные файлы; publish - слать ли ответ в Slack. */ simulate(opts: { managerId?: string; text: string; files?: string[]; publish?: boolean }): Promise; /** Системное событие ассистента (напоминания 12:00/13:00/16:00 и т.п.) всем менеджерам режима. */ event(kind: string): Promise; /** Разовое поручение агенту менеджера от ИТ/владельца (например, применить подтверждённые изменения); ответ уходит в чат менеджера, если publish. */ apply(opts: { managerId: string; text: string; publish?: boolean }): Promise; } export interface PrepApiDeps { pool: Pool; token: string; run(job: PrepJob, opts: { projectId?: string; dryRun?: boolean }): Promise; chat?: ChatApi; usageLog?: UsageLog; /** Письма подрядчикам (команда khb-mail): токен менеджера, не общий токен сервиса. */ mail?: { deps: MailDeps; secret: string }; } interface RunState { id: string; job: PrepJob; status: "running" | "ok" | "skipped" | "error"; startedAt: string; finishedAt?: string; result?: PrepResult; error?: string; } export function buildApi(deps: PrepApiDeps): FastifyInstance { const app = Fastify(); const runs = new Map(); // состояние последних запусков в памяти; постоянный след - ap_*, sched_run app.addHook("onRequest", async (req, reply) => { if (req.url === "/healthz") return; if (req.url.startsWith("/mail/")) { if (!deps.mail || !checkMailAuth(deps.mail.secret, String(req.headers["x-khb-caller"] ?? ""), req.headers.authorization)) return reply.code(401).send({ error: "unauthorized" }); return; } if (req.headers.authorization !== `Bearer ${deps.token}`) return reply.code(401).send({ error: "unauthorized" }); }); registerAgentRoutes(app, deps.pool); if (deps.mail) { const mail = deps.mail.deps; const caller = (req: { headers: Record }) => String(req.headers["x-khb-caller"]); app.post<{ Body: { project?: string; vendor?: string; work?: string } }>("/mail/resolve", async (req) => resolveForManager(mail, { managerId: caller(req), project: req.body?.project, vendor: req.body?.vendor, work: req.body?.work })); app.post<{ Body: { project?: string; vendor?: string; work?: string; date?: string; note?: string; channel?: string } }>("/mail/send", async (req) => sendForManager(mail, { managerId: caller(req), project: req.body?.project, vendor: req.body?.vendor, work: req.body?.work, date: String(req.body?.date ?? ""), note: req.body?.note, channel: req.body?.channel })); } app.get("/healthz", async () => { let db = false; try { await deps.pool.query("select 1"); db = true; } catch { /* db=false */ } return { ok: db, db, time: new Date().toISOString() }; }); app.post<{ Body: { job: PrepJob; projectId?: string; dryRun?: boolean } }>("/runs", async (req, reply) => { const { job, projectId, dryRun } = req.body ?? ({} as never); if (job !== "collect_morning" && job !== "recheck_noon") return reply.code(400).send({ error: "job должен быть collect_morning или recheck_noon" }); const st: RunState = { id: randomUUID(), job, status: "running", startedAt: new Date().toISOString() }; runs.set(st.id, st); if (runs.size > 50) runs.delete(runs.keys().next().value as string); deps.run(job, { projectId, dryRun }).then( (r) => Object.assign(st, { status: r.status, result: r, finishedAt: new Date().toISOString() }), (e) => Object.assign(st, { status: "error", error: e instanceof Error ? e.message : String(e), finishedAt: new Date().toISOString() }), ); return reply.code(202).send({ runId: st.id, status: "running" }); }); // шаг 4: асинхронные запуски (агент работает минуты), состояние по id const chatRuns = new Map(); const startChat = (fn: () => Promise) => { const id = randomUUID(); const st: { status: "running" | "ok" | "error"; result?: unknown; error?: string } = { status: "running" }; chatRuns.set(id, st); if (chatRuns.size > 50) chatRuns.delete(chatRuns.keys().next().value as string); fn().then( (r) => Object.assign(st, { status: "ok", result: r }), (e) => Object.assign(st, { status: "error", error: e instanceof Error ? e.message : String(e) }), ); return id; }; app.post<{ Body: { managerId?: string; text?: string; files?: string[]; publish?: boolean } }>("/chat/simulate", async (req, reply) => { if (!deps.chat) return reply.code(501).send({ error: "chat не настроен" }); const b = req.body ?? {}; if (!b.text) return reply.code(400).send({ error: "нужен text" }); return reply.code(202).send({ chatRunId: startChat(() => deps.chat!.simulate({ managerId: b.managerId, text: b.text!, files: b.files, publish: b.publish })) }); }); app.post<{ Body: { kind?: string } }>("/chat/event", async (req, reply) => { if (!deps.chat) return reply.code(501).send({ error: "chat не настроен" }); const kind = req.body?.kind; if (!kind) return reply.code(400).send({ error: "нужен kind" }); return reply.code(202).send({ chatRunId: startChat(() => deps.chat!.event(kind)) }); }); app.post<{ Body: { managerId?: string; text?: string; publish?: boolean } }>("/chat/apply", async (req, reply) => { if (!deps.chat) return reply.code(501).send({ error: "chat не настроен" }); const b = req.body ?? {}; if (!b.managerId || !b.text) return reply.code(400).send({ error: "нужны managerId и text" }); return reply.code(202).send({ chatRunId: startChat(() => deps.chat!.apply({ managerId: b.managerId!, text: b.text!, publish: b.publish })) }); }); app.get<{ Params: { id: string } }>("/chat/runs/:id", async (req, reply) => chatRuns.get(req.params.id) ?? reply.code(404).send({ error: "not found" })); app.get("/agent/runs", async () => (await deps.pool.query("select id, manager_person_id, step, attempt, resumed, status, started_at, duration_ms, error, changes from agent_run order by started_at desc limit 20")).rows); /** Токены агентов: сводка за N часов (по умолчанию 24) по операциям и менеджерам + лимиты из globals. Денег здесь нет намеренно. */ app.get<{ Querystring: { hours?: string } }>("/agent/usage", async (req) => usageSummary(deps.pool, Number(req.query.hours) || 24, deps.usageLog)); app.get<{ Params: { id: string } }>("/runs/:id", async (req, reply) => runs.get(req.params.id) ?? reply.code(404).send({ error: "not found" })); return app; }