@sentry/junior 0.278.0 → 0.280.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 (90) hide show
  1. package/dist/{actor-B4DYygOB.js → actor-6jsm_v96.js} +1 -1
  2. package/dist/{adapter-BXosqTMx.js → adapter-DVN3iwf9.js} +1 -1
  3. package/dist/{admin-Thn7NfOi.js → admin-Q_UI--9W.js} +1 -1
  4. package/dist/{agent-runner-DE-43MPb.js → agent-runner-_PYLv4Qo.js} +79 -39
  5. package/dist/api/schema.d.ts +2 -2
  6. package/dist/api/schema.js +7 -7
  7. package/dist/api.d.ts +3 -3
  8. package/dist/api.js +184 -418
  9. package/dist/{app-CHNS-AX2.d.ts → app-CL2zzzE0.d.ts} +5 -5
  10. package/dist/app.d.ts +1 -1
  11. package/dist/app.js +462 -80
  12. package/dist/{assistant-reply-pauL6qyn.js → assistant-reply-DbebsAxi.js} +1 -1
  13. package/dist/{automation-DphoTRYl.js → automation-CPqRFjIa.js} +2 -2
  14. package/dist/{background-compaction-queue-CAL4A2y7.js → background-compaction-queue-B9lmh8Ml.js} +3 -3
  15. package/dist/{briefs-4fyPJJEu.js → briefs-Dej7V0Bz.js} +11 -10
  16. package/dist/{catalog-runtime-BoOb5oUv.js → catalog-runtime-DpN0sWQ6.js} +2 -2
  17. package/dist/cli/chat.js +16 -16
  18. package/dist/cli/check.js +3 -3
  19. package/dist/cli/main.js +4 -4
  20. package/dist/cli/plugins.js +5 -5
  21. package/dist/cli/snapshot-create.js +4 -4
  22. package/dist/cli/upgrade.d.ts +1 -1
  23. package/dist/cli/upgrade.js +4 -4
  24. package/dist/{client-v_OVYuHZ.js → client-h2A2ZPzY.js} +7 -3
  25. package/dist/{config-o2jLRY5J.js → config-CusBFORe.js} +3 -3
  26. package/dist/{connections-RC4NXAx8.js → connections-C4h6mGha.js} +11 -11
  27. package/dist/{conversation-CZfyQvdm.js → conversation-DExTZw8B.js} +22 -7
  28. package/dist/conversation-pending-messages-Dgz6hrJs.js +173 -0
  29. package/dist/{conversation-privacy-C23M8KaD.js → conversation-privacy-2cm6OpNg.js} +1 -1
  30. package/dist/{credential-sync-Dd0WyNfF.js → credential-sync-DK06Jgt-.js} +17 -17
  31. package/dist/{db-BjLzDJCt.d.ts → db-Dsvk1Tp1.d.ts} +2 -2
  32. package/dist/{executor-CJfsD0VX.js → executor-Cmr0J8W3.js} +152 -7
  33. package/dist/instrumentation.d.ts +12 -0
  34. package/dist/instrumentation.js +56 -23
  35. package/dist/{logging-dFaXvBRK.js → logging-CGnh65_X.js} +2 -2
  36. package/dist/{media-DTAA8Qs_.js → media-Dq9_svfQ.js} +1 -1
  37. package/dist/{message-DSwxIZet.js → message-RpAnqHPY.js} +10 -10
  38. package/dist/nitro.d.ts +1 -1
  39. package/dist/nitro.js +18 -6
  40. package/dist/{oauth-callback-server-CDcuCp27.js → oauth-callback-server-BBnhVKuX.js} +2 -2
  41. package/dist/{oauth-relay-C6ZAyJgf.js → oauth-relay-D6xxVywK.js} +2 -2
  42. package/dist/{package-discovery-DJBompdd.js → package-discovery-DJhGdS4c.js} +1 -1
  43. package/dist/{plugins-DOm9Y6qI.js → plugins-HYh_JOdw.js} +1 -1
  44. package/dist/{projection-BTge9wrH.js → projection-C1MghKyI.js} +257 -137
  45. package/dist/{prompt-DDtCnlHP.js → prompt-BcHg-BMy.js} +2 -2
  46. package/dist/proxy-path-BHYoKZdq.js +15 -0
  47. package/dist/{queue-C37RbDVc.d.ts → queue-CZyYgPF0.d.ts} +1 -1
  48. package/dist/{registry-Cp6CNmtP.js → registry-DR7DjX9H.js} +4 -4
  49. package/dist/{reporting-window-DgHgwQB3.js → reporting-window-B-QP9zX1.js} +28 -2
  50. package/dist/{resolve-B_7h2cXx.js → resolve-0Ful4oDv.js} +4 -4
  51. package/dist/{result-5LBEfnLX.js → result-Dd9kCuQ-.js} +12 -12
  52. package/dist/{runner-C5-S4oq-.js → runner-yiY8gUUu.js} +11 -11
  53. package/dist/{sandbox-egress-signals-B4GehT1L.js → sandbox-egress-signals-BzQVHCMz.js} +1 -1
  54. package/dist/{schema-Tr484cCC.d.ts → schema-BkMmF552.d.ts} +1232 -222
  55. package/dist/{schema-B5fpczDw.js → schema-C5pEgfHc.js} +30 -70
  56. package/dist/sentry-BRTJqumy.js +51 -0
  57. package/dist/sentry-DrKC2NeM.d.ts +1 -0
  58. package/dist/sentry-route-name-BhwWnfqj.js +51 -0
  59. package/dist/{service-account-Cq_dLrZJ.js → service-account-Cu7HFLZQ.js} +3 -3
  60. package/dist/{service-account-BkEv20zf.js → service-account-PIMpWZHF.js} +3 -3
  61. package/dist/{session-stop-BsS4qFS2.js → session-stop-CDEMsNtv.js} +14 -15
  62. package/dist/{skills-M0BA0_s6.js → skills-B2xIoe0f.js} +5 -5
  63. package/dist/{spawn-BO3y7H4d.js → spawn-C0DySQRV.js} +3 -3
  64. package/dist/{stop-D5R82Wla.js → stop-Dj5-nrAo.js} +740 -285
  65. package/dist/{store-BGBzQWNf.js → store-Dlio-o6u.js} +6 -6
  66. package/dist/{store-CGJZTEVz.js → store-QzOfDwKA.js} +3 -3
  67. package/dist/{task-queue-UD27ei2U.js → task-queue-Cp1V_XW3.js} +4 -4
  68. package/dist/{task-runner-noxjOjkM.js → task-runner-CQkkUj3o.js} +23 -11
  69. package/dist/{thread-state-BSu6rM6p.js → thread-state-Bn87cfzE.js} +4 -4
  70. package/dist/{turn-failure-response-wahwyPrZ.js → turn-failure-response-CQebxByj.js} +8 -8
  71. package/dist/{turn-lifecycle-Bo4Trccw.js → turn-lifecycle-CJJsOhXB.js} +1 -1
  72. package/dist/{turn-session-routing-DnSaaEpn.js → turn-session-routing-bmG330Cf.js} +10 -11
  73. package/dist/{validation-B9-8iKyw.js → validation-D1wcf7hp.js} +2 -2
  74. package/dist/{version-C7HejFP2.js → version-BeHSXUK6.js} +1 -1
  75. package/dist/version.js +1 -1
  76. package/dist/{viewer-DLXajQZE.js → viewer-BZ0Hp5Nb.js} +6 -7
  77. package/dist/{work-DRGSlfia.js → work-BTcCIbWu.js} +12 -12
  78. package/dist/{worker-BGh5Dwc6.js → worker-D3fDK6zc.js} +7 -7
  79. package/migrations/0077_drop_agent_invocation_model_profile.sql +1 -0
  80. package/migrations/0078_plugin_conversation_index.sql +20 -0
  81. package/migrations/0079_conversation_event_author_index.sql +20 -0
  82. package/migrations/meta/0077_snapshot.json +4141 -0
  83. package/migrations/meta/0078_snapshot.json +4175 -0
  84. package/migrations/meta/0079_snapshot.json +4203 -0
  85. package/migrations/meta/_journal.json +21 -0
  86. package/package.json +4 -4
  87. package/dist/agent-invocations-D7c4BQGc.js +0 -182
  88. package/dist/common-Eu6sx09c.js +0 -107
  89. package/dist/rolldown-runtime-nwUcYXjP.js +0 -27
  90. package/dist/sentry-MDkYAVPV.js +0 -23
@@ -1,38 +1,38 @@
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
- import { i as getActiveSpan, r as continueTrace } from "./sentry-MDkYAVPV.js";
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";
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";
1
+ import { i as getActiveSpan, r as continueTrace } from "./sentry-BRTJqumy.js";
2
+ import { $ as completeTurnRecord, $a as notInheritedByForkChild, $n as takeReviewItem, A as getConversationMessageSlackTs, Aa as createPluginLogger, Ai as removeReactionFromMessage, Ba as conversationViewerMarks, Ci as addReactionToMessage, D as buildConversationContext, E as appendThreadContextMessages, En as webActorUserIds, F as turnHasReply, Fa as conversationHasParticipantUser, Fi as SlackActionError, Ga as readLatestConversationBrief, H as AuthorizationFlowDisabledError, Ha as viewerConversationMembership, Hi as normalizeSlackConversationId, I as upsertConversationMessage, Ia as conversationIsMemberRoot, Ii as downloadPrivateSlackFile, J as wasPendingAuthStopped, Ja as readConversationEventPageAround, Jn as getReviewItem, K as clearPendingAuth, Ka as readConversationEventPage, La as conversationNotArchivedForEmail, Ln as getPlugins, Lr as verifyTimerWatchCredentialSubject, M as markConversationMessage, Ma as readConversationAccessFromSql, N as normalizeConversationText, Na as conversationArchivedForEmail, O as createConversationMemoryService, P as recordDeliveredAssistantMessage, Pa as conversationArchivedForUser, Q as abandonTurnRecord, R as PluginCredentialFailureError, Ra as conversationNotArchivedForUser, Ri as getHeaderString, Rr as JUNIOR_THREAD_STATE_TTL_MS, S as resolveConversationTitle, Si as truncateStatusText, Sn as isExperimentalFeatureEnabled, Ut as persistWithRetry, Va as readConversationViewerMarks, Vi as isDmChannel, Wi as withSlackRetries, Wn as closeReviewItem, X as loadTurnCheckpoint, Xn as listReplyActionItems, Z as saveTurnCheckpoint, Za as buildSentryConversationUrl, Zn as listWaitingConversations, a as loadProjection, an as trimTrailingAssistantMessages, ar as isOnlyAssignee, bi as normalizeSlackStatusText, co as listConversationAnnotationsById, d as recordAuthorizationCompleted, do as lookupSlackUser, eo as getSlackFileId, et as failTurnRecord, fn as decideSubscribedThreadReply, fo as createPluginCache, go as piMessageFromHistoryItem, h as recordSubscribedReplyRoute, i as loadConversationProjection, ir as canReadReviewItem, j as isHumanConversationMessage, k as estimateConversationContextTokens, ln as buildDeterministicAssistantMessageId, lr as reviewItemNeedsUser, mn as getThreadStopDecision, mo as configValueSchema, n as commitMessages, no as readAttachmentVisionSummary, nr as canActOnReviewItem, nt as listTurnSummaries, o as loadTurnProjection, pn as getSubscribedReplyPreflightDecision, qa as readConversationEventPageAfter, ro as recordSlackAttachment, rt as recordTurnSummary, so as listConversationAnnotations, t as commitAcceptedReply, tt as getTurnRecord, un as buildDeterministicTurnId, ur as reviewItemReaderForUser, v as hydrateConversationMessages, w as fallbackShortTitle, wn as createUserTokenStore, x as persistConversationMessageSummaries, xr as cancelSubscriptions, y as persistConversationMessages, za as conversationPinnedForUser, zi as getSlackClient, zt as buildTurnErrorResponse } from "./projection-C1MghKyI.js";
3
+ import { a as completeText, c as resolveGatewayModel, m as escapeXml, r as completeDecision, x as isProviderRetryError } from "./client-h2A2ZPzY.js";
4
+ 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-CusBFORe.js";
5
+ 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-CGnh65_X.js";
6
+ import { t as JUNIOR_VERSION } from "./version-BeHSXUK6.js";
7
+ 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-6jsm_v96.js";
8
+ 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-BZ0Hp5Nb.js";
9
+ import { A as juniorIdentities, M as juniorDestinations, O as conversationReadColumns, S as juniorConversationEvents, T as juniorCodeChanges, _ as juniorConversationParticipants, c as juniorReviewItems, g as juniorConversationReadPositions, j as juniorUsers, k as juniorConversations, o as juniorReviewItemConversations, y as juniorConversationBriefs } from "./executor-Cmr0J8W3.js";
10
+ import { g as instructionProvenanceFor, m as contextProvenance, n as detectImageMediaType, r as isVisionImageMediaType } from "./media-Dq9_svfQ.js";
11
+ import { d as actorLogContext, f as credentialContextForActor } from "./registry-DR7DjX9H.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, S as createSlackReviewItemShow, Tt as conversationSubtree, a as buildAuthPauseResponse, b as renderAttachmentText, dt as recordWebConversationActivity, ft as webActorFromUser, i as measureTurnCompactionWait, kt as buildSteeringPiMessage, lt as createAndEnqueueConversation, m as latestProgressStatus, mt as decodeInputImages, n as executeAgentRun, ot as acceptsWebMessages, pt as resolveConversationDestination, rt as deliverReviewItemChange, st as appendAndEnqueueWebMessage, t as createAgentRunner, ut as createConversationId, vt as storeAttachment, x as renderBlockText, z as resolveDestinationVisibility } from "./agent-runner-_PYLv4Qo.js";
13
13
  import { a as withLock, n as MUTATION_LOCK_TTL_MS, r as acquireActiveLock } from "./locks-D-0h111u.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";
20
- import { _ as isEmptyUserInputAnswer, v as normalizeUserInputAnswer } from "./reporting-window-DgHgwQB3.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";
24
- import { n as healthReportSchema, t as apiErrorSchema } from "./common-Eu6sx09c.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";
14
+ import { r as getStateAdapter } from "./adapter-DVN3iwf9.js";
15
+ import { R as readMessageAttachments, c as conversationDetailReportSchema, p as conversationFeedSchema, u as conversationEventPageSchema } from "./conversation-DExTZw8B.js";
16
+ import { a as EVENT_SYSTEM_ACTOR, o as isEventConversationMessage } from "./prompt-BcHg-BMy.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-Dlio-o6u.js";
18
+ import { n as getAssistantReplyText, t as decideReply } from "./assistant-reply-DbebsAxi.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-CDEMsNtv.js";
20
+ import { _ as isEmptyUserInputAnswer, b as webMessageId, v as normalizeUserInputAnswer } from "./reporting-window-B-QP9zX1.js";
21
+ import { g as getTurnRequestDeadline, l as getVercelConversationWorkQueue } from "./background-compaction-queue-B9lmh8Ml.js";
22
+ import { D as stopConversationWork, E as steerWebPendingMessages, a as cancelHumanFacingPendingMessages, g as getConversationWorkState, h as getConversation, m as ensureConversationWake, r as appendAndEnqueueInboundMessage, w as requestConversationWork } from "./store-QzOfDwKA.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-bmG330Cf.js";
24
+ import { d as healthReportSchema, s as conversationPendingMessagesReportSchema, u as apiErrorSchema } from "./conversation-pending-messages-Dgz6hrJs.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-Dd9kCuQ-.js";
26
+ import { n as getTurnLifecycle, t as ConversationTurnLifecycleService } from "./turn-lifecycle-CJJsOhXB.js";
27
+ import { o as AgentRunError, s as executeTurn } from "./work-BTcCIbWu.js";
28
+ import { a as persistThreadStateById, i as persistThreadRuntimeState, n as getPersistedSandboxState, o as coerceThreadConversationState, r as getPersistedThreadState, t as getLocationConfigurationService } from "./thread-state-Bn87cfzE.js";
29
+ import { c as deleteWebAuthorization, d as createPausedTurns, f as getPausedTurnRequest, h as getTurnAuthorization, l as getWebAuthorization, m as wakePausedTurn, s as createWebAuthorization } from "./connections-C4h6mGha.js";
30
+ import { t as bindMessageAgent } from "./message-RpAnqHPY.js";
31
+ import { t as bindSpawnAgent } from "./spawn-C0DySQRV.js";
32
+ import { n as scheduleSessionCompletedPluginTasks, t as processPluginTask } from "./task-runner-CQkkUj3o.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-CQebxByj.js";
34
34
  import { createHash, createHmac, timingSafeEqual } from "node:crypto";
35
- import { z } from "zod";
35
+ import * as z from "zod";
36
36
  import { and, asc, desc, eq, gt, inArray, isNotNull, isNull, lte, max, ne, or, sql } from "drizzle-orm";
37
37
  import { conversationSidebarAnnotationSchema, createSlackSource, objectTypeSchema } from "@sentry/junior-plugin-api";
38
38
  import { alias } from "drizzle-orm/pg-core";
@@ -3774,10 +3774,14 @@ function resolveSlackConversationContext(input) {
3774
3774
  const type = typeFromSlackChannelType(input.channelType) ?? typeFromChannelId(input.channelId, input.channelName);
3775
3775
  if (!type) return void 0;
3776
3776
  const name = normalizeConversationName(type, input.channelName);
3777
+ const topic = input.channelTopic?.trim();
3778
+ const description = input.channelDescription?.trim();
3777
3779
  const visibility = conversationVisibilityFromSlackChannelType(input.channelType);
3778
3780
  return {
3779
3781
  type,
3780
3782
  ...name ? { name } : void 0,
3783
+ ...topic ? { topic } : void 0,
3784
+ ...description ? { description } : void 0,
3781
3785
  ...visibility ? { visibility } : void 0,
3782
3786
  ...input.botUserId ? { botUserId: input.botUserId } : void 0
3783
3787
  };
@@ -3887,33 +3891,30 @@ function inboundMessageProvenance(queued, teamId) {
3887
3891
  });
3888
3892
  return instructionProvenanceFor(author);
3889
3893
  }
3890
- /** Return the Slack channel name when it is available. */
3891
- async function resolveChannelName(thread) {
3892
- const existingName = thread.channel.name?.trim();
3893
- if (existingName) return existingName;
3894
- try {
3895
- return (await thread.channel.fetchMetadata()).name?.trim() || void 0;
3896
- } catch {
3897
- return;
3898
- }
3899
- }
3900
3894
  /**
3901
- * Return the Slack channel type of a message.
3895
+ * Return the Slack channel type, name, topic, and description of a message
3896
+ * with one `conversations.info` call.
3902
3897
  *
3903
3898
  * Slack delivers a channel mention as two events with the same `ts`: `message`
3904
3899
  * has `channel_type`, and `app_mention` does not. Junior stores the event that
3905
- * arrives first. When that event has no `channel_type`, ask Slack for the
3906
- * conversation, so the turn does not depend on the order of the two events.
3900
+ * arrives first. When that event has no `channel_type`, the live conversation
3901
+ * metadata supplies it, so the turn does not depend on the order of the two
3902
+ * events.
3907
3903
  */
3908
- async function resolveSlackChannelType(message, channelId) {
3904
+ async function resolveSlackChannelFacts(message, channelId) {
3909
3905
  const eventChannelType = resolveSlackChannelTypeFromMessage(message);
3910
- if (eventChannelType) return eventChannelType;
3911
3906
  const slackChannelId = parseSlackChannelId(channelId);
3912
- if (!slackChannelId) return;
3907
+ if (!slackChannelId) return { channelType: eventChannelType };
3913
3908
  try {
3914
- return slackChannelTypeFromConversationInfo(await getConversationInfo(slackChannelId));
3909
+ const info = await getConversationInfo(slackChannelId);
3910
+ return {
3911
+ channelType: eventChannelType ?? slackChannelTypeFromConversationInfo(info),
3912
+ name: info.name,
3913
+ topic: info.topic,
3914
+ description: info.description
3915
+ };
3915
3916
  } catch (error) {
3916
- if (error instanceof SlackActionError) return;
3917
+ if (error instanceof SlackActionError) return { channelType: eventChannelType };
3917
3918
  throw error;
3918
3919
  }
3919
3920
  }
@@ -3982,13 +3983,16 @@ function createSlackTurn(deps) {
3982
3983
  if (message.author.isMe) return;
3983
3984
  const threadId = getThreadId(thread, message);
3984
3985
  const channelId = getChannelId(thread, message);
3985
- const channelName = !options.execution && channelId ? await resolveChannelName(thread) : void 0;
3986
+ const channelFacts = options.execution ? { channelType: resolveSlackChannelTypeFromMessage(message) } : await resolveSlackChannelFacts(message, channelId);
3987
+ const channelName = channelFacts.name;
3988
+ const slackChannelType = channelFacts.channelType;
3986
3989
  const destination = requireSlackDestination(options.destination, "Slack reply execution");
3987
- const slackChannelType = options.execution ? resolveSlackChannelTypeFromMessage(message) : await resolveSlackChannelType(message, channelId);
3988
3990
  const slackConversation = resolveSlackConversationContext({
3989
3991
  botUserId: deps.getSlackAdapter().botUserId,
3990
3992
  channelId,
3991
3993
  channelName,
3994
+ channelTopic: channelFacts.topic,
3995
+ channelDescription: channelFacts.description,
3992
3996
  channelType: slackChannelType
3993
3997
  });
3994
3998
  const destinationVisibility = conversationVisibilityFromSlackChannelType(slackChannelType);
@@ -7118,6 +7122,398 @@ async function archiveConversation(viewer, conversationId, body) {
7118
7122
  if (result.status === "missing") throwApiError(404, "Conversation not found.");
7119
7123
  throwApiError(409, "Conversation received new activity.");
7120
7124
  }
7125
+ // src/api/mentions.ts
7126
+ const SLACK_USER_MENTION_RE = /<@([UW][A-Z0-9]+)(?:\|[^<>]*)?>/g;
7127
+ function mentionedSlackUserIds(texts) {
7128
+ const ids = texts.flatMap((text) => text ? [...text.matchAll(SLACK_USER_MENTION_RE)].map((m) => m[1]) : []);
7129
+ return [...new Set(ids)];
7130
+ }
7131
+ /**
7132
+ * Resolve the people that each source mentions, in source order. Every API
7133
+ * that returns display text uses this, so the dashboard can show the same
7134
+ * names and People links everywhere. It does one identity query per Slack
7135
+ * workspace.
7136
+ */
7137
+ async function resolveMentions(executor, sources) {
7138
+ const idsBySource = sources.map((source) => mentionedSlackUserIds(source.texts));
7139
+ const idsByTenant = /* @__PURE__ */ new Map();
7140
+ sources.forEach((source, index) => {
7141
+ if (idsBySource[index].length === 0) return;
7142
+ const ids = idsByTenant.get(source.tenantId) ?? /* @__PURE__ */ new Set();
7143
+ for (const id of idsBySource[index]) ids.add(id);
7144
+ idsByTenant.set(source.tenantId, ids);
7145
+ });
7146
+ const peopleByTenant = new Map(await Promise.all([...idsByTenant].map(async ([tenantId, ids]) => [tenantId, await readMentionedPeople(executor, tenantId, [...ids])])));
7147
+ return sources.map((source, index) => {
7148
+ const people = peopleByTenant.get(source.tenantId);
7149
+ return idsBySource[index].flatMap((id) => {
7150
+ const person = people?.get(id);
7151
+ return person ? [person] : [];
7152
+ });
7153
+ });
7154
+ }
7155
+ /**
7156
+ * Read current names for mentioned Slack users. Known Junior identities come
7157
+ * first. The email is set only for a linked, verified Junior user, because
7158
+ * that email is the People profile route.
7159
+ */
7160
+ async function readMentionedPeople(executor, tenantId, userIds) {
7161
+ const rows = await executor.db().select({
7162
+ displayName: juniorIdentities.displayName,
7163
+ emailVerified: juniorIdentities.emailVerified,
7164
+ handle: juniorIdentities.handle,
7165
+ providerSubjectId: juniorIdentities.providerSubjectId,
7166
+ userDisplayName: juniorUsers.displayName,
7167
+ userEmail: juniorUsers.primaryEmail
7168
+ }).from(juniorIdentities).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(and(eq(juniorIdentities.provider, "slack"), inArray(juniorIdentities.providerSubjectId, userIds), tenantId ? eq(juniorIdentities.providerTenantId, tenantId) : void 0));
7169
+ const people = /* @__PURE__ */ new Map();
7170
+ for (const row of rows) {
7171
+ if (people.has(row.providerSubjectId)) continue;
7172
+ const fullName = row.userDisplayName?.trim() || row.displayName?.trim();
7173
+ const email = row.emailVerified ? row.userEmail?.trim() : void 0;
7174
+ people.set(row.providerSubjectId, {
7175
+ slackUserId: row.providerSubjectId,
7176
+ ...fullName ? { fullName } : void 0,
7177
+ ...row.handle ? { slackUserName: row.handle } : void 0,
7178
+ ...email ? { email } : void 0
7179
+ });
7180
+ }
7181
+ const unnamed = userIds.filter((id) => {
7182
+ const person = people.get(id);
7183
+ return !person?.fullName && !person?.slackUserName;
7184
+ });
7185
+ if (tenantId && unnamed.length > 0) {
7186
+ const profiles = await Promise.all(unnamed.map((id) => lookupSlackUser(tenantId, id)));
7187
+ unnamed.forEach((id, index) => {
7188
+ const profile = profiles[index];
7189
+ if (!profile?.fullName && !profile?.userName) return;
7190
+ people.set(id, {
7191
+ ...people.get(id),
7192
+ slackUserId: id,
7193
+ ...profile.fullName ? { fullName: profile.fullName } : void 0,
7194
+ ...profile.userName ? { slackUserName: profile.userName } : void 0
7195
+ });
7196
+ });
7197
+ }
7198
+ return people;
7199
+ }
7200
+ // src/api/conversations/pending-messages.ts
7201
+ const slackMailboxAuthorSchema = z.object({
7202
+ userId: z.string(),
7203
+ userName: z.string().optional(),
7204
+ fullName: z.string().optional(),
7205
+ isMe: z.boolean().optional()
7206
+ }).passthrough();
7207
+ const slackMailboxMessageSchema = z.object({
7208
+ author: slackMailboxAuthorSchema,
7209
+ id: z.string().min(1),
7210
+ raw: z.unknown().optional()
7211
+ }).passthrough();
7212
+ const slackMailboxMetadataSchema = z.object({
7213
+ message: slackMailboxMessageSchema,
7214
+ platform: z.literal("slack")
7215
+ }).passthrough();
7216
+ /**
7217
+ * Project Slack text the way the Turn stores it in history. The SDK text
7218
+ * turns `<@U123>` into a bare `@U123` or `@name`, which the dashboard
7219
+ * cannot render as a mention.
7220
+ */
7221
+ function slackDisplayText(message, sdkText) {
7222
+ return parseContent({
7223
+ attachments: [],
7224
+ formatted: {
7225
+ type: "root",
7226
+ children: []
7227
+ },
7228
+ raw: message.raw,
7229
+ text: sdkText
7230
+ }).text;
7231
+ }
7232
+ function isoFromMs(value) {
7233
+ return new Date(value).toISOString();
7234
+ }
7235
+ function actorIdentityFromWebMetadata(metadata) {
7236
+ return {
7237
+ email: metadata.authorEmail.trim().toLowerCase(),
7238
+ ...metadata.authorFullName ? { fullName: metadata.authorFullName } : void 0
7239
+ };
7240
+ }
7241
+ async function actorIdentityFromSlackMetadata(metadata, teamId) {
7242
+ if (metadata.message.author.isMe === true) return void 0;
7243
+ const slackUserId = metadata.message.author.userId.trim();
7244
+ if (!slackUserId) return void 0;
7245
+ const profile = teamId ? await lookupSlackUser(teamId, slackUserId) : null;
7246
+ const slackUserName = profile?.userName?.trim() || metadata.message.author.userName?.trim();
7247
+ const fullName = profile?.fullName?.trim() || metadata.message.author.fullName?.trim();
7248
+ const email = profile?.email?.trim().toLowerCase();
7249
+ return {
7250
+ slackUserId,
7251
+ ...slackUserName ? { slackUserName } : void 0,
7252
+ ...fullName ? { fullName } : void 0,
7253
+ ...email ? { email } : void 0
7254
+ };
7255
+ }
7256
+ async function projectPendingMessage(message, canExposePayload) {
7257
+ if (message.source === "web") {
7258
+ const metadata = legacyWebMailboxMetadataSchema.safeParse(message.input.metadata);
7259
+ if (!metadata.success) return void 0;
7260
+ const text = message.input.text.trim();
7261
+ const attachments = readMessageAttachments(message.input.attachments);
7262
+ if (!text && !attachments.length) return void 0;
7263
+ return {
7264
+ createdAt: isoFromMs(message.createdAtMs),
7265
+ delivery: message.delivery,
7266
+ inboundMessageId: message.inboundMessageId,
7267
+ messageId: metadata.data.messageId,
7268
+ receivedAt: isoFromMs(message.receivedAtMs),
7269
+ role: "user",
7270
+ source: "web",
7271
+ ...canExposePayload ? {
7272
+ actorIdentity: actorIdentityFromWebMetadata(metadata.data),
7273
+ text,
7274
+ ...attachments.length ? { attachments } : void 0,
7275
+ ...message.input.reviewItemChange ? { reviewItemChange: message.input.reviewItemChange } : void 0
7276
+ } : { redacted: true }
7277
+ };
7278
+ }
7279
+ if (message.source === "slack") {
7280
+ const metadata = slackMailboxMetadataSchema.safeParse(message.input.metadata);
7281
+ if (!metadata.success) return void 0;
7282
+ if (metadata.data.message.author.isMe === true) return void 0;
7283
+ const text = slackDisplayText(metadata.data.message, message.input.text).trim();
7284
+ if (!text) return void 0;
7285
+ if (!canExposePayload) return {
7286
+ createdAt: isoFromMs(message.createdAtMs),
7287
+ delivery: message.delivery,
7288
+ inboundMessageId: message.inboundMessageId,
7289
+ messageId: metadata.data.message.id,
7290
+ receivedAt: isoFromMs(message.receivedAtMs),
7291
+ redacted: true,
7292
+ role: "user",
7293
+ source: "slack"
7294
+ };
7295
+ const actorIdentity = await actorIdentityFromSlackMetadata(metadata.data, message.destination?.platform === "slack" ? message.destination.teamId : void 0);
7296
+ return {
7297
+ createdAt: isoFromMs(message.createdAtMs),
7298
+ delivery: message.delivery,
7299
+ inboundMessageId: message.inboundMessageId,
7300
+ messageId: metadata.data.message.id,
7301
+ receivedAt: isoFromMs(message.receivedAtMs),
7302
+ role: "user",
7303
+ source: "slack",
7304
+ ...actorIdentity ? { actorIdentity } : void 0,
7305
+ ...message.input.reviewItemChange ? { reviewItemChange: message.input.reviewItemChange } : void 0,
7306
+ text
7307
+ };
7308
+ }
7309
+ }
7310
+ async function attachPendingMentions(conversationId, messages) {
7311
+ if (!messages.some((message) => message.text?.includes("<@"))) return messages;
7312
+ const executor = getSqlExecutor();
7313
+ const tenantId = (await loadConversationSlackTenantIds(executor, [conversationId])).get(conversationId);
7314
+ const mentions = await resolveMentions(executor, messages.map((message) => ({
7315
+ tenantId,
7316
+ texts: [message.text]
7317
+ })));
7318
+ return messages.map((message, index) => mentions[index].length > 0 ? {
7319
+ ...message,
7320
+ mentions: mentions[index]
7321
+ } : message);
7322
+ }
7323
+ /** Read the viewer's pending authorization, also one saved before a deploy. */
7324
+ async function findViewerWebAuthorization(conversationId, viewer) {
7325
+ for (const actorId of webActorUserIds(viewer)) {
7326
+ const authorization = await getWebAuthorization({
7327
+ actorId,
7328
+ conversationId
7329
+ });
7330
+ if (authorization) return authorization;
7331
+ }
7332
+ }
7333
+ /**
7334
+ * Read accepted mailbox messages that have not reached durable history yet.
7335
+ *
7336
+ * Returns only human-facing web and Slack rows. Internal mailbox work stays
7337
+ * hidden from the transcript.
7338
+ */
7339
+ async function readConversationPendingMessages(conversationId, options = {}) {
7340
+ if (!await getConversationStore().get({ conversationId })) return void 0;
7341
+ const access = (await readConversationAccessFromSql(getDb(), [conversationId], options.viewer)).get(conversationId);
7342
+ const canExposePayload = access?.canViewPrivateContent ?? false;
7343
+ const authorization = (access?.isParticipant ?? false) && options.viewer ? await findViewerWebAuthorization(conversationId, options.viewer) : void 0;
7344
+ const pendingMessages = (await getConversation({ conversationId }))?.execution.pendingMessages ?? [];
7345
+ const messages = await attachPendingMentions(conversationId, (await Promise.all(pendingMessages.map((message) => projectPendingMessage(message, canExposePayload)))).flatMap((message, index) => {
7346
+ if (!message) return [];
7347
+ const actorIdentityId = pendingMessages[index].input.authorIdentityId;
7348
+ return [canExposePayload && actorIdentityId ? {
7349
+ ...message,
7350
+ actorIdentityId
7351
+ } : message];
7352
+ }));
7353
+ return conversationPendingMessagesReportSchema.parse({
7354
+ ...authorization ? { authorization: {
7355
+ authorizationUrl: authorization.authorizationUrl,
7356
+ completionText: authorization.completionText,
7357
+ label: authorization.label
7358
+ } } : void 0,
7359
+ conversationId,
7360
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
7361
+ messages
7362
+ });
7363
+ }
7364
+ /** Load pending mailbox messages or throw a standard API not-found error. */
7365
+ async function requireConversationPendingMessages(conversationId, options = {}) {
7366
+ const report = await readConversationPendingMessages(conversationId, options);
7367
+ if (!report) throwApiError(404, "Conversation not found.");
7368
+ return report;
7369
+ }
7370
+ // src/api/conversations/cancel-pending-messages.ts
7371
+ /** Cancel accepted human-facing mailbox rows for one conversation participant. */
7372
+ async function cancelConversationPendingMessagesForViewer(viewer, conversationId, body = {}) {
7373
+ if (!await getConversationStore().get({ conversationId })) throwApiError(404, "Conversation not found.");
7374
+ if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(403, "Only conversation participants can cancel queued messages.");
7375
+ try {
7376
+ const result = await cancelHumanFacingPendingMessages({
7377
+ conversationId,
7378
+ ...body.inboundMessageIds ? { inboundMessageIds: body.inboundMessageIds } : void 0,
7379
+ ...body.receivedBefore ? { receivedBeforeMs: Date.parse(body.receivedBefore) } : void 0,
7380
+ conversationStore: getConversationStore()
7381
+ });
7382
+ await clearSlackPendingReactions({
7383
+ getSlackAdapter: getProductionSlackAdapter,
7384
+ messages: result.cancelledMessages
7385
+ });
7386
+ return {
7387
+ cancelledCount: result.cancelledInboundMessageIds.length,
7388
+ cancelledInboundMessageIds: result.cancelledInboundMessageIds,
7389
+ conversationId
7390
+ };
7391
+ } catch (error) {
7392
+ throwApiError(500, "Unable to cancel queued messages.", error);
7393
+ }
7394
+ }
7395
+ // src/api/conversations/cursor.ts
7396
+ const CURSOR_CONTEXT = "junior-conversation-report-cursor";
7397
+ const conversationCursorPayloadSchema = z.object({
7398
+ conversationId: z.string().min(1),
7399
+ seq: z.number().int().min(-1),
7400
+ version: z.literal(1)
7401
+ }).strict();
7402
+ function cursorSecret() {
7403
+ const secret = process.env.JUNIOR_SECRET?.trim();
7404
+ if (!secret) throw new Error("Cannot sign conversation cursor without JUNIOR_SECRET");
7405
+ return secret;
7406
+ }
7407
+ /** Sign one encoded cursor with the domain-separated server secret. */
7408
+ function signature(payload) {
7409
+ return createHmac("sha256", cursorSecret()).update(`${CURSOR_CONTEXT}:${payload}`).digest("base64url");
7410
+ }
7411
+ /** Encode an authenticated, conversation-bound event position for an API cursor. */
7412
+ function encodeConversationCursor(payload) {
7413
+ const encoded = Buffer.from(JSON.stringify({
7414
+ ...payload,
7415
+ version: 1
7416
+ }), "utf8").toString("base64url");
7417
+ return `${encoded}.${signature(encoded)}`;
7418
+ }
7419
+ /** Decode an authenticated reporting cursor for the expected conversation. */
7420
+ function decodeConversationCursor(args) {
7421
+ const [encoded, actualSignature, extra] = args.cursor.split(".");
7422
+ if (!encoded || !actualSignature || extra !== void 0) return void 0;
7423
+ const expected = Buffer.from(signature(encoded));
7424
+ const actual = Buffer.from(actualSignature);
7425
+ if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) return;
7426
+ try {
7427
+ const parsed = conversationCursorPayloadSchema.parse(JSON.parse(Buffer.from(encoded, "base64url").toString("utf8")));
7428
+ if (parsed.conversationId !== args.conversationId) return;
7429
+ return { seq: parsed.seq };
7430
+ } catch {
7431
+ return;
7432
+ }
7433
+ }
7434
+ // src/api/conversations/create.ts
7435
+ /** Turn image validation failures into request errors before accepting work. */
7436
+ function parseImages(images) {
7437
+ try {
7438
+ return decodeInputImages(images ?? []);
7439
+ } catch (error) {
7440
+ throwApiError(400, error instanceof Error ? error.message : "Unable to read images.");
7441
+ }
7442
+ }
7443
+ function actorFromViewer(viewer) {
7444
+ const normalized = viewer.email.trim().toLowerCase();
7445
+ return webActorFromUser(viewer, { userName: normalized.split("@")[0] || normalized });
7446
+ }
7447
+ /** Create a dashboard root conversation and enqueue its first message. */
7448
+ async function createConversationForViewer(viewer, body, services) {
7449
+ const images = parseImages(body.images);
7450
+ try {
7451
+ return await createAndEnqueueConversation({
7452
+ actor: actorFromViewer(viewer),
7453
+ idempotencyKey: body.idempotencyKey,
7454
+ message: body.message,
7455
+ images,
7456
+ ...body.visibility ? { visibility: body.visibility } : void 0
7457
+ }, {
7458
+ conversationStore: getConversationStore(),
7459
+ attachmentStorage: services.attachmentStorage,
7460
+ queue: services.queue
7461
+ });
7462
+ } catch (error) {
7463
+ throwApiError(500, "Unable to create conversation.", error);
7464
+ }
7465
+ }
7466
+ /** Append one dashboard message to an existing conversation. */
7467
+ async function appendConversationMessageForViewer(viewer, conversationId, body, services) {
7468
+ const conversation = await getConversationStore().get({ conversationId });
7469
+ if (!conversation) throwApiError(404, "Conversation not found.");
7470
+ if (!acceptsWebMessages(conversationId, conversation.destination)) throwApiError(409, "Conversation does not accept web messages.");
7471
+ if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(403, "Only conversation participants can add messages.");
7472
+ const images = parseImages(body.images);
7473
+ const actor = actorFromViewer(viewer);
7474
+ const append = () => appendAndEnqueueWebMessage({
7475
+ actor,
7476
+ conversationId,
7477
+ idempotencyKey: body.idempotencyKey,
7478
+ message: body.message,
7479
+ images
7480
+ }, {
7481
+ conversationStore: getConversationStore(),
7482
+ attachmentStorage: services.attachmentStorage,
7483
+ queue: services.queue
7484
+ });
7485
+ const closeAnswered = () => closeReviewItemsAnsweredByReply({
7486
+ conversationId,
7487
+ delivery: {
7488
+ queue: services.queue,
7489
+ show: createSlackReviewItemShow(getProductionSlackAdapter)
7490
+ },
7491
+ resolveUser: async () => viewer,
7492
+ text: body.message
7493
+ });
7494
+ try {
7495
+ let accepted;
7496
+ try {
7497
+ accepted = await append();
7498
+ } catch (error) {
7499
+ const state = getStateAdapter();
7500
+ await state.connect();
7501
+ const [messageId, work] = await Promise.all([webMessageId({
7502
+ conversationId,
7503
+ idempotencyKey: body.idempotencyKey
7504
+ }), getConversationWorkState({
7505
+ conversationId,
7506
+ state
7507
+ })]);
7508
+ if (work?.execution.inboundMessageIds.includes(messageId)) await closeAnswered();
7509
+ throw error;
7510
+ }
7511
+ await closeAnswered();
7512
+ return accepted;
7513
+ } catch (error) {
7514
+ throwApiError(500, "Unable to append message.", error);
7515
+ }
7516
+ }
7121
7517
  // src/chat/plugins/conversation-sidebar.ts
7122
7518
  /** Show native objects by default and let plugins select compact sidebar labels. */
7123
7519
  async function listConversationSidebarAnnotations(conversationIds, annotationsByConversation) {
@@ -7687,45 +8083,6 @@ async function readConversationModelUsageFromSql(executor, options) {
7687
8083
  }] : [];
7688
8084
  });
7689
8085
  }
7690
- // src/api/conversations/cursor.ts
7691
- const CURSOR_CONTEXT = "junior-conversation-report-cursor";
7692
- const conversationCursorPayloadSchema = z.object({
7693
- conversationId: z.string().min(1),
7694
- seq: z.number().int().min(-1),
7695
- version: z.literal(1)
7696
- }).strict();
7697
- function cursorSecret() {
7698
- const secret = process.env.JUNIOR_SECRET?.trim();
7699
- if (!secret) throw new Error("Cannot sign conversation cursor without JUNIOR_SECRET");
7700
- return secret;
7701
- }
7702
- /** Sign one encoded cursor with the domain-separated server secret. */
7703
- function signature(payload) {
7704
- return createHmac("sha256", cursorSecret()).update(`${CURSOR_CONTEXT}:${payload}`).digest("base64url");
7705
- }
7706
- /** Encode an authenticated, conversation-bound event position for an API cursor. */
7707
- function encodeConversationCursor(payload) {
7708
- const encoded = Buffer.from(JSON.stringify({
7709
- ...payload,
7710
- version: 1
7711
- }), "utf8").toString("base64url");
7712
- return `${encoded}.${signature(encoded)}`;
7713
- }
7714
- /** Decode an authenticated reporting cursor for the expected conversation. */
7715
- function decodeConversationCursor(args) {
7716
- const [encoded, actualSignature, extra] = args.cursor.split(".");
7717
- if (!encoded || !actualSignature || extra !== void 0) return void 0;
7718
- const expected = Buffer.from(signature(encoded));
7719
- const actual = Buffer.from(actualSignature);
7720
- if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) return;
7721
- try {
7722
- const parsed = conversationCursorPayloadSchema.parse(JSON.parse(Buffer.from(encoded, "base64url").toString("utf8")));
7723
- if (parsed.conversationId !== args.conversationId) return;
7724
- return { seq: parsed.seq };
7725
- } catch {
7726
- return;
7727
- }
7728
- }
7729
8086
  // src/api/conversations/first-message.ts
7730
8087
  /**
7731
8088
  * Read the text of the first human message for each untitled conversation.
@@ -7741,81 +8098,6 @@ async function readFirstHumanMessageTexts(db, conversations) {
7741
8098
  }).from(juniorConversationEvents).where(and(inArray(juniorConversationEvents.conversationId, untitledIds), eq(juniorConversationEvents.type, "message"), sql`${juniorConversationEvents.payload}->>'role' = 'user'`, sql`coalesce(${juniorConversationEvents.payload}->'meta'->'author'->>'isBot', 'false') <> 'true'`, isNotNull(sql`nullif(btrim(${text}), '')`))).orderBy(juniorConversationEvents.conversationId, asc(juniorConversationEvents.createdAt), asc(juniorConversationEvents.seq));
7742
8099
  return new Map(rows.map((row) => [row.conversationId, row.text]));
7743
8100
  }
7744
- // src/api/mentions.ts
7745
- const SLACK_USER_MENTION_RE = /<@([UW][A-Z0-9]+)(?:\|[^<>]*)?>/g;
7746
- function mentionedSlackUserIds(texts) {
7747
- const ids = texts.flatMap((text) => text ? [...text.matchAll(SLACK_USER_MENTION_RE)].map((m) => m[1]) : []);
7748
- return [...new Set(ids)];
7749
- }
7750
- /**
7751
- * Resolve the people that each source mentions, in source order. Every API
7752
- * that returns display text uses this, so the dashboard can show the same
7753
- * names and People links everywhere. It does one identity query per Slack
7754
- * workspace.
7755
- */
7756
- async function resolveMentions(executor, sources) {
7757
- const idsBySource = sources.map((source) => mentionedSlackUserIds(source.texts));
7758
- const idsByTenant = /* @__PURE__ */ new Map();
7759
- sources.forEach((source, index) => {
7760
- if (idsBySource[index].length === 0) return;
7761
- const ids = idsByTenant.get(source.tenantId) ?? /* @__PURE__ */ new Set();
7762
- for (const id of idsBySource[index]) ids.add(id);
7763
- idsByTenant.set(source.tenantId, ids);
7764
- });
7765
- const peopleByTenant = new Map(await Promise.all([...idsByTenant].map(async ([tenantId, ids]) => [tenantId, await readMentionedPeople(executor, tenantId, [...ids])])));
7766
- return sources.map((source, index) => {
7767
- const people = peopleByTenant.get(source.tenantId);
7768
- return idsBySource[index].flatMap((id) => {
7769
- const person = people?.get(id);
7770
- return person ? [person] : [];
7771
- });
7772
- });
7773
- }
7774
- /**
7775
- * Read current names for mentioned Slack users. Known Junior identities come
7776
- * first. The email is set only for a linked, verified Junior user, because
7777
- * that email is the People profile route.
7778
- */
7779
- async function readMentionedPeople(executor, tenantId, userIds) {
7780
- const rows = await executor.db().select({
7781
- displayName: juniorIdentities.displayName,
7782
- emailVerified: juniorIdentities.emailVerified,
7783
- handle: juniorIdentities.handle,
7784
- providerSubjectId: juniorIdentities.providerSubjectId,
7785
- userDisplayName: juniorUsers.displayName,
7786
- userEmail: juniorUsers.primaryEmail
7787
- }).from(juniorIdentities).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(and(eq(juniorIdentities.provider, "slack"), inArray(juniorIdentities.providerSubjectId, userIds), tenantId ? eq(juniorIdentities.providerTenantId, tenantId) : void 0));
7788
- const people = /* @__PURE__ */ new Map();
7789
- for (const row of rows) {
7790
- if (people.has(row.providerSubjectId)) continue;
7791
- const fullName = row.userDisplayName?.trim() || row.displayName?.trim();
7792
- const email = row.emailVerified ? row.userEmail?.trim() : void 0;
7793
- people.set(row.providerSubjectId, {
7794
- slackUserId: row.providerSubjectId,
7795
- ...fullName ? { fullName } : void 0,
7796
- ...row.handle ? { slackUserName: row.handle } : void 0,
7797
- ...email ? { email } : void 0
7798
- });
7799
- }
7800
- const unnamed = userIds.filter((id) => {
7801
- const person = people.get(id);
7802
- return !person?.fullName && !person?.slackUserName;
7803
- });
7804
- if (tenantId && unnamed.length > 0) {
7805
- const profiles = await Promise.all(unnamed.map((id) => lookupSlackUser(tenantId, id)));
7806
- unnamed.forEach((id, index) => {
7807
- const profile = profiles[index];
7808
- if (!profile?.fullName && !profile?.userName) return;
7809
- people.set(id, {
7810
- ...people.get(id),
7811
- slackUserId: id,
7812
- ...profile.fullName ? { fullName: profile.fullName } : void 0,
7813
- ...profile.userName ? { slackUserName: profile.userName } : void 0
7814
- });
7815
- });
7816
- }
7817
- return people;
7818
- }
7819
8101
  // src/api/conversations/mentions.ts
7820
8102
  /** Text in one event that the dashboard renders with mentions. */
7821
8103
  function eventMentionTexts(data) {
@@ -8277,14 +8559,19 @@ function participantKey(row) {
8277
8559
  return row.userId ? `user:${row.userId}` : `identity:${row.identityId}`;
8278
8560
  }
8279
8561
  async function readParticipantRows(db, conversationIds) {
8562
+ const authors = db.select({
8563
+ conversationId: juniorConversationEvents.conversationId,
8564
+ actorIdentityId: juniorConversationEvents.actorIdentityId,
8565
+ seq: sql`min(${juniorConversationEvents.seq})`.mapWith(Number).as("first_seq")
8566
+ }).from(juniorConversationEvents).where(and(inArray(juniorConversationEvents.conversationId, [...conversationIds]), isNotNull(juniorConversationEvents.actorIdentityId))).groupBy(juniorConversationEvents.conversationId, juniorConversationEvents.actorIdentityId).as("authors");
8280
8567
  const [rootRows, eventRows] = await Promise.all([db.select({
8281
8568
  conversationId: juniorConversations.conversationId,
8282
8569
  ...identityColumns
8283
- }).from(juniorConversations).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(inArray(juniorConversations.conversationId, [...conversationIds])), db.selectDistinctOn([juniorConversationEvents.conversationId, juniorConversationEvents.actorIdentityId], {
8284
- conversationId: juniorConversationEvents.conversationId,
8285
- seq: juniorConversationEvents.seq,
8570
+ }).from(juniorConversations).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(inArray(juniorConversations.conversationId, [...conversationIds])), db.select({
8571
+ conversationId: authors.conversationId,
8572
+ seq: authors.seq,
8286
8573
  ...identityColumns
8287
- }).from(juniorConversationEvents).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversationEvents.actorIdentityId)).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).innerJoin(juniorConversations, eq(juniorConversations.conversationId, juniorConversationEvents.conversationId)).innerJoin(juniorConversationParticipants, and(eq(juniorConversationParticipants.userId, juniorIdentities.userId), eq(juniorConversationParticipants.rootConversationId, sql`coalesce(${juniorConversations.rootConversationId}, ${juniorConversations.conversationId})`))).where(inArray(juniorConversationEvents.conversationId, [...conversationIds])).orderBy(asc(juniorConversationEvents.conversationId), asc(juniorConversationEvents.actorIdentityId), asc(juniorConversationEvents.seq))]);
8574
+ }).from(authors).innerJoin(juniorIdentities, eq(juniorIdentities.id, authors.actorIdentityId)).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).innerJoin(juniorConversations, eq(juniorConversations.conversationId, authors.conversationId)).innerJoin(juniorConversationParticipants, and(eq(juniorConversationParticipants.userId, juniorIdentities.userId), eq(juniorConversationParticipants.rootConversationId, sql`coalesce(${juniorConversations.rootConversationId}, ${juniorConversations.conversationId})`))).where(inArray(juniorConversations.conversationId, [...conversationIds]))]);
8288
8575
  return [...rootRows, ...eventRows.sort((left, right) => left.seq - right.seq)];
8289
8576
  }
8290
8577
  async function groupParticipants(db, rows) {
@@ -8492,7 +8779,7 @@ async function readConversationFeedFromSql(options = {}) {
8492
8779
  if (filter?.kind === "viewer" && status === "active") rows.push(...await waitingRowsOutsidePage(db, filter, rows));
8493
8780
  const conversations = rows.map((row) => conversationFromRow(row));
8494
8781
  const conversationIds = conversations.map((conversation) => conversation.conversationId);
8495
- const [accessByConversation, viewerMarksByConversation, annotationsByConversation, auxiliaryCostsByRoot, metricsByRoot, participantsByConversation, teamDomainByTeamId, conversationWork, lastUserMessageAtByConversation, activityPreviewByConversation, automationTitleByConversation, firstHumanMessageTextByConversation] = await Promise.all([
8782
+ const [accessByConversation, viewerMarksByConversation, annotationsByConversation, auxiliaryCostsByRoot, metricsByRoot, participantsByConversation, teamDomainByTeamId, { work: conversationWork, lastUserMessageAt: lastUserMessageAtByConversation }, activityPreviewByConversation, automationTitleByConversation, firstHumanMessageTextByConversation] = await Promise.all([
8496
8783
  readConversationAccessFromSql(db, conversationIds, options.viewer),
8497
8784
  conversationViewerMarks(db, conversationIds, filter?.kind === "viewer" ? { userId: filter.userId } : filter?.kind === "actorEmail" ? { email: filter.email } : void 0),
8498
8785
  listConversationAnnotationsById(db, conversationIds),
@@ -8500,8 +8787,10 @@ async function readConversationFeedFromSql(options = {}) {
8500
8787
  readConversationTreeMetricsFromSql(db, conversationIds),
8501
8788
  readConversationParticipants(db, conversationIds),
8502
8789
  resolveSlackTeamDomains(conversations.flatMap((conversation) => conversation.location?.provider === "slack" ? [conversation.location.teamId] : [])),
8503
- listConversationWork(conversationIds),
8504
- readLastUserMessageAtByConversation(db, conversationIds),
8790
+ listConversationWork(conversationIds).then(async (work) => ({
8791
+ work,
8792
+ lastUserMessageAt: await readLastUserMessageAtByConversation(db, work.assignedIds.filter((conversationId) => work.finishedAtById[conversationId]))
8793
+ })),
8505
8794
  readConversationActivityPreviews(db, conversationIds),
8506
8795
  readAutomationTitlesByConversationId(conversations),
8507
8796
  readFirstHumanMessageTexts(db, conversations)
@@ -8568,31 +8857,27 @@ async function readConversationFeed(options = {}) {
8568
8857
  return conversationFeedSchema.parse(await readConversationFeedFromSql(options));
8569
8858
  }
8570
8859
  // src/api/conversations/event-list.ts
8571
- /** Read one bounded page of reporting events before, after, or around a signed cursor. */
8860
+ /** Read one bounded page of reporting events before, after, or around a boundary. */
8572
8861
  async function readConversationEvents(conversationId, boundary, options = {}) {
8573
8862
  const record = await readConversationRecordFromSql(conversationId);
8574
8863
  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.");
8864
+ const position = await boundaryPosition(conversationId, boundary);
8580
8865
  const canExposePayload = (await readConversationAccessFromSql(getDb(), [conversationId], options.viewer)).get(conversationId)?.canViewPrivateContent ?? false;
8581
8866
  const transcriptPurgedAtMs = record.conversation.transcriptPurgedAtMs;
8582
8867
  const pageArgs = {
8583
8868
  canExposePayload,
8584
8869
  conversationId,
8585
- limit: options.limit ?? 500
8870
+ limit: options.limit ?? 150
8586
8871
  };
8587
- const page = transcriptPurgedAtMs !== void 0 ? { events: [] } : "after" in boundary ? await readConversationEventPageAfter(getSqlExecutor(), {
8872
+ const page = transcriptPurgedAtMs !== void 0 ? { events: [] } : position.direction === "after" ? await readConversationEventPageAfter(getSqlExecutor(), {
8588
8873
  ...pageArgs,
8589
- afterSeq: cursor.seq
8590
- }) : "around" in boundary ? await readConversationEventPageAround(getSqlExecutor(), {
8874
+ afterSeq: position.seq
8875
+ }) : position.direction === "around" ? await readConversationEventPageAround(getSqlExecutor(), {
8591
8876
  ...pageArgs,
8592
- seq: cursor.seq
8877
+ seq: position.seq
8593
8878
  }) : await readConversationEventPage(getSqlExecutor(), {
8594
8879
  ...pageArgs,
8595
- beforeSeq: cursor.seq
8880
+ beforeSeq: position.seq
8596
8881
  });
8597
8882
  return conversationEventPageSchema.parse(await conversationEventPageReport(getSqlExecutor(), {
8598
8883
  conversationId,
@@ -8603,6 +8888,39 @@ async function readConversationEvents(conversationId, boundary, options = {}) {
8603
8888
  page
8604
8889
  }));
8605
8890
  }
8891
+ /** Resolve a page boundary to a direction and an event seq. */
8892
+ async function boundaryPosition(conversationId, boundary) {
8893
+ if ("event" in boundary) return {
8894
+ direction: "around",
8895
+ seq: boundary.event
8896
+ };
8897
+ if ("turn" in boundary) {
8898
+ const seq = await readTurnStartedSeq(conversationId, boundary.turn);
8899
+ if (seq === void 0) throwApiError(404, "Turn not found.");
8900
+ return {
8901
+ direction: "around",
8902
+ seq
8903
+ };
8904
+ }
8905
+ const [direction, value] = "after" in boundary ? ["after", boundary.after] : "around" in boundary ? ["around", boundary.around] : ["before", boundary.before];
8906
+ const cursor = decodeConversationCursor({
8907
+ conversationId,
8908
+ cursor: value
8909
+ });
8910
+ if (!cursor) throwApiError(400, "Invalid conversation cursor.");
8911
+ return {
8912
+ direction,
8913
+ seq: cursor.seq
8914
+ };
8915
+ }
8916
+ /**
8917
+ * Find the event that started a Turn. The `(conversation_id, type, seq)`
8918
+ * index reads only this Conversation's `turn_started` rows.
8919
+ */
8920
+ async function readTurnStartedSeq(conversationId, turnId) {
8921
+ const [row] = await getDb().select({ seq: juniorConversationEvents.seq }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "turn_started"), sql`${juniorConversationEvents.payload}->>'turnId' = ${turnId}`)).limit(1);
8922
+ return row?.seq;
8923
+ }
8606
8924
  /** Attach mentions and signed cursors to one bounded page of events. */
8607
8925
  async function conversationEventPageReport(executor, args) {
8608
8926
  const { conversationId, page } = args;
@@ -8618,6 +8936,57 @@ async function conversationEventPageReport(executor, args) {
8618
8936
  generatedAt: (/* @__PURE__ */ new Date()).toISOString()
8619
8937
  };
8620
8938
  }
8939
+ // src/api/conversations/agent-tree.ts
8940
+ /** Bound the parent chain that one agent tree reads. */
8941
+ const MAX_AGENT_TREE_DEPTH = 16;
8942
+ const CHILD_LABEL = "Subagent";
8943
+ async function readParentConversationId(conversationId) {
8944
+ const [row] = await getDb().select({ parentId: juniorConversations.parentConversationId }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId));
8945
+ return row?.parentId ?? void 0;
8946
+ }
8947
+ /**
8948
+ * Read the agent tree of a child Conversation: its parent chain, root first,
8949
+ * with the child last. Returns undefined for a root Conversation. Each
8950
+ * Conversation has its own access check, so a viewer sees a label only where
8951
+ * they can see private content.
8952
+ */
8953
+ async function readConversationAgentTree(conversationId, viewer) {
8954
+ const ids = [conversationId];
8955
+ let parentId = await readParentConversationId(conversationId);
8956
+ while (parentId && !ids.includes(parentId) && ids.length < MAX_AGENT_TREE_DEPTH) {
8957
+ ids.unshift(parentId);
8958
+ parentId = await readParentConversationId(parentId);
8959
+ }
8960
+ if (ids.length < 2) return;
8961
+ const root = parentId ? void 0 : await getConversationStore().get({ conversationId: ids[0] });
8962
+ const [access, automationTitleByConversation, firstHumanMessageTextByConversation] = await Promise.all([
8963
+ readConversationAccessFromSql(getDb(), ids, viewer),
8964
+ readAutomationTitlesByConversationId(root ? [root] : []),
8965
+ readFirstHumanMessageTexts(getDb(), root ? [root] : [])
8966
+ ]);
8967
+ return await Promise.all(ids.map(async (id) => {
8968
+ const itemAccess = access.get(id);
8969
+ if (root?.conversationId === id) return {
8970
+ conversationId: id,
8971
+ label: conversationSummaryFromStoredConversation({
8972
+ access: itemAccess,
8973
+ automationTitle: automationTitleByConversation.get(id),
8974
+ conversation: root,
8975
+ durationMs: 0,
8976
+ firstHumanMessageText: firstHumanMessageTextByConversation.get(id)
8977
+ }).displayTitle
8978
+ };
8979
+ if (!itemAccess?.canViewPrivateContent) return {
8980
+ conversationId: id,
8981
+ label: CHILD_LABEL
8982
+ };
8983
+ const agent = await getChildAgentLabel(id);
8984
+ return {
8985
+ conversationId: id,
8986
+ label: agent?.title ?? agent?.agentName ?? CHILD_LABEL
8987
+ };
8988
+ }));
8989
+ }
8621
8990
  // src/api/conversations/fork.ts
8622
8991
  /** Fork a Conversation that the viewer can read into a new root they own. */
8623
8992
  async function forkConversationForViewer(viewer, sourceConversationId, body) {
@@ -8675,63 +9044,21 @@ async function readConversationForks(conversationId, viewer) {
8675
9044
  }
8676
9045
  return result;
8677
9046
  }
8678
- // src/api/conversations/agent-tree.ts
8679
- /** Bound the parent chain that one agent tree reads. */
8680
- const MAX_AGENT_TREE_DEPTH = 16;
8681
- const CHILD_LABEL = "Subagent";
8682
- async function readParentConversationId(conversationId) {
8683
- const [row] = await getDb().select({ parentId: juniorConversations.parentConversationId }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId));
8684
- return row?.parentId ?? void 0;
8685
- }
9047
+ // src/api/conversations/read-position.ts
8686
9048
  /**
8687
- * Read the agent tree of a child Conversation: its parent chain, root first,
8688
- * with the child last. Returns undefined for a root Conversation. Each
8689
- * Conversation has its own access check, so a viewer sees a label only where
8690
- * they can see private content.
9049
+ * Read how far the viewer has read one Conversation, if they have read it.
9050
+ *
9051
+ * The viewer saw every Message up to one they wrote, also one sent from
9052
+ * Slack, so the position is at least their latest Message.
8691
9053
  */
8692
- async function readConversationAgentTree(conversationId, viewer) {
8693
- const ids = [conversationId];
8694
- let parentId = await readParentConversationId(conversationId);
8695
- while (parentId && !ids.includes(parentId) && ids.length < MAX_AGENT_TREE_DEPTH) {
8696
- ids.unshift(parentId);
8697
- parentId = await readParentConversationId(parentId);
8698
- }
8699
- if (ids.length < 2) return;
8700
- const root = parentId ? void 0 : await getConversationStore().get({ conversationId: ids[0] });
8701
- const [access, automationTitleByConversation, firstHumanMessageTextByConversation] = await Promise.all([
8702
- readConversationAccessFromSql(getDb(), ids, viewer),
8703
- readAutomationTitlesByConversationId(root ? [root] : []),
8704
- readFirstHumanMessageTexts(getDb(), root ? [root] : [])
8705
- ]);
8706
- return await Promise.all(ids.map(async (id) => {
8707
- const itemAccess = access.get(id);
8708
- if (root?.conversationId === id) return {
8709
- conversationId: id,
8710
- label: conversationSummaryFromStoredConversation({
8711
- access: itemAccess,
8712
- automationTitle: automationTitleByConversation.get(id),
8713
- conversation: root,
8714
- durationMs: 0,
8715
- firstHumanMessageText: firstHumanMessageTextByConversation.get(id)
8716
- }).displayTitle
8717
- };
8718
- if (!itemAccess?.canViewPrivateContent) return {
8719
- conversationId: id,
8720
- label: CHILD_LABEL
8721
- };
8722
- const agent = await getChildAgentLabel(id);
8723
- return {
8724
- conversationId: id,
8725
- label: agent?.title ?? agent?.agentName ?? CHILD_LABEL
8726
- };
8727
- }));
8728
- }
8729
- // src/api/conversations/read-position.ts
8730
- /** Read how far the viewer has read one Conversation, if they have read it. */
8731
9054
  async function readConversationReadPosition(viewer, conversationId) {
8732
- const [row] = await getDb().select({ lastReadSeq: juniorConversationReadPositions.lastReadSeq }).from(juniorConversationReadPositions).where(and(eq(juniorConversationReadPositions.userId, viewer.id), eq(juniorConversationReadPositions.conversationId, conversationId))).limit(1);
9055
+ const [row] = await getDb().select({ lastReadSeq: sql`greatest(${juniorConversationReadPositions.lastReadSeq}, (${latestViewerMessageSeq(viewer, conversationId)}))` }).from(juniorConversationReadPositions).where(and(eq(juniorConversationReadPositions.userId, viewer.id), eq(juniorConversationReadPositions.conversationId, conversationId))).limit(1);
8733
9056
  return row;
8734
9057
  }
9058
+ /** The seq of the latest Message that one of the viewer's Identities wrote. */
9059
+ function latestViewerMessageSeq(viewer, conversationId) {
9060
+ return getDb().select({ seq: max(juniorConversationEvents.seq) }).from(juniorConversationEvents).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversationEvents.actorIdentityId)).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "message"), eq(juniorIdentities.userId, viewer.id)));
9061
+ }
8735
9062
  /**
8736
9063
  * Move the viewer's read position forward.
8737
9064
  *
@@ -8743,7 +9070,7 @@ async function markConversationRead(viewer, conversationId, body) {
8743
9070
  const db = getDb();
8744
9071
  const [conversation] = await db.select({ lastSeq: max(juniorConversationEvents.seq) }).from(juniorConversations).leftJoin(juniorConversationEvents, eq(juniorConversationEvents.conversationId, juniorConversations.conversationId)).where(eq(juniorConversations.conversationId, conversationId)).groupBy(juniorConversations.conversationId);
8745
9072
  if (!conversation) throwApiError(404, "Conversation not found.");
8746
- const [row] = await db.insert(juniorConversationReadPositions).values({
9073
+ await db.insert(juniorConversationReadPositions).values({
8747
9074
  conversationId,
8748
9075
  lastReadSeq: Math.min(body.lastReadSeq, conversation.lastSeq ?? 0),
8749
9076
  updatedAt: /* @__PURE__ */ new Date(),
@@ -8754,8 +9081,76 @@ async function markConversationRead(viewer, conversationId, body) {
8754
9081
  lastReadSeq: sql`greatest(${juniorConversationReadPositions.lastReadSeq}, excluded.last_read_seq)`,
8755
9082
  updatedAt: sql`excluded.updated_at`
8756
9083
  }
8757
- }).returning({ lastReadSeq: juniorConversationReadPositions.lastReadSeq });
8758
- return row;
9084
+ });
9085
+ return await readConversationReadPosition(viewer, conversationId);
9086
+ }
9087
+ // src/api/conversations/detail-etag.ts
9088
+ /**
9089
+ * Sum the detail versions of a Conversation and its child agents. Child
9090
+ * writes bump only their own row, and the row count changes when a child
9091
+ * starts, so the parent needs no bump of its own.
9092
+ */
9093
+ async function readSubtreeDetailVersion(conversationId) {
9094
+ const [row] = await getDb().select({
9095
+ conversations: sql`count(*)::int`,
9096
+ version: sql`coalesce(sum(${juniorConversations.detailVersion}), 0)::text`
9097
+ }).from(juniorConversations).innerJoin(conversationSubtree([conversationId]), eq(conversationSubtreeColumns.conversationId, juniorConversations.conversationId));
9098
+ return row ?? {
9099
+ conversations: 0,
9100
+ version: "0"
9101
+ };
9102
+ }
9103
+ /** Read the detail state that the ETag hashes and the report shows. */
9104
+ async function readConversationDetailState(conversationId, viewer) {
9105
+ const [access, viewerMarks, forks, agentTree, readPosition, autoArchive] = await Promise.all([
9106
+ readConversationAccessFromSql(getDb(), [conversationId], viewer),
9107
+ viewer ? readConversationViewerMarks(viewer, conversationId) : void 0,
9108
+ readConversationForks(conversationId, viewer),
9109
+ readConversationAgentTree(conversationId, viewer),
9110
+ viewer ? readConversationReadPosition(viewer, conversationId) : void 0,
9111
+ viewer ? readConversationAutoArchive(viewer, conversationId) : void 0
9112
+ ]);
9113
+ return {
9114
+ access: access.get(conversationId),
9115
+ agentTree,
9116
+ autoArchive,
9117
+ forks,
9118
+ readPosition,
9119
+ viewerMarks
9120
+ };
9121
+ }
9122
+ /**
9123
+ * Return the detail ETag without building the report, or undefined for a
9124
+ * missing Conversation. The state comes back too, so the report reuses it
9125
+ * and matches the ETag.
9126
+ *
9127
+ * Shared content is covered by `detail_version`. The detail state is cheap,
9128
+ * so it is read on each request. Names, avatars, Automation titles, and
9129
+ * plugin sidebar labels are not covered: they refresh with the next detail
9130
+ * change or a reload.
9131
+ *
9132
+ * The read position is not hashed. The dashboard writes it as the reader
9133
+ * scrolls and puts the stored value in its cached detail, so a poll after a
9134
+ * read can answer 304. Other tabs and devices get it with the next detail
9135
+ * change or a reload.
9136
+ */
9137
+ async function readConversationDetailEtag(conversationId, options) {
9138
+ const [subtree, state] = await Promise.all([readSubtreeDetailVersion(conversationId), readConversationDetailState(conversationId, options.viewer)]);
9139
+ if (subtree.conversations === 0) return void 0;
9140
+ const basis = JSON.stringify({
9141
+ access: state.access ?? null,
9142
+ agentTree: state.agentTree ?? null,
9143
+ autoArchive: state.autoArchive ?? null,
9144
+ forks: state.forks,
9145
+ junior: JUNIOR_VERSION,
9146
+ limit: options.limit ?? null,
9147
+ subtree,
9148
+ viewerMarks: state.viewerMarks ?? null
9149
+ });
9150
+ return {
9151
+ etag: createHash("sha256").update(basis).digest("hex"),
9152
+ state
9153
+ };
8759
9154
  }
8760
9155
  // src/api/conversations/detail.ts
8761
9156
  /** Project stored metadata and a bounded event page into a signed history cursor. */
@@ -8810,12 +9205,13 @@ function projectConversationDetail(args) {
8810
9205
  };
8811
9206
  }
8812
9207
  async function readConversationDetailFromSql(conversationId, options) {
8813
- const record = await readConversationRecordFromSql(conversationId);
9208
+ const [record, state] = await Promise.all([readConversationRecordFromSql(conversationId), options.state ?? readConversationDetailState(conversationId, options.viewer)]);
8814
9209
  if (!record) return void 0;
8815
- const viewerMarks = options.viewer ? await readConversationViewerMarks(options.viewer, conversationId) : void 0;
9210
+ const { access, readPosition } = state;
9211
+ const canExposePayload = access?.canViewPrivateContent ?? false;
8816
9212
  const executor = getSqlExecutor();
8817
- const [accessByConversation, annotations, automationTitleByConversation, auxiliaryCostsByConversation, briefVersion, firstHumanMessageTextByConversation, modelUsage, metricsByConversation, people, readPosition, sourceTask, teamDomainByTeamId] = await Promise.all([
8818
- readConversationAccessFromSql(getDb(), [conversationId], options.viewer),
9213
+ const purgedPage = { events: [] };
9214
+ const [annotations, automationTitleByConversation, auxiliaryCostsByConversation, briefVersion, firstHumanMessageTextByConversation, modelUsage, metricsByConversation, people, sourceTask, teamDomainByTeamId, page] = await Promise.all([
8819
9215
  listConversationAnnotations(getDb(), conversationId),
8820
9216
  readAutomationTitlesByConversationId([record.conversation]),
8821
9217
  readConversationAuxiliaryCostsFromSql(getDb(), [conversationId]),
@@ -8824,44 +9220,45 @@ async function readConversationDetailFromSql(conversationId, options) {
8824
9220
  record.conversation.transcriptPurgedAtMs === void 0 ? readConversationModelUsageFromSql(executor, { conversationId }) : Promise.resolve([]),
8825
9221
  readConversationTreeMetricsFromSql(getDb(), [conversationId]),
8826
9222
  readConversationAuthors(getDb(), conversationId),
8827
- options.viewer ? readConversationReadPosition(options.viewer, conversationId) : void 0,
8828
9223
  readConversationSourceTask({
8829
9224
  conversationId,
8830
9225
  ...options.viewer ? { viewer: options.viewer } : void 0
8831
9226
  }),
8832
- resolveSlackTeamDomains(record.conversation.location?.provider === "slack" ? [record.conversation.location.teamId] : [])
9227
+ resolveSlackTeamDomains(record.conversation.location?.provider === "slack" ? [record.conversation.location.teamId] : []),
9228
+ record.conversation.transcriptPurgedAtMs === void 0 ? readConversationEventPage(executor, {
9229
+ canExposePayload,
9230
+ conversationId,
9231
+ latestTurns: options.latestTurns,
9232
+ limit: options.limit
9233
+ }) : purgedPage
8833
9234
  ]);
8834
- const access = accessByConversation.get(conversationId);
8835
- const sidebarAnnotations = access?.canViewPrivateContent ? (await listConversationSidebarAnnotations([conversationId], /* @__PURE__ */ new Map([[conversationId, annotations]])))[conversationId] : void 0;
8836
- const canExposePayload = access?.canViewPrivateContent ?? false;
8837
- const page = record.conversation.transcriptPurgedAtMs === void 0 ? await readConversationEventPage(executor, {
8838
- canExposePayload,
8839
- conversationId,
8840
- limit: options.limit
8841
- }) : { events: [] };
8842
9235
  const firstSeq = page.events[0]?.seq;
8843
9236
  const unreadAfterSeq = readPosition !== void 0 && page.previousSeq !== void 0 && firstSeq !== void 0 && readPosition.lastReadSeq + 1 < firstSeq ? readPosition.lastReadSeq : void 0;
8844
- const brief = access?.canViewPrivateContent ? briefVersion?.content : void 0;
8845
- const [{ briefMentions, events }, unreadPage] = await Promise.all([attachConversationMentions(executor, conversationId, {
8846
- ...brief ? { brief } : void 0,
8847
- events: page.events
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]);
9237
+ const brief = canExposePayload ? briefVersion?.content : void 0;
9238
+ const [{ briefMentions, events }, unreadPage, sidebarAnnotations] = await Promise.all([
9239
+ attachConversationMentions(executor, conversationId, {
9240
+ ...brief ? { brief } : void 0,
9241
+ events: page.events
9242
+ }),
9243
+ options.unreadPage && unreadAfterSeq !== void 0 ? readConversationEventPageAround(executor, {
9244
+ canExposePayload,
9245
+ conversationId,
9246
+ limit: options.limit,
9247
+ seq: unreadAfterSeq
9248
+ }).then((around) => conversationEventPageReport(executor, {
9249
+ conversationId,
9250
+ eventHistory: conversationEventHistory({ canExposePayload }),
9251
+ page: around
9252
+ })).catch(() => void 0) : void 0,
9253
+ canExposePayload ? listConversationSidebarAnnotations([conversationId], /* @__PURE__ */ new Map([[conversationId, annotations]])).then((byConversation) => byConversation[conversationId]) : void 0
9254
+ ]);
8858
9255
  const metrics = metricsByConversation.get(conversationId);
8859
9256
  const auxiliaryCosts = auxiliaryCostsByConversation.get(conversationId);
8860
9257
  const childAgentTotals = childAgentTotalsReport(metrics, auxiliaryCosts);
8861
- return projectConversationDetail({
9258
+ const report = projectConversationDetail({
8862
9259
  ...record,
8863
9260
  access,
8864
- ...viewerMarks,
9261
+ ...state.viewerMarks,
8865
9262
  automationTitle: automationTitleByConversation.get(conversationId),
8866
9263
  annotations,
8867
9264
  sidebarAnnotations,
@@ -8887,25 +9284,83 @@ async function readConversationDetailFromSql(conversationId, options) {
8887
9284
  ...unreadPage ? { unreadPage } : void 0,
8888
9285
  usage: metrics?.usage ?? record.usage ?? void 0
8889
9286
  });
9287
+ return {
9288
+ ...report,
9289
+ ...state.forks,
9290
+ ...state.agentTree ? { agentTree: state.agentTree } : void 0,
9291
+ ...report.isParticipant && state.autoArchive !== void 0 ? { autoArchive: state.autoArchive } : void 0
9292
+ };
8890
9293
  }
8891
- /** Load one conversation from its canonical event history. */
9294
+ /** Turns in the default page: enough to read the latest exchange in context. */
9295
+ const DETAIL_LATEST_TURNS = 3;
9296
+ /**
9297
+ * Load one conversation from its canonical event history. Without `limit`,
9298
+ * events hold the latest Turns, up to the default limit.
9299
+ */
8892
9300
  async function readConversationDetail(conversationId, options = {}) {
8893
9301
  const report = await readConversationDetailFromSql(conversationId, {
8894
9302
  ...options,
8895
- limit: options.limit ?? 500
9303
+ ...options.limit === void 0 ? {
9304
+ latestTurns: DETAIL_LATEST_TURNS,
9305
+ limit: 150
9306
+ } : { limit: options.limit }
8896
9307
  });
8897
- if (!report) return void 0;
8898
- const [forks, agentTree, autoArchive] = await Promise.all([
8899
- readConversationForks(conversationId, options.viewer),
8900
- readConversationAgentTree(conversationId, options.viewer),
8901
- options.viewer && report.isParticipant ? readConversationAutoArchive(options.viewer, conversationId) : void 0
8902
- ]);
8903
- return conversationDetailReportSchema.parse({
8904
- ...report,
8905
- ...forks,
8906
- ...agentTree ? { agentTree } : void 0,
8907
- ...autoArchive === void 0 ? void 0 : { autoArchive }
9308
+ return report ? conversationDetailReportSchema.parse(report) : void 0;
9309
+ }
9310
+ // src/api/conversations/pin.ts
9311
+ /**
9312
+ * Pin or unpin one conversation for the signed-in viewer.
9313
+ *
9314
+ * A pin lives on the viewer's participant row, and that row grants send and
9315
+ * control access. So only a participant can pin, the same as archive. The
9316
+ * root actor may have no row yet, so pinning adds it. A pin also restores an
9317
+ * archived conversation, because the Pinned section shows only active
9318
+ * conversations.
9319
+ */
9320
+ async function pinConversation(viewer, conversationId, body) {
9321
+ if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(404, "Conversation not found.");
9322
+ const executor = getSqlExecutor();
9323
+ const rootConversationId = await resolveRootConversationId(executor, conversationId);
9324
+ const db = executor.db();
9325
+ if (!body.pinned) {
9326
+ await db.update(juniorConversationParticipants).set({ pinnedAt: null }).where(and(eq(juniorConversationParticipants.userId, viewer.id), eq(juniorConversationParticipants.rootConversationId, rootConversationId)));
9327
+ return { pinnedAt: null };
9328
+ }
9329
+ const [root] = await db.select({ lastActivityAt: juniorConversations.lastActivityAt }).from(juniorConversations).where(eq(juniorConversations.conversationId, rootConversationId)).limit(1);
9330
+ if (!root) throwApiError(404, "Conversation not found.");
9331
+ const pinnedAt = /* @__PURE__ */ new Date();
9332
+ await db.insert(juniorConversationParticipants).values({
9333
+ lastMessageAt: root.lastActivityAt,
9334
+ pinnedAt,
9335
+ rootConversationId,
9336
+ userId: viewer.id
9337
+ }).onConflictDoUpdate({
9338
+ target: [juniorConversationParticipants.userId, juniorConversationParticipants.rootConversationId],
9339
+ set: {
9340
+ archivedAt: null,
9341
+ pinnedAt
9342
+ }
8908
9343
  });
9344
+ return { pinnedAt: pinnedAt.toISOString() };
9345
+ }
9346
+ // src/api/conversations/steer-pending-messages.ts
9347
+ /**
9348
+ * Steer the viewer's own queued web messages into the conversation now.
9349
+ *
9350
+ * Only the author can steer a message. Ids that are not the viewer's queued
9351
+ * web messages, or that Junior already read, are left out of the result.
9352
+ */
9353
+ async function steerConversationPendingMessagesForViewer(viewer, conversationId, body) {
9354
+ if (!await getConversationStore().get({ conversationId })) throwApiError(404, "Conversation not found.");
9355
+ if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(403, "Only conversation participants can steer queued messages.");
9356
+ return {
9357
+ conversationId,
9358
+ steeredInboundMessageIds: (await steerWebPendingMessages({
9359
+ authorIds: webActorUserIds(viewer),
9360
+ conversationId,
9361
+ inboundMessageIds: body.inboundMessageIds
9362
+ })).steeredInboundMessageIds
9363
+ };
8909
9364
  }
8910
9365
  // src/api/conversations/stop.ts
8911
9366
  /**
@@ -8959,4 +9414,4 @@ function viewerWebMessages(messages, viewer) {
8959
9414
  }] : [];
8960
9415
  });
8961
9416
  }
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 };
9417
+ export { DEFAULT_AUTO_ARCHIVE_SETTINGS as $, assertNoLegacyAllowedDomains as A, normalizeIncomingSlackThreadId as B, requireConversationPendingMessages as C, createProductionSlackWebhookServices as D, createProductionConversationWorkOptions as E, recordSkippedConversationMessage as F, startProcessingReaction as G, stopConversationTurn as H, buildSlackInboundMessage as I, ReviewItemActionError as J, stripLeadingBotMention as K, clearSlackPendingReactions as L, isAllowedSignInEmail as M, readEnvList as N, getProductionSlackAdapter as O, resolveAllowedDomains as P, reviewItemChange as Q, isSlackMessageStopped as R, readConversationPendingMessages as S, archiveConversation as T, THREAD_OPTOUT_ACK as U, withNormalizedThreadId as V, bindMessageAuthorIdentityId as W, closeReviewItemsAnsweredByReply as X, actOnReviewItem as Y, readReviewItemForUser as Z, appendConversationMessageForViewer as _, readConversationDetailEtag as a, emptyResponse as at, encodeConversationCursor as b, keepQuickQuestionForViewer as c, getAttachmentStorage as ct, readConversationRecordFromSql as d, GET as dt, archiveViewerDoneConversations as et, readConversationAuxiliaryCostsFromSql as f, readHealthReport as ft, readFirstHumanMessageTexts as g, conversationSummaryFromStoredConversation as h, readConversationDetail as i, updateUserAutoArchiveSettings as it, isAllowedDomain as j, createSlackWebApiStatusSender as k, readConversationEvents as l, AGENT_DISPATCH_MAX_AGE_MS as lt, readConversationTreeMetricsFromSql as m, steerConversationPendingMessagesForViewer as n, runAutoArchiveSweep as nt, markConversationRead as o, jsonResponse as ot, childAgentTotalsReport as p, parseContent as q, pinConversation as r, setConversationAutoArchive as rt, forkConversationForViewer as s, throwApiError as st, stopConversationTurnForViewer as t, readUserAutoArchiveSettings as tt, readConversationFeed as u, enqueueAgentDispatch as ut, createConversationForViewer as v, resolveMentions as w, cancelConversationPendingMessagesForViewer as x, decodeConversationCursor as y, stopSlackThread as z };