@sentry/junior 0.312.0 → 0.314.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 (115) hide show
  1. package/dist/{adapter-iIq7ihf7.js → adapter-JARQvoLw.js} +1 -2
  2. package/dist/{adapter-context-BRjEWRy1.js → adapter-context-B4BrJZuS.js} +2 -2
  3. package/dist/{admin-DhInw5K9.js → admin-BXGAySz0.js} +1 -1
  4. package/dist/{agent-runner-C9iDurwX.js → agent-runner-qZU5TR8i.js} +865 -138
  5. package/dist/agent-update-cS7Z9mnG.js +26 -0
  6. package/dist/agent-update-delivery-CZ5M8RDa.js +85 -0
  7. package/dist/api/schema.d.ts +2 -2
  8. package/dist/api/schema.js +6 -6
  9. package/dist/api.d.ts +1 -1
  10. package/dist/api.js +340 -106
  11. package/dist/{app-DRFrC8Mw.d.ts → app-D7tKnw9a.d.ts} +4 -21
  12. package/dist/app.d.ts +2 -2
  13. package/dist/app.js +80 -171
  14. package/dist/{background-compaction-queue-DrKi7w3d.js → background-compaction-queue-C_uIBUvS.js} +6 -17
  15. package/dist/{callback-mFlTUWWx.js → callback-C8SdXCwr.js} +4 -11
  16. package/dist/{catalog-runtime-D7xapBAX.js → catalog-runtime-BLKtnUL3.js} +1 -1
  17. package/dist/{channel-access-CJGfNTdn.js → channel-access-BOL29BG3.js} +6 -6
  18. package/dist/child-message--2G3Ft26.js +19 -0
  19. package/dist/cli/chat.js +18 -21
  20. package/dist/cli/check.js +4 -4
  21. package/dist/cli/main.js +2 -2
  22. package/dist/cli/plugins.js +5 -5
  23. package/dist/cli/snapshot-create.js +5 -5
  24. package/dist/cli/upgrade.d.ts +1 -1
  25. package/dist/cli/upgrade.js +23 -4
  26. package/dist/{config-kXB2Y5tl.js → config-BIfHKNXN.js} +40 -35
  27. package/dist/{continue-in-slack-O6pV5004.js → continue-in-slack-fnmD2Ifb.js} +5 -7
  28. package/dist/{conversation-feed-uNOv_x68.js → conversation-feed-DdFQuQDR.js} +13 -2
  29. package/dist/{logging-dQ9ZRGQ8.js → conversation-privacy-DtZhI91r.js} +188 -2
  30. package/dist/{conversation-turn-CeLbHqdw.js → conversation-turn-DScuDYmN.js} +465 -62
  31. package/dist/create-CrNt4Ewu.js +212 -0
  32. package/dist/{credential-sync-I8VBGk05.js → credential-sync-CtqsGjj1.js} +14 -18
  33. package/dist/{credentialed-Cb6E2phL.js → credentialed-dWRA3-oJ.js} +911 -429
  34. package/dist/{db-LAyyX8tk.js → db-BTmLKZrp.js} +2245 -50
  35. package/dist/{db-BbC5stfa.d.ts → db-DcmzbA55.d.ts} +2 -2
  36. package/dist/{history-CYstOMKX.js → history-CneKY7_V.js} +19 -1
  37. package/dist/{html-BCZ3Xtb_.js → html-B8rBt7F4.js} +5 -7
  38. package/dist/{install-DCFJFkC0.js → install-OtFboxOM.js} +2 -2
  39. package/dist/instrumentation.js +2 -2
  40. package/dist/{lineage-B_m-4TJw.js → lineage-EULJkGO1.js} +1 -2
  41. package/dist/{list-CN2QA2R9.js → list-C5400AlJ.js} +284 -113
  42. package/dist/{thread-state-DhPndWi1.js → mailbox-turn-DL3Lvsm0.js} +4830 -485
  43. package/dist/markers-DUP8aBOp.js +323 -0
  44. package/dist/{media-CYm1QD8T.js → media-FYM-Bl3H.js} +42 -14
  45. package/dist/{message-DSXGj1hM.js → message-DuDelZFr.js} +16 -15
  46. package/dist/{model-input--TrP9hYV.js → model-input-0osF3pBS.js} +3 -3
  47. package/dist/nitro.d.ts +2 -4
  48. package/dist/nitro.js +340 -13
  49. package/dist/{oauth-callback-server-DHCZC6B4.js → oauth-callback-server-DX2fQ7Nq.js} +2 -2
  50. package/dist/{oauth-relay-pPMGnDZt.js → oauth-relay-PwPMdZJv.js} +1 -1
  51. package/dist/{plugins-Bkk0XRo2.js → plugins-BXMdNdyA.js} +1 -1
  52. package/dist/{registry-CZOzddwu.js → registry-D6kS6xYH.js} +1402 -64
  53. package/dist/{statuses-_cRJHXK7.js → reporting-window-C4dbzDiR.js} +1 -27
  54. package/dist/{resolve-cKOQ14Dh.js → resolve-D8CPJcNK.js} +3 -3
  55. package/dist/result-D090hxr5.js +402 -0
  56. package/dist/{runner-DBfUW44l.js → runner-BU7fgrm-.js} +7 -8
  57. package/dist/{sandbox-egress-signals-BVF_xAm1.js → sandbox-egress-signals-BUmVrsoG.js} +1 -1
  58. package/dist/{schema-Bk9Nm2E8.js → schema-7gW9vBpJ.js} +91 -10
  59. package/dist/{schema-BEHKxr4I.d.ts → schema-BB6E0wyV.d.ts} +2105 -2753
  60. package/dist/{service-account-CVYsFjty.js → service-account-plA-uzIB.js} +6 -5
  61. package/dist/{skills-VTnhAJWm.js → skills-CIosT6bS.js} +3 -3
  62. package/dist/{slack-conversation-unfurl-fuLnF1jE.js → slack-conversation-unfurl-CBgZqth6.js} +8 -10
  63. package/dist/spawn-DRjdzh3R.js +46 -0
  64. package/dist/{start-conversation-CEn2KH1A.js → start-conversation-a4NXH4X9.js} +13 -202
  65. package/dist/{store-DFZaN-Ix.js → store-BuhF1QDm.js} +2 -4
  66. package/dist/{task-queue-Cx4Lmjyk.js → task-queue-CrRjFzOh.js} +5 -16
  67. package/dist/{task-runner-CbTwFA6k.js → task-runner-C-pXsgHM.js} +105 -51
  68. package/dist/{thread-context-BkAZDTX2.js → thread-context-CDX4dSZd.js} +8 -10
  69. package/dist/turn-session-routing-CZTRU8IY.js +116 -0
  70. package/dist/turn-wake-Bzq1Efrm.js +154 -0
  71. package/dist/user-customization-B27StpVQ.js +9 -0
  72. package/dist/{validation-nIzMtAVJ.js → validation-bTq88sya.js} +1 -1
  73. package/dist/{vercel-queue-hW90XzbG.js → vercel-queue-nL0Hq3hr.js} +32 -147
  74. package/dist/{version-Brbtz4Qf.js → version-DGUa1dZK.js} +1 -1
  75. package/dist/version.js +1 -1
  76. package/dist/{warmup-BDA5myRK.js → warmup-CCOuIwAS.js} +831 -3254
  77. package/dist/{worker-D63RcaVD.js → worker-AkZg7Dg1.js} +5 -6
  78. package/migrations/0158_keep_legacy_archive_columns.sql +5 -0
  79. package/migrations/0159_conversation_embeddings_fk_validate.sql +5 -0
  80. package/migrations/0160_money_micro_usd_repair.sql +99 -0
  81. package/migrations/0161_agent_config_backfill.sql +34 -0
  82. package/migrations/0162_inbox_item_deliveries.sql +15 -0
  83. package/migrations/0163_pg_trgm.sql +2 -0
  84. package/migrations/0164_search_indexes.sql +4 -0
  85. package/migrations/0165_drop_legacy_archive_columns.sql +4 -0
  86. package/migrations/0166_memory_prefix_index.sql +1 -0
  87. package/migrations/0167_todo_search_indexes.sql +2 -0
  88. package/migrations/0168_todo_inbox_items.sql +4 -0
  89. package/migrations/0169_drop_code_urls.sql +2 -0
  90. package/migrations/meta/0158_snapshot.json +6515 -0
  91. package/migrations/meta/0159_snapshot.json +6515 -0
  92. package/migrations/meta/0160_snapshot.json +6515 -0
  93. package/migrations/meta/0161_snapshot.json +6278 -0
  94. package/migrations/meta/0162_snapshot.json +6404 -0
  95. package/migrations/meta/0163_snapshot.json +6404 -0
  96. package/migrations/meta/0164_snapshot.json +6466 -0
  97. package/migrations/meta/0165_snapshot.json +6466 -0
  98. package/migrations/meta/0166_snapshot.json +6494 -0
  99. package/migrations/meta/0167_snapshot.json +6525 -0
  100. package/migrations/meta/0168_snapshot.json +6525 -0
  101. package/migrations/meta/0169_snapshot.json +6513 -0
  102. package/migrations/meta/_journal.json +84 -0
  103. package/package.json +9 -18
  104. package/skills/design-automation-skill/SKILL.md +2 -3
  105. package/dist/actor-BsBdxDXQ.js +0 -208
  106. package/dist/child-message-DcsritGf.js +0 -179
  107. package/dist/conversation-privacy-L4ja1_W6.js +0 -189
  108. package/dist/executor-SCub-fAq.js +0 -1860
  109. package/dist/fan-out-Cod-yEHG.js +0 -10
  110. package/dist/ingest-BDf3D50j.js +0 -3836
  111. package/dist/result-DcvEOe1r.js +0 -574
  112. package/dist/result-event-type-BdIJuZxg.js +0 -48
  113. package/dist/service-account-Ts4ulcrV.js +0 -931
  114. package/dist/spawn-vxAarlX5.js +0 -73
  115. package/dist/state-C1P3_Ywk.js +0 -161
@@ -1,47 +1,42 @@
1
- import { Aa as ownerConversationId, Ao as getSlackClient, Ar as getDispatchConversationId, Ba as listFiringInboxSnoozeTriggers, Bi as findMatchingEventAutomations, Br as markDispatchCompleted, Ca as dismissOpenInboxItems, Co as verifyScheduledAutomationCredentialSubject, Di as getDashboardLinkFilter, Do as downloadPrivateSlackFile, Dr as claimDispatchMailboxAppend, Eo as SlackActionError, Er as buildDispatchId, Et as createCodeChangePublisher, Fa as SNOOZE_TIMER_EVENT_TYPE, Fr as getPluginDispatchProjection, Ha as settleInboxSnoozes, Ho as updateTimerIndex, Hr as markDispatchRunning, Ii as blockEventAutomation, Ir as isTerminalDispatchStatus, Jn as createPluginAnnotations, Ka as getEventCatalog, Ki as admitEventAutomationRun, Ko as eventGuidance, Li as collectEventAutomationMatchKeys, Lo as streamPrivateSlackFile, Ma as takeInboxItem, Mi as isDashboardLink, Mn as createPluginEmbedder, Mo as isDmChannel, Mr as getDispatchInputMessageId, Ni as parseDashboardConversationLink, No as isSlackRequestTimeout, Nr as getDispatchRecord, Oa as listReplyActionItems, Or as confirmDispatchMailboxAppend, Pa as waitingConversationIdsQuery, Pi as parseDashboardPersonLink, Po as normalizeSlackConversationId, Pr as getDispatchTurnId, Pt as createPluginState, Ro as withSlackRetries, Rr as markDispatchAwaitingResume, So as verifyEventAutomationCredentialSubject, Tt as createPluginInboxItems, Uo as CORE_EVENT_NAMESPACE, Ur as notifyAutomationBlocked, Vr as markDispatchFailed, Wr as addReactionToMessage, Xa as slackChannelMessageReplyThreadTs, Xn as listConversationAnnotationsById, Yi as automationVersionOf, Yn as listConversationAnnotations, Za as slackChannelMessageRunsAutomation, Zr as removeReactionFromMessage, _a as fallbackShortTitle, an as resolveBaseUrl, as as createPluginCache, bo as bindScheduledAutomationCredentialSubject, co as collectEventMatchKeys, cs as completeText, da as readAutomationTitlesByConversationId, di as slackMentionedUserIds, er as lookupSlackUser, fa as recordAutomationExecution, fi as wrapBareSlackUserIds, fo as findMatchingWatches, h as getPlugins, ha as AUTOMATION_ALERT_STEP_FIELD_ID, ho as listConversationsWithWatches, ii as SLACK_USER_MENTION_RE, jr as getDispatchIdForConversation, ki as getDashboardPersonLink, ko as getHeaderString, kr as createOrGetDispatch, kt as createPluginConversationWatches, li as normalizeSlackStatusText, lr as basePluginContext, ma as AUTOMATION_ALERT_STEPS, o as applyPluginFormatMarkdown, oo as cancelSubscriptions, os as completeDecision, pi as truncateStatusText, ps as JUNIOR_NATIVE_EVENT_NAMESPACE, qi as eventAutomationRunLimitReason, r as createUserTokenStore, ra as existingConversationId, rt as storedMessageJson, s as createPluginEventPublisher, tr as lookupSlackUserNames, ui as slackMention, wa as getInboxItem, wi as getDashboardConversationLink, wo as verifySlackDirectCredentialSubject, wr as createPluginLogger, wt as PLUGIN_CHOICE_FIELD_ID, xa as closeInboxItem, xo as bindSlackDirectCredentialSubject, yo as bindEventAutomationCredentialSubject, yt as trimTrailingAssistantMessages, zn as conversationSearchVector, zr as markDispatchBlocked } from "./credentialed-Cb6E2phL.js";
2
- import { L as acquireActiveLock, O as resolveGatewayModel, P as createCache, U as estimateTextTokens, W as textCharsForTokens, a as getSlackBotToken, c as getSlackSigningSecret, ft as isProviderRetryError, n as botConfig, o as getSlackClientId, r as getChatConfig, s as getSlackClientSecret, v as normalizeSlackEmojiName } from "./config-kXB2Y5tl.js";
3
- import { t as mapBounded } from "./fan-out-Cod-yEHG.js";
4
- import { E as withSpan, H as buildSentryConversationUrl, J as normalizeIdentityEmail, S as setTags, T as withLogContext, Y as toOptionalString, b as setSpanAttributes, f as logError, h as logWarn, m as logInfo, n as createChatSdkLogger, o as getActiveTraceContext, p as logException, s as getActiveTraceId, t as buildTurnFailureResponse, y as setSentryUser } from "./logging-dQ9ZRGQ8.js";
1
+ import { $o as normalizeSlackConversationId, $r as markDispatchBlocked, Ba as inboxItemNeedsUserNow, Bo as bindSlackDirectCredentialSubject, Br as buildDispatchId, Bt as createPluginConversationWatches, Ci as normalizeSlackStatusText, Cr as basePluginContext, Di as truncateStatusText, Do as collectEventMatchKeys, Ds as completeText, Ea as recordAutomationExecution, Ei as wrapBareSlackUserIds, Fa as closeInboxItem, Ga as ownerConversationId, Go as SlackActionError, Gr as getDispatchIdForConversation, Gt as createPluginState, Ho as verifyScheduledAutomationCredentialSubject, Hr as confirmDispatchMailboxAppend, Ji as parseDashboardPersonLink, Jo as getHeaderString, Jr as getDispatchTurnId, Ki as isDashboardLink, Ko as downloadPrivateSlackFile, Kr as getDispatchInputMessageId, La as dismissOpenInboxItems, Lt as createCodeChangePublisher, Ms as JUNIOR_NATIVE_EVENT_NAMESPACE, Mt as trimTrailingAssistantMessages, Oa as AUTOMATION_ALERT_STEPS, Po as listConversationsWithWatches, Qo as isSlackRequestTimeout, Qr as markDispatchAwaitingResume, Ra as getInboxItem, Ri as getDashboardConversationLink, Ro as bindEventAutomationCredentialSubject, Rr as createPluginLogger, Ta as readAutomationTitlesByConversationId, Ti as slackMentionedUserIds, To as cancelSubscriptions, Ts as completeDecision, Ui as getDashboardPersonLink, Un as createPluginEmbedder, Uo as verifySlackDirectCredentialSubject, Ur as createOrGetDispatch, Vi as getDashboardLinkFilter, Vo as verifyEventAutomationCredentialSubject, Vr as claimDispatchMailboxAppend, Wa as listReplyActionItems, Wr as getDispatchConversationId, Xi as blockEventAutomation, Xn as conversationSearchVector, Xr as isTerminalDispatchStatus, Yo as getSlackClient, Yr as getPluginDispatchProjection, Zi as collectEventAutomationMatchKeys, Zo as isDmChannel, _a as existingConversationId, ao as listFiringInboxSnoozeTriggers, ar as createPluginConversationChanges, cr as createPluginAnnotations, cs as CORE_EVENT_NAMESPACE, di as removeReactionFromMessage, do as getEventCatalog, ds as eventGuidance, ea as findMatchingEventAutomations, ei as markDispatchCompleted, eo as SNOOZE_TIMER_EVENT_TYPE, gn as resolveBaseUrl, go as slackChannelMessageRunsAutomation, gt as storedMessageJson, h as getPlugins, ho as slackChannelMessageReplyThreadTs, hr as lookupSlackUserNames, ii as addReactionToMessage, ja as fallbackShortTitle, jo as findMatchingWatches, ka as AUTOMATION_ALERT_STEP_FIELD_ID, la as automationVersionOf, lr as listConversationAnnotations, mr as lookupSlackUser, ni as markDispatchRunning, ns as streamPrivateSlackFile, o as applyPluginFormatMarkdown, oa as admitEventAutomationRun, or as PLUGIN_CHOICE_FIELD_ID, qa as takeInboxItem, qi as parseDashboardConversationLink, qr as getDispatchRecord, r as createUserTokenStore, ri as notifyAutomationBlocked, rs as withSlackRetries, s as createPluginEventPublisher, sa as eventAutomationRunLimitReason, so as settleInboxSnoozes, sr as createPluginInboxItems, ss as updateTimerIndex, ti as markDispatchFailed, ur as listConversationAnnotationsById, vi as SLACK_USER_MENTION_RE, wi as slackMention, ws as createPluginCache, zo as bindScheduledAutomationCredentialSubject } from "./credentialed-dWRA3-oJ.js";
2
+ import { L as acquireActiveLock, O as resolveGatewayModel, P as createCache, U as estimateTextTokens, W as textCharsForTokens, a as getSlackBotToken, c as getSlackSigningSecret, ft as isProviderRetryError, gt as mapBounded, n as botConfig, o as getSlackClientId, r as getChatConfig, s as getSlackClientSecret, v as normalizeSlackEmojiName } from "./config-BIfHKNXN.js";
3
+ import { C as logInfo, F as withSpan, O as setSentryUser, P as withLogContext, S as logException, Z as buildSentryConversationUrl, d as createChatSdkLogger, g as getActiveTraceId, h as getActiveTraceContext, it as toOptionalString, j as setTags, k as setSpanAttributes, rt as normalizeIdentityEmail, u as buildTurnFailureResponse, w as logWarn, x as logError } from "./conversation-privacy-DtZhI91r.js";
5
4
  import { h as startSpan, n as captureMessage } from "./sentry-CPbZjomA.js";
6
- import { t as JUNIOR_VERSION } from "./version-Brbtz4Qf.js";
7
- import { f as parseSlackTeamId, i as isActorUserId, n as createSlackActor, o as isUserActor, r as createSlackResumeActor, s as parseActorUserId, t as createActor, u as parseSlackChannelId, v as parseSlackMessageTs } from "./actor-BsBdxDXQ.js";
8
- import { $ as conversationWaitsOnUserSql, $t as resolveActorIdentityId, A as isTopLevelKind, Bn as requireSlackDestination, Cn as conversationIsNotUnsubscribedRoot, Ct as isOnlyAssignee, Dn as viewerMarksFromParticipant, En as rootVisibleToViewer, F as turnBehavior, Gt as hasUserPhoto, H as parseSessionSource, In as nextDetailVersion, Kt as identityAvatarUrl, L as locationFromRow, M as postsRunNotices, Mn as hasAgentTurnUsage, Nn as resolveRootConversationId, On as addAgentTurnUsage, Q as conversationTurnFailedSql, Rn as createSlackDestination, Sn as conversationIsMemberRoot, St as isAutomationAlertItem, T as deliversFinalText, Tn as readMemberParticipants, U as conversationCostOf, X as conversationIsActiveSql, Xt as userAvatarUrlsFromIdentities, Z as conversationStatusSql, Zt as userAvatarUrlsFromJoinedPhotos, _ as readConversationTrees, _n as conversationAccessFromRows, _t as inboxItemOwnedByConversation, a as getConversationStore, b as loadConversationSlackTenantIds, bn as readConversationAccessRows, dn as readCachedUserByEmail, en as saveActorAvatar, et as executionIsActive, f as copyMessageLinks, ft as inboxItemForUser, h as conversationAncestors, hn as canAddConversationMessages, ht as inboxItemNeedsSomeone, it as treeAwaitsAuthorization, jn as agentTurnUsageSchema, m as withConversationEventLock, mt as inboxItemNeedsInput, o as getDb, ot as PLUGIN_INBOX_ITEM_KEY_PREFIX, r as getConversationEventStore, rt as awaitsAuthorizationFrom, s as getSqlExecutor, st as canActOnInboxItem, tt as conversationKindFromRow, ut as canUserReadInboxItem, v as setArchivedAt, vn as createConversationAccessReader, vt as inboxItemPlugin, wn as conversationPinnedForUser, wt as isPluginInboxItem, x as lastMessageAtSql, y as conversationSlackTenantId, yn as readConversationAccessFromSql } from "./db-LAyyX8tk.js";
9
- import { B as juniorAttachments, C as juniorConversationParticipants, H as juniorConversations, K as juniorUsers, L as juniorCodeChanges, M as juniorConversationEvents, P as juniorConversationAnnotations, U as juniorIdentities, V as juniorMessageAttachments, _ as juniorAutomationRuns, c as juniorTodos, g as juniorAutomations, h as juniorInboxItems, n as isPostgresErrorCode, p as juniorInboxItemConversations, q as juniorDestinations, x as juniorAgentInvocations } from "./executor-SCub-fAq.js";
10
- import { d as contextProvenance, p as instructionProvenanceFor, t as KNOWN_CONVERSATION_EVENT_TYPES } from "./history-CYstOMKX.js";
11
- import { a as getStateValues, i as getStateAdapter, o as setStateValues } from "./adapter-iIq7ihf7.js";
12
- import { f as actorLogContext, p as credentialContextForActor } from "./registry-CZOzddwu.js";
13
- import { n as pluginCatalogRuntime } from "./catalog-runtime-D7xapBAX.js";
14
- import { M as shouldEmitDevAgentTrace, S as canPauseConversationDelivery, a as getMcpOAuthCallbackPath, b as safeLinkUrl, c as latestProgressStatus, f as createSlackInboxItemShow, k as RetryableDeliveryError, l as resolveDestinationVisibility, n as executeAgentRun, o as createClientMetadata, r as buildAuthPauseResponse, s as readMcpClientInformation, t as createAgentRunner } from "./agent-runner-C9iDurwX.js";
15
- import { d as PluginMcpClient, u as McpAuthorizationRequiredError, v as getMcpStoredOAuthCredentials } from "./service-account-Ts4ulcrV.js";
16
- import { i as webActorUserIds } from "./state-C1P3_Ywk.js";
17
- import { $ as recordSubscribedReplyRoute, At as PluginCredentialFailureError, C as getConversation, Cn as buildTurnErrorResponse, Dn as finalizeFailedTurnReplyWithEvent, Gt as abandonTurnRecord, Ht as lostWorkerBeforeFirstSave, I as buildDeterministicAssistantMessageId, J as recordAuthorizationCompleted, Kn as getAssistantReplyText, Kt as completeTurnRecord, L as buildDeterministicTurnId, On as getAgentTurnDiagnosticsAttributes, Pt as AuthorizationFlowDisabledError, R as commitAcceptedReply, Rt as clearPendingAuth, U as loadTurnProjection, Ut as pauseLostWorkerTurn, V as loadConversationProjection, Vt as loadTurnCheckpoint, Wt as saveTurnCheckpoint, Xt as listTurnSummaries, Yt as getTurnRecord, Zt as recordTurnSummary, _t as turnHasReply, a as persistThreadStateById, ar as piMessageFromHistoryItem, ct as buildConversationContext, d as cancelHumanFacingPendingMessages, dn as canJoinTurn, dt as isHumanConversationMessage, fn as canShareTurn, ft as latestConversationMessageSeq, gn as loadTurnStart, gt as trimConversationMessages, hn as getTurnLifecycle, ht as recordDeliveredAssistantMessage, i as persistThreadRuntimeState, it as persistConversationMessages, kn as requireTurnFailureEventId, kt as createPluginEgress, l as appendAndEnqueueInboundMessage, lt as estimateConversationMessagesTokens, mt as normalizeConversationText, n as getPersistedSandboxState, nr as persistWithRetry, nt as hydrateConversationMessages, o as coerceThreadConversationState, ot as resolveConversationTitle, pt as markConversationMessage, qt as failTurnRecord, r as getPersistedThreadState, rr as configValueSchema, rt as persistConversationMessageWindow, t as getLocationConfigurationService, ut as getConversationMessageSlackTs, vt as upsertConversationMessage, w as getConversationWorkState, wt as isEventConversationMessage, xt as EVENT_SYSTEM_ACTOR, z as commitMessages } from "./thread-state-DhPndWi1.js";
18
- import { $ as conversationReportStatusSchema, Tt as MAX_ATTACHMENT_BYTES, Zt as answeredChoices, en as isEmptyUserInputAnswer, ft as conversationTreeStateSchema, i as isVisionImageMediaType, kt as readMessageAttachments, ot as activityPreviewText, r as detectImageMediaType, sn as automationTaskText, tn as normalizeUserInputAnswer, tt as conversationSurfaceSchema } from "./media-CYm1QD8T.js";
19
- import { f as readJuniorSecret, t as getVercelConversationWorkQueue } from "./vercel-queue-hW90XzbG.js";
20
- import { At as conversationSubtree, B as TurnInputCommitLostError, C as resolveEventAuthor, G as isTurnInputDeferredError, H as getConversationTurnBoundaryError, I as getTurnUserReplyAttachmentContext, J as markTurnFailed, K as markTurnClosed, L as getTurnUserSlackMessageTs, Nt as isExperimentalFeatureEnabled, P as getTurnUserMessage, Q as getWebAuthorization, R as ConversationTurnBoundaryError, T as resolveBotSlackTeamId, U as isCooperativeTurnYieldError, V as TurnInputDeferredError, W as isTurnInputCommitLostError, Y as startActiveTurn, at as instructionActorFor, dt as renderTaskInput, et as loadInboxItemInput, f as legacyWebMailboxMetadataSchema, it as buildSteeringPiMessage, jt as conversationSubtreeColumns, k as resumeForPersonInput, l as resolveMailboxTurnWork, lt as withoutSavedSteeringMessages, q as markTurnCompleted, t as ingestEvent, tt as savedInputInstruction, v as eventAuthorText, z as CooperativeTurnYieldError } from "./ingest-BDf3D50j.js";
21
- import { $r as findAutomationSkill, An as jsonResponse, Br as readConversationSourceTask, Cn as recordFinishedTurnForAutomatedLimit, Ei as providerCacheTtlMs, Fi as gapSegment, Fn as parseSlackMessageReference, Gn as readSlackRawMessageContext, Kn as resolveSlackChannelIdFromMessage, Lr as takeViewerAutomationAlertStep, Ni as NO_REPLY_GAP_MS, Nn as renderAttachmentText, On as setConversationSubscription, Ot as getChildAgentLabel, Pn as renderBlockText, Ti as connectedState, Tn as executeTurn, Wn as parseSlackThreadId, Zr as AutomationEditError, bn as stopConversation, ci as firstLiveSavingsDate, cn as createPausedTurns, ct as archiveConversation, ei as missingAutomationSkillReason, gn as sendSlackReply, hn as resolveSlackReplyTarget, i as GLOBAL_GAPS_TTL_MS, ji as MINUTE_MS, jn as throwApiError, l as isConversationWorkDone, li as historyPeriodSavings, ln as getPausedTurnRequest, lt as conversationReadPositionQuery, mi as replaceHistorySavings, mn as stopAtAutomatedTurnLimit, mt as deliverInboxItemChange, n as CONVERSATION_STATE_TTL_MS, o as segmentGapsKey, oi as addHistoryPeriod, pn as getTurnAuthorization, r as GLOBAL_GAPS_MAX, si as addHistoryWarmupCost, sn as supersedeTurnForInput, st as readLastUserMessageAtByConversation, t as ANSWER_TOOL_ENDINGS, ti as effectiveTaskOutcomes, u as listConversationWork, un as recordFailedDispatchTurn, wn as AgentRunError, xn as stopChildAgentsOf, zr as ViewerTaskNotFoundError } from "./warmup-BDA5myRK.js";
22
- import { D as getSlackFileId, E as notInheritedByForkChild, M as slackAttachmentsVersionQuery, S as resolveTurnResumeRouting, _ as verifyAttachmentUploads, b as savedTurnMessages, d as recordWebConversationActivity, f as webActorFromUser, j as recordSlackAttachment, k as readAttachmentVisionSummary, l as createAndEnqueueConversation, m as AttachmentUploadError, o as acceptsWebMessages, s as appendAndEnqueueWebMessage, u as createConversationId, x as resolveConversationRouting } from "./start-conversation-CEn2KH1A.js";
23
- import { a as isConversationMember, i as getConversationInfo, l as listThreadReplies, o as isPublicSlackChannel, r as getChannelMessage } from "./channel-access-CJGfNTdn.js";
24
- import { r as isFileAttachment, s as storeAttachment } from "./store-DFZaN-Ix.js";
25
- import { u as OPEN_TODO_STATUSES } from "./result-event-type-BdIJuZxg.js";
26
- import { n as getTurnRequestDeadline } from "./callback-mFlTUWWx.js";
5
+ import { t as JUNIOR_VERSION } from "./version-DGUa1dZK.js";
6
+ import { A as lastMessageAtSql, An as conversationAccessFromRows, Ar as juniorConversationEvents, At as inboxItemPlugin, Bn as rootVisibleToViewer, Br as juniorConversations, C as createSlackActor, Ct as canUserReadInboxItem, D as parseActorUserId, Dt as inboxItemNeedsInput, E as isUserActor, Fr as juniorCodeChanges, Ft as isAutomationAlertItem, Gn as agentTurnUsageSchema, Gr as juniorDestinations, Hn as addAgentTurnUsage, In as conversationIsMemberRoot, It as isOnlyAssignee, K as locationFromRow, Kn as hasAgentTurnUsage, Ln as conversationIsNotUnsubscribedRoot, Lt as isPluginInboxItem, Mn as readConversationAccessFromSql, Mr as juniorConversationAnnotations, N as withConversationMutationLock, Nn as readConversationAccessRows, Nt as inboxItemTodo, On as canAddConversationMessages, P as deliversFinalText, Q as conversationCostOf, Rn as conversationPinnedForUser, Rr as juniorAttachments, S as createActor, T as isActorUserId, Tt as inboxItemForUser, V as postsRunNotices, Vn as viewerMarksFromParticipant, Vr as juniorIdentities, W as turnBehavior, Wr as juniorUsers, Xn as nextDetailVersion, Z as parseSessionSource, a as getDb, an as identityAvatarUrl, b as conversationSlackTenantId, bi as parseSlackMessageTs, bt as canActOnInboxItem, c as isPostgresErrorCode, ci as createSlackDestination, ct as conversationTurnFailedSql, dt as conversationKindFromRow, fi as parseSlackChannelId, fn as resolveActorIdentityId, fr as juniorInboxItemConversations, g as conversationAncestors, gt as PLUGIN_INBOX_ITEM_KEY_PREFIX, h as withConversationEventLock, hr as juniorInboxItems, i as getConversationStore, in as hasUserPhoto, jn as createConversationAccessReader, kt as inboxItemOwnedByConversation, ln as userAvatarUrlsFromIdentities, lt as conversationWaitsOnUserSql, mi as parseSlackTeamId, mt as treeAwaitsAuthorization, n as getConversationEventStore, o as getSqlExecutor, ot as conversationIsActiveSql, p as copyMessageLinks, pn as saveActorAvatar, pt as awaitsAuthorizationFrom, qn as resolveRootConversationId, rr as juniorTodos, st as conversationStatusSql, ui as requireSlackDestination, un as userAvatarUrlsFromJoinedPhotos, ut as executionIsActive, v as readConversationTrees, vr as juniorAutomations, w as createSlackResumeActor, wn as readCachedUserByEmail, wr as juniorConversationParticipants, x as loadConversationSlackTenantIds, y as setArchivedAt, yr as juniorAutomationRuns, yt as TODO_INBOX_ITEM_KEY_PREFIX, z as isTopLevelKind, zn as readMemberParticipants, zr as juniorMessageAttachments } from "./db-BTmLKZrp.js";
7
+ import { d as contextProvenance, h as OPEN_TODO_STATUSES, p as instructionProvenanceFor, t as KNOWN_CONVERSATION_EVENT_TYPES } from "./history-CneKY7_V.js";
8
+ import { a as getStateValues, i as getStateAdapter, o as setStateValues } from "./adapter-JARQvoLw.js";
9
+ import { G as actorLogContext, K as credentialContextForActor, M as webActorUserIds, _ as PluginMcpClient, g as McpAuthorizationRequiredError, w as getMcpStoredOAuthCredentials } from "./registry-D6kS6xYH.js";
10
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-BLKtnUL3.js";
11
+ import { A as canPauseConversationDelivery, C as safeLinkUrl, E as sendSlackReply, L as RetryableDeliveryError, T as resolveSlackReplyTarget, a as getMcpOAuthCallbackPath, c as latestProgressStatus, f as createInboxItemShow, l as resolveDestinationVisibility, m as pushInboxSnoozeWakes, n as executeAgentRun, o as createClientMetadata, r as buildAuthPauseResponse, s as readMcpClientInformation, t as createAgentRunner, z as shouldEmitDevAgentTrace } from "./agent-runner-qZU5TR8i.js";
12
+ import { $n as loadTurnProjection, $r as failTurnRecord, An as conversationSubtreeColumns, Ar as isEventConversationMessage, Br as AuthorizationFlowDisabledError, Bt as getConversationWorkState, Cr as recordDeliveredAssistantMessage, Dn as buildDeterministicAssistantMessageId, Dt as cancelHumanFacingPendingMessages, Er as upsertConversationMessage, Fr as createPluginEgress, H as resolveEventAuthor, Ir as PluginCredentialFailureError, Jn as commitAcceptedReply, Jr as lostWorkerBeforeFirstSave, L as eventAuthorText, Mi as finalizeFailedTurnReplyWithEvent, Mn as isExperimentalFeatureEnabled, Ni as getAgentTurnDiagnosticsAttributes, O as notInheritedByForkChild, Oi as buildTurnErrorResponse, On as buildDeterministicTurnId, Or as EVENT_SYSTEM_ACTOR, Pi as requireTurnFailureEventId, Q as getTurnUserMessage, Qr as completeTurnRecord, Qt as savedInputInstruction, Si as loadTurnStart, Sr as normalizeConversationText, St as getWebAuthorization, Tr as turnHasReply, Tt as appendAndEnqueueInboundMessage, W as resolveBotSlackTeamId, Wr as clearPendingAuth, Xr as saveTurnCheckpoint, Yn as commitMessages, Yr as pauseLostWorkerTurn, Zi as getAssistantReplyText, Zn as loadConversationProjection, Zr as abandonTurnRecord, Zt as loadInboxItemInput, _i as canShareTurn, _n as setTodoStatusByUser, _r as estimateConversationMessagesTokens, _t as persistThreadRuntimeState, a as resolveMailboxTurnWork, at as TurnInputDeferredError, br as latestConversationMessageSeq, c as legacyWebMailboxMetadataSchema, ca as configValueSchema, cn as renderTaskInput, cr as recordSubscribedReplyRoute, ct as isTurnInputCommitLostError, dr as hydrateConversationMessages, dt as markTurnCompleted, ei as getTurnRecord, et as getTurnUserReplyAttachmentContext, fr as persistConversationMessageWindow, ft as markTurnFailed, gi as canJoinTurn, gr as buildConversationContext, gt as getPersistedThreadState, ht as getPersistedSandboxState, it as TurnInputCommitLostError, kn as conversationSubtree, lt as isTurnInputDeferredError, mr as resolveConversationTitle, mt as getLocationConfigurationService, ni as recordTurnSummary, nn as instructionActorFor, nt as ConversationTurnBoundaryError, on as withoutSavedSteeringMessages, ot as getConversationTurnBoundaryError, pr as persistConversationMessages, pt as startActiveTurn, q as resumeForPersonInput, qr as loadTurnCheckpoint, rr as recordAuthorizationCompleted, rt as CooperativeTurnYieldError, sa as persistWithRetry, st as isCooperativeTurnYieldError, ti as listTurnSummaries, tn as buildSteeringPiMessage, tt as getTurnUserSlackMessageTs, ua as piMessageFromHistoryItem, ut as markTurnClosed, vr as getConversationMessageSlackTs, vt as persistThreadStateById, wr as trimConversationMessages, xi as getTurnLifecycle, xr as markConversationMessage, yr as isHumanConversationMessage, yt as coerceThreadConversationState, zt as getConversation } from "./mailbox-turn-DL3Lvsm0.js";
13
+ import { $ as conversationReportStatusSchema, Tt as MAX_ATTACHMENT_BYTES, Zt as answeredChoices, en as isEmptyUserInputAnswer, fn as automationTaskText, ft as conversationTreeStateSchema, gt as renameConversationResponseSchema, ht as renameConversationBodySchema, i as isVisionImageMediaType, kt as readMessageAttachments, ot as activityPreviewText, r as detectImageMediaType, tn as normalizeUserInputAnswer, tt as conversationSurfaceSchema } from "./media-FYM-Bl3H.js";
14
+ import { f as readJuniorSecret, t as getVercelConversationWorkQueue } from "./vercel-queue-nL0Hq3hr.js";
15
+ import { $n as readConversationSourceTask, Br as connectedState, Bt as setConversationSubscription, Cr as historyPeriodSavings, Ct as conversationReadPositionQuery, Gt as renderAttachmentText, Ht as jsonResponse, Jr as NO_REPLY_GAP_MS, Kr as MINUTE_MS, Kt as renderBlockText, O as ingestEvent, Or as replaceHistorySavings, Ot as deliverInboxItemChange, Sr as firstLiveSavingsDate, St as archiveConversation, Ut as throwApiError, Vr as providerCacheTtlMs, Xr as gapSegment, Yn as takeViewerAutomationAlertStep, Zn as ViewerTaskNotFoundError, br as addHistoryPeriod, fr as findAutomationSkill, i as GLOBAL_GAPS_TTL_MS, in as resolveSlackChannelIdFromMessage, l as isConversationWorkDone, mr as effectiveTaskOutcomes, n as CONVERSATION_STATE_TTL_MS, nn as parseSlackThreadId, o as segmentGapsKey, pr as missingAutomationSkillReason, qt as parseSlackMessageReference, r as GLOBAL_GAPS_MAX, rn as readSlackRawMessageContext, st as stopChildAgentsOf, t as ANSWER_TOOL_ENDINGS, u as listConversationWork, ur as AutomationEditError, wt as markConversationRead, xr as addHistoryWarmupCost, xt as readLastUserMessageAtByConversation } from "./warmup-CCOuIwAS.js";
16
+ import { C as recordSlackAttachment, _ as verifyAttachmentUploads, d as recordWebConversationActivity, f as webActorFromUser, l as createAndEnqueueConversation, m as AttachmentUploadError, o as acceptsWebMessages, s as appendAndEnqueueWebMessage, u as createConversationId, w as slackAttachmentsVersionQuery, x as readAttachmentVisionSummary, y as getSlackFileId } from "./start-conversation-a4NXH4X9.js";
17
+ import { a as isConversationMember, i as getConversationInfo, l as listThreadReplies, o as isPublicSlackChannel, r as getChannelMessage } from "./channel-access-BOL29BG3.js";
18
+ import { r as isFileAttachment, s as storeAttachment } from "./store-BuhF1QDm.js";
27
19
  import { t as webMessageId } from "./web-message-id-C6P83ans.js";
28
- import { t as runWithSlackInstallation } from "./adapter-context-BRjEWRy1.js";
29
- import { B as webPageObjectCard, E as healthReportSchema, L as conversationObjectCard, R as messageObjectCard, _ as cancelConversationPendingMessagesResponseSchema, b as conversationPendingMessageDeliverySchema, c as pinConversationBodySchema, f as archiveConversationBodySchema, g as cancelConversationPendingMessagesBodySchema, h as conversationAutoArchiveSchema, l as pinConversationResponseSchema, m as archiveDoneConversationsResponseSchema, o as conversationSubscriptionBodySchema, p as archiveConversationResponseSchema, r as stopConversationTurnResponseSchema, s as conversationSubscriptionResponseSchema, z as personObjectCard } from "./conversation-feed-uNOv_x68.js";
30
- import { a as withTurnSpan, i as turnInputTelemetry, n as createConversationTurnWorker, r as getTurnInputSpanAttributes } from "./conversation-turn-CeLbHqdw.js";
31
- import { n as attachmentFactLines, r as buildStoredAttachmentPromptText } from "./model-input--TrP9hYV.js";
32
- import { i as enqueueAgentInvocationResult, n as createDeliverToParent, s as withAgentInvocationResultActors, t as createChildConversationWorker } from "./result-DcvEOe1r.js";
33
- import { t as bindMessageAgent } from "./message-DSXGj1hM.js";
34
- import { t as readConversationLineage } from "./lineage-B_m-4TJw.js";
35
- import { t as bindSpawnAgent } from "./spawn-vxAarlX5.js";
36
- import { a as buildDeliveredTurnStatePatch, i as persistAuthPauseTurnState, n as loadThreadContextTrimFloor, o as loadPendingMessageCards, r as completeAuthPauseTurn, t as buildTurnThreadContext } from "./thread-context-BkAZDTX2.js";
37
- import { a as readConversationEventPage, n as scheduleSessionCompletedPluginTasks, o as readConversationEventPageAfter, s as readConversationEventPageAround } from "./task-runner-CbTwFA6k.js";
38
- import { s as sendVercelPluginTask } from "./task-queue-Cx4Lmjyk.js";
39
- import { r as canContinueInSlack } from "./continue-in-slack-O6pV5004.js";
20
+ import { l as getChildAgentLabel, n as createDeliverToParent, o as withAgentInvocationResultActors, t as createChildConversationWorker } from "./result-D090hxr5.js";
21
+ import { n as getTurnRequestDeadline } from "./callback-C8SdXCwr.js";
22
+ import { i as savedTurnMessages, n as resolveTurnResumeRouting, t as resolveConversationRouting } from "./turn-session-routing-CZTRU8IY.js";
23
+ import { t as runWithSlackInstallation } from "./adapter-context-B4BrJZuS.js";
24
+ import { B as webPageObjectCard, E as healthReportSchema, L as conversationObjectCard, R as messageObjectCard, _ as cancelConversationPendingMessagesResponseSchema, b as conversationPendingMessageDeliverySchema, c as pinConversationBodySchema, f as archiveConversationBodySchema, g as cancelConversationPendingMessagesBodySchema, h as conversationAutoArchiveSchema, l as pinConversationResponseSchema, m as archiveDoneConversationsResponseSchema, o as conversationSubscriptionBodySchema, p as archiveConversationResponseSchema, r as stopConversationTurnResponseSchema, s as conversationSubscriptionResponseSchema, z as personObjectCard } from "./conversation-feed-DdFQuQDR.js";
25
+ 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-DScuDYmN.js";
26
+ import { n as attachmentFactLines, r as buildStoredAttachmentPromptText } from "./model-input-0osF3pBS.js";
27
+ import { t as bindMessageAgent } from "./message-DuDelZFr.js";
28
+ import { t as readConversationLineage } from "./lineage-EULJkGO1.js";
29
+ import { t as bindSpawnAgent } from "./spawn-DRjdzh3R.js";
30
+ import { a as buildDeliveredTurnStatePatch, i as persistAuthPauseTurnState, n as loadThreadContextTrimFloor, o as loadPendingMessageCards, r as completeAuthPauseTurn, t as buildTurnThreadContext } from "./thread-context-CDX4dSZd.js";
31
+ import { c as readConversationEventPage, l as readConversationEventPageAfter, n as scheduleSessionCompletedPluginTasks, u as readConversationEventPageAround } from "./task-runner-C-pXsgHM.js";
32
+ import { a as sendVercelPluginTask } from "./task-queue-CrRjFzOh.js";
33
+ import { n as getPausedTurnRequest, o as getTurnAuthorization, r as recordFailedDispatchTurn, t as createPausedTurns } from "./turn-wake-Bzq1Efrm.js";
34
+ import { r as canContinueInSlack } from "./continue-in-slack-fnmD2Ifb.js";
40
35
  import * as z from "zod";
41
36
  import pLimit from "p-limit";
42
37
  import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
43
38
  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";
44
- import { and, asc, count, desc, eq, exists, gt, gte, inArray, isNotNull, isNull, lt, lte, min, ne, not, or, sql } from "drizzle-orm";
39
+ import { and, asc, count, desc, eq, exists, gt, gte, inArray, isNotNull, isNull, like, lt, lte, min, ne, not, or, sql } from "drizzle-orm";
45
40
  import { alias } from "drizzle-orm/pg-core";
46
41
  import { Message, ThreadImpl, stringifyMarkdown } from "chat";
47
42
  import net from "node:net";
@@ -6767,10 +6762,6 @@ function createConversationWork(options) {
6767
6762
  },
6768
6763
  runTurn: runtime.runDispatchTurn
6769
6764
  });
6770
- const enqueueResult = async (invocation) => await enqueueAgentInvocationResult(invocation, {
6771
- queue: options.queue,
6772
- state: options.state
6773
- });
6774
6765
  const conversationTurnWorker = createConversationTurnWorker(options.agentRunner, createSlackSystemTurnDelivery({
6775
6766
  getSlackAdapter: options.getSlackAdapter,
6776
6767
  state: options.state
@@ -6778,9 +6769,7 @@ function createConversationWork(options) {
6778
6769
  queue: options.queue,
6779
6770
  state: options.state
6780
6771
  }));
6781
- const childWorker = createChildConversationWorker(options.agentRunner, {
6782
- enqueueResult,
6783
- queue: options.queue,
6772
+ const childWorker = createChildConversationWorker({
6784
6773
  runTurn: conversationTurnWorker,
6785
6774
  state: options.state
6786
6775
  });
@@ -6805,7 +6794,7 @@ function createConversationWork(options) {
6805
6794
  return await destinationWorker(context);
6806
6795
  };
6807
6796
  const runByKind = async (context, topLevel) => {
6808
- if (!topLevel) return await childWorker(context);
6797
+ const worker = topLevel ? runRoot : childWorker;
6809
6798
  const readStopSignal = context.stopSignal;
6810
6799
  let stopSignal;
6811
6800
  const stopLateChildAgents = async () => {
@@ -6813,7 +6802,7 @@ function createConversationWork(options) {
6813
6802
  };
6814
6803
  let result;
6815
6804
  try {
6816
- result = await runRoot({
6805
+ result = await worker({
6817
6806
  ...context,
6818
6807
  stopSignal: readStopSignal ? () => stopSignal = readStopSignal() : void 0
6819
6808
  });
@@ -7930,11 +7919,19 @@ async function loadEvents(conversationIds) {
7930
7919
  }).from(events).innerJoin(juniorConversations, eq(juniorConversations.conversationId, events.conversationId)).where(and(inArray(events.conversationId, conversationIds), or(eq(events.type, "assistant_message"), and(isToolResult, inArray(sql`(${message})->>'toolName'`, Object.keys(ANSWER_TOOL_ENDINGS)), sql`(${message})->>'isError' IS DISTINCT FROM 'true'`), and(isUserMessage, sql`(${events.payload}->'provenance'->>'authority') = 'instruction'`), isWarmupEvent), gte(events.createdAt, juniorConversations.createdAt))).orderBy(events.conversationId, events.seq);
7931
7920
  }
7932
7921
  async function loadChildAgents(conversationIds) {
7933
- return await getDb().select({
7934
- conversationId: juniorAgentInvocations.parentConversationId,
7935
- createdAt: juniorAgentInvocations.createdAt,
7936
- terminalAt: juniorAgentInvocations.terminalAt
7937
- }).from(juniorAgentInvocations).where(inArray(juniorAgentInvocations.parentConversationId, conversationIds));
7922
+ const events = juniorConversationEvents;
7923
+ const rows = await getDb().select({
7924
+ conversationId: events.conversationId,
7925
+ createdAt: events.createdAt,
7926
+ markerId: sql`${events.payload}->>'subagentInvocationId'`,
7927
+ type: events.type
7928
+ }).from(events).where(and(inArray(events.conversationId, conversationIds), inArray(events.type, ["subagent_started", "subagent_ended"])));
7929
+ const endedAt = new Map(rows.flatMap((row) => row.type === "subagent_ended" && row.markerId ? [[`${row.conversationId}\0${row.markerId}`, row.createdAt]] : []));
7930
+ return rows.flatMap((row) => row.type === "subagent_started" ? [{
7931
+ conversationId: row.conversationId,
7932
+ createdAt: row.createdAt,
7933
+ terminalAt: endedAt.get(`${row.conversationId}\0${row.markerId}`) ?? null
7934
+ }] : []);
7938
7935
  }
7939
7936
  /**
7940
7937
  * Replay the model calls of one Conversation the way the recorders in
@@ -8419,12 +8416,30 @@ const INBOX_SNOOZE_TIMER_INDEX = {
8419
8416
  batchSize: 500,
8420
8417
  key: "junior:inbox-snoozes:due"
8421
8418
  };
8419
+ /** The To-do of each resolved item that shows one, for its snoozer. */
8420
+ async function resolvedTodos(db, resolved) {
8421
+ if (resolved.length === 0) return [];
8422
+ const items = await db.select({
8423
+ dedupeKey: juniorInboxItems.dedupeKey,
8424
+ id: juniorInboxItems.id
8425
+ }).from(juniorInboxItems).where(and(inArray(juniorInboxItems.id, resolved.map((row) => row.inboxItemId)), like(juniorInboxItems.dedupeKey, `${TODO_INBOX_ITEM_KEY_PREFIX}%`)));
8426
+ const todoOf = new Map(items.map((item) => [item.id, inboxItemTodo(item)]));
8427
+ return resolved.flatMap((row) => {
8428
+ const todo = todoOf.get(row.inboxItemId);
8429
+ return todo ? [{
8430
+ ...todo,
8431
+ ...row
8432
+ }] : [];
8433
+ });
8434
+ }
8422
8435
  /**
8423
8436
  * Fire the snooze triggers that one Event matches. A `resolve` trigger
8424
- * dismisses the item and cancels its snooze; a `wake` trigger ends the
8437
+ * cancels the snooze and closes the item: it dismisses it, or marks the
8438
+ * To-do of a To-do item done for the person who snoozed it, so the agent
8439
+ * sees the change in its next `<todo-delta>`. A `wake` trigger ends the
8425
8440
  * snooze, which records `reason`. When one Event fires both on a snooze,
8426
- * `resolve` wins. A snooze that already ended ignores the Event. Returns
8427
- * the number of items woken.
8441
+ * `resolve` wins. A snooze that already ended ignores the Event. Each
8442
+ * woken snooze pushes to its User. Returns the number of items woken.
8428
8443
  */
8429
8444
  async function fireTriggers(db, event, reason, nowMs) {
8430
8445
  const triggers = (await listFiringInboxSnoozeTriggers(db, {
@@ -8432,25 +8447,37 @@ async function fireTriggers(db, event, reason, nowMs) {
8432
8447
  identifiers: event.identifiers,
8433
8448
  namespace: event.namespace
8434
8449
  })).filter((trigger) => eventMatches(trigger.match ?? void 0, event.data));
8435
- const resolving = new Set(triggers.filter((trigger) => trigger.outcome === "resolve").map((trigger) => trigger.snoozeId));
8450
+ const resolving = new Map(triggers.filter((trigger) => trigger.outcome === "resolve").map((trigger) => [trigger.snoozeId, trigger]));
8436
8451
  const waking = new Set(triggers.filter((trigger) => !resolving.has(trigger.snoozeId)).map((trigger) => trigger.snoozeId));
8437
8452
  if (resolving.size === 0 && waking.size === 0) return 0;
8438
- return db.transaction(async (tx) => {
8439
- const resolvedItemIds = await settleInboxSnoozes(tx, {
8440
- snoozeIds: [...resolving],
8453
+ const todos = await resolvedTodos(db, [...resolving.values()]);
8454
+ await mapBounded(todos, (todo) => setTodoStatusByUser(getSqlExecutor(), {
8455
+ assignedOnly: true,
8456
+ conversationId: todo.conversationId,
8457
+ id: todo.id,
8458
+ nowMs,
8459
+ status: "done",
8460
+ userId: todo.userId
8461
+ }));
8462
+ const todoItemIds = new Set(todos.map((todo) => todo.inboxItemId));
8463
+ const woken = await db.transaction(async (tx) => {
8464
+ const resolved = await settleInboxSnoozes(tx, {
8465
+ snoozeIds: [...resolving.keys()],
8441
8466
  state: "cancelled"
8442
8467
  });
8443
8468
  await dismissOpenInboxItems(tx, {
8444
- ids: resolvedItemIds,
8469
+ ids: resolved.map((row) => row.inboxItemId).filter((id) => !todoItemIds.has(id)),
8445
8470
  nowMs,
8446
8471
  reason: "A snooze trigger resolved it."
8447
8472
  });
8448
- return (await settleInboxSnoozes(tx, {
8473
+ return await settleInboxSnoozes(tx, {
8449
8474
  reason,
8450
8475
  snoozeIds: [...waking],
8451
8476
  state: "woken"
8452
- })).length;
8477
+ });
8453
8478
  });
8479
+ await pushInboxSnoozeWakes(woken);
8480
+ return woken.length;
8454
8481
  }
8455
8482
  /** Fire the snooze triggers that one published Event matches. */
8456
8483
  async function fireInboxSnoozeTriggers(db, event, nowMs = Date.now()) {
@@ -8633,6 +8660,10 @@ function createHeartbeatContext(args) {
8633
8660
  }) },
8634
8661
  cache: createPluginCache(pluginName),
8635
8662
  codeChanges: createCodeChangePublisher(pluginName),
8663
+ conversationChanges: createPluginConversationChanges({
8664
+ plugin: pluginName,
8665
+ show: args.showInboxItem ?? (async () => {})
8666
+ }),
8636
8667
  nowMs: args.nowMs,
8637
8668
  db: getDb(),
8638
8669
  embedder: createPluginEmbedder(pluginName),
@@ -8838,10 +8869,12 @@ function runCutoff(run) {
8838
8869
  /**
8839
8870
  * True when the participant row's root and every child conversation are idle
8840
8871
  * and had no activity after the cutoff. Child activity does not move the
8841
- * root's `lastActivityAt`, so the whole tree is checked.
8872
+ * root's `lastActivityAt`, so the whole tree is checked. A stopped
8873
+ * conversation counts from its stop: held input still saves Messages, which
8874
+ * would keep it from ever being quiet.
8842
8875
  */
8843
8876
  function treeIsQuiet(run) {
8844
- const active = getDb().select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(or(eq(juniorConversations.conversationId, juniorConversationParticipants.rootConversationId), eq(juniorConversations.rootConversationId, juniorConversationParticipants.rootConversationId)), or(ne(juniorConversations.executionStatus, "idle"), gt(juniorConversations.lastActivityAt, runCutoff(run)))));
8877
+ const active = getDb().select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(or(eq(juniorConversations.conversationId, juniorConversationParticipants.rootConversationId), eq(juniorConversations.rootConversationId, juniorConversationParticipants.rootConversationId)), or(ne(juniorConversations.executionStatus, "idle"), gt(sql`coalesce(${juniorConversations.stoppedAt}, ${juniorConversations.lastActivityAt})`, runCutoff(run)))));
8845
8878
  return sql`not exists (${active})`;
8846
8879
  }
8847
8880
  /**
@@ -8859,16 +8892,6 @@ function treeNeedsNoOne() {
8859
8892
  return sql`not exists (${needing})`;
8860
8893
  }
8861
8894
  /**
8862
- * True when no open Inbox item on the participant row's root or a child
8863
- * conversation needs a person. Archive applies to everyone, so a
8864
- * conversation that waits on anyone must stay in the feed.
8865
- */
8866
- function notWaitingOnAnyone() {
8867
- const linked = alias(juniorConversations, "linked_conversation");
8868
- const waiting = getDb().select({ itemId: juniorInboxItemConversations.itemId }).from(juniorInboxItemConversations).innerJoin(juniorInboxItems, eq(juniorInboxItems.id, juniorInboxItemConversations.itemId)).innerJoin(linked, eq(linked.conversationId, juniorInboxItemConversations.conversationId)).where(and(inboxItemNeedsSomeone(), or(eq(linked.conversationId, juniorConversationParticipants.rootConversationId), eq(linked.rootConversationId, juniorConversationParticipants.rootConversationId))));
8869
- return sql`not exists (${waiting})`;
8870
- }
8871
- /**
8872
8895
  * True when no subscribed participant of the row's root pinned it or turned
8873
8896
  * auto-archive off for it. Archive applies to everyone, so one person's run
8874
8897
  * must not undo another person's pin or manual restore. A person who
@@ -8879,11 +8902,14 @@ function noParticipantKeepsRoot() {
8879
8902
  const keeping = getDb().select({ userId: keeper.userId }).from(keeper).where(and(eq(keeper.rootConversationId, juniorConversationParticipants.rootConversationId), isNull(keeper.unsubscribedAt), or(isNotNull(keeper.pinnedAt), eq(keeper.autoArchive, false))));
8880
8903
  return sql`not exists (${keeping})`;
8881
8904
  }
8882
- /** True when the participant row's root is not archived. */
8883
- function rootIsUnarchived() {
8905
+ /**
8906
+ * True when the participant row's root is not archived and is not a Lead.
8907
+ * The Lead is the dashboard home, not a feed row, so it is never archived.
8908
+ */
8909
+ function rootIsArchivable() {
8884
8910
  const root = alias(juniorConversations, "archive_root");
8885
- const unarchived = getDb().select({ conversationId: root.conversationId }).from(root).where(and(eq(root.conversationId, juniorConversationParticipants.rootConversationId), isNull(root.archivedAt)));
8886
- return sql`exists (${unarchived})`;
8911
+ const eligible = getDb().select({ conversationId: root.conversationId }).from(root).where(and(eq(root.conversationId, juniorConversationParticipants.rootConversationId), isNull(root.archivedAt), or(isNull(root.kind), ne(root.kind, "lead"))));
8912
+ return sql`exists (${eligible})`;
8887
8913
  }
8888
8914
  /**
8889
8915
  * Conditions that a participant row must meet when it is selected and again
@@ -8891,7 +8917,7 @@ function rootIsUnarchived() {
8891
8917
  * changed setting wins over a stale read.
8892
8918
  */
8893
8919
  function archivableRow(run) {
8894
- return and(eq(juniorConversationParticipants.userId, run.userId), isNull(juniorConversationParticipants.unsubscribedAt), rootIsUnarchived(), noParticipantKeepsRoot(), lte(juniorConversationParticipants.lastMessageAt, runCutoff(run)), runOptsIn(run), run.kind === "scheduled" ? sql`${juniorUsers.autoArchiveGraceHours} <= ${run.graceHours}` : void 0, treeIsQuiet(run), treeNeedsNoOne(), notWaitingOnAnyone());
8920
+ return and(eq(juniorConversationParticipants.userId, run.userId), isNull(juniorConversationParticipants.unsubscribedAt), rootIsArchivable(), noParticipantKeepsRoot(), lte(juniorConversationParticipants.lastMessageAt, runCutoff(run)), runOptsIn(run), run.kind === "scheduled" ? sql`${juniorUsers.autoArchiveGraceHours} <= ${run.graceHours}` : void 0, treeIsQuiet(run), treeNeedsNoOne());
8895
8921
  }
8896
8922
  /**
8897
8923
  * One page of the user's participant rows on unarchived roots that may be
@@ -8933,10 +8959,7 @@ async function selectDoneRoots(rootIds, cutoffMs) {
8933
8959
  async function archiveRoots(run, rootConversationIds) {
8934
8960
  if (rootConversationIds.length === 0) return 0;
8935
8961
  const archivable = getDb().select({ userId: juniorConversationParticipants.userId }).from(juniorConversationParticipants).innerJoin(juniorUsers, eq(juniorUsers.id, juniorConversationParticipants.userId)).where(and(eq(juniorConversationParticipants.rootConversationId, juniorConversations.conversationId), archivableRow(run)));
8936
- return (await getDb().update(juniorConversations).set({
8937
- archivedAt: run.now,
8938
- detailVersion: nextDetailVersion
8939
- }).where(and(inArray(juniorConversations.conversationId, rootConversationIds), isNull(juniorConversations.archivedAt), sql`exists (${archivable})`)).returning({ conversationId: juniorConversations.conversationId })).length;
8962
+ return await setArchivedAt(getDb(), rootConversationIds, run.now, and(isNull(juniorConversations.archivedAt), sql`exists (${archivable})`));
8940
8963
  }
8941
8964
  /** Archive every done conversation of one user and count the rows. */
8942
8965
  async function archiveUserDoneConversations(run) {
@@ -8963,7 +8986,7 @@ async function archiveUserDoneConversations(run) {
8963
8986
  * conversation. Most users never turn it on, so the sweep reads only these.
8964
8987
  */
8965
8988
  async function selectAutoArchiveUsers() {
8966
- const optedInConversation = getDb().select({ userId: juniorConversationParticipants.userId }).from(juniorConversationParticipants).where(and(eq(juniorConversationParticipants.userId, juniorUsers.id), eq(juniorConversationParticipants.autoArchive, true), rootIsUnarchived()));
8989
+ const optedInConversation = getDb().select({ userId: juniorConversationParticipants.userId }).from(juniorConversationParticipants).where(and(eq(juniorConversationParticipants.userId, juniorUsers.id), eq(juniorConversationParticipants.autoArchive, true), rootIsArchivable()));
8967
8990
  return await getDb().select({
8968
8991
  graceHours: juniorUsers.autoArchiveGraceHours,
8969
8992
  id: juniorUsers.id
@@ -9368,7 +9391,7 @@ function reviewItemChange(action, user) {
9368
9391
  kind: "taken",
9369
9392
  user
9370
9393
  };
9371
- if (action === "submit") return {
9394
+ if (action === "submit" || action === "done") return {
9372
9395
  kind: "submitted",
9373
9396
  user
9374
9397
  };
@@ -9412,6 +9435,11 @@ async function actOnInboxItem(args) {
9412
9435
  const nowMs = args.nowMs ?? Date.now();
9413
9436
  const db = getDb();
9414
9437
  const item = await readInboxItemForUser(user, args.id);
9438
+ if (inboxItemTodo(item)) {
9439
+ if (action !== "done" && action !== "dismiss") throw new InboxItemActionError("invalid", "A To-do item takes only Done or Dismiss.");
9440
+ return await closeTodoItem(item, user, nowMs, action);
9441
+ }
9442
+ if (action === "done") throw new InboxItemActionError("invalid", "Only a To-do item can be marked done.");
9415
9443
  if (action === "take") {
9416
9444
  if (item.status !== "open") throw new InboxItemActionError("conflict", "Inbox item is closed.");
9417
9445
  if (!canActOnInboxItem(item, user.id)) throw new InboxItemActionError("forbidden", "Only an assignee can take this item.");
@@ -9470,6 +9498,30 @@ async function actOnInboxItem(args) {
9470
9498
  return closed;
9471
9499
  }
9472
9500
  /**
9501
+ * Close a To-do item for its assignee through its To-do: Done marks the
9502
+ * To-do done, and Dismiss drops it. The To-do change closes the item as
9503
+ * done or dismissed (`syncTodoInboxItems`), and the agent sees it in its
9504
+ * next `<todo-delta>`, so it sends no message and starts no Turn. A retry
9505
+ * after the item closed the same way by the same person succeeds.
9506
+ */
9507
+ async function closeTodoItem(item, user, nowMs, action) {
9508
+ const todo = inboxItemTodo(item);
9509
+ if (item.status === "open") {
9510
+ if (!canActOnInboxItem(item, user.id)) throw new InboxItemActionError("forbidden", "Only an assignee can act on this item.");
9511
+ await setTodoStatusByUser(getSqlExecutor(), {
9512
+ assignedOnly: true,
9513
+ conversationId: todo.conversationId,
9514
+ id: todo.id,
9515
+ nowMs,
9516
+ status: action === "done" ? "done" : "dropped",
9517
+ userId: user.id
9518
+ });
9519
+ }
9520
+ const closed = await readInboxItemForUser(user, item.id);
9521
+ if (closed.status !== closedStatus(action) || closed.closedBy?.userId !== user.id) throw new InboxItemActionError("conflict", "Inbox item is closed.");
9522
+ return closed;
9523
+ }
9524
+ /**
9473
9525
  * Return whether a reply from this User answers an open action item, or is
9474
9526
  * a retry of the reply from this User that closed it.
9475
9527
  */
@@ -10126,6 +10178,36 @@ async function reorderPinnedConversations(viewer, body) {
10126
10178
  const updatedIds = new Set(updated.map((row) => row.rootConversationId));
10127
10179
  return { conversationIds: ids.filter((id) => updatedIds.has(id)) };
10128
10180
  }
10181
+ // src/chat/conversations/sql/title.ts
10182
+ /**
10183
+ * Replace one Conversation's title. Returns the stored title, or undefined
10184
+ * when the Conversation does not exist.
10185
+ *
10186
+ * recordActivity reads the title and writes it back under the mutation lock,
10187
+ * so this write takes the same lock. A concurrent Turn cannot restore the old
10188
+ * title.
10189
+ */
10190
+ async function setConversationTitle(executor, conversationId, title) {
10191
+ return await withConversationMutationLock(executor, conversationId, async () => {
10192
+ const [row] = await executor.db().update(juniorConversations).set({
10193
+ detailVersion: nextDetailVersion,
10194
+ title
10195
+ }).where(eq(juniorConversations.conversationId, conversationId)).returning({ title: juniorConversations.title });
10196
+ return row?.title ?? void 0;
10197
+ });
10198
+ }
10199
+ // src/api/conversations/rename.ts
10200
+ /**
10201
+ * Rename one conversation. The title is shared, so only a participant can
10202
+ * change it, the same as pin and archive. Automatic titles are set once, so a
10203
+ * later Turn keeps this title.
10204
+ */
10205
+ async function renameConversation(viewer, conversationId, body) {
10206
+ if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(404, "Conversation not found.");
10207
+ const title = await setConversationTitle(getSqlExecutor(), conversationId, body.title);
10208
+ if (!title) throwApiError(404, "Conversation not found.");
10209
+ return { title };
10210
+ }
10129
10211
  // src/api/conversations/stop.ts
10130
10212
  /**
10131
10213
  * Stop one Conversation for a participant: its active Turn, its session, and
@@ -10220,6 +10302,17 @@ const pinConversationOperation = defineApiOperation({
10220
10302
  annotations: writeAnnotations,
10221
10303
  run: (viewer, { conversationId, ...body }) => pinConversation(viewer, conversationId, body)
10222
10304
  });
10305
+ /** Rename one Conversation for everyone in it. */
10306
+ const renameConversationOperation = defineApiOperation({
10307
+ name: "renameConversation",
10308
+ title: "Rename conversation",
10309
+ description: "Rename one of your conversations for everyone in it. Later turns keep the new title. The Slack thread does not change. Returns the stored title.",
10310
+ scope: "conversations:manage",
10311
+ input: renameConversationBodySchema.extend(conversationIdInput),
10312
+ output: renameConversationResponseSchema,
10313
+ annotations: writeAnnotations,
10314
+ run: (viewer, { conversationId, ...body }) => renameConversation(viewer, conversationId, body)
10315
+ });
10223
10316
  /** Override the viewer's auto-archive default for one Conversation. */
10224
10317
  const setConversationAutoArchiveOperation = defineApiOperation({
10225
10318
  name: "setConversationAutoArchive",
@@ -10276,6 +10369,7 @@ const conversationOperations = [
10276
10369
  archiveConversationOperation,
10277
10370
  archiveDoneConversationsOperation,
10278
10371
  pinConversationOperation,
10372
+ renameConversationOperation,
10279
10373
  setConversationAutoArchiveOperation,
10280
10374
  setConversationSubscriptionOperation,
10281
10375
  stopConversationOperation
@@ -10406,15 +10500,18 @@ async function appendConversationMessageForViewer(viewer, conversationId, body,
10406
10500
  attachmentStorage: services.attachmentStorage,
10407
10501
  queue: services.queue
10408
10502
  });
10409
- const closeAnswered = () => closeInboxItemsAnsweredByReply({
10410
- conversationId,
10411
- delivery: {
10412
- queue: services.queue,
10413
- show: createSlackInboxItemShow(getProductionSlackAdapter)
10414
- },
10415
- resolveUser: async () => viewer,
10416
- text: body.message
10417
- });
10503
+ const closeAnsweredAndRead = async () => {
10504
+ await closeInboxItemsAnsweredByReply({
10505
+ conversationId,
10506
+ delivery: {
10507
+ queue: services.queue,
10508
+ show: createInboxItemShow(getProductionSlackAdapter)
10509
+ },
10510
+ resolveUser: async () => viewer,
10511
+ text: body.message
10512
+ });
10513
+ await markConversationRead(viewer, conversationId, { lastReadSeq: Number.MAX_SAFE_INTEGER });
10514
+ };
10418
10515
  try {
10419
10516
  let accepted;
10420
10517
  try {
@@ -10429,10 +10526,10 @@ async function appendConversationMessageForViewer(viewer, conversationId, body,
10429
10526
  conversationId,
10430
10527
  state
10431
10528
  })]);
10432
- if (work?.execution.inboundMessageIds.includes(messageId)) await closeAnswered();
10529
+ if (work?.execution.inboundMessageIds.includes(messageId)) await closeAnsweredAndRead();
10433
10530
  throw error;
10434
10531
  }
10435
- await closeAnswered();
10532
+ await closeAnsweredAndRead();
10436
10533
  return accepted;
10437
10534
  } catch (error) {
10438
10535
  throwApiError(500, "Unable to append message.", error);
@@ -11251,9 +11348,8 @@ const fork = alias(juniorConversations, "detail_fork");
11251
11348
  const agentTreeRoot = alias(juniorConversations, "detail_agent_tree_root");
11252
11349
  /**
11253
11350
  * Return the root fields that label the agent tree of a child: its title and
11254
- * channel name. The other labels cannot change once the child exists. An
11255
- * agent invocation keeps its title and agent name after insert, and only the
11256
- * spawn sets a title. Access to each node comes from the shared root, so the
11351
+ * channel name. The other labels cannot change once the child exists. Only
11352
+ * the spawn sets a child's title and agent name. Access to each node comes from the shared root, so the
11257
11353
  * viewer's access covers it. This keeps the recursive lineage read out of
11258
11354
  * every poll.
11259
11355
  */
@@ -12051,16 +12147,20 @@ async function readFeedThreadRecords(db, rootIds) {
12051
12147
  * Nest the shown Threads of `readFeedThreadRecords` under their nearest shown
12052
12148
  * ancestor. A Thread shows when it and every ancestor have no
12053
12149
  * `archived_at`. A Thread uses the access of its root. `tree` holds the
12054
- * trees of at least the listed roots.
12150
+ * trees of at least the listed roots. Each root lists at most
12151
+ * `CONVERSATION_FEED_THREAD_LIMIT` Threads, depth first in activity order,
12152
+ * so a kept Thread always has its parent.
12055
12153
  */
12056
12154
  function nestFeedThreads(records, tree, accessByRoot) {
12057
12155
  if (!records) return /* @__PURE__ */ new Map();
12058
12156
  const { firstHumanMessageTexts, rootIds, threads } = records;
12059
12157
  const childrenByParent = /* @__PURE__ */ new Map();
12158
+ const placedByRoot = /* @__PURE__ */ new Map();
12060
12159
  for (const { conversation, row } of threads) {
12061
12160
  const parentId = findThreadPlacement(conversation.conversationId, tree, rootIds);
12062
12161
  if (!parentId) continue;
12063
12162
  const rootId = row.conversation.rootConversationId;
12163
+ if (rootId) placedByRoot.set(rootId, (placedByRoot.get(rootId) ?? 0) + 1);
12064
12164
  const summary = conversationSummaryFromStoredConversation({
12065
12165
  access: rootId ? accessByRoot.get(rootId) : void 0,
12066
12166
  conversation,
@@ -12073,18 +12173,81 @@ function nestFeedThreads(records, tree, accessByRoot) {
12073
12173
  siblings.push(summary);
12074
12174
  childrenByParent.set(parentId, siblings);
12075
12175
  }
12076
- const nest = (items) => items.map((item) => {
12176
+ const nest = (items, budget) => items.flatMap((item) => {
12177
+ if (budget.left === 0) return [];
12178
+ budget.left -= 1;
12077
12179
  const children = childrenByParent.get(item.conversationId);
12078
- return children ? {
12180
+ const nested = children ? nest(children, budget) : [];
12181
+ return [nested.length > 0 ? {
12079
12182
  ...item,
12080
- threads: nest(children)
12081
- } : item;
12183
+ threads: nested
12184
+ } : item];
12082
12185
  });
12083
12186
  return new Map([...rootIds].flatMap((rootId) => {
12084
12187
  const children = childrenByParent.get(rootId);
12085
- return children ? [[rootId, nest(children)]] : [];
12188
+ if (!children) return [];
12189
+ const budget = { left: 100 };
12190
+ const nested = nest(children, budget);
12191
+ const shown = 100 - budget.left;
12192
+ return [[rootId, {
12193
+ omittedThreadCount: (placedByRoot.get(rootId) ?? 0) - shown,
12194
+ threads: nested
12195
+ }]];
12086
12196
  }));
12087
12197
  }
12198
+ // src/chat/inbox-items/waiting.ts
12199
+ const waitingRootId = sql`coalesce(${juniorConversations.rootConversationId}, ${juniorInboxItemConversations.conversationId})`.as("waiting_root_id");
12200
+ const waitingTodoRootId = sql`coalesce(${juniorConversations.rootConversationId}, ${juniorInboxItems.ownerId})`.as("waiting_root_id");
12201
+ /** Open items that need the User now, with the root where each one waits. */
12202
+ function waitingItemsQuery(db, userId) {
12203
+ const columns = {
12204
+ createdAt: juniorInboxItems.createdAt,
12205
+ dedupeKey: juniorInboxItems.dedupeKey,
12206
+ itemId: juniorInboxItems.id,
12207
+ title: juniorInboxItems.title
12208
+ };
12209
+ return db.select({
12210
+ conversationId: waitingRootId,
12211
+ ...columns
12212
+ }).from(juniorInboxItemConversations).innerJoin(juniorInboxItems, eq(juniorInboxItems.id, juniorInboxItemConversations.itemId)).leftJoin(juniorConversations, eq(juniorConversations.conversationId, juniorInboxItemConversations.conversationId)).where(inboxItemNeedsUserNow(userId)).union(db.select({
12213
+ conversationId: waitingTodoRootId,
12214
+ ...columns
12215
+ }).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}%`))));
12216
+ }
12217
+ /**
12218
+ * Return a query for the ids of the root Conversations that wait on a User,
12219
+ * as `listWaitingConversations` lists them, to filter another query by.
12220
+ */
12221
+ function waitingConversationIdsQuery(db, userId) {
12222
+ const items = waitingItemsQuery(db, userId).as("waiting_items");
12223
+ return db.select({ conversationId: items.conversationId }).from(items);
12224
+ }
12225
+ /**
12226
+ * List the root Conversations that wait on a User: each root or one of its
12227
+ * child conversations is linked to, or owns a To-do's, open item that needs
12228
+ * the User now (`inboxItemNeedsUserNow`), so a snoozed item leaves it out.
12229
+ */
12230
+ async function listWaitingConversations(db, userId) {
12231
+ const rows = (await waitingItemsQuery(db, userId)).sort((left, right) => right.createdAt.getTime() - left.createdAt.getTime() || right.itemId.localeCompare(left.itemId));
12232
+ const waiting = /* @__PURE__ */ new Map();
12233
+ for (const row of rows) {
12234
+ const plugin = inboxItemPlugin(row.dedupeKey);
12235
+ const item = {
12236
+ title: row.title,
12237
+ ...plugin ? { plugin } : void 0
12238
+ };
12239
+ const current = waiting.get(row.conversationId);
12240
+ if (current) {
12241
+ current.items.push(item);
12242
+ current.waitingSince = row.createdAt.toISOString();
12243
+ } else waiting.set(row.conversationId, {
12244
+ conversationId: row.conversationId,
12245
+ items: [item],
12246
+ waitingSince: row.createdAt.toISOString()
12247
+ });
12248
+ }
12249
+ return [...waiting.values()].sort((left, right) => left.conversationId.localeCompare(right.conversationId));
12250
+ }
12088
12251
  // src/api/conversations/priority.ts
12089
12252
  /** Conversations with no known work leave Priority after this idle window. */
12090
12253
  const UNASSIGNED_PRIORITY_WINDOW_MS = 108e5;
@@ -12484,6 +12647,11 @@ async function readConversationFeedFromSql(options = {}) {
12484
12647
  filter,
12485
12648
  include,
12486
12649
  includePrivateMatches: true,
12650
+ limit: limit + 50 + 1,
12651
+ pinnedForUserId: {
12652
+ pinned: false,
12653
+ userId: filter.userId
12654
+ },
12487
12655
  status: "active",
12488
12656
  waitingForUserId: filter.userId
12489
12657
  }) : []
@@ -12491,11 +12659,14 @@ async function readConversationFeedFromSql(options = {}) {
12491
12659
  const page = pageRows.slice(0, limit);
12492
12660
  const lastRow = pageRows.length > limit ? page.at(-1) : void 0;
12493
12661
  const rows = [...pinnedRows, ...page];
12662
+ let waitingRowsTruncated = false;
12494
12663
  if (firstPage) {
12495
12664
  const loaded = new Set(rows.map((row) => row.conversation.conversationId));
12496
12665
  const outsidePage = waitingRows.filter((row) => !loaded.has(row.conversation.conversationId));
12497
- options.onWaitingRows?.(outsidePage.length);
12498
- rows.push(...outsidePage);
12666
+ waitingRowsTruncated = outsidePage.length > 50;
12667
+ const waiting = outsidePage.slice(0, 50);
12668
+ options.onWaitingRows?.(waiting.length);
12669
+ rows.push(...waiting);
12499
12670
  }
12500
12671
  const conversations = rows.map((row) => conversationFromRecordRow(row));
12501
12672
  const conversationIds = conversations.map((conversation) => conversation.conversationId);
@@ -12558,12 +12729,11 @@ async function readConversationFeedFromSql(options = {}) {
12558
12729
  ...conversationWork.finishedAtById[conversation.conversationId] ? { finishedWorkAt: conversationWork.finishedAtById[conversation.conversationId] } : void 0,
12559
12730
  ...unfinishedWork.has(conversation.conversationId) ? { unfinishedWork: true } : void 0
12560
12731
  };
12561
- const annotations = access?.canViewPrivateContent ? annotationsByConversation.get(conversation.conversationId) ?? [] : [];
12562
12732
  const activityPreview = visibleActivityPreviews.get(conversation.conversationId);
12563
12733
  const participants = access?.canViewPrivateContent ? participantsByConversation.get(conversation.conversationId) : void 0;
12564
12734
  const threads = threadsByRoot.get(conversation.conversationId);
12565
12735
  const media = access?.canViewPrivateContent ? row.media : null;
12566
- const links = access?.canViewPrivateContent && row.links ? pickFeedLinks(conversation.conversationId, row.links, annotationUrls(annotations)) : [];
12736
+ const links = access?.canViewPrivateContent && row.links ? pickFeedLinks(conversation.conversationId, row.links, annotationUrls(visibleAnnotationsByConversation.get(conversation.conversationId))) : [];
12567
12737
  const lastMessageAt = row.lastMessageAt?.toISOString();
12568
12738
  const treeRead = treeStateByConversation.get(conversation.conversationId);
12569
12739
  const viewerAnswer = access?.canViewPrivateContent ? feedViewerAnswer(row.viewerAnswer) : void 0;
@@ -12574,13 +12744,13 @@ async function readConversationFeedFromSql(options = {}) {
12574
12744
  ...row.awaitingAuthorization ? { awaitingAuthorization: true } : void 0,
12575
12745
  ...row.latestTurnFailed ? { latestTurnFailed: true } : void 0,
12576
12746
  ...lastMessageAt ? { lastMessageAt } : void 0,
12577
- ...threads ? { threads } : void 0,
12747
+ ...threads ? { threads: threads.threads } : void 0,
12748
+ ...threads?.omittedThreadCount ? { omittedThreadCount: threads.omittedThreadCount } : void 0,
12578
12749
  ...participants && participants.length > 0 ? { participants } : void 0,
12579
12750
  ...activityPreview ? { activityPreview } : void 0,
12580
12751
  ...viewerAnswer ? { viewerAnswer } : void 0,
12581
12752
  ...media?.length ? { media } : void 0,
12582
12753
  ...links.length > 0 ? { links } : void 0,
12583
- ...annotations.length > 0 ? { annotations } : void 0,
12584
12754
  ...sidebarAnnotationsByConversation[conversation.conversationId] ? { sidebarAnnotations: sidebarAnnotationsByConversation[conversation.conversationId] } : void 0,
12585
12755
  isPriority: isConversationPriority({
12586
12756
  lastSeenAt: summary.lastSeenAt,
@@ -12594,7 +12764,8 @@ async function readConversationFeedFromSql(options = {}) {
12594
12764
  at: lastRow.activityCursor,
12595
12765
  conversationId: lastRow.conversation.conversationId
12596
12766
  }) } : void 0,
12597
- source: "conversation_index"
12767
+ source: "conversation_index",
12768
+ ...waitingRowsTruncated ? { waitingRowsTruncated: true } : void 0
12598
12769
  };
12599
12770
  }
12600
12771
  /**
@@ -12608,4 +12779,4 @@ async function readConversationFeedFromSql(options = {}) {
12608
12779
  async function readConversationFeed(options = {}) {
12609
12780
  return readConversationFeedFromSql(options);
12610
12781
  }
12611
- export { runAutoArchiveSweep as $, apiOperationHandler as A, slackInboundMessageId as At, mcpMessages as B, stripLeadingBotMention as Bt, cancelQueuedMessagesOperation as C, isPublicAddress as Ct, setConversationSubscriptionOperation as D, getProductionSlackAdapter as Dt, setConversationAutoArchiveOperation as E, createProductionSlackWebhookServices as Et, mcpConversationSchema as F, failStoppedDispatch as Ft, resolveMentions as G, conversationRecordJoins as Gt, readMcpPendingWork as H, SubscribedReplyReason as Ht, mcpCursorSchema as I, recordSkippedConversationMessage as It, closeInboxItemsAnsweredByReply as J, readFirstHumanMessageTexts as Jt, InboxItemActionError as K, readConversationRecordFromSql as Kt, mcpIdempotencyKeySchema as L, createSlackWebApiStatusSender as Lt, mcpAuthorizationSchema as M, withNormalizedThreadId as Mt, mcpConversation as N, AGENT_DISPATCH_MAX_AGE_MS as Nt, stopConversationOperation as O, buildSlackInboundMessage as Ot, mcpConversationIdSchema as P, enqueueAgentDispatch as Pt, ingestEventAutomations as Q, mcpMessageSchema as R, bindMessageAuthorIdentityId as Rt, archiveDoneConversationsOperation as S, guardedFetch as St, pinConversationOperation as T, createProductionConversationWorkOptions as Tt, readMcpPendingWorkAfterSend as U, getThreadStopDecision as Ut, mcpPendingMessagesSchema as V, parseContent as Vt, requireConversationPendingMessages as W, resolvePersonLink as Wt, reviewItemChange as X, IMAGE_WIDTHS as Xt, readInboxItemForUser as Y, createViewerMcp as Yt, createEventAppPublisher as Z, decodeImageId as Zt, createConversationForViewer as _, readLinkObjectType as _t, listedConversation as a, createHeartbeatContext as at, encodeConversationCursor as b, resolveObjectLinks as bt, readConversationAuxiliaryCostsFromSql as c, runInboxSnoozeTimers as ct, conversationVersionsQuery as d, runSavingsRefillSlice as dt, DEFAULT_USER_SETTINGS as et, readConversationDetailEtag as f, startSavingsRefill as ft, appendConversationMessageForViewer as g, OBJECT_LINK_TTL_MS as gt, readConversationEvents as h, readHealthReport as ht, encodePageCursor as i, settleEventAutomationRuns as it, mcpAcceptedMessageSchema as j, normalizeIncomingSlackThreadId as jt, reorderPinnedConversations as k, clearSlackPendingReactions as kt, childAgentTotalsReport as l, scheduleInboxSnoozeTimer as lt, keepQuickQuestionForViewer as m, GET as mt, readConversationFeed as n, updateUserSettings as nt, notLeadConversation as o, dispatchScheduledAutomation as ot, forkConversationForViewer as p, backfillCacheWarmingGaps as pt, actOnInboxItem as q, conversationSummaryFromStoredConversation as qt, decodePageCursor as r, automationReplyAttribution as rt, readConversationDetail as s, getScheduledAutomationDispatch as st, conversationFeedVersionQuery as t, readUserSettings as tt, readConversationTreeMetricsFromSql as u, readSavingsRefill as ut, requireWebMessageConversation as v, readObjectLinkTypes as vt, conversationOperations as w, publicAddressLookup as wt, archiveConversationOperation as x, viewerCanViewPluginLink as xt, decodeConversationCursor as y, resolveObjectLinkNow as yt, mcpMessageTextSchema as z, startProcessingReaction as zt };
12782
+ export { createEventAppPublisher as $, decodeImageId as $t, stopConversationOperation as A, buildSlackInboundMessage as At, mcpMessageSchema as B, bindMessageAuthorIdentityId as Bt, archiveDoneConversationsOperation as C, viewerCanViewPluginLink as Ct, renameConversationOperation as D, createProductionConversationWorkOptions as Dt, pinConversationOperation as E, publicAddressLookup as Et, mcpConversation as F, AGENT_DISPATCH_MAX_AGE_MS as Ft, readMcpPendingWorkAfterSend as G, getThreadStopDecision as Gt, mcpMessages as H, stripLeadingBotMention as Ht, mcpConversationIdSchema as I, enqueueAgentDispatch as It, InboxItemActionError as J, readConversationRecordFromSql as Jt, requireConversationPendingMessages as K, resolvePersonLink as Kt, mcpConversationSchema as L, failStoppedDispatch as Lt, apiOperationHandler as M, slackInboundMessageId as Mt, mcpAcceptedMessageSchema as N, normalizeIncomingSlackThreadId as Nt, setConversationAutoArchiveOperation as O, createProductionSlackWebhookServices as Ot, mcpAuthorizationSchema as P, withNormalizedThreadId as Pt, reviewItemChange as Q, IMAGE_WIDTHS as Qt, mcpCursorSchema as R, recordSkippedConversationMessage as Rt, archiveConversationOperation as S, resolveObjectLinks as St, conversationOperations as T, isPublicAddress as Tt, mcpPendingMessagesSchema as U, parseContent as Ut, mcpMessageTextSchema as V, startProcessingReaction as Vt, readMcpPendingWork as W, SubscribedReplyReason as Wt, closeInboxItemsAnsweredByReply as X, readFirstHumanMessageTexts as Xt, actOnInboxItem as Y, conversationSummaryFromStoredConversation as Yt, readInboxItemForUser as Z, createViewerMcp as Zt, appendConversationMessageForViewer as _, readHealthReport as _t, listWaitingConversations as a, automationReplyAttribution as at, decodeConversationCursor as b, readObjectLinkTypes as bt, readConversationDetail as c, dispatchScheduledAutomation as ct, readConversationTreeMetricsFromSql as d, scheduleInboxSnoozeTimer as dt, ingestEventAutomations as et, conversationVersionsQuery as f, readSavingsRefill as ft, readConversationEvents as g, GET as gt, keepQuickQuestionForViewer as h, backfillCacheWarmingGaps as ht, encodePageCursor as i, updateUserSettings as it, reorderPinnedConversations as j, clearSlackPendingReactions as jt, setConversationSubscriptionOperation as k, getProductionSlackAdapter as kt, readConversationAuxiliaryCostsFromSql as l, getScheduledAutomationDispatch as lt, forkConversationForViewer as m, startSavingsRefill as mt, readConversationFeed as n, DEFAULT_USER_SETTINGS as nt, listedConversation as o, settleEventAutomationRuns as ot, readConversationDetailEtag as p, runSavingsRefillSlice as pt, resolveMentions as q, conversationRecordJoins as qt, decodePageCursor as r, readUserSettings as rt, notLeadConversation as s, createHeartbeatContext as st, conversationFeedVersionQuery as t, runAutoArchiveSweep as tt, childAgentTotalsReport as u, runInboxSnoozeTimers as ut, createConversationForViewer as v, OBJECT_LINK_TTL_MS as vt, cancelQueuedMessagesOperation as w, guardedFetch as wt, encodeConversationCursor as x, resolveObjectLinkNow as xt, requireWebMessageConversation as y, readLinkObjectType as yt, mcpIdempotencyKeySchema as z, createSlackWebApiStatusSender as zt };