@sentry/junior 0.301.0 → 0.303.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 (101) hide show
  1. package/dist/adapter-context-BdVnSuY5.js +43 -0
  2. package/dist/{admin-CRJHvCGg.js → admin-AfeAdS3J.js} +2 -2
  3. package/dist/{agent-runner-H4YhvNBj.js → agent-runner-BP8_DLUv.js} +4688 -13870
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +7 -8
  6. package/dist/api.d.ts +13 -12
  7. package/dist/api.js +268 -118
  8. package/dist/{app-HDZglaIu.d.ts → app-Dd9v1mNx.d.ts} +15 -15
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +99 -330
  11. package/dist/{automation-Cva5ZOwW.js → automation-D9MvhOWY.js} +3 -1
  12. package/dist/{background-compaction-queue-CNrZ3QcU.js → background-compaction-queue-xaE05jxH.js} +97 -206
  13. package/dist/{briefs-x6Mzwxmg.js → briefs-D8i-dKTp.js} +4 -4
  14. package/dist/{catalog-runtime-BEY6EGRi.js → catalog-runtime-d1EM6Z0V.js} +2 -2
  15. package/dist/cli/chat.d.ts +1 -1
  16. package/dist/cli/chat.js +21 -21
  17. package/dist/cli/check.js +8 -8
  18. package/dist/cli/env.d.ts +1 -0
  19. package/dist/cli/env.js +8 -7
  20. package/dist/cli/init.js +13 -4
  21. package/dist/cli/main.js +4 -4
  22. package/dist/cli/plugins.js +6 -6
  23. package/dist/cli/snapshot-create.js +7 -5
  24. package/dist/cli/upgrade.d.ts +2 -2
  25. package/dist/cli/upgrade.js +5 -5
  26. package/dist/{config-CmjhyqgB.js → config-oGM7KA9M.js} +44 -63
  27. package/dist/{connections-CfIRm0xv.js → connections-BlikzEJv.js} +6 -6
  28. package/dist/{continue-in-slack-DPoABVkB.js → continue-in-slack-BZnYifiG.js} +5 -6
  29. package/dist/{conversation-BNXfq6Lb.js → conversation-CY1jnBiC.js} +1 -1
  30. package/dist/{conversation-feed-CfpyFMHP.js → conversation-feed-BZJRk6UV.js} +2 -1
  31. package/dist/{conversation-privacy-0CM0V2qK.js → conversation-privacy-Cx515ddM.js} +7 -7
  32. package/dist/{conversation-turn-C0sxyvS-.js → conversation-turn-DAhRdX4m.js} +20 -24
  33. package/dist/{credential-sync-tEMKZ_8M.js → credential-sync-DfhmWFeo.js} +18 -20
  34. package/dist/{db-Czra10QW.js → db-C-2tFxk3.js} +326 -17
  35. package/dist/{db-BdUHQhrC.d.ts → db-DPqcEM9_.d.ts} +25 -25
  36. package/dist/{executor-D_023K0H.js → executor-NVfS8aQ2.js} +51 -10
  37. package/dist/{history-IjdmO_r6.js → history-UZ3M2M9r.js} +13 -10
  38. package/dist/install-CHLrpRZc.js +228 -0
  39. package/dist/instrumentation.d.ts +4 -4
  40. package/dist/instrumentation.js +10 -10
  41. package/dist/{lineage-DmMIE0VL.js → lineage-HGLhd_-N.js} +2 -2
  42. package/dist/{logging-DcjLDDqi.js → logging-DiyqRLBx.js} +24 -20
  43. package/dist/{message-C0JY9RJP.js → message-CkCOcbFH.js} +9 -9
  44. package/dist/{model-input-CBp-p24N.js → model-input-DmoPPtPE.js} +5 -10
  45. package/dist/nitro.d.ts +1 -1
  46. package/dist/nitro.js +7 -6
  47. package/dist/{oauth-callback-server-BRq9QNhU.js → oauth-callback-server-CIf_6YmA.js} +5 -4
  48. package/dist/{oauth-relay-DRzq73b6.js → oauth-relay-DAmfVmJu.js} +3 -6
  49. package/dist/{package-discovery-DJhGdS4c.js → package-discovery-x4AvVhMj.js} +1 -1
  50. package/dist/{plugin-module-Cf5gVPWP.js → plugin-module-Cv2ETe8Y.js} +1 -1
  51. package/dist/{plugins-BBX07Jzt.js → plugins-Bkk0XRo2.js} +3 -3
  52. package/dist/{projection-CQNDOi82.js → projection-DBq8tsA5.js} +489 -223
  53. package/dist/{prompt-DLUB5m72.js → prompt-D2KlJopL.js} +15 -5
  54. package/dist/{queue-CZyYgPF0.d.ts → queue-CbEHUO0l.d.ts} +1 -1
  55. package/dist/queue-DFaOscp5.js +115 -0
  56. package/dist/{registry-Dj377ADs.js → registry-Bu0Z9BEO.js} +37 -37
  57. package/dist/{resolve-DJkh9Fky.js → resolve-DXuA3G0g.js} +4 -229
  58. package/dist/{result-C8iIpDl1.js → result-DpiNseDA.js} +11 -16
  59. package/dist/rolldown-runtime-BKpuH2hG.js +26 -0
  60. package/dist/{runner-DZqrOy8C.js → runner-iu1heRFv.js} +10 -10
  61. package/dist/{sandbox-egress-signals-CGwH86S9.js → sandbox-egress-signals-2HFYDcQf.js} +1 -1
  62. package/dist/{schema-CdZFn7Qd.d.ts → schema-DHMOaRzC.d.ts} +959 -41
  63. package/dist/{schema-DyHXiQKI.js → schema-DvfX3Gq_.js} +141 -40
  64. package/dist/{secrets-DebYU866.js → secrets-DHaJ5TTn.js} +4 -4
  65. package/dist/{sentry-BRTJqumy.js → sentry-CPbZjomA.js} +3 -28
  66. package/dist/{sentry-route-name-BhwWnfqj.js → sentry-route-name-C6EIzAGP.js} +1 -1
  67. package/dist/{service-account-suY004dx.js → service-account-BcT5LR7V.js} +271 -20
  68. package/dist/{service-account-D6jGR4a1.js → service-account-xYkaQTrw.js} +3 -3
  69. package/dist/{session-stop-BLmfFI3d.js → session-stop-BLLp1IP_.js} +1098 -1110
  70. package/dist/{skills-CmNG0dHb.js → skills-CNAGH4ju.js} +6 -9
  71. package/dist/{slack-conversation-unfurl-Bty-DlHe.js → slack-conversation-unfurl-DYnqe5ci.js} +10 -14
  72. package/dist/{spawn-CNjkpXpk.js → spawn-cGasWW33.js} +7 -7
  73. package/dist/{state-CEbZuZD6.js → state-CDS6h_Wv.js} +34 -5
  74. package/dist/{stop-Bjy2-K4H.js → stop-DMMA67yT.js} +896 -196
  75. package/dist/{store-DmV4CoNr.js → store-Dgs7Oe44.js} +5 -5
  76. package/dist/{task-queue-AhG1tSXR.js → task-queue-DcF0nhhz.js} +3 -3
  77. package/dist/{task-runner-BMxZI3o7.js → task-runner-BGXF7Fo7.js} +15 -20
  78. package/dist/{thread-context-CXLnbg7g.js → thread-context-BPky1KBe.js} +12 -12
  79. package/dist/{store-Epv6t4vV.js → turn-session-routing-DGvn9MSl.js} +384 -13
  80. package/dist/{turn-user-message-DsUZi9gn.js → turn-user-message-19CkuUvM.js} +3 -3
  81. package/dist/{validation-DOz8X9BU.js → validation-lu1DgjNQ.js} +2 -2
  82. package/dist/vercel.js +1 -1
  83. package/dist/{version-CGMRmMPK.js → version-Uo3c94Dx.js} +1 -1
  84. package/dist/version.js +1 -1
  85. package/dist/{viewer-H3EsMWtJ.js → viewer-BPQHMx3-.js} +3 -3
  86. package/dist/warmup-H8uLvW9e.js +13946 -0
  87. package/dist/{statuses-Hn-HsOph.js → web-message-id-lNodcCOI.js} +136 -1
  88. package/dist/{worker-ClphajjD.js → worker-B-pM_-3K.js} +9 -12
  89. package/migrations/0108_conversation_embeddings.sql +13 -0
  90. package/migrations/0109_user_preferences.sql +1 -0
  91. package/migrations/0110_code_change_repository_state_index.sql +1 -0
  92. package/migrations/meta/0108_snapshot.json +4688 -0
  93. package/migrations/meta/0109_snapshot.json +4925 -0
  94. package/migrations/meta/0110_snapshot.json +4952 -0
  95. package/migrations/meta/_journal.json +22 -1
  96. package/package.json +16 -17
  97. package/dist/adapter-CNjGEJO9.js +0 -303
  98. package/dist/reporting-window-DopzcOHh.js +0 -137
  99. package/dist/turn-session-routing-BD3-jJl7.js +0 -380
  100. package/dist/users-BxvYclQg.js +0 -424
  101. package/dist/warmup-CdU5hR49.js +0 -3715
package/dist/app.js CHANGED
@@ -1,56 +1,54 @@
1
- import { i as getActiveSpan, n as captureMessage, u as sentry_exports } from "./sentry-BRTJqumy.js";
2
- import { Bi as createPluginState, C as settleConversationTitleWork, Ci as bindSlackDirectCredentialSubject, Dr as projectConversationMessages, Ea as postSlackEphemeralMessage, Ei as verifySlackDirectCredentialSubject, Es as setConfigDefaults, Fi as getDashboardTaskLink, Fo as readConversationMessageEventSeq, Ha as clearSandboxEgressSignals, Hr as canActOnReviewItem, Ka as parseSandboxEgressCredentialToken, Ma as slackEntitySchema, Mo as readConversationEventPageAfter, Mt as hasRunnableConversationWork, Na as slackExternalRefIdSchema, Ni as getDashboardReviewItemLink, Po as readConversationLastEventSeq, Pt as isInvalidConversationRecordError, Qo as isDmChannel, Qr as reviewItemReaderForUserInConversation, Rr as searchReviewItems, Rt as pruneActiveConversation, Si as bindScheduledAutomationCredentialSubject, Ta as openSlackModal, Ti as verifyScheduledAutomationCredentialSubject, Ts as getConfigDefaults, Ua as consumeSandboxEgressAuthRequiredSignal, Wa as consumeSandboxEgressPermissionDeniedSignal, Xa as normalizeSandboxEgressTracePropagationDomains, Xo as getSlackClient, Zn as createUserTokenStore, Zr as reviewItemReaderForUser, _ as appendConversationMessages, _a as slackMention, _i as findMatchingWatches, _o as createPluginLogger, _r as setBriefsConfig, aa as isVercelSandboxEgressRequest, as as getWorkspaceTeamId, bi as takeDueTimerWatches, cs as resolveRootVisibility, ds as listConversationAnnotations, dt as CONVERSATION_WORK_STALE_ENQUEUE_MS, fr as getPlugins, ii as createCodeChangePublisher, ir as createPluginEventPublisher, jo as readConversationEventPage, jr as dismissOpenReviewItems, ki as getDashboardConversationLink, mr as validatePlugins, oa as proxyVercelSandboxEgressRequest, or as getPluginApiRoutes, os as runWithWorkspaceTeamId, pi as collectEventMatchKeys, pr as setPlugins, ro as createPluginEmbedder, sr as getPluginRoutes, ua as resolveBaseUrl, us as createPluginAnnotations, wi as verifyEventAutomationCredentialSubject, xi as bindEventAutomationCredentialSubject, xo as readConversationAccessFromSql, ys as createPluginCache, zi as setDashboardConversationLinkOptions } from "./projection-CQNDOi82.js";
3
- import { Z as getAttachmentStorage, d as restoreRuntimeConfig, f as setBotModelConfig, g as snapshotRuntimeConfig, h as setSlackReactionConfig, i as getChatConfig, m as setRuntimeLimits, n as botConfig, o as getSlackBotToken, p as setBotName, u as resetRuntimeConfig } from "./config-CmjhyqgB.js";
4
- import { A as JUNIOR_CONTEXT_COMPACTION_CALLBACK_ROUTE, E as withSpan, H as GOOGLE_IDENTITY_PROVIDER, L as JUNIOR_WORKSPACE_SNAPSHOT_JOB_CALLBACK_ROUTE, O as JUNIOR_AUTO_ARCHIVE_ROUTE, P as JUNIOR_PLUGIN_TASK_CALLBACK_ROUTE, T as withLogContext, W as normalizeIdentityEmail, b as setSpanAttributes, h as logWarn, k as JUNIOR_CACHE_WARMUP_CALLBACK_ROUTE, m as logInfo, p as logException, r as createRequestContext, w as withContext } from "./logging-DcjLDDqi.js";
5
- import { t as JUNIOR_VERSION } from "./version-CGMRmMPK.js";
6
- import { b as slackMessageTsSchema, g as slackTeamIdSchema, h as slackChannelIdSchema, n as createSlackActor, p as parseSlackUserId, s as parseActorUserId, u as parseSlackChannelId, v as parseSlackMessageTs, y as slackMessageTsFromMs } from "./actor-D2iXzvlN.js";
7
- import { D as conversationKindFromRow, N as resolveActorIdentityId, W as createCache, a as getConversationStore, f as withConversationEventLock, it as createSlackDestination, o as getDb, r as getConversationEventStore, rt as touchConversationDetail, s as getSqlExecutor, t as closeDb, x as withConversationMutationLock, z as recordGoogleSignIn } from "./db-Czra10QW.js";
8
- import { P as juniorDestinations, b as juniorConversationBriefs, f as juniorAutomations, g as juniorAgentInvocations, h as juniorAgentBindings, j as juniorConversations, l as juniorReviewItems, u as juniorAutomationRuns, w as juniorConversationEvents } from "./executor-D_023K0H.js";
9
- import { c as fenceLock, l as withLock, o as MUTATION_LOCK_TTL_MS, r as getStateAdapter, t as disconnectStateAdapter } from "./adapter-CNjGEJO9.js";
10
- import { n as pluginCatalogRuntime } from "./catalog-runtime-BEY6EGRi.js";
11
- import { $ as effectiveTaskOutcomes, A as parseSlackReviewItemClick, At as ingestEvent, Ct as markConversationRead, D as syncReviewItemSlackCards, E as readSlackReviewItemCardConversationId, G as ViewerTaskNotFoundError, M as parseSlackUserInputSubmission, Mt as missingAutomationSkillReason, N as parseSlackThreadId, R as logScheduledAutomationRunSkipped, T as createSlackReviewItemShow, Y as readViewerAutomationSummary, Z as readViewerAutomations, _t as collectAttachmentGarbage, at as appendAndEnqueueWebMessage, b as unpublishedArtifactHeaders, j as parseSlackReviewItemFormTarget, jt as findAutomationSkill, k as buildSlackReviewItemModal, kt as processWorkspaceSnapshotJob, lt as recordWebConversationActivity, n as executeAgentRun, nt as renderReviewItemMessage, ot as conversationTurnIdForMessage, pt as collectAttachmentUploadGarbage, q as readViewerAutomationExecutions, r as processBackgroundCompaction, rt as reviewItemChangeRecord, t as createAgentRunner, tt as deliverReviewItemChange, ut as webActorFromUser, v as publicArtifactHeaders, x as setConversationSubscription, xt as archiveConversation, y as readPublicArtifact, yt as requestAttachmentDeletion, z as scheduledAutomationRunAttributes } from "./agent-runner-H4YhvNBj.js";
1
+ import { $r as reviewItemReaderForUser, As as setConfigDefaults, C as settleConversationTitleWork, Ci as bindEventAutomationCredentialSubject, Co as readConversationAccessFromSql, Cs as createPluginCache, Da as openSlackModal, Di as verifyScheduledAutomationCredentialSubject, Dr as createPluginReviewItems, Ei as verifyEventAutomationCredentialSubject, Er as projectConversationMessages, Fa as slackExternalRefIdSchema, Fi as getDashboardReviewItemLink, Ga as consumeSandboxEgressAuthRequiredSignal, Hi as createPluginState, Io as readConversationLastEventSeq, Ja as parseSandboxEgressCredentialToken, Ka as consumeSandboxEgressPermissionDeniedSignal, Li as getDashboardTaskLink, Lo as readConversationMessageEventSeq, Mr as dismissOpenReviewItems, Mt as hasRunnableConversationWork, No as readConversationEventPage, Oa as postSlackEphemeralMessage, Oi as verifySlackDirectCredentialSubject, Pa as slackEntitySchema, Po as readConversationEventPageAfter, Pt as isInvalidConversationRecordError, Qa as normalizeSandboxEgressTracePropagationDomains, Qo as getSlackClient, Rt as pruneActiveConversation, Si as takeDueTimerWatches, Ti as bindSlackDirectCredentialSubject, Ur as canActOnReviewItem, Vi as setDashboardConversationLinkOptions, Wa as clearSandboxEgressSignals, Zn as createUserTokenStore, _ as appendConversationMessages, ao as createPluginEmbedder, ar as getPluginRoutes, ca as proxyVercelSandboxEgressRequest, cs as runWithWorkspaceTeamId, dt as CONVERSATION_WORK_STALE_ENQUEUE_MS, ei as reviewItemReaderForUserInConversation, es as isDmChannel, fa as resolveBaseUrl, fr as setPlugins, gr as setBriefsConfig, hi as collectEventMatchKeys, hs as listConversationAnnotations, ir as getPluginApiRoutes, ji as getDashboardConversationLink, ks as getConfigDefaults, ms as createPluginAnnotations, nr as createPluginEventPublisher, oi as createCodeChangePublisher, pr as validatePlugins, sa as isVercelSandboxEgressRequest, ss as getWorkspaceTeamId, ur as getPlugins, us as resolveRootVisibility, wi as bindScheduledAutomationCredentialSubject, ya as slackMention, yi as findMatchingWatches, yo as createPluginLogger, zr as searchReviewItems } from "./projection-DBq8tsA5.js";
2
+ import { Z as getAttachmentStorage, d as restoreRuntimeConfig, f as setBotModelConfig, g as snapshotRuntimeConfig, h as setSlackReactionConfig, i as getChatConfig, m as setRuntimeLimits, n as botConfig, o as getSlackBotToken, p as setBotName, u as resetRuntimeConfig } from "./config-oGM7KA9M.js";
3
+ import { $ as fenceLock, B as recordGoogleSignIn, G as createCache, J as getStateAdapter, K as disconnectStateAdapter, P as resolveActorIdentityId, Z as MUTATION_LOCK_TTL_MS, a as getConversationStore, et as withLock, f as withConversationEventLock, mt as createSlackDestination, o as getDb, pt as touchConversationDetail, r as getConversationEventStore, s as getSqlExecutor, t as closeDb, x as withConversationMutationLock } from "./db-C-2tFxk3.js";
4
+ import { A as JUNIOR_CONTEXT_COMPACTION_CALLBACK_ROUTE, E as withSpan, G as normalizeIdentityEmail, L as JUNIOR_WORKSPACE_SNAPSHOT_JOB_CALLBACK_ROUTE, O as JUNIOR_AUTO_ARCHIVE_ROUTE, P as JUNIOR_PLUGIN_TASK_CALLBACK_ROUTE, T as withLogContext, U as GOOGLE_IDENTITY_PROVIDER, b as setSpanAttributes, h as logWarn, k as JUNIOR_CACHE_WARMUP_CALLBACK_ROUTE, m as logInfo, p as logException, r as createRequestContext, w as withContext } from "./logging-DiyqRLBx.js";
5
+ import { D as parseSlackUserInputSubmission, E as parseSlackReviewItemFormTarget, S as findSlackThreadOwnerId, T as parseSlackReviewItemClick, _ as logScheduledAutomationRunSkipped, b as resolveSlackReviewItemCardConversationId, h as unpublishedArtifactHeaders, m as readPublicArtifact, n as executeAgentRun, p as publicArtifactHeaders, r as processBackgroundCompaction, t as createAgentRunner, v as scheduledAutomationRunAttributes, w as buildSlackReviewItemModal, x as syncReviewItemSlackCards, y as createSlackReviewItemShow } from "./agent-runner-BP8_DLUv.js";
6
+ import { $ as slackChannelMessageEvent, F as renderTaskInput, J as isExperimentalFeatureEnabled, V as renderSlackObjectCard, X as getEventCatalog, Y as setExperimentalFeatures, Z as SLACK_EVENT_NAMESPACE, b as getAuthPausedConversationTurnId, et as slackChannelMessageReplyThreadTs, q as getExperimentalFeatures, tt as slackChannelMessageRunsAutomation } from "./session-stop-BLLp1IP_.js";
7
+ import { a as getSandboxResourceConfig, s as setSandboxResourceConfig } from "./install-CHLrpRZc.js";
8
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-d1EM6Z0V.js";
9
+ import { $ as readObjectLinkTypes, A as isAllowedSignInEmail, B as runAutoArchiveSweep, C as encodeConversationCursor, Ct as getThreadStopDecision, F as actOnReviewItem, I as closeReviewItemsAnsweredByReply, J as backfillCacheWarmingGaps, K as runSavingsRefillSlice, L as readReviewItemForUser, M as resolveAllowedDomains, N as stopConversation, O as assertNoLegacyAllowedDomains, P as ReviewItemActionError, R as reviewItemChange, S as decodeConversationCursor, St as SubscribedReplyReason, T as readConversationPendingMessages, V as setConversationAutoArchive, Y as GET$4, _t as createSlackWebApiStatusSender, at as createProductionConversationWorkOptions, b as createConversationForViewer, bt as stripLeadingBotMention, ct as buildSlackInboundMessage, dt as normalizeIncomingSlackThreadId, ft as withNormalizedThreadId, gt as recordSkippedConversationMessage, ht as failStoppedDispatch, i as readConversationFeed, it as publicAddressLookup, j as readEnvList, k as isAllowedDomain, l as readConversationDetail, lt as clearSlackPendingReactions, mt as enqueueAgentDispatch, n as steerConversationPendingMessagesForViewer, ot as createProductionSlackWebhookServices, rt as isPublicAddress, s as pinConversation, st as getProductionSlackAdapter, t as stopConversationTurnForViewer, ut as slackInboundMessageId, v as readConversationRecordFromSql, vt as bindMessageAuthorIdentityId, w as cancelConversationPendingMessagesForViewer, xt as parseContent, y as appendConversationMessageForViewer, yt as startProcessingReaction, z as archiveViewerDoneConversations } from "./stop-DMMA67yT.js";
10
+ import { n as validatePluginRegistrations, t as validatePluginEgressCredentialHooks } from "./validation-lu1DgjNQ.js";
11
+ import { a as pluginRuntimeRegistrationsFromPluginSet, n as pluginCatalogConfigFromEnv, r as pluginCatalogConfigFromPluginSet, t as defineJuniorPlugins } from "./plugins-Bkk0XRo2.js";
12
+ import { Cr as joinPublicChannel, Di as missingAutomationSkillReason, E as processWorkspaceSnapshotJob, Ei as findAutomationSkill, Jn as setConversationSubscription, L as lookupSlackUserProfile, Mt as collectAttachmentGarbage, Oi as effectiveTaskOutcomes, Ot as collectAttachmentUploadGarbage, Pt as requestAttachmentDeletion, Qt as listPendingAgentInvocationResults, Sn as recordSubagentEnded, Tt as webActorFromUser, Zt as listPendingAgentInvocationMailboxAppends, _t as renderReviewItemMessage, bt as appendAndEnqueueWebMessage, dt as markConversationRead, fi as ViewerTaskNotFoundError, gi as readViewerAutomationSummary, gt as deliverReviewItemChange, hn as enqueueAgentInvocation, k as ingestEvent, lt as archiveConversation, mi as readViewerAutomationExecutions, ur as parseSlackThreadId, vi as readViewerAutomations, vt as reviewItemChangeRecord, wt as recordWebConversationActivity, xt as conversationTurnIdForMessage } from "./warmup-H8uLvW9e.js";
13
+ import { H as automationTaskSchema, N as scheduledRunSchema, U as automationTaskText, l as automationListQuerySchema, s as automationExecutionStatusSchema } from "./automation-D9MvhOWY.js";
14
+ import { E as notifyAutomationBlocked, G as readScheduledAutomation, I as recordAutomationExecution, J as scheduledRunId, O as existingConversationId, U as listScheduledAutomationsForTeam, X as blockEventAutomation, Y as withScheduledAutomationLock, Z as collectEventAutomationMatchKeys, b as listPendingDispatchMailboxAppends, bt as eventGuidance, c as coerceThreadConversationState, d as confirmDispatchMailboxAppend, et as findMatchingEventAutomations, f as createOrGetDispatch, g as getDispatchRecord, l as buildDispatchId, lt as automationVersionOf, ot as admitEventAutomationRun, p as getDispatchConversationId, q as saveScheduledAutomationInLock, st as eventAutomationRunLimitReason, v as getPluginDispatchProjection, w as markDispatchFailed, y as isTerminalDispatchStatus } from "./turn-session-routing-DGvn9MSl.js";
15
+ import { F as juniorDestinations, M as juniorConversations, T as juniorConversationEvents, f as juniorAutomations, g as juniorAgentInvocations, h as juniorAgentBindings, l as juniorReviewItems, u as juniorAutomationRuns, x as juniorConversationBriefs } from "./executor-NVfS8aQ2.js";
16
+ import { i as getActiveSpan, n as captureMessage, u as sentry_exports } from "./sentry-CPbZjomA.js";
17
+ import { a as queueCallback, c as verifyConversationQueueMessage, f as getQueueProvider, g as isConversationQueueMessageRejectedError, h as conversationQueueMessageSchema, i as verifyBackgroundCompactionMessage, o as getVercelConversationWorkQueue, r as vercelBackgroundCompactionQueue, s as resolveConversationWorkQueueTopic, t as BACKGROUND_COMPACTION_QUEUE_TOPIC } from "./background-compaction-queue-xaE05jxH.js";
18
+ import { _ as getConversationWorkState, g as getConversation, h as ensureConversationWake, l as clearExpiredConversationLease, r as appendAndEnqueueInboundMessage, y as listActiveConversationIds } from "./store-Dgs7Oe44.js";
12
19
  import { a as getNextRunAtMs } from "./schedule-cP0AACm1.js";
13
- import { i as readActorIdentity, l as resolveViewerUser, p as parseAvatarUrl } from "./viewer-H3EsMWtJ.js";
14
- import { P as conversationTitleSchema, et as conversationBriefSchema, m as conversationFeedQuerySchema, x as conversationSurfaceSchema, y as conversationReportStatusSchema, z as annotationCard } from "./conversation-BNXfq6Lb.js";
20
+ import { i as enqueueAgentInvocationResult, r as createEndStoppedChildWork } from "./result-DpiNseDA.js";
21
+ import { n as readSchedulerSecret, r as readSignInSecret } from "./secrets-DHaJ5TTn.js";
22
+ import { a as GET$5, i as publishAppHomeView, r as GET$6, t as receiveLocalOAuthCredential } from "./credential-sync-DfhmWFeo.js";
23
+ import { t as nameRequestRoute } from "./sentry-route-name-C6EIzAGP.js";
15
24
  import { t as SANDBOX_EGRESS_PROXY_PATH } from "./proxy-path-BHYoKZdq.js";
16
- import { n as readSchedulerSecret, r as readSignInSecret } from "./secrets-DebYU866.js";
17
- import { C as getAuthPausedConversationTurnId, H as slackChannelMessageReplyThreadTs, R as getEventCatalog, U as slackChannelMessageRunsAutomation, V as slackChannelMessageEvent, Y as renderTaskInput, b as isExperimentalFeatureEnabled, tt as renderSlackObjectCard, x as setExperimentalFeatures, y as getExperimentalFeatures, z as SLACK_EVENT_NAMESPACE } from "./session-stop-BLmfFI3d.js";
18
- import { C as listPendingAgentInvocationMailboxAppends, H as enqueueAgentInvocation, It as gapSegment, Mt as MINUTE_MS, Nt as MIN_WARMUP_PREFIX_TOKENS, Pt as NO_REPLY_GAP_MS, X as recordSubagentEnded, a as segmentGapsKey, n as GLOBAL_GAPS_MAX, r as GLOBAL_GAPS_TTL_MS, t as CONVERSATION_STATE_TTL_MS, w as listPendingAgentInvocationResults } from "./warmup-CdU5hR49.js";
19
- import { E as getQueueProvider, _ as cacheWarmupQueueConsumer, a as WORKSPACE_SNAPSHOT_JOB_QUEUE_TOPIC, c as verifyWorkspaceSnapshotJobMessage, d as verifyConversationQueueMessage, i as verifyBackgroundCompactionMessage, l as getVercelConversationWorkQueue, m as isConversationQueueMessageRejectedError, p as conversationQueueMessageSchema, r as vercelBackgroundCompactionQueue, t as BACKGROUND_COMPACTION_QUEUE_TOPIC, u as resolveConversationWorkQueueTopic, v as createVercelCacheWarmupCallback, w as queueCallback, y as registerVercelCacheWarmupDevConsumer } from "./background-compaction-queue-CNrZ3QcU.js";
20
- import { _ as getConversationWorkState, g as getConversation, h as ensureConversationWake, l as clearExpiredConversationLease, r as appendAndEnqueueInboundMessage, y as listActiveConversationIds } from "./store-DmV4CoNr.js";
21
- import { c as coerceThreadConversationState, p as eventGuidance } from "./turn-session-routing-BD3-jJl7.js";
22
- import { o as buttonUserInputField } from "./statuses-Hn-HsOph.js";
23
- import { c as setSandboxResourceConfig, o as getSandboxResourceConfig } from "./resolve-DJkh9Fky.js";
24
- import { H as automationTaskSchema, N as scheduledRunSchema, U as automationTaskText, l as automationListQuerySchema, s as automationExecutionStatusSchema } from "./automation-Cva5ZOwW.js";
25
- import { $ as eventAutomationRunLimitReason, B as scheduledRunId, F as listScheduledAutomationsForTeam, H as blockEventAutomation, K as findMatchingEventAutomations, L as readScheduledAutomation, O as recordAutomationExecution, Q as admitEventAutomationRun, U as collectEventAutomationMatchKeys, V as withScheduledAutomationLock, a as getDispatchConversationId, b as existingConversationId, c as getDispatchRecord, d as isTerminalDispatchStatus, f as listPendingDispatchMailboxAppends, g as markDispatchFailed, i as createOrGetDispatch, r as confirmDispatchMailboxAppend, t as buildDispatchId, tt as automationVersionOf, u as getPluginDispatchProjection, v as notifyAutomationBlocked, z as saveScheduledAutomationInLock } from "./store-Epv6t4vV.js";
26
- import { a as runWithSlackInstallation, o as verifySlackSignature, p as joinPublicChannel, r as lookupSlackUserProfile } from "./users-BxvYclQg.js";
27
- import { A as resolveAllowedDomains, B as runAutoArchiveSweep, C as readConversationPendingMessages, D as isAllowedDomain, E as assertNoLegacyAllowedDomains, F as readReviewItemForUser, I as reviewItemChange, K as readObjectLinkTypes, M as ReviewItemActionError, N as actOnReviewItem, O as isAllowedSignInEmail, P as closeReviewItemsAnsweredByReply, R as archiveViewerDoneConversations, S as cancelConversationPendingMessagesForViewer, U as GET$4, V as setConversationAutoArchive, X as isPublicAddress, Z as publicAddressLookup, _ as appendConversationMessageForViewer, _t as SubscribedReplyReason, a as pinConversation, at as slackInboundMessageId, b as decodeConversationCursor, dt as recordSkippedConversationMessage, et as createProductionConversationWorkOptions, ft as createSlackWebApiStatusSender, g as readConversationRecordFromSql, gt as parseContent, ht as stripLeadingBotMention, i as readConversationFeed, it as clearSlackPendingReactions, j as stopConversation, k as readEnvList, lt as enqueueAgentDispatch, mt as startProcessingReaction, n as steerConversationPendingMessagesForViewer, nt as getProductionSlackAdapter, ot as normalizeIncomingSlackThreadId, pt as bindMessageAuthorIdentityId, rt as buildSlackInboundMessage, s as readConversationDetail, st as withNormalizedThreadId, t as stopConversationTurnForViewer, tt as createProductionSlackWebhookServices, ut as failStoppedDispatch, v as createConversationForViewer, vt as getThreadStopDecision, x as encodeConversationCursor } from "./stop-Bjy2-K4H.js";
28
- import { s as conversationPendingMessageDeliverySchema } from "./conversation-feed-CfpyFMHP.js";
29
- import { a as resumeConversationDelivery } from "./conversation-turn-C0sxyvS-.js";
30
- import { i as enqueueAgentInvocationResult, r as createEndStoppedChildWork } from "./result-C8iIpDl1.js";
31
- import { t as bindMessageAgent } from "./message-C0JY9RJP.js";
32
- import { t as bindSpawnAgent } from "./spawn-CNjkpXpk.js";
33
- import { a as pluginTaskQueueConsumer, n as createVercelPluginTaskCallback, o as registerVercelPluginTaskDevConsumer } from "./task-queue-AhG1tSXR.js";
34
- import { t as processPluginTask } from "./task-runner-BMxZI3o7.js";
35
- import { n as validatePluginRegistrations, t as validatePluginEgressCredentialHooks } from "./validation-DOz8X9BU.js";
36
- import { a as pluginRuntimeRegistrationsFromPluginSet, n as pluginCatalogConfigFromEnv, r as pluginCatalogConfigFromPluginSet, t as defineJuniorPlugins } from "./plugins-BBX07Jzt.js";
37
- import { o as unlinkProvider } from "./connections-CfIRm0xv.js";
38
- import { a as GET$5, i as publishAppHomeView, r as GET$6, t as receiveLocalOAuthCredential } from "./credential-sync-tEMKZ_8M.js";
39
- import { t as nameRequestRoute } from "./sentry-route-name-BhwWnfqj.js";
40
- import { a as resolveSlackActingUser, i as unfurlDashboardConversationLinks, n as handleSlackContinueHereClick, o as isSlackWorkspaceMember, s as slackWorkspaceBotId, t as SLACK_CONTINUE_HERE_ACTION_ID } from "./slack-conversation-unfurl-Bty-DlHe.js";
41
- import { t as processConversationWork } from "./worker-ClphajjD.js";
25
+ import { P as conversationTitleSchema, et as conversationBriefSchema, m as conversationFeedQuerySchema, x as conversationSurfaceSchema, y as conversationReportStatusSchema, z as annotationCard } from "./conversation-CY1jnBiC.js";
26
+ import { i as readActorIdentity, l as resolveViewerUser, p as parseAvatarUrl } from "./viewer-BPQHMx3-.js";
27
+ import { b as slackMessageTsSchema, g as slackTeamIdSchema, h as slackChannelIdSchema, n as createSlackActor, p as parseSlackUserId, s as parseActorUserId, u as parseSlackChannelId, v as parseSlackMessageTs, y as slackMessageTsFromMs } from "./actor-D2iXzvlN.js";
28
+ import { a as resolveSlackActingUser, i as unfurlDashboardConversationLinks, n as handleSlackContinueHereClick, o as isSlackWorkspaceMember, s as slackWorkspaceBotId, t as SLACK_CONTINUE_HERE_ACTION_ID } from "./slack-conversation-unfurl-DYnqe5ci.js";
29
+ import { o as unlinkProvider } from "./connections-BlikzEJv.js";
30
+ import { s as buttonUserInputField } from "./web-message-id-lNodcCOI.js";
31
+ import { n as verifySlackSignature, t as runWithSlackInstallation } from "./adapter-context-BdVnSuY5.js";
32
+ import { a as resumeConversationDelivery } from "./conversation-turn-DAhRdX4m.js";
33
+ import { t as processConversationWork } from "./worker-B-pM_-3K.js";
34
+ import { t as bindMessageAgent } from "./message-CkCOcbFH.js";
35
+ import { t as bindSpawnAgent } from "./spawn-cGasWW33.js";
36
+ import { a as pluginTaskQueueConsumer, n as createVercelPluginTaskCallback, o as registerVercelPluginTaskDevConsumer } from "./task-queue-DcF0nhhz.js";
37
+ import { t as processPluginTask } from "./task-runner-BGXF7Fo7.js";
38
+ import { i as registerVercelCacheWarmupDevConsumer, l as verifyWorkspaceSnapshotJobMessage, n as cacheWarmupQueueConsumer, o as WORKSPACE_SNAPSHOT_JOB_QUEUE_TOPIC, r as createVercelCacheWarmupCallback } from "./queue-DFaOscp5.js";
39
+ import { t as JUNIOR_VERSION } from "./version-Uo3c94Dx.js";
40
+ import { s as conversationPendingMessageDeliverySchema } from "./conversation-feed-BZJRk6UV.js";
42
41
  import { createRequire } from "node:module";
43
42
  import { Hono } from "hono";
44
43
  import * as z from "zod";
45
44
  import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
46
- import { and, asc, desc, eq, gte, inArray, isNotNull, isNull, lte, ne, or, sql } from "drizzle-orm";
47
- import { EVENT_SUMMARY_MAX_LENGTH, EVENT_TEXT_MAX_LENGTH, dispatchOptionsSchema, eventSchema, eventTriggerFiltersText, isSlackDestination, userSchema } from "@sentry/junior-plugin-api";
45
+ import { and, asc, eq, inArray, isNotNull, isNull, lte, ne, or, sql } from "drizzle-orm";
46
+ import { EVENT_SUMMARY_MAX_LENGTH, EVENT_TEXT_MAX_LENGTH, dispatchOptionsSchema, eventSchema as eventSchema$1, eventTriggerFiltersText, isSlackDestination, userSchema } from "@sentry/junior-plugin-api";
48
47
  import { pathToFileURL } from "node:url";
49
48
  import { Message, ThreadImpl } from "chat";
50
49
  import pLimit from "p-limit";
51
50
  import net from "node:net";
52
51
  import { decodeJwt } from "jose";
53
- import { performance } from "node:perf_hooks";
54
52
  import { HTTPException } from "hono/http-exception";
55
53
  import https from "node:https";
56
54
  import * as acp from "@agentclientprotocol/sdk";
@@ -60,250 +58,6 @@ import { bodyLimit } from "hono/body-limit";
60
58
  import { createAuthMiddleware } from "better-auth/api";
61
59
  import { getSessionCookie } from "better-auth/cookies";
62
60
  import { betterAuth } from "better-auth/minimal";
63
- // src/chat/cache-warming/backfill.ts
64
- /**
65
- * Fill of the empty cache warming gap lists from stored Conversation
66
- * history, about once a month.
67
- *
68
- * `warmup.ts` learns reply gaps only from idle periods after it is deployed.
69
- * Until a `gapSegment` has gaps, Junior sends no warmups for it. This replays
70
- * the stored model calls of the last `GLOBAL_GAPS_TTL_MS` with the same rules
71
- * as live recording, so warming can start soon after the first deploy.
72
- *
73
- * The heartbeat runs it. Only one run claims it, and a completed run marks
74
- * the install as done, also when it stopped on its time budget or skipped a
75
- * batch that the statement timeout canceled. It fills only segment lists
76
- * that are empty when it starts, so it does not add history to gaps that
77
- * live recording already has.
78
- *
79
- * History does not tell the plugin work state or the archive state that a
80
- * Conversation had when an idle period started. So it fills only the
81
- * segments of Conversations that are not archived and have work state
82
- * `none`, which most Conversations have. The `open` and `done` segments and
83
- * the `archived:*` segments stay empty until live gaps arrive. Until then,
84
- * `decideWarmup` leans on their `parentGapSegment`, a `none` segment that
85
- * this fills. Each idle period still records its gap, so the segment fills
86
- * from live idle periods.
87
- */
88
- const BACKFILL_KEY = "junior:cache_warming:backfill:work_state:v2";
89
- const BACKFILL_CLAIM_TTL_MS = 60 * MINUTE_MS;
90
- const BACKFILL_DONE_TTL_MS = GLOBAL_GAPS_TTL_MS;
91
- const CONVERSATION_BATCH_SIZE = 10;
92
- const QUERY_CANCELED = "57014";
93
- const BACKFILL_BUDGET_MS = 6e4;
94
- const BACKFILL_GAPS_MAX = GLOBAL_GAPS_MAX / 2;
95
- const BACKFILL_SEGMENTS = new Set([true, false].flatMap((userActor) => [
96
- 0,
97
- 1,
98
- 2,
99
- 3
100
- ].map((endedTurns) => historySegment(userActor, endedTurns))));
101
- function historySegment(userActor, endedTurns) {
102
- return gapSegment({
103
- userActor,
104
- endedTurns,
105
- workState: "none",
106
- archived: false
107
- });
108
- }
109
- async function loadConversations(windowStartMs) {
110
- return await getDb().select({
111
- conversationId: juniorConversations.conversationId,
112
- kind: juniorConversations.kind,
113
- parentConversationId: juniorConversations.parentConversationId
114
- }).from(juniorConversations).where(and(gte(juniorConversations.lastActivityAt, new Date(windowStartMs)), isNull(juniorConversations.transcriptPurgedAt))).orderBy(desc(juniorConversations.lastActivityAt), juniorConversations.conversationId);
115
- }
116
- async function loadEvents(conversationIds) {
117
- const events = juniorConversationEvents;
118
- const isUserMessage = sql`${events.type} = 'user_message'`;
119
- const message = sql`CASE
120
- WHEN ${events.type} <> 'assistant_message' THEN NULL
121
- WHEN ${events.schemaVersion} >= 2 THEN (${events.payload}->>'message')::jsonb
122
- ELSE ${events.payload}
123
- END`;
124
- return await getDb().select({
125
- conversationId: events.conversationId,
126
- type: sql`${events.type}`,
127
- personInstruction: sql`CASE WHEN ${isUserMessage} THEN (${events.payload}->'provenance'->'actor'->>'userId') IS NOT NULL END`,
128
- stopReason: sql`(${message})->>'stopReason'`,
129
- startedAtMs: sql`(${message})->>'timestamp'`,
130
- cacheRead: sql`${events.payload}->'usage'->>'cacheRead'`,
131
- cacheWrite: sql`${events.payload}->'usage'->>'cacheWrite'`
132
- }).from(events).innerJoin(juniorConversations, eq(juniorConversations.conversationId, events.conversationId)).where(and(inArray(events.conversationId, conversationIds), or(eq(events.type, "assistant_message"), and(isUserMessage, sql`(${events.payload}->'provenance'->>'authority') = 'instruction'`)), gte(events.createdAt, juniorConversations.createdAt))).orderBy(events.conversationId, events.seq);
133
- }
134
- /**
135
- * Replay the model calls of one Conversation the way the recorder in
136
- * `warmup.ts` sees them, and return the gap of each idle period.
137
- *
138
- * Live recording measures from the start of the request that ended a Turn to
139
- * the start of the next recorded request. Here both times are the
140
- * `timestamp` of the stored assistant message, which Pi sets when it starts
141
- * the request. That is the closest stored time to the recorder's clock.
142
- *
143
- * Live recording records gaps only for idle periods that it could warm. The
144
- * stored usage gives the prefix size, so periods with a prefix below
145
- * `MIN_WARMUP_PREFIX_TOKENS` are skipped. The model, cache retention, and
146
- * snapshot size of the request are not checked: this assumes that reply
147
- * timing does not depend on them.
148
- */
149
- function replayConversation(kind, events, nowMs) {
150
- const gaps = [];
151
- const close = (idle, untilMs) => {
152
- const gapMs = untilMs - idle.sinceMs;
153
- if (!idle.eligible || gapMs <= 0) return;
154
- gaps.push({
155
- segment: idle.segment,
156
- sinceMs: idle.sinceMs,
157
- gapMs: gapMs >= 33e5 ? NO_REPLY_GAP_MS : gapMs
158
- });
159
- };
160
- let userActor = false;
161
- let inTurn = false;
162
- let endedTurns = 0;
163
- let lastCallMs;
164
- let idle;
165
- for (const event of events) {
166
- if (event.type === "user_message") {
167
- if (!inTurn) {
168
- userActor = event.personInstruction === true && kind !== "task";
169
- inTurn = true;
170
- }
171
- continue;
172
- }
173
- if (event.stopReason !== "toolUse") inTurn = false;
174
- const startedAtMs = event.startedAtMs === null ? NaN : Number(event.startedAtMs);
175
- if (!Number.isFinite(startedAtMs) || event.stopReason === "error" || event.stopReason === "aborted") continue;
176
- if (idle) close(idle, startedAtMs);
177
- idle = void 0;
178
- if (lastCallMs !== void 0 && startedAtMs - lastCallMs > CONVERSATION_STATE_TTL_MS) endedTurns = 0;
179
- lastCallMs = startedAtMs;
180
- if (event.stopReason === "stop") {
181
- const prefixTokens = Number(event.cacheRead ?? 0) + Number(event.cacheWrite ?? 0);
182
- idle = {
183
- sinceMs: startedAtMs,
184
- segment: historySegment(userActor, endedTurns),
185
- eligible: prefixTokens >= MIN_WARMUP_PREFIX_TOKENS
186
- };
187
- endedTurns += 1;
188
- }
189
- }
190
- if (idle && nowMs - idle.sinceMs >= 33e5) close(idle, nowMs);
191
- return gaps;
192
- }
193
- function isQueryCanceled(error) {
194
- let current = error;
195
- for (let depth = 0; current && depth < 6; depth += 1) {
196
- if (typeof current !== "object") return false;
197
- if (current.code === QUERY_CANCELED) return true;
198
- current = current.cause;
199
- }
200
- return false;
201
- }
202
- async function collectGaps(nowMs, budgetMs) {
203
- const startedAt = performance.now();
204
- const windowStartMs = nowMs - GLOBAL_GAPS_TTL_MS;
205
- const conversations = await loadConversations(windowStartMs);
206
- const recorded = [];
207
- let scanned = 0;
208
- let canceledBatches = 0;
209
- let budgetExceeded = false;
210
- for (let i = 0; i < conversations.length; i += CONVERSATION_BATCH_SIZE) {
211
- if (i > 0 && performance.now() - startedAt >= budgetMs) {
212
- budgetExceeded = true;
213
- break;
214
- }
215
- const batch = conversations.slice(i, i + CONVERSATION_BATCH_SIZE);
216
- let rows;
217
- try {
218
- rows = await loadEvents(batch.map((row) => row.conversationId));
219
- } catch (error) {
220
- if (!isQueryCanceled(error)) throw error;
221
- canceledBatches += 1;
222
- continue;
223
- }
224
- const events = /* @__PURE__ */ new Map();
225
- for (const event of rows) {
226
- const list = events.get(event.conversationId) ?? [];
227
- list.push(event);
228
- events.set(event.conversationId, list);
229
- }
230
- for (const conversation of batch) {
231
- const gaps = replayConversation(conversationKindFromRow(conversation), events.get(conversation.conversationId) ?? [], nowMs);
232
- recorded.push(...gaps.filter((gap) => gap.sinceMs >= windowStartMs));
233
- }
234
- scanned += batch.length;
235
- }
236
- recorded.sort((a, b) => a.sinceMs - b.sinceMs);
237
- const bySegment = /* @__PURE__ */ new Map();
238
- for (const gap of recorded) {
239
- const list = bySegment.get(gap.segment) ?? [];
240
- list.push(gap.gapMs);
241
- bySegment.set(gap.segment, list);
242
- }
243
- return {
244
- bySegment,
245
- scanned,
246
- canceledBatches,
247
- budgetExceeded
248
- };
249
- }
250
- /**
251
- * Fill each empty cache warming gap list from the stored Conversation
252
- * history. The heartbeat calls it each minute. After a run completes, a call
253
- * makes one state request and returns, until the completed run expires.
254
- *
255
- * A run that uses its scan budget writes the gaps that it has and also
256
- * completes. Some gaps are better than none, and a run that cannot finish
257
- * would otherwise try again each hour.
258
- */
259
- async function backfillCacheWarmingGaps(args) {
260
- if (!getChatConfig().cacheWarmingEnabled) return;
261
- const state = getStateAdapter();
262
- await state.connect();
263
- if (!await state.setIfNotExists(BACKFILL_KEY, "running", BACKFILL_CLAIM_TTL_MS)) return;
264
- await withSpan("cache_warming.backfill", "cache_warming.backfill", {}, async (setSpanAttributes) => {
265
- const emptySegments = /* @__PURE__ */ new Set();
266
- for (const segment of BACKFILL_SEGMENTS) if ((await state.getList(segmentGapsKey(segment))).length === 0) emptySegments.add(segment);
267
- const { bySegment, scanned, canceledBatches, budgetExceeded } = await collectGaps(args.nowMs, args.budgetMs ?? BACKFILL_BUDGET_MS);
268
- const logAttributes = {
269
- "app.cache_warming.backfill.conversation_count": scanned,
270
- "app.cache_warming.backfill.canceled_batch_count": canceledBatches,
271
- "app.cache_warming.backfill.budget_exceeded": budgetExceeded
272
- };
273
- if (scanned === 0 && canceledBatches > 0) {
274
- logInfo("cache_warming.backfill.not_completed", logAttributes);
275
- setSpanAttributes({
276
- ...logAttributes,
277
- "app.cache_warming.backfill.outcome": "not_completed"
278
- });
279
- return;
280
- }
281
- let gapCount = 0;
282
- let segmentCount = 0;
283
- for (const [segment, gaps] of bySegment) {
284
- if (!emptySegments.has(segment)) continue;
285
- const key = segmentGapsKey(segment);
286
- const newest = gaps.slice(-BACKFILL_GAPS_MAX);
287
- for (const gapMs of newest) await state.appendToList(key, gapMs, {
288
- maxLength: GLOBAL_GAPS_MAX,
289
- ttlMs: GLOBAL_GAPS_TTL_MS
290
- });
291
- gapCount += newest.length;
292
- segmentCount += 1;
293
- }
294
- await state.set(BACKFILL_KEY, "done", BACKFILL_DONE_TTL_MS);
295
- const completed = {
296
- ...logAttributes,
297
- "app.cache_warming.backfill.gap_count": gapCount,
298
- "app.cache_warming.backfill.segment_count": segmentCount
299
- };
300
- logInfo("cache_warming.backfill.completed", completed);
301
- setSpanAttributes({
302
- ...completed,
303
- "app.cache_warming.backfill.outcome": "completed"
304
- });
305
- });
306
- }
307
61
  // src/chat/events/timers.ts
308
62
  /** Publish a bounded batch of due timers; the mailbox owns agent execution. */
309
63
  async function runTimerWatchHeartbeat(args) {
@@ -431,6 +185,11 @@ function createHeartbeatContext(args) {
431
185
  db: getDb(),
432
186
  embedder: createPluginEmbedder(pluginName),
433
187
  events: args.events,
188
+ reviewItems: { forConversation: (conversationId) => createPluginReviewItems({
189
+ conversationId,
190
+ plugin: pluginName,
191
+ show: args.showReviewItem ?? (async () => {})
192
+ }) },
434
193
  state: createPluginState(pluginName),
435
194
  log: createPluginLogger(pluginName),
436
195
  agent: {
@@ -606,7 +365,7 @@ function eventInput(task, event, outcomes, catalog) {
606
365
  * limit both use the event key, so it runs and counts once.
607
366
  */
608
367
  async function ingestEventAutomations(input, options) {
609
- const event = eventSchema.parse(input);
368
+ const event = eventSchema$1.parse(input);
610
369
  const db = getDb();
611
370
  const nowMs = options.nowMs ?? Date.now();
612
371
  const catalog = getEventCatalog();
@@ -958,7 +717,7 @@ function taskDedupeFingerprint(task) {
958
717
  month: task.schedule.recurrence.month ?? null,
959
718
  startDate: task.schedule.recurrence.startDate,
960
719
  time: task.schedule.recurrence.time,
961
- weekdays: [...task.schedule.recurrence.weekdays ?? []].sort()
720
+ weekdays: [...task.schedule.recurrence.weekdays ?? []].sort((left, right) => left - right)
962
721
  } : null,
963
722
  timezone: task.schedule.timezone
964
723
  },
@@ -1510,7 +1269,8 @@ async function runPluginHeartbeats(args) {
1510
1269
  conversationWorkQueue: args.conversationWorkQueue,
1511
1270
  events: createPluginEventPublisher(plugin, args.events),
1512
1271
  plugin,
1513
- nowMs: args.nowMs
1272
+ nowMs: args.nowMs,
1273
+ showReviewItem: args.showReviewItem
1514
1274
  }))), PLUGIN_HEARTBEAT_TIMEOUT_MS);
1515
1275
  if (typeof result?.dispatchCount === "number" && result.dispatchCount > 0) logInfo("plugin.heartbeat.dispatched", {
1516
1276
  "app.dispatch.count": result.dispatchCount,
@@ -1618,13 +1378,19 @@ async function runHeartbeat(args) {
1618
1378
  await runPluginHeartbeats({
1619
1379
  conversationWorkQueue: queue,
1620
1380
  events,
1621
- nowMs: args.nowMs
1381
+ nowMs: args.nowMs,
1382
+ showReviewItem: args.showReviewItem
1622
1383
  });
1623
1384
  try {
1624
1385
  await backfillCacheWarmingGaps({ nowMs: args.nowMs });
1625
1386
  } catch (error) {
1626
1387
  logException(error, "cache_warming.backfill.failed");
1627
1388
  }
1389
+ try {
1390
+ await runSavingsRefillSlice({ nowMs: args.nowMs });
1391
+ } catch (error) {
1392
+ logException(error, "cache_warming.savings_refill.failed");
1393
+ }
1628
1394
  }
1629
1395
  // src/handlers/scheduler-auth.ts
1630
1396
  /** Check the bearer secret that internal cron requests must send. */
@@ -1645,9 +1411,10 @@ async function GET$3(request, waitUntil, options = {}) {
1645
1411
  waitUntil(() => runHeartbeat({
1646
1412
  conversationWorkQueue: options.conversationWorkQueue,
1647
1413
  events: options.events,
1648
- nowMs
1414
+ nowMs,
1415
+ showReviewItem: options.showReviewItem
1649
1416
  }).catch((error) => {
1650
- logException(error, "heartbeat.failed", { "app.heartbeat.now_ms": nowMs });
1417
+ logException(error, "heartbeat.run.failed", { "app.heartbeat.now_ms": nowMs });
1651
1418
  }));
1652
1419
  return new Response("Accepted", { status: 202 });
1653
1420
  }
@@ -1981,7 +1748,7 @@ async function handleSandboxEgressRoute(request, tracePropagationDomains, next)
1981
1748
  const SANDBOX_EGRESS_TOKEN_HEADER = "x-junior-sandbox-egress-token";
1982
1749
  function isLoopbackDevelopmentRequest(request) {
1983
1750
  const hostname = new URL(request.url).hostname;
1984
- return process.env.NODE_ENV === "development" && (hostname === "127.0.0.1" || hostname === "localhost");
1751
+ return process.env["NODE_ENV"] === "development" && (hostname === "127.0.0.1" || hostname === "localhost");
1985
1752
  }
1986
1753
  /** Clear command-scoped sandbox egress signals through the loopback dev server. */
1987
1754
  async function DELETE(request) {
@@ -2003,7 +1770,7 @@ async function GET(request) {
2003
1770
  });
2004
1771
  }
2005
1772
  // src/chat/slack/annotation-details.ts
2006
- const eventSchema$1 = z.object({
1773
+ const eventSchema = z.object({
2007
1774
  trigger_id: z.string().min(1),
2008
1775
  user: z.string().min(1),
2009
1776
  external_ref: z.object({
@@ -2018,14 +1785,14 @@ const refSchema = z.tuple([
2018
1785
  ]);
2019
1786
  /** Show saved annotation facts only to a viewer who can read their Conversation. */
2020
1787
  async function presentSlackAnnotationDetails(event, teamId) {
2021
- const triggerId = event.trigger_id;
1788
+ const triggerId = event["trigger_id"];
2022
1789
  if (typeof triggerId !== "string" || !triggerId) return;
2023
1790
  const client = getSlackClient();
2024
1791
  const missing = () => client.entity.presentDetails({
2025
1792
  trigger_id: triggerId,
2026
1793
  error: { status: "not_found" }
2027
1794
  });
2028
- const parsed = eventSchema$1.safeParse(event);
1795
+ const parsed = eventSchema.safeParse(event);
2029
1796
  if (!parsed.success || !teamId) {
2030
1797
  await missing();
2031
1798
  return;
@@ -2280,10 +2047,11 @@ async function act(args) {
2280
2047
  const { services, target } = args;
2281
2048
  const actor = await resolveActingUser(services, args.payload, target);
2282
2049
  if (!actor) return;
2283
- const conversationId = await readSlackReviewItemCardConversationId({
2284
- ...target,
2285
- itemId: args.itemId
2286
- }) ?? `slack:${target.channelId}:${target.threadTs}`;
2050
+ const conversationId = await resolveSlackReviewItemCardConversationId({
2051
+ channelId: target.channelId,
2052
+ teamId: actor.teamId,
2053
+ threadTs: target.threadTs
2054
+ });
2287
2055
  const delivery = {
2288
2056
  queue: services.queue,
2289
2057
  show: createSlackReviewItemShow(() => services.adapter)
@@ -2821,8 +2589,8 @@ function slackMessageAttributes(body) {
2821
2589
  "app.slack.bot_id": field(event?.bot_id, /^B[A-Z0-9]+$/),
2822
2590
  "app.slack.team_id": field(body.team_id, /^T[A-Z0-9]+$/),
2823
2591
  "app.slack.enterprise_id": field(body.enterprise_id, /^E[A-Z0-9]+$/),
2824
- "app.slack.user_team": field(event?.user_team, teamId),
2825
- "app.slack.source_team": field(event?.source_team, teamId),
2592
+ "app.slack.user_team": field(event?.["user_team"], teamId),
2593
+ "app.slack.source_team": field(event?.["source_team"], teamId),
2826
2594
  "app.slack.event_team": field(event?.team, teamId),
2827
2595
  "app.slack.context_team_id": field(body.context_team_id, /^T[A-Z0-9]+$/),
2828
2596
  "app.slack.context_enterprise_id": body.context_enterprise_id === null ? "none" : field(body.context_enterprise_id, /^E[A-Z0-9]+$/),
@@ -2923,7 +2691,7 @@ const detailsEventSchema = z.object({
2923
2691
  async function presentSlackAutomationDetails(event, teamId) {
2924
2692
  const parsed = detailsEventSchema.safeParse(event);
2925
2693
  const client = getSlackClient();
2926
- const triggerId = event.trigger_id;
2694
+ const triggerId = event["trigger_id"];
2927
2695
  if (typeof triggerId !== "string" || !triggerId) return;
2928
2696
  if (!parsed.success || !teamId) {
2929
2697
  await client.entity.presentDetails({
@@ -3009,7 +2777,7 @@ async function buildThread(args) {
3009
2777
  });
3010
2778
  }
3011
2779
  function shouldIgnoreMessage(message) {
3012
- return message.author.isMe === true || !parseActorUserId(message.author.userId);
2780
+ return message.author.isMe || !parseActorUserId(message.author.userId);
3013
2781
  }
3014
2782
  /**
3015
2783
  * Resolve the Slack author Identity at ingress and bind its id to the message.
@@ -3029,19 +2797,21 @@ async function resolveSlackConversationId(args) {
3029
2797
  const providerThread = parseSlackThreadId(args.canonicalThreadId);
3030
2798
  const conversationStore = args.conversationStore ?? getConversationStore();
3031
2799
  if (!providerThread) return args.canonicalThreadId;
3032
- const thread = {
3033
- provider: "slack",
3034
- providerDestinationId: providerThread.channelId,
3035
- providerTenantId: args.installation.teamId ?? "",
3036
- providerConversationId: providerThread.threadTs
3037
- };
3038
- const ownerId = await conversationStore.getConversationIdByProviderConversation(thread);
2800
+ const ownerId = await findSlackThreadOwnerId({
2801
+ channelId: providerThread.channelId,
2802
+ conversationStore,
2803
+ teamId: args.installation.teamId ?? "",
2804
+ threadTs: providerThread.threadTs
2805
+ });
3039
2806
  if (ownerId) return ownerId;
3040
2807
  if (args.claimAtMs === void 0 || !args.installation.teamId) return args.canonicalThreadId;
3041
2808
  return await conversationStore.claimProviderConversation({
3042
- ...thread,
3043
2809
  atMs: args.claimAtMs,
3044
- conversationId: args.canonicalThreadId
2810
+ conversationId: args.canonicalThreadId,
2811
+ provider: "slack",
2812
+ providerConversationId: providerThread.threadTs,
2813
+ providerDestinationId: providerThread.channelId,
2814
+ providerTenantId: args.installation.teamId
3045
2815
  });
3046
2816
  }
3047
2817
  /**
@@ -3269,7 +3039,7 @@ async function handleSlackEvent(args) {
3269
3039
  state,
3270
3040
  task: async () => {
3271
3041
  if (event.type === "assistant_thread_started" || event.type === "assistant_thread_context_changed") {
3272
- const parsed = slackAssistantThreadSchema.safeParse(event.assistant_thread);
3042
+ const parsed = slackAssistantThreadSchema.safeParse(event["assistant_thread"]);
3273
3043
  if (!parsed.success) return;
3274
3044
  const thread = parsed.data;
3275
3045
  const callback = {
@@ -3287,7 +3057,7 @@ async function handleSlackEvent(args) {
3287
3057
  return;
3288
3058
  }
3289
3059
  if (event.type === "entity_details_requested") {
3290
- const ref = event.external_ref;
3060
+ const ref = event["external_ref"];
3291
3061
  if (ref && typeof ref === "object" && "type" in ref && ref.type === "annotation") await presentSlackAnnotationDetails(event, installation.teamId);
3292
3062
  else await presentSlackAutomationDetails(event, installation.teamId);
3293
3063
  return;
@@ -4937,8 +4707,8 @@ function authenticatedAcpUser(connection) {
4937
4707
  function supportsUrlElicitation(params) {
4938
4708
  const parsed = initializeParamsSchema.safeParse(params);
4939
4709
  if (!parsed.success) return false;
4940
- const elicitation = parsed.data.clientCapabilities?.elicitation;
4941
- return isRecord(elicitation) && isRecord(elicitation.url);
4710
+ const elicitation = parsed.data.clientCapabilities?.["elicitation"];
4711
+ return isRecord(elicitation) && isRecord(elicitation["url"]);
4942
4712
  }
4943
4713
  function parseParams(schema, params) {
4944
4714
  const parsed = schema.safeParse(params);
@@ -5030,12 +4800,11 @@ function textResponse(body, status) {
5030
4800
  });
5031
4801
  }
5032
4802
  function jsonResponse(value, status, headers) {
4803
+ const responseHeaders = new Headers(headers);
4804
+ if (!responseHeaders.has("Content-Type")) responseHeaders.set("Content-Type", ACP_JSON_MIME_TYPE);
5033
4805
  return new Response(JSON.stringify(value), {
5034
4806
  status,
5035
- headers: {
5036
- "Content-Type": ACP_JSON_MIME_TYPE,
5037
- ...headers
5038
- }
4807
+ headers: responseHeaders
5039
4808
  });
5040
4809
  }
5041
4810
  function emptyResponse(status) {
@@ -7478,8 +7247,8 @@ function createBetterAuth(config) {
7478
7247
  secret,
7479
7248
  trustedOrigins: config.trustedOrigins,
7480
7249
  socialProviders: { google: {
7481
- clientId: required(config.googleClientId ?? process.env.GOOGLE_CLIENT_ID, "GOOGLE_CLIENT_ID"),
7482
- clientSecret: required(config.googleClientSecret ?? process.env.GOOGLE_CLIENT_SECRET, "GOOGLE_CLIENT_SECRET"),
7250
+ clientId: required(config.googleClientId ?? process.env["GOOGLE_CLIENT_ID"], "GOOGLE_CLIENT_ID"),
7251
+ clientSecret: required(config.googleClientSecret ?? process.env["GOOGLE_CLIENT_SECRET"], "GOOGLE_CLIENT_SECRET"),
7483
7252
  hd: hostedDomain,
7484
7253
  prompt: "select_account",
7485
7254
  disableIdTokenSignIn: true,
@@ -7492,7 +7261,7 @@ function createBetterAuth(config) {
7492
7261
  return {
7493
7262
  user: {
7494
7263
  email: claims.email,
7495
- emailVerified: claims.email_verified === true,
7264
+ emailVerified: claims.email_verified,
7496
7265
  image: claims.picture ?? null,
7497
7266
  name: claims.name
7498
7267
  },
@@ -7584,7 +7353,7 @@ const DASHBOARD_PACKAGE_NAME = "@sentry/junior-dashboard";
7584
7353
  function dashboardRequiresSignIn(dashboard) {
7585
7354
  if (!dashboard || dashboard.disabled) return false;
7586
7355
  if (dashboard.authRequired !== void 0) return dashboard.authRequired;
7587
- return process.env.JUNIOR_DASHBOARD_AUTH_REQUIRED?.trim() !== "false";
7356
+ return process.env["JUNIOR_DASHBOARD_AUTH_REQUIRED"]?.trim() !== "false";
7588
7357
  }
7589
7358
  /** Mount the dashboard app on the dashboard-owned host paths. */
7590
7359
  async function createDashboardRouteRegistrations(args) {
@@ -7692,7 +7461,6 @@ function dashboardHostRoutePaths(dashboard, authenticatedRoutes = []) {
7692
7461
  "/api/images/*",
7693
7462
  "/api/objects",
7694
7463
  "/api/stats",
7695
- "/api/reply-times",
7696
7464
  "/api/versions",
7697
7465
  "/api/conversations",
7698
7466
  "/api/conversations/*",
@@ -7783,9 +7551,9 @@ function validateDashboardRouteOwnership(args) {
7783
7551
  // src/app.ts
7784
7552
  /** Resolve the public deployment URL used by ACP and MCP browser authorization. */
7785
7553
  function resolvePublicBaseURL(dashboard) {
7786
- const configured = dashboard?.baseURL?.trim() || process.env.JUNIOR_BASE_URL?.trim();
7554
+ const configured = dashboard?.baseURL?.trim() || process.env["JUNIOR_BASE_URL"]?.trim();
7787
7555
  if (configured) return configured;
7788
- const vercelURL = process.env.VERCEL_PROJECT_PRODUCTION_URL?.trim() || process.env.VERCEL_URL?.trim();
7556
+ const vercelURL = process.env["VERCEL_PROJECT_PRODUCTION_URL"]?.trim() || process.env["VERCEL_URL"]?.trim();
7789
7557
  if (!vercelURL) return void 0;
7790
7558
  return vercelURL.startsWith("https://") || vercelURL.startsWith("http://") ? vercelURL : `https://${vercelURL}`;
7791
7559
  }
@@ -8122,7 +7890,7 @@ async function createApp(options) {
8122
7890
  });
8123
7891
  let agentContinuePOST;
8124
7892
  let pluginTaskPOST;
8125
- if (process.env.NODE_ENV === "development") {
7893
+ if (process.env["NODE_ENV"] === "development") {
8126
7894
  registerVercelConversationWorkDevConsumer(getConversationWorkOptions());
8127
7895
  registerVercelPluginTaskDevConsumer();
8128
7896
  registerVercelWorkspaceSnapshotJobDevConsumer();
@@ -8155,7 +7923,8 @@ async function createApp(options) {
8155
7923
  app.get("/api/internal/heartbeat", (c) => {
8156
7924
  return GET$3(c.req.raw, waitUntil, {
8157
7925
  conversationWorkQueue,
8158
- events
7926
+ events,
7927
+ showReviewItem: createSlackReviewItemShow(getProductionSlackAdapter)
8159
7928
  });
8160
7929
  });
8161
7930
  app.get("/api/internal/retention", (c) => {