peppa/packages/core/src/sessions.ts
Асель 2ef05fac12 PEP-107: failover across providers, pool view, last-subscription warning, superadmin loans
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 15:40:06 +05:00

224 lines
9.2 KiB
TypeScript

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 { 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;
/** 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<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; projectId?: 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,
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<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" | "subscriptionId" | "rotateReason" | "name" | "workspacePath" | "taskId" | "watchState" | "hostId" | "container" | "provider">>,
): 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, ...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<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, taskStatus: tasks.status, subscriptionName: subscriptions.name, agentName: agents.name,
switches: sql<number>`(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<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;
}