@sentry/junior 0.286.0 → 0.288.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 (78) hide show
  1. package/dist/{adapter-JQZaJ-B_.js → adapter-Cikcqdty.js} +1 -1
  2. package/dist/{admin-Dm2bimJ-.js → admin-BcSxHuTB.js} +2 -1
  3. package/dist/{agent-runner-DGCwOEyL.js → agent-runner-9MXyWUL8.js} +784 -368
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +9 -8
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +411 -65
  8. package/dist/{app-BKq0JzWx.d.ts → app-BUklJVBe.d.ts} +4 -2
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +555 -71
  11. package/dist/{assistant-reply-CAPafcUY.js → assistant-reply-mj47jMRV.js} +1 -1
  12. package/dist/{automation-B-jJN_gM.js → automation-DDXwHQs5.js} +4 -7
  13. package/dist/{background-compaction-queue-Btu2oab_.js → background-compaction-queue-CjllSPir.js} +161 -90
  14. package/dist/{briefs-UMeYehUe.js → briefs-DW9iuolG.js} +7 -5
  15. package/dist/{catalog-runtime-Bym8GVdh.js → catalog-runtime-B3gfH58M.js} +1 -1
  16. package/dist/cli/chat.js +14 -14
  17. package/dist/cli/check.js +3 -3
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +4 -4
  20. package/dist/cli/snapshot-create.js +4 -4
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +3 -3
  23. package/dist/config-CLJcyYEF.js +1762 -0
  24. package/dist/{connections-CQ7p0aNJ.js → connections-BtdJftow.js} +9 -9
  25. package/dist/{conversation-BusI2uzj.js → conversation-DhoqHtQ7.js} +30 -6
  26. package/dist/{conversation-pending-messages-DwehU0Fd.js → conversation-pending-messages-DHV0S4uF.js} +2 -5
  27. package/dist/{conversation-privacy-Cd_nZZBM.js → conversation-privacy-BPirIVlX.js} +1 -1
  28. package/dist/core-model-BTt5E5b0.js +182 -0
  29. package/dist/{credential-sync-DmiJi_At.js → credential-sync-Co8Q2xRW.js} +28 -20
  30. package/dist/{viewer-CH-ASQzh.js → db-Co7DTYYh.js} +62 -358
  31. package/dist/{db-C5zi4ecs.d.ts → db-zIs8-Ba3.d.ts} +6 -2
  32. package/dist/{executor-Dipi2Ixl.js → executor-m0kIN71Q.js} +102 -14
  33. package/dist/{media-B-BpXo41.js → history-IjdmO_r6.js} +8 -88
  34. package/dist/instrumentation.js +2 -2
  35. package/dist/{logging-CMFhLLj4.js → logging-DbD-dErY.js} +3 -2
  36. package/dist/media-BAHvgkok.js +85 -0
  37. package/dist/{message-D1xLljUF.js → message-DKTdTYm-.js} +10 -10
  38. package/dist/nitro.d.ts +1 -1
  39. package/dist/nitro.js +19 -41
  40. package/dist/{oauth-callback-server-DCAFIUQr.js → oauth-callback-server-CpbepSbp.js} +2 -2
  41. package/dist/{projection-CoeMNxJ4.js → projection-BViECfYu.js} +361 -746
  42. package/dist/{prompt-C9OQEfan.js → prompt-KT6MaDHN.js} +1 -1
  43. package/dist/{registry-u-sFYtx_.js → registry-D-Acyjhh.js} +1 -1
  44. package/dist/{reporting-window-B4TwyuJo.js → reporting-window-B3Ze-Qnt.js} +4 -1
  45. package/dist/{resolve-DYqgL3Eo.js → resolve-gkT2R66z.js} +3 -3
  46. package/dist/{result-CescSwAw.js → result-DHmCFEt8.js} +8 -8
  47. package/dist/{runner-Cr67a8TB.js → runner-DBKjGjH-.js} +8 -8
  48. package/dist/{sandbox-egress-signals-DLOazy5W.js → sandbox-egress-signals-9n8hqx29.js} +1 -1
  49. package/dist/{schedule-BTp__wrw.js → schedule-cP0AACm1.js} +11 -2
  50. package/dist/{schema-Ih60j59-.d.ts → schema-B_6aOcx5.d.ts} +159 -3
  51. package/dist/{schema-BUSi3sgv.js → schema-DxicIQbc.js} +79 -14
  52. package/dist/{service-account-CsKxktLk.js → service-account-Bi0HsY6w.js} +3 -3
  53. package/dist/{service-account-CGEqz9wG.js → service-account-CDlC9ssy.js} +3 -3
  54. package/dist/{session-stop-CGz5DByb.js → session-stop-BWOsuo8p.js} +62 -20
  55. package/dist/{skills-COCqf61f.js → skills-DO5K68Rq.js} +2 -2
  56. package/dist/spawn-BBqZDcPa.js +79 -0
  57. package/dist/{stop-GyFZkHuQ.js → stop-WC97cmHz.js} +832 -552
  58. package/dist/{store-D0-8plWp.js → store-ByR1Lr7e.js} +4 -16
  59. package/dist/{task-runner-xPuQmEot.js → task-runner-B-Ewf8TX.js} +30 -21
  60. package/dist/{turn-failure-response-BOviBdT-.js → turn-failure-response-CpdPoZSl.js} +25 -11
  61. package/dist/{validation-DZDKorGz.js → validation-B4sbIoES.js} +1 -1
  62. package/dist/{version-BTIz7fGi.js → version-D6lpuAgL.js} +1 -1
  63. package/dist/version.js +1 -1
  64. package/dist/viewer-CeP27tC3.js +337 -0
  65. package/dist/warmup-P_GJCL1c.js +767 -0
  66. package/dist/{work-C75_IM5e.js → work-DI7x1Slm.js} +32 -20
  67. package/dist/{worker-Dl47I729.js → worker-CYPTOT4j.js} +6 -7
  68. package/migrations/0088_conversation_unsubscribe.sql +1 -0
  69. package/migrations/0089_conversation_paused_status.sql +3 -0
  70. package/migrations/0090_guardian_review_time_index.sql +20 -0
  71. package/migrations/meta/0088_snapshot.json +4372 -0
  72. package/migrations/meta/0089_snapshot.json +4372 -0
  73. package/migrations/meta/0090_snapshot.json +4388 -0
  74. package/migrations/meta/_journal.json +21 -0
  75. package/package.json +5 -4
  76. package/dist/client-B0aAs7wC.js +0 -793
  77. package/dist/config-B9f9Lqo5.js +0 -579
  78. package/dist/spawn-C8F_iXWO.js +0 -42
package/dist/app.js CHANGED
@@ -1,38 +1,40 @@
1
1
  import { i as getActiveSpan, n as captureMessage, u as sentry_exports } from "./sentry-BRTJqumy.js";
2
- import { $r as bindScheduledAutomationCredentialSubject, Bo as getConfigDefaults, Ca as clearSandboxEgressSignals, Cn as SubscribedReplyReason, Co as resolveRootVisibility, Cr as canActOnReviewItem, Da as parseSandboxEgressCredentialToken, Dt as isInvalidConversationRecordError, En as getThreadStopDecision, Eo as listConversationAnnotations, Fn as setExperimentalFeatures, In as createUserTokenStore, Jr as findMatchingWatches, La as createPluginEmbedder, Li as resolveBaseUrl, Mi as isVercelSandboxEgressRequest, Mo as createPluginCache, Ni as proxyVercelSandboxEgressRequest, Nn as getExperimentalFeatures, Pn as isExperimentalFeatureEnabled, Qr as bindEventAutomationCredentialSubject, S as projectConversationMessages, Ta as consumeSandboxEgressPermissionDeniedSignal, Tt as hasRunnableConversationWork, Ui as slackMention, Un as getPluginApiRoutes, Vo as setConfigDefaults, Wn as getPluginRoutes, Wr as collectEventMatchKeys, Xi as postSlackEphemeralMessage, Xn as setPlugins, Yi as openSlackModal, Yn as getPlugins, Za as createPluginLogger, Zn as validatePlugins, Zr as takeDueTimerWatches, _ as appendConversationMessages, ci as getDashboardReviewItemLink, ct as CONVERSATION_WORK_STALE_ENQUEUE_MS, di as setDashboardConversationLinkOptions, do as readConversationEventPageAfter, ei as bindSlackDirectCredentialSubject, eo as readConversationAccessFromSql, er as setBriefsConfig, fr as dismissOpenReviewItems, ja as normalizeSandboxEgressTracePropagationDomains, jr as reviewItemReaderForUser, la as isDmChannel, ma as runWithWorkspaceTeamId, mo as readConversationMessageEventSeq, na as slackExternalRefIdSchema, ni as verifyScheduledAutomationCredentialSubject, oi as getDashboardConversationLink, pa as getWorkspaceTeamId, pi as createPluginState, po as readConversationLastEventSeq, ri as verifySlackDirectCredentialSubject, sa as getSlackClient, ta as slackEntitySchema, ti as verifyEventAutomationCredentialSubject, ui as getDashboardTaskLink, uo as readConversationEventPage, w as settleConversationTitleWork, wa as consumeSandboxEgressAuthRequiredSignal, yr as searchReviewItems } from "./projection-CoeMNxJ4.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, y as getAttachmentStorage } from "./config-B9f9Lqo5.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-CMFhLLj4.js";
5
- import { t as JUNIOR_VERSION } from "./version-BTIz7fGi.js";
2
+ import { $r as getDashboardConversationLink, Bn as getPlugins, Di as proxyVercelSandboxEgressRequest, Dn as createUserTokenStore, Ea as normalizeSandboxEgressTracePropagationDomains, Ei as isVercelSandboxEgressRequest, Fn as getPluginRoutes, Fo as setConfigDefaults, Ft as pruneActiveConversation, Gn as setBriefsConfig, Gr as bindEventAutomationCredentialSubject, Hn as validatePlugins, Jr as verifyEventAutomationCredentialSubject, Ka as createPluginLogger, Kr as bindScheduledAutomationCredentialSubject, Li as slackMention, Lr as collectEventMatchKeys, Ma as createPluginEmbedder, Ni as escapeSlackMrkdwnText, Oo as createPluginCache, Pi as formatSlackLink, Pn as getPluginApiRoutes, Po as getConfigDefaults, S as projectConversationMessages, Sa as parseSandboxEgressCredentialToken, So as listConversationAnnotations, Ui as openSlackModal, Vn as setPlugins, Vr as findMatchingWatches, Wi as postSlackEphemeralMessage, Wr as takeDueTimerWatches, Xi as slackEntitySchema, Xr as verifySlackDirectCredentialSubject, Ya as readConversationAccessFromSql, Yr as verifyScheduledAutomationCredentialSubject, Zi as slackExternalRefIdSchema, _ as appendConversationMessages, ai as setDashboardConversationLinkOptions, ao as readLatestConversationBrief, ba as consumeSandboxEgressPermissionDeniedSignal, ca as getWorkspaceTeamId, dr as searchReviewItems, dt as CONVERSATION_WORK_STALE_ENQUEUE_MS, hr as canActOnReviewItem, ia as isDmChannel, ii as parseDashboardConversationLink, ir as dismissOpenReviewItems, ji as resolveBaseUrl, jt as isInvalidConversationRecordError, kt as hasRunnableConversationWork, la as runWithWorkspaceTeamId, lo as readConversationLastEventSeq, na as getSlackClient, oo as readConversationEventPage, qi as unfurlSlackLinks, qr as bindSlackDirectCredentialSubject, ri as getDashboardTaskLink, si as createPluginState, so as readConversationEventPageAfter, ti as getDashboardReviewItemLink, uo as readConversationMessageEventSeq, va as clearSandboxEgressSignals, w as settleConversationTitleWork, wr as reviewItemReaderForUser, ya as consumeSandboxEgressAuthRequiredSignal, yo as resolveRootVisibility } from "./projection-BViECfYu.js";
3
+ import { J as getAttachmentStorage, 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-CLJcyYEF.js";
4
+ import { A as JUNIOR_CONTEXT_COMPACTION_CALLBACK_ROUTE, E as withSpan, G as normalizeIdentityEmail, L as JUNIOR_WORKSPACE_SNAPSHOT_JOB_CALLBACK_ROUTE, O as JUNIOR_AUTO_ARCHIVE_ROUTE, P as JUNIOR_PLUGIN_TASK_CALLBACK_ROUTE, T as withLogContext, U as GOOGLE_IDENTITY_PROVIDER, b as setSpanAttributes, h as logWarn, k as JUNIOR_CACHE_WARMUP_CALLBACK_ROUTE, m as logInfo, p as logException, r as createRequestContext, w as withContext } from "./logging-DbD-dErY.js";
5
+ import { t as JUNIOR_VERSION } from "./version-D6lpuAgL.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-6jsm_v96.js";
7
- import { C as getSqlExecutor, H as resolveActorIdentityId, I as withConversationMutationLock, J as recordGoogleSignIn, S as getDb, _ as closeDb, ct as createSlackDestination, g as createCache, i as readActorIdentity, k as withConversationEventLock, l as resolveViewerUser, p as parseAvatarUrl, tt as touchConversationDetail, x as getConversationStore, y as getConversationEventStore } from "./viewer-CH-ASQzh.js";
8
- import { A as juniorConversations, N as juniorDestinations, b as juniorConversationBriefs, f as juniorAutomations, g as juniorAgentInvocations, h as juniorAgentBindings, l as juniorReviewItems, u as juniorAutomationRuns, w as juniorConversationEvents } from "./executor-Dipi2Ixl.js";
9
- import { n as pluginCatalogRuntime } from "./catalog-runtime-Bym8GVdh.js";
10
- import { $ as readViewerAutomationSummary, A as runWithSlackInstallation, C as readSlackReviewItemCardConversationId, D as parseSlackReviewItemClick, E as buildSlackReviewItemModal, H as logScheduledAutomationRunSkipped, Ht as processWorkspaceSnapshotJob, M as parseSlackThreadId, O as parseSlackReviewItemFormTarget, S as createSlackReviewItemShow, St as recordSubagentEnded, U as scheduledAutomationRunAttributes, Ut as ingestEvent, Y as ViewerTaskNotFoundError, Z as readViewerAutomationExecutions, _ as readPublicArtifact, at as deliverReviewItemChange, g as publicArtifactHeaders, gt as collectAttachmentGarbage, j as verifySlackSignature, k as parseSlackUserInputSubmission, lt as appendAndEnqueueWebMessage, mt as webActorFromUser, n as executeAgentRun, ot as renderReviewItemMessage, pt as recordWebConversationActivity, r as processBackgroundCompaction, rt as effectiveTaskOutcomes, st as reviewItemChangeRecord, t as createAgentRunner, tt as readViewerAutomations, ut as conversationTurnIdForMessage, v as unpublishedArtifactHeaders, vt as requestAttachmentDeletion, w as syncReviewItemSlackCards, y as lookupSlackUserProfile, z as joinPublicChannel } from "./agent-runner-DGCwOEyL.js";
7
+ import { D as resolveActorIdentityId, H as touchConversationDetail, N as recordGoogleSignIn, R as getConversationIdByProviderConversation, Y as createSlackDestination, a as getConversationStore, b as withConversationMutationLock, o as getDb, p as withConversationEventLock, r as getConversationEventStore, s as getSqlExecutor, t as closeDb, x as conversationKindFromRow } from "./db-Co7DTYYh.js";
8
+ import { A as juniorConversations, N as juniorDestinations, b as juniorConversationBriefs, f as juniorAutomations, g as juniorAgentInvocations, h as juniorAgentBindings, l as juniorReviewItems, u as juniorAutomationRuns, w as juniorConversationEvents } from "./executor-m0kIN71Q.js";
9
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-B3gfH58M.js";
10
+ import { $ as readViewerAutomationSummary, A as runWithSlackInstallation, C as readSlackReviewItemCardConversationId, Ct as markConversationRead, D as parseSlackReviewItemClick, E as buildSlackReviewItemModal, H as logScheduledAutomationRunSkipped, I as checkSlackChannelReadAccess, M as parseSlackThreadId, O as parseSlackReviewItemFormTarget, S as createSlackReviewItemShow, U as scheduledAutomationRunAttributes, Xt as processWorkspaceSnapshotJob, Y as ViewerTaskNotFoundError, Z as readViewerAutomationExecutions, Zt as ingestEvent, _ as unpublishedArtifactHeaders, at as deliverReviewItemChange, g as readPublicArtifact, gt as collectAttachmentGarbage, h as publicArtifactHeaders, j as verifySlackSignature, k as parseSlackUserInputSubmission, kt as recordSubagentEnded, lt as appendAndEnqueueWebMessage, mt as webActorFromUser, n as executeAgentRun, ot as renderReviewItemMessage, pt as recordWebConversationActivity, r as processBackgroundCompaction, rt as effectiveTaskOutcomes, st as reviewItemChangeRecord, t as createAgentRunner, tt as readViewerAutomations, ut as conversationTurnIdForMessage, v as setConversationSubscription, vt as requestAttachmentDeletion, w as syncReviewItemSlackCards, xt as archiveConversation, y as lookupSlackUserProfile, z as joinPublicChannel } from "./agent-runner-9MXyWUL8.js";
11
11
  import { a as withLock, i as fenceLock, n as MUTATION_LOCK_TTL_MS } from "./locks-D-0h111u.js";
12
- import { r as getStateAdapter, t as disconnectStateAdapter } from "./adapter-JQZaJ-B_.js";
13
- import { a as getNextRunAtMs } from "./schedule-BTp__wrw.js";
14
- import { G as conversationBriefSchema, j as annotationCard, p as conversationFeedQuerySchema, x as conversationSurfaceSchema, y as conversationReportStatusSchema } from "./conversation-BusI2uzj.js";
12
+ import { g as createCache, i as readActorIdentity, l as resolveViewerUser, p as parseAvatarUrl } from "./viewer-CeP27tC3.js";
13
+ import { r as getStateAdapter, t as disconnectStateAdapter } from "./adapter-Cikcqdty.js";
14
+ import { a as getNextRunAtMs } from "./schedule-cP0AACm1.js";
15
+ import { F as annotationCard, X as conversationBriefSchema, k as conversationTitleSchema, p as conversationFeedQuerySchema, x as conversationSurfaceSchema, y as conversationReportStatusSchema } from "./conversation-DhoqHtQ7.js";
15
16
  import { t as SANDBOX_EGRESS_PROXY_PATH } from "./proxy-path-BHYoKZdq.js";
16
- import { D as listPendingAgentInvocationResults, E as listPendingAgentInvocationMailboxAppends } from "./turn-failure-response-BOviBdT-.js";
17
- import { M as slackChannelMessageReplyThreadTs, N as slackChannelMessageRunsAutomation, O as getEventCatalog, W as renderSlackObjectCard, d as getAuthPausedConversationTurnId, j as slackChannelMessageEvent, k as SLACK_EVENT_NAMESPACE, z as renderTaskInput } from "./session-stop-CGz5DByb.js";
18
- import { g as buttonUserInputField } from "./reporting-window-B4TwyuJo.js";
19
- import { c as setSandboxResourceConfig, o as getSandboxResourceConfig } from "./resolve-DYqgL3Eo.js";
20
- import { T as isConversationQueueMessageRejectedError, _ as getVercelConversationWorkQueue, f as queueCallback, g as verifyWorkspaceSnapshotJobMessage, i as verifyBackgroundCompactionMessage, l as pluginTaskQueueConsumer, o as createVercelPluginTaskCallback, p as WORKSPACE_SNAPSHOT_JOB_QUEUE_TOPIC, r as vercelBackgroundCompactionQueue, t as BACKGROUND_COMPACTION_QUEUE_TOPIC, u as registerVercelPluginTaskDevConsumer, v as resolveConversationWorkQueueTopic, w as conversationQueueMessageSchema, x as getQueueProvider, y as verifyConversationQueueMessage } from "./background-compaction-queue-Btu2oab_.js";
21
- import { C as removeActiveConversation, _ as getConversationWorkState, g as getConversation, h as ensureConversationWake, l as clearExpiredConversationLease, r as appendAndEnqueueInboundMessage, v as hasRunnableConversationWork$1, y as listActiveConversationIds } from "./store-D0-8plWp.js";
22
- import { A as withScheduledAutomationLock, E as readScheduledAutomation, F as findMatchingEventAutomations, H as eventAutomationRunLimitReason, M as collectEventAutomationMatchKeys, O as saveScheduledAutomationInLock, Q as existingConversationId, Tt as eventGuidance, V as admitEventAutomationRun, W as automationVersionOf, bt as coerceThreadConversationState, c as getDispatchConversationId, ct as recordAutomationExecution, d as getDispatchRecord, h as listPendingDispatchMailboxAppends, i as buildDispatchId, j as blockEventAutomation, k as scheduledRunId, m as isTerminalDispatchStatus, o as confirmDispatchMailboxAppend, p as getPluginDispatchProjection, s as createOrGetDispatch, t as processPluginTask, w as listScheduledAutomationsForTeam, x as notifyAutomationBlocked, y as markDispatchFailed } from "./task-runner-xPuQmEot.js";
23
- import { M as scheduledRunSchema, l as automationListQuerySchema, s as automationExecutionStatusSchema } from "./automation-B-jJN_gM.js";
24
- import { n as validatePluginRegistrations, t as validatePluginEgressCredentialHooks } from "./validation-DZDKorGz.js";
17
+ import { a as segmentGapsKey, c as MINUTE_MS, d as gapSegment, l as MIN_WARMUP_PREFIX_TOKENS, n as GLOBAL_GAPS_MAX, r as GLOBAL_GAPS_TTL_MS, t as CONVERSATION_STATE_TTL_MS, u as NO_REPLY_GAP_MS } from "./warmup-P_GJCL1c.js";
18
+ import { A as getQueueProvider, C as cacheWarmupQueueConsumer, O as queueCallback, T as registerVercelCacheWarmupDevConsumer, _ as resolveConversationWorkQueueTopic, b as conversationQueueMessageSchema, f as WORKSPACE_SNAPSHOT_JOB_QUEUE_TOPIC, g as getVercelConversationWorkQueue, h as verifyWorkspaceSnapshotJobMessage, i as verifyBackgroundCompactionMessage, l as pluginTaskQueueConsumer, o as createVercelPluginTaskCallback, r as vercelBackgroundCompactionQueue, t as BACKGROUND_COMPACTION_QUEUE_TOPIC, u as registerVercelPluginTaskDevConsumer, v as verifyConversationQueueMessage, w as createVercelCacheWarmupCallback, x as isConversationQueueMessageRejectedError } from "./background-compaction-queue-CjllSPir.js";
19
+ import { D as listPendingAgentInvocationResults, E as listPendingAgentInvocationMailboxAppends } from "./turn-failure-response-CpdPoZSl.js";
20
+ import { M as slackChannelMessageReplyThreadTs, N as slackChannelMessageRunsAutomation, O as getEventCatalog, W as renderSlackObjectCard, d as getAuthPausedConversationTurnId, it as setExperimentalFeatures, j as slackChannelMessageEvent, k as SLACK_EVENT_NAMESPACE, nt as getExperimentalFeatures, rt as isExperimentalFeatureEnabled, z as renderTaskInput } from "./session-stop-BWOsuo8p.js";
21
+ import { _ as buttonUserInputField } from "./reporting-window-B3Ze-Qnt.js";
22
+ import { c as setSandboxResourceConfig, o as getSandboxResourceConfig } from "./resolve-gkT2R66z.js";
23
+ import { _ as listActiveConversationIds, g as getConversationWorkState, h as getConversation, l as clearExpiredConversationLease, m as ensureConversationWake, r as appendAndEnqueueInboundMessage } from "./store-ByR1Lr7e.js";
24
+ import { A as withScheduledAutomationLock, E as readScheduledAutomation, F as findMatchingEventAutomations, H as eventAutomationRunLimitReason, M as collectEventAutomationMatchKeys, O as saveScheduledAutomationInLock, Q as existingConversationId, Tt as eventGuidance, V as admitEventAutomationRun, W as automationVersionOf, bt as coerceThreadConversationState, c as getDispatchConversationId, ct as recordAutomationExecution, d as getDispatchRecord, h as listPendingDispatchMailboxAppends, i as buildDispatchId, j as blockEventAutomation, k as scheduledRunId, m as isTerminalDispatchStatus, o as confirmDispatchMailboxAppend, p as getPluginDispatchProjection, s as createOrGetDispatch, t as processPluginTask, w as listScheduledAutomationsForTeam, x as notifyAutomationBlocked, y as markDispatchFailed } from "./task-runner-B-Ewf8TX.js";
25
+ import { M as scheduledRunSchema, l as automationListQuerySchema, s as automationExecutionStatusSchema } from "./automation-DDXwHQs5.js";
26
+ import { n as validatePluginRegistrations, t as validatePluginEgressCredentialHooks } from "./validation-B4sbIoES.js";
25
27
  import { a as pluginRuntimeRegistrationsFromPluginSet, n as pluginCatalogConfigFromEnv, r as pluginCatalogConfigFromPluginSet, t as defineJuniorPlugins } from "./plugins-HYh_JOdw.js";
26
- import { a as conversationPendingMessageDeliverySchema } from "./conversation-pending-messages-DwehU0Fd.js";
27
- import { $ as actOnReviewItem, A as archiveConversation, B as startProcessingReaction, C as createConversationForViewer, D as readConversationPendingMessages, E as cancelConversationPendingMessagesForViewer, F as assertNoLegacyAllowedDomains, G as normalizeIncomingSlackThreadId, H as clearSlackPendingReactions, I as isAllowedDomain, J as stopConversation, K as withNormalizedThreadId, L as isAllowedSignInEmail, M as createProductionConversationWorkOptions, N as createProductionSlackWebhookServices, P as getProductionSlackAdapter, Q as ReviewItemActionError, R as readEnvList, S as appendConversationMessageForViewer, T as encodeConversationCursor, U as slackInboundMessageId, V as buildSlackInboundMessage, W as stripLeadingBotMention, X as recordSkippedConversationMessage, Y as parseContent, Z as bindMessageAuthorIdentityId, a as pinConversation, b as readConversationRecordFromSql, et as closeReviewItemsAnsweredByReply, i as readConversationFeed, it as archiveViewerDoneConversations, j as markConversationRead, mt as GET$4, n as steerConversationPendingMessagesForViewer, nt as reviewItemChange, ot as runAutoArchiveSweep, pt as enqueueAgentDispatch, q as createSlackWebApiStatusSender, s as readConversationDetail, st as setConversationAutoArchive, t as stopConversationTurnForViewer, tt as readReviewItemForUser, w as decodeConversationCursor, z as resolveAllowedDomains } from "./stop-GyFZkHuQ.js";
28
- import { a as enqueueAgentInvocation, i as endAgentInvocationsOfStoppedWork } from "./work-C75_IM5e.js";
29
- import { n as enqueueAgentInvocationResult } from "./result-CescSwAw.js";
30
- import { o as unlinkProvider } from "./connections-CQ7p0aNJ.js";
31
- import { a as GET$5, i as publishAppHomeView, r as GET$6, t as receiveLocalOAuthCredential } from "./credential-sync-DmiJi_At.js";
28
+ import { a as conversationPendingMessageDeliverySchema } from "./conversation-pending-messages-DHV0S4uF.js";
29
+ import { $ as actOnReviewItem, A as createProductionConversationWorkOptions, B as clearSlackPendingReactions, C as createConversationForViewer, D as readConversationPendingMessages, E as cancelConversationPendingMessagesForViewer, F as isAllowedSignInEmail, G as createSlackWebApiStatusSender, H as stripLeadingBotMention, I as readEnvList, J as stopConversation, K as SubscribedReplyReason, L as resolveAllowedDomains, M as getProductionSlackAdapter, N as assertNoLegacyAllowedDomains, P as isAllowedDomain, Q as ReviewItemActionError, R as startProcessingReaction, S as appendConversationMessageForViewer, T as encodeConversationCursor, U as normalizeIncomingSlackThreadId, V as slackInboundMessageId, W as withNormalizedThreadId, X as recordSkippedConversationMessage, Y as parseContent, Z as bindMessageAuthorIdentityId, a as pinConversation, at as continueConversationInSlack, b as readConversationRecordFromSql, ct as archiveViewerDoneConversations, dt as setConversationAutoArchive, et as closeReviewItemsAnsweredByReply, ht as GET$4, i as readConversationFeed, it as canContinueInSlack, j as createProductionSlackWebhookServices, mt as enqueueAgentDispatch, n as steerConversationPendingMessagesForViewer, nt as reviewItemChange, ot as isMovableToSlack, q as getThreadStopDecision, rt as alreadyContinuesInSlackMessage, s as readConversationDetail, t as stopConversationTurnForViewer, tt as readReviewItemForUser, ut as runAutoArchiveSweep, w as decodeConversationCursor, z as buildSlackInboundMessage } from "./stop-WC97cmHz.js";
30
+ import { a as enqueueAgentInvocation, i as endAgentInvocationsOfStoppedWork } from "./work-DI7x1Slm.js";
31
+ import { n as enqueueAgentInvocationResult } from "./result-DHmCFEt8.js";
32
+ import { o as unlinkProvider } from "./connections-BtdJftow.js";
33
+ import { a as GET$5, i as publishAppHomeView, r as GET$6, t as receiveLocalOAuthCredential } from "./credential-sync-Co8Q2xRW.js";
32
34
  import { t as nameRequestRoute } from "./sentry-route-name-BhwWnfqj.js";
33
- import { t as processConversationWork } from "./worker-Dl47I729.js";
34
- import { t as bindMessageAgent } from "./message-D1xLljUF.js";
35
- import { t as bindSpawnAgent } from "./spawn-C8F_iXWO.js";
35
+ import { t as processConversationWork } from "./worker-CYPTOT4j.js";
36
+ import { t as bindMessageAgent } from "./message-DKTdTYm-.js";
37
+ import { t as bindSpawnAgent } from "./spawn-BBqZDcPa.js";
36
38
  import { createRequire } from "node:module";
37
39
  import { Hono } from "hono";
38
40
  import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
@@ -40,10 +42,12 @@ import * as z from "zod";
40
42
  import { and, asc, eq, inArray, isNotNull, isNull, lte, ne, or, sql } from "drizzle-orm";
41
43
  import { EVENT_SUMMARY_MAX_LENGTH, EVENT_TEXT_MAX_LENGTH, dispatchOptionsSchema, eventSchema, eventTriggerFiltersText, isSlackDestination, userSchema } from "@sentry/junior-plugin-api";
42
44
  import { pathToFileURL } from "node:url";
45
+ import pLimit from "p-limit";
43
46
  import net from "node:net";
44
47
  import { decodeJwt } from "jose";
45
- import https from "node:https";
48
+ import { performance } from "node:perf_hooks";
46
49
  import { HTTPException } from "hono/http-exception";
50
+ import https from "node:https";
47
51
  import { Message, ThreadImpl } from "chat";
48
52
  import * as acp from "@agentclientprotocol/sdk";
49
53
  import dns from "node:dns";
@@ -53,6 +57,232 @@ import { bodyLimit } from "hono/body-limit";
53
57
  import { createAuthMiddleware } from "better-auth/api";
54
58
  import { getSessionCookie } from "better-auth/cookies";
55
59
  import { betterAuth } from "better-auth/minimal";
60
+ // src/chat/cache-warming/backfill.ts
61
+ /**
62
+ * One-time fill of the cache warming gap lists from stored Conversation
63
+ * history.
64
+ *
65
+ * `warmup.ts` learns reply gaps only from idle periods after it is deployed.
66
+ * Until a `gapSegment` has gaps, Junior sends no warmups for it. This replays
67
+ * the stored model calls of the last `GLOBAL_GAPS_TTL_MS` with the same rules
68
+ * as live recording, so warming can start soon after the first deploy.
69
+ *
70
+ * The heartbeat runs it. Only one run claims it, and a completed run marks
71
+ * the install as done, also when it stopped on its time budget or skipped a
72
+ * batch that the statement timeout canceled. It fills only segment lists
73
+ * that are empty when it starts, so it does not add history to gaps that
74
+ * live recording already has.
75
+ */
76
+ const BACKFILL_KEY = "junior:cache_warming:backfill";
77
+ const BACKFILL_CLAIM_TTL_MS = 60 * MINUTE_MS;
78
+ const CONVERSATION_BATCH_SIZE = 10;
79
+ const QUERY_CANCELED = "57014";
80
+ const BACKFILL_BUDGET_MS = 6e4;
81
+ const BACKFILL_GAPS_MAX = GLOBAL_GAPS_MAX / 2;
82
+ const ALL_SEGMENTS = new Set([true, false].flatMap((userActor) => [
83
+ 0,
84
+ 1,
85
+ 2,
86
+ 3
87
+ ].map((endedTurns) => gapSegment(userActor, endedTurns))));
88
+ async function loadConversations(windowStartMs) {
89
+ return await getSqlExecutor().query(`SELECT conversation_id AS "conversationId", kind,
90
+ parent_conversation_id AS "parentConversationId"
91
+ FROM junior_conversations
92
+ WHERE last_activity_at >= $1 AND transcript_purged_at IS NULL
93
+ ORDER BY last_activity_at DESC, conversation_id`, [new Date(windowStartMs).toISOString()]);
94
+ }
95
+ async function loadEvents(conversationIds) {
96
+ return await getSqlExecutor().query(`SELECT e.conversation_id AS "conversationId", e.type,
97
+ CASE WHEN e.type = 'user_message' THEN
98
+ (e.payload->'provenance'->'actor'->>'userId') IS NOT NULL
99
+ END AS "personInstruction",
100
+ m.message->>'stopReason' AS "stopReason",
101
+ m.message->>'timestamp' AS "startedAtMs",
102
+ e.payload->'usage'->>'cacheRead' AS "cacheRead",
103
+ e.payload->'usage'->>'cacheWrite' AS "cacheWrite"
104
+ FROM junior_conversation_events e
105
+ JOIN junior_conversations c ON c.conversation_id = e.conversation_id
106
+ CROSS JOIN LATERAL (
107
+ SELECT CASE
108
+ WHEN e.type <> 'assistant_message' THEN NULL
109
+ WHEN e.schema_version >= 2 THEN (e.payload->>'message')::jsonb
110
+ ELSE e.payload
111
+ END AS message
112
+ ) m
113
+ WHERE e.conversation_id = ANY($1::text[])
114
+ AND (
115
+ e.type = 'assistant_message'
116
+ OR (
117
+ e.type = 'user_message'
118
+ AND (e.payload->'provenance'->>'authority') = 'instruction'
119
+ )
120
+ )
121
+ AND e.created_at >= c.created_at
122
+ ORDER BY e.conversation_id, e.seq`, [conversationIds]);
123
+ }
124
+ /**
125
+ * Replay the model calls of one Conversation the way the recorder in
126
+ * `warmup.ts` sees them, and return the gap of each idle period.
127
+ *
128
+ * Live recording measures from the start of the request that ended a Turn to
129
+ * the start of the next recorded request. Here both times are the
130
+ * `timestamp` of the stored assistant message, which Pi sets when it starts
131
+ * the request. That is the closest stored time to the recorder's clock.
132
+ *
133
+ * Live recording records gaps only for idle periods that it could warm. The
134
+ * stored usage gives the prefix size, so periods with a prefix below
135
+ * `MIN_WARMUP_PREFIX_TOKENS` are skipped. The model, cache retention, and
136
+ * snapshot size of the request are not checked: this assumes that reply
137
+ * timing does not depend on them.
138
+ */
139
+ function replayConversation(kind, events, nowMs) {
140
+ const gaps = [];
141
+ const close = (idle, untilMs) => {
142
+ const gapMs = untilMs - idle.sinceMs;
143
+ if (!idle.eligible || gapMs <= 0) return;
144
+ gaps.push({
145
+ segment: idle.segment,
146
+ sinceMs: idle.sinceMs,
147
+ gapMs: gapMs >= 33e5 ? NO_REPLY_GAP_MS : gapMs
148
+ });
149
+ };
150
+ let userActor = false;
151
+ let inTurn = false;
152
+ let endedTurns = 0;
153
+ let lastCallMs;
154
+ let idle;
155
+ for (const event of events) {
156
+ if (event.type === "user_message") {
157
+ if (!inTurn) {
158
+ userActor = event.personInstruction === true && kind !== "task";
159
+ inTurn = true;
160
+ }
161
+ continue;
162
+ }
163
+ if (event.stopReason !== "toolUse") inTurn = false;
164
+ const startedAtMs = event.startedAtMs === null ? NaN : Number(event.startedAtMs);
165
+ if (!Number.isFinite(startedAtMs) || event.stopReason === "error" || event.stopReason === "aborted") continue;
166
+ if (idle) close(idle, startedAtMs);
167
+ idle = void 0;
168
+ if (lastCallMs !== void 0 && startedAtMs - lastCallMs > CONVERSATION_STATE_TTL_MS) endedTurns = 0;
169
+ lastCallMs = startedAtMs;
170
+ if (event.stopReason === "stop") {
171
+ const prefixTokens = Number(event.cacheRead ?? 0) + Number(event.cacheWrite ?? 0);
172
+ idle = {
173
+ sinceMs: startedAtMs,
174
+ segment: gapSegment(userActor, endedTurns),
175
+ eligible: prefixTokens >= MIN_WARMUP_PREFIX_TOKENS
176
+ };
177
+ endedTurns += 1;
178
+ }
179
+ }
180
+ if (idle && nowMs - idle.sinceMs >= 33e5) close(idle, nowMs);
181
+ return gaps;
182
+ }
183
+ function isQueryCanceled(error) {
184
+ let current = error;
185
+ for (let depth = 0; current && depth < 6; depth += 1) {
186
+ if (typeof current !== "object") return false;
187
+ if (current.code === QUERY_CANCELED) return true;
188
+ current = current.cause;
189
+ }
190
+ return false;
191
+ }
192
+ async function collectGaps(nowMs, budgetMs) {
193
+ const startedAt = performance.now();
194
+ const windowStartMs = nowMs - GLOBAL_GAPS_TTL_MS;
195
+ const conversations = await loadConversations(windowStartMs);
196
+ const recorded = [];
197
+ let scanned = 0;
198
+ let canceledBatches = 0;
199
+ let budgetExceeded = false;
200
+ for (let i = 0; i < conversations.length; i += CONVERSATION_BATCH_SIZE) {
201
+ if (i > 0 && performance.now() - startedAt >= budgetMs) {
202
+ budgetExceeded = true;
203
+ break;
204
+ }
205
+ const batch = conversations.slice(i, i + CONVERSATION_BATCH_SIZE);
206
+ let rows;
207
+ try {
208
+ rows = await loadEvents(batch.map((row) => row.conversationId));
209
+ } catch (error) {
210
+ if (!isQueryCanceled(error)) throw error;
211
+ canceledBatches += 1;
212
+ continue;
213
+ }
214
+ const events = /* @__PURE__ */ new Map();
215
+ for (const event of rows) {
216
+ const list = events.get(event.conversationId) ?? [];
217
+ list.push(event);
218
+ events.set(event.conversationId, list);
219
+ }
220
+ for (const conversation of batch) {
221
+ const gaps = replayConversation(conversationKindFromRow(conversation), events.get(conversation.conversationId) ?? [], nowMs);
222
+ recorded.push(...gaps.filter((gap) => gap.sinceMs >= windowStartMs));
223
+ }
224
+ scanned += batch.length;
225
+ }
226
+ recorded.sort((a, b) => a.sinceMs - b.sinceMs);
227
+ const bySegment = /* @__PURE__ */ new Map();
228
+ for (const gap of recorded) {
229
+ const list = bySegment.get(gap.segment) ?? [];
230
+ list.push(gap.gapMs);
231
+ bySegment.set(gap.segment, list);
232
+ }
233
+ return {
234
+ bySegment,
235
+ scanned,
236
+ canceledBatches,
237
+ budgetExceeded
238
+ };
239
+ }
240
+ /**
241
+ * Fill each empty cache warming gap list once per install from the stored
242
+ * Conversation history. The heartbeat calls it each minute. After one run
243
+ * completes, a call makes one state request and returns.
244
+ *
245
+ * A run that uses its scan budget writes the gaps that it has and also
246
+ * completes. Some gaps are better than none, and a run that cannot finish
247
+ * would otherwise try again each hour.
248
+ */
249
+ async function backfillCacheWarmingGaps(args) {
250
+ if (!getChatConfig().cacheWarmingEnabled) return;
251
+ const state = getStateAdapter();
252
+ await state.connect();
253
+ if (!await state.setIfNotExists(BACKFILL_KEY, "running", BACKFILL_CLAIM_TTL_MS)) return;
254
+ const emptySegments = /* @__PURE__ */ new Set();
255
+ for (const segment of ALL_SEGMENTS) if ((await state.getList(segmentGapsKey(segment))).length === 0) emptySegments.add(segment);
256
+ const { bySegment, scanned, canceledBatches, budgetExceeded } = await collectGaps(args.nowMs, args.budgetMs ?? BACKFILL_BUDGET_MS);
257
+ const logAttributes = {
258
+ "app.cache_warming.backfill.conversation_count": scanned,
259
+ "app.cache_warming.backfill.canceled_batch_count": canceledBatches,
260
+ "app.cache_warming.backfill.budget_exceeded": budgetExceeded
261
+ };
262
+ if (scanned === 0 && canceledBatches > 0) {
263
+ logInfo("cache_warming.backfill.not_completed", logAttributes);
264
+ return;
265
+ }
266
+ let gapCount = 0;
267
+ let segmentCount = 0;
268
+ for (const [segment, gaps] of bySegment) {
269
+ if (!emptySegments.has(segment)) continue;
270
+ const key = segmentGapsKey(segment);
271
+ const newest = gaps.slice(-BACKFILL_GAPS_MAX);
272
+ for (const gapMs of newest) await state.appendToList(key, gapMs, {
273
+ maxLength: GLOBAL_GAPS_MAX,
274
+ ttlMs: GLOBAL_GAPS_TTL_MS
275
+ });
276
+ gapCount += newest.length;
277
+ segmentCount += 1;
278
+ }
279
+ await state.set(BACKFILL_KEY, "done");
280
+ logInfo("cache_warming.backfill.completed", {
281
+ ...logAttributes,
282
+ "app.cache_warming.backfill.gap_count": gapCount,
283
+ "app.cache_warming.backfill.segment_count": segmentCount
284
+ });
285
+ }
56
286
  // src/chat/events/timers.ts
57
287
  /** Publish a bounded batch of due timers; the mailbox owns agent execution. */
58
288
  async function runTimerWatchHeartbeat(args) {
@@ -105,22 +335,15 @@ async function recoverConversationWork(args) {
105
335
  });
106
336
  } catch (error) {
107
337
  logException(error, "conversation.work.recovery.failed");
108
- if (isInvalidConversationRecordError(error)) await removeActiveConversation({
338
+ if (isInvalidConversationRecordError(error)) await pruneActiveConversation({
109
339
  conversationId,
110
340
  state: args.state
111
341
  });
112
342
  return;
113
343
  }
114
344
  try {
115
- if (!work) {
116
- await removeActiveConversation({
117
- conversationId,
118
- state: args.state
119
- });
120
- return;
121
- }
122
- if (work.execution.status === "idle") {
123
- await removeActiveConversation({
345
+ if (!work || !hasRunnableConversationWork(work)) {
346
+ await pruneActiveConversation({
124
347
  conversationId,
125
348
  state: args.state
126
349
  });
@@ -155,7 +378,7 @@ async function recoverConversationWork(args) {
155
378
  }
156
379
  return;
157
380
  }
158
- if (work.execution.lease || !hasRunnableConversationWork$1(work)) return;
381
+ if (work.execution.lease) return;
159
382
  if ((await ensureConversationWake({
160
383
  conversationId,
161
384
  idempotencyKey: heartbeatIdempotencyKey("pending", conversationId, args.nowMs),
@@ -1141,6 +1364,11 @@ async function runHeartbeat(args) {
1141
1364
  conversationWorkQueue: queue,
1142
1365
  nowMs: args.nowMs
1143
1366
  });
1367
+ try {
1368
+ await backfillCacheWarmingGaps({ nowMs: args.nowMs });
1369
+ } catch (error) {
1370
+ logException(error, "cache_warming.backfill.failed");
1371
+ }
1144
1372
  }
1145
1373
  // src/handlers/scheduler-auth.ts
1146
1374
  function getSchedulerSecret() {
@@ -1736,6 +1964,211 @@ async function isSlackWorkspaceMember(raw, state) {
1736
1964
  };
1737
1965
  });
1738
1966
  }
1967
+ // src/chat/ingress/slack-acting-user.ts
1968
+ /**
1969
+ * Resolve the Junior User of the person who clicked a Slack control. The
1970
+ * click acts as that person, so it needs the same workspace and allowed
1971
+ * domain checks as a Slack mention. A person Junior does not know yet gets
1972
+ * a note to sign in.
1973
+ */
1974
+ async function resolveSlackActingUser(args) {
1975
+ const { payload } = args;
1976
+ const slackUserId = parseActorUserId(payload.user?.id);
1977
+ const teamId = parseSlackTeamId(payload.team?.id ?? payload.user?.team_id);
1978
+ if (!slackUserId || !teamId) throw new Error("Slack interaction payload is missing a user or team");
1979
+ if (!await isSlackWorkspaceMember({
1980
+ user: slackUserId,
1981
+ user_team: payload.user?.team_id
1982
+ }, args.state) || !await args.isAuthorAllowed(slackUserId)) return;
1983
+ const user = (await readActorIdentity(createSlackActor(teamId, slackUserId, void 0)))?.user;
1984
+ if (!user) {
1985
+ await args.tell(slackUserId, "Junior does not know your account yet. Sign in to the Junior dashboard, then try again.");
1986
+ return;
1987
+ }
1988
+ return {
1989
+ slackUserId,
1990
+ teamId,
1991
+ user
1992
+ };
1993
+ }
1994
+ // src/chat/ingress/slack-conversation-unfurl.ts
1995
+ /** Action id of the "Continue here" button on a dashboard link preview. */
1996
+ const SLACK_CONTINUE_HERE_ACTION_ID = "junior_continue_here";
1997
+ const MAX_LINKS = 5;
1998
+ const MAX_SUMMARY_CHARS = 300;
1999
+ const linkSharedEventSchema = z.object({
2000
+ channel: z.string(),
2001
+ links: z.array(z.object({ url: z.string() })),
2002
+ message_ts: z.string(),
2003
+ source: z.string().optional(),
2004
+ thread_ts: slackMessageTsSchema.optional(),
2005
+ unfurl_id: z.string().min(1).optional()
2006
+ });
2007
+ const continueHereValueSchema = z.object({
2008
+ conversationId: z.string().min(1),
2009
+ messageTs: slackMessageTsSchema,
2010
+ threadTs: slackMessageTsSchema,
2011
+ url: z.string().min(1)
2012
+ });
2013
+ function parseContinueHereValue(raw) {
2014
+ try {
2015
+ return continueHereValueSchema.parse(JSON.parse(raw ?? ""));
2016
+ } catch {
2017
+ return;
2018
+ }
2019
+ }
2020
+ async function previewBlocks(args) {
2021
+ const title = args.conversation.title ?? "Junior conversation";
2022
+ const summary = (await readLatestConversationBrief(getDb(), args.conversation.conversationId))?.content.summary.trim();
2023
+ const shortSummary = summary && summary.length > MAX_SUMMARY_CHARS ? `${summary.slice(0, 299)}…` : summary;
2024
+ return [{
2025
+ type: "section",
2026
+ text: {
2027
+ type: "mrkdwn",
2028
+ text: [`*${formatSlackLink(args.url, title)}*`, ...shortSummary ? [escapeSlackMrkdwnText(shortSummary)] : []].join("\n")
2029
+ }
2030
+ }, ...args.footer ? [args.footer] : []];
2031
+ }
2032
+ function continueHereButton(value) {
2033
+ return {
2034
+ type: "actions",
2035
+ elements: [{
2036
+ type: "button",
2037
+ action_id: SLACK_CONTINUE_HERE_ACTION_ID,
2038
+ text: {
2039
+ type: "plain_text",
2040
+ text: "Continue here"
2041
+ },
2042
+ value: JSON.stringify(value)
2043
+ }]
2044
+ };
2045
+ }
2046
+ async function readPublicConversation(conversationId) {
2047
+ const conversation = await getConversationStore().get({ conversationId });
2048
+ if (!conversation || conversation.parentConversationId) return void 0;
2049
+ return (await readConversationAccessFromSql(getDb(), [conversationId])).get(conversationId)?.visibility === "public" ? conversation : void 0;
2050
+ }
2051
+ /** Whether a thread in this channel can take a moved Conversation. */
2052
+ async function canReceiveConversation(teamId, channelId, threadTs) {
2053
+ return !await getConversationIdByProviderConversation(getSqlExecutor(), {
2054
+ provider: "slack",
2055
+ providerDestinationId: channelId,
2056
+ providerTenantId: teamId,
2057
+ providerConversationId: threadTs
2058
+ }) && await isPublicChannel(teamId, channelId);
2059
+ }
2060
+ async function isPublicChannel(teamId, channelId) {
2061
+ const access = await checkSlackChannelReadAccess({
2062
+ currentChannelIds: [],
2063
+ targetChannelId: channelId,
2064
+ teamId
2065
+ });
2066
+ return access.allowed && access.isPublic === true;
2067
+ }
2068
+ /**
2069
+ * Preview dashboard conversation links that a workspace member posted.
2070
+ *
2071
+ * Only public root Conversations get a preview, and only in channels that are
2072
+ * not shared with other organizations. A public dashboard Conversation that
2073
+ * can still move gets a "Continue here" button when the channel is public.
2074
+ */
2075
+ async function unfurlDashboardConversationLinks(args) {
2076
+ const parsed = linkSharedEventSchema.safeParse(args.event);
2077
+ const teamId = parseSlackTeamId(args.teamId);
2078
+ if (!parsed.success || !teamId || parsed.data.source === "composer" || args.isExtSharedChannel || !await isSlackWorkspaceMember(args.event, args.state)) return;
2079
+ const event = parsed.data;
2080
+ const channelId = parseSlackChannelId(event.channel);
2081
+ const messageTs = slackMessageTsSchema.safeParse(event.message_ts);
2082
+ if (!channelId || !messageTs.success) return;
2083
+ const threadTs = event.thread_ts ?? messageTs.data;
2084
+ const unfurls = {};
2085
+ let canReceive;
2086
+ const urls = [...new Set(event.links.map((link) => link.url))];
2087
+ for (const url of urls.slice(0, MAX_LINKS)) {
2088
+ const conversationId = parseDashboardConversationLink(url);
2089
+ const conversation = conversationId ? await readPublicConversation(conversationId) : void 0;
2090
+ if (!conversation) continue;
2091
+ unfurls[url] = { blocks: await previewBlocks({
2092
+ conversation,
2093
+ url,
2094
+ ...isMovableToSlack(conversation) && await (canReceive ??= canReceiveConversation(teamId, channelId, threadTs)) ? { footer: continueHereButton({
2095
+ conversationId: conversation.conversationId,
2096
+ messageTs: messageTs.data,
2097
+ threadTs,
2098
+ url
2099
+ }) } : void 0
2100
+ }) };
2101
+ }
2102
+ if (Object.keys(unfurls).length === 0) return;
2103
+ await unfurlSlackLinks({
2104
+ channelId,
2105
+ messageTs: messageTs.data,
2106
+ ...event.unfurl_id ? { unfurlId: event.unfurl_id } : void 0,
2107
+ unfurls
2108
+ });
2109
+ }
2110
+ /**
2111
+ * Move a dashboard Conversation into the thread of the message that shared
2112
+ * its link, as the participant who clicked "Continue here".
2113
+ */
2114
+ async function handleSlackContinueHereClick(args) {
2115
+ const target = parseContinueHereValue(args.value);
2116
+ const channelId = parseSlackChannelId(args.payload.channel?.id);
2117
+ if (!target || !channelId) throw new Error("Slack Continue here payload is incomplete");
2118
+ const tellPerson = (userId, text) => postSlackEphemeralMessage({
2119
+ channelId,
2120
+ text,
2121
+ ...target.threadTs !== target.messageTs ? { threadTs: target.threadTs } : void 0,
2122
+ userId
2123
+ });
2124
+ const actor = await resolveSlackActingUser({
2125
+ isAuthorAllowed: args.isAuthorAllowed,
2126
+ payload: args.payload,
2127
+ state: args.state,
2128
+ tell: tellPerson
2129
+ });
2130
+ if (!actor) return;
2131
+ const { teamId, user } = actor;
2132
+ const tell = (text) => tellPerson(actor.slackUserId, text);
2133
+ const conversation = await getConversationStore().get({ conversationId: target.conversationId });
2134
+ const access = conversation ? (await readConversationAccessFromSql(getDb(), [target.conversationId], user)).get(target.conversationId) : void 0;
2135
+ if (!conversation || !access?.isParticipant) {
2136
+ await tell("Only people in this conversation can move it here.");
2137
+ return;
2138
+ }
2139
+ if (!canContinueInSlack(conversation, access)) {
2140
+ await tell(conversation.location ? await alreadyContinuesInSlackMessage(conversation) : "This conversation can no longer move to Slack.");
2141
+ return;
2142
+ }
2143
+ const result = await continueConversationInSlack({
2144
+ actorName: user.displayName ?? user.email,
2145
+ channel: {
2146
+ channelId,
2147
+ teamId
2148
+ },
2149
+ conversation,
2150
+ threadTs: target.threadTs
2151
+ });
2152
+ if (result.status === "refused") {
2153
+ await tell(result.message);
2154
+ return;
2155
+ }
2156
+ await unfurlSlackLinks({
2157
+ channelId,
2158
+ messageTs: target.messageTs,
2159
+ unfurls: { [target.url]: { blocks: await previewBlocks({
2160
+ conversation,
2161
+ footer: {
2162
+ type: "context",
2163
+ elements: [{
2164
+ type: "mrkdwn",
2165
+ text: result.locationUrl ? `Continues in ${formatSlackLink(result.locationUrl, "this thread")}.` : "Continues in this thread."
2166
+ }]
2167
+ },
2168
+ url: target.url
2169
+ }) } }
2170
+ });
2171
+ }
1739
2172
  // src/chat/ingress/slack-interaction-input.ts
1740
2173
  /**
1741
2174
  * Build the Slack input that a click or form makes in a thread, as a
@@ -1782,28 +2215,13 @@ async function tellPerson(target, userId, text) {
1782
2215
  userId
1783
2216
  });
1784
2217
  }
1785
- /**
1786
- * Resolve the Junior User of the person who acted. An action starts a Turn
1787
- * as that person, so it needs the same workspace and allowed domain checks
1788
- * as a Slack mention.
1789
- */
1790
- async function resolveActingUser(services, payload, target) {
1791
- const slackUserId = parseActorUserId(payload.user?.id);
1792
- const teamId = payload.team?.id ?? payload.user?.team_id;
1793
- if (!slackUserId || !teamId) throw new Error("Slack review item payload is missing a user or team");
1794
- if (!await isSlackWorkspaceMember({
1795
- user: slackUserId,
1796
- user_team: payload.user?.team_id
1797
- }, services.state) || !await services.isAuthorAllowed(slackUserId)) return;
1798
- const user = (await readActorIdentity(createSlackActor(teamId, slackUserId, void 0)))?.user;
1799
- if (!user) {
1800
- await tellPerson(target, slackUserId, "Junior does not know your account yet. Sign in to the Junior dashboard, then try again.");
1801
- return;
1802
- }
1803
- return {
1804
- slackUserId,
1805
- user
1806
- };
2218
+ function resolveActingUser(services, payload, target) {
2219
+ return resolveSlackActingUser({
2220
+ isAuthorAllowed: services.isAuthorAllowed,
2221
+ payload,
2222
+ state: services.state,
2223
+ tell: (userId, text) => tellPerson(target, userId, text)
2224
+ });
1807
2225
  }
1808
2226
  /** Show the current state of an item, such as after a click on a stale card. */
1809
2227
  async function refreshCards(services, user, itemId) {
@@ -2008,8 +2426,8 @@ async function handleAppHomeDisconnect(args) {
2008
2426
  });
2009
2427
  }
2010
2428
  /**
2011
- * Handle Slack interactions from App Home and Review item cards: block
2012
- * actions and submitted forms.
2429
+ * Handle Slack interactions from App Home, Review item cards, and dashboard
2430
+ * link previews: block actions and submitted forms.
2013
2431
  */
2014
2432
  async function handleSlackInteractivePayload(args) {
2015
2433
  const spanAttributes = { userId: args.payload.user?.id?.trim() || void 0 };
@@ -2033,6 +2451,16 @@ async function handleSlackInteractivePayload(args) {
2033
2451
  return;
2034
2452
  }
2035
2453
  }
2454
+ const continueHere = args.payload.actions?.find((candidate) => candidate.action_id === SLACK_CONTINUE_HERE_ACTION_ID);
2455
+ if (continueHere) {
2456
+ await withSpan("chat.slack_continue_here_click", "chat.slack_continue_here_click", spanAttributes, () => handleSlackContinueHereClick({
2457
+ isAuthorAllowed: args.isAuthorAllowed,
2458
+ payload: args.payload,
2459
+ state: args.state,
2460
+ value: continueHere.value
2461
+ }));
2462
+ return;
2463
+ }
2036
2464
  const disconnect = args.payload.actions?.find((candidate) => candidate.action_id === "app_home_disconnect");
2037
2465
  const provider = disconnect?.selected_option?.value ?? disconnect?.value;
2038
2466
  if (!provider) return;
@@ -2345,7 +2773,8 @@ async function ingestEventAutomations(input, options) {
2345
2773
  const db = getDb();
2346
2774
  const nowMs = options.nowMs ?? Date.now();
2347
2775
  const catalog = getEventCatalog();
2348
- const tasks = (await findMatchingEventAutomations(db, event, options.teamId, catalog)).filter((task) => slackChannelMessageRunsAutomation(event, task));
2776
+ const [matches = []] = await findMatchingEventAutomations(db, [event], options.teamId, catalog);
2777
+ const tasks = matches.filter((task) => slackChannelMessageRunsAutomation(event, task));
2349
2778
  let dispatched = 0;
2350
2779
  const errors = [];
2351
2780
  for (const task of tasks) try {
@@ -2905,6 +3334,15 @@ async function handleSlackEvent(args) {
2905
3334
  else await presentSlackAutomationDetails(event, installation.teamId);
2906
3335
  return;
2907
3336
  }
3337
+ if (event.type === "link_shared") {
3338
+ await unfurlDashboardConversationLinks({
3339
+ event,
3340
+ isExtSharedChannel: args.body.is_ext_shared_channel === true,
3341
+ state,
3342
+ teamId: installation.teamId
3343
+ });
3344
+ return;
3345
+ }
2908
3346
  if (event.type === "app_home_opened" && event.user) {
2909
3347
  await publishAppHomeViewBestEffort(event.user);
2910
3348
  return;
@@ -3356,21 +3794,23 @@ function createEventTeamIdResolver() {
3356
3794
  };
3357
3795
  }
3358
3796
  // src/chat/events/app-publisher.ts
3797
+ const WATCH_MATCH_CONCURRENCY = 4;
3359
3798
  /** Build the core event publisher used by plugin routes. */
3360
3799
  function createEventAppPublisher(args) {
3361
3800
  const resolveEventAutomationTeamId = createEventTeamIdResolver();
3362
3801
  return {
3363
- async hasMatch(event) {
3802
+ async hasMatch(events) {
3364
3803
  const work = args.conversationWork();
3365
3804
  const eventAutomationTeamId = await resolveEventAutomationTeamId();
3366
- const [subscriptions, tasks] = await Promise.all([findMatchingWatches({
3805
+ const limit = pLimit(WATCH_MATCH_CONCURRENCY);
3806
+ const [subscriptions, tasks] = await Promise.all([Promise.all(events.map((event) => limit(() => findMatchingWatches({
3367
3807
  data: event.data,
3368
3808
  eventType: event.eventType,
3369
3809
  namespace: event.namespace,
3370
3810
  identifier: event.identifier,
3371
3811
  state: work.state
3372
- }), eventAutomationTeamId ? findMatchingEventAutomations(getDb(), event, eventAutomationTeamId, getEventCatalog()) : Promise.resolve([])]);
3373
- return subscriptions.length > 0 || tasks.length > 0;
3812
+ })))), eventAutomationTeamId ? findMatchingEventAutomations(getDb(), events, eventAutomationTeamId, getEventCatalog()) : Promise.resolve([])]);
3813
+ return [...subscriptions, ...tasks].some((matched) => matched.length > 0);
3374
3814
  },
3375
3815
  async neededMatchKeys(input) {
3376
3816
  const work = args.conversationWork();
@@ -6314,6 +6754,7 @@ function registerCreateConversationTool(server, { attachmentStorage, queue, user
6314
6754
  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.",
6315
6755
  inputSchema: {
6316
6756
  message: mcpMessageTextSchema,
6757
+ title: conversationTitleSchema.optional().describe("Short title for the conversation. Omit it to generate one from the message."),
6317
6758
  visibility: z.enum(["private", "public"]).default("private").describe("`private` keeps it to its participants. `public` lets people in your workspace find and read it."),
6318
6759
  idempotencyKey: mcpIdempotencyKeySchema
6319
6760
  },
@@ -6324,12 +6765,13 @@ function registerCreateConversationTool(server, { attachmentStorage, queue, user
6324
6765
  openWorldHint: true,
6325
6766
  readOnlyHint: false
6326
6767
  }
6327
- }, async ({ idempotencyKey, message, visibility }) => {
6768
+ }, async ({ idempotencyKey, message, title, visibility }) => {
6328
6769
  let accepted;
6329
6770
  try {
6330
6771
  accepted = await createConversationForViewer(user, {
6331
6772
  idempotencyKey: idempotencyKey ?? randomUUID(),
6332
6773
  message,
6774
+ ...title ? { title } : void 0,
6333
6775
  visibility
6334
6776
  }, {
6335
6777
  attachmentStorage,
@@ -6904,6 +7346,37 @@ function registerSetConversationAutoArchiveTool(server, { user }) {
6904
7346
  }
6905
7347
  });
6906
7348
  }
7349
+ // src/api/mcp/tools/set-conversation-subscription.ts
7350
+ /**
7351
+ * Register `setConversationSubscription`, which subscribes or unsubscribes
7352
+ * the user. It never changes another person's subscription.
7353
+ */
7354
+ function registerSetConversationSubscriptionTool(server, { user }) {
7355
+ server.registerTool("setConversationSubscription", {
7356
+ title: "Set conversation subscription",
7357
+ 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.",
7358
+ inputSchema: {
7359
+ conversationId: mcpConversationIdSchema,
7360
+ subscribed: z.boolean().describe("False unsubscribes you.")
7361
+ },
7362
+ outputSchema: {
7363
+ archivedAt: z.string().nullable().describe("Set when the conversation is archived for everyone."),
7364
+ subscribed: z.boolean()
7365
+ },
7366
+ annotations: {
7367
+ destructiveHint: false,
7368
+ idempotentHint: true,
7369
+ openWorldHint: false,
7370
+ readOnlyHint: false
7371
+ }
7372
+ }, async ({ conversationId, subscribed }) => {
7373
+ try {
7374
+ return mcpToolResult(await setConversationSubscription(user, conversationId, { subscribed }));
7375
+ } catch (error) {
7376
+ return apiToolError(error);
7377
+ }
7378
+ });
7379
+ }
6907
7380
  // src/api/mcp/tools/stop-conversation.ts
6908
7381
  /**
6909
7382
  * Register `stopConversation`, which stops the Conversation and every child
@@ -6958,6 +7431,7 @@ const TOOLS_BY_SCOPE = {
6958
7431
  registerArchiveDoneConversationsTool,
6959
7432
  registerPinConversationTool,
6960
7433
  registerSetConversationAutoArchiveTool,
7434
+ registerSetConversationSubscriptionTool,
6961
7435
  registerMarkConversationReadTool,
6962
7436
  registerStopConversationTool,
6963
7437
  registerCancelQueuedMessagesTool
@@ -7440,6 +7914,7 @@ function dashboardHostRoutePaths(dashboard, authenticatedRoutes = []) {
7440
7914
  const pagePaths = [
7441
7915
  basePath,
7442
7916
  pagePath("admin"),
7917
+ pagePath("board"),
7443
7918
  pagePath("code"),
7444
7919
  `${pagePath("code")}/*`,
7445
7920
  conversationsPath,
@@ -7485,6 +7960,7 @@ function dashboardHostRoutePaths(dashboard, authenticatedRoutes = []) {
7485
7960
  "/api/automations",
7486
7961
  "/api/automations/*",
7487
7962
  "/api/skills",
7963
+ "/api/board",
7488
7964
  "/api/code",
7489
7965
  "/api/code/*",
7490
7966
  "/api/connections",
@@ -7493,6 +7969,7 @@ function dashboardHostRoutePaths(dashboard, authenticatedRoutes = []) {
7493
7969
  "/api/notifications/*",
7494
7970
  "/api/stats",
7495
7971
  "/api/versions",
7972
+ "/api/transcriptions",
7496
7973
  "/api/conversations",
7497
7974
  "/api/conversations/*",
7498
7975
  "/api/locations",
@@ -7919,6 +8396,7 @@ async function createApp(options) {
7919
8396
  registerVercelConversationWorkDevConsumer(getConversationWorkOptions());
7920
8397
  registerVercelPluginTaskDevConsumer();
7921
8398
  registerVercelWorkspaceSnapshotJobDevConsumer();
8399
+ registerVercelCacheWarmupDevConsumer();
7922
8400
  registerVercelBackgroundCompactionDevConsumer();
7923
8401
  }
7924
8402
  app.post("/api/internal/agent/continue", (c) => {
@@ -7934,6 +8412,11 @@ async function createApp(options) {
7934
8412
  workspaceSnapshotJobPOST ??= createVercelWorkspaceSnapshotJobCallback();
7935
8413
  return workspaceSnapshotJobPOST(c.req.raw);
7936
8414
  });
8415
+ let cacheWarmupPOST;
8416
+ app.post(JUNIOR_CACHE_WARMUP_CALLBACK_ROUTE, (c) => {
8417
+ cacheWarmupPOST ??= createVercelCacheWarmupCallback();
8418
+ return cacheWarmupPOST(c.req.raw);
8419
+ });
7937
8420
  let backgroundCompactionPOST;
7938
8421
  app.post(JUNIOR_CONTEXT_COMPACTION_CALLBACK_ROUTE, (c) => {
7939
8422
  backgroundCompactionPOST ??= createVercelBackgroundCompactionCallback();
@@ -7958,6 +8441,7 @@ async function createApp(options) {
7958
8441
  conversationWorkQueueConsumer(getConversationWorkOptions()),
7959
8442
  pluginTaskQueueConsumer(),
7960
8443
  workspaceSnapshotJobQueueConsumer(),
8444
+ cacheWarmupQueueConsumer(),
7961
8445
  backgroundCompactionQueueConsumer()
7962
8446
  ], backgroundWork) });
7963
8447
  }