PEP-154: фильтр служебного текста, ответ — только ввод человека, ошибки платформы — суперадмину
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
parent
a935a42528
commit
c80a31f5cb
@ -3,7 +3,7 @@
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": { ".": "./src/bot.ts", "./telegram": "./src/telegram.ts" },
|
||||
"exports": { ".": "./src/bot.ts", "./telegram": "./src/telegram.ts", "./render": "./src/render.ts" },
|
||||
"bin": { "peppa-bot": "./bin/peppa-bot" },
|
||||
"scripts": { "start": "node src/index.ts", "typecheck": "tsc -p ." },
|
||||
"dependencies": {
|
||||
|
||||
@ -39,6 +39,7 @@ import {
|
||||
markOutboxRetry,
|
||||
markOutboxSent,
|
||||
pendingQuestions,
|
||||
getUiMode,
|
||||
questionByTelegramMessage,
|
||||
setOffset,
|
||||
setSetting,
|
||||
@ -312,11 +313,12 @@ export function createBot(o: BotOptions) {
|
||||
if (!audience.length) continue;
|
||||
const ctx = await context(q);
|
||||
const event = questionEvent(q, { taskStatus: ctx.taskStatus, sessionStatus: ctx.session?.status });
|
||||
const r = renderQuestion(q, ctx);
|
||||
// A push is a "now" signal: questions older than this don't pop up on a fresh subscription.
|
||||
const fresh = Date.now() - q.createdAt.getTime() < PUSH_MAX_AGE_MS;
|
||||
const url = ctx.taskKey ? `/t/${ctx.taskKey}` : `/p/${await projectKey(q.projectId)}`;
|
||||
for (const u of audience) {
|
||||
// PEP-154: the terminal command is for the «Инженер» view only.
|
||||
const r = renderQuestion(q, { ...ctx, engineer: (await getUiMode(db, u.id)) === "engineer" });
|
||||
await deliverToUser(db, u, {
|
||||
event,
|
||||
projectId: q.projectId,
|
||||
@ -331,6 +333,7 @@ export function createBot(o: BotOptions) {
|
||||
// fresh text and its buttons back, at most once in `repeatEditMs`.
|
||||
const repeats = states.get(q.id)?.repeats ?? 0;
|
||||
if (!repeats) continue;
|
||||
const r = renderQuestion(q, ctx);
|
||||
for (const sent of await sentQuestionMessages(db, q.id)) {
|
||||
const key = repeatEditKey(sent.id, repeats);
|
||||
if (await getOutbox(db, key)) continue;
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
// Telegram message texts and buttons for PM questions. HTML parse mode.
|
||||
import type { Question, SessionView } from "@peppa/core";
|
||||
import { stripServiceBlocks, userText, type Question, type SessionView } from "@peppa/core";
|
||||
import type { InlineButton } from "./telegram.ts";
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
|
||||
@ -22,12 +22,13 @@ export interface Rendered {
|
||||
// callback_data (≤64 bytes): "q:<questionId>:<choice>", "s:<sessionId>:<action>" or "i:<incidentId>:<decision>" (core/incidents.ts)
|
||||
export function renderQuestion(
|
||||
q: Question,
|
||||
ctx: { taskKey: string | null; taskTitle: string | null; taskStatus?: string | null; session: SessionView | null; webUrl: string },
|
||||
ctx: { taskKey: string | null; taskTitle: string | null; taskStatus?: string | null; session: SessionView | null; webUrl: string; /** PEP-154: the reader's view is «Инженер» — the terminal command is shown. */ engineer?: boolean },
|
||||
): Rendered {
|
||||
const head = ["<b>" + esc(ctx.taskKey ?? (q.sessionId ? tr("Агент №{id}", { id: q.sessionId }) : tr("Обновления продукта"))) + "</b>", ctx.taskTitle ? `<i>${esc(clip(ctx.taskTitle, 80))}</i>` : null]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
const body = esc(clip(q.text, 3300));
|
||||
// PEP-154: no service text in the message (a permission request keeps its command).
|
||||
const body = esc(clip(q.kind === "permission" ? q.text : userText(q.text) || q.text, 3300));
|
||||
const lines = [head, KIND[q.kind], "", body];
|
||||
|
||||
const buttons: InlineButton[][] = [];
|
||||
@ -59,7 +60,7 @@ export function renderQuestion(
|
||||
lines.push("", italic(tr("Или ответьте на это сообщение — текст уйдёт агенту.")));
|
||||
}
|
||||
}
|
||||
if (ctx.session) lines.push(`<code>tmux attach -t ${esc(ctx.session.tmuxName)}</code>`);
|
||||
if (ctx.session && ctx.engineer) lines.push(`<code>tmux attach -t ${esc(ctx.session.tmuxName)}</code>`);
|
||||
return { text: lines.join("\n"), buttons };
|
||||
}
|
||||
|
||||
@ -67,7 +68,8 @@ export function renderQuestion(
|
||||
export function renderAnswered(original: string, q: Question): string {
|
||||
const mark = q.answeredVia === "system" ? "⌛" : "✅";
|
||||
const via = { telegram: tr("в Telegram"), web: tr("в вебе"), terminal: tr("в терминале"), system: "" }[q.answeredVia ?? "telegram"];
|
||||
const said = q.answeredVia === "system" ? esc(q.answer ?? "") : tr("Ответ {via}: <b>{answer}</b>", { via, answer: esc(clip(q.answer ?? "", 500)) });
|
||||
const answer = stripServiceBlocks(q.answer ?? "");
|
||||
const said = q.answeredVia === "system" ? esc(answer) : tr("Ответ {via}: <b>{answer}</b>", { via, answer: esc(clip(answer, 500)) });
|
||||
return `${original}\n\n${mark} ${said}`;
|
||||
}
|
||||
|
||||
|
||||
@ -309,7 +309,7 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
|
||||
<TaskAgentModel taskKey={ref.key} own={agentOwn} inherited={agentProject} escalation={escalation} back={back} />
|
||||
{live ? (
|
||||
// PEP-9 terminal + PEP-33 step feed of the newest unfinished runner.
|
||||
<SessionCard s={live} back={back} terminal steps={steps} />
|
||||
<SessionCard s={live} back={back} terminal steps={steps} plainSteps={!engineer} />
|
||||
) : (
|
||||
<form action={startTaskSession} className="flex flex-wrap gap-2">
|
||||
<Hidden fields={{ taskKey: ref.key, back }} />
|
||||
|
||||
@ -19,6 +19,19 @@ const KIND: Record<StepKind, { icon: LucideIcon; label: string }> = {
|
||||
other: { icon: Wrench, label: m("инструмент") },
|
||||
};
|
||||
|
||||
// PEP-154: a step for the «Продакт» view — what the agent does, in words: no command, file name or path.
|
||||
const STEP_PLAIN: Record<StepKind, string> = {
|
||||
command: m("Выполняет действие в проекте"),
|
||||
test: m("Запускает проверки"),
|
||||
edit: m("Вносит изменения"),
|
||||
read: m("Изучает проект"),
|
||||
search: m("Ищет нужное в проекте"),
|
||||
web: m("Смотрит в интернете"),
|
||||
agent: m("Поручил часть работы помощнику"),
|
||||
mcp: m("Сверяется с задачей"),
|
||||
other: m("Работает над задачей"),
|
||||
};
|
||||
|
||||
const KEEP = 30;
|
||||
|
||||
function since(iso: string, now: number, t: Translator): string {
|
||||
@ -32,7 +45,7 @@ function since(iso: string, now: number, t: Translator): string {
|
||||
* What the agent is doing now (PEP-33): its latest tool calls, newest first. Initial steps
|
||||
* come from the server, new ones from the live channel (PEP-37, `steps:<sessionId>`).
|
||||
*/
|
||||
export function AgentSteps({ sessionId, initial, live, hooks = true }: { sessionId: number; initial: StepView[]; live: boolean; hooks?: boolean }) {
|
||||
export function AgentSteps({ sessionId, initial, live, hooks = true, plain = false }: { sessionId: number; initial: StepView[]; live: boolean; hooks?: boolean; /** PEP-154: «Продакт» — what the agent does in words, no commands, file names or paths. */ plain?: boolean }) {
|
||||
const [steps, setSteps] = useState(initial);
|
||||
const [now, setNow] = useState(() => Date.now());
|
||||
const t = useT();
|
||||
@ -59,7 +72,7 @@ export function AgentSteps({ sessionId, initial, live, hooks = true }: { session
|
||||
if (!steps.length)
|
||||
return (
|
||||
<p className="m-0 rounded-md border border-dashed px-3 py-2 text-xs text-muted-foreground">
|
||||
{hooks ? (live ? t("Агент ещё ничего не сделал — шаги появятся здесь.") : t("Шагов не записано.")) : t("Этот агент не сообщает шаги (нет хуков) — смотри терминал.")}
|
||||
{hooks ? (live ? t("Агент ещё ничего не сделал — шаги появятся здесь.") : t("Шагов не записано.")) : plain ? t("Этот агент не сообщает о шагах.") : t("Этот агент не сообщает шаги (нет хуков) — смотри терминал.")}
|
||||
</p>
|
||||
);
|
||||
return (
|
||||
@ -70,9 +83,13 @@ export function AgentSteps({ sessionId, initial, live, hooks = true }: { session
|
||||
return (
|
||||
<li key={s.id} className={cn("flex items-center gap-2 rounded px-1.5 py-1 text-xs", i === 0 && live && "bg-info/10")}>
|
||||
<Icon className={cn("size-3.5 shrink-0", s.ok ? "text-muted-foreground" : "text-destructive")} aria-label={t(k.label)} />
|
||||
<span className={cn("min-w-0 flex-1 truncate font-mono", !s.ok && "text-destructive")} title={`${s.tool}: ${s.text}`}>
|
||||
{s.text}
|
||||
</span>
|
||||
{plain ? (
|
||||
<span className={cn("min-w-0 flex-1 truncate", !s.ok && "text-destructive")}>{t(STEP_PLAIN[s.kind] ?? STEP_PLAIN.other)}</span>
|
||||
) : (
|
||||
<span className={cn("min-w-0 flex-1 truncate font-mono", !s.ok && "text-destructive")} title={`${s.tool}: ${s.text}`}>
|
||||
{s.text}
|
||||
</span>
|
||||
)}
|
||||
{!s.ok && <span className="shrink-0 text-[10px] text-destructive">{t("ошибка")}</span>}
|
||||
<span className="shrink-0 font-mono text-[10px] text-muted-foreground tabular-nums">{since(s.at, now, t)}</span>
|
||||
</li>
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
// Domain cards shared by pages: agent questions, runners, project list.
|
||||
import Link from "next/link";
|
||||
import { BellRing, CircleCheck, CircleHelp, FileCheck, Hourglass, Play, RotateCcw, Send, ShieldQuestion, Square, SquareTerminal } from "lucide-react";
|
||||
import { questionState, type Project, type Question, type SessionView, type StepView } from "@peppa/core";
|
||||
import { questionDetails, questionState, type Project, type Question, type SessionView, type StepView } from "@peppa/core";
|
||||
import { db } from "@/lib/db";
|
||||
import { SubscriptionName } from "@/components/SubscriptionName";
|
||||
import { answerQuestion, messageSession, resumeTaskSession, stopTaskSession } from "@/app/(app)/actions";
|
||||
@ -15,6 +15,7 @@ import { RunnerTerminal } from "@/components/RunnerTerminal";
|
||||
import { SessionUsageLine } from "@/components/Accounting";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { subscriptionNamesVisible, uiMode } from "@/lib/auth";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
const KIND = {
|
||||
@ -42,6 +43,8 @@ export async function QuestionCard({ q, taskKey, taskStatus, back, compact = fal
|
||||
// PEP-151: the same state came again — one message with the time it was last refreshed.
|
||||
const state = await questionState(db, q.id).catch(() => null);
|
||||
const updatedAt = state?.updatedAt ? new Date(state.updatedAt) : null;
|
||||
// PEP-154: what the filter removed (command output, paths) — for «Инженер» and a superadmin only.
|
||||
const original = (await uiMode()) === "engineer" || (await subscriptionNamesVisible()) ? await questionDetails(db, q.id).catch(() => null) : null;
|
||||
return (
|
||||
<article id={`q-${q.id}`} className={cn("flex flex-col gap-2.5 rounded-lg border border-l-2 bg-card p-4", answered ? "border-l-border opacity-70" : k.border)}>
|
||||
<header className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm">
|
||||
@ -70,6 +73,12 @@ export async function QuestionCard({ q, taskKey, taskStatus, back, compact = fal
|
||||
<p className="m-0 mt-1">{t("Повторов: {n} · первое сообщение {ago}", { n: state.repeats, ago: ago(q.createdAt, t) })}</p>
|
||||
</details>
|
||||
)}
|
||||
{original && (
|
||||
<details className="text-xs text-muted-foreground" data-question-original={q.id}>
|
||||
<summary className="cursor-pointer">{t("Подробнее: исходный текст")}</summary>
|
||||
<pre className="m-0 mt-1 max-h-72 overflow-auto font-mono whitespace-pre-wrap">{original}</pre>
|
||||
</details>
|
||||
)}
|
||||
{answered ? (
|
||||
<p className="m-0 flex items-center gap-1.5 text-sm text-muted-foreground">
|
||||
{q.answeredVia === "system" ? <Hourglass className="size-3.5" /> : <CircleCheck className="size-3.5 text-ok" />}
|
||||
@ -152,7 +161,7 @@ export function AttachCommand({ name }: { name: string }) {
|
||||
}
|
||||
|
||||
/** `steps` (PEP-33): the live step feed of the agent, shown with the terminal. */
|
||||
export async function SessionCard({ s, back, showTitle = false, terminal = false, steps }: { s: SessionView; back: string; showTitle?: boolean; terminal?: boolean; steps?: StepView[] }) {
|
||||
export async function SessionCard({ s, back, showTitle = false, terminal = false, steps, plainSteps = false }: { s: SessionView; back: string; showTitle?: boolean; terminal?: boolean; steps?: StepView[]; /** PEP-154: «Продакт» — steps in words. */ plainSteps?: boolean }) {
|
||||
const t = await getT();
|
||||
return (
|
||||
<article className="flex flex-col gap-2.5 rounded-lg border bg-card p-3.5">
|
||||
@ -179,7 +188,7 @@ export async function SessionCard({ s, back, showTitle = false, terminal = false
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
{steps && <AgentSteps key={`steps-${s.id}`} sessionId={s.id} initial={steps} live={terminal} hooks={s.provider === "claude"} />}
|
||||
{steps && <AgentSteps key={`steps-${s.id}`} sessionId={s.id} initial={steps} live={terminal} hooks={s.provider === "claude"} plain={plainSteps} />}
|
||||
{terminal && <RunnerTerminal key={s.id} sessionId={s.id} live />}
|
||||
</article>
|
||||
);
|
||||
|
||||
@ -13,6 +13,7 @@ import { notify } from "./notify.ts";
|
||||
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
|
||||
import { projectForUser, userProjectIds, type User } from "./users.ts";
|
||||
import type { OutboxRow } from "./telegram.ts";
|
||||
import { pruneQuestionDetails, userText } from "./user-text.ts";
|
||||
import { chatRepeatKey, chatRepeats, normalizeMessage, pruneMessageStates, questionStates, type ChatRepeat } from "./message-state.ts";
|
||||
|
||||
export type Chat = typeof chats.$inferSelect;
|
||||
@ -101,6 +102,13 @@ export async function listChats(db: Db, user: Pick<User, "id">): Promise<ChatLis
|
||||
|
||||
/** Adds a message; with a `dedupeKey` seen before it is a no-op and returns null. */
|
||||
export async function addChatMessage(db: Db, m: NewChatMessage): Promise<ChatMessage | null> {
|
||||
// PEP-154: what an agent or Peppa says goes through the service-text filter; nothing left — no message.
|
||||
// A question's text was filtered when it was asked (a permission request keeps its command).
|
||||
if (m.authorKind !== "user" && !m.questionId) {
|
||||
const text = userText(m.text);
|
||||
if (!text) return null;
|
||||
m = { ...m, text };
|
||||
}
|
||||
if (m.threadKey && m.threadTitle == null) {
|
||||
const [prev] = await db
|
||||
.select({ t: chatMessages.threadTitle })
|
||||
@ -462,6 +470,8 @@ export async function syncChats(db: Db, o: { now?: Date } = {}): Promise<number>
|
||||
let repeated = 0;
|
||||
const add = async (m: NewChatMessage) => {
|
||||
// PEP-151: the same event of a story again in a row is a counter on the line already there.
|
||||
if (m.authorKind !== "user" && !m.questionId) m.text = userText(m.text); // PEP-154: compared and stored without service text
|
||||
if (!m.text) return;
|
||||
if (await repeatsLastEvent(db, m)) return void repeated++;
|
||||
if (m.threadKey) m.threadTitle = await titleOf(m.threadKey);
|
||||
if (await addChatMessage(db, m)) added++;
|
||||
@ -570,6 +580,7 @@ export async function pruneChats(db: Db, o: { now?: Date } = {}): Promise<number
|
||||
await db.update(telegramOutbox).set({ chatMessageId: null }).where(inArray(telegramOutbox.chatMessageId, old));
|
||||
const rows = await db.delete(chatMessages).where(stale).returning({ id: chatMessages.id });
|
||||
await pruneMessageStates(db, before);
|
||||
await pruneQuestionDetails(db, before);
|
||||
return rows.length;
|
||||
}
|
||||
|
||||
|
||||
@ -47,6 +47,8 @@ export * from "./autonomy.ts";
|
||||
export * from "./accept-pending.ts";
|
||||
export * from "./review-card.ts";
|
||||
export * from "./message-state.ts";
|
||||
export * from "./user-text.ts";
|
||||
export * from "./platform-failure.ts";
|
||||
export * from "./openspec.ts";
|
||||
export * from "./steps.ts";
|
||||
export * from "./preview.ts";
|
||||
|
||||
39
packages/core/src/platform-failure.ts
Normal file
39
packages/core/src/platform-failure.ts
Normal file
@ -0,0 +1,39 @@
|
||||
// PEP-154: an exception inside Peppa is not the project owner's business. A clear refusal
|
||||
// (PeppaError: «подписка не выбрана») is still told to the owner; anything else goes to the
|
||||
// error tracker and, once per error a day, to the superadmins.
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import type { Db } from "@peppa/db";
|
||||
import { createHash } from "node:crypto";
|
||||
import { PeppaError } from "./errors.ts";
|
||||
import { reportPlatformError } from "./error-report.ts";
|
||||
import { normalizeMessage } from "./message-state.ts";
|
||||
import { alertAdmins } from "./monitor.ts";
|
||||
|
||||
export interface FailureContext {
|
||||
/** Which process: "watchdog", "hook", "bot", "web". */
|
||||
service: string;
|
||||
/** Which part failed: "dispatch PAY-7", "restart #12". */
|
||||
where: string;
|
||||
log?: (m: string) => void;
|
||||
now?: Date;
|
||||
}
|
||||
|
||||
/**
|
||||
* What to tell the project owner about a failure: the text of a clear refusal, or null — it is
|
||||
* a platform error (reported to the error tracker and to the superadmins, one message per error
|
||||
* a day) and the owner gets nothing. Never throws.
|
||||
*/
|
||||
export async function platformFailure(db: Db, e: unknown, ctx: FailureContext): Promise<string | null> {
|
||||
if (e instanceof PeppaError) return e.message;
|
||||
const message = (e as Error)?.message ?? String(e);
|
||||
try {
|
||||
await reportPlatformError(db, e, { service: ctx.service, where: ctx.where });
|
||||
// The same error of the same part (numbers aside) is one message a day.
|
||||
const fp = createHash("sha1").update(`${ctx.service}|${normalizeMessage(ctx.where)}|${normalizeMessage(message)}`).digest("hex").slice(0, 12);
|
||||
const day = (ctx.now ?? new Date()).toISOString().slice(0, 10);
|
||||
// glossary-ignore: read by superadmins only
|
||||
const text = tr("⚠️ Сбой в Peppa FACTORY ({where}): {error}", { where: ctx.where, error: message.length > 300 ? `${message.slice(0, 300)}…` : message });
|
||||
await alertAdmins(db, `fail:${fp}:${day}`, text, ctx.log ?? (() => {}));
|
||||
} catch {}
|
||||
return null;
|
||||
}
|
||||
@ -7,6 +7,7 @@ import { actorColumns } from "./actor.ts";
|
||||
import type { Question, QuestionKind } from "./tasks.ts";
|
||||
import { userProjectIds } from "./users.ts";
|
||||
import { questionStates, raiseOnce, type MessageTopic } from "./message-state.ts";
|
||||
import { keepQuestionDetails, messageText } from "./user-text.ts";
|
||||
|
||||
export type Session = typeof sessions.$inferSelect;
|
||||
export type SessionStatus = (typeof sessionStatus.enumValues)[number];
|
||||
@ -182,6 +183,9 @@ export async function raiseSessionQuestion(
|
||||
awaitingHook = false,
|
||||
o: { topic?: MessageTopic; head?: string | null } = {},
|
||||
): Promise<Question> {
|
||||
// PEP-154: no service text (tags, command output, paths) in what the person reads.
|
||||
const original = text;
|
||||
text = messageText(kind, text);
|
||||
const row = await raiseOnce(db, { projectId: s.projectId, taskId: s.taskId, sessionId: s.id, kind, text, options, awaitingHook, ...o }, async () => {
|
||||
const [created] = await db
|
||||
.insert(questions)
|
||||
@ -189,6 +193,7 @@ export async function raiseSessionQuestion(
|
||||
.returning();
|
||||
return created!;
|
||||
});
|
||||
await keepQuestionDetails(db, row.id, original, text).catch(() => {});
|
||||
await notify(db, { type: "question", questionId: row.id });
|
||||
return row;
|
||||
}
|
||||
|
||||
@ -15,6 +15,7 @@ import { blockersOf, dependentsOf, type Blocker } from "./deps.ts";
|
||||
import { taskBudgetView, type TaskBudgetView } from "./budgets.ts";
|
||||
import { productNeeds, type ProductNeedView } from "./product-needs.ts";
|
||||
import { raiseOnce, type MessageTopic } from "./message-state.ts";
|
||||
import { keepQuestionDetails, messageText, stripServiceBlocks } from "./user-text.ts";
|
||||
|
||||
export type Task = typeof tasks.$inferSelect;
|
||||
export type TaskStatus = (typeof taskStatus.enumValues)[number];
|
||||
@ -310,6 +311,9 @@ export interface NewQuestion {
|
||||
|
||||
/** Records a question for the PM and broadcasts it (the bot forwards it to Telegram). */
|
||||
export async function askPm(db: Db, ref: TaskRef, { topic, head, ...q }: NewQuestion): Promise<Question> {
|
||||
// PEP-154: no service text (tags, command output, paths) in what the person reads.
|
||||
const original = q.text;
|
||||
q = { ...q, text: messageText(q.kind, q.text) };
|
||||
// PEP-151: the same state of the story again refreshes the earlier message instead of adding one.
|
||||
const row = await raiseOnce(db, { projectId: ref.project.id, taskId: ref.task.id, sessionId: q.sessionId ?? null, kind: q.kind, text: q.text, options: q.options, topic, head }, async () => {
|
||||
const [created] = await db
|
||||
@ -318,6 +322,7 @@ export async function askPm(db: Db, ref: TaskRef, { topic, head, ...q }: NewQues
|
||||
.returning();
|
||||
return created!;
|
||||
});
|
||||
await keepQuestionDetails(db, row.id, original, q.text).catch(() => {});
|
||||
if (q.kind === "approval") await updateTask(db, ref, { status: "awaiting_approval" }, q.sessionId);
|
||||
await notify(db, { type: "question", questionId: row.id });
|
||||
return row;
|
||||
@ -325,7 +330,9 @@ export async function askPm(db: Db, ref: TaskRef, { topic, head, ...q }: NewQues
|
||||
|
||||
/** A message for the PM about the project as a whole (releases), not about a task. */
|
||||
export async function askPmProject(db: Db, project: Project, q: { kind: QuestionKind; text: string; options?: string[] }): Promise<Question> {
|
||||
const [row] = await db.insert(questions).values({ projectId: project.id, ...q }).returning();
|
||||
const text = messageText(q.kind, q.text);
|
||||
const [row] = await db.insert(questions).values({ projectId: project.id, ...q, text }).returning();
|
||||
await keepQuestionDetails(db, row!.id, q.text, text).catch(() => {});
|
||||
await notify(db, { type: "question", questionId: row!.id });
|
||||
return row!;
|
||||
}
|
||||
@ -344,6 +351,12 @@ export async function answerQuestion(
|
||||
answer: string,
|
||||
via: NonNullable<Question["answeredVia"]>,
|
||||
): Promise<Question> {
|
||||
// PEP-154: an answer is a person's words — service blocks never land in it.
|
||||
if (via !== "system") {
|
||||
const said = stripServiceBlocks(answer);
|
||||
if (!said && answer.trim()) throw new PeppaError(`Question #${questionId}: the answer is service text only`);
|
||||
answer = said;
|
||||
}
|
||||
const [row] = await db
|
||||
.update(questions)
|
||||
.set({ answer, answeredVia: via, answeredAt: new Date() })
|
||||
|
||||
142
packages/core/src/user-text.ts
Normal file
142
packages/core/src/user-text.ts
Normal file
@ -0,0 +1,142 @@
|
||||
// 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;
|
||||
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)));
|
||||
}
|
||||
@ -24,6 +24,7 @@ import {
|
||||
projectPoolExhausted,
|
||||
questionRecipients,
|
||||
raiseSessionQuestion,
|
||||
platformFailure,
|
||||
setSetting,
|
||||
taskPrNumber,
|
||||
type AutonomySettings,
|
||||
@ -213,7 +214,9 @@ async function autoCloseReviews(db: Db, project: Project, a: AutonomySettings, n
|
||||
const key = `auto:closefail:${q.id}`;
|
||||
if (!(await getSetting(db, key))) {
|
||||
await setSetting(db, key, true);
|
||||
await askPm(db, ref, { kind: "question", text: m("⚠️ {key}: не получилось закрыть автоматически — {error}", { key: ref.key, error: (e as Error).message }) });
|
||||
// PEP-154: a platform error goes to the superadmins and the error tracker, not to the owner.
|
||||
const why = await platformFailure(db, e, { service: "watchdog", where: `auto-close ${ref.key}`, log });
|
||||
if (why) await askPm(db, ref, { kind: "question", text: m("⚠️ {key}: не получилось закрыть автоматически — {error}", { key: ref.key, error: why }) });
|
||||
}
|
||||
log(`${ref.key}: auto-close failed — ${(e as Error).message}`);
|
||||
}
|
||||
@ -268,10 +271,13 @@ async function dispatch(db: Db, project: Project, a: AutonomySettings, now: Date
|
||||
const fresh = await resolveTaskById(db, task.id).catch(() => null);
|
||||
if (fresh && fresh.task.status === "in_progress") await moveTask(db, fresh, "backlog").catch(() => {});
|
||||
await setIdle(db, project.id, { ...state, failUntil: now.getTime() + DISPATCH_RETRY_MS });
|
||||
await askPmProject(db, project, {
|
||||
kind: "attention",
|
||||
text: `${m("⚠️ {project}: диспетчер не смог запустить агента на {key} — {error}", { project: project.name, key: ref.key, error: (e as Error).message })}\n${m("Повторю через {n} мин.", { n: DISPATCH_RETRY_MS / 60_000 })}`,
|
||||
});
|
||||
// PEP-154: a platform error goes to the superadmins and the error tracker, not to the owner.
|
||||
const why = await platformFailure(db, e, { service: "watchdog", where: `dispatch ${ref.key}`, log, now });
|
||||
if (why)
|
||||
await askPmProject(db, project, {
|
||||
kind: "attention",
|
||||
text: `${m("⚠️ {project}: диспетчер не смог запустить агента на {key} — {error}", { project: project.name, key: ref.key, error: why })}\n${m("Повторю через {n} мин.", { n: DISPATCH_RETRY_MS / 60_000 })}`,
|
||||
});
|
||||
log(`${ref.key}: dispatch failed — ${(e as Error).message}`);
|
||||
return;
|
||||
}
|
||||
@ -374,7 +380,9 @@ export async function onIdleAnswer(db: Db, q: Question, answer: string): Promise
|
||||
try {
|
||||
await moveTask(db, ref, "in_progress");
|
||||
} catch (e) {
|
||||
await askPmProject(db, ref.project, { kind: "attention", text: m("⚠️ {key} не запущена: {error}", { key: ref.key, error: (e as Error).message }) });
|
||||
// PEP-154: the person pressed a button and gets an answer, but never the text of an exception.
|
||||
const why = await platformFailure(db, e, { service: "runner", where: `start ${ref.key}` });
|
||||
await askPmProject(db, ref.project, { kind: "attention", text: why ? m("⚠️ {key} не запущена: {error}", { key: ref.key, error: why }) : m("⚠️ {key} не запущена. Мы уже разбираемся — попробуйте ещё раз позже.", { key: ref.key }) });
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
// here; Peppa keeps the releases, tells the PM, and starts prod by the PM's button — a
|
||||
// `deploy-prod-*` tag at the healthy staging commit (Gitea 1.22 has no workflow_dispatch API).
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
import { answerQuestion, askPmProject, deleteSetting, getPublishMode, getSetting, setSetting, resolveTask, giteaForBot, logEvent, markSecretsRestart, needsLine, openNeeds, PeppaError, projectSecretMasker, queueProductReview, runLink, type GiteaClient, type Project, type Question } from "@peppa/core";
|
||||
import { answerQuestion, askPmProject, platformFailure, deleteSetting, getPublishMode, getSetting, setSetting, resolveTask, giteaForBot, logEvent, markSecretsRestart, needsLine, openNeeds, PeppaError, projectSecretMasker, queueProductReview, runLink, type GiteaClient, type Project, type Question } from "@peppa/core";
|
||||
import { projects, questions, releases, settings, type Db } from "@peppa/db";
|
||||
import { and, desc, eq, inArray, isNull, sql } from "drizzle-orm";
|
||||
import { deployPlatform, isPlatform } from "./platform-release.ts";
|
||||
@ -288,7 +288,9 @@ export async function onReleaseAnswer(db: Db, q: Question, answer: string, by: s
|
||||
try {
|
||||
await deployProd(db, project, by);
|
||||
} catch (e) {
|
||||
await askPmProject(db, project, { kind: "attention", text: m("Обновление рабочей версии не запущено: {error}", { error: (e as Error).message }) });
|
||||
// PEP-154: the person pressed a button and gets an answer, but never the text of an exception.
|
||||
const why = await platformFailure(db, e, { service: "runner", where: `deploy prod ${project.key}` });
|
||||
await askPmProject(db, project, { kind: "attention", text: why ? m("Обновление рабочей версии не запущено: {error}", { error: why }) : m("Обновление рабочей версии не запущено. Мы уже разбираемся — попробуйте ещё раз позже.") });
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -34,6 +34,9 @@ import {
|
||||
logSessionEvent,
|
||||
peppaInputSentAt,
|
||||
pendingSessionQuestions,
|
||||
isServiceInput,
|
||||
userText,
|
||||
reportPlatformError,
|
||||
raiseSessionQuestion,
|
||||
releaseHookQuestion,
|
||||
updateSession,
|
||||
@ -197,6 +200,8 @@ const NUDGE = (key: string) =>
|
||||
*/
|
||||
async function turnEnd(db: Db, s: SessionView, text: string | null, canContinue: boolean): Promise<unknown> {
|
||||
await logSessionEvent(db, s, "turn_end", { text });
|
||||
// PEP-154: a reply that is service text only (a tag block, command output) says nothing to a person.
|
||||
if (text && !userText(text)) text = null;
|
||||
// PEP-43: the story's budget is spent — the PM was asked; don't push the agent further.
|
||||
if (s.taskId && (await getBudgetState(db, s.taskId))) {
|
||||
await logSessionEvent(db, s, "budget_hold", {});
|
||||
@ -326,9 +331,17 @@ async function handle(event: string, input: HookInput): Promise<void> {
|
||||
// pending for this session is now answered — except hook-held questions, and,
|
||||
// when Peppa typed this text itself, questions raised after it did (e.g. a CI
|
||||
// failure pasted while the PM is being asked about the next one).
|
||||
// PEP-154: a service notification of the CLI (<task-notification>…) is nobody's answer —
|
||||
// the questions stay open and the nudge counter keeps counting.
|
||||
if (isServiceInput(input.prompt ?? "")) {
|
||||
await updateSession(db, s.id, { status: "running", lastActivityAt: now });
|
||||
break;
|
||||
}
|
||||
const sentAt = input.prompt ? await peppaInputSentAt(db, s.id, input.prompt) : null;
|
||||
for (const q of await pendingSessionQuestions(db, s.id, { excludeHook: true, createdBefore: sentAt ?? undefined })) {
|
||||
await answerQuestion(db, q.id, input.prompt ?? "", "terminal").catch(() => {});
|
||||
// What Peppa typed itself (a red check, «лимит сброшен») makes earlier messages stale; it is not an answer.
|
||||
if (sentAt) await answerQuestion(db, q.id, m("(неактуально: агент продолжил работу)"), "system").catch(() => {});
|
||||
else await answerQuestion(db, q.id, input.prompt ?? "", "terminal").catch(() => {});
|
||||
}
|
||||
await updateSession(db, s.id, { status: "running", autoNudges: 0, lastActivityAt: now });
|
||||
break;
|
||||
@ -425,5 +438,8 @@ try {
|
||||
else await handle(event, raw ? (JSON.parse(raw) as HookInput) : {});
|
||||
} catch (e) {
|
||||
log(`${event} session=${process.env.PEPPA_SESSION_ID}: ${(e as Error).stack ?? e}`);
|
||||
// PEP-154: the hook's own failure goes to the error tracker, never to the project owner.
|
||||
// A clear refusal (PeppaError) is not a failure of the platform.
|
||||
if ((e as Error)?.name !== "PeppaError") await reportPlatformError(createDb(), e, { service: "hook", where: event }).catch(() => {});
|
||||
}
|
||||
process.exit(0);
|
||||
|
||||
@ -16,6 +16,7 @@ import {
|
||||
PeppaError,
|
||||
projectAudience,
|
||||
raiseSessionQuestion,
|
||||
platformFailure,
|
||||
touchQuestion,
|
||||
sendProjectMessage,
|
||||
setSetting,
|
||||
@ -184,7 +185,9 @@ export async function restartTick(db: Db, o: { now: Date; cfg: WatchdogSettings;
|
||||
o.log(`#${s.id} ${s.taskKey ?? ""}: restarted automatically (${restarts.length}/${o.cfg.restartMax})`);
|
||||
} catch (e) {
|
||||
await logSessionEvent(db, s, "restart_failed", { error: (e as Error).message });
|
||||
await raiseSessionQuestion(db, s, "attention", m("{who}: не удалось перезапустить автоматически — {error}", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), error: (e as Error).message }));
|
||||
// PEP-154: a platform error goes to the superadmins and the error tracker, not to the owner.
|
||||
const why = await platformFailure(db, e, { service: "watchdog", where: `restart ${s.taskKey ?? `#${s.id}`}`, log: o.log, now: o.now });
|
||||
if (why) await raiseSessionQuestion(db, s, "attention", m("{who}: не удалось перезапустить автоматически — {error}", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), error: why }));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -329,6 +329,10 @@ export const runner: Dict = {
|
||||
"Не удалось подготовить рабочую копию для агента: {error}": "Could not prepare a working copy for the agent: {error}",
|
||||
"(неактуально: агент перезапущен)": "(no longer relevant: the agent was restarted)",
|
||||
"(неактуально: агент остановлен)": "(no longer relevant: the agent was stopped)",
|
||||
"(неактуально: агент продолжил работу)": "(no longer relevant: the agent went on working)",
|
||||
"Обновление рабочей версии не запущено. Мы уже разбираемся — попробуйте ещё раз позже.": "The update of the live version did not start. We are already looking into it — please try again later.",
|
||||
"⚠️ {key} не запущена. Мы уже разбираемся — попробуйте ещё раз позже.": "⚠️ {key} was not started. We are already looking into it — please try again later.",
|
||||
"⚠️ Сбой в Peppa FACTORY ({where}): {error}": "⚠️ Failure in Peppa FACTORY ({where}): {error}",
|
||||
|
||||
// Sharing and visibility
|
||||
"Участниками управляет только владелец проекта": "Only the project owner manages members",
|
||||
|
||||
@ -236,6 +236,17 @@ export const story: Dict = {
|
||||
инструмент: "tool",
|
||||
"Агент ещё ничего не сделал — шаги появятся здесь.": "The agent hasn't done anything yet — steps will appear here.",
|
||||
"Шагов не записано.": "No steps recorded.",
|
||||
"Этот агент не сообщает о шагах.": "This agent does not report its steps.",
|
||||
"Выполняет действие в проекте": "Doing something in the project",
|
||||
"Запускает проверки": "Running the checks",
|
||||
"Вносит изменения": "Making changes",
|
||||
"Изучает проект": "Studying the project",
|
||||
"Ищет нужное в проекте": "Searching the project",
|
||||
"Смотрит в интернете": "Looking it up on the web",
|
||||
"Поручил часть работы помощнику": "Handed part of the work to a helper",
|
||||
"Сверяется с задачей": "Checking against the task",
|
||||
"Работает над задачей": "Working on the task",
|
||||
"Подробнее: исходный текст": "Details: the original text",
|
||||
"Этот агент не сообщает шаги (нет хуков) — смотри терминал.": "This agent doesn't report steps (no hooks) — watch the terminal.",
|
||||
"Шаги агента": "Agent steps",
|
||||
ошибка: "error",
|
||||
|
||||
@ -252,6 +252,10 @@ export const runner: Dict = {
|
||||
"Не удалось подготовить рабочую копию для агента: {error}": "Агентке жұмыс көшірмесін дайындау мүмкін болмады: {error}",
|
||||
"(неактуально: агент перезапущен)": "(өзекті емес: агент қайта іске қосылды)",
|
||||
"(неактуально: агент остановлен)": "(өзекті емес: агент тоқтатылды)",
|
||||
"(неактуально: агент продолжил работу)": "(өзекті емес: агент жұмысын жалғастырды)",
|
||||
"Обновление рабочей версии не запущено. Мы уже разбираемся — попробуйте ещё раз позже.": "Жұмыс нұсқасын жаңарту іске қосылмады. Біз себебін анықтап жатырмыз — кейінірек қайталап көріңіз.",
|
||||
"⚠️ {key} не запущена. Мы уже разбираемся — попробуйте ещё раз позже.": "⚠️ {key} іске қосылмады. Біз себебін анықтап жатырмыз — кейінірек қайталап көріңіз.",
|
||||
"⚠️ Сбой в Peppa FACTORY ({where}): {error}": "⚠️ Peppa FACTORY жүйесінде ақау ({where}): {error}",
|
||||
"Участниками управляет только владелец проекта": "Қатысушыларды тек жоба иесі басқарады",
|
||||
"Укажите логин участника": "Қатысушының логинін көрсетіңіз",
|
||||
"Нет доступа к коду проекта — войдите заново": "Жоба кодына қолжетімділік жоқ — қайта кіріңіз",
|
||||
|
||||
@ -220,6 +220,17 @@ export const story: Dict = {
|
||||
"инструмент": "құрал",
|
||||
"Агент ещё ничего не сделал — шаги появятся здесь.": "Агент әлі ештеңе жасаған жоқ — қадамдар осында пайда болады.",
|
||||
"Шагов не записано.": "Қадамдар жазылмаған.",
|
||||
"Этот агент не сообщает о шагах.": "Бұл агент қадамдары туралы хабарламайды.",
|
||||
"Выполняет действие в проекте": "Жобада әрекет орындап жатыр",
|
||||
"Запускает проверки": "Тексерулерді іске қосып жатыр",
|
||||
"Вносит изменения": "Өзгерістер енгізіп жатыр",
|
||||
"Изучает проект": "Жобаны зерттеп жатыр",
|
||||
"Ищет нужное в проекте": "Жобадан керегін іздеп жатыр",
|
||||
"Смотрит в интернете": "Интернеттен қарап жатыр",
|
||||
"Поручил часть работы помощнику": "Жұмыстың бір бөлігін көмекшіге тапсырды",
|
||||
"Сверяется с задачей": "Тапсырмамен салыстырып жатыр",
|
||||
"Работает над задачей": "Тапсырмамен жұмыс істеп жатыр",
|
||||
"Подробнее: исходный текст": "Толығырақ: бастапқы мәтін",
|
||||
"Этот агент не сообщает шаги (нет хуков) — смотри терминал.": "Бұл агент қадамдарын хабарламайды (хуктар жоқ) — терминалды қараңыз.",
|
||||
"Шаги агента": "Агент қадамдары",
|
||||
"ошибка": "қате",
|
||||
|
||||
229
packages/testkit/test/service-text.test.ts
Normal file
229
packages/testkit/test/service-text.test.ts
Normal file
@ -0,0 +1,229 @@
|
||||
// PEP-154: service text never reaches the person. Blocks like <task-notification>, command
|
||||
// output, shell prompts, stack traces and absolute paths are cut out of messages and answers;
|
||||
// an exception inside Peppa goes to the superadmins and the error tracker, not to the owner.
|
||||
// Tests are named after the spec scenarios.
|
||||
import assert from "node:assert/strict";
|
||||
import { spawn } from "node:child_process";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { after, before, describe, test } from "node:test";
|
||||
// helpers must load first: it sets the isolated test env that runner modules read on load.
|
||||
import { core, db, project, runner, teardown } from "./helpers.ts";
|
||||
import { MockBugsink } from "../src/mock-bugsink.ts";
|
||||
import { projects, questions, sessions, telegramOutbox, users } from "@peppa/db";
|
||||
import { and, eq, isNull, sql } from "drizzle-orm";
|
||||
|
||||
const { createBugsinkClient } = await import("@peppa/bugsink");
|
||||
const { renderQuestion, renderAnswered } = await import("@peppa/bot/render");
|
||||
|
||||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||||
const ROOT = join(dirname(fileURLToPath(import.meta.url)), "../../..");
|
||||
const bugsink = await new MockBugsink().start();
|
||||
process.env.BUGSINK_URL = bugsink.url;
|
||||
|
||||
const NOTIFICATION = "<task-notification>\n<task-id>b7f3</task-id>\n<output-file>/private/tmp/claude-501/tasks/b7f3.output</output-file>\n<status>completed</status>\n<summary>Background command finished</summary>\n</task-notification>";
|
||||
const TERMINAL_REPLY = [
|
||||
"Проверки не прошли, нужен ваш ответ.",
|
||||
"",
|
||||
"$ pnpm test",
|
||||
"```",
|
||||
"FAIL src/app.test.ts",
|
||||
" ● оплата › считает сумму",
|
||||
"```",
|
||||
"TypeError: total is not a function",
|
||||
" at sum (/Users/telecom/Dev/pay/src/app.ts:12:5)",
|
||||
" at async run (node:internal/process/task_queues:95:5)",
|
||||
"Файл: /Users/telecom/Dev/pay/src/app.ts",
|
||||
"\x1b[31mЧто выбрать: чинить сейчас или отложить?\x1b[0m",
|
||||
].join("\n");
|
||||
|
||||
let owner: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||||
let admin: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||||
let seq = 0;
|
||||
|
||||
/** A story at work with its agent's session (no tmux: messages are raised as the hook does). */
|
||||
async function story() {
|
||||
const key = `F${String.fromCharCode(65 + seq++)}`;
|
||||
const p = await core.createProject(db, { slug: key.toLowerCase(), key, name: `Проект ${key}`, giteaOwner: "test", workspacePath: "/tmp/none", ownerId: owner.id });
|
||||
const created = await core.createTask(db, { projectId: p.id, title: "Оплата картой" });
|
||||
await core.updateTask(db, await core.resolveTask(db, created.key), { status: "in_progress" });
|
||||
const [s] = await db.insert(sessions).values({ projectId: p.id, taskId: created.task.id, tmuxName: `mock-${key}`, status: "waiting_input" }).returning();
|
||||
return {
|
||||
project: p,
|
||||
key: created.key,
|
||||
taskId: created.task.id,
|
||||
sessionId: s!.id,
|
||||
session: () => core.getSession(db, s!.id),
|
||||
ref: () => core.resolveTask(db, created.key),
|
||||
asked: () => db.select().from(questions).where(eq(questions.taskId, created.task.id)).orderBy(questions.id),
|
||||
thread: async () => {
|
||||
await core.syncChats(db);
|
||||
return core.chatMessagesView(db, (await core.ensureProjectChat(db, p.id)).id, { threadKey: `task:${created.task.id}` });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Runs the real peppa-hook like Claude Code does: payload on stdin. */
|
||||
function hook(event: string, payload: unknown, sessionId: number): Promise<void> {
|
||||
return new Promise((done) => {
|
||||
const p = spawn(join(ROOT, "packages/runner/bin/peppa-hook"), [event], { env: { ...process.env, PEPPA_SESSION_ID: String(sessionId), PEPPA_GENERATION: "0" }, stdio: ["pipe", "ignore", "inherit"] });
|
||||
p.on("close", (code) => {
|
||||
assert.equal(code, 0);
|
||||
done();
|
||||
});
|
||||
p.stdin.end(JSON.stringify(payload));
|
||||
});
|
||||
}
|
||||
|
||||
const outboxTo = async (chatId: number) =>
|
||||
(await db.select().from(telegramOutbox).where(sql`cast(json_extract(${telegramOutbox.params}, '$.chat_id') as text) = ${String(chatId)}`).orderBy(telegramOutbox.id)).map((r) => String(r.params.text));
|
||||
const openOf = (projectId: number) => db.select().from(questions).where(and(eq(questions.projectId, projectId), isNull(questions.answeredAt)));
|
||||
|
||||
before(async () => {
|
||||
owner = await core.upsertUserFromGitea(db, { id: 541, login: "mock-owner" }, { access_token: "x" });
|
||||
admin = await core.upsertUserFromGitea(db, { id: 542, login: "mock-admin" }, { access_token: "x" });
|
||||
await db.update(users).set({ telegramChatId: 5410, telegramUserId: 5410 }).where(eq(users.id, owner.id));
|
||||
await db.update(users).set({ telegramChatId: 5420, telegramUserId: 5420 }).where(eq(users.id, admin.id));
|
||||
await core.setPlatformAdmins(db, [admin.login]);
|
||||
});
|
||||
after(async () => {
|
||||
await bugsink.stop();
|
||||
await teardown();
|
||||
});
|
||||
|
||||
describe("PEP-154: фильтр служебного текста", () => {
|
||||
test("userText: блоки, ANSI, вывод команд, приглашение оболочки, трассировка и пути убираются; адреса остаются", () => {
|
||||
const out = core.userText(TERMINAL_REPLY);
|
||||
assert.equal(out, "Проверки не прошли, нужен ваш ответ.\n\nФайл:\nЧто выбрать: чинить сейчас или отложить?");
|
||||
assert.equal(core.userText(out), out, "idempotent");
|
||||
assert.equal(core.userText(NOTIFICATION), "");
|
||||
assert.equal(core.userText("Готово. <system-reminder>не для людей</system-reminder> Результат: https://git.example.com/pay/pulls/7"), "Готово. Результат: https://git.example.com/pay/pulls/7");
|
||||
assert.equal(core.userText("Поправил `packages/core/src/chats.ts` и C:\\Users\\pm\\app.ts, проверил."), "Поправил и, проверил.");
|
||||
// A person's own words are not rewritten: only what is certainly service text.
|
||||
assert.equal(core.stripServiceBlocks("Синий, как в /Users/me/макет.png"), "Синий, как в /Users/me/макет.png");
|
||||
assert.equal(core.isServiceInput(NOTIFICATION), true);
|
||||
assert.equal(core.isServiceInput("Синий"), false);
|
||||
});
|
||||
|
||||
test("Реплика агента с выводом терминала и путём", async () => {
|
||||
const st = await story();
|
||||
await hook("stop", { last_assistant_message: TERMINAL_REPLY }, st.sessionId);
|
||||
// Two automatic nudges first (the story is at work), then the message for the person.
|
||||
await hook("stop", { last_assistant_message: TERMINAL_REPLY }, st.sessionId);
|
||||
await hook("stop", { last_assistant_message: TERMINAL_REPLY }, st.sessionId);
|
||||
const [q] = await st.asked();
|
||||
assert.ok(q, "the owner got a message");
|
||||
assert.match(q.text, /Проверки не прошли, нужен ваш ответ\./);
|
||||
assert.match(q.text, /чинить сейчас или отложить/);
|
||||
for (const bad of ["/Users/", "pnpm test", "FAIL", "TypeError", "at sum", "\x1b", "```"]) assert.ok(!q.text.includes(bad), `no «${bad}» in the message`);
|
||||
const thread = await st.thread();
|
||||
assert.ok(thread.some((m) => m.text.includes("Проверки не прошли")));
|
||||
assert.ok(!thread.some((m) => m.text.includes("/Users/") || m.text.includes("pnpm test")));
|
||||
const tg = renderQuestion(q, { taskKey: st.key, taskTitle: "Оплата картой", taskStatus: "in_progress", session: await st.session(), webUrl: "http://peppa.test" });
|
||||
assert.ok(!tg.text.includes("/Users/") && !tg.text.includes("tmux attach"), "Telegram: no path, no terminal command");
|
||||
assert.ok(renderQuestion(q, { taskKey: st.key, taskTitle: null, session: await st.session(), webUrl: "http://peppa.test", engineer: true }).text.includes("tmux attach"), "«Инженер» keeps the terminal command");
|
||||
});
|
||||
|
||||
test("Исходный текст для инженера", async () => {
|
||||
const st = await story();
|
||||
const q = await core.raiseSessionQuestion(db, await st.session(), "attention", "Нужен ваш ответ. Файл /Users/telecom/Dev/pay/src/app.ts не открывается.");
|
||||
assert.ok(!q.text.includes("/Users/"));
|
||||
assert.match((await core.questionDetails(db, q.id)) ?? "", /\/Users\/telecom\/Dev\/pay\/src\/app\.ts/);
|
||||
const clean = await core.askPm(db, await st.ref(), { kind: "question", text: "Какой цвет кнопки?", options: ["Синий", "Зелёный"] });
|
||||
assert.equal(await core.questionDetails(db, clean.id), null, "nothing was cut — nothing to keep");
|
||||
// A permission request keeps its command: that is what the person allows.
|
||||
const perm = await core.raiseSessionQuestion(db, await st.session(), "permission", "Разрешить Bash: rm /Users/telecom/Dev/pay/tmp.txt", ["allow", "deny"]);
|
||||
assert.match(perm.text, /\/Users\/telecom/);
|
||||
});
|
||||
|
||||
test("От реплики ничего не осталось", async () => {
|
||||
const st = await story();
|
||||
await assert.rejects(core.askPm(db, await st.ref(), { kind: "question", text: "<system-reminder>только служебное</system-reminder>" }), /служебный текст/);
|
||||
assert.equal((await st.asked()).length, 0);
|
||||
// The end of a turn with nothing for a person: the plain «агент ждёт» line, not the block.
|
||||
for (let i = 0; i < 3; i++) await hook("stop", { last_assistant_message: NOTIFICATION }, st.sessionId);
|
||||
const [q] = await st.asked();
|
||||
assert.equal(q?.text, "Агент закончил ход и ждёт вашего ответа.");
|
||||
assert.equal(await core.addChatMessage(db, { chatId: (await core.ensureProjectChat(db, st.project.id)).id, kind: "event", authorKind: "agent", text: NOTIFICATION, dedupeKey: `mock:${st.key}` }), null);
|
||||
});
|
||||
});
|
||||
|
||||
describe("PEP-154: ответом вопроса считается только ввод человека", () => {
|
||||
test("Служебное уведомление в терминале", async () => {
|
||||
const st = await story();
|
||||
const q = await core.askPm(db, await st.ref(), { kind: "question", text: "Какой цвет кнопки?", sessionId: st.sessionId });
|
||||
await hook("prompt", { prompt: NOTIFICATION }, st.sessionId);
|
||||
const after = await core.getQuestion(db, q.id);
|
||||
assert.equal(after.answeredAt, null, "the question stays open");
|
||||
assert.equal(after.answer, null);
|
||||
const thread = await st.thread();
|
||||
assert.ok(!thread.some((m) => m.text.includes("task-notification") || (m.question?.answer ?? "").includes("task-notification")), "not in the chat: neither text nor answer");
|
||||
// Even if such a block came glued to a person's words, only the words are the answer.
|
||||
const answered = await core.answerQuestion(db, q.id, `Синий\n${NOTIFICATION}`, "terminal");
|
||||
assert.equal(answered.answer, "Синий");
|
||||
assert.ok(!renderAnswered("Вопрос", answered).includes("task-notification"));
|
||||
await assert.rejects(core.answerQuestion(db, (await core.askPm(db, await st.ref(), { kind: "question", text: "А размер?", sessionId: st.sessionId })).id, NOTIFICATION, "web"));
|
||||
});
|
||||
|
||||
test("Человек печатает в терминале", async () => {
|
||||
const st = await story();
|
||||
const q = await core.askPm(db, await st.ref(), { kind: "question", text: "Какой цвет кнопки?", sessionId: st.sessionId });
|
||||
await hook("prompt", { prompt: "Синий" }, st.sessionId);
|
||||
const after = await core.getQuestion(db, q.id);
|
||||
assert.equal(after.answer, "Синий");
|
||||
assert.equal(after.answeredVia, "terminal");
|
||||
});
|
||||
|
||||
test("Peppa сама пишет агенту", async () => {
|
||||
const st = await story();
|
||||
const q = await core.raiseSessionQuestion(db, await st.session(), "attention", "Агент закончил ход и ждёт вашего ответа.");
|
||||
const report = "Проверки PR красные: test\n$ pnpm test\nFAIL src/app.test.ts";
|
||||
await core.logSessionEvent(db, await st.session(), "input_sent", { text: report });
|
||||
await hook("prompt", { prompt: report }, st.sessionId);
|
||||
const after = await core.getQuestion(db, q.id);
|
||||
assert.equal(after.answeredVia, "system", "closed as stale, not answered");
|
||||
assert.ok(!(after.answer ?? "").includes("FAIL"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("PEP-154: ошибки платформы не идут владельцу проекта", () => {
|
||||
const NO_QUIET = { quietFrom: null, quietTo: null };
|
||||
const autonomy = (now = new Date()) => runner.autonomyTick(db, { now, log: () => {} });
|
||||
|
||||
test("Диспетчер упал с исключением; та же ошибка повторяется", async () => {
|
||||
// The platform project is connected to the error tracker (mock).
|
||||
const platform = await project({ turns: [] });
|
||||
process.env.PEPPA_PLATFORM_KEY = platform.key;
|
||||
core.resetErrorReporting();
|
||||
const client = createBugsinkClient({ url: bugsink.url, token: bugsink.token, teamId: bugsink.teamId, publicUrl: bugsink.url });
|
||||
await runner.connectErrorTracking(db, await core.getProject(db, platform.key), client, "http://peppa.test");
|
||||
|
||||
const tp = await project({ turns: [] });
|
||||
const p = await core.getProject(db, tp.key);
|
||||
await db.update(projects).set({ ownerId: owner.id }).where(eq(projects.id, p.id));
|
||||
await core.setAutonomy(db, p.id, { level: "auto", ...NO_QUIET });
|
||||
// The start blows up inside Peppa: the sessions table is gone for one tick.
|
||||
const now = new Date();
|
||||
const ingested = bugsink.ingested.length;
|
||||
db.run(sql`ALTER TABLE runner_tasks RENAME TO runner_tasks_x`);
|
||||
try {
|
||||
await autonomy(now);
|
||||
assert.equal((await openOf(p.id)).length, 0, "the owner gets no message");
|
||||
assert.equal((await outboxTo(5410)).length, 0, "nothing for the owner in Telegram");
|
||||
const alerts = (await outboxTo(5420)).filter((t) => t.includes("Сбой в Peppa FACTORY"));
|
||||
assert.equal(alerts.length, 1, "the superadmin gets one message");
|
||||
assert.ok(bugsink.ingested.length > ingested, "the error tracker has the exception");
|
||||
// Ten minutes later the same error: no second message.
|
||||
await autonomy(new Date(now.getTime() + 10 * 60_000));
|
||||
assert.equal((await outboxTo(5420)).filter((t) => t.includes("Сбой в Peppa FACTORY")).length, 1);
|
||||
assert.equal((await openOf(p.id)).length, 0);
|
||||
} finally {
|
||||
db.run(sql`ALTER TABLE runner_tasks_x RENAME TO runner_tasks`);
|
||||
}
|
||||
});
|
||||
|
||||
test("Понятный отказ", async () => {
|
||||
assert.equal(await core.platformFailure(db, new core.PeppaError("Подписка не выбрана — выберите её в настройках проекта."), { service: "watchdog", where: "dispatch PAY-7" }), "Подписка не выбрана — выберите её в настройках проекта.");
|
||||
assert.equal(await core.platformFailure(db, new Error("SQLITE_ERROR: no such column: x"), { service: "watchdog", where: "dispatch PAY-7" }), null);
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user