// PEP-153: is a person's message a question or a task? Cheap rules first (core/message-intent.ts), // then one short model call on the project's subscription. A question gets its answer right // away; a task is never filed silently — when the model is not at hand the person is asked. import { asIs, m } from "@peppa/shared/i18n"; import { ANALYST_MAX_STORIES, ANALYST_NAME, chatForUser, createTask, dropChatOffer, getChatOffer, intentPrompt, listUserProjects, mentionedTasks, notify, parseIntent, PeppaError, projectForUser, projectStatusBlock, quickIntent, setChatOffer, setIntakeState, splitStory, statusAnswer, type ChatOffer, type MessageKind, type Project, type User, } from "@peppa/core"; import { chatMessages, tasks, type Db } from "@peppa/db"; import { eq, sql } from "drizzle-orm"; import { sayInDiscussion } from "./analyst-chat.ts"; import { claudePrint } from "./claude-print.ts"; import { checkDuplicate } from "./task-dedup.ts"; export interface ClassifiedMessage { kind: MessageKind; /** The answer to a question; for `unsure` — the model's best answer, if it gave one. */ answer: string | null; /** The model was needed and did not answer (no subscription, a failure, not the JSON asked for). */ failed: boolean; } export interface ClassifyOptions { /** The text began with the key of the person's own project («PAY: …»). */ explicit?: boolean; /** The project the message is about, when known. */ project?: Project | null; log?: (m: string) => void; } /** The project a message is about: named in it by a task key, else the most recently active one. */ async function pickProject(db: Db, text: string, projects: Project[]): Promise { const named = (await mentionedTasks(db, text, projects)).map((t) => t.project); const touched = new Map(); for (const r of await db.select({ projectId: tasks.projectId, at: sql`max(${tasks.updatedAt})` }).from(tasks).groupBy(tasks.projectId)) touched.set(r.projectId, Number(r.at) || 0); const recent = [...projects].sort((a, b) => (touched.get(b.id) ?? 0) - (touched.get(a.id) ?? 0) || b.id - a.id); return [...new Set([...named, ...recent])]; } /** Question, task or unsure — and the answer to a question. Never throws. */ export async function classifyMessage(db: Db, user: Pick, text: string, o: ClassifyOptions = {}): Promise { const hint = quickIntent(text, { explicit: o.explicit }); if (hint === "task") return { kind: "task", answer: null, failed: false }; const log = o.log ?? (() => {}); const fromData = () => statusAnswer(db, user, { text, projectId: o.project?.id }).catch(() => null); const noModel = async (): Promise => (hint === "question" ? { kind: "question", answer: await fromData(), failed: true } : { kind: "unsure", answer: null, failed: true }); try { const mine = await listUserProjects(db, user.id); const projects = o.project ? [o.project] : await pickProject(db, text, mine); if (!projects.length || process.env.PEPPA_MESSAGE_INTENT === "off") return noModel(); const context = (await Promise.all(projects.slice(0, 3).map(async (p) => `# Проект ${p.key} «${p.name}»\n${await projectStatusBlock(db, p)}`))).join("\n\n"); const out = await claudePrint(db, projects[0]!, { bin: process.env.PEPPA_INTENT_BIN ?? process.env.PEPPA_INTAKE_BIN ?? "claude", model: process.env.PEPPA_INTENT_MODEL ?? "haiku", timeoutMs: Number(process.env.PEPPA_INTENT_TIMEOUT_MS ?? 30_000), prompt: intentPrompt(context, text), who: "диспетчер сообщений", }); const parsed = out.ok ? parseIntent(out.text) : null; if (!parsed) { log(`message intent: ${out.ok ? "unparsable answer" : out.error}`); return noModel(); } // The form says «question» and the model says «task»: ask the person. if (hint === "question" && parsed.kind === "task") return { kind: "unsure", answer: null, failed: false }; const kind = hint ?? parsed.kind; if (kind === "question") return { kind, answer: parsed.answer ?? (await fromData()), failed: false }; return { kind, answer: kind === "unsure" ? parsed.answer : null, failed: false }; } catch (e) { log(`message intent: ${(e as Error).message}`); return noModel(); } } // ── offers under a chat message (the project chat in the web) ───────────────── export type ChatOfferChoice = "task" | "answer" | "create" | "cancel" | "stories"; /** A button under a chat message: «Завести как задачу», «Ответить», «Создать», «Отмена». */ export async function resolveChatOffer(db: Db, user: User, messageId: number, choice: ChatOfferChoice): Promise { const [msg] = await db.select().from(chatMessages).where(eq(chatMessages.id, messageId)); if (!msg) throw new PeppaError(m("Сообщение не найдено. Обновите страницу.")); const chat = await chatForUser(db, user, msg.chatId); const offer = await getChatOffer(db, messageId); if (!offer || chat.kind !== "project" || !chat.projectId) throw new PeppaError(m("Эта кнопка уже не работает. Напишите сообщение ещё раз.")); const project = await projectForUser(db, user.id, chat.projectId); const allowed: Record = { task: ["task"], choice: ["answer", "task"], draft: ["create", "cancel"], proposals: [], stories: ["stories", "cancel"] }; if (!allowed[offer.kind].includes(choice)) throw new PeppaError(m("Эта кнопка уже не работает. Напишите сообщение ещё раз.")); // One press — one outcome: the buttons go away first. await dropChatOffer(db, messageId); const { title, rest } = splitStory(offer.text); const say = async (text: string, next: ChatOffer | null, author: string | null = null) => { const said = await sayInDiscussion(db, project, chat.id, text, author); if (said && next) await setChatOffer(db, said.id, next); }; if (choice === "task") { await say(m("📝 Новая задача «{title}». Создать?", { title }), { kind: "draft", text: offer.text }); } else if (choice === "answer") { const answer = offer.answer ?? (await statusAnswer(db, user, { projectId: project.id, text: offer.text })); await say(answer, { kind: "task", text: offer.text }, offer.answer ? ANALYST_NAME : null); } else if (choice === "stories") { // PEP-198 (7.1, 3.5): the person pressed «Завести задачи» — each suggested story is checked // for a repeat of an open or recently done one first; formulated with the analyst already, // they skip intake (3.4). const filed: string[] = []; const repeats: string[] = []; for (const s of (offer.stories ?? []).slice(0, ANALYST_MAX_STORIES)) { const dup = await checkDuplicate(db, project, s); if (dup.kind !== "none") { repeats.push(`• «${asIs(s.title)}» — ${dup.key}`); continue; } const ref = await createTask(db, { projectId: project.id, title: s.title, description: `${s.description}\n\n${m("Создано из чата проекта ({login}).", { login: user.login })}` }); await setIntakeState(db, ref.task.id, { stage: "done", original: { title: s.title, description: s.description }, attempts: 0, note: "сформулирована с аналитиком в чате" }); filed.push(`• ${ref.key} «${asIs(s.title)}»`); } await say( [filed.length ? `${m("📥 Завела задачи:")}\n${filed.join("\n")}` : "", repeats.length ? `${m("Не завела повторно — такие задачи уже есть:")}\n${repeats.join("\n")}` : ""].filter(Boolean).join("\n\n"), null, ANALYST_NAME, ); } else if (choice === "create") { const ref = await createTask(db, { projectId: project.id, title, description: `${rest ? `${rest}\n\n` : ""}${m("Создано из чата проекта ({login}).", { login: user.login })}` }); await say(`${m("📥 Создал {key}: {title}", { key: ref.key, title })}\n${process.env.PEPPA_WEB_URL ?? ""}/t/${ref.key}`, null); } await notify(db, { type: "chat_message", messageId }); }