Долгоживущий агент чата (только для managerIds, тестовый менеджер) и тайминг чата (chat_timing, миграция 016); тесты; docs
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
40
packages/khb_common/migrations/016_chat_timing.sql
Normal file
40
packages/khb_common/migrations/016_chat_timing.sql
Normal file
@@ -0,0 +1,40 @@
|
||||
-- Тайминг обработки запроса в чате ассистента: от сообщения в Slack до ответа в Slack, по этапам (диагностика медленных ответов).
|
||||
create table chat_timing (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
created_at timestamptz not null default now(),
|
||||
manager_person_id uuid references construction_manager(person_id),
|
||||
channel_id text,
|
||||
kind text not null check (kind in ('message', 'event')),
|
||||
agent_version text not null check (agent_version in ('classic', 'live')),
|
||||
status text not null check (status in ('ok', 'failed')),
|
||||
error text,
|
||||
message_ts text,
|
||||
message_at timestamptz, -- время первого сообщения пакета в Slack (из ts)
|
||||
received_at timestamptz, -- когда сообщение принято сервисом (журнал slack_message_log)
|
||||
started_at timestamptz not null, -- начало обработки пакета (после ожидания debounce)
|
||||
reply_slack_ts text, -- ts ответа ассистента, полученный от Slack
|
||||
reply_at timestamptz, -- время ответа в Slack (из reply_slack_ts)
|
||||
slack_in_ms integer, -- Slack -> сервис (received_at - message_at)
|
||||
debounce_ms integer, -- ожидание накопления сообщений (started_at - received_at)
|
||||
inputs_ms integer, -- история напоминаний и вложения (скачивание)
|
||||
drive_ms integer, -- выгрузка исходников в Drive
|
||||
prompt_ms integer, -- сборка промта (запросы к БД, текст)
|
||||
prompt_chars integer,
|
||||
queue_ms integer, -- ожидание очереди менеджера и пула агентов
|
||||
start_ms integer, -- старт процесса агента и прогрев (live; для classic не измеряется отдельно)
|
||||
model_ms integer, -- от отправки промта до результата (все попытки)
|
||||
api_ms integer, -- время запросов к API модели по данным claude
|
||||
first_event_ms integer, -- до первого события хода (live)
|
||||
tool_calls integer,
|
||||
num_turns integer,
|
||||
attempts integer, -- вызовов модели (повторы "исправь формат")
|
||||
cost_usd numeric(10, 4),
|
||||
post_ms integer, -- сохранение памяти, проблем, истории
|
||||
publish_ms integer, -- отправка ответа в Slack (с озвучиванием)
|
||||
final_ms integer, -- повторная выгрузка в Drive после ответа
|
||||
processing_ms integer, -- вся обработка пакета (started_at -> конец)
|
||||
total_ms integer, -- от сообщения в Slack до ответа в Slack (message_at -> reply_at)
|
||||
steps jsonb -- подробности: вызовы модели с таймингом
|
||||
);
|
||||
create index chat_timing_manager_idx on chat_timing (manager_person_id, created_at desc);
|
||||
alter table chat_timing enable row level security;
|
||||
@@ -167,6 +167,56 @@ d("консольные агенты (временная БД, фейковый
|
||||
}
|
||||
});
|
||||
|
||||
it("новая версия агента: только для менеджеров из agent.live.managerIds; в диалоге промт короткий (без инструкций, списка и памяти)", async () => {
|
||||
calls = [];
|
||||
const liveCalls: ClaudeCall[] = [];
|
||||
let active = false;
|
||||
const liveRunner = {
|
||||
run: async (c: ClaudeCall) => { liveCalls.push(c); active = true; return { text: "## Ответ менеджеру\n(без ответа)\n## Память\nлайв-память", sessionId: c.sessionId }; },
|
||||
isActive: () => active, close: () => { active = false; }, closeAll: () => undefined, activeCount: () => (active ? 1 : 0),
|
||||
};
|
||||
const base = ctx();
|
||||
const liveCtx = { ...base, liveRunner, settings: { ...base.settings, live: { managerIds: [MGR], idleMinutes: 10, warmupSeconds: 0 } } };
|
||||
const slack = { postMessage: async () => true, fileInfo: async () => null, download: async () => 0 };
|
||||
const mgr = { personId: MGR, name: "llmtest-Manager", slackUserId: "ULLMTEST", slackChannelId: "CLLMTEST" };
|
||||
const msg = (text: string, ts: string) => [{ channel: "CLLMTEST", ts, text, fileIds: [] }];
|
||||
await handleManagerMessages({ ctx: liveCtx, timezone: "America/New_York", slack, dryPublish: true }, mgr, msg("первое сообщение", "1791741300.000001"));
|
||||
await handleManagerMessages({ ctx: liveCtx, timezone: "America/New_York", slack, dryPublish: true }, mgr, msg("второе сообщение", "1791741310.000001"));
|
||||
expect(calls).toHaveLength(0); // прежний раннер не использовался
|
||||
expect(liveCalls).toHaveLength(2);
|
||||
expect(liveCalls[0]!.prompt).toContain("# Память");
|
||||
expect(liveCalls[0]!.prompt).toContain("ToolSearch с запросом select:mcp__claude_ai_JobTread__query");
|
||||
expect(liveCalls[1]!.prompt).toContain("# Продолжение диалога");
|
||||
expect(liveCalls[1]!.prompt).toContain("второе сообщение");
|
||||
expect(liveCalls[1]!.prompt).not.toContain("\n# Память\n");
|
||||
expect(liveCalls[1]!.prompt).not.toContain("# Список задач на сегодня");
|
||||
// менеджер не из списка: прежняя версия, полный промт каждый раз
|
||||
script = [ok("## Ответ менеджеру\n(без ответа)\n## Память\nм")];
|
||||
const other = { ...liveCtx, settings: { ...liveCtx.settings, live: { managerIds: ["other"], idleMinutes: 10, warmupSeconds: 0 } } };
|
||||
await handleManagerMessages({ ctx: other, timezone: "America/New_York", slack, dryPublish: true }, mgr, msg("третье", "1791741320.000001"));
|
||||
expect(liveCalls).toHaveLength(2);
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0]!.prompt).toContain("# Память");
|
||||
});
|
||||
|
||||
it("тайминг чата: строка chat_timing с этапами от сообщения в Slack до ответа в Slack", async () => {
|
||||
calls = [];
|
||||
const reply = ["## Ответ менеджеру", "тайминг", "## Память", "м"].join(String.fromCharCode(10));
|
||||
script = [async (c) => ({ text: reply, sessionId: c.sessionId, costUsd: 0.05, timing: { startMs: 50, turnMs: 1234, apiMs: 1000, numTurns: 3, toolCalls: 2 } })];
|
||||
await db.pool.query("delete from chat_timing");
|
||||
await db.pool.query("insert into slack_message_log (channel_id, message_ts, manager_person_id, status, received_at) values ('CLLMTEST','1791741990.000001',$1,'received', to_timestamp(1791741991.5))", [MGR]);
|
||||
const slack = { postMessage: async () => true, postMessageTs: async () => "1791741999.000100", fileInfo: async () => null, download: async () => 0 };
|
||||
const mgr = { personId: MGR, name: "llmtest-Manager", slackUserId: "ULLMTEST", slackChannelId: "CLLMTEST" };
|
||||
await handleManagerMessages({ ctx: ctx(), timezone: "America/New_York", slack }, mgr, [{ channel: "CLLMTEST", ts: "1791741990.000001", text: "замер", fileIds: [] }]);
|
||||
const r = (await db.pool.query("select * from chat_timing")).rows;
|
||||
expect(r).toHaveLength(1);
|
||||
expect(r[0]).toMatchObject({ kind: "message", agent_version: "classic", status: "ok", reply_slack_ts: "1791741999.000100", slack_in_ms: 1500, total_ms: 9000, model_ms: 1234, start_ms: 50, api_ms: 1000, num_turns: 3, tool_calls: 2, attempts: 1 });
|
||||
expect(Number(r[0].cost_usd)).toBeCloseTo(0.05);
|
||||
for (const k of ["inputs_ms", "drive_ms", "prompt_ms", "queue_ms", "post_ms", "publish_ms", "final_ms", "processing_ms"]) expect(r[0][k], k).not.toBeNull();
|
||||
expect(r[0].prompt_chars).toBeGreaterThan(100);
|
||||
expect(r[0].steps.runs).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("событие ассистента: напоминание пишется в историю, ответ менеджера закрывает его; через followup агент спрашивает `что-то ещё`", async () => {
|
||||
calls = [];
|
||||
const posted: string[] = [];
|
||||
|
||||
@@ -12,11 +12,27 @@ export interface ClaudeCall {
|
||||
tools: ToolSet;
|
||||
}
|
||||
|
||||
/** Тайминг одного хода агента (для диагностики медленных ответов). */
|
||||
export interface TurnTiming {
|
||||
/** Старт процесса агента и прогрев до отправки промта (0 - процесс уже работал; undefined - классика, не измеряется отдельно). */
|
||||
startMs?: number;
|
||||
/** От отправки промта до результата (для классики - весь запуск процесса). */
|
||||
turnMs?: number;
|
||||
/** Время запросов к API модели по данным claude (duration_api_ms) и общее время хода по данным claude (duration_ms). */
|
||||
apiMs?: number;
|
||||
claudeMs?: number;
|
||||
numTurns?: number;
|
||||
/** Число вызовов инструментов и время до первого события хода (только долгоживущий агент). */
|
||||
toolCalls?: number;
|
||||
firstEventMs?: number;
|
||||
}
|
||||
|
||||
export interface ClaudeResult {
|
||||
text: string;
|
||||
sessionId: string;
|
||||
costUsd?: number;
|
||||
durationMs?: number;
|
||||
timing?: TurnTiming;
|
||||
}
|
||||
|
||||
export type ClaudeRunner = (call: ClaudeCall) => Promise<ClaudeResult>;
|
||||
@@ -37,7 +53,7 @@ export interface CliRunnerOptions {
|
||||
}
|
||||
|
||||
/** Инструменты шага 4: Bash (ffmpeg, whisper, exiftool, rclone), ToolSearch и запросы JobTread через коннектор claude.ai. */
|
||||
const CHAT_TOOLS = ["--tools", "Bash,ToolSearch", "--allowedTools", "Bash", "ToolSearch", "mcp__claude_ai_JobTread__query", "--permission-mode", "acceptEdits"];
|
||||
export const CHAT_TOOLS = ["--tools", "Bash,ToolSearch", "--allowedTools", "Bash", "ToolSearch", "mcp__claude_ai_JobTread__query", "--permission-mode", "acceptEdits"];
|
||||
|
||||
/** Запуск консольного агента `claude -p`: промт через stdin, ответ - JSON (result, session_id, total_cost_usd). */
|
||||
export function createCliRunner(opts: CliRunnerOptions): ClaudeRunner {
|
||||
@@ -48,6 +64,7 @@ export function createCliRunner(opts: CliRunnerOptions): ClaudeRunner {
|
||||
if (opts.model) args.push("--model", opts.model);
|
||||
args.push(...(call.tools === "chat" ? CHAT_TOOLS : ["--tools", ""]));
|
||||
const child = spawn(opts.bin, args, { cwd: call.cwd, stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, ANTHROPIC_API_KEY: "" } });
|
||||
const tStart = Date.now();
|
||||
let out = "";
|
||||
let err = "";
|
||||
let timedOut = false;
|
||||
@@ -69,9 +86,12 @@ export function createCliRunner(opts: CliRunnerOptions): ClaudeRunner {
|
||||
return reject(new ClaudeError(`claude exit=${code}: ${msg}`, /No conversation found/i.test(msg) ? "no_session" : "failed"));
|
||||
}
|
||||
try {
|
||||
const j = JSON.parse(out) as { result?: string; session_id?: string; total_cost_usd?: number; duration_ms?: number; is_error?: boolean };
|
||||
const j = JSON.parse(out) as { result?: string; session_id?: string; total_cost_usd?: number; duration_ms?: number; duration_api_ms?: number; num_turns?: number; is_error?: boolean };
|
||||
if (j.is_error) return reject(new ClaudeError(`claude вернул ошибку: ${String(j.result).slice(0, 300)}`, "failed"));
|
||||
resolve({ text: j.result ?? "", sessionId: j.session_id ?? call.sessionId, costUsd: j.total_cost_usd, durationMs: j.duration_ms });
|
||||
resolve({
|
||||
text: j.result ?? "", sessionId: j.session_id ?? call.sessionId, costUsd: j.total_cost_usd, durationMs: j.duration_ms,
|
||||
timing: { turnMs: Date.now() - tStart, apiMs: j.duration_api_ms, claudeMs: j.duration_ms, numTurns: j.num_turns },
|
||||
});
|
||||
} catch {
|
||||
reject(new ClaudeError(`не удалось разобрать ответ claude: ${out.slice(0, 200)}`, "failed"));
|
||||
}
|
||||
|
||||
216
packages/khbuild_assistant_prep/src/agents/live-runner.ts
Normal file
216
packages/khbuild_assistant_prep/src/agents/live-runner.ts
Normal file
@@ -0,0 +1,216 @@
|
||||
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import { mkdirSync } from "node:fs";
|
||||
import { ClaudeError, CHAT_TOOLS, type ClaudeCall, type ClaudeResult, type ClaudeRunner } from "./cli-runner.js";
|
||||
|
||||
export interface LiveRunnerOptions {
|
||||
bin: string;
|
||||
/** Аргументы перед флагами claude (тесты запускают node + фейковый скрипт). */
|
||||
prefixArgs?: string[];
|
||||
model?: string;
|
||||
/** Таймаут одного хода (сообщение -> результат). */
|
||||
timeoutMs: number;
|
||||
/** Через сколько мс после последнего результата процесс закрывается (stdin закрывается, агент завершается сам). */
|
||||
idleMs: number;
|
||||
/** Пауза после старта процесса перед первым промтом: за это время поднимаются коннекторы claude.ai (JobTread и др.). */
|
||||
warmupMs: number;
|
||||
onEvent?: (e: { kind: "start" | "idle_close" | "exit" | "kill"; cwd: string; sessionId: string; info?: string }) => void;
|
||||
}
|
||||
|
||||
export interface LiveRunner {
|
||||
run: ClaudeRunner;
|
||||
/** Есть ли живой процесс агента в этой папке (т.е. агент уже в диалоге и помнит инструкции). */
|
||||
isActive(cwd: string): boolean;
|
||||
/** Закрыть процесс агента (следующий ход стартует новый процесс с --resume). */
|
||||
close(cwd: string): void;
|
||||
closeAll(): void;
|
||||
activeCount(): number;
|
||||
}
|
||||
|
||||
interface Turn {
|
||||
startMs: number;
|
||||
toolCalls: number;
|
||||
firstEventMs: number | null;
|
||||
resolve(r: ClaudeResult): void;
|
||||
reject(e: Error): void;
|
||||
timer: NodeJS.Timeout;
|
||||
startedAt: number;
|
||||
}
|
||||
|
||||
interface Proc {
|
||||
cwd: string;
|
||||
sessionId: string;
|
||||
child: ChildProcessWithoutNullStreams;
|
||||
buf: string;
|
||||
stderr: string;
|
||||
turn: Turn | null;
|
||||
idle: NodeJS.Timeout | null;
|
||||
exited: boolean;
|
||||
lastCost: number;
|
||||
ready: Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Долгоживущий агент: один процесс `claude -p --input-format stream-json` на менеджера. Ответ на ход - событие `result`;
|
||||
* после него процесс не завершается и ждёт следующее сообщение в stdin. Закрывается через idleMs без новых ходов.
|
||||
* Если процесса нет (первый ход, простой, падение), стартует новый с --resume/--session-id и ждёт warmupMs.
|
||||
*/
|
||||
export function createLiveRunner(opts: LiveRunnerOptions): LiveRunner {
|
||||
const procs = new Map<string, Proc>();
|
||||
|
||||
const clearIdle = (p: Proc) => {
|
||||
if (p.idle) clearTimeout(p.idle);
|
||||
p.idle = null;
|
||||
};
|
||||
const armIdle = (p: Proc) => {
|
||||
clearIdle(p);
|
||||
p.idle = setTimeout(() => {
|
||||
if (p.exited || p.turn) return;
|
||||
opts.onEvent?.({ kind: "idle_close", cwd: p.cwd, sessionId: p.sessionId });
|
||||
p.child.stdin.end(); // агент завершается сам (код 0)
|
||||
}, opts.idleMs);
|
||||
p.idle.unref?.();
|
||||
};
|
||||
|
||||
function onLine(p: Proc, line: string): void {
|
||||
let o: Record<string, unknown>;
|
||||
try {
|
||||
o = JSON.parse(line) as Record<string, unknown>;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (o.type === "system" && o.subtype === "init" && typeof o.session_id === "string") p.sessionId = o.session_id;
|
||||
if (p.turn) {
|
||||
if (p.turn.firstEventMs === null) p.turn.firstEventMs = Date.now() - p.turn.startedAt;
|
||||
if (o.type === "assistant") {
|
||||
const content = (o.message as { content?: Array<{ type?: string }> } | undefined)?.content;
|
||||
if (Array.isArray(content)) p.turn.toolCalls += content.filter((b) => b.type === "tool_use").length;
|
||||
}
|
||||
}
|
||||
if (o.type !== "result" || !p.turn) return;
|
||||
const t = p.turn;
|
||||
p.turn = null;
|
||||
clearTimeout(t.timer);
|
||||
if (typeof o.session_id === "string") p.sessionId = o.session_id;
|
||||
const total = typeof o.total_cost_usd === "number" ? o.total_cost_usd : undefined;
|
||||
const cost = total === undefined ? undefined : Math.max(0, total - p.lastCost);
|
||||
if (total !== undefined) p.lastCost = total;
|
||||
armIdle(p);
|
||||
if (o.is_error === true) return t.reject(new ClaudeError(`claude вернул ошибку: ${String(o.result).slice(0, 300)}`, "failed"));
|
||||
t.resolve({
|
||||
text: String(o.result ?? ""), sessionId: p.sessionId, costUsd: cost, durationMs: typeof o.duration_ms === "number" ? o.duration_ms : Date.now() - t.startedAt,
|
||||
timing: {
|
||||
startMs: t.startMs, turnMs: Date.now() - t.startedAt, apiMs: typeof o.duration_api_ms === "number" ? o.duration_api_ms : undefined,
|
||||
claudeMs: typeof o.duration_ms === "number" ? o.duration_ms : undefined, numTurns: typeof o.num_turns === "number" ? o.num_turns : undefined,
|
||||
toolCalls: t.toolCalls, firstEventMs: t.firstEventMs ?? undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function spawnProc(call: ClaudeCall): Proc {
|
||||
mkdirSync(call.cwd, { recursive: true });
|
||||
const args = [
|
||||
...(opts.prefixArgs ?? []),
|
||||
"-p", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose",
|
||||
call.resume ? "--resume" : "--session-id", call.sessionId,
|
||||
];
|
||||
if (opts.model) args.push("--model", opts.model);
|
||||
args.push(...CHAT_TOOLS);
|
||||
const child = spawn(opts.bin, args, { cwd: call.cwd, stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, ANTHROPIC_API_KEY: "" } });
|
||||
const p: Proc = { cwd: call.cwd, sessionId: call.sessionId, child, buf: "", stderr: "", turn: null, idle: null, exited: false, lastCost: 0, ready: Promise.resolve() };
|
||||
child.stdout.on("data", (d) => {
|
||||
p.buf += d;
|
||||
let i: number;
|
||||
while ((i = p.buf.indexOf("\n")) >= 0) {
|
||||
const line = p.buf.slice(0, i).trim();
|
||||
p.buf = p.buf.slice(i + 1);
|
||||
if (line) onLine(p, line);
|
||||
}
|
||||
});
|
||||
child.stderr.on("data", (d) => (p.stderr = (p.stderr + d).slice(-2000)));
|
||||
child.stdin.on("error", () => undefined);
|
||||
const fail = (e: ClaudeError) => {
|
||||
if (!p.turn) return;
|
||||
const t = p.turn;
|
||||
p.turn = null;
|
||||
clearTimeout(t.timer);
|
||||
t.reject(e);
|
||||
};
|
||||
child.on("error", (e) => {
|
||||
p.exited = true;
|
||||
clearIdle(p);
|
||||
if (procs.get(p.cwd) === p) procs.delete(p.cwd);
|
||||
fail(new ClaudeError(`не удалось запустить ${opts.bin}: ${e.message}`, "failed"));
|
||||
});
|
||||
child.on("close", (code) => {
|
||||
p.exited = true;
|
||||
clearIdle(p);
|
||||
if (procs.get(p.cwd) === p) procs.delete(p.cwd);
|
||||
opts.onEvent?.({ kind: "exit", cwd: p.cwd, sessionId: p.sessionId, info: `code=${code}` });
|
||||
const msg = `${p.stderr}${p.buf}`.slice(0, 500);
|
||||
fail(new ClaudeError(`claude завершился (exit=${code}) до ответа: ${msg}`, /No conversation found/i.test(msg) ? "no_session" : "failed"));
|
||||
});
|
||||
opts.onEvent?.({ kind: "start", cwd: p.cwd, sessionId: p.sessionId });
|
||||
// коннекторы claude.ai поднимаются отдельно от старта процесса: даём им время до первого промта
|
||||
p.ready = new Promise((r) => setTimeout(r, opts.warmupMs));
|
||||
return p;
|
||||
}
|
||||
|
||||
const kill = (p: Proc, why: string) => {
|
||||
clearIdle(p);
|
||||
if (!p.exited) {
|
||||
opts.onEvent?.({ kind: "kill", cwd: p.cwd, sessionId: p.sessionId, info: why });
|
||||
p.child.kill("SIGKILL");
|
||||
}
|
||||
};
|
||||
|
||||
const run: ClaudeRunner = async (call) => {
|
||||
const tCall = Date.now();
|
||||
let p = procs.get(call.cwd);
|
||||
if (p && (p.exited || p.sessionId !== call.sessionId)) {
|
||||
kill(p, "смена сессии");
|
||||
procs.delete(call.cwd);
|
||||
p = undefined;
|
||||
}
|
||||
if (p?.turn) throw new ClaudeError("предыдущий ход агента ещё не завершён", "failed");
|
||||
if (!p) {
|
||||
p = spawnProc(call);
|
||||
procs.set(call.cwd, p);
|
||||
}
|
||||
clearIdle(p);
|
||||
const proc = p;
|
||||
await proc.ready;
|
||||
if (proc.exited) throw new ClaudeError(`агент завершился до первого промта: ${proc.stderr.slice(0, 300)}`, /No conversation found/i.test(proc.stderr) ? "no_session" : "failed");
|
||||
return new Promise<ClaudeResult>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
proc.turn = null;
|
||||
kill(proc, "таймаут хода");
|
||||
procs.delete(call.cwd);
|
||||
reject(new ClaudeError(`таймаут ${opts.timeoutMs} мс`, "timeout"));
|
||||
}, opts.timeoutMs);
|
||||
proc.turn = { resolve, reject, timer, startedAt: Date.now(), startMs: Date.now() - tCall, toolCalls: 0, firstEventMs: null };
|
||||
proc.child.stdin.write(JSON.stringify({ type: "user", message: { role: "user", content: call.prompt } }) + "\n");
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
run,
|
||||
isActive: (cwd) => {
|
||||
const p = procs.get(cwd);
|
||||
return !!p && !p.exited;
|
||||
},
|
||||
close: (cwd) => {
|
||||
const p = procs.get(cwd);
|
||||
if (p) {
|
||||
procs.delete(cwd);
|
||||
kill(p, "закрыт по запросу");
|
||||
}
|
||||
},
|
||||
closeAll: () => {
|
||||
for (const [cwd, p] of procs) {
|
||||
procs.delete(cwd);
|
||||
kill(p, "остановка сервиса");
|
||||
}
|
||||
},
|
||||
activeCount: () => procs.size,
|
||||
};
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
import type { Logger, Pool } from "khb_common";
|
||||
import { ClaudeError, type ClaudeResult, type ClaudeRunner, type ToolSet } from "./cli-runner.js";
|
||||
import { ClaudeError, type ClaudeResult, type ClaudeRunner, type ToolSet, type TurnTiming } from "./cli-runner.js";
|
||||
import type { LiveRunner } from "./live-runner.js";
|
||||
import { KeyedMutex, Semaphore } from "./pool.js";
|
||||
import { missingSections, parseSections } from "./sections.js";
|
||||
import type { AgentSettings } from "../settings.js";
|
||||
@@ -11,21 +12,37 @@ export interface AgentContext {
|
||||
log: Logger;
|
||||
settings: AgentSettings;
|
||||
runner: ClaudeRunner;
|
||||
/** Новая версия агента чата: долгоживущие процессы (только для менеджеров из agent.live.managerIds). */
|
||||
liveRunner?: LiveRunner;
|
||||
gate: Semaphore;
|
||||
locks: KeyedMutex;
|
||||
/** Сообщение ИТ-команде (Slack); ошибки отправки не должны ломать обработку. */
|
||||
notifyIt(text: string): Promise<void>;
|
||||
}
|
||||
|
||||
export class AgentFailure extends Error {}
|
||||
/** Тайминг запуска агента: ожидание очереди и каждый вызов модели (с повторами формата). */
|
||||
export interface AgentTiming {
|
||||
queueMs: number;
|
||||
live: boolean;
|
||||
runs: Array<{ wallMs: number; timing?: TurnTiming; costUsd?: number; error?: string }>;
|
||||
}
|
||||
|
||||
export class AgentFailure extends Error {
|
||||
timing?: AgentTiming;
|
||||
}
|
||||
|
||||
export interface AgentOutcome {
|
||||
text: string;
|
||||
sections: Map<string, string>;
|
||||
sessionId: string;
|
||||
attempts: number;
|
||||
timing: AgentTiming;
|
||||
}
|
||||
|
||||
/** Работает ли для менеджера новая (долгоживущая) версия агента чата. */
|
||||
export const useLive = (ctx: Pick<AgentContext, "liveRunner" | "settings">, managerId: string): boolean =>
|
||||
!!ctx.liveRunner && (ctx.settings.live?.managerIds ?? []).includes(managerId);
|
||||
|
||||
export const managerWorkDir = (s: AgentSettings, managerId: string) => join(s.workRoot, managerId);
|
||||
|
||||
/** Текущая память менеджера (создаёт пустую запись при первом обращении). */
|
||||
@@ -78,9 +95,26 @@ export function runManagerAgent(
|
||||
ctx: AgentContext,
|
||||
opts: { managerId: string; step: "step2" | "step4"; tools: ToolSet; prompt: string; required: string[] },
|
||||
): Promise<AgentOutcome> {
|
||||
const tEnter = Date.now();
|
||||
return ctx.locks.run(opts.managerId, () =>
|
||||
ctx.gate.run(async () => {
|
||||
const timing: AgentTiming = { queueMs: Date.now() - tEnter, live: false, runs: [] };
|
||||
const cwd = managerWorkDir(ctx.settings, opts.managerId);
|
||||
const live = opts.tools === "chat" && useLive(ctx, opts.managerId);
|
||||
timing.live = live;
|
||||
const base: ClaudeRunner = live ? ctx.liveRunner!.run : ctx.runner;
|
||||
const run: ClaudeRunner = async (c) => {
|
||||
const t = Date.now();
|
||||
try {
|
||||
const r = await base(c);
|
||||
timing.runs.push({ wallMs: Date.now() - t, timing: r.timing, costUsd: r.costUsd });
|
||||
return r;
|
||||
} catch (e) {
|
||||
timing.runs.push({ wallMs: Date.now() - t, error: String(e).slice(0, 200) });
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
const fail = (msg: string) => Object.assign(new AgentFailure(msg), { timing });
|
||||
const mem = await loadMemory(ctx.pool, opts.managerId);
|
||||
let sessionId = mem.sessionId ?? randomUUID();
|
||||
let resume = mem.sessionId !== null;
|
||||
@@ -91,7 +125,7 @@ export function runManagerAgent(
|
||||
let res: ClaudeResult;
|
||||
try {
|
||||
try {
|
||||
res = await ctx.runner({ prompt, cwd, sessionId, resume, tools: opts.tools });
|
||||
res = await run({ prompt, cwd, sessionId, resume, tools: opts.tools });
|
||||
} catch (e) {
|
||||
if (!(e instanceof ClaudeError) || e.kind !== "no_session") throw e;
|
||||
// сессия потеряна: новая сессия, инструкции и память подаются заново (они в промте шага; при исправлении формата - исходный промт)
|
||||
@@ -101,12 +135,12 @@ export function runManagerAgent(
|
||||
resume = false;
|
||||
prompt = opts.prompt;
|
||||
runId = await startRun(ctx, opts.managerId, opts.step, attempt, sessionId, false);
|
||||
res = await ctx.runner({ prompt, cwd, sessionId, resume, tools: opts.tools });
|
||||
res = await run({ prompt, cwd, sessionId, resume, tools: opts.tools });
|
||||
}
|
||||
} catch (e) {
|
||||
lastErr = e instanceof Error ? e.message : String(e);
|
||||
await finishRun(ctx, runId, false, { error: lastErr });
|
||||
throw new AgentFailure(lastErr);
|
||||
throw fail(lastErr);
|
||||
}
|
||||
sessionId = res.sessionId;
|
||||
await ctx.pool.query("update agent_manager_memory set claude_session_id = $2, updated_at = now() where manager_person_id = $1", [opts.managerId, sessionId]);
|
||||
@@ -117,19 +151,20 @@ export function runManagerAgent(
|
||||
if (/коннектор[^.\n]{0,60}(недоступ|удал|пропал|отключ)/i.test(connectorText)) {
|
||||
await ctx.pool.query("update agent_manager_memory set claude_session_id = null, updated_at = now() where manager_person_id = $1", [opts.managerId]);
|
||||
ctx.log.warn({ managerId: opts.managerId }, "агент сообщил о недоступности коннектора - сессия claude сброшена");
|
||||
if (live) ctx.liveRunner!.close(cwd);
|
||||
}
|
||||
const missing = missingSections(sections, opts.required);
|
||||
const changes = sections.get("изменения jobtread");
|
||||
if (!missing.length) {
|
||||
await finishRun(ctx, runId, true, { durationMs: res.durationMs, costUsd: res.costUsd, changes });
|
||||
return { text: res.text, sections, sessionId, attempts: attempt };
|
||||
return { text: res.text, sections, sessionId, attempts: attempt, timing };
|
||||
}
|
||||
lastErr = `в ответе нет разделов: ${missing.map((m) => `## ${m}`).join(", ")}`;
|
||||
await finishRun(ctx, runId, false, { durationMs: res.durationMs, costUsd: res.costUsd, error: lastErr, changes });
|
||||
resume = true;
|
||||
prompt = `Твой предыдущий ответ не принят: ${lastErr}. Исправь и выведи ответ ЦЕЛИКОМ в требуемом формате (разделы \`## Название\`), без пояснений вне разделов. Ничего повторно не выполняй в системах (JobTread и др.), только поправь формат.`;
|
||||
}
|
||||
throw new AgentFailure(lastErr);
|
||||
throw fail(lastErr);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
134
packages/khbuild_assistant_prep/src/live-runner.test.ts
Normal file
134
packages/khbuild_assistant_prep/src/live-runner.test.ts
Normal file
@@ -0,0 +1,134 @@
|
||||
import { mkdtempSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { ClaudeError } from "./agents/cli-runner.js";
|
||||
import { createLiveRunner, type LiveRunner } from "./agents/live-runner.js";
|
||||
|
||||
/** Фейковый claude: читает JSON-строки со stdin, на каждое сообщение отвечает событием result; DIE - падает, HANG - молчит. */
|
||||
const FAKE = `
|
||||
const rl = require("readline").createInterface({ input: process.stdin });
|
||||
const sid = process.argv[process.argv.indexOf("--session-id") + 1] || process.argv[process.argv.indexOf("--resume") + 1];
|
||||
if (process.env.FAKE_NO_SESSION && process.argv.includes("--resume")) { console.error("No conversation found with session ID " + sid); process.exit(1); }
|
||||
let n = 0;
|
||||
rl.on("line", (line) => {
|
||||
const m = JSON.parse(line); const text = m.message.content; n++;
|
||||
if (text === "HANG") return;
|
||||
if (text === "DIE") process.exit(3);
|
||||
console.log(JSON.stringify({ type: "system", subtype: "init", session_id: sid }));
|
||||
console.log(JSON.stringify({ type: "result", subtype: "success", is_error: text === "ERR", result: "pid=" + process.pid + " n=" + n + " " + text, session_id: sid, total_cost_usd: 0.01 * n, duration_ms: 5 }));
|
||||
});
|
||||
rl.on("close", () => process.exit(0));
|
||||
`;
|
||||
|
||||
const dir = mkdtempSync(join(tmpdir(), "llmtest-live-"));
|
||||
const script = join(dir, "fake-claude.cjs");
|
||||
writeFileSync(script, FAKE);
|
||||
|
||||
const runners: LiveRunner[] = [];
|
||||
const mk = (o: { idleMs?: number; warmupMs?: number; timeoutMs?: number } = {}) => {
|
||||
const events: string[] = [];
|
||||
const r = createLiveRunner({ bin: process.execPath, prefixArgs: [script], idleMs: o.idleMs ?? 60_000, warmupMs: o.warmupMs ?? 0, timeoutMs: o.timeoutMs ?? 5_000, onEvent: (e) => events.push(e.kind) });
|
||||
runners.push(r);
|
||||
return { r, events };
|
||||
};
|
||||
const call = (cwd: string, prompt: string, sessionId = "11111111-1111-4111-8111-111111111111", resume = false) => ({ prompt, cwd, sessionId, resume, tools: "chat" as const });
|
||||
const pid = (t: string) => t.match(/pid=(\d+)/)![1];
|
||||
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
afterEach(() => { for (const r of runners.splice(0)) r.closeAll(); });
|
||||
|
||||
describe("долгоживущий агент (фейковый claude)", () => {
|
||||
it("один процесс на несколько ходов; стоимость - по ходу, а не накопительно", async () => {
|
||||
const { r, events } = mk();
|
||||
const cwd = join(dir, "m1");
|
||||
const a = await r.run(call(cwd, "привет"));
|
||||
expect(r.isActive(cwd)).toBe(true);
|
||||
const b = await r.run(call(cwd, "ещё"));
|
||||
expect(pid(b.text)).toBe(pid(a.text));
|
||||
expect(b.text).toContain("n=2");
|
||||
expect(a.costUsd).toBeCloseTo(0.01);
|
||||
expect(b.costUsd).toBeCloseTo(0.01); // 0.02 накопительно - 0.01 предыдущего хода
|
||||
expect(events.filter((e) => e === "start")).toHaveLength(1);
|
||||
expect(r.activeCount()).toBe(1);
|
||||
});
|
||||
|
||||
it("закрывается через простой; следующий ход стартует новый процесс", async () => {
|
||||
const { r, events } = mk({ idleMs: 150 });
|
||||
const cwd = join(dir, "m2");
|
||||
const a = await r.run(call(cwd, "раз"));
|
||||
await sleep(500);
|
||||
expect(r.isActive(cwd)).toBe(false);
|
||||
expect(events).toContain("idle_close");
|
||||
const b = await r.run(call(cwd, "два", "11111111-1111-4111-8111-111111111111", true));
|
||||
expect(pid(b.text)).not.toBe(pid(a.text));
|
||||
});
|
||||
|
||||
it("новый ход сбрасывает таймер простоя", async () => {
|
||||
const { r } = mk({ idleMs: 300 });
|
||||
const cwd = join(dir, "m3");
|
||||
await r.run(call(cwd, "раз"));
|
||||
await sleep(200);
|
||||
await r.run(call(cwd, "два"));
|
||||
await sleep(200);
|
||||
expect(r.isActive(cwd)).toBe(true); // с первого хода прошло 400 мс > idleMs, но таймер перезапущен вторым ходом
|
||||
});
|
||||
|
||||
it("после старта процесса ждёт warmup, на следующих ходах - нет", async () => {
|
||||
const { r } = mk({ warmupMs: 400 });
|
||||
const cwd = join(dir, "m4");
|
||||
const t0 = Date.now();
|
||||
await r.run(call(cwd, "раз"));
|
||||
expect(Date.now() - t0).toBeGreaterThanOrEqual(380);
|
||||
const t1 = Date.now();
|
||||
await r.run(call(cwd, "два"));
|
||||
expect(Date.now() - t1).toBeLessThan(300);
|
||||
});
|
||||
|
||||
it("таймаут хода: процесс убит, ошибка timeout, следующий ход работает", async () => {
|
||||
const { r } = mk({ timeoutMs: 300 });
|
||||
const cwd = join(dir, "m5");
|
||||
await expect(r.run(call(cwd, "HANG"))).rejects.toMatchObject({ kind: "timeout" });
|
||||
expect(r.isActive(cwd)).toBe(false);
|
||||
expect((await r.run(call(cwd, "жив"))).text).toContain("жив");
|
||||
});
|
||||
|
||||
it("падение процесса посреди хода: ошибка failed, следующий ход стартует заново", async () => {
|
||||
const { r } = mk();
|
||||
const cwd = join(dir, "m6");
|
||||
await r.run(call(cwd, "раз"));
|
||||
const err = await r.run(call(cwd, "DIE")).catch((e) => e);
|
||||
expect(err).toBeInstanceOf(ClaudeError);
|
||||
expect(err.kind).toBe("failed");
|
||||
expect(r.isActive(cwd)).toBe(false);
|
||||
expect((await r.run(call(cwd, "снова", "11111111-1111-4111-8111-111111111111", true))).text).toContain("снова");
|
||||
});
|
||||
|
||||
it("is_error в результате - ошибка, процесс остаётся жив", async () => {
|
||||
const { r } = mk();
|
||||
const cwd = join(dir, "m7");
|
||||
await expect(r.run(call(cwd, "ERR"))).rejects.toMatchObject({ kind: "failed" });
|
||||
expect(r.isActive(cwd)).toBe(true);
|
||||
});
|
||||
|
||||
it("сессия не найдена при --resume -> no_session", async () => {
|
||||
process.env.FAKE_NO_SESSION = "1";
|
||||
try {
|
||||
const { r } = mk();
|
||||
await expect(r.run(call(join(dir, "m8"), "x", "22222222-2222-4222-8222-222222222222", true))).rejects.toMatchObject({ kind: "no_session" });
|
||||
} finally {
|
||||
delete process.env.FAKE_NO_SESSION;
|
||||
}
|
||||
});
|
||||
|
||||
it("другая сессия в той же папке: старый процесс закрывается, стартует новый; close() закрывает", async () => {
|
||||
const { r } = mk();
|
||||
const cwd = join(dir, "m9");
|
||||
const a = await r.run(call(cwd, "раз"));
|
||||
const b = await r.run(call(cwd, "два", "33333333-3333-4333-8333-333333333333"));
|
||||
expect(pid(b.text)).not.toBe(pid(a.text));
|
||||
expect(r.activeCount()).toBe(1);
|
||||
r.close(cwd);
|
||||
expect(r.isActive(cwd)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import { join } from "node:path";
|
||||
import { createLogger, createPool, itNotify, loadServiceSettings } from "khb_common";
|
||||
import { createCliRunner } from "./agents/cli-runner.js";
|
||||
import { createLiveRunner } from "./agents/live-runner.js";
|
||||
import { KeyedMutex, Semaphore } from "./agents/pool.js";
|
||||
import { closeOrphanRuns, type AgentContext } from "./agents/session.js";
|
||||
import { buildApi } from "./http-api.js";
|
||||
@@ -22,6 +23,13 @@ const ctx: AgentContext = {
|
||||
log,
|
||||
settings: service.agent,
|
||||
runner: createCliRunner({ bin: service.agent.claudeBin, timeoutMs: service.agent.timeoutMs, model: service.agent.model }),
|
||||
liveRunner: service.agent.live?.managerIds.length
|
||||
? createLiveRunner({
|
||||
bin: service.agent.claudeBin, model: service.agent.model, timeoutMs: service.agent.timeoutMs,
|
||||
idleMs: service.agent.live.idleMinutes * 60_000, warmupMs: service.agent.live.warmupSeconds * 1000,
|
||||
onEvent: (e) => log.info({ ...e }, "долгоживущий агент"),
|
||||
})
|
||||
: undefined,
|
||||
gate: new Semaphore(service.agent.concurrency),
|
||||
locks: new KeyedMutex(),
|
||||
notifyIt: async (text) => {
|
||||
@@ -118,3 +126,9 @@ if (service.slack && chatDeps) {
|
||||
log.info({ everySeconds: d.inboxScanSeconds }, "опрос папок приёма Drive запущен");
|
||||
}
|
||||
}
|
||||
|
||||
for (const sig of ["SIGTERM", "SIGINT"] as const)
|
||||
process.on(sig, () => {
|
||||
ctx.liveRunner?.closeAll();
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
@@ -14,6 +14,17 @@ export const agentSchema = z.object({
|
||||
allowedJobIds: z.array(z.string()).default([]),
|
||||
/** Тестовые проекты из allowedJobIds: записи в них начинаются с `llmtest-`; в остальные (рабочие) проекты пишутся обычные названия. */
|
||||
testJobIds: z.array(z.string()).default([]),
|
||||
/**
|
||||
* Новая версия агента чата (шаг 4): долгоживущий процесс, не завершается между сообщениями (закрывается через idleMinutes простоя).
|
||||
* Включается только для перечисленных менеджеров (сейчас - тестовый); у остальных работает прежняя версия (процесс на каждое сообщение).
|
||||
*/
|
||||
live: z
|
||||
.object({
|
||||
managerIds: z.array(z.string()).default([]),
|
||||
idleMinutes: z.number().min(0.1).default(10),
|
||||
warmupSeconds: z.number().min(0).default(6),
|
||||
})
|
||||
.optional(),
|
||||
});
|
||||
export type AgentSettings = z.infer<typeof agentSchema>;
|
||||
|
||||
|
||||
@@ -11,6 +11,8 @@ export interface SlackFile {
|
||||
|
||||
export interface SlackApi {
|
||||
postMessage(channel: string, text: string, threadTs?: string): Promise<boolean>;
|
||||
/** То же, но возвращает ts отправленного сообщения (null - не отправлено): по нему считается время ответа для chat_timing. */
|
||||
postMessageTs?(channel: string, text: string, threadTs?: string): Promise<string | null>;
|
||||
fileInfo(fileId: string): Promise<SlackFile | null>;
|
||||
download(file: SlackFile, toPath: string): Promise<number>;
|
||||
/** Загружает файл в канал (нужен scope files:write). */
|
||||
@@ -25,13 +27,17 @@ export function createSlackApi(botToken: string, fetchFn: typeof fetch = fetch):
|
||||
headers: { "content-type": "application/json; charset=utf-8", authorization: `Bearer ${botToken}` },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
return (await res.json()) as { ok?: boolean; error?: string; file?: Record<string, unknown> };
|
||||
return (await res.json()) as { ok?: boolean; error?: string; ts?: string; file?: Record<string, unknown> };
|
||||
};
|
||||
const postTs = async (channel: string, text: string, threadTs?: string): Promise<string | null> => {
|
||||
// Slack ограничивает текст ~40000 символов; режем с запасом
|
||||
const r = await call("chat.postMessage", { channel, text: text.slice(0, 35000), ...(threadTs ? { thread_ts: threadTs } : {}) });
|
||||
return r.ok === true ? (typeof r.ts === "string" ? r.ts : "") : null;
|
||||
};
|
||||
return {
|
||||
postMessageTs: postTs,
|
||||
async postMessage(channel, text, threadTs) {
|
||||
// Slack ограничивает текст ~40000 символов; режем с запасом
|
||||
const r = await call("chat.postMessage", { channel, text: text.slice(0, 35000), ...(threadTs ? { thread_ts: threadTs } : {}) });
|
||||
return r.ok === true;
|
||||
return (await postTs(channel, text, threadTs)) !== null;
|
||||
},
|
||||
async fileInfo(fileId) {
|
||||
const res = await fetchFn(`https://slack.com/api/files.info?file=${encodeURIComponent(fileId)}`, { headers: { authorization: `Bearer ${botToken}` } });
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { copyFileSync, mkdirSync } from "node:fs";
|
||||
import { basename, join } from "node:path";
|
||||
import { localDate } from "khb_common";
|
||||
import { AgentFailure, loadMemory, managerWorkDir, runManagerAgent, saveMemory, type AgentContext } from "../agents/session.js";
|
||||
import { AgentFailure, loadMemory, managerWorkDir, runManagerAgent, saveMemory, useLive, type AgentContext } from "../agents/session.js";
|
||||
import { loadPrompt } from "../agents/prompts.js";
|
||||
import { saveProblems } from "../agents/step2.js";
|
||||
import type { DriveSync } from "./drive.js";
|
||||
import type { SlackApi } from "./api.js";
|
||||
import { saveChatTiming, type ChatTiming } from "./timing.js";
|
||||
import { normalizeVoice, speechText, type ReplyMode, type Tts } from "./tts.js";
|
||||
|
||||
export interface ManagerInfo {
|
||||
@@ -43,7 +44,7 @@ export interface IncomingMessage {
|
||||
|
||||
export interface ChatDeps {
|
||||
ctx: AgentContext;
|
||||
slack: Pick<SlackApi, "postMessage" | "fileInfo" | "download" | "uploadFile">;
|
||||
slack: Pick<SlackApi, "postMessage" | "postMessageTs" | "fileInfo" | "download" | "uploadFile">;
|
||||
/** Синтез речи; без него ответы всегда текстовые. */
|
||||
tts?: Tts;
|
||||
defaultVoice?: string;
|
||||
@@ -77,6 +78,14 @@ export async function handleManagerMessages(
|
||||
opts: { systemEvent?: string } = {},
|
||||
): Promise<ChatResult> {
|
||||
const { ctx } = deps;
|
||||
const t0 = Date.now();
|
||||
let mark = t0;
|
||||
const lap = () => {
|
||||
const n = Date.now();
|
||||
const d = n - mark;
|
||||
mark = n;
|
||||
return d;
|
||||
};
|
||||
const now = (deps.now ?? (() => new Date()))();
|
||||
const today = localDate(now, deps.timezone);
|
||||
const channel = messages[0]?.channel ?? manager.slackChannelId;
|
||||
@@ -84,6 +93,17 @@ export async function handleManagerMessages(
|
||||
const mediaDir = join(managerWorkDir(ctx.settings, manager.personId), "media", sub);
|
||||
mkdirSync(mediaDir, { recursive: true });
|
||||
|
||||
// тайминг запроса (таблица chat_timing): от сообщения в Slack до ответа в Slack
|
||||
const receivedAt =
|
||||
messages.length && !opts.systemEvent
|
||||
? (((await ctx.pool.query("select min(received_at) as r from slack_message_log where channel_id = $1 and message_ts = any($2)", [channel ?? null, messages.map((m) => m.ts)])).rows[0]?.r as Date | null | undefined) ?? null)
|
||||
: null;
|
||||
const tm: ChatTiming = {
|
||||
managerId: manager.personId, channel: channel ?? null, kind: opts.systemEvent ? "event" : "message", agentVersion: useLive(ctx, manager.personId) ? "live" : "classic",
|
||||
startedAt: new Date(t0), messageTs: opts.systemEvent ? undefined : messages[0]?.ts, receivedAt, status: "ok",
|
||||
};
|
||||
mark = Date.now();
|
||||
|
||||
// история напоминаний (вход 7): ответ менеджера закрывает последнее неотвеченное напоминание
|
||||
if (messages.length && !opts.systemEvent) {
|
||||
await ctx.pool.query(
|
||||
@@ -123,6 +143,8 @@ export async function handleManagerMessages(
|
||||
perMessage.set(m.ts, lines);
|
||||
}
|
||||
|
||||
tm.inputsMs = lap();
|
||||
|
||||
// 2. копии исходников в Drive (сбой не останавливает обработку)
|
||||
let links: Record<string, string> = {};
|
||||
if (deps.drive && attachments.length) {
|
||||
@@ -135,6 +157,8 @@ export async function handleManagerMessages(
|
||||
}
|
||||
}
|
||||
|
||||
tm.driveMs = lap();
|
||||
|
||||
// 3. промт
|
||||
const mem = await loadMemory(ctx.pool, manager.personId);
|
||||
const todayCount = (
|
||||
@@ -165,16 +189,23 @@ export async function handleManagerMessages(
|
||||
}`,
|
||||
]
|
||||
: [];
|
||||
// Новая версия (долгоживущий агент): если процесс уже в диалоге, инструкции, список задач и память не повторяются - только новое
|
||||
const live = useLive(ctx, manager.personId);
|
||||
const inDialog = live && ctx.liveRunner!.isActive(managerWorkDir(ctx.settings, manager.personId));
|
||||
const liveRules = live
|
||||
? "\nСессия долгоживущая: после ответа ты остаёшься в диалоге, следующие сообщения придут как продолжение. Перед записью в JobTread вызови ToolSearch с запросом select:mcp__claude_ai_JobTread__query (если инструмента ещё нет - подожди несколько секунд и повтори, до 3 раз). Только после этого можно считать коннектор недоступным. Никогда не пиши менеджеру, что ИТ что-то исправили или починили, если тебе об этом не сообщали."
|
||||
: "";
|
||||
const prompt = [
|
||||
loadPrompt(proj ? "project_channel.md" : "step4_manager_chat.md", { media_dir: mediaDir }),
|
||||
...(inDialog
|
||||
? ["# Продолжение диалога\nСессия продолжается: инструкции, формат ответа и память выше остаются в силе. Ответь в том же формате разделов (`## Ответ менеджеру`, `## Память` - обновлённая память целиком, `## Изменения JobTread`, `## Обращение в ИТ`, `## Лог проблем`)."]
|
||||
: [loadPrompt(proj ? "project_channel.md" : "step4_manager_chat.md", { media_dir: mediaDir })]),
|
||||
"",
|
||||
`# Дата и время\n${now.toISOString()} (UTC); дата по Тампе: ${today}; сообщений менеджера за последние сутки: ${todayCount}`,
|
||||
...(opts.systemEvent ? ["", `# Системное событие\n${opts.systemEvent}`] : []),
|
||||
...projectBlock,
|
||||
"",
|
||||
`# Список задач на сегодня\n${await todayList(ctx, manager.personId, today)}`,
|
||||
"",
|
||||
`# Память\n${mem.memoryText.trim() || "(пусто)"}`,
|
||||
...(inDialog
|
||||
? []
|
||||
: ["", `# Список задач на сегодня\n${await todayList(ctx, manager.personId, today)}`, "", `# Память\n${mem.memoryText.trim() || "(пусто)"}`]),
|
||||
"",
|
||||
`# Ограничения среды\nМенеджер: ${manager.name}. ${
|
||||
writableJobs.length
|
||||
@@ -188,17 +219,27 @@ export async function handleManagerMessages(
|
||||
disabled.length
|
||||
? `\nОТКЛЮЧЁННЫЕ проекты менеджера (ассистент по ним не работает): ${disabled.map((d) => `${d.name ?? d.jt_job_id} (${d.jt_job_id})`).join("; ")}. Не обсуждай их, не пиши в них и не напоминай о них, даже если задачи этих проектов есть в списке на сегодня. Если менеджер пишет об отключённом проекте - коротко ответь, что по этому проекту ассистент сейчас отключён, и ничего не записывай.`
|
||||
: ""
|
||||
}`,
|
||||
}${liveRules}`,
|
||||
"",
|
||||
`# Новые сообщения менеджера\n${msgBlock}\n\nВложения (локальные пути):\n${attBlock}`,
|
||||
].join("\n");
|
||||
|
||||
tm.promptMs = lap();
|
||||
tm.promptChars = prompt.length;
|
||||
|
||||
// 4. агент
|
||||
let out;
|
||||
try {
|
||||
out = await runManagerAgent(ctx, { managerId: manager.personId, step: "step4", tools: "chat", prompt, required: ["ответ менеджеру", "память"] });
|
||||
tm.agent = out.timing;
|
||||
mark = Date.now();
|
||||
} catch (e) {
|
||||
const err = e instanceof AgentFailure || e instanceof Error ? e.message : String(e);
|
||||
tm.status = "failed";
|
||||
tm.error = err;
|
||||
tm.agent = e instanceof AgentFailure ? e.timing : undefined;
|
||||
tm.processingMs = Date.now() - t0;
|
||||
await saveChatTiming(ctx.pool, tm, ctx.log);
|
||||
ctx.log.error({ manager: manager.personId, err }, "шаг 4 не удался");
|
||||
await ctx.notifyIt(`:warning: khbuild_assistant_prep: шаг 4 (общение) для ${manager.name} не выполнен: ${err.slice(0, 500)}`);
|
||||
if (!deps.dryPublish && channel) await deps.slack.postMessage(channel, "Не смог обработать сообщение - уже сообщил ИТ-команде, скоро разберёмся.");
|
||||
@@ -212,7 +253,13 @@ export async function handleManagerMessages(
|
||||
const reply = /^\(без ответа\)\.?$/i.test(replyRaw) ? null : replyRaw;
|
||||
let published = false;
|
||||
let audioSent = false;
|
||||
if (reply && channel && !deps.dryPublish) ({ published, audioSent } = await publishReply(deps, manager, channel, reply));
|
||||
if (reply && channel && !deps.dryPublish) {
|
||||
const tp = Date.now();
|
||||
const pr = await publishReply(deps, manager, channel, reply);
|
||||
({ published, audioSent } = pr);
|
||||
tm.replySlackTs = pr.replyTs;
|
||||
tm.publishMs = Date.now() - tp;
|
||||
}
|
||||
if (reply && opts.systemEvent) {
|
||||
// напоминание ассистента по событию - в историю напоминаний (вход 7)
|
||||
await ctx.pool.query(
|
||||
@@ -222,13 +269,18 @@ export async function handleManagerMessages(
|
||||
);
|
||||
}
|
||||
|
||||
tm.postMs = Math.max(0, lap() - (tm.publishMs ?? 0));
|
||||
|
||||
// 6. транскрипты и итоговые файлы -> Drive
|
||||
if (deps.drive && attachments.length) await deps.drive.upload(mediaDir, sub).catch((e) => ctx.log.warn({ err: String(e) }, "повторная выгрузка в Drive не удалась"));
|
||||
tm.finalMs = lap();
|
||||
tm.processingMs = Date.now() - t0;
|
||||
await saveChatTiming(ctx.pool, tm, ctx.log);
|
||||
return { reply, published, audioSent, attachments };
|
||||
}
|
||||
|
||||
/** Публикует ответ по настройке чата: текст / текст и аудио / только аудио. Любой сбой аудио - ответ уходит текстом, ИТ видит проблему в логе. */
|
||||
export async function publishReply(deps: ChatDeps, manager: ManagerInfo, channel: string, reply: string): Promise<{ published: boolean; audioSent: boolean }> {
|
||||
export async function publishReply(deps: ChatDeps, manager: ManagerInfo, channel: string, reply: string): Promise<{ published: boolean; audioSent: boolean; replyTs: string | null }> {
|
||||
const mode = manager.replyMode ?? "text";
|
||||
const voice = normalizeVoice(manager.ttsVoice) ?? normalizeVoice(deps.defaultVoice) ?? "Aoede";
|
||||
let audioSent = false;
|
||||
@@ -243,6 +295,13 @@ export async function publishReply(deps: ChatDeps, manager: ManagerInfo, channel
|
||||
}
|
||||
}
|
||||
const needText = mode === "text" || mode === "both" || !audioSent;
|
||||
const published = needText ? await deps.slack.postMessage(channel, reply) : false;
|
||||
return { published: published || audioSent, audioSent };
|
||||
let published = false;
|
||||
let replyTs: string | null = null;
|
||||
if (needText) {
|
||||
if (deps.slack.postMessageTs) {
|
||||
replyTs = await deps.slack.postMessageTs(channel, reply);
|
||||
published = replyTs !== null;
|
||||
} else published = await deps.slack.postMessage(channel, reply);
|
||||
}
|
||||
return { published: published || audioSent, audioSent, replyTs: replyTs || null };
|
||||
}
|
||||
|
||||
65
packages/khbuild_assistant_prep/src/slack/timing.ts
Normal file
65
packages/khbuild_assistant_prep/src/slack/timing.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import type { Pool } from "khb_common";
|
||||
import type { AgentTiming } from "../agents/session.js";
|
||||
|
||||
/** Тайминг обработки пакета сообщений (поля соответствуют таблице chat_timing). */
|
||||
export interface ChatTiming {
|
||||
managerId: string;
|
||||
channel: string | null;
|
||||
kind: "message" | "event";
|
||||
agentVersion: "classic" | "live";
|
||||
startedAt: Date;
|
||||
messageTs?: string;
|
||||
receivedAt?: Date | null;
|
||||
replySlackTs?: string | null;
|
||||
inputsMs?: number;
|
||||
driveMs?: number;
|
||||
promptMs?: number;
|
||||
promptChars?: number;
|
||||
postMs?: number;
|
||||
publishMs?: number;
|
||||
finalMs?: number;
|
||||
processingMs?: number;
|
||||
agent?: AgentTiming;
|
||||
status: "ok" | "failed";
|
||||
error?: string;
|
||||
}
|
||||
|
||||
const int = (v: number | null | undefined): number | null => (typeof v === "number" && Number.isFinite(v) ? Math.max(0, Math.round(v)) : null);
|
||||
const sum = (xs: Array<number | undefined>): number | null => {
|
||||
const v = xs.filter((x): x is number => typeof x === "number");
|
||||
return v.length ? v.reduce((a, b) => a + b, 0) : null;
|
||||
};
|
||||
|
||||
/** Секунды Slack ts ("1791741165.045849") -> Date. */
|
||||
export const slackTsToDate = (ts: string | null | undefined): Date | null => {
|
||||
const n = Number(ts);
|
||||
return Number.isFinite(n) && n > 1e9 ? new Date(Math.round(n * 1000)) : null;
|
||||
};
|
||||
|
||||
/** Сохраняет тайминг; сбой записи диагностики не должен ломать обработку чата. */
|
||||
export async function saveChatTiming(pool: Pool, t: ChatTiming, log?: { warn(o: object, m: string): void }): Promise<void> {
|
||||
try {
|
||||
const runs = t.agent?.runs ?? [];
|
||||
const messageAt = slackTsToDate(t.messageTs);
|
||||
const replyAt = slackTsToDate(t.replySlackTs);
|
||||
const modelMs = sum(runs.map((r) => r.timing?.turnMs ?? r.wallMs));
|
||||
await pool.query(
|
||||
`insert into chat_timing (manager_person_id, channel_id, kind, agent_version, status, error, message_ts, message_at, received_at, started_at, reply_slack_ts, reply_at,
|
||||
slack_in_ms, debounce_ms, inputs_ms, drive_ms, prompt_ms, prompt_chars, queue_ms, start_ms, model_ms, api_ms, first_event_ms, tool_calls, num_turns, attempts, cost_usd,
|
||||
post_ms, publish_ms, final_ms, processing_ms, total_ms, steps)
|
||||
values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$30,$31,$32,$33)`,
|
||||
[
|
||||
t.managerId, t.channel, t.kind, t.agentVersion, t.status, t.error?.slice(0, 500) ?? null, t.messageTs ?? null, messageAt, t.receivedAt ?? null, t.startedAt, t.replySlackTs ?? null, replyAt,
|
||||
int(messageAt && t.receivedAt ? t.receivedAt.getTime() - messageAt.getTime() : null),
|
||||
int(t.receivedAt ? t.startedAt.getTime() - t.receivedAt.getTime() : null),
|
||||
int(t.inputsMs), int(t.driveMs), int(t.promptMs), int(t.promptChars), int(t.agent?.queueMs),
|
||||
int(sum(runs.map((r) => r.timing?.startMs))), int(modelMs), int(sum(runs.map((r) => r.timing?.apiMs))), int(runs[0]?.timing?.firstEventMs),
|
||||
int(sum(runs.map((r) => r.timing?.toolCalls))), int(sum(runs.map((r) => r.timing?.numTurns))), runs.length || null, sum(runs.map((r) => r.costUsd)),
|
||||
int(t.postMs), int(t.publishMs), int(t.finalMs), int(t.processingMs), int(messageAt && replyAt ? replyAt.getTime() - messageAt.getTime() : null),
|
||||
JSON.stringify({ runs }),
|
||||
],
|
||||
);
|
||||
} catch (e) {
|
||||
log?.warn({ err: String(e) }, "не удалось сохранить тайминг чата");
|
||||
}
|
||||
}
|
||||
@@ -67,19 +67,19 @@ describe("режим ответов чата", () => {
|
||||
|
||||
it("по умолчанию - только текст, синтез не вызывается", async () => {
|
||||
const s = setup();
|
||||
expect(await publishReply(s.deps, manager(), "C", "Hi")).toEqual({ published: true, audioSent: false });
|
||||
expect(await publishReply(s.deps, manager(), "C", "Hi")).toMatchObject({ published: true, audioSent: false });
|
||||
expect(s.events).toEqual(["text:Hi"]);
|
||||
});
|
||||
|
||||
it("both - и аудио (голос чата), и текст", async () => {
|
||||
const s = setup();
|
||||
expect(await publishReply(s.deps, manager("both", "Puck"), "C", "Hi")).toEqual({ published: true, audioSent: true });
|
||||
expect(await publishReply(s.deps, manager("both", "Puck"), "C", "Hi")).toMatchObject({ published: true, audioSent: true });
|
||||
expect(s.events).toEqual(["voice:Puck", "audio:assistant-reply.mp3", "text:Hi"]);
|
||||
});
|
||||
|
||||
it("audio - только аудио, голос по умолчанию из настроек", async () => {
|
||||
const s = setup();
|
||||
expect(await publishReply(s.deps, manager("audio"), "C", "Hi")).toEqual({ published: true, audioSent: true });
|
||||
expect(await publishReply(s.deps, manager("audio"), "C", "Hi")).toMatchObject({ published: true, audioSent: true });
|
||||
expect(s.events).toEqual(["voice:Aoede", "audio:assistant-reply.mp3"]);
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user