115 lines
5.5 KiB
TypeScript
115 lines
5.5 KiB
TypeScript
// PEP-299: an agent whose story waits for a person («Ревью», no question of its own) holds a place
|
|
// on the subscription doing nothing. When another story of the set waits «В очереди» and the
|
|
// set is full, the agent silent the longest (past `reviewReleaseMin`) is stopped — one per set per
|
|
// pass. The «готово» card with «Принять» stays open, the owner hears nothing; when the story goes
|
|
// back to work («Поправить», a rebase, the queue), `resumeReleased` continues the same conversation.
|
|
import {
|
|
capacityQueue,
|
|
deleteSetting,
|
|
finishRunnerTask,
|
|
getSession,
|
|
getSetting,
|
|
getSubscription,
|
|
isUsable,
|
|
listSessions,
|
|
liveBySubscription,
|
|
logSessionEvent,
|
|
pendingSessionQuestions,
|
|
poolHasRoom,
|
|
queuedItems,
|
|
setSetting,
|
|
subscriptionCapacities,
|
|
updateSession,
|
|
type SessionView,
|
|
type TaskRef,
|
|
} from "@peppa/core";
|
|
import { subscriptionPoolMembers, type Db } from "@peppa/db";
|
|
import type { WatchdogSettings } from "./recovery.ts";
|
|
import { killRunner, resumeSession } from "./sessions.ts";
|
|
|
|
const MARK = "review.released:";
|
|
const markKey = (taskId: number) => `${MARK}${taskId}`;
|
|
interface Released {
|
|
sessionId: number;
|
|
at: number;
|
|
}
|
|
|
|
/** True when the runner is a candidate: story in review, turn over, silent past the threshold, nothing asked. */
|
|
async function releasable(db: Db, s: SessionView, cutoff: number): Promise<boolean> {
|
|
if (s.taskStatus !== "review" || !s.taskId || s.subscriptionId == null || s.rotateReason) return false;
|
|
if (s.status !== "waiting_input" && s.status !== "idle") return false;
|
|
if (!s.lastActivityAt || s.lastActivityAt.getTime() > cutoff) return false;
|
|
// The «готово» card (attention) is a question to the owner about acceptance, not the agent's own.
|
|
if ((await pendingSessionQuestions(db, s.id)).some((q) => q.kind !== "attention")) return false;
|
|
// A queue-mode runner with more stories to take is not idle.
|
|
if ((await queuedItems(db, { sessionIds: [s.id] })).some((q) => q.taskId !== s.taskId)) return false;
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* Stops the runner without closing its questions (`stopSession` would answer the «готово» card
|
|
* and take «Принять» away) and marks the story so its next start continues the conversation.
|
|
*/
|
|
export async function releaseReviewSession(db: Db, s: SessionView, now = new Date()): Promise<void> {
|
|
await killRunner(s);
|
|
await updateSession(db, s.id, { status: "done", endedAt: now });
|
|
await finishRunnerTask(db, s.id);
|
|
await setSetting(db, markKey(s.taskId!), { sessionId: s.id, at: now.getTime() } satisfies Released);
|
|
const idleMin = s.lastActivityAt ? Math.round((now.getTime() - s.lastActivityAt.getTime()) / 60_000) : null;
|
|
await logSessionEvent(db, s, "review_released", { idleMin });
|
|
}
|
|
|
|
export async function reviewReleaseTick(db: Db, o: { now: Date; cfg: WatchdogSettings; log?: (m: string) => void }): Promise<number> {
|
|
if (!(o.cfg.reviewReleaseMin > 0)) return 0;
|
|
const queue = await capacityQueue(db);
|
|
if (!queue.length) return 0;
|
|
// The first waiting story of each set; a set where it has room waits for something else (repo limit).
|
|
const firstBySet = new Map<number, number>();
|
|
for (const q of queue) if (q.poolId != null && !firstBySet.has(q.poolId)) firstBySet.set(q.poolId, q.projectId);
|
|
if (!firstBySet.size) return 0;
|
|
const members = await db.select().from(subscriptionPoolMembers);
|
|
const live = await listSessions(db, { active: true });
|
|
const cutoff = o.now.getTime() - o.cfg.reviewReleaseMin * 60_000;
|
|
let released = 0;
|
|
for (const [poolId, projectId] of firstBySet) {
|
|
if (await poolHasRoom(db, projectId, o.now)) continue;
|
|
const subs = new Set(members.filter((m) => m.poolId === poolId).map((m) => m.subscriptionId));
|
|
const candidates: SessionView[] = [];
|
|
for (const s of live) if (s.subscriptionId != null && subs.has(s.subscriptionId) && (await releasable(db, s, cutoff))) candidates.push(s);
|
|
const s = candidates.sort((a, b) => a.lastActivityAt!.getTime() - b.lastActivityAt!.getTime() || a.id - b.id)[0];
|
|
if (!s) continue;
|
|
await releaseReviewSession(db, s, o.now);
|
|
// Gone from the live list: another set sharing the subscription won't pick it again.
|
|
live.splice(live.indexOf(s), 1);
|
|
released++;
|
|
o.log?.(`#${s.id} ${s.taskKey ?? ""}: story in review, silent ${Math.round((o.now.getTime() - s.lastActivityAt!.getTime()) / 60_000)} min — gave its place to the queue`);
|
|
}
|
|
return released;
|
|
}
|
|
|
|
export async function clearReviewRelease(db: Db, taskId: number): Promise<void> {
|
|
await deleteSetting(db, markKey(taskId));
|
|
}
|
|
|
|
/**
|
|
* The story goes back to work: its released runner continues the same conversation if its
|
|
* subscription has room (`resumeSession` itself does not check capacity). Null — start as usual.
|
|
*/
|
|
export async function resumeReleased(db: Db, ref: TaskRef, prompt?: string): Promise<number | null> {
|
|
const mark = await getSetting<Released>(db, markKey(ref.task.id));
|
|
if (!mark) return null;
|
|
const s = await getSession(db, mark.sessionId).catch(() => null);
|
|
if (!s || s.taskId !== ref.task.id || s.status !== "done") {
|
|
await clearReviewRelease(db, ref.task.id);
|
|
return null;
|
|
}
|
|
if (s.subscriptionId != null) {
|
|
const sub = await getSubscription(db, s.subscriptionId).catch(() => null);
|
|
if (!sub || !isUsable(sub)) return null;
|
|
const cap = (await subscriptionCapacities(db))(sub.id);
|
|
if (((await liveBySubscription(db)).get(sub.id) ?? 0) >= cap) return null;
|
|
}
|
|
await clearReviewRelease(db, ref.task.id);
|
|
return (await resumeSession(db, s.id, { prompt })).id;
|
|
}
|