@sentry/junior 0.295.0 → 0.297.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 (84) hide show
  1. package/dist/{admin-ifgjyfpF.js → admin-tmGIw4KS.js} +2 -2
  2. package/dist/{agent-runner-DjMTPWEO.js → agent-runner-CneTquAE.js} +468 -1947
  3. package/dist/api/schema.d.ts +2 -2
  4. package/dist/api/schema.js +7 -7
  5. package/dist/api.d.ts +1 -1
  6. package/dist/api.js +306 -569
  7. package/dist/{app-uiTzRbvq.d.ts → app-BJojZ7HL.d.ts} +7 -2
  8. package/dist/app.d.ts +1 -1
  9. package/dist/app.js +64 -44
  10. package/dist/attempt-selection-ClP3MMPr.js +61 -0
  11. package/dist/{automation-yJX3C7i3.js → automation-BrP6ImrC.js} +1 -1
  12. package/dist/{background-compaction-queue-DUkHZjmL.js → background-compaction-queue-CwfJy3Cd.js} +4 -88
  13. package/dist/{briefs-CbNYM-q2.js → briefs-uFTuhMqA.js} +3 -3
  14. package/dist/{catalog-runtime-DgouZKZm.js → catalog-runtime-0kuQqYL4.js} +1 -1
  15. package/dist/cli/chat.js +19 -15
  16. package/dist/cli/check.js +3 -3
  17. package/dist/cli/main.js +3 -3
  18. package/dist/cli/plugins.js +4 -4
  19. package/dist/cli/snapshot-create.js +4 -4
  20. package/dist/cli/upgrade.d.ts +1 -1
  21. package/dist/cli/upgrade.js +3 -3
  22. package/dist/{config-DvnTPCfp.js → config-Dj9M_nqB.js} +18 -2
  23. package/dist/{connections-CWaIVl_1.js → connections-B96JUM5o.js} +6 -6
  24. package/dist/{conversation-CMkSmi02.js → conversation-CvcBU1z2.js} +2 -16
  25. package/dist/{conversation-feed-BVAOga0H.js → conversation-feed-BSMlGZnS.js} +1 -1
  26. package/dist/{conversation-privacy-DPjv4SnA.js → conversation-privacy-DI29jbZV.js} +1 -1
  27. package/dist/conversation-turn-CZWBr091.js +805 -0
  28. package/dist/{credential-sync-BhbaZfmO.js → credential-sync-Blhx4_xf.js} +14 -13
  29. package/dist/{db-Dts2XvLu.js → db-Br0tfAo7.js} +54 -32
  30. package/dist/{db-CCUqQe0E.d.ts → db-CrtyFRz7.d.ts} +13 -1
  31. package/dist/{executor-Ck73J0wP.js → executor-BMPipFVA.js} +19 -5
  32. package/dist/instrumentation.js +19 -2
  33. package/dist/{logging-9OAq-fdg.js → logging-CQjlDQYX.js} +1 -1
  34. package/dist/{message-CtaPzC7m.js → message-BOZEIuxy.js} +15 -13
  35. package/dist/nitro.d.ts +1 -1
  36. package/dist/nitro.js +3 -2
  37. package/dist/{session-stop-DkxI5vc3.js → notification-gusCgdQ6.js} +14 -933
  38. package/dist/{oauth-callback-server-C_LXY1d4.js → oauth-callback-server-V_DuMuNX.js} +2 -2
  39. package/dist/{projection-BzJQncZV.js → projection-B08mfi0u.js} +479 -145
  40. package/dist/{prompt-Cbq5b4SO.js → prompt-BlutWLNt.js} +4 -4
  41. package/dist/prompt-input-Dxn8cDC0.js +1424 -0
  42. package/dist/{registry-cbpOxO4M.js → registry-BDWgCJDf.js} +1 -1
  43. package/dist/reporting-window-DopzcOHh.js +137 -0
  44. package/dist/{resolve-t-pmRdwS.js → resolve-2Z_o_SsI.js} +3 -3
  45. package/dist/result-CAujiaci.js +463 -0
  46. package/dist/{runner-CHv9X9TH.js → runner-D2Chc02N.js} +9 -8
  47. package/dist/{sandbox-egress-signals-Yy3fSCbg.js → sandbox-egress-signals-CFoJduFj.js} +1 -1
  48. package/dist/{schema-BhneuGYv.js → schema-Bqa5NbcP.js} +22 -48
  49. package/dist/{schema-TSEisVJR.d.ts → schema-Ce2XCS7O.d.ts} +24 -107
  50. package/dist/{service-account-DjPIwCMj.js → service-account-C9kRQEb_.js} +3 -3
  51. package/dist/{service-account-C4rBP8ne.js → service-account-CERfXEVU.js} +3 -3
  52. package/dist/session-stop-B-I1rAS1.js +181 -0
  53. package/dist/{skills-BZE2DP8I.js → skills-B0m1nZ_j.js} +3 -3
  54. package/dist/{spawn-BvULxIiu.js → spawn-CwMjRRtn.js} +6 -5
  55. package/dist/{state-CO9ETDzk.js → state-DFnmLmfn.js} +2 -2
  56. package/dist/{stop-CL-rdtQb.js → stop-BCH9VNGf.js} +329 -382
  57. package/dist/{store-DgD78_NK.js → store-B59rOYbS.js} +11 -4
  58. package/dist/{task-runner-CKOj6xla.js → store-m5bmdmsP.js} +929 -1559
  59. package/dist/task-queue-N0kuCknH.js +89 -0
  60. package/dist/task-runner-COOwR8qm.js +291 -0
  61. package/dist/thread-context-Cd44z_W5.js +248 -0
  62. package/dist/turn-cancel-DDu8TOwt.js +201 -0
  63. package/dist/turn-session-routing-BlCtVFRN.js +380 -0
  64. package/dist/{turn-failure-response-BTSo6SMJ.js → turn-user-message-ygLG3ylQ.js} +183 -358
  65. package/dist/turn-wake-DmQec4AG.js +161 -0
  66. package/dist/{reporting-window-B3Ze-Qnt.js → user-input-request-CXNIov9n.js} +24 -143
  67. package/dist/{validation-CXeYgBzq.js → validation-Ba2OcUse.js} +1 -1
  68. package/dist/{version-AQa7Fr2H.js → version-KNDzIAh6.js} +1 -1
  69. package/dist/version.js +1 -1
  70. package/dist/{viewer-Bqkb678l.js → viewer-BPpuN2f9.js} +3 -3
  71. package/dist/warmup-Bskrwmk1.js +2697 -0
  72. package/dist/{worker-Hl7N292I.js → worker-B1skZlit.js} +20 -8
  73. package/migrations/0101_drop_legacy_columns.sql +12 -0
  74. package/migrations/0102_code_change_last_activity.sql +1 -0
  75. package/migrations/0103_agent_invocation_fork.sql +8 -0
  76. package/migrations/meta/0101_snapshot.json +4496 -0
  77. package/migrations/meta/0102_snapshot.json +4502 -0
  78. package/migrations/meta/0103_snapshot.json +4509 -0
  79. package/migrations/meta/_journal.json +21 -0
  80. package/package.json +5 -4
  81. package/dist/result-DhgjR3nQ.js +0 -305
  82. package/dist/result-event-type-DD6BAgT7.js +0 -11
  83. package/dist/warmup-h6u1e9n0.js +0 -1869
  84. package/dist/work-yN_GAuXY.js +0 -768
@@ -1,35 +1,44 @@
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 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-BzJQncZV.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-DvnTPCfp.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-9OAq-fdg.js";
5
- import { t as JUNIOR_VERSION } from "./version-AQa7Fr2H.js";
2
+ import { $ as loadTurnCheckpoint, $i as escapeSlackMrkdwnText, $o as configValueSchema, A as latestConversationMessageSeq, An as trimTrailingAssistantMessages, Br as reviewItemNeedsSomeone, Cr as getReviewItem, D as estimateConversationMessagesTokens, Da as withSlackRetries, Do as readConversationEventPageAfter, E as buildConversationContext, Eo as readConversationEventPage, Er as listWaitingConversations, F as turnHasReply, Fo as getSlackFileId, Fr as canUserReadReviewItem, H as PluginCredentialFailureError, Hn as createUserTokenStore, I as upsertConversationMessage, Ir as isOnlyAssignee, Jo as lookupSlackUserNames, K as AuthorizationFlowDisabledError, Lo as readAttachmentVisionSummary, M as normalizeConversationText, Mr as canActOnReviewItem, N as recordDeliveredAssistantMessage, O as getConversationMessageSlackTs, Oo as readConversationEventPageAround, P as trimConversationMessages, Po as notInheritedByForkChild, Pt as moveIdleConversationDestination, Ro as recordSlackAttachment, S as resolveConversationTitle, Sa as getSlackClient, So as viewerMarksFromParticipant, Ta as normalizeSlackConversationId, To as readLatestConversationBrief, Tr as listReplyActionItems, Uo as listConversationAnnotations, Wn as webActorUserIds, Wo as listConversationAnnotationsById, X as clearPendingAuth, Xt as buildTurnErrorResponse, Zo as createPluginCache, _o as conversationHasParticipantUser, a as loadProjection, aa as addReactionToMessage, an as getAssistantReplyText, at as failTurnRecord, b as persistConversationMessages, bo as conversationPinnedForUser, ct as recordTurnSummary, d as recordAuthorizationCompleted, da as postSlackMessage, ea as formatSlackLink, et as lostWorkerBeforeFirstSave, fa as removeReactionFromMessage, fo as createPluginLogger, go as readConversationAccessFromSql, h as recordSubscribedReplyRoute, ho as createConversationAccessReader, i as loadConversationProjection, ia as truncateStatusText, it as completeTurnRecord, j as markConversationMessage, jo as buildSentryConversationUrl, k as isHumanConversationMessage, kr as takeReviewItem, mn as persistWithRetry, mo as canAddConversationMessages, n as commitMessages, na as normalizeSlackStatusText, nr as getPlugins, nt as saveTurnCheckpoint, o as loadTurnProjection, oa as deleteSlackMessage, ot as getTurnRecord, qo as lookupSlackUser, rt as abandonTurnRecord, sa as getSlackMessagePermalink, st as listTurnSummaries, t as commitAcceptedReply, ti as cancelSubscriptions, ts as piMessageFromHistoryItem, tt as pauseLostWorkerTurn, v as hydrateConversationMessages, va as SlackActionError, vo as conversationIsMemberRoot, w as fallbackShortTitle, wa as isDmChannel, xa as getHeaderString, xo as conversationViewerMarks, y as persistConversationMessageWindow, ya as downloadPrivateSlackFile, yi as getDashboardConversationLink, yo as conversationIsNotUnsubscribedRoot, yr as closeReviewItem, zo as slackAttachmentsVersionQuery, zt as releaseInboundMessage } from "./projection-B08mfi0u.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-Dj9M_nqB.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-CQjlDQYX.js";
5
+ import { t as JUNIOR_VERSION } from "./version-KNDzIAh6.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 { 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-Dts2XvLu.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-Ck73J0wP.js";
7
+ import { A as setFirstConversationLocation, C as deliversFinalText, E as postsRunNotices, F as saveActorAvatar, G as parseSessionSource, K as addAgentTurnUsage, O as conversationKindFromRow, P as resolveActorIdentityId, S as withConversationMutationLock, T as isTopLevelKind, U as claimProviderConversation, W as getConversationIdByProviderConversation, X as hasAgentTurnUsage, Y as agentTurnUsageSchema, Z as resolveRootConversationId, _ as setArchivedAt, a as getConversationStore, et as nextDetailVersion, g as readConversationTrees, it as requireSlackDestination, k as locationFromRow, m as conversationAncestors, nt as createSlackDestination, o as getDb, p as withConversationEventLock, r as getConversationEventStore, s as getSqlExecutor, v as loadConversationSlackTenantIds, y as lastMessageAtSql } from "./db-Br0tfAo7.js";
8
+ import { A as juniorConversations, D as juniorCodeChanges, E as juniorConversationAnnotations, M as juniorUsers, N as juniorDestinations, b as juniorConversationBriefs, j as juniorIdentities, l as juniorReviewItems, s as juniorReviewItemConversations, v as juniorConversationParticipants, w as juniorConversationEvents } from "./executor-BMPipFVA.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-cbpOxO4M.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-DjMTPWEO.js";
12
- import { a as EVENT_SYSTEM_ACTOR, c as completeDecision, o as isEventConversationMessage, u as completeText } from "./prompt-Cbq5b4SO.js";
10
+ import { d as actorLogContext, f as credentialContextForActor } from "./registry-BDWgCJDf.js";
11
+ import { C as createSlackReviewItemShow, Ct as conversationReadPositionQuery, F as resolveSlackChannelIdFromMessage, H as resolveDestinationVisibility, I as resolveSlackChannelIdFromThreadId, L as checkSlackChannelReadAccess, Lt as shouldEmitDevAgentTrace, N as parseSlackThreadId, Ot as throwApiError, P as readSlackRawMessageContext, Pt as RetryableDeliveryError, R as joinPublicChannelForRead, S as renderBlockText, V as listThreadReplies, Z as readConversationSourceTask, _t as decodeInputImages, a as buildAuthPauseResponse, ft as createAndEnqueueConversation, ht as webActorFromUser, j as runWithSlackInstallation, kt as listedConversation, lt as acceptsWebMessages, m as latestProgressStatus, mt as recordWebConversationActivity, n as executeAgentRun, ot as deliverReviewItemChange, pt as createConversationId, t as createAgentRunner, ut as appendAndEnqueueWebMessage, x as renderAttachmentText, xt as storeAttachment, z as getConversationInfo } from "./agent-runner-CneTquAE.js";
12
+ import { a as EVENT_SYSTEM_ACTOR, c as completeDecision, o as isEventConversationMessage, u as completeText } from "./prompt-BlutWLNt.js";
13
13
  import { r as acquireActiveLock } from "./locks-D-0h111u.js";
14
- import { f as identityAvatarUrl, h as readUserAvatarUrls } from "./viewer-Bqkb678l.js";
15
- import { a as getStateAdapter, o as getStateValues, s as setStateValues } from "./state-CO9ETDzk.js";
16
- import { U as readMessageAttachments, d as conversationEventPageSchema, l as conversationDetailReportSchema } from "./conversation-CMkSmi02.js";
14
+ import { f as identityAvatarUrl, h as readUserAvatarUrls } from "./viewer-BPpuN2f9.js";
15
+ import { a as getStateAdapter, o as getStateValues, s as setStateValues } from "./state-DFnmLmfn.js";
16
+ import { H as readMessageAttachments, d as conversationEventPageSchema, l as conversationDetailReportSchema } from "./conversation-CvcBU1z2.js";
17
17
  import { t as readJuniorSecret } from "./secrets-DebYU866.js";
18
- import { D as getAssistantReplyText, S as finishedRunReply, T as runDispatchOutcome, c as listConversationWork, l as readLastUserMessageAtByConversation, s as isConversationWorkDone } from "./warmup-h6u1e9n0.js";
19
- import { g as getVercelConversationWorkQueue, k as getTurnRequestDeadline } from "./background-compaction-queue-DUkHZjmL.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-BTSo6SMJ.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-DkxI5vc3.js";
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-DgD78_NK.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-CKOj6xla.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-yN_GAuXY.js";
27
- import { a as withAgentInvocationResultActors, n as enqueueAgentInvocationResult, t as createChildConversationWorker } from "./result-DhgjR3nQ.js";
28
- import { t as bindMessageAgent } from "./message-CtaPzC7m.js";
29
- import { r as readConversationLineage, t as bindSpawnAgent } from "./spawn-BvULxIiu.js";
18
+ import { C as legacyWebMailboxMetadataSchema, b as resolveMailboxTurnWork, l as withoutSavedSteeringMessages, n as loadReviewItemInput, o as buildSteeringPiMessage, p as isExperimentalFeatureEnabled, r as savedInputInstruction } from "./prompt-input-Dxn8cDC0.js";
19
+ import { C as dropOwnUnreadLoopReplies, E as stopChildAgentsOf, T as stopChildAgentsBelow, c as listConversationWork, l as readLastUserMessageAtByConversation, s as isConversationWorkDone } from "./warmup-Bskrwmk1.js";
20
+ import { l as getVercelConversationWorkQueue, w as getTurnRequestDeadline } from "./background-compaction-queue-CwfJy3Cd.js";
21
+ import { c as conversationSubtreeColumns, o as skipInputAfterConversationStop, r as markConversationsStopped, s as conversationSubtree } from "./session-stop-B-I1rAS1.js";
22
+ import { T as getChildAgentLabel, a as ConversationTurnBoundaryError, c as TurnInputDeferredError, d as isTurnInputCommitLostError, f as isTurnInputDeferredError, g as startActiveTurn, h as markTurnFailed, i as getTurnUserSlackMessageTs, l as getConversationTurnBoundaryError, m as markTurnCompleted, mt as buildDeterministicTurnId, o as CooperativeTurnYieldError, p as markTurnClosed, pt as buildDeterministicAssistantMessageId, r as getTurnUserReplyAttachmentContext, s as TurnInputCommitLostError, t as getTurnUserMessage, u as isCooperativeTurnYieldError, v as getTurnLifecycle } from "./turn-user-message-ygLG3ylQ.js";
23
+ import { S as sendSlackReply, T as recordFinishedTurnForAutomatedLimit, x as resolveSlackReplyTarget, y as maybePostAutomatedTurnLimitNotice } from "./notification-gusCgdQ6.js";
24
+ import { E as stopConversationWork, T as steerWebPendingMessages, _ as getConversationWorkState, a as cancelHumanFacingPendingMessages, g as getConversation, h as ensureConversationWake, r as appendAndEnqueueInboundMessage, s as claimInboundMessage } from "./store-B59rOYbS.js";
25
+ import { a as getPersistedThreadState, c as coerceThreadConversationState, i as getPersistedSandboxState, n as resolveTurnSessionRouting, o as persistThreadRuntimeState, r as getLocationConfigurationService, s as persistThreadStateById, t as resolveConversationRouting } from "./turn-session-routing-BlCtVFRN.js";
26
+ import { a as isEmptyUserInputAnswer, o as normalizeUserInputAnswer } from "./user-input-request-CXNIov9n.js";
27
+ import { a as AgentRunError, i as supersedeTurnForInput, o as executeTurn, t as cancelSignInWait } from "./turn-cancel-DDu8TOwt.js";
28
+ import { a as getTurnAuthorization, c as getWebAuthorization, i as wakePausedTurn, n as getPausedTurnRequest, t as createPausedTurns } from "./turn-wake-DmQec4AG.js";
29
+ import { n as canShareTurn, t as canJoinTurn } from "./attempt-selection-ClP3MMPr.js";
30
+ import { p as webMessageId } from "./reporting-window-DopzcOHh.js";
31
+ import { D as readAutomationTitlesByConversationId, _ as markDispatchRunning, a as getDispatchConversationId, c as getDispatchRecord, d as isTerminalDispatchStatus, g as markDispatchFailed, h as markDispatchCompleted, l as getDispatchTurnId, m as markDispatchBlocked, n as claimDispatchMailboxAppend, p as markDispatchAwaitingResume, r as confirmDispatchMailboxAppend, s as getDispatchInputMessageId } from "./store-m5bmdmsP.js";
32
+ import { l as conversationPendingMessagesReportSchema, n as conversationFeedSchema, p as healthReportSchema, t as conversationFeedBriefSchema } from "./conversation-feed-BSMlGZnS.js";
33
+ import { i as enqueueAgentInvocationResult, n as createDeliverToParent, s as withAgentInvocationResultActors, t as createChildConversationWorker } from "./result-CAujiaci.js";
34
+ import { a as withTurnSpan, i as turnInputTelemetry, n as createConversationTurnWorker, o as canPauseConversationDelivery, r as getTurnInputSpanAttributes } from "./conversation-turn-CZWBr091.js";
35
+ import { t as bindMessageAgent } from "./message-BOZEIuxy.js";
36
+ import { r as readConversationLineage, t as bindSpawnAgent } from "./spawn-CwMjRRtn.js";
37
+ import { n as scheduleSessionCompletedPluginTasks } from "./task-runner-COOwR8qm.js";
38
+ import { a as requireTurnFailureEventId, c as buildDeliveredTurnStatePatch, i as getAgentTurnDiagnosticsAttributes, l as loadPendingMessageCards, n as loadThreadContextTrimFloor, o as completeAuthPauseTurn, r as finalizeFailedTurnReplyWithEvent, s as persistAuthPauseTurnState, t as buildTurnThreadContext } from "./thread-context-Cd44z_W5.js";
30
39
  import { createHash, createHmac, timingSafeEqual } from "node:crypto";
31
40
  import * as z from "zod";
32
- import { and, asc, count, desc, eq, gt, inArray, isNotNull, isNull, lte, max, ne, or, sql } from "drizzle-orm";
41
+ import { and, asc, count, desc, eq, gt, inArray, isNotNull, isNull, lte, ne, or, sql } from "drizzle-orm";
33
42
  import { conversationSidebarAnnotationSchema, createSlackSource, objectTypeSchema } from "@sentry/junior-plugin-api";
34
43
  import { alias } from "drizzle-orm/pg-core";
35
44
  import { Message, ThreadImpl, stringifyMarkdown } from "chat";
@@ -102,16 +111,27 @@ async function enqueueAgentDispatch(dispatch, options) {
102
111
  const nowMs = options.nowMs ?? Date.now();
103
112
  const claimedDispatch = await claimDispatchMailboxAppend(dispatch.id);
104
113
  if (!claimedDispatch) return;
105
- await (options.conversationStore ?? getConversationStore()).recordActivity({
114
+ const conversationStore = options.conversationStore ?? getConversationStore();
115
+ const conversationId = getDispatchConversationId(claimedDispatch);
116
+ const destination = claimedDispatch.destination;
117
+ await conversationStore.recordActivity({
106
118
  activityAtMs: claimedDispatch.createdAtMs,
107
- conversationId: getDispatchConversationId(claimedDispatch),
108
- destination: claimedDispatch.destination,
119
+ conversationId,
120
+ destination,
109
121
  kind: isAutomationRun(claimedDispatch) ? "automation" : "root",
110
122
  nowMs,
111
123
  source: "plugin",
112
124
  sessionSource: claimedDispatch.source,
113
125
  ...claimedDispatch.title ? { title: claimedDispatch.title } : void 0
114
126
  });
127
+ if (destination.platform === "slack" && destination.threadTs) await conversationStore.claimProviderConversation({
128
+ atMs: nowMs,
129
+ conversationId,
130
+ provider: "slack",
131
+ providerDestinationId: destination.channelId,
132
+ providerTenantId: destination.teamId,
133
+ providerConversationId: destination.threadTs
134
+ });
115
135
  await appendAndEnqueueInboundMessage({
116
136
  message: buildAgentDispatchInboundMessage(claimedDispatch, nowMs, await resolveActorIdentityId(getSqlExecutor(), claimedDispatch.actor)),
117
137
  conversationStore: options.conversationStore,
@@ -1701,6 +1721,7 @@ async function stopConversation(args) {
1701
1721
  nowMs: stoppedAtMs,
1702
1722
  state: args.state
1703
1723
  });
1724
+ await dropOwnUnreadLoopReplies(args.conversationId, args.state);
1704
1725
  await cancelSignInWait(args.conversationId);
1705
1726
  const result = await stopConversationWork({
1706
1727
  conversationId: args.conversationId,
@@ -4232,6 +4253,32 @@ async function maybeApplyProviderDefaultConfigRequest(args) {
4232
4253
  });
4233
4254
  return { text: `Default GitHub repo set to \`${repo}\`.` };
4234
4255
  }
4256
+ // src/chat/automation-result.ts
4257
+ /**
4258
+ * Return the text to post after a run ends, if any. A chat Turn already
4259
+ * delivered a successful reply, so it posts only its failure reply. An
4260
+ * Automation run posts only its `reply` text. It never posts a failure
4261
+ * reply to its outcomes. The failed execution shows on the Automation.
4262
+ */
4263
+ function finishedRunReply(result, dispatch) {
4264
+ if (!dispatch?.declaresResult) return result.diagnostics.outcome === "success" ? void 0 : result.text;
4265
+ return result.diagnostics.outcome === "success" && dispatch.outcomes?.length !== 0 ? result.reply?.text : void 0;
4266
+ }
4267
+ /**
4268
+ * Map one finished agent run to its dispatch outcome. A blocked report
4269
+ * becomes a blocked dispatch with the reported reason.
4270
+ */
4271
+ function runDispatchOutcome(result) {
4272
+ if (result.diagnostics.outcome !== "success") return {
4273
+ errorMessage: result.diagnostics.errorMessage ?? `Agent turn ended with ${result.diagnostics.outcome}.`,
4274
+ outcome: "failed"
4275
+ };
4276
+ if (result.blocked) return {
4277
+ errorMessage: result.blocked.missing,
4278
+ outcome: "blocked"
4279
+ };
4280
+ return { outcome: "completed" };
4281
+ }
4235
4282
  // src/chat/providers/slack/input.ts
4236
4283
  /** Return the actor stored with one inbound Slack message. */
4237
4284
  function inboundMessageActor(queued) {
@@ -4720,7 +4767,7 @@ function createSlackTurn(deps) {
4720
4767
  slackMessageTs.push(...messageIds);
4721
4768
  messageDestinations.push(...messageIds.map((messageId) => ({
4722
4769
  destination: outcome.destination,
4723
- messageId
4770
+ messageId: outcome.destination.threadTs ?? messageId
4724
4771
  })));
4725
4772
  }
4726
4773
  else {
@@ -6751,16 +6798,20 @@ function createConversationWork(options) {
6751
6798
  queue: options.queue,
6752
6799
  state: options.state
6753
6800
  });
6801
+ const conversationTurnWorker = createConversationTurnWorker(options.agentRunner, createSlackSystemTurnDelivery({
6802
+ getSlackAdapter: options.getSlackAdapter,
6803
+ state: options.state
6804
+ }), createDeliverToParent({
6805
+ queue: options.queue,
6806
+ state: options.state
6807
+ }));
6754
6808
  const childWorker = createChildConversationWorker(options.agentRunner, {
6755
6809
  enqueueResult,
6756
6810
  maxAgentDepth: botConfig.maxAgentDepth,
6757
6811
  queue: options.queue,
6812
+ runTurn: conversationTurnWorker,
6758
6813
  state: options.state
6759
6814
  });
6760
- const conversationTurnWorker = createConversationTurnWorker(options.agentRunner, createSlackSystemTurnDelivery({
6761
- getSlackAdapter: options.getSlackAdapter,
6762
- state: options.state
6763
- }));
6764
6815
  const destinationWorker = async (context) => {
6765
6816
  const destination = context.destination;
6766
6817
  if (!destination) throw new Error(`Conversation ${context.conversationId} is missing a destination`);
@@ -6786,16 +6837,7 @@ function createConversationWork(options) {
6786
6837
  if ("skipped" in stopped) return stopped.skipped;
6787
6838
  const { context } = stopped;
6788
6839
  const conversation = await options.conversationStore.get({ conversationId: context.conversationId });
6789
- if (conversation?.kind === "thread") {
6790
- const threadTurn = await resolveThreadTurnWork(context);
6791
- if (!threadTurn) return await childWorker(context);
6792
- if (threadTurn.kind === "mailbox") await endActiveAgentInvocations(context.conversationId, {
6793
- enqueueResult,
6794
- errorMessage: "A person sent a Message in this Thread, so this task ended without a result. Send messageAgent again if you still need this work."
6795
- });
6796
- return await conversationTurnWorker(context, threadTurn);
6797
- }
6798
- if (conversation?.parentConversationId) return await childWorker(context);
6840
+ if (!isTopLevelKind(conversation?.kind ?? "root")) return await childWorker(context);
6799
6841
  const readStopSignal = context.stopSignal;
6800
6842
  let stopSignal;
6801
6843
  const stopLateChildAgents = async () => {
@@ -7619,21 +7661,18 @@ async function copyForkEvents(args) {
7619
7661
  } 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);
7620
7662
  }
7621
7663
  if (!seqs.length) return;
7622
- await getSqlExecutor().db().execute(sql`insert into ${e} (${sql.join([
7623
- e.conversationId,
7624
- e.seq,
7625
- e.historyVersion,
7626
- e.schemaVersion,
7627
- e.idempotencyKey,
7628
- e.type,
7629
- e.payload,
7630
- e.actorIdentityId,
7631
- e.createdAt
7632
- ].map((column) => sql.identifier(column.name)), sql`, `)})
7633
- select ${args.conversationId}, ${e.seq}, least(${e.historyVersion}, ${historyVersion}), ${e.schemaVersion}, ${e.idempotencyKey}, ${e.type}, ${e.payload}, ${e.actorIdentityId}, ${e.createdAt}
7634
- from ${e}
7635
- where ${e.conversationId} = ${args.sourceConversationId}
7636
- and ${inArray(e.seq, seqs)}`);
7664
+ const db = getSqlExecutor().db();
7665
+ await db.insert(e).select(db.select({
7666
+ conversationId: sql`${args.conversationId}`.as("conversation_id"),
7667
+ seq: e.seq,
7668
+ historyVersion: sql`least(${e.historyVersion}, ${historyVersion})`.as("history_version"),
7669
+ schemaVersion: e.schemaVersion,
7670
+ idempotencyKey: e.idempotencyKey,
7671
+ type: e.type,
7672
+ payload: e.payload,
7673
+ actorIdentityId: e.actorIdentityId,
7674
+ createdAt: e.createdAt
7675
+ }).from(e).where(and(eq(e.conversationId, args.sourceConversationId), inArray(e.seq, seqs))));
7637
7676
  }
7638
7677
  function hasUnfinishedToolCalls(messages) {
7639
7678
  const pending = /* @__PURE__ */ new Set();
@@ -7909,146 +7948,6 @@ async function readFirstHumanMessageTexts(db, conversations) {
7909
7948
  }).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));
7910
7949
  return new Map(rows.map((row) => [row.conversationId, row.text]));
7911
7950
  }
7912
- // src/api/conversations/mentions.ts
7913
- /** Text in one event that the dashboard renders with mentions. */
7914
- function eventMentionTexts(data) {
7915
- switch (data.type) {
7916
- case "message": return data.redacted ? [] : [
7917
- data.text,
7918
- data.trustedSummary,
7919
- ...(data.events ?? []).map((event) => event.trustedSummary)
7920
- ];
7921
- case "assistant_message": return data.parts.map((part) => part.text);
7922
- case "compaction": return [data.summary];
7923
- case "structured_event": return [data.presentation.preview, ...(data.presentation.details ?? []).map((detail) => detail.description)];
7924
- default: return [];
7925
- }
7926
- }
7927
- function briefMentionTexts(brief) {
7928
- return [
7929
- brief.summary,
7930
- brief.intent,
7931
- brief.outcome.text,
7932
- ...brief.decisions.flatMap((decision) => [decision.text, decision.by]),
7933
- ...brief.facts
7934
- ];
7935
- }
7936
- function withMentions(value, mentions) {
7937
- return mentions.length > 0 ? {
7938
- ...value,
7939
- mentions
7940
- } : value;
7941
- }
7942
- /**
7943
- * Attach the people that each event and the Brief of one conversation
7944
- * mention, resolved at read time.
7945
- */
7946
- async function attachConversationMentions(executor, conversationId, content) {
7947
- const tenantId = (await loadConversationSlackTenantIds(executor, [conversationId])).get(conversationId);
7948
- const sources = content.events.map((event) => ({
7949
- tenantId,
7950
- texts: eventMentionTexts(event.data)
7951
- }));
7952
- if (content.brief) sources.push({
7953
- tenantId,
7954
- texts: briefMentionTexts(content.brief)
7955
- });
7956
- const mentions = await resolveMentions(executor, sources);
7957
- return {
7958
- briefMentions: content.brief ? mentions.at(-1) : [],
7959
- events: content.events.map((event, index) => withMentions(event, mentions[index]))
7960
- };
7961
- }
7962
- /** Attach the people that each activity preview mentions, resolved at read time. */
7963
- async function attachActivityPreviewMentions(executor, previews) {
7964
- const entries = [...previews];
7965
- const tenants = await loadConversationSlackTenantIds(executor, entries.map(([conversationId]) => conversationId));
7966
- const mentions = await resolveMentions(executor, entries.map(([conversationId, preview]) => ({
7967
- tenantId: tenants.get(conversationId),
7968
- texts: [preview.text]
7969
- })));
7970
- return new Map(entries.map(([conversationId, preview], index) => [conversationId, withMentions(preview, mentions[index])]));
7971
- }
7972
- // src/api/conversations/record.ts
7973
- /** The columns of one Conversation record, for `selectConversationRecords`. */
7974
- const conversationRecordColumns = {
7975
- conversation: juniorConversations,
7976
- location: juniorDestinations,
7977
- identityDisplayName: juniorIdentities.displayName,
7978
- identityEmail: juniorIdentities.email,
7979
- identityHandle: juniorIdentities.handle,
7980
- identityProvider: juniorIdentities.provider,
7981
- identitySubjectId: juniorIdentities.providerSubjectId,
7982
- identityTenantId: juniorIdentities.providerTenantId,
7983
- userDisplayName: juniorUsers.displayName
7984
- };
7985
- /** Left-join conditions from a Conversation to its record tables. */
7986
- const conversationRecordJoins = {
7987
- location: eq(juniorDestinations.id, juniorConversations.destinationId),
7988
- identity: eq(juniorIdentities.id, juniorConversations.actorIdentityId),
7989
- user: eq(juniorUsers.id, juniorIdentities.userId)
7990
- };
7991
- /**
7992
- * Select Conversation rows with their Location and Actor names. Callers add
7993
- * the filter, order, and limit.
7994
- */
7995
- function selectConversationRecords(db) {
7996
- return db.select(conversationRecordColumns).from(juniorConversations).leftJoin(juniorDestinations, conversationRecordJoins.location).leftJoin(juniorIdentities, conversationRecordJoins.identity).leftJoin(juniorUsers, conversationRecordJoins.user);
7997
- }
7998
- /** Decode a conversation row with the linked user name and identity-scoped provider fields. */
7999
- function conversationFromRecordRow(row) {
8000
- const value = row.conversation;
8001
- const legacySessionSource = value.sessionSource === null ? void 0 : parseSessionSource(value.sessionSource);
8002
- if (value.sessionSource !== null && !legacySessionSource) throw new Error("Conversation legacy source_json is invalid");
8003
- const actorFullName = row.userDisplayName?.trim() ? row.userDisplayName : row.identityDisplayName;
8004
- const actor = row.identityProvider === "slack" ? {
8005
- platform: "slack",
8006
- ...row.identityEmail ? { email: row.identityEmail } : void 0,
8007
- ...actorFullName ? { fullName: actorFullName } : void 0,
8008
- ...row.identitySubjectId ? { slackUserId: row.identitySubjectId } : void 0,
8009
- ...row.identityHandle ? { slackUserName: row.identityHandle } : void 0,
8010
- ...row.identityTenantId ? { teamId: row.identityTenantId } : void 0
8011
- } : void 0;
8012
- const location = locationFromRow(value.location, row.location, legacySessionSource);
8013
- return {
8014
- schemaVersion: 1,
8015
- conversationId: value.conversationId,
8016
- createdAtMs: value.createdAt.getTime(),
8017
- kind: conversationKindFromRow(value),
8018
- lastActivityAtMs: value.lastActivityAt.getTime(),
8019
- updatedAtMs: value.updatedAt.getTime(),
8020
- execution: {
8021
- status: value.executionStatus,
8022
- ...value.runId ? { runId: value.runId } : void 0,
8023
- ...value.executionUpdatedAt ? { updatedAtMs: value.executionUpdatedAt.getTime() } : void 0
8024
- },
8025
- ...value.parentConversationId ? { parentConversationId: value.parentConversationId } : void 0,
8026
- ...value.archivedAt ? { archivedAtMs: value.archivedAt.getTime() } : void 0,
8027
- ...actor ? { actor } : void 0,
8028
- ...location ? { location } : void 0,
8029
- ...value.channelName ? { channelName: value.channelName } : void 0,
8030
- ...value.source ? { source: value.source } : void 0,
8031
- ...value.title ? { title: value.title } : void 0,
8032
- ...value.transcriptPurgedAt ? { transcriptPurgedAtMs: value.transcriptPurgedAt.getTime() } : void 0,
8033
- ...value.stoppedAt ? { stoppedAtMs: value.stoppedAt.getTime() } : void 0,
8034
- ...value.deliveryPausedAt ? { deliveryPausedAtMs: value.deliveryPausedAt.getTime() } : void 0
8035
- };
8036
- }
8037
- /** Decode one `selectConversationRecords` row into a Conversation record. */
8038
- function conversationRecordFromRow(row) {
8039
- return {
8040
- conversation: conversationFromRecordRow(row),
8041
- durationMs: row.conversation.durationMs,
8042
- ...row.location?.visibility === "public" ? { locationId: row.location.id } : void 0,
8043
- usage: row.conversation.usage,
8044
- rootConversationId: row.conversation.rootConversationId
8045
- };
8046
- }
8047
- /** Read one normalized conversation record directly from its SQL row. */
8048
- async function readConversationRecordFromSql(conversationId) {
8049
- const row = (await selectConversationRecords(getDb()).where(eq(juniorConversations.conversationId, conversationId)).limit(1))[0];
8050
- return row ? conversationRecordFromRow(row) : void 0;
8051
- }
8052
7951
  // src/api/conversations/shared.ts
8053
7952
  /** Format a Slack destination without exposing private channel names. */
8054
7953
  function slackStatsLocationLabel(input) {
@@ -8179,7 +8078,6 @@ function conversationSummaryFromStoredConversation(args) {
8179
8078
  const channelName = channelNameFromConversation(conversation, canViewPrivateContent, visibility);
8180
8079
  const channelNameRedacted = channelNameRedactedFromConversation(conversation, canViewPrivateContent);
8181
8080
  const status = statusFromConversation(conversation);
8182
- const unread = (status === "completed" || status === "stopped") && args.unreadReply === true;
8183
8081
  return {
8184
8082
  conversationId: conversation.conversationId,
8185
8083
  cumulativeDurationMs: durationMs,
@@ -8208,13 +8106,202 @@ function conversationSummaryFromStoredConversation(args) {
8208
8106
  archivedAt: conversation.archivedAtMs === void 0 ? null : new Date(conversation.archivedAtMs).toISOString(),
8209
8107
  pinnedAt: args.pinnedAtMs === void 0 ? null : new Date(args.pinnedAtMs).toISOString(),
8210
8108
  ...args.pinPosition === void 0 ? void 0 : { pinPosition: args.pinPosition },
8211
- ...unread ? { unread: true } : void 0,
8212
8109
  ...slackThread ? { channel: slackThread.channelId } : void 0,
8213
8110
  ...channelName ? { channelName } : void 0,
8214
8111
  ...channelNameRedacted ? { channelNameRedacted: true } : void 0,
8215
8112
  ...args.locationId && !channelNameRedacted ? { locationId: args.locationId } : void 0
8216
8113
  };
8217
8114
  }
8115
+ // src/api/conversations/agent-tree.ts
8116
+ /** Name a child the viewer cannot read, or one with no agent label. */
8117
+ function childLabel(kind) {
8118
+ return kind === "thread" ? "Thread" : "Task";
8119
+ }
8120
+ /**
8121
+ * Read the agent tree of a child Conversation: its parent chain, root first,
8122
+ * with the child last. Returns undefined for a root Conversation. Each
8123
+ * Conversation has its own access check, so a viewer sees a label only where
8124
+ * they can see private content.
8125
+ */
8126
+ async function readConversationAgentTree(conversation, readAccess) {
8127
+ if (!conversation.parentConversationId) return;
8128
+ const lineage = (await readConversationLineage(conversation.conversationId)).slice(-16);
8129
+ if (lineage.length < 2) return;
8130
+ const ids = lineage.map((entry) => entry.conversationId);
8131
+ const kindById = new Map(lineage.map((entry) => [entry.conversationId, entry.kind]));
8132
+ const root = lineage[0].parentConversationId ? void 0 : await getConversationStore().get({ conversationId: ids[0] });
8133
+ const [access, automationTitleByConversation, firstHumanMessageTextByConversation] = await Promise.all([
8134
+ readAccess(ids),
8135
+ readAutomationTitlesByConversationId(root ? [root] : []),
8136
+ readFirstHumanMessageTexts(getDb(), root ? [root] : [])
8137
+ ]);
8138
+ return await Promise.all(ids.map(async (id) => {
8139
+ const itemAccess = access.get(id);
8140
+ if (root?.conversationId === id) return {
8141
+ conversationId: id,
8142
+ kind: "root",
8143
+ label: conversationSummaryFromStoredConversation({
8144
+ access: itemAccess,
8145
+ automationTitle: automationTitleByConversation.get(id),
8146
+ conversation: root,
8147
+ durationMs: 0,
8148
+ firstHumanMessageText: firstHumanMessageTextByConversation.get(id)
8149
+ }).displayTitle
8150
+ };
8151
+ const kind = kindById.get(id);
8152
+ if (!itemAccess?.canViewPrivateContent) return {
8153
+ conversationId: id,
8154
+ kind,
8155
+ label: childLabel(kind)
8156
+ };
8157
+ const agent = await getChildAgentLabel(id);
8158
+ return {
8159
+ conversationId: id,
8160
+ kind,
8161
+ label: agent?.title ?? agent?.agentName ?? childLabel(kind)
8162
+ };
8163
+ }));
8164
+ }
8165
+ // src/api/conversations/mentions.ts
8166
+ /** Text in one event that the dashboard renders with mentions. */
8167
+ function eventMentionTexts(data) {
8168
+ switch (data.type) {
8169
+ case "message": return data.redacted ? [] : [
8170
+ data.text,
8171
+ data.trustedSummary,
8172
+ ...(data.events ?? []).map((event) => event.trustedSummary)
8173
+ ];
8174
+ case "assistant_message": return data.parts.map((part) => part.text);
8175
+ case "compaction": return [data.summary];
8176
+ case "structured_event": return [data.presentation.preview, ...(data.presentation.details ?? []).map((detail) => detail.description)];
8177
+ default: return [];
8178
+ }
8179
+ }
8180
+ function briefMentionTexts(brief) {
8181
+ return [
8182
+ brief.summary,
8183
+ brief.intent,
8184
+ brief.outcome.text,
8185
+ ...brief.decisions.flatMap((decision) => [decision.text, decision.by]),
8186
+ ...brief.facts
8187
+ ];
8188
+ }
8189
+ function withMentions(value, mentions) {
8190
+ return mentions.length > 0 ? {
8191
+ ...value,
8192
+ mentions
8193
+ } : value;
8194
+ }
8195
+ /**
8196
+ * Attach the people that each event and the Brief of one conversation
8197
+ * mention, resolved at read time.
8198
+ */
8199
+ async function attachConversationMentions(executor, conversationId, content) {
8200
+ const tenantId = (await loadConversationSlackTenantIds(executor, [conversationId])).get(conversationId);
8201
+ const sources = content.events.map((event) => ({
8202
+ tenantId,
8203
+ texts: eventMentionTexts(event.data)
8204
+ }));
8205
+ if (content.brief) sources.push({
8206
+ tenantId,
8207
+ texts: briefMentionTexts(content.brief)
8208
+ });
8209
+ const mentions = await resolveMentions(executor, sources);
8210
+ return {
8211
+ briefMentions: content.brief ? mentions.at(-1) : [],
8212
+ events: content.events.map((event, index) => withMentions(event, mentions[index]))
8213
+ };
8214
+ }
8215
+ /** Attach the people that each activity preview mentions, resolved at read time. */
8216
+ async function attachActivityPreviewMentions(executor, previews) {
8217
+ const entries = [...previews];
8218
+ const tenants = await loadConversationSlackTenantIds(executor, entries.map(([conversationId]) => conversationId));
8219
+ const mentions = await resolveMentions(executor, entries.map(([conversationId, preview]) => ({
8220
+ tenantId: tenants.get(conversationId),
8221
+ texts: [preview.text]
8222
+ })));
8223
+ return new Map(entries.map(([conversationId, preview], index) => [conversationId, withMentions(preview, mentions[index])]));
8224
+ }
8225
+ // src/api/conversations/record.ts
8226
+ /** The columns of one Conversation record, for `selectConversationRecords`. */
8227
+ const conversationRecordColumns = {
8228
+ conversation: juniorConversations,
8229
+ location: juniorDestinations,
8230
+ identityDisplayName: juniorIdentities.displayName,
8231
+ identityEmail: juniorIdentities.email,
8232
+ identityHandle: juniorIdentities.handle,
8233
+ identityProvider: juniorIdentities.provider,
8234
+ identitySubjectId: juniorIdentities.providerSubjectId,
8235
+ identityTenantId: juniorIdentities.providerTenantId,
8236
+ userDisplayName: juniorUsers.displayName
8237
+ };
8238
+ /** Left-join conditions from a Conversation to its record tables. */
8239
+ const conversationRecordJoins = {
8240
+ location: eq(juniorDestinations.id, juniorConversations.destinationId),
8241
+ identity: eq(juniorIdentities.id, juniorConversations.actorIdentityId),
8242
+ user: eq(juniorUsers.id, juniorIdentities.userId)
8243
+ };
8244
+ /**
8245
+ * Select Conversation rows with their Location and Actor names. Callers add
8246
+ * the filter, order, and limit.
8247
+ */
8248
+ function selectConversationRecords(db) {
8249
+ return db.select(conversationRecordColumns).from(juniorConversations).leftJoin(juniorDestinations, conversationRecordJoins.location).leftJoin(juniorIdentities, conversationRecordJoins.identity).leftJoin(juniorUsers, conversationRecordJoins.user);
8250
+ }
8251
+ /** Decode a conversation row with the linked user name and identity-scoped provider fields. */
8252
+ function conversationFromRecordRow(row) {
8253
+ const value = row.conversation;
8254
+ const legacySessionSource = value.sessionSource === null ? void 0 : parseSessionSource(value.sessionSource);
8255
+ if (value.sessionSource !== null && !legacySessionSource) throw new Error("Conversation legacy source_json is invalid");
8256
+ const actorFullName = row.userDisplayName?.trim() ? row.userDisplayName : row.identityDisplayName;
8257
+ const actor = row.identityProvider === "slack" ? {
8258
+ platform: "slack",
8259
+ ...row.identityEmail ? { email: row.identityEmail } : void 0,
8260
+ ...actorFullName ? { fullName: actorFullName } : void 0,
8261
+ ...row.identitySubjectId ? { slackUserId: row.identitySubjectId } : void 0,
8262
+ ...row.identityHandle ? { slackUserName: row.identityHandle } : void 0,
8263
+ ...row.identityTenantId ? { teamId: row.identityTenantId } : void 0
8264
+ } : void 0;
8265
+ const location = locationFromRow(value.location, row.location, legacySessionSource);
8266
+ return {
8267
+ schemaVersion: 1,
8268
+ conversationId: value.conversationId,
8269
+ createdAtMs: value.createdAt.getTime(),
8270
+ kind: conversationKindFromRow(value),
8271
+ lastActivityAtMs: value.lastActivityAt.getTime(),
8272
+ updatedAtMs: value.updatedAt.getTime(),
8273
+ execution: {
8274
+ status: value.executionStatus,
8275
+ ...value.runId ? { runId: value.runId } : void 0,
8276
+ ...value.executionUpdatedAt ? { updatedAtMs: value.executionUpdatedAt.getTime() } : void 0
8277
+ },
8278
+ ...value.parentConversationId ? { parentConversationId: value.parentConversationId } : void 0,
8279
+ ...value.archivedAt ? { archivedAtMs: value.archivedAt.getTime() } : void 0,
8280
+ ...actor ? { actor } : void 0,
8281
+ ...location ? { location } : void 0,
8282
+ ...value.channelName ? { channelName: value.channelName } : void 0,
8283
+ ...value.source ? { source: value.source } : void 0,
8284
+ ...value.title ? { title: value.title } : void 0,
8285
+ ...value.transcriptPurgedAt ? { transcriptPurgedAtMs: value.transcriptPurgedAt.getTime() } : void 0,
8286
+ ...value.stoppedAt ? { stoppedAtMs: value.stoppedAt.getTime() } : void 0,
8287
+ ...value.deliveryPausedAt ? { deliveryPausedAtMs: value.deliveryPausedAt.getTime() } : void 0
8288
+ };
8289
+ }
8290
+ /** Decode one `selectConversationRecords` row into a Conversation record. */
8291
+ function conversationRecordFromRow(row) {
8292
+ return {
8293
+ conversation: conversationFromRecordRow(row),
8294
+ durationMs: row.conversation.durationMs,
8295
+ ...row.location?.visibility === "public" ? { locationId: row.location.id } : void 0,
8296
+ usage: row.conversation.usage,
8297
+ rootConversationId: row.conversation.rootConversationId
8298
+ };
8299
+ }
8300
+ /** Read one normalized conversation record directly from its SQL row. */
8301
+ async function readConversationRecordFromSql(conversationId) {
8302
+ const row = (await selectConversationRecords(getDb()).where(eq(juniorConversations.conversationId, conversationId)).limit(1))[0];
8303
+ return row ? conversationRecordFromRow(row) : void 0;
8304
+ }
8218
8305
  // src/api/conversations/event-list.ts
8219
8306
  /** Read one bounded page of reporting events before, after, or around a boundary. */
8220
8307
  async function readConversationEvents(conversationId, boundary, options = {}) {
@@ -8295,56 +8382,6 @@ async function conversationEventPageReport(executor, args) {
8295
8382
  generatedAt: (/* @__PURE__ */ new Date()).toISOString()
8296
8383
  };
8297
8384
  }
8298
- // src/api/conversations/agent-tree.ts
8299
- /** Name a child the viewer cannot read, or one with no agent label. */
8300
- function childLabel(kind) {
8301
- return kind === "thread" ? "Thread" : "Task";
8302
- }
8303
- /**
8304
- * Read the agent tree of a child Conversation: its parent chain, root first,
8305
- * with the child last. Returns undefined for a root Conversation. Each
8306
- * Conversation has its own access check, so a viewer sees a label only where
8307
- * they can see private content.
8308
- */
8309
- async function readConversationAgentTree(conversation, readAccess) {
8310
- if (!conversation.parentConversationId) return;
8311
- const lineage = (await readConversationLineage(conversation.conversationId)).slice(-16);
8312
- if (lineage.length < 2) return;
8313
- const ids = lineage.map((entry) => entry.conversationId);
8314
- const kindById = new Map(lineage.map((entry) => [entry.conversationId, entry.kind]));
8315
- const root = lineage[0].parentConversationId ? void 0 : await getConversationStore().get({ conversationId: ids[0] });
8316
- const [access, automationTitleByConversation, firstHumanMessageTextByConversation] = await Promise.all([
8317
- readAccess(ids),
8318
- readAutomationTitlesByConversationId(root ? [root] : []),
8319
- readFirstHumanMessageTexts(getDb(), root ? [root] : [])
8320
- ]);
8321
- return await Promise.all(ids.map(async (id) => {
8322
- const itemAccess = access.get(id);
8323
- if (root?.conversationId === id) return {
8324
- conversationId: id,
8325
- kind: "root",
8326
- label: conversationSummaryFromStoredConversation({
8327
- access: itemAccess,
8328
- automationTitle: automationTitleByConversation.get(id),
8329
- conversation: root,
8330
- durationMs: 0,
8331
- firstHumanMessageText: firstHumanMessageTextByConversation.get(id)
8332
- }).displayTitle
8333
- };
8334
- const kind = kindById.get(id);
8335
- if (!itemAccess?.canViewPrivateContent) return {
8336
- conversationId: id,
8337
- kind,
8338
- label: childLabel(kind)
8339
- };
8340
- const agent = await getChildAgentLabel(id);
8341
- return {
8342
- conversationId: id,
8343
- kind,
8344
- label: agent?.title ?? agent?.agentName ?? childLabel(kind)
8345
- };
8346
- }));
8347
- }
8348
8385
  // src/api/conversations/fork.ts
8349
8386
  /** Fork a Conversation that the viewer can read into a new root they own. */
8350
8387
  async function forkConversationForViewer(viewer, sourceConversationId, body) {
@@ -8391,107 +8428,22 @@ async function readConversationForks(conversationId, links, readAccess) {
8391
8428
  } : void 0
8392
8429
  };
8393
8430
  }
8394
- // src/api/conversations/unread.ts
8395
- /**
8396
- * Junior's newest reply in the outer Conversation that the transcript shows
8397
- * as its own row. Quiet replies fold into activity, like tools and status
8398
- * events, so they do not count. It walks the message role index from the
8399
- * newest Message, so it stops at the first reply that is not quiet.
8400
- */
8401
- function latestVisibleReply(db, conversationId) {
8402
- return db.select({ seq: juniorConversationEvents.seq }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "message"), sql`${juniorConversationEvents.payload}->>'role' = 'assistant'`, sql`(${juniorConversationEvents.payload}->'meta'->>'quiet') is distinct from 'true'`)).orderBy(desc(juniorConversationEvents.createdAt), desc(juniorConversationEvents.seq)).limit(1);
8403
- }
8404
- /** The seq of the user's latest Message in the outer Conversation. */
8405
- function viewerMessageSeq(db, userId, conversationId) {
8406
- return db.select({ seq: max(juniorConversationEvents.seq) }).from(juniorConversationEvents).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversationEvents.actorIdentityId)).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "message"), eq(juniorIdentities.userId, userId)));
8407
- }
8408
- /**
8409
- * Whether Junior's latest visible reply is after the viewer's read position
8410
- * in one outer Conversation. The position is at least the viewer's own
8411
- * latest Message. No reply reads as false.
8412
- */
8413
- function unreadReplySql(db, userId, conversationId, lastReadSeq) {
8414
- return sql`coalesce((${latestVisibleReply(db, conversationId)}) > greatest(coalesce(${lastReadSeq}, -1), coalesce((${viewerMessageSeq(db, userId, conversationId)}), -1)), false)`;
8415
- }
8416
- /**
8417
- * Return the Conversations that have a visible Junior reply after the
8418
- * user's read position. The position is at least the user's own latest
8419
- * Message, so a reply in Slack or the dashboard counts as read.
8420
- *
8421
- * A Conversation with no stored read position counts from its start. The
8422
- * read-position backfill migration gave each root in a user's feed a
8423
- * position at its last event, so only Conversations that start after it
8424
- * have none.
8425
- */
8426
- async function readUnreadConversationIds(db, conversationIds, userId) {
8427
- if (conversationIds.length === 0) return /* @__PURE__ */ new Set();
8428
- const rows = await db.select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).leftJoin(juniorConversationReadPositions, and(eq(juniorConversationReadPositions.conversationId, juniorConversations.conversationId), eq(juniorConversationReadPositions.userId, userId))).where(and(inArray(juniorConversations.conversationId, [...conversationIds]), unreadReplySql(db, userId, juniorConversations.conversationId, juniorConversationReadPositions.lastReadSeq)));
8429
- return new Set(rows.map((row) => row.conversationId));
8430
- }
8431
- /**
8432
- * Store a read report and say whether Junior's latest visible reply is still
8433
- * unread, so the dashboard can clear its unread flag without a refetch.
8434
- *
8435
- * Only a viewer who may read the transcript can report: a participant, or
8436
- * anyone for a public Conversation. Others get the same 404 as a missing
8437
- * Conversation.
8438
- */
8439
- async function reportConversationRead(viewer, conversationId, body) {
8440
- if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.canViewPrivateContent) throwApiError(404, "Conversation not found.");
8441
- const readPosition = await markConversationRead(viewer, conversationId, body);
8442
- const unread = await readUnreadConversationIds(getDb(), [conversationId], viewer.id);
8443
- return {
8444
- ...readPosition,
8445
- unreadReply: unread.has(conversationId)
8446
- };
8447
- }
8448
- /**
8449
- * Mark one Conversation read or unread for the signed-in viewer. Both write
8450
- * the read position of the root, which the feed reads.
8451
- *
8452
- * Read moves the position to the last event. Unread is the one write that
8453
- * moves it back: to just before Junior's latest visible reply, so the
8454
- * transcript shows that reply as new again. A reply at seq 0 has no seq
8455
- * before it, so unread removes the position and the Conversation counts from
8456
- * its start. The viewer's own latest Message also counts as read, so unread
8457
- * fails when that Message is after the reply.
8458
- */
8459
- async function markConversationUnread(viewer, conversationId, body) {
8460
- if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(404, "Conversation not found.");
8461
- const rootConversationId = await resolveRootConversationId(getSqlExecutor(), conversationId);
8462
- if (!body.unread) {
8463
- await markConversationRead(viewer, rootConversationId, { lastReadSeq: Number.MAX_SAFE_INTEGER });
8464
- return { unreadReply: false };
8465
- }
8466
- const db = getDb();
8467
- const reply = latestVisibleReply(db, juniorConversations.conversationId).as("latest_visible_reply");
8468
- const [row] = await db.select({
8469
- replySeq: reply.seq,
8470
- viewerSeq: sql`(${viewerMessageSeq(db, viewer.id, juniorConversations.conversationId)})`
8471
- }).from(juniorConversations).innerJoinLateral(reply, sql`true`).where(eq(juniorConversations.conversationId, rootConversationId));
8472
- if (!row || row.viewerSeq !== null && row.viewerSeq >= row.replySeq) throwApiError(409, "Conversation has no reply after your last message.");
8473
- if (row.replySeq === 0) {
8474
- await db.delete(juniorConversationReadPositions).where(and(eq(juniorConversationReadPositions.userId, viewer.id), eq(juniorConversationReadPositions.conversationId, rootConversationId)));
8475
- return { unreadReply: true };
8476
- }
8477
- await db.insert(juniorConversationReadPositions).values({
8478
- conversationId: rootConversationId,
8479
- lastReadSeq: row.replySeq - 1,
8480
- updatedAt: /* @__PURE__ */ new Date(),
8481
- userId: viewer.id
8482
- }).onConflictDoUpdate({
8483
- target: [juniorConversationReadPositions.userId, juniorConversationReadPositions.conversationId],
8484
- set: {
8485
- lastReadSeq: sql`excluded.last_read_seq`,
8486
- updatedAt: sql`excluded.updated_at`
8487
- }
8488
- });
8489
- return { unreadReply: true };
8490
- }
8491
8431
  // src/api/conversations/detail-etag.ts
8492
8432
  const detailViewer = alias(juniorUsers, "detail_viewer");
8493
8433
  const forkSource = alias(juniorConversations, "detail_fork_source");
8494
8434
  const fork = alias(juniorConversations, "detail_fork");
8435
+ const agentTreeRoot = alias(juniorConversations, "detail_agent_tree_root");
8436
+ /**
8437
+ * Return the root fields that label the agent tree of a child: its title and
8438
+ * channel name. The other labels cannot change once the child exists. An
8439
+ * agent invocation keeps its title and agent name after insert, and only the
8440
+ * spawn sets a title. Access to each node comes from the shared root, so the
8441
+ * viewer's access covers it. This keeps the recursive lineage read out of
8442
+ * every poll.
8443
+ */
8444
+ function agentTreeRootLabel(db, rootConversationId) {
8445
+ return db.select({ label: sql`row(${agentTreeRoot.title}, ${agentTreeRoot.channelName})::text` }).from(agentTreeRoot).where(eq(agentTreeRoot.conversationId, rootConversationId));
8446
+ }
8495
8447
  /**
8496
8448
  * Sum the detail versions of a Conversation and its child agents. Child
8497
8449
  * writes bump only their own row, and the row count changes when a child
@@ -8551,6 +8503,7 @@ async function readDetailStateRow(conversationId, viewer) {
8551
8503
  const viewerParticipant = viewer ? and(eq(juniorConversationParticipants.userId, viewer.id), eq(juniorConversationParticipants.rootConversationId, rootConversationId)) : sql`false`;
8552
8504
  const [row] = await db.select({
8553
8505
  ...conversationRecordColumns,
8506
+ agentTreeRootLabel: sql`case when ${juniorConversations.parentConversationId} is null then null else (${agentTreeRootLabel(db, rootConversationId)}) end`,
8554
8507
  attachmentsVersion: sql`(${slackAttachmentsVersionQuery(db, conversationId)})`,
8555
8508
  autoArchive: juniorConversationParticipants.autoArchive,
8556
8509
  autoArchiveDefault: detailViewer.autoArchiveDefault,
@@ -8561,7 +8514,6 @@ async function readDetailStateRow(conversationId, viewer) {
8561
8514
  pinnedAt: juniorConversationParticipants.pinnedAt,
8562
8515
  pinPosition: juniorConversationParticipants.pinPosition,
8563
8516
  rootConversationId,
8564
- unreadReply: viewer ? unreadReplySql(db, viewer.id, rootConversationId, sql`(${db.select({ seq: juniorConversationReadPositions.lastReadSeq }).from(juniorConversationReadPositions).where(and(eq(juniorConversationReadPositions.userId, viewer.id), eq(juniorConversationReadPositions.conversationId, rootConversationId)))})`) : sql`false`,
8565
8517
  unsubscribedAt: juniorConversationParticipants.unsubscribedAt,
8566
8518
  version: sql`(${conversationVersionQuery(db, conversationId, viewer?.id)})`
8567
8519
  }).from(juniorConversations).leftJoin(juniorDestinations, conversationRecordJoins.location).leftJoin(juniorIdentities, conversationRecordJoins.identity).leftJoin(juniorUsers, conversationRecordJoins.user).leftJoin(forkSource, eq(forkSource.conversationId, juniorConversations.forkedFromConversationId)).leftJoin(juniorConversationParticipants, viewerParticipant).leftJoin(detailViewer, viewer ? eq(detailViewer.id, viewer.id) : sql`false`).where(eq(juniorConversations.conversationId, conversationId));
@@ -8569,7 +8521,7 @@ async function readDetailStateRow(conversationId, viewer) {
8569
8521
  }
8570
8522
  async function readDetailState(conversationId, viewer, readAccess) {
8571
8523
  const rowRead = readDetailStateRow(conversationId, viewer);
8572
- const [accessById, row, forks, agentTree] = await Promise.all([
8524
+ const [accessById, row, forks] = await Promise.all([
8573
8525
  readAccess([conversationId]),
8574
8526
  rowRead,
8575
8527
  rowRead.then((stored) => readConversationForks(conversationId, {
@@ -8579,10 +8531,6 @@ async function readDetailState(conversationId, viewer, readAccess) {
8579
8531
  title: stored.forkSourceTitle
8580
8532
  } } : void 0,
8581
8533
  isChild: Boolean(stored?.conversation.parentConversationId)
8582
- }, readAccess)),
8583
- rowRead.then((stored) => readConversationAgentTree({
8584
- conversationId,
8585
- ...stored?.conversation.parentConversationId ? { parentConversationId: stored.conversation.parentConversationId } : void 0
8586
8534
  }, readAccess))
8587
8535
  ]);
8588
8536
  const access = accessById.get(conversationId);
@@ -8593,16 +8541,15 @@ async function readDetailState(conversationId, viewer, readAccess) {
8593
8541
  })).digest("base64url");
8594
8542
  const viewerMarks = row ? viewerMarksFromParticipant(row) : void 0;
8595
8543
  return {
8544
+ agentTreeRootLabel: row?.agentTreeRootLabel ?? void 0,
8596
8545
  record: row ? conversationRecordFromRow(row) : void 0,
8597
8546
  state: {
8598
8547
  access,
8599
- agentTree,
8600
8548
  ...viewer ? { autoArchive: row?.autoArchive ?? row?.autoArchiveDefault ?? false } : void 0,
8601
8549
  forks,
8602
8550
  ...row?.lastReadSeq != null ? { readPosition: { lastReadSeq: row.lastReadSeq } } : void 0,
8603
8551
  ...viewer ? { subscribed: !row?.unsubscribedAt } : void 0,
8604
8552
  transcriptVersion,
8605
- ...viewer && row ? { unreadReply: row.unreadReply } : void 0,
8606
8553
  ...viewerMarks ? { viewerMarks } : void 0
8607
8554
  },
8608
8555
  version: row?.version ?? void 0
@@ -8635,18 +8582,17 @@ async function readConversationDetailState(conversationId, viewer, readAccess) {
8635
8582
  * change or a reload.
8636
8583
  */
8637
8584
  async function readConversationDetailEtag(conversationId, options) {
8638
- const { record, state, version } = await readDetailState(conversationId, options.viewer, options.readAccess);
8585
+ const { agentTreeRootLabel, record, state, version } = await readDetailState(conversationId, options.viewer, options.readAccess);
8639
8586
  if (!version) return void 0;
8640
8587
  const basis = JSON.stringify({
8641
8588
  access: state.access ?? null,
8642
- agentTree: state.agentTree ?? null,
8589
+ agentTree: agentTreeRootLabel ?? null,
8643
8590
  autoArchive: state.autoArchive ?? null,
8644
8591
  forks: state.forks,
8645
8592
  junior: JUNIOR_VERSION,
8646
8593
  limit: options.limit ?? null,
8647
8594
  subscribed: state.subscribed ?? null,
8648
8595
  version,
8649
- unreadReply: state.unreadReply ?? false,
8650
8596
  viewerMarks: state.viewerMarks ?? null
8651
8597
  });
8652
8598
  return {
@@ -9029,7 +8975,6 @@ function projectConversationDetail(args) {
9029
8975
  ...conversationSummaryFromStoredConversation({
9030
8976
  access: args.access,
9031
8977
  pinnedAtMs: args.pinnedAtMs,
9032
- unreadReply: args.unreadReply,
9033
8978
  automationTitle: args.automationTitle,
9034
8979
  auxiliaryCosts: args.auxiliaryCosts,
9035
8980
  ...args.childAgentTotals ? { childAgentTotals: args.childAgentTotals } : void 0,
@@ -9071,7 +9016,8 @@ function projectConversationDetail(args) {
9071
9016
  };
9072
9017
  }
9073
9018
  async function readConversationDetailFromSql(conversationId, options) {
9074
- const { record, state } = options.stored ?? await readConversationDetailState(conversationId, options.viewer, createConversationAccessReader(getDb(), options.viewer));
9019
+ const readAccess = createConversationAccessReader(getDb(), options.viewer);
9020
+ const { record, state } = options.stored ?? await readConversationDetailState(conversationId, options.viewer, readAccess);
9075
9021
  if (!record) return void 0;
9076
9022
  const { access, readPosition } = state;
9077
9023
  const canExposePayload = access?.canViewPrivateContent ?? false;
@@ -9103,7 +9049,11 @@ async function readConversationDetailFromSql(conversationId, options) {
9103
9049
  limit: options.limit
9104
9050
  });
9105
9051
  };
9106
- const [annotations, automationTitleByConversation, auxiliaryCostsByConversation, briefVersion, firstHumanMessageTextByConversation, modelUsage, metricsByConversation, people, sourceTask, teamDomainByTeamId, page] = await Promise.all([
9052
+ const [agentTree, annotations, automationTitleByConversation, auxiliaryCostsByConversation, briefVersion, firstHumanMessageTextByConversation, modelUsage, metricsByConversation, people, sourceTask, teamDomainByTeamId, page] = await Promise.all([
9053
+ readConversationAgentTree({
9054
+ conversationId,
9055
+ ...record.conversation.parentConversationId ? { parentConversationId: record.conversation.parentConversationId } : void 0
9056
+ }, readAccess),
9107
9057
  listConversationAnnotations(getDb(), conversationId),
9108
9058
  readAutomationTitlesByConversationId([record.conversation]),
9109
9059
  readConversationAuxiliaryCostsFromSql(getDb(), [conversationId]),
@@ -9156,7 +9106,6 @@ async function readConversationDetailFromSql(conversationId, options) {
9156
9106
  transcript: state.transcriptVersion
9157
9107
  }) },
9158
9108
  ...state.viewerMarks,
9159
- unreadReply: state.unreadReply,
9160
9109
  automationTitle: automationTitleByConversation.get(conversationId),
9161
9110
  annotations,
9162
9111
  sidebarAnnotations,
@@ -9189,7 +9138,7 @@ async function readConversationDetailFromSql(conversationId, options) {
9189
9138
  return {
9190
9139
  ...report,
9191
9140
  ...state.forks,
9192
- ...state.agentTree ? { agentTree: state.agentTree } : void 0,
9141
+ ...agentTree ? { agentTree } : void 0,
9193
9142
  ...report.isParticipant && state.autoArchive !== void 0 ? { autoArchive: state.autoArchive } : void 0,
9194
9143
  ...report.isParticipant && state.subscribed !== void 0 ? { subscribed: state.subscribed } : void 0,
9195
9144
  ...canContinueInSlack(record.conversation, access) ? { canContinueInSlack: true } : void 0,
@@ -9520,9 +9469,17 @@ async function waitingRowsOutsidePage(db, filter, page) {
9520
9469
  status: "active"
9521
9470
  });
9522
9471
  }
9523
- /** Feed rows show last activity only as an age in whole minutes. */
9524
- function shownActivityMinute(lastActivityAt) {
9525
- return sql`date_trunc('minute', ${lastActivityAt})`;
9472
+ /**
9473
+ * Feed rows show last activity only as an age in whole minutes. A running
9474
+ * row shows its running state in place of the age, so it shows no activity.
9475
+ * Every status but `idle` and `failed` shows as running, as in
9476
+ * `statusFromConversation`.
9477
+ */
9478
+ function shownActivityMinute(executionStatus, lastActivityAt) {
9479
+ return sql`case
9480
+ when ${executionStatus} in ('idle', 'failed')
9481
+ then date_trunc('minute', ${lastActivityAt})
9482
+ end`;
9526
9483
  }
9527
9484
  const feedTree = alias(juniorConversations, "feed_tree");
9528
9485
  const feedAnnotated = alias(juniorConversations, "feed_annotated");
@@ -9540,21 +9497,18 @@ const feedAnnotated = alias(juniorConversations, "feed_annotated");
9540
9497
  * token holds its minute. The end of the Turn moves the status.
9541
9498
  * The rows are in feed order, so a move that reorders them moves the token.
9542
9499
  * The newest Message of each role stands for the preview and participants.
9543
- * The row shows only whether a reply is unread, so a scroll that moves the
9544
- * read position does not move the token.
9545
9500
  * Threads and annotations show from the whole tree. Waiting roots outside
9546
9501
  * the page move the Review items token.
9547
9502
  */
9548
9503
  function conversationFeedVersionQuery(db, userId) {
9549
9504
  const pin = juniorConversationParticipants;
9550
- const read = juniorConversationReadPositions;
9551
9505
  const conversationId = juniorConversations.conversationId;
9552
9506
  const tree = db.select({ version: sql`concat_ws(':',
9553
9507
  count(*) filter (where ${feedTree.archivedAt} is not null),
9554
9508
  string_agg(concat_ws('/',
9555
9509
  ${feedTree.conversationId}, ${feedTree.title},
9556
9510
  ${feedTree.executionStatus}, ${feedTree.stoppedAt},
9557
- ${shownActivityMinute(feedTree.lastActivityAt)}
9511
+ ${shownActivityMinute(feedTree.executionStatus, feedTree.lastActivityAt)}
9558
9512
  ), ',' order by ${feedTree.conversationId}) filter (
9559
9513
  where ${feedTree.kind} = 'thread' and ${feedTree.archivedAt} is null
9560
9514
  )
@@ -9569,16 +9523,12 @@ function conversationFeedVersionQuery(db, userId) {
9569
9523
  pinPosition: pin.pinPosition,
9570
9524
  stoppedAt: juniorConversations.stoppedAt,
9571
9525
  title: juniorConversations.title,
9572
- activity: sql`case
9573
- when ${juniorConversations.executionStatus} in ('idle', 'failed')
9574
- then ${shownActivityMinute(juniorConversations.lastActivityAt)}
9575
- end`.as("activity"),
9526
+ activity: shownActivityMinute(juniorConversations.executionStatus, juniorConversations.lastActivityAt).as("activity"),
9576
9527
  assistantSeq: sql`(${latestMessageSeqQuery(db, "assistant", conversationId)})`.as("assistant_seq"),
9577
9528
  userSeq: sql`(${latestMessageSeqQuery(db, "user", conversationId)})`.as("user_seq"),
9578
- unread: unreadReplySql(db, userId, conversationId, read.lastReadSeq).as("unread"),
9579
9529
  threads: sql`(${tree})`.as("threads"),
9580
9530
  annotations: sql`(${annotations})`.as("annotations")
9581
- }).from(juniorConversations).leftJoin(pin, and(eq(pin.rootConversationId, conversationId), eq(pin.userId, userId))).leftJoin(read, and(eq(read.conversationId, conversationId), eq(read.userId, userId))).where(and(listedConversation(), conversationFeedMembershipFilter("active", {
9531
+ }).from(juniorConversations).leftJoin(pin, and(eq(pin.rootConversationId, conversationId), eq(pin.userId, userId))).where(and(listedConversation(), conversationFeedMembershipFilter("active", {
9582
9532
  kind: "viewer",
9583
9533
  userId
9584
9534
  }))).orderBy(desc(isNotNull(pin.pinnedAt)), desc(juniorConversations.lastActivityAt), asc(conversationId)).limit(CONVERSATION_FEED_LIMIT).as("feed_page");
@@ -9590,7 +9540,6 @@ function conversationFeedVersionQuery(db, userId) {
9590
9540
  status: byRow(page.executionStatus, page.stoppedAt),
9591
9541
  activity: byRow(page.activity),
9592
9542
  messages: byRow(page.assistantSeq, page.userSeq),
9593
- unread: byRow(page.unread),
9594
9543
  threads: byRow(page.threads),
9595
9544
  annotations: byRow(page.annotations)
9596
9545
  };
@@ -9636,7 +9585,7 @@ async function readConversationFeedFromSql(options = {}) {
9636
9585
  if (filter?.kind === "viewer" && status === "active") rows.push(...await waitingRowsOutsidePage(db, filter, rows));
9637
9586
  const conversations = rows.map((row) => conversationFromRecordRow(row));
9638
9587
  const conversationIds = conversations.map((conversation) => conversation.conversationId);
9639
- const [accessByConversation, viewerMarksByConversation, annotationsByConversation, auxiliaryCostsByRoot, metricsByRoot, participantsByConversation, teamDomainByTeamId, { work: conversationWork, lastUserMessageAt: lastUserMessageAtByConversation }, activityPreviewByConversation, briefByConversation, automationTitleByConversation, firstHumanMessageTextByConversation, unreadConversationIds] = await Promise.all([
9588
+ const [accessByConversation, viewerMarksByConversation, annotationsByConversation, auxiliaryCostsByRoot, metricsByRoot, participantsByConversation, teamDomainByTeamId, { work: conversationWork, lastUserMessageAt: lastUserMessageAtByConversation }, activityPreviewByConversation, briefByConversation, automationTitleByConversation, firstHumanMessageTextByConversation] = await Promise.all([
9640
9589
  readConversationAccessFromSql(db, conversationIds, options.viewer),
9641
9590
  conversationViewerMarks(db, conversationIds, filter ? feedMember(filter) : void 0),
9642
9591
  listConversationAnnotationsById(db, conversationIds),
@@ -9651,8 +9600,7 @@ async function readConversationFeedFromSql(options = {}) {
9651
9600
  readConversationActivityPreviews(db, conversationIds),
9652
9601
  readConversationFeedBriefs(db, conversationIds),
9653
9602
  readAutomationTitlesByConversationId(conversations),
9654
- readFirstHumanMessageTexts(db, conversations),
9655
- filter?.kind === "viewer" ? readUnreadConversationIds(db, conversationIds, filter.userId) : /* @__PURE__ */ new Set()
9603
+ readFirstHumanMessageTexts(db, conversations)
9656
9604
  ]);
9657
9605
  const visibleActivityPreviews = await attachActivityPreviewMentions(getSqlExecutor(), new Map([...activityPreviewByConversation].filter(([conversationId]) => accessByConversation.get(conversationId)?.canViewPrivateContent)));
9658
9606
  const visibleAnnotationsByConversation = new Map(conversationIds.map((conversationId) => [conversationId, accessByConversation.get(conversationId)?.canViewPrivateContent ? annotationsByConversation.get(conversationId) ?? [] : []]));
@@ -9671,7 +9619,6 @@ async function readConversationFeedFromSql(options = {}) {
9671
9619
  const childAgentTotals = childAgentTotalsReport(metrics, auxiliaryCosts);
9672
9620
  const summary = conversationSummaryFromStoredConversation({
9673
9621
  ...viewerMarksByConversation.get(conversation.conversationId),
9674
- unreadReply: unreadConversationIds.has(conversation.conversationId),
9675
9622
  automationTitle: automationTitleByConversation.get(conversation.conversationId),
9676
9623
  conversation,
9677
9624
  access,
@@ -9799,4 +9746,4 @@ function viewerWebMessages(messages, viewer) {
9799
9746
  }] : [];
9800
9747
  });
9801
9748
  }
9802
- 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 };
9749
+ export { reviewItemChange as $, assertNoLegacyAllowedDomains as A, normalizeIncomingSlackThreadId as B, cancelConversationPendingMessagesForViewer as C, createProductionConversationWorkOptions as D, resolveMentions as E, startProcessingReaction as F, stopConversation as G, createSlackWebApiStatusSender as H, buildSlackInboundMessage as I, bindMessageAuthorIdentityId as J, parseContent as K, clearSlackPendingReactions as L, isAllowedSignInEmail as M, readEnvList as N, createProductionSlackWebhookServices as O, resolveAllowedDomains as P, readReviewItemForUser as Q, slackInboundMessageId as R, encodeConversationCursor as S, requireConversationPendingMessages as T, SubscribedReplyReason as U, withNormalizedThreadId as V, getThreadStopDecision as W, actOnReviewItem as X, ReviewItemActionError as Y, closeReviewItemsAnsweredByReply as Z, conversationSummaryFromStoredConversation as _, pinConversation as a, archiveViewerDoneConversations as at, createConversationForViewer as b, readConversationAuxiliaryCostsFromSql as c, setConversationAutoArchive as ct, conversationVersionQuery as d, enqueueAgentDispatch as dt, alreadyContinuesInSlackMessage as et, readConversationDetailEtag as f, GET as ft, readConversationRecordFromSql as g, readConversationEvents as h, readConversationFeed as i, DEFAULT_AUTO_ARCHIVE_SETTINGS as it, isAllowedDomain as j, getProductionSlackAdapter as k, childAgentTotalsReport as l, updateUserAutoArchiveSettings as lt, keepQuickQuestionForViewer as m, steerConversationPendingMessagesForViewer as n, continueConversationInSlack as nt, reorderPinnedConversations as o, readUserAutoArchiveSettings as ot, forkConversationForViewer as p, readHealthReport as pt, recordSkippedConversationMessage as q, conversationFeedVersionQuery as r, isMovableToSlack as rt, readConversationDetail as s, runAutoArchiveSweep as st, stopConversationTurnForViewer as t, canContinueInSlack as tt, readConversationTreeMetricsFromSql as u, AGENT_DISPATCH_MAX_AGE_MS as ut, readFirstHumanMessageTexts as v, readConversationPendingMessages as w, decodeConversationCursor as x, appendConversationMessageForViewer as y, stripLeadingBotMention as z };