// A refresh between runs pays only if you come back before the next one, so this learns that chance // from the session files. import { createReadStream } from "node:fs"; import { readdir, stat } from "node:fs/promises"; import { join } from "node:path"; import { createInterface } from "node:readline"; /** For the first hour; the last bucket holds longer waits and runs never answered. */ const BUCKET_MINUTES = 0.5; const BUCKETS = 121; export const LEARN_DAYS = 30; /** Fewer runs still waiting make the chance after it noise. */ const MIN_WAITING = 40; export interface Returns { asked: number[]; other: number[]; } export interface Wait { minutes: number; asked: boolean; } export const MEASURED_RUNS = 1688; /** Measured on `MEASURED_RUNS` runs; used until enough is learned. */ const MEASURED: readonly (readonly [until: number, chance: number])[] = [ [9, 0.28], [13.5, 0.12], [18, 0.074], [22.5, 0.06], [31.5, 0.035], ]; const MEASURED_LATER = 0.015; export function emptyReturns(): Returns { return { asked: zeros(), other: zeros() }; } export function isReturns(value: Partial): value is Returns { return value.asked?.length === BUCKETS && value.other?.length === BUCKETS; } export function addWait(returns: Returns, wait: Wait): void { const bucket = Math.min(BUCKETS - 1, Math.floor(wait.minutes / BUCKET_MINUTES)); (wait.asked ? returns.asked : returns.other)[bucket]! += 1; } export function runsIn(returns: Returns): number { return sum(returns.asked) + sum(returns.other); } /** Given none came before. */ export function returnChance( returns: Returns | undefined, minutes: number, window: number, asked: boolean, ): number { if (returns !== undefined) { const own = chanceIn(asked ? returns.asked : returns.other, minutes, window); if (own !== undefined) return own; const both = returns.asked.map((count, bucket) => count + returns.other[bucket]!); const all = chanceIn(both, minutes, window); if (all !== undefined) return all; } return MEASURED.find(([until]) => minutes < until)?.[1] ?? MEASURED_LATER; } function chanceIn(counts: readonly number[], minutes: number, window: number): number | undefined { const from = Math.min(BUCKETS - 1, Math.floor(minutes / BUCKET_MINUTES)); const to = Math.min(BUCKETS - 1, Math.floor((minutes + window) / BUCKET_MINUTES)); const waiting = sum(counts.slice(from)); if (waiting < MIN_WAITING) return undefined; return sum(counts.slice(from, to)) / waiting; } /** A run ends on an assistant message without tool calls; a run nothing followed waited forever. */ export function waitsIn(file: string, since: number): Wait[] { const requests: AgentRequest[] = []; for (const line of file.split("\n")) addRequest(requests, line, since); return waitsAfter(requests); } /** Line by line, so a long session never sits in memory as one string. */ async function waitsInFile(path: string, since: number): Promise { const requests: AgentRequest[] = []; try { const lines = createInterface({ input: createReadStream(path, "utf8"), crlfDelay: Infinity }); for await (const line of lines) addRequest(requests, line, since); } catch { return []; } return waitsAfter(requests); } type AgentRequest = { timestamp: number; ends: boolean; asked: boolean }; function addRequest(requests: AgentRequest[], line: string, since: number): void { // Most lines are tool output; skip them without parsing. if (!line.includes('"role":"assistant"')) return; const message = assistantOf(line); if (message !== undefined && message.timestamp >= since) requests.push(message); } function waitsAfter(requests: readonly AgentRequest[]): Wait[] { return requests.flatMap((request, index) => { if (!request.ends) return []; const next = requests[index + 1]; const minutes = next === undefined ? Infinity : (next.timestamp - request.timestamp) / 60_000; return [{ minutes, asked: request.asked }]; }); } interface Part { type?: string; text?: string; } interface Line { type?: string; message?: { role?: string; timestamp?: unknown; usage?: unknown; content?: unknown }; } function assistantOf(line: string): AgentRequest | undefined { const message = parse(line)?.message; if (message?.role !== "assistant" || message.usage === undefined) return undefined; if (typeof message.timestamp !== "number") return undefined; const content: Part[] = Array.isArray(message.content) ? message.content : []; return { timestamp: message.timestamp, ends: !content.some((part) => part.type === "toolCall"), asked: endsOnQuestion(content), }; } function parse(line: string): Line | undefined { try { const entry = JSON.parse(line) as Line; return entry.type === "message" ? entry : undefined; } catch { return undefined; } } export function endsOnQuestion(content: readonly Part[]): boolean { const texts = content .filter((part) => part.type === "text") .map((part) => part.text?.trim() ?? ""); return texts.findLast((text) => text !== "")?.endsWith("?") ?? false; } /** One file and one line at a time, so no month of sessions is ever in memory. */ export async function learnReturns(root: string, now: number): Promise { const since = now - LEARN_DAYS * 86_400_000; const returns = emptyReturns(); for (const folder of await readdir(root).catch(() => [])) { const dir = join(root, folder); // oxlint-disable-next-line no-await-in-loop -- one file at a time for (const name of await readdir(dir).catch(() => [])) { if (!name.endsWith(".jsonl")) continue; const path = join(dir, name); // oxlint-disable-next-line no-await-in-loop -- as above const changed = await stat(path).then( (info) => info.mtimeMs, () => 0, ); if (changed < since) continue; // oxlint-disable-next-line no-await-in-loop -- as above for (const wait of await waitsInFile(path, since)) addWait(returns, wait); } } return returns; } function zeros(): number[] { return Array.from({ length: BUCKETS }, () => 0); } function sum(values: readonly number[]): number { return values.reduce((total, value) => total + value, 0); }