@sentry/junior 0.288.0 → 0.290.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 (76) hide show
  1. package/dist/{adapter-Cikcqdty.js → adapter-CHMVy-j0.js} +1 -1
  2. package/dist/{admin-BcSxHuTB.js → admin-C45Ap5Tn.js} +2 -2
  3. package/dist/{agent-runner-9MXyWUL8.js → agent-runner-CZjf6MOQ.js} +343 -103
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +6 -7
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +281 -254
  8. package/dist/{app-BUklJVBe.d.ts → app-BB1j2krL.d.ts} +2 -4
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +92 -64
  11. package/dist/assistant-reply-BtIV0hq6.js +58 -0
  12. package/dist/{automation-DDXwHQs5.js → automation-DWbjJltM.js} +1 -1
  13. package/dist/{background-compaction-queue-CjllSPir.js → background-compaction-queue-2gKhjRD3.js} +4 -4
  14. package/dist/{briefs-DW9iuolG.js → briefs-BGke_Cz5.js} +3 -4
  15. package/dist/{catalog-runtime-B3gfH58M.js → catalog-runtime-BSOlVfXi.js} +1 -1
  16. package/dist/cli/chat.js +14 -14
  17. package/dist/cli/check.js +3 -3
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +4 -4
  20. package/dist/cli/snapshot-create.js +4 -4
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +4 -4
  23. package/dist/{config-CLJcyYEF.js → config-DHDub41t.js} +4 -41
  24. package/dist/{connections-BtdJftow.js → connections-BAb0fedk.js} +7 -129
  25. package/dist/{conversation-DhoqHtQ7.js → conversation-CwC8K3RZ.js} +8 -8
  26. package/dist/{conversation-pending-messages-DHV0S4uF.js → conversation-pending-messages-B0cuLReP.js} +1 -1
  27. package/dist/{conversation-privacy-BPirIVlX.js → conversation-privacy-QRdLPH-9.js} +1 -1
  28. package/dist/{credential-sync-Co8Q2xRW.js → credential-sync-YIMGiRk7.js} +13 -13
  29. package/dist/{db-Co7DTYYh.js → db-DBHig2sI.js} +56 -31
  30. package/dist/{db-zIs8-Ba3.d.ts → db-DCSmv9tz.d.ts} +6 -2
  31. package/dist/{executor-m0kIN71Q.js → executor-DKrtH0k_.js} +62 -13
  32. package/dist/instrumentation.js +2 -2
  33. package/dist/{logging-DbD-dErY.js → logging-f24cZPEj.js} +2 -2
  34. package/dist/{history-IjdmO_r6.js → media-BepyEUNm.js} +85 -1
  35. package/dist/{message-DKTdTYm-.js → message-BbBOajiX.js} +9 -9
  36. package/dist/nitro.d.ts +1 -1
  37. package/dist/nitro.js +2 -2
  38. package/dist/{oauth-callback-server-CpbepSbp.js → oauth-callback-server-rHJYjFoz.js} +2 -2
  39. package/dist/{projection-BViECfYu.js → projection-D-9aVaHj.js} +153 -119
  40. package/dist/{prompt-KT6MaDHN.js → prompt-C7SZhNDy.js} +183 -3
  41. package/dist/{registry-D-Acyjhh.js → registry-CwA-kSjW.js} +1 -1
  42. package/dist/{resolve-gkT2R66z.js → resolve-B5WJgt9k.js} +3 -3
  43. package/dist/{result-DHmCFEt8.js → result-B2sCVIwl.js} +16 -10
  44. package/dist/{runner-DBKjGjH-.js → runner-CZq7wyIh.js} +8 -8
  45. package/dist/{sandbox-egress-signals-9n8hqx29.js → sandbox-egress-signals-C4d6Pa9a.js} +1 -1
  46. package/dist/{schema-DxicIQbc.js → schema-Bptz19Ja.js} +14 -9
  47. package/dist/{schema-B_6aOcx5.d.ts → schema-DQaFSkZZ.d.ts} +13 -5
  48. package/dist/{service-account-CDlC9ssy.js → service-account-B6OJtplS.js} +3 -3
  49. package/dist/{service-account-Bi0HsY6w.js → service-account-BC73M8rj.js} +3 -3
  50. package/dist/{session-stop-BWOsuo8p.js → session-stop-1cku9Vm3.js} +41 -30
  51. package/dist/{skills-DO5K68Rq.js → skills-BFopj5ID.js} +2 -2
  52. package/dist/{spawn-BBqZDcPa.js → spawn-B-1JlJwH.js} +5 -5
  53. package/dist/{stop-WC97cmHz.js → stop-CJweYiOH.js} +123 -213
  54. package/dist/{store-ByR1Lr7e.js → store-CK869JpC.js} +3 -3
  55. package/dist/{task-runner-B-Ewf8TX.js → task-runner-XmXL9E-k.js} +13 -17
  56. package/dist/{turn-failure-response-CpdPoZSl.js → turn-failure-response-hhpek6Fn.js} +8 -8
  57. package/dist/{validation-B4sbIoES.js → validation-DHQjCRFx.js} +1 -1
  58. package/dist/{version-D6lpuAgL.js → version-DQgCf4FE.js} +1 -1
  59. package/dist/version.js +1 -1
  60. package/dist/{viewer-CeP27tC3.js → viewer-DG97nzP4.js} +4 -4
  61. package/dist/{warmup-P_GJCL1c.js → warmup-C00-jOoN.js} +272 -78
  62. package/dist/{work-DI7x1Slm.js → work-Ch3EWO6u.js} +14 -14
  63. package/dist/{worker-CYPTOT4j.js → worker-B8kyM1fB.js} +6 -30
  64. package/migrations/0091_conversation_participant_unsubscribed_index.sql +20 -0
  65. package/migrations/0092_turn_metric_actor.sql +12 -0
  66. package/migrations/0093_participant_root_actor_backfill.sql +18 -0
  67. package/migrations/0094_conversation_delivery_paused_at.sql +1 -0
  68. package/migrations/meta/0091_snapshot.json +4410 -0
  69. package/migrations/meta/0092_snapshot.json +4446 -0
  70. package/migrations/meta/0093_snapshot.json +4446 -0
  71. package/migrations/meta/0094_snapshot.json +4452 -0
  72. package/migrations/meta/_journal.json +28 -0
  73. package/package.json +5 -5
  74. package/dist/assistant-reply-mj47jMRV.js +0 -65
  75. package/dist/core-model-BTt5E5b0.js +0 -182
  76. package/dist/media-BAHvgkok.js +0 -85
@@ -1,34 +1,32 @@
1
1
  import { h as startSpan } from "./sentry-BRTJqumy.js";
2
- import { $a as conversationPinnedForUser, $i as downloadPrivateSlackFile, $r as getDashboardConversationLink, $t as persistWithRetry, A as isHumanConversationMessage, Ao as configValueSchema, Bi as deleteSlackMessage, Bn as getPlugins, C as resolveConversationTitle, Co as listConversationAnnotationsById, D as buildConversationContext, Dn as createUserTokenStore, Do as lookupSlackUserNames, Eo as lookupSlackUser, F as trimConversationMessages, Fr as cancelSubscriptions, Gi as postSlackMessage, I as turnHasReply, Ii as normalizeSlackStatusText, Ja as createConversationAccessReader, Ka as createPluginLogger, Ki as removeReactionFromMessage, L as upsertConversationMessage, M as markConversationMessage, Mo as piMessageFromHistoryItem, N as normalizeConversationText, Ni as escapeSlackMrkdwnText, O as estimateConversationMessagesTokens, Oo as createPluginCache, P as recordDeliveredAssistantMessage, Pi as formatSlackLink, Pt as moveIdleConversationDestination, Qa as conversationIsNotUnsubscribedRoot, Qi as SlackActionError, Ri as truncateStatusText, So as listConversationAnnotations, Sr as reviewItemNeedsSomeone, T as fallbackShortTitle, U as PluginCredentialFailureError, Vi as getSlackMessagePermalink, Xa as conversationHasParticipantUser, Ya as readConversationAccessFromSql, Yt as buildTurnErrorResponse, Z as clearPendingAuth, Za as conversationIsMemberRoot, _o as recordSlackAttachment, _r as canReadReviewItem, a as loadProjection, aa as normalizeSlackConversationId, ao as readLatestConversationBrief, at as completeTurnRecord, b as persistConversationMessages, co as readConversationEventPageAround, cr as listReplyActionItems, ct as listTurnSummaries, d as recordAuthorizationCompleted, do as buildSentryConversationUrl, eo as conversationViewerMarks, et as loadTurnCheckpoint, fr as takeReviewItem, go as readAttachmentVisionSummary, h as recordSubscribedReplyRoute, hn as trimTrailingAssistantMessages, hr as canActOnReviewItem, i as loadConversationProjection, ia as isDmChannel, it as abandonTurnRecord, j as latestConversationMessageSeq, k as getConversationMessageSlackTs, kn as webActorUserIds, lr as listWaitingConversations, lt as recordTurnSummary, mo as getSlackFileId, n as commitMessages, na as getSlackClient, no as viewerMarksFromParticipant, nr as closeReviewItem, nt as pauseLostWorkerTurn, o as loadTurnProjection, oo as readConversationEventPage, or as getReviewItem, ot as failTurnRecord, po as notInheritedByForkChild, q as AuthorizationFlowDisabledError, rt as saveTurnCheckpoint, sa as withSlackRetries, so as readConversationEventPageAfter, st as getTurnRecord, t as commitAcceptedReply, ta as getHeaderString, to as viewerConversationMembership, tt as lostWorkerBeforeFirstSave, v as hydrateConversationMessages, vo as slackAttachmentsVersionQuery, vr as isOnlyAssignee, wr as reviewItemReaderForUser, y as persistConversationMessageWindow, zi as addReactionToMessage, zt as releaseInboundMessage } from "./projection-BViECfYu.js";
3
- import { E as resolveGatewayModel, G as isProviderRetryError, M as textCharsForTokens, R as escapeXml, c as getSlackClientSecret, i as getChatConfig, j as estimateTextTokens, l as getSlackSigningSecret, n as botConfig, o as getSlackBotToken, s as getSlackClientId, v as normalizeSlackEmojiName } from "./config-CLJcyYEF.js";
4
- import { E as withSpan, J as toOptionalString, K as isRecord, 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 toOptionalNumber, s as getActiveTraceId, t as buildTurnFailureResponse, y as setSentryUser } from "./logging-DbD-dErY.js";
5
- import { t as JUNIOR_VERSION } from "./version-D6lpuAgL.js";
2
+ import { $ as loadTurnCheckpoint, $a as readConversationAccessFromSql, A as latestConversationMessageSeq, Ao as lookupSlackUserNames, Cr as reviewItemNeedsSomeone, D as estimateConversationMessagesTokens, E as buildConversationContext, En as createUserTokenStore, Eo as listConversationAnnotationsById, F as turnHasReply, Fo as piMessageFromHistoryItem, H as PluginCredentialFailureError, Hi as addReactionToMessage, I as upsertConversationMessage, Ii as escapeSlackMrkdwnText, Ji as postSlackMessage, Jt as buildTurnErrorResponse, K as AuthorizationFlowDisabledError, Li as formatSlackLink, M as normalizeConversationText, N as recordDeliveredAssistantMessage, No as configValueSchema, Nt as moveIdleConversationDestination, O as getConversationMessageSlackTs, On as webActorUserIds, P as trimConversationMessages, Qa as createConversationAccessReader, Qt as persistWithRetry, Rr as cancelSubscriptions, Rt as releaseInboundMessage, S as resolveConversationTitle, To as listConversationAnnotations, Ui as deleteSlackMessage, Vi as truncateStatusText, Wi as getSlackMessagePermalink, X as clearPendingAuth, Ya as createPluginLogger, Yi as removeReactionFromMessage, Za as canAddConversationMessages, _o as getSlackFileId, a as loadProjection, aa as getSlackClient, ao as viewerMarksFromParticipant, at as failTurnRecord, b as persistConversationMessages, bo as recordSlackAttachment, ca as normalizeSlackConversationId, co as readLatestConversationBrief, cr as listReplyActionItems, ct as recordTurnSummary, d as recordAuthorizationCompleted, do as readConversationEventPageAround, eo as conversationHasParticipantUser, et as lostWorkerBeforeFirstSave, fr as takeReviewItem, go as notInheritedByForkChild, h as recordSubscribedReplyRoute, hr as canActOnReviewItem, i as loadConversationProjection, ia as getHeaderString, io as conversationViewerMarks, it as completeTurnRecord, j as markConversationMessage, jo as createPluginCache, k as isHumanConversationMessage, ko as lookupSlackUser, lo as readConversationEventPage, lr as listWaitingConversations, mn as trimTrailingAssistantMessages, mo as buildSentryConversationUrl, n as commitMessages, na as downloadPrivateSlackFile, ni as getDashboardConversationLink, no as conversationIsNotUnsubscribedRoot, nr as closeReviewItem, nt as saveTurnCheckpoint, o as loadTurnProjection, or as getReviewItem, ot as getTurnRecord, ro as conversationPinnedForUser, rt as abandonTurnRecord, sa as isDmChannel, st as listTurnSummaries, t as commitAcceptedReply, ta as SlackActionError, to as conversationIsMemberRoot, tt as pauseLostWorkerTurn, ua as withSlackRetries, uo as readConversationEventPageAfter, v as hydrateConversationMessages, vr as canUserReadReviewItem, w as fallbackShortTitle, xo as slackAttachmentsVersionQuery, y as persistConversationMessageWindow, yo as readAttachmentVisionSummary, yr as isOnlyAssignee, zi as normalizeSlackStatusText, zn as getPlugins } from "./projection-D-9aVaHj.js";
3
+ import { A as estimateTextTokens, E as resolveGatewayModel, L as escapeXml, W as isProviderRetryError, 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-DHDub41t.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-f24cZPEj.js";
5
+ import { t as JUNIOR_VERSION } from "./version-DQgCf4FE.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 { C as setFirstConversationLocation, D as resolveActorIdentityId, J as resolveRootConversationId, K as agentTurnUsageSchema, L as claimProviderConversation, O as saveActorAvatar, R as getConversationIdByProviderConversation, S as locationFromRow, U as addAgentTurnUsage, V as nextDetailVersion, Y as createSlackDestination, Z as requireSlackDestination, _ as setArchivedAt, a as getConversationStore, b as withConversationMutationLock, g as readConversationTrees, m as conversationAncestors, o as getDb, p as withConversationEventLock, q as hasAgentTurnUsage, r as getConversationEventStore, s as getSqlExecutor, v as loadConversationSlackTenantIds, x as conversationKindFromRow, z as parseSessionSource } from "./db-Co7DTYYh.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-m0kIN71Q.js";
9
- import { d as contextProvenance, p as instructionProvenanceFor, t as KNOWN_CONVERSATION_EVENT_TYPES } from "./history-IjdmO_r6.js";
10
- import { d as actorLogContext, f as credentialContextForActor } from "./registry-D-Acyjhh.js";
11
- import { A as runWithSlackInstallation, B as listThreadReplies, Ct as markConversationRead, Dt as stopChildAgentsBelow, Et as throwApiError, F as resolveSlackChannelIdFromThreadId, Ft as executeTurn, I as checkSlackChannelReadAccess, L as joinPublicChannelForRead, Lt as getTurnInputSpanAttributes, M as parseSlackThreadId, Mt as createConversationTurnWorker, N as readSlackRawMessageContext, Ot as stopChildAgentsOf, P as resolveSlackChannelIdFromMessage, Pt as AgentRunError, Qt as RetryableDeliveryError, R as getConversationInfo, Rt as turnInputTelemetry, S as createSlackReviewItemShow, St as conversationReadPositionQuery, V as resolveDestinationVisibility, Vt as getWebAuthorization, X as readConversationSourceTask, at as deliverReviewItemChange, b as renderAttachmentText, bt as readLastUserMessageAtByConversation, ct as acceptsWebMessages, dt as createAndEnqueueConversation, ft as createConversationId, ht as decodeInputImages, i as buildAuthPauseResponse, jt as cancelSignInWait, lt as appendAndEnqueueWebMessage, mt as webActorFromUser, n as executeAgentRun, p as latestProgressStatus, pt as recordWebConversationActivity, t as createAgentRunner, tn as shouldEmitDevAgentTrace, x as renderBlockText, yt as storeAttachment, zt as withTurnSpan } from "./agent-runner-9MXyWUL8.js";
12
- import { r as completeText, t as completeDecision } from "./core-model-BTt5E5b0.js";
7
+ import { B as addAgentTurnUsage, C as setFirstConversationLocation, D as resolveActorIdentityId, G as resolveRootConversationId, J as nextDetailVersion, L as claimProviderConversation, O as saveActorAvatar, Q as requireSlackDestination, R as getConversationIdByProviderConversation, S as locationFromRow, U as agentTurnUsageSchema, W as hasAgentTurnUsage, X as createSlackDestination, _ as setArchivedAt, a as getConversationStore, b as withConversationMutationLock, g as readConversationTrees, m as conversationAncestors, o as getDb, p as withConversationEventLock, r as getConversationEventStore, s as getSqlExecutor, v as loadConversationSlackTenantIds, x as conversationKindFromRow, z as parseSessionSource } from "./db-DBHig2sI.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-DKrtH0k_.js";
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-CwA-kSjW.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, ht as decodeInputImages, i as buildAuthPauseResponse, jt as createConversationTurnWorker, lt as appendAndEnqueueWebMessage, mt as webActorFromUser, n as executeAgentRun, p as latestProgressStatus, pn as shouldEmitDevAgentTrace, pt as recordWebConversationActivity, qt as turnInputTelemetry, t as createAgentRunner, un as RetryableDeliveryError, x as renderBlockText, xt as conversationReadPositionQuery, yt as storeAttachment, zt as canJoinTurn } from "./agent-runner-CZjf6MOQ.js";
12
+ import { a as EVENT_SYSTEM_ACTOR, c as completeDecision, o as isEventConversationMessage, u as completeText } from "./prompt-C7SZhNDy.js";
13
13
  import { r as acquireActiveLock } from "./locks-D-0h111u.js";
14
- import { f as identityAvatarUrl, h as readUserAvatarUrls } from "./viewer-CeP27tC3.js";
15
- import { a as setStateValues, i as getStateValues, r as getStateAdapter } from "./adapter-Cikcqdty.js";
16
- import { i as isVisionImageMediaType, r as detectImageMediaType } from "./media-BAHvgkok.js";
17
- import { G as readMessageAttachments, d as conversationEventPageSchema, l as conversationDetailReportSchema, m as conversationFeedSchema } from "./conversation-DhoqHtQ7.js";
18
- import { a as EVENT_SYSTEM_ACTOR, o as isEventConversationMessage } from "./prompt-KT6MaDHN.js";
19
- import { g as getVercelConversationWorkQueue, k as getTurnRequestDeadline } from "./background-compaction-queue-CjllSPir.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-CpdPoZSl.js";
21
- import { n as getAssistantReplyText } from "./assistant-reply-mj47jMRV.js";
22
- 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 deliversFinalText, ft as finishedRunReply, g as resolveMailboxTurnWork, gt as runDispatchOutcome, l as savedInputInstruction, o as skipInputAfterConversationStop, pt as postsRunNotices, r as markConversationsStopped, rt as isExperimentalFeatureEnabled, x as conversationSubtreeColumns, y as legacyWebMailboxMetadataSchema } from "./session-stop-BWOsuo8p.js";
14
+ import { f as identityAvatarUrl, h as readUserAvatarUrls } from "./viewer-DG97nzP4.js";
15
+ import { a as setStateValues, i as getStateValues, r as getStateAdapter } from "./adapter-CHMVy-j0.js";
16
+ import { W as readMessageAttachments, d as conversationEventPageSchema, l as conversationDetailReportSchema, m as conversationFeedSchema } from "./conversation-CwC8K3RZ.js";
17
+ import { c as listConversationWork, l as readLastUserMessageAtByConversation, s as isConversationWorkDone } from "./warmup-C00-jOoN.js";
18
+ import { g as getVercelConversationWorkQueue, k as getTurnRequestDeadline } from "./background-compaction-queue-2gKhjRD3.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-hhpek6Fn.js";
20
+ import { n as getAssistantReplyText } from "./assistant-reply-BtIV0hq6.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 deliversFinalText, ft as finishedRunReply, g as resolveMailboxTurnWork, gt as runDispatchOutcome, l as savedInputInstruction, o as skipInputAfterConversationStop, pt as postsRunNotices, r as markConversationsStopped, rt as isExperimentalFeatureEnabled, x as conversationSubtreeColumns, y as legacyWebMailboxMetadataSchema } from "./session-stop-1cku9Vm3.js";
23
22
  import { b as normalizeUserInputAnswer, p as webMessageId, y as isEmptyUserInputAnswer } from "./reporting-window-B3Ze-Qnt.js";
24
- 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-ByR1Lr7e.js";
25
- import { _ as markDispatchBlocked, _t as getPersistedThreadState, a as claimDispatchMailboxAppend, b as markDispatchRunning, bt as coerceThreadConversationState, c as getDispatchConversationId, d as getDispatchRecord, f as getDispatchTurnId, g as markDispatchAwaitingResume, gt as getPersistedSandboxState, ht as getLocationConfigurationService, m as isTerminalDispatchStatus, mt as resolveTurnSessionRouting, n as scheduleSessionCompletedPluginTasks, o as confirmDispatchMailboxAppend, pt as resolveConversationRouting, st as readAutomationTitlesByConversationId, u as getDispatchInputMessageId, v as markDispatchCompleted, vt as persistThreadRuntimeState, y as markDispatchFailed, yt as persistThreadStateById } from "./task-runner-B-Ewf8TX.js";
26
- import { d as healthReportSchema, s as conversationPendingMessagesReportSchema } from "./conversation-pending-messages-DHV0S4uF.js";
27
- import { r as endActiveAgentInvocations, s as resolveThreadTurnWork } from "./work-DI7x1Slm.js";
28
- import { a as withAgentInvocationResultActors, n as enqueueAgentInvocationResult, t as createChildConversationWorker } from "./result-DHmCFEt8.js";
29
- import { c as createPausedTurns, d as wakePausedTurn, f as getTurnAuthorization, l as getPausedTurnRequest } from "./connections-BtdJftow.js";
30
- import { t as bindMessageAgent } from "./message-DKTdTYm-.js";
31
- import { r as readConversationLineage, t as bindSpawnAgent } from "./spawn-BBqZDcPa.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-CK869JpC.js";
24
+ import { _ as markDispatchBlocked, _t as persistThreadStateById, a as claimDispatchMailboxAppend, b as markDispatchRunning, c as getDispatchConversationId, d as getDispatchRecord, dt as resolveConversationRouting, f as getDispatchTurnId, ft as resolveTurnSessionRouting, g as markDispatchAwaitingResume, gt as persistThreadRuntimeState, ht as getPersistedThreadState, m as isTerminalDispatchStatus, mt as getPersistedSandboxState, n as scheduleSessionCompletedPluginTasks, o as confirmDispatchMailboxAppend, pt as getLocationConfigurationService, st as readAutomationTitlesByConversationId, u as getDispatchInputMessageId, v as markDispatchCompleted, vt as coerceThreadConversationState, y as markDispatchFailed } from "./task-runner-XmXL9E-k.js";
25
+ import { d as healthReportSchema, s as conversationPendingMessagesReportSchema } from "./conversation-pending-messages-B0cuLReP.js";
26
+ import { r as endActiveAgentInvocations, s as resolveThreadTurnWork } from "./work-Ch3EWO6u.js";
27
+ import { a as withAgentInvocationResultActors, n as enqueueAgentInvocationResult, t as createChildConversationWorker } from "./result-B2sCVIwl.js";
28
+ import { t as bindMessageAgent } from "./message-BbBOajiX.js";
29
+ import { r as readConversationLineage, t as bindSpawnAgent } from "./spawn-B-1JlJwH.js";
32
30
  import { createHash, createHmac, timingSafeEqual } from "node:crypto";
33
31
  import * as z from "zod";
34
32
  import { and, asc, desc, eq, gt, inArray, isNotNull, isNull, lte, max, ne, or, sql } from "drizzle-orm";
@@ -304,86 +302,6 @@ function createAgentDispatchConversationWorker(options) {
304
302
  }
305
303
  };
306
304
  }
307
- // src/chat/plugins/unfinished-work.ts
308
- /**
309
- * Map each candidate and each child of a candidate root to the candidate it
310
- * counts for. A child agent runs under its own conversation id, so a plugin
311
- * links the work that the child does, such as a pull request, to the child.
312
- */
313
- async function readWorkOwners(conversationIds) {
314
- const owners = new Map(conversationIds.map((id) => [id, id]));
315
- const children = await getDb().select({
316
- conversationId: juniorConversations.conversationId,
317
- rootConversationId: juniorConversations.rootConversationId
318
- }).from(juniorConversations).where(inArray(juniorConversations.rootConversationId, conversationIds));
319
- for (const child of children) if (child.rootConversationId && !owners.has(child.conversationId)) owners.set(child.conversationId, child.rootConversationId);
320
- return owners;
321
- }
322
- /**
323
- * Return assigned and unfinished plugin work for the candidate conversations.
324
- * Work in a child conversation counts for its root candidate. Feed Priority
325
- * combines these signals with conversation activity on the host.
326
- */
327
- async function listConversationWork(conversationIds) {
328
- if (conversationIds.length === 0) return {
329
- assignedIds: [],
330
- failed: false,
331
- finishedAtById: {},
332
- unfinishedIds: []
333
- };
334
- const owners = await readWorkOwners(conversationIds);
335
- const queriedIds = [...owners.keys()];
336
- const assigned = /* @__PURE__ */ new Set();
337
- const finishedAtById = /* @__PURE__ */ new Map();
338
- const unfinished = /* @__PURE__ */ new Set();
339
- let failed = false;
340
- for (const plugin of getPlugins()) {
341
- const hook = plugin.hooks?.unfinishedWork;
342
- if (!hook) continue;
343
- try {
344
- const result = await hook({
345
- conversationIds: queriedIds,
346
- db: getDb(),
347
- log: createPluginLogger(plugin.manifest.name),
348
- plugin: { name: plugin.manifest.name },
349
- cache: createPluginCache(plugin.manifest.name)
350
- });
351
- for (const workId of result.conversationIds) {
352
- const conversationId = owners.get(workId);
353
- if (!conversationId) continue;
354
- unfinished.add(conversationId);
355
- assigned.add(conversationId);
356
- }
357
- for (const workId of result.assignedConversationIds ?? []) {
358
- const conversationId = owners.get(workId);
359
- if (conversationId) assigned.add(conversationId);
360
- }
361
- for (const [workId, finishedAt] of Object.entries(result.finishedWorkAtByConversationId ?? {})) {
362
- const conversationId = owners.get(workId);
363
- if (!conversationId) continue;
364
- const time = Date.parse(finishedAt);
365
- if (!Number.isFinite(time)) continue;
366
- const current = finishedAtById.get(conversationId);
367
- if (!current || time > Date.parse(current)) finishedAtById.set(conversationId, finishedAt);
368
- }
369
- } catch (error) {
370
- failed = true;
371
- logWarn("plugin.unfinished_work.hook.failed", {
372
- "app.plugin.name": plugin.manifest.name,
373
- "exception.message": error instanceof Error ? error.message : String(error)
374
- });
375
- }
376
- }
377
- return {
378
- assignedIds: conversationIds.filter((conversationId) => assigned.has(conversationId)),
379
- failed,
380
- finishedAtById: Object.fromEntries(conversationIds.flatMap((conversationId) => {
381
- const finishedAt = finishedAtById.get(conversationId);
382
- return finishedAt ? [[conversationId, finishedAt]] : [];
383
- })),
384
- unfinishedIds: conversationIds.filter((conversationId) => unfinished.has(conversationId))
385
- };
386
- }
387
305
  // src/api/conversations/auto-archive.ts
388
306
  const HOUR_MS = 36e5;
389
307
  /** Participant rows checked per page. A run reads pages until none remain. */
@@ -393,19 +311,6 @@ const DEFAULT_AUTO_ARCHIVE_SETTINGS = {
393
311
  autoArchiveDefault: false,
394
312
  autoArchiveGraceHours: 24
395
313
  };
396
- /**
397
- * Decide whether a conversation's work is done long enough to auto-archive.
398
- * A conversation without plugin-reported work has nothing to wait for, so
399
- * the quiet-tree checks alone decide it.
400
- */
401
- function isConversationWorkDone(conversation, cutoffMs) {
402
- if (conversation.unfinishedWork) return false;
403
- if (!conversation.assignedWork) return true;
404
- const finishedAt = Date.parse(conversation.finishedWorkAt ?? "");
405
- if (!Number.isFinite(finishedAt) || finishedAt > cutoffMs) return false;
406
- const lastUserMessageAt = Date.parse(conversation.lastUserMessageAt ?? "");
407
- return !(Number.isFinite(lastUserMessageAt) && lastUserMessageAt > finishedAt);
408
- }
409
314
  function runOptsIn(run) {
410
315
  return run.kind === "scheduled" ? sql`coalesce(${juniorConversationParticipants.autoArchive}, ${juniorUsers.autoArchiveDefault}) = true` : sql`${juniorConversationParticipants.autoArchive} is distinct from false`;
411
316
  }
@@ -856,7 +761,7 @@ var ReviewItemActionError = class extends Error {
856
761
  /** Read one Review item that a User can see, or fail as not found. */
857
762
  async function readReviewItemForUser(user, id) {
858
763
  const item = await getReviewItem(getDb(), id);
859
- if (!item || !canReadReviewItem(item, reviewItemReaderForUser(user))) throw new ReviewItemActionError("not_found", "Review item not found.");
764
+ if (!item || !await canUserReadReviewItem(item, user)) throw new ReviewItemActionError("not_found", "Review item not found.");
860
765
  return item;
861
766
  }
862
767
  function closedStatus(action) {
@@ -2699,6 +2604,8 @@ function createSlackConversationWorker(options) {
2699
2604
  const state = getConnectedState(options.state);
2700
2605
  await state.connect();
2701
2606
  const records = getPendingRecords({ execution: { pendingMessages: [...context.attempt.messages] } });
2607
+ let yieldForSlackInterrupt = false;
2608
+ const shouldYield = () => yieldForSlackInterrupt || context.shouldYield();
2702
2609
  if (records.length === 0) {
2703
2610
  const destination = requireSlackDestination(context.destination, "Slack paused-turn recovery");
2704
2611
  try {
@@ -2708,7 +2615,14 @@ function createSlackConversationWorker(options) {
2708
2615
  state,
2709
2616
  task: async () => {
2710
2617
  await options.runNextPausedTurn(context.conversationId, {
2711
- shouldYield: context.shouldYield,
2618
+ drainSteeringMessages: (turn) => async () => {
2619
+ await context.attempt.drain(async (pendingRecords) => {
2620
+ yieldForSlackInterrupt ||= pendingRecords.some((record) => record.source === "slack" && !canJoinTurn(turn, record));
2621
+ return [];
2622
+ });
2623
+ return [];
2624
+ },
2625
+ shouldYield,
2712
2626
  checkIn: context.checkIn,
2713
2627
  stopSignal: context.stopSignal?.()
2714
2628
  });
@@ -2727,6 +2641,10 @@ function createSlackConversationWorker(options) {
2727
2641
  const latestMetadata = parseSlackMetadata(latestRecord.input.metadata);
2728
2642
  if (!latestMetadata) throw new Error("Latest conversation mailbox record is not Slack metadata");
2729
2643
  if (!await context.checkIn()) return { status: "lost_lease" };
2644
+ await supersedeTurnForInput({
2645
+ conversationId: context.conversationId,
2646
+ message: latestRecord
2647
+ });
2730
2648
  const turnResult = await runWithSlackInstallation({
2731
2649
  adapter,
2732
2650
  installation: getInstallation(records),
@@ -2756,7 +2674,6 @@ function createSlackConversationWorker(options) {
2756
2674
  skipped: messages.slice(0, -1),
2757
2675
  totalSinceLastHandler: messages.length
2758
2676
  };
2759
- const activeAuthorId = requireSlackAuthorId(latestMessage);
2760
2677
  let initialMessagesAcked = false;
2761
2678
  const ack = async () => {
2762
2679
  if (initialMessagesAcked) return;
@@ -2769,14 +2686,16 @@ function createSlackConversationWorker(options) {
2769
2686
  };
2770
2687
  const drainSteeringMessages = async (accept) => {
2771
2688
  await context.attempt.drain(async (pendingRecords) => {
2772
- const candidates = pendingRecords.filter((record) => record.source === "slack").map((record) => ({
2689
+ const slackRecords = pendingRecords.filter((record) => record.source === "slack");
2690
+ const steering = slackRecords.filter((record) => canShareTurn(latestRecord, record));
2691
+ yieldForSlackInterrupt ||= steering.length < slackRecords.length;
2692
+ return steering.length > 0 ? await accept(steering.map((record) => ({
2773
2693
  inboundMessageId: record.inboundMessageId,
2774
2694
  message: restoreMessage({
2775
2695
  adapter,
2776
2696
  record
2777
2697
  })
2778
- })).filter((candidate) => requireSlackAuthorId(candidate.message) === activeAuthorId);
2779
- return candidates.length > 0 ? await accept(candidates) : [];
2698
+ }))) : [];
2780
2699
  });
2781
2700
  };
2782
2701
  try {
@@ -2787,7 +2706,7 @@ function createSlackConversationWorker(options) {
2787
2706
  drainSteeringMessages,
2788
2707
  ack,
2789
2708
  isFinalAttempt: context.attempt.isFinalAttempt,
2790
- shouldYield: context.shouldYield,
2709
+ shouldYield,
2791
2710
  checkIn: context.checkIn,
2792
2711
  stopSignal: context.stopSignal?.(),
2793
2712
  telemetry
@@ -2799,7 +2718,7 @@ function createSlackConversationWorker(options) {
2799
2718
  drainSteeringMessages,
2800
2719
  ack,
2801
2720
  isFinalAttempt: context.attempt.isFinalAttempt,
2802
- shouldYield: context.shouldYield,
2721
+ shouldYield,
2803
2722
  checkIn: context.checkIn,
2804
2723
  stopSignal: context.stopSignal?.(),
2805
2724
  telemetry
@@ -4690,11 +4609,8 @@ function createSlackTurn(deps) {
4690
4609
  threadTs: assistantThreadContext?.threadTs,
4691
4610
  getSlackAdapter: deps.getSlackAdapter
4692
4611
  });
4693
- let persistedAtLeastOnce = false;
4694
- let shouldPersistFailureState = true;
4695
- let runResultHandled = false;
4696
- let assistantMessageDelivered = false;
4697
- let acceptedDeliveryId;
4612
+ let runState = "running";
4613
+ let acceptedReply;
4698
4614
  let turnCompletionNotified = false;
4699
4615
  const recordDispatchOutcome = async (dispatchOutcome, state) => {
4700
4616
  const dispatchId = options.execution?.dispatch?.id;
@@ -4706,7 +4622,7 @@ function createSlackTurn(deps) {
4706
4622
  destinationVisibility,
4707
4623
  dispatchId,
4708
4624
  dispatchOutcome,
4709
- ...acceptedDeliveryId ? { resultMessageId: acceptedDeliveryId } : void 0,
4625
+ ...acceptedReply?.slackTs ? { resultMessageId: acceptedReply.slackTs } : void 0,
4710
4626
  turnId,
4711
4627
  sliceId: 1,
4712
4628
  source,
@@ -4776,8 +4692,7 @@ function createSlackTurn(deps) {
4776
4692
  });
4777
4693
  }
4778
4694
  const slackTs = slackMessageTs.at(-1);
4779
- assistantMessageDelivered = true;
4780
- acceptedDeliveryId = slackTs;
4695
+ acceptedReply = { slackTs };
4781
4696
  options.onTurnDeliveryAccepted?.(slackTs);
4782
4697
  const recordedMessageId = recordDeliveredAssistantMessage({
4783
4698
  cards,
@@ -4839,10 +4754,7 @@ function createSlackTurn(deps) {
4839
4754
  if (!await saveSteeringMessages({
4840
4755
  conversationId,
4841
4756
  messages: batchedSteeringMessages
4842
- })) {
4843
- shouldPersistFailureState = false;
4844
- throw new TurnInputDeferredError();
4845
- }
4757
+ })) throw new TurnInputDeferredError();
4846
4758
  if (batchedSteeringMessages.length > 0) {
4847
4759
  const newSteeringMessages = withoutSavedSteeringMessages(piMessages ?? [], batchedSteeringMessages.map((entry) => entry.message), (message) => message);
4848
4760
  if (newSteeringMessages.length > 0) piMessages = [...piMessages ?? [], ...newSteeringMessages];
@@ -4977,8 +4889,7 @@ function createSlackTurn(deps) {
4977
4889
  const reply = finishedRunReply(finalResult, options.execution?.dispatch);
4978
4890
  if (reply !== void 0) await deliverAssistantMessage(reply);
4979
4891
  const turnResult = runDispatchOutcome(finalResult);
4980
- runResultHandled = true;
4981
- shouldPersistFailureState = false;
4892
+ runState = "settled";
4982
4893
  boundaryFailureCode = "agent_run_failed";
4983
4894
  const completedState = buildDeliveredTurnStatePatch({
4984
4895
  conversation: preparedState.conversation,
@@ -5002,7 +4913,7 @@ function createSlackTurn(deps) {
5002
4913
  sliceId: 1,
5003
4914
  dispatchOutcome: turnResult.outcome,
5004
4915
  ...options.execution?.dispatch && turnResult.errorMessage ? { errorMessage: turnResult.errorMessage } : void 0,
5005
- ...acceptedDeliveryId ? { resultMessageId: acceptedDeliveryId } : void 0,
4916
+ ...acceptedReply?.slackTs ? { resultMessageId: acceptedReply.slackTs } : void 0,
5006
4917
  messages: finalResult.piMessages,
5007
4918
  actor: executionActor,
5008
4919
  surface: options.execution?.surface ?? "slack",
@@ -5024,7 +4935,7 @@ function createSlackTurn(deps) {
5024
4935
  surface: options.execution?.surface ?? "slack",
5025
4936
  dispatchId: options.execution?.dispatch?.id,
5026
4937
  dispatchOutcome: turnResult.outcome,
5027
- ...acceptedDeliveryId ? { resultMessageId: acceptedDeliveryId } : void 0,
4938
+ ...acceptedReply?.slackTs ? { resultMessageId: acceptedReply.slackTs } : void 0,
5028
4939
  traceId: getActiveTraceId()
5029
4940
  });
5030
4941
  await persistWithRetry(() => persistConversationMessages({
@@ -5048,7 +4959,6 @@ function createSlackTurn(deps) {
5048
4959
  saveFailureEventId = logException(saveError, "slack.reply.post_delivery_commit.failed", messageTs ? { "messaging.message.id": messageTs } : {});
5049
4960
  }
5050
4961
  preparedState.conversation = completedState.conversation;
5051
- persistedAtLeastOnce = true;
5052
4962
  options.onTurnOutcome?.(turnResult);
5053
4963
  completedResult = finalResult;
5054
4964
  if (saveFailed) return {
@@ -5056,7 +4966,7 @@ function createSlackTurn(deps) {
5056
4966
  failureCode: "persistence_failed",
5057
4967
  outcome: "failed"
5058
4968
  };
5059
- if (finalResult.diagnostics.outcome === "success") return { outcome: assistantMessageDelivered ? "success" : "no_reply" };
4969
+ if (finalResult.diagnostics.outcome === "success") return { outcome: acceptedReply ? "success" : "no_reply" };
5060
4970
  return {
5061
4971
  ...failureEventId ? { eventId: failureEventId } : void 0,
5062
4972
  failureCode: "model_execution_failed",
@@ -5084,8 +4994,7 @@ function createSlackTurn(deps) {
5084
4994
  failureCode: "agent_run_failed",
5085
4995
  turnId
5086
4996
  });
5087
- persistedAtLeastOnce = true;
5088
- shouldPersistFailureState = false;
4997
+ runState = "released";
5089
4998
  return;
5090
4999
  }
5091
5000
  await postAuthPauseNotice(outcome.providerDisplayName, outcome.requestText);
@@ -5094,16 +5003,12 @@ function createSlackTurn(deps) {
5094
5003
  sessionId: turnId
5095
5004
  });
5096
5005
  await persistThreadStateById(conversationId, { conversation: preparedState.conversation });
5097
- persistedAtLeastOnce = true;
5098
- shouldPersistFailureState = false;
5006
+ runState = "released";
5099
5007
  return;
5100
5008
  }
5101
5009
  if (outcome.status === "suspended") {
5102
5010
  options.onTurnOutcome?.({ outcome: "awaiting_resume" });
5103
- if (options.shouldYield && (options.shouldYield() || outcome.reason === "timeout")) {
5104
- shouldPersistFailureState = false;
5105
- throw new CooperativeTurnYieldError();
5106
- }
5011
+ if (options.shouldYield && (options.shouldYield() || outcome.reason === "timeout")) throw new CooperativeTurnYieldError();
5107
5012
  if (!destination || !conversationId) throw new Error("Paused turn requires a destination and conversation id");
5108
5013
  try {
5109
5014
  await deps.pausedTurns.wake({
@@ -5112,13 +5017,12 @@ function createSlackTurn(deps) {
5112
5017
  turnId,
5113
5018
  expectedVersion: outcome.resumeVersion
5114
5019
  });
5115
- shouldPersistFailureState = false;
5020
+ runState = "released";
5116
5021
  } catch (scheduleError) {
5117
5022
  logException(scheduleError, "agent.continue.schedule.failed", {
5118
5023
  ...messageTs ? { "messaging.message.id": messageTs } : void 0,
5119
5024
  "app.ai.resume_session_version": outcome.resumeVersion
5120
5025
  });
5121
- shouldPersistFailureState = true;
5122
5026
  throw scheduleError;
5123
5027
  }
5124
5028
  return;
@@ -5139,8 +5043,7 @@ function createSlackTurn(deps) {
5139
5043
  logException(error, "plugin.session.completed_task_schedule.failed");
5140
5044
  }
5141
5045
  } catch (error) {
5142
- if (runResultHandled) {
5143
- shouldPersistFailureState = false;
5046
+ if (runState === "settled") {
5144
5047
  logException(error, "slack.reply.post_delivery_commit.failed", messageTs ? { "messaging.message.id": messageTs } : {});
5145
5048
  try {
5146
5049
  await notifyTurnCompleted();
@@ -5150,22 +5053,21 @@ function createSlackTurn(deps) {
5150
5053
  return;
5151
5054
  }
5152
5055
  if (error instanceof CooperativeTurnYieldError) {
5153
- shouldPersistFailureState = false;
5056
+ runState = "released";
5154
5057
  throw error;
5155
5058
  }
5156
5059
  if (error instanceof TurnInputDeferredError) {
5157
- shouldPersistFailureState = false;
5060
+ runState = "released";
5158
5061
  throw error;
5159
5062
  }
5160
5063
  const leaseLoss = error instanceof AgentRunError ? error.cause : error;
5161
5064
  if (isTurnInputCommitLostError(leaseLoss)) {
5162
- shouldPersistFailureState = false;
5065
+ runState = "released";
5163
5066
  throw leaseLoss;
5164
5067
  }
5165
- shouldPersistFailureState = true;
5166
5068
  const runFailure = error instanceof AgentRunError ? error.cause : error;
5167
5069
  if (options.stopSignal?.aborted) {
5168
- shouldPersistFailureState = false;
5070
+ runState = "released";
5169
5071
  await abandonTurnRecord({
5170
5072
  conversationId,
5171
5073
  turnId,
@@ -5200,7 +5102,7 @@ function createSlackTurn(deps) {
5200
5102
  failureCode
5201
5103
  });
5202
5104
  } finally {
5203
- if (!persistedAtLeastOnce && shouldPersistFailureState) {
5105
+ if (runState === "running") {
5204
5106
  markTurnFailed({
5205
5107
  conversation: preparedState.conversation,
5206
5108
  nowMs: Date.now(),
@@ -5830,7 +5732,7 @@ async function resumeSlackTurnInContext(args) {
5830
5732
  let deferredFailureHandler;
5831
5733
  let stopped = false;
5832
5734
  let runResultHandled = false;
5833
- let assistantMessageDelivered = false;
5735
+ let acceptedReply;
5834
5736
  let shouldScheduleCompletedPluginTasks = false;
5835
5737
  let postDeliveryCommitError;
5836
5738
  const turnLifecycle = getTurnLifecycle();
@@ -5867,7 +5769,6 @@ async function resumeSlackTurnInContext(args) {
5867
5769
  const visibleConversationId = args.conversationId;
5868
5770
  const sessionId = runArgs.turnId;
5869
5771
  let deliveryConversation;
5870
- let acceptedDeliveryId;
5871
5772
  /** Load the resumed conversation once for ordered delivery recording. */
5872
5773
  const getDeliveryConversation = async () => {
5873
5774
  if (deliveryConversation) {
@@ -5924,8 +5825,7 @@ async function resumeSlackTurnInContext(args) {
5924
5825
  throw error;
5925
5826
  }
5926
5827
  const messageTs = slackMessageTs.at(-1);
5927
- assistantMessageDelivered = true;
5928
- acceptedDeliveryId = messageTs;
5828
+ acceptedReply = { slackTs: messageTs };
5929
5829
  const recordedMessageId = recordDeliveredAssistantMessage({
5930
5830
  cards,
5931
5831
  conversation: deliveryState.conversation,
@@ -5972,7 +5872,7 @@ async function resumeSlackTurnInContext(args) {
5972
5872
  failureCode = "agent_run_failed";
5973
5873
  };
5974
5874
  const deliveryState = await getDeliveryConversation();
5975
- assistantMessageDelivered = turnHasReply(deliveryState.conversation, sessionId);
5875
+ acceptedReply = turnHasReply(deliveryState.conversation, sessionId) ? {} : void 0;
5976
5876
  const run = buildResumedRun(runArgs, status, deliverAssistantMessage);
5977
5877
  if (runArgs.inputMessageIds?.length) await turnLifecycle.start({
5978
5878
  conversationId: runArgs.conversationId,
@@ -5995,7 +5895,6 @@ async function resumeSlackTurnInContext(args) {
5995
5895
  if (replyText !== void 0) await deliverAssistantMessage(replyText);
5996
5896
  runResultHandled = true;
5997
5897
  await status.clear();
5998
- failureCode = "persistence_failed";
5999
5898
  if (reply.piMessages?.length) await saveTurnCheckpoint({
6000
5899
  mode: "completed",
6001
5900
  conversationId: runArgs.conversationId,
@@ -6007,7 +5906,7 @@ async function resumeSlackTurnInContext(args) {
6007
5906
  dispatchId: run.dispatch?.id,
6008
5907
  dispatchOutcome: dispatchResult.outcome,
6009
5908
  ...dispatchErrorMessage ? { errorMessage: dispatchErrorMessage } : void 0,
6010
- ...acceptedDeliveryId ? { resultMessageId: acceptedDeliveryId } : void 0,
5909
+ ...acceptedReply?.slackTs ? { resultMessageId: acceptedReply.slackTs } : void 0,
6011
5910
  source: run.source,
6012
5911
  actor: resumeActor,
6013
5912
  surface: run.surface ?? "slack",
@@ -6018,7 +5917,7 @@ async function resumeSlackTurnInContext(args) {
6018
5917
  destination: run.destination,
6019
5918
  dispatchId: run.dispatch?.id,
6020
5919
  dispatchOutcome: dispatchResult.outcome,
6021
- ...acceptedDeliveryId ? { resultMessageId: acceptedDeliveryId } : void 0,
5920
+ ...acceptedReply?.slackTs ? { resultMessageId: acceptedReply.slackTs } : void 0,
6022
5921
  turnId: runArgs.turnId,
6023
5922
  sliceId: runArgs.sliceId ?? 1,
6024
5923
  source: run.source,
@@ -6028,7 +5927,7 @@ async function resumeSlackTurnInContext(args) {
6028
5927
  await runArgs.commitResult?.(reply);
6029
5928
  if (reply.diagnostics.outcome === "success") {
6030
5929
  shouldScheduleCompletedPluginTasks = true;
6031
- return { outcome: assistantMessageDelivered ? "success" : "no_reply" };
5930
+ return { outcome: acceptedReply ? "success" : "no_reply" };
6032
5931
  }
6033
5932
  return {
6034
5933
  outcome: "failed",
@@ -6483,6 +6382,7 @@ async function runPausedTurnInContext(payload, options, runOptions) {
6483
6382
  sandboxRef
6484
6383
  },
6485
6384
  durability: {
6385
+ drainSteeringMessages: runOptions.drainSteeringMessages?.(activeTurn),
6486
6386
  shouldYield: runOptions.shouldYield,
6487
6387
  checkIn: runOptions.checkIn,
6488
6388
  recordPendingAuth: async (nextPendingAuth) => {
@@ -7272,7 +7172,8 @@ async function appendConversationMessageForViewer(viewer, conversationId, body,
7272
7172
  const conversation = await getConversationStore().get({ conversationId });
7273
7173
  if (!conversation) throwApiError(404, "Conversation not found.");
7274
7174
  if (!acceptsWebMessages(conversation)) throwApiError(409, "Conversation does not accept web messages.");
7275
- if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(403, "Only conversation participants can add messages.");
7175
+ const access = await readConversationAccessFromSql(getDb(), [conversationId], viewer);
7176
+ if (!canAddConversationMessages(access.get(conversationId))) throwApiError(403, "Only participants can add messages to a private conversation.");
7276
7177
  const images = parseImages(body.images);
7277
7178
  const actor = actorFromViewer(viewer);
7278
7179
  const append = () => appendAndEnqueueWebMessage({
@@ -8071,7 +7972,8 @@ function conversationFromRecordRow(row) {
8071
7972
  ...value.source ? { source: value.source } : void 0,
8072
7973
  ...value.title ? { title: value.title } : void 0,
8073
7974
  ...value.transcriptPurgedAt ? { transcriptPurgedAtMs: value.transcriptPurgedAt.getTime() } : void 0,
8074
- ...value.stoppedAt ? { stoppedAtMs: value.stoppedAt.getTime() } : void 0
7975
+ ...value.stoppedAt ? { stoppedAtMs: value.stoppedAt.getTime() } : void 0,
7976
+ ...value.deliveryPausedAt ? { deliveryPausedAtMs: value.deliveryPausedAt.getTime() } : void 0
8075
7977
  };
8076
7978
  }
8077
7979
  /** Decode one `selectConversationRecords` row into a Conversation record. */
@@ -9232,7 +9134,8 @@ async function readConversationDetailFromSql(conversationId, options) {
9232
9134
  ...state.agentTree ? { agentTree: state.agentTree } : void 0,
9233
9135
  ...report.isParticipant && state.autoArchive !== void 0 ? { autoArchive: state.autoArchive } : void 0,
9234
9136
  ...report.isParticipant && state.subscribed !== void 0 ? { subscribed: state.subscribed } : void 0,
9235
- ...canContinueInSlack(record.conversation, access) ? { canContinueInSlack: true } : void 0
9137
+ ...canContinueInSlack(record.conversation, access) ? { canContinueInSlack: true } : void 0,
9138
+ ...report.isParticipant && canPauseConversationDelivery(record.conversation) ? { deliveryPaused: record.conversation.deliveryPausedAtMs !== void 0 } : void 0
9236
9139
  };
9237
9140
  }
9238
9141
  /** Turns in the default page: enough to read the latest exchange in context. */
@@ -9260,12 +9163,11 @@ async function readConversationDetail(conversationId, options = {}) {
9260
9163
  * Pin or unpin one conversation for the signed-in viewer.
9261
9164
  *
9262
9165
  * A pin lives on the viewer's participant row, and that row grants send and
9263
- * control access. So only a participant can pin, the same as archive. The
9264
- * root actor may have no row yet, so pinning adds it. A pin also restores an
9265
- * archived conversation for everyone, because the Pinned section shows only
9266
- * active conversations. A pin on a child would be a fact of the child, not
9267
- * of the viewer's root, and no list shows child pins yet, so only a root can
9268
- * be pinned.
9166
+ * control access. So only a participant can pin, the same as archive. A pin
9167
+ * also restores an archived conversation for everyone, because the Pinned
9168
+ * section shows only active conversations. A pin on a child would be a fact
9169
+ * of the child, not of the viewer's root, and no list shows child pins yet,
9170
+ * so only a root can be pinned.
9269
9171
  */
9270
9172
  async function pinConversation(viewer, conversationId, body) {
9271
9173
  if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(404, "Conversation not found.");
@@ -9479,10 +9381,7 @@ function conversationCodeRepositoryFilter(repositoryId, viewerUserId) {
9479
9381
  FROM ${juniorCodeChanges}
9480
9382
  WHERE ${juniorCodeChanges.repositoryId} = ${repositoryId}
9481
9383
  )
9482
- )`, or(eq(juniorDestinations.visibility, "public"), viewerUserId ? viewerConversationMembership({
9483
- actorMatch: eq(juniorIdentities.userId, viewerUserId),
9484
- participantMatch: conversationHasParticipantUser(viewerUserId)
9485
- }) : void 0));
9384
+ )`, or(eq(juniorDestinations.visibility, "public"), viewerUserId ? conversationHasParticipantUser(viewerUserId) : void 0));
9486
9385
  }
9487
9386
  async function conversationRows(db, { codeRepository, conversationIds, filter, includePrivateBriefs = false, limit, query, status }) {
9488
9387
  return selectConversationRecords(db).where(and(isNull(juniorConversations.parentConversationId), isNull(juniorConversations.quickQuestionAt), 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 (
@@ -9525,7 +9424,9 @@ const feedAnnotated = alias(juniorConversations, "feed_annotated");
9525
9424
  /**
9526
9425
  * Return a query for a token that changes when the viewer's default feed
9527
9426
  * page can change. It reads the same newest page as the feed, so its cost
9528
- * does not grow with the viewer's history.
9427
+ * does not grow with the viewer's history. The token lists a short token
9428
+ * for each feed-row input as `name:token`, separated by spaces, so the
9429
+ * dashboard can record which inputs moved it.
9529
9430
  *
9530
9431
  * The token holds only what a feed row shows, so a Task's own writes do not
9531
9432
  * move it. Every Event of a live Turn moves `last_activity_at`, but rows
@@ -9540,20 +9441,7 @@ const feedAnnotated = alias(juniorConversations, "feed_annotated");
9540
9441
  function conversationFeedVersionQuery(db, userId) {
9541
9442
  const pin = juniorConversationParticipants;
9542
9443
  const read = juniorConversationReadPositions;
9543
- const page = db.select({
9544
- conversationId: juniorConversations.conversationId,
9545
- channelName: juniorConversations.channelName,
9546
- executionStatus: juniorConversations.executionStatus,
9547
- lastActivityAt: juniorConversations.lastActivityAt,
9548
- lastReadSeq: read.lastReadSeq,
9549
- pinnedAt: pin.pinnedAt,
9550
- pinPosition: pin.pinPosition,
9551
- stoppedAt: juniorConversations.stoppedAt,
9552
- title: juniorConversations.title
9553
- }).from(juniorConversations).leftJoin(pin, and(eq(pin.rootConversationId, juniorConversations.conversationId), eq(pin.userId, userId))).leftJoin(read, and(eq(read.conversationId, juniorConversations.conversationId), eq(read.userId, userId))).where(and(isNull(juniorConversations.parentConversationId), isNull(juniorConversations.quickQuestionAt), conversationFeedMembershipFilter("active", {
9554
- kind: "viewer",
9555
- userId
9556
- }))).orderBy(desc(isNotNull(pin.pinnedAt)), desc(juniorConversations.lastActivityAt), asc(juniorConversations.conversationId)).limit(CONVERSATION_FEED_LIMIT).as("feed_page");
9444
+ const conversationId = juniorConversations.conversationId;
9557
9445
  const tree = db.select({ version: sql`concat_ws(':',
9558
9446
  count(*) filter (where ${feedTree.archivedAt} is not null),
9559
9447
  string_agg(concat_ws('/',
@@ -9563,18 +9451,40 @@ function conversationFeedVersionQuery(db, userId) {
9563
9451
  ), ',' order by ${feedTree.conversationId}) filter (
9564
9452
  where ${feedTree.kind} = 'thread' and ${feedTree.archivedAt} is null
9565
9453
  )
9566
- )` }).from(feedTree).where(eq(feedTree.rootConversationId, page.conversationId));
9567
- const annotations = db.select({ version: sql`concat_ws(':', count(*), max(${juniorConversationAnnotations.updatedAt}))` }).from(juniorConversationAnnotations).innerJoin(feedAnnotated, eq(feedAnnotated.conversationId, juniorConversationAnnotations.conversationId)).where(eq(feedAnnotated.rootConversationId, page.conversationId));
9568
- return db.select({ version: sql`md5(coalesce(string_agg(
9569
- concat_ws('@', ${page.conversationId}, ${page.pinnedAt}, ${page.pinPosition},
9570
- ${page.title}, ${page.channelName}, ${page.executionStatus},
9571
- ${page.stoppedAt}, ${shownActivityMinute(page.lastActivityAt)},
9572
- (${latestMessageSeqQuery(db, "assistant", page.conversationId)}),
9573
- (${latestMessageSeqQuery(db, "user", page.conversationId)}),
9574
- ${unreadReplySql(db, userId, page.conversationId, page.lastReadSeq)},
9575
- (${tree}), (${annotations})),
9576
- ',' order by ${page.pinnedAt} is not null desc, ${page.lastActivityAt} desc, ${page.conversationId}
9577
- ), ''))` }).from(page);
9454
+ )` }).from(feedTree).where(eq(feedTree.rootConversationId, conversationId));
9455
+ const annotations = db.select({ version: sql`concat_ws(':', count(*), max(${juniorConversationAnnotations.updatedAt}))` }).from(juniorConversationAnnotations).innerJoin(feedAnnotated, eq(feedAnnotated.conversationId, juniorConversationAnnotations.conversationId)).where(eq(feedAnnotated.rootConversationId, conversationId));
9456
+ const page = db.select({
9457
+ conversationId,
9458
+ channelName: juniorConversations.channelName,
9459
+ executionStatus: juniorConversations.executionStatus,
9460
+ lastActivityAt: juniorConversations.lastActivityAt,
9461
+ pinnedAt: pin.pinnedAt,
9462
+ pinPosition: pin.pinPosition,
9463
+ stoppedAt: juniorConversations.stoppedAt,
9464
+ title: juniorConversations.title,
9465
+ activity: shownActivityMinute(juniorConversations.lastActivityAt).as("activity"),
9466
+ assistantSeq: sql`(${latestMessageSeqQuery(db, "assistant", conversationId)})`.as("assistant_seq"),
9467
+ userSeq: sql`(${latestMessageSeqQuery(db, "user", conversationId)})`.as("user_seq"),
9468
+ unread: unreadReplySql(db, userId, conversationId, read.lastReadSeq).as("unread"),
9469
+ threads: sql`(${tree})`.as("threads"),
9470
+ annotations: sql`(${annotations})`.as("annotations")
9471
+ }).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(isNull(juniorConversations.parentConversationId), isNull(juniorConversations.quickQuestionAt), conversationFeedMembershipFilter("active", {
9472
+ kind: "viewer",
9473
+ userId
9474
+ }))).orderBy(desc(isNotNull(pin.pinnedAt)), desc(juniorConversations.lastActivityAt), asc(conversationId)).limit(CONVERSATION_FEED_LIMIT).as("feed_page");
9475
+ const byRow = (...values) => sql`string_agg(concat_ws('@', ${page.conversationId}, ${sql.join(values, sql`, `)}), ',' order by ${page.conversationId})`;
9476
+ const inputs = {
9477
+ order: sql`string_agg(${page.conversationId}, ',' order by ${page.pinnedAt} is not null desc, ${page.lastActivityAt} desc, ${page.conversationId})`,
9478
+ pin: byRow(page.pinnedAt, page.pinPosition),
9479
+ title: byRow(page.title, page.channelName),
9480
+ status: byRow(page.executionStatus, page.stoppedAt),
9481
+ activity: byRow(page.activity),
9482
+ messages: byRow(page.assistantSeq, page.userSeq),
9483
+ unread: byRow(page.unread),
9484
+ threads: byRow(page.threads),
9485
+ annotations: byRow(page.annotations)
9486
+ };
9487
+ return db.select({ version: sql`concat_ws(' ', ${sql.join(Object.entries(inputs).map(([name, input]) => sql`${`${name}:`}::text || left(md5(coalesce(${input}, '')), 8)`), sql`, `)})` }).from(page);
9578
9488
  }
9579
9489
  /** Prefer the authenticated viewer; fall back to actor email membership. */
9580
9490
  function conversationFeedFilter(options) {