@sentry/junior 0.276.0 → 0.278.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 (80) hide show
  1. package/dist/{adapter-DoPR2jS-.js → adapter-BXosqTMx.js} +1 -1
  2. package/dist/{admin-BJTT-kXb.js → admin-Thn7NfOi.js} +1 -1
  3. package/dist/{agent-invocations-CUWrrzkc.js → agent-invocations-D7c4BQGc.js} +6 -2
  4. package/dist/{agent-runner-sMpA5qGM.js → agent-runner-DE-43MPb.js} +396 -877
  5. package/dist/api/schema.d.ts +2 -2
  6. package/dist/api/schema.js +5 -5
  7. package/dist/api.d.ts +13 -2
  8. package/dist/api.js +132 -61
  9. package/dist/{app-DTj-yAQt.d.ts → app-CHNS-AX2.d.ts} +6 -27
  10. package/dist/app.d.ts +3 -3
  11. package/dist/app.js +65 -57
  12. package/dist/{assistant-reply-DbxKnBQF.js → assistant-reply-pauL6qyn.js} +28 -6
  13. package/dist/{automation-B8_mC68r.js → automation-DphoTRYl.js} +1 -1
  14. package/dist/{background-compaction-queue-Bywqo1WJ.js → background-compaction-queue-CAL4A2y7.js} +2 -2
  15. package/dist/{briefs-IL7QnCCR.js → briefs-4fyPJJEu.js} +5 -6
  16. package/dist/{catalog-runtime--sC2CYLQ.js → catalog-runtime-BoOb5oUv.js} +1 -1
  17. package/dist/cli/chat.d.ts +1 -1
  18. package/dist/cli/chat.js +14 -14
  19. package/dist/cli/check.js +3 -3
  20. package/dist/cli/init.js +0 -2
  21. package/dist/cli/main.js +3 -3
  22. package/dist/cli/plugins.d.ts +1 -1
  23. package/dist/cli/plugins.js +4 -4
  24. package/dist/cli/snapshot-create.js +4 -4
  25. package/dist/cli/upgrade.d.ts +2 -2
  26. package/dist/cli/upgrade.js +3 -3
  27. package/dist/{client-7diKvInp.js → client-v_OVYuHZ.js} +3 -3
  28. package/dist/{config-Cb--cuv-.js → config-o2jLRY5J.js} +24 -99
  29. package/dist/{connections-C4-4fxaE.js → connections-RC4NXAx8.js} +10 -10
  30. package/dist/{conversation-DppJ83Hw.js → conversation-CZfyQvdm.js} +54 -109
  31. package/dist/{conversation-privacy-DTwdT3Pi.js → conversation-privacy-C23M8KaD.js} +1 -1
  32. package/dist/{credential-sync-Sl5RQCkS.js → credential-sync-Dd0WyNfF.js} +13 -13
  33. package/dist/{db-Ck6TXQIx.d.ts → db-BjLzDJCt.d.ts} +1 -1
  34. package/dist/{executor-BFKmqxYe.js → executor-CJfsD0VX.js} +13 -5
  35. package/dist/instrumentation.js +2 -2
  36. package/dist/{logging-B04X_eCB.js → logging-dFaXvBRK.js} +4 -2
  37. package/dist/{media-DstkkoNP.js → media-DTAA8Qs_.js} +21 -23
  38. package/dist/{message-DQMFyyE-.js → message-DSwxIZet.js} +22 -28
  39. package/dist/nitro.d.ts +2 -2
  40. package/dist/nitro.js +7 -3
  41. package/dist/{oauth-callback-server-BGq0_vQI.js → oauth-callback-server-CDcuCp27.js} +2 -2
  42. package/dist/{plugins-B_0Cr0MO.d.ts → plugins-DtmjkTza.d.ts} +1 -0
  43. package/dist/{projection-6dXaN0n-.js → projection-BTge9wrH.js} +5426 -5300
  44. package/dist/{prompt-B4fQKGZR.js → prompt-DDtCnlHP.js} +1 -1
  45. package/dist/{registry-CEqKR_ld.js → registry-Cp6CNmtP.js} +24 -8
  46. package/dist/{resolve-8I5DkrfI.js → resolve-B_7h2cXx.js} +3 -3
  47. package/dist/{result-BgAW90IM.js → result-5LBEfnLX.js} +9 -9
  48. package/dist/{runner-CSKDr_19.js → runner-C5-S4oq-.js} +11 -11
  49. package/dist/{sandbox-egress-signals-BxAT276e.js → sandbox-egress-signals-B4GehT1L.js} +1 -1
  50. package/dist/{schema-Cal-EFdi.js → schema-B5fpczDw.js} +82 -4
  51. package/dist/{schema-CaUWl2EV.d.ts → schema-Tr484cCC.d.ts} +935 -688
  52. package/dist/{service-account-CUuVJCKT.js → service-account-BkEv20zf.js} +3 -3
  53. package/dist/{service-account-CtOab1Xz.js → service-account-Cq_dLrZJ.js} +3 -3
  54. package/dist/{session-stop-DK8LuPZW.js → session-stop-BsS4qFS2.js} +26 -16
  55. package/dist/{skills-Bc0D7BGy.js → skills-M0BA0_s6.js} +2 -2
  56. package/dist/{spawn-DF_GUcd8.js → spawn-BO3y7H4d.js} +2 -3
  57. package/dist/{stop-DthSy-z8.js → stop-D5R82Wla.js} +612 -186
  58. package/dist/{store-C5uVTx2G.js → store-BGBzQWNf.js} +9 -16
  59. package/dist/{store-BgH2P3X9.js → store-CGJZTEVz.js} +3 -3
  60. package/dist/{task-queue-C6ROM_XJ.js → task-queue-UD27ei2U.js} +3 -3
  61. package/dist/{task-runner-BwAkjjVE.js → task-runner-noxjOjkM.js} +7 -7
  62. package/dist/{thread-state-BXjgk1pW.js → thread-state-BSu6rM6p.js} +4 -4
  63. package/dist/{turn-failure-response-CVI57qKL.js → turn-failure-response-wahwyPrZ.js} +7 -7
  64. package/dist/{turn-lifecycle-CF6ibonp.js → turn-lifecycle-Bo4Trccw.js} +1 -1
  65. package/dist/{turn-session-routing-DddybdNu.js → turn-session-routing-DnSaaEpn.js} +10 -10
  66. package/dist/{validation-BxF1nQbC.js → validation-B9-8iKyw.js} +1 -1
  67. package/dist/{version-CTzSbCmR.js → version-C7HejFP2.js} +1 -1
  68. package/dist/version.js +1 -1
  69. package/dist/{viewer-CQwBszc7.js → viewer-DLXajQZE.js} +94 -28
  70. package/dist/{work-BHlShEQ6.js → work-DRGSlfia.js} +12 -17
  71. package/dist/{worker-DhY9MnsH.js → worker-BGh5Dwc6.js} +6 -6
  72. package/migrations/0074_conversation_participant_pins.sql +1 -0
  73. package/migrations/0075_conversation_detail_version.sql +1 -0
  74. package/migrations/0076_conversation_auto_archive.sql +5 -0
  75. package/migrations/meta/0074_snapshot.json +4076 -0
  76. package/migrations/meta/0075_snapshot.json +4083 -0
  77. package/migrations/meta/0076_snapshot.json +4147 -0
  78. package/migrations/meta/_journal.json +21 -0
  79. package/package.json +5 -5
  80. package/dist/model-profile-B998sjVd.js +0 -67
@@ -1,46 +1,45 @@
1
- import { $ as loadTurnCheckpoint, $a as listConversationAnnotations, $n as listReplyActionItems, A as buildConversationContext, Aa as createPluginLogger, Bn as getPlugins, D as fallbackShortTitle, Dn as createUserTokenStore, F as markConversationMessage, Fa as conversationHasParticipantUser, G as AuthorizationFlowDisabledError, Ga as notInheritedByForkChild, Ha as readConversationEventPage, Ht as buildTurnErrorResponse, I as normalizeConversationText, Ia as conversationIsMemberRoot, Ja as readAttachmentVisionSummary, Ji as SlackActionError, Ka as getSlackFileId, Kr as truncateStatusText, Kt as persistWithRetry, L as recordDeliveredAssistantMessage, La as conversationNotArchivedForEmail, M as estimateConversationContextTokens, Ma as conversationArchiveTimes, N as getConversationMessageSlackTs, Na as conversationArchivedForEmail, P as isHumanConversationMessage, Pa as conversationArchivedForUser, Qi as getSlackClient, R as turnHasReply, Ra as conversationNotArchivedForUser, S as persistConversationMessages, T as resolveConversationTitle, Tn as isExperimentalFeatureEnabled, Ua as buildSentryConversationUrl, V as PluginCredentialFailureError, Va as readLatestConversationBrief, Wr as normalizeSlackStatusText, Y as clearPendingAuth, Ya as recordSlackAttachment, Yi as downloadPrivateSlackFile, Z as wasPendingAuthStopped, Zi as getHeaderString, Zn as getReviewItem, _ as recordSubscribedReplyRoute, _n as getThreadStopDecision, ar as canActOnReviewItem, at as listTurnSummaries, cn as trimTrailingAssistantMessages, co as piMessageFromHistoryItem, cr as isOnlyAssignee, ea as isDmChannel, ei as removeReactionFromMessage, eo as listConversationAnnotationsById, et as saveTurnCheckpoint, fn as buildDeterministicAssistantMessageId, fr as reviewItemReaderForUser, gn as getSubscribedReplyPreflightDecision, hn as decideSubscribedThreadReply, i as loadConversationProjection, io as createPluginCache, it as getTurnRecord, j as createConversationMemoryService, ja as readConversationAccessFromSql, ji as cancelSubscriptions, k as appendThreadContextMessages, kn as webActorUserIds, n as commitMessages, nr as takeReviewItem, nt as completeTurnRecord, o as loadProjection, oo as configValueSchema, ot as recordTurnSummary, p as recordAuthorizationCompleted, pn as buildDeterministicTurnId, qi as verifyTimerWatchCredentialSubject, qn as closeReviewItem, qr as addReactionToMessage, ra as withSlackRetries, ro as lookupSlackUser, rt as failTurnRecord, s as loadTurnProjection, sa as JUNIOR_THREAD_STATE_TTL_MS, sr as canReadReviewItem, t as commitAcceptedReply, ta as normalizeSlackConversationId, tt as abandonTurnRecord, w as persistConversationMessageSummaries, x as hydrateConversationMessages, z as upsertConversationMessage, za as viewerConversationMembership } from "./projection-6dXaN0n-.js";
2
- import { a as completeText, b as isProviderRetryError, c as resolveGatewayModel, m as escapeXml, r as completeDecision } from "./client-7diKvInp.js";
3
- import { _ as normalizeSlackEmojiName, c as getSlackClientSecret, i as getChatConfig, l as getSlackSigningSecret, n as botConfig, o as getSlackBotToken, s as getSlackClientId, v as createS3AttachmentStorage } from "./config-Cb--cuv-.js";
4
- import { E as withSpan, H as isRecord, S as setTags, T as withLogContext, U as toOptionalNumber, W as toOptionalString, b as setSpanAttributes, f as logError, h as logWarn, m as logInfo, n as createChatSdkLogger, o as getActiveTraceContext, p as logException, s as getActiveTraceId, t as buildTurnFailureResponse, y as setSentryUser } from "./logging-B04X_eCB.js";
1
+ import { $ as completeTurnRecord, $a as recordSlackAttachment, $n as takeReviewItem, A as getConversationMessageSlackTs, Ai as removeReactionFromMessage, Ba as readConversationViewerMarks, Ci as addReactionToMessage, D as buildConversationContext, E as appendThreadContextMessages, En as webActorUserIds, F as turnHasReply, Fa as conversationIsMemberRoot, Fi as SlackActionError, Ga as readConversationEventPageAfter, H as AuthorizationFlowDisabledError, Hi as normalizeSlackConversationId, I as upsertConversationMessage, Ia as conversationNotArchivedForEmail, Ii as downloadPrivateSlackFile, J as wasPendingAuthStopped, Jn as getReviewItem, K as clearPendingAuth, Ka as readConversationEventPageAround, La as conversationNotArchivedForUser, Ln as getPlugins, Lr as verifyTimerWatchCredentialSubject, M as markConversationMessage, Ma as conversationArchivedForEmail, N as normalizeConversationText, Na as conversationArchivedForUser, O as createConversationMemoryService, P as recordDeliveredAssistantMessage, Pa as conversationHasParticipantUser, Q as abandonTurnRecord, Qa as readAttachmentVisionSummary, R as PluginCredentialFailureError, Ra as conversationPinnedForUser, Ri as getHeaderString, Rr as JUNIOR_THREAD_STATE_TTL_MS, S as resolveConversationTitle, Si as truncateStatusText, Sn as isExperimentalFeatureEnabled, Ua as readLatestConversationBrief, Ut as persistWithRetry, Va as viewerConversationMembership, Vi as isDmChannel, Wa as readConversationEventPage, Wi as withSlackRetries, Wn as closeReviewItem, X as loadTurnCheckpoint, Xa as getSlackFileId, Xn as listReplyActionItems, Ya as notInheritedByForkChild, Z as saveTurnCheckpoint, Zn as listWaitingConversations, a as loadProjection, an as trimTrailingAssistantMessages, ar as isOnlyAssignee, bi as normalizeSlackStatusText, co as createPluginCache, d as recordAuthorizationCompleted, et as failTurnRecord, fn as decideSubscribedThreadReply, fo as piMessageFromHistoryItem, h as recordSubscribedReplyRoute, i as loadConversationProjection, io as listConversationAnnotationsById, ir as canReadReviewItem, j as isHumanConversationMessage, ja as readConversationAccessFromSql, k as estimateConversationContextTokens, ka as createPluginLogger, ln as buildDeterministicAssistantMessageId, lr as reviewItemNeedsUser, mn as getThreadStopDecision, n as commitMessages, nr as canActOnReviewItem, nt as listTurnSummaries, o as loadTurnProjection, pn as getSubscribedReplyPreflightDecision, qa as buildSentryConversationUrl, ro as listConversationAnnotations, rt as recordTurnSummary, so as lookupSlackUser, t as commitAcceptedReply, tt as getTurnRecord, un as buildDeterministicTurnId, uo as configValueSchema, ur as reviewItemReaderForUser, v as hydrateConversationMessages, w as fallbackShortTitle, wn as createUserTokenStore, x as persistConversationMessageSummaries, xr as cancelSubscriptions, y as persistConversationMessages, za as conversationViewerMarks, zi as getSlackClient, zt as buildTurnErrorResponse } from "./projection-BTge9wrH.js";
2
+ import { a as completeText, b as isProviderRetryError, c as resolveGatewayModel, m as escapeXml, r as completeDecision } from "./client-v_OVYuHZ.js";
3
+ import { c as getSlackClientSecret, i as getChatConfig, l as getSlackSigningSecret, n as botConfig, o as getSlackBotToken, s as getSlackClientId, v as normalizeSlackEmojiName, y as createS3AttachmentStorage } from "./config-o2jLRY5J.js";
4
+ import { E as withSpan, G as toOptionalNumber, K as toOptionalString, S as setTags, T as withLogContext, W as isRecord, b as setSpanAttributes, f as logError, h as logWarn, m as logInfo, n as createChatSdkLogger, o as getActiveTraceContext, p as logException, s as getActiveTraceId, t as buildTurnFailureResponse, y as setSentryUser } from "./logging-dFaXvBRK.js";
5
5
  import { i as getActiveSpan, r as continueTrace } from "./sentry-MDkYAVPV.js";
6
- import { i as defaultModelId } from "./model-profile-B998sjVd.js";
7
6
  import { f as parseSlackTeamId, h as parseSlackMessageTs, i as isActorUserId, n as createSlackActor, o as isUserActor, r as createSlackResumeActor, s as parseActorUserId, t as createActor, u as parseSlackChannelId } from "./actor-B4DYygOB.js";
8
- import { A as locationFromRow, C as getSqlExecutor, D as loadConversationSlackTenantIds, E as withConversationEventLock, J as hasAgentTurnUsage, N as resolveActorIdentityId, P as saveActorAvatar, Q as requireSlackDestination, S as getDb, U as parseSessionSource, W as addAgentTurnUsage, X as createSlackDestination, Y as resolveRootConversationId, f as identityAvatarUrl, h as readUserAvatarUrls, q as agentTurnUsageSchema, x as getConversationStore, y as getConversationEventStore } from "./viewer-CQwBszc7.js";
9
- import { c as juniorIdentities, d as juniorDestinations, l as juniorUsers, o as conversationReadColumns, s as juniorConversations } from "./agent-invocations-CUWrrzkc.js";
10
- import { C as juniorCodeChanges, _ as juniorConversationBriefs, b as juniorConversationEvents, h as juniorConversationParticipants, m as juniorConversationReadPositions } from "./executor-BFKmqxYe.js";
11
- import { g as instructionProvenanceFor, m as contextProvenance, n as detectImageMediaType, r as isVisionImageMediaType } from "./media-DstkkoNP.js";
12
- import { d as actorLogContext, f as credentialContextForActor } from "./registry-CEqKR_ld.js";
13
- import { A as runWithSlackInstallation, At as withoutSavedSteeringMessages, Et as conversationSubtreeColumns, F as resolveSlackChannelIdFromThreadId, I as getConversationInfo, J as readConversationSourceTask, Lt as shouldEmitDevAgentTrace, M as parseSlackThreadId, N as readSlackRawMessageContext, Nt as RetryableDeliveryError, P as resolveSlackChannelIdFromMessage, R as listThreadReplies, Tt as conversationSubtree, a as buildAuthPauseResponse, b as renderAttachmentText, dt as recordWebConversationActivity, ft as webActorFromUser, i as measureTurnCompactionWait, kt as buildSteeringPiMessage, m as latestProgressStatus, n as executeAgentRun, pt as resolveConversationDestination, rt as deliverReviewItemChange, t as createAgentRunner, ut as createConversationId, vt as storeAttachment, x as renderBlockText, z as resolveDestinationVisibility } from "./agent-runner-sMpA5qGM.js";
7
+ import { $ as agentTurnUsageSchema, A as loadConversationSlackTenantIds, C as getSqlExecutor, I as resolveActorIdentityId, J as nextDetailVersion, K as parseSessionSource, L as saveActorAvatar, N as locationFromRow, S as getDb, X as addAgentTurnUsage, et as hasAgentTurnUsage, f as identityAvatarUrl, h as readUserAvatarUrls, it as requireSlackDestination, k as withConversationEventLock, nt as createSlackDestination, q as conversationDetailTouch, tt as resolveRootConversationId, x as getConversationStore, y as getConversationEventStore } from "./viewer-DLXajQZE.js";
8
+ import { c as juniorIdentities, d as juniorDestinations, l as juniorUsers, o as conversationReadColumns, s as juniorConversations } from "./agent-invocations-D7c4BQGc.js";
9
+ import { C as juniorCodeChanges, _ as juniorConversationBriefs, b as juniorConversationEvents, c as juniorReviewItems, h as juniorConversationParticipants, m as juniorConversationReadPositions, o as juniorReviewItemConversations } from "./executor-CJfsD0VX.js";
10
+ import { g as instructionProvenanceFor, m as contextProvenance, n as detectImageMediaType, r as isVisionImageMediaType } from "./media-DTAA8Qs_.js";
11
+ import { d as actorLogContext, f as credentialContextForActor } from "./registry-Cp6CNmtP.js";
12
+ import { A as runWithSlackInstallation, At as withoutSavedSteeringMessages, Et as conversationSubtreeColumns, F as resolveSlackChannelIdFromThreadId, I as getConversationInfo, J as readConversationSourceTask, Lt as shouldEmitDevAgentTrace, M as parseSlackThreadId, N as readSlackRawMessageContext, Nt as RetryableDeliveryError, P as resolveSlackChannelIdFromMessage, R as listThreadReplies, Tt as conversationSubtree, a as buildAuthPauseResponse, b as renderAttachmentText, dt as recordWebConversationActivity, ft as webActorFromUser, i as measureTurnCompactionWait, kt as buildSteeringPiMessage, m as latestProgressStatus, n as executeAgentRun, pt as resolveConversationDestination, rt as deliverReviewItemChange, t as createAgentRunner, ut as createConversationId, vt as storeAttachment, x as renderBlockText, z as resolveDestinationVisibility } from "./agent-runner-DE-43MPb.js";
14
13
  import { a as withLock, n as MUTATION_LOCK_TTL_MS, r as acquireActiveLock } from "./locks-D-0h111u.js";
15
- import { r as getStateAdapter } from "./adapter-DoPR2jS-.js";
16
- import { K as readMessageAttachments, d as conversationDetailReportSchema, g as conversationFeedSchema } from "./conversation-DppJ83Hw.js";
17
- import { a as EVENT_SYSTEM_ACTOR, o as isEventConversationMessage } from "./prompt-B4fQKGZR.js";
18
- import { $ as markTurnFailed, G as TurnInputCommitLostError, J as isCooperativeTurnYieldError, K as TurnInputDeferredError, Q as markTurnCompleted, U as ConversationTurnBoundaryError, W as CooperativeTurnYieldError, X as isTurnInputDeferredError, Y as isTurnInputCommitLostError, Z as markTurnClosed, et as startActiveTurn, h as getChildAgentLabel, q as getConversationTurnBoundaryError } from "./store-C5uVTx2G.js";
19
- import { n as getAssistantReplyText } from "./assistant-reply-DbxKnBQF.js";
20
- import { C as savedTurnInputMessages, E as maybePostAutomatedTurnLimitNotice, I as deliversFinalText, L as finishedRunReply, M as recordFinishedTurnForAutomatedLimit, O as resolveSlackReplyTarget, R as postsRunNotices, S as joinMailboxText, V as runDispatchOutcome, c as isEventMailboxMetadata, i as skipInputBeforeConversationStop, k as sendSlackReply, l as renderEventBatchText, s as eventBatchMessageMeta, u as timerWatchCredentialSubject, w as webConversationMessage } from "./session-stop-DK8LuPZW.js";
14
+ import { r as getStateAdapter } from "./adapter-BXosqTMx.js";
15
+ import { R as readMessageAttachments, c as conversationDetailReportSchema, p as conversationFeedSchema, u as conversationEventPageSchema } from "./conversation-CZfyQvdm.js";
16
+ import { a as EVENT_SYSTEM_ACTOR, o as isEventConversationMessage } from "./prompt-DDtCnlHP.js";
17
+ import { $ as markTurnFailed, G as TurnInputCommitLostError, J as isCooperativeTurnYieldError, K as TurnInputDeferredError, Q as markTurnCompleted, U as ConversationTurnBoundaryError, W as CooperativeTurnYieldError, X as isTurnInputDeferredError, Y as isTurnInputCommitLostError, Z as markTurnClosed, et as startActiveTurn, h as getChildAgentLabel, q as getConversationTurnBoundaryError } from "./store-BGBzQWNf.js";
18
+ import { n as getAssistantReplyText, t as decideReply } from "./assistant-reply-pauL6qyn.js";
19
+ import { C as savedTurnInputMessages, E as maybePostAutomatedTurnLimitNotice, I as deliversFinalText, L as finishedRunReply, M as recordFinishedTurnForAutomatedLimit, O as resolveSlackReplyTarget, R as postsRunNotices, S as joinMailboxText, V as runDispatchOutcome, c as isEventMailboxMetadata, i as skipInputBeforeConversationStop, k as sendSlackReply, l as renderEventBatchText, s as eventBatchMessageMeta, u as timerWatchCredentialSubject, w as webConversationMessage } from "./session-stop-BsS4qFS2.js";
21
20
  import { _ as isEmptyUserInputAnswer, v as normalizeUserInputAnswer } from "./reporting-window-DgHgwQB3.js";
22
- import { g as getTurnRequestDeadline, l as getVercelConversationWorkQueue } from "./background-compaction-queue-Bywqo1WJ.js";
23
- import { D as stopConversationWork, g as getConversationWorkState, h as getConversation, m as ensureConversationWake, r as appendAndEnqueueInboundMessage, w as requestConversationWork } from "./store-BgH2P3X9.js";
24
- import { _ as markDispatchCompleted, a as confirmDispatchMailboxAppend, d as getDispatchTurnId, g as markDispatchBlocked, h as markDispatchAwaitingResume, i as claimDispatchMailboxAppend, j as readAutomationTitlesByConversationId, l as getDispatchInputMessageId, n as resolveTurnSessionRouting, p as isTerminalDispatchStatus, s as getDispatchConversationId, t as resolveConversationRouting, u as getDispatchRecord, v as markDispatchFailed, y as markDispatchRunning } from "./turn-session-routing-DddybdNu.js";
21
+ import { g as getTurnRequestDeadline, l as getVercelConversationWorkQueue } from "./background-compaction-queue-CAL4A2y7.js";
22
+ import { D as stopConversationWork, g as getConversationWorkState, h as getConversation, m as ensureConversationWake, r as appendAndEnqueueInboundMessage, w as requestConversationWork } from "./store-CGJZTEVz.js";
23
+ import { _ as markDispatchCompleted, a as confirmDispatchMailboxAppend, d as getDispatchTurnId, g as markDispatchBlocked, h as markDispatchAwaitingResume, i as claimDispatchMailboxAppend, j as readAutomationTitlesByConversationId, l as getDispatchInputMessageId, n as resolveTurnSessionRouting, p as isTerminalDispatchStatus, s as getDispatchConversationId, t as resolveConversationRouting, u as getDispatchRecord, v as markDispatchFailed, y as markDispatchRunning } from "./turn-session-routing-DnSaaEpn.js";
25
24
  import { n as healthReportSchema, t as apiErrorSchema } from "./common-Eu6sx09c.js";
26
- import { a as withAgentInvocationResultActors, c as listActiveMailboxTurns, d as turnInputFactsFromConversationMessage, f as legacyWebMailboxMetadataSchema, l as resolveMailboxTurnWork, n as enqueueAgentInvocationResult, o as getAuthPausedConversationTurnId, s as getEventBatchDelayMs, t as createChildConversationWorker, u as sourceFromTurnInput } from "./result-BgAW90IM.js";
27
- import { n as getTurnLifecycle, t as ConversationTurnLifecycleService } from "./turn-lifecycle-CF6ibonp.js";
28
- import { o as AgentRunError, s as executeTurn } from "./work-BHlShEQ6.js";
29
- import { a as persistThreadStateById, i as persistThreadRuntimeState, n as getPersistedSandboxState, o as coerceThreadConversationState, r as getPersistedThreadState, t as getLocationConfigurationService } from "./thread-state-BXjgk1pW.js";
30
- import { c as deleteWebAuthorization, d as createPausedTurns, f as getPausedTurnRequest, h as getTurnAuthorization, m as wakePausedTurn, s as createWebAuthorization } from "./connections-C4-4fxaE.js";
31
- import { t as bindMessageAgent } from "./message-DQMFyyE-.js";
32
- import { t as bindSpawnAgent } from "./spawn-DF_GUcd8.js";
33
- import { n as scheduleSessionCompletedPluginTasks, t as processPluginTask } from "./task-runner-BwAkjjVE.js";
34
- import { a as persistAuthPauseTurnState, c as getTurnUserSlackMessageTs, i as completeAuthPauseTurn, l as buildDeliveredTurnStatePatch, n as getAgentTurnDiagnosticsAttributes, o as getTurnUserMessage, r as requireTurnFailureEventId, s as getTurnUserReplyAttachmentContext, t as finalizeFailedTurnReplyWithEvent, u as loadPendingMessageCards } from "./turn-failure-response-CVI57qKL.js";
25
+ import { a as withAgentInvocationResultActors, c as listActiveMailboxTurns, d as turnInputFactsFromConversationMessage, f as legacyWebMailboxMetadataSchema, l as resolveMailboxTurnWork, n as enqueueAgentInvocationResult, o as getAuthPausedConversationTurnId, s as getEventBatchDelayMs, t as createChildConversationWorker, u as sourceFromTurnInput } from "./result-5LBEfnLX.js";
26
+ import { n as getTurnLifecycle, t as ConversationTurnLifecycleService } from "./turn-lifecycle-Bo4Trccw.js";
27
+ import { o as AgentRunError, s as executeTurn } from "./work-DRGSlfia.js";
28
+ import { a as persistThreadStateById, i as persistThreadRuntimeState, n as getPersistedSandboxState, o as coerceThreadConversationState, r as getPersistedThreadState, t as getLocationConfigurationService } from "./thread-state-BSu6rM6p.js";
29
+ import { c as deleteWebAuthorization, d as createPausedTurns, f as getPausedTurnRequest, h as getTurnAuthorization, m as wakePausedTurn, s as createWebAuthorization } from "./connections-RC4NXAx8.js";
30
+ import { t as bindMessageAgent } from "./message-DSwxIZet.js";
31
+ import { t as bindSpawnAgent } from "./spawn-BO3y7H4d.js";
32
+ import { n as scheduleSessionCompletedPluginTasks, t as processPluginTask } from "./task-runner-noxjOjkM.js";
33
+ import { a as persistAuthPauseTurnState, c as getTurnUserSlackMessageTs, i as completeAuthPauseTurn, l as buildDeliveredTurnStatePatch, n as getAgentTurnDiagnosticsAttributes, o as getTurnUserMessage, r as requireTurnFailureEventId, s as getTurnUserReplyAttachmentContext, t as finalizeFailedTurnReplyWithEvent, u as loadPendingMessageCards } from "./turn-failure-response-wahwyPrZ.js";
35
34
  import { createHash, createHmac, timingSafeEqual } from "node:crypto";
36
35
  import { z } from "zod";
37
- import { and, asc, desc, eq, inArray, isNotNull, isNull, max, or, sql } from "drizzle-orm";
36
+ import { and, asc, desc, eq, gt, inArray, isNotNull, isNull, lte, max, ne, or, sql } from "drizzle-orm";
38
37
  import { conversationSidebarAnnotationSchema, createSlackSource, objectTypeSchema } from "@sentry/junior-plugin-api";
39
38
  import { alias } from "drizzle-orm/pg-core";
40
39
  import { del, get, put } from "@vercel/blob";
40
+ import { HTTPException } from "hono/http-exception";
41
41
  import { Message, ThreadImpl, stringifyMarkdown } from "chat";
42
42
  import { SlackFormatConverter, createSlackAdapter } from "@chat-adapter/slack";
43
- import { HTTPException } from "hono/http-exception";
44
43
  // src/handlers/health.ts
45
44
  /** Build Junior's process health value for HTTP and reporting consumers. */
46
45
  function readHealthReport() {
@@ -381,6 +380,306 @@ function createAttachmentStorage(config) {
381
380
  default: throw new Error(`Unsupported attachment storage provider: ${String(config.provider)}`);
382
381
  }
383
382
  }
383
+ // src/chat/plugins/unfinished-work.ts
384
+ /**
385
+ * Return assigned and unfinished plugin work for the candidate conversations.
386
+ * Feed Priority combines these signals with conversation activity on the host.
387
+ */
388
+ async function listConversationWork(conversationIds) {
389
+ if (conversationIds.length === 0) return {
390
+ assignedIds: [],
391
+ finishedAtById: {},
392
+ unfinishedIds: []
393
+ };
394
+ const candidates = new Set(conversationIds);
395
+ const assigned = /* @__PURE__ */ new Set();
396
+ const finishedAtById = /* @__PURE__ */ new Map();
397
+ const unfinished = /* @__PURE__ */ new Set();
398
+ for (const plugin of getPlugins()) {
399
+ const hook = plugin.hooks?.unfinishedWork;
400
+ if (!hook) continue;
401
+ try {
402
+ const result = await hook({
403
+ conversationIds,
404
+ db: getDb(),
405
+ log: createPluginLogger(plugin.manifest.name),
406
+ plugin: { name: plugin.manifest.name },
407
+ cache: createPluginCache(plugin.manifest.name)
408
+ });
409
+ for (const conversationId of result.conversationIds) {
410
+ if (!candidates.has(conversationId)) continue;
411
+ unfinished.add(conversationId);
412
+ assigned.add(conversationId);
413
+ }
414
+ for (const conversationId of result.assignedConversationIds ?? []) if (candidates.has(conversationId)) assigned.add(conversationId);
415
+ for (const [conversationId, finishedAt] of Object.entries(result.finishedWorkAtByConversationId ?? {})) {
416
+ if (!candidates.has(conversationId)) continue;
417
+ const time = Date.parse(finishedAt);
418
+ if (!Number.isFinite(time)) continue;
419
+ const current = finishedAtById.get(conversationId);
420
+ if (!current || time > Date.parse(current)) finishedAtById.set(conversationId, finishedAt);
421
+ }
422
+ } catch (error) {
423
+ logWarn("plugin.unfinished_work.hook.failed", {
424
+ "app.plugin.name": plugin.manifest.name,
425
+ "exception.message": error instanceof Error ? error.message : String(error)
426
+ });
427
+ }
428
+ }
429
+ return {
430
+ assignedIds: conversationIds.filter((conversationId) => assigned.has(conversationId)),
431
+ finishedAtById: Object.fromEntries(conversationIds.flatMap((conversationId) => {
432
+ const finishedAt = finishedAtById.get(conversationId);
433
+ return finishedAt ? [[conversationId, finishedAt]] : [];
434
+ })),
435
+ unfinishedIds: conversationIds.filter((conversationId) => unfinished.has(conversationId))
436
+ };
437
+ }
438
+ // src/api/http.ts
439
+ const NO_STORE_HEADERS = { "cache-control": "no-store" };
440
+ /** Build response init that keeps personalized API payloads out of shared caches. */
441
+ function noStoreInit(init) {
442
+ if (!init) return { headers: NO_STORE_HEADERS };
443
+ const headers = new Headers(init.headers);
444
+ if (!headers.has("cache-control")) headers.set("cache-control", "no-store");
445
+ return {
446
+ ...init,
447
+ headers
448
+ };
449
+ }
450
+ /** Serialize a REST response only after it satisfies its declared schema. */
451
+ function jsonResponse(schema, value, init) {
452
+ return Response.json(schema.parse(value), noStoreInit(init));
453
+ }
454
+ /** Return an empty personalized API response with no-store caching. */
455
+ function emptyResponse(status = 204) {
456
+ return new Response(null, noStoreInit({ status }));
457
+ }
458
+ /** Stop a request with Junior's stable JSON error contract. */
459
+ function throwApiError(status, message, cause) {
460
+ throw new HTTPException(status, {
461
+ ...cause === void 0 ? void 0 : { cause },
462
+ message,
463
+ res: jsonResponse(apiErrorSchema, { error: message }, { status })
464
+ });
465
+ }
466
+ // src/api/conversations/user-message-activity.ts
467
+ /** Read the latest true user message time for each selected conversation. */
468
+ async function readLastUserMessageAtByConversation(db, conversationIds) {
469
+ if (conversationIds.length === 0) return /* @__PURE__ */ new Map();
470
+ const authority = sql`${juniorConversationEvents.payload}->'provenance'->>'authority'`;
471
+ const actorPlatform = sql`${juniorConversationEvents.payload}->'provenance'->'actor'->>'platform'`;
472
+ const role = sql`${juniorConversationEvents.payload}->>'role'`;
473
+ const rows = await db.select({
474
+ conversationId: juniorConversationEvents.conversationId,
475
+ lastUserMessageAt: sql`max(${juniorConversationEvents.createdAt})`
476
+ }).from(juniorConversationEvents).leftJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversationEvents.actorIdentityId)).where(and(inArray(juniorConversationEvents.conversationId, conversationIds), or(and(eq(juniorConversationEvents.type, "user_message"), eq(authority, "instruction"), sql`${actorPlatform} in ('slack', 'local', 'web')`), and(eq(juniorConversationEvents.type, "message"), eq(role, "user"), eq(juniorIdentities.kind, "user"))))).groupBy(juniorConversationEvents.conversationId);
477
+ return new Map(rows.map((row) => [row.conversationId, new Date(row.lastUserMessageAt).toISOString()]));
478
+ }
479
+ // src/api/conversations/auto-archive.ts
480
+ const HOUR_MS = 36e5;
481
+ /** Participant rows checked per page. A run reads pages until none remain. */
482
+ const AUTO_ARCHIVE_PAGE_SIZE = 500;
483
+ /** Settings of a user who has not changed auto-archive. */
484
+ const DEFAULT_AUTO_ARCHIVE_SETTINGS = {
485
+ autoArchiveDefault: false,
486
+ autoArchiveGraceHours: 24
487
+ };
488
+ /**
489
+ * Decide whether a conversation's work is done long enough to auto-archive.
490
+ * Conversations without plugin-reported work are never done.
491
+ */
492
+ function isConversationWorkDone(conversation, cutoffMs) {
493
+ if (!conversation.assignedWork || conversation.unfinishedWork) return false;
494
+ const finishedAt = Date.parse(conversation.finishedWorkAt ?? "");
495
+ if (!Number.isFinite(finishedAt) || finishedAt > cutoffMs) return false;
496
+ const lastUserMessageAt = Date.parse(conversation.lastUserMessageAt ?? "");
497
+ return !(Number.isFinite(lastUserMessageAt) && lastUserMessageAt > finishedAt);
498
+ }
499
+ function runOptsIn(run) {
500
+ return run.kind === "scheduled" ? sql`coalesce(${juniorConversationParticipants.autoArchive}, ${juniorUsers.autoArchiveDefault}) = true` : sql`${juniorConversationParticipants.autoArchive} is distinct from false`;
501
+ }
502
+ function runCutoff(run) {
503
+ return /* @__PURE__ */ new Date(run.now.getTime() - run.graceHours * HOUR_MS);
504
+ }
505
+ /**
506
+ * True when the participant row's root and every child conversation are idle
507
+ * and had no activity after the cutoff. Child activity does not move the
508
+ * root's `lastActivityAt`, so the whole tree is checked.
509
+ */
510
+ function treeIsQuiet(cutoff) {
511
+ const active = getDb().select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(or(eq(juniorConversations.conversationId, juniorConversationParticipants.rootConversationId), eq(juniorConversations.rootConversationId, juniorConversationParticipants.rootConversationId)), or(ne(juniorConversations.executionStatus, "idle"), gt(juniorConversations.lastActivityAt, cutoff))));
512
+ return sql`not exists (${active})`;
513
+ }
514
+ /**
515
+ * True when no open Review item on the participant row's root or a child
516
+ * conversation needs the user. Such a conversation waits on them, so it must
517
+ * stay in their feed.
518
+ */
519
+ function notWaitingOnUser(userId) {
520
+ const linked = alias(juniorConversations, "linked_conversation");
521
+ const waiting = getDb().select({ itemId: juniorReviewItemConversations.itemId }).from(juniorReviewItemConversations).innerJoin(juniorReviewItems, eq(juniorReviewItems.id, juniorReviewItemConversations.itemId)).innerJoin(linked, eq(linked.conversationId, juniorReviewItemConversations.conversationId)).where(and(reviewItemNeedsUser(userId), or(eq(linked.conversationId, juniorConversationParticipants.rootConversationId), eq(linked.rootConversationId, juniorConversationParticipants.rootConversationId))));
522
+ return sql`not exists (${waiting})`;
523
+ }
524
+ /**
525
+ * Conditions that a participant row must meet when it is selected and again
526
+ * when it is archived, so new activity, a new run, a new Review item, or a
527
+ * changed setting wins over a stale read.
528
+ */
529
+ function archivableRow(run) {
530
+ return and(eq(juniorConversationParticipants.userId, run.userId), isNull(juniorConversationParticipants.archivedAt), isNull(juniorConversationParticipants.pinnedAt), lte(juniorConversationParticipants.lastMessageAt, runCutoff(run)), runOptsIn(run), run.kind === "scheduled" ? sql`${juniorUsers.autoArchiveGraceHours} <= ${run.graceHours}` : void 0, treeIsQuiet(runCutoff(run)), notWaitingOnUser(run.userId));
531
+ }
532
+ /**
533
+ * One page of the user's unarchived participant rows that may be done. Pages
534
+ * follow `junior_conversation_participants_unarchived_activity_idx`, so a run
535
+ * reads only rows older than the cutoff. Archive writes during the run do not
536
+ * move `lastMessageAt`, so they do not skip rows.
537
+ */
538
+ async function selectCandidateRoots(run, after) {
539
+ return await getDb().select({
540
+ lastMessageAt: sql`${juniorConversationParticipants.lastMessageAt}::text`,
541
+ rootConversationId: juniorConversationParticipants.rootConversationId
542
+ }).from(juniorConversationParticipants).innerJoin(juniorUsers, eq(juniorUsers.id, juniorConversationParticipants.userId)).where(and(archivableRow(run), after ? sql`(${juniorConversationParticipants.lastMessageAt}, ${juniorConversationParticipants.rootConversationId}) > (${after.lastMessageAt}::timestamptz, ${after.rootConversationId})` : void 0)).orderBy(asc(juniorConversationParticipants.lastMessageAt), asc(juniorConversationParticipants.rootConversationId)).limit(AUTO_ARCHIVE_PAGE_SIZE);
543
+ }
544
+ /**
545
+ * Keep the roots whose work is done. Work comes first because most roots
546
+ * have none, so the message history read covers only finished work.
547
+ */
548
+ async function selectDoneRoots(rootIds, cutoffMs) {
549
+ const work = await listConversationWork(rootIds);
550
+ const unfinished = new Set(work.unfinishedIds);
551
+ const finished = work.assignedIds.filter((id) => !unfinished.has(id) && isConversationWorkDone({
552
+ assignedWork: true,
553
+ finishedWorkAt: work.finishedAtById[id]
554
+ }, cutoffMs));
555
+ if (finished.length === 0) return [];
556
+ const lastUserMessageAtById = await readLastUserMessageAtByConversation(getDb(), finished);
557
+ return finished.filter((id) => isConversationWorkDone({
558
+ assignedWork: true,
559
+ finishedWorkAt: work.finishedAtById[id],
560
+ lastUserMessageAt: lastUserMessageAtById.get(id)
561
+ }, cutoffMs));
562
+ }
563
+ /** Archive one root for the run's user when it is still archivable. */
564
+ async function archiveRoot(run, rootConversationId) {
565
+ return (await getDb().update(juniorConversationParticipants).set({ archivedAt: run.now }).from(juniorUsers).where(and(eq(juniorUsers.id, juniorConversationParticipants.userId), eq(juniorConversationParticipants.rootConversationId, rootConversationId), archivableRow(run))).returning({ userId: juniorConversationParticipants.userId })).length > 0;
566
+ }
567
+ /** Archive every done conversation of one user and count the rows. */
568
+ async function archiveUserDoneConversations(run) {
569
+ const cutoffMs = runCutoff(run).getTime();
570
+ let after;
571
+ let archived = 0;
572
+ let scanned = 0;
573
+ for (;;) {
574
+ const rows = await selectCandidateRoots(run, after);
575
+ if (rows.length === 0) break;
576
+ scanned += rows.length;
577
+ const rootIds = rows.map((row) => row.rootConversationId);
578
+ for (const rootId of await selectDoneRoots(rootIds, cutoffMs)) if (await archiveRoot(run, rootId)) archived += 1;
579
+ if (rows.length < AUTO_ARCHIVE_PAGE_SIZE) break;
580
+ after = rows.at(-1);
581
+ }
582
+ return {
583
+ archived,
584
+ scanned
585
+ };
586
+ }
587
+ /**
588
+ * Users with auto-archive on by default or for at least one unarchived
589
+ * conversation. Most users never turn it on, so the sweep reads only these.
590
+ */
591
+ async function selectAutoArchiveUsers() {
592
+ const optedInConversation = getDb().select({ userId: juniorConversationParticipants.userId }).from(juniorConversationParticipants).where(and(eq(juniorConversationParticipants.userId, juniorUsers.id), eq(juniorConversationParticipants.autoArchive, true), isNull(juniorConversationParticipants.archivedAt)));
593
+ return await getDb().select({
594
+ graceHours: juniorUsers.autoArchiveGraceHours,
595
+ id: juniorUsers.id
596
+ }).from(juniorUsers).where(or(eq(juniorUsers.autoArchiveDefault, true), sql`exists (${optedInConversation})`)).orderBy(asc(juniorUsers.id));
597
+ }
598
+ /**
599
+ * Run one auto-archive sweep over every user who wants it and return how
600
+ * many participant rows it checked and archived.
601
+ */
602
+ async function runAutoArchiveSweep(args) {
603
+ const now = new Date(args.nowMs);
604
+ let archived = 0;
605
+ let scanned = 0;
606
+ for (const user of await selectAutoArchiveUsers()) {
607
+ const result = await archiveUserDoneConversations({
608
+ graceHours: user.graceHours,
609
+ kind: "scheduled",
610
+ now,
611
+ userId: user.id
612
+ });
613
+ archived += result.archived;
614
+ scanned += result.scanned;
615
+ }
616
+ logInfo("auto_archive.sweep.completed", {
617
+ "app.auto_archive.archived": archived,
618
+ "app.auto_archive.scanned": scanned
619
+ });
620
+ return {
621
+ archived,
622
+ scanned
623
+ };
624
+ }
625
+ /**
626
+ * Archive all of the viewer's done conversations now, with no grace period.
627
+ * It skips conversations where the viewer turned auto-archive off.
628
+ */
629
+ async function archiveViewerDoneConversations(viewer) {
630
+ const { archived } = await archiveUserDoneConversations({
631
+ graceHours: 0,
632
+ kind: "manual",
633
+ now: /* @__PURE__ */ new Date(),
634
+ userId: viewer.id
635
+ });
636
+ return { archived };
637
+ }
638
+ /** Read the viewer's effective auto-archive choice for a conversation. */
639
+ async function readConversationAutoArchive(viewer, conversationId) {
640
+ const rootConversationId = await resolveRootConversationId(getSqlExecutor(), conversationId);
641
+ const [user] = await getDb().select({
642
+ autoArchive: juniorConversationParticipants.autoArchive,
643
+ autoArchiveDefault: juniorUsers.autoArchiveDefault
644
+ }).from(juniorUsers).leftJoin(juniorConversationParticipants, and(eq(juniorConversationParticipants.userId, juniorUsers.id), eq(juniorConversationParticipants.rootConversationId, rootConversationId))).where(eq(juniorUsers.id, viewer.id)).limit(1);
645
+ return user?.autoArchive ?? user?.autoArchiveDefault ?? false;
646
+ }
647
+ /** Turn auto-archive on or off for one conversation and the signed-in viewer. */
648
+ async function setConversationAutoArchive(viewer, conversationId, autoArchive) {
649
+ if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(404, "Conversation not found.");
650
+ const rootConversationId = await resolveRootConversationId(getSqlExecutor(), conversationId);
651
+ const [root] = await getDb().select({ lastActivityAt: juniorConversations.lastActivityAt }).from(juniorConversations).where(eq(juniorConversations.conversationId, rootConversationId)).limit(1);
652
+ if (!root) throwApiError(404, "Conversation not found.");
653
+ await getDb().insert(juniorConversationParticipants).values({
654
+ autoArchive,
655
+ lastMessageAt: root.lastActivityAt,
656
+ rootConversationId,
657
+ userId: viewer.id
658
+ }).onConflictDoUpdate({
659
+ target: [juniorConversationParticipants.userId, juniorConversationParticipants.rootConversationId],
660
+ set: { autoArchive }
661
+ });
662
+ return { autoArchive };
663
+ }
664
+ /** Read the user's auto-archive settings. */
665
+ async function readUserAutoArchiveSettings(userId) {
666
+ const [user] = await getDb().select({
667
+ autoArchiveDefault: juniorUsers.autoArchiveDefault,
668
+ autoArchiveGraceHours: juniorUsers.autoArchiveGraceHours
669
+ }).from(juniorUsers).where(eq(juniorUsers.id, userId)).limit(1);
670
+ return user;
671
+ }
672
+ /** Save changed auto-archive settings and return the saved settings. */
673
+ async function updateUserAutoArchiveSettings(userId, settings) {
674
+ const [user] = await getDb().update(juniorUsers).set({
675
+ ...settings,
676
+ updatedAt: /* @__PURE__ */ new Date()
677
+ }).where(eq(juniorUsers.id, userId)).returning({
678
+ autoArchiveDefault: juniorUsers.autoArchiveDefault,
679
+ autoArchiveGraceHours: juniorUsers.autoArchiveGraceHours
680
+ });
681
+ return user;
682
+ }
384
683
  // src/chat/review-items/reply-match.ts
385
684
  const MATCH_CONFIDENCE_THRESHOLD = .7;
386
685
  /** A slow decision keeps the items open instead of delaying the close. */
@@ -2475,17 +2774,13 @@ function countPotentialImageAttachments(attachments) {
2475
2774
  function isVisionEnabled() {
2476
2775
  return Boolean(botConfig.visionModelId);
2477
2776
  }
2478
- /**
2479
- * Report whether every profile model accepts image input. The router picks the
2480
- * profile after attachments resolve, so native images need every profile to
2481
- * read them.
2482
- */
2483
- function profileModelsAcceptImages() {
2484
- return Object.values(botConfig.profiles).every((profile) => resolveGatewayModel(profile.modelId).input.includes("image"));
2777
+ /** Report whether the main agent model accepts image input. */
2778
+ function agentModelAcceptsImages() {
2779
+ return resolveGatewayModel(botConfig.modelId).input.includes("image");
2485
2780
  }
2486
2781
  /** Report whether the agent can read current-message images by any path. */
2487
2782
  function canReadImages() {
2488
- return isVisionEnabled() || profileModelsAcceptImages();
2783
+ return isVisionEnabled() || agentModelAcceptsImages();
2489
2784
  }
2490
2785
  var ImageAttachmentProcessingError = class extends Error {
2491
2786
  constructor(message) {
@@ -2654,7 +2949,7 @@ async function resolveUserAttachmentsWithDeps(attachments, context, deps) {
2654
2949
  }
2655
2950
  continue;
2656
2951
  }
2657
- const nativeImageMediaType = isImageAttachment && profileModelsAcceptImages() ? detectImageMediaType(data) : void 0;
2952
+ const nativeImageMediaType = isImageAttachment && agentModelAcceptsImages() ? detectImageMediaType(data) : void 0;
2658
2953
  if (nativeImageMediaType) {
2659
2954
  nextCachedImageSummaryIndex += 1;
2660
2955
  resolvedAttachment.mediaType = nativeImageMediaType;
@@ -3726,7 +4021,7 @@ function createSlackTurn(deps) {
3726
4021
  destinationName: channelId,
3727
4022
  runId,
3728
4023
  assistantUserName: botConfig.userName,
3729
- modelId: defaultModelId(botConfig)
4024
+ modelId: botConfig.modelId
3730
4025
  }, async () => {
3731
4026
  await getConversationStore().recordActivity({
3732
4027
  activityAtMs: message.metadata.dateSent.getTime(),
@@ -4858,7 +5153,7 @@ function createSlackRuntime(options) {
4858
5153
  assistantUserName: botConfig.userName,
4859
5154
  cancelWatches: cancelSubscriptions,
4860
5155
  getBotUserId: () => options.getSlackAdapter().botUserId,
4861
- modelId: defaultModelId(botConfig),
5156
+ modelId: botConfig.modelId,
4862
5157
  now: options.now ?? (() => Date.now()),
4863
5158
  prepareTurnState,
4864
5159
  persistPreparedState: async ({ conversationId, preparedState }) => {
@@ -5004,7 +5299,7 @@ function getResumeLogContext(args) {
5004
5299
  ...actorLogContext(args.run?.actor, args.run?.credentialContext),
5005
5300
  destinationName: args.channelId,
5006
5301
  assistantUserName: botConfig.userName,
5007
- modelId: defaultModelId(botConfig)
5302
+ modelId: botConfig.modelId
5008
5303
  };
5009
5304
  }
5010
5305
  async function handleResumeFailure(args) {
@@ -6035,6 +6330,7 @@ async function commitAssistantMessage(args) {
6035
6330
  const conversationMessageId = recordDeliveredAssistantMessage({
6036
6331
  cards: args.cards,
6037
6332
  conversation: args.conversation,
6333
+ ...args.quiet ? { quiet: args.quiet } : void 0,
6038
6334
  sessionId: args.sessionId,
6039
6335
  source: args.source,
6040
6336
  text: args.text,
@@ -6250,7 +6546,8 @@ function createConversationTurnWorker(agentRunner, deliverMessage) {
6250
6546
  });
6251
6547
  const webActor = actor.platform === "web" ? actor : void 0;
6252
6548
  const conversationLocation = storedConversation?.location;
6253
- const deliverToProvider = Boolean(conversationLocation) && (source.kind === "event" || savedMessageIsEvent);
6549
+ const isEventTurn = source.kind === "event" || savedMessageIsEvent;
6550
+ const deliverToProvider = Boolean(conversationLocation) && isEventTurn;
6254
6551
  const surface = deliverToProvider ? "slack" : "api";
6255
6552
  return await withLogContext({
6256
6553
  conversationId: context.conversationId,
@@ -6338,12 +6635,14 @@ function createConversationTurnWorker(agentRunner, deliverMessage) {
6338
6635
  let completedSuccessfully = false;
6339
6636
  const deliverAssistantMessage = async (value) => {
6340
6637
  const agentMessage = typeof value === "string" ? void 0 : value;
6341
- const replyText = typeof value === "string" ? value : getAssistantReplyText(value);
6638
+ const decision = agentMessage ? decideReply(agentMessage) : void 0;
6639
+ const replyText = typeof value === "string" ? value : decision?.kind === "deliver" ? decision.text : void 0;
6342
6640
  if (!replyText?.trim()) return;
6343
6641
  failureCode = "delivery_failed";
6344
6642
  const cards = await loadPendingMessageCards(context.conversationId);
6643
+ const quiet = decision?.kind === "deliver" && decision.quiet === true && isEventTurn && cards.length === 0;
6345
6644
  let deliveryResult;
6346
- if (deliverToProvider) {
6645
+ if (deliverToProvider && !quiet) {
6347
6646
  if (!conversationLocation || !deliverMessage) throw new Error(`Conversation ${context.conversationId} cannot deliver to its Location`);
6348
6647
  deliveryResult = await deliverMessage({
6349
6648
  cards,
@@ -6358,6 +6657,7 @@ function createConversationTurnWorker(agentRunner, deliverMessage) {
6358
6657
  conversation,
6359
6658
  conversationId: context.conversationId,
6360
6659
  ...deliveryResult ? { deliveryResult } : void 0,
6660
+ ...quiet ? { quiet } : void 0,
6361
6661
  sessionId: turnId,
6362
6662
  ...deliveryResult ? { source: "slack" } : source.kind === "web" ? { source: "web" } : void 0,
6363
6663
  text: replyText,
@@ -6765,34 +7065,6 @@ function createProductionConversationWorkOptions(options) {
6765
7065
  waitUntil: options.waitUntil
6766
7066
  });
6767
7067
  }
6768
- // src/api/http.ts
6769
- const NO_STORE_HEADERS = { "cache-control": "no-store" };
6770
- /** Build response init that keeps personalized API payloads out of shared caches. */
6771
- function noStoreInit(init) {
6772
- if (!init) return { headers: NO_STORE_HEADERS };
6773
- const headers = new Headers(init.headers);
6774
- if (!headers.has("cache-control")) headers.set("cache-control", "no-store");
6775
- return {
6776
- ...init,
6777
- headers
6778
- };
6779
- }
6780
- /** Serialize a REST response only after it satisfies its declared schema. */
6781
- function jsonResponse(schema, value, init) {
6782
- return Response.json(schema.parse(value), noStoreInit(init));
6783
- }
6784
- /** Return an empty personalized API response with no-store caching. */
6785
- function emptyResponse(status = 204) {
6786
- return new Response(null, noStoreInit({ status }));
6787
- }
6788
- /** Stop a request with Junior's stable JSON error contract. */
6789
- function throwApiError(status, message, cause) {
6790
- throw new HTTPException(status, {
6791
- ...cause === void 0 ? void 0 : { cause },
6792
- message,
6793
- res: jsonResponse(apiErrorSchema, { error: message }, { status })
6794
- });
6795
- }
6796
7068
  // src/api/conversations/archive.ts
6797
7069
  async function setViewerArchive(args) {
6798
7070
  const executor = getSqlExecutor();
@@ -6804,7 +7076,7 @@ async function setViewerArchive(args) {
6804
7076
  if (root.lastActivityAt.getTime() !== Date.parse(args.lastSeenAt)) return { status: "conflict" };
6805
7077
  const archivedAt = /* @__PURE__ */ new Date();
6806
7078
  const lastMessageAt = new Date(args.lastSeenAt);
6807
- await db.insert(juniorConversationParticipants).values({
7079
+ await db.with(conversationDetailTouch(db, [args.rootConversationId])).insert(juniorConversationParticipants).values({
6808
7080
  archivedAt,
6809
7081
  lastMessageAt,
6810
7082
  rootConversationId: args.rootConversationId,
@@ -6813,6 +7085,7 @@ async function setViewerArchive(args) {
6813
7085
  target: [juniorConversationParticipants.userId, juniorConversationParticipants.rootConversationId],
6814
7086
  set: {
6815
7087
  archivedAt,
7088
+ pinnedAt: null,
6816
7089
  lastMessageAt: sql`greatest(${juniorConversationParticipants.lastMessageAt}, excluded.last_message_at)`
6817
7090
  }
6818
7091
  });
@@ -6821,19 +7094,16 @@ async function setViewerArchive(args) {
6821
7094
  status: "updated"
6822
7095
  };
6823
7096
  }
6824
- await db.update(juniorConversationParticipants).set({ archivedAt: null }).where(and(eq(juniorConversationParticipants.userId, args.userId), eq(juniorConversationParticipants.rootConversationId, args.rootConversationId), isNotNull(juniorConversationParticipants.archivedAt)));
7097
+ await db.with(conversationDetailTouch(db, [args.rootConversationId])).update(juniorConversationParticipants).set({
7098
+ archivedAt: null,
7099
+ autoArchive: false
7100
+ }).where(and(eq(juniorConversationParticipants.userId, args.userId), eq(juniorConversationParticipants.rootConversationId, args.rootConversationId), isNotNull(juniorConversationParticipants.archivedAt)));
6825
7101
  return {
6826
7102
  archivedAt: null,
6827
7103
  status: "updated"
6828
7104
  };
6829
7105
  });
6830
7106
  }
6831
- /** Read one viewer's archive timestamp for a conversation root. */
6832
- async function readConversationArchivedAt(viewer, conversationId) {
6833
- const rootConversationId = await resolveRootConversationId(getSqlExecutor(), conversationId);
6834
- const [row] = await getDb().select({ archivedAt: juniorConversationParticipants.archivedAt }).from(juniorConversationParticipants).where(and(eq(juniorConversationParticipants.userId, viewer.id), eq(juniorConversationParticipants.rootConversationId, rootConversationId))).limit(1);
6835
- return row?.archivedAt?.getTime();
6836
- }
6837
7107
  /** Archive or restore one conversation for the signed-in viewer. */
6838
7108
  async function archiveConversation(viewer, conversationId, body) {
6839
7109
  if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(404, "Conversation not found.");
@@ -7085,7 +7355,8 @@ async function forkConversation(input) {
7085
7355
  await executor.db().update(juniorConversations).set({
7086
7356
  forkedFromConversationId: source.conversationId,
7087
7357
  title: source.title ? `Fork: ${source.title}` : "Forked conversation",
7088
- ...input.quickQuestion ? { quickQuestionAt: new Date(nowMs) } : void 0
7358
+ ...input.quickQuestion ? { quickQuestionAt: new Date(nowMs) } : void 0,
7359
+ detailVersion: nextDetailVersion
7089
7360
  }).where(eq(juniorConversations.conversationId, conversationId));
7090
7361
  await copyForkEvents({
7091
7362
  sourceConversationId: source.conversationId,
@@ -7117,7 +7388,10 @@ async function forkConversation(input) {
7117
7388
  async function keepQuickQuestion(conversationId) {
7118
7389
  const executor = getSqlExecutor();
7119
7390
  return withConversationEventLock(executor, conversationId, async () => {
7120
- if (!(await executor.db().update(juniorConversations).set({ quickQuestionAt: null }).where(and(eq(juniorConversations.conversationId, conversationId), isNotNull(juniorConversations.quickQuestionAt))).returning({ conversationId: juniorConversations.conversationId })).length) return;
7391
+ if (!(await executor.db().update(juniorConversations).set({
7392
+ quickQuestionAt: null,
7393
+ detailVersion: nextDetailVersion
7394
+ }).where(and(eq(juniorConversations.conversationId, conversationId), isNotNull(juniorConversations.quickQuestionAt))).returning({ conversationId: juniorConversations.conversationId })).length) return;
7121
7395
  const nowMs = Date.now();
7122
7396
  await getConversationEventStore().append(conversationId, [{
7123
7397
  idempotencyKey: QUICK_QUESTION_KEPT_NOTE_KEY,
@@ -7227,6 +7501,26 @@ function messageTotalTokens(args) {
7227
7501
  function definedNumber(value) {
7228
7502
  return value === null ? void 0 : value;
7229
7503
  }
7504
+ const modelUsageSumsSchema = z.object({
7505
+ inputTokens: z.number().nullable(),
7506
+ outputTokens: z.number().nullable(),
7507
+ cachedInputTokens: z.number().nullable(),
7508
+ cacheCreationTokens: z.number().nullable(),
7509
+ reasoningTokens: z.number().nullable(),
7510
+ totalTokens: z.number().nullable(),
7511
+ costInput: z.number().nullable(),
7512
+ costOutput: z.number().nullable(),
7513
+ costCacheRead: z.number().nullable(),
7514
+ costCacheWrite: z.number().nullable(),
7515
+ costTotal: z.number().nullable()
7516
+ });
7517
+ const COST_FIELDS = /* @__PURE__ */ new Set([
7518
+ "costInput",
7519
+ "costOutput",
7520
+ "costCacheRead",
7521
+ "costCacheWrite",
7522
+ "costTotal"
7523
+ ]);
7230
7524
  function usageFromRow(row) {
7231
7525
  const components = {
7232
7526
  inputTokens: definedNumber(row.inputTokens),
@@ -7250,12 +7544,8 @@ function usageFromRow(row) {
7250
7544
  };
7251
7545
  return hasAgentTurnUsage(result) ? agentTurnUsageSchema.parse(result) : void 0;
7252
7546
  }
7253
- /**
7254
- * Aggregate real assistant calls by provider/model in SQL, for one
7255
- * Conversation and all its child agents at any depth. Replayed history is not
7256
- * another call; its tokens appear in the next call's input usage.
7257
- */
7258
- async function readConversationModelUsageFromSql(executor, options) {
7547
+ /** Sum assistant calls by model id, in the given seq range of each Conversation. */
7548
+ async function sumModelUsage(executor, ranges) {
7259
7549
  const modelText = sql`(${model} #>> '{}')`;
7260
7550
  const modelId = sql`case
7261
7551
  when position('/' in coalesce(${modelText}, '')) > 0
@@ -7266,7 +7556,8 @@ async function readConversationModelUsageFromSql(executor, options) {
7266
7556
  const outputTokens = token("output", "outputTokens");
7267
7557
  const cachedInputTokens = token("cacheRead", "cachedInputTokens");
7268
7558
  const cacheCreationTokens = token("cacheWrite", "cacheCreationTokens");
7269
- return (await executor.db().select({
7559
+ const rangeRows = sql.join(ranges.map((range) => sql`(${range.conversationId}::text, ${range.fromSeq}::integer, ${range.toSeq}::integer)`), sql`, `);
7560
+ return await executor.db().select({
7270
7561
  modelId,
7271
7562
  inputTokens: summed(inputTokens),
7272
7563
  outputTokens: summed(outputTokens),
@@ -7284,10 +7575,114 @@ async function readConversationModelUsageFromSql(executor, options) {
7284
7575
  costCacheRead: summedCost(nonnegativeNumber(cost, "cacheRead")),
7285
7576
  costCacheWrite: summedCost(nonnegativeNumber(cost, "cacheWrite")),
7286
7577
  costTotal: summedCost(nonnegativeNumber(cost, "total"))
7287
- }).from(juniorConversationEvents).innerJoin(conversationSubtree([options.conversationId]), eq(conversationSubtreeColumns.conversationId, juniorConversationEvents.conversationId)).crossJoinLateral(assistantCall).where(and(eq(juniorConversationEvents.type, "assistant_message"), notCopiedByFork(), notInheritedByForkChild(), sql`jsonb_typeof(${provider}) = 'string'`, sql`jsonb_typeof(${model}) = 'string'`, sql`coalesce(${provider} #>> '{}', '') <> ''`, sql`coalesce(${modelText}, '') <> ''`)).groupBy(modelId).orderBy(modelId)).flatMap((row) => {
7288
- const modelUsage = usageFromRow(row);
7578
+ }).from(juniorConversationEvents).innerJoin(sql`(values ${rangeRows}) as seq_range(conversation_id, from_seq, to_seq)`, sql`seq_range.conversation_id = ${juniorConversationEvents.conversationId}
7579
+ and ${juniorConversationEvents.seq} > seq_range.from_seq
7580
+ and ${juniorConversationEvents.seq} <= seq_range.to_seq`).crossJoinLateral(assistantCall).where(and(eq(juniorConversationEvents.type, "assistant_message"), notCopiedByFork(), notInheritedByForkChild(), sql`jsonb_typeof(${provider}) = 'string'`, sql`jsonb_typeof(${model}) = 'string'`, sql`coalesce(${provider} #>> '{}', '') <> ''`, sql`coalesce(${modelText}, '') <> ''`)).groupBy(modelId);
7581
+ }
7582
+ /**
7583
+ * The last event seq of each Conversation in a subtree, and the creation time
7584
+ * of its first event. A purged Conversation can get new events under the same
7585
+ * id, with seq starting again at 0; the first event time tells them apart.
7586
+ */
7587
+ async function readEventWatermarks(executor, conversationId) {
7588
+ const conversation = juniorConversations.conversationId;
7589
+ return await executor.db().select({
7590
+ conversationId: conversation,
7591
+ seq: sql`(
7592
+ select max(watermark.seq) from junior_conversation_events watermark
7593
+ where watermark.conversation_id = ${conversation}
7594
+ )`,
7595
+ originMs: sql`(
7596
+ select (extract(epoch from origin.created_at) * 1000)::double precision
7597
+ from junior_conversation_events origin
7598
+ where origin.conversation_id = ${conversation}
7599
+ order by origin.seq
7600
+ limit 1
7601
+ )`
7602
+ }).from(juniorConversations).innerJoin(conversationSubtree([conversationId]), eq(conversationSubtreeColumns.conversationId, conversation));
7603
+ }
7604
+ const modelUsageCacheSchema = z.object({
7605
+ conversations: z.record(z.string(), z.object({
7606
+ seq: z.number().int(),
7607
+ originMs: z.number()
7608
+ })),
7609
+ models: z.record(z.string(), modelUsageSumsSchema)
7610
+ });
7611
+ const EMPTY_MODEL_USAGE_CACHE = {
7612
+ conversations: {},
7613
+ models: {}
7614
+ };
7615
+ const MODEL_USAGE_CACHE_TTL_MS = 2592e6;
7616
+ function modelUsageCacheKey(conversationId) {
7617
+ return `conversation-model-usage:${conversationId}`;
7618
+ }
7619
+ function addSums(field, left, right) {
7620
+ if (left === null) return right;
7621
+ if (right === null) return left;
7622
+ return COST_FIELDS.has(field) ? Number((left + right).toFixed(12)) : left + right;
7623
+ }
7624
+ function mergeSums(left, right) {
7625
+ if (!left) return right;
7626
+ const merged = { ...right };
7627
+ for (const field of modelUsageSumsSchema.keyof().options) merged[field] = addSums(field, left[field], right[field]);
7628
+ return merged;
7629
+ }
7630
+ /**
7631
+ * Aggregate real assistant calls by provider/model in SQL, for one
7632
+ * Conversation and all its child agents at any depth. Replayed history is not
7633
+ * another call; its tokens appear in the next call's input usage.
7634
+ *
7635
+ * Reading assistant payloads is slow on long Conversations, so the sums are
7636
+ * cached with the last seq that each Conversation in the subtree added. A read
7637
+ * sums only later events. This is correct because a row at or below a seen
7638
+ * seq never changes and never changes whether it counts:
7639
+ * - Events are append-only. The per-Conversation event lock serializes
7640
+ * appends and is held to commit, so when seq N is visible, lower seqs are.
7641
+ * - `notInheritedByForkChild` reads only lower seqs of the same Conversation.
7642
+ * - `notCopiedByFork` reads a later fork note, but a fork commits its copied
7643
+ * events and the note in one transaction.
7644
+ * Concurrent reads can overwrite each other's entry. Each entry is correct
7645
+ * at its own seqs, so the last write wins safely.
7646
+ */
7647
+ async function readConversationModelUsageFromSql(executor, options) {
7648
+ const state = getStateAdapter();
7649
+ const key = modelUsageCacheKey(options.conversationId);
7650
+ const [stored, watermarks] = await Promise.all([state.get(key), readEventWatermarks(executor, options.conversationId)]);
7651
+ const cached = modelUsageCacheSchema.safeParse(stored).data;
7652
+ const purged = watermarks.some(({ conversationId, seq, originMs }) => {
7653
+ const seen = cached?.conversations[conversationId];
7654
+ return seen && (seq === null || seq < seen.seq || originMs !== seen.originMs);
7655
+ });
7656
+ const base = cached && !purged ? cached : EMPTY_MODEL_USAGE_CACHE;
7657
+ const ranges = [];
7658
+ const conversations = {};
7659
+ for (const { conversationId, seq, originMs } of watermarks) {
7660
+ if (seq === null || originMs === null) continue;
7661
+ conversations[conversationId] = {
7662
+ seq,
7663
+ originMs
7664
+ };
7665
+ const fromSeq = base.conversations[conversationId]?.seq ?? -1;
7666
+ if (seq > fromSeq) ranges.push({
7667
+ conversationId,
7668
+ fromSeq,
7669
+ toSeq: seq
7670
+ });
7671
+ }
7672
+ let models = base.models;
7673
+ if (ranges.length > 0 || base !== cached) {
7674
+ const deltas = ranges.length > 0 ? await sumModelUsage(executor, ranges) : [];
7675
+ models = { ...base.models };
7676
+ for (const { modelId, ...sums } of deltas) models[modelId] = mergeSums(models[modelId], sums);
7677
+ await state.set(key, {
7678
+ conversations,
7679
+ models
7680
+ }, MODEL_USAGE_CACHE_TTL_MS);
7681
+ }
7682
+ return Object.entries(models).sort(([left], [right]) => left < right ? -1 : 1).flatMap(([modelId, sums]) => {
7683
+ const modelUsage = usageFromRow(sums);
7289
7684
  return modelUsage ? [{
7290
- modelId: row.modelId,
7685
+ modelId,
7291
7686
  usage: modelUsage
7292
7687
  }] : [];
7293
7688
  });
@@ -7431,8 +7826,7 @@ function eventMentionTexts(data) {
7431
7826
  ...(data.events ?? []).map((event) => event.trustedSummary)
7432
7827
  ];
7433
7828
  case "assistant_message": return data.parts.map((part) => part.text);
7434
- case "compaction":
7435
- case "handoff": return [data.summary];
7829
+ case "compaction": return [data.summary];
7436
7830
  case "structured_event": return [data.presentation.preview, ...(data.presentation.details ?? []).map((detail) => detail.description)];
7437
7831
  default: return [];
7438
7832
  }
@@ -7630,6 +8024,7 @@ function conversationSummaryFromStoredConversation(args) {
7630
8024
  ...actorIdentity ? { actorIdentity } : void 0,
7631
8025
  ...locationUrl ? { locationUrl } : void 0,
7632
8026
  archivedAt: args.archivedAtMs === void 0 ? null : new Date(args.archivedAtMs).toISOString(),
8027
+ pinnedAt: args.pinnedAtMs === void 0 ? null : new Date(args.pinnedAtMs).toISOString(),
7633
8028
  ...slackThread ? { channel: slackThread.channelId } : void 0,
7634
8029
  ...channelName ? { channelName } : void 0,
7635
8030
  ...channelNameRedacted ? { channelNameRedacted: true } : void 0,
@@ -7806,61 +8201,6 @@ async function readConversationAuxiliaryCostsFromSql(db, conversationIds) {
7806
8201
  }
7807
8202
  return result;
7808
8203
  }
7809
- // src/chat/plugins/unfinished-work.ts
7810
- /**
7811
- * Return assigned and unfinished plugin work for the candidate conversations.
7812
- * Feed Priority combines these signals with conversation activity on the host.
7813
- */
7814
- async function listConversationWork(conversationIds) {
7815
- if (conversationIds.length === 0) return {
7816
- assignedIds: [],
7817
- finishedAtById: {},
7818
- unfinishedIds: []
7819
- };
7820
- const candidates = new Set(conversationIds);
7821
- const assigned = /* @__PURE__ */ new Set();
7822
- const finishedAtById = /* @__PURE__ */ new Map();
7823
- const unfinished = /* @__PURE__ */ new Set();
7824
- for (const plugin of getPlugins()) {
7825
- const hook = plugin.hooks?.unfinishedWork;
7826
- if (!hook) continue;
7827
- try {
7828
- const result = await hook({
7829
- conversationIds,
7830
- db: getDb(),
7831
- log: createPluginLogger(plugin.manifest.name),
7832
- plugin: { name: plugin.manifest.name },
7833
- cache: createPluginCache(plugin.manifest.name)
7834
- });
7835
- for (const conversationId of result.conversationIds) {
7836
- if (!candidates.has(conversationId)) continue;
7837
- unfinished.add(conversationId);
7838
- assigned.add(conversationId);
7839
- }
7840
- for (const conversationId of result.assignedConversationIds ?? []) if (candidates.has(conversationId)) assigned.add(conversationId);
7841
- for (const [conversationId, finishedAt] of Object.entries(result.finishedWorkAtByConversationId ?? {})) {
7842
- if (!candidates.has(conversationId)) continue;
7843
- const time = Date.parse(finishedAt);
7844
- if (!Number.isFinite(time)) continue;
7845
- const current = finishedAtById.get(conversationId);
7846
- if (!current || time > Date.parse(current)) finishedAtById.set(conversationId, finishedAt);
7847
- }
7848
- } catch (error) {
7849
- logWarn("plugin.unfinished_work.hook.failed", {
7850
- "app.plugin.name": plugin.manifest.name,
7851
- "exception.message": error instanceof Error ? error.message : String(error)
7852
- });
7853
- }
7854
- }
7855
- return {
7856
- assignedIds: conversationIds.filter((conversationId) => assigned.has(conversationId)),
7857
- finishedAtById: Object.fromEntries(conversationIds.flatMap((conversationId) => {
7858
- const finishedAt = finishedAtById.get(conversationId);
7859
- return finishedAt ? [[conversationId, finishedAt]] : [];
7860
- })),
7861
- unfinishedIds: conversationIds.filter((conversationId) => unfinished.has(conversationId))
7862
- };
7863
- }
7864
8204
  // src/api/conversations/priority.ts
7865
8205
  /** Conversations with no known work leave Priority after this idle window. */
7866
8206
  const UNASSIGNED_PRIORITY_WINDOW_MS = 108e5;
@@ -7887,19 +8227,6 @@ function isConversationPriority(conversation, nowMs) {
7887
8227
  }
7888
8228
  return nowMs - lastSeenAt <= UNASSIGNED_PRIORITY_WINDOW_MS;
7889
8229
  }
7890
- // src/api/conversations/user-message-activity.ts
7891
- /** Read the latest true user message time for each selected conversation. */
7892
- async function readLastUserMessageAtByConversation(db, conversationIds) {
7893
- if (conversationIds.length === 0) return /* @__PURE__ */ new Map();
7894
- const authority = sql`${juniorConversationEvents.payload}->'provenance'->>'authority'`;
7895
- const actorPlatform = sql`${juniorConversationEvents.payload}->'provenance'->'actor'->>'platform'`;
7896
- const role = sql`${juniorConversationEvents.payload}->>'role'`;
7897
- const rows = await db.select({
7898
- conversationId: juniorConversationEvents.conversationId,
7899
- lastUserMessageAt: sql`max(${juniorConversationEvents.createdAt})`
7900
- }).from(juniorConversationEvents).leftJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversationEvents.actorIdentityId)).where(and(inArray(juniorConversationEvents.conversationId, conversationIds), or(and(eq(juniorConversationEvents.type, "user_message"), eq(authority, "instruction"), sql`${actorPlatform} in ('slack', 'local', 'web')`), and(eq(juniorConversationEvents.type, "message"), eq(role, "user"), eq(juniorIdentities.kind, "user"))))).groupBy(juniorConversationEvents.conversationId);
7901
- return new Map(rows.map((row) => [row.conversationId, new Date(row.lastUserMessageAt).toISOString()]));
7902
- }
7903
8230
  // src/api/conversations/activity-preview.ts
7904
8231
  /** Read one recent assistant message, or the latest user message, for each conversation. */
7905
8232
  async function readConversationActivityPreviews(db, conversationIds) {
@@ -8028,7 +8355,7 @@ function conversationCodeRepositoryFilter(repositoryId, viewerUserId) {
8028
8355
  participantMatch: conversationHasParticipantUser(viewerUserId)
8029
8356
  }) : void 0));
8030
8357
  }
8031
- async function conversationRows(db, limit, status, filter, query, includePrivateBriefs = false, codeRepository) {
8358
+ async function conversationRows(db, { codeRepository, conversationIds, filter, includePrivateBriefs = false, limit, query, status }) {
8032
8359
  return db.select({
8033
8360
  conversation: conversationReadColumns(),
8034
8361
  location: juniorDestinations,
@@ -8039,7 +8366,7 @@ async function conversationRows(db, limit, status, filter, query, includePrivate
8039
8366
  identitySubjectId: juniorIdentities.providerSubjectId,
8040
8367
  identityTenantId: juniorIdentities.providerTenantId,
8041
8368
  userDisplayName: juniorUsers.displayName
8042
- }).from(juniorConversations).leftJoin(juniorDestinations, eq(juniorDestinations.id, juniorConversations.destinationId)).leftJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(and(isNull(juniorConversations.parentConversationId), isNull(juniorConversations.quickQuestionAt), conversationFeedMembershipFilter(status, filter), codeRepository ? conversationCodeRepositoryFilter(codeRepository.id, codeRepository.viewerUserId) : void 0, query ? or(sql`strpos(lower(coalesce(${juniorConversations.title}, '')), ${query}) > 0`, sql`exists (
8369
+ }).from(juniorConversations).leftJoin(juniorDestinations, eq(juniorDestinations.id, juniorConversations.destinationId)).leftJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(and(isNull(juniorConversations.parentConversationId), isNull(juniorConversations.quickQuestionAt), conversationFeedMembershipFilter(status, filter), conversationIds ? inArray(juniorConversations.conversationId, conversationIds) : void 0, codeRepository ? conversationCodeRepositoryFilter(codeRepository.id, codeRepository.viewerUserId) : void 0, query ? or(sql`strpos(lower(coalesce(${juniorConversations.title}, '')), ${query}) > 0`, sql`exists (
8043
8370
  select 1
8044
8371
  from ${juniorConversationBriefs}
8045
8372
  where ${juniorConversationBriefs.conversationId} = ${juniorConversations.conversationId}
@@ -8051,7 +8378,24 @@ async function conversationRows(db, limit, status, filter, query, includePrivate
8051
8378
  )
8052
8379
  and to_tsvector('english', ${juniorConversationBriefs.searchText})
8053
8380
  @@ websearch_to_tsquery('english', ${query})
8054
- )`) : void 0)).orderBy(desc(juniorConversations.lastActivityAt), asc(juniorConversations.conversationId)).limit(limit);
8381
+ )`) : void 0)).orderBy(...filter?.kind === "viewer" && status === "active" ? [desc(conversationPinnedForUser(filter.userId))] : [], desc(juniorConversations.lastActivityAt), asc(juniorConversations.conversationId)).limit(limit);
8382
+ }
8383
+ /**
8384
+ * Read the viewer's active conversations that wait on them but fall outside
8385
+ * the newest page. Needs attention shows every conversation that waits on the
8386
+ * viewer, so an old one must come back to the feed.
8387
+ */
8388
+ async function waitingRowsOutsidePage(db, filter, page) {
8389
+ const loaded = new Set(page.map((row) => row.conversation.conversationId));
8390
+ const missing = (await listWaitingConversations(db, filter.userId)).map((waiting) => waiting.conversationId).filter((conversationId) => !loaded.has(conversationId));
8391
+ if (missing.length === 0) return [];
8392
+ return await conversationRows(db, {
8393
+ conversationIds: missing,
8394
+ filter,
8395
+ includePrivateBriefs: true,
8396
+ limit: missing.length,
8397
+ status: "active"
8398
+ });
8055
8399
  }
8056
8400
  /** Decode a conversation row with the linked user name and identity-scoped provider fields. */
8057
8401
  function conversationFromRow(row) {
@@ -8133,15 +8477,24 @@ async function readConversationFeedFromSql(options = {}) {
8133
8477
  const db = getDb();
8134
8478
  const filter = options.codeRepositoryId ? void 0 : conversationFeedFilter(options);
8135
8479
  const query = options.q?.trim().toLowerCase() || void 0;
8136
- const rows = await conversationRows(db, options.limit ?? CONVERSATION_FEED_LIMIT, query || options.codeRepositoryId ? "all" : options.status ?? "active", filter, query, filter?.kind === "viewer", options.codeRepositoryId ? {
8137
- id: options.codeRepositoryId,
8138
- ...options.viewer ? { viewerUserId: options.viewer.id } : void 0
8139
- } : void 0);
8480
+ const status = query || options.codeRepositoryId ? "all" : options.status ?? "active";
8481
+ const rows = await conversationRows(db, {
8482
+ ...options.codeRepositoryId ? { codeRepository: {
8483
+ id: options.codeRepositoryId,
8484
+ ...options.viewer ? { viewerUserId: options.viewer.id } : void 0
8485
+ } } : void 0,
8486
+ filter,
8487
+ includePrivateBriefs: filter?.kind === "viewer",
8488
+ limit: options.limit ?? CONVERSATION_FEED_LIMIT,
8489
+ query,
8490
+ status
8491
+ });
8492
+ if (filter?.kind === "viewer" && status === "active") rows.push(...await waitingRowsOutsidePage(db, filter, rows));
8140
8493
  const conversations = rows.map((row) => conversationFromRow(row));
8141
8494
  const conversationIds = conversations.map((conversation) => conversation.conversationId);
8142
- const [accessByConversation, archiveTimesByConversation, annotationsByConversation, auxiliaryCostsByRoot, metricsByRoot, participantsByConversation, teamDomainByTeamId, conversationWork, lastUserMessageAtByConversation, activityPreviewByConversation, automationTitleByConversation, firstHumanMessageTextByConversation] = await Promise.all([
8495
+ const [accessByConversation, viewerMarksByConversation, annotationsByConversation, auxiliaryCostsByRoot, metricsByRoot, participantsByConversation, teamDomainByTeamId, conversationWork, lastUserMessageAtByConversation, activityPreviewByConversation, automationTitleByConversation, firstHumanMessageTextByConversation] = await Promise.all([
8143
8496
  readConversationAccessFromSql(db, conversationIds, options.viewer),
8144
- conversationArchiveTimes(db, conversationIds, filter?.kind === "viewer" ? { userId: filter.userId } : filter?.kind === "actorEmail" ? { email: filter.email } : void 0),
8497
+ conversationViewerMarks(db, conversationIds, filter?.kind === "viewer" ? { userId: filter.userId } : filter?.kind === "actorEmail" ? { email: filter.email } : void 0),
8145
8498
  listConversationAnnotationsById(db, conversationIds),
8146
8499
  readConversationAuxiliaryCostsFromSql(db, conversationIds),
8147
8500
  readConversationTreeMetricsFromSql(db, conversationIds),
@@ -8164,9 +8517,8 @@ async function readConversationFeedFromSql(options = {}) {
8164
8517
  const metrics = metricsByRoot.get(conversation.conversationId);
8165
8518
  const auxiliaryCosts = auxiliaryCostsByRoot.get(conversation.conversationId);
8166
8519
  const childAgentTotals = childAgentTotalsReport(metrics, auxiliaryCosts);
8167
- const archivedAtMs = archiveTimesByConversation.get(conversation.conversationId);
8168
8520
  const summary = conversationSummaryFromStoredConversation({
8169
- ...archivedAtMs === void 0 ? void 0 : { archivedAtMs },
8521
+ ...viewerMarksByConversation.get(conversation.conversationId),
8170
8522
  automationTitle: automationTitleByConversation.get(conversation.conversationId),
8171
8523
  conversation,
8172
8524
  access,
@@ -8215,6 +8567,57 @@ async function readConversationFeedFromSql(options = {}) {
8215
8567
  async function readConversationFeed(options = {}) {
8216
8568
  return conversationFeedSchema.parse(await readConversationFeedFromSql(options));
8217
8569
  }
8570
+ // src/api/conversations/event-list.ts
8571
+ /** Read one bounded page of reporting events before, after, or around a signed cursor. */
8572
+ async function readConversationEvents(conversationId, boundary, options = {}) {
8573
+ const record = await readConversationRecordFromSql(conversationId);
8574
+ if (!record) return void 0;
8575
+ const cursor = decodeConversationCursor({
8576
+ conversationId,
8577
+ cursor: "after" in boundary ? boundary.after : "around" in boundary ? boundary.around : boundary.before
8578
+ });
8579
+ if (!cursor) throwApiError(400, "Invalid conversation cursor.");
8580
+ const canExposePayload = (await readConversationAccessFromSql(getDb(), [conversationId], options.viewer)).get(conversationId)?.canViewPrivateContent ?? false;
8581
+ const transcriptPurgedAtMs = record.conversation.transcriptPurgedAtMs;
8582
+ const pageArgs = {
8583
+ canExposePayload,
8584
+ conversationId,
8585
+ limit: options.limit ?? 500
8586
+ };
8587
+ const page = transcriptPurgedAtMs !== void 0 ? { events: [] } : "after" in boundary ? await readConversationEventPageAfter(getSqlExecutor(), {
8588
+ ...pageArgs,
8589
+ afterSeq: cursor.seq
8590
+ }) : "around" in boundary ? await readConversationEventPageAround(getSqlExecutor(), {
8591
+ ...pageArgs,
8592
+ seq: cursor.seq
8593
+ }) : await readConversationEventPage(getSqlExecutor(), {
8594
+ ...pageArgs,
8595
+ beforeSeq: cursor.seq
8596
+ });
8597
+ return conversationEventPageSchema.parse(await conversationEventPageReport(getSqlExecutor(), {
8598
+ conversationId,
8599
+ eventHistory: conversationEventHistory({
8600
+ canExposePayload,
8601
+ ...transcriptPurgedAtMs === void 0 ? void 0 : { transcriptPurgedAtMs }
8602
+ }),
8603
+ page
8604
+ }));
8605
+ }
8606
+ /** Attach mentions and signed cursors to one bounded page of events. */
8607
+ async function conversationEventPageReport(executor, args) {
8608
+ const { conversationId, page } = args;
8609
+ const cursorAt = (seq) => encodeConversationCursor({
8610
+ conversationId,
8611
+ seq
8612
+ });
8613
+ return {
8614
+ events: (await attachConversationMentions(executor, conversationId, { events: page.events })).events,
8615
+ eventHistory: args.eventHistory,
8616
+ ...page.previousSeq === void 0 ? void 0 : { previousCursor: cursorAt(page.previousSeq) },
8617
+ ...page.nextSeq === void 0 ? void 0 : { nextCursor: cursorAt(page.nextSeq) },
8618
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString()
8619
+ };
8620
+ }
8218
8621
  // src/api/conversations/fork.ts
8219
8622
  /** Fork a Conversation that the viewer can read into a new root they own. */
8220
8623
  async function forkConversationForViewer(viewer, sourceConversationId, body) {
@@ -8366,7 +8769,8 @@ function projectConversationDetail(args) {
8366
8769
  return {
8367
8770
  ...conversationSummaryFromStoredConversation({
8368
8771
  access: args.access,
8369
- ...args.archivedAtMs === void 0 ? void 0 : { archivedAtMs: args.archivedAtMs },
8772
+ archivedAtMs: args.archivedAtMs,
8773
+ pinnedAtMs: args.pinnedAtMs,
8370
8774
  automationTitle: args.automationTitle,
8371
8775
  auxiliaryCosts: args.auxiliaryCosts,
8372
8776
  ...args.childAgentTotals ? { childAgentTotals: args.childAgentTotals } : void 0,
@@ -8394,6 +8798,12 @@ function projectConversationDetail(args) {
8394
8798
  canExposePayload,
8395
8799
  ...transcriptPurgedAtMs === void 0 ? void 0 : { transcriptPurgedAtMs }
8396
8800
  }),
8801
+ ...args.readPosition ? { readPosition: args.readPosition } : void 0,
8802
+ ...args.unreadAfterSeq !== void 0 ? { unreadCursor: encodeConversationCursor({
8803
+ conversationId,
8804
+ seq: args.unreadAfterSeq
8805
+ }) } : void 0,
8806
+ ...args.unreadPage ? { unreadPage: args.unreadPage } : void 0,
8397
8807
  generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
8398
8808
  ...sentryConversationUrl ? { sentryConversationUrl } : void 0,
8399
8809
  ...args.sourceTask ? { sourceTask: args.sourceTask } : void 0
@@ -8402,9 +8812,9 @@ function projectConversationDetail(args) {
8402
8812
  async function readConversationDetailFromSql(conversationId, options) {
8403
8813
  const record = await readConversationRecordFromSql(conversationId);
8404
8814
  if (!record) return void 0;
8405
- const archivedAtMs = options.viewer ? await readConversationArchivedAt(options.viewer, conversationId) : void 0;
8815
+ const viewerMarks = options.viewer ? await readConversationViewerMarks(options.viewer, conversationId) : void 0;
8406
8816
  const executor = getSqlExecutor();
8407
- const [accessByConversation, annotations, automationTitleByConversation, auxiliaryCostsByConversation, briefVersion, firstHumanMessageTextByConversation, modelUsage, metricsByConversation, people, sourceTask, teamDomainByTeamId] = await Promise.all([
8817
+ const [accessByConversation, annotations, automationTitleByConversation, auxiliaryCostsByConversation, briefVersion, firstHumanMessageTextByConversation, modelUsage, metricsByConversation, people, readPosition, sourceTask, teamDomainByTeamId] = await Promise.all([
8408
8818
  readConversationAccessFromSql(getDb(), [conversationId], options.viewer),
8409
8819
  listConversationAnnotations(getDb(), conversationId),
8410
8820
  readAutomationTitlesByConversationId([record.conversation]),
@@ -8414,6 +8824,7 @@ async function readConversationDetailFromSql(conversationId, options) {
8414
8824
  record.conversation.transcriptPurgedAtMs === void 0 ? readConversationModelUsageFromSql(executor, { conversationId }) : Promise.resolve([]),
8415
8825
  readConversationTreeMetricsFromSql(getDb(), [conversationId]),
8416
8826
  readConversationAuthors(getDb(), conversationId),
8827
+ options.viewer ? readConversationReadPosition(options.viewer, conversationId) : void 0,
8417
8828
  readConversationSourceTask({
8418
8829
  conversationId,
8419
8830
  ...options.viewer ? { viewer: options.viewer } : void 0
@@ -8422,23 +8833,35 @@ async function readConversationDetailFromSql(conversationId, options) {
8422
8833
  ]);
8423
8834
  const access = accessByConversation.get(conversationId);
8424
8835
  const sidebarAnnotations = access?.canViewPrivateContent ? (await listConversationSidebarAnnotations([conversationId], /* @__PURE__ */ new Map([[conversationId, annotations]])))[conversationId] : void 0;
8836
+ const canExposePayload = access?.canViewPrivateContent ?? false;
8425
8837
  const page = record.conversation.transcriptPurgedAtMs === void 0 ? await readConversationEventPage(executor, {
8426
- canExposePayload: access?.canViewPrivateContent ?? false,
8838
+ canExposePayload,
8427
8839
  conversationId,
8428
8840
  limit: options.limit
8429
8841
  }) : { events: [] };
8842
+ const firstSeq = page.events[0]?.seq;
8843
+ const unreadAfterSeq = readPosition !== void 0 && page.previousSeq !== void 0 && firstSeq !== void 0 && readPosition.lastReadSeq + 1 < firstSeq ? readPosition.lastReadSeq : void 0;
8430
8844
  const brief = access?.canViewPrivateContent ? briefVersion?.content : void 0;
8431
- const { briefMentions, events } = await attachConversationMentions(executor, conversationId, {
8845
+ const [{ briefMentions, events }, unreadPage] = await Promise.all([attachConversationMentions(executor, conversationId, {
8432
8846
  ...brief ? { brief } : void 0,
8433
8847
  events: page.events
8434
- });
8848
+ }), options.unreadPage && unreadAfterSeq !== void 0 ? readConversationEventPageAround(executor, {
8849
+ canExposePayload,
8850
+ conversationId,
8851
+ limit: options.limit,
8852
+ seq: unreadAfterSeq
8853
+ }).then((around) => conversationEventPageReport(executor, {
8854
+ conversationId,
8855
+ eventHistory: conversationEventHistory({ canExposePayload }),
8856
+ page: around
8857
+ })).catch(() => void 0) : void 0]);
8435
8858
  const metrics = metricsByConversation.get(conversationId);
8436
8859
  const auxiliaryCosts = auxiliaryCostsByConversation.get(conversationId);
8437
8860
  const childAgentTotals = childAgentTotalsReport(metrics, auxiliaryCosts);
8438
8861
  return projectConversationDetail({
8439
8862
  ...record,
8440
8863
  access,
8441
- ...archivedAtMs === void 0 ? void 0 : { archivedAtMs },
8864
+ ...viewerMarks,
8442
8865
  automationTitle: automationTitleByConversation.get(conversationId),
8443
8866
  annotations,
8444
8867
  sidebarAnnotations,
@@ -8459,6 +8882,9 @@ async function readConversationDetailFromSql(conversationId, options) {
8459
8882
  ...sourceTask ? { sourceTask } : void 0,
8460
8883
  teamDomainByTeamId,
8461
8884
  ...page.previousSeq === void 0 ? void 0 : { previousSeq: page.previousSeq },
8885
+ ...readPosition ? { readPosition } : void 0,
8886
+ ...unreadAfterSeq === void 0 ? void 0 : { unreadAfterSeq },
8887
+ ...unreadPage ? { unreadPage } : void 0,
8462
8888
  usage: metrics?.usage ?? record.usage ?? void 0
8463
8889
  });
8464
8890
  }
@@ -8469,16 +8895,16 @@ async function readConversationDetail(conversationId, options = {}) {
8469
8895
  limit: options.limit ?? 500
8470
8896
  });
8471
8897
  if (!report) return void 0;
8472
- const [forks, agentTree, readPosition] = await Promise.all([
8898
+ const [forks, agentTree, autoArchive] = await Promise.all([
8473
8899
  readConversationForks(conversationId, options.viewer),
8474
8900
  readConversationAgentTree(conversationId, options.viewer),
8475
- options.viewer ? readConversationReadPosition(options.viewer, conversationId) : void 0
8901
+ options.viewer && report.isParticipant ? readConversationAutoArchive(options.viewer, conversationId) : void 0
8476
8902
  ]);
8477
8903
  return conversationDetailReportSchema.parse({
8478
8904
  ...report,
8479
8905
  ...forks,
8480
8906
  ...agentTree ? { agentTree } : void 0,
8481
- ...readPosition ? { readPosition } : void 0
8907
+ ...autoArchive === void 0 ? void 0 : { autoArchive }
8482
8908
  });
8483
8909
  }
8484
8910
  // src/api/conversations/stop.ts
@@ -8533,4 +8959,4 @@ function viewerWebMessages(messages, viewer) {
8533
8959
  }] : [];
8534
8960
  });
8535
8961
  }
8536
- export { readHealthReport as $, resolveAllowedDomains as A, bindMessageAuthorIdentityId as B, createProductionSlackWebhookServices as C, isAllowedDomain as D, assertNoLegacyAllowedDomains as E, stopSlackThread as F, actOnReviewItem as G, stripLeadingBotMention as H, normalizeIncomingSlackThreadId as I, reviewItemChange as J, closeReviewItemsAnsweredByReply as K, withNormalizedThreadId as L, buildSlackInboundMessage as M, clearSlackPendingReactions as N, isAllowedSignInEmail as O, isSlackMessageStopped as P, GET as Q, stopConversationTurn as R, createProductionConversationWorkOptions as S, createSlackWebApiStatusSender as T, parseContent as U, startProcessingReaction as V, ReviewItemActionError as W, AGENT_DISPATCH_MAX_AGE_MS as X, getAttachmentStorage as Y, enqueueAgentDispatch as Z, encodeConversationCursor as _, keepQuickQuestionForViewer as a, jsonResponse as b, readConversationAuxiliaryCostsFromSql as c, conversationEventHistory as d, conversationSummaryFromStoredConversation as f, decodeConversationCursor as g, readFirstHumanMessageTexts as h, forkConversationForViewer as i, recordSkippedConversationMessage as j, readEnvList as k, childAgentTotalsReport as l, resolveMentions as m, readConversationDetail as n, readConversationFeed as o, attachConversationMentions as p, readReviewItemForUser as q, markConversationRead as r, readConversationRecordFromSql as s, stopConversationTurnForViewer as t, readConversationTreeMetricsFromSql as u, archiveConversation as v, getProductionSlackAdapter as w, throwApiError as x, emptyResponse as y, THREAD_OPTOUT_ACK as z };
8962
+ export { setConversationAutoArchive as $, recordSkippedConversationMessage as A, startProcessingReaction as B, getProductionSlackAdapter as C, isAllowedSignInEmail as D, isAllowedDomain as E, normalizeIncomingSlackThreadId as F, closeReviewItemsAnsweredByReply as G, parseContent as H, withNormalizedThreadId as I, DEFAULT_AUTO_ARCHIVE_SETTINGS as J, readReviewItemForUser as K, stopConversationTurn as L, clearSlackPendingReactions as M, isSlackMessageStopped as N, readEnvList as O, stopSlackThread as P, runAutoArchiveSweep as Q, THREAD_OPTOUT_ACK as R, createProductionSlackWebhookServices as S, assertNoLegacyAllowedDomains as T, ReviewItemActionError as U, stripLeadingBotMention as V, actOnReviewItem as W, readConversationAutoArchive as X, archiveViewerDoneConversations as Y, readUserAutoArchiveSettings as Z, readFirstHumanMessageTexts as _, readConversationAgentTree as a, AGENT_DISPATCH_MAX_AGE_MS as at, archiveConversation as b, readConversationForks as c, readHealthReport as ct, readConversationRecordFromSql as d, updateUserAutoArchiveSettings as et, readConversationAuxiliaryCostsFromSql as f, resolveMentions as g, conversationSummaryFromStoredConversation as h, readConversationReadPosition as i, getAttachmentStorage as it, buildSlackInboundMessage as j, resolveAllowedDomains as k, readConversationEvents as l, readConversationTreeMetricsFromSql as m, readConversationDetail as n, jsonResponse as nt, forkConversationForViewer as o, enqueueAgentDispatch as ot, childAgentTotalsReport as p, reviewItemChange as q, markConversationRead as r, throwApiError as rt, keepQuickQuestionForViewer as s, GET as st, stopConversationTurnForViewer as t, emptyResponse as tt, readConversationFeed as u, decodeConversationCursor as v, createSlackWebApiStatusSender as w, createProductionConversationWorkOptions as x, encodeConversationCursor as y, bindMessageAuthorIdentityId as z };