@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
@@ -1,50 +1,189 @@
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";
1
+ import { $ as loadTurnCheckpoint, A as latestConversationMessageSeq, Aa as removeReactionFromMessage, Bi as parseDashboardPersonLink, Br as takeReviewItem, Ca as addReactionToMessage, Co as readConversationAccessFromSql, Cs as createPluginCache, D as estimateConversationMessagesTokens, Do as conversationPinnedForUser, Ds as piMessageFromHistoryItem, E as buildConversationContext, Eo as conversationIsNotUnsubscribedRoot, F as turnHasReply, Fo as readConversationEventPageAround, H as PluginCredentialFailureError, Ho as getSlackFileId, Ht as releaseInboundMessage, I as upsertConversationMessage, Ir as listReplyActionItems, Jo as SlackActionError, K as AuthorizationFlowDisabledError, Ko as recordSlackAttachment, Kr as canUserReadReviewItem, Ln as trimTrailingAssistantMessages, Lr as listWaitingConversations, M as normalizeConversationText, Mi as getDashboardLinkFilter, Mo as readLatestConversationBrief, N as recordDeliveredAssistantMessage, No as readConversationEventPage, O as getConversationMessageSlackTs, Oo as conversationViewerMarks, P as trimConversationMessages, Pi as getDashboardPersonLink, Po as readConversationEventPageAfter, Pr as getReviewItem, Qo as getSlackClient, Qr as reviewItemNeedsSomeone, Ri as isDashboardLink, Ro as buildSentryConversationUrl, S as resolveConversationTitle, Sa as truncateStatusText, So as createConversationAccessReader, To as conversationIsMemberRoot, Ts as configValueSchema, Ur as canActOnReviewItem, V as createPluginEgress, Vo as notInheritedByForkChild, Wo as readAttachmentVisionSummary, X as clearPendingAuth, Yo as downloadPrivateSlackFile, Zn as createUserTokenStore, Zo as getHeaderString, a as loadProjection, as as withSlackRetries, at as failTurnRecord, b as persistConversationMessages, ba as slackMentionedUserIds, bn as persistWithRetry, bs as lookupSlackUserNames, ct as listTurnSummaries, d as recordAuthorizationCompleted, es as isDmChannel, et as lostWorkerBeforeFirstSave, fa as resolveBaseUrl, gs as listConversationAnnotationsById, h as recordSubscribedReplyRoute, hs as listConversationAnnotations, i as loadConversationProjection, is as streamPrivateSlackFile, it as completeTurnRecord, j as markConversationMessage, ji as getDashboardConversationLink, k as isHumanConversationMessage, ko as viewerMarksFromParticipant, kr as closeReviewItem, lt as recordTurnSummary, ma as SLACK_USER_MENTION_RE, n as commitMessages, ns as normalizeSlackConversationId, nt as saveTurnCheckpoint, o as loadTurnProjection, pi as cancelSubscriptions, qo as slackAttachmentsVersionQuery, qr as isOnlyAssignee, rt as abandonTurnRecord, st as getTurnRecord, t as commitAcceptedReply, tn as buildTurnErrorResponse, tr as applyPluginFormatMarkdown, ts as isSlackRequestTimeout, tt as pauseLostWorkerTurn, un as getAssistantReplyText, ur as getPlugins, v as hydrateConversationMessages, va as normalizeSlackStatusText, w as fallbackShortTitle, wo as conversationHasParticipantUser, xa as wrapBareSlackUserIds, xo as canAddConversationMessages, y as persistConversationMessageWindow, yo as createPluginLogger, ys as lookupSlackUser, zi as parseDashboardConversationLink } from "./projection-DBq8tsA5.js";
2
+ 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-oGM7KA9M.js";
3
+ 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-DiyqRLBx.js";
4
+ import { h as startSpan } from "./sentry-CPbZjomA.js";
5
+ import { t as JUNIOR_VERSION } from "./version-Uo3c94Dx.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";
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";
15
- import { G as MAX_ATTACHMENT_BYTES, Y as readMessageAttachments, f as conversationEventPageSchema, u as conversationDetailReportSchema } from "./conversation-BNXfq6Lb.js";
16
- 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";
7
+ import { D as turnBehavior, 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-C-2tFxk3.js";
8
+ import { D as juniorConversationAnnotations, F as juniorDestinations, M as juniorConversations, N as juniorIdentities, O as juniorCodeChanges, P as juniorUsers, T as juniorConversationEvents, g as juniorAgentInvocations, l as juniorReviewItems, s as juniorReviewItemConversations, v as juniorConversationParticipants, x as juniorConversationBriefs } from "./executor-NVfS8aQ2.js";
9
+ import { d as contextProvenance, p as instructionProvenanceFor, t as KNOWN_CONVERSATION_EVENT_TYPES } from "./history-UZ3M2M9r.js";
10
+ import { d as actorLogContext, f as credentialContextForActor } from "./registry-Bu0Z9BEO.js";
11
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-d1EM6Z0V.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-BP8_DLUv.js";
13
+ import { d as PluginMcpClient, u as McpAuthorizationRequiredError, v as getMcpStoredOAuthCredentials } from "./service-account-BcT5LR7V.js";
14
+ import { i as webActorUserIds } from "./state-CDS6h_Wv.js";
15
+ import { a as EVENT_SYSTEM_ACTOR, c as completeDecision, o as isEventConversationMessage, u as completeText } from "./prompt-D2KlJopL.js";
16
+ import { f as identityAvatarUrl, g as userAvatarUrlsFromIdentities, h as readUserAvatarUrls } from "./viewer-BPQHMx3-.js";
17
+ import { G as MAX_ATTACHMENT_BYTES, Y as readMessageAttachments, f as conversationEventPageSchema, u as conversationDetailReportSchema } from "./conversation-CY1jnBiC.js";
18
+ import { t as readJuniorSecret } from "./secrets-DHaJ5TTn.js";
19
+ 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-BLLp1IP_.js";
20
+ import { $n as renderAttachmentText, At as verifyAttachmentUploads, Ct as createConversationId, Dt as AttachmentUploadError, Fi as NO_REPLY_GAP_MS, Ft as storeAttachment, Gn as AgentRunError, Ii as gapSegment, In as wakePausedTurn, Kn as executeTurn, Ln as getTurnAuthorization, Mn as supersedeTurnForInput, Ni as MINUTE_MS, Nn as createPausedTurns, Pn as getPausedTurnRequest, Rn as canJoinTurn, Sr as isPublicSlackChannel, St as createAndEnqueueConversation, Tt as webActorFromUser, Wn as getWebAuthorization, Zn as throwApiError, _n as dropOwnUnreadLoopReplies, bn as cancelSignInWait, br as getConversationInfo, bt as appendAndEnqueueWebMessage, c as isConversationWorkDone, ct as readLastUserMessageAtByConversation, d as addHistoryPeriod, dr as readSlackRawMessageContext, er as renderBlockText, f as firstLiveSavingsDate, fr as resolveSlackChannelIdFromMessage, gt as deliverReviewItemChange, i as GLOBAL_GAPS_TTL_MS, l as listConversationWork, m as replaceHistorySavings, n as CONVERSATION_STATE_TTL_MS, o as segmentGapsKey, p as idlePeriodSavings, pi as readConversationSourceTask, pr as resolveSlackChannelIdFromThreadId, qt as getChildAgentLabel, r as GLOBAL_GAPS_MAX, t as ANSWER_TOOL_ENDINGS, tr as parseSlackMessageReference, ur as parseSlackThreadId, ut as conversationReadPositionQuery, v as connectedState, vn as stopChildAgentsBelow, wr as listThreadReplies, wt as recordWebConversationActivity, xr as isConversationMember, y as providerCacheTtlMs, yn as stopChildAgentsOf, yr as getChannelMessage, yt as acceptsWebMessages, zn as canShareTurn } from "./warmup-H8uLvW9e.js";
21
+ 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-DGvn9MSl.js";
22
+ import { h as isVisionImageMediaType, l as isEmptyUserInputAnswer, m as detectImageMediaType, t as webMessageId, u as normalizeUserInputAnswer } from "./web-message-id-lNodcCOI.js";
23
+ 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-19CkuUvM.js";
24
+ import { o as getVercelConversationWorkQueue, p as getTurnRequestDeadline } from "./background-compaction-queue-xaE05jxH.js";
25
+ 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-Dgs7Oe44.js";
26
+ import { t as runWithSlackInstallation } from "./adapter-context-BdVnSuY5.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-BZJRk6UV.js";
28
+ import { c as withTurnSpan, n as createConversationTurnWorker, o as getTurnInputSpanAttributes, r as canPauseConversationDelivery, s as turnInputTelemetry } from "./conversation-turn-DAhRdX4m.js";
29
+ import { n as buildStoredAttachmentPromptText } from "./model-input-DmoPPtPE.js";
30
+ import { i as enqueueAgentInvocationResult, n as createDeliverToParent, s as withAgentInvocationResultActors, t as createChildConversationWorker } from "./result-DpiNseDA.js";
31
+ import { t as bindMessageAgent } from "./message-CkCOcbFH.js";
32
+ import { t as readConversationLineage } from "./lineage-HGLhd_-N.js";
33
+ import { t as bindSpawnAgent } from "./spawn-cGasWW33.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-BPky1KBe.js";
35
+ import { n as scheduleSessionCompletedPluginTasks } from "./task-runner-BGXF7Fo7.js";
36
+ import { r as canContinueInSlack } from "./continue-in-slack-BZnYifiG.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.
@@ -195,7 +334,7 @@ function slackChannelTypeFromConversationInfo(info) {
195
334
  function resolveSlackChannelTypeFromMessage(message) {
196
335
  const raw = message.raw;
197
336
  if (!raw || typeof raw !== "object") return;
198
- const channelType = raw.channel_type;
337
+ const channelType = raw["channel_type"];
199
338
  return typeof channelType === "string" ? toSlackEventChannelType(channelType.trim()) : void 0;
200
339
  }
201
340
  /** Build Slack conversation facts available to runtime consumers. */
@@ -480,6 +619,10 @@ async function resolveConversationLink(viewer, url) {
480
619
  });
481
620
  }
482
621
  // src/api/objects/link-types.ts
622
+ /** A link type name for errors, such as `github/task/code_change`. */
623
+ function linkTypeName(linkType) {
624
+ return `${linkType.owner}/${linkType.objectTypes.join("/")}`;
625
+ }
483
626
  function compareSpecificity(left, right) {
484
627
  for (let index = 0; index < left.length; index += 1) {
485
628
  const difference = (left[index] ?? 0) - (right[index] ?? 0);
@@ -506,7 +649,7 @@ function assertNoObjectLinkConflicts(linkTypes) {
506
649
  filter,
507
650
  linkType
508
651
  })));
509
- for (const [index, left] of filters.entries()) for (const right of filters.slice(index + 1)) if (left.linkType !== right.linkType && compareSpecificity(objectLinkFilterSpecificity(left.filter), objectLinkFilterSpecificity(right.filter)) === 0 && filtersOverlap(left.filter, right.filter)) throw new Error(`Link types "${left.linkType.owner}/${left.linkType.objectType}" and "${right.linkType.owner}/${right.linkType.objectType}" claim the same URLs with equal filters.`);
652
+ for (const [index, left] of filters.entries()) for (const right of filters.slice(index + 1)) if (left.linkType !== right.linkType && compareSpecificity(objectLinkFilterSpecificity(left.filter), objectLinkFilterSpecificity(right.filter)) === 0 && filtersOverlap(left.filter, right.filter)) throw new Error(`Link types "${linkTypeName(left.linkType)}" and "${linkTypeName(right.linkType)}" claim the same URLs with equal filters.`);
510
653
  }
511
654
  /** Return the link type whose most specific filter claims the URL. */
512
655
  function findObjectLinkType(linkTypes, url) {
@@ -1028,11 +1171,11 @@ function replaceTopLevelText(content, text) {
1028
1171
  }
1029
1172
  function readRawBlocks(raw) {
1030
1173
  if (!raw || typeof raw !== "object") return void 0;
1031
- return raw.blocks;
1174
+ return raw["blocks"];
1032
1175
  }
1033
1176
  function readRawText(raw) {
1034
1177
  if (!raw || typeof raw !== "object") return "";
1035
- const text = raw.text;
1178
+ const text = raw["text"];
1036
1179
  return typeof text === "string" ? text : "";
1037
1180
  }
1038
1181
  const slackFormat = new SlackFormatConverter();
@@ -1065,7 +1208,7 @@ function renderSlackPlainText(mrkdwn, userNames) {
1065
1208
  function renderTopLevelText(message) {
1066
1209
  const blocks = readRawBlocks(message.raw);
1067
1210
  const blockText = renderBlockText(blocks);
1068
- if (Array.isArray(blocks) && blocks.some((block) => block?.type === "section") && blockText) return blockText;
1211
+ if (Array.isArray(blocks) && blocks.some((block) => isRecord(block) && block["type"] === "section") && blockText) return blockText;
1069
1212
  const rawText = readRawText(message.raw);
1070
1213
  if (rawText.trim()) return renderSlackMrkdwn(rawText);
1071
1214
  if (message.formatted.children.length > 0) return stringifyMarkdown(message.formatted).trim();
@@ -1176,7 +1319,7 @@ function logProcessingReactionFailure(error, eventName, attributes) {
1176
1319
  }
1177
1320
  /** Return true when a Slack reaction tool invocation keeps the processing reaction. */
1178
1321
  function shouldKeepProcessingReactionForToolInvocation(input) {
1179
- return input.toolName === "addReaction" && isProcessingReactionEmoji(input.params.emoji);
1322
+ return input.toolName === "addReaction" && isProcessingReactionEmoji(input.params["emoji"]);
1180
1323
  }
1181
1324
  /** Start Junior's automatic Slack processing reaction for one inbound message. */
1182
1325
  async function startProcessingReaction(args) {
@@ -1709,7 +1852,7 @@ function createSlackTurnRuntime(deps) {
1709
1852
  }
1710
1853
  const eventId = classifiedFailure?.eventId ?? withLogContext(failureLogContext, () => logException(failureCause, "mention.handler.failed"));
1711
1854
  if (!acked && hooks.isFinalAttempt === false) return;
1712
- if (!eventId) throw new Error("Sentry did not return an event ID for mention.handler.failed");
1855
+ if (!eventId) throw new Error("Sentry did not return an event ID for mention.handler.failed", { cause: error });
1713
1856
  let lifecycleError;
1714
1857
  try {
1715
1858
  await failConversationTurn({
@@ -2001,7 +2144,7 @@ function createSlackTurnRuntime(deps) {
2001
2144
  }
2002
2145
  const eventId = classifiedFailure?.eventId ?? withLogContext(failureLogContext, () => logException(failureCause, "subscribed_message.handler.failed"));
2003
2146
  if (!acked && hooks.isFinalAttempt === false) return;
2004
- if (!eventId) throw new Error("Sentry did not return an event ID for subscribed_message.handler.failed");
2147
+ if (!eventId) throw new Error("Sentry did not return an event ID for subscribed_message.handler.failed", { cause: error });
2005
2148
  let lifecycleError;
2006
2149
  try {
2007
2150
  await failConversationTurn({
@@ -2638,7 +2781,7 @@ function createJuniorRuntimeServices(overrides = {}) {
2638
2781
  function getMessageTimestamp(message) {
2639
2782
  const idTs = parseSlackMessageTs(message.id);
2640
2783
  if (idTs) return idTs;
2641
- if (message.raw && typeof message.raw === "object") return parseSlackMessageTs(message.raw.ts);
2784
+ if (message.raw && typeof message.raw === "object") return parseSlackMessageTs(message.raw["ts"]);
2642
2785
  }
2643
2786
  // src/chat/slack/action-token.ts
2644
2787
  const slackActionTokenSchema = z.string().trim().min(1).brand();
@@ -3822,7 +3965,7 @@ function createSlackTurn(deps) {
3822
3965
  status.update({ text: event.text });
3823
3966
  return;
3824
3967
  }
3825
- if (event.type === "tool_started") await options.onToolInvocation?.({
3968
+ if (event.type === "tool_started") options.onToolInvocation?.({
3826
3969
  params: event.params,
3827
3970
  toolName: event.toolName
3828
3971
  });
@@ -4157,13 +4300,13 @@ function visionCacheKey(conversationId) {
4157
4300
  return `vision-cache:v${VISION_CACHE_SCHEMA_VERSION}:${conversationId}`;
4158
4301
  }
4159
4302
  function coerceVisionCache(value) {
4160
- if (!isRecord(value) || value.schemaVersion !== VISION_CACHE_SCHEMA_VERSION) return { byFileId: {} };
4161
- const rawByFileId = isRecord(value.byFileId) ? value.byFileId : {};
4303
+ if (!isRecord(value) || value["schemaVersion"] !== VISION_CACHE_SCHEMA_VERSION) return { byFileId: {} };
4304
+ const rawByFileId = isRecord(value["byFileId"]) ? value["byFileId"] : {};
4162
4305
  const byFileId = {};
4163
4306
  for (const [fileId, rawSummary] of Object.entries(rawByFileId)) {
4164
4307
  if (!fileId.trim() || !isRecord(rawSummary)) continue;
4165
- const summary = toOptionalString(rawSummary.summary);
4166
- const analyzedAtMs = toOptionalNumber(rawSummary.analyzedAtMs);
4308
+ const summary = toOptionalString(rawSummary["summary"]);
4309
+ const analyzedAtMs = toOptionalNumber(rawSummary["analyzedAtMs"]);
4167
4310
  if (!summary || analyzedAtMs === void 0) continue;
4168
4311
  byFileId[fileId] = {
4169
4312
  summary,
@@ -4171,7 +4314,7 @@ function coerceVisionCache(value) {
4171
4314
  };
4172
4315
  }
4173
4316
  return {
4174
- backfillCompletedAtMs: toOptionalNumber(value.backfillCompletedAtMs),
4317
+ backfillCompletedAtMs: toOptionalNumber(value["backfillCompletedAtMs"]),
4175
4318
  byFileId
4176
4319
  };
4177
4320
  }
@@ -4482,7 +4625,10 @@ async function projectDispatchTurnResult(dispatchId, result) {
4482
4625
  case "failed":
4483
4626
  await markDispatchFailed(dispatchId, result.errorMessage ?? "Agent turn failed", result.resultMessageTs);
4484
4627
  break;
4485
- case "completed": await markDispatchCompleted(dispatchId, result.resultMessageTs);
4628
+ case "completed":
4629
+ await markDispatchCompleted(dispatchId, result.resultMessageTs);
4630
+ break;
4631
+ case void 0:
4486
4632
  }
4487
4633
  }
4488
4634
  function getDispatchBlockingError(error) {
@@ -4829,8 +4975,8 @@ function normalizeIncomingSlackThreadId(threadId, message) {
4829
4975
  if (!message || typeof message !== "object") return threadId;
4830
4976
  const raw = message.raw;
4831
4977
  if (!raw || typeof raw !== "object") return threadId;
4832
- const channelId = nonEmptyString(raw.channel);
4833
- const threadTs = nonEmptyString(raw.thread_ts) ?? nonEmptyString(raw.ts);
4978
+ const channelId = nonEmptyString(raw["channel"]);
4979
+ const threadTs = nonEmptyString(raw["thread_ts"]) ?? nonEmptyString(raw["ts"]);
4834
4980
  if (!channelId || !threadTs) return threadId;
4835
4981
  return `slack:${channelId}:${threadTs}`;
4836
4982
  }
@@ -4874,7 +5020,7 @@ function hasValidMdastBase(node, fields) {
4874
5020
  "type",
4875
5021
  ...fields
4876
5022
  ]);
4877
- return Object.keys(node).every((key) => allowed.has(key)) && (node.data === void 0 || typeof node.data === "object" && node.data !== null && !Array.isArray(node.data)) && (node.position === void 0 || mdastPositionSchema.safeParse(node.position).success);
5023
+ return Object.keys(node).every((key) => allowed.has(key)) && (node["data"] === void 0 || typeof node["data"] === "object" && node["data"] !== null && !Array.isArray(node["data"])) && (node["position"] === void 0 || mdastPositionSchema.safeParse(node["position"]).success);
4878
5024
  }
4879
5025
  const mdastPhrasingTypes = /* @__PURE__ */ new Set([
4880
5026
  "break",
@@ -4906,24 +5052,24 @@ const mdastListItemTypes = /* @__PURE__ */ new Set(["listItem"]);
4906
5052
  const mdastTableCellTypes = /* @__PURE__ */ new Set(["tableCell"]);
4907
5053
  const mdastTableRowTypes = /* @__PURE__ */ new Set(["tableRow"]);
4908
5054
  function hasMdastChildren(node, allowedTypes) {
4909
- return Array.isArray(node.children) && node.children.every((child) => isFormattedContentNode(child) && (!allowedTypes || typeof child === "object" && child !== null && !Array.isArray(child) && allowedTypes.has(String(child.type))));
5055
+ return Array.isArray(node["children"]) && node["children"].every((child) => isFormattedContentNode(child) && (!allowedTypes || typeof child === "object" && child !== null && !Array.isArray(child) && allowedTypes.has(String(child.type))));
4910
5056
  }
4911
5057
  /** Validate every supported mdast node before restoring a serialized message. */
4912
5058
  function isFormattedContentNode(value) {
4913
5059
  if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
4914
5060
  const node = value;
4915
- switch (node.type) {
5061
+ switch (node["type"]) {
4916
5062
  case "break":
4917
5063
  case "thematicBreak": return hasValidMdastBase(node, []);
4918
5064
  case "html":
4919
5065
  case "inlineCode":
4920
5066
  case "text":
4921
- case "yaml": return hasValidMdastBase(node, ["value"]) && typeof node.value === "string";
5067
+ case "yaml": return hasValidMdastBase(node, ["value"]) && typeof node["value"] === "string";
4922
5068
  case "code": return hasValidMdastBase(node, [
4923
5069
  "lang",
4924
5070
  "meta",
4925
5071
  "value"
4926
- ]) && typeof node.value === "string" && isOptionalNullableString(node.lang) && isOptionalNullableString(node.meta);
5072
+ ]) && typeof node["value"] === "string" && isOptionalNullableString(node["lang"]) && isOptionalNullableString(node["meta"]);
4927
5073
  case "delete":
4928
5074
  case "emphasis":
4929
5075
  case "paragraph":
@@ -4931,60 +5077,60 @@ function isFormattedContentNode(value) {
4931
5077
  case "tableCell": return hasValidMdastBase(node, ["children"]) && hasMdastChildren(node, mdastPhrasingTypes);
4932
5078
  case "blockquote": return hasValidMdastBase(node, ["children"]) && hasMdastChildren(node, mdastBlockOrDefinitionTypes);
4933
5079
  case "tableRow": return hasValidMdastBase(node, ["children"]) && hasMdastChildren(node, mdastTableCellTypes);
4934
- case "heading": return hasValidMdastBase(node, ["children", "depth"]) && hasMdastChildren(node, mdastPhrasingTypes) && Number.isInteger(node.depth) && Number(node.depth) >= 1 && Number(node.depth) <= 6;
5080
+ case "heading": return hasValidMdastBase(node, ["children", "depth"]) && hasMdastChildren(node, mdastPhrasingTypes) && Number.isInteger(node["depth"]) && Number(node["depth"]) >= 1 && Number(node["depth"]) <= 6;
4935
5081
  case "list": return hasValidMdastBase(node, [
4936
5082
  "children",
4937
5083
  "ordered",
4938
5084
  "spread",
4939
5085
  "start"
4940
- ]) && hasMdastChildren(node, mdastListItemTypes) && isOptionalNullableBoolean(node.ordered) && isOptionalNullableBoolean(node.spread) && (node.start === void 0 || node.start === null || typeof node.start === "number" && Number.isFinite(node.start));
5086
+ ]) && hasMdastChildren(node, mdastListItemTypes) && isOptionalNullableBoolean(node["ordered"]) && isOptionalNullableBoolean(node["spread"]) && (node["start"] === void 0 || node["start"] === null || typeof node["start"] === "number" && Number.isFinite(node["start"]));
4941
5087
  case "listItem": return hasValidMdastBase(node, [
4942
5088
  "checked",
4943
5089
  "children",
4944
5090
  "spread"
4945
- ]) && hasMdastChildren(node, mdastBlockOrDefinitionTypes) && isOptionalNullableBoolean(node.checked) && isOptionalNullableBoolean(node.spread);
4946
- case "table": return hasValidMdastBase(node, ["align", "children"]) && hasMdastChildren(node, mdastTableRowTypes) && (node.align === void 0 || node.align === null || Array.isArray(node.align) && node.align.every((align) => align === null || align === "center" || align === "left" || align === "right"));
5091
+ ]) && hasMdastChildren(node, mdastBlockOrDefinitionTypes) && isOptionalNullableBoolean(node["checked"]) && isOptionalNullableBoolean(node["spread"]);
5092
+ case "table": return hasValidMdastBase(node, ["align", "children"]) && hasMdastChildren(node, mdastTableRowTypes) && (node["align"] === void 0 || node["align"] === null || Array.isArray(node["align"]) && node["align"].every((align) => align === null || align === "center" || align === "left" || align === "right"));
4947
5093
  case "definition": return hasValidMdastBase(node, [
4948
5094
  "identifier",
4949
5095
  "label",
4950
5096
  "title",
4951
5097
  "url"
4952
- ]) && typeof node.identifier === "string" && typeof node.url === "string" && isOptionalNullableString(node.label) && isOptionalNullableString(node.title);
5098
+ ]) && typeof node["identifier"] === "string" && typeof node["url"] === "string" && isOptionalNullableString(node["label"]) && isOptionalNullableString(node["title"]);
4953
5099
  case "footnoteDefinition": return hasValidMdastBase(node, [
4954
5100
  "children",
4955
5101
  "identifier",
4956
5102
  "label"
4957
- ]) && hasMdastChildren(node, mdastBlockOrDefinitionTypes) && typeof node.identifier === "string" && isOptionalNullableString(node.label);
4958
- case "footnoteReference": return hasValidMdastBase(node, ["identifier", "label"]) && typeof node.identifier === "string" && isOptionalNullableString(node.label);
5103
+ ]) && hasMdastChildren(node, mdastBlockOrDefinitionTypes) && typeof node["identifier"] === "string" && isOptionalNullableString(node["label"]);
5104
+ case "footnoteReference": return hasValidMdastBase(node, ["identifier", "label"]) && typeof node["identifier"] === "string" && isOptionalNullableString(node["label"]);
4959
5105
  case "image": return hasValidMdastBase(node, [
4960
5106
  "alt",
4961
5107
  "title",
4962
5108
  "url"
4963
- ]) && typeof node.url === "string" && isOptionalNullableString(node.alt) && isOptionalNullableString(node.title);
5109
+ ]) && typeof node["url"] === "string" && isOptionalNullableString(node["alt"]) && isOptionalNullableString(node["title"]);
4964
5110
  case "imageReference": return hasValidMdastBase(node, [
4965
5111
  "alt",
4966
5112
  "identifier",
4967
5113
  "label",
4968
5114
  "referenceType"
4969
- ]) && typeof node.identifier === "string" && isOptionalNullableString(node.alt) && isOptionalNullableString(node.label) && (node.referenceType === "collapsed" || node.referenceType === "full" || node.referenceType === "shortcut");
5115
+ ]) && typeof node["identifier"] === "string" && isOptionalNullableString(node["alt"]) && isOptionalNullableString(node["label"]) && (node["referenceType"] === "collapsed" || node["referenceType"] === "full" || node["referenceType"] === "shortcut");
4970
5116
  case "link": return hasValidMdastBase(node, [
4971
5117
  "children",
4972
5118
  "title",
4973
5119
  "url"
4974
- ]) && hasMdastChildren(node, mdastPhrasingTypes) && typeof node.url === "string" && isOptionalNullableString(node.title);
5120
+ ]) && hasMdastChildren(node, mdastPhrasingTypes) && typeof node["url"] === "string" && isOptionalNullableString(node["title"]);
4975
5121
  case "linkReference": return hasValidMdastBase(node, [
4976
5122
  "children",
4977
5123
  "identifier",
4978
5124
  "label",
4979
5125
  "referenceType"
4980
- ]) && hasMdastChildren(node, mdastPhrasingTypes) && typeof node.identifier === "string" && isOptionalNullableString(node.label) && (node.referenceType === "collapsed" || node.referenceType === "full" || node.referenceType === "shortcut");
5126
+ ]) && hasMdastChildren(node, mdastPhrasingTypes) && typeof node["identifier"] === "string" && isOptionalNullableString(node["label"]) && (node["referenceType"] === "collapsed" || node["referenceType"] === "full" || node["referenceType"] === "shortcut");
4981
5127
  default: return false;
4982
5128
  }
4983
5129
  }
4984
5130
  const formattedContentSchema = z.custom((value) => {
4985
5131
  if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
4986
5132
  const root = value;
4987
- return root.type === "root" && hasValidMdastBase(root, ["children"]) && hasMdastChildren(root);
5133
+ return root["type"] === "root" && hasValidMdastBase(root, ["children"]) && hasMdastChildren(root);
4988
5134
  }, "must be a valid formatted-content root");
4989
5135
  const serializedMessageSchema = z.object({
4990
5136
  _type: z.literal("chat:Message"),
@@ -6430,7 +6576,7 @@ async function runNextPausedTurnInContext(conversationId, options, runOptions) {
6430
6576
  */
6431
6577
  function createSlackSystemTurnDelivery(args) {
6432
6578
  return async ({ conversationId, location, text, cards }) => {
6433
- if (location.provider !== "slack") throw new Error(`Slack system Turn cannot deliver to ${location.provider} Location`);
6579
+ if (location.provider !== "slack") throw new Error(`Slack system Turn cannot deliver to ${String(location.provider)} Location`);
6434
6580
  let messageIds;
6435
6581
  try {
6436
6582
  messageIds = await runWithSlackInstallation({
@@ -6826,65 +6972,6 @@ async function resolveSlackMessageLink(viewer, url) {
6826
6972
  }));
6827
6973
  }
6828
6974
  }
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
6975
  // src/net/public-address.ts
6889
6976
  /**
6890
6977
  * Own the public-address rule for fetches of URLs that any person can submit.
@@ -7175,9 +7262,9 @@ function children(node) {
7175
7262
  function attribute(element, name) {
7176
7263
  return element.attrs.find((attr) => attr.name === name)?.value;
7177
7264
  }
7178
- function text$1(node) {
7265
+ function text(node) {
7179
7266
  if (node.nodeName === "#text" && "value" in node) return node.value;
7180
- return children(node).map(text$1).join("");
7267
+ return children(node).map(text).join("");
7181
7268
  }
7182
7269
  function clean(value) {
7183
7270
  return value?.replace(/\s+/g, " ").trim() || void 0;
@@ -7189,7 +7276,7 @@ function parsePageMeta(html) {
7189
7276
  const tags = /* @__PURE__ */ new Map();
7190
7277
  let title;
7191
7278
  for (const node of head ? children(head) : []) {
7192
- if (isElement(node, "title")) title ??= clean(text$1(node));
7279
+ if (isElement(node, "title")) title ??= clean(text(node));
7193
7280
  if (!isElement(node, "meta")) continue;
7194
7281
  const name = (attribute(node, "property") ?? attribute(node, "name"))?.toLowerCase();
7195
7282
  const content = clean(attribute(node, "content"));
@@ -7206,6 +7293,7 @@ function parsePageMeta(html) {
7206
7293
  "twitter:image",
7207
7294
  "twitter:image:src"
7208
7295
  ].flatMap((name) => tags.get(name) ?? []),
7296
+ media: tags.get("og:type")?.startsWith("video") || first("og:video", "og:video:url") ? "video" : void 0,
7209
7297
  siteName: first("og:site_name", "application-name"),
7210
7298
  title: first("og:title", "twitter:title") ?? title
7211
7299
  };
@@ -7315,6 +7403,7 @@ const oembedResponseSchema = z.object({
7315
7403
  author_name: optionalText,
7316
7404
  provider_name: optionalText,
7317
7405
  thumbnail_url: optionalText,
7406
+ type: optionalText,
7318
7407
  cache_age: z.coerce.number().positive().optional().catch(void 0)
7319
7408
  });
7320
7409
  /** Read an oEmbed JSON body, or nothing when it is not one. */
@@ -7363,6 +7452,7 @@ async function readOembed(url) {
7363
7452
  author: oembed.author_name,
7364
7453
  cacheAgeSeconds: oembed.cache_age,
7365
7454
  images: oembed.thumbnail_url ? [oembed.thumbnail_url] : [],
7455
+ media: oembed.type === "video" ? "video" : oembed.type === "photo" ? "image" : void 0,
7366
7456
  siteName: oembed.provider_name,
7367
7457
  title: oembed.title
7368
7458
  };
@@ -7402,6 +7492,7 @@ async function loadWebPage(url) {
7402
7492
  value: webPageObjectCard({
7403
7493
  author: page.author,
7404
7494
  description: page.description,
7495
+ media: page.media,
7405
7496
  siteName: page.siteName ?? url.hostname,
7406
7497
  thumbnailUrl: thumbnailPath(page.images, page.pageUrl),
7407
7498
  title: page.title,
@@ -7430,7 +7521,7 @@ function webPageLinkType() {
7430
7521
  cacheCards: false,
7431
7522
  canView: async () => true,
7432
7523
  filters: [{ scheme: "https" }],
7433
- objectType: "web_page",
7524
+ objectTypes: ["web_page"],
7434
7525
  owner: "junior",
7435
7526
  resolve: (_viewer, url) => resolveWebPageLink(url)
7436
7527
  };
@@ -7446,7 +7537,7 @@ function coreLinkTypes() {
7446
7537
  const slack = {
7447
7538
  canView: async () => true,
7448
7539
  filters: [SLACK_MESSAGE_LINK_FILTER],
7449
- objectType: "message",
7540
+ objectTypes: ["message"],
7450
7541
  owner: "junior",
7451
7542
  resolve: resolveSlackMessageLink
7452
7543
  };
@@ -7460,7 +7551,7 @@ function coreLinkTypes() {
7460
7551
  {
7461
7552
  canView: canViewConversationLink,
7462
7553
  filters: [conversations],
7463
- objectType: "conversation",
7554
+ objectTypes: ["conversation"],
7464
7555
  owner: "junior",
7465
7556
  resolve: resolveConversationLink
7466
7557
  },
@@ -7468,7 +7559,7 @@ function coreLinkTypes() {
7468
7559
  cacheCards: false,
7469
7560
  canView: async () => true,
7470
7561
  filters: [people, { scheme: "mailto" }],
7471
- objectType: "person",
7562
+ objectTypes: ["person"],
7472
7563
  owner: "junior",
7473
7564
  resolve: (_viewer, url) => resolvePersonLink(url)
7474
7565
  }
@@ -7482,10 +7573,20 @@ function objectLinkContext(name, viewer) {
7482
7573
  credentialContext: credentialContextForActor(OBJECT_LINK_SYSTEM_ACTOR),
7483
7574
  pluginAuth: { async handleAuthRequired() {} }
7484
7575
  }),
7576
+ imagePath: (ref, version) => imagePath({
7577
+ ref,
7578
+ source: name
7579
+ }, 640, version),
7485
7580
  findPerson: resolvePersonByAccount,
7486
7581
  log: createPluginLogger(name),
7487
7582
  plugin: { name },
7488
- viewer
7583
+ viewer,
7584
+ viewerEgress: createPluginEgress({
7585
+ credentialContext: credentialContextForActor(webActorFromUser(viewer)),
7586
+ pluginAuth: { async handleAuthRequired() {} },
7587
+ userOAuthOnly: true
7588
+ }),
7589
+ viewerMcp: createViewerMcp(name, viewer.id)
7489
7590
  };
7490
7591
  }
7491
7592
  function pluginLinkTypes(plugin) {
@@ -7493,10 +7594,11 @@ function pluginLinkTypes(plugin) {
7493
7594
  return (plugin.objectLinks ?? []).map((link) => ({
7494
7595
  canView: (viewer, url) => link.canView(objectLinkContext(name, viewer), url),
7495
7596
  filters: link.filters,
7496
- objectType: link.objectType,
7597
+ objectTypes: link.objectTypes,
7497
7598
  owner: name,
7498
7599
  readTool: link.readTool,
7499
- resolve: (viewer, url) => link.resolve(objectLinkContext(name, viewer), url)
7600
+ resolve: (viewer, url) => link.resolve(objectLinkContext(name, viewer), url),
7601
+ ...link.webPageFallback ? { webPageFallback: true } : void 0
7500
7602
  }));
7501
7603
  }
7502
7604
  /**
@@ -7508,16 +7610,31 @@ function readObjectLinkTypes(plugins = getPlugins()) {
7508
7610
  assertNoObjectLinkConflicts(linkTypes);
7509
7611
  return linkTypes;
7510
7612
  }
7613
+ /**
7614
+ * Return the object type of the link type that claims a URL, such as
7615
+ * `code_change` for a pull request link from the GitHub plugin. The plugin
7616
+ * that owns the link type decides; core only reads its filters. A link type
7617
+ * that can open more than one type, such as a GitHub issue URL that can open
7618
+ * a pull request, names no type from the URL alone.
7619
+ */
7620
+ function readLinkObjectType(url, linkTypes = readObjectLinkTypes()) {
7621
+ if (!URL.canParse(url)) return void 0;
7622
+ const objectTypes = findObjectLinkType(linkTypes, new URL(url))?.objectTypes;
7623
+ return objectTypes?.length === 1 ? objectTypes[0] : void 0;
7624
+ }
7511
7625
  async function resolveWithLinkType(linkType, viewer, url) {
7512
- if (!await linkType.canView(viewer, url)) return null;
7626
+ if (!await linkType.canView(viewer, url)) return linkType.webPageFallback ? await resolveWithLinkType(webPageLinkType(), viewer, url) : null;
7513
7627
  const resolved = await linkType.resolve(viewer, url);
7514
7628
  if (!resolved) return null;
7515
7629
  const object = objectAnnotationSchema.parse(resolved);
7516
- 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
- });
7630
+ if (!linkType.objectTypes.includes(object.objectType)) throw new Error(`Link type "${linkTypeName(linkType)}" returned a ${object.objectType} object.`);
7631
+ return {
7632
+ linkType,
7633
+ object: ownedObjectAnnotationSchema.parse({
7634
+ ...object,
7635
+ plugin: linkType.owner
7636
+ })
7637
+ };
7521
7638
  }
7522
7639
  /**
7523
7640
  * Resolve one link for one viewer without the card cache, so a change of
@@ -7527,11 +7644,7 @@ async function resolveWithLinkType(linkType, viewer, url) {
7527
7644
  async function resolveObjectLinkNow(viewer, url) {
7528
7645
  const linkType = findObjectLinkType(readObjectLinkTypes(), url);
7529
7646
  if (!linkType) return void 0;
7530
- const object = await resolveWithLinkType(linkType, viewer, url);
7531
- return object ? {
7532
- linkType,
7533
- object
7534
- } : void 0;
7647
+ return await resolveWithLinkType(linkType, viewer, url) ?? void 0;
7535
7648
  }
7536
7649
  /**
7537
7650
  * Resolve links to object cards for one viewer. A link without a link type,
@@ -7546,7 +7659,7 @@ async function resolveObjectLinks(viewer, urls) {
7546
7659
  const linkType = parsed && findObjectLinkType(linkTypes, parsed);
7547
7660
  if (!parsed || !linkType) return [];
7548
7661
  const key = `${viewer.id}:${createHash("sha256").update(url).digest("hex")}`;
7549
- const resolve = () => resolveWithLinkType(linkType, viewer, parsed);
7662
+ const resolve = async () => (await resolveWithLinkType(linkType, viewer, parsed))?.object ?? null;
7550
7663
  try {
7551
7664
  const object = linkType.cacheCards === false ? await resolve() : await cache.getOrLoad(key, async () => ({
7552
7665
  value: await resolve(),
@@ -7577,6 +7690,565 @@ function readHealthReport() {
7577
7690
  function GET() {
7578
7691
  return Response.json(readHealthReport());
7579
7692
  }
7693
+ // src/chat/cache-warming/backfill.ts
7694
+ /**
7695
+ * Fill of the empty cache warming gap lists from stored Conversation
7696
+ * history, about once a month.
7697
+ *
7698
+ * `warmup.ts` learns reply gaps only from idle periods after it is deployed.
7699
+ * Until a `gapSegment` has gaps, Junior sends no warmups for it. This replays
7700
+ * the stored model calls of the last `GLOBAL_GAPS_TTL_MS` with the same rules
7701
+ * as live recording, so warming can start soon after the first deploy.
7702
+ *
7703
+ * The heartbeat runs it. Only one run claims it, and a completed run marks
7704
+ * the install as done, also when it stopped on its time budget or skipped a
7705
+ * batch that the statement timeout canceled. It fills only segment lists
7706
+ * that are empty when it starts, so it does not add history to gaps that
7707
+ * live recording already has.
7708
+ *
7709
+ * History does not tell the plugin work state or the archive state that a
7710
+ * Conversation had when an idle period started. So it fills only the
7711
+ * segments of Conversations that are not archived and have work state
7712
+ * `none`, which most Conversations have. The `open` and `done` segments and
7713
+ * the `archived:*` segments stay empty until live gaps arrive. Until then,
7714
+ * `decideWarmup` leans on their `parentGapSegment`, a `none` segment that
7715
+ * this fills. Each idle period still records its gap, so the segment fills
7716
+ * from live idle periods.
7717
+ */
7718
+ const BACKFILL_KEY = "junior:cache_warming:backfill:work_state:v2";
7719
+ const BACKFILL_CLAIM_TTL_MS = 60 * MINUTE_MS;
7720
+ const BACKFILL_DONE_TTL_MS = GLOBAL_GAPS_TTL_MS;
7721
+ const CONVERSATION_BATCH_SIZE = 10;
7722
+ const CONVERSATION_PAGE_SIZE = 500;
7723
+ const QUERY_CANCELED = "57014";
7724
+ /**
7725
+ * Scan time of one backfill run. The heartbeat gives no deadline. This leaves
7726
+ * most of its function time for the writes and the other heartbeat work.
7727
+ */
7728
+ const BACKFILL_BUDGET_MS = 6e4;
7729
+ const BACKFILL_GAPS_MAX = GLOBAL_GAPS_MAX / 2;
7730
+ const BACKFILL_SEGMENTS = new Set([true, false].flatMap((userActor) => [
7731
+ 0,
7732
+ 1,
7733
+ 2,
7734
+ 3
7735
+ ].map((endedTurns) => historySegment(userActor, endedTurns))));
7736
+ function historySegment(userActor, endedTurns) {
7737
+ return gapSegment({
7738
+ userActor,
7739
+ endedTurns,
7740
+ workState: "none",
7741
+ archived: false
7742
+ });
7743
+ }
7744
+ const inWindow = (windowStartMs) => and(gte(juniorConversations.lastActivityAt, new Date(windowStartMs)), isNull(juniorConversations.transcriptPurgedAt));
7745
+ const conversationColumns = {
7746
+ conversationId: juniorConversations.conversationId,
7747
+ kind: juniorConversations.kind,
7748
+ parentConversationId: juniorConversations.parentConversationId
7749
+ };
7750
+ async function loadConversations(windowStartMs) {
7751
+ return await getDb().select(conversationColumns).from(juniorConversations).where(inWindow(windowStartMs)).orderBy(desc(juniorConversations.lastActivityAt), juniorConversations.conversationId);
7752
+ }
7753
+ async function loadConversationPage(windowStartMs, afterConversationId) {
7754
+ 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);
7755
+ }
7756
+ /** Count the Conversations that a history scan from `windowStartMs` reads. */
7757
+ async function countHistoryConversations(windowStartMs) {
7758
+ const [row] = await getDb().select({ count: count() }).from(juniorConversations).where(inWindow(windowStartMs));
7759
+ return row?.count ?? 0;
7760
+ }
7761
+ async function loadEvents(conversationIds) {
7762
+ const events = juniorConversationEvents;
7763
+ const isUserMessage = sql`${events.type} = 'user_message'`;
7764
+ const isToolResult = sql`${events.type} = 'tool_result'`;
7765
+ const message = sql`CASE
7766
+ WHEN ${events.type} NOT IN ('assistant_message', 'tool_result') THEN NULL
7767
+ WHEN ${events.schemaVersion} >= 2 THEN (${events.payload}->>'message')::jsonb
7768
+ ELSE ${events.payload}
7769
+ END`;
7770
+ return await getDb().select({
7771
+ conversationId: events.conversationId,
7772
+ type: sql`${events.type}`,
7773
+ personInstruction: sql`CASE WHEN ${isUserMessage} THEN (${events.payload}->'provenance'->'actor'->>'userId') IS NOT NULL END`,
7774
+ stopReason: sql`(${message})->>'stopReason'`,
7775
+ toolName: sql`(${message})->>'toolName'`,
7776
+ startedAtMs: sql`(${message})->>'timestamp'`,
7777
+ modelId: sql`(${message})->>'model'`,
7778
+ cacheRead: sql`${events.payload}->'usage'->>'cacheRead'`,
7779
+ cacheWrite: sql`${events.payload}->'usage'->>'cacheWrite'`
7780
+ }).from(events).innerJoin(juniorConversations, eq(juniorConversations.conversationId, events.conversationId)).where(and(inArray(events.conversationId, conversationIds), or(eq(events.type, "assistant_message"), and(isToolResult, inArray(sql`(${message})->>'toolName'`, Object.keys(ANSWER_TOOL_ENDINGS)), sql`(${message})->>'isError' IS DISTINCT FROM 'true'`), and(isUserMessage, sql`(${events.payload}->'provenance'->>'authority') = 'instruction'`)), gte(events.createdAt, juniorConversations.createdAt))).orderBy(events.conversationId, events.seq);
7781
+ }
7782
+ async function loadChildAgents(conversationIds) {
7783
+ return await getDb().select({
7784
+ conversationId: juniorAgentInvocations.parentConversationId,
7785
+ createdAt: juniorAgentInvocations.createdAt,
7786
+ terminalAt: juniorAgentInvocations.terminalAt
7787
+ }).from(juniorAgentInvocations).where(inArray(juniorAgentInvocations.parentConversationId, conversationIds));
7788
+ }
7789
+ /**
7790
+ * Replay the model calls of one Conversation the way the recorders in
7791
+ * `warmup.ts` and `tool-wait.ts` see them, and return each idle period and
7792
+ * tool wait. An idle period starts at a call that ends the Turn: a `stop`
7793
+ * call or an answer tool call that succeeded. A tool wait starts at any
7794
+ * other `toolUse` call, so no pair of calls is in both.
7795
+ *
7796
+ * Live recording measures from the start of the request that ended a Turn to
7797
+ * the start of the next recorded request. Here both times are the
7798
+ * `timestamp` of the stored assistant message, which Pi sets when it starts
7799
+ * the request. That is the closest stored time to the recorder's clock.
7800
+ */
7801
+ function replayConversation(kind, events, children, nowMs) {
7802
+ const periods = [];
7803
+ const toolWaits = [];
7804
+ const close = ({ waitsOnPendingWork, childRunning, ...idle }, untilMs, next) => {
7805
+ const gapMs = untilMs - idle.sinceMs;
7806
+ if (gapMs <= 0) return;
7807
+ if (waitsOnPendingWork && !childRunning && !next) return;
7808
+ const period = {
7809
+ ...idle,
7810
+ gapMs
7811
+ };
7812
+ if (next) period.next = next;
7813
+ periods.push(period);
7814
+ };
7815
+ let userActor = false;
7816
+ let inTurn = false;
7817
+ let endedTurns = 0;
7818
+ let lastCallMs;
7819
+ let idle;
7820
+ let waiting;
7821
+ const answerEndings = /* @__PURE__ */ new Map();
7822
+ let toolUse;
7823
+ for (const event of events) {
7824
+ if (event.type === "assistant_message") toolUse = event.stopReason === "toolUse" ? event : void 0;
7825
+ const ending = event.type === "tool_result" && event.toolName ? ANSWER_TOOL_ENDINGS[event.toolName] : void 0;
7826
+ if (toolUse && ending) answerEndings.set(toolUse, ending);
7827
+ }
7828
+ for (const event of events) {
7829
+ if (event.type === "tool_result") continue;
7830
+ if (event.type === "user_message") {
7831
+ if (!inTurn) {
7832
+ userActor = event.personInstruction === true && kind !== "task";
7833
+ inTurn = true;
7834
+ }
7835
+ continue;
7836
+ }
7837
+ const answerEnding = answerEndings.get(event);
7838
+ const turnEnding = event.stopReason === "stop" ? "reply" : answerEnding;
7839
+ if (event.stopReason !== "toolUse" || answerEnding) inTurn = false;
7840
+ const startedAtMs = event.startedAtMs === null ? NaN : Number(event.startedAtMs);
7841
+ if (!Number.isFinite(startedAtMs)) continue;
7842
+ const next = {
7843
+ modelId: event.modelId,
7844
+ cacheRead: Number(event.cacheRead ?? 0),
7845
+ cacheWrite: Number(event.cacheWrite ?? 0)
7846
+ };
7847
+ if (waiting && startedAtMs > waiting.sinceMs) toolWaits.push({
7848
+ ...waiting,
7849
+ gapMs: startedAtMs - waiting.sinceMs,
7850
+ next
7851
+ });
7852
+ waiting = event.stopReason === "toolUse" && !answerEnding ? {
7853
+ sinceMs: startedAtMs,
7854
+ prefixTokens: next.cacheRead + next.cacheWrite
7855
+ } : void 0;
7856
+ if (event.stopReason === "error" || event.stopReason === "aborted") continue;
7857
+ const { cacheRead, cacheWrite } = next;
7858
+ if (idle) close(idle, startedAtMs, next);
7859
+ idle = void 0;
7860
+ if (lastCallMs !== void 0 && startedAtMs - lastCallMs > CONVERSATION_STATE_TTL_MS) endedTurns = 0;
7861
+ lastCallMs = startedAtMs;
7862
+ if (turnEnding) {
7863
+ const waitsOnPendingWork = turnBehavior({
7864
+ kind,
7865
+ personInput: userActor
7866
+ }).promptMode === "automation";
7867
+ idle = {
7868
+ sinceMs: startedAtMs,
7869
+ segment: historySegment(userActor, endedTurns),
7870
+ turnEnding,
7871
+ prefixTokens: cacheRead + cacheWrite,
7872
+ waitsOnPendingWork,
7873
+ childRunning: waitsOnPendingWork && children.some((child) => child.createdAt.getTime() <= startedAtMs && (child.terminalAt === null || child.terminalAt.getTime() > startedAtMs))
7874
+ };
7875
+ endedTurns += 1;
7876
+ }
7877
+ }
7878
+ if (idle && nowMs - idle.sinceMs >= 33e5) close(idle, nowMs);
7879
+ return {
7880
+ periods,
7881
+ toolWaits
7882
+ };
7883
+ }
7884
+ function byConversation(rows) {
7885
+ const grouped = /* @__PURE__ */ new Map();
7886
+ for (const row of rows) {
7887
+ const list = grouped.get(row.conversationId) ?? [];
7888
+ list.push(row);
7889
+ grouped.set(row.conversationId, list);
7890
+ }
7891
+ return grouped;
7892
+ }
7893
+ function isQueryCanceled(error) {
7894
+ let current = error;
7895
+ for (let depth = 0; current && depth < 6; depth += 1) {
7896
+ if (typeof current !== "object") return false;
7897
+ if (current.code === QUERY_CANCELED) return true;
7898
+ current = current.cause;
7899
+ }
7900
+ return false;
7901
+ }
7902
+ async function replayConversations(conversations, args) {
7903
+ const { windowStartMs, nowMs, budgetMs } = args;
7904
+ const startedAt = performance.now();
7905
+ const periods = [];
7906
+ const toolWaits = [];
7907
+ let scanned = 0;
7908
+ let canceledBatches = 0;
7909
+ let budgetExceeded = false;
7910
+ let lastConversationId;
7911
+ for (let i = 0; i < conversations.length; i += CONVERSATION_BATCH_SIZE) {
7912
+ if (i > 0 && performance.now() - startedAt >= budgetMs) {
7913
+ budgetExceeded = true;
7914
+ break;
7915
+ }
7916
+ const batch = conversations.slice(i, i + CONVERSATION_BATCH_SIZE);
7917
+ lastConversationId = batch.at(-1).conversationId;
7918
+ let rows;
7919
+ let children;
7920
+ try {
7921
+ const ids = batch.map((row) => row.conversationId);
7922
+ [rows, children] = await Promise.all([loadEvents(ids), loadChildAgents(ids)]);
7923
+ } catch (error) {
7924
+ if (!isQueryCanceled(error)) throw error;
7925
+ canceledBatches += 1;
7926
+ continue;
7927
+ }
7928
+ const events = byConversation(rows);
7929
+ const childrenByParent = byConversation(children);
7930
+ for (const conversation of batch) {
7931
+ const replayed = replayConversation(conversationKindFromRow(conversation), events.get(conversation.conversationId) ?? [], childrenByParent.get(conversation.conversationId) ?? [], nowMs);
7932
+ const inScanWindow = (period) => period.sinceMs >= windowStartMs;
7933
+ periods.push(...replayed.periods.filter(inScanWindow));
7934
+ toolWaits.push(...replayed.toolWaits.filter(inScanWindow));
7935
+ }
7936
+ scanned += batch.length;
7937
+ }
7938
+ periods.sort((a, b) => a.sinceMs - b.sinceMs);
7939
+ return {
7940
+ periods,
7941
+ toolWaits,
7942
+ scanned,
7943
+ canceledBatches,
7944
+ budgetExceeded,
7945
+ lastConversationId
7946
+ };
7947
+ }
7948
+ /**
7949
+ * Replay the stored history of each Conversation with activity since
7950
+ * `windowStartMs`, newest first, and return its idle periods that started in
7951
+ * the window, oldest first. The scan stops before the next batch when the
7952
+ * budget is used. The budget uses the monotonic clock, not `nowMs`.
7953
+ */
7954
+ async function scanIdlePeriods(args) {
7955
+ const { lastConversationId: _, ...scan } = await replayConversations(await loadConversations(args.windowStartMs), args);
7956
+ return scan;
7957
+ }
7958
+ /**
7959
+ * Replay the next Conversations in id order after `afterConversationId`,
7960
+ * until the budget is used, as `scanIdlePeriods` does. Continue with the
7961
+ * returned `lastConversationId` until the slice is `complete`.
7962
+ */
7963
+ async function scanIdlePeriodSlice(args) {
7964
+ const page = await loadConversationPage(args.windowStartMs, args.afterConversationId);
7965
+ const scan = await replayConversations(page, args);
7966
+ return {
7967
+ ...scan,
7968
+ complete: !scan.budgetExceeded && page.length < CONVERSATION_PAGE_SIZE
7969
+ };
7970
+ }
7971
+ function gapsBySegment(periods) {
7972
+ const bySegment = /* @__PURE__ */ new Map();
7973
+ for (const period of periods) {
7974
+ if (period.prefixTokens < 5e4) continue;
7975
+ const list = bySegment.get(period.segment) ?? [];
7976
+ list.push(period.gapMs >= 33e5 ? NO_REPLY_GAP_MS : period.gapMs);
7977
+ bySegment.set(period.segment, list);
7978
+ }
7979
+ return bySegment;
7980
+ }
7981
+ /**
7982
+ * Fill each empty cache warming gap list from the stored Conversation
7983
+ * history. The heartbeat calls it each minute. After a run completes, a call
7984
+ * makes one state request and returns, until the completed run expires.
7985
+ *
7986
+ * A run that uses its scan budget writes the gaps that it has and also
7987
+ * completes. Some gaps are better than none, and a run that cannot finish
7988
+ * would otherwise try again each hour.
7989
+ */
7990
+ async function backfillCacheWarmingGaps(args) {
7991
+ if (!getChatConfig().cacheWarmingEnabled) return;
7992
+ const state = getStateAdapter();
7993
+ await state.connect();
7994
+ if (!await state.setIfNotExists(BACKFILL_KEY, "running", BACKFILL_CLAIM_TTL_MS)) return;
7995
+ await withSpan("cache_warming.backfill", "cache_warming.backfill", {}, async (setSpanAttributes) => {
7996
+ const emptySegments = /* @__PURE__ */ new Set();
7997
+ for (const segment of BACKFILL_SEGMENTS) if ((await state.getList(segmentGapsKey(segment))).length === 0) emptySegments.add(segment);
7998
+ const { periods, scanned, canceledBatches, budgetExceeded } = await scanIdlePeriods({
7999
+ windowStartMs: args.nowMs - GLOBAL_GAPS_TTL_MS,
8000
+ nowMs: args.nowMs,
8001
+ budgetMs: args.budgetMs ?? 6e4
8002
+ });
8003
+ const bySegment = gapsBySegment(periods);
8004
+ const logAttributes = {
8005
+ "app.cache_warming.backfill.conversation_count": scanned,
8006
+ "app.cache_warming.backfill.canceled_batch_count": canceledBatches,
8007
+ "app.cache_warming.backfill.budget_exceeded": budgetExceeded
8008
+ };
8009
+ if (scanned === 0 && canceledBatches > 0) {
8010
+ logInfo("cache_warming.backfill.not_completed", logAttributes);
8011
+ setSpanAttributes({
8012
+ ...logAttributes,
8013
+ "app.cache_warming.backfill.outcome": "not_completed"
8014
+ });
8015
+ return;
8016
+ }
8017
+ let gapCount = 0;
8018
+ let segmentCount = 0;
8019
+ for (const [segment, gaps] of bySegment) {
8020
+ if (!emptySegments.has(segment)) continue;
8021
+ const key = segmentGapsKey(segment);
8022
+ const newest = gaps.slice(-BACKFILL_GAPS_MAX);
8023
+ for (const gapMs of newest) await state.appendToList(key, gapMs, {
8024
+ maxLength: GLOBAL_GAPS_MAX,
8025
+ ttlMs: GLOBAL_GAPS_TTL_MS
8026
+ });
8027
+ gapCount += newest.length;
8028
+ segmentCount += 1;
8029
+ }
8030
+ await state.set(BACKFILL_KEY, "done", BACKFILL_DONE_TTL_MS);
8031
+ const completed = {
8032
+ ...logAttributes,
8033
+ "app.cache_warming.backfill.gap_count": gapCount,
8034
+ "app.cache_warming.backfill.segment_count": segmentCount
8035
+ };
8036
+ logInfo("cache_warming.backfill.completed", completed);
8037
+ setSpanAttributes({
8038
+ ...completed,
8039
+ "app.cache_warming.backfill.outcome": "completed"
8040
+ });
8041
+ });
8042
+ }
8043
+ // src/chat/cache-warming/savings-refill.ts
8044
+ /**
8045
+ * Re-fill of the cache warming savings counters from stored Conversation
8046
+ * history. A Junior admin starts it from the System page.
8047
+ *
8048
+ * Live recording (`savings.ts`) counts only idle periods and tool waits that
8049
+ * end after it is deployed. A re-fill replays the stored model calls of the
8050
+ * last `REFILL_DAYS` with the same rules into the days before the first day
8051
+ * with live counters. It replaces those days, so a second re-fill does not
8052
+ * add to the first. It never writes a live day: live days have data that
8053
+ * history does not, the real warmup cost and the warm state split.
8054
+ *
8055
+ * The start request only stores a pending job. The heartbeat runs one slice
8056
+ * of the scan each minute, with a time budget. Each slice keeps its sums and
8057
+ * the scan position in the job with one state write, so a retried slice does
8058
+ * not count twice. The last slice replaces the days in one transaction. A
8059
+ * job whose lease expires, because its slices stopped or kept failing, is
8060
+ * failed, and an admin can start a new one.
8061
+ */
8062
+ const JOB_KEY = "junior:cache_warming:savings_refill:v1";
8063
+ const SLICE_LOCK_KEY = "junior:cache_warming:savings_refill:v1:slice";
8064
+ const SLICE_LOCK_TTL_MS = 5 * MINUTE_MS;
8065
+ const START_LOCK_KEY = "junior:cache_warming:savings_refill:v1:start";
8066
+ const START_LOCK_TTL_MS = MINUTE_MS;
8067
+ const LEASE_MS = 10 * MINUTE_MS;
8068
+ const MAX_JOB_AGE_MS = 360 * MINUTE_MS;
8069
+ const JOB_TTL_MS = 129600 * MINUTE_MS;
8070
+ const REFILL_DAYS = 90;
8071
+ const DAY_MS = 1440 * MINUTE_MS;
8072
+ const SLICE_BUDGET_MS = BACKFILL_BUDGET_MS / 2;
8073
+ const STOPPED_ERROR = "The re-fill stopped before it finished.";
8074
+ const CANCELED_ERROR = "The history queries timed out.";
8075
+ const refillJobSchema = z.object({
8076
+ id: z.string(),
8077
+ status: z.enum([
8078
+ "pending",
8079
+ "running",
8080
+ "done",
8081
+ "failed"
8082
+ ]),
8083
+ startedAtMs: z.number(),
8084
+ finishedAtMs: z.number().optional(),
8085
+ error: z.string().optional(),
8086
+ leaseExpiresAtMs: z.number(),
8087
+ windowStartMs: z.number(),
8088
+ /** First day with live counters. The job writes only days before it. */
8089
+ liveStartDate: z.string(),
8090
+ afterConversationId: z.string().optional(),
8091
+ scannedConversations: z.number(),
8092
+ totalConversations: z.number(),
8093
+ /** Sums of the slices so far, per day and model. */
8094
+ sums: z.record(z.string(), z.record(z.string(), z.record(z.string(), z.number())))
8095
+ }).strict();
8096
+ const utcDate = (ms) => new Date(ms).toISOString().slice(0, 10);
8097
+ const isoTime = (ms) => ms === void 0 ? void 0 : new Date(ms).toISOString();
8098
+ const isActive = (job) => job.status === "pending" || job.status === "running";
8099
+ const isStopped = (job, nowMs) => isActive(job) && (job.leaseExpiresAtMs <= nowMs || nowMs - job.startedAtMs > MAX_JOB_AGE_MS);
8100
+ async function readJob() {
8101
+ const stored = await (await connectedState()).get(JOB_KEY);
8102
+ return stored === null ? void 0 : refillJobSchema.parse(stored);
8103
+ }
8104
+ function toStatus(job, nowMs) {
8105
+ if (!job) return { status: "idle" };
8106
+ const stopped = isStopped(job, nowMs);
8107
+ return {
8108
+ status: stopped ? "failed" : job.status,
8109
+ startedAt: isoTime(job.startedAtMs),
8110
+ finishedAt: isoTime(job.finishedAtMs),
8111
+ error: stopped ? job.error ?? STOPPED_ERROR : job.error,
8112
+ scannedConversations: job.scannedConversations,
8113
+ totalConversations: job.totalConversations
8114
+ };
8115
+ }
8116
+ /** Read the state of the last savings re-fill. */
8117
+ async function readSavingsRefill(nowMs = Date.now()) {
8118
+ return toStatus(await readJob(), nowMs);
8119
+ }
8120
+ /**
8121
+ * Start a savings re-fill. Return `started: false` and the current state
8122
+ * when a job is still pending or running.
8123
+ */
8124
+ async function startSavingsRefill(nowMs = Date.now()) {
8125
+ const state = await connectedState();
8126
+ if (!await state.setIfNotExists(START_LOCK_KEY, true, START_LOCK_TTL_MS)) return {
8127
+ started: false,
8128
+ refill: await readSavingsRefill(nowMs)
8129
+ };
8130
+ try {
8131
+ const current = await readJob();
8132
+ if (current && isActive(current) && !isStopped(current, nowMs)) return {
8133
+ started: false,
8134
+ refill: toStatus(current, nowMs)
8135
+ };
8136
+ const windowStartMs = Date.parse(utcDate(nowMs - REFILL_DAYS * DAY_MS));
8137
+ const job = {
8138
+ id: randomUUID(),
8139
+ status: "pending",
8140
+ startedAtMs: nowMs,
8141
+ leaseExpiresAtMs: nowMs + LEASE_MS,
8142
+ windowStartMs,
8143
+ liveStartDate: await firstLiveSavingsDate() ?? utcDate(nowMs),
8144
+ scannedConversations: 0,
8145
+ totalConversations: await countHistoryConversations(windowStartMs),
8146
+ sums: {}
8147
+ };
8148
+ await state.set(JOB_KEY, job, JOB_TTL_MS);
8149
+ logInfo("cache_warming.savings_refill.started", { "app.cache_warming.backfill.conversation_count": job.totalConversations });
8150
+ return {
8151
+ started: true,
8152
+ refill: toStatus(job, nowMs)
8153
+ };
8154
+ } finally {
8155
+ await state.delete(START_LOCK_KEY);
8156
+ }
8157
+ }
8158
+ function addPeriod(job, period) {
8159
+ const modelId = period.next.modelId;
8160
+ if (!modelId) return;
8161
+ const ttlMs = providerCacheTtlMs(modelId);
8162
+ if (ttlMs === void 0) return;
8163
+ let cost;
8164
+ try {
8165
+ cost = resolveGatewayModel(modelId).cost;
8166
+ } catch {
8167
+ return;
8168
+ }
8169
+ const savings = idlePeriodSavings({
8170
+ cacheTtlMs: ttlMs,
8171
+ gapMs: period.gapMs,
8172
+ prefixTokens: period.prefixTokens,
8173
+ cacheRead: period.next.cacheRead,
8174
+ cacheWrite: period.next.cacheWrite,
8175
+ cacheReadPrice: cost.cacheRead,
8176
+ cacheWritePrice: cost.cacheWrite
8177
+ });
8178
+ if (savings) addHistoryPeriod(job.sums, period.sinceMs + period.gapMs, modelId, savings);
8179
+ }
8180
+ /**
8181
+ * Run the next slice of a pending or running savings re-fill. The heartbeat
8182
+ * calls it each minute. With no job to run, it makes one state request.
8183
+ */
8184
+ async function runSavingsRefillSlice(args) {
8185
+ const { nowMs } = args;
8186
+ const job = await readJob();
8187
+ if (!job || !isActive(job)) return;
8188
+ const state = await connectedState();
8189
+ if (isStopped(job, nowMs)) return;
8190
+ if (!await state.setIfNotExists(SLICE_LOCK_KEY, job.id, SLICE_LOCK_TTL_MS)) return;
8191
+ try {
8192
+ await withSpan("cache_warming.savings_refill.slice", "cache_warming.backfill", {}, async (setSpanAttributes) => {
8193
+ const range = {
8194
+ start: utcDate(job.windowStartMs),
8195
+ end: job.liveStartDate
8196
+ };
8197
+ const scan = range.start < range.end ? await scanIdlePeriodSlice({
8198
+ windowStartMs: job.windowStartMs,
8199
+ nowMs,
8200
+ budgetMs: args.budgetMs ?? SLICE_BUDGET_MS,
8201
+ afterConversationId: job.afterConversationId
8202
+ }) : void 0;
8203
+ for (const period of scan?.periods ?? []) if (period.next) addPeriod(job, {
8204
+ ...period,
8205
+ next: period.next
8206
+ });
8207
+ for (const toolWait of scan?.toolWaits ?? []) addPeriod(job, toolWait);
8208
+ if ((await readJob())?.id !== job.id) return;
8209
+ const next = {
8210
+ ...job,
8211
+ status: "running",
8212
+ leaseExpiresAtMs: nowMs + LEASE_MS,
8213
+ afterConversationId: scan?.lastConversationId ?? job.afterConversationId,
8214
+ scannedConversations: job.scannedConversations + (scan?.scanned ?? 0)
8215
+ };
8216
+ delete next.error;
8217
+ const complete = scan?.complete ?? true;
8218
+ if (scan && complete && next.scannedConversations === 0 && job.totalConversations > 0) Object.assign(next, {
8219
+ status: "failed",
8220
+ finishedAtMs: nowMs,
8221
+ error: CANCELED_ERROR,
8222
+ sums: {}
8223
+ });
8224
+ else if (complete) {
8225
+ await replaceHistorySavings(job.sums, range);
8226
+ Object.assign(next, {
8227
+ status: "done",
8228
+ finishedAtMs: nowMs,
8229
+ sums: {}
8230
+ });
8231
+ }
8232
+ await state.set(JOB_KEY, next, JOB_TTL_MS);
8233
+ const attributes = {
8234
+ "app.cache_warming.backfill.conversation_count": scan?.scanned ?? 0,
8235
+ "app.cache_warming.backfill.canceled_batch_count": scan?.canceledBatches ?? 0,
8236
+ "app.cache_warming.backfill.outcome": complete ? "completed" : "continued"
8237
+ };
8238
+ setSpanAttributes(attributes);
8239
+ if (complete) logInfo("cache_warming.savings_refill.completed", attributes);
8240
+ });
8241
+ } catch (error) {
8242
+ const current = await readJob();
8243
+ if (current?.id === job.id) await state.set(JOB_KEY, {
8244
+ ...current,
8245
+ error: error instanceof Error ? error.message : String(error)
8246
+ }, JOB_TTL_MS);
8247
+ throw error;
8248
+ } finally {
8249
+ await state.delete(SLICE_LOCK_KEY);
8250
+ }
8251
+ }
7580
8252
  // src/chat/conversations/sql/authorization-wait.ts
7581
8253
  /**
7582
8254
  * How long a person can finish an authorization. The MCP auth session and the
@@ -7629,15 +8301,49 @@ function treeAwaitsAuthorization(rootConversationId) {
7629
8301
  and ${awaitsAuthorization(tree.conversationId)}
7630
8302
  )`;
7631
8303
  }
8304
+ // src/api/user-settings.ts
8305
+ const userPreferencesSchema = z.object({
8306
+ /** Show the new dashboard UI instead of the current one. */
8307
+ experimentalUi: z.boolean().optional() });
8308
+ /** Settings of a user who has not changed any. */
8309
+ const DEFAULT_USER_SETTINGS = {
8310
+ autoArchiveDefault: false,
8311
+ autoArchiveGraceHours: 24,
8312
+ experimentalUi: false
8313
+ };
8314
+ const userSettingsColumns = {
8315
+ autoArchiveDefault: juniorUsers.autoArchiveDefault,
8316
+ autoArchiveGraceHours: juniorUsers.autoArchiveGraceHours,
8317
+ preferences: juniorUsers.preferences
8318
+ };
8319
+ function toUserSettings(row) {
8320
+ const { preferences, ...columns } = row;
8321
+ const parsed = userPreferencesSchema.parse(preferences);
8322
+ return {
8323
+ ...columns,
8324
+ experimentalUi: parsed.experimentalUi ?? DEFAULT_USER_SETTINGS.experimentalUi
8325
+ };
8326
+ }
8327
+ /** Read the user's dashboard settings. */
8328
+ async function readUserSettings(userId) {
8329
+ const [user] = await getDb().select(userSettingsColumns).from(juniorUsers).where(eq(juniorUsers.id, userId)).limit(1);
8330
+ return user && toUserSettings(user);
8331
+ }
8332
+ /** Save changed dashboard settings and return the saved settings. */
8333
+ async function updateUserSettings(userId, settings) {
8334
+ const { experimentalUi, ...columns } = settings;
8335
+ const preferences = experimentalUi === void 0 ? {} : { experimentalUi };
8336
+ const [user] = await getDb().update(juniorUsers).set({
8337
+ ...columns,
8338
+ preferences: sql`${juniorUsers.preferences} || ${JSON.stringify(preferences)}::jsonb`,
8339
+ updatedAt: /* @__PURE__ */ new Date()
8340
+ }).where(eq(juniorUsers.id, userId)).returning(userSettingsColumns);
8341
+ return user && toUserSettings(user);
8342
+ }
7632
8343
  // src/api/conversations/auto-archive.ts
7633
8344
  const HOUR_MS = 36e5;
7634
8345
  /** Participant rows checked per page. A run reads pages until none remain. */
7635
8346
  const AUTO_ARCHIVE_PAGE_SIZE = 500;
7636
- /** Settings of a user who has not changed auto-archive. */
7637
- const DEFAULT_AUTO_ARCHIVE_SETTINGS = {
7638
- autoArchiveDefault: false,
7639
- autoArchiveGraceHours: 24
7640
- };
7641
8347
  function runOptsIn(run) {
7642
8348
  return run.kind === "scheduled" ? sql`coalesce(${juniorConversationParticipants.autoArchive}, ${juniorUsers.autoArchiveDefault}) = true` : sql`${juniorConversationParticipants.autoArchive} is distinct from false`;
7643
8349
  }
@@ -7798,7 +8504,7 @@ async function runAutoArchiveSweep(args) {
7798
8504
  */
7799
8505
  async function archiveViewerDoneConversations(viewer) {
7800
8506
  const { archived } = await archiveUserDoneConversations({
7801
- graceHours: (await readUserAutoArchiveSettings(viewer.id))?.autoArchiveGraceHours ?? DEFAULT_AUTO_ARCHIVE_SETTINGS.autoArchiveGraceHours,
8507
+ graceHours: (await readUserSettings(viewer.id))?.autoArchiveGraceHours ?? 24,
7802
8508
  kind: "manual",
7803
8509
  now: /* @__PURE__ */ new Date(),
7804
8510
  userId: viewer.id
@@ -7822,25 +8528,6 @@ async function setConversationAutoArchive(viewer, conversationId, autoArchive) {
7822
8528
  });
7823
8529
  return { autoArchive };
7824
8530
  }
7825
- /** Read the user's auto-archive settings. */
7826
- async function readUserAutoArchiveSettings(userId) {
7827
- const [user] = await getDb().select({
7828
- autoArchiveDefault: juniorUsers.autoArchiveDefault,
7829
- autoArchiveGraceHours: juniorUsers.autoArchiveGraceHours
7830
- }).from(juniorUsers).where(eq(juniorUsers.id, userId)).limit(1);
7831
- return user;
7832
- }
7833
- /** Save changed auto-archive settings and return the saved settings. */
7834
- async function updateUserAutoArchiveSettings(userId, settings) {
7835
- const [user] = await getDb().update(juniorUsers).set({
7836
- ...settings,
7837
- updatedAt: /* @__PURE__ */ new Date()
7838
- }).where(eq(juniorUsers.id, userId)).returning({
7839
- autoArchiveDefault: juniorUsers.autoArchiveDefault,
7840
- autoArchiveGraceHours: juniorUsers.autoArchiveGraceHours
7841
- });
7842
- return user;
7843
- }
7844
8531
  // src/chat/review-items/reply-match.ts
7845
8532
  const MATCH_CONFIDENCE_THRESHOLD = .7;
7846
8533
  /** A slow decision keeps the items open instead of delaying the close. */
@@ -8221,7 +8908,7 @@ function resolveAllowedDomains(allowedDomains) {
8221
8908
  */
8222
8909
  function assertNoLegacyAllowedDomains(dashboardOptionKeys) {
8223
8910
  if (dashboardOptionKeys.includes("allowedGoogleDomains")) throw new Error("dashboard.allowedGoogleDomains was removed; set createApp({ allowedDomains }) instead");
8224
- if (process.env.JUNIOR_DASHBOARD_GOOGLE_DOMAINS?.trim()) throw new Error("JUNIOR_DASHBOARD_GOOGLE_DOMAINS was removed; set JUNIOR_ALLOWED_DOMAINS instead");
8911
+ if (process.env["JUNIOR_DASHBOARD_GOOGLE_DOMAINS"]?.trim()) throw new Error("JUNIOR_DASHBOARD_GOOGLE_DOMAINS was removed; set JUNIOR_ALLOWED_DOMAINS instead");
8225
8912
  }
8226
8913
  /** Return whether a verified domain may use Junior. An empty list allows all. */
8227
8914
  function isAllowedDomain(domain, allowedDomains) {
@@ -9228,8 +9915,9 @@ function format(text, provider) {
9228
9915
  * as GitHub reference and `@login` links that show as object cards. A reply
9229
9916
  * posted to a provider, and the summary of an Event from one, is that
9230
9917
  * provider's text. In a chat reply, a bare `@U123` is a Slack user, as in
9231
- * Slack, and not an account of a plugin's provider. Raw Event text and user
9232
- * text show as written.
9918
+ * Slack, and not an account of a plugin's provider. A person's message gets
9919
+ * the same links, so a typed `owner/repo#12` shows the card that a pasted
9920
+ * URL shows. Raw Event text shows as written.
9233
9921
  */
9234
9922
  function formatConversationEventText(event) {
9235
9923
  const { data } = event;
@@ -9253,13 +9941,15 @@ function formatConversationEventText(event) {
9253
9941
  } : item) } : void 0
9254
9942
  }
9255
9943
  };
9256
- return data.role === "assistant" && data.text !== void 0 ? {
9944
+ if (data.text === void 0 || data.role === "system") return event;
9945
+ const text = data.role === "assistant" ? wrapBareSlackUserIds(data.text) : data.text;
9946
+ return {
9257
9947
  ...event,
9258
9948
  data: {
9259
9949
  ...data,
9260
- text: format(wrapBareSlackUserIds(data.text))
9950
+ text: format(text)
9261
9951
  }
9262
- } : event;
9952
+ };
9263
9953
  }
9264
9954
  // src/api/conversations/mentions.ts
9265
9955
  /** Text in one event that the dashboard renders with mentions. */
@@ -10464,6 +11154,23 @@ async function readConversationFeedBriefs(db, conversationIds) {
10464
11154
  }).from(juniorConversations).innerJoinLateral(latest, sql`true`).where(inArray(juniorConversations.conversationId, conversationIds));
10465
11155
  return new Map(rows.map(({ conversationId, ...brief }) => [conversationId, conversationFeedBriefSchema.parse(brief)]));
10466
11156
  }
11157
+ // src/api/page-cursor.ts
11158
+ /**
11159
+ * Encode the position after the last row of a page as an opaque `cursor`
11160
+ * value. The cursor only moves a position inside a list that access already
11161
+ * scopes, so it carries no signature.
11162
+ */
11163
+ function encodePageCursor(schema, position) {
11164
+ return Buffer.from(JSON.stringify(schema.parse(position)), "utf8").toString("base64url");
11165
+ }
11166
+ /** Decode a `cursor` query value with its schema, or answer 400. */
11167
+ function decodePageCursor(schema, value, message) {
11168
+ try {
11169
+ return schema.parse(JSON.parse(Buffer.from(value, "base64url").toString("utf8")));
11170
+ } catch (error) {
11171
+ throwApiError(400, message, error);
11172
+ }
11173
+ }
10467
11174
  // src/api/conversations/feed-cursor.ts
10468
11175
  /**
10469
11176
  * Position after the last row of one feed page. `at` keeps the microseconds
@@ -10476,18 +11183,11 @@ const conversationFeedCursorSchema = z.object({
10476
11183
  }).strict();
10477
11184
  /** Encode the feed position after one row for `nextCursor`. */
10478
11185
  function encodeConversationFeedCursor(cursor) {
10479
- return Buffer.from(JSON.stringify(cursor), "utf8").toString("base64url");
11186
+ return encodePageCursor(conversationFeedCursorSchema, cursor);
10480
11187
  }
10481
- /**
10482
- * Decode a `cursor` query value. The cursor only moves the position inside a
10483
- * feed that membership already scopes, so it carries no signature.
10484
- */
11188
+ /** Decode a feed `cursor` query value. */
10485
11189
  function decodeConversationFeedCursor(value) {
10486
- try {
10487
- return conversationFeedCursorSchema.parse(JSON.parse(Buffer.from(value, "base64url").toString("utf8")));
10488
- } catch (error) {
10489
- throwApiError(400, "Invalid conversation feed cursor.", error);
10490
- }
11190
+ return decodePageCursor(conversationFeedCursorSchema, value, "Invalid conversation feed cursor.");
10491
11191
  }
10492
11192
  // src/api/conversations/list.ts
10493
11193
  const CONVERSATION_FEED_LIMIT = 50;
@@ -10858,4 +11558,4 @@ function viewerWebMessages(messages, viewer) {
10858
11558
  }] : [];
10859
11559
  });
10860
11560
  }
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 };
11561
+ export { readObjectLinkTypes as $, isAllowedSignInEmail as A, runAutoArchiveSweep as B, encodeConversationCursor as C, getThreadStopDecision as Ct, resolveMentions as D, IMAGE_WIDTHS as Dt, requireConversationPendingMessages as E, createViewerMcp as Et, actOnReviewItem as F, readSavingsRefill as G, DEFAULT_USER_SETTINGS as H, closeReviewItemsAnsweredByReply as I, backfillCacheWarmingGaps as J, runSavingsRefillSlice as K, readReviewItemForUser as L, resolveAllowedDomains as M, stopConversation as N, assertNoLegacyAllowedDomains as O, decodeImageId as Ot, ReviewItemActionError as P, readLinkObjectType as Q, reviewItemChange as R, decodeConversationCursor as S, SubscribedReplyReason as St, readConversationPendingMessages as T, readFirstHumanMessageTexts as Tt, readUserSettings as U, setConversationAutoArchive as V, updateUserSettings as W, readHealthReport as X, GET as Y, OBJECT_LINK_TTL_MS as Z, readConversationEvents as _, createSlackWebApiStatusSender as _t, decodePageCursor as a, createProductionConversationWorkOptions as at, createConversationForViewer as b, stripLeadingBotMention as bt, reorderPinnedConversations as c, buildSlackInboundMessage as ct, childAgentTotalsReport as d, normalizeIncomingSlackThreadId as dt, resolveObjectLinkNow as et, readConversationTreeMetricsFromSql as f, withNormalizedThreadId as ft, keepQuickQuestionForViewer as g, recordSkippedConversationMessage as gt, forkConversationForViewer as h, failStoppedDispatch as ht, readConversationFeed as i, publicAddressLookup as it, readEnvList as j, isAllowedDomain as k, readConversationDetail as l, clearSlackPendingReactions as lt, readConversationDetailEtag as m, enqueueAgentDispatch as mt, steerConversationPendingMessagesForViewer as n, guardedFetch as nt, encodePageCursor as o, createProductionSlackWebhookServices as ot, conversationVersionQuery as p, AGENT_DISPATCH_MAX_AGE_MS as pt, startSavingsRefill as q, conversationFeedVersionQuery as r, isPublicAddress as rt, pinConversation as s, getProductionSlackAdapter as st, stopConversationTurnForViewer as t, resolveObjectLinks as tt, readConversationAuxiliaryCostsFromSql as u, slackInboundMessageId as ut, readConversationRecordFromSql as v, bindMessageAuthorIdentityId as vt, cancelConversationPendingMessagesForViewer as w, conversationSummaryFromStoredConversation as wt, requireWebMessageConversation as x, parseContent as xt, appendConversationMessageForViewer as y, startProcessingReaction as yt, archiveViewerDoneConversations as z };