@sentry/junior 0.318.0 → 0.320.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 (94) hide show
  1. package/dist/{context-BKF_5zzI.js → adapter-DlLLoJKj.js} +537 -537
  2. package/dist/{admin-UOHix_5P.js → admin-BzRXDVfh.js} +1 -1
  3. package/dist/{agent-runner-DeYymwh2.js → agent-DxZ7nHfD.js} +19866 -6720
  4. package/dist/{agent-status-BA5x3Xtp.js → agent-status-Bq_AIpyp.js} +105 -1
  5. package/dist/{agent-update-delivery-DH8bx7jU.js → agent-update-delivery-CO4FU5Gg.js} +4 -5
  6. package/dist/api/schema.d.ts +45 -23
  7. package/dist/api/schema.js +4 -4
  8. package/dist/api.js +79 -84
  9. package/dist/{app-DKAOuaoC.d.ts → app-CHCFIIDu.d.ts} +5 -4
  10. package/dist/app.d.ts +2 -2
  11. package/dist/app.js +119 -194
  12. package/dist/{change-record-BzJgLsv7.d.ts → change-record-K-KsqNhT.d.ts} +9 -5
  13. package/dist/{channel-access-A0de5lRv.js → channel-access-BghWqlXx.js} +1 -1
  14. package/dist/{chat-core-engine-D3Wd7f5n.js → chat-core-engine-BgfSLrDu.js} +31 -14
  15. package/dist/cli/chat.d.ts +1 -1
  16. package/dist/cli/chat.js +23 -23
  17. package/dist/cli/check.js +5 -5
  18. package/dist/cli/main.js +2 -2
  19. package/dist/cli/plugins.d.ts +1 -1
  20. package/dist/cli/plugins.js +8 -8
  21. package/dist/cli/snapshot-create.js +5 -5
  22. package/dist/cli/upgrade.d.ts +1 -1
  23. package/dist/cli/upgrade.js +3 -4
  24. package/dist/{continue-in-slack-YxwMQVeR.js → continue-in-slack-DBlQP4PC.js} +3 -3
  25. package/dist/{conversation-feed-Cj7IuBtM.js → conversation-feed-DEUdD7mb.js} +2 -106
  26. package/dist/{conversation-privacy-Cr_dNW1p.js → conversation-privacy-qoh95v90.js} +1 -1
  27. package/dist/{create-Btl1y1rq.js → create-jZSaDrCR.js} +115 -5
  28. package/dist/{credential-sync-DTarZ63K.js → credential-sync-Bj9-UlNE.js} +15 -18
  29. package/dist/{db-of6e3sGt.js → db-BacvswT0.js} +4602 -727
  30. package/dist/{deployment-C0qXa0FD.js → deployment-BoJkRPDt.js} +3 -3
  31. package/dist/{engine-context-C_QL_bMQ.js → engine-context-Bi3Ync5t.js} +521 -150
  32. package/dist/{html-9_pS9SjY.js → html-DW0pw5Pr.js} +6 -8
  33. package/dist/instrumentation.js +7 -23
  34. package/dist/list-Dz3CdP3g.js +5016 -0
  35. package/dist/{logging-BnOG0qz2.js → logging-DsTnMqyi.js} +8 -33
  36. package/dist/{mailbox-turn-Byrry9o1.js → markers-C33gNYNE.js} +1705 -1284
  37. package/dist/nitro.d.ts +2 -2
  38. package/dist/nitro.js +6 -7
  39. package/dist/{oauth-callback-server-CjnnUr4o.js → oauth-callback-server-C-pEhAQK.js} +2 -2
  40. package/dist/{oauth-relay-BvHFH0fV.js → oauth-relay-DIXdH-io.js} +1 -1
  41. package/dist/{plugins-fBrz8PCV.d.ts → plugins-DhGXZjlu.d.ts} +1 -0
  42. package/dist/{profile-iHw1uu32.js → profile-v9vA3RvH.js} +16 -18
  43. package/dist/{prompt-DEkStuxG.js → prompt-C5CW2wKO.js} +1 -1
  44. package/dist/{reports-C1d9azyV.js → reports-eBgrhPXS.js} +2 -2
  45. package/dist/{resolve-DC6zBuDV.js → resolve-HVXmbeCr.js} +5 -5
  46. package/dist/{result-DxewDuXb.js → result-BPNzgeTl.js} +20 -9
  47. package/dist/{runner-99YxVN_r.js → runner-aNSDTST6.js} +7 -8
  48. package/dist/{sandbox-egress-signals-CgoX5CTI.js → sandbox-egress-signals-nzp9Ykf7.js} +1 -1
  49. package/dist/{schema-BTojNBr5.js → schema-BlTO5M1d.js} +16 -8
  50. package/dist/{service-account-YDCPSByj.js → service-account-DWIf1t6p.js} +4 -5
  51. package/dist/{skills-CleC0Hze.js → skills-50izzzdK.js} +9 -9
  52. package/dist/{slack-conversation-unfurl-BNQLC12R.js → slack-conversation-unfurl-C6jXhVYg.js} +7 -7
  53. package/dist/storage-BtCxXiNt.js +273 -0
  54. package/dist/{system-prompt-table-Ci6Ck4gk.js → system-prompt-table-CIR1B44Z.js} +27 -85
  55. package/dist/topic-B2EWKKBT.js +6 -0
  56. package/dist/{package-discovery-DD9vencX.js → topics-DxuKurCX.js} +21 -1
  57. package/dist/{types-DCzTAA63.js → types-BNHkJrOP.js} +25 -11
  58. package/dist/{users-Cb9c1k9q.js → users-DOVo9sdU.js} +1 -1
  59. package/dist/{validation-BiUmWPhy.js → validation-CK0vuEHB.js} +4 -4
  60. package/dist/{version-VEXiEcZu.js → version-BuLVNlxB.js} +1 -1
  61. package/dist/version.js +1 -1
  62. package/dist/{worker-ChWYQdhm.js → worker-C82kHU1R.js} +4 -4
  63. package/migrations/20261127052408_space_name_nullable/migration.sql +5 -0
  64. package/migrations/20261127052408_space_name_nullable/snapshot.json +29 -0
  65. package/migrations/20261127060000_annotation_object_id_index/migration.sql +1 -0
  66. package/migrations/20261127060000_annotation_object_id_index/snapshot.json +69 -0
  67. package/migrations/20261127060001_annotation_subjects/migration.sql +78 -0
  68. package/migrations/20261127060001_annotation_subjects/snapshot.json +104 -0
  69. package/migrations/20261127060002_annotation_subject_index/migration.sql +1 -0
  70. package/migrations/20261127060002_annotation_subject_index/snapshot.json +70 -0
  71. package/migrations/20261127060003_annotation_title_url/migration.sql +84 -0
  72. package/migrations/20261127060003_annotation_title_url/snapshot.json +73 -0
  73. package/migrations/20261127150242_drop_space_members/migration.sql +9 -0
  74. package/migrations/20261127150242_drop_space_members/snapshot.json +53 -0
  75. package/package.json +9 -7
  76. package/dist/auth-pause-state-f9hJM_zO.js +0 -113
  77. package/dist/catalog-runtime-BfdAnztW.js +0 -6
  78. package/dist/child-message-peFWLcCZ.js +0 -15
  79. package/dist/conversation-turn-Bru4w_FD.js +0 -1250
  80. package/dist/job-runner-B2XEvpif.js +0 -1505
  81. package/dist/lineage-nh4z9iQN.js +0 -36
  82. package/dist/list-HRP3TIRl.js +0 -12631
  83. package/dist/markers-CTTtJqYn.js +0 -342
  84. package/dist/message-BRUuLgrY.js +0 -153
  85. package/dist/model-input-CFC62mf-.js +0 -82
  86. package/dist/registry-Cl7Labpe.js +0 -3279
  87. package/dist/run-conversation-Cz2ubZK-.js +0 -337
  88. package/dist/sender-actors-77zTQbSG.js +0 -84
  89. package/dist/spawn-DuZfodPa.js +0 -45
  90. package/dist/task-runner-BJ9Up3bG.js +0 -1529
  91. package/dist/topic-CRYYBYp-.js +0 -7
  92. package/dist/topics-BoCkoPJJ.js +0 -21
  93. package/dist/turn-membership-VT7XZh-L.js +0 -856
  94. package/dist/turn-wake-C7HeLHAM.js +0 -151
package/dist/app.js CHANGED
@@ -1,43 +1,37 @@
1
- import { E as parseSlackChannelId, F as slackMessageTsFromMs, G as loadConfig, I as slackMessageTsSchema, K as parseEnvList, L as botConfig, M as slackTeamIdSchema, P as parseSlackMessageTs, R as getChatConfig, S as MUTATION_LOCK_TTL_MS, T as withLock, W as installChatConfig, c as createSlackActor, j as slackChannelIdSchema, p as parseActorUserId, w as fenceLock, y as getStateAdapter } from "./context-BKF_5zzI.js";
2
- import { Ad as juniorTurnOutbox, Ci as postSlackEphemeralMessage, Dt as validatePlugins, Ea as automationVersionOf, En as pruneActiveConversation, Et as setPlugins, Fr as verifyConversationQueueMessage, Ga as refreshAutomationLastRun, Hn as resolveSlackInboxItemCardConversationId, Hs as getWorkspaceTeamId, Jn as parseSlackInboxItemFormTarget, Jo as subjectKey, Jr as annotationKeyDigest, Kc as deleteExpiredInboxSnoozes, Kn as buildSlackInboxItemModal, Lr as conversationQueueMessageSchema, Ms as getSlackClient, Nr as getVercelConversationWorkQueue, O as withConversationMutationLock, Oi as slackEntitySchema, Pa as existingConversationId, Pi as slackMention, Po as takeDueTimerWatches, Pr as resolveConversationWorkTopic, Q as canActOnInboxItem, Qa as syncAutomationAlerts, R as conversationCostOf, Rd as juniorQuestions, Rn as createInboxItemShow, Rr as isConversationQueueMessageRejectedError, Sf as juniorDestinations, Si as openSlackModal, Sn as hasRunnableConversationWork, St as inboxItemVisibility, Su as createConversationEmbedder, Tc as searchInboxItems, Un as syncInboxItemSlackCards, Ur as getQueueProvider, Us as runWithWorkspaceTeamId, Ut as appendAndEnqueueInboundMessage, Vd as juniorAutomationRuns, Vn as runInboxItemPushTimers, Wd as juniorAutomations, Wn as findSlackThreadOwnerId, Xn as parseSlackUserInputSubmission, Xr as runWithSlackInstallation, Xs as resolveViewerUser, Yd as juniorInboxItems, Yr as decodeAnnotationRef, Zd as juniorAgentBindings, Zr as verifySlackSignature, Zt as clearExpiredConversationLease, _i as notifyAutomationBlocked, a as getDb, af as juniorTurns, an as getConversationWorkState, ar as createVercelPluginTaskCallback, bd as touchConversationDetail, bu as isEventEmbeddingsEnabled, ca as readScheduledAutomation, co as SLACK_EVENT_NAMESPACE, cr as sendVercelPluginTask, cu as embedConversationEvents, da as scheduledRunId, di as listPendingDispatchMailboxAppends, dl as projectConversationMessages, ec as resolveActorIdentityId, ef as juniorConversationEventLexemes, er as createPluginEventPublisher, et as canAnswerInboxItem, fa as withScheduledAutomationLock, fs as isPublicConversation, hf as juniorConversations, hi as markDispatchFailed, ht as isPluginInboxItem, i as getConversationStore, if as juniorConversationEvents, ii as getDispatchConversationId, in as getConversation, is as listConversationAnnotations, jc as itemQuestion, jd as juniorTurnInbox, ki as slackExternalRefIdSchema, lr as queueCallback, lt as inboxItemReaderForUser, lu as eventIndexLockKey, m as deleteMessageLinks, mu as storeConversationEventLexemes, n as getConversationEventStore, nf as juniorConversationEmbeddings, ni as confirmDispatchMailboxAppend, nl as getDashboardInboxItemLink, nr as getPluginRoutes, o as getSqlExecutor, oa as listScheduledAutomationsForTeam, qn as parseSlackInboxItemClick, qr as renderSlackObjectCard, qs as readActorIdentity, rn as ensureConversationWake, rt as inboxItemAddedByAnyAutomation, sc as recordGoogleSignIn, si as getDispatchRecord, sl as getDashboardTaskLink, sn as listActiveConversationIds, su as EVENT_INDEX_LOCK_TTL_MS, tf as juniorConversationEventEmbeddings, tl as getDashboardConversationLink, tr as getPluginApiRoutes, ts as resumeConversationDelivery, u as isPostgresErrorCode, ua as saveScheduledAutomationInLock, ui as isTerminalDispatchStatus, uo as slackChannelMessageEvent, ut as inboxItemReaderForUserInConversation, v as withConversationEventLock, vn as CONVERSATION_WORK_STALE_ENQUEUE_MS, vr as canAddConversationMessages, wn as isInvalidConversationRecordError, wr as readConversationAccessFromSql, wt as getRegistrations, xd as createSlackDestination, xt as inboxItemOwnerConversationId, xu as backfillConversationEmbeddings, yc as dismissOpenInboxItems, zc as parseAvatarUrl, zn as pushConversationInboxItemsNow } from "./db-of6e3sGt.js";
3
- import { C as withContext, D as GOOGLE_IDENTITY_PROVIDER, T as withSpan, f as logException, k as normalizeIdentityEmail, m as logWarn, n as createRequestContext, p as logInfo, w as withLogContext, y as setSpanAttributes } from "./logging-BnOG0qz2.js";
4
- import { A as vercelBackgroundCompactionQueue, At as parseSlackThreadId, Ft as unpublishedArtifactHeaders, K as stopConversation, N as createVercelCacheWarmupCallback, Nt as publicArtifactHeaders, Pt as readPublicArtifact, Qt as automationCardStatus, W as markConversationRead, Wt as ViewerTaskNotFoundError, X as inboxItemChangeRecord, Y as deliverInboxItemChange, Yt as readViewerAutomationSummary, Z as renderInboxItemMessage, Zt as readViewerAutomations, ct as appendAndEnqueueWebMessage, d as logScheduledAutomationRunSkipped, en as findAutomationSkill, f as scheduledAutomationRunAttributes, ft as recordWebConversationActivity, gt as collectAttachmentUploadGarbage, j as verifyBackgroundCompactionMessage, k as processBackgroundCompaction, lt as conversationTurnIdForMessage, n as executeAgentRun, nn as effectiveTaskOutcomes, pt as webActorFromUser, qt as readViewerAutomationExecutions, t as createAgentRunner, tn as missingAutomationSkillReason, ut as createAndEnqueueConversation } from "./agent-runner-DeYymwh2.js";
5
- import { A as createUserTokenStore, C as clearSandboxEgressSignals, D as parseSandboxEgressCredentialToken, P as normalizeSandboxEgressTracePropagationDomains, T as consumeSandboxEgressPermissionDeniedSignal, c as isVercelSandboxEgressRequest, l as proxyVercelSandboxEgressRequest, w as consumeSandboxEgressAuthRequiredSignal } from "./profile-iHw1uu32.js";
6
- import { n as pluginCatalogRuntime } from "./catalog-runtime-BfdAnztW.js";
7
- import { $ as reviewItemChange, At as createProductionSlackWebhookServices, B as mcpIdempotencyKeySchema, Bt as startProcessingReaction, Dt as isPublicAddress, F as mcpAuthorizationSchema$1, Ft as normalizeIncomingSlackThreadId, G as readMcpPendingWork, H as mcpMessageTextSchema, Ht as parseContent, I as mcpConversation, It as withNormalizedThreadId, K as readMcpPendingWorkAfterSend, Kt as readConversationRecordFromSql, L as mcpConversationIdSchema, Lt as recordSkippedConversationMessage, Mt as buildSlackInboundMessage, Nt as clearSlackPendingReactions, Ot as publicAddressLookup, P as mcpAcceptedMessageSchema, Pt as slackInboundMessageId, Q as readInboxItemForUser, R as mcpConversationSchema, Rt as createSlackWebApiStatusSender, St as readObjectLinkTypes, U as mcpMessages, Ut as SubscribedReplyReason, V as mcpMessageSchema, Vt as stripLeadingBotMention, W as mcpPendingMessagesSchema, Wt as getThreadStopDecision, X as actOnInboxItem, Y as InboxItemActionError, Z as closeInboxItemsAnsweredByReply, _ as createConversationForViewer, _t as backfillCacheWarmingGaps, a as resolveInboxItemSubjects, b as encodeConversationCursor, ct as listOpenAutomationQuestions, dt as getScheduledAutomationDispatch, et as createEventAppPublisher, ft as runInboxSnoozeTimers, g as appendConversationMessageForViewer, ht as runSavingsRefillSlice, jt as getProductionSlackAdapter, kt as createProductionConversationWorkOptions, lt as createHeartbeatContext, n as readConversationFeed, nt as runAutoArchiveSweep, o as readConversationDetail, ot as automationReplyAttribution, st as settleEventAutomationRuns, tt as ingestEventAutomations, ut as dispatchScheduledAutomation, vt as GET$4, w as conversationOperations, y as decodeConversationCursor, z as mcpCursorSchema, zt as bindMessageAuthorIdentityId } from "./list-HRP3TIRl.js";
8
- import { n as validatePluginRegistrations, t as validatePluginEgressCredentialHooks } from "./validation-BiUmWPhy.js";
1
+ import { C as parseActorUserId, E as parseSlackChannelId, F as slackMessageTsFromMs, G as loadConfig, I as slackMessageTsSchema, K as parseEnvList, L as botConfig, M as slackTeamIdSchema, P as parseSlackMessageTs, R as getChatConfig, W as installChatConfig, i as getStateAdapter, j as slackChannelIdSchema, l as fenceLock, s as MUTATION_LOCK_TTL_MS, u as withLock, v as createSlackActor } from "./adapter-DlLLoJKj.js";
2
+ import { $ as canActOnInboxItem, $r as annotationKeyDigest, As as isPublicConversation, Au as embedConversationEvents, Br as verifyConversationQueueMessage, Cl as getDashboardInboxItemLink, Cr as canAddConversationMessages, Ct as inboxItemOwnerConversationId, Di as openSlackModal, Dt as validatePlugins, Ec as recordGoogleSignIn, En as pruneActiveConversation, Ep as juniorConversationEmbeddings, Et as getRegistrations, Fd as installAppContext, Gf as createSlackDestination, Hn as resolveSlackInboxItemCardConversationId, Hr as conversationQueueMessageSchema, Hu as isEventEmbeddingsEnabled, Iu as storeConversationEventLexemes, Jn as parseSlackInboxItemFormTarget, Jr as getQueueProvider, Kn as buildSlackInboxItemModal, Kp as juniorDestinations, Nd as createAppContext, Ni as slackEntitySchema, Nl as projectConversationMessages, O as withConversationMutationLock, Oi as postSlackEphemeralMessage, Ol as getDashboardTaskLink, Op as juniorConversationEvents, Pd as getAppContext, Pi as slackExternalRefIdSchema, Qr as renderSlackObjectCard, Rc as dismissOpenInboxItems, Rn as createInboxItemShow, Rr as getVercelConversationWorkQueue, Si as notifyAutomationBlocked, Sl as getDashboardConversationLink, Sn as hasRunnableConversationWork, Tp as juniorConversationEventEmbeddings, U as conversationIsActiveSql, Un as syncInboxItemSlackCards, Ur as isConversationQueueMessageRejectedError, Ut as appendAndEnqueueInboundMessage, Uu as backfillConversationEmbeddings, Vn as runInboxItemPushTimers, Wc as searchInboxItems, Wf as touchConversationDetail, Wn as findSlackThreadOwnerId, Wu as createConversationEmbedder, Xa as refreshAutomationLastRun, Xc as itemQuestion, Xn as parseSlackUserInputSubmission, Xs as getSlackClient, Zt as clearExpiredConversationLease, _a as withScheduledAutomationLock, a as getDb, an as getConversationWorkState, ar as createVercelPluginTaskCallback, at as inboxItemAddedByAnyAutomation, bi as markDispatchFailed, cp as juniorQuestions, cr as sendVercelPluginTask, da as listScheduledAutomationsForTeam, dc as readActorIdentity, dp as juniorAutomationRuns, dt as inboxItemReaderForUserInConversation, ei as decodeAnnotationRef, ep as juniorTurnOutbox, er as createPluginEventPublisher, es as resumeConversationDelivery, fi as getDispatchRecord, ga as scheduledRunId, gi as listPendingDispatchMailboxAppends, gt as isPluginInboxItem, ha as saveScheduledAutomationInLock, hc as resolveViewerUser, hi as isTerminalDispatchStatus, ho as slackChannelMessageEvent, i as getConversationStore, in as getConversation, ja as automationVersionOf, ju as eventIndexLockKey, kp as juniorTurns, kr as readConversationAccessFromSql, ku as EVENT_INDEX_LOCK_TTL_MS, li as getDispatchConversationId, lr as queueCallback, m as deleteMessageLinks, mp as juniorAutomations, n as getConversationEventStore, ni as verifySlackSignature, nr as getPluginRoutes, o as getSqlExecutor, oc as getWorkspaceTeamId, ol as parseAvatarUrl, pa as readScheduledAutomation, pl as deleteExpiredInboxSnoozes, po as SLACK_EVENT_NAMESPACE, qn as parseSlackInboxItemClick, rn as ensureConversationWake, ro as syncAutomationAlerts, sc as runWithWorkspaceTeamId, si as confirmDispatchMailboxAppend, sn as listActiveConversationIds, ss as subjectKey, ti as runWithSlackInstallation, tp as juniorTurnInbox, tr as getPluginApiRoutes, tt as canAnswerInboxItem, u as isPostgresErrorCode, ut as inboxItemReaderForUser, v as withConversationEventLock, vn as CONVERSATION_WORK_STALE_ENQUEUE_MS, wn as isInvalidConversationRecordError, wp as juniorConversationEventLexemes, wt as inboxItemVisibility, xp as juniorAgentBindings, yc as resolveActorIdentityId, yp as juniorInboxItems, ys as listConversationAnnotations, z as conversationCostOf, za as existingConversationId, zi as slackMention, zn as pushConversationInboxItemsNow, zo as takeDueTimerWatches, zp as juniorConversations, zr as resolveConversationWorkTopic } from "./db-BacvswT0.js";
3
+ import { C as withContext, D as GOOGLE_IDENTITY_PROVIDER, T as withSpan, f as logException, k as normalizeIdentityEmail, m as logWarn, n as createRequestContext, p as logInfo, w as withLogContext, y as setSpanAttributes } from "./logging-DsTnMqyi.js";
4
+ import { $ as slackInboundMessageId, C as processWorkspaceSnapshotJob, Cn as recordWebConversationActivity, En as collectAttachmentUploadGarbage, F as markConversationRead, Ft as isPublicAddress, Gn as readPublicArtifact, Hn as requestAttachmentDeletion, It as publicAddressLookup, J as getProductionSlackAdapter, K as createProductionConversationWorkOptions, Kn as unpublishedArtifactHeaders, L as deliverInboxItemChange, Q as clearSlackPendingReactions, R as inboxItemChangeRecord, S as createVercelCacheWarmupCallback, T as ingestEvent, Un as parseSlackThreadId, Ut as readConversationRecordFromSql, Wn as publicArtifactHeaders, Z as buildSlackInboundMessage, _t as recordSkippedConversationMessage, ar as readViewerAutomationSummary, at as enqueueAgentDispatch, b as vercelBackgroundCompactionQueue, bn as conversationTurnIdForMessage, cn as startProcessingReaction, dr as effectiveTaskOutcomes, dt as readConversationEventPage, er as ViewerTaskNotFoundError, et as normalizeIncomingSlackThreadId, fn as SubscribedReplyReason, ft as readConversationEventPageAfter, ht as readConversationMessageEventSeq, i as scheduledAutomationRunAttributes, in as bindMessageAgent, kt as readObjectLinkTypes, ln as stripLeadingBotMention, lr as findAutomationSkill, mt as readConversationLastEventSeq, on as createAgentRunner, ot as failStoppedDispatch, pn as getThreadStopDecision, q as createProductionSlackWebhookServices, r as logScheduledAutomationRunSkipped, rr as readViewerAutomationExecutions, sn as bindMessageAuthorIdentityId, sr as readViewerAutomations, st as processPluginTask, t as executeAgentRun, tn as bindSpawnAgent, tt as withNormalizedThreadId, un as parseContent, ur as missingAutomationSkillReason, vt as stopConversation, w as verifyWorkspaceSnapshotJobMessage, wn as webActorFromUser, wt as readLiveAnnotations, x as verifyBackgroundCompactionMessage, xn as createAndEnqueueConversation, y as processBackgroundCompaction, yn as appendAndEnqueueWebMessage, yt as createSlackWebApiStatusSender, z as renderInboxItemMessage, zn as collectAttachmentGarbage } from "./agent-DxZ7nHfD.js";
5
+ import { A as createUserTokenStore, C as clearSandboxEgressSignals, D as parseSandboxEgressCredentialToken, P as normalizeSandboxEgressTracePropagationDomains, T as consumeSandboxEgressPermissionDeniedSignal, c as isVercelSandboxEgressRequest, l as proxyVercelSandboxEgressRequest, w as consumeSandboxEgressAuthRequiredSignal } from "./profile-v9vA3RvH.js";
6
+ import { n as validatePluginRegistrations, t as validatePluginEgressCredentialHooks } from "./validation-CK0vuEHB.js";
9
7
  import { a as pluginRuntimeRegistrationsFromPluginSet, n as pluginCatalogConfigFromEnv, r as pluginCatalogConfigFromPluginSet, t as defineJuniorPlugins } from "./plugins-D_Ru4CWc.js";
10
- import { n as processWorkspaceSnapshotJob, o as ingestEvent, r as verifyWorkspaceSnapshotJobMessage } from "./job-runner-B2XEvpif.js";
11
- import { o as enqueueAgentDispatch, s as failStoppedDispatch } from "./run-conversation-Cz2ubZK-.js";
12
- import { I as findTrustedUser, It as renderTaskInput, L as isAllowedDomain, Nn as appendConversationMessages, R as isTrustedSlackAuthor, Rn as settleConversationTitleWork, gt as coerceThreadConversationState, rn as isExperimentalFeatureEnabled, t as getAuthPausedConversationTurnId, z as parseEmail } from "./mailbox-turn-Byrry9o1.js";
13
- import { Bt as annotationCard, Dn as automationTaskSchema, Nn as getNextRunAtMs, On as automationTaskText, _ as automationListQuerySchema, _n as buttonUserInputField, fn as inboxItemQuestion, p as automationExecutionStatusSchema, rn as scheduledRunSchema } from "./types-DCzTAA63.js";
14
- import { t as createEndStoppedChildWork } from "./result-DxewDuXb.js";
15
- import { l as collectAttachmentGarbage, p as requestAttachmentDeletion, y as getAttachmentStorage } from "./turn-membership-VT7XZh-L.js";
16
- import { h as createPluginLogger } from "./prompt-DEkStuxG.js";
8
+ import { $ as reviewItemChange, B as mcpIdempotencyKeySchema, F as mcpAuthorizationSchema$1, G as readMcpPendingWork, H as mcpMessageTextSchema, I as mcpConversation, K as readMcpPendingWorkAfterSend, L as mcpConversationIdSchema, P as mcpAcceptedMessageSchema, Q as readInboxItemForUser, R as mcpConversationSchema, U as mcpMessages, V as mcpMessageSchema, W as mcpPendingMessagesSchema, X as actOnInboxItem, Y as InboxItemActionError, Z as closeInboxItemsAnsweredByReply, _ as createConversationForViewer, _t as backfillCacheWarmingGaps, a as resolveInboxItemSubjects, b as encodeConversationCursor, ct as listOpenAutomationQuestions, dt as getScheduledAutomationDispatch, et as createEventAppPublisher, ft as runInboxSnoozeTimers, g as appendConversationMessageForViewer, ht as runSavingsRefillSlice, lt as createHeartbeatContext, n as readConversationFeed, nt as runAutoArchiveSweep, o as readConversationDetail, ot as automationReplyAttribution, st as settleEventAutomationRuns, tt as ingestEventAutomations, ut as dispatchScheduledAutomation, vt as GET$4, w as conversationOperations, y as decodeConversationCursor, z as mcpCursorSchema } from "./list-Dz3CdP3g.js";
9
+ import { Bn as appendConversationMessages, F as getAuthPausedConversationTurnId, Kn as settleConversationTitleWork, Z as coerceThreadConversationState, ft as findTrustedUser, ht as parseEmail, jt as renderTaskInput, mt as isTrustedSlackAuthor, pt as isAllowedDomain, un as isExperimentalFeatureEnabled } from "./markers-C33gNYNE.js";
10
+ import { Bt as annotationCard, Kt as automationCardStatus, On as automationTaskSchema, Pn as getNextRunAtMs, _ as automationListQuerySchema, in as scheduledRunSchema, kn as automationTaskText, p as automationExecutionStatusSchema, pn as inboxItemQuestion, vn as buttonUserInputField } from "./types-BNHkJrOP.js";
11
+ import { t as createEndStoppedChildWork } from "./result-BPNzgeTl.js";
12
+ import { h as createPluginLogger } from "./prompt-C5CW2wKO.js";
13
+ import { n as getAttachmentStorage } from "./storage-BtCxXiNt.js";
17
14
  import { i as getActiveSpan, u as sentry_exports } from "./sentry-CPbZjomA.js";
18
- import { a as GET$5, i as publishAppHomeView, r as GET$6, t as receiveLocalOAuthCredential } from "./credential-sync-DTarZ63K.js";
15
+ import { a as GET$5, i as publishAppHomeView, r as GET$6, t as receiveLocalOAuthCredential } from "./credential-sync-Bj9-UlNE.js";
19
16
  import { t as nameRequestRoute } from "./sentry-route-name-C6EIzAGP.js";
20
17
  import { t as SANDBOX_EGRESS_PROXY_PATH } from "./proxy-path-BHYoKZdq.js";
21
- import { a as resolveSlackActingUser, i as unfurlDashboardConversationLinks, n as handleSlackContinueHereClick, o as isSlackWorkspaceMember, s as slackWorkspaceBotId, t as SLACK_CONTINUE_HERE_ACTION_ID } from "./slack-conversation-unfurl-BNQLC12R.js";
22
- import { l as unlinkProvider, n as renderHtmlPage, r as requestHasSameOrigin, t as escapeHtml } from "./html-9_pS9SjY.js";
23
- import { s as joinPublicChannel } from "./channel-access-A0de5lRv.js";
24
- import { a as JUNIOR_CONVERSATION_WORK_CALLBACK_ROUTE, f as JUNIOR_TURN_STEP_CALLBACK_ROUTE, i as JUNIOR_CONTEXT_COMPACTION_CALLBACK_ROUTE, l as JUNIOR_PLUGIN_TASK_CALLBACK_ROUTE, n as JUNIOR_AUTO_ARCHIVE_ROUTE, o as JUNIOR_DELIVERY_CALLBACK_ROUTE, p as JUNIOR_WORKSPACE_SNAPSHOT_JOB_CALLBACK_ROUTE, r as JUNIOR_CACHE_WARMUP_CALLBACK_ROUTE } from "./deployment-C0qXa0FD.js";
25
- import { t as processConversationWork } from "./worker-ChWYQdhm.js";
26
- import { t as bindMessageAgent } from "./message-BRUuLgrY.js";
27
- import { t as bindSpawnAgent } from "./spawn-DuZfodPa.js";
28
- import { l as readConversationLastEventSeq, o as readConversationEventPage, s as readConversationEventPageAfter, t as processPluginTask, u as readConversationMessageEventSeq } from "./task-runner-BJ9Up3bG.js";
29
- import { c as replyText, d as publishTurnStep, f as countMetric, i as turnStepConsumer, l as createDeliveryConsumer, n as turnTools, o as findStalledTurns, p as withSpan$1, r as createGatewayModelClient, s as findStalledDeliveries, t as createEngineContext, u as publishDelivery } from "./engine-context-C_QL_bMQ.js";
30
- import { t as JUNIOR_VERSION } from "./version-VEXiEcZu.js";
31
- import { D as conversationPendingMessageDeliverySchema, f as conversationTitleSchema, t as conversationFeedQuerySchema } from "./conversation-feed-Cj7IuBtM.js";
18
+ import { a as resolveSlackActingUser, i as unfurlDashboardConversationLinks, n as handleSlackContinueHereClick, o as isSlackWorkspaceMember, s as slackWorkspaceBotId, t as SLACK_CONTINUE_HERE_ACTION_ID } from "./slack-conversation-unfurl-C6jXhVYg.js";
19
+ import { l as unlinkProvider, n as renderHtmlPage, r as requestHasSameOrigin, t as escapeHtml } from "./html-DW0pw5Pr.js";
20
+ import { s as joinPublicChannel } from "./channel-access-BghWqlXx.js";
21
+ import { a as JUNIOR_CONVERSATION_WORK_CALLBACK_ROUTE, c as JUNIOR_PLUGIN_TASK_CALLBACK_ROUTE, d as JUNIOR_TURN_ENDED_CALLBACK_ROUTE, f as JUNIOR_TURN_STEP_CALLBACK_ROUTE, i as JUNIOR_CONTEXT_COMPACTION_CALLBACK_ROUTE, n as JUNIOR_AUTO_ARCHIVE_ROUTE, p as JUNIOR_WORKSPACE_SNAPSHOT_JOB_CALLBACK_ROUTE, r as JUNIOR_CACHE_WARMUP_CALLBACK_ROUTE } from "./deployment-BoJkRPDt.js";
22
+ import { t as processConversationWork } from "./worker-C82kHU1R.js";
23
+ import { a as createGatewayModelClient, c as findStalledTurns, d as countMetric, f as withSpan$1, i as turnTools, l as publishTurnEnded, n as createDeploymentDelivery, o as turnStepConsumer, r as turnEndedConsumer, t as createEngineContext, u as publishTurnStep } from "./engine-context-Bi3Ync5t.js";
24
+ import { t as JUNIOR_VERSION } from "./version-BuLVNlxB.js";
25
+ import { D as conversationPendingMessageDeliverySchema, f as conversationTitleSchema, t as conversationFeedQuerySchema } from "./conversation-feed-DEUdD7mb.js";
32
26
  import { t as isMissingVirtualModule } from "./virtual-module-BeKA_EII.js";
33
27
  import { createRequire } from "node:module";
34
28
  import { Hono } from "hono";
35
29
  import * as z from "zod";
36
- import { and, asc, desc, eq, gt, gte, inArray, isNotNull, isNull, lt, lte, ne, not, notExists, or, sql } from "drizzle-orm";
37
- import { pgTable, text } from "drizzle-orm/pg-core";
38
- import { destinationSchema, eventTriggerFiltersText, identityDispatchOptionsSchema, userSchema } from "@sentry/junior-plugin-api";
39
- import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
30
+ import { and, asc, desc, eq, gt, gte, inArray, isNotNull, isNull, lt, lte, ne, not, notExists, notInArray, or, sql } from "drizzle-orm";
31
+ import { alias, pgTable, text } from "drizzle-orm/pg-core";
32
+ import { eventTriggerFiltersText, identityDispatchOptionsSchema, userSchema } from "@sentry/junior-plugin-api";
40
33
  import { pathToFileURL } from "node:url";
34
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
41
35
  import { Message, ThreadImpl } from "chat";
42
36
  import net from "node:net";
43
37
  import { decodeJwt } from "jose";
@@ -110,7 +104,8 @@ async function listActiveConversations(db, args) {
110
104
  const after = args.after;
111
105
  return await withScanTimeout(db, async (tx) => await tx.select({
112
106
  at: sql`to_char(${conversations.lastActivityAt} at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`,
113
- conversationId: conversations.conversationId
107
+ conversationId: conversations.conversationId,
108
+ turnActive: conversationIsActiveSql(conversations)
114
109
  }).from(conversations).where(and(gte(conversations.lastActivityAt, new Date(args.sinceMs)), after ? or(lt(conversations.lastActivityAt, sql`${after.at}::timestamptz`), and(eq(conversations.lastActivityAt, sql`${after.at}::timestamptz`), gt(conversations.conversationId, after.conversationId))) : void 0)).orderBy(desc(conversations.lastActivityAt), conversations.conversationId).limit(CONVERSATION_PAGE_SIZE));
115
110
  }
116
111
  async function hasMissingVector(tx, embedder, conversationId) {
@@ -154,6 +149,7 @@ async function backfillEventSearchIndex(args) {
154
149
  const run = {
155
150
  conversations: 0,
156
151
  lexemes: 0,
152
+ running: 0,
157
153
  skipped: 0,
158
154
  vectors: 0
159
155
  };
@@ -174,7 +170,12 @@ async function backfillEventSearchIndex(args) {
174
170
  after,
175
171
  sinceMs
176
172
  });
177
- for (const conversation of page) {
173
+ for (const { turnActive, ...conversation } of page) {
174
+ if (turnActive) {
175
+ run.running += 1;
176
+ after = conversation;
177
+ continue;
178
+ }
178
179
  const lexemeRoom = MAX_LEXEME_EVENTS_PER_RUN - run.lexemes;
179
180
  const vectorRoom = MAX_VECTOR_EVENTS_PER_RUN - run.vectors;
180
181
  if (Date.now() >= args.deadlineMs || lexemeRoom <= 0 || args.embedder && vectorRoom <= 0) return {
@@ -242,6 +243,7 @@ async function runEventSearchBackfill(args) {
242
243
  setSpanAttributes({
243
244
  "app.event_search.backfill.conversation.count": result.run.conversations,
244
245
  "app.event_search.backfill.skipped.count": result.run.skipped,
246
+ "app.event_search.backfill.running.count": result.run.running,
245
247
  "app.event_search.backfill.lexeme.count": result.run.lexemes,
246
248
  "app.event_search.backfill.vector.count": result.run.vectors,
247
249
  "app.event_search.backfill.pass.conversation.count": result.pass.conversations,
@@ -1608,7 +1610,10 @@ const eventSchema = z.object({
1608
1610
  id: slackExternalRefIdSchema
1609
1611
  })
1610
1612
  });
1611
- /** Show saved annotation facts only to a viewer who can read their Conversation. */
1613
+ /**
1614
+ * Show an annotation's object, as the viewer can read it now, only to a
1615
+ * viewer who can read its Conversation.
1616
+ */
1612
1617
  async function presentSlackAnnotationDetails(event, teamId) {
1613
1618
  const triggerId = event["trigger_id"];
1614
1619
  if (typeof triggerId !== "string" || !triggerId) return;
@@ -1650,12 +1655,13 @@ async function presentSlackAnnotationDetails(event, teamId) {
1650
1655
  await missing();
1651
1656
  return;
1652
1657
  }
1653
- const annotation = (await listConversationAnnotations(db, conversationId)).find((item) => annotationKeyDigest(item.plugin, item.key) === keyDigest);
1654
- if (!annotation) {
1658
+ const saved = (await listConversationAnnotations(db, conversationId)).find((item) => annotationKeyDigest(item.plugin, item.key) === keyDigest);
1659
+ if (!saved) {
1655
1660
  await missing();
1656
1661
  return;
1657
1662
  }
1658
- const entity = renderSlackObjectCard(annotationCard(annotation), conversationId, "details").entity;
1663
+ const [annotation] = await readLiveAnnotations(identity.user, [saved]);
1664
+ const entity = annotation && renderSlackObjectCard(annotationCard(annotation), conversationId, "details").entity;
1659
1665
  if (!entity) {
1660
1666
  await missing();
1661
1667
  return;
@@ -3263,161 +3269,23 @@ function backgroundCompactionCallback() {
3263
3269
  function createVercelBackgroundCompactionCallback() {
3264
3270
  return backgroundCompactionCallback().create();
3265
3271
  }
3266
- // src/core/delivery/deliver.ts
3267
- /**
3268
- * A send that failed but can work on a later try. The sender sets
3269
- * `retryAfterMs` when the provider says when to try again.
3270
- */
3271
- var DeliveryRetryableError = class extends Error {
3272
- retryAfterMs;
3273
- constructor(message, options = {}) {
3274
- super(message, { cause: options.cause });
3275
- this.name = "DeliveryRetryableError";
3276
- this.retryAfterMs = options.retryAfterMs;
3277
- }
3278
- };
3279
- const LOCK_MISS_DELAY_MS = 1e3;
3280
- const MAX_DELIVERY_ATTEMPTS = 5;
3281
- const RETRY_BASE_DELAY_MS = 1e3;
3282
- const RETRY_MAX_DELAY_MS = 6e4;
3283
- const tryLockResultSchema = z.object({ rows: z.tuple([z.object({ locked: z.boolean() })]) });
3284
- /**
3285
- * Sends the Conversation's pending outbox rows in event order, each to the
3286
- * Destination stored on its row.
3287
- */
3288
- async function deliverTurn({ executor, queue }, message, delivery) {
3289
- while (true) {
3290
- const next = await executor.transaction(() => sendNextRow({ executor }, message.conversationId, delivery));
3291
- if (next.kind === "idle") return;
3292
- if (next.kind === "later") {
3293
- await publishDelivery({ queue }, message, { delayMs: next.delayMs });
3294
- return;
3295
- }
3296
- }
3297
- }
3298
- /**
3299
- * Sends the Conversation's first pending row, if this transaction gets the
3300
- * Conversation's lock. A retryable failure leaves the row pending, so the
3301
- * rows after it wait.
3302
- */
3303
- async function sendNextRow({ executor }, conversationId, delivery) {
3304
- const db = executor.db();
3305
- if (!tryLockResultSchema.parse(await db.execute(sql`select pg_try_advisory_xact_lock(hashtext(${`junior:delivery:${conversationId}`})) as locked`)).rows[0].locked) return {
3306
- kind: "later",
3307
- delayMs: LOCK_MISS_DELAY_MS
3308
- };
3309
- const [row] = await db.select({
3310
- id: juniorTurnOutbox.id,
3311
- eventSeq: juniorTurnOutbox.eventSeq,
3312
- destination: juniorTurnOutbox.destination,
3313
- attempts: juniorTurnOutbox.attempts
3314
- }).from(juniorTurnOutbox).where(and(eq(juniorTurnOutbox.conversationId, conversationId), eq(juniorTurnOutbox.state, "pending"))).orderBy(asc(juniorTurnOutbox.eventSeq)).limit(1);
3315
- if (!row) return { kind: "idle" };
3316
- const markFailed = async (error) => {
3317
- await db.update(juniorTurnOutbox).set({
3318
- state: "failed",
3319
- error,
3320
- updatedAt: /* @__PURE__ */ new Date()
3321
- }).where(eq(juniorTurnOutbox.id, row.id));
3322
- return { kind: "settled" };
3323
- };
3324
- const destination = destinationSchema.parse(row.destination);
3325
- const [event] = await db.select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.seq, row.eventSeq)));
3326
- const text = event ? replyText(event) : void 0;
3327
- if (!text) return markFailed("The event is not a reply");
3328
- try {
3329
- const result = await delivery.send({
3330
- conversationId,
3331
- destination,
3332
- text
3333
- });
3334
- const now = /* @__PURE__ */ new Date();
3335
- await db.update(juniorTurnOutbox).set({
3336
- state: "sent",
3337
- sentAt: now,
3338
- updatedAt: now,
3339
- providerMessageId: result.providerMessageId ?? null
3340
- }).where(eq(juniorTurnOutbox.id, row.id));
3341
- return { kind: "settled" };
3342
- } catch (error) {
3343
- const attempts = row.attempts + 1;
3344
- if (error instanceof DeliveryRetryableError && attempts < MAX_DELIVERY_ATTEMPTS) {
3345
- await db.update(juniorTurnOutbox).set({
3346
- attempts,
3347
- updatedAt: /* @__PURE__ */ new Date()
3348
- }).where(eq(juniorTurnOutbox.id, row.id));
3349
- return {
3350
- kind: "later",
3351
- delayMs: retryDelayMs(error, attempts)
3352
- };
3353
- }
3354
- logException(error, "turn.delivery.failed", { "gen_ai.conversation.id": conversationId });
3355
- await db.update(juniorTurnOutbox).set({
3356
- state: "failed",
3357
- attempts,
3358
- error: error instanceof Error ? error.message : String(error),
3359
- updatedAt: /* @__PURE__ */ new Date()
3360
- }).where(eq(juniorTurnOutbox.id, row.id));
3361
- return { kind: "settled" };
3362
- }
3363
- }
3364
- /**
3365
- * The wait before the next try of a retryable send. The cap keeps a row that
3366
- * waits for its retry well inside the sweep's stale window.
3367
- */
3368
- function retryDelayMs(error, attempts) {
3369
- return Math.min(error.retryAfterMs ?? RETRY_BASE_DELAY_MS * 2 ** (attempts - 1), RETRY_MAX_DELAY_MS);
3370
- }
3371
- // src/turn-steps/delivery.ts
3372
- /**
3373
- * The Delivery of this deployment. No Destination platform has a sender in
3374
- * core yet, so each reply that has a Destination fails.
3375
- */
3376
- const deploymentDelivery = { send: async ({ destination }) => {
3377
- throw new Error(`No sender for ${destination.platform} Destinations`);
3378
- } };
3379
- /**
3380
- * The queue consumer of delivery messages. The host mounts it on
3381
- * `engineCtx.queue`.
3382
- */
3383
- function deliveryConsumer(engineCtx, delivery) {
3384
- return createDeliveryConsumer(engineCtx, (message) => deliverTurn(engineCtx, message, delivery));
3385
- }
3386
3272
  // src/core/turn/sweep.ts
3387
- const STALE_MS = 3e5;
3388
- const BATCH = 100;
3389
- /**
3390
- * Sends the step message again for each Turn that no message will reach, and
3391
- * the delivery message again for each Conversation whose replies no message
3392
- * will send.
3393
- */
3273
+ const STALE_MS$1 = 3e5;
3274
+ const BATCH$1 = 100;
3275
+ /** Sends the step message again for each Turn that no message will reach. */
3394
3276
  async function sweepTurns(ctx) {
3395
3277
  await withSpan$1("turn.sweep", {}, async (span) => {
3396
3278
  const turns = await findStalledTurns(ctx, {
3397
- staleMs: STALE_MS,
3398
- limit: BATCH
3279
+ staleMs: STALE_MS$1,
3280
+ limit: BATCH$1
3399
3281
  });
3400
3282
  for (const turn of turns) {
3401
3283
  await publishTurnStep(ctx, turn.turnId);
3402
3284
  reportRequeued(turn);
3403
3285
  }
3404
- const deliveries = await findStalledDeliveries(ctx, {
3405
- staleMs: STALE_MS,
3406
- limit: BATCH
3407
- });
3408
- for (const delivery of deliveries) {
3409
- await publishDelivery(ctx, {
3410
- conversationId: delivery.conversationId,
3411
- turnId: delivery.turnId
3412
- });
3413
- reportRequeued({
3414
- ...delivery,
3415
- reason: "delivery_lost"
3416
- });
3417
- }
3418
3286
  span.setAttributes({
3419
- "app.turn.sweep.requeued": turns.length + deliveries.length,
3420
- "app.turn.sweep.batch_full": turns.length === BATCH || deliveries.length === BATCH
3287
+ "app.turn.sweep.requeued": turns.length,
3288
+ "app.turn.sweep.batch_full": turns.length === BATCH$1
3421
3289
  });
3422
3290
  }, { newTrace: true });
3423
3291
  }
@@ -3430,6 +3298,59 @@ function reportRequeued(found) {
3430
3298
  "app.turn.sweep.stalled_ms": found.stalledMs
3431
3299
  });
3432
3300
  }
3301
+ // src/delivery/sweep.ts
3302
+ const STALE_MS = 3e5;
3303
+ const BATCH = 100;
3304
+ /**
3305
+ * Sends the message that a Turn ended again for each Conversation whose
3306
+ * replies no message will send.
3307
+ */
3308
+ async function sweepDeliveries(ctx) {
3309
+ await withSpan$1("delivery.sweep", {}, async (span) => {
3310
+ const stalled = await findStalledDeliveries(ctx, {
3311
+ staleMs: STALE_MS,
3312
+ limit: BATCH
3313
+ });
3314
+ for (const delivery of stalled) {
3315
+ await publishTurnEnded(ctx, {
3316
+ conversationId: delivery.conversationId,
3317
+ turnId: delivery.turnId
3318
+ });
3319
+ countMetric("turn.sweep.requeued", { "app.turn.sweep.reason": "delivery_lost" });
3320
+ logWarn("turn.sweep.requeued", {
3321
+ "app.turn.id": delivery.turnId,
3322
+ "gen_ai.conversation.id": delivery.conversationId,
3323
+ "app.turn.sweep.reason": "delivery_lost",
3324
+ "app.turn.sweep.stalled_ms": delivery.stalledMs
3325
+ });
3326
+ }
3327
+ span.setAttributes({
3328
+ "app.turn.sweep.requeued": stalled.length,
3329
+ "app.turn.sweep.batch_full": stalled.length === BATCH
3330
+ });
3331
+ }, { newTrace: true });
3332
+ }
3333
+ /**
3334
+ * Finds Conversations whose first pending reply belongs to an ended Turn and
3335
+ * has not changed for `staleMs` since the later of its last change and the
3336
+ * Turn's end. A row behind a first row that is still retried waits; it is
3337
+ * not stalled. A row of a running Turn waits for the Turn's end.
3338
+ */
3339
+ async function findStalledDeliveries({ executor }, { staleMs, limit }) {
3340
+ const staleBefore = sql`now() - make_interval(secs => ${staleMs / 1e3})`;
3341
+ const earlier = alias(juniorTurnOutbox, "earlier");
3342
+ const rows = await executor.db().select({
3343
+ conversationId: juniorTurnOutbox.conversationId,
3344
+ turnId: juniorTurnOutbox.turnId,
3345
+ updatedAt: juniorTurnOutbox.updatedAt
3346
+ }).from(juniorTurnOutbox).innerJoin(juniorTurns, eq(juniorTurns.id, juniorTurnOutbox.turnId)).where(and(eq(juniorTurnOutbox.state, "pending"), lt(juniorTurnOutbox.createdAt, staleBefore), lt(juniorTurnOutbox.updatedAt, staleBefore), notInArray(juniorTurns.state, ["queued", "running"]), lt(juniorTurns.endedAt, staleBefore), notExists(executor.db().select({ one: sql`1` }).from(earlier).where(and(eq(earlier.conversationId, juniorTurnOutbox.conversationId), eq(earlier.state, "pending"), lt(earlier.eventSeq, juniorTurnOutbox.eventSeq)))))).limit(limit);
3347
+ const nowMs = Date.now();
3348
+ return rows.map((row) => ({
3349
+ conversationId: row.conversationId,
3350
+ turnId: row.turnId,
3351
+ stalledMs: Math.max(0, nowMs - row.updatedAt.getTime())
3352
+ }));
3353
+ }
3433
3354
  // src/handlers/artifacts.ts
3434
3355
  /** Serve one content-addressed public artifact without authentication. */
3435
3356
  async function publicArtifactGET(args) {
@@ -7183,7 +7104,7 @@ function hasConfiguredPluginCatalog(config) {
7183
7104
  return Boolean(config.inlineManifests?.length || config.packages?.length || Object.keys(config.manifests ?? {}).length);
7184
7105
  }
7185
7106
  function warnUnregisteredConfigDefaults(defaults) {
7186
- for (const key of Object.keys(defaults ?? {})) if (!pluginCatalogRuntime.isConfigKey(key)) logWarn("config.default.unregistered", { "app.config.key": key });
7107
+ for (const key of Object.keys(defaults ?? {})) if (!getAppContext().catalog.isConfigKey(key)) logWarn("config.default.unregistered", { "app.config.key": key });
7187
7108
  }
7188
7109
  function pluginPackageNames(config) {
7189
7110
  return config?.packages ?? [];
@@ -7226,12 +7147,13 @@ async function createApp(options) {
7226
7147
  validatePlugins(plugins);
7227
7148
  getDb();
7228
7149
  const shouldValidatePluginCatalog = hasConfiguredPluginCatalog(pluginConfig) || Boolean(configuredPlugins?.registrations.length) || Boolean(Object.keys(options?.configDefaults ?? {}).length);
7229
- const previousPluginCatalogConfig = pluginCatalogRuntime.setConfig(pluginConfig);
7230
- const previousPlugins = setPlugins(plugins);
7150
+ const previousAppContext = installAppContext(createAppContext({
7151
+ plugins,
7152
+ pluginConfig
7153
+ }));
7231
7154
  let restoreChatConfig;
7232
7155
  const restoreRuntimeConfig = () => {
7233
- pluginCatalogRuntime.setConfig(previousPluginCatalogConfig);
7234
- setPlugins(previousPlugins);
7156
+ installAppContext(previousAppContext);
7235
7157
  restoreChatConfig?.();
7236
7158
  };
7237
7159
  let pluginRoutes = [];
@@ -7258,7 +7180,7 @@ async function createApp(options) {
7258
7180
  dispatchForIdentity = createIdentityDispatcher({ conversationWorkQueue: () => conversationWorkQueue });
7259
7181
  if (dashboard && !dashboard.disabled) signInConfig = resolveSignInAuthConfig(botConfig.userName, allowedDomains, dashboard);
7260
7182
  if (shouldValidatePluginCatalog) {
7261
- pluginCatalogRuntime.getSignature();
7183
+ getAppContext().catalog.getSignature();
7262
7184
  validatePluginRegistrations(configuredPlugins?.registrations ?? []);
7263
7185
  validatePluginEgressCredentialHooks(configuredPlugins?.registrations ?? []);
7264
7186
  }
@@ -7454,7 +7376,7 @@ async function createApp(options) {
7454
7376
  let pluginTaskPOST;
7455
7377
  const chatConfig = getChatConfig();
7456
7378
  const engineCtx = createEngineContext(chatConfig);
7457
- const deliveries = deliveryConsumer(engineCtx, deploymentDelivery);
7379
+ const turnEnds = turnEndedConsumer(engineCtx, createDeploymentDelivery({ getSlackAdapter: getProductionSlackAdapter }));
7458
7380
  app.post(JUNIOR_CONVERSATION_WORK_CALLBACK_ROUTE, (c) => {
7459
7381
  agentContinuePOST ??= createVercelConversationWorkCallback(getConversationWorkOptions());
7460
7382
  return agentContinuePOST(c.req.raw);
@@ -7491,10 +7413,10 @@ async function createApp(options) {
7491
7413
  }));
7492
7414
  return turnStepPOST(c.req.raw);
7493
7415
  });
7494
- let deliveryPOST;
7495
- app.post(JUNIOR_DELIVERY_CALLBACK_ROUTE, (c) => {
7496
- deliveryPOST ??= engineCtx.queue.createCallback(deliveries);
7497
- return deliveryPOST(c.req.raw);
7416
+ let turnEndedPOST;
7417
+ app.post(JUNIOR_TURN_ENDED_CALLBACK_ROUTE, (c) => {
7418
+ turnEndedPOST ??= engineCtx.queue.createCallback(turnEnds);
7419
+ return turnEndedPOST(c.req.raw);
7498
7420
  });
7499
7421
  app.get("/api/internal/heartbeat", (c) => {
7500
7422
  return GET$3(c.req.raw, waitUntil, {
@@ -7503,7 +7425,10 @@ async function createApp(options) {
7503
7425
  events,
7504
7426
  sendPluginTask,
7505
7427
  showInboxItem: createInboxItemShow(getProductionSlackAdapter),
7506
- sweepTurns: () => sweepTurns(engineCtx)
7428
+ sweepTurns: async () => {
7429
+ await sweepTurns(engineCtx);
7430
+ await sweepDeliveries(engineCtx);
7431
+ }
7507
7432
  });
7508
7433
  });
7509
7434
  app.get("/api/internal/retention", (c) => {
@@ -1,5 +1,5 @@
1
1
  import * as z from "zod";
2
- import { ConversationAnnotation, OwnedObjectAnnotation } from "@sentry/junior-plugin-api";
2
+ import { LiveAnnotation, OwnedObjectAnnotation } from "@sentry/junior-plugin-api";
3
3
  /**
4
4
  * Largest file that Junior stores from Slack or the web, or loads into the
5
5
  * sandbox.
@@ -179,10 +179,14 @@ declare const messageCardRefSchema: z.ZodObject<{
179
179
  kind: z.ZodLiteral<"object">;
180
180
  }, z.core.$strict>;
181
181
  type MessageCardRef = z.output<typeof messageCardRefSchema>;
182
- /** Resolve current saved facts without fetching providers or changing history. */
183
- declare function resolveMessageCards(refs: readonly MessageCardRef[], annotations: readonly ConversationAnnotation[]): OwnedObjectAnnotation[];
184
- /** Copy saved annotation facts without storage timestamps for Message delivery. */
185
- declare function annotationCard(annotation: ConversationAnnotation): OwnedObjectAnnotation;
182
+ /** Match each reference to the Annotation as it was read, in reference order. */
183
+ declare function resolveMessageCards(refs: readonly MessageCardRef[], annotations: readonly LiveAnnotation[]): OwnedObjectAnnotation[];
184
+ /**
185
+ * Return the card of a read Annotation without its timestamps, for Message
186
+ * delivery. An Annotation that shows only its label gets that label as its
187
+ * title.
188
+ */
189
+ declare function annotationCard(annotation: LiveAnnotation): OwnedObjectAnnotation;
186
190
  /** Where a failed turn stopped. */
187
191
  declare const conversationTurnFailureCodeSchema: z.ZodEnum<{
188
192
  agent_run_failed: "agent_run_failed";
@@ -1,4 +1,4 @@
1
- import { Bs as withSlackRetries, Ms as getSlackClient, Os as SlackActionError, i as getConversationStore } from "./db-of6e3sGt.js";
1
+ import { Ks as SlackActionError, Xs as getSlackClient, i as getConversationStore, ic as withSlackRetries } from "./db-BacvswT0.js";
2
2
  import * as z from "zod";
3
3
  // src/chat/slack/channel.ts
4
4
  const replySubtypeSchema = z.object({ subtype: z.string().optional() });
@@ -1,9 +1,9 @@
1
- import { R as getChatConfig } from "./context-BKF_5zzI.js";
2
- import { $s as SYSTEM_IDENTITY_ID, af as juniorTurns, d as createSqlConversationEventStore, i as getConversationStore } from "./db-of6e3sGt.js";
1
+ import { R as getChatConfig } from "./adapter-DlLLoJKj.js";
2
+ import { d as createSqlConversationEventStore, i as getConversationStore, kp as juniorTurns, vc as SYSTEM_IDENTITY_ID } from "./db-BacvswT0.js";
3
3
  import { t as startLocalVercelQueueServer } from "./local-server-CpnGhYml.js";
4
- import { ai as projectConversationEvents } from "./mailbox-turn-Byrry9o1.js";
5
- import { n as TURN_STEP_TOPIC } from "./topic-CRYYBYp-.js";
6
- import { a as scheduleInput, i as turnStepConsumer, n as turnTools, r as createGatewayModelClient, t as createEngineContext } from "./engine-context-C_QL_bMQ.js";
4
+ import { mi as projectConversationEvents } from "./markers-C33gNYNE.js";
5
+ import { n as TURN_STEP_TOPIC, t as TURN_ENDED_TOPIC } from "./topic-B2EWKKBT.js";
6
+ import { a as createGatewayModelClient, i as turnTools, o as turnStepConsumer, r as turnEndedConsumer, s as scheduleInput, t as createEngineContext } from "./engine-context-Bi3Ync5t.js";
7
7
  import { eq } from "drizzle-orm";
8
8
  import { localDestinationSchema } from "@sentry/junior-plugin-api";
9
9
  import { randomUUID } from "node:crypto";
@@ -17,11 +17,11 @@ function turnGroupKey(actorIdentityId, source) {
17
17
  /**
18
18
  * `junior chat --engine core -p`: one message through the core Turn engine.
19
19
  *
20
- * The CLI is the Source. It schedules the message as an input, runs a local
21
- * Vercel Queues server that pushes each Turn step message to the Turn step
22
- * consumer in this process, and reads the reply from the stored history when
23
- * the Turn ends. The engine has no Delivery yet, so
24
- * the history is the only place that has the reply.
20
+ * The CLI is the Source. It runs a local Vercel Queues server that pushes
21
+ * each Turn step message and Turn-ended message to their consumers in this
22
+ * process, and reads the reply from the stored history when the Turn ends.
23
+ * The Turn has no Destination, so the history is the only place that has
24
+ * the reply.
25
25
  */
26
26
  const LOCAL_ACTOR = {
27
27
  fullName: "Local CLI",
@@ -31,20 +31,24 @@ const LOCAL_ACTOR = {
31
31
  };
32
32
  const TURN_POLL_INTERVAL_MS = 250;
33
33
  const TURN_STEP_CALLBACK_URL = `http://cli.localhost/${TURN_STEP_TOPIC}`;
34
+ const TURN_ENDED_CALLBACK_URL = `http://cli.localhost/${TURN_ENDED_TOPIC}`;
35
+ const NO_DELIVERY = { send: async () => {
36
+ throw new Error("The CLI has no Destination to send a reply to");
37
+ } };
34
38
  const TURN_WAIT_TIMEOUT_MS = 6e5;
35
39
  const ENDED_STATES = /* @__PURE__ */ new Set([
36
40
  "completed",
37
41
  "failed",
38
42
  "cancelled"
39
43
  ]);
40
- async function waitForTurnEnd({ executor }, turnId) {
44
+ async function waitForTurnEnd({ executor }, turnId, endHandled) {
41
45
  const deadline = Date.now() + TURN_WAIT_TIMEOUT_MS;
42
46
  while (Date.now() < deadline) {
43
47
  const [turn] = await executor.db().select({
44
48
  state: juniorTurns.state,
45
49
  endReason: juniorTurns.endReason
46
50
  }).from(juniorTurns).where(eq(juniorTurns.id, turnId));
47
- if (turn && ENDED_STATES.has(turn.state)) return turn;
51
+ if (turn && ENDED_STATES.has(turn.state) && endHandled()) return turn;
48
52
  await setTimeout(TURN_POLL_INTERVAL_MS);
49
53
  }
50
54
  throw new Error(`Turn ${turnId} did not end within ${TURN_WAIT_TIMEOUT_MS} ms`);
@@ -68,13 +72,26 @@ async function runCoreEnginePrompt(args) {
68
72
  bot: config.bot,
69
73
  tools: turnTools
70
74
  }));
75
+ let endHandled = false;
76
+ const turnEnds = turnEndedConsumer(engineCtx, NO_DELIVERY);
77
+ const turnEndedCallback = engineCtx.queue.createCallback({
78
+ ...turnEnds,
79
+ handler: async (payload, metadata) => {
80
+ await turnEnds.handler(payload, metadata);
81
+ endHandled = true;
82
+ }
83
+ });
71
84
  const server = await startLocalVercelQueueServer({
72
85
  consumers: [{
73
86
  consumerGroup: "local",
74
87
  topic: TURN_STEP_TOPIC,
75
88
  url: TURN_STEP_CALLBACK_URL
89
+ }, {
90
+ consumerGroup: "local",
91
+ topic: TURN_ENDED_TOPIC,
92
+ url: TURN_ENDED_CALLBACK_URL
76
93
  }],
77
- fetch: async (request) => request.url === TURN_STEP_CALLBACK_URL ? turnStepCallback(request) : new Response(null, { status: 404 }),
94
+ fetch: async (request) => request.url === TURN_STEP_CALLBACK_URL ? turnStepCallback(request) : request.url === TURN_ENDED_CALLBACK_URL ? turnEndedCallback(request) : new Response(null, { status: 404 }),
78
95
  port
79
96
  });
80
97
  try {
@@ -108,7 +125,7 @@ async function runCoreEnginePrompt(args) {
108
125
  destination: null,
109
126
  delivery: "defer"
110
127
  });
111
- const turn = await waitForTurnEnd(engineCtx, turnId);
128
+ const turn = await waitForTurnEnd(engineCtx, turnId, () => endHandled);
112
129
  if (turn.state !== "completed") return {
113
130
  outcome: turn.state === "cancelled" ? "cancelled" : "failed",
114
131
  reason: turn.endReason ?? turn.state
@@ -1,4 +1,4 @@
1
- import { n as JuniorPluginSet } from "../plugins-fBrz8PCV.js";
1
+ import { n as JuniorPluginSet } from "../plugins-DhGXZjlu.js";
2
2
  export declare const CHAT_USAGE = "usage: junior chat\n junior chat -p <message>\n junior chat --engine core -p <message>";
3
3
  export type ChatCommandOptions = {
4
4
  mode: "interactive";