import { events, projects, questions, sessions, sessionStatus, tasks, type Db } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; import { and, desc, eq, isNull, notInArray } from "drizzle-orm"; import { PeppaError } from "./errors.ts"; import { notify } from "./notify.ts"; import type { Question, QuestionKind } from "./tasks.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; } export async function createSession( db: Db, s: { projectId: number; taskId?: number; provider?: Session["provider"] }, ): 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 } = {}): 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, ), ) .orderBy(desc(sessions.id)); 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 }) .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 } = {}, ): Promise { return db .select() .from(questions) .where( and( eq(questions.sessionId, sessionId), isNull(questions.answeredAt), opts.excludeHook ? eq(questions.awaitingHook, false) : undefined, ), ); } 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). */ export async function raiseSessionQuestion( db: Db, s: Session, kind: QuestionKind, text: string, options?: string[], awaitingHook = false, ): Promise { const [row] = await db .insert(questions) .values({ projectId: s.projectId, taskId: s.taskId, sessionId: s.id, kind, text, options, awaitingHook }) .returning(); 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 }) .from(sessions) .innerJoin(projects, eq(sessions.projectId, projects.id)) .leftJoin(tasks, eq(sessions.taskId, tasks.id)); } function toView(r: { session: Session; projectKey: string; taskNumber: number | null; taskTitle: string | null }): SessionView { return { ...r.session, projectKey: r.projectKey, taskKey: r.taskNumber != null ? formatTaskKey(r.projectKey, r.taskNumber) : null, 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; }