@sentry/junior 0.308.0 → 0.309.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 (84) hide show
  1. package/dist/{actor-D2iXzvlN.js → actor-BsBdxDXQ.js} +0 -1
  2. package/dist/{adapter-context-BO432242.js → adapter-context-1YUbMpD3.js} +2 -2
  3. package/dist/{admin-vSmheo3Z.js → admin-u30A8TcD.js} +2 -2
  4. package/dist/{agent-runner-BnOofGFG.js → agent-runner-sJLhgPQV.js} +93 -90
  5. package/dist/api/schema.d.ts +1 -1
  6. package/dist/api/schema.js +4 -4
  7. package/dist/api.d.ts +4 -2
  8. package/dist/api.js +416 -272
  9. package/dist/{app-CqYqy541.d.ts → app-B_7Wn0en.d.ts} +4 -6
  10. package/dist/app.d.ts +1 -1
  11. package/dist/app.js +73 -193
  12. package/dist/{background-compaction-queue-BpmDEQf6.js → background-compaction-queue-CUJXVKG3.js} +4 -4
  13. package/dist/{briefs-Dbh94cRp.js → briefs-BHi70IR5.js} +3 -3
  14. package/dist/{catalog-runtime-q9AJjuUN.js → catalog-runtime-Chc_IP2o.js} +1 -1
  15. package/dist/cli/chat.js +16 -16
  16. package/dist/cli/check.js +10 -10
  17. package/dist/cli/main.js +3 -3
  18. package/dist/cli/plugins.js +4 -4
  19. package/dist/cli/snapshot-create.js +5 -5
  20. package/dist/cli/upgrade.d.ts +1 -1
  21. package/dist/cli/upgrade.js +3 -3
  22. package/dist/{config-Cx8H0MRw.js → config-BIyIdTtA.js} +51 -92
  23. package/dist/{continue-in-slack-CtTv1tkn.js → continue-in-slack-BQJBfiQh.js} +6 -6
  24. package/dist/{conversation--f85g4zL.js → conversation-CzrLhdHG.js} +6 -1
  25. package/dist/{conversation-feed-BNs9KiqC.js → conversation-feed-B9e3_gxz.js} +1 -1
  26. package/dist/{conversation-privacy-CivmFlWP.js → conversation-privacy-CkTW29hd.js} +1 -1
  27. package/dist/{conversation-turn-C9-Nfnsy.js → conversation-turn-CZaYQUum.js} +19 -20
  28. package/dist/{credential-sync-CWIORwD9.js → credential-sync-58m_CyIJ.js} +31 -23
  29. package/dist/{db-C41UgdBj.d.ts → db-B4Hjxr-u.d.ts} +2 -2
  30. package/dist/{db-CO6Y10eM.js → db-CFUpEZi9.js} +11 -9
  31. package/dist/{executor-Doo-N6Yn.js → executor-DXL0O0MV.js} +4 -3
  32. package/dist/fan-out-Cod-yEHG.js +10 -0
  33. package/dist/{connections-DUylBPiR.js → html-CaBu2VbT.js} +146 -11
  34. package/dist/{install-Y2s9ZPvk.js → install-DhTBUUov.js} +2 -2
  35. package/dist/instrumentation.js +2 -2
  36. package/dist/{lineage-BcqyhMyp.js → lineage-CxtOI2_p.js} +2 -2
  37. package/dist/{logging-DnBYBM8z.js → logging-BNUovdcX.js} +1 -1
  38. package/dist/{message-fSnXIqvl.js → message-DcUsS2vg.js} +8 -8
  39. package/dist/{model-input-DRChpXJ7.js → model-input-o3rEqgwM.js} +15 -10
  40. package/dist/nitro.d.ts +1 -1
  41. package/dist/nitro.js +4 -4
  42. package/dist/{oauth-callback-server-BUU6zd_T.js → oauth-callback-server-1Fizd1EM.js} +2 -2
  43. package/dist/{oauth-relay-gO_Ynmpb.js → oauth-relay-DOwngqdM.js} +1 -1
  44. package/dist/{package-discovery-x4AvVhMj.js → package-discovery-DD9vencX.js} +0 -1
  45. package/dist/{projection-Bqn6zdVT.js → projection-Ce4pmhKP.js} +98 -122
  46. package/dist/{prompt-DAjjk5fm.js → prompt-DEqjDVMs.js} +25 -14
  47. package/dist/{registry-tHJLCtKS.js → registry-CNE4ZBnG.js} +3 -3
  48. package/dist/{resolve-z2sKt8xM.js → resolve-qbPg-aC-.js} +3 -3
  49. package/dist/{result-D2wshngt.js → result-ZGnDzcsb.js} +12 -13
  50. package/dist/{runner-BvNPWLAy.js → runner-eGIxpAMf.js} +10 -10
  51. package/dist/{sandbox-egress-signals-CmHD-6vr.js → sandbox-egress-signals-DMFB1kCp.js} +1 -1
  52. package/dist/{schedule-BG1tEbRF.js → schedule-Cire6NU7.js} +1 -1
  53. package/dist/{schema-D4jdesIu.js → schema-CfIey9Ao.js} +65 -28
  54. package/dist/{schema-CRXcj4fj.d.ts → schema-DriSvB40.d.ts} +43 -43
  55. package/dist/{service-account-B2d1Er_r.js → service-account-B1VXCTqg.js} +3 -3
  56. package/dist/{service-account-CddxU-yC.js → service-account-Cw_LWZ4-.js} +7 -8
  57. package/dist/{session-stop-BQ0J0Fph.js → session-stop-P2XdTiwr.js} +159 -182
  58. package/dist/{skills-Dm2-5nn5.js → skills-Zg8-vrje.js} +25 -29
  59. package/dist/{slack-conversation-unfurl-CLH0tTLk.js → slack-conversation-unfurl-DA51qH0c.js} +18 -15
  60. package/dist/{spawn-PwAuSN59.js → spawn-DBi4-zD8.js} +6 -6
  61. package/dist/{state-rXH58smZ.js → state-C-Ftk23K.js} +4 -4
  62. package/dist/{stop-CcHPEcFE.js → stop-D9xideLM.js} +175 -134
  63. package/dist/{store-7QA00oK6.js → store-BjIXA0Al.js} +5 -5
  64. package/dist/{task-queue-DvQZH5rG.js → task-queue-D0_qbnpo.js} +7 -4
  65. package/dist/{task-runner-CyZMcuZy.js → task-runner-DQMq4XY0.js} +10 -11
  66. package/dist/{thread-context-C-hLTQST.js → thread-context-D0i1e-5O.js} +13 -11
  67. package/dist/{turn-session-routing-Cqjj1B3i.js → turn-session-routing-C0l68I_O.js} +4 -4
  68. package/dist/{turn-user-message-DbU7MNd9.js → turn-user-message-nBVvOXjs.js} +14 -5
  69. package/dist/{queue-CbEHUO0l.d.ts → types-fnU7Xs__.d.ts} +3 -1
  70. package/dist/{users-B-UpCmw9.js → users-DdjMjbmM.js} +1 -1
  71. package/dist/{validation-BEUlev32.js → validation-CRbvRPvu.js} +1 -1
  72. package/dist/{version-BE1OyrXV.js → version-BYdVs12p.js} +1 -1
  73. package/dist/version.js +1 -1
  74. package/dist/{viewer-CqOkWizK.js → viewer-DudYrQGj.js} +7 -5
  75. package/dist/{warmup-HFgFZFwS.js → warmup-DN9OHN1-.js} +136 -78
  76. package/dist/{worker-CCEDWbsY.js → worker-C9ZfJXmV.js} +8 -8
  77. package/migrations/0121_people_list_metric_index.sql +1 -0
  78. package/migrations/0122_automation_rollout_repair.sql +56 -0
  79. package/migrations/0123_cache_warming_history_reset.sql +10 -0
  80. package/migrations/meta/0121_snapshot.json +5481 -0
  81. package/migrations/meta/0122_snapshot.json +5481 -0
  82. package/migrations/meta/0123_snapshot.json +5481 -0
  83. package/migrations/meta/_journal.json +21 -0
  84. package/package.json +7 -7
package/dist/api.js CHANGED
@@ -1,40 +1,42 @@
1
- import { V as escapeXml, n as botConfig, ut as getAttachmentStorage } from "./config-Cx8H0MRw.js";
2
- import { $ as getStateAdapter, A as conversationKindFromRow, C as withConversationMutationLock, X as createCache, a as getConversationStore, dt as microUsdToUsd, ht as conversationUsageCostExpr, mt as conversationRangeColumns, o as getDb, pt as conversationAggregateColumns, s as getSqlExecutor, ut as microUsdSql, wt as nextDetailVersion, y as loadConversationSlackTenantIds } from "./db-CO6Y10eM.js";
3
- import { Dt as AttachmentUploadError, Ft as listOwnedWatches, Gn as emptyResponse, It as listChildAgents, Kn as jsonResponse, Oi as countOwnedAutomationsNeedingAttention, Tt as webActorFromUser, Wn as setConversationSubscription, _ as closeBreaker, ai as deleteViewerTask, ci as ViewerTaskNotFoundError, di as readViewerAutomationRuns, fi as readViewerAutomationSummary, ft as reportConversationRead, g as breakerStates, h as savingsTotals, ii as changeViewerAutomationLifecycle, jt as writeAttachmentUpload, kt as createAttachmentUpload, lt as archiveConversation, mi as readViewerAutomations, oi as readViewerAutomationEdit, pi as readViewerAutomationVersions, qn as throwApiError, si as updateViewerAutomation, ti as activateViewerAutomationVersion, u as SAVINGS_NAMESPACE, ui as readViewerAutomationExecutions, v as connectedState, w as readStats, xi as AutomationEditError, yt as acceptsWebMessages } from "./warmup-HFgFZFwS.js";
4
- import { C as createConversationMessageBodySchema, H as renameConversationResponseSchema, S as createConversationBodySchema, T as forkConversationResponseSchema, U as conversationReadPositionSchema, V as renameConversationBodySchema, Z as MAX_ATTACHMENT_BYTES, f as conversationEventPageSchema, l as conversationDetailQuerySchema, m as conversationParamsSchema, n as CONVERSATION_VERSION_HEADER, o as conversationAttachmentParamsSchema, p as conversationEventsQuerySchema, r as acceptedConversationMessageSchema, s as conversationAttachmentQuerySchema, t as CONVERSATION_DETAIL_VERSION_HEADER, u as conversationDetailReportSchema, w as forkConversationBodySchema } from "./conversation--f85g4zL.js";
5
- import { $ as testNotificationResponseSchema, A as startServiceAccountSignInResponseSchema, At as objectLinksReportSchema, B as personParamsSchema, Bt as conversationSubscriptionResponseSchema, C as cacheWarmingSavingsRefillResponseSchema, Ct as conversationChildAgentsReportSchema, D as serviceAccountListSchema, Dt as attachObjectLinkBodySchema, E as disconnectServiceAccountResponseSchema, F as personalTokenParamsSchema, Ft as archiveConversationBodySchema, G as locationParamsSchema, Gt as reorderPinnedConversationsBodySchema, Ht as conversationDeliveryResponseSchema, I as revokePersonalTokenResponseSchema, It as archiveConversationResponseSchema, J as activitySixHours$1, Jt as conversationCatchUpSchema, K as activityDays$1, Kt as reorderPinnedConversationsResponseSchema, L as actorDirectoryReportSchema, Lt as archiveDoneConversationsResponseSchema, M as createdPersonalTokenSchema, Mt as conversationStatsReportSchema, N as personalTokenListSchema, O as serviceAccountParamsSchema, Ot as attachObjectLinkResponseSchema, Pt as conversationOutlineSchema, Q as pushSubscriptionDeleteBodySchema, R as actorProfileReportSchema, Rt as conversationAutoArchiveSchema, S as cacheWarmingSavingsQuerySchema, T as closeCacheWarmingBreakerResponseSchema, Tt as continueConversationInSlackResponseSchema, U as locationDetailReportSchema, Ut as pinConversationBodySchema, V as personalSpendReportSchema, Vt as conversationDeliveryBodySchema, W as locationDirectoryReportSchema, Wt as pinConversationResponseSchema, X as notificationSettingsSchema, Xt as attachmentUploadSchema, Yt as attachmentUploadParamsSchema, Z as pushSubscriptionBodySchema, Zt as createAttachmentUploadBodySchema, _ as reviewItemParamsSchema, _t as conversationPlanReportSchema, b as cacheWarmingBreakerListSchema, c as workspaceListSchema, d as workspaceSchema, dt as codeRepositoryParamsSchema, et as connectionListSchema, f as reviewItemActionSchema, ft as codeRepositoryQuerySchema, g as reviewItemListSchema, gt as conversationPlanItemSchema, h as reviewItemListQuerySchema, ht as personCodeQuerySchema, i as statsReportSchema, it as startConnectionResponseSchema, j as createPersonalTokenBodySchema, jt as stopConversationTurnResponseSchema, kt as objectLinksQuerySchema, l as workspaceParamsSchema, lt as codeOverviewReportSchema, m as reviewItemCountSchema, n as versionsSchema, o as deleteWorkspaceResponseSchema, p as reviewItemCountQuerySchema, pt as codeRepositoryReportSchema, q as activityHours$1, qt as conversationCatchUpBodySchema, rt as disconnectConnectionResponseSchema, s as workspaceBodySchema, t as versionsQuerySchema, tt as connectionParamsSchema, ut as codePersonReportSchema, v as reviewItemSchema, vt as planItemParamsSchema, w as cacheWarmingSavingsReportSchema, wt as continueConversationInSlackBodySchema, x as cacheWarmingBreakerParamsSchema, xt as conversationWatchesReportSchema, y as reviewItemWaitingConversationsSchema, yt as planItemStatusBodySchema, z as avatarParamsSchema, zt as conversationSubscriptionBodySchema } from "./schema-D4jdesIu.js";
6
- import { S as skillDetailReportSchema, a as cancelConversationPendingMessagesResponseSchema, b as pluginsSchema, d as conversationUnchangedDetailWithMailboxSchema, f as steerConversationPendingMessagesBodySchema, h as pluginOperationalReportFeedSchema, i as cancelConversationPendingMessagesBodySchema, m as healthReportSchema, n as conversationFeedQuerySchema, o as conversationDetailWithMailboxReportSchema, p as steerConversationPendingMessagesResponseSchema, r as conversationFeedSchema, u as conversationPendingMessagesReportSchema, w as skillReportsSchema, x as runtimeInfoReportSchema } from "./conversation-feed-BNs9KiqC.js";
7
- import { G as isAllowedDomain, H as addConversationNote, S as setPlanItemStatusByUser, _ as readUserCustomization, ft as isExperimentalFeatureEnabled, mt as getEventCatalog, q as parseEmail, v as saveUserCustomization, x as listPlanItems } from "./session-stop-BQ0J0Fph.js";
8
- import { $r as reviewItemReaderForUser, Ar as countOpenReviewItemsForUser, Bi as updateWorkspace, Cr as saveNotificationSchedule, Ea as workspaceRepoCheckoutPath, Fi as deleteWorkspace, Ii as getWorkspace, Is as escapeSlackMrkdwnText, Jr as itemNeedsUser, Ka as createConversationAccessReader, Ki as create, Lr as listWaitingConversations, Ls as formatSlackLink, Nn as getPlugins, No as createPluginAnnotations, Pi as createWorkspace, Po as listConversationAnnotations, Ri as listWorkspaces, Rr as reviewItemsNeedingUserVersionQuery, Sr as readNotificationSchedule, Tc as automationEventCatalog, Tr as isPausedBySlack, Ua as createPluginLogger, Uc as AutomationConflictError, Ur as canActOnReviewItem, Vi as WorkspaceValidationError, _r as readWebPushConfig, bn as createUserTokenStore, bo as readLiveAttachment, br as deletePushSubscription, dl as createPluginCache, ei as reviewItemReaderForUserInConversation, fs as postSlackMessage, ho as readSlackAttachmentSource, jr as countReviewItemsNeedingUserBySubject, oc as getDashboardSettingsLink, qa as readConversationAccessFromSql, qi as hash, qr as isOnlyAssignee, rl as readAutomationTitlesByConversationId, ro as readConversationEventPage, tc as getDashboardConversationLink, to as readConversationBriefThrough, vr as sendPushNotificationToUser, wa as SANDBOX_RUNTIME, wr as savePushSubscription, xr as listPushSubscriptions, yr as resolveNotificationTimezone, z as createPluginEgress, zi as listWorkspacesByRepository, zr as searchReviewItems } from "./projection-Bqn6zdVT.js";
9
- import { A as actOnReviewItem, B as readSavingsRefill, Ct as decodeImageId, D as resolveMentions, E as requireConversationPendingMessages, G as readHealthReport, H as startSavingsRefill, I as setConversationAutoArchive, J as readObjectLinkTypes, K as OBJECT_LINK_TTL_MS, L as DEFAULT_USER_SETTINGS, M as readReviewItemForUser, P as archiveViewerDoneConversations, R as readUserSettings, St as IMAGE_WIDTHS, X as resolveObjectLinks, Y as resolveObjectLinkNow, Z as guardedFetch, _ as readConversationEvents, a as decodePageCursor, b as createConversationForViewer, bt as readFirstHumanMessageTexts, c as reorderPinnedConversations, d as childAgentTotalsReport, f as readConversationTreeMetricsFromSql, g as keepQuickQuestionForViewer, h as forkConversationForViewer, i as readConversationFeed, k as ReviewItemActionError, l as readConversationDetail, m as readConversationDetailEtag, n as steerConversationPendingMessagesForViewer, nt as getProductionSlackAdapter, o as encodePageCursor, p as conversationVersionQuery, q as readLinkObjectType, r as conversationFeedVersionQuery, s as pinConversation, t as stopConversationTurnForViewer, u as readConversationAuxiliaryCostsFromSql, w as cancelConversationPendingMessagesForViewer, x as requireWebMessageConversation, xt as createViewerMcp, y as appendConversationMessageForViewer, yt as conversationSummaryFromStoredConversation, z as updateUserSettings } from "./stop-CcHPEcFE.js";
10
- import { d as completeText, n as briefEntriesFromReportEvents } from "./prompt-DAjjk5fm.js";
11
- import { A as resumeConversationDelivery, D as canPauseConversationDelivery, M as readAttachmentContent, N as previewOriginBelongsTo, _ as createSlackReviewItemShow, j as AttachmentDownloadError, k as pauseConversationDelivery } from "./agent-runner-BnOofGFG.js";
12
- import { _ as runBestEffort, h as logWarn, m as logInfo, p as logException } from "./logging-DnBYBM8z.js";
13
- import { t as runWithSlackInstallation } from "./adapter-context-BO432242.js";
14
- import { A as juniorConversationEvents, B as juniorUsers, E as juniorConversationBriefs, N as juniorCodeChanges, O as juniorConversationMetrics, P as juniorCodeRepositories, R as juniorConversations, V as juniorDestinations, j as juniorApiTokens, z as juniorIdentities } from "./executor-Doo-N6Yn.js";
15
- import { i as continueConversationInSlack, r as canContinueInSlack, t as BUSY } from "./continue-in-slack-CtTv1tkn.js";
16
- import { f as parseSlackTeamId, u as parseSlackChannelId } from "./actor-D2iXzvlN.js";
1
+ import { n as botConfig, ot as getAttachmentStorage } from "./config-BIyIdTtA.js";
2
+ import { A as conversationKindFromRow, C as withConversationMutationLock, Tt as nextDetailVersion, X as cacheKeyPrefix, Z as createCache, a as getConversationStore, dt as microUsdSql, et as getStateAdapter, ft as microUsdToUsd, gt as conversationUsageCostExpr, ht as conversationRangeColumns, mt as conversationAggregateColumns, o as getDb, ot as withLock, s as getSqlExecutor, y as loadConversationSlackTenantIds } from "./db-CFUpEZi9.js";
3
+ import { At as createAttachmentUpload, Et as webActorFromUser, Gn as setConversationSubscription, It as listOwnedWatches, Jn as throwApiError, Kn as emptyResponse, Lt as listChildAgents, Mt as writeAttachmentUpload, Ot as AttachmentUploadError, Si as AutomationEditError, T as readStats, _ as breakerStates, ai as changeViewerAutomationLifecycle, bt as acceptsWebMessages, ci as updateViewerAutomation, di as readViewerAutomationExecutions, fi as readViewerAutomationRuns, g as savingsTotals, hi as readViewerAutomations, ki as countOwnedAutomationsNeedingAttention, li as ViewerTaskNotFoundError, mi as readViewerAutomationVersions, ni as activateViewerAutomationVersion, oi as deleteViewerTask, pi as readViewerAutomationSummary, pt as reportConversationRead, qn as jsonResponse, si as readViewerAutomationEdit, u as SAVINGS_NAMESPACE, ut as archiveConversation, v as closeBreaker, y as connectedState } from "./warmup-DN9OHN1-.js";
4
+ import { C as createConversationMessageBodySchema, H as renameConversationResponseSchema, S as createConversationBodySchema, T as forkConversationResponseSchema, U as conversationReadPositionSchema, V as renameConversationBodySchema, Z as MAX_ATTACHMENT_BYTES, f as conversationEventPageSchema, l as conversationDetailQuerySchema, m as conversationParamsSchema, n as CONVERSATION_VERSION_HEADER, o as conversationAttachmentParamsSchema, p as conversationEventsQuerySchema, r as acceptedConversationMessageSchema, s as conversationAttachmentQuerySchema, t as CONVERSATION_DETAIL_VERSION_HEADER, u as conversationDetailReportSchema, w as forkConversationBodySchema } from "./conversation-CzrLhdHG.js";
5
+ import { $ as testNotificationResponseSchema, A as startServiceAccountSignInResponseSchema, At as objectLinksReportSchema, B as personParamsSchema, Bt as conversationSubscriptionResponseSchema, C as cacheWarmingSavingsRefillResponseSchema, Ct as conversationChildAgentsReportSchema, D as serviceAccountListSchema, Dt as attachObjectLinkBodySchema, E as disconnectServiceAccountResponseSchema, F as personalTokenParamsSchema, Ft as archiveConversationBodySchema, G as locationParamsSchema, Gt as reorderPinnedConversationsBodySchema, Ht as conversationDeliveryResponseSchema, I as revokePersonalTokenResponseSchema, It as archiveConversationResponseSchema, J as activitySixHours$1, Jt as conversationCatchUpSchema, K as activityDays$1, Kt as reorderPinnedConversationsResponseSchema, L as actorDirectoryReportSchema, Lt as archiveDoneConversationsResponseSchema, M as createdPersonalTokenSchema, Mt as conversationStatsReportSchema, N as personalTokenListSchema, O as serviceAccountParamsSchema, Ot as attachObjectLinkResponseSchema, Pt as conversationOutlineSchema, Q as pushSubscriptionDeleteBodySchema, R as actorProfileReportSchema, Rt as conversationAutoArchiveSchema, S as cacheWarmingSavingsQuerySchema, T as closeCacheWarmingBreakerResponseSchema, Tt as continueConversationInSlackResponseSchema, U as locationDetailReportSchema, Ut as pinConversationBodySchema, V as personalSpendReportSchema, Vt as conversationDeliveryBodySchema, W as locationDirectoryReportSchema, Wt as pinConversationResponseSchema, X as notificationSettingsSchema, Xt as attachmentUploadSchema, Yt as attachmentUploadParamsSchema, Z as pushSubscriptionBodySchema, Zt as createAttachmentUploadBodySchema, _ as reviewItemParamsSchema, _t as conversationPlanReportSchema, b as cacheWarmingBreakerListSchema, c as workspaceListSchema, d as workspaceSchema, dt as codeRepositoryParamsSchema, et as connectionListSchema, f as reviewItemActionSchema, ft as codeRepositoryQuerySchema, g as reviewItemListSchema, gt as conversationPlanItemSchema, h as reviewItemListQuerySchema, ht as personCodeQuerySchema, i as statsReportSchema, it as startConnectionResponseSchema, j as createPersonalTokenBodySchema, jt as stopConversationTurnResponseSchema, kt as objectLinksQuerySchema, l as workspaceParamsSchema, lt as codeOverviewReportSchema, m as reviewItemCountSchema, n as versionsSchema, o as deleteWorkspaceResponseSchema, p as reviewItemCountQuerySchema, pt as codeRepositoryReportSchema, q as activityHours$1, qt as conversationCatchUpBodySchema, rt as disconnectConnectionResponseSchema, s as workspaceBodySchema, t as versionsQuerySchema, tt as connectionParamsSchema, ut as codePersonReportSchema, v as reviewItemSchema, vt as planItemParamsSchema, w as cacheWarmingSavingsReportSchema, wt as continueConversationInSlackBodySchema, x as cacheWarmingBreakerParamsSchema, xt as conversationWatchesReportSchema, y as reviewItemWaitingConversationsSchema, yt as planItemStatusBodySchema, z as avatarParamsSchema, zt as conversationSubscriptionBodySchema } from "./schema-CfIey9Ao.js";
6
+ import { S as skillDetailReportSchema, a as cancelConversationPendingMessagesResponseSchema, b as pluginsSchema, d as conversationUnchangedDetailWithMailboxSchema, f as steerConversationPendingMessagesBodySchema, h as pluginOperationalReportFeedSchema, i as cancelConversationPendingMessagesBodySchema, m as healthReportSchema, n as conversationFeedQuerySchema, o as conversationDetailWithMailboxReportSchema, p as steerConversationPendingMessagesResponseSchema, r as conversationFeedSchema, u as conversationPendingMessagesReportSchema, w as skillReportsSchema, x as runtimeInfoReportSchema } from "./conversation-feed-B9e3_gxz.js";
7
+ import { G as isAllowedDomain, H as addConversationNote, S as setPlanItemStatusByUser, _ as readUserCustomization, ft as isExperimentalFeatureEnabled, mt as getEventCatalog, q as parseEmail, v as saveUserCustomization, x as listPlanItems } from "./session-stop-P2XdTiwr.js";
8
+ import { $r as reviewItemReaderForUser, Ar as countOpenReviewItemsForUser, Bi as listWorkspacesByRepository, Cr as saveNotificationSchedule, Da as workspaceRepoCheckoutPath, Ec as automationEventCatalog, Fi as createWorkspace, Fo as listConversationAnnotations, Hi as WorkspaceValidationError, Ii as deleteWorkspace, Ja as readConversationAccessFromSql, Ji as hash, Jr as itemNeedsUser, Li as getWorkspace, Lr as listWaitingConversations, Ls as escapeSlackMrkdwnText, Nn as getPlugins, Po as createPluginAnnotations, Rr as reviewItemsNeedingUserVersionQuery, Rs as formatSlackLink, Sr as readNotificationSchedule, Ta as SANDBOX_RUNTIME, Tr as isPausedBySlack, Ur as canActOnReviewItem, Vi as updateWorkspace, Wa as createPluginLogger, Wc as AutomationConflictError, _r as readWebPushConfig, bn as createUserTokenStore, br as deletePushSubscription, ei as reviewItemReaderForUserInConversation, fl as createPluginCache, go as readSlackAttachmentSource, il as readAutomationTitlesByConversationId, io as readConversationEventPage, jr as countReviewItemsNeedingUserBySubject, nc as getDashboardConversationLink, no as readConversationBriefThrough, ps as postSlackMessage, qa as createConversationAccessReader, qi as create, qr as isOnlyAssignee, sc as getDashboardSettingsLink, ti as reviewItemVisibleTo, vr as sendPushNotificationToUser, wr as savePushSubscription, xo as readLiveAttachment, xr as listPushSubscriptions, yr as resolveNotificationTimezone, z as createPluginEgress, zi as listWorkspaces, zr as searchReviewItems } from "./projection-Ce4pmhKP.js";
9
+ import { A as actOnReviewItem, B as readSavingsRefill, Ct as decodeImageId, D as resolveMentions, E as requireConversationPendingMessages, G as readHealthReport, H as startSavingsRefill, I as setConversationAutoArchive, J as readObjectLinkTypes, K as OBJECT_LINK_TTL_MS, L as DEFAULT_USER_SETTINGS, M as readReviewItemForUser, P as archiveViewerDoneConversations, R as readUserSettings, St as IMAGE_WIDTHS, X as resolveObjectLinks, Y as resolveObjectLinkNow, Z as guardedFetch, _ as readConversationEvents, a as decodePageCursor, b as createConversationForViewer, bt as readFirstHumanMessageTexts, c as reorderPinnedConversations, d as childAgentTotalsReport, f as readConversationTreeMetricsFromSql, g as keepQuickQuestionForViewer, h as forkConversationForViewer, i as readConversationFeed, k as ReviewItemActionError, l as readConversationDetail, m as readConversationDetailEtag, n as steerConversationPendingMessagesForViewer, nt as getProductionSlackAdapter, o as encodePageCursor, p as conversationVersionQuery, q as readLinkObjectType, r as conversationFeedVersionQuery, s as pinConversation, t as stopConversationTurnForViewer, u as readConversationAuxiliaryCostsFromSql, w as cancelConversationPendingMessagesForViewer, x as requireWebMessageConversation, xt as createViewerMcp, y as appendConversationMessageForViewer, yt as conversationSummaryFromStoredConversation, z as updateUserSettings } from "./stop-D9xideLM.js";
10
+ import { d as completeText, n as briefEntriesFromReportEvents } from "./prompt-DEqjDVMs.js";
11
+ import { A as resumeConversationDelivery, D as canPauseConversationDelivery, M as readAttachmentContent, N as previewOriginBelongsTo, _ as createSlackReviewItemShow, j as AttachmentDownloadError, k as pauseConversationDelivery } from "./agent-runner-sJLhgPQV.js";
12
+ import { _ as runBestEffort, h as logWarn, m as logInfo, p as logException } from "./logging-BNUovdcX.js";
13
+ import { t as runWithSlackInstallation } from "./adapter-context-1YUbMpD3.js";
14
+ import { A as juniorConversationEvents, B as juniorUsers, E as juniorConversationBriefs, N as juniorCodeChanges, O as juniorConversationMetrics, P as juniorCodeRepositories, R as juniorConversations, V as juniorDestinations, f as juniorReviewItems, j as juniorApiTokens, u as juniorReviewItemConversations, v as juniorAgentBindings, y as juniorAgentInvocations, z as juniorIdentities } from "./executor-DXL0O0MV.js";
15
+ import { i as continueConversationInSlack, r as canContinueInSlack, t as BUSY } from "./continue-in-slack-BQJBfiQh.js";
16
+ import { f as parseSlackTeamId, u as parseSlackChannelId } from "./actor-BsBdxDXQ.js";
17
17
  import { A as HOUR_MS$1, F as sumUtcHoursIntoSixHours, I as trailingUtcDayWindow, L as trailingUtcHourWindow, M as fillUtcHours, N as fillUtcSixHours, O as apiErrorSchema, P as startOfUtcHour, R as trailingUtcSixHourWindow, _ as userCustomizationSchema, f as INLINE_VIDEO_TYPES, j as fillUtcDays, k as DAY_MS$2, m as detectImageMediaType, p as INPUT_IMAGE_TYPES, x as isOpenPlanItemStatus, z as utcHourKey } from "./web-message-id-BT8Mg8LL.js";
18
- import { a as startConnection, n as isConnectableProvider, r as listConnections, s as htmlCallbackResponse, t as disconnectConnection } from "./connections-DUylBPiR.js";
19
- import { p as credentialContextForActor } from "./registry-tHJLCtKS.js";
20
- import { c as readViewerAvatarUrl, d as updateViewerDisplayName, l as resolveViewerUser, m as readAvatarFetch, t as findUserByEmail } from "./viewer-CqOkWizK.js";
21
- import { n as finishServiceAccountSignIn, o as serviceAccountPlugins, r as getServiceAccountStatus, s as startServiceAccountSignIn, t as disconnectServiceAccount } from "./service-account-CddxU-yC.js";
22
- import { n as pluginCatalogRuntime } from "./catalog-runtime-q9AJjuUN.js";
23
- import { B as compileScheduleIntent, C as automationUpdateSchema, E as automationVersionParamsSchema, Q as automationTaskText, S as automationSummarySchema, T as automationVersionListSchema, _ as automationRunListSchema, a as automationEditSchema, b as automationScheduleIntentSchema, d as automationLifecycleSchema, g as automationParamsSchema, i as automationEditErrorSchema, m as automationListQuerySchema, o as automationEventCatalogSchema, p as automationListPageSchema, r as notificationScheduleSchema, s as automationExecutionListSchema, w as automationVersionActivateSchema, x as automationSchedulePreviewSchema, z as ScheduleIntentError } from "./schedule-BG1tEbRF.js";
24
- import { o as getSandboxResources } from "./install-Y2s9ZPvk.js";
25
- import { t as getCachedSnapshot } from "./resolve-z2sKt8xM.js";
26
- import { m as getVercelConversationWorkQueue } from "./background-compaction-queue-BpmDEQf6.js";
18
+ import { a as isConnectableProvider, c as startConnection, i as disconnectConnection, o as listConnections, t as escapeHtml, u as htmlCallbackResponse } from "./html-CaBu2VbT.js";
19
+ import { p as credentialContextForActor } from "./registry-CNE4ZBnG.js";
20
+ import { c as readViewerAvatarUrl, d as updateViewerDisplayName, l as resolveViewerUser, m as readAvatarFetch, t as findUserByEmail } from "./viewer-DudYrQGj.js";
21
+ import { t as mapBounded } from "./fan-out-Cod-yEHG.js";
22
+ import { n as finishServiceAccountSignIn, o as serviceAccountPlugins, r as getServiceAccountStatus, s as startServiceAccountSignIn, t as disconnectServiceAccount } from "./service-account-Cw_LWZ4-.js";
23
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-Chc_IP2o.js";
24
+ import { B as compileScheduleIntent, C as automationUpdateSchema, E as automationVersionParamsSchema, Q as automationTaskText, S as automationSummarySchema, T as automationVersionListSchema, _ as automationRunListSchema, a as automationEditSchema, b as automationScheduleIntentSchema, d as automationLifecycleSchema, g as automationParamsSchema, i as automationEditErrorSchema, m as automationListQuerySchema, o as automationEventCatalogSchema, p as automationListPageSchema, r as notificationScheduleSchema, s as automationExecutionListSchema, w as automationVersionActivateSchema, x as automationSchedulePreviewSchema, z as ScheduleIntentError } from "./schedule-Cire6NU7.js";
25
+ import { o as getSandboxResources } from "./install-DhTBUUov.js";
26
+ import { t as getCachedSnapshot } from "./resolve-qbPg-aC-.js";
27
+ import { m as getVercelConversationWorkQueue } from "./background-compaction-queue-CUJXVKG3.js";
27
28
  import { Hono } from "hono";
28
29
  import * as z from "zod";
29
30
  import path from "node:path";
30
31
  import { createHash, randomBytes, randomUUID } from "node:crypto";
31
- import { and, asc, countDistinct, desc, eq, gt, gte, inArray, isNull, lt, lte, ne, notExists, or, sql } from "drizzle-orm";
32
32
  import { objectPresentation, pluginUserPageContentSchema, pluginUserPageCursorSchema, pluginUserPageFilterSchema, pluginUserPageLinksSchema, pluginUserPageQuerySchema } from "@sentry/junior-plugin-api";
33
+ import { and, asc, desc, eq, exists, gt, gte, inArray, isNotNull, isNull, lt, lte, ne, or, sql } from "drizzle-orm";
33
34
  import { alias } from "drizzle-orm/pg-core";
34
35
  import fs from "node:fs/promises";
35
36
  import { readFileSync } from "node:fs";
36
37
  import { HTTPException } from "hono/http-exception";
37
38
  import { bodyLimit } from "hono/body-limit";
39
+ import { waitUntil } from "@vercel/functions";
38
40
  import { zValidator } from "@hono/zod-validator";
39
41
  import { createMiddleware } from "hono/factory";
40
42
  // src/api/objects/attach.ts
@@ -656,9 +658,9 @@ function withoutCutToken(text) {
656
658
  return text.length < 200 ? text : text.replace(/<([^<>]*)$/, (_, token) => /^[@#!]/.test(token) ? "" : token.split("|")[0]);
657
659
  }
658
660
  // src/api/conversations/metric-buckets.ts
659
- /** Sum all Conversation metrics into UTC day or hour buckets. */
661
+ /** Sum all Conversation metrics into UTC hour buckets. */
660
662
  async function readConversationMetricBuckets(db, options) {
661
- const date = options.bucket === "day" ? sql`to_char(${juniorConversationMetrics.occurredAt} at time zone 'UTC', 'YYYY-MM-DD')` : sql`to_char(${juniorConversationMetrics.occurredAt} at time zone 'UTC', 'YYYY-MM-DD"T"HH24')`;
663
+ const date = sql`to_char(${juniorConversationMetrics.occurredAt} at time zone 'UTC', 'YYYY-MM-DD"T"HH24')`;
662
664
  return await db.select({
663
665
  date,
664
666
  metric: juniorConversationMetrics.metric,
@@ -668,11 +670,12 @@ async function readConversationMetricBuckets(db, options) {
668
670
  // src/api/conversations/outcome-buckets.ts
669
671
  const changes = juniorCodeChanges;
670
672
  const linked = alias(juniorConversations, "linked");
673
+ const tree = alias(juniorConversations, "outcome_tree");
671
674
  const linksChange = sql`${linked.conversationId} = any(${changes.conversationIds})`;
672
675
  const linkedRoot = sql`coalesce(${linked.rootConversationId}, ${linked.conversationId})`;
673
676
  /**
674
- * Count outcomes per UTC day or hour, with the conversation cost that
675
- * produced them. An outcome is one of:
677
+ * Count outcomes per UTC hour, with the conversation cost that produced
678
+ * them. An outcome is one of:
676
679
  *
677
680
  * - a merged code change, at its merge time. Each root Conversation splits its
678
681
  * tree cost evenly across all of its merged code changes, so a long
@@ -687,12 +690,9 @@ const linkedRoot = sql`coalesce(${linked.rootConversationId}, ${linked.conversat
687
690
  */
688
691
  async function readOutcomeBuckets(db, options) {
689
692
  const [merges, briefRoots] = await Promise.all([readWindowMerges(db, options), readBriefOutcomeRoots(db, options)]);
690
- const mergeRoots = [...new Set(merges.map((merge) => merge.rootId))];
691
- const [rootMerges, treeCosts] = await Promise.all([readRootMergeCounts(db, mergeRoots), readTreeCosts$1(db, [...mergeRoots, ...briefRoots.map((root) => root.rootId)])]);
692
- const dateLength = options.bucket === "day" ? 10 : 13;
693
693
  const buckets = /* @__PURE__ */ new Map();
694
694
  const bucketAt = (instant) => {
695
- const date = instant.toISOString().slice(0, dateLength);
695
+ const date = instant.toISOString().slice(0, 13);
696
696
  let bucket = buckets.get(date);
697
697
  if (!bucket) {
698
698
  bucket = {
@@ -708,7 +708,7 @@ async function readOutcomeBuckets(db, options) {
708
708
  };
709
709
  const changeCosts = /* @__PURE__ */ new Map();
710
710
  for (const merge of merges) {
711
- const share = (treeCosts.get(merge.rootId) ?? 0) / (rootMerges.get(merge.rootId) ?? 1);
711
+ const share = merge.treeCostUsd / merge.rootMerges;
712
712
  const change = changeCosts.get(merge.changeId);
713
713
  if (change) change.costUsd += share;
714
714
  else changeCosts.set(merge.changeId, {
@@ -726,17 +726,39 @@ async function readOutcomeBuckets(db, options) {
726
726
  for (const root of briefRoots) {
727
727
  const bucket = bucketAt(root.lastActivityAt);
728
728
  bucket.outcomes += 1;
729
- bucket.outcomeCostUsd += treeCosts.get(root.rootId) ?? 0;
729
+ bucket.outcomeCostUsd += root.treeCostUsd;
730
730
  }
731
731
  return [...buckets.values()];
732
732
  }
733
+ /** The summed usage cost of the Conversation tree of `rootId`. */
734
+ function treeCostUsd(db, rootId) {
735
+ const cost = db.select({ costUsd: sql`coalesce(sum(${conversationUsageCostExpr(tree.usage)}), 0)` }).from(tree).where(or(eq(tree.rootConversationId, rootId), eq(tree.conversationId, rootId)));
736
+ return sql`(${cost})::double precision`;
737
+ }
738
+ /**
739
+ * Merged code changes in the window, one row per linked root, with the
740
+ * merged changes of all time of that root, so each merge gets its share.
741
+ */
733
742
  async function readWindowMerges(db, options) {
734
- return (await db.selectDistinct({
743
+ const mergedRoots = db.selectDistinct({
735
744
  changeId: changes.id,
736
745
  mergedAt: changes.mergedAt,
737
- rootId: linkedRoot
738
- }).from(changes).innerJoin(linked, linksChange).where(and(eq(changes.state, "merged"), gte(changes.mergedAt, options.start), lte(changes.mergedAt, options.end)))).flatMap(({ changeId, mergedAt, rootId }) => mergedAt && rootId ? [{
739
- changeId,
746
+ rootId: linkedRoot.as("root_id")
747
+ }).from(changes).innerJoin(linked, linksChange).where(eq(changes.state, "merged")).as("merged_roots");
748
+ const counted = db.select({
749
+ changeId: mergedRoots.changeId,
750
+ mergedAt: mergedRoots.mergedAt,
751
+ rootId: mergedRoots.rootId,
752
+ rootMerges: sql`count(*) over (partition by ${mergedRoots.rootId})::integer`.as("root_merges")
753
+ }).from(mergedRoots).as("counted_merges");
754
+ return (await db.select({
755
+ changeId: counted.changeId,
756
+ mergedAt: counted.mergedAt,
757
+ rootId: counted.rootId,
758
+ rootMerges: counted.rootMerges,
759
+ treeCostUsd: treeCostUsd(db, counted.rootId)
760
+ }).from(counted).where(and(gte(counted.mergedAt, options.start), lte(counted.mergedAt, options.end)))).flatMap(({ mergedAt, rootId, ...merge }) => mergedAt && rootId ? [{
761
+ ...merge,
740
762
  mergedAt,
741
763
  rootId
742
764
  }] : []);
@@ -745,30 +767,12 @@ async function readBriefOutcomeRoots(db, options) {
745
767
  const roots = juniorConversations;
746
768
  const briefs = juniorConversationBriefs;
747
769
  const latestBrief = db.select({ status: sql`${briefs.content}->'outcome'->>'status'`.as("status") }).from(briefs).where(eq(briefs.conversationId, roots.conversationId)).orderBy(desc(briefs.version)).limit(1).as("latest_brief");
770
+ const changeRoots = db.selectDistinct({ rootId: linkedRoot.as("root_id") }).from(changes).innerJoin(linked, linksChange).as("change_roots");
748
771
  return await db.select({
749
772
  lastActivityAt: roots.lastActivityAt,
750
- rootId: roots.conversationId
751
- }).from(roots).innerJoinLateral(latestBrief, sql`true`).where(and(isNull(roots.parentConversationId), gte(roots.lastActivityAt, options.start), lte(roots.lastActivityAt, options.end), inArray(latestBrief.status, ["done", "answered"]), notExists(db.select({ id: changes.id }).from(changes).innerJoin(linked, linksChange).where(eq(linkedRoot, roots.conversationId)))));
752
- }
753
- /** Merged code changes of all time per root, so each merge gets its share. */
754
- async function readRootMergeCounts(db, rootIds) {
755
- if (!rootIds.length) return /* @__PURE__ */ new Map();
756
- const rows = await db.select({
757
- merged: countDistinct(changes.id),
758
- rootId: linkedRoot
759
- }).from(changes).innerJoin(linked, linksChange).where(and(eq(changes.state, "merged"), inArray(linkedRoot, [...rootIds]))).groupBy(linkedRoot);
760
- return new Map(rows.flatMap((row) => row.rootId ? [[row.rootId, row.merged]] : []));
761
- }
762
- async function readTreeCosts$1(db, rootIds) {
763
- if (!rootIds.length) return /* @__PURE__ */ new Map();
764
- const conversations = juniorConversations;
765
- const ids = [...new Set(rootIds)];
766
- const treeRoot = sql`coalesce(${conversations.rootConversationId}, ${conversations.conversationId})`;
767
- const rows = await db.select({
768
- costUsd: sql`coalesce(sum(${conversationUsageCostExpr(conversations.usage)}), 0)::double precision`,
769
- rootId: treeRoot
770
- }).from(conversations).where(or(inArray(conversations.rootConversationId, ids), inArray(conversations.conversationId, ids))).groupBy(treeRoot);
771
- return new Map(rows.flatMap((row) => row.rootId ? [[row.rootId, row.costUsd]] : []));
773
+ rootId: roots.conversationId,
774
+ treeCostUsd: treeCostUsd(db, roots.conversationId)
775
+ }).from(roots).innerJoinLateral(latestBrief, sql`true`).leftJoin(changeRoots, eq(changeRoots.rootId, roots.conversationId)).where(and(isNull(roots.parentConversationId), gte(roots.lastActivityAt, options.start), lte(roots.lastActivityAt, options.end), inArray(latestBrief.status, ["done", "answered"]), isNull(changeRoots.rootId)));
772
776
  }
773
777
  // src/api/conversations/stats.query.ts
774
778
  const treeConversation$1 = alias(juniorConversations, "stats_tree_conversation");
@@ -776,48 +780,9 @@ const treeAggregateColumns$1 = conversationAggregateColumns({
776
780
  metrics: treeConversation$1,
777
781
  roots: juniorConversations
778
782
  });
779
- function emptyStatsItem(label) {
780
- return {
781
- active: 0,
782
- conversations: 0,
783
- durationMs: 0,
784
- failed: 0,
785
- label
786
- };
787
- }
788
783
  function addUsd(current, next) {
789
784
  return Math.round(((current ?? 0) + next) * 0xe8d4a51000) / 0xe8d4a51000;
790
785
  }
791
- function actorLabel$1(row) {
792
- return row.userEmail?.trim() || row.identityEmail?.trim() || row.userDisplayName?.trim() || row.identityDisplayName?.trim() || row.identityHandle?.trim() || row.identitySubjectId?.trim() || "Unknown";
793
- }
794
- function surfaceLabel$1(source) {
795
- if (source === "scheduler") return "Scheduler";
796
- if (source === "api" || source === "web") return "Web";
797
- if (source === "internal" || source === "local") return "Internal";
798
- return "Conversation";
799
- }
800
- /** Collapse private Slack destinations before any stored name reaches stats. */
801
- function locationLabel$1(row) {
802
- if (row.destinationProvider !== "slack") return surfaceLabel$1(row.source);
803
- if (row.destinationKind === "dm") return "Direct Message";
804
- if (row.destinationVisibility !== "public") return "Private Conversation";
805
- const name = (row.channelName ?? row.destinationDisplayName)?.trim().replace(/^#/, "");
806
- return name ? `#${name}` : "Public Channel";
807
- }
808
- function addAggregate$1(map, label, row) {
809
- const item = map.get(label) ?? emptyStatsItem(label);
810
- item.active += row.active;
811
- item.conversations += row.conversations;
812
- item.durationMs += row.durationMs;
813
- item.failed += row.failed;
814
- if (row.tokens !== null) item.tokens = (item.tokens ?? 0) + row.tokens;
815
- if (row.costUsd !== null) item.costUsd = addUsd(item.costUsd, row.costUsd);
816
- map.set(label, item);
817
- }
818
- function statsItems$1(map) {
819
- return [...map.values()].sort((left, right) => right.conversations - left.conversations || left.label.localeCompare(right.label));
820
- }
821
786
  function statsWhere(start, end) {
822
787
  return and(isNull(juniorConversations.parentConversationId), gte(juniorConversations.lastActivityAt, start), lte(juniorConversations.lastActivityAt, end));
823
788
  }
@@ -832,8 +797,6 @@ function statsWindow(nowMs) {
832
797
  };
833
798
  }
834
799
  const HOUR_MS = 36e5;
835
- /** Keep 7d of hours so clients can roll 7d charts into 6h buckets. */
836
- const WINDOW_HOURS = 168;
837
800
  function emptyMetricRow(date) {
838
801
  return {
839
802
  cachedInputTokens: null,
@@ -954,7 +917,7 @@ function guardianPoint(date, row) {
954
917
  date,
955
918
  deny: row?.deny ?? 0,
956
919
  requests: row?.requests ?? 0,
957
- ...row?.costUsd !== null && row?.costUsd !== void 0 ? { costUsd: row.costUsd } : void 0
920
+ ...row?.costUsd !== null && row?.costUsd !== void 0 ? { costUsd: addUsd(void 0, row.costUsd) } : void 0
958
921
  };
959
922
  }
960
923
  function guardianStats(dayRows, hourRows, endMs) {
@@ -998,80 +961,32 @@ function guardianStats(dayRows, hourRows, endMs) {
998
961
  ...costUsd !== void 0 ? { costUsd } : void 0
999
962
  };
1000
963
  }
1001
- async function aggregateStats(db, start, end) {
1002
- const where = statsWhere(start, end);
1003
- const hourStart = trailingUtcHourWindow(end.getTime(), WINDOW_HOURS).start;
1004
- const activityDate = sql`TO_CHAR(
1005
- ${juniorConversations.lastActivityAt} AT TIME ZONE 'UTC',
1006
- 'YYYY-MM-DD'
1007
- )`;
964
+ /** Sum hour rows into UTC day rows, one per day and `key`. */
965
+ function sumHoursIntoDays(hours, add, key = () => "") {
966
+ const days = /* @__PURE__ */ new Map();
967
+ for (const hour of hours) {
968
+ const date = hour.date.slice(0, 10);
969
+ const dayKey = `${date}:${key(hour)}`;
970
+ const day = days.get(dayKey);
971
+ if (day) add(day, hour);
972
+ else days.set(dayKey, {
973
+ ...hour,
974
+ date
975
+ });
976
+ }
977
+ return [...days.values()];
978
+ }
979
+ async function readActivityHours(db, start, end) {
1008
980
  const activityHour = sql`TO_CHAR(
1009
981
  ${juniorConversations.lastActivityAt} AT TIME ZONE 'UTC',
1010
982
  'YYYY-MM-DD"T"HH24'
1011
983
  )`;
1012
- const [totalsRows, actorRows, locationRows, metricRows, metricHourRows, dayMetrics, hourMetrics, dayOutcomes, hourOutcomes] = await Promise.all([
1013
- db.select(treeAggregateColumns$1).from(juniorConversations).innerJoin(treeConversation$1, eq(treeConversation$1.rootConversationId, juniorConversations.conversationId)).where(where),
1014
- db.select({
1015
- identityDisplayName: juniorIdentities.displayName,
1016
- identityEmail: juniorIdentities.emailNormalized,
1017
- identityHandle: juniorIdentities.handle,
1018
- identitySubjectId: juniorIdentities.providerSubjectId,
1019
- userDisplayName: juniorUsers.displayName,
1020
- userEmail: juniorUsers.primaryEmailNormalized,
1021
- ...treeAggregateColumns$1
1022
- }).from(juniorConversations).innerJoin(treeConversation$1, eq(treeConversation$1.rootConversationId, juniorConversations.conversationId)).leftJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(where).groupBy(juniorIdentities.displayName, juniorIdentities.emailNormalized, juniorIdentities.handle, juniorIdentities.providerSubjectId, juniorUsers.displayName, juniorUsers.primaryEmailNormalized),
1023
- db.select({
1024
- channelName: juniorConversations.channelName,
1025
- destinationDisplayName: juniorDestinations.displayName,
1026
- destinationKind: juniorDestinations.kind,
1027
- destinationProvider: juniorDestinations.provider,
1028
- destinationVisibility: juniorDestinations.visibility,
1029
- source: juniorConversations.source,
1030
- ...treeAggregateColumns$1
1031
- }).from(juniorConversations).innerJoin(treeConversation$1, eq(treeConversation$1.rootConversationId, juniorConversations.conversationId)).leftJoin(juniorDestinations, eq(juniorDestinations.id, juniorConversations.destinationId)).where(where).groupBy(juniorConversations.channelName, juniorConversations.source, juniorDestinations.displayName, juniorDestinations.kind, juniorDestinations.provider, juniorDestinations.visibility),
1032
- db.select({
1033
- conversations: treeAggregateColumns$1.conversations,
1034
- date: activityDate
1035
- }).from(juniorConversations).innerJoin(treeConversation$1, eq(treeConversation$1.rootConversationId, juniorConversations.conversationId)).where(where).groupBy(activityDate),
1036
- db.select({
1037
- conversations: treeAggregateColumns$1.conversations,
1038
- date: activityHour
1039
- }).from(juniorConversations).innerJoin(treeConversation$1, eq(treeConversation$1.rootConversationId, juniorConversations.conversationId)).where(statsWhere(hourStart, end)).groupBy(activityHour),
1040
- readConversationMetricBuckets(db, {
1041
- bucket: "day",
1042
- start,
1043
- end
1044
- }),
1045
- readConversationMetricBuckets(db, {
1046
- bucket: "hour",
1047
- start: hourStart,
1048
- end
1049
- }),
1050
- readOutcomeBuckets(db, {
1051
- bucket: "day",
1052
- start,
1053
- end
1054
- }),
1055
- readOutcomeBuckets(db, {
1056
- bucket: "hour",
1057
- start: hourStart,
1058
- end
1059
- })
1060
- ]);
1061
- return {
1062
- actorRows,
1063
- locationRows,
1064
- metricHourRows: applyMetricBuckets(metricHourRows, hourMetrics, hourOutcomes),
1065
- metricRows: applyMetricBuckets(metricRows, dayMetrics, dayOutcomes),
1066
- totals: totalsRows[0]
1067
- };
984
+ return await db.select({
985
+ conversations: treeAggregateColumns$1.conversations,
986
+ date: activityHour
987
+ }).from(juniorConversations).innerJoin(treeConversation$1, eq(treeConversation$1.rootConversationId, juniorConversations.conversationId)).where(statsWhere(start, end)).groupBy(activityHour);
1068
988
  }
1069
- async function aggregateGuardianStats(db, start, end) {
1070
- const hourStart = trailingUtcHourWindow(end.getTime(), WINDOW_HOURS).start;
1071
- const day = sql`TO_CHAR(
1072
- ${juniorConversationEvents.createdAt} AT TIME ZONE 'UTC',
1073
- 'YYYY-MM-DD'
1074
- )`;
989
+ async function readGuardianHours(db, start, end) {
1075
990
  const hour = sql`TO_CHAR(
1076
991
  ${juniorConversationEvents.createdAt} AT TIME ZONE 'UTC',
1077
992
  'YYYY-MM-DD"T"HH24'
@@ -1082,67 +997,114 @@ async function aggregateGuardianStats(db, start, end) {
1082
997
  THEN (${juniorConversationEvents.payload}->>'costUsd')::double precision
1083
998
  ELSE NULL
1084
999
  END`;
1085
- const selectColumns = {
1000
+ return await db.select({
1086
1001
  allow: sql`COUNT(*) FILTER (WHERE ${decision} = 'allow')::integer`,
1087
1002
  ask: sql`COUNT(*) FILTER (WHERE ${decision} = 'ask')::integer`,
1088
1003
  costUsd: sql`SUM(${cost})::double precision`,
1004
+ date: hour,
1089
1005
  deny: sql`COUNT(*) FILTER (WHERE ${decision} = 'deny')::integer`,
1090
1006
  requests: sql`COUNT(*)::integer`
1091
- };
1092
- const where = (windowStart) => and(eq(juniorConversationEvents.type, "guardian_action_reviewed"), gte(juniorConversationEvents.createdAt, windowStart), lte(juniorConversationEvents.createdAt, end));
1093
- const [dayRows, hourRows] = await Promise.all([db.select({
1094
- ...selectColumns,
1095
- date: day
1096
- }).from(juniorConversationEvents).where(where(start)).groupBy(day), db.select({
1097
- ...selectColumns,
1098
- date: hour
1099
- }).from(juniorConversationEvents).where(where(hourStart)).groupBy(hour)]);
1100
- return {
1101
- dayRows,
1102
- hourRows
1103
- };
1007
+ }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.type, "guardian_action_reviewed"), gte(juniorConversationEvents.createdAt, start), lte(juniorConversationEvents.createdAt, end))).groupBy(hour);
1104
1008
  }
1105
1009
  /** Build complete 90-day dashboard stats from normalized durable SQL records. */
1106
1010
  async function readConversationStatsFromSql() {
1107
1011
  const nowMs = Date.now();
1108
1012
  const { end, start } = statsWindow(nowMs);
1109
1013
  const db = getDb();
1110
- const [{ actorRows, locationRows, metricHourRows, metricRows, totals }, guardian] = await Promise.all([aggregateStats(db, start, end), aggregateGuardianStats(db, start, end)]);
1111
- const actors = /* @__PURE__ */ new Map();
1112
- const locations = /* @__PURE__ */ new Map();
1113
- for (const row of actorRows) addAggregate$1(actors, actorLabel$1(row), row);
1114
- for (const row of locationRows) addAggregate$1(locations, locationLabel$1(row), row);
1014
+ const [activity, metrics, outcomes, guardian] = await Promise.all([
1015
+ readActivityHours(db, start, end),
1016
+ readConversationMetricBuckets(db, {
1017
+ start,
1018
+ end
1019
+ }),
1020
+ readOutcomeBuckets(db, {
1021
+ start,
1022
+ end
1023
+ }),
1024
+ readGuardianHours(db, start, end)
1025
+ ]);
1026
+ const hours = metricHours(applyMetricBuckets(activity, metrics, outcomes), nowMs);
1115
1027
  return {
1116
- active: totals?.active ?? 0,
1117
- ...totals?.cachedInputTokens !== null && totals?.cachedInputTokens !== void 0 ? { cachedInputTokens: totals.cachedInputTokens } : void 0,
1118
- ...totals?.cacheCreationTokens !== null && totals?.cacheCreationTokens !== void 0 ? { cacheCreationTokens: totals.cacheCreationTokens } : void 0,
1119
- conversations: totals?.conversations ?? 0,
1120
- durationMs: totals?.durationMs ?? 0,
1121
- failed: totals?.failed ?? 0,
1122
1028
  generatedAt: new Date(nowMs).toISOString(),
1123
- guardian: guardianStats(guardian.dayRows, guardian.hourRows, nowMs),
1124
- metricDays: metricDays(metricRows, nowMs),
1125
- ...(() => {
1126
- const hours = metricHours(metricHourRows, nowMs);
1127
- return {
1128
- metricHours: hours,
1129
- metricSixHours: sumMetricHoursIntoSixHours(hours, nowMs)
1130
- };
1131
- })(),
1132
- locations: statsItems$1(locations),
1133
- actors: statsItems$1(actors),
1029
+ guardian: guardianStats(sumHoursIntoDays(guardian, (day, hour) => {
1030
+ day.allow += hour.allow;
1031
+ day.ask += hour.ask;
1032
+ day.deny += hour.deny;
1033
+ day.requests += hour.requests;
1034
+ if (hour.costUsd !== null) day.costUsd = (day.costUsd ?? 0) + hour.costUsd;
1035
+ }), guardian, nowMs),
1036
+ metricDays: metricDays(applyMetricBuckets(sumHoursIntoDays(activity, (day, hour) => {
1037
+ day.conversations += hour.conversations;
1038
+ }), sumHoursIntoDays(metrics, (day, hour) => {
1039
+ day.value += hour.value;
1040
+ }, (bucket) => bucket.metric), sumHoursIntoDays(outcomes, (day, hour) => {
1041
+ day.mergedCodeChangeCostUsd += hour.mergedCodeChangeCostUsd;
1042
+ day.mergedCodeChanges += hour.mergedCodeChanges;
1043
+ day.outcomeCostUsd += hour.outcomeCostUsd;
1044
+ day.outcomes += hour.outcomes;
1045
+ })), nowMs),
1046
+ metricHours: hours,
1047
+ metricSixHours: sumMetricHoursIntoSixHours(hours, nowMs),
1134
1048
  source: "conversation_index",
1135
- ...totals?.costUsd !== null && totals?.costUsd !== void 0 ? { costUsd: addUsd(void 0, totals.costUsd) } : void 0,
1136
- ...totals?.inputTokens !== null && totals?.inputTokens !== void 0 ? { inputTokens: totals.inputTokens } : void 0,
1137
- ...totals?.tokens !== null && totals?.tokens !== void 0 ? { tokens: totals.tokens } : void 0,
1138
1049
  windowEnd: end.toISOString(),
1139
1050
  windowStart: start.toISOString()
1140
1051
  };
1141
1052
  }
1142
1053
  // src/api/conversations/stats.ts
1143
- /** Load aggregate conversation stats directly from durable SQL records. */
1144
- async function readConversationStats() {
1145
- return conversationStatsReportSchema.parse(await readConversationStatsFromSql());
1054
+ const CACHE_NAMESPACE = "core";
1055
+ const CACHE_KEY = "conversation-stats";
1056
+ const FRESH_MS = 3e5;
1057
+ const KEEP_MS = 36e5;
1058
+ const RELOAD_WAIT_MS = 1e4;
1059
+ const cachedStatsSchema = z.object({
1060
+ refreshAtMs: z.number(),
1061
+ report: conversationStatsReportSchema
1062
+ }).strict();
1063
+ async function loadCachedStats() {
1064
+ const report = conversationStatsReportSchema.parse(await readConversationStatsFromSql());
1065
+ return {
1066
+ ttlMs: KEEP_MS,
1067
+ value: {
1068
+ refreshAtMs: Date.now() + FRESH_MS,
1069
+ report
1070
+ }
1071
+ };
1072
+ }
1073
+ /**
1074
+ * Reload the report under one lock. A caller that gets the lock after
1075
+ * another reload first reads the entry that it wrote.
1076
+ */
1077
+ async function reloadCachedStats(state, usable, waitMs) {
1078
+ const cache = createCache(state, CACHE_NAMESPACE);
1079
+ return await withLock(state, `${cacheKeyPrefix(CACHE_NAMESPACE)}${CACHE_KEY}:reload`, async () => {
1080
+ const current = cachedStatsSchema.safeParse(await cache.getOrLoad(CACHE_KEY, loadCachedStats));
1081
+ if (current.success && usable(current.data)) return current.data;
1082
+ return await cache.getOrLoad(CACHE_KEY, loadCachedStats, { refresh: true });
1083
+ }, { waitMs });
1084
+ }
1085
+ async function refreshCachedStats(state) {
1086
+ try {
1087
+ await reloadCachedStats(state, (stats) => Date.now() < stats.refreshAtMs, 0);
1088
+ } catch (error) {
1089
+ logException(error, "conversation_stats.refresh.failed");
1090
+ }
1091
+ }
1092
+ /**
1093
+ * Load aggregate conversation stats from durable SQL records. A cached report
1094
+ * is served for up to an hour. After five minutes, a request also starts a
1095
+ * background refresh.
1096
+ */
1097
+ async function readConversationStats(options) {
1098
+ const state = getStateAdapter();
1099
+ const cached = cachedStatsSchema.safeParse(await createCache(state, CACHE_NAMESPACE).getOrLoad(CACHE_KEY, loadCachedStats));
1100
+ let stats;
1101
+ if (cached.success) stats = cached.data;
1102
+ else {
1103
+ const reload = await reloadCachedStats(state, () => true, RELOAD_WAIT_MS);
1104
+ stats = reload.acquired ? reload.value : (await loadCachedStats()).value;
1105
+ }
1106
+ if (Date.now() >= stats.refreshAtMs) options.waitUntil(() => refreshCachedStats(state));
1107
+ return stats.report;
1146
1108
  }
1147
1109
  // src/api/conversations/watches.ts
1148
1110
  /**
@@ -1262,7 +1224,7 @@ function createConversationRoutes(options) {
1262
1224
  ...viewer ? { viewer } : void 0
1263
1225
  }));
1264
1226
  });
1265
- app.get("/stats", async () => jsonResponse(conversationStatsReportSchema, await readConversationStats()));
1227
+ app.get("/stats", async () => jsonResponse(conversationStatsReportSchema, await readConversationStats({ waitUntil: options.waitUntil })));
1266
1228
  app.post("/", requireViewer, messageBodyLimit, validateRequest("json", createConversationBodySchema, "Invalid request body."), async (context) => {
1267
1229
  const viewer = context.get("viewer");
1268
1230
  const body = context.req.valid("json");
@@ -2784,28 +2746,77 @@ function activityRows(since, unit) {
2784
2746
  }).from(turns).groupBy(turns.bucket);
2785
2747
  }
2786
2748
  /**
2749
+ * Read one row per verified person who ever ran a Turn: their identity and
2750
+ * their first and last Turn over all time. Each edge is a probe of the actor
2751
+ * index, so the cost grows with identities, not with Turns.
2752
+ */
2753
+ function personTurnRange() {
2754
+ const edge = (fn) => sql`(${getDb().select({ at: sql`${sql.raw(fn)}(${metrics.occurredAt})` }).from(metrics).where(eq(metrics.actorIdentityId, juniorIdentities.id))})`;
2755
+ return getDb().select({
2756
+ userId: sql`${juniorUsers.id}`.as("range_user_id"),
2757
+ email: sql`${juniorUsers.primaryEmailNormalized}`.as("range_email"),
2758
+ fullName: sql`${juniorUsers.displayName}`.as("range_full_name"),
2759
+ firstAt: sql`min(${edge("min")})`.as("range_first_at"),
2760
+ lastAt: sql`max(${edge("max")})`.as("range_last_at"),
2761
+ slackUserId: sql`max(CASE WHEN ${juniorIdentities.provider} = 'slack' THEN ${juniorIdentities.providerSubjectId} END)`.as("range_slack_user_id"),
2762
+ slackUserName: sql`max(CASE WHEN ${juniorIdentities.provider} = 'slack' THEN ${juniorIdentities.handle} END)`.as("range_slack_user_name")
2763
+ }).from(juniorIdentities).innerJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(and(verifiedActorWhere(), exists(getDb().select({ one: sql`1` }).from(metrics).where(eq(metrics.actorIdentityId, juniorIdentities.id))))).groupBy(juniorUsers.id).as("person_turn_range");
2764
+ }
2765
+ /**
2766
+ * Count each person's root Conversations with a Turn in each range. Only
2767
+ * Turns since the start of the longest range are read, and they are grouped
2768
+ * before any join.
2769
+ */
2770
+ function personRangeConversations(nowMs, since) {
2771
+ const verifiedIdentities = getDb().select({ id: juniorIdentities.id }).from(juniorIdentities).innerJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(verifiedActorWhere());
2772
+ const turns = getDb().select({
2773
+ identityId: sql`${metrics.actorIdentityId}`.as("recent_identity_id"),
2774
+ conversationId: sql`${metrics.conversationId}`.as("recent_conversation_id"),
2775
+ lastAt: sql`max(${metrics.occurredAt})`.as("recent_last_at")
2776
+ }).from(metrics).where(and(inArray(metrics.actorIdentityId, verifiedIdentities), eq(metrics.metric, "duration_ms"), gte(metrics.occurredAt, since))).groupBy(metrics.actorIdentityId, metrics.conversationId).as("person_recent_turns");
2777
+ const roots = getDb().select({
2778
+ userId: sql`${juniorIdentities.userId}`.as("recent_user_id"),
2779
+ lastAt: sql`max(${turns.lastAt})`.as("recent_root_last_at")
2780
+ }).from(turns).innerJoin(juniorIdentities, eq(juniorIdentities.id, turns.identityId)).innerJoin(juniorConversations, eq(juniorConversations.conversationId, turns.conversationId)).groupBy(juniorIdentities.userId, conversationRootId).as("person_recent_roots");
2781
+ const count = (range) => sql`(count(*) FILTER (
2782
+ WHERE ${roots.lastAt} >= ${rangeStart(nowMs, range).toISOString()}::timestamptz
2783
+ ))::integer`;
2784
+ return getDb().select({
2785
+ userId: sql`${roots.userId}`.as("range_count_user_id"),
2786
+ conversations1: count(1).as("range_conversations_1"),
2787
+ conversations7: count(7).as("range_conversations_7"),
2788
+ conversations30: count(30).as("range_conversations_30"),
2789
+ conversations90: count(90).as("range_conversations_90")
2790
+ }).from(roots).groupBy(roots.userId).as("person_range_conversations");
2791
+ }
2792
+ /**
2787
2793
  * Load the complete People directory with grouping and metrics owned by SQL.
2788
2794
  *
2789
2795
  * Every count and total comes from Turns. A person counts a Conversation when
2790
- * they ran a Turn in it, whoever started it.
2796
+ * they ran a Turn in it, whoever started it. Only the Turn range is
2797
+ * all-time; every other statement reads at most the last 180 days.
2791
2798
  */
2792
2799
  async function readPeopleListFromSql() {
2793
2800
  const nowMs = Date.now();
2794
2801
  const { end, start } = trailingUtcDayWindow(nowMs, DIRECTORY_ACTIVITY_DAYS);
2795
2802
  const hourWindow = trailingUtcHourWindow(nowMs, 168);
2796
2803
  const sixHourWindow = trailingUtcSixHourWindow(nowMs);
2797
- const roots = personRoots();
2798
- const rangeConversations = (range) => sql`(count(*) FILTER (
2799
- WHERE ${roots.lastAt} >= ${rangeStart(nowMs, range).toISOString()}::timestamptz
2800
- ))::integer`;
2804
+ const range = personTurnRange();
2805
+ const counts = personRangeConversations(nowMs, start);
2806
+ const rangeCount = (column) => sql`COALESCE(${column}, 0)::integer`;
2801
2807
  const [rows, activityDayRows, activityHourRows, activitySixHourRows, spend] = await Promise.all([
2802
2808
  getDb().select({
2803
- ...personTotalColumns(roots),
2804
- conversations1: rangeConversations(1),
2805
- conversations7: rangeConversations(7),
2806
- conversations30: rangeConversations(30),
2807
- conversations90: rangeConversations(90)
2808
- }).from(roots).innerJoin(juniorUsers, eq(juniorUsers.id, roots.userId)).innerJoin(turnRoot, personRootJoin(roots)).groupBy(juniorUsers.id),
2809
+ email: range.email,
2810
+ fullName: range.fullName,
2811
+ firstSeenAt: sql`${range.firstAt}`.mapWith(metrics.occurredAt),
2812
+ lastSeenAt: sql`${range.lastAt}`.mapWith(metrics.occurredAt),
2813
+ slackUserId: range.slackUserId,
2814
+ slackUserName: range.slackUserName,
2815
+ conversations1: rangeCount(counts.conversations1),
2816
+ conversations7: rangeCount(counts.conversations7),
2817
+ conversations30: rangeCount(counts.conversations30),
2818
+ conversations90: rangeCount(counts.conversations90)
2819
+ }).from(range).leftJoin(counts, eq(counts.userId, range.userId)),
2809
2820
  activityRows(start, "day"),
2810
2821
  activityRows(hourWindow.start, "hour"),
2811
2822
  activityRows(sixHourWindow.start, "six_hour"),
@@ -2827,11 +2838,6 @@ async function readPeopleListFromSql() {
2827
2838
  };
2828
2839
  const personSpend = spendByEmail.get(row.email);
2829
2840
  return {
2830
- active: row.active,
2831
- activeDays: row.activeDays,
2832
- conversations: row.conversations,
2833
- durationMs: row.durationMs,
2834
- failed: row.failed,
2835
2841
  firstSeenAt: row.firstSeenAt.toISOString(),
2836
2842
  lastSeenAt: row.lastSeenAt.toISOString(),
2837
2843
  actor,
@@ -2840,8 +2846,7 @@ async function readPeopleListFromSql() {
2840
2846
  7: rangeWindow(personSpend?.[7], row.conversations7),
2841
2847
  30: rangeWindow(personSpend?.[30], row.conversations30),
2842
2848
  90: rangeWindow(personSpend?.[90], row.conversations90)
2843
- },
2844
- ...row.tokens !== null ? { tokens: row.tokens } : void 0
2849
+ }
2845
2850
  };
2846
2851
  });
2847
2852
  return {
@@ -2849,7 +2854,7 @@ async function readPeopleListFromSql() {
2849
2854
  activityHours: directoryActivityHours(activityHourRows, nowMs),
2850
2855
  activitySixHours: directoryActivitySixHours(activitySixHourRows, nowMs),
2851
2856
  generatedAt: new Date(nowMs).toISOString(),
2852
- people: people.sort((left, right) => Date.parse(right.lastSeenAt) - Date.parse(left.lastSeenAt) || right.conversations - left.conversations || left.actor.email.localeCompare(right.actor.email)),
2857
+ people: people.sort((left, right) => Date.parse(right.lastSeenAt) - Date.parse(left.lastSeenAt) || right.windows[90].conversations - left.windows[90].conversations || left.actor.email.localeCompare(right.actor.email)),
2853
2858
  source: "conversation_index",
2854
2859
  windowEnd: end.toISOString(),
2855
2860
  windowStart: start.toISOString()
@@ -2870,7 +2875,7 @@ async function readPeoplePluginReports(args) {
2870
2875
  reports: [],
2871
2876
  source: "plugins"
2872
2877
  });
2873
- const { getPluginProfileReports } = await import("./projection-Bqn6zdVT.js").then((n) => n.Cn);
2878
+ const { getPluginProfileReports } = await import("./projection-Ce4pmhKP.js").then((n) => n.Cn);
2874
2879
  return pluginOperationalReportFeedSchema.parse({
2875
2880
  generatedAt: new Date(nowMs).toISOString(),
2876
2881
  reports: await getPluginProfileReports({
@@ -3309,7 +3314,7 @@ function requirePlugin(provider) {
3309
3314
  return plugin;
3310
3315
  }
3311
3316
  function callbackPage(title, message, status) {
3312
- return htmlCallbackResponse(escapeXml(title), escapeXml(message), status, { footerMessage: "You can close this tab and return to the dashboard." });
3317
+ return htmlCallbackResponse(escapeHtml(title), escapeHtml(message), status, { footerMessage: "You can close this tab and return to the dashboard." });
3313
3318
  }
3314
3319
  /**
3315
3320
  * Create admin-only routes that list, connect, and disconnect plugin service
@@ -3321,7 +3326,7 @@ function callbackPage(title, message, status) {
3321
3326
  */
3322
3327
  function createServiceAccountRoutes() {
3323
3328
  const app = new Hono();
3324
- app.get("/", requireAdmin, async () => jsonResponse(serviceAccountListSchema, { serviceAccounts: await Promise.all(serviceAccountPlugins(pluginCatalogRuntime.getProviders()).map(getServiceAccountStatus)) }));
3329
+ app.get("/", requireAdmin, async () => jsonResponse(serviceAccountListSchema, { serviceAccounts: await mapBounded(serviceAccountPlugins(pluginCatalogRuntime.getProviders()), getServiceAccountStatus) }));
3325
3330
  app.post("/:provider", requireAdmin, validateRequest("param", serviceAccountParamsSchema, "Invalid provider."), async (context) => {
3326
3331
  const { provider } = context.req.valid("param");
3327
3332
  const { authorizationUrl } = await startServiceAccountSignIn({
@@ -3370,31 +3375,35 @@ function netSavingsUsd(totals) {
3370
3375
  }
3371
3376
  /**
3372
3377
  * Read what cache warming saved on each of the last `days` UTC days, today
3373
- * included, and in total. Net savings and effectiveness leave out days filled
3374
- * from history: history has no warmup calls, so their warmup cost is unknown.
3378
+ * included, and in total. Days filled from history are marked: their saved
3379
+ * writes come from the replay and their warmup cost from the recorded warmup
3380
+ * calls.
3375
3381
  */
3376
3382
  async function readCacheWarmingSavings(days, nowMs = Date.now()) {
3377
3383
  const dates = Array.from({ length: days }, (_, index) => (/* @__PURE__ */ new Date(nowMs - (days - 1 - index) * DAY_MS)).toISOString().slice(0, 10));
3378
3384
  const stats = (await readStats(dates[0], dates.at(-1))).filter((stat) => stat.namespace === SAVINGS_NAMESPACE);
3379
- const unknownCostDates = new Set(dates.filter((date) => savingsTotals(stats.filter((stat) => stat.date === date)).historyDays > 0));
3380
- const known = savingsTotals(stats.filter((stat) => !unknownCostDates.has(stat.date)));
3381
- const knownNetSavingsUsd = netSavingsUsd(known);
3382
- const knownOracleSavingsUsd = microUsdToUsd(known.oracleSavingsMicroUsd);
3385
+ const dayTotals = dates.map((date) => ({
3386
+ date,
3387
+ totals: savingsTotals(stats.filter((stat) => stat.date === date))
3388
+ }));
3389
+ const historyDates = new Set(dayTotals.filter((day) => day.totals.historyDays > 0).map((day) => day.date));
3390
+ const all = savingsTotals(stats);
3391
+ const net = netSavingsUsd(all);
3392
+ const oracle = microUsdToUsd(all.oracleSavingsMicroUsd);
3393
+ const live = savingsTotals(stats.filter((stat) => !historyDates.has(stat.date)));
3383
3394
  return cacheWarmingSavingsReportSchema.parse({
3384
- days: dates.map((date) => {
3385
- const day = savingsTotals(stats.filter((stat) => stat.date === date));
3386
- return {
3387
- date,
3388
- ...savingsUsd(day),
3389
- netSavingsUsd: unknownCostDates.has(date) ? null : netSavingsUsd(day)
3390
- };
3391
- }),
3395
+ days: dayTotals.map(({ date, totals }) => ({
3396
+ date,
3397
+ ...savingsUsd(totals),
3398
+ netSavingsUsd: netSavingsUsd(totals),
3399
+ history: historyDates.has(date)
3400
+ })),
3392
3401
  totals: {
3393
- ...savingsUsd(savingsTotals(stats)),
3394
- netSavingsUsd: knownNetSavingsUsd,
3395
- knownCostOracleSavingsUsd: knownOracleSavingsUsd,
3396
- effectiveness: knownOracleSavingsUsd > 0 ? knownNetSavingsUsd / knownOracleSavingsUsd : null,
3397
- unknownCostDays: unknownCostDates.size
3402
+ ...savingsUsd(all),
3403
+ netSavingsUsd: net,
3404
+ liveOracleSavingsUsd: microUsdToUsd(live.oracleSavingsMicroUsd),
3405
+ effectiveness: oracle > 0 ? net / oracle : null,
3406
+ historyDays: historyDates.size
3398
3407
  }
3399
3408
  });
3400
3409
  }
@@ -3699,6 +3708,127 @@ function createUserCustomizationRoutes() {
3699
3708
  });
3700
3709
  return app;
3701
3710
  }
3711
+ // src/chat/review-items/related.ts
3712
+ const RELATED_ITEM_LIMIT = 10;
3713
+ const RELATED_CANDIDATE_LIMIT = 11;
3714
+ /** The linked Conversations of an item that point to other work. */
3715
+ function linkedWork(item) {
3716
+ return item.conversationIds.filter((id) => id !== item.addedByConversationId);
3717
+ }
3718
+ function openVisible(reader) {
3719
+ return and(eq(juniorReviewItems.status, "open"), reviewItemVisibleTo(reader));
3720
+ }
3721
+ /** Rank the candidates in each group, newest first. */
3722
+ function newestInGroup(group) {
3723
+ return sql`row_number() over (partition by ${group} order by ${juniorReviewItems.createdAt} desc, ${juniorReviewItems.id} desc)`;
3724
+ }
3725
+ const candidateColumns = {
3726
+ createdAt: juniorReviewItems.createdAt,
3727
+ id: juniorReviewItems.id,
3728
+ subjectId: juniorReviewItems.subjectId,
3729
+ subjectUrl: juniorReviewItems.subjectUrl,
3730
+ title: juniorReviewItems.title
3731
+ };
3732
+ /**
3733
+ * Read the related work of each open item in a page: the other open items
3734
+ * that the reader can see with the same subject id or URL, or linked to one
3735
+ * of the item's other linked Conversations, and those Conversations when the
3736
+ * viewer can see them. The reads cover the whole page at once, so the query
3737
+ * count does not grow with the page.
3738
+ */
3739
+ async function readRelatedReviewWork(db, reader, viewer, items) {
3740
+ const open = items.filter((item) => item.status === "open");
3741
+ const subjectIds = [...new Set(open.flatMap((item) => item.subject?.id ?? []))];
3742
+ const subjectUrls = [...new Set(open.flatMap((item) => item.subject?.url ?? []))];
3743
+ const linkIds = [...new Set(open.flatMap(linkedWork))];
3744
+ const subjectRanks = db.select({
3745
+ ...candidateColumns,
3746
+ idRank: newestInGroup(juniorReviewItems.subjectId).as("id_rank"),
3747
+ urlRank: newestInGroup(juniorReviewItems.subjectUrl).as("url_rank")
3748
+ }).from(juniorReviewItems).where(and(openVisible(reader), or(...subjectIds.length > 0 ? [inArray(juniorReviewItems.subjectId, subjectIds)] : [], ...subjectUrls.length > 0 ? [inArray(juniorReviewItems.subjectUrl, subjectUrls)] : []))).as("subject_ranks");
3749
+ const linkRanks = db.select({
3750
+ ...candidateColumns,
3751
+ conversationId: juniorReviewItemConversations.conversationId,
3752
+ rank: newestInGroup(juniorReviewItemConversations.conversationId).as("link_rank")
3753
+ }).from(juniorReviewItemConversations).innerJoin(juniorReviewItems, eq(juniorReviewItems.id, juniorReviewItemConversations.itemId)).where(and(inArray(juniorReviewItemConversations.conversationId, linkIds), openVisible(reader))).as("link_ranks");
3754
+ const [bySubject, byLink, access] = await Promise.all([
3755
+ subjectIds.length > 0 || subjectUrls.length > 0 ? db.select({
3756
+ createdAt: subjectRanks.createdAt,
3757
+ id: subjectRanks.id,
3758
+ subjectId: subjectRanks.subjectId,
3759
+ subjectUrl: subjectRanks.subjectUrl,
3760
+ title: subjectRanks.title
3761
+ }).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))] : [])) : [],
3762
+ linkIds.length > 0 ? db.select({
3763
+ conversationId: linkRanks.conversationId,
3764
+ createdAt: linkRanks.createdAt,
3765
+ id: linkRanks.id,
3766
+ subjectId: linkRanks.subjectId,
3767
+ subjectUrl: linkRanks.subjectUrl,
3768
+ title: linkRanks.title
3769
+ }).from(linkRanks).where(lte(linkRanks.rank, RELATED_CANDIDATE_LIMIT)) : [],
3770
+ readConversationAccessFromSql(db, linkIds, viewer)
3771
+ ]);
3772
+ const related = /* @__PURE__ */ new Map();
3773
+ for (const item of open) {
3774
+ const links = new Set(linkedWork(item));
3775
+ const matches = /* @__PURE__ */ new Map();
3776
+ 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);
3777
+ for (const candidate of byLink) if (links.has(candidate.conversationId)) matches.set(candidate.id, candidate);
3778
+ matches.delete(item.id);
3779
+ related.set(item.id, {
3780
+ conversationIds: [...links].filter((id) => access.get(id)?.canViewPrivateContent === true),
3781
+ 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 }) => ({
3782
+ id,
3783
+ title
3784
+ }))
3785
+ });
3786
+ }
3787
+ return related;
3788
+ }
3789
+ // src/api/review-items/item-roots.ts
3790
+ /** Name a child with no title by its kind: "Thread" or "Task". */
3791
+ function kindLabel(kind) {
3792
+ return kind ? `${kind[0].toUpperCase()}${kind.slice(1)}` : "Child agent";
3793
+ }
3794
+ /**
3795
+ * Read the root of each Conversation that added an item, at any depth, from
3796
+ * the root that each Conversation stores, with a label for a child, such as
3797
+ * its Thread title. A root needs no read. A child is left out when the
3798
+ * viewer cannot see its root's content, so the viewer learns no root,
3799
+ * title, or name of a tree they cannot see
3800
+ * (`policies/conversation-access.md`, rule for people). The payload then
3801
+ * names the Conversation that added the item as its root.
3802
+ */
3803
+ async function readItemRoots(db, items, viewer) {
3804
+ const ids = [...new Set(items.flatMap((item) => item.addedByRootConversationId === null || item.addedByRootConversationId === item.addedByConversationId ? [] : [item.addedByConversationId]))];
3805
+ if (ids.length === 0) return /* @__PURE__ */ new Map();
3806
+ const children = await db.select({
3807
+ bindingName: juniorAgentBindings.name,
3808
+ conversationId: juniorConversations.conversationId,
3809
+ kind: juniorConversations.kind,
3810
+ title: juniorConversations.title
3811
+ }).from(juniorConversations).leftJoin(juniorAgentBindings, eq(juniorAgentBindings.childConversationId, juniorConversations.conversationId)).where(and(inArray(juniorConversations.conversationId, ids), isNotNull(juniorConversations.parentConversationId)));
3812
+ if (children.length === 0) return /* @__PURE__ */ new Map();
3813
+ const childIds = children.map((child) => child.conversationId);
3814
+ const [access, invocations] = await Promise.all([readConversationAccessFromSql(db, childIds, viewer), db.selectDistinctOn([juniorAgentInvocations.childConversationId], {
3815
+ agentName: juniorAgentInvocations.agentName,
3816
+ childConversationId: juniorAgentInvocations.childConversationId,
3817
+ title: juniorAgentInvocations.title
3818
+ }).from(juniorAgentInvocations).where(inArray(juniorAgentInvocations.childConversationId, childIds)).orderBy(juniorAgentInvocations.childConversationId, sql`${juniorAgentInvocations.title} is null`, desc(juniorAgentInvocations.createdAt))]);
3819
+ const invocationByChild = new Map(invocations.map((row) => [row.childConversationId, row]));
3820
+ return new Map(children.flatMap((child) => {
3821
+ const childAccess = access.get(child.conversationId);
3822
+ const rootConversationId = childAccess?.rootConversationId;
3823
+ if (!rootConversationId || !childAccess.canViewPrivateContent) return [];
3824
+ const invocation = invocationByChild.get(child.conversationId);
3825
+ const label = invocation?.title ?? invocation?.agentName ?? child.title ?? child.bindingName ?? kindLabel(child.kind);
3826
+ return [[child.conversationId, {
3827
+ label,
3828
+ rootConversationId
3829
+ }]];
3830
+ }));
3831
+ }
3702
3832
  // src/api/review-items/routes.ts
3703
3833
  const ARCHIVED_LIMIT = 50;
3704
3834
  const cursorSchema = z.object({
@@ -3753,9 +3883,11 @@ function subjectPayload(subject) {
3753
3883
  };
3754
3884
  }
3755
3885
  /** Build the API payload of one Review item for its viewer. */
3756
- function reviewItemPayload(item, viewer) {
3886
+ function reviewItemPayload(item, viewer, roots, related) {
3887
+ const root = roots.get(item.addedByConversationId);
3757
3888
  return {
3758
3889
  addedByConversationId: item.addedByConversationId,
3890
+ ...root ? { addedByLabel: root.label } : void 0,
3759
3891
  assignedToEveryone: item.assignedToEveryone,
3760
3892
  assignees: item.assignees,
3761
3893
  body: item.body,
@@ -3765,6 +3897,7 @@ function reviewItemPayload(item, viewer) {
3765
3897
  createdAt: item.createdAt.toISOString(),
3766
3898
  id: item.id,
3767
3899
  kind: item.kind,
3900
+ rootConversationId: root?.rootConversationId ?? item.addedByConversationId,
3768
3901
  status: item.status,
3769
3902
  title: item.title,
3770
3903
  updatedAt: item.updatedAt.toISOString(),
@@ -3775,10 +3908,20 @@ function reviewItemPayload(item, viewer) {
3775
3908
  ...item.closeReason ? { closeReason: item.closeReason } : void 0,
3776
3909
  ...item.closedAt ? { closedAt: item.closedAt.toISOString() } : void 0,
3777
3910
  ...item.closedBy ? { closedBy: item.closedBy } : void 0,
3911
+ ...related && (related.items.length > 0 || related.conversationIds.length > 0) ? { related } : void 0,
3778
3912
  ...item.request ? { request: item.request } : void 0,
3779
3913
  ...item.subject ? { subject: subjectPayload(item.subject) } : void 0
3780
3914
  };
3781
3915
  }
3916
+ /**
3917
+ * Build the payloads of a page of items, with the root of each one and the
3918
+ * related work of the open ones. Each read covers the page.
3919
+ */
3920
+ async function reviewItemPayloads(items, viewer, reader) {
3921
+ const db = getDb();
3922
+ const [roots, related] = await Promise.all([readItemRoots(db, items, viewer), readRelatedReviewWork(db, reader, viewer, items)]);
3923
+ return items.map((item) => reviewItemPayload(item, viewer, roots, related.get(item.id)));
3924
+ }
3782
3925
  function actionErrorResponse(error) {
3783
3926
  if (error instanceof ReviewItemActionError) return jsonResponse(apiErrorSchema, { error: error.message }, { status: ERROR_STATUS[error.code] });
3784
3927
  throw error;
@@ -3812,7 +3955,7 @@ function createReviewItemRoutes(services) {
3812
3955
  const page = closed.slice(0, query.limit);
3813
3956
  const last = page.at(-1);
3814
3957
  return jsonResponse(reviewItemListSchema, {
3815
- items: page.map((item) => reviewItemPayload(item, viewer)),
3958
+ items: await reviewItemPayloads(page, viewer, reader),
3816
3959
  ...closed.length > query.limit && last ? { nextCursor: encodeCursor(last, filters, viewer) } : void 0
3817
3960
  });
3818
3961
  }
@@ -3839,7 +3982,7 @@ function createReviewItemRoutes(services) {
3839
3982
  const page = open.slice(0, query.limit);
3840
3983
  const last = page.at(-1);
3841
3984
  return jsonResponse(reviewItemListSchema, {
3842
- items: [...page, ...archived.slice(0, ARCHIVED_LIMIT)].map((item) => reviewItemPayload(item, viewer)),
3985
+ items: await reviewItemPayloads([...page, ...archived.slice(0, ARCHIVED_LIMIT)], viewer, reader),
3843
3986
  ...archived.length > ARCHIVED_LIMIT ? { moreArchived: true } : void 0,
3844
3987
  ...open.length > query.limit && last ? { nextCursor: encodeCursor(last, filters, viewer) } : void 0
3845
3988
  });
@@ -3880,8 +4023,8 @@ function createReviewItemRoutes(services) {
3880
4023
  app.get("/:id", requireViewer, validateRequest("param", reviewItemParamsSchema, "Invalid review item."), async (context) => {
3881
4024
  const viewer = context.get("viewer");
3882
4025
  try {
3883
- const item = await readReviewItemForUser(viewer, context.req.valid("param").id);
3884
- return jsonResponse(reviewItemSchema, reviewItemPayload(item, viewer));
4026
+ const [payload] = await reviewItemPayloads([await readReviewItemForUser(viewer, context.req.valid("param").id)], viewer, reviewItemReaderForUser(viewer));
4027
+ return jsonResponse(reviewItemSchema, payload);
3885
4028
  } catch (error) {
3886
4029
  return actionErrorResponse(error);
3887
4030
  }
@@ -3891,7 +4034,7 @@ function createReviewItemRoutes(services) {
3891
4034
  const body = context.req.valid("json");
3892
4035
  const { id } = context.req.valid("param");
3893
4036
  try {
3894
- const item = await actOnReviewItem({
4037
+ const [payload] = await reviewItemPayloads([await actOnReviewItem({
3895
4038
  action: body.action,
3896
4039
  delivery: services.delivery,
3897
4040
  id,
@@ -3900,8 +4043,8 @@ function createReviewItemRoutes(services) {
3900
4043
  ...body.answer,
3901
4044
  requestId: id
3902
4045
  } } : void 0
3903
- });
3904
- return jsonResponse(reviewItemSchema, reviewItemPayload(item, viewer));
4046
+ })], viewer, reviewItemReaderForUser(viewer));
4047
+ return jsonResponse(reviewItemSchema, payload);
3905
4048
  } catch (error) {
3906
4049
  return actionErrorResponse(error);
3907
4050
  }
@@ -4055,7 +4198,7 @@ function readDescriptionText(home) {
4055
4198
  }
4056
4199
  /** Read discovered skills for runtime diagnostics and the Automation editor. */
4057
4200
  async function readSkillReports() {
4058
- const { discoverSkills } = await import("./skills-Dm2-5nn5.js").then((n) => n.o);
4201
+ const { discoverSkills } = await import("./skills-Zg8-vrje.js").then((n) => n.o);
4059
4202
  const skills = await discoverSkills();
4060
4203
  return skillReportsSchema.parse(skills.map((skill) => ({
4061
4204
  name: skill.name,
@@ -4069,7 +4212,7 @@ async function readSkillReports() {
4069
4212
  * what the skill tells Junior. Returns null when no skill has that name.
4070
4213
  */
4071
4214
  async function readSkillDetailReport(name) {
4072
- const { discoverSkills, findSkillByName, parseSkillFile } = await import("./skills-Dm2-5nn5.js").then((n) => n.o);
4215
+ const { discoverSkills, findSkillByName, parseSkillFile } = await import("./skills-Zg8-vrje.js").then((n) => n.o);
4073
4216
  const skill = findSkillByName(name, await discoverSkills());
4074
4217
  if (!skill) return null;
4075
4218
  const parsed = parseSkillFile(await fs.readFile(path.join(skill.skillPath, "SKILL.md"), "utf8"), skill.name);
@@ -4084,7 +4227,7 @@ async function readSkillDetailReport(name) {
4084
4227
  }
4085
4228
  /** Read safe configured plugin metadata for authenticated runtime diagnostics. */
4086
4229
  async function readPlugins() {
4087
- const { pluginCatalogRuntime } = await import("./catalog-runtime-q9AJjuUN.js").then((n) => n.t);
4230
+ const { pluginCatalogRuntime } = await import("./catalog-runtime-Chc_IP2o.js").then((n) => n.t);
4088
4231
  return pluginsSchema.parse(pluginCatalogRuntime.getProviders().map((plugin) => ({
4089
4232
  configKeys: plugin.manifest.configKeys ?? [],
4090
4233
  description: plugin.manifest.description,
@@ -4095,8 +4238,8 @@ async function readPlugins() {
4095
4238
  /** Read authenticated runtime discovery data. */
4096
4239
  async function readRuntimeInfoReport() {
4097
4240
  const [{ homeDir }, { pluginCatalogRuntime }, plugins, skills] = await Promise.all([
4098
- import("./package-discovery-x4AvVhMj.js").then((n) => n.r),
4099
- import("./catalog-runtime-q9AJjuUN.js").then((n) => n.t),
4241
+ import("./package-discovery-DD9vencX.js").then((n) => n.r),
4242
+ import("./catalog-runtime-Chc_IP2o.js").then((n) => n.t),
4100
4243
  readPlugins(),
4101
4244
  readSkillReports()
4102
4245
  ]);
@@ -4113,7 +4256,7 @@ async function readRuntimeInfoReport() {
4113
4256
  /** Read sanitized operational summaries contributed by plugins. */
4114
4257
  async function readPluginOperationalReportFeed() {
4115
4258
  const nowMs = Date.now();
4116
- const { getPluginOperationalReports } = await import("./projection-Bqn6zdVT.js").then((n) => n.Cn);
4259
+ const { getPluginOperationalReports } = await import("./projection-Ce4pmhKP.js").then((n) => n.Cn);
4117
4260
  return pluginOperationalReportFeedSchema.parse({
4118
4261
  source: "plugins",
4119
4262
  generatedAt: new Date(nowMs).toISOString(),
@@ -4139,7 +4282,8 @@ function createJuniorApi(options = {}) {
4139
4282
  const queue = options.conversationWorkQueue ?? getVercelConversationWorkQueue();
4140
4283
  app.route("/api/conversations", createConversationRoutes({
4141
4284
  attachmentStorage: getAttachmentStorage(),
4142
- queue
4285
+ queue,
4286
+ waitUntil: options.waitUntil ?? ((task) => waitUntil(typeof task === "function" ? task() : task))
4143
4287
  }));
4144
4288
  app.route("/api/review-items", createReviewItemRoutes({ delivery: {
4145
4289
  queue,