@sentry/junior 0.287.0 → 0.289.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 (79) hide show
  1. package/dist/{adapter-CL-HUKgd.js → adapter-tE1wnl0T.js} +1 -1
  2. package/dist/{admin-C9urXVfi.js → admin-BmsPbmO_.js} +2 -2
  3. package/dist/{agent-runner-Bfnw551N.js → agent-runner-bvl8U5uH.js} +489 -165
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +7 -7
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +628 -238
  8. package/dist/{app-DBY5TnfY.d.ts → app-Cu454FXq.d.ts} +2 -2
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +550 -71
  11. package/dist/assistant-reply-1N9oxyyb.js +58 -0
  12. package/dist/{automation-DksGNDRO.js → automation-DWbjJltM.js} +2 -2
  13. package/dist/{background-compaction-queue-CYI909P5.js → background-compaction-queue-D36oCldp.js} +161 -90
  14. package/dist/{briefs-DaXiMWzT.js → briefs-CV-1qkXa.js} +3 -3
  15. package/dist/{catalog-runtime-BCIuBe4d.js → catalog-runtime-BNK4uJVZ.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-CkHcUMN7.js → config-DHAy7XlP.js} +363 -8
  24. package/dist/{connections-BnIj0wtx.js → connections-C3VmH3cf.js} +7 -129
  25. package/dist/{conversation-E7ZPJx2H.js → conversation-CwC8K3RZ.js} +22 -5
  26. package/dist/{conversation-pending-messages-DVch6YQw.js → conversation-pending-messages-B0cuLReP.js} +1 -1
  27. package/dist/{conversation-privacy-DF1hW0ja.js → conversation-privacy-Bky_veSp.js} +1 -1
  28. package/dist/{credential-sync-CzMar9hq.js → credential-sync-dY9o0YSj.js} +28 -20
  29. package/dist/{db-DJ11eZqq.js → db-BS2Kql3j.js} +81 -46
  30. package/dist/{db-YDKKDxlh.d.ts → db-BebRmhsH.d.ts} +10 -2
  31. package/dist/{executor-BY9TB31g.js → executor-cc4nH86C.js} +125 -18
  32. package/dist/instrumentation.js +2 -2
  33. package/dist/{logging-BO5zU6Mt.js → logging-CtCJmt9p.js} +3 -2
  34. package/dist/{media-Cz1ZiV1U.js → media-BepyEUNm.js} +5 -1
  35. package/dist/{message-CsUbuEc8.js → message-C5VuRcP9.js} +9 -9
  36. package/dist/nitro.d.ts +1 -1
  37. package/dist/nitro.js +19 -41
  38. package/dist/{oauth-callback-server-hiDKK0_n.js → oauth-callback-server-KRrYUZ35.js} +2 -2
  39. package/dist/{projection-CL_YWeGf.js → projection-BFJG58TG.js} +448 -721
  40. package/dist/{prompt-BHOEQSmf.js → prompt-D15oftoL.js} +5 -5
  41. package/dist/{registry-BriFLnaJ.js → registry-C_JrgqUz.js} +1 -1
  42. package/dist/{resolve-Bt6GgAiA.js → resolve-Cn_7JfP-.js} +3 -3
  43. package/dist/{result-Bo1TZu0Q.js → result-CIbQFLp6.js} +16 -10
  44. package/dist/{runner-D3YeCQgt.js → runner-BwmaMJVO.js} +8 -8
  45. package/dist/{sandbox-egress-signals-CcnSPP4S.js → sandbox-egress-signals-BOQ8gn7i.js} +1 -1
  46. package/dist/{schedule-BTp__wrw.js → schedule-cP0AACm1.js} +11 -2
  47. package/dist/{schema-BWE3RJEB.js → schema-Bptz19Ja.js} +72 -14
  48. package/dist/{schema-C6fsEwjo.d.ts → schema-DQaFSkZZ.d.ts} +122 -3
  49. package/dist/{service-account-DiQQuuw7.js → service-account-AGw_pANb.js} +3 -3
  50. package/dist/{service-account-r6fl0b-9.js → service-account-CLZfF8O1.js} +3 -3
  51. package/dist/{session-stop-B2Nut40V.js → session-stop-CbzKf7UI.js} +84 -31
  52. package/dist/{skills-CD5aJdzg.js → skills-CcAJBquq.js} +2 -2
  53. package/dist/{spawn-CalgZQiu.js → spawn-BvAk2vTI.js} +5 -5
  54. package/dist/{stop-kujZLbi0.js → stop-BQU4u7la.js} +893 -519
  55. package/dist/{store-DdIEUL1q.js → store-DE7NJOvQ.js} +4 -16
  56. package/dist/{task-runner-D_RDr2Hu.js → task-runner-Q_7duP_T.js} +31 -27
  57. package/dist/{turn-failure-response-B5nV1Er-.js → turn-failure-response-aWZLfUM8.js} +18 -9
  58. package/dist/{validation-K4pqwoVZ.js → validation-BOoPeIJR.js} +1 -1
  59. package/dist/{version-DBvhk1X9.js → version-Db0MFy61.js} +1 -1
  60. package/dist/version.js +1 -1
  61. package/dist/{viewer-DrMmFUul.js → viewer-FFEFu9In.js} +4 -4
  62. package/dist/warmup-DDzrA9Gv.js +967 -0
  63. package/dist/{work-ljRoODGu.js → work-BBJK458E.js} +16 -15
  64. package/dist/{worker-CYO1Q0Js.js → worker-2iU5RFyq.js} +7 -31
  65. package/migrations/0089_conversation_paused_status.sql +3 -0
  66. package/migrations/0090_guardian_review_time_index.sql +20 -0
  67. package/migrations/0091_conversation_participant_unsubscribed_index.sql +20 -0
  68. package/migrations/0092_turn_metric_actor.sql +12 -0
  69. package/migrations/0093_participant_root_actor_backfill.sql +18 -0
  70. package/migrations/0094_conversation_delivery_paused_at.sql +1 -0
  71. package/migrations/meta/0089_snapshot.json +4372 -0
  72. package/migrations/meta/0090_snapshot.json +4388 -0
  73. package/migrations/meta/0091_snapshot.json +4410 -0
  74. package/migrations/meta/0092_snapshot.json +4446 -0
  75. package/migrations/meta/0093_snapshot.json +4446 -0
  76. package/migrations/meta/0094_snapshot.json +4452 -0
  77. package/migrations/meta/_journal.json +42 -0
  78. package/package.json +6 -5
  79. package/dist/assistant-reply-u_PRYzuz.js +0 -65
package/dist/app.js CHANGED
@@ -1,39 +1,40 @@
1
1
  import { i as getActiveSpan, n as captureMessage, u as sentry_exports } from "./sentry-BRTJqumy.js";
2
- import { $a as createPluginLogger, $n as validatePlugins, $r as takeDueTimerWatches, Da as consumeSandboxEgressPermissionDeniedSignal, Dn as getThreadStopDecision, Dt as isInvalidConversationRecordError, Ea as consumeSandboxEgressAuthRequiredSignal, Eo as resolveRootVisibility, Fi as proxyVercelSandboxEgressRequest, Fn as getExperimentalFeatures, Fo as createPluginCache, Gi as slackMention, Gn as getPluginApiRoutes, Ho as setConfigDefaults, In as isExperimentalFeatureEnabled, Kn as getPluginRoutes, Kr as collectEventMatchKeys, Ln as setExperimentalFeatures, Na as normalizeSandboxEgressTracePropagationDomains, Nr as reviewItemReaderForUser, Pi as isVercelSandboxEgressRequest, Qi as postSlackEphemeralMessage, Qn as setPlugins, Rn as createUserTokenStore, S as projectConversationMessages, Ta as clearSandboxEgressSignals, Tr as canActOnReviewItem, Tt as hasRunnableConversationWork, Vo as getConfigDefaults, Xr as findMatchingWatches, Zi as openSlackModal, Zn as getPlugins, _ as appendConversationMessages, _o as readConversationMessageEventSeq, ai as verifySlackDirectCredentialSubject, ci as getDashboardConversationLink, ct as CONVERSATION_WORK_STALE_ENQUEUE_MS, da as isDmChannel, ei as bindEventAutomationCredentialSubject, fi as getDashboardTaskLink, ga as runWithWorkspaceTeamId, go as readConversationLastEventSeq, ha as getWorkspaceTeamId, hi as createPluginState, ia as slackExternalRefIdSchema, ii as verifyScheduledAutomationCredentialSubject, ka as parseSandboxEgressCredentialToken, ko as listConversationAnnotations, la as getSlackClient, mo as readConversationEventPageAfter, mr as dismissOpenReviewItems, ni as bindSlackDirectCredentialSubject, no as readConversationAccessFromSql, nr as setBriefsConfig, pi as setDashboardConversationLinkOptions, po as readConversationEventPage, ra as slackEntitySchema, ri as verifyEventAutomationCredentialSubject, ti as bindScheduledAutomationCredentialSubject, ui as getDashboardReviewItemLink, w as settleConversationTitleWork, wn as SubscribedReplyReason, xr as searchReviewItems, za as createPluginEmbedder, zi as resolveBaseUrl } from "./projection-CL_YWeGf.js";
3
- import { H 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-CkHcUMN7.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-BO5zU6Mt.js";
5
- import { t as JUNIOR_VERSION } from "./version-DBvhk1X9.js";
2
+ import { $a as readConversationAccessFromSql, $i as slackEntitySchema, $r as verifySlackDirectCredentialSubject, Ai as proxyVercelSandboxEgressRequest, At as isInvalidConversationRecordError, Bi as slackMention, Bn as setPlugins, Br as collectEventMatchKeys, C as settleConversationTitleWork, Ca as consumeSandboxEgressPermissionDeniedSignal, En as createUserTokenStore, Er as reviewItemReaderForUserInConversation, Fa as createPluginEmbedder, Ii as escapeSlackMrkdwnText, Jr as bindEventAutomationCredentialSubject, Ki as openSlackModal, Li as formatSlackLink, Lo as getConfigDefaults, Nn as getPluginApiRoutes, Ot as hasRunnableConversationWork, Pi as resolveBaseUrl, Pn as getPluginRoutes, Pt as pruneActiveConversation, Qr as verifyScheduledAutomationCredentialSubject, Ro as setConfigDefaults, Sa as consumeSandboxEgressAuthRequiredSignal, So as resolveRootVisibility, Ta as parseSandboxEgressCredentialToken, To as listConversationAnnotations, Tr as reviewItemReaderForUser, Vn as validatePlugins, Wn as setBriefsConfig, Wr as findMatchingWatches, Xi as unfurlSlackLinks, Xr as bindSlackDirectCredentialSubject, Ya as createPluginLogger, Yr as bindScheduledAutomationCredentialSubject, Zr as verifyEventAutomationCredentialSubject, _ as appendConversationMessages, aa as getSlackClient, ci as setDashboardConversationLinkOptions, co as readLatestConversationBrief, da as getWorkspaceTeamId, dr as searchReviewItems, ea as slackExternalRefIdSchema, er as projectConversationMessages, fa as runWithWorkspaceTeamId, fo as readConversationLastEventSeq, hr as canActOnReviewItem, ii as getDashboardReviewItemLink, ir as dismissOpenReviewItems, jo as createPluginCache, ka as normalizeSandboxEgressTracePropagationDomains, ki as isVercelSandboxEgressRequest, lo as readConversationEventPage, ni as getDashboardConversationLink, oi as getDashboardTaskLink, po as readConversationMessageEventSeq, qi as postSlackEphemeralMessage, qr as takeDueTimerWatches, sa as isDmChannel, si as parseDashboardConversationLink, ui as createPluginState, uo as readConversationEventPageAfter, ut as CONVERSATION_WORK_STALE_ENQUEUE_MS, xa as clearSandboxEgressSignals, zn as getPlugins } from "./projection-BFJG58TG.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, q as getAttachmentStorage, u as resetRuntimeConfig } from "./config-DHAy7XlP.js";
4
+ import { A as JUNIOR_CONTEXT_COMPACTION_CALLBACK_ROUTE, E as withSpan, H as GOOGLE_IDENTITY_PROVIDER, L as JUNIOR_WORKSPACE_SNAPSHOT_JOB_CALLBACK_ROUTE, O as JUNIOR_AUTO_ARCHIVE_ROUTE, P as JUNIOR_PLUGIN_TASK_CALLBACK_ROUTE, T as withLogContext, W as normalizeIdentityEmail, 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-CtCJmt9p.js";
5
+ import { t as JUNIOR_VERSION } from "./version-Db0MFy61.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 { B as touchConversationDetail, D as resolveActorIdentityId, N as recordGoogleSignIn, a as getConversationStore, b as withConversationMutationLock, o as getDb, p as withConversationEventLock, q as createSlackDestination, r as getConversationEventStore, s as getSqlExecutor, t as closeDb } from "./db-DJ11eZqq.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-BY9TB31g.js";
9
- import { n as pluginCatalogRuntime } from "./catalog-runtime-BCIuBe4d.js";
10
- import { $ as readViewerAutomationSummary, A as runWithSlackInstallation, C as readSlackReviewItemCardConversationId, Ct as markConversationRead, D as parseSlackReviewItemClick, E as buildSlackReviewItemModal, H as logScheduledAutomationRunSkipped, M as parseSlackThreadId, O as parseSlackReviewItemFormTarget, S as createSlackReviewItemShow, U as scheduledAutomationRunAttributes, Xt as ingestEvent, Y as ViewerTaskNotFoundError, Yt as processWorkspaceSnapshotJob, Z as readViewerAutomationExecutions, _ 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-Bfnw551N.js";
7
+ import { D as resolveActorIdentityId, N as recordGoogleSignIn, R as getConversationIdByProviderConversation, X as createSlackDestination, Y as touchConversationDetail, 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-BS2Kql3j.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-cc4nH86C.js";
9
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-BNK4uJVZ.js";
10
+ import { $ as readViewerAutomationSummary, $t as resumeConversationDelivery, A as runWithSlackInstallation, C as readSlackReviewItemCardConversationId, D as parseSlackReviewItemClick, E as buildSlackReviewItemModal, H as logScheduledAutomationRunSkipped, I as checkSlackChannelReadAccess, M as parseSlackThreadId, O as parseSlackReviewItemFormTarget, Ot as recordSubagentEnded, S as createSlackReviewItemShow, St as markConversationRead, U as scheduledAutomationRunAttributes, Y as ViewerTaskNotFoundError, Z as readViewerAutomationExecutions, _ as unpublishedArtifactHeaders, at as deliverReviewItemChange, bt as archiveConversation, cn as processWorkspaceSnapshotJob, g as readPublicArtifact, gt as collectAttachmentGarbage, h as publicArtifactHeaders, j as verifySlackSignature, k as parseSlackUserInputSubmission, ln as ingestEvent, 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, y as lookupSlackUserProfile, z as joinPublicChannel } from "./agent-runner-bvl8U5uH.js";
11
11
  import { a as withLock, i as fenceLock, n as MUTATION_LOCK_TTL_MS } from "./locks-D-0h111u.js";
12
- import { g as createCache, i as readActorIdentity, l as resolveViewerUser, p as parseAvatarUrl } from "./viewer-DrMmFUul.js";
13
- import { r as getStateAdapter, t as disconnectStateAdapter } from "./adapter-CL-HUKgd.js";
14
- import { a as getNextRunAtMs } from "./schedule-BTp__wrw.js";
15
- import { G as conversationBriefSchema, j as annotationCard, p as conversationFeedQuerySchema, x as conversationSurfaceSchema, y as conversationReportStatusSchema } from "./conversation-E7ZPJx2H.js";
12
+ import { g as createCache, i as readActorIdentity, l as resolveViewerUser, p as parseAvatarUrl } from "./viewer-FFEFu9In.js";
13
+ import { r as getStateAdapter, t as disconnectStateAdapter } from "./adapter-tE1wnl0T.js";
14
+ import { a as getNextRunAtMs } from "./schedule-cP0AACm1.js";
15
+ import { F as annotationCard, Y as conversationBriefSchema, k as conversationTitleSchema, p as conversationFeedQuerySchema, x as conversationSurfaceSchema, y as conversationReportStatusSchema } from "./conversation-CwC8K3RZ.js";
16
16
  import { t as SANDBOX_EGRESS_PROXY_PATH } from "./proxy-path-BHYoKZdq.js";
17
- import { D as listPendingAgentInvocationResults, E as listPendingAgentInvocationMailboxAppends } from "./turn-failure-response-B5nV1Er-.js";
18
- 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-B2Nut40V.js";
17
+ import { a as segmentGapsKey, d as MINUTE_MS, f as MIN_WARMUP_PREFIX_TOKENS, m as gapSegment, n as GLOBAL_GAPS_MAX, p as NO_REPLY_GAP_MS, r as GLOBAL_GAPS_TTL_MS, t as CONVERSATION_STATE_TTL_MS } from "./warmup-DDzrA9Gv.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-D36oCldp.js";
19
+ import { D as listPendingAgentInvocationResults, E as listPendingAgentInvocationMailboxAppends } from "./turn-failure-response-aWZLfUM8.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-CbzKf7UI.js";
19
21
  import { _ as buttonUserInputField } from "./reporting-window-B3Ze-Qnt.js";
20
- import { c as setSandboxResourceConfig, o as getSandboxResourceConfig } from "./resolve-Bt6GgAiA.js";
21
- 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-CYI909P5.js";
22
- 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-DdIEUL1q.js";
23
- 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-D_RDr2Hu.js";
24
- import { M as scheduledRunSchema, l as automationListQuerySchema, s as automationExecutionStatusSchema } from "./automation-DksGNDRO.js";
25
- import { n as validatePluginRegistrations, t as validatePluginEgressCredentialHooks } from "./validation-K4pqwoVZ.js";
22
+ import { c as setSandboxResourceConfig, o as getSandboxResourceConfig } from "./resolve-Cn_7JfP-.js";
23
+ import { _ as listActiveConversationIds, g as getConversationWorkState, h as getConversation, l as clearExpiredConversationLease, m as ensureConversationWake, r as appendAndEnqueueInboundMessage } from "./store-DE7NJOvQ.js";
24
+ import { A as withScheduledAutomationLock, Ct as eventGuidance, E as readScheduledAutomation, F as findMatchingEventAutomations, H as eventAutomationRunLimitReason, M as collectEventAutomationMatchKeys, O as saveScheduledAutomationInLock, Q as existingConversationId, V as admitEventAutomationRun, W as automationVersionOf, 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, vt as coerceThreadConversationState, w as listScheduledAutomationsForTeam, x as notifyAutomationBlocked, y as markDispatchFailed } from "./task-runner-Q_7duP_T.js";
25
+ import { M as scheduledRunSchema, l as automationListQuerySchema, s as automationExecutionStatusSchema } from "./automation-DWbjJltM.js";
26
+ import { n as validatePluginRegistrations, t as validatePluginEgressCredentialHooks } from "./validation-BOoPeIJR.js";
26
27
  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-DVch6YQw.js";
28
- import { $ as readReviewItemForUser, 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 recordSkippedConversationMessage, K as stopConversation, L as resolveAllowedDomains, M as getProductionSlackAdapter, N as assertNoLegacyAllowedDomains, P as isAllowedDomain, Q as closeReviewItemsAnsweredByReply, R as startProcessingReaction, S as appendConversationMessageForViewer, T as encodeConversationCursor, U as normalizeIncomingSlackThreadId, V as slackInboundMessageId, W as withNormalizedThreadId, X as ReviewItemActionError, Y as bindMessageAuthorIdentityId, Z as actOnReviewItem, a as pinConversation, at as setConversationAutoArchive, b as readConversationRecordFromSql, ct as enqueueAgentDispatch, et as reviewItemChange, i as readConversationFeed, it as runAutoArchiveSweep, j as createProductionSlackWebhookServices, lt as GET$4, n as steerConversationPendingMessagesForViewer, nt as archiveViewerDoneConversations, q as parseContent, s as readConversationDetail, t as stopConversationTurnForViewer, w as decodeConversationCursor, z as buildSlackInboundMessage } from "./stop-kujZLbi0.js";
29
- import { a as enqueueAgentInvocation, i as endAgentInvocationsOfStoppedWork } from "./work-ljRoODGu.js";
30
- import { n as enqueueAgentInvocationResult } from "./result-Bo1TZu0Q.js";
31
- import { o as unlinkProvider } from "./connections-BnIj0wtx.js";
32
- import { a as GET$5, i as publishAppHomeView, r as GET$6, t as receiveLocalOAuthCredential } from "./credential-sync-CzMar9hq.js";
28
+ import { a as conversationPendingMessageDeliverySchema } from "./conversation-pending-messages-B0cuLReP.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-BQU4u7la.js";
30
+ import { a as enqueueAgentInvocation, i as endAgentInvocationsOfStoppedWork } from "./work-BBJK458E.js";
31
+ import { n as enqueueAgentInvocationResult } from "./result-CIbQFLp6.js";
32
+ import { o as unlinkProvider } from "./connections-C3VmH3cf.js";
33
+ import { a as GET$5, i as publishAppHomeView, r as GET$6, t as receiveLocalOAuthCredential } from "./credential-sync-dY9o0YSj.js";
33
34
  import { t as nameRequestRoute } from "./sentry-route-name-BhwWnfqj.js";
34
- import { t as processConversationWork } from "./worker-CYO1Q0Js.js";
35
- import { t as bindMessageAgent } from "./message-CsUbuEc8.js";
36
- import { t as bindSpawnAgent } from "./spawn-CalgZQiu.js";
35
+ import { t as processConversationWork } from "./worker-2iU5RFyq.js";
36
+ import { t as bindMessageAgent } from "./message-C5VuRcP9.js";
37
+ import { t as bindSpawnAgent } from "./spawn-BvAk2vTI.js";
37
38
  import { createRequire } from "node:module";
38
39
  import { Hono } from "hono";
39
40
  import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
@@ -41,8 +42,10 @@ import * as z from "zod";
41
42
  import { and, asc, eq, inArray, isNotNull, isNull, lte, ne, or, sql } from "drizzle-orm";
42
43
  import { EVENT_SUMMARY_MAX_LENGTH, EVENT_TEXT_MAX_LENGTH, dispatchOptionsSchema, eventSchema, eventTriggerFiltersText, isSlackDestination, userSchema } from "@sentry/junior-plugin-api";
43
44
  import { pathToFileURL } from "node:url";
45
+ import pLimit from "p-limit";
44
46
  import net from "node:net";
45
47
  import { decodeJwt } from "jose";
48
+ import { performance } from "node:perf_hooks";
46
49
  import { HTTPException } from "hono/http-exception";
47
50
  import https from "node:https";
48
51
  import { Message, ThreadImpl } from "chat";
@@ -54,6 +57,260 @@ import { bodyLimit } from "hono/body-limit";
54
57
  import { createAuthMiddleware } from "better-auth/api";
55
58
  import { getSessionCookie } from "better-auth/cookies";
56
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
+ * History does not tell the plugin work state or the archive state that a
77
+ * Conversation had when an idle period started. So it fills only the
78
+ * segments of Conversations that are not archived and have work state
79
+ * `none`, which most Conversations have. The `open` and `done` segments and
80
+ * the `archived:*` segments stay empty until live gaps arrive. With fewer
81
+ * than `MIN_GAP_SAMPLES` gaps, `decideWarmup` returns `few_gaps` and Junior
82
+ * sends no warmup. The idle period still records its gap, so the segment
83
+ * fills from live idle periods.
84
+ */
85
+ const BACKFILL_KEY = "junior:cache_warming:backfill:work_state";
86
+ const BACKFILL_CLAIM_TTL_MS = 60 * MINUTE_MS;
87
+ const CONVERSATION_BATCH_SIZE = 10;
88
+ const QUERY_CANCELED = "57014";
89
+ const BACKFILL_BUDGET_MS = 6e4;
90
+ const BACKFILL_GAPS_MAX = GLOBAL_GAPS_MAX / 2;
91
+ const BACKFILL_SEGMENTS = new Set([true, false].flatMap((userActor) => [
92
+ 0,
93
+ 1,
94
+ 2,
95
+ 3
96
+ ].map((endedTurns) => historySegment(userActor, endedTurns))));
97
+ function historySegment(userActor, endedTurns) {
98
+ return gapSegment({
99
+ userActor,
100
+ endedTurns,
101
+ workState: "none",
102
+ archived: false
103
+ });
104
+ }
105
+ async function loadConversations(windowStartMs) {
106
+ return await getSqlExecutor().query(`SELECT conversation_id AS "conversationId", kind,
107
+ parent_conversation_id AS "parentConversationId"
108
+ FROM junior_conversations
109
+ WHERE last_activity_at >= $1 AND transcript_purged_at IS NULL
110
+ ORDER BY last_activity_at DESC, conversation_id`, [new Date(windowStartMs).toISOString()]);
111
+ }
112
+ async function loadEvents(conversationIds) {
113
+ return await getSqlExecutor().query(`SELECT e.conversation_id AS "conversationId", e.type,
114
+ CASE WHEN e.type = 'user_message' THEN
115
+ (e.payload->'provenance'->'actor'->>'userId') IS NOT NULL
116
+ END AS "personInstruction",
117
+ m.message->>'stopReason' AS "stopReason",
118
+ m.message->>'timestamp' AS "startedAtMs",
119
+ e.payload->'usage'->>'cacheRead' AS "cacheRead",
120
+ e.payload->'usage'->>'cacheWrite' AS "cacheWrite"
121
+ FROM junior_conversation_events e
122
+ JOIN junior_conversations c ON c.conversation_id = e.conversation_id
123
+ CROSS JOIN LATERAL (
124
+ SELECT CASE
125
+ WHEN e.type <> 'assistant_message' THEN NULL
126
+ WHEN e.schema_version >= 2 THEN (e.payload->>'message')::jsonb
127
+ ELSE e.payload
128
+ END AS message
129
+ ) m
130
+ WHERE e.conversation_id = ANY($1::text[])
131
+ AND (
132
+ e.type = 'assistant_message'
133
+ OR (
134
+ e.type = 'user_message'
135
+ AND (e.payload->'provenance'->>'authority') = 'instruction'
136
+ )
137
+ )
138
+ AND e.created_at >= c.created_at
139
+ ORDER BY e.conversation_id, e.seq`, [conversationIds]);
140
+ }
141
+ /**
142
+ * Replay the model calls of one Conversation the way the recorder in
143
+ * `warmup.ts` sees them, and return the gap of each idle period.
144
+ *
145
+ * Live recording measures from the start of the request that ended a Turn to
146
+ * the start of the next recorded request. Here both times are the
147
+ * `timestamp` of the stored assistant message, which Pi sets when it starts
148
+ * the request. That is the closest stored time to the recorder's clock.
149
+ *
150
+ * Live recording records gaps only for idle periods that it could warm. The
151
+ * stored usage gives the prefix size, so periods with a prefix below
152
+ * `MIN_WARMUP_PREFIX_TOKENS` are skipped. The model, cache retention, and
153
+ * snapshot size of the request are not checked: this assumes that reply
154
+ * timing does not depend on them.
155
+ */
156
+ function replayConversation(kind, events, nowMs) {
157
+ const gaps = [];
158
+ const close = (idle, untilMs) => {
159
+ const gapMs = untilMs - idle.sinceMs;
160
+ if (!idle.eligible || gapMs <= 0) return;
161
+ gaps.push({
162
+ segment: idle.segment,
163
+ sinceMs: idle.sinceMs,
164
+ gapMs: gapMs >= 33e5 ? NO_REPLY_GAP_MS : gapMs
165
+ });
166
+ };
167
+ let userActor = false;
168
+ let inTurn = false;
169
+ let endedTurns = 0;
170
+ let lastCallMs;
171
+ let idle;
172
+ for (const event of events) {
173
+ if (event.type === "user_message") {
174
+ if (!inTurn) {
175
+ userActor = event.personInstruction === true && kind !== "task";
176
+ inTurn = true;
177
+ }
178
+ continue;
179
+ }
180
+ if (event.stopReason !== "toolUse") inTurn = false;
181
+ const startedAtMs = event.startedAtMs === null ? NaN : Number(event.startedAtMs);
182
+ if (!Number.isFinite(startedAtMs) || event.stopReason === "error" || event.stopReason === "aborted") continue;
183
+ if (idle) close(idle, startedAtMs);
184
+ idle = void 0;
185
+ if (lastCallMs !== void 0 && startedAtMs - lastCallMs > CONVERSATION_STATE_TTL_MS) endedTurns = 0;
186
+ lastCallMs = startedAtMs;
187
+ if (event.stopReason === "stop") {
188
+ const prefixTokens = Number(event.cacheRead ?? 0) + Number(event.cacheWrite ?? 0);
189
+ idle = {
190
+ sinceMs: startedAtMs,
191
+ segment: historySegment(userActor, endedTurns),
192
+ eligible: prefixTokens >= MIN_WARMUP_PREFIX_TOKENS
193
+ };
194
+ endedTurns += 1;
195
+ }
196
+ }
197
+ if (idle && nowMs - idle.sinceMs >= 33e5) close(idle, nowMs);
198
+ return gaps;
199
+ }
200
+ function isQueryCanceled(error) {
201
+ let current = error;
202
+ for (let depth = 0; current && depth < 6; depth += 1) {
203
+ if (typeof current !== "object") return false;
204
+ if (current.code === QUERY_CANCELED) return true;
205
+ current = current.cause;
206
+ }
207
+ return false;
208
+ }
209
+ async function collectGaps(nowMs, budgetMs) {
210
+ const startedAt = performance.now();
211
+ const windowStartMs = nowMs - GLOBAL_GAPS_TTL_MS;
212
+ const conversations = await loadConversations(windowStartMs);
213
+ const recorded = [];
214
+ let scanned = 0;
215
+ let canceledBatches = 0;
216
+ let budgetExceeded = false;
217
+ for (let i = 0; i < conversations.length; i += CONVERSATION_BATCH_SIZE) {
218
+ if (i > 0 && performance.now() - startedAt >= budgetMs) {
219
+ budgetExceeded = true;
220
+ break;
221
+ }
222
+ const batch = conversations.slice(i, i + CONVERSATION_BATCH_SIZE);
223
+ let rows;
224
+ try {
225
+ rows = await loadEvents(batch.map((row) => row.conversationId));
226
+ } catch (error) {
227
+ if (!isQueryCanceled(error)) throw error;
228
+ canceledBatches += 1;
229
+ continue;
230
+ }
231
+ const events = /* @__PURE__ */ new Map();
232
+ for (const event of rows) {
233
+ const list = events.get(event.conversationId) ?? [];
234
+ list.push(event);
235
+ events.set(event.conversationId, list);
236
+ }
237
+ for (const conversation of batch) {
238
+ const gaps = replayConversation(conversationKindFromRow(conversation), events.get(conversation.conversationId) ?? [], nowMs);
239
+ recorded.push(...gaps.filter((gap) => gap.sinceMs >= windowStartMs));
240
+ }
241
+ scanned += batch.length;
242
+ }
243
+ recorded.sort((a, b) => a.sinceMs - b.sinceMs);
244
+ const bySegment = /* @__PURE__ */ new Map();
245
+ for (const gap of recorded) {
246
+ const list = bySegment.get(gap.segment) ?? [];
247
+ list.push(gap.gapMs);
248
+ bySegment.set(gap.segment, list);
249
+ }
250
+ return {
251
+ bySegment,
252
+ scanned,
253
+ canceledBatches,
254
+ budgetExceeded
255
+ };
256
+ }
257
+ /**
258
+ * Fill each empty cache warming gap list once per install from the stored
259
+ * Conversation history. The heartbeat calls it each minute. After one run
260
+ * completes, a call makes one state request and returns.
261
+ *
262
+ * A run that uses its scan budget writes the gaps that it has and also
263
+ * completes. Some gaps are better than none, and a run that cannot finish
264
+ * would otherwise try again each hour.
265
+ */
266
+ async function backfillCacheWarmingGaps(args) {
267
+ if (!getChatConfig().cacheWarmingEnabled) return;
268
+ const state = getStateAdapter();
269
+ await state.connect();
270
+ if (!await state.setIfNotExists(BACKFILL_KEY, "running", BACKFILL_CLAIM_TTL_MS)) return;
271
+ await withSpan("cache_warming.backfill", "cache_warming.backfill", {}, async (setSpanAttributes) => {
272
+ const emptySegments = /* @__PURE__ */ new Set();
273
+ for (const segment of BACKFILL_SEGMENTS) if ((await state.getList(segmentGapsKey(segment))).length === 0) emptySegments.add(segment);
274
+ const { bySegment, scanned, canceledBatches, budgetExceeded } = await collectGaps(args.nowMs, args.budgetMs ?? BACKFILL_BUDGET_MS);
275
+ const logAttributes = {
276
+ "app.cache_warming.backfill.conversation_count": scanned,
277
+ "app.cache_warming.backfill.canceled_batch_count": canceledBatches,
278
+ "app.cache_warming.backfill.budget_exceeded": budgetExceeded
279
+ };
280
+ if (scanned === 0 && canceledBatches > 0) {
281
+ logInfo("cache_warming.backfill.not_completed", logAttributes);
282
+ setSpanAttributes({
283
+ ...logAttributes,
284
+ "app.cache_warming.backfill.outcome": "not_completed"
285
+ });
286
+ return;
287
+ }
288
+ let gapCount = 0;
289
+ let segmentCount = 0;
290
+ for (const [segment, gaps] of bySegment) {
291
+ if (!emptySegments.has(segment)) continue;
292
+ const key = segmentGapsKey(segment);
293
+ const newest = gaps.slice(-BACKFILL_GAPS_MAX);
294
+ for (const gapMs of newest) await state.appendToList(key, gapMs, {
295
+ maxLength: GLOBAL_GAPS_MAX,
296
+ ttlMs: GLOBAL_GAPS_TTL_MS
297
+ });
298
+ gapCount += newest.length;
299
+ segmentCount += 1;
300
+ }
301
+ await state.set(BACKFILL_KEY, "done");
302
+ const completed = {
303
+ ...logAttributes,
304
+ "app.cache_warming.backfill.gap_count": gapCount,
305
+ "app.cache_warming.backfill.segment_count": segmentCount
306
+ };
307
+ logInfo("cache_warming.backfill.completed", completed);
308
+ setSpanAttributes({
309
+ ...completed,
310
+ "app.cache_warming.backfill.outcome": "completed"
311
+ });
312
+ });
313
+ }
57
314
  // src/chat/events/timers.ts
58
315
  /** Publish a bounded batch of due timers; the mailbox owns agent execution. */
59
316
  async function runTimerWatchHeartbeat(args) {
@@ -106,22 +363,15 @@ async function recoverConversationWork(args) {
106
363
  });
107
364
  } catch (error) {
108
365
  logException(error, "conversation.work.recovery.failed");
109
- if (isInvalidConversationRecordError(error)) await removeActiveConversation({
366
+ if (isInvalidConversationRecordError(error)) await pruneActiveConversation({
110
367
  conversationId,
111
368
  state: args.state
112
369
  });
113
370
  return;
114
371
  }
115
372
  try {
116
- if (!work) {
117
- await removeActiveConversation({
118
- conversationId,
119
- state: args.state
120
- });
121
- return;
122
- }
123
- if (work.execution.status === "idle") {
124
- await removeActiveConversation({
373
+ if (!work || !hasRunnableConversationWork(work)) {
374
+ await pruneActiveConversation({
125
375
  conversationId,
126
376
  state: args.state
127
377
  });
@@ -156,7 +406,7 @@ async function recoverConversationWork(args) {
156
406
  }
157
407
  return;
158
408
  }
159
- if (work.execution.lease || !hasRunnableConversationWork$1(work)) return;
409
+ if (work.execution.lease) return;
160
410
  if ((await ensureConversationWake({
161
411
  conversationId,
162
412
  idempotencyKey: heartbeatIdempotencyKey("pending", conversationId, args.nowMs),
@@ -1142,6 +1392,11 @@ async function runHeartbeat(args) {
1142
1392
  conversationWorkQueue: queue,
1143
1393
  nowMs: args.nowMs
1144
1394
  });
1395
+ try {
1396
+ await backfillCacheWarmingGaps({ nowMs: args.nowMs });
1397
+ } catch (error) {
1398
+ logException(error, "cache_warming.backfill.failed");
1399
+ }
1145
1400
  }
1146
1401
  // src/handlers/scheduler-auth.ts
1147
1402
  function getSchedulerSecret() {
@@ -1737,6 +1992,211 @@ async function isSlackWorkspaceMember(raw, state) {
1737
1992
  };
1738
1993
  });
1739
1994
  }
1995
+ // src/chat/ingress/slack-acting-user.ts
1996
+ /**
1997
+ * Resolve the Junior User of the person who clicked a Slack control. The
1998
+ * click acts as that person, so it needs the same workspace and allowed
1999
+ * domain checks as a Slack mention. A person Junior does not know yet gets
2000
+ * a note to sign in.
2001
+ */
2002
+ async function resolveSlackActingUser(args) {
2003
+ const { payload } = args;
2004
+ const slackUserId = parseActorUserId(payload.user?.id);
2005
+ const teamId = parseSlackTeamId(payload.team?.id ?? payload.user?.team_id);
2006
+ if (!slackUserId || !teamId) throw new Error("Slack interaction payload is missing a user or team");
2007
+ if (!await isSlackWorkspaceMember({
2008
+ user: slackUserId,
2009
+ user_team: payload.user?.team_id
2010
+ }, args.state) || !await args.isAuthorAllowed(slackUserId)) return;
2011
+ const user = (await readActorIdentity(createSlackActor(teamId, slackUserId, void 0)))?.user;
2012
+ if (!user) {
2013
+ await args.tell(slackUserId, "Junior does not know your account yet. Sign in to the Junior dashboard, then try again.");
2014
+ return;
2015
+ }
2016
+ return {
2017
+ slackUserId,
2018
+ teamId,
2019
+ user
2020
+ };
2021
+ }
2022
+ // src/chat/ingress/slack-conversation-unfurl.ts
2023
+ /** Action id of the "Continue here" button on a dashboard link preview. */
2024
+ const SLACK_CONTINUE_HERE_ACTION_ID = "junior_continue_here";
2025
+ const MAX_LINKS = 5;
2026
+ const MAX_SUMMARY_CHARS = 300;
2027
+ const linkSharedEventSchema = z.object({
2028
+ channel: z.string(),
2029
+ links: z.array(z.object({ url: z.string() })),
2030
+ message_ts: z.string(),
2031
+ source: z.string().optional(),
2032
+ thread_ts: slackMessageTsSchema.optional(),
2033
+ unfurl_id: z.string().min(1).optional()
2034
+ });
2035
+ const continueHereValueSchema = z.object({
2036
+ conversationId: z.string().min(1),
2037
+ messageTs: slackMessageTsSchema,
2038
+ threadTs: slackMessageTsSchema,
2039
+ url: z.string().min(1)
2040
+ });
2041
+ function parseContinueHereValue(raw) {
2042
+ try {
2043
+ return continueHereValueSchema.parse(JSON.parse(raw ?? ""));
2044
+ } catch {
2045
+ return;
2046
+ }
2047
+ }
2048
+ async function previewBlocks(args) {
2049
+ const title = args.conversation.title ?? "Junior conversation";
2050
+ const summary = (await readLatestConversationBrief(getDb(), args.conversation.conversationId))?.content.summary.trim();
2051
+ const shortSummary = summary && summary.length > MAX_SUMMARY_CHARS ? `${summary.slice(0, 299)}…` : summary;
2052
+ return [{
2053
+ type: "section",
2054
+ text: {
2055
+ type: "mrkdwn",
2056
+ text: [`*${formatSlackLink(args.url, title)}*`, ...shortSummary ? [escapeSlackMrkdwnText(shortSummary)] : []].join("\n")
2057
+ }
2058
+ }, ...args.footer ? [args.footer] : []];
2059
+ }
2060
+ function continueHereButton(value) {
2061
+ return {
2062
+ type: "actions",
2063
+ elements: [{
2064
+ type: "button",
2065
+ action_id: SLACK_CONTINUE_HERE_ACTION_ID,
2066
+ text: {
2067
+ type: "plain_text",
2068
+ text: "Continue here"
2069
+ },
2070
+ value: JSON.stringify(value)
2071
+ }]
2072
+ };
2073
+ }
2074
+ async function readPublicConversation(conversationId) {
2075
+ const conversation = await getConversationStore().get({ conversationId });
2076
+ if (!conversation || conversation.parentConversationId) return void 0;
2077
+ return (await readConversationAccessFromSql(getDb(), [conversationId])).get(conversationId)?.visibility === "public" ? conversation : void 0;
2078
+ }
2079
+ /** Whether a thread in this channel can take a moved Conversation. */
2080
+ async function canReceiveConversation(teamId, channelId, threadTs) {
2081
+ return !await getConversationIdByProviderConversation(getSqlExecutor(), {
2082
+ provider: "slack",
2083
+ providerDestinationId: channelId,
2084
+ providerTenantId: teamId,
2085
+ providerConversationId: threadTs
2086
+ }) && await isPublicChannel(teamId, channelId);
2087
+ }
2088
+ async function isPublicChannel(teamId, channelId) {
2089
+ const access = await checkSlackChannelReadAccess({
2090
+ currentChannelIds: [],
2091
+ targetChannelId: channelId,
2092
+ teamId
2093
+ });
2094
+ return access.allowed && access.isPublic === true;
2095
+ }
2096
+ /**
2097
+ * Preview dashboard conversation links that a workspace member posted.
2098
+ *
2099
+ * Only public root Conversations get a preview, and only in channels that are
2100
+ * not shared with other organizations. A public dashboard Conversation that
2101
+ * can still move gets a "Continue here" button when the channel is public.
2102
+ */
2103
+ async function unfurlDashboardConversationLinks(args) {
2104
+ const parsed = linkSharedEventSchema.safeParse(args.event);
2105
+ const teamId = parseSlackTeamId(args.teamId);
2106
+ if (!parsed.success || !teamId || parsed.data.source === "composer" || args.isExtSharedChannel || !await isSlackWorkspaceMember(args.event, args.state)) return;
2107
+ const event = parsed.data;
2108
+ const channelId = parseSlackChannelId(event.channel);
2109
+ const messageTs = slackMessageTsSchema.safeParse(event.message_ts);
2110
+ if (!channelId || !messageTs.success) return;
2111
+ const threadTs = event.thread_ts ?? messageTs.data;
2112
+ const unfurls = {};
2113
+ let canReceive;
2114
+ const urls = [...new Set(event.links.map((link) => link.url))];
2115
+ for (const url of urls.slice(0, MAX_LINKS)) {
2116
+ const conversationId = parseDashboardConversationLink(url);
2117
+ const conversation = conversationId ? await readPublicConversation(conversationId) : void 0;
2118
+ if (!conversation) continue;
2119
+ unfurls[url] = { blocks: await previewBlocks({
2120
+ conversation,
2121
+ url,
2122
+ ...isMovableToSlack(conversation) && await (canReceive ??= canReceiveConversation(teamId, channelId, threadTs)) ? { footer: continueHereButton({
2123
+ conversationId: conversation.conversationId,
2124
+ messageTs: messageTs.data,
2125
+ threadTs,
2126
+ url
2127
+ }) } : void 0
2128
+ }) };
2129
+ }
2130
+ if (Object.keys(unfurls).length === 0) return;
2131
+ await unfurlSlackLinks({
2132
+ channelId,
2133
+ messageTs: messageTs.data,
2134
+ ...event.unfurl_id ? { unfurlId: event.unfurl_id } : void 0,
2135
+ unfurls
2136
+ });
2137
+ }
2138
+ /**
2139
+ * Move a dashboard Conversation into the thread of the message that shared
2140
+ * its link, as the participant who clicked "Continue here".
2141
+ */
2142
+ async function handleSlackContinueHereClick(args) {
2143
+ const target = parseContinueHereValue(args.value);
2144
+ const channelId = parseSlackChannelId(args.payload.channel?.id);
2145
+ if (!target || !channelId) throw new Error("Slack Continue here payload is incomplete");
2146
+ const tellPerson = (userId, text) => postSlackEphemeralMessage({
2147
+ channelId,
2148
+ text,
2149
+ ...target.threadTs !== target.messageTs ? { threadTs: target.threadTs } : void 0,
2150
+ userId
2151
+ });
2152
+ const actor = await resolveSlackActingUser({
2153
+ isAuthorAllowed: args.isAuthorAllowed,
2154
+ payload: args.payload,
2155
+ state: args.state,
2156
+ tell: tellPerson
2157
+ });
2158
+ if (!actor) return;
2159
+ const { teamId, user } = actor;
2160
+ const tell = (text) => tellPerson(actor.slackUserId, text);
2161
+ const conversation = await getConversationStore().get({ conversationId: target.conversationId });
2162
+ const access = conversation ? (await readConversationAccessFromSql(getDb(), [target.conversationId], user)).get(target.conversationId) : void 0;
2163
+ if (!conversation || !access?.isParticipant) {
2164
+ await tell("Only people in this conversation can move it here.");
2165
+ return;
2166
+ }
2167
+ if (!canContinueInSlack(conversation, access)) {
2168
+ await tell(conversation.location ? await alreadyContinuesInSlackMessage(conversation) : "This conversation can no longer move to Slack.");
2169
+ return;
2170
+ }
2171
+ const result = await continueConversationInSlack({
2172
+ actorName: user.displayName ?? user.email,
2173
+ channel: {
2174
+ channelId,
2175
+ teamId
2176
+ },
2177
+ conversation,
2178
+ threadTs: target.threadTs
2179
+ });
2180
+ if (result.status === "refused") {
2181
+ await tell(result.message);
2182
+ return;
2183
+ }
2184
+ await unfurlSlackLinks({
2185
+ channelId,
2186
+ messageTs: target.messageTs,
2187
+ unfurls: { [target.url]: { blocks: await previewBlocks({
2188
+ conversation,
2189
+ footer: {
2190
+ type: "context",
2191
+ elements: [{
2192
+ type: "mrkdwn",
2193
+ text: result.locationUrl ? `Continues in ${formatSlackLink(result.locationUrl, "this thread")}.` : "Continues in this thread."
2194
+ }]
2195
+ },
2196
+ url: target.url
2197
+ }) } }
2198
+ });
2199
+ }
1740
2200
  // src/chat/ingress/slack-interaction-input.ts
1741
2201
  /**
1742
2202
  * Build the Slack input that a click or form makes in a thread, as a
@@ -1783,28 +2243,13 @@ async function tellPerson(target, userId, text) {
1783
2243
  userId
1784
2244
  });
1785
2245
  }
1786
- /**
1787
- * Resolve the Junior User of the person who acted. An action starts a Turn
1788
- * as that person, so it needs the same workspace and allowed domain checks
1789
- * as a Slack mention.
1790
- */
1791
- async function resolveActingUser(services, payload, target) {
1792
- const slackUserId = parseActorUserId(payload.user?.id);
1793
- const teamId = payload.team?.id ?? payload.user?.team_id;
1794
- if (!slackUserId || !teamId) throw new Error("Slack review item payload is missing a user or team");
1795
- if (!await isSlackWorkspaceMember({
1796
- user: slackUserId,
1797
- user_team: payload.user?.team_id
1798
- }, services.state) || !await services.isAuthorAllowed(slackUserId)) return;
1799
- const user = (await readActorIdentity(createSlackActor(teamId, slackUserId, void 0)))?.user;
1800
- if (!user) {
1801
- await tellPerson(target, slackUserId, "Junior does not know your account yet. Sign in to the Junior dashboard, then try again.");
1802
- return;
1803
- }
1804
- return {
1805
- slackUserId,
1806
- user
1807
- };
2246
+ function resolveActingUser(services, payload, target) {
2247
+ return resolveSlackActingUser({
2248
+ isAuthorAllowed: services.isAuthorAllowed,
2249
+ payload,
2250
+ state: services.state,
2251
+ tell: (userId, text) => tellPerson(target, userId, text)
2252
+ });
1808
2253
  }
1809
2254
  /** Show the current state of an item, such as after a click on a stale card. */
1810
2255
  async function refreshCards(services, user, itemId) {
@@ -2009,8 +2454,8 @@ async function handleAppHomeDisconnect(args) {
2009
2454
  });
2010
2455
  }
2011
2456
  /**
2012
- * Handle Slack interactions from App Home and Review item cards: block
2013
- * actions and submitted forms.
2457
+ * Handle Slack interactions from App Home, Review item cards, and dashboard
2458
+ * link previews: block actions and submitted forms.
2014
2459
  */
2015
2460
  async function handleSlackInteractivePayload(args) {
2016
2461
  const spanAttributes = { userId: args.payload.user?.id?.trim() || void 0 };
@@ -2034,6 +2479,16 @@ async function handleSlackInteractivePayload(args) {
2034
2479
  return;
2035
2480
  }
2036
2481
  }
2482
+ const continueHere = args.payload.actions?.find((candidate) => candidate.action_id === SLACK_CONTINUE_HERE_ACTION_ID);
2483
+ if (continueHere) {
2484
+ await withSpan("chat.slack_continue_here_click", "chat.slack_continue_here_click", spanAttributes, () => handleSlackContinueHereClick({
2485
+ isAuthorAllowed: args.isAuthorAllowed,
2486
+ payload: args.payload,
2487
+ state: args.state,
2488
+ value: continueHere.value
2489
+ }));
2490
+ return;
2491
+ }
2037
2492
  const disconnect = args.payload.actions?.find((candidate) => candidate.action_id === "app_home_disconnect");
2038
2493
  const provider = disconnect?.selected_option?.value ?? disconnect?.value;
2039
2494
  if (!provider) return;
@@ -2346,7 +2801,8 @@ async function ingestEventAutomations(input, options) {
2346
2801
  const db = getDb();
2347
2802
  const nowMs = options.nowMs ?? Date.now();
2348
2803
  const catalog = getEventCatalog();
2349
- const tasks = (await findMatchingEventAutomations(db, event, options.teamId, catalog)).filter((task) => slackChannelMessageRunsAutomation(event, task));
2804
+ const [matches = []] = await findMatchingEventAutomations(db, [event], options.teamId, catalog);
2805
+ const tasks = matches.filter((task) => slackChannelMessageRunsAutomation(event, task));
2350
2806
  let dispatched = 0;
2351
2807
  const errors = [];
2352
2808
  for (const task of tasks) try {
@@ -2809,6 +3265,7 @@ async function routeParsedMessage(args) {
2809
3265
  });
2810
3266
  return;
2811
3267
  }
3268
+ if (route === "mention") await resumeConversationDelivery(conversationId);
2812
3269
  if (isSubscribed && !isExperimentalFeatureEnabled("passive-routing")) {
2813
3270
  await saveSkippedSlackMessage({
2814
3271
  conversationId,
@@ -2906,6 +3363,15 @@ async function handleSlackEvent(args) {
2906
3363
  else await presentSlackAutomationDetails(event, installation.teamId);
2907
3364
  return;
2908
3365
  }
3366
+ if (event.type === "link_shared") {
3367
+ await unfurlDashboardConversationLinks({
3368
+ event,
3369
+ isExtSharedChannel: args.body.is_ext_shared_channel === true,
3370
+ state,
3371
+ teamId: installation.teamId
3372
+ });
3373
+ return;
3374
+ }
2909
3375
  if (event.type === "app_home_opened" && event.user) {
2910
3376
  await publishAppHomeViewBestEffort(event.user);
2911
3377
  return;
@@ -3357,21 +3823,23 @@ function createEventTeamIdResolver() {
3357
3823
  };
3358
3824
  }
3359
3825
  // src/chat/events/app-publisher.ts
3826
+ const WATCH_MATCH_CONCURRENCY = 4;
3360
3827
  /** Build the core event publisher used by plugin routes. */
3361
3828
  function createEventAppPublisher(args) {
3362
3829
  const resolveEventAutomationTeamId = createEventTeamIdResolver();
3363
3830
  return {
3364
- async hasMatch(event) {
3831
+ async hasMatch(events) {
3365
3832
  const work = args.conversationWork();
3366
3833
  const eventAutomationTeamId = await resolveEventAutomationTeamId();
3367
- const [subscriptions, tasks] = await Promise.all([findMatchingWatches({
3834
+ const limit = pLimit(WATCH_MATCH_CONCURRENCY);
3835
+ const [subscriptions, tasks] = await Promise.all([Promise.all(events.map((event) => limit(() => findMatchingWatches({
3368
3836
  data: event.data,
3369
3837
  eventType: event.eventType,
3370
3838
  namespace: event.namespace,
3371
3839
  identifier: event.identifier,
3372
3840
  state: work.state
3373
- }), eventAutomationTeamId ? findMatchingEventAutomations(getDb(), event, eventAutomationTeamId, getEventCatalog()) : Promise.resolve([])]);
3374
- return subscriptions.length > 0 || tasks.length > 0;
3841
+ })))), eventAutomationTeamId ? findMatchingEventAutomations(getDb(), events, eventAutomationTeamId, getEventCatalog()) : Promise.resolve([])]);
3842
+ return [...subscriptions, ...tasks].some((matched) => matched.length > 0);
3375
3843
  },
3376
3844
  async neededMatchKeys(input) {
3377
3845
  const work = args.conversationWork();
@@ -6315,6 +6783,7 @@ function registerCreateConversationTool(server, { attachmentStorage, queue, user
6315
6783
  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.",
6316
6784
  inputSchema: {
6317
6785
  message: mcpMessageTextSchema,
6786
+ title: conversationTitleSchema.optional().describe("Short title for the conversation. Omit it to generate one from the message."),
6318
6787
  visibility: z.enum(["private", "public"]).default("private").describe("`private` keeps it to its participants. `public` lets people in your workspace find and read it."),
6319
6788
  idempotencyKey: mcpIdempotencyKeySchema
6320
6789
  },
@@ -6325,12 +6794,13 @@ function registerCreateConversationTool(server, { attachmentStorage, queue, user
6325
6794
  openWorldHint: true,
6326
6795
  readOnlyHint: false
6327
6796
  }
6328
- }, async ({ idempotencyKey, message, visibility }) => {
6797
+ }, async ({ idempotencyKey, message, title, visibility }) => {
6329
6798
  let accepted;
6330
6799
  try {
6331
6800
  accepted = await createConversationForViewer(user, {
6332
6801
  idempotencyKey: idempotencyKey ?? randomUUID(),
6333
6802
  message,
6803
+ ...title ? { title } : void 0,
6334
6804
  visibility
6335
6805
  }, {
6336
6806
  attachmentStorage,
@@ -6811,7 +7281,7 @@ function registerSearchReviewItemsTool(server, { user }) {
6811
7281
  readOnlyHint: true
6812
7282
  }
6813
7283
  }, async ({ conversationId, limit, q }) => {
6814
- const items = await searchReviewItems(getDb(), reviewItemReaderForUser(user), {
7284
+ const items = await searchReviewItems(getDb(), conversationId ? await reviewItemReaderForUserInConversation(user, conversationId) : reviewItemReaderForUser(user), {
6815
7285
  ...conversationId ? { conversationId } : void 0,
6816
7286
  limit: limit + 1,
6817
7287
  ...q ? { query: q } : void 0,
@@ -7473,6 +7943,7 @@ function dashboardHostRoutePaths(dashboard, authenticatedRoutes = []) {
7473
7943
  const pagePaths = [
7474
7944
  basePath,
7475
7945
  pagePath("admin"),
7946
+ pagePath("board"),
7476
7947
  pagePath("code"),
7477
7948
  `${pagePath("code")}/*`,
7478
7949
  conversationsPath,
@@ -7518,6 +7989,7 @@ function dashboardHostRoutePaths(dashboard, authenticatedRoutes = []) {
7518
7989
  "/api/automations",
7519
7990
  "/api/automations/*",
7520
7991
  "/api/skills",
7992
+ "/api/board",
7521
7993
  "/api/code",
7522
7994
  "/api/code/*",
7523
7995
  "/api/connections",
@@ -7952,6 +8424,7 @@ async function createApp(options) {
7952
8424
  registerVercelConversationWorkDevConsumer(getConversationWorkOptions());
7953
8425
  registerVercelPluginTaskDevConsumer();
7954
8426
  registerVercelWorkspaceSnapshotJobDevConsumer();
8427
+ registerVercelCacheWarmupDevConsumer();
7955
8428
  registerVercelBackgroundCompactionDevConsumer();
7956
8429
  }
7957
8430
  app.post("/api/internal/agent/continue", (c) => {
@@ -7967,6 +8440,11 @@ async function createApp(options) {
7967
8440
  workspaceSnapshotJobPOST ??= createVercelWorkspaceSnapshotJobCallback();
7968
8441
  return workspaceSnapshotJobPOST(c.req.raw);
7969
8442
  });
8443
+ let cacheWarmupPOST;
8444
+ app.post(JUNIOR_CACHE_WARMUP_CALLBACK_ROUTE, (c) => {
8445
+ cacheWarmupPOST ??= createVercelCacheWarmupCallback();
8446
+ return cacheWarmupPOST(c.req.raw);
8447
+ });
7970
8448
  let backgroundCompactionPOST;
7971
8449
  app.post(JUNIOR_CONTEXT_COMPACTION_CALLBACK_ROUTE, (c) => {
7972
8450
  backgroundCompactionPOST ??= createVercelBackgroundCompactionCallback();
@@ -7991,6 +8469,7 @@ async function createApp(options) {
7991
8469
  conversationWorkQueueConsumer(getConversationWorkOptions()),
7992
8470
  pluginTaskQueueConsumer(),
7993
8471
  workspaceSnapshotJobQueueConsumer(),
8472
+ cacheWarmupQueueConsumer(),
7994
8473
  backgroundCompactionQueueConsumer()
7995
8474
  ], backgroundWork) });
7996
8475
  }