import { agents, events, projects, questions, runnerHosts, sessions, sessionStatus, subscriptions, tasks, type Db } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; import { and, desc, eq, inArray, isNull, lte, notInArray, sql } from "drizzle-orm"; import { PeppaError } from "./errors.ts"; import { notify } from "./notify.ts"; import { actorColumns } from "./actor.ts"; import type { Question, QuestionKind } from "./tasks.ts"; import { defaultMessageType, type MessageType } from "./questions.ts"; import { userProjectIds } from "./users.ts"; import { setMessageDetails } from "./message-details.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]; export const FINISHED_SESSION_STATUSES: SessionStatus[] = ["done", "failed"]; export interface SessionView extends Session { projectKey: string; taskKey: string | null; taskTitle: string | null; /** PEP-10: status of the runner's current story. */ taskStatus: string | null; /** PEP-67: name of the subscription the session runs on. */ subscriptionName: string | null; /** PEP-39: how many times the session moved to another subscription (events). */ subscriptionSwitches: number; /** PEP-40: where the runner's tmux lives (null = Peppa's own machine). */ host: SessionHost | null; /** PEP-75: name of the persona working in the runner. */ agentName: string | null; } /** PEP-40: how to reach a runner's host (see runner/exec.ts). */ export interface SessionHost { id: number; name: string; sshTarget: string; sshPort: number; workdir: string; peppaUrl: string | null; } export async function createSession( db: Db, s: { projectId: number; taskId?: number | null; provider?: Session["provider"]; subscriptionId?: number | null; name?: string | null }, ): Promise { // tmux name needs the id, so insert with a unique placeholder first. const [row] = await db .insert(sessions) .values({ ...s, tmuxName: `pending-${crypto.randomUUID()}` }) .returning(); return row!; } export async function getSession(db: Db, id: number): Promise { const [row] = await sessionQuery(db).where(eq(sessions.id, id)); if (!row) throw new PeppaError(`Session #${id} not found`); return toView(row); } export async function listSessions(db: Db, opts: { active?: boolean; taskId?: number; projectId?: number } = {}): Promise { const rows = await sessionQuery(db) .where( and( opts.active ? notInArray(sessions.status, FINISHED_SESSION_STATUSES) : undefined, opts.taskId != null ? eq(sessions.taskId, opts.taskId) : undefined, opts.projectId != null ? eq(sessions.projectId, opts.projectId) : undefined, ), ) .orderBy(desc(sessions.id)); return rows.map(toView); } /** Runner filters on the web «Раннеры» page (PEP-61): session statuses per filter. */ export const RUNNER_FILTERS = { waiting: ["waiting_input"], working: ["starting", "running", "idle", "stalled", "rate_limited"], stopped: ["failed"], finished: ["done"], } satisfies Record; export type RunnerFilter = keyof typeof RUNNER_FILTERS; /** Runners (sessions) of the projects the user owns or is a member of, newest first. */ export async function listUserSessions(db: Db, userId: number, opts: { filter?: RunnerFilter; limit?: number } = {}): Promise { const ids = await userProjectIds(db, userId); if (!ids.length) return []; const rows = await sessionQuery(db) .where(and(inArray(sessions.projectId, ids), opts.filter ? inArray(sessions.status, RUNNER_FILTERS[opts.filter]) : undefined)) .orderBy(desc(sessions.id)) .limit(opts.limit ?? 200); return rows.map(toView); } export async function updateSession( db: Db, id: number, patch: Partial>, ): Promise { const [row] = await db.update(sessions).set(patch).where(eq(sessions.id, id)).returning(); if (!row) throw new PeppaError(`Session #${id} not found`); if (patch.status) await notify(db, { type: "session_updated", sessionId: id }); return row; } export async function logSessionEvent(db: Db, s: Session, type: string, payload?: unknown) { const [row] = await db .insert(events) .values({ projectId: s.projectId, taskId: s.taskId, sessionId: s.id, type, payload, ...actorColumns(s.id) }) .returning(); return row!; } /** Unanswered questions raised by a session (ask_pm, approvals, hook/watchdog alerts). */ export async function pendingSessionQuestions( db: Db, sessionId: number, opts: { excludeHook?: boolean; createdBefore?: Date } = {}, ): Promise { const rows = await db .select() .from(questions) .where( and( eq(questions.sessionId, sessionId), isNull(questions.answeredAt), opts.excludeHook ? eq(questions.awaitingHook, false) : undefined, opts.createdBefore ? lte(questions.createdAt, opts.createdBefore) : undefined, ), ); if (!opts.createdBefore || !rows.length) return rows; // PEP-151: a message raised again counts from the time it came again, not from its first time. const states = await questionStates(db, rows.map((r) => r.id)); return rows.filter((r) => (states.get(r.id)?.repeats ? (states.get(r.id)!.updatedAt ?? 0) : 0) <= opts.createdBefore!.getTime()); } const sameText = (a: string, b: string) => a.replace(/\s+/g, " ").trim() === b.replace(/\s+/g, " ").trim(); /** * When Peppa itself typed `prompt` into the session's terminal (an `input_sent` event), * the time it did so; null if the prompt came from a person. */ export async function peppaInputSentAt(db: Db, sessionId: number, prompt: string): Promise { return (await peppaInput(db, sessionId, prompt))?.at ?? null; } /** * PEP-154: the same, with who wrote the text: `person` — a person's message Peppa only carried * to the terminal («Написать агенту», `peppa session send`); otherwise Peppa's own words * (a red check, «лимит сброшен») — those are nobody's answer. */ export async function peppaInput(db: Db, sessionId: number, prompt: string): Promise<{ at: Date; person: boolean } | null> { const sent = await db .select() .from(events) .where(and(eq(events.sessionId, sessionId), eq(events.type, "input_sent"))) .orderBy(desc(events.id)) .limit(10); const hit = sent.find((e) => sameText(String((e.payload as { text?: string } | null)?.text ?? ""), prompt)); return hit ? { at: hit.createdAt, person: !!(hit.payload as { person?: boolean } | null)?.person } : null; } export async function getQuestion(db: Db, id: number): Promise { const [row] = await db.select().from(questions).where(eq(questions.id, id)); if (!row) throw new PeppaError(`Question #${id} not found`); return row; } /** * A blocking hook gives up waiting: from now on the answer goes to the terminal. * Returns the question if it got answered in the meantime (the race is settled by * Postgres row locking against answerQuestion). */ export async function releaseHookQuestion(db: Db, id: number): Promise { const [released] = await db .update(questions) .set({ awaitingHook: false }) .where(and(eq(questions.id, id), isNull(questions.answeredAt))) .returning(); return released ? null : getQuestion(db, id); } /** * Raises a session-level alert for the PM (permission prompt, idle, stall, crash). * PEP-151: the same state of the story again is not a second message — the earlier one is * refreshed and returned (`o.topic` — see MessageTopic). */ export async function raiseSessionQuestion( db: Db, s: Session, kind: QuestionKind, text: string, options?: string[], awaitingHook = false, { msgType, details, ...o }: { topic?: MessageTopic; head?: string | null; /** PEP-149: default — by kind (core/questions.ts). */ msgType?: MessageType | null; /** PEP-152: for «Подробнее». */ details?: string | null } = {}, ): Promise { // 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) .values({ projectId: s.projectId, taskId: s.taskId, sessionId: s.id, kind, text, options, awaitingHook, msgType: msgType ?? defaultMessageType({ kind, options }) }) .returning(); return created!; }); if (details !== undefined) await setMessageDetails(db, row.id, details); await keepQuestionDetails(db, row.id, original, text).catch(() => {}); await notify(db, { type: "question", questionId: row.id }); return row; } function sessionQuery(db: Db) { return db .select({ session: sessions, projectKey: projects.key, taskNumber: tasks.number, taskTitle: tasks.title, taskStatus: tasks.status, subscriptionName: subscriptions.name, agentName: agents.name, switches: sql`(select count(*) from events e where e.session_id = ${sessions.id} and e.type = 'subscription_switched')`, host: { id: runnerHosts.id, name: runnerHosts.name, sshTarget: runnerHosts.sshTarget, sshPort: runnerHosts.sshPort, workdir: runnerHosts.workdir, peppaUrl: runnerHosts.peppaUrl }, }) .from(sessions) .innerJoin(projects, eq(sessions.projectId, projects.id)) .leftJoin(tasks, eq(sessions.taskId, tasks.id)) .leftJoin(subscriptions, eq(sessions.subscriptionId, subscriptions.id)) .leftJoin(runnerHosts, eq(sessions.hostId, runnerHosts.id)) .leftJoin(agents, eq(sessions.agentId, agents.id)); } function toView(r: { session: Session; projectKey: string; taskNumber: number | null; taskTitle: string | null; taskStatus: string | null; subscriptionName: string | null; agentName: string | null; switches: number; host: SessionHost | { id: null } | null }): SessionView { return { ...r.session, projectKey: r.projectKey, taskKey: r.taskNumber != null ? formatTaskKey(r.projectKey, r.taskNumber) : null, taskTitle: r.taskTitle, taskStatus: r.taskStatus, subscriptionName: r.subscriptionName, agentName: r.agentName, subscriptionSwitches: Number(r.switches ?? 0), host: r.host && r.host.id != null ? (r.host as SessionHost) : null, }; } /** * 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; }