@sentry/junior 0.310.0 → 0.312.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-BhKpjpGD.js → adapter-context-BRjEWRy1.js} +2 -2
- package/dist/adapter-iIq7ihf7.js +259 -0
- package/dist/{admin-tgZEZAk2.js → admin-DhInw5K9.js} +1 -2
- package/dist/{agent-runner-D9cvNlQl.js → agent-runner-C9iDurwX.js} +6507 -7721
- package/dist/api/schema.d.ts +2 -2
- package/dist/api/schema.js +7 -6
- package/dist/api.d.ts +21 -3
- package/dist/api.js +1625 -535
- package/dist/{app-B_7Wn0en.d.ts → app-DRFrC8Mw.d.ts} +14 -10
- package/dist/app.d.ts +2 -2
- package/dist/app.js +454 -994
- package/dist/{background-compaction-queue-BGHqkhkY.js → background-compaction-queue-DrKi7w3d.js} +10 -85
- package/dist/callback-mFlTUWWx.js +75 -0
- package/dist/{catalog-runtime-BxwzbLKY.js → catalog-runtime-D7xapBAX.js} +1 -1
- package/dist/channel-access-CJGfNTdn.js +221 -0
- package/dist/child-message-DcsritGf.js +179 -0
- package/dist/cli/chat.js +18 -19
- package/dist/cli/check.js +23 -29
- package/dist/cli/init.js +1 -7
- package/dist/cli/main.js +3 -7
- package/dist/cli/plugins.js +8 -7
- package/dist/cli/run.d.ts +1 -2
- package/dist/cli/run.js +1 -2
- 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-Dkt2Le2b.js → config-kXB2Y5tl.js} +294 -28
- package/dist/{continue-in-slack-BWVwePKD.js → continue-in-slack-O6pV5004.js} +7 -7
- package/dist/{conversation-feed-Ci6YD1N-.js → conversation-feed-uNOv_x68.js} +87 -24
- package/dist/{conversation-privacy-C39g8BY4.js → conversation-privacy-L4ja1_W6.js} +1 -1
- package/dist/{conversation-turn-CBlZIH02.js → conversation-turn-CeLbHqdw.js} +56 -49
- package/dist/{credential-sync-vGnrB0BY.js → credential-sync-I8VBGk05.js} +16 -16
- package/dist/{projection-jZSlEAXG.js → credentialed-Cb6E2phL.js} +16268 -16821
- package/dist/{db-B4Hjxr-u.d.ts → db-BbC5stfa.d.ts} +13 -6
- package/dist/{db-CFZggNoy.js → db-LAyyX8tk.js} +1698 -1046
- package/dist/{executor-BPkZDx5-.js → executor-SCub-fAq.js} +552 -181
- package/dist/{html-2r2KmLwi.js → html-BCZ3Xtb_.js} +6 -6
- package/dist/{session-stop-BfY4rhJs.js → ingest-BDf3D50j.js} +2134 -2553
- package/dist/{install-C-oE6C_u.js → install-DCFJFkC0.js} +2 -2
- package/dist/instrumentation.js +4 -4
- package/dist/{lineage-CsvrEFQe.js → lineage-B_m-4TJw.js} +2 -2
- package/dist/{stop-DYzjRf2U.js → list-CN2QA2R9.js} +1656 -685
- package/dist/{logging-D5gkyvnK.js → logging-dQ9ZRGQ8.js} +47 -9
- package/dist/media-CYm1QD8T.js +2356 -0
- package/dist/{message-DwvJ-I3w.js → message-DSXGj1hM.js} +19 -29
- package/dist/{model-input-MAq2881y.js → model-input--TrP9hYV.js} +3 -3
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +4 -3
- package/dist/{oauth-callback-server-DIF6Li06.js → oauth-callback-server-DHCZC6B4.js} +2 -2
- package/dist/{oauth-relay-DPE-wrwO.js → oauth-relay-pPMGnDZt.js} +1 -1
- package/dist/{registry-BBkWFCl8.js → registry-CZOzddwu.js} +5 -8
- package/dist/{resolve-B38MkHXE.js → resolve-cKOQ14Dh.js} +3 -3
- package/dist/{result-BaqSZcJb.js → result-DcvEOe1r.js} +119 -93
- package/dist/result-event-type-BdIJuZxg.js +48 -0
- package/dist/rule-DAxQY-1h.js +20 -0
- package/dist/{runner-11h8PrHh.js → runner-DBfUW44l.js} +14 -16
- package/dist/{sandbox-egress-signals-CTcACAtJ.js → sandbox-egress-signals-BVF_xAm1.js} +1 -1
- package/dist/{schema-DriSvB40.d.ts → schema-BEHKxr4I.d.ts} +861 -298
- package/dist/{schema-obw5jvR4.js → schema-Bk9Nm2E8.js} +344 -153
- package/dist/{service-account-Bx93N1n1.js → service-account-CVYsFjty.js} +3 -3
- package/dist/{service-account-Zc5bUcIJ.js → service-account-Ts4ulcrV.js} +68 -68
- package/dist/{skills-C8Npu5zO.js → skills-VTnhAJWm.js} +2 -2
- package/dist/{slack-conversation-unfurl-DlRVA02H.js → slack-conversation-unfurl-fuLnF1jE.js} +9 -11
- package/dist/{spawn-CXr58R0x.js → spawn-vxAarlX5.js} +6 -6
- package/dist/start-conversation-CEn2KH1A.js +941 -0
- package/dist/{state-CGrGVeQC.js → state-C1P3_Ywk.js} +4 -4
- package/dist/statuses-_cRJHXK7.js +150 -0
- package/dist/store-DFZaN-Ix.js +492 -0
- package/dist/task-queue-Cx4Lmjyk.js +90 -0
- package/dist/task-runner-CbTwFA6k.js +1432 -0
- package/dist/{thread-context-Dyj1KWaY.js → thread-context-BkAZDTX2.js} +13 -11
- package/dist/thread-state-DhPndWi1.js +5625 -0
- package/dist/{validation-DxVNIxA0.js → validation-nIzMtAVJ.js} +1 -1
- package/dist/{task-queue-CaZffYaH.js → vercel-queue-hW90XzbG.js} +93 -172
- package/dist/{version-Cr7Z71yG.js → version-Brbtz4Qf.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{warmup-C6LOZ2d2.js → warmup-BDA5myRK.js} +5832 -4567
- package/dist/web-message-id-C6P83ans.js +10 -0
- package/dist/{worker-CUBtu1Li.js → worker-D63RcaVD.js} +20 -8
- package/migrations/0126_artifact_drop_public.sql +8 -0
- package/migrations/0127_artifact_path.sql +4 -0
- package/migrations/0128_artifact_path_index.sql +1 -0
- package/migrations/0129_review_item_answered_index.sql +1 -0
- package/migrations/0130_review_item_status_index.sql +1 -0
- package/migrations/0131_brief_outcome_status.sql +1 -0
- package/migrations/0132_brief_outcome_status_backfill.sql +7 -0
- package/migrations/0133_brief_created_at_index.sql +1 -0
- package/migrations/0134_slack_person_search_index.sql +1 -0
- package/migrations/0135_code_change_size.sql +3 -0
- package/migrations/0136_merge_conflict_notice_dismiss.sql +16 -0
- package/migrations/0137_inbox_snoozes.sql +27 -0
- package/migrations/0138_code_change_search_index.sql +2 -0
- package/migrations/0139_review_item_owner.sql +22 -0
- package/migrations/0140_review_item_owner_index.sql +1 -0
- package/migrations/0141_memory_core_adoption.sql +89 -0
- package/migrations/0142_memory_core_indexes.sql +17 -0
- package/migrations/0143_todos.sql +14 -0
- package/migrations/0144_inbox_items.sql +32 -0
- package/migrations/0145_todo_changed_by_agent.sql +1 -0
- package/migrations/0146_inbox_item_subject_title_parts.sql +1 -0
- package/migrations/0147_inbox_snooze_wake_reason.sql +1 -0
- package/migrations/0148_authorization_request_index.sql +1 -0
- package/migrations/0149_conversation_metadata.sql +10 -0
- package/migrations/0150_conversation_metadata_fill.sql +39 -0
- package/migrations/0151_conversation_search_index.sql +1 -0
- package/migrations/0152_inbox_item_legacy_automation_keys.sql +21 -0
- package/migrations/0153_artifact_expiry.sql +1 -0
- package/migrations/0154_artifact_permanent_sha_index.sql +1 -0
- package/migrations/0155_artifact_drop_public_sha_index.sql +3 -0
- package/migrations/0156_conversation_kind_lead.sql +6 -0
- package/migrations/0157_conversation_lead_actor_index.sql +1 -0
- package/migrations/meta/0126_snapshot.json +5488 -0
- package/migrations/meta/0127_snapshot.json +5519 -0
- package/migrations/meta/0128_snapshot.json +5519 -0
- package/migrations/meta/0129_snapshot.json +5547 -0
- package/migrations/meta/0130_snapshot.json +5563 -0
- package/migrations/meta/0131_snapshot.json +5569 -0
- package/migrations/meta/0132_snapshot.json +5569 -0
- package/migrations/meta/0133_snapshot.json +5590 -0
- package/migrations/meta/0134_snapshot.json +5606 -0
- package/migrations/meta/0135_snapshot.json +5624 -0
- package/migrations/meta/0136_snapshot.json +5624 -0
- package/migrations/meta/0137_snapshot.json +5864 -0
- package/migrations/meta/0138_snapshot.json +5894 -0
- package/migrations/meta/0139_snapshot.json +5898 -0
- package/migrations/meta/0140_snapshot.json +5919 -0
- package/migrations/meta/0141_snapshot.json +6429 -0
- package/migrations/meta/0142_snapshot.json +6457 -0
- package/migrations/meta/0143_snapshot.json +6434 -0
- package/migrations/meta/0144_snapshot.json +6434 -0
- package/migrations/meta/0145_snapshot.json +6440 -0
- package/migrations/meta/0146_snapshot.json +6446 -0
- package/migrations/meta/0147_snapshot.json +6452 -0
- package/migrations/meta/0148_snapshot.json +6474 -0
- package/migrations/meta/0149_snapshot.json +6490 -0
- package/migrations/meta/0150_snapshot.json +6490 -0
- package/migrations/meta/0151_snapshot.json +6505 -0
- package/migrations/meta/0152_snapshot.json +6505 -0
- package/migrations/meta/0153_snapshot.json +6511 -0
- package/migrations/meta/0154_snapshot.json +6533 -0
- package/migrations/meta/0155_snapshot.json +6511 -0
- package/migrations/meta/0156_snapshot.json +6511 -0
- package/migrations/meta/0157_snapshot.json +6527 -0
- package/migrations/meta/_journal.json +224 -0
- package/package.json +7 -8
- package/skills/design-automation-skill/SKILL.md +108 -0
- package/dist/briefs-DKxkoruh.js +0 -395
- package/dist/conversation-M9KZ5JxF.js +0 -1024
- package/dist/prompt-CaMyeCpA.js +0 -910
- package/dist/schedule-DWxZ3kja.js +0 -1146
- package/dist/store-D4FQ1Nml.js +0 -335
- package/dist/task-runner-Dm7BHbGp.js +0 -287
- package/dist/turn-session-routing-CD0BRCex.js +0 -263
- package/dist/turn-user-message-9IxeEv5v.js +0 -364
- package/dist/users-CaUAYMb3.js +0 -181
- package/dist/viewer-AHldghAD.js +0 -212
- package/dist/web-message-id-BT8Mg8LL.js +0 -418
package/dist/app.js
CHANGED
|
@@ -1,46 +1,48 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { d as
|
|
3
|
-
import { $ as
|
|
4
|
-
import { A as JUNIOR_CONTEXT_COMPACTION_CALLBACK_ROUTE, E as withSpan,
|
|
5
|
-
import {
|
|
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 { Ao as getSlackClient, Ar as getDispatchConversationId, Bo as getWorkspaceTeamId, Ca as dismissOpenInboxItems, Ci as withScheduledAutomationLock, Dn as normalizeSandboxEgressTracePropagationDomains, Fi as setDashboardConversationLinkOptions, G as setEventEmbeddingsConfig, Hn as resolveRootVisibility, I as projectConversationMessages, Ir as isTerminalDispatchStatus, J as eventIndexLockKey, Jr as openSlackModal, K as EVENT_INDEX_LOCK_TTL_MS, L as setMemoryConfig, La as deleteExpiredInboxSnoozes, Lr as listPendingDispatchMailboxAppends, Nr as getDispatchRecord, Or as confirmDispatchMailboxAppend, Q as storeConversationEventLexemes, S as readPublicArtifact, Si as scheduledRunId, Ti as getDashboardInboxItemLink, Un as backfillConversationEmbeddings, Ur as notifyAutomationBlocked, Vo as runWithWorkspaceTeamId, Vr as markDispatchFailed, W as isEventEmbeddingsEnabled, Wn as createConversationEmbedder, Ya as slackChannelMessageEvent, Yi as automationVersionOf, Yn as listConversationAnnotations, Yr as postSlackEphemeralMessage, _i as listScheduledAutomationsForTeam, _n as clearSandboxEgressSignals, _o as takeDueTimerWatches, an as resolveBaseUrl, b as publicArtifactHeaders, en as isVercelSandboxEgressRequest, g as getRegistrations, ga as syncAutomationAlerts, ja as searchInboxItems, ji as getDashboardTaskLink, l as getPluginApiRoutes, ni as slackEntitySchema, pa as refreshAutomationLastRun, q as embedConversationEvents, qa as SLACK_EVENT_NAMESPACE, r as createUserTokenStore, ra as existingConversationId, ri as slackExternalRefIdSchema, s as createPluginEventPublisher, tn as proxyVercelSandboxEgressRequest, u as getPluginRoutes, ui as slackMention, v as setPlugins, vn as consumeSandboxEgressAuthRequiredSignal, vs as getConfigDefaults, w as unpublishedArtifactHeaders, wi as getDashboardConversationLink, xi as saveScheduledAutomationInLock, xn as parseSandboxEgressCredentialToken, y as validatePlugins, yi as readScheduledAutomation, yn as consumeSandboxEgressPermissionDeniedSignal, ys as setConfigDefaults } from "./credentialed-Cb6E2phL.js";
|
|
2
|
+
import { I as MUTATION_LOCK_TTL_MS, R as fenceLock, d as setBotModelConfig, f as setBotName, gt as getAttachmentStorage, h as snapshotRuntimeConfig, l as resetRuntimeConfig, m as setSlackReactionConfig, n as botConfig, p as setRuntimeLimits, r as getChatConfig, u as restoreRuntimeConfig, z as withLock } from "./config-kXB2Y5tl.js";
|
|
3
|
+
import { $t as resolveActorIdentityId, Ht as resolveViewerUser, Ln as touchConversationDetail, Lt as readActorIdentity, Rn as createSlackDestination, U as conversationCostOf, a as getConversationStore, bt as inboxItemReaderForUserInConversation, cn as recordGoogleSignIn, m as withConversationEventLock, o as getDb, p as deleteMessageLinks, qt as parseAvatarUrl, r as getConversationEventStore, s as getSqlExecutor, st as canActOnInboxItem, t as closeDb, w as withConversationMutationLock, wt as isPluginInboxItem, yn as readConversationAccessFromSql, yt as inboxItemReaderForUser } from "./db-LAyyX8tk.js";
|
|
4
|
+
import { A as JUNIOR_CONTEXT_COMPACTION_CALLBACK_ROUTE, E as withSpan, J as normalizeIdentityEmail, K 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, 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-dQ9ZRGQ8.js";
|
|
5
|
+
import { T as resumeConversationDelivery, _ as buildSlackInboxItemModal, d as scheduledAutomationRunAttributes, f as createSlackInboxItemShow, h as findSlackThreadOwnerId, m as syncInboxItemSlackCards, n as executeAgentRun, p as resolveSlackInboxItemCardConversationId, t as createAgentRunner, u as logScheduledAutomationRunSkipped, v as parseSlackInboxItemClick, x as parseSlackUserInputSubmission, y as parseSlackInboxItemFormTarget } from "./agent-runner-C9iDurwX.js";
|
|
6
|
+
import { Mt as getExperimentalFeatures, Nt as isExperimentalFeatureEnabled, Pt as setExperimentalFeatures, S as parseEmail, _t as deleteTodos, b as isAllowedDomain, dt as renderTaskInput, i as getAuthPausedConversationTurnId, t as ingestEvent, w as setTrustConfig, x as isTrustedSlackAuthor, y as findTrustedUser } from "./ingest-BDf3D50j.js";
|
|
7
|
+
import { a as getSandboxResourceConfig, s as setSandboxResourceConfig } from "./install-DCFJFkC0.js";
|
|
8
|
+
import { n as pluginCatalogRuntime } from "./catalog-runtime-D7xapBAX.js";
|
|
9
|
+
import { $ as runAutoArchiveSweep, At as slackInboundMessageId, B as mcpMessages, Bt as stripLeadingBotMention, Ct as isPublicAddress, Dt as getProductionSlackAdapter, Et as createProductionSlackWebhookServices, F as mcpConversationSchema, Ft as failStoppedDispatch, H as readMcpPendingWork, Ht as SubscribedReplyReason, I as mcpCursorSchema, It as recordSkippedConversationMessage, J as closeInboxItemsAnsweredByReply, K as InboxItemActionError, Kt as readConversationRecordFromSql, L as mcpIdempotencyKeySchema, Lt as createSlackWebApiStatusSender, M as mcpAuthorizationSchema$1, Mt as withNormalizedThreadId, N as mcpConversation, Ot as buildSlackInboundMessage, P as mcpConversationIdSchema, Pt as enqueueAgentDispatch, Q as ingestEventAutomations, R as mcpMessageSchema, Rt as bindMessageAuthorIdentityId, Tt as createProductionConversationWorkOptions, U as readMcpPendingWorkAfterSend, Ut as getThreadStopDecision, V as mcpPendingMessagesSchema, Vt as parseContent, X as reviewItemChange, Y as readInboxItemForUser, Z as createEventAppPublisher, _ as createConversationForViewer, at as createHeartbeatContext, b as encodeConversationCursor, ct as runInboxSnoozeTimers, dt as runSavingsRefillSlice, g as appendConversationMessageForViewer, it as settleEventAutomationRuns, j as mcpAcceptedMessageSchema, jt as normalizeIncomingSlackThreadId, kt as clearSlackPendingReactions, mt as GET$4, n as readConversationFeed, ot as dispatchScheduledAutomation, pt as backfillCacheWarmingGaps, q as actOnInboxItem, rt as automationReplyAttribution, s as readConversationDetail, st as getScheduledAutomationDispatch, vt as readObjectLinkTypes, w as conversationOperations, wt as publicAddressLookup, y as decodeConversationCursor, z as mcpMessageTextSchema, zt as startProcessingReaction } from "./list-CN2QA2R9.js";
|
|
10
|
+
import { n as validatePluginRegistrations, t as validatePluginEgressCredentialHooks } from "./validation-nIzMtAVJ.js";
|
|
11
11
|
import { a as pluginRuntimeRegistrationsFromPluginSet, n as pluginCatalogConfigFromEnv, r as pluginCatalogConfigFromPluginSet, t as defineJuniorPlugins } from "./plugins-Bkk0XRo2.js";
|
|
12
|
-
import {
|
|
13
|
-
import { _ as
|
|
12
|
+
import { i as getStateAdapter, n as disconnectStateAdapter } from "./adapter-iIq7ihf7.js";
|
|
13
|
+
import { D as juniorConversationEventEmbeddings, E as juniorConversationEventLexemes, H as juniorConversations, M as juniorConversationEvents, O as juniorConversationEmbeddings, T as juniorConversationBriefs, _ as juniorAutomationRuns, b as juniorAgentBindings, g as juniorAutomations, h as juniorInboxItems, n as isPostgresErrorCode, q as juniorDestinations, x as juniorAgentInvocations } from "./executor-SCub-fAq.js";
|
|
14
|
+
import { $t as CONVERSATION_WORK_STALE_ENQUEUE_MS, C as getConversation, E as listActiveConversationIds, S as ensureConversationWake, an as isInvalidConversationRecordError, g as clearExpiredConversationLease, l as appendAndEnqueueInboundMessage, o as coerceThreadConversationState, rn as hasRunnableConversationWork, sn as pruneActiveConversation, st as settleConversationTitleWork, tt as appendConversationMessages, w as getConversationWorkState } from "./thread-state-DhPndWi1.js";
|
|
14
15
|
import { t as mapBounded } from "./fan-out-Cod-yEHG.js";
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import { i as enqueueAgentInvocationResult, r as createEndStoppedChildWork } from "./result-
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
16
|
+
import { It as scheduledRunSchema, Qt as buttonUserInputField, Ut as getNextRunAtMs, b as automationListQuerySchema, g as automationExecutionStatusSchema, mt as conversationTitleSchema, on as automationTaskSchema, sn as automationTaskText, yt as annotationCard } from "./media-CYm1QD8T.js";
|
|
17
|
+
import { $r as findAutomationSkill, Gr as readViewerAutomations, Mt as listPendingAgentInvocationMailboxAppends, Nt as listPendingAgentInvocationResults, Sn as recordSubagentEnded, T as processWorkspaceSnapshotJob, Ur as readViewerAutomationSummary, Vr as readViewerAutomationExecutions, Wn as parseSlackThreadId, Xr as automationCardStatus, Zt as enqueueAgentInvocation, _n as renderSlackObjectCard, bn as stopConversation, ei as missingAutomationSkillReason, gt as renderInboxItemMessage, ht as inboxItemChangeRecord, mt as deliverInboxItemChange, p as processBackgroundCompaction, ti as effectiveTaskOutcomes, ut as markConversationRead, vn as annotationKeyDigest, yn as decodeAnnotationRef, zr as ViewerTaskNotFoundError } from "./warmup-BDA5myRK.js";
|
|
18
|
+
import { a as conversationQueueMessageSchema, d as getQueueProvider, m as readSignInSecret, n as resolveConversationWorkQueueTopic, o as isConversationQueueMessageRejectedError, p as readSchedulerSecret, r as verifyConversationQueueMessage, t as getVercelConversationWorkQueue } from "./vercel-queue-hW90XzbG.js";
|
|
19
|
+
import { i as enqueueAgentInvocationResult, r as createEndStoppedChildWork } from "./result-DcvEOe1r.js";
|
|
20
|
+
import { o as requestAttachmentDeletion, t as collectAttachmentGarbage } from "./store-DFZaN-Ix.js";
|
|
21
|
+
import { c as conversationTurnIdForMessage, d as recordWebConversationActivity, f as webActorFromUser, h as collectAttachmentUploadGarbage, l as createAndEnqueueConversation, s as appendAndEnqueueWebMessage } from "./start-conversation-CEn2KH1A.js";
|
|
22
|
+
import { i as getActiveSpan, u as sentry_exports } from "./sentry-CPbZjomA.js";
|
|
23
|
+
import { a as GET$5, i as publishAppHomeView, r as GET$6, t as receiveLocalOAuthCredential } from "./credential-sync-I8VBGk05.js";
|
|
21
24
|
import { t as nameRequestRoute } from "./sentry-route-name-C6EIzAGP.js";
|
|
22
25
|
import { t as SANDBOX_EGRESS_PROXY_PATH } from "./proxy-path-BHYoKZdq.js";
|
|
23
|
-
import { B as conversationTitleSchema, G as annotationCard, I as conversationBriefSchema, b as conversationSurfaceSchema, v as conversationReportStatusSchema } from "./conversation-M9KZ5JxF.js";
|
|
24
|
-
import { i as readActorIdentity, l as resolveViewerUser, p as parseAvatarUrl } from "./viewer-AHldghAD.js";
|
|
25
26
|
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-BsBdxDXQ.js";
|
|
26
|
-
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-
|
|
27
|
-
import { l as unlinkProvider, n as renderHtmlPage, r as requestHasSameOrigin, t as escapeHtml } from "./html-
|
|
28
|
-
import {
|
|
29
|
-
import {
|
|
30
|
-
import {
|
|
31
|
-
import {
|
|
32
|
-
import { t as
|
|
33
|
-
import { t as
|
|
34
|
-
import {
|
|
35
|
-
import { t as processPluginTask } from "./task-runner-
|
|
36
|
-
import { t as
|
|
37
|
-
import {
|
|
27
|
+
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-fuLnF1jE.js";
|
|
28
|
+
import { l as unlinkProvider, n as renderHtmlPage, r as requestHasSameOrigin, t as escapeHtml } from "./html-BCZ3Xtb_.js";
|
|
29
|
+
import { n as verifySlackSignature, t as runWithSlackInstallation } from "./adapter-context-BRjEWRy1.js";
|
|
30
|
+
import { s as joinPublicChannel } from "./channel-access-CJGfNTdn.js";
|
|
31
|
+
import { t as queueCallback } from "./callback-mFlTUWWx.js";
|
|
32
|
+
import { t as processConversationWork } from "./worker-D63RcaVD.js";
|
|
33
|
+
import { t as bindMessageAgent } from "./message-DSXGj1hM.js";
|
|
34
|
+
import { t as bindSpawnAgent } from "./spawn-vxAarlX5.js";
|
|
35
|
+
import { a as pluginTaskQueueConsumer, n as createVercelPluginTaskCallback, o as registerVercelPluginTaskDevConsumer, s as sendVercelPluginTask } from "./task-queue-Cx4Lmjyk.js";
|
|
36
|
+
import { a as readConversationEventPage, c as readConversationLastEventSeq, l as readConversationMessageEventSeq, o as readConversationEventPageAfter, t as processPluginTask } from "./task-runner-CbTwFA6k.js";
|
|
37
|
+
import { c as registerVercelCacheWarmupDevConsumer, i as verifyBackgroundCompactionMessage, o as cacheWarmupQueueConsumer, p as verifyWorkspaceSnapshotJobMessage, r as vercelBackgroundCompactionQueue, s as createVercelCacheWarmupCallback, t as BACKGROUND_COMPACTION_QUEUE_TOPIC, u as WORKSPACE_SNAPSHOT_JOB_QUEUE_TOPIC } from "./background-compaction-queue-DrKi7w3d.js";
|
|
38
|
+
import { t as JUNIOR_VERSION } from "./version-Brbtz4Qf.js";
|
|
39
|
+
import { b as conversationPendingMessageDeliverySchema, t as conversationFeedQuerySchema } from "./conversation-feed-uNOv_x68.js";
|
|
38
40
|
import { createRequire } from "node:module";
|
|
39
41
|
import { Hono } from "hono";
|
|
40
42
|
import * as z from "zod";
|
|
41
43
|
import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
42
|
-
import {
|
|
43
|
-
import { and, asc, eq, inArray, isNotNull, isNull, lte, ne, or, sql } from "drizzle-orm";
|
|
44
|
+
import { eventTriggerFiltersText, identityDispatchOptionsSchema, userSchema } from "@sentry/junior-plugin-api";
|
|
45
|
+
import { and, asc, desc, eq, gt, gte, inArray, isNotNull, isNull, lt, lte, ne, notExists, or, sql } from "drizzle-orm";
|
|
44
46
|
import { pathToFileURL } from "node:url";
|
|
45
47
|
import { Message, ThreadImpl } from "chat";
|
|
46
48
|
import net from "node:net";
|
|
@@ -55,27 +57,208 @@ import { createAuthMiddleware } from "better-auth/api";
|
|
|
55
57
|
import { getSessionCookie } from "better-auth/cookies";
|
|
56
58
|
import { betterAuth } from "better-auth/minimal";
|
|
57
59
|
// src/chat/conversations/embedding-backfill.ts
|
|
58
|
-
const BACKFILL_BUDGET_MS = 1e4;
|
|
59
|
-
const BACKFILL_CLAIM_TTL_MS = 6e4;
|
|
60
|
-
const BACKFILL_DONE_TTL_MS = 36e5;
|
|
61
|
-
/** Embed the
|
|
60
|
+
const BACKFILL_BUDGET_MS$1 = 1e4;
|
|
61
|
+
const BACKFILL_CLAIM_TTL_MS$1 = 6e4;
|
|
62
|
+
const BACKFILL_DONE_TTL_MS$1 = 36e5;
|
|
63
|
+
/** Embed the Conversation metadata that has no vector of the embedder's model. */
|
|
62
64
|
async function runConversationEmbeddingBackfill(embedder) {
|
|
63
65
|
const key = `junior:conversation_embeddings:backfill:${embedder.provider}:${embedder.model}`;
|
|
64
66
|
const state = getStateAdapter();
|
|
65
|
-
if (!await state.setIfNotExists(key, "running", BACKFILL_CLAIM_TTL_MS)) return;
|
|
67
|
+
if (!await state.setIfNotExists(key, "running", BACKFILL_CLAIM_TTL_MS$1)) return;
|
|
66
68
|
await withSpan("conversation_embeddings.backfill", "conversation_embeddings.backfill", {}, async (setSpanAttributes) => {
|
|
67
69
|
const result = await backfillConversationEmbeddings({
|
|
68
70
|
db: getDb(),
|
|
69
|
-
deadlineMs: Date.now() + BACKFILL_BUDGET_MS,
|
|
71
|
+
deadlineMs: Date.now() + BACKFILL_BUDGET_MS$1,
|
|
70
72
|
embedder
|
|
71
73
|
});
|
|
72
|
-
if (result.done) await state.set(key, "done", BACKFILL_DONE_TTL_MS);
|
|
74
|
+
if (result.done) await state.set(key, "done", BACKFILL_DONE_TTL_MS$1);
|
|
73
75
|
setSpanAttributes({
|
|
74
76
|
"app.conversation_embeddings.backfill.embedded.count": result.embedded,
|
|
75
77
|
"app.conversation_embeddings.backfill.outcome": result.done ? "completed" : "budget_exceeded"
|
|
76
78
|
});
|
|
77
79
|
});
|
|
78
80
|
}
|
|
81
|
+
// src/chat/conversations/event-search-backfill.ts
|
|
82
|
+
const ACTIVE_WINDOW_MS = 6048e5;
|
|
83
|
+
const BACKFILL_BUDGET_MS = 1e4;
|
|
84
|
+
const SCAN_STATEMENT_TIMEOUT_MS = 5e3;
|
|
85
|
+
const BACKFILL_CLAIM_TTL_MS = 3e5;
|
|
86
|
+
const BACKFILL_DONE_TTL_MS = 6e5;
|
|
87
|
+
const BACKFILL_PASS_TTL_MS = 864e5;
|
|
88
|
+
const MAX_LEXEME_EVENTS_PER_RUN = 1e3;
|
|
89
|
+
const MAX_VECTOR_EVENTS_PER_RUN = 256;
|
|
90
|
+
const CONVERSATION_PAGE_SIZE = 50;
|
|
91
|
+
const QUERY_CANCELED = "57014";
|
|
92
|
+
const passCursorSchema = z.object({
|
|
93
|
+
at: z.string(),
|
|
94
|
+
conversationId: z.string()
|
|
95
|
+
});
|
|
96
|
+
const backfillPassSchema = z.object({
|
|
97
|
+
after: passCursorSchema.nullable(),
|
|
98
|
+
conversations: z.number(),
|
|
99
|
+
events: z.number(),
|
|
100
|
+
skipped: z.number()
|
|
101
|
+
});
|
|
102
|
+
const NEW_PASS = {
|
|
103
|
+
after: null,
|
|
104
|
+
conversations: 0,
|
|
105
|
+
events: 0,
|
|
106
|
+
skipped: 0
|
|
107
|
+
};
|
|
108
|
+
async function withScanTimeout(db, run) {
|
|
109
|
+
return await db.transaction(async (tx) => {
|
|
110
|
+
await tx.execute(sql`SELECT set_config('statement_timeout', ${String(SCAN_STATEMENT_TIMEOUT_MS)}, true)`);
|
|
111
|
+
return await run(tx);
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
async function listActiveConversations(db, args) {
|
|
115
|
+
const conversations = juniorConversations;
|
|
116
|
+
const after = args.after;
|
|
117
|
+
return await withScanTimeout(db, async (tx) => await tx.select({
|
|
118
|
+
at: sql`to_char(${conversations.lastActivityAt} at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`,
|
|
119
|
+
conversationId: conversations.conversationId
|
|
120
|
+
}).from(conversations).where(and(gte(conversations.lastActivityAt, new Date(args.sinceMs)), after ? or(lt(conversations.lastActivityAt, sql`${after.at}::timestamptz`), and(eq(conversations.lastActivityAt, sql`${after.at}::timestamptz`), gt(conversations.conversationId, after.conversationId))) : void 0)).orderBy(desc(conversations.lastActivityAt), conversations.conversationId).limit(CONVERSATION_PAGE_SIZE));
|
|
121
|
+
}
|
|
122
|
+
async function hasMissingVector(tx, embedder, conversationId) {
|
|
123
|
+
const lexemes = juniorConversationEventLexemes;
|
|
124
|
+
const vectors = juniorConversationEventEmbeddings;
|
|
125
|
+
return (await tx.select({ seq: lexemes.seq }).from(lexemes).where(and(eq(lexemes.conversationId, conversationId), sql`length(${lexemes.lexemes}) > 0`, notExists(tx.select({ seq: vectors.seq }).from(vectors).where(and(eq(vectors.conversationId, lexemes.conversationId), eq(vectors.seq, lexemes.seq), eq(vectors.provider, embedder.provider), eq(vectors.model, embedder.model)))))).limit(1)).length > 0;
|
|
126
|
+
}
|
|
127
|
+
async function indexConversation(db, args) {
|
|
128
|
+
const attempt = await withLock(getStateAdapter(), eventIndexLockKey(args.conversationId), async () => {
|
|
129
|
+
let lexemes;
|
|
130
|
+
let vectorMissing;
|
|
131
|
+
try {
|
|
132
|
+
[lexemes, vectorMissing] = await withScanTimeout(db, async (tx) => {
|
|
133
|
+
return [await storeConversationEventLexemes(tx, args.conversationId, args.lexemeRoom), args.embedder ? await hasMissingVector(tx, args.embedder, args.conversationId) : false];
|
|
134
|
+
});
|
|
135
|
+
} catch (error) {
|
|
136
|
+
if (!isPostgresErrorCode(error, QUERY_CANCELED)) throw error;
|
|
137
|
+
return { kind: "skipped" };
|
|
138
|
+
}
|
|
139
|
+
const vectors = args.embedder && vectorMissing ? await embedConversationEvents(db, args.embedder, args.conversationId, {
|
|
140
|
+
deadlineMs: args.deadlineMs,
|
|
141
|
+
maxEvents: args.vectorRoom
|
|
142
|
+
}) : 0;
|
|
143
|
+
return {
|
|
144
|
+
kind: "indexed",
|
|
145
|
+
lexemes,
|
|
146
|
+
vectors,
|
|
147
|
+
more: lexemes >= args.lexemeRoom || vectorMissing && (vectors >= args.vectorRoom || Date.now() >= args.deadlineMs)
|
|
148
|
+
};
|
|
149
|
+
}, { ttlMs: EVENT_INDEX_LOCK_TTL_MS });
|
|
150
|
+
return attempt.acquired ? attempt.value : { kind: "skipped" };
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Continue `pass` over the Conversations with activity in the last week:
|
|
154
|
+
* store their missing lexemes, and missing vectors when `embedder` is set,
|
|
155
|
+
* until the deadline or the event limits. Return what the run did and the
|
|
156
|
+
* pass to continue next.
|
|
157
|
+
*/
|
|
158
|
+
async function backfillEventSearchIndex(args) {
|
|
159
|
+
const sinceMs = args.nowMs - ACTIVE_WINDOW_MS;
|
|
160
|
+
const run = {
|
|
161
|
+
conversations: 0,
|
|
162
|
+
lexemes: 0,
|
|
163
|
+
skipped: 0,
|
|
164
|
+
vectors: 0
|
|
165
|
+
};
|
|
166
|
+
let after = args.pass.after;
|
|
167
|
+
const progress = () => ({
|
|
168
|
+
after,
|
|
169
|
+
conversations: args.pass.conversations + run.conversations,
|
|
170
|
+
events: args.pass.events + run.lexemes + run.vectors,
|
|
171
|
+
skipped: args.pass.skipped + run.skipped
|
|
172
|
+
});
|
|
173
|
+
while (true) {
|
|
174
|
+
if (Date.now() >= args.deadlineMs) return {
|
|
175
|
+
outcome: "limit_reached",
|
|
176
|
+
pass: progress(),
|
|
177
|
+
run
|
|
178
|
+
};
|
|
179
|
+
const page = await listActiveConversations(args.db, {
|
|
180
|
+
after,
|
|
181
|
+
sinceMs
|
|
182
|
+
});
|
|
183
|
+
for (const conversation of page) {
|
|
184
|
+
const lexemeRoom = MAX_LEXEME_EVENTS_PER_RUN - run.lexemes;
|
|
185
|
+
const vectorRoom = MAX_VECTOR_EVENTS_PER_RUN - run.vectors;
|
|
186
|
+
if (Date.now() >= args.deadlineMs || lexemeRoom <= 0 || args.embedder && vectorRoom <= 0) return {
|
|
187
|
+
outcome: "limit_reached",
|
|
188
|
+
pass: progress(),
|
|
189
|
+
run
|
|
190
|
+
};
|
|
191
|
+
const result = await indexConversation(args.db, {
|
|
192
|
+
conversationId: conversation.conversationId,
|
|
193
|
+
deadlineMs: args.deadlineMs,
|
|
194
|
+
...args.embedder ? { embedder: args.embedder } : void 0,
|
|
195
|
+
lexemeRoom,
|
|
196
|
+
vectorRoom
|
|
197
|
+
});
|
|
198
|
+
run.conversations += 1;
|
|
199
|
+
if (result.kind === "skipped") run.skipped += 1;
|
|
200
|
+
else {
|
|
201
|
+
run.lexemes += result.lexemes;
|
|
202
|
+
run.vectors += result.vectors;
|
|
203
|
+
if (result.more) return {
|
|
204
|
+
outcome: "limit_reached",
|
|
205
|
+
pass: progress(),
|
|
206
|
+
run
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
after = conversation;
|
|
210
|
+
}
|
|
211
|
+
if (page.length < CONVERSATION_PAGE_SIZE) {
|
|
212
|
+
const pass = progress();
|
|
213
|
+
return {
|
|
214
|
+
outcome: pass.events === 0 && pass.skipped === 0 ? "completed" : "pass_ended",
|
|
215
|
+
pass,
|
|
216
|
+
run
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Index the backlog of event search in recently active Conversations.
|
|
223
|
+
* Vectors only when `embedder` is set.
|
|
224
|
+
*/
|
|
225
|
+
async function runEventSearchBackfill(args) {
|
|
226
|
+
const key = `junior:event_search:backfill:${args.embedder ? `${args.embedder.provider}:${args.embedder.model}` : "lexemes"}`;
|
|
227
|
+
const passKey = `${key}:pass`;
|
|
228
|
+
const state = getStateAdapter();
|
|
229
|
+
if (!await state.setIfNotExists(key, "running", BACKFILL_CLAIM_TTL_MS)) return;
|
|
230
|
+
const deadlineMs = Date.now() + BACKFILL_BUDGET_MS;
|
|
231
|
+
let done = false;
|
|
232
|
+
try {
|
|
233
|
+
await withSpan("event_search.backfill", "event_search.backfill", {}, async (setSpanAttributes) => {
|
|
234
|
+
const stored = backfillPassSchema.safeParse(await state.get(passKey));
|
|
235
|
+
const result = await backfillEventSearchIndex({
|
|
236
|
+
db: getDb(),
|
|
237
|
+
deadlineMs,
|
|
238
|
+
...args.embedder ? { embedder: args.embedder } : void 0,
|
|
239
|
+
nowMs: args.nowMs,
|
|
240
|
+
pass: stored.success ? stored.data : NEW_PASS
|
|
241
|
+
});
|
|
242
|
+
if (result.outcome === "limit_reached") await state.set(passKey, result.pass, BACKFILL_PASS_TTL_MS);
|
|
243
|
+
else await state.delete(passKey);
|
|
244
|
+
if (result.outcome === "completed") {
|
|
245
|
+
await state.set(key, "done", BACKFILL_DONE_TTL_MS);
|
|
246
|
+
done = true;
|
|
247
|
+
}
|
|
248
|
+
setSpanAttributes({
|
|
249
|
+
"app.event_search.backfill.conversation.count": result.run.conversations,
|
|
250
|
+
"app.event_search.backfill.skipped.count": result.run.skipped,
|
|
251
|
+
"app.event_search.backfill.lexeme.count": result.run.lexemes,
|
|
252
|
+
"app.event_search.backfill.vector.count": result.run.vectors,
|
|
253
|
+
"app.event_search.backfill.pass.conversation.count": result.pass.conversations,
|
|
254
|
+
"app.event_search.backfill.pass.event.count": result.pass.events,
|
|
255
|
+
"app.event_search.backfill.outcome": result.outcome
|
|
256
|
+
});
|
|
257
|
+
});
|
|
258
|
+
} finally {
|
|
259
|
+
if (!done) await state.delete(key);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
79
262
|
// src/chat/events/timers.ts
|
|
80
263
|
/** Publish a bounded batch of due timers; the mailbox owns agent execution. */
|
|
81
264
|
async function runTimerWatchHeartbeat(args) {
|
|
@@ -188,266 +371,6 @@ async function recoverConversationWork(args) {
|
|
|
188
371
|
});
|
|
189
372
|
return result;
|
|
190
373
|
}
|
|
191
|
-
// src/chat/agent-dispatch/validation.ts
|
|
192
|
-
function hasIssueAtPath(issues, path) {
|
|
193
|
-
return issues.some((issue) => issue.path.length === path.length && issue.path.every((value, index) => value === path[index]));
|
|
194
|
-
}
|
|
195
|
-
function hasIssueUnderPath(issues, path) {
|
|
196
|
-
return issues.some((issue) => path.every((value, index) => issue.path[index] === value));
|
|
197
|
-
}
|
|
198
|
-
function dispatchOptionsErrorMessage(issues) {
|
|
199
|
-
if (hasIssueAtPath(issues, [])) return issues.some((issue) => issue.code === "unrecognized_keys") ? "Dispatch options must not include unknown fields" : "Dispatch options are required";
|
|
200
|
-
if (issues.some((issue) => issue.code === "unrecognized_keys" && issue.path[0] === "destination")) return "Dispatch destination must not include unknown fields";
|
|
201
|
-
if (issues.some((issue) => issue.code === "unrecognized_keys" && issue.path[0] === "credentialSubject")) return "Dispatch credentialSubject binding is runtime-owned";
|
|
202
|
-
if (hasIssueAtPath(issues, ["destination"])) return "Dispatch destination platform must be slack";
|
|
203
|
-
if (hasIssueUnderPath(issues, ["destination", "teamId"])) return "Dispatch destination teamId must be a Slack team id";
|
|
204
|
-
if (hasIssueUnderPath(issues, ["destination", "channelId"])) return "Dispatch destination channelId must be a Slack channel id";
|
|
205
|
-
if (hasIssueUnderPath(issues, ["idempotencyKey"])) return issues.some((issue) => issue.path[0] === "idempotencyKey" && issue.code === "too_big") ? "Dispatch idempotencyKey exceeds the maximum length" : "Dispatch idempotencyKey is required";
|
|
206
|
-
if (hasIssueUnderPath(issues, ["input"])) return issues.some((issue) => issue.path[0] === "input" && issue.code === "too_big") ? "Dispatch input exceeds the maximum length" : "Dispatch input is required";
|
|
207
|
-
if (hasIssueUnderPath(issues, ["credentialSubject", "userId"])) return "Dispatch credentialSubject userId is required";
|
|
208
|
-
if (hasIssueUnderPath(issues, ["credentialSubject", "allowedWhen"])) return "Dispatch credentialSubject allowedWhen is invalid";
|
|
209
|
-
if (hasIssueUnderPath(issues, ["credentialSubject"])) return "Dispatch credentialSubject type must be user";
|
|
210
|
-
const metadataIssue = issues.find((issue) => issue.path[0] === "metadata" && (issue.message === "Dispatch metadata has too many keys" || issue.message === "Dispatch metadata keys must be single-line strings" || issue.message === "Dispatch metadata values must be single-line strings" || issue.message === "Dispatch metadata key exceeds the maximum length" || issue.message === "Dispatch metadata value exceeds the maximum length"));
|
|
211
|
-
if (metadataIssue) return metadataIssue.message;
|
|
212
|
-
if (hasIssueUnderPath(issues, ["metadata"])) return "Dispatch metadata values must be strings";
|
|
213
|
-
if (hasIssueUnderPath(issues, ["replyAttribution"])) return "Dispatch reply attribution is invalid";
|
|
214
|
-
return "Dispatch options are invalid";
|
|
215
|
-
}
|
|
216
|
-
/** Validate plugin-provided dispatch options before core persists them. */
|
|
217
|
-
function validateDispatchOptions(options) {
|
|
218
|
-
const parsed = dispatchOptionsSchema.safeParse(options);
|
|
219
|
-
if (!parsed.success) throw new Error(dispatchOptionsErrorMessage(parsed.error.issues));
|
|
220
|
-
const { credentialSubject, destination } = parsed.data;
|
|
221
|
-
if (!isSlackDestination(destination)) throw new Error("Dispatch destination platform must be slack");
|
|
222
|
-
if (credentialSubject !== void 0) {
|
|
223
|
-
if (credentialSubject.allowedWhen === "private-direct-conversation" && !isDmChannel(destination.channelId)) throw new Error("Dispatch credentialSubject requires a private direct Slack destination");
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
/** Verify runtime-owned access requirements for delegated dispatch credentials. */
|
|
227
|
-
async function verifyDispatchCredentialSubjectAccess(options, plugin) {
|
|
228
|
-
if (!options.credentialSubject) return;
|
|
229
|
-
if (!(options.credentialSubject.allowedWhen === "scheduled-automation" ? verifyScheduledAutomationCredentialSubject({
|
|
230
|
-
plugin,
|
|
231
|
-
subject: options.credentialSubject
|
|
232
|
-
}) : options.credentialSubject.allowedWhen === "event-automation" ? verifyEventAutomationCredentialSubject({
|
|
233
|
-
plugin,
|
|
234
|
-
subject: options.credentialSubject
|
|
235
|
-
}) : verifySlackDirectCredentialSubject({
|
|
236
|
-
channelId: options.destination.channelId,
|
|
237
|
-
teamId: options.destination.teamId,
|
|
238
|
-
subject: options.credentialSubject
|
|
239
|
-
}))) throw new Error("Dispatch credentialSubject is not valid for this action");
|
|
240
|
-
}
|
|
241
|
-
// src/chat/agent-dispatch/context.ts
|
|
242
|
-
const MAX_DISPATCHES_PER_HEARTBEAT = 25;
|
|
243
|
-
function bindDispatchCredentialSubject(options, plugin) {
|
|
244
|
-
const { credentialSubject, ...baseOptions } = options;
|
|
245
|
-
if (!credentialSubject) return {
|
|
246
|
-
...baseOptions,
|
|
247
|
-
source: { kind: "plugin_dispatch" }
|
|
248
|
-
};
|
|
249
|
-
if ("binding" in credentialSubject) throw new Error("Dispatch credentialSubject binding is runtime-owned");
|
|
250
|
-
const boundSubject = credentialSubject.allowedWhen === "scheduled-automation" ? bindScheduledAutomationCredentialSubject({
|
|
251
|
-
plugin,
|
|
252
|
-
subject: credentialSubject
|
|
253
|
-
}) : bindSlackDirectCredentialSubject({
|
|
254
|
-
channelId: options.destination.channelId,
|
|
255
|
-
teamId: options.destination.teamId,
|
|
256
|
-
subject: credentialSubject
|
|
257
|
-
});
|
|
258
|
-
if (!boundSubject) throw new Error("Dispatch credentialSubject is not valid for this action");
|
|
259
|
-
return {
|
|
260
|
-
...baseOptions,
|
|
261
|
-
credentialSubject: boundSubject,
|
|
262
|
-
source: { kind: "plugin_dispatch" }
|
|
263
|
-
};
|
|
264
|
-
}
|
|
265
|
-
/** Verify, persist, and enqueue one idempotent agent dispatch. */
|
|
266
|
-
async function dispatch(args) {
|
|
267
|
-
await verifyDispatchCredentialSubjectAccess(args.options, args.plugin);
|
|
268
|
-
const result = await createOrGetDispatch({
|
|
269
|
-
plugin: args.plugin,
|
|
270
|
-
options: args.options,
|
|
271
|
-
nowMs: args.nowMs
|
|
272
|
-
});
|
|
273
|
-
if (!isTerminalDispatchStatus(result.record.status)) await enqueueAgentDispatch(result.record, {
|
|
274
|
-
queue: args.conversationWorkQueue,
|
|
275
|
-
nowMs: args.nowMs
|
|
276
|
-
});
|
|
277
|
-
return {
|
|
278
|
-
id: result.record.id,
|
|
279
|
-
status: result.status
|
|
280
|
-
};
|
|
281
|
-
}
|
|
282
|
-
/** Build the plugin-scoped heartbeat context that gates durable dispatch access. */
|
|
283
|
-
function createHeartbeatContext(args) {
|
|
284
|
-
const pluginName = typeof args.plugin === "string" ? args.plugin : args.plugin.manifest.name;
|
|
285
|
-
let dispatchCount = 0;
|
|
286
|
-
const assertDispatchBudget = () => {
|
|
287
|
-
if (dispatchCount >= MAX_DISPATCHES_PER_HEARTBEAT) throw new Error("Plugin heartbeat exceeded the dispatch limit");
|
|
288
|
-
};
|
|
289
|
-
return {
|
|
290
|
-
plugin: { name: pluginName },
|
|
291
|
-
annotations: { forConversation: (conversationId) => createPluginAnnotations({
|
|
292
|
-
conversationId,
|
|
293
|
-
db: getDb(),
|
|
294
|
-
plugin: pluginName
|
|
295
|
-
}) },
|
|
296
|
-
cache: createPluginCache(pluginName),
|
|
297
|
-
codeChanges: createCodeChangePublisher(pluginName),
|
|
298
|
-
nowMs: args.nowMs,
|
|
299
|
-
db: getDb(),
|
|
300
|
-
embedder: createPluginEmbedder(pluginName),
|
|
301
|
-
events: args.events,
|
|
302
|
-
reviewItems: { forConversation: (conversationId) => createPluginReviewItems({
|
|
303
|
-
conversationId,
|
|
304
|
-
plugin: pluginName,
|
|
305
|
-
show: args.showReviewItem ?? (async () => {})
|
|
306
|
-
}) },
|
|
307
|
-
state: createPluginState(pluginName),
|
|
308
|
-
log: createPluginLogger(pluginName),
|
|
309
|
-
agent: {
|
|
310
|
-
async dispatch(options) {
|
|
311
|
-
validateDispatchOptions(options);
|
|
312
|
-
const dispatchOptions = bindDispatchCredentialSubject(options, pluginName);
|
|
313
|
-
assertDispatchBudget();
|
|
314
|
-
const result = await dispatch({
|
|
315
|
-
conversationWorkQueue: args.conversationWorkQueue,
|
|
316
|
-
nowMs: args.nowMs,
|
|
317
|
-
options: dispatchOptions,
|
|
318
|
-
plugin: pluginName
|
|
319
|
-
});
|
|
320
|
-
dispatchCount += 1;
|
|
321
|
-
return result;
|
|
322
|
-
},
|
|
323
|
-
async dispatchForIdentity(options) {
|
|
324
|
-
assertDispatchBudget();
|
|
325
|
-
dispatchCount += 1;
|
|
326
|
-
return await args.dispatchForIdentity(pluginName, options);
|
|
327
|
-
},
|
|
328
|
-
async get(id) {
|
|
329
|
-
return await getPluginDispatchProjection({
|
|
330
|
-
plugin: pluginName,
|
|
331
|
-
id
|
|
332
|
-
});
|
|
333
|
-
}
|
|
334
|
-
}
|
|
335
|
-
};
|
|
336
|
-
}
|
|
337
|
-
/** Create and enqueue one core-owned event automation dispatch. */
|
|
338
|
-
async function dispatchEventAutomation(args) {
|
|
339
|
-
const plugin = "junior";
|
|
340
|
-
const { credentialSubject, outcomes, skill, ...unboundOptions } = args.options;
|
|
341
|
-
validateDispatchOptions({ ...unboundOptions });
|
|
342
|
-
const boundSubject = credentialSubject ? bindEventAutomationCredentialSubject({
|
|
343
|
-
plugin,
|
|
344
|
-
subject: credentialSubject
|
|
345
|
-
}) : void 0;
|
|
346
|
-
if (credentialSubject && !boundSubject) throw new Error("Dispatch credentialSubject is not valid for this action");
|
|
347
|
-
const options = {
|
|
348
|
-
...unboundOptions,
|
|
349
|
-
...outcomes !== void 0 ? { outcomes } : void 0,
|
|
350
|
-
...skill ? { skill } : void 0,
|
|
351
|
-
...boundSubject ? { credentialSubject: boundSubject } : void 0,
|
|
352
|
-
source: {
|
|
353
|
-
kind: "event_automation",
|
|
354
|
-
automationId: args.automationId,
|
|
355
|
-
automationRunId: buildDispatchId(plugin, unboundOptions.idempotencyKey)
|
|
356
|
-
}
|
|
357
|
-
};
|
|
358
|
-
return await dispatch({
|
|
359
|
-
conversationWorkQueue: args.conversationWorkQueue,
|
|
360
|
-
nowMs: args.nowMs,
|
|
361
|
-
options,
|
|
362
|
-
plugin
|
|
363
|
-
});
|
|
364
|
-
}
|
|
365
|
-
/** Create and enqueue one core-owned scheduled automation dispatch. */
|
|
366
|
-
async function dispatchScheduledAutomation(args) {
|
|
367
|
-
const plugin = "scheduler";
|
|
368
|
-
const { credentialSubject, outcomes, skill, ...unboundOptions } = args.options;
|
|
369
|
-
validateDispatchOptions({ ...unboundOptions });
|
|
370
|
-
const boundSubject = credentialSubject ? bindScheduledAutomationCredentialSubject({
|
|
371
|
-
plugin,
|
|
372
|
-
subject: credentialSubject
|
|
373
|
-
}) : void 0;
|
|
374
|
-
if (credentialSubject && !boundSubject) throw new Error("Dispatch credentialSubject is not valid for this action");
|
|
375
|
-
const options = {
|
|
376
|
-
...unboundOptions,
|
|
377
|
-
...outcomes !== void 0 ? { outcomes } : void 0,
|
|
378
|
-
...skill ? { skill } : void 0,
|
|
379
|
-
...boundSubject ? { credentialSubject: boundSubject } : void 0,
|
|
380
|
-
source: {
|
|
381
|
-
kind: "scheduled_automation",
|
|
382
|
-
automationId: args.automationId,
|
|
383
|
-
automationRunId: unboundOptions.idempotencyKey
|
|
384
|
-
}
|
|
385
|
-
};
|
|
386
|
-
return await dispatch({
|
|
387
|
-
conversationWorkQueue: args.conversationWorkQueue,
|
|
388
|
-
nowMs: args.nowMs,
|
|
389
|
-
options,
|
|
390
|
-
plugin
|
|
391
|
-
});
|
|
392
|
-
}
|
|
393
|
-
/** Read the bounded outcome for one core-owned scheduled automation dispatch. */
|
|
394
|
-
async function getScheduledAutomationDispatch(id) {
|
|
395
|
-
return await getPluginDispatchProjection({
|
|
396
|
-
plugin: "scheduler",
|
|
397
|
-
id
|
|
398
|
-
});
|
|
399
|
-
}
|
|
400
|
-
// src/chat/event-automations/runs.ts
|
|
401
|
-
/**
|
|
402
|
-
* Record a dispatched event automation run with the Automation version it ran,
|
|
403
|
-
* and link its Conversation when it exists. The dispatch can finish before
|
|
404
|
-
* this write, so a stored run, or a retry of the same Event, keeps the row it
|
|
405
|
-
* has.
|
|
406
|
-
*/
|
|
407
|
-
async function recordEventAutomationRunStarted(db, args) {
|
|
408
|
-
const conversationId = getDispatchConversationId({ id: args.dispatchId });
|
|
409
|
-
await db.insert(juniorAutomationRuns).values({
|
|
410
|
-
id: args.dispatchId,
|
|
411
|
-
automationId: args.automation.id,
|
|
412
|
-
automationVersion: automationVersionOf(args.automation),
|
|
413
|
-
conversationId: existingConversationId(conversationId),
|
|
414
|
-
costMicroUsd: conversationCostOf(conversationId),
|
|
415
|
-
startedAtMs: args.nowMs,
|
|
416
|
-
status: "running"
|
|
417
|
-
}).onConflictDoNothing({ target: juniorAutomationRuns.id });
|
|
418
|
-
}
|
|
419
|
-
/**
|
|
420
|
-
* Settle running event automation runs whose dispatch has ended. A run whose
|
|
421
|
-
* dispatch record is gone fails.
|
|
422
|
-
*/
|
|
423
|
-
async function settleEventAutomationRuns(db, nowMs) {
|
|
424
|
-
const runs = await db.select({
|
|
425
|
-
automationId: juniorAutomationRuns.automationId,
|
|
426
|
-
id: juniorAutomationRuns.id
|
|
427
|
-
}).from(juniorAutomationRuns).innerJoin(juniorAutomations, eq(juniorAutomations.id, juniorAutomationRuns.automationId)).where(and(eq(juniorAutomations.kind, "event"), eq(juniorAutomationRuns.status, "running")));
|
|
428
|
-
const dispatches = await mapBounded(runs, (run) => getDispatchRecord(run.id));
|
|
429
|
-
for (const [index, run] of runs.entries()) {
|
|
430
|
-
const dispatch = dispatches[index];
|
|
431
|
-
const status = dispatch?.status ?? "failed";
|
|
432
|
-
if (status !== "blocked" && status !== "completed" && status !== "failed") continue;
|
|
433
|
-
await recordAutomationExecution(run.automationId, {
|
|
434
|
-
conversationId: getDispatchConversationId({ id: run.id }),
|
|
435
|
-
errorMessage: dispatch ? dispatch.errorMessage : "Event automation dispatch record is missing.",
|
|
436
|
-
executionId: run.id,
|
|
437
|
-
nowMs: dispatch?.updatedAtMs ?? nowMs,
|
|
438
|
-
status
|
|
439
|
-
});
|
|
440
|
-
}
|
|
441
|
-
}
|
|
442
|
-
// src/chat/automations/reply-attribution.ts
|
|
443
|
-
/** Name the Automation in the footer of the replies that its runs post. */
|
|
444
|
-
function automationReplyAttribution(title) {
|
|
445
|
-
const detail = (title ?? "").replace(/\s+/g, " ").trim().slice(0, 128).trim();
|
|
446
|
-
return detail ? {
|
|
447
|
-
label: "Automation",
|
|
448
|
-
detail
|
|
449
|
-
} : { label: "Automation" };
|
|
450
|
-
}
|
|
451
374
|
// src/chat/scheduled-automations/runs.ts
|
|
452
375
|
const PENDING_CLAIM_STALE_MS = 6e4;
|
|
453
376
|
const MISSED_RUN_MAX_AGE_MS = 864e5;
|
|
@@ -1081,7 +1004,7 @@ async function runWithTimeout(promise, timeoutMs) {
|
|
|
1081
1004
|
/** Run plugin heartbeat hooks with bounded per-invocation work. */
|
|
1082
1005
|
async function runPluginHeartbeats(args) {
|
|
1083
1006
|
let count = 0;
|
|
1084
|
-
for (const plugin of
|
|
1007
|
+
for (const plugin of getRegistrations()) {
|
|
1085
1008
|
const pluginName = plugin.manifest.name;
|
|
1086
1009
|
if (count >= (args.limit ?? DEFAULT_PLUGIN_LIMIT)) break;
|
|
1087
1010
|
const heartbeat = plugin.hooks?.heartbeat;
|
|
@@ -1094,7 +1017,7 @@ async function runPluginHeartbeats(args) {
|
|
|
1094
1017
|
events: createPluginEventPublisher(plugin, args.events),
|
|
1095
1018
|
plugin,
|
|
1096
1019
|
nowMs: args.nowMs,
|
|
1097
|
-
|
|
1020
|
+
showInboxItem: args.showInboxItem
|
|
1098
1021
|
}))), PLUGIN_HEARTBEAT_TIMEOUT_MS);
|
|
1099
1022
|
if (typeof result?.dispatchCount === "number" && result.dispatchCount > 0) logInfo("plugin.heartbeat.dispatched", {
|
|
1100
1023
|
"app.dispatch.count": result.dispatchCount,
|
|
@@ -1206,6 +1129,17 @@ async function runHeartbeat(args) {
|
|
|
1206
1129
|
} catch (error) {
|
|
1207
1130
|
logException(error, "scheduled_automations.heartbeat.failed");
|
|
1208
1131
|
}
|
|
1132
|
+
try {
|
|
1133
|
+
const woke = await runInboxSnoozeTimers(getDb(), args.nowMs);
|
|
1134
|
+
if (woke > 0) logInfo("inbox_snoozes.heartbeat.woken", { "app.inbox_snooze.count": woke });
|
|
1135
|
+
} catch (error) {
|
|
1136
|
+
logException(error, "inbox_snoozes.heartbeat.failed");
|
|
1137
|
+
}
|
|
1138
|
+
try {
|
|
1139
|
+
await syncAutomationAlerts(getDb(), args.nowMs);
|
|
1140
|
+
} catch (error) {
|
|
1141
|
+
logException(error, "automation_alerts.heartbeat.failed");
|
|
1142
|
+
}
|
|
1209
1143
|
try {
|
|
1210
1144
|
await runTimerWatchHeartbeat({
|
|
1211
1145
|
nowMs: args.nowMs,
|
|
@@ -1219,7 +1153,7 @@ async function runHeartbeat(args) {
|
|
|
1219
1153
|
dispatchForIdentity: args.dispatchForIdentity,
|
|
1220
1154
|
events: args.events,
|
|
1221
1155
|
nowMs: args.nowMs,
|
|
1222
|
-
|
|
1156
|
+
showInboxItem: args.showInboxItem
|
|
1223
1157
|
});
|
|
1224
1158
|
try {
|
|
1225
1159
|
await backfillCacheWarmingGaps({ nowMs: args.nowMs });
|
|
@@ -1231,7 +1165,7 @@ async function runHeartbeat(args) {
|
|
|
1231
1165
|
} catch (error) {
|
|
1232
1166
|
logException(error, "cache_warming.savings_refill.failed");
|
|
1233
1167
|
}
|
|
1234
|
-
|
|
1168
|
+
try {
|
|
1235
1169
|
await runConversationEmbeddingBackfill(createConversationEmbedder({
|
|
1236
1170
|
cost: { owner: "none" },
|
|
1237
1171
|
operation: "conversation_embedding"
|
|
@@ -1239,6 +1173,17 @@ async function runHeartbeat(args) {
|
|
|
1239
1173
|
} catch (error) {
|
|
1240
1174
|
logException(error, "conversation_embeddings.backfill.failed");
|
|
1241
1175
|
}
|
|
1176
|
+
try {
|
|
1177
|
+
await runEventSearchBackfill({
|
|
1178
|
+
...isEventEmbeddingsEnabled() ? { embedder: createConversationEmbedder({
|
|
1179
|
+
cost: { owner: "none" },
|
|
1180
|
+
operation: "conversation_embedding"
|
|
1181
|
+
}) } : void 0,
|
|
1182
|
+
nowMs: args.nowMs
|
|
1183
|
+
});
|
|
1184
|
+
} catch (error) {
|
|
1185
|
+
logException(error, "event_search.backfill.failed");
|
|
1186
|
+
}
|
|
1242
1187
|
}
|
|
1243
1188
|
// src/handlers/scheduler-auth.ts
|
|
1244
1189
|
/** Check the bearer secret that internal cron requests must send. */
|
|
@@ -1261,7 +1206,7 @@ async function GET$3(request, waitUntil, options) {
|
|
|
1261
1206
|
dispatchForIdentity: options.dispatchForIdentity,
|
|
1262
1207
|
events: options.events,
|
|
1263
1208
|
nowMs,
|
|
1264
|
-
|
|
1209
|
+
showInboxItem: options.showInboxItem
|
|
1265
1210
|
}).catch((error) => {
|
|
1266
1211
|
logException(error, "heartbeat.run.failed", { "app.heartbeat.now_ms": nowMs });
|
|
1267
1212
|
}));
|
|
@@ -1332,14 +1277,15 @@ async function selectExpiredRoots(executor, args) {
|
|
|
1332
1277
|
or bindings.child_conversation_id = tree.conversation_id
|
|
1333
1278
|
)
|
|
1334
1279
|
or exists (
|
|
1335
|
-
select 1 from
|
|
1336
|
-
where
|
|
1337
|
-
and
|
|
1338
|
-
and
|
|
1280
|
+
select 1 from junior_inbox_items inbox_items
|
|
1281
|
+
where inbox_items.owner_kind = 'conversation'
|
|
1282
|
+
and inbox_items.owner_id = tree.conversation_id
|
|
1283
|
+
and inbox_items.status = 'open'
|
|
1284
|
+
and inbox_items.automation_id is null
|
|
1339
1285
|
)
|
|
1340
1286
|
or exists (
|
|
1341
|
-
select 1 from
|
|
1342
|
-
where
|
|
1287
|
+
select 1 from junior_todos todos
|
|
1288
|
+
where todos.conversation_id = tree.conversation_id
|
|
1343
1289
|
)
|
|
1344
1290
|
or (
|
|
1345
1291
|
${juniorDestinations.visibility} is distinct from 'public'
|
|
@@ -1349,12 +1295,22 @@ async function selectExpiredRoots(executor, args) {
|
|
|
1349
1295
|
where briefs.conversation_id = tree.conversation_id
|
|
1350
1296
|
)
|
|
1351
1297
|
or exists (
|
|
1352
|
-
select 1 from
|
|
1353
|
-
where
|
|
1354
|
-
and
|
|
1298
|
+
select 1 from junior_conversations metadata
|
|
1299
|
+
where metadata.conversation_id = tree.conversation_id
|
|
1300
|
+
and metadata.summary is not null
|
|
1301
|
+
)
|
|
1302
|
+
or exists (
|
|
1303
|
+
select 1 from junior_conversation_embeddings embeddings
|
|
1304
|
+
where embeddings.conversation_id = tree.conversation_id
|
|
1305
|
+
)
|
|
1306
|
+
or exists (
|
|
1307
|
+
select 1 from junior_inbox_items inbox_items
|
|
1308
|
+
where inbox_items.owner_kind = 'conversation'
|
|
1309
|
+
and inbox_items.owner_id = tree.conversation_id
|
|
1310
|
+
and inbox_items.visibility = 'private'
|
|
1355
1311
|
and (
|
|
1356
|
-
|
|
1357
|
-
or
|
|
1312
|
+
inbox_items.status <> 'open'
|
|
1313
|
+
or inbox_items.automation_id is null
|
|
1358
1314
|
)
|
|
1359
1315
|
)
|
|
1360
1316
|
or exists (
|
|
@@ -1382,9 +1338,10 @@ async function selectExpiredRoots(executor, args) {
|
|
|
1382
1338
|
* event rows for the given conversation and every descendant, stamp
|
|
1383
1339
|
* `transcript_purged_at`, and — for non-public content — null the raw-payload
|
|
1384
1340
|
* metadata (`title`, `channel_name`, legacy actor JSON) so purged private
|
|
1385
|
-
* conversations keep only safe metadata.
|
|
1386
|
-
* Non-public content also loses its
|
|
1387
|
-
* added. The metadata rows themselves
|
|
1341
|
+
* conversations keep only safe metadata. To-dos go with the transcript.
|
|
1342
|
+
* Non-public content also loses its summary, Conversation embedding, legacy
|
|
1343
|
+
* Briefs, and the Inbox items that it added. The metadata rows themselves
|
|
1344
|
+
* survive.
|
|
1388
1345
|
*/
|
|
1389
1346
|
async function purgeConversationTree(executor, args) {
|
|
1390
1347
|
return await withConversationMutationLock(executor, args.rootConversationId, async () => {
|
|
@@ -1430,26 +1387,29 @@ async function purgeConversationTree(executor, args) {
|
|
|
1430
1387
|
await deleteMessageLinks(executor, ids);
|
|
1431
1388
|
await executor.db().delete(juniorAgentInvocations).where(or(inArray(juniorAgentInvocations.parentConversationId, ids), inArray(juniorAgentInvocations.childConversationId, ids)));
|
|
1432
1389
|
await executor.db().delete(juniorAgentBindings).where(or(inArray(juniorAgentBindings.parentConversationId, ids), inArray(juniorAgentBindings.childConversationId, ids)));
|
|
1433
|
-
await
|
|
1434
|
-
|
|
1390
|
+
await dismissOpenInboxItems(executor.db(), {
|
|
1391
|
+
ownerConversationIds: ids,
|
|
1435
1392
|
nowMs: args.nowMs,
|
|
1436
1393
|
reason: "Conversation purged"
|
|
1437
1394
|
});
|
|
1438
|
-
await
|
|
1395
|
+
await deleteTodos(executor, ids);
|
|
1439
1396
|
await requestAttachmentDeletion(executor, ids, args.nowMs);
|
|
1440
1397
|
const scrubMetadata = args.retention ? !isPublic : resolvedScrubMetadata;
|
|
1441
|
-
if (scrubMetadata) {
|
|
1442
|
-
await executor.db().delete(juniorConversationBriefs).where(inArray(juniorConversationBriefs.conversationId, ids));
|
|
1443
|
-
await executor.db().delete(juniorReviewItems).where(and(inArray(juniorReviewItems.addedByConversationId, ids), eq(juniorReviewItems.visibility, "private"), or(ne(juniorReviewItems.status, "open"), isNull(juniorReviewItems.automationId))));
|
|
1444
|
-
}
|
|
1445
1398
|
await executor.db().update(juniorConversations).set({
|
|
1446
1399
|
transcriptPurgedAt: new Date(args.nowMs),
|
|
1447
1400
|
...scrubMetadata ? {
|
|
1448
1401
|
title: null,
|
|
1449
1402
|
channelName: null,
|
|
1450
|
-
actor: null
|
|
1403
|
+
actor: null,
|
|
1404
|
+
summary: null,
|
|
1405
|
+
metadataThroughSeq: null
|
|
1451
1406
|
} : void 0
|
|
1452
1407
|
}).where(inArray(juniorConversations.conversationId, ids));
|
|
1408
|
+
if (scrubMetadata) {
|
|
1409
|
+
await executor.db().delete(juniorConversationBriefs).where(inArray(juniorConversationBriefs.conversationId, ids));
|
|
1410
|
+
await executor.db().delete(juniorConversationEmbeddings).where(inArray(juniorConversationEmbeddings.conversationId, ids));
|
|
1411
|
+
await executor.db().delete(juniorInboxItems).where(and(eq(juniorInboxItems.ownerKind, "conversation"), inArray(juniorInboxItems.ownerId, ids), eq(juniorInboxItems.visibility, "private"), or(ne(juniorInboxItems.status, "open"), isNull(juniorInboxItems.automationId))));
|
|
1412
|
+
}
|
|
1453
1413
|
await touchConversationDetail(executor.db(), ids);
|
|
1454
1414
|
return {
|
|
1455
1415
|
purged: true,
|
|
@@ -1466,7 +1426,8 @@ async function purgeConversationTree(executor, args) {
|
|
|
1466
1426
|
* from `last_activity_at` and deleted wholesale by a dedicated cron. Visibility
|
|
1467
1427
|
* is resolved at purge time through the parent chain to the root's destination,
|
|
1468
1428
|
* so no expiry is ever stored and a public↔private flip takes effect on the next
|
|
1469
|
-
* pass. Attachment files use their own 30-day window
|
|
1429
|
+
* pass. Attachment files use their own 30-day window, and so do snoozes
|
|
1430
|
+
* that have woken or been undone.
|
|
1470
1431
|
*/
|
|
1471
1432
|
const DAY_MS = 864e5;
|
|
1472
1433
|
/** Content retention windows keyed by resolved conversation visibility. */
|
|
@@ -1523,9 +1484,11 @@ async function runRetentionPurge(executor, args) {
|
|
|
1523
1484
|
nowMs: args.nowMs,
|
|
1524
1485
|
storage: args.attachmentStorage
|
|
1525
1486
|
}) : { deleted: 0 };
|
|
1487
|
+
const inboxSnoozes = await deleteExpiredInboxSnoozes(executor.db(), args.nowMs);
|
|
1526
1488
|
logInfo("retention.purge.completed", {
|
|
1527
1489
|
"app.retention.attachments": attachmentResult.deleted,
|
|
1528
1490
|
"app.retention.attachment_uploads": uploadResult.deleted,
|
|
1491
|
+
"app.retention.inbox_snoozes": inboxSnoozes,
|
|
1529
1492
|
"app.retention.scanned": roots.length,
|
|
1530
1493
|
"app.retention.purged": purged,
|
|
1531
1494
|
"app.retention.failed": failed,
|
|
@@ -1540,6 +1503,33 @@ async function runRetentionPurge(executor, args) {
|
|
|
1540
1503
|
attachments: attachmentResult.deleted
|
|
1541
1504
|
};
|
|
1542
1505
|
}
|
|
1506
|
+
// src/db/table-size.ts
|
|
1507
|
+
/**
|
|
1508
|
+
* Emit the estimated row count and total on-disk size of each Junior table as
|
|
1509
|
+
* gauges, so production table growth is visible without a table query.
|
|
1510
|
+
*/
|
|
1511
|
+
async function reportTableSizes(executor) {
|
|
1512
|
+
const tables = await executor.query(`
|
|
1513
|
+
SELECT
|
|
1514
|
+
c.relname AS "table",
|
|
1515
|
+
c.reltuples AS "rows",
|
|
1516
|
+
pg_total_relation_size(c.oid) AS "bytes"
|
|
1517
|
+
FROM pg_class c
|
|
1518
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
1519
|
+
WHERE n.nspname = current_schema()
|
|
1520
|
+
AND c.relkind IN ('r', 'p')
|
|
1521
|
+
AND c.relname LIKE 'junior\\_%' ESCAPE '\\'
|
|
1522
|
+
`);
|
|
1523
|
+
for (const table of tables) {
|
|
1524
|
+
const attributes = { "db.collection.name": table.table };
|
|
1525
|
+
const rows = Number(table.rows);
|
|
1526
|
+
if (rows >= 0) sentry_exports.metrics.gauge("db.table.rows", rows, { attributes });
|
|
1527
|
+
sentry_exports.metrics.gauge("db.table.size", Number(table.bytes), {
|
|
1528
|
+
unit: "byte",
|
|
1529
|
+
attributes
|
|
1530
|
+
});
|
|
1531
|
+
}
|
|
1532
|
+
}
|
|
1543
1533
|
// src/handlers/retention.ts
|
|
1544
1534
|
/**
|
|
1545
1535
|
* Handle the authenticated internal retention cron. One request runs a single
|
|
@@ -1549,10 +1539,14 @@ async function runRetentionPurge(executor, args) {
|
|
|
1549
1539
|
async function GET$2(request, options = {}) {
|
|
1550
1540
|
if (!verifySchedulerRequest(request)) return new Response("Unauthorized", { status: 401 });
|
|
1551
1541
|
try {
|
|
1552
|
-
const
|
|
1542
|
+
const executor = getSqlExecutor();
|
|
1543
|
+
const result = await runRetentionPurge(executor, {
|
|
1553
1544
|
attachmentStorage: options.attachmentStorage ?? getAttachmentStorage(),
|
|
1554
1545
|
nowMs: Date.now()
|
|
1555
1546
|
});
|
|
1547
|
+
await reportTableSizes(executor).catch((error) => {
|
|
1548
|
+
logException(error, "db.table_size.failed");
|
|
1549
|
+
});
|
|
1556
1550
|
return Response.json(result, { status: 200 });
|
|
1557
1551
|
} catch (error) {
|
|
1558
1552
|
logException(error, "retention.run.failed");
|
|
@@ -1855,7 +1849,7 @@ function buildSlackInteractionInput(args) {
|
|
|
1855
1849
|
threadId: parsed.threadId
|
|
1856
1850
|
});
|
|
1857
1851
|
}
|
|
1858
|
-
// src/chat/ingress/slack-
|
|
1852
|
+
// src/chat/ingress/slack-inbox-item.ts
|
|
1859
1853
|
async function tellPerson(target, userId, text) {
|
|
1860
1854
|
await postSlackEphemeralMessage({
|
|
1861
1855
|
channelId: target.channelId,
|
|
@@ -1874,18 +1868,19 @@ function resolveActingUser(services, payload, target) {
|
|
|
1874
1868
|
}
|
|
1875
1869
|
/** Show the current state of an item, such as after a click on a stale card. */
|
|
1876
1870
|
async function refreshCards(services, user, itemId) {
|
|
1877
|
-
const item = await
|
|
1871
|
+
const item = await readInboxItemForUser(user, itemId).catch(() => void 0);
|
|
1878
1872
|
if (!item) return;
|
|
1879
|
-
await
|
|
1873
|
+
await syncInboxItemSlackCards({
|
|
1880
1874
|
getSlackAdapter: () => services.adapter,
|
|
1881
1875
|
itemId: item.id
|
|
1882
1876
|
});
|
|
1883
1877
|
}
|
|
1884
1878
|
/**
|
|
1885
1879
|
* Do one person action from a Slack card. The thread of the card gets an
|
|
1886
|
-
* answer as Slack input from the person, like a typed reply. A dismiss
|
|
1887
|
-
* starts no Turn, so the thread gets the same
|
|
1888
|
-
*
|
|
1880
|
+
* answer as Slack input from the person, like a typed reply. A dismiss, or
|
|
1881
|
+
* the answer to a plugin item, starts no Turn, so the thread gets the same
|
|
1882
|
+
* recorded Message as the other linked Conversations, from
|
|
1883
|
+
* `actOnInboxItem`. An expected failure, such as
|
|
1889
1884
|
* an item that is already closed, goes to the person as an ephemeral
|
|
1890
1885
|
* message.
|
|
1891
1886
|
*/
|
|
@@ -1893,30 +1888,32 @@ async function act(args) {
|
|
|
1893
1888
|
const { services, target } = args;
|
|
1894
1889
|
const actor = await resolveActingUser(services, args.payload, target);
|
|
1895
1890
|
if (!actor) return;
|
|
1896
|
-
const conversationId = await
|
|
1891
|
+
const conversationId = await resolveSlackInboxItemCardConversationId({
|
|
1897
1892
|
channelId: target.channelId,
|
|
1898
1893
|
teamId: actor.teamId,
|
|
1899
1894
|
threadTs: target.threadTs
|
|
1900
1895
|
});
|
|
1901
1896
|
const delivery = {
|
|
1902
1897
|
queue: services.queue,
|
|
1903
|
-
show:
|
|
1898
|
+
show: createSlackInboxItemShow(() => services.adapter)
|
|
1904
1899
|
};
|
|
1905
|
-
|
|
1900
|
+
let recordOnly = args.action === "dismiss";
|
|
1906
1901
|
let item;
|
|
1907
1902
|
try {
|
|
1908
|
-
const current = await
|
|
1909
|
-
|
|
1903
|
+
const current = await readInboxItemForUser(actor.user, args.itemId);
|
|
1904
|
+
const pluginAnswer = args.action === "submit" && isPluginInboxItem(current);
|
|
1905
|
+
recordOnly ||= pluginAnswer;
|
|
1906
|
+
item = await actOnInboxItem({
|
|
1910
1907
|
action: args.action,
|
|
1911
1908
|
...recordOnly ? void 0 : { exceptConversationId: conversationId },
|
|
1912
|
-
firstCloseOnly:
|
|
1909
|
+
firstCloseOnly: !pluginAnswer,
|
|
1913
1910
|
delivery,
|
|
1914
1911
|
id: current.id,
|
|
1915
1912
|
user: actor.user,
|
|
1916
1913
|
...args.answer ? { answer: args.answer(current) } : void 0
|
|
1917
1914
|
});
|
|
1918
1915
|
} catch (error) {
|
|
1919
|
-
if (!(error instanceof
|
|
1916
|
+
if (!(error instanceof InboxItemActionError)) throw error;
|
|
1920
1917
|
await tellPerson(target, actor.slackUserId, error.message);
|
|
1921
1918
|
await refreshCards(services, actor.user, args.itemId);
|
|
1922
1919
|
return;
|
|
@@ -1931,13 +1928,13 @@ async function act(args) {
|
|
|
1931
1928
|
messageId: args.messageId,
|
|
1932
1929
|
messageTs: target.messageTs,
|
|
1933
1930
|
payload: args.payload,
|
|
1934
|
-
text:
|
|
1931
|
+
text: renderInboxItemMessage(item, change),
|
|
1935
1932
|
threadTs: target.threadTs,
|
|
1936
1933
|
userId: actor.slackUserId
|
|
1937
|
-
}), { reviewItemChange:
|
|
1934
|
+
}), { reviewItemChange: inboxItemChangeRecord(item, change) });
|
|
1938
1935
|
} catch (error) {
|
|
1939
|
-
logException(error, "
|
|
1940
|
-
await
|
|
1936
|
+
logException(error, "inbox_item.slack_input.persist.failed", { "app.inbox_item.id": item.id });
|
|
1937
|
+
await deliverInboxItemChange({
|
|
1941
1938
|
change,
|
|
1942
1939
|
delivery,
|
|
1943
1940
|
item,
|
|
@@ -1948,7 +1945,7 @@ async function act(args) {
|
|
|
1948
1945
|
function cardTarget(payload) {
|
|
1949
1946
|
const channelId = parseSlackChannelId(payload.channel?.id);
|
|
1950
1947
|
const messageTs = parseSlackMessageTs(payload.message?.ts);
|
|
1951
|
-
if (!channelId || !messageTs) throw new Error("Slack
|
|
1948
|
+
if (!channelId || !messageTs) throw new Error("Slack inbox item payload is incomplete");
|
|
1952
1949
|
return {
|
|
1953
1950
|
channelId,
|
|
1954
1951
|
messageTs,
|
|
@@ -1958,23 +1955,23 @@ function cardTarget(payload) {
|
|
|
1958
1955
|
async function openAnswerForm(args) {
|
|
1959
1956
|
const { target } = args;
|
|
1960
1957
|
const triggerId = args.payload.trigger_id;
|
|
1961
|
-
if (!triggerId) throw new Error("Slack
|
|
1958
|
+
if (!triggerId) throw new Error("Slack inbox item form payload is missing a trigger id");
|
|
1962
1959
|
const actor = await resolveActingUser(args.services, args.payload, target);
|
|
1963
1960
|
if (!actor) return;
|
|
1964
1961
|
let item;
|
|
1965
1962
|
try {
|
|
1966
|
-
item = await
|
|
1963
|
+
item = await readInboxItemForUser(actor.user, args.itemId);
|
|
1967
1964
|
} catch (error) {
|
|
1968
|
-
if (!(error instanceof
|
|
1965
|
+
if (!(error instanceof InboxItemActionError)) throw error;
|
|
1969
1966
|
await tellPerson(target, actor.slackUserId, error.message);
|
|
1970
1967
|
return;
|
|
1971
1968
|
}
|
|
1972
|
-
if (!
|
|
1969
|
+
if (!canActOnInboxItem(item, actor.user.id)) {
|
|
1973
1970
|
await tellPerson(target, actor.slackUserId, item.status === "open" ? "Only an assignee can act on this item." : "This item is already closed.");
|
|
1974
1971
|
await refreshCards(args.services, actor.user, item.id);
|
|
1975
1972
|
return;
|
|
1976
1973
|
}
|
|
1977
|
-
const view =
|
|
1974
|
+
const view = buildSlackInboxItemModal(item, {
|
|
1978
1975
|
...target,
|
|
1979
1976
|
itemId: item.id
|
|
1980
1977
|
});
|
|
@@ -1984,8 +1981,8 @@ async function openAnswerForm(args) {
|
|
|
1984
1981
|
view
|
|
1985
1982
|
});
|
|
1986
1983
|
}
|
|
1987
|
-
/** Handle one click on
|
|
1988
|
-
async function
|
|
1984
|
+
/** Handle one click on an Inbox item card. */
|
|
1985
|
+
async function handleSlackInboxItemClick(args) {
|
|
1989
1986
|
const { click, payload, services } = args;
|
|
1990
1987
|
const target = cardTarget(payload);
|
|
1991
1988
|
if (click.kind === "answer") {
|
|
@@ -1998,11 +1995,11 @@ async function handleSlackReviewItemClick(args) {
|
|
|
1998
1995
|
return;
|
|
1999
1996
|
}
|
|
2000
1997
|
const actionTs = parseSlackMessageTs(args.action.action_ts);
|
|
2001
|
-
if (!actionTs) throw new Error("Slack
|
|
1998
|
+
if (!actionTs) throw new Error("Slack inbox item click payload is incomplete");
|
|
2002
1999
|
const common = {
|
|
2003
2000
|
inputTs: actionTs,
|
|
2004
2001
|
itemId: click.itemId,
|
|
2005
|
-
messageId: `slack-
|
|
2002
|
+
messageId: `slack-inbox-item:${actionTs}`,
|
|
2006
2003
|
payload,
|
|
2007
2004
|
services,
|
|
2008
2005
|
target
|
|
@@ -2019,7 +2016,7 @@ async function handleSlackReviewItemClick(args) {
|
|
|
2019
2016
|
action: "submit",
|
|
2020
2017
|
answer: (item) => {
|
|
2021
2018
|
const field = item.request && buttonUserInputField(item.request);
|
|
2022
|
-
if (!field?.options.some((option) => option.label === click.label)) throw new
|
|
2019
|
+
if (!field?.options.some((option) => option.label === click.label)) throw new InboxItemActionError("conflict", "This card changed. Use the updated card.");
|
|
2023
2020
|
return {
|
|
2024
2021
|
requestId: item.id,
|
|
2025
2022
|
values: { [field.id]: [click.label] }
|
|
@@ -2027,14 +2024,14 @@ async function handleSlackReviewItemClick(args) {
|
|
|
2027
2024
|
}
|
|
2028
2025
|
});
|
|
2029
2026
|
}
|
|
2030
|
-
/** Submit the answer of
|
|
2031
|
-
async function
|
|
2027
|
+
/** Submit the answer of an Inbox item form. */
|
|
2028
|
+
async function handleSlackInboxItemSubmission(args) {
|
|
2032
2029
|
const view = args.payload.view;
|
|
2033
|
-
const formTarget =
|
|
2030
|
+
const formTarget = parseSlackInboxItemFormTarget(view?.private_metadata);
|
|
2034
2031
|
const channelId = parseSlackChannelId(formTarget?.channelId);
|
|
2035
2032
|
const messageTs = parseSlackMessageTs(formTarget?.messageTs);
|
|
2036
2033
|
const threadTs = parseSlackMessageTs(formTarget?.threadTs);
|
|
2037
|
-
if (!view?.id || !formTarget || !channelId || !messageTs || !threadTs) throw new Error("Slack
|
|
2034
|
+
if (!view?.id || !formTarget || !channelId || !messageTs || !threadTs) throw new Error("Slack inbox item form submission is incomplete");
|
|
2038
2035
|
await act({
|
|
2039
2036
|
action: "submit",
|
|
2040
2037
|
answer: (item) => item.request ? parseSlackUserInputSubmission({
|
|
@@ -2047,7 +2044,7 @@ async function handleSlackReviewItemSubmission(args) {
|
|
|
2047
2044
|
},
|
|
2048
2045
|
inputTs: slackMessageTsFromMs(Date.now()),
|
|
2049
2046
|
itemId: formTarget.itemId,
|
|
2050
|
-
messageId: `slack-
|
|
2047
|
+
messageId: `slack-inbox-item:${view.id}`,
|
|
2051
2048
|
payload: args.payload,
|
|
2052
2049
|
services: args.services,
|
|
2053
2050
|
target: {
|
|
@@ -2078,13 +2075,13 @@ async function handleAppHomeDisconnect(args) {
|
|
|
2078
2075
|
});
|
|
2079
2076
|
}
|
|
2080
2077
|
/**
|
|
2081
|
-
* Handle Slack interactions from App Home,
|
|
2078
|
+
* Handle Slack interactions from App Home, Inbox item cards, and dashboard
|
|
2082
2079
|
* link previews: block actions and submitted forms.
|
|
2083
2080
|
*/
|
|
2084
2081
|
async function handleSlackInteractivePayload(args) {
|
|
2085
2082
|
const spanAttributes = { userId: args.payload.user?.id?.trim() || void 0 };
|
|
2086
2083
|
if (args.payload.type === "view_submission" && args.payload.view?.callback_id === "junior_review_item") {
|
|
2087
|
-
await withSpan("chat.
|
|
2084
|
+
await withSpan("chat.slack_inbox_item_submit", "chat.slack_inbox_item_submit", spanAttributes, () => handleSlackInboxItemSubmission({
|
|
2088
2085
|
payload: args.payload,
|
|
2089
2086
|
services: args
|
|
2090
2087
|
}));
|
|
@@ -2092,9 +2089,9 @@ async function handleSlackInteractivePayload(args) {
|
|
|
2092
2089
|
}
|
|
2093
2090
|
if (args.payload.type !== "block_actions") return;
|
|
2094
2091
|
for (const action of args.payload.actions ?? []) {
|
|
2095
|
-
const click =
|
|
2092
|
+
const click = parseSlackInboxItemClick(action);
|
|
2096
2093
|
if (click) {
|
|
2097
|
-
await withSpan("chat.
|
|
2094
|
+
await withSpan("chat.slack_inbox_item_click", "chat.slack_inbox_item_click", spanAttributes, () => handleSlackInboxItemClick({
|
|
2098
2095
|
action,
|
|
2099
2096
|
click,
|
|
2100
2097
|
payload: args.payload,
|
|
@@ -2390,142 +2387,6 @@ function textMentionsBot(text, botUserId) {
|
|
|
2390
2387
|
function eventMentionsBot(event, botUserId) {
|
|
2391
2388
|
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))));
|
|
2392
2389
|
}
|
|
2393
|
-
// src/chat/event-automations/ingest.ts
|
|
2394
|
-
/**
|
|
2395
|
-
* Owns event matching and durable event-automation dispatch.
|
|
2396
|
-
*
|
|
2397
|
-
* Each matching automation is independently idempotent. Aggregate failures propagate
|
|
2398
|
-
* so the provider can retry the original delivery.
|
|
2399
|
-
*/
|
|
2400
|
-
/** Bind provider delivery identity to one automation's durable dispatch. */
|
|
2401
|
-
function eventAutomationDispatchKey(taskId, namespace, eventKey) {
|
|
2402
|
-
return `event-automation:${createHash("sha256").update(`${taskId}\0${namespace}\0${eventKey}`).digest("hex").slice(0, 32)}`;
|
|
2403
|
-
}
|
|
2404
|
-
/** Render plain agent input for one matching event automation. */
|
|
2405
|
-
function eventInput(task, event, outcomes, catalog, author) {
|
|
2406
|
-
const guidance = eventGuidance(catalog, event.namespace, event.eventType);
|
|
2407
|
-
return renderTaskInput({
|
|
2408
|
-
about: task.trigger.label,
|
|
2409
|
-
event: event.eventType,
|
|
2410
|
-
source: event.namespace,
|
|
2411
|
-
creator: slackMention(task.createdBy.slackUserId),
|
|
2412
|
-
instructions: automationTaskText(task.task),
|
|
2413
|
-
...task.task.kind === "skill" ? { skill: task.task.skill } : void 0,
|
|
2414
|
-
outcomes,
|
|
2415
|
-
guidance,
|
|
2416
|
-
trustedSummary: event.trustedSummary,
|
|
2417
|
-
trustedSummaryMaxLength: EVENT_SUMMARY_MAX_LENGTH,
|
|
2418
|
-
verifiedDetails: event.data,
|
|
2419
|
-
authorText: eventAuthorText(author),
|
|
2420
|
-
externalText: event.untrustedText,
|
|
2421
|
-
externalTextMaxLength: EVENT_TEXT_MAX_LENGTH
|
|
2422
|
-
});
|
|
2423
|
-
}
|
|
2424
|
-
/**
|
|
2425
|
-
* Match a normalized event and dispatch every matching automation.
|
|
2426
|
-
*
|
|
2427
|
-
* Plugins publish one copy of an occurrence for each scope, such as a pull
|
|
2428
|
-
* request and its repository. All copies share one event key. An automation
|
|
2429
|
-
* with no identifier matches every copy, and the dispatch key and the run
|
|
2430
|
-
* limit both use the event key, so it runs and counts once.
|
|
2431
|
-
*/
|
|
2432
|
-
async function ingestEventAutomations(input, options) {
|
|
2433
|
-
const event = eventSchema$1.parse(input);
|
|
2434
|
-
const db = getDb();
|
|
2435
|
-
const nowMs = options.nowMs ?? Date.now();
|
|
2436
|
-
const catalog = getEventCatalog();
|
|
2437
|
-
const [matches = []] = await findMatchingEventAutomations(db, [event], options.teamId, catalog);
|
|
2438
|
-
const tasks = matches.filter((task) => slackChannelMessageRunsAutomation(event, task));
|
|
2439
|
-
if (tasks.length === 0) return { dispatched: 0 };
|
|
2440
|
-
const author = await resolveEventAuthor(event);
|
|
2441
|
-
let dispatched = 0;
|
|
2442
|
-
const errors = [];
|
|
2443
|
-
for (const task of tasks) try {
|
|
2444
|
-
const skill = task.task.kind === "skill" ? task.task.skill : void 0;
|
|
2445
|
-
if (skill && !await findAutomationSkill(skill)) {
|
|
2446
|
-
const reason = missingAutomationSkillReason(skill);
|
|
2447
|
-
if (await blockEventAutomation(db, task.id, reason)) await notifyAutomationBlocked({
|
|
2448
|
-
automationId: task.id,
|
|
2449
|
-
kind: "event",
|
|
2450
|
-
reason
|
|
2451
|
-
});
|
|
2452
|
-
continue;
|
|
2453
|
-
}
|
|
2454
|
-
const idempotencyKey = eventAutomationDispatchKey(task.id, event.namespace, event.eventKey);
|
|
2455
|
-
if (await admitEventAutomationRun({
|
|
2456
|
-
automationId: task.id,
|
|
2457
|
-
nowMs,
|
|
2458
|
-
runKey: idempotencyKey
|
|
2459
|
-
}) === "limited") {
|
|
2460
|
-
const reason = eventAutomationRunLimitReason();
|
|
2461
|
-
logWarn("event_automation.run_limit.exceeded", {
|
|
2462
|
-
"app.task.id": task.id,
|
|
2463
|
-
"app.task.type": "event"
|
|
2464
|
-
});
|
|
2465
|
-
if (await blockEventAutomation(db, task.id, reason)) {
|
|
2466
|
-
captureMessage("Event automation blocked by run limit", {
|
|
2467
|
-
level: "warning",
|
|
2468
|
-
fingerprint: ["event_automation.run_limit.blocked"],
|
|
2469
|
-
tags: {
|
|
2470
|
-
"app.event.namespace": event.namespace,
|
|
2471
|
-
"app.task.type": "event"
|
|
2472
|
-
},
|
|
2473
|
-
extra: {
|
|
2474
|
-
"app.event.event_type": event.eventType,
|
|
2475
|
-
"app.event_automation.max_runs": botConfig.maxEventAutomationRuns,
|
|
2476
|
-
"app.event_automation.run_window_ms": botConfig.eventAutomationRunWindowMs,
|
|
2477
|
-
"app.event_automation.resource_type": task.trigger.resourceType ?? "any",
|
|
2478
|
-
"app.task.id": task.id
|
|
2479
|
-
}
|
|
2480
|
-
});
|
|
2481
|
-
await notifyAutomationBlocked({
|
|
2482
|
-
automationId: task.id,
|
|
2483
|
-
kind: "event",
|
|
2484
|
-
reason
|
|
2485
|
-
});
|
|
2486
|
-
}
|
|
2487
|
-
continue;
|
|
2488
|
-
}
|
|
2489
|
-
const replyThreadTs = slackChannelMessageReplyThreadTs(event);
|
|
2490
|
-
const destination = replyThreadTs ? {
|
|
2491
|
-
...task.destination,
|
|
2492
|
-
threadTs: replyThreadTs
|
|
2493
|
-
} : task.destination;
|
|
2494
|
-
const outcomes = effectiveTaskOutcomes(task.outcomes, destination);
|
|
2495
|
-
const credentialSubject = task.credentialMode === "creator" ? {
|
|
2496
|
-
type: "user",
|
|
2497
|
-
userId: task.createdBy.slackUserId,
|
|
2498
|
-
allowedWhen: "event-automation",
|
|
2499
|
-
taskId: task.id
|
|
2500
|
-
} : void 0;
|
|
2501
|
-
const dispatch = await dispatchEventAutomation({
|
|
2502
|
-
automationId: task.id,
|
|
2503
|
-
conversationWorkQueue: options.queue,
|
|
2504
|
-
nowMs,
|
|
2505
|
-
options: {
|
|
2506
|
-
idempotencyKey,
|
|
2507
|
-
...credentialSubject ? { credentialSubject } : void 0,
|
|
2508
|
-
destination,
|
|
2509
|
-
destinationVisibility: task.destinationVisibility,
|
|
2510
|
-
input: eventInput(task, event, outcomes, catalog, author),
|
|
2511
|
-
...skill ? { skill } : void 0,
|
|
2512
|
-
metadata: { eventAutomationId: task.id },
|
|
2513
|
-
replyAttribution: automationReplyAttribution(task.title),
|
|
2514
|
-
outcomes
|
|
2515
|
-
}
|
|
2516
|
-
});
|
|
2517
|
-
await recordEventAutomationRunStarted(db, {
|
|
2518
|
-
automation: task,
|
|
2519
|
-
dispatchId: dispatch.id,
|
|
2520
|
-
nowMs
|
|
2521
|
-
});
|
|
2522
|
-
if (dispatch.status === "created") dispatched += 1;
|
|
2523
|
-
} catch (error) {
|
|
2524
|
-
errors.push(error);
|
|
2525
|
-
}
|
|
2526
|
-
if (errors.length > 0) throw new AggregateError(errors, "Failed to dispatch one or more event automations");
|
|
2527
|
-
return { dispatched };
|
|
2528
|
-
}
|
|
2529
2390
|
// src/chat/ingress/slack-message-telemetry.ts
|
|
2530
2391
|
function field(value, pattern) {
|
|
2531
2392
|
if (value === void 0) return "missing";
|
|
@@ -2918,12 +2779,12 @@ async function routeParsedMessage(args) {
|
|
|
2918
2779
|
});
|
|
2919
2780
|
const closeAnswered = async () => {
|
|
2920
2781
|
if (message.author.isBot === true) return;
|
|
2921
|
-
await
|
|
2782
|
+
await closeInboxItemsAnsweredByReply({
|
|
2922
2783
|
...route === "subscribed" ? { canAnswer: isAuthorTrusted } : void 0,
|
|
2923
2784
|
conversationId,
|
|
2924
2785
|
delivery: {
|
|
2925
2786
|
queue: args.queue,
|
|
2926
|
-
show:
|
|
2787
|
+
show: createSlackInboxItemShow(() => args.adapter)
|
|
2927
2788
|
},
|
|
2928
2789
|
resolveUser: async () => {
|
|
2929
2790
|
const teamId = args.installation.teamId;
|
|
@@ -3463,62 +3324,12 @@ async function publicArtifactGET(args) {
|
|
|
3463
3324
|
headers: unpublishedArtifactHeaders(),
|
|
3464
3325
|
status: 404
|
|
3465
3326
|
});
|
|
3466
|
-
return new Response(artifact.body, { headers: publicArtifactHeaders(artifact.contentType) });
|
|
3327
|
+
return new Response(artifact.body, { headers: publicArtifactHeaders(artifact.contentType, artifact.expiresAt) });
|
|
3467
3328
|
} catch (error) {
|
|
3468
3329
|
logException(error, "public_artifact.get.failed");
|
|
3469
3330
|
return new Response("Internal Server Error", { status: 500 });
|
|
3470
3331
|
}
|
|
3471
3332
|
}
|
|
3472
|
-
// src/chat/events/app-publisher.ts
|
|
3473
|
-
const WATCH_MATCH_CONCURRENCY = 4;
|
|
3474
|
-
/** Build the core event publisher used by plugin routes. */
|
|
3475
|
-
function createEventAppPublisher(args) {
|
|
3476
|
-
return {
|
|
3477
|
-
async hasMatch(events) {
|
|
3478
|
-
const work = args.conversationWork();
|
|
3479
|
-
const eventAutomationTeamId = await resolveBotSlackTeamId();
|
|
3480
|
-
const [subscriptions, tasks] = await Promise.all([mapBounded(events, (event) => findMatchingWatches({
|
|
3481
|
-
data: event.data,
|
|
3482
|
-
eventType: event.eventType,
|
|
3483
|
-
namespace: event.namespace,
|
|
3484
|
-
identifier: event.identifier,
|
|
3485
|
-
state: work.state
|
|
3486
|
-
}), WATCH_MATCH_CONCURRENCY), eventAutomationTeamId ? findMatchingEventAutomations(getDb(), events, eventAutomationTeamId, getEventCatalog()) : Promise.resolve([])]);
|
|
3487
|
-
return [...subscriptions, ...tasks].some((matched) => matched.length > 0);
|
|
3488
|
-
},
|
|
3489
|
-
async neededMatchKeys(input) {
|
|
3490
|
-
const work = args.conversationWork();
|
|
3491
|
-
const eventAutomationTeamId = await resolveBotSlackTeamId();
|
|
3492
|
-
const [watchKeys, taskKeys] = await Promise.all([collectEventMatchKeys({
|
|
3493
|
-
eventTypes: input.eventTypes,
|
|
3494
|
-
identifiers: input.identifiers,
|
|
3495
|
-
namespace: input.namespace,
|
|
3496
|
-
state: work.state
|
|
3497
|
-
}), eventAutomationTeamId ? collectEventAutomationMatchKeys(getDb(), {
|
|
3498
|
-
catalog: getEventCatalog(),
|
|
3499
|
-
...input.data ? { data: input.data } : void 0,
|
|
3500
|
-
eventTypes: input.eventTypes,
|
|
3501
|
-
identifiers: input.identifiers,
|
|
3502
|
-
namespace: input.namespace,
|
|
3503
|
-
teamId: eventAutomationTeamId
|
|
3504
|
-
}) : Promise.resolve([])]);
|
|
3505
|
-
return [.../* @__PURE__ */ new Set([...watchKeys, ...taskKeys])].sort();
|
|
3506
|
-
},
|
|
3507
|
-
async publish(event) {
|
|
3508
|
-
const work = args.conversationWork();
|
|
3509
|
-
const queue = work.queue ?? getVercelConversationWorkQueue();
|
|
3510
|
-
const eventAutomationTeamId = await resolveBotSlackTeamId();
|
|
3511
|
-
await Promise.all([ingestEvent(event, {
|
|
3512
|
-
queue,
|
|
3513
|
-
slackTeamId: eventAutomationTeamId,
|
|
3514
|
-
state: work.state
|
|
3515
|
-
}), eventAutomationTeamId ? ingestEventAutomations(event, {
|
|
3516
|
-
queue,
|
|
3517
|
-
teamId: eventAutomationTeamId
|
|
3518
|
-
}) : Promise.resolve()]);
|
|
3519
|
-
}
|
|
3520
|
-
};
|
|
3521
|
-
}
|
|
3522
3333
|
// src/chat/agent-dispatch/identity.ts
|
|
3523
3334
|
/**
|
|
3524
3335
|
* Build the one entry point that starts work for a person whom a plugin
|
|
@@ -4748,9 +4559,7 @@ const ACP_CONVERSATION_PREFIX = "local:acp:";
|
|
|
4748
4559
|
const ACP_EVENT_STREAM_MIME_TYPE = "text/event-stream";
|
|
4749
4560
|
const ACP_JSON_MIME_TYPE = "application/json";
|
|
4750
4561
|
const MAX_PROMPT_TEXT_LENGTH = 32e3;
|
|
4751
|
-
|
|
4752
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
4753
|
-
}
|
|
4562
|
+
const urlElicitationCapabilitySchema = z.object({ url: z.object({}) });
|
|
4754
4563
|
function authenticatedAcpUser(connection) {
|
|
4755
4564
|
return connection.user;
|
|
4756
4565
|
}
|
|
@@ -4758,7 +4567,7 @@ function supportsUrlElicitation(params) {
|
|
|
4758
4567
|
const parsed = initializeParamsSchema.safeParse(params);
|
|
4759
4568
|
if (!parsed.success) return false;
|
|
4760
4569
|
const elicitation = parsed.data.clientCapabilities?.["elicitation"];
|
|
4761
|
-
return
|
|
4570
|
+
return urlElicitationCapabilitySchema.safeParse(elicitation).success;
|
|
4762
4571
|
}
|
|
4763
4572
|
function parseParams(schema, params) {
|
|
4764
4573
|
const parsed = schema.safeParse(params);
|
|
@@ -4802,7 +4611,7 @@ function stableHex(value, length = 32) {
|
|
|
4802
4611
|
}
|
|
4803
4612
|
function canonicalJson(value) {
|
|
4804
4613
|
if (Array.isArray(value)) return value.map(canonicalJson);
|
|
4805
|
-
if (
|
|
4614
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return value;
|
|
4806
4615
|
return Object.fromEntries(Object.entries(value).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([key, child]) => [key, canonicalJson(child)]));
|
|
4807
4616
|
}
|
|
4808
4617
|
/** Preserve the JSON-RPC id type and request payload in durable retry keys. */
|
|
@@ -5341,7 +5150,7 @@ const MCP_SCOPES = [
|
|
|
5341
5150
|
"conversations:read",
|
|
5342
5151
|
"conversations:manage",
|
|
5343
5152
|
"conversations:write",
|
|
5344
|
-
"
|
|
5153
|
+
"inbox_items:read",
|
|
5345
5154
|
"automations:read"
|
|
5346
5155
|
];
|
|
5347
5156
|
/** What each scope lets the client do, as the consent page says it. */
|
|
@@ -5349,23 +5158,27 @@ const MCP_SCOPE_DESCRIPTIONS = {
|
|
|
5349
5158
|
"conversations:read": "List and read the conversations that you started or take part in",
|
|
5350
5159
|
"conversations:manage": "Archive, pin, and mark your conversations read, stop a running Turn, and cancel queued messages",
|
|
5351
5160
|
"conversations:write": "Start conversations and send messages as you. Each message starts agent work",
|
|
5352
|
-
"
|
|
5161
|
+
"inbox_items:read": "List and read your inbox items",
|
|
5353
5162
|
"automations:read": "List and read the automations that you can see"
|
|
5354
5163
|
};
|
|
5355
5164
|
/** The `scope` value that names every scope. */
|
|
5356
5165
|
const MCP_ALL_SCOPES = MCP_SCOPES.join(" ");
|
|
5166
|
+
const RENAMED_MCP_SCOPES = { "review_items:read": "inbox_items:read" };
|
|
5167
|
+
function scopeNames(value) {
|
|
5168
|
+
return value.split(" ").filter(Boolean).map((name) => RENAMED_MCP_SCOPES[name] ?? name);
|
|
5169
|
+
}
|
|
5357
5170
|
/**
|
|
5358
5171
|
* Parse a space-separated scope value into known scopes in canonical order.
|
|
5359
5172
|
* Return `undefined` when it is empty or names an unknown scope.
|
|
5360
5173
|
*/
|
|
5361
5174
|
function parseMcpScopes(value) {
|
|
5362
|
-
const names = value
|
|
5175
|
+
const names = scopeNames(value);
|
|
5363
5176
|
if (names.length === 0) return void 0;
|
|
5364
5177
|
if (!names.every((name) => MCP_SCOPES.includes(name))) return void 0;
|
|
5365
5178
|
return MCP_SCOPES.filter((scope) => names.includes(scope));
|
|
5366
5179
|
}
|
|
5367
5180
|
/** A stored scope value: known scopes, space-separated, in canonical order. */
|
|
5368
|
-
const mcpScopeValueSchema = z.string().refine((value) => parseMcpScopes(value)?.join(" ") === value);
|
|
5181
|
+
const mcpScopeValueSchema = z.string().refine((value) => parseMcpScopes(value)?.join(" ") === scopeNames(value).join(" "));
|
|
5369
5182
|
// src/api/mcp/oauth/authorization.ts
|
|
5370
5183
|
/**
|
|
5371
5184
|
* Own the OAuth authorization endpoint and its pending requests.
|
|
@@ -5379,7 +5192,7 @@ const AUTHORIZATION_TTL_MS = 6e5;
|
|
|
5379
5192
|
const STATE_MAX_LENGTH = 1e3;
|
|
5380
5193
|
const AUTHORIZATION_ID_PATTERN = /^[A-Za-z0-9_-]{43}$/;
|
|
5381
5194
|
const CODE_CHALLENGE_PATTERN = /^[A-Za-z0-9_-]{43}$/;
|
|
5382
|
-
const mcpAuthorizationSchema
|
|
5195
|
+
const mcpAuthorizationSchema = z.object({
|
|
5383
5196
|
clientId: z.string().min(1),
|
|
5384
5197
|
clientName: z.string().min(1).optional(),
|
|
5385
5198
|
codeChallenge: z.string().regex(CODE_CHALLENGE_PATTERN),
|
|
@@ -5410,7 +5223,7 @@ function claimedKey(authorizationId) {
|
|
|
5410
5223
|
*/
|
|
5411
5224
|
async function readMcpAuthorization(state, authorizationId) {
|
|
5412
5225
|
if (!AUTHORIZATION_ID_PATTERN.test(authorizationId)) return void 0;
|
|
5413
|
-
const authorization = await readRecord(state, authorizationKey(authorizationId), mcpAuthorizationSchema
|
|
5226
|
+
const authorization = await readRecord(state, authorizationKey(authorizationId), mcpAuthorizationSchema);
|
|
5414
5227
|
if (!authorization || authorization.expiresAtMs <= Date.now()) return;
|
|
5415
5228
|
if (await state.get(claimedKey(authorizationId)) !== null) return void 0;
|
|
5416
5229
|
return {
|
|
@@ -5673,7 +5486,7 @@ async function refreshGrant(args) {
|
|
|
5673
5486
|
const token = await readRecord(args.state, key, tokenSchema);
|
|
5674
5487
|
const grant = token ? await readGrant(args.state, token.grantId) : void 0;
|
|
5675
5488
|
if (!token || !grant || grant.clientId !== args.clientId || args.resource !== void 0 && args.resource !== grant.resource) return invalidGrant("The refresh token is not valid.");
|
|
5676
|
-
if (args.scope !== void 0 && parseMcpScopes(args.scope)?.join(" ") !== grant.scope) return {
|
|
5489
|
+
if (args.scope !== void 0 && parseMcpScopes(args.scope)?.join(" ") !== parseMcpScopes(grant.scope)?.join(" ")) return {
|
|
5677
5490
|
description: `Refresh keeps the granted scope: ${grant.scope}.`,
|
|
5678
5491
|
error: "invalid_scope",
|
|
5679
5492
|
ok: false
|
|
@@ -5868,167 +5681,6 @@ async function handleMcpConsentPage(args) {
|
|
|
5868
5681
|
state: authorization.state
|
|
5869
5682
|
});
|
|
5870
5683
|
}
|
|
5871
|
-
// src/api/mcp/conversation.ts
|
|
5872
|
-
/** Own the MCP view of one Conversation, shared by the conversation tools. */
|
|
5873
|
-
/** MCP view of one Conversation. It omits dashboard-only fields. */
|
|
5874
|
-
const mcpConversationSchema = z.object({
|
|
5875
|
-
conversationId: z.string(),
|
|
5876
|
-
title: z.string(),
|
|
5877
|
-
status: conversationReportStatusSchema.describe("`active` while work runs, waits to start, or waits on you. `completed` when no work is left. `failed` when the last turn failed. `stopped` after a person or a parent agent stopped it, until a person sends it input or its parent gives it new work."),
|
|
5878
|
-
surface: conversationSurfaceSchema.describe("Where it started: `slack`, `api` (the dashboard or MCP), `scheduler` (an automation), or `internal`."),
|
|
5879
|
-
channelName: z.string().optional().describe("Slack channel name."),
|
|
5880
|
-
locationUrl: z.string().optional().describe("Slack thread link."),
|
|
5881
|
-
startedAt: z.string(),
|
|
5882
|
-
lastSeenAt: z.string().describe("Time of the newest activity. archiveConversation takes this value."),
|
|
5883
|
-
archivedAt: z.string().optional().describe("Set when anyone archived it. Archive applies to everyone."),
|
|
5884
|
-
pinnedAt: z.string().optional().describe("Set when you pinned it."),
|
|
5885
|
-
url: z.string().optional().describe("Dashboard link.")
|
|
5886
|
-
}).strict();
|
|
5887
|
-
/** Map a Conversation summary to its MCP view. */
|
|
5888
|
-
function mcpConversation(summary) {
|
|
5889
|
-
return {
|
|
5890
|
-
conversationId: summary.conversationId,
|
|
5891
|
-
title: summary.displayTitle,
|
|
5892
|
-
status: summary.status,
|
|
5893
|
-
surface: summary.surface,
|
|
5894
|
-
channelName: summary.channelNameRedacted ? void 0 : summary.channelName,
|
|
5895
|
-
locationUrl: summary.locationUrl,
|
|
5896
|
-
startedAt: summary.startedAt,
|
|
5897
|
-
lastSeenAt: summary.lastSeenAt,
|
|
5898
|
-
archivedAt: summary.archivedAt ?? void 0,
|
|
5899
|
-
pinnedAt: summary.pinnedAt ?? void 0,
|
|
5900
|
-
url: getDashboardConversationLink(summary.conversationId)
|
|
5901
|
-
};
|
|
5902
|
-
}
|
|
5903
|
-
/** Conversation id param shared by the conversation tools. */
|
|
5904
|
-
const mcpConversationIdSchema = z.string().min(1).describe("Conversation id from searchConversations or createConversation.");
|
|
5905
|
-
const mcpAttachmentsSchema = z.array(z.object({
|
|
5906
|
-
filename: z.string(),
|
|
5907
|
-
contentType: z.string(),
|
|
5908
|
-
bytes: z.number().int()
|
|
5909
|
-
}).strict()).optional();
|
|
5910
|
-
function mcpAttachments(attachments) {
|
|
5911
|
-
return attachments?.length ? attachments.map(({ bytes, contentType, filename }) => ({
|
|
5912
|
-
bytes,
|
|
5913
|
-
contentType,
|
|
5914
|
-
filename
|
|
5915
|
-
})) : void 0;
|
|
5916
|
-
}
|
|
5917
|
-
function mcpAuthor(identity) {
|
|
5918
|
-
return identity?.fullName ?? identity?.slackUserName ?? identity?.email;
|
|
5919
|
-
}
|
|
5920
|
-
/** MCP view of one user or assistant Message. */
|
|
5921
|
-
const mcpMessageSchema = z.object({
|
|
5922
|
-
seq: z.number().int().describe("Position in the transcript. markConversationRead takes this value."),
|
|
5923
|
-
messageId: z.string().describe("For a message that you sent, the `messageId` that sendMessage or createConversation returned."),
|
|
5924
|
-
createdAt: z.string(),
|
|
5925
|
-
role: z.enum(["assistant", "user"]),
|
|
5926
|
-
author: z.string().optional(),
|
|
5927
|
-
text: z.string(),
|
|
5928
|
-
attachments: mcpAttachmentsSchema
|
|
5929
|
-
}).strict();
|
|
5930
|
-
/**
|
|
5931
|
-
* Keep the user and assistant Messages of a report event page, in order.
|
|
5932
|
-
* System Messages and Messages with no text or attachment are left out.
|
|
5933
|
-
*/
|
|
5934
|
-
function mcpMessages(events) {
|
|
5935
|
-
return events.flatMap((event) => {
|
|
5936
|
-
const data = event.data;
|
|
5937
|
-
if (data.type !== "message" || data.role === "system") return [];
|
|
5938
|
-
const text = data.text ?? "";
|
|
5939
|
-
const attachments = mcpAttachments(data.attachments);
|
|
5940
|
-
if (!text && !attachments) return [];
|
|
5941
|
-
const author = mcpAuthor(data.actorIdentity);
|
|
5942
|
-
return [{
|
|
5943
|
-
seq: event.seq,
|
|
5944
|
-
messageId: data.messageId,
|
|
5945
|
-
createdAt: event.createdAt,
|
|
5946
|
-
role: data.role,
|
|
5947
|
-
...author ? { author } : void 0,
|
|
5948
|
-
text,
|
|
5949
|
-
...attachments ? { attachments } : void 0
|
|
5950
|
-
}];
|
|
5951
|
-
});
|
|
5952
|
-
}
|
|
5953
|
-
/** Message text param shared by the tools that send a message. */
|
|
5954
|
-
const mcpMessageTextSchema = z.string().trim().min(1).max(32e3).describe("Message text.");
|
|
5955
|
-
/**
|
|
5956
|
-
* Idempotency key param shared by the tools that send a message. A retry
|
|
5957
|
-
* with the same key sends nothing new.
|
|
5958
|
-
*/
|
|
5959
|
-
const mcpIdempotencyKeySchema = z.string().trim().min(1).max(200).optional().describe("Reuse the same key to retry without sending the message twice. Omit it to send a new message.");
|
|
5960
|
-
/**
|
|
5961
|
-
* MCP view of one accepted user Message that no Turn has read yet. It is not
|
|
5962
|
-
* in the transcript, so it has no `seq`.
|
|
5963
|
-
*/
|
|
5964
|
-
const mcpPendingMessageSchema = z.object({
|
|
5965
|
-
messageId: z.string(),
|
|
5966
|
-
createdAt: z.string(),
|
|
5967
|
-
author: z.string().optional(),
|
|
5968
|
-
text: z.string(),
|
|
5969
|
-
attachments: mcpAttachmentsSchema,
|
|
5970
|
-
delivery: conversationPendingMessageDeliverySchema.describe("`defer` waits for the running turn to end. `interrupt` joins the running turn at its next safe step.")
|
|
5971
|
-
}).strict();
|
|
5972
|
-
/** Pending Messages field shared by `getConversation` and the send tools. */
|
|
5973
|
-
const mcpPendingMessagesSchema = z.array(mcpPendingMessageSchema).describe("Accepted messages that no turn has read yet, oldest first. A message leaves this list when a turn reads it.");
|
|
5974
|
-
/** Authorization that a parked Turn waits for. */
|
|
5975
|
-
const mcpAuthorizationSchema = z.object({
|
|
5976
|
-
label: z.string(),
|
|
5977
|
-
url: z.string()
|
|
5978
|
-
}).strict().describe("Set when a turn waits for you to connect an account. Open `url` in a browser to continue.");
|
|
5979
|
-
/**
|
|
5980
|
-
* Read the Messages that wait for a Turn and the authorization that a parked
|
|
5981
|
-
* Turn waits for. The caller must check that `user` is a participant.
|
|
5982
|
-
*/
|
|
5983
|
-
async function readMcpPendingWork(user, conversationId) {
|
|
5984
|
-
const report = await readConversationPendingMessages(conversationId, { viewer: user });
|
|
5985
|
-
const pendingMessages = (report?.messages ?? []).flatMap((message) => {
|
|
5986
|
-
if (message.text === void 0) return [];
|
|
5987
|
-
const author = mcpAuthor(message.actorIdentity);
|
|
5988
|
-
const attachments = mcpAttachments(message.attachments);
|
|
5989
|
-
return [{
|
|
5990
|
-
messageId: message.messageId,
|
|
5991
|
-
createdAt: message.createdAt,
|
|
5992
|
-
...author ? { author } : void 0,
|
|
5993
|
-
text: message.text,
|
|
5994
|
-
...attachments ? { attachments } : void 0,
|
|
5995
|
-
delivery: message.delivery
|
|
5996
|
-
}];
|
|
5997
|
-
});
|
|
5998
|
-
const authorization = report?.authorization;
|
|
5999
|
-
return {
|
|
6000
|
-
pendingMessages,
|
|
6001
|
-
...authorization ? { authorization: {
|
|
6002
|
-
label: authorization.label,
|
|
6003
|
-
url: authorization.authorizationUrl
|
|
6004
|
-
} } : void 0
|
|
6005
|
-
};
|
|
6006
|
-
}
|
|
6007
|
-
/**
|
|
6008
|
-
* Read pending work for a send result. The message already landed, so a
|
|
6009
|
-
* failed read drops these optional fields instead of turning the accepted
|
|
6010
|
-
* send into a tool error that a client may retry.
|
|
6011
|
-
*/
|
|
6012
|
-
async function readMcpPendingWorkAfterSend(user, conversationId) {
|
|
6013
|
-
try {
|
|
6014
|
-
return await readMcpPendingWork(user, conversationId);
|
|
6015
|
-
} catch (error) {
|
|
6016
|
-
logException(error, "mcp.pending_work.read.failed", { "gen_ai.conversation.id": conversationId });
|
|
6017
|
-
return {};
|
|
6018
|
-
}
|
|
6019
|
-
}
|
|
6020
|
-
/** `cursor` result field shared by getConversation and the send tools. */
|
|
6021
|
-
const mcpCursorSchema = z.string().describe("Pass as `after` to getConversation to read the messages that come after this point.");
|
|
6022
|
-
/** Result of a tool that sends a message. */
|
|
6023
|
-
const mcpAcceptedMessageSchema = {
|
|
6024
|
-
conversationId: z.string(),
|
|
6025
|
-
messageId: z.string().describe("Id of your message in `pendingMessages`, and later in the transcript."),
|
|
6026
|
-
status: z.enum(["accepted", "duplicate"]).describe("`duplicate` when the idempotency key was already used."),
|
|
6027
|
-
pendingMessages: mcpPendingMessagesSchema.optional().describe("Accepted messages that no turn has read yet, oldest first. Missing when the read failed after your message was accepted; use getConversation."),
|
|
6028
|
-
authorization: mcpAuthorizationSchema.optional(),
|
|
6029
|
-
cursor: mcpCursorSchema,
|
|
6030
|
-
url: z.string().optional().describe("Dashboard link.")
|
|
6031
|
-
};
|
|
6032
5684
|
// src/api/mcp/tool-context.ts
|
|
6033
5685
|
/**
|
|
6034
5686
|
* Return one structured tool result. The text block holds the same JSON, as
|
|
@@ -6069,80 +5721,24 @@ function apiToolError(error) {
|
|
|
6069
5721
|
async function isConversationParticipant(user, conversationId) {
|
|
6070
5722
|
return (await readConversationAccessFromSql(getDb(), [conversationId], user)).get(conversationId)?.isParticipant ?? false;
|
|
6071
5723
|
}
|
|
6072
|
-
// src/api/mcp/tools/
|
|
5724
|
+
// src/api/mcp/tools/api-operation.ts
|
|
6073
5725
|
/**
|
|
6074
|
-
* Register
|
|
6075
|
-
*
|
|
5726
|
+
* Register an API operation as an MCP tool. A client error from the
|
|
5727
|
+
* operation becomes a tool error.
|
|
6076
5728
|
*/
|
|
6077
|
-
function
|
|
6078
|
-
server.registerTool(
|
|
6079
|
-
title:
|
|
6080
|
-
description:
|
|
6081
|
-
inputSchema:
|
|
6082
|
-
|
|
6083
|
-
archived: z.boolean().default(true).describe("False restores an archived conversation."),
|
|
6084
|
-
applyToChildren: z.boolean().default(false).describe("On archive, true also archives every child of this conversation at any depth; without it, the archive fails while any of its children is not archived. On restore, true also restores the children that were archived with this conversation."),
|
|
6085
|
-
lastSeenAt: z.string().datetime().describe("`lastSeenAt` from searchConversations or getConversation. The archive fails when the conversation has newer activity.")
|
|
6086
|
-
},
|
|
6087
|
-
outputSchema: { archivedAt: z.string().nullable().describe("Null when the conversation is not archived.") },
|
|
5729
|
+
function registerApiOperationTool(server, operation, { queue, user }) {
|
|
5730
|
+
server.registerTool(operation.name, {
|
|
5731
|
+
title: operation.title,
|
|
5732
|
+
description: operation.description,
|
|
5733
|
+
inputSchema: operation.input,
|
|
5734
|
+
outputSchema: operation.output,
|
|
6088
5735
|
annotations: {
|
|
6089
|
-
|
|
6090
|
-
|
|
6091
|
-
openWorldHint: false,
|
|
6092
|
-
readOnlyHint: false
|
|
6093
|
-
}
|
|
6094
|
-
}, async ({ applyToChildren, archived, conversationId, lastSeenAt }) => {
|
|
6095
|
-
try {
|
|
6096
|
-
return mcpToolResult(await archiveConversation(user, conversationId, {
|
|
6097
|
-
applyToChildren,
|
|
6098
|
-
archived,
|
|
6099
|
-
lastSeenAt
|
|
6100
|
-
}));
|
|
6101
|
-
} catch (error) {
|
|
6102
|
-
return apiToolError(error);
|
|
6103
|
-
}
|
|
6104
|
-
});
|
|
6105
|
-
}
|
|
6106
|
-
// src/api/mcp/tools/archive-done-conversations.ts
|
|
6107
|
-
/**
|
|
6108
|
-
* Register `archiveDoneConversations`, which archives every done
|
|
6109
|
-
* Conversation of the user once.
|
|
6110
|
-
*/
|
|
6111
|
-
function registerArchiveDoneConversationsTool(server, { user }) {
|
|
6112
|
-
server.registerTool("archiveDoneConversations", {
|
|
6113
|
-
title: "Archive done conversations",
|
|
6114
|
-
description: "Archive all of your conversations whose work is done and that stayed quiet for your auto-archive wait time, once. It skips conversations that anyone pinned or turned auto-archive off for, and conversations that wait on a person. Archive applies to everyone in the conversation.",
|
|
6115
|
-
inputSchema: {},
|
|
6116
|
-
outputSchema: { archived: z.number().int().describe("Conversations archived.") },
|
|
6117
|
-
annotations: {
|
|
6118
|
-
destructiveHint: false,
|
|
6119
|
-
idempotentHint: true,
|
|
6120
|
-
openWorldHint: false,
|
|
6121
|
-
readOnlyHint: false
|
|
6122
|
-
}
|
|
6123
|
-
}, async () => mcpToolResult(await archiveViewerDoneConversations(user)));
|
|
6124
|
-
}
|
|
6125
|
-
// src/api/mcp/tools/cancel-queued-messages.ts
|
|
6126
|
-
/**
|
|
6127
|
-
* Register `cancelQueuedMessages`, which drops the messages that wait for
|
|
6128
|
-
* the running Turn and leaves the Turn running.
|
|
6129
|
-
*/
|
|
6130
|
-
function registerCancelQueuedMessagesTool(server, { user }) {
|
|
6131
|
-
server.registerTool("cancelQueuedMessages", {
|
|
6132
|
-
title: "Cancel queued messages",
|
|
6133
|
-
description: "Drop every message that waits for the running turn of one of your conversations. The running turn continues.",
|
|
6134
|
-
inputSchema: { conversationId: mcpConversationIdSchema },
|
|
6135
|
-
outputSchema: { cancelledMessages: z.number().int().describe("Messages dropped.") },
|
|
6136
|
-
annotations: {
|
|
6137
|
-
destructiveHint: true,
|
|
6138
|
-
idempotentHint: true,
|
|
6139
|
-
openWorldHint: false,
|
|
6140
|
-
readOnlyHint: false
|
|
5736
|
+
...operation.annotations,
|
|
5737
|
+
openWorldHint: false
|
|
6141
5738
|
}
|
|
6142
|
-
}, async (
|
|
6143
|
-
if (!await isConversationParticipant(user, conversationId)) return mcpToolError("Conversation not found.");
|
|
5739
|
+
}, async (input) => {
|
|
6144
5740
|
try {
|
|
6145
|
-
return mcpToolResult(
|
|
5741
|
+
return mcpToolResult(await operation.run(user, input, { queue }));
|
|
6146
5742
|
} catch (error) {
|
|
6147
5743
|
return apiToolError(error);
|
|
6148
5744
|
}
|
|
@@ -6294,22 +5890,6 @@ function registerGetAutomationTool(server, { user }) {
|
|
|
6294
5890
|
});
|
|
6295
5891
|
}
|
|
6296
5892
|
// src/api/mcp/tools/get-conversation.ts
|
|
6297
|
-
const mcpBriefSchema = conversationBriefSchema.omit({
|
|
6298
|
-
keywords: true,
|
|
6299
|
-
record: true,
|
|
6300
|
-
schemaVersion: true
|
|
6301
|
-
}).extend({ updatedAt: z.string() });
|
|
6302
|
-
function mcpBrief(brief, updatedAt) {
|
|
6303
|
-
return {
|
|
6304
|
-
summary: brief.summary,
|
|
6305
|
-
intent: brief.intent,
|
|
6306
|
-
outcome: brief.outcome,
|
|
6307
|
-
decisions: brief.decisions,
|
|
6308
|
-
facts: brief.facts,
|
|
6309
|
-
links: brief.links,
|
|
6310
|
-
updatedAt
|
|
6311
|
-
};
|
|
6312
|
-
}
|
|
6313
5893
|
const RECENT_EVENT_LIMIT = 100;
|
|
6314
5894
|
const AFTER_EVENT_SCAN_LIMIT = 200;
|
|
6315
5895
|
const AFTER_MESSAGE_LIMIT = 20;
|
|
@@ -6334,25 +5914,24 @@ async function readMessagesAfter(conversationId, afterSeq) {
|
|
|
6334
5914
|
};
|
|
6335
5915
|
}
|
|
6336
5916
|
/**
|
|
6337
|
-
* Register `getConversation`. It returns metadata, the
|
|
5917
|
+
* Register `getConversation`. It returns metadata, the summary, and the last
|
|
6338
5918
|
* Reply or the Messages after a cursor, not the whole transcript.
|
|
6339
5919
|
*/
|
|
6340
5920
|
function registerGetConversationTool(server, { user }) {
|
|
6341
5921
|
server.registerTool("getConversation", {
|
|
6342
5922
|
title: "Get conversation",
|
|
6343
|
-
description: "Get one conversation: its metadata, its
|
|
5923
|
+
description: "Get one conversation: its metadata, including its summary, the messages that no turn has read yet, and a `cursor`. Without `after`, it returns the last assistant reply. With `after`, it returns the messages after that point instead. To follow a conversation, call it again with the newest `cursor` until `turnActive` is false and `hasMore` is not set. Use listConversationMessages for older messages.",
|
|
6344
5924
|
inputSchema: {
|
|
6345
5925
|
conversationId: mcpConversationIdSchema,
|
|
6346
5926
|
after: z.string().min(1).max(1e3).optional().describe("`cursor` from sendMessage, createConversation, or an earlier getConversation call.")
|
|
6347
5927
|
},
|
|
6348
5928
|
outputSchema: {
|
|
6349
5929
|
conversation: mcpConversationSchema,
|
|
6350
|
-
brief: mcpBriefSchema.optional(),
|
|
6351
5930
|
lastReply: mcpMessageSchema.optional().describe("Newest assistant message in the recent events. Set only without `after`."),
|
|
6352
5931
|
messages: z.array(mcpMessageSchema).optional().describe("User and assistant messages after `after`, oldest first. Set only with `after`."),
|
|
6353
|
-
hasMore: z.boolean().optional().describe("True when more messages already follow `cursor`. Call again now, also when `
|
|
5932
|
+
hasMore: z.boolean().optional().describe("True when more messages already follow `cursor`. Call again now, also when `turnActive` is false."),
|
|
6354
5933
|
pendingMessages: mcpPendingMessagesSchema,
|
|
6355
|
-
authorization: mcpAuthorizationSchema.optional(),
|
|
5934
|
+
authorization: mcpAuthorizationSchema$1.optional(),
|
|
6356
5935
|
cursor: mcpCursorSchema
|
|
6357
5936
|
},
|
|
6358
5937
|
annotations: {
|
|
@@ -6381,7 +5960,6 @@ function registerGetConversationTool(server, { user }) {
|
|
|
6381
5960
|
const cursorSeq = newer?.seq ?? detail.events.at(-1)?.seq ?? -1;
|
|
6382
5961
|
return mcpToolResult({
|
|
6383
5962
|
conversation: mcpConversation(detail),
|
|
6384
|
-
...detail.brief ? { brief: mcpBrief(detail.brief.content, detail.brief.updatedAt) } : void 0,
|
|
6385
5963
|
...lastReply ? { lastReply } : void 0,
|
|
6386
5964
|
...newer ? { messages: newer.messages } : void 0,
|
|
6387
5965
|
...newer?.hasMore ? { hasMore: true } : void 0,
|
|
@@ -6393,15 +5971,15 @@ function registerGetConversationTool(server, { user }) {
|
|
|
6393
5971
|
});
|
|
6394
5972
|
});
|
|
6395
5973
|
}
|
|
6396
|
-
// src/api/mcp/
|
|
5974
|
+
// src/api/mcp/inbox-item.ts
|
|
6397
5975
|
/**
|
|
6398
|
-
* Own the MCP view of one
|
|
5976
|
+
* Own the MCP view of one Inbox item, shared by the inbox item tools.
|
|
6399
5977
|
*
|
|
6400
|
-
* MCP
|
|
5978
|
+
* MCP Inbox items stay read-only. An answer sends a message to the linked
|
|
6401
5979
|
* Conversations, which can start a Turn. A dismiss starts no Turn.
|
|
6402
5980
|
*/
|
|
6403
|
-
/** MCP view of one
|
|
6404
|
-
const
|
|
5981
|
+
/** MCP view of one Inbox item. Answers happen in Slack or the dashboard. */
|
|
5982
|
+
const mcpInboxItemSchema = z.object({
|
|
6405
5983
|
id: z.string(),
|
|
6406
5984
|
kind: z.enum(["notice", "action"]),
|
|
6407
5985
|
status: z.enum([
|
|
@@ -6424,9 +6002,9 @@ const mcpReviewItemSchema = z.object({
|
|
|
6424
6002
|
updatedAt: z.string(),
|
|
6425
6003
|
url: z.string().optional().describe("Dashboard link to answer it.")
|
|
6426
6004
|
}).strict();
|
|
6427
|
-
/** Map
|
|
6428
|
-
function
|
|
6429
|
-
const url =
|
|
6005
|
+
/** Map an Inbox item to its MCP view for one user. */
|
|
6006
|
+
function mcpInboxItem(item, userId) {
|
|
6007
|
+
const url = getDashboardInboxItemLink(item.id);
|
|
6430
6008
|
return {
|
|
6431
6009
|
id: item.id,
|
|
6432
6010
|
kind: item.kind,
|
|
@@ -6435,7 +6013,7 @@ function mcpReviewItem(item, userId) {
|
|
|
6435
6013
|
body: item.body,
|
|
6436
6014
|
...item.request ? { question: item.request.question } : void 0,
|
|
6437
6015
|
assignees: item.assignedToEveryone ? [] : item.assignees.map((person) => person.displayName ?? person.email),
|
|
6438
|
-
canAct:
|
|
6016
|
+
canAct: canActOnInboxItem(item, userId),
|
|
6439
6017
|
conversationIds: item.conversationIds,
|
|
6440
6018
|
...item.subject ? { subject: {
|
|
6441
6019
|
id: item.subject.id,
|
|
@@ -6447,14 +6025,14 @@ function mcpReviewItem(item, userId) {
|
|
|
6447
6025
|
...url ? { url } : void 0
|
|
6448
6026
|
};
|
|
6449
6027
|
}
|
|
6450
|
-
// src/api/mcp/tools/get-
|
|
6451
|
-
/** Register `
|
|
6452
|
-
function
|
|
6453
|
-
server.registerTool("
|
|
6454
|
-
title: "Get
|
|
6455
|
-
description: "Get one
|
|
6456
|
-
inputSchema: { id: z.string().min(1).describe("
|
|
6457
|
-
outputSchema: { item:
|
|
6028
|
+
// src/api/mcp/tools/get-inbox-item.ts
|
|
6029
|
+
/** Register `getInboxItem`, which reads one Inbox item in any status. */
|
|
6030
|
+
function registerGetInboxItemTool(server, { user }) {
|
|
6031
|
+
server.registerTool("getInboxItem", {
|
|
6032
|
+
title: "Get inbox item",
|
|
6033
|
+
description: "Get one inbox item, open or closed.",
|
|
6034
|
+
inputSchema: { id: z.string().min(1).describe("Inbox item id from searchInboxItems.") },
|
|
6035
|
+
outputSchema: { item: mcpInboxItemSchema },
|
|
6458
6036
|
annotations: {
|
|
6459
6037
|
destructiveHint: false,
|
|
6460
6038
|
idempotentHint: true,
|
|
@@ -6463,9 +6041,9 @@ function registerGetReviewItemTool(server, { user }) {
|
|
|
6463
6041
|
}
|
|
6464
6042
|
}, async ({ id }) => {
|
|
6465
6043
|
try {
|
|
6466
|
-
return mcpToolResult({ item:
|
|
6044
|
+
return mcpToolResult({ item: mcpInboxItem(await readInboxItemForUser(user, id), user.id) });
|
|
6467
6045
|
} catch (error) {
|
|
6468
|
-
if (error instanceof
|
|
6046
|
+
if (error instanceof InboxItemActionError) return mcpToolError(error.message);
|
|
6469
6047
|
throw error;
|
|
6470
6048
|
}
|
|
6471
6049
|
});
|
|
@@ -6587,31 +6165,6 @@ function registerMarkConversationReadTool(server, { user }) {
|
|
|
6587
6165
|
}
|
|
6588
6166
|
});
|
|
6589
6167
|
}
|
|
6590
|
-
// src/api/mcp/tools/pin-conversation.ts
|
|
6591
|
-
/** Register `pinConversation`, which pins or unpins for the user. */
|
|
6592
|
-
function registerPinConversationTool(server, { user }) {
|
|
6593
|
-
server.registerTool("pinConversation", {
|
|
6594
|
-
title: "Pin conversation",
|
|
6595
|
-
description: "Pin one of your top-level conversations, or unpin it. A child conversation cannot be pinned or unpinned; it uses the pin of its root. A pin applies only to you, restores an archived conversation, and keeps auto-archive from archiving it.",
|
|
6596
|
-
inputSchema: {
|
|
6597
|
-
conversationId: mcpConversationIdSchema,
|
|
6598
|
-
pinned: z.boolean().default(true).describe("False unpins the conversation.")
|
|
6599
|
-
},
|
|
6600
|
-
outputSchema: { pinnedAt: z.string().nullable().describe("Null when the conversation is not pinned.") },
|
|
6601
|
-
annotations: {
|
|
6602
|
-
destructiveHint: false,
|
|
6603
|
-
idempotentHint: true,
|
|
6604
|
-
openWorldHint: false,
|
|
6605
|
-
readOnlyHint: false
|
|
6606
|
-
}
|
|
6607
|
-
}, async ({ conversationId, pinned }) => {
|
|
6608
|
-
try {
|
|
6609
|
-
return mcpToolResult(await pinConversation(user, conversationId, { pinned }));
|
|
6610
|
-
} catch (error) {
|
|
6611
|
-
return apiToolError(error);
|
|
6612
|
-
}
|
|
6613
|
-
});
|
|
6614
|
-
}
|
|
6615
6168
|
// src/api/mcp/tools/search-conversations.ts
|
|
6616
6169
|
/** Register `searchConversations`, which searches the Conversations of the user. */
|
|
6617
6170
|
function registerSearchConversationsTool(server, { user }) {
|
|
@@ -6620,7 +6173,7 @@ function registerSearchConversationsTool(server, { user }) {
|
|
|
6620
6173
|
title: "Search conversations",
|
|
6621
6174
|
description: "Search your conversations and return up to 50, newest activity first. Only conversations that you started or take part in match.",
|
|
6622
6175
|
inputSchema: {
|
|
6623
|
-
q: feedQuery.q.describe("Text to search for in titles and
|
|
6176
|
+
q: feedQuery.q.describe("Text to search for in titles, summaries, and Annotation labels and titles."),
|
|
6624
6177
|
status: feedQuery.status.describe("Return conversations that are not archived (default) or that are archived. A search ignores this filter.")
|
|
6625
6178
|
},
|
|
6626
6179
|
outputSchema: { conversations: z.array(mcpConversationSchema) },
|
|
@@ -6638,19 +6191,19 @@ function registerSearchConversationsTool(server, { user }) {
|
|
|
6638
6191
|
})).conversations.map(mcpConversation) });
|
|
6639
6192
|
});
|
|
6640
6193
|
}
|
|
6641
|
-
// src/api/mcp/tools/search-
|
|
6642
|
-
/** Register `
|
|
6643
|
-
function
|
|
6644
|
-
server.registerTool("
|
|
6645
|
-
title: "Search
|
|
6646
|
-
description: "Search the open
|
|
6194
|
+
// src/api/mcp/tools/search-inbox-items.ts
|
|
6195
|
+
/** Register `searchInboxItems`, which searches open Inbox items for the user. */
|
|
6196
|
+
function registerSearchInboxItemsTool(server, { user }) {
|
|
6197
|
+
server.registerTool("searchInboxItems", {
|
|
6198
|
+
title: "Search inbox items",
|
|
6199
|
+
description: "Search the open inbox items that you can see, newest change first. An inbox item is a question or notice that waits for a person.",
|
|
6647
6200
|
inputSchema: {
|
|
6648
6201
|
q: z.string().trim().min(1).max(200).optional().describe("Words to find in the title or body."),
|
|
6649
6202
|
conversationId: z.string().min(1).optional().describe("Return only the items linked to this conversation."),
|
|
6650
6203
|
limit: z.number().int().min(1).max(50).default(20).describe("Maximum number of items.")
|
|
6651
6204
|
},
|
|
6652
6205
|
outputSchema: {
|
|
6653
|
-
items: z.array(
|
|
6206
|
+
items: z.array(mcpInboxItemSchema),
|
|
6654
6207
|
truncated: z.boolean().describe("True when more items match.")
|
|
6655
6208
|
},
|
|
6656
6209
|
annotations: {
|
|
@@ -6660,14 +6213,14 @@ function registerSearchReviewItemsTool(server, { user }) {
|
|
|
6660
6213
|
readOnlyHint: true
|
|
6661
6214
|
}
|
|
6662
6215
|
}, async ({ conversationId, limit, q }) => {
|
|
6663
|
-
const items = await
|
|
6216
|
+
const items = await searchInboxItems(getDb(), conversationId ? await inboxItemReaderForUserInConversation(user, conversationId) : inboxItemReaderForUser(user), {
|
|
6664
6217
|
...conversationId ? { conversationId } : void 0,
|
|
6665
6218
|
limit: limit + 1,
|
|
6666
6219
|
...q ? { query: q } : void 0,
|
|
6667
6220
|
statuses: ["open"]
|
|
6668
6221
|
});
|
|
6669
6222
|
return mcpToolResult({
|
|
6670
|
-
items: items.slice(0, limit).map((item) =>
|
|
6223
|
+
items: items.slice(0, limit).map((item) => mcpInboxItem(item, user.id)),
|
|
6671
6224
|
truncated: items.length > limit
|
|
6672
6225
|
});
|
|
6673
6226
|
});
|
|
@@ -6705,15 +6258,10 @@ function registerSendMessageTool(server, { attachmentStorage, queue, user }) {
|
|
|
6705
6258
|
}, {
|
|
6706
6259
|
attachmentStorage,
|
|
6707
6260
|
queue
|
|
6708
|
-
});
|
|
6261
|
+
}, delivery);
|
|
6709
6262
|
} catch (error) {
|
|
6710
6263
|
return apiToolError(error);
|
|
6711
6264
|
}
|
|
6712
|
-
if (delivery === "interrupt") try {
|
|
6713
|
-
await steerConversationPendingMessagesForViewer(user, conversationId, { inboundMessageIds: [accepted.messageId] });
|
|
6714
|
-
} catch (error) {
|
|
6715
|
-
logException(error, "mcp.send_message.steer.failed", { "gen_ai.conversation.id": conversationId });
|
|
6716
|
-
}
|
|
6717
6265
|
const messageSeq = accepted.status === "duplicate" ? await readConversationMessageEventSeq(getSqlExecutor(), accepted.conversationId, accepted.messageId) : void 0;
|
|
6718
6266
|
return mcpToolResult({
|
|
6719
6267
|
...accepted,
|
|
@@ -6726,133 +6274,38 @@ function registerSendMessageTool(server, { attachmentStorage, queue, user }) {
|
|
|
6726
6274
|
});
|
|
6727
6275
|
});
|
|
6728
6276
|
}
|
|
6729
|
-
// src/api/mcp/tools/set-conversation-auto-archive.ts
|
|
6730
|
-
/**
|
|
6731
|
-
* Register `setConversationAutoArchive`, which overrides the user's
|
|
6732
|
-
* auto-archive default for one Conversation.
|
|
6733
|
-
*/
|
|
6734
|
-
function registerSetConversationAutoArchiveTool(server, { user }) {
|
|
6735
|
-
server.registerTool("setConversationAutoArchive", {
|
|
6736
|
-
title: "Set conversation auto-archive",
|
|
6737
|
-
description: "Turn auto-archive on or off for one of your conversations. This overrides your default for that conversation only.",
|
|
6738
|
-
inputSchema: {
|
|
6739
|
-
conversationId: mcpConversationIdSchema,
|
|
6740
|
-
autoArchive: z.boolean().describe("True lets auto-archive archive the conversation for everyone after its work is done. False keeps it from auto-archive for everyone.")
|
|
6741
|
-
},
|
|
6742
|
-
outputSchema: { autoArchive: z.boolean() },
|
|
6743
|
-
annotations: {
|
|
6744
|
-
destructiveHint: false,
|
|
6745
|
-
idempotentHint: true,
|
|
6746
|
-
openWorldHint: false,
|
|
6747
|
-
readOnlyHint: false
|
|
6748
|
-
}
|
|
6749
|
-
}, async ({ autoArchive, conversationId }) => {
|
|
6750
|
-
try {
|
|
6751
|
-
return mcpToolResult(await setConversationAutoArchive(user, conversationId, autoArchive));
|
|
6752
|
-
} catch (error) {
|
|
6753
|
-
return apiToolError(error);
|
|
6754
|
-
}
|
|
6755
|
-
});
|
|
6756
|
-
}
|
|
6757
|
-
// src/api/mcp/tools/set-conversation-subscription.ts
|
|
6758
|
-
/**
|
|
6759
|
-
* Register `setConversationSubscription`, which subscribes or unsubscribes
|
|
6760
|
-
* the user. It never changes another person's subscription.
|
|
6761
|
-
*/
|
|
6762
|
-
function registerSetConversationSubscriptionTool(server, { user }) {
|
|
6763
|
-
server.registerTool("setConversationSubscription", {
|
|
6764
|
-
title: "Set conversation subscription",
|
|
6765
|
-
description: "Subscribe to one of your conversations, or unsubscribe from it. Unsubscribe removes it only from your feed and clears your pin. When nobody else is subscribed, it archives the conversation for everyone. Your next mention of the bot in it subscribes you again.",
|
|
6766
|
-
inputSchema: {
|
|
6767
|
-
conversationId: mcpConversationIdSchema,
|
|
6768
|
-
subscribed: z.boolean().describe("False unsubscribes you.")
|
|
6769
|
-
},
|
|
6770
|
-
outputSchema: {
|
|
6771
|
-
archivedAt: z.string().nullable().describe("Set when the conversation is archived for everyone."),
|
|
6772
|
-
subscribed: z.boolean()
|
|
6773
|
-
},
|
|
6774
|
-
annotations: {
|
|
6775
|
-
destructiveHint: false,
|
|
6776
|
-
idempotentHint: true,
|
|
6777
|
-
openWorldHint: false,
|
|
6778
|
-
readOnlyHint: false
|
|
6779
|
-
}
|
|
6780
|
-
}, async ({ conversationId, subscribed }) => {
|
|
6781
|
-
try {
|
|
6782
|
-
return mcpToolResult(await setConversationSubscription(user, conversationId, { subscribed }));
|
|
6783
|
-
} catch (error) {
|
|
6784
|
-
return apiToolError(error);
|
|
6785
|
-
}
|
|
6786
|
-
});
|
|
6787
|
-
}
|
|
6788
|
-
// src/api/mcp/tools/stop-conversation.ts
|
|
6789
|
-
/**
|
|
6790
|
-
* Register `stopConversation`, which stops the Conversation and every child
|
|
6791
|
-
* agent below it until the person sends the Conversation input.
|
|
6792
|
-
*/
|
|
6793
|
-
function registerStopConversationTool(server, { queue, user }) {
|
|
6794
|
-
server.registerTool("stopConversation", {
|
|
6795
|
-
title: "Stop conversation",
|
|
6796
|
-
description: "Stop one of your conversations: its running turn and every child agent below it. Until you send the conversation a message, watch events of it and its child agents are saved to the conversation but start no turn. Messages that wait for the turn are dropped. It starts no new work.",
|
|
6797
|
-
inputSchema: { conversationId: mcpConversationIdSchema },
|
|
6798
|
-
outputSchema: {
|
|
6799
|
-
status: z.enum(["no_work", "requested"]).describe("`requested` when the running turn was asked to stop. `no_work` when no turn was running. Child agents are stopped in both cases."),
|
|
6800
|
-
droppedMessages: z.number().int().describe("Messages that waited for the turn and were dropped.")
|
|
6801
|
-
},
|
|
6802
|
-
annotations: {
|
|
6803
|
-
destructiveHint: true,
|
|
6804
|
-
idempotentHint: true,
|
|
6805
|
-
openWorldHint: false,
|
|
6806
|
-
readOnlyHint: false
|
|
6807
|
-
}
|
|
6808
|
-
}, async ({ conversationId }) => {
|
|
6809
|
-
if (!await isConversationParticipant(user, conversationId)) return mcpToolError("Conversation not found.");
|
|
6810
|
-
try {
|
|
6811
|
-
const result = await stopConversationTurnForViewer(user, conversationId, { queue });
|
|
6812
|
-
return mcpToolResult({
|
|
6813
|
-
status: result.status,
|
|
6814
|
-
droppedMessages: result.stoppedInboundMessageIds.length
|
|
6815
|
-
});
|
|
6816
|
-
} catch (error) {
|
|
6817
|
-
return apiToolError(error);
|
|
6818
|
-
}
|
|
6819
|
-
});
|
|
6820
|
-
}
|
|
6821
6277
|
// src/api/mcp/server.ts
|
|
6822
6278
|
/**
|
|
6823
|
-
* Own the MCP server behind `/api/mcp`.
|
|
6824
|
-
* `tools
|
|
6279
|
+
* Own the MCP server behind `/api/mcp`. A tool that the REST API also serves
|
|
6280
|
+
* is an API operation, registered by `tools/api-operation.ts`; each other tool
|
|
6281
|
+
* lives in its own file under `tools/`.
|
|
6825
6282
|
*
|
|
6826
6283
|
* Each request gets a new server and a stateless transport that answers with
|
|
6827
6284
|
* JSON. No MCP session or SSE stream outlives the request, so the route works
|
|
6828
6285
|
* on any app instance and is not limited by the live-stream duration.
|
|
6829
6286
|
*/
|
|
6830
|
-
/**
|
|
6287
|
+
/** Operations that the REST API also serves. Each names its own scope. */
|
|
6288
|
+
const OPERATIONS = [...conversationOperations];
|
|
6289
|
+
/**
|
|
6290
|
+
* The hand-written tools that each scope unlocks. A client sees only its
|
|
6291
|
+
* granted tools.
|
|
6292
|
+
*/
|
|
6831
6293
|
const TOOLS_BY_SCOPE = {
|
|
6832
6294
|
"conversations:read": [
|
|
6833
6295
|
registerSearchConversationsTool,
|
|
6834
6296
|
registerGetConversationTool,
|
|
6835
6297
|
registerListConversationMessagesTool
|
|
6836
6298
|
],
|
|
6837
|
-
"conversations:manage": [
|
|
6838
|
-
registerArchiveConversationTool,
|
|
6839
|
-
registerArchiveDoneConversationsTool,
|
|
6840
|
-
registerPinConversationTool,
|
|
6841
|
-
registerSetConversationAutoArchiveTool,
|
|
6842
|
-
registerSetConversationSubscriptionTool,
|
|
6843
|
-
registerMarkConversationReadTool,
|
|
6844
|
-
registerStopConversationTool,
|
|
6845
|
-
registerCancelQueuedMessagesTool
|
|
6846
|
-
],
|
|
6299
|
+
"conversations:manage": [registerMarkConversationReadTool],
|
|
6847
6300
|
"conversations:write": [registerCreateConversationTool, registerSendMessageTool],
|
|
6848
|
-
"
|
|
6301
|
+
"inbox_items:read": [registerSearchInboxItemsTool, registerGetInboxItemTool],
|
|
6849
6302
|
"automations:read": [registerSearchAutomationsTool, registerGetAutomationTool]
|
|
6850
6303
|
};
|
|
6851
6304
|
function readInstructions(agentName) {
|
|
6852
|
-
return `${agentName} is a Slack agent. These tools read and manage your ${agentName} conversations, and read your
|
|
6305
|
+
return `${agentName} is a Slack agent. These tools read and manage your ${agentName} conversations, and read your inbox items and automations. They cannot send a message or start agent work. To ask ${agentName} for work or to answer an inbox item, use the Slack or dashboard link in a result.`;
|
|
6853
6306
|
}
|
|
6854
6307
|
function writeInstructions(agentName) {
|
|
6855
|
-
return `${agentName} is a Slack agent. These tools read and manage your ${agentName} conversations, and read your
|
|
6308
|
+
return `${agentName} is a Slack agent. These tools read and manage your ${agentName} conversations, and read your inbox items and automations. createConversation and sendMessage send a message as you, and ${agentName} works on it in the background. They return a \`cursor\`. Call getConversation with \`after\` set to the newest \`cursor\` to read the new messages. Repeat until \`status\` is not \`active\` and \`hasMore\` is not set. \`authorization\` means a turn waits for you to connect an account. To answer an inbox item, use the dashboard link in a result.`;
|
|
6856
6309
|
}
|
|
6857
6310
|
/** Build the MCP server for one authenticated user and granted scopes. */
|
|
6858
6311
|
function createMcpServer(context, scopes) {
|
|
@@ -6861,6 +6314,7 @@ function createMcpServer(context, scopes) {
|
|
|
6861
6314
|
version: JUNIOR_VERSION
|
|
6862
6315
|
}, { instructions: scopes.includes("conversations:write") ? writeInstructions(botConfig.userName) : readInstructions(botConfig.userName) });
|
|
6863
6316
|
for (const scope of scopes) for (const register of TOOLS_BY_SCOPE[scope]) register(server, context);
|
|
6317
|
+
for (const operation of OPERATIONS) if (scopes.includes(operation.scope)) registerApiOperationTool(server, operation, context);
|
|
6864
6318
|
return server;
|
|
6865
6319
|
}
|
|
6866
6320
|
/** Answer one Streamable HTTP POST for an authenticated user. */
|
|
@@ -7376,6 +6830,7 @@ function dashboardHostRoutePaths(dashboard, authenticatedRoutes = []) {
|
|
|
7376
6830
|
`${conversationsPath}/*`,
|
|
7377
6831
|
pagePath("locations"),
|
|
7378
6832
|
`${pagePath("locations")}/*`,
|
|
6833
|
+
pagePath("inbox"),
|
|
7379
6834
|
pagePath("review"),
|
|
7380
6835
|
peoplePath,
|
|
7381
6836
|
`${peoplePath}/*`,
|
|
@@ -7405,6 +6860,8 @@ function dashboardHostRoutePaths(dashboard, authenticatedRoutes = []) {
|
|
|
7405
6860
|
loginPath,
|
|
7406
6861
|
"/api/health",
|
|
7407
6862
|
"/api/runtime",
|
|
6863
|
+
"/api/memory",
|
|
6864
|
+
"/api/memory/*",
|
|
7408
6865
|
"/api/plugins",
|
|
7409
6866
|
"/api/plugins/*",
|
|
7410
6867
|
"/api/plugin-reports",
|
|
@@ -7423,6 +6880,7 @@ function dashboardHostRoutePaths(dashboard, authenticatedRoutes = []) {
|
|
|
7423
6880
|
"/api/notifications",
|
|
7424
6881
|
"/api/notifications/*",
|
|
7425
6882
|
"/api/images/*",
|
|
6883
|
+
"/api/lead",
|
|
7426
6884
|
"/api/objects",
|
|
7427
6885
|
"/api/stats",
|
|
7428
6886
|
"/api/versions",
|
|
@@ -7432,14 +6890,16 @@ function dashboardHostRoutePaths(dashboard, authenticatedRoutes = []) {
|
|
|
7432
6890
|
"/api/locations/*",
|
|
7433
6891
|
"/api/people",
|
|
7434
6892
|
"/api/people/*",
|
|
7435
|
-
"/api/
|
|
7436
|
-
"/api/
|
|
6893
|
+
"/api/inbox/*",
|
|
6894
|
+
"/api/inbox-items",
|
|
6895
|
+
"/api/inbox-items/*",
|
|
7437
6896
|
"/api/personal-tokens",
|
|
7438
6897
|
"/api/personal-tokens/*",
|
|
7439
6898
|
"/api/service-accounts",
|
|
7440
6899
|
"/api/service-accounts/*",
|
|
7441
6900
|
"/api/cache-warming",
|
|
7442
6901
|
"/api/cache-warming/*",
|
|
6902
|
+
"/api/gateway-providers",
|
|
7443
6903
|
"/api/workspaces",
|
|
7444
6904
|
"/api/workspaces/*",
|
|
7445
6905
|
"/api/config",
|
|
@@ -7627,8 +7087,8 @@ async function createApp(options) {
|
|
|
7627
7087
|
const previousConfigDefaults = getConfigDefaults();
|
|
7628
7088
|
const previousSandboxResources = getSandboxResourceConfig();
|
|
7629
7089
|
const previousExperimentalFeatures = getExperimentalFeatures();
|
|
7630
|
-
const previousBriefsConfig = setBriefsConfig(options?.briefs);
|
|
7631
7090
|
const previousEventEmbeddingsConfig = setEventEmbeddingsConfig(options?.eventEmbeddings);
|
|
7091
|
+
const previousMemoryConfig = setMemoryConfig(options?.memory);
|
|
7632
7092
|
const previousDashboardLinkOptions = setDashboardConversationLinkOptions(dashboard);
|
|
7633
7093
|
let previousTrustConfig;
|
|
7634
7094
|
const restoreRuntimeConfig$1 = () => {
|
|
@@ -7639,8 +7099,8 @@ async function createApp(options) {
|
|
|
7639
7099
|
restoreRuntimeConfig(previousRuntimeConfig);
|
|
7640
7100
|
setSandboxResourceConfig(previousSandboxResources);
|
|
7641
7101
|
setExperimentalFeatures(previousExperimentalFeatures);
|
|
7642
|
-
setBriefsConfig(previousBriefsConfig);
|
|
7643
7102
|
setEventEmbeddingsConfig(previousEventEmbeddingsConfig);
|
|
7103
|
+
setMemoryConfig(previousMemoryConfig);
|
|
7644
7104
|
setDashboardConversationLinkOptions(previousDashboardLinkOptions);
|
|
7645
7105
|
};
|
|
7646
7106
|
let pluginRoutes = [];
|
|
@@ -7681,7 +7141,7 @@ async function createApp(options) {
|
|
|
7681
7141
|
pluginRoutes = getPluginRoutes({
|
|
7682
7142
|
dispatchForIdentity,
|
|
7683
7143
|
events,
|
|
7684
|
-
|
|
7144
|
+
showInboxItem: createSlackInboxItemShow(getProductionSlackAdapter)
|
|
7685
7145
|
});
|
|
7686
7146
|
if (dashboard && !dashboard.disabled) {
|
|
7687
7147
|
pluginApiRoutes = getPluginApiRoutes();
|
|
@@ -7902,7 +7362,7 @@ async function createApp(options) {
|
|
|
7902
7362
|
conversationWorkQueue,
|
|
7903
7363
|
dispatchForIdentity,
|
|
7904
7364
|
events,
|
|
7905
|
-
|
|
7365
|
+
showInboxItem: createSlackInboxItemShow(getProductionSlackAdapter)
|
|
7906
7366
|
});
|
|
7907
7367
|
});
|
|
7908
7368
|
app.get("/api/internal/retention", (c) => {
|