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