peppa/packages/core/src/message-intent.ts

225 lines
14 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// PEP-153: a person's message is a question or a task. A question gets an answer (and a
// «Завести как задачу» button), a task — a draft; when it is not clear the person is asked.
// This module is the pure part: cheap rules, the classifier's prompt and parsing, the answer
// built from the platform's data without a model, and the offers (buttons) under chat messages.
// The model call is runner/message-intent.ts.
import { m } from "@peppa/shared/i18n";
import { questions, settings, tasks, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { and, eq, inArray, isNull } from "drizzle-orm";
import type { Project } from "./projects.ts";
import { listSessions } from "./sessions.ts";
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
import { listUserProjects } from "./users.ts";
export type MessageKind = "question" | "task" | "unsure";
export const TITLE_MAX = 120;
/** Title (first line, at most TITLE_MAX chars, cut at a word) and the rest as description. */
export function splitStory(body: string): { title: string; rest: string } {
const [first = "", ...lines] = body.trim().split("\n");
let title = first.trim();
let rest = lines.join("\n").trim();
if (title.length > TITLE_MAX) {
const cut = title.lastIndexOf(" ", TITLE_MAX - 1);
const at = cut > TITLE_MAX / 2 ? cut : TITLE_MAX - 1;
rest = `${title}${rest ? `\n\n${rest}` : ""}`;
title = `${title.slice(0, at).trim()}…`;
}
return { title, rest };
}
// ── cheap rules ───────────────────────────────────────────────────────────────
const ASKS = /^(?:а\s+|и\s+|ну\s+|скажи(?:те)?,?\s+|подскажи(?:те)?,?\s+)?(?:как(?:ие|ой|ая|ое|их|ова|овы)|сколько|когда|что\s+(?:с|со|там|сейчас|нового|делает|делают|происходит|в\s+работе)|где|кто|чем\s+занят|почему|зачем|как\s+(?:дела|там|идёт|идет|продвигается)|есть\s+ли|готов[аоы]?\s+ли|статус|what|what's|when|how|which|who|where|why|status|is|are|any|қандай|қанша|қашан|қайда|кім|неге|не\s+болып)(?![\p{L}\p{N}])/iu;
const WANTS = /^(?:пожалуйста,?\s+|please,?\s+)?(?:добав|сдела|исправ|почин|убер|удал|помен|измен|созда|нарису|перенес|переимену|настро|подключ|покаж|скро|обнов|замен|поправ|реализ|внедр|напиш|вывед|постав|верн|включ|выключ|отключ|запрет|разреш|нужн|надо(?![\p{L}])|хочу|хотим|хочется|давай|add(?![\p{L}])|make(?![\p{L}])|fix(?![\p{L}])|remove(?![\p{L}])|change(?![\p{L}])|create(?![\p{L}])|implement|update(?![\p{L}])|rename|show(?![\p{L}])|hide(?![\p{L}])|build(?![\p{L}])|let's|we\s+need|i\s+want|қос|жаса|түзет|өзгерт|керек)/iu;
/** A Russian infinitive as the first word: «добавить экспорт», «сделать, чтобы…». */
const INFINITIVE = /^[а-яё]{3,}(?:ть|ти|чь)(?:ся)?(?![\p{L}])/iu;
/**
* What the message is by its form alone; null — the rules cannot tell (both signs or none).
* `explicit` — the text began with the key of the person's own project («PAY: …», PEP-45).
*/
export function quickIntent(text: string, o: { explicit?: boolean } = {}): "question" | "task" | null {
const t = text.trim();
if (!t) return null;
const asks = /[??]\s*$/.test(t) || ASKS.test(t);
const wants = !!o.explicit || WANTS.test(t) || INFINITIVE.test(t);
if (asks === wants) return null;
return asks ? "question" : "task";
}
// ── the classifier (a model on the project's subscription) ────────────────────
export function intentPrompt(context: string, text: string): string {
return [
"Ты — диспетчер сообщений софтвер-фабрики Peppa FACTORY. Тебе пишет продакт-менеджер — не программист. Ты ИИ-агент и не выдаёшь себя за человека.",
"Определи, что это за сообщение:",
"- question — человек спрашивает (что происходит, что с задачей, когда будет готово, где посмотреть) и ждёт ответа, а не новой работы;",
"- task — человек описывает изменение продукта, которое нужно сделать («добавь…», «сделай, чтобы…», «не работает…, почините»);",
"- unsure — по сообщению нельзя понять, вопрос это или задача.",
"Для question напиши answer — ответ по данным ниже: коротко, простыми словами, без жаргона (PR, CI, API, ветка, деплой — нельзя), на «вы», на языке собеседника; где уместно — списком «агент — задача — что делает» и ссылкой из данных. Нет ответа в данных — скажи прямо, что не знаешь. Не хвали и не благодари.",
"",
context,
"",
"## Сообщение",
text.trim(),
"",
'Ответь ОДНОЙ строкой JSON без пояснений: {"kind":"question|task|unsure","answer":"…"}',
"answer — только для question (обычный текст, можно с переносами строк и списком через «•»), иначе пустая строка.",
].join("\n");
}
export interface MessageIntent {
kind: MessageKind;
answer: string | null;
}
/** The classifier's answer; null when it is not the JSON asked for. */
export function parseIntent(text: string): MessageIntent | null {
const found = /\{[\s\S]*\}/.exec(text);
if (!found) return null;
try {
const o = JSON.parse(found[0]) as { kind?: unknown; answer?: unknown };
if (o.kind !== "question" && o.kind !== "task" && o.kind !== "unsure") return null;
const answer = typeof o.answer === "string" ? o.answer.trim().slice(0, 3500) : "";
return { kind: o.kind, answer: answer || null };
} catch {
return null;
}
}
// ── the answer from the platform's data, no model ─────────────────────────────
const AGENT_STATE: Record<string, string> = {
starting: m("запускается"),
running: m("работает"),
waiting_input: m("ждёт вашего ответа"),
idle: m("свободен"),
stalled: m("остановился — нужна помощь"),
rate_limited: m("ждёт сброса лимита"),
};
const TASK_STATE: Record<string, string> = {
backlog: m("ждёт очереди"),
proposing: m("агент составляет план"),
awaiting_approval: m("ждёт вашего одобрения плана"),
in_progress: m("в работе у агента"),
review: m("готова, ждёт вашей приёмки"),
done: m("готова и принята"),
blocked: m("остановлена"),
};
const KEY_IN_TEXT = /(?<![\p{L}\p{N}])([A-Za-z][A-Za-z0-9]{1,9})-(\d{1,6})(?![\p{L}\p{N}])/gu;
/** Tasks named in the text by key («что с SHOP-3?») among the given projects. */
export async function mentionedTasks(db: Db, text: string, projects: Project[]): Promise<Array<{ key: string; title: string; status: string; project: Project }>> {
const out: Array<{ key: string; title: string; status: string; project: Project }> = [];
for (const hit of text.matchAll(KEY_IN_TEXT)) {
const project = projects.find((p) => p.key.toLowerCase() === hit[1]!.toLowerCase());
if (!project) continue;
const [t] = await db.select().from(tasks).where(and(eq(tasks.projectId, project.id), eq(tasks.number, Number(hit[2]))));
if (t && !out.some((x) => x.key === formatTaskKey(project.key, t.number))) out.push({ key: formatTaskKey(project.key, t.number), title: t.title, status: t.status, project });
}
return out.slice(0, 5);
}
/**
* «Агент — задача — что делает» for the person's projects (or one project), in plain words:
* the answer to a question about the state of things when no model is at hand.
*/
export async function statusAnswer(db: Db, user: { id: number }, o: { projectId?: number; text?: string; webUrl?: string } = {}): Promise<string> {
const webUrl = o.webUrl ?? process.env.PEPPA_WEB_URL ?? "";
const all = await listUserProjects(db, user.id);
const projects = o.projectId ? all.filter((p) => p.id === o.projectId) : all;
const ids = new Set(projects.map((p) => p.id));
const lines: string[] = [];
for (const t of o.text ? await mentionedTasks(db, o.text, projects) : []) {
lines.push(m("📌 {task} — {state}", { task: `${t.key} «${t.title}»`, state: TASK_STATE[t.status] ?? t.status }), `${webUrl}/t/${t.key}`, "");
}
const working = (await listSessions(db, { active: true })).filter((s) => ids.has(s.projectId) && s.taskKey);
lines.push(m("Агентов за работой: {n}", { n: working.length }));
for (const s of working.slice(0, 15)) {
lines.push(m("• {agent} — {task} — {state}", { agent: s.agentName ?? m("агент"), task: `${s.taskKey} «${s.taskTitle ?? ""}»`, state: AGENT_STATE[s.status] ?? s.status }));
}
if (ids.size) {
const idList = [...ids];
const open = await db.select({ id: questions.id }).from(questions).where(and(inArray(questions.projectId, idList), isNull(questions.answeredAt)));
if (open.length) lines.push(m("Ждут вашего ответа: {n}", { n: open.length }));
const review = await db.select({ projectId: tasks.projectId, number: tasks.number }).from(tasks).where(and(inArray(tasks.projectId, idList), eq(tasks.status, "review"), isNull(tasks.archivedAt)));
if (review.length) {
const keys = review.slice(0, 10).map((t) => formatTaskKey(projects.find((p) => p.id === t.projectId)!.key, t.number));
lines.push(m("Готовы и ждут вашей приёмки: {keys}", { keys: keys.join(", ") }));
}
}
lines.push(m("Все задачи: {url}", { url: projects.length === 1 ? `${webUrl}/p/${projects[0]!.key}` : `${webUrl}/` }));
return lines.join("\n");
}
// ── offers: buttons under a chat message (web) ────────────────────────────────
/**
* What a chat message offers to do next: `task` — «Завести как задачу» under an answer;
* `choice` — «Ответить» / «Завести задачу» when it is not clear; `draft` — «Создать» / «Отмена».
*/
export interface ChatOffer {
/** PEP-198 `stories`: the analyst's suggested stories — filed only by the person's «Завести задачи». */
kind: "task" | "choice" | "draft" | "proposals" | "stories";
/** The person's message the offer is about. */
text: string;
/** `choice`: the answer already at hand (the analyst's); null — answer from the data. */
answer?: string | null;
/** PEP-197 `proposals`: the stories the factory suggests (state is read live by `chatOffers`). */
items?: ProposalItem[];
/** PEP-198 `stories`: what the analyst suggests to file (at most four). */
stories?: Array<{ title: string; description: string }>;
}
export interface ProposalItem {
id: number;
key: string;
title: string;
severity: "breakage" | "important" | "minor" | null;
/** Live: still waiting for «Делать» / «Не надо». */
open?: boolean;
/** Live: what was decided. */
decision?: "approved" | "rejected" | null;
}
const OFFER_PREFIX = "chat.offer:";
const offerKey = (messageId: number) => `${OFFER_PREFIX}${messageId}`;
export const getChatOffer = (db: Db, messageId: number) => getSetting<ChatOffer>(db, offerKey(messageId));
export const setChatOffer = (db: Db, messageId: number, offer: ChatOffer) => setSetting(db, offerKey(messageId), offer);
export const dropChatOffer = (db: Db, messageId: number) => deleteSetting(db, offerKey(messageId));
export async function chatOffers(db: Db, messageIds: number[]): Promise<Map<number, ChatOffer>> {
const out = new Map<number, ChatOffer>();
if (!messageIds.length) return out;
for (const r of await db.select().from(settings).where(inArray(settings.key, messageIds.map(offerKey)))) out.set(Number(r.key.slice(OFFER_PREFIX.length)), r.value as ChatOffer);
// PEP-197: the list of suggested stories shows what became of each (the buttons live while undecided).
for (const offer of out.values()) {
if (offer.kind !== "proposals" || !offer.items?.length) continue;
const rows = await db.select({ id: tasks.id, proposed: tasks.proposed, archivedAt: tasks.archivedAt }).from(tasks).where(inArray(tasks.id, offer.items.map((i) => i.id)));
const byId = new Map(rows.map((x) => [x.id, x]));
offer.items = offer.items.map((i) => {
const t = byId.get(i.id);
return { ...i, open: !!t?.proposed && !t.archivedAt, decision: !t || t.proposed ? null : t.archivedAt ? "rejected" : "approved" };
});
}
return out;
}
/** Texts of the offers — one place for the bot, the chat and the tests. */
export const INTENT_TEXT = {
asTask: m("📝 Завести как задачу"),
answer: m("💬 Ответить"),
file: m("📝 Завести задачу"),
create: m("✅ Создать"),
cancel: m("✖️ Отмена"),
unsure: m("Не понял, это вопрос или новая задача. Ответить или завести задачу?"),
failed: m("Сейчас не получилось разобрать сообщение. Ответить или завести задачу?"),
pick: m("Ответить по данным проекта или завести задачу? Выберите кнопкой."),
};