peppa/packages/core/src/agent-message.ts
Асель 094ab632cc PEP-152: формат сообщения агента — суть, что нужно от вас, где посмотреть, подробности под «Подробнее»
Сообщение агента пользователю собирается из полей summary / need / link / details
(core/agent-message.ts); основной текст проверяется при приёме (длина, словарь, файлы,
ветки, команды, номера PR, статусы из кода) — нарушение возвращается агенту, после трёх
отказов подряд сообщение уходит с нейтральной первой строкой. Разбор словаря — общий
модуль @peppa/shared/glossary. Сайт и Telegram показывают основной текст, details — под
«Подробнее». Карточка «готово» и реплика конца хода — в том же формате. Правила агентам,
переводы en/kk, тесты по сценариям, change pep-152-agent-message-format в архиве.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-16 17:38:04 +05:00

217 lines
12 KiB
TypeScript
Raw Permalink 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-152: the format of an agent's message for the person. A message is four fields — the gist
// (`summary`), «Что нужно от вас» (`need`), «Где посмотреть» (`link`) and technical `details`.
// The platform builds the text from them: the main text (everything but `details`) is what the
// site, the chats and Telegram show; `details` open under «Подробнее».
// The main text is checked when the message is taken: its length, the «Нельзя» column of
// docs/glossary.md (the same parsing as `pnpm lint`) and technical marks — a file, a branch, a
// command, a PR number, a status in code, a tool or a runner name. A message that fails is not
// sent: the agent gets the list of violations back.
import { existsSync, readFileSync, statSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import type { Db } from "@peppa/db";
import { peppaRoot } from "@peppa/shared";
import { glossaryMatcher, parseGlossary, type Matcher } from "@peppa/shared/glossary";
import { asIs, m } from "@peppa/shared/i18n";
import { logEvent } from "./audit.ts";
import { PeppaError } from "./errors.ts";
import { clearRefusals, countRefusal } from "./message-details.ts";
import { alertAdmins } from "./monitor.ts";
import type { MessageType } from "./questions.ts";
import { stripServiceBlocks, userText } from "./user-text.ts";
export interface AgentMessage {
/** What happened, in plain words. */
summary: string;
/** One action the person has to take; empty — nothing. */
need?: string | null;
/** Where to look at the result (http/https). */
link?: string | null;
/** Technical details: shown only under «Подробнее», not checked. */
details?: string | null;
/** The gist is the platform's own neutral line, not the agent's words (it is translated). */
neutral?: boolean;
}
/** Lines of the main text a person sees without opening «Подробнее». */
export const MAIN_MAX_LINES = 5;
const MAIN_MAX_CHARS = 700;
const LINE_MAX_CHARS = 300;
/** Refusals in a row after which the message goes out with the platform's neutral first line. */
export const MAX_REFUSALS = 3;
const one = (s?: string | null) => (s ?? "").trim();
/**
* The text everybody sees: the gist, what is needed from the person, where to look. PEP-139: the
* agent's own words are marked free text — only the factory's phrases around them are translated.
* `defaultNeed` — the platform's phrase used when the agent named no action («ничего»).
*/
export function renderMain(msg: AgentMessage, o: { defaultNeed?: string } = {}): string {
const lines = [msg.neutral ? one(msg.summary) : asIs(one(msg.summary))];
lines.push(m("Что нужно от вас: {need}", { need: one(msg.need) ? asIs(one(msg.need)) : (o.defaultNeed ?? m("ничего")) }));
if (one(msg.link)) lines.push(m("Где посмотреть: {url}", { url: one(msg.link) }));
return lines.join("\n");
}
/** The details as they are stored: the agent's own words, marked free text. */
export const renderDetails = (msg: AgentMessage): string | null => asIs(stripServiceBlocks(one(msg.details))) || null;
const B = "(?<![\\p{L}\\p{N}_])";
const A = "(?![\\p{L}\\p{N}_])";
const FILE_EXT = "md|mdx|ts|tsx|js|jsx|mjs|cjs|json|ya?ml|sh|py|go|rs|rb|java|sql|css|scss|html|toml|lock|env|txt|log|csv|xml|ini|conf";
/** Technical marks that have no place in the main text: [what it is — for the agent, pattern]. */
const MARKS: Array<[string, RegExp]> = [
["a link (put it in `link`)", /https?:\/\/\S+/giu],
["branch", new RegExp(`${B}(?:(?:task|feature|feat|fix|hotfix|bugfix|release)/[\\w.-]+|origin/[\\w./-]+)`, "giu")],
["file name or path", new RegExp(`(?<![\\p{L}\\p{N}_/])(?:[\\w.-]*\\w\\.(?:${FILE_EXT})${A}|\\.?[A-Za-z_][\\w.-]+/[\\w.-]{2,}(?:/[\\w.-]+)*)`, "gu")],
["command", new RegExp(`\`[^\`]+\`|${B}(?:pnpm|npm|npx|yarn|git|docker|node|curl|openspec|tmux|bash|pip)\\s+[a-z-]{2,}|(?<!\\S)--[a-z][\\w-]*`, "gu")],
["pull request number", new RegExp(`${B}(?:PR|MR|ПР|пул-?реквест\\p{L}*)\\s*(?:#|№)?\\s*\\d+|(?<![\\p{L}\\p{N}_&])#\\d+`, "giu")],
["status or identifier from code", new RegExp(`${B}(?:[a-z][a-z0-9]*(?:_[a-z0-9]+)+|proposing|review|done|blocked)${A}|mcp__\\w+|${B}[A-Za-z_][\\w.]*\\(`, "gu")],
["runner or service name", new RegExp(`${B}(?:peppa-[a-z0-9-]+|s\\d+-g\\d+)${A}`, "gu")],
["commit hash", new RegExp(`${B}(?=[0-9a-f]*[a-f])(?=[0-9a-f]*\\d)[0-9a-f]{7,40}${A}`, "gu")],
];
let cached: { file: string; mtime: number; matcher: Matcher } | null = null;
/** The glossary of the platform (docs/glossary.md); null when the file cannot be read. */
export function platformGlossary(): Matcher | null {
try {
const file = join(peppaRoot(resolve(dirname(fileURLToPath(import.meta.url)), "../../..")), "docs/glossary.md");
if (!existsSync(file)) return null;
const mtime = statSync(file).mtimeMs;
if (cached?.file !== file || cached.mtime !== mtime) cached = { file, mtime, matcher: glossaryMatcher(parseGlossary(readFileSync(file, "utf8"))) };
return cached.matcher;
} catch {
return null;
}
}
/** What is wrong with a piece of the main text (empty — nothing). */
function textViolations(field: string, text: string, matcher: Matcher | null): string[] {
const out: string[] = [];
let rest = text;
for (const [what, re] of MARKS) {
const found = [...new Set([...rest.matchAll(re)].map((x) => x[0].trim()))];
if (!found.length) continue;
out.push(`${field}: ${what} — ${found.slice(0, 3).map((f) => `«${f}»`).join(", ")}`);
// A branch is not reported again as a path, a file not again as an identifier.
rest = rest.replace(re, (x) => " ".repeat(x.length));
}
const seen = new Set<string>();
for (const h of matcher?.find(rest) ?? []) {
if (seen.has(h.word)) continue;
seen.add(h.word);
out.push(`${field}: the word «${h.found}» is not for the owner — write «${h.write}»`);
}
return out;
}
export interface CheckOptions {
/** Lines the gist may take (a question with its context — up to 3). */
summaryLines?: number;
/** Answer buttons of a question: read by the person, checked like the main text. */
options?: string[];
/** Name of the gist field in the tool, for the refusal text. */
field?: string;
matcher?: Matcher | null;
}
/** Violations of the format, as a list for the agent; empty — the message may go. */
export function checkAgentMessage(msg: AgentMessage, o: CheckOptions = {}): string[] {
const matcher = o.matcher === undefined ? platformGlossary() : o.matcher;
const field = o.field ?? "summary";
const maxLines = o.summaryLines ?? 1;
const out: string[] = [];
const summary = one(msg.summary);
const need = one(msg.need);
const link = one(msg.link);
if (!summary) out.push(`${field}: empty — say in one sentence what happened`);
const lines = summary.split("\n").filter((l) => l.trim()).length;
if (lines > maxLines) out.push(`${field}: ${lines} lines — at most ${maxLines}; move the rest to \`details\``);
if (summary.length > LINE_MAX_CHARS * maxLines) out.push(`${field}: ${summary.length} characters — at most ${LINE_MAX_CHARS * maxLines}; move the rest to \`details\``);
out.push(...textViolations(field, summary, matcher));
if (need) {
if (need.includes("\n") || need.length > LINE_MAX_CHARS) out.push(`need: one action in one line (at most ${LINE_MAX_CHARS} characters)`);
out.push(...textViolations("need", need, matcher));
}
if (link && !/^https?:\/\/\S+$/i.test(link)) out.push("link: must be one http(s) address of the result, nothing else");
(o.options ?? []).forEach((opt, i) => out.push(...textViolations(`options[${i}]`, opt, matcher)));
return out;
}
/** The platform's own first line when the agent could not write a plain one. */
export const NEUTRAL_SUMMARY: Record<MessageType | "turn", string> = {
// «готово» is the platform's own message: without the agent's words it loses one line, no more.
done: "",
question: m("У агента есть вопрос по задаче."),
progress: m("Агент продолжает работу над задачей."),
blocker: m("Агент не может продолжить работу над задачей."),
turn: m("Агент закончил шаг работы над задачей."),
};
/** Everything the agent sent, as details of a message with a neutral first line. */
function asDetails(msg: AgentMessage): string {
return [one(msg.summary), one(msg.need), one(msg.link), one(msg.details)].filter(Boolean).join("\n\n");
}
/**
* The raw last reply of an agent's turn as a message: a reply that passes the check goes as it
* is; otherwise the gist is the platform's and the whole reply is under «Подробнее».
*/
export function fitAgentText(text: string, o: { matcher?: Matcher | null } = {}): AgentMessage {
// PEP-154: service blocks and terminal escapes are nobody's words — not even under «Подробнее».
const t = stripServiceBlocks(text);
const plain = userText(t);
if (plain && !checkAgentMessage({ summary: plain }, { summaryLines: 3, matcher: o.matcher }).length) return { summary: plain };
return { summary: NEUTRAL_SUMMARY.turn, details: t, neutral: true };
}
/**
* Takes an agent's message: returns it when the format holds; otherwise refuses with the list of
* violations (PeppaError — the tool answers with it). After MAX_REFUSALS refusals in a row the
* message is let through with the platform's neutral gist and the agent's text in the details;
* the superadmins hear about it once.
*/
export async function admitAgentMessage(
db: Db,
who: { projectId: number; taskId: number; taskKey: string; sessionId?: number | null },
type: MessageType,
msg: AgentMessage,
o: CheckOptions = {},
): Promise<AgentMessage & { neutral: boolean }> {
const key = who.sessionId ? `s${who.sessionId}` : `t${who.taskId}`;
const violations = checkAgentMessage(msg, o);
if (!violations.length) {
await clearRefusals(db, key);
return { ...msg, neutral: false };
}
const n = await countRefusal(db, key);
if (n <= MAX_REFUSALS) {
throw new PeppaError(
`Not sent (${n} of ${MAX_REFUSALS}): the owner is not an engineer, and the main text of the message breaks the format:\n${violations.map((v) => `- ${v}`).join("\n")}\nRewrite it in plain words (address the owner as «вы») and call the tool again. File names, branches, commands, PR numbers, statuses and other technical details belong in \`details\` — it opens under «Подробнее» and is not checked.`,
);
}
await clearRefusals(db, key);
await logEvent(db, { projectId: who.projectId, taskId: who.taskId, sessionId: who.sessionId ?? null, type: "message_format_failed", payload: { type, violations: violations.slice(0, 10) } });
await alertAdmins(db, `msgformat:${who.taskId}:${Date.now()}`, `✍️ ${who.taskKey}: ${m("агент трижды подряд не смог написать сообщение понятно — оно ушло с нейтральной первой строкой, текст агента под «Подробнее».")}`, () => {}).catch(() => 0);
return { summary: NEUTRAL_SUMMARY[type], need: null, link: /^https?:\/\/\S+$/i.test(one(msg.link)) ? one(msg.link) : null, details: asDetails({ ...msg, link: null }), neutral: true };
}
/**
* What a screen shows at once and what it hides: at most MAIN_MAX_LINES lines of the text, the
* rest together with the details — under «Подробнее».
*/
export function splitForDisplay(text: string, details?: string | null): { main: string; more: string | null } {
const lines = text.split("\n");
let main = lines.slice(0, MAIN_MAX_LINES).join("\n");
let rest = lines.slice(MAIN_MAX_LINES).join("\n");
if (main.length > MAIN_MAX_CHARS) {
rest = `…${main.slice(MAIN_MAX_CHARS)}${rest ? `\n${rest}` : ""}`;
main = `${main.slice(0, MAIN_MAX_CHARS)}…`;
}
const more = [rest.trim(), one(details)].filter(Boolean).join("\n\n");
return { main: main.trimEnd(), more: more || null };
}