@sentry/junior 0.272.0 → 0.274.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/dist/{adapter-BDYDi1F9.js → adapter-4qThDhgF.js} +1 -1
  2. package/dist/{admin-Dj7EFycG.js → admin-c7ASvs6x.js} +1 -1
  3. package/dist/{agent-runner-Cl6Usx2Y.js → agent-runner-CLHM48dh.js} +780 -396
  4. package/dist/api/schema.d.ts +1 -1
  5. package/dist/api/schema.js +5 -5
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +58 -575
  8. package/dist/{app-DjZblE2J.d.ts → app-BlmPpPoR.d.ts} +4 -9
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +673 -127
  11. package/dist/{assistant-reply-DN2w6JL_.js → assistant-reply-2IwdFWuQ.js} +1 -1
  12. package/dist/{automation-CV7g5h3A.js → automation-BGrd03QO.js} +1 -1
  13. package/dist/{briefs-PysAqnjV.js → briefs-C1-NOh8m.js} +4 -4
  14. package/dist/{catalog-runtime-BNeCWIaF.js → catalog-runtime-BnIJimKZ.js} +1 -1
  15. package/dist/cli/chat.js +15 -15
  16. package/dist/cli/check.js +3 -3
  17. package/dist/cli/init.js +1 -1
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +4 -4
  20. package/dist/cli/snapshot-create.js +4 -4
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +3 -3
  23. package/dist/{client-FRphcDWW.js → client-C0ZIxoDr.js} +63 -5
  24. package/dist/{reporting-schema-CZREhYc-.js → common-Eu6sx09c.js} +4 -1
  25. package/dist/{config-BUP9wjiR.js → config-DS-QLVSL.js} +6 -14
  26. package/dist/{connections-CesHau9u.js → connections-Djb6ANAh.js} +11 -11
  27. package/dist/{conversation-BtQzLoK8.js → conversation-BjTo9ZFL.js} +11 -1
  28. package/dist/{conversation-privacy-DiGvA9a3.js → conversation-privacy-3IMUZSHC.js} +1 -1
  29. package/dist/{credential-sync-D2odJC30.js → credential-sync-ig88EB_v.js} +15 -16
  30. package/dist/{db-BPLmOwXf.d.ts → db-BMZhoYKj.d.ts} +1 -1
  31. package/dist/{executor-DGDpyegI.js → executor-C2moGIHS.js} +2 -2
  32. package/dist/instrumentation.js +114 -3
  33. package/dist/{job-queue-CjB97sii.js → job-queue-Bh9sFO9t.js} +3 -3
  34. package/dist/{logging-CjkDr-jP.js → logging-DYRS7E8s.js} +14 -2
  35. package/dist/{media-U6Tuz6Mi.js → media-DstkkoNP.js} +21 -2
  36. package/dist/{message-D9y8PKA1.js → message-CicNrhCv.js} +9 -9
  37. package/dist/nitro.d.ts +1 -1
  38. package/dist/nitro.js +3 -3
  39. package/dist/{oauth-callback-server-02Pej6hj.js → oauth-callback-server-BXyrepfY.js} +2 -2
  40. package/dist/{credentialed-CgTulRDH.js → projection-CMRrv9Pt.js} +4595 -51
  41. package/dist/{prompt-vfceH0c-.js → prompt-JEWUUpLW.js} +1 -1
  42. package/dist/{registry-7XgwNgQe.js → registry-D92WLl5I.js} +2 -2
  43. package/dist/{resolve-CuuxNfWG.js → resolve-C-Dh14ps.js} +3 -3
  44. package/dist/{result-BRhb6iN1.js → result-DZ8TCQkd.js} +9 -9
  45. package/dist/{runner-DaWCofuS.js → runner-BBmhrQTM.js} +11 -11
  46. package/dist/{sandbox-egress-signals-Bn6FA1UC.js → sandbox-egress-signals-Cehpq6hC.js} +1 -1
  47. package/dist/{schema-D5VLF4NT.js → schema-CX9XGKCm.js} +18 -9
  48. package/dist/{schema-CNjAzYOw.d.ts → schema-DfdHlBnb.d.ts} +22 -2
  49. package/dist/{service-account-H45LIAG2.js → service-account-Bapo6l0R.js} +3 -3
  50. package/dist/{service-account-D9vrsi8d.js → service-account-Ce1465Fn.js} +3 -3
  51. package/dist/{session-stop-HKl0ECX0.js → session-stop-CI5qJU7a.js} +11 -11
  52. package/dist/{skills-CsiKu3-g.js → skills-D-d79XQ6.js} +2 -2
  53. package/dist/{spawn-DqjBxqWh.js → spawn-C_FETz5x.js} +2 -2
  54. package/dist/{list-JZUP1yog.js → stop-CmwFHwiN.js} +1003 -436
  55. package/dist/{store-DyVKH0QB.js → store-BIQYXvoV.js} +4 -4
  56. package/dist/{store-CPF2kzbu.js → store-BvI3yBGS.js} +3 -3
  57. package/dist/{task-queue-BbQXCcNX.js → task-queue-BdB0pab8.js} +4 -4
  58. package/dist/{task-runner-ChzW5E7R.js → task-runner-DQr2QfvJ.js} +7 -7
  59. package/dist/{thread-state-Ds8JTsX6.js → thread-state-ngCvtWNa.js} +4 -5
  60. package/dist/{turn-failure-response-DCMvjsA0.js → turn-failure-response-BDT3sT2v.js} +7 -8
  61. package/dist/{turn-lifecycle-DM_77q33.js → turn-lifecycle-B7O6rZEX.js} +1 -1
  62. package/dist/turn-session-routing-DIeqG2pO.js +1625 -0
  63. package/dist/{validation-DcGelbBi.js → validation-D3Xik64v.js} +1 -1
  64. package/dist/{version-C48azPKq.js → version-BoWLhNzj.js} +1 -1
  65. package/dist/version.js +1 -1
  66. package/dist/{viewer-BCRuO8Wg.js → viewer-D25XOUHc.js} +41 -20
  67. package/dist/{work-zxkmbJAp.js → work-D12-wcf4.js} +11 -39
  68. package/dist/{worker-CNNxHF1V.js → worker-DGxfDtES.js} +6 -6
  69. package/package.json +4 -4
  70. package/dist/turn-session-routing-BV_gX7n3.js +0 -6072
  71. package/dist/{oauth-relay-CTygMkNx.js → oauth-relay-C6ZAyJgf.js} +1 -1
@@ -1,45 +1,46 @@
1
- import { $t as appendThreadContextMessages, An as recordTurnSummary, Ar as trimTrailingAssistantMessages, At as loadProjection, Cn as loadTurnCheckpoint, Dn as failTurnRecord, En as completeTurnRecord, Et as commitMessages, Fr as buildDeterministicTurnId, Gt as hydrateConversationMessages, Jt as persistConversationMessageSummaries, Kt as persistConversationMessages, Lr as decideSubscribedThreadReply, Lt as recordAuthorizationCompleted, On as getTurnRecord, Ot as loadConversationProjection, Pr as buildDeterministicAssistantMessageId, Rr as getSubscribedReplyPreflightDecision, Tn as abandonTurnRecord, Tt as commitAcceptedReply, Vt as recordSubscribedReplyRoute, Wr as isExperimentalFeatureEnabled, Yr as piMessageFromHistoryItem, Yt as resolveConversationTitle, Zt as fallbackShortTitle, _ as markDispatchCompleted, a as confirmDispatchMailboxAppend, an as markConversationMessage, cn as turnHasReply, d as getDispatchTurnId, dn as PluginCredentialFailureError, en as buildConversationContext, fr as buildTurnErrorResponse, g as markDispatchBlocked, gr as persistWithRetry, h as markDispatchAwaitingResume, hn as AuthorizationFlowDisabledError, i as claimDispatchMailboxAppend, in as isHumanConversationMessage, j as readAutomationTitlesByConversationId, jt as loadTurnProjection, kn as listTurnSummaries, l as getDispatchInputMessageId, ln as upsertConversationMessage, n as resolveTurnSessionRouting, nn as estimateConversationContextTokens, on as normalizeConversationText, p as isTerminalDispatchStatus, qr as configValueSchema, rn as getConversationMessageSlackTs, s as getDispatchConversationId, sn as recordDeliveredAssistantMessage, t as resolveConversationRouting, tn as createConversationMemoryService, u as getDispatchRecord, v as markDispatchFailed, wn as saveTurnCheckpoint, xn as wasPendingAuthStopped, y as markDispatchRunning, yn as clearPendingAuth, zr as getThreadStopDecision } from "./turn-session-routing-BV_gX7n3.js";
2
- import { a as completeText, p as escapeXml, r as completeDecision, y as isProviderRetryError } from "./client-FRphcDWW.js";
3
- 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-BUP9wjiR.js";
4
- import { B as isRecord, E as withSpan, H as toOptionalString, S as setTags, T as withLogContext, V as toOptionalNumber, 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-CjkDr-jP.js";
1
+ import { $ as loadTurnCheckpoint, $a as configValueSchema, A as buildConversationContext, Aa as conversationNotArchivedForEmail, Bi as verifyTimerWatchCredentialSubject, Bn as closeReviewItem, Br as addReactionToMessage, Ca as createPluginLogger, D as fallbackShortTitle, Da as conversationArchivedForUser, Ea as conversationArchivedForEmail, F as markConversationMessage, Fa as readConversationEventPage, G as AuthorizationFlowDisabledError, Gi as getSlackClient, Ha as recordSlackAttachment, Hi as downloadPrivateSlackFile, Ht as buildTurnErrorResponse, I as normalizeConversationText, Ia as buildSentryConversationUrl, Ji as normalizeSlackConversationId, Ka as listConversationAnnotations, Kn as listReplyActionItems, Kt as persistWithRetry, L as recordDeliveredAssistantMessage, Lr as normalizeSlackStatusText, M as estimateConversationContextTokens, Ma as viewerConversationMembership, N as getConversationMessageSlackTs, Nn as getPlugins, Oa as conversationHasParticipantUser, P as isHumanConversationMessage, Pa as readLatestConversationBrief, Qn as canActOnReviewItem, R as turnHasReply, Ra as notInheritedByForkChild, S as persistConversationMessages, Sn as createUserTokenStore, T as resolveConversationTitle, Ta as conversationArchiveTimes, V as PluginCredentialFailureError, Va as readAttachmentVisionSummary, Vi as SlackActionError, Wi as getHeaderString, Wn as getReviewItem, Xa as lookupSlackUser, Xi as withSlackRetries, Y as clearPendingAuth, Yn as takeReviewItem, Z as wasPendingAuthStopped, Za as createPluginCache, _ as recordSubscribedReplyRoute, ar as reviewItemReaderForUser, at as listTurnSummaries, bn as isExperimentalFeatureEnabled, dn as buildDeterministicTurnId, ea as JUNIOR_THREAD_STATE_TTL_MS, er as canReadReviewItem, et as saveTurnCheckpoint, hn as getThreadStopDecision, i as loadConversationProjection, it as getTurnRecord, j as createConversationMemoryService, ja as conversationNotArchivedForUser, k as appendThreadContextMessages, ka as conversationIsMemberRoot, mn as getSubscribedReplyPreflightDecision, n as commitMessages, nt as completeTurnRecord, o as loadProjection, on as trimTrailingAssistantMessages, ot as recordTurnSummary, p as recordAuthorizationCompleted, pn as decideSubscribedThreadReply, qa as listConversationAnnotationsById, qi as isDmChannel, qr as removeReactionFromMessage, rt as failTurnRecord, s as loadTurnProjection, t as commitAcceptedReply, to as piMessageFromHistoryItem, tr as isOnlyAssignee, tt as abandonTurnRecord, un as buildDeterministicAssistantMessageId, w as persistConversationMessageSummaries, wa as readConversationAccessFromSql, wi as cancelSubscriptions, x as hydrateConversationMessages, z as upsertConversationMessage, za as getSlackFileId, zr as truncateStatusText } from "./projection-CMRrv9Pt.js";
2
+ import { a as completeText, b as isProviderRetryError, m as escapeXml, r as completeDecision } from "./client-C0ZIxoDr.js";
3
+ import { _ as normalizeSlackEmojiName, c as getSlackClientSecret, i as getChatConfig, l as getSlackSigningSecret, n as botConfig, o as getSlackBotToken, s as getSlackClientId, v as createS3AttachmentStorage } from "./config-DS-QLVSL.js";
4
+ import { E as withSpan, H as toOptionalNumber, S as setTags, T as withLogContext, U as toOptionalString, V 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-DYRS7E8s.js";
5
5
  import { i as getActiveSpan, r as continueTrace } from "./sentry-MDkYAVPV.js";
6
6
  import { i as defaultModelId, r as boundProfile, s as modelIdForProfile } from "./model-profile-B998sjVd.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-B4DYygOB.js";
8
- import { C as getSqlExecutor, E as loadConversationSlackTenantIds, H as parseSessionSource, M as resolveActorIdentityId, N as saveActorAvatar, S as getDb, T as withConversationEventLock, U as addAgentTurnUsage, Y as createSlackDestination, Z as requireSlackDestination, f as identityAvatarUrl, h as readUserAvatarUrls, k as locationFromRow, q as hasAgentTurnUsage, x as getConversationStore, y as getConversationEventStore } from "./viewer-BCRuO8Wg.js";
8
+ import { A as locationFromRow, C as getSqlExecutor, D as loadConversationSlackTenantIds, E as withConversationEventLock, J as hasAgentTurnUsage, N as resolveActorIdentityId, P as saveActorAvatar, Q as requireSlackDestination, S as getDb, U as parseSessionSource, W as addAgentTurnUsage, X as createSlackDestination, Y as resolveRootConversationId, f as identityAvatarUrl, h as readUserAvatarUrls, q as agentTurnUsageSchema, x as getConversationStore, y as getConversationEventStore } from "./viewer-D25XOUHc.js";
9
9
  import { c as juniorIdentities, d as juniorDestinations, l as juniorUsers, o as conversationReadColumns, s as juniorConversations } from "./agent-invocations-C1RNOCs8.js";
10
- import { C as juniorCodeChanges, _ as juniorConversationBriefs, b as juniorConversationEvents, h as juniorConversationParticipants } from "./executor-DGDpyegI.js";
11
- import { g as instructionProvenanceFor, m as contextProvenance, r as isVisionImageMediaType } from "./media-U6Tuz6Mi.js";
12
- import { d as actorLogContext, f as credentialContextForActor } from "./registry-7XgwNgQe.js";
13
- import { Ct as conversationSubtree, Dt as buildSteeringPiMessage, F as getConversationInfo, Ft as shouldEmitDevAgentTrace, L as listThreadReplies, M as readSlackRawMessageContext, N as resolveSlackChannelIdFromMessage, Ot as withoutSavedSteeringMessages, P as resolveSlackChannelIdFromThreadId, R as resolveDestinationVisibility, b as renderBlockText, ct as createConversationId, dt as resolveConversationDestination, gt as storeAttachment, i as buildAuthPauseResponse, j as parseSlackThreadId, jt as RetryableDeliveryError, k as runWithSlackInstallation, lt as recordWebConversationActivity, n as executeAgentRun, nt as deliverReviewItemChange, p as latestProgressStatus, r as createContextCompactor, t as createAgentRunner, ut as webActorFromEmail, wt as conversationSubtreeColumns, y as renderAttachmentText } from "./agent-runner-Cl6Usx2Y.js";
14
- import { An as normalizeSlackConversationId, Ar as lookupSlackUser, Cn as SlackActionError, Dn as getSlackClient, Dr as listConversationAnnotationsById, Dt as removeReactionFromMessage, E as listReplyActionItems, En as getHeaderString, F as isOnlyAssignee, In as JUNIOR_THREAD_STATE_TTL_MS, M as canActOnReviewItem, Mn as withSlackRetries, P as canReadReviewItem, Sn as verifyTimerWatchCredentialSubject, Sr as recordSlackAttachment, _t as normalizeSlackStatusText, ar as createPluginLogger, b as closeReviewItem, bt as addReactionToMessage, cr as conversationArchivedForEmail, dr as conversationIsMemberRoot, fr as conversationNotArchivedForEmail, jr as createPluginCache, k as takeReviewItem, kn as isDmChannel, lr as conversationArchivedForUser, mr as viewerConversationMembership, n as createUserTokenStore, on as cancelSubscriptions, or as readConversationAccessFromSql, p as getPlugins, pr as conversationNotArchivedForUser, sr as conversationArchiveTimes, ur as conversationHasParticipantUser, w as getReviewItem, wn as downloadPrivateSlackFile, xr as readAttachmentVisionSummary, yr as getSlackFileId, yt as truncateStatusText, z as reviewItemReaderForUser } from "./credentialed-CgTulRDH.js";
10
+ import { C as juniorCodeChanges, _ as juniorConversationBriefs, b as juniorConversationEvents, h as juniorConversationParticipants, m as juniorConversationReadPositions } from "./executor-C2moGIHS.js";
11
+ import { g as instructionProvenanceFor, m as contextProvenance, r as isVisionImageMediaType } from "./media-DstkkoNP.js";
12
+ import { d as actorLogContext, f as credentialContextForActor } from "./registry-D92WLl5I.js";
13
+ import { A as runWithSlackInstallation, F as resolveSlackChannelIdFromThreadId, I as getConversationInfo, It as shouldEmitDevAgentTrace, J as readConversationSourceTask, M as parseSlackThreadId, Mt as RetryableDeliveryError, N as readSlackRawMessageContext, Ot as buildSteeringPiMessage, P as resolveSlackChannelIdFromMessage, R as listThreadReplies, Tt as conversationSubtreeColumns, _t as storeAttachment, a as buildAuthPauseResponse, b as renderAttachmentText, dt as webActorFromEmail, ft as resolveConversationDestination, i as measureTurnCompactionWait, kt as withoutSavedSteeringMessages, lt as createConversationId, m as latestProgressStatus, n as executeAgentRun, r as createContextCompactor, rt as deliverReviewItemChange, t as createAgentRunner, ut as recordWebConversationActivity, wt as conversationSubtree, x as renderBlockText, z as resolveDestinationVisibility } from "./agent-runner-CLHM48dh.js";
15
14
  import { a as withLock, n as MUTATION_LOCK_TTL_MS, r as acquireActiveLock } from "./locks-D-0h111u.js";
16
- import { r as getStateAdapter } from "./adapter-BDYDi1F9.js";
17
- import { G as readMessageAttachments, g as conversationFeedSchema } from "./conversation-BtQzLoK8.js";
18
- import { a as EVENT_SYSTEM_ACTOR, o as isEventConversationMessage } from "./prompt-vfceH0c-.js";
19
- import { $ as startActiveTurn, G as TurnInputDeferredError, H as ConversationTurnBoundaryError, J as isTurnInputCommitLostError, K as getConversationTurnBoundaryError, Q as markTurnFailed, U as CooperativeTurnYieldError, W as TurnInputCommitLostError, X as markTurnClosed, Y as isTurnInputDeferredError, Z as markTurnCompleted, q as isCooperativeTurnYieldError } from "./store-DyVKH0QB.js";
20
- import { n as getAssistantReplyText } from "./assistant-reply-DN2w6JL_.js";
21
- import { A as recordFinishedTurnForAutomatedLimit, D as sendSlackReply, E as resolveSlackReplyTarget, F as finishedRunReply, I as postsRunNotices, P as deliversFinalText, S as joinMailboxText, c as isEventMailboxMetadata, i as skipInputBeforeConversationStop, l as renderEventBatchText, s as eventBatchMessageEvents, u as timerWatchCredentialSubject, w as maybePostAutomatedTurnLimitNotice, z as runDispatchOutcome } from "./session-stop-HKl0ECX0.js";
15
+ import { r as getStateAdapter } from "./adapter-4qThDhgF.js";
16
+ import { G as readMessageAttachments, d as conversationDetailReportSchema, g as conversationFeedSchema } from "./conversation-BjTo9ZFL.js";
17
+ import { a as EVENT_SYSTEM_ACTOR, o as isEventConversationMessage } from "./prompt-JEWUUpLW.js";
18
+ import { $ as startActiveTurn, G as TurnInputDeferredError, H as ConversationTurnBoundaryError, J as isTurnInputCommitLostError, K as getConversationTurnBoundaryError, Q as markTurnFailed, U as CooperativeTurnYieldError, W as TurnInputCommitLostError, X as markTurnClosed, Y as isTurnInputDeferredError, Z as markTurnCompleted, m as getChildAgentLabel, q as isCooperativeTurnYieldError } from "./store-BIQYXvoV.js";
19
+ import { n as getAssistantReplyText } from "./assistant-reply-2IwdFWuQ.js";
20
+ import { A as recordFinishedTurnForAutomatedLimit, D as sendSlackReply, E as resolveSlackReplyTarget, F as finishedRunReply, I as postsRunNotices, P as deliversFinalText, S as joinMailboxText, c as isEventMailboxMetadata, i as skipInputBeforeConversationStop, l as renderEventBatchText, s as eventBatchMessageEvents, u as timerWatchCredentialSubject, w as maybePostAutomatedTurnLimitNotice, z as runDispatchOutcome } from "./session-stop-CI5qJU7a.js";
22
21
  import { _ as isEmptyUserInputAnswer, v as normalizeUserInputAnswer } from "./reporting-window-DgHgwQB3.js";
23
- import { a as getVercelConversationWorkQueue, f as getTurnRequestDeadline } from "./job-queue-CjB97sii.js";
24
- import { D as stopConversationWork, g as getConversationWorkState, h as getConversation, m as ensureConversationWake, r as appendAndEnqueueInboundMessage, w as requestConversationWork } from "./store-CPF2kzbu.js";
25
- import { t as healthReportSchema } from "./reporting-schema-CZREhYc-.js";
26
- 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-BRhb6iN1.js";
27
- import { n as getTurnLifecycle, t as ConversationTurnLifecycleService } from "./turn-lifecycle-DM_77q33.js";
28
- import { a as AgentRunError, o as executeTurn } from "./work-zxkmbJAp.js";
29
- import { a as persistThreadStateById, i as persistThreadRuntimeState, n as getPersistedSandboxState, o as coerceThreadConversationState, r as getPersistedThreadState, t as getLocationConfigurationService } from "./thread-state-Ds8JTsX6.js";
30
- import { c as deleteWebAuthorization, d as createPausedTurns, f as getPausedTurnRequest, h as getTurnAuthorization, m as wakePausedTurn, s as createWebAuthorization } from "./connections-CesHau9u.js";
31
- import { t as bindMessageAgent } from "./message-D9y8PKA1.js";
32
- import { t as bindSpawnAgent } from "./spawn-DqjBxqWh.js";
33
- import { n as scheduleSessionCompletedPluginTasks, t as processPluginTask } from "./task-runner-ChzW5E7R.js";
34
- 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-DCMvjsA0.js";
22
+ import { a as getVercelConversationWorkQueue, f as getTurnRequestDeadline } from "./job-queue-Bh9sFO9t.js";
23
+ import { D as stopConversationWork, g as getConversationWorkState, h as getConversation, m as ensureConversationWake, r as appendAndEnqueueInboundMessage, w as requestConversationWork } from "./store-BvI3yBGS.js";
24
+ 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-DIeqG2pO.js";
25
+ import { n as healthReportSchema, t as apiErrorSchema } from "./common-Eu6sx09c.js";
26
+ 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-DZ8TCQkd.js";
27
+ import { n as getTurnLifecycle, t as ConversationTurnLifecycleService } from "./turn-lifecycle-B7O6rZEX.js";
28
+ import { a as AgentRunError, o as executeTurn } from "./work-D12-wcf4.js";
29
+ import { a as persistThreadStateById, i as persistThreadRuntimeState, n as getPersistedSandboxState, o as coerceThreadConversationState, r as getPersistedThreadState, t as getLocationConfigurationService } from "./thread-state-ngCvtWNa.js";
30
+ import { c as deleteWebAuthorization, d as createPausedTurns, f as getPausedTurnRequest, h as getTurnAuthorization, m as wakePausedTurn, s as createWebAuthorization } from "./connections-Djb6ANAh.js";
31
+ import { t as bindMessageAgent } from "./message-CicNrhCv.js";
32
+ import { t as bindSpawnAgent } from "./spawn-C_FETz5x.js";
33
+ import { n as scheduleSessionCompletedPluginTasks, t as processPluginTask } from "./task-runner-DQr2QfvJ.js";
34
+ 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-BDT3sT2v.js";
35
+ import { createHash, createHmac, timingSafeEqual } from "node:crypto";
35
36
  import { z } from "zod";
36
- import { createHash } from "node:crypto";
37
- import { and, asc, desc, eq, inArray, isNotNull, isNull, or, sql } from "drizzle-orm";
37
+ import { and, asc, desc, eq, inArray, isNotNull, isNull, max, or, sql } from "drizzle-orm";
38
38
  import { conversationSidebarAnnotationSchema, createSlackSource, objectTypeSchema } from "@sentry/junior-plugin-api";
39
39
  import { alias } from "drizzle-orm/pg-core";
40
40
  import { del, get, put } from "@vercel/blob";
41
41
  import { Message, ThreadImpl, stringifyMarkdown } from "chat";
42
42
  import { SlackFormatConverter, createSlackAdapter } from "@chat-adapter/slack";
43
+ import { HTTPException } from "hono/http-exception";
43
44
  // src/handlers/health.ts
44
45
  /** Build Junior's process health value for HTTP and reporting consumers. */
45
46
  function readHealthReport() {
@@ -931,11 +932,12 @@ function spanLinks({ sentryTrace }) {
931
932
  *
932
933
  * The span links to the other trace contexts and to the span that was active,
933
934
  * such as the worker span. Without a trace context, the span is a child of the
934
- * active span. A malformed trace context starts a new trace.
935
+ * active span. A malformed trace context starts a new trace. The span records
936
+ * how long the Turn waited on context compaction.
935
937
  */
936
938
  async function withTurnSpan(context, input, callback) {
937
939
  const [parent, ...others] = input?.traceContexts ?? [];
938
- if (!parent) return await withSpan("chat.turn", "chat.turn", context, callback);
940
+ if (!parent) return await withSpan("chat.turn", "chat.turn", context, (set) => measureTurnCompactionWait(set, () => callback(set)));
939
941
  const activeSpan = getActiveSpan();
940
942
  const links = [...others.flatMap(spanLinks), ...activeSpan ? [{ context: activeSpan.spanContext() }] : []];
941
943
  const { baggage, sentryTrace } = parent;
@@ -944,7 +946,7 @@ async function withTurnSpan(context, input, callback) {
944
946
  sentryTrace
945
947
  }, () => withSpan("chat.turn", "chat.turn", context, async (setSpanAttributes) => {
946
948
  getActiveSpan()?.addLinks(links);
947
- return await callback(setSpanAttributes);
949
+ return await measureTurnCompactionWait(setSpanAttributes, () => callback(setSpanAttributes));
948
950
  }));
949
951
  }
950
952
  /**
@@ -2265,7 +2267,6 @@ function getPendingRecords(work) {
2265
2267
  }
2266
2268
  /** Build the worker run function for queued Slack conversation work. */
2267
2269
  function createSlackConversationWorker(options) {
2268
- const crossActorMidRunMode = options.crossActorMidRunMode ?? botConfig.crossActorMidRunMode;
2269
2270
  return async (context) => {
2270
2271
  const adapter = options.getSlackAdapter();
2271
2272
  const actorLookup = options.lookupSlackUser ?? lookupSlackUser;
@@ -2352,7 +2353,7 @@ function createSlackConversationWorker(options) {
2352
2353
  adapter,
2353
2354
  record
2354
2355
  })
2355
- })).filter((candidate) => crossActorMidRunMode === "steer" || requireSlackAuthorId(candidate.message) === activeAuthorId || hasSteeringOverride(candidate.message.text));
2356
+ })).filter((candidate) => requireSlackAuthorId(candidate.message) === activeAuthorId);
2356
2357
  return candidates.length > 0 ? await accept(candidates) : [];
2357
2358
  });
2358
2359
  };
@@ -6772,6 +6773,139 @@ function createProductionConversationWorkOptions(options) {
6772
6773
  waitUntil: options.waitUntil
6773
6774
  });
6774
6775
  }
6776
+ // src/api/http.ts
6777
+ const NO_STORE_HEADERS = { "cache-control": "no-store" };
6778
+ /** Build response init that keeps personalized API payloads out of shared caches. */
6779
+ function noStoreInit(init) {
6780
+ if (!init) return { headers: NO_STORE_HEADERS };
6781
+ const headers = new Headers(init.headers);
6782
+ if (!headers.has("cache-control")) headers.set("cache-control", "no-store");
6783
+ return {
6784
+ ...init,
6785
+ headers
6786
+ };
6787
+ }
6788
+ /** Serialize a REST response only after it satisfies its declared schema. */
6789
+ function jsonResponse(schema, value, init) {
6790
+ return Response.json(schema.parse(value), noStoreInit(init));
6791
+ }
6792
+ /** Return an empty personalized API response with no-store caching. */
6793
+ function emptyResponse(status = 204) {
6794
+ return new Response(null, noStoreInit({ status }));
6795
+ }
6796
+ /** Stop a request with Junior's stable JSON error contract. */
6797
+ function throwApiError(status, message, cause) {
6798
+ throw new HTTPException(status, {
6799
+ ...cause === void 0 ? void 0 : { cause },
6800
+ message,
6801
+ res: jsonResponse(apiErrorSchema, { error: message }, { status })
6802
+ });
6803
+ }
6804
+ // src/api/conversations/archive.ts
6805
+ async function setViewerArchive(args) {
6806
+ const executor = getSqlExecutor();
6807
+ return await executor.transaction(async () => {
6808
+ const db = executor.db();
6809
+ const [root] = await db.select({ lastActivityAt: juniorConversations.lastActivityAt }).from(juniorConversations).where(eq(juniorConversations.conversationId, args.rootConversationId)).limit(1).for("update");
6810
+ if (!root) return { status: "missing" };
6811
+ if (args.archived) {
6812
+ if (root.lastActivityAt.getTime() !== Date.parse(args.lastSeenAt)) return { status: "conflict" };
6813
+ const archivedAt = /* @__PURE__ */ new Date();
6814
+ const lastMessageAt = new Date(args.lastSeenAt);
6815
+ await db.insert(juniorConversationParticipants).values({
6816
+ archivedAt,
6817
+ lastMessageAt,
6818
+ rootConversationId: args.rootConversationId,
6819
+ userId: args.userId
6820
+ }).onConflictDoUpdate({
6821
+ target: [juniorConversationParticipants.userId, juniorConversationParticipants.rootConversationId],
6822
+ set: {
6823
+ archivedAt,
6824
+ lastMessageAt: sql`greatest(${juniorConversationParticipants.lastMessageAt}, excluded.last_message_at)`
6825
+ }
6826
+ });
6827
+ return {
6828
+ archivedAt: archivedAt.toISOString(),
6829
+ status: "updated"
6830
+ };
6831
+ }
6832
+ await db.update(juniorConversationParticipants).set({ archivedAt: null }).where(and(eq(juniorConversationParticipants.userId, args.userId), eq(juniorConversationParticipants.rootConversationId, args.rootConversationId), isNotNull(juniorConversationParticipants.archivedAt)));
6833
+ return {
6834
+ archivedAt: null,
6835
+ status: "updated"
6836
+ };
6837
+ });
6838
+ }
6839
+ /** Read one viewer's archive timestamp for a conversation root. */
6840
+ async function readConversationArchivedAt(viewer, conversationId) {
6841
+ const rootConversationId = await resolveRootConversationId(getSqlExecutor(), conversationId);
6842
+ const [row] = await getDb().select({ archivedAt: juniorConversationParticipants.archivedAt }).from(juniorConversationParticipants).where(and(eq(juniorConversationParticipants.userId, viewer.id), eq(juniorConversationParticipants.rootConversationId, rootConversationId))).limit(1);
6843
+ return row?.archivedAt?.getTime();
6844
+ }
6845
+ /** Archive or restore one conversation for the signed-in viewer. */
6846
+ async function archiveConversation(viewer, conversationId, body) {
6847
+ if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(404, "Conversation not found.");
6848
+ const rootConversationId = await resolveRootConversationId(getSqlExecutor(), conversationId);
6849
+ const result = await setViewerArchive({
6850
+ archived: body.archived,
6851
+ lastSeenAt: body.lastSeenAt,
6852
+ rootConversationId,
6853
+ userId: viewer.id
6854
+ });
6855
+ if (result.status === "updated") return { archivedAt: result.archivedAt };
6856
+ if (result.status === "missing") throwApiError(404, "Conversation not found.");
6857
+ throwApiError(409, "Conversation received new activity.");
6858
+ }
6859
+ // src/chat/plugins/conversation-sidebar.ts
6860
+ /** Show native objects by default and let plugins select compact sidebar labels. */
6861
+ async function listConversationSidebarAnnotations(conversationIds, annotationsByConversation) {
6862
+ const candidates = new Set(conversationIds);
6863
+ const selected = {};
6864
+ const plugins = getPlugins();
6865
+ const customOwners = new Set(plugins.filter((plugin) => plugin.hooks?.conversationSidebar).map((plugin) => plugin.manifest.name));
6866
+ for (const conversationId of conversationIds) {
6867
+ const objects = (annotationsByConversation.get(conversationId) ?? []).flatMap((annotation) => {
6868
+ if (customOwners.has(annotation.plugin) || !annotation.objectType) return [];
6869
+ return [{
6870
+ key: annotation.key,
6871
+ label: annotation.label,
6872
+ objectType: annotation.objectType === "item" && annotation.kind === "object" && annotation.facts?.type === "deployment" ? "deployment" : annotation.objectType,
6873
+ status: annotation.status
6874
+ }];
6875
+ });
6876
+ if (objects.length) selected[conversationId] = objects;
6877
+ }
6878
+ for (const plugin of plugins) {
6879
+ const hook = plugin.hooks?.conversationSidebar;
6880
+ if (!hook) continue;
6881
+ const annotationsByConversationId = Object.fromEntries(conversationIds.flatMap((conversationId) => {
6882
+ const annotations = (annotationsByConversation.get(conversationId) ?? []).filter((annotation) => annotation.plugin === plugin.manifest.name);
6883
+ return annotations.length > 0 ? [[conversationId, annotations]] : [];
6884
+ }));
6885
+ try {
6886
+ const result = await hook({
6887
+ annotationsByConversationId,
6888
+ conversationIds,
6889
+ db: getDb(),
6890
+ log: createPluginLogger(plugin.manifest.name),
6891
+ plugin: { name: plugin.manifest.name },
6892
+ cache: createPluginCache(plugin.manifest.name)
6893
+ });
6894
+ for (const [conversationId, annotations] of Object.entries(result.annotationsByConversationId)) {
6895
+ if (!candidates.has(conversationId)) continue;
6896
+ const parsed = conversationSidebarAnnotationSchema.array().safeParse(annotations);
6897
+ if (!parsed.success || parsed.data.length === 0) continue;
6898
+ selected[conversationId] = [...selected[conversationId] ?? [], ...parsed.data];
6899
+ }
6900
+ } catch (error) {
6901
+ logWarn("plugin.conversation_sidebar.hook.failed", {
6902
+ "app.plugin.name": plugin.manifest.name,
6903
+ "exception.message": error instanceof Error ? error.message : String(error)
6904
+ });
6905
+ }
6906
+ }
6907
+ return selected;
6908
+ }
6775
6909
  // src/chat/slack/location-url.ts
6776
6910
  /** Parse a Slack workspace subdomain used in `https://{domain}.slack.com` URLs. */
6777
6911
  function parseSlackTeamDomain(value) {
@@ -6847,28 +6981,474 @@ async function fetchSlackTeamDomain(teamId) {
6847
6981
  return;
6848
6982
  }
6849
6983
  }
6850
- /** Resolve a workspace subdomain via `team.info`, cached by team id. */
6851
- async function resolveSlackTeamDomain(teamId) {
6852
- const parsedTeamId = parseSlackTeamId(teamId);
6853
- if (!parsedTeamId) return void 0;
6854
- const cached = readTeamDomainCache(parsedTeamId);
6855
- if (cached !== void 0) return cached ?? void 0;
6856
- const pending = teamDomainInflight.get(parsedTeamId);
6857
- if (pending) return pending;
6858
- const lookup = fetchSlackTeamDomain(parsedTeamId).finally(() => {
6859
- teamDomainInflight.delete(parsedTeamId);
6984
+ /** Resolve a workspace subdomain via `team.info`, cached by team id. */
6985
+ async function resolveSlackTeamDomain(teamId) {
6986
+ const parsedTeamId = parseSlackTeamId(teamId);
6987
+ if (!parsedTeamId) return void 0;
6988
+ const cached = readTeamDomainCache(parsedTeamId);
6989
+ if (cached !== void 0) return cached ?? void 0;
6990
+ const pending = teamDomainInflight.get(parsedTeamId);
6991
+ if (pending) return pending;
6992
+ const lookup = fetchSlackTeamDomain(parsedTeamId).finally(() => {
6993
+ teamDomainInflight.delete(parsedTeamId);
6994
+ });
6995
+ teamDomainInflight.set(parsedTeamId, lookup);
6996
+ return lookup;
6997
+ }
6998
+ /** Resolve workspace subdomains for the distinct team ids in one API response. */
6999
+ async function resolveSlackTeamDomains(teamIds) {
7000
+ const uniqueTeamIds = [...new Set([...teamIds].map((teamId) => parseSlackTeamId(teamId)).filter((teamId) => teamId !== void 0))];
7001
+ const resolved = await Promise.all(uniqueTeamIds.map(async (teamId) => {
7002
+ const domain = await resolveSlackTeamDomain(teamId);
7003
+ return domain ? [teamId, domain] : void 0;
7004
+ }));
7005
+ return new Map(resolved.filter((entry) => entry !== void 0));
7006
+ }
7007
+ // src/chat/conversations/fork.ts
7008
+ /** Event key of the agent note that follows the copied events in a fork. */
7009
+ const FORK_NOTE_KEY = "fork:note";
7010
+ const forkNote = alias(juniorConversationEvents, "fork_note");
7011
+ /**
7012
+ * SQL filter for event rows that a fork did not copy from its source. Usage
7013
+ * and cost reports use it, so copied model calls count only in the source.
7014
+ */
7015
+ function notCopiedByFork() {
7016
+ return sql`not exists (
7017
+ select 1 from ${juniorConversationEvents} as ${sql.identifier("fork_note")}
7018
+ where ${forkNote.conversationId} = ${juniorConversationEvents.conversationId}
7019
+ and ${forkNote.idempotencyKey} = ${FORK_NOTE_KEY}
7020
+ and ${forkNote.seq} > ${juniorConversationEvents.seq}
7021
+ )`;
7022
+ }
7023
+ /**
7024
+ * Events that hold credentials, approvals, provider connections, or plugin
7025
+ * state of the source actor. A fork does not copy them.
7026
+ */
7027
+ const UNCOPIED_EVENT_TYPES = /* @__PURE__ */ new Set([
7028
+ "authorization_completed",
7029
+ "authorization_requested",
7030
+ "compaction_prepared",
7031
+ "compaction_requested",
7032
+ "guardian_action_reviewed",
7033
+ "mcp_provider_connected",
7034
+ "mcp_provider_connected_unowned",
7035
+ "structured_event",
7036
+ "unknown"
7037
+ ]);
7038
+ const FORK_NOTE = "This Conversation is a fork. The earlier messages are copied from another Conversation. Sandbox files, active work, approvals, credentials, Watches, Automations, and the delivery location were not copied. Earlier file paths and runtime context belong to the source Conversation. Verify files in the current Sandbox before you use them.";
7039
+ /** An expected fork request failure, such as a reply without saved history. */
7040
+ var ConversationForkError = class extends Error {};
7041
+ /**
7042
+ * Create a new web root Conversation from the agent history of a source
7043
+ * Conversation, through one completed assistant reply.
7044
+ *
7045
+ * Retries with the same requester and key return the same Conversation.
7046
+ */
7047
+ async function forkConversation(input) {
7048
+ const conversationId = createConversationId({
7049
+ actorEmail: input.actorEmail,
7050
+ idempotencyKey: JSON.stringify([
7051
+ "fork",
7052
+ input.sourceConversationId,
7053
+ input.idempotencyKey
7054
+ ])
7055
+ });
7056
+ const executor = getSqlExecutor();
7057
+ const events = getConversationEventStore();
7058
+ const store = getConversationStore();
7059
+ return withConversationEventLock(executor, input.sourceConversationId, () => withConversationEventLock(executor, conversationId, async () => {
7060
+ if (await store.get({ conversationId })) return { conversationId };
7061
+ const source = await store.get({ conversationId: input.sourceConversationId });
7062
+ if (!source || source.transcriptPurgedAtMs !== void 0) throw new ConversationForkError("The source history is no longer available.");
7063
+ if (source.parentConversationId) throw new ConversationForkError("You cannot fork a child conversation.");
7064
+ const boundary = await events.loadByIdempotencyKey(input.sourceConversationId, `message:${input.messageId}:agent`);
7065
+ const reply = boundary?.data.type === "assistant_message" ? piMessageFromHistoryItem(boundary.data) : void 0;
7066
+ if (!boundary || reply?.role !== "assistant" || reply.stopReason !== "stop" || reply.content.some((part) => part.type === "toolCall")) throw new ConversationForkError("Choose a completed assistant reply with saved agent history.");
7067
+ const projection = await loadTurnProjection({
7068
+ conversationId: input.sourceConversationId,
7069
+ committedSeq: boundary.seq,
7070
+ includeTail: false
7071
+ });
7072
+ if (!projection?.messages.length) throw new ConversationForkError("The selected history is no longer available.");
7073
+ if (hasUnfinishedToolCalls(projection.messages)) throw new ConversationForkError("This history has unfinished tool calls. Choose another reply.");
7074
+ const nowMs = Date.now();
7075
+ await recordWebConversationActivity({
7076
+ actor: webActorFromEmail(input.actorEmail, { ...input.actorName ? { fullName: input.actorName } : void 0 }),
7077
+ conversationId,
7078
+ nowMs,
7079
+ rootVisibility: source.visibility === "public" ? "public" : "private"
7080
+ });
7081
+ await executor.db().update(juniorConversations).set({
7082
+ forkedFromConversationId: source.conversationId,
7083
+ title: source.title ? `Fork: ${source.title}` : "Forked conversation"
7084
+ }).where(eq(juniorConversations.conversationId, conversationId));
7085
+ await copyForkEvents({
7086
+ sourceConversationId: source.conversationId,
7087
+ conversationId,
7088
+ events: await events.loadHistory(source.conversationId),
7089
+ boundarySeq: boundary.seq,
7090
+ messageId: input.messageId
7091
+ });
7092
+ await events.append(conversationId, [{
7093
+ idempotencyKey: FORK_NOTE_KEY,
7094
+ createdAtMs: nowMs,
7095
+ data: {
7096
+ type: "user_message",
7097
+ provenance: contextProvenance,
7098
+ content: [{
7099
+ type: "text",
7100
+ text: FORK_NOTE
7101
+ }],
7102
+ timestamp: nowMs
7103
+ }
7104
+ }]);
7105
+ return { conversationId };
7106
+ }));
7107
+ }
7108
+ /**
7109
+ * Copy the source event rows through the selected reply. Copies keep their
7110
+ * sequence, author, timestamp, key, and payload, so the fork shows the same
7111
+ * transcript and event log, and seq references in compactions stay valid.
7112
+ * Later updates of copied Messages and the end of copied Turns are also
7113
+ * copied, so that no copied item stays open in the fork.
7114
+ */
7115
+ async function copyForkEvents(args) {
7116
+ const reply = args.events.find((event) => event.data.type === "message" && event.data.role === "assistant" && event.data.messageId === args.messageId);
7117
+ const cutoffSeq = Math.max(args.boundarySeq, reply?.seq ?? -1);
7118
+ const messageIds = /* @__PURE__ */ new Set();
7119
+ const turnIds = /* @__PURE__ */ new Set();
7120
+ const seqs = [];
7121
+ let historyVersion = 0;
7122
+ for (const event of args.events) {
7123
+ const data = event.data;
7124
+ if (UNCOPIED_EVENT_TYPES.has(data.type)) continue;
7125
+ if (event.idempotencyKey === FORK_NOTE_KEY) continue;
7126
+ if (event.seq <= cutoffSeq) {
7127
+ if (data.type === "message") messageIds.add(data.messageId);
7128
+ if (data.type === "turn_started") turnIds.add(data.turnId);
7129
+ historyVersion = Math.max(historyVersion, event.historyVersion);
7130
+ seqs.push(event.seq);
7131
+ } else if ((data.type === "message_updated" || data.type === "message_handled") && messageIds.has(data.messageId) || (data.type === "turn_completed" || data.type === "turn_failed") && turnIds.has(data.turnId)) seqs.push(event.seq);
7132
+ }
7133
+ if (!seqs.length) return;
7134
+ const e = juniorConversationEvents;
7135
+ await getSqlExecutor().db().execute(sql`insert into ${e} (${sql.join([
7136
+ e.conversationId,
7137
+ e.seq,
7138
+ e.historyVersion,
7139
+ e.schemaVersion,
7140
+ e.idempotencyKey,
7141
+ e.type,
7142
+ e.payload,
7143
+ e.actorIdentityId,
7144
+ e.createdAt
7145
+ ].map((column) => sql.identifier(column.name)), sql`, `)})
7146
+ select ${args.conversationId}, ${e.seq}, least(${e.historyVersion}, ${historyVersion}), ${e.schemaVersion}, ${e.idempotencyKey}, ${e.type}, ${e.payload}, ${e.actorIdentityId}, ${e.createdAt}
7147
+ from ${e}
7148
+ where ${e.conversationId} = ${args.sourceConversationId}
7149
+ and ${inArray(e.seq, seqs)}`);
7150
+ }
7151
+ function hasUnfinishedToolCalls(messages) {
7152
+ const pending = /* @__PURE__ */ new Set();
7153
+ for (const message of messages) if (message.role === "assistant") {
7154
+ for (const part of message.content) if (part.type === "toolCall") pending.add(part.id);
7155
+ } else if (message.role === "toolResult") pending.delete(message.toolCallId);
7156
+ return pending.size > 0;
7157
+ }
7158
+ // src/chat/pi/sql-model-usage.ts
7159
+ /** SQL reporting adapter for usage stored on assistant history events. */
7160
+ const message = sql`${juniorConversationEvents.payload}`;
7161
+ const usage$1 = sql`${message}->'usage'`;
7162
+ const cost = sql`${usage$1}->'cost'`;
7163
+ function nonnegativeNumber(source, field, fallbackField, floor = false) {
7164
+ const value = (name) => sql`case
7165
+ when jsonb_typeof(${source}->${name}) = 'number'
7166
+ and (${source}->>${name})::numeric >= 0
7167
+ then ${floor ? sql`floor((${source}->>${name})::numeric)` : sql`(${source}->>${name})::numeric`}
7168
+ end`;
7169
+ const primary = value(field);
7170
+ return fallbackField ? sql`coalesce(${primary}, ${value(fallbackField)})` : sql`${primary}`;
7171
+ }
7172
+ function token(field, fallbackField) {
7173
+ return nonnegativeNumber(usage$1, field, fallbackField, true);
7174
+ }
7175
+ function summed(value) {
7176
+ return sql`sum(${value})::double precision`;
7177
+ }
7178
+ function summedCost(value) {
7179
+ return sql`round(sum(${value}), 12)::double precision`;
7180
+ }
7181
+ function messageTotalTokens(args) {
7182
+ const { input, output, cacheRead, cacheWrite } = args;
7183
+ return sql`case
7184
+ when ${input} is not null
7185
+ or ${output} is not null
7186
+ or ${cacheRead} is not null
7187
+ or ${cacheWrite} is not null
7188
+ then coalesce(${input}, 0)
7189
+ + coalesce(${output}, 0)
7190
+ + coalesce(${cacheRead}, 0)
7191
+ + coalesce(${cacheWrite}, 0)
7192
+ else ${token("totalTokens")}
7193
+ end`;
7194
+ }
7195
+ function definedNumber(value) {
7196
+ return value === null ? void 0 : value;
7197
+ }
7198
+ function usageFromRow(row) {
7199
+ const components = {
7200
+ inputTokens: definedNumber(row.inputTokens),
7201
+ outputTokens: definedNumber(row.outputTokens),
7202
+ cachedInputTokens: definedNumber(row.cachedInputTokens),
7203
+ cacheCreationTokens: definedNumber(row.cacheCreationTokens)
7204
+ };
7205
+ const costFields = {
7206
+ input: definedNumber(row.costInput),
7207
+ output: definedNumber(row.costOutput),
7208
+ cacheRead: definedNumber(row.costCacheRead),
7209
+ cacheWrite: definedNumber(row.costCacheWrite),
7210
+ total: definedNumber(row.costTotal)
7211
+ };
7212
+ const definedCost = Object.fromEntries(Object.entries(costFields).filter(([, value]) => value !== void 0));
7213
+ const result = {
7214
+ ...Object.fromEntries(Object.entries(components).filter(([, value]) => value !== void 0)),
7215
+ ...row.reasoningTokens === null ? void 0 : { reasoningTokens: row.reasoningTokens },
7216
+ ...row.totalTokens === null ? void 0 : { totalTokens: row.totalTokens },
7217
+ ...Object.keys(definedCost).length > 0 ? { cost: definedCost } : void 0
7218
+ };
7219
+ return hasAgentTurnUsage(result) ? agentTurnUsageSchema.parse(result) : void 0;
7220
+ }
7221
+ /**
7222
+ * Aggregate real assistant calls by provider/model in SQL, for one
7223
+ * Conversation and all its child agents at any depth. Replayed history is not
7224
+ * another call; its tokens appear in the next call's input usage.
7225
+ */
7226
+ async function readConversationModelUsageFromSql(executor, options) {
7227
+ const modelId = sql`case
7228
+ when position('/' in coalesce(${message}->>'model', '')) > 0
7229
+ then ${message}->>'model'
7230
+ else concat(${message}->>'provider', '/', ${message}->>'model')
7231
+ end`;
7232
+ const inputTokens = token("input", "inputTokens");
7233
+ const outputTokens = token("output", "outputTokens");
7234
+ const cachedInputTokens = token("cacheRead", "cachedInputTokens");
7235
+ const cacheCreationTokens = token("cacheWrite", "cacheCreationTokens");
7236
+ return (await executor.db().select({
7237
+ modelId,
7238
+ inputTokens: summed(inputTokens),
7239
+ outputTokens: summed(outputTokens),
7240
+ cachedInputTokens: summed(cachedInputTokens),
7241
+ cacheCreationTokens: summed(cacheCreationTokens),
7242
+ reasoningTokens: summed(token("reasoning", "reasoningTokens")),
7243
+ totalTokens: summed(messageTotalTokens({
7244
+ input: inputTokens,
7245
+ output: outputTokens,
7246
+ cacheRead: cachedInputTokens,
7247
+ cacheWrite: cacheCreationTokens
7248
+ })),
7249
+ costInput: summedCost(nonnegativeNumber(cost, "input")),
7250
+ costOutput: summedCost(nonnegativeNumber(cost, "output")),
7251
+ costCacheRead: summedCost(nonnegativeNumber(cost, "cacheRead")),
7252
+ costCacheWrite: summedCost(nonnegativeNumber(cost, "cacheWrite")),
7253
+ costTotal: summedCost(nonnegativeNumber(cost, "total"))
7254
+ }).from(juniorConversationEvents).innerJoin(conversationSubtree([options.conversationId]), eq(conversationSubtreeColumns.conversationId, juniorConversationEvents.conversationId)).where(and(eq(juniorConversationEvents.type, "assistant_message"), notCopiedByFork(), notInheritedByForkChild(), sql`jsonb_typeof(${message}->'provider') = 'string'`, sql`jsonb_typeof(${message}->'model') = 'string'`, sql`coalesce(${message}->>'provider', '') <> ''`, sql`coalesce(${message}->>'model', '') <> ''`)).groupBy(modelId).orderBy(modelId)).flatMap((row) => {
7255
+ const modelUsage = usageFromRow(row);
7256
+ return modelUsage ? [{
7257
+ modelId: row.modelId,
7258
+ usage: modelUsage
7259
+ }] : [];
7260
+ });
7261
+ }
7262
+ // src/api/conversations/cursor.ts
7263
+ const CURSOR_CONTEXT = "junior-conversation-report-cursor";
7264
+ const conversationCursorPayloadSchema = z.object({
7265
+ conversationId: z.string().min(1),
7266
+ seq: z.number().int().min(-1),
7267
+ version: z.literal(1)
7268
+ }).strict();
7269
+ function cursorSecret() {
7270
+ const secret = process.env.JUNIOR_SECRET?.trim();
7271
+ if (!secret) throw new Error("Cannot sign conversation cursor without JUNIOR_SECRET");
7272
+ return secret;
7273
+ }
7274
+ /** Sign one encoded cursor with the domain-separated server secret. */
7275
+ function signature(payload) {
7276
+ return createHmac("sha256", cursorSecret()).update(`${CURSOR_CONTEXT}:${payload}`).digest("base64url");
7277
+ }
7278
+ /** Encode an authenticated, conversation-bound event position for an API cursor. */
7279
+ function encodeConversationCursor(payload) {
7280
+ const encoded = Buffer.from(JSON.stringify({
7281
+ ...payload,
7282
+ version: 1
7283
+ }), "utf8").toString("base64url");
7284
+ return `${encoded}.${signature(encoded)}`;
7285
+ }
7286
+ /** Decode an authenticated reporting cursor for the expected conversation. */
7287
+ function decodeConversationCursor(args) {
7288
+ const [encoded, actualSignature, extra] = args.cursor.split(".");
7289
+ if (!encoded || !actualSignature || extra !== void 0) return void 0;
7290
+ const expected = Buffer.from(signature(encoded));
7291
+ const actual = Buffer.from(actualSignature);
7292
+ if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) return;
7293
+ try {
7294
+ const parsed = conversationCursorPayloadSchema.parse(JSON.parse(Buffer.from(encoded, "base64url").toString("utf8")));
7295
+ if (parsed.conversationId !== args.conversationId) return;
7296
+ return { seq: parsed.seq };
7297
+ } catch {
7298
+ return;
7299
+ }
7300
+ }
7301
+ // src/api/conversations/first-message.ts
7302
+ /**
7303
+ * Read the text of the first human message for each untitled conversation.
7304
+ * Read-time titles use it while the generated title is still unset.
7305
+ */
7306
+ async function readFirstHumanMessageTexts(db, conversations) {
7307
+ const untitledIds = conversations.flatMap((conversation) => conversation.title ? [] : [conversation.conversationId]);
7308
+ if (untitledIds.length === 0) return /* @__PURE__ */ new Map();
7309
+ const text = sql`${juniorConversationEvents.payload}->>'text'`;
7310
+ const rows = await db.selectDistinctOn([juniorConversationEvents.conversationId], {
7311
+ conversationId: juniorConversationEvents.conversationId,
7312
+ text: text.as("text")
7313
+ }).from(juniorConversationEvents).where(and(inArray(juniorConversationEvents.conversationId, untitledIds), eq(juniorConversationEvents.type, "message"), sql`${juniorConversationEvents.payload}->>'role' = 'user'`, sql`coalesce(${juniorConversationEvents.payload}->'meta'->'author'->>'isBot', 'false') <> 'true'`, isNotNull(sql`nullif(btrim(${text}), '')`))).orderBy(juniorConversationEvents.conversationId, asc(juniorConversationEvents.createdAt), asc(juniorConversationEvents.seq));
7314
+ return new Map(rows.map((row) => [row.conversationId, row.text]));
7315
+ }
7316
+ // src/api/mentions.ts
7317
+ const SLACK_USER_MENTION_RE = /<@([UW][A-Z0-9]+)(?:\|[^<>]*)?>/g;
7318
+ function mentionedSlackUserIds(texts) {
7319
+ const ids = texts.flatMap((text) => text ? [...text.matchAll(SLACK_USER_MENTION_RE)].map((m) => m[1]) : []);
7320
+ return [...new Set(ids)];
7321
+ }
7322
+ /**
7323
+ * Resolve the people that each source mentions, in source order. Every API
7324
+ * that returns display text uses this, so the dashboard can show the same
7325
+ * names and People links everywhere. It does one identity query per Slack
7326
+ * workspace.
7327
+ */
7328
+ async function resolveMentions(executor, sources) {
7329
+ const idsBySource = sources.map((source) => mentionedSlackUserIds(source.texts));
7330
+ const idsByTenant = /* @__PURE__ */ new Map();
7331
+ sources.forEach((source, index) => {
7332
+ if (idsBySource[index].length === 0) return;
7333
+ const ids = idsByTenant.get(source.tenantId) ?? /* @__PURE__ */ new Set();
7334
+ for (const id of idsBySource[index]) ids.add(id);
7335
+ idsByTenant.set(source.tenantId, ids);
7336
+ });
7337
+ const peopleByTenant = new Map(await Promise.all([...idsByTenant].map(async ([tenantId, ids]) => [tenantId, await readMentionedPeople(executor, tenantId, [...ids])])));
7338
+ return sources.map((source, index) => {
7339
+ const people = peopleByTenant.get(source.tenantId);
7340
+ return idsBySource[index].flatMap((id) => {
7341
+ const person = people?.get(id);
7342
+ return person ? [person] : [];
7343
+ });
7344
+ });
7345
+ }
7346
+ /**
7347
+ * Read current names for mentioned Slack users. Known Junior identities come
7348
+ * first. The email is set only for a linked, verified Junior user, because
7349
+ * that email is the People profile route.
7350
+ */
7351
+ async function readMentionedPeople(executor, tenantId, userIds) {
7352
+ const rows = await executor.db().select({
7353
+ displayName: juniorIdentities.displayName,
7354
+ emailVerified: juniorIdentities.emailVerified,
7355
+ handle: juniorIdentities.handle,
7356
+ providerSubjectId: juniorIdentities.providerSubjectId,
7357
+ userDisplayName: juniorUsers.displayName,
7358
+ userEmail: juniorUsers.primaryEmail
7359
+ }).from(juniorIdentities).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(and(eq(juniorIdentities.provider, "slack"), inArray(juniorIdentities.providerSubjectId, userIds), tenantId ? eq(juniorIdentities.providerTenantId, tenantId) : void 0));
7360
+ const people = /* @__PURE__ */ new Map();
7361
+ for (const row of rows) {
7362
+ if (people.has(row.providerSubjectId)) continue;
7363
+ const fullName = row.userDisplayName?.trim() || row.displayName?.trim();
7364
+ const email = row.emailVerified ? row.userEmail?.trim() : void 0;
7365
+ people.set(row.providerSubjectId, {
7366
+ slackUserId: row.providerSubjectId,
7367
+ ...fullName ? { fullName } : void 0,
7368
+ ...row.handle ? { slackUserName: row.handle } : void 0,
7369
+ ...email ? { email } : void 0
7370
+ });
7371
+ }
7372
+ const unnamed = userIds.filter((id) => {
7373
+ const person = people.get(id);
7374
+ return !person?.fullName && !person?.slackUserName;
7375
+ });
7376
+ if (tenantId && unnamed.length > 0) {
7377
+ const profiles = await Promise.all(unnamed.map((id) => lookupSlackUser(tenantId, id)));
7378
+ unnamed.forEach((id, index) => {
7379
+ const profile = profiles[index];
7380
+ if (!profile?.fullName && !profile?.userName) return;
7381
+ people.set(id, {
7382
+ ...people.get(id),
7383
+ slackUserId: id,
7384
+ ...profile.fullName ? { fullName: profile.fullName } : void 0,
7385
+ ...profile.userName ? { slackUserName: profile.userName } : void 0
7386
+ });
7387
+ });
7388
+ }
7389
+ return people;
7390
+ }
7391
+ // src/api/conversations/mentions.ts
7392
+ /** Text in one event that the dashboard renders with mentions. */
7393
+ function eventMentionTexts(data) {
7394
+ switch (data.type) {
7395
+ case "message": return data.redacted ? [] : [
7396
+ data.text,
7397
+ data.trustedSummary,
7398
+ ...(data.events ?? []).map((event) => event.trustedSummary)
7399
+ ];
7400
+ case "assistant_message": return data.parts.map((part) => part.text);
7401
+ case "compaction":
7402
+ case "handoff": return [data.summary];
7403
+ case "structured_event": return [data.presentation.preview, ...(data.presentation.details ?? []).map((detail) => detail.description)];
7404
+ default: return [];
7405
+ }
7406
+ }
7407
+ function briefMentionTexts(brief) {
7408
+ return [
7409
+ brief.summary,
7410
+ brief.intent,
7411
+ brief.outcome.text,
7412
+ ...brief.decisions.flatMap((decision) => [decision.text, decision.by]),
7413
+ ...brief.openDecisions.flatMap((decision) => [decision.text, decision.owner]),
7414
+ ...brief.facts
7415
+ ];
7416
+ }
7417
+ function withMentions(value, mentions) {
7418
+ return mentions.length > 0 ? {
7419
+ ...value,
7420
+ mentions
7421
+ } : value;
7422
+ }
7423
+ /**
7424
+ * Attach the people that each event and the Brief of one conversation
7425
+ * mention, resolved at read time.
7426
+ */
7427
+ async function attachConversationMentions(executor, conversationId, content) {
7428
+ const tenantId = (await loadConversationSlackTenantIds(executor, [conversationId])).get(conversationId);
7429
+ const sources = content.events.map((event) => ({
7430
+ tenantId,
7431
+ texts: eventMentionTexts(event.data)
7432
+ }));
7433
+ if (content.brief) sources.push({
7434
+ tenantId,
7435
+ texts: briefMentionTexts(content.brief)
6860
7436
  });
6861
- teamDomainInflight.set(parsedTeamId, lookup);
6862
- return lookup;
7437
+ const mentions = await resolveMentions(executor, sources);
7438
+ return {
7439
+ briefMentions: content.brief ? mentions.at(-1) : [],
7440
+ events: content.events.map((event, index) => withMentions(event, mentions[index]))
7441
+ };
6863
7442
  }
6864
- /** Resolve workspace subdomains for the distinct team ids in one API response. */
6865
- async function resolveSlackTeamDomains(teamIds) {
6866
- const uniqueTeamIds = [...new Set([...teamIds].map((teamId) => parseSlackTeamId(teamId)).filter((teamId) => teamId !== void 0))];
6867
- const resolved = await Promise.all(uniqueTeamIds.map(async (teamId) => {
6868
- const domain = await resolveSlackTeamDomain(teamId);
6869
- return domain ? [teamId, domain] : void 0;
6870
- }));
6871
- return new Map(resolved.filter((entry) => entry !== void 0));
7443
+ /** Attach the people that each activity preview mentions, resolved at read time. */
7444
+ async function attachActivityPreviewMentions(executor, previews) {
7445
+ const entries = [...previews];
7446
+ const tenants = await loadConversationSlackTenantIds(executor, entries.map(([conversationId]) => conversationId));
7447
+ const mentions = await resolveMentions(executor, entries.map(([conversationId, preview]) => ({
7448
+ tenantId: tenants.get(conversationId),
7449
+ texts: [preview.text]
7450
+ })));
7451
+ return new Map(entries.map(([conversationId, preview], index) => [conversationId, withMentions(preview, mentions[index])]));
6872
7452
  }
6873
7453
  // src/api/conversations/shared.ts
6874
7454
  /** Format a Slack destination without exposing private channel names. */
@@ -7133,155 +7713,6 @@ function childAgentTotalsReport(metrics, auxiliaryCosts) {
7133
7713
  ...childAgents.usage ? { cumulativeUsage: childAgents.usage } : void 0
7134
7714
  };
7135
7715
  }
7136
- // src/chat/conversations/fork.ts
7137
- /** Event key of the agent note that follows the copied events in a fork. */
7138
- const FORK_NOTE_KEY = "fork:note";
7139
- const forkNote = alias(juniorConversationEvents, "fork_note");
7140
- /**
7141
- * SQL filter for event rows that a fork did not copy from its source. Usage
7142
- * and cost reports use it, so copied model calls count only in the source.
7143
- */
7144
- function notCopiedByFork() {
7145
- return sql`not exists (
7146
- select 1 from ${juniorConversationEvents} as ${sql.identifier("fork_note")}
7147
- where ${forkNote.conversationId} = ${juniorConversationEvents.conversationId}
7148
- and ${forkNote.idempotencyKey} = ${FORK_NOTE_KEY}
7149
- and ${forkNote.seq} > ${juniorConversationEvents.seq}
7150
- )`;
7151
- }
7152
- /**
7153
- * Events that hold credentials, approvals, provider connections, or plugin
7154
- * state of the source actor. A fork does not copy them.
7155
- */
7156
- const UNCOPIED_EVENT_TYPES = /* @__PURE__ */ new Set([
7157
- "authorization_completed",
7158
- "authorization_requested",
7159
- "guardian_action_reviewed",
7160
- "mcp_provider_connected",
7161
- "mcp_provider_connected_unowned",
7162
- "structured_event",
7163
- "unknown"
7164
- ]);
7165
- const FORK_NOTE = "This Conversation is a fork. The earlier messages are copied from another Conversation. Sandbox files, active work, approvals, credentials, Watches, Automations, and the delivery location were not copied. Earlier file paths and runtime context belong to the source Conversation. Verify files in the current Sandbox before you use them.";
7166
- /** An expected fork request failure, such as a reply without saved history. */
7167
- var ConversationForkError = class extends Error {};
7168
- /**
7169
- * Create a new web root Conversation from the agent history of a source
7170
- * Conversation, through one completed assistant reply.
7171
- *
7172
- * Retries with the same requester and key return the same Conversation.
7173
- */
7174
- async function forkConversation(input) {
7175
- const conversationId = createConversationId({
7176
- actorEmail: input.actorEmail,
7177
- idempotencyKey: JSON.stringify([
7178
- "fork",
7179
- input.sourceConversationId,
7180
- input.idempotencyKey
7181
- ])
7182
- });
7183
- const executor = getSqlExecutor();
7184
- const events = getConversationEventStore();
7185
- const store = getConversationStore();
7186
- return withConversationEventLock(executor, input.sourceConversationId, () => withConversationEventLock(executor, conversationId, async () => {
7187
- if (await store.get({ conversationId })) return { conversationId };
7188
- const source = await store.get({ conversationId: input.sourceConversationId });
7189
- if (!source || source.transcriptPurgedAtMs !== void 0) throw new ConversationForkError("The source history is no longer available.");
7190
- if (source.parentConversationId) throw new ConversationForkError("You cannot fork a child conversation.");
7191
- const boundary = await events.loadByIdempotencyKey(input.sourceConversationId, `message:${input.messageId}:agent`);
7192
- const reply = boundary?.data.type === "assistant_message" ? piMessageFromHistoryItem(boundary.data) : void 0;
7193
- if (!boundary || reply?.role !== "assistant" || reply.stopReason !== "stop" || reply.content.some((part) => part.type === "toolCall")) throw new ConversationForkError("Choose a completed assistant reply with saved agent history.");
7194
- const projection = await loadTurnProjection({
7195
- conversationId: input.sourceConversationId,
7196
- committedSeq: boundary.seq,
7197
- includeTail: false
7198
- });
7199
- if (!projection?.messages.length) throw new ConversationForkError("The selected history is no longer available.");
7200
- if (hasUnfinishedToolCalls(projection.messages)) throw new ConversationForkError("This history has unfinished tool calls. Choose another reply.");
7201
- const nowMs = Date.now();
7202
- await recordWebConversationActivity({
7203
- actor: webActorFromEmail(input.actorEmail, { ...input.actorName ? { fullName: input.actorName } : void 0 }),
7204
- conversationId,
7205
- nowMs,
7206
- rootVisibility: source.visibility === "public" ? "public" : "private"
7207
- });
7208
- await executor.db().update(juniorConversations).set({
7209
- forkedFromConversationId: source.conversationId,
7210
- title: source.title ? `Fork: ${source.title}` : "Forked conversation"
7211
- }).where(eq(juniorConversations.conversationId, conversationId));
7212
- await copyForkEvents({
7213
- sourceConversationId: source.conversationId,
7214
- conversationId,
7215
- events: await events.loadHistory(source.conversationId),
7216
- boundarySeq: boundary.seq,
7217
- messageId: input.messageId
7218
- });
7219
- await events.append(conversationId, [{
7220
- idempotencyKey: FORK_NOTE_KEY,
7221
- createdAtMs: nowMs,
7222
- data: {
7223
- type: "user_message",
7224
- provenance: contextProvenance,
7225
- content: [{
7226
- type: "text",
7227
- text: FORK_NOTE
7228
- }],
7229
- timestamp: nowMs
7230
- }
7231
- }]);
7232
- return { conversationId };
7233
- }));
7234
- }
7235
- /**
7236
- * Copy the source event rows through the selected reply. Copies keep their
7237
- * sequence, author, timestamp, key, and payload, so the fork shows the same
7238
- * transcript and event log, and seq references in compactions stay valid.
7239
- * Later updates of copied Messages and the end of copied Turns are also
7240
- * copied, so that no copied item stays open in the fork.
7241
- */
7242
- async function copyForkEvents(args) {
7243
- const reply = args.events.find((event) => event.data.type === "message" && event.data.role === "assistant" && event.data.messageId === args.messageId);
7244
- const cutoffSeq = Math.max(args.boundarySeq, reply?.seq ?? -1);
7245
- const messageIds = /* @__PURE__ */ new Set();
7246
- const turnIds = /* @__PURE__ */ new Set();
7247
- const seqs = [];
7248
- let historyVersion = 0;
7249
- for (const event of args.events) {
7250
- const data = event.data;
7251
- if (UNCOPIED_EVENT_TYPES.has(data.type)) continue;
7252
- if (event.idempotencyKey === FORK_NOTE_KEY) continue;
7253
- if (event.seq <= cutoffSeq) {
7254
- if (data.type === "message") messageIds.add(data.messageId);
7255
- if (data.type === "turn_started") turnIds.add(data.turnId);
7256
- historyVersion = Math.max(historyVersion, event.historyVersion);
7257
- seqs.push(event.seq);
7258
- } else if ((data.type === "message_updated" || data.type === "message_handled") && messageIds.has(data.messageId) || (data.type === "turn_completed" || data.type === "turn_failed") && turnIds.has(data.turnId)) seqs.push(event.seq);
7259
- }
7260
- if (!seqs.length) return;
7261
- const e = juniorConversationEvents;
7262
- await getSqlExecutor().db().execute(sql`insert into ${e} (${sql.join([
7263
- e.conversationId,
7264
- e.seq,
7265
- e.historyVersion,
7266
- e.schemaVersion,
7267
- e.idempotencyKey,
7268
- e.type,
7269
- e.payload,
7270
- e.actorIdentityId,
7271
- e.createdAt
7272
- ].map((column) => sql.identifier(column.name)), sql`, `)})
7273
- select ${args.conversationId}, ${e.seq}, least(${e.historyVersion}, ${historyVersion}), ${e.schemaVersion}, ${e.idempotencyKey}, ${e.type}, ${e.payload}, ${e.actorIdentityId}, ${e.createdAt}
7274
- from ${e}
7275
- where ${e.conversationId} = ${args.sourceConversationId}
7276
- and ${inArray(e.seq, seqs)}`);
7277
- }
7278
- function hasUnfinishedToolCalls(messages) {
7279
- const pending = /* @__PURE__ */ new Set();
7280
- for (const message of messages) if (message.role === "assistant") {
7281
- for (const part of message.content) if (part.type === "toolCall") pending.add(part.id);
7282
- } else if (message.role === "toolResult") pending.delete(message.toolCallId);
7283
- return pending.size > 0;
7284
- }
7285
7716
  // src/api/conversations/auxiliary-costs.ts
7286
7717
  function eventCost() {
7287
7718
  return sql`CASE
@@ -7331,66 +7762,16 @@ async function readConversationAuxiliaryCostsFromSql(db, conversationIds) {
7331
7762
  operations: []
7332
7763
  } };
7333
7764
  current.total.costUsd = addCostUsd(current.total.costUsd, row.costUsd);
7334
- if (row.childAgentCostUsd > 0) current.childAgentCostUsd = addCostUsd(current.childAgentCostUsd ?? 0, row.childAgentCostUsd);
7335
- current.total.operations.push({
7336
- costUsd: row.costUsd,
7337
- events: row.events,
7338
- name: row.name,
7339
- namespace: row.namespace
7340
- });
7341
- result.set(row.conversationId, current);
7342
- }
7343
- return result;
7344
- }
7345
- // src/chat/plugins/conversation-sidebar.ts
7346
- /** Show native objects by default and let plugins select compact sidebar labels. */
7347
- async function listConversationSidebarAnnotations(conversationIds, annotationsByConversation) {
7348
- const candidates = new Set(conversationIds);
7349
- const selected = {};
7350
- const plugins = getPlugins();
7351
- const customOwners = new Set(plugins.filter((plugin) => plugin.hooks?.conversationSidebar).map((plugin) => plugin.manifest.name));
7352
- for (const conversationId of conversationIds) {
7353
- const objects = (annotationsByConversation.get(conversationId) ?? []).flatMap((annotation) => {
7354
- if (customOwners.has(annotation.plugin) || !annotation.objectType) return [];
7355
- return [{
7356
- key: annotation.key,
7357
- label: annotation.label,
7358
- objectType: annotation.objectType === "item" && annotation.kind === "object" && annotation.facts?.type === "deployment" ? "deployment" : annotation.objectType,
7359
- status: annotation.status
7360
- }];
7361
- });
7362
- if (objects.length) selected[conversationId] = objects;
7363
- }
7364
- for (const plugin of plugins) {
7365
- const hook = plugin.hooks?.conversationSidebar;
7366
- if (!hook) continue;
7367
- const annotationsByConversationId = Object.fromEntries(conversationIds.flatMap((conversationId) => {
7368
- const annotations = (annotationsByConversation.get(conversationId) ?? []).filter((annotation) => annotation.plugin === plugin.manifest.name);
7369
- return annotations.length > 0 ? [[conversationId, annotations]] : [];
7370
- }));
7371
- try {
7372
- const result = await hook({
7373
- annotationsByConversationId,
7374
- conversationIds,
7375
- db: getDb(),
7376
- log: createPluginLogger(plugin.manifest.name),
7377
- plugin: { name: plugin.manifest.name },
7378
- cache: createPluginCache(plugin.manifest.name)
7379
- });
7380
- for (const [conversationId, annotations] of Object.entries(result.annotationsByConversationId)) {
7381
- if (!candidates.has(conversationId)) continue;
7382
- const parsed = conversationSidebarAnnotationSchema.array().safeParse(annotations);
7383
- if (!parsed.success || parsed.data.length === 0) continue;
7384
- selected[conversationId] = [...selected[conversationId] ?? [], ...parsed.data];
7385
- }
7386
- } catch (error) {
7387
- logWarn("plugin.conversation_sidebar.hook.failed", {
7388
- "app.plugin.name": plugin.manifest.name,
7389
- "exception.message": error instanceof Error ? error.message : String(error)
7390
- });
7391
- }
7765
+ if (row.childAgentCostUsd > 0) current.childAgentCostUsd = addCostUsd(current.childAgentCostUsd ?? 0, row.childAgentCostUsd);
7766
+ current.total.operations.push({
7767
+ costUsd: row.costUsd,
7768
+ events: row.events,
7769
+ name: row.name,
7770
+ namespace: row.namespace
7771
+ });
7772
+ result.set(row.conversationId, current);
7392
7773
  }
7393
- return selected;
7774
+ return result;
7394
7775
  }
7395
7776
  // src/chat/plugins/unfinished-work.ts
7396
7777
  /**
@@ -7505,158 +7886,6 @@ async function readConversationActivityPreviews(db, conversationIds) {
7505
7886
  text: row.text
7506
7887
  }]));
7507
7888
  }
7508
- // src/api/conversations/first-message.ts
7509
- /**
7510
- * Read the text of the first human message for each untitled conversation.
7511
- * Read-time titles use it while the generated title is still unset.
7512
- */
7513
- async function readFirstHumanMessageTexts(db, conversations) {
7514
- const untitledIds = conversations.flatMap((conversation) => conversation.title ? [] : [conversation.conversationId]);
7515
- if (untitledIds.length === 0) return /* @__PURE__ */ new Map();
7516
- const text = sql`${juniorConversationEvents.payload}->>'text'`;
7517
- const rows = await db.selectDistinctOn([juniorConversationEvents.conversationId], {
7518
- conversationId: juniorConversationEvents.conversationId,
7519
- text: text.as("text")
7520
- }).from(juniorConversationEvents).where(and(inArray(juniorConversationEvents.conversationId, untitledIds), eq(juniorConversationEvents.type, "message"), sql`${juniorConversationEvents.payload}->>'role' = 'user'`, sql`coalesce(${juniorConversationEvents.payload}->'meta'->'author'->>'isBot', 'false') <> 'true'`, isNotNull(sql`nullif(btrim(${text}), '')`))).orderBy(juniorConversationEvents.conversationId, asc(juniorConversationEvents.createdAt), asc(juniorConversationEvents.seq));
7521
- return new Map(rows.map((row) => [row.conversationId, row.text]));
7522
- }
7523
- // src/api/mentions.ts
7524
- const SLACK_USER_MENTION_RE = /<@([UW][A-Z0-9]+)(?:\|[^<>]*)?>/g;
7525
- function mentionedSlackUserIds(texts) {
7526
- const ids = texts.flatMap((text) => text ? [...text.matchAll(SLACK_USER_MENTION_RE)].map((m) => m[1]) : []);
7527
- return [...new Set(ids)];
7528
- }
7529
- /**
7530
- * Resolve the people that each source mentions, in source order. Every API
7531
- * that returns display text uses this, so the dashboard can show the same
7532
- * names and People links everywhere. It does one identity query per Slack
7533
- * workspace.
7534
- */
7535
- async function resolveMentions(executor, sources) {
7536
- const idsBySource = sources.map((source) => mentionedSlackUserIds(source.texts));
7537
- const idsByTenant = /* @__PURE__ */ new Map();
7538
- sources.forEach((source, index) => {
7539
- if (idsBySource[index].length === 0) return;
7540
- const ids = idsByTenant.get(source.tenantId) ?? /* @__PURE__ */ new Set();
7541
- for (const id of idsBySource[index]) ids.add(id);
7542
- idsByTenant.set(source.tenantId, ids);
7543
- });
7544
- const peopleByTenant = new Map(await Promise.all([...idsByTenant].map(async ([tenantId, ids]) => [tenantId, await readMentionedPeople(executor, tenantId, [...ids])])));
7545
- return sources.map((source, index) => {
7546
- const people = peopleByTenant.get(source.tenantId);
7547
- return idsBySource[index].flatMap((id) => {
7548
- const person = people?.get(id);
7549
- return person ? [person] : [];
7550
- });
7551
- });
7552
- }
7553
- /**
7554
- * Read current names for mentioned Slack users. Known Junior identities come
7555
- * first. The email is set only for a linked, verified Junior user, because
7556
- * that email is the People profile route.
7557
- */
7558
- async function readMentionedPeople(executor, tenantId, userIds) {
7559
- const rows = await executor.db().select({
7560
- displayName: juniorIdentities.displayName,
7561
- emailVerified: juniorIdentities.emailVerified,
7562
- handle: juniorIdentities.handle,
7563
- providerSubjectId: juniorIdentities.providerSubjectId,
7564
- userDisplayName: juniorUsers.displayName,
7565
- userEmail: juniorUsers.primaryEmail
7566
- }).from(juniorIdentities).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(and(eq(juniorIdentities.provider, "slack"), inArray(juniorIdentities.providerSubjectId, userIds), tenantId ? eq(juniorIdentities.providerTenantId, tenantId) : void 0));
7567
- const people = /* @__PURE__ */ new Map();
7568
- for (const row of rows) {
7569
- if (people.has(row.providerSubjectId)) continue;
7570
- const fullName = row.userDisplayName?.trim() || row.displayName?.trim();
7571
- const email = row.emailVerified ? row.userEmail?.trim() : void 0;
7572
- people.set(row.providerSubjectId, {
7573
- slackUserId: row.providerSubjectId,
7574
- ...fullName ? { fullName } : void 0,
7575
- ...row.handle ? { slackUserName: row.handle } : void 0,
7576
- ...email ? { email } : void 0
7577
- });
7578
- }
7579
- const unnamed = userIds.filter((id) => {
7580
- const person = people.get(id);
7581
- return !person?.fullName && !person?.slackUserName;
7582
- });
7583
- if (tenantId && unnamed.length > 0) {
7584
- const profiles = await Promise.all(unnamed.map((id) => lookupSlackUser(tenantId, id)));
7585
- unnamed.forEach((id, index) => {
7586
- const profile = profiles[index];
7587
- if (!profile?.fullName && !profile?.userName) return;
7588
- people.set(id, {
7589
- ...people.get(id),
7590
- slackUserId: id,
7591
- ...profile.fullName ? { fullName: profile.fullName } : void 0,
7592
- ...profile.userName ? { slackUserName: profile.userName } : void 0
7593
- });
7594
- });
7595
- }
7596
- return people;
7597
- }
7598
- // src/api/conversations/mentions.ts
7599
- /** Text in one event that the dashboard renders with mentions. */
7600
- function eventMentionTexts(data) {
7601
- switch (data.type) {
7602
- case "message": return data.redacted ? [] : [
7603
- data.text,
7604
- data.trustedSummary,
7605
- ...(data.events ?? []).map((event) => event.trustedSummary)
7606
- ];
7607
- case "assistant_message": return data.parts.map((part) => part.text);
7608
- case "compaction":
7609
- case "handoff": return [data.summary];
7610
- case "structured_event": return [data.presentation.preview, ...(data.presentation.details ?? []).map((detail) => detail.description)];
7611
- default: return [];
7612
- }
7613
- }
7614
- function briefMentionTexts(brief) {
7615
- return [
7616
- brief.summary,
7617
- brief.intent,
7618
- brief.outcome.text,
7619
- ...brief.decisions.flatMap((decision) => [decision.text, decision.by]),
7620
- ...brief.openDecisions.flatMap((decision) => [decision.text, decision.owner]),
7621
- ...brief.facts
7622
- ];
7623
- }
7624
- function withMentions(value, mentions) {
7625
- return mentions.length > 0 ? {
7626
- ...value,
7627
- mentions
7628
- } : value;
7629
- }
7630
- /**
7631
- * Attach the people that each event and the Brief of one conversation
7632
- * mention, resolved at read time.
7633
- */
7634
- async function attachConversationMentions(executor, conversationId, content) {
7635
- const tenantId = (await loadConversationSlackTenantIds(executor, [conversationId])).get(conversationId);
7636
- const sources = content.events.map((event) => ({
7637
- tenantId,
7638
- texts: eventMentionTexts(event.data)
7639
- }));
7640
- if (content.brief) sources.push({
7641
- tenantId,
7642
- texts: briefMentionTexts(content.brief)
7643
- });
7644
- const mentions = await resolveMentions(executor, sources);
7645
- return {
7646
- briefMentions: content.brief ? mentions.at(-1) : [],
7647
- events: content.events.map((event, index) => withMentions(event, mentions[index]))
7648
- };
7649
- }
7650
- /** Attach the people that each activity preview mentions, resolved at read time. */
7651
- async function attachActivityPreviewMentions(executor, previews) {
7652
- const entries = [...previews];
7653
- const tenants = await loadConversationSlackTenantIds(executor, entries.map(([conversationId]) => conversationId));
7654
- const mentions = await resolveMentions(executor, entries.map(([conversationId, preview]) => ({
7655
- tenantId: tenants.get(conversationId),
7656
- texts: [preview.text]
7657
- })));
7658
- return new Map(entries.map(([conversationId, preview], index) => [conversationId, withMentions(preview, mentions[index])]));
7659
- }
7660
7889
  // src/api/conversations/participants.ts
7661
7890
  const identityColumns = {
7662
7891
  avatarUrl: juniorIdentities.avatarUrl,
@@ -7684,9 +7913,10 @@ function participantIdentity(row, userAvatarUrls) {
7684
7913
  };
7685
7914
  return Object.keys(participant).length > 0 ? participant : void 0;
7686
7915
  }
7687
- /** Read actor identities in first-appearance order for each Conversation. */
7688
- async function readConversationParticipants(db, conversationIds) {
7689
- if (conversationIds.length === 0) return /* @__PURE__ */ new Map();
7916
+ function participantKey(row) {
7917
+ return row.userId ? `user:${row.userId}` : `identity:${row.identityId}`;
7918
+ }
7919
+ async function readParticipantRows(db, conversationIds) {
7690
7920
  const [rootRows, eventRows] = await Promise.all([db.select({
7691
7921
  conversationId: juniorConversations.conversationId,
7692
7922
  ...identityColumns
@@ -7695,25 +7925,49 @@ async function readConversationParticipants(db, conversationIds) {
7695
7925
  seq: juniorConversationEvents.seq,
7696
7926
  ...identityColumns
7697
7927
  }).from(juniorConversationEvents).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversationEvents.actorIdentityId)).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).innerJoin(juniorConversations, eq(juniorConversations.conversationId, juniorConversationEvents.conversationId)).innerJoin(juniorConversationParticipants, and(eq(juniorConversationParticipants.userId, juniorIdentities.userId), eq(juniorConversationParticipants.rootConversationId, sql`coalesce(${juniorConversations.rootConversationId}, ${juniorConversations.conversationId})`))).where(inArray(juniorConversationEvents.conversationId, [...conversationIds])).orderBy(asc(juniorConversationEvents.conversationId), asc(juniorConversationEvents.actorIdentityId), asc(juniorConversationEvents.seq))]);
7698
- const userAvatarUrls = await readUserAvatarUrls(db, [...rootRows, ...eventRows].flatMap((row) => row.userId ? [row.userId] : []));
7699
- const ordered = /* @__PURE__ */ new Map();
7700
- const add = (conversationId, row) => {
7928
+ return [...rootRows, ...eventRows.sort((left, right) => left.seq - right.seq)];
7929
+ }
7930
+ async function groupParticipants(db, rows) {
7931
+ const userAvatarUrls = await readUserAvatarUrls(db, rows.flatMap((row) => row.userId ? [row.userId] : []));
7932
+ const groups = /* @__PURE__ */ new Map();
7933
+ for (const row of rows) {
7701
7934
  const participant = participantIdentity(row, userAvatarUrls);
7702
- if (!participant) return;
7703
- const group = ordered.get(conversationId) ?? {
7704
- identities: [],
7705
- keys: /* @__PURE__ */ new Set()
7706
- };
7707
- const key = row.userId ? `user:${row.userId}` : `identity:${row.identityId}`;
7708
- if (!group.keys.has(key)) {
7709
- group.keys.add(key);
7710
- group.identities.push(participant);
7711
- }
7712
- ordered.set(conversationId, group);
7935
+ if (!participant) continue;
7936
+ const group = groups.get(row.conversationId) ?? /* @__PURE__ */ new Map();
7937
+ const key = participantKey(row);
7938
+ if (!group.has(key)) group.set(key, participant);
7939
+ groups.set(row.conversationId, group);
7940
+ }
7941
+ return groups;
7942
+ }
7943
+ /** Read actor identities in first-appearance order for each Conversation. */
7944
+ async function readConversationParticipants(db, conversationIds) {
7945
+ if (conversationIds.length === 0) return /* @__PURE__ */ new Map();
7946
+ const groups = await groupParticipants(db, await readParticipantRows(db, conversationIds));
7947
+ return new Map([...groups].map(([conversationId, group]) => [conversationId, [...group.values()]]));
7948
+ }
7949
+ /**
7950
+ * Read the participants of one Conversation, and each of them by each of
7951
+ * their Identity ids. A person is listed under every Identity of their
7952
+ * user, so a pending Message from another provider resolves too.
7953
+ */
7954
+ async function readConversationAuthors(db, conversationId) {
7955
+ const rows = await readParticipantRows(db, [conversationId]);
7956
+ const userIds = [...new Set(rows.flatMap((row) => row.userId ? [row.userId] : []))];
7957
+ const [groups, userIdentities] = await Promise.all([groupParticipants(db, rows), userIds.length > 0 ? db.select({
7958
+ identityId: juniorIdentities.id,
7959
+ userId: juniorIdentities.userId
7960
+ }).from(juniorIdentities).where(inArray(juniorIdentities.userId, userIds)) : []]);
7961
+ const group = groups.get(conversationId) ?? /* @__PURE__ */ new Map();
7962
+ const authors = {};
7963
+ for (const row of [...rows, ...userIdentities]) {
7964
+ const participant = group.get(participantKey(row));
7965
+ if (participant) authors[row.identityId] = participant;
7966
+ }
7967
+ return {
7968
+ authors,
7969
+ participants: [...group.values()]
7713
7970
  };
7714
- for (const row of rootRows) add(row.conversationId, row);
7715
- for (const row of eventRows.sort((left, right) => left.seq - right.seq)) add(row.conversationId, row);
7716
- return new Map([...ordered].map(([conversationId, group]) => [conversationId, group.identities]));
7717
7971
  }
7718
7972
  // src/api/conversations/list.ts
7719
7973
  const CONVERSATION_FEED_LIMIT = 50;
@@ -7928,4 +8182,317 @@ async function readConversationFeedFromSql(options = {}) {
7928
8182
  async function readConversationFeed(options = {}) {
7929
8183
  return conversationFeedSchema.parse(await readConversationFeedFromSql(options));
7930
8184
  }
7931
- export { stopSlackThread as A, actOnReviewItem as B, isAllowedSignInEmail as C, buildSlackInboundMessage as D, recordSkippedConversationMessage as E, bindMessageAuthorIdentityId as F, AGENT_DISPATCH_MAX_AGE_MS as G, readReviewItemForUser as H, startProcessingReaction as I, readHealthReport as J, enqueueAgentDispatch as K, stripLeadingBotMention as L, withNormalizedThreadId as M, stopConversationTurn as N, clearSlackPendingReactions as O, THREAD_OPTOUT_ACK as P, parseContent as R, isAllowedDomain as S, resolveAllowedDomains as T, reviewItemChange as U, closeReviewItemsAnsweredByReply as V, getAttachmentStorage as W, createProductionConversationWorkOptions as _, resolveMentions as a, createSlackWebApiStatusSender as b, readConversationAuxiliaryCostsFromSql as c, notCopiedByFork as d, childAgentTotalsReport as f, resolveSlackTeamDomains as g, conversationSummaryFromStoredConversation as h, attachConversationMentions as i, normalizeIncomingSlackThreadId as j, isSlackMessageStopped as k, ConversationForkError as l, conversationEventHistory as m, readConversationRecordFromSql as n, readFirstHumanMessageTexts as o, readConversationTreeMetricsFromSql as p, GET as q, readConversationParticipants as r, listConversationSidebarAnnotations as s, readConversationFeed as t, forkConversation as u, createProductionSlackWebhookServices as v, readEnvList as w, assertNoLegacyAllowedDomains as x, getProductionSlackAdapter as y, ReviewItemActionError as z };
8185
+ // src/api/conversations/fork.ts
8186
+ /** Fork a Conversation that the viewer can read into a new root they own. */
8187
+ async function forkConversationForViewer(viewer, sourceConversationId, body) {
8188
+ if (!(await readConversationAccessFromSql(getDb(), [sourceConversationId], viewer)).get(sourceConversationId)?.canViewPrivateContent) throwApiError(403, "You do not have access to this conversation.");
8189
+ try {
8190
+ return await forkConversation({
8191
+ sourceConversationId,
8192
+ ...body,
8193
+ actorEmail: viewer.email,
8194
+ ...viewer.displayName ? { actorName: viewer.displayName } : void 0
8195
+ });
8196
+ } catch (error) {
8197
+ if (error instanceof ConversationForkError) throwApiError(409, error.message);
8198
+ throw error;
8199
+ }
8200
+ }
8201
+ /**
8202
+ * Read fork state for the viewer: whether they can fork, and the source and
8203
+ * fork links that they can open.
8204
+ */
8205
+ async function readConversationForks(conversationId, viewer) {
8206
+ const db = getDb();
8207
+ const [row] = await db.select({
8208
+ forkedFrom: juniorConversations.forkedFromConversationId,
8209
+ parent: juniorConversations.parentConversationId
8210
+ }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId));
8211
+ const forks = await db.select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).where(eq(juniorConversations.forkedFromConversationId, conversationId)).orderBy(asc(juniorConversations.createdAt)).limit(50);
8212
+ const forkedFrom = row?.forkedFrom ?? void 0;
8213
+ const ids = forks.map((fork) => fork.conversationId);
8214
+ const access = await readConversationAccessFromSql(db, [
8215
+ conversationId,
8216
+ ...ids,
8217
+ ...forkedFrom ? [forkedFrom] : []
8218
+ ], viewer);
8219
+ const canOpen = (id) => access.get(id)?.canViewPrivateContent;
8220
+ if (!canOpen(conversationId)) return {
8221
+ canFork: false,
8222
+ forks: []
8223
+ };
8224
+ const result = {
8225
+ canFork: !row?.parent,
8226
+ forks: ids.filter(canOpen)
8227
+ };
8228
+ if (forkedFrom && canOpen(forkedFrom)) {
8229
+ const [source] = await db.select({ title: juniorConversations.title }).from(juniorConversations).where(eq(juniorConversations.conversationId, forkedFrom));
8230
+ if (source) {
8231
+ result.forkedFromConversationId = forkedFrom;
8232
+ if (source.title) result.forkedFromTitle = source.title;
8233
+ }
8234
+ }
8235
+ return result;
8236
+ }
8237
+ // src/api/conversations/agent-tree.ts
8238
+ /** Bound the parent chain that one agent tree reads. */
8239
+ const MAX_AGENT_TREE_DEPTH = 16;
8240
+ const CHILD_LABEL = "Subagent";
8241
+ async function readParentConversationId(conversationId) {
8242
+ const [row] = await getDb().select({ parentId: juniorConversations.parentConversationId }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId));
8243
+ return row?.parentId ?? void 0;
8244
+ }
8245
+ /**
8246
+ * Read the agent tree of a child Conversation: its parent chain, root first,
8247
+ * with the child last. Returns undefined for a root Conversation. Each
8248
+ * Conversation has its own access check, so a viewer sees a label only where
8249
+ * they can see private content.
8250
+ */
8251
+ async function readConversationAgentTree(conversationId, viewer) {
8252
+ const ids = [conversationId];
8253
+ let parentId = await readParentConversationId(conversationId);
8254
+ while (parentId && !ids.includes(parentId) && ids.length < MAX_AGENT_TREE_DEPTH) {
8255
+ ids.unshift(parentId);
8256
+ parentId = await readParentConversationId(parentId);
8257
+ }
8258
+ if (ids.length < 2) return;
8259
+ const root = parentId ? void 0 : await getConversationStore().get({ conversationId: ids[0] });
8260
+ const [access, automationTitleByConversation, firstHumanMessageTextByConversation] = await Promise.all([
8261
+ readConversationAccessFromSql(getDb(), ids, viewer),
8262
+ readAutomationTitlesByConversationId(root ? [root] : []),
8263
+ readFirstHumanMessageTexts(getDb(), root ? [root] : [])
8264
+ ]);
8265
+ return await Promise.all(ids.map(async (id) => {
8266
+ const itemAccess = access.get(id);
8267
+ if (root?.conversationId === id) return {
8268
+ conversationId: id,
8269
+ label: conversationSummaryFromStoredConversation({
8270
+ access: itemAccess,
8271
+ automationTitle: automationTitleByConversation.get(id),
8272
+ conversation: root,
8273
+ durationMs: 0,
8274
+ firstHumanMessageText: firstHumanMessageTextByConversation.get(id)
8275
+ }).displayTitle
8276
+ };
8277
+ if (!itemAccess?.canViewPrivateContent) return {
8278
+ conversationId: id,
8279
+ label: CHILD_LABEL
8280
+ };
8281
+ const agent = await getChildAgentLabel(id);
8282
+ return {
8283
+ conversationId: id,
8284
+ label: agent?.title ?? agent?.agentName ?? CHILD_LABEL
8285
+ };
8286
+ }));
8287
+ }
8288
+ // src/api/conversations/read-position.ts
8289
+ /** Read how far the viewer has read one Conversation, if they have read it. */
8290
+ async function readConversationReadPosition(viewer, conversationId) {
8291
+ const [row] = await getDb().select({ lastReadSeq: juniorConversationReadPositions.lastReadSeq }).from(juniorConversationReadPositions).where(and(eq(juniorConversationReadPositions.userId, viewer.id), eq(juniorConversationReadPositions.conversationId, conversationId))).limit(1);
8292
+ return row;
8293
+ }
8294
+ /**
8295
+ * Move the viewer's read position forward.
8296
+ *
8297
+ * The stored value never goes back, so devices can report in any order. A
8298
+ * value past the last event is cut to the last event, so a bad client cannot
8299
+ * hide messages that arrive later.
8300
+ */
8301
+ async function markConversationRead(viewer, conversationId, body) {
8302
+ const db = getDb();
8303
+ const [conversation] = await db.select({ lastSeq: max(juniorConversationEvents.seq) }).from(juniorConversations).leftJoin(juniorConversationEvents, eq(juniorConversationEvents.conversationId, juniorConversations.conversationId)).where(eq(juniorConversations.conversationId, conversationId)).groupBy(juniorConversations.conversationId);
8304
+ if (!conversation) throwApiError(404, "Conversation not found.");
8305
+ const [row] = await db.insert(juniorConversationReadPositions).values({
8306
+ conversationId,
8307
+ lastReadSeq: Math.min(body.lastReadSeq, conversation.lastSeq ?? 0),
8308
+ updatedAt: /* @__PURE__ */ new Date(),
8309
+ userId: viewer.id
8310
+ }).onConflictDoUpdate({
8311
+ target: [juniorConversationReadPositions.userId, juniorConversationReadPositions.conversationId],
8312
+ set: {
8313
+ lastReadSeq: sql`greatest(${juniorConversationReadPositions.lastReadSeq}, excluded.last_read_seq)`,
8314
+ updatedAt: sql`excluded.updated_at`
8315
+ }
8316
+ }).returning({ lastReadSeq: juniorConversationReadPositions.lastReadSeq });
8317
+ return row;
8318
+ }
8319
+ // src/api/conversations/detail.ts
8320
+ /** Project stored metadata and a bounded event page into a signed history cursor. */
8321
+ function projectConversationDetail(args) {
8322
+ const { conversation } = args;
8323
+ const conversationId = conversation.conversationId;
8324
+ const transcriptPurgedAtMs = conversation.transcriptPurgedAtMs;
8325
+ const canExposePayload = args.access?.canViewPrivateContent ?? false;
8326
+ const modelUsage = transcriptPurgedAtMs === void 0 ? args.modelUsage : [];
8327
+ const sentryConversationUrl = buildSentryConversationUrl(conversationId);
8328
+ return {
8329
+ ...conversationSummaryFromStoredConversation({
8330
+ access: args.access,
8331
+ ...args.archivedAtMs === void 0 ? void 0 : { archivedAtMs: args.archivedAtMs },
8332
+ automationTitle: args.automationTitle,
8333
+ auxiliaryCosts: args.auxiliaryCosts,
8334
+ ...args.childAgentTotals ? { childAgentTotals: args.childAgentTotals } : void 0,
8335
+ conversation,
8336
+ durationMs: args.durationMs,
8337
+ firstHumanMessageText: args.firstHumanMessageText,
8338
+ ...args.locationId ? { locationId: args.locationId } : void 0,
8339
+ ...args.teamDomainByTeamId ? { teamDomainByTeamId: args.teamDomainByTeamId } : void 0,
8340
+ usage: args.usage
8341
+ }),
8342
+ annotations: canExposePayload ? args.annotations : [],
8343
+ sidebarAnnotations: canExposePayload ? args.sidebarAnnotations : void 0,
8344
+ ...canExposePayload && args.brief ? { brief: args.brief } : void 0,
8345
+ events: args.events,
8346
+ ...canExposePayload && args.participants.length > 0 ? {
8347
+ authors: args.authors,
8348
+ participants: args.participants
8349
+ } : void 0,
8350
+ ...args.previousSeq !== void 0 ? { previousCursor: encodeConversationCursor({
8351
+ conversationId,
8352
+ seq: args.previousSeq
8353
+ }) } : void 0,
8354
+ ...modelUsage.length > 0 ? { modelUsage } : void 0,
8355
+ eventHistory: conversationEventHistory({
8356
+ canExposePayload,
8357
+ ...transcriptPurgedAtMs === void 0 ? void 0 : { transcriptPurgedAtMs }
8358
+ }),
8359
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
8360
+ ...sentryConversationUrl ? { sentryConversationUrl } : void 0,
8361
+ ...args.sourceTask ? { sourceTask: args.sourceTask } : void 0
8362
+ };
8363
+ }
8364
+ async function readConversationDetailFromSql(conversationId, options) {
8365
+ const record = await readConversationRecordFromSql(conversationId);
8366
+ if (!record) return void 0;
8367
+ const archivedAtMs = options.viewer ? await readConversationArchivedAt(options.viewer, conversationId) : void 0;
8368
+ const executor = getSqlExecutor();
8369
+ const [accessByConversation, annotations, automationTitleByConversation, auxiliaryCostsByConversation, briefVersion, firstHumanMessageTextByConversation, modelUsage, metricsByConversation, people, sourceTask, teamDomainByTeamId] = await Promise.all([
8370
+ readConversationAccessFromSql(getDb(), [conversationId], options.viewer),
8371
+ listConversationAnnotations(getDb(), conversationId),
8372
+ readAutomationTitlesByConversationId([record.conversation]),
8373
+ readConversationAuxiliaryCostsFromSql(getDb(), [conversationId]),
8374
+ readLatestConversationBrief(getDb(), conversationId),
8375
+ readFirstHumanMessageTexts(getDb(), [record.conversation]),
8376
+ record.conversation.transcriptPurgedAtMs === void 0 ? readConversationModelUsageFromSql(executor, { conversationId }) : Promise.resolve([]),
8377
+ readConversationTreeMetricsFromSql(getDb(), [conversationId]),
8378
+ readConversationAuthors(getDb(), conversationId),
8379
+ readConversationSourceTask({
8380
+ conversationId,
8381
+ ...options.viewer ? { viewer: options.viewer } : void 0
8382
+ }),
8383
+ resolveSlackTeamDomains(record.conversation.location?.provider === "slack" ? [record.conversation.location.teamId] : [])
8384
+ ]);
8385
+ const access = accessByConversation.get(conversationId);
8386
+ const sidebarAnnotations = access?.canViewPrivateContent ? (await listConversationSidebarAnnotations([conversationId], /* @__PURE__ */ new Map([[conversationId, annotations]])))[conversationId] : void 0;
8387
+ const page = record.conversation.transcriptPurgedAtMs === void 0 ? await readConversationEventPage(executor, {
8388
+ canExposePayload: access?.canViewPrivateContent ?? false,
8389
+ conversationId,
8390
+ limit: options.limit
8391
+ }) : { events: [] };
8392
+ const brief = access?.canViewPrivateContent ? briefVersion?.content : void 0;
8393
+ const { briefMentions, events } = await attachConversationMentions(executor, conversationId, {
8394
+ ...brief ? { brief } : void 0,
8395
+ events: page.events
8396
+ });
8397
+ const metrics = metricsByConversation.get(conversationId);
8398
+ const auxiliaryCosts = auxiliaryCostsByConversation.get(conversationId);
8399
+ const childAgentTotals = childAgentTotalsReport(metrics, auxiliaryCosts);
8400
+ return projectConversationDetail({
8401
+ ...record,
8402
+ access,
8403
+ ...archivedAtMs === void 0 ? void 0 : { archivedAtMs },
8404
+ automationTitle: automationTitleByConversation.get(conversationId),
8405
+ annotations,
8406
+ sidebarAnnotations,
8407
+ auxiliaryCosts: auxiliaryCosts?.total,
8408
+ ...childAgentTotals ? { childAgentTotals } : void 0,
8409
+ ...briefVersion ? { brief: {
8410
+ content: briefVersion.content,
8411
+ ...briefMentions.length > 0 ? { mentions: briefMentions } : void 0,
8412
+ updatedAt: briefVersion.createdAt.toISOString(),
8413
+ version: briefVersion.version
8414
+ } } : void 0,
8415
+ durationMs: metrics?.durationMs ?? record.durationMs,
8416
+ events,
8417
+ firstHumanMessageText: firstHumanMessageTextByConversation.get(conversationId),
8418
+ modelUsage,
8419
+ authors: people.authors,
8420
+ participants: people.participants,
8421
+ ...sourceTask ? { sourceTask } : void 0,
8422
+ teamDomainByTeamId,
8423
+ ...page.previousSeq === void 0 ? void 0 : { previousSeq: page.previousSeq },
8424
+ usage: metrics?.usage ?? record.usage ?? void 0
8425
+ });
8426
+ }
8427
+ /** Load one conversation from its canonical event history. */
8428
+ async function readConversationDetail(conversationId, options = {}) {
8429
+ const report = await readConversationDetailFromSql(conversationId, {
8430
+ ...options,
8431
+ limit: options.limit ?? 500
8432
+ });
8433
+ if (!report) return void 0;
8434
+ const [forks, agentTree, readPosition] = await Promise.all([
8435
+ readConversationForks(conversationId, options.viewer),
8436
+ readConversationAgentTree(conversationId, options.viewer),
8437
+ options.viewer ? readConversationReadPosition(options.viewer, conversationId) : void 0
8438
+ ]);
8439
+ return conversationDetailReportSchema.parse({
8440
+ ...report,
8441
+ ...forks,
8442
+ ...agentTree ? { agentTree } : void 0,
8443
+ ...readPosition ? { readPosition } : void 0
8444
+ });
8445
+ }
8446
+ // src/api/conversations/stop.ts
8447
+ /**
8448
+ * Stop the active Turn for one conversation participant.
8449
+ *
8450
+ * The stop also removes the human messages queued before it. The viewer's own
8451
+ * web text comes back in the response so the dashboard can restore it to the
8452
+ * composer instead of losing it.
8453
+ */
8454
+ async function stopConversationTurnForViewer(viewer, conversationId, services) {
8455
+ const conversationStore = getConversationStore();
8456
+ if (!await conversationStore.get({ conversationId })) throwApiError(404, "Conversation not found.");
8457
+ if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(403, "Only conversation participants can stop this turn.");
8458
+ try {
8459
+ const result = await stopConversationTurn({
8460
+ conversationId,
8461
+ conversationStore,
8462
+ queue: services.queue
8463
+ });
8464
+ if (result.status === "no_work") return {
8465
+ conversationId,
8466
+ status: "no_work",
8467
+ stoppedInboundMessageIds: [],
8468
+ stoppedMessages: []
8469
+ };
8470
+ await clearSlackPendingReactions({
8471
+ getSlackAdapter: getProductionSlackAdapter,
8472
+ messages: result.pendingMessages
8473
+ });
8474
+ return {
8475
+ conversationId,
8476
+ status: "requested",
8477
+ stoppedInboundMessageIds: result.pendingMessages.map((message) => message.inboundMessageId),
8478
+ stoppedMessages: viewerWebMessages(result.pendingMessages, viewer)
8479
+ };
8480
+ } catch (error) {
8481
+ throwApiError(500, "Unable to stop the active turn.", error);
8482
+ }
8483
+ }
8484
+ function viewerWebMessages(messages, viewer) {
8485
+ const viewerUserId = webActorFromEmail(viewer.email).userId;
8486
+ return messages.flatMap((message) => {
8487
+ if (message.source !== "web") return [];
8488
+ const metadata = legacyWebMailboxMetadataSchema.safeParse(message.input.metadata);
8489
+ if (!metadata.success) return [];
8490
+ if (metadata.data.authorUserId !== viewerUserId) return [];
8491
+ const text = message.input.text.trim();
8492
+ return text ? [{
8493
+ inboundMessageId: message.inboundMessageId,
8494
+ text
8495
+ }] : [];
8496
+ });
8497
+ }
8498
+ export { recordSkippedConversationMessage as A, startProcessingReaction as B, getProductionSlackAdapter as C, isAllowedSignInEmail as D, isAllowedDomain as E, normalizeIncomingSlackThreadId as F, closeReviewItemsAnsweredByReply as G, parseContent as H, withNormalizedThreadId as I, getAttachmentStorage as J, readReviewItemForUser as K, stopConversationTurn as L, clearSlackPendingReactions as M, isSlackMessageStopped as N, readEnvList as O, stopSlackThread as P, readHealthReport as Q, THREAD_OPTOUT_ACK as R, createProductionSlackWebhookServices as S, assertNoLegacyAllowedDomains as T, ReviewItemActionError as U, stripLeadingBotMention as V, actOnReviewItem as W, enqueueAgentDispatch as X, AGENT_DISPATCH_MAX_AGE_MS as Y, GET as Z, archiveConversation as _, readConversationFeed as a, throwApiError as b, childAgentTotalsReport as c, conversationSummaryFromStoredConversation as d, attachConversationMentions as f, encodeConversationCursor as g, decodeConversationCursor as h, forkConversationForViewer as i, buildSlackInboundMessage as j, resolveAllowedDomains as k, readConversationTreeMetricsFromSql as l, readFirstHumanMessageTexts as m, readConversationDetail as n, readConversationRecordFromSql as o, resolveMentions as p, reviewItemChange as q, markConversationRead as r, readConversationAuxiliaryCostsFromSql as s, stopConversationTurnForViewer as t, conversationEventHistory as u, emptyResponse as v, createSlackWebApiStatusSender as w, createProductionConversationWorkOptions as x, jsonResponse as y, bindMessageAuthorIdentityId as z };