@sentry/junior 0.292.0 → 0.294.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.
- package/dist/{adapter-Cigb1MTr.js → adapter-DxLhJEnO.js} +1 -1
- package/dist/{admin-BO9V7vnn.js → admin-vt8aSiCD.js} +2 -2
- package/dist/{agent-runner-BuH7EHrX.js → agent-runner-DJu7w6mI.js} +318 -162
- package/dist/api/schema.d.ts +2 -2
- package/dist/api/schema.js +5 -5
- package/dist/api.d.ts +1 -1
- package/dist/api.js +65 -40
- package/dist/{app-C47PT68y.d.ts → app--a5RLOrr.d.ts} +4 -2
- package/dist/app.d.ts +1 -1
- package/dist/app.js +454 -435
- package/dist/{assistant-reply-ZjLRGHm2.js → assistant-reply-iTtEdDyc.js} +1 -1
- package/dist/{automation-CrsYnvdV.js → automation-BM-OBsKW.js} +72 -23
- package/dist/{background-compaction-queue-CqZBPe9g.js → background-compaction-queue-D2j-0XkH.js} +4 -4
- package/dist/{briefs-DZrhXJss.js → briefs-JOAoCb6d.js} +3 -3
- package/dist/{catalog-runtime-Cj9I0dco.js → catalog-runtime-CLMA9AXd.js} +1 -1
- package/dist/cli/chat.js +15 -15
- package/dist/cli/check.js +3 -3
- package/dist/cli/main.js +3 -3
- package/dist/cli/plugins.js +4 -4
- package/dist/cli/snapshot-create.js +4 -4
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +7 -74
- package/dist/{config-BerMjSVL.js → config-mIZeGEWv.js} +17 -7
- package/dist/{connections-BWmTOVPB.js → connections-XhdVg7OR.js} +6 -6
- package/dist/{conversation-CtjR1Zcx.js → conversation-CDWejM4R.js} +1 -0
- package/dist/{conversation-pending-messages-Cd7ShwBs.js → conversation-pending-messages-Dh2tfbaw.js} +5 -2
- package/dist/{conversation-privacy-BMfbOUCo.js → conversation-privacy-C6h-X2cZ.js} +1 -1
- package/dist/{credential-sync-DZDij2CU.js → credential-sync-zigBlXS3.js} +13 -13
- package/dist/{db-BlfjuqzW.js → db--xuNV7g6.js} +99 -6
- package/dist/{db-7glZCI18.d.ts → db-DV5AbcGM.d.ts} +8 -6
- package/dist/{executor-ikZvFaMD.js → executor-BItuRqAR.js} +87 -21
- package/dist/instrumentation.js +2 -2
- package/dist/{logging-CTCH5jOy.js → logging-Cb6MGvdt.js} +1 -1
- package/dist/{message-C1ID1tKi.js → message-BTGgSmaH.js} +9 -9
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +2 -2
- package/dist/{oauth-callback-server-CStBgDU7.js → oauth-callback-server-Dvh1aOIi.js} +2 -2
- package/dist/{projection-DY93nCfX.js → projection-DLQgfO5N.js} +61 -52
- package/dist/{prompt-exicBZeb.js → prompt-qp_LdxLX.js} +5 -6
- package/dist/{registry-X_xdFY9L.js → registry-MtwokaqW.js} +1 -1
- package/dist/{resolve-B9dYN-nS.js → resolve-BnJA0UNE.js} +3 -3
- package/dist/{result-CC8bV8Fl.js → result-ChL-1KyW.js} +8 -8
- package/dist/{runner-D44qp4rc.js → runner-BONN7Dp2.js} +8 -8
- package/dist/{sandbox-egress-signals-BrH6DWkt.js → sandbox-egress-signals-nmlmI5Ab.js} +1 -1
- package/dist/{schema-CC2RxDAV.d.ts → schema-DgvcyJ1y.d.ts} +283 -45
- package/dist/{schema-CVV5r-qP.js → schema-yr0ccDni.js} +29 -4
- package/dist/{service-account-DoNZuJb-.js → service-account-Bd0lBaGr.js} +3 -3
- package/dist/{service-account-89JZHWCE.js → service-account-kio5nXSD.js} +3 -3
- package/dist/{session-stop-DNucbmPf.js → session-stop-CeCXL3j9.js} +20 -41
- package/dist/{skills-BeUfmYXL.js → skills-e3DDNlKO.js} +10 -9
- package/dist/{spawn-CIAcfcvZ.js → spawn--cRxITWQ.js} +5 -5
- package/dist/{stop-Ckd3735h.js → stop-Iai5N2PU.js} +34 -29
- package/dist/{store-CS0xoqXW.js → store-C8LsaJwS.js} +3 -3
- package/dist/{task-runner-DjjHCX_m.js → task-runner-Dw7exu0-.js} +65 -90
- package/dist/{turn-failure-response-D0bwI462.js → turn-failure-response-BqTTx3XG.js} +8 -8
- package/dist/{validation-Cvx_AupF.js → validation-BrGahtnv.js} +1 -1
- package/dist/{version-BrDx4Fzc.js → version-Bdqhx8Qh.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{viewer-4CxdwLLQ.js → viewer-CjRFHR5U.js} +3 -3
- package/dist/{warmup-B62hd4lD.js → warmup-DuxCtzKC.js} +104 -26
- package/dist/{work-Cu315oJl.js → work-BWBG1EGV.js} +11 -11
- package/dist/{worker-4ClZu6ry.js → worker-DAnBIVMs.js} +6 -6
- package/migrations/0062_plugin_report_index.sql +1 -20
- package/migrations/0078_plugin_conversation_index.sql +1 -20
- package/migrations/0079_conversation_event_author_index.sql +1 -20
- package/migrations/0080_conversation_event_latest_message_indexes.sql +2 -27
- package/migrations/0090_guardian_review_time_index.sql +1 -20
- package/migrations/0091_conversation_participant_unsubscribed_index.sql +1 -20
- package/migrations/0096_automation_task_kind.sql +75 -0
- package/migrations/0097_conversation_kind_automation.sql +6 -0
- package/migrations/meta/0096_snapshot.json +4490 -0
- package/migrations/meta/0097_snapshot.json +4490 -0
- package/migrations/meta/_journal.json +14 -0
- package/package.json +5 -5
package/dist/app.js
CHANGED
|
@@ -1,45 +1,45 @@
|
|
|
1
1
|
import { i as getActiveSpan, n as captureMessage, u as sentry_exports } from "./sentry-BRTJqumy.js";
|
|
2
|
-
import { $
|
|
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,
|
|
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-
|
|
5
|
-
import { t as JUNIOR_VERSION } from "./version-
|
|
2
|
+
import { $r as verifyScheduledAutomationCredentialSubject, Aa as normalizeSandboxEgressTracePropagationDomains, Ai as isVercelSandboxEgressRequest, At as isInvalidConversationRecordError, Bn as getPlugins, C as settleConversationTitleWork, Ca as consumeSandboxEgressAuthRequiredSignal, Co as resolveRootVisibility, Dr as reviewItemReaderForUserInConversation, Ea as parseSandboxEgressCredentialToken, En as createUserTokenStore, Eo as listConversationAnnotations, Er as reviewItemReaderForUser, Fi as resolveBaseUrl, Fn as getPluginRoutes, Gn as setBriefsConfig, Gr as findMatchingWatches, Hn as validatePlugins, Ia as createPluginEmbedder, Ji as postSlackEphemeralMessage, Jr as takeDueTimerWatches, Li as escapeSlackMrkdwnText, Mn as createPluginEventPublisher, Mo as createPluginCache, Ot as hasRunnableConversationWork, Pn as getPluginApiRoutes, Pt as pruneActiveConversation, Qr as verifyEventAutomationCredentialSubject, Ri as formatSlackLink, Ro as getConfigDefaults, Sa as clearSandboxEgressSignals, Vi as slackMention, Vn as setPlugins, Vr as collectEventMatchKeys, Xa as createPluginLogger, Xr as bindScheduledAutomationCredentialSubject, Yr as bindEventAutomationCredentialSubject, Zi as unfurlSlackLinks, Zr as bindSlackDirectCredentialSubject, _ as appendConversationMessages, ai as getDashboardReviewItemLink, ar as dismissOpenReviewItems, ca as isDmChannel, ci as parseDashboardConversationLink, di as createPluginState, do as readConversationEventPageAfter, ea as slackEntitySchema, ei as verifySlackDirectCredentialSubject, eo as readConversationAccessFromSql, fa as getWorkspaceTeamId, fr as searchReviewItems, gr as canActOnReviewItem, ji as proxyVercelSandboxEgressRequest, li as setDashboardConversationLinkOptions, lo as readLatestConversationBrief, mo as readConversationMessageEventSeq, oa as getSlackClient, pa as runWithWorkspaceTeamId, po as readConversationLastEventSeq, qi as openSlackModal, ri as getDashboardConversationLink, si as getDashboardTaskLink, ta as slackExternalRefIdSchema, tr as projectConversationMessages, uo as readConversationEventPage, ut as CONVERSATION_WORK_STALE_ENQUEUE_MS, wa as consumeSandboxEgressPermissionDeniedSignal, zo as setConfigDefaults } from "./projection-DLQgfO5N.js";
|
|
3
|
+
import { Y 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-mIZeGEWv.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-Cb6MGvdt.js";
|
|
5
|
+
import { t as JUNIOR_VERSION } from "./version-Bdqhx8Qh.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 {
|
|
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-
|
|
9
|
-
import { n as pluginCatalogRuntime } from "./catalog-runtime-
|
|
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, g as readPublicArtifact, gt as collectAttachmentGarbage, h as publicArtifactHeaders, j as verifySlackSignature, k as parseSlackUserInputSubmission, ln as processWorkspaceSnapshotJob, 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, un as ingestEvent, ut as conversationTurnIdForMessage, v as setConversationSubscription, vt as requestAttachmentDeletion, w as syncReviewItemSlackCards, y as lookupSlackUserProfile, z as joinPublicChannel } from "./agent-runner-
|
|
7
|
+
import { E as conversationKindFromRow, M as resolveActorIdentityId, R as recordGoogleSignIn, U as getConversationIdByProviderConversation, a as getConversationStore, b as withConversationMutationLock, et as touchConversationDetail, o as getDb, p as withConversationEventLock, r as getConversationEventStore, s as getSqlExecutor, t as closeDb, tt as createSlackDestination } from "./db--xuNV7g6.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-BItuRqAR.js";
|
|
9
|
+
import { n as pluginCatalogRuntime } from "./catalog-runtime-CLMA9AXd.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, dn as findAutomationSkill, fn as missingAutomationSkillReason, g as readPublicArtifact, gt as collectAttachmentGarbage, h as publicArtifactHeaders, j as verifySlackSignature, k as parseSlackUserInputSubmission, ln as processWorkspaceSnapshotJob, 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, un as ingestEvent, ut as conversationTurnIdForMessage, v as setConversationSubscription, vt as requestAttachmentDeletion, w as syncReviewItemSlackCards, y as lookupSlackUserProfile, z as joinPublicChannel } from "./agent-runner-DJu7w6mI.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-
|
|
13
|
-
import { r as getStateAdapter, t as disconnectStateAdapter } from "./adapter-
|
|
12
|
+
import { g as createCache, i as readActorIdentity, l as resolveViewerUser, p as parseAvatarUrl } from "./viewer-CjRFHR5U.js";
|
|
13
|
+
import { r as getStateAdapter, t as disconnectStateAdapter } from "./adapter-DxLhJEnO.js";
|
|
14
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-
|
|
15
|
+
import { F as annotationCard, Y as conversationBriefSchema, k as conversationTitleSchema, p as conversationFeedQuerySchema, x as conversationSurfaceSchema, y as conversationReportStatusSchema } from "./conversation-CDWejM4R.js";
|
|
16
16
|
import { t as SANDBOX_EGRESS_PROXY_PATH } from "./proxy-path-BHYoKZdq.js";
|
|
17
|
-
import { a as segmentGapsKey,
|
|
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-
|
|
19
|
-
import { D as listPendingAgentInvocationResults, E as listPendingAgentInvocationMailboxAppends } from "./turn-failure-response-
|
|
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-
|
|
17
|
+
import { a as segmentGapsKey, f as MINUTE_MS, g as gapSegment, m as NO_REPLY_GAP_MS, n as GLOBAL_GAPS_MAX, p as MIN_WARMUP_PREFIX_TOKENS, r as GLOBAL_GAPS_TTL_MS, t as CONVERSATION_STATE_TTL_MS } from "./warmup-DuxCtzKC.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-D2j-0XkH.js";
|
|
19
|
+
import { D as listPendingAgentInvocationResults, E as listPendingAgentInvocationMailboxAppends } from "./turn-failure-response-BqTTx3XG.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-CeCXL3j9.js";
|
|
21
21
|
import { _ as buttonUserInputField } from "./reporting-window-B3Ze-Qnt.js";
|
|
22
|
-
import { c as setSandboxResourceConfig, o as getSandboxResourceConfig } from "./resolve-
|
|
23
|
-
import { _ as listActiveConversationIds, g as getConversationWorkState, h as getConversation, l as clearExpiredConversationLease, m as ensureConversationWake, r as appendAndEnqueueInboundMessage } from "./store-
|
|
24
|
-
import { A as withScheduledAutomationLock,
|
|
25
|
-
import {
|
|
26
|
-
import { n as validatePluginRegistrations, t as validatePluginEgressCredentialHooks } from "./validation-
|
|
22
|
+
import { c as setSandboxResourceConfig, o as getSandboxResourceConfig } from "./resolve-BnJA0UNE.js";
|
|
23
|
+
import { _ as listActiveConversationIds, g as getConversationWorkState, h as getConversation, l as clearExpiredConversationLease, m as ensureConversationWake, r as appendAndEnqueueInboundMessage } from "./store-C8LsaJwS.js";
|
|
24
|
+
import { A as withScheduledAutomationLock, 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, d as getDispatchRecord, gt as coerceThreadConversationState, h as listPendingDispatchMailboxAppends, i as buildDispatchId, j as blockEventAutomation, k as scheduledRunId, m as isTerminalDispatchStatus, o as confirmDispatchMailboxAppend, ot as recordAutomationExecution, p as getPluginDispatchProjection, s as createOrGetDispatch, t as processPluginTask, w as listScheduledAutomationsForTeam, x as notifyAutomationBlocked, xt as eventGuidance, y as markDispatchFailed } from "./task-runner-Dw7exu0-.js";
|
|
25
|
+
import { H as automationTaskSchema, N as scheduledRunSchema, U as automationTaskText, l as automationListQuerySchema, s as automationExecutionStatusSchema } from "./automation-BM-OBsKW.js";
|
|
26
|
+
import { n as validatePluginRegistrations, t as validatePluginEgressCredentialHooks } from "./validation-BrGahtnv.js";
|
|
27
27
|
import { a as pluginRuntimeRegistrationsFromPluginSet, n as pluginCatalogConfigFromEnv, r as pluginCatalogConfigFromPluginSet, t as defineJuniorPlugins } from "./plugins-HYh_JOdw.js";
|
|
28
|
-
import { a as conversationPendingMessageDeliverySchema } from "./conversation-pending-messages-
|
|
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-
|
|
30
|
-
import { a as enqueueAgentInvocation, i as endAgentInvocationsOfStoppedWork } from "./work-
|
|
31
|
-
import { n as enqueueAgentInvocationResult } from "./result-
|
|
32
|
-
import { o as unlinkProvider } from "./connections-
|
|
33
|
-
import { a as GET$5, i as publishAppHomeView, r as GET$6, t as receiveLocalOAuthCredential } from "./credential-sync-
|
|
28
|
+
import { a as conversationPendingMessageDeliverySchema } from "./conversation-pending-messages-Dh2tfbaw.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-Iai5N2PU.js";
|
|
30
|
+
import { a as enqueueAgentInvocation, i as endAgentInvocationsOfStoppedWork } from "./work-BWBG1EGV.js";
|
|
31
|
+
import { n as enqueueAgentInvocationResult } from "./result-ChL-1KyW.js";
|
|
32
|
+
import { o as unlinkProvider } from "./connections-XhdVg7OR.js";
|
|
33
|
+
import { a as GET$5, i as publishAppHomeView, r as GET$6, t as receiveLocalOAuthCredential } from "./credential-sync-zigBlXS3.js";
|
|
34
34
|
import { t as nameRequestRoute } from "./sentry-route-name-BhwWnfqj.js";
|
|
35
|
-
import { t as processConversationWork } from "./worker-
|
|
36
|
-
import { t as bindMessageAgent } from "./message-
|
|
37
|
-
import { t as bindSpawnAgent } from "./spawn
|
|
35
|
+
import { t as processConversationWork } from "./worker-DAnBIVMs.js";
|
|
36
|
+
import { t as bindMessageAgent } from "./message-BTGgSmaH.js";
|
|
37
|
+
import { t as bindSpawnAgent } from "./spawn--cRxITWQ.js";
|
|
38
38
|
import { createRequire } from "node:module";
|
|
39
39
|
import { Hono } from "hono";
|
|
40
40
|
import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
41
41
|
import * as z from "zod";
|
|
42
|
-
import { and, asc, eq, inArray, isNotNull, isNull, lte, ne, or, sql } from "drizzle-orm";
|
|
42
|
+
import { and, asc, desc, eq, gte, inArray, isNotNull, isNull, lte, ne, or, sql } from "drizzle-orm";
|
|
43
43
|
import { EVENT_SUMMARY_MAX_LENGTH, EVENT_TEXT_MAX_LENGTH, dispatchOptionsSchema, eventSchema, eventTriggerFiltersText, isSlackDestination, userSchema } from "@sentry/junior-plugin-api";
|
|
44
44
|
import { pathToFileURL } from "node:url";
|
|
45
45
|
import pLimit from "p-limit";
|
|
@@ -59,8 +59,8 @@ import { getSessionCookie } from "better-auth/cookies";
|
|
|
59
59
|
import { betterAuth } from "better-auth/minimal";
|
|
60
60
|
// src/chat/cache-warming/backfill.ts
|
|
61
61
|
/**
|
|
62
|
-
*
|
|
63
|
-
* history.
|
|
62
|
+
* Fill of the empty cache warming gap lists from stored Conversation
|
|
63
|
+
* history, about once a month.
|
|
64
64
|
*
|
|
65
65
|
* `warmup.ts` learns reply gaps only from idle periods after it is deployed.
|
|
66
66
|
* Until a `gapSegment` has gaps, Junior sends no warmups for it. This replays
|
|
@@ -77,13 +77,14 @@ import { betterAuth } from "better-auth/minimal";
|
|
|
77
77
|
* Conversation had when an idle period started. So it fills only the
|
|
78
78
|
* segments of Conversations that are not archived and have work state
|
|
79
79
|
* `none`, which most Conversations have. The `open` and `done` segments and
|
|
80
|
-
* the `archived:*` segments stay empty until live gaps arrive.
|
|
81
|
-
*
|
|
82
|
-
*
|
|
83
|
-
*
|
|
80
|
+
* the `archived:*` segments stay empty until live gaps arrive. Until then,
|
|
81
|
+
* `decideWarmup` leans on their `parentGapSegment`, a `none` segment that
|
|
82
|
+
* this fills. Each idle period still records its gap, so the segment fills
|
|
83
|
+
* from live idle periods.
|
|
84
84
|
*/
|
|
85
|
-
const BACKFILL_KEY = "junior:cache_warming:backfill:work_state";
|
|
85
|
+
const BACKFILL_KEY = "junior:cache_warming:backfill:work_state:v2";
|
|
86
86
|
const BACKFILL_CLAIM_TTL_MS = 60 * MINUTE_MS;
|
|
87
|
+
const BACKFILL_DONE_TTL_MS = GLOBAL_GAPS_TTL_MS;
|
|
87
88
|
const CONVERSATION_BATCH_SIZE = 10;
|
|
88
89
|
const QUERY_CANCELED = "57014";
|
|
89
90
|
const BACKFILL_BUDGET_MS = 6e4;
|
|
@@ -103,40 +104,29 @@ function historySegment(userActor, endedTurns) {
|
|
|
103
104
|
});
|
|
104
105
|
}
|
|
105
106
|
async function loadConversations(windowStartMs) {
|
|
106
|
-
return await
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
107
|
+
return await getDb().select({
|
|
108
|
+
conversationId: juniorConversations.conversationId,
|
|
109
|
+
kind: juniorConversations.kind,
|
|
110
|
+
parentConversationId: juniorConversations.parentConversationId
|
|
111
|
+
}).from(juniorConversations).where(and(gte(juniorConversations.lastActivityAt, new Date(windowStartMs)), isNull(juniorConversations.transcriptPurgedAt))).orderBy(desc(juniorConversations.lastActivityAt), juniorConversations.conversationId);
|
|
111
112
|
}
|
|
112
113
|
async function loadEvents(conversationIds) {
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
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]);
|
|
114
|
+
const events = juniorConversationEvents;
|
|
115
|
+
const isUserMessage = sql`${events.type} = 'user_message'`;
|
|
116
|
+
const message = sql`CASE
|
|
117
|
+
WHEN ${events.type} <> 'assistant_message' THEN NULL
|
|
118
|
+
WHEN ${events.schemaVersion} >= 2 THEN (${events.payload}->>'message')::jsonb
|
|
119
|
+
ELSE ${events.payload}
|
|
120
|
+
END`;
|
|
121
|
+
return await getDb().select({
|
|
122
|
+
conversationId: events.conversationId,
|
|
123
|
+
type: sql`${events.type}`,
|
|
124
|
+
personInstruction: sql`CASE WHEN ${isUserMessage} THEN (${events.payload}->'provenance'->'actor'->>'userId') IS NOT NULL END`,
|
|
125
|
+
stopReason: sql`(${message})->>'stopReason'`,
|
|
126
|
+
startedAtMs: sql`(${message})->>'timestamp'`,
|
|
127
|
+
cacheRead: sql`${events.payload}->'usage'->>'cacheRead'`,
|
|
128
|
+
cacheWrite: sql`${events.payload}->'usage'->>'cacheWrite'`
|
|
129
|
+
}).from(events).innerJoin(juniorConversations, eq(juniorConversations.conversationId, events.conversationId)).where(and(inArray(events.conversationId, conversationIds), or(eq(events.type, "assistant_message"), and(isUserMessage, sql`(${events.payload}->'provenance'->>'authority') = 'instruction'`)), gte(events.createdAt, juniorConversations.createdAt))).orderBy(events.conversationId, events.seq);
|
|
140
130
|
}
|
|
141
131
|
/**
|
|
142
132
|
* Replay the model calls of one Conversation the way the recorder in
|
|
@@ -255,9 +245,9 @@ async function collectGaps(nowMs, budgetMs) {
|
|
|
255
245
|
};
|
|
256
246
|
}
|
|
257
247
|
/**
|
|
258
|
-
* Fill each empty cache warming gap list
|
|
259
|
-
*
|
|
260
|
-
*
|
|
248
|
+
* Fill each empty cache warming gap list from the stored Conversation
|
|
249
|
+
* history. The heartbeat calls it each minute. After a run completes, a call
|
|
250
|
+
* makes one state request and returns, until the completed run expires.
|
|
261
251
|
*
|
|
262
252
|
* A run that uses its scan budget writes the gaps that it has and also
|
|
263
253
|
* completes. Some gaps are better than none, and a run that cannot finish
|
|
@@ -298,7 +288,7 @@ async function backfillCacheWarmingGaps(args) {
|
|
|
298
288
|
gapCount += newest.length;
|
|
299
289
|
segmentCount += 1;
|
|
300
290
|
}
|
|
301
|
-
await state.set(BACKFILL_KEY, "done");
|
|
291
|
+
await state.set(BACKFILL_KEY, "done", BACKFILL_DONE_TTL_MS);
|
|
302
292
|
const completed = {
|
|
303
293
|
...logAttributes,
|
|
304
294
|
"app.cache_warming.backfill.gap_count": gapCount,
|
|
@@ -330,99 +320,6 @@ async function runTimerWatchHeartbeat(args) {
|
|
|
330
320
|
}
|
|
331
321
|
if (errors.length) throw new AggregateError(errors, "Timer Watch delivery failed");
|
|
332
322
|
}
|
|
333
|
-
// src/chat/task-execution/heartbeat.ts
|
|
334
|
-
const DEFAULT_RECOVERY_LIMIT = 25;
|
|
335
|
-
function heartbeatIdempotencyKey(reason, conversationId, nowMs) {
|
|
336
|
-
return `heartbeat:${reason}:${conversationId}:${nowMs}`;
|
|
337
|
-
}
|
|
338
|
-
/** Requeue expired leases and stranded mailbox work without running the agent. */
|
|
339
|
-
async function recoverConversationWork(args) {
|
|
340
|
-
if (!getChatConfig().conversationWorkEnabled) {
|
|
341
|
-
logWarn("conversation.work.recovery.disabled");
|
|
342
|
-
return {
|
|
343
|
-
expiredLeaseCount: 0,
|
|
344
|
-
pendingCount: 0
|
|
345
|
-
};
|
|
346
|
-
}
|
|
347
|
-
const result = {
|
|
348
|
-
expiredLeaseCount: 0,
|
|
349
|
-
pendingCount: 0
|
|
350
|
-
};
|
|
351
|
-
const staleBeforeMs = args.nowMs - CONVERSATION_WORK_STALE_ENQUEUE_MS;
|
|
352
|
-
const ids = await listActiveConversationIds({
|
|
353
|
-
limit: args.limit ?? DEFAULT_RECOVERY_LIMIT,
|
|
354
|
-
staleBeforeMs,
|
|
355
|
-
state: args.state
|
|
356
|
-
});
|
|
357
|
-
for (const conversationId of ids) await withLogContext({ conversationId }, async () => {
|
|
358
|
-
let work;
|
|
359
|
-
try {
|
|
360
|
-
work = await getConversationWorkState({
|
|
361
|
-
conversationId,
|
|
362
|
-
state: args.state
|
|
363
|
-
});
|
|
364
|
-
} catch (error) {
|
|
365
|
-
logException(error, "conversation.work.recovery.failed");
|
|
366
|
-
if (isInvalidConversationRecordError(error)) await pruneActiveConversation({
|
|
367
|
-
conversationId,
|
|
368
|
-
state: args.state
|
|
369
|
-
});
|
|
370
|
-
return;
|
|
371
|
-
}
|
|
372
|
-
try {
|
|
373
|
-
if (!work || !hasRunnableConversationWork(work)) {
|
|
374
|
-
await pruneActiveConversation({
|
|
375
|
-
conversationId,
|
|
376
|
-
state: args.state
|
|
377
|
-
});
|
|
378
|
-
return;
|
|
379
|
-
}
|
|
380
|
-
if (work.execution.lease && work.execution.lease.expiresAtMs <= args.nowMs) {
|
|
381
|
-
const recovery = await clearExpiredConversationLease({
|
|
382
|
-
beforeWorkStops: args.beforeWorkStops,
|
|
383
|
-
conversationId,
|
|
384
|
-
nowMs: args.nowMs,
|
|
385
|
-
state: args.state
|
|
386
|
-
});
|
|
387
|
-
if (recovery === "not_expired") return;
|
|
388
|
-
if (recovery === "stopped") {
|
|
389
|
-
logException(/* @__PURE__ */ new Error("Conversation work stopped after repeated failed attempts"), "conversation.work.retry.exhausted", {
|
|
390
|
-
"app.run.id": work.execution.runId ?? "unknown",
|
|
391
|
-
"app.worker.last_progress_at_ms": work.execution.lastProgressAtMs ?? work.createdAtMs,
|
|
392
|
-
"app.worker.retry_count": (work.execution.retryCount ?? 0) + 1
|
|
393
|
-
});
|
|
394
|
-
return;
|
|
395
|
-
}
|
|
396
|
-
if ((await ensureConversationWake({
|
|
397
|
-
conversationId,
|
|
398
|
-
idempotencyKey: heartbeatIdempotencyKey("lease", conversationId, args.nowMs),
|
|
399
|
-
nowMs: args.nowMs,
|
|
400
|
-
queue: args.queue,
|
|
401
|
-
replaceExistingWake: true,
|
|
402
|
-
state: args.state
|
|
403
|
-
})).status === "enqueued") {
|
|
404
|
-
result.expiredLeaseCount += 1;
|
|
405
|
-
logInfo("conversation.work.lease_expired.requeued");
|
|
406
|
-
}
|
|
407
|
-
return;
|
|
408
|
-
}
|
|
409
|
-
if (work.execution.lease) return;
|
|
410
|
-
if ((await ensureConversationWake({
|
|
411
|
-
conversationId,
|
|
412
|
-
idempotencyKey: heartbeatIdempotencyKey("pending", conversationId, args.nowMs),
|
|
413
|
-
nowMs: args.nowMs,
|
|
414
|
-
queue: args.queue,
|
|
415
|
-
state: args.state
|
|
416
|
-
})).status === "enqueued") {
|
|
417
|
-
result.pendingCount += 1;
|
|
418
|
-
logInfo("conversation.work.pending.requeued");
|
|
419
|
-
}
|
|
420
|
-
} catch (error) {
|
|
421
|
-
logException(error, "conversation.work.recovery.failed");
|
|
422
|
-
}
|
|
423
|
-
});
|
|
424
|
-
return result;
|
|
425
|
-
}
|
|
426
323
|
// src/chat/agent-dispatch/validation.ts
|
|
427
324
|
function hasIssueAtPath(issues, path) {
|
|
428
325
|
return issues.some((issue) => issue.path.length === path.length && issue.path.every((value, index) => value === path[index]));
|
|
@@ -524,6 +421,7 @@ function createHeartbeatContext(args) {
|
|
|
524
421
|
nowMs: args.nowMs,
|
|
525
422
|
db: getDb(),
|
|
526
423
|
embedder: createPluginEmbedder(pluginName),
|
|
424
|
+
events: args.events,
|
|
527
425
|
state: createPluginState(pluginName),
|
|
528
426
|
log: createPluginLogger(pluginName),
|
|
529
427
|
agent: {
|
|
@@ -552,7 +450,7 @@ function createHeartbeatContext(args) {
|
|
|
552
450
|
/** Create and enqueue one core-owned event automation dispatch. */
|
|
553
451
|
async function dispatchEventAutomation(args) {
|
|
554
452
|
const plugin = "junior";
|
|
555
|
-
const { credentialSubject, outcomes, ...unboundOptions } = args.options;
|
|
453
|
+
const { credentialSubject, outcomes, skill, ...unboundOptions } = args.options;
|
|
556
454
|
validateDispatchOptions({ ...unboundOptions });
|
|
557
455
|
const boundSubject = credentialSubject ? bindEventAutomationCredentialSubject({
|
|
558
456
|
plugin,
|
|
@@ -562,6 +460,7 @@ async function dispatchEventAutomation(args) {
|
|
|
562
460
|
const options = {
|
|
563
461
|
...unboundOptions,
|
|
564
462
|
...outcomes !== void 0 ? { outcomes } : void 0,
|
|
463
|
+
...skill ? { skill } : void 0,
|
|
565
464
|
...boundSubject ? { credentialSubject: boundSubject } : void 0,
|
|
566
465
|
source: {
|
|
567
466
|
kind: "event_automation",
|
|
@@ -579,7 +478,7 @@ async function dispatchEventAutomation(args) {
|
|
|
579
478
|
/** Create and enqueue one core-owned scheduled automation dispatch. */
|
|
580
479
|
async function dispatchScheduledAutomation(args) {
|
|
581
480
|
const plugin = "scheduler";
|
|
582
|
-
const { credentialSubject, outcomes, ...unboundOptions } = args.options;
|
|
481
|
+
const { credentialSubject, outcomes, skill, ...unboundOptions } = args.options;
|
|
583
482
|
validateDispatchOptions({ ...unboundOptions });
|
|
584
483
|
const boundSubject = credentialSubject ? bindScheduledAutomationCredentialSubject({
|
|
585
484
|
plugin,
|
|
@@ -589,6 +488,7 @@ async function dispatchScheduledAutomation(args) {
|
|
|
589
488
|
const options = {
|
|
590
489
|
...unboundOptions,
|
|
591
490
|
...outcomes !== void 0 ? { outcomes } : void 0,
|
|
491
|
+
...skill ? { skill } : void 0,
|
|
592
492
|
...boundSubject ? { credentialSubject: boundSubject } : void 0,
|
|
593
493
|
source: {
|
|
594
494
|
kind: "scheduled_automation",
|
|
@@ -609,54 +509,356 @@ async function getScheduledAutomationDispatch(id) {
|
|
|
609
509
|
plugin: "scheduler",
|
|
610
510
|
id
|
|
611
511
|
});
|
|
612
|
-
}
|
|
613
|
-
// src/chat/
|
|
614
|
-
/**
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
}
|
|
512
|
+
}
|
|
513
|
+
// src/chat/automations/reply-attribution.ts
|
|
514
|
+
/** Name the Automation in the footer of the replies that its runs post. */
|
|
515
|
+
function automationReplyAttribution(title) {
|
|
516
|
+
const detail = (title ?? "").replace(/\s+/g, " ").trim().slice(0, 128).trim();
|
|
517
|
+
return detail ? {
|
|
518
|
+
label: "Automation",
|
|
519
|
+
detail
|
|
520
|
+
} : { label: "Automation" };
|
|
521
|
+
}
|
|
522
|
+
// src/chat/event-automations/runs.ts
|
|
523
|
+
/**
|
|
524
|
+
* Record a dispatched event automation run with the Automation version it ran,
|
|
525
|
+
* and link its Conversation when it exists. The dispatch can finish before
|
|
526
|
+
* this write, so a stored run, or a retry of the same Event, keeps the row it
|
|
527
|
+
* has.
|
|
528
|
+
*/
|
|
529
|
+
async function recordEventAutomationRunStarted(db, args) {
|
|
530
|
+
await db.insert(juniorAutomationRuns).values({
|
|
531
|
+
id: args.dispatchId,
|
|
532
|
+
automationId: args.automation.id,
|
|
533
|
+
automationVersion: automationVersionOf(args.automation),
|
|
534
|
+
conversationId: existingConversationId(getDispatchConversationId({ id: args.dispatchId })),
|
|
535
|
+
startedAtMs: args.nowMs,
|
|
536
|
+
status: "running"
|
|
537
|
+
}).onConflictDoNothing({ target: juniorAutomationRuns.id });
|
|
538
|
+
}
|
|
539
|
+
/**
|
|
540
|
+
* Settle running event automation runs whose dispatch has ended. A run whose
|
|
541
|
+
* dispatch record is gone fails.
|
|
542
|
+
*/
|
|
543
|
+
async function settleEventAutomationRuns(db, nowMs) {
|
|
544
|
+
const runs = await db.select({
|
|
545
|
+
automationId: juniorAutomationRuns.automationId,
|
|
546
|
+
id: juniorAutomationRuns.id
|
|
547
|
+
}).from(juniorAutomationRuns).innerJoin(juniorAutomations, eq(juniorAutomations.id, juniorAutomationRuns.automationId)).where(and(eq(juniorAutomations.kind, "event"), eq(juniorAutomationRuns.status, "running")));
|
|
548
|
+
for (const run of runs) {
|
|
549
|
+
const dispatch = await getDispatchRecord(run.id);
|
|
550
|
+
const status = dispatch?.status ?? "failed";
|
|
551
|
+
if (status !== "blocked" && status !== "completed" && status !== "failed") continue;
|
|
552
|
+
await recordAutomationExecution(run.automationId, {
|
|
553
|
+
conversationId: getDispatchConversationId({ id: run.id }),
|
|
554
|
+
errorMessage: dispatch ? dispatch.errorMessage : "Event automation dispatch record is missing.",
|
|
555
|
+
executionId: run.id,
|
|
556
|
+
nowMs: dispatch?.updatedAtMs ?? nowMs,
|
|
557
|
+
status
|
|
558
|
+
});
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
// src/chat/event-automations/ingest.ts
|
|
562
|
+
/**
|
|
563
|
+
* Owns event matching and durable event-automation dispatch.
|
|
564
|
+
*
|
|
565
|
+
* Each matching automation is independently idempotent. Aggregate failures propagate
|
|
566
|
+
* so the provider can retry the original delivery.
|
|
567
|
+
*/
|
|
568
|
+
/** Bind provider delivery identity to one automation's durable dispatch. */
|
|
569
|
+
function eventAutomationDispatchKey(taskId, namespace, eventKey) {
|
|
570
|
+
return `event-automation:${createHash("sha256").update(`${taskId}\0${namespace}\0${eventKey}`).digest("hex").slice(0, 32)}`;
|
|
571
|
+
}
|
|
572
|
+
/** Render plain agent input for one matching event automation. */
|
|
573
|
+
function eventInput(task, event, outcomes, catalog) {
|
|
574
|
+
const guidance = eventGuidance(catalog, event.namespace, event.eventType);
|
|
575
|
+
return renderTaskInput({
|
|
576
|
+
about: task.trigger.label,
|
|
577
|
+
event: event.eventType,
|
|
578
|
+
source: event.namespace,
|
|
579
|
+
creator: slackMention(task.createdBy.slackUserId),
|
|
580
|
+
instructions: automationTaskText(task.task),
|
|
581
|
+
...task.task.kind === "skill" ? { skill: task.task.skill } : void 0,
|
|
582
|
+
outcomes,
|
|
583
|
+
guidance,
|
|
584
|
+
trustedSummary: event.trustedSummary,
|
|
585
|
+
trustedSummaryMaxLength: EVENT_SUMMARY_MAX_LENGTH,
|
|
586
|
+
verifiedDetails: event.data,
|
|
587
|
+
externalText: event.untrustedText,
|
|
588
|
+
externalTextMaxLength: EVENT_TEXT_MAX_LENGTH
|
|
589
|
+
});
|
|
590
|
+
}
|
|
591
|
+
/**
|
|
592
|
+
* Match a normalized event and dispatch every matching automation.
|
|
593
|
+
*
|
|
594
|
+
* Plugins publish one copy of an occurrence for each scope, such as a pull
|
|
595
|
+
* request and its repository. All copies share one event key. An automation
|
|
596
|
+
* with no identifier matches every copy, and the dispatch key and the run
|
|
597
|
+
* limit both use the event key, so it runs and counts once.
|
|
598
|
+
*/
|
|
599
|
+
async function ingestEventAutomations(input, options) {
|
|
600
|
+
const event = eventSchema.parse(input);
|
|
601
|
+
const db = getDb();
|
|
602
|
+
const nowMs = options.nowMs ?? Date.now();
|
|
603
|
+
const catalog = getEventCatalog();
|
|
604
|
+
const [matches = []] = await findMatchingEventAutomations(db, [event], options.teamId, catalog);
|
|
605
|
+
const tasks = matches.filter((task) => slackChannelMessageRunsAutomation(event, task));
|
|
606
|
+
let dispatched = 0;
|
|
607
|
+
const errors = [];
|
|
608
|
+
for (const task of tasks) try {
|
|
609
|
+
const skill = task.task.kind === "skill" ? task.task.skill : void 0;
|
|
610
|
+
if (skill && !await findAutomationSkill(skill)) {
|
|
611
|
+
const reason = missingAutomationSkillReason(skill);
|
|
612
|
+
if (await blockEventAutomation(db, task.id, reason)) await notifyAutomationBlocked({
|
|
613
|
+
automationId: task.id,
|
|
614
|
+
kind: "event",
|
|
615
|
+
reason
|
|
616
|
+
});
|
|
617
|
+
continue;
|
|
618
|
+
}
|
|
619
|
+
const idempotencyKey = eventAutomationDispatchKey(task.id, event.namespace, event.eventKey);
|
|
620
|
+
if (await admitEventAutomationRun({
|
|
621
|
+
automationId: task.id,
|
|
622
|
+
nowMs,
|
|
623
|
+
runKey: idempotencyKey
|
|
624
|
+
}) === "limited") {
|
|
625
|
+
const reason = eventAutomationRunLimitReason();
|
|
626
|
+
logWarn("event_automation.run_limit.exceeded", {
|
|
627
|
+
"app.task.id": task.id,
|
|
628
|
+
"app.task.type": "event"
|
|
629
|
+
});
|
|
630
|
+
if (await blockEventAutomation(db, task.id, reason)) {
|
|
631
|
+
captureMessage("Event automation blocked by run limit", {
|
|
632
|
+
level: "warning",
|
|
633
|
+
fingerprint: ["event_automation.run_limit.blocked"],
|
|
634
|
+
tags: {
|
|
635
|
+
"app.event.namespace": event.namespace,
|
|
636
|
+
"app.task.type": "event"
|
|
637
|
+
},
|
|
638
|
+
extra: {
|
|
639
|
+
"app.event.event_type": event.eventType,
|
|
640
|
+
"app.event_automation.max_runs": botConfig.maxEventAutomationRuns,
|
|
641
|
+
"app.event_automation.run_window_ms": botConfig.eventAutomationRunWindowMs,
|
|
642
|
+
"app.event_automation.resource_type": task.trigger.resourceType ?? "any",
|
|
643
|
+
"app.task.id": task.id
|
|
644
|
+
}
|
|
645
|
+
});
|
|
646
|
+
await notifyAutomationBlocked({
|
|
647
|
+
automationId: task.id,
|
|
648
|
+
kind: "event",
|
|
649
|
+
reason
|
|
650
|
+
});
|
|
651
|
+
}
|
|
652
|
+
continue;
|
|
653
|
+
}
|
|
654
|
+
const replyThreadTs = slackChannelMessageReplyThreadTs(event);
|
|
655
|
+
const destination = replyThreadTs ? {
|
|
656
|
+
...task.destination,
|
|
657
|
+
threadTs: replyThreadTs
|
|
658
|
+
} : task.destination;
|
|
659
|
+
const outcomes = effectiveTaskOutcomes(task.outcomes, destination);
|
|
660
|
+
const credentialSubject = task.credentialMode === "creator" ? {
|
|
661
|
+
type: "user",
|
|
662
|
+
userId: task.createdBy.slackUserId,
|
|
663
|
+
allowedWhen: "event-automation",
|
|
664
|
+
taskId: task.id
|
|
665
|
+
} : void 0;
|
|
666
|
+
const dispatch = await dispatchEventAutomation({
|
|
667
|
+
automationId: task.id,
|
|
668
|
+
conversationWorkQueue: options.queue,
|
|
669
|
+
nowMs,
|
|
670
|
+
options: {
|
|
671
|
+
idempotencyKey,
|
|
672
|
+
...credentialSubject ? { credentialSubject } : void 0,
|
|
673
|
+
destination,
|
|
674
|
+
destinationVisibility: task.destinationVisibility,
|
|
675
|
+
input: eventInput(task, event, outcomes, catalog),
|
|
676
|
+
...skill ? { skill } : void 0,
|
|
677
|
+
metadata: { eventAutomationId: task.id },
|
|
678
|
+
replyAttribution: automationReplyAttribution(task.title),
|
|
679
|
+
outcomes
|
|
680
|
+
}
|
|
681
|
+
});
|
|
682
|
+
await recordEventAutomationRunStarted(db, {
|
|
683
|
+
automation: task,
|
|
684
|
+
dispatchId: dispatch.id,
|
|
685
|
+
nowMs
|
|
686
|
+
});
|
|
687
|
+
if (dispatch.status === "created") dispatched += 1;
|
|
688
|
+
} catch (error) {
|
|
689
|
+
errors.push(error);
|
|
690
|
+
}
|
|
691
|
+
if (errors.length > 0) throw new AggregateError(errors, "Failed to dispatch one or more event automations");
|
|
692
|
+
return { dispatched };
|
|
693
|
+
}
|
|
694
|
+
// src/chat/events/workspace.ts
|
|
695
|
+
/**
|
|
696
|
+
* Resolve the single-bot Slack team id for event-automation indexing and
|
|
697
|
+
* Event people mentions.
|
|
698
|
+
*
|
|
699
|
+
* Watch matching does not use this. Event automations still key by
|
|
700
|
+
* destination team until that store is conversation-owned. Event delivery
|
|
701
|
+
* itself is not gated on Slack.
|
|
702
|
+
*/
|
|
703
|
+
function createEventTeamIdResolver() {
|
|
704
|
+
let pending;
|
|
705
|
+
return async () => {
|
|
706
|
+
if (!getSlackBotToken()) return void 0;
|
|
707
|
+
pending ??= getSlackClient().auth.test().then((result) => {
|
|
708
|
+
const teamId = result.team_id?.trim();
|
|
709
|
+
if (!teamId) throw new Error("Slack auth.test did not return a team id");
|
|
710
|
+
return teamId;
|
|
711
|
+
}).catch((error) => {
|
|
712
|
+
pending = void 0;
|
|
713
|
+
throw error;
|
|
714
|
+
});
|
|
715
|
+
return await pending;
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
// src/chat/events/app-publisher.ts
|
|
719
|
+
const WATCH_MATCH_CONCURRENCY = 4;
|
|
720
|
+
/** Build the core event publisher used by plugin routes. */
|
|
721
|
+
function createEventAppPublisher(args) {
|
|
722
|
+
const resolveEventAutomationTeamId = createEventTeamIdResolver();
|
|
723
|
+
return {
|
|
724
|
+
async hasMatch(events) {
|
|
725
|
+
const work = args.conversationWork();
|
|
726
|
+
const eventAutomationTeamId = await resolveEventAutomationTeamId();
|
|
727
|
+
const limit = pLimit(WATCH_MATCH_CONCURRENCY);
|
|
728
|
+
const [subscriptions, tasks] = await Promise.all([Promise.all(events.map((event) => limit(() => findMatchingWatches({
|
|
729
|
+
data: event.data,
|
|
730
|
+
eventType: event.eventType,
|
|
731
|
+
namespace: event.namespace,
|
|
732
|
+
identifier: event.identifier,
|
|
733
|
+
state: work.state
|
|
734
|
+
})))), eventAutomationTeamId ? findMatchingEventAutomations(getDb(), events, eventAutomationTeamId, getEventCatalog()) : Promise.resolve([])]);
|
|
735
|
+
return [...subscriptions, ...tasks].some((matched) => matched.length > 0);
|
|
736
|
+
},
|
|
737
|
+
async neededMatchKeys(input) {
|
|
738
|
+
const work = args.conversationWork();
|
|
739
|
+
const eventAutomationTeamId = await resolveEventAutomationTeamId();
|
|
740
|
+
const [watchKeys, taskKeys] = await Promise.all([collectEventMatchKeys({
|
|
741
|
+
eventTypes: input.eventTypes,
|
|
742
|
+
identifiers: input.identifiers,
|
|
743
|
+
namespace: input.namespace,
|
|
744
|
+
state: work.state
|
|
745
|
+
}), eventAutomationTeamId ? collectEventAutomationMatchKeys(getDb(), {
|
|
746
|
+
catalog: getEventCatalog(),
|
|
747
|
+
...input.data ? { data: input.data } : void 0,
|
|
748
|
+
eventTypes: input.eventTypes,
|
|
749
|
+
identifiers: input.identifiers,
|
|
750
|
+
namespace: input.namespace,
|
|
751
|
+
teamId: eventAutomationTeamId
|
|
752
|
+
}) : Promise.resolve([])]);
|
|
753
|
+
return [.../* @__PURE__ */ new Set([...watchKeys, ...taskKeys])].sort();
|
|
754
|
+
},
|
|
755
|
+
async publish(event) {
|
|
756
|
+
const work = args.conversationWork();
|
|
757
|
+
const queue = work.queue ?? getVercelConversationWorkQueue();
|
|
758
|
+
const eventAutomationTeamId = await resolveEventAutomationTeamId();
|
|
759
|
+
await Promise.all([ingestEvent(event, {
|
|
760
|
+
queue,
|
|
761
|
+
slackTeamId: eventAutomationTeamId,
|
|
762
|
+
state: work.state
|
|
763
|
+
}), eventAutomationTeamId ? ingestEventAutomations(event, {
|
|
764
|
+
queue,
|
|
765
|
+
teamId: eventAutomationTeamId
|
|
766
|
+
}) : Promise.resolve()]);
|
|
767
|
+
}
|
|
768
|
+
};
|
|
769
|
+
}
|
|
770
|
+
// src/chat/task-execution/heartbeat.ts
|
|
771
|
+
const DEFAULT_RECOVERY_LIMIT = 25;
|
|
772
|
+
function heartbeatIdempotencyKey(reason, conversationId, nowMs) {
|
|
773
|
+
return `heartbeat:${reason}:${conversationId}:${nowMs}`;
|
|
774
|
+
}
|
|
775
|
+
/** Requeue expired leases and stranded mailbox work without running the agent. */
|
|
776
|
+
async function recoverConversationWork(args) {
|
|
777
|
+
if (!getChatConfig().conversationWorkEnabled) {
|
|
778
|
+
logWarn("conversation.work.recovery.disabled");
|
|
779
|
+
return {
|
|
780
|
+
expiredLeaseCount: 0,
|
|
781
|
+
pendingCount: 0
|
|
782
|
+
};
|
|
783
|
+
}
|
|
784
|
+
const result = {
|
|
785
|
+
expiredLeaseCount: 0,
|
|
786
|
+
pendingCount: 0
|
|
787
|
+
};
|
|
788
|
+
const staleBeforeMs = args.nowMs - CONVERSATION_WORK_STALE_ENQUEUE_MS;
|
|
789
|
+
const ids = await listActiveConversationIds({
|
|
790
|
+
limit: args.limit ?? DEFAULT_RECOVERY_LIMIT,
|
|
791
|
+
staleBeforeMs,
|
|
792
|
+
state: args.state
|
|
793
|
+
});
|
|
794
|
+
for (const conversationId of ids) await withLogContext({ conversationId }, async () => {
|
|
795
|
+
let work;
|
|
796
|
+
try {
|
|
797
|
+
work = await getConversationWorkState({
|
|
798
|
+
conversationId,
|
|
799
|
+
state: args.state
|
|
800
|
+
});
|
|
801
|
+
} catch (error) {
|
|
802
|
+
logException(error, "conversation.work.recovery.failed");
|
|
803
|
+
if (isInvalidConversationRecordError(error)) await pruneActiveConversation({
|
|
804
|
+
conversationId,
|
|
805
|
+
state: args.state
|
|
806
|
+
});
|
|
807
|
+
return;
|
|
808
|
+
}
|
|
809
|
+
try {
|
|
810
|
+
if (!work || !hasRunnableConversationWork(work)) {
|
|
811
|
+
await pruneActiveConversation({
|
|
812
|
+
conversationId,
|
|
813
|
+
state: args.state
|
|
814
|
+
});
|
|
815
|
+
return;
|
|
816
|
+
}
|
|
817
|
+
if (work.execution.lease && work.execution.lease.expiresAtMs <= args.nowMs) {
|
|
818
|
+
const recovery = await clearExpiredConversationLease({
|
|
819
|
+
beforeWorkStops: args.beforeWorkStops,
|
|
820
|
+
conversationId,
|
|
821
|
+
nowMs: args.nowMs,
|
|
822
|
+
state: args.state
|
|
823
|
+
});
|
|
824
|
+
if (recovery === "not_expired") return;
|
|
825
|
+
if (recovery === "stopped") {
|
|
826
|
+
logException(/* @__PURE__ */ new Error("Conversation work stopped after repeated failed attempts"), "conversation.work.retry.exhausted", {
|
|
827
|
+
"app.run.id": work.execution.runId ?? "unknown",
|
|
828
|
+
"app.worker.last_progress_at_ms": work.execution.lastProgressAtMs ?? work.createdAtMs,
|
|
829
|
+
"app.worker.retry_count": (work.execution.retryCount ?? 0) + 1
|
|
830
|
+
});
|
|
831
|
+
return;
|
|
832
|
+
}
|
|
833
|
+
if ((await ensureConversationWake({
|
|
834
|
+
conversationId,
|
|
835
|
+
idempotencyKey: heartbeatIdempotencyKey("lease", conversationId, args.nowMs),
|
|
836
|
+
nowMs: args.nowMs,
|
|
837
|
+
queue: args.queue,
|
|
838
|
+
replaceExistingWake: true,
|
|
839
|
+
state: args.state
|
|
840
|
+
})).status === "enqueued") {
|
|
841
|
+
result.expiredLeaseCount += 1;
|
|
842
|
+
logInfo("conversation.work.lease_expired.requeued");
|
|
843
|
+
}
|
|
844
|
+
return;
|
|
845
|
+
}
|
|
846
|
+
if (work.execution.lease) return;
|
|
847
|
+
if ((await ensureConversationWake({
|
|
848
|
+
conversationId,
|
|
849
|
+
idempotencyKey: heartbeatIdempotencyKey("pending", conversationId, args.nowMs),
|
|
850
|
+
nowMs: args.nowMs,
|
|
851
|
+
queue: args.queue,
|
|
852
|
+
state: args.state
|
|
853
|
+
})).status === "enqueued") {
|
|
854
|
+
result.pendingCount += 1;
|
|
855
|
+
logInfo("conversation.work.pending.requeued");
|
|
856
|
+
}
|
|
857
|
+
} catch (error) {
|
|
858
|
+
logException(error, "conversation.work.recovery.failed");
|
|
859
|
+
}
|
|
860
|
+
});
|
|
861
|
+
return result;
|
|
660
862
|
}
|
|
661
863
|
// src/chat/scheduled-automations/runs.ts
|
|
662
864
|
const PENDING_CLAIM_STALE_MS = 6e4;
|
|
@@ -751,7 +953,8 @@ function taskDedupeFingerprint(task) {
|
|
|
751
953
|
} : null,
|
|
752
954
|
timezone: task.schedule.timezone
|
|
753
955
|
},
|
|
754
|
-
task: normalizedText(task.task
|
|
956
|
+
task: normalizedText(automationTaskText(task.task)),
|
|
957
|
+
skill: task.task.kind === "skill" ? task.task.skill : null
|
|
755
958
|
});
|
|
756
959
|
}
|
|
757
960
|
async function findStaleRecoveryCanonicalTask(db, task) {
|
|
@@ -992,12 +1195,12 @@ function singleLineMetadataValue(value) {
|
|
|
992
1195
|
function buildDispatchInput(task) {
|
|
993
1196
|
return renderTaskInput({
|
|
994
1197
|
creator: slackMention(task.createdBy.slackUserId),
|
|
995
|
-
instructions: task.task
|
|
1198
|
+
instructions: automationTaskText(task.task),
|
|
1199
|
+
...task.task.kind === "skill" ? { skill: task.task.skill } : void 0,
|
|
996
1200
|
outcomes: effectiveTaskOutcomes(task.outcomes, task.destination)
|
|
997
1201
|
});
|
|
998
1202
|
}
|
|
999
1203
|
function buildDispatchMetadata(args) {
|
|
1000
|
-
if (!args.task.task.text?.trim()) throw new Error("Scheduled automation text is required");
|
|
1001
1204
|
return {
|
|
1002
1205
|
runId: args.run.id,
|
|
1003
1206
|
schedule: singleLineMetadataValue(args.task.schedule.description),
|
|
@@ -1194,17 +1397,11 @@ async function runScheduledAutomationHeartbeat(args) {
|
|
|
1194
1397
|
if (skipped) logScheduledAutomationRunSkipped(task, skipped, { "app.task.run.error": skippedReason });
|
|
1195
1398
|
continue;
|
|
1196
1399
|
}
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
metadata = buildDispatchMetadata({
|
|
1200
|
-
nowMs: args.nowMs,
|
|
1201
|
-
run,
|
|
1202
|
-
task
|
|
1203
|
-
});
|
|
1204
|
-
} catch (error) {
|
|
1400
|
+
const skill = task.task.kind === "skill" ? task.task.skill : void 0;
|
|
1401
|
+
if (skill && !await findAutomationSkill(skill)) {
|
|
1205
1402
|
await finishClaimedRun({
|
|
1206
1403
|
db,
|
|
1207
|
-
errorMessage:
|
|
1404
|
+
errorMessage: missingAutomationSkillReason(skill),
|
|
1208
1405
|
nowMs: args.nowMs,
|
|
1209
1406
|
run,
|
|
1210
1407
|
status: "blocked"
|
|
@@ -1228,7 +1425,12 @@ async function runScheduledAutomationHeartbeat(args) {
|
|
|
1228
1425
|
destination: task.destination,
|
|
1229
1426
|
destinationVisibility: task.conversationAccess.visibility,
|
|
1230
1427
|
input: buildDispatchInput(task),
|
|
1231
|
-
|
|
1428
|
+
...skill ? { skill } : void 0,
|
|
1429
|
+
metadata: buildDispatchMetadata({
|
|
1430
|
+
nowMs: args.nowMs,
|
|
1431
|
+
run,
|
|
1432
|
+
task
|
|
1433
|
+
}),
|
|
1232
1434
|
replyAttribution: automationReplyAttribution(task.title),
|
|
1233
1435
|
outcomes: effectiveTaskOutcomes(task.outcomes, task.destination)
|
|
1234
1436
|
}
|
|
@@ -1287,6 +1489,7 @@ async function runPluginHeartbeats(args) {
|
|
|
1287
1489
|
try {
|
|
1288
1490
|
const result = await runWithTimeout(Promise.resolve(heartbeat(createHeartbeatContext({
|
|
1289
1491
|
conversationWorkQueue: args.conversationWorkQueue,
|
|
1492
|
+
events: createPluginEventPublisher(plugin, args.events),
|
|
1290
1493
|
plugin,
|
|
1291
1494
|
nowMs: args.nowMs
|
|
1292
1495
|
}))), PLUGIN_HEARTBEAT_TIMEOUT_MS);
|
|
@@ -1354,6 +1557,7 @@ async function recoverPendingAgentInvocationResults(args) {
|
|
|
1354
1557
|
/** Run the core heartbeat phases. */
|
|
1355
1558
|
async function runHeartbeat(args) {
|
|
1356
1559
|
const queue = args.conversationWorkQueue ?? getVercelConversationWorkQueue();
|
|
1560
|
+
const events = args.events ?? createEventAppPublisher({ conversationWork: () => ({ queue }) });
|
|
1357
1561
|
await recoverConversationWork({
|
|
1358
1562
|
beforeWorkStops: endAgentInvocationsOfStoppedWork,
|
|
1359
1563
|
nowMs: args.nowMs,
|
|
@@ -1390,6 +1594,7 @@ async function runHeartbeat(args) {
|
|
|
1390
1594
|
}
|
|
1391
1595
|
await runPluginHeartbeats({
|
|
1392
1596
|
conversationWorkQueue: queue,
|
|
1597
|
+
events,
|
|
1393
1598
|
nowMs: args.nowMs
|
|
1394
1599
|
});
|
|
1395
1600
|
try {
|
|
@@ -1419,6 +1624,7 @@ async function GET$3(request, waitUntil, options = {}) {
|
|
|
1419
1624
|
const nowMs = Date.now();
|
|
1420
1625
|
waitUntil(() => runHeartbeat({
|
|
1421
1626
|
conversationWorkQueue: options.conversationWorkQueue,
|
|
1627
|
+
events: options.events,
|
|
1422
1628
|
nowMs
|
|
1423
1629
|
}).catch((error) => {
|
|
1424
1630
|
logException(error, "heartbeat.failed", { "app.heartbeat.now_ms": nowMs });
|
|
@@ -2759,127 +2965,6 @@ function textMentionsBot(text, botUserId) {
|
|
|
2759
2965
|
const id = escapeRegExp(botUserId);
|
|
2760
2966
|
return new RegExp(`<@${id}(?:\\|[^>]+)?>`).test(outside);
|
|
2761
2967
|
}
|
|
2762
|
-
// src/chat/event-automations/ingest.ts
|
|
2763
|
-
/**
|
|
2764
|
-
* Owns event matching and durable event-automation dispatch.
|
|
2765
|
-
*
|
|
2766
|
-
* Each matching automation is independently idempotent. Aggregate failures propagate
|
|
2767
|
-
* so the provider can retry the original delivery.
|
|
2768
|
-
*/
|
|
2769
|
-
/** Bind provider delivery identity to one automation's durable dispatch. */
|
|
2770
|
-
function eventAutomationDispatchKey(taskId, namespace, eventKey) {
|
|
2771
|
-
return `event-automation:${createHash("sha256").update(`${taskId}\0${namespace}\0${eventKey}`).digest("hex").slice(0, 32)}`;
|
|
2772
|
-
}
|
|
2773
|
-
/** Render plain agent input for one matching event automation. */
|
|
2774
|
-
function eventInput(task, event, outcomes, catalog) {
|
|
2775
|
-
const guidance = eventGuidance(catalog, event.namespace, event.eventType);
|
|
2776
|
-
return renderTaskInput({
|
|
2777
|
-
about: task.trigger.label,
|
|
2778
|
-
event: event.eventType,
|
|
2779
|
-
source: event.namespace,
|
|
2780
|
-
creator: slackMention(task.createdBy.slackUserId),
|
|
2781
|
-
instructions: task.task.text,
|
|
2782
|
-
outcomes,
|
|
2783
|
-
guidance,
|
|
2784
|
-
trustedSummary: event.trustedSummary,
|
|
2785
|
-
trustedSummaryMaxLength: EVENT_SUMMARY_MAX_LENGTH,
|
|
2786
|
-
verifiedDetails: event.data,
|
|
2787
|
-
externalText: event.untrustedText,
|
|
2788
|
-
externalTextMaxLength: EVENT_TEXT_MAX_LENGTH
|
|
2789
|
-
});
|
|
2790
|
-
}
|
|
2791
|
-
/**
|
|
2792
|
-
* Match a normalized event and dispatch every matching automation.
|
|
2793
|
-
*
|
|
2794
|
-
* Plugins publish one copy of an occurrence for each scope, such as a pull
|
|
2795
|
-
* request and its repository. All copies share one event key. An automation
|
|
2796
|
-
* with no identifier matches every copy, and the dispatch key and the run
|
|
2797
|
-
* limit both use the event key, so it runs and counts once.
|
|
2798
|
-
*/
|
|
2799
|
-
async function ingestEventAutomations(input, options) {
|
|
2800
|
-
const event = eventSchema.parse(input);
|
|
2801
|
-
const db = getDb();
|
|
2802
|
-
const nowMs = options.nowMs ?? Date.now();
|
|
2803
|
-
const catalog = getEventCatalog();
|
|
2804
|
-
const [matches = []] = await findMatchingEventAutomations(db, [event], options.teamId, catalog);
|
|
2805
|
-
const tasks = matches.filter((task) => slackChannelMessageRunsAutomation(event, task));
|
|
2806
|
-
let dispatched = 0;
|
|
2807
|
-
const errors = [];
|
|
2808
|
-
for (const task of tasks) try {
|
|
2809
|
-
const idempotencyKey = eventAutomationDispatchKey(task.id, event.namespace, event.eventKey);
|
|
2810
|
-
if (await admitEventAutomationRun({
|
|
2811
|
-
automationId: task.id,
|
|
2812
|
-
nowMs,
|
|
2813
|
-
runKey: idempotencyKey
|
|
2814
|
-
}) === "limited") {
|
|
2815
|
-
const reason = eventAutomationRunLimitReason();
|
|
2816
|
-
logWarn("event_automation.run_limit.exceeded", {
|
|
2817
|
-
"app.task.id": task.id,
|
|
2818
|
-
"app.task.type": "event"
|
|
2819
|
-
});
|
|
2820
|
-
if (await blockEventAutomation(db, task.id, reason)) {
|
|
2821
|
-
captureMessage("Event automation blocked by run limit", {
|
|
2822
|
-
level: "warning",
|
|
2823
|
-
fingerprint: ["event_automation.run_limit.blocked"],
|
|
2824
|
-
tags: {
|
|
2825
|
-
"app.event.namespace": event.namespace,
|
|
2826
|
-
"app.task.type": "event"
|
|
2827
|
-
},
|
|
2828
|
-
extra: {
|
|
2829
|
-
"app.event.event_type": event.eventType,
|
|
2830
|
-
"app.event_automation.max_runs": botConfig.maxEventAutomationRuns,
|
|
2831
|
-
"app.event_automation.run_window_ms": botConfig.eventAutomationRunWindowMs,
|
|
2832
|
-
"app.event_automation.resource_type": task.trigger.resourceType ?? "any",
|
|
2833
|
-
"app.task.id": task.id
|
|
2834
|
-
}
|
|
2835
|
-
});
|
|
2836
|
-
await notifyAutomationBlocked({
|
|
2837
|
-
automationId: task.id,
|
|
2838
|
-
kind: "event",
|
|
2839
|
-
reason
|
|
2840
|
-
});
|
|
2841
|
-
}
|
|
2842
|
-
continue;
|
|
2843
|
-
}
|
|
2844
|
-
const replyThreadTs = slackChannelMessageReplyThreadTs(event);
|
|
2845
|
-
const destination = replyThreadTs ? {
|
|
2846
|
-
...task.destination,
|
|
2847
|
-
threadTs: replyThreadTs
|
|
2848
|
-
} : task.destination;
|
|
2849
|
-
const outcomes = effectiveTaskOutcomes(task.outcomes, destination);
|
|
2850
|
-
const credentialSubject = task.credentialMode === "creator" ? {
|
|
2851
|
-
type: "user",
|
|
2852
|
-
userId: task.createdBy.slackUserId,
|
|
2853
|
-
allowedWhen: "event-automation",
|
|
2854
|
-
taskId: task.id
|
|
2855
|
-
} : void 0;
|
|
2856
|
-
const dispatch = await dispatchEventAutomation({
|
|
2857
|
-
automationId: task.id,
|
|
2858
|
-
conversationWorkQueue: options.queue,
|
|
2859
|
-
nowMs,
|
|
2860
|
-
options: {
|
|
2861
|
-
idempotencyKey,
|
|
2862
|
-
...credentialSubject ? { credentialSubject } : void 0,
|
|
2863
|
-
destination,
|
|
2864
|
-
destinationVisibility: task.destinationVisibility,
|
|
2865
|
-
input: eventInput(task, event, outcomes, catalog),
|
|
2866
|
-
metadata: { eventAutomationId: task.id },
|
|
2867
|
-
replyAttribution: automationReplyAttribution(task.title),
|
|
2868
|
-
outcomes
|
|
2869
|
-
}
|
|
2870
|
-
});
|
|
2871
|
-
await recordEventAutomationRunStarted(db, {
|
|
2872
|
-
automation: task,
|
|
2873
|
-
dispatchId: dispatch.id,
|
|
2874
|
-
nowMs
|
|
2875
|
-
});
|
|
2876
|
-
if (dispatch.status === "created") dispatched += 1;
|
|
2877
|
-
} catch (error) {
|
|
2878
|
-
errors.push(error);
|
|
2879
|
-
}
|
|
2880
|
-
if (errors.length > 0) throw new AggregateError(errors, "Failed to dispatch one or more event automations");
|
|
2881
|
-
return { dispatched };
|
|
2882
|
-
}
|
|
2883
2968
|
// src/chat/ingress/slack-allowed-domain.ts
|
|
2884
2969
|
const ALLOWED_TTL_MS = 3e5;
|
|
2885
2970
|
const NOT_ALLOWED_TTL_MS = 3e4;
|
|
@@ -2964,11 +3049,15 @@ function dateField(key, label, value, empty) {
|
|
|
2964
3049
|
function renderAutomationDetails(automation) {
|
|
2965
3050
|
const url = getDashboardTaskLink(automation.id);
|
|
2966
3051
|
if (!url) return void 0;
|
|
2967
|
-
const fields = [textField("status", "Status", automation.kind === "scheduled" ? automation.status : automation.trigger.problems.length === 0 ? "ready" : "unavailable")
|
|
2968
|
-
|
|
3052
|
+
const fields = [textField("status", "Status", automation.kind === "scheduled" ? automation.status : automation.trigger.problems.length === 0 ? "ready" : "unavailable")];
|
|
3053
|
+
const { task } = automation;
|
|
3054
|
+
if (task.kind === "skill") fields.push(textField("skill", "Skill", task.skill));
|
|
3055
|
+
const text = automationTaskText(task);
|
|
3056
|
+
if (text) fields.push({
|
|
3057
|
+
...textField("description", task.kind === "skill" ? "Context" : "Instruction", text),
|
|
2969
3058
|
format: "markdown",
|
|
2970
3059
|
long: true
|
|
2971
|
-
}
|
|
3060
|
+
});
|
|
2972
3061
|
if (automation.kind === "scheduled") fields.push({
|
|
2973
3062
|
...textField("trigger", "Schedule", automation.schedule),
|
|
2974
3063
|
long: true
|
|
@@ -3798,82 +3887,6 @@ async function publicArtifactGET(args) {
|
|
|
3798
3887
|
return new Response("Internal Server Error", { status: 500 });
|
|
3799
3888
|
}
|
|
3800
3889
|
}
|
|
3801
|
-
// src/chat/events/workspace.ts
|
|
3802
|
-
/**
|
|
3803
|
-
* Resolve the single-bot Slack team id for event-automation indexing and
|
|
3804
|
-
* Event people mentions.
|
|
3805
|
-
*
|
|
3806
|
-
* Watch matching does not use this. Event automations still key by
|
|
3807
|
-
* destination team until that store is conversation-owned. Event delivery
|
|
3808
|
-
* itself is not gated on Slack.
|
|
3809
|
-
*/
|
|
3810
|
-
function createEventTeamIdResolver() {
|
|
3811
|
-
let pending;
|
|
3812
|
-
return async () => {
|
|
3813
|
-
if (!getSlackBotToken()) return void 0;
|
|
3814
|
-
pending ??= getSlackClient().auth.test().then((result) => {
|
|
3815
|
-
const teamId = result.team_id?.trim();
|
|
3816
|
-
if (!teamId) throw new Error("Slack auth.test did not return a team id");
|
|
3817
|
-
return teamId;
|
|
3818
|
-
}).catch((error) => {
|
|
3819
|
-
pending = void 0;
|
|
3820
|
-
throw error;
|
|
3821
|
-
});
|
|
3822
|
-
return await pending;
|
|
3823
|
-
};
|
|
3824
|
-
}
|
|
3825
|
-
// src/chat/events/app-publisher.ts
|
|
3826
|
-
const WATCH_MATCH_CONCURRENCY = 4;
|
|
3827
|
-
/** Build the core event publisher used by plugin routes. */
|
|
3828
|
-
function createEventAppPublisher(args) {
|
|
3829
|
-
const resolveEventAutomationTeamId = createEventTeamIdResolver();
|
|
3830
|
-
return {
|
|
3831
|
-
async hasMatch(events) {
|
|
3832
|
-
const work = args.conversationWork();
|
|
3833
|
-
const eventAutomationTeamId = await resolveEventAutomationTeamId();
|
|
3834
|
-
const limit = pLimit(WATCH_MATCH_CONCURRENCY);
|
|
3835
|
-
const [subscriptions, tasks] = await Promise.all([Promise.all(events.map((event) => limit(() => findMatchingWatches({
|
|
3836
|
-
data: event.data,
|
|
3837
|
-
eventType: event.eventType,
|
|
3838
|
-
namespace: event.namespace,
|
|
3839
|
-
identifier: event.identifier,
|
|
3840
|
-
state: work.state
|
|
3841
|
-
})))), eventAutomationTeamId ? findMatchingEventAutomations(getDb(), events, eventAutomationTeamId, getEventCatalog()) : Promise.resolve([])]);
|
|
3842
|
-
return [...subscriptions, ...tasks].some((matched) => matched.length > 0);
|
|
3843
|
-
},
|
|
3844
|
-
async neededMatchKeys(input) {
|
|
3845
|
-
const work = args.conversationWork();
|
|
3846
|
-
const eventAutomationTeamId = await resolveEventAutomationTeamId();
|
|
3847
|
-
const [watchKeys, taskKeys] = await Promise.all([collectEventMatchKeys({
|
|
3848
|
-
eventTypes: input.eventTypes,
|
|
3849
|
-
identifiers: input.identifiers,
|
|
3850
|
-
namespace: input.namespace,
|
|
3851
|
-
state: work.state
|
|
3852
|
-
}), eventAutomationTeamId ? collectEventAutomationMatchKeys(getDb(), {
|
|
3853
|
-
catalog: getEventCatalog(),
|
|
3854
|
-
...input.data ? { data: input.data } : void 0,
|
|
3855
|
-
eventTypes: input.eventTypes,
|
|
3856
|
-
identifiers: input.identifiers,
|
|
3857
|
-
namespace: input.namespace,
|
|
3858
|
-
teamId: eventAutomationTeamId
|
|
3859
|
-
}) : Promise.resolve([])]);
|
|
3860
|
-
return [.../* @__PURE__ */ new Set([...watchKeys, ...taskKeys])].sort();
|
|
3861
|
-
},
|
|
3862
|
-
async publish(event) {
|
|
3863
|
-
const work = args.conversationWork();
|
|
3864
|
-
const queue = work.queue ?? getVercelConversationWorkQueue();
|
|
3865
|
-
const eventAutomationTeamId = await resolveEventAutomationTeamId();
|
|
3866
|
-
await Promise.all([ingestEvent(event, {
|
|
3867
|
-
queue,
|
|
3868
|
-
slackTeamId: eventAutomationTeamId,
|
|
3869
|
-
state: work.state
|
|
3870
|
-
}), eventAutomationTeamId ? ingestEventAutomations(event, {
|
|
3871
|
-
queue,
|
|
3872
|
-
teamId: eventAutomationTeamId
|
|
3873
|
-
}) : Promise.resolve()]);
|
|
3874
|
-
}
|
|
3875
|
-
};
|
|
3876
|
-
}
|
|
3877
3890
|
// src/api/acp/conversations.ts
|
|
3878
3891
|
const EVENT_PAGE_SIZE = 50;
|
|
3879
3892
|
async function hasConversationAccess(conversationId, user) {
|
|
@@ -6827,7 +6840,7 @@ const mcpAutomationSchema = z.object({
|
|
|
6827
6840
|
id: z.string(),
|
|
6828
6841
|
kind: z.enum(["scheduled", "event"]),
|
|
6829
6842
|
title: z.string(),
|
|
6830
|
-
|
|
6843
|
+
task: automationTaskSchema,
|
|
6831
6844
|
status: z.enum([
|
|
6832
6845
|
"active",
|
|
6833
6846
|
"blocked",
|
|
@@ -6861,7 +6874,7 @@ function mcpAutomation(automation) {
|
|
|
6861
6874
|
id: automation.id,
|
|
6862
6875
|
kind: automation.kind,
|
|
6863
6876
|
title: automation.title,
|
|
6864
|
-
|
|
6877
|
+
task: automation.task,
|
|
6865
6878
|
status: automation.status,
|
|
6866
6879
|
...automation.statusReason ? { statusReason: automation.statusReason } : void 0,
|
|
6867
6880
|
trigger: triggerText(automation),
|
|
@@ -7099,15 +7112,16 @@ function registerSearchAutomationsTool(server, { user }) {
|
|
|
7099
7112
|
const listQuery = automationListQuerySchema.shape;
|
|
7100
7113
|
server.registerTool("searchAutomations", {
|
|
7101
7114
|
title: "Search automations",
|
|
7102
|
-
description: "Search the automations that you can see, newest first. An automation is a saved instruction that runs on a schedule or on events.",
|
|
7115
|
+
description: "Search the automations that you can see, newest first. An automation is a saved instruction or skill that runs on a schedule or on events.",
|
|
7103
7116
|
inputSchema: {
|
|
7104
|
-
q: listQuery.q.describe("Text to search for in titles and
|
|
7117
|
+
q: listQuery.q.describe("Text to search for in titles, instructions, and skill names."),
|
|
7105
7118
|
scope: z.enum([
|
|
7106
7119
|
"all",
|
|
7107
7120
|
"mine",
|
|
7108
7121
|
"attention"
|
|
7109
7122
|
]).default("all").describe("`mine` lists the ones you created. `attention` lists the ones that are blocked, cannot run, or had a problem in their last run."),
|
|
7110
7123
|
state: listQuery.state.describe("Filter by state."),
|
|
7124
|
+
skill: listQuery.skill.describe("Only automations that run this skill, by exact name."),
|
|
7111
7125
|
page: listQuery.page.describe("Page number, from 1.")
|
|
7112
7126
|
},
|
|
7113
7127
|
outputSchema: {
|
|
@@ -7120,11 +7134,12 @@ function registerSearchAutomationsTool(server, { user }) {
|
|
|
7120
7134
|
openWorldHint: false,
|
|
7121
7135
|
readOnlyHint: true
|
|
7122
7136
|
}
|
|
7123
|
-
}, async ({ page, q, scope, state }) => {
|
|
7137
|
+
}, async ({ page, q, scope, skill, state }) => {
|
|
7124
7138
|
const list = await readViewerAutomations(user, automationListQuerySchema.parse({
|
|
7125
7139
|
page,
|
|
7126
7140
|
q,
|
|
7127
7141
|
scope,
|
|
7142
|
+
skill,
|
|
7128
7143
|
state
|
|
7129
7144
|
}));
|
|
7130
7145
|
return mcpToolResult({
|
|
@@ -7997,6 +8012,7 @@ function dashboardHostRoutePaths(dashboard, authenticatedRoutes = []) {
|
|
|
7997
8012
|
"/api/notifications",
|
|
7998
8013
|
"/api/notifications/*",
|
|
7999
8014
|
"/api/stats",
|
|
8015
|
+
"/api/reply-times",
|
|
8000
8016
|
"/api/versions",
|
|
8001
8017
|
"/api/conversations",
|
|
8002
8018
|
"/api/conversations/*",
|
|
@@ -8451,7 +8467,10 @@ async function createApp(options) {
|
|
|
8451
8467
|
return backgroundCompactionPOST(c.req.raw);
|
|
8452
8468
|
});
|
|
8453
8469
|
app.get("/api/internal/heartbeat", (c) => {
|
|
8454
|
-
return GET$3(c.req.raw, waitUntil, {
|
|
8470
|
+
return GET$3(c.req.raw, waitUntil, {
|
|
8471
|
+
conversationWorkQueue,
|
|
8472
|
+
events
|
|
8473
|
+
});
|
|
8455
8474
|
});
|
|
8456
8475
|
app.get("/api/internal/retention", (c) => {
|
|
8457
8476
|
return GET$2(c.req.raw);
|