@sentry/junior 0.287.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 (72) hide show
  1. package/dist/{adapter-CL-HUKgd.js → adapter-Cikcqdty.js} +1 -1
  2. package/dist/{admin-C9urXVfi.js → admin-BcSxHuTB.js} +2 -2
  3. package/dist/{agent-runner-Bfnw551N.js → agent-runner-9MXyWUL8.js} +173 -89
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +8 -7
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +403 -40
  8. package/dist/{app-DBY5TnfY.d.ts → app-BUklJVBe.d.ts} +4 -2
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +521 -70
  11. package/dist/{assistant-reply-u_PRYzuz.js → assistant-reply-mj47jMRV.js} +1 -1
  12. package/dist/{automation-DksGNDRO.js → automation-DDXwHQs5.js} +2 -2
  13. package/dist/{background-compaction-queue-CYI909P5.js → background-compaction-queue-CjllSPir.js} +161 -90
  14. package/dist/{briefs-DaXiMWzT.js → briefs-DW9iuolG.js} +4 -3
  15. package/dist/{catalog-runtime-BCIuBe4d.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-CkHcUMN7.js → config-CLJcyYEF.js} +401 -9
  24. package/dist/{connections-BnIj0wtx.js → connections-BtdJftow.js} +9 -9
  25. package/dist/{conversation-E7ZPJx2H.js → conversation-DhoqHtQ7.js} +23 -6
  26. package/dist/{conversation-pending-messages-DVch6YQw.js → conversation-pending-messages-DHV0S4uF.js} +1 -1
  27. package/dist/{conversation-privacy-DF1hW0ja.js → conversation-privacy-BPirIVlX.js} +1 -1
  28. package/dist/core-model-BTt5E5b0.js +182 -0
  29. package/dist/{credential-sync-CzMar9hq.js → credential-sync-Co8Q2xRW.js} +28 -20
  30. package/dist/{db-DJ11eZqq.js → db-Co7DTYYh.js} +30 -20
  31. package/dist/{db-YDKKDxlh.d.ts → db-zIs8-Ba3.d.ts} +6 -2
  32. package/dist/{executor-BY9TB31g.js → executor-m0kIN71Q.js} +93 -12
  33. package/dist/{media-Cz1ZiV1U.js → history-IjdmO_r6.js} +6 -86
  34. package/dist/instrumentation.js +2 -2
  35. package/dist/{logging-BO5zU6Mt.js → logging-DbD-dErY.js} +3 -2
  36. package/dist/media-BAHvgkok.js +85 -0
  37. package/dist/{message-CsUbuEc8.js → message-DKTdTYm-.js} +9 -9
  38. package/dist/nitro.d.ts +1 -1
  39. package/dist/nitro.js +19 -41
  40. package/dist/{oauth-callback-server-hiDKK0_n.js → oauth-callback-server-CpbepSbp.js} +2 -2
  41. package/dist/{projection-CL_YWeGf.js → projection-BViECfYu.js} +309 -616
  42. package/dist/{prompt-BHOEQSmf.js → prompt-KT6MaDHN.js} +2 -182
  43. package/dist/{registry-BriFLnaJ.js → registry-D-Acyjhh.js} +1 -1
  44. package/dist/{resolve-Bt6GgAiA.js → resolve-gkT2R66z.js} +3 -3
  45. package/dist/{result-Bo1TZu0Q.js → result-DHmCFEt8.js} +8 -8
  46. package/dist/{runner-D3YeCQgt.js → runner-DBKjGjH-.js} +8 -8
  47. package/dist/{sandbox-egress-signals-CcnSPP4S.js → sandbox-egress-signals-9n8hqx29.js} +1 -1
  48. package/dist/{schedule-BTp__wrw.js → schedule-cP0AACm1.js} +11 -2
  49. package/dist/{schema-C6fsEwjo.d.ts → schema-B_6aOcx5.d.ts} +114 -3
  50. package/dist/{schema-BWE3RJEB.js → schema-DxicIQbc.js} +66 -13
  51. package/dist/{service-account-r6fl0b-9.js → service-account-Bi0HsY6w.js} +3 -3
  52. package/dist/{service-account-DiQQuuw7.js → service-account-CDlC9ssy.js} +3 -3
  53. package/dist/{session-stop-B2Nut40V.js → session-stop-BWOsuo8p.js} +56 -14
  54. package/dist/{skills-CD5aJdzg.js → skills-DO5K68Rq.js} +2 -2
  55. package/dist/{spawn-CalgZQiu.js → spawn-BBqZDcPa.js} +5 -5
  56. package/dist/{stop-kujZLbi0.js → stop-WC97cmHz.js} +802 -338
  57. package/dist/{store-DdIEUL1q.js → store-ByR1Lr7e.js} +4 -16
  58. package/dist/{task-runner-D_RDr2Hu.js → task-runner-B-Ewf8TX.js} +30 -22
  59. package/dist/{turn-failure-response-B5nV1Er-.js → turn-failure-response-CpdPoZSl.js} +18 -9
  60. package/dist/{validation-K4pqwoVZ.js → validation-B4sbIoES.js} +1 -1
  61. package/dist/{version-DBvhk1X9.js → version-D6lpuAgL.js} +1 -1
  62. package/dist/version.js +1 -1
  63. package/dist/{viewer-DrMmFUul.js → viewer-CeP27tC3.js} +4 -4
  64. package/dist/warmup-P_GJCL1c.js +767 -0
  65. package/dist/{work-ljRoODGu.js → work-DI7x1Slm.js} +14 -13
  66. package/dist/{worker-CYO1Q0Js.js → worker-CYPTOT4j.js} +6 -6
  67. package/migrations/0089_conversation_paused_status.sql +3 -0
  68. package/migrations/0090_guardian_review_time_index.sql +20 -0
  69. package/migrations/meta/0089_snapshot.json +4372 -0
  70. package/migrations/meta/0090_snapshot.json +4388 -0
  71. package/migrations/meta/_journal.json +14 -0
  72. package/package.json +5 -4
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 { $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 { 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, 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 { 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-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";
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, 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";
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-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";
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-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";
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-CYPTOT4j.js";
36
+ import { t as bindMessageAgent } from "./message-DKTdTYm-.js";
37
+ import { t as bindSpawnAgent } from "./spawn-BBqZDcPa.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,232 @@ 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
+ 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
+ }
57
286
  // src/chat/events/timers.ts
58
287
  /** Publish a bounded batch of due timers; the mailbox owns agent execution. */
59
288
  async function runTimerWatchHeartbeat(args) {
@@ -106,22 +335,15 @@ async function recoverConversationWork(args) {
106
335
  });
107
336
  } catch (error) {
108
337
  logException(error, "conversation.work.recovery.failed");
109
- if (isInvalidConversationRecordError(error)) await removeActiveConversation({
338
+ if (isInvalidConversationRecordError(error)) await pruneActiveConversation({
110
339
  conversationId,
111
340
  state: args.state
112
341
  });
113
342
  return;
114
343
  }
115
344
  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({
345
+ if (!work || !hasRunnableConversationWork(work)) {
346
+ await pruneActiveConversation({
125
347
  conversationId,
126
348
  state: args.state
127
349
  });
@@ -156,7 +378,7 @@ async function recoverConversationWork(args) {
156
378
  }
157
379
  return;
158
380
  }
159
- if (work.execution.lease || !hasRunnableConversationWork$1(work)) return;
381
+ if (work.execution.lease) return;
160
382
  if ((await ensureConversationWake({
161
383
  conversationId,
162
384
  idempotencyKey: heartbeatIdempotencyKey("pending", conversationId, args.nowMs),
@@ -1142,6 +1364,11 @@ async function runHeartbeat(args) {
1142
1364
  conversationWorkQueue: queue,
1143
1365
  nowMs: args.nowMs
1144
1366
  });
1367
+ try {
1368
+ await backfillCacheWarmingGaps({ nowMs: args.nowMs });
1369
+ } catch (error) {
1370
+ logException(error, "cache_warming.backfill.failed");
1371
+ }
1145
1372
  }
1146
1373
  // src/handlers/scheduler-auth.ts
1147
1374
  function getSchedulerSecret() {
@@ -1737,6 +1964,211 @@ async function isSlackWorkspaceMember(raw, state) {
1737
1964
  };
1738
1965
  });
1739
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
+ }
1740
2172
  // src/chat/ingress/slack-interaction-input.ts
1741
2173
  /**
1742
2174
  * Build the Slack input that a click or form makes in a thread, as a
@@ -1783,28 +2215,13 @@ async function tellPerson(target, userId, text) {
1783
2215
  userId
1784
2216
  });
1785
2217
  }
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
- };
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
+ });
1808
2225
  }
1809
2226
  /** Show the current state of an item, such as after a click on a stale card. */
1810
2227
  async function refreshCards(services, user, itemId) {
@@ -2009,8 +2426,8 @@ async function handleAppHomeDisconnect(args) {
2009
2426
  });
2010
2427
  }
2011
2428
  /**
2012
- * Handle Slack interactions from App Home and Review item cards: block
2013
- * actions and submitted forms.
2429
+ * Handle Slack interactions from App Home, Review item cards, and dashboard
2430
+ * link previews: block actions and submitted forms.
2014
2431
  */
2015
2432
  async function handleSlackInteractivePayload(args) {
2016
2433
  const spanAttributes = { userId: args.payload.user?.id?.trim() || void 0 };
@@ -2034,6 +2451,16 @@ async function handleSlackInteractivePayload(args) {
2034
2451
  return;
2035
2452
  }
2036
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
+ }
2037
2464
  const disconnect = args.payload.actions?.find((candidate) => candidate.action_id === "app_home_disconnect");
2038
2465
  const provider = disconnect?.selected_option?.value ?? disconnect?.value;
2039
2466
  if (!provider) return;
@@ -2346,7 +2773,8 @@ async function ingestEventAutomations(input, options) {
2346
2773
  const db = getDb();
2347
2774
  const nowMs = options.nowMs ?? Date.now();
2348
2775
  const catalog = getEventCatalog();
2349
- 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));
2350
2778
  let dispatched = 0;
2351
2779
  const errors = [];
2352
2780
  for (const task of tasks) try {
@@ -2906,6 +3334,15 @@ async function handleSlackEvent(args) {
2906
3334
  else await presentSlackAutomationDetails(event, installation.teamId);
2907
3335
  return;
2908
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
+ }
2909
3346
  if (event.type === "app_home_opened" && event.user) {
2910
3347
  await publishAppHomeViewBestEffort(event.user);
2911
3348
  return;
@@ -3357,21 +3794,23 @@ function createEventTeamIdResolver() {
3357
3794
  };
3358
3795
  }
3359
3796
  // src/chat/events/app-publisher.ts
3797
+ const WATCH_MATCH_CONCURRENCY = 4;
3360
3798
  /** Build the core event publisher used by plugin routes. */
3361
3799
  function createEventAppPublisher(args) {
3362
3800
  const resolveEventAutomationTeamId = createEventTeamIdResolver();
3363
3801
  return {
3364
- async hasMatch(event) {
3802
+ async hasMatch(events) {
3365
3803
  const work = args.conversationWork();
3366
3804
  const eventAutomationTeamId = await resolveEventAutomationTeamId();
3367
- 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({
3368
3807
  data: event.data,
3369
3808
  eventType: event.eventType,
3370
3809
  namespace: event.namespace,
3371
3810
  identifier: event.identifier,
3372
3811
  state: work.state
3373
- }), eventAutomationTeamId ? findMatchingEventAutomations(getDb(), event, eventAutomationTeamId, getEventCatalog()) : Promise.resolve([])]);
3374
- 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);
3375
3814
  },
3376
3815
  async neededMatchKeys(input) {
3377
3816
  const work = args.conversationWork();
@@ -6315,6 +6754,7 @@ function registerCreateConversationTool(server, { attachmentStorage, queue, user
6315
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.",
6316
6755
  inputSchema: {
6317
6756
  message: mcpMessageTextSchema,
6757
+ title: conversationTitleSchema.optional().describe("Short title for the conversation. Omit it to generate one from the message."),
6318
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."),
6319
6759
  idempotencyKey: mcpIdempotencyKeySchema
6320
6760
  },
@@ -6325,12 +6765,13 @@ function registerCreateConversationTool(server, { attachmentStorage, queue, user
6325
6765
  openWorldHint: true,
6326
6766
  readOnlyHint: false
6327
6767
  }
6328
- }, async ({ idempotencyKey, message, visibility }) => {
6768
+ }, async ({ idempotencyKey, message, title, visibility }) => {
6329
6769
  let accepted;
6330
6770
  try {
6331
6771
  accepted = await createConversationForViewer(user, {
6332
6772
  idempotencyKey: idempotencyKey ?? randomUUID(),
6333
6773
  message,
6774
+ ...title ? { title } : void 0,
6334
6775
  visibility
6335
6776
  }, {
6336
6777
  attachmentStorage,
@@ -7473,6 +7914,7 @@ function dashboardHostRoutePaths(dashboard, authenticatedRoutes = []) {
7473
7914
  const pagePaths = [
7474
7915
  basePath,
7475
7916
  pagePath("admin"),
7917
+ pagePath("board"),
7476
7918
  pagePath("code"),
7477
7919
  `${pagePath("code")}/*`,
7478
7920
  conversationsPath,
@@ -7518,6 +7960,7 @@ function dashboardHostRoutePaths(dashboard, authenticatedRoutes = []) {
7518
7960
  "/api/automations",
7519
7961
  "/api/automations/*",
7520
7962
  "/api/skills",
7963
+ "/api/board",
7521
7964
  "/api/code",
7522
7965
  "/api/code/*",
7523
7966
  "/api/connections",
@@ -7526,6 +7969,7 @@ function dashboardHostRoutePaths(dashboard, authenticatedRoutes = []) {
7526
7969
  "/api/notifications/*",
7527
7970
  "/api/stats",
7528
7971
  "/api/versions",
7972
+ "/api/transcriptions",
7529
7973
  "/api/conversations",
7530
7974
  "/api/conversations/*",
7531
7975
  "/api/locations",
@@ -7952,6 +8396,7 @@ async function createApp(options) {
7952
8396
  registerVercelConversationWorkDevConsumer(getConversationWorkOptions());
7953
8397
  registerVercelPluginTaskDevConsumer();
7954
8398
  registerVercelWorkspaceSnapshotJobDevConsumer();
8399
+ registerVercelCacheWarmupDevConsumer();
7955
8400
  registerVercelBackgroundCompactionDevConsumer();
7956
8401
  }
7957
8402
  app.post("/api/internal/agent/continue", (c) => {
@@ -7967,6 +8412,11 @@ async function createApp(options) {
7967
8412
  workspaceSnapshotJobPOST ??= createVercelWorkspaceSnapshotJobCallback();
7968
8413
  return workspaceSnapshotJobPOST(c.req.raw);
7969
8414
  });
8415
+ let cacheWarmupPOST;
8416
+ app.post(JUNIOR_CACHE_WARMUP_CALLBACK_ROUTE, (c) => {
8417
+ cacheWarmupPOST ??= createVercelCacheWarmupCallback();
8418
+ return cacheWarmupPOST(c.req.raw);
8419
+ });
7970
8420
  let backgroundCompactionPOST;
7971
8421
  app.post(JUNIOR_CONTEXT_COMPACTION_CALLBACK_ROUTE, (c) => {
7972
8422
  backgroundCompactionPOST ??= createVercelBackgroundCompactionCallback();
@@ -7991,6 +8441,7 @@ async function createApp(options) {
7991
8441
  conversationWorkQueueConsumer(getConversationWorkOptions()),
7992
8442
  pluginTaskQueueConsumer(),
7993
8443
  workspaceSnapshotJobQueueConsumer(),
8444
+ cacheWarmupQueueConsumer(),
7994
8445
  backgroundCompactionQueueConsumer()
7995
8446
  ], backgroundWork) });
7996
8447
  }