@sentry/junior 0.281.0 → 0.283.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-D8-lqOBF.js} +1 -1
- package/dist/{admin-DQpHx6Og.js → admin-Dnw5SCXp.js} +1 -1
- package/dist/{agent-runner-B229gXUY.js → agent-runner-Bj7GhysW.js} +52 -29
- package/dist/api/schema.d.ts +2 -2
- package/dist/api/schema.js +6 -6
- package/dist/api.d.ts +1 -1
- package/dist/api.js +94 -59
- package/dist/{app-BQ9RZS43.d.ts → app-CMBP-N43.d.ts} +2 -2
- package/dist/app.d.ts +1 -1
- package/dist/app.js +30 -30
- package/dist/{assistant-reply-DQbtwc6j.js → assistant-reply-CdYsLbXL.js} +1 -1
- package/dist/{automation-sIsmIXH7.js → automation-MLWOrghe.js} +1 -1
- package/dist/{background-compaction-queue-oegyrxSe.js → background-compaction-queue-Bbsqx8Vm.js} +2 -2
- package/dist/{briefs-BwzGWJgR.js → briefs-C4qBY-jb.js} +4 -4
- package/dist/{catalog-runtime-ClKzLvbN.js → catalog-runtime-B7NRB7eH.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-a3Ib6wxr.js} +2 -2
- package/dist/{config-3AZ11aSM.js → config-DFVlYCeY.js} +97 -4
- package/dist/{connections-C0ut_6RW.js → connections-BtnvpBEV.js} +10 -10
- package/dist/{conversation-DNtcULyX.js → conversation-DdT7SNar.js} +3 -1
- package/dist/{conversation-pending-messages-LlFnr9-m.js → conversation-pending-messages-Dct5pheX.js} +1 -1
- package/dist/{conversation-privacy-DAgeBGLN.js → conversation-privacy-DLq-abjU.js} +1 -1
- package/dist/{credential-sync-Bg8NPuvj.js → credential-sync-B4XFVcjM.js} +13 -13
- package/dist/{db-BCFM0CUX.d.ts → db-A_WrTY-s.d.ts} +2 -1
- package/dist/{executor-DLKnzP6S.js → executor-HPgHGAWK.js} +20 -3
- package/dist/instrumentation.js +2 -2
- package/dist/{logging-DHzrobea.js → logging-2BXvW7Mp.js} +1 -1
- package/dist/{media-Dq9_svfQ.js → media-Bu9C6lz0.js} +3 -1
- package/dist/{message-LR8z5jXJ.js → message-BG1v1lXX.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-CXNZJymo.js} +2 -2
- package/dist/{projection-Bhz1tp0G.js → projection-BfKkpOGQ.js} +42 -18
- package/dist/{prompt-DI6KCtwb.js → prompt-CCtaGgbI.js} +1 -1
- package/dist/{registry-EjhulgQW.js → registry-CLooHPAz.js} +1 -1
- package/dist/{resolve-Cw6OW4Fj.js → resolve-D3MK9oRJ.js} +3 -3
- package/dist/{result-BoD0jevy.js → result-BPCjUefO.js} +9 -9
- package/dist/{runner-D22bsBDS.js → runner-Ds31u3rB.js} +11 -11
- package/dist/{sandbox-egress-signals-BG5GYacQ.js → sandbox-egress-signals-CLd5RPUw.js} +1 -1
- package/dist/{schema-BN34Jy-U.js → schema-CHNP0GfH.js} +11 -4
- package/dist/{schema-CsqJzkP5.d.ts → schema-jW3ccLjp.d.ts} +22 -1
- package/dist/{service-account-xo-CeMqI.js → service-account-CWpTsoIM.js} +3 -3
- package/dist/{service-account-Dd1nnAQZ.js → service-account-D6AMahy7.js} +3 -3
- package/dist/{session-stop-CHSYB2uw.js → session-stop-D8LGC3H6.js} +12 -12
- package/dist/{skills-BGJr6xtW.js → skills-DuOKByQH.js} +2 -2
- package/dist/{spawn-Cl8WS7zi.js → spawn-CNIQGgAS.js} +2 -2
- package/dist/{stop-C9lHWpvl.js → stop-DX2oOIgl.js} +291 -204
- package/dist/{store-DeTnwVJt.js → store-61mD4ZSh.js} +4 -4
- package/dist/{store-C4z8gOgZ.js → store-DAJntSEv.js} +3 -3
- package/dist/{task-queue-BBos68l0.js → task-queue-BE70Pb9p.js} +3 -3
- package/dist/{task-runner-BSF9zO-H.js → task-runner-CmmfddSZ.js} +7 -7
- package/dist/{thread-state-DGq1o5JX.js → thread-state-0UfRMWYd.js} +4 -4
- package/dist/{turn-failure-response--9bA4uLP.js → turn-failure-response-DKdzxJHE.js} +7 -7
- package/dist/{turn-lifecycle-t5fimxwQ.js → turn-lifecycle-24sBZ4Ip.js} +1 -1
- package/dist/{turn-session-routing-RBtUe-3y.js → turn-session-routing-CzCnNAUO.js} +9 -9
- package/dist/{validation-DrR0leBT.js → validation-Cs_knhR8.js} +1 -1
- package/dist/{version-D_HFt_Dq.js → version-ZMC4cXWN.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{viewer-DWlpSFdj.js → viewer-CYB9T4rm.js} +19 -7
- package/dist/{work-pPoqtRea.js → work-J1n6RQkY.js} +11 -11
- package/dist/{worker-CoVKgJ-O.js → worker-s1fCvj1z.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/0081_conversation_pin_position.sql +1 -0
- package/migrations/meta/0080_snapshot.json +4265 -0
- package/migrations/meta/0081_snapshot.json +4271 -0
- package/migrations/meta/_journal.json +14 -0
- package/package.json +4 -4
|
@@ -1,42 +1,41 @@
|
|
|
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
|
|
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-BfKkpOGQ.js";
|
|
3
|
+
import { a as completeText, c as resolveGatewayModel, m as escapeXml, r as completeDecision, x as isProviderRetryError } from "./client-a3Ib6wxr.js";
|
|
4
|
+
import { c as getSlackClientSecret, i as getChatConfig, l as getSlackSigningSecret, n as botConfig, o as getSlackBotToken, s as getSlackClientId, v as normalizeSlackEmojiName } from "./config-DFVlYCeY.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-2BXvW7Mp.js";
|
|
6
|
+
import { t as JUNIOR_VERSION } from "./version-ZMC4cXWN.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
|
|
10
|
-
import {
|
|
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-
|
|
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-CYB9T4rm.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-HPgHGAWK.js";
|
|
10
|
+
import { _ as instructionProvenanceFor, h as contextProvenance, i as isVisionImageMediaType, r as detectImageMediaType } from "./media-Bu9C6lz0.js";
|
|
11
|
+
import { d as actorLogContext, f as credentialContextForActor } from "./registry-CLooHPAz.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-Bj7GhysW.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-
|
|
15
|
-
import { R as readMessageAttachments, c as conversationDetailReportSchema, p as conversationFeedSchema, u as conversationEventPageSchema } from "./conversation-
|
|
16
|
-
import { a as EVENT_SYSTEM_ACTOR, o as isEventConversationMessage } from "./prompt-
|
|
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-
|
|
14
|
+
import { r as getStateAdapter } from "./adapter-D8-lqOBF.js";
|
|
15
|
+
import { R as readMessageAttachments, c as conversationDetailReportSchema, p as conversationFeedSchema, u as conversationEventPageSchema } from "./conversation-DdT7SNar.js";
|
|
16
|
+
import { a as EVENT_SYSTEM_ACTOR, o as isEventConversationMessage } from "./prompt-CCtaGgbI.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-61mD4ZSh.js";
|
|
18
|
+
import { n as getAssistantReplyText, t as decideReply } from "./assistant-reply-CdYsLbXL.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-D8LGC3H6.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-
|
|
24
|
-
import { d as apiErrorSchema, f as healthReportSchema, s as conversationPendingMessagesReportSchema } from "./conversation-pending-messages-
|
|
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
|
|
21
|
+
import { g as getTurnRequestDeadline, l as getVercelConversationWorkQueue } from "./background-compaction-queue-Bbsqx8Vm.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-DAJntSEv.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-CzCnNAUO.js";
|
|
24
|
+
import { d as apiErrorSchema, f as healthReportSchema, s as conversationPendingMessagesReportSchema } from "./conversation-pending-messages-Dct5pheX.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-BPCjUefO.js";
|
|
26
|
+
import { n as getTurnLifecycle, t as ConversationTurnLifecycleService } from "./turn-lifecycle-24sBZ4Ip.js";
|
|
27
|
+
import { o as AgentRunError, s as executeTurn } from "./work-J1n6RQkY.js";
|
|
28
|
+
import { a as persistThreadStateById, i as persistThreadRuntimeState, n as getPersistedSandboxState, o as coerceThreadConversationState, r as getPersistedThreadState, t as getLocationConfigurationService } from "./thread-state-0UfRMWYd.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-BtnvpBEV.js";
|
|
30
|
+
import { t as bindMessageAgent } from "./message-BG1v1lXX.js";
|
|
31
|
+
import { t as bindSpawnAgent } from "./spawn-CNIQGgAS.js";
|
|
32
|
+
import { n as scheduleSessionCompletedPluginTasks, t as processPluginTask } from "./task-runner-CmmfddSZ.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-DKdzxJHE.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";
|
|
37
37
|
import { conversationSidebarAnnotationSchema, createSlackSource, objectTypeSchema } from "@sentry/junior-plugin-api";
|
|
38
38
|
import { alias } from "drizzle-orm/pg-core";
|
|
39
|
-
import { del, get, put } from "@vercel/blob";
|
|
40
39
|
import { HTTPException } from "hono/http-exception";
|
|
41
40
|
import { Message, ThreadImpl, stringifyMarkdown } from "chat";
|
|
42
41
|
import { SlackFormatConverter, createSlackAdapter } from "@chat-adapter/slack";
|
|
@@ -303,83 +302,6 @@ function createAgentDispatchConversationWorker(options) {
|
|
|
303
302
|
}
|
|
304
303
|
};
|
|
305
304
|
}
|
|
306
|
-
// src/chat/attachments/memory.ts
|
|
307
|
-
/**
|
|
308
|
-
* Store attachments in process memory, for tests.
|
|
309
|
-
*
|
|
310
|
-
* Objects are lost when the process stops, and each process has its own
|
|
311
|
-
* copy. Do not use this provider for deployed apps.
|
|
312
|
-
*/
|
|
313
|
-
function createMemoryAttachmentStorage() {
|
|
314
|
-
const objects = /* @__PURE__ */ new Map();
|
|
315
|
-
return {
|
|
316
|
-
objects,
|
|
317
|
-
provider: "memory",
|
|
318
|
-
async put(input) {
|
|
319
|
-
objects.set(input.key, Buffer.from(input.body));
|
|
320
|
-
},
|
|
321
|
-
async get(key) {
|
|
322
|
-
const body = objects.get(key);
|
|
323
|
-
if (!body) return null;
|
|
324
|
-
return new ReadableStream({ start(controller) {
|
|
325
|
-
controller.enqueue(new Uint8Array(body));
|
|
326
|
-
controller.close();
|
|
327
|
-
} });
|
|
328
|
-
},
|
|
329
|
-
async delete(keys) {
|
|
330
|
-
for (const key of keys) objects.delete(key);
|
|
331
|
-
}
|
|
332
|
-
};
|
|
333
|
-
}
|
|
334
|
-
// src/chat/attachments/vercel.ts
|
|
335
|
-
/** Store private conversation attachments in Vercel Blob. */
|
|
336
|
-
function createVercelAttachmentStorage() {
|
|
337
|
-
return {
|
|
338
|
-
provider: "vercel-blob",
|
|
339
|
-
async put(input) {
|
|
340
|
-
await put(input.key, input.body, {
|
|
341
|
-
access: "private",
|
|
342
|
-
addRandomSuffix: false,
|
|
343
|
-
allowOverwrite: true,
|
|
344
|
-
contentType: input.contentType
|
|
345
|
-
});
|
|
346
|
-
},
|
|
347
|
-
async get(key) {
|
|
348
|
-
const result = await get(key, {
|
|
349
|
-
access: "private",
|
|
350
|
-
useCache: false
|
|
351
|
-
});
|
|
352
|
-
return result?.statusCode === 200 ? result.stream : null;
|
|
353
|
-
},
|
|
354
|
-
async delete(keys) {
|
|
355
|
-
if (keys.length === 0) return;
|
|
356
|
-
await del(keys);
|
|
357
|
-
}
|
|
358
|
-
};
|
|
359
|
-
}
|
|
360
|
-
// src/chat/attachments/storage.ts
|
|
361
|
-
/**
|
|
362
|
-
* Return attachment storage for the configured provider.
|
|
363
|
-
*
|
|
364
|
-
* Callers do not choose a provider. Chat config decides it.
|
|
365
|
-
*/
|
|
366
|
-
function getAttachmentStorage() {
|
|
367
|
-
return createAttachmentStorage(getChatConfig().attachmentStorage);
|
|
368
|
-
}
|
|
369
|
-
/**
|
|
370
|
-
* Create attachment storage for one provider config.
|
|
371
|
-
*
|
|
372
|
-
* Runtime code uses `getAttachmentStorage()`. Call this only to test a
|
|
373
|
-
* provider adapter with its own config.
|
|
374
|
-
*/
|
|
375
|
-
function createAttachmentStorage(config) {
|
|
376
|
-
switch (config.provider) {
|
|
377
|
-
case "vercel-blob": return createVercelAttachmentStorage();
|
|
378
|
-
case "s3": return createS3AttachmentStorage(config.s3);
|
|
379
|
-
case "memory": return createMemoryAttachmentStorage();
|
|
380
|
-
default: throw new Error(`Unsupported attachment storage provider: ${String(config.provider)}`);
|
|
381
|
-
}
|
|
382
|
-
}
|
|
383
305
|
// src/chat/plugins/unfinished-work.ts
|
|
384
306
|
/**
|
|
385
307
|
* Return assigned and unfinished plugin work for the candidate conversations.
|
|
@@ -484,17 +406,33 @@ function throwApiError(status, message, cause) {
|
|
|
484
406
|
});
|
|
485
407
|
}
|
|
486
408
|
// src/api/conversations/user-message-activity.ts
|
|
409
|
+
/**
|
|
410
|
+
* The newest event of one type in the outer Conversation that matches the
|
|
411
|
+
* filter. It walks the message role or user message time index from the
|
|
412
|
+
* newest event. The user message index has only matching entries, so that
|
|
413
|
+
* read stops at the first one.
|
|
414
|
+
*/
|
|
415
|
+
function latestEventAt(db, type, filter) {
|
|
416
|
+
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}`);
|
|
417
|
+
}
|
|
487
418
|
/** Read the latest true user message time for each selected conversation. */
|
|
488
419
|
async function readLastUserMessageAtByConversation(db, conversationIds) {
|
|
489
420
|
if (conversationIds.length === 0) return /* @__PURE__ */ new Map();
|
|
490
|
-
const
|
|
491
|
-
const
|
|
492
|
-
const
|
|
421
|
+
const payload = juniorConversationEvents.payload;
|
|
422
|
+
const instruction = latestEventAt(db, "user_message", isUserInstruction(payload));
|
|
423
|
+
const authorKind = sql`(${db.select({ kind: juniorIdentities.kind }).from(juniorIdentities).where(eq(juniorIdentities.id, juniorConversationEvents.actorIdentityId))})`;
|
|
424
|
+
const message = latestEventAt(db, "message", sql`${payload}->>'role' = 'user' and ${authorKind} = 'user'`);
|
|
493
425
|
const rows = await db.select({
|
|
494
|
-
conversationId:
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
426
|
+
conversationId: juniorConversations.conversationId,
|
|
427
|
+
instructionAt: instruction.createdAt,
|
|
428
|
+
messageAt: message.createdAt
|
|
429
|
+
}).from(juniorConversations).leftJoinLateral(instruction, sql`true`).leftJoinLateral(message, sql`true`).where(inArray(juniorConversations.conversationId, conversationIds));
|
|
430
|
+
const result = /* @__PURE__ */ new Map();
|
|
431
|
+
for (const { conversationId, instructionAt, messageAt } of rows) {
|
|
432
|
+
const times = [instructionAt, messageAt].flatMap((at) => at ? [at.getTime()] : []);
|
|
433
|
+
if (times.length > 0) result.set(conversationId, new Date(Math.max(...times)).toISOString());
|
|
434
|
+
}
|
|
435
|
+
return result;
|
|
498
436
|
}
|
|
499
437
|
// src/api/conversations/auto-archive.ts
|
|
500
438
|
const HOUR_MS = 36e5;
|
|
@@ -655,9 +593,8 @@ async function archiveViewerDoneConversations(viewer) {
|
|
|
655
593
|
});
|
|
656
594
|
return { archived };
|
|
657
595
|
}
|
|
658
|
-
/** Read the viewer's effective auto-archive choice for a conversation. */
|
|
659
|
-
async function readConversationAutoArchive(viewer,
|
|
660
|
-
const rootConversationId = await resolveRootConversationId(getSqlExecutor(), conversationId);
|
|
596
|
+
/** Read the viewer's effective auto-archive choice for a conversation root. */
|
|
597
|
+
async function readConversationAutoArchive(viewer, rootConversationId) {
|
|
661
598
|
const [user] = await getDb().select({
|
|
662
599
|
autoArchive: juniorConversationParticipants.autoArchive,
|
|
663
600
|
autoArchiveDefault: juniorUsers.autoArchiveDefault
|
|
@@ -7110,6 +7047,7 @@ async function setViewerArchive(args) {
|
|
|
7110
7047
|
set: {
|
|
7111
7048
|
archivedAt,
|
|
7112
7049
|
pinnedAt: null,
|
|
7050
|
+
pinPosition: null,
|
|
7113
7051
|
lastMessageAt: sql`greatest(${juniorConversationParticipants.lastMessageAt}, excluded.last_message_at)`
|
|
7114
7052
|
}
|
|
7115
7053
|
});
|
|
@@ -7879,6 +7817,40 @@ function hasUnfinishedToolCalls(messages) {
|
|
|
7879
7817
|
} else if (message.role === "toolResult") pending.delete(message.toolCallId);
|
|
7880
7818
|
return pending.size > 0;
|
|
7881
7819
|
}
|
|
7820
|
+
// src/chat/conversations/sql/event-watermarks.ts
|
|
7821
|
+
/**
|
|
7822
|
+
* Read the event watermark of each selected Conversation and each of its
|
|
7823
|
+
* child agents at any depth. Two primary key lookups per Conversation.
|
|
7824
|
+
*/
|
|
7825
|
+
async function readSubtreeEventWatermarks(db, conversationIds) {
|
|
7826
|
+
const conversation = juniorConversations.conversationId;
|
|
7827
|
+
return await db.select({
|
|
7828
|
+
scopeConversationId: conversationSubtreeColumns.scopeConversationId,
|
|
7829
|
+
conversationId: conversation,
|
|
7830
|
+
seq: sql`(
|
|
7831
|
+
select max(watermark.seq) from junior_conversation_events watermark
|
|
7832
|
+
where watermark.conversation_id = ${conversation}
|
|
7833
|
+
)`,
|
|
7834
|
+
originMs: sql`(
|
|
7835
|
+
select (extract(epoch from origin.created_at) * 1000)::double precision
|
|
7836
|
+
from junior_conversation_events origin
|
|
7837
|
+
where origin.conversation_id = ${conversation}
|
|
7838
|
+
order by origin.seq
|
|
7839
|
+
limit 1
|
|
7840
|
+
)`
|
|
7841
|
+
}).from(juniorConversations).innerJoin(conversationSubtree(conversationIds), eq(conversationSubtreeColumns.conversationId, conversation));
|
|
7842
|
+
}
|
|
7843
|
+
/**
|
|
7844
|
+
* Arguments for `innerJoin` that keep only the events inside the seq range of
|
|
7845
|
+
* their Conversation. The range is in the index condition, so a read touches
|
|
7846
|
+
* only the new events.
|
|
7847
|
+
*/
|
|
7848
|
+
function seqRangeJoin(ranges) {
|
|
7849
|
+
const rows = sql.join(ranges.map((range) => sql`(${range.conversationId}::text, ${range.fromSeq}::integer, ${range.toSeq}::integer)`), sql`, `);
|
|
7850
|
+
return [sql`(values ${rows}) as seq_range(conversation_id, from_seq, to_seq)`, sql`seq_range.conversation_id = ${juniorConversationEvents.conversationId}
|
|
7851
|
+
and ${juniorConversationEvents.seq} > seq_range.from_seq
|
|
7852
|
+
and ${juniorConversationEvents.seq} <= seq_range.to_seq`];
|
|
7853
|
+
}
|
|
7882
7854
|
// src/chat/pi/sql-model-usage.ts
|
|
7883
7855
|
/** SQL reporting adapter for usage stored on assistant history events. */
|
|
7884
7856
|
const assistantCall = sql`jsonb_to_record(${juniorConversationEvents.payload})
|
|
@@ -7977,7 +7949,6 @@ async function sumModelUsage(executor, ranges) {
|
|
|
7977
7949
|
const outputTokens = token("output", "outputTokens");
|
|
7978
7950
|
const cachedInputTokens = token("cacheRead", "cachedInputTokens");
|
|
7979
7951
|
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
7952
|
return await executor.db().select({
|
|
7982
7953
|
modelId,
|
|
7983
7954
|
inputTokens: summed(inputTokens),
|
|
@@ -7996,31 +7967,7 @@ async function sumModelUsage(executor, ranges) {
|
|
|
7996
7967
|
costCacheRead: summedCost(nonnegativeNumber(cost, "cacheRead")),
|
|
7997
7968
|
costCacheWrite: summedCost(nonnegativeNumber(cost, "cacheWrite")),
|
|
7998
7969
|
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));
|
|
7970
|
+
}).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
7971
|
}
|
|
8025
7972
|
const modelUsageCacheSchema = z.object({
|
|
8026
7973
|
conversations: z.record(z.string(), z.object({
|
|
@@ -8068,7 +8015,7 @@ function mergeSums(left, right) {
|
|
|
8068
8015
|
async function readConversationModelUsageFromSql(executor, options) {
|
|
8069
8016
|
const state = getStateAdapter();
|
|
8070
8017
|
const key = modelUsageCacheKey(options.conversationId);
|
|
8071
|
-
const [stored, watermarks] = await Promise.all([state.get(key),
|
|
8018
|
+
const [stored, watermarks] = await Promise.all([state.get(key), readSubtreeEventWatermarks(executor.db(), [options.conversationId])]);
|
|
8072
8019
|
const cached = modelUsageCacheSchema.safeParse(stored).data;
|
|
8073
8020
|
const purged = watermarks.some(({ conversationId, seq, originMs }) => {
|
|
8074
8021
|
const seen = cached?.conversations[conversationId];
|
|
@@ -8331,6 +8278,7 @@ function conversationSummaryFromStoredConversation(args) {
|
|
|
8331
8278
|
...locationUrl ? { locationUrl } : void 0,
|
|
8332
8279
|
archivedAt: args.archivedAtMs === void 0 ? null : new Date(args.archivedAtMs).toISOString(),
|
|
8333
8280
|
pinnedAt: args.pinnedAtMs === void 0 ? null : new Date(args.pinnedAtMs).toISOString(),
|
|
8281
|
+
...args.pinPosition === void 0 ? void 0 : { pinPosition: args.pinPosition },
|
|
8334
8282
|
...slackThread ? { channel: slackThread.channelId } : void 0,
|
|
8335
8283
|
...channelName ? { channelName } : void 0,
|
|
8336
8284
|
...channelNameRedacted ? { channelNameRedacted: true } : void 0,
|
|
@@ -8462,14 +8410,43 @@ function eventCost() {
|
|
|
8462
8410
|
function addCostUsd(left, right) {
|
|
8463
8411
|
return Math.round((left + right) * 0xe8d4a51000) / 0xe8d4a51000;
|
|
8464
8412
|
}
|
|
8465
|
-
|
|
8466
|
-
|
|
8467
|
-
|
|
8468
|
-
*/
|
|
8469
|
-
|
|
8470
|
-
|
|
8471
|
-
|
|
8472
|
-
|
|
8413
|
+
function compareText(left, right) {
|
|
8414
|
+
return left < right ? -1 : left > right ? 1 : 0;
|
|
8415
|
+
}
|
|
8416
|
+
/** Cost sums of one operation. Sums of two seq ranges add field by field. */
|
|
8417
|
+
const operationSumsSchema = z.object({
|
|
8418
|
+
costUsd: z.number(),
|
|
8419
|
+
events: z.number().int(),
|
|
8420
|
+
name: z.string(),
|
|
8421
|
+
namespace: z.string()
|
|
8422
|
+
});
|
|
8423
|
+
const auxiliaryCostCacheSchema = z.object({
|
|
8424
|
+
seq: z.number().int(),
|
|
8425
|
+
originMs: z.number(),
|
|
8426
|
+
operations: z.array(operationSumsSchema)
|
|
8427
|
+
});
|
|
8428
|
+
const AUXILIARY_COST_CACHE_TTL_MS = 2592e6;
|
|
8429
|
+
function auxiliaryCostCacheKey(conversationId) {
|
|
8430
|
+
return `conversation-auxiliary-costs:${conversationId}`;
|
|
8431
|
+
}
|
|
8432
|
+
function operationKey(operation) {
|
|
8433
|
+
return `${operation.namespace}\u0000${operation.name}`;
|
|
8434
|
+
}
|
|
8435
|
+
function mergeOperations(operations) {
|
|
8436
|
+
const merged = /* @__PURE__ */ new Map();
|
|
8437
|
+
for (const operation of operations) {
|
|
8438
|
+
const key = operationKey(operation);
|
|
8439
|
+
const current = merged.get(key);
|
|
8440
|
+
merged.set(key, current ? {
|
|
8441
|
+
...current,
|
|
8442
|
+
costUsd: addCostUsd(current.costUsd, operation.costUsd),
|
|
8443
|
+
events: current.events + operation.events
|
|
8444
|
+
} : operation);
|
|
8445
|
+
}
|
|
8446
|
+
return merged;
|
|
8447
|
+
}
|
|
8448
|
+
/** Sum additive event costs by operation, in the seq range of each Conversation. */
|
|
8449
|
+
async function sumOperationCosts(db, ranges) {
|
|
8473
8450
|
const namespace = sql`CASE
|
|
8474
8451
|
WHEN ${juniorConversationEvents.type} = 'structured_event'
|
|
8475
8452
|
THEN ${juniorConversationEvents.payload}->>'namespace'
|
|
@@ -8481,29 +8458,91 @@ async function readConversationAuxiliaryCostsFromSql(db, conversationIds) {
|
|
|
8481
8458
|
ELSE ${juniorConversationEvents.type}
|
|
8482
8459
|
END`;
|
|
8483
8460
|
const cost = eventCost();
|
|
8484
|
-
|
|
8485
|
-
conversationId:
|
|
8486
|
-
childAgentCostUsd: sql`coalesce(round(sum(case when ${isChildAgent} then ${cost} end), 12), 0)::double precision`.mapWith(Number),
|
|
8461
|
+
return await db.select({
|
|
8462
|
+
conversationId: juniorConversationEvents.conversationId,
|
|
8487
8463
|
costUsd: sql`round(sum(${cost}), 12)::double precision`.mapWith(Number),
|
|
8488
8464
|
events: sql`count(*)::integer`.mapWith(Number),
|
|
8489
8465
|
name,
|
|
8490
8466
|
namespace
|
|
8491
|
-
}).from(juniorConversationEvents).innerJoin(
|
|
8467
|
+
}).from(juniorConversationEvents).innerJoin(...seqRangeJoin(ranges)).where(and(inArray(juniorConversationEvents.type, [
|
|
8468
|
+
"structured_event",
|
|
8469
|
+
"guardian_action_reviewed",
|
|
8470
|
+
"turn_routed"
|
|
8471
|
+
]), sql`${cost} >= 0`, notCopiedByFork())).groupBy(juniorConversationEvents.conversationId, namespace, name);
|
|
8472
|
+
}
|
|
8473
|
+
/**
|
|
8474
|
+
* Read the cost operations of each Conversation, from its cache entry plus
|
|
8475
|
+
* the events after the cached seq. The entry is correct for the same reasons
|
|
8476
|
+
* as the model usage cache in `readConversationModelUsageFromSql`: events
|
|
8477
|
+
* are append-only and appends commit in seq order, and a fork commits its
|
|
8478
|
+
* copied events and its fork note in one transaction.
|
|
8479
|
+
*/
|
|
8480
|
+
async function readOperationsByConversation(db, watermarks) {
|
|
8481
|
+
const latest = /* @__PURE__ */ new Map();
|
|
8482
|
+
for (const { conversationId, seq, originMs } of watermarks) if (seq !== null && originMs !== null) latest.set(conversationId, {
|
|
8483
|
+
seq,
|
|
8484
|
+
originMs
|
|
8485
|
+
});
|
|
8486
|
+
const state = getStateAdapter();
|
|
8487
|
+
const entries = await Promise.all([...latest].map(async ([conversationId, watermark]) => {
|
|
8488
|
+
const cached = auxiliaryCostCacheSchema.safeParse(await state.get(auxiliaryCostCacheKey(conversationId))).data;
|
|
8489
|
+
return {
|
|
8490
|
+
base: cached && cached.seq <= watermark.seq && cached.originMs === watermark.originMs ? cached : void 0,
|
|
8491
|
+
conversationId,
|
|
8492
|
+
watermark
|
|
8493
|
+
};
|
|
8494
|
+
}));
|
|
8495
|
+
const ranges = entries.flatMap(({ base, conversationId, watermark }) => watermark.seq > (base?.seq ?? -1) ? [{
|
|
8496
|
+
conversationId,
|
|
8497
|
+
fromSeq: base?.seq ?? -1,
|
|
8498
|
+
toSeq: watermark.seq
|
|
8499
|
+
}] : []);
|
|
8500
|
+
const deltas = ranges.length > 0 ? await sumOperationCosts(db, ranges) : [];
|
|
8492
8501
|
const result = /* @__PURE__ */ new Map();
|
|
8493
|
-
|
|
8494
|
-
|
|
8495
|
-
|
|
8496
|
-
|
|
8497
|
-
}
|
|
8498
|
-
|
|
8499
|
-
|
|
8500
|
-
|
|
8501
|
-
|
|
8502
|
-
|
|
8503
|
-
|
|
8504
|
-
|
|
8502
|
+
await Promise.all(entries.map(async ({ base, conversationId, watermark }) => {
|
|
8503
|
+
if (base && base.seq === watermark.seq) {
|
|
8504
|
+
result.set(conversationId, base.operations);
|
|
8505
|
+
return;
|
|
8506
|
+
}
|
|
8507
|
+
const operations = [...mergeOperations([...base?.operations ?? [], ...deltas.flatMap(({ conversationId: deltaId, ...operation }) => deltaId === conversationId ? [operation] : [])]).values()];
|
|
8508
|
+
result.set(conversationId, operations);
|
|
8509
|
+
await state.set(auxiliaryCostCacheKey(conversationId), {
|
|
8510
|
+
...watermark,
|
|
8511
|
+
operations
|
|
8512
|
+
}, AUXILIARY_COST_CACHE_TTL_MS);
|
|
8513
|
+
}));
|
|
8514
|
+
return result;
|
|
8515
|
+
}
|
|
8516
|
+
/**
|
|
8517
|
+
* Aggregate additive event costs by namespaced operation. The total for each
|
|
8518
|
+
* selected Conversation includes itself and all its child agents at any depth.
|
|
8519
|
+
*/
|
|
8520
|
+
async function readConversationAuxiliaryCostsFromSql(db, conversationIds) {
|
|
8521
|
+
if (conversationIds.length === 0) return /* @__PURE__ */ new Map();
|
|
8522
|
+
const watermarks = await readSubtreeEventWatermarks(db, conversationIds);
|
|
8523
|
+
const operationsByConversation = await readOperationsByConversation(db, watermarks);
|
|
8524
|
+
const membersByScope = /* @__PURE__ */ new Map();
|
|
8525
|
+
for (const { scopeConversationId, conversationId } of watermarks) {
|
|
8526
|
+
const members = membersByScope.get(scopeConversationId) ?? [];
|
|
8527
|
+
members.push(conversationId);
|
|
8528
|
+
membersByScope.set(scopeConversationId, members);
|
|
8529
|
+
}
|
|
8530
|
+
const result = /* @__PURE__ */ new Map();
|
|
8531
|
+
for (const [scopeConversationId, members] of membersByScope) {
|
|
8532
|
+
let childAgentCostUsd = 0;
|
|
8533
|
+
for (const member of members) {
|
|
8534
|
+
if (member === scopeConversationId) continue;
|
|
8535
|
+
for (const operation of operationsByConversation.get(member) ?? []) childAgentCostUsd = addCostUsd(childAgentCostUsd, operation.costUsd);
|
|
8536
|
+
}
|
|
8537
|
+
const operations = [...mergeOperations(members.flatMap((member) => operationsByConversation.get(member) ?? [])).values()].sort((left, right) => compareText(left.namespace, right.namespace) || compareText(left.name, right.name));
|
|
8538
|
+
if (operations.length === 0) continue;
|
|
8539
|
+
result.set(scopeConversationId, {
|
|
8540
|
+
total: {
|
|
8541
|
+
costUsd: operations.reduce((total, operation) => addCostUsd(total, operation.costUsd), 0),
|
|
8542
|
+
operations
|
|
8543
|
+
},
|
|
8544
|
+
...childAgentCostUsd > 0 ? { childAgentCostUsd } : void 0
|
|
8505
8545
|
});
|
|
8506
|
-
result.set(row.conversationId, current);
|
|
8507
8546
|
}
|
|
8508
8547
|
return result;
|
|
8509
8548
|
}
|
|
@@ -8534,23 +8573,44 @@ function isConversationPriority(conversation, nowMs) {
|
|
|
8534
8573
|
return nowMs - lastSeenAt <= UNASSIGNED_PRIORITY_WINDOW_MS;
|
|
8535
8574
|
}
|
|
8536
8575
|
// src/api/conversations/activity-preview.ts
|
|
8576
|
+
/**
|
|
8577
|
+
* The latest non-empty message with one role in the outer Conversation. It
|
|
8578
|
+
* walks `junior_conversation_events_message_role_idx` from the newest
|
|
8579
|
+
* message and stops at the first match.
|
|
8580
|
+
*/
|
|
8581
|
+
function latestMessage(db, role) {
|
|
8582
|
+
const text = sql`${juniorConversationEvents.payload}->>'text'`;
|
|
8583
|
+
return db.select({
|
|
8584
|
+
createdAt: juniorConversationEvents.createdAt,
|
|
8585
|
+
text: text.as(`${role}_text`)
|
|
8586
|
+
}).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}`);
|
|
8587
|
+
}
|
|
8537
8588
|
/** Read one recent assistant message, or the latest user message, for each conversation. */
|
|
8538
8589
|
async function readConversationActivityPreviews(db, conversationIds) {
|
|
8539
8590
|
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
|
-
|
|
8591
|
+
const assistant = latestMessage(db, "assistant");
|
|
8592
|
+
const user = latestMessage(db, "user");
|
|
8593
|
+
const rows = await db.select({
|
|
8594
|
+
conversationId: juniorConversations.conversationId,
|
|
8595
|
+
assistantAt: assistant.createdAt,
|
|
8596
|
+
assistantText: assistant.text,
|
|
8597
|
+
userAt: user.createdAt,
|
|
8598
|
+
userText: user.text
|
|
8599
|
+
}).from(juniorConversations).leftJoinLateral(assistant, sql`true`).leftJoinLateral(user, sql`true`).where(inArray(juniorConversations.conversationId, conversationIds));
|
|
8600
|
+
const previews = /* @__PURE__ */ new Map();
|
|
8601
|
+
for (const row of rows) {
|
|
8602
|
+
const preview = row.assistantAt && row.assistantText !== null ? {
|
|
8603
|
+
createdAt: row.assistantAt.toISOString(),
|
|
8604
|
+
role: "assistant",
|
|
8605
|
+
text: row.assistantText
|
|
8606
|
+
} : row.userAt && row.userText !== null ? {
|
|
8607
|
+
createdAt: row.userAt.toISOString(),
|
|
8608
|
+
role: "user",
|
|
8609
|
+
text: row.userText
|
|
8610
|
+
} : void 0;
|
|
8611
|
+
if (preview) previews.set(row.conversationId, preview);
|
|
8612
|
+
}
|
|
8613
|
+
return previews;
|
|
8554
8614
|
}
|
|
8555
8615
|
// src/api/conversations/participants.ts
|
|
8556
8616
|
const identityColumns = {
|
|
@@ -8974,7 +9034,7 @@ async function readParentConversationId(conversationId) {
|
|
|
8974
9034
|
* Conversation has its own access check, so a viewer sees a label only where
|
|
8975
9035
|
* they can see private content.
|
|
8976
9036
|
*/
|
|
8977
|
-
async function readConversationAgentTree(conversationId,
|
|
9037
|
+
async function readConversationAgentTree(conversationId, readAccess) {
|
|
8978
9038
|
const ids = [conversationId];
|
|
8979
9039
|
let parentId = await readParentConversationId(conversationId);
|
|
8980
9040
|
while (parentId && !ids.includes(parentId) && ids.length < MAX_AGENT_TREE_DEPTH) {
|
|
@@ -8984,7 +9044,7 @@ async function readConversationAgentTree(conversationId, viewer) {
|
|
|
8984
9044
|
if (ids.length < 2) return;
|
|
8985
9045
|
const root = parentId ? void 0 : await getConversationStore().get({ conversationId: ids[0] });
|
|
8986
9046
|
const [access, automationTitleByConversation, firstHumanMessageTextByConversation] = await Promise.all([
|
|
8987
|
-
|
|
9047
|
+
readAccess(ids),
|
|
8988
9048
|
readAutomationTitlesByConversationId(root ? [root] : []),
|
|
8989
9049
|
readFirstHumanMessageTexts(getDb(), root ? [root] : [])
|
|
8990
9050
|
]);
|
|
@@ -9036,7 +9096,7 @@ async function keepQuickQuestionForViewer(viewer, conversationId) {
|
|
|
9036
9096
|
* Read fork state for the viewer: whether they can fork, and the source and
|
|
9037
9097
|
* fork links that they can open.
|
|
9038
9098
|
*/
|
|
9039
|
-
async function readConversationForks(conversationId,
|
|
9099
|
+
async function readConversationForks(conversationId, readAccess) {
|
|
9040
9100
|
const db = getDb();
|
|
9041
9101
|
const [row] = await db.select({
|
|
9042
9102
|
forkedFrom: juniorConversations.forkedFromConversationId,
|
|
@@ -9045,11 +9105,11 @@ async function readConversationForks(conversationId, viewer) {
|
|
|
9045
9105
|
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
9106
|
const forkedFrom = row?.forkedFrom ?? void 0;
|
|
9047
9107
|
const ids = forks.map((fork) => fork.conversationId);
|
|
9048
|
-
const access = await
|
|
9108
|
+
const access = await readAccess([
|
|
9049
9109
|
conversationId,
|
|
9050
9110
|
...ids,
|
|
9051
9111
|
...forkedFrom ? [forkedFrom] : []
|
|
9052
|
-
]
|
|
9112
|
+
]);
|
|
9053
9113
|
const canOpen = (id) => access.get(id)?.canViewPrivateContent;
|
|
9054
9114
|
if (!canOpen(conversationId)) return {
|
|
9055
9115
|
canFork: false,
|
|
@@ -9124,30 +9184,40 @@ async function readSubtreeDetailVersion(conversationId) {
|
|
|
9124
9184
|
version: "0"
|
|
9125
9185
|
};
|
|
9126
9186
|
}
|
|
9187
|
+
/** Read the viewer's marks and auto-archive choice, which live on the root. */
|
|
9188
|
+
async function readViewerRootState(viewer, conversationId) {
|
|
9189
|
+
const rootConversationId = await resolveRootConversationId(getSqlExecutor(), conversationId);
|
|
9190
|
+
const [viewerMarks, autoArchive] = await Promise.all([readConversationViewerMarks(viewer, rootConversationId), readConversationAutoArchive(viewer, rootConversationId)]);
|
|
9191
|
+
return {
|
|
9192
|
+
autoArchive,
|
|
9193
|
+
viewerMarks
|
|
9194
|
+
};
|
|
9195
|
+
}
|
|
9127
9196
|
/** Read the detail state that the ETag hashes and the report shows. */
|
|
9128
9197
|
async function readConversationDetailState(conversationId, viewer) {
|
|
9129
|
-
const
|
|
9130
|
-
|
|
9131
|
-
|
|
9132
|
-
|
|
9133
|
-
|
|
9198
|
+
const readAccess = createConversationAccessReader(getDb(), viewer);
|
|
9199
|
+
const [accessById, viewerRootState, forks, agentTree, readPosition, attachmentsVersion] = await Promise.all([
|
|
9200
|
+
readAccess([conversationId]),
|
|
9201
|
+
viewer ? readViewerRootState(viewer, conversationId) : void 0,
|
|
9202
|
+
readConversationForks(conversationId, readAccess),
|
|
9203
|
+
readConversationAgentTree(conversationId, readAccess),
|
|
9134
9204
|
viewer ? readConversationReadPosition(viewer, conversationId) : void 0,
|
|
9135
|
-
viewer ? readConversationAutoArchive(viewer, conversationId) : void 0,
|
|
9136
9205
|
readSlackAttachmentsVersion(getSqlExecutor(), conversationId)
|
|
9137
9206
|
]);
|
|
9138
9207
|
const access = accessById.get(conversationId);
|
|
9208
|
+
const transcriptVersion = createHash("sha256").update(JSON.stringify({
|
|
9209
|
+
attachments: attachmentsVersion,
|
|
9210
|
+
canViewPrivateContent: access?.canViewPrivateContent ?? false,
|
|
9211
|
+
junior: JUNIOR_VERSION
|
|
9212
|
+
})).digest("base64url");
|
|
9139
9213
|
return {
|
|
9140
9214
|
access,
|
|
9141
9215
|
agentTree,
|
|
9142
|
-
autoArchive,
|
|
9216
|
+
autoArchive: viewerRootState?.autoArchive,
|
|
9143
9217
|
forks,
|
|
9144
9218
|
readPosition,
|
|
9145
|
-
transcriptVersion
|
|
9146
|
-
|
|
9147
|
-
canViewPrivateContent: access?.canViewPrivateContent ?? false,
|
|
9148
|
-
junior: JUNIOR_VERSION
|
|
9149
|
-
})).digest("base64url"),
|
|
9150
|
-
viewerMarks
|
|
9219
|
+
transcriptVersion,
|
|
9220
|
+
viewerMarks: viewerRootState?.viewerMarks
|
|
9151
9221
|
};
|
|
9152
9222
|
}
|
|
9153
9223
|
/**
|
|
@@ -9395,7 +9465,10 @@ async function pinConversation(viewer, conversationId, body) {
|
|
|
9395
9465
|
const rootConversationId = await resolveRootConversationId(executor, conversationId);
|
|
9396
9466
|
const db = executor.db();
|
|
9397
9467
|
if (!body.pinned) {
|
|
9398
|
-
await db.update(juniorConversationParticipants).set({
|
|
9468
|
+
await db.update(juniorConversationParticipants).set({
|
|
9469
|
+
pinnedAt: null,
|
|
9470
|
+
pinPosition: null
|
|
9471
|
+
}).where(and(eq(juniorConversationParticipants.userId, viewer.id), eq(juniorConversationParticipants.rootConversationId, rootConversationId)));
|
|
9399
9472
|
return { pinnedAt: null };
|
|
9400
9473
|
}
|
|
9401
9474
|
const [root] = await db.select({ lastActivityAt: juniorConversations.lastActivityAt }).from(juniorConversations).where(eq(juniorConversations.conversationId, rootConversationId)).limit(1);
|
|
@@ -9410,11 +9483,25 @@ async function pinConversation(viewer, conversationId, body) {
|
|
|
9410
9483
|
target: [juniorConversationParticipants.userId, juniorConversationParticipants.rootConversationId],
|
|
9411
9484
|
set: {
|
|
9412
9485
|
archivedAt: null,
|
|
9413
|
-
pinnedAt
|
|
9486
|
+
pinnedAt,
|
|
9487
|
+
pinPosition: null
|
|
9414
9488
|
}
|
|
9415
9489
|
});
|
|
9416
9490
|
return { pinnedAt: pinnedAt.toISOString() };
|
|
9417
9491
|
}
|
|
9492
|
+
/**
|
|
9493
|
+
* Save the viewer's Pinned order. Each listed pin takes its index as its
|
|
9494
|
+
* place. The update reads only the viewer's own pinned rows, so an id that
|
|
9495
|
+
* the viewer did not pin changes nothing and grants nothing.
|
|
9496
|
+
*/
|
|
9497
|
+
async function reorderPinnedConversations(viewer, body) {
|
|
9498
|
+
const ids = body.conversationIds;
|
|
9499
|
+
const participants = juniorConversationParticipants;
|
|
9500
|
+
const positions = sql.join(ids.map((id, index) => sql`when ${id} then ${index}::integer`), sql` `);
|
|
9501
|
+
const updated = await getDb().update(participants).set({ pinPosition: sql`case ${participants.rootConversationId} ${positions} else ${participants.pinPosition} + ${ids.length}::integer end` }).where(and(eq(participants.userId, viewer.id), isNotNull(participants.pinnedAt))).returning({ rootConversationId: participants.rootConversationId });
|
|
9502
|
+
const updatedIds = new Set(updated.map((row) => row.rootConversationId));
|
|
9503
|
+
return { conversationIds: ids.filter((id) => updatedIds.has(id)) };
|
|
9504
|
+
}
|
|
9418
9505
|
// src/api/conversations/steer-pending-messages.ts
|
|
9419
9506
|
/**
|
|
9420
9507
|
* Steer the viewer's own queued web messages into the conversation now.
|
|
@@ -9486,4 +9573,4 @@ function viewerWebMessages(messages, viewer) {
|
|
|
9486
9573
|
}] : [];
|
|
9487
9574
|
});
|
|
9488
9575
|
}
|
|
9489
|
-
export {
|
|
9576
|
+
export { reviewItemChange as $, createSlackWebApiStatusSender as A, stopSlackThread as B, readConversationPendingMessages as C, createProductionConversationWorkOptions as D, archiveConversation as E, resolveAllowedDomains as F, bindMessageAuthorIdentityId as G, withNormalizedThreadId as H, recordSkippedConversationMessage as I, parseContent as J, startProcessingReaction as K, buildSlackInboundMessage as L, isAllowedDomain as M, isAllowedSignInEmail as N, createProductionSlackWebhookServices as O, readEnvList as P, readReviewItemForUser as Q, clearSlackPendingReactions as R, cancelConversationPendingMessagesForViewer as S, resolveMentions as T, stopConversationTurn as U, normalizeIncomingSlackThreadId as V, THREAD_OPTOUT_ACK as W, actOnReviewItem as X, ReviewItemActionError as Y, closeReviewItemsAnsweredByReply as Z, readFirstHumanMessageTexts as _, readConversationDetail as a, updateUserAutoArchiveSettings as at, decodeConversationCursor as b, forkConversationForViewer as c, throwApiError as ct, readConversationFeed as d, GET as dt, DEFAULT_AUTO_ARCHIVE_SETTINGS as et, readConversationRecordFromSql as f, readHealthReport as ft, conversationSummaryFromStoredConversation as g, readConversationTreeMetricsFromSql as h, reorderPinnedConversations as i, setConversationAutoArchive as it, assertNoLegacyAllowedDomains as j, getProductionSlackAdapter as k, keepQuickQuestionForViewer as l, AGENT_DISPATCH_MAX_AGE_MS as lt, childAgentTotalsReport as m, steerConversationPendingMessagesForViewer as n, readUserAutoArchiveSettings as nt, readConversationDetailEtag as o, emptyResponse as ot, readConversationAuxiliaryCostsFromSql as p, stripLeadingBotMention as q, pinConversation as r, runAutoArchiveSweep as rt, markConversationRead as s, jsonResponse as st, stopConversationTurnForViewer as t, archiveViewerDoneConversations as tt, readConversationEvents as u, enqueueAgentDispatch as ut, appendConversationMessageForViewer as v, requireConversationPendingMessages as w, encodeConversationCursor as x, createConversationForViewer as y, isSlackMessageStopped as z };
|