@sentry/junior 0.287.0 → 0.289.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 (79) hide show
  1. package/dist/{adapter-CL-HUKgd.js → adapter-tE1wnl0T.js} +1 -1
  2. package/dist/{admin-C9urXVfi.js → admin-BmsPbmO_.js} +2 -2
  3. package/dist/{agent-runner-Bfnw551N.js → agent-runner-bvl8U5uH.js} +489 -165
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +7 -7
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +628 -238
  8. package/dist/{app-DBY5TnfY.d.ts → app-Cu454FXq.d.ts} +2 -2
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +550 -71
  11. package/dist/assistant-reply-1N9oxyyb.js +58 -0
  12. package/dist/{automation-DksGNDRO.js → automation-DWbjJltM.js} +2 -2
  13. package/dist/{background-compaction-queue-CYI909P5.js → background-compaction-queue-D36oCldp.js} +161 -90
  14. package/dist/{briefs-DaXiMWzT.js → briefs-CV-1qkXa.js} +3 -3
  15. package/dist/{catalog-runtime-BCIuBe4d.js → catalog-runtime-BNK4uJVZ.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-DHAy7XlP.js} +363 -8
  24. package/dist/{connections-BnIj0wtx.js → connections-C3VmH3cf.js} +7 -129
  25. package/dist/{conversation-E7ZPJx2H.js → conversation-CwC8K3RZ.js} +22 -5
  26. package/dist/{conversation-pending-messages-DVch6YQw.js → conversation-pending-messages-B0cuLReP.js} +1 -1
  27. package/dist/{conversation-privacy-DF1hW0ja.js → conversation-privacy-Bky_veSp.js} +1 -1
  28. package/dist/{credential-sync-CzMar9hq.js → credential-sync-dY9o0YSj.js} +28 -20
  29. package/dist/{db-DJ11eZqq.js → db-BS2Kql3j.js} +81 -46
  30. package/dist/{db-YDKKDxlh.d.ts → db-BebRmhsH.d.ts} +10 -2
  31. package/dist/{executor-BY9TB31g.js → executor-cc4nH86C.js} +125 -18
  32. package/dist/instrumentation.js +2 -2
  33. package/dist/{logging-BO5zU6Mt.js → logging-CtCJmt9p.js} +3 -2
  34. package/dist/{media-Cz1ZiV1U.js → media-BepyEUNm.js} +5 -1
  35. package/dist/{message-CsUbuEc8.js → message-C5VuRcP9.js} +9 -9
  36. package/dist/nitro.d.ts +1 -1
  37. package/dist/nitro.js +19 -41
  38. package/dist/{oauth-callback-server-hiDKK0_n.js → oauth-callback-server-KRrYUZ35.js} +2 -2
  39. package/dist/{projection-CL_YWeGf.js → projection-BFJG58TG.js} +448 -721
  40. package/dist/{prompt-BHOEQSmf.js → prompt-D15oftoL.js} +5 -5
  41. package/dist/{registry-BriFLnaJ.js → registry-C_JrgqUz.js} +1 -1
  42. package/dist/{resolve-Bt6GgAiA.js → resolve-Cn_7JfP-.js} +3 -3
  43. package/dist/{result-Bo1TZu0Q.js → result-CIbQFLp6.js} +16 -10
  44. package/dist/{runner-D3YeCQgt.js → runner-BwmaMJVO.js} +8 -8
  45. package/dist/{sandbox-egress-signals-CcnSPP4S.js → sandbox-egress-signals-BOQ8gn7i.js} +1 -1
  46. package/dist/{schedule-BTp__wrw.js → schedule-cP0AACm1.js} +11 -2
  47. package/dist/{schema-BWE3RJEB.js → schema-Bptz19Ja.js} +72 -14
  48. package/dist/{schema-C6fsEwjo.d.ts → schema-DQaFSkZZ.d.ts} +122 -3
  49. package/dist/{service-account-DiQQuuw7.js → service-account-AGw_pANb.js} +3 -3
  50. package/dist/{service-account-r6fl0b-9.js → service-account-CLZfF8O1.js} +3 -3
  51. package/dist/{session-stop-B2Nut40V.js → session-stop-CbzKf7UI.js} +84 -31
  52. package/dist/{skills-CD5aJdzg.js → skills-CcAJBquq.js} +2 -2
  53. package/dist/{spawn-CalgZQiu.js → spawn-BvAk2vTI.js} +5 -5
  54. package/dist/{stop-kujZLbi0.js → stop-BQU4u7la.js} +893 -519
  55. package/dist/{store-DdIEUL1q.js → store-DE7NJOvQ.js} +4 -16
  56. package/dist/{task-runner-D_RDr2Hu.js → task-runner-Q_7duP_T.js} +31 -27
  57. package/dist/{turn-failure-response-B5nV1Er-.js → turn-failure-response-aWZLfUM8.js} +18 -9
  58. package/dist/{validation-K4pqwoVZ.js → validation-BOoPeIJR.js} +1 -1
  59. package/dist/{version-DBvhk1X9.js → version-Db0MFy61.js} +1 -1
  60. package/dist/version.js +1 -1
  61. package/dist/{viewer-DrMmFUul.js → viewer-FFEFu9In.js} +4 -4
  62. package/dist/warmup-DDzrA9Gv.js +967 -0
  63. package/dist/{work-ljRoODGu.js → work-BBJK458E.js} +16 -15
  64. package/dist/{worker-CYO1Q0Js.js → worker-2iU5RFyq.js} +7 -31
  65. package/migrations/0089_conversation_paused_status.sql +3 -0
  66. package/migrations/0090_guardian_review_time_index.sql +20 -0
  67. package/migrations/0091_conversation_participant_unsubscribed_index.sql +20 -0
  68. package/migrations/0092_turn_metric_actor.sql +12 -0
  69. package/migrations/0093_participant_root_actor_backfill.sql +18 -0
  70. package/migrations/0094_conversation_delivery_paused_at.sql +1 -0
  71. package/migrations/meta/0089_snapshot.json +4372 -0
  72. package/migrations/meta/0090_snapshot.json +4388 -0
  73. package/migrations/meta/0091_snapshot.json +4410 -0
  74. package/migrations/meta/0092_snapshot.json +4446 -0
  75. package/migrations/meta/0093_snapshot.json +4446 -0
  76. package/migrations/meta/0094_snapshot.json +4452 -0
  77. package/migrations/meta/_journal.json +42 -0
  78. package/package.json +6 -5
  79. package/dist/assistant-reply-u_PRYzuz.js +0 -65
@@ -0,0 +1,967 @@
1
+ import { n as captureMessage, v as __exportAll } from "./sentry-BRTJqumy.js";
2
+ import { Ya as createPluginLogger, jo as createPluginCache, zn as getPlugins } from "./projection-BFJG58TG.js";
3
+ import { E as resolveGatewayModel, W as isProviderRetryError, i as getChatConfig } from "./config-DHAy7XlP.js";
4
+ import { E as withSpan, h as logWarn, m as logInfo, x as setSpanStatus } from "./logging-CtCJmt9p.js";
5
+ import { K as rootConversationIsArchived, a as getConversationStore, o as getDb, s as getSqlExecutor } from "./db-BS2Kql3j.js";
6
+ import { A as juniorConversations, C as isUserInstruction, j as juniorIdentities, w as juniorConversationEvents } from "./executor-cc4nH86C.js";
7
+ import { u as completeText } from "./prompt-D15oftoL.js";
8
+ import { r as getStateAdapter } from "./adapter-tE1wnl0T.js";
9
+ import { E as sendCacheWarmup } from "./background-compaction-queue-D36oCldp.js";
10
+ import { streamSimple } from "@earendil-works/pi-ai/compat";
11
+ import { promisify } from "node:util";
12
+ import { randomUUID } from "node:crypto";
13
+ import { and, desc, eq, inArray, sql } from "drizzle-orm";
14
+ import { constants, zstdCompress, zstdDecompress } from "node:zlib";
15
+ // src/chat/cache-warming/model.ts
16
+ /**
17
+ * Cost model for prompt cache warming.
18
+ *
19
+ * Ported from Lore's cache warmer (BYK/loreai,
20
+ * `packages/gateway/src/cache-warmer.ts`). The model estimates the chance that
21
+ * a person returns to an idle conversation before the cache expires. It then
22
+ * compares that chance with the cost of one more warmup.
23
+ */
24
+ /** One minute in milliseconds. */
25
+ const MINUTE_MS = 6e4;
26
+ /** Upper edges (ms) of the gap histogram bins. */
27
+ const GAP_BIN_EDGES_MS = [
28
+ 1e4,
29
+ 2e4,
30
+ 3e4,
31
+ 45e3,
32
+ MINUTE_MS,
33
+ 1.5 * MINUTE_MS,
34
+ 2 * MINUTE_MS,
35
+ 3 * MINUTE_MS,
36
+ 4 * MINUTE_MS,
37
+ 5 * MINUTE_MS,
38
+ 7 * MINUTE_MS,
39
+ 10 * MINUTE_MS,
40
+ 15 * MINUTE_MS,
41
+ 20 * MINUTE_MS,
42
+ 30 * MINUTE_MS,
43
+ 45 * MINUTE_MS,
44
+ 60 * MINUTE_MS,
45
+ 90 * MINUTE_MS,
46
+ 120 * MINUTE_MS,
47
+ 240 * MINUTE_MS,
48
+ Infinity
49
+ ];
50
+ const GAP_BIN_COUNT = GAP_BIN_EDGES_MS.length;
51
+ /** Gaps a conversation needs before its own gaps replace the global gaps. */
52
+ const BLEND_PSEUDOCOUNT = 20;
53
+ /**
54
+ * Gaps that a decision needs in total. With fewer, one gap sets the return
55
+ * chance for each Conversation of the segment, such as at launch or after
56
+ * the gap lists expire.
57
+ */
58
+ const MIN_GAP_SAMPLES = 20;
59
+ /** Below this prefix size, one cache miss costs too little to warm for. */
60
+ const MIN_WARMUP_PREFIX_TOKENS = 5e4;
61
+ /**
62
+ * Junior watches an idle period for this long. A person who replies later
63
+ * counts as a person who did not reply. The reply chance of a warmup counts
64
+ * only replies before this time. For a cache that outlives the horizon, this
65
+ * is less than the real chance, so Junior warms less, never more.
66
+ *
67
+ * The horizon message is signed when the idle period starts, and a queue
68
+ * signature is valid for 60 minutes (`QUEUE_SIGNATURE_MAX_AGE_MS`). The other
69
+ * 5 minutes let a late horizon still record its no-reply gap.
70
+ */
71
+ const IDLE_HORIZON_MS = 55 * MINUTE_MS;
72
+ /**
73
+ * Whether a failed warmup request counts as a miss for the provider breaker.
74
+ * A request that the provider rejects fails the same way for each
75
+ * Conversation, so it counts. A retryable failure, such as an overload or a
76
+ * timeout, says nothing about the cache, so it must not stop warming for
77
+ * every Conversation.
78
+ */
79
+ function warmupFailureCountsAsMiss(error) {
80
+ return !isProviderRetryError(error);
81
+ }
82
+ /** Gap that Junior records for an idle period with no reply in the horizon. */
83
+ const NO_REPLY_GAP_MS = 1440 * MINUTE_MS;
84
+ const BASE_WARMUP_MARGIN_MS = 45e3;
85
+ const MARGIN_PER_PREFIX_TOKEN_MS = .27;
86
+ const MAX_SIZE_MARGIN_MS = 9e4;
87
+ function binIndex(gapMs) {
88
+ return GAP_BIN_EDGES_MS.findIndex((edge) => gapMs < edge);
89
+ }
90
+ function histogramOf(gapsMs) {
91
+ const counts = Array.from({ length: GAP_BIN_COUNT }, () => 0);
92
+ for (const gap of gapsMs) counts[binIndex(gap)] += 1;
93
+ return {
94
+ counts,
95
+ total: gapsMs.length
96
+ };
97
+ }
98
+ function blendHistograms(conversation, global) {
99
+ if (conversation.total === 0 || global.total === 0) return conversation.total === 0 ? global : conversation;
100
+ const weight = Math.min(conversation.total / BLEND_PSEUDOCOUNT, 1);
101
+ return {
102
+ counts: conversation.counts.map((count, index) => weight * count / conversation.total + (1 - weight) * global.counts[index] / global.total),
103
+ total: 1
104
+ };
105
+ }
106
+ function survival(histogram, tMs) {
107
+ if (histogram.total === 0) return 1;
108
+ const index = binIndex(tMs);
109
+ let surviving = 0;
110
+ for (let i = index + 1; i < GAP_BIN_COUNT; i++) surviving += histogram.counts[i];
111
+ const binStart = index > 0 ? GAP_BIN_EDGES_MS[index - 1] : 0;
112
+ const fractionPast = Math.min(1, Math.max(0, (tMs - binStart) / (GAP_BIN_EDGES_MS[index] - binStart)));
113
+ surviving += histogram.counts[index] * (1 - fractionPast);
114
+ return surviving / histogram.total;
115
+ }
116
+ function returnProbability(histogram, idleMs, windowMs) {
117
+ const now = survival(histogram, idleMs);
118
+ if (now < .001) return 0;
119
+ return Math.max(0, (now - survival(histogram, idleMs + windowMs)) / now);
120
+ }
121
+ /**
122
+ * Return how long before cache expiry to send a warmup. The warmup refreshes
123
+ * the cache only if the provider reads the whole prefix before it expires. A
124
+ * larger prefix takes longer to send and read, and its cache blocks were
125
+ * written at slightly different times. So the margin grows with the prefix up
126
+ * to a fixed cap.
127
+ */
128
+ function warmupMarginMs(prefixTokens) {
129
+ return BASE_WARMUP_MARGIN_MS + Math.min(Math.max(0, prefixTokens) * MARGIN_PER_PREFIX_TOKEN_MS, MAX_SIZE_MARGIN_MS);
130
+ }
131
+ /**
132
+ * Pick the gap histogram for an idle period. Return chances differ most by
133
+ * who started the Turn and by how many Turns the Conversation had before it.
134
+ * Turns that no person started rarely get a quick reply. In 30 days of
135
+ * production data, segments by these two keys saved more than one histogram.
136
+ * Local time of day did not improve the result, so it is not a key.
137
+ *
138
+ * The work state lets the histograms learn how often anything returns after
139
+ * the work is done. An event does not restore an archived Conversation, so
140
+ * most returns to one are events, not people. Its segment has only the work
141
+ * state, which keeps the number of segments small.
142
+ */
143
+ function gapSegment(input) {
144
+ if (input.archived) return `archived:${input.workState}`;
145
+ const depth = input.endedTurns === 0 ? "1" : input.endedTurns < 3 ? "2-3" : "4+";
146
+ return `${input.userActor ? "user" : "system"}:${depth}:${input.workState}`;
147
+ }
148
+ /**
149
+ * Decide whether to send the next warmup.
150
+ *
151
+ * A warmup costs one cache read of the prefix. A return to a warm cache saves
152
+ * one write minus one read. So warming pays when the expected returns per
153
+ * warmup are above read/(write − read). Earlier warmups are already paid, so
154
+ * the threshold is the same for each warmup.
155
+ *
156
+ * One warmup alone can be useless when people return a little after the next
157
+ * TTL, while two or three warmups in a row would reach them. So the decision
158
+ * compares plans of 1, 2, ... warmups up to the horizon. Each plan sends its
159
+ * next warmup only while nobody returned. Junior warms when the best plan
160
+ * pays, and decides again at the next warmup.
161
+ */
162
+ function decideWarmup(input) {
163
+ const savedPerReturn = input.cacheWritePrice - input.cacheReadPrice;
164
+ const threshold = savedPerReturn > 0 ? Math.min(input.cacheReadPrice / savedPerReturn, 1) : 1;
165
+ const conversation = histogramOf(input.conversationGapsMs);
166
+ const global = histogramOf(input.globalGapsMs);
167
+ const histogram = blendHistograms(conversation, global);
168
+ const probability = returnProbability(histogram, input.idleMs, Math.min(input.cacheTtlMs, IDLE_HORIZON_MS - input.idleMs));
169
+ const perWarmup = returnsPerWarmup(histogram, input.idleMs, input.cacheExpiryIdleMs, input.cacheTtlMs, input.prefixTokens);
170
+ const decision = (reason) => ({
171
+ warm: reason === "warm",
172
+ reason,
173
+ returnProbability: probability,
174
+ returnsPerWarmup: perWarmup,
175
+ threshold
176
+ });
177
+ if (input.prefixTokens < 5e4) return decision("prefix_too_small");
178
+ if (threshold >= 1) return decision("no_savings");
179
+ if (input.idleMs >= 33e5) return decision("horizon");
180
+ if (conversation.total + global.total < MIN_GAP_SAMPLES) return decision("few_gaps");
181
+ return decision(perWarmup >= threshold ? "warm" : "unlikely_return");
182
+ }
183
+ function returnsPerWarmup(histogram, idleMs, cacheExpiryIdleMs, ttlMs, prefixTokens) {
184
+ const now = survival(histogram, idleMs);
185
+ const intervalMs = ttlMs - warmupMarginMs(prefixTokens);
186
+ if (now < .001 || intervalMs <= 0) return 0;
187
+ const leftAtExpiry = survival(histogram, Math.min(cacheExpiryIdleMs, IDLE_HORIZON_MS));
188
+ let best = 0;
189
+ let warmups = 0;
190
+ for (let startMs = idleMs; startMs < IDLE_HORIZON_MS; startMs += intervalMs) {
191
+ warmups += survival(histogram, startMs) / now;
192
+ const endMs = Math.min(startMs + ttlMs, IDLE_HORIZON_MS);
193
+ const returns = Math.max(0, leftAtExpiry - survival(histogram, endMs)) / now;
194
+ best = Math.max(best, returns / warmups);
195
+ }
196
+ return best;
197
+ }
198
+ // src/chat/cache-warming/request.ts
199
+ const KEY_PREFIX = "junior:cache_warming";
200
+ const CACHE_RETENTION = "short";
201
+ const REFRESHED_READ_FRACTION = .9;
202
+ const BREAKER_OUTCOMES_MAX = 20;
203
+ const BREAKER_MAX_MISSES = 10;
204
+ const BREAKER_OUTCOMES_TTL_MS = 360 * MINUTE_MS;
205
+ const BREAKER_OPEN_TTL_MS = 1440 * MINUTE_MS;
206
+ const breakerOutcomesKey = (provider) => `${KEY_PREFIX}:breaker:${provider}:outcomes`;
207
+ const breakerOpenKey = (provider) => `${KEY_PREFIX}:breaker:${provider}:open`;
208
+ const providerOf = (modelId) => modelId.split("/")[0] ?? "";
209
+ /** Connect the state adapter that holds cache warming state. */
210
+ async function connectedState() {
211
+ const state = getStateAdapter();
212
+ await state.connect();
213
+ return state;
214
+ }
215
+ const CACHE_TTL_MS = {
216
+ anthropic: 5 * MINUTE_MS,
217
+ alibaba: 5 * MINUTE_MS,
218
+ openai: 30 * MINUTE_MS
219
+ };
220
+ /**
221
+ * Return true when warmups can refresh the prompt cache of this request.
222
+ * Warming pays only when a cache write costs more than a read. Pi adds a
223
+ * thinking budget to the one-token output limit on the Anthropic Messages API
224
+ * for models without adaptive thinking. Then a warmup could cost as much as a
225
+ * short answer, and a smaller budget would miss the cached messages.
226
+ */
227
+ function supportsWarming(request) {
228
+ const { model, reasoning } = request;
229
+ const budgetThinking = reasoning !== void 0 && model.api === "anthropic-messages" && model.compat?.forceAdaptiveThinking !== true;
230
+ return CACHE_TTL_MS[providerOf(model.id)] !== void 0 && model.cost.cacheRead > 0 && model.cost.cacheWrite > model.cost.cacheRead && !budgetThinking && request.cacheRetention === "short";
231
+ }
232
+ /** Return the cache TTL of a request that Junior can warm. */
233
+ function cacheTtlMs(request) {
234
+ return supportsWarming(request) ? CACHE_TTL_MS[providerOf(request.model.id)] : void 0;
235
+ }
236
+ /** Return the cached prefix tokens of a finished model request. */
237
+ function cachedPrefixTokens(message) {
238
+ return message.usage.cacheRead + message.usage.cacheWrite;
239
+ }
240
+ /**
241
+ * Return when the cache that a request at `requestStartedAtMs` read or wrote
242
+ * expires, and the delay until the warmup that refreshes it.
243
+ */
244
+ function warmupTiming(requestStartedAtMs, prefixTokens, ttlMs) {
245
+ const cacheExpiresAtMs = requestStartedAtMs + ttlMs;
246
+ return {
247
+ cacheExpiresAtMs,
248
+ delayMs: cacheExpiresAtMs - warmupMarginMs(prefixTokens) - Date.now()
249
+ };
250
+ }
251
+ const LATE_WARMUP_MS = 1e4;
252
+ /**
253
+ * Return true when a warmup is too late to refresh the cache. The cache is
254
+ * gone, so the warmup must not run or count as a miss.
255
+ */
256
+ function warmupTooLate(cacheExpiresAtMs) {
257
+ return Date.now() + LATE_WARMUP_MS >= cacheExpiresAtMs;
258
+ }
259
+ /**
260
+ * Return true while too many recent warmups of the model's provider missed,
261
+ * so its warming is off.
262
+ */
263
+ async function breakerOpen(state, modelId) {
264
+ return await state.get(breakerOpenKey(providerOf(modelId))) === true;
265
+ }
266
+ async function countOutcome(state, modelId, miss) {
267
+ const provider = providerOf(modelId);
268
+ await state.appendToList(breakerOutcomesKey(provider), miss ? 1 : 0, {
269
+ maxLength: BREAKER_OUTCOMES_MAX,
270
+ ttlMs: BREAKER_OUTCOMES_TTL_MS
271
+ });
272
+ if (!miss) return;
273
+ const outcomes = await state.getList(breakerOutcomesKey(provider));
274
+ const misses = outcomes.filter((outcome) => outcome === 1).length;
275
+ 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", {
276
+ level: "error",
277
+ fingerprint: ["cache_warming.breaker.opened", provider],
278
+ tags: { "gen_ai.request.model": modelId },
279
+ extra: {
280
+ "app.cache_warming.misses": misses,
281
+ "app.cache_warming.outcomes": outcomes.length
282
+ }
283
+ });
284
+ }
285
+ /**
286
+ * Send one warmup: the same request with a one-token output limit. Count its
287
+ * outcome for the breaker, and report a miss to Sentry. A rejected request
288
+ * counts as a miss and rethrows, because it fails the same way for each
289
+ * Conversation.
290
+ */
291
+ async function sendWarmup(state, params) {
292
+ const { conversationId, modelId, context, prefixTokens } = params;
293
+ const { message: result } = await completeText({
294
+ modelId,
295
+ system: context.systemPrompt,
296
+ messages: context.messages,
297
+ ...context.tools ? { tools: context.tools } : void 0,
298
+ ...params.reasoning ? { thinkingLevel: params.reasoning } : void 0,
299
+ cacheRetention: CACHE_RETENTION,
300
+ maxTokens: 1,
301
+ messageAttributeMode: "metadata",
302
+ metadata: { conversationId },
303
+ operation: "cache_warmup",
304
+ cost: { conversationId },
305
+ sessionId: conversationId
306
+ }).catch(async (error) => {
307
+ if (warmupFailureCountsAsMiss(error)) await countOutcome(state, modelId, true);
308
+ throw error;
309
+ });
310
+ const attributes = {
311
+ "app.cost.total_usd": result.usage.cost.total,
312
+ "gen_ai.usage.cache_read.input_tokens": result.usage.cacheRead,
313
+ "gen_ai.usage.cache_creation.input_tokens": result.usage.cacheWrite
314
+ };
315
+ const refreshed = result.usage.cacheRead >= prefixTokens * REFRESHED_READ_FRACTION;
316
+ if (!refreshed) captureMessage("Cache warmup missed the cache", {
317
+ level: "warning",
318
+ fingerprint: ["cache_warming.warmup.missed", modelId],
319
+ tags: { "gen_ai.request.model": modelId },
320
+ extra: { "app.cache_warming.read_fraction": result.usage.cacheRead / prefixTokens }
321
+ });
322
+ await countOutcome(state, modelId, !refreshed);
323
+ return {
324
+ refreshed,
325
+ attributes
326
+ };
327
+ }
328
+ // src/chat/cache-warming/tool-wait.ts
329
+ const TOOL_WAIT_GAPS_KEY = `${KEY_PREFIX}:gaps:tool_wait`;
330
+ const TOOL_WAIT_GAPS_MAX = 2e3;
331
+ const TOOL_WAIT_GAPS_TTL_MS = 43200 * MINUTE_MS;
332
+ const MIN_RECORDED_TOOL_WAIT_MS = 2 * MINUTE_MS;
333
+ /** Create the tool wait warmer of one agent run. */
334
+ function createToolWaitWarmer(conversationId) {
335
+ let timer;
336
+ let waiting;
337
+ let returnedAtMs;
338
+ let generation = 0;
339
+ const schedule = (cache, refreshedAtMs, cycle) => {
340
+ const current = generation;
341
+ const { cacheExpiresAtMs, delayMs } = warmupTiming(refreshedAtMs, cache.prefixTokens, cache.ttlMs);
342
+ timer = setTimeout(() => {
343
+ timer = void 0;
344
+ warm(cache, cacheExpiresAtMs, cycle, current);
345
+ }, Math.max(0, delayMs));
346
+ timer.unref?.();
347
+ };
348
+ const warm = (cache, cacheExpiresAtMs, cycle, current) => {
349
+ const { request, prefixTokens } = cache;
350
+ const attributes = {
351
+ "app.cache_warming.cycle": cycle,
352
+ "app.cache_warming.prefix_tokens": prefixTokens,
353
+ "app.cache_warming.trigger": "tool_wait"
354
+ };
355
+ return withSpan("cache_warming.warmup", "cache_warming.warmup", {
356
+ conversationId,
357
+ modelId: request.model.id
358
+ }, async (setSpanAttributes) => {
359
+ const setOutcome = (outcome, extra = {}) => setSpanAttributes({
360
+ ...attributes,
361
+ ...extra,
362
+ "app.cache_warming.outcome": outcome
363
+ });
364
+ const skip = (reason) => {
365
+ const skipReason = { "app.cache_warming.skip_reason": reason };
366
+ logInfo("cache_warming.warmup.skipped", {
367
+ ...attributes,
368
+ ...skipReason
369
+ });
370
+ setOutcome("skipped", skipReason);
371
+ };
372
+ if (warmupTooLate(cacheExpiresAtMs)) {
373
+ skip("cache_expired");
374
+ return;
375
+ }
376
+ try {
377
+ const state = await connectedState();
378
+ if (await breakerOpen(state, request.model.id)) {
379
+ skip("breaker_open");
380
+ return;
381
+ }
382
+ const decision = decideWarmup({
383
+ conversationGapsMs: [],
384
+ globalGapsMs: await state.getList(TOOL_WAIT_GAPS_KEY),
385
+ idleMs: Date.now() - request.startedAtMs,
386
+ cacheExpiryIdleMs: cacheExpiresAtMs - request.startedAtMs,
387
+ cacheTtlMs: cache.ttlMs,
388
+ prefixTokens,
389
+ cacheReadPrice: request.model.cost.cacheRead,
390
+ cacheWritePrice: request.model.cost.cacheWrite
391
+ });
392
+ attributes["app.cache_warming.return_probability"] = decision.returnProbability;
393
+ attributes["app.cache_warming.returns_per_warmup"] = decision.returnsPerWarmup;
394
+ attributes["app.cache_warming.threshold"] = decision.threshold;
395
+ if (current !== generation) {
396
+ setOutcome("skipped", { "app.cache_warming.skip_reason": "stopped" });
397
+ return;
398
+ }
399
+ if (!decision.warm) {
400
+ skip(decision.reason);
401
+ return;
402
+ }
403
+ const startedAtMs = Date.now();
404
+ const warmup = await sendWarmup(state, {
405
+ conversationId,
406
+ modelId: request.model.id,
407
+ context: request.context,
408
+ ...request.reasoning ? { reasoning: request.reasoning } : void 0,
409
+ prefixTokens
410
+ });
411
+ Object.assign(attributes, warmup.attributes);
412
+ if (!warmup.refreshed) {
413
+ logWarn("cache_warming.warmup.failed", attributes);
414
+ setOutcome("missed");
415
+ return;
416
+ }
417
+ logInfo("cache_warming.warmup.completed", attributes);
418
+ setOutcome("completed");
419
+ if (current === generation) schedule(cache, startedAtMs, cycle + 1);
420
+ } catch (error) {
421
+ logWarn("cache_warming.warmup.failed", {
422
+ ...attributes,
423
+ "exception.message": error instanceof Error ? error.message : String(error)
424
+ });
425
+ setOutcome("failed", { "error.type": error instanceof Error ? error.name : typeof error });
426
+ setSpanStatus("error");
427
+ }
428
+ }, attributes);
429
+ };
430
+ const stop = () => {
431
+ generation += 1;
432
+ clearTimeout(timer);
433
+ timer = void 0;
434
+ };
435
+ const recordWait = async (waitMs) => {
436
+ if (waitMs < MIN_RECORDED_TOOL_WAIT_MS) return;
437
+ await (await connectedState()).appendToList(TOOL_WAIT_GAPS_KEY, waitMs, {
438
+ maxLength: TOOL_WAIT_GAPS_MAX,
439
+ ttlMs: TOOL_WAIT_GAPS_TTL_MS
440
+ });
441
+ };
442
+ return {
443
+ async record(request, message) {
444
+ stop();
445
+ const previous = waiting;
446
+ waiting = message.stopReason === "toolUse" ? request : void 0;
447
+ returnedAtMs = void 0;
448
+ const prefixTokens = cachedPrefixTokens(message);
449
+ const ttlMs = cacheTtlMs(request);
450
+ if (waiting && prefixTokens >= 5e4 && ttlMs !== void 0) schedule({
451
+ request,
452
+ prefixTokens,
453
+ ttlMs
454
+ }, request.startedAtMs, 1);
455
+ if (previous) await recordWait(request.startedAtMs - previous.startedAtMs);
456
+ },
457
+ stop,
458
+ toolsReturned() {
459
+ stop();
460
+ if (waiting) returnedAtMs ??= Date.now();
461
+ },
462
+ async end() {
463
+ stop();
464
+ const open = waiting;
465
+ const returned = returnedAtMs;
466
+ waiting = void 0;
467
+ returnedAtMs = void 0;
468
+ if (!open) return;
469
+ if (returned !== void 0) {
470
+ await recordWait(returned - open.startedAtMs);
471
+ return;
472
+ }
473
+ if (Date.now() - open.startedAtMs >= MIN_RECORDED_TOOL_WAIT_MS) await recordWait(NO_REPLY_GAP_MS);
474
+ }
475
+ };
476
+ }
477
+ // src/api/conversations/user-message-activity.ts
478
+ /**
479
+ * The newest event of one type in the outer Conversation that matches the
480
+ * filter. It walks the message role or user message time index from the
481
+ * newest event. The user message index has only matching entries, so that
482
+ * read stops at the first one.
483
+ */
484
+ function latestEventAt(db, type, filter) {
485
+ return db.select({ createdAt: juniorConversationEvents.createdAt }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, juniorConversations.conversationId), eq(juniorConversationEvents.type, type), filter)).orderBy(desc(juniorConversationEvents.createdAt), desc(juniorConversationEvents.seq)).limit(1).as(`latest_${type}`);
486
+ }
487
+ /** Read the latest true user message time for each selected conversation. */
488
+ async function readLastUserMessageAtByConversation(db, conversationIds) {
489
+ if (conversationIds.length === 0) return /* @__PURE__ */ new Map();
490
+ const payload = juniorConversationEvents.payload;
491
+ const instruction = latestEventAt(db, "user_message", isUserInstruction(payload));
492
+ const authorKind = sql`(${db.select({ kind: juniorIdentities.kind }).from(juniorIdentities).where(eq(juniorIdentities.id, juniorConversationEvents.actorIdentityId))})`;
493
+ const message = latestEventAt(db, "message", sql`${payload}->>'role' = 'user' and ${authorKind} = 'user'`);
494
+ const rows = await db.select({
495
+ conversationId: juniorConversations.conversationId,
496
+ instructionAt: instruction.createdAt,
497
+ messageAt: message.createdAt
498
+ }).from(juniorConversations).leftJoinLateral(instruction, sql`true`).leftJoinLateral(message, sql`true`).where(inArray(juniorConversations.conversationId, conversationIds));
499
+ const result = /* @__PURE__ */ new Map();
500
+ for (const { conversationId, instructionAt, messageAt } of rows) {
501
+ const times = [instructionAt, messageAt].flatMap((at) => at ? [at.getTime()] : []);
502
+ if (times.length > 0) result.set(conversationId, new Date(Math.max(...times)).toISOString());
503
+ }
504
+ return result;
505
+ }
506
+ // src/chat/plugins/unfinished-work.ts
507
+ /**
508
+ * Decide whether a conversation's work finished at or before the cutoff,
509
+ * with no person's message after it finished. Auto-archive passes now minus
510
+ * the grace period. A conversation without plugin-reported work has nothing
511
+ * to wait for, so it counts as done here; cache warming needs reported work
512
+ * and checks `assignedWork` itself.
513
+ */
514
+ function isConversationWorkDone(conversation, cutoffMs) {
515
+ if (conversation.unfinishedWork) return false;
516
+ if (!conversation.assignedWork) return true;
517
+ const finishedAt = Date.parse(conversation.finishedWorkAt ?? "");
518
+ if (!Number.isFinite(finishedAt) || finishedAt > cutoffMs) return false;
519
+ const lastUserMessageAt = Date.parse(conversation.lastUserMessageAt ?? "");
520
+ return !(Number.isFinite(lastUserMessageAt) && lastUserMessageAt > finishedAt);
521
+ }
522
+ /**
523
+ * Map each candidate and each child of a candidate root to the candidate it
524
+ * counts for. A child agent runs under its own conversation id, so a plugin
525
+ * links the work that the child does, such as a pull request, to the child.
526
+ */
527
+ async function readWorkOwners(conversationIds) {
528
+ const owners = new Map(conversationIds.map((id) => [id, id]));
529
+ const children = await getDb().select({
530
+ conversationId: juniorConversations.conversationId,
531
+ rootConversationId: juniorConversations.rootConversationId
532
+ }).from(juniorConversations).where(inArray(juniorConversations.rootConversationId, conversationIds));
533
+ for (const child of children) if (child.rootConversationId && !owners.has(child.conversationId)) owners.set(child.conversationId, child.rootConversationId);
534
+ return owners;
535
+ }
536
+ /**
537
+ * Return assigned and unfinished plugin work for the candidate conversations.
538
+ * Work in a child conversation counts for its root candidate. Feed Priority
539
+ * combines these signals with conversation activity on the host.
540
+ */
541
+ async function listConversationWork(conversationIds) {
542
+ if (conversationIds.length === 0) return {
543
+ assignedIds: [],
544
+ failed: false,
545
+ finishedAtById: {},
546
+ unfinishedIds: []
547
+ };
548
+ const owners = await readWorkOwners(conversationIds);
549
+ const queriedIds = [...owners.keys()];
550
+ const assigned = /* @__PURE__ */ new Set();
551
+ const finishedAtById = /* @__PURE__ */ new Map();
552
+ const unfinished = /* @__PURE__ */ new Set();
553
+ let failed = false;
554
+ for (const plugin of getPlugins()) {
555
+ const hook = plugin.hooks?.unfinishedWork;
556
+ if (!hook) continue;
557
+ try {
558
+ const result = await hook({
559
+ conversationIds: queriedIds,
560
+ db: getDb(),
561
+ log: createPluginLogger(plugin.manifest.name),
562
+ plugin: { name: plugin.manifest.name },
563
+ cache: createPluginCache(plugin.manifest.name)
564
+ });
565
+ for (const workId of result.conversationIds) {
566
+ const conversationId = owners.get(workId);
567
+ if (!conversationId) continue;
568
+ unfinished.add(conversationId);
569
+ assigned.add(conversationId);
570
+ }
571
+ for (const workId of result.assignedConversationIds ?? []) {
572
+ const conversationId = owners.get(workId);
573
+ if (conversationId) assigned.add(conversationId);
574
+ }
575
+ for (const [workId, finishedAt] of Object.entries(result.finishedWorkAtByConversationId ?? {})) {
576
+ const conversationId = owners.get(workId);
577
+ if (!conversationId) continue;
578
+ const time = Date.parse(finishedAt);
579
+ if (!Number.isFinite(time)) continue;
580
+ const current = finishedAtById.get(conversationId);
581
+ if (!current || time > Date.parse(current)) finishedAtById.set(conversationId, finishedAt);
582
+ }
583
+ } catch (error) {
584
+ failed = true;
585
+ logWarn("plugin.unfinished_work.hook.failed", {
586
+ "app.plugin.name": plugin.manifest.name,
587
+ "exception.message": error instanceof Error ? error.message : String(error)
588
+ });
589
+ }
590
+ }
591
+ return {
592
+ assignedIds: conversationIds.filter((conversationId) => assigned.has(conversationId)),
593
+ failed,
594
+ finishedAtById: Object.fromEntries(conversationIds.flatMap((conversationId) => {
595
+ const finishedAt = finishedAtById.get(conversationId);
596
+ return finishedAt ? [[conversationId, finishedAt]] : [];
597
+ })),
598
+ unfinishedIds: conversationIds.filter((conversationId) => unfinished.has(conversationId))
599
+ };
600
+ }
601
+ // src/chat/cache-warming/work-state.ts
602
+ /**
603
+ * Read the plugin work state and the archive state of a Conversation when an
604
+ * idle period starts that Junior can warm. Work of child Conversations counts
605
+ * for their root. A child counts as archived when it or its root is: a manual
606
+ * archive also archives the children, but auto-archive sets only the root.
607
+ */
608
+ async function readSegmentState(conversationId, nowMs) {
609
+ const [work, conversation, rootArchived] = await Promise.all([
610
+ listConversationWork([conversationId]),
611
+ getConversationStore().get({ conversationId }),
612
+ rootConversationIsArchived(getSqlExecutor(), conversationId)
613
+ ]);
614
+ const archived = rootArchived || conversation?.archivedAtMs !== void 0;
615
+ if (work.failed || !work.assignedIds.includes(conversationId)) return {
616
+ workState: "none",
617
+ archived
618
+ };
619
+ if (work.unfinishedIds.includes(conversationId)) return {
620
+ workState: "open",
621
+ archived
622
+ };
623
+ const lastUserMessageAt = (await readLastUserMessageAtByConversation(getDb(), [conversationId])).get(conversationId);
624
+ return {
625
+ workState: isConversationWorkDone({
626
+ assignedWork: true,
627
+ finishedWorkAt: work.finishedAtById[conversationId],
628
+ lastUserMessageAt
629
+ }, nowMs) ? "done" : "none",
630
+ archived
631
+ };
632
+ }
633
+ // src/chat/cache-warming/warmup.ts
634
+ /**
635
+ * Prompt cache warming for idle Conversations.
636
+ *
637
+ * After a turn ends, the next human message often arrives after the short
638
+ * prompt cache TTL. Then the full history is written to the cache again. A
639
+ * warmup sends the same request again with a one-token output limit before
640
+ * the cache expires. The provider reads the cached prefix and refreshes its
641
+ * TTL. `model.ts` owns the cost model.
642
+ *
643
+ * Each idle period gets one recorded reply gap, so the model also sees the
644
+ * people who do not reply. A reply records its gap. A delayed `horizon`
645
+ * message records `NO_REPLY_GAP_MS` when no reply came in the idle horizon.
646
+ *
647
+ * Only a Turn writes the Conversation state. Warmups and the horizon run
648
+ * while the next Turn can start, so they write only keys of their own idle
649
+ * period (`generation`): the snapshot, the warmup count, and the gap claim.
650
+ * Work for an old idle period then cannot change a newer one.
651
+ */
652
+ var warmup_exports = /* @__PURE__ */ __exportAll({
653
+ CONVERSATION_STATE_TTL_MS: () => CONVERSATION_STATE_TTL_MS,
654
+ GLOBAL_GAPS_MAX: () => GLOBAL_GAPS_MAX,
655
+ GLOBAL_GAPS_TTL_MS: () => GLOBAL_GAPS_TTL_MS,
656
+ createCacheWarmingRecorder: () => createCacheWarmingRecorder,
657
+ runCacheWarmup: () => runCacheWarmup,
658
+ segmentGapsKey: () => segmentGapsKey
659
+ });
660
+ const zstdCompress$1 = promisify(zstdCompress);
661
+ const zstdDecompress$1 = promisify(zstdDecompress);
662
+ const SNAPSHOT_ZSTD_PARAMS = { params: { [constants.ZSTD_c_compressionLevel]: 1 } };
663
+ /** Gaps kept in each segment list. */
664
+ const GLOBAL_GAPS_MAX = 2e3;
665
+ /** A segment list expires this long after its last gap. */
666
+ const GLOBAL_GAPS_TTL_MS = 43200 * MINUTE_MS;
667
+ const CONVERSATION_GAPS_MAX = 50;
668
+ /** The Turn count of a Conversation resets after this long with no call. */
669
+ const CONVERSATION_STATE_TTL_MS = 10080 * MINUTE_MS;
670
+ const MAX_SNAPSHOT_BYTES = 1048576;
671
+ /** State list of the recent reply gaps (ms) of one `gapSegment`. */
672
+ const segmentGapsKey = (segment) => `${KEY_PREFIX}:gaps:${segment}`;
673
+ const conversationKey = (conversationId) => `${KEY_PREFIX}:conversation:${conversationId}`;
674
+ /**
675
+ * Recent reply gaps (ms) of the idle periods of this Conversation, per
676
+ * `gapSegment`. A person's quick replies must not set the return chance of an
677
+ * idle period that a system Turn started.
678
+ */
679
+ const conversationGapsKey = (conversationId, segment) => `${KEY_PREFIX}:gaps:conversation:${conversationId}:${segment}`;
680
+ const snapshotKey = (conversationId, generation) => `${KEY_PREFIX}:snapshot:${conversationId}:${generation}`;
681
+ /** Warmups that completed in the idle period. */
682
+ const warmupsKey = (conversationId, generation) => `${KEY_PREFIX}:warmups:${conversationId}:${generation}`;
683
+ /** Set by the first of the reply and the horizon to record the gap. */
684
+ const gapClaimKey = (conversationId, generation) => `${KEY_PREFIX}:gap_claim:${conversationId}:${generation}`;
685
+ const segmentAttributes = (warm) => ({
686
+ "app.cache_warming.work_state": warm.workState,
687
+ "app.cache_warming.archived": warm.archived
688
+ });
689
+ async function scheduleWarmup(message, requestStartedAtMs, warm) {
690
+ const { cacheExpiresAtMs, delayMs } = warmupTiming(requestStartedAtMs, warm.prefixTokens, warm.cacheTtlMs);
691
+ await sendCacheWarmup({
692
+ ...message,
693
+ cacheExpiresAtMs
694
+ }, delayMs);
695
+ }
696
+ function snapshotContext(context) {
697
+ return {
698
+ ...context.systemPrompt !== void 0 ? { systemPrompt: context.systemPrompt } : void 0,
699
+ messages: context.messages,
700
+ ...context.tools ? { tools: context.tools.map((tool) => ({
701
+ name: tool.name,
702
+ description: tool.description,
703
+ parameters: tool.parameters,
704
+ ...tool.constrainedSampling !== void 0 ? { constrainedSampling: tool.constrainedSampling } : void 0
705
+ })) } : void 0
706
+ };
707
+ }
708
+ async function recordGap(state, conversationId, generation, warm, gapMs) {
709
+ if (!await state.setIfNotExists(gapClaimKey(conversationId, generation), true, CONVERSATION_STATE_TTL_MS)) return;
710
+ await state.appendToList(segmentGapsKey(warm.segment), gapMs, {
711
+ maxLength: GLOBAL_GAPS_MAX,
712
+ ttlMs: GLOBAL_GAPS_TTL_MS
713
+ });
714
+ await state.appendToList(conversationGapsKey(conversationId, warm.segment), gapMs, {
715
+ maxLength: CONVERSATION_GAPS_MAX,
716
+ ttlMs: CONVERSATION_STATE_TTL_MS
717
+ });
718
+ }
719
+ async function startIdlePeriod(state, conversationId, request, message, turn) {
720
+ const idle = {
721
+ generation: randomUUID(),
722
+ sinceMs: request.startedAtMs
723
+ };
724
+ const prefixTokens = cachedPrefixTokens(message);
725
+ const ttlMs = cacheTtlMs(request);
726
+ if (ttlMs === void 0 || prefixTokens < 5e4) return idle;
727
+ const snapshot = (await zstdCompress$1(JSON.stringify(snapshotContext(request.context)), SNAPSHOT_ZSTD_PARAMS)).toString("base64");
728
+ if (snapshot.length > MAX_SNAPSHOT_BYTES) {
729
+ logInfo("cache_warming.snapshot.skipped", {
730
+ "app.cache_warming.prefix_tokens": prefixTokens,
731
+ "app.cache_warming.snapshot_bytes": snapshot.length
732
+ });
733
+ return idle;
734
+ }
735
+ const segmentState = await readSegmentState(conversationId, Date.now());
736
+ await state.set(snapshotKey(conversationId, idle.generation), snapshot, IDLE_HORIZON_MS);
737
+ return {
738
+ ...idle,
739
+ warm: {
740
+ segment: gapSegment({
741
+ ...turn,
742
+ ...segmentState
743
+ }),
744
+ ...segmentState,
745
+ modelId: request.model.id,
746
+ prefixTokens,
747
+ cacheTtlMs: ttlMs,
748
+ ...request.reasoning ? { reasoning: request.reasoning } : void 0
749
+ }
750
+ };
751
+ }
752
+ async function recordModelCall(conversationId, userActor, request, message) {
753
+ const state = await connectedState();
754
+ const previous = await state.get(conversationKey(conversationId));
755
+ const idle = previous?.idle;
756
+ if (idle?.warm) {
757
+ const gapMs = request.startedAtMs - idle.sinceMs;
758
+ if (gapMs > 0) await recordGap(state, conversationId, idle.generation, idle.warm, gapMs);
759
+ await state.delete(snapshotKey(conversationId, idle.generation));
760
+ const warmups = await state.get(warmupsKey(conversationId, idle.generation)) ?? 0;
761
+ if (warmups > 0) logInfo("cache_warming.conversation.returned", {
762
+ "app.cache_warming.gap_ms": gapMs,
763
+ "app.cache_warming.prefix_tokens": idle.warm.prefixTokens,
764
+ "app.cache_warming.warmup_count": warmups,
765
+ ...segmentAttributes(idle.warm),
766
+ "gen_ai.usage.cache_read.input_tokens": message.usage.cacheRead,
767
+ "gen_ai.usage.cache_creation.input_tokens": message.usage.cacheWrite
768
+ });
769
+ }
770
+ const endedTurns = previous?.endedTurns ?? 0;
771
+ const next = message.stopReason === "stop" ? {
772
+ endedTurns: endedTurns + 1,
773
+ idle: await startIdlePeriod(state, conversationId, request, message, {
774
+ userActor,
775
+ endedTurns
776
+ })
777
+ } : { endedTurns };
778
+ if (!idle && !next.idle) return;
779
+ await state.set(conversationKey(conversationId), next, CONVERSATION_STATE_TTL_MS);
780
+ if (next.idle?.warm) {
781
+ const { generation } = next.idle;
782
+ await sendCacheWarmup({
783
+ kind: "horizon",
784
+ conversationId,
785
+ generation
786
+ }, request.startedAtMs + IDLE_HORIZON_MS - Date.now());
787
+ await scheduleWarmup({
788
+ kind: "warmup",
789
+ conversationId,
790
+ cycle: 1,
791
+ generation
792
+ }, request.startedAtMs, next.idle.warm);
793
+ }
794
+ }
795
+ async function stopIdleWarmups(conversationId) {
796
+ try {
797
+ const state = await connectedState();
798
+ const idle = (await state.get(conversationKey(conversationId)))?.idle;
799
+ if (idle?.warm) await state.delete(snapshotKey(conversationId, idle.generation));
800
+ } catch (error) {
801
+ logWarn("cache_warming.idle_period.stop_failed", { "exception.message": error instanceof Error ? error.message : String(error) });
802
+ }
803
+ }
804
+ /**
805
+ * Create a recorder for one agent run. `userActor` is true when a person
806
+ * started the Turn. A failure to record only loses cache warming, so it is
807
+ * logged and does not stop the run.
808
+ */
809
+ function createCacheWarmingRecorder(conversationId, userActor) {
810
+ let lastRequest;
811
+ let idleEnded = false;
812
+ let warmupsStopped;
813
+ const toolWait = createToolWaitWarmer(conversationId);
814
+ return {
815
+ wrap: (base = streamSimple) => (model, context, options) => {
816
+ if (!warmupsStopped && getChatConfig().cacheWarmingEnabled) warmupsStopped = stopIdleWarmups(conversationId);
817
+ toolWait.stop();
818
+ const cacheRetention = options?.cacheRetention ?? (getChatConfig().cacheWarmingEnabled ? "short" : void 0);
819
+ lastRequest = {
820
+ model,
821
+ context: {
822
+ ...context,
823
+ messages: [...context.messages]
824
+ },
825
+ ...options?.reasoning ? { reasoning: options.reasoning } : void 0,
826
+ ...cacheRetention ? { cacheRetention } : void 0,
827
+ startedAtMs: Date.now()
828
+ };
829
+ return base(model, context, cacheRetention ? {
830
+ ...options,
831
+ cacheRetention
832
+ } : options);
833
+ },
834
+ record: async (message) => {
835
+ const request = lastRequest;
836
+ lastRequest = void 0;
837
+ await warmupsStopped;
838
+ if (!getChatConfig().cacheWarmingEnabled || !request) return;
839
+ try {
840
+ await toolWait.record(request, message);
841
+ } catch (error) {
842
+ logWarn("cache_warming.tool_wait.record_failed", { "exception.message": error instanceof Error ? error.message : String(error) });
843
+ }
844
+ if (message.stopReason === "error" || message.stopReason === "aborted" || idleEnded && message.stopReason !== "stop") return;
845
+ idleEnded = message.stopReason !== "stop";
846
+ try {
847
+ await recordModelCall(conversationId, userActor, request, message);
848
+ } catch (error) {
849
+ logWarn("cache_warming.model_call.record_failed", { "exception.message": error instanceof Error ? error.message : String(error) });
850
+ }
851
+ },
852
+ toolsReturned: toolWait.toolsReturned,
853
+ stop: async () => {
854
+ try {
855
+ await toolWait.end();
856
+ } catch (error) {
857
+ logWarn("cache_warming.tool_wait.record_failed", { "exception.message": error instanceof Error ? error.message : String(error) });
858
+ }
859
+ }
860
+ };
861
+ }
862
+ /**
863
+ * Run one scheduled cache warming message. A message for an idle period that
864
+ * already ended does nothing.
865
+ */
866
+ async function runCacheWarmup(message) {
867
+ const { conversationId } = message;
868
+ const state = await connectedState();
869
+ const idle = (await state.get(conversationKey(conversationId)))?.idle;
870
+ const warm = idle?.warm;
871
+ if (!idle || !warm || idle.generation !== message.generation) return;
872
+ const { generation } = idle;
873
+ const stop = () => state.delete(snapshotKey(conversationId, generation));
874
+ if (message.kind === "horizon") {
875
+ await stop();
876
+ await recordGap(state, conversationId, generation, warm, NO_REPLY_GAP_MS);
877
+ return;
878
+ }
879
+ if ((await state.get(warmupsKey(conversationId, generation)) ?? 0) !== message.cycle - 1) return;
880
+ const attributes = {
881
+ "app.cache_warming.cycle": message.cycle,
882
+ "app.cache_warming.prefix_tokens": warm.prefixTokens,
883
+ "app.cache_warming.trigger": "idle",
884
+ ...segmentAttributes(warm),
885
+ "app.cache_warming.cache_ttl_left_ms": message.cacheExpiresAtMs - Date.now()
886
+ };
887
+ await withSpan("cache_warming.warmup", "cache_warming.warmup", {
888
+ conversationId,
889
+ modelId: warm.modelId
890
+ }, async (setSpanAttributes) => {
891
+ const setOutcome = (outcome, extra = {}) => setSpanAttributes({
892
+ ...attributes,
893
+ ...extra,
894
+ "app.cache_warming.outcome": outcome
895
+ });
896
+ const skip = async (reason) => {
897
+ const skipReason = { "app.cache_warming.skip_reason": reason };
898
+ logInfo("cache_warming.warmup.skipped", {
899
+ ...attributes,
900
+ ...skipReason
901
+ });
902
+ setOutcome("skipped", skipReason);
903
+ await stop();
904
+ };
905
+ if (warmupTooLate(message.cacheExpiresAtMs)) {
906
+ await skip("cache_expired");
907
+ return;
908
+ }
909
+ if (await breakerOpen(state, warm.modelId)) {
910
+ await skip("breaker_open");
911
+ return;
912
+ }
913
+ const model = resolveGatewayModel(warm.modelId);
914
+ const decision = decideWarmup({
915
+ conversationGapsMs: await state.getList(conversationGapsKey(conversationId, warm.segment)),
916
+ globalGapsMs: await state.getList(segmentGapsKey(warm.segment)),
917
+ idleMs: Date.now() - idle.sinceMs,
918
+ cacheExpiryIdleMs: message.cacheExpiresAtMs - idle.sinceMs,
919
+ cacheTtlMs: warm.cacheTtlMs,
920
+ prefixTokens: warm.prefixTokens,
921
+ cacheReadPrice: model.cost.cacheRead,
922
+ cacheWritePrice: model.cost.cacheWrite
923
+ });
924
+ attributes["app.cache_warming.return_probability"] = decision.returnProbability;
925
+ attributes["app.cache_warming.returns_per_warmup"] = decision.returnsPerWarmup;
926
+ attributes["app.cache_warming.threshold"] = decision.threshold;
927
+ if (!decision.warm) {
928
+ await skip(decision.reason);
929
+ return;
930
+ }
931
+ const snapshot = await state.get(snapshotKey(conversationId, generation));
932
+ if (!snapshot) {
933
+ setOutcome("skipped", { "app.cache_warming.skip_reason": "stopped" });
934
+ return;
935
+ }
936
+ const context = JSON.parse((await zstdDecompress$1(Buffer.from(snapshot, "base64"))).toString("utf8"));
937
+ const startedAtMs = Date.now();
938
+ const warmup = await sendWarmup(state, {
939
+ conversationId,
940
+ modelId: warm.modelId,
941
+ context,
942
+ ...warm.reasoning ? { reasoning: warm.reasoning } : void 0,
943
+ prefixTokens: warm.prefixTokens
944
+ }).catch(async (error) => {
945
+ setOutcome("failed");
946
+ await stop();
947
+ throw error;
948
+ });
949
+ Object.assign(attributes, warmup.attributes);
950
+ if (!warmup.refreshed) {
951
+ logWarn("cache_warming.warmup.failed", attributes);
952
+ setOutcome("missed");
953
+ await stop();
954
+ return;
955
+ }
956
+ logInfo("cache_warming.warmup.completed", attributes);
957
+ setOutcome("completed");
958
+ await state.set(warmupsKey(conversationId, generation), message.cycle, IDLE_HORIZON_MS);
959
+ if (await state.get(snapshotKey(conversationId, generation))) await scheduleWarmup({
960
+ kind: "warmup",
961
+ conversationId,
962
+ cycle: message.cycle + 1,
963
+ generation
964
+ }, startedAtMs, warm);
965
+ }, attributes);
966
+ }
967
+ export { segmentGapsKey as a, listConversationWork as c, MINUTE_MS as d, MIN_WARMUP_PREFIX_TOKENS as f, createCacheWarmingRecorder as i, readLastUserMessageAtByConversation as l, gapSegment as m, GLOBAL_GAPS_MAX as n, warmup_exports as o, NO_REPLY_GAP_MS as p, GLOBAL_GAPS_TTL_MS as r, isConversationWorkDone as s, CONVERSATION_STATE_TTL_MS as t, IDLE_HORIZON_MS as u };