@sentry/junior 0.315.0 → 0.317.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 (139) hide show
  1. package/dist/{admin-5jUYY46p.js → admin-CAugg87B.js} +1 -1
  2. package/dist/{agent-runner-C7GNLRB6.js → agent-runner-AjrEV6Qe.js} +13532 -12811
  3. package/dist/{reporting-window-C4dbzDiR.js → agent-status-BA5x3Xtp.js} +33 -1
  4. package/dist/{agent-update-delivery-BNEYQsAf.js → agent-update-delivery-B_YIZcgf.js} +10 -37
  5. package/dist/api/schema.d.ts +609 -104
  6. package/dist/api/schema.js +6 -6
  7. package/dist/api.js +373 -469
  8. package/dist/{app-D_bAXRDe.d.ts → app-MoNAsVV5.d.ts} +52 -28
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +177 -132
  11. package/dist/catalog-runtime-DfSpJZdY.js +6 -0
  12. package/dist/{change-record-Bqsa5ZXE.d.ts → change-record-BzJgLsv7.d.ts} +60 -1
  13. package/dist/{adapter-context-BlSGE44V.js → channel-access-j-YAVYK4.js} +2 -42
  14. package/dist/{chat-core-engine-CxkwRpn9.js → chat-core-engine-aH85nEHv.js} +4 -3
  15. package/dist/{child-message--2G3Ft26.js → child-message-DHjQLEd1.js} +1 -1
  16. package/dist/cli/chat.js +23 -23
  17. package/dist/cli/check.js +5 -5
  18. package/dist/cli/main.js +2 -2
  19. package/dist/cli/plugins.js +5 -4
  20. package/dist/cli/snapshot-create.js +5 -2
  21. package/dist/cli/upgrade.js +27 -5
  22. package/dist/config-CHQ8X251.js +2422 -0
  23. package/dist/{continue-in-slack-BGKjIdFp.js → continue-in-slack-D-FZ8Fin.js} +2 -3
  24. package/dist/{conversation-feed-Sl8lKKmR.js → conversation-feed--9S0_PXL.js} +9 -4
  25. package/dist/{proxy-path-Dc-0jXGi.js → conversation-privacy-B1uXn5sf.js} +2 -16
  26. package/dist/{conversation-turn-BoLK9i6g.js → conversation-turn-BUE_7xaN.js} +102 -172
  27. package/dist/{create-BOycVH9h.js → create-DoDIYgtZ.js} +12 -10
  28. package/dist/{credential-sync-Mn4OdkEh.js → credential-sync-BJOqGnjV.js} +17 -12
  29. package/dist/{db-DXTOYRzR.js → db-BFmyYZtJ.js} +20276 -27398
  30. package/dist/{deployment-CG3TchWh.js → deployment-DXq9ZLU4.js} +17 -15
  31. package/dist/{engine-context-dyWlfNdD.js → engine-context-CgQ7mlHt.js} +264 -50
  32. package/dist/{html-CfXEwl_h.js → html-B3VKTGbJ.js} +6 -2
  33. package/dist/instrumentation.js +15 -7
  34. package/dist/{job-runner-CySgpi9v.js → job-runner-A1lCkybD.js} +397 -22
  35. package/dist/{lineage-tRTOcrsL.js → lineage-Bktb0UcV.js} +1 -1
  36. package/dist/{list-DXBz8SYL.js → list-Bxvg5wXf.js} +260 -698
  37. package/dist/{logging-czs0nqLC.js → logging--smS7XRK.js} +2 -2
  38. package/dist/{mailbox-turn-79Nv1JXv.js → mailbox-turn-uSXhUFc9.js} +648 -2957
  39. package/dist/{message-BTox2Cmb.js → message-BNenhsmB.js} +12 -22
  40. package/dist/{model-input-IRGa98V7.js → model-input-BReSnwHp.js} +3 -3
  41. package/dist/nitro.d.ts +1 -1
  42. package/dist/nitro.js +20 -6
  43. package/dist/{oauth-callback-server-NXK7AlBp.js → oauth-callback-server-CE4soEIY.js} +2 -2
  44. package/dist/{oauth-relay-6NBPSpFE.js → oauth-relay-C36gX1gH.js} +2 -2
  45. package/dist/{package-discovery-BI6T_RkD.js → package-discovery-DD9vencX.js} +1 -50
  46. package/dist/{parent-result-Dg6P6roR.js → parent-result-Ck1rFYRQ.js} +93 -106
  47. package/dist/{plugins-BXMdNdyA.js → plugins-D_Ru4CWc.js} +1 -1
  48. package/dist/profile-BQ-iBDsZ.js +4657 -0
  49. package/dist/{transcript-BHhJVY0P.js → prompt-Dv7gkpD6.js} +97 -103
  50. package/dist/proxy-path-BHYoKZdq.js +15 -0
  51. package/dist/registry-iXMT5Jmh.js +3279 -0
  52. package/dist/reports-WKHfGTsU.js +195 -0
  53. package/dist/{resolve-BUFkmxkT.js → resolve-tony4ibz.js} +9 -29
  54. package/dist/{result-DfATzX77.js → result-Bta_dlWa.js} +42 -117
  55. package/dist/run-conversation-DL6ru7iW.js +336 -0
  56. package/dist/{runner-CmKP3inb.js → runner-BstDRbD9.js} +7 -7
  57. package/dist/{sandbox-egress-signals-DYo5BsM7.js → sandbox-egress-signals-oSJMJOnn.js} +1 -1
  58. package/dist/{schema-DrBMdPmv.js → schema-DfqrHACA.js} +67 -84
  59. package/dist/sender-actors-CPglLd5R.js +83 -0
  60. package/dist/{service-account-CxTX7nnR.js → service-account-CTV_jaNu.js} +3 -1
  61. package/dist/{skills-BlHUDj7k.js → skills-BCEU41zM.js} +4 -4
  62. package/dist/{slack-conversation-unfurl-Dhe3lB1U.js → slack-conversation-unfurl-DxVmhbGP.js} +7 -6
  63. package/dist/{spawn-CfvlFdfz.js → spawn-frczVPIr.js} +11 -8
  64. package/dist/{system-prompt-table-CDCYVwqN.js → system-prompt-table-CiXy0eNR.js} +91 -70
  65. package/dist/{task-runner-DcdQJd9e.js → task-runner-C9Yc2_ae.js} +35 -49
  66. package/dist/{thread-context-DF5uDcWN.js → thread-context-CqZDKErp.js} +6 -6
  67. package/dist/topics-SRN7IVX-.js +24 -0
  68. package/dist/turn-membership-CENFf3kI.js +856 -0
  69. package/dist/{turn-wake-um5Ubd4m.js → turn-wake-BhloiI2h.js} +4 -5
  70. package/dist/{media-Cr9pGkzr.js → types-C4iC-IMC.js} +819 -777
  71. package/dist/user-customization-CvfuY9Eo.js +93 -0
  72. package/dist/users-ByG5RCEJ.js +181 -0
  73. package/dist/{validation-CJyuOPD2.js → validation-8gjfR91V.js} +1 -1
  74. package/dist/{version-Bhe7RPIe.js → version-BeZhWWBE.js} +1 -1
  75. package/dist/version.js +1 -1
  76. package/dist/{worker-D8PRgUqr.js → worker-BqMQQNRk.js} +5 -4
  77. package/migrations/20261125171254_conversation_visibility/migration.sql +4 -0
  78. package/migrations/20261125171254_conversation_visibility/snapshot.json +67 -0
  79. package/migrations/20261125171257_conversation_visibility_backfill/migration.sql +25 -0
  80. package/migrations/20261125171257_conversation_visibility_backfill/snapshot.json +9 -0
  81. package/migrations/20261125213232_drop_versions_notify/migration.sql +19 -0
  82. package/migrations/20261125213232_drop_versions_notify/snapshot.json +9 -0
  83. package/migrations/20261125225138_conversation_kind_root_thread/migration.sql +23 -0
  84. package/migrations/20261125225138_conversation_kind_root_thread/snapshot.json +55 -0
  85. package/migrations/20261125225142_conversation_kind_root_thread_backfill/migration.sql +7 -0
  86. package/migrations/20261125225142_conversation_kind_root_thread_backfill/snapshot.json +9 -0
  87. package/migrations/20261126000151_conversation_event_message_role_seq_index/migration.sql +1 -0
  88. package/migrations/20261126000151_conversation_event_message_role_seq_index/snapshot.json +69 -0
  89. package/migrations/20261126012917_merge_leaves/migration.sql +2 -0
  90. package/migrations/20261126012917_merge_leaves/snapshot.json +12 -0
  91. package/migrations/20261126025226_drop_agent_invocations/migration.sql +6 -0
  92. package/migrations/20261126025226_drop_agent_invocations/snapshot.json +9 -0
  93. package/migrations/20261126033000_space_conversations_lead_children/migration.sql +155 -0
  94. package/migrations/20261126033000_space_conversations_lead_children/snapshot.json +9 -0
  95. package/migrations/20261126144620_drop_user_message_time_index/migration.sql +1 -0
  96. package/migrations/20261126144620_drop_user_message_time_index/snapshot.json +38 -0
  97. package/migrations/20261126153100_inbox_item_subjects/migration.sql +140 -0
  98. package/migrations/20261126153100_inbox_item_subjects/snapshot.json +9 -0
  99. package/migrations/20261126153103_inbox_item_subjects_not_null/migration.sql +12 -0
  100. package/migrations/20261126153103_inbox_item_subjects_not_null/snapshot.json +9 -0
  101. package/migrations/20261126153105_inbox_item_subject_indexes/migration.sql +1 -0
  102. package/migrations/20261126153105_inbox_item_subject_indexes/snapshot.json +9 -0
  103. package/migrations/20261126153108_automation_run_conversation_index/migration.sql +1 -0
  104. package/migrations/20261126153108_automation_run_conversation_index/snapshot.json +9 -0
  105. package/migrations/20261126153159_inbox_item_subjects_schema/migration.sql +4 -0
  106. package/migrations/20261126153159_inbox_item_subjects_schema/snapshot.json +437 -0
  107. package/migrations/20261126153259_inbox_questions/migration.sql +76 -0
  108. package/migrations/20261126153259_inbox_questions/snapshot.json +9 -0
  109. package/migrations/20261126153301_inbox_questions_valid/migration.sql +3 -0
  110. package/migrations/20261126153301_inbox_questions_valid/snapshot.json +9 -0
  111. package/migrations/20261126153343_inbox_questions_schema/migration.sql +5 -0
  112. package/migrations/20261126153343_inbox_questions_schema/snapshot.json +407 -0
  113. package/migrations/20261126154025_inbox_item_owners/migration.sql +74 -0
  114. package/migrations/20261126154025_inbox_item_owners/snapshot.json +9 -0
  115. package/migrations/20261126154048_inbox_item_open_subject_key_index/migration.sql +1 -0
  116. package/migrations/20261126154048_inbox_item_open_subject_key_index/snapshot.json +9 -0
  117. package/migrations/20261126154051_drop_inbox_item_owner_indexes/migration.sql +7 -0
  118. package/migrations/20261126154051_drop_inbox_item_owner_indexes/snapshot.json +9 -0
  119. package/migrations/20261126154121_inbox_item_owners_schema/migration.sql +8 -0
  120. package/migrations/20261126154121_inbox_item_owners_schema/snapshot.json +311 -0
  121. package/migrations/20261126175601_conversation_event_turn/migration.sql +5 -0
  122. package/migrations/20261126175601_conversation_event_turn/snapshot.json +103 -0
  123. package/migrations/20261126175614_conversation_event_turn_index/migration.sql +1 -0
  124. package/migrations/20261126175614_conversation_event_turn_index/snapshot.json +62 -0
  125. package/migrations/20261126230028_merge_leaves/migration.sql +2 -0
  126. package/migrations/20261126230028_merge_leaves/snapshot.json +12 -0
  127. package/migrations/20261126231932_space_lead_holds_name/migration.sql +46 -0
  128. package/migrations/20261126231932_space_lead_holds_name/snapshot.json +58 -0
  129. package/migrations/20261127001022_merge_leaves/migration.sql +2 -0
  130. package/migrations/20261127001022_merge_leaves/snapshot.json +12 -0
  131. package/package.json +5 -5
  132. package/skills/jr-rpc/SKILL.md +3 -5
  133. package/dist/direct-url-BYgYfuIy.js +0 -22
  134. package/dist/markers-CE0HMXWT.js +0 -67
  135. package/dist/people-Cegp1Iwq.js +0 -81
  136. package/dist/start-conversation-Uh8Sk1EF.js +0 -162
  137. package/dist/turn-session-routing-GtetHsdO.js +0 -1309
  138. package/dist/user-customization-B27StpVQ.js +0 -9
  139. package/dist/web-message-id-C6P83ans.js +0 -10
@@ -1,38 +1,42 @@
1
- import { $ as getPlugins, $d as getStateValues, $i as getVercelConversationWorkQueue, $o as existingConversationId, A as resolveRootConversationId, Aa as createPluginCache, Ac as inboxItemPlugin, Af as botConfig, Ao as parseDashboardPersonLink, Ar as pluginCatalogRuntime, As as treeAwaitsAuthorization, B as normalizeSlackStatusText, Ba as getDispatchTurnId, Bs as dismissOpenInboxItems, Bt as canMoveToSpace, C as locationFromRow, Cd as isDmChannel, Co as getDashboardLinkFilter, Cr as createUserTokenStore, Cs as conversationStatusSql, Cu as juniorSpaces, Dc as inboxItemForUser, Df as parseSlackMessageTs, Dl as readConversationAccessRows, Ds as conversationKindFromRow, Du as juniorUsers, Ec as canUserReadInboxItem, El as readConversationAccessFromSql, Es as executionIsActive, F as SLACK_USER_MENTION_RE, Fa as createOrGetDispatch, Fc as isAutomationAlertItem, Ff as getSlackClientSecret, Fl as rootSpaceReadableBy, Fu as slackChannelMessageReplyThreadTs, G as applyPluginFormatMarkdown, Ga as markDispatchBlocked, Go as automationVersionOf, Gr as PluginMcpClient, Gt as isTopLevel, H as slackMentionedUserIds, Ha as isTerminalDispatchStatus, Hl as juniorTodos, Ho as admitEventAutomationRun, Ia as getDispatchConversationId, Ic as isInboxItemForEveryone, If as getSlackSigningSecret, Il as rootVisibleToViewer, Io as findMatchingEventAutomations, Iu as slackChannelMessageRunsAutomation, Ja as markDispatchRunning, Js as ownerConversationId, Ju as cancelSubscriptions, K as createPluginEventPublisher, Ka as markDispatchCompleted, Kf as normalizeSlackEmojiName, Kt as messagesNeedSpaceMembership, La as getDispatchIdForConversation, Lc as isOnlyAssignee, Ld as eventGuidance, Li as completeDecision, Ll as viewerMarksFromParticipant, M as conversationSlackTenantId, Ma as buildDispatchId, Ml as conversationIsNotUnsubscribedRoot, Mo as blockEventAutomation, Ms as AUTOMATION_ALERT_STEP_FIELD_ID, N as loadConversationSlackTenantIds, Na as claimDispatchMailboxAppend, Nc as inboxItemTodo, Nd as updateTimerIndex, Nf as getSlackBotToken, Nl as conversationPinnedForUser, No as collectEventAutomationMatchKeys, Oc as inboxItemNeedsInput, Od as streamPrivateSlackFile, Ol as readPrivateSpaceMemberships, Oo as isDashboardLink, Os as awaitsAuthorizationFrom, Ou as juniorDestinations, P as parseSessionSource, Pa as confirmDispatchMailboxAppend, Pd as CORE_EVENT_NAMESPACE, Pf as getSlackClientId, Pl as readMemberParticipants, Ps as fallbackShortTitle, Qd as getStateAdapter, Qi as createPluginInboxItems, Qr as getMcpStoredOAuthCredentials, Ra as getDispatchInputMessageId, Rc as isPluginInboxItem, Rs as closeInboxItem, S as withConversationMutationLock, Sc as canActOnInboxItem, Si as createPluginEmbedder, Sl as canAddConversationMessages, Ss as conversationIsActiveSql, Td as normalizeSlackConversationId, Tl as createConversationAccessReader, To as getDashboardPersonLink, Ts as conversationWaitsOnUserSql, U as wrapBareSlackUserIds, Uo as eventAutomationRunLimitReason, Us as inboxItemNeedsUserNow, V as slackMention, Va as getPluginDispatchProjection, Vs as getInboxItem, Vt as deliversFinalText, Wa as markDispatchAwaitingResume, Wi as JUNIOR_NATIVE_EVENT_NAMESPACE, Wr as McpAuthorizationRequiredError, Xa as addReactionToMessage, Xi as createPluginConversationChanges, Xs as takeInboxItem, Xu as collectEventMatchKeys, Ya as notifyAutomationBlocked, Yf as resolveGatewayModel, Yl as juniorInboxItemConversations, Yt as turnBehavior, Zi as PLUGIN_CHOICE_FIELD_ID, Zl as juniorInboxItems, _ as readConversationTrees, _d as SlackActionError, _f as requireSlackDestination, a as getDb, au as juniorConversationParticipants, bd as getHeaderString, bl as readCachedUserByEmail, bn as getTurnRequestDeadline, bo as getDashboardConversationLink, bu as juniorConversations, cd as bindScheduledAutomationCredentialSubject, cf as createSlackResumeActor, cl as userAvatarUrlsFromIdentities, cp as estimateTextTokens, cs as recordAutomationExecution, da as listConversationAnnotationsById, dc as settleInboxSnoozes, dd as verifyScheduledAutomationCredentialSubject, df as parseActorUserId, dl as resolveActorIdentityId, ed as findMatchingWatches, ef as setStateValues, en as indexEndedTurnEvents, ep as createCache, eu as juniorAutomations, f as copyMessageLinks, fd as verifySlackDirectCredentialSubject, fl as saveActorAvatar, fs as agentTurnUsageSchema, fu as juniorConversationAnnotations, ga as lookupSlackUserNames, gc as nextDetailVersion, h as conversationAncestors, ha as lookupSlackUser, hf as createSlackDestination, hu as juniorCodeChanges, i as getConversationStore, ic as SNOOZE_TIMER_EVENT_TYPE, il as identityAvatarUrl, jf as getChatConfig, jl as conversationIsMemberRoot, js as AUTOMATION_ALERT_STEPS, ju as getEventCatalog, kc as inboxItemOwnedByConversation, kd as withSlackRetries, ki as conversationSearchVector, kn as createPluginState, ko as parseDashboardConversationLink, ks as hasUnexpiredAuthorizationRequest, la as createPluginAnnotations, lc as listFiringInboxSnoozeTriggers, ld as bindSlackDirectCredentialSubject, lf as isActorUserId, ll as userAvatarUrlsFromJoinedPhotos, ln as storedMessageJson, lp as textCharsForTokens, m as withConversationEventLock, md as readJuniorSecret, mf as truncateStatusText, ms as conversationCostOf, n as getConversationEventStore, nf as credentialContextForActor, np as acquireActiveLock, nr as resolveBaseUrl, o as getSqlExecutor, of as createActor, pn as createPluginTaskStarter, ps as hasAgentTurnUsage, qa as markDispatchFailed, qs as listReplyActionItems, qt as postsRunNotices, rd as listConversationsWithWatches, ri as webActorUserIds, rl as hasUserPhoto, ro as removeReactionFromMessage, sd as bindEventAutomationCredentialSubject, sf as createSlackActor, ss as readAutomationTitlesByConversationId, tf as actorLogContext, tu as juniorAutomationRuns, ua as listConversationAnnotations, ud as verifyEventAutomationCredentialSubject, uf as isUserActor, us as addAgentTurnUsage, uu as juniorConversationEvents, v as setArchivedAt, vc as PLUGIN_INBOX_ITEM_KEY_PREFIX, vd as downloadPrivateSlackFile, vn as sendVercelPluginTask, vu as juniorAttachments, wa as basePluginContext, wc as canAnswerInboxItem, wd as isSlackRequestTimeout, wl as conversationAccessFromRows, wn as createPluginConversationWatches, ws as conversationTurnFailedSql, wu as juniorIdentities, xc as TODO_INBOX_ITEM_KEY_PREFIX, xd as getSlackClient, xf as parseSlackTeamId, xn as createPluginCodeChanges, xp as isProviderRetryError, y as lastMessageAtSql, yf as parseSlackChannelId, yu as juniorMessageAttachments, za as getDispatchRecord, zi as completeText, zn as isPostgresErrorCode } from "./db-DXTOYRzR.js";
2
- import { G as mapBounded, I as createPluginLogger, _ as trimTrailingAssistantMessages } from "./transcript-BHhJVY0P.js";
3
- import { D as buildSentryConversationUrl, E as withSpan, N as normalizeIdentityEmail, P as toOptionalString, S as setTags, T as withLogContext, b as setSpanAttributes, f as logError, h as logWarn, m as logInfo, n as createChatSdkLogger, o as getActiveTraceContext, p as logException, s as getActiveTraceId, t as buildTurnFailureResponse, y as setSentryUser } from "./logging-czs0nqLC.js";
1
+ import { $l as deliversFinalText, Ac as listReplyActionItems, Ai as wrapBareSlackUserIds, Al as isDashboardLink, Ao as bindScheduledAutomationCredentialSubject, Ar as viewerMarksFromParticipant, B as conversationIsActiveSql, Bo as credentialContextForActor, C as conversationSlackTenantId, Cd as topLevelConversation, Cl as getDashboardConversationLink, Cr as readConversationAccessRows, Cs as createSlackActor, Da as existingConversationId, Dc as getInboxItem, Di as normalizeSlackStatusText, Dr as conversationPinnedForUser, Ds as parseActorUserId, Ec as dismissOpenInboxItems, El as getDashboardPersonLink, Er as conversationIsNotUnsubscribedRoot, Es as isUserActor, F as parseSessionSource, Fc as inboxItemAnswer, Fd as juniorAutomationRuns, Fo as verifySlackDirectCredentialSubject, Fs as SlackActionError, G as executionIsActive, Gc as identityAvatarUrl, H as conversationStatusSql, Hs as isDmChannel, I as conversationCostOf, Ia as readAutomationTitlesByConversationId, Ic as inboxItemRequest, Ii as createPluginEmbedder, In as createInboxItemShow, Is as downloadPrivateSlackFile, J as hasUnexpiredAuthorizationRequest, Ji as createPluginCache, Jr as buildDispatchId, Ju as setStateValues, K as conversationKindFromRow, Ka as fallbackShortTitle, Ko as readSubjectLinks, Kr as resolveConversationRouting, Ks as streamPrivateSlackFile, Ku as getStateAdapter, La as recordAutomationExecution, Lo as updateTimerIndex, Md as juniorQuestions, Ml as parseDashboardPersonLink, Mu as completeDecision, Nc as takeInboxItem, No as verifyEventAutomationCredentialSubject, Oi as slackMention, On as canJoinTurn, Or as readMemberParticipants, Pi as createPluginState, Po as verifyScheduledAutomationCredentialSubject, Pu as completeText, Q as canAnswerInboxItem, Qd as juniorConversationEvents, Qn as createPluginEventPublisher, Qr as getDispatchConversationId, Qu as hasAgentTurnUsage, Rc as itemQuestion, Rd as juniorAutomations, Rn as pushInboxSnoozeWakes, Rs as getHeaderString, Rt as setTodoStatusByUser, S as setArchivedAt, Sc as closeHandledReplyNotices, So as findMatchingWatches, Sr as readConversationAccessFromSql, Ss as createActor, T as lastMessageAtSql, Tc as closeInboxItem, Tl as getDashboardLinkFilter, To as listConversationsWithWatches, Tr as conversationIsMemberRoot, Ts as isActorUserId, U as conversationTurnFailedSql, Ua as AUTOMATION_ALERT_STEPS, Uc as subjectTodo, Ud as juniorInboxItems, Us as isSlackRequestTimeout, Vi as basePluginContext, W as conversationWaitsOnUserSql, Wa as AUTOMATION_ALERT_STEP_FIELD_ID, Wc as hasUserPhoto, Wr as runWithSlackInstallation, Ws as normalizeSlackConversationId, Wt as cancelHumanFacingPendingMessages, X as canActOnInboxItem, Xc as userAvatarUrlsFromJoinedPhotos, Xn as sendSlackReply, Y as treeAwaitsAuthorization, Yc as userAvatarUrlsFromIdentities, Yi as truncateStatusText, Yn as resolveSlackReplyTarget, Yu as addAgentTurnUsage, Zc as SNOOZE_TIMER_EVENT_TYPE, Zo as canPauseConversationDelivery, Zr as createOrGetDispatch, Zs as createPluginUsers, Zu as agentTurnUsageSchema, _a as eventAutomationRunLimitReason, _c as readCachedUserByEmail, _r as canInviteToConversation, a as getDb, ad as createSlackDestination, ao as slackChannelMessageRunsAutomation, as as conversationSearchVector, at as inboxItemOwnedByConversation, bd as spaceLeadIds, br as createConversationAccessReader, bs as lookupSlackUser, cc as saveActorAvatar, cd as parseSlackChannelId, cf as juniorMessageAttachments, cl as CORE_EVENT_NAMESPACE, cr as getTurnRequestDeadline, cs as isPublicConversation, di as notifyAutomationBlocked, dl as eventGuidance, ds as conversationAncestorsOrSelf, dt as isInboxItemForEveryone, ed as resolveRootConversationId, ei as getDispatchInputMessageId, eo as getEventCatalog, et as canUserReadInboxItem, ff as juniorIdentities, fi as addReactionToMessage, fr as createPluginConversationChanges, fs as conversationSubtree, ft as isOnlyAssignee, ga as admitEventAutomationRun, gd as parseSlackMessageTs, gf as juniorDestinations, go as cancelSubscriptions, gr as canAddConversationMessages, hf as juniorUsers, hu as indexEndedTurnEvents, i as getConversationStore, if as juniorCodeChanges, ii as isTerminalDispatchStatus, il as settleInboxSnoozes, io as slackChannelMessageReplyThreadTs, is as listConversationAnnotationsById, it as inboxItemNeedsInput, iu as isTopLevel, jc as ownerConversationId, ji as applyPluginFormatMarkdown, jl as parseDashboardConversationLink, jo as bindSlackDirectCredentialSubject, jr as getVercelConversationWorkQueue, k as locationFromRow, kd as juniorTodos, ki as slackMentionedUserIds, kn as canShareTurn, ko as bindEventAutomationCredentialSubject, kr as rootVisibleToViewer, lf as juniorConversations, lr as createPluginCodeChanges, mr as createPluginInboxItems, n as getConversationEventStore, ni as getDispatchTurnId, nl as listFiringInboxSnoozeTriggers, nn as getConversation, ns as createPluginAnnotations, nt as inboxItemAddedByAutomation, o as getSqlExecutor, oa as blockEventAutomation, od as requireSlackDestination, or as sendVercelPluginTask, ot as inboxItemPlugin, ou as ownsLocation, p as copyMessageLinks, pr as PLUGIN_CHOICE_FIELD_ID, ps as conversationSubtreeColumns, pt as isPluginInboxItem, q as awaitsAuthorizationFrom, qd as juniorConversationParticipants, qn as safeLinkUrl, qr as resolveTurnResumeRouting, qs as withSlackRetries, qu as getStateValues, rd as nextDetailVersion, ri as getPluginDispatchProjection, rn as getConversationWorkState, rs as listConversationAnnotations, rt as inboxItemForUser, ru as isThread, sa as collectEventAutomationMatchKeys, sc as resolveActorIdentityId, sf as juniorAttachments, su as postsRunNotices, tf as juniorConversationAnnotations, ti as getDispatchRecord, tr as createPluginTaskStarter, u as isPostgresErrorCode, ua as findMatchingEventAutomations, ud as parseSlackTeamId, ut as isAutomationAlertItem, uu as turnBehavior, v as withConversationEventLock, vo as collectEventMatchKeys, w as loadConversationSlackTenantIds, wi as SLACK_USER_MENTION_RE, ws as createSlackResumeActor, wu as storedMessageJson, x as readConversationTrees, xc as waitingConversationIdsQuery, xd as listedConversation, xr as leaveEndsAccess, xs as lookupSlackUserNames, xt as getPlugins, y as conversationAncestors, ya as automationVersionOf, yd as rootSpaceIdSql, yi as removeReactionFromMessage, yr as conversationAccessFromRows, zc as INBOX_SUBJECT_KINDS, zo as actorLogContext, zs as getSlackClient, zu as JUNIOR_NATIVE_EVENT_NAMESPACE } from "./db-BFmyYZtJ.js";
2
+ import { $ as isProviderRetryError, B as textCharsForTokens, C as resolveGatewayModel, M as acquireActiveLock, a as getSlackClientId, d as normalizeSlackEmojiName, i as getSlackBotToken, k as createCache, n as getChatConfig, o as getSlackClientSecret, s as getSlackSigningSecret, t as botConfig, z as estimateTextTokens } from "./config-CHQ8X251.js";
3
+ import { D as buildSentryConversationUrl, E as withSpan, N as normalizeIdentityEmail, P as toOptionalString, S as setTags, T as withLogContext, b as setSpanAttributes, f as logError, h as logWarn, m as logInfo, n as createChatSdkLogger, o as getActiveTraceContext, p as logException, s as getActiveTraceId, t as buildTurnFailureResponse, y as setSentryUser } from "./logging--smS7XRK.js";
4
4
  import { h as startSpan, n as captureMessage } from "./sentry-CPbZjomA.js";
5
- import { t as JUNIOR_VERSION } from "./version-Bhe7RPIe.js";
6
- import { Cn as isEmptyUserInputAnswer, Fn as automationTaskText, Ht as MAX_ATTACHMENT_BYTES, Kt as readMessageAttachments, Nt as conversationTreeStateSchema, Q as conversationReportStatusSchema, bn as answeredChoices, bt as instructionProvenanceFor, ct as KNOWN_CONVERSATION_EVENT_TYPES, et as conversationSurfaceSchema, i as isVisionImageMediaType, nt as activityPreviewText, r as detectImageMediaType, un as OPEN_TODO_STATUSES, vt as contextProvenance, wn as normalizeUserInputAnswer } from "./media-Cr9pGkzr.js";
7
- import { $i as persistWithRetry, $r as saveTurnCheckpoint, Cr as latestConversationMessageSeq, D as notInheritedByForkChild, Dr as trimConversationMessages, Ei as loadTurnStart, Er as recordDeliveredAssistantMessage, Ft as renderTaskInput, Gt as pushInboxSnoozeWakes, H as resolveEventAuthor, Ii as finalizeFailedTurnReplyWithEvent, In as isExperimentalFeatureEnabled, L as eventAuthorText, Li as getAgentTurnDiagnosticsAttributes, Mi as buildTurnErrorResponse, Mn as buildDeterministicTurnId, Nn as conversationSubtree, Nr as isEventConversationMessage, Nt as withoutSavedSteeringMessages, Or as turnHasReply, Ot as buildSteeringPiMessage, Pn as conversationSubtreeColumns, Q as getTurnUserMessage, Qn as commitMessages, Qr as pauseLostWorkerTurn, Qt as cancelHumanFacingPendingMessages, Ri as requireTurnFailureEventId, Rr as createPluginEgress, Sr as isHumanConversationMessage, St as getWebAuthorization, Ti as getTurnLifecycle, Tr as normalizeConversationText, Tt as savedInputInstruction, Ur as AuthorizationFlowDisabledError, Ut as setTodoStatusByUser, W as resolveBotSlackTeamId, Xr as loadTurnCheckpoint, Xt as appendAndEnqueueInboundMessage, Zn as commitAcceptedReply, Zr as lostWorkerBeforeFirstSave, _r as resolveConversationTitle, _t as persistThreadRuntimeState, a as resolveMailboxTurnWork, aa as configValueSchema, ai as recordTurnSummary, at as TurnInputDeferredError, bi as canShareTurn, br as estimateConversationMessagesTokens, c as legacyWebMailboxMetadataSchema, ct as isTurnInputCommitLostError, dn as getConversationWorkState, dr as recordSubscribedReplyRoute, dt as markTurnCompleted, ei as abandonTurnRecord, er as loadConversationProjection, et as getTurnUserReplyAttachmentContext, ft as markTurnFailed, gr as persistConversationMessages, gt as getPersistedThreadState, hr as persistConversationMessageWindow, ht as getPersistedSandboxState, ii as listTurnSummaries, it as TurnInputCommitLostError, jn as buildDeterministicAssistantMessageId, jr as EVENT_SYSTEM_ACTOR, kr as upsertConversationMessage, kt as instructionActorFor, lt as isTurnInputDeferredError, mr as hydrateConversationMessages, mt as getLocationConfigurationService, ni as failTurnRecord, nr as loadTurnProjection, nt as ConversationTurnBoundaryError, or as recordAuthorizationCompleted, ot as getConversationTurnBoundaryError, pt as startActiveTurn, q as resumeForPersonInput, qr as clearPendingAuth, ri as getTurnRecord, rt as CooperativeTurnYieldError, st as isCooperativeTurnYieldError, ta as piMessageFromHistoryItem, ti as completeTurnRecord, tt as getTurnUserSlackMessageTs, un as getConversation, ut as markTurnClosed, vt as persistThreadStateById, wr as markConversationMessage, wt as loadInboxItemInput, xr as getConversationMessageSlackTs, yi as canJoinTurn, yr as buildConversationContext, yt as coerceThreadConversationState, zr as PluginCredentialFailureError } from "./mailbox-turn-79Nv1JXv.js";
8
- import { o as ingestEvent } from "./job-runner-CySgpi9v.js";
9
- import { $t as addHistoryWarmupCost, At as resolveSlackChannelIdFromMessage, B as ANSWER_TOOL_ENDINGS, C as resolveSlackReplyTarget, Ct as jsonResponse, Dt as parseSlackMessageReference, Et as renderBlockText, Ft as takeViewerAutomationAlertStep, G as isConversationWorkDone, H as GLOBAL_GAPS_MAX, Jt as missingAutomationSkillReason, K as listConversationWork, Kt as AutomationEditError, L as RetryableDeliveryError, Lt as ViewerTaskNotFoundError, O as canPauseConversationDelivery, Ot as parseSlackThreadId, Qt as addHistoryPeriod, Tt as renderAttachmentText, U as GLOBAL_GAPS_TTL_MS, V as CONVERSATION_STATE_TTL_MS, W as segmentGapsKey, Yt as effectiveTaskOutcomes, a as getMcpOAuthCallbackPath, cn as connectedState, dn as MINUTE_MS, dt as archiveConversation, en as firstLiveSavingsDate, ft as conversationReadPositionQuery, hn as resolveConversationConfiguration, ht as deliverInboxItemChange, it as stopChildAgentsOf, kt as readSlackRawMessageContext, l as latestProgressStatus, ln as providerCacheTtlMs, mn as gapSegment, n as executeAgentRun, nn as replaceHistorySavings, o as createClientMetadata, p as createInboxItemShow, pn as NO_REPLY_GAP_MS, pt as markConversationRead, qt as findAutomationSkill, r as buildAuthPauseResponse, s as readMcpClientInformation, t as createAgentRunner, tn as historyPeriodSavings, u as resolveDestinationVisibility, ut as readLastUserMessageAtByConversation, w as sendSlackReply, wt as throwApiError, x as safeLinkUrl, xt as setConversationSubscription, yt as inviteMentionedPeople, z as shouldEmitDevAgentTrace, zt as readConversationSourceTask } from "./agent-runner-C7GNLRB6.js";
10
- import { p as getAssistantReplyText } from "./system-prompt-table-CDCYVwqN.js";
11
- import { D as readSpace, P as storeAttachment, _ as AttachmentUploadError, b as verifyAttachmentUploads, f as createAndEnqueueConversation, h as webActorFromUser, i as savedTurnMessages, j as isFileAttachment, l as acceptsWebMessages, m as recordWebConversationActivity, n as resolveTurnResumeRouting, p as createConversationId, t as resolveConversationRouting, u as appendAndEnqueueWebMessage } from "./turn-session-routing-GtetHsdO.js";
12
- import { a as getChannelMessage, c as isPublicSlackChannel, d as listThreadReplies, o as getConversationInfo, s as isConversationMember, t as runWithSlackInstallation } from "./adapter-context-BlSGE44V.js";
13
- import { a as readAttachmentVisionSummary, c as slackAttachmentsVersionQuery, r as getSlackFileId, s as recordSlackAttachment } from "./start-conversation-Uh8Sk1EF.js";
14
- import { i as getChildAgentLabel } from "./parent-result-Dg6P6roR.js";
15
- import { t as webMessageId } from "./web-message-id-C6P83ans.js";
16
- import { C as cancelConversationPendingMessagesResponseSchema, E as conversationPendingMessageDeliverySchema, G as personObjectCard, K as webPageObjectCard, M as healthReportSchema, S as cancelConversationPendingMessagesBodySchema, U as conversationObjectCard, W as messageObjectCard, b as archiveDoneConversationsResponseSchema, c as setConversationSpaceBodySchema, f as renameConversationBodySchema, h as pinConversationResponseSchema, l as setConversationSpaceResponseSchema, m as pinConversationBodySchema, o as conversationSubscriptionBodySchema, p as renameConversationResponseSchema, r as stopConversationTurnResponseSchema, s as conversationSubscriptionResponseSchema, v as archiveConversationBodySchema, x as conversationAutoArchiveSchema, y as archiveConversationResponseSchema } from "./conversation-feed-Sl8lKKmR.js";
17
- import { a as stopConversation, c as executeTurn, d as withTurnSpan, i as stopAtAutomatedTurnLimit, l as getTurnInputSpanAttributes, n as createConversationTurnWorker, o as recordFinishedTurnForAutomatedLimit, r as supersedeTurnForInput, s as AgentRunError, u as turnInputTelemetry } from "./conversation-turn-BoLK9i6g.js";
18
- import { n as attachmentFactLines, r as buildStoredAttachmentPromptText } from "./model-input-IRGa98V7.js";
19
- import { s as withAgentInvocationResultActors, t as createChildConversationWorker } from "./result-DfATzX77.js";
20
- import { t as bindMessageAgent } from "./message-BTox2Cmb.js";
21
- import { t as readConversationLineage } from "./lineage-tRTOcrsL.js";
22
- import { t as bindSpawnAgent } from "./spawn-CfvlFdfz.js";
23
- import { a as buildDeliveredTurnStatePatch, i as persistAuthPauseTurnState, n as loadThreadContextTrimFloor, o as loadPendingMessageCards, r as completeAuthPauseTurn, t as buildTurnThreadContext } from "./thread-context-DF5uDcWN.js";
24
- import { d as readConversationEventPageAround, l as readConversationEventPage, n as scheduleSessionCompletedPluginTasks, u as readConversationEventPageAfter } from "./task-runner-DcdQJd9e.js";
25
- import { n as getPausedTurnRequest, o as getTurnAuthorization, r as recordFailedDispatchTurn, t as createPausedTurns } from "./turn-wake-um5Ubd4m.js";
26
- import { r as canContinueInSlack } from "./continue-in-slack-BGKjIdFp.js";
5
+ import { t as JUNIOR_VERSION } from "./version-BeZhWWBE.js";
6
+ import { L as mapBounded, M as trimTrailingAssistantMessages, h as createPluginLogger } from "./prompt-Dv7gkpD6.js";
7
+ import { $ as activityPreviewText, Fn as automationTaskText, Kt as MAX_ATTACHMENT_BYTES, Lt as conversationTreeStateSchema, St as contextProvenance, Xt as readMessageAttachments, Y as conversationReportStatusSchema, Z as conversationSurfaceSchema, at as KNOWN_CONVERSATION_EVENT_TYPES, bn as normalizeUserInputAnswer, fn as inboxItemQuestion, gn as answeredChoices, t as OPEN_TODO_STATUSES, wt as instructionProvenanceFor, yn as isEmptyUserInputAnswer, yt as piMessageFromHistoryItem } from "./types-C4iC-IMC.js";
8
+ import { n as webMessageId } from "./agent-status-BA5x3Xtp.js";
9
+ import { $ as getTurnUserSlackMessageTs, An as recordSubscribedReplyRoute, B as resolveEventAuthor, Bn as getConversationMessageSlackTs, Br as requireTurnFailureEventId, Cr as listTurnSummaries, Ct as savedInputInstruction, D as notInheritedByForkChild, Dr as loadTurnStart, Dt as instructionActorFor, Er as getTurnLifecycle, Et as buildSteeringPiMessage, F as eventAuthorText, Fn as persistConversationMessages, G as resumeForPersonInput, Gn as recordDeliveredAssistantMessage, H as resolveBotSlackTeamId, Hn as latestConversationMessageSeq, In as resolveConversationTitle, Jn as upsertConversationMessage, Kn as trimConversationMessages, Lt as buildDeterministicAssistantMessageId, Nn as hydrateConversationMessages, Nt as renderTaskInput, Pn as persistConversationMessageWindow, Pr as buildTurnErrorResponse, Q as getTurnUserReplyAttachmentContext, Qn as isEventConversationMessage, Rn as buildConversationContext, Rr as finalizeFailedTurnReplyWithEvent, Rt as buildDeterministicTurnId, Sr as getTurnRecord, St as loadInboxItemInput, Tn as recordAuthorizationCompleted, Un as markConversationMessage, Vn as isHumanConversationMessage, Wn as normalizeConversationText, X as getTurnUserMessage, Xn as EVENT_SYSTEM_ACTOR, _n as commitMessages, _r as pauseLostWorkerTurn, _t as coerceThreadConversationState, at as isCooperativeTurnYieldError, br as completeTurnRecord, bt as getWebAuthorization, c as legacyWebMailboxMetadataSchema, cr as AuthorizationFlowDisabledError, ct as markTurnClosed, dt as startActiveTurn, et as ConversationTurnBoundaryError, fr as clearPendingAuth, ft as getLocationConfigurationService, gn as commitAcceptedReply, gr as lostWorkerBeforeFirstSave, gt as persistThreadStateById, hr as loadTurnCheckpoint, ht as persistThreadRuntimeState, ir as PluginCredentialFailureError, it as getConversationTurnBoundaryError, jt as withoutSavedSteeringMessages, li as configValueSchema, lt as markTurnCompleted, mt as getPersistedThreadState, nt as TurnInputCommitLostError, ot as isTurnInputCommitLostError, pt as getPersistedSandboxState, qn as turnHasReply, rr as createPluginEgress, rt as TurnInputDeferredError, st as isTurnInputDeferredError, ti as persistWithRetry, tn as isExperimentalFeatureEnabled, tt as CooperativeTurnYieldError, ut as markTurnFailed, vr as saveTurnCheckpoint, wr as recordTurnSummary, xn as loadTurnProjection, xr as failTurnRecord, yn as loadConversationProjection, yr as abandonTurnRecord, zn as estimateConversationMessagesTokens, zr as getAgentTurnDiagnosticsAttributes } from "./mailbox-turn-uSXhUFc9.js";
10
+ import { o as ingestEvent } from "./job-runner-A1lCkybD.js";
11
+ import { $ as requireSpaceForWork, $t as AutomationEditError, At as parseSlackThreadId, B as archiveConversation, C as CONVERSATION_STATE_TTL_MS, Ct as setConversationSubscription, D as isConversationWorkDone, Dt as renderAttachmentText, E as segmentGapsKey, Et as throwApiError, Ht as takeViewerAutomationAlertStep, It as createPluginConversationWatches, J as stopChildAgentsOf, K as stopConversation, Kt as readConversationSourceTask, Mt as resolveSlackChannelIdFromMessage, O as listConversationWork, Ot as renderBlockText, S as ANSWER_TOOL_ENDINGS, Sn as resolveConversationConfiguration, St as leaveConversation, T as GLOBAL_GAPS_TTL_MS, Tt as jsonResponse, U as conversationReadPositionQuery, W as markConversationRead, Wt as ViewerTaskNotFoundError, Y as deliverInboxItemChange, a as getMcpOAuthCallbackPath, an as addHistoryPeriod, bn as NO_REPLY_GAP_MS, bt as setConversationTitle, cn as historyPeriodSavings, ct as acceptsWebMessages, dt as createAndEnqueueConversation, en as findAutomationSkill, et as setConversationSpaceForViewer, ft as createConversationId, gn as providerCacheTtlMs, hn as connectedState, ht as AttachmentUploadError, jt as readSlackRawMessageContext, kt as parseSlackMessageReference, l as latestProgressStatus, ln as replaceHistorySavings, lt as appendAndEnqueueWebMessage, mt as webActorFromUser, n as executeAgentRun, nn as effectiveTaskOutcomes, nt as getSpaceLead, o as createClientMetadata, on as addHistoryWarmupCost, pt as recordWebConversationActivity, r as buildAuthPauseResponse, s as readMcpClientInformation, sn as firstLiveSavingsDate, t as createAgentRunner, tn as missingAutomationSkillReason, tt as readSpaceRefs, u as resolveDestinationVisibility, vn as MINUTE_MS, vt as verifyAttachmentUploads, w as GLOBAL_GAPS_MAX, x as shouldEmitDevAgentTrace, xn as gapSegment, y as RetryableDeliveryError, z as readLastUserMessageAtByConversation } from "./agent-runner-AjrEV6Qe.js";
12
+ import { N as webActorUserIds, T as getMcpStoredOAuthCredentials, _ as McpAuthorizationRequiredError, v as PluginMcpClient } from "./registry-iXMT5Jmh.js";
13
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-DfSpJZdY.js";
14
+ import { A as createUserTokenStore } from "./profile-BQ-iBDsZ.js";
15
+ import { h as getAssistantReplyText } from "./system-prompt-table-CiXy0eNR.js";
16
+ import { o as detectImageMediaType, s as isVisionImageMediaType } from "./user-customization-CvfuY9Eo.js";
17
+ import { a as readAttachmentVisionSummary, c as slackAttachmentsVersionQuery, m as storeAttachment, n as savedTurnMessages, r as getSlackFileId, s as recordSlackAttachment, u as isFileAttachment } from "./turn-membership-CENFf3kI.js";
18
+ import { a as isConversationMember, i as getConversationInfo, l as listThreadReplies, o as isPublicSlackChannel, r as getChannelMessage } from "./channel-access-j-YAVYK4.js";
19
+ import { C as cancelConversationPendingMessagesBodySchema, D as conversationPendingMessageDeliverySchema, G as messageObjectCard, K as personObjectCard, N as healthReportSchema, S as conversationAutoArchiveSchema, W as conversationObjectCard, b as archiveConversationResponseSchema, c as conversationSubscriptionResponseSchema, g as pinConversationResponseSchema, h as pinConversationBodySchema, l as setConversationSpaceBodySchema, m as renameConversationResponseSchema, o as conversationLeaveResponseSchema, p as renameConversationBodySchema, q as webPageObjectCard, r as stopConversationTurnResponseSchema, s as conversationSubscriptionBodySchema, u as setConversationSpaceResponseSchema, w as cancelConversationPendingMessagesResponseSchema, x as archiveDoneConversationsResponseSchema, y as archiveConversationBodySchema } from "./conversation-feed--9S0_PXL.js";
20
+ import { a as recordFinishedTurnForAutomatedLimit, c as getTurnInputSpanAttributes, i as stopAtAutomatedTurnLimit, l as turnInputTelemetry, n as createConversationTurnWorker, o as AgentRunError, r as supersedeTurnForInput, s as executeTurn, u as withTurnSpan } from "./conversation-turn-BUE_7xaN.js";
21
+ import { n as attachmentFactLines, r as buildStoredAttachmentPromptText } from "./model-input-BReSnwHp.js";
22
+ import { a as getChildAgentLabel } from "./result-Bta_dlWa.js";
23
+ import { t as bindMessageAgent } from "./message-BNenhsmB.js";
24
+ import { t as readConversationLineage } from "./lineage-Bktb0UcV.js";
25
+ import { t as bindSpawnAgent } from "./spawn-frczVPIr.js";
26
+ import { a as buildDeliveredTurnStatePatch, i as persistAuthPauseTurnState, n as loadThreadContextTrimFloor, o as loadPendingMessageCards, r as completeAuthPauseTurn, t as buildTurnThreadContext } from "./thread-context-CqZDKErp.js";
27
+ import { c as readConversationEventPageAround, n as scheduleSessionCompletedPluginTasks, o as readConversationEventPage, s as readConversationEventPageAfter } from "./task-runner-C9Yc2_ae.js";
28
+ import { a as createAgentDispatchConversationWorker, i as buildDispatchRoutingContext, o as enqueueAgentDispatch, s as failStoppedDispatch, t as runConversation } from "./run-conversation-DL6ru7iW.js";
29
+ import { n as getPausedTurnRequest, o as getTurnAuthorization, r as recordFailedDispatchTurn, t as createPausedTurns } from "./turn-wake-BhloiI2h.js";
30
+ import { r as canContinueInSlack } from "./continue-in-slack-D-FZ8Fin.js";
27
31
  import * as z from "zod";
28
- import pLimit from "p-limit";
29
32
  import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
30
33
  import { EVENT_SUMMARY_MAX_LENGTH, EVENT_TEXT_MAX_LENGTH, conversationSidebarAnnotationSchema, createSlackSource, dispatchOptionsSchema, encodeObjectImageRef, escapeTagText, escapeTagTextAndQuotes, eventMatches, eventSchema, isSlackDestination, objectAnnotationSchema, objectLinkFilterMatches, objectLinkFilterSpecificity, objectTypeSchema, ownedObjectAnnotationSchema, renderEmptyTag, renderTag } from "@sentry/junior-plugin-api";
31
- import { and, asc, count, desc, eq, exists, gt, gte, inArray, isNotNull, isNull, like, lt, lte, min, ne, not, or, sql } from "drizzle-orm";
34
+ import { and, asc, count, desc, eq, gt, gte, inArray, isNotNull, isNull, lt, lte, min, ne, not, or, sql } from "drizzle-orm";
32
35
  import { alias } from "drizzle-orm/pg-core";
36
+ import pLimit from "p-limit";
37
+ import { performance } from "node:perf_hooks";
33
38
  import { Message, ThreadImpl, stringifyMarkdown } from "chat";
34
39
  import net from "node:net";
35
- import { performance } from "node:perf_hooks";
36
40
  import https from "node:https";
37
41
  import { SlackFormatConverter, createSlackAdapter } from "@chat-adapter/slack";
38
42
  import dns from "node:dns";
@@ -61,7 +65,7 @@ const imageIdPayloadSchema = z.object({
61
65
  source: z.string().min(1)
62
66
  }).strict();
63
67
  function signature$1(payload) {
64
- const secret = readJuniorSecret();
68
+ const secret = getChatConfig().secrets.juniorSecret;
65
69
  if (!secret) throw new Error("Cannot sign image ids without JUNIOR_SECRET");
66
70
  return createHmac("sha256", secret).update(`${IMAGE_ID_CONTEXT}:${payload}`).digest("base64url");
67
71
  }
@@ -99,7 +103,7 @@ function imagePath(image, width, version) {
99
103
  // src/chat/mcp/viewer.ts
100
104
  function viewerAuthProvider(plugin, userId) {
101
105
  const provider = plugin.manifest.name;
102
- const baseUrl = resolveBaseUrl();
106
+ const baseUrl = getChatConfig().deployment.baseUrl;
103
107
  if (!baseUrl) throw new Error("Cannot determine base URL (set JUNIOR_BASE_URL or deploy to Vercel)");
104
108
  const callbackUrl = `${baseUrl}${getMcpOAuthCallbackPath(provider)}`;
105
109
  return {
@@ -578,7 +582,8 @@ const conversationRecordColumns = () => ({
578
582
  identityProvider: juniorIdentities.provider,
579
583
  identitySubjectId: juniorIdentities.providerSubjectId,
580
584
  identityTenantId: juniorIdentities.providerTenantId,
581
- userDisplayName: juniorUsers.displayName
585
+ userDisplayName: juniorUsers.displayName,
586
+ spaceId: rootSpaceIdSql(juniorConversations)
582
587
  });
583
588
  /** Left-join conditions from a Conversation to its record tables. */
584
589
  const conversationRecordJoins = {
@@ -621,7 +626,7 @@ function conversationFromRecordRow(row) {
621
626
  ...value.executionUpdatedAt ? { updatedAtMs: value.executionUpdatedAt.getTime() } : void 0
622
627
  },
623
628
  ...value.parentConversationId ? { parentConversationId: value.parentConversationId } : void 0,
624
- ...value.spaceId ? { spaceId: value.spaceId } : void 0,
629
+ ...row.spaceId ? { spaceId: row.spaceId } : void 0,
625
630
  ...value.archivedAt ? { archivedAtMs: value.archivedAt.getTime() } : void 0,
626
631
  ...actor ? { actor } : void 0,
627
632
  ...location ? { location } : void 0,
@@ -4059,6 +4064,7 @@ function createSlackTurn(deps) {
4059
4064
  } : void 0,
4060
4065
  credentialContext,
4061
4066
  actor: executionActor,
4067
+ ...!options.execution && message.author.isBot === true ? { actorIsApp: true } : void 0,
4062
4068
  slackConversation,
4063
4069
  source,
4064
4070
  ...location ? { location } : void 0,
@@ -4599,297 +4605,6 @@ function createPrepareTurnState(deps) {
4599
4605
  };
4600
4606
  };
4601
4607
  }
4602
- // src/chat/agent-dispatch/work.ts
4603
- const agentDispatchMailboxMetadataSchema = z.object({
4604
- dispatchId: z.string().min(1),
4605
- kind: z.literal("agent_dispatch")
4606
- }).strict();
4607
- const AGENT_DISPATCH_MAX_AGE_MS = 864e5;
4608
- /** Return whether a dispatch is a Scheduled or Event automation run. */
4609
- function isAutomationRun(dispatch) {
4610
- return dispatch.source.kind === "scheduled_automation" || dispatch.source.kind === "event_automation";
4611
- }
4612
- /** Restore the exact actor, credential, and dispatch routing for every slice. */
4613
- function buildDispatchRoutingContext(dispatch) {
4614
- return {
4615
- actor: dispatch.actor,
4616
- credentialContext: credentialContextForActor(dispatch.actor, dispatch.credentialSubject),
4617
- dispatch: {
4618
- actor: dispatch.actor,
4619
- id: dispatch.id,
4620
- metadata: dispatch.metadata,
4621
- plugin: dispatch.plugin,
4622
- replyAttribution: dispatch.replyAttribution,
4623
- outcomes: dispatch.outcomes,
4624
- ...dispatch.skill ? { skill: dispatch.skill } : void 0,
4625
- ...isAutomationRun(dispatch) ? { declaresResult: true } : void 0
4626
- },
4627
- surface: "api"
4628
- };
4629
- }
4630
- /** Build the stable mailbox work item for one agent dispatch. */
4631
- function buildAgentDispatchInboundMessage(dispatch, nowMs = Date.now(), authorIdentityId) {
4632
- return {
4633
- conversationId: getDispatchConversationId(dispatch),
4634
- createdAtMs: dispatch.createdAtMs,
4635
- delivery: "defer",
4636
- destination: dispatch.destination,
4637
- inboundMessageId: getDispatchInputMessageId(dispatch.id),
4638
- input: {
4639
- text: "[plugin dispatch]",
4640
- ...authorIdentityId ? { authorIdentityId } : void 0,
4641
- metadata: {
4642
- dispatchId: dispatch.id,
4643
- kind: "agent_dispatch"
4644
- }
4645
- },
4646
- receivedAtMs: nowMs,
4647
- source: "plugin"
4648
- };
4649
- }
4650
- /** Persist dispatch mailbox work before sending its conversation wake-up. */
4651
- async function enqueueAgentDispatch(dispatch, options) {
4652
- const nowMs = options.nowMs ?? Date.now();
4653
- const claimedDispatch = await claimDispatchMailboxAppend(dispatch.id);
4654
- if (!claimedDispatch) return;
4655
- const conversationStore = options.conversationStore ?? getConversationStore();
4656
- const conversationId = getDispatchConversationId(claimedDispatch);
4657
- const destination = claimedDispatch.destination;
4658
- await conversationStore.recordActivity({
4659
- activityAtMs: claimedDispatch.createdAtMs,
4660
- conversationId,
4661
- destination,
4662
- kind: isAutomationRun(claimedDispatch) ? "automation" : "root",
4663
- nowMs,
4664
- source: "plugin",
4665
- sessionSource: claimedDispatch.source,
4666
- ...claimedDispatch.title ? { title: claimedDispatch.title } : void 0
4667
- });
4668
- if (destination.platform === "slack" && destination.threadTs) await conversationStore.claimProviderConversation({
4669
- atMs: nowMs,
4670
- conversationId,
4671
- provider: "slack",
4672
- providerDestinationId: destination.channelId,
4673
- providerTenantId: destination.teamId,
4674
- providerConversationId: destination.threadTs
4675
- });
4676
- await appendAndEnqueueInboundMessage({
4677
- message: buildAgentDispatchInboundMessage(claimedDispatch, nowMs, await resolveActorIdentityId(getSqlExecutor(), claimedDispatch.actor)),
4678
- conversationStore: options.conversationStore,
4679
- nowMs,
4680
- queue: options.queue,
4681
- state: options.state
4682
- });
4683
- await confirmDispatchMailboxAppend(claimedDispatch.id);
4684
- }
4685
- /** Parse dispatch routing metadata from a durable mailbox message. */
4686
- function dispatchIdFromMessages(messages) {
4687
- if (messages.length === 0) return;
4688
- const parsed = messages.map((message) => agentDispatchMailboxMetadataSchema.safeParse(message.input.metadata));
4689
- if (parsed.every((result) => !result.success)) return;
4690
- if (parsed.some((result) => !result.success)) throw new Error("Conversation mailbox mixes dispatch and provider input");
4691
- const ids = new Set(parsed.map((result) => {
4692
- if (!result.success) throw new Error("Dispatch mailbox metadata failed validation");
4693
- return result.data.dispatchId;
4694
- }));
4695
- if (ids.size !== 1) throw new Error("Conversation mailbox contains multiple dispatches");
4696
- return ids.values().next().value;
4697
- }
4698
- /**
4699
- * Resolve a dispatch from concrete mailbox metadata or the active turn.
4700
- *
4701
- * Provider source and conversation-id conventions are deliberately not
4702
- * execution routing authority.
4703
- */
4704
- async function resolveAgentDispatchId(context) {
4705
- const mailboxDispatchId = dispatchIdFromMessages(context.attempt.messages);
4706
- if (mailboxDispatchId) return mailboxDispatchId;
4707
- if (context.attempt.messages.length > 0) return;
4708
- const summaries = await listTurnSummaries(context.conversationId);
4709
- const activeDispatchIds = new Set(summaries.filter((summary) => (summary.state === "paused" || summary.state === "running") && Boolean(summary.dispatchId)).map((summary) => summary.dispatchId).filter((id) => Boolean(id)));
4710
- if (activeDispatchIds.size > 1) throw new Error(`Conversation ${context.conversationId} has multiple active dispatches`);
4711
- const activeDispatchId = activeDispatchIds.values().next().value;
4712
- if (activeDispatchId) return activeDispatchId;
4713
- const durableDispatchIds = new Set(summaries.map((summary) => summary.dispatchId).filter((id) => Boolean(id)));
4714
- if (durableDispatchIds.size > 1) throw new Error(`Conversation ${context.conversationId} has multiple dispatch sessions`);
4715
- const durableDispatchId = durableDispatchIds.values().next().value;
4716
- if (!durableDispatchId) return;
4717
- const dispatch = await getDispatchRecord(durableDispatchId);
4718
- return dispatch && !isTerminalDispatchStatus(dispatch.status) ? durableDispatchId : void 0;
4719
- }
4720
- async function readDispatchTurnResult(dispatch) {
4721
- const conversationId = getDispatchConversationId(dispatch);
4722
- const turnId = getDispatchTurnId(dispatch.id);
4723
- const storedSession = await getTurnRecord(conversationId, turnId);
4724
- const summary = (await listTurnSummaries(conversationId)).find((candidate) => candidate.turnId === turnId);
4725
- const session = storedSession ?? summary;
4726
- const dispatchOutcome = summary?.dispatchOutcome ?? storedSession?.dispatchOutcome;
4727
- const resultMessageTs = summary?.resultMessageId ?? storedSession?.resultMessageId;
4728
- const errorMessage = storedSession?.errorMessage;
4729
- if (dispatchOutcome) return {
4730
- ...errorMessage ? { errorMessage } : void 0,
4731
- outcome: dispatchOutcome,
4732
- ...resultMessageTs ? { resultMessageTs } : void 0
4733
- };
4734
- if (resultMessageTs) return {
4735
- outcome: "completed",
4736
- resultMessageTs
4737
- };
4738
- if (!session) return { outcome: "not_started" };
4739
- switch (session.state) {
4740
- case "paused": return { outcome: "awaiting_resume" };
4741
- case "running": return { outcome: "still_running" };
4742
- case "completed": return { outcome: "completed" };
4743
- case "abandoned":
4744
- case "failed": return {
4745
- ...errorMessage ? { errorMessage } : void 0,
4746
- outcome: "retryable"
4747
- };
4748
- }
4749
- }
4750
- async function projectDispatchTurnResult(dispatchId, result) {
4751
- switch (result.outcome) {
4752
- case "awaiting_resume":
4753
- await markDispatchAwaitingResume(dispatchId);
4754
- break;
4755
- case "blocked":
4756
- await markDispatchBlocked(dispatchId, result.errorMessage ?? "Dispatch requires authorization that is unavailable for background work", result.resultMessageTs);
4757
- break;
4758
- case "failed":
4759
- await markDispatchFailed(dispatchId, result.errorMessage ?? "Agent turn failed", result.resultMessageTs);
4760
- break;
4761
- case "completed":
4762
- await markDispatchCompleted(dispatchId, result.resultMessageTs);
4763
- break;
4764
- case "not_started": await markDispatchFailed(dispatchId, "Dispatch turn record is missing");
4765
- }
4766
- }
4767
- function getDispatchBlockingError(error) {
4768
- const cause = getConversationTurnBoundaryError(error)?.cause ?? error;
4769
- return cause instanceof AuthorizationFlowDisabledError || cause instanceof PluginCredentialFailureError ? cause : void 0;
4770
- }
4771
- function missingAuthorizationReason(dispatch, provider) {
4772
- return dispatch.credentialSubject ? `This run needs a connected ${provider} account.` : `This run uses system credentials, which have no ${provider} access. Switch it to creator credentials and connect a ${provider} account.`;
4773
- }
4774
- async function persistBlockedDispatchTurn(dispatch, error) {
4775
- const conversationId = getDispatchConversationId(dispatch);
4776
- const sessionId = getDispatchTurnId(dispatch.id);
4777
- const session = await getTurnRecord(conversationId, sessionId);
4778
- await recordTurnSummary({
4779
- actor: dispatch.actor,
4780
- conversationId,
4781
- destination: dispatch.destination,
4782
- dispatchId: dispatch.id,
4783
- dispatchOutcome: "blocked",
4784
- turnId: sessionId,
4785
- sliceId: session?.sliceId ?? 1,
4786
- source: dispatch.source,
4787
- state: "failed",
4788
- surface: "api"
4789
- });
4790
- await markDispatchBlocked(dispatch.id, error instanceof AuthorizationFlowDisabledError ? missingAuthorizationReason(dispatch, error.provider) : error.message);
4791
- }
4792
- /** Run one dispatch start or resume under the owning conversation lease. */
4793
- function createAgentDispatchConversationWorker(options) {
4794
- return async (context, dispatchId) => {
4795
- const dispatch = await getDispatchRecord(dispatchId);
4796
- if (!dispatch) throw new Error(`Dispatch record is missing for ${dispatchId}`);
4797
- const expectedConversationId = getDispatchConversationId(dispatch);
4798
- if (context.conversationId !== expectedConversationId) throw new Error(`Dispatch ${dispatch.id} belongs to ${expectedConversationId}, not ${context.conversationId}`);
4799
- if (!context.destination || context.destination.platform !== dispatch.destination.platform || context.destination.teamId !== dispatch.destination.teamId || context.destination.channelId !== dispatch.destination.channelId) throw new Error(`Dispatch ${dispatch.id} destination does not match its conversation lease`);
4800
- let acknowledged = context.attempt.messages.length === 0;
4801
- const acknowledge = async () => {
4802
- if (acknowledged) return;
4803
- try {
4804
- await context.attempt.ack();
4805
- } catch {
4806
- throw new TurnInputCommitLostError(`Conversation work lease lost before dispatch inbox ack for ${context.conversationId}`);
4807
- }
4808
- acknowledged = true;
4809
- };
4810
- if (isTerminalDispatchStatus(dispatch.status)) {
4811
- await acknowledge();
4812
- return { status: "completed" };
4813
- }
4814
- const durableResult = await readDispatchTurnResult(dispatch);
4815
- if (durableResult.outcome === "blocked" || durableResult.outcome === "completed" || durableResult.outcome === "failed") {
4816
- await projectDispatchTurnResult(dispatch.id, durableResult);
4817
- await acknowledge();
4818
- return { status: "completed" };
4819
- }
4820
- if (Date.now() - dispatch.createdAtMs > 864e5) {
4821
- await markDispatchFailed(dispatch.id, "Dispatch exceeded its maximum processing age");
4822
- await acknowledge();
4823
- return { status: "completed" };
4824
- }
4825
- const runningDispatch = await markDispatchRunning(dispatch.id);
4826
- if (!runningDispatch) throw new Error(`Dispatch record disappeared for ${dispatch.id}`);
4827
- if (isTerminalDispatchStatus(runningDispatch.status)) {
4828
- await acknowledge();
4829
- return { status: "completed" };
4830
- }
4831
- try {
4832
- const resumesDurableTurn = durableResult.outcome === "awaiting_resume" || durableResult.outcome === "still_running";
4833
- if (resumesDurableTurn && context.attempt.messages.length > 0) await acknowledge();
4834
- let result;
4835
- if (resumesDurableTurn) {
4836
- await options.resumeTurn(dispatch, {
4837
- shouldYield: context.shouldYield,
4838
- checkIn: context.checkIn
4839
- });
4840
- result = await readDispatchTurnResult(dispatch);
4841
- } else result = await options.runTurn(dispatch, {
4842
- ack: acknowledge,
4843
- shouldYield: context.shouldYield,
4844
- checkIn: context.checkIn
4845
- }) ?? await readDispatchTurnResult(dispatch);
4846
- if (result.outcome === "still_running") throw new Error(`Dispatch turn ${dispatch.id} is still running after its attempt`);
4847
- if (result.outcome === "retryable") throw new Error(result.errorMessage ?? `Dispatch turn ${dispatch.id} failed`);
4848
- await projectDispatchTurnResult(dispatch.id, result);
4849
- if (!acknowledged) await acknowledge();
4850
- return result.outcome === "awaiting_resume" && context.shouldYield() ? { status: "yielded" } : { status: "completed" };
4851
- } catch (error) {
4852
- if (isCooperativeTurnYieldError(error)) {
4853
- await markDispatchAwaitingResume(dispatch.id);
4854
- return { status: "yielded" };
4855
- }
4856
- if (isTurnInputCommitLostError(error)) {
4857
- logWarn("agent.dispatch.lost_lease", {
4858
- "app.dispatch.id": dispatch.id,
4859
- "error.type": error.name,
4860
- "exception.message": error.message
4861
- });
4862
- return { status: "lost_lease" };
4863
- }
4864
- const blockingError = getDispatchBlockingError(error);
4865
- if (blockingError) {
4866
- await persistBlockedDispatchTurn(dispatch, blockingError);
4867
- await indexEndedTurnEvents({
4868
- conversationId: context.conversationId,
4869
- turnId: getDispatchTurnId(dispatch.id)
4870
- });
4871
- await acknowledge();
4872
- return { status: "completed" };
4873
- }
4874
- if (!context.attempt.isFinalAttempt) throw error;
4875
- await markDispatchFailed(dispatch.id, error instanceof Error ? error.message : "Dispatch turn failed");
4876
- await indexEndedTurnEvents({
4877
- conversationId: context.conversationId,
4878
- turnId: getDispatchTurnId(dispatch.id)
4879
- });
4880
- await acknowledge();
4881
- return { status: "completed" };
4882
- }
4883
- };
4884
- }
4885
- /**
4886
- * Fail the dispatch of stopped Conversation work, so the Automation run that
4887
- * waits on it settles instead of blocking later runs.
4888
- */
4889
- async function failStoppedDispatch(conversationId) {
4890
- const dispatchId = getDispatchIdForConversation(conversationId);
4891
- if (dispatchId) await markDispatchFailed(dispatchId, "Dispatch work stopped after repeated failed attempts.");
4892
- }
4893
4608
  // src/chat/slack/dispatch-turn.ts
4894
4609
  /** Build the Slack provider adapter for agent-dispatched conversation turns. */
4895
4610
  function createSlackDispatchTurnRunner(options) {
@@ -6485,6 +6200,7 @@ async function runPausedTurnInContext(payload, options, runOptions) {
6485
6200
  seqs: activeTurn.piMessageSeqs
6486
6201
  } : await loadConversationProjection({ conversationId: payload.conversationId }),
6487
6202
  actor,
6203
+ ...!dispatchId && !isEventConversationMessage(userMessage) && userMessage.author?.isBot === true ? { actorIsApp: true } : void 0,
6488
6204
  credentialContext,
6489
6205
  destination: routingDestination,
6490
6206
  ...dispatch ? { dispatch } : void 0,
@@ -6826,32 +6542,7 @@ function createConversationWork(options) {
6826
6542
  queue: options.queue,
6827
6543
  state: options.state
6828
6544
  });
6829
- const childWorker = createChildConversationWorker({
6830
- runTurn: conversationTurnWorker,
6831
- state: options.state
6832
- });
6833
- const destinationWorker = async (context) => {
6834
- const destination = context.destination;
6835
- if (!destination) throw new Error(`Conversation ${context.conversationId} is missing a destination`);
6836
- if (destination.platform === "slack") return await slackWorker(context);
6837
- throw new Error(`Conversation ${context.conversationId} has a ${destination.platform} destination but no matching conversation worker`);
6838
- };
6839
- const runRoot = async (context) => {
6840
- const mailboxTurn = await resolveMailboxTurnWork(context);
6841
- if (mailboxTurn) {
6842
- const work = await withAgentInvocationResultActors(mailboxTurn);
6843
- if (!work) {
6844
- await context.attempt.ack();
6845
- return { status: "completed" };
6846
- }
6847
- return await conversationTurnWorker(context, work);
6848
- }
6849
- const dispatchId = await resolveAgentDispatchId(context);
6850
- if (dispatchId) return await dispatchWorker(context, dispatchId);
6851
- return await destinationWorker(context);
6852
- };
6853
- const runByKind = async (context, topLevel) => {
6854
- const worker = topLevel ? runRoot : childWorker;
6545
+ const runWithStopCascade = async (context) => {
6855
6546
  const readStopSignal = context.stopSignal;
6856
6547
  let stopSignal;
6857
6548
  const stopLateChildAgents = async () => {
@@ -6859,9 +6550,14 @@ function createConversationWork(options) {
6859
6550
  };
6860
6551
  let result;
6861
6552
  try {
6862
- result = await worker({
6553
+ result = await runConversation({
6863
6554
  ...context,
6864
6555
  stopSignal: readStopSignal ? () => stopSignal = readStopSignal() : void 0
6556
+ }, {
6557
+ destinations: { slack: slackWorker },
6558
+ runDispatch: dispatchWorker,
6559
+ runTurn: conversationTurnWorker,
6560
+ state: options.state
6865
6561
  });
6866
6562
  } catch (error) {
6867
6563
  await stopLateChildAgents().catch((cascadeError) => {
@@ -6875,8 +6571,8 @@ function createConversationWork(options) {
6875
6571
  const run = async (context) => {
6876
6572
  await resumeForPersonInput(context.conversationId, context.attempt.messages);
6877
6573
  const conversation = await options.conversationStore.get({ conversationId: context.conversationId });
6878
- const topLevel = !conversation || isTopLevel(conversation);
6879
- return await withLogContext({ rootConversationId: conversation?.rootConversationId ?? (topLevel ? context.conversationId : void 0) }, () => runByKind(context, topLevel));
6574
+ const topLevel = !conversation || ownsLocation(conversation);
6575
+ return await withLogContext({ rootConversationId: conversation?.rootConversationId ?? (topLevel ? context.conversationId : void 0) }, () => runWithStopCascade(context));
6880
6576
  };
6881
6577
  return {
6882
6578
  beforeWorkStops: failStoppedDispatch,
@@ -8026,7 +7722,7 @@ async function loadChildAgents(conversationIds) {
8026
7722
  * `timestamp` of the stored assistant message, which Pi sets when it starts
8027
7723
  * the request. That is the closest stored time to the recorder's clock.
8028
7724
  */
8029
- function replayConversation(kind, events, children, nowMs) {
7725
+ function replayConversation(conversation, events, children, nowMs) {
8030
7726
  const periods = [];
8031
7727
  const toolWaits = [];
8032
7728
  const warmupTimes = events.flatMap((event) => event.type === "warmup" ? [Number(event.warmupAtMs)] : []);
@@ -8062,7 +7758,7 @@ function replayConversation(kind, events, children, nowMs) {
8062
7758
  if (event.type === "tool_result" || event.type === "warmup") continue;
8063
7759
  if (event.type === "user_message") {
8064
7760
  if (!inTurn) {
8065
- userActor = event.personInstruction === true && kind !== "task";
7761
+ userActor = event.personInstruction === true && conversation.kind !== "task";
8066
7762
  inTurn = true;
8067
7763
  }
8068
7764
  continue;
@@ -8095,7 +7791,7 @@ function replayConversation(kind, events, children, nowMs) {
8095
7791
  lastCallMs = startedAtMs;
8096
7792
  if (turnEnding) {
8097
7793
  const waitsOnPendingWork = turnBehavior({
8098
- kind,
7794
+ ...conversation,
8099
7795
  personInput: userActor
8100
7796
  }).idleNeedsPendingWork;
8101
7797
  idle = {
@@ -8153,7 +7849,10 @@ async function replayConversations(conversations, args) {
8153
7849
  const events = byConversation(rows);
8154
7850
  const childrenByParent = byConversation(children);
8155
7851
  for (const conversation of batch) {
8156
- const replayed = replayConversation(conversationKindFromRow(conversation), events.get(conversation.conversationId) ?? [], childrenByParent.get(conversation.conversationId) ?? [], nowMs);
7852
+ const replayed = replayConversation({
7853
+ kind: conversationKindFromRow(conversation),
7854
+ hasParent: !isTopLevel({ parentConversationId: conversation.parentConversationId ?? void 0 })
7855
+ }, events.get(conversation.conversationId) ?? [], childrenByParent.get(conversation.conversationId) ?? [], nowMs);
8157
7856
  const inScanWindow = (period) => period.sinceMs >= windowStartMs;
8158
7857
  periods.push(...replayed.periods.filter(inScanWindow));
8159
7858
  toolWaits.push(...replayed.toolWaits.filter(inScanWindow));
@@ -8501,10 +8200,14 @@ const INBOX_SNOOZE_TIMER_INDEX = {
8501
8200
  async function resolvedTodos(db, resolved) {
8502
8201
  if (resolved.length === 0) return [];
8503
8202
  const items = await db.select({
8504
- dedupeKey: juniorInboxItems.dedupeKey,
8505
- id: juniorInboxItems.id
8506
- }).from(juniorInboxItems).where(and(inArray(juniorInboxItems.id, resolved.map((row) => row.inboxItemId)), like(juniorInboxItems.dedupeKey, `${TODO_INBOX_ITEM_KEY_PREFIX}%`)));
8507
- const todoOf = new Map(items.map((item) => [item.id, inboxItemTodo(item)]));
8203
+ id: juniorInboxItems.id,
8204
+ subjectId: juniorInboxItems.subjectId,
8205
+ subjectKind: juniorInboxItems.subjectKind
8206
+ }).from(juniorInboxItems).where(and(inArray(juniorInboxItems.id, resolved.map((row) => row.inboxItemId)), eq(juniorInboxItems.subjectKind, INBOX_SUBJECT_KINDS.todo)));
8207
+ const todoOf = new Map(items.map((item) => [item.id, subjectTodo({
8208
+ id: item.subjectId,
8209
+ kind: item.subjectKind
8210
+ })]));
8508
8211
  return resolved.flatMap((row) => {
8509
8212
  const todo = todoOf.get(row.inboxItemId);
8510
8213
  return todo ? [{
@@ -8517,7 +8220,7 @@ async function resolvedTodos(db, resolved) {
8517
8220
  * Fire the snooze triggers that one Event matches. A `resolve` trigger
8518
8221
  * cancels the snooze and closes the item: it dismisses it, or marks the
8519
8222
  * To-do of a To-do item done for the person who snoozed it, so the agent
8520
- * sees the change in its next `<todo-delta>`. A `wake` trigger ends the
8223
+ * sees the change in its next To-do delta. A `wake` trigger ends the
8521
8224
  * snooze, which records `reason`. When one Event fires both on a snooze,
8522
8225
  * `resolve` wins. A snooze that already ended ignores the Event. Each
8523
8226
  * woken snooze pushes to its User. Returns the number of items woken.
@@ -8760,6 +8463,7 @@ function createHeartbeatContext(args) {
8760
8463
  send: args.sendPluginTask,
8761
8464
  tasks: typeof args.plugin === "string" ? void 0 : args.plugin.tasks
8762
8465
  }),
8466
+ users: createPluginUsers(pluginName),
8763
8467
  log: createPluginLogger(pluginName),
8764
8468
  agent: {
8765
8469
  async dispatch(options) {
@@ -8789,9 +8493,14 @@ function createHeartbeatContext(args) {
8789
8493
  }
8790
8494
  };
8791
8495
  }
8496
+ const EVENT_AUTOMATION_PLUGIN = "junior";
8497
+ /** The dispatch id of an event automation run, which is also its run id. */
8498
+ function eventAutomationDispatchId(idempotencyKey) {
8499
+ return buildDispatchId(EVENT_AUTOMATION_PLUGIN, idempotencyKey);
8500
+ }
8792
8501
  /** Create and enqueue one core-owned event automation dispatch. */
8793
8502
  async function dispatchEventAutomation(args) {
8794
- const plugin = "junior";
8503
+ const plugin = EVENT_AUTOMATION_PLUGIN;
8795
8504
  const { credentialSubject, outcomes, skill, ...unboundOptions } = args.options;
8796
8505
  validateDispatchOptions({ ...unboundOptions });
8797
8506
  const boundSubject = credentialSubject ? bindEventAutomationCredentialSubject({
@@ -8807,7 +8516,7 @@ async function dispatchEventAutomation(args) {
8807
8516
  source: {
8808
8517
  kind: "event_automation",
8809
8518
  automationId: args.automationId,
8810
- automationRunId: buildDispatchId(plugin, unboundOptions.idempotencyKey)
8519
+ automationRunId: eventAutomationDispatchId(unboundOptions.idempotencyKey)
8811
8520
  }
8812
8521
  };
8813
8522
  return await dispatch({
@@ -8852,12 +8561,25 @@ async function getScheduledAutomationDispatch(id) {
8852
8561
  id
8853
8562
  });
8854
8563
  }
8564
+ // src/chat/inbox-items/automation-questions.ts
8565
+ const OPEN_AUTOMATION_QUESTION_LIMIT = 20;
8566
+ /**
8567
+ * List the open questions that the runs of one Automation asked, oldest
8568
+ * first, by item id and title. A later run of the Automation gets them in
8569
+ * its task, so it changes one by its id instead of asking it again.
8570
+ */
8571
+ async function listOpenAutomationQuestions(db, automationId) {
8572
+ return await db.select({
8573
+ id: juniorInboxItems.id,
8574
+ title: juniorQuestions.title
8575
+ }).from(juniorInboxItems).innerJoin(juniorQuestions, itemQuestion).where(and(eq(juniorInboxItems.status, "open"), inboxItemAddedByAutomation(automationId))).orderBy(asc(juniorInboxItems.createdAt), asc(juniorInboxItems.id)).limit(OPEN_AUTOMATION_QUESTION_LIMIT);
8576
+ }
8855
8577
  // src/chat/event-automations/runs.ts
8856
8578
  /**
8857
- * Record a dispatched event automation run with the Automation version it ran,
8858
- * and link its Conversation when it exists. The dispatch can finish before
8859
- * this write, so a stored run, or a retry of the same Event, keeps the row it
8860
- * has.
8579
+ * Record an event automation run with the Automation version it runs, before
8580
+ * its dispatch, so the dispatch can link the run's Conversation as soon as it
8581
+ * exists. A retry of the same Event keeps the row it has. A run whose
8582
+ * dispatch is never stored fails when the heartbeat settles it.
8861
8583
  */
8862
8584
  async function recordEventAutomationRunStarted(db, args) {
8863
8585
  const conversationId = getDispatchConversationId({ id: args.dispatchId });
@@ -8871,18 +8593,21 @@ async function recordEventAutomationRunStarted(db, args) {
8871
8593
  status: "running"
8872
8594
  }).onConflictDoNothing({ target: juniorAutomationRuns.id });
8873
8595
  }
8596
+ const MISSING_DISPATCH_GRACE_MS = 3e5;
8874
8597
  /**
8875
8598
  * Settle running event automation runs whose dispatch has ended. A run whose
8876
- * dispatch record is gone fails.
8599
+ * dispatch record is still missing after a short grace fails.
8877
8600
  */
8878
8601
  async function settleEventAutomationRuns(db, nowMs) {
8879
8602
  const runs = await db.select({
8880
8603
  automationId: juniorAutomationRuns.automationId,
8881
- id: juniorAutomationRuns.id
8604
+ id: juniorAutomationRuns.id,
8605
+ startedAtMs: juniorAutomationRuns.startedAtMs
8882
8606
  }).from(juniorAutomationRuns).innerJoin(juniorAutomations, eq(juniorAutomations.id, juniorAutomationRuns.automationId)).where(and(eq(juniorAutomations.kind, "event"), eq(juniorAutomationRuns.status, "running")));
8883
8607
  const dispatches = await mapBounded(runs, (run) => getDispatchRecord(run.id));
8884
8608
  for (const [index, run] of runs.entries()) {
8885
8609
  const dispatch = dispatches[index];
8610
+ if (!dispatch && (run.startedAtMs ?? 0) > nowMs - MISSING_DISPATCH_GRACE_MS) continue;
8886
8611
  const status = dispatch?.status ?? "failed";
8887
8612
  if (status !== "blocked" && status !== "completed" && status !== "failed") continue;
8888
8613
  await recordAutomationExecution(run.automationId, {
@@ -9145,8 +8870,11 @@ async function answerAutomationAlert(args) {
9145
8870
  function eventAutomationDispatchKey(taskId, namespace, eventKey) {
9146
8871
  return `event-automation:${createHash("sha256").update(`${taskId}\0${namespace}\0${eventKey}`).digest("hex").slice(0, 32)}`;
9147
8872
  }
9148
- /** Render plain agent input for one matching event automation. */
9149
- function eventInput(task, event, outcomes, catalog, author) {
8873
+ /**
8874
+ * Render plain agent input for one matching event automation, with the open
8875
+ * questions of its earlier runs.
8876
+ */
8877
+ function eventInput(task, event, outcomes, catalog, author, openQuestions) {
9150
8878
  const guidance = eventGuidance(catalog, event.namespace, event.eventType);
9151
8879
  return renderTaskInput({
9152
8880
  about: task.trigger.label,
@@ -9155,6 +8883,7 @@ function eventInput(task, event, outcomes, catalog, author) {
9155
8883
  creator: slackMention(task.createdBy.slackUserId),
9156
8884
  instructions: automationTaskText(task.task),
9157
8885
  ...task.task.kind === "skill" ? { skill: task.task.skill } : void 0,
8886
+ openQuestions,
9158
8887
  outcomes,
9159
8888
  guidance,
9160
8889
  trustedSummary: event.trustedSummary,
@@ -9242,7 +8971,12 @@ async function ingestEventAutomations(input, options) {
9242
8971
  allowedWhen: "event-automation",
9243
8972
  taskId: task.id
9244
8973
  } : void 0;
9245
- const dispatch = await dispatchEventAutomation({
8974
+ await recordEventAutomationRunStarted(db, {
8975
+ automation: task,
8976
+ dispatchId: eventAutomationDispatchId(idempotencyKey),
8977
+ nowMs
8978
+ });
8979
+ if ((await dispatchEventAutomation({
9246
8980
  automationId: task.id,
9247
8981
  conversationWorkQueue: options.queue,
9248
8982
  nowMs,
@@ -9251,19 +8985,13 @@ async function ingestEventAutomations(input, options) {
9251
8985
  ...credentialSubject ? { credentialSubject } : void 0,
9252
8986
  destination,
9253
8987
  destinationVisibility: task.destinationVisibility,
9254
- input: eventInput(task, event, outcomes, catalog, author),
8988
+ input: eventInput(task, event, outcomes, catalog, author, await listOpenAutomationQuestions(db, task.id)),
9255
8989
  ...skill ? { skill } : void 0,
9256
8990
  metadata: { eventAutomationId: task.id },
9257
8991
  replyAttribution: automationReplyAttribution(task.title),
9258
8992
  outcomes
9259
8993
  }
9260
- });
9261
- await recordEventAutomationRunStarted(db, {
9262
- automation: task,
9263
- dispatchId: dispatch.id,
9264
- nowMs
9265
- });
9266
- if (dispatch.status === "created") dispatched += 1;
8994
+ })).status === "created") dispatched += 1;
9267
8995
  } catch (error) {
9268
8996
  errors.push(error);
9269
8997
  }
@@ -9348,7 +9076,7 @@ function createEventAppPublisher(args) {
9348
9076
  */
9349
9077
  async function answerPluginInboxItem(args) {
9350
9078
  const { item } = args;
9351
- const pluginName = inboxItemPlugin(item.dedupeKey);
9079
+ const pluginName = inboxItemPlugin(item);
9352
9080
  const choice = item.answer?.values[PLUGIN_CHOICE_FIELD_ID]?.[0];
9353
9081
  const conversationId = ownerConversationId(item);
9354
9082
  if (!pluginName || !choice || !conversationId) return;
@@ -9361,7 +9089,10 @@ async function answerPluginInboxItem(args) {
9361
9089
  choice,
9362
9090
  codeChanges: createPluginCodeChanges(pluginName),
9363
9091
  conversationId,
9364
- dedupeKey: item.dedupeKey.slice(`${PLUGIN_INBOX_ITEM_KEY_PREFIX}${pluginName}:`.length),
9092
+ subject: {
9093
+ id: item.subject.id,
9094
+ kind: item.subject.kind.slice(pluginName.length + 1)
9095
+ },
9365
9096
  events: createPluginEventPublisher(plugin, events),
9366
9097
  itemId: item.id,
9367
9098
  nowMs: args.nowMs,
@@ -9379,11 +9110,12 @@ const MATCH_CONFIDENCE_THRESHOLD = .7;
9379
9110
  /** A slow decision keeps the items open instead of delaying the close. */
9380
9111
  const MATCH_TIMEOUT_MS = 1e4;
9381
9112
  function describeItem(item) {
9382
- const fields = (item.request?.fields ?? []).map((field) => "options" in field ? `- ${field.label}: ${field.options.map((option) => option.label).join(" / ")}` : `- ${field.label}: free text`);
9113
+ const request = inboxItemQuestion(item.request);
9114
+ const fields = (request?.fields ?? []).map((field) => "options" in field ? `- ${field.label}: ${field.options.map((option) => option.label).join(" / ")}` : `- ${field.label}: free text`);
9383
9115
  return [
9384
9116
  `Title: ${item.title}`,
9385
9117
  `Details: ${item.body}`,
9386
- ...item.request ? [`Question: ${item.request.question}`] : [],
9118
+ ...request ? [`Question: ${request.question}`] : [],
9387
9119
  ...fields.length ? ["Fields:", ...fields] : []
9388
9120
  ].join("\n");
9389
9121
  }
@@ -9479,8 +9211,9 @@ function isSameClose(item, action, user) {
9479
9211
  return item.closeReason !== "Replied in thread" && item.closedBy?.userId === user.id && item.status === closedStatus(action) && action === "submit" === Boolean(item.answer);
9480
9212
  }
9481
9213
  function submittedAnswer(item, answer) {
9482
- if (item.kind !== "action" || !item.request) throw new InboxItemActionError("invalid", "Only an action item takes an answer.");
9483
- const normalized = normalizeUserInputAnswer(item.request, {
9214
+ const question = inboxItemQuestion(item.request);
9215
+ if (item.kind !== "action" || !question) throw new InboxItemActionError("invalid", "Only an action item takes an answer.");
9216
+ const normalized = normalizeUserInputAnswer(question, {
9484
9217
  other: answer?.other,
9485
9218
  requestId: item.id,
9486
9219
  values: answer?.values ?? {}
@@ -9499,16 +9232,24 @@ function submittedAnswer(item, answer) {
9499
9232
  * `exceptConversationId` is the Conversation where the person acted. It gets
9500
9233
  * the person's input from its own surface, so it gets no message here.
9501
9234
  * `delivery` shows the change and sends the messages; see
9502
- * `deliverInboxItemChange`.
9235
+ * `deliverInboxItemChange`. A submit, dismiss, or done also closes the
9236
+ * person's reply notices in the item's Conversations: the item had their
9237
+ * attention.
9503
9238
  */
9504
9239
  async function actOnInboxItem(args) {
9505
9240
  const { action, user } = args;
9506
9241
  const nowMs = args.nowMs ?? Date.now();
9507
9242
  const db = getDb();
9508
9243
  const item = await readInboxItemForUser(user, args.id);
9509
- if (inboxItemTodo(item)) {
9244
+ if (subjectTodo(item.subject)) {
9510
9245
  if (action !== "done" && action !== "dismiss") throw new InboxItemActionError("invalid", "A To-do item takes only Done or Dismiss.");
9511
- return await closeTodoItem(item, user, nowMs, action);
9246
+ const closed = await closeTodoItem(item, user, nowMs, action);
9247
+ await closeHandledReplyNotices(db, {
9248
+ item: closed,
9249
+ nowMs,
9250
+ userId: user.id
9251
+ });
9252
+ return closed;
9512
9253
  }
9513
9254
  if (action === "done") throw new InboxItemActionError("invalid", "Only a To-do item can be marked done.");
9514
9255
  if (action === "take") {
@@ -9544,6 +9285,11 @@ async function actOnInboxItem(args) {
9544
9285
  closed = await readInboxItemForUser(user, item.id);
9545
9286
  }
9546
9287
  if (args.firstCloseOnly ? !closedNow : !isSameClose(closed, action, user)) throw new InboxItemActionError("conflict", "Inbox item is closed.");
9288
+ await closeHandledReplyNotices(db, {
9289
+ item: closed,
9290
+ nowMs,
9291
+ userId: user.id
9292
+ });
9547
9293
  if (action === "submit" && isPluginInboxItem(closed)) await answerPluginInboxItem({
9548
9294
  delivery: args.delivery,
9549
9295
  item: closed,
@@ -9572,11 +9318,11 @@ async function actOnInboxItem(args) {
9572
9318
  * Close a To-do item for its assignee through its To-do: Done marks the
9573
9319
  * To-do done, and Dismiss drops it. The To-do change closes the item as
9574
9320
  * done or dismissed (`syncTodoInboxItems`), and the agent sees it in its
9575
- * next `<todo-delta>`, so it sends no message and starts no Turn. A retry
9321
+ * next To-do delta, so it sends no message and starts no Turn. A retry
9576
9322
  * after the item closed the same way by the same person succeeds.
9577
9323
  */
9578
9324
  async function closeTodoItem(item, user, nowMs, action) {
9579
- const todo = inboxItemTodo(item);
9325
+ const todo = subjectTodo(item.subject);
9580
9326
  if (item.status === "open") {
9581
9327
  if (!canActOnInboxItem(item, user.id)) throw new InboxItemActionError("forbidden", "Only an assignee can act on this item.");
9582
9328
  await setTodoStatusByUser(getSqlExecutor(), {
@@ -9603,8 +9349,9 @@ function replyAnswers(item, user) {
9603
9349
  }
9604
9350
  /** Return the answer that the text of a person's message gives to an item. */
9605
9351
  function messageAnswer(item, text) {
9606
- if (!item.request) return void 0;
9607
- const answer = normalizeUserInputAnswer(item.request, {
9352
+ const question = inboxItemQuestion(item.request);
9353
+ if (!question) return void 0;
9354
+ const answer = normalizeUserInputAnswer(question, {
9608
9355
  other: text,
9609
9356
  requestId: item.id,
9610
9357
  values: {}
@@ -10249,24 +9996,6 @@ async function reorderPinnedConversations(viewer, body) {
10249
9996
  const updatedIds = new Set(updated.map((row) => row.rootConversationId));
10250
9997
  return { conversationIds: ids.filter((id) => updatedIds.has(id)) };
10251
9998
  }
10252
- // src/chat/conversations/sql/title.ts
10253
- /**
10254
- * Replace one Conversation's title. Returns the stored title, or undefined
10255
- * when the Conversation does not exist.
10256
- *
10257
- * recordActivity reads the title and writes it back under the mutation lock,
10258
- * so this write takes the same lock. A concurrent Turn cannot restore the old
10259
- * title.
10260
- */
10261
- async function setConversationTitle(executor, conversationId, title) {
10262
- return await withConversationMutationLock(executor, conversationId, async () => {
10263
- const [row] = await executor.db().update(juniorConversations).set({
10264
- detailVersion: nextDetailVersion,
10265
- title
10266
- }).where(eq(juniorConversations.conversationId, conversationId)).returning({ title: juniorConversations.title });
10267
- return row?.title ?? void 0;
10268
- });
10269
- }
10270
9999
  // src/api/conversations/rename.ts
10271
10000
  /**
10272
10001
  * Rename one conversation. The title is shared, so only a participant can
@@ -10279,148 +10008,6 @@ async function renameConversation(viewer, conversationId, body) {
10279
10008
  if (!title) throwApiError(404, "Conversation not found.");
10280
10009
  return { title };
10281
10010
  }
10282
- // src/chat/spaces/conversations.ts
10283
- /**
10284
- * Conversations in a Space (`design/spaces.md`). Only a root stores its
10285
- * Space. A child is in the Space of its root, so the two never disagree.
10286
- */
10287
- const spaceRoot$1 = alias(juniorConversations, "space_root");
10288
- /** Read the id and name of each Space, by id. A missing id has no entry. */
10289
- async function readSpaceRefs(db, spaceIds) {
10290
- const ids = [...new Set(spaceIds)];
10291
- if (ids.length === 0) return /* @__PURE__ */ new Map();
10292
- const rows = await db.select({
10293
- id: juniorSpaces.id,
10294
- name: juniorSpaces.name
10295
- }).from(juniorSpaces).where(inArray(juniorSpaces.id, ids));
10296
- return new Map(rows.map((row) => [row.id, row]));
10297
- }
10298
- /**
10299
- * Put one root in a Space, or take it out of every Space with null. The root
10300
- * gets the Space's visibility on its own Location. The caller checks who may
10301
- * move it out of `fromSpaceId`, the Space that it read before the move.
10302
- */
10303
- async function setConversationSpace(conversationId, spaceId, fromSpaceId) {
10304
- const executor = getSqlExecutor();
10305
- return await executor.transaction(async () => {
10306
- const db = executor.db();
10307
- const [root] = await db.select({
10308
- locationId: juniorConversations.destinationId,
10309
- provider: juniorDestinations.provider,
10310
- spaceId: juniorConversations.spaceId
10311
- }).from(juniorConversations).leftJoin(juniorDestinations, eq(juniorDestinations.id, juniorConversations.destinationId)).where(and(eq(juniorConversations.conversationId, conversationId), isNull(juniorConversations.parentConversationId))).limit(1).for("update", { of: juniorConversations });
10312
- if (!root) return "not_found";
10313
- if (root.spaceId !== fromSpaceId) return "moved";
10314
- const spaceIds = [root.spaceId, spaceId].filter((id) => id !== null);
10315
- const spaces = spaceIds.length > 0 ? await db.select({
10316
- id: juniorSpaces.id,
10317
- visibility: juniorSpaces.visibility
10318
- }).from(juniorSpaces).where(inArray(juniorSpaces.id, spaceIds)) : [];
10319
- if (spaces.find((space) => space.id === root.spaceId)?.visibility === "private") return "leaves_private";
10320
- if (spaces.find((space) => space.id === spaceId)?.visibility === "private") {
10321
- if (root.provider !== "local" || !root.locationId) return "shared_location";
10322
- await db.update(juniorDestinations).set({
10323
- visibility: "private",
10324
- updatedAt: /* @__PURE__ */ new Date()
10325
- }).where(eq(juniorDestinations.id, root.locationId));
10326
- }
10327
- await db.update(juniorConversations).set({
10328
- spaceId,
10329
- detailVersion: nextDetailVersion
10330
- }).where(eq(juniorConversations.conversationId, conversationId));
10331
- });
10332
- }
10333
- /**
10334
- * Every Conversation in the Space, at any depth. A root from before
10335
- * `root_conversation_id` was set matches by its own id.
10336
- */
10337
- function inSpaceTrees(db, spaceId) {
10338
- const roots = db.select({ id: spaceRoot$1.conversationId }).from(spaceRoot$1).where(eq(spaceRoot$1.spaceId, spaceId));
10339
- return or(inArray(juniorConversations.rootConversationId, roots), inArray(juniorConversations.conversationId, roots));
10340
- }
10341
- /**
10342
- * Archive or restore a Space with its Conversations.
10343
- *
10344
- * Archive writes one time to the Space and to each unarchived Conversation
10345
- * in it, at any depth. Then it stops each root that is not stopped, with the
10346
- * child agents below it, so no work in the Space keeps running. A retry
10347
- * stops what an earlier try left running.
10348
- *
10349
- * Restore clears the Space and the Conversations that its archive wrote. A
10350
- * Conversation that was archived on its own stays archived. Restore starts
10351
- * no work.
10352
- */
10353
- async function setSpaceArchive(args) {
10354
- const executor = getSqlExecutor();
10355
- await executor.transaction(async () => {
10356
- const db = executor.db();
10357
- const [space] = await db.select({ archivedAt: juniorSpaces.archivedAt }).from(juniorSpaces).where(eq(juniorSpaces.id, args.spaceId)).limit(1).for("update");
10358
- if (!space) return;
10359
- const now = /* @__PURE__ */ new Date();
10360
- if (args.archived) {
10361
- if (space.archivedAt) return;
10362
- await db.update(juniorSpaces).set({
10363
- archivedAt: now,
10364
- updatedAt: now
10365
- }).where(eq(juniorSpaces.id, args.spaceId));
10366
- await setArchivedAt(db, inSpaceTrees(db, args.spaceId), now, isNull(juniorConversations.archivedAt));
10367
- return;
10368
- }
10369
- if (!space.archivedAt) return;
10370
- await db.update(juniorSpaces).set({
10371
- archivedAt: null,
10372
- updatedAt: now
10373
- }).where(eq(juniorSpaces.id, args.spaceId));
10374
- await setArchivedAt(db, inSpaceTrees(db, args.spaceId), null, eq(juniorConversations.archivedAt, space.archivedAt));
10375
- });
10376
- if (!args.archived) return;
10377
- const running = await getDb().select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(eq(juniorConversations.spaceId, args.spaceId), isNull(juniorConversations.stoppedAt)));
10378
- await mapBounded(running, ({ conversationId }) => stopConversation({
10379
- conversationId,
10380
- queue: args.queue
10381
- }));
10382
- }
10383
- // src/api/conversations/space.ts
10384
- /**
10385
- * Return the Space that the viewer puts work in. Only a member starts or
10386
- * moves work into a Space, and an archived Space takes no new work.
10387
- */
10388
- async function requireSpaceForWork(viewer, spaceId) {
10389
- const space = await readSpace(viewer.id, spaceId);
10390
- if (!space) throwApiError(404, "Space was not found.");
10391
- if (space.archivedAt) throwApiError(409, "Restore the Space before you add work to it.");
10392
- if (!space.viewerIsMember) throwApiError(403, "Join the Space to add work to it.");
10393
- return space;
10394
- }
10395
- /**
10396
- * Put one root Conversation in a Space, or make it a one-off with null.
10397
- * Only a participant moves it. They must be a member of the Space that it
10398
- * leaves and of the Space that it joins. Only a public root joins a Space.
10399
- * A root in a private Space stays there, so its data stays with the members.
10400
- */
10401
- async function setConversationSpaceForViewer(viewer, conversationId, body) {
10402
- const [conversation, access] = await Promise.all([getConversationStore().get({ conversationId }), readConversationAccessFromSql(getDb(), [conversationId], viewer).then((byId) => byId.get(conversationId))]);
10403
- if (!conversation || !access?.isParticipant) throwApiError(404, "Conversation not found.");
10404
- if (!canMoveToSpace(conversation)) throwApiError(409, "Only a top-level conversation moves. A child is in the Space of its root.");
10405
- const currentSpaceId = conversation.spaceId ?? null;
10406
- const target = body.spaceId ? await requireSpaceForWork(viewer, body.spaceId) : void 0;
10407
- const response = { space: target ? {
10408
- id: target.id,
10409
- name: target.name
10410
- } : null };
10411
- if (body.spaceId === currentSpaceId) return response;
10412
- if (currentSpaceId) {
10413
- const source = await readSpace(viewer.id, currentSpaceId);
10414
- if (source && !source.viewerIsMember) throwApiError(403, "Join the Space that it is in to move it.");
10415
- }
10416
- if (target && access.visibility !== "public") throwApiError(409, "Only a public conversation can join a Space.");
10417
- const refusal = await setConversationSpace(conversationId, body.spaceId, currentSpaceId);
10418
- if (refusal === "not_found") throwApiError(404, "Conversation not found.");
10419
- if (refusal === "moved") throwApiError(409, "It moved to another Space. Reload and try again.");
10420
- if (refusal === "leaves_private") throwApiError(409, "A conversation in a private Space stays in it.");
10421
- if (refusal === "shared_location") throwApiError(409, "A Slack conversation can't join a private Space.");
10422
- return response;
10423
- }
10424
10011
  // src/api/conversations/stop.ts
10425
10012
  /**
10426
10013
  * Stop one Conversation for a participant: its active Turn, its session, and
@@ -10486,12 +10073,12 @@ const writeAnnotations = {
10486
10073
  const archiveConversationOperation = defineApiOperation({
10487
10074
  name: "archiveConversation",
10488
10075
  title: "Archive conversation",
10489
- description: "Archive one of your conversations, or restore it, for everyone in it. Archiving a conversation hides it and its child conversations. A restore fails while a conversation above it is archived. A new message from a person restores the conversation and the archived conversations above it.",
10076
+ description: "Archive one of your conversations, or restore it, for everyone in it. Archiving a conversation hides it and its child conversations and stops their running work. A restore fails while a conversation above it is archived. A new message from a person restores the conversation and the archived conversations above it.",
10490
10077
  scope: "conversations:manage",
10491
10078
  input: archiveConversationBodySchema.extend(conversationIdInput),
10492
10079
  output: archiveConversationResponseSchema,
10493
10080
  annotations: writeAnnotations,
10494
- run: (viewer, { conversationId, ...body }) => archiveConversation(viewer, conversationId, body)
10081
+ run: (viewer, { conversationId, ...body }, services) => archiveConversation(viewer, conversationId, body, services)
10495
10082
  });
10496
10083
  /** Archive every done Conversation of the viewer once. */
10497
10084
  const archiveDoneConversationsOperation = defineApiOperation({
@@ -10548,6 +10135,20 @@ const setConversationAutoArchiveOperation = defineApiOperation({
10548
10135
  annotations: writeAnnotations,
10549
10136
  run: (viewer, { autoArchive, conversationId }) => setConversationAutoArchive(viewer, conversationId, autoArchive)
10550
10137
  });
10138
+ /** The viewer leaves a Conversation. Nobody removes another person. */
10139
+ const leaveConversationOperation = defineApiOperation({
10140
+ name: "leaveConversation",
10141
+ title: "Leave conversation",
10142
+ description: "Leave one of your conversations. It leaves your feed and clears your pin. In a private conversation you also lose access, and only another participant can invite you back. A public one stays readable, and you can subscribe again. When nobody else is subscribed, it archives the conversation for everyone.",
10143
+ scope: "conversations:manage",
10144
+ input: z.object(conversationIdInput).strict(),
10145
+ output: conversationLeaveResponseSchema,
10146
+ annotations: {
10147
+ ...writeAnnotations,
10148
+ destructiveHint: true
10149
+ },
10150
+ run: (viewer, { conversationId }) => leaveConversation(viewer, conversationId)
10151
+ });
10551
10152
  /** Subscribe or unsubscribe the viewer. It never changes another person. */
10552
10153
  const setConversationSubscriptionOperation = defineApiOperation({
10553
10154
  name: "setConversationSubscription",
@@ -10592,6 +10193,7 @@ const conversationOperations = [
10592
10193
  cancelQueuedMessagesOperation,
10593
10194
  archiveConversationOperation,
10594
10195
  archiveDoneConversationsOperation,
10196
+ leaveConversationOperation,
10595
10197
  pinConversationOperation,
10596
10198
  renameConversationOperation,
10597
10199
  setConversationAutoArchiveOperation,
@@ -10609,7 +10211,7 @@ const conversationCursorPayloadSchema = z.object({
10609
10211
  version: z.literal(1)
10610
10212
  }).strict();
10611
10213
  function cursorSecret() {
10612
- const secret = readJuniorSecret();
10214
+ const secret = getChatConfig().secrets.juniorSecret;
10613
10215
  if (!secret) throw new Error("Cannot sign conversation cursor without JUNIOR_SECRET");
10614
10216
  return secret;
10615
10217
  }
@@ -10674,7 +10276,6 @@ async function requireWebMessageConversation(viewer, conversationId, idempotency
10674
10276
  if (!acceptsWebMessages(conversation)) throwApiError(409, "Conversation does not accept web messages.");
10675
10277
  const access = await readConversationAccessFromSql(getDb(), [conversationId], viewer);
10676
10278
  if (!canAddConversationMessages(access.get(conversationId))) throwApiError(403, "Only participants can add messages to a private conversation.");
10677
- if (messagesNeedSpaceMembership(conversation.kind) && conversation.spaceId) await requireSpaceForWork(viewer, conversation.spaceId);
10678
10279
  return conversationId;
10679
10280
  }
10680
10281
  function actorFromViewer(viewer) {
@@ -10686,6 +10287,7 @@ async function createConversationForViewer(viewer, body, services) {
10686
10287
  const space = body.spaceId ? await requireSpaceForWork(viewer, body.spaceId) : void 0;
10687
10288
  if (space && body.visibility && body.visibility !== space.visibility) throwApiError(400, `A conversation in this Space is ${space.visibility}.`);
10688
10289
  const visibility = space?.visibility ?? body.visibility;
10290
+ const lead = space ? await getSpaceLead(space.id) : void 0;
10689
10291
  const uploads = await verifyUploads({
10690
10292
  conversationId: await requireWebMessageConversation(viewer, void 0, body.idempotencyKey),
10691
10293
  idempotencyKey: body.idempotencyKey,
@@ -10700,7 +10302,7 @@ async function createConversationForViewer(viewer, body, services) {
10700
10302
  uploads,
10701
10303
  ...body.title ? { title: body.title } : void 0,
10702
10304
  ...visibility ? { visibility } : void 0,
10703
- ...space ? { spaceId: space.id } : void 0
10305
+ ...lead ? { leadConversationId: lead.conversationId } : void 0
10704
10306
  }, {
10705
10307
  conversationStore: getConversationStore(),
10706
10308
  attachmentStorage: services.attachmentStorage,
@@ -10709,7 +10311,6 @@ async function createConversationForViewer(viewer, body, services) {
10709
10311
  } catch (error) {
10710
10312
  throwApiError(500, "Unable to create conversation.", error);
10711
10313
  }
10712
- await inviteMentionedPeople(viewer, accepted.conversationId, body.message);
10713
10314
  return accepted;
10714
10315
  }
10715
10316
  /** Append one viewer message to an existing conversation. */
@@ -10734,7 +10335,6 @@ async function appendConversationMessageForViewer(viewer, conversationId, body,
10734
10335
  queue: services.queue
10735
10336
  });
10736
10337
  const applyAccepted = async () => {
10737
- await inviteMentionedPeople(viewer, conversationId, body.message);
10738
10338
  await closeInboxItemsAnsweredByReply({
10739
10339
  conversationId,
10740
10340
  delivery: {
@@ -11303,18 +10903,21 @@ async function readConversationAgentTree(conversation, readAccess) {
11303
10903
  ]);
11304
10904
  return await mapBounded(ids, async (id) => {
11305
10905
  const itemAccess = access.get(id);
11306
- if (rootRecord && root?.conversationId === id) return {
11307
- conversationId: id,
11308
- kind: "root",
11309
- label: conversationSummaryFromStoredConversation({
10906
+ if (rootRecord && root?.conversationId === id) {
10907
+ const summary = conversationSummaryFromStoredConversation({
11310
10908
  access: itemAccess,
11311
10909
  automationTitle: automationTitleByConversation.get(id),
11312
10910
  conversation: root,
11313
10911
  durationMs: 0,
11314
10912
  firstHumanMessageText: firstHumanMessageTextByConversation.get(id),
11315
10913
  status: rootRecord.status
11316
- }).displayTitle
11317
- };
10914
+ });
10915
+ return {
10916
+ conversationId: id,
10917
+ kind: root.kind,
10918
+ label: summary.displayTitle
10919
+ };
10920
+ }
11318
10921
  const kind = kindById.get(id);
11319
10922
  if (!itemAccess?.canViewPrivateContent) return {
11320
10923
  conversationId: id,
@@ -11631,11 +11234,12 @@ function viewerStateVersion(db, conversationId, viewerId) {
11631
11234
  const versionSpaceConversation = alias(juniorConversations, "version_space_conversation");
11632
11235
  const versionSpaceRoot = alias(juniorConversations, "version_space_root");
11633
11236
  /**
11634
- * Hash the root's Space. A move writes only the root, and a rename writes
11635
- * only the Space, so a child's token reads both through its root.
11237
+ * Hash the root's Space. A move and a rename write only the root, the Lead
11238
+ * whose title is the Space's name, so a child's token reads both through
11239
+ * its root.
11636
11240
  */
11637
11241
  function rootSpaceVersion(db, conversationId) {
11638
- const space = db.select({ state: sql`md5(concat_ws(':', ${versionSpaceRoot.spaceId}, ${juniorSpaces.name}))` }).from(versionSpaceConversation).innerJoin(versionSpaceRoot, eq(versionSpaceRoot.conversationId, sql`coalesce(${versionSpaceConversation.rootConversationId}, ${versionSpaceConversation.conversationId})`)).leftJoin(juniorSpaces, eq(juniorSpaces.id, versionSpaceRoot.spaceId)).where(eq(versionSpaceConversation.conversationId, conversationId));
11242
+ const space = db.select({ state: sql`md5(concat_ws(':', ${versionSpaceRoot.spaceId}, ${versionSpaceRoot.title}))` }).from(versionSpaceConversation).innerJoin(versionSpaceRoot, eq(versionSpaceRoot.conversationId, sql`coalesce(${versionSpaceConversation.rootConversationId}, ${versionSpaceConversation.conversationId})`)).where(eq(versionSpaceConversation.conversationId, conversationId));
11639
11243
  return sql`coalesce((${space}), '')`;
11640
11244
  }
11641
11245
  /**
@@ -11688,11 +11292,11 @@ async function readDetailStateRow(conversationId, viewer) {
11688
11292
  pinnedAt: juniorConversationParticipants.pinnedAt,
11689
11293
  pinPosition: juniorConversationParticipants.pinPosition,
11690
11294
  rootConversationId,
11691
- spaceId: juniorSpaces.id,
11692
- spaceName: juniorSpaces.name,
11295
+ spaceId: spaceRoot.spaceId,
11296
+ spaceName: spaceRoot.title,
11693
11297
  unsubscribedAt: juniorConversationParticipants.unsubscribedAt,
11694
11298
  version: sql`(${conversationVersionQuery(db, conversationId, viewer?.id)})`
11695
- }).from(juniorConversations).leftJoin(juniorDestinations, conversationRecordJoins.location).leftJoin(juniorIdentities, conversationRecordJoins.identity).leftJoin(juniorUsers, conversationRecordJoins.user).leftJoin(forkSource, eq(forkSource.conversationId, juniorConversations.forkedFromConversationId)).leftJoin(spaceRoot, eq(spaceRoot.conversationId, rootConversationId)).leftJoin(juniorSpaces, eq(juniorSpaces.id, spaceRoot.spaceId)).leftJoin(juniorConversationParticipants, viewerParticipant).leftJoin(detailViewer, viewer ? eq(detailViewer.id, viewer.id) : sql`false`).where(eq(juniorConversations.conversationId, conversationId));
11299
+ }).from(juniorConversations).leftJoin(juniorDestinations, conversationRecordJoins.location).leftJoin(juniorIdentities, conversationRecordJoins.identity).leftJoin(juniorUsers, conversationRecordJoins.user).leftJoin(forkSource, eq(forkSource.conversationId, juniorConversations.forkedFromConversationId)).leftJoin(spaceRoot, eq(spaceRoot.conversationId, rootConversationId)).leftJoin(juniorConversationParticipants, viewerParticipant).leftJoin(detailViewer, viewer ? eq(detailViewer.id, viewer.id) : sql`false`).where(eq(juniorConversations.conversationId, conversationId));
11696
11300
  return row;
11697
11301
  }
11698
11302
  async function readDetailState(conversationId, viewer, readAccess) {
@@ -11724,7 +11328,7 @@ async function readDetailState(conversationId, viewer, readAccess) {
11724
11328
  ...viewer ? { autoArchive: row?.autoArchive ?? row?.autoArchiveDefault ?? false } : void 0,
11725
11329
  forks,
11726
11330
  ...row?.lastReadSeq != null ? { readPosition: { lastReadSeq: row.lastReadSeq } } : void 0,
11727
- space: row?.spaceId && row.spaceName && (!access?.privateSpaceId || access.canViewPrivateContent) ? {
11331
+ space: row?.spaceId && row.spaceName && access?.canViewPrivateContent ? {
11728
11332
  id: row.spaceId,
11729
11333
  name: row.spaceName
11730
11334
  } : null,
@@ -12106,11 +11710,10 @@ function needsUserSql(userId) {
12106
11710
  * Conversation and every child Conversation at any depth. When more than
12107
11711
  * one applies:
12108
11712
  *
12109
- * - `needs_you`: the tree's `needs_input` includes the viewer. A Review
12110
- * item or a sign-in wait anywhere in the tree counts. Only the
12111
- * Conversation's own wait on its starter counts, and only when the
12112
- * viewer is the starter. Input that waits on another person is not
12113
- * shown.
11713
+ * - `needs_you`: the tree's `needs_input` includes the viewer. An Inbox
11714
+ * item, a sign-in wait, or a wait on the starter anywhere in the tree
11715
+ * counts when it waits on the viewer. Input that waits on another person
11716
+ * is not shown.
12114
11717
  * - `working`: a Turn is queued or running anywhere in the tree.
12115
11718
  * - `done`: anything else.
12116
11719
  *
@@ -12130,7 +11733,7 @@ function needsUserSql(userId) {
12130
11733
  async function readConversationTreeStates(db, conversationIds, viewerUserId) {
12131
11734
  if (conversationIds.length === 0) return /* @__PURE__ */ new Map();
12132
11735
  const scopeId = conversationSubtreeColumns.scopeConversationId;
12133
- const needsViewer = viewerUserId ? sql`bool_or(${needsUserSql(viewerUserId)} or (${eq(juniorConversations.conversationId, scopeId)} and ${conversationWaitsOnUserSql(juniorConversations, viewerUserId)}))` : sql`false`;
11736
+ const needsViewer = viewerUserId ? sql`bool_or(${needsUserSql(viewerUserId)} or ${conversationWaitsOnUserSql(juniorConversations, viewerUserId)})` : sql`false`;
12134
11737
  const rows = await db.select({
12135
11738
  conversationId: scopeId,
12136
11739
  needsViewer,
@@ -12321,14 +11924,17 @@ async function readConversationDetailFromSql(conversationId, options) {
12321
11924
  name: "Project conversation detail",
12322
11925
  op: "function"
12323
11926
  }, () => projectConversationDetail(detail));
11927
+ const isRoot = access?.rootConversationId === conversationId;
12324
11928
  return {
12325
11929
  ...report,
12326
11930
  ...state.forks,
12327
11931
  ...treeStateByConversation.get(conversationId),
12328
11932
  ...agentTree ? { agentTree } : void 0,
12329
11933
  ...report.isParticipant && state.autoArchive !== void 0 ? { autoArchive: state.autoArchive } : void 0,
12330
- ...report.isParticipant && state.subscribed !== void 0 ? { subscribed: state.subscribed } : void 0,
11934
+ ...isRoot && (report.isParticipant ? state.subscribed !== void 0 : access?.visibility === "public") ? { subscribed: report.isParticipant && state.subscribed === true } : void 0,
12331
11935
  ...canContinueInSlack(record.conversation, access) ? { canContinueInSlack: true } : void 0,
11936
+ ...canInviteToConversation(access) ? { canInvite: true } : void 0,
11937
+ ...isRoot && leaveEndsAccess(access) ? { leaveEndsAccess: true } : void 0,
12332
11938
  ...report.isParticipant && canPauseConversationDelivery(record.conversation) ? { deliveryPaused: record.conversation.deliveryPausedAtMs !== void 0 } : void 0
12333
11939
  };
12334
11940
  }
@@ -12347,54 +11953,65 @@ async function readConversationDetail(conversationId, options = {}) {
12347
11953
  } : { limit: options.limit }
12348
11954
  });
12349
11955
  }
12350
- // src/chat/conversations/sql/listed.ts
12351
- /**
12352
- * Match Conversations that are not a Lead. Its Space's page opens the Lead,
12353
- * so lists leave it out. Older rows have no kind.
12354
- */
12355
- function notLeadConversation() {
12356
- return or(isNull(juniorConversations.kind), ne(juniorConversations.kind, "lead"));
12357
- }
12358
- /**
12359
- * Match Conversations that lists and searches may show: roots that are not
12360
- * an unkept Quick question or a Lead. Each list adds its own access and
12361
- * scope filters. Structural root checks, such as retention, do not use this.
12362
- */
12363
- function listedConversation() {
12364
- return and(isNull(juniorConversations.parentConversationId), isNull(juniorConversations.quickQuestionAt), notLeadConversation());
11956
+ // src/api/inbox-items/resolve-subjects.ts
11957
+ /**
11958
+ * Read the link and card of each item subject that has a link, such as a
11959
+ * pull request, for one viewer and one page of items, by `subjectKey`. A
11960
+ * link type that can read many objects at once reads the page with one
11961
+ * call, such as one GitHub GraphQL query. A subject whose card cannot be
11962
+ * read, such as when its provider is down, has only its link: the Inbox
11963
+ * then shows the item's own title and the label of its kind.
11964
+ */
11965
+ async function resolveInboxItemSubjects(viewer, items) {
11966
+ const links = await readSubjectLinks(getDb(), items);
11967
+ if (links.size === 0) return /* @__PURE__ */ new Map();
11968
+ const cards = new Map((await resolveObjectLinks(viewer, [...new Set(links.values())])).map(({ object, url }) => [url, object]));
11969
+ return new Map([...links].map(([key, url]) => {
11970
+ const object = cards.get(url);
11971
+ return [key, {
11972
+ url,
11973
+ ...object ? { object } : void 0
11974
+ }];
11975
+ }));
12365
11976
  }
12366
11977
  // src/api/conversations/threads.ts
12367
11978
  /**
12368
- * Find where a Thread nests: its nearest ancestor that is a listed root or a
12369
- * Thread. A Thread under a Task moves up. Returns undefined when an ancestor
12370
- * is archived, because an archive hides its whole subtree.
11979
+ * Find where a Thread nests: its nearest ancestor that is a listed row or a
11980
+ * Thread, and the listed row above it. A Thread under a Task moves up.
11981
+ * Returns undefined when an ancestor is archived, because an archive hides
11982
+ * its whole subtree.
12371
11983
  */
12372
11984
  function findThreadPlacement(threadId, tree, rootIds) {
12373
11985
  let placement;
12374
11986
  for (const ancestor of conversationAncestors(tree, threadId)) {
12375
- if (rootIds.has(ancestor.conversationId)) return placement ?? ancestor.conversationId;
11987
+ if (rootIds.has(ancestor.conversationId)) return {
11988
+ listedId: ancestor.conversationId,
11989
+ parentId: placement ?? ancestor.conversationId
11990
+ };
12376
11991
  if (ancestor.archivedAt) return void 0;
12377
- if (ancestor.kind === "thread") placement ??= ancestor.conversationId;
11992
+ if (isThread(ancestor)) placement ??= ancestor.conversationId;
12378
11993
  }
12379
11994
  }
12380
11995
  /**
12381
- * Read the stored Threads of the listed roots for the feed, with their
12382
- * read-time titles. It needs no access, so it can start with the other
12383
- * feed reads. The caller passes only unarchived roots, so a root archive
11996
+ * Read the stored Threads under the listed rows for the feed, with their
11997
+ * read-time titles and each Thread's tree state for the viewer. It needs
11998
+ * no access, so it can start with the other feed reads. The caller passes only unarchived roots, so a root archive
12384
11999
  * hides its tree with no writes to the children.
12385
12000
  */
12386
- async function readFeedThreadRecords(db, rootIds) {
12001
+ async function readFeedThreadRecords(db, rootIds, viewerUserId) {
12387
12002
  if (rootIds.length === 0) return void 0;
12388
- const rows = await selectConversationRecords(db).where(and(inArray(juniorConversations.rootConversationId, rootIds), eq(juniorConversations.kind, "thread"), isNull(juniorConversations.archivedAt))).orderBy(desc(juniorConversations.lastActivityAt), asc(juniorConversations.conversationId));
12003
+ const rows = await selectConversationRecords(db).innerJoin(conversationSubtree(rootIds), eq(conversationSubtreeColumns.conversationId, juniorConversations.conversationId)).where(and(eq(juniorConversations.kind, "thread"), isNotNull(juniorConversations.parentConversationId), not(topLevelConversation()), isNull(juniorConversations.archivedAt))).orderBy(desc(juniorConversations.lastActivityAt), asc(juniorConversations.conversationId));
12389
12004
  if (rows.length === 0) return void 0;
12390
12005
  const threads = rows.map((row) => ({
12391
12006
  conversation: conversationFromRecordRow(row),
12392
12007
  row
12393
12008
  }));
12009
+ const [firstHumanMessageTexts, treeStates] = await Promise.all([readFirstHumanMessageTexts(db, threads.map(({ conversation }) => conversation)), readConversationTreeStates(db, threads.map(({ conversation }) => conversation.conversationId), viewerUserId)]);
12394
12010
  return {
12395
- firstHumanMessageTexts: await readFirstHumanMessageTexts(db, threads.map(({ conversation }) => conversation)),
12011
+ firstHumanMessageTexts,
12396
12012
  rootIds: new Set(rootIds),
12397
- threads
12013
+ threads,
12014
+ treeStates
12398
12015
  };
12399
12016
  }
12400
12017
  /**
@@ -12407,16 +12024,16 @@ async function readFeedThreadRecords(db, rootIds) {
12407
12024
  */
12408
12025
  function nestFeedThreads(records, tree, accessByRoot) {
12409
12026
  if (!records) return /* @__PURE__ */ new Map();
12410
- const { firstHumanMessageTexts, rootIds, threads } = records;
12027
+ const { firstHumanMessageTexts, rootIds, threads, treeStates } = records;
12411
12028
  const childrenByParent = /* @__PURE__ */ new Map();
12412
12029
  const placedByRoot = /* @__PURE__ */ new Map();
12413
12030
  for (const { conversation, row } of threads) {
12414
- const parentId = findThreadPlacement(conversation.conversationId, tree, rootIds);
12415
- if (!parentId) continue;
12416
- const rootId = row.conversation.rootConversationId;
12417
- if (rootId) placedByRoot.set(rootId, (placedByRoot.get(rootId) ?? 0) + 1);
12031
+ const placement = findThreadPlacement(conversation.conversationId, tree, rootIds);
12032
+ if (!placement) continue;
12033
+ const { listedId, parentId } = placement;
12034
+ placedByRoot.set(listedId, (placedByRoot.get(listedId) ?? 0) + 1);
12418
12035
  const summary = conversationSummaryFromStoredConversation({
12419
- access: rootId ? accessByRoot.get(rootId) : void 0,
12036
+ access: accessByRoot.get(listedId),
12420
12037
  conversation,
12421
12038
  durationMs: row.conversation.durationMs,
12422
12039
  firstHumanMessageText: firstHumanMessageTexts.get(conversation.conversationId),
@@ -12424,7 +12041,10 @@ function nestFeedThreads(records, tree, accessByRoot) {
12424
12041
  ...row.conversation.usage ? { usage: row.conversation.usage } : void 0
12425
12042
  });
12426
12043
  const siblings = childrenByParent.get(parentId) ?? [];
12427
- siblings.push(summary);
12044
+ siblings.push({
12045
+ ...summary,
12046
+ ...treeStates.get(conversation.conversationId)
12047
+ });
12428
12048
  childrenByParent.set(parentId, siblings);
12429
12049
  }
12430
12050
  const nest = (items, budget) => items.flatMap((item) => {
@@ -12449,59 +12069,6 @@ function nestFeedThreads(records, tree, accessByRoot) {
12449
12069
  }]];
12450
12070
  }));
12451
12071
  }
12452
- // src/chat/inbox-items/waiting.ts
12453
- const waitingRootId = sql`coalesce(${juniorConversations.rootConversationId}, ${juniorInboxItemConversations.conversationId})`.as("waiting_root_id");
12454
- const waitingTodoRootId = sql`coalesce(${juniorConversations.rootConversationId}, ${juniorInboxItems.ownerId})`.as("waiting_root_id");
12455
- /** Open items that need the User now, with the root where each one waits. */
12456
- function waitingItemsQuery(db, userId) {
12457
- const columns = {
12458
- createdAt: juniorInboxItems.createdAt,
12459
- dedupeKey: juniorInboxItems.dedupeKey,
12460
- itemId: juniorInboxItems.id,
12461
- title: juniorInboxItems.title
12462
- };
12463
- return db.select({
12464
- conversationId: waitingRootId,
12465
- ...columns
12466
- }).from(juniorInboxItemConversations).innerJoin(juniorInboxItems, eq(juniorInboxItems.id, juniorInboxItemConversations.itemId)).leftJoin(juniorConversations, eq(juniorConversations.conversationId, juniorInboxItemConversations.conversationId)).where(inboxItemNeedsUserNow(userId)).union(db.select({
12467
- conversationId: waitingTodoRootId,
12468
- ...columns
12469
- }).from(juniorInboxItems).leftJoin(juniorConversations, eq(juniorConversations.conversationId, juniorInboxItems.ownerId)).where(and(inboxItemNeedsUserNow(userId), eq(juniorInboxItems.ownerKind, "conversation"), like(juniorInboxItems.dedupeKey, `${TODO_INBOX_ITEM_KEY_PREFIX}%`))));
12470
- }
12471
- /**
12472
- * Return a query for the ids of the root Conversations that wait on a User,
12473
- * as `listWaitingConversations` lists them, to filter another query by.
12474
- */
12475
- function waitingConversationIdsQuery(db, userId) {
12476
- const items = waitingItemsQuery(db, userId).as("waiting_items");
12477
- return db.select({ conversationId: items.conversationId }).from(items);
12478
- }
12479
- /**
12480
- * List the root Conversations that wait on a User: each root or one of its
12481
- * child conversations is linked to, or owns a To-do's, open item that needs
12482
- * the User now (`inboxItemNeedsUserNow`), so a snoozed item leaves it out.
12483
- */
12484
- async function listWaitingConversations(db, userId) {
12485
- const rows = (await waitingItemsQuery(db, userId)).sort((left, right) => right.createdAt.getTime() - left.createdAt.getTime() || right.itemId.localeCompare(left.itemId));
12486
- const waiting = /* @__PURE__ */ new Map();
12487
- for (const row of rows) {
12488
- const plugin = inboxItemPlugin(row.dedupeKey);
12489
- const item = {
12490
- title: row.title,
12491
- ...plugin ? { plugin } : void 0
12492
- };
12493
- const current = waiting.get(row.conversationId);
12494
- if (current) {
12495
- current.items.push(item);
12496
- current.waitingSince = row.createdAt.toISOString();
12497
- } else waiting.set(row.conversationId, {
12498
- conversationId: row.conversationId,
12499
- items: [item],
12500
- waitingSince: row.createdAt.toISOString()
12501
- });
12502
- }
12503
- return [...waiting.values()].sort((left, right) => left.conversationId.localeCompare(right.conversationId));
12504
- }
12505
12072
  // src/api/conversations/priority.ts
12506
12073
  /** Conversations with no known work leave Priority after this idle window. */
12507
12074
  const UNASSIGNED_PRIORITY_WINDOW_MS = 108e5;
@@ -12651,7 +12218,7 @@ function feedMediaSql(db) {
12651
12218
  * closed since.
12652
12219
  */
12653
12220
  function feedViewerAnswerSql(db, userId) {
12654
- const latest = db.select({ answer: sql`jsonb_build_object('answer', ${juniorInboxItems.answer}, 'closedAt', ${juniorInboxItems.closedAt}, 'request', ${juniorInboxItems.request})` }).from(juniorInboxItems).where(and(inboxItemOwnedByConversation(juniorConversations.conversationId), eq(juniorInboxItems.closedByUserId, userId), isNotNull(juniorInboxItems.answer), isNotNull(juniorInboxItems.request))).orderBy(desc(juniorInboxItems.closedAt), desc(juniorInboxItems.id)).limit(1);
12221
+ const latest = db.select({ answer: sql`jsonb_build_object('answer', ${inboxItemAnswer}, 'closedAt', ${juniorInboxItems.closedAt}, 'request', ${inboxItemRequest})` }).from(juniorInboxItems).leftJoin(juniorQuestions, itemQuestion).where(and(inboxItemOwnedByConversation(juniorConversations.conversationId), eq(juniorInboxItems.closedByUserId, userId), isNotNull(inboxItemAnswer), isNotNull(inboxItemRequest))).orderBy(desc(juniorInboxItems.closedAt), desc(juniorInboxItems.id)).limit(1);
12655
12222
  return sql`(${latest})`;
12656
12223
  }
12657
12224
  /**
@@ -12708,30 +12275,25 @@ function feedMember(filter) {
12708
12275
  function conversationFeedMembershipFilter(status, filter) {
12709
12276
  if (!filter) return status === "archived" ? sql`false` : void 0;
12710
12277
  const member = feedMember(filter);
12711
- return and(conversationIsMemberRoot(member), rootSpaceReadableBy(member), status === "archived" ? isNotNull(juniorConversations.archivedAt) : status === "all" ? void 0 : and(isNull(juniorConversations.archivedAt), conversationIsNotUnsubscribedRoot(member)));
12278
+ return and(conversationIsMemberRoot(member), status === "archived" ? isNotNull(juniorConversations.archivedAt) : status === "all" ? void 0 : and(isNull(juniorConversations.archivedAt), conversationIsNotUnsubscribedRoot(member)));
12712
12279
  }
12713
12280
  /**
12714
- * Keep root conversations linked to one code repository. A code change can
12715
- * link a child conversation, so linked ids resolve to their root. Private
12716
- * roots stay visible only to their members.
12281
+ * Keep top-level conversations linked to one code repository. A code change
12282
+ * can link a child conversation, so linked ids resolve to their ancestors,
12283
+ * and the list keeps the top-level one. Private roots stay visible only to
12284
+ * their members.
12717
12285
  */
12718
12286
  function conversationCodeRepositoryFilter(repositoryId, viewerUserId) {
12719
- return and(sql`${juniorConversations.conversationId} IN (
12720
- SELECT coalesce(linked.root_conversation_id, linked.conversation_id)
12721
- FROM ${juniorConversations} AS linked
12722
- WHERE linked.conversation_id IN (
12723
- SELECT unnest(${juniorCodeChanges.conversationIds})
12287
+ return and(sql`${juniorConversations.conversationId} IN ${conversationAncestorsOrSelf(sql`SELECT unnest(${juniorCodeChanges.conversationIds})
12724
12288
  FROM ${juniorCodeChanges}
12725
- WHERE ${juniorCodeChanges.repositoryId} = ${repositoryId}
12726
- )
12727
- )`, rootVisibleToViewer(viewerUserId));
12289
+ WHERE ${juniorCodeChanges.repositoryId} = ${repositoryId}`)}`, rootVisibleToViewer(viewerUserId));
12728
12290
  }
12729
12291
  /**
12730
- * Keep the roots of one Space with the status that the viewer may find. A
12731
- * private Space shows its roots only to its members.
12292
+ * Keep the Lead's children in one Space with the status that the viewer may
12293
+ * find. A private Space shows its work only to its members.
12732
12294
  */
12733
12295
  function conversationSpaceFilter(spaceId, status, viewerUserId) {
12734
- return and(eq(juniorConversations.spaceId, spaceId), status === "archived" ? isNotNull(juniorConversations.archivedAt) : status === "active" ? isNull(juniorConversations.archivedAt) : void 0, rootVisibleToViewer(viewerUserId));
12296
+ return and(inArray(juniorConversations.parentConversationId, spaceLeadIds(spaceId)), status === "archived" ? isNotNull(juniorConversations.archivedAt) : status === "active" ? isNull(juniorConversations.archivedAt) : void 0, rootVisibleToViewer(viewerUserId));
12735
12297
  }
12736
12298
  async function conversationRows(db, { codeRepository, conversationIds, cursor, filter, include = [], includePrivateMatches = false, limit, pinnedForUserId, query, space, status, waitingForUserId }) {
12737
12299
  const rows = db.select({
@@ -12743,19 +12305,18 @@ async function conversationRows(db, { codeRepository, conversationIds, cursor, f
12743
12305
  links: include.includes("links") ? feedLinksSql(db) : sql`null`,
12744
12306
  media: include.includes("media") ? feedMediaSql(db) : sql`null`,
12745
12307
  viewerAnswer: filter?.kind === "viewer" ? feedViewerAnswerSql(db, filter.userId) : sql`null`
12746
- }).from(juniorConversations).leftJoin(juniorDestinations, conversationRecordJoins.location).leftJoin(juniorIdentities, conversationRecordJoins.identity).leftJoin(juniorUsers, conversationRecordJoins.user).where(and(listedConversation(), space ? conversationSpaceFilter(space.id, status, space.viewerUserId) : conversationFeedMembershipFilter(status, filter), conversationIds ? inArray(juniorConversations.conversationId, conversationIds) : void 0, waitingForUserId ? inArray(juniorConversations.conversationId, waitingConversationIdsQuery(db, waitingForUserId)) : void 0, pinnedForUserId ? pinnedForUserId.pinned ? conversationPinnedForUser(pinnedForUserId.userId) : not(conversationPinnedForUser(pinnedForUserId.userId)) : void 0, cursor ? sql`(${juniorConversations.lastActivityAt} < ${cursor.at}::timestamptz or (${juniorConversations.lastActivityAt} = ${cursor.at}::timestamptz and ${juniorConversations.conversationId} > ${cursor.conversationId}))` : void 0, codeRepository ? conversationCodeRepositoryFilter(codeRepository.id, codeRepository.viewerUserId) : void 0, query ? or(sql`strpos(lower(coalesce(${juniorConversations.title}, '')), ${query}) > 0`, and(includePrivateMatches ? void 0 : eq(juniorDestinations.visibility, "public"), sql`${conversationSearchVector} @@ websearch_to_tsquery('english', ${query})`), annotationMatch(db, query, includePrivateMatches)) : void 0)).orderBy(desc(juniorConversations.lastActivityAt), asc(juniorConversations.conversationId)).$dynamic();
12308
+ }).from(juniorConversations).leftJoin(juniorDestinations, conversationRecordJoins.location).leftJoin(juniorIdentities, conversationRecordJoins.identity).leftJoin(juniorUsers, conversationRecordJoins.user).where(and(listedConversation(), space ? conversationSpaceFilter(space.id, status, space.viewerUserId) : conversationFeedMembershipFilter(status, filter), conversationIds ? inArray(juniorConversations.conversationId, conversationIds) : void 0, waitingForUserId ? inArray(juniorConversations.conversationId, waitingConversationIdsQuery(db, waitingForUserId)) : void 0, pinnedForUserId ? pinnedForUserId.pinned ? conversationPinnedForUser(pinnedForUserId.userId) : not(conversationPinnedForUser(pinnedForUserId.userId)) : void 0, cursor ? sql`(${juniorConversations.lastActivityAt} < ${cursor.at}::timestamptz or (${juniorConversations.lastActivityAt} = ${cursor.at}::timestamptz and ${juniorConversations.conversationId} > ${cursor.conversationId}))` : void 0, codeRepository ? conversationCodeRepositoryFilter(codeRepository.id, codeRepository.viewerUserId) : void 0, query ? or(sql`strpos(lower(coalesce(${juniorConversations.title}, '')), ${query}) > 0`, and(includePrivateMatches ? void 0 : isPublicConversation(juniorConversations), sql`${conversationSearchVector} @@ websearch_to_tsquery('english', ${query})`), annotationMatch(db, query, includePrivateMatches)) : void 0)).orderBy(desc(juniorConversations.lastActivityAt), asc(juniorConversations.conversationId)).$dynamic();
12747
12309
  return limit === void 0 ? rows : rows.limit(limit);
12748
12310
  }
12749
- const searchAnnotated = alias(juniorConversations, "search_annotated");
12750
12311
  /**
12751
- * Match a root whose tree has an Annotation with the text in its label or
12752
- * title, such as `getsentry/roach#12`. The feed shows the annotations of
12753
- * the whole tree, so search reads the same rows. Private annotations match
12754
- * only where the feed shows them.
12312
+ * Match a top-level Conversation whose tree has an Annotation with the text
12313
+ * in its label or title, such as `getsentry/roach#12`. The feed shows the
12314
+ * annotations of the whole tree, so search reads the same rows. Private
12315
+ * annotations match only where the feed shows them.
12755
12316
  */
12756
12317
  function annotationMatch(db, query, includePrivate) {
12757
12318
  const annotation = juniorConversationAnnotations.annotation;
12758
- return exists(db.select({ one: sql`1` }).from(juniorConversationAnnotations).innerJoin(searchAnnotated, eq(searchAnnotated.conversationId, juniorConversationAnnotations.conversationId)).where(and(eq(searchAnnotated.rootConversationId, juniorConversations.conversationId), includePrivate ? void 0 : eq(juniorDestinations.visibility, "public"), sql`strpos(lower(concat_ws(' ', ${annotation}->>'label', ${annotation}->>'title')), ${query}) > 0`)));
12319
+ return and(includePrivate ? void 0 : isPublicConversation(juniorConversations), sql`${juniorConversations.conversationId} IN ${conversationAncestorsOrSelf(sql`${db.select({ conversationId: juniorConversationAnnotations.conversationId }).from(juniorConversationAnnotations).where(sql`strpos(lower(concat_ws(' ', ${annotation}->>'label', ${annotation}->>'title')), ${query}) > 0`)}`)}`);
12759
12320
  }
12760
12321
  /**
12761
12322
  * Feed rows show last activity only as an age in whole minutes. A running
@@ -12805,6 +12366,7 @@ function conversationFeedVersionQuery(db, userId) {
12805
12366
  then concat('active:', ${ownedItemsVersion(row.conversationId)})
12806
12367
  else ${row.detailVersion}::text
12807
12368
  end`;
12369
+ const feedRowTreeRoot = sql`coalesce(${juniorConversations.rootConversationId}, ${conversationId})`;
12808
12370
  const child = sql`${feedTree.conversationId} <> ${conversationId}`;
12809
12371
  const active = conversationIsActiveSql(feedTree);
12810
12372
  const tree = db.select({ version: sql`concat_ws(':',
@@ -12819,8 +12381,8 @@ function conversationFeedVersionQuery(db, userId) {
12819
12381
  where ${child} and ${active} and ${feedTree.kind} = 'thread'
12820
12382
  )),
12821
12383
  count(*) filter (where ${hasUnexpiredAuthorizationRequest(feedTree.conversationId)})
12822
- )` }).from(feedTree).where(or(eq(feedTree.conversationId, conversationId), eq(feedTree.rootConversationId, conversationId)));
12823
- const annotations = db.select({ version: sql`concat_ws(':', count(*), max(${juniorConversationAnnotations.updatedAt}))` }).from(juniorConversationAnnotations).innerJoin(feedAnnotated, eq(feedAnnotated.conversationId, juniorConversationAnnotations.conversationId)).where(eq(feedAnnotated.rootConversationId, conversationId));
12384
+ )` }).from(feedTree).where(or(eq(feedTree.conversationId, conversationId), eq(feedTree.rootConversationId, feedRowTreeRoot)));
12385
+ const annotations = db.select({ version: sql`concat_ws(':', count(*), max(${juniorConversationAnnotations.updatedAt}))` }).from(juniorConversationAnnotations).innerJoin(feedAnnotated, eq(feedAnnotated.conversationId, juniorConversationAnnotations.conversationId)).where(eq(feedAnnotated.rootConversationId, feedRowTreeRoot));
12824
12386
  const page = db.select({
12825
12387
  conversationId,
12826
12388
  channelName: juniorConversations.channelName,
@@ -12945,11 +12507,12 @@ async function readConversationFeedFromSql(options = {}) {
12945
12507
  }
12946
12508
  const conversations = rows.map((row) => conversationFromRecordRow(row));
12947
12509
  const conversationIds = conversations.map((conversation) => conversation.conversationId);
12510
+ const rootConversationIds = [...new Set(conversations.map((conversation) => conversation.rootConversationId ?? conversation.conversationId))];
12948
12511
  const conversationTrees = readConversationTrees(db, conversationIds);
12949
12512
  const [accessRows, tree, participantsByRoot, annotationsByConversation, auxiliaryCostsByRoot, metricsByRoot, participantsByConversation, teamDomainByTeamId, { work: conversationWork, lastUserMessageAt: lastUserMessageAtByConversation }, activityPreviewByConversation, automationTitleByConversation, firstHumanMessageTextByConversation, treeStateByConversation, threadRecords, spaceRefs] = await Promise.all([
12950
12513
  readConversationAccessRows(db, conversationIds),
12951
12514
  conversationTrees,
12952
- readMemberParticipants(db, conversationIds, options.viewer ? { userId: options.viewer.id } : filter ? feedMember(filter) : void 0),
12515
+ readMemberParticipants(db, rootConversationIds, options.viewer ? { userId: options.viewer.id } : filter ? feedMember(filter) : void 0),
12953
12516
  listConversationAnnotationsById(db, conversationIds),
12954
12517
  readConversationAuxiliaryCostsFromSql(db, conversationIds),
12955
12518
  readConversationTreeMetricsFromSql(db, conversationIds),
@@ -12963,11 +12526,10 @@ async function readConversationFeedFromSql(options = {}) {
12963
12526
  readAutomationTitlesByConversationId(conversations),
12964
12527
  readFirstHumanMessageTexts(db, conversations),
12965
12528
  readConversationTreeStates(db, conversationIds, options.viewer?.id),
12966
- readFeedThreadRecords(db, conversations.filter((conversation) => conversation.archivedAtMs === void 0).map(({ conversationId }) => conversationId)),
12529
+ readFeedThreadRecords(db, conversations.filter((conversation) => conversation.archivedAtMs === void 0).map(({ conversationId }) => conversationId), options.viewer?.id),
12967
12530
  readSpaceRefs(db, conversations.flatMap(({ spaceId }) => spaceId ? [spaceId] : []))
12968
12531
  ]);
12969
- const memberSpaceIds = options.viewer ? await readPrivateSpaceMemberships(db, accessRows, options.viewer.id) : /* @__PURE__ */ new Set();
12970
- const accessByConversation = conversationAccessFromRows(accessRows, options.viewer ? new Set(participantsByRoot.keys()) : /* @__PURE__ */ new Set(), memberSpaceIds);
12532
+ const accessByConversation = conversationAccessFromRows(accessRows, options.viewer ? new Set(participantsByRoot.keys()) : /* @__PURE__ */ new Set());
12971
12533
  const tenantByConversation = new Map(rows.flatMap((row) => {
12972
12534
  const tenantId = conversationSlackTenantId({
12973
12535
  provider: row.location?.provider,
@@ -12994,7 +12556,7 @@ async function readConversationFeedFromSql(options = {}) {
12994
12556
  automationTitle: automationTitleByConversation.get(conversation.conversationId),
12995
12557
  conversation,
12996
12558
  access,
12997
- space: conversation.spaceId && (!access?.privateSpaceId || access.canViewPrivateContent) ? spaceRefs.get(conversation.spaceId) ?? null : null,
12559
+ space: conversation.spaceId && access?.canViewPrivateContent ? spaceRefs.get(conversation.spaceId) ?? null : null,
12998
12560
  auxiliaryCosts: auxiliaryCosts?.total,
12999
12561
  ...childAgentTotals ? { childAgentTotals } : void 0,
13000
12562
  durationMs: metrics?.durationMs ?? row.conversation.durationMs,
@@ -13058,4 +12620,4 @@ async function readConversationFeedFromSql(options = {}) {
13058
12620
  async function readConversationFeed(options = {}) {
13059
12621
  return readConversationFeedFromSql(options);
13060
12622
  }
13061
- export { readInboxItemForUser as $, createViewerMcp as $t, setConversationSubscriptionOperation as A, createProductionSlackWebhookServices as At, mcpCursorSchema as B, recordSkippedConversationMessage as Bt, archiveDoneConversationsOperation as C, resolveObjectLinkNow as Ct, renameConversationOperation as D, isPublicAddress as Dt, pinConversationOperation as E, guardedFetch as Et, mcpAcceptedMessageSchema as F, normalizeIncomingSlackThreadId as Ft, mcpPendingMessagesSchema as G, parseContent as Gt, mcpMessageSchema as H, bindMessageAuthorIdentityId as Ht, mcpAuthorizationSchema as I, withNormalizedThreadId as It, requireConversationPendingMessages as J, resolvePersonLink as Jt, readMcpPendingWork as K, SubscribedReplyReason as Kt, mcpConversation as L, AGENT_DISPATCH_MAX_AGE_MS as Lt, setSpaceArchive as M, buildSlackInboundMessage as Mt, reorderPinnedConversations as N, clearSlackPendingReactions as Nt, setConversationAutoArchiveOperation as O, publicAddressLookup as Ot, apiOperationHandler as P, slackInboundMessageId as Pt, closeInboxItemsAnsweredByReply as Q, readFirstHumanMessageTexts as Qt, mcpConversationIdSchema as R, enqueueAgentDispatch as Rt, archiveConversationOperation as S, readObjectLinkTypes as St, conversationOperations as T, viewerCanViewPluginLink as Tt, mcpMessageTextSchema as U, startProcessingReaction as Ut, mcpIdempotencyKeySchema as V, createSlackWebApiStatusSender as Vt, mcpMessages as W, stripLeadingBotMention as Wt, InboxItemActionError as X, readConversationRecordFromSql as Xt, resolveMentions as Y, conversationRecordJoins as Yt, actOnInboxItem as Z, conversationSummaryFromStoredConversation as Zt, appendConversationMessageForViewer as _, backfillCacheWarmingGaps as _t, listWaitingConversations as a, readUserSettings as at, decodeConversationCursor as b, OBJECT_LINK_TTL_MS as bt, readConversationDetail as c, settleEventAutomationRuns as ct, readConversationTreeMetricsFromSql as d, getScheduledAutomationDispatch as dt, IMAGE_WIDTHS as en, reviewItemChange as et, conversationVersionsQuery as f, runInboxSnoozeTimers as ft, readConversationEvents as g, startSavingsRefill as gt, keepQuickQuestionForViewer as h, runSavingsRefillSlice as ht, encodePageCursor as i, DEFAULT_USER_SETTINGS as it, stopConversationOperation as j, getProductionSlackAdapter as jt, setConversationSpaceOperation as k, createProductionConversationWorkOptions as kt, readConversationAuxiliaryCostsFromSql as l, createHeartbeatContext as lt, forkConversationForViewer as m, readSavingsRefill as mt, readConversationFeed as n, ingestEventAutomations as nt, listedConversation as o, updateUserSettings as ot, readConversationDetailEtag as p, scheduleInboxSnoozeTimer as pt, readMcpPendingWorkAfterSend as q, getThreadStopDecision as qt, decodePageCursor as r, runAutoArchiveSweep as rt, notLeadConversation as s, automationReplyAttribution as st, conversationFeedVersionQuery as t, decodeImageId as tn, createEventAppPublisher as tt, childAgentTotalsReport as u, dispatchScheduledAutomation as ut, createConversationForViewer as v, GET as vt, cancelQueuedMessagesOperation as w, resolveObjectLinks as wt, encodeConversationCursor as x, readLinkObjectType as xt, requireWebMessageConversation as y, readHealthReport as yt, mcpConversationSchema as z, failStoppedDispatch as zt };
12623
+ export { reviewItemChange as $, setConversationSubscriptionOperation as A, createProductionSlackWebhookServices as At, mcpIdempotencyKeySchema as B, startProcessingReaction as Bt, cancelQueuedMessagesOperation as C, resolveObjectLinkNow as Ct, renameConversationOperation as D, isPublicAddress as Dt, pinConversationOperation as E, guardedFetch as Et, mcpAuthorizationSchema as F, normalizeIncomingSlackThreadId as Ft, readMcpPendingWork as G, resolvePersonLink as Gt, mcpMessageTextSchema as H, parseContent as Ht, mcpConversation as I, withNormalizedThreadId as It, resolveMentions as J, readFirstHumanMessageTexts as Jt, readMcpPendingWorkAfterSend as K, readConversationRecordFromSql as Kt, mcpConversationIdSchema as L, recordSkippedConversationMessage as Lt, reorderPinnedConversations as M, buildSlackInboundMessage as Mt, apiOperationHandler as N, clearSlackPendingReactions as Nt, setConversationAutoArchiveOperation as O, publicAddressLookup as Ot, mcpAcceptedMessageSchema as P, slackInboundMessageId as Pt, readInboxItemForUser as Q, mcpConversationSchema as R, createSlackWebApiStatusSender as Rt, archiveDoneConversationsOperation as S, readObjectLinkTypes as St, leaveConversationOperation as T, viewerCanViewPluginLink as Tt, mcpMessages as U, SubscribedReplyReason as Ut, mcpMessageSchema as V, stripLeadingBotMention as Vt, mcpPendingMessagesSchema as W, getThreadStopDecision as Wt, actOnInboxItem as X, IMAGE_WIDTHS as Xt, InboxItemActionError as Y, createViewerMcp as Yt, closeInboxItemsAnsweredByReply as Z, decodeImageId as Zt, createConversationForViewer as _, backfillCacheWarmingGaps as _t, resolveInboxItemSubjects as a, updateUserSettings as at, encodeConversationCursor as b, OBJECT_LINK_TTL_MS as bt, readConversationAuxiliaryCostsFromSql as c, listOpenAutomationQuestions as ct, conversationVersionsQuery as d, getScheduledAutomationDispatch as dt, createEventAppPublisher as et, readConversationDetailEtag as f, runInboxSnoozeTimers as ft, appendConversationMessageForViewer as g, startSavingsRefill as gt, readConversationEvents as h, runSavingsRefillSlice as ht, encodePageCursor as i, readUserSettings as it, stopConversationOperation as j, getProductionSlackAdapter as jt, setConversationSpaceOperation as k, createProductionConversationWorkOptions as kt, childAgentTotalsReport as l, createHeartbeatContext as lt, keepQuickQuestionForViewer as m, readSavingsRefill as mt, readConversationFeed as n, runAutoArchiveSweep as nt, readConversationDetail as o, automationReplyAttribution as ot, forkConversationForViewer as p, scheduleInboxSnoozeTimer as pt, requireConversationPendingMessages as q, conversationSummaryFromStoredConversation as qt, decodePageCursor as r, DEFAULT_USER_SETTINGS as rt, readConversationTreeStates as s, settleEventAutomationRuns as st, conversationFeedVersionQuery as t, ingestEventAutomations as tt, readConversationTreeMetricsFromSql as u, dispatchScheduledAutomation as ut, requireWebMessageConversation as v, GET as vt, conversationOperations as w, resolveObjectLinks as wt, archiveConversationOperation as x, readLinkObjectType as xt, decodeConversationCursor as y, readHealthReport as yt, mcpCursorSchema as z, bindMessageAuthorIdentityId as zt };