145 lines
7.3 KiB
TypeScript
145 lines
7.3 KiB
TypeScript
// PEP-154: what a person reads must not carry service text. One filter for everything shown to
|
||
// the user from an agent's mouth or from a terminal: service blocks (<task-notification>,
|
||
// <system-reminder>, any XML/HTML-like tag), ANSI sequences, code and command output, shell
|
||
// prompt lines, stack traces, absolute paths. The original stays under «Подробнее» for a
|
||
// superadmin and the «Инженер» view (`question.details:<id>`), never in the main text.
|
||
import { settings, type Db } from "@peppa/db";
|
||
import { and, like, lt } from "drizzle-orm";
|
||
import { PeppaError } from "./errors.ts";
|
||
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
|
||
|
||
/** Blocks Claude Code and Peppa put into a conversation for the model, never for a person. */
|
||
const SERVICE_TAGS = [
|
||
"task-notification",
|
||
"system-reminder",
|
||
"local-command-stdout",
|
||
"local-command-stderr",
|
||
"local-command-caveat",
|
||
"command-name",
|
||
"command-message",
|
||
"command-args",
|
||
"command-contents",
|
||
"bash-input",
|
||
"bash-stdout",
|
||
"bash-stderr",
|
||
"user-prompt-submit-hook",
|
||
"user-memory-input",
|
||
"persisted-output",
|
||
"tool_use_error",
|
||
"function_calls",
|
||
"function_results",
|
||
"new-diagnostics",
|
||
"ide_opened_file",
|
||
"ide_selection",
|
||
"pasted_content",
|
||
].join("|");
|
||
|
||
// CSI / OSC / two-byte escapes, then the other control characters (tab, \n and \r stay).
|
||
const ANSI_RE = /\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-Z\\-_]|[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g;
|
||
const SERVICE_BLOCK_RE = new RegExp(`<(${SERVICE_TAGS})\\b[^>]*>[\\s\\S]*?</\\1\\s*>`, "gi");
|
||
/** A service block cut off before its closing tag (clipped text): everything after it is its body. */
|
||
const SERVICE_OPEN_RE = new RegExp(`<(?:${SERVICE_TAGS})\\b[^>]*>[\\s\\S]*$`, "i");
|
||
|
||
/**
|
||
* Removes only what is certainly not a person's words: known service blocks and terminal
|
||
* escape sequences. Safe for a person's own text (an answer, input typed into a terminal).
|
||
*/
|
||
export function stripServiceBlocks(text: string): string {
|
||
return text.replace(/\r\n?/g, "\n").replace(ANSI_RE, "").replace(SERVICE_BLOCK_RE, "").replace(SERVICE_OPEN_RE, "").trim();
|
||
}
|
||
|
||
/** Input that reached a session but was not typed by anyone: nothing is left without service blocks. */
|
||
export const isServiceInput = (text: string) => !!text.trim() && !stripServiceBlocks(text);
|
||
|
||
// Where a removed block stood (private-use character: never in real text).
|
||
const CUT = "";
|
||
// Any paired block whose tag name has a hyphen or an underscore — nobody writes prose like that.
|
||
const CUSTOM_BLOCK_RE = /<([a-z][\w.]*[-_][\w.-]*)\b[^>]*>[\s\S]*?<\/\1\s*>/gi;
|
||
const FENCE_RE = /^[ \t]*(```|~~~)[^\n]*\n[\s\S]*?(?:^[ \t]*\1[ \t]*$|(?![\s\S]))/gm;
|
||
const TAG_RE = /<\/?[a-zA-Z][\w:.-]*(?:\s[^<>]*)?\/?>/g;
|
||
const PROMPT_LINE_RE = /^\s*(?:[\w.-]+@[\w.-]+[^\n$#%]*[$#%]|\$|❯|➜|>>>|PS [A-Za-z]:\\[^>\n]*>)\s+\S.*$/;
|
||
const TRACE_LINE_RE = /^\s*(?:at\s.+(?::\d+:\d+\)?|\))\s*$|File ".+", line \d+.*$|Traceback \(most recent call last\):?\s*$|\.{3} \d+ more\s*$|Caused by: .+$)/;
|
||
const ERROR_HEAD_RE = /^\s*(?:Uncaught\s+)?(?:[\w$]+\.)*[\w$]*(?:Error|Exception)\b.*$/;
|
||
const PATH_SRC = String.raw`(?<![\w/.:~\\-])(?:~\/|\/(?:Users|home|private|tmp|var|etc|opt|usr|root|Volumes|mnt|srv|workspace)\/|[A-Za-z]:\\|\/(?=[\w.@+-]+\/[\w.@+-])|(?=(?:[\w.@+-]+\/){2,}[\w.@+-]*\.[A-Za-z]{1,5}\b))[^\s"'\`<>()\[\],;]*`;
|
||
const PATH_RE = new RegExp(PATH_SRC, "g");
|
||
const HAS_PATH_RE = new RegExp(PATH_SRC);
|
||
const INLINE_CODE_RE = /`[^`\n]*`/g;
|
||
const HAS_WORD_RE = /[\p{L}\p{N}]/u;
|
||
|
||
/**
|
||
* Text of an agent or a terminal, as a person may read it: without service blocks, tags, code
|
||
* and command output, shell prompts, stack traces and absolute paths. Idempotent. An empty
|
||
* result means there was nothing for a person in it.
|
||
*/
|
||
export function userText(text: string): string {
|
||
const src = stripServiceBlocks(text);
|
||
let s = src.replace(CUSTOM_BLOCK_RE, "").replace(FENCE_RE, `${CUT}\n`);
|
||
const lines = s.split("\n");
|
||
const kept: string[] = [];
|
||
for (let i = 0; i < lines.length; i++) {
|
||
const line = lines[i]!;
|
||
const cutLine = PROMPT_LINE_RE.test(line) || TRACE_LINE_RE.test(line) || (ERROR_HEAD_RE.test(line) && TRACE_LINE_RE.test(lines[i + 1] ?? ""));
|
||
kept.push(cutLine ? CUT : line);
|
||
}
|
||
s = kept.join("\n");
|
||
s = s.replace(INLINE_CODE_RE, (code) => (HAS_PATH_RE.test(code) ? "" : code)).replace(PATH_RE, (path) => /[.!?]$/.test(path) ? path.slice(-1) : "").replace(TAG_RE, "");
|
||
const out: string[] = [];
|
||
const srcLines = new Set(src.split("\n").map((l) => l.trim()));
|
||
for (const raw of s.split("\n")) {
|
||
if (raw.includes(CUT)) {
|
||
// «Вот вывод:» before a removed block: the colon promises what is no longer there.
|
||
for (let j = out.length - 1; j >= 0; j--) {
|
||
if (!out[j]) continue;
|
||
if (/[::]$/.test(out[j]!)) out[j] = `${out[j]!.slice(0, -1)}.`;
|
||
break;
|
||
}
|
||
out.push("");
|
||
continue;
|
||
}
|
||
const line = raw
|
||
.replace(/[ \t]+$/g, "")
|
||
.replace(/(\S)[ \t]{2,}/g, "$1 ")
|
||
.replace(/\(\s*[,;:]?\s*\)|\[\s*\]|«\s*»|"\s*"|``/g, "")
|
||
.replace(/[ \t]+([.,;:!?)»])/g, "$1")
|
||
.replace(/([(«])[ \t]+/g, "$1")
|
||
.replace(/[ \t]+$/g, "");
|
||
// A line the filter emptied (a bullet with only a path) goes away; an untouched one stays.
|
||
if (line.trim() && !HAS_WORD_RE.test(line) && !srcLines.has(raw.trim())) continue;
|
||
// «Файл: <path>» without the path is a label of nothing.
|
||
if (/[::]$/.test(line) && line.trim().split(/\s+/).length <= 3 && !srcLines.has(raw.trim())) continue;
|
||
out.push(line);
|
||
}
|
||
return out.join("\n").replace(/\n{3,}/g, "\n\n").trim();
|
||
}
|
||
|
||
/**
|
||
* The text of a message for the user as it is stored. A permission request keeps its command
|
||
* (that is what the person allows; «Продакт» has it under «Подробнее», PEP-120). Nothing left
|
||
* after the filter — no message: PeppaError (an agent's `ask_pm` gets it as a hint).
|
||
*/
|
||
export function messageText(kind: string, text: string): string {
|
||
if (kind === "permission") return text;
|
||
const shown = userText(text);
|
||
// i18n-ignore: read by the agent (ask_pm) or the log, not by the user
|
||
if (!shown) throw new PeppaError("В сообщении только служебный текст (теги, вывод команд, пути) — показать пользователю нечего. Напиши его простыми словами.");
|
||
return shown;
|
||
}
|
||
|
||
const DETAILS_PREFIX = "question.details:";
|
||
const detailsKey = (questionId: number) => `${DETAILS_PREFIX}${questionId}`;
|
||
|
||
/** Keeps the original of a filtered message for «Подробнее» (superadmin, «Инженер»); none when nothing was cut. */
|
||
export async function keepQuestionDetails(db: Db, questionId: number, original: string, shown: string): Promise<void> {
|
||
if (original.trim() === shown.trim()) await deleteSetting(db, detailsKey(questionId));
|
||
else await setSetting(db, detailsKey(questionId), { text: original.slice(0, 8000) });
|
||
}
|
||
|
||
/** The unfiltered text of a message, if the filter removed something. Show only to a superadmin or in «Инженер». */
|
||
export async function questionDetails(db: Db, questionId: number): Promise<string | null> {
|
||
return (await getSetting<{ text: string }>(db, detailsKey(questionId)))?.text ?? null;
|
||
}
|
||
|
||
export async function pruneQuestionDetails(db: Db, before: Date): Promise<void> {
|
||
await db.delete(settings).where(and(like(settings.key, `${DETAILS_PREFIX}%`), lt(settings.updatedAt, before)));
|
||
}
|