@sentry/junior 0.304.0 → 0.306.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-context-B1IpoELr.js → adapter-context-CnY-i32r.js} +2 -2
- package/dist/{admin-BnVFGo_z.js → admin-BLLdLnXh.js} +2 -2
- package/dist/{agent-runner-CoEeZSRh.js → agent-runner-BaLjEjPR.js} +312 -204
- package/dist/api/schema.d.ts +2 -2
- package/dist/api/schema.js +7 -8
- package/dist/api.d.ts +19 -4
- package/dist/api.js +137 -40
- package/dist/{app-Cs157Zc5.d.ts → app-DvYbM9UD.d.ts} +2 -2
- package/dist/app.d.ts +1 -1
- package/dist/app.js +489 -445
- package/dist/{background-compaction-queue-WLPNSF_b.js → background-compaction-queue-D2wzxtGU.js} +7 -3
- package/dist/{briefs-CagVVefw.js → briefs-DvyzXfrF.js} +3 -3
- package/dist/{catalog-runtime-B8ZXvXWm.js → catalog-runtime-B1R-nHd3.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 +5 -5
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +3 -3
- package/dist/{config-DdO1BNcw.js → config-DUD-zMvp.js} +111 -13
- package/dist/{connections-D20kp0j5.js → connections-CDhsqPcC.js} +6 -6
- package/dist/{continue-in-slack-BKEVMBj1.js → continue-in-slack-BXQizz9o.js} +5 -5
- package/dist/{conversation-BOqdRtUx.js → conversation--f85g4zL.js} +132 -132
- package/dist/{conversation-feed-CgpgP7yi.js → conversation-feed-BNs9KiqC.js} +1 -1
- package/dist/{conversation-privacy-L1SK_v0V.js → conversation-privacy-YE54gMN8.js} +1 -1
- package/dist/{conversation-turn-BptVJylj.js → conversation-turn-BzdmrHb0.js} +22 -40
- package/dist/{credential-sync-D1J1CGzL.js → credential-sync-Cdm-e1vJ.js} +14 -13
- package/dist/{db-EKJnkrIb.js → db-DV2ZUb1Y.js} +90 -11
- package/dist/{db-zbN5ZV_o.d.ts → db-pH357Dkt.d.ts} +1 -1
- package/dist/{executor-CoIZmFK8.js → executor-CjNhwwnj.js} +47 -4
- package/dist/{history-m2-ceTTX.js → history-N7IVbUom.js} +5 -1
- package/dist/{install-BT2Pf6HP.js → install-DbD7C5td.js} +2 -2
- package/dist/instrumentation.js +2 -2
- package/dist/{lineage-C5DGQCS_.js → lineage-BFdIPb3o.js} +2 -2
- package/dist/{logging-QSZuMcvo.js → logging-oYpJYr-S.js} +1 -1
- package/dist/{message-TtxftRHj.js → message-BBPcMKJY.js} +8 -8
- package/dist/{model-input-BHXfA29g.js → model-input-DYYF3a8B.js} +3 -3
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +4 -4
- package/dist/{oauth-callback-server-B0enqHtZ.js → oauth-callback-server-C7Q987su.js} +2 -2
- package/dist/{projection-CNKK7doO.js → projection-CWXDE0f6.js} +7740 -6165
- package/dist/{prompt-DSjhoKu5.js → prompt-P3eRqO8C.js} +15 -7
- package/dist/{queue-CDxkit82.js → queue-7FSijgqG.js} +4 -4
- package/dist/{registry-DBDNUUmz.js → registry-1pzXmplY.js} +1 -1
- package/dist/{resolve-CQLhMWSu.js → resolve-n87oXY-d.js} +3 -3
- package/dist/{result-B-pauj42.js → result-BmF9v9bv.js} +9 -9
- package/dist/{runner-B3KxKks5.js → runner-4j7ZsxP5.js} +13 -15
- package/dist/{sandbox-egress-signals-DJJX9ClG.js → sandbox-egress-signals-BRQI8HvT.js} +1 -1
- package/dist/{automation-CuA3yEcD.js → schedule-CHPWQn-x.js} +347 -5
- package/dist/{schema-CKcu-IK6.d.ts → schema-CVbIjrF3.d.ts} +71 -1
- package/dist/{schema-Bx0Mlo32.js → schema-D7iIEh6t.js} +52 -6
- package/dist/{service-account-DQLqkSVv.js → service-account-BDQ9xzta.js} +3 -3
- package/dist/{service-account-2HmlNPvy.js → service-account-DzQiOmqa.js} +5 -5
- package/dist/{session-stop-DEeZKqbX.js → session-stop-BQxgHR4X.js} +919 -168
- package/dist/{skills-2UrD7JkN.js → skills-CPf4vNuC.js} +2 -2
- package/dist/{slack-conversation-unfurl-Dd129Uov.js → slack-conversation-unfurl-B1KEptUg.js} +10 -9
- package/dist/{spawn-eMho9HDJ.js → spawn-CjGddiAU.js} +6 -6
- package/dist/{state-Bveuc4Zh.js → state-9wfj6aSD.js} +4 -4
- package/dist/{stop-D_ltJLDS.js → stop-CsQGuN5n.js} +62 -118
- package/dist/{store-COeYnPL_.js → store-Dz3YZ7gQ.js} +5 -5
- package/dist/{task-queue-CBIDXZpV.js → task-queue-CFlrJguF.js} +3 -3
- package/dist/{task-runner-CJF7zIJL.js → task-runner-frzlUvFD.js} +8 -9
- package/dist/{thread-context-Cg0jt0aE.js → thread-context-C4QuZlM8.js} +8 -91
- package/dist/turn-session-routing-BXaubz2w.js +244 -0
- package/dist/{turn-user-message-tcom1RYd.js → turn-user-message-DNC0eRZ7.js} +3 -3
- package/dist/users-XCCKn3xW.js +181 -0
- package/dist/{validation-EU91JwIT.js → validation-L5fdjmFX.js} +1 -1
- package/dist/{version-BYRPhY5G.js → version-BFmuwgxP.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{viewer-Cf8ISkAc.js → viewer-DKOeHpv3.js} +3 -3
- package/dist/{warmup-TgY4S1vx.js → warmup-mTMIatCV.js} +271 -279
- package/dist/{web-message-id-lNodcCOI.js → web-message-id-CUaSiGme.js} +16 -1
- package/dist/{worker-C6Uq4OKD.js → worker-Bz4KNxjI.js} +7 -7
- package/migrations/0114_plan_items.sql +22 -0
- package/migrations/meta/0114_snapshot.json +5203 -0
- package/migrations/meta/_journal.json +7 -0
- package/package.json +6 -6
- package/dist/schedule-cP0AACm1.js +0 -344
- package/dist/turn-session-routing-CaY3Tp8m.js +0 -1792
package/dist/app.js
CHANGED
|
@@ -1,49 +1,48 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { d as restoreRuntimeConfig,
|
|
3
|
-
import { $ as
|
|
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-
|
|
5
|
-
import { C as parseSlackReviewItemClick, E as parseSlackUserInputSubmission, S as buildSlackReviewItemModal, _ as createSlackReviewItemShow, b as findSlackThreadOwnerId, d as publicArtifactHeaders, f as readPublicArtifact, g as scheduledAutomationRunAttributes, h as logScheduledAutomationRunSkipped, n as executeAgentRun, p as unpublishedArtifactHeaders, r as processBackgroundCompaction, t as createAgentRunner, v as resolveSlackReviewItemCardConversationId, w as parseSlackReviewItemFormTarget, y as syncReviewItemSlackCards } from "./agent-runner-
|
|
6
|
-
import {
|
|
7
|
-
import { a as getSandboxResourceConfig, s as setSandboxResourceConfig } from "./install-
|
|
8
|
-
import { n as pluginCatalogRuntime } from "./catalog-runtime-
|
|
9
|
-
import { $ as
|
|
10
|
-
import { n as validatePluginRegistrations, t as validatePluginEgressCredentialHooks } from "./validation-
|
|
1
|
+
import { $n as getPlugins, Ao as confirmDispatchMailboxAppend, At as hasRunnableConversationWork, Bn as createUserTokenStore, C as settleConversationTitleWork, Cc as automationVersionOf, Fa as readConversationAccessFromSql, Fo as getDispatchRecord, Ga as readConversationEventPage, Gn as createPluginEventPublisher, Go as notifyAutomationBlocked, Gs as getDashboardTaskLink, Hi as proxyVercelSandboxEgressRequest, Hr as reviewItemReaderForUser, Is as saveScheduledAutomationInLock, It as pruneActiveConversation, Ja as readConversationLastEventSeq, Jn as getPluginRoutes, Ka as readConversationEventPageAfter, Ki as resolveBaseUrl, Lo as getPluginDispatchProjection, Ls as scheduledRunId, Mo as getDispatchConversationId, Mr as canActOnReviewItem, Ms as listScheduledAutomationsForTeam, Mt as isInvalidConversationRecordError, Nc as existingConversationId, Oo as buildDispatchId, Or as searchReviewItems, Ps as readScheduledAutomation, Ro as isTerminalDispatchStatus, Rs as withScheduledAutomationLock, Ts as slackMention, Uo as markDispatchFailed, Ur as reviewItemReaderForUserInConversation, Us as getDashboardReviewItemLink, Vc as recordAutomationExecution, Vi as isVercelSandboxEgressRequest, Xc as createPluginCache, Xo as openSlackModal, Xs as blockEventAutomation, Ya as readConversationMessageEventSeq, Yr as createCodeChangePublisher, Ys as setDashboardConversationLinkOptions, Zo as postSlackEphemeralMessage, Zs as collectEventAutomationMatchKeys, _ as appendConversationMessages, _a as createPluginEmbedder, _i as verifyEventAutomationCredentialSubject, aa as consumeSandboxEgressAuthRequiredSignal, ar as setBriefsConfig, bo as listConversationAnnotations, ca as parseSandboxEgressCredentialToken, ci as findMatchingWatches, ds as isDmChannel, ec as findMatchingEventAutomations, fa as normalizeSandboxEgressTracePropagationDomains, fc as eventGuidance, fi as takeDueTimerWatches, gi as bindSlackDirectCredentialSubject, gr as createPluginReviewItems, hi as bindScheduledAutomationCredentialSubject, ho as resolveRootVisibility, hr as projectConversationMessages, ia as clearSandboxEgressSignals, ii as collectEventMatchKeys, is as slackExternalRefIdSchema, ja as createPluginLogger, jo as createOrGetDispatch, ls as getSlackClient, lt as CONVERSATION_WORK_STALE_ENQUEUE_MS, mi as bindEventAutomationCredentialSubject, nl as getConfigDefaults, nr as validatePlugins, oa as consumeSandboxEgressPermissionDeniedSignal, oc as admitEventAutomationRun, oo as collectAttachmentGarbage, qn as getPluginApiRoutes, rl as setConfigDefaults, rs as slackEntitySchema, sc as eventAutomationRunLimitReason, tr as setPlugins, uo as requestAttachmentDeletion, vi as verifyScheduledAutomationCredentialSubject, vs as getWorkspaceTeamId, xi as createPluginState, xr as dismissOpenReviewItems, yi as verifySlackDirectCredentialSubject, yo as createPluginAnnotations, ys as runWithWorkspaceTeamId, zo as listPendingDispatchMailboxAppends, zs as getDashboardConversationLink } from "./projection-CWXDE0f6.js";
|
|
2
|
+
import { d as restoreRuntimeConfig, f as setBotModelConfig, g as snapshotRuntimeConfig, h as setSlackReactionConfig, i as getChatConfig, m as setRuntimeLimits, n as botConfig, p as setBotName, u as resetRuntimeConfig, ut as getAttachmentStorage } from "./config-DUD-zMvp.js";
|
|
3
|
+
import { $ as getStateAdapter, C as withConversationMutationLock, G as recordGoogleSignIn, I as resolveActorIdentityId, Z as disconnectStateAdapter, a as getConversationStore, at as withLock, it as fenceLock, m as withConversationEventLock, nt as MUTATION_LOCK_TTL_MS, o as getDb, p as deleteMessageLinks, r as getConversationEventStore, s as getSqlExecutor, t as closeDb, vt as touchConversationDetail, yt as createSlackDestination } from "./db-DV2ZUb1Y.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-oYpJYr-S.js";
|
|
5
|
+
import { C as parseSlackReviewItemClick, E as parseSlackUserInputSubmission, S as buildSlackReviewItemModal, _ as createSlackReviewItemShow, b as findSlackThreadOwnerId, d as publicArtifactHeaders, f as readPublicArtifact, g as scheduledAutomationRunAttributes, h as logScheduledAutomationRunSkipped, n as executeAgentRun, p as unpublishedArtifactHeaders, r as processBackgroundCompaction, t as createAgentRunner, v as resolveSlackReviewItemCardConversationId, w as parseSlackReviewItemFormTarget, y as syncReviewItemSlackCards } from "./agent-runner-BaLjEjPR.js";
|
|
6
|
+
import { E as getAuthPausedConversationTurnId, G as isAllowedDomain, J as resolveEventAuthor, K as isTrustedSlackAuthor, U as eventAuthorText, W as findTrustedUser, X as resolveBotSlackTeamId, Y as setTrustConfig, Z as renderTaskInput, _t as slackChannelMessageEvent, at as decodeAnnotationRef, b as deletePlanItems, dt as getExperimentalFeatures, ft as isExperimentalFeatureEnabled, ht as SLACK_EVENT_NAMESPACE, it as annotationKeyDigest, mt as getEventCatalog, pt as setExperimentalFeatures, q as parseEmail, rt as renderSlackObjectCard, vt as slackChannelMessageReplyThreadTs, yt as slackChannelMessageRunsAutomation } from "./session-stop-BQxgHR4X.js";
|
|
7
|
+
import { a as getSandboxResourceConfig, s as setSandboxResourceConfig } from "./install-DbD7C5td.js";
|
|
8
|
+
import { n as pluginCatalogRuntime } from "./catalog-runtime-B1R-nHd3.js";
|
|
9
|
+
import { $ as publicAddressLookup, A as actOnReviewItem, C as encodeConversationCursor, F as runAutoArchiveSweep, I as setConversationAutoArchive, J as readObjectLinkTypes, M as readReviewItemForUser, N as reviewItemChange, O as stopConversation, P as archiveViewerDoneConversations, Q as isPublicAddress, S as decodeConversationCursor, T as readConversationPendingMessages, U as backfillCacheWarmingGaps, V as runSavingsRefillSlice, W as GET$4, _t as SubscribedReplyReason, at as slackInboundMessageId, b as createConversationForViewer, dt as recordSkippedConversationMessage, et as createProductionConversationWorkOptions, ft as createSlackWebApiStatusSender, gt as parseContent, ht as stripLeadingBotMention, i as readConversationFeed, it as clearSlackPendingReactions, j as closeReviewItemsAnsweredByReply, k as ReviewItemActionError, l as readConversationDetail, lt as enqueueAgentDispatch, mt as startProcessingReaction, n as steerConversationPendingMessagesForViewer, nt as getProductionSlackAdapter, ot as normalizeIncomingSlackThreadId, pt as bindMessageAuthorIdentityId, rt as buildSlackInboundMessage, s as pinConversation, st as withNormalizedThreadId, t as stopConversationTurnForViewer, tt as createProductionSlackWebhookServices, ut as failStoppedDispatch, v as readConversationRecordFromSql, vt as getThreadStopDecision, w as cancelConversationPendingMessagesForViewer, y as appendConversationMessageForViewer } from "./stop-CsQGuN5n.js";
|
|
10
|
+
import { n as validatePluginRegistrations, t as validatePluginEgressCredentialHooks } from "./validation-L5fdjmFX.js";
|
|
11
11
|
import { a as pluginRuntimeRegistrationsFromPluginSet, n as pluginCatalogConfigFromEnv, r as pluginCatalogConfigFromPluginSet, t as defineJuniorPlugins } from "./plugins-Bkk0XRo2.js";
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import { i as
|
|
17
|
-
import {
|
|
18
|
-
import { _ as getConversationWorkState, g as getConversation, h as ensureConversationWake, l as clearExpiredConversationLease, r as appendAndEnqueueInboundMessage, y as listActiveConversationIds } from "./store-COeYnPL_.js";
|
|
19
|
-
import { a as getNextRunAtMs } from "./schedule-cP0AACm1.js";
|
|
20
|
-
import { i as enqueueAgentInvocationResult, r as createEndStoppedChildWork } from "./result-B-pauj42.js";
|
|
12
|
+
import { Ci as effectiveTaskOutcomes, E as processWorkspaceSnapshotJob, Kt as listPendingAgentInvocationMailboxAppends, Ot as collectAttachmentUploadGarbage, Si as missingAutomationSkillReason, St as createAndEnqueueConversation, Tt as webActorFromUser, Un as setConversationSubscription, _n as recordSubagentEnded, _r as joinPublicChannel, _t as renderReviewItemMessage, ar as parseSlackThreadId, bt as appendAndEnqueueWebMessage, di as readViewerAutomationSummary, dt as markConversationRead, gt as deliverReviewItemChange, k as ingestEvent, li as readViewerAutomationExecutions, lt as archiveConversation, pi as readViewerAutomations, qt as listPendingAgentInvocationResults, si as ViewerTaskNotFoundError, un as enqueueAgentInvocation, vt as reviewItemChangeRecord, wt as recordWebConversationActivity, xi as findAutomationSkill, xt as conversationTurnIdForMessage } from "./warmup-mTMIatCV.js";
|
|
13
|
+
import { _ as getConversationWorkState, g as getConversation, h as ensureConversationWake, l as clearExpiredConversationLease, r as appendAndEnqueueInboundMessage, y as listActiveConversationIds } from "./store-Dz3YZ7gQ.js";
|
|
14
|
+
import { I as scheduledRunSchema, U as getNextRunAtMs, X as automationTaskText, Y as automationTaskSchema, f as automationListQuerySchema, u as automationExecutionStatusSchema } from "./schedule-CHPWQn-x.js";
|
|
15
|
+
import { C as juniorConversationBriefs, D as juniorConversationEvents, F as juniorConversations, R as juniorDestinations, _ as juniorAgentBindings, d as juniorReviewItems, f as juniorAutomationRuns, m as juniorAutomations, v as juniorAgentInvocations } from "./executor-CjNhwwnj.js";
|
|
16
|
+
import { a as queueCallback, c as verifyConversationQueueMessage, f as getQueueProvider, g as isConversationQueueMessageRejectedError, h as conversationQueueMessageSchema, i as verifyBackgroundCompactionMessage, o as getVercelConversationWorkQueue, r as vercelBackgroundCompactionQueue, s as resolveConversationWorkQueueTopic, t as BACKGROUND_COMPACTION_QUEUE_TOPIC } from "./background-compaction-queue-D2wzxtGU.js";
|
|
17
|
+
import { i as enqueueAgentInvocationResult, r as createEndStoppedChildWork } from "./result-BmF9v9bv.js";
|
|
21
18
|
import { n as readSchedulerSecret, r as readSignInSecret } from "./secrets-DHaJ5TTn.js";
|
|
22
|
-
import { a as GET$5, i as publishAppHomeView, r as GET$6, t as receiveLocalOAuthCredential } from "./credential-sync-
|
|
19
|
+
import { a as GET$5, i as publishAppHomeView, r as GET$6, t as receiveLocalOAuthCredential } from "./credential-sync-Cdm-e1vJ.js";
|
|
23
20
|
import { t as nameRequestRoute } from "./sentry-route-name-C6EIzAGP.js";
|
|
24
21
|
import { t as SANDBOX_EGRESS_PROXY_PATH } from "./proxy-path-BHYoKZdq.js";
|
|
25
|
-
import {
|
|
26
|
-
import { i as readActorIdentity, l as resolveViewerUser, p as parseAvatarUrl } from "./viewer-
|
|
27
|
-
import { b as slackMessageTsSchema, g as slackTeamIdSchema, h as slackChannelIdSchema, n as createSlackActor,
|
|
28
|
-
import { a as resolveSlackActingUser, i as unfurlDashboardConversationLinks, n as handleSlackContinueHereClick, o as isSlackWorkspaceMember, s as slackWorkspaceBotId, t as SLACK_CONTINUE_HERE_ACTION_ID } from "./slack-conversation-unfurl-
|
|
29
|
-
import { o as unlinkProvider } from "./connections-
|
|
30
|
-
import { s as buttonUserInputField } from "./web-message-id-
|
|
31
|
-
import { n as verifySlackSignature, t as runWithSlackInstallation } from "./adapter-context-
|
|
32
|
-
import {
|
|
33
|
-
import {
|
|
34
|
-
import {
|
|
35
|
-
import { t as
|
|
36
|
-
import {
|
|
37
|
-
import { t as
|
|
38
|
-
import {
|
|
39
|
-
import { t as
|
|
40
|
-
import {
|
|
22
|
+
import { B as conversationTitleSchema, G as annotationCard, I as conversationBriefSchema, b as conversationSurfaceSchema, v as conversationReportStatusSchema } from "./conversation--f85g4zL.js";
|
|
23
|
+
import { i as readActorIdentity, l as resolveViewerUser, p as parseAvatarUrl } from "./viewer-DKOeHpv3.js";
|
|
24
|
+
import { b as slackMessageTsSchema, g as slackTeamIdSchema, h as slackChannelIdSchema, n as createSlackActor, s as parseActorUserId, u as parseSlackChannelId, v as parseSlackMessageTs, y as slackMessageTsFromMs } from "./actor-D2iXzvlN.js";
|
|
25
|
+
import { a as resolveSlackActingUser, i as unfurlDashboardConversationLinks, n as handleSlackContinueHereClick, o as isSlackWorkspaceMember, s as slackWorkspaceBotId, t as SLACK_CONTINUE_HERE_ACTION_ID } from "./slack-conversation-unfurl-B1KEptUg.js";
|
|
26
|
+
import { o as unlinkProvider } from "./connections-CDhsqPcC.js";
|
|
27
|
+
import { s as buttonUserInputField } from "./web-message-id-CUaSiGme.js";
|
|
28
|
+
import { n as verifySlackSignature, t as runWithSlackInstallation } from "./adapter-context-CnY-i32r.js";
|
|
29
|
+
import { c as coerceThreadConversationState } from "./turn-session-routing-BXaubz2w.js";
|
|
30
|
+
import { a as resumeConversationDelivery } from "./conversation-turn-BzdmrHb0.js";
|
|
31
|
+
import { i as getActiveSpan, n as captureMessage, u as sentry_exports } from "./sentry-CPbZjomA.js";
|
|
32
|
+
import { t as processConversationWork } from "./worker-Bz4KNxjI.js";
|
|
33
|
+
import { t as bindMessageAgent } from "./message-BBPcMKJY.js";
|
|
34
|
+
import { t as bindSpawnAgent } from "./spawn-CjGddiAU.js";
|
|
35
|
+
import { a as pluginTaskQueueConsumer, n as createVercelPluginTaskCallback, o as registerVercelPluginTaskDevConsumer, s as sendVercelPluginTask } from "./task-queue-CFlrJguF.js";
|
|
36
|
+
import { t as processPluginTask } from "./task-runner-frzlUvFD.js";
|
|
37
|
+
import { i as registerVercelCacheWarmupDevConsumer, l as verifyWorkspaceSnapshotJobMessage, n as cacheWarmupQueueConsumer, o as WORKSPACE_SNAPSHOT_JOB_QUEUE_TOPIC, r as createVercelCacheWarmupCallback } from "./queue-7FSijgqG.js";
|
|
38
|
+
import { t as JUNIOR_VERSION } from "./version-BFmuwgxP.js";
|
|
39
|
+
import { c as conversationPendingMessageDeliverySchema, n as conversationFeedQuerySchema } from "./conversation-feed-BNs9KiqC.js";
|
|
41
40
|
import { createRequire } from "node:module";
|
|
42
41
|
import { Hono } from "hono";
|
|
43
42
|
import * as z from "zod";
|
|
44
43
|
import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
45
44
|
import { and, asc, eq, inArray, isNotNull, isNull, lte, ne, or, sql } from "drizzle-orm";
|
|
46
|
-
import { EVENT_SUMMARY_MAX_LENGTH, EVENT_TEXT_MAX_LENGTH, dispatchOptionsSchema, eventSchema as eventSchema$1, eventTriggerFiltersText, isSlackDestination, userSchema } from "@sentry/junior-plugin-api";
|
|
45
|
+
import { EVENT_SUMMARY_MAX_LENGTH, EVENT_TEXT_MAX_LENGTH, dispatchOptionsSchema, eventSchema as eventSchema$1, eventTriggerFiltersText, identityDispatchOptionsSchema, isSlackDestination, userSchema } from "@sentry/junior-plugin-api";
|
|
47
46
|
import { pathToFileURL } from "node:url";
|
|
48
47
|
import { Message, ThreadImpl } from "chat";
|
|
49
48
|
import pLimit from "p-limit";
|
|
@@ -77,6 +76,99 @@ async function runTimerWatchHeartbeat(args) {
|
|
|
77
76
|
}
|
|
78
77
|
if (errors.length) throw new AggregateError(errors, "Timer Watch delivery failed");
|
|
79
78
|
}
|
|
79
|
+
// src/chat/task-execution/heartbeat.ts
|
|
80
|
+
const DEFAULT_RECOVERY_LIMIT = 25;
|
|
81
|
+
function heartbeatIdempotencyKey(reason, conversationId, nowMs) {
|
|
82
|
+
return `heartbeat:${reason}:${conversationId}:${nowMs}`;
|
|
83
|
+
}
|
|
84
|
+
/** Requeue expired leases and stranded mailbox work without running the agent. */
|
|
85
|
+
async function recoverConversationWork(args) {
|
|
86
|
+
if (!getChatConfig().conversationWorkEnabled) {
|
|
87
|
+
logWarn("conversation.work.recovery.disabled");
|
|
88
|
+
return {
|
|
89
|
+
expiredLeaseCount: 0,
|
|
90
|
+
pendingCount: 0
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
const result = {
|
|
94
|
+
expiredLeaseCount: 0,
|
|
95
|
+
pendingCount: 0
|
|
96
|
+
};
|
|
97
|
+
const staleBeforeMs = args.nowMs - CONVERSATION_WORK_STALE_ENQUEUE_MS;
|
|
98
|
+
const ids = await listActiveConversationIds({
|
|
99
|
+
limit: args.limit ?? DEFAULT_RECOVERY_LIMIT,
|
|
100
|
+
staleBeforeMs,
|
|
101
|
+
state: args.state
|
|
102
|
+
});
|
|
103
|
+
for (const conversationId of ids) await withLogContext({ conversationId }, async () => {
|
|
104
|
+
let work;
|
|
105
|
+
try {
|
|
106
|
+
work = await getConversationWorkState({
|
|
107
|
+
conversationId,
|
|
108
|
+
state: args.state
|
|
109
|
+
});
|
|
110
|
+
} catch (error) {
|
|
111
|
+
logException(error, "conversation.work.recovery.failed");
|
|
112
|
+
if (isInvalidConversationRecordError(error)) await pruneActiveConversation({
|
|
113
|
+
conversationId,
|
|
114
|
+
state: args.state
|
|
115
|
+
});
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
try {
|
|
119
|
+
if (!work || !hasRunnableConversationWork(work)) {
|
|
120
|
+
await pruneActiveConversation({
|
|
121
|
+
conversationId,
|
|
122
|
+
state: args.state
|
|
123
|
+
});
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
if (work.execution.lease && work.execution.lease.expiresAtMs <= args.nowMs) {
|
|
127
|
+
const recovery = await clearExpiredConversationLease({
|
|
128
|
+
beforeWorkStops: args.beforeWorkStops,
|
|
129
|
+
conversationId,
|
|
130
|
+
nowMs: args.nowMs,
|
|
131
|
+
state: args.state
|
|
132
|
+
});
|
|
133
|
+
if (recovery === "not_expired") return;
|
|
134
|
+
if (recovery === "stopped") {
|
|
135
|
+
logException(/* @__PURE__ */ new Error("Conversation work stopped after repeated failed attempts"), "conversation.work.retry.exhausted", {
|
|
136
|
+
"app.run.id": work.execution.runId ?? "unknown",
|
|
137
|
+
"app.worker.last_progress_at_ms": work.execution.lastProgressAtMs ?? work.createdAtMs,
|
|
138
|
+
"app.worker.retry_count": (work.execution.retryCount ?? 0) + 1
|
|
139
|
+
});
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
if ((await ensureConversationWake({
|
|
143
|
+
conversationId,
|
|
144
|
+
idempotencyKey: heartbeatIdempotencyKey("lease", conversationId, args.nowMs),
|
|
145
|
+
nowMs: args.nowMs,
|
|
146
|
+
queue: args.queue,
|
|
147
|
+
replaceExistingWake: true,
|
|
148
|
+
state: args.state
|
|
149
|
+
})).status === "enqueued") {
|
|
150
|
+
result.expiredLeaseCount += 1;
|
|
151
|
+
logInfo("conversation.work.lease_expired.requeued");
|
|
152
|
+
}
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
if (work.execution.lease) return;
|
|
156
|
+
if ((await ensureConversationWake({
|
|
157
|
+
conversationId,
|
|
158
|
+
idempotencyKey: heartbeatIdempotencyKey("pending", conversationId, args.nowMs),
|
|
159
|
+
nowMs: args.nowMs,
|
|
160
|
+
queue: args.queue,
|
|
161
|
+
state: args.state
|
|
162
|
+
})).status === "enqueued") {
|
|
163
|
+
result.pendingCount += 1;
|
|
164
|
+
logInfo("conversation.work.pending.requeued");
|
|
165
|
+
}
|
|
166
|
+
} catch (error) {
|
|
167
|
+
logException(error, "conversation.work.recovery.failed");
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
return result;
|
|
171
|
+
}
|
|
80
172
|
// src/chat/agent-dispatch/validation.ts
|
|
81
173
|
function hasIssueAtPath(issues, path) {
|
|
82
174
|
return issues.some((issue) => issue.path.length === path.length && issue.path.every((value, index) => value === path[index]));
|
|
@@ -172,6 +264,9 @@ async function dispatch(args) {
|
|
|
172
264
|
function createHeartbeatContext(args) {
|
|
173
265
|
const pluginName = typeof args.plugin === "string" ? args.plugin : args.plugin.manifest.name;
|
|
174
266
|
let dispatchCount = 0;
|
|
267
|
+
const assertDispatchBudget = () => {
|
|
268
|
+
if (dispatchCount >= MAX_DISPATCHES_PER_HEARTBEAT) throw new Error("Plugin heartbeat exceeded the dispatch limit");
|
|
269
|
+
};
|
|
175
270
|
return {
|
|
176
271
|
plugin: { name: pluginName },
|
|
177
272
|
annotations: { forConversation: (conversationId) => createPluginAnnotations({
|
|
@@ -196,7 +291,7 @@ function createHeartbeatContext(args) {
|
|
|
196
291
|
async dispatch(options) {
|
|
197
292
|
validateDispatchOptions(options);
|
|
198
293
|
const dispatchOptions = bindDispatchCredentialSubject(options, pluginName);
|
|
199
|
-
|
|
294
|
+
assertDispatchBudget();
|
|
200
295
|
const result = await dispatch({
|
|
201
296
|
conversationWorkQueue: args.conversationWorkQueue,
|
|
202
297
|
nowMs: args.nowMs,
|
|
@@ -206,6 +301,11 @@ function createHeartbeatContext(args) {
|
|
|
206
301
|
dispatchCount += 1;
|
|
207
302
|
return result;
|
|
208
303
|
},
|
|
304
|
+
async dispatchForIdentity(options) {
|
|
305
|
+
assertDispatchBudget();
|
|
306
|
+
dispatchCount += 1;
|
|
307
|
+
return await args.dispatchForIdentity(pluginName, options);
|
|
308
|
+
},
|
|
209
309
|
async get(id) {
|
|
210
310
|
return await getPluginDispatchProjection({
|
|
211
311
|
plugin: pluginName,
|
|
@@ -278,355 +378,53 @@ async function getScheduledAutomationDispatch(id) {
|
|
|
278
378
|
id
|
|
279
379
|
});
|
|
280
380
|
}
|
|
281
|
-
// src/chat/automations/reply-attribution.ts
|
|
282
|
-
/** Name the Automation in the footer of the replies that its runs post. */
|
|
283
|
-
function automationReplyAttribution(title) {
|
|
284
|
-
const detail = (title ?? "").replace(/\s+/g, " ").trim().slice(0, 128).trim();
|
|
285
|
-
return detail ? {
|
|
286
|
-
label: "Automation",
|
|
287
|
-
detail
|
|
288
|
-
} : { label: "Automation" };
|
|
289
|
-
}
|
|
290
381
|
// src/chat/event-automations/runs.ts
|
|
291
382
|
/**
|
|
292
383
|
* Record a dispatched event automation run with the Automation version it ran,
|
|
293
384
|
* and link its Conversation when it exists. The dispatch can finish before
|
|
294
|
-
* this write, so a stored run, or a retry of the same Event, keeps the row it
|
|
295
|
-
* has.
|
|
296
|
-
*/
|
|
297
|
-
async function recordEventAutomationRunStarted(db, args) {
|
|
298
|
-
await db.insert(juniorAutomationRuns).values({
|
|
299
|
-
id: args.dispatchId,
|
|
300
|
-
automationId: args.automation.id,
|
|
301
|
-
automationVersion: automationVersionOf(args.automation),
|
|
302
|
-
conversationId: existingConversationId(getDispatchConversationId({ id: args.dispatchId })),
|
|
303
|
-
startedAtMs: args.nowMs,
|
|
304
|
-
status: "running"
|
|
305
|
-
}).onConflictDoNothing({ target: juniorAutomationRuns.id });
|
|
306
|
-
}
|
|
307
|
-
/**
|
|
308
|
-
* Settle running event automation runs whose dispatch has ended. A run whose
|
|
309
|
-
* dispatch record is gone fails.
|
|
310
|
-
*/
|
|
311
|
-
async function settleEventAutomationRuns(db, nowMs) {
|
|
312
|
-
const runs = await db.select({
|
|
313
|
-
automationId: juniorAutomationRuns.automationId,
|
|
314
|
-
id: juniorAutomationRuns.id
|
|
315
|
-
}).from(juniorAutomationRuns).innerJoin(juniorAutomations, eq(juniorAutomations.id, juniorAutomationRuns.automationId)).where(and(eq(juniorAutomations.kind, "event"), eq(juniorAutomationRuns.status, "running")));
|
|
316
|
-
for (const run of runs) {
|
|
317
|
-
const dispatch = await getDispatchRecord(run.id);
|
|
318
|
-
const status = dispatch?.status ?? "failed";
|
|
319
|
-
if (status !== "blocked" && status !== "completed" && status !== "failed") continue;
|
|
320
|
-
await recordAutomationExecution(run.automationId, {
|
|
321
|
-
conversationId: getDispatchConversationId({ id: run.id }),
|
|
322
|
-
errorMessage: dispatch ? dispatch.errorMessage : "Event automation dispatch record is missing.",
|
|
323
|
-
executionId: run.id,
|
|
324
|
-
nowMs: dispatch?.updatedAtMs ?? nowMs,
|
|
325
|
-
status
|
|
326
|
-
});
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
// src/chat/
|
|
330
|
-
/**
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
function eventAutomationDispatchKey(taskId, namespace, eventKey) {
|
|
338
|
-
return `event-automation:${createHash("sha256").update(`${taskId}\0${namespace}\0${eventKey}`).digest("hex").slice(0, 32)}`;
|
|
339
|
-
}
|
|
340
|
-
/** Render plain agent input for one matching event automation. */
|
|
341
|
-
function eventInput(task, event, outcomes, catalog) {
|
|
342
|
-
const guidance = eventGuidance(catalog, event.namespace, event.eventType);
|
|
343
|
-
return renderTaskInput({
|
|
344
|
-
about: task.trigger.label,
|
|
345
|
-
event: event.eventType,
|
|
346
|
-
source: event.namespace,
|
|
347
|
-
creator: slackMention(task.createdBy.slackUserId),
|
|
348
|
-
instructions: automationTaskText(task.task),
|
|
349
|
-
...task.task.kind === "skill" ? { skill: task.task.skill } : void 0,
|
|
350
|
-
outcomes,
|
|
351
|
-
guidance,
|
|
352
|
-
trustedSummary: event.trustedSummary,
|
|
353
|
-
trustedSummaryMaxLength: EVENT_SUMMARY_MAX_LENGTH,
|
|
354
|
-
verifiedDetails: event.data,
|
|
355
|
-
externalText: event.untrustedText,
|
|
356
|
-
externalTextMaxLength: EVENT_TEXT_MAX_LENGTH
|
|
357
|
-
});
|
|
358
|
-
}
|
|
359
|
-
/**
|
|
360
|
-
* Match a normalized event and dispatch every matching automation.
|
|
361
|
-
*
|
|
362
|
-
* Plugins publish one copy of an occurrence for each scope, such as a pull
|
|
363
|
-
* request and its repository. All copies share one event key. An automation
|
|
364
|
-
* with no identifier matches every copy, and the dispatch key and the run
|
|
365
|
-
* limit both use the event key, so it runs and counts once.
|
|
366
|
-
*/
|
|
367
|
-
async function ingestEventAutomations(input, options) {
|
|
368
|
-
const event = eventSchema$1.parse(input);
|
|
369
|
-
const db = getDb();
|
|
370
|
-
const nowMs = options.nowMs ?? Date.now();
|
|
371
|
-
const catalog = getEventCatalog();
|
|
372
|
-
const [matches = []] = await findMatchingEventAutomations(db, [event], options.teamId, catalog);
|
|
373
|
-
const tasks = matches.filter((task) => slackChannelMessageRunsAutomation(event, task));
|
|
374
|
-
let dispatched = 0;
|
|
375
|
-
const errors = [];
|
|
376
|
-
for (const task of tasks) try {
|
|
377
|
-
const skill = task.task.kind === "skill" ? task.task.skill : void 0;
|
|
378
|
-
if (skill && !await findAutomationSkill(skill)) {
|
|
379
|
-
const reason = missingAutomationSkillReason(skill);
|
|
380
|
-
if (await blockEventAutomation(db, task.id, reason)) await notifyAutomationBlocked({
|
|
381
|
-
automationId: task.id,
|
|
382
|
-
kind: "event",
|
|
383
|
-
reason
|
|
384
|
-
});
|
|
385
|
-
continue;
|
|
386
|
-
}
|
|
387
|
-
const idempotencyKey = eventAutomationDispatchKey(task.id, event.namespace, event.eventKey);
|
|
388
|
-
if (await admitEventAutomationRun({
|
|
389
|
-
automationId: task.id,
|
|
390
|
-
nowMs,
|
|
391
|
-
runKey: idempotencyKey
|
|
392
|
-
}) === "limited") {
|
|
393
|
-
const reason = eventAutomationRunLimitReason();
|
|
394
|
-
logWarn("event_automation.run_limit.exceeded", {
|
|
395
|
-
"app.task.id": task.id,
|
|
396
|
-
"app.task.type": "event"
|
|
397
|
-
});
|
|
398
|
-
if (await blockEventAutomation(db, task.id, reason)) {
|
|
399
|
-
captureMessage("Event automation blocked by run limit", {
|
|
400
|
-
level: "warning",
|
|
401
|
-
fingerprint: ["event_automation.run_limit.blocked"],
|
|
402
|
-
tags: {
|
|
403
|
-
"app.event.namespace": event.namespace,
|
|
404
|
-
"app.task.type": "event"
|
|
405
|
-
},
|
|
406
|
-
extra: {
|
|
407
|
-
"app.event.event_type": event.eventType,
|
|
408
|
-
"app.event_automation.max_runs": botConfig.maxEventAutomationRuns,
|
|
409
|
-
"app.event_automation.run_window_ms": botConfig.eventAutomationRunWindowMs,
|
|
410
|
-
"app.event_automation.resource_type": task.trigger.resourceType ?? "any",
|
|
411
|
-
"app.task.id": task.id
|
|
412
|
-
}
|
|
413
|
-
});
|
|
414
|
-
await notifyAutomationBlocked({
|
|
415
|
-
automationId: task.id,
|
|
416
|
-
kind: "event",
|
|
417
|
-
reason
|
|
418
|
-
});
|
|
419
|
-
}
|
|
420
|
-
continue;
|
|
421
|
-
}
|
|
422
|
-
const replyThreadTs = slackChannelMessageReplyThreadTs(event);
|
|
423
|
-
const destination = replyThreadTs ? {
|
|
424
|
-
...task.destination,
|
|
425
|
-
threadTs: replyThreadTs
|
|
426
|
-
} : task.destination;
|
|
427
|
-
const outcomes = effectiveTaskOutcomes(task.outcomes, destination);
|
|
428
|
-
const credentialSubject = task.credentialMode === "creator" ? {
|
|
429
|
-
type: "user",
|
|
430
|
-
userId: task.createdBy.slackUserId,
|
|
431
|
-
allowedWhen: "event-automation",
|
|
432
|
-
taskId: task.id
|
|
433
|
-
} : void 0;
|
|
434
|
-
const dispatch = await dispatchEventAutomation({
|
|
435
|
-
automationId: task.id,
|
|
436
|
-
conversationWorkQueue: options.queue,
|
|
437
|
-
nowMs,
|
|
438
|
-
options: {
|
|
439
|
-
idempotencyKey,
|
|
440
|
-
...credentialSubject ? { credentialSubject } : void 0,
|
|
441
|
-
destination,
|
|
442
|
-
destinationVisibility: task.destinationVisibility,
|
|
443
|
-
input: eventInput(task, event, outcomes, catalog),
|
|
444
|
-
...skill ? { skill } : void 0,
|
|
445
|
-
metadata: { eventAutomationId: task.id },
|
|
446
|
-
replyAttribution: automationReplyAttribution(task.title),
|
|
447
|
-
outcomes
|
|
448
|
-
}
|
|
449
|
-
});
|
|
450
|
-
await recordEventAutomationRunStarted(db, {
|
|
451
|
-
automation: task,
|
|
452
|
-
dispatchId: dispatch.id,
|
|
453
|
-
nowMs
|
|
454
|
-
});
|
|
455
|
-
if (dispatch.status === "created") dispatched += 1;
|
|
456
|
-
} catch (error) {
|
|
457
|
-
errors.push(error);
|
|
458
|
-
}
|
|
459
|
-
if (errors.length > 0) throw new AggregateError(errors, "Failed to dispatch one or more event automations");
|
|
460
|
-
return { dispatched };
|
|
461
|
-
}
|
|
462
|
-
// src/chat/events/workspace.ts
|
|
463
|
-
/**
|
|
464
|
-
* Resolve the single-bot Slack team id for event-automation indexing and
|
|
465
|
-
* Event people mentions.
|
|
466
|
-
*
|
|
467
|
-
* Watch matching does not use this. Event automations still key by
|
|
468
|
-
* destination team until that store is conversation-owned. Event delivery
|
|
469
|
-
* itself is not gated on Slack.
|
|
470
|
-
*/
|
|
471
|
-
function createEventTeamIdResolver() {
|
|
472
|
-
let pending;
|
|
473
|
-
return async () => {
|
|
474
|
-
if (!getSlackBotToken()) return void 0;
|
|
475
|
-
pending ??= getSlackClient().auth.test().then((result) => {
|
|
476
|
-
const teamId = result.team_id?.trim();
|
|
477
|
-
if (!teamId) throw new Error("Slack auth.test did not return a team id");
|
|
478
|
-
return teamId;
|
|
479
|
-
}).catch((error) => {
|
|
480
|
-
pending = void 0;
|
|
481
|
-
throw error;
|
|
482
|
-
});
|
|
483
|
-
return await pending;
|
|
484
|
-
};
|
|
485
|
-
}
|
|
486
|
-
// src/chat/events/app-publisher.ts
|
|
487
|
-
const WATCH_MATCH_CONCURRENCY = 4;
|
|
488
|
-
/** Build the core event publisher used by plugin routes. */
|
|
489
|
-
function createEventAppPublisher(args) {
|
|
490
|
-
const resolveEventAutomationTeamId = createEventTeamIdResolver();
|
|
491
|
-
return {
|
|
492
|
-
async hasMatch(events) {
|
|
493
|
-
const work = args.conversationWork();
|
|
494
|
-
const eventAutomationTeamId = await resolveEventAutomationTeamId();
|
|
495
|
-
const limit = pLimit(WATCH_MATCH_CONCURRENCY);
|
|
496
|
-
const [subscriptions, tasks] = await Promise.all([Promise.all(events.map((event) => limit(() => findMatchingWatches({
|
|
497
|
-
data: event.data,
|
|
498
|
-
eventType: event.eventType,
|
|
499
|
-
namespace: event.namespace,
|
|
500
|
-
identifier: event.identifier,
|
|
501
|
-
state: work.state
|
|
502
|
-
})))), eventAutomationTeamId ? findMatchingEventAutomations(getDb(), events, eventAutomationTeamId, getEventCatalog()) : Promise.resolve([])]);
|
|
503
|
-
return [...subscriptions, ...tasks].some((matched) => matched.length > 0);
|
|
504
|
-
},
|
|
505
|
-
async neededMatchKeys(input) {
|
|
506
|
-
const work = args.conversationWork();
|
|
507
|
-
const eventAutomationTeamId = await resolveEventAutomationTeamId();
|
|
508
|
-
const [watchKeys, taskKeys] = await Promise.all([collectEventMatchKeys({
|
|
509
|
-
eventTypes: input.eventTypes,
|
|
510
|
-
identifiers: input.identifiers,
|
|
511
|
-
namespace: input.namespace,
|
|
512
|
-
state: work.state
|
|
513
|
-
}), eventAutomationTeamId ? collectEventAutomationMatchKeys(getDb(), {
|
|
514
|
-
catalog: getEventCatalog(),
|
|
515
|
-
...input.data ? { data: input.data } : void 0,
|
|
516
|
-
eventTypes: input.eventTypes,
|
|
517
|
-
identifiers: input.identifiers,
|
|
518
|
-
namespace: input.namespace,
|
|
519
|
-
teamId: eventAutomationTeamId
|
|
520
|
-
}) : Promise.resolve([])]);
|
|
521
|
-
return [.../* @__PURE__ */ new Set([...watchKeys, ...taskKeys])].sort();
|
|
522
|
-
},
|
|
523
|
-
async publish(event) {
|
|
524
|
-
const work = args.conversationWork();
|
|
525
|
-
const queue = work.queue ?? getVercelConversationWorkQueue();
|
|
526
|
-
const eventAutomationTeamId = await resolveEventAutomationTeamId();
|
|
527
|
-
await Promise.all([ingestEvent(event, {
|
|
528
|
-
queue,
|
|
529
|
-
slackTeamId: eventAutomationTeamId,
|
|
530
|
-
state: work.state
|
|
531
|
-
}), eventAutomationTeamId ? ingestEventAutomations(event, {
|
|
532
|
-
queue,
|
|
533
|
-
teamId: eventAutomationTeamId
|
|
534
|
-
}) : Promise.resolve()]);
|
|
535
|
-
}
|
|
536
|
-
};
|
|
537
|
-
}
|
|
538
|
-
// src/chat/task-execution/heartbeat.ts
|
|
539
|
-
const DEFAULT_RECOVERY_LIMIT = 25;
|
|
540
|
-
function heartbeatIdempotencyKey(reason, conversationId, nowMs) {
|
|
541
|
-
return `heartbeat:${reason}:${conversationId}:${nowMs}`;
|
|
542
|
-
}
|
|
543
|
-
/** Requeue expired leases and stranded mailbox work without running the agent. */
|
|
544
|
-
async function recoverConversationWork(args) {
|
|
545
|
-
if (!getChatConfig().conversationWorkEnabled) {
|
|
546
|
-
logWarn("conversation.work.recovery.disabled");
|
|
547
|
-
return {
|
|
548
|
-
expiredLeaseCount: 0,
|
|
549
|
-
pendingCount: 0
|
|
550
|
-
};
|
|
551
|
-
}
|
|
552
|
-
const result = {
|
|
553
|
-
expiredLeaseCount: 0,
|
|
554
|
-
pendingCount: 0
|
|
555
|
-
};
|
|
556
|
-
const staleBeforeMs = args.nowMs - CONVERSATION_WORK_STALE_ENQUEUE_MS;
|
|
557
|
-
const ids = await listActiveConversationIds({
|
|
558
|
-
limit: args.limit ?? DEFAULT_RECOVERY_LIMIT,
|
|
559
|
-
staleBeforeMs,
|
|
560
|
-
state: args.state
|
|
561
|
-
});
|
|
562
|
-
for (const conversationId of ids) await withLogContext({ conversationId }, async () => {
|
|
563
|
-
let work;
|
|
564
|
-
try {
|
|
565
|
-
work = await getConversationWorkState({
|
|
566
|
-
conversationId,
|
|
567
|
-
state: args.state
|
|
568
|
-
});
|
|
569
|
-
} catch (error) {
|
|
570
|
-
logException(error, "conversation.work.recovery.failed");
|
|
571
|
-
if (isInvalidConversationRecordError(error)) await pruneActiveConversation({
|
|
572
|
-
conversationId,
|
|
573
|
-
state: args.state
|
|
574
|
-
});
|
|
575
|
-
return;
|
|
576
|
-
}
|
|
577
|
-
try {
|
|
578
|
-
if (!work || !hasRunnableConversationWork(work)) {
|
|
579
|
-
await pruneActiveConversation({
|
|
580
|
-
conversationId,
|
|
581
|
-
state: args.state
|
|
582
|
-
});
|
|
583
|
-
return;
|
|
584
|
-
}
|
|
585
|
-
if (work.execution.lease && work.execution.lease.expiresAtMs <= args.nowMs) {
|
|
586
|
-
const recovery = await clearExpiredConversationLease({
|
|
587
|
-
beforeWorkStops: args.beforeWorkStops,
|
|
588
|
-
conversationId,
|
|
589
|
-
nowMs: args.nowMs,
|
|
590
|
-
state: args.state
|
|
591
|
-
});
|
|
592
|
-
if (recovery === "not_expired") return;
|
|
593
|
-
if (recovery === "stopped") {
|
|
594
|
-
logException(/* @__PURE__ */ new Error("Conversation work stopped after repeated failed attempts"), "conversation.work.retry.exhausted", {
|
|
595
|
-
"app.run.id": work.execution.runId ?? "unknown",
|
|
596
|
-
"app.worker.last_progress_at_ms": work.execution.lastProgressAtMs ?? work.createdAtMs,
|
|
597
|
-
"app.worker.retry_count": (work.execution.retryCount ?? 0) + 1
|
|
598
|
-
});
|
|
599
|
-
return;
|
|
600
|
-
}
|
|
601
|
-
if ((await ensureConversationWake({
|
|
602
|
-
conversationId,
|
|
603
|
-
idempotencyKey: heartbeatIdempotencyKey("lease", conversationId, args.nowMs),
|
|
604
|
-
nowMs: args.nowMs,
|
|
605
|
-
queue: args.queue,
|
|
606
|
-
replaceExistingWake: true,
|
|
607
|
-
state: args.state
|
|
608
|
-
})).status === "enqueued") {
|
|
609
|
-
result.expiredLeaseCount += 1;
|
|
610
|
-
logInfo("conversation.work.lease_expired.requeued");
|
|
611
|
-
}
|
|
612
|
-
return;
|
|
613
|
-
}
|
|
614
|
-
if (work.execution.lease) return;
|
|
615
|
-
if ((await ensureConversationWake({
|
|
616
|
-
conversationId,
|
|
617
|
-
idempotencyKey: heartbeatIdempotencyKey("pending", conversationId, args.nowMs),
|
|
618
|
-
nowMs: args.nowMs,
|
|
619
|
-
queue: args.queue,
|
|
620
|
-
state: args.state
|
|
621
|
-
})).status === "enqueued") {
|
|
622
|
-
result.pendingCount += 1;
|
|
623
|
-
logInfo("conversation.work.pending.requeued");
|
|
624
|
-
}
|
|
625
|
-
} catch (error) {
|
|
626
|
-
logException(error, "conversation.work.recovery.failed");
|
|
627
|
-
}
|
|
628
|
-
});
|
|
629
|
-
return result;
|
|
385
|
+
* this write, so a stored run, or a retry of the same Event, keeps the row it
|
|
386
|
+
* has.
|
|
387
|
+
*/
|
|
388
|
+
async function recordEventAutomationRunStarted(db, args) {
|
|
389
|
+
await db.insert(juniorAutomationRuns).values({
|
|
390
|
+
id: args.dispatchId,
|
|
391
|
+
automationId: args.automation.id,
|
|
392
|
+
automationVersion: automationVersionOf(args.automation),
|
|
393
|
+
conversationId: existingConversationId(getDispatchConversationId({ id: args.dispatchId })),
|
|
394
|
+
startedAtMs: args.nowMs,
|
|
395
|
+
status: "running"
|
|
396
|
+
}).onConflictDoNothing({ target: juniorAutomationRuns.id });
|
|
397
|
+
}
|
|
398
|
+
/**
|
|
399
|
+
* Settle running event automation runs whose dispatch has ended. A run whose
|
|
400
|
+
* dispatch record is gone fails.
|
|
401
|
+
*/
|
|
402
|
+
async function settleEventAutomationRuns(db, nowMs) {
|
|
403
|
+
const runs = await db.select({
|
|
404
|
+
automationId: juniorAutomationRuns.automationId,
|
|
405
|
+
id: juniorAutomationRuns.id
|
|
406
|
+
}).from(juniorAutomationRuns).innerJoin(juniorAutomations, eq(juniorAutomations.id, juniorAutomationRuns.automationId)).where(and(eq(juniorAutomations.kind, "event"), eq(juniorAutomationRuns.status, "running")));
|
|
407
|
+
for (const run of runs) {
|
|
408
|
+
const dispatch = await getDispatchRecord(run.id);
|
|
409
|
+
const status = dispatch?.status ?? "failed";
|
|
410
|
+
if (status !== "blocked" && status !== "completed" && status !== "failed") continue;
|
|
411
|
+
await recordAutomationExecution(run.automationId, {
|
|
412
|
+
conversationId: getDispatchConversationId({ id: run.id }),
|
|
413
|
+
errorMessage: dispatch ? dispatch.errorMessage : "Event automation dispatch record is missing.",
|
|
414
|
+
executionId: run.id,
|
|
415
|
+
nowMs: dispatch?.updatedAtMs ?? nowMs,
|
|
416
|
+
status
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
// src/chat/automations/reply-attribution.ts
|
|
421
|
+
/** Name the Automation in the footer of the replies that its runs post. */
|
|
422
|
+
function automationReplyAttribution(title) {
|
|
423
|
+
const detail = (title ?? "").replace(/\s+/g, " ").trim().slice(0, 128).trim();
|
|
424
|
+
return detail ? {
|
|
425
|
+
label: "Automation",
|
|
426
|
+
detail
|
|
427
|
+
} : { label: "Automation" };
|
|
630
428
|
}
|
|
631
429
|
// src/chat/scheduled-automations/runs.ts
|
|
632
430
|
const PENDING_CLAIM_STALE_MS = 6e4;
|
|
@@ -1267,6 +1065,7 @@ async function runPluginHeartbeats(args) {
|
|
|
1267
1065
|
try {
|
|
1268
1066
|
const result = await runWithTimeout(Promise.resolve(heartbeat(createHeartbeatContext({
|
|
1269
1067
|
conversationWorkQueue: args.conversationWorkQueue,
|
|
1068
|
+
dispatchForIdentity: args.dispatchForIdentity,
|
|
1270
1069
|
events: createPluginEventPublisher(plugin, args.events),
|
|
1271
1070
|
plugin,
|
|
1272
1071
|
nowMs: args.nowMs,
|
|
@@ -1336,7 +1135,6 @@ async function recoverPendingAgentInvocationResults(args) {
|
|
|
1336
1135
|
/** Run the core heartbeat phases. */
|
|
1337
1136
|
async function runHeartbeat(args) {
|
|
1338
1137
|
const queue = args.conversationWorkQueue ?? getVercelConversationWorkQueue();
|
|
1339
|
-
const events = args.events ?? createEventAppPublisher({ conversationWork: () => ({ queue }) });
|
|
1340
1138
|
const endStoppedChildWork = createEndStoppedChildWork({ queue });
|
|
1341
1139
|
await recoverConversationWork({
|
|
1342
1140
|
beforeWorkStops: async (conversationId, inboundMessageIds) => {
|
|
@@ -1377,7 +1175,8 @@ async function runHeartbeat(args) {
|
|
|
1377
1175
|
}
|
|
1378
1176
|
await runPluginHeartbeats({
|
|
1379
1177
|
conversationWorkQueue: queue,
|
|
1380
|
-
|
|
1178
|
+
dispatchForIdentity: args.dispatchForIdentity,
|
|
1179
|
+
events: args.events,
|
|
1381
1180
|
nowMs: args.nowMs,
|
|
1382
1181
|
showReviewItem: args.showReviewItem
|
|
1383
1182
|
});
|
|
@@ -1405,11 +1204,12 @@ function verifySchedulerRequest(request) {
|
|
|
1405
1204
|
}
|
|
1406
1205
|
// src/handlers/heartbeat.ts
|
|
1407
1206
|
/** Handle the authenticated internal heartbeat. */
|
|
1408
|
-
async function GET$3(request, waitUntil, options
|
|
1207
|
+
async function GET$3(request, waitUntil, options) {
|
|
1409
1208
|
if (!verifySchedulerRequest(request)) return new Response("Unauthorized", { status: 401 });
|
|
1410
1209
|
const nowMs = Date.now();
|
|
1411
1210
|
waitUntil(() => runHeartbeat({
|
|
1412
1211
|
conversationWorkQueue: options.conversationWorkQueue,
|
|
1212
|
+
dispatchForIdentity: options.dispatchForIdentity,
|
|
1413
1213
|
events: options.events,
|
|
1414
1214
|
nowMs,
|
|
1415
1215
|
showReviewItem: options.showReviewItem
|
|
@@ -1488,6 +1288,10 @@ async function selectExpiredRoots(executor, args) {
|
|
|
1488
1288
|
and review_items.status = 'open'
|
|
1489
1289
|
and review_items.automation_id is null
|
|
1490
1290
|
)
|
|
1291
|
+
or exists (
|
|
1292
|
+
select 1 from junior_plan_items plan_items
|
|
1293
|
+
where plan_items.conversation_id = tree.conversation_id
|
|
1294
|
+
)
|
|
1491
1295
|
or (
|
|
1492
1296
|
${juniorDestinations.visibility} is distinct from 'public'
|
|
1493
1297
|
and (
|
|
@@ -1529,9 +1333,9 @@ async function selectExpiredRoots(executor, args) {
|
|
|
1529
1333
|
* event rows for the given conversation and every descendant, stamp
|
|
1530
1334
|
* `transcript_purged_at`, and — for non-public content — null the raw-payload
|
|
1531
1335
|
* metadata (`title`, `channel_name`, legacy actor JSON) so purged private
|
|
1532
|
-
* conversations keep only safe metadata.
|
|
1533
|
-
* Briefs and the Review items that it
|
|
1534
|
-
* survive.
|
|
1336
|
+
* conversations keep only safe metadata. Plan items go with the transcript.
|
|
1337
|
+
* Non-public content also loses its Briefs and the Review items that it
|
|
1338
|
+
* added. The metadata rows themselves survive.
|
|
1535
1339
|
*/
|
|
1536
1340
|
async function purgeConversationTree(executor, args) {
|
|
1537
1341
|
return await withConversationMutationLock(executor, args.rootConversationId, async () => {
|
|
@@ -1582,6 +1386,7 @@ async function purgeConversationTree(executor, args) {
|
|
|
1582
1386
|
nowMs: args.nowMs,
|
|
1583
1387
|
reason: "Conversation purged"
|
|
1584
1388
|
});
|
|
1389
|
+
await deletePlanItems(executor, ids);
|
|
1585
1390
|
await requestAttachmentDeletion(executor, ids, args.nowMs);
|
|
1586
1391
|
const scrubMetadata = args.retention ? !isPublic : resolvedScrubMetadata;
|
|
1587
1392
|
if (scrubMetadata) {
|
|
@@ -1776,14 +1581,9 @@ const eventSchema = z.object({
|
|
|
1776
1581
|
user: z.string().min(1),
|
|
1777
1582
|
external_ref: z.object({
|
|
1778
1583
|
type: z.literal("annotation"),
|
|
1779
|
-
id: slackExternalRefIdSchema
|
|
1584
|
+
id: slackExternalRefIdSchema
|
|
1780
1585
|
})
|
|
1781
1586
|
});
|
|
1782
|
-
const refSchema = z.tuple([
|
|
1783
|
-
z.string().min(1),
|
|
1784
|
-
z.string().min(1),
|
|
1785
|
-
z.string().min(1)
|
|
1786
|
-
]);
|
|
1787
1587
|
/** Show saved annotation facts only to a viewer who can read their Conversation. */
|
|
1788
1588
|
async function presentSlackAnnotationDetails(event, teamId) {
|
|
1789
1589
|
const triggerId = event["trigger_id"];
|
|
@@ -1798,19 +1598,12 @@ async function presentSlackAnnotationDetails(event, teamId) {
|
|
|
1798
1598
|
await missing();
|
|
1799
1599
|
return;
|
|
1800
1600
|
}
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
value = JSON.parse(Buffer.from(parsed.data.external_ref.id, "base64url").toString("utf8"));
|
|
1804
|
-
} catch {
|
|
1805
|
-
await missing();
|
|
1806
|
-
return;
|
|
1807
|
-
}
|
|
1808
|
-
const ref = refSchema.safeParse(value);
|
|
1809
|
-
if (!ref.success) {
|
|
1601
|
+
const ref = decodeAnnotationRef(parsed.data.external_ref.id);
|
|
1602
|
+
if (!ref) {
|
|
1810
1603
|
await missing();
|
|
1811
1604
|
return;
|
|
1812
1605
|
}
|
|
1813
|
-
const
|
|
1606
|
+
const { conversationId, keyDigest } = ref;
|
|
1814
1607
|
const db = getDb();
|
|
1815
1608
|
const identity = await readActorIdentity({
|
|
1816
1609
|
platform: "slack",
|
|
@@ -1833,7 +1626,7 @@ async function presentSlackAnnotationDetails(event, teamId) {
|
|
|
1833
1626
|
await missing();
|
|
1834
1627
|
return;
|
|
1835
1628
|
}
|
|
1836
|
-
const annotation = (await listConversationAnnotations(db, conversationId)).find((item) => item.plugin
|
|
1629
|
+
const annotation = (await listConversationAnnotations(db, conversationId)).find((item) => annotationKeyDigest(item.plugin, item.key) === keyDigest);
|
|
1837
1630
|
if (!annotation) {
|
|
1838
1631
|
await missing();
|
|
1839
1632
|
return;
|
|
@@ -1845,7 +1638,10 @@ async function presentSlackAnnotationDetails(event, teamId) {
|
|
|
1845
1638
|
}
|
|
1846
1639
|
await client.entity.presentDetails({
|
|
1847
1640
|
trigger_id: parsed.data.trigger_id,
|
|
1848
|
-
metadata: slackEntitySchema.parse(
|
|
1641
|
+
metadata: slackEntitySchema.parse({
|
|
1642
|
+
...entity,
|
|
1643
|
+
external_ref: parsed.data.external_ref
|
|
1644
|
+
})
|
|
1849
1645
|
});
|
|
1850
1646
|
}
|
|
1851
1647
|
// src/chat/ingress/slack-payload.ts
|
|
@@ -2545,33 +2341,142 @@ function textMentionsBot(text, botUserId) {
|
|
|
2545
2341
|
function eventMentionsBot(event, botUserId) {
|
|
2546
2342
|
return Boolean(botUserId && (textMentionsBot(event.text ?? "", botUserId) || event.blocks?.some((block) => block.type === "section" && typeof block.text === "object" && block.text.type === "mrkdwn" && textMentionsBot(block.text.text, botUserId))));
|
|
2547
2343
|
}
|
|
2548
|
-
// src/chat/
|
|
2549
|
-
const ALLOWED_TTL_MS = 3e5;
|
|
2550
|
-
const NOT_ALLOWED_TTL_MS = 3e4;
|
|
2344
|
+
// src/chat/event-automations/ingest.ts
|
|
2551
2345
|
/**
|
|
2552
|
-
*
|
|
2553
|
-
*
|
|
2554
|
-
*
|
|
2555
|
-
*
|
|
2346
|
+
* Owns event matching and durable event-automation dispatch.
|
|
2347
|
+
*
|
|
2348
|
+
* Each matching automation is independently idempotent. Aggregate failures propagate
|
|
2349
|
+
* so the provider can retry the original delivery.
|
|
2556
2350
|
*/
|
|
2557
|
-
|
|
2558
|
-
|
|
2559
|
-
|
|
2560
|
-
|
|
2561
|
-
|
|
2562
|
-
|
|
2563
|
-
|
|
2564
|
-
|
|
2565
|
-
|
|
2566
|
-
|
|
2567
|
-
|
|
2568
|
-
|
|
2569
|
-
|
|
2570
|
-
|
|
2571
|
-
|
|
2572
|
-
|
|
2351
|
+
/** Bind provider delivery identity to one automation's durable dispatch. */
|
|
2352
|
+
function eventAutomationDispatchKey(taskId, namespace, eventKey) {
|
|
2353
|
+
return `event-automation:${createHash("sha256").update(`${taskId}\0${namespace}\0${eventKey}`).digest("hex").slice(0, 32)}`;
|
|
2354
|
+
}
|
|
2355
|
+
/** Render plain agent input for one matching event automation. */
|
|
2356
|
+
function eventInput(task, event, outcomes, catalog, author) {
|
|
2357
|
+
const guidance = eventGuidance(catalog, event.namespace, event.eventType);
|
|
2358
|
+
return renderTaskInput({
|
|
2359
|
+
about: task.trigger.label,
|
|
2360
|
+
event: event.eventType,
|
|
2361
|
+
source: event.namespace,
|
|
2362
|
+
creator: slackMention(task.createdBy.slackUserId),
|
|
2363
|
+
instructions: automationTaskText(task.task),
|
|
2364
|
+
...task.task.kind === "skill" ? { skill: task.task.skill } : void 0,
|
|
2365
|
+
outcomes,
|
|
2366
|
+
guidance,
|
|
2367
|
+
trustedSummary: event.trustedSummary,
|
|
2368
|
+
trustedSummaryMaxLength: EVENT_SUMMARY_MAX_LENGTH,
|
|
2369
|
+
verifiedDetails: event.data,
|
|
2370
|
+
authorText: eventAuthorText(author),
|
|
2371
|
+
externalText: event.untrustedText,
|
|
2372
|
+
externalTextMaxLength: EVENT_TEXT_MAX_LENGTH
|
|
2573
2373
|
});
|
|
2574
2374
|
}
|
|
2375
|
+
/**
|
|
2376
|
+
* Match a normalized event and dispatch every matching automation.
|
|
2377
|
+
*
|
|
2378
|
+
* Plugins publish one copy of an occurrence for each scope, such as a pull
|
|
2379
|
+
* request and its repository. All copies share one event key. An automation
|
|
2380
|
+
* with no identifier matches every copy, and the dispatch key and the run
|
|
2381
|
+
* limit both use the event key, so it runs and counts once.
|
|
2382
|
+
*/
|
|
2383
|
+
async function ingestEventAutomations(input, options) {
|
|
2384
|
+
const event = eventSchema$1.parse(input);
|
|
2385
|
+
const db = getDb();
|
|
2386
|
+
const nowMs = options.nowMs ?? Date.now();
|
|
2387
|
+
const catalog = getEventCatalog();
|
|
2388
|
+
const [matches = []] = await findMatchingEventAutomations(db, [event], options.teamId, catalog);
|
|
2389
|
+
const tasks = matches.filter((task) => slackChannelMessageRunsAutomation(event, task));
|
|
2390
|
+
if (tasks.length === 0) return { dispatched: 0 };
|
|
2391
|
+
const author = await resolveEventAuthor(event);
|
|
2392
|
+
let dispatched = 0;
|
|
2393
|
+
const errors = [];
|
|
2394
|
+
for (const task of tasks) try {
|
|
2395
|
+
const skill = task.task.kind === "skill" ? task.task.skill : void 0;
|
|
2396
|
+
if (skill && !await findAutomationSkill(skill)) {
|
|
2397
|
+
const reason = missingAutomationSkillReason(skill);
|
|
2398
|
+
if (await blockEventAutomation(db, task.id, reason)) await notifyAutomationBlocked({
|
|
2399
|
+
automationId: task.id,
|
|
2400
|
+
kind: "event",
|
|
2401
|
+
reason
|
|
2402
|
+
});
|
|
2403
|
+
continue;
|
|
2404
|
+
}
|
|
2405
|
+
const idempotencyKey = eventAutomationDispatchKey(task.id, event.namespace, event.eventKey);
|
|
2406
|
+
if (await admitEventAutomationRun({
|
|
2407
|
+
automationId: task.id,
|
|
2408
|
+
nowMs,
|
|
2409
|
+
runKey: idempotencyKey
|
|
2410
|
+
}) === "limited") {
|
|
2411
|
+
const reason = eventAutomationRunLimitReason();
|
|
2412
|
+
logWarn("event_automation.run_limit.exceeded", {
|
|
2413
|
+
"app.task.id": task.id,
|
|
2414
|
+
"app.task.type": "event"
|
|
2415
|
+
});
|
|
2416
|
+
if (await blockEventAutomation(db, task.id, reason)) {
|
|
2417
|
+
captureMessage("Event automation blocked by run limit", {
|
|
2418
|
+
level: "warning",
|
|
2419
|
+
fingerprint: ["event_automation.run_limit.blocked"],
|
|
2420
|
+
tags: {
|
|
2421
|
+
"app.event.namespace": event.namespace,
|
|
2422
|
+
"app.task.type": "event"
|
|
2423
|
+
},
|
|
2424
|
+
extra: {
|
|
2425
|
+
"app.event.event_type": event.eventType,
|
|
2426
|
+
"app.event_automation.max_runs": botConfig.maxEventAutomationRuns,
|
|
2427
|
+
"app.event_automation.run_window_ms": botConfig.eventAutomationRunWindowMs,
|
|
2428
|
+
"app.event_automation.resource_type": task.trigger.resourceType ?? "any",
|
|
2429
|
+
"app.task.id": task.id
|
|
2430
|
+
}
|
|
2431
|
+
});
|
|
2432
|
+
await notifyAutomationBlocked({
|
|
2433
|
+
automationId: task.id,
|
|
2434
|
+
kind: "event",
|
|
2435
|
+
reason
|
|
2436
|
+
});
|
|
2437
|
+
}
|
|
2438
|
+
continue;
|
|
2439
|
+
}
|
|
2440
|
+
const replyThreadTs = slackChannelMessageReplyThreadTs(event);
|
|
2441
|
+
const destination = replyThreadTs ? {
|
|
2442
|
+
...task.destination,
|
|
2443
|
+
threadTs: replyThreadTs
|
|
2444
|
+
} : task.destination;
|
|
2445
|
+
const outcomes = effectiveTaskOutcomes(task.outcomes, destination);
|
|
2446
|
+
const credentialSubject = task.credentialMode === "creator" ? {
|
|
2447
|
+
type: "user",
|
|
2448
|
+
userId: task.createdBy.slackUserId,
|
|
2449
|
+
allowedWhen: "event-automation",
|
|
2450
|
+
taskId: task.id
|
|
2451
|
+
} : void 0;
|
|
2452
|
+
const dispatch = await dispatchEventAutomation({
|
|
2453
|
+
automationId: task.id,
|
|
2454
|
+
conversationWorkQueue: options.queue,
|
|
2455
|
+
nowMs,
|
|
2456
|
+
options: {
|
|
2457
|
+
idempotencyKey,
|
|
2458
|
+
...credentialSubject ? { credentialSubject } : void 0,
|
|
2459
|
+
destination,
|
|
2460
|
+
destinationVisibility: task.destinationVisibility,
|
|
2461
|
+
input: eventInput(task, event, outcomes, catalog, author),
|
|
2462
|
+
...skill ? { skill } : void 0,
|
|
2463
|
+
metadata: { eventAutomationId: task.id },
|
|
2464
|
+
replyAttribution: automationReplyAttribution(task.title),
|
|
2465
|
+
outcomes
|
|
2466
|
+
}
|
|
2467
|
+
});
|
|
2468
|
+
await recordEventAutomationRunStarted(db, {
|
|
2469
|
+
automation: task,
|
|
2470
|
+
dispatchId: dispatch.id,
|
|
2471
|
+
nowMs
|
|
2472
|
+
});
|
|
2473
|
+
if (dispatch.status === "created") dispatched += 1;
|
|
2474
|
+
} catch (error) {
|
|
2475
|
+
errors.push(error);
|
|
2476
|
+
}
|
|
2477
|
+
if (errors.length > 0) throw new AggregateError(errors, "Failed to dispatch one or more event automations");
|
|
2478
|
+
return { dispatched };
|
|
2479
|
+
}
|
|
2575
2480
|
// src/chat/ingress/slack-message-telemetry.ts
|
|
2576
2481
|
function field(value, pattern) {
|
|
2577
2482
|
if (value === void 0) return "missing";
|
|
@@ -2898,14 +2803,12 @@ async function routeParsedMessage(args) {
|
|
|
2898
2803
|
text: args.event.text ?? "",
|
|
2899
2804
|
isExplicitMention: isMention
|
|
2900
2805
|
});
|
|
2901
|
-
const
|
|
2902
|
-
allowedBotUserIds: args.allowedBotUserIds,
|
|
2903
|
-
allowedDomains: args.allowedDomains,
|
|
2806
|
+
const isAuthorTrusted = () => isTrustedSlackAuthor({
|
|
2904
2807
|
state: args.state,
|
|
2905
2808
|
teamId: args.installation.teamId,
|
|
2906
2809
|
user: args.event.user
|
|
2907
2810
|
});
|
|
2908
|
-
if (!stopDecision && route === "mention" && !await
|
|
2811
|
+
if (!stopDecision && route === "mention" && !await isAuthorTrusted()) return;
|
|
2909
2812
|
await bindSlackAuthorIdentity(message, args.installation);
|
|
2910
2813
|
const conversationId = await resolveSlackConversationId({
|
|
2911
2814
|
canonicalThreadId,
|
|
@@ -2962,7 +2865,7 @@ async function routeParsedMessage(args) {
|
|
|
2962
2865
|
const closeAnswered = async () => {
|
|
2963
2866
|
if (message.author.isBot === true) return;
|
|
2964
2867
|
await closeReviewItemsAnsweredByReply({
|
|
2965
|
-
...route === "subscribed" ? { canAnswer:
|
|
2868
|
+
...route === "subscribed" ? { canAnswer: isAuthorTrusted } : void 0,
|
|
2966
2869
|
conversationId,
|
|
2967
2870
|
delivery: {
|
|
2968
2871
|
queue: args.queue,
|
|
@@ -3140,8 +3043,6 @@ async function handleSlackEvent(args) {
|
|
|
3140
3043
|
conversationStore: args.services.conversationStore,
|
|
3141
3044
|
queue: args.services.queue,
|
|
3142
3045
|
receivedAtMs,
|
|
3143
|
-
allowedBotUserIds: args.services.allowedBotUserIds ?? [],
|
|
3144
|
-
allowedDomains: args.services.allowedDomains ?? [],
|
|
3145
3046
|
runAfterUnlock: (task) => {
|
|
3146
3047
|
afterUnlock = task;
|
|
3147
3048
|
},
|
|
@@ -3200,9 +3101,7 @@ async function handleSlackWebhook(args) {
|
|
|
3200
3101
|
adapter,
|
|
3201
3102
|
body,
|
|
3202
3103
|
getUserTokenStore: () => getUserTokenStore(args.services),
|
|
3203
|
-
isAuthorAllowed: (userId, installation) =>
|
|
3204
|
-
allowedBotUserIds: args.services.allowedBotUserIds ?? [],
|
|
3205
|
-
allowedDomains: args.services.allowedDomains ?? [],
|
|
3104
|
+
isAuthorAllowed: (userId, installation) => isTrustedSlackAuthor({
|
|
3206
3105
|
state,
|
|
3207
3106
|
teamId: installation.teamId,
|
|
3208
3107
|
user: userId
|
|
@@ -3515,6 +3414,98 @@ async function publicArtifactGET(args) {
|
|
|
3515
3414
|
return new Response("Internal Server Error", { status: 500 });
|
|
3516
3415
|
}
|
|
3517
3416
|
}
|
|
3417
|
+
// src/chat/events/app-publisher.ts
|
|
3418
|
+
const WATCH_MATCH_CONCURRENCY = 4;
|
|
3419
|
+
/** Build the core event publisher used by plugin routes. */
|
|
3420
|
+
function createEventAppPublisher(args) {
|
|
3421
|
+
return {
|
|
3422
|
+
async hasMatch(events) {
|
|
3423
|
+
const work = args.conversationWork();
|
|
3424
|
+
const eventAutomationTeamId = await resolveBotSlackTeamId();
|
|
3425
|
+
const limit = pLimit(WATCH_MATCH_CONCURRENCY);
|
|
3426
|
+
const [subscriptions, tasks] = await Promise.all([Promise.all(events.map((event) => limit(() => findMatchingWatches({
|
|
3427
|
+
data: event.data,
|
|
3428
|
+
eventType: event.eventType,
|
|
3429
|
+
namespace: event.namespace,
|
|
3430
|
+
identifier: event.identifier,
|
|
3431
|
+
state: work.state
|
|
3432
|
+
})))), eventAutomationTeamId ? findMatchingEventAutomations(getDb(), events, eventAutomationTeamId, getEventCatalog()) : Promise.resolve([])]);
|
|
3433
|
+
return [...subscriptions, ...tasks].some((matched) => matched.length > 0);
|
|
3434
|
+
},
|
|
3435
|
+
async neededMatchKeys(input) {
|
|
3436
|
+
const work = args.conversationWork();
|
|
3437
|
+
const eventAutomationTeamId = await resolveBotSlackTeamId();
|
|
3438
|
+
const [watchKeys, taskKeys] = await Promise.all([collectEventMatchKeys({
|
|
3439
|
+
eventTypes: input.eventTypes,
|
|
3440
|
+
identifiers: input.identifiers,
|
|
3441
|
+
namespace: input.namespace,
|
|
3442
|
+
state: work.state
|
|
3443
|
+
}), eventAutomationTeamId ? collectEventAutomationMatchKeys(getDb(), {
|
|
3444
|
+
catalog: getEventCatalog(),
|
|
3445
|
+
...input.data ? { data: input.data } : void 0,
|
|
3446
|
+
eventTypes: input.eventTypes,
|
|
3447
|
+
identifiers: input.identifiers,
|
|
3448
|
+
namespace: input.namespace,
|
|
3449
|
+
teamId: eventAutomationTeamId
|
|
3450
|
+
}) : Promise.resolve([])]);
|
|
3451
|
+
return [.../* @__PURE__ */ new Set([...watchKeys, ...taskKeys])].sort();
|
|
3452
|
+
},
|
|
3453
|
+
async publish(event) {
|
|
3454
|
+
const work = args.conversationWork();
|
|
3455
|
+
const queue = work.queue ?? getVercelConversationWorkQueue();
|
|
3456
|
+
const eventAutomationTeamId = await resolveBotSlackTeamId();
|
|
3457
|
+
await Promise.all([ingestEvent(event, {
|
|
3458
|
+
queue,
|
|
3459
|
+
slackTeamId: eventAutomationTeamId,
|
|
3460
|
+
state: work.state
|
|
3461
|
+
}), eventAutomationTeamId ? ingestEventAutomations(event, {
|
|
3462
|
+
queue,
|
|
3463
|
+
teamId: eventAutomationTeamId
|
|
3464
|
+
}) : Promise.resolve()]);
|
|
3465
|
+
}
|
|
3466
|
+
};
|
|
3467
|
+
}
|
|
3468
|
+
// src/chat/agent-dispatch/identity.ts
|
|
3469
|
+
/**
|
|
3470
|
+
* Build the one entry point that starts work for a person whom a plugin
|
|
3471
|
+
* names, from a webhook route or a heartbeat.
|
|
3472
|
+
*
|
|
3473
|
+
* The person must be a Trusted author with a User (`findTrustedUser`): a
|
|
3474
|
+
* `subjectId` of the calling plugin's provider that the OAuth account-linking
|
|
3475
|
+
* flow linked, or a `verifiedEmail` that is the User's primary email. Without
|
|
3476
|
+
* a Slack bot, nothing matches.
|
|
3477
|
+
*
|
|
3478
|
+
* On a match, the input is that person's first Message in a new public
|
|
3479
|
+
* Conversation, as if they sent it from the dashboard. The Conversation has no
|
|
3480
|
+
* Slack Destination.
|
|
3481
|
+
*/
|
|
3482
|
+
function createIdentityDispatcher(args) {
|
|
3483
|
+
const notLinked = (plugin, reason) => {
|
|
3484
|
+
logInfo("dispatch.identity.not_linked", {
|
|
3485
|
+
"app.plugin.name": plugin,
|
|
3486
|
+
"app.dispatch.identity.reason": reason
|
|
3487
|
+
});
|
|
3488
|
+
return { status: "not_linked" };
|
|
3489
|
+
};
|
|
3490
|
+
return async (plugin, options) => {
|
|
3491
|
+
const request = identityDispatchOptionsSchema.parse(options);
|
|
3492
|
+
const trust = await findTrustedUser("subjectId" in request ? {
|
|
3493
|
+
provider: plugin,
|
|
3494
|
+
subjectId: request.subjectId
|
|
3495
|
+
} : { verifiedEmail: request.verifiedEmail });
|
|
3496
|
+
if (trust.status === "untrusted") return notLinked(plugin, trust.reason);
|
|
3497
|
+
const accepted = await createAndEnqueueConversation({
|
|
3498
|
+
actor: webActorFromUser(trust.user),
|
|
3499
|
+
idempotencyKey: `${plugin}:${request.idempotencyKey}`,
|
|
3500
|
+
message: request.input,
|
|
3501
|
+
visibility: "public"
|
|
3502
|
+
}, { queue: args.conversationWorkQueue() });
|
|
3503
|
+
return {
|
|
3504
|
+
conversationId: accepted.conversationId,
|
|
3505
|
+
status: accepted.status === "duplicate" ? "already_exists" : "created"
|
|
3506
|
+
};
|
|
3507
|
+
};
|
|
3508
|
+
}
|
|
3518
3509
|
// src/api/acp/conversations.ts
|
|
3519
3510
|
const EVENT_PAGE_SIZE = 50;
|
|
3520
3511
|
async function hasConversationAccess(conversationId, user) {
|
|
@@ -7087,7 +7078,11 @@ function createMcpHttpHandler(options) {
|
|
|
7087
7078
|
state: options.state,
|
|
7088
7079
|
token
|
|
7089
7080
|
}) : void 0;
|
|
7090
|
-
const
|
|
7081
|
+
const email = grant ? parseEmail(grant.email) : void 0;
|
|
7082
|
+
const user = grant && email && isAllowedDomain(email.domain, {
|
|
7083
|
+
allowedDomains: options.allowedDomains,
|
|
7084
|
+
ifNoDomains: "deny"
|
|
7085
|
+
}) ? await resolveViewerUser(grant.email) : void 0;
|
|
7091
7086
|
if (!grant || !user) return unauthorized(requestUrls, token !== void 0);
|
|
7092
7087
|
if (c.req.method !== "POST") return new Response(null, {
|
|
7093
7088
|
status: 405,
|
|
@@ -7183,6 +7178,43 @@ async function handleAcpAuthorizationPage(args) {
|
|
|
7183
7178
|
});
|
|
7184
7179
|
return renderResult(args.agentName, result);
|
|
7185
7180
|
}
|
|
7181
|
+
// src/chat/sign-in/allowlist.ts
|
|
7182
|
+
/**
|
|
7183
|
+
* Read the domain list that may use Junior. Slack authors must have a Slack
|
|
7184
|
+
* profile email on one of them, and dashboard Google sign-ins must come from
|
|
7185
|
+
* a Google Workspace account whose `hd` claim is one of them. Slack and the
|
|
7186
|
+
* dashboard share one list. `chat/identities/trust` decides who matches.
|
|
7187
|
+
*/
|
|
7188
|
+
/** Read a list env var: a JSON string array or comma-separated values. */
|
|
7189
|
+
function readEnvList(name) {
|
|
7190
|
+
const value = process.env[name]?.trim();
|
|
7191
|
+
if (!value) return void 0;
|
|
7192
|
+
if (!value.startsWith("[")) return value.split(",");
|
|
7193
|
+
let parsed;
|
|
7194
|
+
try {
|
|
7195
|
+
parsed = JSON.parse(value);
|
|
7196
|
+
} catch (error) {
|
|
7197
|
+
throw new Error(`${name} must be a JSON string array`, { cause: error });
|
|
7198
|
+
}
|
|
7199
|
+
const list = z.array(z.string()).safeParse(parsed);
|
|
7200
|
+
if (!list.success) throw new Error(`${name} must be a JSON string array`);
|
|
7201
|
+
return list.data;
|
|
7202
|
+
}
|
|
7203
|
+
/**
|
|
7204
|
+
* Resolve the allowed domains: the `createApp` option when set, else
|
|
7205
|
+
* `JUNIOR_ALLOWED_DOMAINS`. An empty list allows every domain.
|
|
7206
|
+
*/
|
|
7207
|
+
function resolveAllowedDomains(allowedDomains) {
|
|
7208
|
+
return [...new Set((allowedDomains ?? readEnvList("JUNIOR_ALLOWED_DOMAINS") ?? []).map((value) => value.trim().toLowerCase()).filter(Boolean))];
|
|
7209
|
+
}
|
|
7210
|
+
/**
|
|
7211
|
+
* Fail startup on the removed Google-specific names. Ignoring them would
|
|
7212
|
+
* leave the list empty, which lets every Slack workspace member in.
|
|
7213
|
+
*/
|
|
7214
|
+
function assertNoLegacyAllowedDomains(dashboardOptionKeys) {
|
|
7215
|
+
if (dashboardOptionKeys.includes("allowedGoogleDomains")) throw new Error("dashboard.allowedGoogleDomains was removed; set createApp({ allowedDomains }) instead");
|
|
7216
|
+
if (process.env["JUNIOR_DASHBOARD_GOOGLE_DOMAINS"]?.trim()) throw new Error("JUNIOR_DASHBOARD_GOOGLE_DOMAINS was removed; set JUNIOR_ALLOWED_DOMAINS instead");
|
|
7217
|
+
}
|
|
7186
7218
|
// src/chat/sign-in/auth.ts
|
|
7187
7219
|
/**
|
|
7188
7220
|
* Google sign-in session for the dashboard.
|
|
@@ -7267,7 +7299,10 @@ function createBetterAuth(config) {
|
|
|
7267
7299
|
if (!token.idToken) return null;
|
|
7268
7300
|
const claims = readGoogleClaims(token.idToken);
|
|
7269
7301
|
if (!claims) return null;
|
|
7270
|
-
if (!isAllowedDomain(claims.hd,
|
|
7302
|
+
if (!isAllowedDomain(claims.hd, {
|
|
7303
|
+
allowedDomains,
|
|
7304
|
+
ifNoDomains: "allow"
|
|
7305
|
+
})) return null;
|
|
7271
7306
|
return {
|
|
7272
7307
|
user: {
|
|
7273
7308
|
email: claims.email,
|
|
@@ -7675,7 +7710,9 @@ async function createApp(options) {
|
|
|
7675
7710
|
const previousExperimentalFeatures = getExperimentalFeatures();
|
|
7676
7711
|
const previousBriefsConfig = setBriefsConfig(options?.briefs);
|
|
7677
7712
|
const previousDashboardLinkOptions = setDashboardConversationLinkOptions(dashboard);
|
|
7713
|
+
let previousTrustConfig;
|
|
7678
7714
|
const restoreRuntimeConfig$1 = () => {
|
|
7715
|
+
if (previousTrustConfig) setTrustConfig(previousTrustConfig);
|
|
7679
7716
|
pluginCatalogRuntime.setConfig(previousPluginCatalogConfig);
|
|
7680
7717
|
setPlugins(previousPlugins);
|
|
7681
7718
|
setConfigDefaults(previousConfigDefaults);
|
|
@@ -7694,6 +7731,7 @@ async function createApp(options) {
|
|
|
7694
7731
|
let sandboxEgressTracePropagationDomains = [];
|
|
7695
7732
|
let signInConfig;
|
|
7696
7733
|
let allowedDomains = [];
|
|
7734
|
+
let dispatchForIdentity;
|
|
7697
7735
|
try {
|
|
7698
7736
|
sandboxEgressTracePropagationDomains = normalizeSandboxEgressTracePropagationDomains(options?.sandbox?.egressTracePropagationDomains);
|
|
7699
7737
|
setSandboxResourceConfig(options?.sandbox);
|
|
@@ -7707,7 +7745,12 @@ async function createApp(options) {
|
|
|
7707
7745
|
setSlackReactionConfig(options?.slack ?? {});
|
|
7708
7746
|
assertNoLegacyAllowedDomains(Object.keys(dashboard ?? {}));
|
|
7709
7747
|
allowedDomains = resolveAllowedDomains(options?.allowedDomains);
|
|
7748
|
+
previousTrustConfig = setTrustConfig({
|
|
7749
|
+
allowedBotUserIds: options?.slack?.allowedBotUserIds ?? [],
|
|
7750
|
+
allowedDomains
|
|
7751
|
+
});
|
|
7710
7752
|
if (allowedDomains.length === 0) logWarn("app.allowed_domains.unset", { "app.reason": "allowedDomains is empty, so any Slack workspace member can use the bot" });
|
|
7753
|
+
dispatchForIdentity = createIdentityDispatcher({ conversationWorkQueue: () => conversationWorkQueue });
|
|
7711
7754
|
if (dashboard && !dashboard.disabled) signInConfig = resolveSignInAuthConfig(botConfig.userName, allowedDomains, dashboard);
|
|
7712
7755
|
if (shouldValidatePluginCatalog) {
|
|
7713
7756
|
pluginCatalogRuntime.getSignature();
|
|
@@ -7715,6 +7758,7 @@ async function createApp(options) {
|
|
|
7715
7758
|
validatePluginEgressCredentialHooks(configuredPlugins?.registrations ?? []);
|
|
7716
7759
|
}
|
|
7717
7760
|
pluginRoutes = getPluginRoutes({
|
|
7761
|
+
dispatchForIdentity,
|
|
7718
7762
|
events,
|
|
7719
7763
|
showReviewItem: createSlackReviewItemShow(getProductionSlackAdapter)
|
|
7720
7764
|
});
|
|
@@ -7733,6 +7777,7 @@ async function createApp(options) {
|
|
|
7733
7777
|
messageId: delivery.messageId
|
|
7734
7778
|
})) ?? getVercelConversationWorkQueue();
|
|
7735
7779
|
const pluginTaskQueue = options?.pluginTaskQueue?.(processPluginTask);
|
|
7780
|
+
const sendPluginTask = pluginTaskQueue ? (message) => pluginTaskQueue.send(message) : sendVercelPluginTask;
|
|
7736
7781
|
const backgroundCompactionQueue = options?.backgroundCompactionQueue?.((message) => processBackgroundCompaction(message)) ?? vercelBackgroundCompactionQueue;
|
|
7737
7782
|
const attachmentStorage = getAttachmentStorage();
|
|
7738
7783
|
const agentRunner = createAgentRunner(executeAgentRun, {
|
|
@@ -7754,7 +7799,7 @@ async function createApp(options) {
|
|
|
7754
7799
|
conversationWorkOptions ??= options?.conversationWork ?? createProductionConversationWorkOptions({
|
|
7755
7800
|
agentRunner,
|
|
7756
7801
|
queue: conversationWorkQueue,
|
|
7757
|
-
|
|
7802
|
+
sendPluginTask,
|
|
7758
7803
|
services: runtimeServiceOverrides,
|
|
7759
7804
|
waitUntil: (task) => {
|
|
7760
7805
|
backgroundWork.add(task);
|
|
@@ -7833,8 +7878,6 @@ async function createApp(options) {
|
|
|
7833
7878
|
queue: conversationWorkQueue,
|
|
7834
7879
|
services: runtimeServiceOverrides
|
|
7835
7880
|
}),
|
|
7836
|
-
allowedBotUserIds: options?.slack?.allowedBotUserIds ?? [],
|
|
7837
|
-
allowedDomains,
|
|
7838
7881
|
autoJoinNewChannels: options?.slack?.autoJoinNewChannels === true
|
|
7839
7882
|
};
|
|
7840
7883
|
const app = new Hono();
|
|
@@ -7936,6 +7979,7 @@ async function createApp(options) {
|
|
|
7936
7979
|
app.get("/api/internal/heartbeat", (c) => {
|
|
7937
7980
|
return GET$3(c.req.raw, waitUntil, {
|
|
7938
7981
|
conversationWorkQueue,
|
|
7982
|
+
dispatchForIdentity,
|
|
7939
7983
|
events,
|
|
7940
7984
|
showReviewItem: createSlackReviewItemShow(getProductionSlackAdapter)
|
|
7941
7985
|
});
|