@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
package/dist/api.js CHANGED
@@ -1,36 +1,35 @@
1
- import { $ as getPlugins, $c as readViewerAvatarUrl, $f as cacheKeyPrefix, $i as getVercelConversationWorkQueue, $l as automationSearchDocument, Aa as createPluginCache, Af as botConfig, Ar as pluginCatalogRuntime, At as memoryDb, Cr as createUserTokenStore, Cs as conversationStatusSql, Dc as inboxItemForUser, Ds as conversationKindFromRow, Dt as contentVersion, Du as juniorUsers, Ec as canUserReadInboxItem, El as readConversationAccessFromSql, Eo as getDashboardSettingsLink, Et as REVALIDATED_READ_PATHS, Eu as slackPersonSearchDocument, Fd as automationEventCatalog, Fn as listWorkspaces, Ft as prefixMatch, Gn as hash, Hl as juniorTodos, I as escapeSlackMrkdwnText, Ic as isInboxItemForEveryone, Il as rootVisibleToViewer, In as listWorkspacesByRepository, It as prefixRank, Jc as findUserByEmail, Js as ownerConversationId, Kl as inboxItemFuzzyTitle, L as formatSlackLink, Lc as isOnlyAssignee, Ln as updateWorkspace, Lr as serviceAccountPlugins, Lt as rankSearchMatches, Mc as inboxItemReaderForUserInConversation, Mn as deleteWorkspace, Mr as disconnectServiceAccount, Mt as parseTypedQuery, N as loadConversationSlackTenantIds, Nc as inboxItemTodo, Nn as getWorkspace, Nr as finishServiceAccountSignIn, Nt as fuzzyMatch, Ot as contentVersionHeaders, Ou as juniorDestinations, Pc as inboxItemVisibleTo, Pr as getServiceAccountStatus, Pt as fuzzyRank, Qd as getStateAdapter, Qf as saveEnabledProviders, Ql as automationFuzzyTitle, Rn as WorkspaceValidationError, Rr as startServiceAccountSignIn, Rt as scoredSearchMatches, Sc as canActOnInboxItem, Si as createPluginEmbedder, Ss as conversationIsActiveSql, St as isPausedBySlack, Tl as createConversationAccessReader, To as getDashboardPersonLink, Tu as slackPersonPredicate, Ul as todoFuzzyTitle, Vs as getInboxItem, Wl as todoSearchDocument, Wn as create, Ws as inboxItemsNeedingUserVersionQuery, Wu as isAgentResourceType, Xf as readEnabledProviders, Yl as juniorInboxItemConversations, Yo as AutomationConflictError, Ys as searchInboxItems, Yu as cancelWatch, Zf as readServedProviders, Zl as juniorInboxItems, _t as listPushSubscriptions, a as getDb, ac as clearInboxWakeReasons, bi as workspaceRepoCheckoutPath, bl as readCachedUserByEmail, bo as getDashboardConversationLink, bs as conversationRangeColumns, bt as savePushSubscription, bu as juniorConversations, cc as inboxItemSnoozedBy, dc as settleInboxSnoozes, dt as readWebPushConfig, du as juniorApiTokens, el as resolveViewerUser, ep as createCache, et as getRegistrations, eu as juniorAutomations, fc as snoozeInboxItems, ft as sendPushNotificationToUser, gs as microUsdToUsd, gt as deletePushSubscription, gu as juniorCodeRepositories, hs as microUsdSql, ht as resolveNotificationTimezone, hu as juniorCodeChanges, i as getConversationStore, id as listWatches, il as identityAvatarUrl, ip as withLock, jc as inboxItemReaderForUser, jf as getChatConfig, jn as createWorkspace, jt as searchTypedMemories, ju as getEventCatalog, kl as readableSlackTeamId, kt as revalidateContent, la as createPluginAnnotations, lt as apiRoutePrefix, lu as juniorConversationMetrics, mc as unsnoozeInboxRow, mu as codeRepositorySearchDocument, nf as credentialContextForActor, nl as updateViewerDisplayName, no as postSlackMessage, o as getSqlExecutor, ol as readAvatarFetch, pc as snoozeTimerTrigger, pu as codeChangeSearchDocument, ql as inboxItemSearchDocument, ri as webActorUserIds, ru as juniorAgentBindings, sc as inboxItemInRow, sl as readUserAvatarUrls, ss as readAutomationTitlesByConversationId, tu as juniorAutomationRuns, ua as listConversationAnnotations, uc as readViewerInboxSnoozes, uu as juniorConversationEvents, vi as SANDBOX_RUNTIME, vs as usdToMicroUsdUnbiased, vt as readNotificationSchedule, wc as canAnswerInboxItem, wp as getAttachmentStorage, ws as conversationTurnFailedSql, wu as juniorIdentities, xf as parseSlackTeamId, xs as conversationUsageCostExpr, yf as parseSlackChannelId, ys as conversationAggregateColumns, yt as saveNotificationSchedule, zc as itemNeedsUser, zd as eventWatchUnavailable, zi as completeText, zs as countInboxItemsNeedingUserBySubject } from "./db-DXTOYRzR.js";
2
- import { E as withSpan, N as normalizeIdentityEmail, _ as runBestEffort, h as logWarn, m as logInfo, p as logException, y as setSentryUser } from "./logging-czs0nqLC.js";
3
- import { A as pauseConversationDelivery, Bt as readViewerAutomationExecutions, Ct as jsonResponse, Ht as readViewerAutomationSummary, It as updateViewerAutomation, Kt as AutomationEditError, Lt as ViewerTaskNotFoundError, M as AttachmentDownloadError, Mt as changeViewerAutomationLifecycle, N as readAttachmentContent, Nt as deleteViewerTask, O as canPauseConversationDelivery, P as previewOriginBelongsTo, Pt as readViewerAutomationEdit, Rt as collectionRowTitle, St as emptyResponse, Ut as readViewerAutomationVersions, Vt as readViewerAutomationRuns, Wt as readViewerAutomations, Xt as viewerAutomationCollection, Zt as SAVINGS_NAMESPACE, an as readStats, bt as inviteToConversation, cn as connectedState, in as addStats, j as resumeConversationDelivery, jt as activateViewerAutomationVersion, mt as reportConversationRead, on as breakerStates, p as createInboxItemShow, rn as savingsTotals, sn as closeBreaker, vt as listOwnedWatches, wt as throwApiError } from "./agent-runner-C7GNLRB6.js";
4
- import { A as automationVersionActivateSchema, At as spaceSchema, B as conversationAttachmentParamsSchema, C as automationRunListSchema, D as automationSchedulePreviewSchema, Dt as spaceListSchema, E as automationScheduleIntentSchema, Et as spaceListQuerySchema, Fn as automationTaskText, Ht as MAX_ATTACHMENT_BYTES, I as CONVERSATION_DETAIL_VERSION_HEADER, J as conversationParamsSchema, K as conversationEventPageSchema, L as CONVERSATION_VERSION_HEADER, M as automationVersionParamsSchema, Mt as updateSpaceBodySchema, O as automationSummarySchema, Ot as spaceParamsSchema, Pt as conversationReadPositionSchema, S as automationParamsSchema, Tt as createSpaceBodySchema, U as conversationDetailQuerySchema, V as conversationAttachmentQuerySchema, W as conversationDetailReportSchema, _ as automationLifecycleSchema, b as automationListQuerySchema, d as automationEditSchema, en as ScheduleIntentError, f as automationEventCatalogSchema, j as automationVersionListSchema, k as automationUpdateSchema, l as apiErrorSchema, mn as isOpenTodoStatus, n as INPUT_IMAGE_TYPES, p as automationExecutionListSchema, q as conversationEventsQuerySchema, r as detectImageMediaType, s as notificationScheduleSchema, t as INLINE_VIDEO_TYPES, tn as compileScheduleIntent, u as automationEditErrorSchema, wt as archiveSpaceBodySchema, y as automationListPageSchema } from "./media-Cr9pGkzr.js";
5
- import { A as gatewayProvidersSchema, At as disconnectConnectionResponseSchema, B as disconnectServiceAccountResponseSchema, Bt as codeRepositoryParamsSchema, Ct as notificationSettingsSchema, D as inboxSnoozeSchema, Dt as connectionListSchema, E as inboxSnoozeResourceSchema, Et as testNotificationResponseSchema, F as cacheWarmingBreakerParamsSchema, Ft as codeChangeSearchReportSchema, G as searchQuerySchema, Gt as personCodeQuerySchema, H as serviceAccountParamsSchema, Ht as codeRepositoryReportSchema, I as cacheWarmingSavingsQuerySchema, J as createdPersonalTokenSchema, Jt as todoParamsSchema, K as searchReportSchema, Kt as conversationTodoSchema, L as cacheWarmingSavingsRefillResponseSchema, M as cacheHealthQuerySchema, N as cacheHealthReportSchema, O as inboxSnoozeSubjectSchema, Ot as connectionParamsSchema, P as cacheWarmingBreakerListSchema, Pt as codeChangeSearchQuerySchema, Q as revokePersonalTokenResponseSchema, Qt as watchParamsSchema, R as cacheWarmingSavingsReportSchema, Rt as codeOverviewReportSchema, S as inboxItemWaitingConversationsSchema, Sn as forkConversationResponseSchema, T as inboxSnoozeResourceQuerySchema, Tt as pushSubscriptionDeleteBodySchema, V as serviceAccountListSchema, Vt as codeRepositoryQuerySchema, W as startServiceAccountSignInResponseSchema, Y as personalTokenListSchema, Yt as todoStatusBodySchema, Z as personalTokenParamsSchema, Zt as conversationWatchesReportSchema, _ as inboxItemCountSchema, _n as createAttachmentUploadBodySchema, _t as locationDirectoryReportSchema, a as versionsSchema, an as attachObjectLinkResponseSchema, at as peopleSearchReportSchema, b as inboxItemParamsSchema, bn as createConversationMessageBodySchema, bt as activityHours$2, cn as conversationStatsReportSchema, ct as personalSpendReportSchema, d as workspaceListSchema, dn as conversationDeliveryBodySchema, en as conversationChildAgentsReportSchema, et as actorDirectoryReportSchema, f as workspaceParamsSchema, fn as conversationDeliveryResponseSchema, ft as leadSchema, g as inboxItemCountQuerySchema, gn as attachmentUploadSchema, gt as locationDetailReportSchema, h as inboxItemActionSchema, hn as attachmentUploadParamsSchema, i as versionsQuerySchema, in as attachObjectLinkBodySchema, it as peopleSearchQuerySchema, j as updateGatewayProvidersBodySchema, jt as startConnectionResponseSchema, k as inboxSnoozeWakesClearSchema, l as deleteWorkspaceResponseSchema, lt as addSpaceMemberBodySchema, m as workspaceSchema, mn as conversationCatchUpSchema, mt as spaceConfigurationSchema, n as VERSIONS_STREAM_HEADER, nn as continueConversationInSlackResponseSchema, nt as avatarParamsSchema, on as objectLinksQuerySchema, ot as personCardReportSchema, pn as conversationCatchUpBodySchema, q as createPersonalTokenBodySchema, qt as conversationTodosReportSchema, r as VERSIONS_STREAM_KEEPALIVE_EVENT, s as statsReportSchema, sn as objectLinksReportSchema, st as personParamsSchema, tn as continueConversationInSlackBodySchema, tt as actorProfileReportSchema, u as workspaceBodySchema, un as conversationOutlineSchema, ut as spaceMemberListSchema, v as inboxItemListQuerySchema, vn as acceptedConversationMessageSchema, vt as locationParamsSchema, w as inboxSnoozeCreateSchema, wt as pushSubscriptionBodySchema, x as inboxItemSchema, xn as forkConversationBodySchema, xt as activitySixHours$1, y as inboxItemListSchema, yn as createConversationBodySchema, yt as activityDays$1, z as closeCacheWarmingBreakerResponseSchema, zt as codePersonReportSchema } from "./schema-DrBMdPmv.js";
6
- import { A as steerConversationPendingMessagesBodySchema, B as skillDetailReportSchema, H as skillReportsSchema, M as healthReportSchema, N as pluginOperationalReportFeedSchema, O as conversationPendingMessagesReportSchema, R as pluginsSchema, _ as reorderPinnedConversationsResponseSchema, a as conversationInviteResponseSchema, g as reorderPinnedConversationsBodySchema, i as conversationInviteBodySchema, j as steerConversationPendingMessagesResponseSchema, k as conversationUnchangedDetailWithMailboxSchema, n as conversationFeedSchema, t as conversationFeedQuerySchema, w as conversationDetailWithMailboxReportSchema, z as runtimeInfoReportSchema } from "./conversation-feed-Sl8lKKmR.js";
7
- import { Ht as listTodos, In as isExperimentalFeatureEnabled, It as readUserCustomization, Lt as saveUserCustomization, Rr as createPluginEgress, Ut as setTodoStatusByUser, V as parseEmail, Wt as pushConversationInboxItemsNow, bn as steerWebPendingMessages, kn as addConversationNote, z as isAllowedDomain } from "./mailbox-turn-79Nv1JXv.js";
8
- import { C as joinSpace, D as readSpace, E as listSpaces, M as readLiveAttachment, O as updateSpace, S as createSpace, T as listSpaceMembers, _ as AttachmentUploadError, a as getSpaceLead, h as webActorFromUser, l as acceptsWebMessages, s as readSpaceLead, w as leaveSpace, x as writeAttachmentUpload, y as createAttachmentUpload } from "./turn-session-routing-GtetHsdO.js";
9
- import { $ as readInboxItemForUser, $t as createViewerMcp, A as setConversationSubscriptionOperation, C as archiveDoneConversationsOperation, Ct as resolveObjectLinkNow, D as renameConversationOperation, E as pinConversationOperation, Et as guardedFetch, J as requireConversationPendingMessages, Jt as resolvePersonLink, M as setSpaceArchive, N as reorderPinnedConversations, O as setConversationAutoArchiveOperation, P as apiOperationHandler, Qt as readFirstHumanMessageTexts, S as archiveConversationOperation, St as readObjectLinkTypes, Tt as viewerCanViewPluginLink, X as InboxItemActionError, Y as resolveMentions, Yt as conversationRecordJoins, Z as actOnInboxItem, Zt as conversationSummaryFromStoredConversation, _ as appendConversationMessageForViewer, a as listWaitingConversations, at as readUserSettings, bt as OBJECT_LINK_TTL_MS, c as readConversationDetail, d as readConversationTreeMetricsFromSql, en as IMAGE_WIDTHS, f as conversationVersionsQuery, g as readConversationEvents, gt as startSavingsRefill, h as keepQuickQuestionForViewer, i as encodePageCursor, it as DEFAULT_USER_SETTINGS, j as stopConversationOperation, jt as getProductionSlackAdapter, k as setConversationSpaceOperation, l as readConversationAuxiliaryCostsFromSql, m as forkConversationForViewer, mt as readSavingsRefill, n as readConversationFeed, o as listedConversation, ot as updateUserSettings, p as readConversationDetailEtag, pt as scheduleInboxSnoozeTimer, r as decodePageCursor, s as notLeadConversation, t as conversationFeedVersionQuery, tn as decodeImageId, u as childAgentTotalsReport, v as createConversationForViewer, w as cancelQueuedMessagesOperation, wt as resolveObjectLinks, xt as readLinkObjectType, y as requireWebMessageConversation, yt as readHealthReport } from "./list-DXBz8SYL.js";
10
- import { a as transcriptEntriesFromReportEvents, c as linkedCodeProviders, f as readConversationLastEventSeq, l as readConversationEventPage, m as reportParentAgentInput, o as codeChangeUrl, s as codeRepositoryUrl } from "./task-runner-DcdQJd9e.js";
11
- import { t as runWithSlackInstallation } from "./adapter-context-BlSGE44V.js";
12
- import { o as listChildAgents } from "./parent-result-Dg6P6roR.js";
13
- import { i as continueConversationInSlack, r as canContinueInSlack, t as BUSY } from "./continue-in-slack-BGKjIdFp.js";
14
- import { o as readSlackAttachmentSource } from "./start-conversation-Uh8Sk1EF.js";
1
+ import { d as readLiveAttachment, o as readSlackAttachmentSource, y as getAttachmentStorage } from "./turn-membership-CENFf3kI.js";
2
+ import { $o as pauseConversationDelivery, Ad as todoFuzzyTitle, As as listPushSubscriptions, B as conversationIsActiveSql, Ba as microUsdToUsd, Bc as questionLinks, Bd as inboxItemFuzzyTitle, Bl as memoryDb, Bo as credentialContextForActor, Ca as AutomationConflictError, Cd as topLevelConversation, Cl as getDashboardConversationLink, Dc as getInboxItem, Dl as getDashboardSettingsLink, Ei as formatSlackLink, El as getDashboardPersonLink, Et as apiRoutePrefix, Fd as juniorAutomationRuns, Gc as identityAvatarUrl, Gd as juniorAgentBindings, Gl as prefixMatch, Go as codeChangeSubjectProvider, H as conversationStatusSql, Ha as usdToMicroUsdUnbiased, Hc as subjectKindPlugin, Hd as juniorInboxItemConversations, Hl as parseTypedQuery, Ia as readAutomationTitlesByConversationId, Ic as inboxItemRequest, Id as automationFuzzyTitle, Ii as createPluginEmbedder, Il as REVALIDATED_READ_PATHS, In as createInboxItemShow, Jc as readUserAvatarUrls, Ji as createPluginCache, Jl as scoredSearchMatches, Jo as codeChangeUrl, K as conversationKindFromRow, Kl as prefixRank, Ko as readSubjectLinks, Ku as getStateAdapter, L as conversationAggregateColumns, Lc as inboxItemTitle, Ld as automationSearchDocument, Ll as contentVersion, Ln as pushConversationInboxItemsNow, Lt as listTodos, Mc as searchInboxItems, Md as juniorQuestions, Ms as saveNotificationSchedule, Nd as questionFuzzyTitle, Ns as savePushSubscription, Pd as questionSearchDocument, Ps as isPausedBySlack, Pu as completeText, Q as canAnswerInboxItem, Qc as clearInboxWakeReasons, Qd as juniorConversationEvents, Qs as findUserByEmail, R as conversationRangeColumns, Rc as itemQuestion, Rd as juniorAutomations, Rl as contentVersionHeaders, Rt as setTodoStatusByUser, Sd as notLeadConversation, Sr as readConversationAccessFromSql, St as getRegistrations, Ti as escapeSlackMrkdwnText, U as conversationTurnFailedSql, Uc as subjectTodo, Ud as juniorInboxItems, Ul as fuzzyMatch, Vc as subjectKindLabel, Vd as inboxItemSearchDocument, Vl as searchTypedMemories, Wl as fuzzyRank, Wr as runWithSlackInstallation, X as canActOnInboxItem, Xo as linkedCodeProviders, Yo as codeRepositoryUrl, Zd as juniorConversationMetrics, Zo as canPauseConversationDelivery, _o as cancelWatch, a as getDb, ac as updateViewerDisplayName, af as juniorCodeRepositories, al as snoozeInboxItems, bc as listWaitingConversations, br as createConversationAccessReader, cd as parseSlackChannelId, cs as isPublicConversation, ct as inboxItemReaderForUserInConversation, dt as isInboxItemForEveryone, ef as juniorApiTokens, el as inboxItemInRow, eo as getEventCatalog, es as resumeConversationDelivery, et as canUserReadInboxItem, ff as juniorIdentities, fn as steerWebPendingMessages, ft as isOnlyAssignee, gf as juniorDestinations, gs as resolveNotificationTimezone, hf as juniorUsers, hs as sendPushNotificationToUser, i as getConversationStore, if as juniorCodeChanges, il as settleInboxSnoozes, jc as ownerConversationId, jd as todoSearchDocument, jr as getVercelConversationWorkQueue, js as readNotificationSchedule, kd as juniorTodos, kr as rootVisibleToViewer, ks as deletePushSubscription, lf as juniorConversations, ll as automationEventCatalog, lt as inboxItemVisibleTo, mf as slackPersonSearchDocument, ms as readWebPushConfig, mt as itemNeedsUser, nc as readViewerAvatarUrl, nf as codeChangeSearchDocument, ns as createPluginAnnotations, o as getSqlExecutor, ol as snoozeTimerTrigger, pf as slackPersonPredicate, pl as eventWatchUnavailable, qc as readAvatarFetch, qd as juniorConversationParticipants, ql as rankSearchMatches, qo as subjectKey, rc as resolveViewerUser, rf as codeRepositorySearchDocument, rl as readViewerInboxSnoozes, rs as listConversationAnnotations, rt as inboxItemForUser, sl as unsnoozeInboxRow, st as inboxItemReaderForUser, tl as inboxItemSnoozedBy, ud as parseSlackTeamId, vc as countInboxItemsNeedingUserBySubject, vi as postSlackMessage, w as loadConversationSlackTenantIds, wr as readableSlackTeamId, xd as listedConversation, xt as getPlugins, yc as inboxItemsNeedingUserVersionQuery, yd as rootSpaceIdSql, z as conversationUsageCostExpr, za as microUsdSql, zc as INBOX_SUBJECT_KINDS, zl as revalidateContent } from "./db-BFmyYZtJ.js";
3
+ import { E as withSpan, _ as runBestEffort, h as logWarn, m as logInfo, p as logException, y as setSentryUser } from "./logging--smS7XRK.js";
4
+ import { $t as AutomationEditError, Bt as deleteViewerTask, Et as throwApiError, G as reportConversationRead, Gt as collectionRowTitle, H as stopArchivedWork, Jt as readViewerAutomationRuns, Q as listOwnedWatches, Rt as activateViewerAutomationVersion, Tt as jsonResponse, Ut as updateViewerAutomation, V as setConversationArchive, Vt as readViewerAutomationEdit, Wt as ViewerTaskNotFoundError, Xt as readViewerAutomationVersions, Yt as readViewerAutomationSummary, Zt as readViewerAutomations, _t as createAttachmentUpload, at as readSpace, ct as acceptsWebMessages, dn as addStats, fn as readStats, h as previewOriginBelongsTo, hn as connectedState, ht as AttachmentUploadError, in as SAVINGS_NAMESPACE, it as listSpaces, m as readAttachmentContent, mn as closeBreaker, mt as webActorFromUser, nt as getSpaceLead, ot as updateSpace, p as AttachmentDownloadError, pn as breakerStates, qt as readViewerAutomationExecutions, rn as viewerAutomationCollection, rt as createSpace, st as writeLegacySpaceArchive, un as savingsTotals, wt as emptyResponse, xt as inviteToConversation, yt as writeAttachmentUpload, zt as changeViewerAutomationLifecycle } from "./agent-runner-AjrEV6Qe.js";
5
+ import { At as spaceListQuerySchema, B as conversationDetailQuerySchema, C as automationScheduleIntentSchema, D as automationVersionActivateSchema, E as automationUpdateSchema, Fn as automationTaskText, G as conversationParamsSchema, It as updateSpaceBodySchema, Kt as MAX_ATTACHMENT_BYTES, L as conversationAttachmentParamsSchema, Mt as spaceParamsSchema, N as CONVERSATION_DETAIL_VERSION_HEADER, O as automationVersionListSchema, Ot as archiveSpaceBodySchema, P as CONVERSATION_VERSION_HEADER, Pt as spaceSchema, R as conversationAttachmentQuerySchema, Rn as notificationScheduleSchema, Rt as conversationReadPositionSchema, T as automationSummarySchema, U as conversationEventPageSchema, V as conversationDetailReportSchema, W as conversationEventsQuerySchema, Wn as apiErrorSchema, _ as automationListQuerySchema, an as compileScheduleIntent, b as automationRunListSchema, c as automationEditSchema, fn as inboxItemQuestion, g as automationListPageSchema, in as ScheduleIntentError, jt as spaceListSchema, k as automationVersionParamsSchema, kt as createSpaceBodySchema, l as automationEventCatalogSchema, m as automationLifecycleSchema, o as isOpenTodoStatus, s as automationEditErrorSchema, u as automationExecutionListSchema, w as automationSchedulePreviewSchema, y as automationParamsSchema } from "./types-C4iC-IMC.js";
6
+ import { $ as userSearchQuerySchema, $t as conversationChildAgentsReportSchema, A as cacheHealthQuerySchema, At as startConnectionResponseSchema, B as serviceAccountParamsSchema, Bt as codeRepositoryQuerySchema, C as inboxSnoozeResourceQuerySchema, Ct as pushSubscriptionBodySchema, D as inboxSnoozeWakesClearSchema, Dt as connectionParamsSchema, E as inboxSnoozeSubjectSchema, Et as connectionListSchema, F as cacheWarmingSavingsRefillResponseSchema, G as createPersonalTokenBodySchema, Gt as conversationTodoSchema, H as startServiceAccountSignInResponseSchema, I as cacheWarmingSavingsReportSchema, Jt as todoStatusBodySchema, K as createdPersonalTokenSchema, Kt as conversationTodosReportSchema, L as closeCacheWarmingBreakerResponseSchema, Lt as codeOverviewReportSchema, M as cacheWarmingBreakerListSchema, N as cacheWarmingBreakerParamsSchema, Nt as codeChangeSearchQuerySchema, O as gatewayProvidersSchema, P as cacheWarmingSavingsQuerySchema, Pt as codeChangeSearchReportSchema, R as disconnectServiceAccountResponseSchema, Rt as codePersonReportSchema, S as inboxSnoozeCreateSchema, St as notificationSettingsSchema, T as inboxSnoozeSchema, Tt as testNotificationResponseSchema, U as searchQuerySchema, Vt as codeRepositoryReportSchema, W as searchReportSchema, Wt as personCodeQuerySchema, X as revokePersonalTokenResponseSchema, Xt as conversationWatchesReportSchema, Y as personalTokenParamsSchema, Zt as watchParamsSchema, _ as inboxItemListSchema, _n as acceptedConversationMessageSchema, _t as locationParamsSchema, a as statsReportSchema, an as objectLinksQuerySchema, at as avatarParamsSchema, b as inboxItemWaitingConversationsSchema, bn as forkConversationBodySchema, bt as activitySixHours$1, c as workspaceBodySchema, ct as peopleSearchReportSchema, dn as conversationDeliveryResponseSchema, dt as personalSpendReportSchema, en as continueConversationInSlackBodySchema, et as userSearchReportSchema, f as workspaceSchema, fn as conversationCatchUpBodySchema, g as inboxItemListQuerySchema, gn as createAttachmentUploadBodySchema, gt as locationDirectoryReportSchema, h as inboxItemCountSchema, hn as attachmentUploadSchema, ht as locationDetailReportSchema, in as attachObjectLinkResponseSchema, it as actorProfileReportSchema, j as cacheHealthReportSchema, k as updateGatewayProvidersBodySchema, kt as disconnectConnectionResponseSchema, l as workspaceListSchema, ln as conversationOutlineSchema, lt as personCardReportSchema, m as inboxItemCountQuerySchema, mn as attachmentUploadParamsSchema, n as versionsQuerySchema, on as objectLinksReportSchema, p as inboxItemActionSchema, pn as conversationCatchUpSchema, pt as spaceConfigurationSchema, q as personalTokenListSchema, qt as todoParamsSchema, r as versionsSchema, rn as attachObjectLinkBodySchema, rt as actorDirectoryReportSchema, s as deleteWorkspaceResponseSchema, sn as conversationStatsReportSchema, st as peopleSearchQuerySchema, tn as continueConversationInSlackResponseSchema, u as workspaceParamsSchema, un as conversationDeliveryBodySchema, ut as personParamsSchema, v as inboxItemParamsSchema, vn as createConversationBodySchema, vt as activityDays$1, w as inboxSnoozeResourceSchema, wt as pushSubscriptionDeleteBodySchema, xn as forkConversationResponseSchema, y as inboxItemSchema, yn as createConversationMessageBodySchema, yt as activityHours$2, z as serviceAccountListSchema, zt as codeRepositoryParamsSchema } from "./schema-DfqrHACA.js";
7
+ import { A as conversationUnchangedDetailWithMailboxSchema, B as runtimeInfoReportSchema, M as steerConversationPendingMessagesResponseSchema, N as healthReportSchema, P as pluginOperationalReportFeedSchema, T as conversationDetailWithMailboxReportSchema, U as skillReportsSchema, V as skillDetailReportSchema, _ as reorderPinnedConversationsBodySchema, a as conversationInviteResponseSchema, i as conversationInviteBodySchema, j as steerConversationPendingMessagesBodySchema, k as conversationPendingMessagesReportSchema, n as conversationFeedSchema, t as conversationFeedQuerySchema, v as reorderPinnedConversationsResponseSchema, z as pluginsSchema } from "./conversation-feed--9S0_PXL.js";
8
+ import { Bt as deleteWorkspace, Ft as saveUserCustomization, Gt as listWorkspacesByRepository, It as addConversationNote, Kt as updateWorkspace, L as isAllowedDomain, Pt as readUserCustomization, Vt as getWorkspace, Wt as listWorkspaces, Yt as workspaceRepoCheckoutPath, qt as WorkspaceValidationError, rr as createPluginEgress, tn as isExperimentalFeatureEnabled, z as parseEmail, zt as createWorkspace } from "./mailbox-turn-uSXhUFc9.js";
9
+ import { A as setConversationSubscriptionOperation, C as cancelQueuedMessagesOperation, Ct as resolveObjectLinkNow, D as renameConversationOperation, E as pinConversationOperation, Et as guardedFetch, Gt as resolvePersonLink, J as resolveMentions, Jt as readFirstHumanMessageTexts, M as reorderPinnedConversations, N as apiOperationHandler, O as setConversationAutoArchiveOperation, Q as readInboxItemForUser, S as archiveDoneConversationsOperation, St as readObjectLinkTypes, T as leaveConversationOperation, Tt as viewerCanViewPluginLink, X as actOnInboxItem, Xt as IMAGE_WIDTHS, Y as InboxItemActionError, Yt as createViewerMcp, Zt as decodeImageId, _ as createConversationForViewer, a as resolveInboxItemSubjects, at as updateUserSettings, bt as OBJECT_LINK_TTL_MS, c as readConversationAuxiliaryCostsFromSql, d as conversationVersionsQuery, f as readConversationDetailEtag, g as appendConversationMessageForViewer, gt as startSavingsRefill, h as readConversationEvents, i as encodePageCursor, it as readUserSettings, j as stopConversationOperation, jt as getProductionSlackAdapter, k as setConversationSpaceOperation, l as childAgentTotalsReport, m as keepQuickQuestionForViewer, mt as readSavingsRefill, n as readConversationFeed, o as readConversationDetail, p as forkConversationForViewer, pt as scheduleInboxSnoozeTimer, q as requireConversationPendingMessages, qt as conversationSummaryFromStoredConversation, r as decodePageCursor, rt as DEFAULT_USER_SETTINGS, s as readConversationTreeStates, t as conversationFeedVersionQuery, u as readConversationTreeMetricsFromSql, v as requireWebMessageConversation, wt as resolveObjectLinks, x as archiveConversationOperation, xt as readLinkObjectType, yt as readHealthReport } from "./list-Bxvg5wXf.js";
10
+ import { a as transcriptEntriesFromReportEvents, d as reportParentAgentInput, o as readConversationEventPage } from "./task-runner-C9Yc2_ae.js";
11
+ import { D as saveEnabledProviders, E as readServedProviders, O as cacheKeyPrefix, P as withLock, T as readEnabledProviders, k as createCache, n as getChatConfig, t as botConfig } from "./config-CHQ8X251.js";
12
+ import { a as listChildAgents } from "./parent-result-Ck1rFYRQ.js";
13
+ import { i as continueConversationInSlack, r as canContinueInSlack, t as BUSY } from "./continue-in-slack-D-FZ8Fin.js";
14
+ import { a as INPUT_IMAGE_TYPES, i as INLINE_VIDEO_TYPES, n as userCustomizationSchema, o as detectImageMediaType } from "./user-customization-CvfuY9Eo.js";
15
15
  import { u as sentry_exports } from "./sentry-CPbZjomA.js";
16
- import { a as fillUtcSixHours, c as trailingUtcDayWindow, d as utcHourKey, i as fillUtcHours, l as trailingUtcHourWindow, n as HOUR_MS$3, o as startOfUtcHour, r as fillUtcDays, s as sumUtcHoursIntoSixHours, t as DAY_MS$3, u as trailingUtcSixHourWindow } from "./reporting-window-C4dbzDiR.js";
17
- import { a as isConnectableProvider, c as startConnection, i as disconnectConnection, o as listConnections, t as escapeHtml, u as htmlCallbackResponse } from "./html-CfXEwl_h.js";
18
- import { G as mapBounded, I as createPluginLogger } from "./transcript-BHhJVY0P.js";
19
- import { D as listSpaceConfiguration } from "./job-runner-CySgpi9v.js";
20
- import { n as userCustomizationSchema } from "./user-customization-B27StpVQ.js";
21
- import { s as getSandboxResources, t as getCachedSnapshot } from "./resolve-BUFkmxkT.js";
22
- import { t as readDirectDatabaseUrl } from "./direct-url-BYgYfuIy.js";
16
+ import { N as webActorUserIds, a as disconnectServiceAccount, d as startServiceAccountSignIn, o as finishServiceAccountSignIn, s as getServiceAccountStatus, u as serviceAccountPlugins } from "./registry-iXMT5Jmh.js";
17
+ import { a as fillUtcDays, c as startOfUtcHour, d as trailingUtcHourWindow, f as trailingUtcSixHourWindow, i as HOUR_MS$3, l as sumUtcHoursIntoSixHours, o as fillUtcHours, p as utcHourKey, r as DAY_MS$3, s as fillUtcSixHours, u as trailingUtcDayWindow } from "./agent-status-BA5x3Xtp.js";
18
+ import { A as createUserTokenStore, n as hash, t as create, u as SANDBOX_RUNTIME } from "./profile-BQ-iBDsZ.js";
19
+ import { a as isConnectableProvider, c as startConnection, i as disconnectConnection, o as listConnections, t as escapeHtml, u as htmlCallbackResponse } from "./html-B3VKTGbJ.js";
20
+ import { L as mapBounded, h as createPluginLogger } from "./prompt-Dv7gkpD6.js";
21
+ import { F as listSpaceConfiguration } from "./job-runner-A1lCkybD.js";
22
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-DfSpJZdY.js";
23
+ import { o as getSandboxResources, t as getCachedSnapshot } from "./resolve-tony4ibz.js";
23
24
  import { Hono } from "hono";
24
25
  import * as z from "zod";
25
26
  import path from "node:path";
26
27
  import { createHash, randomBytes, randomUUID } from "node:crypto";
27
28
  import { normalizeEventIdentifier, objectPresentation, pluginUserPageContentSchema, pluginUserPageCursorSchema, pluginUserPageFilterSchema, pluginUserPageLinksSchema, pluginUserPageQuerySchema } from "@sentry/junior-plugin-api";
28
- import { and, asc, count as count$1, desc, eq, exists, gt, gte, inArray, isNotNull, isNull, lt, lte, ne, or, sql } from "drizzle-orm";
29
+ import { and, asc, count as count$1, desc, eq, exists, gt, gte, inArray, isNotNull, isNull, like, lt, lte, ne, or, sql } from "drizzle-orm";
29
30
  import { alias, union } from "drizzle-orm/pg-core";
30
31
  import fs from "node:fs/promises";
31
32
  import { readFileSync } from "node:fs";
32
- import { Client } from "@neondatabase/serverless";
33
- import pg from "pg";
34
33
  import { HTTPException } from "hono/http-exception";
35
34
  import { bodyLimit } from "hono/body-limit";
36
35
  import { waitUntil } from "@vercel/functions";
@@ -291,12 +290,17 @@ async function requireConversationChildAgents(conversationId, options = {}) {
291
290
  const [accessByConversation, children] = await Promise.all([readConversationAccessFromSql(db, [conversationId], options.viewer), listChildAgents(conversationId)]);
292
291
  const canExposePayload = accessByConversation.get(conversationId)?.canViewPrivateContent ?? false;
293
292
  const childIds = children.map((agent) => agent.childConversationId);
294
- const [metricsByChild, auxiliaryCostsByChild] = await Promise.all([readConversationTreeMetricsFromSql(db, childIds), readConversationAuxiliaryCostsFromSql(db, childIds)]);
293
+ const [metricsByChild, auxiliaryCostsByChild, treeByChild] = await Promise.all([
294
+ readConversationTreeMetricsFromSql(db, childIds),
295
+ readConversationAuxiliaryCostsFromSql(db, childIds),
296
+ readConversationTreeStates(db, childIds, options.viewer?.id)
297
+ ]);
295
298
  return {
296
299
  agents: children.map((agent) => {
297
300
  const metrics = metricsByChild.get(agent.childConversationId);
298
301
  const auxiliaryCosts = auxiliaryCostsByChild.get(agent.childConversationId);
299
302
  const childAgentTotals = childAgentTotalsReport(metrics, auxiliaryCosts);
303
+ const tree = treeByChild.get(agent.childConversationId);
300
304
  return {
301
305
  conversationId: agent.childConversationId,
302
306
  cumulativeDurationMs: metrics?.durationMs ?? 0,
@@ -305,13 +309,14 @@ async function requireConversationChildAgents(conversationId, options = {}) {
305
309
  ...childAgentTotals ? { childAgentTotals } : void 0,
306
310
  archivedAt: agent.archivedAtMs !== void 0 ? new Date(agent.archivedAtMs).toISOString() : null,
307
311
  kind: agent.kind,
312
+ ...agent.lastResult ? { lastResult: agent.lastResult } : void 0,
308
313
  status: agent.status,
314
+ treeState: tree?.treeState ?? "done",
309
315
  updatedAt: new Date(agent.updatedAtMs).toISOString(),
316
+ watching: tree?.watching ?? false,
310
317
  ...canExposePayload ? {
311
318
  ...agent.agentName ? { name: agent.agentName } : void 0,
312
- task: agent.task,
313
- ...agent.title ? { title: agent.title } : void 0,
314
- ...agent.errorMessage ? { error: agent.errorMessage } : void 0
319
+ title: agent.title ?? null
315
320
  } : { redacted: true }
316
321
  };
317
322
  }),
@@ -657,7 +662,7 @@ async function readConversationOutline(conversationId, options = {}) {
657
662
  }
658
663
  /**
659
664
  * Read the cut text of one role's messages in seq order. The
660
- * `message_role_idx` index reads only these messages, not all events.
665
+ * `message_role_seq_idx` index reads only these messages, in that order.
661
666
  */
662
667
  function readMessages(conversationId, role, ...filters) {
663
668
  return getDb().select({
@@ -889,7 +894,7 @@ function rootAggregateColumns(roots) {
889
894
  active: sql`(count(*) FILTER (WHERE ${conversationIsActiveSql(turnRoot)}))::integer`,
890
895
  conversations: sql`count(*)::integer`,
891
896
  durationMs: sql`COALESCE(sum(${roots.durationMs}), 0)::double precision`,
892
- failed: sql`(count(*) FILTER (WHERE ${conversationTurnFailedSql(turnRoot)} AND ${turnRoot.stoppedAt} IS NULL))::integer`,
897
+ failed: sql`(count(*) FILTER (WHERE ${turnRoot.stoppedAt} IS NULL AND ${conversationTurnFailedSql(turnRoot)}))::integer`,
893
898
  tokens: sql`sum(${roots.tokens})::double precision`
894
899
  };
895
900
  }
@@ -1450,7 +1455,7 @@ async function readConversationStatsFromSql() {
1450
1455
  /** Load aggregate conversation stats from durable SQL records. */
1451
1456
  const readConversationStats = createCachedReport({
1452
1457
  freshMs: 3e5,
1453
- keepMs: 36e5,
1458
+ keepMs: 6048e5,
1454
1459
  key: "conversation-stats",
1455
1460
  read: readConversationStatsFromSql,
1456
1461
  refreshFailedEvent: "conversation_stats.refresh.failed",
@@ -1558,7 +1563,7 @@ async function requireConversationTodos(conversationId, options = {}) {
1558
1563
  /**
1559
1564
  * Set the status of one To-do for a person. The To-dos are shared, so only
1560
1565
  * a Participant can change them, the same as the title. The agent sees the
1561
- * change in a `<todo-delta>` on its next Turn.
1566
+ * change in a To-do delta on its next Turn.
1562
1567
  */
1563
1568
  async function setConversationTodoStatus(viewer, conversationId, todoId, body) {
1564
1569
  const conversationAccess = (await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId);
@@ -1638,6 +1643,7 @@ function createConversationRoutes(options) {
1638
1643
  app.put("/:conversationId/space", requireViewer, apiOperationHandler(setConversationSpaceOperation, options));
1639
1644
  app.patch("/:conversationId/pin", requireViewer, apiOperationHandler(pinConversationOperation, options));
1640
1645
  app.patch("/:conversationId/delivery", requireViewer, validateRequest("param", conversationParamsSchema, "Invalid route parameters."), validateRequest("json", conversationDeliveryBodySchema, "Invalid request body."), async (context) => jsonResponse(conversationDeliveryResponseSchema, await setConversationDeliveryForViewer(context.get("viewer"), context.req.valid("param").conversationId, context.req.valid("json"))));
1646
+ app.post("/:conversationId/leave", requireViewer, apiOperationHandler(leaveConversationOperation, options));
1641
1647
  app.patch("/:conversationId/subscription", requireViewer, apiOperationHandler(setConversationSubscriptionOperation, options));
1642
1648
  app.post("/:conversationId/invites", requireViewer, validateRequest("param", conversationParamsSchema, "Invalid route parameters."), validateRequest("json", conversationInviteBodySchema, "Invalid request body."), async (context) => jsonResponse(conversationInviteResponseSchema, await inviteToConversation(context.get("viewer"), context.req.valid("param").conversationId, context.req.valid("json"))));
1643
1649
  app.patch("/:conversationId/title", requireViewer, apiOperationHandler(renameConversationOperation, options));
@@ -2226,7 +2232,7 @@ async function readCodeChangeSearchFromSql(query, viewerUserId) {
2226
2232
  const repositoryDocument = codeRepositorySearchDocument(juniorCodeRepositories);
2227
2233
  const textMatch = (condition) => db.select({ id: matched.id }).from(matched).innerJoin(juniorCodeRepositories, eq(juniorCodeRepositories.id, matched.repositoryId)).where(and(condition, terms.length > 1 ? sql`(${codeChangeSearchDocument(matched)} || ${repositoryDocument}) @@ to_tsquery('simple', ${everyTerm})` : void 0));
2228
2234
  const matches = number ? and(sql`${changeDocument} @@ to_tsquery('simple', ${everyTerm})`, sql`${juniorCodeChanges.number}::text like ${`${number}%`}`) : inArray(juniorCodeChanges.id, union(textMatch(sql`${codeChangeSearchDocument(matched)} @@ to_tsquery('simple', ${anyTerm})`), textMatch(sql`${repositoryDocument} @@ to_tsquery('simple', ${anyTerm})`)));
2229
- const visible = exists(db.select({ conversationId: juniorConversations.conversationId }).from(linked).innerJoin(juniorConversations, eq(juniorConversations.conversationId, sql`coalesce(${linked.rootConversationId}, ${linked.conversationId})`)).leftJoin(juniorDestinations, conversationRecordJoins.location).where(and(sql`${linked.conversationId} = any(${juniorCodeChanges.conversationIds})`, listedConversation(), rootVisibleToViewer(viewerUserId))));
2235
+ const visible = exists(db.select({ conversationId: juniorConversations.conversationId }).from(linked).innerJoin(juniorConversations, eq(juniorConversations.conversationId, sql`coalesce(${linked.rootConversationId}, ${linked.conversationId})`)).where(and(sql`${linked.conversationId} = any(${juniorCodeChanges.conversationIds})`, listedConversation(), rootVisibleToViewer(viewerUserId))));
2230
2236
  return (await db.transaction(async (tx) => {
2231
2237
  await tx.execute(sql`SELECT set_config('statement_timeout', ${String(CODE_CHANGE_SEARCH_TIMEOUT_MS)}, true)`);
2232
2238
  return await tx.select({
@@ -2482,10 +2488,10 @@ function emptyActor(actor) {
2482
2488
  };
2483
2489
  }
2484
2490
  function topLevelWhere() {
2485
- return isNull(juniorConversations.parentConversationId);
2491
+ return topLevelConversation();
2486
2492
  }
2487
2493
  function publicLocationWhere(locationId) {
2488
- return and(topLevelWhere(), locationId === DASHBOARD_LOCATION_ID ? eq(juniorDestinations.provider, "local") : and(eq(juniorDestinations.id, locationId), ne(juniorDestinations.provider, "local")), eq(juniorDestinations.visibility, "public"));
2494
+ return and(topLevelWhere(), locationId === DASHBOARD_LOCATION_ID ? eq(juniorDestinations.provider, "local") : and(eq(juniorDestinations.id, locationId), ne(juniorDestinations.provider, "local")), isPublicConversation(juniorConversations));
2489
2495
  }
2490
2496
  function locationColumns() {
2491
2497
  return {
@@ -2494,7 +2500,8 @@ function locationColumns() {
2494
2500
  destinationKind: juniorDestinations.kind,
2495
2501
  destinationProvider: juniorDestinations.provider,
2496
2502
  destinationProviderId: juniorDestinations.providerDestinationId,
2497
- destinationVisibility: juniorDestinations.visibility
2503
+ destinationVisibility: juniorDestinations.visibility,
2504
+ rootVisibility: juniorConversations.visibility
2498
2505
  };
2499
2506
  }
2500
2507
  function locationGroupBy() {
@@ -2504,12 +2511,16 @@ function locationGroupBy() {
2504
2511
  juniorDestinations.kind,
2505
2512
  juniorDestinations.provider,
2506
2513
  juniorDestinations.providerDestinationId,
2507
- juniorDestinations.visibility
2514
+ juniorDestinations.visibility,
2515
+ juniorConversations.visibility
2508
2516
  ];
2509
2517
  }
2510
- /** Admit only complete persisted-public destinations as named locations. */
2518
+ /**
2519
+ * Admit only public roots at complete persisted-public destinations as named
2520
+ * locations.
2521
+ */
2511
2522
  function locationFromAggregate(row) {
2512
- if (row.destinationVisibility !== "public" || !row.destinationId || !row.destinationProvider || !row.destinationProviderId || !row.destinationKind) return;
2523
+ if (row.rootVisibility !== "public" || row.destinationVisibility !== "public" || !row.destinationId || !row.destinationProvider || !row.destinationProviderId || !row.destinationKind) return;
2513
2524
  const dashboard = row.destinationProvider === "local";
2514
2525
  const location = {
2515
2526
  ...emptyMetrics(),
@@ -2561,15 +2572,15 @@ async function directoryActivityRows(db, start, hourStart) {
2561
2572
  )`;
2562
2573
  const select = {
2563
2574
  conversations: sql`COUNT(*)::integer`,
2564
- visibility: juniorDestinations.visibility
2575
+ visibility: juniorConversations.visibility
2565
2576
  };
2566
2577
  const [dayRows, hourRows] = await Promise.all([db.select({
2567
2578
  ...select,
2568
2579
  date: day
2569
- }).from(juniorConversations).leftJoin(juniorDestinations, eq(juniorDestinations.id, juniorConversations.destinationId)).where(and(topLevelWhere(), gte(juniorConversations.lastActivityAt, start))).groupBy(day, juniorDestinations.visibility), db.select({
2580
+ }).from(juniorConversations).where(and(topLevelWhere(), gte(juniorConversations.lastActivityAt, start))).groupBy(day, juniorConversations.visibility), db.select({
2570
2581
  ...select,
2571
2582
  date: hour
2572
- }).from(juniorConversations).leftJoin(juniorDestinations, eq(juniorDestinations.id, juniorConversations.destinationId)).where(and(topLevelWhere(), gte(juniorConversations.lastActivityAt, hourStart))).groupBy(hour, juniorDestinations.visibility)]);
2583
+ }).from(juniorConversations).where(and(topLevelWhere(), gte(juniorConversations.lastActivityAt, hourStart))).groupBy(hour, juniorConversations.visibility)]);
2573
2584
  return {
2574
2585
  dayRows,
2575
2586
  hourRows
@@ -2988,18 +2999,33 @@ async function spaceResponse(viewerUserId, spaceId, init) {
2988
2999
  return jsonResponse(spaceSchema, spaceReport(await requireSpace(viewerUserId, spaceId)), init);
2989
3000
  }
2990
3001
  // src/api/spaces/archive.ts
2991
- /** Create the route that archives or restores a Space with its Conversations. */
3002
+ /**
3003
+ * Create the route that archives or restores a Space. A Space is its Lead,
3004
+ * so this archives or restores the Lead's tree, as for any root, and an
3005
+ * archive stops the tree's running work.
3006
+ */
2992
3007
  function createSpaceArchiveRoutes(options) {
2993
3008
  const app = new Hono();
2994
3009
  app.patch("/:spaceId/archive", requireViewer, spaceParamsValidator, validateRequest("json", archiveSpaceBodySchema, "Invalid request body."), async (context) => {
2995
3010
  const viewerUserId = context.get("viewer").id;
2996
3011
  const { spaceId } = context.req.valid("param");
2997
- await requireMemberSpace(viewerUserId, spaceId);
2998
- await setSpaceArchive({
2999
- archived: context.req.valid("json").archived,
3000
- queue: options.queue,
3001
- spaceId
3002
- });
3012
+ const { archived } = context.req.valid("json");
3013
+ const space = await requireMemberSpace(viewerUserId, spaceId);
3014
+ const lead = await getSpaceLead(spaceId);
3015
+ if (archived !== (space.archivedAt !== null)) {
3016
+ const result = await setConversationArchive(archived ? {
3017
+ applyToChildren: true,
3018
+ archived: true,
3019
+ conversationId: lead.conversationId
3020
+ } : {
3021
+ applyToChildren: true,
3022
+ archived: false,
3023
+ conversationId: lead.conversationId,
3024
+ userId: viewerUserId
3025
+ });
3026
+ await writeLegacySpaceArchive(spaceId, result.status === "archived" ? new Date(result.archivedAt) : null);
3027
+ }
3028
+ if (archived) await stopArchivedWork(lead.conversationId, options.queue);
3003
3029
  return await spaceResponse(viewerUserId, spaceId);
3004
3030
  });
3005
3031
  return app;
@@ -3007,7 +3033,7 @@ function createSpaceArchiveRoutes(options) {
3007
3033
  // src/api/spaces/configuration.ts
3008
3034
  /**
3009
3035
  * Create the route that reads a Space's configuration. Anyone who reads the
3010
- * Space reads it. Junior changes it with its `setSpaceConfiguration` tool,
3036
+ * Space reads it. Junior changes it with its `setConfiguration` tool,
3011
3037
  * when a member asks.
3012
3038
  */
3013
3039
  function createSpaceConfigurationRoutes() {
@@ -3023,92 +3049,66 @@ function createSpaceConfigurationRoutes() {
3023
3049
  });
3024
3050
  return app;
3025
3051
  }
3026
- // src/api/spaces/lead.ts
3052
+ // src/api/spaces/state.ts
3027
3053
  /**
3028
- * Create the route that finds a Space's Lead. A member's first read creates
3029
- * it. Anyone who reads the Space reads its Lead, which is public like the
3030
- * Space.
3054
+ * The most Conversations of the listed Spaces that one read rolls up, newest
3055
+ * activity first. The Lead archives finished work, so a Space has few
3056
+ * Conversations that are not archived. Past this, the oldest ones count for
3057
+ * nothing.
3031
3058
  */
3032
- function createSpaceLeadRoutes() {
3033
- const app = new Hono();
3034
- app.get("/:spaceId/lead", requireViewer, spaceParamsValidator, async (context) => {
3035
- const viewer = context.get("viewer");
3036
- const space = await requireSpace(viewer.id, context.req.valid("param").spaceId);
3037
- const lead = space.viewerIsMember ? await getSpaceLead({
3038
- member: viewer,
3039
- space
3040
- }) : await readSpaceLead(space.id);
3041
- if (!lead) throwApiError(404, "This Space has no Lead yet.");
3042
- const lastSeq = await readConversationLastEventSeq(getSqlExecutor(), lead.conversationId);
3043
- const watches = await listWatches({ conversationId: lead.conversationId });
3044
- const watchedConversationIds = [...new Set(watches.filter((watch) => watch.namespace === "junior" && isAgentResourceType(watch.resourceType)).map((watch) => watch.identifier))];
3045
- return jsonResponse(leadSchema, {
3046
- conversationId: lead.conversationId,
3047
- lastSeq,
3048
- watchedConversationIds
3049
- }, { headers: { "cache-control": "private, no-store" } });
3050
- });
3051
- return app;
3052
- }
3053
- // src/api/spaces/members.ts
3059
+ const SPACE_STATE_CONVERSATION_LIMIT = 200;
3060
+ const spaceLead = alias(juniorConversations, "state_space_lead");
3061
+ const TREE_STATE_ORDER = [
3062
+ "needs_you",
3063
+ "working",
3064
+ "done"
3065
+ ];
3054
3066
  /**
3055
- * Create the routes that list a Space's members, add a member, and join or
3056
- * leave it.
3067
+ * Roll up the tree state of every Conversation in each Space that the viewer
3068
+ * can read and that is not archived, the Lead included. Each Space gets an
3069
+ * entry, and a Space with none of them reads `done`. `treeState` is the
3070
+ * first that applies over them, as for one Conversation. `latestTurnFailed`
3071
+ * is set when the latest Turn of one of them failed.
3057
3072
  */
3058
- function createSpaceMemberRoutes() {
3059
- const app = new Hono();
3060
- app.get("/:spaceId/members", requireViewer, spaceParamsValidator, async (context) => {
3061
- const { spaceId } = context.req.valid("param");
3062
- await requireSpace(context.get("viewer").id, spaceId);
3063
- const members = await listSpaceMembers(spaceId);
3064
- return jsonResponse(spaceMemberListSchema, { members: members.map((member) => ({
3065
- ...member,
3066
- joinedAt: member.joinedAt.toISOString()
3067
- })) });
3068
- });
3069
- app.post("/:spaceId/members", requireViewer, spaceParamsValidator, validateRequest("json", addSpaceMemberBodySchema, "Invalid request body."), async (context) => {
3070
- const viewerUserId = context.get("viewer").id;
3071
- const { spaceId } = context.req.valid("param");
3072
- await requireMemberSpace(viewerUserId, spaceId);
3073
- const email = normalizeIdentityEmail(context.req.valid("json").email);
3074
- const person = email ? await readCachedUserByEmail(getDb(), email) : void 0;
3075
- if (!person) throwApiError(404, "No person has that email.");
3076
- await joinSpace(spaceId, person.user.id);
3077
- return await spaceResponse(viewerUserId, spaceId);
3078
- });
3079
- app.put("/:spaceId/members/me", requireViewer, spaceParamsValidator, async (context) => {
3080
- const viewerUserId = context.get("viewer").id;
3081
- const { spaceId } = context.req.valid("param");
3082
- await requireSpace(viewerUserId, spaceId);
3083
- await joinSpace(spaceId, viewerUserId);
3084
- return await spaceResponse(viewerUserId, spaceId);
3085
- });
3086
- app.delete("/:spaceId/members/me", requireViewer, spaceParamsValidator, async (context) => {
3087
- const viewerUserId = context.get("viewer").id;
3088
- const { spaceId } = context.req.valid("param");
3089
- const space = await requireSpace(viewerUserId, spaceId);
3090
- if (await leaveSpace(spaceId, viewerUserId) === "last_member") throwApiError(409, "The last member can't leave a private Space.");
3091
- if (space.visibility === "private") return jsonResponse(spaceSchema, {
3092
- ...spaceReport(space),
3093
- memberCount: space.memberCount - 1,
3094
- viewerIsMember: false
3095
- });
3096
- return await spaceResponse(viewerUserId, spaceId);
3097
- });
3098
- return app;
3073
+ async function readSpaceStates(db, spaceIds, viewerUserId) {
3074
+ if (spaceIds.length === 0) return /* @__PURE__ */ new Map();
3075
+ const leads = db.select({ id: spaceLead.conversationId }).from(spaceLead).where(and(eq(spaceLead.kind, "lead"), inArray(spaceLead.spaceId, [...spaceIds])));
3076
+ const roots = await db.select({
3077
+ conversationId: juniorConversations.conversationId,
3078
+ spaceId: rootSpaceIdSql(juniorConversations),
3079
+ latestTurnFailed: conversationTurnFailedSql(juniorConversations)
3080
+ }).from(juniorConversations).where(and(or(inArray(juniorConversations.conversationId, leads), inArray(juniorConversations.parentConversationId, leads)), isNull(juniorConversations.archivedAt), isNull(juniorConversations.quickQuestionAt), rootVisibleToViewer(viewerUserId))).orderBy(desc(juniorConversations.lastActivityAt)).limit(SPACE_STATE_CONVERSATION_LIMIT);
3081
+ const trees = await readConversationTreeStates(db, roots.map((root) => root.conversationId), viewerUserId);
3082
+ const states = new Map(spaceIds.map((spaceId) => [spaceId, {
3083
+ latestTurnFailed: false,
3084
+ treeState: "done"
3085
+ }]));
3086
+ for (const root of roots) {
3087
+ const current = root.spaceId ? states.get(root.spaceId) : void 0;
3088
+ if (!current) continue;
3089
+ const treeState = trees.get(root.conversationId)?.treeState ?? "done";
3090
+ if (root.latestTurnFailed) current.latestTurnFailed = true;
3091
+ if (TREE_STATE_ORDER.indexOf(treeState) < TREE_STATE_ORDER.indexOf(current.treeState)) current.treeState = treeState;
3092
+ }
3093
+ return states;
3099
3094
  }
3100
3095
  // src/api/spaces/space.ts
3101
3096
  /** Create the routes that list, create, read, and change Spaces. */
3102
3097
  function createSpaceRoutes() {
3103
3098
  const app = new Hono();
3104
3099
  app.get("/", requireViewer, validateRequest("query", spaceListQuerySchema, "Invalid query parameters."), async (context) => {
3105
- const spaces = await listSpaces(context.get("viewer").id, context.req.valid("query"));
3106
- return jsonResponse(spaceListSchema, { spaces: spaces.map(spaceReport) });
3100
+ const viewerUserId = context.get("viewer").id;
3101
+ const spaces = await listSpaces(viewerUserId, context.req.valid("query"));
3102
+ const states = await readSpaceStates(getDb(), spaces.map((space) => space.id), viewerUserId);
3103
+ return jsonResponse(spaceListSchema, { spaces: spaces.map((space) => ({
3104
+ ...spaceReport(space),
3105
+ ...states.get(space.id)
3106
+ })) });
3107
3107
  });
3108
3108
  app.post("/", requireViewer, validateRequest("json", createSpaceBodySchema, "Invalid request body."), async (context) => {
3109
3109
  const body = context.req.valid("json");
3110
3110
  const space = await createSpace({
3111
- creatorUserId: context.get("viewer").id,
3111
+ creator: context.get("viewer"),
3112
3112
  name: body.name,
3113
3113
  description: body.description ?? null,
3114
3114
  visibility: body.visibility
@@ -3534,7 +3534,7 @@ async function readPeoplePluginReports(args) {
3534
3534
  reports: [],
3535
3535
  source: "plugins"
3536
3536
  });
3537
- const { getPluginProfileReports } = await import("./db-DXTOYRzR.js").then((n) => n.W);
3537
+ const { getPluginProfileReports } = await import("./reports-WKHfGTsU.js");
3538
3538
  return pluginOperationalReportFeedSchema.parse({
3539
3539
  generatedAt: new Date(nowMs).toISOString(),
3540
3540
  reports: await getPluginProfileReports({
@@ -3598,7 +3598,7 @@ function channelExpression(table) {
3598
3598
  }
3599
3599
  function locationLabel(row) {
3600
3600
  if (row.surface !== "slack") return surfaceLabel(row.surface);
3601
- if (row.destinationVisibility !== "public") return "Private Conversation";
3601
+ if (row.visibility !== "public") return "Private Conversation";
3602
3602
  return slackLocationLabel({
3603
3603
  channel: row.channel || void 0,
3604
3604
  channelName: row.channelName ?? void 0
@@ -3654,7 +3654,7 @@ function rootBucketRows(args) {
3654
3654
  date: sql`TO_CHAR(${buckets.bucket}, ${sql.raw(`'${format}'`)})`,
3655
3655
  durationMs: sql`COALESCE(sum(${buckets.durationMs}), 0)::double precision`,
3656
3656
  failed: sql`(count(*) FILTER (
3657
- WHERE ${buckets.isLastTurn} AND ${conversationTurnFailedSql(turnRoot)} AND ${turnRoot.stoppedAt} IS NULL
3657
+ WHERE ${buckets.isLastTurn} AND ${turnRoot.stoppedAt} IS NULL AND ${conversationTurnFailedSql(turnRoot)}
3658
3658
  ))::integer`,
3659
3659
  tokens: sql`sum(${buckets.tokens})::double precision`
3660
3660
  }).from(buckets).innerJoin(turnRoot, eq(turnRoot.conversationId, buckets.rootConversationId)).where(sql`${buckets.bucket} >= (${args.since.toISOString()}::timestamptz AT TIME ZONE 'UTC')`).groupBy(buckets.bucket);
@@ -3688,10 +3688,10 @@ async function readPeopleProfileFromSql(email, options = {}) {
3688
3688
  getDb().select({
3689
3689
  channel,
3690
3690
  channelName: turnRoot.channelName,
3691
- destinationVisibility: juniorDestinations.visibility,
3692
3691
  surface,
3692
+ visibility: turnRoot.visibility,
3693
3693
  ...aggregate
3694
- }).from(roots).innerJoin(turnRoot, personRootJoin(roots)).leftJoin(juniorDestinations, eq(juniorDestinations.id, turnRoot.destinationId)).groupBy(channel, turnRoot.channelName, juniorDestinations.visibility, surface),
3694
+ }).from(roots).innerJoin(turnRoot, personRootJoin(roots)).groupBy(channel, turnRoot.channelName, turnRoot.visibility, surface),
3695
3695
  getDb().select({
3696
3696
  surface,
3697
3697
  ...aggregate
@@ -3867,6 +3867,94 @@ async function readPersonalSpendFromSql(email, nowMs = Date.now()) {
3867
3867
  windowStart: thirtyDayStart.toISOString()
3868
3868
  };
3869
3869
  }
3870
+ // src/api/people/user-search.query.ts
3871
+ const USER_SEARCH_TERMS = 4;
3872
+ /**
3873
+ * Split typed text into lowercase search terms. A leading `@` of a Slack
3874
+ * handle is not part of it.
3875
+ */
3876
+ function userSearchTerms(query) {
3877
+ return query.toLowerCase().split(/\s+/).map((term) => term.replace(/^@+/, "")).filter(Boolean).slice(0, USER_SEARCH_TERMS);
3878
+ }
3879
+ /**
3880
+ * Find Users whose name, Slack name, Slack handle, or primary email holds
3881
+ * each word of the query. An exact match of a whole field ranks first, then
3882
+ * a field or a word of the name that starts with the query, then any other
3883
+ * match. Ties sort by name, then email, then User id, so the order is
3884
+ * stable. Users are people: Slack bots and service accounts have none.
3885
+ */
3886
+ async function readUserSearchFromSql(args) {
3887
+ const terms = userSearchTerms(args.query);
3888
+ if (terms.length === 0) return [];
3889
+ const whole = terms.join(" ");
3890
+ const { target } = args;
3891
+ const db = getDb();
3892
+ const slack = alias(juniorIdentities, "user_search_slack");
3893
+ const slackJoin = and(eq(slack.userId, juniorUsers.id), slackPersonPredicate(slack));
3894
+ const name = sql`lower(coalesce(${juniorUsers.displayName}, ${slack.displayName}, ''))`;
3895
+ const handle = sql`lower(coalesce(${slack.handle}, ''))`;
3896
+ const email = juniorUsers.primaryEmailNormalized;
3897
+ const document = sql`(${name} || ' ' || lower(coalesce(${slack.displayName}, '')) || ' ' || ${handle} || ' ' || ${email})`;
3898
+ const exact = sql`(${name} = ${whole} or ${handle} = ${whole} or ${email} = ${whole} or split_part(${email}, '@', 1) = ${whole})`;
3899
+ const prefix = sql`(starts_with(${name}, ${whole}) or starts_with(${handle}, ${whole}) or starts_with(${email}, ${whole}) or strpos(' ' || ${name}, ' ' || ${whole}) > 0)`;
3900
+ const rank = sql`case when ${exact} then 0 when ${prefix} then 1 else 2 end`;
3901
+ const matches = db.selectDistinctOn([juniorUsers.id], {
3902
+ email: juniorUsers.primaryEmail,
3903
+ emailNormalized: email,
3904
+ fullName: sql`coalesce(${juniorUsers.displayName}, ${slack.displayName})`.as("full_name"),
3905
+ rank: rank.as("rank"),
3906
+ slackUserName: slack.handle,
3907
+ sortName: name.as("sort_name"),
3908
+ userId: juniorUsers.id
3909
+ }).from(juniorUsers).leftJoin(slack, slackJoin).where(and(...terms.map((term) => sql`strpos(${document}, ${term}) > 0`))).orderBy(juniorUsers.id, asc(rank), asc(slack.id)).as("user_search_matches");
3910
+ const rows = await db.select({
3911
+ email: matches.email,
3912
+ fullName: matches.fullName,
3913
+ isMember: memberSql(db, target, matches.userId).as("is_member"),
3914
+ slackUserName: matches.slackUserName,
3915
+ userId: matches.userId
3916
+ }).from(matches).orderBy(asc(matches.rank), asc(matches.sortName), asc(matches.emailNormalized), asc(matches.userId)).limit(args.limit);
3917
+ const avatars = await readUserAvatarUrls(db, rows.map((row) => row.userId));
3918
+ return rows.map((row) => {
3919
+ const fullName = row.fullName?.trim();
3920
+ const avatarUrl = avatars.get(row.userId);
3921
+ return {
3922
+ email: row.email,
3923
+ userId: row.userId,
3924
+ ...fullName ? { fullName } : void 0,
3925
+ ...row.slackUserName ? { slackUserName: row.slackUserName } : void 0,
3926
+ ...avatarUrl ? { avatarUrl } : void 0,
3927
+ ...row.isMember ? { isMember: true } : void 0
3928
+ };
3929
+ });
3930
+ }
3931
+ /** SQL: the User is already a Participant of the root. */
3932
+ function memberSql(db, target, userId) {
3933
+ const participants = juniorConversationParticipants;
3934
+ return sql`${exists(db.select({ userId: participants.userId }).from(participants).where(and(eq(participants.rootConversationId, target.rootConversationId), eq(participants.userId, userId))))}`;
3935
+ }
3936
+ // src/api/people/user-search.ts
3937
+ /**
3938
+ * Find Users to add to a Conversation, such as a Space's Lead. The viewer
3939
+ * must be able to read it, so who is a Participant does not leak;
3940
+ * otherwise it looks missing. The Users are those of this install, which is
3941
+ * the tenant of every dashboard Conversation, with or without a Slack
3942
+ * account. Whether the viewer may add them stays with the route that adds
3943
+ * them.
3944
+ */
3945
+ async function searchUsersForViewer(viewer, query) {
3946
+ return await readUserSearchFromSql({
3947
+ limit: query.limit,
3948
+ query: query.q,
3949
+ target: await readUserSearchTarget(viewer, query)
3950
+ });
3951
+ }
3952
+ async function readUserSearchTarget(viewer, query) {
3953
+ const { conversationId } = query;
3954
+ const access = (await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId);
3955
+ if (!access?.canViewPrivateContent || !access.rootConversationId) throwApiError(404, "Conversation not found.");
3956
+ return { rootConversationId: access.rootConversationId };
3957
+ }
3870
3958
  // src/api/people/routes.ts
3871
3959
  /** Create the HTTP routes owned by the People API. */
3872
3960
  function createPeopleRoutes(options) {
@@ -3890,6 +3978,7 @@ function createPeopleRoutes(options) {
3890
3978
  const slackTeamId = conversationId ? readableSlackTeamId((await readConversationAccessFromSql(getDb(), [conversationId], context.get("viewer"))).get(conversationId)) : void 0;
3891
3979
  return jsonResponse(peopleSearchReportSchema, { people: await readPeopleSearchFromSql(q, slackTeamId) });
3892
3980
  });
3981
+ app.get("/user-search", requireViewer, validateRequest("query", userSearchQuerySchema, "Invalid search query."), async (context) => jsonResponse(userSearchReportSchema, { users: await searchUsersForViewer(context.get("viewer"), context.req.valid("query")) }));
3893
3982
  app.get("/:email/plugin-reports", requireViewer, validateRequest("param", personParamsSchema, "Invalid route parameters."), async (context) => {
3894
3983
  const { email } = context.req.valid("param");
3895
3984
  const viewer = context.get("viewer");
@@ -4059,33 +4148,63 @@ async function searchAutomationsForViewer(viewer, query, limit) {
4059
4148
  }]);
4060
4149
  }
4061
4150
  // src/chat/inbox-items/search.ts
4151
+ function codeChangeSubjectKinds() {
4152
+ return getPlugins().flatMap((plugin) => (plugin.inboxSubjects ?? []).flatMap((subject) => {
4153
+ const kind = `${plugin.manifest.name}:${subject.kind}`;
4154
+ return codeChangeSubjectProvider(kind) ? [kind] : [];
4155
+ }));
4156
+ }
4157
+ function subjectCodeChange(item, change) {
4158
+ return and(eq(change.providerId, item.subjectId), eq(change.provider, sql`split_part(${item.subjectKind}, ':', 1)`));
4159
+ }
4160
+ function subjectQuestion(item, question) {
4161
+ return and(eq(item.subjectKind, INBOX_SUBJECT_KINDS.question), eq(question.id, item.subjectId));
4162
+ }
4062
4163
  /**
4063
4164
  * Find the items of the viewer's own Inbox, open and closed, as the Inbox
4064
4165
  * shows them. A word of the title or body starts with each word of the
4065
- * query, or the title is close to the query despite a typo. Open items come
4166
+ * query, or the title is close to the query despite a typo. A question
4167
+ * item matches on its question's title and body. An item whose subject is
4168
+ * a code change also matches on the code change's title. Open items come
4066
4169
  * first, each group best match first. Reads the GIN indexes
4067
- * `junior_inbox_items_search_idx` and `junior_inbox_items_title_trgm_idx`.
4170
+ * `junior_inbox_items_search_idx`, `junior_inbox_items_title_trgm_idx`,
4171
+ * `junior_questions_search_idx`, `junior_questions_title_trgm_idx`, and
4172
+ * `junior_code_changes_search_idx`.
4068
4173
  */
4069
4174
  async function searchInboxItemsForUser(viewer, query, limit) {
4070
4175
  const db = getDb();
4071
4176
  const items = juniorInboxItems;
4072
- const candidates = db.select({ id: items.id }).from(items).where(and(or(prefixMatch(inboxItemSearchDocument(items), query), fuzzyMatch(inboxItemFuzzyTitle(items), query)), inboxItemVisibleTo(inboxItemReaderForUser(viewer)), inboxItemForUser(viewer.id))).orderBy(desc(items.updatedAt), desc(items.id)).limit(200).as("inbox_item_candidates");
4177
+ const visible = and(inboxItemVisibleTo(inboxItemReaderForUser(viewer)), inboxItemForUser(viewer.id));
4178
+ const ownMatches = db.select({ id: items.id }).from(items).where(and(or(prefixMatch(inboxItemSearchDocument(items), query), fuzzyMatch(inboxItemFuzzyTitle(items), query)), visible)).orderBy(desc(items.updatedAt), desc(items.id)).limit(200);
4179
+ const questionMatches = db.select({ id: items.id }).from(juniorQuestions).innerJoin(items, subjectQuestion(items, juniorQuestions)).where(and(or(prefixMatch(questionSearchDocument(juniorQuestions), query), fuzzyMatch(questionFuzzyTitle(juniorQuestions), query)), visible)).orderBy(desc(items.updatedAt), desc(items.id)).limit(200);
4180
+ const kinds = codeChangeSubjectKinds();
4181
+ const subjectMatches = db.select({ id: items.id }).from(juniorCodeChanges).innerJoin(items, subjectCodeChange(items, juniorCodeChanges)).where(and(prefixMatch(codeChangeSearchDocument(juniorCodeChanges), query), inArray(items.subjectKind, kinds), visible)).orderBy(desc(items.updatedAt), desc(items.id)).limit(200);
4182
+ const candidates = (kinds.length ? union(ownMatches, questionMatches, subjectMatches) : union(ownMatches, questionMatches)).as("inbox_item_candidates");
4073
4183
  const item = alias(juniorInboxItems, "inbox_item");
4074
- const document = inboxItemSearchDocument(item);
4075
- const title = inboxItemFuzzyTitle(item);
4184
+ const question = alias(juniorQuestions, "inbox_item_question");
4185
+ const change = alias(juniorCodeChanges, "inbox_item_change");
4186
+ const document = sql`coalesce(${questionSearchDocument(question)}, ${inboxItemSearchDocument(item)})`;
4187
+ const changeDocument = codeChangeSearchDocument(change);
4188
+ const title = sql`coalesce(${questionFuzzyTitle(question)}, ${inboxItemFuzzyTitle(item)})`;
4076
4189
  const rows = await db.select({
4190
+ changeLexical: prefixRank(changeDocument, query),
4191
+ changeMatched: prefixMatch(changeDocument, query),
4077
4192
  fuzzy: fuzzyRank(title, query),
4078
4193
  fuzzyMatched: fuzzyMatch(title, query),
4079
4194
  id: item.id,
4080
4195
  lexical: prefixRank(document, query),
4081
4196
  lexicalMatched: prefixMatch(document, query),
4082
4197
  status: item.status,
4083
- title: item.title,
4198
+ title: sql`coalesce(${question.title}, ${item.title}, '')`,
4084
4199
  updatedAt: item.updatedAt
4085
- }).from(candidates).innerJoin(item, eq(item.id, candidates.id));
4200
+ }).from(candidates).innerJoin(item, eq(item.id, candidates.id)).leftJoin(question, subjectQuestion(item, question)).leftJoin(change, and(subjectCodeChange(item, change), kinds.length ? inArray(item.subjectKind, kinds) : sql`false`));
4086
4201
  const ranked = rankSearchMatches(scoredSearchMatches(rows, {
4087
4202
  fuzzy: (row) => row.fuzzyMatched ? Number(row.fuzzy) : void 0,
4088
- lexical: (row) => row.lexicalMatched ? Number(row.lexical) : void 0
4203
+ lexical: (row) => {
4204
+ const own = row.lexicalMatched ? Number(row.lexical) : void 0;
4205
+ const subject = row.changeMatched ? Number(row.changeLexical) : void 0;
4206
+ return own === void 0 || subject === void 0 ? own ?? subject : Math.max(own, subject);
4207
+ }
4089
4208
  }), {
4090
4209
  key: (row) => row.id,
4091
4210
  tiebreak: (left, right) => right.updatedAt.getTime() - left.updatedAt.getTime() || right.id.localeCompare(left.id)
@@ -4193,7 +4312,7 @@ async function searchTodosForViewer(viewer, query, limit) {
4193
4312
  const candidates = db.select({
4194
4313
  conversationId: todos.conversationId,
4195
4314
  id: todos.id
4196
- }).from(todos).innerJoin(conversation, eq(conversation.conversationId, todos.conversationId)).innerJoin(juniorConversations, and(eq(juniorConversations.conversationId, conversation.rootConversationId), eq(juniorConversations.rootConversationId, juniorConversations.conversationId), isNull(juniorConversations.parentConversationId))).leftJoin(juniorDestinations, eq(juniorDestinations.id, juniorConversations.destinationId)).where(and(or(prefixMatch(todoSearchDocument(todos), query), fuzzyMatch(todoFuzzyTitle(todos), query)), or(isNotNull(conversation.parentConversationId), eq(conversation.rootConversationId, conversation.conversationId)), rootVisibleToViewer(viewer.id))).orderBy(desc(todos.updatedAt), desc(todos.conversationId), desc(todos.id)).limit(200).as("todo_candidates");
4315
+ }).from(todos).innerJoin(conversation, eq(conversation.conversationId, todos.conversationId)).innerJoin(juniorConversations, and(eq(juniorConversations.conversationId, conversation.rootConversationId), eq(juniorConversations.rootConversationId, juniorConversations.conversationId), isNull(juniorConversations.parentConversationId))).where(and(or(prefixMatch(todoSearchDocument(todos), query), fuzzyMatch(todoFuzzyTitle(todos), query)), or(isNotNull(conversation.parentConversationId), eq(conversation.rootConversationId, conversation.conversationId)), rootVisibleToViewer(viewer.id))).orderBy(desc(todos.updatedAt), desc(todos.conversationId), desc(todos.id)).limit(200).as("todo_candidates");
4197
4316
  const todo = alias(juniorTodos, "todo");
4198
4317
  const document = todoSearchDocument(todo);
4199
4318
  const title = todoFuzzyTitle(todo);
@@ -4267,11 +4386,13 @@ function createSearchRoutes() {
4267
4386
  /**
4268
4387
  * Public URL of the OAuth callback for one plugin's service account.
4269
4388
  *
4270
- * It uses the request origin unless `JUNIOR_BASE_URL` is set, so the
4389
+ * It uses the request origin unless a base URL is configured, so the
4271
4390
  * provider sends the Admin back to the dashboard session that started it.
4391
+ * The Vercel URL is not used here: it can name another host than the one
4392
+ * the Admin signed in on.
4272
4393
  */
4273
4394
  function callbackUrl(request, provider) {
4274
- const base = process.env["JUNIOR_BASE_URL"]?.trim() || new URL(request.url).origin;
4395
+ const base = getChatConfig().deployment.configuredBaseUrl ?? new URL(request.url).origin;
4275
4396
  return new URL(`api/service-accounts/${encodeURIComponent(provider)}/callback`, base.endsWith("/") ? base : `${base}/`).toString();
4276
4397
  }
4277
4398
  function requirePlugin(provider) {
@@ -5026,59 +5147,64 @@ function newestInGroup(group) {
5026
5147
  const candidateColumns = {
5027
5148
  createdAt: juniorInboxItems.createdAt,
5028
5149
  id: juniorInboxItems.id,
5029
- subjectId: juniorInboxItems.subjectId,
5030
- subjectUrl: juniorInboxItems.subjectUrl,
5031
- title: juniorInboxItems.title
5150
+ title: inboxItemTitle.as("title")
5032
5151
  };
5033
5152
  /**
5034
- * Read the related work of each open item in a page: the other open items
5035
- * that the reader can see with the same subject id or URL, or linked to one
5036
- * of the item's other linked Conversations, and those Conversations when the
5037
- * viewer can see them. The reads cover the whole page at once, so the query
5038
- * count does not grow with the page.
5153
+ * The outside object that a plugin item is about, which related work
5154
+ * matches: its subject id, such as a pull request. A question's related
5155
+ * links show on its card, but they relate it to no other item. Other core
5156
+ * kinds relate to nothing by object.
5157
+ */
5158
+ function relatedObjects(item) {
5159
+ return subjectKindPlugin(item.subject.kind) ? [item.subject.id] : [];
5160
+ }
5161
+ /**
5162
+ * Read the related work of each open item in a page: the other open plugin
5163
+ * items that the reader can see about the same object
5164
+ * (`relatedObjects`), or in one of the Conversations that the item links,
5165
+ * and the linked Conversations when the viewer can see them. The reads
5166
+ * cover the whole page at once, so the query count does not grow with the
5167
+ * page.
5039
5168
  */
5040
5169
  async function readRelatedReviewWork(db, reader, viewer, items) {
5041
5170
  const open = items.filter((item) => item.status === "open");
5042
- const subjectIds = [...new Set(open.flatMap((item) => item.subject?.id ?? []))];
5043
- const subjectUrls = [...new Set(open.flatMap((item) => item.subject?.url ?? []))];
5171
+ const objects = [...new Set(open.flatMap(relatedObjects))];
5044
5172
  const linkIds = [...new Set(open.flatMap(linkedWork))];
5045
- const subjectRanks = db.select({
5173
+ const objectRanks = db.select({
5046
5174
  ...candidateColumns,
5047
- idRank: newestInGroup(juniorInboxItems.subjectId).as("id_rank"),
5048
- urlRank: newestInGroup(juniorInboxItems.subjectUrl).as("url_rank")
5049
- }).from(juniorInboxItems).where(and(openVisible(reader), or(...subjectIds.length > 0 ? [inArray(juniorInboxItems.subjectId, subjectIds)] : [], ...subjectUrls.length > 0 ? [inArray(juniorInboxItems.subjectUrl, subjectUrls)] : []))).as("subject_ranks");
5175
+ subjectId: juniorInboxItems.subjectId,
5176
+ rank: newestInGroup(juniorInboxItems.subjectId).as("object_rank")
5177
+ }).from(juniorInboxItems).leftJoin(juniorQuestions, itemQuestion).where(and(openVisible(reader), like(juniorInboxItems.subjectKind, "%:%"), inArray(juniorInboxItems.subjectId, objects))).as("object_ranks");
5050
5178
  const linkRanks = db.select({
5051
5179
  ...candidateColumns,
5052
5180
  conversationId: juniorInboxItemConversations.conversationId,
5053
5181
  rank: newestInGroup(juniorInboxItemConversations.conversationId).as("link_rank")
5054
- }).from(juniorInboxItemConversations).innerJoin(juniorInboxItems, eq(juniorInboxItems.id, juniorInboxItemConversations.itemId)).where(and(inArray(juniorInboxItemConversations.conversationId, linkIds), openVisible(reader))).as("link_ranks");
5055
- const [bySubject, byLink, access] = await Promise.all([
5056
- subjectIds.length > 0 || subjectUrls.length > 0 ? db.select({
5057
- createdAt: subjectRanks.createdAt,
5058
- id: subjectRanks.id,
5059
- subjectId: subjectRanks.subjectId,
5060
- subjectUrl: subjectRanks.subjectUrl,
5061
- title: subjectRanks.title
5062
- }).from(subjectRanks).where(or(...subjectIds.length > 0 ? [and(inArray(subjectRanks.subjectId, subjectIds), lte(subjectRanks.idRank, RELATED_CANDIDATE_LIMIT))] : [], ...subjectUrls.length > 0 ? [and(inArray(subjectRanks.subjectUrl, subjectUrls), lte(subjectRanks.urlRank, RELATED_CANDIDATE_LIMIT))] : [])) : [],
5182
+ }).from(juniorInboxItemConversations).innerJoin(juniorInboxItems, eq(juniorInboxItems.id, juniorInboxItemConversations.itemId)).leftJoin(juniorQuestions, itemQuestion).where(and(inArray(juniorInboxItemConversations.conversationId, linkIds), openVisible(reader))).as("link_ranks");
5183
+ const [byObject, byLink, access] = await Promise.all([
5184
+ objects.length > 0 ? db.select({
5185
+ createdAt: objectRanks.createdAt,
5186
+ id: objectRanks.id,
5187
+ subjectId: objectRanks.subjectId,
5188
+ title: objectRanks.title
5189
+ }).from(objectRanks).where(lte(objectRanks.rank, RELATED_CANDIDATE_LIMIT)) : [],
5063
5190
  linkIds.length > 0 ? db.select({
5064
5191
  conversationId: linkRanks.conversationId,
5065
5192
  createdAt: linkRanks.createdAt,
5066
5193
  id: linkRanks.id,
5067
- subjectId: linkRanks.subjectId,
5068
- subjectUrl: linkRanks.subjectUrl,
5069
5194
  title: linkRanks.title
5070
5195
  }).from(linkRanks).where(lte(linkRanks.rank, RELATED_CANDIDATE_LIMIT)) : [],
5071
5196
  readConversationAccessFromSql(db, linkIds, viewer)
5072
5197
  ]);
5073
5198
  const related = /* @__PURE__ */ new Map();
5074
5199
  for (const item of open) {
5075
- const links = new Set(linkedWork(item));
5200
+ const about = new Set(relatedObjects(item));
5201
+ const work = new Set(linkedWork(item));
5076
5202
  const matches = /* @__PURE__ */ new Map();
5077
- for (const candidate of bySubject) if (item.subject?.id && candidate.subjectId === item.subject.id || item.subject?.url && candidate.subjectUrl === item.subject.url) matches.set(candidate.id, candidate);
5078
- for (const candidate of byLink) if (links.has(candidate.conversationId)) matches.set(candidate.id, candidate);
5203
+ for (const candidate of byObject) if (about.has(candidate.subjectId)) matches.set(candidate.id, candidate);
5204
+ for (const candidate of byLink) if (work.has(candidate.conversationId)) matches.set(candidate.id, candidate);
5079
5205
  matches.delete(item.id);
5080
5206
  related.set(item.id, {
5081
- conversationIds: [...links].filter((id) => access.get(id)?.canViewPrivateContent === true),
5207
+ conversationIds: linkedWork(item).filter((id) => access.get(id)?.canViewPrivateContent === true),
5082
5208
  items: [...matches.values()].sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime() || b.id.localeCompare(a.id)).slice(0, RELATED_ITEM_LIMIT).map(({ id, title }) => ({
5083
5209
  id,
5084
5210
  title
@@ -5156,20 +5282,46 @@ async function visibleRowItems(user, root, inboxItemId) {
5156
5282
  const item = await getInboxItem(getDb(), inboxItemId);
5157
5283
  const owner = item && ownerConversationId(item);
5158
5284
  const inRow = root === void 0 || (item ? await rootConversationIds([...item.conversationIds, ...owner ? [owner] : []]) : []).includes(root);
5159
- if (item?.status === "open" && inRow && await canUserReadInboxItem(item, user)) return [{
5160
- canAct: canActOnInboxItem(item, user.id),
5161
- id: item.id,
5162
- subjectUrl: item.subject?.url ?? null
5163
- }];
5285
+ if (item?.status === "open" && inRow && await canUserReadInboxItem(item, user)) {
5286
+ const links = await readSubjectLinks(getDb(), [item]);
5287
+ return [{
5288
+ canAct: canActOnInboxItem(item, user.id),
5289
+ id: item.id,
5290
+ subjectUrl: snoozeLink(item, links)
5291
+ }];
5292
+ }
5164
5293
  return [];
5165
5294
  }
5166
5295
  if (!root) return [];
5167
5296
  const reader = await inboxItemReaderForUserInConversation(user, root);
5168
- return getDb().select({
5297
+ const rows = await getDb().select({
5169
5298
  canAct: sql`${inboxItemForUser(user.id)}`,
5170
5299
  id: juniorInboxItems.id,
5171
- subjectUrl: juniorInboxItems.subjectUrl
5172
- }).from(juniorInboxItems).where(and(eq(juniorInboxItems.status, "open"), inboxItemVisibleTo(reader), inboxItemInRow(root)));
5300
+ request: inboxItemRequest,
5301
+ subjectId: juniorInboxItems.subjectId,
5302
+ subjectKind: juniorInboxItems.subjectKind
5303
+ }).from(juniorInboxItems).leftJoin(juniorQuestions, itemQuestion).where(and(eq(juniorInboxItems.status, "open"), inboxItemVisibleTo(reader), inboxItemInRow(root)));
5304
+ const items = rows.map((row) => ({
5305
+ request: row.request,
5306
+ subject: {
5307
+ id: row.subjectId,
5308
+ kind: row.subjectKind
5309
+ }
5310
+ }));
5311
+ const links = await readSubjectLinks(getDb(), items);
5312
+ return rows.map((row, index) => ({
5313
+ canAct: row.canAct,
5314
+ id: row.id,
5315
+ subjectUrl: snoozeLink(items[index], links)
5316
+ }));
5317
+ }
5318
+ /**
5319
+ * Return the link that a snooze of the item waits on by default. A
5320
+ * question's subject has no link, so it waits on what its first related
5321
+ * link names, such as a pull request. That does not decide its card.
5322
+ */
5323
+ function snoozeLink(item, links) {
5324
+ return links.get(subjectKey(item.subject)) ?? questionLinks(item)[0];
5173
5325
  }
5174
5326
  /**
5175
5327
  * Read the resource of each page that the triggers name. The viewer must
@@ -5341,7 +5493,7 @@ async function readInboxItemMentions(executor, items) {
5341
5493
  texts: [
5342
5494
  item.title,
5343
5495
  item.body,
5344
- item.request?.question
5496
+ inboxItemQuestion(item.request)?.question
5345
5497
  ]
5346
5498
  })));
5347
5499
  }
@@ -5393,11 +5545,21 @@ const ERROR_STATUS = {
5393
5545
  invalid: 400,
5394
5546
  not_found: 404
5395
5547
  };
5396
- function subjectPayload(subject) {
5397
- const objectType = subject.url && readLinkObjectType(subject.url);
5398
- const resource = subject.url && snoozeSubjectResource(getEventCatalog(), subject.url);
5548
+ function subjectPayload(item, views, viewer) {
5549
+ const { subject } = item;
5550
+ const view = views.get(subjectKey(subject));
5551
+ const url = view?.url;
5552
+ const object = view?.object;
5553
+ const label = subjectKindLabel(subject.kind, getPlugins(), object, viewer);
5554
+ const objectType = url && readLinkObjectType(url);
5555
+ const snoozeUrl = url ?? questionLinks(item)[0];
5556
+ const resource = snoozeUrl && snoozeSubjectResource(getEventCatalog(), snoozeUrl);
5399
5557
  return {
5400
- ...subject,
5558
+ id: subject.id,
5559
+ kind: subject.kind,
5560
+ ...label ? { label } : void 0,
5561
+ ...url ? { url } : void 0,
5562
+ ...object ? { object } : void 0,
5401
5563
  ...objectType ? { objectType } : void 0,
5402
5564
  ...resource ? { resource: {
5403
5565
  events: [...resource.events],
@@ -5418,10 +5580,11 @@ function wakePayload(reason) {
5418
5580
  };
5419
5581
  }
5420
5582
  /** Build the API payload of one Inbox item for its viewer. */
5421
- function inboxItemPayload(item, viewer, roots, mentions, related, wake) {
5583
+ function inboxItemPayload(item, viewer, roots, mentions, related, wake, views) {
5422
5584
  const conversationId = ownerConversationId(item);
5423
5585
  const root = conversationId ? roots.get(conversationId) : void 0;
5424
- const todo = inboxItemTodo(item);
5586
+ const todo = subjectTodo(item.subject);
5587
+ const question = inboxItemQuestion(item.request);
5425
5588
  return {
5426
5589
  ...root ? { addedByLabel: root.label } : void 0,
5427
5590
  assignedToEveryone: isInboxItemForEveryone(item),
@@ -5436,43 +5599,44 @@ function inboxItemPayload(item, viewer, roots, mentions, related, wake) {
5436
5599
  kind: item.kind,
5437
5600
  owner: item.owner,
5438
5601
  status: item.status,
5602
+ subject: subjectPayload(item, views, viewer),
5439
5603
  title: item.title,
5440
5604
  updatedAt: item.updatedAt.toISOString(),
5441
5605
  visibility: item.visibility,
5442
5606
  ...conversationId ? { rootConversationId: root?.rootConversationId ?? conversationId } : void 0,
5443
5607
  ...item.answer ? { answer: item.answer } : void 0,
5444
5608
  ...item.addedByTurnId ? { addedByTurnId: item.addedByTurnId } : void 0,
5445
- ...item.automationId ? { automationId: item.automationId } : void 0,
5609
+ ...item.addedByAutomationId ? { automationId: item.addedByAutomationId } : void 0,
5446
5610
  ...item.closeReason ? { closeReason: item.closeReason } : void 0,
5447
5611
  ...item.closedAt ? { closedAt: item.closedAt.toISOString() } : void 0,
5448
5612
  ...item.closedBy ? { closedBy: item.closedBy } : void 0,
5449
5613
  ...mentions.length > 0 ? { mentions: [...mentions] } : void 0,
5450
5614
  ...related && (related.items.length > 0 || related.conversationIds.length > 0) ? { related } : void 0,
5451
- ...item.dedupeKey.startsWith("reply:") ? { replyNotice: true } : void 0,
5452
- ...item.request ? { request: item.request } : void 0,
5453
- ...item.subject ? { subject: subjectPayload(item.subject) } : void 0,
5615
+ ...item.request && (question || item.request.related?.length) ? { request: question ?? item.request } : void 0,
5454
5616
  ...todo ? { todoId: todo.id } : void 0,
5455
5617
  ...wake ? { wake: wakePayload(wake) } : void 0
5456
5618
  };
5457
5619
  }
5458
5620
  /**
5459
5621
  * Build the payloads of a page of items, with the root of each one, the
5460
- * people they mention, and the related work and wake reason of the open
5461
- * ones. Each read covers the page, and the reads run at once.
5622
+ * people they mention, the card of each subject, and the related work and
5623
+ * wake reason of the open ones. Each read covers the page, and the reads
5624
+ * run at once.
5462
5625
  */
5463
5626
  async function inboxItemPayloads(items, viewer, reader) {
5464
5627
  const db = getDb();
5465
- const [roots, mentions, related, snoozes] = await Promise.all([
5628
+ const [roots, mentions, related, snoozes, views] = await Promise.all([
5466
5629
  readItemRoots(db, items, viewer),
5467
5630
  readInboxItemMentions(getSqlExecutor(), items),
5468
5631
  readRelatedReviewWork(db, reader, viewer, items),
5469
5632
  readViewerInboxSnoozes(db, {
5470
5633
  inboxItemIds: items.filter((item) => item.status === "open").map((item) => item.id),
5471
5634
  userId: viewer.id
5472
- })
5635
+ }),
5636
+ resolveInboxItemSubjects(viewer, items)
5473
5637
  ]);
5474
5638
  return items.map((item, index) => {
5475
- const payload = inboxItemPayload(item, viewer, roots, mentions[index], related.get(item.id), snoozes.wakeReasons.get(item.id));
5639
+ const payload = inboxItemPayload(item, viewer, roots, mentions[index], related.get(item.id), snoozes.wakeReasons.get(item.id), views);
5476
5640
  return snoozes.snoozed.has(item.id) ? {
5477
5641
  ...payload,
5478
5642
  snoozedByViewer: true
@@ -5552,6 +5716,10 @@ function createInboxItemRoutes(services) {
5552
5716
  const query = context.req.valid("query");
5553
5717
  const db = getDb();
5554
5718
  const [subjects, snoozed] = await Promise.all([countInboxItemsNeedingUserBySubject(db, viewer.id), query.include.includes("snoozed") ? countViewerSnoozes(viewer) : 0]);
5719
+ const links = await readSubjectLinks(db, subjects.map((subject) => ({ subject: {
5720
+ id: subject.subjectId,
5721
+ kind: subject.subjectKind
5722
+ } })));
5555
5723
  let automations = 0;
5556
5724
  const linkTypes = readObjectLinkTypes();
5557
5725
  let codeChanges = 0;
@@ -5563,7 +5731,12 @@ function createInboxItemRoutes(services) {
5563
5731
  needsViewer += subject.total;
5564
5732
  decisions += subject.decisions;
5565
5733
  todos += subject.todos;
5566
- if (subject.subjectUrl && readLinkObjectType(subject.subjectUrl, linkTypes) === "code_change") codeChanges += subject.total;
5734
+ const key = {
5735
+ id: subject.subjectId,
5736
+ kind: subject.subjectKind
5737
+ };
5738
+ const url = links.get(subjectKey(key));
5739
+ if (codeChangeSubjectProvider(key.kind) || url && readLinkObjectType(url, linkTypes) === "code_change") codeChanges += subject.total;
5567
5740
  }
5568
5741
  return jsonResponse(inboxItemCountSchema, {
5569
5742
  ...query.include.includes("automations") ? { automations } : void 0,
@@ -5774,128 +5947,7 @@ async function readStatsReport() {
5774
5947
  windowStart: start
5775
5948
  };
5776
5949
  }
5777
- // src/db/listen.ts
5778
- /**
5779
- * The session runs `SELECT 1` this often. A socket that drops with no close
5780
- * frame reports nothing, and a `NOTIFY` sent to a dead session is lost, so
5781
- * the ping is the only way to notice.
5782
- */
5783
- const PING_INTERVAL_MS = 15e3;
5784
- const PING_TIMEOUT_MS = 5e3;
5785
- /**
5786
- * Open a session on the direct endpoint of `databaseUrl` and `LISTEN` on
5787
- * `channel`. The pooled endpoint cannot hold a `LISTEN`, because it shares
5788
- * one server session between clients.
5789
- *
5790
- * `onNotify` runs for each notification. `onLost` runs at most once, when
5791
- * the session fails, ends, or misses a ping. The caller then opens a new
5792
- * session: a `NOTIFY` sent while no session listens is lost.
5793
- */
5794
- async function openListenSession(args) {
5795
- const config = { connectionString: readDirectDatabaseUrl(args.databaseUrl) };
5796
- const client = args.driver === "postgres" ? new pg.Client(config) : new Client(config);
5797
- let connected = false;
5798
- let ended = false;
5799
- let ping;
5800
- const end = async () => {
5801
- ended = true;
5802
- clearInterval(ping);
5803
- await client.end().catch(() => void 0);
5804
- };
5805
- const lose = (error) => {
5806
- if (ended) return;
5807
- end();
5808
- if (connected) args.onLost(error);
5809
- };
5810
- client.on("error", lose);
5811
- try {
5812
- await client.connect();
5813
- await client.query(`SET application_name = '${args.applicationName}'`);
5814
- await client.query(`LISTEN "${args.channel}"`);
5815
- connected = true;
5816
- } catch (error) {
5817
- await end();
5818
- throw error;
5819
- }
5820
- client.on("notification", () => {
5821
- if (!ended) args.onNotify();
5822
- });
5823
- client.on("end", () => lose(/* @__PURE__ */ new Error("LISTEN session ended")));
5824
- ping = setInterval(() => {
5825
- let timer;
5826
- const timeout = new Promise((_, reject) => {
5827
- timer = setTimeout(() => reject(/* @__PURE__ */ new Error("LISTEN session missed a ping")), PING_TIMEOUT_MS);
5828
- });
5829
- Promise.race([client.query("SELECT 1"), timeout]).catch((error) => lose(error instanceof Error ? error : new Error(String(error)))).finally(() => clearTimeout(timer));
5830
- }, PING_INTERVAL_MS);
5831
- ping.unref?.();
5832
- return { close: end };
5833
- }
5834
- // src/api/versions/changes.ts
5835
- /**
5836
- * The channel that the `junior_notify_versions` triggers send to. They send
5837
- * an empty payload, so Postgres folds the notifications of one transaction
5838
- * into one.
5839
- */
5840
- const VERSIONS_CHANNEL = "junior_versions";
5841
- /** Lets an operator find this instance's session in `pg_stat_activity`. */
5842
- const APPLICATION_NAME = "junior-versions-listen";
5843
- /**
5844
- * Share one direct Postgres `LISTEN` session among the versions streams of
5845
- * one API instance. The session opens with the first stream and closes with
5846
- * the last one.
5847
- */
5848
- function createVersionChanges() {
5849
- const subscribers = /* @__PURE__ */ new Set();
5850
- let session;
5851
- const lose = (lost, error) => {
5852
- if (session !== lost) return;
5853
- session = void 0;
5854
- logWarn("versions_stream.listener_lost", {
5855
- "error.type": error.name,
5856
- "exception.message": error.message,
5857
- "app.versions_stream.subscribers": subscribers.size
5858
- });
5859
- const ended = [...subscribers];
5860
- subscribers.clear();
5861
- for (const subscriber of ended) subscriber.onLost();
5862
- };
5863
- const connect = () => {
5864
- const { sql } = getChatConfig();
5865
- const opened = openListenSession({
5866
- applicationName: APPLICATION_NAME,
5867
- channel: VERSIONS_CHANNEL,
5868
- databaseUrl: sql.databaseUrl,
5869
- driver: sql.driver,
5870
- onLost: (error) => lose(opened, error),
5871
- onNotify: () => {
5872
- for (const subscriber of subscribers) subscriber.onChange();
5873
- }
5874
- });
5875
- opened.catch(() => {
5876
- if (session === opened) session = void 0;
5877
- });
5878
- return opened;
5879
- };
5880
- return { async subscribe(subscriber) {
5881
- session ??= connect();
5882
- const current = session;
5883
- subscribers.add(subscriber);
5884
- try {
5885
- await current;
5886
- } catch (error) {
5887
- subscribers.delete(subscriber);
5888
- throw error;
5889
- }
5890
- return () => {
5891
- if (!subscribers.delete(subscriber)) return;
5892
- if (subscribers.size > 0 || session !== current) return;
5893
- session = void 0;
5894
- current.then((listen) => listen.close());
5895
- };
5896
- } };
5897
- }
5898
- // src/api/versions/read.ts
5950
+ // src/api/versions.ts
5899
5951
  /**
5900
5952
  * Build a JSON object of each Conversation's tree token by id, with no entry
5901
5953
  * for a missing one. The tokens come from one grouped pass over all the ids.
@@ -5923,152 +5975,6 @@ async function readVersions(viewer, options) {
5923
5975
  if (!row) throw new Error("Viewer user row is missing");
5924
5976
  return row;
5925
5977
  }
5926
- // src/api/versions/stream.ts
5927
- /**
5928
- * A stream ends by itself after about this long. Vercel does not tell the
5929
- * function when the client goes away, and a write to a closed client does
5930
- * not fail, so the cap is what ends a stream that nobody reads. The client
5931
- * reconnects and reads a fresh baseline. The cap also bounds how long a
5932
- * revoked session keeps getting tokens.
5933
- */
5934
- const STREAM_MAX_MS = 12e4;
5935
- /** Ends spread out, so tabs that opened together do not reconnect together. */
5936
- const STREAM_MAX_JITTER_MS = 2e4;
5937
- /** The stream ends this long before the function's max duration. */
5938
- const FUNCTION_DEADLINE_MARGIN_MS = 15e3;
5939
- /** The client counts a stream as healthy while it hears from it this often. */
5940
- const KEEPALIVE_MS = 15e3;
5941
- /**
5942
- * After a read, the next one waits at least this long, the same as the poll
5943
- * of a present reader. A busy viewer then costs no more than the poll.
5944
- */
5945
- const MIN_READ_GAP_MS = 5e3;
5946
- /** The client waits this long, plus jitter, before it reconnects. */
5947
- const RETRY_MS = 1e3;
5948
- const RETRY_JITTER_MS = 2e3;
5949
- function streamMaxMs() {
5950
- const functionMaxMs = getChatConfig().functionMaxDurationSeconds * 1e3 - FUNCTION_DEADLINE_MARGIN_MS;
5951
- return Math.min(STREAM_MAX_MS - STREAM_MAX_JITTER_MS / 2 + Math.random() * STREAM_MAX_JITTER_MS, functionMaxMs);
5952
- }
5953
- /**
5954
- * Open an SSE stream of one viewer's `Versions`. The first message is the
5955
- * baseline. After that, a message comes only when a write may have moved a
5956
- * token and a fresh read differs from the last message. Each message is a
5957
- * fresh `readVersions`, with the same access as the poll.
5958
- */
5959
- async function openVersionsStream(args) {
5960
- const encoder = new TextEncoder();
5961
- let controller;
5962
- const body = new ReadableStream({
5963
- start(streamController) {
5964
- controller = streamController;
5965
- },
5966
- cancel() {
5967
- close();
5968
- }
5969
- });
5970
- let closed = false;
5971
- let unsubscribe;
5972
- let keepAlive;
5973
- let cap;
5974
- let nextRead;
5975
- let reading = false;
5976
- let dirty = false;
5977
- let lastReadAtMs = 0;
5978
- let lastMessage;
5979
- function close() {
5980
- if (closed) return;
5981
- closed = true;
5982
- clearInterval(keepAlive);
5983
- clearTimeout(cap);
5984
- clearTimeout(nextRead);
5985
- unsubscribe?.();
5986
- try {
5987
- controller.close();
5988
- } catch {}
5989
- }
5990
- const write = (chunk) => {
5991
- if (closed) return;
5992
- try {
5993
- controller.enqueue(encoder.encode(chunk));
5994
- } catch {
5995
- close();
5996
- }
5997
- };
5998
- const read = async () => {
5999
- reading = true;
6000
- dirty = false;
6001
- lastReadAtMs = Date.now();
6002
- try {
6003
- const message = JSON.stringify(await readVersions(args.viewer, { conversationIds: args.conversationIds }));
6004
- if (message !== lastMessage) {
6005
- lastMessage = message;
6006
- write(`data: ${message}\n\n`);
6007
- }
6008
- } catch (error) {
6009
- logException(error, "versions_stream.read_failed");
6010
- close();
6011
- return;
6012
- } finally {
6013
- reading = false;
6014
- }
6015
- if (dirty) scheduleRead();
6016
- };
6017
- function scheduleRead() {
6018
- if (closed || reading || nextRead) return;
6019
- nextRead = setTimeout(() => {
6020
- nextRead = void 0;
6021
- read();
6022
- }, Math.max(0, lastReadAtMs + MIN_READ_GAP_MS - Date.now()));
6023
- }
6024
- try {
6025
- unsubscribe = await args.changes.subscribe({
6026
- onChange: () => {
6027
- dirty = true;
6028
- scheduleRead();
6029
- },
6030
- onLost: close
6031
- });
6032
- } catch (error) {
6033
- close();
6034
- throw error;
6035
- }
6036
- write(`retry: ${Math.round(RETRY_MS + Math.random() * RETRY_JITTER_MS)}\n\n`);
6037
- keepAlive = setInterval(() => write(`event: ${VERSIONS_STREAM_KEEPALIVE_EVENT}\ndata: 1\n\n`), KEEPALIVE_MS);
6038
- keepAlive.unref?.();
6039
- cap = setTimeout(close, streamMaxMs());
6040
- cap.unref?.();
6041
- read();
6042
- return new Response(body, { headers: {
6043
- "cache-control": "private, no-store, no-transform",
6044
- "content-type": "text/event-stream"
6045
- } });
6046
- }
6047
- // src/api/versions/routes.ts
6048
- /**
6049
- * Create the routes of the dashboard change tokens: one poll, and one SSE
6050
- * stream that pushes the same tokens. The streams of this API share one
6051
- * Postgres `LISTEN` session.
6052
- */
6053
- function createVersionsRoutes() {
6054
- const app = new Hono();
6055
- const changes = createVersionChanges();
6056
- const query = validateRequest("query", versionsQuerySchema, "Invalid query parameters.");
6057
- app.get("/", requireViewer, query, async (context) => {
6058
- const headers = { "cache-control": "private, no-store" };
6059
- if (getChatConfig().versionsStreamEnabled) headers[VERSIONS_STREAM_HEADER] = "1";
6060
- return jsonResponse(versionsSchema, await readVersions(context.get("viewer"), context.req.valid("query")), { headers });
6061
- });
6062
- app.get("/stream", requireViewer, query, async (context) => {
6063
- if (!getChatConfig().versionsStreamEnabled) return emptyResponse();
6064
- return await openVersionsStream({
6065
- changes,
6066
- conversationIds: context.req.valid("query").conversationIds,
6067
- viewer: context.get("viewer")
6068
- });
6069
- });
6070
- return app;
6071
- }
6072
5978
  // src/reporting.ts
6073
5979
  function readDescriptionText(home) {
6074
5980
  try {
@@ -6079,7 +5985,7 @@ function readDescriptionText(home) {
6079
5985
  }
6080
5986
  /** Read discovered skills for runtime diagnostics and the Automation editor. */
6081
5987
  async function readSkillReports() {
6082
- const { discoverSkills } = await import("./skills-BlHUDj7k.js").then((n) => n.s);
5988
+ const { discoverSkills } = await import("./skills-BCEU41zM.js").then((n) => n.s);
6083
5989
  const skills = await discoverSkills();
6084
5990
  return skillReportsSchema.parse(skills.map((skill) => ({
6085
5991
  name: skill.name,
@@ -6093,7 +5999,7 @@ async function readSkillReports() {
6093
5999
  * what the skill tells Junior. Returns null when no skill has that name.
6094
6000
  */
6095
6001
  async function readSkillDetailReport(name) {
6096
- const { discoverSkills, findSkillByName, parseSkillFile } = await import("./skills-BlHUDj7k.js").then((n) => n.s);
6002
+ const { discoverSkills, findSkillByName, parseSkillFile } = await import("./skills-BCEU41zM.js").then((n) => n.s);
6097
6003
  const skill = findSkillByName(name, await discoverSkills());
6098
6004
  if (!skill) return null;
6099
6005
  const parsed = parseSkillFile(await fs.readFile(path.join(skill.skillPath, "SKILL.md"), "utf8"), skill.name);
@@ -6108,7 +6014,7 @@ async function readSkillDetailReport(name) {
6108
6014
  }
6109
6015
  /** Read safe configured plugin metadata for authenticated runtime diagnostics. */
6110
6016
  async function readPlugins() {
6111
- const { pluginCatalogRuntime } = await import("./db-DXTOYRzR.js").then((n) => n.kr);
6017
+ const { pluginCatalogRuntime } = await import("./catalog-runtime-DfSpJZdY.js").then((n) => n.t);
6112
6018
  return pluginsSchema.parse(pluginCatalogRuntime.getProviders().map((plugin) => ({
6113
6019
  configKeys: plugin.manifest.configKeys ?? [],
6114
6020
  description: plugin.manifest.description,
@@ -6119,8 +6025,8 @@ async function readPlugins() {
6119
6025
  /** Read authenticated runtime discovery data. */
6120
6026
  async function readRuntimeInfoReport() {
6121
6027
  const [{ homeDir }, { pluginCatalogRuntime }, plugins, skills] = await Promise.all([
6122
- import("./package-discovery-BI6T_RkD.js").then((n) => n.r),
6123
- import("./db-DXTOYRzR.js").then((n) => n.kr),
6028
+ import("./package-discovery-DD9vencX.js").then((n) => n.r),
6029
+ import("./catalog-runtime-DfSpJZdY.js").then((n) => n.t),
6124
6030
  readPlugins(),
6125
6031
  readSkillReports()
6126
6032
  ]);
@@ -6137,7 +6043,7 @@ async function readRuntimeInfoReport() {
6137
6043
  /** Read sanitized operational summaries contributed by plugins. */
6138
6044
  async function readPluginOperationalReportFeed() {
6139
6045
  const nowMs = Date.now();
6140
- const { getPluginOperationalReports } = await import("./db-DXTOYRzR.js").then((n) => n.W);
6046
+ const { getPluginOperationalReports } = await import("./reports-WKHfGTsU.js");
6141
6047
  return pluginOperationalReportFeedSchema.parse({
6142
6048
  source: "plugins",
6143
6049
  generatedAt: new Date(nowMs).toISOString(),
@@ -6159,7 +6065,7 @@ function createJuniorApi(options = {}) {
6159
6065
  });
6160
6066
  app.get("/api/plugin-reports", async () => jsonResponse(pluginOperationalReportFeedSchema, await readPluginOperationalReportFeed()));
6161
6067
  app.get("/api/stats", async () => jsonResponse(statsReportSchema, await readStatsReport()));
6162
- app.route("/api/versions", createVersionsRoutes());
6068
+ app.get("/api/versions", requireViewer, validateRequest("query", versionsQuerySchema, "Invalid query parameters."), async (context) => jsonResponse(versionsSchema, await readVersions(context.get("viewer"), context.req.valid("query")), { headers: { "cache-control": "private, no-store" } }));
6163
6069
  for (const path of REVALIDATED_READ_PATHS) app.use(path, revalidateContent);
6164
6070
  const queue = options.conversationWorkQueue ?? getVercelConversationWorkQueue();
6165
6071
  const waitUntil$1 = options.waitUntil ?? ((task) => waitUntil(typeof task === "function" ? task() : task));
@@ -6187,9 +6093,7 @@ function createJuniorApi(options = {}) {
6187
6093
  app.route("/api/search", createSearchRoutes());
6188
6094
  app.route("/api/spaces", createSpaceRoutes());
6189
6095
  app.route("/api/spaces", createSpaceArchiveRoutes({ queue }));
6190
- app.route("/api/spaces", createSpaceMemberRoutes());
6191
6096
  app.route("/api/spaces", createSpaceConfigurationRoutes());
6192
- app.route("/api/spaces", createSpaceLeadRoutes());
6193
6097
  app.route("/api/user-pages", createUserPageRoutes());
6194
6098
  app.route("/api/user-customization", createUserCustomizationRoutes());
6195
6099
  app.route("/api/automations", createAutomationRoutes());