@sentry/junior 0.287.0 → 0.288.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/dist/{adapter-CL-HUKgd.js → adapter-Cikcqdty.js} +1 -1
  2. package/dist/{admin-C9urXVfi.js → admin-BcSxHuTB.js} +2 -2
  3. package/dist/{agent-runner-Bfnw551N.js → agent-runner-9MXyWUL8.js} +173 -89
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +8 -7
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +403 -40
  8. package/dist/{app-DBY5TnfY.d.ts → app-BUklJVBe.d.ts} +4 -2
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +521 -70
  11. package/dist/{assistant-reply-u_PRYzuz.js → assistant-reply-mj47jMRV.js} +1 -1
  12. package/dist/{automation-DksGNDRO.js → automation-DDXwHQs5.js} +2 -2
  13. package/dist/{background-compaction-queue-CYI909P5.js → background-compaction-queue-CjllSPir.js} +161 -90
  14. package/dist/{briefs-DaXiMWzT.js → briefs-DW9iuolG.js} +4 -3
  15. package/dist/{catalog-runtime-BCIuBe4d.js → catalog-runtime-B3gfH58M.js} +1 -1
  16. package/dist/cli/chat.js +14 -14
  17. package/dist/cli/check.js +3 -3
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +4 -4
  20. package/dist/cli/snapshot-create.js +4 -4
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +3 -3
  23. package/dist/{config-CkHcUMN7.js → config-CLJcyYEF.js} +401 -9
  24. package/dist/{connections-BnIj0wtx.js → connections-BtdJftow.js} +9 -9
  25. package/dist/{conversation-E7ZPJx2H.js → conversation-DhoqHtQ7.js} +23 -6
  26. package/dist/{conversation-pending-messages-DVch6YQw.js → conversation-pending-messages-DHV0S4uF.js} +1 -1
  27. package/dist/{conversation-privacy-DF1hW0ja.js → conversation-privacy-BPirIVlX.js} +1 -1
  28. package/dist/core-model-BTt5E5b0.js +182 -0
  29. package/dist/{credential-sync-CzMar9hq.js → credential-sync-Co8Q2xRW.js} +28 -20
  30. package/dist/{db-DJ11eZqq.js → db-Co7DTYYh.js} +30 -20
  31. package/dist/{db-YDKKDxlh.d.ts → db-zIs8-Ba3.d.ts} +6 -2
  32. package/dist/{executor-BY9TB31g.js → executor-m0kIN71Q.js} +93 -12
  33. package/dist/{media-Cz1ZiV1U.js → history-IjdmO_r6.js} +6 -86
  34. package/dist/instrumentation.js +2 -2
  35. package/dist/{logging-BO5zU6Mt.js → logging-DbD-dErY.js} +3 -2
  36. package/dist/media-BAHvgkok.js +85 -0
  37. package/dist/{message-CsUbuEc8.js → message-DKTdTYm-.js} +9 -9
  38. package/dist/nitro.d.ts +1 -1
  39. package/dist/nitro.js +19 -41
  40. package/dist/{oauth-callback-server-hiDKK0_n.js → oauth-callback-server-CpbepSbp.js} +2 -2
  41. package/dist/{projection-CL_YWeGf.js → projection-BViECfYu.js} +309 -616
  42. package/dist/{prompt-BHOEQSmf.js → prompt-KT6MaDHN.js} +2 -182
  43. package/dist/{registry-BriFLnaJ.js → registry-D-Acyjhh.js} +1 -1
  44. package/dist/{resolve-Bt6GgAiA.js → resolve-gkT2R66z.js} +3 -3
  45. package/dist/{result-Bo1TZu0Q.js → result-DHmCFEt8.js} +8 -8
  46. package/dist/{runner-D3YeCQgt.js → runner-DBKjGjH-.js} +8 -8
  47. package/dist/{sandbox-egress-signals-CcnSPP4S.js → sandbox-egress-signals-9n8hqx29.js} +1 -1
  48. package/dist/{schedule-BTp__wrw.js → schedule-cP0AACm1.js} +11 -2
  49. package/dist/{schema-C6fsEwjo.d.ts → schema-B_6aOcx5.d.ts} +114 -3
  50. package/dist/{schema-BWE3RJEB.js → schema-DxicIQbc.js} +66 -13
  51. package/dist/{service-account-r6fl0b-9.js → service-account-Bi0HsY6w.js} +3 -3
  52. package/dist/{service-account-DiQQuuw7.js → service-account-CDlC9ssy.js} +3 -3
  53. package/dist/{session-stop-B2Nut40V.js → session-stop-BWOsuo8p.js} +56 -14
  54. package/dist/{skills-CD5aJdzg.js → skills-DO5K68Rq.js} +2 -2
  55. package/dist/{spawn-CalgZQiu.js → spawn-BBqZDcPa.js} +5 -5
  56. package/dist/{stop-kujZLbi0.js → stop-WC97cmHz.js} +802 -338
  57. package/dist/{store-DdIEUL1q.js → store-ByR1Lr7e.js} +4 -16
  58. package/dist/{task-runner-D_RDr2Hu.js → task-runner-B-Ewf8TX.js} +30 -22
  59. package/dist/{turn-failure-response-B5nV1Er-.js → turn-failure-response-CpdPoZSl.js} +18 -9
  60. package/dist/{validation-K4pqwoVZ.js → validation-B4sbIoES.js} +1 -1
  61. package/dist/{version-DBvhk1X9.js → version-D6lpuAgL.js} +1 -1
  62. package/dist/version.js +1 -1
  63. package/dist/{viewer-DrMmFUul.js → viewer-CeP27tC3.js} +4 -4
  64. package/dist/warmup-P_GJCL1c.js +767 -0
  65. package/dist/{work-ljRoODGu.js → work-DI7x1Slm.js} +14 -13
  66. package/dist/{worker-CYO1Q0Js.js → worker-CYPTOT4j.js} +6 -6
  67. package/migrations/0089_conversation_paused_status.sql +3 -0
  68. package/migrations/0090_guardian_review_time_index.sql +20 -0
  69. package/migrations/meta/0089_snapshot.json +4372 -0
  70. package/migrations/meta/0090_snapshot.json +4388 -0
  71. package/migrations/meta/_journal.json +14 -0
  72. package/package.json +5 -4
@@ -0,0 +1,767 @@
1
+ import { n as captureMessage, v as __exportAll } from "./sentry-BRTJqumy.js";
2
+ import { E as resolveGatewayModel, G as isProviderRetryError, i as getChatConfig } from "./config-CLJcyYEF.js";
3
+ import { H as runWithLogContext, h as logWarn, m as logInfo } from "./logging-DbD-dErY.js";
4
+ import { r as completeText } from "./core-model-BTt5E5b0.js";
5
+ import { r as getStateAdapter } from "./adapter-Cikcqdty.js";
6
+ import { E as sendCacheWarmup } from "./background-compaction-queue-CjllSPir.js";
7
+ import { streamSimple } from "@earendil-works/pi-ai/compat";
8
+ import { promisify } from "node:util";
9
+ import { randomUUID } from "node:crypto";
10
+ import { constants, zstdCompress, zstdDecompress } from "node:zlib";
11
+ // src/chat/cache-warming/model.ts
12
+ /**
13
+ * Cost model for prompt cache warming.
14
+ *
15
+ * Ported from Lore's cache warmer (BYK/loreai,
16
+ * `packages/gateway/src/cache-warmer.ts`). The model estimates the chance that
17
+ * a person returns to an idle conversation before the cache expires. It then
18
+ * compares that chance with the cost of one more warmup.
19
+ */
20
+ /** One minute in milliseconds. */
21
+ const MINUTE_MS = 6e4;
22
+ /** Upper edges (ms) of the gap histogram bins. */
23
+ const GAP_BIN_EDGES_MS = [
24
+ 1e4,
25
+ 2e4,
26
+ 3e4,
27
+ 45e3,
28
+ MINUTE_MS,
29
+ 1.5 * MINUTE_MS,
30
+ 2 * MINUTE_MS,
31
+ 3 * MINUTE_MS,
32
+ 4 * MINUTE_MS,
33
+ 5 * MINUTE_MS,
34
+ 7 * MINUTE_MS,
35
+ 10 * MINUTE_MS,
36
+ 15 * MINUTE_MS,
37
+ 20 * MINUTE_MS,
38
+ 30 * MINUTE_MS,
39
+ 45 * MINUTE_MS,
40
+ 60 * MINUTE_MS,
41
+ 90 * MINUTE_MS,
42
+ 120 * MINUTE_MS,
43
+ 240 * MINUTE_MS,
44
+ Infinity
45
+ ];
46
+ const GAP_BIN_COUNT = GAP_BIN_EDGES_MS.length;
47
+ /** Gaps a conversation needs before its own gaps replace the global gaps. */
48
+ const BLEND_PSEUDOCOUNT = 20;
49
+ /**
50
+ * Gaps that a decision needs in total. With fewer, one gap sets the return
51
+ * chance for each Conversation of the segment, such as at launch or after
52
+ * the gap lists expire.
53
+ */
54
+ const MIN_GAP_SAMPLES = 20;
55
+ /** Below this prefix size, one cache miss costs too little to warm for. */
56
+ const MIN_WARMUP_PREFIX_TOKENS = 5e4;
57
+ /**
58
+ * Junior watches an idle period for this long. A person who replies later
59
+ * counts as a person who did not reply. The reply chance of a warmup counts
60
+ * only replies before this time. For a cache that outlives the horizon, this
61
+ * is less than the real chance, so Junior warms less, never more.
62
+ *
63
+ * The horizon message is signed when the idle period starts, and a queue
64
+ * signature is valid for 60 minutes (`QUEUE_SIGNATURE_MAX_AGE_MS`). The other
65
+ * 5 minutes let a late horizon still record its no-reply gap.
66
+ */
67
+ const IDLE_HORIZON_MS = 55 * MINUTE_MS;
68
+ /**
69
+ * Whether a failed warmup request counts as a miss for the provider breaker.
70
+ * A request that the provider rejects fails the same way for each
71
+ * Conversation, so it counts. A retryable failure, such as an overload or a
72
+ * timeout, says nothing about the cache, so it must not stop warming for
73
+ * every Conversation.
74
+ */
75
+ function warmupFailureCountsAsMiss(error) {
76
+ return !isProviderRetryError(error);
77
+ }
78
+ /** Gap that Junior records for an idle period with no reply in the horizon. */
79
+ const NO_REPLY_GAP_MS = 1440 * MINUTE_MS;
80
+ const BASE_WARMUP_MARGIN_MS = 45e3;
81
+ const MARGIN_PER_PREFIX_TOKEN_MS = .27;
82
+ const MAX_SIZE_MARGIN_MS = 9e4;
83
+ function binIndex(gapMs) {
84
+ return GAP_BIN_EDGES_MS.findIndex((edge) => gapMs < edge);
85
+ }
86
+ function histogramOf(gapsMs) {
87
+ const counts = Array.from({ length: GAP_BIN_COUNT }, () => 0);
88
+ for (const gap of gapsMs) counts[binIndex(gap)] += 1;
89
+ return {
90
+ counts,
91
+ total: gapsMs.length
92
+ };
93
+ }
94
+ function blendHistograms(conversation, global) {
95
+ if (conversation.total === 0 || global.total === 0) return conversation.total === 0 ? global : conversation;
96
+ const weight = Math.min(conversation.total / BLEND_PSEUDOCOUNT, 1);
97
+ return {
98
+ counts: conversation.counts.map((count, index) => weight * count / conversation.total + (1 - weight) * global.counts[index] / global.total),
99
+ total: 1
100
+ };
101
+ }
102
+ function survival(histogram, tMs) {
103
+ if (histogram.total === 0) return 1;
104
+ const index = binIndex(tMs);
105
+ let surviving = 0;
106
+ for (let i = index + 1; i < GAP_BIN_COUNT; i++) surviving += histogram.counts[i];
107
+ const binStart = index > 0 ? GAP_BIN_EDGES_MS[index - 1] : 0;
108
+ const fractionPast = Math.min(1, Math.max(0, (tMs - binStart) / (GAP_BIN_EDGES_MS[index] - binStart)));
109
+ surviving += histogram.counts[index] * (1 - fractionPast);
110
+ return surviving / histogram.total;
111
+ }
112
+ function returnProbability(histogram, idleMs, windowMs) {
113
+ const now = survival(histogram, idleMs);
114
+ if (now < .001) return 0;
115
+ return Math.max(0, (now - survival(histogram, idleMs + windowMs)) / now);
116
+ }
117
+ /**
118
+ * Return how long before cache expiry to send a warmup. The warmup refreshes
119
+ * the cache only if the provider reads the whole prefix before it expires. A
120
+ * larger prefix takes longer to send and read, and its cache blocks were
121
+ * written at slightly different times. So the margin grows with the prefix up
122
+ * to a fixed cap.
123
+ */
124
+ function warmupMarginMs(prefixTokens) {
125
+ return BASE_WARMUP_MARGIN_MS + Math.min(Math.max(0, prefixTokens) * MARGIN_PER_PREFIX_TOKEN_MS, MAX_SIZE_MARGIN_MS);
126
+ }
127
+ /**
128
+ * Pick the gap histogram for an idle period. Return chances differ most by
129
+ * who started the Turn and by how many Turns the Conversation had before it.
130
+ * Turns that no person started rarely get a quick reply. In 30 days of
131
+ * production data, segments by these two keys saved more than one histogram.
132
+ * Local time of day did not improve the result, so it is not a key.
133
+ */
134
+ function gapSegment(userActor, endedTurns) {
135
+ return `${userActor ? "user" : "system"}:${endedTurns === 0 ? "1" : endedTurns < 3 ? "2-3" : "4+"}`;
136
+ }
137
+ /**
138
+ * Decide whether to send the next warmup.
139
+ *
140
+ * A warmup costs one cache read of the prefix. A return to a warm cache saves
141
+ * one write minus one read. So warming pays when the expected returns per
142
+ * warmup are above read/(write − read). Earlier warmups are already paid, so
143
+ * the threshold is the same for each warmup.
144
+ *
145
+ * One warmup alone can be useless when people return a little after the next
146
+ * TTL, while two or three warmups in a row would reach them. So the decision
147
+ * compares plans of 1, 2, ... warmups up to the horizon. Each plan sends its
148
+ * next warmup only while nobody returned. Junior warms when the best plan
149
+ * pays, and decides again at the next warmup.
150
+ */
151
+ function decideWarmup(input) {
152
+ const savedPerReturn = input.cacheWritePrice - input.cacheReadPrice;
153
+ const threshold = savedPerReturn > 0 ? Math.min(input.cacheReadPrice / savedPerReturn, 1) : 1;
154
+ const conversation = histogramOf(input.conversationGapsMs);
155
+ const global = histogramOf(input.globalGapsMs);
156
+ const histogram = blendHistograms(conversation, global);
157
+ const probability = returnProbability(histogram, input.idleMs, Math.min(input.cacheTtlMs, IDLE_HORIZON_MS - input.idleMs));
158
+ const perWarmup = returnsPerWarmup(histogram, input.idleMs, input.cacheExpiryIdleMs, input.cacheTtlMs, input.prefixTokens);
159
+ const decision = (reason) => ({
160
+ warm: reason === "warm",
161
+ reason,
162
+ returnProbability: probability,
163
+ returnsPerWarmup: perWarmup,
164
+ threshold
165
+ });
166
+ if (input.prefixTokens < 5e4) return decision("prefix_too_small");
167
+ if (threshold >= 1) return decision("no_savings");
168
+ if (input.idleMs >= 33e5) return decision("horizon");
169
+ if (conversation.total + global.total < MIN_GAP_SAMPLES) return decision("few_gaps");
170
+ return decision(perWarmup >= threshold ? "warm" : "unlikely_return");
171
+ }
172
+ function returnsPerWarmup(histogram, idleMs, cacheExpiryIdleMs, ttlMs, prefixTokens) {
173
+ const now = survival(histogram, idleMs);
174
+ const intervalMs = ttlMs - warmupMarginMs(prefixTokens);
175
+ if (now < .001 || intervalMs <= 0) return 0;
176
+ const leftAtExpiry = survival(histogram, Math.min(cacheExpiryIdleMs, IDLE_HORIZON_MS));
177
+ let best = 0;
178
+ let warmups = 0;
179
+ for (let startMs = idleMs; startMs < IDLE_HORIZON_MS; startMs += intervalMs) {
180
+ warmups += survival(histogram, startMs) / now;
181
+ const endMs = Math.min(startMs + ttlMs, IDLE_HORIZON_MS);
182
+ const returns = Math.max(0, leftAtExpiry - survival(histogram, endMs)) / now;
183
+ best = Math.max(best, returns / warmups);
184
+ }
185
+ return best;
186
+ }
187
+ // src/chat/cache-warming/request.ts
188
+ const KEY_PREFIX = "junior:cache_warming";
189
+ const CACHE_RETENTION = "short";
190
+ const REFRESHED_READ_FRACTION = .9;
191
+ const BREAKER_OUTCOMES_MAX = 20;
192
+ const BREAKER_MAX_MISSES = 10;
193
+ const BREAKER_OUTCOMES_TTL_MS = 360 * MINUTE_MS;
194
+ const BREAKER_OPEN_TTL_MS = 1440 * MINUTE_MS;
195
+ const breakerOutcomesKey = (provider) => `${KEY_PREFIX}:breaker:${provider}:outcomes`;
196
+ const breakerOpenKey = (provider) => `${KEY_PREFIX}:breaker:${provider}:open`;
197
+ const providerOf = (modelId) => modelId.split("/")[0] ?? "";
198
+ /** Connect the state adapter that holds cache warming state. */
199
+ async function connectedState() {
200
+ const state = getStateAdapter();
201
+ await state.connect();
202
+ return state;
203
+ }
204
+ const CACHE_TTL_MS = {
205
+ anthropic: 5 * MINUTE_MS,
206
+ alibaba: 5 * MINUTE_MS,
207
+ openai: 30 * MINUTE_MS
208
+ };
209
+ /**
210
+ * Return true when warmups can refresh the prompt cache of this request.
211
+ * Warming pays only when a cache write costs more than a read. Pi adds a
212
+ * thinking budget to the one-token output limit on the Anthropic Messages API
213
+ * for models without adaptive thinking. Then a warmup could cost as much as a
214
+ * short answer, and a smaller budget would miss the cached messages.
215
+ */
216
+ function supportsWarming(request) {
217
+ const { model, reasoning } = request;
218
+ const budgetThinking = reasoning !== void 0 && model.api === "anthropic-messages" && model.compat?.forceAdaptiveThinking !== true;
219
+ return CACHE_TTL_MS[providerOf(model.id)] !== void 0 && model.cost.cacheRead > 0 && model.cost.cacheWrite > model.cost.cacheRead && !budgetThinking && request.cacheRetention === "short";
220
+ }
221
+ /** Return the cache TTL of a request that Junior can warm. */
222
+ function cacheTtlMs(request) {
223
+ return supportsWarming(request) ? CACHE_TTL_MS[providerOf(request.model.id)] : void 0;
224
+ }
225
+ /** Return the cached prefix tokens of a finished model request. */
226
+ function cachedPrefixTokens(message) {
227
+ return message.usage.cacheRead + message.usage.cacheWrite;
228
+ }
229
+ /**
230
+ * Return when the cache that a request at `requestStartedAtMs` read or wrote
231
+ * expires, and the delay until the warmup that refreshes it.
232
+ */
233
+ function warmupTiming(requestStartedAtMs, prefixTokens, ttlMs) {
234
+ const cacheExpiresAtMs = requestStartedAtMs + ttlMs;
235
+ return {
236
+ cacheExpiresAtMs,
237
+ delayMs: cacheExpiresAtMs - warmupMarginMs(prefixTokens) - Date.now()
238
+ };
239
+ }
240
+ const LATE_WARMUP_MS = 1e4;
241
+ /**
242
+ * Return true when a warmup is too late to refresh the cache. The cache is
243
+ * gone, so the warmup must not run or count as a miss.
244
+ */
245
+ function warmupTooLate(cacheExpiresAtMs) {
246
+ return Date.now() + LATE_WARMUP_MS >= cacheExpiresAtMs;
247
+ }
248
+ /**
249
+ * Return true while too many recent warmups of the model's provider missed,
250
+ * so its warming is off.
251
+ */
252
+ async function breakerOpen(state, modelId) {
253
+ return await state.get(breakerOpenKey(providerOf(modelId))) === true;
254
+ }
255
+ async function countOutcome(state, modelId, miss) {
256
+ const provider = providerOf(modelId);
257
+ await state.appendToList(breakerOutcomesKey(provider), miss ? 1 : 0, {
258
+ maxLength: BREAKER_OUTCOMES_MAX,
259
+ ttlMs: BREAKER_OUTCOMES_TTL_MS
260
+ });
261
+ if (!miss) return;
262
+ const outcomes = await state.getList(breakerOutcomesKey(provider));
263
+ const misses = outcomes.filter((outcome) => outcome === 1).length;
264
+ if (misses >= BREAKER_MAX_MISSES && await state.setIfNotExists(breakerOpenKey(provider), true, BREAKER_OPEN_TTL_MS)) captureMessage("Cache warming stopped: too many warmups missed the cache", {
265
+ level: "error",
266
+ fingerprint: ["cache_warming.breaker.opened", provider],
267
+ tags: { "gen_ai.request.model": modelId },
268
+ extra: {
269
+ "app.cache_warming.misses": misses,
270
+ "app.cache_warming.outcomes": outcomes.length
271
+ }
272
+ });
273
+ }
274
+ /**
275
+ * Send one warmup: the same request with a one-token output limit. Count its
276
+ * outcome for the breaker, and report a miss to Sentry. A rejected request
277
+ * counts as a miss and rethrows, because it fails the same way for each
278
+ * Conversation.
279
+ */
280
+ async function sendWarmup(state, params) {
281
+ const { conversationId, modelId, context, prefixTokens } = params;
282
+ const { message: result } = await completeText({
283
+ modelId,
284
+ system: context.systemPrompt,
285
+ messages: context.messages,
286
+ ...context.tools ? { tools: context.tools } : void 0,
287
+ ...params.reasoning ? { thinkingLevel: params.reasoning } : void 0,
288
+ cacheRetention: CACHE_RETENTION,
289
+ maxTokens: 1,
290
+ messageAttributeMode: "metadata",
291
+ metadata: { conversationId },
292
+ operation: "cache_warmup",
293
+ cost: { conversationId },
294
+ sessionId: conversationId
295
+ }).catch(async (error) => {
296
+ if (warmupFailureCountsAsMiss(error)) await countOutcome(state, modelId, true);
297
+ throw error;
298
+ });
299
+ const attributes = {
300
+ "app.cost.total_usd": result.usage.cost.total,
301
+ "gen_ai.usage.cache_read.input_tokens": result.usage.cacheRead,
302
+ "gen_ai.usage.cache_creation.input_tokens": result.usage.cacheWrite
303
+ };
304
+ const refreshed = result.usage.cacheRead >= prefixTokens * REFRESHED_READ_FRACTION;
305
+ if (!refreshed) captureMessage("Cache warmup missed the cache", {
306
+ level: "warning",
307
+ fingerprint: ["cache_warming.warmup.missed", modelId],
308
+ tags: { "gen_ai.request.model": modelId },
309
+ extra: { "app.cache_warming.read_fraction": result.usage.cacheRead / prefixTokens }
310
+ });
311
+ await countOutcome(state, modelId, !refreshed);
312
+ return {
313
+ refreshed,
314
+ attributes
315
+ };
316
+ }
317
+ // src/chat/cache-warming/tool-wait.ts
318
+ const TOOL_WAIT_GAPS_KEY = `${KEY_PREFIX}:gaps:tool_wait`;
319
+ const TOOL_WAIT_GAPS_MAX = 2e3;
320
+ const TOOL_WAIT_GAPS_TTL_MS = 43200 * MINUTE_MS;
321
+ const MIN_RECORDED_TOOL_WAIT_MS = 2 * MINUTE_MS;
322
+ /** Create the tool wait warmer of one agent run. */
323
+ function createToolWaitWarmer(conversationId) {
324
+ let timer;
325
+ let waiting;
326
+ let returnedAtMs;
327
+ let generation = 0;
328
+ const schedule = (cache, refreshedAtMs, cycle) => {
329
+ const current = generation;
330
+ const { cacheExpiresAtMs, delayMs } = warmupTiming(refreshedAtMs, cache.prefixTokens, cache.ttlMs);
331
+ timer = setTimeout(() => {
332
+ timer = void 0;
333
+ warm(cache, cacheExpiresAtMs, cycle, current);
334
+ }, Math.max(0, delayMs));
335
+ timer.unref?.();
336
+ };
337
+ const warm = (cache, cacheExpiresAtMs, cycle, current) => {
338
+ const { request, prefixTokens } = cache;
339
+ return runWithLogContext({
340
+ conversationId,
341
+ modelId: request.model.id
342
+ }, {}, async () => {
343
+ const attributes = {
344
+ "app.cache_warming.cycle": cycle,
345
+ "app.cache_warming.prefix_tokens": prefixTokens,
346
+ "app.cache_warming.trigger": "tool_wait"
347
+ };
348
+ if (warmupTooLate(cacheExpiresAtMs)) {
349
+ logInfo("cache_warming.warmup.skipped", {
350
+ ...attributes,
351
+ "app.cache_warming.skip_reason": "cache_expired"
352
+ });
353
+ return;
354
+ }
355
+ try {
356
+ const state = await connectedState();
357
+ if (await breakerOpen(state, request.model.id)) {
358
+ logInfo("cache_warming.warmup.skipped", {
359
+ ...attributes,
360
+ "app.cache_warming.skip_reason": "breaker_open"
361
+ });
362
+ return;
363
+ }
364
+ const decision = decideWarmup({
365
+ conversationGapsMs: [],
366
+ globalGapsMs: await state.getList(TOOL_WAIT_GAPS_KEY),
367
+ idleMs: Date.now() - request.startedAtMs,
368
+ cacheExpiryIdleMs: cacheExpiresAtMs - request.startedAtMs,
369
+ cacheTtlMs: cache.ttlMs,
370
+ prefixTokens,
371
+ cacheReadPrice: request.model.cost.cacheRead,
372
+ cacheWritePrice: request.model.cost.cacheWrite
373
+ });
374
+ attributes["app.cache_warming.return_probability"] = decision.returnProbability;
375
+ attributes["app.cache_warming.returns_per_warmup"] = decision.returnsPerWarmup;
376
+ attributes["app.cache_warming.threshold"] = decision.threshold;
377
+ if (current !== generation) return;
378
+ if (!decision.warm) {
379
+ logInfo("cache_warming.warmup.skipped", {
380
+ ...attributes,
381
+ "app.cache_warming.skip_reason": decision.reason
382
+ });
383
+ return;
384
+ }
385
+ const startedAtMs = Date.now();
386
+ const warmup = await sendWarmup(state, {
387
+ conversationId,
388
+ modelId: request.model.id,
389
+ context: request.context,
390
+ ...request.reasoning ? { reasoning: request.reasoning } : void 0,
391
+ prefixTokens
392
+ });
393
+ Object.assign(attributes, warmup.attributes);
394
+ if (!warmup.refreshed) {
395
+ logWarn("cache_warming.warmup.failed", attributes);
396
+ return;
397
+ }
398
+ logInfo("cache_warming.warmup.completed", attributes);
399
+ if (current === generation) schedule(cache, startedAtMs, cycle + 1);
400
+ } catch (error) {
401
+ logWarn("cache_warming.warmup.failed", {
402
+ ...attributes,
403
+ "exception.message": error instanceof Error ? error.message : String(error)
404
+ });
405
+ }
406
+ });
407
+ };
408
+ const stop = () => {
409
+ generation += 1;
410
+ clearTimeout(timer);
411
+ timer = void 0;
412
+ };
413
+ const recordWait = async (waitMs) => {
414
+ if (waitMs < MIN_RECORDED_TOOL_WAIT_MS) return;
415
+ await (await connectedState()).appendToList(TOOL_WAIT_GAPS_KEY, waitMs, {
416
+ maxLength: TOOL_WAIT_GAPS_MAX,
417
+ ttlMs: TOOL_WAIT_GAPS_TTL_MS
418
+ });
419
+ };
420
+ return {
421
+ async record(request, message) {
422
+ stop();
423
+ const previous = waiting;
424
+ waiting = message.stopReason === "toolUse" ? request : void 0;
425
+ returnedAtMs = void 0;
426
+ const prefixTokens = cachedPrefixTokens(message);
427
+ const ttlMs = cacheTtlMs(request);
428
+ if (waiting && prefixTokens >= 5e4 && ttlMs !== void 0) schedule({
429
+ request,
430
+ prefixTokens,
431
+ ttlMs
432
+ }, request.startedAtMs, 1);
433
+ if (previous) await recordWait(request.startedAtMs - previous.startedAtMs);
434
+ },
435
+ stop,
436
+ toolsReturned() {
437
+ stop();
438
+ if (waiting) returnedAtMs ??= Date.now();
439
+ },
440
+ async end() {
441
+ stop();
442
+ const open = waiting;
443
+ const returned = returnedAtMs;
444
+ waiting = void 0;
445
+ returnedAtMs = void 0;
446
+ if (!open) return;
447
+ if (returned !== void 0) {
448
+ await recordWait(returned - open.startedAtMs);
449
+ return;
450
+ }
451
+ if (Date.now() - open.startedAtMs >= MIN_RECORDED_TOOL_WAIT_MS) await recordWait(NO_REPLY_GAP_MS);
452
+ }
453
+ };
454
+ }
455
+ // src/chat/cache-warming/warmup.ts
456
+ /**
457
+ * Prompt cache warming for idle Conversations.
458
+ *
459
+ * After a turn ends, the next human message often arrives after the short
460
+ * prompt cache TTL. Then the full history is written to the cache again. A
461
+ * warmup sends the same request again with a one-token output limit before
462
+ * the cache expires. The provider reads the cached prefix and refreshes its
463
+ * TTL. `model.ts` owns the cost model.
464
+ *
465
+ * Each idle period gets one recorded reply gap, so the model also sees the
466
+ * people who do not reply. A reply records its gap. A delayed `horizon`
467
+ * message records `NO_REPLY_GAP_MS` when no reply came in the idle horizon.
468
+ *
469
+ * Only a Turn writes the Conversation state. Warmups and the horizon run
470
+ * while the next Turn can start, so they write only keys of their own idle
471
+ * period (`generation`): the snapshot, the warmup count, and the gap claim.
472
+ * Work for an old idle period then cannot change a newer one.
473
+ */
474
+ var warmup_exports = /* @__PURE__ */ __exportAll({
475
+ CONVERSATION_STATE_TTL_MS: () => CONVERSATION_STATE_TTL_MS,
476
+ GLOBAL_GAPS_MAX: () => GLOBAL_GAPS_MAX,
477
+ GLOBAL_GAPS_TTL_MS: () => GLOBAL_GAPS_TTL_MS,
478
+ createCacheWarmingRecorder: () => createCacheWarmingRecorder,
479
+ runCacheWarmup: () => runCacheWarmup,
480
+ segmentGapsKey: () => segmentGapsKey
481
+ });
482
+ const zstdCompress$1 = promisify(zstdCompress);
483
+ const zstdDecompress$1 = promisify(zstdDecompress);
484
+ const SNAPSHOT_ZSTD_PARAMS = { params: { [constants.ZSTD_c_compressionLevel]: 1 } };
485
+ /** Gaps kept in each segment list. */
486
+ const GLOBAL_GAPS_MAX = 2e3;
487
+ /** A segment list expires this long after its last gap. */
488
+ const GLOBAL_GAPS_TTL_MS = 43200 * MINUTE_MS;
489
+ const CONVERSATION_GAPS_MAX = 50;
490
+ /** The Turn count of a Conversation resets after this long with no call. */
491
+ const CONVERSATION_STATE_TTL_MS = 10080 * MINUTE_MS;
492
+ const MAX_SNAPSHOT_BYTES = 1048576;
493
+ /** State list of the recent reply gaps (ms) of one `gapSegment`. */
494
+ const segmentGapsKey = (segment) => `${KEY_PREFIX}:gaps:${segment}`;
495
+ const conversationKey = (conversationId) => `${KEY_PREFIX}:conversation:${conversationId}`;
496
+ /**
497
+ * Recent reply gaps (ms) of the idle periods of this Conversation, per
498
+ * `gapSegment`. A person's quick replies must not set the return chance of an
499
+ * idle period that a system Turn started.
500
+ */
501
+ const conversationGapsKey = (conversationId, segment) => `${KEY_PREFIX}:gaps:conversation:${conversationId}:${segment}`;
502
+ const snapshotKey = (conversationId, generation) => `${KEY_PREFIX}:snapshot:${conversationId}:${generation}`;
503
+ /** Warmups that completed in the idle period. */
504
+ const warmupsKey = (conversationId, generation) => `${KEY_PREFIX}:warmups:${conversationId}:${generation}`;
505
+ /** Set by the first of the reply and the horizon to record the gap. */
506
+ const gapClaimKey = (conversationId, generation) => `${KEY_PREFIX}:gap_claim:${conversationId}:${generation}`;
507
+ async function scheduleWarmup(message, requestStartedAtMs, warm) {
508
+ const { cacheExpiresAtMs, delayMs } = warmupTiming(requestStartedAtMs, warm.prefixTokens, warm.cacheTtlMs);
509
+ await sendCacheWarmup({
510
+ ...message,
511
+ cacheExpiresAtMs
512
+ }, delayMs);
513
+ }
514
+ function snapshotContext(context) {
515
+ return {
516
+ ...context.systemPrompt !== void 0 ? { systemPrompt: context.systemPrompt } : void 0,
517
+ messages: context.messages,
518
+ ...context.tools ? { tools: context.tools.map((tool) => ({
519
+ name: tool.name,
520
+ description: tool.description,
521
+ parameters: tool.parameters,
522
+ ...tool.constrainedSampling !== void 0 ? { constrainedSampling: tool.constrainedSampling } : void 0
523
+ })) } : void 0
524
+ };
525
+ }
526
+ async function recordGap(state, conversationId, idle, gapMs) {
527
+ if (!await state.setIfNotExists(gapClaimKey(conversationId, idle.generation), true, CONVERSATION_STATE_TTL_MS)) return;
528
+ await state.appendToList(segmentGapsKey(idle.segment), gapMs, {
529
+ maxLength: GLOBAL_GAPS_MAX,
530
+ ttlMs: GLOBAL_GAPS_TTL_MS
531
+ });
532
+ await state.appendToList(conversationGapsKey(conversationId, idle.segment), gapMs, {
533
+ maxLength: CONVERSATION_GAPS_MAX,
534
+ ttlMs: CONVERSATION_STATE_TTL_MS
535
+ });
536
+ }
537
+ async function startIdlePeriod(state, conversationId, request, message, segment) {
538
+ const idle = {
539
+ generation: randomUUID(),
540
+ segment,
541
+ sinceMs: request.startedAtMs
542
+ };
543
+ const prefixTokens = cachedPrefixTokens(message);
544
+ const ttlMs = cacheTtlMs(request);
545
+ if (ttlMs === void 0 || prefixTokens < 5e4) return idle;
546
+ const snapshot = (await zstdCompress$1(JSON.stringify(snapshotContext(request.context)), SNAPSHOT_ZSTD_PARAMS)).toString("base64");
547
+ if (snapshot.length > MAX_SNAPSHOT_BYTES) {
548
+ logInfo("cache_warming.snapshot.skipped", {
549
+ "app.cache_warming.prefix_tokens": prefixTokens,
550
+ "app.cache_warming.snapshot_bytes": snapshot.length
551
+ });
552
+ return idle;
553
+ }
554
+ await state.set(snapshotKey(conversationId, idle.generation), snapshot, IDLE_HORIZON_MS);
555
+ return {
556
+ ...idle,
557
+ warm: {
558
+ modelId: request.model.id,
559
+ prefixTokens,
560
+ cacheTtlMs: ttlMs,
561
+ ...request.reasoning ? { reasoning: request.reasoning } : void 0
562
+ }
563
+ };
564
+ }
565
+ async function recordModelCall(conversationId, userActor, request, message) {
566
+ const state = await connectedState();
567
+ const previous = await state.get(conversationKey(conversationId));
568
+ const idle = previous?.idle;
569
+ if (idle?.warm) {
570
+ const gapMs = request.startedAtMs - idle.sinceMs;
571
+ if (gapMs > 0) await recordGap(state, conversationId, idle, gapMs);
572
+ await state.delete(snapshotKey(conversationId, idle.generation));
573
+ const warmups = await state.get(warmupsKey(conversationId, idle.generation)) ?? 0;
574
+ if (warmups > 0) logInfo("cache_warming.conversation.returned", {
575
+ "app.cache_warming.gap_ms": gapMs,
576
+ "app.cache_warming.prefix_tokens": idle.warm.prefixTokens,
577
+ "app.cache_warming.warmup_count": warmups,
578
+ "gen_ai.usage.cache_read.input_tokens": message.usage.cacheRead,
579
+ "gen_ai.usage.cache_creation.input_tokens": message.usage.cacheWrite
580
+ });
581
+ }
582
+ const endedTurns = previous?.endedTurns ?? 0;
583
+ const next = message.stopReason === "stop" ? {
584
+ endedTurns: endedTurns + 1,
585
+ idle: await startIdlePeriod(state, conversationId, request, message, gapSegment(userActor, endedTurns))
586
+ } : { endedTurns };
587
+ if (!idle && !next.idle) return;
588
+ await state.set(conversationKey(conversationId), next, CONVERSATION_STATE_TTL_MS);
589
+ if (next.idle?.warm) {
590
+ const { generation } = next.idle;
591
+ await sendCacheWarmup({
592
+ kind: "horizon",
593
+ conversationId,
594
+ generation
595
+ }, request.startedAtMs + IDLE_HORIZON_MS - Date.now());
596
+ await scheduleWarmup({
597
+ kind: "warmup",
598
+ conversationId,
599
+ cycle: 1,
600
+ generation
601
+ }, request.startedAtMs, next.idle.warm);
602
+ }
603
+ }
604
+ async function stopIdleWarmups(conversationId) {
605
+ try {
606
+ const state = await connectedState();
607
+ const idle = (await state.get(conversationKey(conversationId)))?.idle;
608
+ if (idle?.warm) await state.delete(snapshotKey(conversationId, idle.generation));
609
+ } catch (error) {
610
+ logWarn("cache_warming.idle_period.stop_failed", { "exception.message": error instanceof Error ? error.message : String(error) });
611
+ }
612
+ }
613
+ /**
614
+ * Create a recorder for one agent run. `userActor` is true when a person
615
+ * started the Turn. A failure to record only loses cache warming, so it is
616
+ * logged and does not stop the run.
617
+ */
618
+ function createCacheWarmingRecorder(conversationId, userActor) {
619
+ let lastRequest;
620
+ let idleEnded = false;
621
+ let warmupsStopped;
622
+ const toolWait = createToolWaitWarmer(conversationId);
623
+ return {
624
+ wrap: (base = streamSimple) => (model, context, options) => {
625
+ if (!warmupsStopped && getChatConfig().cacheWarmingEnabled) warmupsStopped = stopIdleWarmups(conversationId);
626
+ toolWait.stop();
627
+ const cacheRetention = options?.cacheRetention ?? (getChatConfig().cacheWarmingEnabled ? "short" : void 0);
628
+ lastRequest = {
629
+ model,
630
+ context: {
631
+ ...context,
632
+ messages: [...context.messages]
633
+ },
634
+ ...options?.reasoning ? { reasoning: options.reasoning } : void 0,
635
+ ...cacheRetention ? { cacheRetention } : void 0,
636
+ startedAtMs: Date.now()
637
+ };
638
+ return base(model, context, cacheRetention ? {
639
+ ...options,
640
+ cacheRetention
641
+ } : options);
642
+ },
643
+ record: async (message) => {
644
+ const request = lastRequest;
645
+ lastRequest = void 0;
646
+ await warmupsStopped;
647
+ if (!getChatConfig().cacheWarmingEnabled || !request) return;
648
+ try {
649
+ await toolWait.record(request, message);
650
+ } catch (error) {
651
+ logWarn("cache_warming.tool_wait.record_failed", { "exception.message": error instanceof Error ? error.message : String(error) });
652
+ }
653
+ if (message.stopReason === "error" || message.stopReason === "aborted" || idleEnded && message.stopReason !== "stop") return;
654
+ idleEnded = message.stopReason !== "stop";
655
+ try {
656
+ await recordModelCall(conversationId, userActor, request, message);
657
+ } catch (error) {
658
+ logWarn("cache_warming.model_call.record_failed", { "exception.message": error instanceof Error ? error.message : String(error) });
659
+ }
660
+ },
661
+ toolsReturned: toolWait.toolsReturned,
662
+ stop: async () => {
663
+ try {
664
+ await toolWait.end();
665
+ } catch (error) {
666
+ logWarn("cache_warming.tool_wait.record_failed", { "exception.message": error instanceof Error ? error.message : String(error) });
667
+ }
668
+ }
669
+ };
670
+ }
671
+ /**
672
+ * Run one scheduled cache warming message. A message for an idle period that
673
+ * already ended does nothing.
674
+ */
675
+ async function runCacheWarmup(message) {
676
+ const { conversationId } = message;
677
+ const state = await connectedState();
678
+ const idle = (await state.get(conversationKey(conversationId)))?.idle;
679
+ const warm = idle?.warm;
680
+ if (!idle || !warm || idle.generation !== message.generation) return;
681
+ const { generation } = idle;
682
+ const stop = () => state.delete(snapshotKey(conversationId, generation));
683
+ if (message.kind === "horizon") {
684
+ await stop();
685
+ await recordGap(state, conversationId, idle, NO_REPLY_GAP_MS);
686
+ return;
687
+ }
688
+ if ((await state.get(warmupsKey(conversationId, generation)) ?? 0) !== message.cycle - 1) return;
689
+ await runWithLogContext({
690
+ conversationId,
691
+ modelId: warm.modelId
692
+ }, {}, async () => {
693
+ const attributes = {
694
+ "app.cache_warming.cycle": message.cycle,
695
+ "app.cache_warming.prefix_tokens": warm.prefixTokens,
696
+ "app.cache_warming.trigger": "idle",
697
+ "app.cache_warming.cache_ttl_left_ms": message.cacheExpiresAtMs - Date.now()
698
+ };
699
+ if (warmupTooLate(message.cacheExpiresAtMs)) {
700
+ logInfo("cache_warming.warmup.skipped", {
701
+ ...attributes,
702
+ "app.cache_warming.skip_reason": "cache_expired"
703
+ });
704
+ await stop();
705
+ return;
706
+ }
707
+ if (await breakerOpen(state, warm.modelId)) {
708
+ logInfo("cache_warming.warmup.skipped", {
709
+ ...attributes,
710
+ "app.cache_warming.skip_reason": "breaker_open"
711
+ });
712
+ await stop();
713
+ return;
714
+ }
715
+ const model = resolveGatewayModel(warm.modelId);
716
+ const decision = decideWarmup({
717
+ conversationGapsMs: await state.getList(conversationGapsKey(conversationId, idle.segment)),
718
+ globalGapsMs: await state.getList(segmentGapsKey(idle.segment)),
719
+ idleMs: Date.now() - idle.sinceMs,
720
+ cacheExpiryIdleMs: message.cacheExpiresAtMs - idle.sinceMs,
721
+ cacheTtlMs: warm.cacheTtlMs,
722
+ prefixTokens: warm.prefixTokens,
723
+ cacheReadPrice: model.cost.cacheRead,
724
+ cacheWritePrice: model.cost.cacheWrite
725
+ });
726
+ attributes["app.cache_warming.return_probability"] = decision.returnProbability;
727
+ attributes["app.cache_warming.returns_per_warmup"] = decision.returnsPerWarmup;
728
+ attributes["app.cache_warming.threshold"] = decision.threshold;
729
+ if (!decision.warm) {
730
+ logInfo("cache_warming.warmup.skipped", {
731
+ ...attributes,
732
+ "app.cache_warming.skip_reason": decision.reason
733
+ });
734
+ await stop();
735
+ return;
736
+ }
737
+ const snapshot = await state.get(snapshotKey(conversationId, generation));
738
+ if (!snapshot) return;
739
+ const context = JSON.parse((await zstdDecompress$1(Buffer.from(snapshot, "base64"))).toString("utf8"));
740
+ const startedAtMs = Date.now();
741
+ const warmup = await sendWarmup(state, {
742
+ conversationId,
743
+ modelId: warm.modelId,
744
+ context,
745
+ ...warm.reasoning ? { reasoning: warm.reasoning } : void 0,
746
+ prefixTokens: warm.prefixTokens
747
+ }).catch(async (error) => {
748
+ await stop();
749
+ throw error;
750
+ });
751
+ Object.assign(attributes, warmup.attributes);
752
+ if (!warmup.refreshed) {
753
+ logWarn("cache_warming.warmup.failed", attributes);
754
+ await stop();
755
+ return;
756
+ }
757
+ logInfo("cache_warming.warmup.completed", attributes);
758
+ await state.set(warmupsKey(conversationId, generation), message.cycle, IDLE_HORIZON_MS);
759
+ if (await state.get(snapshotKey(conversationId, generation))) await scheduleWarmup({
760
+ kind: "warmup",
761
+ conversationId,
762
+ cycle: message.cycle + 1,
763
+ generation
764
+ }, startedAtMs, warm);
765
+ });
766
+ }
767
+ export { segmentGapsKey as a, MINUTE_MS as c, gapSegment as d, createCacheWarmingRecorder as i, MIN_WARMUP_PREFIX_TOKENS as l, GLOBAL_GAPS_MAX as n, warmup_exports as o, GLOBAL_GAPS_TTL_MS as r, IDLE_HORIZON_MS as s, CONVERSATION_STATE_TTL_MS as t, NO_REPLY_GAP_MS as u };