@sentry/junior 0.310.0 → 0.311.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 (112) hide show
  1. package/dist/adapter-B1wujchl.js +259 -0
  2. package/dist/{adapter-context-BhKpjpGD.js → adapter-context-G2M0y6rP.js} +2 -2
  3. package/dist/{admin-tgZEZAk2.js → admin-DCiBhUT1.js} +1 -2
  4. package/dist/{agent-runner-D9cvNlQl.js → agent-runner-BVHPUIc8.js} +543 -1703
  5. package/dist/api/schema.d.ts +2 -2
  6. package/dist/api/schema.js +7 -6
  7. package/dist/api.d.ts +21 -3
  8. package/dist/api.js +1479 -372
  9. package/dist/{app-B_7Wn0en.d.ts → app-Cw5Vy6H6.d.ts} +14 -3
  10. package/dist/app.d.ts +2 -2
  11. package/dist/app.js +232 -506
  12. package/dist/{background-compaction-queue-BGHqkhkY.js → background-compaction-queue-CJDnWVOJ.js} +4 -4
  13. package/dist/{briefs-DKxkoruh.js → briefs-BDjnug6Y.js} +3 -3
  14. package/dist/{catalog-runtime-BxwzbLKY.js → catalog-runtime-DMY3VV-D.js} +1 -1
  15. package/dist/cli/chat.js +16 -16
  16. package/dist/cli/check.js +23 -29
  17. package/dist/cli/init.js +1 -6
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +8 -7
  20. package/dist/cli/snapshot-create.js +5 -5
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +3 -3
  23. package/dist/{config-Dkt2Le2b.js → config-BrXDQefC.js} +239 -5
  24. package/dist/{continue-in-slack-BWVwePKD.js → continue-in-slack-DNXSC9So.js} +6 -5
  25. package/dist/{conversation-M9KZ5JxF.js → conversation-ca__NDQW.js} +47 -8
  26. package/dist/{conversation-feed-Ci6YD1N-.js → conversation-feed-DkinDu5o.js} +15 -6
  27. package/dist/{conversation-privacy-C39g8BY4.js → conversation-privacy-DxttrKb9.js} +1 -1
  28. package/dist/{conversation-turn-CBlZIH02.js → conversation-turn-DWw7Xhdr.js} +41 -38
  29. package/dist/{credential-sync-vGnrB0BY.js → credential-sync-Bk8wGb8Y.js} +15 -16
  30. package/dist/{db-B4Hjxr-u.d.ts → db-7ETESH44.d.ts} +3 -1
  31. package/dist/{db-CFZggNoy.js → db-DTxzH7u5.js} +1609 -1040
  32. package/dist/{executor-BPkZDx5-.js → executor-DqTiYj9S.js} +450 -99
  33. package/dist/{html-2r2KmLwi.js → html-B9Sl4Axb.js} +6 -6
  34. package/dist/{install-C-oE6C_u.js → install-Sg4ePfLl.js} +2 -2
  35. package/dist/instrumentation.js +3 -3
  36. package/dist/{lineage-CsvrEFQe.js → lineage-BHAMpNKr.js} +2 -2
  37. package/dist/{logging-D5gkyvnK.js → logging-FjclQsXu.js} +47 -9
  38. package/dist/{message-DwvJ-I3w.js → message-CJ7_RL50.js} +5 -8
  39. package/dist/{model-input-MAq2881y.js → model-input-CMLh4Cwq.js} +3 -3
  40. package/dist/nitro.d.ts +1 -1
  41. package/dist/nitro.js +3 -3
  42. package/dist/{oauth-callback-server-DIF6Li06.js → oauth-callback-server-RVcbiDjL.js} +2 -2
  43. package/dist/{oauth-relay-DPE-wrwO.js → oauth-relay-Bu9kkaQu.js} +1 -1
  44. package/dist/{projection-jZSlEAXG.js → projection-Cns7XwWa.js} +9445 -5574
  45. package/dist/{prompt-CaMyeCpA.js → prompt-CDqcsDYC.js} +4 -4
  46. package/dist/{registry-BBkWFCl8.js → registry-BPwuOP2O.js} +5 -8
  47. package/dist/{resolve-B38MkHXE.js → resolve-BK29bBry.js} +3 -3
  48. package/dist/rule-DAxQY-1h.js +20 -0
  49. package/dist/{runner-11h8PrHh.js → runner-BcAE-cJm.js} +10 -10
  50. package/dist/{sandbox-egress-signals-CTcACAtJ.js → sandbox-egress-signals-C-q0go5b.js} +1 -1
  51. package/dist/{schedule-DWxZ3kja.js → schedule-BLJ476XQ.js} +209 -43
  52. package/dist/{schema-obw5jvR4.js → schema-BLgSZXcL.js} +255 -49
  53. package/dist/{schema-DriSvB40.d.ts → schema-DYcJeV7d.d.ts} +701 -62
  54. package/dist/{service-account-Zc5bUcIJ.js → service-account-gN0zqf0S.js} +68 -68
  55. package/dist/{service-account-Bx93N1n1.js → service-account-iJoCtkHR.js} +3 -3
  56. package/dist/{skills-C8Npu5zO.js → skills-BoZ80epJ.js} +2 -2
  57. package/dist/{slack-conversation-unfurl-DlRVA02H.js → slack-conversation-unfurl-CogYrITA.js} +8 -10
  58. package/dist/{spawn-CXr58R0x.js → spawn-Dk92r7mX.js} +5 -6
  59. package/dist/{state-CGrGVeQC.js → state-DH3Cmgp3.js} +4 -4
  60. package/dist/{stop-DYzjRf2U.js → stop-CYsfc0Ed.js} +1063 -313
  61. package/dist/{store-D4FQ1Nml.js → store-DmmMIrQi.js} +5 -5
  62. package/dist/{task-queue-CaZffYaH.js → task-queue-C_zldF5J.js} +3 -3
  63. package/dist/{task-runner-Dm7BHbGp.js → task-runner-C7oCJQIx.js} +20 -13
  64. package/dist/{thread-context-Dyj1KWaY.js → thread-context-BW2BsQbH.js} +13 -11
  65. package/dist/{turn-session-routing-CD0BRCex.js → turn-session-routing-Xh_2nSQe.js} +52 -54
  66. package/dist/{validation-DxVNIxA0.js → validation-DrJd0nnq.js} +1 -1
  67. package/dist/{version-Cr7Z71yG.js → version-CNKZ8owc.js} +1 -1
  68. package/dist/version.js +1 -1
  69. package/dist/{warmup-C6LOZ2d2.js → warmup-BWdHew2H.js} +14287 -7195
  70. package/dist/{web-message-id-BT8Mg8LL.js → web-message-id-Ch5dPq-a.js} +32 -144
  71. package/dist/{worker-CUBtu1Li.js → worker-t9qpu_Zx.js} +7 -8
  72. package/migrations/0126_artifact_drop_public.sql +8 -0
  73. package/migrations/0127_artifact_path.sql +4 -0
  74. package/migrations/0128_artifact_path_index.sql +1 -0
  75. package/migrations/0129_review_item_answered_index.sql +1 -0
  76. package/migrations/0130_review_item_status_index.sql +1 -0
  77. package/migrations/0131_brief_outcome_status.sql +1 -0
  78. package/migrations/0132_brief_outcome_status_backfill.sql +7 -0
  79. package/migrations/0133_brief_created_at_index.sql +1 -0
  80. package/migrations/0134_slack_person_search_index.sql +1 -0
  81. package/migrations/0135_code_change_size.sql +3 -0
  82. package/migrations/0136_merge_conflict_notice_dismiss.sql +16 -0
  83. package/migrations/0137_inbox_snoozes.sql +27 -0
  84. package/migrations/0138_code_change_search_index.sql +2 -0
  85. package/migrations/0139_review_item_owner.sql +22 -0
  86. package/migrations/0140_review_item_owner_index.sql +1 -0
  87. package/migrations/0141_memory_core_adoption.sql +89 -0
  88. package/migrations/0142_memory_core_indexes.sql +17 -0
  89. package/migrations/meta/0126_snapshot.json +5488 -0
  90. package/migrations/meta/0127_snapshot.json +5519 -0
  91. package/migrations/meta/0128_snapshot.json +5519 -0
  92. package/migrations/meta/0129_snapshot.json +5547 -0
  93. package/migrations/meta/0130_snapshot.json +5563 -0
  94. package/migrations/meta/0131_snapshot.json +5569 -0
  95. package/migrations/meta/0132_snapshot.json +5569 -0
  96. package/migrations/meta/0133_snapshot.json +5590 -0
  97. package/migrations/meta/0134_snapshot.json +5606 -0
  98. package/migrations/meta/0135_snapshot.json +5624 -0
  99. package/migrations/meta/0136_snapshot.json +5624 -0
  100. package/migrations/meta/0137_snapshot.json +5864 -0
  101. package/migrations/meta/0138_snapshot.json +5894 -0
  102. package/migrations/meta/0139_snapshot.json +5898 -0
  103. package/migrations/meta/0140_snapshot.json +5919 -0
  104. package/migrations/meta/0141_snapshot.json +6429 -0
  105. package/migrations/meta/0142_snapshot.json +6457 -0
  106. package/migrations/meta/_journal.json +120 -1
  107. package/package.json +6 -7
  108. package/dist/result-BaqSZcJb.js +0 -548
  109. package/dist/session-stop-BfY4rhJs.js +0 -4255
  110. package/dist/turn-user-message-9IxeEv5v.js +0 -364
  111. package/dist/users-CaUAYMb3.js +0 -181
  112. package/dist/viewer-AHldghAD.js +0 -212
package/dist/app.js CHANGED
@@ -1,46 +1,43 @@
1
- import { $s as readScheduledAutomation, Ai as bindSlackDirectCredentialSubject, An as getPluginRoutes, Ao as resolveRootVisibility, Bn as isBriefsEnabled, Dn as createPluginEventPublisher, Ds as getSlackClient, Ea as normalizeSandboxEgressTracePropagationDomains, Ec as eventAutomationRunLimitReason, Ei as takeDueTimerWatches, Fi as createPluginState, Fn as getPlugins, Go as buildDispatchId, Gr as canActOnReviewItem, Hc as automationVersionOf, Io as createPluginAnnotations, Is as getWorkspaceTeamId, Jo as createOrGetDispatch, Ka as createPluginLogger, Ln as setPlugins, Lo as listConversationAnnotations, Ls as runWithWorkspaceTeamId, Mi as verifyScheduledAutomationCredentialSubject, Mo as backfillConversationEmbeddings, Mt as hasRunnableConversationWork, Ni as verifySlackDirectCredentialSubject, No as createConversationEmbedder, Oi as bindEventAutomationCredentialSubject, Or as projectConversationMessages, Pr as dismissOpenReviewItems, Pt as isInvalidConversationRecordError, Qc as existingConversationId, Qo as getDispatchRecord, Rn as validatePlugins, Rt as pruneActiveConversation, Sa as parseSandboxEgressCredentialToken, Si as findMatchingWatches, Sn as createUserTokenStore, Ss as slackExternalRefIdSchema, T as settleConversationTitleWork, Tc as admitEventAutomationRun, To as requestAttachmentDeletion, Un as setBriefsConfig, Vr as searchReviewItems, Wn as setEventEmbeddingsConfig, Ws as slackMention, Xa as readConversationAccessFromSql, Yo as getDispatchConversationId, Zs as listScheduledAutomationsForTeam, ba as consumeSandboxEgressPermissionDeniedSignal, bl as getConfigDefaults, cc as getDashboardReviewItemLink, cl as refreshAutomationLastRun, cs as notifyAutomationBlocked, dt as CONVERSATION_WORK_STALE_ENQUEUE_MS, es as getPluginDispatchProjection, gc as collectEventAutomationMatchKeys, hc as blockEventAutomation, ic as getDashboardConversationLink, ja as createPluginEmbedder, jc as eventGuidance, ji as verifyEventAutomationCredentialSubject, ki as bindScheduledAutomationCredentialSubject, kn as getPluginApiRoutes, kr as createPluginReviewItems, ks as isDmChannel, li as createCodeChangePublisher, lo as readConversationLastEventSeq, mc as setDashboardConversationLinkOptions, ml as createPluginCache, ms as postSlackEphemeralMessage, na as proxyVercelSandboxEgressRequest, nc as scheduledRunId, ni as reviewItemReaderForUserInConversation, ns as listPendingDispatchMailboxAppends, oa as resolveBaseUrl, oo as readConversationEventPage, os as markDispatchFailed, ps as openSlackModal, qo as confirmDispatchMailboxAppend, rc as withScheduledAutomationLock, sl as recordAutomationExecution, so as readConversationEventPageAfter, ta as isVercelSandboxEgressRequest, tc as saveScheduledAutomationInLock, ti as reviewItemReaderForUser, ts as isTerminalDispatchStatus, uc as getDashboardTaskLink, uo as readConversationMessageEventSeq, va as clearSandboxEgressSignals, vi as collectEventMatchKeys, xl as setConfigDefaults, xo as collectAttachmentGarbage, xs as slackEntitySchema, y as appendConversationMessages, ya as consumeSandboxEgressAuthRequiredSignal, yc as findMatchingEventAutomations } from "./projection-jZSlEAXG.js";
2
- import { d as restoreRuntimeConfig, f as setBotModelConfig, g as snapshotRuntimeConfig, h as setSlackReactionConfig, i as getChatConfig, m as setRuntimeLimits, n as botConfig, ot as getAttachmentStorage, p as setBotName, u as resetRuntimeConfig } from "./config-Dkt2Le2b.js";
3
- import { $ as disconnectStateAdapter, C as withConversationMutationLock, Dt as touchConversationDetail, K as recordGoogleSignIn, L as resolveActorIdentityId, Ot as createSlackDestination, a as getConversationStore, dt as conversationCostOf, it as MUTATION_LOCK_TTL_MS, m as withConversationEventLock, o as getDb, ot as fenceLock, p as deleteMessageLinks, r as getConversationEventStore, s as getSqlExecutor, st as withLock, t as closeDb, tt as getStateAdapter } from "./db-CFZggNoy.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-D5gkyvnK.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-D9cvNlQl.js";
6
- import { E as getAuthPausedConversationTurnId, G as isAllowedDomain, J as resolveEventAuthor, K as isTrustedSlackAuthor, Q as renderTaskInput, U as eventAuthorText, W as findTrustedUser, X as resolveBotSlackTeamId, Y as setTrustConfig, at as annotationKeyDigest, b as deletePlanItems, bt as slackChannelMessageRunsAutomation, ft as getExperimentalFeatures, gt as SLACK_EVENT_NAMESPACE, ht as getEventCatalog, it as renderSlackObjectCard, mt as setExperimentalFeatures, ot as decodeAnnotationRef, pt as isExperimentalFeatureEnabled, q as parseEmail, vt as slackChannelMessageEvent, yt as slackChannelMessageReplyThreadTs } from "./session-stop-BfY4rhJs.js";
7
- import { a as getSandboxResourceConfig, s as setSandboxResourceConfig } from "./install-C-oE6C_u.js";
8
- import { n as pluginCatalogRuntime } from "./catalog-runtime-BxwzbLKY.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-DYzjRf2U.js";
10
- import { n as validatePluginRegistrations, t as validatePluginEgressCredentialHooks } from "./validation-DxVNIxA0.js";
1
+ import { $i as consumeSandboxEgressAuthRequiredSignal, $n as setMemoryConfig, $s as automationVersionOf, An as getPluginApiRoutes, Bi as resolveBaseUrl, Bn as validatePlugins, Cn as createUserTokenStore, Co as getDispatchRecord, Dl as setConfigDefaults, Do as listPendingDispatchMailboxAppends, Ds as scheduledRunId, Ec as dismissOpenReviewItems, El as getConfigDefaults, Eo as isTerminalDispatchStatus, Es as saveScheduledAutomationInLock, Fa as readConversationLastEventSeq, Fi as isVercelSandboxEgressRequest, Fs as getDashboardTaskLink, Ia as readConversationMessageEventSeq, Ii as proxyVercelSandboxEgressRequest, Ir as setBriefsConfig, Jc as SLACK_EVENT_NAMESPACE, Ka as collectAttachmentGarbage, Ko as slackEntitySchema, Ln as getRegistrations, Lr as setEventEmbeddingsConfig, Ma as readConversationEventPage, Mt as hasRunnableConversationWork, Na as readConversationEventPageAfter, No as notifyAutomationBlocked, Nr as isBriefsEnabled, Ns as getDashboardReviewItemLink, On as createPluginEventPublisher, Os as withScheduledAutomationLock, Pc as searchReviewItems, Pr as isEventEmbeddingsEnabled, Pt as isInvalidConversationRecordError, Qi as clearSandboxEgressSignals, Qn as projectConversationMessages, Qo as getSlackClient, Ro as openSlackModal, Rt as pruneActiveConversation, Ss as listScheduledAutomationsForTeam, T as settleConversationTitleWork, Xa as requestAttachmentDeletion, Xc as slackChannelMessageEvent, _c as refreshAutomationLastRun, ai as takeDueTimerWatches, bc as syncAutomationAlerts, bo as getDispatchConversationId, co as listConversationAnnotations, cr as SEARCHABLE_EVENT_TYPES, cs as runWithWorkspaceTeamId, dt as CONVERSATION_WORK_STALE_ENQUEUE_MS, ea as consumeSandboxEgressPermissionDeniedSignal, hs as slackMention, io as createConversationEmbedder, jn as getPluginRoutes, jo as markDispatchFailed, ks as getDashboardConversationLink, na as parseSandboxEgressCredentialToken, nr as embedConversationEvents, oa as normalizeSandboxEgressTracePropagationDomains, qo as slackExternalRefIdSchema, ro as backfillConversationEmbeddings, rr as eventIndexLockKey, sc as existingConversationId, sr as storeConversationEventLexemes, ss as getWorkspaceTeamId, to as resolveRootVisibility, tr as EVENT_INDEX_LOCK_TTL_MS, vo as confirmDispatchMailboxAppend, ws as readScheduledAutomation, y as appendConversationMessages, zc as deleteExpiredInboxSnoozes, zn as setPlugins, zo as postSlackEphemeralMessage, zs as setDashboardConversationLinkOptions } from "./projection-Cns7XwWa.js";
2
+ import { B as withLock, L as MUTATION_LOCK_TTL_MS, _t as getAttachmentStorage, 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, z as fenceLock } from "./config-BrXDQefC.js";
3
+ import { Ct as reviewItemReaderForUser, Nn as touchConversationDetail, Pn as createSlackDestination, Pt as readActorIdentity, V as conversationCostOf, Wt as parseAvatarUrl, Xt as resolveActorIdentityId, a as getConversationStore, an as recordGoogleSignIn, hn as readConversationAccessFromSql, it as canActOnReviewItem, m as withConversationEventLock, o as getDb, p as deleteMessageLinks, r as getConversationEventStore, s as getSqlExecutor, t as closeDb, ut as isPluginReviewItem, w as withConversationMutationLock, wt as reviewItemReaderForUserInConversation, zt as resolveViewerUser } from "./db-DTxzH7u5.js";
4
+ import { A as JUNIOR_CONTEXT_COMPACTION_CALLBACK_ROUTE, E as withSpan, J as normalizeIdentityEmail, K as GOOGLE_IDENTITY_PROVIDER, L as JUNIOR_WORKSPACE_SNAPSHOT_JOB_CALLBACK_ROUTE, O as JUNIOR_AUTO_ARCHIVE_ROUTE, P as JUNIOR_PLUGIN_TASK_CALLBACK_ROUTE, T as withLogContext, 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-FjclQsXu.js";
5
+ import { O as resumeConversationDelivery, S as parseSlackReviewItemFormTarget, _ as syncReviewItemSlackCards, b as buildSlackReviewItemModal, d as unpublishedArtifactHeaders, g as resolveSlackReviewItemCardConversationId, h as createSlackReviewItemShow, l as publicArtifactHeaders, m as scheduledAutomationRunAttributes, n as executeAgentRun, p as logScheduledAutomationRunSkipped, t as createAgentRunner, u as readPublicArtifact, v as findSlackThreadOwnerId, w as parseSlackUserInputSubmission, x as parseSlackReviewItemClick } from "./agent-runner-BVHPUIc8.js";
6
+ import { $a as automationCardStatus, $n as listPendingAgentInvocationMailboxAppends, At as renderReviewItemMessage, Cn as decodeAnnotationRef, Dn as enqueueAgentInvocationResult, En as createEndStoppedChildWork, Ft as createAndEnqueueConversation, Ha as ViewerTaskNotFoundError, I as processWorkspaceSnapshotJob, Ii as parseSlackThreadId, In as enqueueAgentInvocation, Ja as readViewerAutomations, Ji as joinPublicChannel, Ka as readViewerAutomationSummary, Kn as recordSubagentEnded, Lt as recordWebConversationActivity, Nt as appendAndEnqueueWebMessage, Pt as conversationTurnIdForMessage, Rt as webActorFromUser, Sn as annotationKeyDigest, St as archiveConversation, Vt as collectAttachmentUploadGarbage, Wa as readViewerAutomationExecutions, Xt as getAuthPausedConversationTurnId, aa as getExperimentalFeatures, ai as renderTaskInput, ao as effectiveTaskOutcomes, bi as setConversationSubscription, ci as deletePlanItems, cn as findTrustedUser, dn as parseEmail, er as listPendingAgentInvocationResults, f as processBackgroundCompaction, io as missingAutomationSkillReason, jt as reviewItemChangeRecord, kt as deliverReviewItemChange, ln as isAllowedDomain, oa as isExperimentalFeatureEnabled, pn as setTrustConfig, ro as findAutomationSkill, sa as setExperimentalFeatures, un as isTrustedSlackAuthor, wt as markConversationRead, xn as renderSlackObjectCard, z as ingestEvent } from "./warmup-BWdHew2H.js";
7
+ import { a as getSandboxResourceConfig, s as setSandboxResourceConfig } from "./install-Sg4ePfLl.js";
8
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-DMY3VV-D.js";
9
+ import { $ as GET$4, A as actOnReviewItem, C as encodeConversationCursor, Ct as bindMessageAuthorIdentityId, Dt as SubscribedReplyReason, Et as parseContent, F as ingestEventAutomations, G as dispatchScheduledAutomation, H as automationReplyAttribution, I as archiveViewerDoneConversations, K as getScheduledAutomationDispatch, L as runAutoArchiveSweep, M as readReviewItemForUser, N as reviewItemChange, O as stopConversation, Ot as getThreadStopDecision, P as createEventAppPublisher, Q as backfillCacheWarmingGaps, R as setConversationAutoArchive, S as decodeConversationCursor, St as createSlackWebApiStatusSender, T as readConversationPendingMessages, Tt as stripLeadingBotMention, U as settleEventAutomationRuns, W as createHeartbeatContext, X as runSavingsRefillSlice, _t as withNormalizedThreadId, b as createConversationForViewer, bt as failStoppedDispatch, c as pinConversation, ct as isPublicAddress, dt as createProductionSlackWebhookServices, ft as getProductionSlackAdapter, gt as normalizeIncomingSlackThreadId, ht as slackInboundMessageId, i as readConversationFeed, j as closeReviewItemsAnsweredByReply, jt as readConversationRecordFromSql, k as ReviewItemActionError, lt as publicAddressLookup, mt as clearSlackPendingReactions, n as steerConversationPendingMessagesForViewer, pt as buildSlackInboundMessage, q as runInboxSnoozeTimers, rt as readObjectLinkTypes, t as stopConversationTurnForViewer, u as readConversationDetail, ut as createProductionConversationWorkOptions, w as cancelConversationPendingMessagesForViewer, wt as startProcessingReaction, xt as recordSkippedConversationMessage, y as appendConversationMessageForViewer, yt as enqueueAgentDispatch } from "./stop-CYsfc0Ed.js";
10
+ import { n as validatePluginRegistrations, t as validatePluginEgressCredentialHooks } from "./validation-DrJd0nnq.js";
11
11
  import { a as pluginRuntimeRegistrationsFromPluginSet, n as pluginCatalogConfigFromEnv, r as pluginCatalogConfigFromPluginSet, t as defineJuniorPlugins } from "./plugins-Bkk0XRo2.js";
12
- import { A as ingestEvent, Ct as createAndEnqueueConversation, D as processWorkspaceSnapshotJob, Ei as effectiveTaskOutcomes, Et as webActorFromUser, Gn as setConversationSubscription, Jt as listPendingAgentInvocationResults, St as conversationTurnIdForMessage, Ti as missingAutomationSkillReason, Tt as recordWebConversationActivity, _t as deliverReviewItemChange, bi as automationCardStatus, di as readViewerAutomationExecutions, dn as enqueueAgentInvocation, ft as markConversationRead, hi as readViewerAutomations, kt as collectAttachmentUploadGarbage, li as ViewerTaskNotFoundError, pi as readViewerAutomationSummary, qt as listPendingAgentInvocationMailboxAppends, sr as parseSlackThreadId, ut as archiveConversation, vn as recordSubagentEnded, vt as renderReviewItemMessage, wi as findAutomationSkill, xt as appendAndEnqueueWebMessage, yr as joinPublicChannel, yt as reviewItemChangeRecord } from "./warmup-C6LOZ2d2.js";
13
- import { _ as getConversationWorkState, g as getConversation, h as ensureConversationWake, l as clearExpiredConversationLease, r as appendAndEnqueueInboundMessage, y as listActiveConversationIds } from "./store-D4FQ1Nml.js";
12
+ import { i as getStateAdapter, n as disconnectStateAdapter } from "./adapter-B1wujchl.js";
13
+ import { E as juniorConversationEventEmbeddings, H as juniorConversations, M as juniorConversationEvents, O as juniorConversationBriefs, T as juniorConversationEventLexemes, _ as juniorAutomationRuns, b as juniorAgentBindings, g as juniorAutomations, h as juniorReviewItems, q as juniorDestinations, x as juniorAgentInvocations } from "./executor-DqTiYj9S.js";
14
+ import { _ as getConversationWorkState, g as getConversation, h as ensureConversationWake, l as clearExpiredConversationLease, r as appendAndEnqueueInboundMessage, y as listActiveConversationIds } from "./store-DmmMIrQi.js";
14
15
  import { t as mapBounded } from "./fan-out-Cod-yEHG.js";
15
- import { G as getNextRunAtMs, Q as automationTaskText, R as scheduledRunSchema, Z as automationTaskSchema, m as automationListQuerySchema, u as automationExecutionStatusSchema } from "./schedule-DWxZ3kja.js";
16
- 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-BPkZDx5-.js";
17
- 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-BGHqkhkY.js";
18
- import { i as enqueueAgentInvocationResult, r as createEndStoppedChildWork } from "./result-BaqSZcJb.js";
19
- 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-CaZffYaH.js";
20
- import { a as GET$5, i as publishAppHomeView, r as GET$6, t as receiveLocalOAuthCredential } from "./credential-sync-vGnrB0BY.js";
16
+ import { I as scheduledRunSchema, Q as buttonUserInputField, U as getNextRunAtMs, m as automationListQuerySchema, ot as automationTaskSchema, st as automationTaskText, u as automationExecutionStatusSchema } from "./schedule-BLJ476XQ.js";
17
+ 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-CJDnWVOJ.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-C_zldF5J.js";
19
+ import { i as getActiveSpan, u as sentry_exports } from "./sentry-CPbZjomA.js";
20
+ import { a as GET$5, i as publishAppHomeView, r as GET$6, t as receiveLocalOAuthCredential } from "./credential-sync-Bk8wGb8Y.js";
21
21
  import { t as nameRequestRoute } from "./sentry-route-name-C6EIzAGP.js";
22
22
  import { t as SANDBOX_EGRESS_PROXY_PATH } from "./proxy-path-BHYoKZdq.js";
23
- import { B as conversationTitleSchema, G as annotationCard, I as conversationBriefSchema, b as conversationSurfaceSchema, v as conversationReportStatusSchema } from "./conversation-M9KZ5JxF.js";
24
- import { i as readActorIdentity, l as resolveViewerUser, p as parseAvatarUrl } from "./viewer-AHldghAD.js";
23
+ import { B as conversationTreeStateSchema, H as conversationTitleSchema, L as conversationBriefSchema, b as conversationSurfaceSchema, q as annotationCard, v as conversationReportStatusSchema } from "./conversation-ca__NDQW.js";
25
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-BsBdxDXQ.js";
26
- 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-DlRVA02H.js";
27
- import { l as unlinkProvider, n as renderHtmlPage, r as requestHasSameOrigin, t as escapeHtml } from "./html-2r2KmLwi.js";
28
- import { s as buttonUserInputField } from "./web-message-id-BT8Mg8LL.js";
29
- import { n as verifySlackSignature, t as runWithSlackInstallation } from "./adapter-context-BhKpjpGD.js";
30
- import { c as coerceThreadConversationState } from "./turn-session-routing-CD0BRCex.js";
31
- import { i as getActiveSpan, n as captureMessage, u as sentry_exports } from "./sentry-CPbZjomA.js";
32
- import { t as processConversationWork } from "./worker-CUBtu1Li.js";
33
- import { t as bindMessageAgent } from "./message-DwvJ-I3w.js";
34
- import { t as bindSpawnAgent } from "./spawn-CXr58R0x.js";
35
- import { t as processPluginTask } from "./task-runner-Dm7BHbGp.js";
36
- import { t as JUNIOR_VERSION } from "./version-Cr7Z71yG.js";
37
- import { c as conversationPendingMessageDeliverySchema, n as conversationFeedQuerySchema } from "./conversation-feed-Ci6YD1N-.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-CogYrITA.js";
26
+ import { l as unlinkProvider, n as renderHtmlPage, r as requestHasSameOrigin, t as escapeHtml } from "./html-B9Sl4Axb.js";
27
+ import { n as verifySlackSignature, t as runWithSlackInstallation } from "./adapter-context-G2M0y6rP.js";
28
+ import { c as coerceThreadConversationState } from "./turn-session-routing-Xh_2nSQe.js";
29
+ import { t as processConversationWork } from "./worker-t9qpu_Zx.js";
30
+ import { t as bindMessageAgent } from "./message-CJ7_RL50.js";
31
+ import { t as bindSpawnAgent } from "./spawn-Dk92r7mX.js";
32
+ import { t as processPluginTask } from "./task-runner-C7oCJQIx.js";
33
+ import { t as JUNIOR_VERSION } from "./version-CNKZ8owc.js";
34
+ import { c as conversationPendingMessageDeliverySchema, n as conversationFeedQuerySchema } from "./conversation-feed-DkinDu5o.js";
38
35
  import { createRequire } from "node:module";
39
36
  import { Hono } from "hono";
40
37
  import * as z from "zod";
41
38
  import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
42
- import { EVENT_SUMMARY_MAX_LENGTH, EVENT_TEXT_MAX_LENGTH, dispatchOptionsSchema, eventSchema as eventSchema$1, eventTriggerFiltersText, identityDispatchOptionsSchema, isSlackDestination, userSchema } from "@sentry/junior-plugin-api";
43
- import { and, asc, eq, inArray, isNotNull, isNull, lte, ne, or, sql } from "drizzle-orm";
39
+ import { eventTriggerFiltersText, identityDispatchOptionsSchema, userSchema } from "@sentry/junior-plugin-api";
40
+ import { and, asc, desc, eq, gte, inArray, isNotNull, isNull, lte, ne, or, sql } from "drizzle-orm";
44
41
  import { pathToFileURL } from "node:url";
45
42
  import { Message, ThreadImpl } from "chat";
46
43
  import net from "node:net";
@@ -55,27 +52,130 @@ import { createAuthMiddleware } from "better-auth/api";
55
52
  import { getSessionCookie } from "better-auth/cookies";
56
53
  import { betterAuth } from "better-auth/minimal";
57
54
  // 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;
55
+ const BACKFILL_BUDGET_MS$1 = 1e4;
56
+ const BACKFILL_CLAIM_TTL_MS$1 = 6e4;
57
+ const BACKFILL_DONE_TTL_MS$1 = 36e5;
61
58
  /** Embed the latest Briefs that have no vector of the embedder's model. */
62
59
  async function runConversationEmbeddingBackfill(embedder) {
63
60
  const key = `junior:conversation_embeddings:backfill:${embedder.provider}:${embedder.model}`;
64
61
  const state = getStateAdapter();
65
- if (!await state.setIfNotExists(key, "running", BACKFILL_CLAIM_TTL_MS)) return;
62
+ if (!await state.setIfNotExists(key, "running", BACKFILL_CLAIM_TTL_MS$1)) return;
66
63
  await withSpan("conversation_embeddings.backfill", "conversation_embeddings.backfill", {}, async (setSpanAttributes) => {
67
64
  const result = await backfillConversationEmbeddings({
68
65
  db: getDb(),
69
- deadlineMs: Date.now() + BACKFILL_BUDGET_MS,
66
+ deadlineMs: Date.now() + BACKFILL_BUDGET_MS$1,
70
67
  embedder
71
68
  });
72
- if (result.done) await state.set(key, "done", BACKFILL_DONE_TTL_MS);
69
+ if (result.done) await state.set(key, "done", BACKFILL_DONE_TTL_MS$1);
73
70
  setSpanAttributes({
74
71
  "app.conversation_embeddings.backfill.embedded.count": result.embedded,
75
72
  "app.conversation_embeddings.backfill.outcome": result.done ? "completed" : "budget_exceeded"
76
73
  });
77
74
  });
78
75
  }
76
+ // src/chat/conversations/event-search-backfill.ts
77
+ const ACTIVE_WINDOW_MS = 6048e5;
78
+ const BACKFILL_BUDGET_MS = 1e4;
79
+ const BACKFILL_CLAIM_TTL_MS = 6e4;
80
+ const BACKFILL_DONE_TTL_MS = 6e5;
81
+ const MAX_LEXEME_EVENTS_PER_RUN = 1e3;
82
+ const MAX_VECTOR_EVENTS_PER_RUN = 256;
83
+ const MAX_BACKLOG_CONVERSATIONS = 200;
84
+ /**
85
+ * Conversations with recent activity that have searchable events without
86
+ * lexemes, or without a vector of the embedder's model, most recent first.
87
+ */
88
+ async function listConversationBacklogs(db, args) {
89
+ const events = juniorConversationEvents;
90
+ const lexemes = juniorConversationEventLexemes;
91
+ const vectors = juniorConversationEventEmbeddings;
92
+ const conversations = juniorConversations;
93
+ const missingLexemes = sql`count(*) filter (where ${lexemes.seq} is null)`;
94
+ const missingVectors = args.embedder ? sql`count(*) filter (where ${vectors.seq} is null and (${lexemes.seq} is null or length(${lexemes.lexemes}) > 0))` : sql`0`;
95
+ const query = db.select({
96
+ conversationId: events.conversationId,
97
+ lexemes: missingLexemes.mapWith(Number),
98
+ vectors: missingVectors.mapWith(Number)
99
+ }).from(events).innerJoin(conversations, eq(conversations.conversationId, events.conversationId)).leftJoin(lexemes, and(eq(lexemes.conversationId, events.conversationId), eq(lexemes.seq, events.seq))).$dynamic();
100
+ const embedder = args.embedder;
101
+ return await (embedder ? query.leftJoin(vectors, and(eq(vectors.conversationId, events.conversationId), eq(vectors.seq, events.seq), eq(vectors.provider, embedder.provider), eq(vectors.model, embedder.model))) : query).where(and(gte(conversations.lastActivityAt, new Date(args.sinceMs)), inArray(events.type, [...SEARCHABLE_EVENT_TYPES]))).groupBy(events.conversationId, conversations.lastActivityAt).having(sql`${missingLexemes} > 0 or ${missingVectors} > 0`).orderBy(desc(conversations.lastActivityAt), events.conversationId).limit(MAX_BACKLOG_CONVERSATIONS);
102
+ }
103
+ /**
104
+ * Store missing lexemes, and missing vectors when `embedder` is set, of the
105
+ * Conversations with activity in the last week. Return what it stored and
106
+ * whether it indexed the whole backlog.
107
+ */
108
+ async function backfillEventSearchIndex(args) {
109
+ const backlogs = await listConversationBacklogs(args.db, {
110
+ ...args.embedder ? { embedder: args.embedder } : void 0,
111
+ sinceMs: args.nowMs - ACTIVE_WINDOW_MS
112
+ });
113
+ const state = getStateAdapter();
114
+ const stored = {
115
+ lexemes: 0,
116
+ vectors: 0
117
+ };
118
+ let done = backlogs.length < MAX_BACKLOG_CONVERSATIONS;
119
+ for (const backlog of backlogs) {
120
+ const lexemeRoom = MAX_LEXEME_EVENTS_PER_RUN - stored.lexemes;
121
+ const vectorRoom = args.embedder ? MAX_VECTOR_EVENTS_PER_RUN - stored.vectors : 0;
122
+ if (Date.now() >= args.deadlineMs || backlog.lexemes > 0 && lexemeRoom <= 0 || backlog.vectors > 0 && vectorRoom <= 0) {
123
+ done = false;
124
+ break;
125
+ }
126
+ const attempt = await withLock(state, eventIndexLockKey(backlog.conversationId), async () => {
127
+ return {
128
+ lexemes: backlog.lexemes > 0 ? await storeConversationEventLexemes(args.db, backlog.conversationId, lexemeRoom) : 0,
129
+ vectors: args.embedder && backlog.vectors > 0 ? await embedConversationEvents(args.db, args.embedder, backlog.conversationId, {
130
+ deadlineMs: args.deadlineMs,
131
+ maxEvents: vectorRoom
132
+ }) : 0
133
+ };
134
+ }, { ttlMs: EVENT_INDEX_LOCK_TTL_MS });
135
+ if (!attempt.acquired) {
136
+ done = false;
137
+ continue;
138
+ }
139
+ stored.lexemes += attempt.value.lexemes;
140
+ stored.vectors += attempt.value.vectors;
141
+ if (attempt.value.lexemes < backlog.lexemes || attempt.value.vectors < backlog.vectors) done = false;
142
+ }
143
+ return {
144
+ backlog: {
145
+ conversations: backlogs.length,
146
+ lexemes: backlogs.reduce((sum, backlog) => sum + backlog.lexemes, 0),
147
+ vectors: backlogs.reduce((sum, backlog) => sum + backlog.vectors, 0)
148
+ },
149
+ done,
150
+ stored
151
+ };
152
+ }
153
+ /**
154
+ * Index the backlog of event search in recently active Conversations.
155
+ * Vectors only when `embedder` is set.
156
+ */
157
+ async function runEventSearchBackfill(args) {
158
+ const key = `junior:event_search:backfill:${args.embedder ? `${args.embedder.provider}:${args.embedder.model}` : "lexemes"}`;
159
+ const state = getStateAdapter();
160
+ if (!await state.setIfNotExists(key, "running", BACKFILL_CLAIM_TTL_MS)) return;
161
+ await withSpan("event_search.backfill", "event_search.backfill", {}, async (setSpanAttributes) => {
162
+ const result = await backfillEventSearchIndex({
163
+ db: getDb(),
164
+ deadlineMs: Date.now() + BACKFILL_BUDGET_MS,
165
+ ...args.embedder ? { embedder: args.embedder } : void 0,
166
+ nowMs: args.nowMs
167
+ });
168
+ if (result.done) await state.set(key, "done", BACKFILL_DONE_TTL_MS);
169
+ setSpanAttributes({
170
+ "app.event_search.backfill.backlog.conversation.count": result.backlog.conversations,
171
+ "app.event_search.backfill.backlog.lexeme.count": result.backlog.lexemes,
172
+ "app.event_search.backfill.backlog.vector.count": result.backlog.vectors,
173
+ "app.event_search.backfill.lexeme.count": result.stored.lexemes,
174
+ "app.event_search.backfill.vector.count": result.stored.vectors,
175
+ "app.event_search.backfill.outcome": result.done ? "completed" : "limit_reached"
176
+ });
177
+ });
178
+ }
79
179
  // src/chat/events/timers.ts
80
180
  /** Publish a bounded batch of due timers; the mailbox owns agent execution. */
81
181
  async function runTimerWatchHeartbeat(args) {
@@ -188,266 +288,6 @@ async function recoverConversationWork(args) {
188
288
  });
189
289
  return result;
190
290
  }
191
- // src/chat/agent-dispatch/validation.ts
192
- function hasIssueAtPath(issues, path) {
193
- return issues.some((issue) => issue.path.length === path.length && issue.path.every((value, index) => value === path[index]));
194
- }
195
- function hasIssueUnderPath(issues, path) {
196
- return issues.some((issue) => path.every((value, index) => issue.path[index] === value));
197
- }
198
- function dispatchOptionsErrorMessage(issues) {
199
- if (hasIssueAtPath(issues, [])) return issues.some((issue) => issue.code === "unrecognized_keys") ? "Dispatch options must not include unknown fields" : "Dispatch options are required";
200
- if (issues.some((issue) => issue.code === "unrecognized_keys" && issue.path[0] === "destination")) return "Dispatch destination must not include unknown fields";
201
- if (issues.some((issue) => issue.code === "unrecognized_keys" && issue.path[0] === "credentialSubject")) return "Dispatch credentialSubject binding is runtime-owned";
202
- if (hasIssueAtPath(issues, ["destination"])) return "Dispatch destination platform must be slack";
203
- if (hasIssueUnderPath(issues, ["destination", "teamId"])) return "Dispatch destination teamId must be a Slack team id";
204
- if (hasIssueUnderPath(issues, ["destination", "channelId"])) return "Dispatch destination channelId must be a Slack channel id";
205
- if (hasIssueUnderPath(issues, ["idempotencyKey"])) return issues.some((issue) => issue.path[0] === "idempotencyKey" && issue.code === "too_big") ? "Dispatch idempotencyKey exceeds the maximum length" : "Dispatch idempotencyKey is required";
206
- if (hasIssueUnderPath(issues, ["input"])) return issues.some((issue) => issue.path[0] === "input" && issue.code === "too_big") ? "Dispatch input exceeds the maximum length" : "Dispatch input is required";
207
- if (hasIssueUnderPath(issues, ["credentialSubject", "userId"])) return "Dispatch credentialSubject userId is required";
208
- if (hasIssueUnderPath(issues, ["credentialSubject", "allowedWhen"])) return "Dispatch credentialSubject allowedWhen is invalid";
209
- if (hasIssueUnderPath(issues, ["credentialSubject"])) return "Dispatch credentialSubject type must be user";
210
- const metadataIssue = issues.find((issue) => issue.path[0] === "metadata" && (issue.message === "Dispatch metadata has too many keys" || issue.message === "Dispatch metadata keys must be single-line strings" || issue.message === "Dispatch metadata values must be single-line strings" || issue.message === "Dispatch metadata key exceeds the maximum length" || issue.message === "Dispatch metadata value exceeds the maximum length"));
211
- if (metadataIssue) return metadataIssue.message;
212
- if (hasIssueUnderPath(issues, ["metadata"])) return "Dispatch metadata values must be strings";
213
- if (hasIssueUnderPath(issues, ["replyAttribution"])) return "Dispatch reply attribution is invalid";
214
- return "Dispatch options are invalid";
215
- }
216
- /** Validate plugin-provided dispatch options before core persists them. */
217
- function validateDispatchOptions(options) {
218
- const parsed = dispatchOptionsSchema.safeParse(options);
219
- if (!parsed.success) throw new Error(dispatchOptionsErrorMessage(parsed.error.issues));
220
- const { credentialSubject, destination } = parsed.data;
221
- if (!isSlackDestination(destination)) throw new Error("Dispatch destination platform must be slack");
222
- if (credentialSubject !== void 0) {
223
- if (credentialSubject.allowedWhen === "private-direct-conversation" && !isDmChannel(destination.channelId)) throw new Error("Dispatch credentialSubject requires a private direct Slack destination");
224
- }
225
- }
226
- /** Verify runtime-owned access requirements for delegated dispatch credentials. */
227
- async function verifyDispatchCredentialSubjectAccess(options, plugin) {
228
- if (!options.credentialSubject) return;
229
- if (!(options.credentialSubject.allowedWhen === "scheduled-automation" ? verifyScheduledAutomationCredentialSubject({
230
- plugin,
231
- subject: options.credentialSubject
232
- }) : options.credentialSubject.allowedWhen === "event-automation" ? verifyEventAutomationCredentialSubject({
233
- plugin,
234
- subject: options.credentialSubject
235
- }) : verifySlackDirectCredentialSubject({
236
- channelId: options.destination.channelId,
237
- teamId: options.destination.teamId,
238
- subject: options.credentialSubject
239
- }))) throw new Error("Dispatch credentialSubject is not valid for this action");
240
- }
241
- // src/chat/agent-dispatch/context.ts
242
- const MAX_DISPATCHES_PER_HEARTBEAT = 25;
243
- function bindDispatchCredentialSubject(options, plugin) {
244
- const { credentialSubject, ...baseOptions } = options;
245
- if (!credentialSubject) return {
246
- ...baseOptions,
247
- source: { kind: "plugin_dispatch" }
248
- };
249
- if ("binding" in credentialSubject) throw new Error("Dispatch credentialSubject binding is runtime-owned");
250
- const boundSubject = credentialSubject.allowedWhen === "scheduled-automation" ? bindScheduledAutomationCredentialSubject({
251
- plugin,
252
- subject: credentialSubject
253
- }) : bindSlackDirectCredentialSubject({
254
- channelId: options.destination.channelId,
255
- teamId: options.destination.teamId,
256
- subject: credentialSubject
257
- });
258
- if (!boundSubject) throw new Error("Dispatch credentialSubject is not valid for this action");
259
- return {
260
- ...baseOptions,
261
- credentialSubject: boundSubject,
262
- source: { kind: "plugin_dispatch" }
263
- };
264
- }
265
- /** Verify, persist, and enqueue one idempotent agent dispatch. */
266
- async function dispatch(args) {
267
- await verifyDispatchCredentialSubjectAccess(args.options, args.plugin);
268
- const result = await createOrGetDispatch({
269
- plugin: args.plugin,
270
- options: args.options,
271
- nowMs: args.nowMs
272
- });
273
- if (!isTerminalDispatchStatus(result.record.status)) await enqueueAgentDispatch(result.record, {
274
- queue: args.conversationWorkQueue,
275
- nowMs: args.nowMs
276
- });
277
- return {
278
- id: result.record.id,
279
- status: result.status
280
- };
281
- }
282
- /** Build the plugin-scoped heartbeat context that gates durable dispatch access. */
283
- function createHeartbeatContext(args) {
284
- const pluginName = typeof args.plugin === "string" ? args.plugin : args.plugin.manifest.name;
285
- let dispatchCount = 0;
286
- const assertDispatchBudget = () => {
287
- if (dispatchCount >= MAX_DISPATCHES_PER_HEARTBEAT) throw new Error("Plugin heartbeat exceeded the dispatch limit");
288
- };
289
- return {
290
- plugin: { name: pluginName },
291
- annotations: { forConversation: (conversationId) => createPluginAnnotations({
292
- conversationId,
293
- db: getDb(),
294
- plugin: pluginName
295
- }) },
296
- cache: createPluginCache(pluginName),
297
- codeChanges: createCodeChangePublisher(pluginName),
298
- nowMs: args.nowMs,
299
- db: getDb(),
300
- embedder: createPluginEmbedder(pluginName),
301
- events: args.events,
302
- reviewItems: { forConversation: (conversationId) => createPluginReviewItems({
303
- conversationId,
304
- plugin: pluginName,
305
- show: args.showReviewItem ?? (async () => {})
306
- }) },
307
- state: createPluginState(pluginName),
308
- log: createPluginLogger(pluginName),
309
- agent: {
310
- async dispatch(options) {
311
- validateDispatchOptions(options);
312
- const dispatchOptions = bindDispatchCredentialSubject(options, pluginName);
313
- assertDispatchBudget();
314
- const result = await dispatch({
315
- conversationWorkQueue: args.conversationWorkQueue,
316
- nowMs: args.nowMs,
317
- options: dispatchOptions,
318
- plugin: pluginName
319
- });
320
- dispatchCount += 1;
321
- return result;
322
- },
323
- async dispatchForIdentity(options) {
324
- assertDispatchBudget();
325
- dispatchCount += 1;
326
- return await args.dispatchForIdentity(pluginName, options);
327
- },
328
- async get(id) {
329
- return await getPluginDispatchProjection({
330
- plugin: pluginName,
331
- id
332
- });
333
- }
334
- }
335
- };
336
- }
337
- /** Create and enqueue one core-owned event automation dispatch. */
338
- async function dispatchEventAutomation(args) {
339
- const plugin = "junior";
340
- const { credentialSubject, outcomes, skill, ...unboundOptions } = args.options;
341
- validateDispatchOptions({ ...unboundOptions });
342
- const boundSubject = credentialSubject ? bindEventAutomationCredentialSubject({
343
- plugin,
344
- subject: credentialSubject
345
- }) : void 0;
346
- if (credentialSubject && !boundSubject) throw new Error("Dispatch credentialSubject is not valid for this action");
347
- const options = {
348
- ...unboundOptions,
349
- ...outcomes !== void 0 ? { outcomes } : void 0,
350
- ...skill ? { skill } : void 0,
351
- ...boundSubject ? { credentialSubject: boundSubject } : void 0,
352
- source: {
353
- kind: "event_automation",
354
- automationId: args.automationId,
355
- automationRunId: buildDispatchId(plugin, unboundOptions.idempotencyKey)
356
- }
357
- };
358
- return await dispatch({
359
- conversationWorkQueue: args.conversationWorkQueue,
360
- nowMs: args.nowMs,
361
- options,
362
- plugin
363
- });
364
- }
365
- /** Create and enqueue one core-owned scheduled automation dispatch. */
366
- async function dispatchScheduledAutomation(args) {
367
- const plugin = "scheduler";
368
- const { credentialSubject, outcomes, skill, ...unboundOptions } = args.options;
369
- validateDispatchOptions({ ...unboundOptions });
370
- const boundSubject = credentialSubject ? bindScheduledAutomationCredentialSubject({
371
- plugin,
372
- subject: credentialSubject
373
- }) : void 0;
374
- if (credentialSubject && !boundSubject) throw new Error("Dispatch credentialSubject is not valid for this action");
375
- const options = {
376
- ...unboundOptions,
377
- ...outcomes !== void 0 ? { outcomes } : void 0,
378
- ...skill ? { skill } : void 0,
379
- ...boundSubject ? { credentialSubject: boundSubject } : void 0,
380
- source: {
381
- kind: "scheduled_automation",
382
- automationId: args.automationId,
383
- automationRunId: unboundOptions.idempotencyKey
384
- }
385
- };
386
- return await dispatch({
387
- conversationWorkQueue: args.conversationWorkQueue,
388
- nowMs: args.nowMs,
389
- options,
390
- plugin
391
- });
392
- }
393
- /** Read the bounded outcome for one core-owned scheduled automation dispatch. */
394
- async function getScheduledAutomationDispatch(id) {
395
- return await getPluginDispatchProjection({
396
- plugin: "scheduler",
397
- id
398
- });
399
- }
400
- // src/chat/event-automations/runs.ts
401
- /**
402
- * Record a dispatched event automation run with the Automation version it ran,
403
- * and link its Conversation when it exists. The dispatch can finish before
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
- const dispatches = await mapBounded(runs, (run) => getDispatchRecord(run.id));
429
- for (const [index, run] of runs.entries()) {
430
- const dispatch = dispatches[index];
431
- const status = dispatch?.status ?? "failed";
432
- if (status !== "blocked" && status !== "completed" && status !== "failed") continue;
433
- await recordAutomationExecution(run.automationId, {
434
- conversationId: getDispatchConversationId({ id: run.id }),
435
- errorMessage: dispatch ? dispatch.errorMessage : "Event automation dispatch record is missing.",
436
- executionId: run.id,
437
- nowMs: dispatch?.updatedAtMs ?? nowMs,
438
- status
439
- });
440
- }
441
- }
442
- // src/chat/automations/reply-attribution.ts
443
- /** Name the Automation in the footer of the replies that its runs post. */
444
- function automationReplyAttribution(title) {
445
- const detail = (title ?? "").replace(/\s+/g, " ").trim().slice(0, 128).trim();
446
- return detail ? {
447
- label: "Automation",
448
- detail
449
- } : { label: "Automation" };
450
- }
451
291
  // src/chat/scheduled-automations/runs.ts
452
292
  const PENDING_CLAIM_STALE_MS = 6e4;
453
293
  const MISSED_RUN_MAX_AGE_MS = 864e5;
@@ -1081,7 +921,7 @@ async function runWithTimeout(promise, timeoutMs) {
1081
921
  /** Run plugin heartbeat hooks with bounded per-invocation work. */
1082
922
  async function runPluginHeartbeats(args) {
1083
923
  let count = 0;
1084
- for (const plugin of getPlugins()) {
924
+ for (const plugin of getRegistrations()) {
1085
925
  const pluginName = plugin.manifest.name;
1086
926
  if (count >= (args.limit ?? DEFAULT_PLUGIN_LIMIT)) break;
1087
927
  const heartbeat = plugin.hooks?.heartbeat;
@@ -1206,6 +1046,17 @@ async function runHeartbeat(args) {
1206
1046
  } catch (error) {
1207
1047
  logException(error, "scheduled_automations.heartbeat.failed");
1208
1048
  }
1049
+ try {
1050
+ const woke = await runInboxSnoozeTimers(getDb(), args.nowMs);
1051
+ if (woke > 0) logInfo("inbox_snoozes.heartbeat.woken", { "app.inbox_snooze.count": woke });
1052
+ } catch (error) {
1053
+ logException(error, "inbox_snoozes.heartbeat.failed");
1054
+ }
1055
+ try {
1056
+ await syncAutomationAlerts(getDb(), args.nowMs);
1057
+ } catch (error) {
1058
+ logException(error, "automation_alerts.heartbeat.failed");
1059
+ }
1209
1060
  try {
1210
1061
  await runTimerWatchHeartbeat({
1211
1062
  nowMs: args.nowMs,
@@ -1239,6 +1090,17 @@ async function runHeartbeat(args) {
1239
1090
  } catch (error) {
1240
1091
  logException(error, "conversation_embeddings.backfill.failed");
1241
1092
  }
1093
+ try {
1094
+ await runEventSearchBackfill({
1095
+ ...isEventEmbeddingsEnabled() ? { embedder: createConversationEmbedder({
1096
+ cost: { owner: "none" },
1097
+ operation: "conversation_embedding"
1098
+ }) } : void 0,
1099
+ nowMs: args.nowMs
1100
+ });
1101
+ } catch (error) {
1102
+ logException(error, "event_search.backfill.failed");
1103
+ }
1242
1104
  }
1243
1105
  // src/handlers/scheduler-auth.ts
1244
1106
  /** Check the bearer secret that internal cron requests must send. */
@@ -1333,7 +1195,8 @@ async function selectExpiredRoots(executor, args) {
1333
1195
  )
1334
1196
  or exists (
1335
1197
  select 1 from junior_review_items review_items
1336
- where review_items.added_by_conversation_id = tree.conversation_id
1198
+ where review_items.owner_kind = 'conversation'
1199
+ and review_items.owner_id = tree.conversation_id
1337
1200
  and review_items.status = 'open'
1338
1201
  and review_items.automation_id is null
1339
1202
  )
@@ -1350,7 +1213,8 @@ async function selectExpiredRoots(executor, args) {
1350
1213
  )
1351
1214
  or exists (
1352
1215
  select 1 from junior_review_items review_items
1353
- where review_items.added_by_conversation_id = tree.conversation_id
1216
+ where review_items.owner_kind = 'conversation'
1217
+ and review_items.owner_id = tree.conversation_id
1354
1218
  and review_items.visibility = 'private'
1355
1219
  and (
1356
1220
  review_items.status <> 'open'
@@ -1431,7 +1295,7 @@ async function purgeConversationTree(executor, args) {
1431
1295
  await executor.db().delete(juniorAgentInvocations).where(or(inArray(juniorAgentInvocations.parentConversationId, ids), inArray(juniorAgentInvocations.childConversationId, ids)));
1432
1296
  await executor.db().delete(juniorAgentBindings).where(or(inArray(juniorAgentBindings.parentConversationId, ids), inArray(juniorAgentBindings.childConversationId, ids)));
1433
1297
  await dismissOpenReviewItems(executor.db(), {
1434
- addedByConversationIds: ids,
1298
+ ownerConversationIds: ids,
1435
1299
  nowMs: args.nowMs,
1436
1300
  reason: "Conversation purged"
1437
1301
  });
@@ -1440,7 +1304,7 @@ async function purgeConversationTree(executor, args) {
1440
1304
  const scrubMetadata = args.retention ? !isPublic : resolvedScrubMetadata;
1441
1305
  if (scrubMetadata) {
1442
1306
  await executor.db().delete(juniorConversationBriefs).where(inArray(juniorConversationBriefs.conversationId, ids));
1443
- await executor.db().delete(juniorReviewItems).where(and(inArray(juniorReviewItems.addedByConversationId, ids), eq(juniorReviewItems.visibility, "private"), or(ne(juniorReviewItems.status, "open"), isNull(juniorReviewItems.automationId))));
1307
+ await executor.db().delete(juniorReviewItems).where(and(eq(juniorReviewItems.ownerKind, "conversation"), inArray(juniorReviewItems.ownerId, ids), eq(juniorReviewItems.visibility, "private"), or(ne(juniorReviewItems.status, "open"), isNull(juniorReviewItems.automationId))));
1444
1308
  }
1445
1309
  await executor.db().update(juniorConversations).set({
1446
1310
  transcriptPurgedAt: new Date(args.nowMs),
@@ -1466,7 +1330,8 @@ async function purgeConversationTree(executor, args) {
1466
1330
  * from `last_activity_at` and deleted wholesale by a dedicated cron. Visibility
1467
1331
  * is resolved at purge time through the parent chain to the root's destination,
1468
1332
  * so no expiry is ever stored and a public↔private flip takes effect on the next
1469
- * pass. Attachment files use their own 30-day window.
1333
+ * pass. Attachment files use their own 30-day window, and so do snoozes
1334
+ * that have woken or been undone.
1470
1335
  */
1471
1336
  const DAY_MS = 864e5;
1472
1337
  /** Content retention windows keyed by resolved conversation visibility. */
@@ -1523,9 +1388,11 @@ async function runRetentionPurge(executor, args) {
1523
1388
  nowMs: args.nowMs,
1524
1389
  storage: args.attachmentStorage
1525
1390
  }) : { deleted: 0 };
1391
+ const inboxSnoozes = await deleteExpiredInboxSnoozes(executor.db(), args.nowMs);
1526
1392
  logInfo("retention.purge.completed", {
1527
1393
  "app.retention.attachments": attachmentResult.deleted,
1528
1394
  "app.retention.attachment_uploads": uploadResult.deleted,
1395
+ "app.retention.inbox_snoozes": inboxSnoozes,
1529
1396
  "app.retention.scanned": roots.length,
1530
1397
  "app.retention.purged": purged,
1531
1398
  "app.retention.failed": failed,
@@ -1540,6 +1407,33 @@ async function runRetentionPurge(executor, args) {
1540
1407
  attachments: attachmentResult.deleted
1541
1408
  };
1542
1409
  }
1410
+ // src/db/table-size.ts
1411
+ /**
1412
+ * Emit the estimated row count and total on-disk size of each Junior table as
1413
+ * gauges, so production table growth is visible without a table query.
1414
+ */
1415
+ async function reportTableSizes(executor) {
1416
+ const tables = await executor.query(`
1417
+ SELECT
1418
+ c.relname AS "table",
1419
+ c.reltuples AS "rows",
1420
+ pg_total_relation_size(c.oid) AS "bytes"
1421
+ FROM pg_class c
1422
+ JOIN pg_namespace n ON n.oid = c.relnamespace
1423
+ WHERE n.nspname = current_schema()
1424
+ AND c.relkind IN ('r', 'p')
1425
+ AND c.relname LIKE 'junior\\_%' ESCAPE '\\'
1426
+ `);
1427
+ for (const table of tables) {
1428
+ const attributes = { "db.collection.name": table.table };
1429
+ const rows = Number(table.rows);
1430
+ if (rows >= 0) sentry_exports.metrics.gauge("db.table.rows", rows, { attributes });
1431
+ sentry_exports.metrics.gauge("db.table.size", Number(table.bytes), {
1432
+ unit: "byte",
1433
+ attributes
1434
+ });
1435
+ }
1436
+ }
1543
1437
  // src/handlers/retention.ts
1544
1438
  /**
1545
1439
  * Handle the authenticated internal retention cron. One request runs a single
@@ -1549,10 +1443,14 @@ async function runRetentionPurge(executor, args) {
1549
1443
  async function GET$2(request, options = {}) {
1550
1444
  if (!verifySchedulerRequest(request)) return new Response("Unauthorized", { status: 401 });
1551
1445
  try {
1552
- const result = await runRetentionPurge(getSqlExecutor(), {
1446
+ const executor = getSqlExecutor();
1447
+ const result = await runRetentionPurge(executor, {
1553
1448
  attachmentStorage: options.attachmentStorage ?? getAttachmentStorage(),
1554
1449
  nowMs: Date.now()
1555
1450
  });
1451
+ await reportTableSizes(executor).catch((error) => {
1452
+ logException(error, "db.table_size.failed");
1453
+ });
1556
1454
  return Response.json(result, { status: 200 });
1557
1455
  } catch (error) {
1558
1456
  logException(error, "retention.run.failed");
@@ -1883,9 +1781,10 @@ async function refreshCards(services, user, itemId) {
1883
1781
  }
1884
1782
  /**
1885
1783
  * Do one person action from a Slack card. The thread of the card gets an
1886
- * answer as Slack input from the person, like a typed reply. A dismiss
1887
- * starts no Turn, so the thread gets the same recorded Message as the other
1888
- * linked Conversations, from `actOnReviewItem`. An expected failure, such as
1784
+ * answer as Slack input from the person, like a typed reply. A dismiss, or
1785
+ * the answer to a plugin item, starts no Turn, so the thread gets the same
1786
+ * recorded Message as the other linked Conversations, from
1787
+ * `actOnReviewItem`. An expected failure, such as
1889
1788
  * an item that is already closed, goes to the person as an ephemeral
1890
1789
  * message.
1891
1790
  */
@@ -1902,14 +1801,16 @@ async function act(args) {
1902
1801
  queue: services.queue,
1903
1802
  show: createSlackReviewItemShow(() => services.adapter)
1904
1803
  };
1905
- const recordOnly = args.action === "dismiss";
1804
+ let recordOnly = args.action === "dismiss";
1906
1805
  let item;
1907
1806
  try {
1908
1807
  const current = await readReviewItemForUser(actor.user, args.itemId);
1808
+ const pluginAnswer = args.action === "submit" && isPluginReviewItem(current);
1809
+ recordOnly ||= pluginAnswer;
1909
1810
  item = await actOnReviewItem({
1910
1811
  action: args.action,
1911
1812
  ...recordOnly ? void 0 : { exceptConversationId: conversationId },
1912
- firstCloseOnly: true,
1813
+ firstCloseOnly: !pluginAnswer,
1913
1814
  delivery,
1914
1815
  id: current.id,
1915
1816
  user: actor.user,
@@ -2390,142 +2291,6 @@ function textMentionsBot(text, botUserId) {
2390
2291
  function eventMentionsBot(event, botUserId) {
2391
2292
  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))));
2392
2293
  }
2393
- // src/chat/event-automations/ingest.ts
2394
- /**
2395
- * Owns event matching and durable event-automation dispatch.
2396
- *
2397
- * Each matching automation is independently idempotent. Aggregate failures propagate
2398
- * so the provider can retry the original delivery.
2399
- */
2400
- /** Bind provider delivery identity to one automation's durable dispatch. */
2401
- function eventAutomationDispatchKey(taskId, namespace, eventKey) {
2402
- return `event-automation:${createHash("sha256").update(`${taskId}\0${namespace}\0${eventKey}`).digest("hex").slice(0, 32)}`;
2403
- }
2404
- /** Render plain agent input for one matching event automation. */
2405
- function eventInput(task, event, outcomes, catalog, author) {
2406
- const guidance = eventGuidance(catalog, event.namespace, event.eventType);
2407
- return renderTaskInput({
2408
- about: task.trigger.label,
2409
- event: event.eventType,
2410
- source: event.namespace,
2411
- creator: slackMention(task.createdBy.slackUserId),
2412
- instructions: automationTaskText(task.task),
2413
- ...task.task.kind === "skill" ? { skill: task.task.skill } : void 0,
2414
- outcomes,
2415
- guidance,
2416
- trustedSummary: event.trustedSummary,
2417
- trustedSummaryMaxLength: EVENT_SUMMARY_MAX_LENGTH,
2418
- verifiedDetails: event.data,
2419
- authorText: eventAuthorText(author),
2420
- externalText: event.untrustedText,
2421
- externalTextMaxLength: EVENT_TEXT_MAX_LENGTH
2422
- });
2423
- }
2424
- /**
2425
- * Match a normalized event and dispatch every matching automation.
2426
- *
2427
- * Plugins publish one copy of an occurrence for each scope, such as a pull
2428
- * request and its repository. All copies share one event key. An automation
2429
- * with no identifier matches every copy, and the dispatch key and the run
2430
- * limit both use the event key, so it runs and counts once.
2431
- */
2432
- async function ingestEventAutomations(input, options) {
2433
- const event = eventSchema$1.parse(input);
2434
- const db = getDb();
2435
- const nowMs = options.nowMs ?? Date.now();
2436
- const catalog = getEventCatalog();
2437
- const [matches = []] = await findMatchingEventAutomations(db, [event], options.teamId, catalog);
2438
- const tasks = matches.filter((task) => slackChannelMessageRunsAutomation(event, task));
2439
- if (tasks.length === 0) return { dispatched: 0 };
2440
- const author = await resolveEventAuthor(event);
2441
- let dispatched = 0;
2442
- const errors = [];
2443
- for (const task of tasks) try {
2444
- const skill = task.task.kind === "skill" ? task.task.skill : void 0;
2445
- if (skill && !await findAutomationSkill(skill)) {
2446
- const reason = missingAutomationSkillReason(skill);
2447
- if (await blockEventAutomation(db, task.id, reason)) await notifyAutomationBlocked({
2448
- automationId: task.id,
2449
- kind: "event",
2450
- reason
2451
- });
2452
- continue;
2453
- }
2454
- const idempotencyKey = eventAutomationDispatchKey(task.id, event.namespace, event.eventKey);
2455
- if (await admitEventAutomationRun({
2456
- automationId: task.id,
2457
- nowMs,
2458
- runKey: idempotencyKey
2459
- }) === "limited") {
2460
- const reason = eventAutomationRunLimitReason();
2461
- logWarn("event_automation.run_limit.exceeded", {
2462
- "app.task.id": task.id,
2463
- "app.task.type": "event"
2464
- });
2465
- if (await blockEventAutomation(db, task.id, reason)) {
2466
- captureMessage("Event automation blocked by run limit", {
2467
- level: "warning",
2468
- fingerprint: ["event_automation.run_limit.blocked"],
2469
- tags: {
2470
- "app.event.namespace": event.namespace,
2471
- "app.task.type": "event"
2472
- },
2473
- extra: {
2474
- "app.event.event_type": event.eventType,
2475
- "app.event_automation.max_runs": botConfig.maxEventAutomationRuns,
2476
- "app.event_automation.run_window_ms": botConfig.eventAutomationRunWindowMs,
2477
- "app.event_automation.resource_type": task.trigger.resourceType ?? "any",
2478
- "app.task.id": task.id
2479
- }
2480
- });
2481
- await notifyAutomationBlocked({
2482
- automationId: task.id,
2483
- kind: "event",
2484
- reason
2485
- });
2486
- }
2487
- continue;
2488
- }
2489
- const replyThreadTs = slackChannelMessageReplyThreadTs(event);
2490
- const destination = replyThreadTs ? {
2491
- ...task.destination,
2492
- threadTs: replyThreadTs
2493
- } : task.destination;
2494
- const outcomes = effectiveTaskOutcomes(task.outcomes, destination);
2495
- const credentialSubject = task.credentialMode === "creator" ? {
2496
- type: "user",
2497
- userId: task.createdBy.slackUserId,
2498
- allowedWhen: "event-automation",
2499
- taskId: task.id
2500
- } : void 0;
2501
- const dispatch = await dispatchEventAutomation({
2502
- automationId: task.id,
2503
- conversationWorkQueue: options.queue,
2504
- nowMs,
2505
- options: {
2506
- idempotencyKey,
2507
- ...credentialSubject ? { credentialSubject } : void 0,
2508
- destination,
2509
- destinationVisibility: task.destinationVisibility,
2510
- input: eventInput(task, event, outcomes, catalog, author),
2511
- ...skill ? { skill } : void 0,
2512
- metadata: { eventAutomationId: task.id },
2513
- replyAttribution: automationReplyAttribution(task.title),
2514
- outcomes
2515
- }
2516
- });
2517
- await recordEventAutomationRunStarted(db, {
2518
- automation: task,
2519
- dispatchId: dispatch.id,
2520
- nowMs
2521
- });
2522
- if (dispatch.status === "created") dispatched += 1;
2523
- } catch (error) {
2524
- errors.push(error);
2525
- }
2526
- if (errors.length > 0) throw new AggregateError(errors, "Failed to dispatch one or more event automations");
2527
- return { dispatched };
2528
- }
2529
2294
  // src/chat/ingress/slack-message-telemetry.ts
2530
2295
  function field(value, pattern) {
2531
2296
  if (value === void 0) return "missing";
@@ -3469,56 +3234,6 @@ async function publicArtifactGET(args) {
3469
3234
  return new Response("Internal Server Error", { status: 500 });
3470
3235
  }
3471
3236
  }
3472
- // src/chat/events/app-publisher.ts
3473
- const WATCH_MATCH_CONCURRENCY = 4;
3474
- /** Build the core event publisher used by plugin routes. */
3475
- function createEventAppPublisher(args) {
3476
- return {
3477
- async hasMatch(events) {
3478
- const work = args.conversationWork();
3479
- const eventAutomationTeamId = await resolveBotSlackTeamId();
3480
- const [subscriptions, tasks] = await Promise.all([mapBounded(events, (event) => findMatchingWatches({
3481
- data: event.data,
3482
- eventType: event.eventType,
3483
- namespace: event.namespace,
3484
- identifier: event.identifier,
3485
- state: work.state
3486
- }), WATCH_MATCH_CONCURRENCY), eventAutomationTeamId ? findMatchingEventAutomations(getDb(), events, eventAutomationTeamId, getEventCatalog()) : Promise.resolve([])]);
3487
- return [...subscriptions, ...tasks].some((matched) => matched.length > 0);
3488
- },
3489
- async neededMatchKeys(input) {
3490
- const work = args.conversationWork();
3491
- const eventAutomationTeamId = await resolveBotSlackTeamId();
3492
- const [watchKeys, taskKeys] = await Promise.all([collectEventMatchKeys({
3493
- eventTypes: input.eventTypes,
3494
- identifiers: input.identifiers,
3495
- namespace: input.namespace,
3496
- state: work.state
3497
- }), eventAutomationTeamId ? collectEventAutomationMatchKeys(getDb(), {
3498
- catalog: getEventCatalog(),
3499
- ...input.data ? { data: input.data } : void 0,
3500
- eventTypes: input.eventTypes,
3501
- identifiers: input.identifiers,
3502
- namespace: input.namespace,
3503
- teamId: eventAutomationTeamId
3504
- }) : Promise.resolve([])]);
3505
- return [.../* @__PURE__ */ new Set([...watchKeys, ...taskKeys])].sort();
3506
- },
3507
- async publish(event) {
3508
- const work = args.conversationWork();
3509
- const queue = work.queue ?? getVercelConversationWorkQueue();
3510
- const eventAutomationTeamId = await resolveBotSlackTeamId();
3511
- await Promise.all([ingestEvent(event, {
3512
- queue,
3513
- slackTeamId: eventAutomationTeamId,
3514
- state: work.state
3515
- }), eventAutomationTeamId ? ingestEventAutomations(event, {
3516
- queue,
3517
- teamId: eventAutomationTeamId
3518
- }) : Promise.resolve()]);
3519
- }
3520
- };
3521
- }
3522
3237
  // src/chat/agent-dispatch/identity.ts
3523
3238
  /**
3524
3239
  * Build the one entry point that starts work for a person whom a plugin
@@ -4748,9 +4463,7 @@ const ACP_CONVERSATION_PREFIX = "local:acp:";
4748
4463
  const ACP_EVENT_STREAM_MIME_TYPE = "text/event-stream";
4749
4464
  const ACP_JSON_MIME_TYPE = "application/json";
4750
4465
  const MAX_PROMPT_TEXT_LENGTH = 32e3;
4751
- function isRecord(value) {
4752
- return typeof value === "object" && value !== null && !Array.isArray(value);
4753
- }
4466
+ const urlElicitationCapabilitySchema = z.object({ url: z.object({}) });
4754
4467
  function authenticatedAcpUser(connection) {
4755
4468
  return connection.user;
4756
4469
  }
@@ -4758,7 +4471,7 @@ function supportsUrlElicitation(params) {
4758
4471
  const parsed = initializeParamsSchema.safeParse(params);
4759
4472
  if (!parsed.success) return false;
4760
4473
  const elicitation = parsed.data.clientCapabilities?.["elicitation"];
4761
- return isRecord(elicitation) && isRecord(elicitation["url"]);
4474
+ return urlElicitationCapabilitySchema.safeParse(elicitation).success;
4762
4475
  }
4763
4476
  function parseParams(schema, params) {
4764
4477
  const parsed = schema.safeParse(params);
@@ -4802,7 +4515,7 @@ function stableHex(value, length = 32) {
4802
4515
  }
4803
4516
  function canonicalJson(value) {
4804
4517
  if (Array.isArray(value)) return value.map(canonicalJson);
4805
- if (!isRecord(value)) return value;
4518
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return value;
4806
4519
  return Object.fromEntries(Object.entries(value).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([key, child]) => [key, canonicalJson(child)]));
4807
4520
  }
4808
4521
  /** Preserve the JSON-RPC id type and request payload in durable retry keys. */
@@ -5874,7 +5587,10 @@ async function handleMcpConsentPage(args) {
5874
5587
  const mcpConversationSchema = z.object({
5875
5588
  conversationId: z.string(),
5876
5589
  title: z.string(),
5877
- status: conversationReportStatusSchema.describe("`active` while work runs, waits to start, or waits on you. `completed` when no work is left. `failed` when the last turn failed. `stopped` after a person or a parent agent stopped it, until a person sends it input or its parent gives it new work."),
5590
+ status: conversationReportStatusSchema.describe("`needs_input` while it waits on a person: a Review item it added, a sign-in, a failed latest Turn, a `partial` or `blocked` Brief, or an answer its starter has not read. `working` while a Turn runs or waits to start. `done` otherwise, also after a stop."),
5591
+ turnActive: z.boolean().describe("True while a Turn runs or waits to start, whatever `status` is. To follow a Conversation, wait until it is false."),
5592
+ treeState: conversationTreeStateSchema.optional().describe("Your viewer state, over this Conversation and all its child agents. `needs_you` when one of them waits on you or on everyone. `working` while a Turn runs or waits to start in any of them. `done` otherwise. Show this in a list, not `status`."),
5593
+ watching: z.boolean().optional().describe("True when one of them has an active Watch or a pending Timer. It is not work."),
5878
5594
  surface: conversationSurfaceSchema.describe("Where it started: `slack`, `api` (the dashboard or MCP), `scheduler` (an automation), or `internal`."),
5879
5595
  channelName: z.string().optional().describe("Slack channel name."),
5880
5596
  locationUrl: z.string().optional().describe("Slack thread link."),
@@ -5890,6 +5606,9 @@ function mcpConversation(summary) {
5890
5606
  conversationId: summary.conversationId,
5891
5607
  title: summary.displayTitle,
5892
5608
  status: summary.status,
5609
+ turnActive: summary.turnActive,
5610
+ treeState: summary.treeState,
5611
+ watching: summary.watching,
5893
5612
  surface: summary.surface,
5894
5613
  channelName: summary.channelNameRedacted ? void 0 : summary.channelName,
5895
5614
  locationUrl: summary.locationUrl,
@@ -6340,7 +6059,7 @@ async function readMessagesAfter(conversationId, afterSeq) {
6340
6059
  function registerGetConversationTool(server, { user }) {
6341
6060
  server.registerTool("getConversation", {
6342
6061
  title: "Get conversation",
6343
- description: "Get one conversation: its metadata, its Brief (a summary of intent, outcome, and state), the messages that no turn has read yet, and a `cursor`. Without `after`, it returns the last assistant reply. With `after`, it returns the messages after that point instead. To follow a conversation, call it again with the newest `cursor` until `status` is not `active` and `hasMore` is not set. Use listConversationMessages for older messages.",
6062
+ description: "Get one conversation: its metadata, its Brief (a summary of intent, outcome, and state), the messages that no turn has read yet, and a `cursor`. Without `after`, it returns the last assistant reply. With `after`, it returns the messages after that point instead. To follow a conversation, call it again with the newest `cursor` until `turnActive` is false and `hasMore` is not set. Use listConversationMessages for older messages.",
6344
6063
  inputSchema: {
6345
6064
  conversationId: mcpConversationIdSchema,
6346
6065
  after: z.string().min(1).max(1e3).optional().describe("`cursor` from sendMessage, createConversation, or an earlier getConversation call.")
@@ -6350,7 +6069,7 @@ function registerGetConversationTool(server, { user }) {
6350
6069
  brief: mcpBriefSchema.optional(),
6351
6070
  lastReply: mcpMessageSchema.optional().describe("Newest assistant message in the recent events. Set only without `after`."),
6352
6071
  messages: z.array(mcpMessageSchema).optional().describe("User and assistant messages after `after`, oldest first. Set only with `after`."),
6353
- hasMore: z.boolean().optional().describe("True when more messages already follow `cursor`. Call again now, also when `status` is not `active`."),
6072
+ hasMore: z.boolean().optional().describe("True when more messages already follow `cursor`. Call again now, also when `turnActive` is false."),
6354
6073
  pendingMessages: mcpPendingMessagesSchema,
6355
6074
  authorization: mcpAuthorizationSchema.optional(),
6356
6075
  cursor: mcpCursorSchema
@@ -7376,6 +7095,7 @@ function dashboardHostRoutePaths(dashboard, authenticatedRoutes = []) {
7376
7095
  `${conversationsPath}/*`,
7377
7096
  pagePath("locations"),
7378
7097
  `${pagePath("locations")}/*`,
7098
+ pagePath("inbox"),
7379
7099
  pagePath("review"),
7380
7100
  peoplePath,
7381
7101
  `${peoplePath}/*`,
@@ -7405,6 +7125,8 @@ function dashboardHostRoutePaths(dashboard, authenticatedRoutes = []) {
7405
7125
  loginPath,
7406
7126
  "/api/health",
7407
7127
  "/api/runtime",
7128
+ "/api/memory",
7129
+ "/api/memory/*",
7408
7130
  "/api/plugins",
7409
7131
  "/api/plugins/*",
7410
7132
  "/api/plugin-reports",
@@ -7432,6 +7154,7 @@ function dashboardHostRoutePaths(dashboard, authenticatedRoutes = []) {
7432
7154
  "/api/locations/*",
7433
7155
  "/api/people",
7434
7156
  "/api/people/*",
7157
+ "/api/inbox/*",
7435
7158
  "/api/review-items",
7436
7159
  "/api/review-items/*",
7437
7160
  "/api/personal-tokens",
@@ -7440,6 +7163,7 @@ function dashboardHostRoutePaths(dashboard, authenticatedRoutes = []) {
7440
7163
  "/api/service-accounts/*",
7441
7164
  "/api/cache-warming",
7442
7165
  "/api/cache-warming/*",
7166
+ "/api/gateway-providers",
7443
7167
  "/api/workspaces",
7444
7168
  "/api/workspaces/*",
7445
7169
  "/api/config",
@@ -7629,6 +7353,7 @@ async function createApp(options) {
7629
7353
  const previousExperimentalFeatures = getExperimentalFeatures();
7630
7354
  const previousBriefsConfig = setBriefsConfig(options?.briefs);
7631
7355
  const previousEventEmbeddingsConfig = setEventEmbeddingsConfig(options?.eventEmbeddings);
7356
+ const previousMemoryConfig = setMemoryConfig(options?.memory);
7632
7357
  const previousDashboardLinkOptions = setDashboardConversationLinkOptions(dashboard);
7633
7358
  let previousTrustConfig;
7634
7359
  const restoreRuntimeConfig$1 = () => {
@@ -7641,6 +7366,7 @@ async function createApp(options) {
7641
7366
  setExperimentalFeatures(previousExperimentalFeatures);
7642
7367
  setBriefsConfig(previousBriefsConfig);
7643
7368
  setEventEmbeddingsConfig(previousEventEmbeddingsConfig);
7369
+ setMemoryConfig(previousMemoryConfig);
7644
7370
  setDashboardConversationLinkOptions(previousDashboardLinkOptions);
7645
7371
  };
7646
7372
  let pluginRoutes = [];