|
| 1 | +/** |
| 2 | + * The cache warming recorder of one agent run. It sees each model request of |
| 3 | + * the run, records the finished calls, and starts the idle period when the |
| 4 | + * Turn ends. `warmup.ts` owns the idle period and its warmups. |
| 5 | + */ |
| 6 | +import type { AssistantMessage } from "@earendil-works/pi-ai/compat"; |
| 7 | +// oxlint-disable-next-line no-restricted-imports -- The agent loop stream. Its Turn records the cost. |
| 8 | +import { streamSimple } from "@earendil-works/pi-ai/compat"; |
| 9 | +import { getChatConfig } from "@/chat/config"; |
| 10 | +import { logWarn } from "@/chat/logging"; |
| 11 | +import type { AgentRequestStreamFn } from "@/chat/pi/agent-history"; |
| 12 | +import type { ToolDefinitionsKey } from "@/chat/tool-support/registry"; |
| 13 | +import { CACHE_RETENTION, type ModelRequest } from "./request"; |
| 14 | +import { createToolWaitWarmer } from "./tool-wait"; |
| 15 | +import { |
| 16 | + ANSWER_TOOL_ENDINGS, |
| 17 | + recordModelCall, |
| 18 | + stopIdleWarmups, |
| 19 | + type CacheWarmingTurn, |
| 20 | + type TurnEnding, |
| 21 | +} from "./warmup"; |
| 22 | + |
| 23 | +/** Records the model calls of one agent run and schedules cache warmups. */ |
| 24 | +export interface CacheWarmingRecorder { |
| 25 | + /** |
| 26 | + * Wrap the stream function so the recorder sees each model request. The |
| 27 | + * wrapper also sets the cache retention that warming assumes while warming |
| 28 | + * is on. |
| 29 | + */ |
| 30 | + wrap(base?: AgentRequestStreamFn): AgentRequestStreamFn; |
| 31 | + /** Record the finished assistant message of the last model request. */ |
| 32 | + record(message: AssistantMessage): Promise<void>; |
| 33 | + /** Mark that the tools of the last request returned. */ |
| 34 | + toolsReturned(): void; |
| 35 | + /** |
| 36 | + * Mark that an answer tool call of the last request ended the run. After |
| 37 | + * `reply`, `noReply` or `reportBlocked`, `stop` starts the idle period from |
| 38 | + * that request, as a final response would. |
| 39 | + */ |
| 40 | + answerToolEnded(toolName: string): void; |
| 41 | + /** Stop the warmups of this run. Call it when the run ends. */ |
| 42 | + stop(): Promise<void>; |
| 43 | +} |
| 44 | + |
| 45 | +/** |
| 46 | + * Create a recorder for one agent run. A failure to record only loses cache |
| 47 | + * warming, so it is logged and does not stop the run. |
| 48 | + */ |
| 49 | +export function createCacheWarmingRecorder( |
| 50 | + conversationId: string, |
| 51 | + turn: CacheWarmingTurn, |
| 52 | + definitionsKey: ToolDefinitionsKey, |
| 53 | +): CacheWarmingRecorder { |
| 54 | + let lastRequest: ModelRequest | undefined; |
| 55 | + // The last finished call, for an idle period that an answer tool starts. |
| 56 | + let lastCall: |
| 57 | + | { request: ModelRequest; message: AssistantMessage } |
| 58 | + | undefined; |
| 59 | + let answerToolEnding: TurnEnding | undefined; |
| 60 | + // After the first call of the run ends the idle period, the next mid-turn |
| 61 | + // calls have nothing to record. This keeps them free of state reads. |
| 62 | + let idleEnded = false; |
| 63 | + let warmupsStopped: Promise<void> | undefined; |
| 64 | + const toolWait = createToolWaitWarmer(conversationId); |
| 65 | + return { |
| 66 | + wrap: |
| 67 | + (base = streamSimple) => |
| 68 | + (model, context, options) => { |
| 69 | + if (!warmupsStopped && getChatConfig().cacheWarmingEnabled) { |
| 70 | + warmupsStopped = stopIdleWarmups(conversationId); |
| 71 | + } |
| 72 | + // The tools returned, so this request reads the cache. |
| 73 | + toolWait.stop(); |
| 74 | + // With warming off, Pi's own retention applies. |
| 75 | + const cacheRetention = |
| 76 | + options?.cacheRetention ?? |
| 77 | + (getChatConfig().cacheWarmingEnabled ? CACHE_RETENTION : undefined); |
| 78 | + lastRequest = { |
| 79 | + model, |
| 80 | + // Copy the list, so later changes to the run do not change it. |
| 81 | + context: { ...context, messages: [...context.messages] }, |
| 82 | + ...(options?.reasoning |
| 83 | + ? { reasoning: options.reasoning } |
| 84 | + : undefined), |
| 85 | + ...(cacheRetention ? { cacheRetention } : undefined), |
| 86 | + startedAtMs: Date.now(), |
| 87 | + }; |
| 88 | + return base( |
| 89 | + model, |
| 90 | + context, |
| 91 | + cacheRetention ? { ...options, cacheRetention } : options, |
| 92 | + ); |
| 93 | + }, |
| 94 | + record: async (message) => { |
| 95 | + const request = lastRequest; |
| 96 | + lastRequest = undefined; |
| 97 | + await warmupsStopped; |
| 98 | + if (!getChatConfig().cacheWarmingEnabled || !request) { |
| 99 | + return; |
| 100 | + } |
| 101 | + try { |
| 102 | + await toolWait.record(request, message); |
| 103 | + } catch (error) { |
| 104 | + logWarn("cache_warming.tool_wait.record_failed", { |
| 105 | + "exception.message": |
| 106 | + error instanceof Error ? error.message : String(error), |
| 107 | + }); |
| 108 | + } |
| 109 | + if (message.stopReason === "error" || message.stopReason === "aborted") { |
| 110 | + return; |
| 111 | + } |
| 112 | + lastCall = { request, message }; |
| 113 | + if (idleEnded && message.stopReason !== "stop") { |
| 114 | + return; |
| 115 | + } |
| 116 | + idleEnded = message.stopReason !== "stop"; |
| 117 | + try { |
| 118 | + await recordModelCall( |
| 119 | + conversationId, |
| 120 | + turn, |
| 121 | + definitionsKey, |
| 122 | + request, |
| 123 | + message, |
| 124 | + message.stopReason === "stop" ? "reply" : undefined, |
| 125 | + ); |
| 126 | + } catch (error) { |
| 127 | + logWarn("cache_warming.model_call.record_failed", { |
| 128 | + "exception.message": |
| 129 | + error instanceof Error ? error.message : String(error), |
| 130 | + }); |
| 131 | + } |
| 132 | + }, |
| 133 | + toolsReturned: toolWait.toolsReturned, |
| 134 | + answerToolEnded: (toolName) => { |
| 135 | + answerToolEnding = ANSWER_TOOL_ENDINGS[toolName]; |
| 136 | + }, |
| 137 | + stop: async () => { |
| 138 | + try { |
| 139 | + await toolWait.end(answerToolEnding !== undefined); |
| 140 | + } catch (error) { |
| 141 | + logWarn("cache_warming.tool_wait.record_failed", { |
| 142 | + "exception.message": |
| 143 | + error instanceof Error ? error.message : String(error), |
| 144 | + }); |
| 145 | + } |
| 146 | + // The answer tool call stopped the run, so no final response came. Its |
| 147 | + // request holds the prefix that the next Turn reads. |
| 148 | + if (!answerToolEnding || !lastCall) return; |
| 149 | + try { |
| 150 | + await recordModelCall( |
| 151 | + conversationId, |
| 152 | + turn, |
| 153 | + definitionsKey, |
| 154 | + lastCall.request, |
| 155 | + lastCall.message, |
| 156 | + answerToolEnding, |
| 157 | + ); |
| 158 | + } catch (error) { |
| 159 | + logWarn("cache_warming.model_call.record_failed", { |
| 160 | + "exception.message": |
| 161 | + error instanceof Error ? error.message : String(error), |
| 162 | + }); |
| 163 | + } |
| 164 | + }, |
| 165 | + }; |
| 166 | +} |
0 commit comments