@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
|
@@ -1,45 +1,47 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { Aa as ownerConversationId, Ao as getSlackClient, Ar as getDispatchConversationId, Ba as listFiringInboxSnoozeTriggers, Bi as findMatchingEventAutomations, Br as markDispatchCompleted, Ca as dismissOpenInboxItems, Co as verifyScheduledAutomationCredentialSubject, Di as getDashboardLinkFilter, Do as downloadPrivateSlackFile, Dr as claimDispatchMailboxAppend, Eo as SlackActionError, Er as buildDispatchId, Et as createCodeChangePublisher, Fa as SNOOZE_TIMER_EVENT_TYPE, Fr as getPluginDispatchProjection, Ha as settleInboxSnoozes, Ho as updateTimerIndex, Hr as markDispatchRunning, Ii as blockEventAutomation, Ir as isTerminalDispatchStatus, Jn as createPluginAnnotations, Ka as getEventCatalog, Ki as admitEventAutomationRun, Ko as eventGuidance, Li as collectEventAutomationMatchKeys, Lo as streamPrivateSlackFile, Ma as takeInboxItem, Mi as isDashboardLink, Mn as createPluginEmbedder, Mo as isDmChannel, Mr as getDispatchInputMessageId, Ni as parseDashboardConversationLink, No as isSlackRequestTimeout, Nr as getDispatchRecord, Oa as listReplyActionItems, Or as confirmDispatchMailboxAppend, Pa as waitingConversationIdsQuery, Pi as parseDashboardPersonLink, Po as normalizeSlackConversationId, Pr as getDispatchTurnId, Pt as createPluginState, Ro as withSlackRetries, Rr as markDispatchAwaitingResume, So as verifyEventAutomationCredentialSubject, Tt as createPluginInboxItems, Uo as CORE_EVENT_NAMESPACE, Ur as notifyAutomationBlocked, Vr as markDispatchFailed, Wr as addReactionToMessage, Xa as slackChannelMessageReplyThreadTs, Xn as listConversationAnnotationsById, Yi as automationVersionOf, Yn as listConversationAnnotations, Za as slackChannelMessageRunsAutomation, Zr as removeReactionFromMessage, _a as fallbackShortTitle, an as resolveBaseUrl, as as createPluginCache, bo as bindScheduledAutomationCredentialSubject, co as collectEventMatchKeys, cs as completeText, da as readAutomationTitlesByConversationId, di as slackMentionedUserIds, er as lookupSlackUser, fa as recordAutomationExecution, fi as wrapBareSlackUserIds, fo as findMatchingWatches, h as getPlugins, ha as AUTOMATION_ALERT_STEP_FIELD_ID, ho as listConversationsWithWatches, ii as SLACK_USER_MENTION_RE, jr as getDispatchIdForConversation, ki as getDashboardPersonLink, ko as getHeaderString, kr as createOrGetDispatch, kt as createPluginConversationWatches, li as normalizeSlackStatusText, lr as basePluginContext, ma as AUTOMATION_ALERT_STEPS, o as applyPluginFormatMarkdown, oo as cancelSubscriptions, os as completeDecision, pi as truncateStatusText, ps as JUNIOR_NATIVE_EVENT_NAMESPACE, qi as eventAutomationRunLimitReason, r as createUserTokenStore, ra as existingConversationId, rt as storedMessageJson, s as createPluginEventPublisher, tr as lookupSlackUserNames, ui as slackMention, wa as getInboxItem, wi as getDashboardConversationLink, wo as verifySlackDirectCredentialSubject, wr as createPluginLogger, wt as PLUGIN_CHOICE_FIELD_ID, xa as closeInboxItem, xo as bindSlackDirectCredentialSubject, yo as bindEventAutomationCredentialSubject, yt as trimTrailingAssistantMessages, zn as conversationSearchVector, zr as markDispatchBlocked } from "./credentialed-Cb6E2phL.js";
|
|
2
|
+
import { L as acquireActiveLock, O as resolveGatewayModel, P as createCache, U as estimateTextTokens, W as textCharsForTokens, a as getSlackBotToken, c as getSlackSigningSecret, ft as isProviderRetryError, n as botConfig, o as getSlackClientId, r as getChatConfig, s as getSlackClientSecret, v as normalizeSlackEmojiName } from "./config-kXB2Y5tl.js";
|
|
3
3
|
import { t as mapBounded } from "./fan-out-Cod-yEHG.js";
|
|
4
|
-
import { E as withSpan,
|
|
5
|
-
import { h as startSpan } from "./sentry-CPbZjomA.js";
|
|
6
|
-
import { t as JUNIOR_VERSION } from "./version-
|
|
4
|
+
import { E as withSpan, H as buildSentryConversationUrl, J as normalizeIdentityEmail, S as setTags, T as withLogContext, Y as toOptionalString, b as setSpanAttributes, f as logError, h as logWarn, m as logInfo, n as createChatSdkLogger, o as getActiveTraceContext, p as logException, s as getActiveTraceId, t as buildTurnFailureResponse, y as setSentryUser } from "./logging-dQ9ZRGQ8.js";
|
|
5
|
+
import { h as startSpan, n as captureMessage } from "./sentry-CPbZjomA.js";
|
|
6
|
+
import { t as JUNIOR_VERSION } from "./version-Brbtz4Qf.js";
|
|
7
7
|
import { f as parseSlackTeamId, i as isActorUserId, n as createSlackActor, o as isUserActor, r as createSlackResumeActor, s as parseActorUserId, t as createActor, u as parseSlackChannelId, v as parseSlackMessageTs } from "./actor-BsBdxDXQ.js";
|
|
8
|
-
import { A as
|
|
9
|
-
import {
|
|
8
|
+
import { $ as conversationWaitsOnUserSql, $t as resolveActorIdentityId, A as isTopLevelKind, Bn as requireSlackDestination, Cn as conversationIsNotUnsubscribedRoot, Ct as isOnlyAssignee, Dn as viewerMarksFromParticipant, En as rootVisibleToViewer, F as turnBehavior, Gt as hasUserPhoto, H as parseSessionSource, In as nextDetailVersion, Kt as identityAvatarUrl, L as locationFromRow, M as postsRunNotices, Mn as hasAgentTurnUsage, Nn as resolveRootConversationId, On as addAgentTurnUsage, Q as conversationTurnFailedSql, Rn as createSlackDestination, Sn as conversationIsMemberRoot, St as isAutomationAlertItem, T as deliversFinalText, Tn as readMemberParticipants, U as conversationCostOf, X as conversationIsActiveSql, Xt as userAvatarUrlsFromIdentities, Z as conversationStatusSql, Zt as userAvatarUrlsFromJoinedPhotos, _ as readConversationTrees, _n as conversationAccessFromRows, _t as inboxItemOwnedByConversation, a as getConversationStore, b as loadConversationSlackTenantIds, bn as readConversationAccessRows, dn as readCachedUserByEmail, en as saveActorAvatar, et as executionIsActive, f as copyMessageLinks, ft as inboxItemForUser, h as conversationAncestors, hn as canAddConversationMessages, ht as inboxItemNeedsSomeone, it as treeAwaitsAuthorization, jn as agentTurnUsageSchema, m as withConversationEventLock, mt as inboxItemNeedsInput, o as getDb, ot as PLUGIN_INBOX_ITEM_KEY_PREFIX, r as getConversationEventStore, rt as awaitsAuthorizationFrom, s as getSqlExecutor, st as canActOnInboxItem, tt as conversationKindFromRow, ut as canUserReadInboxItem, v as setArchivedAt, vn as createConversationAccessReader, vt as inboxItemPlugin, wn as conversationPinnedForUser, wt as isPluginInboxItem, x as lastMessageAtSql, y as conversationSlackTenantId, yn as readConversationAccessFromSql } from "./db-LAyyX8tk.js";
|
|
9
|
+
import { B as juniorAttachments, C as juniorConversationParticipants, H as juniorConversations, K as juniorUsers, L as juniorCodeChanges, M as juniorConversationEvents, P as juniorConversationAnnotations, U as juniorIdentities, V as juniorMessageAttachments, _ as juniorAutomationRuns, c as juniorTodos, g as juniorAutomations, h as juniorInboxItems, n as isPostgresErrorCode, p as juniorInboxItemConversations, q as juniorDestinations, x as juniorAgentInvocations } from "./executor-SCub-fAq.js";
|
|
10
10
|
import { d as contextProvenance, p as instructionProvenanceFor, t as KNOWN_CONVERSATION_EVENT_TYPES } from "./history-CYstOMKX.js";
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
22
|
-
import {
|
|
23
|
-
import {
|
|
24
|
-
import {
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
27
|
-
import { t as
|
|
28
|
-
import {
|
|
29
|
-
import {
|
|
30
|
-
import { n as
|
|
31
|
-
import {
|
|
32
|
-
import { t as
|
|
33
|
-
import { t as
|
|
34
|
-
import { t as
|
|
35
|
-
import {
|
|
36
|
-
import { n as
|
|
37
|
-
import {
|
|
11
|
+
import { a as getStateValues, i as getStateAdapter, o as setStateValues } from "./adapter-iIq7ihf7.js";
|
|
12
|
+
import { f as actorLogContext, p as credentialContextForActor } from "./registry-CZOzddwu.js";
|
|
13
|
+
import { n as pluginCatalogRuntime } from "./catalog-runtime-D7xapBAX.js";
|
|
14
|
+
import { M as shouldEmitDevAgentTrace, S as canPauseConversationDelivery, a as getMcpOAuthCallbackPath, b as safeLinkUrl, c as latestProgressStatus, f as createSlackInboxItemShow, k as RetryableDeliveryError, l as resolveDestinationVisibility, n as executeAgentRun, o as createClientMetadata, r as buildAuthPauseResponse, s as readMcpClientInformation, t as createAgentRunner } from "./agent-runner-C9iDurwX.js";
|
|
15
|
+
import { d as PluginMcpClient, u as McpAuthorizationRequiredError, v as getMcpStoredOAuthCredentials } from "./service-account-Ts4ulcrV.js";
|
|
16
|
+
import { i as webActorUserIds } from "./state-C1P3_Ywk.js";
|
|
17
|
+
import { $ as recordSubscribedReplyRoute, At as PluginCredentialFailureError, C as getConversation, Cn as buildTurnErrorResponse, Dn as finalizeFailedTurnReplyWithEvent, Gt as abandonTurnRecord, Ht as lostWorkerBeforeFirstSave, I as buildDeterministicAssistantMessageId, J as recordAuthorizationCompleted, Kn as getAssistantReplyText, Kt as completeTurnRecord, L as buildDeterministicTurnId, On as getAgentTurnDiagnosticsAttributes, Pt as AuthorizationFlowDisabledError, R as commitAcceptedReply, Rt as clearPendingAuth, U as loadTurnProjection, Ut as pauseLostWorkerTurn, V as loadConversationProjection, Vt as loadTurnCheckpoint, Wt as saveTurnCheckpoint, Xt as listTurnSummaries, Yt as getTurnRecord, Zt as recordTurnSummary, _t as turnHasReply, a as persistThreadStateById, ar as piMessageFromHistoryItem, ct as buildConversationContext, d as cancelHumanFacingPendingMessages, dn as canJoinTurn, dt as isHumanConversationMessage, fn as canShareTurn, ft as latestConversationMessageSeq, gn as loadTurnStart, gt as trimConversationMessages, hn as getTurnLifecycle, ht as recordDeliveredAssistantMessage, i as persistThreadRuntimeState, it as persistConversationMessages, kn as requireTurnFailureEventId, kt as createPluginEgress, l as appendAndEnqueueInboundMessage, lt as estimateConversationMessagesTokens, mt as normalizeConversationText, n as getPersistedSandboxState, nr as persistWithRetry, nt as hydrateConversationMessages, o as coerceThreadConversationState, ot as resolveConversationTitle, pt as markConversationMessage, qt as failTurnRecord, r as getPersistedThreadState, rr as configValueSchema, rt as persistConversationMessageWindow, t as getLocationConfigurationService, ut as getConversationMessageSlackTs, vt as upsertConversationMessage, w as getConversationWorkState, wt as isEventConversationMessage, xt as EVENT_SYSTEM_ACTOR, z as commitMessages } from "./thread-state-DhPndWi1.js";
|
|
18
|
+
import { $ as conversationReportStatusSchema, Tt as MAX_ATTACHMENT_BYTES, Zt as answeredChoices, en as isEmptyUserInputAnswer, ft as conversationTreeStateSchema, i as isVisionImageMediaType, kt as readMessageAttachments, ot as activityPreviewText, r as detectImageMediaType, sn as automationTaskText, tn as normalizeUserInputAnswer, tt as conversationSurfaceSchema } from "./media-CYm1QD8T.js";
|
|
19
|
+
import { f as readJuniorSecret, t as getVercelConversationWorkQueue } from "./vercel-queue-hW90XzbG.js";
|
|
20
|
+
import { At as conversationSubtree, B as TurnInputCommitLostError, C as resolveEventAuthor, G as isTurnInputDeferredError, H as getConversationTurnBoundaryError, I as getTurnUserReplyAttachmentContext, J as markTurnFailed, K as markTurnClosed, L as getTurnUserSlackMessageTs, Nt as isExperimentalFeatureEnabled, P as getTurnUserMessage, Q as getWebAuthorization, R as ConversationTurnBoundaryError, T as resolveBotSlackTeamId, U as isCooperativeTurnYieldError, V as TurnInputDeferredError, W as isTurnInputCommitLostError, Y as startActiveTurn, at as instructionActorFor, dt as renderTaskInput, et as loadInboxItemInput, f as legacyWebMailboxMetadataSchema, it as buildSteeringPiMessage, jt as conversationSubtreeColumns, k as resumeForPersonInput, l as resolveMailboxTurnWork, lt as withoutSavedSteeringMessages, q as markTurnCompleted, t as ingestEvent, tt as savedInputInstruction, v as eventAuthorText, z as CooperativeTurnYieldError } from "./ingest-BDf3D50j.js";
|
|
21
|
+
import { $r as findAutomationSkill, An as jsonResponse, Br as readConversationSourceTask, Cn as recordFinishedTurnForAutomatedLimit, Ei as providerCacheTtlMs, Fi as gapSegment, Fn as parseSlackMessageReference, Gn as readSlackRawMessageContext, Kn as resolveSlackChannelIdFromMessage, Lr as takeViewerAutomationAlertStep, Ni as NO_REPLY_GAP_MS, Nn as renderAttachmentText, On as setConversationSubscription, Ot as getChildAgentLabel, Pn as renderBlockText, Ti as connectedState, Tn as executeTurn, Wn as parseSlackThreadId, Zr as AutomationEditError, bn as stopConversation, ci as firstLiveSavingsDate, cn as createPausedTurns, ct as archiveConversation, ei as missingAutomationSkillReason, gn as sendSlackReply, hn as resolveSlackReplyTarget, i as GLOBAL_GAPS_TTL_MS, ji as MINUTE_MS, jn as throwApiError, l as isConversationWorkDone, li as historyPeriodSavings, ln as getPausedTurnRequest, lt as conversationReadPositionQuery, mi as replaceHistorySavings, mn as stopAtAutomatedTurnLimit, mt as deliverInboxItemChange, n as CONVERSATION_STATE_TTL_MS, o as segmentGapsKey, oi as addHistoryPeriod, pn as getTurnAuthorization, r as GLOBAL_GAPS_MAX, si as addHistoryWarmupCost, sn as supersedeTurnForInput, st as readLastUserMessageAtByConversation, t as ANSWER_TOOL_ENDINGS, ti as effectiveTaskOutcomes, u as listConversationWork, un as recordFailedDispatchTurn, wn as AgentRunError, xn as stopChildAgentsOf, zr as ViewerTaskNotFoundError } from "./warmup-BDA5myRK.js";
|
|
22
|
+
import { D as getSlackFileId, E as notInheritedByForkChild, M as slackAttachmentsVersionQuery, S as resolveTurnResumeRouting, _ as verifyAttachmentUploads, b as savedTurnMessages, d as recordWebConversationActivity, f as webActorFromUser, j as recordSlackAttachment, k as readAttachmentVisionSummary, l as createAndEnqueueConversation, m as AttachmentUploadError, o as acceptsWebMessages, s as appendAndEnqueueWebMessage, u as createConversationId, x as resolveConversationRouting } from "./start-conversation-CEn2KH1A.js";
|
|
23
|
+
import { a as isConversationMember, i as getConversationInfo, l as listThreadReplies, o as isPublicSlackChannel, r as getChannelMessage } from "./channel-access-CJGfNTdn.js";
|
|
24
|
+
import { r as isFileAttachment, s as storeAttachment } from "./store-DFZaN-Ix.js";
|
|
25
|
+
import { u as OPEN_TODO_STATUSES } from "./result-event-type-BdIJuZxg.js";
|
|
26
|
+
import { n as getTurnRequestDeadline } from "./callback-mFlTUWWx.js";
|
|
27
|
+
import { t as webMessageId } from "./web-message-id-C6P83ans.js";
|
|
28
|
+
import { t as runWithSlackInstallation } from "./adapter-context-BRjEWRy1.js";
|
|
29
|
+
import { B as webPageObjectCard, E as healthReportSchema, L as conversationObjectCard, R as messageObjectCard, _ as cancelConversationPendingMessagesResponseSchema, b as conversationPendingMessageDeliverySchema, c as pinConversationBodySchema, f as archiveConversationBodySchema, g as cancelConversationPendingMessagesBodySchema, h as conversationAutoArchiveSchema, l as pinConversationResponseSchema, m as archiveDoneConversationsResponseSchema, o as conversationSubscriptionBodySchema, p as archiveConversationResponseSchema, r as stopConversationTurnResponseSchema, s as conversationSubscriptionResponseSchema, z as personObjectCard } from "./conversation-feed-uNOv_x68.js";
|
|
30
|
+
import { a as withTurnSpan, i as turnInputTelemetry, n as createConversationTurnWorker, r as getTurnInputSpanAttributes } from "./conversation-turn-CeLbHqdw.js";
|
|
31
|
+
import { n as attachmentFactLines, r as buildStoredAttachmentPromptText } from "./model-input--TrP9hYV.js";
|
|
32
|
+
import { i as enqueueAgentInvocationResult, n as createDeliverToParent, s as withAgentInvocationResultActors, t as createChildConversationWorker } from "./result-DcvEOe1r.js";
|
|
33
|
+
import { t as bindMessageAgent } from "./message-DSXGj1hM.js";
|
|
34
|
+
import { t as readConversationLineage } from "./lineage-B_m-4TJw.js";
|
|
35
|
+
import { t as bindSpawnAgent } from "./spawn-vxAarlX5.js";
|
|
36
|
+
import { a as buildDeliveredTurnStatePatch, i as persistAuthPauseTurnState, n as loadThreadContextTrimFloor, o as loadPendingMessageCards, r as completeAuthPauseTurn, t as buildTurnThreadContext } from "./thread-context-BkAZDTX2.js";
|
|
37
|
+
import { a as readConversationEventPage, n as scheduleSessionCompletedPluginTasks, o as readConversationEventPageAfter, s as readConversationEventPageAround } from "./task-runner-CbTwFA6k.js";
|
|
38
|
+
import { s as sendVercelPluginTask } from "./task-queue-Cx4Lmjyk.js";
|
|
39
|
+
import { r as canContinueInSlack } from "./continue-in-slack-O6pV5004.js";
|
|
38
40
|
import * as z from "zod";
|
|
39
41
|
import pLimit from "p-limit";
|
|
40
42
|
import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
|
|
41
|
-
import { conversationSidebarAnnotationSchema, createSlackSource, encodeObjectImageRef, escapeTagText, escapeTagTextAndQuotes, objectAnnotationSchema, objectLinkFilterMatches, objectLinkFilterSpecificity, objectTypeSchema, ownedObjectAnnotationSchema, renderEmptyTag, renderTag } from "@sentry/junior-plugin-api";
|
|
42
|
-
import { and, asc, count, desc, eq, gt, gte, inArray, isNotNull, isNull, lt, lte, min, ne, not, or, sql } from "drizzle-orm";
|
|
43
|
+
import { EVENT_SUMMARY_MAX_LENGTH, EVENT_TEXT_MAX_LENGTH, conversationSidebarAnnotationSchema, createSlackSource, dispatchOptionsSchema, encodeObjectImageRef, escapeTagText, escapeTagTextAndQuotes, eventMatches, eventSchema, isSlackDestination, objectAnnotationSchema, objectLinkFilterMatches, objectLinkFilterSpecificity, objectTypeSchema, ownedObjectAnnotationSchema, renderEmptyTag, renderTag } from "@sentry/junior-plugin-api";
|
|
44
|
+
import { and, asc, count, desc, eq, exists, gt, gte, inArray, isNotNull, isNull, lt, lte, min, ne, not, or, sql } from "drizzle-orm";
|
|
43
45
|
import { alias } from "drizzle-orm/pg-core";
|
|
44
46
|
import { Message, ThreadImpl, stringifyMarkdown } from "chat";
|
|
45
47
|
import net from "node:net";
|
|
@@ -202,12 +204,20 @@ async function readFirstHumanMessageTexts(db, conversations) {
|
|
|
202
204
|
return new Map(rows.map((row) => [row.conversationId, row.text]));
|
|
203
205
|
}
|
|
204
206
|
// src/api/conversations/participants.ts
|
|
207
|
+
const userPhotos$1 = alias(juniorIdentities, "user_photos");
|
|
208
|
+
const userPhotoJoin = and(eq(userPhotos$1.userId, juniorIdentities.userId), hasUserPhoto(userPhotos$1));
|
|
205
209
|
const identityColumns = {
|
|
206
210
|
avatarUrl: juniorIdentities.avatarUrl,
|
|
207
211
|
displayName: juniorIdentities.displayName,
|
|
208
212
|
email: juniorIdentities.email,
|
|
209
213
|
handle: juniorIdentities.handle,
|
|
210
214
|
identityId: juniorIdentities.id,
|
|
215
|
+
photo: {
|
|
216
|
+
avatarUrl: userPhotos$1.avatarUrl,
|
|
217
|
+
identityId: userPhotos$1.id,
|
|
218
|
+
provider: userPhotos$1.provider,
|
|
219
|
+
updatedAt: userPhotos$1.updatedAt
|
|
220
|
+
},
|
|
211
221
|
provider: juniorIdentities.provider,
|
|
212
222
|
providerSubjectId: juniorIdentities.providerSubjectId,
|
|
213
223
|
userDisplayName: juniorUsers.displayName,
|
|
@@ -240,15 +250,15 @@ async function readParticipantRows(db, conversationIds) {
|
|
|
240
250
|
const [rootRows, eventRows] = await Promise.all([db.select({
|
|
241
251
|
conversationId: juniorConversations.conversationId,
|
|
242
252
|
...identityColumns
|
|
243
|
-
}).from(juniorConversations).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(inArray(juniorConversations.conversationId, [...conversationIds])), db.select({
|
|
253
|
+
}).from(juniorConversations).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).leftJoin(userPhotos$1, userPhotoJoin).where(inArray(juniorConversations.conversationId, [...conversationIds])), db.select({
|
|
244
254
|
conversationId: authors.conversationId,
|
|
245
255
|
seq: authors.seq,
|
|
246
256
|
...identityColumns
|
|
247
|
-
}).from(authors).innerJoin(juniorIdentities, eq(juniorIdentities.id, authors.actorIdentityId)).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).innerJoin(juniorConversations, eq(juniorConversations.conversationId, authors.conversationId)).innerJoin(juniorConversationParticipants, and(eq(juniorConversationParticipants.userId, juniorIdentities.userId), eq(juniorConversationParticipants.rootConversationId, sql`coalesce(${juniorConversations.rootConversationId}, ${juniorConversations.conversationId})`))).where(inArray(juniorConversations.conversationId, [...conversationIds]))]);
|
|
257
|
+
}).from(authors).innerJoin(juniorIdentities, eq(juniorIdentities.id, authors.actorIdentityId)).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).leftJoin(userPhotos$1, userPhotoJoin).innerJoin(juniorConversations, eq(juniorConversations.conversationId, authors.conversationId)).innerJoin(juniorConversationParticipants, and(eq(juniorConversationParticipants.userId, juniorIdentities.userId), eq(juniorConversationParticipants.rootConversationId, sql`coalesce(${juniorConversations.rootConversationId}, ${juniorConversations.conversationId})`))).where(inArray(juniorConversations.conversationId, [...conversationIds]))]);
|
|
248
258
|
return [...rootRows, ...eventRows.sort((left, right) => left.seq - right.seq)];
|
|
249
259
|
}
|
|
250
|
-
|
|
251
|
-
const userAvatarUrls =
|
|
260
|
+
function groupParticipants(rows) {
|
|
261
|
+
const userAvatarUrls = userAvatarUrlsFromJoinedPhotos(rows);
|
|
252
262
|
const groups = /* @__PURE__ */ new Map();
|
|
253
263
|
for (const row of rows) {
|
|
254
264
|
const participant = participantIdentity(row, userAvatarUrls);
|
|
@@ -263,7 +273,7 @@ async function groupParticipants(db, rows) {
|
|
|
263
273
|
/** Read actor identities in first-appearance order for each Conversation. */
|
|
264
274
|
async function readConversationParticipants(db, conversationIds) {
|
|
265
275
|
if (conversationIds.length === 0) return /* @__PURE__ */ new Map();
|
|
266
|
-
const groups =
|
|
276
|
+
const groups = groupParticipants(await readParticipantRows(db, conversationIds));
|
|
267
277
|
return new Map([...groups].map(([conversationId, group]) => [conversationId, [...group.values()]]));
|
|
268
278
|
}
|
|
269
279
|
/**
|
|
@@ -274,10 +284,11 @@ async function readConversationParticipants(db, conversationIds) {
|
|
|
274
284
|
async function readConversationAuthors(db, conversationId) {
|
|
275
285
|
const rows = await readParticipantRows(db, [conversationId]);
|
|
276
286
|
const userIds = [...new Set(rows.flatMap((row) => row.userId ? [row.userId] : []))];
|
|
277
|
-
const
|
|
287
|
+
const groups = groupParticipants(rows);
|
|
288
|
+
const userIdentities = userIds.length > 0 ? await db.select({
|
|
278
289
|
identityId: juniorIdentities.id,
|
|
279
290
|
userId: juniorIdentities.userId
|
|
280
|
-
}).from(juniorIdentities).where(inArray(juniorIdentities.userId, userIds)) : []
|
|
291
|
+
}).from(juniorIdentities).where(inArray(juniorIdentities.userId, userIds)) : [];
|
|
281
292
|
const group = groups.get(conversationId) ?? /* @__PURE__ */ new Map();
|
|
282
293
|
const authors = {};
|
|
283
294
|
for (const row of [...rows, ...userIdentities]) {
|
|
@@ -409,7 +420,7 @@ function buildSlackLocationUrl(args) {
|
|
|
409
420
|
url.searchParams.set("cid", channelId);
|
|
410
421
|
return url.toString();
|
|
411
422
|
}
|
|
412
|
-
// src/api/conversations/
|
|
423
|
+
// src/api/conversations/location-labels.ts
|
|
413
424
|
/** Format a Slack destination without exposing private channel names. */
|
|
414
425
|
function slackStatsLocationLabel(input) {
|
|
415
426
|
const channelId = input.channel;
|
|
@@ -469,17 +480,6 @@ function actorIdentityReport(actor) {
|
|
|
469
480
|
};
|
|
470
481
|
return Object.keys(identity).length > 0 ? identity : void 0;
|
|
471
482
|
}
|
|
472
|
-
/**
|
|
473
|
-
* A stopped Conversation shows as `stopped` while no work runs. A Turn that
|
|
474
|
-
* runs before the stop ends, such as one that its parent's new work starts,
|
|
475
|
-
* shows as `active`.
|
|
476
|
-
*/
|
|
477
|
-
function statusFromConversation(conversation) {
|
|
478
|
-
const status = conversation.execution.status;
|
|
479
|
-
if (status !== "idle" && status !== "failed") return "active";
|
|
480
|
-
if (conversation.stoppedAtMs !== void 0) return "stopped";
|
|
481
|
-
return status === "idle" ? "completed" : "failed";
|
|
482
|
-
}
|
|
483
483
|
function titleFromConversation(args) {
|
|
484
484
|
const slackThread = parseSlackThreadId(args.conversation.conversationId);
|
|
485
485
|
const effectiveChannelName = args.conversation.channelName;
|
|
@@ -538,7 +538,7 @@ function conversationSummaryFromStoredConversation(args) {
|
|
|
538
538
|
const slackThread = parseSlackThreadId(conversation.conversationId);
|
|
539
539
|
const channelName = channelNameFromConversation(conversation, canViewPrivateContent, visibility);
|
|
540
540
|
const channelNameRedacted = channelNameRedactedFromConversation(conversation, canViewPrivateContent);
|
|
541
|
-
const status =
|
|
541
|
+
const { status } = args;
|
|
542
542
|
return {
|
|
543
543
|
conversationId: conversation.conversationId,
|
|
544
544
|
cumulativeDurationMs: durationMs,
|
|
@@ -551,6 +551,7 @@ function conversationSummaryFromStoredConversation(args) {
|
|
|
551
551
|
visibility
|
|
552
552
|
}),
|
|
553
553
|
kind: conversation.kind,
|
|
554
|
+
...canViewPrivateContent && conversation.summary ? { summary: conversation.summary } : void 0,
|
|
554
555
|
...conversation.parentConversationId ? { parentConversationId: conversation.parentConversationId } : void 0,
|
|
555
556
|
isParticipant: args.access?.isParticipant ?? false,
|
|
556
557
|
...visibility ? { visibility } : void 0,
|
|
@@ -558,6 +559,7 @@ function conversationSummaryFromStoredConversation(args) {
|
|
|
558
559
|
lastSeenAt: new Date(conversation.lastActivityAtMs).toISOString(),
|
|
559
560
|
startedAt: new Date(conversation.createdAtMs).toISOString(),
|
|
560
561
|
status,
|
|
562
|
+
turnActive: executionIsActive(conversation.execution.status),
|
|
561
563
|
surface,
|
|
562
564
|
...args.auxiliaryCosts ? { auxiliaryCosts: args.auxiliaryCosts } : void 0,
|
|
563
565
|
...usage ? { cumulativeUsage: usage } : void 0,
|
|
@@ -573,6 +575,92 @@ function conversationSummaryFromStoredConversation(args) {
|
|
|
573
575
|
...args.locationId && !channelNameRedacted ? { locationId: args.locationId } : void 0
|
|
574
576
|
};
|
|
575
577
|
}
|
|
578
|
+
// src/api/conversations/record.ts
|
|
579
|
+
/**
|
|
580
|
+
* The columns of one Conversation record, for `selectConversationRecords`.
|
|
581
|
+
* Build them for each query: the status binds the app clock.
|
|
582
|
+
*/
|
|
583
|
+
const conversationRecordColumns = () => ({
|
|
584
|
+
conversation: juniorConversations,
|
|
585
|
+
status: conversationStatusSql(juniorConversations),
|
|
586
|
+
location: juniorDestinations,
|
|
587
|
+
identityDisplayName: juniorIdentities.displayName,
|
|
588
|
+
identityEmail: juniorIdentities.email,
|
|
589
|
+
identityHandle: juniorIdentities.handle,
|
|
590
|
+
identityProvider: juniorIdentities.provider,
|
|
591
|
+
identitySubjectId: juniorIdentities.providerSubjectId,
|
|
592
|
+
identityTenantId: juniorIdentities.providerTenantId,
|
|
593
|
+
userDisplayName: juniorUsers.displayName
|
|
594
|
+
});
|
|
595
|
+
/** Left-join conditions from a Conversation to its record tables. */
|
|
596
|
+
const conversationRecordJoins = {
|
|
597
|
+
location: eq(juniorDestinations.id, juniorConversations.destinationId),
|
|
598
|
+
identity: eq(juniorIdentities.id, juniorConversations.actorIdentityId),
|
|
599
|
+
user: eq(juniorUsers.id, juniorIdentities.userId)
|
|
600
|
+
};
|
|
601
|
+
/**
|
|
602
|
+
* Select Conversation rows with their Location and Actor names. Callers add
|
|
603
|
+
* the filter, order, and limit.
|
|
604
|
+
*/
|
|
605
|
+
function selectConversationRecords(db) {
|
|
606
|
+
return db.select(conversationRecordColumns()).from(juniorConversations).leftJoin(juniorDestinations, conversationRecordJoins.location).leftJoin(juniorIdentities, conversationRecordJoins.identity).leftJoin(juniorUsers, conversationRecordJoins.user);
|
|
607
|
+
}
|
|
608
|
+
/** Decode a conversation row with the linked user name and identity-scoped provider fields. */
|
|
609
|
+
function conversationFromRecordRow(row) {
|
|
610
|
+
const value = row.conversation;
|
|
611
|
+
const legacySessionSource = value.sessionSource === null ? void 0 : parseSessionSource(value.sessionSource);
|
|
612
|
+
if (value.sessionSource !== null && !legacySessionSource) throw new Error("Conversation legacy source_json is invalid");
|
|
613
|
+
const actorFullName = row.userDisplayName?.trim() ? row.userDisplayName : row.identityDisplayName;
|
|
614
|
+
const actor = row.identityProvider === "slack" ? {
|
|
615
|
+
platform: "slack",
|
|
616
|
+
...row.identityEmail ? { email: row.identityEmail } : void 0,
|
|
617
|
+
...actorFullName ? { fullName: actorFullName } : void 0,
|
|
618
|
+
...row.identitySubjectId ? { slackUserId: row.identitySubjectId } : void 0,
|
|
619
|
+
...row.identityHandle ? { slackUserName: row.identityHandle } : void 0,
|
|
620
|
+
...row.identityTenantId ? { teamId: row.identityTenantId } : void 0
|
|
621
|
+
} : void 0;
|
|
622
|
+
const location = locationFromRow(value.location, row.location, legacySessionSource);
|
|
623
|
+
return {
|
|
624
|
+
schemaVersion: 1,
|
|
625
|
+
conversationId: value.conversationId,
|
|
626
|
+
createdAtMs: value.createdAt.getTime(),
|
|
627
|
+
kind: conversationKindFromRow(value),
|
|
628
|
+
lastActivityAtMs: value.lastActivityAt.getTime(),
|
|
629
|
+
updatedAtMs: value.updatedAt.getTime(),
|
|
630
|
+
execution: {
|
|
631
|
+
status: value.executionStatus,
|
|
632
|
+
...value.runId ? { runId: value.runId } : void 0,
|
|
633
|
+
...value.executionUpdatedAt ? { updatedAtMs: value.executionUpdatedAt.getTime() } : void 0
|
|
634
|
+
},
|
|
635
|
+
...value.parentConversationId ? { parentConversationId: value.parentConversationId } : void 0,
|
|
636
|
+
...value.archivedAt ? { archivedAtMs: value.archivedAt.getTime() } : void 0,
|
|
637
|
+
...actor ? { actor } : void 0,
|
|
638
|
+
...location ? { location } : void 0,
|
|
639
|
+
...value.channelName ? { channelName: value.channelName } : void 0,
|
|
640
|
+
...value.source ? { source: value.source } : void 0,
|
|
641
|
+
...value.title ? { title: value.title } : void 0,
|
|
642
|
+
...value.summary ? { summary: value.summary } : void 0,
|
|
643
|
+
...value.transcriptPurgedAt ? { transcriptPurgedAtMs: value.transcriptPurgedAt.getTime() } : void 0,
|
|
644
|
+
...value.stoppedAt ? { stoppedAtMs: value.stoppedAt.getTime() } : void 0,
|
|
645
|
+
...value.deliveryPausedAt ? { deliveryPausedAtMs: value.deliveryPausedAt.getTime() } : void 0
|
|
646
|
+
};
|
|
647
|
+
}
|
|
648
|
+
/** Decode one `selectConversationRecords` row into a Conversation record. */
|
|
649
|
+
function conversationRecordFromRow(row) {
|
|
650
|
+
return {
|
|
651
|
+
conversation: conversationFromRecordRow(row),
|
|
652
|
+
durationMs: row.conversation.durationMs,
|
|
653
|
+
...row.location?.visibility === "public" ? { locationId: row.location.id } : void 0,
|
|
654
|
+
status: row.status,
|
|
655
|
+
usage: row.conversation.usage,
|
|
656
|
+
rootConversationId: row.conversation.rootConversationId
|
|
657
|
+
};
|
|
658
|
+
}
|
|
659
|
+
/** Read one normalized conversation record directly from its SQL row. */
|
|
660
|
+
async function readConversationRecordFromSql(conversationId) {
|
|
661
|
+
const row = (await selectConversationRecords(getDb()).where(eq(juniorConversations.conversationId, conversationId)).limit(1))[0];
|
|
662
|
+
return row ? conversationRecordFromRow(row) : void 0;
|
|
663
|
+
}
|
|
576
664
|
// src/api/objects/conversation.ts
|
|
577
665
|
async function readViewerAccess(viewer, conversationId) {
|
|
578
666
|
return (await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId);
|
|
@@ -596,26 +684,27 @@ async function resolveConversationLink(viewer, url) {
|
|
|
596
684
|
const conversationId = parseDashboardConversationLink(url.href);
|
|
597
685
|
const canonicalUrl = conversationId ? getDashboardConversationLink(conversationId) : void 0;
|
|
598
686
|
if (!conversationId || !canonicalUrl) return void 0;
|
|
599
|
-
const
|
|
600
|
-
if (!
|
|
687
|
+
const record = await readConversationRecordFromSql(conversationId);
|
|
688
|
+
if (!record) return void 0;
|
|
689
|
+
const { conversation } = record;
|
|
601
690
|
const db = getDb();
|
|
602
691
|
const access = await readViewerAccess(viewer, conversationId);
|
|
603
692
|
if (!access?.canViewPrivateContent) return void 0;
|
|
604
|
-
const [firstTexts, automationTitles,
|
|
693
|
+
const [firstTexts, automationTitles, participants] = await Promise.all([
|
|
605
694
|
readFirstHumanMessageTexts(db, [conversation]),
|
|
606
695
|
readAutomationTitlesByConversationId([conversation]),
|
|
607
|
-
readLatestConversationBrief(db, conversationId),
|
|
608
696
|
readConversationParticipants(db, [conversationId])
|
|
609
697
|
]);
|
|
610
698
|
return conversationObjectCard({
|
|
611
|
-
|
|
699
|
+
description: conversation.summary,
|
|
612
700
|
participants: participants.get(conversationId) ?? [],
|
|
613
701
|
summary: conversationSummaryFromStoredConversation({
|
|
614
702
|
access,
|
|
615
703
|
automationTitle: automationTitles.get(conversationId),
|
|
616
704
|
conversation,
|
|
617
705
|
durationMs: 0,
|
|
618
|
-
firstHumanMessageText: firstTexts.get(conversationId)
|
|
706
|
+
firstHumanMessageText: firstTexts.get(conversationId),
|
|
707
|
+
status: record.status
|
|
619
708
|
}),
|
|
620
709
|
url: canonicalUrl
|
|
621
710
|
});
|
|
@@ -1212,7 +1301,7 @@ function renderSlackPlainText(mrkdwn, userNames) {
|
|
|
1212
1301
|
function renderTopLevelText(message) {
|
|
1213
1302
|
const blocks = readRawBlocks(message.raw);
|
|
1214
1303
|
const blockText = renderBlockText(blocks);
|
|
1215
|
-
if (Array.isArray(blocks) && blocks.some((block) =>
|
|
1304
|
+
if (Array.isArray(blocks) && blocks.some((block) => typeof block === "object" && block !== null && "type" in block && block.type === "section") && blockText) return blockText;
|
|
1216
1305
|
const rawText = readRawText(message.raw);
|
|
1217
1306
|
if (rawText.trim()) return renderSlackMrkdwn(rawText);
|
|
1218
1307
|
if (message.formatted.children.length > 0) return stringifyMarkdown(message.formatted).trim();
|
|
@@ -2805,14 +2894,14 @@ function readSlackActionToken(message) {
|
|
|
2805
2894
|
const token = slackActionTokenSchema.safeParse(envelope.data.raw?.action_token);
|
|
2806
2895
|
return token.success ? token.data : void 0;
|
|
2807
2896
|
}
|
|
2808
|
-
// src/chat/
|
|
2897
|
+
// src/chat/inbox-items/message-change.ts
|
|
2809
2898
|
const messageChangeRecords = /* @__PURE__ */ new WeakMap();
|
|
2810
2899
|
/** Keep the record of a restored Slack input for its Message write. */
|
|
2811
|
-
function
|
|
2900
|
+
function bindMessageInboxItemChange(message, record) {
|
|
2812
2901
|
if (record) messageChangeRecords.set(message, record);
|
|
2813
2902
|
}
|
|
2814
2903
|
/** Read the record that a restored Slack input carries. */
|
|
2815
|
-
function
|
|
2904
|
+
function getMessageInboxItemChange(message) {
|
|
2816
2905
|
return messageChangeRecords.get(message);
|
|
2817
2906
|
}
|
|
2818
2907
|
// src/chat/slack/assistant-thread/status-render.ts
|
|
@@ -3223,7 +3312,7 @@ function toConversationMessage(args) {
|
|
|
3223
3312
|
const messageHasPotentialImageAttachment = hasPotentialImageAttachment(args.entry.attachments);
|
|
3224
3313
|
const imageAttachmentCount = messageHasPotentialImageAttachment ? countPotentialImageAttachments(args.entry.attachments) : 0;
|
|
3225
3314
|
const authorIdentityId = args.entry.author.isMe ? void 0 : getMessageAuthorIdentityId(args.entry);
|
|
3226
|
-
const reviewItemChange =
|
|
3315
|
+
const reviewItemChange = getMessageInboxItemChange(args.entry);
|
|
3227
3316
|
return {
|
|
3228
3317
|
id: args.entry.id,
|
|
3229
3318
|
role: args.entry.author.isMe ? "assistant" : "user",
|
|
@@ -3392,14 +3481,23 @@ async function persistThreadRuntimeStateWithRetry(conversationId, patch) {
|
|
|
3392
3481
|
* Both are SQL-backed; there is no thread-state fallback.
|
|
3393
3482
|
*/
|
|
3394
3483
|
async function loadPiMessagesForTurn(args) {
|
|
3395
|
-
if (!args.conversationId) return {};
|
|
3484
|
+
if (!args.conversationId) return { seqs: [] };
|
|
3396
3485
|
if (args.activeTurnId) {
|
|
3397
3486
|
const sessionRecord = await getTurnRecord(args.conversationId, args.activeTurnId);
|
|
3398
|
-
if (sessionRecord?.piMessages.length)
|
|
3487
|
+
if (sessionRecord?.piMessages.length) {
|
|
3488
|
+
const piMessages = trimTrailingAssistantMessages(sessionRecord.piMessages);
|
|
3489
|
+
return {
|
|
3490
|
+
piMessages,
|
|
3491
|
+
seqs: sessionRecord.piMessageSeqs.slice(0, piMessages.length)
|
|
3492
|
+
};
|
|
3493
|
+
}
|
|
3399
3494
|
}
|
|
3400
3495
|
const projection = await loadConversationProjection({ conversationId: args.conversationId });
|
|
3401
|
-
if (projection.messages.length > 0) return {
|
|
3402
|
-
|
|
3496
|
+
if (projection.messages.length > 0) return {
|
|
3497
|
+
piMessages: projection.messages,
|
|
3498
|
+
seqs: projection.seqs
|
|
3499
|
+
};
|
|
3500
|
+
return { seqs: [] };
|
|
3403
3501
|
}
|
|
3404
3502
|
/** Build the Slack caller that prepares input and delivers output for a Turn. */
|
|
3405
3503
|
function createSlackTurn(deps) {
|
|
@@ -3534,12 +3632,12 @@ function createSlackTurn(deps) {
|
|
|
3534
3632
|
const resolveSteeringMessages = async (queuedMessages) => {
|
|
3535
3633
|
return await mapBounded(queuedMessages, async (queued) => {
|
|
3536
3634
|
const attachments = queued.message.attachments;
|
|
3537
|
-
const
|
|
3635
|
+
const inboxItemInput = await loadInboxItemInput(getMessageInboxItemChange(queued.message));
|
|
3538
3636
|
return {
|
|
3539
3637
|
actor: inboundMessageActor(queued),
|
|
3540
|
-
...
|
|
3638
|
+
...inboxItemInput ? { kind: "runtime" } : void 0,
|
|
3541
3639
|
provenance: inboundMessageProvenance(queued, teamId),
|
|
3542
|
-
text:
|
|
3640
|
+
text: inboxItemInput?.text ?? queued.userText,
|
|
3543
3641
|
timestampMs: queued.message.metadata.dateSent.getTime(),
|
|
3544
3642
|
omittedImageAttachmentCount: !canReadImages() && hasPotentialImageAttachment(attachments) ? countPotentialImageAttachments(attachments) : 0,
|
|
3545
3643
|
attachments: await deps.resolveUserAttachments(attachments, {
|
|
@@ -3868,10 +3966,11 @@ function createSlackTurn(deps) {
|
|
|
3868
3966
|
boundaryFailureCode = "agent_run_failed";
|
|
3869
3967
|
};
|
|
3870
3968
|
try {
|
|
3871
|
-
|
|
3969
|
+
const loadedPiMessages = await loadPiMessagesForTurn({
|
|
3872
3970
|
conversationId,
|
|
3873
3971
|
activeTurnId
|
|
3874
|
-
})
|
|
3972
|
+
});
|
|
3973
|
+
let piMessages = loadedPiMessages.piMessages;
|
|
3875
3974
|
const hasHistory = Boolean(piMessages?.length);
|
|
3876
3975
|
const batchedSteeringMessages = (await resolveSteeringMessages((options.queuedMessages ?? []).filter((queued) => queued.explicitMention))).map((steering) => ({
|
|
3877
3976
|
message: buildSteeringPiMessage(steering),
|
|
@@ -3928,7 +4027,7 @@ function createSlackTurn(deps) {
|
|
|
3928
4027
|
const location = (await getConversationStore().get({ conversationId }))?.location;
|
|
3929
4028
|
const savedInput = await savedInputInstruction({
|
|
3930
4029
|
runtime: Boolean(options.execution?.dispatch),
|
|
3931
|
-
reviewItemChange:
|
|
4030
|
+
reviewItemChange: getMessageInboxItemChange(message),
|
|
3932
4031
|
text: effectiveUserText
|
|
3933
4032
|
});
|
|
3934
4033
|
const run = {
|
|
@@ -3947,7 +4046,10 @@ function createSlackTurn(deps) {
|
|
|
3947
4046
|
omittedImageAttachmentCount,
|
|
3948
4047
|
attachments: userAttachments
|
|
3949
4048
|
},
|
|
3950
|
-
history: piMessages
|
|
4049
|
+
history: piMessages ? {
|
|
4050
|
+
messages: piMessages,
|
|
4051
|
+
seqs: loadedPiMessages.seqs
|
|
4052
|
+
} : void 0,
|
|
3951
4053
|
credentialContext,
|
|
3952
4054
|
actor: executionActor,
|
|
3953
4055
|
slackConversation,
|
|
@@ -4071,7 +4173,7 @@ function createSlackTurn(deps) {
|
|
|
4071
4173
|
maxTurns: botConfig.maxConsecutiveAutomatedTurns,
|
|
4072
4174
|
source
|
|
4073
4175
|
});
|
|
4074
|
-
await
|
|
4176
|
+
await stopAtAutomatedTurnLimit({
|
|
4075
4177
|
conversationId,
|
|
4076
4178
|
maxTurns: botConfig.maxConsecutiveAutomatedTurns,
|
|
4077
4179
|
source,
|
|
@@ -4305,22 +4407,26 @@ const VISION_CACHE_TTL_MS = 6048e5;
|
|
|
4305
4407
|
function visionCacheKey(conversationId) {
|
|
4306
4408
|
return `vision-cache:v${VISION_CACHE_SCHEMA_VERSION}:${conversationId}`;
|
|
4307
4409
|
}
|
|
4410
|
+
const visionCacheSchema = z.object({
|
|
4411
|
+
schemaVersion: z.literal(VISION_CACHE_SCHEMA_VERSION),
|
|
4412
|
+
backfillCompletedAtMs: z.number().optional().catch(void 0),
|
|
4413
|
+
byFileId: z.record(z.string(), z.unknown()).catch({})
|
|
4414
|
+
});
|
|
4415
|
+
const visionSummarySchema = z.object({
|
|
4416
|
+
summary: z.string().refine((summary) => summary.trim() !== ""),
|
|
4417
|
+
analyzedAtMs: z.number()
|
|
4418
|
+
});
|
|
4308
4419
|
function coerceVisionCache(value) {
|
|
4309
|
-
|
|
4310
|
-
|
|
4420
|
+
const parsed = visionCacheSchema.safeParse(value);
|
|
4421
|
+
if (!parsed.success) return { byFileId: {} };
|
|
4311
4422
|
const byFileId = {};
|
|
4312
|
-
for (const [fileId, rawSummary] of Object.entries(
|
|
4313
|
-
if (!fileId.trim()
|
|
4314
|
-
const summary =
|
|
4315
|
-
|
|
4316
|
-
if (!summary || analyzedAtMs === void 0) continue;
|
|
4317
|
-
byFileId[fileId] = {
|
|
4318
|
-
summary,
|
|
4319
|
-
analyzedAtMs
|
|
4320
|
-
};
|
|
4423
|
+
for (const [fileId, rawSummary] of Object.entries(parsed.data.byFileId)) {
|
|
4424
|
+
if (!fileId.trim()) continue;
|
|
4425
|
+
const summary = visionSummarySchema.safeParse(rawSummary);
|
|
4426
|
+
if (summary.success) byFileId[fileId] = summary.data;
|
|
4321
4427
|
}
|
|
4322
4428
|
return {
|
|
4323
|
-
backfillCompletedAtMs:
|
|
4429
|
+
backfillCompletedAtMs: parsed.data.backfillCompletedAtMs,
|
|
4324
4430
|
byFileId
|
|
4325
4431
|
};
|
|
4326
4432
|
}
|
|
@@ -5273,7 +5379,7 @@ function restoreMessage(args) {
|
|
|
5273
5379
|
message.attachments = message.attachments.map((attachment) => args.adapter.rehydrateAttachment(attachment));
|
|
5274
5380
|
rehydrateAttachmentFetchers(message);
|
|
5275
5381
|
bindMessageAuthorIdentityId(message, args.record.input.authorIdentityId);
|
|
5276
|
-
|
|
5382
|
+
bindMessageInboxItemChange(message, args.record.input.reviewItemChange);
|
|
5277
5383
|
return message;
|
|
5278
5384
|
}
|
|
5279
5385
|
async function bindSlackActorIdentities(args) {
|
|
@@ -6243,6 +6349,12 @@ async function runPausedTurnInContext(payload, options, runOptions) {
|
|
|
6243
6349
|
turnId: turn.turnId,
|
|
6244
6350
|
errorMessage: "Authorization no longer belongs to this request"
|
|
6245
6351
|
});
|
|
6352
|
+
await getTurnLifecycle().complete({
|
|
6353
|
+
conversationId: payload.conversationId,
|
|
6354
|
+
createdAtMs: Date.now(),
|
|
6355
|
+
outcome: "cancelled",
|
|
6356
|
+
turnId: turn.turnId
|
|
6357
|
+
});
|
|
6246
6358
|
clearPendingAuth(conversation, turn.turnId);
|
|
6247
6359
|
await persistThreadStateById(payload.conversationId, { conversation });
|
|
6248
6360
|
return false;
|
|
@@ -6282,7 +6394,7 @@ async function runPausedTurnInContext(payload, options, runOptions) {
|
|
|
6282
6394
|
});
|
|
6283
6395
|
const source = routing.source;
|
|
6284
6396
|
const routingDestination = routing.destination;
|
|
6285
|
-
const turnMessages = activeTurn
|
|
6397
|
+
const turnMessages = savedTurnMessages(activeTurn, await loadTurnStart(payload.conversationId, payload.turnId)).map(({ message }) => message);
|
|
6286
6398
|
const recordDispatchOutcome = async (dispatchOutcome) => {
|
|
6287
6399
|
if (!dispatch) return;
|
|
6288
6400
|
await recordTurnSummary({
|
|
@@ -6311,11 +6423,15 @@ async function runPausedTurnInContext(payload, options, runOptions) {
|
|
|
6311
6423
|
...getTurnUserReplyAttachmentContext(userMessage),
|
|
6312
6424
|
...await savedInputInstruction({
|
|
6313
6425
|
runtime: Boolean(dispatchId) || isEventConversationMessage(userMessage),
|
|
6426
|
+
requestText: userMessage.meta?.requestText,
|
|
6314
6427
|
reviewItemChange: userMessage.meta?.reviewItemChanges?.[0],
|
|
6315
6428
|
text: userMessage.text
|
|
6316
6429
|
})
|
|
6317
6430
|
},
|
|
6318
|
-
history: dispatchId ?
|
|
6431
|
+
history: dispatchId ? {
|
|
6432
|
+
messages: activeTurn.piMessages,
|
|
6433
|
+
seqs: activeTurn.piMessageSeqs
|
|
6434
|
+
} : await loadConversationProjection({ conversationId: payload.conversationId }),
|
|
6319
6435
|
actor,
|
|
6320
6436
|
credentialContext,
|
|
6321
6437
|
destination: routingDestination,
|
|
@@ -6688,12 +6804,8 @@ function createConversationWork(options) {
|
|
|
6688
6804
|
if (dispatchId) return await dispatchWorker(context, dispatchId);
|
|
6689
6805
|
return await destinationWorker(context);
|
|
6690
6806
|
};
|
|
6691
|
-
const
|
|
6692
|
-
|
|
6693
|
-
if ("skipped" in stopped) return stopped.skipped;
|
|
6694
|
-
const { context } = stopped;
|
|
6695
|
-
const conversation = await options.conversationStore.get({ conversationId: context.conversationId });
|
|
6696
|
-
if (!isTopLevelKind(conversation?.kind ?? "root")) return await childWorker(context);
|
|
6807
|
+
const runByKind = async (context, topLevel) => {
|
|
6808
|
+
if (!topLevel) return await childWorker(context);
|
|
6697
6809
|
const readStopSignal = context.stopSignal;
|
|
6698
6810
|
let stopSignal;
|
|
6699
6811
|
const stopLateChildAgents = async () => {
|
|
@@ -6714,6 +6826,12 @@ function createConversationWork(options) {
|
|
|
6714
6826
|
await stopLateChildAgents();
|
|
6715
6827
|
return result;
|
|
6716
6828
|
};
|
|
6829
|
+
const run = async (context) => {
|
|
6830
|
+
await resumeForPersonInput(context.conversationId, context.attempt.messages);
|
|
6831
|
+
const conversation = await options.conversationStore.get({ conversationId: context.conversationId });
|
|
6832
|
+
const topLevel = isTopLevelKind(conversation?.kind ?? "root");
|
|
6833
|
+
return await withLogContext({ rootConversationId: conversation?.rootConversationId ?? (topLevel ? context.conversationId : void 0) }, () => runByKind(context, topLevel));
|
|
6834
|
+
};
|
|
6717
6835
|
return {
|
|
6718
6836
|
beforeWorkStops: failStoppedDispatch,
|
|
6719
6837
|
conversationStore: options.conversationStore,
|
|
@@ -7638,6 +7756,16 @@ async function resolveObjectLinkNow(viewer, url) {
|
|
|
7638
7756
|
return await resolveWithLinkType(linkType, viewer, url) ?? void 0;
|
|
7639
7757
|
}
|
|
7640
7758
|
/**
|
|
7759
|
+
* Return whether a link type of `plugin` claims the URL, lets the viewer
|
|
7760
|
+
* see it now, and reads an object there. A missing or deleted object does
|
|
7761
|
+
* not count. Neither does the web page card: it shows what anyone can read
|
|
7762
|
+
* signed out, not what the viewer can see.
|
|
7763
|
+
*/
|
|
7764
|
+
async function viewerCanViewPluginLink(viewer, url, plugin) {
|
|
7765
|
+
const linkType = findObjectLinkType(readObjectLinkTypes(), url);
|
|
7766
|
+
return linkType?.owner === plugin && await linkType.canView(viewer, url) && Boolean(await linkType.resolve(viewer, url));
|
|
7767
|
+
}
|
|
7768
|
+
/**
|
|
7641
7769
|
* Resolve links to object cards for one viewer. A link without a link type,
|
|
7642
7770
|
* without access, or with a failed read gets no card. Nothing is saved on a
|
|
7643
7771
|
* Conversation.
|
|
@@ -8282,57 +8410,381 @@ async function runSavingsRefillSlice(args) {
|
|
|
8282
8410
|
await state.delete(SLICE_LOCK_KEY);
|
|
8283
8411
|
}
|
|
8284
8412
|
}
|
|
8285
|
-
// src/chat/
|
|
8413
|
+
// src/chat/inbox-snoozes/triggers.ts
|
|
8286
8414
|
/**
|
|
8287
|
-
*
|
|
8288
|
-
*
|
|
8289
|
-
* resume after it.
|
|
8415
|
+
* Pending snooze timers. A snooze wakes in one cheap update, so one claim
|
|
8416
|
+
* takes many.
|
|
8290
8417
|
*/
|
|
8291
|
-
const
|
|
8418
|
+
const INBOX_SNOOZE_TIMER_INDEX = {
|
|
8419
|
+
batchSize: 500,
|
|
8420
|
+
key: "junior:inbox-snoozes:due"
|
|
8421
|
+
};
|
|
8422
|
+
/**
|
|
8423
|
+
* Fire the snooze triggers that one Event matches. A `resolve` trigger
|
|
8424
|
+
* dismisses the item and cancels its snooze; a `wake` trigger ends the
|
|
8425
|
+
* snooze, which records `reason`. When one Event fires both on a snooze,
|
|
8426
|
+
* `resolve` wins. A snooze that already ended ignores the Event. Returns
|
|
8427
|
+
* the number of items woken.
|
|
8428
|
+
*/
|
|
8429
|
+
async function fireTriggers(db, event, reason, nowMs) {
|
|
8430
|
+
const triggers = (await listFiringInboxSnoozeTriggers(db, {
|
|
8431
|
+
eventTypes: [event.eventType],
|
|
8432
|
+
identifiers: event.identifiers,
|
|
8433
|
+
namespace: event.namespace
|
|
8434
|
+
})).filter((trigger) => eventMatches(trigger.match ?? void 0, event.data));
|
|
8435
|
+
const resolving = new Set(triggers.filter((trigger) => trigger.outcome === "resolve").map((trigger) => trigger.snoozeId));
|
|
8436
|
+
const waking = new Set(triggers.filter((trigger) => !resolving.has(trigger.snoozeId)).map((trigger) => trigger.snoozeId));
|
|
8437
|
+
if (resolving.size === 0 && waking.size === 0) return 0;
|
|
8438
|
+
return db.transaction(async (tx) => {
|
|
8439
|
+
const resolvedItemIds = await settleInboxSnoozes(tx, {
|
|
8440
|
+
snoozeIds: [...resolving],
|
|
8441
|
+
state: "cancelled"
|
|
8442
|
+
});
|
|
8443
|
+
await dismissOpenInboxItems(tx, {
|
|
8444
|
+
ids: resolvedItemIds,
|
|
8445
|
+
nowMs,
|
|
8446
|
+
reason: "A snooze trigger resolved it."
|
|
8447
|
+
});
|
|
8448
|
+
return (await settleInboxSnoozes(tx, {
|
|
8449
|
+
reason,
|
|
8450
|
+
snoozeIds: [...waking],
|
|
8451
|
+
state: "woken"
|
|
8452
|
+
})).length;
|
|
8453
|
+
});
|
|
8454
|
+
}
|
|
8455
|
+
/** Fire the snooze triggers that one published Event matches. */
|
|
8456
|
+
async function fireInboxSnoozeTriggers(db, event, nowMs = Date.now()) {
|
|
8457
|
+
await fireTriggers(db, {
|
|
8458
|
+
data: event.data,
|
|
8459
|
+
eventType: event.eventType,
|
|
8460
|
+
identifiers: [event.identifier],
|
|
8461
|
+
namespace: event.namespace
|
|
8462
|
+
}, {
|
|
8463
|
+
eventType: event.eventType,
|
|
8464
|
+
identifier: event.identifier,
|
|
8465
|
+
kind: "event",
|
|
8466
|
+
namespace: event.namespace
|
|
8467
|
+
}, nowMs);
|
|
8468
|
+
}
|
|
8469
|
+
/**
|
|
8470
|
+
* Return whether any of these Events fires a snooze trigger. A plugin
|
|
8471
|
+
* batch has one namespace, so this is one read.
|
|
8472
|
+
*/
|
|
8473
|
+
async function hasInboxSnoozeMatch(db, events) {
|
|
8474
|
+
const namespaces = [...new Set(events.map((event) => event.namespace))];
|
|
8475
|
+
return (await mapBounded(namespaces, async (namespace) => {
|
|
8476
|
+
const group = events.filter((event) => event.namespace === namespace);
|
|
8477
|
+
const triggers = await listFiringInboxSnoozeTriggers(db, {
|
|
8478
|
+
eventTypes: [...new Set(group.map((event) => event.eventType))],
|
|
8479
|
+
identifiers: [...new Set(group.map((event) => event.identifier))],
|
|
8480
|
+
namespace
|
|
8481
|
+
});
|
|
8482
|
+
return group.some((event) => triggers.some((trigger) => trigger.eventType === event.eventType && trigger.identifier === event.identifier && eventMatches(trigger.match ?? void 0, event.data)));
|
|
8483
|
+
})).some(Boolean);
|
|
8484
|
+
}
|
|
8485
|
+
/** Return the Event data keys that snooze triggers on these resources match. */
|
|
8486
|
+
async function collectInboxSnoozeMatchKeys(db, input) {
|
|
8487
|
+
const triggers = await listFiringInboxSnoozeTriggers(db, input);
|
|
8488
|
+
return [...new Set(triggers.flatMap((trigger) => Object.keys(trigger.match ?? {})))];
|
|
8489
|
+
}
|
|
8292
8490
|
/**
|
|
8293
|
-
*
|
|
8294
|
-
*
|
|
8295
|
-
*
|
|
8296
|
-
*
|
|
8297
|
-
* it and its parent gets the result instead.
|
|
8491
|
+
* Schedule the timer of a snooze. Its `timer.fired` Event wakes the
|
|
8492
|
+
* snoozes whose triggers name `timerId`. A claimed timer is removed even
|
|
8493
|
+
* when no snooze names it yet, so a caller that schedules before the
|
|
8494
|
+
* snoozes commit wakes them itself if the fire time passed meanwhile.
|
|
8298
8495
|
*/
|
|
8299
|
-
|
|
8300
|
-
|
|
8301
|
-
|
|
8302
|
-
|
|
8303
|
-
|
|
8304
|
-
|
|
8305
|
-
|
|
8496
|
+
async function scheduleInboxSnoozeTimer(timerId, firesAtMs) {
|
|
8497
|
+
const state = getStateAdapter();
|
|
8498
|
+
await state.connect();
|
|
8499
|
+
await updateTimerIndex(state, INBOX_SNOOZE_TIMER_INDEX, {
|
|
8500
|
+
atMs: firesAtMs,
|
|
8501
|
+
id: timerId,
|
|
8502
|
+
kind: "add"
|
|
8503
|
+
});
|
|
8504
|
+
}
|
|
8306
8505
|
/**
|
|
8307
|
-
*
|
|
8308
|
-
*
|
|
8309
|
-
*
|
|
8310
|
-
* events and has not expired.
|
|
8506
|
+
* Fire the snooze timers that are due, as `timer.fired` Events. A failed
|
|
8507
|
+
* pass leaves its claims to expire, so the next heartbeat retries them.
|
|
8508
|
+
* Returns the number of items woken.
|
|
8311
8509
|
*/
|
|
8312
|
-
function
|
|
8313
|
-
const
|
|
8314
|
-
|
|
8315
|
-
|
|
8316
|
-
|
|
8317
|
-
|
|
8318
|
-
|
|
8319
|
-
|
|
8320
|
-
|
|
8321
|
-
|
|
8322
|
-
|
|
8323
|
-
|
|
8324
|
-
|
|
8325
|
-
|
|
8326
|
-
|
|
8327
|
-
|
|
8328
|
-
|
|
8329
|
-
|
|
8330
|
-
|
|
8331
|
-
|
|
8332
|
-
|
|
8333
|
-
|
|
8334
|
-
|
|
8335
|
-
|
|
8510
|
+
async function runInboxSnoozeTimers(db, nowMs) {
|
|
8511
|
+
const state = getStateAdapter();
|
|
8512
|
+
await state.connect();
|
|
8513
|
+
const timerIds = await updateTimerIndex(state, INBOX_SNOOZE_TIMER_INDEX, {
|
|
8514
|
+
kind: "claim",
|
|
8515
|
+
nowMs
|
|
8516
|
+
});
|
|
8517
|
+
if (timerIds.length === 0) return 0;
|
|
8518
|
+
const woken = await fireTriggers(db, {
|
|
8519
|
+
eventType: SNOOZE_TIMER_EVENT_TYPE,
|
|
8520
|
+
identifiers: timerIds,
|
|
8521
|
+
namespace: CORE_EVENT_NAMESPACE
|
|
8522
|
+
}, { kind: "time" }, nowMs);
|
|
8523
|
+
await mapBounded(timerIds, (id) => updateTimerIndex(state, INBOX_SNOOZE_TIMER_INDEX, {
|
|
8524
|
+
id,
|
|
8525
|
+
kind: "remove"
|
|
8526
|
+
}));
|
|
8527
|
+
return woken;
|
|
8528
|
+
}
|
|
8529
|
+
// src/chat/agent-dispatch/validation.ts
|
|
8530
|
+
function hasIssueAtPath(issues, path) {
|
|
8531
|
+
return issues.some((issue) => issue.path.length === path.length && issue.path.every((value, index) => value === path[index]));
|
|
8532
|
+
}
|
|
8533
|
+
function hasIssueUnderPath(issues, path) {
|
|
8534
|
+
return issues.some((issue) => path.every((value, index) => issue.path[index] === value));
|
|
8535
|
+
}
|
|
8536
|
+
function dispatchOptionsErrorMessage(issues) {
|
|
8537
|
+
if (hasIssueAtPath(issues, [])) return issues.some((issue) => issue.code === "unrecognized_keys") ? "Dispatch options must not include unknown fields" : "Dispatch options are required";
|
|
8538
|
+
if (issues.some((issue) => issue.code === "unrecognized_keys" && issue.path[0] === "destination")) return "Dispatch destination must not include unknown fields";
|
|
8539
|
+
if (issues.some((issue) => issue.code === "unrecognized_keys" && issue.path[0] === "credentialSubject")) return "Dispatch credentialSubject binding is runtime-owned";
|
|
8540
|
+
if (hasIssueAtPath(issues, ["destination"])) return "Dispatch destination platform must be slack";
|
|
8541
|
+
if (hasIssueUnderPath(issues, ["destination", "teamId"])) return "Dispatch destination teamId must be a Slack team id";
|
|
8542
|
+
if (hasIssueUnderPath(issues, ["destination", "channelId"])) return "Dispatch destination channelId must be a Slack channel id";
|
|
8543
|
+
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";
|
|
8544
|
+
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";
|
|
8545
|
+
if (hasIssueUnderPath(issues, ["credentialSubject", "userId"])) return "Dispatch credentialSubject userId is required";
|
|
8546
|
+
if (hasIssueUnderPath(issues, ["credentialSubject", "allowedWhen"])) return "Dispatch credentialSubject allowedWhen is invalid";
|
|
8547
|
+
if (hasIssueUnderPath(issues, ["credentialSubject"])) return "Dispatch credentialSubject type must be user";
|
|
8548
|
+
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"));
|
|
8549
|
+
if (metadataIssue) return metadataIssue.message;
|
|
8550
|
+
if (hasIssueUnderPath(issues, ["metadata"])) return "Dispatch metadata values must be strings";
|
|
8551
|
+
if (hasIssueUnderPath(issues, ["replyAttribution"])) return "Dispatch reply attribution is invalid";
|
|
8552
|
+
return "Dispatch options are invalid";
|
|
8553
|
+
}
|
|
8554
|
+
/** Validate plugin-provided dispatch options before core persists them. */
|
|
8555
|
+
function validateDispatchOptions(options) {
|
|
8556
|
+
const parsed = dispatchOptionsSchema.safeParse(options);
|
|
8557
|
+
if (!parsed.success) throw new Error(dispatchOptionsErrorMessage(parsed.error.issues));
|
|
8558
|
+
const { credentialSubject, destination } = parsed.data;
|
|
8559
|
+
if (!isSlackDestination(destination)) throw new Error("Dispatch destination platform must be slack");
|
|
8560
|
+
if (credentialSubject !== void 0) {
|
|
8561
|
+
if (credentialSubject.allowedWhen === "private-direct-conversation" && !isDmChannel(destination.channelId)) throw new Error("Dispatch credentialSubject requires a private direct Slack destination");
|
|
8562
|
+
}
|
|
8563
|
+
}
|
|
8564
|
+
/** Verify runtime-owned access requirements for delegated dispatch credentials. */
|
|
8565
|
+
async function verifyDispatchCredentialSubjectAccess(options, plugin) {
|
|
8566
|
+
if (!options.credentialSubject) return;
|
|
8567
|
+
if (!(options.credentialSubject.allowedWhen === "scheduled-automation" ? verifyScheduledAutomationCredentialSubject({
|
|
8568
|
+
plugin,
|
|
8569
|
+
subject: options.credentialSubject
|
|
8570
|
+
}) : options.credentialSubject.allowedWhen === "event-automation" ? verifyEventAutomationCredentialSubject({
|
|
8571
|
+
plugin,
|
|
8572
|
+
subject: options.credentialSubject
|
|
8573
|
+
}) : verifySlackDirectCredentialSubject({
|
|
8574
|
+
channelId: options.destination.channelId,
|
|
8575
|
+
teamId: options.destination.teamId,
|
|
8576
|
+
subject: options.credentialSubject
|
|
8577
|
+
}))) throw new Error("Dispatch credentialSubject is not valid for this action");
|
|
8578
|
+
}
|
|
8579
|
+
// src/chat/agent-dispatch/context.ts
|
|
8580
|
+
const MAX_DISPATCHES_PER_HEARTBEAT = 25;
|
|
8581
|
+
function bindDispatchCredentialSubject(options, plugin) {
|
|
8582
|
+
const { credentialSubject, ...baseOptions } = options;
|
|
8583
|
+
if (!credentialSubject) return {
|
|
8584
|
+
...baseOptions,
|
|
8585
|
+
source: { kind: "plugin_dispatch" }
|
|
8586
|
+
};
|
|
8587
|
+
if ("binding" in credentialSubject) throw new Error("Dispatch credentialSubject binding is runtime-owned");
|
|
8588
|
+
const boundSubject = credentialSubject.allowedWhen === "scheduled-automation" ? bindScheduledAutomationCredentialSubject({
|
|
8589
|
+
plugin,
|
|
8590
|
+
subject: credentialSubject
|
|
8591
|
+
}) : bindSlackDirectCredentialSubject({
|
|
8592
|
+
channelId: options.destination.channelId,
|
|
8593
|
+
teamId: options.destination.teamId,
|
|
8594
|
+
subject: credentialSubject
|
|
8595
|
+
});
|
|
8596
|
+
if (!boundSubject) throw new Error("Dispatch credentialSubject is not valid for this action");
|
|
8597
|
+
return {
|
|
8598
|
+
...baseOptions,
|
|
8599
|
+
credentialSubject: boundSubject,
|
|
8600
|
+
source: { kind: "plugin_dispatch" }
|
|
8601
|
+
};
|
|
8602
|
+
}
|
|
8603
|
+
/** Verify, persist, and enqueue one idempotent agent dispatch. */
|
|
8604
|
+
async function dispatch(args) {
|
|
8605
|
+
await verifyDispatchCredentialSubjectAccess(args.options, args.plugin);
|
|
8606
|
+
const result = await createOrGetDispatch({
|
|
8607
|
+
plugin: args.plugin,
|
|
8608
|
+
options: args.options,
|
|
8609
|
+
nowMs: args.nowMs
|
|
8610
|
+
});
|
|
8611
|
+
if (!isTerminalDispatchStatus(result.record.status)) await enqueueAgentDispatch(result.record, {
|
|
8612
|
+
queue: args.conversationWorkQueue,
|
|
8613
|
+
nowMs: args.nowMs
|
|
8614
|
+
});
|
|
8615
|
+
return {
|
|
8616
|
+
id: result.record.id,
|
|
8617
|
+
status: result.status
|
|
8618
|
+
};
|
|
8619
|
+
}
|
|
8620
|
+
/** Build the plugin-scoped heartbeat context that gates durable dispatch access. */
|
|
8621
|
+
function createHeartbeatContext(args) {
|
|
8622
|
+
const pluginName = typeof args.plugin === "string" ? args.plugin : args.plugin.manifest.name;
|
|
8623
|
+
let dispatchCount = 0;
|
|
8624
|
+
const assertDispatchBudget = () => {
|
|
8625
|
+
if (dispatchCount >= MAX_DISPATCHES_PER_HEARTBEAT) throw new Error("Plugin heartbeat exceeded the dispatch limit");
|
|
8626
|
+
};
|
|
8627
|
+
return {
|
|
8628
|
+
plugin: { name: pluginName },
|
|
8629
|
+
annotations: { forConversation: (conversationId) => createPluginAnnotations({
|
|
8630
|
+
conversationId,
|
|
8631
|
+
db: getDb(),
|
|
8632
|
+
plugin: pluginName
|
|
8633
|
+
}) },
|
|
8634
|
+
cache: createPluginCache(pluginName),
|
|
8635
|
+
codeChanges: createCodeChangePublisher(pluginName),
|
|
8636
|
+
nowMs: args.nowMs,
|
|
8637
|
+
db: getDb(),
|
|
8638
|
+
embedder: createPluginEmbedder(pluginName),
|
|
8639
|
+
events: args.events,
|
|
8640
|
+
inboxItems: { forConversation: (conversationId) => createPluginInboxItems({
|
|
8641
|
+
conversationId,
|
|
8642
|
+
plugin: pluginName,
|
|
8643
|
+
show: args.showInboxItem ?? (async () => {})
|
|
8644
|
+
}) },
|
|
8645
|
+
state: createPluginState(pluginName),
|
|
8646
|
+
log: createPluginLogger(pluginName),
|
|
8647
|
+
agent: {
|
|
8648
|
+
async dispatch(options) {
|
|
8649
|
+
validateDispatchOptions(options);
|
|
8650
|
+
const dispatchOptions = bindDispatchCredentialSubject(options, pluginName);
|
|
8651
|
+
assertDispatchBudget();
|
|
8652
|
+
const result = await dispatch({
|
|
8653
|
+
conversationWorkQueue: args.conversationWorkQueue,
|
|
8654
|
+
nowMs: args.nowMs,
|
|
8655
|
+
options: dispatchOptions,
|
|
8656
|
+
plugin: pluginName
|
|
8657
|
+
});
|
|
8658
|
+
dispatchCount += 1;
|
|
8659
|
+
return result;
|
|
8660
|
+
},
|
|
8661
|
+
async dispatchForIdentity(options) {
|
|
8662
|
+
assertDispatchBudget();
|
|
8663
|
+
dispatchCount += 1;
|
|
8664
|
+
return await args.dispatchForIdentity(pluginName, options);
|
|
8665
|
+
},
|
|
8666
|
+
async get(id) {
|
|
8667
|
+
return await getPluginDispatchProjection({
|
|
8668
|
+
plugin: pluginName,
|
|
8669
|
+
id
|
|
8670
|
+
});
|
|
8671
|
+
}
|
|
8672
|
+
}
|
|
8673
|
+
};
|
|
8674
|
+
}
|
|
8675
|
+
/** Create and enqueue one core-owned event automation dispatch. */
|
|
8676
|
+
async function dispatchEventAutomation(args) {
|
|
8677
|
+
const plugin = "junior";
|
|
8678
|
+
const { credentialSubject, outcomes, skill, ...unboundOptions } = args.options;
|
|
8679
|
+
validateDispatchOptions({ ...unboundOptions });
|
|
8680
|
+
const boundSubject = credentialSubject ? bindEventAutomationCredentialSubject({
|
|
8681
|
+
plugin,
|
|
8682
|
+
subject: credentialSubject
|
|
8683
|
+
}) : void 0;
|
|
8684
|
+
if (credentialSubject && !boundSubject) throw new Error("Dispatch credentialSubject is not valid for this action");
|
|
8685
|
+
const options = {
|
|
8686
|
+
...unboundOptions,
|
|
8687
|
+
...outcomes !== void 0 ? { outcomes } : void 0,
|
|
8688
|
+
...skill ? { skill } : void 0,
|
|
8689
|
+
...boundSubject ? { credentialSubject: boundSubject } : void 0,
|
|
8690
|
+
source: {
|
|
8691
|
+
kind: "event_automation",
|
|
8692
|
+
automationId: args.automationId,
|
|
8693
|
+
automationRunId: buildDispatchId(plugin, unboundOptions.idempotencyKey)
|
|
8694
|
+
}
|
|
8695
|
+
};
|
|
8696
|
+
return await dispatch({
|
|
8697
|
+
conversationWorkQueue: args.conversationWorkQueue,
|
|
8698
|
+
nowMs: args.nowMs,
|
|
8699
|
+
options,
|
|
8700
|
+
plugin
|
|
8701
|
+
});
|
|
8702
|
+
}
|
|
8703
|
+
/** Create and enqueue one core-owned scheduled automation dispatch. */
|
|
8704
|
+
async function dispatchScheduledAutomation(args) {
|
|
8705
|
+
const plugin = "scheduler";
|
|
8706
|
+
const { credentialSubject, outcomes, skill, ...unboundOptions } = args.options;
|
|
8707
|
+
validateDispatchOptions({ ...unboundOptions });
|
|
8708
|
+
const boundSubject = credentialSubject ? bindScheduledAutomationCredentialSubject({
|
|
8709
|
+
plugin,
|
|
8710
|
+
subject: credentialSubject
|
|
8711
|
+
}) : void 0;
|
|
8712
|
+
if (credentialSubject && !boundSubject) throw new Error("Dispatch credentialSubject is not valid for this action");
|
|
8713
|
+
const options = {
|
|
8714
|
+
...unboundOptions,
|
|
8715
|
+
...outcomes !== void 0 ? { outcomes } : void 0,
|
|
8716
|
+
...skill ? { skill } : void 0,
|
|
8717
|
+
...boundSubject ? { credentialSubject: boundSubject } : void 0,
|
|
8718
|
+
source: {
|
|
8719
|
+
kind: "scheduled_automation",
|
|
8720
|
+
automationId: args.automationId,
|
|
8721
|
+
automationRunId: unboundOptions.idempotencyKey
|
|
8722
|
+
}
|
|
8723
|
+
};
|
|
8724
|
+
return await dispatch({
|
|
8725
|
+
conversationWorkQueue: args.conversationWorkQueue,
|
|
8726
|
+
nowMs: args.nowMs,
|
|
8727
|
+
options,
|
|
8728
|
+
plugin
|
|
8729
|
+
});
|
|
8730
|
+
}
|
|
8731
|
+
/** Read the bounded outcome for one core-owned scheduled automation dispatch. */
|
|
8732
|
+
async function getScheduledAutomationDispatch(id) {
|
|
8733
|
+
return await getPluginDispatchProjection({
|
|
8734
|
+
plugin: "scheduler",
|
|
8735
|
+
id
|
|
8736
|
+
});
|
|
8737
|
+
}
|
|
8738
|
+
// src/chat/event-automations/runs.ts
|
|
8739
|
+
/**
|
|
8740
|
+
* Record a dispatched event automation run with the Automation version it ran,
|
|
8741
|
+
* and link its Conversation when it exists. The dispatch can finish before
|
|
8742
|
+
* this write, so a stored run, or a retry of the same Event, keeps the row it
|
|
8743
|
+
* has.
|
|
8744
|
+
*/
|
|
8745
|
+
async function recordEventAutomationRunStarted(db, args) {
|
|
8746
|
+
const conversationId = getDispatchConversationId({ id: args.dispatchId });
|
|
8747
|
+
await db.insert(juniorAutomationRuns).values({
|
|
8748
|
+
id: args.dispatchId,
|
|
8749
|
+
automationId: args.automation.id,
|
|
8750
|
+
automationVersion: automationVersionOf(args.automation),
|
|
8751
|
+
conversationId: existingConversationId(conversationId),
|
|
8752
|
+
costMicroUsd: conversationCostOf(conversationId),
|
|
8753
|
+
startedAtMs: args.nowMs,
|
|
8754
|
+
status: "running"
|
|
8755
|
+
}).onConflictDoNothing({ target: juniorAutomationRuns.id });
|
|
8756
|
+
}
|
|
8757
|
+
/**
|
|
8758
|
+
* Settle running event automation runs whose dispatch has ended. A run whose
|
|
8759
|
+
* dispatch record is gone fails.
|
|
8760
|
+
*/
|
|
8761
|
+
async function settleEventAutomationRuns(db, nowMs) {
|
|
8762
|
+
const runs = await db.select({
|
|
8763
|
+
automationId: juniorAutomationRuns.automationId,
|
|
8764
|
+
id: juniorAutomationRuns.id
|
|
8765
|
+
}).from(juniorAutomationRuns).innerJoin(juniorAutomations, eq(juniorAutomations.id, juniorAutomationRuns.automationId)).where(and(eq(juniorAutomations.kind, "event"), eq(juniorAutomationRuns.status, "running")));
|
|
8766
|
+
const dispatches = await mapBounded(runs, (run) => getDispatchRecord(run.id));
|
|
8767
|
+
for (const [index, run] of runs.entries()) {
|
|
8768
|
+
const dispatch = dispatches[index];
|
|
8769
|
+
const status = dispatch?.status ?? "failed";
|
|
8770
|
+
if (status !== "blocked" && status !== "completed" && status !== "failed") continue;
|
|
8771
|
+
await recordAutomationExecution(run.automationId, {
|
|
8772
|
+
conversationId: getDispatchConversationId({ id: run.id }),
|
|
8773
|
+
errorMessage: dispatch ? dispatch.errorMessage : "Event automation dispatch record is missing.",
|
|
8774
|
+
executionId: run.id,
|
|
8775
|
+
nowMs: dispatch?.updatedAtMs ?? nowMs,
|
|
8776
|
+
status
|
|
8777
|
+
});
|
|
8778
|
+
}
|
|
8779
|
+
}
|
|
8780
|
+
// src/chat/automations/reply-attribution.ts
|
|
8781
|
+
/** Name the Automation in the footer of the replies that its runs post. */
|
|
8782
|
+
function automationReplyAttribution(title) {
|
|
8783
|
+
const detail = (title ?? "").replace(/\s+/g, " ").trim().slice(0, 128).trim();
|
|
8784
|
+
return detail ? {
|
|
8785
|
+
label: "Automation",
|
|
8786
|
+
detail
|
|
8787
|
+
} : { label: "Automation" };
|
|
8336
8788
|
}
|
|
8337
8789
|
// src/api/user-settings.ts
|
|
8338
8790
|
const userPreferencesSchema = z.object({
|
|
@@ -8384,23 +8836,36 @@ function runCutoff(run) {
|
|
|
8384
8836
|
return /* @__PURE__ */ new Date(run.now.getTime() - run.graceHours * HOUR_MS);
|
|
8385
8837
|
}
|
|
8386
8838
|
/**
|
|
8387
|
-
* True when the participant row's root and every child conversation are idle
|
|
8388
|
-
*
|
|
8389
|
-
*
|
|
8390
|
-
* `lastActivityAt`, so the whole tree is checked.
|
|
8839
|
+
* True when the participant row's root and every child conversation are idle
|
|
8840
|
+
* and had no activity after the cutoff. Child activity does not move the
|
|
8841
|
+
* root's `lastActivityAt`, so the whole tree is checked.
|
|
8391
8842
|
*/
|
|
8392
8843
|
function treeIsQuiet(run) {
|
|
8393
|
-
const active = getDb().select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(or(eq(juniorConversations.conversationId, juniorConversationParticipants.rootConversationId), eq(juniorConversations.rootConversationId, juniorConversationParticipants.rootConversationId)), or(ne(juniorConversations.executionStatus, "idle"), gt(juniorConversations.lastActivityAt, runCutoff(run))
|
|
8844
|
+
const active = getDb().select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(or(eq(juniorConversations.conversationId, juniorConversationParticipants.rootConversationId), eq(juniorConversations.rootConversationId, juniorConversationParticipants.rootConversationId)), or(ne(juniorConversations.executionStatus, "idle"), gt(juniorConversations.lastActivityAt, runCutoff(run)))));
|
|
8394
8845
|
return sql`not exists (${active})`;
|
|
8395
8846
|
}
|
|
8396
8847
|
/**
|
|
8397
|
-
* True when
|
|
8848
|
+
* True when nothing in the participant row's tree needs a person. No
|
|
8849
|
+
* conversation in it has `needs_input` status: an open action Inbox item
|
|
8850
|
+
* that it added, a sign-in wait, or work that waits on its starter, such
|
|
8851
|
+
* as an answer that the starter has not read. No open To-do in it is
|
|
8852
|
+
* assigned to a person. Archive applies to everyone, so input that waits
|
|
8853
|
+
* on anyone keeps the tree. An archived child counts for nothing, as in
|
|
8854
|
+
* the tree state.
|
|
8855
|
+
*/
|
|
8856
|
+
function treeNeedsNoOne() {
|
|
8857
|
+
const assignedToPerson = getDb().select({ id: juniorTodos.id }).from(juniorTodos).where(and(eq(juniorTodos.conversationId, juniorConversations.conversationId), isNotNull(juniorTodos.assigneeUserId), inArray(juniorTodos.status, OPEN_TODO_STATUSES)));
|
|
8858
|
+
const needing = getDb().select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(or(eq(juniorConversations.conversationId, juniorConversationParticipants.rootConversationId), and(eq(juniorConversations.rootConversationId, juniorConversationParticipants.rootConversationId), isNull(juniorConversations.archivedAt))), or(sql`${conversationStatusSql(juniorConversations)} = 'needs_input'`, sql`exists (${assignedToPerson})`)));
|
|
8859
|
+
return sql`not exists (${needing})`;
|
|
8860
|
+
}
|
|
8861
|
+
/**
|
|
8862
|
+
* True when no open Inbox item on the participant row's root or a child
|
|
8398
8863
|
* conversation needs a person. Archive applies to everyone, so a
|
|
8399
8864
|
* conversation that waits on anyone must stay in the feed.
|
|
8400
8865
|
*/
|
|
8401
8866
|
function notWaitingOnAnyone() {
|
|
8402
8867
|
const linked = alias(juniorConversations, "linked_conversation");
|
|
8403
|
-
const waiting = getDb().select({ itemId:
|
|
8868
|
+
const waiting = getDb().select({ itemId: juniorInboxItemConversations.itemId }).from(juniorInboxItemConversations).innerJoin(juniorInboxItems, eq(juniorInboxItems.id, juniorInboxItemConversations.itemId)).innerJoin(linked, eq(linked.conversationId, juniorInboxItemConversations.conversationId)).where(and(inboxItemNeedsSomeone(), or(eq(linked.conversationId, juniorConversationParticipants.rootConversationId), eq(linked.rootConversationId, juniorConversationParticipants.rootConversationId))));
|
|
8404
8869
|
return sql`not exists (${waiting})`;
|
|
8405
8870
|
}
|
|
8406
8871
|
/**
|
|
@@ -8422,11 +8887,11 @@ function rootIsUnarchived() {
|
|
|
8422
8887
|
}
|
|
8423
8888
|
/**
|
|
8424
8889
|
* Conditions that a participant row must meet when it is selected and again
|
|
8425
|
-
* when it is archived, so new activity, a new run, a new
|
|
8890
|
+
* when it is archived, so new activity, a new run, a new Inbox item, or a
|
|
8426
8891
|
* changed setting wins over a stale read.
|
|
8427
8892
|
*/
|
|
8428
8893
|
function archivableRow(run) {
|
|
8429
|
-
return and(eq(juniorConversationParticipants.userId, run.userId), isNull(juniorConversationParticipants.unsubscribedAt), rootIsUnarchived(), noParticipantKeepsRoot(), lte(juniorConversationParticipants.lastMessageAt, runCutoff(run)), runOptsIn(run), run.kind === "scheduled" ? sql`${juniorUsers.autoArchiveGraceHours} <= ${run.graceHours}` : void 0, treeIsQuiet(run), notWaitingOnAnyone());
|
|
8894
|
+
return and(eq(juniorConversationParticipants.userId, run.userId), isNull(juniorConversationParticipants.unsubscribedAt), rootIsUnarchived(), noParticipantKeepsRoot(), lte(juniorConversationParticipants.lastMessageAt, runCutoff(run)), runOptsIn(run), run.kind === "scheduled" ? sql`${juniorUsers.autoArchiveGraceHours} <= ${run.graceHours}` : void 0, treeIsQuiet(run), treeNeedsNoOne(), notWaitingOnAnyone());
|
|
8430
8895
|
}
|
|
8431
8896
|
/**
|
|
8432
8897
|
* One page of the user's participant rows on unarchived roots that may be
|
|
@@ -8562,7 +9027,260 @@ async function setConversationAutoArchive(viewer, conversationId, autoArchive) {
|
|
|
8562
9027
|
});
|
|
8563
9028
|
return { autoArchive };
|
|
8564
9029
|
}
|
|
8565
|
-
// src/chat/
|
|
9030
|
+
// src/chat/inbox-items/automation-answer.ts
|
|
9031
|
+
function isStepLabel(label) {
|
|
9032
|
+
return Object.hasOwn(AUTOMATION_ALERT_STEPS, label);
|
|
9033
|
+
}
|
|
9034
|
+
/**
|
|
9035
|
+
* Take the step that a person picked on an Automation alert, Run again or
|
|
9036
|
+
* Pause, so core does the work. The answer starts no Turn. Throws when the
|
|
9037
|
+
* step fails, so the person can retry the same answer.
|
|
9038
|
+
*/
|
|
9039
|
+
async function answerAutomationAlert(args) {
|
|
9040
|
+
const label = args.item.answer?.values[AUTOMATION_ALERT_STEP_FIELD_ID]?.[0];
|
|
9041
|
+
if (!label || !isStepLabel(label)) return;
|
|
9042
|
+
await takeViewerAutomationAlertStep(args.user, args.item.owner.id, AUTOMATION_ALERT_STEPS[label]);
|
|
9043
|
+
}
|
|
9044
|
+
// src/chat/event-automations/ingest.ts
|
|
9045
|
+
/**
|
|
9046
|
+
* Owns event matching and durable event-automation dispatch.
|
|
9047
|
+
*
|
|
9048
|
+
* Each matching automation is independently idempotent. Aggregate failures propagate
|
|
9049
|
+
* so the provider can retry the original delivery.
|
|
9050
|
+
*/
|
|
9051
|
+
/** Bind provider delivery identity to one automation's durable dispatch. */
|
|
9052
|
+
function eventAutomationDispatchKey(taskId, namespace, eventKey) {
|
|
9053
|
+
return `event-automation:${createHash("sha256").update(`${taskId}\0${namespace}\0${eventKey}`).digest("hex").slice(0, 32)}`;
|
|
9054
|
+
}
|
|
9055
|
+
/** Render plain agent input for one matching event automation. */
|
|
9056
|
+
function eventInput(task, event, outcomes, catalog, author) {
|
|
9057
|
+
const guidance = eventGuidance(catalog, event.namespace, event.eventType);
|
|
9058
|
+
return renderTaskInput({
|
|
9059
|
+
about: task.trigger.label,
|
|
9060
|
+
event: event.eventType,
|
|
9061
|
+
source: event.namespace,
|
|
9062
|
+
creator: slackMention(task.createdBy.slackUserId),
|
|
9063
|
+
instructions: automationTaskText(task.task),
|
|
9064
|
+
...task.task.kind === "skill" ? { skill: task.task.skill } : void 0,
|
|
9065
|
+
outcomes,
|
|
9066
|
+
guidance,
|
|
9067
|
+
trustedSummary: event.trustedSummary,
|
|
9068
|
+
trustedSummaryMaxLength: EVENT_SUMMARY_MAX_LENGTH,
|
|
9069
|
+
verifiedDetails: event.data,
|
|
9070
|
+
authorText: eventAuthorText(author),
|
|
9071
|
+
externalText: event.untrustedText,
|
|
9072
|
+
externalTextMaxLength: EVENT_TEXT_MAX_LENGTH
|
|
9073
|
+
});
|
|
9074
|
+
}
|
|
9075
|
+
/**
|
|
9076
|
+
* Match a normalized event and dispatch every matching automation.
|
|
9077
|
+
*
|
|
9078
|
+
* Plugins publish one copy of an occurrence for each scope, such as a pull
|
|
9079
|
+
* request and its repository. All copies share one event key. An automation
|
|
9080
|
+
* with no identifier matches every copy, and the dispatch key and the run
|
|
9081
|
+
* limit both use the event key, so it runs and counts once.
|
|
9082
|
+
*/
|
|
9083
|
+
async function ingestEventAutomations(input, options) {
|
|
9084
|
+
const event = eventSchema.parse(input);
|
|
9085
|
+
const db = getDb();
|
|
9086
|
+
const nowMs = options.nowMs ?? Date.now();
|
|
9087
|
+
const catalog = getEventCatalog();
|
|
9088
|
+
const [matches = []] = await findMatchingEventAutomations(db, [event], options.teamId, catalog);
|
|
9089
|
+
const tasks = matches.filter((task) => slackChannelMessageRunsAutomation(event, task));
|
|
9090
|
+
if (tasks.length === 0) return { dispatched: 0 };
|
|
9091
|
+
const author = await resolveEventAuthor(event);
|
|
9092
|
+
let dispatched = 0;
|
|
9093
|
+
const errors = [];
|
|
9094
|
+
for (const task of tasks) try {
|
|
9095
|
+
const skill = task.task.kind === "skill" ? task.task.skill : void 0;
|
|
9096
|
+
if (skill && !await findAutomationSkill(skill)) {
|
|
9097
|
+
const reason = missingAutomationSkillReason(skill);
|
|
9098
|
+
if (await blockEventAutomation(db, task.id, reason)) await notifyAutomationBlocked({
|
|
9099
|
+
automationId: task.id,
|
|
9100
|
+
kind: "event",
|
|
9101
|
+
reason
|
|
9102
|
+
});
|
|
9103
|
+
continue;
|
|
9104
|
+
}
|
|
9105
|
+
const idempotencyKey = eventAutomationDispatchKey(task.id, event.namespace, event.eventKey);
|
|
9106
|
+
if (await admitEventAutomationRun({
|
|
9107
|
+
automationId: task.id,
|
|
9108
|
+
nowMs,
|
|
9109
|
+
runKey: idempotencyKey
|
|
9110
|
+
}) === "limited") {
|
|
9111
|
+
const reason = eventAutomationRunLimitReason();
|
|
9112
|
+
logWarn("event_automation.run_limit.exceeded", {
|
|
9113
|
+
"app.task.id": task.id,
|
|
9114
|
+
"app.task.type": "event"
|
|
9115
|
+
});
|
|
9116
|
+
if (await blockEventAutomation(db, task.id, reason)) {
|
|
9117
|
+
captureMessage("Event automation blocked by run limit", {
|
|
9118
|
+
level: "warning",
|
|
9119
|
+
fingerprint: ["event_automation.run_limit.blocked"],
|
|
9120
|
+
tags: {
|
|
9121
|
+
"app.event.namespace": event.namespace,
|
|
9122
|
+
"app.task.type": "event"
|
|
9123
|
+
},
|
|
9124
|
+
extra: {
|
|
9125
|
+
"app.event.event_type": event.eventType,
|
|
9126
|
+
"app.event_automation.max_runs": botConfig.maxEventAutomationRuns,
|
|
9127
|
+
"app.event_automation.run_window_ms": botConfig.eventAutomationRunWindowMs,
|
|
9128
|
+
"app.event_automation.resource_type": task.trigger.resourceType ?? "any",
|
|
9129
|
+
"app.task.id": task.id
|
|
9130
|
+
}
|
|
9131
|
+
});
|
|
9132
|
+
await notifyAutomationBlocked({
|
|
9133
|
+
automationId: task.id,
|
|
9134
|
+
kind: "event",
|
|
9135
|
+
reason
|
|
9136
|
+
});
|
|
9137
|
+
}
|
|
9138
|
+
continue;
|
|
9139
|
+
}
|
|
9140
|
+
const replyThreadTs = slackChannelMessageReplyThreadTs(event);
|
|
9141
|
+
const destination = replyThreadTs ? {
|
|
9142
|
+
...task.destination,
|
|
9143
|
+
threadTs: replyThreadTs
|
|
9144
|
+
} : task.destination;
|
|
9145
|
+
const outcomes = effectiveTaskOutcomes(task.outcomes, destination);
|
|
9146
|
+
const credentialSubject = task.credentialMode === "creator" ? {
|
|
9147
|
+
type: "user",
|
|
9148
|
+
userId: task.createdBy.slackUserId,
|
|
9149
|
+
allowedWhen: "event-automation",
|
|
9150
|
+
taskId: task.id
|
|
9151
|
+
} : void 0;
|
|
9152
|
+
const dispatch = await dispatchEventAutomation({
|
|
9153
|
+
automationId: task.id,
|
|
9154
|
+
conversationWorkQueue: options.queue,
|
|
9155
|
+
nowMs,
|
|
9156
|
+
options: {
|
|
9157
|
+
idempotencyKey,
|
|
9158
|
+
...credentialSubject ? { credentialSubject } : void 0,
|
|
9159
|
+
destination,
|
|
9160
|
+
destinationVisibility: task.destinationVisibility,
|
|
9161
|
+
input: eventInput(task, event, outcomes, catalog, author),
|
|
9162
|
+
...skill ? { skill } : void 0,
|
|
9163
|
+
metadata: { eventAutomationId: task.id },
|
|
9164
|
+
replyAttribution: automationReplyAttribution(task.title),
|
|
9165
|
+
outcomes
|
|
9166
|
+
}
|
|
9167
|
+
});
|
|
9168
|
+
await recordEventAutomationRunStarted(db, {
|
|
9169
|
+
automation: task,
|
|
9170
|
+
dispatchId: dispatch.id,
|
|
9171
|
+
nowMs
|
|
9172
|
+
});
|
|
9173
|
+
if (dispatch.status === "created") dispatched += 1;
|
|
9174
|
+
} catch (error) {
|
|
9175
|
+
errors.push(error);
|
|
9176
|
+
}
|
|
9177
|
+
if (errors.length > 0) throw new AggregateError(errors, "Failed to dispatch one or more event automations");
|
|
9178
|
+
return { dispatched };
|
|
9179
|
+
}
|
|
9180
|
+
// src/chat/events/app-publisher.ts
|
|
9181
|
+
const WATCH_MATCH_CONCURRENCY = 4;
|
|
9182
|
+
/** Build the core event publisher used by plugin routes. */
|
|
9183
|
+
function createEventAppPublisher(args) {
|
|
9184
|
+
return {
|
|
9185
|
+
async hasMatch(events) {
|
|
9186
|
+
const work = args.conversationWork();
|
|
9187
|
+
const eventAutomationTeamId = await resolveBotSlackTeamId();
|
|
9188
|
+
const [subscriptions, tasks, snoozed] = await Promise.all([
|
|
9189
|
+
mapBounded(events, (event) => findMatchingWatches({
|
|
9190
|
+
data: event.data,
|
|
9191
|
+
eventType: event.eventType,
|
|
9192
|
+
namespace: event.namespace,
|
|
9193
|
+
identifier: event.identifier,
|
|
9194
|
+
state: work.state
|
|
9195
|
+
}), WATCH_MATCH_CONCURRENCY),
|
|
9196
|
+
eventAutomationTeamId ? findMatchingEventAutomations(getDb(), events, eventAutomationTeamId, getEventCatalog()) : Promise.resolve([]),
|
|
9197
|
+
hasInboxSnoozeMatch(getDb(), events)
|
|
9198
|
+
]);
|
|
9199
|
+
return snoozed || [...subscriptions, ...tasks].some((matched) => matched.length > 0);
|
|
9200
|
+
},
|
|
9201
|
+
async neededMatchKeys(input) {
|
|
9202
|
+
const work = args.conversationWork();
|
|
9203
|
+
const eventAutomationTeamId = await resolveBotSlackTeamId();
|
|
9204
|
+
const [watchKeys, taskKeys, snoozeKeys] = await Promise.all([
|
|
9205
|
+
collectEventMatchKeys({
|
|
9206
|
+
eventTypes: input.eventTypes,
|
|
9207
|
+
identifiers: input.identifiers,
|
|
9208
|
+
namespace: input.namespace,
|
|
9209
|
+
state: work.state
|
|
9210
|
+
}),
|
|
9211
|
+
eventAutomationTeamId ? collectEventAutomationMatchKeys(getDb(), {
|
|
9212
|
+
catalog: getEventCatalog(),
|
|
9213
|
+
...input.data ? { data: input.data } : void 0,
|
|
9214
|
+
eventTypes: input.eventTypes,
|
|
9215
|
+
identifiers: input.identifiers,
|
|
9216
|
+
namespace: input.namespace,
|
|
9217
|
+
teamId: eventAutomationTeamId
|
|
9218
|
+
}) : Promise.resolve([]),
|
|
9219
|
+
collectInboxSnoozeMatchKeys(getDb(), {
|
|
9220
|
+
eventTypes: input.eventTypes,
|
|
9221
|
+
identifiers: input.identifiers,
|
|
9222
|
+
namespace: input.namespace
|
|
9223
|
+
})
|
|
9224
|
+
]);
|
|
9225
|
+
return [.../* @__PURE__ */ new Set([
|
|
9226
|
+
...watchKeys,
|
|
9227
|
+
...taskKeys,
|
|
9228
|
+
...snoozeKeys
|
|
9229
|
+
])].sort();
|
|
9230
|
+
},
|
|
9231
|
+
async publish(event) {
|
|
9232
|
+
const work = args.conversationWork();
|
|
9233
|
+
const queue = work.queue ?? getVercelConversationWorkQueue();
|
|
9234
|
+
const eventAutomationTeamId = await resolveBotSlackTeamId();
|
|
9235
|
+
await Promise.all([
|
|
9236
|
+
ingestEvent(event, {
|
|
9237
|
+
queue,
|
|
9238
|
+
slackTeamId: eventAutomationTeamId,
|
|
9239
|
+
state: work.state
|
|
9240
|
+
}),
|
|
9241
|
+
eventAutomationTeamId ? ingestEventAutomations(event, {
|
|
9242
|
+
queue,
|
|
9243
|
+
teamId: eventAutomationTeamId
|
|
9244
|
+
}) : Promise.resolve(),
|
|
9245
|
+
fireInboxSnoozeTriggers(getDb(), event)
|
|
9246
|
+
]);
|
|
9247
|
+
}
|
|
9248
|
+
};
|
|
9249
|
+
}
|
|
9250
|
+
// src/chat/inbox-items/plugin-answer.ts
|
|
9251
|
+
/**
|
|
9252
|
+
* Give the answer of a plugin item with choices to the plugin that added it,
|
|
9253
|
+
* so the plugin does the work. The answer starts no Turn. Throws when the
|
|
9254
|
+
* plugin fails, so the person can retry the same answer.
|
|
9255
|
+
*/
|
|
9256
|
+
async function answerPluginInboxItem(args) {
|
|
9257
|
+
const { item } = args;
|
|
9258
|
+
const pluginName = inboxItemPlugin(item.dedupeKey);
|
|
9259
|
+
const choice = item.answer?.values[PLUGIN_CHOICE_FIELD_ID]?.[0];
|
|
9260
|
+
const conversationId = ownerConversationId(item);
|
|
9261
|
+
if (!pluginName || !choice || !conversationId) return;
|
|
9262
|
+
const plugin = getPlugins().find((p) => p.manifest.name === pluginName);
|
|
9263
|
+
const hook = plugin?.hooks?.inboxItemAnswered;
|
|
9264
|
+
if (!plugin || !hook) return;
|
|
9265
|
+
const events = createEventAppPublisher({ conversationWork: () => ({ queue: args.delivery.queue }) });
|
|
9266
|
+
await hook({
|
|
9267
|
+
...basePluginContext(plugin),
|
|
9268
|
+
choice,
|
|
9269
|
+
conversationId,
|
|
9270
|
+
dedupeKey: item.dedupeKey.slice(`${PLUGIN_INBOX_ITEM_KEY_PREFIX}${pluginName}:`.length),
|
|
9271
|
+
events: createPluginEventPublisher(plugin, events),
|
|
9272
|
+
itemId: item.id,
|
|
9273
|
+
nowMs: args.nowMs,
|
|
9274
|
+
inboxItems: { forConversation: (conversationId) => createPluginInboxItems({
|
|
9275
|
+
conversationId,
|
|
9276
|
+
plugin: pluginName,
|
|
9277
|
+
show: args.delivery.show
|
|
9278
|
+
}) },
|
|
9279
|
+
state: createPluginState(pluginName),
|
|
9280
|
+
watches: createPluginConversationWatches(plugin, conversationId)
|
|
9281
|
+
});
|
|
9282
|
+
}
|
|
9283
|
+
// src/chat/inbox-items/reply-match.ts
|
|
8566
9284
|
const MATCH_CONFIDENCE_THRESHOLD = .7;
|
|
8567
9285
|
/** A slow decision keeps the items open instead of delaying the close. */
|
|
8568
9286
|
const MATCH_TIMEOUT_MS = 1e4;
|
|
@@ -8597,7 +9315,7 @@ function matchQuestion(item) {
|
|
|
8597
9315
|
* decision call judges each item on its own, so a reply can answer one item,
|
|
8598
9316
|
* several items, or none. A failed decision throws.
|
|
8599
9317
|
*/
|
|
8600
|
-
async function
|
|
9318
|
+
async function matchReplyToInboxItems(args) {
|
|
8601
9319
|
const text = args.text.trim();
|
|
8602
9320
|
if (!text || args.items.length === 0) return /* @__PURE__ */ new Set();
|
|
8603
9321
|
const keys = args.items.map((_, index) => `item_${index}`);
|
|
@@ -8607,7 +9325,7 @@ async function matchReplyToReviewItems(args) {
|
|
|
8607
9325
|
modelId: botConfig.decisionModelId
|
|
8608
9326
|
},
|
|
8609
9327
|
modelId: botConfig.decisionModelId,
|
|
8610
|
-
operation: "
|
|
9328
|
+
operation: "inbox_item_reply_match",
|
|
8611
9329
|
cost: { conversationId: args.conversationId },
|
|
8612
9330
|
questions: Object.fromEntries(args.items.map((item, index) => [keys[index], matchQuestion(item)])),
|
|
8613
9331
|
signal: AbortSignal.timeout(MATCH_TIMEOUT_MS),
|
|
@@ -8625,20 +9343,20 @@ async function matchReplyToReviewItems(args) {
|
|
|
8625
9343
|
}
|
|
8626
9344
|
return matched;
|
|
8627
9345
|
}
|
|
8628
|
-
// src/chat/
|
|
9346
|
+
// src/chat/inbox-items/actions.ts
|
|
8629
9347
|
/** An expected failure of a person action, for the API to report. */
|
|
8630
|
-
var
|
|
9348
|
+
var InboxItemActionError = class extends Error {
|
|
8631
9349
|
code;
|
|
8632
9350
|
constructor(code, message) {
|
|
8633
9351
|
super(message);
|
|
8634
|
-
this.name = "
|
|
9352
|
+
this.name = "InboxItemActionError";
|
|
8635
9353
|
this.code = code;
|
|
8636
9354
|
}
|
|
8637
9355
|
};
|
|
8638
|
-
/** Read one
|
|
8639
|
-
async function
|
|
8640
|
-
const item = await
|
|
8641
|
-
if (!item || !await
|
|
9356
|
+
/** Read one Inbox item that a User can see, or fail as not found. */
|
|
9357
|
+
async function readInboxItemForUser(user, id) {
|
|
9358
|
+
const item = await getInboxItem(getDb(), id);
|
|
9359
|
+
if (!item || !await canUserReadInboxItem(item, user)) throw new InboxItemActionError("not_found", "Inbox item not found.");
|
|
8642
9360
|
return item;
|
|
8643
9361
|
}
|
|
8644
9362
|
function closedStatus(action) {
|
|
@@ -8661,23 +9379,23 @@ function reviewItemChange(action, user) {
|
|
|
8661
9379
|
}
|
|
8662
9380
|
/**
|
|
8663
9381
|
* Return whether a closed item is the result of this same action. An item
|
|
8664
|
-
* that a person's message closed never matches a card or
|
|
9382
|
+
* that a person's message closed never matches a card or Inbox action.
|
|
8665
9383
|
*/
|
|
8666
9384
|
function isSameClose(item, action, user) {
|
|
8667
9385
|
return item.closeReason !== "Replied in thread" && item.closedBy?.userId === user.id && item.status === closedStatus(action) && action === "submit" === Boolean(item.answer);
|
|
8668
9386
|
}
|
|
8669
9387
|
function submittedAnswer(item, answer) {
|
|
8670
|
-
if (item.kind !== "action" || !item.request) throw new
|
|
9388
|
+
if (item.kind !== "action" || !item.request) throw new InboxItemActionError("invalid", "Only an action item takes an answer.");
|
|
8671
9389
|
const normalized = normalizeUserInputAnswer(item.request, {
|
|
8672
9390
|
other: answer?.other,
|
|
8673
9391
|
requestId: item.id,
|
|
8674
9392
|
values: answer?.values ?? {}
|
|
8675
9393
|
});
|
|
8676
|
-
if (isEmptyUserInputAnswer(normalized)) throw new
|
|
9394
|
+
if (isEmptyUserInputAnswer(normalized)) throw new InboxItemActionError("invalid", "The answer is empty.");
|
|
8677
9395
|
return normalized;
|
|
8678
9396
|
}
|
|
8679
9397
|
/**
|
|
8680
|
-
* Do one person action on
|
|
9398
|
+
* Do one person action on an Inbox item and tell its linked Conversations.
|
|
8681
9399
|
* The first submit or dismiss closes the item for every
|
|
8682
9400
|
* assignee. A retry of the same close sends any missing messages again and
|
|
8683
9401
|
* succeeds, so a client can retry after a failure. With `firstCloseOnly`,
|
|
@@ -8687,23 +9405,23 @@ function submittedAnswer(item, answer) {
|
|
|
8687
9405
|
* `exceptConversationId` is the Conversation where the person acted. It gets
|
|
8688
9406
|
* the person's input from its own surface, so it gets no message here.
|
|
8689
9407
|
* `delivery` shows the change and sends the messages; see
|
|
8690
|
-
* `
|
|
9408
|
+
* `deliverInboxItemChange`.
|
|
8691
9409
|
*/
|
|
8692
|
-
async function
|
|
9410
|
+
async function actOnInboxItem(args) {
|
|
8693
9411
|
const { action, user } = args;
|
|
8694
9412
|
const nowMs = args.nowMs ?? Date.now();
|
|
8695
9413
|
const db = getDb();
|
|
8696
|
-
const item = await
|
|
9414
|
+
const item = await readInboxItemForUser(user, args.id);
|
|
8697
9415
|
if (action === "take") {
|
|
8698
|
-
if (item.status !== "open") throw new
|
|
8699
|
-
if (!
|
|
8700
|
-
if (!isOnlyAssignee(item, user.id) && !await
|
|
9416
|
+
if (item.status !== "open") throw new InboxItemActionError("conflict", "Inbox item is closed.");
|
|
9417
|
+
if (!canActOnInboxItem(item, user.id)) throw new InboxItemActionError("forbidden", "Only an assignee can take this item.");
|
|
9418
|
+
if (!isOnlyAssignee(item, user.id) && !await takeInboxItem(db, {
|
|
8701
9419
|
id: item.id,
|
|
8702
9420
|
nowMs,
|
|
8703
9421
|
userId: user.id
|
|
8704
|
-
})) throw new
|
|
8705
|
-
const taken = await
|
|
8706
|
-
await
|
|
9422
|
+
})) throw new InboxItemActionError("conflict", "Inbox item is closed.");
|
|
9423
|
+
const taken = await readInboxItemForUser(user, item.id);
|
|
9424
|
+
await deliverInboxItemChange({
|
|
8707
9425
|
change: reviewItemChange(action, user),
|
|
8708
9426
|
delivery: args.delivery,
|
|
8709
9427
|
exceptConversationId: args.exceptConversationId,
|
|
@@ -8715,19 +9433,34 @@ async function actOnReviewItem(args) {
|
|
|
8715
9433
|
let closed = item;
|
|
8716
9434
|
let closedNow = false;
|
|
8717
9435
|
if (item.status === "open") {
|
|
8718
|
-
if (!
|
|
9436
|
+
if (!canActOnInboxItem(item, user.id)) throw new InboxItemActionError("forbidden", "Only an assignee can act on this item.");
|
|
8719
9437
|
const answer = action === "submit" ? submittedAnswer(item, args.answer) : void 0;
|
|
8720
|
-
closedNow = await
|
|
9438
|
+
closedNow = await closeInboxItem(db, {
|
|
8721
9439
|
closedByUserId: user.id,
|
|
8722
9440
|
id: item.id,
|
|
8723
9441
|
nowMs,
|
|
8724
9442
|
status: closedStatus(action),
|
|
8725
9443
|
...answer ? { answer } : void 0
|
|
8726
9444
|
});
|
|
8727
|
-
closed = await
|
|
9445
|
+
closed = await readInboxItemForUser(user, item.id);
|
|
9446
|
+
}
|
|
9447
|
+
if (args.firstCloseOnly ? !closedNow : !isSameClose(closed, action, user)) throw new InboxItemActionError("conflict", "Inbox item is closed.");
|
|
9448
|
+
if (action === "submit" && isPluginInboxItem(closed)) await answerPluginInboxItem({
|
|
9449
|
+
delivery: args.delivery,
|
|
9450
|
+
item: closed,
|
|
9451
|
+
nowMs
|
|
9452
|
+
});
|
|
9453
|
+
if (action === "submit" && isAutomationAlertItem(closed)) try {
|
|
9454
|
+
await answerAutomationAlert({
|
|
9455
|
+
item: closed,
|
|
9456
|
+
user
|
|
9457
|
+
});
|
|
9458
|
+
} catch (error) {
|
|
9459
|
+
if (error instanceof ViewerTaskNotFoundError) throw new InboxItemActionError("not_found", "Automation not found.");
|
|
9460
|
+
if (error instanceof AutomationEditError) throw new InboxItemActionError("invalid", error.message);
|
|
9461
|
+
throw error;
|
|
8728
9462
|
}
|
|
8729
|
-
|
|
8730
|
-
await deliverReviewItemChange({
|
|
9463
|
+
await deliverInboxItemChange({
|
|
8731
9464
|
change: reviewItemChange(action, user),
|
|
8732
9465
|
delivery: args.delivery,
|
|
8733
9466
|
exceptConversationId: args.exceptConversationId,
|
|
@@ -8764,25 +9497,25 @@ function messageAnswer(item, text) {
|
|
|
8764
9497
|
*
|
|
8765
9498
|
* A reply closes an item only when all of these are true:
|
|
8766
9499
|
* - The item is an open `action` item.
|
|
8767
|
-
* - The agent added it in this Conversation
|
|
9500
|
+
* - The agent added it in this Conversation, its owner.
|
|
8768
9501
|
* - The replier is an assigned User, or the item has no assignees. A Slack
|
|
8769
9502
|
* replier without a Junior User closes only items with no assignees.
|
|
8770
9503
|
* - The decision model says that the reply answers this item
|
|
8771
|
-
* (`
|
|
9504
|
+
* (`matchReplyToInboxItems`). Other open items in the thread stay open.
|
|
8772
9505
|
* When the decision fails, all items stay open.
|
|
8773
9506
|
*
|
|
8774
9507
|
* Items assigned to Everyone, or only to other people, stay open. They need
|
|
8775
|
-
* an answer on the card or the
|
|
8776
|
-
* `
|
|
9508
|
+
* an answer on the card or the Inbox. Each item closes as `done` with
|
|
9509
|
+
* `INBOX_ITEM_REPLIED_REASON`, and the replier closes it. The reply itself
|
|
8777
9510
|
* is the answer in this Conversation, so only the other linked
|
|
8778
9511
|
* Conversations get a message. A click that closes the item first wins.
|
|
8779
9512
|
* A retry of the reply, or a later reply from the same person, delivers
|
|
8780
9513
|
* the items that it closed again: the cards show the close, and only the
|
|
8781
9514
|
* missing messages go. Each message has a key, so a message that was sent
|
|
8782
9515
|
* does not go again. `delivery` shows the change and sends the messages;
|
|
8783
|
-
* see `
|
|
9516
|
+
* see `deliverInboxItemChange`.
|
|
8784
9517
|
*/
|
|
8785
|
-
async function
|
|
9518
|
+
async function closeInboxItemsAnsweredByReply(args) {
|
|
8786
9519
|
const db = getDb();
|
|
8787
9520
|
const items = await listReplyActionItems(db, args.conversationId);
|
|
8788
9521
|
if (items.length === 0) return;
|
|
@@ -8792,13 +9525,13 @@ async function closeReviewItemsAnsweredByReply(args) {
|
|
|
8792
9525
|
const answered = items.filter((candidate) => replyAnswers(candidate, user));
|
|
8793
9526
|
let matched;
|
|
8794
9527
|
try {
|
|
8795
|
-
matched = await
|
|
9528
|
+
matched = await matchReplyToInboxItems({
|
|
8796
9529
|
conversationId: args.conversationId,
|
|
8797
9530
|
items: answered.filter((candidate) => candidate.status === "open"),
|
|
8798
9531
|
text: args.text
|
|
8799
9532
|
});
|
|
8800
9533
|
} catch (error) {
|
|
8801
|
-
logWarn("
|
|
9534
|
+
logWarn("inbox_item.reply_match.failed", {
|
|
8802
9535
|
"exception.message": error instanceof Error ? error.message : String(error),
|
|
8803
9536
|
"gen_ai.conversation.id": args.conversationId
|
|
8804
9537
|
});
|
|
@@ -8809,7 +9542,7 @@ async function closeReviewItemsAnsweredByReply(args) {
|
|
|
8809
9542
|
let closedItem = item;
|
|
8810
9543
|
if (item.status === "open") {
|
|
8811
9544
|
const answer = messageAnswer(item, args.text);
|
|
8812
|
-
if (!await
|
|
9545
|
+
if (!await closeInboxItem(db, {
|
|
8813
9546
|
...answer ? { answer } : void 0,
|
|
8814
9547
|
id: item.id,
|
|
8815
9548
|
nowMs,
|
|
@@ -8817,10 +9550,10 @@ async function closeReviewItemsAnsweredByReply(args) {
|
|
|
8817
9550
|
status: "done",
|
|
8818
9551
|
...user ? { closedByUserId: user.id } : void 0
|
|
8819
9552
|
})) continue;
|
|
8820
|
-
closedItem = await
|
|
9553
|
+
closedItem = await getInboxItem(db, item.id);
|
|
8821
9554
|
if (!closedItem) continue;
|
|
8822
9555
|
}
|
|
8823
|
-
await
|
|
9556
|
+
await deliverInboxItemChange({
|
|
8824
9557
|
change: {
|
|
8825
9558
|
kind: "replied",
|
|
8826
9559
|
who: user ? user.displayName ?? user.email : "A person"
|
|
@@ -8832,81 +9565,6 @@ async function closeReviewItemsAnsweredByReply(args) {
|
|
|
8832
9565
|
});
|
|
8833
9566
|
}
|
|
8834
9567
|
}
|
|
8835
|
-
// src/chat/conversations/stop.ts
|
|
8836
|
-
/**
|
|
8837
|
-
* Stop a Conversation for a person, on every stop path. Every child agent
|
|
8838
|
-
* below it stops, then it and they are stopped Conversations until a person
|
|
8839
|
-
* sends input, and then its Turn stops. A Turn that waits for sign-in ends
|
|
8840
|
-
* too, so a later sign-in does not resume it. Their Watch Events are saved
|
|
8841
|
-
* and start no Turn. Nothing above it changes: a stopped child agent's worker
|
|
8842
|
-
* reports the stop to its parent.
|
|
8843
|
-
*
|
|
8844
|
-
* A stop that comes from a message or a button press, such as the Slack
|
|
8845
|
-
* `stop` keyword or stop button, passes it. Its id is claimed in the mailbox
|
|
8846
|
-
* first, so a redelivery returns `duplicate` and stops nothing, not even
|
|
8847
|
-
* newer work. A stop that fails before its stop request is saved releases
|
|
8848
|
-
* its claim, so a redelivery can stop again. A failed claim check keeps a
|
|
8849
|
-
* claim that an earlier delivery saved. A failure after the stop request is
|
|
8850
|
-
* saved keeps the claim, as does a failed reply: the work is already
|
|
8851
|
-
* stopped, and a redelivery must not stop newer work. Its send time
|
|
8852
|
-
* is the stop time, and only person input sent at or before it is dropped.
|
|
8853
|
-
* So a retry writes the same stop and keeps input that the person sent after
|
|
8854
|
-
* it.
|
|
8855
|
-
*
|
|
8856
|
-
* The child agents and sessions stop first, so a failure leaves the Turn
|
|
8857
|
-
* running and the stop can be retried. A child agent can outlive the parent
|
|
8858
|
-
* Turn, so this runs even when no Turn runs.
|
|
8859
|
-
*/
|
|
8860
|
-
async function stopConversation(args) {
|
|
8861
|
-
if (args.message && (await claimInboundMessage({
|
|
8862
|
-
conversationStore: args.conversationStore,
|
|
8863
|
-
message: args.message,
|
|
8864
|
-
state: args.state
|
|
8865
|
-
})).status === "duplicate") return { status: "duplicate" };
|
|
8866
|
-
let stopSaved = false;
|
|
8867
|
-
try {
|
|
8868
|
-
const nowMs = Date.now();
|
|
8869
|
-
const stoppedAtMs = args.message?.createdAtMs ?? nowMs;
|
|
8870
|
-
await stopChildAgentsBelow(args.conversationId, {
|
|
8871
|
-
nowMs,
|
|
8872
|
-
stoppedAtMs,
|
|
8873
|
-
state: args.state
|
|
8874
|
-
});
|
|
8875
|
-
await markConversationsStopped([args.conversationId], {
|
|
8876
|
-
cancelWatches: false,
|
|
8877
|
-
nowMs: stoppedAtMs,
|
|
8878
|
-
state: args.state
|
|
8879
|
-
});
|
|
8880
|
-
await dropOwnUnreadLoopReplies(args.conversationId, args.state);
|
|
8881
|
-
await cancelSignInWait(args.conversationId);
|
|
8882
|
-
const result = await stopConversationWork({
|
|
8883
|
-
conversationId: args.conversationId,
|
|
8884
|
-
conversationStore: args.conversationStore,
|
|
8885
|
-
nowMs,
|
|
8886
|
-
onStopSaved: () => {
|
|
8887
|
-
stopSaved = true;
|
|
8888
|
-
},
|
|
8889
|
-
sentAtOrBeforeMs: args.message ? stoppedAtMs : void 0,
|
|
8890
|
-
state: args.state
|
|
8891
|
-
});
|
|
8892
|
-
if (result.status === "requested") await ensureConversationWake({
|
|
8893
|
-
conversationId: args.conversationId,
|
|
8894
|
-
conversationStore: args.conversationStore,
|
|
8895
|
-
idempotencyKey: `conversation-stop:${args.conversationId}:${result.runId}`,
|
|
8896
|
-
nowMs,
|
|
8897
|
-
queue: args.queue,
|
|
8898
|
-
replaceExistingWake: true,
|
|
8899
|
-
state: args.state
|
|
8900
|
-
});
|
|
8901
|
-
return result;
|
|
8902
|
-
} catch (error) {
|
|
8903
|
-
if (args.message && !stopSaved) await releaseInboundMessage({
|
|
8904
|
-
message: args.message,
|
|
8905
|
-
state: args.state
|
|
8906
|
-
});
|
|
8907
|
-
throw error;
|
|
8908
|
-
}
|
|
8909
|
-
}
|
|
8910
9568
|
// src/api/mentions.ts
|
|
8911
9569
|
function mentionedSlackUserIds(texts) {
|
|
8912
9570
|
const ids = texts.flatMap((text) => text ? slackMentionedUserIds(text) : []);
|
|
@@ -8936,27 +9594,40 @@ async function resolveMentions(executor, sources) {
|
|
|
8936
9594
|
});
|
|
8937
9595
|
});
|
|
8938
9596
|
}
|
|
9597
|
+
const userPhotos = alias(juniorIdentities, "mention_user_photos");
|
|
8939
9598
|
/**
|
|
8940
|
-
* Read current names for mentioned Slack users. Known Junior
|
|
8941
|
-
* first. The email is set only for a linked, verified Junior
|
|
8942
|
-
* that email is the People profile route.
|
|
9599
|
+
* Read current names and photos for mentioned Slack users. Known Junior
|
|
9600
|
+
* identities come first. The email is set only for a linked, verified Junior
|
|
9601
|
+
* user, because that email is the People profile route.
|
|
8943
9602
|
*/
|
|
8944
9603
|
async function readMentionedPeople(executor, tenantId, userIds) {
|
|
8945
9604
|
const rows = await executor.db().select({
|
|
9605
|
+
avatarUrl: juniorIdentities.avatarUrl,
|
|
8946
9606
|
displayName: juniorIdentities.displayName,
|
|
8947
9607
|
emailVerified: juniorIdentities.emailVerified,
|
|
8948
9608
|
handle: juniorIdentities.handle,
|
|
9609
|
+
identityId: juniorIdentities.id,
|
|
9610
|
+
photo: {
|
|
9611
|
+
avatarUrl: userPhotos.avatarUrl,
|
|
9612
|
+
identityId: userPhotos.id,
|
|
9613
|
+
provider: userPhotos.provider,
|
|
9614
|
+
updatedAt: userPhotos.updatedAt
|
|
9615
|
+
},
|
|
8949
9616
|
providerSubjectId: juniorIdentities.providerSubjectId,
|
|
8950
9617
|
userDisplayName: juniorUsers.displayName,
|
|
8951
|
-
userEmail: juniorUsers.primaryEmail
|
|
8952
|
-
|
|
9618
|
+
userEmail: juniorUsers.primaryEmail,
|
|
9619
|
+
userId: juniorIdentities.userId
|
|
9620
|
+
}).from(juniorIdentities).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).leftJoin(userPhotos, and(eq(userPhotos.userId, juniorIdentities.userId), hasUserPhoto(userPhotos))).where(and(eq(juniorIdentities.provider, "slack"), inArray(juniorIdentities.providerSubjectId, userIds), tenantId ? eq(juniorIdentities.providerTenantId, tenantId) : void 0));
|
|
9621
|
+
const userAvatarUrls = userAvatarUrlsFromJoinedPhotos(rows);
|
|
8953
9622
|
const people = /* @__PURE__ */ new Map();
|
|
8954
9623
|
for (const row of rows) {
|
|
8955
9624
|
if (people.has(row.providerSubjectId)) continue;
|
|
8956
9625
|
const fullName = row.userDisplayName?.trim() || row.displayName?.trim();
|
|
8957
9626
|
const email = row.emailVerified ? row.userEmail?.trim() : void 0;
|
|
9627
|
+
const avatarUrl = identityAvatarUrl(row, userAvatarUrls);
|
|
8958
9628
|
people.set(row.providerSubjectId, {
|
|
8959
9629
|
slackUserId: row.providerSubjectId,
|
|
9630
|
+
...avatarUrl ? { avatarUrl } : void 0,
|
|
8960
9631
|
...fullName ? { fullName } : void 0,
|
|
8961
9632
|
...row.handle ? { slackUserName: row.handle } : void 0,
|
|
8962
9633
|
...email ? { email } : void 0
|
|
@@ -9132,7 +9803,7 @@ async function readConversationPendingMessages(conversationId, options = {}) {
|
|
|
9132
9803
|
actorIdentityId
|
|
9133
9804
|
} : message];
|
|
9134
9805
|
}));
|
|
9135
|
-
return
|
|
9806
|
+
return {
|
|
9136
9807
|
...authorization ? { authorization: {
|
|
9137
9808
|
authorizationUrl: authorization.authorizationUrl,
|
|
9138
9809
|
completionText: authorization.completionText,
|
|
@@ -9141,7 +9812,7 @@ async function readConversationPendingMessages(conversationId, options = {}) {
|
|
|
9141
9812
|
conversationId,
|
|
9142
9813
|
generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
9143
9814
|
messages
|
|
9144
|
-
}
|
|
9815
|
+
};
|
|
9145
9816
|
}
|
|
9146
9817
|
/** Load pending mailbox messages or throw a standard API not-found error. */
|
|
9147
9818
|
async function requireConversationPendingMessages(conversationId, options = {}) {
|
|
@@ -9149,11 +9820,209 @@ async function requireConversationPendingMessages(conversationId, options = {})
|
|
|
9149
9820
|
if (!report) throwApiError(404, "Conversation not found.");
|
|
9150
9821
|
return report;
|
|
9151
9822
|
}
|
|
9823
|
+
// src/api/mcp/conversation.ts
|
|
9824
|
+
/** Own the MCP view of one Conversation, shared by the conversation tools. */
|
|
9825
|
+
/** MCP view of one Conversation. It omits dashboard-only fields. */
|
|
9826
|
+
const mcpConversationSchema = z.object({
|
|
9827
|
+
conversationId: z.string(),
|
|
9828
|
+
title: z.string(),
|
|
9829
|
+
summary: z.string().optional().describe("What was asked and what happened, as of the last Turn."),
|
|
9830
|
+
status: conversationReportStatusSchema.describe("`needs_input` while it waits on a person: an Inbox item it added, a sign-in, a failed latest Turn, a `partial` or `blocked` Brief, or an answer its starter has not read. `working` while a Turn runs or waits to start. `done` otherwise, also after a stop."),
|
|
9831
|
+
turnActive: z.boolean().describe("True while a Turn runs or waits to start, whatever `status` is. To follow a Conversation, wait until it is false."),
|
|
9832
|
+
treeState: conversationTreeStateSchema.optional().describe("Your viewer state, over this Conversation and all its child agents. `needs_you` when one of them waits on you or on everyone. `working` while a Turn runs or waits to start in any of them. `done` otherwise. Show this in a list, not `status`."),
|
|
9833
|
+
watching: z.boolean().optional().describe("True when one of them has an active Watch or a pending Timer. It is not work."),
|
|
9834
|
+
surface: conversationSurfaceSchema.describe("Where it started: `slack`, `api` (the dashboard or MCP), `scheduler` (an automation), or `internal`."),
|
|
9835
|
+
channelName: z.string().optional().describe("Slack channel name."),
|
|
9836
|
+
locationUrl: z.string().optional().describe("Slack thread link."),
|
|
9837
|
+
startedAt: z.string(),
|
|
9838
|
+
lastSeenAt: z.string().describe("Time of the newest activity. archiveConversation takes this value."),
|
|
9839
|
+
archivedAt: z.string().optional().describe("Set when anyone archived it. Archive applies to everyone."),
|
|
9840
|
+
pinnedAt: z.string().optional().describe("Set when you pinned it."),
|
|
9841
|
+
url: z.string().optional().describe("Dashboard link.")
|
|
9842
|
+
}).strict();
|
|
9843
|
+
/** Map a Conversation summary to its MCP view. */
|
|
9844
|
+
function mcpConversation(summary) {
|
|
9845
|
+
return {
|
|
9846
|
+
conversationId: summary.conversationId,
|
|
9847
|
+
title: summary.displayTitle,
|
|
9848
|
+
summary: summary.summary,
|
|
9849
|
+
status: summary.status,
|
|
9850
|
+
turnActive: summary.turnActive,
|
|
9851
|
+
treeState: summary.treeState,
|
|
9852
|
+
watching: summary.watching,
|
|
9853
|
+
surface: summary.surface,
|
|
9854
|
+
channelName: summary.channelNameRedacted ? void 0 : summary.channelName,
|
|
9855
|
+
locationUrl: summary.locationUrl,
|
|
9856
|
+
startedAt: summary.startedAt,
|
|
9857
|
+
lastSeenAt: summary.lastSeenAt,
|
|
9858
|
+
archivedAt: summary.archivedAt ?? void 0,
|
|
9859
|
+
pinnedAt: summary.pinnedAt ?? void 0,
|
|
9860
|
+
url: getDashboardConversationLink(summary.conversationId)
|
|
9861
|
+
};
|
|
9862
|
+
}
|
|
9863
|
+
/** Conversation id param shared by the conversation tools. */
|
|
9864
|
+
const mcpConversationIdSchema = z.string().min(1).describe("Conversation id from searchConversations or createConversation.");
|
|
9865
|
+
const mcpAttachmentsSchema = z.array(z.object({
|
|
9866
|
+
filename: z.string(),
|
|
9867
|
+
contentType: z.string(),
|
|
9868
|
+
bytes: z.number().int()
|
|
9869
|
+
}).strict()).optional();
|
|
9870
|
+
function mcpAttachments(attachments) {
|
|
9871
|
+
return attachments?.length ? attachments.map(({ bytes, contentType, filename }) => ({
|
|
9872
|
+
bytes,
|
|
9873
|
+
contentType,
|
|
9874
|
+
filename
|
|
9875
|
+
})) : void 0;
|
|
9876
|
+
}
|
|
9877
|
+
function mcpAuthor(identity) {
|
|
9878
|
+
return identity?.fullName ?? identity?.slackUserName ?? identity?.email;
|
|
9879
|
+
}
|
|
9880
|
+
/** MCP view of one user or assistant Message. */
|
|
9881
|
+
const mcpMessageSchema = z.object({
|
|
9882
|
+
seq: z.number().int().describe("Position in the transcript. markConversationRead takes this value."),
|
|
9883
|
+
messageId: z.string().describe("For a message that you sent, the `messageId` that sendMessage or createConversation returned."),
|
|
9884
|
+
createdAt: z.string(),
|
|
9885
|
+
role: z.enum(["assistant", "user"]),
|
|
9886
|
+
author: z.string().optional(),
|
|
9887
|
+
text: z.string(),
|
|
9888
|
+
attachments: mcpAttachmentsSchema
|
|
9889
|
+
}).strict();
|
|
9890
|
+
/**
|
|
9891
|
+
* Keep the user and assistant Messages of a report event page, in order.
|
|
9892
|
+
* System Messages and Messages with no text or attachment are left out.
|
|
9893
|
+
*/
|
|
9894
|
+
function mcpMessages(events) {
|
|
9895
|
+
return events.flatMap((event) => {
|
|
9896
|
+
const data = event.data;
|
|
9897
|
+
if (data.type !== "message" || data.role === "system") return [];
|
|
9898
|
+
const text = data.text ?? "";
|
|
9899
|
+
const attachments = mcpAttachments(data.attachments);
|
|
9900
|
+
if (!text && !attachments) return [];
|
|
9901
|
+
const author = mcpAuthor(data.actorIdentity);
|
|
9902
|
+
return [{
|
|
9903
|
+
seq: event.seq,
|
|
9904
|
+
messageId: data.messageId,
|
|
9905
|
+
createdAt: event.createdAt,
|
|
9906
|
+
role: data.role,
|
|
9907
|
+
...author ? { author } : void 0,
|
|
9908
|
+
text,
|
|
9909
|
+
...attachments ? { attachments } : void 0
|
|
9910
|
+
}];
|
|
9911
|
+
});
|
|
9912
|
+
}
|
|
9913
|
+
/** Message text param shared by the tools that send a message. */
|
|
9914
|
+
const mcpMessageTextSchema = z.string().trim().min(1).max(32e3).describe("Message text.");
|
|
9915
|
+
/**
|
|
9916
|
+
* Idempotency key param shared by the tools that send a message. A retry
|
|
9917
|
+
* with the same key sends nothing new.
|
|
9918
|
+
*/
|
|
9919
|
+
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.");
|
|
9920
|
+
/**
|
|
9921
|
+
* MCP view of one accepted user Message that no Turn has read yet. It is not
|
|
9922
|
+
* in the transcript, so it has no `seq`.
|
|
9923
|
+
*/
|
|
9924
|
+
const mcpPendingMessageSchema = z.object({
|
|
9925
|
+
messageId: z.string(),
|
|
9926
|
+
createdAt: z.string(),
|
|
9927
|
+
author: z.string().optional(),
|
|
9928
|
+
text: z.string(),
|
|
9929
|
+
attachments: mcpAttachmentsSchema,
|
|
9930
|
+
delivery: conversationPendingMessageDeliverySchema.describe("`defer` waits for the running turn to end. `interrupt` joins the running turn at its next safe step.")
|
|
9931
|
+
}).strict();
|
|
9932
|
+
/** Pending Messages field shared by `getConversation` and the send tools. */
|
|
9933
|
+
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.");
|
|
9934
|
+
/** Authorization that a parked Turn waits for. */
|
|
9935
|
+
const mcpAuthorizationSchema = z.object({
|
|
9936
|
+
label: z.string(),
|
|
9937
|
+
url: z.string()
|
|
9938
|
+
}).strict().describe("Set when a turn waits for you to connect an account. Open `url` in a browser to continue.");
|
|
9939
|
+
/**
|
|
9940
|
+
* Read the Messages that wait for a Turn and the authorization that a parked
|
|
9941
|
+
* Turn waits for. The caller must check that `user` is a participant.
|
|
9942
|
+
*/
|
|
9943
|
+
async function readMcpPendingWork(user, conversationId) {
|
|
9944
|
+
const report = await readConversationPendingMessages(conversationId, { viewer: user });
|
|
9945
|
+
const pendingMessages = (report?.messages ?? []).flatMap((message) => {
|
|
9946
|
+
if (message.text === void 0) return [];
|
|
9947
|
+
const author = mcpAuthor(message.actorIdentity);
|
|
9948
|
+
const attachments = mcpAttachments(message.attachments);
|
|
9949
|
+
return [{
|
|
9950
|
+
messageId: message.messageId,
|
|
9951
|
+
createdAt: message.createdAt,
|
|
9952
|
+
...author ? { author } : void 0,
|
|
9953
|
+
text: message.text,
|
|
9954
|
+
...attachments ? { attachments } : void 0,
|
|
9955
|
+
delivery: message.delivery
|
|
9956
|
+
}];
|
|
9957
|
+
});
|
|
9958
|
+
const authorization = report?.authorization;
|
|
9959
|
+
return {
|
|
9960
|
+
pendingMessages,
|
|
9961
|
+
...authorization ? { authorization: {
|
|
9962
|
+
label: authorization.label,
|
|
9963
|
+
url: authorization.authorizationUrl
|
|
9964
|
+
} } : void 0
|
|
9965
|
+
};
|
|
9966
|
+
}
|
|
9967
|
+
/**
|
|
9968
|
+
* Read pending work for a send result. The message already landed, so a
|
|
9969
|
+
* failed read drops these optional fields instead of turning the accepted
|
|
9970
|
+
* send into a tool error that a client may retry.
|
|
9971
|
+
*/
|
|
9972
|
+
async function readMcpPendingWorkAfterSend(user, conversationId) {
|
|
9973
|
+
try {
|
|
9974
|
+
return await readMcpPendingWork(user, conversationId);
|
|
9975
|
+
} catch (error) {
|
|
9976
|
+
logException(error, "mcp.pending_work.read.failed", { "gen_ai.conversation.id": conversationId });
|
|
9977
|
+
return {};
|
|
9978
|
+
}
|
|
9979
|
+
}
|
|
9980
|
+
/** `cursor` result field shared by getConversation and the send tools. */
|
|
9981
|
+
const mcpCursorSchema = z.string().describe("Pass as `after` to getConversation to read the messages that come after this point.");
|
|
9982
|
+
/** Result of a tool that sends a message. */
|
|
9983
|
+
const mcpAcceptedMessageSchema = {
|
|
9984
|
+
conversationId: z.string(),
|
|
9985
|
+
messageId: z.string().describe("Id of your message in `pendingMessages`, and later in the transcript."),
|
|
9986
|
+
status: z.enum(["accepted", "duplicate"]).describe("`duplicate` when the idempotency key was already used."),
|
|
9987
|
+
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."),
|
|
9988
|
+
authorization: mcpAuthorizationSchema.optional(),
|
|
9989
|
+
cursor: mcpCursorSchema,
|
|
9990
|
+
url: z.string().optional().describe("Dashboard link.")
|
|
9991
|
+
};
|
|
9992
|
+
// src/api/operation.ts
|
|
9993
|
+
/** Define an operation and keep its input and output types. */
|
|
9994
|
+
function defineApiOperation(operation) {
|
|
9995
|
+
return operation;
|
|
9996
|
+
}
|
|
9997
|
+
async function readJsonBody(context) {
|
|
9998
|
+
const text = await context.req.text();
|
|
9999
|
+
if (!text) return {};
|
|
10000
|
+
try {
|
|
10001
|
+
return JSON.parse(text);
|
|
10002
|
+
} catch (error) {
|
|
10003
|
+
throwApiError(400, "Invalid request body.", error);
|
|
10004
|
+
}
|
|
10005
|
+
}
|
|
10006
|
+
/**
|
|
10007
|
+
* Serve an operation as a REST handler after `requireViewer`. Route params
|
|
10008
|
+
* win over body fields of the same name.
|
|
10009
|
+
*/
|
|
10010
|
+
function apiOperationHandler(operation, services) {
|
|
10011
|
+
return async (context) => {
|
|
10012
|
+
const body = await readJsonBody(context);
|
|
10013
|
+
const input = operation.input.safeParse(typeof body === "object" && body !== null && !Array.isArray(body) ? {
|
|
10014
|
+
...body,
|
|
10015
|
+
...context.req.param()
|
|
10016
|
+
} : body);
|
|
10017
|
+
if (!input.success) throwApiError(400, "Invalid request body.", input.error);
|
|
10018
|
+
return jsonResponse(operation.output, await operation.run(context.get("viewer"), input.data, services));
|
|
10019
|
+
};
|
|
10020
|
+
}
|
|
9152
10021
|
// src/api/conversations/cancel-pending-messages.ts
|
|
9153
10022
|
/** Cancel accepted human-facing mailbox rows for one conversation participant. */
|
|
9154
10023
|
async function cancelConversationPendingMessagesForViewer(viewer, conversationId, body = {}) {
|
|
9155
10024
|
if (!await getConversationStore().get({ conversationId })) throwApiError(404, "Conversation not found.");
|
|
9156
|
-
if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(
|
|
10025
|
+
if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(404, "Conversation not found.");
|
|
9157
10026
|
try {
|
|
9158
10027
|
const result = await cancelHumanFacingPendingMessages({
|
|
9159
10028
|
conversationId,
|
|
@@ -9174,6 +10043,243 @@ async function cancelConversationPendingMessagesForViewer(viewer, conversationId
|
|
|
9174
10043
|
throwApiError(500, "Unable to cancel queued messages.", error);
|
|
9175
10044
|
}
|
|
9176
10045
|
}
|
|
10046
|
+
// src/api/conversations/pin.ts
|
|
10047
|
+
/**
|
|
10048
|
+
* Pin or unpin one conversation for the signed-in viewer.
|
|
10049
|
+
*
|
|
10050
|
+
* A pin lives on the viewer's participant row, and that row grants send and
|
|
10051
|
+
* control access. So only a participant can pin, the same as archive. A pin
|
|
10052
|
+
* also restores an archived conversation for everyone, because the Pinned
|
|
10053
|
+
* section shows only active conversations. A pin on a child would be a fact
|
|
10054
|
+
* of the child, not of the viewer's root, and no list shows child pins yet,
|
|
10055
|
+
* so only a root can be pinned.
|
|
10056
|
+
*/
|
|
10057
|
+
async function pinConversation(viewer, conversationId, body) {
|
|
10058
|
+
if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(404, "Conversation not found.");
|
|
10059
|
+
const executor = getSqlExecutor();
|
|
10060
|
+
return await executor.transaction(async () => {
|
|
10061
|
+
const db = executor.db();
|
|
10062
|
+
const result = await setPin(db, viewer, conversationId, body.pinned);
|
|
10063
|
+
recordPinUsage(body.pinned ? "pin" : "unpin", await countViewerPins(db, viewer));
|
|
10064
|
+
return result;
|
|
10065
|
+
});
|
|
10066
|
+
}
|
|
10067
|
+
/**
|
|
10068
|
+
* Tag the request span with a pin change and the viewer's pin count after
|
|
10069
|
+
* it. Pins stay manual; this shows how much people use them.
|
|
10070
|
+
*/
|
|
10071
|
+
function recordPinUsage(action, pinnedCount) {
|
|
10072
|
+
setSpanAttributes({
|
|
10073
|
+
"app.conversation.pin.action": action,
|
|
10074
|
+
"app.conversation.pin.count": pinnedCount
|
|
10075
|
+
});
|
|
10076
|
+
}
|
|
10077
|
+
async function countViewerPins(db, viewer) {
|
|
10078
|
+
const [row] = await db.select({ pins: count() }).from(juniorConversationParticipants).where(and(eq(juniorConversationParticipants.userId, viewer.id), isNotNull(juniorConversationParticipants.pinnedAt)));
|
|
10079
|
+
return row?.pins ?? 0;
|
|
10080
|
+
}
|
|
10081
|
+
async function setPin(db, viewer, conversationId, pinned) {
|
|
10082
|
+
const [conversation] = await db.select({
|
|
10083
|
+
archivedAt: juniorConversations.archivedAt,
|
|
10084
|
+
kind: juniorConversations.kind,
|
|
10085
|
+
lastActivityAt: juniorConversations.lastActivityAt,
|
|
10086
|
+
parentConversationId: juniorConversations.parentConversationId,
|
|
10087
|
+
rootConversationId: juniorConversations.rootConversationId
|
|
10088
|
+
}).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId)).limit(1).for("no key update");
|
|
10089
|
+
if (!conversation) throwApiError(404, "Conversation not found.");
|
|
10090
|
+
if (!isTopLevelKind(conversationKindFromRow(conversation))) throwApiError(409, `A child conversation cannot be pinned or unpinned. It uses its root's pin: ${conversation.rootConversationId ?? conversation.parentConversationId}.`);
|
|
10091
|
+
if (!pinned) {
|
|
10092
|
+
await db.update(juniorConversationParticipants).set({
|
|
10093
|
+
pinnedAt: null,
|
|
10094
|
+
pinPosition: null
|
|
10095
|
+
}).where(and(eq(juniorConversationParticipants.userId, viewer.id), eq(juniorConversationParticipants.rootConversationId, conversationId)));
|
|
10096
|
+
return { pinnedAt: null };
|
|
10097
|
+
}
|
|
10098
|
+
if (conversation.archivedAt) await setArchivedAt(db, [conversationId], null);
|
|
10099
|
+
const pinnedAt = /* @__PURE__ */ new Date();
|
|
10100
|
+
await db.insert(juniorConversationParticipants).values({
|
|
10101
|
+
lastMessageAt: conversation.lastActivityAt,
|
|
10102
|
+
pinnedAt,
|
|
10103
|
+
rootConversationId: conversationId,
|
|
10104
|
+
userId: viewer.id
|
|
10105
|
+
}).onConflictDoUpdate({
|
|
10106
|
+
target: [juniorConversationParticipants.userId, juniorConversationParticipants.rootConversationId],
|
|
10107
|
+
set: {
|
|
10108
|
+
pinnedAt,
|
|
10109
|
+
pinPosition: null,
|
|
10110
|
+
unsubscribedAt: null
|
|
10111
|
+
}
|
|
10112
|
+
});
|
|
10113
|
+
return { pinnedAt: pinnedAt.toISOString() };
|
|
10114
|
+
}
|
|
10115
|
+
/**
|
|
10116
|
+
* Save the viewer's Pinned order. Each listed pin takes its index as its
|
|
10117
|
+
* place. The update reads only the viewer's own pinned rows, so an id that
|
|
10118
|
+
* the viewer did not pin changes nothing and grants nothing.
|
|
10119
|
+
*/
|
|
10120
|
+
async function reorderPinnedConversations(viewer, body) {
|
|
10121
|
+
const ids = body.conversationIds;
|
|
10122
|
+
const participants = juniorConversationParticipants;
|
|
10123
|
+
const positions = sql.join(ids.map((id, index) => sql`when ${id} then ${index}::integer`), sql` `);
|
|
10124
|
+
const updated = await getDb().update(participants).set({ pinPosition: sql`case ${participants.rootConversationId} ${positions} else ${participants.pinPosition} + ${ids.length}::integer end` }).where(and(eq(participants.userId, viewer.id), isNotNull(participants.pinnedAt))).returning({ rootConversationId: participants.rootConversationId });
|
|
10125
|
+
recordPinUsage("reorder", updated.length);
|
|
10126
|
+
const updatedIds = new Set(updated.map((row) => row.rootConversationId));
|
|
10127
|
+
return { conversationIds: ids.filter((id) => updatedIds.has(id)) };
|
|
10128
|
+
}
|
|
10129
|
+
// src/api/conversations/stop.ts
|
|
10130
|
+
/**
|
|
10131
|
+
* Stop one Conversation for a participant: its active Turn, its session, and
|
|
10132
|
+
* every child agent below it.
|
|
10133
|
+
*
|
|
10134
|
+
* The stop also removes the human messages queued before it. The viewer's own
|
|
10135
|
+
* web text comes back in the response so the dashboard can restore it to the
|
|
10136
|
+
* composer instead of losing it.
|
|
10137
|
+
*/
|
|
10138
|
+
async function stopConversationTurnForViewer(viewer, conversationId, services) {
|
|
10139
|
+
const conversationStore = getConversationStore();
|
|
10140
|
+
if (!await conversationStore.get({ conversationId })) throwApiError(404, "Conversation not found.");
|
|
10141
|
+
if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(404, "Conversation not found.");
|
|
10142
|
+
try {
|
|
10143
|
+
const result = await stopConversation({
|
|
10144
|
+
conversationId,
|
|
10145
|
+
conversationStore,
|
|
10146
|
+
queue: services.queue
|
|
10147
|
+
});
|
|
10148
|
+
if (result.status !== "requested") return {
|
|
10149
|
+
conversationId,
|
|
10150
|
+
status: "no_work",
|
|
10151
|
+
stoppedInboundMessageIds: [],
|
|
10152
|
+
stoppedMessages: []
|
|
10153
|
+
};
|
|
10154
|
+
await clearSlackPendingReactions({
|
|
10155
|
+
getSlackAdapter: getProductionSlackAdapter,
|
|
10156
|
+
messages: result.pendingMessages
|
|
10157
|
+
});
|
|
10158
|
+
return {
|
|
10159
|
+
conversationId,
|
|
10160
|
+
status: "requested",
|
|
10161
|
+
stoppedInboundMessageIds: result.pendingMessages.map((message) => message.inboundMessageId),
|
|
10162
|
+
stoppedMessages: viewerWebMessages(result.pendingMessages, viewer)
|
|
10163
|
+
};
|
|
10164
|
+
} catch (error) {
|
|
10165
|
+
throwApiError(500, "Unable to stop the active turn.", error);
|
|
10166
|
+
}
|
|
10167
|
+
}
|
|
10168
|
+
function viewerWebMessages(messages, viewer) {
|
|
10169
|
+
const viewerUserIds = webActorUserIds(viewer);
|
|
10170
|
+
return messages.flatMap((message) => {
|
|
10171
|
+
if (message.source !== "web") return [];
|
|
10172
|
+
const metadata = legacyWebMailboxMetadataSchema.safeParse(message.input.metadata);
|
|
10173
|
+
if (!metadata.success) return [];
|
|
10174
|
+
if (!viewerUserIds.includes(metadata.data.authorUserId)) return [];
|
|
10175
|
+
const text = message.input.text.trim();
|
|
10176
|
+
return text ? [{
|
|
10177
|
+
inboundMessageId: message.inboundMessageId,
|
|
10178
|
+
text
|
|
10179
|
+
}] : [];
|
|
10180
|
+
});
|
|
10181
|
+
}
|
|
10182
|
+
// src/api/conversations/operations.ts
|
|
10183
|
+
/** Own the Conversation operations that the REST API and MCP share. */
|
|
10184
|
+
const conversationIdInput = { conversationId: mcpConversationIdSchema };
|
|
10185
|
+
const writeAnnotations = {
|
|
10186
|
+
destructiveHint: false,
|
|
10187
|
+
idempotentHint: true,
|
|
10188
|
+
readOnlyHint: false
|
|
10189
|
+
};
|
|
10190
|
+
/** Archive or restore one Conversation, and optionally its children. */
|
|
10191
|
+
const archiveConversationOperation = defineApiOperation({
|
|
10192
|
+
name: "archiveConversation",
|
|
10193
|
+
title: "Archive conversation",
|
|
10194
|
+
description: "Archive one of your conversations, or restore it, for everyone in it. Archiving a conversation hides it and its child conversations. A restore fails while a conversation above it is archived. A new message from a person restores the conversation and the archived conversations above it.",
|
|
10195
|
+
scope: "conversations:manage",
|
|
10196
|
+
input: archiveConversationBodySchema.extend(conversationIdInput),
|
|
10197
|
+
output: archiveConversationResponseSchema,
|
|
10198
|
+
annotations: writeAnnotations,
|
|
10199
|
+
run: (viewer, { conversationId, ...body }) => archiveConversation(viewer, conversationId, body)
|
|
10200
|
+
});
|
|
10201
|
+
/** Archive every done Conversation of the viewer once. */
|
|
10202
|
+
const archiveDoneConversationsOperation = defineApiOperation({
|
|
10203
|
+
name: "archiveDoneConversations",
|
|
10204
|
+
title: "Archive done conversations",
|
|
10205
|
+
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.",
|
|
10206
|
+
scope: "conversations:manage",
|
|
10207
|
+
input: z.object({}).strict(),
|
|
10208
|
+
output: archiveDoneConversationsResponseSchema,
|
|
10209
|
+
annotations: writeAnnotations,
|
|
10210
|
+
run: (viewer) => archiveViewerDoneConversations(viewer)
|
|
10211
|
+
});
|
|
10212
|
+
/** Pin or unpin one top-level Conversation for the viewer. */
|
|
10213
|
+
const pinConversationOperation = defineApiOperation({
|
|
10214
|
+
name: "pinConversation",
|
|
10215
|
+
title: "Pin conversation",
|
|
10216
|
+
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.",
|
|
10217
|
+
scope: "conversations:manage",
|
|
10218
|
+
input: pinConversationBodySchema.extend(conversationIdInput),
|
|
10219
|
+
output: pinConversationResponseSchema,
|
|
10220
|
+
annotations: writeAnnotations,
|
|
10221
|
+
run: (viewer, { conversationId, ...body }) => pinConversation(viewer, conversationId, body)
|
|
10222
|
+
});
|
|
10223
|
+
/** Override the viewer's auto-archive default for one Conversation. */
|
|
10224
|
+
const setConversationAutoArchiveOperation = defineApiOperation({
|
|
10225
|
+
name: "setConversationAutoArchive",
|
|
10226
|
+
title: "Set conversation auto-archive",
|
|
10227
|
+
description: "Turn auto-archive on or off for one of your conversations. This overrides your default for that conversation only.",
|
|
10228
|
+
scope: "conversations:manage",
|
|
10229
|
+
input: conversationAutoArchiveSchema.extend(conversationIdInput),
|
|
10230
|
+
output: conversationAutoArchiveSchema,
|
|
10231
|
+
annotations: writeAnnotations,
|
|
10232
|
+
run: (viewer, { autoArchive, conversationId }) => setConversationAutoArchive(viewer, conversationId, autoArchive)
|
|
10233
|
+
});
|
|
10234
|
+
/** Subscribe or unsubscribe the viewer. It never changes another person. */
|
|
10235
|
+
const setConversationSubscriptionOperation = defineApiOperation({
|
|
10236
|
+
name: "setConversationSubscription",
|
|
10237
|
+
title: "Set conversation subscription",
|
|
10238
|
+
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.",
|
|
10239
|
+
scope: "conversations:manage",
|
|
10240
|
+
input: conversationSubscriptionBodySchema.extend(conversationIdInput),
|
|
10241
|
+
output: conversationSubscriptionResponseSchema,
|
|
10242
|
+
annotations: writeAnnotations,
|
|
10243
|
+
run: (viewer, { conversationId, ...body }) => setConversationSubscription(viewer, conversationId, body)
|
|
10244
|
+
});
|
|
10245
|
+
/** Stop the running Turn and every child agent below it. */
|
|
10246
|
+
const stopConversationOperation = defineApiOperation({
|
|
10247
|
+
name: "stopConversation",
|
|
10248
|
+
title: "Stop conversation",
|
|
10249
|
+
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.",
|
|
10250
|
+
scope: "conversations:manage",
|
|
10251
|
+
input: z.object(conversationIdInput).strict(),
|
|
10252
|
+
output: stopConversationTurnResponseSchema,
|
|
10253
|
+
annotations: {
|
|
10254
|
+
...writeAnnotations,
|
|
10255
|
+
destructiveHint: true
|
|
10256
|
+
},
|
|
10257
|
+
run: (viewer, { conversationId }, services) => stopConversationTurnForViewer(viewer, conversationId, services)
|
|
10258
|
+
});
|
|
10259
|
+
/** Drop the messages that wait for the running Turn. The Turn continues. */
|
|
10260
|
+
const cancelQueuedMessagesOperation = defineApiOperation({
|
|
10261
|
+
name: "cancelQueuedMessages",
|
|
10262
|
+
title: "Cancel queued messages",
|
|
10263
|
+
description: "Drop the messages that wait for the running turn of one of your conversations. Without a filter, it drops every one. The running turn continues.",
|
|
10264
|
+
scope: "conversations:manage",
|
|
10265
|
+
input: cancelConversationPendingMessagesBodySchema.extend(conversationIdInput),
|
|
10266
|
+
output: cancelConversationPendingMessagesResponseSchema,
|
|
10267
|
+
annotations: {
|
|
10268
|
+
...writeAnnotations,
|
|
10269
|
+
destructiveHint: true
|
|
10270
|
+
},
|
|
10271
|
+
run: (viewer, { conversationId, ...body }) => cancelConversationPendingMessagesForViewer(viewer, conversationId, body)
|
|
10272
|
+
});
|
|
10273
|
+
/** Every Conversation operation, for the MCP server. */
|
|
10274
|
+
const conversationOperations = [
|
|
10275
|
+
cancelQueuedMessagesOperation,
|
|
10276
|
+
archiveConversationOperation,
|
|
10277
|
+
archiveDoneConversationsOperation,
|
|
10278
|
+
pinConversationOperation,
|
|
10279
|
+
setConversationAutoArchiveOperation,
|
|
10280
|
+
setConversationSubscriptionOperation,
|
|
10281
|
+
stopConversationOperation
|
|
10282
|
+
];
|
|
9177
10283
|
// src/api/conversations/cursor.ts
|
|
9178
10284
|
const CURSOR_CONTEXT = "junior-conversation-report-cursor";
|
|
9179
10285
|
const conversationCursorPayloadSchema = z.object({
|
|
@@ -9279,8 +10385,8 @@ async function createConversationForViewer(viewer, body, services) {
|
|
|
9279
10385
|
throwApiError(500, "Unable to create conversation.", error);
|
|
9280
10386
|
}
|
|
9281
10387
|
}
|
|
9282
|
-
/** Append one
|
|
9283
|
-
async function appendConversationMessageForViewer(viewer, conversationId, body, services) {
|
|
10388
|
+
/** Append one viewer message to an existing conversation. */
|
|
10389
|
+
async function appendConversationMessageForViewer(viewer, conversationId, body, services, delivery) {
|
|
9284
10390
|
await requireWebMessageConversation(viewer, conversationId, body.idempotencyKey);
|
|
9285
10391
|
const uploads = await verifyUploads({
|
|
9286
10392
|
conversationId,
|
|
@@ -9291,6 +10397,7 @@ async function appendConversationMessageForViewer(viewer, conversationId, body,
|
|
|
9291
10397
|
const append = () => appendAndEnqueueWebMessage({
|
|
9292
10398
|
actor,
|
|
9293
10399
|
conversationId,
|
|
10400
|
+
delivery,
|
|
9294
10401
|
idempotencyKey: body.idempotencyKey,
|
|
9295
10402
|
message: body.message,
|
|
9296
10403
|
uploads
|
|
@@ -9299,11 +10406,11 @@ async function appendConversationMessageForViewer(viewer, conversationId, body,
|
|
|
9299
10406
|
attachmentStorage: services.attachmentStorage,
|
|
9300
10407
|
queue: services.queue
|
|
9301
10408
|
});
|
|
9302
|
-
const closeAnswered = () =>
|
|
10409
|
+
const closeAnswered = () => closeInboxItemsAnsweredByReply({
|
|
9303
10410
|
conversationId,
|
|
9304
10411
|
delivery: {
|
|
9305
10412
|
queue: services.queue,
|
|
9306
|
-
show:
|
|
10413
|
+
show: createSlackInboxItemShow(getProductionSlackAdapter)
|
|
9307
10414
|
},
|
|
9308
10415
|
resolveUser: async () => viewer,
|
|
9309
10416
|
text: body.message
|
|
@@ -9856,7 +10963,8 @@ async function readConversationAgentTree(conversation, readAccess) {
|
|
|
9856
10963
|
if (lineage.length < 2) return;
|
|
9857
10964
|
const ids = lineage.map((entry) => entry.conversationId);
|
|
9858
10965
|
const kindById = new Map(lineage.map((entry) => [entry.conversationId, entry.kind]));
|
|
9859
|
-
const
|
|
10966
|
+
const rootRecord = lineage[0].parentConversationId ? void 0 : await readConversationRecordFromSql(ids[0]);
|
|
10967
|
+
const root = rootRecord?.conversation;
|
|
9860
10968
|
const [access, automationTitleByConversation, firstHumanMessageTextByConversation] = await Promise.all([
|
|
9861
10969
|
readAccess(ids),
|
|
9862
10970
|
readAutomationTitlesByConversationId(root ? [root] : []),
|
|
@@ -9864,7 +10972,7 @@ async function readConversationAgentTree(conversation, readAccess) {
|
|
|
9864
10972
|
]);
|
|
9865
10973
|
return await mapBounded(ids, async (id) => {
|
|
9866
10974
|
const itemAccess = access.get(id);
|
|
9867
|
-
if (root?.conversationId === id) return {
|
|
10975
|
+
if (rootRecord && root?.conversationId === id) return {
|
|
9868
10976
|
conversationId: id,
|
|
9869
10977
|
kind: "root",
|
|
9870
10978
|
label: conversationSummaryFromStoredConversation({
|
|
@@ -9872,7 +10980,8 @@ async function readConversationAgentTree(conversation, readAccess) {
|
|
|
9872
10980
|
automationTitle: automationTitleByConversation.get(id),
|
|
9873
10981
|
conversation: root,
|
|
9874
10982
|
durationMs: 0,
|
|
9875
|
-
firstHumanMessageText: firstHumanMessageTextByConversation.get(id)
|
|
10983
|
+
firstHumanMessageText: firstHumanMessageTextByConversation.get(id),
|
|
10984
|
+
status: rootRecord.status
|
|
9876
10985
|
}).displayTitle
|
|
9877
10986
|
};
|
|
9878
10987
|
const kind = kindById.get(id);
|
|
@@ -9954,15 +11063,6 @@ function eventMentionTexts(data) {
|
|
|
9954
11063
|
default: return [];
|
|
9955
11064
|
}
|
|
9956
11065
|
}
|
|
9957
|
-
function briefMentionTexts(brief) {
|
|
9958
|
-
return [
|
|
9959
|
-
brief.summary,
|
|
9960
|
-
brief.intent,
|
|
9961
|
-
brief.outcome.text,
|
|
9962
|
-
...brief.decisions.flatMap((decision) => [decision.text, decision.by]),
|
|
9963
|
-
...brief.facts
|
|
9964
|
-
];
|
|
9965
|
-
}
|
|
9966
11066
|
function withMentions(value, mentions) {
|
|
9967
11067
|
return mentions.length > 0 ? {
|
|
9968
11068
|
...value,
|
|
@@ -9970,7 +11070,7 @@ function withMentions(value, mentions) {
|
|
|
9970
11070
|
} : value;
|
|
9971
11071
|
}
|
|
9972
11072
|
/**
|
|
9973
|
-
* Attach the people that each event and the
|
|
11073
|
+
* Attach the people that each event and the summary of one conversation
|
|
9974
11074
|
* mention, resolved at read time.
|
|
9975
11075
|
*/
|
|
9976
11076
|
async function attachConversationMentions(executor, conversationId, content) {
|
|
@@ -9979,106 +11079,29 @@ async function attachConversationMentions(executor, conversationId, content) {
|
|
|
9979
11079
|
tenantId,
|
|
9980
11080
|
texts: eventMentionTexts(event.data)
|
|
9981
11081
|
}));
|
|
9982
|
-
if (content.
|
|
11082
|
+
if (content.summary) sources.push({
|
|
9983
11083
|
tenantId,
|
|
9984
|
-
texts:
|
|
11084
|
+
texts: [content.summary]
|
|
9985
11085
|
});
|
|
9986
11086
|
const mentions = await resolveMentions(executor, sources);
|
|
9987
11087
|
return {
|
|
9988
|
-
|
|
9989
|
-
|
|
11088
|
+
events: content.events.map((event, index) => withMentions(event, mentions[index])),
|
|
11089
|
+
summaryMentions: content.summary ? mentions.at(-1) : []
|
|
9990
11090
|
};
|
|
9991
11091
|
}
|
|
9992
|
-
/**
|
|
9993
|
-
|
|
11092
|
+
/**
|
|
11093
|
+
* Attach the people that each activity preview mentions, resolved at read
|
|
11094
|
+
* time. `tenants` holds the Slack workspace of each conversation, which the
|
|
11095
|
+
* feed already read with its rows.
|
|
11096
|
+
*/
|
|
11097
|
+
async function attachActivityPreviewMentions(executor, previews, tenants) {
|
|
9994
11098
|
const entries = [...previews];
|
|
9995
|
-
const tenants = await loadConversationSlackTenantIds(executor, entries.map(([conversationId]) => conversationId));
|
|
9996
11099
|
const mentions = await resolveMentions(executor, entries.map(([conversationId, preview]) => ({
|
|
9997
11100
|
tenantId: tenants.get(conversationId),
|
|
9998
11101
|
texts: [preview.text]
|
|
9999
11102
|
})));
|
|
10000
11103
|
return new Map(entries.map(([conversationId, preview], index) => [conversationId, withMentions(preview, mentions[index])]));
|
|
10001
11104
|
}
|
|
10002
|
-
// src/api/conversations/record.ts
|
|
10003
|
-
/** The columns of one Conversation record, for `selectConversationRecords`. */
|
|
10004
|
-
const conversationRecordColumns = {
|
|
10005
|
-
conversation: juniorConversations,
|
|
10006
|
-
location: juniorDestinations,
|
|
10007
|
-
identityDisplayName: juniorIdentities.displayName,
|
|
10008
|
-
identityEmail: juniorIdentities.email,
|
|
10009
|
-
identityHandle: juniorIdentities.handle,
|
|
10010
|
-
identityProvider: juniorIdentities.provider,
|
|
10011
|
-
identitySubjectId: juniorIdentities.providerSubjectId,
|
|
10012
|
-
identityTenantId: juniorIdentities.providerTenantId,
|
|
10013
|
-
userDisplayName: juniorUsers.displayName
|
|
10014
|
-
};
|
|
10015
|
-
/** Left-join conditions from a Conversation to its record tables. */
|
|
10016
|
-
const conversationRecordJoins = {
|
|
10017
|
-
location: eq(juniorDestinations.id, juniorConversations.destinationId),
|
|
10018
|
-
identity: eq(juniorIdentities.id, juniorConversations.actorIdentityId),
|
|
10019
|
-
user: eq(juniorUsers.id, juniorIdentities.userId)
|
|
10020
|
-
};
|
|
10021
|
-
/**
|
|
10022
|
-
* Select Conversation rows with their Location and Actor names. Callers add
|
|
10023
|
-
* the filter, order, and limit.
|
|
10024
|
-
*/
|
|
10025
|
-
function selectConversationRecords(db) {
|
|
10026
|
-
return db.select(conversationRecordColumns).from(juniorConversations).leftJoin(juniorDestinations, conversationRecordJoins.location).leftJoin(juniorIdentities, conversationRecordJoins.identity).leftJoin(juniorUsers, conversationRecordJoins.user);
|
|
10027
|
-
}
|
|
10028
|
-
/** Decode a conversation row with the linked user name and identity-scoped provider fields. */
|
|
10029
|
-
function conversationFromRecordRow(row) {
|
|
10030
|
-
const value = row.conversation;
|
|
10031
|
-
const legacySessionSource = value.sessionSource === null ? void 0 : parseSessionSource(value.sessionSource);
|
|
10032
|
-
if (value.sessionSource !== null && !legacySessionSource) throw new Error("Conversation legacy source_json is invalid");
|
|
10033
|
-
const actorFullName = row.userDisplayName?.trim() ? row.userDisplayName : row.identityDisplayName;
|
|
10034
|
-
const actor = row.identityProvider === "slack" ? {
|
|
10035
|
-
platform: "slack",
|
|
10036
|
-
...row.identityEmail ? { email: row.identityEmail } : void 0,
|
|
10037
|
-
...actorFullName ? { fullName: actorFullName } : void 0,
|
|
10038
|
-
...row.identitySubjectId ? { slackUserId: row.identitySubjectId } : void 0,
|
|
10039
|
-
...row.identityHandle ? { slackUserName: row.identityHandle } : void 0,
|
|
10040
|
-
...row.identityTenantId ? { teamId: row.identityTenantId } : void 0
|
|
10041
|
-
} : void 0;
|
|
10042
|
-
const location = locationFromRow(value.location, row.location, legacySessionSource);
|
|
10043
|
-
return {
|
|
10044
|
-
schemaVersion: 1,
|
|
10045
|
-
conversationId: value.conversationId,
|
|
10046
|
-
createdAtMs: value.createdAt.getTime(),
|
|
10047
|
-
kind: conversationKindFromRow(value),
|
|
10048
|
-
lastActivityAtMs: value.lastActivityAt.getTime(),
|
|
10049
|
-
updatedAtMs: value.updatedAt.getTime(),
|
|
10050
|
-
execution: {
|
|
10051
|
-
status: value.executionStatus,
|
|
10052
|
-
...value.runId ? { runId: value.runId } : void 0,
|
|
10053
|
-
...value.executionUpdatedAt ? { updatedAtMs: value.executionUpdatedAt.getTime() } : void 0
|
|
10054
|
-
},
|
|
10055
|
-
...value.parentConversationId ? { parentConversationId: value.parentConversationId } : void 0,
|
|
10056
|
-
...value.archivedAt ? { archivedAtMs: value.archivedAt.getTime() } : void 0,
|
|
10057
|
-
...actor ? { actor } : void 0,
|
|
10058
|
-
...location ? { location } : void 0,
|
|
10059
|
-
...value.channelName ? { channelName: value.channelName } : void 0,
|
|
10060
|
-
...value.source ? { source: value.source } : void 0,
|
|
10061
|
-
...value.title ? { title: value.title } : void 0,
|
|
10062
|
-
...value.transcriptPurgedAt ? { transcriptPurgedAtMs: value.transcriptPurgedAt.getTime() } : void 0,
|
|
10063
|
-
...value.stoppedAt ? { stoppedAtMs: value.stoppedAt.getTime() } : void 0,
|
|
10064
|
-
...value.deliveryPausedAt ? { deliveryPausedAtMs: value.deliveryPausedAt.getTime() } : void 0
|
|
10065
|
-
};
|
|
10066
|
-
}
|
|
10067
|
-
/** Decode one `selectConversationRecords` row into a Conversation record. */
|
|
10068
|
-
function conversationRecordFromRow(row) {
|
|
10069
|
-
return {
|
|
10070
|
-
conversation: conversationFromRecordRow(row),
|
|
10071
|
-
durationMs: row.conversation.durationMs,
|
|
10072
|
-
...row.location?.visibility === "public" ? { locationId: row.location.id } : void 0,
|
|
10073
|
-
usage: row.conversation.usage,
|
|
10074
|
-
rootConversationId: row.conversation.rootConversationId
|
|
10075
|
-
};
|
|
10076
|
-
}
|
|
10077
|
-
/** Read one normalized conversation record directly from its SQL row. */
|
|
10078
|
-
async function readConversationRecordFromSql(conversationId) {
|
|
10079
|
-
const row = (await selectConversationRecords(getDb()).where(eq(juniorConversations.conversationId, conversationId)).limit(1))[0];
|
|
10080
|
-
return row ? conversationRecordFromRow(row) : void 0;
|
|
10081
|
-
}
|
|
10082
11105
|
// src/api/conversations/event-list.ts
|
|
10083
11106
|
/** Read one bounded page of reporting events before, after, or around a boundary. */
|
|
10084
11107
|
async function readConversationEvents(conversationId, boundary, options = {}) {
|
|
@@ -10102,14 +11125,14 @@ async function readConversationEvents(conversationId, boundary, options = {}) {
|
|
|
10102
11125
|
...pageArgs,
|
|
10103
11126
|
beforeSeq: position.seq
|
|
10104
11127
|
});
|
|
10105
|
-
return
|
|
11128
|
+
return await conversationEventPageReport(getSqlExecutor(), {
|
|
10106
11129
|
conversationId,
|
|
10107
11130
|
eventHistory: conversationEventHistory({
|
|
10108
11131
|
canExposePayload,
|
|
10109
11132
|
...transcriptPurgedAtMs === void 0 ? void 0 : { transcriptPurgedAtMs }
|
|
10110
11133
|
}),
|
|
10111
11134
|
page
|
|
10112
|
-
})
|
|
11135
|
+
});
|
|
10113
11136
|
}
|
|
10114
11137
|
/** Resolve a page boundary to a direction and an event seq. */
|
|
10115
11138
|
async function boundaryPosition(conversationId, boundary) {
|
|
@@ -10237,16 +11260,19 @@ const agentTreeRoot = alias(juniorConversations, "detail_agent_tree_root");
|
|
|
10237
11260
|
function agentTreeRootLabel(db, rootConversationId) {
|
|
10238
11261
|
return db.select({ label: sql`row(${agentTreeRoot.title}, ${agentTreeRoot.channelName})::text` }).from(agentTreeRoot).where(eq(agentTreeRoot.conversationId, rootConversationId));
|
|
10239
11262
|
}
|
|
11263
|
+
const SUBTREE = "detail_subtree";
|
|
10240
11264
|
/**
|
|
10241
|
-
* Sum the detail versions of
|
|
11265
|
+
* Sum the detail versions of each Conversation and its child agents, one
|
|
11266
|
+
* row per Conversation found, in one pass over all their trees. Child
|
|
10242
11267
|
* writes bump only their own row, and the row count changes when a child
|
|
10243
11268
|
* starts, so the parent needs no bump of its own.
|
|
10244
11269
|
*/
|
|
10245
|
-
function
|
|
11270
|
+
function subtreeDetailVersions(conversationIds) {
|
|
10246
11271
|
return getDb().select({
|
|
11272
|
+
conversationId: sql`${conversationSubtreeColumns.scopeConversationId}`.as("conversation_id"),
|
|
10247
11273
|
conversations: sql`count(*)::int`.as("conversations"),
|
|
10248
11274
|
version: sql`coalesce(sum(${juniorConversations.detailVersion}), 0)::text`.as("version")
|
|
10249
|
-
}).from(juniorConversations).innerJoin(conversationSubtree(
|
|
11275
|
+
}).from(juniorConversations).innerJoin(conversationSubtree(conversationIds), eq(conversationSubtreeColumns.conversationId, juniorConversations.conversationId)).groupBy(conversationSubtreeColumns.scopeConversationId).as(SUBTREE);
|
|
10250
11276
|
}
|
|
10251
11277
|
const versionConversation = alias(juniorConversations, "version_conversation");
|
|
10252
11278
|
const versionFork = alias(juniorConversations, "version_fork");
|
|
@@ -10256,7 +11282,8 @@ const versionUser = alias(juniorUsers, "version_user");
|
|
|
10256
11282
|
* Hash the detail state whose writes do not bump `detail_version`: the
|
|
10257
11283
|
* viewer's marks and auto-archive choice on the root, the forks, and the
|
|
10258
11284
|
* matched Slack files. Each part is a lookup by key, so the versions poll
|
|
10259
|
-
* stays one cheap statement.
|
|
11285
|
+
* stays one cheap statement. `conversationId` is the id column of the
|
|
11286
|
+
* outer row.
|
|
10260
11287
|
*/
|
|
10261
11288
|
function viewerStateVersion(db, conversationId, viewerId) {
|
|
10262
11289
|
const root = db.select({ id: sql`coalesce(${versionConversation.rootConversationId}, ${versionConversation.conversationId})` }).from(versionConversation).where(eq(versionConversation.conversationId, conversationId));
|
|
@@ -10271,15 +11298,28 @@ function viewerStateVersion(db, conversationId, viewerId) {
|
|
|
10271
11298
|
))`;
|
|
10272
11299
|
}
|
|
10273
11300
|
/**
|
|
10274
|
-
* Return a query for the change token of
|
|
10275
|
-
* agents, as the viewer sees it,
|
|
10276
|
-
* detail report sends the same token, so the dashboard
|
|
10277
|
-
* detail without asking for the report.
|
|
11301
|
+
* Return a query for the change token of each Conversation and its child
|
|
11302
|
+
* agents, as the viewer sees it, one row per Conversation found. A missing
|
|
11303
|
+
* one has no row. The detail report sends the same token, so the dashboard
|
|
11304
|
+
* can find a stale detail without asking for the report. All ids share
|
|
11305
|
+
* one plan, so a longer list adds no subquery per id.
|
|
11306
|
+
*/
|
|
11307
|
+
function conversationVersionsQuery(db, conversationIds, viewerId) {
|
|
11308
|
+
const subtree = subtreeDetailVersions(conversationIds);
|
|
11309
|
+
const rowConversationId = sql`${sql.identifier(SUBTREE)}.${sql.identifier("conversation_id")}`;
|
|
11310
|
+
const viewerState = viewerId ? viewerStateVersion(db, rowConversationId, viewerId) : sql`null`;
|
|
11311
|
+
return db.select({
|
|
11312
|
+
conversationId: subtree.conversationId,
|
|
11313
|
+
version: sql`concat_ws(':', ${subtree.conversations}, ${subtree.version}, ${viewerState})`.as("version")
|
|
11314
|
+
}).from(subtree);
|
|
11315
|
+
}
|
|
11316
|
+
/**
|
|
11317
|
+
* Return a query for the `conversationVersionsQuery` token of one
|
|
11318
|
+
* Conversation, or a null token when it is missing.
|
|
10278
11319
|
*/
|
|
10279
11320
|
function conversationVersionQuery(db, conversationId, viewerId) {
|
|
10280
|
-
const
|
|
10281
|
-
|
|
10282
|
-
return db.select({ version: sql`case when ${subtree.conversations} = 0 then null else concat_ws(':', ${subtree.conversations}, ${subtree.version}, ${viewerState}) end` }).from(subtree);
|
|
11321
|
+
const versions = conversationVersionsQuery(db, [conversationId], viewerId).as("detail_token");
|
|
11322
|
+
return db.select({ version: versions.version }).from(versions);
|
|
10283
11323
|
}
|
|
10284
11324
|
/**
|
|
10285
11325
|
* Read the record and the stored rows that the detail state needs in one
|
|
@@ -10295,7 +11335,7 @@ async function readDetailStateRow(conversationId, viewer) {
|
|
|
10295
11335
|
const forkIds = db.select({ conversationId: fork.conversationId }).from(fork).where(and(eq(fork.forkedFromConversationId, conversationId), isNull(fork.quickQuestionAt))).orderBy(asc(fork.createdAt)).limit(50);
|
|
10296
11336
|
const viewerParticipant = viewer ? and(eq(juniorConversationParticipants.userId, viewer.id), eq(juniorConversationParticipants.rootConversationId, rootConversationId)) : sql`false`;
|
|
10297
11337
|
const [row] = await db.select({
|
|
10298
|
-
...conversationRecordColumns,
|
|
11338
|
+
...conversationRecordColumns(),
|
|
10299
11339
|
agentTreeRootLabel: sql`case when ${juniorConversations.parentConversationId} is null then null else (${agentTreeRootLabel(db, rootConversationId)}) end`,
|
|
10300
11340
|
attachmentsVersion: sql`(${slackAttachmentsVersionQuery(db, conversationId)})`,
|
|
10301
11341
|
autoArchive: juniorConversationParticipants.autoArchive,
|
|
@@ -10698,6 +11738,63 @@ function objectPreviewImages(annotation) {
|
|
|
10698
11738
|
};
|
|
10699
11739
|
});
|
|
10700
11740
|
}
|
|
11741
|
+
// src/api/conversations/tree-state.ts
|
|
11742
|
+
/**
|
|
11743
|
+
* The most Conversations of one tree whose Watches a read checks, newest
|
|
11744
|
+
* activity first. A tree with more children than this can miss a Watch on
|
|
11745
|
+
* an old child.
|
|
11746
|
+
*/
|
|
11747
|
+
const WATCH_LOOKUP_LIMIT = 50;
|
|
11748
|
+
/**
|
|
11749
|
+
* SQL: the Conversation needs input from this User. An open action Review
|
|
11750
|
+
* item that it added is assigned to the User, to Everyone, or to no one, or
|
|
11751
|
+
* a Turn waits on the User to sign in.
|
|
11752
|
+
*/
|
|
11753
|
+
function needsUserSql(userId) {
|
|
11754
|
+
return sql`(exists (select 1 from ${juniorInboxItems} where ${and(inboxItemOwnedByConversation(juniorConversations.conversationId), inboxItemNeedsInput(), inboxItemForUser(userId))}) or ${awaitsAuthorizationFrom(juniorConversations.conversationId, userId)})`;
|
|
11755
|
+
}
|
|
11756
|
+
/**
|
|
11757
|
+
* Read the tree state of each Conversation for one viewer, over the
|
|
11758
|
+
* Conversation and every child Conversation at any depth. When more than
|
|
11759
|
+
* one applies:
|
|
11760
|
+
*
|
|
11761
|
+
* - `needs_you`: the tree's `needs_input` includes the viewer. A Review
|
|
11762
|
+
* item or a sign-in wait anywhere in the tree counts. Only the
|
|
11763
|
+
* Conversation's own wait on its starter counts, and only when the
|
|
11764
|
+
* viewer is the starter. Input that waits on another person is not
|
|
11765
|
+
* shown.
|
|
11766
|
+
* - `working`: a Turn is queued or running anywhere in the tree.
|
|
11767
|
+
* - `done`: anything else.
|
|
11768
|
+
*
|
|
11769
|
+
* `watching` is set when a Conversation in the tree that is not stopped has
|
|
11770
|
+
* an active Watch or a pending Timer. It is not part of the shared status.
|
|
11771
|
+
*
|
|
11772
|
+
* An archived child and its descendants count for nothing, since the feed
|
|
11773
|
+
* hides them. Archive takes a child's descendants with it. The
|
|
11774
|
+
* Conversation itself counts even when it is archived.
|
|
11775
|
+
*
|
|
11776
|
+
* Children use the visibility of their root, so a viewer who can see the
|
|
11777
|
+
* row may see its tree state. It shows no child's content.
|
|
11778
|
+
*
|
|
11779
|
+
* One SQL statement reads the trees, then two batched state reads check
|
|
11780
|
+
* Watches and Timers.
|
|
11781
|
+
*/
|
|
11782
|
+
async function readConversationTreeStates(db, conversationIds, viewerUserId) {
|
|
11783
|
+
if (conversationIds.length === 0) return /* @__PURE__ */ new Map();
|
|
11784
|
+
const scopeId = conversationSubtreeColumns.scopeConversationId;
|
|
11785
|
+
const needsViewer = viewerUserId ? sql`bool_or(${needsUserSql(viewerUserId)} or (${eq(juniorConversations.conversationId, scopeId)} and ${conversationWaitsOnUserSql(juniorConversations, viewerUserId)}))` : sql`false`;
|
|
11786
|
+
const rows = await db.select({
|
|
11787
|
+
conversationId: scopeId,
|
|
11788
|
+
needsViewer,
|
|
11789
|
+
working: sql`bool_or(${conversationIsActiveSql(juniorConversations)})`,
|
|
11790
|
+
watchable: sql`(array_agg(${juniorConversations.conversationId} order by ${desc(juniorConversations.lastActivityAt)}) filter (where ${isNull(juniorConversations.stoppedAt)}))[1:${WATCH_LOOKUP_LIMIT}]`
|
|
11791
|
+
}).from(juniorConversations).innerJoin(conversationSubtree(conversationIds), eq(conversationSubtreeColumns.conversationId, juniorConversations.conversationId)).where(or(eq(juniorConversations.conversationId, scopeId), isNull(juniorConversations.archivedAt))).groupBy(scopeId);
|
|
11792
|
+
const watched = await listConversationsWithWatches({ conversationIds: [...new Set(rows.flatMap((row) => row.watchable ?? []))] });
|
|
11793
|
+
return new Map(rows.map((row) => [row.conversationId, {
|
|
11794
|
+
treeState: row.needsViewer ? "needs_you" : row.working ? "working" : "done",
|
|
11795
|
+
watching: (row.watchable ?? []).some((id) => watched.has(id))
|
|
11796
|
+
}]));
|
|
11797
|
+
}
|
|
10701
11798
|
// src/api/conversations/detail.ts
|
|
10702
11799
|
/** Project stored metadata and a bounded event page into a signed history cursor. */
|
|
10703
11800
|
function projectConversationDetail(args) {
|
|
@@ -10718,12 +11815,13 @@ function projectConversationDetail(args) {
|
|
|
10718
11815
|
durationMs: args.durationMs,
|
|
10719
11816
|
firstHumanMessageText: args.firstHumanMessageText,
|
|
10720
11817
|
...args.locationId ? { locationId: args.locationId } : void 0,
|
|
11818
|
+
status: args.status,
|
|
10721
11819
|
...args.teamDomainByTeamId ? { teamDomainByTeamId: args.teamDomainByTeamId } : void 0,
|
|
10722
11820
|
usage: args.usage
|
|
10723
11821
|
}),
|
|
10724
11822
|
annotations: canExposePayload ? args.annotations : [],
|
|
10725
11823
|
sidebarAnnotations: canExposePayload ? args.sidebarAnnotations : void 0,
|
|
10726
|
-
...canExposePayload && args.
|
|
11824
|
+
...canExposePayload && args.summaryMentions ? { summaryMentions: args.summaryMentions } : void 0,
|
|
10727
11825
|
events: args.events,
|
|
10728
11826
|
...args.appended ? { appended: true } : void 0,
|
|
10729
11827
|
...args.appendCursor ? { appendCursor: args.appendCursor } : void 0,
|
|
@@ -10785,7 +11883,7 @@ async function readConversationDetailFromSql(conversationId, options) {
|
|
|
10785
11883
|
limit: options.limit
|
|
10786
11884
|
});
|
|
10787
11885
|
};
|
|
10788
|
-
const [agentTree, annotations, automationTitleByConversation, auxiliaryCostsByConversation,
|
|
11886
|
+
const [agentTree, annotations, automationTitleByConversation, auxiliaryCostsByConversation, firstHumanMessageTextByConversation, modelUsage, metricsByConversation, people, sourceTask, teamDomainByTeamId, treeStateByConversation, page] = await Promise.all([
|
|
10789
11887
|
readConversationAgentTree({
|
|
10790
11888
|
conversationId,
|
|
10791
11889
|
...record.conversation.parentConversationId ? { parentConversationId: record.conversation.parentConversationId } : void 0
|
|
@@ -10799,7 +11897,6 @@ async function readConversationDetailFromSql(conversationId, options) {
|
|
|
10799
11897
|
})),
|
|
10800
11898
|
readAutomationTitlesByConversationId([record.conversation]),
|
|
10801
11899
|
readConversationAuxiliaryCostsFromSql(getDb(), [conversationId]),
|
|
10802
|
-
readLatestConversationBrief(getDb(), conversationId),
|
|
10803
11900
|
readFirstHumanMessageTexts(getDb(), [record.conversation]),
|
|
10804
11901
|
isPurged ? Promise.resolve([]) : readConversationModelUsageFromSql(executor, { conversationId }),
|
|
10805
11902
|
readConversationTreeMetricsFromSql(getDb(), [conversationId]),
|
|
@@ -10809,18 +11906,19 @@ async function readConversationDetailFromSql(conversationId, options) {
|
|
|
10809
11906
|
...options.viewer ? { viewer: options.viewer } : void 0
|
|
10810
11907
|
}),
|
|
10811
11908
|
resolveSlackTeamDomains(record.conversation.location?.provider === "slack" ? [record.conversation.location.teamId] : []),
|
|
11909
|
+
readConversationTreeStates(getDb(), [conversationId], options.viewer?.id),
|
|
10812
11910
|
readPage()
|
|
10813
11911
|
]);
|
|
10814
11912
|
const firstSeq = page.events[0]?.seq;
|
|
10815
11913
|
const unreadAfterSeq = readPosition !== void 0 && page.previousSeq !== void 0 && firstSeq !== void 0 && readPosition.lastReadSeq + 1 < firstSeq ? readPosition.lastReadSeq : void 0;
|
|
10816
|
-
const
|
|
10817
|
-
const [{
|
|
11914
|
+
const summary = canExposePayload ? record.conversation.summary : void 0;
|
|
11915
|
+
const [{ events, summaryMentions }, unreadPage, sidebarAnnotations] = await Promise.all([
|
|
10818
11916
|
startSpan({
|
|
10819
11917
|
name: "Attach conversation mentions",
|
|
10820
11918
|
op: "function"
|
|
10821
11919
|
}, () => attachConversationMentions(executor, conversationId, {
|
|
10822
|
-
|
|
10823
|
-
|
|
11920
|
+
events: page.events.map(formatConversationEventText),
|
|
11921
|
+
...summary ? { summary } : void 0
|
|
10824
11922
|
})),
|
|
10825
11923
|
options.unreadPage && unreadAfterSeq !== void 0 ? readConversationEventPageAround(executor, {
|
|
10826
11924
|
canExposePayload,
|
|
@@ -10853,12 +11951,7 @@ async function readConversationDetailFromSql(conversationId, options) {
|
|
|
10853
11951
|
sidebarAnnotations,
|
|
10854
11952
|
auxiliaryCosts: auxiliaryCosts?.total,
|
|
10855
11953
|
...childAgentTotals ? { childAgentTotals } : void 0,
|
|
10856
|
-
...
|
|
10857
|
-
content: briefVersion.content,
|
|
10858
|
-
...briefMentions.length > 0 ? { mentions: briefMentions } : void 0,
|
|
10859
|
-
updatedAt: briefVersion.createdAt.toISOString(),
|
|
10860
|
-
version: briefVersion.version
|
|
10861
|
-
} } : void 0,
|
|
11954
|
+
...summaryMentions.length > 0 ? { summaryMentions } : void 0,
|
|
10862
11955
|
durationMs: metrics?.durationMs ?? record.durationMs,
|
|
10863
11956
|
events,
|
|
10864
11957
|
firstHumanMessageText: firstHumanMessageTextByConversation.get(conversationId),
|
|
@@ -10866,6 +11959,7 @@ async function readConversationDetailFromSql(conversationId, options) {
|
|
|
10866
11959
|
authors: people.authors,
|
|
10867
11960
|
participants: people.participants,
|
|
10868
11961
|
...sourceTask ? { sourceTask } : void 0,
|
|
11962
|
+
status: record.status,
|
|
10869
11963
|
teamDomainByTeamId,
|
|
10870
11964
|
...page.previousSeq === void 0 ? void 0 : { previousSeq: page.previousSeq },
|
|
10871
11965
|
...readPosition ? { readPosition } : void 0,
|
|
@@ -10880,6 +11974,7 @@ async function readConversationDetailFromSql(conversationId, options) {
|
|
|
10880
11974
|
return {
|
|
10881
11975
|
...report,
|
|
10882
11976
|
...state.forks,
|
|
11977
|
+
...treeStateByConversation.get(conversationId),
|
|
10883
11978
|
...agentTree ? { agentTree } : void 0,
|
|
10884
11979
|
...report.isParticipant && state.autoArchive !== void 0 ? { autoArchive: state.autoArchive } : void 0,
|
|
10885
11980
|
...report.isParticipant && state.subscribed !== void 0 ? { subscribed: state.subscribed } : void 0,
|
|
@@ -10894,110 +11989,29 @@ const DETAIL_LATEST_TURNS = 3;
|
|
|
10894
11989
|
* events hold the latest Turns, up to the default limit.
|
|
10895
11990
|
*/
|
|
10896
11991
|
async function readConversationDetail(conversationId, options = {}) {
|
|
10897
|
-
|
|
11992
|
+
return await readConversationDetailFromSql(conversationId, {
|
|
10898
11993
|
...options,
|
|
10899
11994
|
...options.limit === void 0 ? {
|
|
10900
11995
|
latestTurns: DETAIL_LATEST_TURNS,
|
|
10901
11996
|
limit: 150
|
|
10902
11997
|
} : { limit: options.limit }
|
|
10903
11998
|
});
|
|
10904
|
-
if (!report) return void 0;
|
|
10905
|
-
return startSpan({
|
|
10906
|
-
name: "Validate conversation detail",
|
|
10907
|
-
op: "function"
|
|
10908
|
-
}, () => conversationDetailReportSchema.parse(report));
|
|
10909
|
-
}
|
|
10910
|
-
// src/api/conversations/pin.ts
|
|
10911
|
-
/**
|
|
10912
|
-
* Pin or unpin one conversation for the signed-in viewer.
|
|
10913
|
-
*
|
|
10914
|
-
* A pin lives on the viewer's participant row, and that row grants send and
|
|
10915
|
-
* control access. So only a participant can pin, the same as archive. A pin
|
|
10916
|
-
* also restores an archived conversation for everyone, because the Pinned
|
|
10917
|
-
* section shows only active conversations. A pin on a child would be a fact
|
|
10918
|
-
* of the child, not of the viewer's root, and no list shows child pins yet,
|
|
10919
|
-
* so only a root can be pinned.
|
|
10920
|
-
*/
|
|
10921
|
-
async function pinConversation(viewer, conversationId, body) {
|
|
10922
|
-
if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(404, "Conversation not found.");
|
|
10923
|
-
const executor = getSqlExecutor();
|
|
10924
|
-
return await executor.transaction(async () => {
|
|
10925
|
-
const db = executor.db();
|
|
10926
|
-
const result = await setPin(db, viewer, conversationId, body.pinned);
|
|
10927
|
-
recordPinUsage(body.pinned ? "pin" : "unpin", await countViewerPins(db, viewer));
|
|
10928
|
-
return result;
|
|
10929
|
-
});
|
|
10930
|
-
}
|
|
10931
|
-
/**
|
|
10932
|
-
* Tag the request span with a pin change and the viewer's pin count after
|
|
10933
|
-
* it. Pins stay manual; this shows how much people use them.
|
|
10934
|
-
*/
|
|
10935
|
-
function recordPinUsage(action, pinnedCount) {
|
|
10936
|
-
setSpanAttributes({
|
|
10937
|
-
"app.conversation.pin.action": action,
|
|
10938
|
-
"app.conversation.pin.count": pinnedCount
|
|
10939
|
-
});
|
|
10940
|
-
}
|
|
10941
|
-
async function countViewerPins(db, viewer) {
|
|
10942
|
-
const [row] = await db.select({ pins: count() }).from(juniorConversationParticipants).where(and(eq(juniorConversationParticipants.userId, viewer.id), isNotNull(juniorConversationParticipants.pinnedAt)));
|
|
10943
|
-
return row?.pins ?? 0;
|
|
10944
|
-
}
|
|
10945
|
-
async function setPin(db, viewer, conversationId, pinned) {
|
|
10946
|
-
const [conversation] = await db.select({
|
|
10947
|
-
archivedAt: juniorConversations.archivedAt,
|
|
10948
|
-
kind: juniorConversations.kind,
|
|
10949
|
-
lastActivityAt: juniorConversations.lastActivityAt,
|
|
10950
|
-
parentConversationId: juniorConversations.parentConversationId,
|
|
10951
|
-
rootConversationId: juniorConversations.rootConversationId
|
|
10952
|
-
}).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId)).limit(1).for("no key update");
|
|
10953
|
-
if (!conversation) throwApiError(404, "Conversation not found.");
|
|
10954
|
-
if (!isTopLevelKind(conversationKindFromRow(conversation))) throwApiError(409, `A child conversation cannot be pinned or unpinned. It uses its root's pin: ${conversation.rootConversationId ?? conversation.parentConversationId}.`);
|
|
10955
|
-
if (!pinned) {
|
|
10956
|
-
await db.update(juniorConversationParticipants).set({
|
|
10957
|
-
pinnedAt: null,
|
|
10958
|
-
pinPosition: null
|
|
10959
|
-
}).where(and(eq(juniorConversationParticipants.userId, viewer.id), eq(juniorConversationParticipants.rootConversationId, conversationId)));
|
|
10960
|
-
return { pinnedAt: null };
|
|
10961
|
-
}
|
|
10962
|
-
if (conversation.archivedAt) await setArchivedAt(db, [conversationId], null);
|
|
10963
|
-
const pinnedAt = /* @__PURE__ */ new Date();
|
|
10964
|
-
await db.insert(juniorConversationParticipants).values({
|
|
10965
|
-
lastMessageAt: conversation.lastActivityAt,
|
|
10966
|
-
pinnedAt,
|
|
10967
|
-
rootConversationId: conversationId,
|
|
10968
|
-
userId: viewer.id
|
|
10969
|
-
}).onConflictDoUpdate({
|
|
10970
|
-
target: [juniorConversationParticipants.userId, juniorConversationParticipants.rootConversationId],
|
|
10971
|
-
set: {
|
|
10972
|
-
pinnedAt,
|
|
10973
|
-
pinPosition: null,
|
|
10974
|
-
unsubscribedAt: null
|
|
10975
|
-
}
|
|
10976
|
-
});
|
|
10977
|
-
return { pinnedAt: pinnedAt.toISOString() };
|
|
10978
11999
|
}
|
|
12000
|
+
// src/chat/conversations/sql/listed.ts
|
|
10979
12001
|
/**
|
|
10980
|
-
*
|
|
10981
|
-
*
|
|
10982
|
-
* the viewer did not pin changes nothing and grants nothing.
|
|
12002
|
+
* Match Conversations that are not a Lead. The dashboard home opens the
|
|
12003
|
+
* Lead, so lists leave it out. Older rows have no kind.
|
|
10983
12004
|
*/
|
|
10984
|
-
|
|
10985
|
-
|
|
10986
|
-
const participants = juniorConversationParticipants;
|
|
10987
|
-
const positions = sql.join(ids.map((id, index) => sql`when ${id} then ${index}::integer`), sql` `);
|
|
10988
|
-
const updated = await getDb().update(participants).set({ pinPosition: sql`case ${participants.rootConversationId} ${positions} else ${participants.pinPosition} + ${ids.length}::integer end` }).where(and(eq(participants.userId, viewer.id), isNotNull(participants.pinnedAt))).returning({ rootConversationId: participants.rootConversationId });
|
|
10989
|
-
recordPinUsage("reorder", updated.length);
|
|
10990
|
-
const updatedIds = new Set(updated.map((row) => row.rootConversationId));
|
|
10991
|
-
return { conversationIds: ids.filter((id) => updatedIds.has(id)) };
|
|
12005
|
+
function notLeadConversation() {
|
|
12006
|
+
return or(isNull(juniorConversations.kind), ne(juniorConversations.kind, "lead"));
|
|
10992
12007
|
}
|
|
10993
|
-
// src/chat/conversations/sql/listed.ts
|
|
10994
12008
|
/**
|
|
10995
12009
|
* Match Conversations that lists and searches may show: roots that are not
|
|
10996
|
-
* an unkept Quick question. Each list adds its own access and
|
|
10997
|
-
* Structural root checks, such as retention, do not use this.
|
|
12010
|
+
* an unkept Quick question or a Lead. Each list adds its own access and
|
|
12011
|
+
* scope filters. Structural root checks, such as retention, do not use this.
|
|
10998
12012
|
*/
|
|
10999
12013
|
function listedConversation() {
|
|
11000
|
-
return and(isNull(juniorConversations.parentConversationId), isNull(juniorConversations.quickQuestionAt));
|
|
12014
|
+
return and(isNull(juniorConversations.parentConversationId), isNull(juniorConversations.quickQuestionAt), notLeadConversation());
|
|
11001
12015
|
}
|
|
11002
12016
|
// src/api/conversations/threads.ts
|
|
11003
12017
|
/**
|
|
@@ -11014,24 +12028,34 @@ function findThreadPlacement(threadId, tree, rootIds) {
|
|
|
11014
12028
|
}
|
|
11015
12029
|
}
|
|
11016
12030
|
/**
|
|
11017
|
-
* Read the
|
|
11018
|
-
*
|
|
11019
|
-
*
|
|
11020
|
-
*
|
|
11021
|
-
* access of its root.
|
|
12031
|
+
* Read the stored Threads of the listed roots for the feed, with their
|
|
12032
|
+
* read-time titles. It needs no access, so it can start with the other
|
|
12033
|
+
* feed reads. The caller passes only unarchived roots, so a root archive
|
|
12034
|
+
* hides its tree with no writes to the children.
|
|
11022
12035
|
*/
|
|
11023
|
-
async function
|
|
11024
|
-
if (
|
|
11025
|
-
const
|
|
11026
|
-
|
|
11027
|
-
const [rows, tree] = await Promise.all([selectConversationRecords(db).where(and(inArray(juniorConversations.rootConversationId, rootIdList), eq(juniorConversations.kind, "thread"), isNull(juniorConversations.archivedAt))).orderBy(desc(juniorConversations.lastActivityAt), asc(juniorConversations.conversationId)), readConversationTrees(db, rootIdList)]);
|
|
11028
|
-
if (rows.length === 0) return /* @__PURE__ */ new Map();
|
|
12036
|
+
async function readFeedThreadRecords(db, rootIds) {
|
|
12037
|
+
if (rootIds.length === 0) return void 0;
|
|
12038
|
+
const rows = await selectConversationRecords(db).where(and(inArray(juniorConversations.rootConversationId, rootIds), eq(juniorConversations.kind, "thread"), isNull(juniorConversations.archivedAt))).orderBy(desc(juniorConversations.lastActivityAt), asc(juniorConversations.conversationId));
|
|
12039
|
+
if (rows.length === 0) return void 0;
|
|
11029
12040
|
const threads = rows.map((row) => ({
|
|
11030
12041
|
conversation: conversationFromRecordRow(row),
|
|
11031
12042
|
row
|
|
11032
12043
|
}));
|
|
11033
|
-
|
|
11034
|
-
|
|
12044
|
+
return {
|
|
12045
|
+
firstHumanMessageTexts: await readFirstHumanMessageTexts(db, threads.map(({ conversation }) => conversation)),
|
|
12046
|
+
rootIds: new Set(rootIds),
|
|
12047
|
+
threads
|
|
12048
|
+
};
|
|
12049
|
+
}
|
|
12050
|
+
/**
|
|
12051
|
+
* Nest the shown Threads of `readFeedThreadRecords` under their nearest shown
|
|
12052
|
+
* ancestor. A Thread shows when it and every ancestor have no
|
|
12053
|
+
* `archived_at`. A Thread uses the access of its root. `tree` holds the
|
|
12054
|
+
* trees of at least the listed roots.
|
|
12055
|
+
*/
|
|
12056
|
+
function nestFeedThreads(records, tree, accessByRoot) {
|
|
12057
|
+
if (!records) return /* @__PURE__ */ new Map();
|
|
12058
|
+
const { firstHumanMessageTexts, rootIds, threads } = records;
|
|
11035
12059
|
const childrenByParent = /* @__PURE__ */ new Map();
|
|
11036
12060
|
for (const { conversation, row } of threads) {
|
|
11037
12061
|
const parentId = findThreadPlacement(conversation.conversationId, tree, rootIds);
|
|
@@ -11042,6 +12066,7 @@ async function readFeedThreads(db, roots) {
|
|
|
11042
12066
|
conversation,
|
|
11043
12067
|
durationMs: row.conversation.durationMs,
|
|
11044
12068
|
firstHumanMessageText: firstHumanMessageTexts.get(conversation.conversationId),
|
|
12069
|
+
status: row.status,
|
|
11045
12070
|
...row.conversation.usage ? { usage: row.conversation.usage } : void 0
|
|
11046
12071
|
});
|
|
11047
12072
|
const siblings = childrenByParent.get(parentId) ?? [];
|
|
@@ -11055,9 +12080,9 @@ async function readFeedThreads(db, roots) {
|
|
|
11055
12080
|
threads: nest(children)
|
|
11056
12081
|
} : item;
|
|
11057
12082
|
});
|
|
11058
|
-
return new Map(
|
|
11059
|
-
const children = childrenByParent.get(
|
|
11060
|
-
return children ? [[
|
|
12083
|
+
return new Map([...rootIds].flatMap((rootId) => {
|
|
12084
|
+
const children = childrenByParent.get(rootId);
|
|
12085
|
+
return children ? [[rootId, nest(children)]] : [];
|
|
11061
12086
|
}));
|
|
11062
12087
|
}
|
|
11063
12088
|
// src/api/conversations/priority.ts
|
|
@@ -11096,7 +12121,7 @@ function latestMessage(db, role) {
|
|
|
11096
12121
|
const text = sql`${juniorConversationEvents.payload}->>'text'`;
|
|
11097
12122
|
return db.select({
|
|
11098
12123
|
createdAt: juniorConversationEvents.createdAt,
|
|
11099
|
-
text: text
|
|
12124
|
+
text: sql`left(${text}, ${401})`.as(`${role}_text`)
|
|
11100
12125
|
}).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, juniorConversations.conversationId), eq(juniorConversationEvents.type, "message"), sql`${juniorConversationEvents.payload}->>'role' = ${role}`, isNotNull(sql`nullif(btrim(${text}), '')`))).orderBy(desc(juniorConversationEvents.createdAt), desc(juniorConversationEvents.seq)).limit(1).as(`latest_${role}`);
|
|
11101
12126
|
}
|
|
11102
12127
|
/**
|
|
@@ -11125,39 +12150,16 @@ async function readConversationActivityPreviews(db, conversationIds) {
|
|
|
11125
12150
|
const preview = row.assistantAt && row.assistantText !== null ? {
|
|
11126
12151
|
createdAt: row.assistantAt.toISOString(),
|
|
11127
12152
|
role: "assistant",
|
|
11128
|
-
text: row.assistantText
|
|
12153
|
+
text: activityPreviewText(row.assistantText)
|
|
11129
12154
|
} : row.userAt && row.userText !== null ? {
|
|
11130
12155
|
createdAt: row.userAt.toISOString(),
|
|
11131
12156
|
role: "user",
|
|
11132
|
-
text: row.userText
|
|
12157
|
+
text: activityPreviewText(row.userText)
|
|
11133
12158
|
} : void 0;
|
|
11134
12159
|
if (preview) previews.set(row.conversationId, preview);
|
|
11135
12160
|
}
|
|
11136
12161
|
return previews;
|
|
11137
12162
|
}
|
|
11138
|
-
// src/api/conversations/feed-brief.ts
|
|
11139
|
-
/**
|
|
11140
|
-
* Read the latest Brief version of each Conversation on a feed page, in one
|
|
11141
|
-
* query. A lateral limit reads one row per Conversation from the
|
|
11142
|
-
* (conversation, version) key, so long Brief histories do not slow the feed.
|
|
11143
|
-
* Callers show the result only when the viewer can see private content.
|
|
11144
|
-
*/
|
|
11145
|
-
async function readConversationFeedBriefs(db, conversationIds) {
|
|
11146
|
-
if (conversationIds.length === 0) return /* @__PURE__ */ new Map();
|
|
11147
|
-
const content = juniorConversationBriefs.content;
|
|
11148
|
-
const latest = db.select({
|
|
11149
|
-
intent: sql`${content}->>'intent'`.as("intent"),
|
|
11150
|
-
status: sql`${content}->'outcome'->>'status'`.as("status"),
|
|
11151
|
-
summary: sql`${content}->>'summary'`.as("summary")
|
|
11152
|
-
}).from(juniorConversationBriefs).where(eq(juniorConversationBriefs.conversationId, juniorConversations.conversationId)).orderBy(desc(juniorConversationBriefs.version)).limit(1).as("latest_brief");
|
|
11153
|
-
const rows = await db.select({
|
|
11154
|
-
conversationId: juniorConversations.conversationId,
|
|
11155
|
-
intent: latest.intent,
|
|
11156
|
-
status: latest.status,
|
|
11157
|
-
summary: latest.summary
|
|
11158
|
-
}).from(juniorConversations).innerJoinLateral(latest, sql`true`).where(inArray(juniorConversations.conversationId, conversationIds));
|
|
11159
|
-
return new Map(rows.map(({ conversationId, ...brief }) => [conversationId, conversationFeedBriefSchema.parse(brief)]));
|
|
11160
|
-
}
|
|
11161
12163
|
// src/api/conversations/feed-links.ts
|
|
11162
12164
|
const RECENT_USE_LIMIT = 20;
|
|
11163
12165
|
const CANDIDATE_LINK_LIMIT = 6;
|
|
@@ -11224,6 +12226,28 @@ function feedMediaSql(db) {
|
|
|
11224
12226
|
const files = db.select({ files: sql`jsonb_agg(jsonb_build_object('contentType', ${recentFiles.contentType}, 'filename', ${recentFiles.filename}, 'id', ${recentFiles.id}) order by ${recentFiles.createdAt} desc, ${recentFiles.id} desc)` }).from(recentFiles);
|
|
11225
12227
|
return sql`(${files})`;
|
|
11226
12228
|
}
|
|
12229
|
+
// src/api/conversations/feed-answer.ts
|
|
12230
|
+
/**
|
|
12231
|
+
* A feed row column with the viewer's newest answered Inbox item of its
|
|
12232
|
+
* Conversation, or null. It is a scalar subquery on the row read, so the
|
|
12233
|
+
* answer costs no round trip of its own, however many items the viewer
|
|
12234
|
+
* closed since.
|
|
12235
|
+
*/
|
|
12236
|
+
function feedViewerAnswerSql(db, userId) {
|
|
12237
|
+
const latest = db.select({ answer: sql`jsonb_build_object('answer', ${juniorInboxItems.answer}, 'closedAt', ${juniorInboxItems.closedAt}, 'request', ${juniorInboxItems.request})` }).from(juniorInboxItems).where(and(inboxItemOwnedByConversation(juniorConversations.conversationId), eq(juniorInboxItems.closedByUserId, userId), isNotNull(juniorInboxItems.answer), isNotNull(juniorInboxItems.request))).orderBy(desc(juniorInboxItems.closedAt), desc(juniorInboxItems.id)).limit(1);
|
|
12238
|
+
return sql`(${latest})`;
|
|
12239
|
+
}
|
|
12240
|
+
/**
|
|
12241
|
+
* Keep only what a row says about the answer: when it closed and the
|
|
12242
|
+
* options that the viewer picked. Text answers have no choices.
|
|
12243
|
+
*/
|
|
12244
|
+
function feedViewerAnswer(stored) {
|
|
12245
|
+
if (!stored) return void 0;
|
|
12246
|
+
return {
|
|
12247
|
+
choices: answeredChoices(stored.request, stored.answer),
|
|
12248
|
+
closedAt: new Date(stored.closedAt).toISOString()
|
|
12249
|
+
};
|
|
12250
|
+
}
|
|
11227
12251
|
// src/api/page-cursor.ts
|
|
11228
12252
|
/**
|
|
11229
12253
|
* Encode the position after the last row of a page as an opaque `cursor`
|
|
@@ -11283,48 +12307,31 @@ function conversationCodeRepositoryFilter(repositoryId, viewerUserId) {
|
|
|
11283
12307
|
FROM ${juniorCodeChanges}
|
|
11284
12308
|
WHERE ${juniorCodeChanges.repositoryId} = ${repositoryId}
|
|
11285
12309
|
)
|
|
11286
|
-
)`,
|
|
12310
|
+
)`, rootVisibleToViewer(viewerUserId));
|
|
11287
12311
|
}
|
|
11288
|
-
async function conversationRows(db, { codeRepository, conversationIds, cursor, filter, include = [],
|
|
12312
|
+
async function conversationRows(db, { codeRepository, conversationIds, cursor, filter, include = [], includePrivateMatches = false, limit, pinnedForUserId, query, status, waitingForUserId }) {
|
|
11289
12313
|
const rows = db.select({
|
|
11290
|
-
...conversationRecordColumns,
|
|
12314
|
+
...conversationRecordColumns(),
|
|
11291
12315
|
activityCursor: sql`to_char(${juniorConversations.lastActivityAt} at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`,
|
|
11292
12316
|
lastMessageAt: sql`coalesce(${juniorConversations.lastMessageAt}, ${lastMessageAtSql(db)})`.mapWith(juniorConversations.lastMessageAt),
|
|
11293
12317
|
awaitingAuthorization: treeAwaitsAuthorization(juniorConversations.conversationId),
|
|
12318
|
+
latestTurnFailed: conversationTurnFailedSql(juniorConversations),
|
|
11294
12319
|
links: include.includes("links") ? feedLinksSql(db) : sql`null`,
|
|
11295
|
-
media: include.includes("media") ? feedMediaSql(db) : sql`null
|
|
11296
|
-
|
|
11297
|
-
|
|
11298
|
-
from ${juniorConversationBriefs}
|
|
11299
|
-
where ${juniorConversationBriefs.conversationId} = ${juniorConversations.conversationId}
|
|
11300
|
-
and ${includePrivateBriefs ? sql`true` : eq(juniorDestinations.visibility, "public")}
|
|
11301
|
-
and ${juniorConversationBriefs.version} = (
|
|
11302
|
-
select max(${juniorConversationBriefs.version})
|
|
11303
|
-
from ${juniorConversationBriefs}
|
|
11304
|
-
where ${juniorConversationBriefs.conversationId} = ${juniorConversations.conversationId}
|
|
11305
|
-
)
|
|
11306
|
-
and to_tsvector('english', ${juniorConversationBriefs.searchText})
|
|
11307
|
-
@@ websearch_to_tsquery('english', ${query})
|
|
11308
|
-
)`) : void 0)).orderBy(desc(juniorConversations.lastActivityAt), asc(juniorConversations.conversationId)).$dynamic();
|
|
12320
|
+
media: include.includes("media") ? feedMediaSql(db) : sql`null`,
|
|
12321
|
+
viewerAnswer: filter?.kind === "viewer" ? feedViewerAnswerSql(db, filter.userId) : sql`null`
|
|
12322
|
+
}).from(juniorConversations).leftJoin(juniorDestinations, conversationRecordJoins.location).leftJoin(juniorIdentities, conversationRecordJoins.identity).leftJoin(juniorUsers, conversationRecordJoins.user).where(and(listedConversation(), conversationFeedMembershipFilter(status, filter), conversationIds ? inArray(juniorConversations.conversationId, conversationIds) : void 0, waitingForUserId ? inArray(juniorConversations.conversationId, waitingConversationIdsQuery(db, waitingForUserId)) : void 0, pinnedForUserId ? pinnedForUserId.pinned ? conversationPinnedForUser(pinnedForUserId.userId) : not(conversationPinnedForUser(pinnedForUserId.userId)) : void 0, cursor ? sql`(${juniorConversations.lastActivityAt} < ${cursor.at}::timestamptz or (${juniorConversations.lastActivityAt} = ${cursor.at}::timestamptz and ${juniorConversations.conversationId} > ${cursor.conversationId}))` : void 0, codeRepository ? conversationCodeRepositoryFilter(codeRepository.id, codeRepository.viewerUserId) : void 0, query ? or(sql`strpos(lower(coalesce(${juniorConversations.title}, '')), ${query}) > 0`, and(includePrivateMatches ? void 0 : eq(juniorDestinations.visibility, "public"), sql`${conversationSearchVector} @@ websearch_to_tsquery('english', ${query})`), annotationMatch(db, query, includePrivateMatches)) : void 0)).orderBy(desc(juniorConversations.lastActivityAt), asc(juniorConversations.conversationId)).$dynamic();
|
|
11309
12323
|
return limit === void 0 ? rows : rows.limit(limit);
|
|
11310
12324
|
}
|
|
12325
|
+
const searchAnnotated = alias(juniorConversations, "search_annotated");
|
|
11311
12326
|
/**
|
|
11312
|
-
*
|
|
11313
|
-
*
|
|
11314
|
-
*
|
|
12327
|
+
* Match a root whose tree has an Annotation with the text in its label or
|
|
12328
|
+
* title, such as `getsentry/roach#12`. The feed shows the annotations of
|
|
12329
|
+
* the whole tree, so search reads the same rows. Private annotations match
|
|
12330
|
+
* only where the feed shows them.
|
|
11315
12331
|
*/
|
|
11316
|
-
|
|
11317
|
-
const
|
|
11318
|
-
|
|
11319
|
-
if (missing.length === 0) return [];
|
|
11320
|
-
return await conversationRows(db, {
|
|
11321
|
-
conversationIds: missing,
|
|
11322
|
-
filter,
|
|
11323
|
-
include,
|
|
11324
|
-
includePrivateBriefs: true,
|
|
11325
|
-
limit: missing.length,
|
|
11326
|
-
status: "active"
|
|
11327
|
-
});
|
|
12332
|
+
function annotationMatch(db, query, includePrivate) {
|
|
12333
|
+
const annotation = juniorConversationAnnotations.annotation;
|
|
12334
|
+
return exists(db.select({ one: sql`1` }).from(juniorConversationAnnotations).innerJoin(searchAnnotated, eq(searchAnnotated.conversationId, juniorConversationAnnotations.conversationId)).where(and(eq(searchAnnotated.rootConversationId, juniorConversations.conversationId), includePrivate ? void 0 : eq(juniorDestinations.visibility, "public"), sql`strpos(lower(concat_ws(' ', ${annotation}->>'label', ${annotation}->>'title')), ${query}) > 0`)));
|
|
11328
12335
|
}
|
|
11329
12336
|
/**
|
|
11330
12337
|
* Feed rows show last activity only as an age in whole minutes. A running
|
|
@@ -11347,38 +12354,46 @@ const feedAnnotated = alias(juniorConversations, "feed_annotated");
|
|
|
11347
12354
|
* for each feed-row input as `name:token`, separated by spaces, so the
|
|
11348
12355
|
* dashboard can record which inputs moved it.
|
|
11349
12356
|
*
|
|
11350
|
-
* The token holds only what a feed row shows, so a Task
|
|
11351
|
-
*
|
|
11352
|
-
*
|
|
12357
|
+
* The token holds only what a feed row shows, so a Task moves it only when
|
|
12358
|
+
* the tree state moves. Watches and Timers live outside SQL. A Turn makes
|
|
12359
|
+
* or cancels one, and the end of that Turn moves the status or the tree's
|
|
12360
|
+
* work, so a read after it sees the change. A Timer that fires starts a
|
|
12361
|
+
* Turn. A stop anywhere in the tree moves it too, since a stopped
|
|
12362
|
+
* Conversation's Watches start no Turn. A Watch that expires on its own
|
|
12363
|
+
* moves nothing, so its row shows `watching` until the feed reads again. Every Event of a live Turn moves `last_activity_at`, but
|
|
12364
|
+
* a running row shows its running state in place of the age, so the token
|
|
11353
12365
|
* holds no activity for it. Other rows show an age in whole minutes, so the
|
|
11354
12366
|
* token holds its minute. The end of the Turn moves the status.
|
|
11355
12367
|
* The rows are in feed order, so a move that reorders them moves the token.
|
|
11356
12368
|
* The newest Message of each role stands for the preview and participants.
|
|
11357
12369
|
* Threads and annotations show from the whole tree. Waiting roots outside
|
|
11358
|
-
* the page move the
|
|
12370
|
+
* the page move the Inbox items token.
|
|
11359
12371
|
*/
|
|
11360
12372
|
function conversationFeedVersionQuery(db, userId) {
|
|
11361
12373
|
const pin = juniorConversationParticipants;
|
|
11362
12374
|
const conversationId = juniorConversations.conversationId;
|
|
11363
12375
|
const tree = db.select({ version: sql`concat_ws(':',
|
|
11364
12376
|
count(*) filter (where ${feedTree.archivedAt} is not null),
|
|
12377
|
+
count(*) filter (where ${feedTree.stoppedAt} is not null),
|
|
12378
|
+
coalesce(bool_or(${conversationIsActiveSql(feedTree)}) filter (where ${ne(feedTree.conversationId, conversationId)}), false),
|
|
12379
|
+
bool_or(exists (select 1 from ${juniorInboxItems} where ${and(inboxItemOwnedByConversation(feedTree.conversationId), inboxItemNeedsInput(), inboxItemForUser(userId))}) or ${awaitsAuthorizationFrom(feedTree.conversationId, userId)}),
|
|
11365
12380
|
string_agg(concat_ws('/',
|
|
11366
12381
|
${feedTree.conversationId}, ${feedTree.title},
|
|
11367
|
-
${feedTree
|
|
12382
|
+
${conversationStatusSql(feedTree)},
|
|
11368
12383
|
${shownActivityMinute(feedTree.executionStatus, feedTree.lastActivityAt)}
|
|
11369
12384
|
), ',' order by ${feedTree.conversationId}) filter (
|
|
11370
12385
|
where ${feedTree.kind} = 'thread' and ${feedTree.archivedAt} is null
|
|
11371
12386
|
)
|
|
11372
|
-
)` }).from(feedTree).where(eq(feedTree.rootConversationId, conversationId));
|
|
12387
|
+
)` }).from(feedTree).where(or(eq(feedTree.conversationId, conversationId), eq(feedTree.rootConversationId, conversationId)));
|
|
11373
12388
|
const annotations = db.select({ version: sql`concat_ws(':', count(*), max(${juniorConversationAnnotations.updatedAt}))` }).from(juniorConversationAnnotations).innerJoin(feedAnnotated, eq(feedAnnotated.conversationId, juniorConversationAnnotations.conversationId)).where(eq(feedAnnotated.rootConversationId, conversationId));
|
|
11374
12389
|
const page = db.select({
|
|
11375
12390
|
conversationId,
|
|
11376
12391
|
channelName: juniorConversations.channelName,
|
|
11377
|
-
executionStatus: juniorConversations.executionStatus,
|
|
11378
12392
|
lastActivityAt: juniorConversations.lastActivityAt,
|
|
11379
12393
|
pinnedAt: pin.pinnedAt,
|
|
11380
12394
|
pinPosition: pin.pinPosition,
|
|
11381
|
-
|
|
12395
|
+
status: conversationStatusSql(juniorConversations).as("status"),
|
|
12396
|
+
waitsOnViewer: conversationWaitsOnUserSql(juniorConversations, userId).as("waits_on_viewer"),
|
|
11382
12397
|
title: juniorConversations.title,
|
|
11383
12398
|
activity: shownActivityMinute(juniorConversations.executionStatus, juniorConversations.lastActivityAt).as("activity"),
|
|
11384
12399
|
assistantSeq: sql`(${latestMessageSeqQuery(db, "assistant", conversationId)})`.as("assistant_seq"),
|
|
@@ -11394,7 +12409,7 @@ function conversationFeedVersionQuery(db, userId) {
|
|
|
11394
12409
|
order: sql`string_agg(${page.conversationId}, ',' order by ${page.pinnedAt} is not null desc, ${page.lastActivityAt} desc, ${page.conversationId})`,
|
|
11395
12410
|
pin: byRow(page.pinnedAt, page.pinPosition),
|
|
11396
12411
|
title: byRow(page.title, page.channelName),
|
|
11397
|
-
status: byRow(page.
|
|
12412
|
+
status: byRow(page.status, page.waitsOnViewer),
|
|
11398
12413
|
activity: byRow(page.activity),
|
|
11399
12414
|
messages: byRow(page.assistantSeq, page.userSeq),
|
|
11400
12415
|
threads: byRow(page.threads),
|
|
@@ -11443,54 +12458,78 @@ async function readConversationFeedFromSql(options = {}) {
|
|
|
11443
12458
|
} } : void 0,
|
|
11444
12459
|
filter,
|
|
11445
12460
|
include,
|
|
11446
|
-
|
|
12461
|
+
includePrivateMatches: filter?.kind === "viewer",
|
|
11447
12462
|
query,
|
|
11448
12463
|
status
|
|
11449
12464
|
};
|
|
11450
|
-
const
|
|
11451
|
-
|
|
11452
|
-
|
|
11453
|
-
|
|
11454
|
-
|
|
11455
|
-
|
|
11456
|
-
|
|
11457
|
-
|
|
11458
|
-
|
|
11459
|
-
|
|
11460
|
-
|
|
11461
|
-
|
|
11462
|
-
|
|
11463
|
-
|
|
11464
|
-
|
|
12465
|
+
const firstPage = pinsFirst && !cursor;
|
|
12466
|
+
const [pinnedRows, pageRows, waitingRows] = await Promise.all([
|
|
12467
|
+
firstPage ? conversationRows(db, {
|
|
12468
|
+
...feedQuery,
|
|
12469
|
+
pinnedForUserId: {
|
|
12470
|
+
pinned: true,
|
|
12471
|
+
userId: filter.userId
|
|
12472
|
+
}
|
|
12473
|
+
}) : [],
|
|
12474
|
+
conversationRows(db, {
|
|
12475
|
+
...feedQuery,
|
|
12476
|
+
...cursor ? { cursor } : void 0,
|
|
12477
|
+
limit: limit + 1,
|
|
12478
|
+
...pinsFirst ? { pinnedForUserId: {
|
|
12479
|
+
pinned: false,
|
|
12480
|
+
userId: filter.userId
|
|
12481
|
+
} } : void 0
|
|
12482
|
+
}),
|
|
12483
|
+
firstPage ? conversationRows(db, {
|
|
12484
|
+
filter,
|
|
12485
|
+
include,
|
|
12486
|
+
includePrivateMatches: true,
|
|
12487
|
+
status: "active",
|
|
12488
|
+
waitingForUserId: filter.userId
|
|
12489
|
+
}) : []
|
|
12490
|
+
]);
|
|
11465
12491
|
const page = pageRows.slice(0, limit);
|
|
11466
12492
|
const lastRow = pageRows.length > limit ? page.at(-1) : void 0;
|
|
11467
12493
|
const rows = [...pinnedRows, ...page];
|
|
11468
|
-
if (
|
|
12494
|
+
if (firstPage) {
|
|
12495
|
+
const loaded = new Set(rows.map((row) => row.conversation.conversationId));
|
|
12496
|
+
const outsidePage = waitingRows.filter((row) => !loaded.has(row.conversation.conversationId));
|
|
12497
|
+
options.onWaitingRows?.(outsidePage.length);
|
|
12498
|
+
rows.push(...outsidePage);
|
|
12499
|
+
}
|
|
11469
12500
|
const conversations = rows.map((row) => conversationFromRecordRow(row));
|
|
11470
12501
|
const conversationIds = conversations.map((conversation) => conversation.conversationId);
|
|
11471
|
-
const
|
|
11472
|
-
|
|
11473
|
-
|
|
12502
|
+
const conversationTrees = readConversationTrees(db, conversationIds);
|
|
12503
|
+
const [accessRows, tree, participantsByRoot, annotationsByConversation, auxiliaryCostsByRoot, metricsByRoot, participantsByConversation, teamDomainByTeamId, { work: conversationWork, lastUserMessageAt: lastUserMessageAtByConversation }, activityPreviewByConversation, automationTitleByConversation, firstHumanMessageTextByConversation, treeStateByConversation, threadRecords] = await Promise.all([
|
|
12504
|
+
readConversationAccessRows(db, conversationIds),
|
|
12505
|
+
conversationTrees,
|
|
12506
|
+
readMemberParticipants(db, conversationIds, options.viewer ? { userId: options.viewer.id } : filter ? feedMember(filter) : void 0),
|
|
11474
12507
|
listConversationAnnotationsById(db, conversationIds),
|
|
11475
12508
|
readConversationAuxiliaryCostsFromSql(db, conversationIds),
|
|
11476
12509
|
readConversationTreeMetricsFromSql(db, conversationIds),
|
|
11477
12510
|
readConversationParticipants(db, conversationIds),
|
|
11478
12511
|
resolveSlackTeamDomains(conversations.flatMap((conversation) => conversation.location?.provider === "slack" ? [conversation.location.teamId] : [])),
|
|
11479
|
-
listConversationWork(conversationIds).then(async (work) => ({
|
|
12512
|
+
conversationTrees.then((tree) => listConversationWork(conversationIds, tree)).then(async (work) => ({
|
|
11480
12513
|
work,
|
|
11481
12514
|
lastUserMessageAt: await readLastUserMessageAtByConversation(db, work.assignedIds.filter((conversationId) => work.finishedAtById[conversationId]))
|
|
11482
12515
|
})),
|
|
11483
12516
|
readConversationActivityPreviews(db, conversationIds),
|
|
11484
|
-
readConversationFeedBriefs(db, conversationIds),
|
|
11485
12517
|
readAutomationTitlesByConversationId(conversations),
|
|
11486
|
-
readFirstHumanMessageTexts(db, conversations)
|
|
12518
|
+
readFirstHumanMessageTexts(db, conversations),
|
|
12519
|
+
readConversationTreeStates(db, conversationIds, options.viewer?.id),
|
|
12520
|
+
readFeedThreadRecords(db, conversations.filter((conversation) => conversation.archivedAtMs === void 0).map(({ conversationId }) => conversationId))
|
|
11487
12521
|
]);
|
|
11488
|
-
const
|
|
12522
|
+
const accessByConversation = conversationAccessFromRows(accessRows, options.viewer ? new Set(participantsByRoot.keys()) : /* @__PURE__ */ new Set());
|
|
12523
|
+
const tenantByConversation = new Map(rows.flatMap((row) => {
|
|
12524
|
+
const tenantId = conversationSlackTenantId({
|
|
12525
|
+
providerTenantId: row.location?.providerTenantId,
|
|
12526
|
+
sessionSource: row.conversation.sessionSource
|
|
12527
|
+
});
|
|
12528
|
+
return tenantId ? [[row.conversation.conversationId, tenantId]] : [];
|
|
12529
|
+
}));
|
|
11489
12530
|
const visibleAnnotationsByConversation = new Map(conversationIds.map((conversationId) => [conversationId, accessByConversation.get(conversationId)?.canViewPrivateContent ? annotationsByConversation.get(conversationId) ?? [] : []]));
|
|
11490
|
-
const [
|
|
11491
|
-
|
|
11492
|
-
conversationId
|
|
11493
|
-
})))]);
|
|
12531
|
+
const [visibleActivityPreviews, sidebarAnnotationsByConversation] = await Promise.all([attachActivityPreviewMentions(getSqlExecutor(), new Map([...activityPreviewByConversation].filter(([conversationId]) => accessByConversation.get(conversationId)?.canViewPrivateContent)), tenantByConversation), listConversationSidebarAnnotations(conversationIds, visibleAnnotationsByConversation)]);
|
|
12532
|
+
const threadsByRoot = nestFeedThreads(threadRecords, tree, accessByConversation);
|
|
11494
12533
|
const assignedWork = new Set(conversationWork.assignedIds);
|
|
11495
12534
|
const unfinishedWork = new Set(conversationWork.unfinishedIds);
|
|
11496
12535
|
return {
|
|
@@ -11501,7 +12540,8 @@ async function readConversationFeedFromSql(options = {}) {
|
|
|
11501
12540
|
const auxiliaryCosts = auxiliaryCostsByRoot.get(conversation.conversationId);
|
|
11502
12541
|
const childAgentTotals = childAgentTotalsReport(metrics, auxiliaryCosts);
|
|
11503
12542
|
const summary = conversationSummaryFromStoredConversation({
|
|
11504
|
-
...
|
|
12543
|
+
...filter ? participantsByRoot.get(conversation.conversationId) : void 0,
|
|
12544
|
+
status: row.status,
|
|
11505
12545
|
automationTitle: automationTitleByConversation.get(conversation.conversationId),
|
|
11506
12546
|
conversation,
|
|
11507
12547
|
access,
|
|
@@ -11520,21 +12560,24 @@ async function readConversationFeedFromSql(options = {}) {
|
|
|
11520
12560
|
};
|
|
11521
12561
|
const annotations = access?.canViewPrivateContent ? annotationsByConversation.get(conversation.conversationId) ?? [] : [];
|
|
11522
12562
|
const activityPreview = visibleActivityPreviews.get(conversation.conversationId);
|
|
11523
|
-
const brief = access?.canViewPrivateContent ? briefByConversation.get(conversation.conversationId) : void 0;
|
|
11524
12563
|
const participants = access?.canViewPrivateContent ? participantsByConversation.get(conversation.conversationId) : void 0;
|
|
11525
12564
|
const threads = threadsByRoot.get(conversation.conversationId);
|
|
11526
12565
|
const media = access?.canViewPrivateContent ? row.media : null;
|
|
11527
12566
|
const links = access?.canViewPrivateContent && row.links ? pickFeedLinks(conversation.conversationId, row.links, annotationUrls(annotations)) : [];
|
|
11528
12567
|
const lastMessageAt = row.lastMessageAt?.toISOString();
|
|
12568
|
+
const treeRead = treeStateByConversation.get(conversation.conversationId);
|
|
12569
|
+
const viewerAnswer = access?.canViewPrivateContent ? feedViewerAnswer(row.viewerAnswer) : void 0;
|
|
11529
12570
|
return {
|
|
11530
12571
|
...summary,
|
|
11531
12572
|
...work,
|
|
12573
|
+
...treeRead,
|
|
11532
12574
|
...row.awaitingAuthorization ? { awaitingAuthorization: true } : void 0,
|
|
12575
|
+
...row.latestTurnFailed ? { latestTurnFailed: true } : void 0,
|
|
11533
12576
|
...lastMessageAt ? { lastMessageAt } : void 0,
|
|
11534
12577
|
...threads ? { threads } : void 0,
|
|
11535
12578
|
...participants && participants.length > 0 ? { participants } : void 0,
|
|
11536
12579
|
...activityPreview ? { activityPreview } : void 0,
|
|
11537
|
-
...
|
|
12580
|
+
...viewerAnswer ? { viewerAnswer } : void 0,
|
|
11538
12581
|
...media?.length ? { media } : void 0,
|
|
11539
12582
|
...links.length > 0 ? { links } : void 0,
|
|
11540
12583
|
...annotations.length > 0 ? { annotations } : void 0,
|
|
@@ -11563,78 +12606,6 @@ async function readConversationFeedFromSql(options = {}) {
|
|
|
11563
12606
|
* guarantee, so they are not an authorization boundary.
|
|
11564
12607
|
*/
|
|
11565
12608
|
async function readConversationFeed(options = {}) {
|
|
11566
|
-
return
|
|
11567
|
-
}
|
|
11568
|
-
// src/api/conversations/steer-pending-messages.ts
|
|
11569
|
-
/**
|
|
11570
|
-
* Steer the viewer's own queued web messages into the conversation now.
|
|
11571
|
-
*
|
|
11572
|
-
* Only the author can steer a message. Ids that are not the viewer's queued
|
|
11573
|
-
* web messages, or that Junior already read, are left out of the result.
|
|
11574
|
-
*/
|
|
11575
|
-
async function steerConversationPendingMessagesForViewer(viewer, conversationId, body) {
|
|
11576
|
-
if (!await getConversationStore().get({ conversationId })) throwApiError(404, "Conversation not found.");
|
|
11577
|
-
if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(403, "Only conversation participants can steer queued messages.");
|
|
11578
|
-
return {
|
|
11579
|
-
conversationId,
|
|
11580
|
-
steeredInboundMessageIds: (await steerWebPendingMessages({
|
|
11581
|
-
authorIds: webActorUserIds(viewer),
|
|
11582
|
-
conversationId,
|
|
11583
|
-
inboundMessageIds: body.inboundMessageIds
|
|
11584
|
-
})).steeredInboundMessageIds
|
|
11585
|
-
};
|
|
11586
|
-
}
|
|
11587
|
-
// src/api/conversations/stop.ts
|
|
11588
|
-
/**
|
|
11589
|
-
* Stop one Conversation for a participant: its active Turn, its session, and
|
|
11590
|
-
* every child agent below it.
|
|
11591
|
-
*
|
|
11592
|
-
* The stop also removes the human messages queued before it. The viewer's own
|
|
11593
|
-
* web text comes back in the response so the dashboard can restore it to the
|
|
11594
|
-
* composer instead of losing it.
|
|
11595
|
-
*/
|
|
11596
|
-
async function stopConversationTurnForViewer(viewer, conversationId, services) {
|
|
11597
|
-
const conversationStore = getConversationStore();
|
|
11598
|
-
if (!await conversationStore.get({ conversationId })) throwApiError(404, "Conversation not found.");
|
|
11599
|
-
if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(403, "Only conversation participants can stop this turn.");
|
|
11600
|
-
try {
|
|
11601
|
-
const result = await stopConversation({
|
|
11602
|
-
conversationId,
|
|
11603
|
-
conversationStore,
|
|
11604
|
-
queue: services.queue
|
|
11605
|
-
});
|
|
11606
|
-
if (result.status !== "requested") return {
|
|
11607
|
-
conversationId,
|
|
11608
|
-
status: "no_work",
|
|
11609
|
-
stoppedInboundMessageIds: [],
|
|
11610
|
-
stoppedMessages: []
|
|
11611
|
-
};
|
|
11612
|
-
await clearSlackPendingReactions({
|
|
11613
|
-
getSlackAdapter: getProductionSlackAdapter,
|
|
11614
|
-
messages: result.pendingMessages
|
|
11615
|
-
});
|
|
11616
|
-
return {
|
|
11617
|
-
conversationId,
|
|
11618
|
-
status: "requested",
|
|
11619
|
-
stoppedInboundMessageIds: result.pendingMessages.map((message) => message.inboundMessageId),
|
|
11620
|
-
stoppedMessages: viewerWebMessages(result.pendingMessages, viewer)
|
|
11621
|
-
};
|
|
11622
|
-
} catch (error) {
|
|
11623
|
-
throwApiError(500, "Unable to stop the active turn.", error);
|
|
11624
|
-
}
|
|
11625
|
-
}
|
|
11626
|
-
function viewerWebMessages(messages, viewer) {
|
|
11627
|
-
const viewerUserIds = webActorUserIds(viewer);
|
|
11628
|
-
return messages.flatMap((message) => {
|
|
11629
|
-
if (message.source !== "web") return [];
|
|
11630
|
-
const metadata = legacyWebMailboxMetadataSchema.safeParse(message.input.metadata);
|
|
11631
|
-
if (!metadata.success) return [];
|
|
11632
|
-
if (!viewerUserIds.includes(metadata.data.authorUserId)) return [];
|
|
11633
|
-
const text = message.input.text.trim();
|
|
11634
|
-
return text ? [{
|
|
11635
|
-
inboundMessageId: message.inboundMessageId,
|
|
11636
|
-
text
|
|
11637
|
-
}] : [];
|
|
11638
|
-
});
|
|
12609
|
+
return readConversationFeedFromSql(options);
|
|
11639
12610
|
}
|
|
11640
|
-
export {
|
|
12611
|
+
export { runAutoArchiveSweep as $, apiOperationHandler as A, slackInboundMessageId as At, mcpMessages as B, stripLeadingBotMention as Bt, cancelQueuedMessagesOperation as C, isPublicAddress as Ct, setConversationSubscriptionOperation as D, getProductionSlackAdapter as Dt, setConversationAutoArchiveOperation as E, createProductionSlackWebhookServices as Et, mcpConversationSchema as F, failStoppedDispatch as Ft, resolveMentions as G, conversationRecordJoins as Gt, readMcpPendingWork as H, SubscribedReplyReason as Ht, mcpCursorSchema as I, recordSkippedConversationMessage as It, closeInboxItemsAnsweredByReply as J, readFirstHumanMessageTexts as Jt, InboxItemActionError as K, readConversationRecordFromSql as Kt, mcpIdempotencyKeySchema as L, createSlackWebApiStatusSender as Lt, mcpAuthorizationSchema as M, withNormalizedThreadId as Mt, mcpConversation as N, AGENT_DISPATCH_MAX_AGE_MS as Nt, stopConversationOperation as O, buildSlackInboundMessage as Ot, mcpConversationIdSchema as P, enqueueAgentDispatch as Pt, ingestEventAutomations as Q, mcpMessageSchema as R, bindMessageAuthorIdentityId as Rt, archiveDoneConversationsOperation as S, guardedFetch as St, pinConversationOperation as T, createProductionConversationWorkOptions as Tt, readMcpPendingWorkAfterSend as U, getThreadStopDecision as Ut, mcpPendingMessagesSchema as V, parseContent as Vt, requireConversationPendingMessages as W, resolvePersonLink as Wt, reviewItemChange as X, IMAGE_WIDTHS as Xt, readInboxItemForUser as Y, createViewerMcp as Yt, createEventAppPublisher as Z, decodeImageId as Zt, createConversationForViewer as _, readLinkObjectType as _t, listedConversation as a, createHeartbeatContext as at, encodeConversationCursor as b, resolveObjectLinks as bt, readConversationAuxiliaryCostsFromSql as c, runInboxSnoozeTimers as ct, conversationVersionsQuery as d, runSavingsRefillSlice as dt, DEFAULT_USER_SETTINGS as et, readConversationDetailEtag as f, startSavingsRefill as ft, appendConversationMessageForViewer as g, OBJECT_LINK_TTL_MS as gt, readConversationEvents as h, readHealthReport as ht, encodePageCursor as i, settleEventAutomationRuns as it, mcpAcceptedMessageSchema as j, normalizeIncomingSlackThreadId as jt, reorderPinnedConversations as k, clearSlackPendingReactions as kt, childAgentTotalsReport as l, scheduleInboxSnoozeTimer as lt, keepQuickQuestionForViewer as m, GET as mt, readConversationFeed as n, updateUserSettings as nt, notLeadConversation as o, dispatchScheduledAutomation as ot, forkConversationForViewer as p, backfillCacheWarmingGaps as pt, actOnInboxItem as q, conversationSummaryFromStoredConversation as qt, decodePageCursor as r, automationReplyAttribution as rt, readConversationDetail as s, getScheduledAutomationDispatch as st, conversationFeedVersionQuery as t, readUserSettings as tt, readConversationTreeMetricsFromSql as u, readSavingsRefill as ut, requireWebMessageConversation as v, readObjectLinkTypes as vt, conversationOperations as w, publicAddressLookup as wt, archiveConversationOperation as x, viewerCanViewPluginLink as xt, decodeConversationCursor as y, resolveObjectLinkNow as yt, mcpMessageTextSchema as z, startProcessingReaction as zt };
|