UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

304 lines • 13.3 kB
import { costCardAt, resolvePromptCacheTtlSeconds, supportsAnthropicCacheWarming, warmPromptCache, } from "@earendil-works/pi-ai"; import { convertToLlm, filterContextExcludedMessages } from "../../../messages.js"; import { noticeEntryRenderer } from "../../notice/index.js"; import { formatWarmTokenCount } from "../goal/cache-warm.js"; import { createSessionPrewarm } from "./session-prewarm.js"; import { createStartupActivityGate } from "./startup-activity-gate.js"; export const CACHE_KEEPALIVE_ENTRY_TYPE = "cache-keepalive"; export const CACHE_WARM_PING_EVENT = "cache_warm_ping"; export const renderCacheKeepAliveEntry = noticeEntryRenderer((entry) => { const data = entry.data; if (data?.phase !== "ping") return undefined; const refreshed = data.cacheRead + data.cacheWrite; return { title: `⚡ Warm ping #${data.iteration} · ~${formatWarmTokenCount(refreshed)} tokens refreshed · ${formatUsd(data.estimatedCostUsd)}`, why: "Refreshed the active Anthropic prompt cache while the session was idle.", expandedLine: `cache read ${data.cacheRead} · cache write ${data.cacheWrite} · session total ${formatUsd(data.cumulativeEstimatedUsd)}`, }; }); export function createCacheKeepAliveExtension(dependencies = {}) { const warm = dependencies.warmPromptCache ?? warmPromptCache; return (pi) => { const prewarm = createSessionPrewarm(pi, { warm, isPrewarmModel: dependencies.isPromptCachePrewarmModel }); const startupActivity = createStartupActivityGate(); let ctx; let timer; let inFlight = false; let generation = 0; let active = false; let parked = false; let attempts = 0; let cumulativeEstimatedUsd = 0; let lastCompletedAtMs; let lastMessages = []; let lastUsage; pi.registerEntryRenderer(CACHE_KEEPALIVE_ENTRY_TYPE, renderCacheKeepAliveEntry); // No goal-timer coupling: an armed goal continuation timer issues no // provider request until it fires, and `promptCache.goalBackstopMaxSeconds` // may place that past the TTL, so it cannot be relied on to refresh the // prompt cache on this loop's behalf. function append(data) { pi.appendEntry(CACHE_KEEPALIVE_ENTRY_TYPE, data); } let armOnSettle = false; function stop(reason, forceEntry = false) { const shouldAppend = active || inFlight || timer !== undefined || forceEntry; generation += 1; if (timer !== undefined) clearTimeout(timer); timer = undefined; active = false; if (shouldAppend) { append({ phase: "stopped", iterations: attempts, stopReason: reason, cumulativeEstimatedUsd, }); } } function arm() { if (startupActivity.waiting || parked || timer !== undefined || inFlight) return; const current = ctx; const settings = current?.getPromptCacheKeepAliveSettings?.(); if (!settings?.enabled || current?.model === undefined || lastCompletedAtMs === undefined) return; if (!isWarmSupportedModel(current.model)) return; if (!current.isIdle()) { stop("agent-busy"); return; } if (current.hasPendingMessages()) { stop("pending-messages"); return; } const safeWaitSeconds = current.getPromptCacheSafeWaitSeconds?.(); if (safeWaitSeconds === undefined || !Number.isFinite(safeWaitSeconds)) return; if (attempts >= Math.max(0, settings.maxRequestsPerSession)) { stop("max-requests", true); return; } const projectedUsd = projectedPingCost(current.model, lastUsage); if (cumulativeEstimatedUsd + projectedUsd > Math.max(0, settings.maxCostUsdPerSession)) { stop("cost-cap", true); return; } if (!active) { active = true; append({ phase: "started" }); } const intervalMs = Math.max(0, safeWaitSeconds - Math.max(0, settings.marginSeconds)) * 1000; const delayMs = Math.max(0, lastCompletedAtMs + intervalMs - Date.now()); const scheduledGeneration = generation; timer = setTimeout(() => { timer = undefined; void ping(scheduledGeneration); }, delayMs); } async function ping(scheduledGeneration) { if (scheduledGeneration !== generation) return; const current = ctx; const settings = current?.getPromptCacheKeepAliveSettings?.(); if (current === undefined || settings?.enabled !== true || current.model === undefined || !isWarmSupportedModel(current.model) || !current.isIdle() || current.hasPendingMessages() || attempts >= Math.max(0, settings.maxRequestsPerSession) || cumulativeEstimatedUsd + projectedPingCost(current.model, lastUsage) > Math.max(0, settings.maxCostUsdPerSession)) { arm(); return; } inFlight = true; attempts += 1; const iteration = attempts; const pingGeneration = generation; try { const preparation = await current.prepareProviderRequest?.(lastMessages, { allowServerSearch: true }); if (pingGeneration !== generation) { inFlight = false; arm(); return; } const preparedMessages = preparation?.messages ?? lastMessages; const prefix = await current.getPromptCachePrefixRequest?.(); const activeToolNames = new Set(pi.getActiveTools()); const tools = prefix?.status === "ready" ? (prefix.request.context.tools ?? []) : pi .getAllTools() .filter((tool) => activeToolNames.has(tool.name)) .map(({ name, description, parameters }) => ({ name, description, parameters })); const auth = await current.modelRegistry.getApiKeyAndHeaders(current.model, { sessionId: current.sessionManager.getSessionId(), }); if (pingGeneration !== generation) { inFlight = false; arm(); return; } if (!auth.ok) throw new Error(auth.error); const authHeaders = auth.headers ?? {}; const headers = preparation ? await preparation.transformHeaders(authHeaders) : authHeaders; const systemPrompt = current.getSystemPrompt(); // The ping splits the system prompt where the real request does (senpi#4447, senpi#2389). const stablePrefix = current.getSystemPromptStablePrefix?.(); const result = await warm(current.model, { systemPrompt, ...(stablePrefix !== undefined && systemPrompt.startsWith(stablePrefix) ? { systemPromptStablePrefix: stablePrefix } : {}), messages: convertToLlm(filterContextExcludedMessages(preparedMessages)), ...(tools.length > 0 ? { tools } : {}), }, { apiKey: auth.apiKey, headers, sessionId: current.sessionManager.getSessionId(), cacheRetention: current.model.cacheRetention, onPayload: preparation ? async (payload) => await preparation.transformPayload(payload) : undefined, }); if (pingGeneration !== generation) { inFlight = false; arm(); return; } if (!result.supported) { inFlight = false; stop("unsupported-model"); return; } const estimatedCostUsd = actualPingCost(current.model, result.usage); cumulativeEstimatedUsd += estimatedCostUsd; lastCompletedAtMs = Date.now(); const cachedTokens = result.usage.cacheRead + result.usage.cacheWrite; const ttlSeconds = resolvePromptCacheTtlSeconds(current.model) ?? 0; pi.events?.emit(CACHE_WARM_PING_EVENT, { iteration, cachedTokens, ttlSeconds, estimatedCostUsd }); append({ phase: "ping", iteration, cacheRead: result.usage.cacheRead, cacheWrite: result.usage.cacheWrite, estimatedCostUsd, cumulativeEstimatedUsd, }); inFlight = false; arm(); } catch { inFlight = false; if (pingGeneration === generation) stop("provider-error"); else arm(); } } pi.on("session_start", (event, nextCtx) => { if (event.sizesOnly) return; prewarm.start(nextCtx); stop("session-restart"); ctx = nextCtx; attempts = 0; cumulativeEstimatedUsd = 0; lastMessages = nextCtx.sessionManager.buildSessionContext().messages; const usage = lastAssistantUsage(lastMessages); lastUsage = usage; lastCompletedAtMs = lastAssistantTimestamp(lastMessages); startupActivity.start(nextCtx, arm); }); pi.on("agent_end", (event, nextCtx) => { ctx = nextCtx; const usage = lastAssistantUsage(event.messages); if (usage?.stopReason === "error") { armOnSettle = false; stop("provider-error"); return; } lastMessages = [...event.messages]; startupActivity.release(); lastUsage = usage; lastCompletedAtMs = Date.now(); armOnSettle = true; arm(); }); pi.on("agent_settled", (_event, nextCtx) => { ctx = nextCtx; if (!armOnSettle) return; armOnSettle = false; arm(); }); pi.on("model_select", (_event, nextCtx) => { ctx = nextCtx; stop("model-changed"); arm(); }); pi.on("session_parked", () => { parked = true; stop("session-parked"); }); pi.on("session_resumed", (_event, nextCtx) => { parked = false; ctx = nextCtx; arm(); }); pi.on("agent_start", () => stop("agent-busy")); pi.on("input", () => stop("user-input")); pi.on("session_shutdown", () => { stop("session-dispose"); startupActivity.release(); prewarm.cancel(); ctx = undefined; }); }; } function isWarmSupportedModel(model) { return model.api === "anthropic-messages" && supportsAnthropicCacheWarming(model); } function lastAssistantUsage(messages) { for (let index = messages.length - 1; index >= 0; index -= 1) { const message = messages[index]; if (message.role !== "assistant") continue; return { input: finiteTokens(message.usage.input), cacheRead: finiteTokens(message.usage.cacheRead), cacheWrite: finiteTokens(message.usage.cacheWrite), stopReason: message.stopReason, }; } return undefined; } function lastAssistantTimestamp(messages) { for (let index = messages.length - 1; index >= 0; index -= 1) { const message = messages[index]; if (message.role === "assistant" && Number.isFinite(message.timestamp)) return message.timestamp; } return undefined; } function projectedPingCost(model, usage) { const promptTokens = (usage?.input ?? 0) + (usage?.cacheRead ?? 0) + (usage?.cacheWrite ?? 0); const rates = costCardAt(model.cost, Date.now()); return (promptTokens * Math.max(rates.cacheRead, rates.cacheWrite)) / 1_000_000; } function actualPingCost(model, usage) { const rates = costCardAt(model.cost, Date.now()); return ((usage.cacheRead * rates.cacheRead + usage.cacheWrite * rates.cacheWrite + usage.input * rates.input) / 1_000_000); } function finiteTokens(value) { return Number.isFinite(value) && value > 0 ? value : 0; } function formatUsd(value) { return `$${value.toFixed(3)}`; } export default createCacheKeepAliveExtension(); //# sourceMappingURL=index.js.map