@sentry/junior 0.311.0 → 0.313.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 (120) hide show
  1. package/dist/{adapter-B1wujchl.js → adapter-CYAvJzZS.js} +1 -1
  2. package/dist/{adapter-context-G2M0y6rP.js → adapter-context-CVsHoVSf.js} +2 -2
  3. package/dist/{admin-DCiBhUT1.js → admin-Cyhb4TwZ.js} +1 -1
  4. package/dist/{agent-runner-BVHPUIc8.js → agent-runner-B5y9MsT-.js} +3487 -3493
  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 +294 -311
  9. package/dist/{app-Cw5Vy6H6.d.ts → app-DA8-hCMj.d.ts} +2 -9
  10. package/dist/app.d.ts +1 -1
  11. package/dist/app.js +336 -604
  12. package/dist/{background-compaction-queue-CJDnWVOJ.js → background-compaction-queue-iZXadLV3.js} +60 -85
  13. package/dist/{catalog-runtime-DMY3VV-D.js → catalog-runtime-kkE3hvCX.js} +1 -1
  14. package/dist/channel-access-mt7K6dPh.js +221 -0
  15. package/dist/cli/chat.js +18 -19
  16. package/dist/cli/check.js +3 -3
  17. package/dist/cli/init.js +0 -1
  18. package/dist/cli/main.js +3 -7
  19. package/dist/cli/plugins.js +4 -4
  20. package/dist/cli/run.d.ts +1 -2
  21. package/dist/cli/run.js +1 -2
  22. package/dist/cli/snapshot-create.js +5 -5
  23. package/dist/cli/upgrade.d.ts +1 -1
  24. package/dist/cli/upgrade.js +3 -3
  25. package/dist/{config-BrXDQefC.js → config-CWbwKj0j.js} +59 -27
  26. package/dist/{continue-in-slack-DNXSC9So.js → continue-in-slack-CxyFzdlF.js} +7 -8
  27. package/dist/{conversation-feed-DkinDu5o.js → conversation-feed-BEXLD3Me.js} +86 -21
  28. package/dist/{conversation-privacy-DxttrKb9.js → conversation-privacy-BrMiDN61.js} +1 -1
  29. package/dist/{conversation-turn-DWw7Xhdr.js → conversation-turn-B35eu0uz.js} +78 -56
  30. package/dist/{credential-sync-Bk8wGb8Y.js → credential-sync-DWTOEQrm.js} +15 -15
  31. package/dist/{projection-Cns7XwWa.js → credentialed-Dyv8b-lu.js} +16306 -20732
  32. package/dist/{db-7ETESH44.d.ts → db-DYGcXYl3.d.ts} +11 -6
  33. package/dist/{db-DTxzH7u5.js → db-PwSRzWWn.js} +181 -100
  34. package/dist/{executor-DqTiYj9S.js → executor-CgWyWfYz.js} +117 -99
  35. package/dist/{html-B9Sl4Axb.js → html-DidUcRhI.js} +6 -6
  36. package/dist/ingest-B0AggUEC.js +7931 -0
  37. package/dist/{install-Sg4ePfLl.js → install-2urLLXNt.js} +2 -2
  38. package/dist/instrumentation.js +3 -3
  39. package/dist/{lineage-BHAMpNKr.js → lineage-BXplQAVH.js} +2 -2
  40. package/dist/{stop-CYsfc0Ed.js → list-DyIyReSV.js} +709 -475
  41. package/dist/{logging-FjclQsXu.js → logging-DNt-qOIO.js} +1 -1
  42. package/dist/{schedule-BLJ476XQ.js → media-B0pZJ0bG.js} +1058 -11
  43. package/dist/{message-CJ7_RL50.js → message-Z5YKC-Af.js} +35 -28
  44. package/dist/{model-input-CMLh4Cwq.js → model-input-BhPJYdSV.js} +3 -3
  45. package/dist/nitro.d.ts +1 -1
  46. package/dist/nitro.js +4 -3
  47. package/dist/{oauth-callback-server-RVcbiDjL.js → oauth-callback-server-ByvDdcdY.js} +2 -2
  48. package/dist/{oauth-relay-Bu9kkaQu.js → oauth-relay-D-kK0yoN.js} +1 -1
  49. package/dist/{registry-BPwuOP2O.js → registry-POH4bZC4.js} +1 -1
  50. package/dist/reporting-window-C4dbzDiR.js +124 -0
  51. package/dist/request-deadline-BUiRYQYj.js +24 -0
  52. package/dist/{resolve-BK29bBry.js → resolve-CWtBNSKP.js} +3 -3
  53. package/dist/{runner-BcAE-cJm.js → runner-CsZ_VRxp.js} +14 -16
  54. package/dist/{sandbox-egress-signals-C-q0go5b.js → sandbox-egress-signals-FbCk1FkN.js} +1 -1
  55. package/dist/{schema-DYcJeV7d.d.ts → schema-DBf18QPS.d.ts} +2773 -3630
  56. package/dist/{schema-BLgSZXcL.js → schema-DojR2uCL.js} +106 -121
  57. package/dist/{service-account-iJoCtkHR.js → service-account-CDYb9hfX.js} +3 -3
  58. package/dist/{service-account-gN0zqf0S.js → service-account-o15pZWcJ.js} +5 -5
  59. package/dist/{skills-BoZ80epJ.js → skills-B0jP4whm.js} +2 -2
  60. package/dist/{slack-conversation-unfurl-CogYrITA.js → slack-conversation-unfurl-D26t9kBC.js} +9 -9
  61. package/dist/{spawn-Dk92r7mX.js → spawn-BjljgExZ.js} +14 -32
  62. package/dist/start-conversation-DbVujrwO.js +755 -0
  63. package/dist/{state-DH3Cmgp3.js → state-BTawTCme.js} +4 -4
  64. package/dist/statuses-BKwqCPhj.js +69 -0
  65. package/dist/store-CjXrp-Up.js +492 -0
  66. package/dist/task-queue-Cwlatjz3.js +90 -0
  67. package/dist/task-runner--Ke8KSMf.js +1432 -0
  68. package/dist/{thread-context-BW2BsQbH.js → thread-context-B8exINEe.js} +6 -7
  69. package/dist/turn-membership-DTR3SaKD.js +5859 -0
  70. package/dist/{validation-DrJd0nnq.js → validation-Ce0qbMlT.js} +1 -1
  71. package/dist/{task-queue-C_zldF5J.js → vercel-queue-q4z8w5QO.js} +93 -172
  72. package/dist/{version-CNKZ8owc.js → version-DFh4n9nr.js} +1 -1
  73. package/dist/version.js +1 -1
  74. package/dist/{warmup-BWdHew2H.js → warmup-D5hzqTcp.js} +4853 -13605
  75. package/dist/web-message-id-C6P83ans.js +10 -0
  76. package/dist/{worker-t9qpu_Zx.js → worker-CDg9Lbpg.js} +20 -7
  77. package/migrations/0143_todos.sql +14 -0
  78. package/migrations/0144_inbox_items.sql +32 -0
  79. package/migrations/0145_todo_changed_by_agent.sql +1 -0
  80. package/migrations/0146_inbox_item_subject_title_parts.sql +1 -0
  81. package/migrations/0147_inbox_snooze_wake_reason.sql +1 -0
  82. package/migrations/0148_authorization_request_index.sql +1 -0
  83. package/migrations/0149_conversation_metadata.sql +10 -0
  84. package/migrations/0150_conversation_metadata_fill.sql +39 -0
  85. package/migrations/0151_conversation_search_index.sql +1 -0
  86. package/migrations/0152_inbox_item_legacy_automation_keys.sql +21 -0
  87. package/migrations/0153_artifact_expiry.sql +1 -0
  88. package/migrations/0154_artifact_permanent_sha_index.sql +1 -0
  89. package/migrations/0155_artifact_drop_public_sha_index.sql +3 -0
  90. package/migrations/0156_conversation_kind_lead.sql +6 -0
  91. package/migrations/0157_conversation_lead_actor_index.sql +1 -0
  92. package/migrations/0158_keep_legacy_archive_columns.sql +5 -0
  93. package/migrations/0159_conversation_embeddings_fk_validate.sql +5 -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/0158_snapshot.json +6515 -0
  110. package/migrations/meta/0159_snapshot.json +6515 -0
  111. package/migrations/meta/_journal.json +120 -1
  112. package/package.json +6 -6
  113. package/skills/design-automation-skill/SKILL.md +108 -0
  114. package/dist/briefs-BDjnug6Y.js +0 -395
  115. package/dist/conversation-ca__NDQW.js +0 -1063
  116. package/dist/prompt-CDqcsDYC.js +0 -910
  117. package/dist/store-DmmMIrQi.js +0 -335
  118. package/dist/task-runner-C7oCJQIx.js +0 -294
  119. package/dist/turn-session-routing-Xh_2nSQe.js +0 -261
  120. package/dist/web-message-id-Ch5dPq-a.js +0 -306
package/dist/app.js CHANGED
@@ -1,43 +1,46 @@
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-Dyv8b-lu.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-CWbwKj0j.js";
3
+ import { Ct as isPluginInboxItem, In as touchConversationDetail, It as readActorIdentity, Kt as parseAvatarUrl, Ln as createSlackDestination, Qt as resolveActorIdentityId, U as conversationCostOf, Vt as resolveViewerUser, a as getConversationStore, m as withConversationEventLock, o as getDb, p as deleteMessageLinks, r as getConversationEventStore, s as getSqlExecutor, sn as recordGoogleSignIn, st as canActOnInboxItem, t as closeDb, vn as readConversationAccessFromSql, vt as inboxItemReaderForUser, w as withConversationMutationLock, yt as inboxItemReaderForUserInConversation } from "./db-PwSRzWWn.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-DNt-qOIO.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-B5y9MsT-.js";
6
+ import { $ as recordSubagentEnded, A as annotationKeyDigest, At as parseEmail, Dt as findTrustedUser, L as createEndStoppedChildWork, Ln as getExperimentalFeatures, M as stopConversation, Mt as setTrustConfig, Ot as isAllowedDomain, R as enqueueAgentInvocationResult, Rn as isExperimentalFeatureEnabled, Sn as deleteTodos, _ as enqueueAgentInvocation, _n as renderTaskInput, ct as listPendingAgentInvocationMailboxAppends, j as decodeAnnotationRef, k as renderSlackObjectCard, kt as isTrustedSlackAuthor, lt as listPendingAgentInvocationResults, o as getAuthPausedConversationTurnId, t as ingestEvent, zn as setExperimentalFeatures } from "./ingest-B0AggUEC.js";
7
+ import { a as getSandboxResourceConfig, s as setSandboxResourceConfig } from "./install-2urLLXNt.js";
8
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-kkE3hvCX.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-DyIyReSV.js";
10
+ import { n as validatePluginRegistrations, t as validatePluginEgressCredentialHooks } from "./validation-Ce0qbMlT.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-CYAvJzZS.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-CgWyWfYz.js";
14
+ import { F as listActiveConversationIds, M as getConversation, N as getConversationWorkState, T as clearExpiredConversationLease, _ as appendAndEnqueueInboundMessage, dn as hasRunnableConversationWork, hn as pruneActiveConversation, ht as settleConversationTitleWork, j as ensureConversationWake, lt as appendConversationMessages, m as coerceThreadConversationState, pn as isInvalidConversationRecordError, sn as CONVERSATION_WORK_STALE_ENQUEUE_MS } from "./turn-membership-DTR3SaKD.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-B0pZJ0bG.js";
17
+ import { Bn as readViewerAutomations, Gn as automationCardStatus, In as readViewerAutomationExecutions, Jn as findAutomationSkill, Pn as ViewerTaskNotFoundError, Rn as readViewerAutomationSummary, T as processWorkspaceSnapshotJob, Xn as effectiveTaskOutcomes, Yn as missingAutomationSkillReason, gt as renderInboxItemMessage, ht as inboxItemChangeRecord, mt as deliverInboxItemChange, p as processBackgroundCompaction, ut as markConversationRead, zt as parseSlackThreadId } from "./warmup-D5hzqTcp.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-q4z8w5QO.js";
19
+ import { o as requestAttachmentDeletion, t as collectAttachmentGarbage } from "./store-CjXrp-Up.js";
20
+ import { c as conversationTurnIdForMessage, d as recordWebConversationActivity, f as webActorFromUser, h as collectAttachmentUploadGarbage, l as createAndEnqueueConversation, s as appendAndEnqueueWebMessage } from "./start-conversation-DbVujrwO.js";
19
21
  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";
22
+ import { a as GET$5, i as publishAppHomeView, r as GET$6, t as receiveLocalOAuthCredential } from "./credential-sync-DWTOEQrm.js";
21
23
  import { t as nameRequestRoute } from "./sentry-route-name-C6EIzAGP.js";
22
24
  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
25
  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";
26
+ import { a as resolveSlackActingUser, i as unfurlDashboardConversationLinks, n as handleSlackContinueHereClick, o as isSlackWorkspaceMember, s as slackWorkspaceBotId, t as SLACK_CONTINUE_HERE_ACTION_ID } from "./slack-conversation-unfurl-D26t9kBC.js";
27
+ import { l as unlinkProvider, n as renderHtmlPage, r as requestHasSameOrigin, t as escapeHtml } from "./html-DidUcRhI.js";
28
+ import { n as verifySlackSignature, t as runWithSlackInstallation } from "./adapter-context-CVsHoVSf.js";
29
+ import { s as joinPublicChannel } from "./channel-access-mt7K6dPh.js";
30
+ import { c as registerVercelCacheWarmupDevConsumer, d as WORKSPACE_SNAPSHOT_JOB_QUEUE_TOPIC, i as verifyBackgroundCompactionMessage, m as verifyWorkspaceSnapshotJobMessage, o as cacheWarmupQueueConsumer, r as vercelBackgroundCompactionQueue, s as createVercelCacheWarmupCallback, t as BACKGROUND_COMPACTION_QUEUE_TOPIC, u as queueCallback } from "./background-compaction-queue-iZXadLV3.js";
31
+ import { t as processConversationWork } from "./worker-CDg9Lbpg.js";
32
+ import { t as bindMessageAgent } from "./message-Z5YKC-Af.js";
33
+ import { t as bindSpawnAgent } from "./spawn-BjljgExZ.js";
34
+ import { a as pluginTaskQueueConsumer, n as createVercelPluginTaskCallback, o as registerVercelPluginTaskDevConsumer, s as sendVercelPluginTask } from "./task-queue-Cwlatjz3.js";
35
+ import { a as readConversationEventPage, c as readConversationLastEventSeq, l as readConversationMessageEventSeq, o as readConversationEventPageAfter, t as processPluginTask } from "./task-runner--Ke8KSMf.js";
36
+ import { t as JUNIOR_VERSION } from "./version-DFh4n9nr.js";
37
+ import { b as conversationPendingMessageDeliverySchema, t as conversationFeedQuerySchema } from "./conversation-feed-BEXLD3Me.js";
35
38
  import { createRequire } from "node:module";
36
39
  import { Hono } from "hono";
37
40
  import * as z from "zod";
38
41
  import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
39
42
  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";
43
+ import { and, asc, desc, eq, gt, gte, inArray, isNotNull, isNull, lt, lte, ne, notExists, or, sql } from "drizzle-orm";
41
44
  import { pathToFileURL } from "node:url";
42
45
  import { Message, ThreadImpl } from "chat";
43
46
  import net from "node:net";
@@ -55,7 +58,7 @@ import { betterAuth } from "better-auth/minimal";
55
58
  const BACKFILL_BUDGET_MS$1 = 1e4;
56
59
  const BACKFILL_CLAIM_TTL_MS$1 = 6e4;
57
60
  const BACKFILL_DONE_TTL_MS$1 = 36e5;
58
- /** Embed the latest Briefs that have no vector of the embedder's model. */
61
+ /** Embed the Conversation metadata that has no vector of the embedder's model. */
59
62
  async function runConversationEmbeddingBackfill(embedder) {
60
63
  const key = `junior:conversation_embeddings:backfill:${embedder.provider}:${embedder.model}`;
61
64
  const state = getStateAdapter();
@@ -76,79 +79,142 @@ async function runConversationEmbeddingBackfill(embedder) {
76
79
  // src/chat/conversations/event-search-backfill.ts
77
80
  const ACTIVE_WINDOW_MS = 6048e5;
78
81
  const BACKFILL_BUDGET_MS = 1e4;
79
- const BACKFILL_CLAIM_TTL_MS = 6e4;
82
+ const SCAN_STATEMENT_TIMEOUT_MS = 5e3;
83
+ const BACKFILL_CLAIM_TTL_MS = 3e5;
80
84
  const BACKFILL_DONE_TTL_MS = 6e5;
85
+ const BACKFILL_PASS_TTL_MS = 864e5;
81
86
  const MAX_LEXEME_EVENTS_PER_RUN = 1e3;
82
87
  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;
88
+ const CONVERSATION_PAGE_SIZE = 50;
89
+ const QUERY_CANCELED = "57014";
90
+ const passCursorSchema = z.object({
91
+ at: z.string(),
92
+ conversationId: z.string()
93
+ });
94
+ const backfillPassSchema = z.object({
95
+ after: passCursorSchema.nullable(),
96
+ conversations: z.number(),
97
+ events: z.number(),
98
+ skipped: z.number()
99
+ });
100
+ const NEW_PASS = {
101
+ after: null,
102
+ conversations: 0,
103
+ events: 0,
104
+ skipped: 0
105
+ };
106
+ async function withScanTimeout(db, run) {
107
+ return await db.transaction(async (tx) => {
108
+ await tx.execute(sql`SELECT set_config('statement_timeout', ${String(SCAN_STATEMENT_TIMEOUT_MS)}, true)`);
109
+ return await run(tx);
110
+ });
111
+ }
112
+ async function listActiveConversations(db, args) {
113
+ const conversations = juniorConversations;
114
+ const after = args.after;
115
+ return await withScanTimeout(db, async (tx) => await tx.select({
116
+ at: sql`to_char(${conversations.lastActivityAt} at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`,
117
+ conversationId: conversations.conversationId
118
+ }).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));
119
+ }
120
+ async function hasMissingVector(tx, embedder, conversationId) {
90
121
  const lexemes = juniorConversationEventLexemes;
91
122
  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);
123
+ 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;
124
+ }
125
+ async function indexConversation(db, args) {
126
+ const attempt = await withLock(getStateAdapter(), eventIndexLockKey(args.conversationId), async () => {
127
+ let lexemes;
128
+ let vectorMissing;
129
+ try {
130
+ [lexemes, vectorMissing] = await withScanTimeout(db, async (tx) => {
131
+ return [await storeConversationEventLexemes(tx, args.conversationId, args.lexemeRoom), args.embedder ? await hasMissingVector(tx, args.embedder, args.conversationId) : false];
132
+ });
133
+ } catch (error) {
134
+ if (!isPostgresErrorCode(error, QUERY_CANCELED)) throw error;
135
+ return { kind: "skipped" };
136
+ }
137
+ const vectors = args.embedder && vectorMissing ? await embedConversationEvents(db, args.embedder, args.conversationId, {
138
+ deadlineMs: args.deadlineMs,
139
+ maxEvents: args.vectorRoom
140
+ }) : 0;
141
+ return {
142
+ kind: "indexed",
143
+ lexemes,
144
+ vectors,
145
+ more: lexemes >= args.lexemeRoom || vectorMissing && (vectors >= args.vectorRoom || Date.now() >= args.deadlineMs)
146
+ };
147
+ }, { ttlMs: EVENT_INDEX_LOCK_TTL_MS });
148
+ return attempt.acquired ? attempt.value : { kind: "skipped" };
102
149
  }
103
150
  /**
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.
151
+ * Continue `pass` over the Conversations with activity in the last week:
152
+ * store their missing lexemes, and missing vectors when `embedder` is set,
153
+ * until the deadline or the event limits. Return what the run did and the
154
+ * pass to continue next.
107
155
  */
108
156
  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 = {
157
+ const sinceMs = args.nowMs - ACTIVE_WINDOW_MS;
158
+ const run = {
159
+ conversations: 0,
115
160
  lexemes: 0,
161
+ skipped: 0,
116
162
  vectors: 0
117
163
  };
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;
164
+ let after = args.pass.after;
165
+ const progress = () => ({
166
+ after,
167
+ conversations: args.pass.conversations + run.conversations,
168
+ events: args.pass.events + run.lexemes + run.vectors,
169
+ skipped: args.pass.skipped + run.skipped
170
+ });
171
+ while (true) {
172
+ if (Date.now() >= args.deadlineMs) return {
173
+ outcome: "limit_reached",
174
+ pass: progress(),
175
+ run
176
+ };
177
+ const page = await listActiveConversations(args.db, {
178
+ after,
179
+ sinceMs
180
+ });
181
+ for (const conversation of page) {
182
+ const lexemeRoom = MAX_LEXEME_EVENTS_PER_RUN - run.lexemes;
183
+ const vectorRoom = MAX_VECTOR_EVENTS_PER_RUN - run.vectors;
184
+ if (Date.now() >= args.deadlineMs || lexemeRoom <= 0 || args.embedder && vectorRoom <= 0) return {
185
+ outcome: "limit_reached",
186
+ pass: progress(),
187
+ run
188
+ };
189
+ const result = await indexConversation(args.db, {
190
+ conversationId: conversation.conversationId,
191
+ deadlineMs: args.deadlineMs,
192
+ ...args.embedder ? { embedder: args.embedder } : void 0,
193
+ lexemeRoom,
194
+ vectorRoom
195
+ });
196
+ run.conversations += 1;
197
+ if (result.kind === "skipped") run.skipped += 1;
198
+ else {
199
+ run.lexemes += result.lexemes;
200
+ run.vectors += result.vectors;
201
+ if (result.more) return {
202
+ outcome: "limit_reached",
203
+ pass: progress(),
204
+ run
205
+ };
206
+ }
207
+ after = conversation;
125
208
  }
126
- const attempt = await withLock(state, eventIndexLockKey(backlog.conversationId), async () => {
209
+ if (page.length < CONVERSATION_PAGE_SIZE) {
210
+ const pass = progress();
127
211
  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
212
+ outcome: pass.events === 0 && pass.skipped === 0 ? "completed" : "pass_ended",
213
+ pass,
214
+ run
133
215
  };
134
- }, { ttlMs: EVENT_INDEX_LOCK_TTL_MS });
135
- if (!attempt.acquired) {
136
- done = false;
137
- continue;
138
216
  }
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
217
  }
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
218
  }
153
219
  /**
154
220
  * Index the backlog of event search in recently active Conversations.
@@ -156,25 +222,40 @@ async function backfillEventSearchIndex(args) {
156
222
  */
157
223
  async function runEventSearchBackfill(args) {
158
224
  const key = `junior:event_search:backfill:${args.embedder ? `${args.embedder.provider}:${args.embedder.model}` : "lexemes"}`;
225
+ const passKey = `${key}:pass`;
159
226
  const state = getStateAdapter();
160
227
  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"
228
+ const deadlineMs = Date.now() + BACKFILL_BUDGET_MS;
229
+ let done = false;
230
+ try {
231
+ await withSpan("event_search.backfill", "event_search.backfill", {}, async (setSpanAttributes) => {
232
+ const stored = backfillPassSchema.safeParse(await state.get(passKey));
233
+ const result = await backfillEventSearchIndex({
234
+ db: getDb(),
235
+ deadlineMs,
236
+ ...args.embedder ? { embedder: args.embedder } : void 0,
237
+ nowMs: args.nowMs,
238
+ pass: stored.success ? stored.data : NEW_PASS
239
+ });
240
+ if (result.outcome === "limit_reached") await state.set(passKey, result.pass, BACKFILL_PASS_TTL_MS);
241
+ else await state.delete(passKey);
242
+ if (result.outcome === "completed") {
243
+ await state.set(key, "done", BACKFILL_DONE_TTL_MS);
244
+ done = true;
245
+ }
246
+ setSpanAttributes({
247
+ "app.event_search.backfill.conversation.count": result.run.conversations,
248
+ "app.event_search.backfill.skipped.count": result.run.skipped,
249
+ "app.event_search.backfill.lexeme.count": result.run.lexemes,
250
+ "app.event_search.backfill.vector.count": result.run.vectors,
251
+ "app.event_search.backfill.pass.conversation.count": result.pass.conversations,
252
+ "app.event_search.backfill.pass.event.count": result.pass.events,
253
+ "app.event_search.backfill.outcome": result.outcome
254
+ });
176
255
  });
177
- });
256
+ } finally {
257
+ if (!done) await state.delete(key);
258
+ }
178
259
  }
179
260
  // src/chat/events/timers.ts
180
261
  /** Publish a bounded batch of due timers; the mailbox owns agent execution. */
@@ -934,7 +1015,7 @@ async function runPluginHeartbeats(args) {
934
1015
  events: createPluginEventPublisher(plugin, args.events),
935
1016
  plugin,
936
1017
  nowMs: args.nowMs,
937
- showReviewItem: args.showReviewItem
1018
+ showInboxItem: args.showInboxItem
938
1019
  }))), PLUGIN_HEARTBEAT_TIMEOUT_MS);
939
1020
  if (typeof result?.dispatchCount === "number" && result.dispatchCount > 0) logInfo("plugin.heartbeat.dispatched", {
940
1021
  "app.dispatch.count": result.dispatchCount,
@@ -1070,7 +1151,7 @@ async function runHeartbeat(args) {
1070
1151
  dispatchForIdentity: args.dispatchForIdentity,
1071
1152
  events: args.events,
1072
1153
  nowMs: args.nowMs,
1073
- showReviewItem: args.showReviewItem
1154
+ showInboxItem: args.showInboxItem
1074
1155
  });
1075
1156
  try {
1076
1157
  await backfillCacheWarmingGaps({ nowMs: args.nowMs });
@@ -1082,7 +1163,7 @@ async function runHeartbeat(args) {
1082
1163
  } catch (error) {
1083
1164
  logException(error, "cache_warming.savings_refill.failed");
1084
1165
  }
1085
- if (isBriefsEnabled()) try {
1166
+ try {
1086
1167
  await runConversationEmbeddingBackfill(createConversationEmbedder({
1087
1168
  cost: { owner: "none" },
1088
1169
  operation: "conversation_embedding"
@@ -1123,7 +1204,7 @@ async function GET$3(request, waitUntil, options) {
1123
1204
  dispatchForIdentity: options.dispatchForIdentity,
1124
1205
  events: options.events,
1125
1206
  nowMs,
1126
- showReviewItem: options.showReviewItem
1207
+ showInboxItem: options.showInboxItem
1127
1208
  }).catch((error) => {
1128
1209
  logException(error, "heartbeat.run.failed", { "app.heartbeat.now_ms": nowMs });
1129
1210
  }));
@@ -1194,15 +1275,15 @@ async function selectExpiredRoots(executor, args) {
1194
1275
  or bindings.child_conversation_id = tree.conversation_id
1195
1276
  )
1196
1277
  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
1278
+ select 1 from junior_inbox_items inbox_items
1279
+ where inbox_items.owner_kind = 'conversation'
1280
+ and inbox_items.owner_id = tree.conversation_id
1281
+ and inbox_items.status = 'open'
1282
+ and inbox_items.automation_id is null
1202
1283
  )
1203
1284
  or exists (
1204
- select 1 from junior_plan_items plan_items
1205
- where plan_items.conversation_id = tree.conversation_id
1285
+ select 1 from junior_todos todos
1286
+ where todos.conversation_id = tree.conversation_id
1206
1287
  )
1207
1288
  or (
1208
1289
  ${juniorDestinations.visibility} is distinct from 'public'
@@ -1212,13 +1293,22 @@ async function selectExpiredRoots(executor, args) {
1212
1293
  where briefs.conversation_id = tree.conversation_id
1213
1294
  )
1214
1295
  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'
1296
+ select 1 from junior_conversations metadata
1297
+ where metadata.conversation_id = tree.conversation_id
1298
+ and metadata.summary is not null
1299
+ )
1300
+ or exists (
1301
+ select 1 from junior_conversation_embeddings embeddings
1302
+ where embeddings.conversation_id = tree.conversation_id
1303
+ )
1304
+ or exists (
1305
+ select 1 from junior_inbox_items inbox_items
1306
+ where inbox_items.owner_kind = 'conversation'
1307
+ and inbox_items.owner_id = tree.conversation_id
1308
+ and inbox_items.visibility = 'private'
1219
1309
  and (
1220
- review_items.status <> 'open'
1221
- or review_items.automation_id is null
1310
+ inbox_items.status <> 'open'
1311
+ or inbox_items.automation_id is null
1222
1312
  )
1223
1313
  )
1224
1314
  or exists (
@@ -1246,9 +1336,10 @@ async function selectExpiredRoots(executor, args) {
1246
1336
  * event rows for the given conversation and every descendant, stamp
1247
1337
  * `transcript_purged_at`, and — for non-public content — null the raw-payload
1248
1338
  * 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.
1339
+ * conversations keep only safe metadata. To-dos go with the transcript.
1340
+ * Non-public content also loses its summary, Conversation embedding, legacy
1341
+ * Briefs, and the Inbox items that it added. The metadata rows themselves
1342
+ * survive.
1252
1343
  */
1253
1344
  async function purgeConversationTree(executor, args) {
1254
1345
  return await withConversationMutationLock(executor, args.rootConversationId, async () => {
@@ -1294,26 +1385,29 @@ async function purgeConversationTree(executor, args) {
1294
1385
  await deleteMessageLinks(executor, ids);
1295
1386
  await executor.db().delete(juniorAgentInvocations).where(or(inArray(juniorAgentInvocations.parentConversationId, ids), inArray(juniorAgentInvocations.childConversationId, ids)));
1296
1387
  await executor.db().delete(juniorAgentBindings).where(or(inArray(juniorAgentBindings.parentConversationId, ids), inArray(juniorAgentBindings.childConversationId, ids)));
1297
- await dismissOpenReviewItems(executor.db(), {
1388
+ await dismissOpenInboxItems(executor.db(), {
1298
1389
  ownerConversationIds: ids,
1299
1390
  nowMs: args.nowMs,
1300
1391
  reason: "Conversation purged"
1301
1392
  });
1302
- await deletePlanItems(executor, ids);
1393
+ await deleteTodos(executor, ids);
1303
1394
  await requestAttachmentDeletion(executor, ids, args.nowMs);
1304
1395
  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
1396
  await executor.db().update(juniorConversations).set({
1310
1397
  transcriptPurgedAt: new Date(args.nowMs),
1311
1398
  ...scrubMetadata ? {
1312
1399
  title: null,
1313
1400
  channelName: null,
1314
- actor: null
1401
+ actor: null,
1402
+ summary: null,
1403
+ metadataThroughSeq: null
1315
1404
  } : void 0
1316
1405
  }).where(inArray(juniorConversations.conversationId, ids));
1406
+ if (scrubMetadata) {
1407
+ await executor.db().delete(juniorConversationBriefs).where(inArray(juniorConversationBriefs.conversationId, ids));
1408
+ await executor.db().delete(juniorConversationEmbeddings).where(inArray(juniorConversationEmbeddings.conversationId, ids));
1409
+ 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))));
1410
+ }
1317
1411
  await touchConversationDetail(executor.db(), ids);
1318
1412
  return {
1319
1413
  purged: true,
@@ -1753,7 +1847,7 @@ function buildSlackInteractionInput(args) {
1753
1847
  threadId: parsed.threadId
1754
1848
  });
1755
1849
  }
1756
- // src/chat/ingress/slack-review-item.ts
1850
+ // src/chat/ingress/slack-inbox-item.ts
1757
1851
  async function tellPerson(target, userId, text) {
1758
1852
  await postSlackEphemeralMessage({
1759
1853
  channelId: target.channelId,
@@ -1772,9 +1866,9 @@ function resolveActingUser(services, payload, target) {
1772
1866
  }
1773
1867
  /** Show the current state of an item, such as after a click on a stale card. */
1774
1868
  async function refreshCards(services, user, itemId) {
1775
- const item = await readReviewItemForUser(user, itemId).catch(() => void 0);
1869
+ const item = await readInboxItemForUser(user, itemId).catch(() => void 0);
1776
1870
  if (!item) return;
1777
- await syncReviewItemSlackCards({
1871
+ await syncInboxItemSlackCards({
1778
1872
  getSlackAdapter: () => services.adapter,
1779
1873
  itemId: item.id
1780
1874
  });
@@ -1784,7 +1878,7 @@ async function refreshCards(services, user, itemId) {
1784
1878
  * answer as Slack input from the person, like a typed reply. A dismiss, or
1785
1879
  * the answer to a plugin item, starts no Turn, so the thread gets the same
1786
1880
  * recorded Message as the other linked Conversations, from
1787
- * `actOnReviewItem`. An expected failure, such as
1881
+ * `actOnInboxItem`. An expected failure, such as
1788
1882
  * an item that is already closed, goes to the person as an ephemeral
1789
1883
  * message.
1790
1884
  */
@@ -1792,22 +1886,22 @@ async function act(args) {
1792
1886
  const { services, target } = args;
1793
1887
  const actor = await resolveActingUser(services, args.payload, target);
1794
1888
  if (!actor) return;
1795
- const conversationId = await resolveSlackReviewItemCardConversationId({
1889
+ const conversationId = await resolveSlackInboxItemCardConversationId({
1796
1890
  channelId: target.channelId,
1797
1891
  teamId: actor.teamId,
1798
1892
  threadTs: target.threadTs
1799
1893
  });
1800
1894
  const delivery = {
1801
1895
  queue: services.queue,
1802
- show: createSlackReviewItemShow(() => services.adapter)
1896
+ show: createSlackInboxItemShow(() => services.adapter)
1803
1897
  };
1804
1898
  let recordOnly = args.action === "dismiss";
1805
1899
  let item;
1806
1900
  try {
1807
- const current = await readReviewItemForUser(actor.user, args.itemId);
1808
- const pluginAnswer = args.action === "submit" && isPluginReviewItem(current);
1901
+ const current = await readInboxItemForUser(actor.user, args.itemId);
1902
+ const pluginAnswer = args.action === "submit" && isPluginInboxItem(current);
1809
1903
  recordOnly ||= pluginAnswer;
1810
- item = await actOnReviewItem({
1904
+ item = await actOnInboxItem({
1811
1905
  action: args.action,
1812
1906
  ...recordOnly ? void 0 : { exceptConversationId: conversationId },
1813
1907
  firstCloseOnly: !pluginAnswer,
@@ -1817,7 +1911,7 @@ async function act(args) {
1817
1911
  ...args.answer ? { answer: args.answer(current) } : void 0
1818
1912
  });
1819
1913
  } catch (error) {
1820
- if (!(error instanceof ReviewItemActionError)) throw error;
1914
+ if (!(error instanceof InboxItemActionError)) throw error;
1821
1915
  await tellPerson(target, actor.slackUserId, error.message);
1822
1916
  await refreshCards(services, actor.user, args.itemId);
1823
1917
  return;
@@ -1832,13 +1926,13 @@ async function act(args) {
1832
1926
  messageId: args.messageId,
1833
1927
  messageTs: target.messageTs,
1834
1928
  payload: args.payload,
1835
- text: renderReviewItemMessage(item, change),
1929
+ text: renderInboxItemMessage(item, change),
1836
1930
  threadTs: target.threadTs,
1837
1931
  userId: actor.slackUserId
1838
- }), { reviewItemChange: reviewItemChangeRecord(item, change) });
1932
+ }), { reviewItemChange: inboxItemChangeRecord(item, change) });
1839
1933
  } catch (error) {
1840
- logException(error, "review_item.slack_input.persist.failed", { "app.review_item.id": item.id });
1841
- await deliverReviewItemChange({
1934
+ logException(error, "inbox_item.slack_input.persist.failed", { "app.inbox_item.id": item.id });
1935
+ await deliverInboxItemChange({
1842
1936
  change,
1843
1937
  delivery,
1844
1938
  item,
@@ -1849,7 +1943,7 @@ async function act(args) {
1849
1943
  function cardTarget(payload) {
1850
1944
  const channelId = parseSlackChannelId(payload.channel?.id);
1851
1945
  const messageTs = parseSlackMessageTs(payload.message?.ts);
1852
- if (!channelId || !messageTs) throw new Error("Slack review item payload is incomplete");
1946
+ if (!channelId || !messageTs) throw new Error("Slack inbox item payload is incomplete");
1853
1947
  return {
1854
1948
  channelId,
1855
1949
  messageTs,
@@ -1859,23 +1953,23 @@ function cardTarget(payload) {
1859
1953
  async function openAnswerForm(args) {
1860
1954
  const { target } = args;
1861
1955
  const triggerId = args.payload.trigger_id;
1862
- if (!triggerId) throw new Error("Slack review item form payload is missing a trigger id");
1956
+ if (!triggerId) throw new Error("Slack inbox item form payload is missing a trigger id");
1863
1957
  const actor = await resolveActingUser(args.services, args.payload, target);
1864
1958
  if (!actor) return;
1865
1959
  let item;
1866
1960
  try {
1867
- item = await readReviewItemForUser(actor.user, args.itemId);
1961
+ item = await readInboxItemForUser(actor.user, args.itemId);
1868
1962
  } catch (error) {
1869
- if (!(error instanceof ReviewItemActionError)) throw error;
1963
+ if (!(error instanceof InboxItemActionError)) throw error;
1870
1964
  await tellPerson(target, actor.slackUserId, error.message);
1871
1965
  return;
1872
1966
  }
1873
- if (!canActOnReviewItem(item, actor.user.id)) {
1967
+ if (!canActOnInboxItem(item, actor.user.id)) {
1874
1968
  await tellPerson(target, actor.slackUserId, item.status === "open" ? "Only an assignee can act on this item." : "This item is already closed.");
1875
1969
  await refreshCards(args.services, actor.user, item.id);
1876
1970
  return;
1877
1971
  }
1878
- const view = buildSlackReviewItemModal(item, {
1972
+ const view = buildSlackInboxItemModal(item, {
1879
1973
  ...target,
1880
1974
  itemId: item.id
1881
1975
  });
@@ -1885,8 +1979,8 @@ async function openAnswerForm(args) {
1885
1979
  view
1886
1980
  });
1887
1981
  }
1888
- /** Handle one click on a Review item card. */
1889
- async function handleSlackReviewItemClick(args) {
1982
+ /** Handle one click on an Inbox item card. */
1983
+ async function handleSlackInboxItemClick(args) {
1890
1984
  const { click, payload, services } = args;
1891
1985
  const target = cardTarget(payload);
1892
1986
  if (click.kind === "answer") {
@@ -1899,11 +1993,11 @@ async function handleSlackReviewItemClick(args) {
1899
1993
  return;
1900
1994
  }
1901
1995
  const actionTs = parseSlackMessageTs(args.action.action_ts);
1902
- if (!actionTs) throw new Error("Slack review item click payload is incomplete");
1996
+ if (!actionTs) throw new Error("Slack inbox item click payload is incomplete");
1903
1997
  const common = {
1904
1998
  inputTs: actionTs,
1905
1999
  itemId: click.itemId,
1906
- messageId: `slack-review-item:${actionTs}`,
2000
+ messageId: `slack-inbox-item:${actionTs}`,
1907
2001
  payload,
1908
2002
  services,
1909
2003
  target
@@ -1920,7 +2014,7 @@ async function handleSlackReviewItemClick(args) {
1920
2014
  action: "submit",
1921
2015
  answer: (item) => {
1922
2016
  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.");
2017
+ if (!field?.options.some((option) => option.label === click.label)) throw new InboxItemActionError("conflict", "This card changed. Use the updated card.");
1924
2018
  return {
1925
2019
  requestId: item.id,
1926
2020
  values: { [field.id]: [click.label] }
@@ -1928,14 +2022,14 @@ async function handleSlackReviewItemClick(args) {
1928
2022
  }
1929
2023
  });
1930
2024
  }
1931
- /** Submit the answer of a Review item form. */
1932
- async function handleSlackReviewItemSubmission(args) {
2025
+ /** Submit the answer of an Inbox item form. */
2026
+ async function handleSlackInboxItemSubmission(args) {
1933
2027
  const view = args.payload.view;
1934
- const formTarget = parseSlackReviewItemFormTarget(view?.private_metadata);
2028
+ const formTarget = parseSlackInboxItemFormTarget(view?.private_metadata);
1935
2029
  const channelId = parseSlackChannelId(formTarget?.channelId);
1936
2030
  const messageTs = parseSlackMessageTs(formTarget?.messageTs);
1937
2031
  const threadTs = parseSlackMessageTs(formTarget?.threadTs);
1938
- if (!view?.id || !formTarget || !channelId || !messageTs || !threadTs) throw new Error("Slack review item form submission is incomplete");
2032
+ if (!view?.id || !formTarget || !channelId || !messageTs || !threadTs) throw new Error("Slack inbox item form submission is incomplete");
1939
2033
  await act({
1940
2034
  action: "submit",
1941
2035
  answer: (item) => item.request ? parseSlackUserInputSubmission({
@@ -1948,7 +2042,7 @@ async function handleSlackReviewItemSubmission(args) {
1948
2042
  },
1949
2043
  inputTs: slackMessageTsFromMs(Date.now()),
1950
2044
  itemId: formTarget.itemId,
1951
- messageId: `slack-review-item:${view.id}`,
2045
+ messageId: `slack-inbox-item:${view.id}`,
1952
2046
  payload: args.payload,
1953
2047
  services: args.services,
1954
2048
  target: {
@@ -1979,13 +2073,13 @@ async function handleAppHomeDisconnect(args) {
1979
2073
  });
1980
2074
  }
1981
2075
  /**
1982
- * Handle Slack interactions from App Home, Review item cards, and dashboard
2076
+ * Handle Slack interactions from App Home, Inbox item cards, and dashboard
1983
2077
  * link previews: block actions and submitted forms.
1984
2078
  */
1985
2079
  async function handleSlackInteractivePayload(args) {
1986
2080
  const spanAttributes = { userId: args.payload.user?.id?.trim() || void 0 };
1987
2081
  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({
2082
+ await withSpan("chat.slack_inbox_item_submit", "chat.slack_inbox_item_submit", spanAttributes, () => handleSlackInboxItemSubmission({
1989
2083
  payload: args.payload,
1990
2084
  services: args
1991
2085
  }));
@@ -1993,9 +2087,9 @@ async function handleSlackInteractivePayload(args) {
1993
2087
  }
1994
2088
  if (args.payload.type !== "block_actions") return;
1995
2089
  for (const action of args.payload.actions ?? []) {
1996
- const click = parseSlackReviewItemClick(action);
2090
+ const click = parseSlackInboxItemClick(action);
1997
2091
  if (click) {
1998
- await withSpan("chat.slack_review_item_click", "chat.slack_review_item_click", spanAttributes, () => handleSlackReviewItemClick({
2092
+ await withSpan("chat.slack_inbox_item_click", "chat.slack_inbox_item_click", spanAttributes, () => handleSlackInboxItemClick({
1999
2093
  action,
2000
2094
  click,
2001
2095
  payload: args.payload,
@@ -2683,12 +2777,12 @@ async function routeParsedMessage(args) {
2683
2777
  });
2684
2778
  const closeAnswered = async () => {
2685
2779
  if (message.author.isBot === true) return;
2686
- await closeReviewItemsAnsweredByReply({
2780
+ await closeInboxItemsAnsweredByReply({
2687
2781
  ...route === "subscribed" ? { canAnswer: isAuthorTrusted } : void 0,
2688
2782
  conversationId,
2689
2783
  delivery: {
2690
2784
  queue: args.queue,
2691
- show: createSlackReviewItemShow(() => args.adapter)
2785
+ show: createSlackInboxItemShow(() => args.adapter)
2692
2786
  },
2693
2787
  resolveUser: async () => {
2694
2788
  const teamId = args.installation.teamId;
@@ -3228,7 +3322,7 @@ async function publicArtifactGET(args) {
3228
3322
  headers: unpublishedArtifactHeaders(),
3229
3323
  status: 404
3230
3324
  });
3231
- return new Response(artifact.body, { headers: publicArtifactHeaders(artifact.contentType) });
3325
+ return new Response(artifact.body, { headers: publicArtifactHeaders(artifact.contentType, artifact.expiresAt) });
3232
3326
  } catch (error) {
3233
3327
  logException(error, "public_artifact.get.failed");
3234
3328
  return new Response("Internal Server Error", { status: 500 });
@@ -5054,7 +5148,7 @@ const MCP_SCOPES = [
5054
5148
  "conversations:read",
5055
5149
  "conversations:manage",
5056
5150
  "conversations:write",
5057
- "review_items:read",
5151
+ "inbox_items:read",
5058
5152
  "automations:read"
5059
5153
  ];
5060
5154
  /** What each scope lets the client do, as the consent page says it. */
@@ -5062,23 +5156,27 @@ const MCP_SCOPE_DESCRIPTIONS = {
5062
5156
  "conversations:read": "List and read the conversations that you started or take part in",
5063
5157
  "conversations:manage": "Archive, pin, and mark your conversations read, stop a running Turn, and cancel queued messages",
5064
5158
  "conversations:write": "Start conversations and send messages as you. Each message starts agent work",
5065
- "review_items:read": "List and read your review items",
5159
+ "inbox_items:read": "List and read your inbox items",
5066
5160
  "automations:read": "List and read the automations that you can see"
5067
5161
  };
5068
5162
  /** The `scope` value that names every scope. */
5069
5163
  const MCP_ALL_SCOPES = MCP_SCOPES.join(" ");
5164
+ const RENAMED_MCP_SCOPES = { "review_items:read": "inbox_items:read" };
5165
+ function scopeNames(value) {
5166
+ return value.split(" ").filter(Boolean).map((name) => RENAMED_MCP_SCOPES[name] ?? name);
5167
+ }
5070
5168
  /**
5071
5169
  * Parse a space-separated scope value into known scopes in canonical order.
5072
5170
  * Return `undefined` when it is empty or names an unknown scope.
5073
5171
  */
5074
5172
  function parseMcpScopes(value) {
5075
- const names = value.split(" ").filter(Boolean);
5173
+ const names = scopeNames(value);
5076
5174
  if (names.length === 0) return void 0;
5077
5175
  if (!names.every((name) => MCP_SCOPES.includes(name))) return void 0;
5078
5176
  return MCP_SCOPES.filter((scope) => names.includes(scope));
5079
5177
  }
5080
5178
  /** A stored scope value: known scopes, space-separated, in canonical order. */
5081
- const mcpScopeValueSchema = z.string().refine((value) => parseMcpScopes(value)?.join(" ") === value);
5179
+ const mcpScopeValueSchema = z.string().refine((value) => parseMcpScopes(value)?.join(" ") === scopeNames(value).join(" "));
5082
5180
  // src/api/mcp/oauth/authorization.ts
5083
5181
  /**
5084
5182
  * Own the OAuth authorization endpoint and its pending requests.
@@ -5092,7 +5190,7 @@ const AUTHORIZATION_TTL_MS = 6e5;
5092
5190
  const STATE_MAX_LENGTH = 1e3;
5093
5191
  const AUTHORIZATION_ID_PATTERN = /^[A-Za-z0-9_-]{43}$/;
5094
5192
  const CODE_CHALLENGE_PATTERN = /^[A-Za-z0-9_-]{43}$/;
5095
- const mcpAuthorizationSchema$1 = z.object({
5193
+ const mcpAuthorizationSchema = z.object({
5096
5194
  clientId: z.string().min(1),
5097
5195
  clientName: z.string().min(1).optional(),
5098
5196
  codeChallenge: z.string().regex(CODE_CHALLENGE_PATTERN),
@@ -5123,7 +5221,7 @@ function claimedKey(authorizationId) {
5123
5221
  */
5124
5222
  async function readMcpAuthorization(state, authorizationId) {
5125
5223
  if (!AUTHORIZATION_ID_PATTERN.test(authorizationId)) return void 0;
5126
- const authorization = await readRecord(state, authorizationKey(authorizationId), mcpAuthorizationSchema$1);
5224
+ const authorization = await readRecord(state, authorizationKey(authorizationId), mcpAuthorizationSchema);
5127
5225
  if (!authorization || authorization.expiresAtMs <= Date.now()) return;
5128
5226
  if (await state.get(claimedKey(authorizationId)) !== null) return void 0;
5129
5227
  return {
@@ -5386,7 +5484,7 @@ async function refreshGrant(args) {
5386
5484
  const token = await readRecord(args.state, key, tokenSchema);
5387
5485
  const grant = token ? await readGrant(args.state, token.grantId) : void 0;
5388
5486
  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 {
5487
+ if (args.scope !== void 0 && parseMcpScopes(args.scope)?.join(" ") !== parseMcpScopes(grant.scope)?.join(" ")) return {
5390
5488
  description: `Refresh keeps the granted scope: ${grant.scope}.`,
5391
5489
  error: "invalid_scope",
5392
5490
  ok: false
@@ -5581,173 +5679,6 @@ async function handleMcpConsentPage(args) {
5581
5679
  state: authorization.state
5582
5680
  });
5583
5681
  }
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
5682
  // src/api/mcp/tool-context.ts
5752
5683
  /**
5753
5684
  * Return one structured tool result. The text block holds the same JSON, as
@@ -5788,80 +5719,24 @@ function apiToolError(error) {
5788
5719
  async function isConversationParticipant(user, conversationId) {
5789
5720
  return (await readConversationAccessFromSql(getDb(), [conversationId], user)).get(conversationId)?.isParticipant ?? false;
5790
5721
  }
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
5722
+ // src/api/mcp/tools/api-operation.ts
5826
5723
  /**
5827
- * Register `archiveDoneConversations`, which archives every done
5828
- * Conversation of the user once.
5724
+ * Register an API operation as an MCP tool. A client error from the
5725
+ * operation becomes a tool error.
5829
5726
  */
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.") },
5727
+ function registerApiOperationTool(server, operation, { queue, user }) {
5728
+ server.registerTool(operation.name, {
5729
+ title: operation.title,
5730
+ description: operation.description,
5731
+ inputSchema: operation.input,
5732
+ outputSchema: operation.output,
5836
5733
  annotations: {
5837
- destructiveHint: false,
5838
- idempotentHint: true,
5839
- openWorldHint: false,
5840
- readOnlyHint: false
5734
+ ...operation.annotations,
5735
+ openWorldHint: false
5841
5736
  }
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.");
5737
+ }, async (input) => {
5863
5738
  try {
5864
- return mcpToolResult({ cancelledMessages: (await cancelConversationPendingMessagesForViewer(user, conversationId)).cancelledCount });
5739
+ return mcpToolResult(await operation.run(user, input, { queue }));
5865
5740
  } catch (error) {
5866
5741
  return apiToolError(error);
5867
5742
  }
@@ -6013,22 +5888,6 @@ function registerGetAutomationTool(server, { user }) {
6013
5888
  });
6014
5889
  }
6015
5890
  // 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
5891
  const RECENT_EVENT_LIMIT = 100;
6033
5892
  const AFTER_EVENT_SCAN_LIMIT = 200;
6034
5893
  const AFTER_MESSAGE_LIMIT = 20;
@@ -6053,25 +5912,24 @@ async function readMessagesAfter(conversationId, afterSeq) {
6053
5912
  };
6054
5913
  }
6055
5914
  /**
6056
- * Register `getConversation`. It returns metadata, the Brief, and the last
5915
+ * Register `getConversation`. It returns metadata, the summary, and the last
6057
5916
  * Reply or the Messages after a cursor, not the whole transcript.
6058
5917
  */
6059
5918
  function registerGetConversationTool(server, { user }) {
6060
5919
  server.registerTool("getConversation", {
6061
5920
  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.",
5921
+ 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
5922
  inputSchema: {
6064
5923
  conversationId: mcpConversationIdSchema,
6065
5924
  after: z.string().min(1).max(1e3).optional().describe("`cursor` from sendMessage, createConversation, or an earlier getConversation call.")
6066
5925
  },
6067
5926
  outputSchema: {
6068
5927
  conversation: mcpConversationSchema,
6069
- brief: mcpBriefSchema.optional(),
6070
5928
  lastReply: mcpMessageSchema.optional().describe("Newest assistant message in the recent events. Set only without `after`."),
6071
5929
  messages: z.array(mcpMessageSchema).optional().describe("User and assistant messages after `after`, oldest first. Set only with `after`."),
6072
5930
  hasMore: z.boolean().optional().describe("True when more messages already follow `cursor`. Call again now, also when `turnActive` is false."),
6073
5931
  pendingMessages: mcpPendingMessagesSchema,
6074
- authorization: mcpAuthorizationSchema.optional(),
5932
+ authorization: mcpAuthorizationSchema$1.optional(),
6075
5933
  cursor: mcpCursorSchema
6076
5934
  },
6077
5935
  annotations: {
@@ -6100,7 +5958,6 @@ function registerGetConversationTool(server, { user }) {
6100
5958
  const cursorSeq = newer?.seq ?? detail.events.at(-1)?.seq ?? -1;
6101
5959
  return mcpToolResult({
6102
5960
  conversation: mcpConversation(detail),
6103
- ...detail.brief ? { brief: mcpBrief(detail.brief.content, detail.brief.updatedAt) } : void 0,
6104
5961
  ...lastReply ? { lastReply } : void 0,
6105
5962
  ...newer ? { messages: newer.messages } : void 0,
6106
5963
  ...newer?.hasMore ? { hasMore: true } : void 0,
@@ -6112,15 +5969,15 @@ function registerGetConversationTool(server, { user }) {
6112
5969
  });
6113
5970
  });
6114
5971
  }
6115
- // src/api/mcp/review-item.ts
5972
+ // src/api/mcp/inbox-item.ts
6116
5973
  /**
6117
- * Own the MCP view of one Review item, shared by the review item tools.
5974
+ * Own the MCP view of one Inbox item, shared by the inbox item tools.
6118
5975
  *
6119
- * MCP Review items stay read-only. An answer sends a message to the linked
5976
+ * MCP Inbox items stay read-only. An answer sends a message to the linked
6120
5977
  * Conversations, which can start a Turn. A dismiss starts no Turn.
6121
5978
  */
6122
- /** MCP view of one Review item. Answers happen in Slack or the dashboard. */
6123
- const mcpReviewItemSchema = z.object({
5979
+ /** MCP view of one Inbox item. Answers happen in Slack or the dashboard. */
5980
+ const mcpInboxItemSchema = z.object({
6124
5981
  id: z.string(),
6125
5982
  kind: z.enum(["notice", "action"]),
6126
5983
  status: z.enum([
@@ -6143,9 +6000,9 @@ const mcpReviewItemSchema = z.object({
6143
6000
  updatedAt: z.string(),
6144
6001
  url: z.string().optional().describe("Dashboard link to answer it.")
6145
6002
  }).strict();
6146
- /** Map a Review item to its MCP view for one user. */
6147
- function mcpReviewItem(item, userId) {
6148
- const url = getDashboardReviewItemLink(item.id);
6003
+ /** Map an Inbox item to its MCP view for one user. */
6004
+ function mcpInboxItem(item, userId) {
6005
+ const url = getDashboardInboxItemLink(item.id);
6149
6006
  return {
6150
6007
  id: item.id,
6151
6008
  kind: item.kind,
@@ -6154,7 +6011,7 @@ function mcpReviewItem(item, userId) {
6154
6011
  body: item.body,
6155
6012
  ...item.request ? { question: item.request.question } : void 0,
6156
6013
  assignees: item.assignedToEveryone ? [] : item.assignees.map((person) => person.displayName ?? person.email),
6157
- canAct: canActOnReviewItem(item, userId),
6014
+ canAct: canActOnInboxItem(item, userId),
6158
6015
  conversationIds: item.conversationIds,
6159
6016
  ...item.subject ? { subject: {
6160
6017
  id: item.subject.id,
@@ -6166,14 +6023,14 @@ function mcpReviewItem(item, userId) {
6166
6023
  ...url ? { url } : void 0
6167
6024
  };
6168
6025
  }
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 },
6026
+ // src/api/mcp/tools/get-inbox-item.ts
6027
+ /** Register `getInboxItem`, which reads one Inbox item in any status. */
6028
+ function registerGetInboxItemTool(server, { user }) {
6029
+ server.registerTool("getInboxItem", {
6030
+ title: "Get inbox item",
6031
+ description: "Get one inbox item, open or closed.",
6032
+ inputSchema: { id: z.string().min(1).describe("Inbox item id from searchInboxItems.") },
6033
+ outputSchema: { item: mcpInboxItemSchema },
6177
6034
  annotations: {
6178
6035
  destructiveHint: false,
6179
6036
  idempotentHint: true,
@@ -6182,9 +6039,9 @@ function registerGetReviewItemTool(server, { user }) {
6182
6039
  }
6183
6040
  }, async ({ id }) => {
6184
6041
  try {
6185
- return mcpToolResult({ item: mcpReviewItem(await readReviewItemForUser(user, id), user.id) });
6042
+ return mcpToolResult({ item: mcpInboxItem(await readInboxItemForUser(user, id), user.id) });
6186
6043
  } catch (error) {
6187
- if (error instanceof ReviewItemActionError) return mcpToolError(error.message);
6044
+ if (error instanceof InboxItemActionError) return mcpToolError(error.message);
6188
6045
  throw error;
6189
6046
  }
6190
6047
  });
@@ -6306,31 +6163,6 @@ function registerMarkConversationReadTool(server, { user }) {
6306
6163
  }
6307
6164
  });
6308
6165
  }
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
6166
  // src/api/mcp/tools/search-conversations.ts
6335
6167
  /** Register `searchConversations`, which searches the Conversations of the user. */
6336
6168
  function registerSearchConversationsTool(server, { user }) {
@@ -6339,7 +6171,7 @@ function registerSearchConversationsTool(server, { user }) {
6339
6171
  title: "Search conversations",
6340
6172
  description: "Search your conversations and return up to 50, newest activity first. Only conversations that you started or take part in match.",
6341
6173
  inputSchema: {
6342
- q: feedQuery.q.describe("Text to search for in titles and Briefs."),
6174
+ q: feedQuery.q.describe("Text to search for in titles, summaries, and Annotation labels and titles."),
6343
6175
  status: feedQuery.status.describe("Return conversations that are not archived (default) or that are archived. A search ignores this filter.")
6344
6176
  },
6345
6177
  outputSchema: { conversations: z.array(mcpConversationSchema) },
@@ -6357,19 +6189,19 @@ function registerSearchConversationsTool(server, { user }) {
6357
6189
  })).conversations.map(mcpConversation) });
6358
6190
  });
6359
6191
  }
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.",
6192
+ // src/api/mcp/tools/search-inbox-items.ts
6193
+ /** Register `searchInboxItems`, which searches open Inbox items for the user. */
6194
+ function registerSearchInboxItemsTool(server, { user }) {
6195
+ server.registerTool("searchInboxItems", {
6196
+ title: "Search inbox items",
6197
+ 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
6198
  inputSchema: {
6367
6199
  q: z.string().trim().min(1).max(200).optional().describe("Words to find in the title or body."),
6368
6200
  conversationId: z.string().min(1).optional().describe("Return only the items linked to this conversation."),
6369
6201
  limit: z.number().int().min(1).max(50).default(20).describe("Maximum number of items.")
6370
6202
  },
6371
6203
  outputSchema: {
6372
- items: z.array(mcpReviewItemSchema),
6204
+ items: z.array(mcpInboxItemSchema),
6373
6205
  truncated: z.boolean().describe("True when more items match.")
6374
6206
  },
6375
6207
  annotations: {
@@ -6379,14 +6211,14 @@ function registerSearchReviewItemsTool(server, { user }) {
6379
6211
  readOnlyHint: true
6380
6212
  }
6381
6213
  }, async ({ conversationId, limit, q }) => {
6382
- const items = await searchReviewItems(getDb(), conversationId ? await reviewItemReaderForUserInConversation(user, conversationId) : reviewItemReaderForUser(user), {
6214
+ const items = await searchInboxItems(getDb(), conversationId ? await inboxItemReaderForUserInConversation(user, conversationId) : inboxItemReaderForUser(user), {
6383
6215
  ...conversationId ? { conversationId } : void 0,
6384
6216
  limit: limit + 1,
6385
6217
  ...q ? { query: q } : void 0,
6386
6218
  statuses: ["open"]
6387
6219
  });
6388
6220
  return mcpToolResult({
6389
- items: items.slice(0, limit).map((item) => mcpReviewItem(item, user.id)),
6221
+ items: items.slice(0, limit).map((item) => mcpInboxItem(item, user.id)),
6390
6222
  truncated: items.length > limit
6391
6223
  });
6392
6224
  });
@@ -6424,15 +6256,10 @@ function registerSendMessageTool(server, { attachmentStorage, queue, user }) {
6424
6256
  }, {
6425
6257
  attachmentStorage,
6426
6258
  queue
6427
- });
6259
+ }, delivery);
6428
6260
  } catch (error) {
6429
6261
  return apiToolError(error);
6430
6262
  }
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
6263
  const messageSeq = accepted.status === "duplicate" ? await readConversationMessageEventSeq(getSqlExecutor(), accepted.conversationId, accepted.messageId) : void 0;
6437
6264
  return mcpToolResult({
6438
6265
  ...accepted,
@@ -6445,133 +6272,38 @@ function registerSendMessageTool(server, { attachmentStorage, queue, user }) {
6445
6272
  });
6446
6273
  });
6447
6274
  }
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
6275
  // src/api/mcp/server.ts
6541
6276
  /**
6542
- * Own the MCP server behind `/api/mcp`. Each tool lives in its own file under
6543
- * `tools/`.
6277
+ * Own the MCP server behind `/api/mcp`. A tool that the REST API also serves
6278
+ * is an API operation, registered by `tools/api-operation.ts`; each other tool
6279
+ * lives in its own file under `tools/`.
6544
6280
  *
6545
6281
  * Each request gets a new server and a stateless transport that answers with
6546
6282
  * JSON. No MCP session or SSE stream outlives the request, so the route works
6547
6283
  * on any app instance and is not limited by the live-stream duration.
6548
6284
  */
6549
- /** The tools that each scope unlocks. A client sees only its granted tools. */
6285
+ /** Operations that the REST API also serves. Each names its own scope. */
6286
+ const OPERATIONS = [...conversationOperations];
6287
+ /**
6288
+ * The hand-written tools that each scope unlocks. A client sees only its
6289
+ * granted tools.
6290
+ */
6550
6291
  const TOOLS_BY_SCOPE = {
6551
6292
  "conversations:read": [
6552
6293
  registerSearchConversationsTool,
6553
6294
  registerGetConversationTool,
6554
6295
  registerListConversationMessagesTool
6555
6296
  ],
6556
- "conversations:manage": [
6557
- registerArchiveConversationTool,
6558
- registerArchiveDoneConversationsTool,
6559
- registerPinConversationTool,
6560
- registerSetConversationAutoArchiveTool,
6561
- registerSetConversationSubscriptionTool,
6562
- registerMarkConversationReadTool,
6563
- registerStopConversationTool,
6564
- registerCancelQueuedMessagesTool
6565
- ],
6297
+ "conversations:manage": [registerMarkConversationReadTool],
6566
6298
  "conversations:write": [registerCreateConversationTool, registerSendMessageTool],
6567
- "review_items:read": [registerSearchReviewItemsTool, registerGetReviewItemTool],
6299
+ "inbox_items:read": [registerSearchInboxItemsTool, registerGetInboxItemTool],
6568
6300
  "automations:read": [registerSearchAutomationsTool, registerGetAutomationTool]
6569
6301
  };
6570
6302
  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.`;
6303
+ 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
6304
  }
6573
6305
  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.`;
6306
+ 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
6307
  }
6576
6308
  /** Build the MCP server for one authenticated user and granted scopes. */
6577
6309
  function createMcpServer(context, scopes) {
@@ -6580,6 +6312,7 @@ function createMcpServer(context, scopes) {
6580
6312
  version: JUNIOR_VERSION
6581
6313
  }, { instructions: scopes.includes("conversations:write") ? writeInstructions(botConfig.userName) : readInstructions(botConfig.userName) });
6582
6314
  for (const scope of scopes) for (const register of TOOLS_BY_SCOPE[scope]) register(server, context);
6315
+ for (const operation of OPERATIONS) if (scopes.includes(operation.scope)) registerApiOperationTool(server, operation, context);
6583
6316
  return server;
6584
6317
  }
6585
6318
  /** Answer one Streamable HTTP POST for an authenticated user. */
@@ -7145,6 +6878,7 @@ function dashboardHostRoutePaths(dashboard, authenticatedRoutes = []) {
7145
6878
  "/api/notifications",
7146
6879
  "/api/notifications/*",
7147
6880
  "/api/images/*",
6881
+ "/api/lead",
7148
6882
  "/api/objects",
7149
6883
  "/api/stats",
7150
6884
  "/api/versions",
@@ -7155,8 +6889,8 @@ function dashboardHostRoutePaths(dashboard, authenticatedRoutes = []) {
7155
6889
  "/api/people",
7156
6890
  "/api/people/*",
7157
6891
  "/api/inbox/*",
7158
- "/api/review-items",
7159
- "/api/review-items/*",
6892
+ "/api/inbox-items",
6893
+ "/api/inbox-items/*",
7160
6894
  "/api/personal-tokens",
7161
6895
  "/api/personal-tokens/*",
7162
6896
  "/api/service-accounts",
@@ -7351,7 +7085,6 @@ async function createApp(options) {
7351
7085
  const previousConfigDefaults = getConfigDefaults();
7352
7086
  const previousSandboxResources = getSandboxResourceConfig();
7353
7087
  const previousExperimentalFeatures = getExperimentalFeatures();
7354
- const previousBriefsConfig = setBriefsConfig(options?.briefs);
7355
7088
  const previousEventEmbeddingsConfig = setEventEmbeddingsConfig(options?.eventEmbeddings);
7356
7089
  const previousMemoryConfig = setMemoryConfig(options?.memory);
7357
7090
  const previousDashboardLinkOptions = setDashboardConversationLinkOptions(dashboard);
@@ -7364,7 +7097,6 @@ async function createApp(options) {
7364
7097
  restoreRuntimeConfig(previousRuntimeConfig);
7365
7098
  setSandboxResourceConfig(previousSandboxResources);
7366
7099
  setExperimentalFeatures(previousExperimentalFeatures);
7367
- setBriefsConfig(previousBriefsConfig);
7368
7100
  setEventEmbeddingsConfig(previousEventEmbeddingsConfig);
7369
7101
  setMemoryConfig(previousMemoryConfig);
7370
7102
  setDashboardConversationLinkOptions(previousDashboardLinkOptions);
@@ -7407,7 +7139,7 @@ async function createApp(options) {
7407
7139
  pluginRoutes = getPluginRoutes({
7408
7140
  dispatchForIdentity,
7409
7141
  events,
7410
- showReviewItem: createSlackReviewItemShow(getProductionSlackAdapter)
7142
+ showInboxItem: createSlackInboxItemShow(getProductionSlackAdapter)
7411
7143
  });
7412
7144
  if (dashboard && !dashboard.disabled) {
7413
7145
  pluginApiRoutes = getPluginApiRoutes();
@@ -7628,7 +7360,7 @@ async function createApp(options) {
7628
7360
  conversationWorkQueue,
7629
7361
  dispatchForIdentity,
7630
7362
  events,
7631
- showReviewItem: createSlackReviewItemShow(getProductionSlackAdapter)
7363
+ showInboxItem: createSlackInboxItemShow(getProductionSlackAdapter)
7632
7364
  });
7633
7365
  });
7634
7366
  app.get("/api/internal/retention", (c) => {