// Pi keeps the cache warm assuming a fixed 15% chance you return. The chance falls the longer you // are away, so the learned strategy uses the measured one. import type { Model } from "@earendil-works/pi-ai"; import type { CacheWarmingDecisionEvent, CacheWarmingDecisionEventResult, } from "@earendil-works/pi-coding-agent"; import { returnChance, type Returns } from "./returns.ts"; export type CacheModel = Pick, "cost" | "promptCache">; export const STRATEGIES = ["learned", "pi", "minutes", "off"] as const; const MAX_WARM_MINUTES = 120; export type Strategy = (typeof STRATEGIES)[number]; export interface Away { minutes: number; asked: boolean; window: number; } export interface Plan { strategy: Strategy; upTo: number; returns: Returns | undefined; } /** Undefined leaves the decision to pi: while the agent works, and when pi has no prices. */ export function warmAction( event: Pick, away: Away, plan: Plan, ): CacheWarmingDecisionEventResult | undefined { if (event.continuationProbability >= 1 || event.missCost <= 0) return undefined; switch (plan.strategy) { case "pi": return undefined; case "off": return { action: "stop" }; case "minutes": return { action: away.minutes < plan.upTo ? "warm" : "stop" }; case "learned": { const chance = returnChance(plan.returns, away.minutes, away.window, away.asked); return { action: chance * event.missCost >= event.warmCost ? "warm" : "stop" }; } } } /** At 90% of the cache's lifetime, with at least ten seconds of margin. */ export function refreshWindow(model: CacheModel | undefined): number { const retention = process.env.PI_CACHE_RETENTION === "long" ? "long" : "short"; const seconds = model?.promptCache?.[retention] ?? 300; const ms = seconds * 1000; return Math.min(ms * 0.9, ms - 10_000) / 60_000; } /** Independent of prompt size: a refresh reads from cache, a miss writes everything again. */ export function warmFor(model: CacheModel, returns: Returns | undefined, asked: boolean): number { const { cacheRead, cacheWrite } = model.cost; if (cacheWrite <= cacheRead) return 0; const enough = cacheRead / (cacheWrite - cacheRead); const window = refreshWindow(model); let minutes = window; while (minutes < MAX_WARM_MINUTES && returnChance(returns, minutes, window, asked) >= enough) minutes += window; return minutes; }