@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
182 lines • 8.09 kB
JavaScript
import { costCardAt, resolvePromptCacheLifetime } from "@earendil-works/pi-ai";
/** Custom session-entry type carrying the cache-warm continuation story. */
export const GOAL_CACHE_WARMUP_ENTRY_TYPE = "goal-cache-warmup";
/**
* Accounting fallback for a monitor continuation whose scheduled delay is no
* longer known (a held timer restored across a reload). It is deliberately NOT
* the armed delay: while a wake source is live the monitor arms the configured
* backstop below, never a timer derived from the cache-safe wait.
*/
export const GOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS = 240_000;
/**
* Default `promptCache.goalBackstopMaxSeconds` (settings-manager.ts) expressed in ms:
* the 5-minute Anthropic prompt-cache TTL minus the 30s safety buffer, so the
* periodic re-check lands inside the cache.
*/
export const GOAL_MONITOR_BACKSTOP_DEFAULT_DELAY_MS = 270_000;
/**
* Backstop used instead of the 270s default when the active model's prompt cache is best-effort
* (for example direct DeepSeek, code-yeongyu/senpi#831): there is no TTL for the re-check to land
* inside, so the goal only needs the long liveness re-check, not a cache-preservation wake.
*/
export const GOAL_MONITOR_BEST_EFFORT_BACKSTOP_SECONDS = 3570;
const GOAL_MONITOR_CONTINUATION_MIN_DELAY_MS = 1_000;
const GOAL_MONITOR_CONTINUATION_HARD_CEILING_MS = 3_600_000;
/**
* Delay of the goal-monitor backstop, in milliseconds.
*
* A live wake source normally resumes the goal when it delivers (the drain
* fire), but a wake source can be misconfigured - a filter that never matches,
* a stream that never ends - so the backstop is the floor underneath it: the
* goal re-checks at least this often instead of trusting the source for an
* hour. It is configured, never derived from the prompt-cache safe wait, through
* `promptCache.goalBackstopMaxSeconds`; a missing, non-finite, or non-positive
* setting falls back to the 270s default, and the result is clamped into
* [1s, 1h].
*/
export function resolveGoalMonitorContinuationDelayMs(goalBackstopMaxSeconds) {
const configuredMs = typeof goalBackstopMaxSeconds === "number" &&
Number.isFinite(goalBackstopMaxSeconds) &&
goalBackstopMaxSeconds > 0
? goalBackstopMaxSeconds * 1000
: GOAL_MONITOR_BACKSTOP_DEFAULT_DELAY_MS;
return Math.max(GOAL_MONITOR_CONTINUATION_MIN_DELAY_MS, Math.min(configuredMs, GOAL_MONITOR_CONTINUATION_HARD_CEILING_MS));
}
/**
* Backstop ceiling in seconds for the active model's cache lifetime. The built-in 270s default exists
* to land the re-check inside a 5-minute TTL; a best-effort cache has no TTL, so an unconfigured
* backstop becomes the long liveness re-check. The settings getter reports an unset value as the
* 270s default, so a value equal to it is treated as the default.
*/
export function resolveGoalBackstopMaxSecondsForCache(goalBackstopMaxSeconds, lifetime) {
if (lifetime?.kind !== "best-effort")
return goalBackstopMaxSeconds;
const isDefault = goalBackstopMaxSeconds === undefined || goalBackstopMaxSeconds * 1000 === GOAL_MONITOR_BACKSTOP_DEFAULT_DELAY_MS;
return isDefault ? GOAL_MONITOR_BEST_EFFORT_BACKSTOP_SECONDS : goalBackstopMaxSeconds;
}
/** Prompt-cache lifetime of the active model, from the provider's documented cache contract. */
export function resolveGoalPromptCacheLifetime(model, env) {
return model === undefined ? undefined : resolvePromptCacheLifetime(model, toProviderEnv(env));
}
export function createGoalCacheWarmScheduleData(options) {
return {
goalId: options.goalId,
delayMs: options.delayMs,
dueAtMs: options.scheduledAtMs + options.delayMs,
iteration: options.iteration,
activeMonitorCount: options.activeMonitorCount,
wakeSources: options.wakeSources,
...(options.cache !== undefined ? { cache: options.cache } : {}),
};
}
const TOKENS_PER_PRICE_UNIT = 1_000_000;
export function estimateCacheWarmMetrics(model, env, lastTurnUsage) {
const cachedTokens = clampTokens(lastTurnUsage?.cacheRead) + clampTokens(lastTurnUsage?.cacheWrite);
const lifetime = resolveGoalPromptCacheLifetime(model, env);
if (lifetime?.kind === "best-effort") {
return cachedTokens === 0 ? undefined : { cachedTokens, cacheLifetime: "best-effort" };
}
const ttlSeconds = lifetime?.kind === "ttl" ? lifetime.ttlSeconds : undefined;
if (ttlSeconds === undefined && cachedTokens === 0)
return undefined;
const rates = model === undefined ? undefined : costCardAt(model.cost, Date.now());
const estimatedSavedUsd = rates !== undefined && cachedTokens > 0
? (Math.max(0, rates.input - rates.cacheRead) * cachedTokens) / TOKENS_PER_PRICE_UNIT
: undefined;
return {
cachedTokens,
...(ttlSeconds !== undefined ? { ttlSeconds } : {}),
...(estimatedSavedUsd !== undefined ? { estimatedSavedUsd } : {}),
};
}
export function formatWarmTokenCount(tokens) {
if (tokens >= 1_000_000)
return `${trimTrailingZero((tokens / 1_000_000).toFixed(1))}M`;
if (tokens >= 1000)
return `${trimTrailingZero((tokens / 1000).toFixed(1))}K`;
return String(Math.max(0, Math.trunc(tokens)));
}
export function formatWakeDuration(ms) {
const seconds = Math.round(ms / 1000);
if (seconds < 60)
return `${seconds}s`;
const minutes = Math.floor(seconds / 60);
const restSeconds = seconds % 60;
if (minutes < 60)
return restSeconds === 0 ? `${minutes}m` : `${minutes}m ${restSeconds}s`;
const hours = Math.floor(minutes / 60);
const restMinutes = minutes % 60;
return restMinutes === 0 ? `${hours}h` : `${hours}h ${restMinutes}m`;
}
/**
* Wake timestamp shown in cache-warm notices. Rendered in the user's local
* system timezone with its short zone label (for example `GMT+9`); falls back
* to the legacy UTC shape when local timezone formatting is unavailable.
*/
export function formatWakeTimestamp(dueAtMs) {
const date = new Date(dueAtMs);
const local = formatLocalWakeTimestamp(date);
if (local !== undefined)
return local;
return `${date.toISOString().slice(0, 16).replace("T", " ")} UTC`;
}
function formatLocalWakeTimestamp(date) {
try {
const parts = new Intl.DateTimeFormat("en-CA", {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
hourCycle: "h23",
timeZoneName: "short",
}).formatToParts(date);
const read = (type) => parts.find((part) => part.type === type)?.value;
const year = read("year");
const month = read("month");
const day = read("day");
const hour = read("hour");
const minute = read("minute");
if (year === undefined ||
month === undefined ||
day === undefined ||
hour === undefined ||
minute === undefined) {
return undefined;
}
const zone = read("timeZoneName");
return `${year}-${month}-${day} ${hour}:${minute}${zone === undefined ? "" : ` ${zone}`}`;
}
catch {
return undefined;
}
}
export function formatCacheTtl(seconds) {
if (seconds % 3600 === 0)
return `${seconds / 3600}h`;
if (seconds % 60 === 0)
return `${seconds / 60}m`;
return `${seconds}s`;
}
export function formatSavedUsd(value) {
if (value < 0.0005)
return "<$0.001";
if (value < 1)
return `$${value.toFixed(3)}`;
return `$${value.toFixed(2)}`;
}
function trimTrailingZero(value) {
return value.endsWith(".0") ? value.slice(0, -2) : value;
}
function clampTokens(value) {
return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;
}
function toProviderEnv(env) {
const resolved = {};
for (const [key, value] of Object.entries(env)) {
if (value !== undefined)
resolved[key] = value;
}
return resolved;
}
//# sourceMappingURL=cache-warm.js.map