@sentry/junior 0.310.0 → 0.311.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.
- package/dist/adapter-B1wujchl.js +259 -0
- package/dist/{adapter-context-BhKpjpGD.js → adapter-context-G2M0y6rP.js} +2 -2
- package/dist/{admin-tgZEZAk2.js → admin-DCiBhUT1.js} +1 -2
- package/dist/{agent-runner-D9cvNlQl.js → agent-runner-BVHPUIc8.js} +543 -1703
- package/dist/api/schema.d.ts +2 -2
- package/dist/api/schema.js +7 -6
- package/dist/api.d.ts +21 -3
- package/dist/api.js +1479 -372
- package/dist/{app-B_7Wn0en.d.ts → app-Cw5Vy6H6.d.ts} +14 -3
- package/dist/app.d.ts +2 -2
- package/dist/app.js +232 -506
- package/dist/{background-compaction-queue-BGHqkhkY.js → background-compaction-queue-CJDnWVOJ.js} +4 -4
- package/dist/{briefs-DKxkoruh.js → briefs-BDjnug6Y.js} +3 -3
- package/dist/{catalog-runtime-BxwzbLKY.js → catalog-runtime-DMY3VV-D.js} +1 -1
- package/dist/cli/chat.js +16 -16
- package/dist/cli/check.js +23 -29
- package/dist/cli/init.js +1 -6
- package/dist/cli/main.js +3 -3
- package/dist/cli/plugins.js +8 -7
- package/dist/cli/snapshot-create.js +5 -5
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +3 -3
- package/dist/{config-Dkt2Le2b.js → config-BrXDQefC.js} +239 -5
- package/dist/{continue-in-slack-BWVwePKD.js → continue-in-slack-DNXSC9So.js} +6 -5
- package/dist/{conversation-M9KZ5JxF.js → conversation-ca__NDQW.js} +47 -8
- package/dist/{conversation-feed-Ci6YD1N-.js → conversation-feed-DkinDu5o.js} +15 -6
- package/dist/{conversation-privacy-C39g8BY4.js → conversation-privacy-DxttrKb9.js} +1 -1
- package/dist/{conversation-turn-CBlZIH02.js → conversation-turn-DWw7Xhdr.js} +41 -38
- package/dist/{credential-sync-vGnrB0BY.js → credential-sync-Bk8wGb8Y.js} +15 -16
- package/dist/{db-B4Hjxr-u.d.ts → db-7ETESH44.d.ts} +3 -1
- package/dist/{db-CFZggNoy.js → db-DTxzH7u5.js} +1609 -1040
- package/dist/{executor-BPkZDx5-.js → executor-DqTiYj9S.js} +450 -99
- package/dist/{html-2r2KmLwi.js → html-B9Sl4Axb.js} +6 -6
- package/dist/{install-C-oE6C_u.js → install-Sg4ePfLl.js} +2 -2
- package/dist/instrumentation.js +3 -3
- package/dist/{lineage-CsvrEFQe.js → lineage-BHAMpNKr.js} +2 -2
- package/dist/{logging-D5gkyvnK.js → logging-FjclQsXu.js} +47 -9
- package/dist/{message-DwvJ-I3w.js → message-CJ7_RL50.js} +5 -8
- package/dist/{model-input-MAq2881y.js → model-input-CMLh4Cwq.js} +3 -3
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +3 -3
- package/dist/{oauth-callback-server-DIF6Li06.js → oauth-callback-server-RVcbiDjL.js} +2 -2
- package/dist/{oauth-relay-DPE-wrwO.js → oauth-relay-Bu9kkaQu.js} +1 -1
- package/dist/{projection-jZSlEAXG.js → projection-Cns7XwWa.js} +9445 -5574
- package/dist/{prompt-CaMyeCpA.js → prompt-CDqcsDYC.js} +4 -4
- package/dist/{registry-BBkWFCl8.js → registry-BPwuOP2O.js} +5 -8
- package/dist/{resolve-B38MkHXE.js → resolve-BK29bBry.js} +3 -3
- package/dist/rule-DAxQY-1h.js +20 -0
- package/dist/{runner-11h8PrHh.js → runner-BcAE-cJm.js} +10 -10
- package/dist/{sandbox-egress-signals-CTcACAtJ.js → sandbox-egress-signals-C-q0go5b.js} +1 -1
- package/dist/{schedule-DWxZ3kja.js → schedule-BLJ476XQ.js} +209 -43
- package/dist/{schema-obw5jvR4.js → schema-BLgSZXcL.js} +255 -49
- package/dist/{schema-DriSvB40.d.ts → schema-DYcJeV7d.d.ts} +701 -62
- package/dist/{service-account-Zc5bUcIJ.js → service-account-gN0zqf0S.js} +68 -68
- package/dist/{service-account-Bx93N1n1.js → service-account-iJoCtkHR.js} +3 -3
- package/dist/{skills-C8Npu5zO.js → skills-BoZ80epJ.js} +2 -2
- package/dist/{slack-conversation-unfurl-DlRVA02H.js → slack-conversation-unfurl-CogYrITA.js} +8 -10
- package/dist/{spawn-CXr58R0x.js → spawn-Dk92r7mX.js} +5 -6
- package/dist/{state-CGrGVeQC.js → state-DH3Cmgp3.js} +4 -4
- package/dist/{stop-DYzjRf2U.js → stop-CYsfc0Ed.js} +1063 -313
- package/dist/{store-D4FQ1Nml.js → store-DmmMIrQi.js} +5 -5
- package/dist/{task-queue-CaZffYaH.js → task-queue-C_zldF5J.js} +3 -3
- package/dist/{task-runner-Dm7BHbGp.js → task-runner-C7oCJQIx.js} +20 -13
- package/dist/{thread-context-Dyj1KWaY.js → thread-context-BW2BsQbH.js} +13 -11
- package/dist/{turn-session-routing-CD0BRCex.js → turn-session-routing-Xh_2nSQe.js} +52 -54
- package/dist/{validation-DxVNIxA0.js → validation-DrJd0nnq.js} +1 -1
- package/dist/{version-Cr7Z71yG.js → version-CNKZ8owc.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{warmup-C6LOZ2d2.js → warmup-BWdHew2H.js} +14287 -7195
- package/dist/{web-message-id-BT8Mg8LL.js → web-message-id-Ch5dPq-a.js} +32 -144
- package/dist/{worker-CUBtu1Li.js → worker-t9qpu_Zx.js} +7 -8
- package/migrations/0126_artifact_drop_public.sql +8 -0
- package/migrations/0127_artifact_path.sql +4 -0
- package/migrations/0128_artifact_path_index.sql +1 -0
- package/migrations/0129_review_item_answered_index.sql +1 -0
- package/migrations/0130_review_item_status_index.sql +1 -0
- package/migrations/0131_brief_outcome_status.sql +1 -0
- package/migrations/0132_brief_outcome_status_backfill.sql +7 -0
- package/migrations/0133_brief_created_at_index.sql +1 -0
- package/migrations/0134_slack_person_search_index.sql +1 -0
- package/migrations/0135_code_change_size.sql +3 -0
- package/migrations/0136_merge_conflict_notice_dismiss.sql +16 -0
- package/migrations/0137_inbox_snoozes.sql +27 -0
- package/migrations/0138_code_change_search_index.sql +2 -0
- package/migrations/0139_review_item_owner.sql +22 -0
- package/migrations/0140_review_item_owner_index.sql +1 -0
- package/migrations/0141_memory_core_adoption.sql +89 -0
- package/migrations/0142_memory_core_indexes.sql +17 -0
- package/migrations/meta/0126_snapshot.json +5488 -0
- package/migrations/meta/0127_snapshot.json +5519 -0
- package/migrations/meta/0128_snapshot.json +5519 -0
- package/migrations/meta/0129_snapshot.json +5547 -0
- package/migrations/meta/0130_snapshot.json +5563 -0
- package/migrations/meta/0131_snapshot.json +5569 -0
- package/migrations/meta/0132_snapshot.json +5569 -0
- package/migrations/meta/0133_snapshot.json +5590 -0
- package/migrations/meta/0134_snapshot.json +5606 -0
- package/migrations/meta/0135_snapshot.json +5624 -0
- package/migrations/meta/0136_snapshot.json +5624 -0
- package/migrations/meta/0137_snapshot.json +5864 -0
- package/migrations/meta/0138_snapshot.json +5894 -0
- package/migrations/meta/0139_snapshot.json +5898 -0
- package/migrations/meta/0140_snapshot.json +5919 -0
- package/migrations/meta/0141_snapshot.json +6429 -0
- package/migrations/meta/0142_snapshot.json +6457 -0
- package/migrations/meta/_journal.json +120 -1
- package/package.json +6 -7
- package/dist/result-BaqSZcJb.js +0 -548
- package/dist/session-stop-BfY4rhJs.js +0 -4255
- package/dist/turn-user-message-9IxeEv5v.js +0 -364
- package/dist/users-CaUAYMb3.js +0 -181
- package/dist/viewer-AHldghAD.js +0 -212
package/dist/api.js
CHANGED
|
@@ -1,37 +1,37 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { C as
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import { $ as
|
|
6
|
-
import { S as
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import { A as actOnReviewItem,
|
|
10
|
-
import { d as completeText, n as briefEntriesFromReportEvents } from "./prompt-
|
|
11
|
-
import { A as
|
|
12
|
-
import { _ as runBestEffort, h as logWarn, m as logInfo, p as logException } from "./logging-
|
|
13
|
-
import { t as runWithSlackInstallation } from "./adapter-context-
|
|
14
|
-
import { A as
|
|
15
|
-
import { i as continueConversationInSlack, r as canContinueInSlack, t as BUSY } from "./continue-in-slack-
|
|
1
|
+
import { B as withLock, F as createCache, M as readServedProviders, N as saveEnabledProviders, P as cacheKeyPrefix, _t as getAttachmentStorage, j as readEnabledProviders, n as botConfig } from "./config-BrXDQefC.js";
|
|
2
|
+
import { A as sumUtcHoursIntoSixHours, C as apiErrorSchema, D as fillUtcHours, E as fillUtcDays, M as trailingUtcHourWindow, N as trailingUtcSixHourWindow, O as fillUtcSixHours, P as utcHourKey, S as CONTENT_VERSION_HEADER, T as HOUR_MS$3, d as INLINE_VIDEO_TYPES, f as INPUT_IMAGE_TYPES, g as userCustomizationSchema, j as trailingUtcDayWindow, k as startOfUtcHour, p as detectImageMediaType, w as DAY_MS$3, x as isOpenPlanItemStatus } from "./web-message-id-Ch5dPq-a.js";
|
|
3
|
+
import { $ as conversationKindFromRow, Ct as reviewItemReaderForUser, G as conversationAggregateColumns, Gt as readAvatarFetch, H as microUsdSql, J as conversationIsActiveSql, K as conversationRangeColumns, Kt as readUserAvatarUrls, Mn as nextDetailVersion, Rt as readViewerAvatarUrl, Sn as rootVisibleToViewer, Tt as reviewItemVisibleTo, U as microUsdToUsd, Ut as identityAvatarUrl, Vt as updateViewerDisplayName, X as conversationTurnFailedSql, Y as conversationStatusSql, _n as readableSlackTeamId, a as getConversationStore, b as loadConversationSlackTenantIds, dt as itemNeedsUser, gt as reviewItemForUser, hn as readConversationAccessFromSql, it as canActOnReviewItem, jt as findUserByEmail, lt as isOnlyAssignee, mn as createConversationAccessReader, o as getDb, q as conversationUsageCostExpr, s as getSqlExecutor, st as canUserReadReviewItem, w as withConversationMutationLock, wt as reviewItemReaderForUserInConversation, zt as resolveViewerUser } from "./db-DTxzH7u5.js";
|
|
4
|
+
import { Bt as AttachmentUploadError, Ci as throwApiError, D as closeBreaker, E as breakerStates, Ga as readViewerAutomationRuns, Ha as ViewerTaskNotFoundError, Ht as createAttachmentUpload, Ja as readViewerAutomations, Jt as listOwnedWatches, Ka as readViewerAutomationSummary, La as changeViewerAutomationLifecycle, Mt as acceptsWebMessages, O as connectedState, P as readStats, Pa as activateViewerAutomationVersion, Ra as deleteViewerTask, Rt as webActorFromUser, Si as jsonResponse, St as archiveConversation, T as savingsTotals, Tt as reportConversationRead, Va as updateViewerAutomation, Wa as readViewerAutomationExecutions, Wt as writeAttachmentUpload, Yt as listChildAgents, bi as setConversationSubscription, di as addConversationNote, dn as parseEmail, li as listPlanItems, ln as isAllowedDomain, oa as isExperimentalFeatureEnabled, oi as readUserCustomization, qa as readViewerAutomationVersions, si as saveUserCustomization, to as AutomationEditError, ui as setPlanItemStatusByUser, xi as emptyResponse, y as SAVINGS_NAMESPACE, yi as inviteToConversation, za as readViewerAutomationEdit } from "./warmup-BWdHew2H.js";
|
|
5
|
+
import { $ as MAX_ATTACHMENT_BYTES, C as createConversationMessageBodySchema, G as conversationReadPositionSchema, S as createConversationBodySchema, T as forkConversationResponseSchema, U as renameConversationBodySchema, W as renameConversationResponseSchema, 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-ca__NDQW.js";
|
|
6
|
+
import { $ as peopleSearchQuerySchema, A as cacheHealthReportSchema, At as codeRepositoryQuerySchema, Bt as conversationWatchesReportSchema, C as inboxSnoozeResourceQuerySchema, Ct as codeChangeSearchQuerySchema, D as gatewayProvidersSchema, Dt as codeOverviewReportSchema, E as inboxSnoozeSubjectSchema, F as cacheWarmingSavingsReportSchema, Ft as conversationPlanItemSchema, Gt as continueConversationInSlackResponseSchema, H as createPersonalTokenBodySchema, I as closeCacheWarmingBreakerResponseSchema, It as conversationPlanReportSchema, Jt as attachObjectLinkResponseSchema, K as personalTokenParamsSchema, L as disconnectServiceAccountResponseSchema, Lt as planItemParamsSchema, M as cacheWarmingBreakerParamsSchema, N as cacheWarmingSavingsQuerySchema, O as updateGatewayProvidersBodySchema, Ot as codePersonReportSchema, P as cacheWarmingSavingsRefillResponseSchema, Pt as personCodeQuerySchema, Qt as conversationStatsReportSchema, R as serviceAccountListSchema, Rt as planItemStatusBodySchema, S as inboxSnoozeCreateSchema, T as inboxSnoozeSchema, U as createdPersonalTokenSchema, Ut as conversationChildAgentsReportSchema, V as startServiceAccountSignInResponseSchema, Vt as watchParamsSchema, W as personalTokenListSchema, Wt as continueConversationInSlackBodySchema, X as actorProfileReportSchema, Xt as objectLinksReportSchema, Y as actorDirectoryReportSchema, Yt as objectLinksQuerySchema, Z as avatarParamsSchema, Zt as stopConversationTurnResponseSchema, _ as reviewItemListSchema, _n as attachmentUploadParamsSchema, _t as connectionParamsSchema, a as statsReportSchema, an as conversationInviteBodySchema, at as locationDetailReportSchema, b as reviewItemWaitingConversationsSchema, bt as startConnectionResponseSchema, c as workspaceBodySchema, cn as conversationSubscriptionResponseSchema, ct as activityDays$1, dn as pinConversationBodySchema, en as conversationOutlineSchema, et as peopleSearchReportSchema, f as workspaceSchema, fn as pinConversationResponseSchema, ft as notificationSettingsSchema, g as reviewItemListQuerySchema, gn as conversationCatchUpSchema, gt as connectionListSchema, h as reviewItemCountSchema, hn as conversationCatchUpBodySchema, ht as testNotificationResponseSchema, in as conversationAutoArchiveSchema, j as cacheWarmingBreakerListSchema, jt as codeRepositoryReportSchema, k as cacheHealthQuerySchema, kt as codeRepositoryParamsSchema, l as workspaceListSchema, ln as conversationDeliveryBodySchema, lt as activityHours$2, m as reviewItemCountQuerySchema, mn as reorderPinnedConversationsResponseSchema, mt as pushSubscriptionDeleteBodySchema, n as versionsQuerySchema, nn as archiveConversationResponseSchema, nt as personParamsSchema, on as conversationInviteResponseSchema, ot as locationDirectoryReportSchema, p as reviewItemActionSchema, pn as reorderPinnedConversationsBodySchema, pt as pushSubscriptionBodySchema, q as revokePersonalTokenResponseSchema, qt as attachObjectLinkBodySchema, r as versionsSchema, rn as archiveDoneConversationsResponseSchema, rt as personalSpendReportSchema, s as deleteWorkspaceResponseSchema, sn as conversationSubscriptionBodySchema, st as locationParamsSchema, tn as archiveConversationBodySchema, tt as personCardReportSchema, u as workspaceParamsSchema, un as conversationDeliveryResponseSchema, ut as activitySixHours$1, v as reviewItemParamsSchema, vn as attachmentUploadSchema, w as inboxSnoozeResourceSchema, wt as codeChangeSearchReportSchema, y as reviewItemSchema, yn as createAttachmentUploadBodySchema, yt as disconnectConnectionResponseSchema, z as serviceAccountParamsSchema } from "./schema-BLgSZXcL.js";
|
|
7
|
+
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-DkinDu5o.js";
|
|
8
|
+
import { Aa as readConversationBriefThrough, Ai as hash, Bo as postSlackMessage, Ci as updateWorkspace, Cn as createUserTokenStore, Da as createPluginLogger, Gc as snoozeTimerTrigger, Gn as resolveNotificationTimezone, Hc as reviewItemSnoozedBy, In as getPlugins, Ja as readLiveAttachment, Jn as readNotificationSchedule, Kc as unsnoozeInboxRow, Kn as deletePushSubscription, Ln as getRegistrations, Ma as readConversationEventPage, Mc as ownerConversationId, Ms as getDashboardPersonLink, Nc as reviewItemsNeedingUserVersionQuery, Oc as getReviewItem, Pc as searchReviewItems, Ps as getDashboardSettingsLink, Si as listWorkspacesByRepository, Tc as countReviewItemsNeedingUserBySubject, Ua as readSlackAttachmentSource, Uc as settleInboxSnoozes, Un as readWebPushConfig, V as createPluginEgress, Vc as reviewItemInRow, Vn as apiRoutePrefix, Wc as snoozeInboxItems, Wn as sendPushNotificationToUser, Xn as savePushSubscription, Yn as saveNotificationSchedule, Yr as cancelWatch, Zn as isPausedBySlack, _i as createWorkspace, al as automationEventCatalog, bl as createPluginCache, co as listConversationAnnotations, ds as formatSlackLink, hc as readAutomationTitlesByConversationId, jc as listWaitingConversations, ki as create, ks as getDashboardConversationLink, la as workspaceRepoCheckoutPath, ll as eventWatchUnavailable, qc as getEventCatalog, qn as listPushSubscriptions, rc as AutomationConflictError, sa as SANDBOX_RUNTIME, so as createPluginAnnotations, us as escapeSlackMrkdwnText, vi as deleteWorkspace, wi as WorkspaceValidationError, xi as listWorkspaces, yi as getWorkspace } from "./projection-Cns7XwWa.js";
|
|
9
|
+
import { A as actOnReviewItem, At as conversationRecordJoins, B as readUserSettings, D as resolveMentions, E as requireConversationPendingMessages, Ft as IMAGE_WIDTHS, I as archiveViewerDoneConversations, It as decodeImageId, J as scheduleInboxSnoozeTimer, M as readReviewItemForUser, Mt as conversationSummaryFromStoredConversation, Nt as readFirstHumanMessageTexts, Pt as createViewerMcp, R as setConversationAutoArchive, V as updateUserSettings, Y as readSavingsRefill, Z as startSavingsRefill, _ as keepQuickQuestionForViewer, a as decodePageCursor, at as resolveObjectLinks, b as createConversationForViewer, c as pinConversation, d as readConversationAuxiliaryCostsFromSql, et as readHealthReport, f as childAgentTotalsReport, ft as getProductionSlackAdapter, g as forkConversationForViewer, h as readConversationDetailEtag, i as readConversationFeed, it as resolveObjectLinkNow, k as ReviewItemActionError, kt as resolvePersonLink, l as reorderPinnedConversations, m as conversationVersionQuery, n as steerConversationPendingMessagesForViewer, nt as readLinkObjectType, o as encodePageCursor, ot as viewerCanViewPluginLink, p as readConversationTreeMetricsFromSql, r as conversationFeedVersionQuery, rt as readObjectLinkTypes, s as listedConversation, st as guardedFetch, t as stopConversationTurnForViewer, tt as OBJECT_LINK_TTL_MS, u as readConversationDetail, v as readConversationEvents, w as cancelConversationPendingMessagesForViewer, x as requireWebMessageConversation, y as appendConversationMessageForViewer, z as DEFAULT_USER_SETTINGS } from "./stop-CYsfc0Ed.js";
|
|
10
|
+
import { d as completeText, n as briefEntriesFromReportEvents } from "./prompt-CDqcsDYC.js";
|
|
11
|
+
import { A as readAttachmentContent, D as pauseConversationDelivery, O as resumeConversationDelivery, T as canPauseConversationDelivery, h as createSlackReviewItemShow, j as previewOriginBelongsTo, k as AttachmentDownloadError } from "./agent-runner-BVHPUIc8.js";
|
|
12
|
+
import { E as withSpan, _ as runBestEffort, h as logWarn, m as logInfo, p as logException } from "./logging-FjclQsXu.js";
|
|
13
|
+
import { t as runWithSlackInstallation } from "./adapter-context-G2M0y6rP.js";
|
|
14
|
+
import { A as juniorConversationMetrics, F as codeChangeSearchDocument, G as slackPersonSearchDocument, H as juniorConversations, I as codeRepositorySearchDocument, K as juniorUsers, L as juniorCodeChanges, M as juniorConversationEvents, N as juniorApiTokens, O as juniorConversationBriefs, R as juniorCodeRepositories, U as juniorIdentities, W as slackPersonPredicate, b as juniorAgentBindings, h as juniorReviewItems, p as juniorReviewItemConversations, q as juniorDestinations, x as juniorAgentInvocations } from "./executor-DqTiYj9S.js";
|
|
15
|
+
import { i as continueConversationInSlack, r as canContinueInSlack, t as BUSY } from "./continue-in-slack-DNXSC9So.js";
|
|
16
16
|
import { f as parseSlackTeamId, u as parseSlackChannelId } from "./actor-BsBdxDXQ.js";
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
17
|
+
import { u as sentry_exports } from "./sentry-CPbZjomA.js";
|
|
18
|
+
import { i as getStateAdapter } from "./adapter-B1wujchl.js";
|
|
19
|
+
import { a as isConnectableProvider, c as startConnection, i as disconnectConnection, o as listConnections, t as escapeHtml, u as htmlCallbackResponse } from "./html-B9Sl4Axb.js";
|
|
20
|
+
import { p as credentialContextForActor } from "./registry-BPwuOP2O.js";
|
|
21
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-
|
|
23
|
-
import { n as pluginCatalogRuntime } from "./catalog-runtime-
|
|
24
|
-
import {
|
|
25
|
-
import { o as getSandboxResources } from "./install-
|
|
26
|
-
import { t as getCachedSnapshot } from "./resolve-
|
|
27
|
-
import { m as getVercelConversationWorkQueue } from "./background-compaction-queue-
|
|
22
|
+
import { n as finishServiceAccountSignIn, o as serviceAccountPlugins, r as getServiceAccountStatus, s as startServiceAccountSignIn, t as disconnectServiceAccount } from "./service-account-gN0zqf0S.js";
|
|
23
|
+
import { n as pluginCatalogRuntime } from "./catalog-runtime-DMY3VV-D.js";
|
|
24
|
+
import { C as automationUpdateSchema, E as automationVersionParamsSchema, L as ScheduleIntentError, R as compileScheduleIntent, 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, st as automationTaskText, w as automationVersionActivateSchema, x as automationSchedulePreviewSchema } from "./schedule-BLJ476XQ.js";
|
|
25
|
+
import { o as getSandboxResources } from "./install-Sg4ePfLl.js";
|
|
26
|
+
import { t as getCachedSnapshot } from "./resolve-BK29bBry.js";
|
|
27
|
+
import { m as getVercelConversationWorkQueue } from "./background-compaction-queue-CJDnWVOJ.js";
|
|
28
28
|
import { Hono } from "hono";
|
|
29
29
|
import * as z from "zod";
|
|
30
30
|
import path from "node:path";
|
|
31
31
|
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
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";
|
|
34
|
-
import { alias } from "drizzle-orm/pg-core";
|
|
32
|
+
import { normalizeEventIdentifier, objectPresentation, pluginUserPageContentSchema, pluginUserPageCursorSchema, pluginUserPageFilterSchema, pluginUserPageLinksSchema, pluginUserPageQuerySchema } from "@sentry/junior-plugin-api";
|
|
33
|
+
import { and, asc, count as count$1, desc, eq, exists, gt, gte, inArray, isNotNull, isNull, lt, lte, ne, or, sql } from "drizzle-orm";
|
|
34
|
+
import { alias, union } from "drizzle-orm/pg-core";
|
|
35
35
|
import fs from "node:fs/promises";
|
|
36
36
|
import { readFileSync } from "node:fs";
|
|
37
37
|
import { HTTPException } from "hono/http-exception";
|
|
@@ -39,6 +39,55 @@ import { bodyLimit } from "hono/body-limit";
|
|
|
39
39
|
import { waitUntil } from "@vercel/functions";
|
|
40
40
|
import { zValidator } from "@hono/zod-validator";
|
|
41
41
|
import { createMiddleware } from "hono/factory";
|
|
42
|
+
import { createSentryClient } from "@sentry/api";
|
|
43
|
+
// src/api/content-version.ts
|
|
44
|
+
/**
|
|
45
|
+
* Hash a response body without its top-level `generatedAt`, the read time,
|
|
46
|
+
* so two reads of unchanged content get the same token.
|
|
47
|
+
*/
|
|
48
|
+
function contentVersion(body) {
|
|
49
|
+
const content = JSON.stringify(body, function(key, value) {
|
|
50
|
+
return this === body && key === "generatedAt" ? void 0 : value;
|
|
51
|
+
});
|
|
52
|
+
return createHash("sha256").update(content).digest("base64url");
|
|
53
|
+
}
|
|
54
|
+
/** Headers of a revalidated read. The content is the viewer's own. */
|
|
55
|
+
function contentVersionHeaders(version) {
|
|
56
|
+
return {
|
|
57
|
+
"cache-control": "private, no-store",
|
|
58
|
+
[CONTENT_VERSION_HEADER]: version
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Answer an unchanged JSON read with an empty 304, after the route built it.
|
|
63
|
+
* This saves the download and the client parse, not the read, so a route
|
|
64
|
+
* with a cheaper token, such as the detail version, sets its own. A response
|
|
65
|
+
* that already carries `CONTENT_VERSION_HEADER` is left alone.
|
|
66
|
+
*/
|
|
67
|
+
const revalidateContent = async (context, next) => {
|
|
68
|
+
await next();
|
|
69
|
+
const response = context.res;
|
|
70
|
+
if (context.req.method !== "GET" || response.status !== 200 || response.headers.has("x-junior-content-version") || !response.headers.get("content-type")?.startsWith("application/json")) return;
|
|
71
|
+
const version = contentVersion(await response.clone().json());
|
|
72
|
+
for (const [name, value] of Object.entries(contentVersionHeaders(version))) context.header(name, value);
|
|
73
|
+
if (context.req.header("x-junior-content-version") !== version) return;
|
|
74
|
+
context.res = new Response(null, {
|
|
75
|
+
headers: context.res.headers,
|
|
76
|
+
status: 304
|
|
77
|
+
});
|
|
78
|
+
};
|
|
79
|
+
/**
|
|
80
|
+
* Polled dashboard reads with no stored version token. The versions poll,
|
|
81
|
+
* a detail change, or a running re-fill reads them again, and most reads
|
|
82
|
+
* find them unchanged. The dashboard sends their tokens back.
|
|
83
|
+
*/
|
|
84
|
+
const REVALIDATED_READ_PATHS = [
|
|
85
|
+
"/api/cache-warming/savings/refill",
|
|
86
|
+
"/api/conversations/:conversationId/agents",
|
|
87
|
+
"/api/conversations/:conversationId/plan",
|
|
88
|
+
"/api/conversations/:conversationId/watches",
|
|
89
|
+
"/api/review-items/:id"
|
|
90
|
+
];
|
|
42
91
|
// src/api/objects/attach.ts
|
|
43
92
|
function sameLink(left, right) {
|
|
44
93
|
const key = (url) => url.replace(/\/+$/, "");
|
|
@@ -334,32 +383,31 @@ async function requireConversationChildAgents(conversationId, options = {}) {
|
|
|
334
383
|
const canExposePayload = accessByConversation.get(conversationId)?.canViewPrivateContent ?? false;
|
|
335
384
|
const childIds = children.map((agent) => agent.childConversationId);
|
|
336
385
|
const [metricsByChild, auxiliaryCostsByChild] = await Promise.all([readConversationTreeMetricsFromSql(db, childIds), readConversationAuxiliaryCostsFromSql(db, childIds)]);
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
...
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
agents,
|
|
386
|
+
return {
|
|
387
|
+
agents: children.map((agent) => {
|
|
388
|
+
const metrics = metricsByChild.get(agent.childConversationId);
|
|
389
|
+
const auxiliaryCosts = auxiliaryCostsByChild.get(agent.childConversationId);
|
|
390
|
+
const childAgentTotals = childAgentTotalsReport(metrics, auxiliaryCosts);
|
|
391
|
+
return {
|
|
392
|
+
conversationId: agent.childConversationId,
|
|
393
|
+
cumulativeDurationMs: metrics?.durationMs ?? 0,
|
|
394
|
+
...metrics?.usage ? { cumulativeUsage: metrics.usage } : void 0,
|
|
395
|
+
...auxiliaryCosts ? { auxiliaryCosts: auxiliaryCosts.total } : void 0,
|
|
396
|
+
...childAgentTotals ? { childAgentTotals } : void 0,
|
|
397
|
+
archivedAt: agent.archivedAtMs !== void 0 ? new Date(agent.archivedAtMs).toISOString() : null,
|
|
398
|
+
kind: agent.kind,
|
|
399
|
+
status: agent.status,
|
|
400
|
+
updatedAt: new Date(agent.updatedAtMs).toISOString(),
|
|
401
|
+
...canExposePayload ? {
|
|
402
|
+
...agent.agentName ? { name: agent.agentName } : void 0,
|
|
403
|
+
task: agent.task,
|
|
404
|
+
...agent.title ? { title: agent.title } : void 0,
|
|
405
|
+
...agent.errorMessage ? { error: agent.errorMessage } : void 0
|
|
406
|
+
} : { redacted: true }
|
|
407
|
+
};
|
|
408
|
+
}),
|
|
361
409
|
conversationId
|
|
362
|
-
}
|
|
410
|
+
};
|
|
363
411
|
}
|
|
364
412
|
// src/api/conversations/continue-in-slack.ts
|
|
365
413
|
async function readSlackChannelLocation(locationId) {
|
|
@@ -592,6 +640,68 @@ async function writeAttachmentUploadForViewer(args) {
|
|
|
592
640
|
throw error;
|
|
593
641
|
}
|
|
594
642
|
}
|
|
643
|
+
// src/api/conversations/feed-response.ts
|
|
644
|
+
function countThreads(rows) {
|
|
645
|
+
let count = 0;
|
|
646
|
+
for (const row of rows) if (row.threads) count += row.threads.length + countThreads(row.threads);
|
|
647
|
+
return count;
|
|
648
|
+
}
|
|
649
|
+
/**
|
|
650
|
+
* Serialize a parsed feed to JSON, and report how many chars the large row
|
|
651
|
+
* fields take. Top-level rows only: `threads` holds the nested Threads with
|
|
652
|
+
* all their fields. `waitingRows` counts the rows from outside the page.
|
|
653
|
+
* The same sizes go to span attributes and to metrics.
|
|
654
|
+
*/
|
|
655
|
+
function serializeConversationFeed(feed, waitingRows) {
|
|
656
|
+
const measured = [
|
|
657
|
+
"activityPreview",
|
|
658
|
+
"annotations",
|
|
659
|
+
"participants",
|
|
660
|
+
"threads"
|
|
661
|
+
];
|
|
662
|
+
const chars = {
|
|
663
|
+
activityPreview: 0,
|
|
664
|
+
annotations: 0,
|
|
665
|
+
participants: 0,
|
|
666
|
+
threads: 0
|
|
667
|
+
};
|
|
668
|
+
const rows = feed.conversations.map((row) => {
|
|
669
|
+
const { activityPreview: _activityPreview, annotations: _annotations, participants: _participants, threads: _threads, ...rest } = row;
|
|
670
|
+
let json = JSON.stringify(rest).slice(0, -1);
|
|
671
|
+
for (const key of measured) {
|
|
672
|
+
if (row[key] === void 0) continue;
|
|
673
|
+
const value = JSON.stringify(row[key]);
|
|
674
|
+
chars[key] += value.length;
|
|
675
|
+
json += `,"${key}":${value}`;
|
|
676
|
+
}
|
|
677
|
+
return `${json}}`;
|
|
678
|
+
});
|
|
679
|
+
const { conversations: _conversations, ...meta } = feed;
|
|
680
|
+
const body = `{"conversations":[${rows.join(",")}],${JSON.stringify(meta).slice(1)}`;
|
|
681
|
+
const threads = countThreads(feed.conversations);
|
|
682
|
+
sentry_exports.metrics.distribution("conversation_feed.response.chars", body.length);
|
|
683
|
+
for (const [field, value] of [
|
|
684
|
+
["activity_preview", chars.activityPreview],
|
|
685
|
+
["annotations", chars.annotations],
|
|
686
|
+
["participants", chars.participants],
|
|
687
|
+
["threads", chars.threads]
|
|
688
|
+
]) sentry_exports.metrics.distribution("conversation_feed.response.field_chars", value, { attributes: { "app.api.response.field": field } });
|
|
689
|
+
sentry_exports.metrics.distribution("conversation_feed.rows", feed.conversations.length);
|
|
690
|
+
sentry_exports.metrics.distribution("conversation_feed.threads", threads);
|
|
691
|
+
sentry_exports.metrics.distribution("conversation_feed.waiting_rows", waitingRows);
|
|
692
|
+
return {
|
|
693
|
+
attributes: {
|
|
694
|
+
"app.api.response.field_chars.activity_preview": chars.activityPreview,
|
|
695
|
+
"app.api.response.field_chars.annotations": chars.annotations,
|
|
696
|
+
"app.api.response.field_chars.participants": chars.participants,
|
|
697
|
+
"app.api.response.field_chars.threads": chars.threads,
|
|
698
|
+
"app.conversation_feed.rows": feed.conversations.length,
|
|
699
|
+
"app.conversation_feed.threads": threads,
|
|
700
|
+
"app.conversation_feed.waiting_rows": waitingRows
|
|
701
|
+
},
|
|
702
|
+
body
|
|
703
|
+
};
|
|
704
|
+
}
|
|
595
705
|
// src/api/conversations/outline.ts
|
|
596
706
|
const payload = juniorConversationEvents.payload;
|
|
597
707
|
/**
|
|
@@ -657,6 +767,135 @@ function readMessages(conversationId, role, ...filters) {
|
|
|
657
767
|
function withoutCutToken(text) {
|
|
658
768
|
return text.length < 200 ? text : text.replace(/<([^<>]*)$/, (_, token) => /^[@#!]/.test(token) ? "" : token.split("|")[0]);
|
|
659
769
|
}
|
|
770
|
+
// src/api/cached-report.ts
|
|
771
|
+
const CACHE_NAMESPACE = "core";
|
|
772
|
+
const FRESH_MS$1 = 3e5;
|
|
773
|
+
const KEEP_MS = 36e5;
|
|
774
|
+
const RELOAD_WAIT_MS = 1e4;
|
|
775
|
+
/**
|
|
776
|
+
* Create a reader for one report that is the same for every viewer. A cached
|
|
777
|
+
* report is served for up to an hour. After five minutes, a request also
|
|
778
|
+
* starts a background refresh.
|
|
779
|
+
*/
|
|
780
|
+
function createCachedReport(source) {
|
|
781
|
+
const cachedSchema = z.object({
|
|
782
|
+
refreshAtMs: z.number(),
|
|
783
|
+
report: source.schema
|
|
784
|
+
}).strict();
|
|
785
|
+
const load = async () => ({
|
|
786
|
+
ttlMs: KEEP_MS,
|
|
787
|
+
value: {
|
|
788
|
+
refreshAtMs: Date.now() + FRESH_MS$1,
|
|
789
|
+
report: source.schema.parse(await source.read())
|
|
790
|
+
}
|
|
791
|
+
});
|
|
792
|
+
/**
|
|
793
|
+
* Reload the report under one lock. A caller that gets the lock after
|
|
794
|
+
* another reload first reads the entry that it wrote.
|
|
795
|
+
*/
|
|
796
|
+
const reload = async (state, usable, waitMs) => {
|
|
797
|
+
const cache = createCache(state, CACHE_NAMESPACE);
|
|
798
|
+
return await withLock(state, `${cacheKeyPrefix(CACHE_NAMESPACE)}${source.key}:reload`, async () => {
|
|
799
|
+
const current = cachedSchema.safeParse(await cache.getOrLoad(source.key, load));
|
|
800
|
+
if (current.success && usable(current.data)) return current.data;
|
|
801
|
+
return await cache.getOrLoad(source.key, load, { refresh: true });
|
|
802
|
+
}, { waitMs });
|
|
803
|
+
};
|
|
804
|
+
const refresh = (state) => withSpan(source.key, "cache.refresh", {}, async () => {
|
|
805
|
+
try {
|
|
806
|
+
await reload(state, (cached) => Date.now() < cached.refreshAtMs, 0);
|
|
807
|
+
} catch (error) {
|
|
808
|
+
logException(error, source.refreshFailedEvent);
|
|
809
|
+
}
|
|
810
|
+
}, { "cache.key": [source.key] });
|
|
811
|
+
return ({ waitUntil }) => withSpan(source.key, "cache.get", {}, async (setSpanAttributes) => {
|
|
812
|
+
const state = getStateAdapter();
|
|
813
|
+
let hit = true;
|
|
814
|
+
const loadOnMiss = () => {
|
|
815
|
+
hit = false;
|
|
816
|
+
return load();
|
|
817
|
+
};
|
|
818
|
+
const parsed = cachedSchema.safeParse(await createCache(state, CACHE_NAMESPACE).getOrLoad(source.key, loadOnMiss));
|
|
819
|
+
let cached;
|
|
820
|
+
if (parsed.success) cached = parsed.data;
|
|
821
|
+
else {
|
|
822
|
+
hit = false;
|
|
823
|
+
const reloaded = await reload(state, () => true, RELOAD_WAIT_MS);
|
|
824
|
+
cached = reloaded.acquired ? reloaded.value : (await load()).value;
|
|
825
|
+
}
|
|
826
|
+
const now = Date.now();
|
|
827
|
+
const stale = now >= cached.refreshAtMs;
|
|
828
|
+
setSpanAttributes({
|
|
829
|
+
"cache.hit": hit,
|
|
830
|
+
"cache.item_size": Buffer.byteLength(JSON.stringify(cached)),
|
|
831
|
+
"app.cache.stale": stale,
|
|
832
|
+
"app.cache.age_ms": now - (cached.refreshAtMs - FRESH_MS$1)
|
|
833
|
+
});
|
|
834
|
+
if (stale) waitUntil(() => refresh(state));
|
|
835
|
+
return cached.report;
|
|
836
|
+
}, { "cache.key": [source.key] });
|
|
837
|
+
}
|
|
838
|
+
// src/api/conversations/guardian-hours.ts
|
|
839
|
+
const HOUR_MS$2 = 36e5;
|
|
840
|
+
const STATE_KEY = `${cacheKeyPrefix("core")}conversation-stats:guardian-hours`;
|
|
841
|
+
const LATE_COMMIT_MS = 3e5;
|
|
842
|
+
const guardianHourSchema = z.object({
|
|
843
|
+
allow: z.number(),
|
|
844
|
+
ask: z.number(),
|
|
845
|
+
costUsd: z.number().nullable(),
|
|
846
|
+
date: z.string(),
|
|
847
|
+
deny: z.number(),
|
|
848
|
+
requests: z.number()
|
|
849
|
+
}).strict();
|
|
850
|
+
const storedHoursSchema = z.object({
|
|
851
|
+
hours: z.array(guardianHourSchema),
|
|
852
|
+
throughMs: z.number()
|
|
853
|
+
}).strict();
|
|
854
|
+
function hourKey(instant) {
|
|
855
|
+
return instant.toISOString().slice(0, 13);
|
|
856
|
+
}
|
|
857
|
+
/**
|
|
858
|
+
* Read Guardian review counts per UTC hour. The hours of the previous read
|
|
859
|
+
* stay in state, so a read only reads the reviews after it, plus the overlap
|
|
860
|
+
* for late commits. Without stored hours it reads the whole window.
|
|
861
|
+
*/
|
|
862
|
+
async function readGuardianHours(db, state, window) {
|
|
863
|
+
await state.connect();
|
|
864
|
+
const stored = storedHoursSchema.safeParse(await state.get(STATE_KEY));
|
|
865
|
+
const previous = stored.success && stored.data.throughMs <= window.end.getTime() ? stored.data : void 0;
|
|
866
|
+
const from = previous ? new Date(Math.max(window.start.getTime(), Math.floor((previous.throughMs - LATE_COMMIT_MS) / HOUR_MS$2) * HOUR_MS$2)) : window.start;
|
|
867
|
+
const startHour = hourKey(window.start);
|
|
868
|
+
const fromHour = hourKey(from);
|
|
869
|
+
const kept = (previous?.hours ?? []).filter((hour) => hour.date >= startHour && hour.date < fromHour);
|
|
870
|
+
const read = await readGuardianHoursFromSql(db, from, window.end);
|
|
871
|
+
const hours = [...kept, ...read].sort((left, right) => left.date < right.date ? -1 : 1);
|
|
872
|
+
await state.set(STATE_KEY, {
|
|
873
|
+
hours,
|
|
874
|
+
throughMs: window.end.getTime()
|
|
875
|
+
}, window.end.getTime() - window.start.getTime() + HOUR_MS$2);
|
|
876
|
+
return hours;
|
|
877
|
+
}
|
|
878
|
+
async function readGuardianHoursFromSql(db, start, end) {
|
|
879
|
+
const events = juniorConversationEvents;
|
|
880
|
+
const hour = sql`TO_CHAR(
|
|
881
|
+
${events.createdAt} AT TIME ZONE 'UTC',
|
|
882
|
+
'YYYY-MM-DD"T"HH24'
|
|
883
|
+
)`;
|
|
884
|
+
const decision = sql`${events.payload}->>'decision'`;
|
|
885
|
+
const cost = sql`CASE
|
|
886
|
+
WHEN jsonb_typeof(${events.payload}->'costUsd') = 'number'
|
|
887
|
+
THEN (${events.payload}->>'costUsd')::double precision
|
|
888
|
+
ELSE NULL
|
|
889
|
+
END`;
|
|
890
|
+
return await db.select({
|
|
891
|
+
allow: sql`COUNT(*) FILTER (WHERE ${decision} = 'allow')::integer`,
|
|
892
|
+
ask: sql`COUNT(*) FILTER (WHERE ${decision} = 'ask')::integer`,
|
|
893
|
+
costUsd: sql`SUM(${cost})::double precision`,
|
|
894
|
+
date: hour,
|
|
895
|
+
deny: sql`COUNT(*) FILTER (WHERE ${decision} = 'deny')::integer`,
|
|
896
|
+
requests: sql`COUNT(*)::integer`
|
|
897
|
+
}).from(events).where(and(eq(events.type, "guardian_action_reviewed"), gte(events.createdAt, start), lte(events.createdAt, end))).groupBy(hour);
|
|
898
|
+
}
|
|
660
899
|
// src/api/conversations/metric-buckets.ts
|
|
661
900
|
/** Sum all Conversation metrics into UTC hour buckets. */
|
|
662
901
|
async function readConversationMetricBuckets(db, options) {
|
|
@@ -669,10 +908,10 @@ async function readConversationMetricBuckets(db, options) {
|
|
|
669
908
|
}
|
|
670
909
|
// src/api/conversations/outcome-buckets.ts
|
|
671
910
|
const changes = juniorCodeChanges;
|
|
672
|
-
const linked = alias(juniorConversations, "linked");
|
|
911
|
+
const linked$1 = alias(juniorConversations, "linked");
|
|
673
912
|
const tree = alias(juniorConversations, "outcome_tree");
|
|
674
|
-
const
|
|
675
|
-
const linkedRoot = sql`coalesce(${linked.rootConversationId}, ${linked.conversationId})`;
|
|
913
|
+
const unnestedConversationId = sql`unnest(${changes.conversationIds})`;
|
|
914
|
+
const linkedRoot = sql`coalesce(${linked$1.rootConversationId}, ${linked$1.conversationId})`;
|
|
676
915
|
/**
|
|
677
916
|
* Count outcomes per UTC hour, with the conversation cost that produced
|
|
678
917
|
* them. An outcome is one of:
|
|
@@ -688,8 +927,7 @@ const linkedRoot = sql`coalesce(${linked.rootConversationId}, ${linked.conversat
|
|
|
688
927
|
* with no linked Conversation has an unknown cost, not a zero cost, so it is
|
|
689
928
|
* left out instead of making the mean look cheaper.
|
|
690
929
|
*/
|
|
691
|
-
|
|
692
|
-
const [merges, briefRoots] = await Promise.all([readWindowMerges(db, options), readBriefOutcomeRoots(db, options)]);
|
|
930
|
+
function outcomeBuckets(reads) {
|
|
693
931
|
const buckets = /* @__PURE__ */ new Map();
|
|
694
932
|
const bucketAt = (instant) => {
|
|
695
933
|
const date = instant.toISOString().slice(0, 13);
|
|
@@ -707,7 +945,7 @@ async function readOutcomeBuckets(db, options) {
|
|
|
707
945
|
return bucket;
|
|
708
946
|
};
|
|
709
947
|
const changeCosts = /* @__PURE__ */ new Map();
|
|
710
|
-
for (const merge of merges) {
|
|
948
|
+
for (const merge of reads.merges) {
|
|
711
949
|
const share = merge.treeCostUsd / merge.rootMerges;
|
|
712
950
|
const change = changeCosts.get(merge.changeId);
|
|
713
951
|
if (change) change.costUsd += share;
|
|
@@ -723,13 +961,38 @@ async function readOutcomeBuckets(db, options) {
|
|
|
723
961
|
bucket.outcomes += 1;
|
|
724
962
|
bucket.outcomeCostUsd += change.costUsd;
|
|
725
963
|
}
|
|
726
|
-
|
|
964
|
+
const windowRoots = new Map(reads.windowRoots.map((root) => [root.rootId, root]));
|
|
965
|
+
for (const { rootId } of reads.briefRoots) {
|
|
966
|
+
const root = windowRoots.get(rootId);
|
|
967
|
+
if (!root) continue;
|
|
727
968
|
const bucket = bucketAt(root.lastActivityAt);
|
|
728
969
|
bucket.outcomes += 1;
|
|
729
970
|
bucket.outcomeCostUsd += root.treeCostUsd;
|
|
730
971
|
}
|
|
731
972
|
return [...buckets.values()];
|
|
732
973
|
}
|
|
974
|
+
/**
|
|
975
|
+
* Read each root Conversation active in the window, with the size and cost
|
|
976
|
+
* of its tree. One join reads every tree, so a stats read does not look up
|
|
977
|
+
* each tree on its own.
|
|
978
|
+
*/
|
|
979
|
+
async function readWindowRoots(db, options) {
|
|
980
|
+
const roots = juniorConversations;
|
|
981
|
+
const unreferencedRootCost = sql`CASE
|
|
982
|
+
WHEN ${roots.rootConversationId} IS DISTINCT FROM ${roots.conversationId}
|
|
983
|
+
THEN COALESCE(${conversationUsageCostExpr(roots.usage)}, 0)
|
|
984
|
+
ELSE 0
|
|
985
|
+
END`;
|
|
986
|
+
return await db.select({
|
|
987
|
+
lastActivityAt: roots.lastActivityAt,
|
|
988
|
+
rootId: roots.conversationId,
|
|
989
|
+
treeConversations: sql`count(${tree.conversationId})::integer`,
|
|
990
|
+
treeCostUsd: sql`(
|
|
991
|
+
coalesce(sum(${conversationUsageCostExpr(tree.usage)}), 0)
|
|
992
|
+
+ ${unreferencedRootCost}
|
|
993
|
+
)::double precision`
|
|
994
|
+
}).from(roots).leftJoin(tree, eq(tree.rootConversationId, roots.conversationId)).where(and(isNull(roots.parentConversationId), gte(roots.lastActivityAt, options.start), lte(roots.lastActivityAt, options.end))).groupBy(roots.conversationId);
|
|
995
|
+
}
|
|
733
996
|
/** The summed usage cost of the Conversation tree of `rootId`. */
|
|
734
997
|
function treeCostUsd(db, rootId) {
|
|
735
998
|
const cost = db.select({ costUsd: sql`coalesce(sum(${conversationUsageCostExpr(tree.usage)}), 0)` }).from(tree).where(or(eq(tree.rootConversationId, rootId), eq(tree.conversationId, rootId)));
|
|
@@ -740,11 +1003,16 @@ function treeCostUsd(db, rootId) {
|
|
|
740
1003
|
* merged changes of all time of that root, so each merge gets its share.
|
|
741
1004
|
*/
|
|
742
1005
|
async function readWindowMerges(db, options) {
|
|
743
|
-
const
|
|
1006
|
+
const mergedIds = db.select({
|
|
744
1007
|
changeId: changes.id,
|
|
745
|
-
|
|
1008
|
+
listedId: unnestedConversationId.as("listed_id"),
|
|
1009
|
+
mergedAt: changes.mergedAt
|
|
1010
|
+
}).from(changes).where(eq(changes.state, "merged")).as("merged_ids");
|
|
1011
|
+
const mergedRoots = db.selectDistinct({
|
|
1012
|
+
changeId: mergedIds.changeId,
|
|
1013
|
+
mergedAt: mergedIds.mergedAt,
|
|
746
1014
|
rootId: linkedRoot.as("root_id")
|
|
747
|
-
}).from(
|
|
1015
|
+
}).from(mergedIds).innerJoin(linked$1, eq(linked$1.conversationId, mergedIds.listedId)).as("merged_roots");
|
|
748
1016
|
const counted = db.select({
|
|
749
1017
|
changeId: mergedRoots.changeId,
|
|
750
1018
|
mergedAt: mergedRoots.mergedAt,
|
|
@@ -763,29 +1031,22 @@ async function readWindowMerges(db, options) {
|
|
|
763
1031
|
rootId
|
|
764
1032
|
}] : []);
|
|
765
1033
|
}
|
|
1034
|
+
/**
|
|
1035
|
+
* Window roots with no linked code change whose latest Brief is `done` or
|
|
1036
|
+
* `answered`.
|
|
1037
|
+
*/
|
|
766
1038
|
async function readBriefOutcomeRoots(db, options) {
|
|
767
1039
|
const roots = juniorConversations;
|
|
768
1040
|
const briefs = juniorConversationBriefs;
|
|
769
|
-
const latestBrief = db.select({ status: sql
|
|
770
|
-
const
|
|
771
|
-
|
|
772
|
-
|
|
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)));
|
|
1041
|
+
const latestBrief = db.select({ status: sql`coalesce(${briefs.outcomeStatus}, ${briefs.content}->'outcome'->>'status')`.as("status") }).from(briefs).where(eq(briefs.conversationId, roots.conversationId)).orderBy(desc(briefs.version)).limit(1).as("latest_brief");
|
|
1042
|
+
const changeIds = db.select({ id: unnestedConversationId.as("id") }).from(changes).as("change_ids");
|
|
1043
|
+
const changeRoots = db.selectDistinct({ rootId: linkedRoot.as("root_id") }).from(changeIds).innerJoin(linked$1, eq(linked$1.conversationId, changeIds.id)).as("change_roots");
|
|
1044
|
+
return await db.select({ rootId: roots.conversationId }).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)));
|
|
776
1045
|
}
|
|
777
1046
|
// src/api/conversations/stats.query.ts
|
|
778
|
-
const treeConversation$1 = alias(juniorConversations, "stats_tree_conversation");
|
|
779
|
-
const treeAggregateColumns$1 = conversationAggregateColumns({
|
|
780
|
-
metrics: treeConversation$1,
|
|
781
|
-
roots: juniorConversations
|
|
782
|
-
});
|
|
783
1047
|
function addUsd(current, next) {
|
|
784
1048
|
return Math.round(((current ?? 0) + next) * 0xe8d4a51000) / 0xe8d4a51000;
|
|
785
1049
|
}
|
|
786
|
-
function statsWhere(start, end) {
|
|
787
|
-
return and(isNull(juniorConversations.parentConversationId), gte(juniorConversations.lastActivityAt, start), lte(juniorConversations.lastActivityAt, end));
|
|
788
|
-
}
|
|
789
1050
|
function statsWindow(nowMs) {
|
|
790
1051
|
const end = new Date(nowMs);
|
|
791
1052
|
const start = new Date(nowMs);
|
|
@@ -796,7 +1057,7 @@ function statsWindow(nowMs) {
|
|
|
796
1057
|
start
|
|
797
1058
|
};
|
|
798
1059
|
}
|
|
799
|
-
const HOUR_MS = 36e5;
|
|
1060
|
+
const HOUR_MS$1 = 36e5;
|
|
800
1061
|
function emptyMetricRow(date) {
|
|
801
1062
|
return {
|
|
802
1063
|
cachedInputTokens: null,
|
|
@@ -902,9 +1163,9 @@ function sumGuardianHoursIntoSixHours(hours, endMs) {
|
|
|
902
1163
|
function metricHours(rows, endMs) {
|
|
903
1164
|
const byHour = new Map(rows.map((row) => [row.date, row]));
|
|
904
1165
|
const end = startOfUtcHour(endMs);
|
|
905
|
-
const start = /* @__PURE__ */ new Date(end.getTime() - 167 * HOUR_MS);
|
|
1166
|
+
const start = /* @__PURE__ */ new Date(end.getTime() - 167 * HOUR_MS$1);
|
|
906
1167
|
const hours = [];
|
|
907
|
-
for (const cursor = new Date(start); cursor.getTime() <= end.getTime(); cursor.setTime(cursor.getTime() + HOUR_MS)) {
|
|
1168
|
+
for (const cursor = new Date(start); cursor.getTime() <= end.getTime(); cursor.setTime(cursor.getTime() + HOUR_MS$1)) {
|
|
908
1169
|
const date = utcHourKey(cursor);
|
|
909
1170
|
hours.push(metricPoint(date, byHour.get(date)));
|
|
910
1171
|
}
|
|
@@ -944,9 +1205,9 @@ function guardianStats(dayRows, hourRows, endMs) {
|
|
|
944
1205
|
}
|
|
945
1206
|
const byHour = new Map(hourRows.map((row) => [row.date, row]));
|
|
946
1207
|
const hourEnd = startOfUtcHour(endMs);
|
|
947
|
-
const hourStart = /* @__PURE__ */ new Date(hourEnd.getTime() - 167 * HOUR_MS);
|
|
1208
|
+
const hourStart = /* @__PURE__ */ new Date(hourEnd.getTime() - 167 * HOUR_MS$1);
|
|
948
1209
|
const metricHours = [];
|
|
949
|
-
for (const cursor = new Date(hourStart); cursor.getTime() <= hourEnd.getTime(); cursor.setTime(cursor.getTime() + HOUR_MS)) {
|
|
1210
|
+
for (const cursor = new Date(hourStart); cursor.getTime() <= hourEnd.getTime(); cursor.setTime(cursor.getTime() + HOUR_MS$1)) {
|
|
950
1211
|
const date = utcHourKey(cursor);
|
|
951
1212
|
metricHours.push(guardianPoint(date, byHour.get(date)));
|
|
952
1213
|
}
|
|
@@ -976,53 +1237,54 @@ function sumHoursIntoDays(hours, add, key = () => "") {
|
|
|
976
1237
|
}
|
|
977
1238
|
return [...days.values()];
|
|
978
1239
|
}
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
)`;
|
|
994
|
-
const decision = sql`${juniorConversationEvents.payload}->>'decision'`;
|
|
995
|
-
const cost = sql`CASE
|
|
996
|
-
WHEN jsonb_typeof(${juniorConversationEvents.payload}->'costUsd') = 'number'
|
|
997
|
-
THEN (${juniorConversationEvents.payload}->>'costUsd')::double precision
|
|
998
|
-
ELSE NULL
|
|
999
|
-
END`;
|
|
1000
|
-
return await db.select({
|
|
1001
|
-
allow: sql`COUNT(*) FILTER (WHERE ${decision} = 'allow')::integer`,
|
|
1002
|
-
ask: sql`COUNT(*) FILTER (WHERE ${decision} = 'ask')::integer`,
|
|
1003
|
-
costUsd: sql`SUM(${cost})::double precision`,
|
|
1004
|
-
date: hour,
|
|
1005
|
-
deny: sql`COUNT(*) FILTER (WHERE ${decision} = 'deny')::integer`,
|
|
1006
|
-
requests: sql`COUNT(*)::integer`
|
|
1007
|
-
}).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.type, "guardian_action_reviewed"), gte(juniorConversationEvents.createdAt, start), lte(juniorConversationEvents.createdAt, end))).groupBy(hour);
|
|
1240
|
+
/** Count the window roots that have a tree, per UTC hour of last activity. */
|
|
1241
|
+
function activityHours$1(roots) {
|
|
1242
|
+
const hours = /* @__PURE__ */ new Map();
|
|
1243
|
+
for (const root of roots) {
|
|
1244
|
+
if (root.treeConversations === 0) continue;
|
|
1245
|
+
const date = root.lastActivityAt.toISOString().slice(0, 13);
|
|
1246
|
+
const hour = hours.get(date);
|
|
1247
|
+
if (hour) hour.conversations += 1;
|
|
1248
|
+
else hours.set(date, {
|
|
1249
|
+
conversations: 1,
|
|
1250
|
+
date
|
|
1251
|
+
});
|
|
1252
|
+
}
|
|
1253
|
+
return [...hours.values()];
|
|
1008
1254
|
}
|
|
1009
1255
|
/** Build complete 90-day dashboard stats from normalized durable SQL records. */
|
|
1010
1256
|
async function readConversationStatsFromSql() {
|
|
1011
1257
|
const nowMs = Date.now();
|
|
1012
1258
|
const { end, start } = statsWindow(nowMs);
|
|
1013
1259
|
const db = getDb();
|
|
1014
|
-
const [
|
|
1015
|
-
|
|
1260
|
+
const [windowRoots, metrics, merges, briefRoots, guardian] = await Promise.all([
|
|
1261
|
+
readWindowRoots(db, {
|
|
1262
|
+
start,
|
|
1263
|
+
end
|
|
1264
|
+
}),
|
|
1016
1265
|
readConversationMetricBuckets(db, {
|
|
1017
1266
|
start,
|
|
1018
1267
|
end
|
|
1019
1268
|
}),
|
|
1020
|
-
|
|
1269
|
+
readWindowMerges(db, {
|
|
1270
|
+
start,
|
|
1271
|
+
end
|
|
1272
|
+
}),
|
|
1273
|
+
readBriefOutcomeRoots(db, {
|
|
1021
1274
|
start,
|
|
1022
1275
|
end
|
|
1023
1276
|
}),
|
|
1024
|
-
readGuardianHours(db,
|
|
1277
|
+
readGuardianHours(db, getStateAdapter(), {
|
|
1278
|
+
start,
|
|
1279
|
+
end
|
|
1280
|
+
})
|
|
1025
1281
|
]);
|
|
1282
|
+
const activity = activityHours$1(windowRoots);
|
|
1283
|
+
const outcomes = outcomeBuckets({
|
|
1284
|
+
briefRoots,
|
|
1285
|
+
merges,
|
|
1286
|
+
windowRoots
|
|
1287
|
+
});
|
|
1026
1288
|
const hours = metricHours(applyMetricBuckets(activity, metrics, outcomes), nowMs);
|
|
1027
1289
|
return {
|
|
1028
1290
|
generatedAt: new Date(nowMs).toISOString(),
|
|
@@ -1051,61 +1313,13 @@ async function readConversationStatsFromSql() {
|
|
|
1051
1313
|
};
|
|
1052
1314
|
}
|
|
1053
1315
|
// src/api/conversations/stats.ts
|
|
1054
|
-
|
|
1055
|
-
const
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
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;
|
|
1108
|
-
}
|
|
1316
|
+
/** Load aggregate conversation stats from durable SQL records. */
|
|
1317
|
+
const readConversationStats = createCachedReport({
|
|
1318
|
+
key: "conversation-stats",
|
|
1319
|
+
read: readConversationStatsFromSql,
|
|
1320
|
+
refreshFailedEvent: "conversation_stats.refresh.failed",
|
|
1321
|
+
schema: conversationStatsReportSchema
|
|
1322
|
+
});
|
|
1109
1323
|
// src/api/conversations/watches.ts
|
|
1110
1324
|
/**
|
|
1111
1325
|
* Load the active Watches that one Conversation owns, or throw a standard API
|
|
@@ -1117,35 +1331,52 @@ async function requireConversationWatches(conversationId, options = {}) {
|
|
|
1117
1331
|
const [accessByConversation, owned] = await Promise.all([readConversationAccessFromSql(getDb(), [conversationId], options.viewer), listOwnedWatches(conversationId)]);
|
|
1118
1332
|
const canExposePayload = accessByConversation.get(conversationId)?.canViewPrivateContent ?? false;
|
|
1119
1333
|
const catalog = getEventCatalog();
|
|
1120
|
-
|
|
1121
|
-
const url = canExposePayload ? catalog[watch.namespace]?.resourceUrl?.({
|
|
1122
|
-
identifier: watch.identifier,
|
|
1123
|
-
resourceType: watch.resourceType
|
|
1124
|
-
}) : void 0;
|
|
1125
|
-
return {
|
|
1126
|
-
...childAgent ? { childAgent: {
|
|
1127
|
-
conversationId: childAgent.conversationId,
|
|
1128
|
-
...canExposePayload && childAgent.name ? { name: childAgent.name } : void 0
|
|
1129
|
-
} } : void 0,
|
|
1130
|
-
createdAt: new Date(watch.createdAtMs).toISOString(),
|
|
1131
|
-
events: watch.events,
|
|
1132
|
-
expiresAt: new Date(watch.expiresAtMs).toISOString(),
|
|
1133
|
-
...watch.firesAtMs !== void 0 ? { firesAt: new Date(watch.firesAtMs).toISOString() } : void 0,
|
|
1134
|
-
id: watch.id,
|
|
1135
|
-
namespace: watch.namespace,
|
|
1136
|
-
resourceType: watch.resourceType,
|
|
1137
|
-
...canExposePayload ? {
|
|
1138
|
-
intent: watch.intent,
|
|
1139
|
-
label: watch.label,
|
|
1140
|
-
...watch.match ? { match: watch.match } : void 0,
|
|
1141
|
-
...url ? { url } : void 0
|
|
1142
|
-
} : { redacted: true }
|
|
1143
|
-
};
|
|
1144
|
-
});
|
|
1145
|
-
return conversationWatchesReportSchema.parse({
|
|
1334
|
+
return {
|
|
1146
1335
|
conversationId,
|
|
1147
|
-
watches
|
|
1336
|
+
watches: owned.map(({ childAgent, watch }) => {
|
|
1337
|
+
const url = canExposePayload ? catalog[watch.namespace]?.resourceUrl?.({
|
|
1338
|
+
identifier: watch.identifier,
|
|
1339
|
+
resourceType: watch.resourceType
|
|
1340
|
+
}) : void 0;
|
|
1341
|
+
return {
|
|
1342
|
+
...childAgent ? { childAgent: {
|
|
1343
|
+
conversationId: childAgent.conversationId,
|
|
1344
|
+
...canExposePayload && childAgent.name ? { name: childAgent.name } : void 0
|
|
1345
|
+
} } : void 0,
|
|
1346
|
+
createdAt: new Date(watch.createdAtMs).toISOString(),
|
|
1347
|
+
events: watch.events,
|
|
1348
|
+
expiresAt: new Date(watch.expiresAtMs).toISOString(),
|
|
1349
|
+
...watch.firesAtMs !== void 0 ? { firesAt: new Date(watch.firesAtMs).toISOString() } : void 0,
|
|
1350
|
+
id: watch.id,
|
|
1351
|
+
namespace: watch.namespace,
|
|
1352
|
+
resourceType: watch.resourceType,
|
|
1353
|
+
...canExposePayload ? {
|
|
1354
|
+
intent: watch.intent,
|
|
1355
|
+
label: watch.label,
|
|
1356
|
+
...watch.match ? { match: watch.match } : void 0,
|
|
1357
|
+
...url ? { url } : void 0
|
|
1358
|
+
} : { redacted: true }
|
|
1359
|
+
};
|
|
1360
|
+
})
|
|
1361
|
+
};
|
|
1362
|
+
}
|
|
1363
|
+
/**
|
|
1364
|
+
* Cancel one active Watch of one Conversation for a Participant, the same
|
|
1365
|
+
* people who can stop its Turn. Only the Conversation that created the Watch
|
|
1366
|
+
* cancels it, so a child agent's Watch is cancelled through the child.
|
|
1367
|
+
*
|
|
1368
|
+
* The agent gets no notice. Its next `listWatches` no longer shows the Watch.
|
|
1369
|
+
*/
|
|
1370
|
+
async function cancelConversationWatchForViewer(viewer, conversationId, watchId) {
|
|
1371
|
+
const access = (await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId);
|
|
1372
|
+
if (!access?.canViewPrivateContent) throwApiError(404, "Conversation not found.");
|
|
1373
|
+
if (!access.isParticipant) throwApiError(403, "Only conversation participants can cancel a Watch.");
|
|
1374
|
+
const watch = await cancelWatch({
|
|
1375
|
+
conversationId,
|
|
1376
|
+
id: watchId
|
|
1148
1377
|
});
|
|
1378
|
+
if (!watch) throwApiError(404, "Watch not found.");
|
|
1379
|
+
if (watch.status === "completed") throwApiError(409, "Watch already completed.");
|
|
1149
1380
|
}
|
|
1150
1381
|
// src/api/conversations/plan.ts
|
|
1151
1382
|
/** Closed items that the report shows after the open ones. */
|
|
@@ -1183,10 +1414,10 @@ async function requireConversationPlan(conversationId, options = {}) {
|
|
|
1183
1414
|
const [accessByConversation, items] = await Promise.all([readConversationAccessFromSql(getDb(), [conversationId], options.viewer), listPlanItems(getSqlExecutor(), conversationId)]);
|
|
1184
1415
|
const canViewPrivateContent = accessByConversation.get(conversationId)?.canViewPrivateContent ?? false;
|
|
1185
1416
|
const closed = items.filter((item) => !isOpenPlanItemStatus(item.status)).sort((left, right) => right.updatedAtMs - left.updatedAtMs).slice(0, RECENT_CLOSED_ITEMS);
|
|
1186
|
-
return
|
|
1417
|
+
return {
|
|
1187
1418
|
conversationId,
|
|
1188
1419
|
items: [...items.filter((item) => isOpenPlanItemStatus(item.status)), ...closed].map((item) => reportItem(item, canViewPrivateContent))
|
|
1189
|
-
}
|
|
1420
|
+
};
|
|
1190
1421
|
}
|
|
1191
1422
|
/**
|
|
1192
1423
|
* Set the status of one Plan item for a person. The plan is shared, so only
|
|
@@ -1214,15 +1445,26 @@ function createConversationRoutes(options) {
|
|
|
1214
1445
|
app.get("/", validateRequest("query", conversationFeedQuerySchema, "Invalid query parameters."), async (context) => {
|
|
1215
1446
|
const { actorEmail, codeRepositoryId, cursor, include, q, status } = context.req.valid("query");
|
|
1216
1447
|
const viewer = context.get("viewer");
|
|
1217
|
-
|
|
1448
|
+
let waitingRows = 0;
|
|
1449
|
+
const feed = await readConversationFeed({
|
|
1218
1450
|
...actorEmail ? { actorEmail } : void 0,
|
|
1219
1451
|
...codeRepositoryId ? { codeRepositoryId } : void 0,
|
|
1220
1452
|
...cursor ? { cursor } : void 0,
|
|
1221
1453
|
include,
|
|
1454
|
+
onWaitingRows: (count) => {
|
|
1455
|
+
waitingRows = count;
|
|
1456
|
+
},
|
|
1222
1457
|
...q ? { q } : void 0,
|
|
1223
1458
|
status,
|
|
1224
1459
|
...viewer ? { viewer } : void 0
|
|
1225
|
-
})
|
|
1460
|
+
});
|
|
1461
|
+
const version = contentVersion(feed);
|
|
1462
|
+
const headers = contentVersionHeaders(version);
|
|
1463
|
+
if (context.req.header("x-junior-content-version") === version) return new Response(null, {
|
|
1464
|
+
status: 304,
|
|
1465
|
+
headers
|
|
1466
|
+
});
|
|
1467
|
+
return jsonResponse(conversationFeedSchema, feed, { headers }, (parsed) => serializeConversationFeed(parsed, waitingRows));
|
|
1226
1468
|
});
|
|
1227
1469
|
app.get("/stats", async () => jsonResponse(conversationStatsReportSchema, await readConversationStats({ waitUntil: options.waitUntil })));
|
|
1228
1470
|
app.post("/", requireViewer, messageBodyLimit, validateRequest("json", createConversationBodySchema, "Invalid request body."), async (context) => {
|
|
@@ -1268,6 +1510,7 @@ function createConversationRoutes(options) {
|
|
|
1268
1510
|
app.patch("/:conversationId/pin", requireViewer, validateRequest("param", conversationParamsSchema, "Invalid route parameters."), validateRequest("json", pinConversationBodySchema, "Invalid request body."), async (context) => jsonResponse(pinConversationResponseSchema, await pinConversation(context.get("viewer"), context.req.valid("param").conversationId, context.req.valid("json"))));
|
|
1269
1511
|
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"))));
|
|
1270
1512
|
app.patch("/:conversationId/subscription", requireViewer, validateRequest("param", conversationParamsSchema, "Invalid route parameters."), validateRequest("json", conversationSubscriptionBodySchema, "Invalid request body."), async (context) => jsonResponse(conversationSubscriptionResponseSchema, await setConversationSubscription(context.get("viewer"), context.req.valid("param").conversationId, context.req.valid("json"))));
|
|
1513
|
+
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"))));
|
|
1271
1514
|
app.patch("/:conversationId/title", requireViewer, validateRequest("param", conversationParamsSchema, "Invalid route parameters."), validateRequest("json", renameConversationBodySchema, "Invalid request body."), async (context) => jsonResponse(renameConversationResponseSchema, await renameConversation(context.get("viewer"), context.req.valid("param").conversationId, context.req.valid("json"))));
|
|
1272
1515
|
app.post("/:conversationId/annotations", requireViewer, validateRequest("param", conversationParamsSchema, "Invalid route parameters."), validateRequest("json", attachObjectLinkBodySchema, "Invalid request body."), async (context) => jsonResponse(attachObjectLinkResponseSchema, await attachObjectLink(context.get("viewer"), context.req.valid("param").conversationId, context.req.valid("json").url)));
|
|
1273
1516
|
app.put("/:conversationId/read-position", requireViewer, validateRequest("param", conversationParamsSchema, "Invalid route parameters."), validateRequest("json", conversationReadPositionSchema, "Invalid request body."), async (context) => {
|
|
@@ -1313,6 +1556,11 @@ function createConversationRoutes(options) {
|
|
|
1313
1556
|
const viewer = context.get("viewer");
|
|
1314
1557
|
return jsonResponse(conversationWatchesReportSchema, await requireConversationWatches(conversationId, { viewer }));
|
|
1315
1558
|
});
|
|
1559
|
+
app.delete("/:conversationId/watches/:watchId", requireViewer, validateRequest("param", watchParamsSchema, "Invalid route parameters."), async (context) => {
|
|
1560
|
+
const { conversationId, watchId } = context.req.valid("param");
|
|
1561
|
+
await cancelConversationWatchForViewer(context.get("viewer"), conversationId, watchId);
|
|
1562
|
+
return emptyResponse();
|
|
1563
|
+
});
|
|
1316
1564
|
app.get("/:conversationId/plan", validateRequest("param", conversationParamsSchema, "Invalid route parameters."), async (context) => {
|
|
1317
1565
|
const { conversationId } = context.req.valid("param");
|
|
1318
1566
|
const viewer = context.get("viewer");
|
|
@@ -1400,7 +1648,7 @@ function createConversationRoutes(options) {
|
|
|
1400
1648
|
return app;
|
|
1401
1649
|
}
|
|
1402
1650
|
// src/api/code/overview.ts
|
|
1403
|
-
const DAY_MS$
|
|
1651
|
+
const DAY_MS$2 = 864e5;
|
|
1404
1652
|
const WINDOW_DAYS = 30;
|
|
1405
1653
|
/**
|
|
1406
1654
|
* Code changes on one page of a person's code overview. Open changes sort
|
|
@@ -1504,12 +1752,12 @@ function changeScopeFilter(args) {
|
|
|
1504
1752
|
async function readCodeWindows(args) {
|
|
1505
1753
|
const db = getDb();
|
|
1506
1754
|
const windowEnd = new Date(args.nowMs);
|
|
1507
|
-
const windowStart = /* @__PURE__ */ new Date(args.nowMs - WINDOW_DAYS * DAY_MS$
|
|
1508
|
-
const activityStart = startOfUtcDay(args.nowMs - 89 * DAY_MS$
|
|
1755
|
+
const windowStart = /* @__PURE__ */ new Date(args.nowMs - WINDOW_DAYS * DAY_MS$2);
|
|
1756
|
+
const activityStart = startOfUtcDay(args.nowMs - 89 * DAY_MS$2);
|
|
1509
1757
|
const changes = juniorCodeChanges;
|
|
1510
1758
|
const activityHourEnd = new Date(args.nowMs);
|
|
1511
1759
|
activityHourEnd.setUTCMinutes(0, 0, 0);
|
|
1512
|
-
const activityHourStart = /* @__PURE__ */ new Date(activityHourEnd.getTime() - 167 * (DAY_MS$
|
|
1760
|
+
const activityHourStart = /* @__PURE__ */ new Date(activityHourEnd.getTime() - 167 * (DAY_MS$2 / 24));
|
|
1513
1761
|
const rows = await db.select({
|
|
1514
1762
|
closedAt: changes.closedAt,
|
|
1515
1763
|
conversationIds: changes.conversationIds,
|
|
@@ -1529,13 +1777,13 @@ async function readCodeWindows(args) {
|
|
|
1529
1777
|
end: activityHourEnd,
|
|
1530
1778
|
keyLength: 13,
|
|
1531
1779
|
start: activityHourStart,
|
|
1532
|
-
stepMs: DAY_MS$
|
|
1780
|
+
stepMs: DAY_MS$2 / 24
|
|
1533
1781
|
});
|
|
1534
1782
|
const summary = {
|
|
1535
1783
|
closed: closed.length,
|
|
1536
1784
|
costUsd: treeCost(createdConversationIds),
|
|
1537
1785
|
created: created.length,
|
|
1538
|
-
idle: rows.filter((row) => row.state === "open" && Math.floor((args.nowMs - (row.lastActivityAt ?? row.openedAt).getTime()) / DAY_MS$
|
|
1786
|
+
idle: rows.filter((row) => row.state === "open" && Math.floor((args.nowMs - (row.lastActivityAt ?? row.openedAt).getTime()) / DAY_MS$2) > 7).length,
|
|
1539
1787
|
medianCostUsd: median(changeCosts.filter((cost) => cost > 0)),
|
|
1540
1788
|
medianMergeTimeMs: median(merged.flatMap((row) => row.state === "merged" && row.mergedAt ? [row.mergedAt.getTime() - row.openedAt.getTime()] : [])),
|
|
1541
1789
|
merged: merged.length,
|
|
@@ -1546,7 +1794,7 @@ async function readCodeWindows(args) {
|
|
|
1546
1794
|
end: startOfUtcDay(args.nowMs),
|
|
1547
1795
|
keyLength: 10,
|
|
1548
1796
|
start: activityStart,
|
|
1549
|
-
stepMs: DAY_MS$
|
|
1797
|
+
stepMs: DAY_MS$2
|
|
1550
1798
|
}),
|
|
1551
1799
|
activityHours,
|
|
1552
1800
|
activitySixHours: sumUtcHoursIntoSixHours({
|
|
@@ -1569,7 +1817,10 @@ async function readCodeWindows(args) {
|
|
|
1569
1817
|
}
|
|
1570
1818
|
/** Columns read for one code change report row. */
|
|
1571
1819
|
const codeChangeReportColumns = {
|
|
1820
|
+
additions: juniorCodeChanges.additions,
|
|
1821
|
+
changedFiles: juniorCodeChanges.changedFiles,
|
|
1572
1822
|
closedAt: juniorCodeChanges.closedAt,
|
|
1823
|
+
deletions: juniorCodeChanges.deletions,
|
|
1573
1824
|
draft: juniorCodeChanges.draft,
|
|
1574
1825
|
id: juniorCodeChanges.id,
|
|
1575
1826
|
lastActivityAt: juniorCodeChanges.lastActivityAt,
|
|
@@ -1583,9 +1834,14 @@ const codeChangeReportColumns = {
|
|
|
1583
1834
|
url: juniorCodeChanges.url
|
|
1584
1835
|
};
|
|
1585
1836
|
/** Convert one code change row to its report shape. */
|
|
1586
|
-
function codeChangeReport(change) {
|
|
1837
|
+
function codeChangeReport({ additions, changedFiles, deletions, ...change }) {
|
|
1838
|
+
const size = {};
|
|
1839
|
+
if (additions !== null) size.additions = additions;
|
|
1840
|
+
if (deletions !== null) size.deletions = deletions;
|
|
1841
|
+
if (changedFiles !== null) size.changedFiles = changedFiles;
|
|
1587
1842
|
return {
|
|
1588
1843
|
...change,
|
|
1844
|
+
...Object.keys(size).length > 0 ? { size } : void 0,
|
|
1589
1845
|
closedAt: change.closedAt?.toISOString(),
|
|
1590
1846
|
lastActivityAt: change.lastActivityAt?.toISOString(),
|
|
1591
1847
|
mergedAt: change.mergedAt?.toISOString(),
|
|
@@ -1627,7 +1883,7 @@ async function readCodeOverview(nowMs = Date.now()) {
|
|
|
1627
1883
|
costs.push(cost);
|
|
1628
1884
|
repositoryCosts.set(change.repositoryId, costs);
|
|
1629
1885
|
}
|
|
1630
|
-
return
|
|
1886
|
+
return {
|
|
1631
1887
|
activityDays: windows.activityDays,
|
|
1632
1888
|
activityHours: windows.activityHours,
|
|
1633
1889
|
activitySixHours: windows.activitySixHours,
|
|
@@ -1642,7 +1898,7 @@ async function readCodeOverview(nowMs = Date.now()) {
|
|
|
1642
1898
|
summary: windows.summary,
|
|
1643
1899
|
windowEnd: windows.windowEnd.toISOString(),
|
|
1644
1900
|
windowStart: windows.windowStart.toISOString()
|
|
1645
|
-
}
|
|
1901
|
+
};
|
|
1646
1902
|
}
|
|
1647
1903
|
/**
|
|
1648
1904
|
* Position after the last change of a page of a person's code overview.
|
|
@@ -1679,7 +1935,7 @@ async function readPersonCodeOverview(args) {
|
|
|
1679
1935
|
updatedAt: juniorCodeChanges.updatedAt
|
|
1680
1936
|
}).from(juniorCodeChanges).innerJoin(juniorCodeRepositories, eq(juniorCodeChanges.repositoryId, juniorCodeRepositories.id)).where(and(changeScopeFilter({ userId: args.userId }), after ? afterPersonCodeCursor(after) : void 0)).orderBy(desc(sql`${juniorCodeChanges.state} = 'open'`), asc(sql`CASE WHEN ${juniorCodeChanges.state} = 'open' THEN ${idleSince} END`), desc(juniorCodeChanges.updatedAt), asc(juniorCodeChanges.id)).limit(PERSON_CHANGE_LIMIT)]);
|
|
1681
1937
|
const last = changes.at(-1);
|
|
1682
|
-
return
|
|
1938
|
+
return {
|
|
1683
1939
|
activityDays: windows.activityDays,
|
|
1684
1940
|
activityHours: windows.activityHours,
|
|
1685
1941
|
activitySixHours: windows.activitySixHours,
|
|
@@ -1693,7 +1949,15 @@ async function readPersonCodeOverview(args) {
|
|
|
1693
1949
|
summary: windows.summary,
|
|
1694
1950
|
windowEnd: windows.windowEnd.toISOString(),
|
|
1695
1951
|
windowStart: windows.windowStart.toISOString()
|
|
1696
|
-
}
|
|
1952
|
+
};
|
|
1953
|
+
}
|
|
1954
|
+
/**
|
|
1955
|
+
* Read the code changes that one person merged most recently, by their
|
|
1956
|
+
* normalized email, in one statement.
|
|
1957
|
+
*/
|
|
1958
|
+
async function readPersonMergedChanges(args) {
|
|
1959
|
+
const userId = getDb().select({ id: juniorUsers.id }).from(juniorUsers).where(eq(juniorUsers.primaryEmailNormalized, args.email));
|
|
1960
|
+
return (await getDb().select({ change: codeChangeReportColumns }).from(juniorCodeChanges).innerJoin(juniorCodeRepositories, eq(juniorCodeChanges.repositoryId, juniorCodeRepositories.id)).where(and(ownedByUserSql(sql`(${userId})`), eq(juniorCodeChanges.state, "merged"), isNotNull(juniorCodeChanges.mergedAt))).orderBy(desc(juniorCodeChanges.mergedAt), asc(juniorCodeChanges.id)).limit(args.limit)).map((row) => codeChangeReport(row.change));
|
|
1697
1961
|
}
|
|
1698
1962
|
// src/api/code/repository.ts
|
|
1699
1963
|
/** Most recent code changes listed on one repository page. */
|
|
@@ -1732,7 +1996,7 @@ async function readCodeRepository(repositoryId, options = {}) {
|
|
|
1732
1996
|
repo: repository.name
|
|
1733
1997
|
})
|
|
1734
1998
|
]);
|
|
1735
|
-
return
|
|
1999
|
+
return {
|
|
1736
2000
|
activityDays: windows.activityDays,
|
|
1737
2001
|
activityHours: windows.activityHours,
|
|
1738
2002
|
activitySixHours: windows.activitySixHours,
|
|
@@ -1751,13 +2015,50 @@ async function readCodeRepository(repositoryId, options = {}) {
|
|
|
1751
2015
|
windowEnd: windows.windowEnd.toISOString(),
|
|
1752
2016
|
windowStart: windows.windowStart.toISOString(),
|
|
1753
2017
|
workspaces
|
|
1754
|
-
}
|
|
2018
|
+
};
|
|
2019
|
+
}
|
|
2020
|
+
// src/api/code/search.query.ts
|
|
2021
|
+
const CODE_CHANGE_SEARCH_LIMIT = 8;
|
|
2022
|
+
const CODE_CHANGE_SEARCH_TERMS = 4;
|
|
2023
|
+
const titleMatch = alias(juniorCodeChanges, "title_match");
|
|
2024
|
+
const repositoryMatch = alias(juniorCodeChanges, "repository_match");
|
|
2025
|
+
const linked = alias(juniorConversations, "linked_conversation");
|
|
2026
|
+
/**
|
|
2027
|
+
* Find code changes for the composer `#` menu, newest activity first. A
|
|
2028
|
+
* query of digits, with an optional leading `#`, matches the start of the
|
|
2029
|
+
* number. Other text matches word prefixes of the title and the repository
|
|
2030
|
+
* name. The viewer finds only changes linked to a Conversation that they can
|
|
2031
|
+
* find in the feed. It reads the indexes `junior_code_changes_search_idx` and
|
|
2032
|
+
* `junior_code_repositories_search_idx` in one statement.
|
|
2033
|
+
*/
|
|
2034
|
+
async function readCodeChangeSearchFromSql(query, viewerUserId) {
|
|
2035
|
+
const number = /^#?(\d+)$/.exec(query.trim())?.[1];
|
|
2036
|
+
const terms = number ? [number] : (query.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? []).slice(0, CODE_CHANGE_SEARCH_TERMS);
|
|
2037
|
+
if (terms.length === 0) return [];
|
|
2038
|
+
const everyTerm = terms.map((term) => `${term}:*`).join(" & ");
|
|
2039
|
+
const anyTerm = terms.map((term) => `${term}:*`).join(" | ");
|
|
2040
|
+
const db = getDb();
|
|
2041
|
+
const changeDocument = codeChangeSearchDocument(juniorCodeChanges);
|
|
2042
|
+
const matches = number ? and(sql`${changeDocument} @@ to_tsquery('simple', ${everyTerm})`, sql`${juniorCodeChanges.number}::text like ${`${number}%`}`) : and(inArray(juniorCodeChanges.id, union(db.select({ id: titleMatch.id }).from(titleMatch).where(sql`${codeChangeSearchDocument(titleMatch)} @@ to_tsquery('simple', ${anyTerm})`), db.select({ id: repositoryMatch.id }).from(repositoryMatch).innerJoin(juniorCodeRepositories, eq(juniorCodeRepositories.id, repositoryMatch.repositoryId)).where(sql`${codeRepositorySearchDocument(juniorCodeRepositories)} @@ to_tsquery('simple', ${anyTerm})`))), sql`(${changeDocument} || ${codeRepositorySearchDocument(juniorCodeRepositories)}) @@ to_tsquery('simple', ${everyTerm})`);
|
|
2043
|
+
const visible = exists(db.select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).leftJoin(juniorDestinations, conversationRecordJoins.location).where(and(listedConversation(), rootVisibleToViewer(viewerUserId), inArray(juniorConversations.conversationId, db.select({ rootConversationId: sql`coalesce(${linked.rootConversationId}, ${linked.conversationId})` }).from(linked).where(sql`${linked.conversationId} = any(${juniorCodeChanges.conversationIds})`)))));
|
|
2044
|
+
return (await db.select({
|
|
2045
|
+
draft: juniorCodeChanges.draft,
|
|
2046
|
+
number: juniorCodeChanges.number,
|
|
2047
|
+
repository: juniorCodeRepositories.name,
|
|
2048
|
+
state: juniorCodeChanges.state,
|
|
2049
|
+
title: juniorCodeChanges.title,
|
|
2050
|
+
url: juniorCodeChanges.url
|
|
2051
|
+
}).from(juniorCodeChanges).innerJoin(juniorCodeRepositories, eq(juniorCodeRepositories.id, juniorCodeChanges.repositoryId)).where(and(matches, isNotNull(juniorCodeChanges.url), visible)).orderBy(...number ? [desc(sql`${juniorCodeChanges.number}::text = ${number}`)] : [], desc(sql`coalesce(${juniorCodeChanges.lastActivityAt}, ${juniorCodeChanges.openedAt})`), asc(juniorCodeChanges.id)).limit(CODE_CHANGE_SEARCH_LIMIT)).flatMap((row) => row.url ? [{
|
|
2052
|
+
...row,
|
|
2053
|
+
url: row.url
|
|
2054
|
+
}] : []);
|
|
1755
2055
|
}
|
|
1756
2056
|
// src/api/code/routes.ts
|
|
1757
2057
|
/** Create the code analytics API. */
|
|
1758
2058
|
function createCodeRoutes() {
|
|
1759
2059
|
const app = new Hono();
|
|
1760
2060
|
app.get("/", async () => jsonResponse(codeOverviewReportSchema, await readCodeOverview()));
|
|
2061
|
+
app.get("/changes/search", requireViewer, validateRequest("query", codeChangeSearchQuerySchema, "Invalid search query."), async (context) => jsonResponse(codeChangeSearchReportSchema, { changes: await readCodeChangeSearchFromSql(context.req.valid("query").q, context.get("viewer").id) }));
|
|
1761
2062
|
app.get("/repositories/:repositoryId", validateRequest("param", codeRepositoryParamsSchema, "Invalid route parameters."), validateRequest("query", codeRepositoryQuerySchema, "Invalid query parameters."), async (context) => {
|
|
1762
2063
|
const { repositoryId } = context.req.valid("param");
|
|
1763
2064
|
const { state } = context.req.valid("query");
|
|
@@ -1810,14 +2111,14 @@ async function readSettings(userId) {
|
|
|
1810
2111
|
isPausedBySlack(db, userId, nowMs)
|
|
1811
2112
|
]);
|
|
1812
2113
|
const config = readWebPushConfig();
|
|
1813
|
-
return
|
|
2114
|
+
return {
|
|
1814
2115
|
...config ? { publicKey: config.publicKey } : void 0,
|
|
1815
2116
|
deviceCount: subscriptions.length,
|
|
1816
2117
|
schedule,
|
|
1817
2118
|
slackPausedNow,
|
|
1818
2119
|
timezone,
|
|
1819
2120
|
timezoneSource: source
|
|
1820
|
-
}
|
|
2121
|
+
};
|
|
1821
2122
|
}
|
|
1822
2123
|
async function settingsResponse(userId) {
|
|
1823
2124
|
return jsonResponse(notificationSettingsSchema, await readSettings(userId));
|
|
@@ -1929,7 +2230,6 @@ function summaryFromRow(row, options = {}) {
|
|
|
1929
2230
|
...row.parentConversationId ? { parentConversationId: row.parentConversationId } : void 0,
|
|
1930
2231
|
...row.archivedAt ? { archivedAtMs: row.archivedAt.getTime() } : void 0,
|
|
1931
2232
|
...row.source ? { source: row.source } : void 0,
|
|
1932
|
-
...row.stoppedAt ? { stoppedAtMs: row.stoppedAt.getTime() } : void 0,
|
|
1933
2233
|
...row.title ? { title: row.title } : void 0
|
|
1934
2234
|
};
|
|
1935
2235
|
return conversationSummaryFromStoredConversation({
|
|
@@ -1938,6 +2238,7 @@ function summaryFromRow(row, options = {}) {
|
|
|
1938
2238
|
conversation,
|
|
1939
2239
|
durationMs: options.metrics?.durationMs ?? row.durationMs,
|
|
1940
2240
|
firstHumanMessageText: options.firstHumanMessageText,
|
|
2241
|
+
status: row.status,
|
|
1941
2242
|
...options.access?.visibility === "public" && row.destinationId ? { locationId: row.destinationId } : void 0,
|
|
1942
2243
|
usage: options.metrics?.usage ?? row.usage ?? void 0
|
|
1943
2244
|
});
|
|
@@ -2144,7 +2445,6 @@ async function recentLocationRows(db, locationId) {
|
|
|
2144
2445
|
${juniorIdentities.email}
|
|
2145
2446
|
)`,
|
|
2146
2447
|
executionStatus: juniorConversations.executionStatus,
|
|
2147
|
-
stoppedAt: juniorConversations.stoppedAt,
|
|
2148
2448
|
executionUpdatedAt: juniorConversations.executionUpdatedAt,
|
|
2149
2449
|
fullName: juniorUsers.displayName,
|
|
2150
2450
|
kind: juniorConversations.kind,
|
|
@@ -2158,6 +2458,7 @@ async function recentLocationRows(db, locationId) {
|
|
|
2158
2458
|
ELSE NULL
|
|
2159
2459
|
END`,
|
|
2160
2460
|
source: juniorConversations.source,
|
|
2461
|
+
status: conversationStatusSql(juniorConversations),
|
|
2161
2462
|
title: juniorConversations.title,
|
|
2162
2463
|
updatedAt: juniorConversations.updatedAt,
|
|
2163
2464
|
usage: juniorConversations.usage
|
|
@@ -2239,7 +2540,7 @@ async function readLocationDetailFromSql(locationId, options = {}) {
|
|
|
2239
2540
|
actors.push(item);
|
|
2240
2541
|
}
|
|
2241
2542
|
const activity = activityDays$1(days, nowMs, ACTIVITY_DAYS$1);
|
|
2242
|
-
const hourlyActivity = activityHours$
|
|
2543
|
+
const hourlyActivity = activityHours$2(hours, nowMs);
|
|
2243
2544
|
const recentConversationIds = recentRows.map((row) => row.conversationId);
|
|
2244
2545
|
const [accessByConversation, metricsByRoot, automationTitleByConversation, firstHumanMessageTextByConversation] = await Promise.all([
|
|
2245
2546
|
readConversationAccessFromSql(getDb(), recentConversationIds, options.viewer),
|
|
@@ -2265,26 +2566,15 @@ async function readLocationDetailFromSql(locationId, options = {}) {
|
|
|
2265
2566
|
windowStart: activity[0] ? `${activity[0].date}T00:00:00.000Z` : end.toISOString()
|
|
2266
2567
|
};
|
|
2267
2568
|
}
|
|
2268
|
-
// src/api/locations/detail.ts
|
|
2269
|
-
/** Expose operational detail for one persisted public conversation location. */
|
|
2270
|
-
async function readLocationDetail(locationId, options = {}) {
|
|
2271
|
-
const report = await readLocationDetailFromSql(locationId, options);
|
|
2272
|
-
return report ? locationDetailReportSchema.parse(report) : void 0;
|
|
2273
|
-
}
|
|
2274
|
-
// src/api/locations/list.ts
|
|
2275
|
-
/** Expose public conversation destinations as the dashboard's location index. */
|
|
2276
|
-
async function readLocationDirectory() {
|
|
2277
|
-
return locationDirectoryReportSchema.parse(await readLocationDirectoryFromSql());
|
|
2278
|
-
}
|
|
2279
2569
|
// src/api/locations/routes.ts
|
|
2280
2570
|
/** Create the HTTP routes owned by the locations API. */
|
|
2281
2571
|
function createLocationRoutes() {
|
|
2282
2572
|
const app = new Hono();
|
|
2283
|
-
app.get("/", async () => jsonResponse(locationDirectoryReportSchema, await
|
|
2573
|
+
app.get("/", async () => jsonResponse(locationDirectoryReportSchema, await readLocationDirectoryFromSql()));
|
|
2284
2574
|
app.get("/:locationId", validateRequest("param", locationParamsSchema, "Invalid route parameters."), async (context) => {
|
|
2285
2575
|
const { locationId } = context.req.valid("param");
|
|
2286
2576
|
const viewer = context.get("viewer");
|
|
2287
|
-
const report = await
|
|
2577
|
+
const report = await readLocationDetailFromSql(locationId, viewer ? { viewer } : {});
|
|
2288
2578
|
if (!report) throwApiError(404, "Location not found.");
|
|
2289
2579
|
return jsonResponse(locationDetailReportSchema, report);
|
|
2290
2580
|
});
|
|
@@ -2443,32 +2733,6 @@ function createImageRoutes() {
|
|
|
2443
2733
|
});
|
|
2444
2734
|
return app;
|
|
2445
2735
|
}
|
|
2446
|
-
// src/api/people/code.ts
|
|
2447
|
-
/** Read person-scoped native code activity for one People profile. */
|
|
2448
|
-
async function readPeopleCode(email, cursor) {
|
|
2449
|
-
const subject = await findUserByEmail(email);
|
|
2450
|
-
if (!subject) {
|
|
2451
|
-
const now = /* @__PURE__ */ new Date();
|
|
2452
|
-
return codePersonReportSchema.parse({
|
|
2453
|
-
activityDays: [],
|
|
2454
|
-
changes: [],
|
|
2455
|
-
generatedAt: now.toISOString(),
|
|
2456
|
-
summary: {
|
|
2457
|
-
closed: 0,
|
|
2458
|
-
created: 0,
|
|
2459
|
-
idle: 0,
|
|
2460
|
-
merged: 0,
|
|
2461
|
-
open: 0
|
|
2462
|
-
},
|
|
2463
|
-
windowEnd: now.toISOString(),
|
|
2464
|
-
windowStart: (/* @__PURE__ */ new Date(now.getTime() - 2592e6)).toISOString()
|
|
2465
|
-
});
|
|
2466
|
-
}
|
|
2467
|
-
return await readPersonCodeOverview({
|
|
2468
|
-
cursor,
|
|
2469
|
-
userId: subject.id
|
|
2470
|
-
});
|
|
2471
|
-
}
|
|
2472
2736
|
const metrics$1 = juniorConversationMetrics;
|
|
2473
2737
|
/** Sum the values of one metric among grouped metric rows. */
|
|
2474
2738
|
function metricSum(metric) {
|
|
@@ -2525,14 +2789,10 @@ function personRootJoin(roots) {
|
|
|
2525
2789
|
*/
|
|
2526
2790
|
function rootAggregateColumns(roots) {
|
|
2527
2791
|
return {
|
|
2528
|
-
active: sql`(count(*) FILTER (
|
|
2529
|
-
WHERE ${turnRoot.executionStatus} NOT IN ('idle', 'failed')
|
|
2530
|
-
))::integer`,
|
|
2792
|
+
active: sql`(count(*) FILTER (WHERE ${conversationIsActiveSql(turnRoot)}))::integer`,
|
|
2531
2793
|
conversations: sql`count(*)::integer`,
|
|
2532
2794
|
durationMs: sql`COALESCE(sum(${roots.durationMs}), 0)::double precision`,
|
|
2533
|
-
failed: sql`(count(*) FILTER (
|
|
2534
|
-
WHERE ${turnRoot.executionStatus} = 'failed' AND ${turnRoot.stoppedAt} IS NULL
|
|
2535
|
-
))::integer`,
|
|
2795
|
+
failed: sql`(count(*) FILTER (WHERE ${conversationTurnFailedSql(turnRoot)} AND ${turnRoot.stoppedAt} IS NULL))::integer`,
|
|
2536
2796
|
tokens: sql`sum(${roots.tokens})::double precision`
|
|
2537
2797
|
};
|
|
2538
2798
|
}
|
|
@@ -2647,7 +2907,6 @@ async function recentActorRows(email) {
|
|
|
2647
2907
|
durationMs: juniorConversations.durationMs,
|
|
2648
2908
|
email: juniorUsers.primaryEmailNormalized,
|
|
2649
2909
|
executionStatus: juniorConversations.executionStatus,
|
|
2650
|
-
stoppedAt: juniorConversations.stoppedAt,
|
|
2651
2910
|
executionUpdatedAt: juniorConversations.executionUpdatedAt,
|
|
2652
2911
|
fullName: juniorUsers.displayName,
|
|
2653
2912
|
kind: juniorConversations.kind,
|
|
@@ -2657,15 +2916,140 @@ async function recentActorRows(email) {
|
|
|
2657
2916
|
lastActivityAt: juniorConversations.lastActivityAt,
|
|
2658
2917
|
providerSubjectId: sql`CASE WHEN ${juniorIdentities.provider} = 'slack' THEN ${juniorIdentities.providerSubjectId} END`,
|
|
2659
2918
|
source: juniorConversations.source,
|
|
2919
|
+
status: conversationStatusSql(juniorConversations),
|
|
2660
2920
|
title: juniorConversations.title,
|
|
2661
2921
|
updatedAt: juniorConversations.updatedAt,
|
|
2662
2922
|
usage: juniorConversations.usage
|
|
2663
2923
|
}).from(lastTurns).innerJoin(juniorConversations, eq(juniorConversations.conversationId, lastTurns.conversationId)).leftJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).leftJoin(juniorDestinations, eq(juniorDestinations.id, juniorConversations.destinationId)).orderBy(desc(lastTurns.lastTurnAt), asc(juniorConversations.conversationId)).limit(25);
|
|
2664
2924
|
}
|
|
2925
|
+
// src/api/people/card.ts
|
|
2926
|
+
const RECENT_DAYS = 30;
|
|
2927
|
+
const RECENT_CANDIDATES = 10;
|
|
2928
|
+
const DAY_MS$1 = 864e5;
|
|
2929
|
+
const CARD_TTL_MS = 6e4;
|
|
2930
|
+
function personCardTurns(email, since) {
|
|
2931
|
+
return getDb().select({
|
|
2932
|
+
occurredAt: juniorConversationMetrics.occurredAt,
|
|
2933
|
+
rootConversationId: sql`coalesce(
|
|
2934
|
+
${juniorConversations.rootConversationId},
|
|
2935
|
+
${juniorConversations.conversationId}
|
|
2936
|
+
)`.as("card_root_conversation_id")
|
|
2937
|
+
}).from(juniorConversationMetrics).innerJoin(juniorConversations, eq(juniorConversations.conversationId, juniorConversationMetrics.conversationId)).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversationMetrics.actorIdentityId)).innerJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(and(verifiedActorWhere(email), eq(juniorConversationMetrics.metric, "duration_ms"), gte(juniorConversationMetrics.occurredAt, since))).as("person_card_turns");
|
|
2938
|
+
}
|
|
2939
|
+
async function readPersonActivity(email, viewer, nowMs) {
|
|
2940
|
+
const turns = personCardTurns(email, /* @__PURE__ */ new Date(nowMs - RECENT_DAYS * DAY_MS$1));
|
|
2941
|
+
const lastTurns = getDb().select({
|
|
2942
|
+
lastTurnAt: sql`max(${turns.occurredAt})`.as("card_last_turn_at"),
|
|
2943
|
+
rootConversationId: turns.rootConversationId
|
|
2944
|
+
}).from(turns).groupBy(turns.rootConversationId).as("person_card_roots");
|
|
2945
|
+
const recentRows = await getDb().select({
|
|
2946
|
+
archivedAt: juniorConversations.archivedAt,
|
|
2947
|
+
channelName: juniorConversations.channelName,
|
|
2948
|
+
conversationId: juniorConversations.conversationId,
|
|
2949
|
+
createdAt: juniorConversations.createdAt,
|
|
2950
|
+
durationMs: juniorConversations.durationMs,
|
|
2951
|
+
executionStatus: juniorConversations.executionStatus,
|
|
2952
|
+
executionUpdatedAt: juniorConversations.executionUpdatedAt,
|
|
2953
|
+
kind: juniorConversations.kind,
|
|
2954
|
+
lastActivityAt: juniorConversations.lastActivityAt,
|
|
2955
|
+
lastTurnAt: sql`${lastTurns.lastTurnAt}`.mapWith(juniorConversationMetrics.occurredAt),
|
|
2956
|
+
parentConversationId: juniorConversations.parentConversationId,
|
|
2957
|
+
source: juniorConversations.source,
|
|
2958
|
+
status: conversationStatusSql(juniorConversations),
|
|
2959
|
+
stoppedAt: juniorConversations.stoppedAt,
|
|
2960
|
+
title: juniorConversations.title,
|
|
2961
|
+
updatedAt: juniorConversations.updatedAt,
|
|
2962
|
+
usage: juniorConversations.usage
|
|
2963
|
+
}).from(lastTurns).innerJoin(juniorConversations, eq(juniorConversations.conversationId, lastTurns.rootConversationId)).orderBy(desc(lastTurns.lastTurnAt), asc(juniorConversations.conversationId)).limit(RECENT_CANDIDATES);
|
|
2964
|
+
const access = await readConversationAccessFromSql(getDb(), recentRows.map((row) => row.conversationId), viewer);
|
|
2965
|
+
const recentConversations = recentRows.flatMap(({ lastTurnAt, ...row }) => {
|
|
2966
|
+
const rowAccess = access.get(row.conversationId);
|
|
2967
|
+
if (!rowAccess?.canViewPrivateContent) return [];
|
|
2968
|
+
const summary = summaryFromRow({
|
|
2969
|
+
...row,
|
|
2970
|
+
destinationId: rowAccess.destinationId ?? null,
|
|
2971
|
+
email: null,
|
|
2972
|
+
fullName: null,
|
|
2973
|
+
handle: null,
|
|
2974
|
+
providerSubjectId: null
|
|
2975
|
+
}, { access: rowAccess });
|
|
2976
|
+
return [{
|
|
2977
|
+
conversationId: row.conversationId,
|
|
2978
|
+
lastTurnAt: lastTurnAt.toISOString(),
|
|
2979
|
+
title: summary.displayTitle
|
|
2980
|
+
}];
|
|
2981
|
+
}).slice(0, 3);
|
|
2982
|
+
const lastActiveAt = recentRows[0]?.lastTurnAt;
|
|
2983
|
+
return {
|
|
2984
|
+
...lastActiveAt ? { lastActiveAt: lastActiveAt.toISOString() } : void 0,
|
|
2985
|
+
recentConversations
|
|
2986
|
+
};
|
|
2987
|
+
}
|
|
2988
|
+
/**
|
|
2989
|
+
* Read the card of one person for a viewer: their object card, the code
|
|
2990
|
+
* changes they merged most recently, and their recent Junior activity. Each
|
|
2991
|
+
* viewer and person pair is cached briefly, so a reader who hovers the same
|
|
2992
|
+
* person again reads nothing.
|
|
2993
|
+
*/
|
|
2994
|
+
async function readPersonCard(email, viewer) {
|
|
2995
|
+
const normalizedEmail = normalizeEmail$1(email);
|
|
2996
|
+
if (!normalizedEmail) return {
|
|
2997
|
+
activity: { recentConversations: [] },
|
|
2998
|
+
mergedChanges: []
|
|
2999
|
+
};
|
|
3000
|
+
const link = getDashboardPersonLink(normalizedEmail);
|
|
3001
|
+
const key = `${viewer.id}:${createHash("sha256").update(normalizedEmail).digest("hex")}`;
|
|
3002
|
+
return createCache(getStateAdapter(), "person-cards").getOrLoad(key, async () => {
|
|
3003
|
+
const [card, activity, mergedChanges] = await Promise.all([
|
|
3004
|
+
link ? resolvePersonLink(new URL(link)) : void 0,
|
|
3005
|
+
readPersonActivity(normalizedEmail, viewer, Date.now()),
|
|
3006
|
+
readPersonMergedChanges({
|
|
3007
|
+
email: normalizedEmail,
|
|
3008
|
+
limit: 3
|
|
3009
|
+
})
|
|
3010
|
+
]);
|
|
3011
|
+
const value = {
|
|
3012
|
+
activity,
|
|
3013
|
+
...card ? { card: {
|
|
3014
|
+
...card,
|
|
3015
|
+
plugin: "junior"
|
|
3016
|
+
} } : void 0,
|
|
3017
|
+
mergedChanges
|
|
3018
|
+
};
|
|
3019
|
+
return {
|
|
3020
|
+
ttlMs: CARD_TTL_MS,
|
|
3021
|
+
value
|
|
3022
|
+
};
|
|
3023
|
+
});
|
|
3024
|
+
}
|
|
3025
|
+
// src/api/people/code.ts
|
|
3026
|
+
/** Read person-scoped native code activity for one People profile. */
|
|
3027
|
+
async function readPeopleCode(email, cursor) {
|
|
3028
|
+
const subject = await findUserByEmail(email);
|
|
3029
|
+
if (!subject) {
|
|
3030
|
+
const now = /* @__PURE__ */ new Date();
|
|
3031
|
+
return {
|
|
3032
|
+
activityDays: [],
|
|
3033
|
+
changes: [],
|
|
3034
|
+
generatedAt: now.toISOString(),
|
|
3035
|
+
summary: {
|
|
3036
|
+
closed: 0,
|
|
3037
|
+
created: 0,
|
|
3038
|
+
idle: 0,
|
|
3039
|
+
merged: 0,
|
|
3040
|
+
open: 0
|
|
3041
|
+
},
|
|
3042
|
+
windowEnd: now.toISOString(),
|
|
3043
|
+
windowStart: (/* @__PURE__ */ new Date(now.getTime() - 2592e6)).toISOString()
|
|
3044
|
+
};
|
|
3045
|
+
}
|
|
3046
|
+
return await readPersonCodeOverview({
|
|
3047
|
+
cursor,
|
|
3048
|
+
userId: subject.id
|
|
3049
|
+
});
|
|
3050
|
+
}
|
|
2665
3051
|
// src/api/people/list.query.ts
|
|
2666
3052
|
const DIRECTORY_ACTIVITY_DAYS = 90;
|
|
2667
|
-
/** Day ranges need the prior equal period too (90d + prior 90d). */
|
|
2668
|
-
const DAY_METRIC_LOOKBACK = 180;
|
|
2669
3053
|
const metrics = juniorConversationMetrics;
|
|
2670
3054
|
function emptyDirectoryDay(date) {
|
|
2671
3055
|
return {
|
|
@@ -2674,6 +3058,14 @@ function emptyDirectoryDay(date) {
|
|
|
2674
3058
|
date
|
|
2675
3059
|
};
|
|
2676
3060
|
}
|
|
3061
|
+
/** Pick one series from activity rows, without the unit. */
|
|
3062
|
+
function activitySeries(rows, unit) {
|
|
3063
|
+
return rows.filter((row) => row.unit === unit).map(({ activePeople, conversations, date }) => ({
|
|
3064
|
+
activePeople,
|
|
3065
|
+
conversations,
|
|
3066
|
+
date
|
|
3067
|
+
}));
|
|
3068
|
+
}
|
|
2677
3069
|
function directoryActivityDays(rows, nowMs) {
|
|
2678
3070
|
return fillUtcDays({
|
|
2679
3071
|
count: DIRECTORY_ACTIVITY_DAYS,
|
|
@@ -2701,21 +3093,50 @@ function directoryActivitySixHours(rows, nowMs) {
|
|
|
2701
3093
|
function rangeStart(nowMs, range) {
|
|
2702
3094
|
return range === 1 ? trailingUtcHourWindow(nowMs, 24).start : trailingUtcDayWindow(nowMs, range).start;
|
|
2703
3095
|
}
|
|
3096
|
+
/** Start of the prior period of each range, of equal length. */
|
|
3097
|
+
function rangePriorStart(nowMs, range) {
|
|
3098
|
+
return new Date(rangeStart(nowMs, range).getTime() - (range === 1 ? 24 * HOUR_MS$3 : range * DAY_MS$3));
|
|
3099
|
+
}
|
|
2704
3100
|
/**
|
|
2705
|
-
* Sum one
|
|
2706
|
-
* period
|
|
3101
|
+
* Sum one metric of one range: the current period and, for cost, the prior
|
|
3102
|
+
* period. A column that does not apply to the metric is null, so the cost
|
|
3103
|
+
* and duration branches of `identitySpend` have the same columns.
|
|
2707
3104
|
*/
|
|
2708
|
-
function
|
|
3105
|
+
function rangeSpendSums(nowMs, range, metric) {
|
|
2709
3106
|
const start = rangeStart(nowMs, range);
|
|
2710
|
-
const
|
|
2711
|
-
const
|
|
2712
|
-
const
|
|
2713
|
-
|
|
2714
|
-
const
|
|
3107
|
+
const sumWhere = (when) => sql`sum(${metrics.value}) FILTER (WHERE ${when})`;
|
|
3108
|
+
const none = sql`NULL::double precision`;
|
|
3109
|
+
const current = sumWhere(gte(metrics.occurredAt, start));
|
|
3110
|
+
const prior = sumWhere(and(gte(metrics.occurredAt, rangePriorStart(nowMs, range)), lt(metrics.occurredAt, start)));
|
|
3111
|
+
const cost = metric === "cost_micro_usd";
|
|
2715
3112
|
return {
|
|
2716
|
-
costMicroUsd:
|
|
2717
|
-
durationMs:
|
|
2718
|
-
priorCostMicroUsd:
|
|
3113
|
+
costMicroUsd: (cost ? current : none).as(`cost_micro_usd_${range}`),
|
|
3114
|
+
durationMs: (cost ? none : current).as(`duration_ms_${range}`),
|
|
3115
|
+
priorCostMicroUsd: (cost ? prior : none).as(`prior_cost_micro_usd_${range}`)
|
|
3116
|
+
};
|
|
3117
|
+
}
|
|
3118
|
+
/**
|
|
3119
|
+
* Sum each identity's spend in every range in one pass over the metric
|
|
3120
|
+
* rows, grouped before any join. Cost and duration are separate branches,
|
|
3121
|
+
* so each row checks only its own metric's periods, and duration rows are
|
|
3122
|
+
* read only for the longest current period.
|
|
3123
|
+
*/
|
|
3124
|
+
function identitySpend(nowMs) {
|
|
3125
|
+
const byIdentity = (metric, since) => getDb().select({
|
|
3126
|
+
identityId: sql`${metrics.actorIdentityId}`.as("identity_totals_id"),
|
|
3127
|
+
1: rangeSpendSums(nowMs, 1, metric),
|
|
3128
|
+
7: rangeSpendSums(nowMs, 7, metric),
|
|
3129
|
+
30: rangeSpendSums(nowMs, 30, metric),
|
|
3130
|
+
90: rangeSpendSums(nowMs, 90, metric)
|
|
3131
|
+
}).from(metrics).where(and(eq(metrics.metric, metric), gte(metrics.occurredAt, since))).groupBy(metrics.actorIdentityId);
|
|
3132
|
+
return byIdentity("cost_micro_usd", rangePriorStart(nowMs, 90)).unionAll(byIdentity("duration_ms", rangeStart(nowMs, 90))).as("person_identity_totals");
|
|
3133
|
+
}
|
|
3134
|
+
/** Sum one range of a person's spend over their identities. */
|
|
3135
|
+
function rangeSpendColumns(spend) {
|
|
3136
|
+
return {
|
|
3137
|
+
costMicroUsd: microUsdSql(sql`sum(${spend.costMicroUsd})`),
|
|
3138
|
+
durationMs: sql`COALESCE(sum(${spend.durationMs}), 0)::double precision`,
|
|
3139
|
+
priorCostMicroUsd: microUsdSql(sql`sum(${spend.priorCostMicroUsd})`)
|
|
2719
3140
|
};
|
|
2720
3141
|
}
|
|
2721
3142
|
function rangeWindow(spend, conversations) {
|
|
@@ -2727,23 +3148,39 @@ function rangeWindow(spend, conversations) {
|
|
|
2727
3148
|
};
|
|
2728
3149
|
}
|
|
2729
3150
|
/**
|
|
2730
|
-
* Count active people and root Conversations in each bucket
|
|
2731
|
-
*
|
|
3151
|
+
* Count active people and root Conversations in each bucket of each series,
|
|
3152
|
+
* from one read of the Turns since `since`. The time bound applies to the
|
|
3153
|
+
* metric rows before any join. Six-hour buckets roll up hour buckets.
|
|
3154
|
+
*
|
|
3155
|
+
* Each count is a hashed `DISTINCT` of (bucket, person) or (bucket, root)
|
|
3156
|
+
* pairs, which costs less than sorting for `COUNT(DISTINCT)`.
|
|
2732
3157
|
*/
|
|
2733
|
-
function activityRows(since,
|
|
3158
|
+
function activityRows(since, read) {
|
|
2734
3159
|
const utc = sql`(${metrics.occurredAt} AT TIME ZONE 'UTC')`;
|
|
2735
|
-
const
|
|
2736
|
-
const
|
|
2737
|
-
|
|
2738
|
-
bucket: bucket.as("activity_bucket"),
|
|
3160
|
+
const readBucket = sql`date_trunc(${sql.raw(`'${read}'`)}, ${utc})`;
|
|
3161
|
+
const turns = getDb().$with("activity_turns").as(getDb().select({
|
|
3162
|
+
bucket: readBucket.as("activity_bucket"),
|
|
2739
3163
|
userId: sql`${juniorUsers.id}`.as("activity_user_id"),
|
|
2740
3164
|
rootConversationId: conversationRootId.as("activity_root_id")
|
|
2741
|
-
}).from(metrics).innerJoin(juniorIdentities, eq(juniorIdentities.id, metrics.actorIdentityId)).innerJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).innerJoin(juniorConversations, eq(juniorConversations.conversationId, metrics.conversationId)).where(and(verifiedActorWhere(), eq(metrics.metric, "duration_ms"), gte(metrics.occurredAt, since))).groupBy(
|
|
2742
|
-
|
|
2743
|
-
|
|
2744
|
-
|
|
2745
|
-
|
|
2746
|
-
|
|
3165
|
+
}).from(metrics).innerJoin(juniorIdentities, eq(juniorIdentities.id, metrics.actorIdentityId)).innerJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).innerJoin(juniorConversations, eq(juniorConversations.conversationId, metrics.conversationId)).where(and(verifiedActorWhere(), eq(metrics.metric, "duration_ms"), gte(metrics.occurredAt, since))).groupBy(readBucket, juniorUsers.id, conversationRootId));
|
|
3166
|
+
const unitCounts = (unit) => {
|
|
3167
|
+
const bucket = unit === "six_hour" ? sql`date_trunc('day', ${turns.bucket}) + FLOOR(EXTRACT(HOUR FROM ${turns.bucket}) / 6) * INTERVAL '6 hours'` : sql`${turns.bucket}`;
|
|
3168
|
+
const pairs = (kind, id) => getDb().selectDistinct({
|
|
3169
|
+
bucket: bucket.as("pair_bucket"),
|
|
3170
|
+
kind: sql`${kind}::text`.as("pair_kind"),
|
|
3171
|
+
id: sql`${id}`.as("pair_id")
|
|
3172
|
+
}).from(turns);
|
|
3173
|
+
const allPairs = pairs("people", sql`${turns.userId}`).unionAll(pairs("conversations", sql`${turns.rootConversationId}`)).as("activity_pairs");
|
|
3174
|
+
const format = unit === "day" ? "YYYY-MM-DD" : "YYYY-MM-DD\"T\"HH24";
|
|
3175
|
+
return getDb().select({
|
|
3176
|
+
unit: sql`${unit}::text`.as("activity_unit"),
|
|
3177
|
+
activePeople: sql`(count(*) FILTER (WHERE ${allPairs.kind} = 'people'))::int`.as("activity_people"),
|
|
3178
|
+
conversations: sql`(count(*) FILTER (WHERE ${allPairs.kind} = 'conversations'))::int`.as("activity_conversations"),
|
|
3179
|
+
date: sql`TO_CHAR(${allPairs.bucket}, ${sql.raw(`'${format}'`)})`.as("activity_date")
|
|
3180
|
+
}).from(allPairs).groupBy(allPairs.bucket);
|
|
3181
|
+
};
|
|
3182
|
+
const counts = read === "day" ? unitCounts("day").as("activity_counts") : unitCounts("hour").unionAll(unitCounts("six_hour")).as("activity_counts");
|
|
3183
|
+
return getDb().with(turns).select().from(counts);
|
|
2747
3184
|
}
|
|
2748
3185
|
/**
|
|
2749
3186
|
* Read one row per verified person who ever ran a Turn: their identity and
|
|
@@ -2801,10 +3238,12 @@ async function readPeopleListFromSql() {
|
|
|
2801
3238
|
const { end, start } = trailingUtcDayWindow(nowMs, DIRECTORY_ACTIVITY_DAYS);
|
|
2802
3239
|
const hourWindow = trailingUtcHourWindow(nowMs, 168);
|
|
2803
3240
|
const sixHourWindow = trailingUtcSixHourWindow(nowMs);
|
|
3241
|
+
const hourlySince = new Date(Math.min(hourWindow.start.getTime(), sixHourWindow.start.getTime()));
|
|
2804
3242
|
const range = personTurnRange();
|
|
2805
3243
|
const counts = personRangeConversations(nowMs, start);
|
|
3244
|
+
const spendByIdentity = identitySpend(nowMs);
|
|
2806
3245
|
const rangeCount = (column) => sql`COALESCE(${column}, 0)::integer`;
|
|
2807
|
-
const [rows, activityDayRows,
|
|
3246
|
+
const [rows, activityDayRows, activityHourAndSixHourRows, spend] = await Promise.all([
|
|
2808
3247
|
getDb().select({
|
|
2809
3248
|
email: range.email,
|
|
2810
3249
|
fullName: range.fullName,
|
|
@@ -2818,15 +3257,14 @@ async function readPeopleListFromSql() {
|
|
|
2818
3257
|
conversations90: rangeCount(counts.conversations90)
|
|
2819
3258
|
}).from(range).leftJoin(counts, eq(counts.userId, range.userId)),
|
|
2820
3259
|
activityRows(start, "day"),
|
|
2821
|
-
activityRows(
|
|
2822
|
-
activityRows(sixHourWindow.start, "six_hour"),
|
|
3260
|
+
activityRows(hourlySince, "hour"),
|
|
2823
3261
|
getDb().select({
|
|
2824
3262
|
email: sql`${juniorUsers.primaryEmailNormalized}`,
|
|
2825
|
-
1: rangeSpendColumns(
|
|
2826
|
-
7: rangeSpendColumns(
|
|
2827
|
-
30: rangeSpendColumns(
|
|
2828
|
-
90: rangeSpendColumns(
|
|
2829
|
-
}).from(
|
|
3263
|
+
1: rangeSpendColumns(spendByIdentity[1]),
|
|
3264
|
+
7: rangeSpendColumns(spendByIdentity[7]),
|
|
3265
|
+
30: rangeSpendColumns(spendByIdentity[30]),
|
|
3266
|
+
90: rangeSpendColumns(spendByIdentity[90])
|
|
3267
|
+
}).from(spendByIdentity).innerJoin(juniorIdentities, eq(juniorIdentities.id, spendByIdentity.identityId)).innerJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(verifiedActorWhere()).groupBy(juniorUsers.id)
|
|
2830
3268
|
]);
|
|
2831
3269
|
const spendByEmail = new Map(spend.map((row) => [row.email, row]));
|
|
2832
3270
|
const people = rows.map((row) => {
|
|
@@ -2850,9 +3288,9 @@ async function readPeopleListFromSql() {
|
|
|
2850
3288
|
};
|
|
2851
3289
|
});
|
|
2852
3290
|
return {
|
|
2853
|
-
activityDays: directoryActivityDays(activityDayRows, nowMs),
|
|
2854
|
-
activityHours: directoryActivityHours(
|
|
2855
|
-
activitySixHours: directoryActivitySixHours(
|
|
3291
|
+
activityDays: directoryActivityDays(activitySeries(activityDayRows, "day"), nowMs),
|
|
3292
|
+
activityHours: directoryActivityHours(activitySeries(activityHourAndSixHourRows, "hour"), nowMs),
|
|
3293
|
+
activitySixHours: directoryActivitySixHours(activitySeries(activityHourAndSixHourRows, "six_hour"), nowMs),
|
|
2856
3294
|
generatedAt: new Date(nowMs).toISOString(),
|
|
2857
3295
|
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)),
|
|
2858
3296
|
source: "conversation_index",
|
|
@@ -2861,10 +3299,16 @@ async function readPeopleListFromSql() {
|
|
|
2861
3299
|
};
|
|
2862
3300
|
}
|
|
2863
3301
|
// src/api/people/list.ts
|
|
2864
|
-
/**
|
|
2865
|
-
|
|
2866
|
-
|
|
2867
|
-
|
|
3302
|
+
/**
|
|
3303
|
+
* Load the people list from verified user identities in SQL. Every viewer
|
|
3304
|
+
* gets the same list, so one cached copy serves them all.
|
|
3305
|
+
*/
|
|
3306
|
+
const readPeopleList = createCachedReport({
|
|
3307
|
+
key: "people-list",
|
|
3308
|
+
read: readPeopleListFromSql,
|
|
3309
|
+
refreshFailedEvent: "people_list.refresh.failed",
|
|
3310
|
+
schema: actorDirectoryReportSchema
|
|
3311
|
+
});
|
|
2868
3312
|
// src/api/people/plugin-reports.ts
|
|
2869
3313
|
/** Read sanitized person-scoped plugin reports for one profile subject. */
|
|
2870
3314
|
async function readPeoplePluginReports(args) {
|
|
@@ -2875,7 +3319,7 @@ async function readPeoplePluginReports(args) {
|
|
|
2875
3319
|
reports: [],
|
|
2876
3320
|
source: "plugins"
|
|
2877
3321
|
});
|
|
2878
|
-
const { getPluginProfileReports } = await import("./projection-
|
|
3322
|
+
const { getPluginProfileReports } = await import("./projection-Cns7XwWa.js").then((n) => n.En);
|
|
2879
3323
|
return pluginOperationalReportFeedSchema.parse({
|
|
2880
3324
|
generatedAt: new Date(nowMs).toISOString(),
|
|
2881
3325
|
reports: await getPluginProfileReports({
|
|
@@ -2988,16 +3432,14 @@ function rootBucketRows(args) {
|
|
|
2988
3432
|
}).from(rootBuckets).as("person_buckets");
|
|
2989
3433
|
return getDb().select({
|
|
2990
3434
|
active: sql`(count(*) FILTER (
|
|
2991
|
-
WHERE ${buckets.isLastTurn} AND ${turnRoot
|
|
3435
|
+
WHERE ${buckets.isLastTurn} AND ${conversationIsActiveSql(turnRoot)}
|
|
2992
3436
|
))::integer`,
|
|
2993
3437
|
conversations: sql`count(*)::integer`,
|
|
2994
3438
|
costMicroUsd: microUsdSql(sql`sum(${buckets.costMicroUsd})`),
|
|
2995
3439
|
date: sql`TO_CHAR(${buckets.bucket}, ${sql.raw(`'${format}'`)})`,
|
|
2996
3440
|
durationMs: sql`COALESCE(sum(${buckets.durationMs}), 0)::double precision`,
|
|
2997
3441
|
failed: sql`(count(*) FILTER (
|
|
2998
|
-
WHERE ${buckets.isLastTurn}
|
|
2999
|
-
AND ${turnRoot.executionStatus} = 'failed'
|
|
3000
|
-
AND ${turnRoot.stoppedAt} IS NULL
|
|
3442
|
+
WHERE ${buckets.isLastTurn} AND ${conversationTurnFailedSql(turnRoot)} AND ${turnRoot.stoppedAt} IS NULL
|
|
3001
3443
|
))::integer`,
|
|
3002
3444
|
tokens: sql`sum(${buckets.tokens})::double precision`
|
|
3003
3445
|
}).from(buckets).innerJoin(turnRoot, eq(turnRoot.conversationId, buckets.rootConversationId)).where(sql`${buckets.bucket} >= (${args.since.toISOString()}::timestamptz AT TIME ZONE 'UTC')`).groupBy(buckets.bucket);
|
|
@@ -3089,10 +3531,52 @@ async function readPeopleProfileFromSql(email, options = {}) {
|
|
|
3089
3531
|
windowStart: start.toISOString()
|
|
3090
3532
|
};
|
|
3091
3533
|
}
|
|
3092
|
-
// src/api/people/
|
|
3093
|
-
|
|
3094
|
-
|
|
3095
|
-
|
|
3534
|
+
// src/api/people/search.query.ts
|
|
3535
|
+
const PEOPLE_SEARCH_LIMIT = 8;
|
|
3536
|
+
const PEOPLE_SEARCH_TERMS = 4;
|
|
3537
|
+
/**
|
|
3538
|
+
* Find Slack people whose name or handle has a word that starts with each
|
|
3539
|
+
* word of the query, for the composer `@` menu. It reads one index
|
|
3540
|
+
* (`junior_identities_slack_person_search_idx`) and the photos of the
|
|
3541
|
+
* matches. With `slackTeamId`, it finds only people in that Slack
|
|
3542
|
+
* workspace. Without it, a person with Slack accounts in two workspaces
|
|
3543
|
+
* shows once.
|
|
3544
|
+
*/
|
|
3545
|
+
async function readPeopleSearchFromSql(query, slackTeamId) {
|
|
3546
|
+
const terms = (query.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? []).slice(0, PEOPLE_SEARCH_TERMS);
|
|
3547
|
+
if (terms.length === 0) return [];
|
|
3548
|
+
const tsquery = terms.map((term) => `${term}:*`).join(" & ");
|
|
3549
|
+
const db = getDb();
|
|
3550
|
+
const rows = await db.select({
|
|
3551
|
+
avatarUrl: juniorIdentities.avatarUrl,
|
|
3552
|
+
displayName: juniorIdentities.displayName,
|
|
3553
|
+
emailVerified: juniorIdentities.emailVerified,
|
|
3554
|
+
handle: juniorIdentities.handle,
|
|
3555
|
+
identityId: juniorIdentities.id,
|
|
3556
|
+
providerSubjectId: juniorIdentities.providerSubjectId,
|
|
3557
|
+
userDisplayName: juniorUsers.displayName,
|
|
3558
|
+
userEmail: juniorUsers.primaryEmail,
|
|
3559
|
+
userId: juniorIdentities.userId
|
|
3560
|
+
}).from(juniorIdentities).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(and(slackPersonPredicate(juniorIdentities), sql`${slackPersonSearchDocument(juniorIdentities)} @@ to_tsquery('simple', ${tsquery})`, slackTeamId ? eq(juniorIdentities.providerTenantId, slackTeamId) : void 0)).orderBy(asc(sql`lower(coalesce(${juniorUsers.displayName}, ${juniorIdentities.displayName}, ${juniorIdentities.handle}))`), asc(juniorIdentities.id)).limit(PEOPLE_SEARCH_LIMIT);
|
|
3561
|
+
const avatars = await readUserAvatarUrls(db, rows.flatMap((row) => row.userId ? [row.userId] : []));
|
|
3562
|
+
const seenUsers = /* @__PURE__ */ new Set();
|
|
3563
|
+
return rows.flatMap((row) => {
|
|
3564
|
+
if (row.userId) {
|
|
3565
|
+
if (seenUsers.has(row.userId)) return [];
|
|
3566
|
+
seenUsers.add(row.userId);
|
|
3567
|
+
}
|
|
3568
|
+
const fullName = row.userDisplayName?.trim() || row.displayName?.trim();
|
|
3569
|
+
const email = row.emailVerified ? row.userEmail?.trim() : void 0;
|
|
3570
|
+
const avatarUrl = identityAvatarUrl(row, avatars);
|
|
3571
|
+
return [{
|
|
3572
|
+
slackUserId: row.providerSubjectId,
|
|
3573
|
+
...row.userId ? { hasUser: true } : void 0,
|
|
3574
|
+
...fullName ? { fullName } : void 0,
|
|
3575
|
+
...row.handle ? { slackUserName: row.handle } : void 0,
|
|
3576
|
+
...email ? { email } : void 0,
|
|
3577
|
+
...avatarUrl ? { avatarUrl } : void 0
|
|
3578
|
+
}];
|
|
3579
|
+
});
|
|
3096
3580
|
}
|
|
3097
3581
|
// src/api/people/spend.query.ts
|
|
3098
3582
|
const SEVEN_DAY_OFFSET = 6;
|
|
@@ -3169,7 +3653,7 @@ async function readPersonalSpendFromSql(email, nowMs = Date.now()) {
|
|
|
3169
3653
|
}
|
|
3170
3654
|
// src/api/people/routes.ts
|
|
3171
3655
|
/** Create the HTTP routes owned by the People API. */
|
|
3172
|
-
function createPeopleRoutes() {
|
|
3656
|
+
function createPeopleRoutes(options) {
|
|
3173
3657
|
const app = new Hono();
|
|
3174
3658
|
app.get("/avatars/:identityId", requireViewer, validateRequest("param", avatarParamsSchema, "Invalid route parameters."), async (context) => {
|
|
3175
3659
|
const { identityId } = context.req.valid("param");
|
|
@@ -3184,7 +3668,12 @@ function createPeopleRoutes() {
|
|
|
3184
3668
|
const viewer = context.get("viewer");
|
|
3185
3669
|
return jsonResponse(personalSpendReportSchema, await readPersonalSpendFromSql(viewer.email));
|
|
3186
3670
|
});
|
|
3187
|
-
app.get("/", async () => jsonResponse(actorDirectoryReportSchema, await readPeopleList()));
|
|
3671
|
+
app.get("/", async () => jsonResponse(actorDirectoryReportSchema, await readPeopleList({ waitUntil: options.waitUntil })));
|
|
3672
|
+
app.get("/search", requireViewer, validateRequest("query", peopleSearchQuerySchema, "Invalid search query."), async (context) => {
|
|
3673
|
+
const { conversationId, q } = context.req.valid("query");
|
|
3674
|
+
const slackTeamId = conversationId ? readableSlackTeamId((await readConversationAccessFromSql(getDb(), [conversationId], context.get("viewer"))).get(conversationId)) : void 0;
|
|
3675
|
+
return jsonResponse(peopleSearchReportSchema, { people: await readPeopleSearchFromSql(q, slackTeamId) });
|
|
3676
|
+
});
|
|
3188
3677
|
app.get("/:email/plugin-reports", requireViewer, validateRequest("param", personParamsSchema, "Invalid route parameters."), async (context) => {
|
|
3189
3678
|
const { email } = context.req.valid("param");
|
|
3190
3679
|
const viewer = context.get("viewer");
|
|
@@ -3193,6 +3682,10 @@ function createPeopleRoutes() {
|
|
|
3193
3682
|
viewer
|
|
3194
3683
|
}));
|
|
3195
3684
|
});
|
|
3685
|
+
app.get("/:email/card", requireViewer, validateRequest("param", personParamsSchema, "Invalid route parameters."), async (context) => jsonResponse(personCardReportSchema, await readPersonCard(context.req.valid("param").email, context.get("viewer")), { headers: {
|
|
3686
|
+
"cache-control": "private, max-age=60",
|
|
3687
|
+
vary: "Authorization, Cookie"
|
|
3688
|
+
} }));
|
|
3196
3689
|
app.get("/:email/code", validateRequest("param", personParamsSchema, "Invalid route parameters."), validateRequest("query", personCodeQuerySchema, "Invalid code query."), async (context) => {
|
|
3197
3690
|
const { email } = context.req.valid("param");
|
|
3198
3691
|
const { cursor } = context.req.valid("query");
|
|
@@ -3201,7 +3694,7 @@ function createPeopleRoutes() {
|
|
|
3201
3694
|
app.get("/:email", validateRequest("param", personParamsSchema, "Invalid route parameters."), async (context) => {
|
|
3202
3695
|
const { email } = context.req.valid("param");
|
|
3203
3696
|
const viewer = context.get("viewer");
|
|
3204
|
-
return jsonResponse(actorProfileReportSchema, await
|
|
3697
|
+
return jsonResponse(actorProfileReportSchema, await readPeopleProfileFromSql(email, viewer ? { viewer } : {}));
|
|
3205
3698
|
});
|
|
3206
3699
|
return app;
|
|
3207
3700
|
}
|
|
@@ -3357,6 +3850,303 @@ function createServiceAccountRoutes() {
|
|
|
3357
3850
|
});
|
|
3358
3851
|
return app;
|
|
3359
3852
|
}
|
|
3853
|
+
// src/chat/sentry-telemetry.ts
|
|
3854
|
+
/**
|
|
3855
|
+
* Read Junior's own telemetry back from Sentry, for System page reports.
|
|
3856
|
+
*
|
|
3857
|
+
* Junior sends its telemetry to the project of `SENTRY_DSN`, so it reads only
|
|
3858
|
+
* that project, in the `SENTRY_ORG_SLUG` org, with the `SENTRY_READ_TOKEN` org
|
|
3859
|
+
* read token, through the `@sentry/api` client. Only server code calls
|
|
3860
|
+
* Sentry, so the token never reaches a browser.
|
|
3861
|
+
*/
|
|
3862
|
+
const env = (name) => process.env[name]?.trim() || void 0;
|
|
3863
|
+
function apiUrlOf(dsn) {
|
|
3864
|
+
const region = /^o\d+\.ingest\.((?:[a-z]+\.)?sentry\.io)$/.exec(dsn.host);
|
|
3865
|
+
if (region) return `https://${region[1]}`;
|
|
3866
|
+
const prefix = dsn.pathname.split("/").slice(0, -1).join("/");
|
|
3867
|
+
return `${dsn.protocol}//${dsn.host}${prefix}`;
|
|
3868
|
+
}
|
|
3869
|
+
/**
|
|
3870
|
+
* Return where to read Junior's telemetry, or the settings that are missing.
|
|
3871
|
+
*/
|
|
3872
|
+
function sentryTelemetry() {
|
|
3873
|
+
const dsn = env("SENTRY_DSN");
|
|
3874
|
+
const org = env("SENTRY_ORG_SLUG");
|
|
3875
|
+
const token = env("SENTRY_READ_TOKEN");
|
|
3876
|
+
const url = dsn && URL.canParse(dsn) ? new URL(dsn) : void 0;
|
|
3877
|
+
const projectId = url?.pathname.split("/").at(-1);
|
|
3878
|
+
if (!url || !projectId || !org || !token) return { missing: [
|
|
3879
|
+
...projectId ? [] : ["SENTRY_DSN"],
|
|
3880
|
+
...org ? [] : ["SENTRY_ORG_SLUG"],
|
|
3881
|
+
...token ? [] : ["SENTRY_READ_TOKEN"]
|
|
3882
|
+
] };
|
|
3883
|
+
return {
|
|
3884
|
+
client: createSentryClient({
|
|
3885
|
+
baseUrl: apiUrlOf(url),
|
|
3886
|
+
auth: token
|
|
3887
|
+
}),
|
|
3888
|
+
org,
|
|
3889
|
+
projectId
|
|
3890
|
+
};
|
|
3891
|
+
}
|
|
3892
|
+
/**
|
|
3893
|
+
* Return the answer of one telemetry read through the `@sentry/api` client.
|
|
3894
|
+
* Throw for a failure that is not a rate limit or a denied token, naming
|
|
3895
|
+
* `what` failed.
|
|
3896
|
+
*/
|
|
3897
|
+
function telemetryResponse(result, what) {
|
|
3898
|
+
if (!("error" in result)) return {
|
|
3899
|
+
status: "ok",
|
|
3900
|
+
data: result.data
|
|
3901
|
+
};
|
|
3902
|
+
const status = result.response?.status;
|
|
3903
|
+
if (status === 429) return { status: "rate_limited" };
|
|
3904
|
+
if (status === 401 || status === 403) return { status: "denied" };
|
|
3905
|
+
throw new Error(`Sentry ${what} read failed with status ${status}.`, { cause: result.error });
|
|
3906
|
+
}
|
|
3907
|
+
// src/api/cache-warming/health.ts
|
|
3908
|
+
const HOUR_MS = 36e5;
|
|
3909
|
+
const WEEK_MS = 168 * HOUR_MS;
|
|
3910
|
+
const WINDOWS = {
|
|
3911
|
+
"24h": {
|
|
3912
|
+
ms: 24 * HOUR_MS,
|
|
3913
|
+
interval: "1h"
|
|
3914
|
+
},
|
|
3915
|
+
"7d": {
|
|
3916
|
+
ms: WEEK_MS,
|
|
3917
|
+
interval: "6h"
|
|
3918
|
+
}
|
|
3919
|
+
};
|
|
3920
|
+
const FRESH_MS = 6e4;
|
|
3921
|
+
const STALE_MS = 36e5;
|
|
3922
|
+
const READ_CONCURRENCY = 2;
|
|
3923
|
+
const REFRESH_WAIT_MS = 15e3;
|
|
3924
|
+
const cacheKey = (window) => `junior:cache_warming:health:${window}`;
|
|
3925
|
+
const tableSchema = z.object({ data: z.array(z.record(z.string(), z.unknown())) });
|
|
3926
|
+
const timeseriesSchema = z.object({ timeSeries: z.array(z.object({
|
|
3927
|
+
yAxis: z.string(),
|
|
3928
|
+
values: z.array(z.object({
|
|
3929
|
+
timestamp: z.number(),
|
|
3930
|
+
value: z.number().nullable()
|
|
3931
|
+
}))
|
|
3932
|
+
})) });
|
|
3933
|
+
const agentCalls = (modelId) => `span.op:gen_ai.chat !has:gen_ai.prompt.name gen_ai.request.model:"${modelId}"`;
|
|
3934
|
+
const FULL_REWRITE = "gen_ai.usage.cache_creation.input_tokens:>50000 gen_ai.usage.cache_read.input_tokens:<20000";
|
|
3935
|
+
const CALL_AGGREGATES = [
|
|
3936
|
+
"count()",
|
|
3937
|
+
"sum(gen_ai.usage.input_tokens)",
|
|
3938
|
+
"sum(gen_ai.usage.cache_creation.input_tokens)"
|
|
3939
|
+
];
|
|
3940
|
+
const IDLE_PERIOD_METRIC = "cache_warming.idle_period.saved_usd,distribution,none";
|
|
3941
|
+
const BREAKER_METRIC = "sum(value,cache_warming.breaker,counter,none)";
|
|
3942
|
+
const count = (value) => typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.round(value)) : 0;
|
|
3943
|
+
const usd = (value) => typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
|
|
3944
|
+
const label = (value) => typeof value === "string" && value ? value : void 0;
|
|
3945
|
+
const bucketKey = (ms) => new Date(ms).toISOString().slice(0, 13);
|
|
3946
|
+
function windowReads(telemetry, window, nowMs) {
|
|
3947
|
+
const { client, org, projectId } = telemetry;
|
|
3948
|
+
const { ms, interval } = WINDOWS[window];
|
|
3949
|
+
const calls = agentCalls(botConfig.modelId);
|
|
3950
|
+
const path = { organization_id_or_slug: org };
|
|
3951
|
+
const timeseries = (query, yAxis) => async () => telemetryResponse(await client.listOrganizationEventsTimeseries({
|
|
3952
|
+
path,
|
|
3953
|
+
query: {
|
|
3954
|
+
dataset: "spans",
|
|
3955
|
+
project: [projectId],
|
|
3956
|
+
statsPeriod: window,
|
|
3957
|
+
interval,
|
|
3958
|
+
query,
|
|
3959
|
+
yAxis
|
|
3960
|
+
}
|
|
3961
|
+
}), "events-timeseries");
|
|
3962
|
+
const table = (query) => async () => telemetryResponse(await client.listOrganizationEvents({
|
|
3963
|
+
path,
|
|
3964
|
+
query: {
|
|
3965
|
+
...query,
|
|
3966
|
+
project: [projectId]
|
|
3967
|
+
}
|
|
3968
|
+
}), "events");
|
|
3969
|
+
return [
|
|
3970
|
+
timeseries(calls, CALL_AGGREGATES),
|
|
3971
|
+
timeseries(`${calls} ${FULL_REWRITE}`, ["count()"]),
|
|
3972
|
+
table({
|
|
3973
|
+
dataset: "spans",
|
|
3974
|
+
start: (/* @__PURE__ */ new Date(nowMs - WEEK_MS - ms)).toISOString(),
|
|
3975
|
+
end: (/* @__PURE__ */ new Date(nowMs - WEEK_MS)).toISOString(),
|
|
3976
|
+
query: calls,
|
|
3977
|
+
field: CALL_AGGREGATES
|
|
3978
|
+
}),
|
|
3979
|
+
table({
|
|
3980
|
+
statsPeriod: window,
|
|
3981
|
+
dataset: "spans",
|
|
3982
|
+
query: "span.op:cache_warming.warmup",
|
|
3983
|
+
field: [
|
|
3984
|
+
"app.cache_warming.trigger",
|
|
3985
|
+
"app.cache_warming.outcome",
|
|
3986
|
+
"app.cache_warming.turn_ending",
|
|
3987
|
+
"app.cache_warming.skip_reason",
|
|
3988
|
+
"count()",
|
|
3989
|
+
"sum(app.cost.total_usd)"
|
|
3990
|
+
],
|
|
3991
|
+
per_page: 100
|
|
3992
|
+
}),
|
|
3993
|
+
table({
|
|
3994
|
+
statsPeriod: window,
|
|
3995
|
+
dataset: "tracemetrics",
|
|
3996
|
+
field: [
|
|
3997
|
+
"app.cache_warming.idle_outcome",
|
|
3998
|
+
`count(value,${IDLE_PERIOD_METRIC})`,
|
|
3999
|
+
`sum(value,${IDLE_PERIOD_METRIC})`
|
|
4000
|
+
]
|
|
4001
|
+
}),
|
|
4002
|
+
table({
|
|
4003
|
+
statsPeriod: window,
|
|
4004
|
+
dataset: "tracemetrics",
|
|
4005
|
+
field: ["app.cache_warming.breaker_event", BREAKER_METRIC]
|
|
4006
|
+
})
|
|
4007
|
+
];
|
|
4008
|
+
}
|
|
4009
|
+
function series(body, axis) {
|
|
4010
|
+
const values = timeseriesSchema.parse(body).timeSeries.find((item) => item.yAxis === axis)?.values ?? [];
|
|
4011
|
+
return new Map(values.map((point) => [point.timestamp, point.value]));
|
|
4012
|
+
}
|
|
4013
|
+
function callTotals(row) {
|
|
4014
|
+
return {
|
|
4015
|
+
calls: count(row?.["count()"]),
|
|
4016
|
+
inputTokens: count(row?.["sum(gen_ai.usage.input_tokens)"]),
|
|
4017
|
+
cacheWriteTokens: count(row?.["sum(gen_ai.usage.cache_creation.input_tokens)"])
|
|
4018
|
+
};
|
|
4019
|
+
}
|
|
4020
|
+
function warmupTotals(body) {
|
|
4021
|
+
const sentByTurnEnding = {};
|
|
4022
|
+
const skipReasons = {};
|
|
4023
|
+
let costUsd = 0;
|
|
4024
|
+
for (const row of tableSchema.parse(body).data) {
|
|
4025
|
+
const rows = count(row["count()"]);
|
|
4026
|
+
costUsd += usd(row["sum(app.cost.total_usd)"]);
|
|
4027
|
+
const outcome = label(row["app.cache_warming.outcome"]);
|
|
4028
|
+
if (outcome === "skipped") {
|
|
4029
|
+
const reason = label(row["app.cache_warming.skip_reason"]) ?? "unknown";
|
|
4030
|
+
skipReasons[reason] = (skipReasons[reason] ?? 0) + rows;
|
|
4031
|
+
} else if (outcome === "completed" || outcome === "missed") {
|
|
4032
|
+
const ending = label(row["app.cache_warming.trigger"]) === "tool_wait" ? "tool_wait" : label(row["app.cache_warming.turn_ending"]) ?? "unknown";
|
|
4033
|
+
sentByTurnEnding[ending] = (sentByTurnEnding[ending] ?? 0) + rows;
|
|
4034
|
+
}
|
|
4035
|
+
}
|
|
4036
|
+
return {
|
|
4037
|
+
sentByTurnEnding,
|
|
4038
|
+
skipReasons,
|
|
4039
|
+
costUsd
|
|
4040
|
+
};
|
|
4041
|
+
}
|
|
4042
|
+
function idlePeriodTotals(body) {
|
|
4043
|
+
const byOutcome = new Map(tableSchema.parse(body).data.map((row) => [label(row["app.cache_warming.idle_outcome"]), row]));
|
|
4044
|
+
const periods = (outcome) => count(byOutcome.get(outcome)?.[`count(value,${IDLE_PERIOD_METRIC})`]);
|
|
4045
|
+
return {
|
|
4046
|
+
saved: periods("saved"),
|
|
4047
|
+
notWarmed: periods("not_warmed"),
|
|
4048
|
+
stoppedEarly: periods("stopped_early"),
|
|
4049
|
+
cacheLost: periods("cache_lost"),
|
|
4050
|
+
savedUsd: usd(byOutcome.get("saved")?.[`sum(value,${IDLE_PERIOD_METRIC})`])
|
|
4051
|
+
};
|
|
4052
|
+
}
|
|
4053
|
+
function breakerEventTotals(body) {
|
|
4054
|
+
const rows = tableSchema.parse(body).data;
|
|
4055
|
+
const events = (event) => count(rows.find((row) => row["app.cache_warming.breaker_event"] === event)?.[BREAKER_METRIC]);
|
|
4056
|
+
return {
|
|
4057
|
+
opened: events("opened"),
|
|
4058
|
+
closed: events("closed")
|
|
4059
|
+
};
|
|
4060
|
+
}
|
|
4061
|
+
function healthData(window, bodies, nowMs) {
|
|
4062
|
+
const [callBody, rewriteBody, lastWeek, warmups, idlePeriods, breakers] = bodies;
|
|
4063
|
+
const [calls, inputTokens, cacheWriteTokens] = CALL_AGGREGATES.map((axis) => series(callBody, axis));
|
|
4064
|
+
const rewrites = series(rewriteBody, "count()");
|
|
4065
|
+
return {
|
|
4066
|
+
status: "ok",
|
|
4067
|
+
window,
|
|
4068
|
+
modelId: botConfig.modelId,
|
|
4069
|
+
fetchedAt: new Date(nowMs).toISOString(),
|
|
4070
|
+
stale: false,
|
|
4071
|
+
buckets: [...calls ?? []].map(([timestamp, value]) => ({
|
|
4072
|
+
start: bucketKey(timestamp),
|
|
4073
|
+
calls: count(value),
|
|
4074
|
+
inputTokens: count(inputTokens?.get(timestamp)),
|
|
4075
|
+
cacheWriteTokens: count(cacheWriteTokens?.get(timestamp)),
|
|
4076
|
+
fullRewrites: count(rewrites.get(timestamp))
|
|
4077
|
+
})),
|
|
4078
|
+
lastWeek: callTotals(tableSchema.parse(lastWeek).data[0]),
|
|
4079
|
+
warmups: warmupTotals(warmups),
|
|
4080
|
+
idlePeriods: idlePeriodTotals(idlePeriods),
|
|
4081
|
+
breakerEvents: breakerEventTotals(breakers)
|
|
4082
|
+
};
|
|
4083
|
+
}
|
|
4084
|
+
async function readWindow(telemetry, window, nowMs) {
|
|
4085
|
+
let stopped;
|
|
4086
|
+
const answers = await mapBounded(windowReads(telemetry, window, nowMs), async (read) => {
|
|
4087
|
+
if (stopped) return stopped;
|
|
4088
|
+
const answer = await read();
|
|
4089
|
+
if (answer.status !== "ok") stopped ??= answer;
|
|
4090
|
+
return answer;
|
|
4091
|
+
}, READ_CONCURRENCY);
|
|
4092
|
+
const bodies = [];
|
|
4093
|
+
for (const answer of answers) {
|
|
4094
|
+
if (answer.status !== "ok") return { status: answer.status };
|
|
4095
|
+
bodies.push(answer.data);
|
|
4096
|
+
}
|
|
4097
|
+
return healthData(window, bodies, nowMs);
|
|
4098
|
+
}
|
|
4099
|
+
/** Report whether warming is paused for each provider of the warmed models. */
|
|
4100
|
+
async function warmedBreakerStates() {
|
|
4101
|
+
return await breakerStates(await connectedState(), [botConfig.modelId, ...botConfig.refusalFallbackModelId ? [botConfig.refusalFallbackModelId] : []]);
|
|
4102
|
+
}
|
|
4103
|
+
const isFresh = (health, nowMs) => nowMs - Date.parse(health.fetchedAt) < FRESH_MS;
|
|
4104
|
+
async function refreshWindow(state, telemetry, window, nowMs) {
|
|
4105
|
+
const cached = await state.get(cacheKey(window));
|
|
4106
|
+
if (cached && isFresh(cached, nowMs)) return cached;
|
|
4107
|
+
const read = await readWindow(telemetry, window, nowMs);
|
|
4108
|
+
if (read.status === "ok") {
|
|
4109
|
+
await state.set(cacheKey(window), read, STALE_MS);
|
|
4110
|
+
return read;
|
|
4111
|
+
}
|
|
4112
|
+
if (read.status === "rate_limited" && cached) return {
|
|
4113
|
+
...cached,
|
|
4114
|
+
stale: true
|
|
4115
|
+
};
|
|
4116
|
+
return read;
|
|
4117
|
+
}
|
|
4118
|
+
/**
|
|
4119
|
+
* Read the cache health of the last 24 hours or 7 days from Junior's own
|
|
4120
|
+
* Sentry telemetry. Page loads within a minute share one answer through the
|
|
4121
|
+
* state adapter, and one load at a time refreshes it. When Sentry rate limits
|
|
4122
|
+
* a read, an answer up to an hour old is served, marked stale. The breaker
|
|
4123
|
+
* state is always live.
|
|
4124
|
+
*/
|
|
4125
|
+
async function readCacheHealth(window, nowMs = Date.now()) {
|
|
4126
|
+
const telemetry = sentryTelemetry();
|
|
4127
|
+
if ("missing" in telemetry) return {
|
|
4128
|
+
status: "unconfigured",
|
|
4129
|
+
missing: telemetry.missing
|
|
4130
|
+
};
|
|
4131
|
+
const state = await connectedState();
|
|
4132
|
+
const cached = await state.get(cacheKey(window));
|
|
4133
|
+
let health;
|
|
4134
|
+
if (cached && isFresh(cached, nowMs)) health = cached;
|
|
4135
|
+
else {
|
|
4136
|
+
const refresh = await withLock(state, `${cacheKey(window)}:refresh`, () => refreshWindow(state, telemetry, window, nowMs), { waitMs: REFRESH_WAIT_MS });
|
|
4137
|
+
if (refresh.acquired) health = refresh.value;
|
|
4138
|
+
else if (cached) health = {
|
|
4139
|
+
...cached,
|
|
4140
|
+
stale: true
|
|
4141
|
+
};
|
|
4142
|
+
else health = { status: "busy" };
|
|
4143
|
+
}
|
|
4144
|
+
if (health.status !== "ok") return { status: health.status };
|
|
4145
|
+
return {
|
|
4146
|
+
...health,
|
|
4147
|
+
breakers: await warmedBreakerStates()
|
|
4148
|
+
};
|
|
4149
|
+
}
|
|
3360
4150
|
// src/api/cache-warming/savings.ts
|
|
3361
4151
|
const DAY_MS = 864e5;
|
|
3362
4152
|
function savingsUsd(totals) {
|
|
@@ -3391,7 +4181,7 @@ async function readCacheWarmingSavings(days, nowMs = Date.now()) {
|
|
|
3391
4181
|
const net = netSavingsUsd(all);
|
|
3392
4182
|
const oracle = microUsdToUsd(all.oracleSavingsMicroUsd);
|
|
3393
4183
|
const live = savingsTotals(stats.filter((stat) => !historyDates.has(stat.date)));
|
|
3394
|
-
return
|
|
4184
|
+
return {
|
|
3395
4185
|
days: dayTotals.map(({ date, totals }) => ({
|
|
3396
4186
|
date,
|
|
3397
4187
|
...savingsUsd(totals),
|
|
@@ -3405,13 +4195,13 @@ async function readCacheWarmingSavings(days, nowMs = Date.now()) {
|
|
|
3405
4195
|
effectiveness: oracle > 0 ? net / oracle : null,
|
|
3406
4196
|
historyDays: historyDates.size
|
|
3407
4197
|
}
|
|
3408
|
-
}
|
|
4198
|
+
};
|
|
3409
4199
|
}
|
|
3410
4200
|
// src/api/cache-warming/routes.ts
|
|
3411
4201
|
/**
|
|
3412
|
-
* Create the cache warming routes: its savings
|
|
3413
|
-
* admin-only routes that re-fill the savings from history and
|
|
3414
|
-
* the breakers.
|
|
4202
|
+
* Create the cache warming routes: its savings and cache health for the
|
|
4203
|
+
* System page, and admin-only routes that re-fill the savings from history and
|
|
4204
|
+
* show and close the breakers.
|
|
3415
4205
|
*
|
|
3416
4206
|
* A breaker stops warming for every Conversation, so only a Junior admin can
|
|
3417
4207
|
* close one before it closes by itself. A re-fill replaces counters that
|
|
@@ -3420,12 +4210,13 @@ async function readCacheWarmingSavings(days, nowMs = Date.now()) {
|
|
|
3420
4210
|
function createCacheWarmingRoutes() {
|
|
3421
4211
|
const app = new Hono();
|
|
3422
4212
|
app.get("/savings", validateRequest("query", cacheWarmingSavingsQuerySchema, "Invalid query parameters."), async (context) => jsonResponse(cacheWarmingSavingsReportSchema, await readCacheWarmingSavings(context.req.valid("query").days)));
|
|
4213
|
+
app.get("/health", validateRequest("query", cacheHealthQuerySchema, "Invalid query parameters."), async (context) => jsonResponse(cacheHealthReportSchema, await readCacheHealth(context.req.valid("query").window)));
|
|
3423
4214
|
app.get("/savings/refill", requireAdmin, async () => jsonResponse(cacheWarmingSavingsRefillResponseSchema, { refill: await readSavingsRefill() }));
|
|
3424
4215
|
app.post("/savings/refill", requireAdmin, async () => {
|
|
3425
4216
|
const { started, refill } = await startSavingsRefill();
|
|
3426
4217
|
return jsonResponse(cacheWarmingSavingsRefillResponseSchema, { refill }, { status: started ? 202 : 409 });
|
|
3427
4218
|
});
|
|
3428
|
-
app.get("/breakers", requireAdmin, async () => jsonResponse(cacheWarmingBreakerListSchema, { breakers: await
|
|
4219
|
+
app.get("/breakers", requireAdmin, async () => jsonResponse(cacheWarmingBreakerListSchema, { breakers: await warmedBreakerStates() }));
|
|
3429
4220
|
app.delete("/breakers/:provider", requireAdmin, validateRequest("param", cacheWarmingBreakerParamsSchema, "Invalid provider."), async (context) => {
|
|
3430
4221
|
const { provider } = context.req.valid("param");
|
|
3431
4222
|
if (!await closeBreaker(await connectedState(), provider)) throwApiError(404, "Breaker not found.");
|
|
@@ -3434,6 +4225,42 @@ function createCacheWarmingRoutes() {
|
|
|
3434
4225
|
});
|
|
3435
4226
|
return app;
|
|
3436
4227
|
}
|
|
4228
|
+
// src/api/gateway-providers/routes.ts
|
|
4229
|
+
async function readGatewayProviders() {
|
|
4230
|
+
const state = getStateAdapter();
|
|
4231
|
+
const modelIds = [.../* @__PURE__ */ new Set([botConfig.modelId, ...botConfig.refusalFallbackModelId ? [botConfig.refusalFallbackModelId] : []])];
|
|
4232
|
+
const [enabled, models] = await Promise.all([readEnabledProviders(state), mapBounded(modelIds, async (id) => ({
|
|
4233
|
+
id,
|
|
4234
|
+
providers: await readServedProviders(state, id)
|
|
4235
|
+
}))]);
|
|
4236
|
+
return {
|
|
4237
|
+
enabled,
|
|
4238
|
+
providers: [...new Set(models.flatMap((model) => model.providers))].sort(),
|
|
4239
|
+
models
|
|
4240
|
+
};
|
|
4241
|
+
}
|
|
4242
|
+
/**
|
|
4243
|
+
* Create the admin-only routes of the "Enabled providers" setting.
|
|
4244
|
+
*
|
|
4245
|
+
* The setting changes where every agent model call goes, and a narrow list
|
|
4246
|
+
* makes calls fail when its providers are down, so only a Junior admin can
|
|
4247
|
+
* read or change it.
|
|
4248
|
+
*/
|
|
4249
|
+
function createGatewayProviderRoutes() {
|
|
4250
|
+
const app = new Hono();
|
|
4251
|
+
app.get("/", requireAdmin, async () => jsonResponse(gatewayProvidersSchema, await readGatewayProviders()));
|
|
4252
|
+
app.put("/", requireAdmin, validateRequest("json", updateGatewayProvidersBodySchema, "Invalid request body."), async (context) => {
|
|
4253
|
+
const { enabled } = context.req.valid("json");
|
|
4254
|
+
const current = await readGatewayProviders();
|
|
4255
|
+
await saveEnabledProviders(getStateAdapter(), enabled);
|
|
4256
|
+
logInfo("dashboard.gateway_providers.updated", { "app.gateway.enabled_providers": enabled ?? ["*"] });
|
|
4257
|
+
return jsonResponse(gatewayProvidersSchema, {
|
|
4258
|
+
...current,
|
|
4259
|
+
enabled
|
|
4260
|
+
});
|
|
4261
|
+
});
|
|
4262
|
+
return app;
|
|
4263
|
+
}
|
|
3437
4264
|
// src/chat/plugins/user-pages.ts
|
|
3438
4265
|
/**
|
|
3439
4266
|
* Runtime ownership for plugin user pages.
|
|
@@ -3447,7 +4274,7 @@ function viewerCanSeePage(page, viewer) {
|
|
|
3447
4274
|
}
|
|
3448
4275
|
/** List safe navigation metadata for the plugin user pages one viewer can see. */
|
|
3449
4276
|
function readPluginUserPageLinks(viewer) {
|
|
3450
|
-
return pluginUserPageLinksSchema.parse(
|
|
4277
|
+
return pluginUserPageLinksSchema.parse(getRegistrations().flatMap((plugin) => (plugin.userPages ?? []).filter((page) => viewerCanSeePage(page, viewer)).map((page) => ({
|
|
3451
4278
|
description: page.description,
|
|
3452
4279
|
id: page.id,
|
|
3453
4280
|
label: page.label,
|
|
@@ -3458,11 +4285,11 @@ function readPluginUserPageLinks(viewer) {
|
|
|
3458
4285
|
}
|
|
3459
4286
|
function actionBelongsToPlugin(href, pluginName) {
|
|
3460
4287
|
const parsed = new URL(href, "http://junior.local");
|
|
3461
|
-
return parsed.origin === "http://junior.local" && parsed.pathname === href && parsed.pathname.startsWith(
|
|
4288
|
+
return parsed.origin === "http://junior.local" && parsed.pathname === href && parsed.pathname.startsWith(`${apiRoutePrefix(pluginName)}/`) && !parsed.search && !parsed.hash;
|
|
3462
4289
|
}
|
|
3463
4290
|
/** Read one registered plugin user page for the authenticated viewer. */
|
|
3464
4291
|
async function readPluginUserPage(input) {
|
|
3465
|
-
const plugin =
|
|
4292
|
+
const plugin = getRegistrations().find((candidate) => candidate.manifest.name === input.pluginName);
|
|
3466
4293
|
const page = plugin?.userPages?.find((candidate) => candidate.id === input.pageId);
|
|
3467
4294
|
if (!plugin || !page) return void 0;
|
|
3468
4295
|
const viewer = await resolveViewerUser(input.email);
|
|
@@ -3713,7 +4540,7 @@ const RELATED_ITEM_LIMIT = 10;
|
|
|
3713
4540
|
const RELATED_CANDIDATE_LIMIT = 11;
|
|
3714
4541
|
/** The linked Conversations of an item that point to other work. */
|
|
3715
4542
|
function linkedWork(item) {
|
|
3716
|
-
return item.conversationIds.filter((id) => id !== item
|
|
4543
|
+
return item.conversationIds.filter((id) => id !== ownerConversationId(item));
|
|
3717
4544
|
}
|
|
3718
4545
|
function openVisible(reader) {
|
|
3719
4546
|
return and(eq(juniorReviewItems.status, "open"), reviewItemVisibleTo(reader));
|
|
@@ -3786,22 +4613,225 @@ async function readRelatedReviewWork(db, reader, viewer, items) {
|
|
|
3786
4613
|
}
|
|
3787
4614
|
return related;
|
|
3788
4615
|
}
|
|
4616
|
+
// src/chat/inbox-snoozes/subject.ts
|
|
4617
|
+
/**
|
|
4618
|
+
* Return the Event resource that a subject URL names, such as the pull
|
|
4619
|
+
* request of a GitHub link. The plugin that owns the source reads the URL,
|
|
4620
|
+
* so core keeps no provider URL rules. A snooze waits on the resource's
|
|
4621
|
+
* Events as a Watch does, so a resource type that cannot be watched has
|
|
4622
|
+
* none.
|
|
4623
|
+
*/
|
|
4624
|
+
function snoozeSubjectResource(catalog, url) {
|
|
4625
|
+
for (const [namespace, registration] of Object.entries(catalog)) {
|
|
4626
|
+
const found = registration.resourceForUrl?.(url);
|
|
4627
|
+
if (!found) continue;
|
|
4628
|
+
const resourceType = registration.resourceTypes.find((candidate) => candidate.type === found.resourceType);
|
|
4629
|
+
if (!resourceType || eventWatchUnavailable(catalog, namespace, resourceType.type)) return;
|
|
4630
|
+
const phrases = {};
|
|
4631
|
+
for (const eventType of resourceType.supportedEvents) {
|
|
4632
|
+
const phrase = registration.events[eventType]?.phrase;
|
|
4633
|
+
if (phrase) phrases[eventType] = phrase;
|
|
4634
|
+
}
|
|
4635
|
+
return {
|
|
4636
|
+
events: resourceType.supportedEvents,
|
|
4637
|
+
phrases,
|
|
4638
|
+
identifier: normalizeEventIdentifier(registration, found.identifier),
|
|
4639
|
+
namespace,
|
|
4640
|
+
resourceType: resourceType.type
|
|
4641
|
+
};
|
|
4642
|
+
}
|
|
4643
|
+
}
|
|
4644
|
+
/**
|
|
4645
|
+
* Return the Event resource of a page that the viewer names, such as
|
|
4646
|
+
* another pull request. An item's subject is already in the viewer's
|
|
4647
|
+
* Inbox, but this page is not, so the plugin that owns its Events must let
|
|
4648
|
+
* the viewer see the page now, as it does for the page's card.
|
|
4649
|
+
*/
|
|
4650
|
+
async function viewerSnoozeResource(viewer, catalog, url) {
|
|
4651
|
+
const resource = snoozeSubjectResource(catalog, url);
|
|
4652
|
+
return resource && URL.canParse(url) && await viewerCanViewPluginLink(viewer, new URL(url), resource.namespace) ? resource : void 0;
|
|
4653
|
+
}
|
|
4654
|
+
// src/chat/inbox-snoozes/viewer.ts
|
|
4655
|
+
/** A snooze request that the viewer may not make, such as a past time. */
|
|
4656
|
+
var InboxSnoozeInputError = class extends Error {};
|
|
4657
|
+
/** The viewer cannot see the Inbox row, or it does not exist. */
|
|
4658
|
+
var InboxRowNotFoundError = class extends Error {};
|
|
4659
|
+
async function rootConversationId(conversationId) {
|
|
4660
|
+
const [row] = await getDb().select({
|
|
4661
|
+
conversationId: juniorConversations.conversationId,
|
|
4662
|
+
rootConversationId: juniorConversations.rootConversationId
|
|
4663
|
+
}).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId)).limit(1);
|
|
4664
|
+
return row ? row.rootConversationId ?? row.conversationId : void 0;
|
|
4665
|
+
}
|
|
4666
|
+
/** The root Conversations of these Conversations, in one read. */
|
|
4667
|
+
async function rootConversationIds(conversationIds) {
|
|
4668
|
+
if (conversationIds.length === 0) return [];
|
|
4669
|
+
return (await getDb().select({
|
|
4670
|
+
conversationId: juniorConversations.conversationId,
|
|
4671
|
+
rootConversationId: juniorConversations.rootConversationId
|
|
4672
|
+
}).from(juniorConversations).where(inArray(juniorConversations.conversationId, conversationIds))).map((row) => row.rootConversationId ?? row.conversationId);
|
|
4673
|
+
}
|
|
4674
|
+
/**
|
|
4675
|
+
* Return the open Review items of the row that the viewer can see: the one
|
|
4676
|
+
* item, in the root Conversation's row when a root is given, or every item
|
|
4677
|
+
* in the root Conversation's row. A missing row and a hidden row look the
|
|
4678
|
+
* same.
|
|
4679
|
+
*/
|
|
4680
|
+
async function visibleRowItems(user, root, reviewItemId) {
|
|
4681
|
+
if (reviewItemId) {
|
|
4682
|
+
const item = await getReviewItem(getDb(), reviewItemId);
|
|
4683
|
+
const inRow = root === void 0 || (item ? await rootConversationIds(item.conversationIds) : []).includes(root);
|
|
4684
|
+
if (item?.status === "open" && inRow && await canUserReadReviewItem(item, user)) return [{
|
|
4685
|
+
canAct: canActOnReviewItem(item, user.id),
|
|
4686
|
+
id: item.id,
|
|
4687
|
+
subjectUrl: item.subject?.url ?? null
|
|
4688
|
+
}];
|
|
4689
|
+
return [];
|
|
4690
|
+
}
|
|
4691
|
+
if (!root) return [];
|
|
4692
|
+
const reader = await reviewItemReaderForUserInConversation(user, root);
|
|
4693
|
+
return getDb().select({
|
|
4694
|
+
canAct: sql`${reviewItemForUser(user.id)}`,
|
|
4695
|
+
id: juniorReviewItems.id,
|
|
4696
|
+
subjectUrl: juniorReviewItems.subjectUrl
|
|
4697
|
+
}).from(juniorReviewItems).where(and(eq(juniorReviewItems.status, "open"), reviewItemVisibleTo(reader), reviewItemInRow(root)));
|
|
4698
|
+
}
|
|
4699
|
+
/**
|
|
4700
|
+
* Read the resource of each page that the triggers name. The viewer must
|
|
4701
|
+
* be allowed to see each one, so a snooze cannot learn about a page that
|
|
4702
|
+
* they cannot see.
|
|
4703
|
+
*/
|
|
4704
|
+
async function namedResources(user, triggers) {
|
|
4705
|
+
const urls = [...new Set(triggers.flatMap((trigger) => trigger.resourceUrl ?? []))];
|
|
4706
|
+
const catalog = getEventCatalog();
|
|
4707
|
+
const resources = await mapBounded(urls, (url) => viewerSnoozeResource(user, catalog, url));
|
|
4708
|
+
const named = /* @__PURE__ */ new Map();
|
|
4709
|
+
for (const [index, url] of urls.entries()) {
|
|
4710
|
+
const resource = resources[index];
|
|
4711
|
+
if (!resource) throw new InboxSnoozeInputError(`A snooze cannot wait on ${url}.`);
|
|
4712
|
+
named.set(url, resource);
|
|
4713
|
+
}
|
|
4714
|
+
return named;
|
|
4715
|
+
}
|
|
4716
|
+
/**
|
|
4717
|
+
* Aim each trigger at its named resource, or at the resource of the item's
|
|
4718
|
+
* subject. A viewer waits on the subject without a check, as the item
|
|
4719
|
+
* already names it. A `resolve` dismisses the item, so it needs a viewer
|
|
4720
|
+
* who can dismiss it. Returns undefined when a trigger does not apply to
|
|
4721
|
+
* the item.
|
|
4722
|
+
*/
|
|
4723
|
+
function itemTriggers(item, triggers, named) {
|
|
4724
|
+
const subject = item.subjectUrl && snoozeSubjectResource(getEventCatalog(), item.subjectUrl);
|
|
4725
|
+
const aimed = [];
|
|
4726
|
+
for (const trigger of triggers) {
|
|
4727
|
+
const resource = trigger.resourceUrl ? named.get(trigger.resourceUrl) : subject;
|
|
4728
|
+
if (!resource || !resource.events.includes(trigger.eventType) || trigger.outcome === "resolve" && !item.canAct) return;
|
|
4729
|
+
aimed.push({
|
|
4730
|
+
eventType: trigger.eventType,
|
|
4731
|
+
identifier: resource.identifier,
|
|
4732
|
+
namespace: resource.namespace,
|
|
4733
|
+
outcome: trigger.outcome
|
|
4734
|
+
});
|
|
4735
|
+
}
|
|
4736
|
+
return aimed;
|
|
4737
|
+
}
|
|
4738
|
+
/**
|
|
4739
|
+
* The row's items that take every trigger, each with its triggers. A root
|
|
4740
|
+
* row snoozes only those, as the Inbox can show fewer of its items than
|
|
4741
|
+
* the viewer can read, such as an item that an earlier snooze hides; the
|
|
4742
|
+
* rest stay as they are. Throws when no item takes them.
|
|
4743
|
+
*/
|
|
4744
|
+
function itemsWithTriggers(items, triggers, named) {
|
|
4745
|
+
const taken = items.flatMap((item) => {
|
|
4746
|
+
const aimed = itemTriggers(item, triggers, named);
|
|
4747
|
+
return aimed ? [{
|
|
4748
|
+
item,
|
|
4749
|
+
triggers: aimed
|
|
4750
|
+
}] : [];
|
|
4751
|
+
});
|
|
4752
|
+
if (taken.length === 0) throw new InboxSnoozeInputError("No item in the row takes these Events from this viewer.");
|
|
4753
|
+
return taken;
|
|
4754
|
+
}
|
|
4755
|
+
/**
|
|
4756
|
+
* Snooze the open items of one Inbox row for the viewer until `wakeAtMs`,
|
|
4757
|
+
* or until one of `triggers` fires on an item's subject or on a page that
|
|
4758
|
+
* the viewer names, whichever is first. Each item gets its own snooze, which replaces the viewer's
|
|
4759
|
+
* earlier one; a later item in the row shows by itself. Returns the
|
|
4760
|
+
* snoozed items.
|
|
4761
|
+
*/
|
|
4762
|
+
async function createViewerSnooze(user, input, nowMs = Date.now()) {
|
|
4763
|
+
const { wakeAtMs } = input;
|
|
4764
|
+
if (wakeAtMs === void 0 && !input.triggers?.length) throw new InboxSnoozeInputError("Set a wake time or a trigger.");
|
|
4765
|
+
if (wakeAtMs !== void 0 && wakeAtMs <= nowMs) throw new InboxSnoozeInputError("The wake time must be in the future.");
|
|
4766
|
+
const { conversationId, reviewItemId } = input.subject;
|
|
4767
|
+
const root = conversationId === void 0 ? void 0 : await rootConversationId(conversationId);
|
|
4768
|
+
const items = conversationId === void 0 || root ? await visibleRowItems(user, root, reviewItemId) : [];
|
|
4769
|
+
if (items.length === 0) throw new InboxRowNotFoundError("Inbox row was not found.");
|
|
4770
|
+
const triggers = input.triggers ?? [];
|
|
4771
|
+
const snoozed = itemsWithTriggers(items, triggers, await namedResources(user, triggers));
|
|
4772
|
+
const timerId = wakeAtMs === void 0 ? void 0 : `inbox-snooze:${randomUUID()}`;
|
|
4773
|
+
if (timerId && wakeAtMs !== void 0) await scheduleInboxSnoozeTimer(timerId, wakeAtMs);
|
|
4774
|
+
const snoozeIds = await snoozeInboxItems(getDb(), {
|
|
4775
|
+
items: snoozed.map(({ item, triggers }) => ({
|
|
4776
|
+
reviewItemId: item.id,
|
|
4777
|
+
triggers: [...timerId ? [snoozeTimerTrigger(timerId)] : [], ...triggers]
|
|
4778
|
+
})),
|
|
4779
|
+
nowMs,
|
|
4780
|
+
userId: user.id
|
|
4781
|
+
});
|
|
4782
|
+
if (wakeAtMs !== void 0 && Date.now() >= wakeAtMs) await settleInboxSnoozes(getDb(), {
|
|
4783
|
+
snoozeIds,
|
|
4784
|
+
state: "woken"
|
|
4785
|
+
});
|
|
4786
|
+
return snoozed.map(({ item }) => item.id);
|
|
4787
|
+
}
|
|
4788
|
+
/**
|
|
4789
|
+
* Wake the viewer's snoozes on one Inbox row now. A row with no snooze of
|
|
4790
|
+
* theirs does not change.
|
|
4791
|
+
*/
|
|
4792
|
+
async function unsnoozeViewerRow(user, subject) {
|
|
4793
|
+
const { conversationId, reviewItemId } = subject;
|
|
4794
|
+
if (reviewItemId) {
|
|
4795
|
+
await unsnoozeInboxRow(getDb(), {
|
|
4796
|
+
reviewItemId,
|
|
4797
|
+
userId: user.id
|
|
4798
|
+
});
|
|
4799
|
+
return;
|
|
4800
|
+
}
|
|
4801
|
+
const root = conversationId && await rootConversationId(conversationId);
|
|
4802
|
+
if (!root) return;
|
|
4803
|
+
await unsnoozeInboxRow(getDb(), {
|
|
4804
|
+
rootConversationId: root,
|
|
4805
|
+
userId: user.id
|
|
4806
|
+
});
|
|
4807
|
+
}
|
|
4808
|
+
/**
|
|
4809
|
+
* Count the open items that the viewer snoozed. Snoozed shows a card for
|
|
4810
|
+
* each, as a root Conversation's stack does.
|
|
4811
|
+
*/
|
|
4812
|
+
async function countViewerSnoozes(user) {
|
|
4813
|
+
const [row] = await getDb().select({ count: count$1() }).from(juniorReviewItems).where(and(eq(juniorReviewItems.status, "open"), reviewItemVisibleTo(reviewItemReaderForUser(user)), reviewItemForUser(user.id), reviewItemSnoozedBy(user.id)));
|
|
4814
|
+
return row?.count ?? 0;
|
|
4815
|
+
}
|
|
3789
4816
|
// src/api/review-items/item-roots.ts
|
|
3790
4817
|
/** Name a child with no title by its kind: "Thread" or "Task". */
|
|
3791
4818
|
function kindLabel(kind) {
|
|
3792
4819
|
return kind ? `${kind[0].toUpperCase()}${kind.slice(1)}` : "Child agent";
|
|
3793
4820
|
}
|
|
3794
4821
|
/**
|
|
3795
|
-
* Read the root of each Conversation that
|
|
4822
|
+
* Read the root of each Conversation that owns an item, at any depth, from
|
|
3796
4823
|
* the root that each Conversation stores, with a label for a child, such as
|
|
3797
4824
|
* its Thread title. A root needs no read. A child is left out when the
|
|
3798
4825
|
* viewer cannot see its root's content, so the viewer learns no root,
|
|
3799
4826
|
* title, or name of a tree they cannot see
|
|
3800
4827
|
* (`policies/conversation-access.md`, rule for people). The payload then
|
|
3801
|
-
* names the Conversation
|
|
4828
|
+
* names the owner Conversation as its root.
|
|
3802
4829
|
*/
|
|
3803
4830
|
async function readItemRoots(db, items, viewer) {
|
|
3804
|
-
const ids = [...new Set(items.flatMap((item) =>
|
|
4831
|
+
const ids = [...new Set(items.flatMap((item) => {
|
|
4832
|
+
const conversationId = ownerConversationId(item);
|
|
4833
|
+
return !conversationId || item.ownerRootConversationId === null || item.ownerRootConversationId === conversationId ? [] : [conversationId];
|
|
4834
|
+
}))];
|
|
3805
4835
|
if (ids.length === 0) return /* @__PURE__ */ new Map();
|
|
3806
4836
|
const children = await db.select({
|
|
3807
4837
|
bindingName: juniorAgentBindings.name,
|
|
@@ -3829,6 +4859,21 @@ async function readItemRoots(db, items, viewer) {
|
|
|
3829
4859
|
}]];
|
|
3830
4860
|
}));
|
|
3831
4861
|
}
|
|
4862
|
+
// src/api/review-items/mentions.ts
|
|
4863
|
+
/**
|
|
4864
|
+
* Resolve the people that each Review item's title, body, and question
|
|
4865
|
+
* mention, in item order. Agents name people as Slack `<@U123>` mentions.
|
|
4866
|
+
*/
|
|
4867
|
+
async function readReviewItemMentions(executor, items) {
|
|
4868
|
+
return resolveMentions(executor, items.map((item) => ({
|
|
4869
|
+
tenantId: item.tenant?.provider === "slack" ? item.tenant.providerTenantId : void 0,
|
|
4870
|
+
texts: [
|
|
4871
|
+
item.title,
|
|
4872
|
+
item.body,
|
|
4873
|
+
item.request?.question
|
|
4874
|
+
]
|
|
4875
|
+
})));
|
|
4876
|
+
}
|
|
3832
4877
|
// src/api/review-items/routes.ts
|
|
3833
4878
|
const ARCHIVED_LIMIT = 50;
|
|
3834
4879
|
const cursorSchema = z.object({
|
|
@@ -3838,7 +4883,9 @@ const cursorSchema = z.object({
|
|
|
3838
4883
|
forUserId: z.string().min(1).optional(),
|
|
3839
4884
|
id: z.string().min(1),
|
|
3840
4885
|
needsUser: z.boolean().optional(),
|
|
4886
|
+
ownerKind: z.enum(["automation", "conversation"]).optional(),
|
|
3841
4887
|
query: z.string().min(1).optional(),
|
|
4888
|
+
snoozedForUserId: z.string().min(1).optional(),
|
|
3842
4889
|
sort: z.literal("waiting").optional(),
|
|
3843
4890
|
status: z.string().min(1).optional(),
|
|
3844
4891
|
version: z.literal(2)
|
|
@@ -3861,7 +4908,7 @@ function encodeCursor(item, filters, viewer) {
|
|
|
3861
4908
|
/** Decode a cursor of the same list, or stop the request with a 400. */
|
|
3862
4909
|
function decodeCursor(cursor, filters) {
|
|
3863
4910
|
const parsed = decodePageCursor(cursorSchema, cursor, INVALID_CURSOR);
|
|
3864
|
-
if (parsed.conversationId !== filters.conversationId || parsed.forUserId !== filters.forUserId || parsed.query !== filters.query || parsed.sort !== filters.sort || parsed.status !== filters.status || filters.status !== void 0 && parsed.closedAtMs === void 0 || filters.sort !== void 0 && parsed.needsUser === void 0) throwApiError(400, INVALID_CURSOR);
|
|
4911
|
+
if (parsed.conversationId !== filters.conversationId || parsed.forUserId !== filters.forUserId || parsed.ownerKind !== filters.ownerKind || parsed.query !== filters.query || parsed.snoozedForUserId !== filters.snoozedForUserId || parsed.sort !== filters.sort || parsed.status !== filters.status || filters.status !== void 0 && parsed.closedAtMs === void 0 || filters.sort !== void 0 && parsed.needsUser === void 0) throwApiError(400, INVALID_CURSOR);
|
|
3865
4912
|
return {
|
|
3866
4913
|
...parsed.closedAtMs !== void 0 ? { closedAt: new Date(parsed.closedAtMs) } : void 0,
|
|
3867
4914
|
createdAt: new Date(parsed.createdAtMs),
|
|
@@ -3877,16 +4924,23 @@ const ERROR_STATUS = {
|
|
|
3877
4924
|
};
|
|
3878
4925
|
function subjectPayload(subject) {
|
|
3879
4926
|
const objectType = subject.url && readLinkObjectType(subject.url);
|
|
4927
|
+
const resource = subject.url && snoozeSubjectResource(getEventCatalog(), subject.url);
|
|
3880
4928
|
return {
|
|
3881
4929
|
...subject,
|
|
3882
|
-
...objectType ? { objectType } : void 0
|
|
4930
|
+
...objectType ? { objectType } : void 0,
|
|
4931
|
+
...resource ? { resource: {
|
|
4932
|
+
events: [...resource.events],
|
|
4933
|
+
namespace: resource.namespace,
|
|
4934
|
+
phrases: { ...resource.phrases },
|
|
4935
|
+
resourceType: resource.resourceType
|
|
4936
|
+
} } : void 0
|
|
3883
4937
|
};
|
|
3884
4938
|
}
|
|
3885
4939
|
/** Build the API payload of one Review item for its viewer. */
|
|
3886
|
-
function reviewItemPayload(item, viewer, roots, related) {
|
|
3887
|
-
const
|
|
4940
|
+
function reviewItemPayload(item, viewer, roots, mentions, related) {
|
|
4941
|
+
const conversationId = ownerConversationId(item);
|
|
4942
|
+
const root = conversationId ? roots.get(conversationId) : void 0;
|
|
3888
4943
|
return {
|
|
3889
|
-
addedByConversationId: item.addedByConversationId,
|
|
3890
4944
|
...root ? { addedByLabel: root.label } : void 0,
|
|
3891
4945
|
assignedToEveryone: item.assignedToEveryone,
|
|
3892
4946
|
assignees: item.assignees,
|
|
@@ -3897,36 +4951,43 @@ function reviewItemPayload(item, viewer, roots, related) {
|
|
|
3897
4951
|
createdAt: item.createdAt.toISOString(),
|
|
3898
4952
|
id: item.id,
|
|
3899
4953
|
kind: item.kind,
|
|
3900
|
-
|
|
4954
|
+
owner: item.owner,
|
|
3901
4955
|
status: item.status,
|
|
3902
4956
|
title: item.title,
|
|
3903
4957
|
updatedAt: item.updatedAt.toISOString(),
|
|
3904
4958
|
visibility: item.visibility,
|
|
4959
|
+
...conversationId ? { rootConversationId: root?.rootConversationId ?? conversationId } : void 0,
|
|
3905
4960
|
...item.answer ? { answer: item.answer } : void 0,
|
|
3906
4961
|
...item.addedByTurnId ? { addedByTurnId: item.addedByTurnId } : void 0,
|
|
3907
4962
|
...item.automationId ? { automationId: item.automationId } : void 0,
|
|
3908
4963
|
...item.closeReason ? { closeReason: item.closeReason } : void 0,
|
|
3909
4964
|
...item.closedAt ? { closedAt: item.closedAt.toISOString() } : void 0,
|
|
3910
4965
|
...item.closedBy ? { closedBy: item.closedBy } : void 0,
|
|
4966
|
+
...mentions.length > 0 ? { mentions: [...mentions] } : void 0,
|
|
3911
4967
|
...related && (related.items.length > 0 || related.conversationIds.length > 0) ? { related } : void 0,
|
|
3912
4968
|
...item.request ? { request: item.request } : void 0,
|
|
3913
4969
|
...item.subject ? { subject: subjectPayload(item.subject) } : void 0
|
|
3914
4970
|
};
|
|
3915
4971
|
}
|
|
3916
4972
|
/**
|
|
3917
|
-
* Build the payloads of a page of items, with the root of each one
|
|
3918
|
-
* related work of the open ones. Each read
|
|
4973
|
+
* Build the payloads of a page of items, with the root of each one, the
|
|
4974
|
+
* people they mention, and the related work of the open ones. Each read
|
|
4975
|
+
* covers the page, and the reads run at once.
|
|
3919
4976
|
*/
|
|
3920
4977
|
async function reviewItemPayloads(items, viewer, reader) {
|
|
3921
4978
|
const db = getDb();
|
|
3922
|
-
const [roots, related] = await Promise.all([
|
|
3923
|
-
|
|
4979
|
+
const [roots, mentions, related] = await Promise.all([
|
|
4980
|
+
readItemRoots(db, items, viewer),
|
|
4981
|
+
readReviewItemMentions(getSqlExecutor(), items),
|
|
4982
|
+
readRelatedReviewWork(db, reader, viewer, items)
|
|
4983
|
+
]);
|
|
4984
|
+
return items.map((item, index) => reviewItemPayload(item, viewer, roots, mentions[index], related.get(item.id)));
|
|
3924
4985
|
}
|
|
3925
4986
|
function actionErrorResponse(error) {
|
|
3926
4987
|
if (error instanceof ReviewItemActionError) return jsonResponse(apiErrorSchema, { error: error.message }, { status: ERROR_STATUS[error.code] });
|
|
3927
4988
|
throw error;
|
|
3928
4989
|
}
|
|
3929
|
-
/** Create the authenticated
|
|
4990
|
+
/** Create the authenticated Inbox routes. */
|
|
3930
4991
|
function createReviewItemRoutes(services) {
|
|
3931
4992
|
const app = new Hono();
|
|
3932
4993
|
app.get("/", requireViewer, validateRequest("query", reviewItemListQuerySchema, "Invalid review item query."), async (context) => {
|
|
@@ -3935,7 +4996,9 @@ function createReviewItemRoutes(services) {
|
|
|
3935
4996
|
const filters = {
|
|
3936
4997
|
...query.conversationId ? { conversationId: query.conversationId } : void 0,
|
|
3937
4998
|
...query.for === "viewer" ? { forUserId: viewer.id } : void 0,
|
|
4999
|
+
...query.owner ? { ownerKind: query.owner } : void 0,
|
|
3938
5000
|
...query.q ? { query: query.q } : void 0,
|
|
5001
|
+
...query.snoozed ? { snoozedForUserId: viewer.id } : void 0,
|
|
3939
5002
|
...query.status[0] === "open" ? query.sort ? { sort: query.sort } : void 0 : { status: [...query.status].sort().join(",") }
|
|
3940
5003
|
};
|
|
3941
5004
|
const after = query.cursor ? decodeCursor(query.cursor, filters) : void 0;
|
|
@@ -3961,6 +5024,7 @@ function createReviewItemRoutes(services) {
|
|
|
3961
5024
|
}
|
|
3962
5025
|
const [open, archived] = await Promise.all([searchReviewItems(db, reader, {
|
|
3963
5026
|
...filters,
|
|
5027
|
+
...query.for === "viewer" && !filters.conversationId && !filters.query && !filters.snoozedForUserId ? { awakeForUserId: viewer.id } : void 0,
|
|
3964
5028
|
limit: query.limit + 1,
|
|
3965
5029
|
statuses: ["open"],
|
|
3966
5030
|
...filters.sort ? {
|
|
@@ -3991,25 +5055,20 @@ function createReviewItemRoutes(services) {
|
|
|
3991
5055
|
const viewer = context.get("viewer");
|
|
3992
5056
|
const query = context.req.valid("query");
|
|
3993
5057
|
const db = getDb();
|
|
3994
|
-
const [subjects, snoozed
|
|
3995
|
-
|
|
3996
|
-
countOpenReviewItemsForUser(db, {
|
|
3997
|
-
...reviewItemReaderForUser(viewer),
|
|
3998
|
-
userId: viewer.id
|
|
3999
|
-
}, query.snoozed),
|
|
4000
|
-
query.include === "automations" ? countOwnedAutomationsNeedingAttention(viewer) : void 0
|
|
4001
|
-
]);
|
|
5058
|
+
const [subjects, snoozed] = await Promise.all([countReviewItemsNeedingUserBySubject(db, viewer.id), query.include.includes("snoozed") ? countViewerSnoozes(viewer) : 0]);
|
|
5059
|
+
let automations = 0;
|
|
4002
5060
|
const linkTypes = readObjectLinkTypes();
|
|
4003
5061
|
let codeChanges = 0;
|
|
4004
5062
|
let decisions = 0;
|
|
4005
5063
|
let needsViewer = 0;
|
|
4006
5064
|
for (const subject of subjects) {
|
|
5065
|
+
automations += subject.automations;
|
|
4007
5066
|
needsViewer += subject.total;
|
|
4008
5067
|
decisions += subject.decisions;
|
|
4009
5068
|
if (subject.subjectUrl && readLinkObjectType(subject.subjectUrl, linkTypes) === "code_change") codeChanges += subject.total;
|
|
4010
5069
|
}
|
|
4011
5070
|
return jsonResponse(reviewItemCountSchema, {
|
|
4012
|
-
...automations
|
|
5071
|
+
...query.include.includes("automations") ? { automations } : void 0,
|
|
4013
5072
|
codeChanges,
|
|
4014
5073
|
decisions,
|
|
4015
5074
|
needsViewer,
|
|
@@ -4051,6 +5110,44 @@ function createReviewItemRoutes(services) {
|
|
|
4051
5110
|
});
|
|
4052
5111
|
return app;
|
|
4053
5112
|
}
|
|
5113
|
+
// src/api/inbox-snoozes/routes.ts
|
|
5114
|
+
/**
|
|
5115
|
+
* Create authenticated routes for the viewer's Inbox snoozes. The snoozed
|
|
5116
|
+
* rows are listed by `GET /api/review-items?for=viewer&snoozed=true`.
|
|
5117
|
+
*/
|
|
5118
|
+
function createInboxSnoozeRoutes() {
|
|
5119
|
+
const app = new Hono();
|
|
5120
|
+
app.post("/", requireViewer, validateRequest("json", inboxSnoozeCreateSchema, "Invalid snooze."), async (context) => {
|
|
5121
|
+
const { triggers, wakeAt, ...subject } = context.req.valid("json");
|
|
5122
|
+
try {
|
|
5123
|
+
const reviewItemIds = await createViewerSnooze(context.get("viewer"), {
|
|
5124
|
+
subject,
|
|
5125
|
+
...triggers ? { triggers } : void 0,
|
|
5126
|
+
...wakeAt ? { wakeAtMs: Date.parse(wakeAt) } : void 0
|
|
5127
|
+
});
|
|
5128
|
+
return jsonResponse(inboxSnoozeSchema, { reviewItemIds }, { status: 201 });
|
|
5129
|
+
} catch (error) {
|
|
5130
|
+
if (error instanceof InboxRowNotFoundError) throwApiError(404, error.message);
|
|
5131
|
+
if (error instanceof InboxSnoozeInputError) throwApiError(400, error.message);
|
|
5132
|
+
throw error;
|
|
5133
|
+
}
|
|
5134
|
+
});
|
|
5135
|
+
app.get("/resource", requireViewer, validateRequest("query", inboxSnoozeResourceQuerySchema, "Invalid link."), async (context) => {
|
|
5136
|
+
const resource = await viewerSnoozeResource(context.get("viewer"), getEventCatalog(), context.req.valid("query").url);
|
|
5137
|
+
if (!resource) throwApiError(404, "A snooze cannot wait on this link.");
|
|
5138
|
+
return jsonResponse(inboxSnoozeResourceSchema, {
|
|
5139
|
+
events: [...resource.events],
|
|
5140
|
+
namespace: resource.namespace,
|
|
5141
|
+
phrases: { ...resource.phrases },
|
|
5142
|
+
resourceType: resource.resourceType
|
|
5143
|
+
});
|
|
5144
|
+
});
|
|
5145
|
+
app.delete("/", requireViewer, validateRequest("json", inboxSnoozeSubjectSchema, "Invalid snooze."), async (context) => {
|
|
5146
|
+
await unsnoozeViewerRow(context.get("viewer"), context.req.valid("json"));
|
|
5147
|
+
return emptyResponse();
|
|
5148
|
+
});
|
|
5149
|
+
return app;
|
|
5150
|
+
}
|
|
4054
5151
|
// src/api/workspaces/routes.ts
|
|
4055
5152
|
function snapshotView(workspace) {
|
|
4056
5153
|
const recorded = workspace.snapshot;
|
|
@@ -4158,35 +5255,41 @@ async function readStatsReport() {
|
|
|
4158
5255
|
startDate.setUTCHours(0, 0, 0, 0);
|
|
4159
5256
|
startDate.setUTCDate(startDate.getUTCDate() - 89);
|
|
4160
5257
|
const start = startDate.toISOString().slice(0, 10);
|
|
4161
|
-
return
|
|
5258
|
+
return {
|
|
4162
5259
|
generatedAt: now.toISOString(),
|
|
4163
5260
|
stats: await readStats(start, end),
|
|
4164
5261
|
windowEnd: end,
|
|
4165
5262
|
windowStart: start
|
|
4166
|
-
}
|
|
5263
|
+
};
|
|
4167
5264
|
}
|
|
4168
5265
|
// src/api/versions.ts
|
|
4169
5266
|
/**
|
|
5267
|
+
* Build a JSON object of each Conversation's tree token by id, with no entry
|
|
5268
|
+
* for a missing one. Each id is its own key lookup in the same statement.
|
|
5269
|
+
* Pairs join with `||`, because `jsonb_build_object` takes at most 100
|
|
5270
|
+
* arguments.
|
|
5271
|
+
*/
|
|
5272
|
+
function conversationDetailsVersionQuery(db, conversationIds, viewerId) {
|
|
5273
|
+
if (conversationIds.length === 0) return sql`'{}'::jsonb`;
|
|
5274
|
+
const pairs = conversationIds.map((conversationId) => sql`jsonb_build_object(${conversationId}::text, (${conversationVersionQuery(db, conversationId, viewerId)}))`);
|
|
5275
|
+
return sql`jsonb_strip_nulls(${sql.join(pairs, sql` || `)})`;
|
|
5276
|
+
}
|
|
5277
|
+
/**
|
|
4170
5278
|
* Read the change tokens of the dashboard reads in one statement, so one
|
|
4171
5279
|
* cheap poll can tell which reads to refresh. The real endpoints still check
|
|
4172
|
-
* access.
|
|
5280
|
+
* access. A Conversation token shows no more than its detail report does:
|
|
4173
5281
|
* that report answers any viewer, with private content redacted.
|
|
4174
5282
|
*/
|
|
4175
|
-
async function readVersions(viewer, options
|
|
5283
|
+
async function readVersions(viewer, options) {
|
|
4176
5284
|
const db = getDb();
|
|
4177
5285
|
const [row] = await db.select({
|
|
4178
|
-
|
|
5286
|
+
conversationDetails: conversationDetailsVersionQuery(db, options.conversationIds, viewer.id),
|
|
4179
5287
|
conversations: sql`(${conversationFeedVersionQuery(db, viewer.id)})`,
|
|
4180
5288
|
reviewItems: sql`(${reviewItemsNeedingUserVersionQuery(db, viewer.id)})`,
|
|
4181
5289
|
spend: sql`(${personalSpendVersionQuery(db, viewer.email, Date.now())})`
|
|
4182
5290
|
}).from(juniorUsers).where(eq(juniorUsers.id, viewer.id));
|
|
4183
5291
|
if (!row) throw new Error("Viewer user row is missing");
|
|
4184
|
-
return
|
|
4185
|
-
...row.conversation ? { conversation: row.conversation } : void 0,
|
|
4186
|
-
conversations: row.conversations,
|
|
4187
|
-
reviewItems: row.reviewItems,
|
|
4188
|
-
spend: row.spend
|
|
4189
|
-
};
|
|
5292
|
+
return row;
|
|
4190
5293
|
}
|
|
4191
5294
|
// src/reporting.ts
|
|
4192
5295
|
function readDescriptionText(home) {
|
|
@@ -4198,7 +5301,7 @@ function readDescriptionText(home) {
|
|
|
4198
5301
|
}
|
|
4199
5302
|
/** Read discovered skills for runtime diagnostics and the Automation editor. */
|
|
4200
5303
|
async function readSkillReports() {
|
|
4201
|
-
const { discoverSkills } = await import("./skills-
|
|
5304
|
+
const { discoverSkills } = await import("./skills-BoZ80epJ.js").then((n) => n.s);
|
|
4202
5305
|
const skills = await discoverSkills();
|
|
4203
5306
|
return skillReportsSchema.parse(skills.map((skill) => ({
|
|
4204
5307
|
name: skill.name,
|
|
@@ -4212,7 +5315,7 @@ async function readSkillReports() {
|
|
|
4212
5315
|
* what the skill tells Junior. Returns null when no skill has that name.
|
|
4213
5316
|
*/
|
|
4214
5317
|
async function readSkillDetailReport(name) {
|
|
4215
|
-
const { discoverSkills, findSkillByName, parseSkillFile } = await import("./skills-
|
|
5318
|
+
const { discoverSkills, findSkillByName, parseSkillFile } = await import("./skills-BoZ80epJ.js").then((n) => n.s);
|
|
4216
5319
|
const skill = findSkillByName(name, await discoverSkills());
|
|
4217
5320
|
if (!skill) return null;
|
|
4218
5321
|
const parsed = parseSkillFile(await fs.readFile(path.join(skill.skillPath, "SKILL.md"), "utf8"), skill.name);
|
|
@@ -4227,7 +5330,7 @@ async function readSkillDetailReport(name) {
|
|
|
4227
5330
|
}
|
|
4228
5331
|
/** Read safe configured plugin metadata for authenticated runtime diagnostics. */
|
|
4229
5332
|
async function readPlugins() {
|
|
4230
|
-
const { pluginCatalogRuntime } = await import("./catalog-runtime-
|
|
5333
|
+
const { pluginCatalogRuntime } = await import("./catalog-runtime-DMY3VV-D.js").then((n) => n.t);
|
|
4231
5334
|
return pluginsSchema.parse(pluginCatalogRuntime.getProviders().map((plugin) => ({
|
|
4232
5335
|
configKeys: plugin.manifest.configKeys ?? [],
|
|
4233
5336
|
description: plugin.manifest.description,
|
|
@@ -4239,7 +5342,7 @@ async function readPlugins() {
|
|
|
4239
5342
|
async function readRuntimeInfoReport() {
|
|
4240
5343
|
const [{ homeDir }, { pluginCatalogRuntime }, plugins, skills] = await Promise.all([
|
|
4241
5344
|
import("./package-discovery-DD9vencX.js").then((n) => n.r),
|
|
4242
|
-
import("./catalog-runtime-
|
|
5345
|
+
import("./catalog-runtime-DMY3VV-D.js").then((n) => n.t),
|
|
4243
5346
|
readPlugins(),
|
|
4244
5347
|
readSkillReports()
|
|
4245
5348
|
]);
|
|
@@ -4256,7 +5359,7 @@ async function readRuntimeInfoReport() {
|
|
|
4256
5359
|
/** Read sanitized operational summaries contributed by plugins. */
|
|
4257
5360
|
async function readPluginOperationalReportFeed() {
|
|
4258
5361
|
const nowMs = Date.now();
|
|
4259
|
-
const { getPluginOperationalReports } = await import("./projection-
|
|
5362
|
+
const { getPluginOperationalReports } = await import("./projection-Cns7XwWa.js").then((n) => n.En);
|
|
4260
5363
|
return pluginOperationalReportFeedSchema.parse({
|
|
4261
5364
|
source: "plugins",
|
|
4262
5365
|
generatedAt: new Date(nowMs).toISOString(),
|
|
@@ -4279,25 +5382,29 @@ function createJuniorApi(options = {}) {
|
|
|
4279
5382
|
app.get("/api/plugin-reports", async () => jsonResponse(pluginOperationalReportFeedSchema, await readPluginOperationalReportFeed()));
|
|
4280
5383
|
app.get("/api/stats", async () => jsonResponse(statsReportSchema, await readStatsReport()));
|
|
4281
5384
|
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" } }));
|
|
5385
|
+
for (const path of REVALIDATED_READ_PATHS) app.use(path, revalidateContent);
|
|
4282
5386
|
const queue = options.conversationWorkQueue ?? getVercelConversationWorkQueue();
|
|
5387
|
+
const waitUntil$1 = options.waitUntil ?? ((task) => waitUntil(typeof task === "function" ? task() : task));
|
|
4283
5388
|
app.route("/api/conversations", createConversationRoutes({
|
|
4284
5389
|
attachmentStorage: getAttachmentStorage(),
|
|
4285
5390
|
queue,
|
|
4286
|
-
waitUntil:
|
|
5391
|
+
waitUntil: waitUntil$1
|
|
4287
5392
|
}));
|
|
4288
5393
|
app.route("/api/review-items", createReviewItemRoutes({ delivery: {
|
|
4289
5394
|
queue,
|
|
4290
5395
|
show: createSlackReviewItemShow(getProductionSlackAdapter)
|
|
4291
5396
|
} }));
|
|
5397
|
+
app.route("/api/inbox/snoozes", createInboxSnoozeRoutes());
|
|
4292
5398
|
app.route("/api/code", createCodeRoutes());
|
|
4293
5399
|
app.route("/api/connections", createConnectionRoutes());
|
|
4294
5400
|
app.route("/api/notifications", createNotificationRoutes());
|
|
4295
5401
|
app.route("/api/personal-tokens", createPersonalTokenRoutes());
|
|
4296
5402
|
app.route("/api/service-accounts", createServiceAccountRoutes());
|
|
4297
5403
|
app.route("/api/cache-warming", createCacheWarmingRoutes());
|
|
5404
|
+
app.route("/api/gateway-providers", createGatewayProviderRoutes());
|
|
4298
5405
|
app.route("/api/images", createImageRoutes());
|
|
4299
5406
|
app.route("/api/objects", createObjectRoutes());
|
|
4300
|
-
app.route("/api/people", createPeopleRoutes());
|
|
5407
|
+
app.route("/api/people", createPeopleRoutes({ waitUntil: waitUntil$1 }));
|
|
4301
5408
|
app.route("/api/locations", createLocationRoutes());
|
|
4302
5409
|
app.route("/api/user-pages", createUserPageRoutes());
|
|
4303
5410
|
app.route("/api/user-customization", createUserCustomizationRoutes());
|
|
@@ -4314,4 +5421,4 @@ function createJuniorApi(options = {}) {
|
|
|
4314
5421
|
});
|
|
4315
5422
|
return app;
|
|
4316
5423
|
}
|
|
4317
|
-
export { DEFAULT_USER_SETTINGS, authenticatePersonalToken, createJuniorApi, isAllowedDomain, jsonResponse, parseEmail, readUserSettings, readViewerAvatarUrl, resolveViewerUser, updateUserSettings, updateViewerDisplayName };
|
|
5424
|
+
export { DEFAULT_USER_SETTINGS, REVALIDATED_READ_PATHS, authenticatePersonalToken, createJuniorApi, isAllowedDomain, jsonResponse, parseEmail, readUserSettings, readViewerAvatarUrl, resolveViewerUser, revalidateContent, updateUserSettings, updateViewerDisplayName };
|