@sentry/junior 0.311.0 → 0.312.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 (118) hide show
  1. package/dist/{adapter-context-G2M0y6rP.js → adapter-context-BRjEWRy1.js} +2 -2
  2. package/dist/{adapter-B1wujchl.js → adapter-iIq7ihf7.js} +1 -1
  3. package/dist/{admin-DCiBhUT1.js → admin-DhInw5K9.js} +1 -1
  4. package/dist/{agent-runner-BVHPUIc8.js → agent-runner-C9iDurwX.js} +3423 -3477
  5. package/dist/api/schema.d.ts +2 -2
  6. package/dist/api/schema.js +6 -6
  7. package/dist/api.d.ts +2 -2
  8. package/dist/api.js +289 -306
  9. package/dist/{app-Cw5Vy6H6.d.ts → app-DRFrC8Mw.d.ts} +2 -9
  10. package/dist/app.d.ts +1 -1
  11. package/dist/app.js +338 -604
  12. package/dist/{background-compaction-queue-CJDnWVOJ.js → background-compaction-queue-DrKi7w3d.js} +10 -85
  13. package/dist/callback-mFlTUWWx.js +75 -0
  14. package/dist/{catalog-runtime-DMY3VV-D.js → catalog-runtime-D7xapBAX.js} +1 -1
  15. package/dist/channel-access-CJGfNTdn.js +221 -0
  16. package/dist/child-message-DcsritGf.js +179 -0
  17. package/dist/cli/chat.js +18 -19
  18. package/dist/cli/check.js +3 -3
  19. package/dist/cli/init.js +0 -1
  20. package/dist/cli/main.js +3 -7
  21. package/dist/cli/plugins.js +4 -4
  22. package/dist/cli/run.d.ts +1 -2
  23. package/dist/cli/run.js +1 -2
  24. package/dist/cli/snapshot-create.js +5 -5
  25. package/dist/cli/upgrade.d.ts +1 -1
  26. package/dist/cli/upgrade.js +3 -3
  27. package/dist/{config-BrXDQefC.js → config-kXB2Y5tl.js} +59 -27
  28. package/dist/{continue-in-slack-DNXSC9So.js → continue-in-slack-O6pV5004.js} +7 -8
  29. package/dist/{conversation-feed-DkinDu5o.js → conversation-feed-uNOv_x68.js} +74 -20
  30. package/dist/{conversation-privacy-DxttrKb9.js → conversation-privacy-L4ja1_W6.js} +1 -1
  31. package/dist/{conversation-turn-DWw7Xhdr.js → conversation-turn-CeLbHqdw.js} +31 -27
  32. package/dist/{credential-sync-Bk8wGb8Y.js → credential-sync-I8VBGk05.js} +16 -15
  33. package/dist/{projection-Cns7XwWa.js → credentialed-Cb6E2phL.js} +16308 -20732
  34. package/dist/{db-7ETESH44.d.ts → db-BbC5stfa.d.ts} +11 -6
  35. package/dist/{db-DTxzH7u5.js → db-LAyyX8tk.js} +174 -91
  36. package/dist/{executor-DqTiYj9S.js → executor-SCub-fAq.js} +117 -97
  37. package/dist/{html-B9Sl4Axb.js → html-BCZ3Xtb_.js} +6 -6
  38. package/dist/ingest-BDf3D50j.js +3836 -0
  39. package/dist/{install-Sg4ePfLl.js → install-DCFJFkC0.js} +2 -2
  40. package/dist/instrumentation.js +3 -3
  41. package/dist/{lineage-BHAMpNKr.js → lineage-B_m-4TJw.js} +2 -2
  42. package/dist/{stop-CYsfc0Ed.js → list-CN2QA2R9.js} +663 -442
  43. package/dist/{logging-FjclQsXu.js → logging-dQ9ZRGQ8.js} +1 -1
  44. package/dist/{schedule-BLJ476XQ.js → media-CYm1QD8T.js} +1055 -11
  45. package/dist/{message-CJ7_RL50.js → message-DSXGj1hM.js} +19 -26
  46. package/dist/{model-input-CMLh4Cwq.js → model-input--TrP9hYV.js} +3 -3
  47. package/dist/nitro.d.ts +1 -1
  48. package/dist/nitro.js +4 -3
  49. package/dist/{oauth-callback-server-RVcbiDjL.js → oauth-callback-server-DHCZC6B4.js} +2 -2
  50. package/dist/{oauth-relay-Bu9kkaQu.js → oauth-relay-pPMGnDZt.js} +1 -1
  51. package/dist/{registry-BPwuOP2O.js → registry-CZOzddwu.js} +1 -1
  52. package/dist/{resolve-BK29bBry.js → resolve-cKOQ14Dh.js} +3 -3
  53. package/dist/result-DcvEOe1r.js +574 -0
  54. package/dist/result-event-type-BdIJuZxg.js +48 -0
  55. package/dist/{runner-BcAE-cJm.js → runner-DBfUW44l.js} +14 -16
  56. package/dist/{sandbox-egress-signals-C-q0go5b.js → sandbox-egress-signals-BVF_xAm1.js} +1 -1
  57. package/dist/{schema-DYcJeV7d.d.ts → schema-BEHKxr4I.d.ts} +166 -242
  58. package/dist/{schema-BLgSZXcL.js → schema-Bk9Nm2E8.js} +106 -121
  59. package/dist/{service-account-iJoCtkHR.js → service-account-CVYsFjty.js} +3 -3
  60. package/dist/{service-account-gN0zqf0S.js → service-account-Ts4ulcrV.js} +5 -5
  61. package/dist/{skills-BoZ80epJ.js → skills-VTnhAJWm.js} +2 -2
  62. package/dist/{slack-conversation-unfurl-CogYrITA.js → slack-conversation-unfurl-fuLnF1jE.js} +9 -9
  63. package/dist/{spawn-Dk92r7mX.js → spawn-vxAarlX5.js} +6 -5
  64. package/dist/start-conversation-CEn2KH1A.js +941 -0
  65. package/dist/{state-DH3Cmgp3.js → state-C1P3_Ywk.js} +4 -4
  66. package/dist/statuses-_cRJHXK7.js +150 -0
  67. package/dist/store-DFZaN-Ix.js +492 -0
  68. package/dist/task-queue-Cx4Lmjyk.js +90 -0
  69. package/dist/task-runner-CbTwFA6k.js +1432 -0
  70. package/dist/{thread-context-BW2BsQbH.js → thread-context-BkAZDTX2.js} +7 -7
  71. package/dist/thread-state-DhPndWi1.js +5625 -0
  72. package/dist/{validation-DrJd0nnq.js → validation-nIzMtAVJ.js} +1 -1
  73. package/dist/{task-queue-C_zldF5J.js → vercel-queue-hW90XzbG.js} +93 -172
  74. package/dist/{version-CNKZ8owc.js → version-Brbtz4Qf.js} +1 -1
  75. package/dist/version.js +1 -1
  76. package/dist/{warmup-BWdHew2H.js → warmup-BDA5myRK.js} +6463 -12290
  77. package/dist/web-message-id-C6P83ans.js +10 -0
  78. package/dist/{worker-t9qpu_Zx.js → worker-D63RcaVD.js} +20 -7
  79. package/migrations/0143_todos.sql +14 -0
  80. package/migrations/0144_inbox_items.sql +32 -0
  81. package/migrations/0145_todo_changed_by_agent.sql +1 -0
  82. package/migrations/0146_inbox_item_subject_title_parts.sql +1 -0
  83. package/migrations/0147_inbox_snooze_wake_reason.sql +1 -0
  84. package/migrations/0148_authorization_request_index.sql +1 -0
  85. package/migrations/0149_conversation_metadata.sql +10 -0
  86. package/migrations/0150_conversation_metadata_fill.sql +39 -0
  87. package/migrations/0151_conversation_search_index.sql +1 -0
  88. package/migrations/0152_inbox_item_legacy_automation_keys.sql +21 -0
  89. package/migrations/0153_artifact_expiry.sql +1 -0
  90. package/migrations/0154_artifact_permanent_sha_index.sql +1 -0
  91. package/migrations/0155_artifact_drop_public_sha_index.sql +3 -0
  92. package/migrations/0156_conversation_kind_lead.sql +6 -0
  93. package/migrations/0157_conversation_lead_actor_index.sql +1 -0
  94. package/migrations/meta/0143_snapshot.json +6434 -0
  95. package/migrations/meta/0144_snapshot.json +6434 -0
  96. package/migrations/meta/0145_snapshot.json +6440 -0
  97. package/migrations/meta/0146_snapshot.json +6446 -0
  98. package/migrations/meta/0147_snapshot.json +6452 -0
  99. package/migrations/meta/0148_snapshot.json +6474 -0
  100. package/migrations/meta/0149_snapshot.json +6490 -0
  101. package/migrations/meta/0150_snapshot.json +6490 -0
  102. package/migrations/meta/0151_snapshot.json +6505 -0
  103. package/migrations/meta/0152_snapshot.json +6505 -0
  104. package/migrations/meta/0153_snapshot.json +6511 -0
  105. package/migrations/meta/0154_snapshot.json +6533 -0
  106. package/migrations/meta/0155_snapshot.json +6511 -0
  107. package/migrations/meta/0156_snapshot.json +6511 -0
  108. package/migrations/meta/0157_snapshot.json +6527 -0
  109. package/migrations/meta/_journal.json +106 -1
  110. package/package.json +6 -6
  111. package/skills/design-automation-skill/SKILL.md +108 -0
  112. package/dist/briefs-BDjnug6Y.js +0 -395
  113. package/dist/conversation-ca__NDQW.js +0 -1063
  114. package/dist/prompt-CDqcsDYC.js +0 -910
  115. package/dist/store-DmmMIrQi.js +0 -335
  116. package/dist/task-runner-C7oCJQIx.js +0 -294
  117. package/dist/turn-session-routing-Xh_2nSQe.js +0 -261
  118. package/dist/web-message-id-Ch5dPq-a.js +0 -306
package/dist/app.js CHANGED
@@ -1,43 +1,48 @@
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";
1
+ import { Ao as getSlackClient, Ar as getDispatchConversationId, Bo as getWorkspaceTeamId, Ca as dismissOpenInboxItems, Ci as withScheduledAutomationLock, Dn as normalizeSandboxEgressTracePropagationDomains, Fi as setDashboardConversationLinkOptions, G as setEventEmbeddingsConfig, Hn as resolveRootVisibility, I as projectConversationMessages, Ir as isTerminalDispatchStatus, J as eventIndexLockKey, Jr as openSlackModal, K as EVENT_INDEX_LOCK_TTL_MS, L as setMemoryConfig, La as deleteExpiredInboxSnoozes, Lr as listPendingDispatchMailboxAppends, Nr as getDispatchRecord, Or as confirmDispatchMailboxAppend, Q as storeConversationEventLexemes, S as readPublicArtifact, Si as scheduledRunId, Ti as getDashboardInboxItemLink, Un as backfillConversationEmbeddings, Ur as notifyAutomationBlocked, Vo as runWithWorkspaceTeamId, Vr as markDispatchFailed, W as isEventEmbeddingsEnabled, Wn as createConversationEmbedder, Ya as slackChannelMessageEvent, Yi as automationVersionOf, Yn as listConversationAnnotations, Yr as postSlackEphemeralMessage, _i as listScheduledAutomationsForTeam, _n as clearSandboxEgressSignals, _o as takeDueTimerWatches, an as resolveBaseUrl, b as publicArtifactHeaders, en as isVercelSandboxEgressRequest, g as getRegistrations, ga as syncAutomationAlerts, ja as searchInboxItems, ji as getDashboardTaskLink, l as getPluginApiRoutes, ni as slackEntitySchema, pa as refreshAutomationLastRun, q as embedConversationEvents, qa as SLACK_EVENT_NAMESPACE, r as createUserTokenStore, ra as existingConversationId, ri as slackExternalRefIdSchema, s as createPluginEventPublisher, tn as proxyVercelSandboxEgressRequest, u as getPluginRoutes, ui as slackMention, v as setPlugins, vn as consumeSandboxEgressAuthRequiredSignal, vs as getConfigDefaults, w as unpublishedArtifactHeaders, wi as getDashboardConversationLink, xi as saveScheduledAutomationInLock, xn as parseSandboxEgressCredentialToken, y as validatePlugins, yi as readScheduledAutomation, yn as consumeSandboxEgressPermissionDeniedSignal, ys as setConfigDefaults } from "./credentialed-Cb6E2phL.js";
2
+ import { I as MUTATION_LOCK_TTL_MS, R as fenceLock, d as setBotModelConfig, f as setBotName, gt as getAttachmentStorage, h as snapshotRuntimeConfig, l as resetRuntimeConfig, m as setSlackReactionConfig, n as botConfig, p as setRuntimeLimits, r as getChatConfig, u as restoreRuntimeConfig, z as withLock } from "./config-kXB2Y5tl.js";
3
+ import { $t as resolveActorIdentityId, Ht as resolveViewerUser, Ln as touchConversationDetail, Lt as readActorIdentity, Rn as createSlackDestination, U as conversationCostOf, a as getConversationStore, bt as inboxItemReaderForUserInConversation, cn as recordGoogleSignIn, m as withConversationEventLock, o as getDb, p as deleteMessageLinks, qt as parseAvatarUrl, r as getConversationEventStore, s as getSqlExecutor, st as canActOnInboxItem, t as closeDb, w as withConversationMutationLock, wt as isPluginInboxItem, yn as readConversationAccessFromSql, yt as inboxItemReaderForUser } from "./db-LAyyX8tk.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-dQ9ZRGQ8.js";
5
+ import { T as resumeConversationDelivery, _ as buildSlackInboxItemModal, d as scheduledAutomationRunAttributes, f as createSlackInboxItemShow, h as findSlackThreadOwnerId, m as syncInboxItemSlackCards, n as executeAgentRun, p as resolveSlackInboxItemCardConversationId, t as createAgentRunner, u as logScheduledAutomationRunSkipped, v as parseSlackInboxItemClick, x as parseSlackUserInputSubmission, y as parseSlackInboxItemFormTarget } from "./agent-runner-C9iDurwX.js";
6
+ import { Mt as getExperimentalFeatures, Nt as isExperimentalFeatureEnabled, Pt as setExperimentalFeatures, S as parseEmail, _t as deleteTodos, b as isAllowedDomain, dt as renderTaskInput, i as getAuthPausedConversationTurnId, t as ingestEvent, w as setTrustConfig, x as isTrustedSlackAuthor, y as findTrustedUser } from "./ingest-BDf3D50j.js";
7
+ import { a as getSandboxResourceConfig, s as setSandboxResourceConfig } from "./install-DCFJFkC0.js";
8
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-D7xapBAX.js";
9
+ import { $ as runAutoArchiveSweep, At as slackInboundMessageId, B as mcpMessages, Bt as stripLeadingBotMention, Ct as isPublicAddress, Dt as getProductionSlackAdapter, Et as createProductionSlackWebhookServices, F as mcpConversationSchema, Ft as failStoppedDispatch, H as readMcpPendingWork, Ht as SubscribedReplyReason, I as mcpCursorSchema, It as recordSkippedConversationMessage, J as closeInboxItemsAnsweredByReply, K as InboxItemActionError, Kt as readConversationRecordFromSql, L as mcpIdempotencyKeySchema, Lt as createSlackWebApiStatusSender, M as mcpAuthorizationSchema$1, Mt as withNormalizedThreadId, N as mcpConversation, Ot as buildSlackInboundMessage, P as mcpConversationIdSchema, Pt as enqueueAgentDispatch, Q as ingestEventAutomations, R as mcpMessageSchema, Rt as bindMessageAuthorIdentityId, Tt as createProductionConversationWorkOptions, U as readMcpPendingWorkAfterSend, Ut as getThreadStopDecision, V as mcpPendingMessagesSchema, Vt as parseContent, X as reviewItemChange, Y as readInboxItemForUser, Z as createEventAppPublisher, _ as createConversationForViewer, at as createHeartbeatContext, b as encodeConversationCursor, ct as runInboxSnoozeTimers, dt as runSavingsRefillSlice, g as appendConversationMessageForViewer, it as settleEventAutomationRuns, j as mcpAcceptedMessageSchema, jt as normalizeIncomingSlackThreadId, kt as clearSlackPendingReactions, mt as GET$4, n as readConversationFeed, ot as dispatchScheduledAutomation, pt as backfillCacheWarmingGaps, q as actOnInboxItem, rt as automationReplyAttribution, s as readConversationDetail, st as getScheduledAutomationDispatch, vt as readObjectLinkTypes, w as conversationOperations, wt as publicAddressLookup, y as decodeConversationCursor, z as mcpMessageTextSchema, zt as startProcessingReaction } from "./list-CN2QA2R9.js";
10
+ import { n as validatePluginRegistrations, t as validatePluginEgressCredentialHooks } from "./validation-nIzMtAVJ.js";
11
11
  import { a as pluginRuntimeRegistrationsFromPluginSet, n as pluginCatalogConfigFromEnv, r as pluginCatalogConfigFromPluginSet, t as defineJuniorPlugins } from "./plugins-Bkk0XRo2.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";
12
+ import { i as getStateAdapter, n as disconnectStateAdapter } from "./adapter-iIq7ihf7.js";
13
+ import { D as juniorConversationEventEmbeddings, E as juniorConversationEventLexemes, H as juniorConversations, M as juniorConversationEvents, O as juniorConversationEmbeddings, T as juniorConversationBriefs, _ as juniorAutomationRuns, b as juniorAgentBindings, g as juniorAutomations, h as juniorInboxItems, n as isPostgresErrorCode, q as juniorDestinations, x as juniorAgentInvocations } from "./executor-SCub-fAq.js";
14
+ import { $t as CONVERSATION_WORK_STALE_ENQUEUE_MS, C as getConversation, E as listActiveConversationIds, S as ensureConversationWake, an as isInvalidConversationRecordError, g as clearExpiredConversationLease, l as appendAndEnqueueInboundMessage, o as coerceThreadConversationState, rn as hasRunnableConversationWork, sn as pruneActiveConversation, st as settleConversationTitleWork, tt as appendConversationMessages, w as getConversationWorkState } from "./thread-state-DhPndWi1.js";
15
15
  import { t as mapBounded } from "./fan-out-Cod-yEHG.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";
16
+ import { It as scheduledRunSchema, Qt as buttonUserInputField, Ut as getNextRunAtMs, b as automationListQuerySchema, g as automationExecutionStatusSchema, mt as conversationTitleSchema, on as automationTaskSchema, sn as automationTaskText, yt as annotationCard } from "./media-CYm1QD8T.js";
17
+ import { $r as findAutomationSkill, Gr as readViewerAutomations, Mt as listPendingAgentInvocationMailboxAppends, Nt as listPendingAgentInvocationResults, Sn as recordSubagentEnded, T as processWorkspaceSnapshotJob, Ur as readViewerAutomationSummary, Vr as readViewerAutomationExecutions, Wn as parseSlackThreadId, Xr as automationCardStatus, Zt as enqueueAgentInvocation, _n as renderSlackObjectCard, bn as stopConversation, ei as missingAutomationSkillReason, gt as renderInboxItemMessage, ht as inboxItemChangeRecord, mt as deliverInboxItemChange, p as processBackgroundCompaction, ti as effectiveTaskOutcomes, ut as markConversationRead, vn as annotationKeyDigest, yn as decodeAnnotationRef, zr as ViewerTaskNotFoundError } from "./warmup-BDA5myRK.js";
18
+ import { a as conversationQueueMessageSchema, d as getQueueProvider, m as readSignInSecret, n as resolveConversationWorkQueueTopic, o as isConversationQueueMessageRejectedError, p as readSchedulerSecret, r as verifyConversationQueueMessage, t as getVercelConversationWorkQueue } from "./vercel-queue-hW90XzbG.js";
19
+ import { i as enqueueAgentInvocationResult, r as createEndStoppedChildWork } from "./result-DcvEOe1r.js";
20
+ import { o as requestAttachmentDeletion, t as collectAttachmentGarbage } from "./store-DFZaN-Ix.js";
21
+ import { c as conversationTurnIdForMessage, d as recordWebConversationActivity, f as webActorFromUser, h as collectAttachmentUploadGarbage, l as createAndEnqueueConversation, s as appendAndEnqueueWebMessage } from "./start-conversation-CEn2KH1A.js";
19
22
  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";
23
+ import { a as GET$5, i as publishAppHomeView, r as GET$6, t as receiveLocalOAuthCredential } from "./credential-sync-I8VBGk05.js";
21
24
  import { t as nameRequestRoute } from "./sentry-route-name-C6EIzAGP.js";
22
25
  import { t as SANDBOX_EGRESS_PROXY_PATH } from "./proxy-path-BHYoKZdq.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";
24
26
  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";
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";
27
+ 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-fuLnF1jE.js";
28
+ import { l as unlinkProvider, n as renderHtmlPage, r as requestHasSameOrigin, t as escapeHtml } from "./html-BCZ3Xtb_.js";
29
+ import { n as verifySlackSignature, t as runWithSlackInstallation } from "./adapter-context-BRjEWRy1.js";
30
+ import { s as joinPublicChannel } from "./channel-access-CJGfNTdn.js";
31
+ import { t as queueCallback } from "./callback-mFlTUWWx.js";
32
+ import { t as processConversationWork } from "./worker-D63RcaVD.js";
33
+ import { t as bindMessageAgent } from "./message-DSXGj1hM.js";
34
+ import { t as bindSpawnAgent } from "./spawn-vxAarlX5.js";
35
+ import { a as pluginTaskQueueConsumer, n as createVercelPluginTaskCallback, o as registerVercelPluginTaskDevConsumer, s as sendVercelPluginTask } from "./task-queue-Cx4Lmjyk.js";
36
+ import { a as readConversationEventPage, c as readConversationLastEventSeq, l as readConversationMessageEventSeq, o as readConversationEventPageAfter, t as processPluginTask } from "./task-runner-CbTwFA6k.js";
37
+ import { c as registerVercelCacheWarmupDevConsumer, i as verifyBackgroundCompactionMessage, 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 } from "./background-compaction-queue-DrKi7w3d.js";
38
+ import { t as JUNIOR_VERSION } from "./version-Brbtz4Qf.js";
39
+ import { b as conversationPendingMessageDeliverySchema, t as conversationFeedQuerySchema } from "./conversation-feed-uNOv_x68.js";
35
40
  import { createRequire } from "node:module";
36
41
  import { Hono } from "hono";
37
42
  import * as z from "zod";
38
43
  import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
39
44
  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";
45
+ import { and, asc, desc, eq, gt, gte, inArray, isNotNull, isNull, lt, lte, ne, notExists, or, sql } from "drizzle-orm";
41
46
  import { pathToFileURL } from "node:url";
42
47
  import { Message, ThreadImpl } from "chat";
43
48
  import net from "node:net";
@@ -55,7 +60,7 @@ import { betterAuth } from "better-auth/minimal";
55
60
  const BACKFILL_BUDGET_MS$1 = 1e4;
56
61
  const BACKFILL_CLAIM_TTL_MS$1 = 6e4;
57
62
  const BACKFILL_DONE_TTL_MS$1 = 36e5;
58
- /** Embed the latest Briefs that have no vector of the embedder's model. */
63
+ /** Embed the Conversation metadata that has no vector of the embedder's model. */
59
64
  async function runConversationEmbeddingBackfill(embedder) {
60
65
  const key = `junior:conversation_embeddings:backfill:${embedder.provider}:${embedder.model}`;
61
66
  const state = getStateAdapter();
@@ -76,79 +81,142 @@ async function runConversationEmbeddingBackfill(embedder) {
76
81
  // src/chat/conversations/event-search-backfill.ts
77
82
  const ACTIVE_WINDOW_MS = 6048e5;
78
83
  const BACKFILL_BUDGET_MS = 1e4;
79
- const BACKFILL_CLAIM_TTL_MS = 6e4;
84
+ const SCAN_STATEMENT_TIMEOUT_MS = 5e3;
85
+ const BACKFILL_CLAIM_TTL_MS = 3e5;
80
86
  const BACKFILL_DONE_TTL_MS = 6e5;
87
+ const BACKFILL_PASS_TTL_MS = 864e5;
81
88
  const MAX_LEXEME_EVENTS_PER_RUN = 1e3;
82
89
  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 CONVERSATION_PAGE_SIZE = 50;
91
+ const QUERY_CANCELED = "57014";
92
+ const passCursorSchema = z.object({
93
+ at: z.string(),
94
+ conversationId: z.string()
95
+ });
96
+ const backfillPassSchema = z.object({
97
+ after: passCursorSchema.nullable(),
98
+ conversations: z.number(),
99
+ events: z.number(),
100
+ skipped: z.number()
101
+ });
102
+ const NEW_PASS = {
103
+ after: null,
104
+ conversations: 0,
105
+ events: 0,
106
+ skipped: 0
107
+ };
108
+ async function withScanTimeout(db, run) {
109
+ return await db.transaction(async (tx) => {
110
+ await tx.execute(sql`SELECT set_config('statement_timeout', ${String(SCAN_STATEMENT_TIMEOUT_MS)}, true)`);
111
+ return await run(tx);
112
+ });
113
+ }
114
+ async function listActiveConversations(db, args) {
115
+ const conversations = juniorConversations;
116
+ const after = args.after;
117
+ return await withScanTimeout(db, async (tx) => await tx.select({
118
+ at: sql`to_char(${conversations.lastActivityAt} at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`,
119
+ conversationId: conversations.conversationId
120
+ }).from(conversations).where(and(gte(conversations.lastActivityAt, new Date(args.sinceMs)), after ? or(lt(conversations.lastActivityAt, sql`${after.at}::timestamptz`), and(eq(conversations.lastActivityAt, sql`${after.at}::timestamptz`), gt(conversations.conversationId, after.conversationId))) : void 0)).orderBy(desc(conversations.lastActivityAt), conversations.conversationId).limit(CONVERSATION_PAGE_SIZE));
121
+ }
122
+ async function hasMissingVector(tx, embedder, conversationId) {
90
123
  const lexemes = juniorConversationEventLexemes;
91
124
  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);
125
+ return (await tx.select({ seq: lexemes.seq }).from(lexemes).where(and(eq(lexemes.conversationId, conversationId), sql`length(${lexemes.lexemes}) > 0`, notExists(tx.select({ seq: vectors.seq }).from(vectors).where(and(eq(vectors.conversationId, lexemes.conversationId), eq(vectors.seq, lexemes.seq), eq(vectors.provider, embedder.provider), eq(vectors.model, embedder.model)))))).limit(1)).length > 0;
126
+ }
127
+ async function indexConversation(db, args) {
128
+ const attempt = await withLock(getStateAdapter(), eventIndexLockKey(args.conversationId), async () => {
129
+ let lexemes;
130
+ let vectorMissing;
131
+ try {
132
+ [lexemes, vectorMissing] = await withScanTimeout(db, async (tx) => {
133
+ return [await storeConversationEventLexemes(tx, args.conversationId, args.lexemeRoom), args.embedder ? await hasMissingVector(tx, args.embedder, args.conversationId) : false];
134
+ });
135
+ } catch (error) {
136
+ if (!isPostgresErrorCode(error, QUERY_CANCELED)) throw error;
137
+ return { kind: "skipped" };
138
+ }
139
+ const vectors = args.embedder && vectorMissing ? await embedConversationEvents(db, args.embedder, args.conversationId, {
140
+ deadlineMs: args.deadlineMs,
141
+ maxEvents: args.vectorRoom
142
+ }) : 0;
143
+ return {
144
+ kind: "indexed",
145
+ lexemes,
146
+ vectors,
147
+ more: lexemes >= args.lexemeRoom || vectorMissing && (vectors >= args.vectorRoom || Date.now() >= args.deadlineMs)
148
+ };
149
+ }, { ttlMs: EVENT_INDEX_LOCK_TTL_MS });
150
+ return attempt.acquired ? attempt.value : { kind: "skipped" };
102
151
  }
103
152
  /**
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.
153
+ * Continue `pass` over the Conversations with activity in the last week:
154
+ * store their missing lexemes, and missing vectors when `embedder` is set,
155
+ * until the deadline or the event limits. Return what the run did and the
156
+ * pass to continue next.
107
157
  */
108
158
  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 = {
159
+ const sinceMs = args.nowMs - ACTIVE_WINDOW_MS;
160
+ const run = {
161
+ conversations: 0,
115
162
  lexemes: 0,
163
+ skipped: 0,
116
164
  vectors: 0
117
165
  };
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;
166
+ let after = args.pass.after;
167
+ const progress = () => ({
168
+ after,
169
+ conversations: args.pass.conversations + run.conversations,
170
+ events: args.pass.events + run.lexemes + run.vectors,
171
+ skipped: args.pass.skipped + run.skipped
172
+ });
173
+ while (true) {
174
+ if (Date.now() >= args.deadlineMs) return {
175
+ outcome: "limit_reached",
176
+ pass: progress(),
177
+ run
178
+ };
179
+ const page = await listActiveConversations(args.db, {
180
+ after,
181
+ sinceMs
182
+ });
183
+ for (const conversation of page) {
184
+ const lexemeRoom = MAX_LEXEME_EVENTS_PER_RUN - run.lexemes;
185
+ const vectorRoom = MAX_VECTOR_EVENTS_PER_RUN - run.vectors;
186
+ if (Date.now() >= args.deadlineMs || lexemeRoom <= 0 || args.embedder && vectorRoom <= 0) return {
187
+ outcome: "limit_reached",
188
+ pass: progress(),
189
+ run
190
+ };
191
+ const result = await indexConversation(args.db, {
192
+ conversationId: conversation.conversationId,
193
+ deadlineMs: args.deadlineMs,
194
+ ...args.embedder ? { embedder: args.embedder } : void 0,
195
+ lexemeRoom,
196
+ vectorRoom
197
+ });
198
+ run.conversations += 1;
199
+ if (result.kind === "skipped") run.skipped += 1;
200
+ else {
201
+ run.lexemes += result.lexemes;
202
+ run.vectors += result.vectors;
203
+ if (result.more) return {
204
+ outcome: "limit_reached",
205
+ pass: progress(),
206
+ run
207
+ };
208
+ }
209
+ after = conversation;
125
210
  }
126
- const attempt = await withLock(state, eventIndexLockKey(backlog.conversationId), async () => {
211
+ if (page.length < CONVERSATION_PAGE_SIZE) {
212
+ const pass = progress();
127
213
  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
214
+ outcome: pass.events === 0 && pass.skipped === 0 ? "completed" : "pass_ended",
215
+ pass,
216
+ run
133
217
  };
134
- }, { ttlMs: EVENT_INDEX_LOCK_TTL_MS });
135
- if (!attempt.acquired) {
136
- done = false;
137
- continue;
138
218
  }
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
219
  }
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
220
  }
153
221
  /**
154
222
  * Index the backlog of event search in recently active Conversations.
@@ -156,25 +224,40 @@ async function backfillEventSearchIndex(args) {
156
224
  */
157
225
  async function runEventSearchBackfill(args) {
158
226
  const key = `junior:event_search:backfill:${args.embedder ? `${args.embedder.provider}:${args.embedder.model}` : "lexemes"}`;
227
+ const passKey = `${key}:pass`;
159
228
  const state = getStateAdapter();
160
229
  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"
230
+ const deadlineMs = Date.now() + BACKFILL_BUDGET_MS;
231
+ let done = false;
232
+ try {
233
+ await withSpan("event_search.backfill", "event_search.backfill", {}, async (setSpanAttributes) => {
234
+ const stored = backfillPassSchema.safeParse(await state.get(passKey));
235
+ const result = await backfillEventSearchIndex({
236
+ db: getDb(),
237
+ deadlineMs,
238
+ ...args.embedder ? { embedder: args.embedder } : void 0,
239
+ nowMs: args.nowMs,
240
+ pass: stored.success ? stored.data : NEW_PASS
241
+ });
242
+ if (result.outcome === "limit_reached") await state.set(passKey, result.pass, BACKFILL_PASS_TTL_MS);
243
+ else await state.delete(passKey);
244
+ if (result.outcome === "completed") {
245
+ await state.set(key, "done", BACKFILL_DONE_TTL_MS);
246
+ done = true;
247
+ }
248
+ setSpanAttributes({
249
+ "app.event_search.backfill.conversation.count": result.run.conversations,
250
+ "app.event_search.backfill.skipped.count": result.run.skipped,
251
+ "app.event_search.backfill.lexeme.count": result.run.lexemes,
252
+ "app.event_search.backfill.vector.count": result.run.vectors,
253
+ "app.event_search.backfill.pass.conversation.count": result.pass.conversations,
254
+ "app.event_search.backfill.pass.event.count": result.pass.events,
255
+ "app.event_search.backfill.outcome": result.outcome
256
+ });
176
257
  });
177
- });
258
+ } finally {
259
+ if (!done) await state.delete(key);
260
+ }
178
261
  }
179
262
  // src/chat/events/timers.ts
180
263
  /** Publish a bounded batch of due timers; the mailbox owns agent execution. */
@@ -934,7 +1017,7 @@ async function runPluginHeartbeats(args) {
934
1017
  events: createPluginEventPublisher(plugin, args.events),
935
1018
  plugin,
936
1019
  nowMs: args.nowMs,
937
- showReviewItem: args.showReviewItem
1020
+ showInboxItem: args.showInboxItem
938
1021
  }))), PLUGIN_HEARTBEAT_TIMEOUT_MS);
939
1022
  if (typeof result?.dispatchCount === "number" && result.dispatchCount > 0) logInfo("plugin.heartbeat.dispatched", {
940
1023
  "app.dispatch.count": result.dispatchCount,
@@ -1070,7 +1153,7 @@ async function runHeartbeat(args) {
1070
1153
  dispatchForIdentity: args.dispatchForIdentity,
1071
1154
  events: args.events,
1072
1155
  nowMs: args.nowMs,
1073
- showReviewItem: args.showReviewItem
1156
+ showInboxItem: args.showInboxItem
1074
1157
  });
1075
1158
  try {
1076
1159
  await backfillCacheWarmingGaps({ nowMs: args.nowMs });
@@ -1082,7 +1165,7 @@ async function runHeartbeat(args) {
1082
1165
  } catch (error) {
1083
1166
  logException(error, "cache_warming.savings_refill.failed");
1084
1167
  }
1085
- if (isBriefsEnabled()) try {
1168
+ try {
1086
1169
  await runConversationEmbeddingBackfill(createConversationEmbedder({
1087
1170
  cost: { owner: "none" },
1088
1171
  operation: "conversation_embedding"
@@ -1123,7 +1206,7 @@ async function GET$3(request, waitUntil, options) {
1123
1206
  dispatchForIdentity: options.dispatchForIdentity,
1124
1207
  events: options.events,
1125
1208
  nowMs,
1126
- showReviewItem: options.showReviewItem
1209
+ showInboxItem: options.showInboxItem
1127
1210
  }).catch((error) => {
1128
1211
  logException(error, "heartbeat.run.failed", { "app.heartbeat.now_ms": nowMs });
1129
1212
  }));
@@ -1194,15 +1277,15 @@ async function selectExpiredRoots(executor, args) {
1194
1277
  or bindings.child_conversation_id = tree.conversation_id
1195
1278
  )
1196
1279
  or exists (
1197
- select 1 from junior_review_items review_items
1198
- where review_items.owner_kind = 'conversation'
1199
- and review_items.owner_id = tree.conversation_id
1200
- and review_items.status = 'open'
1201
- and review_items.automation_id is null
1280
+ select 1 from junior_inbox_items inbox_items
1281
+ where inbox_items.owner_kind = 'conversation'
1282
+ and inbox_items.owner_id = tree.conversation_id
1283
+ and inbox_items.status = 'open'
1284
+ and inbox_items.automation_id is null
1202
1285
  )
1203
1286
  or exists (
1204
- select 1 from junior_plan_items plan_items
1205
- where plan_items.conversation_id = tree.conversation_id
1287
+ select 1 from junior_todos todos
1288
+ where todos.conversation_id = tree.conversation_id
1206
1289
  )
1207
1290
  or (
1208
1291
  ${juniorDestinations.visibility} is distinct from 'public'
@@ -1212,13 +1295,22 @@ async function selectExpiredRoots(executor, args) {
1212
1295
  where briefs.conversation_id = tree.conversation_id
1213
1296
  )
1214
1297
  or exists (
1215
- select 1 from junior_review_items review_items
1216
- where review_items.owner_kind = 'conversation'
1217
- and review_items.owner_id = tree.conversation_id
1218
- and review_items.visibility = 'private'
1298
+ select 1 from junior_conversations metadata
1299
+ where metadata.conversation_id = tree.conversation_id
1300
+ and metadata.summary is not null
1301
+ )
1302
+ or exists (
1303
+ select 1 from junior_conversation_embeddings embeddings
1304
+ where embeddings.conversation_id = tree.conversation_id
1305
+ )
1306
+ or exists (
1307
+ select 1 from junior_inbox_items inbox_items
1308
+ where inbox_items.owner_kind = 'conversation'
1309
+ and inbox_items.owner_id = tree.conversation_id
1310
+ and inbox_items.visibility = 'private'
1219
1311
  and (
1220
- review_items.status <> 'open'
1221
- or review_items.automation_id is null
1312
+ inbox_items.status <> 'open'
1313
+ or inbox_items.automation_id is null
1222
1314
  )
1223
1315
  )
1224
1316
  or exists (
@@ -1246,9 +1338,10 @@ async function selectExpiredRoots(executor, args) {
1246
1338
  * event rows for the given conversation and every descendant, stamp
1247
1339
  * `transcript_purged_at`, and — for non-public content — null the raw-payload
1248
1340
  * metadata (`title`, `channel_name`, legacy actor JSON) so purged private
1249
- * conversations keep only safe metadata. Plan items go with the transcript.
1250
- * Non-public content also loses its Briefs and the Review items that it
1251
- * added. The metadata rows themselves survive.
1341
+ * conversations keep only safe metadata. To-dos go with the transcript.
1342
+ * Non-public content also loses its summary, Conversation embedding, legacy
1343
+ * Briefs, and the Inbox items that it added. The metadata rows themselves
1344
+ * survive.
1252
1345
  */
1253
1346
  async function purgeConversationTree(executor, args) {
1254
1347
  return await withConversationMutationLock(executor, args.rootConversationId, async () => {
@@ -1294,26 +1387,29 @@ async function purgeConversationTree(executor, args) {
1294
1387
  await deleteMessageLinks(executor, ids);
1295
1388
  await executor.db().delete(juniorAgentInvocations).where(or(inArray(juniorAgentInvocations.parentConversationId, ids), inArray(juniorAgentInvocations.childConversationId, ids)));
1296
1389
  await executor.db().delete(juniorAgentBindings).where(or(inArray(juniorAgentBindings.parentConversationId, ids), inArray(juniorAgentBindings.childConversationId, ids)));
1297
- await dismissOpenReviewItems(executor.db(), {
1390
+ await dismissOpenInboxItems(executor.db(), {
1298
1391
  ownerConversationIds: ids,
1299
1392
  nowMs: args.nowMs,
1300
1393
  reason: "Conversation purged"
1301
1394
  });
1302
- await deletePlanItems(executor, ids);
1395
+ await deleteTodos(executor, ids);
1303
1396
  await requestAttachmentDeletion(executor, ids, args.nowMs);
1304
1397
  const scrubMetadata = args.retention ? !isPublic : resolvedScrubMetadata;
1305
- if (scrubMetadata) {
1306
- await executor.db().delete(juniorConversationBriefs).where(inArray(juniorConversationBriefs.conversationId, ids));
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))));
1308
- }
1309
1398
  await executor.db().update(juniorConversations).set({
1310
1399
  transcriptPurgedAt: new Date(args.nowMs),
1311
1400
  ...scrubMetadata ? {
1312
1401
  title: null,
1313
1402
  channelName: null,
1314
- actor: null
1403
+ actor: null,
1404
+ summary: null,
1405
+ metadataThroughSeq: null
1315
1406
  } : void 0
1316
1407
  }).where(inArray(juniorConversations.conversationId, ids));
1408
+ if (scrubMetadata) {
1409
+ await executor.db().delete(juniorConversationBriefs).where(inArray(juniorConversationBriefs.conversationId, ids));
1410
+ await executor.db().delete(juniorConversationEmbeddings).where(inArray(juniorConversationEmbeddings.conversationId, ids));
1411
+ await executor.db().delete(juniorInboxItems).where(and(eq(juniorInboxItems.ownerKind, "conversation"), inArray(juniorInboxItems.ownerId, ids), eq(juniorInboxItems.visibility, "private"), or(ne(juniorInboxItems.status, "open"), isNull(juniorInboxItems.automationId))));
1412
+ }
1317
1413
  await touchConversationDetail(executor.db(), ids);
1318
1414
  return {
1319
1415
  purged: true,
@@ -1753,7 +1849,7 @@ function buildSlackInteractionInput(args) {
1753
1849
  threadId: parsed.threadId
1754
1850
  });
1755
1851
  }
1756
- // src/chat/ingress/slack-review-item.ts
1852
+ // src/chat/ingress/slack-inbox-item.ts
1757
1853
  async function tellPerson(target, userId, text) {
1758
1854
  await postSlackEphemeralMessage({
1759
1855
  channelId: target.channelId,
@@ -1772,9 +1868,9 @@ function resolveActingUser(services, payload, target) {
1772
1868
  }
1773
1869
  /** Show the current state of an item, such as after a click on a stale card. */
1774
1870
  async function refreshCards(services, user, itemId) {
1775
- const item = await readReviewItemForUser(user, itemId).catch(() => void 0);
1871
+ const item = await readInboxItemForUser(user, itemId).catch(() => void 0);
1776
1872
  if (!item) return;
1777
- await syncReviewItemSlackCards({
1873
+ await syncInboxItemSlackCards({
1778
1874
  getSlackAdapter: () => services.adapter,
1779
1875
  itemId: item.id
1780
1876
  });
@@ -1784,7 +1880,7 @@ async function refreshCards(services, user, itemId) {
1784
1880
  * answer as Slack input from the person, like a typed reply. A dismiss, or
1785
1881
  * the answer to a plugin item, starts no Turn, so the thread gets the same
1786
1882
  * recorded Message as the other linked Conversations, from
1787
- * `actOnReviewItem`. An expected failure, such as
1883
+ * `actOnInboxItem`. An expected failure, such as
1788
1884
  * an item that is already closed, goes to the person as an ephemeral
1789
1885
  * message.
1790
1886
  */
@@ -1792,22 +1888,22 @@ async function act(args) {
1792
1888
  const { services, target } = args;
1793
1889
  const actor = await resolveActingUser(services, args.payload, target);
1794
1890
  if (!actor) return;
1795
- const conversationId = await resolveSlackReviewItemCardConversationId({
1891
+ const conversationId = await resolveSlackInboxItemCardConversationId({
1796
1892
  channelId: target.channelId,
1797
1893
  teamId: actor.teamId,
1798
1894
  threadTs: target.threadTs
1799
1895
  });
1800
1896
  const delivery = {
1801
1897
  queue: services.queue,
1802
- show: createSlackReviewItemShow(() => services.adapter)
1898
+ show: createSlackInboxItemShow(() => services.adapter)
1803
1899
  };
1804
1900
  let recordOnly = args.action === "dismiss";
1805
1901
  let item;
1806
1902
  try {
1807
- const current = await readReviewItemForUser(actor.user, args.itemId);
1808
- const pluginAnswer = args.action === "submit" && isPluginReviewItem(current);
1903
+ const current = await readInboxItemForUser(actor.user, args.itemId);
1904
+ const pluginAnswer = args.action === "submit" && isPluginInboxItem(current);
1809
1905
  recordOnly ||= pluginAnswer;
1810
- item = await actOnReviewItem({
1906
+ item = await actOnInboxItem({
1811
1907
  action: args.action,
1812
1908
  ...recordOnly ? void 0 : { exceptConversationId: conversationId },
1813
1909
  firstCloseOnly: !pluginAnswer,
@@ -1817,7 +1913,7 @@ async function act(args) {
1817
1913
  ...args.answer ? { answer: args.answer(current) } : void 0
1818
1914
  });
1819
1915
  } catch (error) {
1820
- if (!(error instanceof ReviewItemActionError)) throw error;
1916
+ if (!(error instanceof InboxItemActionError)) throw error;
1821
1917
  await tellPerson(target, actor.slackUserId, error.message);
1822
1918
  await refreshCards(services, actor.user, args.itemId);
1823
1919
  return;
@@ -1832,13 +1928,13 @@ async function act(args) {
1832
1928
  messageId: args.messageId,
1833
1929
  messageTs: target.messageTs,
1834
1930
  payload: args.payload,
1835
- text: renderReviewItemMessage(item, change),
1931
+ text: renderInboxItemMessage(item, change),
1836
1932
  threadTs: target.threadTs,
1837
1933
  userId: actor.slackUserId
1838
- }), { reviewItemChange: reviewItemChangeRecord(item, change) });
1934
+ }), { reviewItemChange: inboxItemChangeRecord(item, change) });
1839
1935
  } catch (error) {
1840
- logException(error, "review_item.slack_input.persist.failed", { "app.review_item.id": item.id });
1841
- await deliverReviewItemChange({
1936
+ logException(error, "inbox_item.slack_input.persist.failed", { "app.inbox_item.id": item.id });
1937
+ await deliverInboxItemChange({
1842
1938
  change,
1843
1939
  delivery,
1844
1940
  item,
@@ -1849,7 +1945,7 @@ async function act(args) {
1849
1945
  function cardTarget(payload) {
1850
1946
  const channelId = parseSlackChannelId(payload.channel?.id);
1851
1947
  const messageTs = parseSlackMessageTs(payload.message?.ts);
1852
- if (!channelId || !messageTs) throw new Error("Slack review item payload is incomplete");
1948
+ if (!channelId || !messageTs) throw new Error("Slack inbox item payload is incomplete");
1853
1949
  return {
1854
1950
  channelId,
1855
1951
  messageTs,
@@ -1859,23 +1955,23 @@ function cardTarget(payload) {
1859
1955
  async function openAnswerForm(args) {
1860
1956
  const { target } = args;
1861
1957
  const triggerId = args.payload.trigger_id;
1862
- if (!triggerId) throw new Error("Slack review item form payload is missing a trigger id");
1958
+ if (!triggerId) throw new Error("Slack inbox item form payload is missing a trigger id");
1863
1959
  const actor = await resolveActingUser(args.services, args.payload, target);
1864
1960
  if (!actor) return;
1865
1961
  let item;
1866
1962
  try {
1867
- item = await readReviewItemForUser(actor.user, args.itemId);
1963
+ item = await readInboxItemForUser(actor.user, args.itemId);
1868
1964
  } catch (error) {
1869
- if (!(error instanceof ReviewItemActionError)) throw error;
1965
+ if (!(error instanceof InboxItemActionError)) throw error;
1870
1966
  await tellPerson(target, actor.slackUserId, error.message);
1871
1967
  return;
1872
1968
  }
1873
- if (!canActOnReviewItem(item, actor.user.id)) {
1969
+ if (!canActOnInboxItem(item, actor.user.id)) {
1874
1970
  await tellPerson(target, actor.slackUserId, item.status === "open" ? "Only an assignee can act on this item." : "This item is already closed.");
1875
1971
  await refreshCards(args.services, actor.user, item.id);
1876
1972
  return;
1877
1973
  }
1878
- const view = buildSlackReviewItemModal(item, {
1974
+ const view = buildSlackInboxItemModal(item, {
1879
1975
  ...target,
1880
1976
  itemId: item.id
1881
1977
  });
@@ -1885,8 +1981,8 @@ async function openAnswerForm(args) {
1885
1981
  view
1886
1982
  });
1887
1983
  }
1888
- /** Handle one click on a Review item card. */
1889
- async function handleSlackReviewItemClick(args) {
1984
+ /** Handle one click on an Inbox item card. */
1985
+ async function handleSlackInboxItemClick(args) {
1890
1986
  const { click, payload, services } = args;
1891
1987
  const target = cardTarget(payload);
1892
1988
  if (click.kind === "answer") {
@@ -1899,11 +1995,11 @@ async function handleSlackReviewItemClick(args) {
1899
1995
  return;
1900
1996
  }
1901
1997
  const actionTs = parseSlackMessageTs(args.action.action_ts);
1902
- if (!actionTs) throw new Error("Slack review item click payload is incomplete");
1998
+ if (!actionTs) throw new Error("Slack inbox item click payload is incomplete");
1903
1999
  const common = {
1904
2000
  inputTs: actionTs,
1905
2001
  itemId: click.itemId,
1906
- messageId: `slack-review-item:${actionTs}`,
2002
+ messageId: `slack-inbox-item:${actionTs}`,
1907
2003
  payload,
1908
2004
  services,
1909
2005
  target
@@ -1920,7 +2016,7 @@ async function handleSlackReviewItemClick(args) {
1920
2016
  action: "submit",
1921
2017
  answer: (item) => {
1922
2018
  const field = item.request && buttonUserInputField(item.request);
1923
- if (!field?.options.some((option) => option.label === click.label)) throw new ReviewItemActionError("conflict", "This card changed. Use the updated card.");
2019
+ if (!field?.options.some((option) => option.label === click.label)) throw new InboxItemActionError("conflict", "This card changed. Use the updated card.");
1924
2020
  return {
1925
2021
  requestId: item.id,
1926
2022
  values: { [field.id]: [click.label] }
@@ -1928,14 +2024,14 @@ async function handleSlackReviewItemClick(args) {
1928
2024
  }
1929
2025
  });
1930
2026
  }
1931
- /** Submit the answer of a Review item form. */
1932
- async function handleSlackReviewItemSubmission(args) {
2027
+ /** Submit the answer of an Inbox item form. */
2028
+ async function handleSlackInboxItemSubmission(args) {
1933
2029
  const view = args.payload.view;
1934
- const formTarget = parseSlackReviewItemFormTarget(view?.private_metadata);
2030
+ const formTarget = parseSlackInboxItemFormTarget(view?.private_metadata);
1935
2031
  const channelId = parseSlackChannelId(formTarget?.channelId);
1936
2032
  const messageTs = parseSlackMessageTs(formTarget?.messageTs);
1937
2033
  const threadTs = parseSlackMessageTs(formTarget?.threadTs);
1938
- if (!view?.id || !formTarget || !channelId || !messageTs || !threadTs) throw new Error("Slack review item form submission is incomplete");
2034
+ if (!view?.id || !formTarget || !channelId || !messageTs || !threadTs) throw new Error("Slack inbox item form submission is incomplete");
1939
2035
  await act({
1940
2036
  action: "submit",
1941
2037
  answer: (item) => item.request ? parseSlackUserInputSubmission({
@@ -1948,7 +2044,7 @@ async function handleSlackReviewItemSubmission(args) {
1948
2044
  },
1949
2045
  inputTs: slackMessageTsFromMs(Date.now()),
1950
2046
  itemId: formTarget.itemId,
1951
- messageId: `slack-review-item:${view.id}`,
2047
+ messageId: `slack-inbox-item:${view.id}`,
1952
2048
  payload: args.payload,
1953
2049
  services: args.services,
1954
2050
  target: {
@@ -1979,13 +2075,13 @@ async function handleAppHomeDisconnect(args) {
1979
2075
  });
1980
2076
  }
1981
2077
  /**
1982
- * Handle Slack interactions from App Home, Review item cards, and dashboard
2078
+ * Handle Slack interactions from App Home, Inbox item cards, and dashboard
1983
2079
  * link previews: block actions and submitted forms.
1984
2080
  */
1985
2081
  async function handleSlackInteractivePayload(args) {
1986
2082
  const spanAttributes = { userId: args.payload.user?.id?.trim() || void 0 };
1987
2083
  if (args.payload.type === "view_submission" && args.payload.view?.callback_id === "junior_review_item") {
1988
- await withSpan("chat.slack_review_item_submit", "chat.slack_review_item_submit", spanAttributes, () => handleSlackReviewItemSubmission({
2084
+ await withSpan("chat.slack_inbox_item_submit", "chat.slack_inbox_item_submit", spanAttributes, () => handleSlackInboxItemSubmission({
1989
2085
  payload: args.payload,
1990
2086
  services: args
1991
2087
  }));
@@ -1993,9 +2089,9 @@ async function handleSlackInteractivePayload(args) {
1993
2089
  }
1994
2090
  if (args.payload.type !== "block_actions") return;
1995
2091
  for (const action of args.payload.actions ?? []) {
1996
- const click = parseSlackReviewItemClick(action);
2092
+ const click = parseSlackInboxItemClick(action);
1997
2093
  if (click) {
1998
- await withSpan("chat.slack_review_item_click", "chat.slack_review_item_click", spanAttributes, () => handleSlackReviewItemClick({
2094
+ await withSpan("chat.slack_inbox_item_click", "chat.slack_inbox_item_click", spanAttributes, () => handleSlackInboxItemClick({
1999
2095
  action,
2000
2096
  click,
2001
2097
  payload: args.payload,
@@ -2683,12 +2779,12 @@ async function routeParsedMessage(args) {
2683
2779
  });
2684
2780
  const closeAnswered = async () => {
2685
2781
  if (message.author.isBot === true) return;
2686
- await closeReviewItemsAnsweredByReply({
2782
+ await closeInboxItemsAnsweredByReply({
2687
2783
  ...route === "subscribed" ? { canAnswer: isAuthorTrusted } : void 0,
2688
2784
  conversationId,
2689
2785
  delivery: {
2690
2786
  queue: args.queue,
2691
- show: createSlackReviewItemShow(() => args.adapter)
2787
+ show: createSlackInboxItemShow(() => args.adapter)
2692
2788
  },
2693
2789
  resolveUser: async () => {
2694
2790
  const teamId = args.installation.teamId;
@@ -3228,7 +3324,7 @@ async function publicArtifactGET(args) {
3228
3324
  headers: unpublishedArtifactHeaders(),
3229
3325
  status: 404
3230
3326
  });
3231
- return new Response(artifact.body, { headers: publicArtifactHeaders(artifact.contentType) });
3327
+ return new Response(artifact.body, { headers: publicArtifactHeaders(artifact.contentType, artifact.expiresAt) });
3232
3328
  } catch (error) {
3233
3329
  logException(error, "public_artifact.get.failed");
3234
3330
  return new Response("Internal Server Error", { status: 500 });
@@ -5054,7 +5150,7 @@ const MCP_SCOPES = [
5054
5150
  "conversations:read",
5055
5151
  "conversations:manage",
5056
5152
  "conversations:write",
5057
- "review_items:read",
5153
+ "inbox_items:read",
5058
5154
  "automations:read"
5059
5155
  ];
5060
5156
  /** What each scope lets the client do, as the consent page says it. */
@@ -5062,23 +5158,27 @@ const MCP_SCOPE_DESCRIPTIONS = {
5062
5158
  "conversations:read": "List and read the conversations that you started or take part in",
5063
5159
  "conversations:manage": "Archive, pin, and mark your conversations read, stop a running Turn, and cancel queued messages",
5064
5160
  "conversations:write": "Start conversations and send messages as you. Each message starts agent work",
5065
- "review_items:read": "List and read your review items",
5161
+ "inbox_items:read": "List and read your inbox items",
5066
5162
  "automations:read": "List and read the automations that you can see"
5067
5163
  };
5068
5164
  /** The `scope` value that names every scope. */
5069
5165
  const MCP_ALL_SCOPES = MCP_SCOPES.join(" ");
5166
+ const RENAMED_MCP_SCOPES = { "review_items:read": "inbox_items:read" };
5167
+ function scopeNames(value) {
5168
+ return value.split(" ").filter(Boolean).map((name) => RENAMED_MCP_SCOPES[name] ?? name);
5169
+ }
5070
5170
  /**
5071
5171
  * Parse a space-separated scope value into known scopes in canonical order.
5072
5172
  * Return `undefined` when it is empty or names an unknown scope.
5073
5173
  */
5074
5174
  function parseMcpScopes(value) {
5075
- const names = value.split(" ").filter(Boolean);
5175
+ const names = scopeNames(value);
5076
5176
  if (names.length === 0) return void 0;
5077
5177
  if (!names.every((name) => MCP_SCOPES.includes(name))) return void 0;
5078
5178
  return MCP_SCOPES.filter((scope) => names.includes(scope));
5079
5179
  }
5080
5180
  /** A stored scope value: known scopes, space-separated, in canonical order. */
5081
- const mcpScopeValueSchema = z.string().refine((value) => parseMcpScopes(value)?.join(" ") === value);
5181
+ const mcpScopeValueSchema = z.string().refine((value) => parseMcpScopes(value)?.join(" ") === scopeNames(value).join(" "));
5082
5182
  // src/api/mcp/oauth/authorization.ts
5083
5183
  /**
5084
5184
  * Own the OAuth authorization endpoint and its pending requests.
@@ -5092,7 +5192,7 @@ const AUTHORIZATION_TTL_MS = 6e5;
5092
5192
  const STATE_MAX_LENGTH = 1e3;
5093
5193
  const AUTHORIZATION_ID_PATTERN = /^[A-Za-z0-9_-]{43}$/;
5094
5194
  const CODE_CHALLENGE_PATTERN = /^[A-Za-z0-9_-]{43}$/;
5095
- const mcpAuthorizationSchema$1 = z.object({
5195
+ const mcpAuthorizationSchema = z.object({
5096
5196
  clientId: z.string().min(1),
5097
5197
  clientName: z.string().min(1).optional(),
5098
5198
  codeChallenge: z.string().regex(CODE_CHALLENGE_PATTERN),
@@ -5123,7 +5223,7 @@ function claimedKey(authorizationId) {
5123
5223
  */
5124
5224
  async function readMcpAuthorization(state, authorizationId) {
5125
5225
  if (!AUTHORIZATION_ID_PATTERN.test(authorizationId)) return void 0;
5126
- const authorization = await readRecord(state, authorizationKey(authorizationId), mcpAuthorizationSchema$1);
5226
+ const authorization = await readRecord(state, authorizationKey(authorizationId), mcpAuthorizationSchema);
5127
5227
  if (!authorization || authorization.expiresAtMs <= Date.now()) return;
5128
5228
  if (await state.get(claimedKey(authorizationId)) !== null) return void 0;
5129
5229
  return {
@@ -5386,7 +5486,7 @@ async function refreshGrant(args) {
5386
5486
  const token = await readRecord(args.state, key, tokenSchema);
5387
5487
  const grant = token ? await readGrant(args.state, token.grantId) : void 0;
5388
5488
  if (!token || !grant || grant.clientId !== args.clientId || args.resource !== void 0 && args.resource !== grant.resource) return invalidGrant("The refresh token is not valid.");
5389
- if (args.scope !== void 0 && parseMcpScopes(args.scope)?.join(" ") !== grant.scope) return {
5489
+ if (args.scope !== void 0 && parseMcpScopes(args.scope)?.join(" ") !== parseMcpScopes(grant.scope)?.join(" ")) return {
5390
5490
  description: `Refresh keeps the granted scope: ${grant.scope}.`,
5391
5491
  error: "invalid_scope",
5392
5492
  ok: false
@@ -5581,173 +5681,6 @@ async function handleMcpConsentPage(args) {
5581
5681
  state: authorization.state
5582
5682
  });
5583
5683
  }
5584
- // src/api/mcp/conversation.ts
5585
- /** Own the MCP view of one Conversation, shared by the conversation tools. */
5586
- /** MCP view of one Conversation. It omits dashboard-only fields. */
5587
- const mcpConversationSchema = z.object({
5588
- conversationId: z.string(),
5589
- title: z.string(),
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."),
5594
- surface: conversationSurfaceSchema.describe("Where it started: `slack`, `api` (the dashboard or MCP), `scheduler` (an automation), or `internal`."),
5595
- channelName: z.string().optional().describe("Slack channel name."),
5596
- locationUrl: z.string().optional().describe("Slack thread link."),
5597
- startedAt: z.string(),
5598
- lastSeenAt: z.string().describe("Time of the newest activity. archiveConversation takes this value."),
5599
- archivedAt: z.string().optional().describe("Set when anyone archived it. Archive applies to everyone."),
5600
- pinnedAt: z.string().optional().describe("Set when you pinned it."),
5601
- url: z.string().optional().describe("Dashboard link.")
5602
- }).strict();
5603
- /** Map a Conversation summary to its MCP view. */
5604
- function mcpConversation(summary) {
5605
- return {
5606
- conversationId: summary.conversationId,
5607
- title: summary.displayTitle,
5608
- status: summary.status,
5609
- turnActive: summary.turnActive,
5610
- treeState: summary.treeState,
5611
- watching: summary.watching,
5612
- surface: summary.surface,
5613
- channelName: summary.channelNameRedacted ? void 0 : summary.channelName,
5614
- locationUrl: summary.locationUrl,
5615
- startedAt: summary.startedAt,
5616
- lastSeenAt: summary.lastSeenAt,
5617
- archivedAt: summary.archivedAt ?? void 0,
5618
- pinnedAt: summary.pinnedAt ?? void 0,
5619
- url: getDashboardConversationLink(summary.conversationId)
5620
- };
5621
- }
5622
- /** Conversation id param shared by the conversation tools. */
5623
- const mcpConversationIdSchema = z.string().min(1).describe("Conversation id from searchConversations or createConversation.");
5624
- const mcpAttachmentsSchema = z.array(z.object({
5625
- filename: z.string(),
5626
- contentType: z.string(),
5627
- bytes: z.number().int()
5628
- }).strict()).optional();
5629
- function mcpAttachments(attachments) {
5630
- return attachments?.length ? attachments.map(({ bytes, contentType, filename }) => ({
5631
- bytes,
5632
- contentType,
5633
- filename
5634
- })) : void 0;
5635
- }
5636
- function mcpAuthor(identity) {
5637
- return identity?.fullName ?? identity?.slackUserName ?? identity?.email;
5638
- }
5639
- /** MCP view of one user or assistant Message. */
5640
- const mcpMessageSchema = z.object({
5641
- seq: z.number().int().describe("Position in the transcript. markConversationRead takes this value."),
5642
- messageId: z.string().describe("For a message that you sent, the `messageId` that sendMessage or createConversation returned."),
5643
- createdAt: z.string(),
5644
- role: z.enum(["assistant", "user"]),
5645
- author: z.string().optional(),
5646
- text: z.string(),
5647
- attachments: mcpAttachmentsSchema
5648
- }).strict();
5649
- /**
5650
- * Keep the user and assistant Messages of a report event page, in order.
5651
- * System Messages and Messages with no text or attachment are left out.
5652
- */
5653
- function mcpMessages(events) {
5654
- return events.flatMap((event) => {
5655
- const data = event.data;
5656
- if (data.type !== "message" || data.role === "system") return [];
5657
- const text = data.text ?? "";
5658
- const attachments = mcpAttachments(data.attachments);
5659
- if (!text && !attachments) return [];
5660
- const author = mcpAuthor(data.actorIdentity);
5661
- return [{
5662
- seq: event.seq,
5663
- messageId: data.messageId,
5664
- createdAt: event.createdAt,
5665
- role: data.role,
5666
- ...author ? { author } : void 0,
5667
- text,
5668
- ...attachments ? { attachments } : void 0
5669
- }];
5670
- });
5671
- }
5672
- /** Message text param shared by the tools that send a message. */
5673
- const mcpMessageTextSchema = z.string().trim().min(1).max(32e3).describe("Message text.");
5674
- /**
5675
- * Idempotency key param shared by the tools that send a message. A retry
5676
- * with the same key sends nothing new.
5677
- */
5678
- const mcpIdempotencyKeySchema = z.string().trim().min(1).max(200).optional().describe("Reuse the same key to retry without sending the message twice. Omit it to send a new message.");
5679
- /**
5680
- * MCP view of one accepted user Message that no Turn has read yet. It is not
5681
- * in the transcript, so it has no `seq`.
5682
- */
5683
- const mcpPendingMessageSchema = z.object({
5684
- messageId: z.string(),
5685
- createdAt: z.string(),
5686
- author: z.string().optional(),
5687
- text: z.string(),
5688
- attachments: mcpAttachmentsSchema,
5689
- delivery: conversationPendingMessageDeliverySchema.describe("`defer` waits for the running turn to end. `interrupt` joins the running turn at its next safe step.")
5690
- }).strict();
5691
- /** Pending Messages field shared by `getConversation` and the send tools. */
5692
- const mcpPendingMessagesSchema = z.array(mcpPendingMessageSchema).describe("Accepted messages that no turn has read yet, oldest first. A message leaves this list when a turn reads it.");
5693
- /** Authorization that a parked Turn waits for. */
5694
- const mcpAuthorizationSchema = z.object({
5695
- label: z.string(),
5696
- url: z.string()
5697
- }).strict().describe("Set when a turn waits for you to connect an account. Open `url` in a browser to continue.");
5698
- /**
5699
- * Read the Messages that wait for a Turn and the authorization that a parked
5700
- * Turn waits for. The caller must check that `user` is a participant.
5701
- */
5702
- async function readMcpPendingWork(user, conversationId) {
5703
- const report = await readConversationPendingMessages(conversationId, { viewer: user });
5704
- const pendingMessages = (report?.messages ?? []).flatMap((message) => {
5705
- if (message.text === void 0) return [];
5706
- const author = mcpAuthor(message.actorIdentity);
5707
- const attachments = mcpAttachments(message.attachments);
5708
- return [{
5709
- messageId: message.messageId,
5710
- createdAt: message.createdAt,
5711
- ...author ? { author } : void 0,
5712
- text: message.text,
5713
- ...attachments ? { attachments } : void 0,
5714
- delivery: message.delivery
5715
- }];
5716
- });
5717
- const authorization = report?.authorization;
5718
- return {
5719
- pendingMessages,
5720
- ...authorization ? { authorization: {
5721
- label: authorization.label,
5722
- url: authorization.authorizationUrl
5723
- } } : void 0
5724
- };
5725
- }
5726
- /**
5727
- * Read pending work for a send result. The message already landed, so a
5728
- * failed read drops these optional fields instead of turning the accepted
5729
- * send into a tool error that a client may retry.
5730
- */
5731
- async function readMcpPendingWorkAfterSend(user, conversationId) {
5732
- try {
5733
- return await readMcpPendingWork(user, conversationId);
5734
- } catch (error) {
5735
- logException(error, "mcp.pending_work.read.failed", { "gen_ai.conversation.id": conversationId });
5736
- return {};
5737
- }
5738
- }
5739
- /** `cursor` result field shared by getConversation and the send tools. */
5740
- const mcpCursorSchema = z.string().describe("Pass as `after` to getConversation to read the messages that come after this point.");
5741
- /** Result of a tool that sends a message. */
5742
- const mcpAcceptedMessageSchema = {
5743
- conversationId: z.string(),
5744
- messageId: z.string().describe("Id of your message in `pendingMessages`, and later in the transcript."),
5745
- status: z.enum(["accepted", "duplicate"]).describe("`duplicate` when the idempotency key was already used."),
5746
- pendingMessages: mcpPendingMessagesSchema.optional().describe("Accepted messages that no turn has read yet, oldest first. Missing when the read failed after your message was accepted; use getConversation."),
5747
- authorization: mcpAuthorizationSchema.optional(),
5748
- cursor: mcpCursorSchema,
5749
- url: z.string().optional().describe("Dashboard link.")
5750
- };
5751
5684
  // src/api/mcp/tool-context.ts
5752
5685
  /**
5753
5686
  * Return one structured tool result. The text block holds the same JSON, as
@@ -5788,80 +5721,24 @@ function apiToolError(error) {
5788
5721
  async function isConversationParticipant(user, conversationId) {
5789
5722
  return (await readConversationAccessFromSql(getDb(), [conversationId], user)).get(conversationId)?.isParticipant ?? false;
5790
5723
  }
5791
- // src/api/mcp/tools/archive-conversation.ts
5792
- /**
5793
- * Register `archiveConversation`. It archives or restores one Conversation,
5794
- * and optionally its children, for everyone.
5795
- */
5796
- function registerArchiveConversationTool(server, { user }) {
5797
- server.registerTool("archiveConversation", {
5798
- title: "Archive conversation",
5799
- description: "Archive one of your conversations, or restore it, for everyone in it. Archiving a conversation hides it and its child conversations. A restore fails while a conversation above it is archived. A new message from a person restores the conversation and the archived conversations above it.",
5800
- inputSchema: {
5801
- conversationId: mcpConversationIdSchema,
5802
- archived: z.boolean().default(true).describe("False restores an archived conversation."),
5803
- applyToChildren: z.boolean().default(false).describe("On archive, true also archives every child of this conversation at any depth; without it, the archive fails while any of its children is not archived. On restore, true also restores the children that were archived with this conversation."),
5804
- lastSeenAt: z.string().datetime().describe("`lastSeenAt` from searchConversations or getConversation. The archive fails when the conversation has newer activity.")
5805
- },
5806
- outputSchema: { archivedAt: z.string().nullable().describe("Null when the conversation is not archived.") },
5807
- annotations: {
5808
- destructiveHint: false,
5809
- idempotentHint: true,
5810
- openWorldHint: false,
5811
- readOnlyHint: false
5812
- }
5813
- }, async ({ applyToChildren, archived, conversationId, lastSeenAt }) => {
5814
- try {
5815
- return mcpToolResult(await archiveConversation(user, conversationId, {
5816
- applyToChildren,
5817
- archived,
5818
- lastSeenAt
5819
- }));
5820
- } catch (error) {
5821
- return apiToolError(error);
5822
- }
5823
- });
5824
- }
5825
- // src/api/mcp/tools/archive-done-conversations.ts
5724
+ // src/api/mcp/tools/api-operation.ts
5826
5725
  /**
5827
- * Register `archiveDoneConversations`, which archives every done
5828
- * Conversation of the user once.
5726
+ * Register an API operation as an MCP tool. A client error from the
5727
+ * operation becomes a tool error.
5829
5728
  */
5830
- function registerArchiveDoneConversationsTool(server, { user }) {
5831
- server.registerTool("archiveDoneConversations", {
5832
- title: "Archive done conversations",
5833
- description: "Archive all of your conversations whose work is done and that stayed quiet for your auto-archive wait time, once. It skips conversations that anyone pinned or turned auto-archive off for, and conversations that wait on a person. Archive applies to everyone in the conversation.",
5834
- inputSchema: {},
5835
- outputSchema: { archived: z.number().int().describe("Conversations archived.") },
5729
+ function registerApiOperationTool(server, operation, { queue, user }) {
5730
+ server.registerTool(operation.name, {
5731
+ title: operation.title,
5732
+ description: operation.description,
5733
+ inputSchema: operation.input,
5734
+ outputSchema: operation.output,
5836
5735
  annotations: {
5837
- destructiveHint: false,
5838
- idempotentHint: true,
5839
- openWorldHint: false,
5840
- readOnlyHint: false
5736
+ ...operation.annotations,
5737
+ openWorldHint: false
5841
5738
  }
5842
- }, async () => mcpToolResult(await archiveViewerDoneConversations(user)));
5843
- }
5844
- // src/api/mcp/tools/cancel-queued-messages.ts
5845
- /**
5846
- * Register `cancelQueuedMessages`, which drops the messages that wait for
5847
- * the running Turn and leaves the Turn running.
5848
- */
5849
- function registerCancelQueuedMessagesTool(server, { user }) {
5850
- server.registerTool("cancelQueuedMessages", {
5851
- title: "Cancel queued messages",
5852
- description: "Drop every message that waits for the running turn of one of your conversations. The running turn continues.",
5853
- inputSchema: { conversationId: mcpConversationIdSchema },
5854
- outputSchema: { cancelledMessages: z.number().int().describe("Messages dropped.") },
5855
- annotations: {
5856
- destructiveHint: true,
5857
- idempotentHint: true,
5858
- openWorldHint: false,
5859
- readOnlyHint: false
5860
- }
5861
- }, async ({ conversationId }) => {
5862
- if (!await isConversationParticipant(user, conversationId)) return mcpToolError("Conversation not found.");
5739
+ }, async (input) => {
5863
5740
  try {
5864
- return mcpToolResult({ cancelledMessages: (await cancelConversationPendingMessagesForViewer(user, conversationId)).cancelledCount });
5741
+ return mcpToolResult(await operation.run(user, input, { queue }));
5865
5742
  } catch (error) {
5866
5743
  return apiToolError(error);
5867
5744
  }
@@ -6013,22 +5890,6 @@ function registerGetAutomationTool(server, { user }) {
6013
5890
  });
6014
5891
  }
6015
5892
  // src/api/mcp/tools/get-conversation.ts
6016
- const mcpBriefSchema = conversationBriefSchema.omit({
6017
- keywords: true,
6018
- record: true,
6019
- schemaVersion: true
6020
- }).extend({ updatedAt: z.string() });
6021
- function mcpBrief(brief, updatedAt) {
6022
- return {
6023
- summary: brief.summary,
6024
- intent: brief.intent,
6025
- outcome: brief.outcome,
6026
- decisions: brief.decisions,
6027
- facts: brief.facts,
6028
- links: brief.links,
6029
- updatedAt
6030
- };
6031
- }
6032
5893
  const RECENT_EVENT_LIMIT = 100;
6033
5894
  const AFTER_EVENT_SCAN_LIMIT = 200;
6034
5895
  const AFTER_MESSAGE_LIMIT = 20;
@@ -6053,25 +5914,24 @@ async function readMessagesAfter(conversationId, afterSeq) {
6053
5914
  };
6054
5915
  }
6055
5916
  /**
6056
- * Register `getConversation`. It returns metadata, the Brief, and the last
5917
+ * Register `getConversation`. It returns metadata, the summary, and the last
6057
5918
  * Reply or the Messages after a cursor, not the whole transcript.
6058
5919
  */
6059
5920
  function registerGetConversationTool(server, { user }) {
6060
5921
  server.registerTool("getConversation", {
6061
5922
  title: "Get conversation",
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.",
5923
+ description: "Get one conversation: its metadata, including its summary, 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.",
6063
5924
  inputSchema: {
6064
5925
  conversationId: mcpConversationIdSchema,
6065
5926
  after: z.string().min(1).max(1e3).optional().describe("`cursor` from sendMessage, createConversation, or an earlier getConversation call.")
6066
5927
  },
6067
5928
  outputSchema: {
6068
5929
  conversation: mcpConversationSchema,
6069
- brief: mcpBriefSchema.optional(),
6070
5930
  lastReply: mcpMessageSchema.optional().describe("Newest assistant message in the recent events. Set only without `after`."),
6071
5931
  messages: z.array(mcpMessageSchema).optional().describe("User and assistant messages after `after`, oldest first. Set only with `after`."),
6072
5932
  hasMore: z.boolean().optional().describe("True when more messages already follow `cursor`. Call again now, also when `turnActive` is false."),
6073
5933
  pendingMessages: mcpPendingMessagesSchema,
6074
- authorization: mcpAuthorizationSchema.optional(),
5934
+ authorization: mcpAuthorizationSchema$1.optional(),
6075
5935
  cursor: mcpCursorSchema
6076
5936
  },
6077
5937
  annotations: {
@@ -6100,7 +5960,6 @@ function registerGetConversationTool(server, { user }) {
6100
5960
  const cursorSeq = newer?.seq ?? detail.events.at(-1)?.seq ?? -1;
6101
5961
  return mcpToolResult({
6102
5962
  conversation: mcpConversation(detail),
6103
- ...detail.brief ? { brief: mcpBrief(detail.brief.content, detail.brief.updatedAt) } : void 0,
6104
5963
  ...lastReply ? { lastReply } : void 0,
6105
5964
  ...newer ? { messages: newer.messages } : void 0,
6106
5965
  ...newer?.hasMore ? { hasMore: true } : void 0,
@@ -6112,15 +5971,15 @@ function registerGetConversationTool(server, { user }) {
6112
5971
  });
6113
5972
  });
6114
5973
  }
6115
- // src/api/mcp/review-item.ts
5974
+ // src/api/mcp/inbox-item.ts
6116
5975
  /**
6117
- * Own the MCP view of one Review item, shared by the review item tools.
5976
+ * Own the MCP view of one Inbox item, shared by the inbox item tools.
6118
5977
  *
6119
- * MCP Review items stay read-only. An answer sends a message to the linked
5978
+ * MCP Inbox items stay read-only. An answer sends a message to the linked
6120
5979
  * Conversations, which can start a Turn. A dismiss starts no Turn.
6121
5980
  */
6122
- /** MCP view of one Review item. Answers happen in Slack or the dashboard. */
6123
- const mcpReviewItemSchema = z.object({
5981
+ /** MCP view of one Inbox item. Answers happen in Slack or the dashboard. */
5982
+ const mcpInboxItemSchema = z.object({
6124
5983
  id: z.string(),
6125
5984
  kind: z.enum(["notice", "action"]),
6126
5985
  status: z.enum([
@@ -6143,9 +6002,9 @@ const mcpReviewItemSchema = z.object({
6143
6002
  updatedAt: z.string(),
6144
6003
  url: z.string().optional().describe("Dashboard link to answer it.")
6145
6004
  }).strict();
6146
- /** Map a Review item to its MCP view for one user. */
6147
- function mcpReviewItem(item, userId) {
6148
- const url = getDashboardReviewItemLink(item.id);
6005
+ /** Map an Inbox item to its MCP view for one user. */
6006
+ function mcpInboxItem(item, userId) {
6007
+ const url = getDashboardInboxItemLink(item.id);
6149
6008
  return {
6150
6009
  id: item.id,
6151
6010
  kind: item.kind,
@@ -6154,7 +6013,7 @@ function mcpReviewItem(item, userId) {
6154
6013
  body: item.body,
6155
6014
  ...item.request ? { question: item.request.question } : void 0,
6156
6015
  assignees: item.assignedToEveryone ? [] : item.assignees.map((person) => person.displayName ?? person.email),
6157
- canAct: canActOnReviewItem(item, userId),
6016
+ canAct: canActOnInboxItem(item, userId),
6158
6017
  conversationIds: item.conversationIds,
6159
6018
  ...item.subject ? { subject: {
6160
6019
  id: item.subject.id,
@@ -6166,14 +6025,14 @@ function mcpReviewItem(item, userId) {
6166
6025
  ...url ? { url } : void 0
6167
6026
  };
6168
6027
  }
6169
- // src/api/mcp/tools/get-review-item.ts
6170
- /** Register `getReviewItem`, which reads one Review item in any status. */
6171
- function registerGetReviewItemTool(server, { user }) {
6172
- server.registerTool("getReviewItem", {
6173
- title: "Get review item",
6174
- description: "Get one review item, open or closed.",
6175
- inputSchema: { id: z.string().min(1).describe("Review item id from searchReviewItems.") },
6176
- outputSchema: { item: mcpReviewItemSchema },
6028
+ // src/api/mcp/tools/get-inbox-item.ts
6029
+ /** Register `getInboxItem`, which reads one Inbox item in any status. */
6030
+ function registerGetInboxItemTool(server, { user }) {
6031
+ server.registerTool("getInboxItem", {
6032
+ title: "Get inbox item",
6033
+ description: "Get one inbox item, open or closed.",
6034
+ inputSchema: { id: z.string().min(1).describe("Inbox item id from searchInboxItems.") },
6035
+ outputSchema: { item: mcpInboxItemSchema },
6177
6036
  annotations: {
6178
6037
  destructiveHint: false,
6179
6038
  idempotentHint: true,
@@ -6182,9 +6041,9 @@ function registerGetReviewItemTool(server, { user }) {
6182
6041
  }
6183
6042
  }, async ({ id }) => {
6184
6043
  try {
6185
- return mcpToolResult({ item: mcpReviewItem(await readReviewItemForUser(user, id), user.id) });
6044
+ return mcpToolResult({ item: mcpInboxItem(await readInboxItemForUser(user, id), user.id) });
6186
6045
  } catch (error) {
6187
- if (error instanceof ReviewItemActionError) return mcpToolError(error.message);
6046
+ if (error instanceof InboxItemActionError) return mcpToolError(error.message);
6188
6047
  throw error;
6189
6048
  }
6190
6049
  });
@@ -6306,31 +6165,6 @@ function registerMarkConversationReadTool(server, { user }) {
6306
6165
  }
6307
6166
  });
6308
6167
  }
6309
- // src/api/mcp/tools/pin-conversation.ts
6310
- /** Register `pinConversation`, which pins or unpins for the user. */
6311
- function registerPinConversationTool(server, { user }) {
6312
- server.registerTool("pinConversation", {
6313
- title: "Pin conversation",
6314
- description: "Pin one of your top-level conversations, or unpin it. A child conversation cannot be pinned or unpinned; it uses the pin of its root. A pin applies only to you, restores an archived conversation, and keeps auto-archive from archiving it.",
6315
- inputSchema: {
6316
- conversationId: mcpConversationIdSchema,
6317
- pinned: z.boolean().default(true).describe("False unpins the conversation.")
6318
- },
6319
- outputSchema: { pinnedAt: z.string().nullable().describe("Null when the conversation is not pinned.") },
6320
- annotations: {
6321
- destructiveHint: false,
6322
- idempotentHint: true,
6323
- openWorldHint: false,
6324
- readOnlyHint: false
6325
- }
6326
- }, async ({ conversationId, pinned }) => {
6327
- try {
6328
- return mcpToolResult(await pinConversation(user, conversationId, { pinned }));
6329
- } catch (error) {
6330
- return apiToolError(error);
6331
- }
6332
- });
6333
- }
6334
6168
  // src/api/mcp/tools/search-conversations.ts
6335
6169
  /** Register `searchConversations`, which searches the Conversations of the user. */
6336
6170
  function registerSearchConversationsTool(server, { user }) {
@@ -6339,7 +6173,7 @@ function registerSearchConversationsTool(server, { user }) {
6339
6173
  title: "Search conversations",
6340
6174
  description: "Search your conversations and return up to 50, newest activity first. Only conversations that you started or take part in match.",
6341
6175
  inputSchema: {
6342
- q: feedQuery.q.describe("Text to search for in titles and Briefs."),
6176
+ q: feedQuery.q.describe("Text to search for in titles, summaries, and Annotation labels and titles."),
6343
6177
  status: feedQuery.status.describe("Return conversations that are not archived (default) or that are archived. A search ignores this filter.")
6344
6178
  },
6345
6179
  outputSchema: { conversations: z.array(mcpConversationSchema) },
@@ -6357,19 +6191,19 @@ function registerSearchConversationsTool(server, { user }) {
6357
6191
  })).conversations.map(mcpConversation) });
6358
6192
  });
6359
6193
  }
6360
- // src/api/mcp/tools/search-review-items.ts
6361
- /** Register `searchReviewItems`, which searches open Review items for the user. */
6362
- function registerSearchReviewItemsTool(server, { user }) {
6363
- server.registerTool("searchReviewItems", {
6364
- title: "Search review items",
6365
- description: "Search the open review items that you can see, newest change first. A review item is a question or notice that waits for a person.",
6194
+ // src/api/mcp/tools/search-inbox-items.ts
6195
+ /** Register `searchInboxItems`, which searches open Inbox items for the user. */
6196
+ function registerSearchInboxItemsTool(server, { user }) {
6197
+ server.registerTool("searchInboxItems", {
6198
+ title: "Search inbox items",
6199
+ description: "Search the open inbox items that you can see, newest change first. An inbox item is a question or notice that waits for a person.",
6366
6200
  inputSchema: {
6367
6201
  q: z.string().trim().min(1).max(200).optional().describe("Words to find in the title or body."),
6368
6202
  conversationId: z.string().min(1).optional().describe("Return only the items linked to this conversation."),
6369
6203
  limit: z.number().int().min(1).max(50).default(20).describe("Maximum number of items.")
6370
6204
  },
6371
6205
  outputSchema: {
6372
- items: z.array(mcpReviewItemSchema),
6206
+ items: z.array(mcpInboxItemSchema),
6373
6207
  truncated: z.boolean().describe("True when more items match.")
6374
6208
  },
6375
6209
  annotations: {
@@ -6379,14 +6213,14 @@ function registerSearchReviewItemsTool(server, { user }) {
6379
6213
  readOnlyHint: true
6380
6214
  }
6381
6215
  }, async ({ conversationId, limit, q }) => {
6382
- const items = await searchReviewItems(getDb(), conversationId ? await reviewItemReaderForUserInConversation(user, conversationId) : reviewItemReaderForUser(user), {
6216
+ const items = await searchInboxItems(getDb(), conversationId ? await inboxItemReaderForUserInConversation(user, conversationId) : inboxItemReaderForUser(user), {
6383
6217
  ...conversationId ? { conversationId } : void 0,
6384
6218
  limit: limit + 1,
6385
6219
  ...q ? { query: q } : void 0,
6386
6220
  statuses: ["open"]
6387
6221
  });
6388
6222
  return mcpToolResult({
6389
- items: items.slice(0, limit).map((item) => mcpReviewItem(item, user.id)),
6223
+ items: items.slice(0, limit).map((item) => mcpInboxItem(item, user.id)),
6390
6224
  truncated: items.length > limit
6391
6225
  });
6392
6226
  });
@@ -6424,15 +6258,10 @@ function registerSendMessageTool(server, { attachmentStorage, queue, user }) {
6424
6258
  }, {
6425
6259
  attachmentStorage,
6426
6260
  queue
6427
- });
6261
+ }, delivery);
6428
6262
  } catch (error) {
6429
6263
  return apiToolError(error);
6430
6264
  }
6431
- if (delivery === "interrupt") try {
6432
- await steerConversationPendingMessagesForViewer(user, conversationId, { inboundMessageIds: [accepted.messageId] });
6433
- } catch (error) {
6434
- logException(error, "mcp.send_message.steer.failed", { "gen_ai.conversation.id": conversationId });
6435
- }
6436
6265
  const messageSeq = accepted.status === "duplicate" ? await readConversationMessageEventSeq(getSqlExecutor(), accepted.conversationId, accepted.messageId) : void 0;
6437
6266
  return mcpToolResult({
6438
6267
  ...accepted,
@@ -6445,133 +6274,38 @@ function registerSendMessageTool(server, { attachmentStorage, queue, user }) {
6445
6274
  });
6446
6275
  });
6447
6276
  }
6448
- // src/api/mcp/tools/set-conversation-auto-archive.ts
6449
- /**
6450
- * Register `setConversationAutoArchive`, which overrides the user's
6451
- * auto-archive default for one Conversation.
6452
- */
6453
- function registerSetConversationAutoArchiveTool(server, { user }) {
6454
- server.registerTool("setConversationAutoArchive", {
6455
- title: "Set conversation auto-archive",
6456
- description: "Turn auto-archive on or off for one of your conversations. This overrides your default for that conversation only.",
6457
- inputSchema: {
6458
- conversationId: mcpConversationIdSchema,
6459
- autoArchive: z.boolean().describe("True lets auto-archive archive the conversation for everyone after its work is done. False keeps it from auto-archive for everyone.")
6460
- },
6461
- outputSchema: { autoArchive: z.boolean() },
6462
- annotations: {
6463
- destructiveHint: false,
6464
- idempotentHint: true,
6465
- openWorldHint: false,
6466
- readOnlyHint: false
6467
- }
6468
- }, async ({ autoArchive, conversationId }) => {
6469
- try {
6470
- return mcpToolResult(await setConversationAutoArchive(user, conversationId, autoArchive));
6471
- } catch (error) {
6472
- return apiToolError(error);
6473
- }
6474
- });
6475
- }
6476
- // src/api/mcp/tools/set-conversation-subscription.ts
6477
- /**
6478
- * Register `setConversationSubscription`, which subscribes or unsubscribes
6479
- * the user. It never changes another person's subscription.
6480
- */
6481
- function registerSetConversationSubscriptionTool(server, { user }) {
6482
- server.registerTool("setConversationSubscription", {
6483
- title: "Set conversation subscription",
6484
- description: "Subscribe to one of your conversations, or unsubscribe from it. Unsubscribe removes it only from your feed and clears your pin. When nobody else is subscribed, it archives the conversation for everyone. Your next mention of the bot in it subscribes you again.",
6485
- inputSchema: {
6486
- conversationId: mcpConversationIdSchema,
6487
- subscribed: z.boolean().describe("False unsubscribes you.")
6488
- },
6489
- outputSchema: {
6490
- archivedAt: z.string().nullable().describe("Set when the conversation is archived for everyone."),
6491
- subscribed: z.boolean()
6492
- },
6493
- annotations: {
6494
- destructiveHint: false,
6495
- idempotentHint: true,
6496
- openWorldHint: false,
6497
- readOnlyHint: false
6498
- }
6499
- }, async ({ conversationId, subscribed }) => {
6500
- try {
6501
- return mcpToolResult(await setConversationSubscription(user, conversationId, { subscribed }));
6502
- } catch (error) {
6503
- return apiToolError(error);
6504
- }
6505
- });
6506
- }
6507
- // src/api/mcp/tools/stop-conversation.ts
6508
- /**
6509
- * Register `stopConversation`, which stops the Conversation and every child
6510
- * agent below it until the person sends the Conversation input.
6511
- */
6512
- function registerStopConversationTool(server, { queue, user }) {
6513
- server.registerTool("stopConversation", {
6514
- title: "Stop conversation",
6515
- description: "Stop one of your conversations: its running turn and every child agent below it. Until you send the conversation a message, watch events of it and its child agents are saved to the conversation but start no turn. Messages that wait for the turn are dropped. It starts no new work.",
6516
- inputSchema: { conversationId: mcpConversationIdSchema },
6517
- outputSchema: {
6518
- status: z.enum(["no_work", "requested"]).describe("`requested` when the running turn was asked to stop. `no_work` when no turn was running. Child agents are stopped in both cases."),
6519
- droppedMessages: z.number().int().describe("Messages that waited for the turn and were dropped.")
6520
- },
6521
- annotations: {
6522
- destructiveHint: true,
6523
- idempotentHint: true,
6524
- openWorldHint: false,
6525
- readOnlyHint: false
6526
- }
6527
- }, async ({ conversationId }) => {
6528
- if (!await isConversationParticipant(user, conversationId)) return mcpToolError("Conversation not found.");
6529
- try {
6530
- const result = await stopConversationTurnForViewer(user, conversationId, { queue });
6531
- return mcpToolResult({
6532
- status: result.status,
6533
- droppedMessages: result.stoppedInboundMessageIds.length
6534
- });
6535
- } catch (error) {
6536
- return apiToolError(error);
6537
- }
6538
- });
6539
- }
6540
6277
  // src/api/mcp/server.ts
6541
6278
  /**
6542
- * Own the MCP server behind `/api/mcp`. Each tool lives in its own file under
6543
- * `tools/`.
6279
+ * Own the MCP server behind `/api/mcp`. A tool that the REST API also serves
6280
+ * is an API operation, registered by `tools/api-operation.ts`; each other tool
6281
+ * lives in its own file under `tools/`.
6544
6282
  *
6545
6283
  * Each request gets a new server and a stateless transport that answers with
6546
6284
  * JSON. No MCP session or SSE stream outlives the request, so the route works
6547
6285
  * on any app instance and is not limited by the live-stream duration.
6548
6286
  */
6549
- /** The tools that each scope unlocks. A client sees only its granted tools. */
6287
+ /** Operations that the REST API also serves. Each names its own scope. */
6288
+ const OPERATIONS = [...conversationOperations];
6289
+ /**
6290
+ * The hand-written tools that each scope unlocks. A client sees only its
6291
+ * granted tools.
6292
+ */
6550
6293
  const TOOLS_BY_SCOPE = {
6551
6294
  "conversations:read": [
6552
6295
  registerSearchConversationsTool,
6553
6296
  registerGetConversationTool,
6554
6297
  registerListConversationMessagesTool
6555
6298
  ],
6556
- "conversations:manage": [
6557
- registerArchiveConversationTool,
6558
- registerArchiveDoneConversationsTool,
6559
- registerPinConversationTool,
6560
- registerSetConversationAutoArchiveTool,
6561
- registerSetConversationSubscriptionTool,
6562
- registerMarkConversationReadTool,
6563
- registerStopConversationTool,
6564
- registerCancelQueuedMessagesTool
6565
- ],
6299
+ "conversations:manage": [registerMarkConversationReadTool],
6566
6300
  "conversations:write": [registerCreateConversationTool, registerSendMessageTool],
6567
- "review_items:read": [registerSearchReviewItemsTool, registerGetReviewItemTool],
6301
+ "inbox_items:read": [registerSearchInboxItemsTool, registerGetInboxItemTool],
6568
6302
  "automations:read": [registerSearchAutomationsTool, registerGetAutomationTool]
6569
6303
  };
6570
6304
  function readInstructions(agentName) {
6571
- return `${agentName} is a Slack agent. These tools read and manage your ${agentName} conversations, and read your review items and automations. They cannot send a message or start agent work. To ask ${agentName} for work or to answer a review item, use the Slack or dashboard link in a result.`;
6305
+ return `${agentName} is a Slack agent. These tools read and manage your ${agentName} conversations, and read your inbox items and automations. They cannot send a message or start agent work. To ask ${agentName} for work or to answer an inbox item, use the Slack or dashboard link in a result.`;
6572
6306
  }
6573
6307
  function writeInstructions(agentName) {
6574
- return `${agentName} is a Slack agent. These tools read and manage your ${agentName} conversations, and read your review items and automations. createConversation and sendMessage send a message as you, and ${agentName} works on it in the background. They return a \`cursor\`. Call getConversation with \`after\` set to the newest \`cursor\` to read the new messages. Repeat until \`status\` is not \`active\` and \`hasMore\` is not set. \`authorization\` means a turn waits for you to connect an account. To answer a review item, use the dashboard link in a result.`;
6308
+ return `${agentName} is a Slack agent. These tools read and manage your ${agentName} conversations, and read your inbox items and automations. createConversation and sendMessage send a message as you, and ${agentName} works on it in the background. They return a \`cursor\`. Call getConversation with \`after\` set to the newest \`cursor\` to read the new messages. Repeat until \`status\` is not \`active\` and \`hasMore\` is not set. \`authorization\` means a turn waits for you to connect an account. To answer an inbox item, use the dashboard link in a result.`;
6575
6309
  }
6576
6310
  /** Build the MCP server for one authenticated user and granted scopes. */
6577
6311
  function createMcpServer(context, scopes) {
@@ -6580,6 +6314,7 @@ function createMcpServer(context, scopes) {
6580
6314
  version: JUNIOR_VERSION
6581
6315
  }, { instructions: scopes.includes("conversations:write") ? writeInstructions(botConfig.userName) : readInstructions(botConfig.userName) });
6582
6316
  for (const scope of scopes) for (const register of TOOLS_BY_SCOPE[scope]) register(server, context);
6317
+ for (const operation of OPERATIONS) if (scopes.includes(operation.scope)) registerApiOperationTool(server, operation, context);
6583
6318
  return server;
6584
6319
  }
6585
6320
  /** Answer one Streamable HTTP POST for an authenticated user. */
@@ -7145,6 +6880,7 @@ function dashboardHostRoutePaths(dashboard, authenticatedRoutes = []) {
7145
6880
  "/api/notifications",
7146
6881
  "/api/notifications/*",
7147
6882
  "/api/images/*",
6883
+ "/api/lead",
7148
6884
  "/api/objects",
7149
6885
  "/api/stats",
7150
6886
  "/api/versions",
@@ -7155,8 +6891,8 @@ function dashboardHostRoutePaths(dashboard, authenticatedRoutes = []) {
7155
6891
  "/api/people",
7156
6892
  "/api/people/*",
7157
6893
  "/api/inbox/*",
7158
- "/api/review-items",
7159
- "/api/review-items/*",
6894
+ "/api/inbox-items",
6895
+ "/api/inbox-items/*",
7160
6896
  "/api/personal-tokens",
7161
6897
  "/api/personal-tokens/*",
7162
6898
  "/api/service-accounts",
@@ -7351,7 +7087,6 @@ async function createApp(options) {
7351
7087
  const previousConfigDefaults = getConfigDefaults();
7352
7088
  const previousSandboxResources = getSandboxResourceConfig();
7353
7089
  const previousExperimentalFeatures = getExperimentalFeatures();
7354
- const previousBriefsConfig = setBriefsConfig(options?.briefs);
7355
7090
  const previousEventEmbeddingsConfig = setEventEmbeddingsConfig(options?.eventEmbeddings);
7356
7091
  const previousMemoryConfig = setMemoryConfig(options?.memory);
7357
7092
  const previousDashboardLinkOptions = setDashboardConversationLinkOptions(dashboard);
@@ -7364,7 +7099,6 @@ async function createApp(options) {
7364
7099
  restoreRuntimeConfig(previousRuntimeConfig);
7365
7100
  setSandboxResourceConfig(previousSandboxResources);
7366
7101
  setExperimentalFeatures(previousExperimentalFeatures);
7367
- setBriefsConfig(previousBriefsConfig);
7368
7102
  setEventEmbeddingsConfig(previousEventEmbeddingsConfig);
7369
7103
  setMemoryConfig(previousMemoryConfig);
7370
7104
  setDashboardConversationLinkOptions(previousDashboardLinkOptions);
@@ -7407,7 +7141,7 @@ async function createApp(options) {
7407
7141
  pluginRoutes = getPluginRoutes({
7408
7142
  dispatchForIdentity,
7409
7143
  events,
7410
- showReviewItem: createSlackReviewItemShow(getProductionSlackAdapter)
7144
+ showInboxItem: createSlackInboxItemShow(getProductionSlackAdapter)
7411
7145
  });
7412
7146
  if (dashboard && !dashboard.disabled) {
7413
7147
  pluginApiRoutes = getPluginApiRoutes();
@@ -7628,7 +7362,7 @@ async function createApp(options) {
7628
7362
  conversationWorkQueue,
7629
7363
  dispatchForIdentity,
7630
7364
  events,
7631
- showReviewItem: createSlackReviewItemShow(getProductionSlackAdapter)
7365
+ showInboxItem: createSlackInboxItemShow(getProductionSlackAdapter)
7632
7366
  });
7633
7367
  });
7634
7368
  app.get("/api/internal/retention", (c) => {