@sentry/junior 0.288.0 → 0.289.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/dist/{adapter-Cikcqdty.js → adapter-tE1wnl0T.js} +1 -1
  2. package/dist/{admin-BcSxHuTB.js → admin-BmsPbmO_.js} +2 -2
  3. package/dist/{agent-runner-9MXyWUL8.js → agent-runner-bvl8U5uH.js} +343 -103
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +6 -7
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +281 -254
  8. package/dist/{app-BUklJVBe.d.ts → app-Cu454FXq.d.ts} +2 -4
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +92 -64
  11. package/dist/assistant-reply-1N9oxyyb.js +58 -0
  12. package/dist/{automation-DDXwHQs5.js → automation-DWbjJltM.js} +1 -1
  13. package/dist/{background-compaction-queue-CjllSPir.js → background-compaction-queue-D36oCldp.js} +4 -4
  14. package/dist/{briefs-DW9iuolG.js → briefs-CV-1qkXa.js} +3 -4
  15. package/dist/{catalog-runtime-B3gfH58M.js → catalog-runtime-BNK4uJVZ.js} +1 -1
  16. package/dist/cli/chat.js +14 -14
  17. package/dist/cli/check.js +3 -3
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +4 -4
  20. package/dist/cli/snapshot-create.js +4 -4
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +3 -3
  23. package/dist/{config-CLJcyYEF.js → config-DHAy7XlP.js} +4 -41
  24. package/dist/{connections-BtdJftow.js → connections-C3VmH3cf.js} +7 -129
  25. package/dist/{conversation-DhoqHtQ7.js → conversation-CwC8K3RZ.js} +8 -8
  26. package/dist/{conversation-pending-messages-DHV0S4uF.js → conversation-pending-messages-B0cuLReP.js} +1 -1
  27. package/dist/{conversation-privacy-BPirIVlX.js → conversation-privacy-Bky_veSp.js} +1 -1
  28. package/dist/{credential-sync-Co8Q2xRW.js → credential-sync-dY9o0YSj.js} +13 -13
  29. package/dist/{db-Co7DTYYh.js → db-BS2Kql3j.js} +56 -31
  30. package/dist/{db-zIs8-Ba3.d.ts → db-BebRmhsH.d.ts} +5 -1
  31. package/dist/{executor-m0kIN71Q.js → executor-cc4nH86C.js} +35 -9
  32. package/dist/instrumentation.js +2 -2
  33. package/dist/{logging-DbD-dErY.js → logging-CtCJmt9p.js} +2 -2
  34. package/dist/{history-IjdmO_r6.js → media-BepyEUNm.js} +85 -1
  35. package/dist/{message-DKTdTYm-.js → message-C5VuRcP9.js} +9 -9
  36. package/dist/nitro.d.ts +1 -1
  37. package/dist/nitro.js +2 -2
  38. package/dist/{oauth-callback-server-CpbepSbp.js → oauth-callback-server-KRrYUZ35.js} +2 -2
  39. package/dist/{projection-BViECfYu.js → projection-BFJG58TG.js} +153 -119
  40. package/dist/{prompt-KT6MaDHN.js → prompt-D15oftoL.js} +183 -3
  41. package/dist/{registry-D-Acyjhh.js → registry-C_JrgqUz.js} +1 -1
  42. package/dist/{resolve-gkT2R66z.js → resolve-Cn_7JfP-.js} +3 -3
  43. package/dist/{result-DHmCFEt8.js → result-CIbQFLp6.js} +16 -10
  44. package/dist/{runner-DBKjGjH-.js → runner-BwmaMJVO.js} +8 -8
  45. package/dist/{sandbox-egress-signals-9n8hqx29.js → sandbox-egress-signals-BOQ8gn7i.js} +1 -1
  46. package/dist/{schema-DxicIQbc.js → schema-Bptz19Ja.js} +14 -9
  47. package/dist/{schema-B_6aOcx5.d.ts → schema-DQaFSkZZ.d.ts} +13 -5
  48. package/dist/{service-account-CDlC9ssy.js → service-account-AGw_pANb.js} +3 -3
  49. package/dist/{service-account-Bi0HsY6w.js → service-account-CLZfF8O1.js} +3 -3
  50. package/dist/{session-stop-BWOsuo8p.js → session-stop-CbzKf7UI.js} +41 -30
  51. package/dist/{skills-DO5K68Rq.js → skills-CcAJBquq.js} +2 -2
  52. package/dist/{spawn-BBqZDcPa.js → spawn-BvAk2vTI.js} +5 -5
  53. package/dist/{stop-WC97cmHz.js → stop-BQU4u7la.js} +123 -213
  54. package/dist/{store-ByR1Lr7e.js → store-DE7NJOvQ.js} +3 -3
  55. package/dist/{task-runner-B-Ewf8TX.js → task-runner-Q_7duP_T.js} +13 -17
  56. package/dist/{turn-failure-response-CpdPoZSl.js → turn-failure-response-aWZLfUM8.js} +8 -8
  57. package/dist/{validation-B4sbIoES.js → validation-BOoPeIJR.js} +1 -1
  58. package/dist/{version-D6lpuAgL.js → version-Db0MFy61.js} +1 -1
  59. package/dist/version.js +1 -1
  60. package/dist/{viewer-CeP27tC3.js → viewer-FFEFu9In.js} +4 -4
  61. package/dist/{warmup-P_GJCL1c.js → warmup-DDzrA9Gv.js} +260 -60
  62. package/dist/{work-DI7x1Slm.js → work-BBJK458E.js} +14 -14
  63. package/dist/{worker-CYPTOT4j.js → worker-2iU5RFyq.js} +6 -30
  64. package/migrations/0091_conversation_participant_unsubscribed_index.sql +20 -0
  65. package/migrations/0092_turn_metric_actor.sql +12 -0
  66. package/migrations/0093_participant_root_actor_backfill.sql +18 -0
  67. package/migrations/0094_conversation_delivery_paused_at.sql +1 -0
  68. package/migrations/meta/0091_snapshot.json +4410 -0
  69. package/migrations/meta/0092_snapshot.json +4446 -0
  70. package/migrations/meta/0093_snapshot.json +4446 -0
  71. package/migrations/meta/0094_snapshot.json +4452 -0
  72. package/migrations/meta/_journal.json +28 -0
  73. package/package.json +5 -5
  74. package/dist/assistant-reply-mj47jMRV.js +0 -65
  75. package/dist/core-model-BTt5E5b0.js +0 -182
  76. package/dist/media-BAHvgkok.js +0 -85
@@ -1,6 +1,6 @@
1
- import { Bt as requestAnotherSlice$1, Dt as getConversationWorkState$1, Et as getConversation$1, Ht as startConversationWork$1, It as recordAttemptFailure$1, Lt as recordConversationRetry$1, Mt as listActiveConversationIds$1, Nt as markConversationWorkEnqueued$1, Rt as releaseConversationWork$1, St as completeConversationWork$1, Tt as drainConversationMailbox$1, Ut as steerWebPendingMessages$1, Vt as requestConversationWork$1, Wt as stopConversationWork$1, _t as checkInConversationWork$1, bt as clearExpiredConversationLease$1, ft as ackMessages$1, gt as cancelHumanFacingPendingMessages$1, ht as beginConversationResume$1, kt as hasRunnableConversationWork, mt as appendInboundMessage, pt as appendExclusiveInboundMessage, vt as claimInboundMessage$1, wt as deadLetterAttempt$1, xt as completeConversationStop$1, yt as clearConsumedConversationWake$1, zt as releaseInboundMessage } from "./projection-BViECfYu.js";
2
- import { a as getConversationStore } from "./db-Co7DTYYh.js";
3
- import "./background-compaction-queue-CjllSPir.js";
1
+ import { Bt as requestConversationWork$1, Ct as deadLetterAttempt$1, Et as getConversationWorkState$1, Ft as recordAttemptFailure$1, Ht as steerWebPendingMessages$1, It as recordConversationRetry$1, Lt as releaseConversationWork$1, Mt as markConversationWorkEnqueued$1, Ot as hasRunnableConversationWork, Rt as releaseInboundMessage, Tt as getConversation$1, Ut as stopConversationWork$1, Vt as startConversationWork$1, _t as claimInboundMessage$1, bt as completeConversationStop$1, dt as ackMessages$1, ft as appendExclusiveInboundMessage, gt as checkInConversationWork$1, ht as cancelHumanFacingPendingMessages$1, jt as listActiveConversationIds$1, mt as beginConversationResume$1, pt as appendInboundMessage, vt as clearConsumedConversationWake$1, wt as drainConversationMailbox$1, xt as completeConversationWork$1, yt as clearExpiredConversationLease$1, zt as requestAnotherSlice$1 } from "./projection-BFJG58TG.js";
2
+ import { a as getConversationStore } from "./db-BS2Kql3j.js";
3
+ import "./background-compaction-queue-D36oCldp.js";
4
4
  // src/chat/task-execution/store.ts
5
5
  function metadataStore(options) {
6
6
  return options.conversationStore ?? getConversationStore();
@@ -1,16 +1,16 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { Bn as getPlugins, Ga as createPluginModelCostRecorder, Gi as postSlackMessage, Hi as openSlackDirectMessage, Ka as createPluginLogger, Ma as createPluginEmbedder, Na as createPluginModel, Ni as escapeSlackMrkdwnText, Oo as createPluginCache, Pi as formatSlackLink, Qr as JUNIOR_THREAD_STATE_TTL_MS, T as fallbackShortTitle, Un as coreTaskRegistrations, b as persistConversationMessages, dn as isToolResultMessage, fn as normalizeToolNameFromResult, ko as createDurableLocationConfigurationService, mn as stripRuntimeTurnContext, oi as ToolInputError, on as instructionTextForProjection, ri as getDashboardTaskLink, ro as createPluginConversationEvents, si as createPluginState, st as getTurnRecord, tn as getPiMessageRole, un as isToolResultError, v as hydrateConversationMessages } from "./projection-BViECfYu.js";
3
- import { n as botConfig } from "./config-CLJcyYEF.js";
4
- import { E as withSpan, J as toOptionalString, K as isRecord$1, _ as runBestEffort, h as logWarn, q as toOptionalNumber } from "./logging-DbD-dErY.js";
2
+ import { Fa as createPluginEmbedder, Gi as openSlackDirectMessage, Hn as coreTaskRegistrations, Ia as createPluginModel, Ii as escapeSlackMrkdwnText, Ja as createPluginModelCostRecorder, Ji as postSlackMessage, Li as formatSlackLink, Mo as createDurableLocationConfigurationService, Ya as createPluginLogger, an as instructionTextForProjection, b as persistConversationMessages, dn as normalizeToolNameFromResult, en as getPiMessageRole, jo as createPluginCache, li as ToolInputError, ln as isToolResultError, oi as getDashboardTaskLink, oo as createPluginConversationEvents, ot as getTurnRecord, pn as stripRuntimeTurnContext, ti as JUNIOR_THREAD_STATE_TTL_MS, ui as createPluginState, un as isToolResultMessage, v as hydrateConversationMessages, w as fallbackShortTitle, zn as getPlugins } from "./projection-BFJG58TG.js";
3
+ import { n as botConfig } from "./config-DHAy7XlP.js";
4
+ import { E as withSpan, G as isRecord$1, K as toOptionalNumber, _ as runBestEffort, h as logWarn, q as toOptionalString } from "./logging-CtCJmt9p.js";
5
5
  import { h as parseSlackMessageTs } from "./actor-6jsm_v96.js";
6
- import { G as agentTurnTotalTokens, W as agentTurnCostUsd, a as getConversationStore, o as getDb } from "./db-Co7DTYYh.js";
7
- import { A as juniorConversations, d as juniorAutomationVersions, f as juniorAutomations, u as juniorAutomationRuns } from "./executor-m0kIN71Q.js";
8
- import { m as sameActorIdentity } from "./history-IjdmO_r6.js";
9
- import { h as credentialSubjectSchema } from "./registry-D-Acyjhh.js";
10
- import { i as readActorIdentity } from "./viewer-CeP27tC3.js";
11
- import { r as getStateAdapter } from "./adapter-Cikcqdty.js";
12
- import { c as pluginTaskParamsSchema, d as sendVercelPluginTask, s as pluginTaskId } from "./background-compaction-queue-CjllSPir.js";
13
- import { O as eventAutomationSchema, S as automationVersionSchema, j as scheduledAutomationSchema } from "./automation-DDXwHQs5.js";
6
+ import { H as agentTurnTotalTokens, V as agentTurnCostUsd, a as getConversationStore, o as getDb } from "./db-BS2Kql3j.js";
7
+ import { A as juniorConversations, d as juniorAutomationVersions, f as juniorAutomations, u as juniorAutomationRuns } from "./executor-cc4nH86C.js";
8
+ import { v as sameActorIdentity } from "./media-BepyEUNm.js";
9
+ import { h as credentialSubjectSchema } from "./registry-C_JrgqUz.js";
10
+ import { i as readActorIdentity } from "./viewer-FFEFu9In.js";
11
+ import { r as getStateAdapter } from "./adapter-tE1wnl0T.js";
12
+ import { c as pluginTaskParamsSchema, d as sendVercelPluginTask, s as pluginTaskId } from "./background-compaction-queue-D36oCldp.js";
13
+ import { O as eventAutomationSchema, S as automationVersionSchema, j as scheduledAutomationSchema } from "./automation-DWbjJltM.js";
14
14
  import { createHash } from "node:crypto";
15
15
  import * as z from "zod";
16
16
  import { and, asc, count, desc, eq, gte, inArray, isNotNull, isNull, lte, max, ne, or, sql } from "drizzle-orm";
@@ -349,7 +349,7 @@ function slackSourceForDestination(args) {
349
349
  * Reads parent Conversations when this Conversation has no Destination.
350
350
  */
351
351
  async function resolveConversationRouting(args) {
352
- const conversationStore = args.conversationStore ?? (await import("./db-Co7DTYYh.js").then((n) => n.n)).getConversationStore();
352
+ const conversationStore = args.conversationStore ?? (await import("./db-BS2Kql3j.js").then((n) => n.n)).getConversationStore();
353
353
  const chain = await loadConversationChain(args.conversationId, conversationStore);
354
354
  let destination;
355
355
  let source;
@@ -466,10 +466,6 @@ function conversationRangeColumns() {
466
466
  lastSeenAt: sql`MAX(${juniorConversations.lastActivityAt})`.mapWith(juniorConversations.lastActivityAt)
467
467
  };
468
468
  }
469
- /** Count distinct UTC activity dates without loading conversation timestamps into the app. */
470
- function conversationActiveDaysColumn() {
471
- return sql`COUNT(DISTINCT (${juniorConversations.lastActivityAt} AT TIME ZONE 'UTC')::date)::integer`;
472
- }
473
469
  // src/chat/automations/execution-stats.ts
474
470
  const AUTOMATION_EXECUTION_STATUSES = [
475
471
  "blocked",
@@ -2077,4 +2073,4 @@ async function processPluginTask(message, options = {}) {
2077
2073
  "app.plugin.task": message.name
2078
2074
  });
2079
2075
  }
2080
- export { readAutomationExecutionByConversationId as $, withScheduledAutomationLock as A, registeredEventTriggerProblems as At, setEventAutomationStatus as B, deleteScheduledAutomation as C, describeRegisteredEventTrigger as Ct, saveScheduledAutomation as D, eventWatchUnavailable as Dt, readScheduledAutomation as E, eventNamespaceSchema as Et, findMatchingEventAutomations as F, listAutomationVersions as G, eventAutomationRunLimitReason as H, getEventAutomation as I, AutomationConflictError as J, readAutomationVersion as K, listDeletedEventAutomationsCreatedBy as L, collectEventAutomationMatchKeys as M, registeredResourceTypeSchema as Mt, createEventAutomation as N, requireEventIdentifier as Nt, saveScheduledAutomationInLock as O, hasEventCatalogEntries as Ot, deleteEventAutomation as P, requireValidEventTrigger as Pt, existingConversationId as Q, parseEventAutomationRow as R, createScheduledAutomation as S, automationEventCatalog as St, parseScheduledAutomationRow as T, eventGuidance as Tt, automationDefinition as U, admitEventAutomationRun as V, automationVersionOf as W, requireAutomationRevision as X, automationRevision as Y, emptyAutomationRunWindows as Z, markDispatchBlocked as _, getPersistedThreadState as _t, claimDispatchMailboxAppend as a, readAutomationExecutions as at, markDispatchRunning as b, coerceThreadConversationState as bt, getDispatchConversationId as c, recordAutomationExecution as ct, getDispatchRecord as d, conversationRangeColumns as dt, readAutomationExecutionDays as et, getDispatchTurnId as f, conversationUsageCostExpr as ft, markDispatchAwaitingResume as g, getPersistedSandboxState as gt, listPendingDispatchMailboxAppends as h, getLocationConfigurationService as ht, buildDispatchId as i, readAutomationExecutionSummaries as it, blockEventAutomation as j, registeredEventTypeSchema as jt, scheduledRunId as k, registeredEventMatchSchema as kt, getDispatchIdForConversation as l, conversationActiveDaysColumn as lt, isTerminalDispatchStatus as m, resolveTurnSessionRouting as mt, scheduleSessionCompletedPluginTasks as n, readAutomationExecutionStatusDays as nt, confirmDispatchMailboxAppend as o, readAutomationRuns as ot, getPluginDispatchProjection as p, resolveConversationRouting as pt, sameDefinitionValue as q, task_runner_exports as r, readAutomationExecutionStatusHours as rt, createOrGetDispatch as s, readAutomationTitlesByConversationId as st, processPluginTask as t, readAutomationExecutionHours as tt, getDispatchInputMessageId as u, conversationAggregateColumns as ut, markDispatchCompleted as v, persistThreadRuntimeState as vt, listScheduledAutomationsForTeam as w, eventCatalogEntry as wt, notifyAutomationBlocked as x, CORE_EVENT_NAMESPACE as xt, markDispatchFailed as y, persistThreadStateById as yt, saveEventAutomation as z };
2076
+ export { readAutomationExecutionByConversationId as $, withScheduledAutomationLock as A, registeredResourceTypeSchema as At, setEventAutomationStatus as B, deleteScheduledAutomation as C, eventGuidance as Ct, saveScheduledAutomation as D, registeredEventMatchSchema as Dt, readScheduledAutomation as E, hasEventCatalogEntries as Et, findMatchingEventAutomations as F, listAutomationVersions as G, eventAutomationRunLimitReason as H, getEventAutomation as I, AutomationConflictError as J, readAutomationVersion as K, listDeletedEventAutomationsCreatedBy as L, collectEventAutomationMatchKeys as M, requireValidEventTrigger as Mt, createEventAutomation as N, saveScheduledAutomationInLock as O, registeredEventTriggerProblems as Ot, deleteEventAutomation as P, existingConversationId as Q, parseEventAutomationRow as R, createScheduledAutomation as S, eventCatalogEntry as St, parseScheduledAutomationRow as T, eventWatchUnavailable as Tt, automationDefinition as U, admitEventAutomationRun as V, automationVersionOf as W, requireAutomationRevision as X, automationRevision as Y, emptyAutomationRunWindows as Z, markDispatchBlocked as _, persistThreadStateById as _t, claimDispatchMailboxAppend as a, readAutomationExecutions as at, markDispatchRunning as b, automationEventCatalog as bt, getDispatchConversationId as c, recordAutomationExecution as ct, getDispatchRecord as d, resolveConversationRouting as dt, readAutomationExecutionDays as et, getDispatchTurnId as f, resolveTurnSessionRouting as ft, markDispatchAwaitingResume as g, persistThreadRuntimeState as gt, listPendingDispatchMailboxAppends as h, getPersistedThreadState as ht, buildDispatchId as i, readAutomationExecutionSummaries as it, blockEventAutomation as j, requireEventIdentifier as jt, scheduledRunId as k, registeredEventTypeSchema as kt, getDispatchIdForConversation as l, conversationAggregateColumns as lt, isTerminalDispatchStatus as m, getPersistedSandboxState as mt, scheduleSessionCompletedPluginTasks as n, readAutomationExecutionStatusDays as nt, confirmDispatchMailboxAppend as o, readAutomationRuns as ot, getPluginDispatchProjection as p, getLocationConfigurationService as pt, sameDefinitionValue as q, task_runner_exports as r, readAutomationExecutionStatusHours as rt, createOrGetDispatch as s, readAutomationTitlesByConversationId as st, processPluginTask as t, readAutomationExecutionHours as tt, getDispatchInputMessageId as u, conversationRangeColumns as ut, markDispatchCompleted as v, coerceThreadConversationState as vt, listScheduledAutomationsForTeam as w, eventNamespaceSchema as wt, notifyAutomationBlocked as x, describeRegisteredEventTrigger as xt, markDispatchFailed as y, CORE_EVENT_NAMESPACE as yt, saveEventAutomation as z };
@@ -1,13 +1,13 @@
1
- import { D as buildConversationContext, M as markConversationMessage, So as listConversationAnnotations, Z as clearPendingAuth, v as hydrateConversationMessages } from "./projection-BViECfYu.js";
2
- import { B as ProviderError, H as findProviderError, U as getProviderErrorAttributes, W as getProviderErrorUserMessage, g as TURN_REASONING_LEVELS } from "./config-CLJcyYEF.js";
3
- import { K as isRecord, b as setSpanAttributes, t as buildTurnFailureResponse } from "./logging-DbD-dErY.js";
1
+ import { E as buildConversationContext, To as listConversationAnnotations, X as clearPendingAuth, j as markConversationMessage, v as hydrateConversationMessages } from "./projection-BFJG58TG.js";
2
+ import { H as getProviderErrorAttributes, U as getProviderErrorUserMessage, V as findProviderError, g as TURN_REASONING_LEVELS, z as ProviderError } from "./config-DHAy7XlP.js";
3
+ import { G as isRecord, b as setSpanAttributes, t as buildTurnFailureResponse } from "./logging-CtCJmt9p.js";
4
4
  import { h as parseSlackMessageTs } from "./actor-6jsm_v96.js";
5
- import { o as getDb, r as getConversationEventStore, s as getSqlExecutor } from "./db-Co7DTYYh.js";
6
- import { g as juniorAgentInvocations } from "./executor-m0kIN71Q.js";
7
- import { p as credentialContextSchema } from "./registry-D-Acyjhh.js";
8
- import { B as resolveMessageCards, R as readMessageCardRefs, z as removedCardSchema } from "./conversation-DhoqHtQ7.js";
5
+ import { o as getDb, r as getConversationEventStore, s as getSqlExecutor } from "./db-BS2Kql3j.js";
6
+ import { g as juniorAgentInvocations } from "./executor-cc4nH86C.js";
7
+ import { p as credentialContextSchema } from "./registry-C_JrgqUz.js";
8
+ import { B as resolveMessageCards, R as readMessageCardRefs, z as removedCardSchema } from "./conversation-CwC8K3RZ.js";
9
9
  import { C as AGENT_INVOCATION_PARENT_MAILBOX_STATUSES, S as AGENT_INVOCATION_MAILBOX_STATUSES } from "./reporting-window-B3Ze-Qnt.js";
10
- import { _t as getPersistedThreadState, bt as coerceThreadConversationState, yt as persistThreadStateById } from "./task-runner-B-Ewf8TX.js";
10
+ import { _t as persistThreadStateById, ht as getPersistedThreadState, vt as coerceThreadConversationState } from "./task-runner-Q_7duP_T.js";
11
11
  import { createHash } from "node:crypto";
12
12
  import * as z from "zod";
13
13
  import { and, asc, desc, eq, inArray, or, sql } from "drizzle-orm";
@@ -1,5 +1,5 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { n as pluginCatalogRuntime } from "./catalog-runtime-B3gfH58M.js";
2
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-BNK4uJVZ.js";
3
3
  import { isDeepStrictEqual } from "node:util";
4
4
  // src/chat/plugins/validation.ts
5
5
  var validation_exports = /* @__PURE__ */ __exportAll({
@@ -1,5 +1,5 @@
1
1
  // package.json
2
- var version = "0.288.0";
2
+ var version = "0.289.0";
3
3
  // src/version.ts
4
4
  /** Installed Junior package version, or `unknown` when package metadata is unavailable. */
5
5
  const JUNIOR_VERSION = typeof version === "string" && version.trim() ? version : "unknown";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export { t as JUNIOR_VERSION } from "./version-D6lpuAgL.js";
1
+ export { t as JUNIOR_VERSION } from "./version-Db0MFy61.js";
@@ -1,8 +1,8 @@
1
- import { G as normalizeIdentityEmail, U as GOOGLE_IDENTITY_PROVIDER, h as logWarn } from "./logging-DbD-dErY.js";
2
- import { E as findActorIdentityId, o as getDb } from "./db-Co7DTYYh.js";
3
- import { M as juniorUsers, j as juniorIdentities } from "./executor-m0kIN71Q.js";
1
+ import { H as GOOGLE_IDENTITY_PROVIDER, W as normalizeIdentityEmail, h as logWarn } from "./logging-CtCJmt9p.js";
2
+ import { E as findActorIdentityId, o as getDb } from "./db-BS2Kql3j.js";
3
+ import { M as juniorUsers, j as juniorIdentities } from "./executor-cc4nH86C.js";
4
+ import { r as detectImageMediaType } from "./media-BepyEUNm.js";
4
5
  import { a as withLock } from "./locks-D-0h111u.js";
5
- import { r as detectImageMediaType } from "./media-BAHvgkok.js";
6
6
  import { createHash, randomUUID } from "node:crypto";
7
7
  import { and, asc, eq, inArray, isNotNull } from "drizzle-orm";
8
8
  import { identitySchema, userSchema } from "@sentry/junior-plugin-api";
@@ -1,12 +1,16 @@
1
1
  import { n as captureMessage, v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { E as resolveGatewayModel, G as isProviderRetryError, i as getChatConfig } from "./config-CLJcyYEF.js";
3
- import { H as runWithLogContext, h as logWarn, m as logInfo } from "./logging-DbD-dErY.js";
4
- import { r as completeText } from "./core-model-BTt5E5b0.js";
5
- import { r as getStateAdapter } from "./adapter-Cikcqdty.js";
6
- import { E as sendCacheWarmup } from "./background-compaction-queue-CjllSPir.js";
2
+ import { Ya as createPluginLogger, jo as createPluginCache, zn as getPlugins } from "./projection-BFJG58TG.js";
3
+ import { E as resolveGatewayModel, W as isProviderRetryError, i as getChatConfig } from "./config-DHAy7XlP.js";
4
+ import { E as withSpan, h as logWarn, m as logInfo, x as setSpanStatus } from "./logging-CtCJmt9p.js";
5
+ import { K as rootConversationIsArchived, a as getConversationStore, o as getDb, s as getSqlExecutor } from "./db-BS2Kql3j.js";
6
+ import { A as juniorConversations, C as isUserInstruction, j as juniorIdentities, w as juniorConversationEvents } from "./executor-cc4nH86C.js";
7
+ import { u as completeText } from "./prompt-D15oftoL.js";
8
+ import { r as getStateAdapter } from "./adapter-tE1wnl0T.js";
9
+ import { E as sendCacheWarmup } from "./background-compaction-queue-D36oCldp.js";
7
10
  import { streamSimple } from "@earendil-works/pi-ai/compat";
8
11
  import { promisify } from "node:util";
9
12
  import { randomUUID } from "node:crypto";
13
+ import { and, desc, eq, inArray, sql } from "drizzle-orm";
10
14
  import { constants, zstdCompress, zstdDecompress } from "node:zlib";
11
15
  // src/chat/cache-warming/model.ts
12
16
  /**
@@ -130,9 +134,16 @@ function warmupMarginMs(prefixTokens) {
130
134
  * Turns that no person started rarely get a quick reply. In 30 days of
131
135
  * production data, segments by these two keys saved more than one histogram.
132
136
  * Local time of day did not improve the result, so it is not a key.
137
+ *
138
+ * The work state lets the histograms learn how often anything returns after
139
+ * the work is done. An event does not restore an archived Conversation, so
140
+ * most returns to one are events, not people. Its segment has only the work
141
+ * state, which keeps the number of segments small.
133
142
  */
134
- function gapSegment(userActor, endedTurns) {
135
- return `${userActor ? "user" : "system"}:${endedTurns === 0 ? "1" : endedTurns < 3 ? "2-3" : "4+"}`;
143
+ function gapSegment(input) {
144
+ if (input.archived) return `archived:${input.workState}`;
145
+ const depth = input.endedTurns === 0 ? "1" : input.endedTurns < 3 ? "2-3" : "4+";
146
+ return `${input.userActor ? "user" : "system"}:${depth}:${input.workState}`;
136
147
  }
137
148
  /**
138
149
  * Decide whether to send the next warmup.
@@ -336,29 +347,36 @@ function createToolWaitWarmer(conversationId) {
336
347
  };
337
348
  const warm = (cache, cacheExpiresAtMs, cycle, current) => {
338
349
  const { request, prefixTokens } = cache;
339
- return runWithLogContext({
350
+ const attributes = {
351
+ "app.cache_warming.cycle": cycle,
352
+ "app.cache_warming.prefix_tokens": prefixTokens,
353
+ "app.cache_warming.trigger": "tool_wait"
354
+ };
355
+ return withSpan("cache_warming.warmup", "cache_warming.warmup", {
340
356
  conversationId,
341
357
  modelId: request.model.id
342
- }, {}, async () => {
343
- const attributes = {
344
- "app.cache_warming.cycle": cycle,
345
- "app.cache_warming.prefix_tokens": prefixTokens,
346
- "app.cache_warming.trigger": "tool_wait"
347
- };
348
- if (warmupTooLate(cacheExpiresAtMs)) {
358
+ }, async (setSpanAttributes) => {
359
+ const setOutcome = (outcome, extra = {}) => setSpanAttributes({
360
+ ...attributes,
361
+ ...extra,
362
+ "app.cache_warming.outcome": outcome
363
+ });
364
+ const skip = (reason) => {
365
+ const skipReason = { "app.cache_warming.skip_reason": reason };
349
366
  logInfo("cache_warming.warmup.skipped", {
350
367
  ...attributes,
351
- "app.cache_warming.skip_reason": "cache_expired"
368
+ ...skipReason
352
369
  });
370
+ setOutcome("skipped", skipReason);
371
+ };
372
+ if (warmupTooLate(cacheExpiresAtMs)) {
373
+ skip("cache_expired");
353
374
  return;
354
375
  }
355
376
  try {
356
377
  const state = await connectedState();
357
378
  if (await breakerOpen(state, request.model.id)) {
358
- logInfo("cache_warming.warmup.skipped", {
359
- ...attributes,
360
- "app.cache_warming.skip_reason": "breaker_open"
361
- });
379
+ skip("breaker_open");
362
380
  return;
363
381
  }
364
382
  const decision = decideWarmup({
@@ -374,12 +392,12 @@ function createToolWaitWarmer(conversationId) {
374
392
  attributes["app.cache_warming.return_probability"] = decision.returnProbability;
375
393
  attributes["app.cache_warming.returns_per_warmup"] = decision.returnsPerWarmup;
376
394
  attributes["app.cache_warming.threshold"] = decision.threshold;
377
- if (current !== generation) return;
395
+ if (current !== generation) {
396
+ setOutcome("skipped", { "app.cache_warming.skip_reason": "stopped" });
397
+ return;
398
+ }
378
399
  if (!decision.warm) {
379
- logInfo("cache_warming.warmup.skipped", {
380
- ...attributes,
381
- "app.cache_warming.skip_reason": decision.reason
382
- });
400
+ skip(decision.reason);
383
401
  return;
384
402
  }
385
403
  const startedAtMs = Date.now();
@@ -393,17 +411,21 @@ function createToolWaitWarmer(conversationId) {
393
411
  Object.assign(attributes, warmup.attributes);
394
412
  if (!warmup.refreshed) {
395
413
  logWarn("cache_warming.warmup.failed", attributes);
414
+ setOutcome("missed");
396
415
  return;
397
416
  }
398
417
  logInfo("cache_warming.warmup.completed", attributes);
418
+ setOutcome("completed");
399
419
  if (current === generation) schedule(cache, startedAtMs, cycle + 1);
400
420
  } catch (error) {
401
421
  logWarn("cache_warming.warmup.failed", {
402
422
  ...attributes,
403
423
  "exception.message": error instanceof Error ? error.message : String(error)
404
424
  });
425
+ setOutcome("failed", { "error.type": error instanceof Error ? error.name : typeof error });
426
+ setSpanStatus("error");
405
427
  }
406
- });
428
+ }, attributes);
407
429
  };
408
430
  const stop = () => {
409
431
  generation += 1;
@@ -452,6 +474,162 @@ function createToolWaitWarmer(conversationId) {
452
474
  }
453
475
  };
454
476
  }
477
+ // src/api/conversations/user-message-activity.ts
478
+ /**
479
+ * The newest event of one type in the outer Conversation that matches the
480
+ * filter. It walks the message role or user message time index from the
481
+ * newest event. The user message index has only matching entries, so that
482
+ * read stops at the first one.
483
+ */
484
+ function latestEventAt(db, type, filter) {
485
+ return db.select({ createdAt: juniorConversationEvents.createdAt }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, juniorConversations.conversationId), eq(juniorConversationEvents.type, type), filter)).orderBy(desc(juniorConversationEvents.createdAt), desc(juniorConversationEvents.seq)).limit(1).as(`latest_${type}`);
486
+ }
487
+ /** Read the latest true user message time for each selected conversation. */
488
+ async function readLastUserMessageAtByConversation(db, conversationIds) {
489
+ if (conversationIds.length === 0) return /* @__PURE__ */ new Map();
490
+ const payload = juniorConversationEvents.payload;
491
+ const instruction = latestEventAt(db, "user_message", isUserInstruction(payload));
492
+ const authorKind = sql`(${db.select({ kind: juniorIdentities.kind }).from(juniorIdentities).where(eq(juniorIdentities.id, juniorConversationEvents.actorIdentityId))})`;
493
+ const message = latestEventAt(db, "message", sql`${payload}->>'role' = 'user' and ${authorKind} = 'user'`);
494
+ const rows = await db.select({
495
+ conversationId: juniorConversations.conversationId,
496
+ instructionAt: instruction.createdAt,
497
+ messageAt: message.createdAt
498
+ }).from(juniorConversations).leftJoinLateral(instruction, sql`true`).leftJoinLateral(message, sql`true`).where(inArray(juniorConversations.conversationId, conversationIds));
499
+ const result = /* @__PURE__ */ new Map();
500
+ for (const { conversationId, instructionAt, messageAt } of rows) {
501
+ const times = [instructionAt, messageAt].flatMap((at) => at ? [at.getTime()] : []);
502
+ if (times.length > 0) result.set(conversationId, new Date(Math.max(...times)).toISOString());
503
+ }
504
+ return result;
505
+ }
506
+ // src/chat/plugins/unfinished-work.ts
507
+ /**
508
+ * Decide whether a conversation's work finished at or before the cutoff,
509
+ * with no person's message after it finished. Auto-archive passes now minus
510
+ * the grace period. A conversation without plugin-reported work has nothing
511
+ * to wait for, so it counts as done here; cache warming needs reported work
512
+ * and checks `assignedWork` itself.
513
+ */
514
+ function isConversationWorkDone(conversation, cutoffMs) {
515
+ if (conversation.unfinishedWork) return false;
516
+ if (!conversation.assignedWork) return true;
517
+ const finishedAt = Date.parse(conversation.finishedWorkAt ?? "");
518
+ if (!Number.isFinite(finishedAt) || finishedAt > cutoffMs) return false;
519
+ const lastUserMessageAt = Date.parse(conversation.lastUserMessageAt ?? "");
520
+ return !(Number.isFinite(lastUserMessageAt) && lastUserMessageAt > finishedAt);
521
+ }
522
+ /**
523
+ * Map each candidate and each child of a candidate root to the candidate it
524
+ * counts for. A child agent runs under its own conversation id, so a plugin
525
+ * links the work that the child does, such as a pull request, to the child.
526
+ */
527
+ async function readWorkOwners(conversationIds) {
528
+ const owners = new Map(conversationIds.map((id) => [id, id]));
529
+ const children = await getDb().select({
530
+ conversationId: juniorConversations.conversationId,
531
+ rootConversationId: juniorConversations.rootConversationId
532
+ }).from(juniorConversations).where(inArray(juniorConversations.rootConversationId, conversationIds));
533
+ for (const child of children) if (child.rootConversationId && !owners.has(child.conversationId)) owners.set(child.conversationId, child.rootConversationId);
534
+ return owners;
535
+ }
536
+ /**
537
+ * Return assigned and unfinished plugin work for the candidate conversations.
538
+ * Work in a child conversation counts for its root candidate. Feed Priority
539
+ * combines these signals with conversation activity on the host.
540
+ */
541
+ async function listConversationWork(conversationIds) {
542
+ if (conversationIds.length === 0) return {
543
+ assignedIds: [],
544
+ failed: false,
545
+ finishedAtById: {},
546
+ unfinishedIds: []
547
+ };
548
+ const owners = await readWorkOwners(conversationIds);
549
+ const queriedIds = [...owners.keys()];
550
+ const assigned = /* @__PURE__ */ new Set();
551
+ const finishedAtById = /* @__PURE__ */ new Map();
552
+ const unfinished = /* @__PURE__ */ new Set();
553
+ let failed = false;
554
+ for (const plugin of getPlugins()) {
555
+ const hook = plugin.hooks?.unfinishedWork;
556
+ if (!hook) continue;
557
+ try {
558
+ const result = await hook({
559
+ conversationIds: queriedIds,
560
+ db: getDb(),
561
+ log: createPluginLogger(plugin.manifest.name),
562
+ plugin: { name: plugin.manifest.name },
563
+ cache: createPluginCache(plugin.manifest.name)
564
+ });
565
+ for (const workId of result.conversationIds) {
566
+ const conversationId = owners.get(workId);
567
+ if (!conversationId) continue;
568
+ unfinished.add(conversationId);
569
+ assigned.add(conversationId);
570
+ }
571
+ for (const workId of result.assignedConversationIds ?? []) {
572
+ const conversationId = owners.get(workId);
573
+ if (conversationId) assigned.add(conversationId);
574
+ }
575
+ for (const [workId, finishedAt] of Object.entries(result.finishedWorkAtByConversationId ?? {})) {
576
+ const conversationId = owners.get(workId);
577
+ if (!conversationId) continue;
578
+ const time = Date.parse(finishedAt);
579
+ if (!Number.isFinite(time)) continue;
580
+ const current = finishedAtById.get(conversationId);
581
+ if (!current || time > Date.parse(current)) finishedAtById.set(conversationId, finishedAt);
582
+ }
583
+ } catch (error) {
584
+ failed = true;
585
+ logWarn("plugin.unfinished_work.hook.failed", {
586
+ "app.plugin.name": plugin.manifest.name,
587
+ "exception.message": error instanceof Error ? error.message : String(error)
588
+ });
589
+ }
590
+ }
591
+ return {
592
+ assignedIds: conversationIds.filter((conversationId) => assigned.has(conversationId)),
593
+ failed,
594
+ finishedAtById: Object.fromEntries(conversationIds.flatMap((conversationId) => {
595
+ const finishedAt = finishedAtById.get(conversationId);
596
+ return finishedAt ? [[conversationId, finishedAt]] : [];
597
+ })),
598
+ unfinishedIds: conversationIds.filter((conversationId) => unfinished.has(conversationId))
599
+ };
600
+ }
601
+ // src/chat/cache-warming/work-state.ts
602
+ /**
603
+ * Read the plugin work state and the archive state of a Conversation when an
604
+ * idle period starts that Junior can warm. Work of child Conversations counts
605
+ * for their root. A child counts as archived when it or its root is: a manual
606
+ * archive also archives the children, but auto-archive sets only the root.
607
+ */
608
+ async function readSegmentState(conversationId, nowMs) {
609
+ const [work, conversation, rootArchived] = await Promise.all([
610
+ listConversationWork([conversationId]),
611
+ getConversationStore().get({ conversationId }),
612
+ rootConversationIsArchived(getSqlExecutor(), conversationId)
613
+ ]);
614
+ const archived = rootArchived || conversation?.archivedAtMs !== void 0;
615
+ if (work.failed || !work.assignedIds.includes(conversationId)) return {
616
+ workState: "none",
617
+ archived
618
+ };
619
+ if (work.unfinishedIds.includes(conversationId)) return {
620
+ workState: "open",
621
+ archived
622
+ };
623
+ const lastUserMessageAt = (await readLastUserMessageAtByConversation(getDb(), [conversationId])).get(conversationId);
624
+ return {
625
+ workState: isConversationWorkDone({
626
+ assignedWork: true,
627
+ finishedWorkAt: work.finishedAtById[conversationId],
628
+ lastUserMessageAt
629
+ }, nowMs) ? "done" : "none",
630
+ archived
631
+ };
632
+ }
455
633
  // src/chat/cache-warming/warmup.ts
456
634
  /**
457
635
  * Prompt cache warming for idle Conversations.
@@ -504,6 +682,10 @@ const snapshotKey = (conversationId, generation) => `${KEY_PREFIX}:snapshot:${co
504
682
  const warmupsKey = (conversationId, generation) => `${KEY_PREFIX}:warmups:${conversationId}:${generation}`;
505
683
  /** Set by the first of the reply and the horizon to record the gap. */
506
684
  const gapClaimKey = (conversationId, generation) => `${KEY_PREFIX}:gap_claim:${conversationId}:${generation}`;
685
+ const segmentAttributes = (warm) => ({
686
+ "app.cache_warming.work_state": warm.workState,
687
+ "app.cache_warming.archived": warm.archived
688
+ });
507
689
  async function scheduleWarmup(message, requestStartedAtMs, warm) {
508
690
  const { cacheExpiresAtMs, delayMs } = warmupTiming(requestStartedAtMs, warm.prefixTokens, warm.cacheTtlMs);
509
691
  await sendCacheWarmup({
@@ -523,21 +705,20 @@ function snapshotContext(context) {
523
705
  })) } : void 0
524
706
  };
525
707
  }
526
- async function recordGap(state, conversationId, idle, gapMs) {
527
- if (!await state.setIfNotExists(gapClaimKey(conversationId, idle.generation), true, CONVERSATION_STATE_TTL_MS)) return;
528
- await state.appendToList(segmentGapsKey(idle.segment), gapMs, {
708
+ async function recordGap(state, conversationId, generation, warm, gapMs) {
709
+ if (!await state.setIfNotExists(gapClaimKey(conversationId, generation), true, CONVERSATION_STATE_TTL_MS)) return;
710
+ await state.appendToList(segmentGapsKey(warm.segment), gapMs, {
529
711
  maxLength: GLOBAL_GAPS_MAX,
530
712
  ttlMs: GLOBAL_GAPS_TTL_MS
531
713
  });
532
- await state.appendToList(conversationGapsKey(conversationId, idle.segment), gapMs, {
714
+ await state.appendToList(conversationGapsKey(conversationId, warm.segment), gapMs, {
533
715
  maxLength: CONVERSATION_GAPS_MAX,
534
716
  ttlMs: CONVERSATION_STATE_TTL_MS
535
717
  });
536
718
  }
537
- async function startIdlePeriod(state, conversationId, request, message, segment) {
719
+ async function startIdlePeriod(state, conversationId, request, message, turn) {
538
720
  const idle = {
539
721
  generation: randomUUID(),
540
- segment,
541
722
  sinceMs: request.startedAtMs
542
723
  };
543
724
  const prefixTokens = cachedPrefixTokens(message);
@@ -551,10 +732,16 @@ async function startIdlePeriod(state, conversationId, request, message, segment)
551
732
  });
552
733
  return idle;
553
734
  }
735
+ const segmentState = await readSegmentState(conversationId, Date.now());
554
736
  await state.set(snapshotKey(conversationId, idle.generation), snapshot, IDLE_HORIZON_MS);
555
737
  return {
556
738
  ...idle,
557
739
  warm: {
740
+ segment: gapSegment({
741
+ ...turn,
742
+ ...segmentState
743
+ }),
744
+ ...segmentState,
558
745
  modelId: request.model.id,
559
746
  prefixTokens,
560
747
  cacheTtlMs: ttlMs,
@@ -568,13 +755,14 @@ async function recordModelCall(conversationId, userActor, request, message) {
568
755
  const idle = previous?.idle;
569
756
  if (idle?.warm) {
570
757
  const gapMs = request.startedAtMs - idle.sinceMs;
571
- if (gapMs > 0) await recordGap(state, conversationId, idle, gapMs);
758
+ if (gapMs > 0) await recordGap(state, conversationId, idle.generation, idle.warm, gapMs);
572
759
  await state.delete(snapshotKey(conversationId, idle.generation));
573
760
  const warmups = await state.get(warmupsKey(conversationId, idle.generation)) ?? 0;
574
761
  if (warmups > 0) logInfo("cache_warming.conversation.returned", {
575
762
  "app.cache_warming.gap_ms": gapMs,
576
763
  "app.cache_warming.prefix_tokens": idle.warm.prefixTokens,
577
764
  "app.cache_warming.warmup_count": warmups,
765
+ ...segmentAttributes(idle.warm),
578
766
  "gen_ai.usage.cache_read.input_tokens": message.usage.cacheRead,
579
767
  "gen_ai.usage.cache_creation.input_tokens": message.usage.cacheWrite
580
768
  });
@@ -582,7 +770,10 @@ async function recordModelCall(conversationId, userActor, request, message) {
582
770
  const endedTurns = previous?.endedTurns ?? 0;
583
771
  const next = message.stopReason === "stop" ? {
584
772
  endedTurns: endedTurns + 1,
585
- idle: await startIdlePeriod(state, conversationId, request, message, gapSegment(userActor, endedTurns))
773
+ idle: await startIdlePeriod(state, conversationId, request, message, {
774
+ userActor,
775
+ endedTurns
776
+ })
586
777
  } : { endedTurns };
587
778
  if (!idle && !next.idle) return;
588
779
  await state.set(conversationKey(conversationId), next, CONVERSATION_STATE_TTL_MS);
@@ -682,40 +873,47 @@ async function runCacheWarmup(message) {
682
873
  const stop = () => state.delete(snapshotKey(conversationId, generation));
683
874
  if (message.kind === "horizon") {
684
875
  await stop();
685
- await recordGap(state, conversationId, idle, NO_REPLY_GAP_MS);
876
+ await recordGap(state, conversationId, generation, warm, NO_REPLY_GAP_MS);
686
877
  return;
687
878
  }
688
879
  if ((await state.get(warmupsKey(conversationId, generation)) ?? 0) !== message.cycle - 1) return;
689
- await runWithLogContext({
880
+ const attributes = {
881
+ "app.cache_warming.cycle": message.cycle,
882
+ "app.cache_warming.prefix_tokens": warm.prefixTokens,
883
+ "app.cache_warming.trigger": "idle",
884
+ ...segmentAttributes(warm),
885
+ "app.cache_warming.cache_ttl_left_ms": message.cacheExpiresAtMs - Date.now()
886
+ };
887
+ await withSpan("cache_warming.warmup", "cache_warming.warmup", {
690
888
  conversationId,
691
889
  modelId: warm.modelId
692
- }, {}, async () => {
693
- const attributes = {
694
- "app.cache_warming.cycle": message.cycle,
695
- "app.cache_warming.prefix_tokens": warm.prefixTokens,
696
- "app.cache_warming.trigger": "idle",
697
- "app.cache_warming.cache_ttl_left_ms": message.cacheExpiresAtMs - Date.now()
698
- };
699
- if (warmupTooLate(message.cacheExpiresAtMs)) {
890
+ }, async (setSpanAttributes) => {
891
+ const setOutcome = (outcome, extra = {}) => setSpanAttributes({
892
+ ...attributes,
893
+ ...extra,
894
+ "app.cache_warming.outcome": outcome
895
+ });
896
+ const skip = async (reason) => {
897
+ const skipReason = { "app.cache_warming.skip_reason": reason };
700
898
  logInfo("cache_warming.warmup.skipped", {
701
899
  ...attributes,
702
- "app.cache_warming.skip_reason": "cache_expired"
900
+ ...skipReason
703
901
  });
902
+ setOutcome("skipped", skipReason);
704
903
  await stop();
904
+ };
905
+ if (warmupTooLate(message.cacheExpiresAtMs)) {
906
+ await skip("cache_expired");
705
907
  return;
706
908
  }
707
909
  if (await breakerOpen(state, warm.modelId)) {
708
- logInfo("cache_warming.warmup.skipped", {
709
- ...attributes,
710
- "app.cache_warming.skip_reason": "breaker_open"
711
- });
712
- await stop();
910
+ await skip("breaker_open");
713
911
  return;
714
912
  }
715
913
  const model = resolveGatewayModel(warm.modelId);
716
914
  const decision = decideWarmup({
717
- conversationGapsMs: await state.getList(conversationGapsKey(conversationId, idle.segment)),
718
- globalGapsMs: await state.getList(segmentGapsKey(idle.segment)),
915
+ conversationGapsMs: await state.getList(conversationGapsKey(conversationId, warm.segment)),
916
+ globalGapsMs: await state.getList(segmentGapsKey(warm.segment)),
719
917
  idleMs: Date.now() - idle.sinceMs,
720
918
  cacheExpiryIdleMs: message.cacheExpiresAtMs - idle.sinceMs,
721
919
  cacheTtlMs: warm.cacheTtlMs,
@@ -727,15 +925,14 @@ async function runCacheWarmup(message) {
727
925
  attributes["app.cache_warming.returns_per_warmup"] = decision.returnsPerWarmup;
728
926
  attributes["app.cache_warming.threshold"] = decision.threshold;
729
927
  if (!decision.warm) {
730
- logInfo("cache_warming.warmup.skipped", {
731
- ...attributes,
732
- "app.cache_warming.skip_reason": decision.reason
733
- });
734
- await stop();
928
+ await skip(decision.reason);
735
929
  return;
736
930
  }
737
931
  const snapshot = await state.get(snapshotKey(conversationId, generation));
738
- if (!snapshot) return;
932
+ if (!snapshot) {
933
+ setOutcome("skipped", { "app.cache_warming.skip_reason": "stopped" });
934
+ return;
935
+ }
739
936
  const context = JSON.parse((await zstdDecompress$1(Buffer.from(snapshot, "base64"))).toString("utf8"));
740
937
  const startedAtMs = Date.now();
741
938
  const warmup = await sendWarmup(state, {
@@ -745,16 +942,19 @@ async function runCacheWarmup(message) {
745
942
  ...warm.reasoning ? { reasoning: warm.reasoning } : void 0,
746
943
  prefixTokens: warm.prefixTokens
747
944
  }).catch(async (error) => {
945
+ setOutcome("failed");
748
946
  await stop();
749
947
  throw error;
750
948
  });
751
949
  Object.assign(attributes, warmup.attributes);
752
950
  if (!warmup.refreshed) {
753
951
  logWarn("cache_warming.warmup.failed", attributes);
952
+ setOutcome("missed");
754
953
  await stop();
755
954
  return;
756
955
  }
757
956
  logInfo("cache_warming.warmup.completed", attributes);
957
+ setOutcome("completed");
758
958
  await state.set(warmupsKey(conversationId, generation), message.cycle, IDLE_HORIZON_MS);
759
959
  if (await state.get(snapshotKey(conversationId, generation))) await scheduleWarmup({
760
960
  kind: "warmup",
@@ -762,6 +962,6 @@ async function runCacheWarmup(message) {
762
962
  cycle: message.cycle + 1,
763
963
  generation
764
964
  }, startedAtMs, warm);
765
- });
965
+ }, attributes);
766
966
  }
767
- export { segmentGapsKey as a, MINUTE_MS as c, gapSegment as d, createCacheWarmingRecorder as i, MIN_WARMUP_PREFIX_TOKENS as l, GLOBAL_GAPS_MAX as n, warmup_exports as o, GLOBAL_GAPS_TTL_MS as r, IDLE_HORIZON_MS as s, CONVERSATION_STATE_TTL_MS as t, NO_REPLY_GAP_MS as u };
967
+ export { segmentGapsKey as a, listConversationWork as c, MINUTE_MS as d, MIN_WARMUP_PREFIX_TOKENS as f, createCacheWarmingRecorder as i, readLastUserMessageAtByConversation as l, gapSegment as m, GLOBAL_GAPS_MAX as n, warmup_exports as o, NO_REPLY_GAP_MS as p, GLOBAL_GAPS_TTL_MS as r, isConversationWorkDone as s, CONVERSATION_STATE_TTL_MS as t, IDLE_HORIZON_MS as u };