@sentry/junior 0.295.0 → 0.296.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 (62) hide show
  1. package/dist/{admin-ifgjyfpF.js → admin-z_lgDi-z.js} +2 -2
  2. package/dist/{agent-runner-DjMTPWEO.js → agent-runner-HoQiUKLL.js} +194 -132
  3. package/dist/api/schema.d.ts +1 -1
  4. package/dist/api/schema.js +1 -1
  5. package/dist/api.d.ts +1 -1
  6. package/dist/api.js +294 -328
  7. package/dist/{app-uiTzRbvq.d.ts → app-C75Ft-A_.d.ts} +2 -2
  8. package/dist/app.d.ts +1 -1
  9. package/dist/app.js +26 -26
  10. package/dist/{background-compaction-queue-DUkHZjmL.js → background-compaction-queue-Cre1wFt9.js} +4 -4
  11. package/dist/{briefs-CbNYM-q2.js → briefs-BXECHduJ.js} +2 -2
  12. package/dist/{catalog-runtime-DgouZKZm.js → catalog-runtime-CpCmlD9L.js} +1 -1
  13. package/dist/cli/chat.js +14 -14
  14. package/dist/cli/check.js +3 -3
  15. package/dist/cli/main.js +3 -3
  16. package/dist/cli/plugins.js +4 -4
  17. package/dist/cli/snapshot-create.js +4 -4
  18. package/dist/cli/upgrade.d.ts +1 -1
  19. package/dist/cli/upgrade.js +3 -3
  20. package/dist/{config-DvnTPCfp.js → config-CCPHvTqx.js} +18 -2
  21. package/dist/{connections-CWaIVl_1.js → connections-B5pWh8e2.js} +6 -6
  22. package/dist/{conversation-privacy-DPjv4SnA.js → conversation-privacy-CZD5soDW.js} +1 -1
  23. package/dist/{credential-sync-BhbaZfmO.js → credential-sync-DwLkIvXI.js} +13 -13
  24. package/dist/{db-CCUqQe0E.d.ts → db-B3iyr_Or.d.ts} +1 -1
  25. package/dist/{db-Dts2XvLu.js → db-C1M1y-bh.js} +17 -23
  26. package/dist/{executor-Ck73J0wP.js → executor-DUSEwXaO.js} +10 -4
  27. package/dist/instrumentation.js +19 -2
  28. package/dist/{logging-9OAq-fdg.js → logging-D0svFM8r.js} +1 -1
  29. package/dist/{message-CtaPzC7m.js → message-BFnIwKpx.js} +9 -9
  30. package/dist/nitro.d.ts +1 -1
  31. package/dist/nitro.js +2 -2
  32. package/dist/{oauth-callback-server-C_LXY1d4.js → oauth-callback-server-BXRtD6Fk.js} +2 -2
  33. package/dist/{projection-BzJQncZV.js → projection-B6VS7kbo.js} +156 -49
  34. package/dist/{prompt-Cbq5b4SO.js → prompt-CD11tfG8.js} +3 -3
  35. package/dist/{registry-cbpOxO4M.js → registry-CHewwYEo.js} +1 -1
  36. package/dist/{resolve-t-pmRdwS.js → resolve-1owMH4qo.js} +3 -3
  37. package/dist/{result-DhgjR3nQ.js → result-CEqQFrEf.js} +8 -8
  38. package/dist/{runner-CHv9X9TH.js → runner-BtWvJslp.js} +7 -7
  39. package/dist/{sandbox-egress-signals-Yy3fSCbg.js → sandbox-egress-signals-ByftwJVt.js} +1 -1
  40. package/dist/{schema-TSEisVJR.d.ts → schema-Ct1Zf2xy.d.ts} +16 -0
  41. package/dist/{schema-BhneuGYv.js → schema-D2iGyYIp.js} +11 -0
  42. package/dist/{service-account-C4rBP8ne.js → service-account-BZEuMKdo.js} +3 -3
  43. package/dist/{service-account-DjPIwCMj.js → service-account-DLoeoHww.js} +3 -3
  44. package/dist/{session-stop-DkxI5vc3.js → session-stop-hYNTNpVf.js} +14 -14
  45. package/dist/{skills-BZE2DP8I.js → skills-DXgd5Inh.js} +3 -3
  46. package/dist/{spawn-BvULxIiu.js → spawn-YeqlNDv8.js} +5 -5
  47. package/dist/{state-CO9ETDzk.js → state-C3CbtD_m.js} +2 -2
  48. package/dist/{stop-CL-rdtQb.js → stop-Cze_pEL8.js} +288 -246
  49. package/dist/{store-DgD78_NK.js → store-CZ9vqR4P.js} +3 -3
  50. package/dist/{task-runner-CKOj6xla.js → task-runner-CMiNGsER.js} +274 -250
  51. package/dist/{turn-failure-response-BTSo6SMJ.js → turn-failure-response-pXhZ2wMK.js} +11 -8
  52. package/dist/{validation-CXeYgBzq.js → validation-Du7NdkOR.js} +1 -1
  53. package/dist/{version-AQa7Fr2H.js → version-EN3Wnq-R.js} +1 -1
  54. package/dist/version.js +1 -1
  55. package/dist/{viewer-Bqkb678l.js → viewer-Agxi_o5c.js} +3 -3
  56. package/dist/{warmup-h6u1e9n0.js → warmup-CY2ArYag.js} +251 -103
  57. package/dist/{work-yN_GAuXY.js → work-EA98F0ia.js} +11 -11
  58. package/dist/{worker-Hl7N292I.js → worker-BALVdWbv.js} +6 -6
  59. package/migrations/0101_drop_legacy_columns.sql +12 -0
  60. package/migrations/meta/0101_snapshot.json +4496 -0
  61. package/migrations/meta/_journal.json +7 -0
  62. package/package.json +5 -4
@@ -1,13 +1,13 @@
1
- import { n as captureMessage, v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { $t as extractAssistantText, Bn as getPlugins, Ha as SANDBOX_WORKSPACE_ROOT, Ln as getPluginSystemPromptContributions, Po as createPluginCache, Ua as sandboxSkillDir, Xa as createPluginLogger, _n as TURN_CONTEXT_TAG, dn as normalizeToolNameFromResult, gn as SESSION_CONTEXT_SECTION_TAG, hn as REQUEST_CONTEXT_SECTION_TAG, ln as isToolResultError, on as isAssistantMessage, un as isToolResultMessage, za as SANDBOX_DATA_ROOT } from "./projection-BzJQncZV.js";
3
- import { E as resolveGatewayModel, K as isProviderRetryError, L as escapeXml, R as escapeXmlText, i as getChatConfig, n as botConfig } from "./config-DvnTPCfp.js";
4
- import { E as withSpan, h as logWarn, m as logInfo, x as setSpanStatus } from "./logging-9OAq-fdg.js";
5
- import { $ as rootConversationIsArchived, a as getConversationStore, b as userMessageQueries, o as getDb, s as getSqlExecutor } from "./db-Dts2XvLu.js";
6
- import { A as juniorConversations } from "./executor-Ck73J0wP.js";
1
+ import { n as captureMessage, u as sentry_exports, v as __exportAll } from "./sentry-BRTJqumy.js";
2
+ import { $t as extractAssistantText, Bn as getPlugins, Ha as SANDBOX_WORKSPACE_ROOT, Ln as getPluginSystemPromptContributions, Po as createPluginCache, Ua as sandboxSkillDir, Xa as createPluginLogger, _n as TURN_CONTEXT_TAG, dn as normalizeToolNameFromResult, gn as SESSION_CONTEXT_SECTION_TAG, hn as REQUEST_CONTEXT_SECTION_TAG, ln as isToolResultError, on as isAssistantMessage, un as isToolResultMessage, za as SANDBOX_DATA_ROOT } from "./projection-B6VS7kbo.js";
3
+ import { E as resolveGatewayModel, K as isProviderRetryError, L as escapeXml, R as escapeXmlText, i as getChatConfig, n as botConfig } from "./config-CCPHvTqx.js";
4
+ import { E as withSpan, h as logWarn, m as logInfo, x as setSpanStatus } from "./logging-D0svFM8r.js";
5
+ import { $ as rootConversationIsArchived, a as getConversationStore, b as userMessageQueries, o as getDb, s as getSqlExecutor } from "./db-C1M1y-bh.js";
6
+ import { A as juniorConversations } from "./executor-DUSEwXaO.js";
7
7
  import { a as listReferenceFiles, c as soulPathCandidates, l as worldPathCandidates } from "./package-discovery-DJhGdS4c.js";
8
- import { u as completeText } from "./prompt-Cbq5b4SO.js";
9
- import { a as getStateAdapter } from "./state-CO9ETDzk.js";
10
- import { E as sendCacheWarmup } from "./background-compaction-queue-DUkHZjmL.js";
8
+ import { u as completeText } from "./prompt-CD11tfG8.js";
9
+ import { a as getStateAdapter } from "./state-C3CbtD_m.js";
10
+ import { E as sendCacheWarmup } from "./background-compaction-queue-Cre1wFt9.js";
11
11
  import { streamSimple } from "@earendil-works/pi-ai/compat";
12
12
  import path from "node:path";
13
13
  import { promisify } from "node:util";
@@ -39,7 +39,7 @@ function readBlockedReport(messages) {
39
39
  /** No-reply result of a Turn. */
40
40
  /** Model-facing tool that ends a Turn with no reply. */
41
41
  const NO_REPLY_TOOL_NAME = "noReply";
42
- const noReplySchema = z.object({ note: z.string().trim().min(1).optional() });
42
+ const noReplySchema$1 = z.object({ note: z.string().trim().min(1).optional() });
43
43
  /**
44
44
  * Read the last successful no-reply result from the new messages of one run.
45
45
  * Do not pass the whole history: a call from an earlier Turn must not end
@@ -49,7 +49,7 @@ function readNoReply(messages) {
49
49
  for (let index = messages.length - 1; index >= 0; index -= 1) {
50
50
  const message = messages[index];
51
51
  if (!isToolResultMessage(message) || isToolResultError(message) || normalizeToolNameFromResult(message) !== "noReply") continue;
52
- const parsed = noReplySchema.safeParse(message.details);
52
+ const parsed = noReplySchema$1.safeParse(message.details);
53
53
  if (parsed.success) return parsed.data;
54
54
  }
55
55
  }
@@ -94,85 +94,87 @@ function getAssistantReplyText(message) {
94
94
  const decision = decideReply(message);
95
95
  return decision.kind === "deliver" ? decision.text : void 0;
96
96
  }
97
- // src/chat/automation-result.ts
97
+ // src/chat/turn-answer.ts
98
98
  /**
99
- * Automation run result.
99
+ * Answer of a gated Turn.
100
100
  *
101
- * A Scheduled automation or Event automation run ends with one declared
102
- * result. The run does not deliver its final response. The work owner
103
- * reads the declared result and applies the stored outcomes.
101
+ * A gated Turn ends with one answer tool: `reply`, `noReply`, or
102
+ * `reportBlocked`. Its final response is not delivered. The runtime reads the
103
+ * answer and decides what to post.
104
104
  */
105
- /** Model-facing tool that ends an Automation run. */
106
- const FINISH_AUTOMATION_RUN_TOOL_NAME = "finishAutomationRun";
107
- /** One declared result for an Automation run. */
108
- const automationResultSchema = z.discriminatedUnion("result", [
105
+ /** Model-facing tool that sets the reply of a gated Turn. */
106
+ const REPLY_TOOL_NAME = "reply";
107
+ /** The `reply` text gets the same cleanup as a chat reply. */
108
+ const replyTextSchema = z.string().transform(sanitizeAssistantText).pipe(z.string().min(1));
109
+ const replySchema = z.object({ text: replyTextSchema });
110
+ const noReplySchema = z.object({ note: z.string().trim().min(1).optional() });
111
+ const blockedSchema = z.object({ missing: z.string().trim().min(1) });
112
+ const LEGACY_FINISH_AUTOMATION_RUN_TOOL_NAME = "finishAutomationRun";
113
+ const legacyResultSchema = z.discriminatedUnion("result", [
109
114
  z.object({
110
115
  result: z.literal("send_message"),
111
- message: z.string().transform(sanitizeAssistantText).pipe(z.string().min(1))
116
+ message: replyTextSchema
112
117
  }),
113
118
  z.object({
114
119
  result: z.literal("no_action"),
115
- reason: z.string().trim().min(1)
120
+ reason: z.string()
116
121
  }),
117
122
  z.object({
118
123
  result: z.literal("misconfigured"),
119
- reason: z.string().trim().min(1)
124
+ reason: z.string().min(1)
120
125
  })
121
126
  ]);
122
- /**
123
- * Return the text to post after a run ends, if any. A chat Turn already
124
- * delivered a successful reply, so it posts only its failure reply. An
125
- * Automation run posts only a declared message. It never posts a failure
126
- * reply to its outcomes. The failed execution shows on the Automation.
127
- */
128
- function finishedRunReply(result, dispatch) {
129
- if (!dispatch?.declaresResult) return result.diagnostics.outcome === "success" ? void 0 : result.text;
130
- return result.diagnostics.outcome === "success" && result.automation?.result === "send_message" && dispatch.outcomes?.length !== 0 ? result.text : void 0;
127
+ function parseAnswer(toolName, details) {
128
+ switch (toolName) {
129
+ case REPLY_TOOL_NAME: {
130
+ const parsed = replySchema.safeParse(details);
131
+ return parsed.success ? { reply: parsed.data } : void 0;
132
+ }
133
+ case NO_REPLY_TOOL_NAME: {
134
+ const parsed = noReplySchema.safeParse(details);
135
+ return parsed.success ? { noReply: parsed.data } : void 0;
136
+ }
137
+ case REPORT_BLOCKED_TOOL_NAME: {
138
+ const parsed = blockedSchema.safeParse(details);
139
+ return parsed.success ? { blocked: parsed.data } : void 0;
140
+ }
141
+ case LEGACY_FINISH_AUTOMATION_RUN_TOOL_NAME: {
142
+ const parsed = legacyResultSchema.safeParse(details);
143
+ if (!parsed.success) return void 0;
144
+ switch (parsed.data.result) {
145
+ case "send_message": return { reply: { text: parsed.data.message } };
146
+ case "no_action": return { noReply: {} };
147
+ case "misconfigured": return { blocked: { missing: parsed.data.reason } };
148
+ }
149
+ }
150
+ }
131
151
  }
132
152
  /**
133
- * Read the last successful declared result from agent history items.
134
- *
135
- * Pass the whole run history, not only the current slice. An Automation run
136
- * owns its dispatch Conversation, and a resumed slice must see a result that
137
- * an earlier slice already saved.
153
+ * Read the last successful answer from the messages of one Turn. Do not pass
154
+ * the whole history: an answer from an earlier Turn must not end this one.
138
155
  */
139
- function readAutomationResult(messages) {
156
+ function readTurnAnswer(messages) {
140
157
  for (let index = messages.length - 1; index >= 0; index -= 1) {
141
158
  const message = messages[index];
142
- if (!isToolResultMessage(message) || isToolResultError(message) || normalizeToolNameFromResult(message) !== "finishAutomationRun") continue;
143
- const parsed = automationResultSchema.safeParse(message.details);
144
- if (parsed.success) return parsed.data;
159
+ if (!isToolResultMessage(message) || isToolResultError(message)) continue;
160
+ const answer = parseAnswer(normalizeToolNameFromResult(message), message.details);
161
+ if (answer) return answer;
145
162
  }
146
163
  }
164
+ const MISSING_ANSWER_REMINDER = `This Turn has not ended. Your text was not delivered. Call \`${REPLY_TOOL_NAME}\`, \`${NO_REPLY_TOOL_NAME}\`, or \`${REPORT_BLOCKED_TOOL_NAME}\` now.`;
147
165
  /**
148
- * Map one finished agent run to its dispatch outcome. A declared
149
- * `misconfigured` result becomes a blocked dispatch with the declared reason.
166
+ * Return agent history plus a reminder when the model stopped without an
167
+ * answer, or undefined when the Turn already has one. `turnStart` is the
168
+ * index of the Turn's first message in `messages`.
150
169
  */
151
- function runDispatchOutcome(result) {
152
- if (result.diagnostics.outcome !== "success") return {
153
- errorMessage: result.diagnostics.errorMessage ?? `Agent turn ended with ${result.diagnostics.outcome}.`,
154
- outcome: "failed"
155
- };
156
- if (result.automation?.result === "misconfigured") return {
157
- errorMessage: result.automation.reason,
158
- outcome: "blocked"
159
- };
160
- return { outcome: "completed" };
161
- }
162
- /** Reminder for an Automation run that stopped without a declared result. */
163
- const MISSING_RESULT_REMINDER = "This automation run has not ended. Your text was not delivered. Call `finishAutomationRun` now with one result.";
164
- /**
165
- * Return agent history plus a reminder when the model stopped without a
166
- * declared result, or undefined when the run already declared one.
167
- */
168
- function remindMissingAutomationResult(messages) {
170
+ function remindMissingAnswer(messages, turnStart) {
169
171
  const last = messages.at(-1);
170
- if (!isAssistantMessage(last) || last.stopReason !== "stop" || readAutomationResult(messages)) return;
172
+ if (!isAssistantMessage(last) || last.stopReason !== "stop" || readTurnAnswer(messages.slice(turnStart))) return;
171
173
  return [...messages, {
172
174
  role: "user",
173
175
  content: [{
174
176
  type: "text",
175
- text: MISSING_RESULT_REMINDER
177
+ text: MISSING_ANSWER_REMINDER
176
178
  }],
177
179
  timestamp: Date.now()
178
180
  }];
@@ -205,14 +207,15 @@ const AGENT_INPUT_RULES = [
205
207
  /**
206
208
  * Block 2, `<automation-run>`: the job rules for a stored automation. No person
207
209
  * reads the run while it executes, so Junior does the work without waiting.
208
- * A decision that only a person can make goes on the review desk, and the
209
- * run ends with the result tool.
210
+ * A decision that only a person can make goes on the review desk, and each
211
+ * Turn ends with one answer tool.
210
212
  */
211
213
  const AUTOMATION_RUN_RULES = [
212
214
  "- This run comes from a stored automation, not from a person. The stored instruction is the job, and its creator already approved it.",
213
215
  "- Nobody reads this run while it executes. Infer intent conservatively and do the work now. Ask a person with `addReviewItem` only for a decision that is truly theirs and blocks the work.",
214
216
  "- Check every condition in the instruction before any action with side effects. If a condition is not met or cannot be verified, stop before you act.",
215
- `- Assistant text is never delivered. End the run with \`${FINISH_AUTOMATION_RUN_TOOL_NAME}\`. Do not post the result with another tool.`
217
+ `- Assistant text is never delivered. End each Turn with one of \`${REPLY_TOOL_NAME}\`, \`${NO_REPLY_TOOL_NAME}\`, or \`${REPORT_BLOCKED_TOOL_NAME}\`. Do not post the reply with another tool. When \`${REPLY_TOOL_NAME}\` is not available, this automation posts nothing.`,
218
+ `- Use \`${NO_REPLY_TOOL_NAME}\` when the run worked and nothing should be posted, such as when a condition in the instruction is not met, or when a temporary failure stopped the work.`
216
219
  ];
217
220
  /**
218
221
  * Block 2, `<child-agent-run>`: the job rules for a run that a parent agent
@@ -329,10 +332,10 @@ const SLACK_ACTION_RULES = [
329
332
  const FAILURE_REPORTING_RULES = ["- Keep raw tool payloads and internal routing metadata out of the final response."];
330
333
  /**
331
334
  * Block 6, `<failure-reporting>` for automation runs. No person reads the run,
332
- * so a failure that stops the job goes in the declared reason, never in the
333
- * posted message.
335
+ * so a failure that stops the job goes in `noReply` or `reportBlocked`, never
336
+ * in the reply.
334
337
  */
335
- const AUTOMATION_FAILURE_REPORTING_RULES = ["- Keep commands, error output, raw tool payloads, and internal routing metadata out of the message.", `- When a failure stops the job, put its cause in the \`${FINISH_AUTOMATION_RUN_TOOL_NAME}\` reason, not in the message.`];
338
+ const AUTOMATION_FAILURE_REPORTING_RULES = ["- Keep commands, error output, raw tool payloads, and internal routing metadata out of the message.", `- When a failure stops the job, put its cause in the \`note\` of \`${NO_REPLY_TOOL_NAME}\` or the \`missing\` field of \`${REPORT_BLOCKED_TOOL_NAME}\`, not in the reply.`];
336
339
  /**
337
340
  * Block 6, `<failure-reporting>` for child agent runs. A text reply is finished
338
341
  * work, so a failure that stops the task goes in the blocked report.
@@ -1219,6 +1222,103 @@ async function sendWarmup(state, params) {
1219
1222
  attributes
1220
1223
  };
1221
1224
  }
1225
+ // src/chat/cache-warming/snapshot.ts
1226
+ /**
1227
+ * Storage format of the idle-period snapshot: the exact Pi context of the
1228
+ * request that ended a Turn, which each idle warmup sends again.
1229
+ *
1230
+ * Base64 image data does not compress, so one screenshot can make a snapshot
1231
+ * too large to store. The data of each image part moves to its own state key,
1232
+ * named by its SHA-256 hash, and the snapshot keeps `sha256:<hash>` in its
1233
+ * place. Base64 has no `:`, so a reference cannot be image data.
1234
+ * The next Turn's snapshot often holds the same images, so it writes the same
1235
+ * keys again and refreshes their TTL. A loaded snapshot gets each image's
1236
+ * data back at the same JSON position, so the warmup request is the same as
1237
+ * the original request and reads its cached prefix. A snapshot with a missing
1238
+ * image does not load: a changed request would write a new cache entry.
1239
+ * Deleting a snapshot keeps its images, because the next snapshot of the
1240
+ * Conversation likely holds them. They expire with their TTL.
1241
+ * A snapshot whose images are over their own limit is not stored, so one
1242
+ * Conversation cannot keep an unbounded amount of image data in state.
1243
+ * Removing its images would change the request, so it would miss the cache.
1244
+ */
1245
+ const zstdCompress$1 = promisify(zstdCompress);
1246
+ const zstdDecompress$1 = promisify(zstdDecompress);
1247
+ const SNAPSHOT_ZSTD_PARAMS = { params: { [constants.ZSTD_c_compressionLevel]: 1 } };
1248
+ const MAX_SNAPSHOT_BYTES = 1048576;
1249
+ const MAX_SNAPSHOT_IMAGE_BYTES = 8388608;
1250
+ const IMAGE_REF_PREFIX = "sha256:";
1251
+ const imageKey = (conversationId, sha256) => `${KEY_PREFIX}:image:${conversationId}:${sha256}`;
1252
+ function imageParts(message) {
1253
+ if (message.role === "assistant" || typeof message.content === "string") return [];
1254
+ return message.content.filter((part) => part.type === "image");
1255
+ }
1256
+ function snapshotContext(context, toRef) {
1257
+ return {
1258
+ ...context.systemPrompt !== void 0 ? { systemPrompt: context.systemPrompt } : void 0,
1259
+ messages: context.messages.map((message) => message.role === "assistant" || typeof message.content === "string" ? message : {
1260
+ ...message,
1261
+ content: message.content.map(toRef)
1262
+ }),
1263
+ ...context.tools ? { tools: context.tools.map((tool) => ({
1264
+ name: tool.name,
1265
+ description: tool.description,
1266
+ parameters: tool.parameters,
1267
+ ...tool.constrainedSampling !== void 0 ? { constrainedSampling: tool.constrainedSampling } : void 0
1268
+ })) } : void 0
1269
+ };
1270
+ }
1271
+ /**
1272
+ * Store the snapshot of a request context with its images under hash keys.
1273
+ * Stores nothing and returns a `skipReason` when the snapshot without its
1274
+ * images or the images are over their limit. Every key expires after `ttlMs`.
1275
+ */
1276
+ async function saveSnapshot(state, conversationId, key, context, ttlMs) {
1277
+ const images = /* @__PURE__ */ new Map();
1278
+ const toRef = (part) => {
1279
+ if (part.type !== "image") return part;
1280
+ const sha256 = createHash("sha256").update(part.data).digest("hex");
1281
+ images.set(sha256, part.data);
1282
+ return {
1283
+ ...part,
1284
+ data: `${IMAGE_REF_PREFIX}${sha256}`
1285
+ };
1286
+ };
1287
+ const snapshot = (await zstdCompress$1(JSON.stringify(snapshotContext(context, toRef)), SNAPSHOT_ZSTD_PARAMS)).toString("base64");
1288
+ const size = {
1289
+ bytes: snapshot.length,
1290
+ imageCount: images.size,
1291
+ imageBytes: [...images.values()].reduce((sum, data) => sum + data.length, 0)
1292
+ };
1293
+ if (size.bytes > MAX_SNAPSHOT_BYTES) return {
1294
+ ...size,
1295
+ skipReason: "snapshot_too_large"
1296
+ };
1297
+ if (size.imageBytes > MAX_SNAPSHOT_IMAGE_BYTES) return {
1298
+ ...size,
1299
+ skipReason: "images_too_large"
1300
+ };
1301
+ await state.set(key, snapshot, ttlMs);
1302
+ await Promise.all([...images].map(([sha256, data]) => state.set(imageKey(conversationId, sha256), data, ttlMs)));
1303
+ return size;
1304
+ }
1305
+ /**
1306
+ * Load a stored snapshot with its image data. Returns `stopped` when the
1307
+ * snapshot is gone and `image_missing` when one of its images is gone.
1308
+ */
1309
+ async function loadSnapshot(state, conversationId, key) {
1310
+ const snapshot = await state.get(key);
1311
+ if (!snapshot) return "stopped";
1312
+ const context = JSON.parse((await zstdDecompress$1(Buffer.from(snapshot, "base64"))).toString("utf8"));
1313
+ for (const part of context.messages.flatMap(imageParts)) {
1314
+ if (!part.data.startsWith(IMAGE_REF_PREFIX)) continue;
1315
+ const sha256 = part.data.slice(7);
1316
+ const data = await state.get(imageKey(conversationId, sha256));
1317
+ if (data === null) return "image_missing";
1318
+ part.data = data;
1319
+ }
1320
+ return context;
1321
+ }
1222
1322
  // src/chat/cache-warming/tool-wait.ts
1223
1323
  const TOOL_WAIT_GAPS_KEY = `${KEY_PREFIX}:gaps:tool_wait`;
1224
1324
  const TOOL_WAIT_GAPS_MAX = 2e3;
@@ -1545,9 +1645,6 @@ var warmup_exports = /* @__PURE__ */ __exportAll({
1545
1645
  runCacheWarmup: () => runCacheWarmup,
1546
1646
  segmentGapsKey: () => segmentGapsKey
1547
1647
  });
1548
- const zstdCompress$1 = promisify(zstdCompress);
1549
- const zstdDecompress$1 = promisify(zstdDecompress);
1550
- const SNAPSHOT_ZSTD_PARAMS = { params: { [constants.ZSTD_c_compressionLevel]: 1 } };
1551
1648
  /** Gaps kept in each segment list. */
1552
1649
  const GLOBAL_GAPS_MAX = 2e3;
1553
1650
  /** A segment list expires this long after its last gap. */
@@ -1555,7 +1652,6 @@ const GLOBAL_GAPS_TTL_MS = 43200 * MINUTE_MS;
1555
1652
  const CONVERSATION_GAPS_MAX = 50;
1556
1653
  /** The Turn count of a Conversation resets after this long with no call. */
1557
1654
  const CONVERSATION_STATE_TTL_MS = 10080 * MINUTE_MS;
1558
- const MAX_SNAPSHOT_BYTES = 1048576;
1559
1655
  /** State list of the recent reply gaps (ms) of one `gapSegment`. */
1560
1656
  const segmentGapsKey = (segment) => `${KEY_PREFIX}:gaps:${segment}`;
1561
1657
  const conversationKey = (conversationId) => `${KEY_PREFIX}:conversation:${conversationId}`;
@@ -1572,7 +1668,13 @@ const warmupsKey = (conversationId, generation) => `${KEY_PREFIX}:warmups:${conv
1572
1668
  const gapClaimKey = (conversationId, generation) => `${KEY_PREFIX}:gap_claim:${conversationId}:${generation}`;
1573
1669
  const segmentAttributes = (warm) => ({
1574
1670
  "app.cache_warming.work_state": warm.workState,
1575
- "app.cache_warming.archived": warm.archived
1671
+ "app.cache_warming.archived": warm.archived,
1672
+ ...warm.turnEnding ? { "app.cache_warming.turn_ending": warm.turnEnding } : void 0
1673
+ });
1674
+ const snapshotAttributes = (size) => ({
1675
+ "app.cache_warming.snapshot_bytes": size.bytes,
1676
+ "app.cache_warming.snapshot_image_count": size.imageCount,
1677
+ "app.cache_warming.snapshot_image_bytes": size.imageBytes
1576
1678
  });
1577
1679
  async function scheduleWarmup(message, requestStartedAtMs, warm) {
1578
1680
  const { cacheExpiresAtMs, delayMs } = warmupTiming(requestStartedAtMs, warm.cacheTtlMs);
@@ -1581,18 +1683,6 @@ async function scheduleWarmup(message, requestStartedAtMs, warm) {
1581
1683
  cacheExpiresAtMs
1582
1684
  }, delayMs);
1583
1685
  }
1584
- function snapshotContext(context) {
1585
- return {
1586
- ...context.systemPrompt !== void 0 ? { systemPrompt: context.systemPrompt } : void 0,
1587
- messages: context.messages,
1588
- ...context.tools ? { tools: context.tools.map((tool) => ({
1589
- name: tool.name,
1590
- description: tool.description,
1591
- parameters: tool.parameters,
1592
- ...tool.constrainedSampling !== void 0 ? { constrainedSampling: tool.constrainedSampling } : void 0
1593
- })) } : void 0
1594
- };
1595
- }
1596
1686
  async function recordGap(state, conversationId, generation, warm, gapMs) {
1597
1687
  if (!await state.setIfNotExists(gapClaimKey(conversationId, generation), true, CONVERSATION_STATE_TTL_MS)) return;
1598
1688
  await state.appendToList(segmentGapsKey(warm.segment), gapMs, {
@@ -1604,7 +1694,7 @@ async function recordGap(state, conversationId, generation, warm, gapMs) {
1604
1694
  ttlMs: CONVERSATION_STATE_TTL_MS
1605
1695
  });
1606
1696
  }
1607
- async function startIdlePeriod(state, conversationId, request, message, turn, systemPrompt) {
1697
+ async function startIdlePeriod(state, conversationId, request, message, turn, systemPrompt, turnEnding) {
1608
1698
  const idle = {
1609
1699
  generation: randomUUID(),
1610
1700
  sinceMs: request.startedAtMs
@@ -1612,16 +1702,22 @@ async function startIdlePeriod(state, conversationId, request, message, turn, sy
1612
1702
  const prefixTokens = cachedPrefixTokens(message);
1613
1703
  const ttlMs = cacheTtlMs(request);
1614
1704
  if (ttlMs === void 0 || prefixTokens < 5e4) return idle;
1615
- const snapshot = (await zstdCompress$1(JSON.stringify(snapshotContext(request.context)), SNAPSHOT_ZSTD_PARAMS)).toString("base64");
1616
- if (snapshot.length > MAX_SNAPSHOT_BYTES) {
1617
- logInfo("cache_warming.snapshot.skipped", {
1705
+ const { skipReason, ...snapshot } = await saveSnapshot(state, conversationId, snapshotKey(conversationId, idle.generation), request.context, IDLE_HORIZON_MS);
1706
+ const metricOptions = {
1707
+ unit: "byte",
1708
+ attributes: { "app.cache_warming.stored": skipReason === void 0 }
1709
+ };
1710
+ sentry_exports.metrics.distribution("cache_warming.snapshot.bytes", snapshot.bytes, metricOptions);
1711
+ sentry_exports.metrics.distribution("cache_warming.snapshot.image_bytes", snapshot.imageBytes, metricOptions);
1712
+ if (skipReason) {
1713
+ logWarn("cache_warming.snapshot.skipped", {
1714
+ "app.cache_warming.skip_reason": skipReason,
1618
1715
  "app.cache_warming.prefix_tokens": prefixTokens,
1619
- "app.cache_warming.snapshot_bytes": snapshot.length
1716
+ ...snapshotAttributes(snapshot)
1620
1717
  });
1621
1718
  return idle;
1622
1719
  }
1623
1720
  const segmentState = await readSegmentState(conversationId, Date.now());
1624
- await state.set(snapshotKey(conversationId, idle.generation), snapshot, IDLE_HORIZON_MS);
1625
1721
  const segmentInput = {
1626
1722
  ...turn,
1627
1723
  ...segmentState
@@ -1631,6 +1727,7 @@ async function startIdlePeriod(state, conversationId, request, message, turn, sy
1631
1727
  ...idle,
1632
1728
  warm: {
1633
1729
  segment: gapSegment(segmentInput),
1730
+ turnEnding,
1634
1731
  ...parentSegment ? { parentSegment } : void 0,
1635
1732
  ...request.context.systemPrompt !== void 0 ? { systemPrompt: {
1636
1733
  ...systemPrompt,
@@ -1640,11 +1737,12 @@ async function startIdlePeriod(state, conversationId, request, message, turn, sy
1640
1737
  modelId: request.model.id,
1641
1738
  prefixTokens,
1642
1739
  cacheTtlMs: ttlMs,
1643
- ...request.reasoning ? { reasoning: request.reasoning } : void 0
1740
+ ...request.reasoning ? { reasoning: request.reasoning } : void 0,
1741
+ snapshot
1644
1742
  }
1645
1743
  };
1646
1744
  }
1647
- async function recordModelCall(conversationId, userActor, systemPrompt, request, message) {
1745
+ async function recordModelCall(conversationId, userActor, systemPrompt, request, message, turnEnding) {
1648
1746
  const state = await connectedState();
1649
1747
  const previous = await state.get(conversationKey(conversationId));
1650
1748
  const idle = previous?.idle;
@@ -1663,12 +1761,12 @@ async function recordModelCall(conversationId, userActor, systemPrompt, request,
1663
1761
  });
1664
1762
  }
1665
1763
  const endedTurns = previous?.endedTurns ?? 0;
1666
- const next = message.stopReason === "stop" ? {
1764
+ const next = turnEnding ? {
1667
1765
  endedTurns: endedTurns + 1,
1668
1766
  idle: await startIdlePeriod(state, conversationId, request, message, {
1669
1767
  userActor,
1670
1768
  endedTurns
1671
- }, systemPrompt)
1769
+ }, systemPrompt, turnEnding)
1672
1770
  } : { endedTurns };
1673
1771
  if (!idle && !next.idle) return;
1674
1772
  await state.set(conversationKey(conversationId), next, CONVERSATION_STATE_TTL_MS);
@@ -1703,6 +1801,8 @@ async function stopIdleWarmups(conversationId) {
1703
1801
  */
1704
1802
  function createCacheWarmingRecorder(conversationId, userActor, systemPrompt) {
1705
1803
  let lastRequest;
1804
+ let lastCall;
1805
+ let noReplyEnded = false;
1706
1806
  let idleEnded = false;
1707
1807
  let warmupsStopped;
1708
1808
  const toolWait = createToolWaitWarmer(conversationId);
@@ -1736,27 +1836,71 @@ function createCacheWarmingRecorder(conversationId, userActor, systemPrompt) {
1736
1836
  } catch (error) {
1737
1837
  logWarn("cache_warming.tool_wait.record_failed", { "exception.message": error instanceof Error ? error.message : String(error) });
1738
1838
  }
1739
- if (message.stopReason === "error" || message.stopReason === "aborted" || idleEnded && message.stopReason !== "stop") return;
1839
+ if (message.stopReason === "error" || message.stopReason === "aborted") return;
1840
+ lastCall = {
1841
+ request,
1842
+ message
1843
+ };
1844
+ if (idleEnded && message.stopReason !== "stop") return;
1740
1845
  idleEnded = message.stopReason !== "stop";
1741
1846
  try {
1742
- await recordModelCall(conversationId, userActor, systemPrompt, request, message);
1847
+ await recordModelCall(conversationId, userActor, systemPrompt, request, message, message.stopReason === "stop" ? "reply" : void 0);
1743
1848
  } catch (error) {
1744
1849
  logWarn("cache_warming.model_call.record_failed", { "exception.message": error instanceof Error ? error.message : String(error) });
1745
1850
  }
1746
1851
  },
1747
1852
  toolsReturned: toolWait.toolsReturned,
1853
+ noReplyEnded: () => {
1854
+ noReplyEnded = true;
1855
+ },
1748
1856
  stop: async () => {
1749
1857
  try {
1750
1858
  await toolWait.end();
1751
1859
  } catch (error) {
1752
1860
  logWarn("cache_warming.tool_wait.record_failed", { "exception.message": error instanceof Error ? error.message : String(error) });
1753
1861
  }
1862
+ if (!noReplyEnded || !lastCall) return;
1863
+ try {
1864
+ await recordModelCall(conversationId, userActor, systemPrompt, lastCall.request, lastCall.message, "no_reply");
1865
+ } catch (error) {
1866
+ logWarn("cache_warming.model_call.record_failed", { "exception.message": error instanceof Error ? error.message : String(error) });
1867
+ }
1754
1868
  }
1755
1869
  };
1756
1870
  }
1757
1871
  /**
1758
1872
  * Run one scheduled cache warming message. A message for an idle period that
1759
- * already ended does nothing.
1873
+ * already ended does nothing and makes no span.
1874
+ *
1875
+ * Each warmup decision has one `cache_warming.warmup` span, with the warmup
1876
+ * call as a child `gen_ai.chat` span (`junior.cache_warmup`). A tool wait
1877
+ * warmup (`tool-wait.ts`) has the same span in the trace of its Turn.
1878
+ * `app.cache_warming.outcome`:
1879
+ * - `missed`: the warmup call did not read the cached prefix. It logs
1880
+ * `cache_warming.warmup.failed` and reports to Sentry.
1881
+ * - `failed`: the warmup call threw.
1882
+ * - `skipped`: `skip_reason` is `cache_expired`, `breaker_open`,
1883
+ * `prompt_changed` (a deploy changed the system prompt, so the idle period
1884
+ * stops), `stopped` (warming stopped or the tools returned first; no log),
1885
+ * `image_missing` (an image key of the snapshot expired, so the idle period
1886
+ * stops), or a `decideWarmup` reason.
1887
+ *
1888
+ * Idle warmups carry the sizes of the idle period's snapshot:
1889
+ * `snapshot_bytes` (compressed, without images), `snapshot_image_count`
1890
+ * (distinct images stored under hash keys), and `snapshot_image_bytes`
1891
+ * (their base64 data). A snapshot over a limit stores nothing and warns
1892
+ * `cache_warming.snapshot.skipped` with `prefix_tokens`, the same sizes, and
1893
+ * `skip_reason` `snapshot_too_large` (still over the limit without its
1894
+ * images) or `images_too_large` (its images are over their limit). Each
1895
+ * snapshot also records the unsampled distribution metrics
1896
+ * `cache_warming.snapshot.bytes` and `cache_warming.snapshot.image_bytes`,
1897
+ * with `app.cache_warming.stored` false for a snapshot over a limit.
1898
+ *
1899
+ * `work_state` and `archived` are read when the idle period starts and pick
1900
+ * its `gapSegment`. `turn_ending` is `reply` or `no_reply`: how the Turn
1901
+ * before the idle period ended. The `conversation.returned` log has the same
1902
+ * three. Decision attributes are absent when the warmup skipped before the
1903
+ * decision. Cost and usage are absent when no call completed.
1760
1904
  */
1761
1905
  async function runCacheWarmup(message) {
1762
1906
  const { conversationId } = message;
@@ -1777,6 +1921,7 @@ async function runCacheWarmup(message) {
1777
1921
  "app.cache_warming.prefix_tokens": warm.prefixTokens,
1778
1922
  "app.cache_warming.trigger": "idle",
1779
1923
  ...segmentAttributes(warm),
1924
+ ...warm.snapshot ? snapshotAttributes(warm.snapshot) : void 0,
1780
1925
  "app.cache_warming.cache_ttl_left_ms": message.cacheExpiresAtMs - Date.now()
1781
1926
  };
1782
1927
  await withSpan("cache_warming.warmup", "cache_warming.warmup", {
@@ -1830,12 +1975,15 @@ async function runCacheWarmup(message) {
1830
1975
  await skip(decision.reason);
1831
1976
  return;
1832
1977
  }
1833
- const snapshot = await state.get(snapshotKey(conversationId, generation));
1834
- if (!snapshot) {
1978
+ const context = await loadSnapshot(state, conversationId, snapshotKey(conversationId, generation));
1979
+ if (context === "stopped") {
1835
1980
  setOutcome("skipped", { "app.cache_warming.skip_reason": "stopped" });
1836
1981
  return;
1837
1982
  }
1838
- const context = JSON.parse((await zstdDecompress$1(Buffer.from(snapshot, "base64"))).toString("utf8"));
1983
+ if (context === "image_missing") {
1984
+ await skip("image_missing");
1985
+ return;
1986
+ }
1839
1987
  const startedAtMs = Date.now();
1840
1988
  const warmup = await sendWarmup(state, {
1841
1989
  conversationId,
@@ -1866,4 +2014,4 @@ async function runCacheWarmup(message) {
1866
2014
  }, startedAtMs, warm);
1867
2015
  }, attributes);
1868
2016
  }
1869
- export { findLegacyNoReplyMarker as A, readAutomationResult as C, getAssistantReplyText as D, decideReply as E, readNoReply as M, REPORT_BLOCKED_TOOL_NAME as N, sanitizeAssistantText as O, readBlockedReport as P, finishedRunReply as S, runDispatchOutcome as T, buildDeploymentSystemPrompt as _, segmentGapsKey as a, FINISH_AUTOMATION_RUN_TOOL_NAME as b, listConversationWork as c, IDLE_HORIZON_MS as d, MINUTE_MS as f, gapSegment as g, gapHistogramReport as h, createCacheWarmingRecorder as i, isLegacyNoReplyMarker as j, NO_REPLY_TOOL_NAME as k, 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, JUNIOR_PERSONALITY as v, remindMissingAutomationResult as w, automationResultSchema as x, buildTurnContextPrompt as y };
2017
+ export { readNoReply as A, replyTextSchema as C, NO_REPLY_TOOL_NAME as D, sanitizeAssistantText as E, readBlockedReport as M, findLegacyNoReplyMarker as O, remindMissingAnswer as S, getAssistantReplyText as T, buildDeploymentSystemPrompt as _, segmentGapsKey as a, REPLY_TOOL_NAME as b, listConversationWork as c, IDLE_HORIZON_MS as d, MINUTE_MS as f, gapSegment as g, gapHistogramReport as h, createCacheWarmingRecorder as i, REPORT_BLOCKED_TOOL_NAME as j, isLegacyNoReplyMarker as k, 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, JUNIOR_PERSONALITY as v, decideReply as w, readTurnAnswer as x, buildTurnContextPrompt as y };
@@ -1,15 +1,15 @@
1
- import { H as PluginCredentialFailureError, K as AuthorizationFlowDisabledError, Sn as renderTag, Xt as isTurnExecutionLimitExceededError, at as failTurnRecord, et as lostWorkerBeforeFirstSave, go as loadForkHistory, nt as saveTurnCheckpoint, ot as getTurnRecord, rt as abandonTurnRecord, s as openConversationProjection, tn as getTerminalAssistantMessages, tt as pauseLostWorkerTurn, v as hydrateConversationMessages, vn as escapeClosingTags } from "./projection-BzJQncZV.js";
2
- import { n as botConfig } from "./config-DvnTPCfp.js";
3
- import { M as SYSTEM_IDENTITY_ID, a as getConversationStore, r as getConversationEventStore, s as getSqlExecutor } from "./db-Dts2XvLu.js";
4
- import { g as juniorAgentInvocations, h as juniorAgentBindings } from "./executor-Ck73J0wP.js";
1
+ import { H as PluginCredentialFailureError, K as AuthorizationFlowDisabledError, Sn as renderTag, Xt as isTurnExecutionLimitExceededError, at as failTurnRecord, et as lostWorkerBeforeFirstSave, go as loadForkHistory, nt as saveTurnCheckpoint, ot as getTurnRecord, rt as abandonTurnRecord, s as openConversationProjection, tn as getTerminalAssistantMessages, tt as pauseLostWorkerTurn, v as hydrateConversationMessages, vn as escapeClosingTags } from "./projection-B6VS7kbo.js";
2
+ import { n as botConfig } from "./config-CCPHvTqx.js";
3
+ import { M as SYSTEM_IDENTITY_ID, a as getConversationStore, r as getConversationEventStore, s as getSqlExecutor } from "./db-C1M1y-bh.js";
4
+ import { g as juniorAgentInvocations, h as juniorAgentBindings } from "./executor-DUSEwXaO.js";
5
5
  import { h as contextProvenance, m as agentInstructionProvenance, v as sameActorIdentity } from "./media-BepyEUNm.js";
6
- import { Dt as stopChildAgentsOf, Gt as finishTurn, Mt as supersedeOpenMailboxTurns, Ot as recordSubagentEnded, Ut as AgentRunError, Wt as executeTurn, an as AgentNameInUseError, kt as recordSubagentStarted, rn as AgentMessageQueueFullError, tn as AgentInvocationLimitError } from "./agent-runner-DjMTPWEO.js";
7
- import { D as getAssistantReplyText, P as readBlockedReport } from "./warmup-h6u1e9n0.js";
8
- import { k as getTurnRequestDeadline } from "./background-compaction-queue-DUkHZjmL.js";
9
- import { $ as getUnnamedAgentConversationId, A as markAgentInvocationPaused, C as isTerminalAgentInvocation, H as agentTypeStartsWithParentHistory, J as getAgentInvocationMessageId, L as agentBindingSchema, M as markAgentInvocationSteered, N as reportReplacedAgentInvocation, O as markAgentInvocationMailboxAppended, Q as getNamedAgentConversationId, T as listOpenAgentInvocations, V as agentTypeInstructions, W as getAgentInvocationId, X as getAgentInvocationTurnId, Z as getChildAgentLockName, _ as completeAgentInvocation, at as getConversationTurnBoundaryError, f as ConversationTurnLifecycleService, g as NON_TERMINAL_AGENT_INVOCATION_STATUSES, h as ACTIVE_AGENT_INVOCATION_STATUSES, j as markAgentInvocationRunning, rt as TurnInputCommitLostError, st as isTurnInputCommitLostError, v as getActiveAgentInvocationForConversation, w as listAgentInvocationsForConversation, x as getLatestAgentInvocationForConversation, y as getAgentInvocation, z as createAgentInvocationSchema } from "./turn-failure-response-BTSo6SMJ.js";
10
- import { $ as withoutSavedSteeringMessages, B as maybePostAutomatedTurnLimitNotice, K as recordFinishedTurnForAutomatedLimit, X as buildSteeringPiMessage, Z as instructionForInputs, h as parseWebMessages, i as resumeStoppedConversationTree, p as listActiveMailboxTurns, q as resetAutomatedTurnLimit, u as getActiveConversationTurnId } from "./session-stop-DkxI5vc3.js";
11
- import { r as appendAndEnqueueInboundMessage } from "./store-DgD78_NK.js";
12
- import { ft as getPersistedSandboxState, gt as coerceThreadConversationState, ht as persistThreadStateById, pt as getPersistedThreadState } from "./task-runner-CKOj6xla.js";
6
+ import { Dt as stopChildAgentsOf, Gt as finishTurn, Mt as supersedeOpenMailboxTurns, Ot as recordSubagentEnded, Ut as AgentRunError, Wt as executeTurn, an as AgentNameInUseError, kt as recordSubagentStarted, rn as AgentMessageQueueFullError, tn as AgentInvocationLimitError } from "./agent-runner-HoQiUKLL.js";
7
+ import { M as readBlockedReport, T as getAssistantReplyText } from "./warmup-CY2ArYag.js";
8
+ import { k as getTurnRequestDeadline } from "./background-compaction-queue-Cre1wFt9.js";
9
+ import { $ as getUnnamedAgentConversationId, A as markAgentInvocationPaused, C as isTerminalAgentInvocation, H as agentTypeStartsWithParentHistory, J as getAgentInvocationMessageId, L as agentBindingSchema, M as markAgentInvocationSteered, N as reportReplacedAgentInvocation, O as markAgentInvocationMailboxAppended, Q as getNamedAgentConversationId, T as listOpenAgentInvocations, V as agentTypeInstructions, W as getAgentInvocationId, X as getAgentInvocationTurnId, Z as getChildAgentLockName, _ as completeAgentInvocation, at as getConversationTurnBoundaryError, f as ConversationTurnLifecycleService, g as NON_TERMINAL_AGENT_INVOCATION_STATUSES, h as ACTIVE_AGENT_INVOCATION_STATUSES, j as markAgentInvocationRunning, rt as TurnInputCommitLostError, st as isTurnInputCommitLostError, v as getActiveAgentInvocationForConversation, w as listAgentInvocationsForConversation, x as getLatestAgentInvocationForConversation, y as getAgentInvocation, z as createAgentInvocationSchema } from "./turn-failure-response-pXhZ2wMK.js";
10
+ import { $ as withoutSavedSteeringMessages, B as maybePostAutomatedTurnLimitNotice, K as recordFinishedTurnForAutomatedLimit, X as buildSteeringPiMessage, Z as instructionForInputs, h as parseWebMessages, i as resumeStoppedConversationTree, p as listActiveMailboxTurns, q as resetAutomatedTurnLimit, u as getActiveConversationTurnId } from "./session-stop-hYNTNpVf.js";
11
+ import { r as appendAndEnqueueInboundMessage } from "./store-CZ9vqR4P.js";
12
+ import { c as getPersistedThreadState, d as coerceThreadConversationState, s as getPersistedSandboxState, u as persistThreadStateById } from "./task-runner-CMiNGsER.js";
13
13
  import { isDeepStrictEqual } from "node:util";
14
14
  import * as z from "zod";
15
15
  import { and, eq } from "drizzle-orm";
@@ -1,10 +1,10 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { At as isInvalidConversationRecordError, Dt as hasConversationStop, St as countPendingConversationMessages, kt as isFinalAttempt } from "./projection-BzJQncZV.js";
3
- import { K as isProviderRetryError, i as getChatConfig } from "./config-DvnTPCfp.js";
4
- import { T as withLogContext, b as setSpanAttributes, h as logWarn, m as logInfo, p as logException } from "./logging-9OAq-fdg.js";
5
- import { Ht as selectAttemptMessages, Vt as isAttemptInterrupt } from "./agent-runner-DjMTPWEO.js";
6
- import { k as getTurnRequestDeadline, y as ConversationQueueMessageRejectedError } from "./background-compaction-queue-DUkHZjmL.js";
7
- import { C as startConversationWork, b as releaseConversationWork, c as clearConsumedConversationWake, d as completeConversationWork, f as deadLetterAttempt, g as getConversationWorkState, i as beginConversationResume, m as ensureConversationWake, o as checkInConversationWork, p as drainConversationMailbox, t as ackMessages, u as completeConversationStop, v as recordAttemptFailure, x as requestAnotherSlice, y as recordConversationRetry } from "./store-DgD78_NK.js";
2
+ import { At as isInvalidConversationRecordError, Dt as hasConversationStop, St as countPendingConversationMessages, kt as isFinalAttempt } from "./projection-B6VS7kbo.js";
3
+ import { K as isProviderRetryError, i as getChatConfig } from "./config-CCPHvTqx.js";
4
+ import { T as withLogContext, b as setSpanAttributes, h as logWarn, m as logInfo, p as logException } from "./logging-D0svFM8r.js";
5
+ import { Ht as selectAttemptMessages, Vt as isAttemptInterrupt } from "./agent-runner-HoQiUKLL.js";
6
+ import { k as getTurnRequestDeadline, y as ConversationQueueMessageRejectedError } from "./background-compaction-queue-Cre1wFt9.js";
7
+ import { C as startConversationWork, b as releaseConversationWork, c as clearConsumedConversationWake, d as completeConversationWork, f as deadLetterAttempt, g as getConversationWorkState, i as beginConversationResume, m as ensureConversationWake, o as checkInConversationWork, p as drainConversationMailbox, t as ackMessages, u as completeConversationStop, v as recordAttemptFailure, x as requestAnotherSlice, y as recordConversationRetry } from "./store-CZ9vqR4P.js";
8
8
  // src/chat/task-execution/worker.ts
9
9
  var worker_exports = /* @__PURE__ */ __exportAll({
10
10
  CONVERSATION_WORK_DEFER_DELAY_MS: () => CONVERSATION_WORK_DEFER_DELAY_MS,
@@ -0,0 +1,12 @@
1
+ -- Repeat the awaiting_resume rename of 0089_conversation_paused_status.
2
+ -- Workers before 0.288.0 still wrote awaiting_resume after 0089 ran, and
3
+ -- readers no longer accept that name.
4
+ -- junior:bounded-backfill: changes only Conversations that an old worker paused and that did not resume, so few rows match.
5
+ UPDATE "junior_conversations" SET "execution_status" = 'paused' WHERE "execution_status" = 'awaiting_resume';--> statement-breakpoint
6
+ -- 0057_drop_legacy_automation_tables removed these from the snapshot and kept
7
+ -- them in the database for one release.
8
+ DROP INDEX IF EXISTS "junior_conversations_origin_idx";--> statement-breakpoint
9
+ ALTER TABLE "junior_conversations" DROP COLUMN IF EXISTS "origin_type";--> statement-breakpoint
10
+ ALTER TABLE "junior_conversations" DROP COLUMN IF EXISTS "origin_id";--> statement-breakpoint
11
+ ALTER TABLE "junior_conversations" DROP COLUMN IF EXISTS "origin_run_id";--> statement-breakpoint
12
+ ALTER TABLE "junior_automation_versions" DROP COLUMN IF EXISTS "kind";