Отключение агента менеджера: на время и до команды владельца (миграция 017, API pause/resume, события, шаг 2 и приём сообщений); тесты; docs
Some checks failed
ci / deploy (push) Has been cancelled
ci / test (push) Has been cancelled

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-19 19:56:51 +03:00
parent 3e696bb53f
commit f3e0b0618e
13 changed files with 273 additions and 22 deletions

View File

@@ -1,6 +1,7 @@
import type { FastifyInstance } from "fastify";
import type { Pool } from "khb_common";
import { loadMemory, saveMemory } from "./agents/session.js";
import { 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 => {
@@ -23,6 +24,7 @@ export function registerAgentRoutes(app: FastifyInstance, pool: Pool): void {
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.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
@@ -32,6 +34,58 @@ export function registerAgentRoutes(app: FastifyInstance, pool: Pool): void {
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 };
/** Отключить агента менеджера: на время (until / hours / days) или до команды владельца (срок не задан). Ассистент ничего не пишет и не обрабатывает его сообщения. */
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 });
await setPause(pool, req.params.id, { until: u.until, reason: b.reason ?? null, by: b.by ?? "api" });
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 n = await setPauseAll(pool, { until: u.until, reason: b.reason ?? null, by: b.by ?? "api" });
return { ok: true, managers: n, until: u.until };
});
app.post("/agents/resume-all", async () => ({ ok: true, managers: await resumeAll(pool) }));
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: "менеджер не найден" });