@sentry/junior 0.301.0 → 0.302.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 (79) hide show
  1. package/dist/adapter-context-Cx9fn9B3.js +43 -0
  2. package/dist/{admin-CRJHvCGg.js → admin-_poE5NKL.js} +2 -2
  3. package/dist/{agent-runner-H4YhvNBj.js → agent-runner-CY9RvsTX.js} +1380 -10601
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +4 -5
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +91 -68
  8. package/dist/{app-HDZglaIu.d.ts → app-BpY3wtRP.d.ts} +2 -2
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +66 -296
  11. package/dist/{background-compaction-queue-CNrZ3QcU.js → background-compaction-queue-CXFq1_Cz.js} +94 -203
  12. package/dist/{briefs-x6Mzwxmg.js → briefs-B3NG-pid.js} +2 -2
  13. package/dist/{catalog-runtime-BEY6EGRi.js → catalog-runtime-Dss0lSV6.js} +1 -1
  14. package/dist/cli/chat.js +15 -15
  15. package/dist/cli/check.js +3 -3
  16. package/dist/cli/main.js +3 -3
  17. package/dist/cli/plugins.js +4 -4
  18. package/dist/cli/snapshot-create.js +4 -4
  19. package/dist/cli/upgrade.d.ts +1 -1
  20. package/dist/cli/upgrade.js +3 -3
  21. package/dist/{config-CmjhyqgB.js → config-CzeZiMKs.js} +2 -2
  22. package/dist/{connections-CfIRm0xv.js → connections-CDYhMfrs.js} +6 -6
  23. package/dist/{continue-in-slack-DPoABVkB.js → continue-in-slack-7Uf05ndC.js} +5 -6
  24. package/dist/{conversation-feed-CfpyFMHP.js → conversation-feed-Clf_cv0n.js} +1 -0
  25. package/dist/{conversation-privacy-0CM0V2qK.js → conversation-privacy-D9xnM5mK.js} +1 -1
  26. package/dist/{conversation-turn-C0sxyvS-.js → conversation-turn-D7SEZgTG.js} +15 -16
  27. package/dist/{credential-sync-tEMKZ_8M.js → credential-sync-DoD0gW-j.js} +13 -15
  28. package/dist/{db-Czra10QW.js → db-B-gtnNjr.js} +314 -5
  29. package/dist/{db-BdUHQhrC.d.ts → db-BdsCzytP.d.ts} +1 -1
  30. package/dist/{executor-D_023K0H.js → executor-DZg20EqU.js} +39 -4
  31. package/dist/install-t1KQyTUs.js +228 -0
  32. package/dist/instrumentation.js +2 -2
  33. package/dist/{state-CEbZuZD6.js → legacy-web-actor-id-C-cEeWqL.js} +33 -4
  34. package/dist/{lineage-DmMIE0VL.js → lineage-C79GjoQr.js} +2 -2
  35. package/dist/{logging-DcjLDDqi.js → logging-C9oDAg4M.js} +7 -3
  36. package/dist/{message-C0JY9RJP.js → message-BLUCzJXN.js} +8 -8
  37. package/dist/{model-input-CBp-p24N.js → model-input-5jwNC45G.js} +3 -3
  38. package/dist/nitro.d.ts +1 -1
  39. package/dist/nitro.js +4 -3
  40. package/dist/{oauth-callback-server-BRq9QNhU.js → oauth-callback-server-BBl66vCb.js} +2 -2
  41. package/dist/{projection-CQNDOi82.js → projection-CIBwgD3s.js} +282 -64
  42. package/dist/{prompt-DLUB5m72.js → prompt-CRQbzp5e.js} +14 -4
  43. package/dist/queue-DtCDaIct.js +115 -0
  44. package/dist/{registry-Dj377ADs.js → registry-DdFQHZ_d.js} +1 -1
  45. package/dist/{resolve-DJkh9Fky.js → resolve-CdW4BdrK.js} +4 -229
  46. package/dist/{result-C8iIpDl1.js → result-oOMv1t4O.js} +9 -9
  47. package/dist/{runner-DZqrOy8C.js → runner-DqitLtm-.js} +8 -8
  48. package/dist/{sandbox-egress-signals-CGwH86S9.js → sandbox-egress-signals-Bw9I0yfJ.js} +1 -1
  49. package/dist/{schema-CdZFn7Qd.d.ts → schema-BIFM-U1a.d.ts} +441 -30
  50. package/dist/{schema-DyHXiQKI.js → schema-DnVQepWP.js} +66 -29
  51. package/dist/{service-account-D6jGR4a1.js → service-account-B6mKAPVo.js} +3 -3
  52. package/dist/{service-account-suY004dx.js → service-account-CrZftRTb.js} +257 -6
  53. package/dist/{session-stop-BLmfFI3d.js → session-stop-DW63Z3kj.js} +543 -548
  54. package/dist/{skills-CmNG0dHb.js → skills-C16fz60Z.js} +2 -2
  55. package/dist/{slack-conversation-unfurl-Bty-DlHe.js → slack-conversation-unfurl-BHhefEb7.js} +8 -7
  56. package/dist/{spawn-CNjkpXpk.js → spawn-D_RnFYfy.js} +6 -6
  57. package/dist/{stop-Bjy2-K4H.js → stop-7p1i08CY.js} +724 -106
  58. package/dist/{store-DmV4CoNr.js → store-C28I0CVW.js} +5 -5
  59. package/dist/{task-queue-AhG1tSXR.js → task-queue-BVUJbQ28.js} +3 -3
  60. package/dist/{task-runner-BMxZI3o7.js → task-runner-CWi8j7Z6.js} +6 -8
  61. package/dist/{thread-context-CXLnbg7g.js → thread-context-D3-yYUd0.js} +7 -7
  62. package/dist/{store-Epv6t4vV.js → turn-session-routing-BFMS9ATF.js} +381 -10
  63. package/dist/{turn-user-message-DsUZi9gn.js → turn-user-message-C3-O8Omt.js} +3 -3
  64. package/dist/{validation-DOz8X9BU.js → validation-BSFKUIb4.js} +1 -1
  65. package/dist/{version-CGMRmMPK.js → version-BHHXNi-0.js} +1 -1
  66. package/dist/version.js +1 -1
  67. package/dist/{viewer-H3EsMWtJ.js → viewer-B1SO21Qa.js} +3 -3
  68. package/dist/warmup-Bz9bzkzN.js +13927 -0
  69. package/dist/{statuses-Hn-HsOph.js → web-message-id-lNodcCOI.js} +136 -1
  70. package/dist/{worker-ClphajjD.js → worker-BspReIIK.js} +7 -7
  71. package/migrations/0108_conversation_embeddings.sql +13 -0
  72. package/migrations/meta/0108_snapshot.json +4688 -0
  73. package/migrations/meta/_journal.json +7 -0
  74. package/package.json +8 -6
  75. package/dist/adapter-CNjGEJO9.js +0 -303
  76. package/dist/reporting-window-DopzcOHh.js +0 -137
  77. package/dist/turn-session-routing-BD3-jJl7.js +0 -380
  78. package/dist/users-BxvYclQg.js +0 -424
  79. package/dist/warmup-CdU5hR49.js +0 -3715
@@ -1,50 +1,189 @@
1
1
  import { h as startSpan } from "./sentry-BRTJqumy.js";
2
- import { $ as loadTurnCheckpoint, $n as webActorUserIds, $o as isSlackRequestTimeout, A as latestConversationMessageSeq, Ai as getDashboardLinkFilter, Ao as readLatestConversationBrief, Bo as getSlackFileId, Co as conversationIsMemberRoot, Cs as piMessageFromHistoryItem, D as estimateConversationMessagesTokens, Do as viewerMarksFromParticipant, E as buildConversationContext, Eo as conversationViewerMarks, F as turnHasReply, Fr as listReplyActionItems, Go as slackAttachmentsVersionQuery, Gr as canUserReadReviewItem, H as PluginCredentialFailureError, Ho as readAttachmentVisionSummary, Hr as canActOnReviewItem, Ht as releaseInboundMessage, I as upsertConversationMessage, Ii as isDashboardLink, Io as buildSentryConversationUrl, Ir as listWaitingConversations, K as AuthorizationFlowDisabledError, Ko as SlackActionError, Kr as isOnlyAssignee, Li as parseDashboardConversationLink, Ln as trimTrailingAssistantMessages, M as normalizeConversationText, Mi as getDashboardPersonLink, Mo as readConversationEventPageAfter, N as recordDeliveredAssistantMessage, No as readConversationEventPageAround, Nr as getReviewItem, O as getConversationMessageSlackTs, Oa as removeReactionFromMessage, P as trimConversationMessages, Qo as isDmChannel, Ri as parseDashboardPersonLink, S as resolveConversationTitle, So as conversationHasParticipantUser, To as conversationPinnedForUser, V as createPluginEgress, Wo as recordSlackAttachment, X as clearPendingAuth, Xo as getSlackClient, Xr as reviewItemNeedsSomeone, Yo as getHeaderString, Zn as createUserTokenStore, _o as createPluginLogger, a as loadProjection, at as failTurnRecord, b as persistConversationMessages, ba as truncateStatusText, bn as persistWithRetry, bo as createConversationAccessReader, ct as listTurnSummaries, d as recordAuthorizationCompleted, di as cancelSubscriptions, ds as listConversationAnnotations, es as normalizeSlackConversationId, et as lostWorkerBeforeFirstSave, fa as SLACK_USER_MENTION_RE, fr as getPlugins, fs as listConversationAnnotationsById, ga as normalizeSlackStatusText, gs as lookupSlackUserNames, h as recordSubscribedReplyRoute, hs as lookupSlackUser, i as loadConversationProjection, it as completeTurnRecord, j as markConversationMessage, jo as readConversationEventPage, k as isHumanConversationMessage, ki as getDashboardConversationLink, kr as closeReviewItem, lt as recordTurnSummary, n as commitMessages, ns as streamPrivateSlackFile, nt as saveTurnCheckpoint, o as loadTurnProjection, qo as downloadPrivateSlackFile, rr as applyPluginFormatMarkdown, rs as withSlackRetries, rt as abandonTurnRecord, st as getTurnRecord, t as commitAcceptedReply, tn as buildTurnErrorResponse, tt as pauseLostWorkerTurn, un as getAssistantReplyText, v as hydrateConversationMessages, va as slackMentionedUserIds, w as fallbackShortTitle, wo as conversationIsNotUnsubscribedRoot, xa as addReactionToMessage, xo as readConversationAccessFromSql, xs as configValueSchema, y as persistConversationMessageWindow, ya as wrapBareSlackUserIds, yo as canAddConversationMessages, ys as createPluginCache, zo as notInheritedByForkChild, zr as takeReviewItem } from "./projection-CQNDOi82.js";
3
- import { D as resolveGatewayModel, M as textCharsForTokens, R as escapeXml, c as getSlackClientSecret, i as getChatConfig, j as estimateTextTokens, l as getSlackSigningSecret, n as botConfig, o as getSlackBotToken, q as isProviderRetryError, s as getSlackClientId, y as normalizeSlackEmojiName } from "./config-CmjhyqgB.js";
4
- import { E as withSpan, G as isRecord, K as toOptionalNumber, S as setTags, T as withLogContext, W as normalizeIdentityEmail, b as setSpanAttributes, f as logError, h as logWarn, m as logInfo, n as createChatSdkLogger, o as getActiveTraceContext, p as logException, q as toOptionalString, s as getActiveTraceId, t as buildTurnFailureResponse, y as setSentryUser } from "./logging-DcjLDDqi.js";
5
- import { t as JUNIOR_VERSION } from "./version-CGMRmMPK.js";
2
+ import { $ as loadTurnCheckpoint, $o as isSlackRequestTimeout, A as latestConversationMessageSeq, Ai as getDashboardLinkFilter, Ao as readLatestConversationBrief, Bo as getSlackFileId, Co as conversationIsMemberRoot, Cs as configValueSchema, D as estimateConversationMessagesTokens, Do as viewerMarksFromParticipant, E as buildConversationContext, Eo as conversationViewerMarks, F as turnHasReply, Fr as listReplyActionItems, Go as slackAttachmentsVersionQuery, Gr as canUserReadReviewItem, H as PluginCredentialFailureError, Ho as readAttachmentVisionSummary, Hr as canActOnReviewItem, Ht as releaseInboundMessage, I as upsertConversationMessage, Ii as isDashboardLink, Io as buildSentryConversationUrl, Ir as listWaitingConversations, K as AuthorizationFlowDisabledError, Ko as SlackActionError, Kr as isOnlyAssignee, Li as parseDashboardConversationLink, Ln as trimTrailingAssistantMessages, M as normalizeConversationText, Mi as getDashboardPersonLink, Mo as readConversationEventPageAfter, N as recordDeliveredAssistantMessage, No as readConversationEventPageAround, Nr as getReviewItem, O as getConversationMessageSlackTs, Oa as removeReactionFromMessage, P as trimConversationMessages, Qo as isDmChannel, Ri as parseDashboardPersonLink, S as resolveConversationTitle, So as conversationHasParticipantUser, To as conversationPinnedForUser, Ts as piMessageFromHistoryItem, V as createPluginEgress, Wo as recordSlackAttachment, X as clearPendingAuth, Xo as getSlackClient, Xr as reviewItemNeedsSomeone, Yo as getHeaderString, Zn as createUserTokenStore, _o as createPluginLogger, _s as lookupSlackUser, a as loadProjection, at as failTurnRecord, b as persistConversationMessages, ba as truncateStatusText, bn as persistWithRetry, bo as createConversationAccessReader, ct as listTurnSummaries, d as recordAuthorizationCompleted, di as cancelSubscriptions, es as normalizeSlackConversationId, et as lostWorkerBeforeFirstSave, fa as SLACK_USER_MENTION_RE, ga as normalizeSlackStatusText, h as recordSubscribedReplyRoute, i as loadConversationProjection, it as completeTurnRecord, j as markConversationMessage, jo as readConversationEventPage, k as isHumanConversationMessage, ki as getDashboardConversationLink, kr as closeReviewItem, lt as recordTurnSummary, ms as listConversationAnnotationsById, n as commitMessages, ns as streamPrivateSlackFile, nt as saveTurnCheckpoint, o as loadTurnProjection, ps as listConversationAnnotations, qo as downloadPrivateSlackFile, rs as withSlackRetries, rt as abandonTurnRecord, st as getTurnRecord, t as commitAcceptedReply, tn as buildTurnErrorResponse, tr as applyPluginFormatMarkdown, tt as pauseLostWorkerTurn, ua as resolveBaseUrl, un as getAssistantReplyText, ur as getPlugins, v as hydrateConversationMessages, va as slackMentionedUserIds, vs as lookupSlackUserNames, w as fallbackShortTitle, wo as conversationIsNotUnsubscribedRoot, xa as addReactionToMessage, xo as readConversationAccessFromSql, xs as createPluginCache, y as persistConversationMessageWindow, ya as wrapBareSlackUserIds, yo as canAddConversationMessages, zo as notInheritedByForkChild, zr as takeReviewItem } from "./projection-CIBwgD3s.js";
3
+ import { D as resolveGatewayModel, M as textCharsForTokens, R as escapeXml, c as getSlackClientSecret, i as getChatConfig, j as estimateTextTokens, l as getSlackSigningSecret, n as botConfig, o as getSlackBotToken, q as isProviderRetryError, s as getSlackClientId, y as normalizeSlackEmojiName } from "./config-CzeZiMKs.js";
4
+ import { E as withSpan, G as normalizeIdentityEmail, J as toOptionalString, K as isRecord, S as setTags, T as withLogContext, b as setSpanAttributes, f as logError, h as logWarn, m as logInfo, n as createChatSdkLogger, o as getActiveTraceContext, p as logException, q as toOptionalNumber, s as getActiveTraceId, t as buildTurnFailureResponse, y as setSentryUser } from "./logging-C9oDAg4M.js";
5
+ import { t as JUNIOR_VERSION } from "./version-BHHXNi-0.js";
6
6
  import { f as parseSlackTeamId, i as isActorUserId, n as createSlackActor, o as isUserActor, r as createSlackResumeActor, s as parseActorUserId, t as createActor, u as parseSlackChannelId, v as parseSlackMessageTs } from "./actor-D2iXzvlN.js";
7
- import { $ as resolveRootConversationId, D as conversationKindFromRow, J as addAgentTurnUsage, N as resolveActorIdentityId, O as locationFromRow, P as saveActorAvatar, Q as hasAgentTurnUsage, S as deliversFinalText, T as postsRunNotices, U as readCachedUserByEmail, W as createCache, Z as agentTurnUsageSchema, _ as loadConversationSlackTenantIds, a as getConversationStore, f as withConversationEventLock, g as setArchivedAt, h as readConversationTrees, it as createSlackDestination, nt as nextDetailVersion, o as getDb, ot as requireSlackDestination, p as conversationAncestors, q as parseSessionSource, r as getConversationEventStore, s as getSqlExecutor, v as lastMessageAtSql, w as isTopLevelKind } from "./db-Czra10QW.js";
8
- import { D as juniorCodeChanges, E as juniorConversationAnnotations, M as juniorIdentities, N as juniorUsers, P as juniorDestinations, b as juniorConversationBriefs, j as juniorConversations, l as juniorReviewItems, s as juniorReviewItemConversations, v as juniorConversationParticipants, w as juniorConversationEvents } from "./executor-D_023K0H.js";
7
+ import { F as saveActorAvatar, G as createCache, J as getStateAdapter, O as conversationKindFromRow, P as resolveActorIdentityId, Q as acquireActiveLock, S as deliversFinalText, T as postsRunNotices, W as readCachedUserByEmail, X as setStateValues, Y as getStateValues, _ as loadConversationSlackTenantIds, a as getConversationStore, ct as hasAgentTurnUsage, f as withConversationEventLock, ft as nextDetailVersion, g as setArchivedAt, gt as requireSlackDestination, h as readConversationTrees, it as addAgentTurnUsage, k as locationFromRow, lt as resolveRootConversationId, mt as createSlackDestination, o as getDb, p as conversationAncestors, r as getConversationEventStore, rt as parseSessionSource, s as getSqlExecutor, st as agentTurnUsageSchema, v as lastMessageAtSql, w as isTopLevelKind } from "./db-B-gtnNjr.js";
8
+ import { D as juniorConversationAnnotations, F as juniorDestinations, M as juniorConversations, N as juniorIdentities, O as juniorCodeChanges, P as juniorUsers, T as juniorConversationEvents, l as juniorReviewItems, s as juniorReviewItemConversations, v as juniorConversationParticipants, x as juniorConversationBriefs } from "./executor-DZg20EqU.js";
9
9
  import { d as contextProvenance, p as instructionProvenanceFor, t as KNOWN_CONVERSATION_EVENT_TYPES } from "./history-IjdmO_r6.js";
10
- import { a as setStateValues, i as getStateValues, r as getStateAdapter, s as acquireActiveLock } from "./adapter-CNjGEJO9.js";
11
- import { d as actorLogContext, f as credentialContextForActor } from "./registry-Dj377ADs.js";
12
- import { C as renderBlockText, Dt as throwApiError, F as resolveSlackChannelIdFromMessage, I as resolveSlackChannelIdFromThreadId, It as shouldEmitDevAgentTrace, K as readConversationSourceTask, L as resolveDestinationVisibility, N as parseSlackThreadId, Nt as RetryableDeliveryError, P as readSlackRawMessageContext, S as renderAttachmentText, St as conversationReadPositionQuery, T as createSlackReviewItemShow, a as buildAuthPauseResponse, at as appendAndEnqueueWebMessage, bt as storeAttachment, ct as createConversationId, ft as AttachmentUploadError, ht as verifyAttachmentUploads, it as acceptsWebMessages, lt as recordWebConversationActivity, m as latestProgressStatus, n as executeAgentRun, st as createAndEnqueueConversation, t as createAgentRunner, tt as deliverReviewItemChange, ut as webActorFromUser, w as parseSlackMessageReference } from "./agent-runner-H4YhvNBj.js";
13
- import { a as EVENT_SYSTEM_ACTOR, c as completeDecision, o as isEventConversationMessage, u as completeText } from "./prompt-DLUB5m72.js";
14
- import { f as identityAvatarUrl, g as userAvatarUrlsFromIdentities, h as readUserAvatarUrls } from "./viewer-H3EsMWtJ.js";
10
+ import { d as actorLogContext, f as credentialContextForActor } from "./registry-DdFQHZ_d.js";
11
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-Dss0lSV6.js";
12
+ import { M as shouldEmitDevAgentTrace, a as buildAuthPauseResponse, c as createClientMetadata, g as resolveDestinationVisibility, k as RetryableDeliveryError, l as readMcpClientInformation, n as executeAgentRun, s as getMcpOAuthCallbackPath, t as createAgentRunner, u as latestProgressStatus, y as createSlackReviewItemShow } from "./agent-runner-CY9RvsTX.js";
13
+ import { a as EVENT_SYSTEM_ACTOR, c as completeDecision, o as isEventConversationMessage, u as completeText } from "./prompt-CRQbzp5e.js";
14
+ import { f as identityAvatarUrl, g as userAvatarUrlsFromIdentities, h as readUserAvatarUrls } from "./viewer-B1SO21Qa.js";
15
15
  import { G as MAX_ATTACHMENT_BYTES, Y as readMessageAttachments, f as conversationEventPageSchema, u as conversationDetailReportSchema } from "./conversation-BNXfq6Lb.js";
16
+ import { n as webActorUserIds } from "./legacy-web-actor-id-C-cEeWqL.js";
16
17
  import { t as readJuniorSecret } from "./secrets-DebYU866.js";
17
- import { $ as sendSlackReply, O as resolveMailboxTurnWork, Q as resolveSlackReplyTarget, X as maybePostAutomatedTurnLimitNotice, at as conversationSubtree, b as isExperimentalFeatureEnabled, c as loadReviewItemInput, f as buildSteeringPiMessage, g as withoutSavedSteeringMessages, j as legacyWebMailboxMetadataSchema, l as savedInputInstruction, o as skipInputAfterConversationStop, ot as conversationSubtreeColumns, p as instructionActorFor, r as markConversationsStopped, rt as recordFinishedTurnForAutomatedLimit } from "./session-stop-BLmfFI3d.js";
18
- import { Et as executeTurn, J as cancelSignInWait, K as stopChildAgentsBelow, Tt as AgentRunError, W as dropOwnUnreadLoopReplies, _t as getTurnAuthorization, c as listConversationWork, ft as supersedeTurnForInput, gt as wakePausedTurn, l as readLastUserMessageAtByConversation, mt as getPausedTurnRequest, pt as createPausedTurns, q as stopChildAgentsOf, s as isConversationWorkDone, v as getChildAgentLabel, vt as canJoinTurn, wt as getWebAuthorization, yt as canShareTurn } from "./warmup-CdU5hR49.js";
19
- import { T as getTurnRequestDeadline, l as getVercelConversationWorkQueue } from "./background-compaction-queue-CNrZ3QcU.js";
20
- import { L as buildDeterministicAssistantMessageId, R as buildDeterministicTurnId, a as ConversationTurnBoundaryError, c as TurnInputDeferredError, d as isTurnInputCommitLostError, f as isTurnInputDeferredError, g as startActiveTurn, h as markTurnFailed, i as getTurnUserSlackMessageTs, l as getConversationTurnBoundaryError, m as markTurnCompleted, o as CooperativeTurnYieldError, p as markTurnClosed, r as getTurnUserReplyAttachmentContext, s as TurnInputCommitLostError, t as getTurnUserMessage, u as isCooperativeTurnYieldError, v as getTurnLifecycle } from "./turn-user-message-DsUZi9gn.js";
21
- import { D as stopConversationWork, E as steerWebPendingMessages, _ as getConversationWorkState, a as cancelHumanFacingPendingMessages, g as getConversation, h as ensureConversationWake, r as appendAndEnqueueInboundMessage, s as claimInboundMessage } from "./store-DmV4CoNr.js";
22
- import { a as getPersistedThreadState, c as coerceThreadConversationState, i as getPersistedSandboxState, n as resolveTurnSessionRouting, o as persistThreadRuntimeState, r as getLocationConfigurationService, s as persistThreadStateById, t as resolveConversationRouting } from "./turn-session-routing-BD3-jJl7.js";
23
- import { c as isEmptyUserInputAnswer, l as normalizeUserInputAnswer, m as isVisionImageMediaType, p as detectImageMediaType } from "./statuses-Hn-HsOph.js";
24
- import { p as webMessageId } from "./reporting-window-DopzcOHh.js";
25
- import { D as readAutomationTitlesByConversationId, _ as markDispatchRunning, a as getDispatchConversationId, c as getDispatchRecord, d as isTerminalDispatchStatus, g as markDispatchFailed, h as markDispatchCompleted, l as getDispatchTurnId, m as markDispatchBlocked, n as claimDispatchMailboxAppend, o as getDispatchIdForConversation, p as markDispatchAwaitingResume, r as confirmDispatchMailboxAppend, s as getDispatchInputMessageId } from "./store-Epv6t4vV.js";
26
- import { a as runWithSlackInstallation, d as isConversationMember, f as isPublicSlackChannel, h as listThreadReplies, l as getChannelMessage, u as getConversationInfo } from "./users-BxvYclQg.js";
27
- import { D as webPageObjectCard, E as personObjectCard, T as messageObjectCard, l as conversationPendingMessagesReportSchema, n as conversationFeedSchema, p as healthReportSchema, t as conversationFeedBriefSchema, w as conversationObjectCard } from "./conversation-feed-CfpyFMHP.js";
28
- import { c as withTurnSpan, n as createConversationTurnWorker, o as getTurnInputSpanAttributes, r as canPauseConversationDelivery, s as turnInputTelemetry } from "./conversation-turn-C0sxyvS-.js";
29
- import { n as buildStoredAttachmentPromptText } from "./model-input-CBp-p24N.js";
30
- import { i as enqueueAgentInvocationResult, n as createDeliverToParent, s as withAgentInvocationResultActors, t as createChildConversationWorker } from "./result-C8iIpDl1.js";
31
- import { t as bindMessageAgent } from "./message-C0JY9RJP.js";
32
- import { t as readConversationLineage } from "./lineage-DmMIE0VL.js";
33
- import { t as bindSpawnAgent } from "./spawn-CNjkpXpk.js";
34
- import { a as requireTurnFailureEventId, c as buildDeliveredTurnStatePatch, i as getAgentTurnDiagnosticsAttributes, l as loadPendingMessageCards, n as loadThreadContextTrimFloor, o as completeAuthPauseTurn, r as finalizeFailedTurnReplyWithEvent, s as persistAuthPauseTurnState, t as buildTurnThreadContext } from "./thread-context-CXLnbg7g.js";
35
- import { n as scheduleSessionCompletedPluginTasks } from "./task-runner-BMxZI3o7.js";
36
- import { r as canContinueInSlack } from "./continue-in-slack-DPoABVkB.js";
18
+ import { G as conversationSubtree, I as maybePostAutomatedTurnLimitNotice, J as isExperimentalFeatureEnabled, K as conversationSubtreeColumns, O as legacyWebMailboxMetadataSchema, R as resolveSlackReplyTarget, T as resolveMailboxTurnWork, U as recordFinishedTurnForAutomatedLimit, c as loadReviewItemInput, f as buildSteeringPiMessage, g as withoutSavedSteeringMessages, l as savedInputInstruction, o as skipInputAfterConversationStop, p as instructionActorFor, r as markConversationsStopped, z as sendSlackReply } from "./session-stop-DW63Z3kj.js";
19
+ import { $n as renderBlockText, Cr as listThreadReplies, Ct as recordWebConversationActivity, Et as AttachmentUploadError, Fn as wakePausedTurn, Gn as executeTurn, In as getTurnAuthorization, Kt as getChildAgentLabel, Ln as canJoinTurn, Mn as createPausedTurns, Ni as NO_REPLY_GAP_MS, Nn as getPausedTurnRequest, Pi as gapSegment, Pt as storeAttachment, Qn as renderAttachmentText, Rn as canShareTurn, St as createConversationId, Un as getWebAuthorization, Wn as AgentRunError, Xn as throwApiError, _ as connectedState, _n as stopChildAgentsBelow, a as segmentGapsKey, br as isConversationMember, c as listConversationWork, d as firstLiveSavingsDate, dr as resolveSlackChannelIdFromMessage, er as parseSlackMessageReference, f as idlePeriodSavings, fi as readConversationSourceTask, fr as resolveSlackChannelIdFromThreadId, gn as dropOwnUnreadLoopReplies, ht as deliverReviewItemChange, ji as MINUTE_MS, jn as supersedeTurnForInput, kt as verifyAttachmentUploads, lr as parseSlackThreadId, lt as conversationReadPositionQuery, n as GLOBAL_GAPS_MAX, p as replaceHistorySavings, r as GLOBAL_GAPS_TTL_MS, s as isConversationWorkDone, st as readLastUserMessageAtByConversation, t as CONVERSATION_STATE_TTL_MS, u as addHistoryPeriod, ur as readSlackRawMessageContext, v as providerCacheTtlMs, vn as stopChildAgentsOf, vr as getChannelMessage, vt as acceptsWebMessages, wt as webActorFromUser, xr as isPublicSlackChannel, xt as createAndEnqueueConversation, yn as cancelSignInWait, yr as getConversationInfo, yt as appendAndEnqueueWebMessage } from "./warmup-Bz9bzkzN.js";
20
+ import { C as markDispatchCompleted, F as readAutomationTitlesByConversationId, S as markDispatchBlocked, T as markDispatchRunning, _ as getDispatchTurnId, a as getPersistedThreadState, c as coerceThreadConversationState, d as confirmDispatchMailboxAppend, g as getDispatchRecord, h as getDispatchInputMessageId, i as getPersistedSandboxState, m as getDispatchIdForConversation, n as resolveTurnSessionRouting, o as persistThreadRuntimeState, p as getDispatchConversationId, r as getLocationConfigurationService, s as persistThreadStateById, t as resolveConversationRouting, u as claimDispatchMailboxAppend, w as markDispatchFailed, x as markDispatchAwaitingResume, y as isTerminalDispatchStatus } from "./turn-session-routing-BFMS9ATF.js";
21
+ import { h as isVisionImageMediaType, l as isEmptyUserInputAnswer, m as detectImageMediaType, t as webMessageId, u as normalizeUserInputAnswer } from "./web-message-id-lNodcCOI.js";
22
+ import { L as buildDeterministicAssistantMessageId, R as buildDeterministicTurnId, a as ConversationTurnBoundaryError, c as TurnInputDeferredError, d as isTurnInputCommitLostError, f as isTurnInputDeferredError, g as startActiveTurn, h as markTurnFailed, i as getTurnUserSlackMessageTs, l as getConversationTurnBoundaryError, m as markTurnCompleted, o as CooperativeTurnYieldError, p as markTurnClosed, r as getTurnUserReplyAttachmentContext, s as TurnInputCommitLostError, t as getTurnUserMessage, u as isCooperativeTurnYieldError, v as getTurnLifecycle } from "./turn-user-message-C3-O8Omt.js";
23
+ import { o as getVercelConversationWorkQueue, p as getTurnRequestDeadline } from "./background-compaction-queue-CXFq1_Cz.js";
24
+ import { D as stopConversationWork, E as steerWebPendingMessages, _ as getConversationWorkState, a as cancelHumanFacingPendingMessages, g as getConversation, h as ensureConversationWake, r as appendAndEnqueueInboundMessage, s as claimInboundMessage } from "./store-C28I0CVW.js";
25
+ import { d as PluginMcpClient, u as McpAuthorizationRequiredError, v as getMcpStoredOAuthCredentials } from "./service-account-CrZftRTb.js";
26
+ import { t as runWithSlackInstallation } from "./adapter-context-Cx9fn9B3.js";
27
+ import { D as webPageObjectCard, E as personObjectCard, T as messageObjectCard, l as conversationPendingMessagesReportSchema, n as conversationFeedSchema, p as healthReportSchema, t as conversationFeedBriefSchema, w as conversationObjectCard } from "./conversation-feed-Clf_cv0n.js";
28
+ import { c as withTurnSpan, n as createConversationTurnWorker, o as getTurnInputSpanAttributes, r as canPauseConversationDelivery, s as turnInputTelemetry } from "./conversation-turn-D7SEZgTG.js";
29
+ import { n as buildStoredAttachmentPromptText } from "./model-input-5jwNC45G.js";
30
+ import { i as enqueueAgentInvocationResult, n as createDeliverToParent, s as withAgentInvocationResultActors, t as createChildConversationWorker } from "./result-oOMv1t4O.js";
31
+ import { t as bindMessageAgent } from "./message-BLUCzJXN.js";
32
+ import { t as readConversationLineage } from "./lineage-C79GjoQr.js";
33
+ import { t as bindSpawnAgent } from "./spawn-D_RnFYfy.js";
34
+ import { a as requireTurnFailureEventId, c as buildDeliveredTurnStatePatch, i as getAgentTurnDiagnosticsAttributes, l as loadPendingMessageCards, n as loadThreadContextTrimFloor, o as completeAuthPauseTurn, r as finalizeFailedTurnReplyWithEvent, s as persistAuthPauseTurnState, t as buildTurnThreadContext } from "./thread-context-D3-yYUd0.js";
35
+ import { n as scheduleSessionCompletedPluginTasks } from "./task-runner-CWi8j7Z6.js";
36
+ import { r as canContinueInSlack } from "./continue-in-slack-7Uf05ndC.js";
37
37
  import * as z from "zod";
38
- import { createHash, createHmac, timingSafeEqual } from "node:crypto";
39
- import { and, asc, count, desc, eq, gt, inArray, isNotNull, isNull, lte, ne, not, or, sql } from "drizzle-orm";
38
+ import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
39
+ import { and, asc, count, desc, eq, gt, gte, inArray, isNotNull, isNull, lte, ne, not, or, sql } from "drizzle-orm";
40
40
  import { conversationSidebarAnnotationSchema, createSlackSource, encodeObjectImageRef, objectAnnotationSchema, objectLinkFilterMatches, objectLinkFilterSpecificity, objectTypeSchema, ownedObjectAnnotationSchema } from "@sentry/junior-plugin-api";
41
41
  import { alias } from "drizzle-orm/pg-core";
42
42
  import { Message, ThreadImpl, stringifyMarkdown } from "chat";
43
43
  import net from "node:net";
44
+ import { performance } from "node:perf_hooks";
44
45
  import https from "node:https";
45
46
  import { SlackFormatConverter, createSlackAdapter } from "@chat-adapter/slack";
46
47
  import dns from "node:dns";
47
48
  import { parse } from "parse5";
49
+ // src/chat/images/ids.ts
50
+ /**
51
+ * Opaque, signed ids for images that Junior serves. A browser never gets the
52
+ * address of the image, and it cannot ask for an image that Junior did not
53
+ * name.
54
+ */
55
+ const IMAGE_ID_CONTEXT = "junior-image-id";
56
+ /**
57
+ * Widths that the image route serves. A fixed set keeps the cache small.
58
+ * Callers ask for at least 2x the CSS width, so images stay sharp on
59
+ * high-density screens.
60
+ */
61
+ const IMAGE_WIDTHS = [
62
+ 64,
63
+ 128,
64
+ 320,
65
+ 640,
66
+ 1280
67
+ ];
68
+ const imageIdPayloadSchema = z.object({
69
+ ref: z.string().min(1),
70
+ source: z.string().min(1)
71
+ }).strict();
72
+ function signature$1(payload) {
73
+ const secret = readJuniorSecret();
74
+ if (!secret) throw new Error("Cannot sign image ids without JUNIOR_SECRET");
75
+ return createHmac("sha256", secret).update(`${IMAGE_ID_CONTEXT}:${payload}`).digest("base64url");
76
+ }
77
+ /** Return the signed id of one image. */
78
+ function encodeImageId(image) {
79
+ const payload = Buffer.from(JSON.stringify({
80
+ ref: image.ref,
81
+ source: image.source
82
+ }), "utf8").toString("base64url");
83
+ return `${payload}.${signature$1(payload)}`;
84
+ }
85
+ /** Return the image of a signed id, or nothing when the id is not valid. */
86
+ function decodeImageId(id) {
87
+ const [payload, actual, extra] = id.split(".");
88
+ if (!payload || !actual || extra !== void 0) return void 0;
89
+ const expected = Buffer.from(signature$1(payload));
90
+ const given = Buffer.from(actual);
91
+ if (expected.length !== given.length || !timingSafeEqual(expected, given)) return;
92
+ try {
93
+ const parsed = imageIdPayloadSchema.safeParse(JSON.parse(Buffer.from(payload, "base64url").toString("utf8")));
94
+ return parsed.success ? parsed.data : void 0;
95
+ } catch {
96
+ return;
97
+ }
98
+ }
99
+ /**
100
+ * Return the Junior API path of one image at one width. `version` changes
101
+ * the path when the image changes, so a browser can keep each path.
102
+ */
103
+ function imagePath(image, width, version) {
104
+ const query = new URLSearchParams({ w: String(width) });
105
+ if (version) query.set("v", version);
106
+ return `/api/images/${encodeImageId(image)}?${query}`;
107
+ }
108
+ // src/chat/mcp/viewer.ts
109
+ function viewerAuthProvider(plugin, userId) {
110
+ const provider = plugin.manifest.name;
111
+ const baseUrl = resolveBaseUrl();
112
+ if (!baseUrl) throw new Error("Cannot determine base URL (set JUNIOR_BASE_URL or deploy to Vercel)");
113
+ const callbackUrl = `${baseUrl}${getMcpOAuthCallbackPath(provider)}`;
114
+ return {
115
+ redirectUrl: callbackUrl,
116
+ clientMetadata: createClientMetadata(callbackUrl),
117
+ clientInformation: async () => await readMcpClientInformation({
118
+ callbackUrl,
119
+ oauthClient: plugin.manifest.mcp?.oauthClient,
120
+ provider,
121
+ userId
122
+ }),
123
+ saveClientInformation: () => {
124
+ throw new Error(`A ${provider} viewer read cannot register a client`);
125
+ },
126
+ tokens: async () => (await getMcpStoredOAuthCredentials(userId, provider))?.tokens,
127
+ saveTokens: () => void 0,
128
+ discoveryState: async () => (await getMcpStoredOAuthCredentials(userId, provider))?.discoveryState,
129
+ invalidateCredentials: () => void 0,
130
+ redirectToAuthorization: () => void 0,
131
+ saveCodeVerifier: () => void 0,
132
+ codeVerifier: () => {
133
+ throw new Error(`A ${provider} viewer read has no sign-in`);
134
+ },
135
+ mcpLoginOwner: async () => ({
136
+ provider,
137
+ userId
138
+ })
139
+ };
140
+ }
141
+ function providerContent(content) {
142
+ return content.flatMap((part) => {
143
+ if (part.type === "text" && "text" in part) return [{
144
+ type: "text",
145
+ text: String(part.text)
146
+ }];
147
+ if (part.type === "image" && "data" in part && "mimeType" in part) return [{
148
+ type: "image",
149
+ data: String(part.data),
150
+ mimeType: String(part.mimeType)
151
+ }];
152
+ return [];
153
+ });
154
+ }
155
+ /**
156
+ * Create read-only MCP access to one plugin's provider as one viewer. The
157
+ * viewer's User id is the subject of their stored MCP login.
158
+ */
159
+ function createViewerMcp(provider, userId) {
160
+ return { async callTool(input) {
161
+ const plugin = pluginCatalogRuntime.getDefinition(provider);
162
+ if (!plugin?.manifest.mcp) throw new Error(`Plugin "${provider}" does not support MCP`);
163
+ if (!plugin.manifest.mcp.allowedTools?.includes(input.name)) throw new Error(`Plugin ${provider} does not allow MCP tool ${input.name} for viewer reads`);
164
+ if (!(await getMcpStoredOAuthCredentials(userId, provider))?.tokens) return { status: "not_connected" };
165
+ const client = new PluginMcpClient(plugin, { authProvider: viewerAuthProvider(plugin, userId) });
166
+ try {
167
+ if ((await client.listTools()).find((candidate) => candidate.name === input.name)?.annotations?.readOnlyHint !== true) throw new Error(`MCP tool ${provider}/${input.name} is not read-only`);
168
+ const result = await client.callTool(input.name, input.arguments ?? {});
169
+ const content = Array.isArray(result.content) ? providerContent(result.content) : [];
170
+ if (result.isError) return {
171
+ status: "error",
172
+ message: content.flatMap((part) => part.type === "text" ? [part.text] : []).join("\n").trim() || "MCP tool call failed"
173
+ };
174
+ return {
175
+ status: "success",
176
+ content,
177
+ ...result.structuredContent !== void 0 ? { structuredContent: result.structuredContent } : void 0
178
+ };
179
+ } catch (error) {
180
+ if (error instanceof McpAuthorizationRequiredError) return { status: "not_connected" };
181
+ throw error;
182
+ } finally {
183
+ await client.close().catch(() => void 0);
184
+ }
185
+ } };
186
+ }
48
187
  // src/api/conversations/first-message.ts
49
188
  /**
50
189
  * Read the text of the first human message for each untitled conversation.
@@ -6826,65 +6965,6 @@ async function resolveSlackMessageLink(viewer, url) {
6826
6965
  }));
6827
6966
  }
6828
6967
  }
6829
- // src/chat/images/ids.ts
6830
- /**
6831
- * Opaque, signed ids for images that Junior serves. A browser never gets the
6832
- * address of the image, and it cannot ask for an image that Junior did not
6833
- * name.
6834
- */
6835
- const IMAGE_ID_CONTEXT = "junior-image-id";
6836
- /**
6837
- * Widths that the image route serves. A fixed set keeps the cache small.
6838
- * Callers ask for at least 2x the CSS width, so images stay sharp on
6839
- * high-density screens.
6840
- */
6841
- const IMAGE_WIDTHS = [
6842
- 64,
6843
- 128,
6844
- 320,
6845
- 640,
6846
- 1280
6847
- ];
6848
- const imageIdPayloadSchema = z.object({
6849
- ref: z.string().min(1),
6850
- source: z.string().min(1)
6851
- }).strict();
6852
- function signature$1(payload) {
6853
- const secret = readJuniorSecret();
6854
- if (!secret) throw new Error("Cannot sign image ids without JUNIOR_SECRET");
6855
- return createHmac("sha256", secret).update(`${IMAGE_ID_CONTEXT}:${payload}`).digest("base64url");
6856
- }
6857
- /** Return the signed id of one image. */
6858
- function encodeImageId(image) {
6859
- const payload = Buffer.from(JSON.stringify({
6860
- ref: image.ref,
6861
- source: image.source
6862
- }), "utf8").toString("base64url");
6863
- return `${payload}.${signature$1(payload)}`;
6864
- }
6865
- /** Return the image of a signed id, or nothing when the id is not valid. */
6866
- function decodeImageId(id) {
6867
- const [payload, actual, extra] = id.split(".");
6868
- if (!payload || !actual || extra !== void 0) return void 0;
6869
- const expected = Buffer.from(signature$1(payload));
6870
- const given = Buffer.from(actual);
6871
- if (expected.length !== given.length || !timingSafeEqual(expected, given)) return;
6872
- try {
6873
- const parsed = imageIdPayloadSchema.safeParse(JSON.parse(Buffer.from(payload, "base64url").toString("utf8")));
6874
- return parsed.success ? parsed.data : void 0;
6875
- } catch {
6876
- return;
6877
- }
6878
- }
6879
- /**
6880
- * Return the Junior API path of one image at one width. `version` changes
6881
- * the path when the image changes, so a browser can keep each path.
6882
- */
6883
- function imagePath(image, width, version) {
6884
- const query = new URLSearchParams({ w: String(width) });
6885
- if (version) query.set("v", version);
6886
- return `/api/images/${encodeImageId(image)}?${query}`;
6887
- }
6888
6968
  // src/net/public-address.ts
6889
6969
  /**
6890
6970
  * Own the public-address rule for fetches of URLs that any person can submit.
@@ -7206,6 +7286,7 @@ function parsePageMeta(html) {
7206
7286
  "twitter:image",
7207
7287
  "twitter:image:src"
7208
7288
  ].flatMap((name) => tags.get(name) ?? []),
7289
+ media: tags.get("og:type")?.startsWith("video") || first("og:video", "og:video:url") ? "video" : void 0,
7209
7290
  siteName: first("og:site_name", "application-name"),
7210
7291
  title: first("og:title", "twitter:title") ?? title
7211
7292
  };
@@ -7315,6 +7396,7 @@ const oembedResponseSchema = z.object({
7315
7396
  author_name: optionalText,
7316
7397
  provider_name: optionalText,
7317
7398
  thumbnail_url: optionalText,
7399
+ type: optionalText,
7318
7400
  cache_age: z.coerce.number().positive().optional().catch(void 0)
7319
7401
  });
7320
7402
  /** Read an oEmbed JSON body, or nothing when it is not one. */
@@ -7363,6 +7445,7 @@ async function readOembed(url) {
7363
7445
  author: oembed.author_name,
7364
7446
  cacheAgeSeconds: oembed.cache_age,
7365
7447
  images: oembed.thumbnail_url ? [oembed.thumbnail_url] : [],
7448
+ media: oembed.type === "video" ? "video" : oembed.type === "photo" ? "image" : void 0,
7366
7449
  siteName: oembed.provider_name,
7367
7450
  title: oembed.title
7368
7451
  };
@@ -7402,6 +7485,7 @@ async function loadWebPage(url) {
7402
7485
  value: webPageObjectCard({
7403
7486
  author: page.author,
7404
7487
  description: page.description,
7488
+ media: page.media,
7405
7489
  siteName: page.siteName ?? url.hostname,
7406
7490
  thumbnailUrl: thumbnailPath(page.images, page.pageUrl),
7407
7491
  title: page.title,
@@ -7482,10 +7566,20 @@ function objectLinkContext(name, viewer) {
7482
7566
  credentialContext: credentialContextForActor(OBJECT_LINK_SYSTEM_ACTOR),
7483
7567
  pluginAuth: { async handleAuthRequired() {} }
7484
7568
  }),
7569
+ imagePath: (ref, version) => imagePath({
7570
+ ref,
7571
+ source: name
7572
+ }, 640, version),
7485
7573
  findPerson: resolvePersonByAccount,
7486
7574
  log: createPluginLogger(name),
7487
7575
  plugin: { name },
7488
- viewer
7576
+ viewer,
7577
+ viewerEgress: createPluginEgress({
7578
+ credentialContext: credentialContextForActor(webActorFromUser(viewer)),
7579
+ pluginAuth: { async handleAuthRequired() {} },
7580
+ userOAuthOnly: true
7581
+ }),
7582
+ viewerMcp: createViewerMcp(name, viewer.id)
7489
7583
  };
7490
7584
  }
7491
7585
  function pluginLinkTypes(plugin) {
@@ -7496,7 +7590,8 @@ function pluginLinkTypes(plugin) {
7496
7590
  objectType: link.objectType,
7497
7591
  owner: name,
7498
7592
  readTool: link.readTool,
7499
- resolve: (viewer, url) => link.resolve(objectLinkContext(name, viewer), url)
7593
+ resolve: (viewer, url) => link.resolve(objectLinkContext(name, viewer), url),
7594
+ ...link.webPageFallback ? { webPageFallback: true } : void 0
7500
7595
  }));
7501
7596
  }
7502
7597
  /**
@@ -7509,15 +7604,18 @@ function readObjectLinkTypes(plugins = getPlugins()) {
7509
7604
  return linkTypes;
7510
7605
  }
7511
7606
  async function resolveWithLinkType(linkType, viewer, url) {
7512
- if (!await linkType.canView(viewer, url)) return null;
7607
+ if (!await linkType.canView(viewer, url)) return linkType.webPageFallback ? await resolveWithLinkType(webPageLinkType(), viewer, url) : null;
7513
7608
  const resolved = await linkType.resolve(viewer, url);
7514
7609
  if (!resolved) return null;
7515
7610
  const object = objectAnnotationSchema.parse(resolved);
7516
7611
  if (object.objectType !== linkType.objectType) throw new Error(`Link type "${linkType.owner}/${linkType.objectType}" returned a ${object.objectType} object.`);
7517
- return ownedObjectAnnotationSchema.parse({
7518
- ...object,
7519
- plugin: linkType.owner
7520
- });
7612
+ return {
7613
+ linkType,
7614
+ object: ownedObjectAnnotationSchema.parse({
7615
+ ...object,
7616
+ plugin: linkType.owner
7617
+ })
7618
+ };
7521
7619
  }
7522
7620
  /**
7523
7621
  * Resolve one link for one viewer without the card cache, so a change of
@@ -7527,11 +7625,7 @@ async function resolveWithLinkType(linkType, viewer, url) {
7527
7625
  async function resolveObjectLinkNow(viewer, url) {
7528
7626
  const linkType = findObjectLinkType(readObjectLinkTypes(), url);
7529
7627
  if (!linkType) return void 0;
7530
- const object = await resolveWithLinkType(linkType, viewer, url);
7531
- return object ? {
7532
- linkType,
7533
- object
7534
- } : void 0;
7628
+ return await resolveWithLinkType(linkType, viewer, url) ?? void 0;
7535
7629
  }
7536
7630
  /**
7537
7631
  * Resolve links to object cards for one viewer. A link without a link type,
@@ -7546,7 +7640,7 @@ async function resolveObjectLinks(viewer, urls) {
7546
7640
  const linkType = parsed && findObjectLinkType(linkTypes, parsed);
7547
7641
  if (!parsed || !linkType) return [];
7548
7642
  const key = `${viewer.id}:${createHash("sha256").update(url).digest("hex")}`;
7549
- const resolve = () => resolveWithLinkType(linkType, viewer, parsed);
7643
+ const resolve = async () => (await resolveWithLinkType(linkType, viewer, parsed))?.object ?? null;
7550
7644
  try {
7551
7645
  const object = linkType.cacheCards === false ? await resolve() : await cache.getOrLoad(key, async () => ({
7552
7646
  value: await resolve(),
@@ -7577,6 +7671,530 @@ function readHealthReport() {
7577
7671
  function GET() {
7578
7672
  return Response.json(readHealthReport());
7579
7673
  }
7674
+ // src/chat/cache-warming/backfill.ts
7675
+ /**
7676
+ * Fill of the empty cache warming gap lists from stored Conversation
7677
+ * history, about once a month.
7678
+ *
7679
+ * `warmup.ts` learns reply gaps only from idle periods after it is deployed.
7680
+ * Until a `gapSegment` has gaps, Junior sends no warmups for it. This replays
7681
+ * the stored model calls of the last `GLOBAL_GAPS_TTL_MS` with the same rules
7682
+ * as live recording, so warming can start soon after the first deploy.
7683
+ *
7684
+ * The heartbeat runs it. Only one run claims it, and a completed run marks
7685
+ * the install as done, also when it stopped on its time budget or skipped a
7686
+ * batch that the statement timeout canceled. It fills only segment lists
7687
+ * that are empty when it starts, so it does not add history to gaps that
7688
+ * live recording already has.
7689
+ *
7690
+ * History does not tell the plugin work state or the archive state that a
7691
+ * Conversation had when an idle period started. So it fills only the
7692
+ * segments of Conversations that are not archived and have work state
7693
+ * `none`, which most Conversations have. The `open` and `done` segments and
7694
+ * the `archived:*` segments stay empty until live gaps arrive. Until then,
7695
+ * `decideWarmup` leans on their `parentGapSegment`, a `none` segment that
7696
+ * this fills. Each idle period still records its gap, so the segment fills
7697
+ * from live idle periods.
7698
+ */
7699
+ const BACKFILL_KEY = "junior:cache_warming:backfill:work_state:v2";
7700
+ const BACKFILL_CLAIM_TTL_MS = 60 * MINUTE_MS;
7701
+ const BACKFILL_DONE_TTL_MS = GLOBAL_GAPS_TTL_MS;
7702
+ const CONVERSATION_BATCH_SIZE = 10;
7703
+ const CONVERSATION_PAGE_SIZE = 500;
7704
+ const QUERY_CANCELED = "57014";
7705
+ /**
7706
+ * Scan time of one backfill run. The heartbeat gives no deadline. This leaves
7707
+ * most of its function time for the writes and the other heartbeat work.
7708
+ */
7709
+ const BACKFILL_BUDGET_MS = 6e4;
7710
+ const BACKFILL_GAPS_MAX = GLOBAL_GAPS_MAX / 2;
7711
+ const BACKFILL_SEGMENTS = new Set([true, false].flatMap((userActor) => [
7712
+ 0,
7713
+ 1,
7714
+ 2,
7715
+ 3
7716
+ ].map((endedTurns) => historySegment(userActor, endedTurns))));
7717
+ function historySegment(userActor, endedTurns) {
7718
+ return gapSegment({
7719
+ userActor,
7720
+ endedTurns,
7721
+ workState: "none",
7722
+ archived: false
7723
+ });
7724
+ }
7725
+ const inWindow = (windowStartMs) => and(gte(juniorConversations.lastActivityAt, new Date(windowStartMs)), isNull(juniorConversations.transcriptPurgedAt));
7726
+ const conversationColumns = {
7727
+ conversationId: juniorConversations.conversationId,
7728
+ kind: juniorConversations.kind,
7729
+ parentConversationId: juniorConversations.parentConversationId
7730
+ };
7731
+ async function loadConversations(windowStartMs) {
7732
+ return await getDb().select(conversationColumns).from(juniorConversations).where(inWindow(windowStartMs)).orderBy(desc(juniorConversations.lastActivityAt), juniorConversations.conversationId);
7733
+ }
7734
+ async function loadConversationPage(windowStartMs, afterConversationId) {
7735
+ return await getDb().select(conversationColumns).from(juniorConversations).where(and(inWindow(windowStartMs), afterConversationId === void 0 ? void 0 : gt(juniorConversations.conversationId, afterConversationId))).orderBy(juniorConversations.conversationId).limit(CONVERSATION_PAGE_SIZE);
7736
+ }
7737
+ /** Count the Conversations that a history scan from `windowStartMs` reads. */
7738
+ async function countHistoryConversations(windowStartMs) {
7739
+ const [row] = await getDb().select({ count: count() }).from(juniorConversations).where(inWindow(windowStartMs));
7740
+ return row?.count ?? 0;
7741
+ }
7742
+ async function loadEvents(conversationIds) {
7743
+ const events = juniorConversationEvents;
7744
+ const isUserMessage = sql`${events.type} = 'user_message'`;
7745
+ const message = sql`CASE
7746
+ WHEN ${events.type} <> 'assistant_message' THEN NULL
7747
+ WHEN ${events.schemaVersion} >= 2 THEN (${events.payload}->>'message')::jsonb
7748
+ ELSE ${events.payload}
7749
+ END`;
7750
+ return await getDb().select({
7751
+ conversationId: events.conversationId,
7752
+ type: sql`${events.type}`,
7753
+ personInstruction: sql`CASE WHEN ${isUserMessage} THEN (${events.payload}->'provenance'->'actor'->>'userId') IS NOT NULL END`,
7754
+ stopReason: sql`(${message})->>'stopReason'`,
7755
+ startedAtMs: sql`(${message})->>'timestamp'`,
7756
+ modelId: sql`(${message})->>'model'`,
7757
+ cacheRead: sql`${events.payload}->'usage'->>'cacheRead'`,
7758
+ cacheWrite: sql`${events.payload}->'usage'->>'cacheWrite'`
7759
+ }).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);
7760
+ }
7761
+ /**
7762
+ * Replay the model calls of one Conversation the way the recorders in
7763
+ * `warmup.ts` and `tool-wait.ts` see them, and return each idle period and
7764
+ * tool wait. An idle period starts at a `stop` call and a tool wait at a
7765
+ * `toolUse` call, so no pair of calls is in both.
7766
+ *
7767
+ * Live recording measures from the start of the request that ended a Turn to
7768
+ * the start of the next recorded request. Here both times are the
7769
+ * `timestamp` of the stored assistant message, which Pi sets when it starts
7770
+ * the request. That is the closest stored time to the recorder's clock.
7771
+ */
7772
+ function replayConversation(kind, events, nowMs) {
7773
+ const periods = [];
7774
+ const toolWaits = [];
7775
+ const close = (idle, untilMs, next) => {
7776
+ const gapMs = untilMs - idle.sinceMs;
7777
+ if (gapMs <= 0) return;
7778
+ const period = {
7779
+ ...idle,
7780
+ gapMs
7781
+ };
7782
+ if (next) period.next = next;
7783
+ periods.push(period);
7784
+ };
7785
+ let userActor = false;
7786
+ let inTurn = false;
7787
+ let endedTurns = 0;
7788
+ let lastCallMs;
7789
+ let idle;
7790
+ let waiting;
7791
+ for (const event of events) {
7792
+ if (event.type === "user_message") {
7793
+ if (!inTurn) {
7794
+ userActor = event.personInstruction === true && kind !== "task";
7795
+ inTurn = true;
7796
+ }
7797
+ continue;
7798
+ }
7799
+ if (event.stopReason !== "toolUse") inTurn = false;
7800
+ const startedAtMs = event.startedAtMs === null ? NaN : Number(event.startedAtMs);
7801
+ if (!Number.isFinite(startedAtMs)) continue;
7802
+ const next = {
7803
+ modelId: event.modelId,
7804
+ cacheRead: Number(event.cacheRead ?? 0),
7805
+ cacheWrite: Number(event.cacheWrite ?? 0)
7806
+ };
7807
+ if (waiting && startedAtMs > waiting.sinceMs) toolWaits.push({
7808
+ ...waiting,
7809
+ gapMs: startedAtMs - waiting.sinceMs,
7810
+ next
7811
+ });
7812
+ waiting = event.stopReason === "toolUse" ? {
7813
+ sinceMs: startedAtMs,
7814
+ prefixTokens: next.cacheRead + next.cacheWrite
7815
+ } : void 0;
7816
+ if (event.stopReason === "error" || event.stopReason === "aborted") continue;
7817
+ const { cacheRead, cacheWrite } = next;
7818
+ if (idle) close(idle, startedAtMs, next);
7819
+ idle = void 0;
7820
+ if (lastCallMs !== void 0 && startedAtMs - lastCallMs > CONVERSATION_STATE_TTL_MS) endedTurns = 0;
7821
+ lastCallMs = startedAtMs;
7822
+ if (event.stopReason === "stop") {
7823
+ idle = {
7824
+ sinceMs: startedAtMs,
7825
+ segment: historySegment(userActor, endedTurns),
7826
+ prefixTokens: cacheRead + cacheWrite
7827
+ };
7828
+ endedTurns += 1;
7829
+ }
7830
+ }
7831
+ if (idle && nowMs - idle.sinceMs >= 33e5) close(idle, nowMs);
7832
+ return {
7833
+ periods,
7834
+ toolWaits
7835
+ };
7836
+ }
7837
+ function isQueryCanceled(error) {
7838
+ let current = error;
7839
+ for (let depth = 0; current && depth < 6; depth += 1) {
7840
+ if (typeof current !== "object") return false;
7841
+ if (current.code === QUERY_CANCELED) return true;
7842
+ current = current.cause;
7843
+ }
7844
+ return false;
7845
+ }
7846
+ async function replayConversations(conversations, args) {
7847
+ const { windowStartMs, nowMs, budgetMs } = args;
7848
+ const startedAt = performance.now();
7849
+ const periods = [];
7850
+ const toolWaits = [];
7851
+ let scanned = 0;
7852
+ let canceledBatches = 0;
7853
+ let budgetExceeded = false;
7854
+ let lastConversationId;
7855
+ for (let i = 0; i < conversations.length; i += CONVERSATION_BATCH_SIZE) {
7856
+ if (i > 0 && performance.now() - startedAt >= budgetMs) {
7857
+ budgetExceeded = true;
7858
+ break;
7859
+ }
7860
+ const batch = conversations.slice(i, i + CONVERSATION_BATCH_SIZE);
7861
+ lastConversationId = batch.at(-1).conversationId;
7862
+ let rows;
7863
+ try {
7864
+ rows = await loadEvents(batch.map((row) => row.conversationId));
7865
+ } catch (error) {
7866
+ if (!isQueryCanceled(error)) throw error;
7867
+ canceledBatches += 1;
7868
+ continue;
7869
+ }
7870
+ const events = /* @__PURE__ */ new Map();
7871
+ for (const event of rows) {
7872
+ const list = events.get(event.conversationId) ?? [];
7873
+ list.push(event);
7874
+ events.set(event.conversationId, list);
7875
+ }
7876
+ for (const conversation of batch) {
7877
+ const replayed = replayConversation(conversationKindFromRow(conversation), events.get(conversation.conversationId) ?? [], nowMs);
7878
+ const inScanWindow = (period) => period.sinceMs >= windowStartMs;
7879
+ periods.push(...replayed.periods.filter(inScanWindow));
7880
+ toolWaits.push(...replayed.toolWaits.filter(inScanWindow));
7881
+ }
7882
+ scanned += batch.length;
7883
+ }
7884
+ periods.sort((a, b) => a.sinceMs - b.sinceMs);
7885
+ return {
7886
+ periods,
7887
+ toolWaits,
7888
+ scanned,
7889
+ canceledBatches,
7890
+ budgetExceeded,
7891
+ lastConversationId
7892
+ };
7893
+ }
7894
+ /**
7895
+ * Replay the stored history of each Conversation with activity since
7896
+ * `windowStartMs`, newest first, and return its idle periods that started in
7897
+ * the window, oldest first. The scan stops before the next batch when the
7898
+ * budget is used. The budget uses the monotonic clock, not `nowMs`.
7899
+ */
7900
+ async function scanIdlePeriods(args) {
7901
+ const { lastConversationId: _, ...scan } = await replayConversations(await loadConversations(args.windowStartMs), args);
7902
+ return scan;
7903
+ }
7904
+ /**
7905
+ * Replay the next Conversations in id order after `afterConversationId`,
7906
+ * until the budget is used, as `scanIdlePeriods` does. Continue with the
7907
+ * returned `lastConversationId` until the slice is `complete`.
7908
+ */
7909
+ async function scanIdlePeriodSlice(args) {
7910
+ const page = await loadConversationPage(args.windowStartMs, args.afterConversationId);
7911
+ const scan = await replayConversations(page, args);
7912
+ return {
7913
+ ...scan,
7914
+ complete: !scan.budgetExceeded && page.length < CONVERSATION_PAGE_SIZE
7915
+ };
7916
+ }
7917
+ function gapsBySegment(periods) {
7918
+ const bySegment = /* @__PURE__ */ new Map();
7919
+ for (const period of periods) {
7920
+ if (period.prefixTokens < 5e4) continue;
7921
+ const list = bySegment.get(period.segment) ?? [];
7922
+ list.push(period.gapMs >= 33e5 ? NO_REPLY_GAP_MS : period.gapMs);
7923
+ bySegment.set(period.segment, list);
7924
+ }
7925
+ return bySegment;
7926
+ }
7927
+ /**
7928
+ * Fill each empty cache warming gap list from the stored Conversation
7929
+ * history. The heartbeat calls it each minute. After a run completes, a call
7930
+ * makes one state request and returns, until the completed run expires.
7931
+ *
7932
+ * A run that uses its scan budget writes the gaps that it has and also
7933
+ * completes. Some gaps are better than none, and a run that cannot finish
7934
+ * would otherwise try again each hour.
7935
+ */
7936
+ async function backfillCacheWarmingGaps(args) {
7937
+ if (!getChatConfig().cacheWarmingEnabled) return;
7938
+ const state = getStateAdapter();
7939
+ await state.connect();
7940
+ if (!await state.setIfNotExists(BACKFILL_KEY, "running", BACKFILL_CLAIM_TTL_MS)) return;
7941
+ await withSpan("cache_warming.backfill", "cache_warming.backfill", {}, async (setSpanAttributes) => {
7942
+ const emptySegments = /* @__PURE__ */ new Set();
7943
+ for (const segment of BACKFILL_SEGMENTS) if ((await state.getList(segmentGapsKey(segment))).length === 0) emptySegments.add(segment);
7944
+ const { periods, scanned, canceledBatches, budgetExceeded } = await scanIdlePeriods({
7945
+ windowStartMs: args.nowMs - GLOBAL_GAPS_TTL_MS,
7946
+ nowMs: args.nowMs,
7947
+ budgetMs: args.budgetMs ?? 6e4
7948
+ });
7949
+ const bySegment = gapsBySegment(periods);
7950
+ const logAttributes = {
7951
+ "app.cache_warming.backfill.conversation_count": scanned,
7952
+ "app.cache_warming.backfill.canceled_batch_count": canceledBatches,
7953
+ "app.cache_warming.backfill.budget_exceeded": budgetExceeded
7954
+ };
7955
+ if (scanned === 0 && canceledBatches > 0) {
7956
+ logInfo("cache_warming.backfill.not_completed", logAttributes);
7957
+ setSpanAttributes({
7958
+ ...logAttributes,
7959
+ "app.cache_warming.backfill.outcome": "not_completed"
7960
+ });
7961
+ return;
7962
+ }
7963
+ let gapCount = 0;
7964
+ let segmentCount = 0;
7965
+ for (const [segment, gaps] of bySegment) {
7966
+ if (!emptySegments.has(segment)) continue;
7967
+ const key = segmentGapsKey(segment);
7968
+ const newest = gaps.slice(-BACKFILL_GAPS_MAX);
7969
+ for (const gapMs of newest) await state.appendToList(key, gapMs, {
7970
+ maxLength: GLOBAL_GAPS_MAX,
7971
+ ttlMs: GLOBAL_GAPS_TTL_MS
7972
+ });
7973
+ gapCount += newest.length;
7974
+ segmentCount += 1;
7975
+ }
7976
+ await state.set(BACKFILL_KEY, "done", BACKFILL_DONE_TTL_MS);
7977
+ const completed = {
7978
+ ...logAttributes,
7979
+ "app.cache_warming.backfill.gap_count": gapCount,
7980
+ "app.cache_warming.backfill.segment_count": segmentCount
7981
+ };
7982
+ logInfo("cache_warming.backfill.completed", completed);
7983
+ setSpanAttributes({
7984
+ ...completed,
7985
+ "app.cache_warming.backfill.outcome": "completed"
7986
+ });
7987
+ });
7988
+ }
7989
+ // src/chat/cache-warming/savings-refill.ts
7990
+ /**
7991
+ * Re-fill of the cache warming savings counters from stored Conversation
7992
+ * history. A Junior admin starts it from the System page.
7993
+ *
7994
+ * Live recording (`savings.ts`) counts only idle periods and tool waits that
7995
+ * end after it is deployed. A re-fill replays the stored model calls of the
7996
+ * last `REFILL_DAYS` with the same rules into the days before the first day
7997
+ * with live counters. It replaces those days, so a second re-fill does not
7998
+ * add to the first. It never writes a live day: live days have data that
7999
+ * history does not, the real warmup cost and the warm state split.
8000
+ *
8001
+ * The start request only stores a pending job. The heartbeat runs one slice
8002
+ * of the scan each minute, with a time budget. Each slice keeps its sums and
8003
+ * the scan position in the job with one state write, so a retried slice does
8004
+ * not count twice. The last slice replaces the days in one transaction. A
8005
+ * job whose lease expires, because its slices stopped or kept failing, is
8006
+ * failed, and an admin can start a new one.
8007
+ */
8008
+ const JOB_KEY = "junior:cache_warming:savings_refill:v1";
8009
+ const SLICE_LOCK_KEY = "junior:cache_warming:savings_refill:v1:slice";
8010
+ const SLICE_LOCK_TTL_MS = 5 * MINUTE_MS;
8011
+ const START_LOCK_KEY = "junior:cache_warming:savings_refill:v1:start";
8012
+ const START_LOCK_TTL_MS = MINUTE_MS;
8013
+ const LEASE_MS = 10 * MINUTE_MS;
8014
+ const MAX_JOB_AGE_MS = 360 * MINUTE_MS;
8015
+ const JOB_TTL_MS = 129600 * MINUTE_MS;
8016
+ const REFILL_DAYS = 90;
8017
+ const DAY_MS = 1440 * MINUTE_MS;
8018
+ const SLICE_BUDGET_MS = BACKFILL_BUDGET_MS / 2;
8019
+ const STOPPED_ERROR = "The re-fill stopped before it finished.";
8020
+ const CANCELED_ERROR = "The history queries timed out.";
8021
+ const refillJobSchema = z.object({
8022
+ id: z.string(),
8023
+ status: z.enum([
8024
+ "pending",
8025
+ "running",
8026
+ "done",
8027
+ "failed"
8028
+ ]),
8029
+ startedAtMs: z.number(),
8030
+ finishedAtMs: z.number().optional(),
8031
+ error: z.string().optional(),
8032
+ leaseExpiresAtMs: z.number(),
8033
+ windowStartMs: z.number(),
8034
+ /** First day with live counters. The job writes only days before it. */
8035
+ liveStartDate: z.string(),
8036
+ afterConversationId: z.string().optional(),
8037
+ scannedConversations: z.number(),
8038
+ totalConversations: z.number(),
8039
+ /** Sums of the slices so far, per day and model. */
8040
+ sums: z.record(z.string(), z.record(z.string(), z.record(z.string(), z.number())))
8041
+ }).strict();
8042
+ const utcDate = (ms) => new Date(ms).toISOString().slice(0, 10);
8043
+ const isoTime = (ms) => ms === void 0 ? void 0 : new Date(ms).toISOString();
8044
+ const isActive = (job) => job.status === "pending" || job.status === "running";
8045
+ const isStopped = (job, nowMs) => isActive(job) && (job.leaseExpiresAtMs <= nowMs || nowMs - job.startedAtMs > MAX_JOB_AGE_MS);
8046
+ async function readJob() {
8047
+ const stored = await (await connectedState()).get(JOB_KEY);
8048
+ return stored === null ? void 0 : refillJobSchema.parse(stored);
8049
+ }
8050
+ function toStatus(job, nowMs) {
8051
+ if (!job) return { status: "idle" };
8052
+ const stopped = isStopped(job, nowMs);
8053
+ return {
8054
+ status: stopped ? "failed" : job.status,
8055
+ startedAt: isoTime(job.startedAtMs),
8056
+ finishedAt: isoTime(job.finishedAtMs),
8057
+ error: stopped ? job.error ?? STOPPED_ERROR : job.error,
8058
+ scannedConversations: job.scannedConversations,
8059
+ totalConversations: job.totalConversations
8060
+ };
8061
+ }
8062
+ /** Read the state of the last savings re-fill. */
8063
+ async function readSavingsRefill(nowMs = Date.now()) {
8064
+ return toStatus(await readJob(), nowMs);
8065
+ }
8066
+ /**
8067
+ * Start a savings re-fill. Return `started: false` and the current state
8068
+ * when a job is still pending or running.
8069
+ */
8070
+ async function startSavingsRefill(nowMs = Date.now()) {
8071
+ const state = await connectedState();
8072
+ if (!await state.setIfNotExists(START_LOCK_KEY, true, START_LOCK_TTL_MS)) return {
8073
+ started: false,
8074
+ refill: await readSavingsRefill(nowMs)
8075
+ };
8076
+ try {
8077
+ const current = await readJob();
8078
+ if (current && isActive(current) && !isStopped(current, nowMs)) return {
8079
+ started: false,
8080
+ refill: toStatus(current, nowMs)
8081
+ };
8082
+ const windowStartMs = Date.parse(utcDate(nowMs - REFILL_DAYS * DAY_MS));
8083
+ const job = {
8084
+ id: randomUUID(),
8085
+ status: "pending",
8086
+ startedAtMs: nowMs,
8087
+ leaseExpiresAtMs: nowMs + LEASE_MS,
8088
+ windowStartMs,
8089
+ liveStartDate: await firstLiveSavingsDate() ?? utcDate(nowMs),
8090
+ scannedConversations: 0,
8091
+ totalConversations: await countHistoryConversations(windowStartMs),
8092
+ sums: {}
8093
+ };
8094
+ await state.set(JOB_KEY, job, JOB_TTL_MS);
8095
+ logInfo("cache_warming.savings_refill.started", { "app.cache_warming.backfill.conversation_count": job.totalConversations });
8096
+ return {
8097
+ started: true,
8098
+ refill: toStatus(job, nowMs)
8099
+ };
8100
+ } finally {
8101
+ await state.delete(START_LOCK_KEY);
8102
+ }
8103
+ }
8104
+ function addPeriod(job, period) {
8105
+ const modelId = period.next.modelId;
8106
+ if (!modelId) return;
8107
+ const ttlMs = providerCacheTtlMs(modelId);
8108
+ if (ttlMs === void 0) return;
8109
+ let cost;
8110
+ try {
8111
+ cost = resolveGatewayModel(modelId).cost;
8112
+ } catch {
8113
+ return;
8114
+ }
8115
+ const savings = idlePeriodSavings({
8116
+ cacheTtlMs: ttlMs,
8117
+ gapMs: period.gapMs,
8118
+ prefixTokens: period.prefixTokens,
8119
+ cacheRead: period.next.cacheRead,
8120
+ cacheWrite: period.next.cacheWrite,
8121
+ cacheReadPrice: cost.cacheRead,
8122
+ cacheWritePrice: cost.cacheWrite
8123
+ });
8124
+ if (savings) addHistoryPeriod(job.sums, period.sinceMs + period.gapMs, modelId, savings);
8125
+ }
8126
+ /**
8127
+ * Run the next slice of a pending or running savings re-fill. The heartbeat
8128
+ * calls it each minute. With no job to run, it makes one state request.
8129
+ */
8130
+ async function runSavingsRefillSlice(args) {
8131
+ const { nowMs } = args;
8132
+ const job = await readJob();
8133
+ if (!job || !isActive(job)) return;
8134
+ const state = await connectedState();
8135
+ if (isStopped(job, nowMs)) return;
8136
+ if (!await state.setIfNotExists(SLICE_LOCK_KEY, job.id, SLICE_LOCK_TTL_MS)) return;
8137
+ try {
8138
+ await withSpan("cache_warming.savings_refill.slice", "cache_warming.backfill", {}, async (setSpanAttributes) => {
8139
+ const range = {
8140
+ start: utcDate(job.windowStartMs),
8141
+ end: job.liveStartDate
8142
+ };
8143
+ const scan = range.start < range.end ? await scanIdlePeriodSlice({
8144
+ windowStartMs: job.windowStartMs,
8145
+ nowMs,
8146
+ budgetMs: args.budgetMs ?? SLICE_BUDGET_MS,
8147
+ afterConversationId: job.afterConversationId
8148
+ }) : void 0;
8149
+ for (const period of scan?.periods ?? []) if (period.next) addPeriod(job, {
8150
+ ...period,
8151
+ next: period.next
8152
+ });
8153
+ for (const toolWait of scan?.toolWaits ?? []) addPeriod(job, toolWait);
8154
+ if ((await readJob())?.id !== job.id) return;
8155
+ const next = {
8156
+ ...job,
8157
+ status: "running",
8158
+ leaseExpiresAtMs: nowMs + LEASE_MS,
8159
+ afterConversationId: scan?.lastConversationId ?? job.afterConversationId,
8160
+ scannedConversations: job.scannedConversations + (scan?.scanned ?? 0)
8161
+ };
8162
+ delete next.error;
8163
+ const complete = scan?.complete ?? true;
8164
+ if (scan && complete && next.scannedConversations === 0 && job.totalConversations > 0) Object.assign(next, {
8165
+ status: "failed",
8166
+ finishedAtMs: nowMs,
8167
+ error: CANCELED_ERROR,
8168
+ sums: {}
8169
+ });
8170
+ else if (complete) {
8171
+ await replaceHistorySavings(job.sums, range);
8172
+ Object.assign(next, {
8173
+ status: "done",
8174
+ finishedAtMs: nowMs,
8175
+ sums: {}
8176
+ });
8177
+ }
8178
+ await state.set(JOB_KEY, next, JOB_TTL_MS);
8179
+ const attributes = {
8180
+ "app.cache_warming.backfill.conversation_count": scan?.scanned ?? 0,
8181
+ "app.cache_warming.backfill.canceled_batch_count": scan?.canceledBatches ?? 0,
8182
+ "app.cache_warming.backfill.outcome": complete ? "completed" : "continued"
8183
+ };
8184
+ setSpanAttributes(attributes);
8185
+ if (complete) logInfo("cache_warming.savings_refill.completed", attributes);
8186
+ });
8187
+ } catch (error) {
8188
+ const current = await readJob();
8189
+ if (current?.id === job.id) await state.set(JOB_KEY, {
8190
+ ...current,
8191
+ error: error instanceof Error ? error.message : String(error)
8192
+ }, JOB_TTL_MS);
8193
+ throw error;
8194
+ } finally {
8195
+ await state.delete(SLICE_LOCK_KEY);
8196
+ }
8197
+ }
7580
8198
  // src/chat/conversations/sql/authorization-wait.ts
7581
8199
  /**
7582
8200
  * How long a person can finish an authorization. The MCP auth session and the
@@ -10858,4 +11476,4 @@ function viewerWebMessages(messages, viewer) {
10858
11476
  }] : [];
10859
11477
  });
10860
11478
  }
10861
- export { decodeImageId as $, resolveAllowedDomains as A, runAutoArchiveSweep as B, readConversationPendingMessages as C, isAllowedDomain as D, assertNoLegacyAllowedDomains as E, readReviewItemForUser as F, OBJECT_LINK_TTL_MS as G, updateUserAutoArchiveSettings as H, reviewItemChange as I, resolveObjectLinks as J, readObjectLinkTypes as K, DEFAULT_AUTO_ARCHIVE_SETTINGS as L, ReviewItemActionError as M, actOnReviewItem as N, isAllowedSignInEmail as O, closeReviewItemsAnsweredByReply as P, IMAGE_WIDTHS as Q, archiveViewerDoneConversations as R, cancelConversationPendingMessagesForViewer as S, resolveMentions as T, GET as U, setConversationAutoArchive as V, readHealthReport as W, isPublicAddress as X, guardedFetch as Y, publicAddressLookup as Z, appendConversationMessageForViewer as _, SubscribedReplyReason as _t, pinConversation as a, slackInboundMessageId as at, decodeConversationCursor as b, readFirstHumanMessageTexts as bt, readConversationAuxiliaryCostsFromSql as c, AGENT_DISPATCH_MAX_AGE_MS as ct, conversationVersionQuery as d, recordSkippedConversationMessage as dt, createProductionConversationWorkOptions as et, readConversationDetailEtag as f, createSlackWebApiStatusSender as ft, readConversationRecordFromSql as g, parseContent as gt, readConversationEvents as h, stripLeadingBotMention as ht, readConversationFeed as i, clearSlackPendingReactions as it, stopConversation as j, readEnvList as k, childAgentTotalsReport as l, enqueueAgentDispatch as lt, keepQuickQuestionForViewer as m, startProcessingReaction as mt, steerConversationPendingMessagesForViewer as n, getProductionSlackAdapter as nt, reorderPinnedConversations as o, normalizeIncomingSlackThreadId as ot, forkConversationForViewer as p, bindMessageAuthorIdentityId as pt, resolveObjectLinkNow as q, conversationFeedVersionQuery as r, buildSlackInboundMessage as rt, readConversationDetail as s, withNormalizedThreadId as st, stopConversationTurnForViewer as t, createProductionSlackWebhookServices as tt, readConversationTreeMetricsFromSql as u, failStoppedDispatch as ut, createConversationForViewer as v, getThreadStopDecision as vt, requireConversationPendingMessages as w, encodeConversationCursor as x, requireWebMessageConversation as y, conversationSummaryFromStoredConversation as yt, readUserAutoArchiveSettings as z };
11479
+ export { guardedFetch as $, resolveAllowedDomains as A, runAutoArchiveSweep as B, readConversationPendingMessages as C, createViewerMcp as Ct, isAllowedDomain as D, assertNoLegacyAllowedDomains as E, readReviewItemForUser as F, startSavingsRefill as G, updateUserAutoArchiveSettings as H, reviewItemChange as I, readHealthReport as J, backfillCacheWarmingGaps as K, DEFAULT_AUTO_ARCHIVE_SETTINGS as L, ReviewItemActionError as M, actOnReviewItem as N, isAllowedSignInEmail as O, closeReviewItemsAnsweredByReply as P, resolveObjectLinks as Q, archiveViewerDoneConversations as R, cancelConversationPendingMessagesForViewer as S, readFirstHumanMessageTexts as St, resolveMentions as T, decodeImageId as Tt, readSavingsRefill as U, setConversationAutoArchive as V, runSavingsRefillSlice as W, readObjectLinkTypes as X, OBJECT_LINK_TTL_MS as Y, resolveObjectLinkNow as Z, appendConversationMessageForViewer as _, stripLeadingBotMention as _t, pinConversation as a, buildSlackInboundMessage as at, decodeConversationCursor as b, getThreadStopDecision as bt, readConversationAuxiliaryCostsFromSql as c, normalizeIncomingSlackThreadId as ct, conversationVersionQuery as d, enqueueAgentDispatch as dt, isPublicAddress as et, readConversationDetailEtag as f, failStoppedDispatch as ft, readConversationRecordFromSql as g, startProcessingReaction as gt, readConversationEvents as h, bindMessageAuthorIdentityId as ht, readConversationFeed as i, getProductionSlackAdapter as it, stopConversation as j, readEnvList as k, childAgentTotalsReport as l, withNormalizedThreadId as lt, keepQuickQuestionForViewer as m, createSlackWebApiStatusSender as mt, steerConversationPendingMessagesForViewer as n, createProductionConversationWorkOptions as nt, reorderPinnedConversations as o, clearSlackPendingReactions as ot, forkConversationForViewer as p, recordSkippedConversationMessage as pt, GET as q, conversationFeedVersionQuery as r, createProductionSlackWebhookServices as rt, readConversationDetail as s, slackInboundMessageId as st, stopConversationTurnForViewer as t, publicAddressLookup as tt, readConversationTreeMetricsFromSql as u, AGENT_DISPATCH_MAX_AGE_MS as ut, createConversationForViewer as v, parseContent as vt, requireConversationPendingMessages as w, IMAGE_WIDTHS as wt, encodeConversationCursor as x, conversationSummaryFromStoredConversation as xt, requireWebMessageConversation as y, SubscribedReplyReason as yt, readUserAutoArchiveSettings as z };