@sentry/junior 0.280.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-DVN3iwf9.js → adapter-BAqo7eOH.js} +1 -1
- package/dist/{admin-Q_UI--9W.js → admin-DbWpMHh6.js} +1 -1
- package/dist/{agent-runner-_PYLv4Qo.js → agent-runner-h4CDcnDV.js} +1001 -981
- package/dist/api/schema.d.ts +2 -2
- package/dist/api/schema.js +5 -5
- package/dist/api.d.ts +1 -1
- package/dist/api.js +39 -33
- package/dist/{app-CL2zzzE0.d.ts → app-B-0wwAxr.d.ts} +2 -2
- package/dist/app.d.ts +1 -1
- package/dist/app.js +42 -34
- package/dist/{assistant-reply-DbebsAxi.js → assistant-reply-4Wvo95-N.js} +1 -1
- package/dist/{automation-CPqRFjIa.js → automation-sIsmIXH7.js} +1 -1
- package/dist/{background-compaction-queue-B9lmh8Ml.js → background-compaction-queue-CoWqScCC.js} +2 -2
- package/dist/{briefs-Dej7V0Bz.js → briefs-CMiotFo9.js} +4 -8
- package/dist/{catalog-runtime-DpN0sWQ6.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-h2A2ZPzY.js → client-BHgCXeaF.js} +2 -2
- package/dist/{config-CusBFORe.js → config-DBdBimZ9.js} +1 -1
- package/dist/{connections-C4h6mGha.js → connections-DjY72_uF.js} +10 -10
- package/dist/{conversation-DExTZw8B.js → conversation-DNtcULyX.js} +29 -8
- package/dist/{conversation-pending-messages-Dgz6hrJs.js → conversation-pending-messages-LlFnr9-m.js} +10 -2
- package/dist/{conversation-privacy-2cm6OpNg.js → conversation-privacy-DiDh9KE4.js} +1 -1
- package/dist/{credential-sync-DK06Jgt-.js → credential-sync-DUrQwccr.js} +13 -13
- package/dist/{db-Dsvk1Tp1.d.ts → db-hQsoB16L.d.ts} +2 -1
- package/dist/{executor-Cmr0J8W3.js → executor-CGqJCxgR.js} +14 -3
- package/dist/instrumentation.js +2 -2
- package/dist/{logging-CGnh65_X.js → logging-DapIaJAi.js} +1 -1
- package/dist/{message-RpAnqHPY.js → message-BjN5sKad.js} +9 -9
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +3 -11
- package/dist/{oauth-callback-server-BBnhVKuX.js → oauth-callback-server-DVHKrjJP.js} +2 -2
- package/dist/{projection-C1MghKyI.js → projection-ii_OYu6z.js} +78 -30
- package/dist/{prompt-BcHg-BMy.js → prompt-DI6KCtwb.js} +5 -26
- package/dist/{registry-DR7DjX9H.js → registry-DpjG3yS-.js} +1 -1
- package/dist/{resolve-0Ful4oDv.js → resolve-iMW9Dgo2.js} +3 -3
- package/dist/{result-Dd9kCuQ-.js → result-BrlvfyIj.js} +9 -9
- package/dist/{runner-yiY8gUUu.js → runner-Bg9mr2pB.js} +11 -11
- package/dist/{sandbox-egress-signals-BzQVHCMz.js → sandbox-egress-signals-Bd3lb_Wd.js} +1 -1
- package/dist/{schema-C5pEgfHc.js → schema-BN34Jy-U.js} +3 -3
- package/dist/{schema-BkMmF552.d.ts → schema-CsqJzkP5.d.ts} +68 -9
- package/dist/{service-account-Cu7HFLZQ.js → service-account-Bd1348kw.js} +3 -3
- package/dist/{service-account-PIMpWZHF.js → service-account-Dfl9Pitm.js} +3 -3
- package/dist/{session-stop-CDEMsNtv.js → session-stop-CVEEx_YD.js} +12 -12
- package/dist/{skills-B2xIoe0f.js → skills-DqUUuf4L.js} +2 -2
- package/dist/{spawn-C0DySQRV.js → spawn-e7rQs14T.js} +2 -2
- package/dist/{stop-Dj5-nrAo.js → stop-DtpBUUJq.js} +353 -135
- package/dist/{store-Dlio-o6u.js → store-nETG4KVg.js} +4 -4
- package/dist/{store-QzOfDwKA.js → store-nu3Xx08K.js} +3 -3
- package/dist/{task-queue-Cp1V_XW3.js → task-queue-CYje8WKs.js} +3 -3
- package/dist/{task-runner-CQkkUj3o.js → task-runner-CwegN45x.js} +6 -6
- package/dist/{thread-state-Bn87cfzE.js → thread-state-BDaMl9yd.js} +4 -4
- package/dist/{turn-failure-response-CQebxByj.js → turn-failure-response-CV06tN_R.js} +7 -7
- package/dist/{turn-lifecycle-CJJsOhXB.js → turn-lifecycle-CF2N7ud5.js} +1 -1
- package/dist/{turn-session-routing-bmG330Cf.js → turn-session-routing-BIJGJjVh.js} +9 -9
- package/dist/{validation-D1wcf7hp.js → validation-DXvxEEjq.js} +1 -1
- package/dist/{version-BeHSXUK6.js → version-CzEk1KBX.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{viewer-BZ0Hp5Nb.js → viewer-C2PztlYX.js} +22 -8
- package/dist/{work-BTcCIbWu.js → work-BM_L0Pv9.js} +10 -10
- package/dist/{worker-D3fDK6zc.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,36 +1,36 @@
|
|
|
1
|
-
import { 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-
|
|
1
|
+
import { h as startSpan, i as getActiveSpan, r as continueTrace } from "./sentry-BRTJqumy.js";
|
|
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-
|
|
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-BAqo7eOH.js";
|
|
15
|
+
import { R as readMessageAttachments, c as conversationDetailReportSchema, p as conversationFeedSchema, u as conversationEventPageSchema } from "./conversation-DNtcULyX.js";
|
|
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-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-
|
|
24
|
-
import { d as
|
|
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-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
|
+
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-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";
|
|
@@ -449,7 +449,27 @@ function noStoreInit(init) {
|
|
|
449
449
|
}
|
|
450
450
|
/** Serialize a REST response only after it satisfies its declared schema. */
|
|
451
451
|
function jsonResponse(schema, value, init) {
|
|
452
|
-
return
|
|
452
|
+
return startSpan({
|
|
453
|
+
name: "Write API response",
|
|
454
|
+
op: "serialize"
|
|
455
|
+
}, (span) => {
|
|
456
|
+
const startedAt = performance.now();
|
|
457
|
+
const parsed = schema.parse(value);
|
|
458
|
+
const parsedAt = performance.now();
|
|
459
|
+
const body = JSON.stringify(parsed);
|
|
460
|
+
span.setAttributes({
|
|
461
|
+
"app.api.response.chars": body.length,
|
|
462
|
+
"app.api.response.json_stringify_ms": Math.round(performance.now() - parsedAt),
|
|
463
|
+
"app.api.response.schema_parse_ms": Math.round(parsedAt - startedAt)
|
|
464
|
+
});
|
|
465
|
+
const responseInit = noStoreInit(init);
|
|
466
|
+
const headers = new Headers(responseInit.headers);
|
|
467
|
+
if (!headers.has("content-type")) headers.set("content-type", "application/json");
|
|
468
|
+
return new Response(body, {
|
|
469
|
+
...responseInit,
|
|
470
|
+
headers
|
|
471
|
+
});
|
|
472
|
+
});
|
|
453
473
|
}
|
|
454
474
|
/** Return an empty personalized API response with no-store caching. */
|
|
455
475
|
function emptyResponse(status = 204) {
|
|
@@ -464,17 +484,33 @@ function throwApiError(status, message, cause) {
|
|
|
464
484
|
});
|
|
465
485
|
}
|
|
466
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
|
+
}
|
|
467
496
|
/** Read the latest true user message time for each selected conversation. */
|
|
468
497
|
async function readLastUserMessageAtByConversation(db, conversationIds) {
|
|
469
498
|
if (conversationIds.length === 0) return /* @__PURE__ */ new Map();
|
|
470
|
-
const
|
|
471
|
-
const
|
|
472
|
-
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'`);
|
|
473
503
|
const rows = await db.select({
|
|
474
|
-
conversationId:
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
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;
|
|
478
514
|
}
|
|
479
515
|
// src/api/conversations/auto-archive.ts
|
|
480
516
|
const HOUR_MS = 36e5;
|
|
@@ -635,9 +671,8 @@ async function archiveViewerDoneConversations(viewer) {
|
|
|
635
671
|
});
|
|
636
672
|
return { archived };
|
|
637
673
|
}
|
|
638
|
-
/** Read the viewer's effective auto-archive choice for a conversation. */
|
|
639
|
-
async function readConversationAutoArchive(viewer,
|
|
640
|
-
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) {
|
|
641
676
|
const [user] = await getDb().select({
|
|
642
677
|
autoArchive: juniorConversationParticipants.autoArchive,
|
|
643
678
|
autoArchiveDefault: juniorUsers.autoArchiveDefault
|
|
@@ -7397,6 +7432,8 @@ const CURSOR_CONTEXT = "junior-conversation-report-cursor";
|
|
|
7397
7432
|
const conversationCursorPayloadSchema = z.object({
|
|
7398
7433
|
conversationId: z.string().min(1),
|
|
7399
7434
|
seq: z.number().int().min(-1),
|
|
7435
|
+
/** Transcript version of the detail that issued an `appendCursor`. */
|
|
7436
|
+
transcript: z.string().min(1).optional(),
|
|
7400
7437
|
version: z.literal(1)
|
|
7401
7438
|
}).strict();
|
|
7402
7439
|
function cursorSecret() {
|
|
@@ -7426,7 +7463,10 @@ function decodeConversationCursor(args) {
|
|
|
7426
7463
|
try {
|
|
7427
7464
|
const parsed = conversationCursorPayloadSchema.parse(JSON.parse(Buffer.from(encoded, "base64url").toString("utf8")));
|
|
7428
7465
|
if (parsed.conversationId !== args.conversationId) return;
|
|
7429
|
-
return {
|
|
7466
|
+
return {
|
|
7467
|
+
seq: parsed.seq,
|
|
7468
|
+
...parsed.transcript ? { transcript: parsed.transcript } : void 0
|
|
7469
|
+
};
|
|
7430
7470
|
} catch {
|
|
7431
7471
|
return;
|
|
7432
7472
|
}
|
|
@@ -7854,6 +7894,40 @@ function hasUnfinishedToolCalls(messages) {
|
|
|
7854
7894
|
} else if (message.role === "toolResult") pending.delete(message.toolCallId);
|
|
7855
7895
|
return pending.size > 0;
|
|
7856
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
|
+
}
|
|
7857
7931
|
// src/chat/pi/sql-model-usage.ts
|
|
7858
7932
|
/** SQL reporting adapter for usage stored on assistant history events. */
|
|
7859
7933
|
const assistantCall = sql`jsonb_to_record(${juniorConversationEvents.payload})
|
|
@@ -7952,7 +8026,6 @@ async function sumModelUsage(executor, ranges) {
|
|
|
7952
8026
|
const outputTokens = token("output", "outputTokens");
|
|
7953
8027
|
const cachedInputTokens = token("cacheRead", "cachedInputTokens");
|
|
7954
8028
|
const cacheCreationTokens = token("cacheWrite", "cacheCreationTokens");
|
|
7955
|
-
const rangeRows = sql.join(ranges.map((range) => sql`(${range.conversationId}::text, ${range.fromSeq}::integer, ${range.toSeq}::integer)`), sql`, `);
|
|
7956
8029
|
return await executor.db().select({
|
|
7957
8030
|
modelId,
|
|
7958
8031
|
inputTokens: summed(inputTokens),
|
|
@@ -7971,31 +8044,7 @@ async function sumModelUsage(executor, ranges) {
|
|
|
7971
8044
|
costCacheRead: summedCost(nonnegativeNumber(cost, "cacheRead")),
|
|
7972
8045
|
costCacheWrite: summedCost(nonnegativeNumber(cost, "cacheWrite")),
|
|
7973
8046
|
costTotal: summedCost(nonnegativeNumber(cost, "total"))
|
|
7974
|
-
}).from(juniorConversationEvents).innerJoin(sql`(
|
|
7975
|
-
and ${juniorConversationEvents.seq} > seq_range.from_seq
|
|
7976
|
-
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);
|
|
7977
|
-
}
|
|
7978
|
-
/**
|
|
7979
|
-
* The last event seq of each Conversation in a subtree, and the creation time
|
|
7980
|
-
* of its first event. A purged Conversation can get new events under the same
|
|
7981
|
-
* id, with seq starting again at 0; the first event time tells them apart.
|
|
7982
|
-
*/
|
|
7983
|
-
async function readEventWatermarks(executor, conversationId) {
|
|
7984
|
-
const conversation = juniorConversations.conversationId;
|
|
7985
|
-
return await executor.db().select({
|
|
7986
|
-
conversationId: conversation,
|
|
7987
|
-
seq: sql`(
|
|
7988
|
-
select max(watermark.seq) from junior_conversation_events watermark
|
|
7989
|
-
where watermark.conversation_id = ${conversation}
|
|
7990
|
-
)`,
|
|
7991
|
-
originMs: sql`(
|
|
7992
|
-
select (extract(epoch from origin.created_at) * 1000)::double precision
|
|
7993
|
-
from junior_conversation_events origin
|
|
7994
|
-
where origin.conversation_id = ${conversation}
|
|
7995
|
-
order by origin.seq
|
|
7996
|
-
limit 1
|
|
7997
|
-
)`
|
|
7998
|
-
}).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);
|
|
7999
8048
|
}
|
|
8000
8049
|
const modelUsageCacheSchema = z.object({
|
|
8001
8050
|
conversations: z.record(z.string(), z.object({
|
|
@@ -8043,7 +8092,7 @@ function mergeSums(left, right) {
|
|
|
8043
8092
|
async function readConversationModelUsageFromSql(executor, options) {
|
|
8044
8093
|
const state = getStateAdapter();
|
|
8045
8094
|
const key = modelUsageCacheKey(options.conversationId);
|
|
8046
|
-
const [stored, watermarks] = await Promise.all([state.get(key),
|
|
8095
|
+
const [stored, watermarks] = await Promise.all([state.get(key), readSubtreeEventWatermarks(executor.db(), [options.conversationId])]);
|
|
8047
8096
|
const cached = modelUsageCacheSchema.safeParse(stored).data;
|
|
8048
8097
|
const purged = watermarks.some(({ conversationId, seq, originMs }) => {
|
|
8049
8098
|
const seen = cached?.conversations[conversationId];
|
|
@@ -8119,7 +8168,6 @@ function briefMentionTexts(brief) {
|
|
|
8119
8168
|
brief.intent,
|
|
8120
8169
|
brief.outcome.text,
|
|
8121
8170
|
...brief.decisions.flatMap((decision) => [decision.text, decision.by]),
|
|
8122
|
-
...brief.openDecisions.flatMap((decision) => [decision.text, decision.owner]),
|
|
8123
8171
|
...brief.facts
|
|
8124
8172
|
];
|
|
8125
8173
|
}
|
|
@@ -8438,14 +8486,43 @@ function eventCost() {
|
|
|
8438
8486
|
function addCostUsd(left, right) {
|
|
8439
8487
|
return Math.round((left + right) * 0xe8d4a51000) / 0xe8d4a51000;
|
|
8440
8488
|
}
|
|
8441
|
-
|
|
8442
|
-
|
|
8443
|
-
|
|
8444
|
-
*/
|
|
8445
|
-
|
|
8446
|
-
|
|
8447
|
-
|
|
8448
|
-
|
|
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) {
|
|
8449
8526
|
const namespace = sql`CASE
|
|
8450
8527
|
WHEN ${juniorConversationEvents.type} = 'structured_event'
|
|
8451
8528
|
THEN ${juniorConversationEvents.payload}->>'namespace'
|
|
@@ -8457,29 +8534,91 @@ async function readConversationAuxiliaryCostsFromSql(db, conversationIds) {
|
|
|
8457
8534
|
ELSE ${juniorConversationEvents.type}
|
|
8458
8535
|
END`;
|
|
8459
8536
|
const cost = eventCost();
|
|
8460
|
-
|
|
8461
|
-
conversationId:
|
|
8462
|
-
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,
|
|
8463
8539
|
costUsd: sql`round(sum(${cost}), 12)::double precision`.mapWith(Number),
|
|
8464
8540
|
events: sql`count(*)::integer`.mapWith(Number),
|
|
8465
8541
|
name,
|
|
8466
8542
|
namespace
|
|
8467
|
-
}).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) : [];
|
|
8468
8577
|
const result = /* @__PURE__ */ new Map();
|
|
8469
|
-
|
|
8470
|
-
|
|
8471
|
-
|
|
8472
|
-
|
|
8473
|
-
}
|
|
8474
|
-
|
|
8475
|
-
|
|
8476
|
-
|
|
8477
|
-
|
|
8478
|
-
|
|
8479
|
-
|
|
8480
|
-
|
|
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
|
|
8481
8621
|
});
|
|
8482
|
-
result.set(row.conversationId, current);
|
|
8483
8622
|
}
|
|
8484
8623
|
return result;
|
|
8485
8624
|
}
|
|
@@ -8510,23 +8649,44 @@ function isConversationPriority(conversation, nowMs) {
|
|
|
8510
8649
|
return nowMs - lastSeenAt <= UNASSIGNED_PRIORITY_WINDOW_MS;
|
|
8511
8650
|
}
|
|
8512
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
|
+
}
|
|
8513
8664
|
/** Read one recent assistant message, or the latest user message, for each conversation. */
|
|
8514
8665
|
async function readConversationActivityPreviews(db, conversationIds) {
|
|
8515
8666
|
if (conversationIds.length === 0) return /* @__PURE__ */ new Map();
|
|
8516
|
-
const
|
|
8517
|
-
const
|
|
8518
|
-
const
|
|
8519
|
-
|
|
8520
|
-
|
|
8521
|
-
|
|
8522
|
-
|
|
8523
|
-
|
|
8524
|
-
}).from(
|
|
8525
|
-
|
|
8526
|
-
|
|
8527
|
-
|
|
8528
|
-
|
|
8529
|
-
|
|
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;
|
|
8530
8690
|
}
|
|
8531
8691
|
// src/api/conversations/participants.ts
|
|
8532
8692
|
const identityColumns = {
|
|
@@ -8950,7 +9110,7 @@ async function readParentConversationId(conversationId) {
|
|
|
8950
9110
|
* Conversation has its own access check, so a viewer sees a label only where
|
|
8951
9111
|
* they can see private content.
|
|
8952
9112
|
*/
|
|
8953
|
-
async function readConversationAgentTree(conversationId,
|
|
9113
|
+
async function readConversationAgentTree(conversationId, readAccess) {
|
|
8954
9114
|
const ids = [conversationId];
|
|
8955
9115
|
let parentId = await readParentConversationId(conversationId);
|
|
8956
9116
|
while (parentId && !ids.includes(parentId) && ids.length < MAX_AGENT_TREE_DEPTH) {
|
|
@@ -8960,7 +9120,7 @@ async function readConversationAgentTree(conversationId, viewer) {
|
|
|
8960
9120
|
if (ids.length < 2) return;
|
|
8961
9121
|
const root = parentId ? void 0 : await getConversationStore().get({ conversationId: ids[0] });
|
|
8962
9122
|
const [access, automationTitleByConversation, firstHumanMessageTextByConversation] = await Promise.all([
|
|
8963
|
-
|
|
9123
|
+
readAccess(ids),
|
|
8964
9124
|
readAutomationTitlesByConversationId(root ? [root] : []),
|
|
8965
9125
|
readFirstHumanMessageTexts(getDb(), root ? [root] : [])
|
|
8966
9126
|
]);
|
|
@@ -9012,7 +9172,7 @@ async function keepQuickQuestionForViewer(viewer, conversationId) {
|
|
|
9012
9172
|
* Read fork state for the viewer: whether they can fork, and the source and
|
|
9013
9173
|
* fork links that they can open.
|
|
9014
9174
|
*/
|
|
9015
|
-
async function readConversationForks(conversationId,
|
|
9175
|
+
async function readConversationForks(conversationId, readAccess) {
|
|
9016
9176
|
const db = getDb();
|
|
9017
9177
|
const [row] = await db.select({
|
|
9018
9178
|
forkedFrom: juniorConversations.forkedFromConversationId,
|
|
@@ -9021,11 +9181,11 @@ async function readConversationForks(conversationId, viewer) {
|
|
|
9021
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);
|
|
9022
9182
|
const forkedFrom = row?.forkedFrom ?? void 0;
|
|
9023
9183
|
const ids = forks.map((fork) => fork.conversationId);
|
|
9024
|
-
const access = await
|
|
9184
|
+
const access = await readAccess([
|
|
9025
9185
|
conversationId,
|
|
9026
9186
|
...ids,
|
|
9027
9187
|
...forkedFrom ? [forkedFrom] : []
|
|
9028
|
-
]
|
|
9188
|
+
]);
|
|
9029
9189
|
const canOpen = (id) => access.get(id)?.canViewPrivateContent;
|
|
9030
9190
|
if (!canOpen(conversationId)) return {
|
|
9031
9191
|
canFork: false,
|
|
@@ -9100,23 +9260,40 @@ async function readSubtreeDetailVersion(conversationId) {
|
|
|
9100
9260
|
version: "0"
|
|
9101
9261
|
};
|
|
9102
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
|
+
}
|
|
9103
9272
|
/** Read the detail state that the ETag hashes and the report shows. */
|
|
9104
9273
|
async function readConversationDetailState(conversationId, viewer) {
|
|
9105
|
-
const
|
|
9106
|
-
|
|
9107
|
-
|
|
9108
|
-
|
|
9109
|
-
|
|
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),
|
|
9110
9280
|
viewer ? readConversationReadPosition(viewer, conversationId) : void 0,
|
|
9111
|
-
|
|
9281
|
+
readSlackAttachmentsVersion(getSqlExecutor(), conversationId)
|
|
9112
9282
|
]);
|
|
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");
|
|
9113
9289
|
return {
|
|
9114
|
-
access
|
|
9290
|
+
access,
|
|
9115
9291
|
agentTree,
|
|
9116
|
-
autoArchive,
|
|
9292
|
+
autoArchive: viewerRootState?.autoArchive,
|
|
9117
9293
|
forks,
|
|
9118
9294
|
readPosition,
|
|
9119
|
-
|
|
9295
|
+
transcriptVersion,
|
|
9296
|
+
viewerMarks: viewerRootState?.viewerMarks
|
|
9120
9297
|
};
|
|
9121
9298
|
}
|
|
9122
9299
|
/**
|
|
@@ -9180,6 +9357,8 @@ function projectConversationDetail(args) {
|
|
|
9180
9357
|
sidebarAnnotations: canExposePayload ? args.sidebarAnnotations : void 0,
|
|
9181
9358
|
...canExposePayload && args.brief ? { brief: args.brief } : void 0,
|
|
9182
9359
|
events: args.events,
|
|
9360
|
+
...args.appended ? { appended: true } : void 0,
|
|
9361
|
+
...args.appendCursor ? { appendCursor: args.appendCursor } : void 0,
|
|
9183
9362
|
...canExposePayload && args.participants.length > 0 ? {
|
|
9184
9363
|
authors: args.authors,
|
|
9185
9364
|
participants: args.participants
|
|
@@ -9210,14 +9389,40 @@ async function readConversationDetailFromSql(conversationId, options) {
|
|
|
9210
9389
|
const { access, readPosition } = state;
|
|
9211
9390
|
const canExposePayload = access?.canViewPrivateContent ?? false;
|
|
9212
9391
|
const executor = getSqlExecutor();
|
|
9213
|
-
const
|
|
9392
|
+
const isPurged = record.conversation.transcriptPurgedAtMs !== void 0;
|
|
9393
|
+
const after = options.after && !options.unreadPage && !isPurged ? decodeConversationCursor({
|
|
9394
|
+
conversationId,
|
|
9395
|
+
cursor: options.after
|
|
9396
|
+
}) : void 0;
|
|
9397
|
+
const afterSeq = after && after.transcript === state.transcriptVersion ? after.seq : void 0;
|
|
9398
|
+
const readPage = async () => {
|
|
9399
|
+
if (isPurged) return { events: [] };
|
|
9400
|
+
if (afterSeq !== void 0) {
|
|
9401
|
+
const newer = await readConversationEventPageAfter(executor, {
|
|
9402
|
+
afterSeq,
|
|
9403
|
+
canExposePayload,
|
|
9404
|
+
conversationId,
|
|
9405
|
+
limit: options.limit
|
|
9406
|
+
});
|
|
9407
|
+
if (newer.nextSeq === void 0) return {
|
|
9408
|
+
appended: true,
|
|
9409
|
+
events: newer.events
|
|
9410
|
+
};
|
|
9411
|
+
}
|
|
9412
|
+
return readConversationEventPage(executor, {
|
|
9413
|
+
canExposePayload,
|
|
9414
|
+
conversationId,
|
|
9415
|
+
latestTurns: options.latestTurns,
|
|
9416
|
+
limit: options.limit
|
|
9417
|
+
});
|
|
9418
|
+
};
|
|
9214
9419
|
const [annotations, automationTitleByConversation, auxiliaryCostsByConversation, briefVersion, firstHumanMessageTextByConversation, modelUsage, metricsByConversation, people, sourceTask, teamDomainByTeamId, page] = await Promise.all([
|
|
9215
9420
|
listConversationAnnotations(getDb(), conversationId),
|
|
9216
9421
|
readAutomationTitlesByConversationId([record.conversation]),
|
|
9217
9422
|
readConversationAuxiliaryCostsFromSql(getDb(), [conversationId]),
|
|
9218
9423
|
readLatestConversationBrief(getDb(), conversationId),
|
|
9219
9424
|
readFirstHumanMessageTexts(getDb(), [record.conversation]),
|
|
9220
|
-
|
|
9425
|
+
isPurged ? Promise.resolve([]) : readConversationModelUsageFromSql(executor, { conversationId }),
|
|
9221
9426
|
readConversationTreeMetricsFromSql(getDb(), [conversationId]),
|
|
9222
9427
|
readConversationAuthors(getDb(), conversationId),
|
|
9223
9428
|
readConversationSourceTask({
|
|
@@ -9225,21 +9430,19 @@ async function readConversationDetailFromSql(conversationId, options) {
|
|
|
9225
9430
|
...options.viewer ? { viewer: options.viewer } : void 0
|
|
9226
9431
|
}),
|
|
9227
9432
|
resolveSlackTeamDomains(record.conversation.location?.provider === "slack" ? [record.conversation.location.teamId] : []),
|
|
9228
|
-
|
|
9229
|
-
canExposePayload,
|
|
9230
|
-
conversationId,
|
|
9231
|
-
latestTurns: options.latestTurns,
|
|
9232
|
-
limit: options.limit
|
|
9233
|
-
}) : purgedPage
|
|
9433
|
+
readPage()
|
|
9234
9434
|
]);
|
|
9235
9435
|
const firstSeq = page.events[0]?.seq;
|
|
9236
9436
|
const unreadAfterSeq = readPosition !== void 0 && page.previousSeq !== void 0 && firstSeq !== void 0 && readPosition.lastReadSeq + 1 < firstSeq ? readPosition.lastReadSeq : void 0;
|
|
9237
9437
|
const brief = canExposePayload ? briefVersion?.content : void 0;
|
|
9238
9438
|
const [{ briefMentions, events }, unreadPage, sidebarAnnotations] = await Promise.all([
|
|
9239
|
-
|
|
9439
|
+
startSpan({
|
|
9440
|
+
name: "Attach conversation mentions",
|
|
9441
|
+
op: "function"
|
|
9442
|
+
}, () => attachConversationMentions(executor, conversationId, {
|
|
9240
9443
|
...brief ? { brief } : void 0,
|
|
9241
9444
|
events: page.events
|
|
9242
|
-
}),
|
|
9445
|
+
})),
|
|
9243
9446
|
options.unreadPage && unreadAfterSeq !== void 0 ? readConversationEventPageAround(executor, {
|
|
9244
9447
|
canExposePayload,
|
|
9245
9448
|
conversationId,
|
|
@@ -9252,12 +9455,19 @@ async function readConversationDetailFromSql(conversationId, options) {
|
|
|
9252
9455
|
})).catch(() => void 0) : void 0,
|
|
9253
9456
|
canExposePayload ? listConversationSidebarAnnotations([conversationId], /* @__PURE__ */ new Map([[conversationId, annotations]])).then((byConversation) => byConversation[conversationId]) : void 0
|
|
9254
9457
|
]);
|
|
9458
|
+
const appendedAfterSeq = page.appended ? afterSeq : void 0;
|
|
9255
9459
|
const metrics = metricsByConversation.get(conversationId);
|
|
9256
9460
|
const auxiliaryCosts = auxiliaryCostsByConversation.get(conversationId);
|
|
9257
9461
|
const childAgentTotals = childAgentTotalsReport(metrics, auxiliaryCosts);
|
|
9258
|
-
const
|
|
9462
|
+
const detail = {
|
|
9259
9463
|
...record,
|
|
9260
9464
|
access,
|
|
9465
|
+
...page.appended ? { appended: true } : void 0,
|
|
9466
|
+
...isPurged ? void 0 : { appendCursor: encodeConversationCursor({
|
|
9467
|
+
conversationId,
|
|
9468
|
+
seq: page.events.at(-1)?.seq ?? appendedAfterSeq ?? -1,
|
|
9469
|
+
transcript: state.transcriptVersion
|
|
9470
|
+
}) },
|
|
9261
9471
|
...state.viewerMarks,
|
|
9262
9472
|
automationTitle: automationTitleByConversation.get(conversationId),
|
|
9263
9473
|
annotations,
|
|
@@ -9283,7 +9493,11 @@ async function readConversationDetailFromSql(conversationId, options) {
|
|
|
9283
9493
|
...unreadAfterSeq === void 0 ? void 0 : { unreadAfterSeq },
|
|
9284
9494
|
...unreadPage ? { unreadPage } : void 0,
|
|
9285
9495
|
usage: metrics?.usage ?? record.usage ?? void 0
|
|
9286
|
-
}
|
|
9496
|
+
};
|
|
9497
|
+
const report = startSpan({
|
|
9498
|
+
name: "Project conversation detail",
|
|
9499
|
+
op: "function"
|
|
9500
|
+
}, () => projectConversationDetail(detail));
|
|
9287
9501
|
return {
|
|
9288
9502
|
...report,
|
|
9289
9503
|
...state.forks,
|
|
@@ -9305,7 +9519,11 @@ async function readConversationDetail(conversationId, options = {}) {
|
|
|
9305
9519
|
limit: 150
|
|
9306
9520
|
} : { limit: options.limit }
|
|
9307
9521
|
});
|
|
9308
|
-
|
|
9522
|
+
if (!report) return void 0;
|
|
9523
|
+
return startSpan({
|
|
9524
|
+
name: "Validate conversation detail",
|
|
9525
|
+
op: "function"
|
|
9526
|
+
}, () => conversationDetailReportSchema.parse(report));
|
|
9309
9527
|
}
|
|
9310
9528
|
// src/api/conversations/pin.ts
|
|
9311
9529
|
/**
|