@sentry/junior 0.278.0 → 0.279.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 (86) hide show
  1. package/dist/{adapter-BXosqTMx.js → adapter-phTTgw7H.js} +1 -1
  2. package/dist/{admin-Thn7NfOi.js → admin-PcpJDugZ.js} +1 -1
  3. package/dist/{agent-invocations-D7c4BQGc.js → agent-invocations-CUg_SODU.js} +0 -1
  4. package/dist/{agent-runner-DE-43MPb.js → agent-runner-DwvT1BY0.js} +76 -35
  5. package/dist/api/schema.d.ts +2 -2
  6. package/dist/api/schema.js +5 -5
  7. package/dist/api.d.ts +1 -1
  8. package/dist/api.js +37 -367
  9. package/dist/{app-CHNS-AX2.d.ts → app-DVs6noo7.d.ts} +3 -3
  10. package/dist/app.d.ts +1 -1
  11. package/dist/app.js +460 -77
  12. package/dist/{assistant-reply-pauL6qyn.js → assistant-reply-BXfxczd7.js} +1 -1
  13. package/dist/{automation-DphoTRYl.js → automation-BehArCcq.js} +1 -1
  14. package/dist/{background-compaction-queue-CAL4A2y7.js → background-compaction-queue-CcbuLJrZ.js} +2 -2
  15. package/dist/{briefs-4fyPJJEu.js → briefs-Dd_ezwED.js} +10 -9
  16. package/dist/{catalog-runtime-BoOb5oUv.js → catalog-runtime-BWVMeZhW.js} +2 -2
  17. package/dist/cli/chat.js +16 -16
  18. package/dist/cli/check.js +3 -3
  19. package/dist/cli/main.js +4 -4
  20. package/dist/cli/plugins.js +5 -5
  21. package/dist/cli/snapshot-create.js +4 -4
  22. package/dist/cli/upgrade.d.ts +1 -1
  23. package/dist/cli/upgrade.js +4 -4
  24. package/dist/{client-v_OVYuHZ.js → client-Bpxe4vKa.js} +7 -3
  25. package/dist/{config-o2jLRY5J.js → config-C_bmRhrJ.js} +2 -2
  26. package/dist/{connections-RC4NXAx8.js → connections-B2rHe5W5.js} +10 -10
  27. package/dist/{conversation-CZfyQvdm.js → conversation-CIiJtx5q.js} +6 -1
  28. package/dist/conversation-pending-messages-CnBvE6-6.js +173 -0
  29. package/dist/{conversation-privacy-C23M8KaD.js → conversation-privacy-CzOfcz0U.js} +1 -1
  30. package/dist/{credential-sync-Dd0WyNfF.js → credential-sync-Dal_unpv.js} +15 -15
  31. package/dist/{db-BjLzDJCt.d.ts → db-CyLrV9C7.d.ts} +1 -1
  32. package/dist/{executor-CJfsD0VX.js → executor-BfYH-Wws.js} +6 -4
  33. package/dist/instrumentation.d.ts +12 -0
  34. package/dist/instrumentation.js +56 -23
  35. package/dist/{logging-dFaXvBRK.js → logging-CkT3_Xxp.js} +2 -2
  36. package/dist/{message-DSwxIZet.js → message-Q5dkgaJ5.js} +10 -10
  37. package/dist/nitro.d.ts +1 -1
  38. package/dist/nitro.js +18 -6
  39. package/dist/{oauth-callback-server-CDcuCp27.js → oauth-callback-server-BDRaqe8O.js} +2 -2
  40. package/dist/{oauth-relay-C6ZAyJgf.js → oauth-relay-D0G3T16m.js} +1 -1
  41. package/dist/{package-discovery-DJBompdd.js → package-discovery-DJhGdS4c.js} +1 -1
  42. package/dist/{plugins-DOm9Y6qI.js → plugins-HYh_JOdw.js} +1 -1
  43. package/dist/{projection-BTge9wrH.js → projection-DWxX7pb1.js} +122 -44
  44. package/dist/{prompt-DDtCnlHP.js → prompt--dwus7Y-.js} +1 -1
  45. package/dist/proxy-path-BHYoKZdq.js +15 -0
  46. package/dist/{registry-Cp6CNmtP.js → registry-DnrdeO4s.js} +2 -2
  47. package/dist/{resolve-B_7h2cXx.js → resolve-C_QXfqD_.js} +3 -3
  48. package/dist/{result-5LBEfnLX.js → result-DNmOxT-N.js} +10 -10
  49. package/dist/{runner-C5-S4oq-.js → runner-zd_noJ1l.js} +11 -11
  50. package/dist/{sandbox-egress-signals-B4GehT1L.js → sandbox-egress-signals-DQjv-nbG.js} +1 -1
  51. package/dist/{schema-B5fpczDw.js → schema-CNJNzvr8.js} +5 -68
  52. package/dist/{schema-Tr484cCC.d.ts → schema-e90H5FIN.d.ts} +988 -1
  53. package/dist/sentry-BRTJqumy.js +51 -0
  54. package/dist/sentry-DrKC2NeM.d.ts +1 -0
  55. package/dist/sentry-route-name-BhwWnfqj.js +51 -0
  56. package/dist/{service-account-Cq_dLrZJ.js → service-account-BK26XlHo.js} +3 -3
  57. package/dist/{service-account-BkEv20zf.js → service-account-CCH2Hv4h.js} +3 -3
  58. package/dist/{session-stop-BsS4qFS2.js → session-stop-6Tf--T7G.js} +14 -14
  59. package/dist/{skills-M0BA0_s6.js → skills-BNrk8gi4.js} +4 -4
  60. package/dist/{spawn-BO3y7H4d.js → spawn-C75hAB9l.js} +3 -3
  61. package/dist/{stop-D5R82Wla.js → stop-RYbf7PWi.js} +516 -172
  62. package/dist/{store-BGBzQWNf.js → store-CO5vGjwD.js} +5 -5
  63. package/dist/{store-CGJZTEVz.js → store-G3h2djJU.js} +3 -3
  64. package/dist/{task-queue-UD27ei2U.js → task-queue-DlN58XeM.js} +3 -3
  65. package/dist/{task-runner-noxjOjkM.js → task-runner-B-Bdm23d.js} +21 -9
  66. package/dist/{thread-state-BSu6rM6p.js → thread-state-Cj_7Slru.js} +4 -4
  67. package/dist/{turn-failure-response-wahwyPrZ.js → turn-failure-response-CE7gaoC7.js} +7 -7
  68. package/dist/{turn-lifecycle-Bo4Trccw.js → turn-lifecycle-7sXwXLJ6.js} +1 -1
  69. package/dist/{turn-session-routing-DnSaaEpn.js → turn-session-routing-FBdaH1zf.js} +10 -10
  70. package/dist/{validation-B9-8iKyw.js → validation-DLWxEzWW.js} +2 -2
  71. package/dist/{version-C7HejFP2.js → version-DtQ8WFIZ.js} +1 -1
  72. package/dist/version.js +1 -1
  73. package/dist/{viewer-DLXajQZE.js → viewer-vsM8_90o.js} +5 -5
  74. package/dist/{work-DRGSlfia.js → work-DsoFRO_0.js} +10 -10
  75. package/dist/{worker-BGh5Dwc6.js → worker-6kZEsCXs.js} +7 -7
  76. package/migrations/0077_drop_agent_invocation_model_profile.sql +1 -0
  77. package/migrations/0078_plugin_conversation_index.sql +20 -0
  78. package/migrations/0079_conversation_event_author_index.sql +20 -0
  79. package/migrations/meta/0077_snapshot.json +4141 -0
  80. package/migrations/meta/0078_snapshot.json +4175 -0
  81. package/migrations/meta/0079_snapshot.json +4203 -0
  82. package/migrations/meta/_journal.json +21 -0
  83. package/package.json +5 -5
  84. package/dist/common-Eu6sx09c.js +0 -107
  85. package/dist/rolldown-runtime-nwUcYXjP.js +0 -27
  86. package/dist/sentry-MDkYAVPV.js +0 -23
package/dist/app.js CHANGED
@@ -1,39 +1,42 @@
1
- import { Ar as takeDueTimerWatches, C as settleConversationTitleWork, Cn as setExperimentalFeatures, Cr as collectEventMatchKeys, Ct as isInvalidConversationRecordError, Di as openSlackModal, Dr as findMatchingWatches, Fr as verifyScheduledAutomationCredentialSubject, Gi as getWorkspaceTeamId, Gr as createPluginState, Hn as setBriefsConfig, Hr as getDashboardTaskLink, Ir as verifySlackDirectCredentialSubject, Ki as runWithWorkspaceTeamId, Kn as dismissOpenReviewItems, Ln as getPlugins, Mn as getPluginRoutes, Mr as bindScheduledAutomationCredentialSubject, Ni as slackEntitySchema, Nr as bindSlackDirectCredentialSubject, Oi as postSlackEphemeralMessage, Pi as slackExternalRefIdSchema, Pr as verifyEventAutomationCredentialSubject, Qn as searchReviewItems, Rn as setPlugins, Sn as isExperimentalFeatureEnabled, Ur as setDashboardConversationLinkOptions, Vi as isDmChannel, Vr as getDashboardReviewItemLink, Wa as readConversationEventPage, _ as appendConversationMessages, _o as setConfigDefaults, aa as parseSandboxEgressCredentialToken, at as CONVERSATION_WORK_STALE_ENQUEUE_MS, b as projectConversationMessages, co as createPluginCache, di as proxyVercelSandboxEgressRequest, dn as SubscribedReplyReason, eo as resolveRootVisibility, go as getConfigDefaults, ha as createPluginEmbedder, hi as resolveBaseUrl, ja as readConversationAccessFromSql, jn as getPluginApiRoutes, jr as bindEventAutomationCredentialSubject, ka as createPluginLogger, la as normalizeSandboxEgressTracePropagationDomains, mn as getThreadStopDecision, na as consumeSandboxEgressAuthRequiredSignal, nr as canActOnReviewItem, ra as consumeSandboxEgressPermissionDeniedSignal, ro as listConversationAnnotations, ta as clearSandboxEgressSignals, ui as isVercelSandboxEgressRequest, ur as reviewItemReaderForUser, wn as createUserTokenStore, xi as slackMention, xn as getExperimentalFeatures, xt as hasRunnableConversationWork, zi as getSlackClient, zn as validatePlugins, zr as getDashboardConversationLink } from "./projection-BTge9wrH.js";
2
- import { d as restoreRuntimeConfig, f as setBotModelConfig, h as snapshotRuntimeConfig, i as getChatConfig, m as setSlackReactionConfig, n as botConfig, o as getSlackBotToken, p as setRuntimeLimits, u as resetRuntimeConfig } from "./config-o2jLRY5J.js";
3
- import { E as withSpan, I as JUNIOR_WORKSPACE_SNAPSHOT_JOB_CALLBACK_ROUTE, N as JUNIOR_PLUGIN_TASK_CALLBACK_ROUTE, O as JUNIOR_AUTO_ARCHIVE_ROUTE, T as withLogContext, U as normalizeIdentityEmail, V as GOOGLE_IDENTITY_PROVIDER, b as setSpanAttributes, h as logWarn, k as JUNIOR_CONTEXT_COMPACTION_CALLBACK_ROUTE, m as logInfo, p as logException, r as createRequestContext, w as withContext } from "./logging-dFaXvBRK.js";
4
- import { n as captureMessage } from "./sentry-MDkYAVPV.js";
5
- import { t as JUNIOR_VERSION } from "./version-C7HejFP2.js";
1
+ import { n as captureMessage } from "./sentry-BRTJqumy.js";
2
+ import { Aa as createPluginLogger, Ar as takeDueTimerWatches, C as settleConversationTitleWork, Cn as setExperimentalFeatures, Cr as collectEventMatchKeys, Ct as isInvalidConversationRecordError, Di as openSlackModal, Dr as findMatchingWatches, Fr as verifyScheduledAutomationCredentialSubject, Ga as readConversationEventPage, Gi as getWorkspaceTeamId, Gr as createPluginState, Hn as setBriefsConfig, Hr as getDashboardTaskLink, Ir as verifySlackDirectCredentialSubject, Ja as readConversationLastEventSeq, Ka as readConversationEventPageAfter, Ki as runWithWorkspaceTeamId, Kn as dismissOpenReviewItems, Ln as getPlugins, Ma as readConversationAccessFromSql, Mn as getPluginRoutes, Mr as bindScheduledAutomationCredentialSubject, Ni as slackEntitySchema, Nr as bindSlackDirectCredentialSubject, Oi as postSlackEphemeralMessage, Pi as slackExternalRefIdSchema, Pr as verifyEventAutomationCredentialSubject, Qn as searchReviewItems, Rn as setPlugins, Sn as isExperimentalFeatureEnabled, Ur as setDashboardConversationLinkOptions, Vi as isDmChannel, Vr as getDashboardReviewItemLink, Ya as readConversationMessageEventSeq, _ as appendConversationMessages, aa as parseSandboxEgressCredentialToken, at as CONVERSATION_WORK_STALE_ENQUEUE_MS, b as projectConversationMessages, bo as setConfigDefaults, di as proxyVercelSandboxEgressRequest, dn as SubscribedReplyReason, do as createPluginCache, ha as createPluginEmbedder, hi as resolveBaseUrl, jn as getPluginApiRoutes, jr as bindEventAutomationCredentialSubject, la as normalizeSandboxEgressTracePropagationDomains, mn as getThreadStopDecision, na as consumeSandboxEgressAuthRequiredSignal, nr as canActOnReviewItem, oo as listConversationAnnotations, ra as consumeSandboxEgressPermissionDeniedSignal, ro as resolveRootVisibility, ta as clearSandboxEgressSignals, ui as isVercelSandboxEgressRequest, ur as reviewItemReaderForUser, wn as createUserTokenStore, xi as slackMention, xn as getExperimentalFeatures, xt as hasRunnableConversationWork, yo as getConfigDefaults, zi as getSlackClient, zn as validatePlugins, zr as getDashboardConversationLink } from "./projection-DWxX7pb1.js";
3
+ import { d as restoreRuntimeConfig, f as setBotModelConfig, h as snapshotRuntimeConfig, i as getChatConfig, m as setSlackReactionConfig, n as botConfig, o as getSlackBotToken, p as setRuntimeLimits, u as resetRuntimeConfig } from "./config-C_bmRhrJ.js";
4
+ import { E as withSpan, I as JUNIOR_WORKSPACE_SNAPSHOT_JOB_CALLBACK_ROUTE, N as JUNIOR_PLUGIN_TASK_CALLBACK_ROUTE, O as JUNIOR_AUTO_ARCHIVE_ROUTE, T as withLogContext, U as normalizeIdentityEmail, V as GOOGLE_IDENTITY_PROVIDER, b as setSpanAttributes, h as logWarn, k as JUNIOR_CONTEXT_COMPACTION_CALLBACK_ROUTE, m as logInfo, p as logException, r as createRequestContext, w as withContext } from "./logging-CkT3_Xxp.js";
5
+ import { t as JUNIOR_VERSION } from "./version-DtQ8WFIZ.js";
6
6
  import { _ as slackMessageTsSchema, f as parseSlackTeamId, g as slackMessageTsFromMs, h as parseSlackMessageTs, m as slackChannelIdSchema, n as createSlackActor, p as parseSlackUserId, s as parseActorUserId, u as parseSlackChannelId } from "./actor-B4DYygOB.js";
7
- import { C as getSqlExecutor, H as recordGoogleSignIn, I as resolveActorIdentityId, M as withConversationMutationLock, S as getDb, Y as touchConversationDetail, _ as closeDb, g as createCache, i as readActorIdentity, k as withConversationEventLock, l as resolveViewerUser, p as parseAvatarUrl, x as getConversationStore, y as getConversationEventStore } from "./viewer-DLXajQZE.js";
8
- import { a as juniorAgentInvocations, d as juniorDestinations, i as juniorAgentBindings, s as juniorConversations } from "./agent-invocations-D7c4BQGc.js";
9
- import { _ as juniorConversationBriefs, b as juniorConversationEvents, c as juniorReviewItems, d as juniorAutomations, l as juniorAutomationRuns } from "./executor-CJfsD0VX.js";
10
- import { n as pluginCatalogRuntime } from "./catalog-runtime-BoOb5oUv.js";
11
- import { $ as readViewerAutomations, A as runWithSlackInstallation, B as logScheduledAutomationRunSkipped, C as readSlackReviewItemCardConversationId, D as parseSlackReviewItemClick, Dt as processWorkspaceSnapshotJob, E as buildSlackReviewItemModal, L as joinPublicChannel, M as parseSlackThreadId, O as parseSlackReviewItemFormTarget, Ot as ingestEvent, S as createSlackReviewItemShow, V as scheduledAutomationRunAttributes, Y as readViewerAutomationExecutions, Z as readViewerAutomationSummary, _ as readPublicArtifact, _t as requestAttachmentDeletion, at as reviewItemChangeRecord, bt as stopConversationSession, ct as conversationTurnIdForMessage, dt as recordWebConversationActivity, ft as webActorFromUser, g as publicArtifactHeaders, ht as collectAttachmentGarbage, it as renderReviewItemMessage, j as verifySlackSignature, k as parseSlackUserInputSubmission, n as executeAgentRun, q as ViewerTaskNotFoundError, r as processBackgroundCompaction, rt as deliverReviewItemChange, st as appendAndEnqueueWebMessage, t as createAgentRunner, tt as effectiveTaskOutcomes, v as unpublishedArtifactHeaders, w as syncReviewItemSlackCards, xt as recordSubagentEnded, y as lookupSlackUserProfile } from "./agent-runner-DE-43MPb.js";
7
+ import { C as getSqlExecutor, H as recordGoogleSignIn, I as resolveActorIdentityId, M as withConversationMutationLock, S as getDb, Y as touchConversationDetail, _ as closeDb, g as createCache, i as readActorIdentity, k as withConversationEventLock, l as resolveViewerUser, p as parseAvatarUrl, x as getConversationStore, y as getConversationEventStore } from "./viewer-vsM8_90o.js";
8
+ import { a as juniorAgentInvocations, d as juniorDestinations, i as juniorAgentBindings, s as juniorConversations } from "./agent-invocations-CUg_SODU.js";
9
+ import { _ as juniorConversationBriefs, b as juniorConversationEvents, c as juniorReviewItems, d as juniorAutomations, l as juniorAutomationRuns } from "./executor-BfYH-Wws.js";
10
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-BWVMeZhW.js";
11
+ import { $ as readViewerAutomations, A as runWithSlackInstallation, B as logScheduledAutomationRunSkipped, C as readSlackReviewItemCardConversationId, D as parseSlackReviewItemClick, Dt as processWorkspaceSnapshotJob, E as buildSlackReviewItemModal, L as joinPublicChannel, M as parseSlackThreadId, O as parseSlackReviewItemFormTarget, Ot as ingestEvent, S as createSlackReviewItemShow, V as scheduledAutomationRunAttributes, Y as readViewerAutomationExecutions, Z as readViewerAutomationSummary, _ as readPublicArtifact, _t as requestAttachmentDeletion, at as reviewItemChangeRecord, bt as stopConversationSession, ct as conversationTurnIdForMessage, dt as recordWebConversationActivity, ft as webActorFromUser, g as publicArtifactHeaders, ht as collectAttachmentGarbage, it as renderReviewItemMessage, j as verifySlackSignature, k as parseSlackUserInputSubmission, n as executeAgentRun, q as ViewerTaskNotFoundError, r as processBackgroundCompaction, rt as deliverReviewItemChange, st as appendAndEnqueueWebMessage, t as createAgentRunner, tt as effectiveTaskOutcomes, v as unpublishedArtifactHeaders, w as syncReviewItemSlackCards, xt as recordSubagentEnded, y as lookupSlackUserProfile } from "./agent-runner-DwvT1BY0.js";
12
12
  import { a as withLock, i as fenceLock, n as MUTATION_LOCK_TTL_MS } from "./locks-D-0h111u.js";
13
- import { r as getStateAdapter, t as disconnectStateAdapter } from "./adapter-BXosqTMx.js";
13
+ import { r as getStateAdapter, t as disconnectStateAdapter } from "./adapter-phTTgw7H.js";
14
14
  import { n as getNextRunAtMs } from "./cadence-R7Em4RjE.js";
15
- import { H as conversationBriefSchema, b as conversationSurfaceSchema, f as conversationFeedQuerySchema, k as annotationCard, v as conversationReportStatusSchema } from "./conversation-CZfyQvdm.js";
16
- import { S as listPendingAgentInvocationResults, x as listPendingAgentInvocationMailboxAppends } from "./store-BGBzQWNf.js";
17
- import { A as renderSlackObjectCard, T as renderTaskInput, d as getEventCatalog, f as SLACK_EVENT_NAMESPACE, g as slackChannelMessageRunsAutomation, h as slackChannelMessageReplyThreadTs, m as slackChannelMessageEvent } from "./session-stop-BsS4qFS2.js";
15
+ import { H as conversationBriefSchema, b as conversationSurfaceSchema, f as conversationFeedQuerySchema, k as annotationCard, v as conversationReportStatusSchema } from "./conversation-CIiJtx5q.js";
16
+ import { t as SANDBOX_EGRESS_PROXY_PATH } from "./proxy-path-BHYoKZdq.js";
17
+ import { S as listPendingAgentInvocationResults, x as listPendingAgentInvocationMailboxAppends } from "./store-CO5vGjwD.js";
18
+ import { A as renderSlackObjectCard, T as renderTaskInput, d as getEventCatalog, f as SLACK_EVENT_NAMESPACE, g as slackChannelMessageRunsAutomation, h as slackChannelMessageReplyThreadTs, m as slackChannelMessageEvent } from "./session-stop-6Tf--T7G.js";
18
19
  import { h as buttonUserInputField } from "./reporting-window-DgHgwQB3.js";
19
- import { c as setSandboxResourceConfig, o as getSandboxResourceConfig } from "./resolve-B_7h2cXx.js";
20
- import { a as WORKSPACE_SNAPSHOT_JOB_QUEUE_TOPIC, b as isConversationQueueMessageRejectedError, c as verifyWorkspaceSnapshotJobMessage, d as verifyConversationQueueMessage, h as getQueueProvider, i as verifyBackgroundCompactionMessage, l as getVercelConversationWorkQueue, r as vercelBackgroundCompactionQueue, t as BACKGROUND_COMPACTION_QUEUE_TOPIC, u as resolveConversationWorkQueueTopic, y as conversationQueueMessageSchema } from "./background-compaction-queue-CAL4A2y7.js";
21
- import { S as removeActiveConversation, _ as hasRunnableConversationWork$1, c as clearExpiredConversationLease, g as getConversationWorkState, h as getConversation, m as ensureConversationWake, r as appendAndEnqueueInboundMessage, v as listActiveConversationIds } from "./store-CGJZTEVz.js";
22
- import { B as readScheduledAutomation, G as blockEventAutomation, H as saveScheduledAutomationInLock, K as collectEventAutomationMatchKeys, M as recordAutomationExecution, R as listScheduledAutomationsForTeam, S as existingConversationId, U as scheduledRunId, W as withScheduledAutomationLock, Y as findMatchingEventAutomations, a as confirmDispatchMailboxAppend, b as notifyAutomationBlocked, f as getPluginDispatchProjection, ht as eventGuidance, it as automationVersionOf, m as listPendingDispatchMailboxAppends, nt as eventAutomationRunLimitReason, o as createOrGetDispatch, p as isTerminalDispatchStatus, r as buildDispatchId, s as getDispatchConversationId, tt as admitEventAutomationRun, u as getDispatchRecord, v as markDispatchFailed } from "./turn-session-routing-DnSaaEpn.js";
23
- import { M as scheduledRunSchema, l as automationListQuerySchema, s as automationExecutionStatusSchema } from "./automation-DphoTRYl.js";
24
- import { n as validatePluginRegistrations, t as validatePluginEgressCredentialHooks } from "./validation-B9-8iKyw.js";
25
- import { a as pluginRuntimeRegistrationsFromPluginSet, n as pluginCatalogConfigFromEnv, r as pluginCatalogConfigFromPluginSet, t as defineJuniorPlugins } from "./plugins-DOm9Y6qI.js";
26
- import { A as recordSkippedConversationMessage, B as startProcessingReaction, C as getProductionSlackAdapter, D as isAllowedSignInEmail, E as isAllowedDomain, F as normalizeIncomingSlackThreadId, G as closeReviewItemsAnsweredByReply, H as parseContent, I as withNormalizedThreadId, K as readReviewItemForUser, L as stopConversationTurn, M as clearSlackPendingReactions, N as isSlackMessageStopped, O as readEnvList, P as stopSlackThread, Q as runAutoArchiveSweep, R as THREAD_OPTOUT_ACK, S as createProductionSlackWebhookServices, T as assertNoLegacyAllowedDomains, U as ReviewItemActionError, V as stripLeadingBotMention, W as actOnReviewItem, b as archiveConversation, d as readConversationRecordFromSql, it as getAttachmentStorage, j as buildSlackInboundMessage, k as resolveAllowedDomains, n as readConversationDetail, ot as enqueueAgentDispatch, q as reviewItemChange, st as GET$4, t as stopConversationTurnForViewer, u as readConversationFeed, v as decodeConversationCursor, w as createSlackWebApiStatusSender, x as createProductionConversationWorkOptions, y as encodeConversationCursor, z as bindMessageAuthorIdentityId } from "./stop-D5R82Wla.js";
27
- import { n as enqueueAgentInvocationResult, o as getAuthPausedConversationTurnId } from "./result-5LBEfnLX.js";
28
- import { i as enqueueAgentInvocation, r as endAgentInvocationsOfStoppedWork } from "./work-DRGSlfia.js";
29
- import { o as coerceThreadConversationState } from "./thread-state-BSu6rM6p.js";
30
- import { o as unlinkProvider } from "./connections-RC4NXAx8.js";
31
- import { a as GET$5, i as publishAppHomeView, r as GET$6, t as receiveLocalOAuthCredential } from "./credential-sync-Dd0WyNfF.js";
32
- import { a as pluginTaskQueueConsumer, c as queueCallback, n as createVercelPluginTaskCallback, o as registerVercelPluginTaskDevConsumer } from "./task-queue-UD27ei2U.js";
33
- import { t as processConversationWork } from "./worker-BGh5Dwc6.js";
34
- import { t as bindMessageAgent } from "./message-DSwxIZet.js";
35
- import { t as bindSpawnAgent } from "./spawn-BO3y7H4d.js";
36
- import { t as processPluginTask } from "./task-runner-noxjOjkM.js";
20
+ import { c as setSandboxResourceConfig, o as getSandboxResourceConfig } from "./resolve-C_QXfqD_.js";
21
+ import { a as WORKSPACE_SNAPSHOT_JOB_QUEUE_TOPIC, b as isConversationQueueMessageRejectedError, c as verifyWorkspaceSnapshotJobMessage, d as verifyConversationQueueMessage, h as getQueueProvider, i as verifyBackgroundCompactionMessage, l as getVercelConversationWorkQueue, r as vercelBackgroundCompactionQueue, t as BACKGROUND_COMPACTION_QUEUE_TOPIC, u as resolveConversationWorkQueueTopic, y as conversationQueueMessageSchema } from "./background-compaction-queue-CcbuLJrZ.js";
22
+ import { S as removeActiveConversation, _ as hasRunnableConversationWork$1, c as clearExpiredConversationLease, g as getConversationWorkState, h as getConversation, m as ensureConversationWake, r as appendAndEnqueueInboundMessage, v as listActiveConversationIds } from "./store-G3h2djJU.js";
23
+ import { B as readScheduledAutomation, G as blockEventAutomation, H as saveScheduledAutomationInLock, K as collectEventAutomationMatchKeys, M as recordAutomationExecution, R as listScheduledAutomationsForTeam, S as existingConversationId, U as scheduledRunId, W as withScheduledAutomationLock, Y as findMatchingEventAutomations, a as confirmDispatchMailboxAppend, b as notifyAutomationBlocked, f as getPluginDispatchProjection, ht as eventGuidance, it as automationVersionOf, m as listPendingDispatchMailboxAppends, nt as eventAutomationRunLimitReason, o as createOrGetDispatch, p as isTerminalDispatchStatus, r as buildDispatchId, s as getDispatchConversationId, tt as admitEventAutomationRun, u as getDispatchRecord, v as markDispatchFailed } from "./turn-session-routing-FBdaH1zf.js";
24
+ import { M as scheduledRunSchema, l as automationListQuerySchema, s as automationExecutionStatusSchema } from "./automation-BehArCcq.js";
25
+ import { n as validatePluginRegistrations, t as validatePluginEgressCredentialHooks } from "./validation-DLWxEzWW.js";
26
+ import { a as pluginRuntimeRegistrationsFromPluginSet, n as pluginCatalogConfigFromEnv, r as pluginCatalogConfigFromPluginSet, t as defineJuniorPlugins } from "./plugins-HYh_JOdw.js";
27
+ import { a as conversationPendingMessageDeliverySchema } from "./conversation-pending-messages-CnBvE6-6.js";
28
+ import { $ as readReviewItemForUser, A as getProductionSlackAdapter, B as isSlackMessageStopped, C as cancelConversationPendingMessagesForViewer, D as archiveConversation, F as readEnvList, G as THREAD_OPTOUT_ACK, H as normalizeIncomingSlackThreadId, I as resolveAllowedDomains, J as stripLeadingBotMention, K as bindMessageAuthorIdentityId, L as recordSkippedConversationMessage, M as assertNoLegacyAllowedDomains, N as isAllowedDomain, O as createProductionConversationWorkOptions, P as isAllowedSignInEmail, Q as closeReviewItemsAnsweredByReply, R as buildSlackInboundMessage, S as encodeConversationCursor, U as withNormalizedThreadId, V as stopSlackThread, W as stopConversationTurn, X as ReviewItemActionError, Y as parseContent, Z as actOnReviewItem, a as markConversationRead, at as runAutoArchiveSweep, b as createConversationForViewer, dt as getAttachmentStorage, et as reviewItemChange, f as readConversationFeed, i as readConversationDetail, j as createSlackWebApiStatusSender, k as createProductionSlackWebhookServices, mt as GET$4, n as steerConversationPendingMessagesForViewer, nt as archiveViewerDoneConversations, ot as setConversationAutoArchive, p as readConversationRecordFromSql, pt as enqueueAgentDispatch, q as startProcessingReaction, r as pinConversation, t as stopConversationTurnForViewer, w as readConversationPendingMessages, x as decodeConversationCursor, y as appendConversationMessageForViewer, z as clearSlackPendingReactions } from "./stop-RYbf7PWi.js";
29
+ import { n as enqueueAgentInvocationResult, o as getAuthPausedConversationTurnId } from "./result-DNmOxT-N.js";
30
+ import { i as enqueueAgentInvocation, r as endAgentInvocationsOfStoppedWork } from "./work-DsoFRO_0.js";
31
+ import { o as coerceThreadConversationState } from "./thread-state-Cj_7Slru.js";
32
+ import { o as unlinkProvider } from "./connections-B2rHe5W5.js";
33
+ import { a as GET$5, i as publishAppHomeView, r as GET$6, t as receiveLocalOAuthCredential } from "./credential-sync-Dal_unpv.js";
34
+ import { t as nameRequestRoute } from "./sentry-route-name-BhwWnfqj.js";
35
+ import { a as pluginTaskQueueConsumer, c as queueCallback, n as createVercelPluginTaskCallback, o as registerVercelPluginTaskDevConsumer } from "./task-queue-DlN58XeM.js";
36
+ import { t as processConversationWork } from "./worker-6kZEsCXs.js";
37
+ import { t as bindMessageAgent } from "./message-Q5dkgaJ5.js";
38
+ import { t as bindSpawnAgent } from "./spawn-C75hAB9l.js";
39
+ import { t as processPluginTask } from "./task-runner-B-Bdm23d.js";
37
40
  import { createRequire } from "node:module";
38
41
  import { Hono } from "hono";
39
42
  import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
@@ -1478,11 +1481,15 @@ function isSandboxEgressRequest(request) {
1478
1481
  return isVercelSandboxEgressRequest(request);
1479
1482
  }
1480
1483
  // src/handlers/sandbox-egress-route.ts
1484
+ const SANDBOX_EGRESS_ROUTE = `${SANDBOX_EGRESS_PROXY_PATH}/<token>`;
1481
1485
  /**
1482
1486
  * Route authenticated sandbox egress proxy traffic before ordinary app routes.
1483
1487
  */
1484
1488
  async function handleSandboxEgressRoute(request, tracePropagationDomains, next) {
1485
- if (isSandboxEgressRequest(request)) return await ALL(request, { tracePropagation: { domains: tracePropagationDomains } });
1489
+ if (isSandboxEgressRequest(request)) {
1490
+ nameRequestRoute(request.method, SANDBOX_EGRESS_ROUTE);
1491
+ return await ALL(request, { tracePropagation: { domains: tracePropagationDomains } });
1492
+ }
1486
1493
  await next();
1487
1494
  }
1488
1495
  // src/handlers/sandbox-egress-signals.ts
@@ -3070,7 +3077,6 @@ async function handleWebhookRequest(request, platform, run) {
3070
3077
  }
3071
3078
  logWarn("webhook.response.unsuccessful", {
3072
3079
  "http.response.status_code": response.status,
3073
- "http.request.header.x_slack_signature": request.headers.get("x-slack-signature") ?? void 0,
3074
3080
  "http.request.header.x_slack_request_timestamp": request.headers.get("x-slack-request-timestamp") ?? void 0,
3075
3081
  ...responseBodySnippet ? { "app.webhook.response_body": responseBodySnippet } : void 0
3076
3082
  });
@@ -5449,8 +5455,10 @@ function renderMcpPage(page) {
5449
5455
  }
5450
5456
  // src/api/mcp/oauth/scopes.ts
5451
5457
  /**
5452
- * Own the MCP OAuth scopes. Each scope unlocks a fixed set of tools. No
5453
- * scope lets a client send a message or start a Turn.
5458
+ * Own the MCP OAuth scopes. Each scope unlocks a fixed set of tools. Only
5459
+ * `conversations:write` lets a client send a message, which starts agent
5460
+ * work as the user. It is a separate scope so a grant without it can never
5461
+ * start a Turn.
5454
5462
  *
5455
5463
  * A grant stores its scopes as one space-separated string (RFC 6749 section
5456
5464
  * 3.3), so grants from before the scope split still parse.
@@ -5459,13 +5467,15 @@ function renderMcpPage(page) {
5459
5467
  const MCP_SCOPES = [
5460
5468
  "conversations:read",
5461
5469
  "conversations:manage",
5470
+ "conversations:write",
5462
5471
  "review_items:read",
5463
5472
  "automations:read"
5464
5473
  ];
5465
5474
  /** What each scope lets the client do, as the consent page says it. */
5466
5475
  const MCP_SCOPE_DESCRIPTIONS = {
5467
5476
  "conversations:read": "List and read the conversations that you started or take part in",
5468
- "conversations:manage": "Archive your conversations and stop a running Turn",
5477
+ "conversations:manage": "Archive, pin, and mark your conversations read, stop a running Turn, and cancel queued messages",
5478
+ "conversations:write": "Start conversations and send messages as you. Junior runs agent work for each message",
5469
5479
  "review_items:read": "List and read your review items",
5470
5480
  "automations:read": "List and read the automations that you can see"
5471
5481
  };
@@ -5496,7 +5506,7 @@ const AUTHORIZATION_TTL_MS = 6e5;
5496
5506
  const STATE_MAX_LENGTH = 1e3;
5497
5507
  const AUTHORIZATION_ID_PATTERN = /^[A-Za-z0-9_-]{43}$/;
5498
5508
  const CODE_CHALLENGE_PATTERN = /^[A-Za-z0-9_-]{43}$/;
5499
- const mcpAuthorizationSchema = z.object({
5509
+ const mcpAuthorizationSchema$1 = z.object({
5500
5510
  clientId: z.string().min(1),
5501
5511
  clientName: z.string().min(1).optional(),
5502
5512
  codeChallenge: z.string().regex(CODE_CHALLENGE_PATTERN),
@@ -5527,7 +5537,7 @@ function claimedKey(authorizationId) {
5527
5537
  */
5528
5538
  async function readMcpAuthorization(state, authorizationId) {
5529
5539
  if (!AUTHORIZATION_ID_PATTERN.test(authorizationId)) return void 0;
5530
- const authorization = await readRecord(state, authorizationKey(authorizationId), mcpAuthorizationSchema);
5540
+ const authorization = await readRecord(state, authorizationKey(authorizationId), mcpAuthorizationSchema$1);
5531
5541
  if (!authorization || authorization.expiresAtMs <= Date.now()) return;
5532
5542
  if (await state.get(claimedKey(authorizationId)) !== null) return void 0;
5533
5543
  return {
@@ -5991,14 +6001,15 @@ async function handleMcpConsentPage(args) {
5991
6001
  const mcpConversationSchema = z.object({
5992
6002
  conversationId: z.string(),
5993
6003
  title: z.string(),
5994
- status: conversationReportStatusSchema,
5995
- surface: conversationSurfaceSchema,
5996
- channelName: z.string().optional(),
5997
- locationUrl: z.string().optional(),
6004
+ status: conversationReportStatusSchema.describe("`active` while work runs, waits to start, or waits on you. `completed` when no work is left. `failed` when the last turn failed."),
6005
+ surface: conversationSurfaceSchema.describe("Where it started: `slack`, `api` (the dashboard or MCP), `scheduler` (an automation), or `internal`."),
6006
+ channelName: z.string().optional().describe("Slack channel name."),
6007
+ locationUrl: z.string().optional().describe("Slack thread link."),
5998
6008
  startedAt: z.string(),
5999
- lastSeenAt: z.string(),
6000
- archivedAt: z.string().optional(),
6001
- url: z.string().optional()
6009
+ lastSeenAt: z.string().describe("Time of the newest activity. archiveConversation takes this value."),
6010
+ archivedAt: z.string().optional().describe("Set when you archived it."),
6011
+ pinnedAt: z.string().optional().describe("Set when you pinned it."),
6012
+ url: z.string().optional().describe("Dashboard link.")
6002
6013
  }).strict();
6003
6014
  /** Map a Conversation summary to its MCP view. */
6004
6015
  function mcpConversation(summary) {
@@ -6012,23 +6023,36 @@ function mcpConversation(summary) {
6012
6023
  startedAt: summary.startedAt,
6013
6024
  lastSeenAt: summary.lastSeenAt,
6014
6025
  archivedAt: summary.archivedAt ?? void 0,
6026
+ pinnedAt: summary.pinnedAt ?? void 0,
6015
6027
  url: getDashboardConversationLink(summary.conversationId)
6016
6028
  };
6017
6029
  }
6018
6030
  /** Conversation id param shared by the conversation tools. */
6019
- const mcpConversationIdSchema = z.string().min(1).describe("Conversation id from searchConversations.");
6031
+ const mcpConversationIdSchema = z.string().min(1).describe("Conversation id from searchConversations or createConversation.");
6032
+ const mcpAttachmentsSchema = z.array(z.object({
6033
+ filename: z.string(),
6034
+ contentType: z.string(),
6035
+ bytes: z.number().int()
6036
+ }).strict()).optional();
6037
+ function mcpAttachments(attachments) {
6038
+ return attachments?.length ? attachments.map(({ bytes, contentType, filename }) => ({
6039
+ bytes,
6040
+ contentType,
6041
+ filename
6042
+ })) : void 0;
6043
+ }
6044
+ function mcpAuthor(identity) {
6045
+ return identity?.fullName ?? identity?.slackUserName ?? identity?.email;
6046
+ }
6020
6047
  /** MCP view of one user or assistant Message. */
6021
6048
  const mcpMessageSchema = z.object({
6022
- seq: z.number().int(),
6049
+ seq: z.number().int().describe("Position in the transcript. markConversationRead takes this value."),
6050
+ messageId: z.string().describe("For a message that you sent, the `messageId` that sendMessage or createConversation returned."),
6023
6051
  createdAt: z.string(),
6024
6052
  role: z.enum(["assistant", "user"]),
6025
6053
  author: z.string().optional(),
6026
6054
  text: z.string(),
6027
- attachments: z.array(z.object({
6028
- filename: z.string(),
6029
- contentType: z.string(),
6030
- bytes: z.number().int()
6031
- }).strict()).optional()
6055
+ attachments: mcpAttachmentsSchema
6032
6056
  }).strict();
6033
6057
  /**
6034
6058
  * Keep the user and assistant Messages of a report event page, in order.
@@ -6039,23 +6063,99 @@ function mcpMessages(events) {
6039
6063
  const data = event.data;
6040
6064
  if (data.type !== "message" || data.role === "system") return [];
6041
6065
  const text = data.text ?? "";
6042
- const attachments = data.attachments?.map(({ bytes, contentType, filename }) => ({
6043
- bytes,
6044
- contentType,
6045
- filename
6046
- }));
6047
- if (!text && !attachments?.length) return [];
6048
- const author = data.actorIdentity?.fullName ?? data.actorIdentity?.slackUserName;
6066
+ const attachments = mcpAttachments(data.attachments);
6067
+ if (!text && !attachments) return [];
6068
+ const author = mcpAuthor(data.actorIdentity);
6049
6069
  return [{
6050
6070
  seq: event.seq,
6071
+ messageId: data.messageId,
6051
6072
  createdAt: event.createdAt,
6052
6073
  role: data.role,
6053
6074
  ...author ? { author } : void 0,
6054
6075
  text,
6055
- ...attachments?.length ? { attachments } : void 0
6076
+ ...attachments ? { attachments } : void 0
6077
+ }];
6078
+ });
6079
+ }
6080
+ /** Message text param shared by the tools that send a message. */
6081
+ const mcpMessageTextSchema = z.string().trim().min(1).max(32e3).describe("Message text.");
6082
+ /**
6083
+ * Idempotency key param shared by the tools that send a message. A retry
6084
+ * with the same key sends nothing new.
6085
+ */
6086
+ 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.");
6087
+ /**
6088
+ * MCP view of one accepted user Message that no Turn has read yet. It is not
6089
+ * in the transcript, so it has no `seq`.
6090
+ */
6091
+ const mcpPendingMessageSchema = z.object({
6092
+ messageId: z.string(),
6093
+ createdAt: z.string(),
6094
+ author: z.string().optional(),
6095
+ text: z.string(),
6096
+ attachments: mcpAttachmentsSchema,
6097
+ delivery: conversationPendingMessageDeliverySchema.describe("`defer` waits for the running turn to end. `interrupt` joins the running turn at its next safe step.")
6098
+ }).strict();
6099
+ /** Pending Messages field shared by `getConversation` and the send tools. */
6100
+ 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.");
6101
+ /** Authorization that a parked Turn waits for. */
6102
+ const mcpAuthorizationSchema = z.object({
6103
+ label: z.string(),
6104
+ url: z.string()
6105
+ }).strict().describe("Set when a turn waits for you to connect an account. Open `url` in a browser to continue.");
6106
+ /**
6107
+ * Read the Messages that wait for a Turn and the authorization that a parked
6108
+ * Turn waits for. The caller must check that `user` is a participant.
6109
+ */
6110
+ async function readMcpPendingWork(user, conversationId) {
6111
+ const report = await readConversationPendingMessages(conversationId, { viewer: user });
6112
+ const pendingMessages = (report?.messages ?? []).flatMap((message) => {
6113
+ if (message.text === void 0) return [];
6114
+ const author = mcpAuthor(message.actorIdentity);
6115
+ const attachments = mcpAttachments(message.attachments);
6116
+ return [{
6117
+ messageId: message.messageId,
6118
+ createdAt: message.createdAt,
6119
+ ...author ? { author } : void 0,
6120
+ text: message.text,
6121
+ ...attachments ? { attachments } : void 0,
6122
+ delivery: message.delivery
6056
6123
  }];
6057
6124
  });
6125
+ const authorization = report?.authorization;
6126
+ return {
6127
+ pendingMessages,
6128
+ ...authorization ? { authorization: {
6129
+ label: authorization.label,
6130
+ url: authorization.authorizationUrl
6131
+ } } : void 0
6132
+ };
6058
6133
  }
6134
+ /**
6135
+ * Read pending work for a send result. The message already landed, so a
6136
+ * failed read drops these optional fields instead of turning the accepted
6137
+ * send into a tool error that a client may retry.
6138
+ */
6139
+ async function readMcpPendingWorkAfterSend(user, conversationId) {
6140
+ try {
6141
+ return await readMcpPendingWork(user, conversationId);
6142
+ } catch (error) {
6143
+ logException(error, "mcp.pending_work.read.failed", { "gen_ai.conversation.id": conversationId });
6144
+ return {};
6145
+ }
6146
+ }
6147
+ /** `cursor` result field shared by getConversation and the send tools. */
6148
+ const mcpCursorSchema = z.string().describe("Pass as `after` to getConversation to read the messages that come after this point.");
6149
+ /** Result of a tool that sends a message. */
6150
+ const mcpAcceptedMessageSchema = {
6151
+ conversationId: z.string(),
6152
+ messageId: z.string().describe("Id of your message in `pendingMessages`, and later in the transcript."),
6153
+ status: z.enum(["accepted", "duplicate"]).describe("`duplicate` when the idempotency key was already used."),
6154
+ 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."),
6155
+ authorization: mcpAuthorizationSchema.optional(),
6156
+ cursor: mcpCursorSchema,
6157
+ url: z.string().optional().describe("Dashboard link.")
6158
+ };
6059
6159
  // src/api/mcp/tool-context.ts
6060
6160
  /**
6061
6161
  * Return one structured tool result. The text block holds the same JSON, as
@@ -6107,7 +6207,7 @@ function registerArchiveConversationTool(server, { user }) {
6107
6207
  archived: z.boolean().default(true).describe("False restores an archived conversation."),
6108
6208
  lastSeenAt: z.string().datetime().describe("`lastSeenAt` from searchConversations or getConversation. The archive fails when the conversation has newer activity.")
6109
6209
  },
6110
- outputSchema: { archivedAt: z.string().nullable() },
6210
+ outputSchema: { archivedAt: z.string().nullable().describe("Null when the conversation is not archived.") },
6111
6211
  annotations: {
6112
6212
  destructiveHint: false,
6113
6213
  idempotentHint: true,
@@ -6125,6 +6225,97 @@ function registerArchiveConversationTool(server, { user }) {
6125
6225
  }
6126
6226
  });
6127
6227
  }
6228
+ // src/api/mcp/tools/archive-done-conversations.ts
6229
+ /**
6230
+ * Register `archiveDoneConversations`, which archives every done
6231
+ * Conversation of the user once.
6232
+ */
6233
+ function registerArchiveDoneConversationsTool(server, { user }) {
6234
+ server.registerTool("archiveDoneConversations", {
6235
+ title: "Archive done conversations",
6236
+ description: "Archive all of your conversations whose work is done, once. It skips pinned conversations, conversations with auto-archive off, and conversations that wait on you. Archiving hides them only for you.",
6237
+ inputSchema: {},
6238
+ outputSchema: { archived: z.number().int().describe("Conversations archived.") },
6239
+ annotations: {
6240
+ destructiveHint: false,
6241
+ idempotentHint: true,
6242
+ openWorldHint: false,
6243
+ readOnlyHint: false
6244
+ }
6245
+ }, async () => mcpToolResult(await archiveViewerDoneConversations(user)));
6246
+ }
6247
+ // src/api/mcp/tools/cancel-queued-messages.ts
6248
+ /**
6249
+ * Register `cancelQueuedMessages`, which drops the messages that wait for
6250
+ * the running Turn and leaves the Turn running.
6251
+ */
6252
+ function registerCancelQueuedMessagesTool(server, { user }) {
6253
+ server.registerTool("cancelQueuedMessages", {
6254
+ title: "Cancel queued messages",
6255
+ description: "Drop every message that waits for the running turn of one of your conversations. The running turn continues.",
6256
+ inputSchema: { conversationId: mcpConversationIdSchema },
6257
+ outputSchema: { cancelledMessages: z.number().int().describe("Messages dropped.") },
6258
+ annotations: {
6259
+ destructiveHint: true,
6260
+ idempotentHint: true,
6261
+ openWorldHint: false,
6262
+ readOnlyHint: false
6263
+ }
6264
+ }, async ({ conversationId }) => {
6265
+ if (!await isConversationParticipant(user, conversationId)) return mcpToolError("Conversation not found.");
6266
+ try {
6267
+ return mcpToolResult({ cancelledMessages: (await cancelConversationPendingMessagesForViewer(user, conversationId)).cancelledCount });
6268
+ } catch (error) {
6269
+ return apiToolError(error);
6270
+ }
6271
+ });
6272
+ }
6273
+ // src/api/mcp/tools/create-conversation.ts
6274
+ /**
6275
+ * Register `createConversation`, which starts a dashboard Conversation with
6276
+ * the user's first message. Junior starts a Turn for it.
6277
+ */
6278
+ function registerCreateConversationTool(server, { attachmentStorage, queue, user }) {
6279
+ server.registerTool("createConversation", {
6280
+ title: "Create conversation",
6281
+ description: "Start a new conversation as you, with a first message. The agent works on it in the background. Returns the messages that no turn has read yet and a `cursor`. Pass the `cursor` as `after` to getConversation to read the reply.",
6282
+ inputSchema: {
6283
+ message: mcpMessageTextSchema,
6284
+ visibility: z.enum(["private", "public"]).default("private").describe("`private` keeps it to its participants. `public` lets people in your workspace find and read it."),
6285
+ idempotencyKey: mcpIdempotencyKeySchema
6286
+ },
6287
+ outputSchema: mcpAcceptedMessageSchema,
6288
+ annotations: {
6289
+ destructiveHint: false,
6290
+ idempotentHint: false,
6291
+ openWorldHint: true,
6292
+ readOnlyHint: false
6293
+ }
6294
+ }, async ({ idempotencyKey, message, visibility }) => {
6295
+ let accepted;
6296
+ try {
6297
+ accepted = await createConversationForViewer(user, {
6298
+ idempotencyKey: idempotencyKey ?? randomUUID(),
6299
+ message,
6300
+ visibility
6301
+ }, {
6302
+ attachmentStorage,
6303
+ queue
6304
+ });
6305
+ } catch (error) {
6306
+ return apiToolError(error);
6307
+ }
6308
+ return mcpToolResult({
6309
+ ...accepted,
6310
+ ...await readMcpPendingWorkAfterSend(user, accepted.conversationId),
6311
+ cursor: encodeConversationCursor({
6312
+ conversationId: accepted.conversationId,
6313
+ seq: -1
6314
+ }),
6315
+ url: getDashboardConversationLink(accepted.conversationId)
6316
+ });
6317
+ });
6318
+ }
6128
6319
  // src/api/mcp/automation.ts
6129
6320
  /** Own the MCP view of one Automation, shared by the automation tools. */
6130
6321
  /** MCP view of one Automation. It omits cost and run-count charts. */
@@ -6240,19 +6431,49 @@ function mcpBrief(brief, updatedAt) {
6240
6431
  };
6241
6432
  }
6242
6433
  const RECENT_EVENT_LIMIT = 100;
6434
+ const AFTER_EVENT_SCAN_LIMIT = 200;
6435
+ const AFTER_MESSAGE_LIMIT = 20;
6436
+ /**
6437
+ * Read the Messages after a transcript position and the position to continue
6438
+ * from. The cursor stops at the last returned Message when more are left.
6439
+ */
6440
+ async function readMessagesAfter(conversationId, afterSeq) {
6441
+ const page = await readConversationEventPageAfter(getSqlExecutor(), {
6442
+ afterSeq,
6443
+ canExposePayload: true,
6444
+ conversationId,
6445
+ limit: AFTER_EVENT_SCAN_LIMIT
6446
+ });
6447
+ const scanned = mcpMessages(page.events);
6448
+ const messages = scanned.slice(0, AFTER_MESSAGE_LIMIT);
6449
+ const cut = scanned.length > messages.length;
6450
+ return {
6451
+ messages,
6452
+ hasMore: cut || page.nextSeq !== void 0,
6453
+ seq: cut ? messages.at(-1).seq : page.events.at(-1)?.seq ?? afterSeq
6454
+ };
6455
+ }
6243
6456
  /**
6244
6457
  * Register `getConversation`. It returns metadata, the Brief, and the last
6245
- * Reply, not the whole transcript.
6458
+ * Reply or the Messages after a cursor, not the whole transcript.
6246
6459
  */
6247
6460
  function registerGetConversationTool(server, { user }) {
6248
6461
  server.registerTool("getConversation", {
6249
6462
  title: "Get conversation",
6250
- description: "Get one conversation: its metadata, its Brief (a summary of intent, outcome, and state), and the last assistant reply. Use listConversationMessages for the full transcript.",
6251
- inputSchema: { conversationId: mcpConversationIdSchema },
6463
+ description: "Get one conversation: its metadata, its Brief (a summary of intent, outcome, and state), the messages that no turn has read yet, and a `cursor`. Without `after`, it returns the last assistant reply. With `after`, it returns the messages after that point instead. To follow a conversation, call it again with the newest `cursor` until `status` is not `active` and `hasMore` is not set. Use listConversationMessages for older messages.",
6464
+ inputSchema: {
6465
+ conversationId: mcpConversationIdSchema,
6466
+ after: z.string().min(1).max(1e3).optional().describe("`cursor` from sendMessage, createConversation, or an earlier getConversation call.")
6467
+ },
6252
6468
  outputSchema: {
6253
6469
  conversation: mcpConversationSchema,
6254
6470
  brief: mcpBriefSchema.optional(),
6255
- lastReply: mcpMessageSchema.optional()
6471
+ lastReply: mcpMessageSchema.optional().describe("Newest assistant message in the recent events. Set only without `after`."),
6472
+ messages: z.array(mcpMessageSchema).optional().describe("User and assistant messages after `after`, oldest first. Set only with `after`."),
6473
+ hasMore: z.boolean().optional().describe("True when more messages already follow `cursor`. Call again now, also when `status` is not `active`."),
6474
+ pendingMessages: mcpPendingMessagesSchema,
6475
+ authorization: mcpAuthorizationSchema.optional(),
6476
+ cursor: mcpCursorSchema
6256
6477
  },
6257
6478
  annotations: {
6258
6479
  destructiveHint: false,
@@ -6260,17 +6481,35 @@ function registerGetConversationTool(server, { user }) {
6260
6481
  openWorldHint: false,
6261
6482
  readOnlyHint: true
6262
6483
  }
6263
- }, async ({ conversationId }) => {
6484
+ }, async ({ after, conversationId }) => {
6485
+ const afterSeq = after ? decodeConversationCursor({
6486
+ conversationId,
6487
+ cursor: after
6488
+ })?.seq : void 0;
6489
+ if (after && afterSeq === void 0) return mcpToolError("The cursor is not valid. Omit `after` to read the current state.");
6264
6490
  const detail = await isConversationParticipant(user, conversationId) ? await readConversationDetail(conversationId, {
6265
6491
  limit: RECENT_EVENT_LIMIT,
6266
6492
  viewer: user
6267
6493
  }) : void 0;
6268
6494
  if (!detail) return mcpToolError("Conversation not found.");
6269
- const lastReply = mcpMessages(detail.events).filter((message) => message.role === "assistant").at(-1);
6495
+ const newer = afterSeq === void 0 ? void 0 : detail.eventHistory.status === "expired" ? {
6496
+ messages: [],
6497
+ hasMore: false,
6498
+ seq: afterSeq
6499
+ } : await readMessagesAfter(conversationId, afterSeq);
6500
+ const lastReply = newer ? void 0 : mcpMessages(detail.events).filter((message) => message.role === "assistant").at(-1);
6501
+ const cursorSeq = newer?.seq ?? detail.events.at(-1)?.seq ?? -1;
6270
6502
  return mcpToolResult({
6271
6503
  conversation: mcpConversation(detail),
6272
6504
  ...detail.brief ? { brief: mcpBrief(detail.brief.content, detail.brief.updatedAt) } : void 0,
6273
- ...lastReply ? { lastReply } : void 0
6505
+ ...lastReply ? { lastReply } : void 0,
6506
+ ...newer ? { messages: newer.messages } : void 0,
6507
+ ...newer?.hasMore ? { hasMore: true } : void 0,
6508
+ ...await readMcpPendingWork(user, conversationId),
6509
+ cursor: encodeConversationCursor({
6510
+ conversationId,
6511
+ seq: cursorSeq
6512
+ })
6274
6513
  });
6275
6514
  });
6276
6515
  }
@@ -6440,6 +6679,57 @@ function registerListConversationMessagesTool(server, { user }) {
6440
6679
  });
6441
6680
  });
6442
6681
  }
6682
+ // src/api/mcp/tools/mark-conversation-read.ts
6683
+ /** Register `markConversationRead`, which moves the user's read position. */
6684
+ function registerMarkConversationReadTool(server, { user }) {
6685
+ server.registerTool("markConversationRead", {
6686
+ title: "Mark conversation read",
6687
+ description: "Mark one of your conversations as read for you. The read position only moves forward.",
6688
+ inputSchema: {
6689
+ conversationId: mcpConversationIdSchema,
6690
+ lastReadSeq: z.number().int().nonnegative().optional().describe("`seq` of the last message read, from listConversationMessages or getConversation. Omit it to mark every message read.")
6691
+ },
6692
+ outputSchema: { lastReadSeq: z.number().int().describe("`seq` of the last message that you read.") },
6693
+ annotations: {
6694
+ destructiveHint: false,
6695
+ idempotentHint: true,
6696
+ openWorldHint: false,
6697
+ readOnlyHint: false
6698
+ }
6699
+ }, async ({ conversationId, lastReadSeq }) => {
6700
+ if (!await isConversationParticipant(user, conversationId)) return mcpToolError("Conversation not found.");
6701
+ try {
6702
+ return mcpToolResult(await markConversationRead(user, conversationId, { lastReadSeq: lastReadSeq ?? Number.MAX_SAFE_INTEGER }));
6703
+ } catch (error) {
6704
+ return apiToolError(error);
6705
+ }
6706
+ });
6707
+ }
6708
+ // src/api/mcp/tools/pin-conversation.ts
6709
+ /** Register `pinConversation`, which pins or unpins for the user. */
6710
+ function registerPinConversationTool(server, { user }) {
6711
+ server.registerTool("pinConversation", {
6712
+ title: "Pin conversation",
6713
+ description: "Pin one of your conversations, or unpin it. A pin applies only to you, restores an archived conversation, and keeps auto-archive from archiving it.",
6714
+ inputSchema: {
6715
+ conversationId: mcpConversationIdSchema,
6716
+ pinned: z.boolean().default(true).describe("False unpins the conversation.")
6717
+ },
6718
+ outputSchema: { pinnedAt: z.string().nullable().describe("Null when the conversation is not pinned.") },
6719
+ annotations: {
6720
+ destructiveHint: false,
6721
+ idempotentHint: true,
6722
+ openWorldHint: false,
6723
+ readOnlyHint: false
6724
+ }
6725
+ }, async ({ conversationId, pinned }) => {
6726
+ try {
6727
+ return mcpToolResult(await pinConversation(user, conversationId, { pinned }));
6728
+ } catch (error) {
6729
+ return apiToolError(error);
6730
+ }
6731
+ });
6732
+ }
6443
6733
  // src/api/mcp/tools/search-conversations.ts
6444
6734
  /** Register `searchConversations`, which searches the Conversations of the user. */
6445
6735
  function registerSearchConversationsTool(server, { user }) {
@@ -6500,6 +6790,88 @@ function registerSearchReviewItemsTool(server, { user }) {
6500
6790
  });
6501
6791
  });
6502
6792
  }
6793
+ // src/api/mcp/tools/send-message.ts
6794
+ /**
6795
+ * Register `sendMessage`, which adds the user's message to a Conversation.
6796
+ * Junior reads it in a new Turn, or after the running Turn.
6797
+ */
6798
+ function registerSendMessageTool(server, { attachmentStorage, queue, user }) {
6799
+ server.registerTool("sendMessage", {
6800
+ title: "Send message",
6801
+ description: "Send a message as you to one of your conversations. The agent answers in the background. When a turn is running, the message waits for it unless `delivery` is `interrupt`. Returns the messages that no turn has read yet and a `cursor`. Pass the `cursor` as `after` to getConversation to read the reply.",
6802
+ inputSchema: {
6803
+ conversationId: mcpConversationIdSchema,
6804
+ message: mcpMessageTextSchema,
6805
+ idempotencyKey: mcpIdempotencyKeySchema,
6806
+ delivery: conversationPendingMessageDeliverySchema.default("defer").describe("`defer` waits for the running turn to end. `interrupt` joins the running turn at its next safe step. Use it to correct or add to the work in progress.")
6807
+ },
6808
+ outputSchema: mcpAcceptedMessageSchema,
6809
+ annotations: {
6810
+ destructiveHint: false,
6811
+ idempotentHint: false,
6812
+ openWorldHint: true,
6813
+ readOnlyHint: false
6814
+ }
6815
+ }, async ({ conversationId, delivery, idempotencyKey, message }) => {
6816
+ if (!await isConversationParticipant(user, conversationId)) return mcpToolError("Conversation not found.");
6817
+ const lastSeq = await readConversationLastEventSeq(getSqlExecutor(), conversationId);
6818
+ let accepted;
6819
+ try {
6820
+ accepted = await appendConversationMessageForViewer(user, conversationId, {
6821
+ idempotencyKey: idempotencyKey ?? randomUUID(),
6822
+ message
6823
+ }, {
6824
+ attachmentStorage,
6825
+ queue
6826
+ });
6827
+ } catch (error) {
6828
+ return apiToolError(error);
6829
+ }
6830
+ if (delivery === "interrupt") try {
6831
+ await steerConversationPendingMessagesForViewer(user, conversationId, { inboundMessageIds: [accepted.messageId] });
6832
+ } catch (error) {
6833
+ logException(error, "mcp.send_message.steer.failed", { "gen_ai.conversation.id": conversationId });
6834
+ }
6835
+ const messageSeq = accepted.status === "duplicate" ? await readConversationMessageEventSeq(getSqlExecutor(), accepted.conversationId, accepted.messageId) : void 0;
6836
+ return mcpToolResult({
6837
+ ...accepted,
6838
+ ...await readMcpPendingWorkAfterSend(user, accepted.conversationId),
6839
+ cursor: encodeConversationCursor({
6840
+ conversationId: accepted.conversationId,
6841
+ seq: messageSeq === void 0 ? lastSeq : messageSeq - 1
6842
+ }),
6843
+ url: getDashboardConversationLink(accepted.conversationId)
6844
+ });
6845
+ });
6846
+ }
6847
+ // src/api/mcp/tools/set-conversation-auto-archive.ts
6848
+ /**
6849
+ * Register `setConversationAutoArchive`, which overrides the user's
6850
+ * auto-archive default for one Conversation.
6851
+ */
6852
+ function registerSetConversationAutoArchiveTool(server, { user }) {
6853
+ server.registerTool("setConversationAutoArchive", {
6854
+ title: "Set conversation auto-archive",
6855
+ description: "Turn auto-archive on or off for one of your conversations. This overrides your default for that conversation only.",
6856
+ inputSchema: {
6857
+ conversationId: mcpConversationIdSchema,
6858
+ autoArchive: z.boolean().describe("True archives the conversation for you after its work is done. False keeps it in your list.")
6859
+ },
6860
+ outputSchema: { autoArchive: z.boolean() },
6861
+ annotations: {
6862
+ destructiveHint: false,
6863
+ idempotentHint: true,
6864
+ openWorldHint: false,
6865
+ readOnlyHint: false
6866
+ }
6867
+ }, async ({ autoArchive, conversationId }) => {
6868
+ try {
6869
+ return mcpToolResult(await setConversationAutoArchive(user, conversationId, autoArchive));
6870
+ } catch (error) {
6871
+ return apiToolError(error);
6872
+ }
6873
+ });
6874
+ }
6503
6875
  // src/api/mcp/tools/stop-conversation.ts
6504
6876
  /** Register `stopConversation`, which stops the active Turn. */
6505
6877
  function registerStopConversationTool(server, { queue, user }) {
@@ -6508,8 +6880,8 @@ function registerStopConversationTool(server, { queue, user }) {
6508
6880
  description: "Stop the running turn of one of your conversations. Messages that wait for the turn are dropped. It starts no new work.",
6509
6881
  inputSchema: { conversationId: mcpConversationIdSchema },
6510
6882
  outputSchema: {
6511
- status: z.enum(["no_work", "requested"]).describe("`no_work` when nothing was running."),
6512
- droppedMessages: z.number().int()
6883
+ status: z.enum(["no_work", "requested"]).describe("`requested` when the running turn was asked to stop. `no_work` when nothing was running."),
6884
+ droppedMessages: z.number().int().describe("Messages that waited for the turn and were dropped.")
6513
6885
  },
6514
6886
  annotations: {
6515
6887
  destructiveHint: true,
@@ -6546,17 +6918,27 @@ const TOOLS_BY_SCOPE = {
6546
6918
  registerGetConversationTool,
6547
6919
  registerListConversationMessagesTool
6548
6920
  ],
6549
- "conversations:manage": [registerArchiveConversationTool, registerStopConversationTool],
6921
+ "conversations:manage": [
6922
+ registerArchiveConversationTool,
6923
+ registerArchiveDoneConversationsTool,
6924
+ registerPinConversationTool,
6925
+ registerSetConversationAutoArchiveTool,
6926
+ registerMarkConversationReadTool,
6927
+ registerStopConversationTool,
6928
+ registerCancelQueuedMessagesTool
6929
+ ],
6930
+ "conversations:write": [registerCreateConversationTool, registerSendMessageTool],
6550
6931
  "review_items:read": [registerSearchReviewItemsTool, registerGetReviewItemTool],
6551
6932
  "automations:read": [registerSearchAutomationsTool, registerGetAutomationTool]
6552
6933
  };
6553
- const INSTRUCTIONS = "Junior is a Slack agent. These tools read your Junior conversations, review items, and automations. They cannot send a message or start agent work. To ask Junior for work or to answer a review item, use the Slack or dashboard link in a result.";
6934
+ const READ_INSTRUCTIONS = "Junior is a Slack agent. These tools read and manage your Junior conversations, and read your review items and automations. They cannot send a message or start agent work. To ask Junior for work or to answer a review item, use the Slack or dashboard link in a result.";
6935
+ const WRITE_INSTRUCTIONS = "Junior is a Slack agent. These tools read and manage your Junior conversations, and read your review items and automations. createConversation and sendMessage send a message as you, and Junior 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.";
6554
6936
  /** Build the MCP server for one authenticated user and granted scopes. */
6555
6937
  function createMcpServer(context, scopes) {
6556
6938
  const server = new McpServer({
6557
6939
  name: "junior",
6558
6940
  version: JUNIOR_VERSION
6559
- }, { instructions: INSTRUCTIONS });
6941
+ }, { instructions: scopes.includes("conversations:write") ? WRITE_INSTRUCTIONS : READ_INSTRUCTIONS });
6560
6942
  for (const scope of scopes) for (const register of TOOLS_BY_SCOPE[scope]) register(server, context);
6561
6943
  return server;
6562
6944
  }
@@ -6701,6 +7083,7 @@ function createMcpHttpHandler(options) {
6701
7083
  headers: { allow: "POST" }
6702
7084
  });
6703
7085
  return await handleMcpServerRequest(c.req.raw, {
7086
+ attachmentStorage: options.attachmentStorage,
6704
7087
  queue: options.queue,
6705
7088
  scopes: grant.scopes,
6706
7089
  user
@@ -7042,8 +7425,7 @@ function dashboardHostRoutePaths(dashboard, authenticatedRoutes = []) {
7042
7425
  "/favicon.ico",
7043
7426
  "/_junior/dashboard/avatar.png",
7044
7427
  "/_junior/dashboard/object-icons/*",
7045
- "/_junior/dashboard/client.js",
7046
- "/_junior/dashboard/chunks/*",
7428
+ "/_junior/dashboard/assets/*",
7047
7429
  "/_junior/dashboard/icon-512.png",
7048
7430
  "/_junior/dashboard/manifest.webmanifest",
7049
7431
  loginPath,
@@ -7425,7 +7807,7 @@ async function createApp(options) {
7425
7807
  logException(err, "route.unhandled.exception");
7426
7808
  return c.text("Internal Server Error", 500);
7427
7809
  });
7428
- app.use("*", async (c, next) => {
7810
+ app.use("*", async function sandboxEgress(c, next) {
7429
7811
  return await handleSandboxEgressRoute(c.req.raw, sandboxEgressTracePropagationDomains, next);
7430
7812
  });
7431
7813
  app.on([
@@ -7443,6 +7825,7 @@ async function createApp(options) {
7443
7825
  handleMcpRequest ??= createMcpHttpHandler({
7444
7826
  allowedDomains,
7445
7827
  baseURL: resolvePublicBaseURL(dashboard),
7828
+ attachmentStorage,
7446
7829
  queue: conversationWorkQueue,
7447
7830
  state: getMcpState()
7448
7831
  });