@sentry/junior 0.281.0 → 0.282.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-RVQGEa98.js → adapter-BAqo7eOH.js} +1 -1
- package/dist/{admin-DQpHx6Og.js → admin-DbWpMHh6.js} +1 -1
- package/dist/{agent-runner-B229gXUY.js → agent-runner-h4CDcnDV.js} +22 -25
- package/dist/api.d.ts +1 -1
- package/dist/api.js +21 -21
- package/dist/{app-BQ9RZS43.d.ts → app-B-0wwAxr.d.ts} +1 -1
- package/dist/app.d.ts +1 -1
- package/dist/app.js +27 -27
- package/dist/{assistant-reply-DQbtwc6j.js → assistant-reply-4Wvo95-N.js} +1 -1
- package/dist/{background-compaction-queue-oegyrxSe.js → background-compaction-queue-CoWqScCC.js} +2 -2
- package/dist/{briefs-BwzGWJgR.js → briefs-CMiotFo9.js} +2 -2
- package/dist/{catalog-runtime-ClKzLvbN.js → catalog-runtime-Cpje_Uic.js} +1 -1
- package/dist/cli/chat.js +14 -14
- package/dist/cli/check.js +3 -3
- package/dist/cli/main.js +3 -3
- package/dist/cli/plugins.js +4 -4
- package/dist/cli/snapshot-create.js +4 -4
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +74 -7
- package/dist/{client-DkG0Tj53.js → client-BHgCXeaF.js} +2 -2
- package/dist/{config-3AZ11aSM.js → config-DBdBimZ9.js} +1 -1
- package/dist/{connections-C0ut_6RW.js → connections-DjY72_uF.js} +10 -10
- package/dist/{conversation-privacy-DAgeBGLN.js → conversation-privacy-DiDh9KE4.js} +1 -1
- package/dist/{credential-sync-Bg8NPuvj.js → credential-sync-DUrQwccr.js} +13 -13
- package/dist/{db-BCFM0CUX.d.ts → db-hQsoB16L.d.ts} +1 -0
- package/dist/{executor-DLKnzP6S.js → executor-CGqJCxgR.js} +14 -3
- package/dist/instrumentation.js +2 -2
- package/dist/{logging-DHzrobea.js → logging-DapIaJAi.js} +1 -1
- package/dist/{message-LR8z5jXJ.js → message-BjN5sKad.js} +9 -9
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +3 -11
- package/dist/{oauth-callback-server-EWdpj0_y.js → oauth-callback-server-DVHKrjJP.js} +2 -2
- package/dist/{projection-Bhz1tp0G.js → projection-ii_OYu6z.js} +28 -13
- package/dist/{registry-EjhulgQW.js → registry-DpjG3yS-.js} +1 -1
- package/dist/{resolve-Cw6OW4Fj.js → resolve-iMW9Dgo2.js} +3 -3
- package/dist/{result-BoD0jevy.js → result-BrlvfyIj.js} +8 -8
- package/dist/{runner-D22bsBDS.js → runner-Bg9mr2pB.js} +10 -10
- package/dist/{sandbox-egress-signals-BG5GYacQ.js → sandbox-egress-signals-Bd3lb_Wd.js} +1 -1
- package/dist/{service-account-xo-CeMqI.js → service-account-Bd1348kw.js} +3 -3
- package/dist/{service-account-Dd1nnAQZ.js → service-account-Dfl9Pitm.js} +3 -3
- package/dist/{session-stop-CHSYB2uw.js → session-stop-CVEEx_YD.js} +10 -10
- package/dist/{skills-BGJr6xtW.js → skills-DqUUuf4L.js} +2 -2
- package/dist/{spawn-Cl8WS7zi.js → spawn-e7rQs14T.js} +2 -2
- package/dist/{stop-C9lHWpvl.js → stop-DtpBUUJq.js} +265 -119
- package/dist/{store-DeTnwVJt.js → store-nETG4KVg.js} +4 -4
- package/dist/{store-C4z8gOgZ.js → store-nu3Xx08K.js} +3 -3
- package/dist/{task-queue-BBos68l0.js → task-queue-CYje8WKs.js} +3 -3
- package/dist/{task-runner-BSF9zO-H.js → task-runner-CwegN45x.js} +6 -6
- package/dist/{thread-state-DGq1o5JX.js → thread-state-BDaMl9yd.js} +4 -4
- package/dist/{turn-failure-response--9bA4uLP.js → turn-failure-response-CV06tN_R.js} +6 -6
- package/dist/{turn-lifecycle-t5fimxwQ.js → turn-lifecycle-CF2N7ud5.js} +1 -1
- package/dist/{turn-session-routing-RBtUe-3y.js → turn-session-routing-BIJGJjVh.js} +8 -8
- package/dist/{validation-DrR0leBT.js → validation-DXvxEEjq.js} +1 -1
- package/dist/{version-D_HFt_Dq.js → version-CzEk1KBX.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{viewer-DWlpSFdj.js → viewer-C2PztlYX.js} +18 -6
- package/dist/{work-pPoqtRea.js → work-BM_L0Pv9.js} +10 -10
- package/dist/{worker-CoVKgJ-O.js → worker-2no53G60.js} +6 -6
- package/migrations/0062_plugin_report_index.sql +3 -3
- package/migrations/0078_plugin_conversation_index.sql +3 -3
- package/migrations/0079_conversation_event_author_index.sql +3 -3
- package/migrations/0080_conversation_event_latest_message_indexes.sql +27 -0
- package/migrations/meta/0080_snapshot.json +4265 -0
- package/migrations/meta/_journal.json +7 -0
- package/package.json +5 -5
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
import { v as __exportAll } from "./sentry-BRTJqumy.js";
|
|
2
|
-
import { Br as getDashboardObjectIconLink, Ln as getPlugins, Lr as verifyTimerWatchCredentialSubject, N as normalizeConversationText, Nn as getPluginSlackConversationLink,
|
|
3
|
-
import { n as botConfig } from "./config-
|
|
4
|
-
import { h as logWarn, m as logInfo, p as logException } from "./logging-
|
|
5
|
-
import { C as getSqlExecutor, F as SYSTEM_IDENTITY_ID, J as nextDetailVersion, x as getConversationStore } from "./viewer-
|
|
6
|
-
import {
|
|
7
|
-
import { h as credentialSubjectSchema } from "./registry-
|
|
8
|
-
import { r as getStateAdapter } from "./adapter-
|
|
2
|
+
import { Br as getDashboardObjectIconLink, Ln as getPlugins, Lr as verifyTimerWatchCredentialSubject, N as normalizeConversationText, Nn as getPluginSlackConversationLink, Qa as buildSentryConversationUrl, Rr as JUNIOR_THREAD_STATE_TTL_MS, Wr as ToolInputError, Zt as isAssistantMessage, _i as escapeSlackMrkdwnText, en as isToolResultError, ki as postSlackMessage, nn as normalizeToolNameFromResult, tn as isToolResultMessage, vi as formatSlackLink, yi as normalizeSlackReplyMarkdown, zr as getDashboardConversationLink } from "./projection-ii_OYu6z.js";
|
|
3
|
+
import { n as botConfig } from "./config-DBdBimZ9.js";
|
|
4
|
+
import { h as logWarn, m as logInfo, p as logException } from "./logging-DapIaJAi.js";
|
|
5
|
+
import { C as getSqlExecutor, F as SYSTEM_IDENTITY_ID, J as nextDetailVersion, x as getConversationStore } from "./viewer-C2PztlYX.js";
|
|
6
|
+
import { A as juniorConversations } from "./executor-CGqJCxgR.js";
|
|
7
|
+
import { h as credentialSubjectSchema } from "./registry-DpjG3yS-.js";
|
|
8
|
+
import { r as getStateAdapter } from "./adapter-BAqo7eOH.js";
|
|
9
9
|
import { R as readMessageAttachments } from "./conversation-DNtcULyX.js";
|
|
10
10
|
import { r as EVENT_AUTHOR_ID } from "./prompt-DI6KCtwb.js";
|
|
11
|
-
import { a as QUIET_MARKER, r as sanitizeAssistantText } from "./assistant-reply-
|
|
12
|
-
import { r as appendAndEnqueueInboundMessage } from "./store-
|
|
13
|
-
import { dt as CORE_EVENT_NAMESPACE, ht as eventGuidance, mt as eventCatalogEntry } from "./turn-session-routing-
|
|
11
|
+
import { a as QUIET_MARKER, r as sanitizeAssistantText } from "./assistant-reply-4Wvo95-N.js";
|
|
12
|
+
import { r as appendAndEnqueueInboundMessage } from "./store-nu3Xx08K.js";
|
|
13
|
+
import { dt as CORE_EVENT_NAMESPACE, ht as eventGuidance, mt as eventCatalogEntry } from "./turn-session-routing-BIJGJjVh.js";
|
|
14
14
|
import * as z from "zod";
|
|
15
15
|
import { eq, inArray } from "drizzle-orm";
|
|
16
16
|
import { agentEventKeys, eventMatchFieldsSchema, objectFactFields, objectPresentation, objectTypeSchema } from "@sentry/junior-plugin-api";
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { v as __exportAll } from "./sentry-BRTJqumy.js";
|
|
2
|
-
import { h as logWarn } from "./logging-
|
|
2
|
+
import { h as logWarn } from "./logging-DapIaJAi.js";
|
|
3
3
|
import { s as skillRoots } from "./package-discovery-DJhGdS4c.js";
|
|
4
|
-
import { n as pluginCatalogRuntime } from "./catalog-runtime-
|
|
4
|
+
import { n as pluginCatalogRuntime } from "./catalog-runtime-Cpje_Uic.js";
|
|
5
5
|
import path from "node:path";
|
|
6
6
|
import * as z from "zod";
|
|
7
7
|
import fs from "node:fs/promises";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { v as __exportAll } from "./sentry-BRTJqumy.js";
|
|
2
|
-
import { Ft as toolInvocationDestination, Pt as actorFromRun } from "./agent-runner-
|
|
3
|
-
import { n as createAndEnqueueAgentInvocation } from "./work-
|
|
2
|
+
import { Ft as toolInvocationDestination, Pt as actorFromRun } from "./agent-runner-h4CDcnDV.js";
|
|
3
|
+
import { n as createAndEnqueueAgentInvocation } from "./work-BM_L0Pv9.js";
|
|
4
4
|
// src/chat/agent-invocations/spawn.ts
|
|
5
5
|
var spawn_exports = /* @__PURE__ */ __exportAll({ bindSpawnAgent: () => bindSpawnAgent });
|
|
6
6
|
/** Bind a Run's Actor and credentials to new Agent invocations. */
|
|
@@ -1,36 +1,36 @@
|
|
|
1
1
|
import { h as startSpan, i as getActiveSpan, r as continueTrace } from "./sentry-BRTJqumy.js";
|
|
2
|
-
import { $ as completeTurnRecord, $
|
|
3
|
-
import { a as completeText, c as resolveGatewayModel, m as escapeXml, r as completeDecision, x as isProviderRetryError } from "./client-
|
|
4
|
-
import { c as getSlackClientSecret, i as getChatConfig, l as getSlackSigningSecret, n as botConfig, o as getSlackBotToken, s as getSlackClientId, v as normalizeSlackEmojiName, y as createS3AttachmentStorage } from "./config-
|
|
5
|
-
import { E as withSpan, G as toOptionalNumber, K as toOptionalString, S as setTags, T as withLogContext, W as isRecord, b as setSpanAttributes, f as logError, h as logWarn, m as logInfo, n as createChatSdkLogger, o as getActiveTraceContext, p as logException, s as getActiveTraceId, t as buildTurnFailureResponse, y as setSentryUser } from "./logging-
|
|
6
|
-
import { t as JUNIOR_VERSION } from "./version-
|
|
2
|
+
import { $ as completeTurnRecord, $n as takeReviewItem, A as getConversationMessageSlackTs, Aa as createPluginLogger, Ai as removeReactionFromMessage, Ba as conversationPinnedForUser, Ci as addReactionToMessage, D as buildConversationContext, E as appendThreadContextMessages, En as webActorUserIds, F as turnHasReply, Fa as conversationArchivedForUser, Fi as SlackActionError, H as AuthorizationFlowDisabledError, Ha as readConversationViewerMarks, Hi as normalizeSlackConversationId, I as upsertConversationMessage, Ia as conversationHasParticipantUser, Ii as downloadPrivateSlackFile, J as wasPendingAuthStopped, Ja as readConversationEventPageAfter, Jn as getReviewItem, K as clearPendingAuth, Ka as readLatestConversationBrief, La as conversationIsMemberRoot, Ln as getPlugins, Lr as verifyTimerWatchCredentialSubject, M as markConversationMessage, Ma as createConversationAccessReader, N as normalizeConversationText, Na as readConversationAccessFromSql, O as createConversationMemoryService, P as recordDeliveredAssistantMessage, Pa as conversationArchivedForEmail, Q as abandonTurnRecord, Qa as buildSentryConversationUrl, R as PluginCredentialFailureError, Ra as conversationNotArchivedForEmail, Ri as getHeaderString, Rr as JUNIOR_THREAD_STATE_TTL_MS, S as resolveConversationTitle, Si as truncateStatusText, Sn as isExperimentalFeatureEnabled, Ua as viewerConversationMembership, Ut as persistWithRetry, Va as conversationViewerMarks, Vi as isDmChannel, Wi as withSlackRetries, Wn as closeReviewItem, X as loadTurnCheckpoint, Xn as listReplyActionItems, Ya as readConversationEventPageAround, Z as saveTurnCheckpoint, Zn as listWaitingConversations, a as loadProjection, an as trimTrailingAssistantMessages, ao as recordSlackAttachment, ar as isOnlyAssignee, bi as normalizeSlackStatusText, d as recordAuthorizationCompleted, eo as notInheritedByForkChild, et as failTurnRecord, fn as decideSubscribedThreadReply, go as configValueSchema, h as recordSubscribedReplyRoute, i as loadConversationProjection, io as readSlackAttachmentsVersion, ir as canReadReviewItem, j as isHumanConversationMessage, k as estimateConversationContextTokens, ln as buildDeterministicAssistantMessageId, lo as listConversationAnnotations, lr as reviewItemNeedsUser, mn as getThreadStopDecision, mo as createPluginCache, n as commitMessages, nr as canActOnReviewItem, nt as listTurnSummaries, o as loadTurnProjection, pn as getSubscribedReplyPreflightDecision, po as lookupSlackUser, qa as readConversationEventPage, ro as readAttachmentVisionSummary, rt as recordTurnSummary, t as commitAcceptedReply, to as getSlackFileId, tt as getTurnRecord, un as buildDeterministicTurnId, uo as listConversationAnnotationsById, ur as reviewItemReaderForUser, v as hydrateConversationMessages, vo as piMessageFromHistoryItem, w as fallbackShortTitle, wn as createUserTokenStore, x as persistConversationMessageSummaries, xr as cancelSubscriptions, y as persistConversationMessages, za as conversationNotArchivedForUser, zi as getSlackClient, zt as buildTurnErrorResponse } from "./projection-ii_OYu6z.js";
|
|
3
|
+
import { a as completeText, c as resolveGatewayModel, m as escapeXml, r as completeDecision, x as isProviderRetryError } from "./client-BHgCXeaF.js";
|
|
4
|
+
import { c as getSlackClientSecret, i as getChatConfig, l as getSlackSigningSecret, n as botConfig, o as getSlackBotToken, s as getSlackClientId, v as normalizeSlackEmojiName, y as createS3AttachmentStorage } from "./config-DBdBimZ9.js";
|
|
5
|
+
import { E as withSpan, G as toOptionalNumber, K as toOptionalString, S as setTags, T as withLogContext, W as isRecord, b as setSpanAttributes, f as logError, h as logWarn, m as logInfo, n as createChatSdkLogger, o as getActiveTraceContext, p as logException, s as getActiveTraceId, t as buildTurnFailureResponse, y as setSentryUser } from "./logging-DapIaJAi.js";
|
|
6
|
+
import { t as JUNIOR_VERSION } from "./version-CzEk1KBX.js";
|
|
7
7
|
import { f as parseSlackTeamId, h as parseSlackMessageTs, i as isActorUserId, n as createSlackActor, o as isUserActor, r as createSlackResumeActor, s as parseActorUserId, t as createActor, u as parseSlackChannelId } from "./actor-6jsm_v96.js";
|
|
8
|
-
import { $ as agentTurnUsageSchema, A as loadConversationSlackTenantIds, C as getSqlExecutor, I as resolveActorIdentityId, J as nextDetailVersion, K as parseSessionSource, L as saveActorAvatar, N as locationFromRow, S as getDb, X as addAgentTurnUsage, et as hasAgentTurnUsage, f as identityAvatarUrl, h as readUserAvatarUrls, it as requireSlackDestination, k as withConversationEventLock, nt as createSlackDestination, q as conversationDetailTouch, tt as resolveRootConversationId, x as getConversationStore, y as getConversationEventStore } from "./viewer-
|
|
9
|
-
import { A as
|
|
8
|
+
import { $ as agentTurnUsageSchema, A as loadConversationSlackTenantIds, C as getSqlExecutor, I as resolveActorIdentityId, J as nextDetailVersion, K as parseSessionSource, L as saveActorAvatar, N as locationFromRow, S as getDb, X as addAgentTurnUsage, et as hasAgentTurnUsage, f as identityAvatarUrl, h as readUserAvatarUrls, it as requireSlackDestination, k as withConversationEventLock, nt as createSlackDestination, q as conversationDetailTouch, tt as resolveRootConversationId, x as getConversationStore, y as getConversationEventStore } from "./viewer-C2PztlYX.js";
|
|
9
|
+
import { A as juniorConversations, C as juniorConversationEvents, E as juniorCodeChanges, M as juniorUsers, N as juniorDestinations, S as isUserInstruction, _ as juniorConversationParticipants, c as juniorReviewItems, g as juniorConversationReadPositions, j as juniorIdentities, k as conversationReadColumns, o as juniorReviewItemConversations, y as juniorConversationBriefs } from "./executor-CGqJCxgR.js";
|
|
10
10
|
import { g as instructionProvenanceFor, m as contextProvenance, n as detectImageMediaType, r as isVisionImageMediaType } from "./media-Dq9_svfQ.js";
|
|
11
|
-
import { d as actorLogContext, f as credentialContextForActor } from "./registry-
|
|
12
|
-
import { A as runWithSlackInstallation, At as withoutSavedSteeringMessages, Et as conversationSubtreeColumns, F as resolveSlackChannelIdFromThreadId, I as getConversationInfo, J as readConversationSourceTask, Lt as shouldEmitDevAgentTrace, M as parseSlackThreadId, N as readSlackRawMessageContext, Nt as RetryableDeliveryError, P as resolveSlackChannelIdFromMessage, R as listThreadReplies, S as createSlackReviewItemShow, Tt as conversationSubtree, a as buildAuthPauseResponse, b as renderAttachmentText, dt as recordWebConversationActivity, ft as webActorFromUser, i as measureTurnCompactionWait, kt as buildSteeringPiMessage, lt as createAndEnqueueConversation, m as latestProgressStatus, mt as decodeInputImages, n as executeAgentRun, ot as acceptsWebMessages, pt as resolveConversationDestination, rt as deliverReviewItemChange, st as appendAndEnqueueWebMessage, t as createAgentRunner, ut as createConversationId, vt as storeAttachment, x as renderBlockText, z as resolveDestinationVisibility } from "./agent-runner-
|
|
11
|
+
import { d as actorLogContext, f as credentialContextForActor } from "./registry-DpjG3yS-.js";
|
|
12
|
+
import { A as runWithSlackInstallation, At as withoutSavedSteeringMessages, Et as conversationSubtreeColumns, F as resolveSlackChannelIdFromThreadId, I as getConversationInfo, J as readConversationSourceTask, Lt as shouldEmitDevAgentTrace, M as parseSlackThreadId, N as readSlackRawMessageContext, Nt as RetryableDeliveryError, P as resolveSlackChannelIdFromMessage, R as listThreadReplies, S as createSlackReviewItemShow, Tt as conversationSubtree, a as buildAuthPauseResponse, b as renderAttachmentText, dt as recordWebConversationActivity, ft as webActorFromUser, i as measureTurnCompactionWait, kt as buildSteeringPiMessage, lt as createAndEnqueueConversation, m as latestProgressStatus, mt as decodeInputImages, n as executeAgentRun, ot as acceptsWebMessages, pt as resolveConversationDestination, rt as deliverReviewItemChange, st as appendAndEnqueueWebMessage, t as createAgentRunner, ut as createConversationId, vt as storeAttachment, x as renderBlockText, z as resolveDestinationVisibility } from "./agent-runner-h4CDcnDV.js";
|
|
13
13
|
import { a as withLock, n as MUTATION_LOCK_TTL_MS, r as acquireActiveLock } from "./locks-D-0h111u.js";
|
|
14
|
-
import { r as getStateAdapter } from "./adapter-
|
|
14
|
+
import { r as getStateAdapter } from "./adapter-BAqo7eOH.js";
|
|
15
15
|
import { R as readMessageAttachments, c as conversationDetailReportSchema, p as conversationFeedSchema, u as conversationEventPageSchema } from "./conversation-DNtcULyX.js";
|
|
16
16
|
import { a as EVENT_SYSTEM_ACTOR, o as isEventConversationMessage } from "./prompt-DI6KCtwb.js";
|
|
17
|
-
import { $ as markTurnFailed, G as TurnInputCommitLostError, J as isCooperativeTurnYieldError, K as TurnInputDeferredError, Q as markTurnCompleted, U as ConversationTurnBoundaryError, W as CooperativeTurnYieldError, X as isTurnInputDeferredError, Y as isTurnInputCommitLostError, Z as markTurnClosed, et as startActiveTurn, h as getChildAgentLabel, q as getConversationTurnBoundaryError } from "./store-
|
|
18
|
-
import { n as getAssistantReplyText, t as decideReply } from "./assistant-reply-
|
|
19
|
-
import { C as savedTurnInputMessages, E as maybePostAutomatedTurnLimitNotice, I as deliversFinalText, L as finishedRunReply, M as recordFinishedTurnForAutomatedLimit, O as resolveSlackReplyTarget, R as postsRunNotices, S as joinMailboxText, V as runDispatchOutcome, c as isEventMailboxMetadata, i as skipInputBeforeConversationStop, k as sendSlackReply, l as renderEventBatchText, s as eventBatchMessageMeta, u as timerWatchCredentialSubject, w as webConversationMessage } from "./session-stop-
|
|
17
|
+
import { $ as markTurnFailed, G as TurnInputCommitLostError, J as isCooperativeTurnYieldError, K as TurnInputDeferredError, Q as markTurnCompleted, U as ConversationTurnBoundaryError, W as CooperativeTurnYieldError, X as isTurnInputDeferredError, Y as isTurnInputCommitLostError, Z as markTurnClosed, et as startActiveTurn, h as getChildAgentLabel, q as getConversationTurnBoundaryError } from "./store-nETG4KVg.js";
|
|
18
|
+
import { n as getAssistantReplyText, t as decideReply } from "./assistant-reply-4Wvo95-N.js";
|
|
19
|
+
import { C as savedTurnInputMessages, E as maybePostAutomatedTurnLimitNotice, I as deliversFinalText, L as finishedRunReply, M as recordFinishedTurnForAutomatedLimit, O as resolveSlackReplyTarget, R as postsRunNotices, S as joinMailboxText, V as runDispatchOutcome, c as isEventMailboxMetadata, i as skipInputBeforeConversationStop, k as sendSlackReply, l as renderEventBatchText, s as eventBatchMessageMeta, u as timerWatchCredentialSubject, w as webConversationMessage } from "./session-stop-CVEEx_YD.js";
|
|
20
20
|
import { _ as isEmptyUserInputAnswer, b as webMessageId, v as normalizeUserInputAnswer } from "./reporting-window-B-QP9zX1.js";
|
|
21
|
-
import { g as getTurnRequestDeadline, l as getVercelConversationWorkQueue } from "./background-compaction-queue-
|
|
22
|
-
import { D as stopConversationWork, E as steerWebPendingMessages, a as cancelHumanFacingPendingMessages, g as getConversationWorkState, h as getConversation, m as ensureConversationWake, r as appendAndEnqueueInboundMessage, w as requestConversationWork } from "./store-
|
|
23
|
-
import { _ as markDispatchCompleted, a as confirmDispatchMailboxAppend, d as getDispatchTurnId, g as markDispatchBlocked, h as markDispatchAwaitingResume, i as claimDispatchMailboxAppend, j as readAutomationTitlesByConversationId, l as getDispatchInputMessageId, n as resolveTurnSessionRouting, p as isTerminalDispatchStatus, s as getDispatchConversationId, t as resolveConversationRouting, u as getDispatchRecord, v as markDispatchFailed, y as markDispatchRunning } from "./turn-session-routing-
|
|
21
|
+
import { g as getTurnRequestDeadline, l as getVercelConversationWorkQueue } from "./background-compaction-queue-CoWqScCC.js";
|
|
22
|
+
import { D as stopConversationWork, E as steerWebPendingMessages, a as cancelHumanFacingPendingMessages, g as getConversationWorkState, h as getConversation, m as ensureConversationWake, r as appendAndEnqueueInboundMessage, w as requestConversationWork } from "./store-nu3Xx08K.js";
|
|
23
|
+
import { _ as markDispatchCompleted, a as confirmDispatchMailboxAppend, d as getDispatchTurnId, g as markDispatchBlocked, h as markDispatchAwaitingResume, i as claimDispatchMailboxAppend, j as readAutomationTitlesByConversationId, l as getDispatchInputMessageId, n as resolveTurnSessionRouting, p as isTerminalDispatchStatus, s as getDispatchConversationId, t as resolveConversationRouting, u as getDispatchRecord, v as markDispatchFailed, y as markDispatchRunning } from "./turn-session-routing-BIJGJjVh.js";
|
|
24
24
|
import { d as apiErrorSchema, f as healthReportSchema, s as conversationPendingMessagesReportSchema } from "./conversation-pending-messages-LlFnr9-m.js";
|
|
25
|
-
import { a as withAgentInvocationResultActors, c as listActiveMailboxTurns, d as turnInputFactsFromConversationMessage, f as legacyWebMailboxMetadataSchema, l as resolveMailboxTurnWork, n as enqueueAgentInvocationResult, o as getAuthPausedConversationTurnId, s as getEventBatchDelayMs, t as createChildConversationWorker, u as sourceFromTurnInput } from "./result-
|
|
26
|
-
import { n as getTurnLifecycle, t as ConversationTurnLifecycleService } from "./turn-lifecycle-
|
|
27
|
-
import { o as AgentRunError, s as executeTurn } from "./work-
|
|
28
|
-
import { a as persistThreadStateById, i as persistThreadRuntimeState, n as getPersistedSandboxState, o as coerceThreadConversationState, r as getPersistedThreadState, t as getLocationConfigurationService } from "./thread-state-
|
|
29
|
-
import { c as deleteWebAuthorization, d as createPausedTurns, f as getPausedTurnRequest, h as getTurnAuthorization, l as getWebAuthorization, m as wakePausedTurn, s as createWebAuthorization } from "./connections-
|
|
30
|
-
import { t as bindMessageAgent } from "./message-
|
|
31
|
-
import { t as bindSpawnAgent } from "./spawn-
|
|
32
|
-
import { n as scheduleSessionCompletedPluginTasks, t as processPluginTask } from "./task-runner-
|
|
33
|
-
import { a as persistAuthPauseTurnState, c as getTurnUserSlackMessageTs, i as completeAuthPauseTurn, l as buildDeliveredTurnStatePatch, n as getAgentTurnDiagnosticsAttributes, o as getTurnUserMessage, r as requireTurnFailureEventId, s as getTurnUserReplyAttachmentContext, t as finalizeFailedTurnReplyWithEvent, u as loadPendingMessageCards } from "./turn-failure-response
|
|
25
|
+
import { a as withAgentInvocationResultActors, c as listActiveMailboxTurns, d as turnInputFactsFromConversationMessage, f as legacyWebMailboxMetadataSchema, l as resolveMailboxTurnWork, n as enqueueAgentInvocationResult, o as getAuthPausedConversationTurnId, s as getEventBatchDelayMs, t as createChildConversationWorker, u as sourceFromTurnInput } from "./result-BrlvfyIj.js";
|
|
26
|
+
import { n as getTurnLifecycle, t as ConversationTurnLifecycleService } from "./turn-lifecycle-CF2N7ud5.js";
|
|
27
|
+
import { o as AgentRunError, s as executeTurn } from "./work-BM_L0Pv9.js";
|
|
28
|
+
import { a as persistThreadStateById, i as persistThreadRuntimeState, n as getPersistedSandboxState, o as coerceThreadConversationState, r as getPersistedThreadState, t as getLocationConfigurationService } from "./thread-state-BDaMl9yd.js";
|
|
29
|
+
import { c as deleteWebAuthorization, d as createPausedTurns, f as getPausedTurnRequest, h as getTurnAuthorization, l as getWebAuthorization, m as wakePausedTurn, s as createWebAuthorization } from "./connections-DjY72_uF.js";
|
|
30
|
+
import { t as bindMessageAgent } from "./message-BjN5sKad.js";
|
|
31
|
+
import { t as bindSpawnAgent } from "./spawn-e7rQs14T.js";
|
|
32
|
+
import { n as scheduleSessionCompletedPluginTasks, t as processPluginTask } from "./task-runner-CwegN45x.js";
|
|
33
|
+
import { a as persistAuthPauseTurnState, c as getTurnUserSlackMessageTs, i as completeAuthPauseTurn, l as buildDeliveredTurnStatePatch, n as getAgentTurnDiagnosticsAttributes, o as getTurnUserMessage, r as requireTurnFailureEventId, s as getTurnUserReplyAttachmentContext, t as finalizeFailedTurnReplyWithEvent, u as loadPendingMessageCards } from "./turn-failure-response-CV06tN_R.js";
|
|
34
34
|
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
|
|
35
35
|
import * as z from "zod";
|
|
36
36
|
import { and, asc, desc, eq, gt, inArray, isNotNull, isNull, lte, max, ne, or, sql } from "drizzle-orm";
|
|
@@ -484,17 +484,33 @@ function throwApiError(status, message, cause) {
|
|
|
484
484
|
});
|
|
485
485
|
}
|
|
486
486
|
// src/api/conversations/user-message-activity.ts
|
|
487
|
+
/**
|
|
488
|
+
* The newest event of one type in the outer Conversation that matches the
|
|
489
|
+
* filter. It walks the message role or user message time index from the
|
|
490
|
+
* newest event. The user message index has only matching entries, so that
|
|
491
|
+
* read stops at the first one.
|
|
492
|
+
*/
|
|
493
|
+
function latestEventAt(db, type, filter) {
|
|
494
|
+
return db.select({ createdAt: juniorConversationEvents.createdAt }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, juniorConversations.conversationId), eq(juniorConversationEvents.type, type), filter)).orderBy(desc(juniorConversationEvents.createdAt), desc(juniorConversationEvents.seq)).limit(1).as(`latest_${type}`);
|
|
495
|
+
}
|
|
487
496
|
/** Read the latest true user message time for each selected conversation. */
|
|
488
497
|
async function readLastUserMessageAtByConversation(db, conversationIds) {
|
|
489
498
|
if (conversationIds.length === 0) return /* @__PURE__ */ new Map();
|
|
490
|
-
const
|
|
491
|
-
const
|
|
492
|
-
const
|
|
499
|
+
const payload = juniorConversationEvents.payload;
|
|
500
|
+
const instruction = latestEventAt(db, "user_message", isUserInstruction(payload));
|
|
501
|
+
const authorKind = sql`(${db.select({ kind: juniorIdentities.kind }).from(juniorIdentities).where(eq(juniorIdentities.id, juniorConversationEvents.actorIdentityId))})`;
|
|
502
|
+
const message = latestEventAt(db, "message", sql`${payload}->>'role' = 'user' and ${authorKind} = 'user'`);
|
|
493
503
|
const rows = await db.select({
|
|
494
|
-
conversationId:
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
504
|
+
conversationId: juniorConversations.conversationId,
|
|
505
|
+
instructionAt: instruction.createdAt,
|
|
506
|
+
messageAt: message.createdAt
|
|
507
|
+
}).from(juniorConversations).leftJoinLateral(instruction, sql`true`).leftJoinLateral(message, sql`true`).where(inArray(juniorConversations.conversationId, conversationIds));
|
|
508
|
+
const result = /* @__PURE__ */ new Map();
|
|
509
|
+
for (const { conversationId, instructionAt, messageAt } of rows) {
|
|
510
|
+
const times = [instructionAt, messageAt].flatMap((at) => at ? [at.getTime()] : []);
|
|
511
|
+
if (times.length > 0) result.set(conversationId, new Date(Math.max(...times)).toISOString());
|
|
512
|
+
}
|
|
513
|
+
return result;
|
|
498
514
|
}
|
|
499
515
|
// src/api/conversations/auto-archive.ts
|
|
500
516
|
const HOUR_MS = 36e5;
|
|
@@ -655,9 +671,8 @@ async function archiveViewerDoneConversations(viewer) {
|
|
|
655
671
|
});
|
|
656
672
|
return { archived };
|
|
657
673
|
}
|
|
658
|
-
/** Read the viewer's effective auto-archive choice for a conversation. */
|
|
659
|
-
async function readConversationAutoArchive(viewer,
|
|
660
|
-
const rootConversationId = await resolveRootConversationId(getSqlExecutor(), conversationId);
|
|
674
|
+
/** Read the viewer's effective auto-archive choice for a conversation root. */
|
|
675
|
+
async function readConversationAutoArchive(viewer, rootConversationId) {
|
|
661
676
|
const [user] = await getDb().select({
|
|
662
677
|
autoArchive: juniorConversationParticipants.autoArchive,
|
|
663
678
|
autoArchiveDefault: juniorUsers.autoArchiveDefault
|
|
@@ -7879,6 +7894,40 @@ function hasUnfinishedToolCalls(messages) {
|
|
|
7879
7894
|
} else if (message.role === "toolResult") pending.delete(message.toolCallId);
|
|
7880
7895
|
return pending.size > 0;
|
|
7881
7896
|
}
|
|
7897
|
+
// src/chat/conversations/sql/event-watermarks.ts
|
|
7898
|
+
/**
|
|
7899
|
+
* Read the event watermark of each selected Conversation and each of its
|
|
7900
|
+
* child agents at any depth. Two primary key lookups per Conversation.
|
|
7901
|
+
*/
|
|
7902
|
+
async function readSubtreeEventWatermarks(db, conversationIds) {
|
|
7903
|
+
const conversation = juniorConversations.conversationId;
|
|
7904
|
+
return await db.select({
|
|
7905
|
+
scopeConversationId: conversationSubtreeColumns.scopeConversationId,
|
|
7906
|
+
conversationId: conversation,
|
|
7907
|
+
seq: sql`(
|
|
7908
|
+
select max(watermark.seq) from junior_conversation_events watermark
|
|
7909
|
+
where watermark.conversation_id = ${conversation}
|
|
7910
|
+
)`,
|
|
7911
|
+
originMs: sql`(
|
|
7912
|
+
select (extract(epoch from origin.created_at) * 1000)::double precision
|
|
7913
|
+
from junior_conversation_events origin
|
|
7914
|
+
where origin.conversation_id = ${conversation}
|
|
7915
|
+
order by origin.seq
|
|
7916
|
+
limit 1
|
|
7917
|
+
)`
|
|
7918
|
+
}).from(juniorConversations).innerJoin(conversationSubtree(conversationIds), eq(conversationSubtreeColumns.conversationId, conversation));
|
|
7919
|
+
}
|
|
7920
|
+
/**
|
|
7921
|
+
* Arguments for `innerJoin` that keep only the events inside the seq range of
|
|
7922
|
+
* their Conversation. The range is in the index condition, so a read touches
|
|
7923
|
+
* only the new events.
|
|
7924
|
+
*/
|
|
7925
|
+
function seqRangeJoin(ranges) {
|
|
7926
|
+
const rows = sql.join(ranges.map((range) => sql`(${range.conversationId}::text, ${range.fromSeq}::integer, ${range.toSeq}::integer)`), sql`, `);
|
|
7927
|
+
return [sql`(values ${rows}) as seq_range(conversation_id, from_seq, to_seq)`, sql`seq_range.conversation_id = ${juniorConversationEvents.conversationId}
|
|
7928
|
+
and ${juniorConversationEvents.seq} > seq_range.from_seq
|
|
7929
|
+
and ${juniorConversationEvents.seq} <= seq_range.to_seq`];
|
|
7930
|
+
}
|
|
7882
7931
|
// src/chat/pi/sql-model-usage.ts
|
|
7883
7932
|
/** SQL reporting adapter for usage stored on assistant history events. */
|
|
7884
7933
|
const assistantCall = sql`jsonb_to_record(${juniorConversationEvents.payload})
|
|
@@ -7977,7 +8026,6 @@ async function sumModelUsage(executor, ranges) {
|
|
|
7977
8026
|
const outputTokens = token("output", "outputTokens");
|
|
7978
8027
|
const cachedInputTokens = token("cacheRead", "cachedInputTokens");
|
|
7979
8028
|
const cacheCreationTokens = token("cacheWrite", "cacheCreationTokens");
|
|
7980
|
-
const rangeRows = sql.join(ranges.map((range) => sql`(${range.conversationId}::text, ${range.fromSeq}::integer, ${range.toSeq}::integer)`), sql`, `);
|
|
7981
8029
|
return await executor.db().select({
|
|
7982
8030
|
modelId,
|
|
7983
8031
|
inputTokens: summed(inputTokens),
|
|
@@ -7996,31 +8044,7 @@ async function sumModelUsage(executor, ranges) {
|
|
|
7996
8044
|
costCacheRead: summedCost(nonnegativeNumber(cost, "cacheRead")),
|
|
7997
8045
|
costCacheWrite: summedCost(nonnegativeNumber(cost, "cacheWrite")),
|
|
7998
8046
|
costTotal: summedCost(nonnegativeNumber(cost, "total"))
|
|
7999
|
-
}).from(juniorConversationEvents).innerJoin(sql`(
|
|
8000
|
-
and ${juniorConversationEvents.seq} > seq_range.from_seq
|
|
8001
|
-
and ${juniorConversationEvents.seq} <= seq_range.to_seq`).crossJoinLateral(assistantCall).where(and(eq(juniorConversationEvents.type, "assistant_message"), notCopiedByFork(), notInheritedByForkChild(), sql`jsonb_typeof(${provider}) = 'string'`, sql`jsonb_typeof(${model}) = 'string'`, sql`coalesce(${provider} #>> '{}', '') <> ''`, sql`coalesce(${modelText}, '') <> ''`)).groupBy(modelId);
|
|
8002
|
-
}
|
|
8003
|
-
/**
|
|
8004
|
-
* The last event seq of each Conversation in a subtree, and the creation time
|
|
8005
|
-
* of its first event. A purged Conversation can get new events under the same
|
|
8006
|
-
* id, with seq starting again at 0; the first event time tells them apart.
|
|
8007
|
-
*/
|
|
8008
|
-
async function readEventWatermarks(executor, conversationId) {
|
|
8009
|
-
const conversation = juniorConversations.conversationId;
|
|
8010
|
-
return await executor.db().select({
|
|
8011
|
-
conversationId: conversation,
|
|
8012
|
-
seq: sql`(
|
|
8013
|
-
select max(watermark.seq) from junior_conversation_events watermark
|
|
8014
|
-
where watermark.conversation_id = ${conversation}
|
|
8015
|
-
)`,
|
|
8016
|
-
originMs: sql`(
|
|
8017
|
-
select (extract(epoch from origin.created_at) * 1000)::double precision
|
|
8018
|
-
from junior_conversation_events origin
|
|
8019
|
-
where origin.conversation_id = ${conversation}
|
|
8020
|
-
order by origin.seq
|
|
8021
|
-
limit 1
|
|
8022
|
-
)`
|
|
8023
|
-
}).from(juniorConversations).innerJoin(conversationSubtree([conversationId]), eq(conversationSubtreeColumns.conversationId, conversation));
|
|
8047
|
+
}).from(juniorConversationEvents).innerJoin(...seqRangeJoin(ranges)).crossJoinLateral(assistantCall).where(and(eq(juniorConversationEvents.type, "assistant_message"), notCopiedByFork(), notInheritedByForkChild(), sql`jsonb_typeof(${provider}) = 'string'`, sql`jsonb_typeof(${model}) = 'string'`, sql`coalesce(${provider} #>> '{}', '') <> ''`, sql`coalesce(${modelText}, '') <> ''`)).groupBy(modelId);
|
|
8024
8048
|
}
|
|
8025
8049
|
const modelUsageCacheSchema = z.object({
|
|
8026
8050
|
conversations: z.record(z.string(), z.object({
|
|
@@ -8068,7 +8092,7 @@ function mergeSums(left, right) {
|
|
|
8068
8092
|
async function readConversationModelUsageFromSql(executor, options) {
|
|
8069
8093
|
const state = getStateAdapter();
|
|
8070
8094
|
const key = modelUsageCacheKey(options.conversationId);
|
|
8071
|
-
const [stored, watermarks] = await Promise.all([state.get(key),
|
|
8095
|
+
const [stored, watermarks] = await Promise.all([state.get(key), readSubtreeEventWatermarks(executor.db(), [options.conversationId])]);
|
|
8072
8096
|
const cached = modelUsageCacheSchema.safeParse(stored).data;
|
|
8073
8097
|
const purged = watermarks.some(({ conversationId, seq, originMs }) => {
|
|
8074
8098
|
const seen = cached?.conversations[conversationId];
|
|
@@ -8462,14 +8486,43 @@ function eventCost() {
|
|
|
8462
8486
|
function addCostUsd(left, right) {
|
|
8463
8487
|
return Math.round((left + right) * 0xe8d4a51000) / 0xe8d4a51000;
|
|
8464
8488
|
}
|
|
8465
|
-
|
|
8466
|
-
|
|
8467
|
-
|
|
8468
|
-
*/
|
|
8469
|
-
|
|
8470
|
-
|
|
8471
|
-
|
|
8472
|
-
|
|
8489
|
+
function compareText(left, right) {
|
|
8490
|
+
return left < right ? -1 : left > right ? 1 : 0;
|
|
8491
|
+
}
|
|
8492
|
+
/** Cost sums of one operation. Sums of two seq ranges add field by field. */
|
|
8493
|
+
const operationSumsSchema = z.object({
|
|
8494
|
+
costUsd: z.number(),
|
|
8495
|
+
events: z.number().int(),
|
|
8496
|
+
name: z.string(),
|
|
8497
|
+
namespace: z.string()
|
|
8498
|
+
});
|
|
8499
|
+
const auxiliaryCostCacheSchema = z.object({
|
|
8500
|
+
seq: z.number().int(),
|
|
8501
|
+
originMs: z.number(),
|
|
8502
|
+
operations: z.array(operationSumsSchema)
|
|
8503
|
+
});
|
|
8504
|
+
const AUXILIARY_COST_CACHE_TTL_MS = 2592e6;
|
|
8505
|
+
function auxiliaryCostCacheKey(conversationId) {
|
|
8506
|
+
return `conversation-auxiliary-costs:${conversationId}`;
|
|
8507
|
+
}
|
|
8508
|
+
function operationKey(operation) {
|
|
8509
|
+
return `${operation.namespace}\u0000${operation.name}`;
|
|
8510
|
+
}
|
|
8511
|
+
function mergeOperations(operations) {
|
|
8512
|
+
const merged = /* @__PURE__ */ new Map();
|
|
8513
|
+
for (const operation of operations) {
|
|
8514
|
+
const key = operationKey(operation);
|
|
8515
|
+
const current = merged.get(key);
|
|
8516
|
+
merged.set(key, current ? {
|
|
8517
|
+
...current,
|
|
8518
|
+
costUsd: addCostUsd(current.costUsd, operation.costUsd),
|
|
8519
|
+
events: current.events + operation.events
|
|
8520
|
+
} : operation);
|
|
8521
|
+
}
|
|
8522
|
+
return merged;
|
|
8523
|
+
}
|
|
8524
|
+
/** Sum additive event costs by operation, in the seq range of each Conversation. */
|
|
8525
|
+
async function sumOperationCosts(db, ranges) {
|
|
8473
8526
|
const namespace = sql`CASE
|
|
8474
8527
|
WHEN ${juniorConversationEvents.type} = 'structured_event'
|
|
8475
8528
|
THEN ${juniorConversationEvents.payload}->>'namespace'
|
|
@@ -8481,29 +8534,91 @@ async function readConversationAuxiliaryCostsFromSql(db, conversationIds) {
|
|
|
8481
8534
|
ELSE ${juniorConversationEvents.type}
|
|
8482
8535
|
END`;
|
|
8483
8536
|
const cost = eventCost();
|
|
8484
|
-
|
|
8485
|
-
conversationId:
|
|
8486
|
-
childAgentCostUsd: sql`coalesce(round(sum(case when ${isChildAgent} then ${cost} end), 12), 0)::double precision`.mapWith(Number),
|
|
8537
|
+
return await db.select({
|
|
8538
|
+
conversationId: juniorConversationEvents.conversationId,
|
|
8487
8539
|
costUsd: sql`round(sum(${cost}), 12)::double precision`.mapWith(Number),
|
|
8488
8540
|
events: sql`count(*)::integer`.mapWith(Number),
|
|
8489
8541
|
name,
|
|
8490
8542
|
namespace
|
|
8491
|
-
}).from(juniorConversationEvents).innerJoin(
|
|
8543
|
+
}).from(juniorConversationEvents).innerJoin(...seqRangeJoin(ranges)).where(and(inArray(juniorConversationEvents.type, [
|
|
8544
|
+
"structured_event",
|
|
8545
|
+
"guardian_action_reviewed",
|
|
8546
|
+
"turn_routed"
|
|
8547
|
+
]), sql`${cost} >= 0`, notCopiedByFork())).groupBy(juniorConversationEvents.conversationId, namespace, name);
|
|
8548
|
+
}
|
|
8549
|
+
/**
|
|
8550
|
+
* Read the cost operations of each Conversation, from its cache entry plus
|
|
8551
|
+
* the events after the cached seq. The entry is correct for the same reasons
|
|
8552
|
+
* as the model usage cache in `readConversationModelUsageFromSql`: events
|
|
8553
|
+
* are append-only and appends commit in seq order, and a fork commits its
|
|
8554
|
+
* copied events and its fork note in one transaction.
|
|
8555
|
+
*/
|
|
8556
|
+
async function readOperationsByConversation(db, watermarks) {
|
|
8557
|
+
const latest = /* @__PURE__ */ new Map();
|
|
8558
|
+
for (const { conversationId, seq, originMs } of watermarks) if (seq !== null && originMs !== null) latest.set(conversationId, {
|
|
8559
|
+
seq,
|
|
8560
|
+
originMs
|
|
8561
|
+
});
|
|
8562
|
+
const state = getStateAdapter();
|
|
8563
|
+
const entries = await Promise.all([...latest].map(async ([conversationId, watermark]) => {
|
|
8564
|
+
const cached = auxiliaryCostCacheSchema.safeParse(await state.get(auxiliaryCostCacheKey(conversationId))).data;
|
|
8565
|
+
return {
|
|
8566
|
+
base: cached && cached.seq <= watermark.seq && cached.originMs === watermark.originMs ? cached : void 0,
|
|
8567
|
+
conversationId,
|
|
8568
|
+
watermark
|
|
8569
|
+
};
|
|
8570
|
+
}));
|
|
8571
|
+
const ranges = entries.flatMap(({ base, conversationId, watermark }) => watermark.seq > (base?.seq ?? -1) ? [{
|
|
8572
|
+
conversationId,
|
|
8573
|
+
fromSeq: base?.seq ?? -1,
|
|
8574
|
+
toSeq: watermark.seq
|
|
8575
|
+
}] : []);
|
|
8576
|
+
const deltas = ranges.length > 0 ? await sumOperationCosts(db, ranges) : [];
|
|
8492
8577
|
const result = /* @__PURE__ */ new Map();
|
|
8493
|
-
|
|
8494
|
-
|
|
8495
|
-
|
|
8496
|
-
|
|
8497
|
-
}
|
|
8498
|
-
|
|
8499
|
-
|
|
8500
|
-
|
|
8501
|
-
|
|
8502
|
-
|
|
8503
|
-
|
|
8504
|
-
|
|
8578
|
+
await Promise.all(entries.map(async ({ base, conversationId, watermark }) => {
|
|
8579
|
+
if (base && base.seq === watermark.seq) {
|
|
8580
|
+
result.set(conversationId, base.operations);
|
|
8581
|
+
return;
|
|
8582
|
+
}
|
|
8583
|
+
const operations = [...mergeOperations([...base?.operations ?? [], ...deltas.flatMap(({ conversationId: deltaId, ...operation }) => deltaId === conversationId ? [operation] : [])]).values()];
|
|
8584
|
+
result.set(conversationId, operations);
|
|
8585
|
+
await state.set(auxiliaryCostCacheKey(conversationId), {
|
|
8586
|
+
...watermark,
|
|
8587
|
+
operations
|
|
8588
|
+
}, AUXILIARY_COST_CACHE_TTL_MS);
|
|
8589
|
+
}));
|
|
8590
|
+
return result;
|
|
8591
|
+
}
|
|
8592
|
+
/**
|
|
8593
|
+
* Aggregate additive event costs by namespaced operation. The total for each
|
|
8594
|
+
* selected Conversation includes itself and all its child agents at any depth.
|
|
8595
|
+
*/
|
|
8596
|
+
async function readConversationAuxiliaryCostsFromSql(db, conversationIds) {
|
|
8597
|
+
if (conversationIds.length === 0) return /* @__PURE__ */ new Map();
|
|
8598
|
+
const watermarks = await readSubtreeEventWatermarks(db, conversationIds);
|
|
8599
|
+
const operationsByConversation = await readOperationsByConversation(db, watermarks);
|
|
8600
|
+
const membersByScope = /* @__PURE__ */ new Map();
|
|
8601
|
+
for (const { scopeConversationId, conversationId } of watermarks) {
|
|
8602
|
+
const members = membersByScope.get(scopeConversationId) ?? [];
|
|
8603
|
+
members.push(conversationId);
|
|
8604
|
+
membersByScope.set(scopeConversationId, members);
|
|
8605
|
+
}
|
|
8606
|
+
const result = /* @__PURE__ */ new Map();
|
|
8607
|
+
for (const [scopeConversationId, members] of membersByScope) {
|
|
8608
|
+
let childAgentCostUsd = 0;
|
|
8609
|
+
for (const member of members) {
|
|
8610
|
+
if (member === scopeConversationId) continue;
|
|
8611
|
+
for (const operation of operationsByConversation.get(member) ?? []) childAgentCostUsd = addCostUsd(childAgentCostUsd, operation.costUsd);
|
|
8612
|
+
}
|
|
8613
|
+
const operations = [...mergeOperations(members.flatMap((member) => operationsByConversation.get(member) ?? [])).values()].sort((left, right) => compareText(left.namespace, right.namespace) || compareText(left.name, right.name));
|
|
8614
|
+
if (operations.length === 0) continue;
|
|
8615
|
+
result.set(scopeConversationId, {
|
|
8616
|
+
total: {
|
|
8617
|
+
costUsd: operations.reduce((total, operation) => addCostUsd(total, operation.costUsd), 0),
|
|
8618
|
+
operations
|
|
8619
|
+
},
|
|
8620
|
+
...childAgentCostUsd > 0 ? { childAgentCostUsd } : void 0
|
|
8505
8621
|
});
|
|
8506
|
-
result.set(row.conversationId, current);
|
|
8507
8622
|
}
|
|
8508
8623
|
return result;
|
|
8509
8624
|
}
|
|
@@ -8534,23 +8649,44 @@ function isConversationPriority(conversation, nowMs) {
|
|
|
8534
8649
|
return nowMs - lastSeenAt <= UNASSIGNED_PRIORITY_WINDOW_MS;
|
|
8535
8650
|
}
|
|
8536
8651
|
// src/api/conversations/activity-preview.ts
|
|
8652
|
+
/**
|
|
8653
|
+
* The latest non-empty message with one role in the outer Conversation. It
|
|
8654
|
+
* walks `junior_conversation_events_message_role_idx` from the newest
|
|
8655
|
+
* message and stops at the first match.
|
|
8656
|
+
*/
|
|
8657
|
+
function latestMessage(db, role) {
|
|
8658
|
+
const text = sql`${juniorConversationEvents.payload}->>'text'`;
|
|
8659
|
+
return db.select({
|
|
8660
|
+
createdAt: juniorConversationEvents.createdAt,
|
|
8661
|
+
text: text.as(`${role}_text`)
|
|
8662
|
+
}).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, juniorConversations.conversationId), eq(juniorConversationEvents.type, "message"), sql`${juniorConversationEvents.payload}->>'role' = ${role}`, isNotNull(sql`nullif(btrim(${text}), '')`))).orderBy(desc(juniorConversationEvents.createdAt), desc(juniorConversationEvents.seq)).limit(1).as(`latest_${role}`);
|
|
8663
|
+
}
|
|
8537
8664
|
/** Read one recent assistant message, or the latest user message, for each conversation. */
|
|
8538
8665
|
async function readConversationActivityPreviews(db, conversationIds) {
|
|
8539
8666
|
if (conversationIds.length === 0) return /* @__PURE__ */ new Map();
|
|
8540
|
-
const
|
|
8541
|
-
const
|
|
8542
|
-
const
|
|
8543
|
-
|
|
8544
|
-
|
|
8545
|
-
|
|
8546
|
-
|
|
8547
|
-
|
|
8548
|
-
}).from(
|
|
8549
|
-
|
|
8550
|
-
|
|
8551
|
-
|
|
8552
|
-
|
|
8553
|
-
|
|
8667
|
+
const assistant = latestMessage(db, "assistant");
|
|
8668
|
+
const user = latestMessage(db, "user");
|
|
8669
|
+
const rows = await db.select({
|
|
8670
|
+
conversationId: juniorConversations.conversationId,
|
|
8671
|
+
assistantAt: assistant.createdAt,
|
|
8672
|
+
assistantText: assistant.text,
|
|
8673
|
+
userAt: user.createdAt,
|
|
8674
|
+
userText: user.text
|
|
8675
|
+
}).from(juniorConversations).leftJoinLateral(assistant, sql`true`).leftJoinLateral(user, sql`true`).where(inArray(juniorConversations.conversationId, conversationIds));
|
|
8676
|
+
const previews = /* @__PURE__ */ new Map();
|
|
8677
|
+
for (const row of rows) {
|
|
8678
|
+
const preview = row.assistantAt && row.assistantText !== null ? {
|
|
8679
|
+
createdAt: row.assistantAt.toISOString(),
|
|
8680
|
+
role: "assistant",
|
|
8681
|
+
text: row.assistantText
|
|
8682
|
+
} : row.userAt && row.userText !== null ? {
|
|
8683
|
+
createdAt: row.userAt.toISOString(),
|
|
8684
|
+
role: "user",
|
|
8685
|
+
text: row.userText
|
|
8686
|
+
} : void 0;
|
|
8687
|
+
if (preview) previews.set(row.conversationId, preview);
|
|
8688
|
+
}
|
|
8689
|
+
return previews;
|
|
8554
8690
|
}
|
|
8555
8691
|
// src/api/conversations/participants.ts
|
|
8556
8692
|
const identityColumns = {
|
|
@@ -8974,7 +9110,7 @@ async function readParentConversationId(conversationId) {
|
|
|
8974
9110
|
* Conversation has its own access check, so a viewer sees a label only where
|
|
8975
9111
|
* they can see private content.
|
|
8976
9112
|
*/
|
|
8977
|
-
async function readConversationAgentTree(conversationId,
|
|
9113
|
+
async function readConversationAgentTree(conversationId, readAccess) {
|
|
8978
9114
|
const ids = [conversationId];
|
|
8979
9115
|
let parentId = await readParentConversationId(conversationId);
|
|
8980
9116
|
while (parentId && !ids.includes(parentId) && ids.length < MAX_AGENT_TREE_DEPTH) {
|
|
@@ -8984,7 +9120,7 @@ async function readConversationAgentTree(conversationId, viewer) {
|
|
|
8984
9120
|
if (ids.length < 2) return;
|
|
8985
9121
|
const root = parentId ? void 0 : await getConversationStore().get({ conversationId: ids[0] });
|
|
8986
9122
|
const [access, automationTitleByConversation, firstHumanMessageTextByConversation] = await Promise.all([
|
|
8987
|
-
|
|
9123
|
+
readAccess(ids),
|
|
8988
9124
|
readAutomationTitlesByConversationId(root ? [root] : []),
|
|
8989
9125
|
readFirstHumanMessageTexts(getDb(), root ? [root] : [])
|
|
8990
9126
|
]);
|
|
@@ -9036,7 +9172,7 @@ async function keepQuickQuestionForViewer(viewer, conversationId) {
|
|
|
9036
9172
|
* Read fork state for the viewer: whether they can fork, and the source and
|
|
9037
9173
|
* fork links that they can open.
|
|
9038
9174
|
*/
|
|
9039
|
-
async function readConversationForks(conversationId,
|
|
9175
|
+
async function readConversationForks(conversationId, readAccess) {
|
|
9040
9176
|
const db = getDb();
|
|
9041
9177
|
const [row] = await db.select({
|
|
9042
9178
|
forkedFrom: juniorConversations.forkedFromConversationId,
|
|
@@ -9045,11 +9181,11 @@ async function readConversationForks(conversationId, viewer) {
|
|
|
9045
9181
|
const forks = await db.select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(eq(juniorConversations.forkedFromConversationId, conversationId), isNull(juniorConversations.quickQuestionAt))).orderBy(asc(juniorConversations.createdAt)).limit(50);
|
|
9046
9182
|
const forkedFrom = row?.forkedFrom ?? void 0;
|
|
9047
9183
|
const ids = forks.map((fork) => fork.conversationId);
|
|
9048
|
-
const access = await
|
|
9184
|
+
const access = await readAccess([
|
|
9049
9185
|
conversationId,
|
|
9050
9186
|
...ids,
|
|
9051
9187
|
...forkedFrom ? [forkedFrom] : []
|
|
9052
|
-
]
|
|
9188
|
+
]);
|
|
9053
9189
|
const canOpen = (id) => access.get(id)?.canViewPrivateContent;
|
|
9054
9190
|
if (!canOpen(conversationId)) return {
|
|
9055
9191
|
canFork: false,
|
|
@@ -9124,30 +9260,40 @@ async function readSubtreeDetailVersion(conversationId) {
|
|
|
9124
9260
|
version: "0"
|
|
9125
9261
|
};
|
|
9126
9262
|
}
|
|
9263
|
+
/** Read the viewer's marks and auto-archive choice, which live on the root. */
|
|
9264
|
+
async function readViewerRootState(viewer, conversationId) {
|
|
9265
|
+
const rootConversationId = await resolveRootConversationId(getSqlExecutor(), conversationId);
|
|
9266
|
+
const [viewerMarks, autoArchive] = await Promise.all([readConversationViewerMarks(viewer, rootConversationId), readConversationAutoArchive(viewer, rootConversationId)]);
|
|
9267
|
+
return {
|
|
9268
|
+
autoArchive,
|
|
9269
|
+
viewerMarks
|
|
9270
|
+
};
|
|
9271
|
+
}
|
|
9127
9272
|
/** Read the detail state that the ETag hashes and the report shows. */
|
|
9128
9273
|
async function readConversationDetailState(conversationId, viewer) {
|
|
9129
|
-
const
|
|
9130
|
-
|
|
9131
|
-
|
|
9132
|
-
|
|
9133
|
-
|
|
9274
|
+
const readAccess = createConversationAccessReader(getDb(), viewer);
|
|
9275
|
+
const [accessById, viewerRootState, forks, agentTree, readPosition, attachmentsVersion] = await Promise.all([
|
|
9276
|
+
readAccess([conversationId]),
|
|
9277
|
+
viewer ? readViewerRootState(viewer, conversationId) : void 0,
|
|
9278
|
+
readConversationForks(conversationId, readAccess),
|
|
9279
|
+
readConversationAgentTree(conversationId, readAccess),
|
|
9134
9280
|
viewer ? readConversationReadPosition(viewer, conversationId) : void 0,
|
|
9135
|
-
viewer ? readConversationAutoArchive(viewer, conversationId) : void 0,
|
|
9136
9281
|
readSlackAttachmentsVersion(getSqlExecutor(), conversationId)
|
|
9137
9282
|
]);
|
|
9138
9283
|
const access = accessById.get(conversationId);
|
|
9284
|
+
const transcriptVersion = createHash("sha256").update(JSON.stringify({
|
|
9285
|
+
attachments: attachmentsVersion,
|
|
9286
|
+
canViewPrivateContent: access?.canViewPrivateContent ?? false,
|
|
9287
|
+
junior: JUNIOR_VERSION
|
|
9288
|
+
})).digest("base64url");
|
|
9139
9289
|
return {
|
|
9140
9290
|
access,
|
|
9141
9291
|
agentTree,
|
|
9142
|
-
autoArchive,
|
|
9292
|
+
autoArchive: viewerRootState?.autoArchive,
|
|
9143
9293
|
forks,
|
|
9144
9294
|
readPosition,
|
|
9145
|
-
transcriptVersion
|
|
9146
|
-
|
|
9147
|
-
canViewPrivateContent: access?.canViewPrivateContent ?? false,
|
|
9148
|
-
junior: JUNIOR_VERSION
|
|
9149
|
-
})).digest("base64url"),
|
|
9150
|
-
viewerMarks
|
|
9295
|
+
transcriptVersion,
|
|
9296
|
+
viewerMarks: viewerRootState?.viewerMarks
|
|
9151
9297
|
};
|
|
9152
9298
|
}
|
|
9153
9299
|
/**
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { g as TURN_REASONING_LEVELS } from "./config-
|
|
2
|
-
import { C as getSqlExecutor, x as getConversationStore } from "./viewer-
|
|
3
|
-
import { h as juniorAgentInvocations, m as juniorAgentBindings } from "./executor-
|
|
4
|
-
import { p as credentialContextSchema } from "./registry-
|
|
1
|
+
import { g as TURN_REASONING_LEVELS } from "./config-DBdBimZ9.js";
|
|
2
|
+
import { C as getSqlExecutor, x as getConversationStore } from "./viewer-C2PztlYX.js";
|
|
3
|
+
import { h as juniorAgentInvocations, m as juniorAgentBindings } from "./executor-CGqJCxgR.js";
|
|
4
|
+
import { p as credentialContextSchema } from "./registry-DpjG3yS-.js";
|
|
5
5
|
import { S as AGENT_INVOCATION_PARENT_MAILBOX_STATUSES, x as AGENT_INVOCATION_MAILBOX_STATUSES } from "./reporting-window-B-QP9zX1.js";
|
|
6
6
|
import { createHash } from "node:crypto";
|
|
7
7
|
import * as z from "zod";
|