185 lines
13 KiB
TypeScript
185 lines
13 KiB
TypeScript
import type { FastifyInstance } from "fastify";
|
||
import type { Pool } from "khb_common";
|
||
import { loadMemory, saveMemory } from "./agents/session.js";
|
||
import { activeWindow, loadWindows, NOT_PAUSED_SQL, pauseState, resumeAll, resumeManager, setPause, setPauseAll } from "./pause.js";
|
||
|
||
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||
const clampLimit = (v: unknown, def: number, max: number): number => {
|
||
const n = Number(v);
|
||
return Number.isFinite(n) && n > 0 ? Math.min(Math.floor(n), max) : def;
|
||
};
|
||
|
||
/**
|
||
* Инструменты разбора инцидентов: память агента менеджера (чтение, запись с аудитом, сброс сессии) и история работы агента.
|
||
* Доступ - тот же токен сервиса. Предложение и планы (MCP-обёртка и т.д.): docs/proposed/modules/khbuild_assistant_prep/agent-ops-tools.md.
|
||
*/
|
||
export function registerAgentRoutes(app: FastifyInstance, pool: Pool): void {
|
||
const knownManager = async (id: string): Promise<{ name: string } | null> => {
|
||
if (!UUID.test(id)) return null;
|
||
const { rows } = await pool.query("select p.display_name from construction_manager cm join person p on p.id = cm.person_id where cm.person_id = $1", [id]);
|
||
return rows[0] ? { name: String(rows[0].display_name) } : null;
|
||
};
|
||
|
||
/** Список агентов (менеджеров) с состоянием памяти, сессии и последним запуском. */
|
||
app.get("/agents", async () => {
|
||
const { rows } = await pool.query(
|
||
`select cm.person_id as id, p.display_name as name, cm.slack_channel_id, cm.is_active,
|
||
(not ${NOT_PAUSED_SQL("cm")}) as paused, cm.pause_mode, cm.agent_paused as paused_indefinitely, cm.paused_until, cm.pause_reason, cm.paused_by,
|
||
coalesce(length(m.memory_text), 0)::int as memory_chars, m.updated_at as memory_updated_at, (m.claude_session_id is not null) as has_session,
|
||
(select jsonb_build_object('step', r.step, 'status', r.status, 'started_at', r.started_at, 'error', r.error)
|
||
from agent_run r where r.manager_person_id = cm.person_id order by r.started_at desc limit 1) as last_run
|
||
from construction_manager cm join person p on p.id = cm.person_id left join agent_manager_memory m on m.manager_person_id = cm.person_id
|
||
order by p.display_name`,
|
||
);
|
||
return rows;
|
||
});
|
||
|
||
/**
|
||
* Срок отключения из тела запроса: `until` (ISO-время с часовым поясом), либо `hours`, либо `days` от сейчас; ничего не задано - до команды владельца.
|
||
* Возвращает { until: Date | null } или { error }.
|
||
*/
|
||
const parseUntil = (b: { until?: unknown; hours?: unknown; days?: unknown }): { until: Date | null } | { error: string } => {
|
||
let until: Date | null = null;
|
||
if (b.until !== undefined && b.until !== null && b.until !== "") {
|
||
until = new Date(String(b.until));
|
||
if (Number.isNaN(until.getTime())) return { error: "until: нужна дата-время ISO, например 2026-10-23T12:00:00-04:00" };
|
||
} else if (b.hours !== undefined && b.hours !== null) {
|
||
const h = Number(b.hours);
|
||
if (!(h > 0)) return { error: "hours: нужно положительное число" };
|
||
until = new Date(Date.now() + h * 3600_000);
|
||
} else if (b.days !== undefined && b.days !== null) {
|
||
const d = Number(b.days);
|
||
if (!(d > 0)) return { error: "days: нужно положительное число" };
|
||
until = new Date(Date.now() + d * 86_400_000);
|
||
}
|
||
if (until && until.getTime() <= Date.now()) return { error: "срок отключения уже в прошлом" };
|
||
if (until && until.getTime() > Date.now() + 366 * 86_400_000) return { error: "срок отключения больше года - для долгого отключения не задавайте срок (до команды владельца)" };
|
||
return { until };
|
||
};
|
||
type PauseBody = { until?: unknown; hours?: unknown; days?: unknown; reason?: string; by?: string; mode?: string };
|
||
const parseMode = (m: unknown): "passive" | "off" | null => (m === undefined || m === null || m === "" || m === "passive" ? "passive" : m === "off" ? "off" : null);
|
||
|
||
/**
|
||
* Отключить агента менеджера: на время (until / hours / days) или до команды владельца (срок не задан).
|
||
* mode: passive (по умолчанию) - сам ничего не пишет, но на сообщения менеджера отвечает как обычно; off - вообще ничего.
|
||
*/
|
||
app.post<{ Params: { id: string }; Body: PauseBody }>("/agents/:id/pause", async (req, reply) => {
|
||
if (!(await knownManager(req.params.id))) return reply.code(404).send({ error: "менеджер не найден" });
|
||
const b = req.body ?? {};
|
||
const u = parseUntil(b);
|
||
if ("error" in u) return reply.code(400).send({ error: u.error });
|
||
const mode = parseMode(b.mode);
|
||
if (!mode) return reply.code(400).send({ error: "mode: passive (по умолчанию) или off" });
|
||
await setPause(pool, req.params.id, { until: u.until, reason: b.reason ?? null, by: b.by ?? "api", mode });
|
||
return { ok: true, ...(await pauseState(pool, req.params.id)) };
|
||
});
|
||
|
||
/** Включить агента менеджера обратно. */
|
||
app.post<{ Params: { id: string } }>("/agents/:id/resume", async (req, reply) => {
|
||
if (!(await knownManager(req.params.id))) return reply.code(404).send({ error: "менеджер не найден" });
|
||
await resumeManager(pool, req.params.id);
|
||
return { ok: true, ...(await pauseState(pool, req.params.id)) };
|
||
});
|
||
|
||
/** Отключить агентов ВСЕХ активных менеджеров (на время или до команды). */
|
||
app.post<{ Body: PauseBody }>("/agents/pause-all", async (req, reply) => {
|
||
const b = req.body ?? {};
|
||
const u = parseUntil(b);
|
||
if ("error" in u) return reply.code(400).send({ error: u.error });
|
||
const mode = parseMode(b.mode);
|
||
if (!mode) return reply.code(400).send({ error: "mode: passive (по умолчанию) или off" });
|
||
const n = await setPauseAll(pool, { until: u.until, reason: b.reason ?? null, by: b.by ?? "api", mode });
|
||
return { ok: true, managers: n, mode, until: u.until };
|
||
});
|
||
|
||
app.post("/agents/resume-all", async () => ({ ok: true, managers: await resumeAll(pool) }));
|
||
|
||
/** Календарь пассивных окон по дням недели: в это время все агенты в режиме passive. */
|
||
app.get("/agents/passive-windows", async () => ({ windows: await loadWindows(pool), activeNow: await activeWindow(pool) }));
|
||
|
||
const WEEKDAYS: Record<string, number> = { mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6, sun: 7 };
|
||
const hhmm = (v: unknown, def: number): number | null => {
|
||
if (v === undefined || v === null || v === "") return def;
|
||
const m = String(v).match(/^(\d{1,2}):(\d{2})$/);
|
||
if (!m) return null;
|
||
const x = Number(m[1]) * 60 + Number(m[2]);
|
||
return x >= 0 && x <= 1440 ? x : null;
|
||
};
|
||
/** Добавить пассивное окно: weekday (1-7 или mon..sun), from/to ("HH:MM", по умолчанию весь день), timezone, note. */
|
||
app.post<{ Body: { weekday?: string | number; from?: string; to?: string; timezone?: string; note?: string } }>("/agents/passive-windows", async (req, reply) => {
|
||
const b = req.body ?? {};
|
||
const wd = typeof b.weekday === "number" ? b.weekday : (WEEKDAYS[String(b.weekday ?? "").slice(0, 3).toLowerCase()] ?? Number(b.weekday));
|
||
const from = hhmm(b.from, 0);
|
||
const to = hhmm(b.to, 1440);
|
||
if (!(wd >= 1 && wd <= 7)) return reply.code(400).send({ error: "weekday: 1-7 (1 - понедельник) или mon..sun" });
|
||
if (from === null || to === null || from >= to || from > 1439) return reply.code(400).send({ error: "from/to: время HH:MM, from меньше to (to может быть 24:00)" });
|
||
const tz = b.timezone ?? "America/New_York";
|
||
try {
|
||
new Intl.DateTimeFormat("en-US", { timeZone: tz });
|
||
} catch {
|
||
return reply.code(400).send({ error: "timezone: неизвестный часовой пояс" });
|
||
}
|
||
const { rows } = await pool.query("insert into agent_passive_window (weekday, from_minute, to_minute, timezone, note) values ($1,$2,$3,$4,$5) returning id", [wd, from, to, tz, b.note ?? null]);
|
||
return { ok: true, id: rows[0].id };
|
||
});
|
||
|
||
app.delete<{ Params: { wid: string } }>("/agents/passive-windows/:wid", async (req, reply) => {
|
||
if (!UUID.test(req.params.wid)) return reply.code(404).send({ error: "окно не найдено" });
|
||
const r = await pool.query("delete from agent_passive_window where id = $1", [req.params.wid]);
|
||
return r.rowCount ? { ok: true } : reply.code(404).send({ error: "окно не найдено" });
|
||
});
|
||
|
||
app.get<{ Params: { id: string } }>("/agents/:id/memory", async (req, reply) => {
|
||
const m = await knownManager(req.params.id);
|
||
if (!m) return reply.code(404).send({ error: "менеджер не найден" });
|
||
const mem = await loadMemory(pool, req.params.id);
|
||
const upd = (await pool.query("select updated_at from agent_manager_memory where manager_person_id = $1", [req.params.id])).rows[0];
|
||
return { managerId: req.params.id, name: m.name, memoryText: mem.memoryText, hasSession: mem.sessionId !== null, updatedAt: upd?.updated_at ?? null };
|
||
});
|
||
|
||
/**
|
||
* Запись памяти (целиком). Прежний текст сохраняется в журнале проблем (severity log, префикс `[memory-edit]`) - откат и аудит.
|
||
* `resetSession: true` дополнительно сбрасывает сессию claude: следующий запуск начнётся заново, память подаётся в промте.
|
||
*/
|
||
app.put<{ Params: { id: string }; Body: { memoryText?: string; note?: string; resetSession?: boolean } }>("/agents/:id/memory", async (req, reply) => {
|
||
const m = await knownManager(req.params.id);
|
||
if (!m) return reply.code(404).send({ error: "менеджер не найден" });
|
||
const b = req.body ?? {};
|
||
if (typeof b.memoryText !== "string") return reply.code(400).send({ error: "нужен memoryText (строка; память записывается целиком)" });
|
||
if (b.memoryText.length > 20_000) return reply.code(400).send({ error: "память слишком длинная (максимум 20000 знаков)" });
|
||
const prev = await loadMemory(pool, req.params.id);
|
||
await pool.query("insert into agent_problem_log (manager_person_id, step, severity, body) values ($1,'step4','log',$2)", [
|
||
req.params.id,
|
||
`[memory-edit] ${b.note ?? "правка памяти через API"}\n--- прежний текст памяти ---\n${prev.memoryText}`,
|
||
]);
|
||
await saveMemory(pool, req.params.id, b.memoryText);
|
||
if (b.resetSession) await pool.query("update agent_manager_memory set claude_session_id = null where manager_person_id = $1", [req.params.id]);
|
||
return { ok: true, chars: b.memoryText.length, sessionReset: b.resetSession === true };
|
||
});
|
||
|
||
app.post<{ Params: { id: string } }>("/agents/:id/session/reset", async (req, reply) => {
|
||
if (!(await knownManager(req.params.id))) return reply.code(404).send({ error: "менеджер не найден" });
|
||
await loadMemory(pool, req.params.id);
|
||
await pool.query("update agent_manager_memory set claude_session_id = null, updated_at = now() where manager_person_id = $1", [req.params.id]);
|
||
return { ok: true };
|
||
});
|
||
|
||
/** Последняя история агента: запуски (с изменениями JobTread и ошибками), обращения/логи проблем, принятые сообщения, напоминания. */
|
||
app.get<{ Params: { id: string }; Querystring: { limit?: string } }>("/agents/:id/history", async (req, reply) => {
|
||
const m = await knownManager(req.params.id);
|
||
if (!m) return reply.code(404).send({ error: "менеджер не найден" });
|
||
const limit = clampLimit(req.query.limit, 20, 100);
|
||
const q = (sql: string) => pool.query(sql, [req.params.id, limit]).then((r) => r.rows);
|
||
const [runs, problems, messages, reminders] = await Promise.all([
|
||
q("select id, step, attempt, resumed, status, started_at, finished_at, duration_ms, cost_usd, error, changes from agent_run where manager_person_id = $1 order by started_at desc limit $2"),
|
||
q("select created_at, step, severity, body from agent_problem_log where manager_person_id = $1 order by created_at desc limit $2"),
|
||
q("select received_at, channel_id, message_ts, status, has_files, sender_slack_user_id from slack_message_log where manager_person_id = $1 order by received_at desc limit $2"),
|
||
q(
|
||
`select r.reminded_at, left(r.reminder_text, 500) as reminder_text, r.reply_at, left(r.reply_summary, 300) as reply_summary
|
||
from reminder_history r join assistant_project ap on ap.id = r.assistant_project_id where ap.manager_person_id = $1 order by r.reminded_at desc limit $2`,
|
||
),
|
||
]);
|
||
return { managerId: req.params.id, name: m.name, runs, problems, messages, reminders };
|
||
});
|
||
}
|