// PEP-143: the feedback agent. The watchdog calls `feedbackTick`: a new report (text, tech data, // screenshots) goes to the model on the platform project's own subscription together with the // platform's recent errors and open stories; the answer — what it is, why, 2–3 ways to fix it — // goes to the superadmins with decision buttons. The agent gets one try: whatever fails, the // report still reaches the superadmins, without an analysis, once. The same tick tells authors // whose story has been accepted. import { closeFixedFeedback, feedbackProject, feedbackPrompt, feedbackPromptContext, feedbackScreenshotFiles, guardUntrusted, finishFeedbackAnalysis, parseFeedbackAnalysis, type Feedback, } from "@peppa/core"; import { feedback, users, type Db } from "@peppa/db"; import { and, eq, isNull } from "drizzle-orm"; import { basename } from "node:path"; import { claudePrint } from "./claude-print.ts"; const inFlight = new Set(); const timeoutMs = () => Number(process.env.PEPPA_FEEDBACK_TIMEOUT_MS ?? process.env.PEPPA_INTAKE_TIMEOUT_MS ?? 180_000); export interface FeedbackTickOptions { log?: (m: string) => void; now?: Date; /** Wait for the model calls (tests); the watchdog lets them run in the background. */ wait?: boolean; } export async function feedbackTick(db: Db, opts: FeedbackTickOptions = {}): Promise { const log = opts.log ?? (() => {}); const now = (opts.now ?? new Date()).getTime(); // A Telegram album arrives photo by photo: give it a moment before the agent looks. const settleMs = Math.max(0, Number(process.env.PEPPA_FEEDBACK_SETTLE_SEC ?? 20) || 0) * 1000; const jobs: Promise[] = []; for (const f of await db.select().from(feedback).where(eq(feedback.status, "received")).orderBy(feedback.id).limit(20)) { if (inFlight.has(f.id)) continue; if (f.analysisStartedAt) { // Started by a process that is gone (this one would have it in flight): no second try. if (now - f.analysisStartedAt.getTime() > timeoutMs() + 60_000) await finishFeedbackAnalysis(db, f.id, { error: "агент не ответил" }); continue; } if (f.via === "telegram" && now - f.createdAt.getTime() < settleMs) continue; const [claimed] = await db .update(feedback) .set({ analysisStartedAt: new Date(now) }) .where(and(eq(feedback.id, f.id), eq(feedback.status, "received"), isNull(feedback.analysisStartedAt))) .returning(); if (!claimed) continue; inFlight.add(f.id); jobs.push( analyse(db, claimed, log) .catch(async (e) => { log(`feedback #${f.id}: ${(e as Error).message}`); await finishFeedbackAnalysis(db, f.id, { error: (e as Error).message }).catch(() => null); }) .finally(() => inFlight.delete(f.id)), ); } if (opts.wait) await Promise.all(jobs); const fixed = await closeFixedFeedback(db); if (fixed) log(`feedback: ${fixed} fixed, authors told`); } async function analyse(db: Db, f: Feedback, log: (m: string) => void): Promise { const skip = async (why: string) => { await finishFeedbackAnalysis(db, f.id, { error: why }); log(`feedback #${f.id}: без разбора — ${why}`); }; if (process.env.PEPPA_FEEDBACK === "off") return skip("агент обратной связи выключен"); const project = await feedbackProject(db); if (!project) return skip("нет проекта платформы"); const [author] = await db.select({ login: users.login }).from(users).where(eq(users.id, f.userId)); const files = feedbackScreenshotFiles(f).map((path) => ({ name: `screenshot-${basename(path)}`, path })); if (f.text) await guardUntrusted(db, { projectId: project.id, source: `обращение #${f.id}`, text: f.text }); const out = await claudePrint(db, project, { bin: process.env.PEPPA_FEEDBACK_BIN ?? process.env.PEPPA_INTAKE_BIN ?? "claude", model: process.env.PEPPA_FEEDBACK_MODEL ?? process.env.PEPPA_INTAKE_MODEL ?? "sonnet", timeoutMs: timeoutMs(), who: "агент обратной связи", files, prompt: feedbackPrompt({ f, author: author?.login ?? "?", screenshots: files.map((x) => x.name), ...(await feedbackPromptContext(db, project)) }), }); if (!out.ok) return skip(out.error); const analysis = parseFeedbackAnalysis(out.text); if (!analysis) return skip("ответ не по форме"); await finishFeedbackAnalysis(db, f.id, { analysis }); log(`feedback #${f.id}: ${analysis.kind}, options ${analysis.options.length}${analysis.duplicateOf ? `, duplicate of ${analysis.duplicateOf}` : ""}`); }