peppa/packages/core/src/sessions.ts
Асель 8dc82859c7 PEP-36 stage 1: run Peppa with Node 26 type stripping instead of tsx
- tsconfig: erasableSyntaxOnly + verbatimModuleSyntax; parameter properties
  rewritten (BugsinkError, GiteaError, GiteaClient, OAuthError, TelegramError,
  TelegramApi, MockGitea)
- bin wrappers (peppa, peppa-mcp, peppa-hook, peppa-bot, testkit mocks,
  peppa-dev): `node --import scripts/lib/require-node.mjs` (clear error on
  Node < 26, PEPPA_NODE overrides the binary); package scripts and tests on
  `node` / `node --test`; tsx removed
- install-launchd.sh pins PEPPA_NODE (checked absolute path) in the plists
- fix a race the faster hooks exposed: the prompt hook answered every pending
  question, including a PM question raised after Peppa itself pasted text
  into the terminal; sendToSession now logs `input_sent` and the hook only
  answers questions older than that input
- change pep-36-lightweight-stack: stage 1 done, hook start numbers

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 16:51:22 +05:00

191 lines
7.2 KiB
TypeScript

import { events, projects, questions, sessions, sessionStatus, tasks, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { and, desc, eq, inArray, isNull, lte, notInArray } from "drizzle-orm";
import { PeppaError } from "./errors.ts";
import { notify } from "./notify.ts";
import type { Question, QuestionKind } from "./tasks.ts";
import { userProjectIds } from "./users.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<Session> {
// 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<SessionView> {
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<SessionView[]> {
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);
}
/** 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<string, SessionStatus[]>;
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<SessionView[]> {
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<Pick<Session, "status" | "tmuxName" | "conversationId" | "generation" | "autoNudges" | "lastActivityAt" | "endedAt" | "resumeAt" | "limitProbeMin" | "limitResumes" | "limitResumesDay" | "limitResumedAt">>,
): Promise<Session> {
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; createdBefore?: Date } = {},
): Promise<Question[]> {
return 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,
),
);
}
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<Date | 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?.createdAt ?? null;
}
export async function getQuestion(db: Db, id: number): Promise<Question> {
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<Question | null> {
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<Question> {
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<Question[]> {
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;
}