diff --git a/AGENTS.md b/AGENTS.md index 70d066cf..4a1b674a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -5,12 +5,12 @@ ## Структура - `apps/web` — Next.js платформа (порт 3100): проекты, цели, задачи, сессии -- `apps/bot` — Telegram-бот (grammY) +- `apps/bot` — Telegram-бот (`peppa-bot`, launchd `quest.telecom.peppa.bot`): свой мини-клиент Bot API (`TELEGRAM_API_URL` для мока), long polling с сохранённым offset, `telegram_updates` фиксирует update до действия (без повторов после рестарта), durable outbox с ретраями (429 retry_after, 5xx), привязка только через `/start <код>` (`peppa telegram pair`), чужие чаты игнорируются. Отвечает только на конкретный вопрос (кнопки/реплай) и умеет resume/stop сессии из алерта - `packages/db` — Drizzle-схема и клиент (Postgres на 127.0.0.1:5433) - `packages/shared` — env, ключи задач (`PEP-42`) - `packages/core` — доменная логика (проекты, цели, задачи, вопросы PM, pg NOTIFY `peppa_events`); всё ходит через неё - `packages/mcp` — MCP-сервер `peppa` (бинарь `peppa-mcp`) для сессий в проектах; проект берётся из `.peppa/project.json` в cwd -- `packages/testkit` — `mock-claude` / `mock-codex` (моки CLI агентов по сценариям: хуки, notify, MCP, лимиты, зависания, падения) и e2e-набор CJM +- `packages/testkit` — `mock-claude` / `mock-codex`, `mock-telegram` (мок Bot API) (моки CLI агентов по сценариям: хуки, notify, MCP, лимиты, зависания, падения) и e2e-набор CJM - `packages/cli` — CLI `peppa` (project/goal/task/q), пока нет веба - `packages/runner` — запуск claude в tmux (`peppa--s`), вачдог, `peppa-hook` - хуки не в репо проекта, а в генерируемом `~/.peppa/runs/s-g/settings.json` (`claude --settings`) diff --git a/apps/bot/bin/peppa-bot b/apps/bot/bin/peppa-bot new file mode 100755 index 00000000..1f7067b7 --- /dev/null +++ b/apps/bot/bin/peppa-bot @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +PEPPA_ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)" +. "$PEPPA_ROOT/scripts/lib/load-env.sh" +exec "$PEPPA_ROOT/node_modules/.bin/tsx" "$PEPPA_ROOT/apps/bot/src/index.ts" "$@" diff --git a/apps/bot/package.json b/apps/bot/package.json index cfedebf0..1dca122c 100644 --- a/apps/bot/package.json +++ b/apps/bot/package.json @@ -3,6 +3,14 @@ "version": "0.0.0", "private": true, "type": "module", + "exports": { ".": "./src/bot.ts", "./telegram": "./src/telegram.ts" }, + "bin": { "peppa-bot": "./bin/peppa-bot" }, "scripts": { "start": "tsx src/index.ts", "typecheck": "tsc -p ." }, - "dependencies": { "@peppa/db": "workspace:*", "@peppa/shared": "workspace:*" } + "dependencies": { + "@peppa/core": "workspace:*", + "@peppa/db": "workspace:*", + "@peppa/runner": "workspace:*", + "@peppa/shared": "workspace:*", + "drizzle-orm": "0.45.4" + } } diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts new file mode 100644 index 00000000..ae71466f --- /dev/null +++ b/apps/bot/src/bot.ts @@ -0,0 +1,310 @@ +// Peppa Telegram bot: forwards PM questions (approvals, questions, permissions, session +// alerts) to the paired chat and turns button presses / replies into answers delivered +// back into the agent session. Telegram is an adapter over the DB, not a remote shell: +// it can only answer a specific pending question or resume/stop the session it is about. +import { + acceptPairing, + claimUpdate, + dueOutbox, + enqueueTelegram, + EVENTS_CHANNEL, + finishUpdate, + getBinding, + getOffset, + getOutbox, + getQuestion, + getSession, + listSessions, + markOutboxRetry, + markOutboxSent, + pendingQuestions, + questionByTelegramMessage, + setOffset, + setSetting, + type OutboxRow, + type Question, + type SessionView, +} from "@peppa/core"; +import { questions, tasks, projects, type Db } from "@peppa/db"; +import { formatTaskKey } from "@peppa/shared"; +import { answerAndDeliver, resumeSession, stopSession } from "@peppa/runner"; +import { and, eq, gt, isNotNull } from "drizzle-orm"; +import { choiceToAnswer, esc, renderAnswered, renderQuestion } from "./render.ts"; +import { TelegramApi, TelegramError, type TgCallbackQuery, type TgMessage, type TgUpdate } from "./telegram.ts"; + +export interface BotOptions { + db: Db; + api: TelegramApi; + /** Server-side secret for hashing pairing codes (the bot token). */ + secret: string; + webUrl: string; + pollTimeoutSec?: number; + outboxIntervalMs?: number; + reconcileIntervalMs?: number; + log?: (msg: string) => void; +} + +const HELP = `Я бот Пеппы. Присылаю вопросы от агентов: одобрения proposal, вопросы, разрешения и сигналы, что сессия ждёт тебя. + +• Кнопки под сообщением — быстрый ответ. +• Ответ реплаем на сообщение — свой текст, он уйдёт прямо в сессию. +• /status — активные сессии и открытые вопросы.`; + +export function createBot(o: BotOptions) { + const { db, api } = o; + const log = o.log ?? (() => {}); + const abort = new AbortController(); + let reconcileQueued = false; + let wakeOutbox: (() => void) | null = null; + + // ── questions → outbox ───────────────────────────────────────────────────────── + async function context(q: Question) { + let session: SessionView | null = null; + if (q.sessionId) session = await getSession(db, q.sessionId).catch(() => null); + if (session) return { taskKey: session.taskKey, taskTitle: session.taskTitle, session, webUrl: o.webUrl }; + if (q.taskId) { + const [t] = await db + .select({ key: projects.key, number: tasks.number, title: tasks.title }) + .from(tasks) + .innerJoin(projects, eq(tasks.projectId, projects.id)) + .where(eq(tasks.id, q.taskId)); + if (t) return { taskKey: formatTaskKey(t.key, t.number), taskTitle: t.title, session: null, webUrl: o.webUrl }; + } + return { taskKey: null, taskTitle: null, session: null, webUrl: o.webUrl }; + } + + /** Makes sure every open question has a message and every closed one an edit. */ + async function reconcile(): Promise { + const binding = await getBinding(db); + if (!binding) return; + for (const q of await pendingQuestions(db)) { + if (await getOutbox(db, `q:${q.id}`)) continue; + const r = renderQuestion(q, await context(q)); + await enqueueTelegram(db, { + dedupeKey: `q:${q.id}`, + method: "sendMessage", + questionId: q.id, + params: { chat_id: binding.chatId, text: r.text, parse_mode: "HTML", reply_markup: { inline_keyboard: r.buttons } }, + }); + } + const since = new Date(Date.now() - 24 * 3600_000); + const answered = await db + .select() + .from(questions) + .where(and(isNotNull(questions.answeredAt), isNotNull(questions.telegramMessageId), gt(questions.answeredAt, since))); + for (const q of answered) { + if (await getOutbox(db, `qa:${q.id}`)) continue; + const sent = await getOutbox(db, `q:${q.id}`); + if (!sent) continue; + await enqueueTelegram(db, { + dedupeKey: `qa:${q.id}`, + method: "editMessageText", + questionId: q.id, + params: { + chat_id: sent.params.chat_id, + message_id: q.telegramMessageId, + text: renderAnswered(String(sent.params.text), q), + parse_mode: "HTML", + reply_markup: { inline_keyboard: [] }, + }, + }); + } + wakeOutbox?.(); + } + + function scheduleReconcile() { + if (reconcileQueued) return; + reconcileQueued = true; + setTimeout(() => { + reconcileQueued = false; + reconcile().catch((e) => log(`reconcile: ${(e as Error).message}`)); + }, 150); + } + + // ── outbox → Telegram ────────────────────────────────────────────────────────── + async function deliver(row: OutboxRow): Promise { + if (row.method === "sendMessage" && row.questionId) { + // Answered before we got to it (e.g. in the terminal): no point in asking. + const q = await getQuestion(db, row.questionId).catch(() => null); + if (q?.answeredAt) return markOutboxSent(db, { ...row, questionId: null }, null); + } + try { + const res = await api.call(row.method, row.params); + await markOutboxSent(db, row, typeof res === "object" ? res.message_id : null); + } catch (e) { + if (!(e instanceof TelegramError)) throw e; + if (e.code === 400 && /not modified/i.test(e.description)) return markOutboxSent(db, row, null); + log(`outbox #${row.id} ${row.method}: ${e.message}`); + // 400/403 won't get better by retrying. + if (e.code === 400 || e.code === 403) return markOutboxRetry(db, { ...row, attempts: 99 }, e.message); + await markOutboxRetry(db, row, e.message, e.retryAfter); + } + } + + async function flushOutbox(): Promise { + for (const row of await dueOutbox(db)) await deliver(row); + } + + // ── Telegram → answers ───────────────────────────────────────────────────────── + async function reply(chatId: number, text: string, replyTo?: number) { + await api.sendMessage(chatId, text, replyTo ? { reply_parameters: { message_id: replyTo } } : {}).catch((e) => log(`reply: ${e.message}`)); + } + + async function answer(q: Question, text: string): Promise { + const fresh = await getQuestion(db, q.id); + if (fresh.answeredAt) return `Уже отвечено${fresh.answeredVia === "system" ? "" : ` (${fresh.answeredVia})`}: ${fresh.answer}`; + const { delivered } = await answerAndDeliver(db, q.id, text, "telegram"); + scheduleReconcile(); + return delivered ? "Отправлено в сессию ✅" : "Ответ сохранён, но сессия сейчас не запущена — агент увидит его в истории задачи."; + } + + async function status(): Promise { + const sessions = await listSessions(db, { active: true }); + const open = await pendingQuestions(db); + const lines = [`Активные сессии: ${sessions.length}`]; + for (const s of sessions) lines.push(`• ${esc(s.taskKey ?? `#${s.id}`)} — ${s.status} (${s.provider})`); + lines.push("", `Открытых вопросов: ${open.length}`); + return lines.join("\n"); + } + + async function onMessage(m: TgMessage): Promise<"done" | "ignored"> { + const text = m.text?.trim() ?? ""; + const binding = await getBinding(db); + const start = /^\/start(?:@\w+)?(?:\s+(\S+))?$/.exec(text); + if (start?.[1] && m.from) { + const b = await acceptPairing(db, o.secret, start[1], { chatId: m.chat.id, userId: m.from.id, username: m.from.username }); + if (b) { + await reply(m.chat.id, `Привязано ✅\n\n${HELP}`); + scheduleReconcile(); + return "done"; + } + await reply(m.chat.id, "Код привязки неверный или истёк. Получи новый: peppa telegram pair"); + return "done"; + } + if (!binding || m.chat.id !== binding.chatId || m.from?.id !== binding.userId) return "ignored"; + + if (/^\/(start|help)\b/.test(text)) return reply(m.chat.id, HELP).then(() => "done"); + if (/^\/status\b/.test(text)) return reply(m.chat.id, await status()).then(() => "done"); + + if (m.reply_to_message) { + const q = await questionByTelegramMessage(db, m.reply_to_message.message_id); + if (!q) { + await reply(m.chat.id, "Не нашёл вопрос для этого сообщения.", m.message_id); + return "done"; + } + await reply(m.chat.id, esc(await answer(q, text)), m.message_id); + return "done"; + } + await reply(m.chat.id, "Чтобы ответить агенту, ответь реплаем на его сообщение. /status — что сейчас происходит."); + return "done"; + } + + async function onCallback(c: TgCallbackQuery): Promise<"done" | "ignored"> { + const binding = await getBinding(db); + if (!binding || c.from.id !== binding.userId || c.message?.chat.id !== binding.chatId) { + await api.answerCallbackQuery(c.id, "Нет доступа").catch(() => {}); + return "ignored"; + } + const [kind, idStr, choice] = (c.data ?? "").split(":"); + const id = Number(idStr); + let toast = "Неизвестная кнопка"; + if (kind === "q") { + const q = await getQuestion(db, id).catch(() => null); + const text = q && choice ? choiceToAnswer(q, choice) : null; + toast = q && text ? await answer(q, text) : "Вопрос не найден"; + } else if (kind === "s") { + const s = await getSession(db, id).catch(() => null); + if (!s) toast = "Сессия не найдена"; + else if (choice === "resume") { + try { + const r = await resumeSession(db, s.id); + toast = `Перезапущено (поколение ${r.generation}) 🔁`; + } catch (e) { + toast = (e as Error).message; + } + } else if (choice === "stop") { + await stopSession(db, s.id); + toast = "Сессия остановлена ⏹"; + } + scheduleReconcile(); + } + await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`)); + return "done"; + } + + async function handleUpdate(u: TgUpdate): Promise { + if (!(await claimUpdate(db, u.update_id))) return; + try { + const r = u.message ? await onMessage(u.message) : u.callback_query ? await onCallback(u.callback_query) : "ignored"; + await finishUpdate(db, u.update_id, r); + } catch (e) { + log(`update ${u.update_id}: ${(e as Error).stack ?? e}`); + await finishUpdate(db, u.update_id, "failed"); + } + } + + // ── loops ────────────────────────────────────────────────────────────────────── + const sleep = (ms: number) => + new Promise((r) => { + const t = setTimeout(r, ms); + abort.signal.addEventListener("abort", () => (clearTimeout(t), r()), { once: true }); + }); + + async function pollLoop() { + while (!abort.signal.aborted) { + try { + let offset = await getOffset(db); + const updates = await api.getUpdates(offset, o.pollTimeoutSec ?? 25, abort.signal); + for (const u of updates) { + await handleUpdate(u); + offset = u.update_id + 1; + await setOffset(db, offset); + } + } catch (e) { + log(`poll: ${(e as Error).message}`); + await sleep(3000); + } + } + } + + async function outboxLoop() { + while (!abort.signal.aborted) { + await flushOutbox().catch((e) => log(`outbox: ${(e as Error).message}`)); + await Promise.race([sleep(o.outboxIntervalMs ?? 1000), new Promise((r) => (wakeOutbox = r))]); + wakeOutbox = null; + } + } + + async function reconcileLoop() { + while (!abort.signal.aborted) { + await reconcile().catch((e) => log(`reconcile: ${(e as Error).message}`)); + await sleep(o.reconcileIntervalMs ?? 10_000); + } + } + + let loops: Promise | null = null; + let unlisten: (() => Promise) | null = null; + + return { + reconcile, + flushOutbox, + handleUpdate, + async start() { + const me = await api.getMe(); + await setSetting(db, "telegram.bot", { id: me.id, username: me.username }); + log(`bot @${me.username} started`); + const l = await db.$client.listen(EVENTS_CHANNEL, () => scheduleReconcile()); + unlisten = () => l.unlisten(); + loops = Promise.all([pollLoop(), outboxLoop(), reconcileLoop()]); + return me; + }, + async stop() { + abort.abort(); + wakeOutbox?.(); + await unlisten?.().catch(() => {}); + await loops; + }, + }; +} + +export type Bot = ReturnType; diff --git a/apps/bot/src/index.ts b/apps/bot/src/index.ts index 0612a7f5..2fc21e3a 100644 --- a/apps/bot/src/index.ts +++ b/apps/bot/src/index.ts @@ -1,2 +1,22 @@ -// Telegram bot (stage 4): notifies the PM and relays answers into tmux sessions. -console.log("@peppa/bot: not implemented yet"); +// Entry point: `peppa-bot` (launchd agent quest.telecom.peppa.bot). +import { createDb } from "@peppa/db"; +import { loadEnv } from "@peppa/shared"; +import { createBot } from "./bot.ts"; +import { TelegramApi } from "./telegram.ts"; + +const env = loadEnv(); +if (!env.TELEGRAM_BOT_TOKEN) { + console.error("TELEGRAM_BOT_TOKEN is not set"); + process.exit(1); +} +const bot = createBot({ + db: createDb(env.DATABASE_URL), + api: new TelegramApi(env.TELEGRAM_BOT_TOKEN, process.env.TELEGRAM_API_URL), + secret: env.TELEGRAM_BOT_TOKEN, + webUrl: env.PEPPA_WEB_URL, + log: (m) => console.log(`${new Date().toISOString()} ${m}`), +}); +await bot.start(); +for (const sig of ["SIGINT", "SIGTERM"] as const) { + process.on(sig, () => void bot.stop().then(() => process.exit(0))); +} diff --git a/apps/bot/src/render.ts b/apps/bot/src/render.ts new file mode 100644 index 00000000..51f288ec --- /dev/null +++ b/apps/bot/src/render.ts @@ -0,0 +1,72 @@ +// Telegram message texts and buttons for PM questions. HTML parse mode. +import type { Question, SessionView } from "@peppa/core"; +import type { InlineButton } from "./telegram.ts"; + +export const esc = (s: string) => s.replace(/&/g, "&").replace(//g, ">"); +const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}…` : s); + +const KIND: Record = { + approval: "📝 Нужно одобрение proposal", + question: "❓ Вопрос", + permission: "🔐 Нужно разрешение", + attention: "👀 Сессия ждёт тебя", +}; + +export interface Rendered { + text: string; + buttons: InlineButton[][]; +} + +// callback_data (≤64 bytes): "q::" or "s::" +export function renderQuestion(q: Question, ctx: { taskKey: string | null; taskTitle: string | null; session: SessionView | null; webUrl: string }): Rendered { + const head = [`${esc(ctx.taskKey ?? `Сессия ${q.sessionId ?? "?"}`)}`, ctx.taskTitle ? `${esc(clip(ctx.taskTitle, 80))}` : null] + .filter(Boolean) + .join(" · "); + const body = esc(clip(q.text, 3300)); + const lines = [head, KIND[q.kind], "", body]; + + const buttons: InlineButton[][] = []; + if (q.kind === "approval") { + buttons.push([{ text: "✅ Одобрить", callback_data: `q:${q.id}:approve` }]); + lines.push("", "Чтобы вернуть на доработку — ответь на это сообщение комментарием."); + } else if (q.kind === "permission") { + buttons.push([ + { text: "✅ Разрешить", callback_data: `q:${q.id}:allow` }, + { text: "♾ Всегда", callback_data: `q:${q.id}:always` }, + { text: "⛔ Запретить", callback_data: `q:${q.id}:deny` }, + ]); + } else if (q.kind === "question") { + (q.options ?? []).slice(0, 6).forEach((o, i) => buttons.push([{ text: clip(o, 60), callback_data: `q:${q.id}:o${i}` }])); + lines.push("", "Выбери вариант или ответь на это сообщение своим текстом."); + } else { + const s = ctx.session; + if (s && ["failed", "rate_limited", "stalled"].includes(s.status)) { + buttons.push([ + { text: "🔁 Перезапустить", callback_data: `s:${s.id}:resume` }, + { text: "⏹ Остановить", callback_data: `s:${s.id}:stop` }, + ]); + } else { + buttons.push([{ text: "▶️ Продолжай", callback_data: `q:${q.id}:cont` }]); + lines.push("", "Или ответь на это сообщение — текст уйдёт в сессию."); + } + } + if (ctx.session) lines.push(`tmux attach -t ${esc(ctx.session.tmuxName)}`); + return { text: lines.join("\n"), buttons }; +} + +/** Text after the question is closed: original + who answered what, no buttons. */ +export function renderAnswered(original: string, q: Question): string { + const mark = q.answeredVia === "system" ? "⌛" : "✅"; + const via = { telegram: "в Telegram", web: "в вебе", terminal: "в терминале", system: "" }[q.answeredVia ?? "telegram"]; + return `${original}\n\n${mark} ${q.answeredVia === "system" ? esc(q.answer ?? "") : `Ответ ${via}: ${esc(clip(q.answer ?? "", 500))}`}`; +} + +/** The answer text a button stands for. */ +export function choiceToAnswer(q: Question, choice: string): string | null { + if (q.kind === "approval" && choice === "approve") return "ок"; + if (q.kind === "permission" && ["allow", "always", "deny"].includes(choice)) return choice; + if (q.kind === "attention" && choice === "cont") return "Продолжай."; + const m = /^o(\d+)$/.exec(choice); + if (q.kind === "question" && m) return q.options?.[Number(m[1])] ?? null; + return null; +} diff --git a/apps/bot/src/telegram.ts b/apps/bot/src/telegram.ts new file mode 100644 index 00000000..bea22d50 --- /dev/null +++ b/apps/bot/src/telegram.ts @@ -0,0 +1,97 @@ +// Minimal Telegram Bot API client. The base URL is configurable so tests can point it at +// mock-telegram (packages/testkit). + +export interface TgUser { + id: number; + username?: string; + first_name?: string; +} +export interface TgMessage { + message_id: number; + chat: { id: number; type: string }; + from?: TgUser; + text?: string; + reply_to_message?: TgMessage; +} +export interface TgCallbackQuery { + id: string; + from: TgUser; + message?: TgMessage; + data?: string; +} +export interface TgUpdate { + update_id: number; + message?: TgMessage; + callback_query?: TgCallbackQuery; +} +export interface InlineButton { + text: string; + callback_data?: string; + url?: string; +} + +export class TelegramError extends Error { + constructor( + readonly method: string, + readonly code: number, + readonly description: string, + readonly retryAfter?: number, + ) { + super(`${method}: ${code} ${description}`); + } +} + +export class TelegramApi { + constructor( + private readonly token: string, + private readonly baseUrl = "https://api.telegram.org", + ) {} + + async call(method: string, params: Record = {}, timeoutMs = 15_000): Promise { + let res: Response; + try { + res = await fetch(`${this.baseUrl}/bot${this.token}/${method}`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(params), + signal: AbortSignal.timeout(timeoutMs), + }); + } catch (e) { + throw new TelegramError(method, 0, (e as Error).message); + } + const body = (await res.json().catch(() => ({}))) as { + ok?: boolean; + result?: T; + description?: string; + error_code?: number; + parameters?: { retry_after?: number }; + }; + if (!body.ok) { + throw new TelegramError(method, body.error_code ?? res.status, body.description ?? res.statusText, body.parameters?.retry_after); + } + return body.result as T; + } + + getMe() { + return this.call("getMe"); + } + + getUpdates(offset: number, timeoutSec: number, signal?: AbortSignal) { + return this.call( + "getUpdates", + { offset, timeout: timeoutSec, allowed_updates: ["message", "callback_query"] }, + (timeoutSec + 10) * 1000, + ).catch((e) => { + if (signal?.aborted) return []; + throw e; + }); + } + + answerCallbackQuery(id: string, text?: string) { + return this.call("answerCallbackQuery", { callback_query_id: id, text }); + } + + sendMessage(chatId: number, text: string, extra: Record = {}) { + return this.call("sendMessage", { chat_id: chatId, text, parse_mode: "HTML", ...extra }); + } +} diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index ae8ff535..fb255071 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -7,8 +7,12 @@ import { createTask, findProjectFile, getProject, + createPairingCode, + getBinding, getSession, + getSetting, getTaskDetails, + unpair, listSessions, listGoals, listProjects, @@ -43,6 +47,7 @@ const USAGE = `peppa — Peppa software factory CLI peppa session attach peppa session stop peppa session resume [-p ] (new generation, claude --resume) + peppa telegram pair | status | unpair peppa watchdog [--once] [--interval ] [--stall ] KEY defaults to the project of the current directory (.peppa/project.json). @@ -198,6 +203,25 @@ async function main(): Promise { await stopSession(db, Number(args[0])); console.log("stopped"); break; + case "telegram pair": { + if (!env.TELEGRAM_BOT_TOKEN) throw new PeppaError("TELEGRAM_BOT_TOKEN is not set in .env"); + const bot = await getSetting<{ username: string }>(db, "telegram.bot"); + const code = await createPairingCode(db, env.TELEGRAM_BOT_TOKEN); + console.log(`Открой в Telegram (ссылка живёт 10 минут):\n https://t.me/${bot?.username ?? ""}?start=${code}`); + if (!bot) console.log("(бот ещё ни разу не запускался — имя подставится после первого старта peppa-bot)"); + break; + } + case "telegram status": { + const b = await getBinding(db); + const bot = await getSetting<{ username: string }>(db, "telegram.bot"); + console.log(`bot: ${bot ? `@${bot.username}` : "не запускался"}`); + console.log(b ? `привязан: chat ${b.chatId}, user ${b.userId}${b.username ? ` (@${b.username})` : ""}, с ${b.pairedAt}` : "не привязан — peppa telegram pair"); + break; + } + case "telegram unpair": + await unpair(db); + console.log("отвязано"); + break; case "watchdog": { const wopts = { intervalMs: Number(opts.interval) * 1000, diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index a86988a5..c9083e4c 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -5,3 +5,5 @@ export * from "./projects.ts"; export * from "./tasks.ts"; export * from "./sessions.ts"; export * from "./rules.ts"; +export * from "./settings.ts"; +export * from "./telegram.ts"; diff --git a/packages/core/src/sessions.ts b/packages/core/src/sessions.ts index f6f29144..2ded2323 100644 --- a/packages/core/src/sessions.ts +++ b/packages/core/src/sessions.ts @@ -135,3 +135,17 @@ function toView(r: { session: Session; projectKey: string; taskNumber: number | taskTitle: r.taskTitle, }; } + +/** + * Closes a session's open questions when it is stopped or relaunched: their answer could + * no longer reach the run that asked (a resumed run asks again if it still needs to). + */ +export async function expireSessionQuestions(db: Db, sessionId: number, reason: string): Promise { + const rows = await db + .update(questions) + .set({ answer: reason, answeredVia: "system", answeredAt: new Date(), awaitingHook: false }) + .where(and(eq(questions.sessionId, sessionId), isNull(questions.answeredAt))) + .returning(); + for (const q of rows) await notify(db, { type: "question_answered", questionId: q.id }); + return rows; +} diff --git a/packages/core/src/settings.ts b/packages/core/src/settings.ts new file mode 100644 index 00000000..f9f482b6 --- /dev/null +++ b/packages/core/src/settings.ts @@ -0,0 +1,18 @@ +import { settings, type Db } from "@peppa/db"; +import { eq } from "drizzle-orm"; + +export async function getSetting(db: Db, key: string): Promise { + const [row] = await db.select().from(settings).where(eq(settings.key, key)); + return (row?.value as T | undefined) ?? null; +} + +export async function setSetting(db: Db, key: string, value: unknown): Promise { + await db + .insert(settings) + .values({ key, value }) + .onConflictDoUpdate({ target: settings.key, set: { value, updatedAt: new Date() } }); +} + +export async function deleteSetting(db: Db, key: string): Promise { + await db.delete(settings).where(eq(settings.key, key)); +} diff --git a/packages/core/src/telegram.ts b/packages/core/src/telegram.ts new file mode 100644 index 00000000..33bb80f1 --- /dev/null +++ b/packages/core/src/telegram.ts @@ -0,0 +1,130 @@ +import { createHmac, randomBytes, timingSafeEqual } from "node:crypto"; +import { questions, telegramOutbox, telegramUpdates, type Db } from "@peppa/db"; +import { and, asc, eq, lte } from "drizzle-orm"; +import { deleteSetting, getSetting, setSetting } from "./settings.ts"; + +export type OutboxRow = typeof telegramOutbox.$inferSelect; + +const PAIRING = "telegram.pairing"; +const BINDING = "telegram.binding"; +const OFFSET = "telegram.offset"; +const PAIRING_TTL_MS = 10 * 60_000; + +export interface TelegramBinding { + chatId: number; + userId: number; + username: string | null; + pairedAt: string; +} + +// Only a keyed hash of the pairing code is stored. +const hashCode = (code: string, secret: string) => createHmac("sha256", secret).update(code).digest("hex"); + +/** One-time /start code for binding the PM's Telegram chat (valid 10 minutes). */ +export async function createPairingCode(db: Db, secret: string): Promise { + const code = randomBytes(18).toString("base64url"); + await setSetting(db, PAIRING, { hash: hashCode(code, secret), expiresAt: Date.now() + PAIRING_TTL_MS }); + return code; +} + +/** Binds the chat if `code` matches the pending pairing code. One binding at a time. */ +export async function acceptPairing( + db: Db, + secret: string, + code: string, + who: { chatId: number; userId: number; username?: string | null }, +): Promise { + const saved = await getSetting<{ hash: string; expiresAt: number }>(db, PAIRING); + if (!saved || Date.now() >= saved.expiresAt) return null; + const a = Buffer.from(hashCode(code, secret)); + const b = Buffer.from(saved.hash); + if (a.length !== b.length || !timingSafeEqual(a, b)) return null; + const binding: TelegramBinding = { + chatId: who.chatId, + userId: who.userId, + username: who.username ?? null, + pairedAt: new Date().toISOString(), + }; + await setSetting(db, BINDING, binding); + await deleteSetting(db, PAIRING); + return binding; +} + +export const getBinding = (db: Db) => getSetting(db, BINDING); + +export async function unpair(db: Db): Promise { + await deleteSetting(db, BINDING); + await db.delete(telegramOutbox).where(eq(telegramOutbox.status, "pending")); +} + +export const getOffset = async (db: Db) => (await getSetting(db, OFFSET)) ?? 0; +export const setOffset = (db: Db, offset: number) => setSetting(db, OFFSET, offset); + +/** Claims an update before acting on it. False = already taken (don't replay). */ +export async function claimUpdate(db: Db, updateId: number): Promise { + const rows = await db + .insert(telegramUpdates) + .values({ updateId, status: "dispatching" }) + .onConflictDoNothing() + .returning(); + return rows.length > 0; +} + +export async function finishUpdate(db: Db, updateId: number, status: "done" | "ignored" | "failed"): Promise { + await db.update(telegramUpdates).set({ status }).where(eq(telegramUpdates.updateId, updateId)); +} + +/** Queues a Bot API call; a no-op if `dedupeKey` was queued before. */ +export async function enqueueTelegram( + db: Db, + m: { dedupeKey: string; method: OutboxRow["method"]; params: Record; questionId?: number }, +): Promise { + const rows = await db.insert(telegramOutbox).values(m).onConflictDoNothing().returning(); + return rows.length > 0; +} + +export async function getOutbox(db: Db, dedupeKey: string): Promise { + const [row] = await db.select().from(telegramOutbox).where(eq(telegramOutbox.dedupeKey, dedupeKey)); + return row ?? null; +} + +export async function dueOutbox(db: Db, limit = 20): Promise { + return db + .select() + .from(telegramOutbox) + .where(and(eq(telegramOutbox.status, "pending"), lte(telegramOutbox.nextAttemptAt, new Date()))) + .orderBy(asc(telegramOutbox.id)) + .limit(limit); +} + +export async function markOutboxSent(db: Db, row: OutboxRow, telegramMessageId: number | null): Promise { + await db + .update(telegramOutbox) + .set({ status: "sent", sentAt: new Date(), telegramMessageId, attempts: row.attempts + 1, error: null }) + .where(eq(telegramOutbox.id, row.id)); + if (row.method === "sendMessage" && row.questionId && telegramMessageId) { + await db.update(questions).set({ telegramMessageId }).where(eq(questions.id, row.questionId)); + } +} + +const MAX_ATTEMPTS = 8; + +/** Schedules a retry (honouring Telegram's retry_after), or gives up after MAX_ATTEMPTS. */ +export async function markOutboxRetry(db: Db, row: OutboxRow, error: string, retryAfterSec?: number): Promise { + const attempts = row.attempts + 1; + const delayMs = retryAfterSec != null ? retryAfterSec * 1000 : Math.min(60_000, 1000 * 2 ** attempts); + await db + .update(telegramOutbox) + .set({ + attempts, + error, + status: attempts >= MAX_ATTEMPTS ? "failed" : "pending", + nextAttemptAt: new Date(Date.now() + delayMs), + }) + .where(eq(telegramOutbox.id, row.id)); +} + +export async function questionByTelegramMessage(db: Db, messageId: number) { + const [row] = await db.select().from(questions).where(eq(questions.telegramMessageId, messageId)); + return row ?? null; +} diff --git a/packages/db/migrations/0003_material_wild_child.sql b/packages/db/migrations/0003_material_wild_child.sql new file mode 100644 index 00000000..44c8daab --- /dev/null +++ b/packages/db/migrations/0003_material_wild_child.sql @@ -0,0 +1,29 @@ +CREATE TABLE "settings" ( + "key" text PRIMARY KEY NOT NULL, + "value" jsonb NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "telegram_outbox" ( + "id" serial PRIMARY KEY NOT NULL, + "dedupe_key" text NOT NULL, + "method" text NOT NULL, + "params" jsonb NOT NULL, + "question_id" integer, + "status" text DEFAULT 'pending' NOT NULL, + "attempts" integer DEFAULT 0 NOT NULL, + "next_attempt_at" timestamp with time zone DEFAULT now() NOT NULL, + "telegram_message_id" integer, + "error" text, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "sent_at" timestamp with time zone, + CONSTRAINT "telegram_outbox_dedupe_key_unique" UNIQUE("dedupe_key") +); +--> statement-breakpoint +CREATE TABLE "telegram_updates" ( + "update_id" integer PRIMARY KEY NOT NULL, + "status" text NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +ALTER TABLE "telegram_outbox" ADD CONSTRAINT "telegram_outbox_question_id_questions_id_fk" FOREIGN KEY ("question_id") REFERENCES "public"."questions"("id") ON DELETE set null ON UPDATE no action; \ No newline at end of file diff --git a/packages/db/migrations/meta/0003_snapshot.json b/packages/db/migrations/meta/0003_snapshot.json new file mode 100644 index 00000000..2abf1302 --- /dev/null +++ b/packages/db/migrations/meta/0003_snapshot.json @@ -0,0 +1,888 @@ +{ + "id": "6c02c03e-025e-4f66-83bc-fbb2ac391ed4", + "prevId": "93b4fb9b-40f7-4af5-9ff7-b89be76777ed", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.events": { + "name": "events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "events_project_id_projects_id_fk": { + "name": "events_project_id_projects_id_fk", + "tableFrom": "events", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_task_id_tasks_id_fk": { + "name": "events_task_id_tasks_id_fk", + "tableFrom": "events", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_session_id_sessions_id_fk": { + "name": "events_session_id_sessions_id_fk", + "tableFrom": "events", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.goals": { + "name": "goals", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "goal_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "goals_project_id_projects_id_fk": { + "name": "goals_project_id_projects_id_fk", + "tableFrom": "goals", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.projects": { + "name": "projects", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "gitea_owner": { + "name": "gitea_owner", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "gitea_repo": { + "name": "gitea_repo", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "default_branch": { + "name": "default_branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'main'" + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "next_task_number": { + "name": "next_task_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "projects_slug_unique": { + "name": "projects_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + }, + "projects_key_unique": { + "name": "projects_key_unique", + "nullsNotDistinct": false, + "columns": [ + "key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.questions": { + "name": "questions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "options": { + "name": "options", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "answer": { + "name": "answer", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "answered_via": { + "name": "answered_via", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "awaiting_hook": { + "name": "awaiting_hook", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "answered_at": { + "name": "answered_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "questions_project_id_projects_id_fk": { + "name": "questions_project_id_projects_id_fk", + "tableFrom": "questions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_task_id_tasks_id_fk": { + "name": "questions_task_id_tasks_id_fk", + "tableFrom": "questions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_session_id_sessions_id_fk": { + "name": "questions_session_id_sessions_id_fk", + "tableFrom": "questions", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sessions": { + "name": "sessions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "tmux_name": { + "name": "tmux_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'claude'" + }, + "claude_session_id": { + "name": "claude_session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "status": { + "name": "status", + "type": "session_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'starting'" + }, + "last_activity_at": { + "name": "last_activity_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "ended_at": { + "name": "ended_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "sessions_project_id_projects_id_fk": { + "name": "sessions_project_id_projects_id_fk", + "tableFrom": "sessions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sessions_task_id_tasks_id_fk": { + "name": "sessions_task_id_tasks_id_fk", + "tableFrom": "sessions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "sessions_tmux_name_unique": { + "name": "sessions_tmux_name_unique", + "nullsNotDistinct": false, + "columns": [ + "tmux_name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.settings": { + "name": "settings", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "value": { + "name": "value", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tasks": { + "name": "tasks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "number": { + "name": "number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "task_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'backlog'" + }, + "openspec_change": { + "name": "openspec_change", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tasks_project_number": { + "name": "tasks_project_number", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "tasks_project_id_projects_id_fk": { + "name": "tasks_project_id_projects_id_fk", + "tableFrom": "tasks", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tasks_goal_id_goals_id_fk": { + "name": "tasks_goal_id_goals_id_fk", + "tableFrom": "tasks", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.telegram_outbox": { + "name": "telegram_outbox", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "params": { + "name": "params", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "question_id": { + "name": "question_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "telegram_outbox_question_id_questions_id_fk": { + "name": "telegram_outbox_question_id_questions_id_fk", + "tableFrom": "telegram_outbox", + "tableTo": "questions", + "columnsFrom": [ + "question_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "telegram_outbox_dedupe_key_unique": { + "name": "telegram_outbox_dedupe_key_unique", + "nullsNotDistinct": false, + "columns": [ + "dedupe_key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.telegram_updates": { + "name": "telegram_updates", + "schema": "", + "columns": { + "update_id": { + "name": "update_id", + "type": "integer", + "primaryKey": true, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.goal_status": { + "name": "goal_status", + "schema": "public", + "values": [ + "open", + "done", + "archived" + ] + }, + "public.session_status": { + "name": "session_status", + "schema": "public", + "values": [ + "starting", + "running", + "waiting_input", + "idle", + "stalled", + "rate_limited", + "done", + "failed" + ] + }, + "public.task_status": { + "name": "task_status", + "schema": "public", + "values": [ + "backlog", + "proposing", + "awaiting_approval", + "in_progress", + "review", + "done", + "blocked" + ] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index 802fc526..5ad81311 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -22,6 +22,13 @@ "when": 1794495121487, "tag": "0002_happy_preak", "breakpoints": true + }, + { + "idx": 3, + "version": "7", + "when": 1794496377868, + "tag": "0003_material_wild_child", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index 2d75dd5e..4a8636c7 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -103,7 +103,8 @@ export const questions = pgTable("questions", { text: text("text").notNull(), options: jsonb("options").$type(), answer: text("answer"), - answeredVia: text("answered_via", { enum: ["telegram", "web", "terminal"] }), + // "system": closed by Peppa itself (session stopped/resumed), not by a person. + answeredVia: text("answered_via", { enum: ["telegram", "web", "terminal", "system"] }), telegramMessageId: integer("telegram_message_id"), // A blocking hook (PermissionRequest / AskUserQuestion) is polling for the answer, // so it must not also be typed into the terminal. @@ -123,6 +124,39 @@ export const events = pgTable("events", { createdAt: createdAt(), }); +/** Small key/value store for service state (Telegram offset, pairing, binding). */ +export const settings = pgTable("settings", { + key: text("key").primaryKey(), + value: jsonb("value").notNull(), + updatedAt: updatedAt(), +}); + +/** + * Durable Telegram outbox: every message/edit is queued here first, then delivered with + * retries. `dedupeKey` makes enqueueing idempotent (e.g. "q:42" = question 42's message). + */ +export const telegramOutbox = pgTable("telegram_outbox", { + id: serial("id").primaryKey(), + dedupeKey: text("dedupe_key").notNull().unique(), + method: text("method", { enum: ["sendMessage", "editMessageText"] }).notNull(), + params: jsonb("params").$type>().notNull(), + questionId: integer("question_id").references(() => questions.id, { onDelete: "set null" }), + status: text("status", { enum: ["pending", "sent", "failed"] }).notNull().default("pending"), + attempts: integer("attempts").notNull().default(0), + nextAttemptAt: timestamp("next_attempt_at", { withTimezone: true }).notNull().defaultNow(), + telegramMessageId: integer("telegram_message_id"), + error: text("error"), + createdAt: createdAt(), + sentAt: timestamp("sent_at", { withTimezone: true }), +}); + +/** Telegram updates already taken: recorded before acting, so a restart never replays one. */ +export const telegramUpdates = pgTable("telegram_updates", { + updateId: integer("update_id").primaryKey(), + status: text("status", { enum: ["dispatching", "done", "ignored", "failed"] }).notNull(), + createdAt: createdAt(), +}); + export const projectsRelations = relations(projects, ({ many }) => ({ goals: many(goals), tasks: many(tasks), diff --git a/packages/runner/src/sessions.ts b/packages/runner/src/sessions.ts index b8e11939..65e6473b 100644 --- a/packages/runner/src/sessions.ts +++ b/packages/runner/src/sessions.ts @@ -3,6 +3,7 @@ import { join } from "node:path"; import { answerQuestion, createSession, + expireSessionQuestions, getSession, loadSharedRules, PeppaError, @@ -59,6 +60,7 @@ export async function resumeSession(db: Db, sessionId: number, opts: StartOption if (!(await tmux.paneState(s.tmuxName)).dead) throw new PeppaError(`Session #${s.id} is still running`); await tmux.killSession(s.tmuxName); } + await expireSessionQuestions(db, s.id, "(неактуально: сессия перезапущена)"); const [project] = await db.select().from(projects).where(eq(projects.id, s.projectId)); const cwd = realpathSync(project!.workspacePath); if (s.provider === "claude") trustWorkspace(cwd); @@ -135,6 +137,7 @@ export async function sendToSession(db: Db, sessionId: number, text: string): Pr export async function stopSession(db: Db, sessionId: number): Promise { const s = await getSession(db, sessionId); if (await tmux.hasSession(s.tmuxName)) await tmux.killSession(s.tmuxName); + await expireSessionQuestions(db, s.id, "(неактуально: сессия остановлена)"); await updateSession(db, s.id, { status: "done", endedAt: new Date() }); await logSessionEvent(db, s, "stopped"); } diff --git a/packages/runner/src/tmux.ts b/packages/runner/src/tmux.ts index 06486121..28ed1ef9 100644 --- a/packages/runner/src/tmux.ts +++ b/packages/runner/src/tmux.ts @@ -20,6 +20,9 @@ export interface NewTmuxSession { export async function newSession(s: NewTmuxSession): Promise { const envArgs = Object.entries(s.env).flatMap(([k, v]) => ["-e", `${k}=${v}`]); + // Keep the server up when its last session ends: otherwise a session created while the + // previous last one is being killed can land on a server that is shutting down. + await tmux("start-server", ";", "set-option", "-s", "exit-empty", "off"); await tmux("new-session", "-d", "-s", s.name, "-c", s.cwd, "-x", "220", "-y", "50", ...envArgs, s.command); // Keep the pane after claude exits so the watchdog can read the exit status. await tmux("set-option", "-t", s.name, "remain-on-exit", "on"); diff --git a/packages/testkit/package.json b/packages/testkit/package.json index 501f7aa3..f8220cca 100644 --- a/packages/testkit/package.json +++ b/packages/testkit/package.json @@ -13,6 +13,7 @@ "@peppa/db": "workspace:*", "@peppa/runner": "workspace:*", "@peppa/shared": "workspace:*", - "drizzle-orm": "0.45.4" + "drizzle-orm": "0.45.4", + "@peppa/bot": "workspace:*" } } diff --git a/packages/testkit/src/mock-telegram.ts b/packages/testkit/src/mock-telegram.ts new file mode 100644 index 00000000..176a7bf0 --- /dev/null +++ b/packages/testkit/src/mock-telegram.ts @@ -0,0 +1,151 @@ +// Mock Telegram Bot API server for bot tests: the methods Peppa's bot uses, long-polling +// getUpdates, injectable user actions, and failure injection (429 / 5xx). +import { createServer, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; + +export interface MockTgMessage { + message_id: number; + chat_id: number; + text: string; + reply_markup?: { inline_keyboard: Array> }; + edits: number; + reply_to?: number; +} + +export interface MockTgUser { + id: number; + chatId: number; + username?: string; +} + +export class MockTelegram { + readonly token = "mock-123:TOKEN"; + readonly bot = { id: 999, username: "mock_peppa_bot", is_bot: true, first_name: "Mock Peppa" }; + readonly messages = new Map(); + readonly callbackAnswers: Array<{ id: string; text?: string }> = []; + readonly calls: Array<{ method: string; params: Record }> = []; + private updates: Array & { update_id: number }> = []; + private nextUpdateId = 1; + private nextMessageId = 100; + private waiters: Array<() => void> = []; + private failures: Array<{ method: string; code: number; retryAfter?: number }> = []; + private server: Server | null = null; + url = ""; + + async start(): Promise { + this.server = createServer((req, res) => { + let body = ""; + req.on("data", (c) => (body += c)); + req.on("end", async () => { + const method = req.url!.split("/").pop()!; + const params = body ? (JSON.parse(body) as Record) : {}; + const result = await this.handle(method, params); + res.writeHead(result.ok ? 200 : (result.error_code as number), { "Content-Type": "application/json" }); + res.end(JSON.stringify(result)); + }); + }); + await new Promise((r) => this.server!.listen(0, "127.0.0.1", r)); + this.url = `http://127.0.0.1:${(this.server.address() as AddressInfo).port}`; + return this; + } + + async stop() { + this.waiters.forEach((w) => w()); + await new Promise((r) => this.server?.close(() => r()) ?? r()); + } + + /** The next call to `method` fails with this code (429 carries retry_after). */ + failNext(method: string, code: number, retryAfter?: number) { + this.failures.push({ method, code, retryAfter }); + } + + private async handle(method: string, p: Record): Promise> { + if (method !== "getUpdates") this.calls.push({ method, params: p }); + const f = this.failures.findIndex((x) => x.method === method); + if (f >= 0) { + const { code, retryAfter } = this.failures.splice(f, 1)[0]!; + return { ok: false, error_code: code, description: code === 429 ? "Too Many Requests" : "Internal Server Error", ...(retryAfter != null ? { parameters: { retry_after: retryAfter } } : {}) }; + } + switch (method) { + case "getMe": + return { ok: true, result: this.bot }; + case "getUpdates": { + const offset = Number(p.offset ?? 0); + const timeout = Math.min(Number(p.timeout ?? 0), 1); + const pending = () => this.updates.filter((u) => u.update_id >= offset); + if (!pending().length && timeout > 0) { + await new Promise((r) => { + const t = setTimeout(r, timeout * 1000); + this.waiters.push(() => (clearTimeout(t), r())); + }); + } + return { ok: true, result: pending() }; + } + case "sendMessage": { + const m: MockTgMessage = { + message_id: this.nextMessageId++, + chat_id: Number(p.chat_id), + text: String(p.text), + reply_markup: p.reply_markup as MockTgMessage["reply_markup"], + edits: 0, + reply_to: (p.reply_parameters as { message_id?: number } | undefined)?.message_id, + }; + this.messages.set(m.message_id, m); + return { ok: true, result: { message_id: m.message_id, chat: { id: m.chat_id, type: "private" }, text: m.text } }; + } + case "editMessageText": { + const m = this.messages.get(Number(p.message_id)); + if (!m) return { ok: false, error_code: 400, description: "Bad Request: message to edit not found" }; + if (m.text === p.text) return { ok: false, error_code: 400, description: "Bad Request: message is not modified" }; + m.text = String(p.text); + m.reply_markup = p.reply_markup as MockTgMessage["reply_markup"]; + m.edits++; + return { ok: true, result: { message_id: m.message_id } }; + } + case "answerCallbackQuery": + this.callbackAnswers.push({ id: String(p.callback_query_id), text: p.text as string | undefined }); + return { ok: true, result: true }; + default: + return { ok: false, error_code: 404, description: `mock: unknown method ${method}` }; + } + } + + private push(update: Record) { + const u = { update_id: this.nextUpdateId++, ...update }; + this.updates.push(u); + this.waiters.splice(0).forEach((w) => w()); + return u.update_id; + } + + /** User sends a text message (optionally as a reply). */ + userSends(user: MockTgUser, text: string, replyTo?: number) { + return this.push({ + message: { + message_id: this.nextMessageId++, + chat: { id: user.chatId, type: "private" }, + from: { id: user.id, username: user.username, first_name: user.username ?? "user" }, + text, + ...(replyTo ? { reply_to_message: { message_id: replyTo, chat: { id: user.chatId, type: "private" } } } : {}), + }, + }); + } + + /** User presses an inline button on a bot message. */ + userClicks(user: MockTgUser, messageId: number, data: string) { + const id = `cb-${this.nextUpdateId}`; + const m = this.messages.get(messageId); + this.push({ + callback_query: { + id, + from: { id: user.id, username: user.username }, + message: { message_id: messageId, chat: { id: m?.chat_id ?? user.chatId, type: "private" }, text: m?.text }, + data, + }, + }); + return id; + } + + botMessages(chatId: number) { + return [...this.messages.values()].filter((m) => m.chat_id === chatId); + } +} diff --git a/packages/testkit/test/bot.test.ts b/packages/testkit/test/bot.test.ts new file mode 100644 index 00000000..cc217edc --- /dev/null +++ b/packages/testkit/test/bot.test.ts @@ -0,0 +1,211 @@ +// Telegram journeys: the real bot against mock-telegram, with mock agents in tmux. +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +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, tick, waitFor } from "./helpers.ts"; +import { MockTelegram, type MockTgMessage } from "../src/mock-telegram.ts"; +import type { Bot } from "@peppa/bot"; + +const { createBot } = await import("@peppa/bot"); +const { TelegramApi } = await import("@peppa/bot/telegram"); + +const tg = await new MockTelegram().start(); +const PM = { id: 501, chatId: 501, username: "pm" }; +const STRANGER = { id: 777, chatId: 777, username: "stranger" }; +let bot: Bot; + +before(async () => { + bot = createBot({ + db, + api: new TelegramApi(tg.token, tg.url), + secret: tg.token, + webUrl: "http://peppa.test", + pollTimeoutSec: 1, + outboxIntervalMs: 100, + reconcileIntervalMs: 400, + }); + await bot.start(); +}); +after(async () => { + await bot.stop(); + await tg.stop(); + await teardown(); +}); + +const isPrompt = (needle: string) => (e: { ev: string; prompt?: unknown }) => e.ev === "prompt" && String(e.prompt).includes(needle); + +/** Waits for the bot message about a question (sent to the PM's chat). */ +async function messageFor(questionId: number): Promise { + const q = await waitFor(`telegram message for question #${questionId}`, async () => { + const row = await core.getQuestion(db, questionId); + return row.telegramMessageId ? row : null; + }); + return tg.messages.get(q.telegramMessageId!)!; +} + +const lastReplyTo = (chatId: number) => tg.botMessages(chatId).at(-1); + +describe("pairing", () => { + test("only the /start code holder gets bound; strangers are ignored", async () => { + tg.userSends(STRANGER, "/status"); + tg.userSends(PM, "/start wrong-code"); + await waitFor("wrong code reply", async () => tg.botMessages(PM.chatId).some((m) => /неверный или истёк/.test(m.text))); + assert.equal(tg.botMessages(STRANGER.chatId).length, 0); + + const code = await core.createPairingCode(db, tg.token); + tg.userSends(PM, `/start ${code}`); + await waitFor("paired", async () => tg.botMessages(PM.chatId).some((m) => /Привязано/.test(m.text))); + const b = await core.getBinding(db); + assert.equal(b?.chatId, PM.chatId); + + // The code is single-use; a stranger can't take over with it. + tg.userSends(STRANGER, `/start ${code}`); + await waitFor("stranger refused", async () => tg.botMessages(STRANGER.chatId).some((m) => /неверный/.test(m.text))); + assert.equal((await core.getBinding(db))?.userId, PM.id); + + tg.userSends(PM, "/status"); + await waitFor("status", async () => tg.botMessages(PM.chatId).some((m) => /Активные сессии/.test(m.text))); + }); +}); + +describe("answering from Telegram", () => { + test("question with options: button press reaches the agent, message is closed", async () => { + const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Какую БД взять?", options: ["Postgres", "SQLite"] } }, { say: "Жду." }], [{ say: "Ок." }]] }); + const sid = await p.start(); + const q = await p.waitQuestion(sid, "question"); + const m = await messageFor(q.id); + assert.match(m.text, /Какую БД взять/); + assert.match(m.text, new RegExp(p.taskKey)); + assert.deepEqual(m.reply_markup!.inline_keyboard.map((r) => r[0]!.text), ["Postgres", "SQLite"]); + + const cb = tg.userClicks(PM, m.message_id, `q:${q.id}:o0`); + await p.waitLog("answer delivered", isPrompt(`Ответ PM на вопрос #${q.id}: Postgres`)); + await waitFor("toast", async () => tg.callbackAnswers.find((a) => a.id === cb && /Отправлено/.test(a.text ?? ""))); + await waitFor("message closed", async () => /Ответ в Telegram: Postgres<\/b>/.test(m.text) && m.reply_markup?.inline_keyboard.length === 0); + await runner.stopSession(db, sid); + }); + + test("approve button moves the task to in_progress", async () => { + const p = await project({ turns: [[{ mcp: "request_approval", args: { task: "1", summary: "План: сделать X. Риски: нет." } }], [{ say: "Делаю." }]] }); + const sid = await p.start(); + const q = await p.waitQuestion(sid, "approval"); + const m = await messageFor(q.id); + tg.userClicks(PM, m.message_id, `q:${q.id}:approve`); + await p.waitLog("approval delivered", isPrompt("одобрил proposal")); + assert.equal((await p.task()).status, "in_progress"); + await runner.stopSession(db, sid); + }); + + test("reply with a comment rejects the proposal", async () => { + const p = await project({ turns: [[{ mcp: "request_approval", args: { task: "1", summary: "План Б для проверки реплая." } }], [{ say: "Переделываю." }]] }); + const sid = await p.start(); + const q = await p.waitQuestion(sid, "approval"); + const m = await messageFor(q.id); + tg.userSends(PM, "нет, без новых зависимостей", m.message_id); + await p.waitLog("rejection delivered", isPrompt("без новых зависимостей")); + assert.equal((await p.task()).status, "proposing"); + await waitFor("ack reply", async () => lastReplyTo(PM.chatId)?.text.includes("Отправлено")); + await runner.stopSession(db, sid); + }); + + test("permission buttons answer the waiting hook", async () => { + const p = await project({ turns: [[{ permission: { tool: "Bash", input: { command: "npm publish" } } }, { say: "Опубликовал." }]] }); + const sid = await p.start(); + const q = await p.waitQuestion(sid, "permission"); + const m = await messageFor(q.id); + assert.match(m.text, /npm publish/); + tg.userClicks(PM, m.message_id, `q:${q.id}:always`); + const e = await p.waitLog("hook decision", (x) => x.ev === "permission"); + assert.equal(e.via, "hook"); + assert.equal(e.behavior, "allow"); + assert.equal(e.updatedPermissions, true); + await runner.stopSession(db, sid); + }); + + test("free-text reply to a 'session is waiting' alert is typed into the session", async () => { + const p = await project({ turns: [[{ say: "Сделал черновик. Что дальше?" }], [{ say: "Понял." }]] }); + const sid = await p.start(); + const q = await p.waitQuestion(sid, "attention"); + const m = await messageFor(q.id); + assert.match(m.text, /Что дальше/); + tg.userSends(PM, "добавь тесты\nи README", m.message_id); + const e = await p.waitLog("reply delivered", isPrompt("добавь тесты")); + assert.equal(e.prompt, "добавь тесты\nи README"); + await runner.stopSession(db, sid); + }); +}); + +describe("staleness and reliability", () => { + test("answered in the terminal: Telegram message is closed and old buttons do nothing", async () => { + const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Порт сервиса?", options: ["8080", "3000"] } }], [{ say: "Ок." }]] }); + const sid = await p.start(); + const q = await p.waitQuestion(sid, "question"); + const m = await messageFor(q.id); + await runner.sendToSession(db, sid, "порт 9000"); + await waitFor("closed as answered in terminal", async () => /Ответ в терминале/.test(m.text)); + const cb = tg.userClicks(PM, m.message_id, `q:${q.id}:o0`); + await waitFor("stale toast", async () => tg.callbackAnswers.find((a) => a.id === cb && /Уже отвечено/.test(a.text ?? ""))); + assert.equal(p.log().filter((e) => e.ev === "prompt").length, 2, "no extra prompt from the stale button"); + await runner.stopSession(db, sid); + }); + + test("an update re-delivered after a restart is not replayed", async () => { + const p = await project({ turns: [[{ say: "Жду указаний." }], [{ say: "Ок." }], [{ say: "лишний ход" }]] }); + const sid = await p.start(); + const q = await p.waitQuestion(sid, "attention"); + const m = await messageFor(q.id); + const updateId = tg.userSends(PM, "сделай раз", m.message_id); + await p.waitLog("delivered once", isPrompt("сделай раз")); + // Simulate a crash before the offset was saved: Telegram sends the update again. + await core.setOffset(db, updateId); + await new Promise((r) => setTimeout(r, 2500)); + assert.equal(p.log().filter(isPrompt("сделай раз")).length, 1); + await runner.stopSession(db, sid); + }); + + test("outbox retries after 429 (retry_after) and 5xx", async () => { + tg.failNext("sendMessage", 429, 1); + tg.failNext("sendMessage", 500); + const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Проверка ретраев?" } }], [{ say: "Ок." }]] }); + const sid = await p.start(); + const q = await p.waitQuestion(sid, "question"); + const m = await messageFor(q.id); + assert.match(m.text, /Проверка ретраев/); + const row = await core.getOutbox(db, `q:${q.id}`); + assert.ok(row && row.attempts >= 2, `expected retries, got ${row?.attempts}`); + await runner.stopSession(db, sid); + }); + + test("crash alert offers Resume; the button relaunches the session", async () => { + const p = await project({ turns: [[{ crash: 7 }]], resumeTurns: [[{ say: "Поднялся после падения." }]] }); + const sid = await p.start(); + await p.waitLog("crashed", (e) => e.ev === "exit"); + await waitFor("failed", async () => { + await tick(); + return (await p.session(sid)).status === "failed"; + }); + const q = await p.waitQuestion(sid, "attention"); + const m = await messageFor(q.id); + assert.match(m.text, /код 7/); + const resume = m.reply_markup!.inline_keyboard[0]!.find((b) => b.callback_data === `s:${sid}:resume`); + assert.ok(resume, "resume button"); + const cb = tg.userClicks(PM, m.message_id, resume.callback_data!); + await waitFor("resumed toast", async () => tg.callbackAnswers.find((a) => a.id === cb && /Перезапущено/.test(a.text ?? ""))); + await p.waitLog("gen 2 running", (e) => e.ev === "turn_end" && e.gen === "2"); + // The old alert is closed as no longer relevant. + await waitFor("old alert closed", async () => /неактуально/.test(m.text)); + await runner.stopSession(db, sid); + }); + + test("tmux killed while waiting: answer is saved, PM told the session is down", async () => { + const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Что с API?" } }]] }); + const sid = await p.start(); + const q = await p.waitQuestion(sid, "question"); + const m = await messageFor(q.id); + execFileSync("tmux", ["-L", process.env.PEPPA_TMUX_SOCKET!, "kill-session", "-t", `=${(await p.session(sid)).tmuxName}`]); + tg.userSends(PM, "используй v2", m.message_id); + await waitFor("down notice", async () => lastReplyTo(PM.chatId)?.text.includes("сессия сейчас не запущена")); + assert.equal((await core.getQuestion(db, q.id)).answer, "используй v2"); + }); +}); diff --git a/packages/testkit/test/helpers.ts b/packages/testkit/test/helpers.ts index 1db87b2a..f6d4a332 100644 --- a/packages/testkit/test/helpers.ts +++ b/packages/testkit/test/helpers.ts @@ -1,5 +1,7 @@ // Test harness for the CJM suite: isolated Postgres database, tmux server, state dir and // workspaces; mock agents instead of the real CLIs. +// Import this before anything that pulls in @peppa/runner (statically or via @peppa/bot): +// runner modules read PEPPA_TMUX_SOCKET / PEPPA_HOME when they load. import { execFileSync } from "node:child_process"; import { mkdirSync, mkdtempSync, readFileSync, existsSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -40,7 +42,7 @@ const { sql } = await import("drizzle-orm"); export const db = dbmod.createDb(); await migrate(db, { migrationsFolder: join(ROOT, "packages/db/migrations") }); -await db.execute(sql`truncate projects restart identity cascade`); +await db.execute(sql`truncate projects, settings, telegram_outbox, telegram_updates restart identity cascade`); export async function teardown() { await db.$client.end(); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index fdfba4d4..f8f4a222 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -178,12 +178,21 @@ importers: apps/bot: dependencies: + '@peppa/core': + specifier: workspace:* + version: link:../../packages/core '@peppa/db': specifier: workspace:* version: link:../../packages/db + '@peppa/runner': + specifier: workspace:* + version: link:../../packages/runner '@peppa/shared': specifier: workspace:* version: link:../../packages/shared + drizzle-orm: + specifier: 0.45.4 + version: 0.45.4(postgres@4.1.1) apps/web: dependencies: @@ -297,6 +306,9 @@ importers: '@modelcontextprotocol/sdk': specifier: 1.32.2 version: 1.32.2(zod@4.6.7) + '@peppa/bot': + specifier: workspace:* + version: link:../../apps/bot '@peppa/core': specifier: workspace:* version: link:../core diff --git a/scripts/install-bins.sh b/scripts/install-bins.sh index df71ea0d..fbf73b6b 100755 --- a/scripts/install-bins.sh +++ b/scripts/install-bins.sh @@ -1,10 +1,10 @@ #!/usr/bin/env bash -# Symlinks Peppa's CLIs (peppa, peppa-mcp, later peppa-hook) into ~/.local/bin. +# Symlinks Peppa's CLIs (packages/*/bin, apps/*/bin) into ~/.local/bin. set -euo pipefail ROOT="$(cd "$(dirname "$0")/.." && pwd)" BIN="${PEPPA_BIN_DIR:-$HOME/.local/bin}" mkdir -p "$BIN" -for f in "$ROOT"/packages/*/bin/*; do +for f in "$ROOT"/packages/*/bin/* "$ROOT"/apps/*/bin/*; do ln -sf "$f" "$BIN/$(basename "$f")" echo "linked $BIN/$(basename "$f")" done diff --git a/scripts/install-launchd.sh b/scripts/install-launchd.sh index caf542d1..ce102372 100755 --- a/scripts/install-launchd.sh +++ b/scripts/install-launchd.sh @@ -2,7 +2,8 @@ # Installs Peppa's launchd agents (start at login, restart on crash): # quest.telecom.peppa.watchdog — session watchdog under caffeinate -i (no idle sleep) # quest.telecom.peppa.web — Next.js platform on :3100 (needs `pnpm --filter @peppa/web build`) -# Usage: scripts/install-launchd.sh [watchdog] [web] (default: both) +# quest.telecom.peppa.bot — Telegram bot (TELEGRAM_BOT_TOKEN in .env) +# Usage: scripts/install-launchd.sh [watchdog] [web] [bot] (default: all) # Remove: launchctl bootout gui/$(id -u)/