Отключение агента менеджера: на время и до команды владельца (миграция 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: "менеджер не найден" });

View File

@@ -8,7 +8,10 @@ import { KeyedMutex, Semaphore } from "./agents/pool.js";
import { parseSections } from "./agents/sections.js";
import { AgentFailure, closeOrphanRuns, runManagerAgent, type AgentContext } from "./agents/session.js";
import { runStep2, saveProblems } from "./agents/step2.js";
import Fastify from "fastify";
import { registerAgentRoutes } from "./agents-api.js";
import { buildApi } from "./http-api.js";
import { listManagers } from "./managers.js";
import { handleManagerMessages } from "./slack/chat.js";
import { DriveInbox } from "./slack/drive-inbox.js";
import { SlackIntake } from "./slack/intake.js";
@@ -221,6 +224,72 @@ d("консольные агенты (временная БД, фейковый
expect(r[0].steps.runs).toHaveLength(1);
});
it("отключение агента: на время и до команды; события и сообщения менеджера не идут, после включения всё работает", async () => {
calls = [];
const app = Fastify();
registerAgentRoutes(app, db.pool);
await db.pool.query("insert into assistant_project (jt_job_id, manager_person_id, mode, is_enabled) values ('llmtest-pause',$1,'test',true)", [MGR]);
const ids = async (includePaused = false) => (await listManagers(db.pool, ["test"], { includePaused })).map((m) => m.personId);
const post = (url: string, payload?: object) => app.inject({ method: "POST", url, payload: payload ?? {} });
const nl = String.fromCharCode(10);
const intakeSend = async (ts: string, text: string) => {
const posted: string[] = [];
const deps = { ctx: ctx(), timezone: "America/New_York", slack: { postMessage: async (_c: string, x: string) => { posted.push(x); return true; }, fileInfo: async () => null, download: async () => 0 } };
const intake = new SlackIntake(deps, { channelIds: [], debounceMs: 600_000 });
await intake.onEvent({ type: "message", channel: "CLLMTEST", user: "ULLMTEST", ts, text });
await intake.flush(MGR);
await intake.idle();
intake.stop();
return posted;
};
try {
expect(await ids()).toContain(MGR);
// до команды владельца (срок не задан)
let r = await post("/agents/" + MGR + "/pause", { reason: "тест" });
expect(r.json()).toMatchObject({ ok: true, paused: true, indefinite: true, until: null, reason: "тест" });
expect(await ids()).not.toContain(MGR); // системные события ему не идут
expect(await ids(true)).toContain(MGR); // ручные запуски владельца - идут
expect(await intakeSend("7.1", "сообщение отключённому")).toEqual([]);
expect(calls).toHaveLength(0); // агент не запускался
const ignored = await db.pool.query("select status from slack_message_log where message_ts = '7.1'");
expect(ignored.rows).toEqual([{ status: "ignored" }]);
const listed = ((await app.inject("/agents")).json() as Array<Record<string, unknown>>).find((a) => a.id === MGR);
expect(listed).toMatchObject({ paused: true, paused_indefinitely: true });
// включить обратно
r = await post("/agents/" + MGR + "/resume");
expect(r.json()).toMatchObject({ ok: true, paused: false });
expect(await ids()).toContain(MGR);
script = [ok(["## Ответ менеджеру", "после включения", "## Память", "м"].join(nl))];
expect(await intakeSend("7.2", "сообщение после включения")).toEqual(["после включения"]);
// на время
r = await post("/agents/" + MGR + "/pause", { hours: 2 });
const j = r.json() as { paused: boolean; indefinite: boolean; until: string };
expect(j).toMatchObject({ paused: true, indefinite: false });
expect(new Date(j.until).getTime() - Date.now()).toBeGreaterThan(1.9 * 3600_000);
expect(await ids()).not.toContain(MGR);
await db.pool.query("update construction_manager set paused_until = now() - interval '1 minute' where person_id = $1", [MGR]); // срок истёк
expect(await ids()).toContain(MGR);
expect((await post("/agents/" + MGR + "/pause", { until: "2020-01-01T00:00:00Z" })).statusCode).toBe(400);
expect((await post("/agents/" + MGR + "/pause", { until: "не дата" })).statusCode).toBe(400);
expect((await post("/agents/" + MGR + "/pause", { days: 4000 })).statusCode).toBe(400);
expect((await post("/agents/00000000-0000-4000-8000-000000000000/pause")).statusCode).toBe(404);
// все менеджеры
const all = (await post("/agents/pause-all", { reason: "общая остановка" })).json() as { managers: number };
expect(all.managers).toBeGreaterThanOrEqual(1);
expect(await ids()).not.toContain(MGR);
expect(((await post("/agents/resume-all")).json() as { managers: number }).managers).toBeGreaterThanOrEqual(1);
expect(await ids()).toContain(MGR);
} finally {
await db.pool.query("update construction_manager set agent_paused = false, paused_until = null where person_id = $1", [MGR]);
await db.pool.query("delete from assistant_project where jt_job_id = 'llmtest-pause'");
await app.close();
}
});
it("событие ассистента: напоминание пишется в историю, ответ менеджера закрывает его; через followup агент спрашивает `что-то ещё`", async () => {
calls = [];
const posted: string[] = [];

View File

@@ -2,6 +2,7 @@ import { itNotify, localDate, MirrorNotReadyError, requireFreshTables, type Comm
import { runStep2 } from "./agents/step2.js";
import type { AgentContext } from "./agents/session.js";
import { buildItems, paramsFor } from "./inputs/build.js";
import { NOT_PAUSED_SQL } from "./pause.js";
import { writePackage } from "./inputs/package-writer.js";
export type PrepJob = "collect_morning" | "recheck_noon";
@@ -68,10 +69,10 @@ export async function runPrepJob(deps: PrepDeps, job: PrepJob, opts: { projectId
join construction_manager cm on cm.person_id = ap.manager_person_id
join person per on per.id = cm.person_id
where ap.is_enabled and ap.mode = any($1) and cm.is_active and per.is_active and per.jt_membership_id is not null
and (cm.paused_until is null or cm.paused_until < $2::date)
and ($3::uuid is null or ap.id = $3)
and ${NOT_PAUSED_SQL("cm")}
and ($2::uuid is null or ap.id = $2)
order by ap.created_at`,
[deps.modes, today, opts.projectId ?? null],
[deps.modes, opts.projectId ?? null],
);
const outcomes: ProjectOutcome[] = [];

View File

@@ -3,6 +3,7 @@ import { createLogger, createPool, itNotify, loadServiceSettings } from "khb_com
import { createCliRunner } from "./agents/cli-runner.js";
import { createLiveRunner } from "./agents/live-runner.js";
import { loadFragment } from "./agents/prompts.js";
import { listManagers } from "./managers.js";
import { KeyedMutex, Semaphore } from "./agents/pool.js";
import { closeOrphanRuns, promptSideFor, type AgentContext } from "./agents/session.js";
import { buildApi } from "./http-api.js";
@@ -45,16 +46,8 @@ const chatDeps: ChatDeps | undefined = slackApi
? { ctx, slack: slackApi, drive: service.drive ? createRcloneDrive(service.drive) : undefined, tts: service.tts ? createGoogleTts(service.tts) : undefined, defaultVoice: service.tts?.defaultVoice, timezone: common.timezone }
: undefined;
async function managers(modes: string[]): Promise<ManagerInfo[]> {
const { rows } = await pool.query(
`select distinct cm.person_id, p.display_name, cm.slack_user_id, cm.slack_channel_id, cm.reply_mode, cm.tts_voice
from construction_manager cm join person p on p.id = cm.person_id
join assistant_project ap on ap.manager_person_id = cm.person_id and ap.is_enabled and ap.mode = any($1)
where cm.is_active and p.is_active`,
[modes],
);
return rows.map(rowToManager);
}
/** Для ручных запусков владельца (simulate/apply) включаем и отключённых менеджеров; системные события идут только включённым. */
const managers = (modes: string[], includePaused = false) => listManagers(pool, modes, { includePaused });
/** Системные события по таймеру: заголовок фрагмента в p-chat-events.md. */
const EVENT_TITLE: Record<string, string> = { noon: "Напоминание 12:00", followup: "Повтор 13:00", summary: "Итог дня 16:00" };
@@ -62,7 +55,7 @@ const EVENT_TITLE: Record<string, string> = { noon: "Напоминание 12:0
const chat = chatDeps
? {
async simulate(o: { managerId?: string; text: string; files?: string[]; publish?: boolean }) {
const all = await managers(service.modes);
const all = await managers(service.modes, true);
const m = o.managerId ? all.find((x) => x.personId === o.managerId) : all[0];
if (!m) throw new Error("менеджер не найден");
return handleManagerMessages(
@@ -72,7 +65,7 @@ const chat = chatDeps
);
},
async apply(o: { managerId: string; text: string; publish?: boolean }) {
const m = (await managers(service.modes)).find((x) => x.personId === o.managerId);
const m = (await managers(service.modes, true)).find((x) => x.personId === o.managerId);
if (!m) throw new Error("менеджер не найден");
return handleManagerMessages({ ...chatDeps, dryPublish: !o.publish }, m, [], { systemEvent: o.text });
},

View File

@@ -0,0 +1,19 @@
import type { Pool } from "khb_common";
import { NOT_PAUSED_SQL } from "./pause.js";
import { rowToManager } from "./slack/intake.js";
import type { ManagerInfo } from "./slack/chat.js";
/**
* Менеджеры с включённым проектом нужного режима. По умолчанию без отключённых (пауза на время или до команды): системные события им не идут.
* Для ручных запусков владельца (simulate/apply) отключённых можно включить в список (`includePaused`).
*/
export async function listManagers(pool: Pool, modes: string[], opts: { includePaused?: boolean } = {}): Promise<ManagerInfo[]> {
const { rows } = await pool.query(
`select distinct cm.person_id, p.display_name, cm.slack_user_id, cm.slack_channel_id, cm.reply_mode, cm.tts_voice
from construction_manager cm join person p on p.id = cm.person_id
join assistant_project ap on ap.manager_person_id = cm.person_id and ap.is_enabled and ap.mode = any($1)
where cm.is_active and p.is_active${opts.includePaused ? "" : ` and ${NOT_PAUSED_SQL("cm")}`}`,
[modes],
);
return rows.map(rowToManager);
}

View File

@@ -0,0 +1,63 @@
import type { Pool } from "khb_common";
/** Условие SQL: агент менеджера включён (не отключён бессрочно и срок отключения истёк). */
export const NOT_PAUSED_SQL = (alias = "cm"): string => `(not ${alias}.agent_paused and (${alias}.paused_until is null or ${alias}.paused_until <= now()))`;
export interface PauseState {
paused: boolean;
/** true - отключён до команды владельца (без срока). */
indefinite: boolean;
until: Date | null;
reason: string | null;
by: string | null;
}
export async function pauseState(pool: Pool, managerId: string): Promise<PauseState> {
const { rows } = await pool.query(
`select (not ${NOT_PAUSED_SQL("cm")}) as paused, cm.agent_paused, cm.paused_until, cm.pause_reason, cm.paused_by from construction_manager cm where cm.person_id = $1`,
[managerId],
);
const r = rows[0];
if (!r) return { paused: false, indefinite: false, until: null, reason: null, by: null };
const paused = r.paused === true;
return { paused, indefinite: paused && r.agent_paused === true, until: paused && !r.agent_paused ? (r.paused_until as Date) : null, reason: paused ? (r.pause_reason as string | null) : null, by: paused ? (r.paused_by as string | null) : null };
}
export interface PauseOptions {
/** Срок отключения; null/не задан - до команды владельца. */
until?: Date | null;
reason?: string | null;
by?: string | null;
}
const SET_PAUSE = `update construction_manager
set agent_paused = $2, paused_until = $3, pause_reason = $4, paused_by = $5, paused_at = now()`;
/** Отключает агента менеджера: на время (until) или до команды (until не задан). Возвращает false, если менеджера нет. */
export async function setPause(pool: Pool, managerId: string, o: PauseOptions = {}): Promise<boolean> {
const r = await pool.query(`${SET_PAUSE} where person_id = $1`, [managerId, !o.until, o.until ?? null, o.reason ?? null, o.by ?? null]);
return (r.rowCount ?? 0) > 0;
}
/** Включает агента менеджера обратно. */
export async function resumeManager(pool: Pool, managerId: string): Promise<boolean> {
const r = await pool.query(
"update construction_manager set agent_paused = false, paused_until = null, pause_reason = null, paused_by = null, paused_at = null where person_id = $1",
[managerId],
);
return (r.rowCount ?? 0) > 0;
}
/** Отключает агентов всех активных менеджеров. Возвращает число менеджеров. */
export async function setPauseAll(pool: Pool, o: PauseOptions = {}): Promise<number> {
const r = await pool.query(
"update construction_manager set agent_paused = $1, paused_until = $2, pause_reason = $3, paused_by = $4, paused_at = now() where is_active",
[!o.until, o.until ?? null, o.reason ?? null, o.by ?? null],
);
return r.rowCount ?? 0;
}
export async function resumeAll(pool: Pool): Promise<number> {
const r = await pool.query("update construction_manager set agent_paused = false, paused_until = null, pause_reason = null, paused_by = null, paused_at = null where agent_paused or paused_until is not null");
return r.rowCount ?? 0;
}

View File

@@ -1,6 +1,7 @@
import type { Pool } from "khb_common";
import { isReplyMode } from "./tts.js";
import { loadFragment } from "../agents/prompts.js";
import { pauseState } from "../pause.js";
import { promptSideFor } from "../agents/session.js";
import { handleManagerMessages, type ChatDeps, type IncomingMessage, type ManagerInfo, type ProjectContext } from "./chat.js";
@@ -146,6 +147,14 @@ export class SlackIntake {
/** Журнал (защита от дублей) + накопление в debounce-пакет менеджера. */
private async accept(manager: ManagerInfo, msg: IncomingMessage): Promise<boolean> {
// агент менеджера отключён (на время или до команды владельца): сообщение только фиксируется, агент не запускается и ничего не пишет
if ((await pauseState(this.pool, manager.personId)).paused) {
await this.pool.query(
"insert into slack_message_log (channel_id, message_ts, manager_person_id, has_files, status, sender_slack_user_id, processed_at) values ($1,$2,$3,$4,'ignored',$5, now()) on conflict do nothing",
[msg.channel, msg.ts, manager.personId, msg.fileIds.length > 0 || (msg.localFiles?.length ?? 0) > 0, msg.senderUserId ?? null],
);
return false;
}
const ins = await this.pool.query(
"insert into slack_message_log (channel_id, message_ts, manager_person_id, has_files, status, sender_slack_user_id) values ($1,$2,$3,$4,'received',$5) on conflict do nothing returning message_ts",
[msg.channel, msg.ts, manager.personId, msg.fileIds.length > 0 || (msg.localFiles?.length ?? 0) > 0, msg.senderUserId ?? null],
@@ -175,6 +184,10 @@ export class SlackIntake {
const keys = p.messages.map((m) => [m.channel, m.ts] as const);
const setStatus = (status: string) =>
Promise.all(keys.map(([c, t]) => this.pool.query("update slack_message_log set status = $3, processed_at = case when $3 in ('done','failed') then now() else null end where channel_id = $1 and message_ts = $2", [c, t, status])));
if ((await pauseState(this.pool, managerId)).paused) {
await setStatus("ignored");
return;
}
await setStatus("processing");
try {
await handleManagerMessages(this.deps, p.manager, p.messages);
@@ -193,17 +206,21 @@ export class SlackIntake {
const t = setTimeout(() => {
this.followups.delete(manager.personId);
this.track(
handleManagerMessages(this.deps, manager, [], {
systemEvent: loadFragment("p-chat-events.md", "Что-то ещё?", {}, promptSideFor(this.deps.ctx, manager.personId)),
}).then(
() => undefined,
() => undefined,
),
pauseState(this.pool, manager.personId).then((s) => (s.paused ? undefined : this.runFollowup(manager))),
);
}, this.opts.followupMs);
this.followups.set(manager.personId, t);
}
private runFollowup(manager: ManagerInfo): Promise<void> {
return handleManagerMessages(this.deps, manager, [], {
systemEvent: loadFragment("p-chat-events.md", "Что-то ещё?", {}, promptSideFor(this.deps.ctx, manager.personId)),
}).then(
() => undefined,
() => undefined,
);
}
/** Дождаться текущих обработок (тесты, остановка). */
async idle(): Promise<void> {
while (this.inflight.size) await Promise.allSettled([...this.inflight]);