@sentry/junior 0.277.0 → 0.279.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 (91) hide show
  1. package/dist/{adapter-BtfBHVM5.js → adapter-phTTgw7H.js} +1 -1
  2. package/dist/{admin-DzAKbZsm.js → admin-PcpJDugZ.js} +1 -1
  3. package/dist/{agent-invocations-Crs3XHhg.js → agent-invocations-CUg_SODU.js} +0 -1
  4. package/dist/{agent-runner-BsYAbniN.js → agent-runner-DwvT1BY0.js} +321 -847
  5. package/dist/api/schema.d.ts +2 -2
  6. package/dist/api/schema.js +6 -6
  7. package/dist/api.d.ts +1 -1
  8. package/dist/api.js +46 -414
  9. package/dist/{app-BjEQwNVP.d.ts → app-DVs6noo7.d.ts} +6 -27
  10. package/dist/app.d.ts +2 -2
  11. package/dist/app.js +460 -78
  12. package/dist/{assistant-reply-NebRGG4G.js → assistant-reply-BXfxczd7.js} +28 -6
  13. package/dist/{automation-Cql9h2vO.js → automation-BehArCcq.js} +1 -1
  14. package/dist/{background-compaction-queue-hh18yCeU.js → background-compaction-queue-CcbuLJrZ.js} +2 -2
  15. package/dist/{briefs-BBo0Eimi.js → briefs-Dd_ezwED.js} +10 -10
  16. package/dist/{catalog-runtime-DE-F4Awo.js → catalog-runtime-BWVMeZhW.js} +2 -2
  17. package/dist/cli/chat.js +16 -16
  18. package/dist/cli/check.js +3 -3
  19. package/dist/cli/init.js +0 -2
  20. package/dist/cli/main.js +4 -4
  21. package/dist/cli/plugins.js +5 -5
  22. package/dist/cli/snapshot-create.js +4 -4
  23. package/dist/cli/upgrade.d.ts +1 -1
  24. package/dist/cli/upgrade.js +4 -4
  25. package/dist/{client-DZ8HTnYH.js → client-Bpxe4vKa.js} +8 -4
  26. package/dist/{config-D5uUtrCP.js → config-C_bmRhrJ.js} +25 -100
  27. package/dist/{connections-Do24CGP5.js → connections-B2rHe5W5.js} +10 -10
  28. package/dist/{conversation-SsASlWL7.js → conversation-CIiJtx5q.js} +56 -104
  29. package/dist/conversation-pending-messages-CnBvE6-6.js +173 -0
  30. package/dist/{conversation-privacy-VuylvlKr.js → conversation-privacy-CzOfcz0U.js} +1 -1
  31. package/dist/{credential-sync-BGQK3pOa.js → credential-sync-Dal_unpv.js} +15 -15
  32. package/dist/{db-DEiwO5Sh.d.ts → db-CyLrV9C7.d.ts} +1 -1
  33. package/dist/{executor-hPfFTH0C.js → executor-BfYH-Wws.js} +6 -4
  34. package/dist/instrumentation.d.ts +12 -0
  35. package/dist/instrumentation.js +56 -23
  36. package/dist/{logging-cI3T1dNc.js → logging-CkT3_Xxp.js} +2 -2
  37. package/dist/{media-DstkkoNP.js → media-DTAA8Qs_.js} +21 -23
  38. package/dist/{message-DBwsAl7O.js → message-Q5dkgaJ5.js} +23 -29
  39. package/dist/nitro.d.ts +1 -1
  40. package/dist/nitro.js +18 -6
  41. package/dist/{oauth-callback-server-DXrnbplb.js → oauth-callback-server-BDRaqe8O.js} +2 -2
  42. package/dist/{oauth-relay-C6ZAyJgf.js → oauth-relay-D0G3T16m.js} +1 -1
  43. package/dist/{package-discovery-DJBompdd.js → package-discovery-DJhGdS4c.js} +1 -1
  44. package/dist/{plugins-DOm9Y6qI.js → plugins-HYh_JOdw.js} +1 -1
  45. package/dist/{projection-7EFIqzuj.js → projection-DWxX7pb1.js} +214 -138
  46. package/dist/{prompt-oRfGsxd3.js → prompt--dwus7Y-.js} +1 -1
  47. package/dist/proxy-path-BHYoKZdq.js +15 -0
  48. package/dist/{registry-Bzefs7kT.js → registry-DnrdeO4s.js} +2 -2
  49. package/dist/{resolve-CuiEY_2u.js → resolve-C_QXfqD_.js} +3 -3
  50. package/dist/{result-DrcUtFaD.js → result-DNmOxT-N.js} +10 -10
  51. package/dist/{runner-CDE4CZ52.js → runner-zd_noJ1l.js} +11 -11
  52. package/dist/{sandbox-egress-signals-0tcmGd13.js → sandbox-egress-signals-DQjv-nbG.js} +1 -1
  53. package/dist/{schema-Dzi3lkdP.js → schema-CNJNzvr8.js} +4 -4
  54. package/dist/{schema-B6N2nc6v.d.ts → schema-e90H5FIN.d.ts} +2176 -967
  55. package/dist/sentry-BRTJqumy.js +51 -0
  56. package/dist/sentry-DrKC2NeM.d.ts +1 -0
  57. package/dist/sentry-route-name-BhwWnfqj.js +51 -0
  58. package/dist/{service-account-BOz9pqOE.js → service-account-BK26XlHo.js} +3 -3
  59. package/dist/{service-account-DIyz_9Uh.js → service-account-CCH2Hv4h.js} +3 -3
  60. package/dist/{session-stop-0juF_BP0.js → session-stop-6Tf--T7G.js} +23 -16
  61. package/dist/{skills-CU5Is147.js → skills-BNrk8gi4.js} +4 -4
  62. package/dist/{spawn-6C9jHH4b.js → spawn-C75hAB9l.js} +3 -4
  63. package/dist/{stop-6FVG1c-r.js → stop-RYbf7PWi.js} +742 -207
  64. package/dist/{store-DtHZviJ1.js → store-CO5vGjwD.js} +9 -16
  65. package/dist/{store-DKs1WwdB.js → store-G3h2djJU.js} +3 -3
  66. package/dist/{task-queue-CcvFQE_p.js → task-queue-DlN58XeM.js} +3 -3
  67. package/dist/{task-runner-DBkNejLl.js → task-runner-B-Bdm23d.js} +22 -10
  68. package/dist/{thread-state-4hjEIkIq.js → thread-state-Cj_7Slru.js} +4 -4
  69. package/dist/{turn-failure-response-BZNLydC3.js → turn-failure-response-CE7gaoC7.js} +7 -7
  70. package/dist/{turn-lifecycle-BhqYjaa4.js → turn-lifecycle-7sXwXLJ6.js} +1 -1
  71. package/dist/{turn-session-routing-jnLOfBHJ.js → turn-session-routing-FBdaH1zf.js} +10 -10
  72. package/dist/{validation-BUFmsnKs.js → validation-DLWxEzWW.js} +2 -2
  73. package/dist/{version-DJTk0ZCE.js → version-DtQ8WFIZ.js} +1 -1
  74. package/dist/version.js +1 -1
  75. package/dist/{viewer-WY0RYE4E.js → viewer-vsM8_90o.js} +53 -22
  76. package/dist/{work-C5AKvXJV.js → work-DsoFRO_0.js} +12 -17
  77. package/dist/{worker-BcYVDVUy.js → worker-6kZEsCXs.js} +7 -7
  78. package/migrations/0077_drop_agent_invocation_model_profile.sql +1 -0
  79. package/migrations/0078_plugin_conversation_index.sql +20 -0
  80. package/migrations/0079_conversation_event_author_index.sql +20 -0
  81. package/migrations/meta/0075_snapshot.json +98 -314
  82. package/migrations/meta/0076_snapshot.json +98 -314
  83. package/migrations/meta/0077_snapshot.json +4141 -0
  84. package/migrations/meta/0078_snapshot.json +4175 -0
  85. package/migrations/meta/0079_snapshot.json +4203 -0
  86. package/migrations/meta/_journal.json +22 -1
  87. package/package.json +5 -5
  88. package/dist/common-Eu6sx09c.js +0 -107
  89. package/dist/model-profile-B998sjVd.js +0 -67
  90. package/dist/rolldown-runtime-nwUcYXjP.js +0 -27
  91. package/dist/sentry-MDkYAVPV.js +0 -23
@@ -1,37 +1,36 @@
1
- import { $ as loadTurnCheckpoint, $a as recordSlackAttachment, $n as listReplyActionItems, A as buildConversationContext, Ba as conversationPinnedForUser, Bn as getPlugins, Br as verifyTimerWatchCredentialSubject, Ci as normalizeSlackStatusText, D as fallbackShortTitle, Dn as createUserTokenStore, Ei as addReactionToMessage, F as markConversationMessage, Fa as conversationArchivedForUser, G as AuthorizationFlowDisabledError, Ga as readLatestConversationBrief, Gi as normalizeSlackConversationId, Ha as readConversationViewerMarks, Hi as getSlackClient, Ht as buildTurnErrorResponse, I as normalizeConversationText, Ia as conversationHasParticipantUser, Ka as readConversationEventPage, Kt as persistWithRetry, L as recordDeliveredAssistantMessage, La as conversationIsMemberRoot, M as estimateConversationContextTokens, Ma as createPluginLogger, N as getConversationMessageSlackTs, Na as readConversationAccessFromSql, Ni as removeReactionFromMessage, P as isHumanConversationMessage, Pa as conversationArchivedForEmail, Qa as readAttachmentVisionSummary, R as turnHasReply, Ra as conversationNotArchivedForEmail, Ri as SlackActionError, S as persistConversationMessages, T as resolveConversationTitle, Ti as truncateStatusText, Tn as isExperimentalFeatureEnabled, Ua as viewerConversationMembership, V as PluginCredentialFailureError, Va as conversationViewerMarks, Vi as getHeaderString, Vr as JUNIOR_THREAD_STATE_TTL_MS, Wi as isDmChannel, Xa as getSlackFileId, Y as clearPendingAuth, Ya as notInheritedByForkChild, Z as wasPendingAuthStopped, Zn as getReviewItem, _ as recordSubscribedReplyRoute, _n as getThreadStopDecision, ar as canActOnReviewItem, at as listTurnSummaries, cn as trimTrailingAssistantMessages, co as createPluginCache, cr as isOnlyAssignee, er as listWaitingConversations, et as saveTurnCheckpoint, fn as buildDeterministicAssistantMessageId, fo as piMessageFromHistoryItem, fr as reviewItemNeedsUser, gn as getSubscribedReplyPreflightDecision, hn as decideSubscribedThreadReply, i as loadConversationProjection, io as listConversationAnnotationsById, it as getTurnRecord, j as createConversationMemoryService, k as appendThreadContextMessages, kn as webActorUserIds, n as commitMessages, nr as takeReviewItem, nt as completeTurnRecord, o as loadProjection, ot as recordTurnSummary, p as recordAuthorizationCompleted, pn as buildDeterministicTurnId, pr as reviewItemReaderForUser, qa as buildSentryConversationUrl, qi as withSlackRetries, qn as closeReviewItem, ro as listConversationAnnotations, rt as failTurnRecord, s as loadTurnProjection, so as lookupSlackUser, sr as canReadReviewItem, t as commitAcceptedReply, tt as abandonTurnRecord, uo as configValueSchema, w as persistConversationMessageSummaries, wr as cancelSubscriptions, x as hydrateConversationMessages, z as upsertConversationMessage, za as conversationNotArchivedForUser, zi as downloadPrivateSlackFile } from "./projection-7EFIqzuj.js";
2
- import { a as completeText, b as isProviderRetryError, c as resolveGatewayModel, m as escapeXml, r as completeDecision } from "./client-DZ8HTnYH.js";
3
- import { _ as normalizeSlackEmojiName, c as getSlackClientSecret, i as getChatConfig, l as getSlackSigningSecret, n as botConfig, o as getSlackBotToken, s as getSlackClientId, v as createS3AttachmentStorage } from "./config-D5uUtrCP.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-cI3T1dNc.js";
5
- import { i as getActiveSpan, r as continueTrace } from "./sentry-MDkYAVPV.js";
6
- import { i as defaultModelId } from "./model-profile-B998sjVd.js";
1
+ import { i as getActiveSpan, r as continueTrace } from "./sentry-BRTJqumy.js";
2
+ import { $ as completeTurnRecord, $a as getSlackFileId, $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 readConversationEventPage, H as AuthorizationFlowDisabledError, Ha as viewerConversationMembership, Hi as normalizeSlackConversationId, I as upsertConversationMessage, Ia as conversationIsMemberRoot, Ii as downloadPrivateSlackFile, J as wasPendingAuthStopped, Jn as getReviewItem, K as clearPendingAuth, Ka as readConversationEventPageAfter, 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, Qa as notInheritedByForkChild, 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, Wa as readLatestConversationBrief, Wi as withSlackRetries, Wn as closeReviewItem, X as loadTurnCheckpoint, Xa as buildSentryConversationUrl, Xn as listReplyActionItems, Z as saveTurnCheckpoint, Zn as listWaitingConversations, a as loadProjection, an as trimTrailingAssistantMessages, ar as isOnlyAssignee, bi as normalizeSlackStatusText, d as recordAuthorizationCompleted, do as createPluginCache, et as failTurnRecord, fn as decideSubscribedThreadReply, h as recordSubscribedReplyRoute, ho as piMessageFromHistoryItem, i as loadConversationProjection, ir as canReadReviewItem, j as isHumanConversationMessage, k as estimateConversationContextTokens, ln as buildDeterministicAssistantMessageId, lr as reviewItemNeedsUser, mn as getThreadStopDecision, n as commitMessages, no as recordSlackAttachment, nr as canActOnReviewItem, nt as listTurnSummaries, o as loadTurnProjection, oo as listConversationAnnotations, pn as getSubscribedReplyPreflightDecision, po as configValueSchema, qa as readConversationEventPageAround, rt as recordTurnSummary, so as listConversationAnnotationsById, t as commitAcceptedReply, to as readAttachmentVisionSummary, tt as getTurnRecord, un as buildDeterministicTurnId, uo as lookupSlackUser, 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-DWxX7pb1.js";
3
+ import { a as completeText, c as resolveGatewayModel, m as escapeXml, r as completeDecision, x as isProviderRetryError } from "./client-Bpxe4vKa.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-C_bmRhrJ.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-CkT3_Xxp.js";
7
6
  import { f as parseSlackTeamId, h as parseSlackMessageTs, i as isActorUserId, n as createSlackActor, o as isUserActor, r as createSlackResumeActor, s as parseActorUserId, t as createActor, u as parseSlackChannelId } from "./actor-B4DYygOB.js";
8
- import { $ as createSlackDestination, A as locationFromRow, C as getSqlExecutor, D as loadConversationSlackTenantIds, E as withConversationEventLock, G as nextDetailVersion, N as resolveActorIdentityId, P as saveActorAvatar, Q as resolveRootConversationId, S as getDb, U as parseSessionSource, W as conversationDetailTouch, X as agentTurnUsageSchema, Z as hasAgentTurnUsage, f as identityAvatarUrl, h as readUserAvatarUrls, q as addAgentTurnUsage, tt as requireSlackDestination, x as getConversationStore, y as getConversationEventStore } from "./viewer-WY0RYE4E.js";
9
- import { c as juniorIdentities, d as juniorDestinations, l as juniorUsers, o as conversationReadColumns, s as juniorConversations } from "./agent-invocations-Crs3XHhg.js";
10
- import { C as juniorCodeChanges, _ as juniorConversationBriefs, b as juniorConversationEvents, c as juniorReviewItems, h as juniorConversationParticipants, m as juniorConversationReadPositions, o as juniorReviewItemConversations } from "./executor-hPfFTH0C.js";
11
- import { g as instructionProvenanceFor, m as contextProvenance, n as detectImageMediaType, r as isVisionImageMediaType } from "./media-DstkkoNP.js";
12
- import { d as actorLogContext, f as credentialContextForActor } from "./registry-Bzefs7kT.js";
13
- import { A as runWithSlackInstallation, At as withoutSavedSteeringMessages, Et as conversationSubtreeColumns, F as resolveSlackChannelIdFromThreadId, I as getConversationInfo, J as readConversationSourceTask, Lt as shouldEmitDevAgentTrace, M as parseSlackThreadId, N as readSlackRawMessageContext, Nt as RetryableDeliveryError, P as resolveSlackChannelIdFromMessage, R as listThreadReplies, Tt as conversationSubtree, a as buildAuthPauseResponse, b as renderAttachmentText, dt as recordWebConversationActivity, ft as webActorFromUser, i as measureTurnCompactionWait, kt as buildSteeringPiMessage, m as latestProgressStatus, n as executeAgentRun, pt as resolveConversationDestination, rt as deliverReviewItemChange, t as createAgentRunner, ut as createConversationId, vt as storeAttachment, x as renderBlockText, z as resolveDestinationVisibility } from "./agent-runner-BsYAbniN.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-vsM8_90o.js";
8
+ import { c as juniorIdentities, d as juniorDestinations, l as juniorUsers, o as conversationReadColumns, s as juniorConversations } from "./agent-invocations-CUg_SODU.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-BfYH-Wws.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-DnrdeO4s.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-DwvT1BY0.js";
14
13
  import { a as withLock, n as MUTATION_LOCK_TTL_MS, r as acquireActiveLock } from "./locks-D-0h111u.js";
15
- import { r as getStateAdapter } from "./adapter-BtfBHVM5.js";
16
- import { W as readMessageAttachments, l as conversationDetailReportSchema, m as conversationFeedSchema } from "./conversation-SsASlWL7.js";
17
- import { a as EVENT_SYSTEM_ACTOR, o as isEventConversationMessage } from "./prompt-oRfGsxd3.js";
18
- import { $ as markTurnFailed, G as TurnInputCommitLostError, J as isCooperativeTurnYieldError, K as TurnInputDeferredError, Q as markTurnCompleted, U as ConversationTurnBoundaryError, W as CooperativeTurnYieldError, X as isTurnInputDeferredError, Y as isTurnInputCommitLostError, Z as markTurnClosed, et as startActiveTurn, h as getChildAgentLabel, q as getConversationTurnBoundaryError } from "./store-DtHZviJ1.js";
19
- import { n as getAssistantReplyText } from "./assistant-reply-NebRGG4G.js";
20
- import { C as savedTurnInputMessages, E as maybePostAutomatedTurnLimitNotice, I as deliversFinalText, L as finishedRunReply, M as recordFinishedTurnForAutomatedLimit, O as resolveSlackReplyTarget, R as postsRunNotices, S as joinMailboxText, V as runDispatchOutcome, c as isEventMailboxMetadata, i as skipInputBeforeConversationStop, k as sendSlackReply, l as renderEventBatchText, s as eventBatchMessageMeta, u as timerWatchCredentialSubject, w as webConversationMessage } from "./session-stop-0juF_BP0.js";
21
- import { _ as isEmptyUserInputAnswer, v as normalizeUserInputAnswer } from "./reporting-window-DgHgwQB3.js";
22
- import { g as getTurnRequestDeadline, l as getVercelConversationWorkQueue } from "./background-compaction-queue-hh18yCeU.js";
23
- import { D as stopConversationWork, g as getConversationWorkState, h as getConversation, m as ensureConversationWake, r as appendAndEnqueueInboundMessage, w as requestConversationWork } from "./store-DKs1WwdB.js";
24
- import { _ as markDispatchCompleted, a as confirmDispatchMailboxAppend, d as getDispatchTurnId, g as markDispatchBlocked, h as markDispatchAwaitingResume, i as claimDispatchMailboxAppend, j as readAutomationTitlesByConversationId, l as getDispatchInputMessageId, n as resolveTurnSessionRouting, p as isTerminalDispatchStatus, s as getDispatchConversationId, t as resolveConversationRouting, u as getDispatchRecord, v as markDispatchFailed, y as markDispatchRunning } from "./turn-session-routing-jnLOfBHJ.js";
25
- import { n as healthReportSchema, t as apiErrorSchema } from "./common-Eu6sx09c.js";
26
- import { a as withAgentInvocationResultActors, c as listActiveMailboxTurns, d as turnInputFactsFromConversationMessage, f as legacyWebMailboxMetadataSchema, l as resolveMailboxTurnWork, n as enqueueAgentInvocationResult, o as getAuthPausedConversationTurnId, s as getEventBatchDelayMs, t as createChildConversationWorker, u as sourceFromTurnInput } from "./result-DrcUtFaD.js";
27
- import { n as getTurnLifecycle, t as ConversationTurnLifecycleService } from "./turn-lifecycle-BhqYjaa4.js";
28
- import { o as AgentRunError, s as executeTurn } from "./work-C5AKvXJV.js";
29
- import { a as persistThreadStateById, i as persistThreadRuntimeState, n as getPersistedSandboxState, o as coerceThreadConversationState, r as getPersistedThreadState, t as getLocationConfigurationService } from "./thread-state-4hjEIkIq.js";
30
- import { c as deleteWebAuthorization, d as createPausedTurns, f as getPausedTurnRequest, h as getTurnAuthorization, m as wakePausedTurn, s as createWebAuthorization } from "./connections-Do24CGP5.js";
31
- import { t as bindMessageAgent } from "./message-DBwsAl7O.js";
32
- import { t as bindSpawnAgent } from "./spawn-6C9jHH4b.js";
33
- import { n as scheduleSessionCompletedPluginTasks, t as processPluginTask } from "./task-runner-DBkNejLl.js";
34
- import { a as persistAuthPauseTurnState, c as getTurnUserSlackMessageTs, i as completeAuthPauseTurn, l as buildDeliveredTurnStatePatch, n as getAgentTurnDiagnosticsAttributes, o as getTurnUserMessage, r as requireTurnFailureEventId, s as getTurnUserReplyAttachmentContext, t as finalizeFailedTurnReplyWithEvent, u as loadPendingMessageCards } from "./turn-failure-response-BZNLydC3.js";
14
+ import { r as getStateAdapter } from "./adapter-phTTgw7H.js";
15
+ import { R as readMessageAttachments, c as conversationDetailReportSchema, p as conversationFeedSchema, u as conversationEventPageSchema } from "./conversation-CIiJtx5q.js";
16
+ import { a as EVENT_SYSTEM_ACTOR, o as isEventConversationMessage } from "./prompt--dwus7Y-.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-CO5vGjwD.js";
18
+ import { n as getAssistantReplyText, t as decideReply } from "./assistant-reply-BXfxczd7.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-6Tf--T7G.js";
20
+ import { _ as isEmptyUserInputAnswer, b as webMessageId, v as normalizeUserInputAnswer } from "./reporting-window-DgHgwQB3.js";
21
+ import { g as getTurnRequestDeadline, l as getVercelConversationWorkQueue } from "./background-compaction-queue-CcbuLJrZ.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-G3h2djJU.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-FBdaH1zf.js";
24
+ import { d as healthReportSchema, s as conversationPendingMessagesReportSchema, u as apiErrorSchema } from "./conversation-pending-messages-CnBvE6-6.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-DNmOxT-N.js";
26
+ import { n as getTurnLifecycle, t as ConversationTurnLifecycleService } from "./turn-lifecycle-7sXwXLJ6.js";
27
+ import { o as AgentRunError, s as executeTurn } from "./work-DsoFRO_0.js";
28
+ import { a as persistThreadStateById, i as persistThreadRuntimeState, n as getPersistedSandboxState, o as coerceThreadConversationState, r as getPersistedThreadState, t as getLocationConfigurationService } from "./thread-state-Cj_7Slru.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-B2rHe5W5.js";
30
+ import { t as bindMessageAgent } from "./message-Q5dkgaJ5.js";
31
+ import { t as bindSpawnAgent } from "./spawn-C75hAB9l.js";
32
+ import { n as scheduleSessionCompletedPluginTasks, t as processPluginTask } from "./task-runner-B-Bdm23d.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-CE7gaoC7.js";
35
34
  import { createHash, createHmac, timingSafeEqual } from "node:crypto";
36
35
  import { z } from "zod";
37
36
  import { and, asc, desc, eq, gt, inArray, isNotNull, isNull, lte, max, ne, or, sql } from "drizzle-orm";
@@ -2775,17 +2774,13 @@ function countPotentialImageAttachments(attachments) {
2775
2774
  function isVisionEnabled() {
2776
2775
  return Boolean(botConfig.visionModelId);
2777
2776
  }
2778
- /**
2779
- * Report whether every profile model accepts image input. The router picks the
2780
- * profile after attachments resolve, so native images need every profile to
2781
- * read them.
2782
- */
2783
- function profileModelsAcceptImages() {
2784
- return Object.values(botConfig.profiles).every((profile) => resolveGatewayModel(profile.modelId).input.includes("image"));
2777
+ /** Report whether the main agent model accepts image input. */
2778
+ function agentModelAcceptsImages() {
2779
+ return resolveGatewayModel(botConfig.modelId).input.includes("image");
2785
2780
  }
2786
2781
  /** Report whether the agent can read current-message images by any path. */
2787
2782
  function canReadImages() {
2788
- return isVisionEnabled() || profileModelsAcceptImages();
2783
+ return isVisionEnabled() || agentModelAcceptsImages();
2789
2784
  }
2790
2785
  var ImageAttachmentProcessingError = class extends Error {
2791
2786
  constructor(message) {
@@ -2954,7 +2949,7 @@ async function resolveUserAttachmentsWithDeps(attachments, context, deps) {
2954
2949
  }
2955
2950
  continue;
2956
2951
  }
2957
- const nativeImageMediaType = isImageAttachment && profileModelsAcceptImages() ? detectImageMediaType(data) : void 0;
2952
+ const nativeImageMediaType = isImageAttachment && agentModelAcceptsImages() ? detectImageMediaType(data) : void 0;
2958
2953
  if (nativeImageMediaType) {
2959
2954
  nextCachedImageSummaryIndex += 1;
2960
2955
  resolvedAttachment.mediaType = nativeImageMediaType;
@@ -3779,10 +3774,14 @@ function resolveSlackConversationContext(input) {
3779
3774
  const type = typeFromSlackChannelType(input.channelType) ?? typeFromChannelId(input.channelId, input.channelName);
3780
3775
  if (!type) return void 0;
3781
3776
  const name = normalizeConversationName(type, input.channelName);
3777
+ const topic = input.channelTopic?.trim();
3778
+ const description = input.channelDescription?.trim();
3782
3779
  const visibility = conversationVisibilityFromSlackChannelType(input.channelType);
3783
3780
  return {
3784
3781
  type,
3785
3782
  ...name ? { name } : void 0,
3783
+ ...topic ? { topic } : void 0,
3784
+ ...description ? { description } : void 0,
3786
3785
  ...visibility ? { visibility } : void 0,
3787
3786
  ...input.botUserId ? { botUserId: input.botUserId } : void 0
3788
3787
  };
@@ -3892,33 +3891,30 @@ function inboundMessageProvenance(queued, teamId) {
3892
3891
  });
3893
3892
  return instructionProvenanceFor(author);
3894
3893
  }
3895
- /** Return the Slack channel name when it is available. */
3896
- async function resolveChannelName(thread) {
3897
- const existingName = thread.channel.name?.trim();
3898
- if (existingName) return existingName;
3899
- try {
3900
- return (await thread.channel.fetchMetadata()).name?.trim() || void 0;
3901
- } catch {
3902
- return;
3903
- }
3904
- }
3905
3894
  /**
3906
- * 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.
3907
3897
  *
3908
3898
  * Slack delivers a channel mention as two events with the same `ts`: `message`
3909
3899
  * has `channel_type`, and `app_mention` does not. Junior stores the event that
3910
- * arrives first. When that event has no `channel_type`, ask Slack for the
3911
- * 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.
3912
3903
  */
3913
- async function resolveSlackChannelType(message, channelId) {
3904
+ async function resolveSlackChannelFacts(message, channelId) {
3914
3905
  const eventChannelType = resolveSlackChannelTypeFromMessage(message);
3915
- if (eventChannelType) return eventChannelType;
3916
3906
  const slackChannelId = parseSlackChannelId(channelId);
3917
- if (!slackChannelId) return;
3907
+ if (!slackChannelId) return { channelType: eventChannelType };
3918
3908
  try {
3919
- 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
+ };
3920
3916
  } catch (error) {
3921
- if (error instanceof SlackActionError) return;
3917
+ if (error instanceof SlackActionError) return { channelType: eventChannelType };
3922
3918
  throw error;
3923
3919
  }
3924
3920
  }
@@ -3987,13 +3983,16 @@ function createSlackTurn(deps) {
3987
3983
  if (message.author.isMe) return;
3988
3984
  const threadId = getThreadId(thread, message);
3989
3985
  const channelId = getChannelId(thread, message);
3990
- 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;
3991
3989
  const destination = requireSlackDestination(options.destination, "Slack reply execution");
3992
- const slackChannelType = options.execution ? resolveSlackChannelTypeFromMessage(message) : await resolveSlackChannelType(message, channelId);
3993
3990
  const slackConversation = resolveSlackConversationContext({
3994
3991
  botUserId: deps.getSlackAdapter().botUserId,
3995
3992
  channelId,
3996
3993
  channelName,
3994
+ channelTopic: channelFacts.topic,
3995
+ channelDescription: channelFacts.description,
3997
3996
  channelType: slackChannelType
3998
3997
  });
3999
3998
  const destinationVisibility = conversationVisibilityFromSlackChannelType(slackChannelType);
@@ -4026,7 +4025,7 @@ function createSlackTurn(deps) {
4026
4025
  destinationName: channelId,
4027
4026
  runId,
4028
4027
  assistantUserName: botConfig.userName,
4029
- modelId: defaultModelId(botConfig)
4028
+ modelId: botConfig.modelId
4030
4029
  }, async () => {
4031
4030
  await getConversationStore().recordActivity({
4032
4031
  activityAtMs: message.metadata.dateSent.getTime(),
@@ -5158,7 +5157,7 @@ function createSlackRuntime(options) {
5158
5157
  assistantUserName: botConfig.userName,
5159
5158
  cancelWatches: cancelSubscriptions,
5160
5159
  getBotUserId: () => options.getSlackAdapter().botUserId,
5161
- modelId: defaultModelId(botConfig),
5160
+ modelId: botConfig.modelId,
5162
5161
  now: options.now ?? (() => Date.now()),
5163
5162
  prepareTurnState,
5164
5163
  persistPreparedState: async ({ conversationId, preparedState }) => {
@@ -5304,7 +5303,7 @@ function getResumeLogContext(args) {
5304
5303
  ...actorLogContext(args.run?.actor, args.run?.credentialContext),
5305
5304
  destinationName: args.channelId,
5306
5305
  assistantUserName: botConfig.userName,
5307
- modelId: defaultModelId(botConfig)
5306
+ modelId: botConfig.modelId
5308
5307
  };
5309
5308
  }
5310
5309
  async function handleResumeFailure(args) {
@@ -6335,6 +6334,7 @@ async function commitAssistantMessage(args) {
6335
6334
  const conversationMessageId = recordDeliveredAssistantMessage({
6336
6335
  cards: args.cards,
6337
6336
  conversation: args.conversation,
6337
+ ...args.quiet ? { quiet: args.quiet } : void 0,
6338
6338
  sessionId: args.sessionId,
6339
6339
  source: args.source,
6340
6340
  text: args.text,
@@ -6550,7 +6550,8 @@ function createConversationTurnWorker(agentRunner, deliverMessage) {
6550
6550
  });
6551
6551
  const webActor = actor.platform === "web" ? actor : void 0;
6552
6552
  const conversationLocation = storedConversation?.location;
6553
- const deliverToProvider = Boolean(conversationLocation) && (source.kind === "event" || savedMessageIsEvent);
6553
+ const isEventTurn = source.kind === "event" || savedMessageIsEvent;
6554
+ const deliverToProvider = Boolean(conversationLocation) && isEventTurn;
6554
6555
  const surface = deliverToProvider ? "slack" : "api";
6555
6556
  return await withLogContext({
6556
6557
  conversationId: context.conversationId,
@@ -6638,12 +6639,14 @@ function createConversationTurnWorker(agentRunner, deliverMessage) {
6638
6639
  let completedSuccessfully = false;
6639
6640
  const deliverAssistantMessage = async (value) => {
6640
6641
  const agentMessage = typeof value === "string" ? void 0 : value;
6641
- const replyText = typeof value === "string" ? value : getAssistantReplyText(value);
6642
+ const decision = agentMessage ? decideReply(agentMessage) : void 0;
6643
+ const replyText = typeof value === "string" ? value : decision?.kind === "deliver" ? decision.text : void 0;
6642
6644
  if (!replyText?.trim()) return;
6643
6645
  failureCode = "delivery_failed";
6644
6646
  const cards = await loadPendingMessageCards(context.conversationId);
6647
+ const quiet = decision?.kind === "deliver" && decision.quiet === true && isEventTurn && cards.length === 0;
6645
6648
  let deliveryResult;
6646
- if (deliverToProvider) {
6649
+ if (deliverToProvider && !quiet) {
6647
6650
  if (!conversationLocation || !deliverMessage) throw new Error(`Conversation ${context.conversationId} cannot deliver to its Location`);
6648
6651
  deliveryResult = await deliverMessage({
6649
6652
  cards,
@@ -6658,6 +6661,7 @@ function createConversationTurnWorker(agentRunner, deliverMessage) {
6658
6661
  conversation,
6659
6662
  conversationId: context.conversationId,
6660
6663
  ...deliveryResult ? { deliveryResult } : void 0,
6664
+ ...quiet ? { quiet } : void 0,
6661
6665
  sessionId: turnId,
6662
6666
  ...deliveryResult ? { source: "slack" } : source.kind === "web" ? { source: "web" } : void 0,
6663
6667
  text: replyText,
@@ -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) {
@@ -7501,6 +7897,26 @@ function messageTotalTokens(args) {
7501
7897
  function definedNumber(value) {
7502
7898
  return value === null ? void 0 : value;
7503
7899
  }
7900
+ const modelUsageSumsSchema = z.object({
7901
+ inputTokens: z.number().nullable(),
7902
+ outputTokens: z.number().nullable(),
7903
+ cachedInputTokens: z.number().nullable(),
7904
+ cacheCreationTokens: z.number().nullable(),
7905
+ reasoningTokens: z.number().nullable(),
7906
+ totalTokens: z.number().nullable(),
7907
+ costInput: z.number().nullable(),
7908
+ costOutput: z.number().nullable(),
7909
+ costCacheRead: z.number().nullable(),
7910
+ costCacheWrite: z.number().nullable(),
7911
+ costTotal: z.number().nullable()
7912
+ });
7913
+ const COST_FIELDS = /* @__PURE__ */ new Set([
7914
+ "costInput",
7915
+ "costOutput",
7916
+ "costCacheRead",
7917
+ "costCacheWrite",
7918
+ "costTotal"
7919
+ ]);
7504
7920
  function usageFromRow(row) {
7505
7921
  const components = {
7506
7922
  inputTokens: definedNumber(row.inputTokens),
@@ -7524,12 +7940,8 @@ function usageFromRow(row) {
7524
7940
  };
7525
7941
  return hasAgentTurnUsage(result) ? agentTurnUsageSchema.parse(result) : void 0;
7526
7942
  }
7527
- /**
7528
- * Aggregate real assistant calls by provider/model in SQL, for one
7529
- * Conversation and all its child agents at any depth. Replayed history is not
7530
- * another call; its tokens appear in the next call's input usage.
7531
- */
7532
- async function readConversationModelUsageFromSql(executor, options) {
7943
+ /** Sum assistant calls by model id, in the given seq range of each Conversation. */
7944
+ async function sumModelUsage(executor, ranges) {
7533
7945
  const modelText = sql`(${model} #>> '{}')`;
7534
7946
  const modelId = sql`case
7535
7947
  when position('/' in coalesce(${modelText}, '')) > 0
@@ -7540,7 +7952,8 @@ async function readConversationModelUsageFromSql(executor, options) {
7540
7952
  const outputTokens = token("output", "outputTokens");
7541
7953
  const cachedInputTokens = token("cacheRead", "cachedInputTokens");
7542
7954
  const cacheCreationTokens = token("cacheWrite", "cacheCreationTokens");
7543
- return (await executor.db().select({
7955
+ const rangeRows = sql.join(ranges.map((range) => sql`(${range.conversationId}::text, ${range.fromSeq}::integer, ${range.toSeq}::integer)`), sql`, `);
7956
+ return await executor.db().select({
7544
7957
  modelId,
7545
7958
  inputTokens: summed(inputTokens),
7546
7959
  outputTokens: summed(outputTokens),
@@ -7558,52 +7971,117 @@ async function readConversationModelUsageFromSql(executor, options) {
7558
7971
  costCacheRead: summedCost(nonnegativeNumber(cost, "cacheRead")),
7559
7972
  costCacheWrite: summedCost(nonnegativeNumber(cost, "cacheWrite")),
7560
7973
  costTotal: summedCost(nonnegativeNumber(cost, "total"))
7561
- }).from(juniorConversationEvents).innerJoin(conversationSubtree([options.conversationId]), eq(conversationSubtreeColumns.conversationId, juniorConversationEvents.conversationId)).crossJoinLateral(assistantCall).where(and(eq(juniorConversationEvents.type, "assistant_message"), notCopiedByFork(), notInheritedByForkChild(), sql`jsonb_typeof(${provider}) = 'string'`, sql`jsonb_typeof(${model}) = 'string'`, sql`coalesce(${provider} #>> '{}', '') <> ''`, sql`coalesce(${modelText}, '') <> ''`)).groupBy(modelId).orderBy(modelId)).flatMap((row) => {
7562
- const modelUsage = usageFromRow(row);
7563
- return modelUsage ? [{
7564
- modelId: row.modelId,
7565
- usage: modelUsage
7566
- }] : [];
7567
- });
7974
+ }).from(juniorConversationEvents).innerJoin(sql`(values ${rangeRows}) as seq_range(conversation_id, from_seq, to_seq)`, sql`seq_range.conversation_id = ${juniorConversationEvents.conversationId}
7975
+ and ${juniorConversationEvents.seq} > seq_range.from_seq
7976
+ and ${juniorConversationEvents.seq} <= seq_range.to_seq`).crossJoinLateral(assistantCall).where(and(eq(juniorConversationEvents.type, "assistant_message"), notCopiedByFork(), notInheritedByForkChild(), sql`jsonb_typeof(${provider}) = 'string'`, sql`jsonb_typeof(${model}) = 'string'`, sql`coalesce(${provider} #>> '{}', '') <> ''`, sql`coalesce(${modelText}, '') <> ''`)).groupBy(modelId);
7568
7977
  }
7569
- // src/api/conversations/cursor.ts
7570
- const CURSOR_CONTEXT = "junior-conversation-report-cursor";
7571
- const conversationCursorPayloadSchema = z.object({
7572
- conversationId: z.string().min(1),
7573
- seq: z.number().int().min(-1),
7574
- version: z.literal(1)
7575
- }).strict();
7576
- function cursorSecret() {
7577
- const secret = process.env.JUNIOR_SECRET?.trim();
7578
- if (!secret) throw new Error("Cannot sign conversation cursor without JUNIOR_SECRET");
7579
- return secret;
7978
+ /**
7979
+ * The last event seq of each Conversation in a subtree, and the creation time
7980
+ * of its first event. A purged Conversation can get new events under the same
7981
+ * id, with seq starting again at 0; the first event time tells them apart.
7982
+ */
7983
+ async function readEventWatermarks(executor, conversationId) {
7984
+ const conversation = juniorConversations.conversationId;
7985
+ return await executor.db().select({
7986
+ conversationId: conversation,
7987
+ seq: sql`(
7988
+ select max(watermark.seq) from junior_conversation_events watermark
7989
+ where watermark.conversation_id = ${conversation}
7990
+ )`,
7991
+ originMs: sql`(
7992
+ select (extract(epoch from origin.created_at) * 1000)::double precision
7993
+ from junior_conversation_events origin
7994
+ where origin.conversation_id = ${conversation}
7995
+ order by origin.seq
7996
+ limit 1
7997
+ )`
7998
+ }).from(juniorConversations).innerJoin(conversationSubtree([conversationId]), eq(conversationSubtreeColumns.conversationId, conversation));
7999
+ }
8000
+ const modelUsageCacheSchema = z.object({
8001
+ conversations: z.record(z.string(), z.object({
8002
+ seq: z.number().int(),
8003
+ originMs: z.number()
8004
+ })),
8005
+ models: z.record(z.string(), modelUsageSumsSchema)
8006
+ });
8007
+ const EMPTY_MODEL_USAGE_CACHE = {
8008
+ conversations: {},
8009
+ models: {}
8010
+ };
8011
+ const MODEL_USAGE_CACHE_TTL_MS = 2592e6;
8012
+ function modelUsageCacheKey(conversationId) {
8013
+ return `conversation-model-usage:${conversationId}`;
7580
8014
  }
7581
- /** Sign one encoded cursor with the domain-separated server secret. */
7582
- function signature(payload) {
7583
- return createHmac("sha256", cursorSecret()).update(`${CURSOR_CONTEXT}:${payload}`).digest("base64url");
8015
+ function addSums(field, left, right) {
8016
+ if (left === null) return right;
8017
+ if (right === null) return left;
8018
+ return COST_FIELDS.has(field) ? Number((left + right).toFixed(12)) : left + right;
7584
8019
  }
7585
- /** Encode an authenticated, conversation-bound event position for an API cursor. */
7586
- function encodeConversationCursor(payload) {
7587
- const encoded = Buffer.from(JSON.stringify({
7588
- ...payload,
7589
- version: 1
7590
- }), "utf8").toString("base64url");
7591
- return `${encoded}.${signature(encoded)}`;
8020
+ function mergeSums(left, right) {
8021
+ if (!left) return right;
8022
+ const merged = { ...right };
8023
+ for (const field of modelUsageSumsSchema.keyof().options) merged[field] = addSums(field, left[field], right[field]);
8024
+ return merged;
7592
8025
  }
7593
- /** Decode an authenticated reporting cursor for the expected conversation. */
7594
- function decodeConversationCursor(args) {
7595
- const [encoded, actualSignature, extra] = args.cursor.split(".");
7596
- if (!encoded || !actualSignature || extra !== void 0) return void 0;
7597
- const expected = Buffer.from(signature(encoded));
7598
- const actual = Buffer.from(actualSignature);
7599
- if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) return;
7600
- try {
7601
- const parsed = conversationCursorPayloadSchema.parse(JSON.parse(Buffer.from(encoded, "base64url").toString("utf8")));
7602
- if (parsed.conversationId !== args.conversationId) return;
7603
- return { seq: parsed.seq };
7604
- } catch {
7605
- return;
8026
+ /**
8027
+ * Aggregate real assistant calls by provider/model in SQL, for one
8028
+ * Conversation and all its child agents at any depth. Replayed history is not
8029
+ * another call; its tokens appear in the next call's input usage.
8030
+ *
8031
+ * Reading assistant payloads is slow on long Conversations, so the sums are
8032
+ * cached with the last seq that each Conversation in the subtree added. A read
8033
+ * sums only later events. This is correct because a row at or below a seen
8034
+ * seq never changes and never changes whether it counts:
8035
+ * - Events are append-only. The per-Conversation event lock serializes
8036
+ * appends and is held to commit, so when seq N is visible, lower seqs are.
8037
+ * - `notInheritedByForkChild` reads only lower seqs of the same Conversation.
8038
+ * - `notCopiedByFork` reads a later fork note, but a fork commits its copied
8039
+ * events and the note in one transaction.
8040
+ * Concurrent reads can overwrite each other's entry. Each entry is correct
8041
+ * at its own seqs, so the last write wins safely.
8042
+ */
8043
+ async function readConversationModelUsageFromSql(executor, options) {
8044
+ const state = getStateAdapter();
8045
+ const key = modelUsageCacheKey(options.conversationId);
8046
+ const [stored, watermarks] = await Promise.all([state.get(key), readEventWatermarks(executor, options.conversationId)]);
8047
+ const cached = modelUsageCacheSchema.safeParse(stored).data;
8048
+ const purged = watermarks.some(({ conversationId, seq, originMs }) => {
8049
+ const seen = cached?.conversations[conversationId];
8050
+ return seen && (seq === null || seq < seen.seq || originMs !== seen.originMs);
8051
+ });
8052
+ const base = cached && !purged ? cached : EMPTY_MODEL_USAGE_CACHE;
8053
+ const ranges = [];
8054
+ const conversations = {};
8055
+ for (const { conversationId, seq, originMs } of watermarks) {
8056
+ if (seq === null || originMs === null) continue;
8057
+ conversations[conversationId] = {
8058
+ seq,
8059
+ originMs
8060
+ };
8061
+ const fromSeq = base.conversations[conversationId]?.seq ?? -1;
8062
+ if (seq > fromSeq) ranges.push({
8063
+ conversationId,
8064
+ fromSeq,
8065
+ toSeq: seq
8066
+ });
8067
+ }
8068
+ let models = base.models;
8069
+ if (ranges.length > 0 || base !== cached) {
8070
+ const deltas = ranges.length > 0 ? await sumModelUsage(executor, ranges) : [];
8071
+ models = { ...base.models };
8072
+ for (const { modelId, ...sums } of deltas) models[modelId] = mergeSums(models[modelId], sums);
8073
+ await state.set(key, {
8074
+ conversations,
8075
+ models
8076
+ }, MODEL_USAGE_CACHE_TTL_MS);
7606
8077
  }
8078
+ return Object.entries(models).sort(([left], [right]) => left < right ? -1 : 1).flatMap(([modelId, sums]) => {
8079
+ const modelUsage = usageFromRow(sums);
8080
+ return modelUsage ? [{
8081
+ modelId,
8082
+ usage: modelUsage
8083
+ }] : [];
8084
+ });
7607
8085
  }
7608
8086
  // src/api/conversations/first-message.ts
7609
8087
  /**
@@ -7620,81 +8098,6 @@ async function readFirstHumanMessageTexts(db, conversations) {
7620
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));
7621
8099
  return new Map(rows.map((row) => [row.conversationId, row.text]));
7622
8100
  }
7623
- // src/api/mentions.ts
7624
- const SLACK_USER_MENTION_RE = /<@([UW][A-Z0-9]+)(?:\|[^<>]*)?>/g;
7625
- function mentionedSlackUserIds(texts) {
7626
- const ids = texts.flatMap((text) => text ? [...text.matchAll(SLACK_USER_MENTION_RE)].map((m) => m[1]) : []);
7627
- return [...new Set(ids)];
7628
- }
7629
- /**
7630
- * Resolve the people that each source mentions, in source order. Every API
7631
- * that returns display text uses this, so the dashboard can show the same
7632
- * names and People links everywhere. It does one identity query per Slack
7633
- * workspace.
7634
- */
7635
- async function resolveMentions(executor, sources) {
7636
- const idsBySource = sources.map((source) => mentionedSlackUserIds(source.texts));
7637
- const idsByTenant = /* @__PURE__ */ new Map();
7638
- sources.forEach((source, index) => {
7639
- if (idsBySource[index].length === 0) return;
7640
- const ids = idsByTenant.get(source.tenantId) ?? /* @__PURE__ */ new Set();
7641
- for (const id of idsBySource[index]) ids.add(id);
7642
- idsByTenant.set(source.tenantId, ids);
7643
- });
7644
- const peopleByTenant = new Map(await Promise.all([...idsByTenant].map(async ([tenantId, ids]) => [tenantId, await readMentionedPeople(executor, tenantId, [...ids])])));
7645
- return sources.map((source, index) => {
7646
- const people = peopleByTenant.get(source.tenantId);
7647
- return idsBySource[index].flatMap((id) => {
7648
- const person = people?.get(id);
7649
- return person ? [person] : [];
7650
- });
7651
- });
7652
- }
7653
- /**
7654
- * Read current names for mentioned Slack users. Known Junior identities come
7655
- * first. The email is set only for a linked, verified Junior user, because
7656
- * that email is the People profile route.
7657
- */
7658
- async function readMentionedPeople(executor, tenantId, userIds) {
7659
- const rows = await executor.db().select({
7660
- displayName: juniorIdentities.displayName,
7661
- emailVerified: juniorIdentities.emailVerified,
7662
- handle: juniorIdentities.handle,
7663
- providerSubjectId: juniorIdentities.providerSubjectId,
7664
- userDisplayName: juniorUsers.displayName,
7665
- userEmail: juniorUsers.primaryEmail
7666
- }).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));
7667
- const people = /* @__PURE__ */ new Map();
7668
- for (const row of rows) {
7669
- if (people.has(row.providerSubjectId)) continue;
7670
- const fullName = row.userDisplayName?.trim() || row.displayName?.trim();
7671
- const email = row.emailVerified ? row.userEmail?.trim() : void 0;
7672
- people.set(row.providerSubjectId, {
7673
- slackUserId: row.providerSubjectId,
7674
- ...fullName ? { fullName } : void 0,
7675
- ...row.handle ? { slackUserName: row.handle } : void 0,
7676
- ...email ? { email } : void 0
7677
- });
7678
- }
7679
- const unnamed = userIds.filter((id) => {
7680
- const person = people.get(id);
7681
- return !person?.fullName && !person?.slackUserName;
7682
- });
7683
- if (tenantId && unnamed.length > 0) {
7684
- const profiles = await Promise.all(unnamed.map((id) => lookupSlackUser(tenantId, id)));
7685
- unnamed.forEach((id, index) => {
7686
- const profile = profiles[index];
7687
- if (!profile?.fullName && !profile?.userName) return;
7688
- people.set(id, {
7689
- ...people.get(id),
7690
- slackUserId: id,
7691
- ...profile.fullName ? { fullName: profile.fullName } : void 0,
7692
- ...profile.userName ? { slackUserName: profile.userName } : void 0
7693
- });
7694
- });
7695
- }
7696
- return people;
7697
- }
7698
8101
  // src/api/conversations/mentions.ts
7699
8102
  /** Text in one event that the dashboard renders with mentions. */
7700
8103
  function eventMentionTexts(data) {
@@ -7705,8 +8108,7 @@ function eventMentionTexts(data) {
7705
8108
  ...(data.events ?? []).map((event) => event.trustedSummary)
7706
8109
  ];
7707
8110
  case "assistant_message": return data.parts.map((part) => part.text);
7708
- case "compaction":
7709
- case "handoff": return [data.summary];
8111
+ case "compaction": return [data.summary];
7710
8112
  case "structured_event": return [data.presentation.preview, ...(data.presentation.details ?? []).map((detail) => detail.description)];
7711
8113
  default: return [];
7712
8114
  }
@@ -8157,14 +8559,19 @@ function participantKey(row) {
8157
8559
  return row.userId ? `user:${row.userId}` : `identity:${row.identityId}`;
8158
8560
  }
8159
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");
8160
8567
  const [rootRows, eventRows] = await Promise.all([db.select({
8161
8568
  conversationId: juniorConversations.conversationId,
8162
8569
  ...identityColumns
8163
- }).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], {
8164
- conversationId: juniorConversationEvents.conversationId,
8165
- 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,
8166
8573
  ...identityColumns
8167
- }).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]))]);
8168
8575
  return [...rootRows, ...eventRows.sort((left, right) => left.seq - right.seq)];
8169
8576
  }
8170
8577
  async function groupParticipants(db, rows) {
@@ -8372,7 +8779,7 @@ async function readConversationFeedFromSql(options = {}) {
8372
8779
  if (filter?.kind === "viewer" && status === "active") rows.push(...await waitingRowsOutsidePage(db, filter, rows));
8373
8780
  const conversations = rows.map((row) => conversationFromRow(row));
8374
8781
  const conversationIds = conversations.map((conversation) => conversation.conversationId);
8375
- 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([
8376
8783
  readConversationAccessFromSql(db, conversationIds, options.viewer),
8377
8784
  conversationViewerMarks(db, conversationIds, filter?.kind === "viewer" ? { userId: filter.userId } : filter?.kind === "actorEmail" ? { email: filter.email } : void 0),
8378
8785
  listConversationAnnotationsById(db, conversationIds),
@@ -8380,8 +8787,10 @@ async function readConversationFeedFromSql(options = {}) {
8380
8787
  readConversationTreeMetricsFromSql(db, conversationIds),
8381
8788
  readConversationParticipants(db, conversationIds),
8382
8789
  resolveSlackTeamDomains(conversations.flatMap((conversation) => conversation.location?.provider === "slack" ? [conversation.location.teamId] : [])),
8383
- listConversationWork(conversationIds),
8384
- readLastUserMessageAtByConversation(db, conversationIds),
8790
+ listConversationWork(conversationIds).then(async (work) => ({
8791
+ work,
8792
+ lastUserMessageAt: await readLastUserMessageAtByConversation(db, work.assignedIds.filter((conversationId) => work.finishedAtById[conversationId]))
8793
+ })),
8385
8794
  readConversationActivityPreviews(db, conversationIds),
8386
8795
  readAutomationTitlesByConversationId(conversations),
8387
8796
  readFirstHumanMessageTexts(db, conversations)
@@ -8447,6 +8856,57 @@ async function readConversationFeedFromSql(options = {}) {
8447
8856
  async function readConversationFeed(options = {}) {
8448
8857
  return conversationFeedSchema.parse(await readConversationFeedFromSql(options));
8449
8858
  }
8859
+ // src/api/conversations/event-list.ts
8860
+ /** Read one bounded page of reporting events before, after, or around a signed cursor. */
8861
+ async function readConversationEvents(conversationId, boundary, options = {}) {
8862
+ const record = await readConversationRecordFromSql(conversationId);
8863
+ if (!record) return void 0;
8864
+ const cursor = decodeConversationCursor({
8865
+ conversationId,
8866
+ cursor: "after" in boundary ? boundary.after : "around" in boundary ? boundary.around : boundary.before
8867
+ });
8868
+ if (!cursor) throwApiError(400, "Invalid conversation cursor.");
8869
+ const canExposePayload = (await readConversationAccessFromSql(getDb(), [conversationId], options.viewer)).get(conversationId)?.canViewPrivateContent ?? false;
8870
+ const transcriptPurgedAtMs = record.conversation.transcriptPurgedAtMs;
8871
+ const pageArgs = {
8872
+ canExposePayload,
8873
+ conversationId,
8874
+ limit: options.limit ?? 500
8875
+ };
8876
+ const page = transcriptPurgedAtMs !== void 0 ? { events: [] } : "after" in boundary ? await readConversationEventPageAfter(getSqlExecutor(), {
8877
+ ...pageArgs,
8878
+ afterSeq: cursor.seq
8879
+ }) : "around" in boundary ? await readConversationEventPageAround(getSqlExecutor(), {
8880
+ ...pageArgs,
8881
+ seq: cursor.seq
8882
+ }) : await readConversationEventPage(getSqlExecutor(), {
8883
+ ...pageArgs,
8884
+ beforeSeq: cursor.seq
8885
+ });
8886
+ return conversationEventPageSchema.parse(await conversationEventPageReport(getSqlExecutor(), {
8887
+ conversationId,
8888
+ eventHistory: conversationEventHistory({
8889
+ canExposePayload,
8890
+ ...transcriptPurgedAtMs === void 0 ? void 0 : { transcriptPurgedAtMs }
8891
+ }),
8892
+ page
8893
+ }));
8894
+ }
8895
+ /** Attach mentions and signed cursors to one bounded page of events. */
8896
+ async function conversationEventPageReport(executor, args) {
8897
+ const { conversationId, page } = args;
8898
+ const cursorAt = (seq) => encodeConversationCursor({
8899
+ conversationId,
8900
+ seq
8901
+ });
8902
+ return {
8903
+ events: (await attachConversationMentions(executor, conversationId, { events: page.events })).events,
8904
+ eventHistory: args.eventHistory,
8905
+ ...page.previousSeq === void 0 ? void 0 : { previousCursor: cursorAt(page.previousSeq) },
8906
+ ...page.nextSeq === void 0 ? void 0 : { nextCursor: cursorAt(page.nextSeq) },
8907
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString()
8908
+ };
8909
+ }
8450
8910
  // src/api/conversations/fork.ts
8451
8911
  /** Fork a Conversation that the viewer can read into a new root they own. */
8452
8912
  async function forkConversationForViewer(viewer, sourceConversationId, body) {
@@ -8627,6 +9087,12 @@ function projectConversationDetail(args) {
8627
9087
  canExposePayload,
8628
9088
  ...transcriptPurgedAtMs === void 0 ? void 0 : { transcriptPurgedAtMs }
8629
9089
  }),
9090
+ ...args.readPosition ? { readPosition: args.readPosition } : void 0,
9091
+ ...args.unreadAfterSeq !== void 0 ? { unreadCursor: encodeConversationCursor({
9092
+ conversationId,
9093
+ seq: args.unreadAfterSeq
9094
+ }) } : void 0,
9095
+ ...args.unreadPage ? { unreadPage: args.unreadPage } : void 0,
8630
9096
  generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
8631
9097
  ...sentryConversationUrl ? { sentryConversationUrl } : void 0,
8632
9098
  ...args.sourceTask ? { sourceTask: args.sourceTask } : void 0
@@ -8637,7 +9103,7 @@ async function readConversationDetailFromSql(conversationId, options) {
8637
9103
  if (!record) return void 0;
8638
9104
  const viewerMarks = options.viewer ? await readConversationViewerMarks(options.viewer, conversationId) : void 0;
8639
9105
  const executor = getSqlExecutor();
8640
- const [accessByConversation, annotations, automationTitleByConversation, auxiliaryCostsByConversation, briefVersion, firstHumanMessageTextByConversation, modelUsage, metricsByConversation, people, sourceTask, teamDomainByTeamId] = await Promise.all([
9106
+ const [accessByConversation, annotations, automationTitleByConversation, auxiliaryCostsByConversation, briefVersion, firstHumanMessageTextByConversation, modelUsage, metricsByConversation, people, readPosition, sourceTask, teamDomainByTeamId] = await Promise.all([
8641
9107
  readConversationAccessFromSql(getDb(), [conversationId], options.viewer),
8642
9108
  listConversationAnnotations(getDb(), conversationId),
8643
9109
  readAutomationTitlesByConversationId([record.conversation]),
@@ -8647,6 +9113,7 @@ async function readConversationDetailFromSql(conversationId, options) {
8647
9113
  record.conversation.transcriptPurgedAtMs === void 0 ? readConversationModelUsageFromSql(executor, { conversationId }) : Promise.resolve([]),
8648
9114
  readConversationTreeMetricsFromSql(getDb(), [conversationId]),
8649
9115
  readConversationAuthors(getDb(), conversationId),
9116
+ options.viewer ? readConversationReadPosition(options.viewer, conversationId) : void 0,
8650
9117
  readConversationSourceTask({
8651
9118
  conversationId,
8652
9119
  ...options.viewer ? { viewer: options.viewer } : void 0
@@ -8655,16 +9122,28 @@ async function readConversationDetailFromSql(conversationId, options) {
8655
9122
  ]);
8656
9123
  const access = accessByConversation.get(conversationId);
8657
9124
  const sidebarAnnotations = access?.canViewPrivateContent ? (await listConversationSidebarAnnotations([conversationId], /* @__PURE__ */ new Map([[conversationId, annotations]])))[conversationId] : void 0;
9125
+ const canExposePayload = access?.canViewPrivateContent ?? false;
8658
9126
  const page = record.conversation.transcriptPurgedAtMs === void 0 ? await readConversationEventPage(executor, {
8659
- canExposePayload: access?.canViewPrivateContent ?? false,
9127
+ canExposePayload,
8660
9128
  conversationId,
8661
9129
  limit: options.limit
8662
9130
  }) : { events: [] };
9131
+ const firstSeq = page.events[0]?.seq;
9132
+ const unreadAfterSeq = readPosition !== void 0 && page.previousSeq !== void 0 && firstSeq !== void 0 && readPosition.lastReadSeq + 1 < firstSeq ? readPosition.lastReadSeq : void 0;
8663
9133
  const brief = access?.canViewPrivateContent ? briefVersion?.content : void 0;
8664
- const { briefMentions, events } = await attachConversationMentions(executor, conversationId, {
9134
+ const [{ briefMentions, events }, unreadPage] = await Promise.all([attachConversationMentions(executor, conversationId, {
8665
9135
  ...brief ? { brief } : void 0,
8666
9136
  events: page.events
8667
- });
9137
+ }), options.unreadPage && unreadAfterSeq !== void 0 ? readConversationEventPageAround(executor, {
9138
+ canExposePayload,
9139
+ conversationId,
9140
+ limit: options.limit,
9141
+ seq: unreadAfterSeq
9142
+ }).then((around) => conversationEventPageReport(executor, {
9143
+ conversationId,
9144
+ eventHistory: conversationEventHistory({ canExposePayload }),
9145
+ page: around
9146
+ })).catch(() => void 0) : void 0]);
8668
9147
  const metrics = metricsByConversation.get(conversationId);
8669
9148
  const auxiliaryCosts = auxiliaryCostsByConversation.get(conversationId);
8670
9149
  const childAgentTotals = childAgentTotalsReport(metrics, auxiliaryCosts);
@@ -8692,6 +9171,9 @@ async function readConversationDetailFromSql(conversationId, options) {
8692
9171
  ...sourceTask ? { sourceTask } : void 0,
8693
9172
  teamDomainByTeamId,
8694
9173
  ...page.previousSeq === void 0 ? void 0 : { previousSeq: page.previousSeq },
9174
+ ...readPosition ? { readPosition } : void 0,
9175
+ ...unreadAfterSeq === void 0 ? void 0 : { unreadAfterSeq },
9176
+ ...unreadPage ? { unreadPage } : void 0,
8695
9177
  usage: metrics?.usage ?? record.usage ?? void 0
8696
9178
  });
8697
9179
  }
@@ -8702,20 +9184,73 @@ async function readConversationDetail(conversationId, options = {}) {
8702
9184
  limit: options.limit ?? 500
8703
9185
  });
8704
9186
  if (!report) return void 0;
8705
- const [forks, agentTree, readPosition, autoArchive] = await Promise.all([
9187
+ const [forks, agentTree, autoArchive] = await Promise.all([
8706
9188
  readConversationForks(conversationId, options.viewer),
8707
9189
  readConversationAgentTree(conversationId, options.viewer),
8708
- options.viewer ? readConversationReadPosition(options.viewer, conversationId) : void 0,
8709
9190
  options.viewer && report.isParticipant ? readConversationAutoArchive(options.viewer, conversationId) : void 0
8710
9191
  ]);
8711
9192
  return conversationDetailReportSchema.parse({
8712
9193
  ...report,
8713
9194
  ...forks,
8714
9195
  ...agentTree ? { agentTree } : void 0,
8715
- ...readPosition ? { readPosition } : void 0,
8716
9196
  ...autoArchive === void 0 ? void 0 : { autoArchive }
8717
9197
  });
8718
9198
  }
9199
+ // src/api/conversations/pin.ts
9200
+ /**
9201
+ * Pin or unpin one conversation for the signed-in viewer.
9202
+ *
9203
+ * A pin lives on the viewer's participant row, and that row grants send and
9204
+ * control access. So only a participant can pin, the same as archive. The
9205
+ * root actor may have no row yet, so pinning adds it. A pin also restores an
9206
+ * archived conversation, because the Pinned section shows only active
9207
+ * conversations.
9208
+ */
9209
+ async function pinConversation(viewer, conversationId, body) {
9210
+ if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(404, "Conversation not found.");
9211
+ const executor = getSqlExecutor();
9212
+ const rootConversationId = await resolveRootConversationId(executor, conversationId);
9213
+ const db = executor.db();
9214
+ if (!body.pinned) {
9215
+ await db.update(juniorConversationParticipants).set({ pinnedAt: null }).where(and(eq(juniorConversationParticipants.userId, viewer.id), eq(juniorConversationParticipants.rootConversationId, rootConversationId)));
9216
+ return { pinnedAt: null };
9217
+ }
9218
+ const [root] = await db.select({ lastActivityAt: juniorConversations.lastActivityAt }).from(juniorConversations).where(eq(juniorConversations.conversationId, rootConversationId)).limit(1);
9219
+ if (!root) throwApiError(404, "Conversation not found.");
9220
+ const pinnedAt = /* @__PURE__ */ new Date();
9221
+ await db.insert(juniorConversationParticipants).values({
9222
+ lastMessageAt: root.lastActivityAt,
9223
+ pinnedAt,
9224
+ rootConversationId,
9225
+ userId: viewer.id
9226
+ }).onConflictDoUpdate({
9227
+ target: [juniorConversationParticipants.userId, juniorConversationParticipants.rootConversationId],
9228
+ set: {
9229
+ archivedAt: null,
9230
+ pinnedAt
9231
+ }
9232
+ });
9233
+ return { pinnedAt: pinnedAt.toISOString() };
9234
+ }
9235
+ // src/api/conversations/steer-pending-messages.ts
9236
+ /**
9237
+ * Steer the viewer's own queued web messages into the conversation now.
9238
+ *
9239
+ * Only the author can steer a message. Ids that are not the viewer's queued
9240
+ * web messages, or that Junior already read, are left out of the result.
9241
+ */
9242
+ async function steerConversationPendingMessagesForViewer(viewer, conversationId, body) {
9243
+ if (!await getConversationStore().get({ conversationId })) throwApiError(404, "Conversation not found.");
9244
+ if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(403, "Only conversation participants can steer queued messages.");
9245
+ return {
9246
+ conversationId,
9247
+ steeredInboundMessageIds: (await steerWebPendingMessages({
9248
+ authorIds: webActorUserIds(viewer),
9249
+ conversationId,
9250
+ inboundMessageIds: body.inboundMessageIds
9251
+ })).steeredInboundMessageIds
9252
+ };
9253
+ }
8719
9254
  // src/api/conversations/stop.ts
8720
9255
  /**
8721
9256
  * Stop the active Turn for one conversation participant.
@@ -8768,4 +9303,4 @@ function viewerWebMessages(messages, viewer) {
8768
9303
  }] : [];
8769
9304
  });
8770
9305
  }
8771
- export { runAutoArchiveSweep as $, resolveAllowedDomains as A, bindMessageAuthorIdentityId as B, createProductionSlackWebhookServices as C, isAllowedDomain as D, assertNoLegacyAllowedDomains as E, stopSlackThread as F, actOnReviewItem as G, stripLeadingBotMention as H, normalizeIncomingSlackThreadId as I, reviewItemChange as J, closeReviewItemsAnsweredByReply as K, withNormalizedThreadId as L, buildSlackInboundMessage as M, clearSlackPendingReactions as N, isAllowedSignInEmail as O, isSlackMessageStopped as P, readUserAutoArchiveSettings as Q, stopConversationTurn as R, createProductionConversationWorkOptions as S, createSlackWebApiStatusSender as T, parseContent as U, startProcessingReaction as V, ReviewItemActionError as W, archiveViewerDoneConversations as X, DEFAULT_AUTO_ARCHIVE_SETTINGS as Y, readConversationAutoArchive as Z, resolveMentions as _, readConversationAgentTree as a, getAttachmentStorage as at, encodeConversationCursor as b, readConversationForks as c, GET as ct, readConversationAuxiliaryCostsFromSql as d, setConversationAutoArchive as et, childAgentTotalsReport as f, attachConversationMentions as g, conversationSummaryFromStoredConversation as h, readConversationReadPosition as i, throwApiError as it, recordSkippedConversationMessage as j, readEnvList as k, readConversationFeed as l, readHealthReport as lt, conversationEventHistory as m, readConversationDetail as n, emptyResponse as nt, forkConversationForViewer as o, AGENT_DISPATCH_MAX_AGE_MS as ot, readConversationTreeMetricsFromSql as p, readReviewItemForUser as q, markConversationRead as r, jsonResponse as rt, keepQuickQuestionForViewer as s, enqueueAgentDispatch as st, stopConversationTurnForViewer as t, updateUserAutoArchiveSettings as tt, readConversationRecordFromSql as u, readFirstHumanMessageTexts as v, getProductionSlackAdapter as w, archiveConversation as x, decodeConversationCursor as y, THREAD_OPTOUT_ACK as z };
9306
+ export { readReviewItemForUser as $, getProductionSlackAdapter as A, isSlackMessageStopped as B, cancelConversationPendingMessagesForViewer as C, archiveConversation as D, resolveMentions as E, readEnvList as F, THREAD_OPTOUT_ACK as G, normalizeIncomingSlackThreadId as H, resolveAllowedDomains as I, stripLeadingBotMention as J, bindMessageAuthorIdentityId as K, recordSkippedConversationMessage as L, assertNoLegacyAllowedDomains as M, isAllowedDomain as N, createProductionConversationWorkOptions as O, isAllowedSignInEmail as P, closeReviewItemsAnsweredByReply as Q, buildSlackInboundMessage as R, encodeConversationCursor as S, requireConversationPendingMessages as T, withNormalizedThreadId as U, stopSlackThread as V, stopConversationTurn as W, ReviewItemActionError as X, parseContent as Y, actOnReviewItem as Z, conversationSummaryFromStoredConversation as _, markConversationRead as a, runAutoArchiveSweep as at, createConversationForViewer as b, forkConversationForViewer as c, emptyResponse as ct, readConversationEvents as d, getAttachmentStorage as dt, reviewItemChange as et, readConversationFeed as f, AGENT_DISPATCH_MAX_AGE_MS as ft, readConversationTreeMetricsFromSql as g, childAgentTotalsReport as h, readHealthReport as ht, readConversationDetail as i, readUserAutoArchiveSettings as it, createSlackWebApiStatusSender as j, createProductionSlackWebhookServices as k, keepQuickQuestionForViewer as l, jsonResponse as lt, readConversationAuxiliaryCostsFromSql as m, GET as mt, steerConversationPendingMessagesForViewer as n, archiveViewerDoneConversations as nt, readConversationReadPosition as o, setConversationAutoArchive as ot, readConversationRecordFromSql as p, enqueueAgentDispatch as pt, startProcessingReaction as q, pinConversation as r, readConversationAutoArchive as rt, readConversationAgentTree as s, updateUserAutoArchiveSettings as st, stopConversationTurnForViewer as t, DEFAULT_AUTO_ARCHIVE_SETTINGS as tt, readConversationForks as u, throwApiError as ut, readFirstHumanMessageTexts as v, readConversationPendingMessages as w, decodeConversationCursor as x, appendConversationMessageForViewer as y, clearSlackPendingReactions as z };