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; /** Длина ответа в словах без упоминаний: по ней отличаем короткое напоминание от осмысленного сообщения. */ replyWords?: number | 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 | 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 { 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, reply_words, 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,$34)`, [ 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, t.replyWords ?? null, 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, null, // cost_usd не ведётся: токены - в agent_usage 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) }, "не удалось сохранить тайминг чата"); } }