@sentry/junior 0.305.0 → 0.307.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 (98) hide show
  1. package/dist/{adapter-context-BpvbUki8.js → adapter-context-B69WPn6b.js} +2 -2
  2. package/dist/{admin-CoDt35ny.js → admin-nCJXMgkp.js} +2 -2
  3. package/dist/{agent-runner-C5d6rY5g.js → agent-runner-DdFcxAxG.js} +463 -303
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +7 -8
  6. package/dist/api.d.ts +19 -4
  7. package/dist/api.js +437 -310
  8. package/dist/{app-Cs157Zc5.d.ts → app-EZur8cVC.d.ts} +12 -3
  9. package/dist/app.d.ts +2 -2
  10. package/dist/app.js +532 -439
  11. package/dist/background-compaction-queue-BhEe4UfU.js +231 -0
  12. package/dist/{briefs-BRdznF7c.js → briefs-Dl9lxi7J.js} +3 -3
  13. package/dist/{catalog-runtime-J52Tej47.js → catalog-runtime-OXrv2Ewn.js} +1 -1
  14. package/dist/cli/chat.d.ts +1 -1
  15. package/dist/cli/chat.js +17 -16
  16. package/dist/cli/check.js +58 -48
  17. package/dist/cli/main.js +3 -3
  18. package/dist/cli/plugins.d.ts +1 -1
  19. package/dist/cli/plugins.js +4 -4
  20. package/dist/cli/snapshot-create.js +5 -5
  21. package/dist/cli/upgrade.d.ts +2 -2
  22. package/dist/cli/upgrade.js +3 -8
  23. package/dist/{config-CBZp0udd.js → config-362yMSIz.js} +183 -49
  24. package/dist/{connections-BYmuJ6Vm.js → connections-BJv3EjmB.js} +10 -8
  25. package/dist/{continue-in-slack-Cvot6S38.js → continue-in-slack-CFEevC7z.js} +5 -5
  26. package/dist/{conversation-BOqdRtUx.js → conversation--f85g4zL.js} +132 -132
  27. package/dist/{conversation-feed-CgpgP7yi.js → conversation-feed-BNs9KiqC.js} +1 -1
  28. package/dist/{conversation-privacy-D2pOzBNl.js → conversation-privacy-Tjj5P2W6.js} +1 -1
  29. package/dist/{conversation-turn-CI8WDpnK.js → conversation-turn-DU0_WDAr.js} +26 -72
  30. package/dist/{credential-sync-COqnZ1Dx.js → credential-sync-D6aFARKE.js} +28 -27
  31. package/dist/{db-DU84dCVu.js → db-Bcbd9zQc.js} +226 -18
  32. package/dist/{db-zbN5ZV_o.d.ts → db-C41UgdBj.d.ts} +1 -1
  33. package/dist/{executor-CFyrgOu1.js → executor-DBMBrpNV.js} +137 -33
  34. package/dist/{history-m2-ceTTX.js → history-N7IVbUom.js} +5 -1
  35. package/dist/{install-CQ76CfRw.js → install-CgoAbzfF.js} +2 -2
  36. package/dist/instrumentation.js +2 -2
  37. package/dist/{lineage-DLd2UxVP.js → lineage-CsZDmz3e.js} +2 -2
  38. package/dist/{logging-BPNTQVFu.js → logging-CHCuQ5iz.js} +1 -1
  39. package/dist/{message-BWJLeQ5e.js → message-B8vCbZZB.js} +8 -8
  40. package/dist/{model-input-DoM9Ht-d.js → model-input-Xluiy-1W.js} +3 -3
  41. package/dist/nitro.d.ts +2 -2
  42. package/dist/nitro.js +3 -4
  43. package/dist/{oauth-callback-server-DeHbnAQl.js → oauth-callback-server-BUuNvfvu.js} +2 -2
  44. package/dist/{oauth-relay-DAmfVmJu.js → oauth-relay-DGAZzg9m.js} +1 -1
  45. package/dist/{plugins-B_0Cr0MO.d.ts → plugins-fBrz8PCV.d.ts} +2 -0
  46. package/dist/{projection-CcFBVFUo.js → projection-xPpvqexa.js} +13423 -11432
  47. package/dist/{prompt-C5LREK2p.js → prompt-D8u4jFs_.js} +15 -7
  48. package/dist/{registry-BjZZqKqi.js → registry-D20hG3r6.js} +19 -9
  49. package/dist/{resolve-CeJgXuH1.js → resolve-BhCySRCW.js} +3 -3
  50. package/dist/{result-icDrueyB.js → result-DddO63S9.js} +13 -11
  51. package/dist/{runner-nVfMkMMB.js → runner-DQR9vYce.js} +13 -15
  52. package/dist/{sandbox-egress-signals-H9vQ5qRf.js → sandbox-egress-signals-DFlNUOnK.js} +1 -1
  53. package/dist/{automation-CuA3yEcD.js → schedule-BG1tEbRF.js} +380 -8
  54. package/dist/{schema-CKcu-IK6.d.ts → schema-CRXcj4fj.d.ts} +420 -143
  55. package/dist/{schema-Bx0Mlo32.js → schema-D4jdesIu.js} +62 -8
  56. package/dist/{service-account-DU5865XA.js → service-account-Bv5QwrEq.js} +8 -6
  57. package/dist/{service-account-Dw06p3zm.js → service-account-CNfycv0z.js} +3 -3
  58. package/dist/{session-stop-uotLtp4g.js → session-stop-BDdwyZaa.js} +878 -171
  59. package/dist/{skills-Bex1EaO5.js → skills-63i1Bcv1.js} +32 -28
  60. package/dist/{slack-conversation-unfurl-EPG3riWF.js → slack-conversation-unfurl-DtpBUlUu.js} +10 -9
  61. package/dist/{spawn-CoD3vDuS.js → spawn-mwimEY9_.js} +6 -6
  62. package/dist/{state-nCR4Muhn.js → state-BBn9L6gC.js} +4 -4
  63. package/dist/{stop-BFVd0P0m.js → stop-Da-Ug7tg.js} +172 -239
  64. package/dist/{store-Ca6G962n.js → store-CdWg2r2L.js} +5 -5
  65. package/dist/{background-compaction-queue-BTqMIfTA.js → task-queue-BcjAYWyB.js} +164 -180
  66. package/dist/{task-runner-xsOPIxCZ.js → task-runner-CoXmMlsW.js} +13 -11
  67. package/dist/{thread-context-BOvZhsKK.js → thread-context-ZPGqOjW7.js} +8 -91
  68. package/dist/turn-session-routing-DFYak28Q.js +263 -0
  69. package/dist/{turn-user-message-BrhuyYrH.js → turn-user-message-B1S8nOnG.js} +3 -3
  70. package/dist/users-DDbENg-I.js +181 -0
  71. package/dist/{validation-BnY9K5WB.js → validation-fl21ps-k.js} +1 -1
  72. package/dist/{version-qROlRQGF.js → version-DCdMMx_0.js} +1 -1
  73. package/dist/version.js +1 -1
  74. package/dist/{viewer-CxUiOraX.js → viewer-DN_xzVKj.js} +3 -3
  75. package/dist/{warmup--Gkz7iB-.js → warmup-CxhEhm71.js} +842 -532
  76. package/dist/{web-message-id-lNodcCOI.js → web-message-id-BT8Mg8LL.js} +16 -1
  77. package/dist/{worker-DJ8d9fmD.js → worker-Btb1SB5h.js} +8 -7
  78. package/migrations/0114_plan_items.sql +22 -0
  79. package/migrations/0115_automation_creator_slack_index.sql +1 -0
  80. package/migrations/0116_conversation_event_search.sql +25 -0
  81. package/migrations/0117_automation_last_run.sql +46 -0
  82. package/migrations/0118_automation_last_run_index.sql +1 -0
  83. package/migrations/0119_money_micro_usd.sql +29 -0
  84. package/migrations/0120_conversation_cost_micro_usd.sql +8 -0
  85. package/migrations/meta/0114_snapshot.json +5203 -0
  86. package/migrations/meta/0115_snapshot.json +5225 -0
  87. package/migrations/meta/0116_snapshot.json +5388 -0
  88. package/migrations/meta/0117_snapshot.json +5413 -0
  89. package/migrations/meta/0118_snapshot.json +5428 -0
  90. package/migrations/meta/0119_snapshot.json +5441 -0
  91. package/migrations/meta/0120_snapshot.json +5441 -0
  92. package/migrations/meta/_journal.json +49 -0
  93. package/package.json +10 -9
  94. package/dist/queue-B2AAL3ym.js +0 -115
  95. package/dist/schedule-cP0AACm1.js +0 -344
  96. package/dist/secrets-DHaJ5TTn.js +0 -18
  97. package/dist/task-queue-BLPZU6kC.js +0 -89
  98. package/dist/turn-session-routing-2bW2qfeb.js +0 -1792
package/dist/app.js CHANGED
@@ -1,52 +1,48 @@
1
- import { Ar as dismissOpenReviewItems, Bi as createPluginState, C as settleConversationTitleWork, Ci as bindSlackDirectCredentialSubject, Ea as postSlackEphemeralMessage, Ei as verifySlackDirectCredentialSubject, Fi as getDashboardTaskLink, Fo as readConversationMessageEventSeq, Fs as getConfigDefaults, Ha as clearSandboxEgressSignals, Is as setConfigDefaults, Ka as parseSandboxEgressCredentialToken, Ko as collectAttachmentGarbage, Lr as searchReviewItems, Ma as slackEntitySchema, Mo as readConversationEventPageAfter, Mt as hasRunnableConversationWork, Na as slackExternalRefIdSchema, Ni as getDashboardReviewItemLink, Po as readConversationLastEventSeq, Pt as isInvalidConversationRecordError, Qr as reviewItemReaderForUserInConversation, Rt as pruneActiveConversation, Si as bindScheduledAutomationCredentialSubject, Ta as openSlackModal, Ti as verifyScheduledAutomationCredentialSubject, Tr as createPluginReviewItems, Ua as consumeSandboxEgressAuthRequiredSignal, Vr as canActOnReviewItem, Wa as consumeSandboxEgressPermissionDeniedSignal, Xa as normalizeSandboxEgressTracePropagationDomains, Xo as requestAttachmentDeletion, Yn as createUserTokenStore, Zr as reviewItemReaderForUser, _ as appendConversationMessages, _a as slackMention, _i as findMatchingWatches, _o as createPluginLogger, aa as isVercelSandboxEgressRequest, bi as takeDueTimerWatches, bs as createPluginAnnotations, cr as getPlugins, dr as validatePlugins, dt as CONVERSATION_WORK_STALE_ENQUEUE_MS, er as createPluginEventPublisher, gs as resolveRootVisibility, ii as createCodeChangePublisher, is as getSlackClient, jo as readConversationEventPage, ki as getDashboardConversationLink, ks as createPluginCache, mr as setBriefsConfig, ms as runWithWorkspaceTeamId, nr as getPluginApiRoutes, oa as proxyVercelSandboxEgressRequest, os as isDmChannel, pi as collectEventMatchKeys, ps as getWorkspaceTeamId, ro as createPluginEmbedder, rr as getPluginRoutes, ua as resolveBaseUrl, ur as setPlugins, wi as verifyEventAutomationCredentialSubject, wr as projectConversationMessages, xi as bindEventAutomationCredentialSubject, xo as readConversationAccessFromSql, xs as listConversationAnnotations, zi as setDashboardConversationLinkOptions } from "./projection-CcFBVFUo.js";
2
- import { d as restoreRuntimeConfig, et as getAttachmentStorage, f as setBotModelConfig, g as snapshotRuntimeConfig, h as setSlackReactionConfig, i as getChatConfig, m as setRuntimeLimits, n as botConfig, o as getSlackBotToken, p as setBotName, u as resetRuntimeConfig } from "./config-CBZp0udd.js";
3
- import { $ as MUTATION_LOCK_TTL_MS, C as withConversationMutationLock, H as recordGoogleSignIn, I as resolveActorIdentityId, J as disconnectStateAdapter, X as getStateAdapter, a as getConversationStore, gt as createSlackDestination, ht as touchConversationDetail, m as withConversationEventLock, nt as withLock, o as getDb, p as deleteMessageLinks, q as createCache, r as getConversationEventStore, s as getSqlExecutor, t as closeDb, tt as fenceLock } from "./db-DU84dCVu.js";
4
- import { A as JUNIOR_CONTEXT_COMPACTION_CALLBACK_ROUTE, E as withSpan, G as normalizeIdentityEmail, L as JUNIOR_WORKSPACE_SNAPSHOT_JOB_CALLBACK_ROUTE, O as JUNIOR_AUTO_ARCHIVE_ROUTE, P as JUNIOR_PLUGIN_TASK_CALLBACK_ROUTE, T as withLogContext, U as GOOGLE_IDENTITY_PROVIDER, b as setSpanAttributes, h as logWarn, k as JUNIOR_CACHE_WARMUP_CALLBACK_ROUTE, m as logInfo, p as logException, r as createRequestContext, w as withContext } from "./logging-BPNTQVFu.js";
5
- import { C as parseSlackReviewItemClick, E as parseSlackUserInputSubmission, S as buildSlackReviewItemModal, _ as createSlackReviewItemShow, b as findSlackThreadOwnerId, d as publicArtifactHeaders, f as readPublicArtifact, g as scheduledAutomationRunAttributes, h as logScheduledAutomationRunSkipped, n as executeAgentRun, p as unpublishedArtifactHeaders, r as processBackgroundCompaction, t as createAgentRunner, v as resolveSlackReviewItemCardConversationId, w as parseSlackReviewItemFormTarget, y as syncReviewItemSlackCards } from "./agent-runner-C5d6rY5g.js";
6
- import { $ as SLACK_EVENT_NAMESPACE, F as renderTaskInput, H as annotationKeyDigest, Q as getEventCatalog, U as decodeAnnotationRef, V as renderSlackObjectCard, X as isExperimentalFeatureEnabled, Y as getExperimentalFeatures, Z as setExperimentalFeatures, b as getAuthPausedConversationTurnId, nt as slackChannelMessageReplyThreadTs, rt as slackChannelMessageRunsAutomation, tt as slackChannelMessageEvent } from "./session-stop-uotLtp4g.js";
7
- import { a as getSandboxResourceConfig, s as setSandboxResourceConfig } from "./install-CQ76CfRw.js";
8
- import { n as pluginCatalogRuntime } from "./catalog-runtime-J52Tej47.js";
9
- import { $ as readObjectLinkTypes, A as isAllowedSignInEmail, B as runAutoArchiveSweep, C as encodeConversationCursor, Ct as getThreadStopDecision, F as actOnReviewItem, I as closeReviewItemsAnsweredByReply, J as backfillCacheWarmingGaps, K as runSavingsRefillSlice, L as readReviewItemForUser, M as resolveAllowedDomains, N as stopConversation, O as assertNoLegacyAllowedDomains, P as ReviewItemActionError, R as reviewItemChange, S as decodeConversationCursor, St as SubscribedReplyReason, T as readConversationPendingMessages, V as setConversationAutoArchive, Y as GET$4, _t as createSlackWebApiStatusSender, at as createProductionConversationWorkOptions, b as createConversationForViewer, bt as stripLeadingBotMention, ct as buildSlackInboundMessage, dt as normalizeIncomingSlackThreadId, ft as withNormalizedThreadId, gt as recordSkippedConversationMessage, ht as failStoppedDispatch, i as readConversationFeed, it as publicAddressLookup, j as readEnvList, k as isAllowedDomain, l as readConversationDetail, lt as clearSlackPendingReactions, mt as enqueueAgentDispatch, n as steerConversationPendingMessagesForViewer, ot as createProductionSlackWebhookServices, rt as isPublicAddress, s as pinConversation, st as getProductionSlackAdapter, t as stopConversationTurnForViewer, ut as slackInboundMessageId, v as readConversationRecordFromSql, vt as bindMessageAuthorIdentityId, w as cancelConversationPendingMessagesForViewer, xt as parseContent, y as appendConversationMessageForViewer, yt as startProcessingReaction, z as archiveViewerDoneConversations } from "./stop-BFVd0P0m.js";
10
- import { n as validatePluginRegistrations, t as validatePluginEgressCredentialHooks } from "./validation-BnY9K5WB.js";
1
+ import { $i as proxyVercelSandboxEgressRequest, $o as listPendingDispatchMailboxAppends, $r as reviewItemReaderForUser, $s as withScheduledAutomationLock, Ai as verifySlackDirectCredentialSubject, Ao as createConversationEmbedder, At as hasRunnableConversationWork, Bs as slackMention, C as settleConversationTitleWork, Ca as normalizeSandboxEgressTracePropagationDomains, Ci as takeDueTimerWatches, Dc as eventGuidance, Di as bindSlackDirectCredentialSubject, Dn as getPluginApiRoutes, Do as resolveRootVisibility, Dr as createPluginReviewItems, Ei as bindScheduledAutomationCredentialSubject, Er as projectConversationMessages, Es as isDmChannel, Fn as setPlugins, Go as createOrGetDispatch, Hn as setEventEmbeddingsConfig, Ho as buildDispatchId, In as validatePlugins, It as pruneActiveConversation, Jc as existingConversationId, Ko as getDispatchConversationId, Mi as createPluginState, Mr as dismissOpenReviewItems, Mt as isInvalidConversationRecordError, Nn as getPlugins, No as createPluginAnnotations, Ns as getWorkspaceTeamId, Oa as createPluginEmbedder, Oi as verifyEventAutomationCredentialSubject, On as getPluginRoutes, Po as listConversationAnnotations, Ps as runWithWorkspaceTeamId, Qi as isVercelSandboxEgressRequest, Qo as isTerminalDispatchStatus, Qs as scheduledRunId, Rc as automationVersionOf, Rn as isBriefsEnabled, Sc as eventAutomationRunLimitReason, So as requestAttachmentDeletion, Ti as bindEventAutomationCredentialSubject, Tn as createPluginEventPublisher, Ua as createPluginLogger, Ur as canActOnReviewItem, Vn as setBriefsConfig, Wo as confirmDispatchMailboxAppend, Yo as getDispatchRecord, Ys as readScheduledAutomation, Zo as getPluginDispatchProjection, Zs as saveScheduledAutomationInLock, _ as appendConversationMessages, _a as consumeSandboxEgressPermissionDeniedSignal, _l as setConfigDefaults, as as notifyAutomationBlocked, bn as createUserTokenStore, dc as blockEventAutomation, ds as postSlackEphemeralMessage, ec as getDashboardConversationLink, ei as reviewItemReaderForUserInConversation, fc as collectEventAutomationMatchKeys, ga as consumeSandboxEgressAuthRequiredSignal, gl as getConfigDefaults, ha as clearSandboxEgressSignals, hc as findMatchingEventAutomations, hi as collectEventMatchKeys, ic as getDashboardReviewItemLink, il as refreshAutomationLastRun, io as readConversationEventPageAfter, ki as verifyScheduledAutomationCredentialSubject, ko as backfillConversationEmbeddings, lt as CONVERSATION_WORK_STALE_ENQUEUE_MS, oc as getDashboardTaskLink, oi as createCodeChangePublisher, oo as readConversationLastEventSeq, qa as readConversationAccessFromSql, qs as listScheduledAutomationsForTeam, ra as resolveBaseUrl, rl as recordAutomationExecution, ro as readConversationEventPage, rs as markDispatchFailed, so as readConversationMessageEventSeq, uc as setDashboardConversationLinkOptions, ul as createPluginCache, us as openSlackModal, vo as collectAttachmentGarbage, vs as slackEntitySchema, ws as getSlackClient, xc as admitEventAutomationRun, ya as parseSandboxEgressCredentialToken, yi as findMatchingWatches, ys as slackExternalRefIdSchema, zr as searchReviewItems } from "./projection-xPpvqexa.js";
2
+ import { d as restoreRuntimeConfig, f as setBotModelConfig, g as snapshotRuntimeConfig, h as setSlackReactionConfig, i as getChatConfig, m as setRuntimeLimits, n as botConfig, p as setBotName, u as resetRuntimeConfig, ut as getAttachmentStorage } from "./config-362yMSIz.js";
3
+ import { $ as getStateAdapter, C as withConversationMutationLock, Et as createSlackDestination, G as recordGoogleSignIn, I as resolveActorIdentityId, Tt as touchConversationDetail, Z as disconnectStateAdapter, a as getConversationStore, at as withLock, it as fenceLock, lt as conversationCostOf, m as withConversationEventLock, nt as MUTATION_LOCK_TTL_MS, o as getDb, p as deleteMessageLinks, r as getConversationEventStore, s as getSqlExecutor, t as closeDb } from "./db-Bcbd9zQc.js";
4
+ import { A as JUNIOR_CONTEXT_COMPACTION_CALLBACK_ROUTE, E as withSpan, G as normalizeIdentityEmail, L as JUNIOR_WORKSPACE_SNAPSHOT_JOB_CALLBACK_ROUTE, O as JUNIOR_AUTO_ARCHIVE_ROUTE, P as JUNIOR_PLUGIN_TASK_CALLBACK_ROUTE, T as withLogContext, U as GOOGLE_IDENTITY_PROVIDER, b as setSpanAttributes, h as logWarn, k as JUNIOR_CACHE_WARMUP_CALLBACK_ROUTE, m as logInfo, p as logException, r as createRequestContext, w as withContext } from "./logging-CHCuQ5iz.js";
5
+ import { A as resumeConversationDelivery, C as parseSlackReviewItemClick, E as parseSlackUserInputSubmission, S as buildSlackReviewItemModal, _ as createSlackReviewItemShow, b as findSlackThreadOwnerId, d as publicArtifactHeaders, f as readPublicArtifact, g as scheduledAutomationRunAttributes, h as logScheduledAutomationRunSkipped, n as executeAgentRun, p as unpublishedArtifactHeaders, r as processBackgroundCompaction, t as createAgentRunner, v as resolveSlackReviewItemCardConversationId, w as parseSlackReviewItemFormTarget, y as syncReviewItemSlackCards } from "./agent-runner-DdFcxAxG.js";
6
+ import { E as getAuthPausedConversationTurnId, G as isAllowedDomain, J as resolveEventAuthor, K as isTrustedSlackAuthor, U as eventAuthorText, W as findTrustedUser, X as resolveBotSlackTeamId, Y as setTrustConfig, Z as renderTaskInput, _t as slackChannelMessageEvent, at as decodeAnnotationRef, b as deletePlanItems, dt as getExperimentalFeatures, ft as isExperimentalFeatureEnabled, ht as SLACK_EVENT_NAMESPACE, it as annotationKeyDigest, mt as getEventCatalog, pt as setExperimentalFeatures, q as parseEmail, rt as renderSlackObjectCard, vt as slackChannelMessageReplyThreadTs, yt as slackChannelMessageRunsAutomation } from "./session-stop-BDdwyZaa.js";
7
+ import { a as getSandboxResourceConfig, s as setSandboxResourceConfig } from "./install-CgoAbzfF.js";
8
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-OXrv2Ewn.js";
9
+ import { $ as publicAddressLookup, A as actOnReviewItem, C as encodeConversationCursor, F as runAutoArchiveSweep, I as setConversationAutoArchive, J as readObjectLinkTypes, M as readReviewItemForUser, N as reviewItemChange, O as stopConversation, P as archiveViewerDoneConversations, Q as isPublicAddress, S as decodeConversationCursor, T as readConversationPendingMessages, U as backfillCacheWarmingGaps, V as runSavingsRefillSlice, W as GET$4, _t as SubscribedReplyReason, at as slackInboundMessageId, b as createConversationForViewer, dt as recordSkippedConversationMessage, et as createProductionConversationWorkOptions, ft as createSlackWebApiStatusSender, gt as parseContent, ht as stripLeadingBotMention, i as readConversationFeed, it as clearSlackPendingReactions, j as closeReviewItemsAnsweredByReply, k as ReviewItemActionError, l as readConversationDetail, lt as enqueueAgentDispatch, mt as startProcessingReaction, n as steerConversationPendingMessagesForViewer, nt as getProductionSlackAdapter, ot as normalizeIncomingSlackThreadId, pt as bindMessageAuthorIdentityId, rt as buildSlackInboundMessage, s as pinConversation, st as withNormalizedThreadId, t as stopConversationTurnForViewer, tt as createProductionSlackWebhookServices, ut as failStoppedDispatch, v as readConversationRecordFromSql, vt as getThreadStopDecision, w as cancelConversationPendingMessagesForViewer, y as appendConversationMessageForViewer } from "./stop-Da-Ug7tg.js";
10
+ import { n as validatePluginRegistrations, t as validatePluginEgressCredentialHooks } from "./validation-fl21ps-k.js";
11
11
  import { a as pluginRuntimeRegistrationsFromPluginSet, n as pluginCatalogConfigFromEnv, r as pluginCatalogConfigFromPluginSet, t as defineJuniorPlugins } from "./plugins-Bkk0XRo2.js";
12
- import { At as collectAttachmentUploadGarbage, Ci as missingAutomationSkillReason, Ct as conversationTurnIdForMessage, Dt as webActorFromUser, E as processWorkspaceSnapshotJob, Et as recordWebConversationActivity, Gn as setConversationSubscription, Jt as listPendingAgentInvocationMailboxAppends, L as lookupSlackUserProfile, Si as findAutomationSkill, St as appendAndEnqueueWebMessage, Yt as listPendingAgentInvocationResults, bt as reviewItemChangeRecord, ci as ViewerTaskNotFoundError, dt as archiveConversation, fi as readViewerAutomationSummary, fn as enqueueAgentInvocation, k as ingestEvent, mi as readViewerAutomations, pt as markConversationRead, sr as parseSlackThreadId, ui as readViewerAutomationExecutions, vt as deliverReviewItemChange, wi as effectiveTaskOutcomes, yn as recordSubagentEnded, yr as joinPublicChannel, yt as renderReviewItemMessage } from "./warmup--Gkz7iB-.js";
13
- import { H as automationTaskSchema, N as scheduledRunSchema, U as automationTaskText, l as automationListQuerySchema, s as automationExecutionStatusSchema } from "./automation-CuA3yEcD.js";
14
- import { E as notifyAutomationBlocked, G as readScheduledAutomation, I as recordAutomationExecution, J as scheduledRunId, O as existingConversationId, U as listScheduledAutomationsForTeam, X as blockEventAutomation, Y as withScheduledAutomationLock, Z as collectEventAutomationMatchKeys, b as listPendingDispatchMailboxAppends, bt as eventGuidance, c as coerceThreadConversationState, d as confirmDispatchMailboxAppend, et as findMatchingEventAutomations, f as createOrGetDispatch, g as getDispatchRecord, l as buildDispatchId, lt as automationVersionOf, ot as admitEventAutomationRun, p as getDispatchConversationId, q as saveScheduledAutomationInLock, st as eventAutomationRunLimitReason, v as getPluginDispatchProjection, w as markDispatchFailed, y as isTerminalDispatchStatus } from "./turn-session-routing-2bW2qfeb.js";
15
- import { I as juniorDestinations, N as juniorConversations, T as juniorConversationEvents, f as juniorAutomations, g as juniorAgentInvocations, h as juniorAgentBindings, l as juniorReviewItems, u as juniorAutomationRuns, x as juniorConversationBriefs } from "./executor-CFyrgOu1.js";
16
- import { i as getActiveSpan, n as captureMessage, u as sentry_exports } from "./sentry-CPbZjomA.js";
17
- import { a as queueCallback, c as verifyConversationQueueMessage, f as getQueueProvider, g as isConversationQueueMessageRejectedError, h as conversationQueueMessageSchema, i as verifyBackgroundCompactionMessage, o as getVercelConversationWorkQueue, r as vercelBackgroundCompactionQueue, s as resolveConversationWorkQueueTopic, t as BACKGROUND_COMPACTION_QUEUE_TOPIC } from "./background-compaction-queue-BTqMIfTA.js";
18
- import { _ as getConversationWorkState, g as getConversation, h as ensureConversationWake, l as clearExpiredConversationLease, r as appendAndEnqueueInboundMessage, y as listActiveConversationIds } from "./store-Ca6G962n.js";
19
- import { a as getNextRunAtMs } from "./schedule-cP0AACm1.js";
20
- import { i as enqueueAgentInvocationResult, r as createEndStoppedChildWork } from "./result-icDrueyB.js";
21
- import { n as readSchedulerSecret, r as readSignInSecret } from "./secrets-DHaJ5TTn.js";
22
- import { a as GET$5, i as publishAppHomeView, r as GET$6, t as receiveLocalOAuthCredential } from "./credential-sync-COqnZ1Dx.js";
12
+ import { Ci as findAutomationSkill, E as processWorkspaceSnapshotJob, Kt as listPendingAgentInvocationMailboxAppends, Ot as collectAttachmentUploadGarbage, St as createAndEnqueueConversation, Ti as effectiveTaskOutcomes, Tt as webActorFromUser, Wn as setConversationSubscription, _n as recordSubagentEnded, _t as renderReviewItemMessage, bt as appendAndEnqueueWebMessage, ci as ViewerTaskNotFoundError, dt as markConversationRead, fi as readViewerAutomationSummary, gt as deliverReviewItemChange, k as ingestEvent, lt as archiveConversation, mi as readViewerAutomations, or as parseSlackThreadId, qt as listPendingAgentInvocationResults, ui as readViewerAutomationExecutions, un as enqueueAgentInvocation, vr as joinPublicChannel, vt as reviewItemChangeRecord, wi as missingAutomationSkillReason, wt as recordWebConversationActivity, xt as conversationTurnIdForMessage, yi as automationCardStatus } from "./warmup-CxhEhm71.js";
13
+ import { _ as getConversationWorkState, g as getConversation, h as ensureConversationWake, l as clearExpiredConversationLease, r as appendAndEnqueueInboundMessage, y as listActiveConversationIds } from "./store-CdWg2r2L.js";
14
+ import { G as getNextRunAtMs, Q as automationTaskText, R as scheduledRunSchema, Z as automationTaskSchema, m as automationListQuerySchema, u as automationExecutionStatusSchema } from "./schedule-BG1tEbRF.js";
15
+ import { A as juniorConversationEvents, E as juniorConversationBriefs, R as juniorConversations, V as juniorDestinations, f as juniorReviewItems, h as juniorAutomations, p as juniorAutomationRuns, v as juniorAgentBindings, y as juniorAgentInvocations } from "./executor-DBMBrpNV.js";
16
+ import { c as registerVercelCacheWarmupDevConsumer, g as verifyConversationQueueMessage, h as resolveConversationWorkQueueTopic, i as verifyBackgroundCompactionMessage, m as getVercelConversationWorkQueue, o as cacheWarmupQueueConsumer, p as verifyWorkspaceSnapshotJobMessage, r as vercelBackgroundCompactionQueue, s as createVercelCacheWarmupCallback, t as BACKGROUND_COMPACTION_QUEUE_TOPIC, u as WORKSPACE_SNAPSHOT_JOB_QUEUE_TOPIC, v as conversationQueueMessageSchema, y as isConversationQueueMessageRejectedError } from "./background-compaction-queue-BhEe4UfU.js";
17
+ import { i as enqueueAgentInvocationResult, r as createEndStoppedChildWork } from "./result-DddO63S9.js";
18
+ import { _ as getQueueProvider, a as pluginTaskQueueConsumer, f as readSchedulerSecret, h as queueCallback, n as createVercelPluginTaskCallback, o as registerVercelPluginTaskDevConsumer, p as readSignInSecret, s as sendVercelPluginTask } from "./task-queue-BcjAYWyB.js";
19
+ import { a as GET$5, i as publishAppHomeView, r as GET$6, t as receiveLocalOAuthCredential } from "./credential-sync-D6aFARKE.js";
23
20
  import { t as nameRequestRoute } from "./sentry-route-name-C6EIzAGP.js";
24
21
  import { t as SANDBOX_EGRESS_PROXY_PATH } from "./proxy-path-BHYoKZdq.js";
25
- import { $ as conversationBriefSchema, N as conversationTitleSchema, R as annotationCard, b as conversationSurfaceSchema, v as conversationReportStatusSchema } from "./conversation-BOqdRtUx.js";
26
- import { i as readActorIdentity, l as resolveViewerUser, p as parseAvatarUrl } from "./viewer-CxUiOraX.js";
27
- import { b as slackMessageTsSchema, g as slackTeamIdSchema, h as slackChannelIdSchema, n as createSlackActor, p as parseSlackUserId, s as parseActorUserId, u as parseSlackChannelId, v as parseSlackMessageTs, y as slackMessageTsFromMs } from "./actor-D2iXzvlN.js";
28
- 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-EPG3riWF.js";
29
- import { o as unlinkProvider } from "./connections-BYmuJ6Vm.js";
30
- import { s as buttonUserInputField } from "./web-message-id-lNodcCOI.js";
31
- import { n as verifySlackSignature, t as runWithSlackInstallation } from "./adapter-context-BpvbUki8.js";
32
- import { a as resumeConversationDelivery } from "./conversation-turn-CI8WDpnK.js";
33
- import { t as processConversationWork } from "./worker-DJ8d9fmD.js";
34
- import { t as bindMessageAgent } from "./message-BWJLeQ5e.js";
35
- import { t as bindSpawnAgent } from "./spawn-CoD3vDuS.js";
36
- import { a as pluginTaskQueueConsumer, n as createVercelPluginTaskCallback, o as registerVercelPluginTaskDevConsumer } from "./task-queue-BLPZU6kC.js";
37
- import { t as processPluginTask } from "./task-runner-xsOPIxCZ.js";
38
- import { i as registerVercelCacheWarmupDevConsumer, l as verifyWorkspaceSnapshotJobMessage, n as cacheWarmupQueueConsumer, o as WORKSPACE_SNAPSHOT_JOB_QUEUE_TOPIC, r as createVercelCacheWarmupCallback } from "./queue-B2AAL3ym.js";
39
- import { t as JUNIOR_VERSION } from "./version-qROlRQGF.js";
40
- import { c as conversationPendingMessageDeliverySchema, n as conversationFeedQuerySchema } from "./conversation-feed-CgpgP7yi.js";
22
+ import { B as conversationTitleSchema, G as annotationCard, I as conversationBriefSchema, b as conversationSurfaceSchema, v as conversationReportStatusSchema } from "./conversation--f85g4zL.js";
23
+ import { i as readActorIdentity, l as resolveViewerUser, p as parseAvatarUrl } from "./viewer-DN_xzVKj.js";
24
+ import { b as slackMessageTsSchema, g as slackTeamIdSchema, h as slackChannelIdSchema, n as createSlackActor, s as parseActorUserId, u as parseSlackChannelId, v as parseSlackMessageTs, y as slackMessageTsFromMs } from "./actor-D2iXzvlN.js";
25
+ 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-DtpBUlUu.js";
26
+ import { o as unlinkProvider } from "./connections-BJv3EjmB.js";
27
+ import { s as buttonUserInputField } from "./web-message-id-BT8Mg8LL.js";
28
+ import { n as verifySlackSignature, t as runWithSlackInstallation } from "./adapter-context-B69WPn6b.js";
29
+ import { c as coerceThreadConversationState } from "./turn-session-routing-DFYak28Q.js";
30
+ import { i as getActiveSpan, n as captureMessage, u as sentry_exports } from "./sentry-CPbZjomA.js";
31
+ import { t as processConversationWork } from "./worker-Btb1SB5h.js";
32
+ import { t as bindMessageAgent } from "./message-B8vCbZZB.js";
33
+ import { t as bindSpawnAgent } from "./spawn-mwimEY9_.js";
34
+ import { t as processPluginTask } from "./task-runner-CoXmMlsW.js";
35
+ import { t as JUNIOR_VERSION } from "./version-DCdMMx_0.js";
36
+ import { c as conversationPendingMessageDeliverySchema, n as conversationFeedQuerySchema } from "./conversation-feed-BNs9KiqC.js";
41
37
  import { createRequire } from "node:module";
42
38
  import { Hono } from "hono";
39
+ import pLimit from "p-limit";
43
40
  import * as z from "zod";
44
41
  import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
45
42
  import { and, asc, eq, inArray, isNotNull, isNull, lte, ne, or, sql } from "drizzle-orm";
46
- import { EVENT_SUMMARY_MAX_LENGTH, EVENT_TEXT_MAX_LENGTH, dispatchOptionsSchema, eventSchema as eventSchema$1, eventTriggerFiltersText, isSlackDestination, userSchema } from "@sentry/junior-plugin-api";
43
+ import { EVENT_SUMMARY_MAX_LENGTH, EVENT_TEXT_MAX_LENGTH, dispatchOptionsSchema, eventSchema as eventSchema$1, eventTriggerFiltersText, identityDispatchOptionsSchema, isSlackDestination, userSchema } from "@sentry/junior-plugin-api";
47
44
  import { pathToFileURL } from "node:url";
48
45
  import { Message, ThreadImpl } from "chat";
49
- import pLimit from "p-limit";
50
46
  import net from "node:net";
51
47
  import { decodeJwt } from "jose";
52
48
  import { HTTPException } from "hono/http-exception";
@@ -58,6 +54,28 @@ import { bodyLimit } from "hono/body-limit";
58
54
  import { createAuthMiddleware } from "better-auth/api";
59
55
  import { getSessionCookie } from "better-auth/cookies";
60
56
  import { betterAuth } from "better-auth/minimal";
57
+ // src/chat/conversations/embedding-backfill.ts
58
+ const BACKFILL_BUDGET_MS = 1e4;
59
+ const BACKFILL_CLAIM_TTL_MS = 6e4;
60
+ const BACKFILL_DONE_TTL_MS = 36e5;
61
+ /** Embed the latest Briefs that have no vector of the embedder's model. */
62
+ async function runConversationEmbeddingBackfill(embedder) {
63
+ const key = `junior:conversation_embeddings:backfill:${embedder.provider}:${embedder.model}`;
64
+ const state = getStateAdapter();
65
+ if (!await state.setIfNotExists(key, "running", BACKFILL_CLAIM_TTL_MS)) return;
66
+ await withSpan("conversation_embeddings.backfill", "conversation_embeddings.backfill", {}, async (setSpanAttributes) => {
67
+ const result = await backfillConversationEmbeddings({
68
+ db: getDb(),
69
+ deadlineMs: Date.now() + BACKFILL_BUDGET_MS,
70
+ embedder
71
+ });
72
+ if (result.done) await state.set(key, "done", BACKFILL_DONE_TTL_MS);
73
+ setSpanAttributes({
74
+ "app.conversation_embeddings.backfill.embedded.count": result.embedded,
75
+ "app.conversation_embeddings.backfill.outcome": result.done ? "completed" : "budget_exceeded"
76
+ });
77
+ });
78
+ }
61
79
  // src/chat/events/timers.ts
62
80
  /** Publish a bounded batch of due timers; the mailbox owns agent execution. */
63
81
  async function runTimerWatchHeartbeat(args) {
@@ -77,6 +95,99 @@ async function runTimerWatchHeartbeat(args) {
77
95
  }
78
96
  if (errors.length) throw new AggregateError(errors, "Timer Watch delivery failed");
79
97
  }
98
+ // src/chat/task-execution/heartbeat.ts
99
+ const DEFAULT_RECOVERY_LIMIT = 25;
100
+ function heartbeatIdempotencyKey(reason, conversationId, nowMs) {
101
+ return `heartbeat:${reason}:${conversationId}:${nowMs}`;
102
+ }
103
+ /** Requeue expired leases and stranded mailbox work without running the agent. */
104
+ async function recoverConversationWork(args) {
105
+ if (!getChatConfig().conversationWorkEnabled) {
106
+ logWarn("conversation.work.recovery.disabled");
107
+ return {
108
+ expiredLeaseCount: 0,
109
+ pendingCount: 0
110
+ };
111
+ }
112
+ const result = {
113
+ expiredLeaseCount: 0,
114
+ pendingCount: 0
115
+ };
116
+ const staleBeforeMs = args.nowMs - CONVERSATION_WORK_STALE_ENQUEUE_MS;
117
+ const ids = await listActiveConversationIds({
118
+ limit: args.limit ?? DEFAULT_RECOVERY_LIMIT,
119
+ staleBeforeMs,
120
+ state: args.state
121
+ });
122
+ for (const conversationId of ids) await withLogContext({ conversationId }, async () => {
123
+ let work;
124
+ try {
125
+ work = await getConversationWorkState({
126
+ conversationId,
127
+ state: args.state
128
+ });
129
+ } catch (error) {
130
+ logException(error, "conversation.work.recovery.failed");
131
+ if (isInvalidConversationRecordError(error)) await pruneActiveConversation({
132
+ conversationId,
133
+ state: args.state
134
+ });
135
+ return;
136
+ }
137
+ try {
138
+ if (!work || !hasRunnableConversationWork(work)) {
139
+ await pruneActiveConversation({
140
+ conversationId,
141
+ state: args.state
142
+ });
143
+ return;
144
+ }
145
+ if (work.execution.lease && work.execution.lease.expiresAtMs <= args.nowMs) {
146
+ const recovery = await clearExpiredConversationLease({
147
+ beforeWorkStops: args.beforeWorkStops,
148
+ conversationId,
149
+ nowMs: args.nowMs,
150
+ state: args.state
151
+ });
152
+ if (recovery === "not_expired") return;
153
+ if (recovery === "stopped") {
154
+ logException(/* @__PURE__ */ new Error("Conversation work stopped after repeated failed attempts"), "conversation.work.retry.exhausted", {
155
+ "app.run.id": work.execution.runId ?? "unknown",
156
+ "app.worker.last_progress_at_ms": work.execution.lastProgressAtMs ?? work.createdAtMs,
157
+ "app.worker.retry_count": (work.execution.retryCount ?? 0) + 1
158
+ });
159
+ return;
160
+ }
161
+ if ((await ensureConversationWake({
162
+ conversationId,
163
+ idempotencyKey: heartbeatIdempotencyKey("lease", conversationId, args.nowMs),
164
+ nowMs: args.nowMs,
165
+ queue: args.queue,
166
+ replaceExistingWake: true,
167
+ state: args.state
168
+ })).status === "enqueued") {
169
+ result.expiredLeaseCount += 1;
170
+ logInfo("conversation.work.lease_expired.requeued");
171
+ }
172
+ return;
173
+ }
174
+ if (work.execution.lease) return;
175
+ if ((await ensureConversationWake({
176
+ conversationId,
177
+ idempotencyKey: heartbeatIdempotencyKey("pending", conversationId, args.nowMs),
178
+ nowMs: args.nowMs,
179
+ queue: args.queue,
180
+ state: args.state
181
+ })).status === "enqueued") {
182
+ result.pendingCount += 1;
183
+ logInfo("conversation.work.pending.requeued");
184
+ }
185
+ } catch (error) {
186
+ logException(error, "conversation.work.recovery.failed");
187
+ }
188
+ });
189
+ return result;
190
+ }
80
191
  // src/chat/agent-dispatch/validation.ts
81
192
  function hasIssueAtPath(issues, path) {
82
193
  return issues.some((issue) => issue.path.length === path.length && issue.path.every((value, index) => value === path[index]));
@@ -172,6 +283,9 @@ async function dispatch(args) {
172
283
  function createHeartbeatContext(args) {
173
284
  const pluginName = typeof args.plugin === "string" ? args.plugin : args.plugin.manifest.name;
174
285
  let dispatchCount = 0;
286
+ const assertDispatchBudget = () => {
287
+ if (dispatchCount >= MAX_DISPATCHES_PER_HEARTBEAT) throw new Error("Plugin heartbeat exceeded the dispatch limit");
288
+ };
175
289
  return {
176
290
  plugin: { name: pluginName },
177
291
  annotations: { forConversation: (conversationId) => createPluginAnnotations({
@@ -196,7 +310,7 @@ function createHeartbeatContext(args) {
196
310
  async dispatch(options) {
197
311
  validateDispatchOptions(options);
198
312
  const dispatchOptions = bindDispatchCredentialSubject(options, pluginName);
199
- if (dispatchCount >= MAX_DISPATCHES_PER_HEARTBEAT) throw new Error("Plugin heartbeat exceeded the dispatch limit");
313
+ assertDispatchBudget();
200
314
  const result = await dispatch({
201
315
  conversationWorkQueue: args.conversationWorkQueue,
202
316
  nowMs: args.nowMs,
@@ -206,6 +320,11 @@ function createHeartbeatContext(args) {
206
320
  dispatchCount += 1;
207
321
  return result;
208
322
  },
323
+ async dispatchForIdentity(options) {
324
+ assertDispatchBudget();
325
+ dispatchCount += 1;
326
+ return await args.dispatchForIdentity(pluginName, options);
327
+ },
209
328
  async get(id) {
210
329
  return await getPluginDispatchProjection({
211
330
  plugin: pluginName,
@@ -278,355 +397,55 @@ async function getScheduledAutomationDispatch(id) {
278
397
  id
279
398
  });
280
399
  }
281
- // src/chat/automations/reply-attribution.ts
282
- /** Name the Automation in the footer of the replies that its runs post. */
283
- function automationReplyAttribution(title) {
284
- const detail = (title ?? "").replace(/\s+/g, " ").trim().slice(0, 128).trim();
285
- return detail ? {
286
- label: "Automation",
287
- detail
288
- } : { label: "Automation" };
289
- }
290
400
  // src/chat/event-automations/runs.ts
291
401
  /**
292
402
  * Record a dispatched event automation run with the Automation version it ran,
293
403
  * and link its Conversation when it exists. The dispatch can finish before
294
- * this write, so a stored run, or a retry of the same Event, keeps the row it
295
- * has.
296
- */
297
- async function recordEventAutomationRunStarted(db, args) {
298
- await db.insert(juniorAutomationRuns).values({
299
- id: args.dispatchId,
300
- automationId: args.automation.id,
301
- automationVersion: automationVersionOf(args.automation),
302
- conversationId: existingConversationId(getDispatchConversationId({ id: args.dispatchId })),
303
- startedAtMs: args.nowMs,
304
- status: "running"
305
- }).onConflictDoNothing({ target: juniorAutomationRuns.id });
306
- }
307
- /**
308
- * Settle running event automation runs whose dispatch has ended. A run whose
309
- * dispatch record is gone fails.
310
- */
311
- async function settleEventAutomationRuns(db, nowMs) {
312
- const runs = await db.select({
313
- automationId: juniorAutomationRuns.automationId,
314
- id: juniorAutomationRuns.id
315
- }).from(juniorAutomationRuns).innerJoin(juniorAutomations, eq(juniorAutomations.id, juniorAutomationRuns.automationId)).where(and(eq(juniorAutomations.kind, "event"), eq(juniorAutomationRuns.status, "running")));
316
- for (const run of runs) {
317
- const dispatch = await getDispatchRecord(run.id);
318
- const status = dispatch?.status ?? "failed";
319
- if (status !== "blocked" && status !== "completed" && status !== "failed") continue;
320
- await recordAutomationExecution(run.automationId, {
321
- conversationId: getDispatchConversationId({ id: run.id }),
322
- errorMessage: dispatch ? dispatch.errorMessage : "Event automation dispatch record is missing.",
323
- executionId: run.id,
324
- nowMs: dispatch?.updatedAtMs ?? nowMs,
325
- status
326
- });
327
- }
328
- }
329
- // src/chat/event-automations/ingest.ts
330
- /**
331
- * Owns event matching and durable event-automation dispatch.
332
- *
333
- * Each matching automation is independently idempotent. Aggregate failures propagate
334
- * so the provider can retry the original delivery.
335
- */
336
- /** Bind provider delivery identity to one automation's durable dispatch. */
337
- function eventAutomationDispatchKey(taskId, namespace, eventKey) {
338
- return `event-automation:${createHash("sha256").update(`${taskId}\0${namespace}\0${eventKey}`).digest("hex").slice(0, 32)}`;
339
- }
340
- /** Render plain agent input for one matching event automation. */
341
- function eventInput(task, event, outcomes, catalog) {
342
- const guidance = eventGuidance(catalog, event.namespace, event.eventType);
343
- return renderTaskInput({
344
- about: task.trigger.label,
345
- event: event.eventType,
346
- source: event.namespace,
347
- creator: slackMention(task.createdBy.slackUserId),
348
- instructions: automationTaskText(task.task),
349
- ...task.task.kind === "skill" ? { skill: task.task.skill } : void 0,
350
- outcomes,
351
- guidance,
352
- trustedSummary: event.trustedSummary,
353
- trustedSummaryMaxLength: EVENT_SUMMARY_MAX_LENGTH,
354
- verifiedDetails: event.data,
355
- externalText: event.untrustedText,
356
- externalTextMaxLength: EVENT_TEXT_MAX_LENGTH
357
- });
358
- }
359
- /**
360
- * Match a normalized event and dispatch every matching automation.
361
- *
362
- * Plugins publish one copy of an occurrence for each scope, such as a pull
363
- * request and its repository. All copies share one event key. An automation
364
- * with no identifier matches every copy, and the dispatch key and the run
365
- * limit both use the event key, so it runs and counts once.
366
- */
367
- async function ingestEventAutomations(input, options) {
368
- const event = eventSchema$1.parse(input);
369
- const db = getDb();
370
- const nowMs = options.nowMs ?? Date.now();
371
- const catalog = getEventCatalog();
372
- const [matches = []] = await findMatchingEventAutomations(db, [event], options.teamId, catalog);
373
- const tasks = matches.filter((task) => slackChannelMessageRunsAutomation(event, task));
374
- let dispatched = 0;
375
- const errors = [];
376
- for (const task of tasks) try {
377
- const skill = task.task.kind === "skill" ? task.task.skill : void 0;
378
- if (skill && !await findAutomationSkill(skill)) {
379
- const reason = missingAutomationSkillReason(skill);
380
- if (await blockEventAutomation(db, task.id, reason)) await notifyAutomationBlocked({
381
- automationId: task.id,
382
- kind: "event",
383
- reason
384
- });
385
- continue;
386
- }
387
- const idempotencyKey = eventAutomationDispatchKey(task.id, event.namespace, event.eventKey);
388
- if (await admitEventAutomationRun({
389
- automationId: task.id,
390
- nowMs,
391
- runKey: idempotencyKey
392
- }) === "limited") {
393
- const reason = eventAutomationRunLimitReason();
394
- logWarn("event_automation.run_limit.exceeded", {
395
- "app.task.id": task.id,
396
- "app.task.type": "event"
397
- });
398
- if (await blockEventAutomation(db, task.id, reason)) {
399
- captureMessage("Event automation blocked by run limit", {
400
- level: "warning",
401
- fingerprint: ["event_automation.run_limit.blocked"],
402
- tags: {
403
- "app.event.namespace": event.namespace,
404
- "app.task.type": "event"
405
- },
406
- extra: {
407
- "app.event.event_type": event.eventType,
408
- "app.event_automation.max_runs": botConfig.maxEventAutomationRuns,
409
- "app.event_automation.run_window_ms": botConfig.eventAutomationRunWindowMs,
410
- "app.event_automation.resource_type": task.trigger.resourceType ?? "any",
411
- "app.task.id": task.id
412
- }
413
- });
414
- await notifyAutomationBlocked({
415
- automationId: task.id,
416
- kind: "event",
417
- reason
418
- });
419
- }
420
- continue;
421
- }
422
- const replyThreadTs = slackChannelMessageReplyThreadTs(event);
423
- const destination = replyThreadTs ? {
424
- ...task.destination,
425
- threadTs: replyThreadTs
426
- } : task.destination;
427
- const outcomes = effectiveTaskOutcomes(task.outcomes, destination);
428
- const credentialSubject = task.credentialMode === "creator" ? {
429
- type: "user",
430
- userId: task.createdBy.slackUserId,
431
- allowedWhen: "event-automation",
432
- taskId: task.id
433
- } : void 0;
434
- const dispatch = await dispatchEventAutomation({
435
- automationId: task.id,
436
- conversationWorkQueue: options.queue,
437
- nowMs,
438
- options: {
439
- idempotencyKey,
440
- ...credentialSubject ? { credentialSubject } : void 0,
441
- destination,
442
- destinationVisibility: task.destinationVisibility,
443
- input: eventInput(task, event, outcomes, catalog),
444
- ...skill ? { skill } : void 0,
445
- metadata: { eventAutomationId: task.id },
446
- replyAttribution: automationReplyAttribution(task.title),
447
- outcomes
448
- }
449
- });
450
- await recordEventAutomationRunStarted(db, {
451
- automation: task,
452
- dispatchId: dispatch.id,
453
- nowMs
454
- });
455
- if (dispatch.status === "created") dispatched += 1;
456
- } catch (error) {
457
- errors.push(error);
458
- }
459
- if (errors.length > 0) throw new AggregateError(errors, "Failed to dispatch one or more event automations");
460
- return { dispatched };
461
- }
462
- // src/chat/events/workspace.ts
463
- /**
464
- * Resolve the single-bot Slack team id for event-automation indexing and
465
- * Event people mentions.
466
- *
467
- * Watch matching does not use this. Event automations still key by
468
- * destination team until that store is conversation-owned. Event delivery
469
- * itself is not gated on Slack.
470
- */
471
- function createEventTeamIdResolver() {
472
- let pending;
473
- return async () => {
474
- if (!getSlackBotToken()) return void 0;
475
- pending ??= getSlackClient().auth.test().then((result) => {
476
- const teamId = result.team_id?.trim();
477
- if (!teamId) throw new Error("Slack auth.test did not return a team id");
478
- return teamId;
479
- }).catch((error) => {
480
- pending = void 0;
481
- throw error;
482
- });
483
- return await pending;
484
- };
485
- }
486
- // src/chat/events/app-publisher.ts
487
- const WATCH_MATCH_CONCURRENCY = 4;
488
- /** Build the core event publisher used by plugin routes. */
489
- function createEventAppPublisher(args) {
490
- const resolveEventAutomationTeamId = createEventTeamIdResolver();
491
- return {
492
- async hasMatch(events) {
493
- const work = args.conversationWork();
494
- const eventAutomationTeamId = await resolveEventAutomationTeamId();
495
- const limit = pLimit(WATCH_MATCH_CONCURRENCY);
496
- const [subscriptions, tasks] = await Promise.all([Promise.all(events.map((event) => limit(() => findMatchingWatches({
497
- data: event.data,
498
- eventType: event.eventType,
499
- namespace: event.namespace,
500
- identifier: event.identifier,
501
- state: work.state
502
- })))), eventAutomationTeamId ? findMatchingEventAutomations(getDb(), events, eventAutomationTeamId, getEventCatalog()) : Promise.resolve([])]);
503
- return [...subscriptions, ...tasks].some((matched) => matched.length > 0);
504
- },
505
- async neededMatchKeys(input) {
506
- const work = args.conversationWork();
507
- const eventAutomationTeamId = await resolveEventAutomationTeamId();
508
- const [watchKeys, taskKeys] = await Promise.all([collectEventMatchKeys({
509
- eventTypes: input.eventTypes,
510
- identifiers: input.identifiers,
511
- namespace: input.namespace,
512
- state: work.state
513
- }), eventAutomationTeamId ? collectEventAutomationMatchKeys(getDb(), {
514
- catalog: getEventCatalog(),
515
- ...input.data ? { data: input.data } : void 0,
516
- eventTypes: input.eventTypes,
517
- identifiers: input.identifiers,
518
- namespace: input.namespace,
519
- teamId: eventAutomationTeamId
520
- }) : Promise.resolve([])]);
521
- return [.../* @__PURE__ */ new Set([...watchKeys, ...taskKeys])].sort();
522
- },
523
- async publish(event) {
524
- const work = args.conversationWork();
525
- const queue = work.queue ?? getVercelConversationWorkQueue();
526
- const eventAutomationTeamId = await resolveEventAutomationTeamId();
527
- await Promise.all([ingestEvent(event, {
528
- queue,
529
- slackTeamId: eventAutomationTeamId,
530
- state: work.state
531
- }), eventAutomationTeamId ? ingestEventAutomations(event, {
532
- queue,
533
- teamId: eventAutomationTeamId
534
- }) : Promise.resolve()]);
535
- }
536
- };
537
- }
538
- // src/chat/task-execution/heartbeat.ts
539
- const DEFAULT_RECOVERY_LIMIT = 25;
540
- function heartbeatIdempotencyKey(reason, conversationId, nowMs) {
541
- return `heartbeat:${reason}:${conversationId}:${nowMs}`;
542
- }
543
- /** Requeue expired leases and stranded mailbox work without running the agent. */
544
- async function recoverConversationWork(args) {
545
- if (!getChatConfig().conversationWorkEnabled) {
546
- logWarn("conversation.work.recovery.disabled");
547
- return {
548
- expiredLeaseCount: 0,
549
- pendingCount: 0
550
- };
551
- }
552
- const result = {
553
- expiredLeaseCount: 0,
554
- pendingCount: 0
555
- };
556
- const staleBeforeMs = args.nowMs - CONVERSATION_WORK_STALE_ENQUEUE_MS;
557
- const ids = await listActiveConversationIds({
558
- limit: args.limit ?? DEFAULT_RECOVERY_LIMIT,
559
- staleBeforeMs,
560
- state: args.state
561
- });
562
- for (const conversationId of ids) await withLogContext({ conversationId }, async () => {
563
- let work;
564
- try {
565
- work = await getConversationWorkState({
566
- conversationId,
567
- state: args.state
568
- });
569
- } catch (error) {
570
- logException(error, "conversation.work.recovery.failed");
571
- if (isInvalidConversationRecordError(error)) await pruneActiveConversation({
572
- conversationId,
573
- state: args.state
574
- });
575
- return;
576
- }
577
- try {
578
- if (!work || !hasRunnableConversationWork(work)) {
579
- await pruneActiveConversation({
580
- conversationId,
581
- state: args.state
582
- });
583
- return;
584
- }
585
- if (work.execution.lease && work.execution.lease.expiresAtMs <= args.nowMs) {
586
- const recovery = await clearExpiredConversationLease({
587
- beforeWorkStops: args.beforeWorkStops,
588
- conversationId,
589
- nowMs: args.nowMs,
590
- state: args.state
591
- });
592
- if (recovery === "not_expired") return;
593
- if (recovery === "stopped") {
594
- logException(/* @__PURE__ */ new Error("Conversation work stopped after repeated failed attempts"), "conversation.work.retry.exhausted", {
595
- "app.run.id": work.execution.runId ?? "unknown",
596
- "app.worker.last_progress_at_ms": work.execution.lastProgressAtMs ?? work.createdAtMs,
597
- "app.worker.retry_count": (work.execution.retryCount ?? 0) + 1
598
- });
599
- return;
600
- }
601
- if ((await ensureConversationWake({
602
- conversationId,
603
- idempotencyKey: heartbeatIdempotencyKey("lease", conversationId, args.nowMs),
604
- nowMs: args.nowMs,
605
- queue: args.queue,
606
- replaceExistingWake: true,
607
- state: args.state
608
- })).status === "enqueued") {
609
- result.expiredLeaseCount += 1;
610
- logInfo("conversation.work.lease_expired.requeued");
611
- }
612
- return;
613
- }
614
- if (work.execution.lease) return;
615
- if ((await ensureConversationWake({
616
- conversationId,
617
- idempotencyKey: heartbeatIdempotencyKey("pending", conversationId, args.nowMs),
618
- nowMs: args.nowMs,
619
- queue: args.queue,
620
- state: args.state
621
- })).status === "enqueued") {
622
- result.pendingCount += 1;
623
- logInfo("conversation.work.pending.requeued");
624
- }
625
- } catch (error) {
626
- logException(error, "conversation.work.recovery.failed");
627
- }
628
- });
629
- return result;
404
+ * this write, so a stored run, or a retry of the same Event, keeps the row it
405
+ * has.
406
+ */
407
+ async function recordEventAutomationRunStarted(db, args) {
408
+ const conversationId = getDispatchConversationId({ id: args.dispatchId });
409
+ await db.insert(juniorAutomationRuns).values({
410
+ id: args.dispatchId,
411
+ automationId: args.automation.id,
412
+ automationVersion: automationVersionOf(args.automation),
413
+ conversationId: existingConversationId(conversationId),
414
+ costMicroUsd: conversationCostOf(conversationId),
415
+ startedAtMs: args.nowMs,
416
+ status: "running"
417
+ }).onConflictDoNothing({ target: juniorAutomationRuns.id });
418
+ }
419
+ /**
420
+ * Settle running event automation runs whose dispatch has ended. A run whose
421
+ * dispatch record is gone fails.
422
+ */
423
+ async function settleEventAutomationRuns(db, nowMs) {
424
+ const runs = await db.select({
425
+ automationId: juniorAutomationRuns.automationId,
426
+ id: juniorAutomationRuns.id
427
+ }).from(juniorAutomationRuns).innerJoin(juniorAutomations, eq(juniorAutomations.id, juniorAutomationRuns.automationId)).where(and(eq(juniorAutomations.kind, "event"), eq(juniorAutomationRuns.status, "running")));
428
+ for (const run of runs) {
429
+ const dispatch = await getDispatchRecord(run.id);
430
+ const status = dispatch?.status ?? "failed";
431
+ if (status !== "blocked" && status !== "completed" && status !== "failed") continue;
432
+ await recordAutomationExecution(run.automationId, {
433
+ conversationId: getDispatchConversationId({ id: run.id }),
434
+ errorMessage: dispatch ? dispatch.errorMessage : "Event automation dispatch record is missing.",
435
+ executionId: run.id,
436
+ nowMs: dispatch?.updatedAtMs ?? nowMs,
437
+ status
438
+ });
439
+ }
440
+ }
441
+ // src/chat/automations/reply-attribution.ts
442
+ /** Name the Automation in the footer of the replies that its runs post. */
443
+ function automationReplyAttribution(title) {
444
+ const detail = (title ?? "").replace(/\s+/g, " ").trim().slice(0, 128).trim();
445
+ return detail ? {
446
+ label: "Automation",
447
+ detail
448
+ } : { label: "Automation" };
630
449
  }
631
450
  // src/chat/scheduled-automations/runs.ts
632
451
  const PENDING_CLAIM_STALE_MS = 6e4;
@@ -662,13 +481,15 @@ async function readRun(db, runId) {
662
481
  */
663
482
  async function writeRun(db, run, automationVersion) {
664
483
  const stored = scheduledRunSchema.parse(run);
484
+ const dispatchConversationId = stored.dispatchId ? getDispatchConversationId({ id: stored.dispatchId }) : void 0;
665
485
  const columns = {
666
486
  ...automationVersion ? { automationVersion } : void 0,
667
487
  attempt: stored.attempt,
668
488
  automationId: stored.taskId,
669
489
  claimedAtMs: stored.claimedAtMs,
670
490
  completedAtMs: stored.completedAtMs ?? null,
671
- conversationId: stored.dispatchId ? existingConversationId(getDispatchConversationId({ id: stored.dispatchId })) : null,
491
+ conversationId: dispatchConversationId ? existingConversationId(dispatchConversationId) : null,
492
+ costMicroUsd: dispatchConversationId ? conversationCostOf(dispatchConversationId) : null,
672
493
  dispatchId: stored.dispatchId ?? null,
673
494
  errorMessage: stored.errorMessage ?? null,
674
495
  resultMessageTs: stored.resultMessageTs ?? null,
@@ -683,6 +504,7 @@ async function writeRun(db, run, automationVersion) {
683
504
  target: juniorAutomationRuns.id,
684
505
  set: columns
685
506
  });
507
+ if (stored.completedAtMs !== void 0) await refreshAutomationLastRun(db, stored.taskId);
686
508
  }
687
509
  /**
688
510
  * List incomplete Scheduled automation runs, optionally for one automation.
@@ -1267,6 +1089,7 @@ async function runPluginHeartbeats(args) {
1267
1089
  try {
1268
1090
  const result = await runWithTimeout(Promise.resolve(heartbeat(createHeartbeatContext({
1269
1091
  conversationWorkQueue: args.conversationWorkQueue,
1092
+ dispatchForIdentity: args.dispatchForIdentity,
1270
1093
  events: createPluginEventPublisher(plugin, args.events),
1271
1094
  plugin,
1272
1095
  nowMs: args.nowMs,
@@ -1336,7 +1159,6 @@ async function recoverPendingAgentInvocationResults(args) {
1336
1159
  /** Run the core heartbeat phases. */
1337
1160
  async function runHeartbeat(args) {
1338
1161
  const queue = args.conversationWorkQueue ?? getVercelConversationWorkQueue();
1339
- const events = args.events ?? createEventAppPublisher({ conversationWork: () => ({ queue }) });
1340
1162
  const endStoppedChildWork = createEndStoppedChildWork({ queue });
1341
1163
  await recoverConversationWork({
1342
1164
  beforeWorkStops: async (conversationId, inboundMessageIds) => {
@@ -1377,7 +1199,8 @@ async function runHeartbeat(args) {
1377
1199
  }
1378
1200
  await runPluginHeartbeats({
1379
1201
  conversationWorkQueue: queue,
1380
- events,
1202
+ dispatchForIdentity: args.dispatchForIdentity,
1203
+ events: args.events,
1381
1204
  nowMs: args.nowMs,
1382
1205
  showReviewItem: args.showReviewItem
1383
1206
  });
@@ -1391,6 +1214,14 @@ async function runHeartbeat(args) {
1391
1214
  } catch (error) {
1392
1215
  logException(error, "cache_warming.savings_refill.failed");
1393
1216
  }
1217
+ if (isBriefsEnabled()) try {
1218
+ await runConversationEmbeddingBackfill(createConversationEmbedder({
1219
+ cost: { owner: "none" },
1220
+ operation: "conversation_embedding"
1221
+ }));
1222
+ } catch (error) {
1223
+ logException(error, "conversation_embeddings.backfill.failed");
1224
+ }
1394
1225
  }
1395
1226
  // src/handlers/scheduler-auth.ts
1396
1227
  /** Check the bearer secret that internal cron requests must send. */
@@ -1405,11 +1236,12 @@ function verifySchedulerRequest(request) {
1405
1236
  }
1406
1237
  // src/handlers/heartbeat.ts
1407
1238
  /** Handle the authenticated internal heartbeat. */
1408
- async function GET$3(request, waitUntil, options = {}) {
1239
+ async function GET$3(request, waitUntil, options) {
1409
1240
  if (!verifySchedulerRequest(request)) return new Response("Unauthorized", { status: 401 });
1410
1241
  const nowMs = Date.now();
1411
1242
  waitUntil(() => runHeartbeat({
1412
1243
  conversationWorkQueue: options.conversationWorkQueue,
1244
+ dispatchForIdentity: options.dispatchForIdentity,
1413
1245
  events: options.events,
1414
1246
  nowMs,
1415
1247
  showReviewItem: options.showReviewItem
@@ -1488,6 +1320,10 @@ async function selectExpiredRoots(executor, args) {
1488
1320
  and review_items.status = 'open'
1489
1321
  and review_items.automation_id is null
1490
1322
  )
1323
+ or exists (
1324
+ select 1 from junior_plan_items plan_items
1325
+ where plan_items.conversation_id = tree.conversation_id
1326
+ )
1491
1327
  or (
1492
1328
  ${juniorDestinations.visibility} is distinct from 'public'
1493
1329
  and (
@@ -1529,9 +1365,9 @@ async function selectExpiredRoots(executor, args) {
1529
1365
  * event rows for the given conversation and every descendant, stamp
1530
1366
  * `transcript_purged_at`, and — for non-public content — null the raw-payload
1531
1367
  * metadata (`title`, `channel_name`, legacy actor JSON) so purged private
1532
- * conversations keep only safe metadata. Non-public content also loses its
1533
- * Briefs and the Review items that it added. The metadata rows themselves
1534
- * survive.
1368
+ * conversations keep only safe metadata. Plan items go with the transcript.
1369
+ * Non-public content also loses its Briefs and the Review items that it
1370
+ * added. The metadata rows themselves survive.
1535
1371
  */
1536
1372
  async function purgeConversationTree(executor, args) {
1537
1373
  return await withConversationMutationLock(executor, args.rootConversationId, async () => {
@@ -1582,6 +1418,7 @@ async function purgeConversationTree(executor, args) {
1582
1418
  nowMs: args.nowMs,
1583
1419
  reason: "Conversation purged"
1584
1420
  });
1421
+ await deletePlanItems(executor, ids);
1585
1422
  await requestAttachmentDeletion(executor, ids, args.nowMs);
1586
1423
  const scrubMetadata = args.retention ? !isPublic : resolvedScrubMetadata;
1587
1424
  if (scrubMetadata) {
@@ -2536,33 +2373,142 @@ function textMentionsBot(text, botUserId) {
2536
2373
  function eventMentionsBot(event, botUserId) {
2537
2374
  return Boolean(botUserId && (textMentionsBot(event.text ?? "", botUserId) || event.blocks?.some((block) => block.type === "section" && typeof block.text === "object" && block.text.type === "mrkdwn" && textMentionsBot(block.text.text, botUserId))));
2538
2375
  }
2539
- // src/chat/ingress/slack-allowed-domain.ts
2540
- const ALLOWED_TTL_MS = 3e5;
2541
- const NOT_ALLOWED_TTL_MS = 3e4;
2376
+ // src/chat/event-automations/ingest.ts
2542
2377
  /**
2543
- * Return whether a Slack author may start a Turn. With allowed domains, the
2544
- * email of the author's Slack profile must be on one of them. Slack verifies
2545
- * that email, so Junior trusts it. Bots have no profile email, so the allowed
2546
- * bot user IDs skip this check. Without allowed domains, every author may.
2378
+ * Owns event matching and durable event-automation dispatch.
2379
+ *
2380
+ * Each matching automation is independently idempotent. Aggregate failures propagate
2381
+ * so the provider can retry the original delivery.
2547
2382
  */
2548
- async function isSlackAuthorDomainAllowed(args) {
2549
- if (args.allowedDomains.length === 0) return true;
2550
- const userId = parseSlackUserId(args.user);
2551
- if (!args.teamId || !userId) return false;
2552
- if (args.allowedBotUserIds.includes(userId)) return true;
2553
- return await createCache(args.state, "core").getOrLoad(`slack:allowed-domain:${args.teamId}:${userId}`, async () => {
2554
- const profile = await lookupSlackUserProfile(userId);
2555
- const email = profile.email?.toLowerCase();
2556
- const separator = email?.lastIndexOf("@") ?? -1;
2557
- const domain = separator > 0 ? email?.slice(separator + 1) : void 0;
2558
- const allowed = profile.id === userId && isAllowedDomain(domain, args.allowedDomains);
2559
- if (!allowed) logWarn("slack.allowed_domain.rejected", { "app.reason": email ? "domain_not_allowed" : "missing_email" });
2560
- return {
2561
- value: allowed,
2562
- ttlMs: allowed ? ALLOWED_TTL_MS : NOT_ALLOWED_TTL_MS
2563
- };
2383
+ /** Bind provider delivery identity to one automation's durable dispatch. */
2384
+ function eventAutomationDispatchKey(taskId, namespace, eventKey) {
2385
+ return `event-automation:${createHash("sha256").update(`${taskId}\0${namespace}\0${eventKey}`).digest("hex").slice(0, 32)}`;
2386
+ }
2387
+ /** Render plain agent input for one matching event automation. */
2388
+ function eventInput(task, event, outcomes, catalog, author) {
2389
+ const guidance = eventGuidance(catalog, event.namespace, event.eventType);
2390
+ return renderTaskInput({
2391
+ about: task.trigger.label,
2392
+ event: event.eventType,
2393
+ source: event.namespace,
2394
+ creator: slackMention(task.createdBy.slackUserId),
2395
+ instructions: automationTaskText(task.task),
2396
+ ...task.task.kind === "skill" ? { skill: task.task.skill } : void 0,
2397
+ outcomes,
2398
+ guidance,
2399
+ trustedSummary: event.trustedSummary,
2400
+ trustedSummaryMaxLength: EVENT_SUMMARY_MAX_LENGTH,
2401
+ verifiedDetails: event.data,
2402
+ authorText: eventAuthorText(author),
2403
+ externalText: event.untrustedText,
2404
+ externalTextMaxLength: EVENT_TEXT_MAX_LENGTH
2564
2405
  });
2565
2406
  }
2407
+ /**
2408
+ * Match a normalized event and dispatch every matching automation.
2409
+ *
2410
+ * Plugins publish one copy of an occurrence for each scope, such as a pull
2411
+ * request and its repository. All copies share one event key. An automation
2412
+ * with no identifier matches every copy, and the dispatch key and the run
2413
+ * limit both use the event key, so it runs and counts once.
2414
+ */
2415
+ async function ingestEventAutomations(input, options) {
2416
+ const event = eventSchema$1.parse(input);
2417
+ const db = getDb();
2418
+ const nowMs = options.nowMs ?? Date.now();
2419
+ const catalog = getEventCatalog();
2420
+ const [matches = []] = await findMatchingEventAutomations(db, [event], options.teamId, catalog);
2421
+ const tasks = matches.filter((task) => slackChannelMessageRunsAutomation(event, task));
2422
+ if (tasks.length === 0) return { dispatched: 0 };
2423
+ const author = await resolveEventAuthor(event);
2424
+ let dispatched = 0;
2425
+ const errors = [];
2426
+ for (const task of tasks) try {
2427
+ const skill = task.task.kind === "skill" ? task.task.skill : void 0;
2428
+ if (skill && !await findAutomationSkill(skill)) {
2429
+ const reason = missingAutomationSkillReason(skill);
2430
+ if (await blockEventAutomation(db, task.id, reason)) await notifyAutomationBlocked({
2431
+ automationId: task.id,
2432
+ kind: "event",
2433
+ reason
2434
+ });
2435
+ continue;
2436
+ }
2437
+ const idempotencyKey = eventAutomationDispatchKey(task.id, event.namespace, event.eventKey);
2438
+ if (await admitEventAutomationRun({
2439
+ automationId: task.id,
2440
+ nowMs,
2441
+ runKey: idempotencyKey
2442
+ }) === "limited") {
2443
+ const reason = eventAutomationRunLimitReason();
2444
+ logWarn("event_automation.run_limit.exceeded", {
2445
+ "app.task.id": task.id,
2446
+ "app.task.type": "event"
2447
+ });
2448
+ if (await blockEventAutomation(db, task.id, reason)) {
2449
+ captureMessage("Event automation blocked by run limit", {
2450
+ level: "warning",
2451
+ fingerprint: ["event_automation.run_limit.blocked"],
2452
+ tags: {
2453
+ "app.event.namespace": event.namespace,
2454
+ "app.task.type": "event"
2455
+ },
2456
+ extra: {
2457
+ "app.event.event_type": event.eventType,
2458
+ "app.event_automation.max_runs": botConfig.maxEventAutomationRuns,
2459
+ "app.event_automation.run_window_ms": botConfig.eventAutomationRunWindowMs,
2460
+ "app.event_automation.resource_type": task.trigger.resourceType ?? "any",
2461
+ "app.task.id": task.id
2462
+ }
2463
+ });
2464
+ await notifyAutomationBlocked({
2465
+ automationId: task.id,
2466
+ kind: "event",
2467
+ reason
2468
+ });
2469
+ }
2470
+ continue;
2471
+ }
2472
+ const replyThreadTs = slackChannelMessageReplyThreadTs(event);
2473
+ const destination = replyThreadTs ? {
2474
+ ...task.destination,
2475
+ threadTs: replyThreadTs
2476
+ } : task.destination;
2477
+ const outcomes = effectiveTaskOutcomes(task.outcomes, destination);
2478
+ const credentialSubject = task.credentialMode === "creator" ? {
2479
+ type: "user",
2480
+ userId: task.createdBy.slackUserId,
2481
+ allowedWhen: "event-automation",
2482
+ taskId: task.id
2483
+ } : void 0;
2484
+ const dispatch = await dispatchEventAutomation({
2485
+ automationId: task.id,
2486
+ conversationWorkQueue: options.queue,
2487
+ nowMs,
2488
+ options: {
2489
+ idempotencyKey,
2490
+ ...credentialSubject ? { credentialSubject } : void 0,
2491
+ destination,
2492
+ destinationVisibility: task.destinationVisibility,
2493
+ input: eventInput(task, event, outcomes, catalog, author),
2494
+ ...skill ? { skill } : void 0,
2495
+ metadata: { eventAutomationId: task.id },
2496
+ replyAttribution: automationReplyAttribution(task.title),
2497
+ outcomes
2498
+ }
2499
+ });
2500
+ await recordEventAutomationRunStarted(db, {
2501
+ automation: task,
2502
+ dispatchId: dispatch.id,
2503
+ nowMs
2504
+ });
2505
+ if (dispatch.status === "created") dispatched += 1;
2506
+ } catch (error) {
2507
+ errors.push(error);
2508
+ }
2509
+ if (errors.length > 0) throw new AggregateError(errors, "Failed to dispatch one or more event automations");
2510
+ return { dispatched };
2511
+ }
2566
2512
  // src/chat/ingress/slack-message-telemetry.ts
2567
2513
  function field(value, pattern) {
2568
2514
  if (value === void 0) return "missing";
@@ -2622,7 +2568,12 @@ function dateField(key, label, value, empty) {
2622
2568
  function renderAutomationDetails(automation) {
2623
2569
  const url = getDashboardTaskLink(automation.id);
2624
2570
  if (!url) return void 0;
2625
- const fields = [textField("status", "Status", automation.kind === "scheduled" ? automation.status : automation.trigger.problems.length === 0 ? "ready" : "unavailable")];
2571
+ const { status, warning } = automationCardStatus({
2572
+ status: automation.status,
2573
+ statusReason: automation.statusReason,
2574
+ triggerProblems: automation.kind === "event" ? automation.trigger.problems : void 0
2575
+ });
2576
+ const fields = [textField("status", "Status", status)];
2626
2577
  const { task } = automation;
2627
2578
  if (task.kind === "skill") fields.push(textField("skill", "Skill", task.skill));
2628
2579
  const text = automationTaskText(task);
@@ -2647,11 +2598,11 @@ function renderAutomationDetails(automation) {
2647
2598
  ...textField("filters", "Filters", trigger.filters.length > 0 ? eventTriggerFiltersText(trigger.filters) : "No filters. Runs on every selected event."),
2648
2599
  long: true
2649
2600
  });
2650
- if (trigger.problems.length > 0) fields.push({
2651
- ...textField("warning", "Needs attention", ["Trigger unavailable.", ...trigger.problems].join(" ")),
2652
- long: true
2653
- });
2654
2601
  }
2602
+ if (warning) fields.push({
2603
+ ...textField("warning", "Needs attention", warning),
2604
+ long: true
2605
+ });
2655
2606
  const lastRun = dateField("last_run", "Last execution", automation.lastRunAt, "Never run");
2656
2607
  if (automation.lastRunAt && automation.lastConversationId) lastRun.link = getDashboardConversationLink(automation.lastConversationId);
2657
2608
  fields.push(textField("outcomes", "Outcomes", automation.outcomes.length === 0 ? "None (silent)" : `${automation.outcomes.length} message${automation.outcomes.length === 1 ? "" : "s"}`), textField("destination", "Destination", `${automation.destination.label} · ${automation.destination.visibility}`), textField("created_by", "Created by", automation.createdBy), dateField("date_created", "Created", automation.createdAt, "Unknown"), textField("executions", "Executions", `${automation.totalRuns} total · ${automation.runs[30]} in the last 30 days`), lastRun);
@@ -2675,7 +2626,7 @@ const detailsEventSchema = z.object({
2675
2626
  trigger_id: z.string().min(1),
2676
2627
  user: z.string().min(1),
2677
2628
  external_ref: z.object({
2678
- id: z.string().min(1),
2629
+ id: slackExternalRefIdSchema,
2679
2630
  type: z.literal("automation")
2680
2631
  })
2681
2632
  });
@@ -2889,14 +2840,12 @@ async function routeParsedMessage(args) {
2889
2840
  text: args.event.text ?? "",
2890
2841
  isExplicitMention: isMention
2891
2842
  });
2892
- const isAuthorDomainAllowed = () => isSlackAuthorDomainAllowed({
2893
- allowedBotUserIds: args.allowedBotUserIds,
2894
- allowedDomains: args.allowedDomains,
2843
+ const isAuthorTrusted = () => isTrustedSlackAuthor({
2895
2844
  state: args.state,
2896
2845
  teamId: args.installation.teamId,
2897
2846
  user: args.event.user
2898
2847
  });
2899
- if (!stopDecision && route === "mention" && !await isAuthorDomainAllowed()) return;
2848
+ if (!stopDecision && route === "mention" && !await isAuthorTrusted()) return;
2900
2849
  await bindSlackAuthorIdentity(message, args.installation);
2901
2850
  const conversationId = await resolveSlackConversationId({
2902
2851
  canonicalThreadId,
@@ -2953,7 +2902,7 @@ async function routeParsedMessage(args) {
2953
2902
  const closeAnswered = async () => {
2954
2903
  if (message.author.isBot === true) return;
2955
2904
  await closeReviewItemsAnsweredByReply({
2956
- ...route === "subscribed" ? { canAnswer: isAuthorDomainAllowed } : void 0,
2905
+ ...route === "subscribed" ? { canAnswer: isAuthorTrusted } : void 0,
2957
2906
  conversationId,
2958
2907
  delivery: {
2959
2908
  queue: args.queue,
@@ -3131,8 +3080,6 @@ async function handleSlackEvent(args) {
3131
3080
  conversationStore: args.services.conversationStore,
3132
3081
  queue: args.services.queue,
3133
3082
  receivedAtMs,
3134
- allowedBotUserIds: args.services.allowedBotUserIds ?? [],
3135
- allowedDomains: args.services.allowedDomains ?? [],
3136
3083
  runAfterUnlock: (task) => {
3137
3084
  afterUnlock = task;
3138
3085
  },
@@ -3191,9 +3138,7 @@ async function handleSlackWebhook(args) {
3191
3138
  adapter,
3192
3139
  body,
3193
3140
  getUserTokenStore: () => getUserTokenStore(args.services),
3194
- isAuthorAllowed: (userId, installation) => isSlackAuthorDomainAllowed({
3195
- allowedBotUserIds: args.services.allowedBotUserIds ?? [],
3196
- allowedDomains: args.services.allowedDomains ?? [],
3141
+ isAuthorAllowed: (userId, installation) => isTrustedSlackAuthor({
3197
3142
  state,
3198
3143
  teamId: installation.teamId,
3199
3144
  user: userId
@@ -3506,6 +3451,98 @@ async function publicArtifactGET(args) {
3506
3451
  return new Response("Internal Server Error", { status: 500 });
3507
3452
  }
3508
3453
  }
3454
+ // src/chat/events/app-publisher.ts
3455
+ const WATCH_MATCH_CONCURRENCY = 4;
3456
+ /** Build the core event publisher used by plugin routes. */
3457
+ function createEventAppPublisher(args) {
3458
+ return {
3459
+ async hasMatch(events) {
3460
+ const work = args.conversationWork();
3461
+ const eventAutomationTeamId = await resolveBotSlackTeamId();
3462
+ const limit = pLimit(WATCH_MATCH_CONCURRENCY);
3463
+ const [subscriptions, tasks] = await Promise.all([Promise.all(events.map((event) => limit(() => findMatchingWatches({
3464
+ data: event.data,
3465
+ eventType: event.eventType,
3466
+ namespace: event.namespace,
3467
+ identifier: event.identifier,
3468
+ state: work.state
3469
+ })))), eventAutomationTeamId ? findMatchingEventAutomations(getDb(), events, eventAutomationTeamId, getEventCatalog()) : Promise.resolve([])]);
3470
+ return [...subscriptions, ...tasks].some((matched) => matched.length > 0);
3471
+ },
3472
+ async neededMatchKeys(input) {
3473
+ const work = args.conversationWork();
3474
+ const eventAutomationTeamId = await resolveBotSlackTeamId();
3475
+ const [watchKeys, taskKeys] = await Promise.all([collectEventMatchKeys({
3476
+ eventTypes: input.eventTypes,
3477
+ identifiers: input.identifiers,
3478
+ namespace: input.namespace,
3479
+ state: work.state
3480
+ }), eventAutomationTeamId ? collectEventAutomationMatchKeys(getDb(), {
3481
+ catalog: getEventCatalog(),
3482
+ ...input.data ? { data: input.data } : void 0,
3483
+ eventTypes: input.eventTypes,
3484
+ identifiers: input.identifiers,
3485
+ namespace: input.namespace,
3486
+ teamId: eventAutomationTeamId
3487
+ }) : Promise.resolve([])]);
3488
+ return [.../* @__PURE__ */ new Set([...watchKeys, ...taskKeys])].sort();
3489
+ },
3490
+ async publish(event) {
3491
+ const work = args.conversationWork();
3492
+ const queue = work.queue ?? getVercelConversationWorkQueue();
3493
+ const eventAutomationTeamId = await resolveBotSlackTeamId();
3494
+ await Promise.all([ingestEvent(event, {
3495
+ queue,
3496
+ slackTeamId: eventAutomationTeamId,
3497
+ state: work.state
3498
+ }), eventAutomationTeamId ? ingestEventAutomations(event, {
3499
+ queue,
3500
+ teamId: eventAutomationTeamId
3501
+ }) : Promise.resolve()]);
3502
+ }
3503
+ };
3504
+ }
3505
+ // src/chat/agent-dispatch/identity.ts
3506
+ /**
3507
+ * Build the one entry point that starts work for a person whom a plugin
3508
+ * names, from a webhook route or a heartbeat.
3509
+ *
3510
+ * The person must be a Trusted author with a User (`findTrustedUser`): a
3511
+ * `subjectId` of the calling plugin's provider that the OAuth account-linking
3512
+ * flow linked, or a `verifiedEmail` that is the User's primary email. Without
3513
+ * a Slack bot, nothing matches.
3514
+ *
3515
+ * On a match, the input is that person's first Message in a new public
3516
+ * Conversation, as if they sent it from the dashboard. The Conversation has no
3517
+ * Slack Destination.
3518
+ */
3519
+ function createIdentityDispatcher(args) {
3520
+ const notLinked = (plugin, reason) => {
3521
+ logInfo("dispatch.identity.not_linked", {
3522
+ "app.plugin.name": plugin,
3523
+ "app.dispatch.identity.reason": reason
3524
+ });
3525
+ return { status: "not_linked" };
3526
+ };
3527
+ return async (plugin, options) => {
3528
+ const request = identityDispatchOptionsSchema.parse(options);
3529
+ const trust = await findTrustedUser("subjectId" in request ? {
3530
+ provider: plugin,
3531
+ subjectId: request.subjectId
3532
+ } : { verifiedEmail: request.verifiedEmail });
3533
+ if (trust.status === "untrusted") return notLinked(plugin, trust.reason);
3534
+ const accepted = await createAndEnqueueConversation({
3535
+ actor: webActorFromUser(trust.user),
3536
+ idempotencyKey: `${plugin}:${request.idempotencyKey}`,
3537
+ message: request.input,
3538
+ visibility: "public"
3539
+ }, { queue: args.conversationWorkQueue() });
3540
+ return {
3541
+ conversationId: accepted.conversationId,
3542
+ status: accepted.status === "duplicate" ? "already_exists" : "created"
3543
+ };
3544
+ };
3545
+ }
3509
3546
  // src/api/acp/conversations.ts
3510
3547
  const EVENT_PAGE_SIZE = 50;
3511
3548
  async function hasConversationAccess(conversationId, user) {
@@ -6312,7 +6349,7 @@ function triggerText(automation) {
6312
6349
  const { events, filters } = automation.trigger;
6313
6350
  return [`${events.join(", ")} on ${automation.resource}`, ...filters].join("; ");
6314
6351
  }
6315
- /** Map an Automation summary to its MCP view. */
6352
+ /** Map an Automation list row or summary to its MCP view. */
6316
6353
  function mcpAutomation(automation) {
6317
6354
  const url = getDashboardTaskLink(automation.id);
6318
6355
  return {
@@ -6358,9 +6395,10 @@ function registerGetAutomationTool(server, { user }) {
6358
6395
  }
6359
6396
  }, async ({ id }) => {
6360
6397
  try {
6361
- const list = await readViewerAutomationExecutions(user, id);
6398
+ const [automation, list] = await Promise.all([readViewerAutomationSummary(user, id), readViewerAutomationExecutions(user, id)]);
6399
+ if (!automation) return mcpToolError("Automation not found.");
6362
6400
  return mcpToolResult({
6363
- automation: mcpAutomation(list.automation),
6401
+ automation: mcpAutomation(automation),
6364
6402
  runs: list.executions.slice(0, RECENT_RUN_LIMIT).map(({ conversationId, error, executedAt, status }) => ({
6365
6403
  executedAt,
6366
6404
  status,
@@ -7078,7 +7116,11 @@ function createMcpHttpHandler(options) {
7078
7116
  state: options.state,
7079
7117
  token
7080
7118
  }) : void 0;
7081
- const user = grant && isAllowedSignInEmail(grant.email, options.allowedDomains) ? await resolveViewerUser(grant.email) : void 0;
7119
+ const email = grant ? parseEmail(grant.email) : void 0;
7120
+ const user = grant && email && isAllowedDomain(email.domain, {
7121
+ allowedDomains: options.allowedDomains,
7122
+ ifNoDomains: "deny"
7123
+ }) ? await resolveViewerUser(grant.email) : void 0;
7082
7124
  if (!grant || !user) return unauthorized(requestUrls, token !== void 0);
7083
7125
  if (c.req.method !== "POST") return new Response(null, {
7084
7126
  status: 405,
@@ -7174,6 +7216,43 @@ async function handleAcpAuthorizationPage(args) {
7174
7216
  });
7175
7217
  return renderResult(args.agentName, result);
7176
7218
  }
7219
+ // src/chat/sign-in/allowlist.ts
7220
+ /**
7221
+ * Read the domain list that may use Junior. Slack authors must have a Slack
7222
+ * profile email on one of them, and dashboard Google sign-ins must come from
7223
+ * a Google Workspace account whose `hd` claim is one of them. Slack and the
7224
+ * dashboard share one list. `chat/identities/trust` decides who matches.
7225
+ */
7226
+ /** Read a list env var: a JSON string array or comma-separated values. */
7227
+ function readEnvList(name) {
7228
+ const value = process.env[name]?.trim();
7229
+ if (!value) return void 0;
7230
+ if (!value.startsWith("[")) return value.split(",");
7231
+ let parsed;
7232
+ try {
7233
+ parsed = JSON.parse(value);
7234
+ } catch (error) {
7235
+ throw new Error(`${name} must be a JSON string array`, { cause: error });
7236
+ }
7237
+ const list = z.array(z.string()).safeParse(parsed);
7238
+ if (!list.success) throw new Error(`${name} must be a JSON string array`);
7239
+ return list.data;
7240
+ }
7241
+ /**
7242
+ * Resolve the allowed domains: the `createApp` option when set, else
7243
+ * `JUNIOR_ALLOWED_DOMAINS`. An empty list allows every domain.
7244
+ */
7245
+ function resolveAllowedDomains(allowedDomains) {
7246
+ return [...new Set((allowedDomains ?? readEnvList("JUNIOR_ALLOWED_DOMAINS") ?? []).map((value) => value.trim().toLowerCase()).filter(Boolean))];
7247
+ }
7248
+ /**
7249
+ * Fail startup on the removed Google-specific names. Ignoring them would
7250
+ * leave the list empty, which lets every Slack workspace member in.
7251
+ */
7252
+ function assertNoLegacyAllowedDomains(dashboardOptionKeys) {
7253
+ if (dashboardOptionKeys.includes("allowedGoogleDomains")) throw new Error("dashboard.allowedGoogleDomains was removed; set createApp({ allowedDomains }) instead");
7254
+ if (process.env["JUNIOR_DASHBOARD_GOOGLE_DOMAINS"]?.trim()) throw new Error("JUNIOR_DASHBOARD_GOOGLE_DOMAINS was removed; set JUNIOR_ALLOWED_DOMAINS instead");
7255
+ }
7177
7256
  // src/chat/sign-in/auth.ts
7178
7257
  /**
7179
7258
  * Google sign-in session for the dashboard.
@@ -7258,7 +7337,10 @@ function createBetterAuth(config) {
7258
7337
  if (!token.idToken) return null;
7259
7338
  const claims = readGoogleClaims(token.idToken);
7260
7339
  if (!claims) return null;
7261
- if (!isAllowedDomain(claims.hd, allowedDomains)) return null;
7340
+ if (!isAllowedDomain(claims.hd, {
7341
+ allowedDomains,
7342
+ ifNoDomains: "allow"
7343
+ })) return null;
7262
7344
  return {
7263
7345
  user: {
7264
7346
  email: claims.email,
@@ -7665,8 +7747,11 @@ async function createApp(options) {
7665
7747
  const previousSandboxResources = getSandboxResourceConfig();
7666
7748
  const previousExperimentalFeatures = getExperimentalFeatures();
7667
7749
  const previousBriefsConfig = setBriefsConfig(options?.briefs);
7750
+ const previousEventEmbeddingsConfig = setEventEmbeddingsConfig(options?.eventEmbeddings);
7668
7751
  const previousDashboardLinkOptions = setDashboardConversationLinkOptions(dashboard);
7752
+ let previousTrustConfig;
7669
7753
  const restoreRuntimeConfig$1 = () => {
7754
+ if (previousTrustConfig) setTrustConfig(previousTrustConfig);
7670
7755
  pluginCatalogRuntime.setConfig(previousPluginCatalogConfig);
7671
7756
  setPlugins(previousPlugins);
7672
7757
  setConfigDefaults(previousConfigDefaults);
@@ -7674,6 +7759,7 @@ async function createApp(options) {
7674
7759
  setSandboxResourceConfig(previousSandboxResources);
7675
7760
  setExperimentalFeatures(previousExperimentalFeatures);
7676
7761
  setBriefsConfig(previousBriefsConfig);
7762
+ setEventEmbeddingsConfig(previousEventEmbeddingsConfig);
7677
7763
  setDashboardConversationLinkOptions(previousDashboardLinkOptions);
7678
7764
  };
7679
7765
  let pluginRoutes = [];
@@ -7685,6 +7771,7 @@ async function createApp(options) {
7685
7771
  let sandboxEgressTracePropagationDomains = [];
7686
7772
  let signInConfig;
7687
7773
  let allowedDomains = [];
7774
+ let dispatchForIdentity;
7688
7775
  try {
7689
7776
  sandboxEgressTracePropagationDomains = normalizeSandboxEgressTracePropagationDomains(options?.sandbox?.egressTracePropagationDomains);
7690
7777
  setSandboxResourceConfig(options?.sandbox);
@@ -7698,7 +7785,12 @@ async function createApp(options) {
7698
7785
  setSlackReactionConfig(options?.slack ?? {});
7699
7786
  assertNoLegacyAllowedDomains(Object.keys(dashboard ?? {}));
7700
7787
  allowedDomains = resolveAllowedDomains(options?.allowedDomains);
7788
+ previousTrustConfig = setTrustConfig({
7789
+ allowedBotUserIds: options?.slack?.allowedBotUserIds ?? [],
7790
+ allowedDomains
7791
+ });
7701
7792
  if (allowedDomains.length === 0) logWarn("app.allowed_domains.unset", { "app.reason": "allowedDomains is empty, so any Slack workspace member can use the bot" });
7793
+ dispatchForIdentity = createIdentityDispatcher({ conversationWorkQueue: () => conversationWorkQueue });
7702
7794
  if (dashboard && !dashboard.disabled) signInConfig = resolveSignInAuthConfig(botConfig.userName, allowedDomains, dashboard);
7703
7795
  if (shouldValidatePluginCatalog) {
7704
7796
  pluginCatalogRuntime.getSignature();
@@ -7706,6 +7798,7 @@ async function createApp(options) {
7706
7798
  validatePluginEgressCredentialHooks(configuredPlugins?.registrations ?? []);
7707
7799
  }
7708
7800
  pluginRoutes = getPluginRoutes({
7801
+ dispatchForIdentity,
7709
7802
  events,
7710
7803
  showReviewItem: createSlackReviewItemShow(getProductionSlackAdapter)
7711
7804
  });
@@ -7724,6 +7817,7 @@ async function createApp(options) {
7724
7817
  messageId: delivery.messageId
7725
7818
  })) ?? getVercelConversationWorkQueue();
7726
7819
  const pluginTaskQueue = options?.pluginTaskQueue?.(processPluginTask);
7820
+ const sendPluginTask = pluginTaskQueue ? (message) => pluginTaskQueue.send(message) : sendVercelPluginTask;
7727
7821
  const backgroundCompactionQueue = options?.backgroundCompactionQueue?.((message) => processBackgroundCompaction(message)) ?? vercelBackgroundCompactionQueue;
7728
7822
  const attachmentStorage = getAttachmentStorage();
7729
7823
  const agentRunner = createAgentRunner(executeAgentRun, {
@@ -7745,7 +7839,7 @@ async function createApp(options) {
7745
7839
  conversationWorkOptions ??= options?.conversationWork ?? createProductionConversationWorkOptions({
7746
7840
  agentRunner,
7747
7841
  queue: conversationWorkQueue,
7748
- ...pluginTaskQueue ? { sendPluginTask: (message) => pluginTaskQueue.send(message) } : void 0,
7842
+ sendPluginTask,
7749
7843
  services: runtimeServiceOverrides,
7750
7844
  waitUntil: (task) => {
7751
7845
  backgroundWork.add(task);
@@ -7824,8 +7918,6 @@ async function createApp(options) {
7824
7918
  queue: conversationWorkQueue,
7825
7919
  services: runtimeServiceOverrides
7826
7920
  }),
7827
- allowedBotUserIds: options?.slack?.allowedBotUserIds ?? [],
7828
- allowedDomains,
7829
7921
  autoJoinNewChannels: options?.slack?.autoJoinNewChannels === true
7830
7922
  };
7831
7923
  const app = new Hono();
@@ -7927,6 +8019,7 @@ async function createApp(options) {
7927
8019
  app.get("/api/internal/heartbeat", (c) => {
7928
8020
  return GET$3(c.req.raw, waitUntil, {
7929
8021
  conversationWorkQueue,
8022
+ dispatchForIdentity,
7930
8023
  events,
7931
8024
  showReviewItem: createSlackReviewItemShow(getProductionSlackAdapter)
7932
8025
  });