@sentry/junior 0.294.0 → 0.295.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 (77) hide show
  1. package/dist/{admin-vt8aSiCD.js → admin-ifgjyfpF.js} +2 -2
  2. package/dist/{agent-runner-DJu7w6mI.js → agent-runner-DjMTPWEO.js} +147 -90
  3. package/dist/api/schema.d.ts +2 -2
  4. package/dist/api/schema.js +5 -5
  5. package/dist/api.d.ts +1 -1
  6. package/dist/api.js +52 -28
  7. package/dist/{app--a5RLOrr.d.ts → app-uiTzRbvq.d.ts} +3 -3
  8. package/dist/app.d.ts +2 -2
  9. package/dist/app.js +33 -34
  10. package/dist/{automation-BM-OBsKW.js → automation-yJX3C7i3.js} +3 -3
  11. package/dist/{background-compaction-queue-D2j-0XkH.js → background-compaction-queue-DUkHZjmL.js} +7 -9
  12. package/dist/{briefs-JOAoCb6d.js → briefs-CbNYM-q2.js} +3 -3
  13. package/dist/{catalog-runtime-CLMA9AXd.js → catalog-runtime-DgouZKZm.js} +1 -1
  14. package/dist/cli/chat.d.ts +1 -1
  15. package/dist/cli/chat.js +15 -15
  16. package/dist/cli/check.js +3 -3
  17. package/dist/cli/init.js +2 -0
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.d.ts +1 -1
  20. package/dist/cli/plugins.js +4 -4
  21. package/dist/cli/snapshot-create.js +4 -4
  22. package/dist/cli/upgrade.d.ts +2 -2
  23. package/dist/cli/upgrade.js +3 -3
  24. package/dist/{config-mIZeGEWv.js → config-DvnTPCfp.js} +43 -2
  25. package/dist/{connections-XhdVg7OR.js → connections-CWaIVl_1.js} +6 -6
  26. package/dist/{conversation-CDWejM4R.js → conversation-CMkSmi02.js} +2 -11
  27. package/dist/{conversation-pending-messages-Dh2tfbaw.js → conversation-feed-BVAOga0H.js} +27 -2
  28. package/dist/{conversation-privacy-C6h-X2cZ.js → conversation-privacy-DPjv4SnA.js} +1 -1
  29. package/dist/{credential-sync-zigBlXS3.js → credential-sync-BhbaZfmO.js} +16 -15
  30. package/dist/{db-DV5AbcGM.d.ts → db-CCUqQe0E.d.ts} +6 -1
  31. package/dist/{db--xuNV7g6.js → db-Dts2XvLu.js} +54 -10
  32. package/dist/{executor-BItuRqAR.js → executor-Ck73J0wP.js} +8 -3
  33. package/dist/instrumentation.js +2 -2
  34. package/dist/{logging-Cb6MGvdt.js → logging-9OAq-fdg.js} +2 -1
  35. package/dist/{message-BTGgSmaH.js → message-CtaPzC7m.js} +9 -9
  36. package/dist/nitro.d.ts +2 -2
  37. package/dist/nitro.js +2 -2
  38. package/dist/{oauth-callback-server-Dvh1aOIi.js → oauth-callback-server-C_LXY1d4.js} +2 -2
  39. package/dist/{oauth-relay-D6xxVywK.js → oauth-relay-CsfIazeF.js} +2 -1
  40. package/dist/{plugins-DtmjkTza.d.ts → plugins-B_0Cr0MO.d.ts} +0 -1
  41. package/dist/{projection-DLQgfO5N.js → projection-BzJQncZV.js} +248 -77
  42. package/dist/{prompt-qp_LdxLX.js → prompt-Cbq5b4SO.js} +4 -4
  43. package/dist/{registry-MtwokaqW.js → registry-cbpOxO4M.js} +3 -13
  44. package/dist/{resolve-BnJA0UNE.js → resolve-t-pmRdwS.js} +3 -3
  45. package/dist/{result-ChL-1KyW.js → result-DhgjR3nQ.js} +8 -8
  46. package/dist/{runner-BONN7Dp2.js → runner-CHv9X9TH.js} +8 -8
  47. package/dist/{sandbox-egress-signals-nmlmI5Ab.js → sandbox-egress-signals-Yy3fSCbg.js} +1 -1
  48. package/dist/{schema-yr0ccDni.js → schema-BhneuGYv.js} +13 -6
  49. package/dist/{schema-DgvcyJ1y.d.ts → schema-TSEisVJR.d.ts} +50 -14
  50. package/dist/secrets-DebYU866.js +18 -0
  51. package/dist/{service-account-Bd0lBaGr.js → service-account-C4rBP8ne.js} +3 -3
  52. package/dist/{service-account-kio5nXSD.js → service-account-DjPIwCMj.js} +42 -26
  53. package/dist/{session-stop-CeCXL3j9.js → session-stop-DkxI5vc3.js} +20 -775
  54. package/dist/{skills-e3DDNlKO.js → skills-BZE2DP8I.js} +2 -2
  55. package/dist/{spawn--cRxITWQ.js → spawn-BvULxIiu.js} +5 -5
  56. package/dist/{adapter-DxLhJEnO.js → state-CO9ETDzk.js} +132 -2
  57. package/dist/{stop-Iai5N2PU.js → stop-CL-rdtQb.js} +84 -30
  58. package/dist/{store-C8LsaJwS.js → store-DgD78_NK.js} +3 -3
  59. package/dist/{task-runner-Dw7exu0-.js → task-runner-CKOj6xla.js} +11 -11
  60. package/dist/{turn-failure-response-BqTTx3XG.js → turn-failure-response-BTSo6SMJ.js} +8 -8
  61. package/dist/{validation-BrGahtnv.js → validation-CXeYgBzq.js} +1 -1
  62. package/dist/{version-Bdqhx8Qh.js → version-AQa7Fr2H.js} +1 -1
  63. package/dist/version.js +1 -1
  64. package/dist/{viewer-CjRFHR5U.js → viewer-Bqkb678l.js} +3 -3
  65. package/dist/warmup-h6u1e9n0.js +1869 -0
  66. package/dist/{work-BWBG1EGV.js → work-yN_GAuXY.js} +11 -11
  67. package/dist/{worker-DAnBIVMs.js → worker-Hl7N292I.js} +6 -6
  68. package/migrations/0098_review_item_plugin_actions.sql +5 -0
  69. package/migrations/0099_conversation_last_message_at.sql +1 -0
  70. package/migrations/0100_automation_task_kind_repair.sql +48 -0
  71. package/migrations/meta/0098_snapshot.json +4490 -0
  72. package/migrations/meta/0099_snapshot.json +4720 -0
  73. package/migrations/meta/0100_snapshot.json +4496 -0
  74. package/migrations/meta/_journal.json +21 -0
  75. package/package.json +5 -5
  76. package/dist/assistant-reply-iTtEdDyc.js +0 -58
  77. package/dist/warmup-DuxCtzKC.js +0 -1039
@@ -1,1039 +0,0 @@
1
- import { n as captureMessage, v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { Bn as getPlugins, Mo as createPluginCache, Xa as createPluginLogger } from "./projection-DLQgfO5N.js";
3
- import { E as resolveGatewayModel, K as isProviderRetryError, i as getChatConfig } from "./config-mIZeGEWv.js";
4
- import { E as withSpan, h as logWarn, m as logInfo, x as setSpanStatus } from "./logging-Cb6MGvdt.js";
5
- import { Z as rootConversationIsArchived, a as getConversationStore, o as getDb, s as getSqlExecutor } from "./db--xuNV7g6.js";
6
- import { A as juniorConversations, C as isUserInstruction, j as juniorIdentities, w as juniorConversationEvents } from "./executor-BItuRqAR.js";
7
- import { u as completeText } from "./prompt-qp_LdxLX.js";
8
- import { r as getStateAdapter } from "./adapter-DxLhJEnO.js";
9
- import { E as sendCacheWarmup } from "./background-compaction-queue-D2j-0XkH.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
- /**
52
- * Gaps that a segment needs before its gaps replace its parent segment's
53
- * gaps (`parentGapSegment`). A new or rare segment starts with its parent's
54
- * return chances, so it can warm before it has gaps of its own.
55
- */
56
- const BLEND_PSEUDOCOUNT = 20;
57
- /**
58
- * Gaps that a Conversation needs before its gaps replace its segment's gaps.
59
- * One Conversation has few gaps, and a few unusual replies say little about
60
- * its next one. A backtest of time-ordered decisions showed that a weight
61
- * this slow predicts returns better than both a faster weight and no
62
- * Conversation weight at all.
63
- */
64
- const CONVERSATION_BLEND_PSEUDOCOUNT = 100;
65
- /** Below this prefix size, one cache miss costs too little to warm for. */
66
- const MIN_WARMUP_PREFIX_TOKENS = 5e4;
67
- /**
68
- * Junior watches an idle period for this long. A person who replies later
69
- * counts as a person who did not reply. The reply chance of a warmup counts
70
- * only replies before this time. For a cache that outlives the horizon, this
71
- * is less than the real chance, so Junior warms less, never more.
72
- *
73
- * The horizon message is signed when the idle period starts, and a queue
74
- * signature is valid for 60 minutes (`QUEUE_SIGNATURE_MAX_AGE_MS`). The other
75
- * 5 minutes let a late horizon still record its no-reply gap.
76
- */
77
- const IDLE_HORIZON_MS = 55 * MINUTE_MS;
78
- /**
79
- * Whether a failed warmup request counts as a miss for the provider breaker.
80
- * A request that the provider rejects fails the same way for each
81
- * Conversation, so it counts. A retryable failure, such as an overload or a
82
- * timeout, says nothing about the cache, so it must not stop warming for
83
- * every Conversation.
84
- */
85
- function warmupFailureCountsAsMiss(error) {
86
- return !isProviderRetryError(error);
87
- }
88
- /** Gap that Junior records for an idle period with no reply in the horizon. */
89
- const NO_REPLY_GAP_MS = 1440 * MINUTE_MS;
90
- function binIndex(gapMs) {
91
- return GAP_BIN_EDGES_MS.findIndex((edge) => gapMs < edge);
92
- }
93
- function histogramOf(gapsMs) {
94
- const counts = Array.from({ length: GAP_BIN_COUNT }, () => 0);
95
- for (const gap of gapsMs) counts[binIndex(gap)] += 1;
96
- return {
97
- counts,
98
- total: gapsMs.length
99
- };
100
- }
101
- function blendHistograms(own, prior, pseudocount) {
102
- if (own.total === 0 || prior.total === 0) return own.total === 0 ? prior : own;
103
- const weight = Math.min(own.total / pseudocount, 1);
104
- return {
105
- counts: own.counts.map((count, index) => weight * count / own.total + (1 - weight) * prior.counts[index] / prior.total),
106
- total: 1
107
- };
108
- }
109
- function survival(histogram, tMs) {
110
- if (histogram.total === 0) return 1;
111
- const index = binIndex(tMs);
112
- let surviving = 0;
113
- for (let i = index + 1; i < GAP_BIN_COUNT; i++) surviving += histogram.counts[i];
114
- const binStart = index > 0 ? GAP_BIN_EDGES_MS[index - 1] : 0;
115
- const fractionPast = Math.min(1, Math.max(0, (tMs - binStart) / (GAP_BIN_EDGES_MS[index] - binStart)));
116
- surviving += histogram.counts[index] * (1 - fractionPast);
117
- return surviving / histogram.total;
118
- }
119
- function returnProbability(histogram, idleMs, windowMs) {
120
- const now = survival(histogram, idleMs);
121
- if (now < .001) return 0;
122
- return Math.max(0, (now - survival(histogram, idleMs + windowMs)) / now);
123
- }
124
- /**
125
- * How long before cache expiry Junior sends a warmup. A warmup reads each
126
- * cache block of the prefix in one request, so the provider refreshes all
127
- * blocks together. A margin that grows with the prefix size gains nothing.
128
- * The margin covers only the queue delay and the time of the warmup request.
129
- */
130
- const WARMUP_MARGIN_MS = 45e3;
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
- /** Each segment that `gapSegment` returns, in display order. */
149
- const GAP_SEGMENTS = [...[true, false].flatMap((userActor) => [
150
- 0,
151
- 1,
152
- 3
153
- ].flatMap((endedTurns) => [
154
- "open",
155
- "done",
156
- "none"
157
- ].map((workState) => gapSegment({
158
- userActor,
159
- endedTurns,
160
- workState,
161
- archived: false
162
- })))), ...[
163
- "open",
164
- "done",
165
- "none"
166
- ].map((workState) => gapSegment({
167
- userActor: false,
168
- endedTurns: 0,
169
- workState,
170
- archived: true
171
- }))];
172
- /**
173
- * Count gaps in the bins that `decideWarmup` uses, for reports. A gap at or
174
- * after `IDLE_HORIZON_MS` is a no-reply gap, as the recorder stores it. The
175
- * bins after the horizon never get a gap, so they are left out.
176
- */
177
- function gapHistogramReport(gapsMs) {
178
- const { counts } = histogramOf(gapsMs.filter((gapMs) => gapMs < IDLE_HORIZON_MS));
179
- const bins = [];
180
- for (const [index, endMs] of GAP_BIN_EDGES_MS.entries()) {
181
- const startMs = index > 0 ? GAP_BIN_EDGES_MS[index - 1] : 0;
182
- if (startMs >= 33e5) break;
183
- bins.push({
184
- startMs,
185
- endMs: Math.min(endMs, IDLE_HORIZON_MS),
186
- count: counts[index]
187
- });
188
- }
189
- return {
190
- bins,
191
- noReply: gapsMs.filter((gapMs) => gapMs >= IDLE_HORIZON_MS).length,
192
- total: gapsMs.length
193
- };
194
- }
195
- /**
196
- * Segment whose gaps a thin segment leans on: the `none` segment with the
197
- * same Actor and Turn depth. The backfill and most traffic keep the `none`
198
- * segments full. A `none` segment that is not archived has no parent.
199
- */
200
- function parentGapSegment(input) {
201
- if (!input.archived && input.workState === "none") return void 0;
202
- return gapSegment({
203
- ...input,
204
- workState: "none",
205
- archived: false
206
- });
207
- }
208
- /** Whether a segment has too few gaps to stand without its parent. */
209
- function segmentNeedsParent(segmentGaps) {
210
- return segmentGaps < BLEND_PSEUDOCOUNT;
211
- }
212
- /**
213
- * Decide whether to send the next warmup.
214
- *
215
- * A warmup costs one cache read of the prefix. A return to a warm cache saves
216
- * one write minus one read. So warming pays when the expected returns per
217
- * warmup are above read/(write − read). Earlier warmups are already paid, so
218
- * the threshold is the same for each warmup.
219
- *
220
- * One warmup alone can be useless when people return a little after the next
221
- * TTL, while two or three warmups in a row would reach them. So the decision
222
- * compares plans of 1, 2, ... warmups up to the horizon. Each plan sends its
223
- * next warmup only while nobody returned. Junior warms when the best plan
224
- * pays, and decides again at the next warmup.
225
- */
226
- function decideWarmup(input) {
227
- const savedPerReturn = input.cacheWritePrice - input.cacheReadPrice;
228
- const threshold = savedPerReturn > 0 ? Math.min(input.cacheReadPrice / savedPerReturn, 1) : 1;
229
- const conversation = histogramOf(input.conversationGapsMs);
230
- const global = histogramOf(input.globalGapsMs);
231
- const parent = input.parentGapsMs && segmentNeedsParent(global.total) ? histogramOf(input.parentGapsMs) : void 0;
232
- const histogram = blendHistograms(conversation, parent ? blendHistograms(global, parent, BLEND_PSEUDOCOUNT) : global, CONVERSATION_BLEND_PSEUDOCOUNT);
233
- const probability = returnProbability(histogram, input.idleMs, Math.min(input.cacheTtlMs, IDLE_HORIZON_MS - input.idleMs));
234
- const perWarmup = returnsPerWarmup(histogram, input.idleMs, input.cacheExpiryIdleMs, input.cacheTtlMs);
235
- const decision = (reason) => ({
236
- warm: reason === "warm",
237
- reason,
238
- returnProbability: probability,
239
- returnsPerWarmup: perWarmup,
240
- threshold,
241
- parentPrior: (parent?.total ?? 0) > 0
242
- });
243
- if (input.prefixTokens < 5e4) return decision("prefix_too_small");
244
- if (threshold >= 1) return decision("no_savings");
245
- if (input.idleMs >= 33e5) return decision("horizon");
246
- if (conversation.total + global.total + (parent?.total ?? 0) < 20) return decision("few_gaps");
247
- return decision(perWarmup >= threshold ? "warm" : "unlikely_return");
248
- }
249
- function returnsPerWarmup(histogram, idleMs, cacheExpiryIdleMs, ttlMs) {
250
- const now = survival(histogram, idleMs);
251
- const intervalMs = ttlMs - WARMUP_MARGIN_MS;
252
- if (now < .001 || intervalMs <= 0) return 0;
253
- const leftAtExpiry = survival(histogram, Math.min(cacheExpiryIdleMs, IDLE_HORIZON_MS));
254
- let best = 0;
255
- let warmups = 0;
256
- for (let startMs = idleMs; startMs < IDLE_HORIZON_MS; startMs += intervalMs) {
257
- warmups += survival(histogram, startMs) / now;
258
- const endMs = Math.min(startMs + ttlMs, IDLE_HORIZON_MS);
259
- const returns = Math.max(0, leftAtExpiry - survival(histogram, endMs)) / now;
260
- best = Math.max(best, returns / warmups);
261
- }
262
- return best;
263
- }
264
- // src/chat/cache-warming/request.ts
265
- const KEY_PREFIX = "junior:cache_warming";
266
- const CACHE_RETENTION = "short";
267
- const REFRESHED_READ_FRACTION = .9;
268
- const BREAKER_OUTCOMES_MAX = 20;
269
- const BREAKER_MAX_MISSES = 10;
270
- const BREAKER_OUTCOMES_TTL_MS = 360 * MINUTE_MS;
271
- const BREAKER_OPEN_TTL_MS = 1440 * MINUTE_MS;
272
- const breakerOutcomesKey = (provider) => `${KEY_PREFIX}:breaker:${provider}:outcomes`;
273
- const breakerOpenKey = (provider) => `${KEY_PREFIX}:breaker:${provider}:open`;
274
- const providerOf = (modelId) => modelId.split("/")[0] ?? "";
275
- /** Connect the state adapter that holds cache warming state. */
276
- async function connectedState() {
277
- const state = getStateAdapter();
278
- await state.connect();
279
- return state;
280
- }
281
- const CACHE_TTL_MS = {
282
- anthropic: 5 * MINUTE_MS,
283
- alibaba: 5 * MINUTE_MS,
284
- openai: 30 * MINUTE_MS
285
- };
286
- /**
287
- * Return true when warmups can refresh the prompt cache of this request.
288
- * Warming pays only when a cache write costs more than a read. Pi adds a
289
- * thinking budget to the one-token output limit on the Anthropic Messages API
290
- * for models without adaptive thinking. Then a warmup could cost as much as a
291
- * short answer, and a smaller budget would miss the cached messages.
292
- */
293
- function supportsWarming(request) {
294
- const { model, reasoning } = request;
295
- const budgetThinking = reasoning !== void 0 && model.api === "anthropic-messages" && model.compat?.forceAdaptiveThinking !== true;
296
- return CACHE_TTL_MS[providerOf(model.id)] !== void 0 && model.cost.cacheRead > 0 && model.cost.cacheWrite > model.cost.cacheRead && !budgetThinking && request.cacheRetention === "short";
297
- }
298
- /** Return the cache TTL of a request that Junior can warm. */
299
- function cacheTtlMs(request) {
300
- return supportsWarming(request) ? CACHE_TTL_MS[providerOf(request.model.id)] : void 0;
301
- }
302
- /** Return the cached prefix tokens of a finished model request. */
303
- function cachedPrefixTokens(message) {
304
- return message.usage.cacheRead + message.usage.cacheWrite;
305
- }
306
- /**
307
- * Return when the cache that a request at `requestStartedAtMs` read or wrote
308
- * expires, and the delay until the warmup that refreshes it.
309
- */
310
- function warmupTiming(requestStartedAtMs, ttlMs) {
311
- const cacheExpiresAtMs = requestStartedAtMs + ttlMs;
312
- return {
313
- cacheExpiresAtMs,
314
- delayMs: cacheExpiresAtMs - WARMUP_MARGIN_MS - Date.now()
315
- };
316
- }
317
- const LATE_WARMUP_MS = 1e4;
318
- /**
319
- * Return true when a warmup is too late to refresh the cache. The cache is
320
- * gone, so the warmup must not run or count as a miss.
321
- */
322
- function warmupTooLate(cacheExpiresAtMs) {
323
- return Date.now() + LATE_WARMUP_MS >= cacheExpiresAtMs;
324
- }
325
- /**
326
- * Return true while too many recent warmups of the model's provider missed,
327
- * so its warming is off.
328
- */
329
- async function breakerOpen(state, modelId) {
330
- return await state.get(breakerOpenKey(providerOf(modelId))) === true;
331
- }
332
- async function countOutcome(state, modelId, miss) {
333
- const provider = providerOf(modelId);
334
- await state.appendToList(breakerOutcomesKey(provider), miss ? 1 : 0, {
335
- maxLength: BREAKER_OUTCOMES_MAX,
336
- ttlMs: BREAKER_OUTCOMES_TTL_MS
337
- });
338
- if (!miss) return;
339
- const outcomes = await state.getList(breakerOutcomesKey(provider));
340
- const misses = outcomes.filter((outcome) => outcome === 1).length;
341
- 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", {
342
- level: "error",
343
- fingerprint: ["cache_warming.breaker.opened", provider],
344
- tags: { "gen_ai.request.model": modelId },
345
- extra: {
346
- "app.cache_warming.misses": misses,
347
- "app.cache_warming.outcomes": outcomes.length
348
- }
349
- });
350
- }
351
- /**
352
- * Send one warmup: the same request with a one-token output limit. Count its
353
- * outcome for the breaker, and report a miss to Sentry. A rejected request
354
- * counts as a miss and rethrows, because it fails the same way for each
355
- * Conversation.
356
- */
357
- async function sendWarmup(state, params) {
358
- const { conversationId, modelId, context, prefixTokens } = params;
359
- const { message: result } = await completeText({
360
- modelId,
361
- system: context.systemPrompt,
362
- messages: context.messages,
363
- ...context.tools ? { tools: context.tools } : void 0,
364
- ...params.reasoning ? { thinkingLevel: params.reasoning } : void 0,
365
- cacheRetention: CACHE_RETENTION,
366
- maxTokens: 1,
367
- messageAttributeMode: "metadata",
368
- metadata: { conversationId },
369
- operation: "cache_warmup",
370
- cost: { conversationId },
371
- sessionId: conversationId
372
- }).catch(async (error) => {
373
- if (warmupFailureCountsAsMiss(error)) await countOutcome(state, modelId, true);
374
- throw error;
375
- });
376
- const attributes = {
377
- "app.cost.total_usd": result.usage.cost.total,
378
- "gen_ai.usage.cache_read.input_tokens": result.usage.cacheRead,
379
- "gen_ai.usage.cache_creation.input_tokens": result.usage.cacheWrite
380
- };
381
- const refreshed = result.usage.cacheRead >= prefixTokens * REFRESHED_READ_FRACTION;
382
- if (!refreshed) captureMessage("Cache warmup missed the cache", {
383
- level: "warning",
384
- fingerprint: ["cache_warming.warmup.missed", modelId],
385
- tags: { "gen_ai.request.model": modelId },
386
- extra: { "app.cache_warming.read_fraction": result.usage.cacheRead / prefixTokens }
387
- });
388
- await countOutcome(state, modelId, !refreshed);
389
- return {
390
- refreshed,
391
- attributes
392
- };
393
- }
394
- // src/chat/cache-warming/tool-wait.ts
395
- const TOOL_WAIT_GAPS_KEY = `${KEY_PREFIX}:gaps:tool_wait`;
396
- const TOOL_WAIT_GAPS_MAX = 2e3;
397
- const TOOL_WAIT_GAPS_TTL_MS = 43200 * MINUTE_MS;
398
- const MIN_RECORDED_TOOL_WAIT_MS = 2 * MINUTE_MS;
399
- /** Create the tool wait warmer of one agent run. */
400
- function createToolWaitWarmer(conversationId) {
401
- let timer;
402
- let waiting;
403
- let returnedAtMs;
404
- let generation = 0;
405
- const schedule = (cache, refreshedAtMs, cycle) => {
406
- const current = generation;
407
- const { cacheExpiresAtMs, delayMs } = warmupTiming(refreshedAtMs, cache.ttlMs);
408
- timer = setTimeout(() => {
409
- timer = void 0;
410
- warm(cache, cacheExpiresAtMs, cycle, current);
411
- }, Math.max(0, delayMs));
412
- timer.unref?.();
413
- };
414
- const warm = (cache, cacheExpiresAtMs, cycle, current) => {
415
- const { request, prefixTokens } = cache;
416
- const attributes = {
417
- "app.cache_warming.cycle": cycle,
418
- "app.cache_warming.prefix_tokens": prefixTokens,
419
- "app.cache_warming.trigger": "tool_wait"
420
- };
421
- return withSpan("cache_warming.warmup", "cache_warming.warmup", {
422
- conversationId,
423
- modelId: request.model.id
424
- }, async (setSpanAttributes) => {
425
- const setOutcome = (outcome, extra = {}) => setSpanAttributes({
426
- ...attributes,
427
- ...extra,
428
- "app.cache_warming.outcome": outcome
429
- });
430
- const skip = (reason) => {
431
- const skipReason = { "app.cache_warming.skip_reason": reason };
432
- logInfo("cache_warming.warmup.skipped", {
433
- ...attributes,
434
- ...skipReason
435
- });
436
- setOutcome("skipped", skipReason);
437
- };
438
- if (warmupTooLate(cacheExpiresAtMs)) {
439
- skip("cache_expired");
440
- return;
441
- }
442
- try {
443
- const state = await connectedState();
444
- if (await breakerOpen(state, request.model.id)) {
445
- skip("breaker_open");
446
- return;
447
- }
448
- const decision = decideWarmup({
449
- conversationGapsMs: [],
450
- globalGapsMs: await state.getList(TOOL_WAIT_GAPS_KEY),
451
- idleMs: Date.now() - request.startedAtMs,
452
- cacheExpiryIdleMs: cacheExpiresAtMs - request.startedAtMs,
453
- cacheTtlMs: cache.ttlMs,
454
- prefixTokens,
455
- cacheReadPrice: request.model.cost.cacheRead,
456
- cacheWritePrice: request.model.cost.cacheWrite
457
- });
458
- attributes["app.cache_warming.return_probability"] = decision.returnProbability;
459
- attributes["app.cache_warming.returns_per_warmup"] = decision.returnsPerWarmup;
460
- attributes["app.cache_warming.threshold"] = decision.threshold;
461
- if (current !== generation) {
462
- setOutcome("skipped", { "app.cache_warming.skip_reason": "stopped" });
463
- return;
464
- }
465
- if (!decision.warm) {
466
- skip(decision.reason);
467
- return;
468
- }
469
- const startedAtMs = Date.now();
470
- const warmup = await sendWarmup(state, {
471
- conversationId,
472
- modelId: request.model.id,
473
- context: request.context,
474
- ...request.reasoning ? { reasoning: request.reasoning } : void 0,
475
- prefixTokens
476
- });
477
- Object.assign(attributes, warmup.attributes);
478
- if (!warmup.refreshed) {
479
- logWarn("cache_warming.warmup.failed", attributes);
480
- setOutcome("missed");
481
- return;
482
- }
483
- logInfo("cache_warming.warmup.completed", attributes);
484
- setOutcome("completed");
485
- if (current === generation) schedule(cache, startedAtMs, cycle + 1);
486
- } catch (error) {
487
- logWarn("cache_warming.warmup.failed", {
488
- ...attributes,
489
- "exception.message": error instanceof Error ? error.message : String(error)
490
- });
491
- setOutcome("failed", { "error.type": error instanceof Error ? error.name : typeof error });
492
- setSpanStatus("error");
493
- }
494
- }, attributes);
495
- };
496
- const stop = () => {
497
- generation += 1;
498
- clearTimeout(timer);
499
- timer = void 0;
500
- };
501
- const recordWait = async (waitMs) => {
502
- if (waitMs < MIN_RECORDED_TOOL_WAIT_MS) return;
503
- await (await connectedState()).appendToList(TOOL_WAIT_GAPS_KEY, waitMs, {
504
- maxLength: TOOL_WAIT_GAPS_MAX,
505
- ttlMs: TOOL_WAIT_GAPS_TTL_MS
506
- });
507
- };
508
- return {
509
- async record(request, message) {
510
- stop();
511
- const previous = waiting;
512
- waiting = message.stopReason === "toolUse" ? request : void 0;
513
- returnedAtMs = void 0;
514
- const prefixTokens = cachedPrefixTokens(message);
515
- const ttlMs = cacheTtlMs(request);
516
- if (waiting && prefixTokens >= 5e4 && ttlMs !== void 0) schedule({
517
- request,
518
- prefixTokens,
519
- ttlMs
520
- }, request.startedAtMs, 1);
521
- if (previous) await recordWait(request.startedAtMs - previous.startedAtMs);
522
- },
523
- stop,
524
- toolsReturned() {
525
- stop();
526
- if (waiting) returnedAtMs ??= Date.now();
527
- },
528
- async end() {
529
- stop();
530
- const open = waiting;
531
- const returned = returnedAtMs;
532
- waiting = void 0;
533
- returnedAtMs = void 0;
534
- if (!open) return;
535
- if (returned !== void 0) {
536
- await recordWait(returned - open.startedAtMs);
537
- return;
538
- }
539
- if (Date.now() - open.startedAtMs >= MIN_RECORDED_TOOL_WAIT_MS) await recordWait(NO_REPLY_GAP_MS);
540
- }
541
- };
542
- }
543
- // src/api/conversations/user-message-activity.ts
544
- /**
545
- * The newest event of one type in the outer Conversation that matches the
546
- * filter. It walks the message role or user message time index from the
547
- * newest event. The user message index has only matching entries, so that
548
- * read stops at the first one.
549
- */
550
- function latestEventAt(db, type, filter) {
551
- 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}`);
552
- }
553
- /** Read the latest true user message time for each selected conversation. */
554
- async function readLastUserMessageAtByConversation(db, conversationIds) {
555
- if (conversationIds.length === 0) return /* @__PURE__ */ new Map();
556
- const payload = juniorConversationEvents.payload;
557
- const instruction = latestEventAt(db, "user_message", isUserInstruction(payload));
558
- const authorKind = sql`(${db.select({ kind: juniorIdentities.kind }).from(juniorIdentities).where(eq(juniorIdentities.id, juniorConversationEvents.actorIdentityId))})`;
559
- const message = latestEventAt(db, "message", sql`${payload}->>'role' = 'user' and ${authorKind} = 'user'`);
560
- const rows = await db.select({
561
- conversationId: juniorConversations.conversationId,
562
- instructionAt: instruction.createdAt,
563
- messageAt: message.createdAt
564
- }).from(juniorConversations).leftJoinLateral(instruction, sql`true`).leftJoinLateral(message, sql`true`).where(inArray(juniorConversations.conversationId, conversationIds));
565
- const result = /* @__PURE__ */ new Map();
566
- for (const { conversationId, instructionAt, messageAt } of rows) {
567
- const times = [instructionAt, messageAt].flatMap((at) => at ? [at.getTime()] : []);
568
- if (times.length > 0) result.set(conversationId, new Date(Math.max(...times)).toISOString());
569
- }
570
- return result;
571
- }
572
- // src/chat/plugins/unfinished-work.ts
573
- /**
574
- * Decide whether a conversation's work finished at or before the cutoff,
575
- * with no person's message after it finished. Auto-archive passes now minus
576
- * the grace period. A conversation without plugin-reported work has nothing
577
- * to wait for, so it counts as done here; cache warming needs reported work
578
- * and checks `assignedWork` itself.
579
- */
580
- function isConversationWorkDone(conversation, cutoffMs) {
581
- if (conversation.unfinishedWork) return false;
582
- if (!conversation.assignedWork) return true;
583
- const finishedAt = Date.parse(conversation.finishedWorkAt ?? "");
584
- if (!Number.isFinite(finishedAt) || finishedAt > cutoffMs) return false;
585
- const lastUserMessageAt = Date.parse(conversation.lastUserMessageAt ?? "");
586
- return !(Number.isFinite(lastUserMessageAt) && lastUserMessageAt > finishedAt);
587
- }
588
- /**
589
- * Map each candidate and each child of a candidate root to the candidate it
590
- * counts for. A child agent runs under its own conversation id, so a plugin
591
- * links the work that the child does, such as a pull request, to the child.
592
- */
593
- async function readWorkOwners(conversationIds) {
594
- const owners = new Map(conversationIds.map((id) => [id, id]));
595
- const children = await getDb().select({
596
- conversationId: juniorConversations.conversationId,
597
- rootConversationId: juniorConversations.rootConversationId
598
- }).from(juniorConversations).where(inArray(juniorConversations.rootConversationId, conversationIds));
599
- for (const child of children) if (child.rootConversationId && !owners.has(child.conversationId)) owners.set(child.conversationId, child.rootConversationId);
600
- return owners;
601
- }
602
- /**
603
- * Return assigned and unfinished plugin work for the candidate conversations.
604
- * Work in a child conversation counts for its root candidate. Feed Priority
605
- * combines these signals with conversation activity on the host.
606
- */
607
- async function listConversationWork(conversationIds) {
608
- if (conversationIds.length === 0) return {
609
- assignedIds: [],
610
- failed: false,
611
- finishedAtById: {},
612
- unfinishedIds: []
613
- };
614
- const owners = await readWorkOwners(conversationIds);
615
- const queriedIds = [...owners.keys()];
616
- const assigned = /* @__PURE__ */ new Set();
617
- const finishedAtById = /* @__PURE__ */ new Map();
618
- const unfinished = /* @__PURE__ */ new Set();
619
- let failed = false;
620
- for (const plugin of getPlugins()) {
621
- const hook = plugin.hooks?.unfinishedWork;
622
- if (!hook) continue;
623
- try {
624
- const result = await hook({
625
- conversationIds: queriedIds,
626
- db: getDb(),
627
- log: createPluginLogger(plugin.manifest.name),
628
- plugin: { name: plugin.manifest.name },
629
- cache: createPluginCache(plugin.manifest.name)
630
- });
631
- for (const workId of result.conversationIds) {
632
- const conversationId = owners.get(workId);
633
- if (!conversationId) continue;
634
- unfinished.add(conversationId);
635
- assigned.add(conversationId);
636
- }
637
- for (const workId of result.assignedConversationIds ?? []) {
638
- const conversationId = owners.get(workId);
639
- if (conversationId) assigned.add(conversationId);
640
- }
641
- for (const [workId, finishedAt] of Object.entries(result.finishedWorkAtByConversationId ?? {})) {
642
- const conversationId = owners.get(workId);
643
- if (!conversationId) continue;
644
- const time = Date.parse(finishedAt);
645
- if (!Number.isFinite(time)) continue;
646
- const current = finishedAtById.get(conversationId);
647
- if (!current || time > Date.parse(current)) finishedAtById.set(conversationId, finishedAt);
648
- }
649
- } catch (error) {
650
- failed = true;
651
- logWarn("plugin.unfinished_work.hook.failed", {
652
- "app.plugin.name": plugin.manifest.name,
653
- "exception.message": error instanceof Error ? error.message : String(error)
654
- });
655
- }
656
- }
657
- return {
658
- assignedIds: conversationIds.filter((conversationId) => assigned.has(conversationId)),
659
- failed,
660
- finishedAtById: Object.fromEntries(conversationIds.flatMap((conversationId) => {
661
- const finishedAt = finishedAtById.get(conversationId);
662
- return finishedAt ? [[conversationId, finishedAt]] : [];
663
- })),
664
- unfinishedIds: conversationIds.filter((conversationId) => unfinished.has(conversationId))
665
- };
666
- }
667
- // src/chat/cache-warming/work-state.ts
668
- /**
669
- * Read the plugin work state and the archive state of a Conversation when an
670
- * idle period starts that Junior can warm. Work of child Conversations counts
671
- * for their root. A child counts as archived when it or its root is: a manual
672
- * archive also archives the children, but auto-archive sets only the root.
673
- */
674
- async function readSegmentState(conversationId, nowMs) {
675
- const [work, conversation, rootArchived] = await Promise.all([
676
- listConversationWork([conversationId]),
677
- getConversationStore().get({ conversationId }),
678
- rootConversationIsArchived(getSqlExecutor(), conversationId)
679
- ]);
680
- const archived = rootArchived || conversation?.archivedAtMs !== void 0;
681
- if (work.failed || !work.assignedIds.includes(conversationId)) return {
682
- workState: "none",
683
- archived
684
- };
685
- if (work.unfinishedIds.includes(conversationId)) return {
686
- workState: "open",
687
- archived
688
- };
689
- const lastUserMessageAt = (await readLastUserMessageAtByConversation(getDb(), [conversationId])).get(conversationId);
690
- return {
691
- workState: isConversationWorkDone({
692
- assignedWork: true,
693
- finishedWorkAt: work.finishedAtById[conversationId],
694
- lastUserMessageAt
695
- }, nowMs) ? "done" : "none",
696
- archived
697
- };
698
- }
699
- // src/chat/cache-warming/warmup.ts
700
- /**
701
- * Prompt cache warming for idle Conversations.
702
- *
703
- * After a turn ends, the next human message often arrives after the short
704
- * prompt cache TTL. Then the full history is written to the cache again. A
705
- * warmup sends the same request again with a one-token output limit before
706
- * the cache expires. The provider reads the cached prefix and refreshes its
707
- * TTL. `model.ts` owns the cost model.
708
- *
709
- * Each idle period gets one recorded reply gap, so the model also sees the
710
- * people who do not reply. A reply records its gap. A delayed `horizon`
711
- * message records `NO_REPLY_GAP_MS` when no reply came in the idle horizon.
712
- *
713
- * Only a Turn writes the Conversation state. Warmups and the horizon run
714
- * while the next Turn can start, so they write only keys of their own idle
715
- * period (`generation`): the snapshot, the warmup count, and the gap claim.
716
- * Work for an old idle period then cannot change a newer one.
717
- */
718
- var warmup_exports = /* @__PURE__ */ __exportAll({
719
- CONVERSATION_STATE_TTL_MS: () => CONVERSATION_STATE_TTL_MS,
720
- GLOBAL_GAPS_MAX: () => GLOBAL_GAPS_MAX,
721
- GLOBAL_GAPS_TTL_MS: () => GLOBAL_GAPS_TTL_MS,
722
- createCacheWarmingRecorder: () => createCacheWarmingRecorder,
723
- runCacheWarmup: () => runCacheWarmup,
724
- segmentGapsKey: () => segmentGapsKey
725
- });
726
- const zstdCompress$1 = promisify(zstdCompress);
727
- const zstdDecompress$1 = promisify(zstdDecompress);
728
- const SNAPSHOT_ZSTD_PARAMS = { params: { [constants.ZSTD_c_compressionLevel]: 1 } };
729
- /** Gaps kept in each segment list. */
730
- const GLOBAL_GAPS_MAX = 2e3;
731
- /** A segment list expires this long after its last gap. */
732
- const GLOBAL_GAPS_TTL_MS = 43200 * MINUTE_MS;
733
- const CONVERSATION_GAPS_MAX = 50;
734
- /** The Turn count of a Conversation resets after this long with no call. */
735
- const CONVERSATION_STATE_TTL_MS = 10080 * MINUTE_MS;
736
- const MAX_SNAPSHOT_BYTES = 1048576;
737
- /** State list of the recent reply gaps (ms) of one `gapSegment`. */
738
- const segmentGapsKey = (segment) => `${KEY_PREFIX}:gaps:${segment}`;
739
- const conversationKey = (conversationId) => `${KEY_PREFIX}:conversation:${conversationId}`;
740
- /**
741
- * Recent reply gaps (ms) of the idle periods of this Conversation, per
742
- * `gapSegment`. A person's quick replies must not set the return chance of an
743
- * idle period that a system Turn started.
744
- */
745
- const conversationGapsKey = (conversationId, segment) => `${KEY_PREFIX}:gaps:conversation:${conversationId}:${segment}`;
746
- const snapshotKey = (conversationId, generation) => `${KEY_PREFIX}:snapshot:${conversationId}:${generation}`;
747
- /** Warmups that completed in the idle period. */
748
- const warmupsKey = (conversationId, generation) => `${KEY_PREFIX}:warmups:${conversationId}:${generation}`;
749
- /** Set by the first of the reply and the horizon to record the gap. */
750
- const gapClaimKey = (conversationId, generation) => `${KEY_PREFIX}:gap_claim:${conversationId}:${generation}`;
751
- const segmentAttributes = (warm) => ({
752
- "app.cache_warming.work_state": warm.workState,
753
- "app.cache_warming.archived": warm.archived
754
- });
755
- async function scheduleWarmup(message, requestStartedAtMs, warm) {
756
- const { cacheExpiresAtMs, delayMs } = warmupTiming(requestStartedAtMs, warm.cacheTtlMs);
757
- await sendCacheWarmup({
758
- ...message,
759
- cacheExpiresAtMs
760
- }, delayMs);
761
- }
762
- function snapshotContext(context) {
763
- return {
764
- ...context.systemPrompt !== void 0 ? { systemPrompt: context.systemPrompt } : void 0,
765
- messages: context.messages,
766
- ...context.tools ? { tools: context.tools.map((tool) => ({
767
- name: tool.name,
768
- description: tool.description,
769
- parameters: tool.parameters,
770
- ...tool.constrainedSampling !== void 0 ? { constrainedSampling: tool.constrainedSampling } : void 0
771
- })) } : void 0
772
- };
773
- }
774
- async function recordGap(state, conversationId, generation, warm, gapMs) {
775
- if (!await state.setIfNotExists(gapClaimKey(conversationId, generation), true, CONVERSATION_STATE_TTL_MS)) return;
776
- await state.appendToList(segmentGapsKey(warm.segment), gapMs, {
777
- maxLength: GLOBAL_GAPS_MAX,
778
- ttlMs: GLOBAL_GAPS_TTL_MS
779
- });
780
- await state.appendToList(conversationGapsKey(conversationId, warm.segment), gapMs, {
781
- maxLength: CONVERSATION_GAPS_MAX,
782
- ttlMs: CONVERSATION_STATE_TTL_MS
783
- });
784
- }
785
- async function startIdlePeriod(state, conversationId, request, message, turn) {
786
- const idle = {
787
- generation: randomUUID(),
788
- sinceMs: request.startedAtMs
789
- };
790
- const prefixTokens = cachedPrefixTokens(message);
791
- const ttlMs = cacheTtlMs(request);
792
- if (ttlMs === void 0 || prefixTokens < 5e4) return idle;
793
- const snapshot = (await zstdCompress$1(JSON.stringify(snapshotContext(request.context)), SNAPSHOT_ZSTD_PARAMS)).toString("base64");
794
- if (snapshot.length > MAX_SNAPSHOT_BYTES) {
795
- logInfo("cache_warming.snapshot.skipped", {
796
- "app.cache_warming.prefix_tokens": prefixTokens,
797
- "app.cache_warming.snapshot_bytes": snapshot.length
798
- });
799
- return idle;
800
- }
801
- const segmentState = await readSegmentState(conversationId, Date.now());
802
- await state.set(snapshotKey(conversationId, idle.generation), snapshot, IDLE_HORIZON_MS);
803
- const segmentInput = {
804
- ...turn,
805
- ...segmentState
806
- };
807
- const parentSegment = parentGapSegment(segmentInput);
808
- return {
809
- ...idle,
810
- warm: {
811
- segment: gapSegment(segmentInput),
812
- ...parentSegment ? { parentSegment } : void 0,
813
- ...segmentState,
814
- modelId: request.model.id,
815
- prefixTokens,
816
- cacheTtlMs: ttlMs,
817
- ...request.reasoning ? { reasoning: request.reasoning } : void 0
818
- }
819
- };
820
- }
821
- async function recordModelCall(conversationId, userActor, request, message) {
822
- const state = await connectedState();
823
- const previous = await state.get(conversationKey(conversationId));
824
- const idle = previous?.idle;
825
- if (idle?.warm) {
826
- const gapMs = request.startedAtMs - idle.sinceMs;
827
- if (gapMs > 0) await recordGap(state, conversationId, idle.generation, idle.warm, gapMs);
828
- await state.delete(snapshotKey(conversationId, idle.generation));
829
- const warmups = await state.get(warmupsKey(conversationId, idle.generation)) ?? 0;
830
- if (warmups > 0) logInfo("cache_warming.conversation.returned", {
831
- "app.cache_warming.gap_ms": gapMs,
832
- "app.cache_warming.prefix_tokens": idle.warm.prefixTokens,
833
- "app.cache_warming.warmup_count": warmups,
834
- ...segmentAttributes(idle.warm),
835
- "gen_ai.usage.cache_read.input_tokens": message.usage.cacheRead,
836
- "gen_ai.usage.cache_creation.input_tokens": message.usage.cacheWrite
837
- });
838
- }
839
- const endedTurns = previous?.endedTurns ?? 0;
840
- const next = message.stopReason === "stop" ? {
841
- endedTurns: endedTurns + 1,
842
- idle: await startIdlePeriod(state, conversationId, request, message, {
843
- userActor,
844
- endedTurns
845
- })
846
- } : { endedTurns };
847
- if (!idle && !next.idle) return;
848
- await state.set(conversationKey(conversationId), next, CONVERSATION_STATE_TTL_MS);
849
- if (next.idle?.warm) {
850
- const { generation } = next.idle;
851
- await sendCacheWarmup({
852
- kind: "horizon",
853
- conversationId,
854
- generation
855
- }, request.startedAtMs + IDLE_HORIZON_MS - Date.now());
856
- await scheduleWarmup({
857
- kind: "warmup",
858
- conversationId,
859
- cycle: 1,
860
- generation
861
- }, request.startedAtMs, next.idle.warm);
862
- }
863
- }
864
- async function stopIdleWarmups(conversationId) {
865
- try {
866
- const state = await connectedState();
867
- const idle = (await state.get(conversationKey(conversationId)))?.idle;
868
- if (idle?.warm) await state.delete(snapshotKey(conversationId, idle.generation));
869
- } catch (error) {
870
- logWarn("cache_warming.idle_period.stop_failed", { "exception.message": error instanceof Error ? error.message : String(error) });
871
- }
872
- }
873
- /**
874
- * Create a recorder for one agent run. `userActor` is true when a person
875
- * started the Turn. A failure to record only loses cache warming, so it is
876
- * logged and does not stop the run.
877
- */
878
- function createCacheWarmingRecorder(conversationId, userActor) {
879
- let lastRequest;
880
- let idleEnded = false;
881
- let warmupsStopped;
882
- const toolWait = createToolWaitWarmer(conversationId);
883
- return {
884
- wrap: (base = streamSimple) => (model, context, options) => {
885
- if (!warmupsStopped && getChatConfig().cacheWarmingEnabled) warmupsStopped = stopIdleWarmups(conversationId);
886
- toolWait.stop();
887
- const cacheRetention = options?.cacheRetention ?? (getChatConfig().cacheWarmingEnabled ? "short" : void 0);
888
- lastRequest = {
889
- model,
890
- context: {
891
- ...context,
892
- messages: [...context.messages]
893
- },
894
- ...options?.reasoning ? { reasoning: options.reasoning } : void 0,
895
- ...cacheRetention ? { cacheRetention } : void 0,
896
- startedAtMs: Date.now()
897
- };
898
- return base(model, context, cacheRetention ? {
899
- ...options,
900
- cacheRetention
901
- } : options);
902
- },
903
- record: async (message) => {
904
- const request = lastRequest;
905
- lastRequest = void 0;
906
- await warmupsStopped;
907
- if (!getChatConfig().cacheWarmingEnabled || !request) return;
908
- try {
909
- await toolWait.record(request, message);
910
- } catch (error) {
911
- logWarn("cache_warming.tool_wait.record_failed", { "exception.message": error instanceof Error ? error.message : String(error) });
912
- }
913
- if (message.stopReason === "error" || message.stopReason === "aborted" || idleEnded && message.stopReason !== "stop") return;
914
- idleEnded = message.stopReason !== "stop";
915
- try {
916
- await recordModelCall(conversationId, userActor, request, message);
917
- } catch (error) {
918
- logWarn("cache_warming.model_call.record_failed", { "exception.message": error instanceof Error ? error.message : String(error) });
919
- }
920
- },
921
- toolsReturned: toolWait.toolsReturned,
922
- stop: async () => {
923
- try {
924
- await toolWait.end();
925
- } catch (error) {
926
- logWarn("cache_warming.tool_wait.record_failed", { "exception.message": error instanceof Error ? error.message : String(error) });
927
- }
928
- }
929
- };
930
- }
931
- /**
932
- * Run one scheduled cache warming message. A message for an idle period that
933
- * already ended does nothing.
934
- */
935
- async function runCacheWarmup(message) {
936
- const { conversationId } = message;
937
- const state = await connectedState();
938
- const idle = (await state.get(conversationKey(conversationId)))?.idle;
939
- const warm = idle?.warm;
940
- if (!idle || !warm || idle.generation !== message.generation) return;
941
- const { generation } = idle;
942
- const stop = () => state.delete(snapshotKey(conversationId, generation));
943
- if (message.kind === "horizon") {
944
- await stop();
945
- await recordGap(state, conversationId, generation, warm, NO_REPLY_GAP_MS);
946
- return;
947
- }
948
- if ((await state.get(warmupsKey(conversationId, generation)) ?? 0) !== message.cycle - 1) return;
949
- const attributes = {
950
- "app.cache_warming.cycle": message.cycle,
951
- "app.cache_warming.prefix_tokens": warm.prefixTokens,
952
- "app.cache_warming.trigger": "idle",
953
- ...segmentAttributes(warm),
954
- "app.cache_warming.cache_ttl_left_ms": message.cacheExpiresAtMs - Date.now()
955
- };
956
- await withSpan("cache_warming.warmup", "cache_warming.warmup", {
957
- conversationId,
958
- modelId: warm.modelId
959
- }, async (setSpanAttributes) => {
960
- const setOutcome = (outcome, extra = {}) => setSpanAttributes({
961
- ...attributes,
962
- ...extra,
963
- "app.cache_warming.outcome": outcome
964
- });
965
- const skip = async (reason) => {
966
- const skipReason = { "app.cache_warming.skip_reason": reason };
967
- logInfo("cache_warming.warmup.skipped", {
968
- ...attributes,
969
- ...skipReason
970
- });
971
- setOutcome("skipped", skipReason);
972
- await stop();
973
- };
974
- if (warmupTooLate(message.cacheExpiresAtMs)) {
975
- await skip("cache_expired");
976
- return;
977
- }
978
- if (await breakerOpen(state, warm.modelId)) {
979
- await skip("breaker_open");
980
- return;
981
- }
982
- const model = resolveGatewayModel(warm.modelId);
983
- const globalGapsMs = await state.getList(segmentGapsKey(warm.segment));
984
- const decision = decideWarmup({
985
- conversationGapsMs: await state.getList(conversationGapsKey(conversationId, warm.segment)),
986
- globalGapsMs,
987
- ...warm.parentSegment && segmentNeedsParent(globalGapsMs.length) ? { parentGapsMs: await state.getList(segmentGapsKey(warm.parentSegment)) } : void 0,
988
- idleMs: Date.now() - idle.sinceMs,
989
- cacheExpiryIdleMs: message.cacheExpiresAtMs - idle.sinceMs,
990
- cacheTtlMs: warm.cacheTtlMs,
991
- prefixTokens: warm.prefixTokens,
992
- cacheReadPrice: model.cost.cacheRead,
993
- cacheWritePrice: model.cost.cacheWrite
994
- });
995
- attributes["app.cache_warming.return_probability"] = decision.returnProbability;
996
- attributes["app.cache_warming.returns_per_warmup"] = decision.returnsPerWarmup;
997
- attributes["app.cache_warming.threshold"] = decision.threshold;
998
- attributes["app.cache_warming.parent_prior"] = decision.parentPrior;
999
- if (!decision.warm) {
1000
- await skip(decision.reason);
1001
- return;
1002
- }
1003
- const snapshot = await state.get(snapshotKey(conversationId, generation));
1004
- if (!snapshot) {
1005
- setOutcome("skipped", { "app.cache_warming.skip_reason": "stopped" });
1006
- return;
1007
- }
1008
- const context = JSON.parse((await zstdDecompress$1(Buffer.from(snapshot, "base64"))).toString("utf8"));
1009
- const startedAtMs = Date.now();
1010
- const warmup = await sendWarmup(state, {
1011
- conversationId,
1012
- modelId: warm.modelId,
1013
- context,
1014
- ...warm.reasoning ? { reasoning: warm.reasoning } : void 0,
1015
- prefixTokens: warm.prefixTokens
1016
- }).catch(async (error) => {
1017
- setOutcome("failed");
1018
- await stop();
1019
- throw error;
1020
- });
1021
- Object.assign(attributes, warmup.attributes);
1022
- if (!warmup.refreshed) {
1023
- logWarn("cache_warming.warmup.failed", attributes);
1024
- setOutcome("missed");
1025
- await stop();
1026
- return;
1027
- }
1028
- logInfo("cache_warming.warmup.completed", attributes);
1029
- setOutcome("completed");
1030
- await state.set(warmupsKey(conversationId, generation), message.cycle, IDLE_HORIZON_MS);
1031
- if (await state.get(snapshotKey(conversationId, generation))) await scheduleWarmup({
1032
- kind: "warmup",
1033
- conversationId,
1034
- cycle: message.cycle + 1,
1035
- generation
1036
- }, startedAtMs, warm);
1037
- }, attributes);
1038
- }
1039
- export { segmentGapsKey as a, listConversationWork as c, IDLE_HORIZON_MS as d, MINUTE_MS as f, gapSegment as g, gapHistogramReport as h, createCacheWarmingRecorder as i, readLastUserMessageAtByConversation as l, NO_REPLY_GAP_MS as m, GLOBAL_GAPS_MAX as n, warmup_exports as o, MIN_WARMUP_PREFIX_TOKENS as p, GLOBAL_GAPS_TTL_MS as r, isConversationWorkDone as s, CONVERSATION_STATE_TTL_MS as t, GAP_SEGMENTS as u };