Режим passive при отключении агента: молчит по своей инициативе, на сообщения менеджера отвечает как обычно (миграция 018); off - вообще ничего; тесты; docs
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -24,7 +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,
|
||||
(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
|
||||
@@ -56,15 +56,21 @@ export function registerAgentRoutes(app: FastifyInstance, pool: Pool): void {
|
||||
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 };
|
||||
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) или до команды владельца (срок не задан). Ассистент ничего не пишет и не обрабатывает его сообщения. */
|
||||
/**
|
||||
* Отключить агента менеджера: на время (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 });
|
||||
await setPause(pool, req.params.id, { until: u.until, reason: b.reason ?? null, by: b.by ?? "api" });
|
||||
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)) };
|
||||
});
|
||||
|
||||
@@ -80,8 +86,10 @@ export function registerAgentRoutes(app: FastifyInstance, pool: Pool): void {
|
||||
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 };
|
||||
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) }));
|
||||
|
||||
@@ -245,17 +245,26 @@ d("консольные агенты (временная БД, фейковый
|
||||
try {
|
||||
expect(await ids()).toContain(MGR);
|
||||
|
||||
// до команды владельца (срок не задан)
|
||||
// до команды владельца (срок не задан), режим passive по умолчанию: сам молчит, на сообщения отвечает
|
||||
let r = await post("/agents/" + MGR + "/pause", { reason: "тест" });
|
||||
expect(r.json()).toMatchObject({ ok: true, paused: true, indefinite: true, until: null, reason: "тест" });
|
||||
expect(r.json()).toMatchObject({ ok: true, paused: true, mode: "passive", indefinite: true, until: null, reason: "тест" });
|
||||
expect(await ids()).not.toContain(MGR); // системные события ему не идут
|
||||
expect(await ids(true)).toContain(MGR); // ручные запуски владельца - идут
|
||||
script = [ok(["## Ответ менеджеру", "ответ пассивного", "## Память", "м"].join(nl))];
|
||||
expect(await intakeSend("7.0", "пишут пассивному")).toEqual(["ответ пассивного"]);
|
||||
expect(calls).toHaveLength(1);
|
||||
|
||||
// режим off: вообще ничего, сообщение только фиксируется
|
||||
calls = [];
|
||||
r = await post("/agents/" + MGR + "/pause", { reason: "тест off", mode: "off" });
|
||||
expect(r.json()).toMatchObject({ ok: true, paused: true, mode: "off", indefinite: true });
|
||||
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 });
|
||||
expect(listed).toMatchObject({ paused: true, paused_indefinitely: true, pause_mode: "off" });
|
||||
expect((await post("/agents/" + MGR + "/pause", { mode: "что-то" })).statusCode).toBe(400);
|
||||
|
||||
// включить обратно
|
||||
r = await post("/agents/" + MGR + "/resume");
|
||||
|
||||
@@ -2,7 +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 { NOT_OFF_SQL } from "./pause.js";
|
||||
import { writePackage } from "./inputs/package-writer.js";
|
||||
|
||||
export type PrepJob = "collect_morning" | "recheck_noon";
|
||||
@@ -69,7 +69,7 @@ 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 ${NOT_PAUSED_SQL("cm")}
|
||||
and ${NOT_OFF_SQL("cm")}
|
||||
and ($2::uuid is null or ap.id = $2)
|
||||
order by ap.created_at`,
|
||||
[deps.modes, opts.projectId ?? null],
|
||||
|
||||
@@ -1,10 +1,17 @@
|
||||
import type { Pool } from "khb_common";
|
||||
|
||||
/** Условие SQL: агент не в режиме off (passive и включённый - шаг 2 и ответы идут). */
|
||||
export const NOT_OFF_SQL = (alias = "cm"): string => `(${alias}.pause_mode = 'passive' or (not ${alias}.agent_paused and (${alias}.paused_until is null or ${alias}.paused_until <= now())))`;
|
||||
|
||||
/** Условие 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 type PauseMode = "passive" | "off";
|
||||
|
||||
export interface PauseState {
|
||||
paused: boolean;
|
||||
/** passive - молчит, пока ему не пишут (на сообщения отвечает как обычно); off - ничего не делает. */
|
||||
mode: PauseMode;
|
||||
/** true - отключён до команды владельца (без срока). */
|
||||
indefinite: boolean;
|
||||
until: Date | null;
|
||||
@@ -14,13 +21,13 @@ export interface PauseState {
|
||||
|
||||
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`,
|
||||
`select (not ${NOT_PAUSED_SQL("cm")}) as paused, cm.pause_mode, 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 };
|
||||
if (!r) return { paused: false, mode: "passive", 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 };
|
||||
return { paused, mode: r.pause_mode === "off" ? "off" : "passive", 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 {
|
||||
@@ -28,14 +35,16 @@ export interface PauseOptions {
|
||||
until?: Date | null;
|
||||
reason?: string | null;
|
||||
by?: string | null;
|
||||
/** passive (по умолчанию) - молчит, пока ему не пишут; off - вообще ничего. */
|
||||
mode?: PauseMode;
|
||||
}
|
||||
|
||||
const SET_PAUSE = `update construction_manager
|
||||
set agent_paused = $2, paused_until = $3, pause_reason = $4, paused_by = $5, paused_at = now()`;
|
||||
set agent_paused = $2, paused_until = $3, pause_reason = $4, paused_by = $5, paused_at = now(), pause_mode = $6`;
|
||||
|
||||
/** Отключает агента менеджера: на время (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]);
|
||||
const r = await pool.query(`${SET_PAUSE} where person_id = $1`, [managerId, !o.until, o.until ?? null, o.reason ?? null, o.by ?? null, o.mode ?? "passive"]);
|
||||
return (r.rowCount ?? 0) > 0;
|
||||
}
|
||||
|
||||
@@ -51,8 +60,8 @@ export async function resumeManager(pool: Pool, managerId: string): Promise<bool
|
||||
/** Отключает агентов всех активных менеджеров. Возвращает число менеджеров. */
|
||||
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],
|
||||
"update construction_manager set agent_paused = $1, paused_until = $2, pause_reason = $3, paused_by = $4, paused_at = now(), pause_mode = $5 where is_active",
|
||||
[!o.until, o.until ?? null, o.reason ?? null, o.by ?? null, o.mode ?? "passive"],
|
||||
);
|
||||
return r.rowCount ?? 0;
|
||||
}
|
||||
|
||||
@@ -146,9 +146,15 @@ export class SlackIntake {
|
||||
}
|
||||
|
||||
/** Журнал (защита от дублей) + накопление в debounce-пакет менеджера. */
|
||||
private async isOff(managerId: string): Promise<boolean> {
|
||||
const s = await pauseState(this.pool, managerId);
|
||||
return s.paused && s.mode === "off";
|
||||
}
|
||||
|
||||
private async accept(manager: ManagerInfo, msg: IncomingMessage): Promise<boolean> {
|
||||
// агент менеджера отключён (на время или до команды владельца): сообщение только фиксируется, агент не запускается и ничего не пишет
|
||||
if ((await pauseState(this.pool, manager.personId)).paused) {
|
||||
// агент в режиме off (на время или до команды владельца): сообщение только фиксируется, агент не запускается и ничего не пишет;
|
||||
// в режиме passive агент отвечает на сообщения как обычно (молчит только по своей инициативе)
|
||||
if (await this.isOff(manager.personId)) {
|
||||
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],
|
||||
@@ -184,7 +190,7 @@ 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) {
|
||||
if (await this.isOff(managerId)) {
|
||||
await setStatus("ignored");
|
||||
return;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user