import { randomUUID } from "node:crypto"; import type { Db, TxDb } from "../../db/db.ts"; import { RateLimiter } from "../accounts/rate-limit.ts"; import { LlmUnavailableError, type LlmClient } from "../audits/llm.ts"; import type { Offer } from "../billing/offers.ts"; import { guardLlmPayload, PiiLeakError } from "../privacy/anonymize.ts"; import { UploadNotFoundError, type Actor, type UploadStore } from "../privacy/uploads.ts"; import { buildClientPrompt, buildEvaluationPrompt, TECHNIQUES, validateClientReply, validateEvaluation, type Evaluation, type Line } from "./llm.ts"; import { scenarioById, type Scenario } from "./scenarios.ts"; export const TRAINER_OFFER_ID = "trainer-monthly"; export const MAX_LINE = 2000; export const MAX_TURNS = 30; export const SESSION_TTL_MS = 24 * 60 * 60 * 1000; /** Ошибка с кодом для ответа `{"error":""}` и HTTP-статусом. */ export class TrainerError extends Error { readonly status: number; constructor(status: number, code: string) { super(code); this.name = "TrainerError"; this.status = status; } } export interface Trainee { id: string; orgId: string | null; } export interface TrainerServiceOptions { db: TxDb; uploads: UploadStore; llm: LlmClient; offer: Offer; now: () => number; /** Ходов и завершений в час на оператора. */ hourlyLimit?: number; } interface SessionRow { id: string; user_id: string; org_id: string; scenario_id: string; turns: number; transcript_upload_id: string | null; created_at: Date | string; } export type TrainerService = ReturnType; export function createTrainerService(opts: TrainerServiceOptions) { const { db, uploads, llm, offer, now } = opts; const limiter = new RateLimiter(opts.hourlyLimit ?? 60, 60 * 60 * 1000, now); const seatLimit = offer.seats ?? 0; async function subscriptionActive(q: Db, orgId: string): Promise { const r = await q.query( `SELECT 1 FROM entitlements WHERE org_id = $1 AND offer_id = $2 AND status = 'active' AND (valid_until IS NULL OR valid_until > $3)`, [orgId, offer.id, new Date(now())], ); return r.rows.length > 0; } /** Проверка доступа к тренировкам: организация, подписка, место. */ async function requireAccess(u: Trainee): Promise { if (!u.orgId) throw new TrainerError(403, "forbidden"); if (!(await subscriptionActive(db, u.orgId))) throw new TrainerError(402, "subscription_required"); const seat = await db.query("SELECT 1 FROM trainer_seats WHERE user_id = $1 AND org_id = $2", [u.id, u.orgId]); if (seat.rows.length === 0) throw new TrainerError(403, "no_seat"); return u.orgId; } const actorOf = (s: { user_id: string; org_id: string }): Actor => ({ userId: s.user_id, orgId: s.org_id }); async function dropTranscript(s: SessionRow): Promise { if (s.transcript_upload_id) await uploads.completeUpload(actorOf(s), s.transcript_upload_id).catch(() => undefined); } async function storeTranscript(actor: Actor, lines: readonly Line[]): Promise { return uploads.storeUpload(actor, "trainer-transcript", Buffer.from(JSON.stringify(lines), "utf8")); } async function abandon(s: SessionRow): Promise { await db.query("UPDATE trainer_sessions SET status = 'abandoned', transcript_upload_id = NULL WHERE id = $1 AND status = 'active'", [s.id]); await dropTranscript(s); } async function activeSession(u: Trainee): Promise<{ session: SessionRow; scenario: Scenario; lines: Line[] }> { const r = await db.query("SELECT * FROM trainer_sessions WHERE user_id = $1 AND status = 'active'", [u.id]); const session = r.rows[0]; if (!session) throw new TrainerError(404, "no_active_session"); const scenario = scenarioById(session.scenario_id); const expired = new Date(session.created_at).getTime() + SESSION_TTL_MS <= now(); let lines: Line[] | null = null; if (scenario && !expired && session.transcript_upload_id) { try { lines = JSON.parse((await uploads.readUpload(actorOf(session), session.transcript_upload_id)).toString("utf8")) as Line[]; } catch (err) { if (!(err instanceof UploadNotFoundError)) throw err; } } if (!scenario || !lines) { await abandon(session); throw new TrainerError(410, "session_expired"); } return { session, scenario, lines }; } function rateLimit(u: Trainee): void { if (limiter.blocked(u.id)) throw new TrainerError(429, "too_many_requests"); limiter.hit(u.id); } async function callLlm(req: Parameters[0], validate: (raw: unknown) => T | null): Promise { let raw: unknown; try { raw = await llm.analyze(req); } catch (err) { if (err instanceof LlmUnavailableError) throw new TrainerError(502, "llm_unavailable"); throw err; } const v = validate(raw); if (v === null) throw new TrainerError(502, "llm_invalid_response"); return v; } return { seatLimit, subscriptionActive: (orgId: string) => subscriptionActive(db, orgId), async start(u: Trainee, scenarioId: unknown): Promise<{ id: string; scenario: Scenario; client: string }> { const scenario = scenarioById(scenarioId); if (!scenario) throw new TrainerError(404, "not_found"); const orgId = await requireAccess(u); const prev = await db.query("SELECT * FROM trainer_sessions WHERE user_id = $1 AND status = 'active'", [u.id]); for (const s of prev.rows) await abandon(s); const actor = { userId: u.id, orgId }; const uploadId = await storeTranscript(actor, [{ role: "client", text: scenario.opening }]); const id = randomUUID(); try { await db.query( "INSERT INTO trainer_sessions (id, user_id, org_id, scenario_id, transcript_upload_id, created_at) VALUES ($1, $2, $3, $4, $5, $6)", [id, u.id, orgId, scenario.id, uploadId, new Date(now())], ); } catch (err) { await uploads.completeUpload(actor, uploadId).catch(() => undefined); if ((err as { code?: string })?.code === "23505") throw new TrainerError(409, "session_conflict"); throw err; } return { id, scenario, client: scenario.opening }; }, async turn(u: Trainee, text: unknown): Promise<{ reply: string; turn: number }> { if (typeof text !== "string" || text.trim() === "" || text.length > MAX_LINE) throw new TrainerError(400, "invalid_input"); await requireAccess(u); const { session, scenario, lines } = await activeSession(u); if (session.turns >= MAX_TURNS) throw new TrainerError(409, "turn_limit"); rateLimit(u); // Одна строка: оператор не может подделать реплику клиента переводом строки. const flat = text.replace(/\s+/gu, " ").trim(); let anon: string; try { anon = guardLlmPayload(flat).text; } catch (err) { if (err instanceof PiiLeakError) throw new TrainerError(422, "pii_not_anonymized"); throw err; } const withOperator: Line[] = [...lines, { role: "operator", text: anon }]; const reply = await callLlm(buildClientPrompt(scenario, withOperator), validateClientReply); const next = [...withOperator, { role: "client" as const, text: reply }]; const newId = await storeTranscript(actorOf(session), next); const upd = await db.query( "UPDATE trainer_sessions SET turns = turns + 1, transcript_upload_id = $2 WHERE id = $1 AND status = 'active' AND transcript_upload_id = $3", [session.id, newId, session.transcript_upload_id], ); if ((upd.rowCount ?? 0) === 0) { await uploads.completeUpload(actorOf(session), newId).catch(() => undefined); throw new TrainerError(409, "session_conflict"); } await dropTranscript(session); return { reply, turn: session.turns + 1 }; }, async finish(u: Trainee): Promise { await requireAccess(u); const { session, scenario, lines } = await activeSession(u); if (session.turns === 0) throw new TrainerError(409, "no_turns"); rateLimit(u); const evaluation = await callLlm(buildEvaluationPrompt(scenario, lines), validateEvaluation); // В БД — только числа и флаги; комментарии возвращаются один раз. const scores = Object.fromEntries(TECHNIQUES.map((t) => [t, { applied: evaluation.techniques[t].applied, score: evaluation.techniques[t].score }])); const upd = await db.query( "UPDATE trainer_sessions SET status = 'finished', scores = $2, finished_at = $3, transcript_upload_id = NULL WHERE id = $1 AND status = 'active'", [session.id, JSON.stringify(scores), new Date(now())], ); if ((upd.rowCount ?? 0) === 0) throw new TrainerError(409, "session_conflict"); await dropTranscript(session); return { id: session.id, ...evaluation }; }, }; }