Сообщение боту и в чате проекта сначала классифицируется (правила, затем модель на подписке проекта): вопрос получает ответ с кнопкой «Завести как задачу», описание изменения — черновик, неясное или сбой — выбор кнопками. OpenSpec change pep-153-question-not-task (в архиве). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
125 lines
6.7 KiB
TypeScript
125 lines
6.7 KiB
TypeScript
// 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 { m } from "@peppa/shared/i18n";
|
|
import {
|
|
ANALYST_NAME,
|
|
chatForUser,
|
|
createTask,
|
|
dropChatOffer,
|
|
getChatOffer,
|
|
intentPrompt,
|
|
listUserProjects,
|
|
mentionedTasks,
|
|
notify,
|
|
parseIntent,
|
|
PeppaError,
|
|
projectForUser,
|
|
projectStatusBlock,
|
|
quickIntent,
|
|
setChatOffer,
|
|
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";
|
|
|
|
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<Project[]> {
|
|
const named = (await mentionedTasks(db, text, projects)).map((t) => t.project);
|
|
const touched = new Map<number, number>();
|
|
for (const r of await db.select({ projectId: tasks.projectId, at: sql<number>`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<User, "id">, text: string, o: ClassifyOptions = {}): Promise<ClassifiedMessage> {
|
|
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<ClassifiedMessage> => (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";
|
|
|
|
/** A button under a chat message: «Завести как задачу», «Ответить», «Создать», «Отмена». */
|
|
export async function resolveChatOffer(db: Db, user: User, messageId: number, choice: ChatOfferChoice): Promise<void> {
|
|
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<ChatOffer["kind"], ChatOfferChoice[]> = { task: ["task"], choice: ["answer", "task"], draft: ["create", "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 === "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 });
|
|
}
|