125 lines
8.9 KiB
TypeScript
125 lines
8.9 KiB
TypeScript
// PEP-198: the analyst is the only one who talks to the owner. A developer agent's question
|
||
// (MCP ask_pm, a product blocker) comes to the analyst first, and the analyst decides:
|
||
// - a technical question (stack, base, libraries, architecture, which service to plug in) does
|
||
// not reach the owner — the agent decides itself;
|
||
// - the same question by meaning as one already asked does not reach the owner again;
|
||
// - a product question goes to the owner once, in the analyst's words, with answers to tap.
|
||
// Cheap rules first (no model), then one short model call on the project's subscription
|
||
// (`PEPPA_RELAY_MODEL`, haiku). A failing model lets the question through as the agent wrote it:
|
||
// better asked twice than lost. `PEPPA_AGENT_RELAY=off` — the old way, straight to the owner.
|
||
import { questions, type Db } from "@peppa/db";
|
||
import { and, desc, eq, gte } from "drizzle-orm";
|
||
import { logEvent, normTitle, type Project, type TaskRef } from "@peppa/core";
|
||
import { stripAsIs } from "@peppa/shared/i18n";
|
||
import { claudePrint } from "./claude-print.ts";
|
||
|
||
export const RELAY_PROMPT_HEAD = "Ты — аналитик софтвер-фабрики между агентами и владельцем продукта.";
|
||
const WINDOW_MS = 7 * 86_400_000;
|
||
|
||
/** Words that make a question technical by themselves: the owner (not a programmer) cannot answer it. */
|
||
const TECH = /(баз[аеуыой]{1,2} данных|postgres|sqlite|mysql|mongo|redis|библиотек|фреймворк|(?<![а-яё])стек(?![а-яё])|миграци|схем[аеуы] данных|архитектур|\bapi\b|эндпоинт|\bendpoint|\bsdk\b|\bdocker|контейнер|(?<![а-яё])ветк[аеиу](?![а-яё])|\bgit\b|\bci\b|линтер|typescript|python|\breact\b|next\.?js|node\.?js|\bnpm\b|\bpnpm\b|webhook|вебхук|\borm\b|\bjwt\b|oauth|автотест|юнит-тест)/i;
|
||
|
||
export type RelayVerdict =
|
||
| { kind: "product"; text: string; options: string[]; defaultOption: string; byModel: boolean }
|
||
| { kind: "technical"; reason: string }
|
||
| { kind: "repeat"; questionId: number };
|
||
|
||
export interface AgentQuestion {
|
||
text: string;
|
||
options: string[];
|
||
defaultOption: string;
|
||
}
|
||
|
||
export function relayPrompt(o: { project: string; task: string; question: AgentQuestion; earlier: Array<{ id: number; text: string }> }): string {
|
||
return [
|
||
`${RELAY_PROMPT_HEAD} Агент-разработчик хочет спросить владельца. Владелец — не программист. Реши, что из этого дойдёт до него.`,
|
||
"verdict:",
|
||
"- technical — вопрос о том, как сделать (стек, база, библиотеки, архитектура, какой внешний сервис подключить, тесты, сборка): владелец на него ответить не может, агент решает сам. Если продукту нужен внешний сервис или ключ — это тоже technical: сервис выбирает агент, а не владелец.",
|
||
"- repeat — по смыслу то же, что уже спрошено у владельца (список ниже), даже другими словами. repeat_of — номер того вопроса.",
|
||
"- product — вопрос о продукте, на который может ответить только владелец: что увидит или получит пользователь, правила, тексты, деньги. Тогда text — твой пересказ вопроса для владельца: одна-две фразы, простые слова, на «вы», без жаргона, без названий файлов и веток; options — 2–4 варианта ответа (вариант агента по умолчанию — первым), default — вариант по умолчанию.",
|
||
"",
|
||
`Проект: ${o.project}`,
|
||
`Задача: ${o.task}`,
|
||
"",
|
||
"## Вопрос агента",
|
||
o.question.text.trim(),
|
||
"",
|
||
`Варианты агента: ${o.question.options.join(" | ")}`,
|
||
`По умолчанию: ${o.question.defaultOption}`,
|
||
"",
|
||
"## Уже спрошено у владельца",
|
||
o.earlier.length ? o.earlier.map((q) => `- #${q.id}: ${q.text.replace(/\s+/g, " ").slice(0, 300)}`).join("\n") : "(ничего)",
|
||
"",
|
||
'Ответь ОДНОЙ строкой JSON без пояснений: {"verdict":"product|technical|repeat","repeat_of":null,"text":"…","options":["…"],"default":"…"}',
|
||
].join("\n");
|
||
}
|
||
|
||
export function parseRelay(text: string): { verdict: "product" | "technical" | "repeat"; repeatOf: number | null; text: string; options: string[]; default: string } | null {
|
||
const m = /\{[\s\S]*\}/.exec(text);
|
||
if (!m) return null;
|
||
try {
|
||
const o = JSON.parse(m[0]) as Record<string, unknown>;
|
||
const verdict = o.verdict === "product" || o.verdict === "technical" || o.verdict === "repeat" ? o.verdict : null;
|
||
if (!verdict) return null;
|
||
const options = (Array.isArray(o.options) ? o.options : []).map((x) => String(x ?? "").trim().slice(0, 120)).filter(Boolean).slice(0, 4);
|
||
return { verdict, repeatOf: Number(o.repeat_of) || null, text: typeof o.text === "string" ? o.text.trim().slice(0, 600) : "", options, default: typeof o.default === "string" ? o.default.trim() : "" };
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/** What the owner was already asked about this story lately (open first). */
|
||
async function earlierQuestions(db: Db, taskId: number): Promise<Array<{ id: number; text: string; open: boolean }>> {
|
||
const rows = await db
|
||
.select({ id: questions.id, text: questions.text, answeredAt: questions.answeredAt, msgType: questions.msgType })
|
||
.from(questions)
|
||
.where(and(eq(questions.taskId, taskId), eq(questions.kind, "question"), gte(questions.createdAt, new Date(Date.now() - WINDOW_MS))))
|
||
.orderBy(desc(questions.id))
|
||
.limit(10);
|
||
return rows.map((r) => ({ id: r.id, text: stripAsIs(r.text).split("\n")[0] ?? "", open: !r.answeredAt }));
|
||
}
|
||
|
||
export async function relayAgentQuestion(db: Db, ref: TaskRef, q: AgentQuestion, o: { log?: (m: string) => void } = {}): Promise<RelayVerdict> {
|
||
const asIsQuestion: RelayVerdict = { kind: "product", text: q.text, options: q.options, defaultOption: q.defaultOption, byModel: false };
|
||
if (process.env.PEPPA_AGENT_RELAY === "off") return asIsQuestion;
|
||
const decided = async (v: RelayVerdict) => {
|
||
await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "relay_decided", payload: { verdict: v.kind, question: q.text.slice(0, 500), ...(v.kind === "repeat" ? { of: v.questionId } : {}) } }).catch(() => {});
|
||
return v;
|
||
};
|
||
if (TECH.test(q.text)) return decided({ kind: "technical", reason: "rule" });
|
||
const earlier = await earlierQuestions(db, ref.task.id);
|
||
const same = earlier.find((e) => normTitle(e.text) === normTitle(q.text));
|
||
if (same) return decided({ kind: "repeat", questionId: same.id });
|
||
const out = await ask(db, ref.project, relayPrompt({ project: ref.project.name, task: `${ref.key} «${ref.task.title}»`, question: q, earlier }));
|
||
const r = out.ok ? parseRelay(out.text) : null;
|
||
if (!r) {
|
||
o.log?.(`relay ${ref.key}: ${out.ok ? "unparsable" : out.error} — passed as is`);
|
||
return asIsQuestion;
|
||
}
|
||
if (r.verdict === "technical") return decided({ kind: "technical", reason: "model" });
|
||
if (r.verdict === "repeat") {
|
||
const of = earlier.find((e) => e.id === r.repeatOf) ?? earlier[0];
|
||
if (of) return decided({ kind: "repeat", questionId: of.id });
|
||
return asIsQuestion;
|
||
}
|
||
const options = r.options.length >= 2 ? r.options : q.options;
|
||
const defaultOption = options.includes(r.default) ? r.default : options.includes(q.defaultOption) ? q.defaultOption : options[0]!;
|
||
return decided({ kind: "product", text: r.text || q.text, options: [defaultOption, ...options.filter((x) => x !== defaultOption)], defaultOption, byModel: true });
|
||
}
|
||
|
||
const ask = (db: Db, project: Project, prompt: string) =>
|
||
claudePrint(db, project, {
|
||
bin: process.env.PEPPA_INTENT_BIN ?? process.env.PEPPA_INTAKE_BIN ?? "claude",
|
||
model: process.env.PEPPA_RELAY_MODEL ?? process.env.PEPPA_INTENT_MODEL ?? "haiku",
|
||
timeoutMs: Number(process.env.PEPPA_INTENT_TIMEOUT_MS ?? 30_000),
|
||
who: "аналитик",
|
||
prompt,
|
||
});
|
||
|
||
/** What the agent is told when its question does not reach the owner. */
|
||
export function relayRefusal(v: Exclude<RelayVerdict, { kind: "product" }>, key: string): string {
|
||
return v.kind === "technical"
|
||
? `Not sent to the owner: the analyst sees a technical question (how to build it — stack, data, libraries, which service to use). The owner is a product person and cannot answer it. Decide yourself, note the choice and why in design.md and project memory (remember, «Решения»), and go on with ${key}.`
|
||
: `Not sent to the owner: the same question (#${v.questionId}) is already with the owner. Don't ask again — go on with your default; the answer arrives as a message.`;
|
||
}
|