@sentry/junior 0.294.0 → 0.296.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 (79) hide show
  1. package/dist/{admin-vt8aSiCD.js → admin-z_lgDi-z.js} +2 -2
  2. package/dist/{agent-runner-DJu7w6mI.js → agent-runner-HoQiUKLL.js} +318 -199
  3. package/dist/api/schema.d.ts +2 -2
  4. package/dist/api/schema.js +5 -5
  5. package/dist/api.d.ts +1 -1
  6. package/dist/api.js +321 -331
  7. package/dist/{app--a5RLOrr.d.ts → app-C75Ft-A_.d.ts} +3 -3
  8. package/dist/app.d.ts +2 -2
  9. package/dist/app.js +33 -34
  10. package/dist/{automation-BM-OBsKW.js → automation-yJX3C7i3.js} +3 -3
  11. package/dist/{background-compaction-queue-D2j-0XkH.js → background-compaction-queue-Cre1wFt9.js} +7 -9
  12. package/dist/{briefs-JOAoCb6d.js → briefs-BXECHduJ.js} +3 -3
  13. package/dist/{catalog-runtime-CLMA9AXd.js → catalog-runtime-CpCmlD9L.js} +1 -1
  14. package/dist/cli/chat.d.ts +1 -1
  15. package/dist/cli/chat.js +15 -15
  16. package/dist/cli/check.js +3 -3
  17. package/dist/cli/init.js +2 -0
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.d.ts +1 -1
  20. package/dist/cli/plugins.js +4 -4
  21. package/dist/cli/snapshot-create.js +4 -4
  22. package/dist/cli/upgrade.d.ts +2 -2
  23. package/dist/cli/upgrade.js +3 -3
  24. package/dist/{config-mIZeGEWv.js → config-CCPHvTqx.js} +59 -2
  25. package/dist/{connections-XhdVg7OR.js → connections-B5pWh8e2.js} +6 -6
  26. package/dist/{conversation-CDWejM4R.js → conversation-CMkSmi02.js} +2 -11
  27. package/dist/{conversation-pending-messages-Dh2tfbaw.js → conversation-feed-BVAOga0H.js} +27 -2
  28. package/dist/{conversation-privacy-C6h-X2cZ.js → conversation-privacy-CZD5soDW.js} +1 -1
  29. package/dist/{credential-sync-zigBlXS3.js → credential-sync-DwLkIvXI.js} +16 -15
  30. package/dist/{db-DV5AbcGM.d.ts → db-B3iyr_Or.d.ts} +6 -1
  31. package/dist/{db--xuNV7g6.js → db-C1M1y-bh.js} +64 -26
  32. package/dist/{executor-BItuRqAR.js → executor-DUSEwXaO.js} +16 -5
  33. package/dist/instrumentation.js +19 -2
  34. package/dist/{logging-Cb6MGvdt.js → logging-D0svFM8r.js} +2 -1
  35. package/dist/{message-BTGgSmaH.js → message-BFnIwKpx.js} +9 -9
  36. package/dist/nitro.d.ts +2 -2
  37. package/dist/nitro.js +2 -2
  38. package/dist/{oauth-callback-server-Dvh1aOIi.js → oauth-callback-server-BXRtD6Fk.js} +2 -2
  39. package/dist/{oauth-relay-D6xxVywK.js → oauth-relay-CsfIazeF.js} +2 -1
  40. package/dist/{plugins-DtmjkTza.d.ts → plugins-B_0Cr0MO.d.ts} +0 -1
  41. package/dist/{projection-DLQgfO5N.js → projection-B6VS7kbo.js} +386 -108
  42. package/dist/{prompt-qp_LdxLX.js → prompt-CD11tfG8.js} +4 -4
  43. package/dist/{registry-MtwokaqW.js → registry-CHewwYEo.js} +3 -13
  44. package/dist/{resolve-BnJA0UNE.js → resolve-1owMH4qo.js} +3 -3
  45. package/dist/{result-ChL-1KyW.js → result-CEqQFrEf.js} +8 -8
  46. package/dist/{runner-BONN7Dp2.js → runner-BtWvJslp.js} +8 -8
  47. package/dist/{sandbox-egress-signals-nmlmI5Ab.js → sandbox-egress-signals-ByftwJVt.js} +1 -1
  48. package/dist/{schema-DgvcyJ1y.d.ts → schema-Ct1Zf2xy.d.ts} +66 -14
  49. package/dist/{schema-yr0ccDni.js → schema-D2iGyYIp.js} +24 -6
  50. package/dist/secrets-DebYU866.js +18 -0
  51. package/dist/{service-account-Bd0lBaGr.js → service-account-BZEuMKdo.js} +3 -3
  52. package/dist/{service-account-kio5nXSD.js → service-account-DLoeoHww.js} +42 -26
  53. package/dist/{session-stop-CeCXL3j9.js → session-stop-hYNTNpVf.js} +23 -778
  54. package/dist/{skills-e3DDNlKO.js → skills-DXgd5Inh.js} +3 -3
  55. package/dist/{spawn--cRxITWQ.js → spawn-YeqlNDv8.js} +5 -5
  56. package/dist/{adapter-DxLhJEnO.js → state-C3CbtD_m.js} +132 -2
  57. package/dist/{stop-Iai5N2PU.js → stop-Cze_pEL8.js} +351 -255
  58. package/dist/{store-C8LsaJwS.js → store-CZ9vqR4P.js} +3 -3
  59. package/dist/{task-runner-Dw7exu0-.js → task-runner-CMiNGsER.js} +275 -251
  60. package/dist/{turn-failure-response-BqTTx3XG.js → turn-failure-response-pXhZ2wMK.js} +12 -9
  61. package/dist/{validation-BrGahtnv.js → validation-Du7NdkOR.js} +1 -1
  62. package/dist/{version-Bdqhx8Qh.js → version-EN3Wnq-R.js} +1 -1
  63. package/dist/version.js +1 -1
  64. package/dist/{viewer-CjRFHR5U.js → viewer-Agxi_o5c.js} +3 -3
  65. package/dist/warmup-CY2ArYag.js +2017 -0
  66. package/dist/{work-BWBG1EGV.js → work-EA98F0ia.js} +11 -11
  67. package/dist/{worker-DAnBIVMs.js → worker-BALVdWbv.js} +6 -6
  68. package/migrations/0098_review_item_plugin_actions.sql +5 -0
  69. package/migrations/0099_conversation_last_message_at.sql +1 -0
  70. package/migrations/0100_automation_task_kind_repair.sql +48 -0
  71. package/migrations/0101_drop_legacy_columns.sql +12 -0
  72. package/migrations/meta/0098_snapshot.json +4490 -0
  73. package/migrations/meta/0099_snapshot.json +4720 -0
  74. package/migrations/meta/0100_snapshot.json +4496 -0
  75. package/migrations/meta/0101_snapshot.json +4496 -0
  76. package/migrations/meta/_journal.json +28 -0
  77. package/package.json +6 -5
  78. package/dist/assistant-reply-iTtEdDyc.js +0 -58
  79. package/dist/warmup-DuxCtzKC.js +0 -1039
@@ -1,35 +1,35 @@
1
1
  import { h as startSpan } from "./sentry-BRTJqumy.js";
2
- import { $ as loadTurnCheckpoint, $a as createConversationAccessReader, A as latestConversationMessageSeq, Ao as lookupSlackUser, Bi as normalizeSlackStatusText, Bn as getPlugins, D as estimateConversationMessagesTokens, Do as listConversationAnnotationsById, E as buildConversationContext, En as createUserTokenStore, Eo as listConversationAnnotations, F as turnHasReply, Gi as getSlackMessagePermalink, H as PluginCredentialFailureError, Hi as truncateStatusText, I as upsertConversationMessage, Io as piMessageFromHistoryItem, Jt as buildTurnErrorResponse, K as AuthorizationFlowDisabledError, Li as escapeSlackMrkdwnText, M as normalizeConversationText, Mo as createPluginCache, N as recordDeliveredAssistantMessage, Nt as moveIdleConversationDestination, O as getConversationMessageSlackTs, On as webActorUserIds, P as trimConversationMessages, Po as configValueSchema, Qa as canAddConversationMessages, Qt as persistWithRetry, Ri as formatSlackLink, Rt as releaseInboundMessage, S as resolveConversationTitle, So as slackAttachmentsVersionQuery, Ui as addReactionToMessage, Wi as deleteSlackMessage, X as clearPendingAuth, Xa as createPluginLogger, Xi as removeReactionFromMessage, Yi as postSlackMessage, _o as notInheritedByForkChild, a as loadProjection, aa as getHeaderString, ao as conversationViewerMarks, at as failTurnRecord, b as persistConversationMessages, bo as readAttachmentVisionSummary, br as isOnlyAssignee, ca as isDmChannel, ct as recordTurnSummary, d as recordAuthorizationCompleted, da as withSlackRetries, do as readConversationEventPageAfter, eo as readConversationAccessFromSql, et as lostWorkerBeforeFirstSave, fo as readConversationEventPageAround, gr as canActOnReviewItem, h as recordSubscribedReplyRoute, ho as buildSentryConversationUrl, i as loadConversationProjection, io as conversationPinnedForUser, it as completeTurnRecord, j as markConversationMessage, jo as lookupSlackUserNames, k as isHumanConversationMessage, la as normalizeSlackConversationId, lo as readLatestConversationBrief, lr as listReplyActionItems, mn as trimTrailingAssistantMessages, n as commitMessages, na as SlackActionError, no as conversationIsMemberRoot, nt as saveTurnCheckpoint, o as loadTurnProjection, oa as getSlackClient, oo as viewerMarksFromParticipant, ot as getTurnRecord, pr as takeReviewItem, ra as downloadPrivateSlackFile, ri as getDashboardConversationLink, ro as conversationIsNotUnsubscribedRoot, rr as closeReviewItem, rt as abandonTurnRecord, sr as getReviewItem, st as listTurnSummaries, t as commitAcceptedReply, to as conversationHasParticipantUser, tt as pauseLostWorkerTurn, uo as readConversationEventPage, ur as listWaitingConversations, v as hydrateConversationMessages, vo as getSlackFileId, w as fallbackShortTitle, wr as reviewItemNeedsSomeone, xo as recordSlackAttachment, y as persistConversationMessageWindow, yr as canUserReadReviewItem, zr as cancelSubscriptions } from "./projection-DLQgfO5N.js";
3
- import { A as estimateTextTokens, E as resolveGatewayModel, K as isProviderRetryError, L as escapeXml, c as getSlackClientSecret, i as getChatConfig, j as textCharsForTokens, l as getSlackSigningSecret, n as botConfig, o as getSlackBotToken, s as getSlackClientId, v as normalizeSlackEmojiName } from "./config-mIZeGEWv.js";
4
- import { E as withSpan, G as isRecord, K as toOptionalNumber, S as setTags, T as withLogContext, b as setSpanAttributes, f as logError, h as logWarn, m as logInfo, n as createChatSdkLogger, o as getActiveTraceContext, p as logException, q as toOptionalString, s as getActiveTraceId, t as buildTurnFailureResponse, y as setSentryUser } from "./logging-Cb6MGvdt.js";
5
- import { t as JUNIOR_VERSION } from "./version-Bdqhx8Qh.js";
2
+ import { $ as loadTurnCheckpoint, $a as createConversationAccessReader, A as latestConversationMessageSeq, Ao as lookupSlackUser, Bi as normalizeSlackStatusText, Bn as getPlugins, D as estimateConversationMessagesTokens, Do as listConversationAnnotationsById, E as buildConversationContext, En as createUserTokenStore, Eo as listConversationAnnotations, F as turnHasReply, Gi as getSlackMessagePermalink, H as PluginCredentialFailureError, Hi as truncateStatusText, I as upsertConversationMessage, Io as configValueSchema, Jt as buildTurnErrorResponse, K as AuthorizationFlowDisabledError, Li as escapeSlackMrkdwnText, M as normalizeConversationText, N as recordDeliveredAssistantMessage, Nt as moveIdleConversationDestination, O as getConversationMessageSlackTs, On as webActorUserIds, P as trimConversationMessages, Po as createPluginCache, Qa as canAddConversationMessages, Qt as persistWithRetry, Ri as formatSlackLink, Ro as piMessageFromHistoryItem, Rt as releaseInboundMessage, S as resolveConversationTitle, So as slackAttachmentsVersionQuery, Ui as addReactionToMessage, Wi as deleteSlackMessage, X as clearPendingAuth, Xa as createPluginLogger, Xi as removeReactionFromMessage, Yi as postSlackMessage, _o as notInheritedByForkChild, a as loadProjection, aa as getHeaderString, ao as conversationViewerMarks, at as failTurnRecord, b as persistConversationMessages, bo as readAttachmentVisionSummary, br as isOnlyAssignee, ca as isDmChannel, ct as recordTurnSummary, d as recordAuthorizationCompleted, da as withSlackRetries, do as readConversationEventPageAfter, eo as readConversationAccessFromSql, et as lostWorkerBeforeFirstSave, fo as readConversationEventPageAround, gr as canActOnReviewItem, h as recordSubscribedReplyRoute, ho as buildSentryConversationUrl, i as loadConversationProjection, io as conversationPinnedForUser, it as completeTurnRecord, j as markConversationMessage, jo as lookupSlackUserNames, k as isHumanConversationMessage, la as normalizeSlackConversationId, lo as readLatestConversationBrief, lr as listReplyActionItems, mn as trimTrailingAssistantMessages, n as commitMessages, na as SlackActionError, no as conversationIsMemberRoot, nt as saveTurnCheckpoint, o as loadTurnProjection, oa as getSlackClient, oo as viewerMarksFromParticipant, ot as getTurnRecord, pr as takeReviewItem, ra as downloadPrivateSlackFile, ri as getDashboardConversationLink, ro as conversationIsNotUnsubscribedRoot, rr as closeReviewItem, rt as abandonTurnRecord, sr as getReviewItem, st as listTurnSummaries, t as commitAcceptedReply, to as conversationHasParticipantUser, tt as pauseLostWorkerTurn, uo as readConversationEventPage, ur as listWaitingConversations, v as hydrateConversationMessages, vo as getSlackFileId, w as fallbackShortTitle, wr as reviewItemNeedsSomeone, xo as recordSlackAttachment, y as persistConversationMessageWindow, yr as canUserReadReviewItem, zr as cancelSubscriptions } from "./projection-B6VS7kbo.js";
3
+ import { A as estimateTextTokens, E as resolveGatewayModel, K as isProviderRetryError, L as escapeXml, c as getSlackClientSecret, i as getChatConfig, j as textCharsForTokens, l as getSlackSigningSecret, n as botConfig, o as getSlackBotToken, s as getSlackClientId, v as normalizeSlackEmojiName } from "./config-CCPHvTqx.js";
4
+ import { E as withSpan, G as isRecord, K as toOptionalNumber, S as setTags, T as withLogContext, b as setSpanAttributes, f as logError, h as logWarn, m as logInfo, n as createChatSdkLogger, o as getActiveTraceContext, p as logException, q as toOptionalString, s as getActiveTraceId, t as buildTurnFailureResponse, y as setSentryUser } from "./logging-D0svFM8r.js";
5
+ import { t as JUNIOR_VERSION } from "./version-EN3Wnq-R.js";
6
6
  import { f as parseSlackTeamId, h as parseSlackMessageTs, i as isActorUserId, n as createSlackActor, o as isUserActor, r as createSlackResumeActor, s as parseActorUserId, t as createActor, u as parseSlackChannelId } from "./actor-6jsm_v96.js";
7
- import { $ as nextDetailVersion, C as isTopLevelKind, D as locationFromRow, E as conversationKindFromRow, G as addAgentTurnUsage, H as claimProviderConversation, J as agentTurnUsageSchema, M as resolveActorIdentityId, N as saveActorAvatar, O as setFirstConversationLocation, U as getConversationIdByProviderConversation, W as parseSessionSource, X as resolveRootConversationId, Y as hasAgentTurnUsage, _ as setArchivedAt, a as getConversationStore, b as withConversationMutationLock, g as readConversationTrees, m as conversationAncestors, o as getDb, p as withConversationEventLock, r as getConversationEventStore, rt as requireSlackDestination, s as getSqlExecutor, tt as createSlackDestination, v as loadConversationSlackTenantIds, w as postsRunNotices, x as deliversFinalText } from "./db--xuNV7g6.js";
8
- import { A as juniorConversations, D as juniorCodeChanges, E as juniorConversationAnnotations, M as juniorUsers, N as juniorDestinations, _ as juniorConversationReadPositions, b as juniorConversationBriefs, j as juniorIdentities, l as juniorReviewItems, s as juniorReviewItemConversations, v as juniorConversationParticipants, w as juniorConversationEvents } from "./executor-BItuRqAR.js";
7
+ import { A as setFirstConversationLocation, C as deliversFinalText, E as postsRunNotices, F as saveActorAvatar, G as getConversationIdByProviderConversation, K as parseSessionSource, O as conversationKindFromRow, P as resolveActorIdentityId, Q as resolveRootConversationId, S as withConversationMutationLock, T as isTopLevelKind, W as claimProviderConversation, X as agentTurnUsageSchema, Z as hasAgentTurnUsage, _ as setArchivedAt, a as getConversationStore, at as requireSlackDestination, g as readConversationTrees, k as locationFromRow, m as conversationAncestors, o as getDb, p as withConversationEventLock, q as addAgentTurnUsage, r as getConversationEventStore, rt as createSlackDestination, s as getSqlExecutor, tt as nextDetailVersion, v as loadConversationSlackTenantIds, y as lastMessageAtSql } from "./db-C1M1y-bh.js";
8
+ import { A as juniorConversations, D as juniorCodeChanges, E as juniorConversationAnnotations, M as juniorUsers, N as juniorDestinations, _ as juniorConversationReadPositions, b as juniorConversationBriefs, j as juniorIdentities, l as juniorReviewItems, s as juniorReviewItemConversations, v as juniorConversationParticipants, w as juniorConversationEvents } from "./executor-DUSEwXaO.js";
9
9
  import { _ as instructionProvenanceFor, a as KNOWN_CONVERSATION_EVENT_TYPES, h as contextProvenance, i as isVisionImageMediaType, r as detectImageMediaType } from "./media-BepyEUNm.js";
10
- import { d as actorLogContext, f as credentialContextForActor } from "./registry-MtwokaqW.js";
11
- import { A as runWithSlackInstallation, At as cancelSignInWait, B as listThreadReplies, Bt as canShareTurn, Dt as stopChildAgentsOf, Et as stopChildAgentsBelow, F as resolveSlackChannelIdFromThreadId, Ft as getPausedTurnRequest, I as checkSlackChannelReadAccess, Jt as withTurnSpan, Kt as getTurnInputSpanAttributes, L as joinPublicChannelForRead, Lt as wakePausedTurn, M as parseSlackThreadId, N as readSlackRawMessageContext, Nt as supersedeTurnForInput, P as resolveSlackChannelIdFromMessage, Pt as createPausedTurns, R as getConversationInfo, Rt as getTurnAuthorization, S as createSlackReviewItemShow, St as markConversationRead, Tt as throwApiError, Ut as AgentRunError, V as resolveDestinationVisibility, Wt as executeTurn, X as readConversationSourceTask, Xt as getWebAuthorization, Zt as canPauseConversationDelivery, at as deliverReviewItemChange, b as renderAttachmentText, ct as acceptsWebMessages, dt as createAndEnqueueConversation, ft as createConversationId, gn as shouldEmitDevAgentTrace, ht as decodeInputImages, i as buildAuthPauseResponse, jt as createConversationTurnWorker, lt as appendAndEnqueueWebMessage, mt as webActorFromUser, n as executeAgentRun, on as listedConversation, p as latestProgressStatus, pn as RetryableDeliveryError, pt as recordWebConversationActivity, qt as turnInputTelemetry, t as createAgentRunner, x as renderBlockText, xt as conversationReadPositionQuery, yt as storeAttachment, zt as canJoinTurn } from "./agent-runner-DJu7w6mI.js";
12
- import { a as EVENT_SYSTEM_ACTOR, c as completeDecision, o as isEventConversationMessage, u as completeText } from "./prompt-qp_LdxLX.js";
10
+ import { d as actorLogContext, f as credentialContextForActor } from "./registry-CHewwYEo.js";
11
+ import { A as runWithSlackInstallation, At as cancelSignInWait, B as listThreadReplies, Bt as canShareTurn, Dt as stopChildAgentsOf, Et as stopChildAgentsBelow, F as resolveSlackChannelIdFromThreadId, Ft as getPausedTurnRequest, I as checkSlackChannelReadAccess, Jt as withTurnSpan, Kt as getTurnInputSpanAttributes, L as joinPublicChannelForRead, Lt as wakePausedTurn, M as parseSlackThreadId, N as readSlackRawMessageContext, Nt as supersedeTurnForInput, P as resolveSlackChannelIdFromMessage, Pt as createPausedTurns, R as getConversationInfo, Rt as getTurnAuthorization, S as createSlackReviewItemShow, St as markConversationRead, Tt as throwApiError, Ut as AgentRunError, V as resolveDestinationVisibility, Wt as executeTurn, X as readConversationSourceTask, Xt as getWebAuthorization, Zt as canPauseConversationDelivery, at as deliverReviewItemChange, b as renderAttachmentText, ct as acceptsWebMessages, dt as createAndEnqueueConversation, ft as createConversationId, gn as shouldEmitDevAgentTrace, ht as decodeInputImages, i as buildAuthPauseResponse, jt as createConversationTurnWorker, lt as appendAndEnqueueWebMessage, mt as webActorFromUser, n as executeAgentRun, on as listedConversation, p as latestProgressStatus, pn as RetryableDeliveryError, pt as recordWebConversationActivity, qt as turnInputTelemetry, t as createAgentRunner, x as renderBlockText, xt as conversationReadPositionQuery, yt as storeAttachment, zt as canJoinTurn } from "./agent-runner-HoQiUKLL.js";
12
+ import { a as EVENT_SYSTEM_ACTOR, c as completeDecision, o as isEventConversationMessage, u as completeText } from "./prompt-CD11tfG8.js";
13
13
  import { r as acquireActiveLock } from "./locks-D-0h111u.js";
14
- import { f as identityAvatarUrl, h as readUserAvatarUrls } from "./viewer-CjRFHR5U.js";
15
- import { a as setStateValues, i as getStateValues, r as getStateAdapter } from "./adapter-DxLhJEnO.js";
16
- import { W as readMessageAttachments, d as conversationEventPageSchema, l as conversationDetailReportSchema, m as conversationFeedSchema } from "./conversation-CDWejM4R.js";
17
- import { c as listConversationWork, l as readLastUserMessageAtByConversation, s as isConversationWorkDone } from "./warmup-DuxCtzKC.js";
18
- import { g as getVercelConversationWorkQueue, k as getTurnRequestDeadline } from "./background-compaction-queue-D2j-0XkH.js";
19
- import { a as persistAuthPauseTurnState, at as getConversationTurnBoundaryError, b as getChildAgentLabel, c as getTurnUserSlackMessageTs, ct as isTurnInputDeferredError, d as loadThreadContextTrimFloor, dt as markTurnFailed, ft as startActiveTurn, i as completeAuthPauseTurn, it as TurnInputDeferredError, l as buildDeliveredTurnStatePatch, lt as markTurnClosed, m as loadPendingMessageCards, mt as buildDeterministicTurnId, n as getAgentTurnDiagnosticsAttributes, nt as CooperativeTurnYieldError, o as getTurnUserMessage, ot as isCooperativeTurnYieldError, p as getTurnLifecycle, pt as buildDeterministicAssistantMessageId, r as requireTurnFailureEventId, rt as TurnInputCommitLostError, s as getTurnUserReplyAttachmentContext, st as isTurnInputCommitLostError, t as finalizeFailedTurnReplyWithEvent, tt as ConversationTurnBoundaryError, u as buildTurnThreadContext, ut as markTurnCompleted } from "./turn-failure-response-BqTTx3XG.js";
20
- import { n as getAssistantReplyText } from "./assistant-reply-iTtEdDyc.js";
21
- import { $ as withoutSavedSteeringMessages, B as maybePostAutomatedTurnLimitNotice, H as resolveSlackReplyTarget, K as recordFinishedTurnForAutomatedLimit, U as sendSlackReply, X as buildSteeringPiMessage, b as conversationSubtree, c as loadReviewItemInput, dt as finishedRunReply, g as resolveMailboxTurnWork, l as savedInputInstruction, mt as runDispatchOutcome, o as skipInputAfterConversationStop, r as markConversationsStopped, rt as isExperimentalFeatureEnabled, x as conversationSubtreeColumns, y as legacyWebMailboxMetadataSchema } from "./session-stop-CeCXL3j9.js";
14
+ import { f as identityAvatarUrl, h as readUserAvatarUrls } from "./viewer-Agxi_o5c.js";
15
+ import { a as getStateAdapter, o as getStateValues, s as setStateValues } from "./state-C3CbtD_m.js";
16
+ import { U as readMessageAttachments, d as conversationEventPageSchema, l as conversationDetailReportSchema } from "./conversation-CMkSmi02.js";
17
+ import { t as readJuniorSecret } from "./secrets-DebYU866.js";
18
+ import { T as getAssistantReplyText, c as listConversationWork, l as readLastUserMessageAtByConversation, s as isConversationWorkDone } from "./warmup-CY2ArYag.js";
19
+ import { g as getVercelConversationWorkQueue, k as getTurnRequestDeadline } from "./background-compaction-queue-Cre1wFt9.js";
20
+ import { a as persistAuthPauseTurnState, at as getConversationTurnBoundaryError, b as getChildAgentLabel, c as getTurnUserSlackMessageTs, ct as isTurnInputDeferredError, d as loadThreadContextTrimFloor, dt as markTurnFailed, ft as startActiveTurn, i as completeAuthPauseTurn, it as TurnInputDeferredError, l as buildDeliveredTurnStatePatch, lt as markTurnClosed, m as loadPendingMessageCards, mt as buildDeterministicTurnId, n as getAgentTurnDiagnosticsAttributes, nt as CooperativeTurnYieldError, o as getTurnUserMessage, ot as isCooperativeTurnYieldError, p as getTurnLifecycle, pt as buildDeterministicAssistantMessageId, r as requireTurnFailureEventId, rt as TurnInputCommitLostError, s as getTurnUserReplyAttachmentContext, st as isTurnInputCommitLostError, t as finalizeFailedTurnReplyWithEvent, tt as ConversationTurnBoundaryError, u as buildTurnThreadContext, ut as markTurnCompleted } from "./turn-failure-response-pXhZ2wMK.js";
21
+ import { $ as withoutSavedSteeringMessages, B as maybePostAutomatedTurnLimitNotice, H as resolveSlackReplyTarget, K as recordFinishedTurnForAutomatedLimit, U as sendSlackReply, X as buildSteeringPiMessage, b as conversationSubtree, c as loadReviewItemInput, g as resolveMailboxTurnWork, l as savedInputInstruction, o as skipInputAfterConversationStop, r as markConversationsStopped, rt as isExperimentalFeatureEnabled, x as conversationSubtreeColumns, y as legacyWebMailboxMetadataSchema } from "./session-stop-hYNTNpVf.js";
22
22
  import { b as normalizeUserInputAnswer, p as webMessageId, y as isEmptyUserInputAnswer } from "./reporting-window-B3Ze-Qnt.js";
23
- import { T as stopConversationWork, a as cancelHumanFacingPendingMessages, g as getConversationWorkState, h as getConversation, m as ensureConversationWake, r as appendAndEnqueueInboundMessage, s as claimInboundMessage, w as steerWebPendingMessages } from "./store-C8LsaJwS.js";
24
- import { _ as markDispatchBlocked, a as claimDispatchMailboxAppend, at as readAutomationTitlesByConversationId, b as markDispatchRunning, c as getDispatchConversationId, d as getDispatchRecord, dt as getLocationConfigurationService, f as getDispatchTurnId, ft as getPersistedSandboxState, g as markDispatchAwaitingResume, gt as coerceThreadConversationState, ht as persistThreadStateById, lt as resolveConversationRouting, m as isTerminalDispatchStatus, mt as persistThreadRuntimeState, n as scheduleSessionCompletedPluginTasks, o as confirmDispatchMailboxAppend, pt as getPersistedThreadState, u as getDispatchInputMessageId, ut as resolveTurnSessionRouting, v as markDispatchCompleted, y as markDispatchFailed } from "./task-runner-Dw7exu0-.js";
25
- import { d as healthReportSchema, s as conversationPendingMessagesReportSchema } from "./conversation-pending-messages-Dh2tfbaw.js";
26
- import { r as endActiveAgentInvocations, s as resolveThreadTurnWork } from "./work-BWBG1EGV.js";
27
- import { a as withAgentInvocationResultActors, n as enqueueAgentInvocationResult, t as createChildConversationWorker } from "./result-ChL-1KyW.js";
28
- import { t as bindMessageAgent } from "./message-BTGgSmaH.js";
29
- import { r as readConversationLineage, t as bindSpawnAgent } from "./spawn--cRxITWQ.js";
23
+ import { T as stopConversationWork, a as cancelHumanFacingPendingMessages, g as getConversationWorkState, h as getConversation, m as ensureConversationWake, r as appendAndEnqueueInboundMessage, s as claimInboundMessage, w as steerWebPendingMessages } from "./store-CZ9vqR4P.js";
24
+ import { D as markDispatchFailed, E as markDispatchCompleted, O as markDispatchRunning, S as isTerminalDispatchStatus, T as markDispatchBlocked, a as resolveTurnSessionRouting, b as getDispatchTurnId, c as getPersistedThreadState, d as coerceThreadConversationState, g as getDispatchConversationId, i as resolveConversationRouting, l as persistThreadRuntimeState, m as confirmDispatchMailboxAppend, mt as readAutomationTitlesByConversationId, n as scheduleSessionCompletedPluginTasks, o as getLocationConfigurationService, p as claimDispatchMailboxAppend, s as getPersistedSandboxState, u as persistThreadStateById, v as getDispatchInputMessageId, w as markDispatchAwaitingResume, y as getDispatchRecord } from "./task-runner-CMiNGsER.js";
25
+ import { l as conversationPendingMessagesReportSchema, n as conversationFeedSchema, p as healthReportSchema, t as conversationFeedBriefSchema } from "./conversation-feed-BVAOga0H.js";
26
+ import { r as endActiveAgentInvocations, s as resolveThreadTurnWork } from "./work-EA98F0ia.js";
27
+ import { a as withAgentInvocationResultActors, n as enqueueAgentInvocationResult, t as createChildConversationWorker } from "./result-CEqQFrEf.js";
28
+ import { t as bindMessageAgent } from "./message-BFnIwKpx.js";
29
+ import { r as readConversationLineage, t as bindSpawnAgent } from "./spawn-YeqlNDv8.js";
30
30
  import { createHash, createHmac, timingSafeEqual } from "node:crypto";
31
31
  import * as z from "zod";
32
- import { and, asc, desc, eq, gt, inArray, isNotNull, isNull, lte, max, ne, or, sql } from "drizzle-orm";
32
+ import { and, asc, count, desc, eq, gt, inArray, isNotNull, isNull, lte, max, ne, or, sql } from "drizzle-orm";
33
33
  import { conversationSidebarAnnotationSchema, createSlackSource, objectTypeSchema } from "@sentry/junior-plugin-api";
34
34
  import { alias } from "drizzle-orm/pg-core";
35
35
  import { Message, ThreadImpl, stringifyMarkdown } from "chat";
@@ -55,6 +55,10 @@ const agentDispatchMailboxMetadataSchema = z.object({
55
55
  kind: z.literal("agent_dispatch")
56
56
  }).strict();
57
57
  const AGENT_DISPATCH_MAX_AGE_MS = 864e5;
58
+ /** Return whether a dispatch is a Scheduled or Event automation run. */
59
+ function isAutomationRun(dispatch) {
60
+ return dispatch.source.kind === "scheduled_automation" || dispatch.source.kind === "event_automation";
61
+ }
58
62
  /** Restore the exact actor, credential, and dispatch routing for every slice. */
59
63
  function buildDispatchRoutingContext(dispatch) {
60
64
  return {
@@ -68,7 +72,7 @@ function buildDispatchRoutingContext(dispatch) {
68
72
  replyAttribution: dispatch.replyAttribution,
69
73
  outcomes: dispatch.outcomes,
70
74
  ...dispatch.skill ? { skill: dispatch.skill } : void 0,
71
- ...dispatch.source.kind === "scheduled_automation" || dispatch.source.kind === "event_automation" ? { declaresResult: true } : void 0
75
+ ...isAutomationRun(dispatch) ? { declaresResult: true } : void 0
72
76
  },
73
77
  surface: "api"
74
78
  };
@@ -102,6 +106,7 @@ async function enqueueAgentDispatch(dispatch, options) {
102
106
  activityAtMs: claimedDispatch.createdAtMs,
103
107
  conversationId: getDispatchConversationId(claimedDispatch),
104
108
  destination: claimedDispatch.destination,
109
+ kind: isAutomationRun(claimedDispatch) ? "automation" : "root",
105
110
  nowMs,
106
111
  source: "plugin",
107
112
  sessionSource: claimedDispatch.source,
@@ -4227,6 +4232,32 @@ async function maybeApplyProviderDefaultConfigRequest(args) {
4227
4232
  });
4228
4233
  return { text: `Default GitHub repo set to \`${repo}\`.` };
4229
4234
  }
4235
+ // src/chat/automation-result.ts
4236
+ /**
4237
+ * Return the text to post after a run ends, if any. A chat Turn already
4238
+ * delivered a successful reply, so it posts only its failure reply. An
4239
+ * Automation run posts only its `reply` text. It never posts a failure
4240
+ * reply to its outcomes. The failed execution shows on the Automation.
4241
+ */
4242
+ function finishedRunReply(result, dispatch) {
4243
+ if (!dispatch?.declaresResult) return result.diagnostics.outcome === "success" ? void 0 : result.text;
4244
+ return result.diagnostics.outcome === "success" && dispatch.outcomes?.length !== 0 ? result.reply?.text : void 0;
4245
+ }
4246
+ /**
4247
+ * Map one finished agent run to its dispatch outcome. A blocked report
4248
+ * becomes a blocked dispatch with the reported reason.
4249
+ */
4250
+ function runDispatchOutcome(result) {
4251
+ if (result.diagnostics.outcome !== "success") return {
4252
+ errorMessage: result.diagnostics.errorMessage ?? `Agent turn ended with ${result.diagnostics.outcome}.`,
4253
+ outcome: "failed"
4254
+ };
4255
+ if (result.blocked) return {
4256
+ errorMessage: result.blocked.missing,
4257
+ outcome: "blocked"
4258
+ };
4259
+ return { outcome: "completed" };
4260
+ }
4230
4261
  // src/chat/providers/slack/input.ts
4231
4262
  /** Return the actor stored with one inbound Slack message. */
4232
4263
  function inboundMessageActor(queued) {
@@ -7153,7 +7184,7 @@ const conversationCursorPayloadSchema = z.object({
7153
7184
  version: z.literal(1)
7154
7185
  }).strict();
7155
7186
  function cursorSecret() {
7156
- const secret = process.env.JUNIOR_SECRET?.trim();
7187
+ const secret = readJuniorSecret();
7157
7188
  if (!secret) throw new Error("Cannot sign conversation cursor without JUNIOR_SECRET");
7158
7189
  return secret;
7159
7190
  }
@@ -7614,21 +7645,18 @@ async function copyForkEvents(args) {
7614
7645
  } else if ((row.type === "message_updated" || row.type === "message_handled") && messageIds.has(row.messageId) || (row.type === "turn_completed" || row.type === "turn_failed") && turnIds.has(row.turnId)) seqs.push(row.seq);
7615
7646
  }
7616
7647
  if (!seqs.length) return;
7617
- await getSqlExecutor().db().execute(sql`insert into ${e} (${sql.join([
7618
- e.conversationId,
7619
- e.seq,
7620
- e.historyVersion,
7621
- e.schemaVersion,
7622
- e.idempotencyKey,
7623
- e.type,
7624
- e.payload,
7625
- e.actorIdentityId,
7626
- e.createdAt
7627
- ].map((column) => sql.identifier(column.name)), sql`, `)})
7628
- select ${args.conversationId}, ${e.seq}, least(${e.historyVersion}, ${historyVersion}), ${e.schemaVersion}, ${e.idempotencyKey}, ${e.type}, ${e.payload}, ${e.actorIdentityId}, ${e.createdAt}
7629
- from ${e}
7630
- where ${e.conversationId} = ${args.sourceConversationId}
7631
- and ${inArray(e.seq, seqs)}`);
7648
+ const db = getSqlExecutor().db();
7649
+ await db.insert(e).select(db.select({
7650
+ conversationId: sql`${args.conversationId}`.as("conversation_id"),
7651
+ seq: e.seq,
7652
+ historyVersion: sql`least(${e.historyVersion}, ${historyVersion})`.as("history_version"),
7653
+ schemaVersion: e.schemaVersion,
7654
+ idempotencyKey: e.idempotencyKey,
7655
+ type: e.type,
7656
+ payload: e.payload,
7657
+ actorIdentityId: e.actorIdentityId,
7658
+ createdAt: e.createdAt
7659
+ }).from(e).where(and(eq(e.conversationId, args.sourceConversationId), inArray(e.seq, seqs))));
7632
7660
  }
7633
7661
  function hasUnfinishedToolCalls(messages) {
7634
7662
  const pending = /* @__PURE__ */ new Set();
@@ -7904,146 +7932,6 @@ async function readFirstHumanMessageTexts(db, conversations) {
7904
7932
  }).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));
7905
7933
  return new Map(rows.map((row) => [row.conversationId, row.text]));
7906
7934
  }
7907
- // src/api/conversations/mentions.ts
7908
- /** Text in one event that the dashboard renders with mentions. */
7909
- function eventMentionTexts(data) {
7910
- switch (data.type) {
7911
- case "message": return data.redacted ? [] : [
7912
- data.text,
7913
- data.trustedSummary,
7914
- ...(data.events ?? []).map((event) => event.trustedSummary)
7915
- ];
7916
- case "assistant_message": return data.parts.map((part) => part.text);
7917
- case "compaction": return [data.summary];
7918
- case "structured_event": return [data.presentation.preview, ...(data.presentation.details ?? []).map((detail) => detail.description)];
7919
- default: return [];
7920
- }
7921
- }
7922
- function briefMentionTexts(brief) {
7923
- return [
7924
- brief.summary,
7925
- brief.intent,
7926
- brief.outcome.text,
7927
- ...brief.decisions.flatMap((decision) => [decision.text, decision.by]),
7928
- ...brief.facts
7929
- ];
7930
- }
7931
- function withMentions(value, mentions) {
7932
- return mentions.length > 0 ? {
7933
- ...value,
7934
- mentions
7935
- } : value;
7936
- }
7937
- /**
7938
- * Attach the people that each event and the Brief of one conversation
7939
- * mention, resolved at read time.
7940
- */
7941
- async function attachConversationMentions(executor, conversationId, content) {
7942
- const tenantId = (await loadConversationSlackTenantIds(executor, [conversationId])).get(conversationId);
7943
- const sources = content.events.map((event) => ({
7944
- tenantId,
7945
- texts: eventMentionTexts(event.data)
7946
- }));
7947
- if (content.brief) sources.push({
7948
- tenantId,
7949
- texts: briefMentionTexts(content.brief)
7950
- });
7951
- const mentions = await resolveMentions(executor, sources);
7952
- return {
7953
- briefMentions: content.brief ? mentions.at(-1) : [],
7954
- events: content.events.map((event, index) => withMentions(event, mentions[index]))
7955
- };
7956
- }
7957
- /** Attach the people that each activity preview mentions, resolved at read time. */
7958
- async function attachActivityPreviewMentions(executor, previews) {
7959
- const entries = [...previews];
7960
- const tenants = await loadConversationSlackTenantIds(executor, entries.map(([conversationId]) => conversationId));
7961
- const mentions = await resolveMentions(executor, entries.map(([conversationId, preview]) => ({
7962
- tenantId: tenants.get(conversationId),
7963
- texts: [preview.text]
7964
- })));
7965
- return new Map(entries.map(([conversationId, preview], index) => [conversationId, withMentions(preview, mentions[index])]));
7966
- }
7967
- // src/api/conversations/record.ts
7968
- /** The columns of one Conversation record, for `selectConversationRecords`. */
7969
- const conversationRecordColumns = {
7970
- conversation: juniorConversations,
7971
- location: juniorDestinations,
7972
- identityDisplayName: juniorIdentities.displayName,
7973
- identityEmail: juniorIdentities.email,
7974
- identityHandle: juniorIdentities.handle,
7975
- identityProvider: juniorIdentities.provider,
7976
- identitySubjectId: juniorIdentities.providerSubjectId,
7977
- identityTenantId: juniorIdentities.providerTenantId,
7978
- userDisplayName: juniorUsers.displayName
7979
- };
7980
- /** Left-join conditions from a Conversation to its record tables. */
7981
- const conversationRecordJoins = {
7982
- location: eq(juniorDestinations.id, juniorConversations.destinationId),
7983
- identity: eq(juniorIdentities.id, juniorConversations.actorIdentityId),
7984
- user: eq(juniorUsers.id, juniorIdentities.userId)
7985
- };
7986
- /**
7987
- * Select Conversation rows with their Location and Actor names. Callers add
7988
- * the filter, order, and limit.
7989
- */
7990
- function selectConversationRecords(db) {
7991
- return db.select(conversationRecordColumns).from(juniorConversations).leftJoin(juniorDestinations, conversationRecordJoins.location).leftJoin(juniorIdentities, conversationRecordJoins.identity).leftJoin(juniorUsers, conversationRecordJoins.user);
7992
- }
7993
- /** Decode a conversation row with the linked user name and identity-scoped provider fields. */
7994
- function conversationFromRecordRow(row) {
7995
- const value = row.conversation;
7996
- const legacySessionSource = value.sessionSource === null ? void 0 : parseSessionSource(value.sessionSource);
7997
- if (value.sessionSource !== null && !legacySessionSource) throw new Error("Conversation legacy source_json is invalid");
7998
- const actorFullName = row.userDisplayName?.trim() ? row.userDisplayName : row.identityDisplayName;
7999
- const actor = row.identityProvider === "slack" ? {
8000
- platform: "slack",
8001
- ...row.identityEmail ? { email: row.identityEmail } : void 0,
8002
- ...actorFullName ? { fullName: actorFullName } : void 0,
8003
- ...row.identitySubjectId ? { slackUserId: row.identitySubjectId } : void 0,
8004
- ...row.identityHandle ? { slackUserName: row.identityHandle } : void 0,
8005
- ...row.identityTenantId ? { teamId: row.identityTenantId } : void 0
8006
- } : void 0;
8007
- const location = locationFromRow(value.location, row.location, legacySessionSource);
8008
- return {
8009
- schemaVersion: 1,
8010
- conversationId: value.conversationId,
8011
- createdAtMs: value.createdAt.getTime(),
8012
- kind: conversationKindFromRow(value),
8013
- lastActivityAtMs: value.lastActivityAt.getTime(),
8014
- updatedAtMs: value.updatedAt.getTime(),
8015
- execution: {
8016
- status: value.executionStatus,
8017
- ...value.runId ? { runId: value.runId } : void 0,
8018
- ...value.executionUpdatedAt ? { updatedAtMs: value.executionUpdatedAt.getTime() } : void 0
8019
- },
8020
- ...value.parentConversationId ? { parentConversationId: value.parentConversationId } : void 0,
8021
- ...value.archivedAt ? { archivedAtMs: value.archivedAt.getTime() } : void 0,
8022
- ...actor ? { actor } : void 0,
8023
- ...location ? { location } : void 0,
8024
- ...value.channelName ? { channelName: value.channelName } : void 0,
8025
- ...value.source ? { source: value.source } : void 0,
8026
- ...value.title ? { title: value.title } : void 0,
8027
- ...value.transcriptPurgedAt ? { transcriptPurgedAtMs: value.transcriptPurgedAt.getTime() } : void 0,
8028
- ...value.stoppedAt ? { stoppedAtMs: value.stoppedAt.getTime() } : void 0,
8029
- ...value.deliveryPausedAt ? { deliveryPausedAtMs: value.deliveryPausedAt.getTime() } : void 0
8030
- };
8031
- }
8032
- /** Decode one `selectConversationRecords` row into a Conversation record. */
8033
- function conversationRecordFromRow(row) {
8034
- return {
8035
- conversation: conversationFromRecordRow(row),
8036
- durationMs: row.conversation.durationMs,
8037
- ...row.location?.visibility === "public" ? { locationId: row.location.id } : void 0,
8038
- usage: row.conversation.usage,
8039
- rootConversationId: row.conversation.rootConversationId
8040
- };
8041
- }
8042
- /** Read one normalized conversation record directly from its SQL row. */
8043
- async function readConversationRecordFromSql(conversationId) {
8044
- const row = (await selectConversationRecords(getDb()).where(eq(juniorConversations.conversationId, conversationId)).limit(1))[0];
8045
- return row ? conversationRecordFromRow(row) : void 0;
8046
- }
8047
7935
  // src/api/conversations/shared.ts
8048
7936
  /** Format a Slack destination without exposing private channel names. */
8049
7937
  function slackStatsLocationLabel(input) {
@@ -8210,6 +8098,196 @@ function conversationSummaryFromStoredConversation(args) {
8210
8098
  ...args.locationId && !channelNameRedacted ? { locationId: args.locationId } : void 0
8211
8099
  };
8212
8100
  }
8101
+ // src/api/conversations/agent-tree.ts
8102
+ /** Name a child the viewer cannot read, or one with no agent label. */
8103
+ function childLabel(kind) {
8104
+ return kind === "thread" ? "Thread" : "Task";
8105
+ }
8106
+ /**
8107
+ * Read the agent tree of a child Conversation: its parent chain, root first,
8108
+ * with the child last. Returns undefined for a root Conversation. Each
8109
+ * Conversation has its own access check, so a viewer sees a label only where
8110
+ * they can see private content.
8111
+ */
8112
+ async function readConversationAgentTree(conversation, readAccess) {
8113
+ if (!conversation.parentConversationId) return;
8114
+ const lineage = (await readConversationLineage(conversation.conversationId)).slice(-16);
8115
+ if (lineage.length < 2) return;
8116
+ const ids = lineage.map((entry) => entry.conversationId);
8117
+ const kindById = new Map(lineage.map((entry) => [entry.conversationId, entry.kind]));
8118
+ const root = lineage[0].parentConversationId ? void 0 : await getConversationStore().get({ conversationId: ids[0] });
8119
+ const [access, automationTitleByConversation, firstHumanMessageTextByConversation] = await Promise.all([
8120
+ readAccess(ids),
8121
+ readAutomationTitlesByConversationId(root ? [root] : []),
8122
+ readFirstHumanMessageTexts(getDb(), root ? [root] : [])
8123
+ ]);
8124
+ return await Promise.all(ids.map(async (id) => {
8125
+ const itemAccess = access.get(id);
8126
+ if (root?.conversationId === id) return {
8127
+ conversationId: id,
8128
+ kind: "root",
8129
+ label: conversationSummaryFromStoredConversation({
8130
+ access: itemAccess,
8131
+ automationTitle: automationTitleByConversation.get(id),
8132
+ conversation: root,
8133
+ durationMs: 0,
8134
+ firstHumanMessageText: firstHumanMessageTextByConversation.get(id)
8135
+ }).displayTitle
8136
+ };
8137
+ const kind = kindById.get(id);
8138
+ if (!itemAccess?.canViewPrivateContent) return {
8139
+ conversationId: id,
8140
+ kind,
8141
+ label: childLabel(kind)
8142
+ };
8143
+ const agent = await getChildAgentLabel(id);
8144
+ return {
8145
+ conversationId: id,
8146
+ kind,
8147
+ label: agent?.title ?? agent?.agentName ?? childLabel(kind)
8148
+ };
8149
+ }));
8150
+ }
8151
+ // src/api/conversations/mentions.ts
8152
+ /** Text in one event that the dashboard renders with mentions. */
8153
+ function eventMentionTexts(data) {
8154
+ switch (data.type) {
8155
+ case "message": return data.redacted ? [] : [
8156
+ data.text,
8157
+ data.trustedSummary,
8158
+ ...(data.events ?? []).map((event) => event.trustedSummary)
8159
+ ];
8160
+ case "assistant_message": return data.parts.map((part) => part.text);
8161
+ case "compaction": return [data.summary];
8162
+ case "structured_event": return [data.presentation.preview, ...(data.presentation.details ?? []).map((detail) => detail.description)];
8163
+ default: return [];
8164
+ }
8165
+ }
8166
+ function briefMentionTexts(brief) {
8167
+ return [
8168
+ brief.summary,
8169
+ brief.intent,
8170
+ brief.outcome.text,
8171
+ ...brief.decisions.flatMap((decision) => [decision.text, decision.by]),
8172
+ ...brief.facts
8173
+ ];
8174
+ }
8175
+ function withMentions(value, mentions) {
8176
+ return mentions.length > 0 ? {
8177
+ ...value,
8178
+ mentions
8179
+ } : value;
8180
+ }
8181
+ /**
8182
+ * Attach the people that each event and the Brief of one conversation
8183
+ * mention, resolved at read time.
8184
+ */
8185
+ async function attachConversationMentions(executor, conversationId, content) {
8186
+ const tenantId = (await loadConversationSlackTenantIds(executor, [conversationId])).get(conversationId);
8187
+ const sources = content.events.map((event) => ({
8188
+ tenantId,
8189
+ texts: eventMentionTexts(event.data)
8190
+ }));
8191
+ if (content.brief) sources.push({
8192
+ tenantId,
8193
+ texts: briefMentionTexts(content.brief)
8194
+ });
8195
+ const mentions = await resolveMentions(executor, sources);
8196
+ return {
8197
+ briefMentions: content.brief ? mentions.at(-1) : [],
8198
+ events: content.events.map((event, index) => withMentions(event, mentions[index]))
8199
+ };
8200
+ }
8201
+ /** Attach the people that each activity preview mentions, resolved at read time. */
8202
+ async function attachActivityPreviewMentions(executor, previews) {
8203
+ const entries = [...previews];
8204
+ const tenants = await loadConversationSlackTenantIds(executor, entries.map(([conversationId]) => conversationId));
8205
+ const mentions = await resolveMentions(executor, entries.map(([conversationId, preview]) => ({
8206
+ tenantId: tenants.get(conversationId),
8207
+ texts: [preview.text]
8208
+ })));
8209
+ return new Map(entries.map(([conversationId, preview], index) => [conversationId, withMentions(preview, mentions[index])]));
8210
+ }
8211
+ // src/api/conversations/record.ts
8212
+ /** The columns of one Conversation record, for `selectConversationRecords`. */
8213
+ const conversationRecordColumns = {
8214
+ conversation: juniorConversations,
8215
+ location: juniorDestinations,
8216
+ identityDisplayName: juniorIdentities.displayName,
8217
+ identityEmail: juniorIdentities.email,
8218
+ identityHandle: juniorIdentities.handle,
8219
+ identityProvider: juniorIdentities.provider,
8220
+ identitySubjectId: juniorIdentities.providerSubjectId,
8221
+ identityTenantId: juniorIdentities.providerTenantId,
8222
+ userDisplayName: juniorUsers.displayName
8223
+ };
8224
+ /** Left-join conditions from a Conversation to its record tables. */
8225
+ const conversationRecordJoins = {
8226
+ location: eq(juniorDestinations.id, juniorConversations.destinationId),
8227
+ identity: eq(juniorIdentities.id, juniorConversations.actorIdentityId),
8228
+ user: eq(juniorUsers.id, juniorIdentities.userId)
8229
+ };
8230
+ /**
8231
+ * Select Conversation rows with their Location and Actor names. Callers add
8232
+ * the filter, order, and limit.
8233
+ */
8234
+ function selectConversationRecords(db) {
8235
+ return db.select(conversationRecordColumns).from(juniorConversations).leftJoin(juniorDestinations, conversationRecordJoins.location).leftJoin(juniorIdentities, conversationRecordJoins.identity).leftJoin(juniorUsers, conversationRecordJoins.user);
8236
+ }
8237
+ /** Decode a conversation row with the linked user name and identity-scoped provider fields. */
8238
+ function conversationFromRecordRow(row) {
8239
+ const value = row.conversation;
8240
+ const legacySessionSource = value.sessionSource === null ? void 0 : parseSessionSource(value.sessionSource);
8241
+ if (value.sessionSource !== null && !legacySessionSource) throw new Error("Conversation legacy source_json is invalid");
8242
+ const actorFullName = row.userDisplayName?.trim() ? row.userDisplayName : row.identityDisplayName;
8243
+ const actor = row.identityProvider === "slack" ? {
8244
+ platform: "slack",
8245
+ ...row.identityEmail ? { email: row.identityEmail } : void 0,
8246
+ ...actorFullName ? { fullName: actorFullName } : void 0,
8247
+ ...row.identitySubjectId ? { slackUserId: row.identitySubjectId } : void 0,
8248
+ ...row.identityHandle ? { slackUserName: row.identityHandle } : void 0,
8249
+ ...row.identityTenantId ? { teamId: row.identityTenantId } : void 0
8250
+ } : void 0;
8251
+ const location = locationFromRow(value.location, row.location, legacySessionSource);
8252
+ return {
8253
+ schemaVersion: 1,
8254
+ conversationId: value.conversationId,
8255
+ createdAtMs: value.createdAt.getTime(),
8256
+ kind: conversationKindFromRow(value),
8257
+ lastActivityAtMs: value.lastActivityAt.getTime(),
8258
+ updatedAtMs: value.updatedAt.getTime(),
8259
+ execution: {
8260
+ status: value.executionStatus,
8261
+ ...value.runId ? { runId: value.runId } : void 0,
8262
+ ...value.executionUpdatedAt ? { updatedAtMs: value.executionUpdatedAt.getTime() } : void 0
8263
+ },
8264
+ ...value.parentConversationId ? { parentConversationId: value.parentConversationId } : void 0,
8265
+ ...value.archivedAt ? { archivedAtMs: value.archivedAt.getTime() } : void 0,
8266
+ ...actor ? { actor } : void 0,
8267
+ ...location ? { location } : void 0,
8268
+ ...value.channelName ? { channelName: value.channelName } : void 0,
8269
+ ...value.source ? { source: value.source } : void 0,
8270
+ ...value.title ? { title: value.title } : void 0,
8271
+ ...value.transcriptPurgedAt ? { transcriptPurgedAtMs: value.transcriptPurgedAt.getTime() } : void 0,
8272
+ ...value.stoppedAt ? { stoppedAtMs: value.stoppedAt.getTime() } : void 0,
8273
+ ...value.deliveryPausedAt ? { deliveryPausedAtMs: value.deliveryPausedAt.getTime() } : void 0
8274
+ };
8275
+ }
8276
+ /** Decode one `selectConversationRecords` row into a Conversation record. */
8277
+ function conversationRecordFromRow(row) {
8278
+ return {
8279
+ conversation: conversationFromRecordRow(row),
8280
+ durationMs: row.conversation.durationMs,
8281
+ ...row.location?.visibility === "public" ? { locationId: row.location.id } : void 0,
8282
+ usage: row.conversation.usage,
8283
+ rootConversationId: row.conversation.rootConversationId
8284
+ };
8285
+ }
8286
+ /** Read one normalized conversation record directly from its SQL row. */
8287
+ async function readConversationRecordFromSql(conversationId) {
8288
+ const row = (await selectConversationRecords(getDb()).where(eq(juniorConversations.conversationId, conversationId)).limit(1))[0];
8289
+ return row ? conversationRecordFromRow(row) : void 0;
8290
+ }
8213
8291
  // src/api/conversations/event-list.ts
8214
8292
  /** Read one bounded page of reporting events before, after, or around a boundary. */
8215
8293
  async function readConversationEvents(conversationId, boundary, options = {}) {
@@ -8290,56 +8368,6 @@ async function conversationEventPageReport(executor, args) {
8290
8368
  generatedAt: (/* @__PURE__ */ new Date()).toISOString()
8291
8369
  };
8292
8370
  }
8293
- // src/api/conversations/agent-tree.ts
8294
- /** Name a child the viewer cannot read, or one with no agent label. */
8295
- function childLabel(kind) {
8296
- return kind === "thread" ? "Thread" : "Task";
8297
- }
8298
- /**
8299
- * Read the agent tree of a child Conversation: its parent chain, root first,
8300
- * with the child last. Returns undefined for a root Conversation. Each
8301
- * Conversation has its own access check, so a viewer sees a label only where
8302
- * they can see private content.
8303
- */
8304
- async function readConversationAgentTree(conversation, readAccess) {
8305
- if (!conversation.parentConversationId) return;
8306
- const lineage = (await readConversationLineage(conversation.conversationId)).slice(-16);
8307
- if (lineage.length < 2) return;
8308
- const ids = lineage.map((entry) => entry.conversationId);
8309
- const kindById = new Map(lineage.map((entry) => [entry.conversationId, entry.kind]));
8310
- const root = lineage[0].parentConversationId ? void 0 : await getConversationStore().get({ conversationId: ids[0] });
8311
- const [access, automationTitleByConversation, firstHumanMessageTextByConversation] = await Promise.all([
8312
- readAccess(ids),
8313
- readAutomationTitlesByConversationId(root ? [root] : []),
8314
- readFirstHumanMessageTexts(getDb(), root ? [root] : [])
8315
- ]);
8316
- return await Promise.all(ids.map(async (id) => {
8317
- const itemAccess = access.get(id);
8318
- if (root?.conversationId === id) return {
8319
- conversationId: id,
8320
- kind: "root",
8321
- label: conversationSummaryFromStoredConversation({
8322
- access: itemAccess,
8323
- automationTitle: automationTitleByConversation.get(id),
8324
- conversation: root,
8325
- durationMs: 0,
8326
- firstHumanMessageText: firstHumanMessageTextByConversation.get(id)
8327
- }).displayTitle
8328
- };
8329
- const kind = kindById.get(id);
8330
- if (!itemAccess?.canViewPrivateContent) return {
8331
- conversationId: id,
8332
- kind,
8333
- label: childLabel(kind)
8334
- };
8335
- const agent = await getChildAgentLabel(id);
8336
- return {
8337
- conversationId: id,
8338
- kind,
8339
- label: agent?.title ?? agent?.agentName ?? childLabel(kind)
8340
- };
8341
- }));
8342
- }
8343
8371
  // src/api/conversations/fork.ts
8344
8372
  /** Fork a Conversation that the viewer can read into a new root they own. */
8345
8373
  async function forkConversationForViewer(viewer, sourceConversationId, body) {
@@ -8487,6 +8515,18 @@ async function markConversationUnread(viewer, conversationId, body) {
8487
8515
  const detailViewer = alias(juniorUsers, "detail_viewer");
8488
8516
  const forkSource = alias(juniorConversations, "detail_fork_source");
8489
8517
  const fork = alias(juniorConversations, "detail_fork");
8518
+ const agentTreeRoot = alias(juniorConversations, "detail_agent_tree_root");
8519
+ /**
8520
+ * Return the root fields that label the agent tree of a child: its title and
8521
+ * channel name. The other labels cannot change once the child exists. An
8522
+ * agent invocation keeps its title and agent name after insert, and only the
8523
+ * spawn sets a title. Access to each node comes from the shared root, so the
8524
+ * viewer's access covers it. This keeps the recursive lineage read out of
8525
+ * every poll.
8526
+ */
8527
+ function agentTreeRootLabel(db, rootConversationId) {
8528
+ return db.select({ label: sql`row(${agentTreeRoot.title}, ${agentTreeRoot.channelName})::text` }).from(agentTreeRoot).where(eq(agentTreeRoot.conversationId, rootConversationId));
8529
+ }
8490
8530
  /**
8491
8531
  * Sum the detail versions of a Conversation and its child agents. Child
8492
8532
  * writes bump only their own row, and the row count changes when a child
@@ -8546,6 +8586,7 @@ async function readDetailStateRow(conversationId, viewer) {
8546
8586
  const viewerParticipant = viewer ? and(eq(juniorConversationParticipants.userId, viewer.id), eq(juniorConversationParticipants.rootConversationId, rootConversationId)) : sql`false`;
8547
8587
  const [row] = await db.select({
8548
8588
  ...conversationRecordColumns,
8589
+ agentTreeRootLabel: sql`case when ${juniorConversations.parentConversationId} is null then null else (${agentTreeRootLabel(db, rootConversationId)}) end`,
8549
8590
  attachmentsVersion: sql`(${slackAttachmentsVersionQuery(db, conversationId)})`,
8550
8591
  autoArchive: juniorConversationParticipants.autoArchive,
8551
8592
  autoArchiveDefault: detailViewer.autoArchiveDefault,
@@ -8564,7 +8605,7 @@ async function readDetailStateRow(conversationId, viewer) {
8564
8605
  }
8565
8606
  async function readDetailState(conversationId, viewer, readAccess) {
8566
8607
  const rowRead = readDetailStateRow(conversationId, viewer);
8567
- const [accessById, row, forks, agentTree] = await Promise.all([
8608
+ const [accessById, row, forks] = await Promise.all([
8568
8609
  readAccess([conversationId]),
8569
8610
  rowRead,
8570
8611
  rowRead.then((stored) => readConversationForks(conversationId, {
@@ -8574,10 +8615,6 @@ async function readDetailState(conversationId, viewer, readAccess) {
8574
8615
  title: stored.forkSourceTitle
8575
8616
  } } : void 0,
8576
8617
  isChild: Boolean(stored?.conversation.parentConversationId)
8577
- }, readAccess)),
8578
- rowRead.then((stored) => readConversationAgentTree({
8579
- conversationId,
8580
- ...stored?.conversation.parentConversationId ? { parentConversationId: stored.conversation.parentConversationId } : void 0
8581
8618
  }, readAccess))
8582
8619
  ]);
8583
8620
  const access = accessById.get(conversationId);
@@ -8588,10 +8625,10 @@ async function readDetailState(conversationId, viewer, readAccess) {
8588
8625
  })).digest("base64url");
8589
8626
  const viewerMarks = row ? viewerMarksFromParticipant(row) : void 0;
8590
8627
  return {
8628
+ agentTreeRootLabel: row?.agentTreeRootLabel ?? void 0,
8591
8629
  record: row ? conversationRecordFromRow(row) : void 0,
8592
8630
  state: {
8593
8631
  access,
8594
- agentTree,
8595
8632
  ...viewer ? { autoArchive: row?.autoArchive ?? row?.autoArchiveDefault ?? false } : void 0,
8596
8633
  forks,
8597
8634
  ...row?.lastReadSeq != null ? { readPosition: { lastReadSeq: row.lastReadSeq } } : void 0,
@@ -8630,11 +8667,11 @@ async function readConversationDetailState(conversationId, viewer, readAccess) {
8630
8667
  * change or a reload.
8631
8668
  */
8632
8669
  async function readConversationDetailEtag(conversationId, options) {
8633
- const { record, state, version } = await readDetailState(conversationId, options.viewer, options.readAccess);
8670
+ const { agentTreeRootLabel, record, state, version } = await readDetailState(conversationId, options.viewer, options.readAccess);
8634
8671
  if (!version) return void 0;
8635
8672
  const basis = JSON.stringify({
8636
8673
  access: state.access ?? null,
8637
- agentTree: state.agentTree ?? null,
8674
+ agentTree: agentTreeRootLabel ?? null,
8638
8675
  autoArchive: state.autoArchive ?? null,
8639
8676
  forks: state.forks,
8640
8677
  junior: JUNIOR_VERSION,
@@ -9066,7 +9103,8 @@ function projectConversationDetail(args) {
9066
9103
  };
9067
9104
  }
9068
9105
  async function readConversationDetailFromSql(conversationId, options) {
9069
- const { record, state } = options.stored ?? await readConversationDetailState(conversationId, options.viewer, createConversationAccessReader(getDb(), options.viewer));
9106
+ const readAccess = createConversationAccessReader(getDb(), options.viewer);
9107
+ const { record, state } = options.stored ?? await readConversationDetailState(conversationId, options.viewer, readAccess);
9070
9108
  if (!record) return void 0;
9071
9109
  const { access, readPosition } = state;
9072
9110
  const canExposePayload = access?.canViewPrivateContent ?? false;
@@ -9098,7 +9136,11 @@ async function readConversationDetailFromSql(conversationId, options) {
9098
9136
  limit: options.limit
9099
9137
  });
9100
9138
  };
9101
- const [annotations, automationTitleByConversation, auxiliaryCostsByConversation, briefVersion, firstHumanMessageTextByConversation, modelUsage, metricsByConversation, people, sourceTask, teamDomainByTeamId, page] = await Promise.all([
9139
+ const [agentTree, annotations, automationTitleByConversation, auxiliaryCostsByConversation, briefVersion, firstHumanMessageTextByConversation, modelUsage, metricsByConversation, people, sourceTask, teamDomainByTeamId, page] = await Promise.all([
9140
+ readConversationAgentTree({
9141
+ conversationId,
9142
+ ...record.conversation.parentConversationId ? { parentConversationId: record.conversation.parentConversationId } : void 0
9143
+ }, readAccess),
9102
9144
  listConversationAnnotations(getDb(), conversationId),
9103
9145
  readAutomationTitlesByConversationId([record.conversation]),
9104
9146
  readConversationAuxiliaryCostsFromSql(getDb(), [conversationId]),
@@ -9184,7 +9226,7 @@ async function readConversationDetailFromSql(conversationId, options) {
9184
9226
  return {
9185
9227
  ...report,
9186
9228
  ...state.forks,
9187
- ...state.agentTree ? { agentTree: state.agentTree } : void 0,
9229
+ ...agentTree ? { agentTree } : void 0,
9188
9230
  ...report.isParticipant && state.autoArchive !== void 0 ? { autoArchive: state.autoArchive } : void 0,
9189
9231
  ...report.isParticipant && state.subscribed !== void 0 ? { subscribed: state.subscribed } : void 0,
9190
9232
  ...canContinueInSlack(record.conversation, access) ? { canContinueInSlack: true } : void 0,
@@ -9225,7 +9267,26 @@ async function readConversationDetail(conversationId, options = {}) {
9225
9267
  async function pinConversation(viewer, conversationId, body) {
9226
9268
  if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(404, "Conversation not found.");
9227
9269
  const executor = getSqlExecutor();
9228
- return await executor.transaction(() => setPin(executor.db(), viewer, conversationId, body.pinned));
9270
+ return await executor.transaction(async () => {
9271
+ const db = executor.db();
9272
+ const result = await setPin(db, viewer, conversationId, body.pinned);
9273
+ recordPinUsage(body.pinned ? "pin" : "unpin", await countViewerPins(db, viewer));
9274
+ return result;
9275
+ });
9276
+ }
9277
+ /**
9278
+ * Tag the request span with a pin change and the viewer's pin count after
9279
+ * it. Pins stay manual; this shows how much people use them.
9280
+ */
9281
+ function recordPinUsage(action, pinnedCount) {
9282
+ setSpanAttributes({
9283
+ "app.conversation.pin.action": action,
9284
+ "app.conversation.pin.count": pinnedCount
9285
+ });
9286
+ }
9287
+ async function countViewerPins(db, viewer) {
9288
+ const [row] = await db.select({ pins: count() }).from(juniorConversationParticipants).where(and(eq(juniorConversationParticipants.userId, viewer.id), isNotNull(juniorConversationParticipants.pinnedAt)));
9289
+ return row?.pins ?? 0;
9229
9290
  }
9230
9291
  async function setPin(db, viewer, conversationId, pinned) {
9231
9292
  const [conversation] = await db.select({
@@ -9271,6 +9332,7 @@ async function reorderPinnedConversations(viewer, body) {
9271
9332
  const participants = juniorConversationParticipants;
9272
9333
  const positions = sql.join(ids.map((id, index) => sql`when ${id} then ${index}::integer`), sql` `);
9273
9334
  const updated = await getDb().update(participants).set({ pinPosition: sql`case ${participants.rootConversationId} ${positions} else ${participants.pinPosition} + ${ids.length}::integer end` }).where(and(eq(participants.userId, viewer.id), isNotNull(participants.pinnedAt))).returning({ rootConversationId: participants.rootConversationId });
9335
+ recordPinUsage("reorder", updated.length);
9274
9336
  const updatedIds = new Set(updated.map((row) => row.rootConversationId));
9275
9337
  return { conversationIds: ids.filter((id) => updatedIds.has(id)) };
9276
9338
  }
@@ -9410,6 +9472,29 @@ async function readConversationActivityPreviews(db, conversationIds) {
9410
9472
  }
9411
9473
  return previews;
9412
9474
  }
9475
+ // src/api/conversations/feed-brief.ts
9476
+ /**
9477
+ * Read the latest Brief version of each Conversation on a feed page, in one
9478
+ * query. A lateral limit reads one row per Conversation from the
9479
+ * (conversation, version) key, so long Brief histories do not slow the feed.
9480
+ * Callers show the result only when the viewer can see private content.
9481
+ */
9482
+ async function readConversationFeedBriefs(db, conversationIds) {
9483
+ if (conversationIds.length === 0) return /* @__PURE__ */ new Map();
9484
+ const content = juniorConversationBriefs.content;
9485
+ const latest = db.select({
9486
+ intent: sql`${content}->>'intent'`.as("intent"),
9487
+ status: sql`${content}->'outcome'->>'status'`.as("status"),
9488
+ summary: sql`${content}->>'summary'`.as("summary")
9489
+ }).from(juniorConversationBriefs).where(eq(juniorConversationBriefs.conversationId, juniorConversations.conversationId)).orderBy(desc(juniorConversationBriefs.version)).limit(1).as("latest_brief");
9490
+ const rows = await db.select({
9491
+ conversationId: juniorConversations.conversationId,
9492
+ intent: latest.intent,
9493
+ status: latest.status,
9494
+ summary: latest.summary
9495
+ }).from(juniorConversations).innerJoinLateral(latest, sql`true`).where(inArray(juniorConversations.conversationId, conversationIds));
9496
+ return new Map(rows.map(({ conversationId, ...brief }) => [conversationId, conversationFeedBriefSchema.parse(brief)]));
9497
+ }
9413
9498
  // src/api/conversations/list.ts
9414
9499
  const CONVERSATION_FEED_LIMIT = 50;
9415
9500
  function feedMember(filter) {
@@ -9439,6 +9524,7 @@ function conversationCodeRepositoryFilter(repositoryId, viewerUserId) {
9439
9524
  async function conversationRows(db, { codeRepository, conversationIds, filter, includePrivateBriefs = false, limit, query, status }) {
9440
9525
  return db.select({
9441
9526
  ...conversationRecordColumns,
9527
+ lastMessageAt: sql`coalesce(${juniorConversations.lastMessageAt}, ${lastMessageAtSql(db)})`.mapWith(juniorConversations.lastMessageAt),
9442
9528
  awaitingAuthorization: treeAwaitsAuthorization(juniorConversations.conversationId)
9443
9529
  }).from(juniorConversations).leftJoin(juniorDestinations, conversationRecordJoins.location).leftJoin(juniorIdentities, conversationRecordJoins.identity).leftJoin(juniorUsers, conversationRecordJoins.user).where(and(listedConversation(), conversationFeedMembershipFilter(status, filter), conversationIds ? inArray(juniorConversations.conversationId, conversationIds) : void 0, codeRepository ? conversationCodeRepositoryFilter(codeRepository.id, codeRepository.viewerUserId) : void 0, query ? or(sql`strpos(lower(coalesce(${juniorConversations.title}, '')), ${query}) > 0`, sql`exists (
9444
9530
  select 1
@@ -9456,7 +9542,7 @@ async function conversationRows(db, { codeRepository, conversationIds, filter, i
9456
9542
  }
9457
9543
  /**
9458
9544
  * Read the viewer's active conversations that wait on them but fall outside
9459
- * the newest page. Needs attention shows every conversation that waits on the
9545
+ * the newest page. Needs you shows every conversation that waits on the
9460
9546
  * viewer, so an old one must come back to the feed.
9461
9547
  */
9462
9548
  async function waitingRowsOutsidePage(db, filter, page) {
@@ -9471,9 +9557,17 @@ async function waitingRowsOutsidePage(db, filter, page) {
9471
9557
  status: "active"
9472
9558
  });
9473
9559
  }
9474
- /** Feed rows show last activity only as an age in whole minutes. */
9475
- function shownActivityMinute(lastActivityAt) {
9476
- return sql`date_trunc('minute', ${lastActivityAt})`;
9560
+ /**
9561
+ * Feed rows show last activity only as an age in whole minutes. A running
9562
+ * row shows its running state in place of the age, so it shows no activity.
9563
+ * Every status but `idle` and `failed` shows as running, as in
9564
+ * `statusFromConversation`.
9565
+ */
9566
+ function shownActivityMinute(executionStatus, lastActivityAt) {
9567
+ return sql`case
9568
+ when ${executionStatus} in ('idle', 'failed')
9569
+ then date_trunc('minute', ${lastActivityAt})
9570
+ end`;
9477
9571
  }
9478
9572
  const feedTree = alias(juniorConversations, "feed_tree");
9479
9573
  const feedAnnotated = alias(juniorConversations, "feed_annotated");
@@ -9505,7 +9599,7 @@ function conversationFeedVersionQuery(db, userId) {
9505
9599
  string_agg(concat_ws('/',
9506
9600
  ${feedTree.conversationId}, ${feedTree.title},
9507
9601
  ${feedTree.executionStatus}, ${feedTree.stoppedAt},
9508
- ${shownActivityMinute(feedTree.lastActivityAt)}
9602
+ ${shownActivityMinute(feedTree.executionStatus, feedTree.lastActivityAt)}
9509
9603
  ), ',' order by ${feedTree.conversationId}) filter (
9510
9604
  where ${feedTree.kind} = 'thread' and ${feedTree.archivedAt} is null
9511
9605
  )
@@ -9520,10 +9614,7 @@ function conversationFeedVersionQuery(db, userId) {
9520
9614
  pinPosition: pin.pinPosition,
9521
9615
  stoppedAt: juniorConversations.stoppedAt,
9522
9616
  title: juniorConversations.title,
9523
- activity: sql`case
9524
- when ${juniorConversations.executionStatus} in ('idle', 'failed')
9525
- then ${shownActivityMinute(juniorConversations.lastActivityAt)}
9526
- end`.as("activity"),
9617
+ activity: shownActivityMinute(juniorConversations.executionStatus, juniorConversations.lastActivityAt).as("activity"),
9527
9618
  assistantSeq: sql`(${latestMessageSeqQuery(db, "assistant", conversationId)})`.as("assistant_seq"),
9528
9619
  userSeq: sql`(${latestMessageSeqQuery(db, "user", conversationId)})`.as("user_seq"),
9529
9620
  unread: unreadReplySql(db, userId, conversationId, read.lastReadSeq).as("unread"),
@@ -9587,7 +9678,7 @@ async function readConversationFeedFromSql(options = {}) {
9587
9678
  if (filter?.kind === "viewer" && status === "active") rows.push(...await waitingRowsOutsidePage(db, filter, rows));
9588
9679
  const conversations = rows.map((row) => conversationFromRecordRow(row));
9589
9680
  const conversationIds = conversations.map((conversation) => conversation.conversationId);
9590
- const [accessByConversation, viewerMarksByConversation, annotationsByConversation, auxiliaryCostsByRoot, metricsByRoot, participantsByConversation, teamDomainByTeamId, { work: conversationWork, lastUserMessageAt: lastUserMessageAtByConversation }, activityPreviewByConversation, automationTitleByConversation, firstHumanMessageTextByConversation, unreadConversationIds] = await Promise.all([
9681
+ const [accessByConversation, viewerMarksByConversation, annotationsByConversation, auxiliaryCostsByRoot, metricsByRoot, participantsByConversation, teamDomainByTeamId, { work: conversationWork, lastUserMessageAt: lastUserMessageAtByConversation }, activityPreviewByConversation, briefByConversation, automationTitleByConversation, firstHumanMessageTextByConversation, unreadConversationIds] = await Promise.all([
9591
9682
  readConversationAccessFromSql(db, conversationIds, options.viewer),
9592
9683
  conversationViewerMarks(db, conversationIds, filter ? feedMember(filter) : void 0),
9593
9684
  listConversationAnnotationsById(db, conversationIds),
@@ -9600,6 +9691,7 @@ async function readConversationFeedFromSql(options = {}) {
9600
9691
  lastUserMessageAt: await readLastUserMessageAtByConversation(db, work.assignedIds.filter((conversationId) => work.finishedAtById[conversationId]))
9601
9692
  })),
9602
9693
  readConversationActivityPreviews(db, conversationIds),
9694
+ readConversationFeedBriefs(db, conversationIds),
9603
9695
  readAutomationTitlesByConversationId(conversations),
9604
9696
  readFirstHumanMessageTexts(db, conversations),
9605
9697
  filter?.kind === "viewer" ? readUnreadConversationIds(db, conversationIds, filter.userId) : /* @__PURE__ */ new Set()
@@ -9640,15 +9732,19 @@ async function readConversationFeedFromSql(options = {}) {
9640
9732
  };
9641
9733
  const annotations = access?.canViewPrivateContent ? annotationsByConversation.get(conversation.conversationId) ?? [] : [];
9642
9734
  const activityPreview = visibleActivityPreviews.get(conversation.conversationId);
9735
+ const brief = access?.canViewPrivateContent ? briefByConversation.get(conversation.conversationId) : void 0;
9643
9736
  const participants = access?.canViewPrivateContent ? participantsByConversation.get(conversation.conversationId) : void 0;
9644
9737
  const threads = threadsByRoot.get(conversation.conversationId);
9738
+ const lastMessageAt = row.lastMessageAt?.toISOString();
9645
9739
  return {
9646
9740
  ...summary,
9647
9741
  ...work,
9648
9742
  ...row.awaitingAuthorization ? { awaitingAuthorization: true } : void 0,
9743
+ ...lastMessageAt ? { lastMessageAt } : void 0,
9649
9744
  ...threads ? { threads } : void 0,
9650
9745
  ...participants && participants.length > 0 ? { participants } : void 0,
9651
9746
  ...activityPreview ? { activityPreview } : void 0,
9747
+ ...brief ? { brief } : void 0,
9652
9748
  ...annotations.length > 0 ? { annotations } : void 0,
9653
9749
  ...sidebarAnnotationsByConversation[conversation.conversationId] ? { sidebarAnnotations: sidebarAnnotationsByConversation[conversation.conversationId] } : void 0,
9654
9750
  isPriority: isConversationPriority({
@@ -9745,4 +9841,4 @@ function viewerWebMessages(messages, viewer) {
9745
9841
  }] : [];
9746
9842
  });
9747
9843
  }
9748
- export { actOnReviewItem as $, createProductionConversationWorkOptions as A, clearSlackPendingReactions as B, createConversationForViewer as C, readConversationPendingMessages as D, cancelConversationPendingMessagesForViewer as E, isAllowedSignInEmail as F, createSlackWebApiStatusSender as G, stripLeadingBotMention as H, readEnvList as I, stopConversation as J, SubscribedReplyReason as K, resolveAllowedDomains as L, getProductionSlackAdapter as M, assertNoLegacyAllowedDomains as N, requireConversationPendingMessages as O, isAllowedDomain as P, ReviewItemActionError as Q, startProcessingReaction as R, appendConversationMessageForViewer as S, encodeConversationCursor as T, normalizeIncomingSlackThreadId as U, slackInboundMessageId as V, withNormalizedThreadId as W, recordSkippedConversationMessage as X, parseContent as Y, bindMessageAuthorIdentityId as Z, keepQuickQuestionForViewer as _, pinConversation as a, continueConversationInSlack as at, readConversationRecordFromSql as b, readConversationParticipants as c, archiveViewerDoneConversations as ct, readConversationTreeMetricsFromSql as d, setConversationAutoArchive as dt, closeReviewItemsAnsweredByReply as et, conversationVersionQuery as f, updateUserAutoArchiveSettings as ft, forkConversationForViewer as g, readHealthReport as gt, reportConversationRead as h, GET as ht, readConversationFeed as i, canContinueInSlack as it, createProductionSlackWebhookServices as j, resolveMentions as k, readConversationAuxiliaryCostsFromSql as l, readUserAutoArchiveSettings as lt, markConversationUnread as m, enqueueAgentDispatch as mt, steerConversationPendingMessagesForViewer as n, reviewItemChange as nt, reorderPinnedConversations as o, isMovableToSlack as ot, readConversationDetailEtag as p, AGENT_DISPATCH_MAX_AGE_MS as pt, getThreadStopDecision as q, conversationFeedVersionQuery as r, alreadyContinuesInSlackMessage as rt, readConversationDetail as s, DEFAULT_AUTO_ARCHIVE_SETTINGS as st, stopConversationTurnForViewer as t, readReviewItemForUser as tt, childAgentTotalsReport as u, runAutoArchiveSweep as ut, readConversationEvents as v, decodeConversationCursor as w, readFirstHumanMessageTexts as x, conversationSummaryFromStoredConversation as y, buildSlackInboundMessage as z };
9844
+ export { actOnReviewItem as $, createProductionConversationWorkOptions as A, clearSlackPendingReactions as B, createConversationForViewer as C, readConversationPendingMessages as D, cancelConversationPendingMessagesForViewer as E, isAllowedSignInEmail as F, createSlackWebApiStatusSender as G, stripLeadingBotMention as H, readEnvList as I, stopConversation as J, SubscribedReplyReason as K, resolveAllowedDomains as L, getProductionSlackAdapter as M, assertNoLegacyAllowedDomains as N, requireConversationPendingMessages as O, isAllowedDomain as P, ReviewItemActionError as Q, startProcessingReaction as R, appendConversationMessageForViewer as S, encodeConversationCursor as T, normalizeIncomingSlackThreadId as U, slackInboundMessageId as V, withNormalizedThreadId as W, recordSkippedConversationMessage as X, parseContent as Y, bindMessageAuthorIdentityId as Z, keepQuickQuestionForViewer as _, pinConversation as a, continueConversationInSlack as at, conversationSummaryFromStoredConversation as b, readConversationParticipants as c, archiveViewerDoneConversations as ct, readConversationTreeMetricsFromSql as d, setConversationAutoArchive as dt, closeReviewItemsAnsweredByReply as et, conversationVersionQuery as f, updateUserAutoArchiveSettings as ft, forkConversationForViewer as g, readHealthReport as gt, reportConversationRead as h, GET as ht, readConversationFeed as i, canContinueInSlack as it, createProductionSlackWebhookServices as j, resolveMentions as k, readConversationAuxiliaryCostsFromSql as l, readUserAutoArchiveSettings as lt, markConversationUnread as m, enqueueAgentDispatch as mt, steerConversationPendingMessagesForViewer as n, reviewItemChange as nt, reorderPinnedConversations as o, isMovableToSlack as ot, readConversationDetailEtag as p, AGENT_DISPATCH_MAX_AGE_MS as pt, getThreadStopDecision as q, conversationFeedVersionQuery as r, alreadyContinuesInSlackMessage as rt, readConversationDetail as s, DEFAULT_AUTO_ARCHIVE_SETTINGS as st, stopConversationTurnForViewer as t, readReviewItemForUser as tt, childAgentTotalsReport as u, runAutoArchiveSweep as ut, readConversationEvents as v, decodeConversationCursor as w, readFirstHumanMessageTexts as x, readConversationRecordFromSql as y, buildSlackInboundMessage as z };