import type { ContextUsage } from "@earendil-works/pi-coding-agent"; import type { ThresholdEvaluation, TriggerSnapshot, UsableContextUsage, } from "./types.ts"; export function normalizeContextUsage(usage: ContextUsage | undefined): UsableContextUsage | undefined { if (!usage) return undefined; if (usage.tokens === null || usage.percent === null) return undefined; if (!Number.isFinite(usage.tokens) || usage.tokens < 0) return undefined; if (!Number.isFinite(usage.percent) || usage.percent < 0) return undefined; if (!Number.isFinite(usage.contextWindow) || usage.contextWindow <= 0) return undefined; return { tokens: usage.tokens, contextWindow: usage.contextWindow, percent: usage.percent, }; } export function evaluateThreshold( usage: ContextUsage | undefined, thresholdPercent: number, ): ThresholdEvaluation | undefined { const normalized = normalizeContextUsage(usage); if (!normalized || normalized.percent < thresholdPercent) return undefined; const trigger: TriggerSnapshot = { tokens: normalized.tokens, contextWindow: normalized.contextWindow, percent: normalized.percent, thresholdPercent, }; return { usage: normalized, trigger }; } export function buildFailureKey(sessionId: string, usage: UsableContextUsage): string { return `${sessionId}:${usage.contextWindow}:${Math.floor(usage.tokens / 1000)}`; }