Сообщение агента пользователю собирается из полей 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>
397 lines
17 KiB
TypeScript
397 lines
17 KiB
TypeScript
// Interface language (PEP-98). Dictionary keys are the Russian strings themselves (templates
|
||
// with {name} placeholders): Russian needs no dictionary, a missing translation shows Russian.
|
||
// `t` translates a known key; `localizeText` translates text that was already rendered from a
|
||
// template somewhere else (core/runner messages, errors, notifications) by reverse matching.
|
||
// Pure module: used by the server, the bot and client components.
|
||
import { en } from "./en/index.ts";
|
||
import { kk } from "./kk.ts";
|
||
|
||
export const LOCALES = ["ru", "en", "kk"] as const;
|
||
export type Locale = (typeof LOCALES)[number];
|
||
export const DEFAULT_LOCALE: Locale = "ru";
|
||
/** Cookie with the chosen language. */
|
||
export const LOCALE_COOKIE = "peppa_lang";
|
||
/** Switcher labels. */
|
||
export const LOCALE_LABELS: Record<Locale, string> = { ru: "RU", en: "EN", kk: "KZ" };
|
||
|
||
export type Dict = Record<string, string>;
|
||
|
||
const DICTS: Record<Locale, Dict> = { ru: {}, en, kk };
|
||
|
||
export function normalizeLocale(v: unknown): Locale {
|
||
return typeof v === "string" && (LOCALES as readonly string[]).includes(v) ? (v as Locale) : DEFAULT_LOCALE;
|
||
}
|
||
|
||
export const isLocale = (v: unknown): v is Locale => typeof v === "string" && (LOCALES as readonly string[]).includes(v);
|
||
|
||
/** Best language from an Accept-Language header (null when nothing matches). */
|
||
export function localeFromAcceptLanguage(header: string | null | undefined): Locale | null {
|
||
if (!header) return null;
|
||
const langs = header
|
||
.split(",")
|
||
.map((p) => {
|
||
const [tag, ...params] = p.trim().split(";");
|
||
const q = params.map((x) => x.trim()).find((x) => x.startsWith("q="));
|
||
return { tag: (tag ?? "").toLowerCase(), q: q ? Number(q.slice(2)) || 0 : 1 };
|
||
})
|
||
.filter((x) => x.tag)
|
||
.sort((a, b) => b.q - a.q);
|
||
for (const { tag } of langs) {
|
||
const base = tag.split("-")[0];
|
||
if (base === "ru") return "ru";
|
||
if (base === "en") return "en";
|
||
if (base === "kk" || base === "kz") return "kk";
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/** Substitutes {name} placeholders. */
|
||
export function fill(s: string, vars?: Record<string, unknown>): string {
|
||
if (!vars) return s;
|
||
return s.replace(/\{(\w+)\}/g, (all, k: string) => (k in vars && vars[k] != null ? String(vars[k]) : all));
|
||
}
|
||
|
||
/** The dictionary entry for `key` in `locale`, or undefined (kk falls back to Russian). */
|
||
function entry(locale: Locale, key: string): string | undefined {
|
||
return DICTS[locale][key];
|
||
}
|
||
|
||
/** Translates a Russian key (a template) into `locale` and fills the placeholders. */
|
||
export function t(locale: Locale, key: string, vars?: Record<string, unknown>): string {
|
||
return fill(entry(locale, key) ?? key, vars);
|
||
}
|
||
|
||
/**
|
||
* Marks a Russian template for the dictionary check and renders it in Russian (as before).
|
||
* Used where the text is produced without knowing the reader (core, runner); the delivery
|
||
* layer translates it with `localizeText`.
|
||
*/
|
||
export const m = (key: string, vars?: Record<string, unknown>): string => fill(key, vars);
|
||
|
||
/** Russian plural form: one (1, 21), few (2–4, 22), many (5, 11, 25). */
|
||
export function ruPlural<T>(n: number, one: T, few: T, many: T): T {
|
||
const a = Math.abs(n) % 100;
|
||
const b = a % 10;
|
||
if (a > 10 && a < 20) return many;
|
||
if (b === 1) return one;
|
||
if (b >= 2 && b <= 4) return few;
|
||
return many;
|
||
}
|
||
|
||
/**
|
||
* Plural-aware translation: Russian forms are the keys; English uses the `one` entry for
|
||
* n = 1 and the `many` entry otherwise. `{n}` is filled with the number.
|
||
*/
|
||
export function tn(locale: Locale, n: number, one: string, few: string, many: string, vars?: Record<string, unknown>): string {
|
||
const v = { n, ...vars };
|
||
if (locale === "ru" || (locale === "kk" && entry("kk", many) === undefined)) return fill(ruPlural(n, one, few, many), v);
|
||
return t(locale, n === 1 ? one : many, v);
|
||
}
|
||
|
||
/** A translator bound to a locale — what pages and components use. */
|
||
export interface Translator {
|
||
(key: string, vars?: Record<string, unknown>): string;
|
||
locale: Locale;
|
||
n: (n: number, one: string, few: string, many: string, vars?: Record<string, unknown>) => string;
|
||
/** Translates already rendered Russian text (see localizeText). */
|
||
text: (text: string | null | undefined) => string;
|
||
/** Translates the fixed lines of an AI role's message, leaving its free text (see localizeRoleMessage). */
|
||
role: (text: string | null | undefined) => string;
|
||
}
|
||
|
||
export function translator(locale: Locale): Translator {
|
||
const fn = ((key: string, vars?: Record<string, unknown>) => t(locale, key, vars)) as Translator;
|
||
fn.locale = locale;
|
||
fn.n = (n, one, few, many, vars) => tn(locale, n, one, few, many, vars);
|
||
fn.text = (text) => localizeText(locale, text ?? "");
|
||
fn.role = (text) => localizeRoleMessage(locale, text);
|
||
return fn;
|
||
}
|
||
|
||
// ---- Reverse matching of rendered text --------------------------------------------------
|
||
|
||
interface Template {
|
||
re: RegExp;
|
||
names: string[];
|
||
out: string;
|
||
weight: number;
|
||
/** Starts with a placeholder: anchored only by text in the middle ("{a} из {b}"). */
|
||
loose: boolean;
|
||
}
|
||
|
||
const CYR = /[А-Яа-яЁё]/;
|
||
const compiled = new Map<Locale, { byHead: Map<string, Template[]>; loose: Template[] }>();
|
||
const caches = new Map<Locale, Map<string, string>>();
|
||
const CACHE_MAX = 5000;
|
||
|
||
const escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||
|
||
function compile(locale: Locale) {
|
||
let c = compiled.get(locale);
|
||
if (c) return c;
|
||
c = { byHead: new Map(), loose: [] };
|
||
for (const [key, out] of Object.entries(DICTS[locale])) {
|
||
if (!key.includes("{")) continue;
|
||
const parts = key.split(/\{(\w+)\}/);
|
||
const names: string[] = [];
|
||
let src = "^";
|
||
let weight = 0;
|
||
for (let i = 0; i < parts.length; i++) {
|
||
if (i % 2) {
|
||
names.push(parts[i]!);
|
||
// A one-line key must not swallow the following lines of a multi-line message.
|
||
src += key.includes("\n") ? "([\\s\\S]+?)" : "([^\\n]+?)";
|
||
} else {
|
||
src += escapeRe(parts[i]!);
|
||
weight += parts[i]!.length;
|
||
}
|
||
}
|
||
if (weight < 2) continue; // "{a} {b}" would match anything
|
||
const tpl: Template = { re: new RegExp(src + "$"), names, out, weight, loose: parts[0] === "" };
|
||
const head = parts[0]!.slice(0, 2);
|
||
if (head.length === 2) {
|
||
const list = c.byHead.get(head) ?? [];
|
||
list.push(tpl);
|
||
c.byHead.set(head, list);
|
||
} else c.loose.push(tpl);
|
||
}
|
||
for (const list of c.byHead.values()) list.sort((a, b) => b.weight - a.weight);
|
||
c.loose.sort((a, b) => b.weight - a.weight);
|
||
compiled.set(locale, c);
|
||
return c;
|
||
}
|
||
|
||
/** A translation and how many Russian letters it left untranslated (Kazakh is Cyrillic too). */
|
||
interface Rendered {
|
||
text: string;
|
||
left: number;
|
||
}
|
||
|
||
function matchTemplate(locale: Locale, s: string, depth: number): Rendered | undefined {
|
||
const c = compile(locale);
|
||
const lists = [c.byHead.get(s.slice(0, 2)) ?? [], c.loose];
|
||
for (const list of lists) {
|
||
for (const tpl of list) {
|
||
const mt = tpl.re.exec(s);
|
||
if (!mt) continue;
|
||
const vars: Record<string, string> = {};
|
||
let left = 0;
|
||
let ok = true;
|
||
tpl.names.forEach((name, i) => {
|
||
const v = mt[i + 1]!;
|
||
const sub = depth < 2 ? piece(locale, v, depth + 1) : undefined;
|
||
vars[name] = sub?.text ?? v;
|
||
const rest = sub ? sub.left : cyrillic(v);
|
||
left += rest;
|
||
// A template anchored only in the middle must not cut free Russian text (a person's or an
|
||
// agent's sentence "Какой формат из двух?" is not "{done} из {total}"). Russian left
|
||
// untranslated counts, not Cyrillic: Kazakh is Cyrillic too.
|
||
if (tpl.loose && rest) ok = false;
|
||
});
|
||
if (!ok) continue;
|
||
return { text: fill(tpl.out, vars), left };
|
||
}
|
||
}
|
||
return undefined;
|
||
}
|
||
|
||
/** Exact entry or a template match; undefined when nothing fits. */
|
||
function piece(locale: Locale, s: string, depth = 0): Rendered | undefined {
|
||
if (!CYR.test(s)) return undefined;
|
||
const exact = entry(locale, s);
|
||
if (exact !== undefined) return { text: exact, left: 0 };
|
||
return matchTemplate(locale, s, depth);
|
||
}
|
||
|
||
/** Leading/trailing decoration around a phrase: whitespace, emoji, bullets, dashes, punctuation. */
|
||
const EDGE = /^([^А-Яа-яЁёA-Za-z0-9«"(<{]*)([\s\S]*?)([\s.:;,!?…)»"]*)$/u;
|
||
|
||
const cyrillic = (s: string) => (s.match(/[А-Яа-яЁё]/g) ?? []).length;
|
||
/** The variant with the least Russian left untranslated; the first one wins a tie. */
|
||
const fewest = (list: Rendered[]) => list.reduce((best, x) => (x.left < best.left ? x : best));
|
||
const untouched = (s: string): Rendered => ({ text: s, left: cyrillic(s) });
|
||
|
||
function phrase(locale: Locale, s: string): Rendered {
|
||
const out = [untouched(s)];
|
||
const direct = piece(locale, s);
|
||
if (direct !== undefined) {
|
||
if (!direct.left) return direct;
|
||
out.push(direct);
|
||
}
|
||
// Decorations stripped: "🧪 Проверки: 4 из 4" must not be eaten by a key starting with a placeholder.
|
||
const mt = EDGE.exec(s);
|
||
if (mt && (mt[1] || mt[3])) {
|
||
const core = mt[2]!;
|
||
const inner = piece(locale, core);
|
||
if (inner !== undefined) out.push({ text: mt[1] + inner.text + mt[3], left: inner.left + cyrillic(mt[1]! + mt[3]) });
|
||
if (mt[3]) {
|
||
const kept = mt[3].trimEnd();
|
||
const withTail = piece(locale, core + kept);
|
||
if (withTail !== undefined) out.push({ text: mt[1] + withTail.text + mt[3].slice(kept.length), left: withTail.left + cyrillic(mt[1]!) });
|
||
}
|
||
}
|
||
return fewest(out);
|
||
}
|
||
|
||
const joined = (parts: Rendered[], sep: string): Rendered => ({
|
||
text: parts.map((p) => p.text).join(sep),
|
||
left: parts.reduce((n, p) => n + p.left, 0),
|
||
});
|
||
|
||
function line(locale: Locale, s: string): Rendered {
|
||
if (!CYR.test(s)) return untouched(s);
|
||
const whole = phrase(locale, s);
|
||
if (!whole.left) return whole;
|
||
const out = [whole];
|
||
// Telegram HTML: the text between tags one by one.
|
||
if (s.includes("<")) {
|
||
const segs = s.split(/(<[^>]+>)/);
|
||
if (segs.length > 1) out.push(joined(segs.map((seg) => (seg.startsWith("<") || !seg ? untouched(seg) : line(locale, seg))), ""));
|
||
}
|
||
// "a · b", "a — b" and "Label: value" pieces.
|
||
for (const sep of [" · ", " — ", ": "]) {
|
||
if (s.includes(sep)) out.push(joined(s.split(sep).map((p) => line(locale, p)), sep));
|
||
}
|
||
return fewest(out);
|
||
}
|
||
|
||
/**
|
||
* Translates already rendered Russian text into `locale`: the whole text, its lines one by one,
|
||
* the pieces between HTML tags and around " · ", " — ", ": " are tried and the variant with the
|
||
* least Russian left wins (a short template must not swallow a longer message). Unknown text
|
||
* stays as it is.
|
||
*/
|
||
export function localizeText(locale: Locale, text: string): string {
|
||
if (!text) return text;
|
||
if (!text.includes(AS_IS_OPEN)) return rendered(locale, stripAsIs(text));
|
||
if (locale === "ru") return stripAsIs(text);
|
||
// PEP-139: free text goes around the matching as tokens without Cyrillic — it is neither
|
||
// split into lines and pieces nor counted as "Russian left", and comes back as written.
|
||
const kept: string[] = [];
|
||
const skeleton = text.replace(AS_IS_SPAN, (_all, inner: string) => `${AS_IS_OPEN}${kept.push(inner) - 1}${AS_IS_CLOSE}`);
|
||
return stripAsIs(rendered(locale, skeleton).replace(AS_IS_TOKEN, (_all, i: string) => kept[Number(i)] ?? ""));
|
||
}
|
||
|
||
function rendered(locale: Locale, text: string): string {
|
||
if (locale === "ru" || !text || !CYR.test(text)) return text;
|
||
let cache = caches.get(locale);
|
||
if (!cache) caches.set(locale, (cache = new Map()));
|
||
const hit = cache.get(text);
|
||
if (hit !== undefined) return hit;
|
||
const whole = phrase(locale, text);
|
||
const out = (
|
||
!whole.left ? whole : text.includes("\n") ? fewest([whole, joined(text.split("\n").map((l) => line(locale, l)), "\n")]) : fewest([whole, line(locale, text)])
|
||
).text;
|
||
if (cache.size >= CACHE_MAX) cache.clear();
|
||
cache.set(text, out);
|
||
return out;
|
||
}
|
||
|
||
// ---- Free text inside rendered messages (PEP-139) -----------------------------------------
|
||
|
||
// U+2068 / U+2069 (directional isolates): invisible and harmless where a text is shown unstripped.
|
||
const AS_IS_OPEN = "\u2068";
|
||
const AS_IS_CLOSE = "\u2069";
|
||
/** A marked piece; a mark left open (the text was cut) runs to the end. */
|
||
const AS_IS_SPAN = /\u2068([^\u2069]*)(?:\u2069|$)/g;
|
||
const AS_IS_TOKEN = /\u2068(\d+)\u2069/g;
|
||
const AS_IS_MARKS = /[\u2068\u2069]/g;
|
||
|
||
/** Removes the free-text marks: the text as it is shown to a reader. */
|
||
export const stripAsIs = (text: string): string => (text.includes(AS_IS_OPEN) || text.includes(AS_IS_CLOSE) ? text.replace(AS_IS_MARKS, "") : text);
|
||
|
||
/**
|
||
* Marks free text — a person's or a model's own words, a story title, a login — inside a
|
||
* message that is rendered in Russian and translated later: `localizeText` leaves the marked
|
||
* piece exactly as written and translates only the factory's phrases around it. Whoever shows
|
||
* the message translates it (`localizeText`, `Translator.text`) or calls `stripAsIs`.
|
||
*/
|
||
/** PEP-152: does the text carry free-text marks already? */
|
||
export const hasAsIs = (text: string | null | undefined): boolean => !!text && text.includes(AS_IS_OPEN);
|
||
|
||
export const asIs = (text: string | null | undefined): string => (text ? `${AS_IS_OPEN}${stripAsIs(text)}${AS_IS_CLOSE}` : "");
|
||
|
||
// ---- Messages of the AI roles: fixed lines among free text (PEP-138) ----------------------
|
||
|
||
/**
|
||
* The fixed lines of the messages AI roles write into a project's discussion (analyst, product
|
||
* agent, the «чтобы заработало по-настоящему» list) and the roles' names. The rest of such a
|
||
* message is the model's own text, which `localizeText` must not touch: its "least Russian
|
||
* left" matching rewrites free sentences («Сделано три задачи из пяти.»).
|
||
*/
|
||
export const ROLE_MESSAGE_KEYS: readonly string[] = [
|
||
"Аналитик",
|
||
"Продакт",
|
||
"Агент",
|
||
"Агент {name}",
|
||
"Завёл в бэклог:",
|
||
"Посмотрел рабочую версию: {url}",
|
||
"Посмотрел версию для проверки: {url}",
|
||
"Как пользоваться:",
|
||
"Пока не настоящее:",
|
||
"Чтобы заработало по-настоящему, нужно от вас:",
|
||
"Где взять: {how}",
|
||
"Вставить или отметить «Сделано» — в карточке «Ваш продукт»: {url}",
|
||
"Завёл доработки в бэклог:",
|
||
"Чтобы продукт заработал по-настоящему, а не в демо-режиме, нужно от вас:",
|
||
"Куда вставить: страница проекта → карточка «Ваш продукт» → поле рядом с этим пунктом.",
|
||
"Когда сделаете — отметьте «Сделано» в карточке «Ваш продукт».",
|
||
"Карточка «Ваш продукт»: {url}",
|
||
"Ключи хранятся зашифрованными, Peppa FACTORY сама передаст их продукту и перезапустит его.",
|
||
];
|
||
|
||
const roleLines = new Map<Locale, { exact: Map<string, string>; templates: { re: RegExp; names: string[]; out: string }[] }>();
|
||
|
||
function compileRoleLines(locale: Locale) {
|
||
let c = roleLines.get(locale);
|
||
if (c) return c;
|
||
c = { exact: new Map(), templates: [] };
|
||
for (const key of ROLE_MESSAGE_KEYS) {
|
||
const out = entry(locale, key);
|
||
if (out === undefined) continue;
|
||
if (!key.includes("{")) {
|
||
c.exact.set(key, out);
|
||
continue;
|
||
}
|
||
const parts = key.split(/\{(\w+)\}/);
|
||
c.templates.push({ re: new RegExp(`^${parts.map((p, i) => (i % 2 ? "(.+)" : escapeRe(p))).join("")}$`), names: parts.filter((_p, i) => i % 2), out });
|
||
}
|
||
roleLines.set(locale, c);
|
||
return c;
|
||
}
|
||
|
||
/**
|
||
* Translates a message of an AI role: only whole lines that are one of ROLE_MESSAGE_KEYS
|
||
* (indentation kept, placeholder values as written); every other line stays as it is.
|
||
*/
|
||
export function localizeRoleMessage(locale: Locale, text: string | null | undefined): string {
|
||
if (!text) return "";
|
||
text = stripAsIs(text);
|
||
if (locale === "ru" || !CYR.test(text)) return text;
|
||
const c = compileRoleLines(locale);
|
||
return text
|
||
.split("\n")
|
||
.map((raw) => {
|
||
const lead = /^\s*/.exec(raw)![0];
|
||
const body = raw.slice(lead.length);
|
||
const exact = c.exact.get(body);
|
||
if (exact !== undefined) return lead + exact;
|
||
for (const tpl of c.templates) {
|
||
const mt = tpl.re.exec(body);
|
||
if (mt) return lead + fill(tpl.out, Object.fromEntries(tpl.names.map((n, i) => [n, mt[i + 1]])));
|
||
}
|
||
return raw;
|
||
})
|
||
.join("\n");
|
||
}
|
||
|
||
/** BCP 47 tag for Intl / toLocaleString in `locale`. */
|
||
export const intlLocale = (locale: Locale) => (locale === "en" ? "en-GB" : locale === "kk" ? "kk-KZ" : "ru-RU");
|
||
|
||
/** Product name — the same in every language, never translated or transliterated (PM decision). */
|
||
export const PRODUCT_NAME = "Peppa FACTORY";
|
||
export const productName = (_locale?: Locale) => PRODUCT_NAME;
|
||
|
||
/** All keys of the English dictionary (for the coverage check). */
|
||
export const dictionary = (locale: Locale): Dict => DICTS[locale];
|