@sentry/junior 0.311.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-G2M0y6rP.js → adapter-context-BRjEWRy1.js} +2 -2
- package/dist/{adapter-B1wujchl.js → adapter-iIq7ihf7.js} +1 -1
- package/dist/{admin-DCiBhUT1.js → admin-DhInw5K9.js} +1 -1
- package/dist/{agent-runner-BVHPUIc8.js → agent-runner-C9iDurwX.js} +3423 -3477
- package/dist/api/schema.d.ts +2 -2
- package/dist/api/schema.js +6 -6
- package/dist/api.d.ts +2 -2
- package/dist/api.js +289 -306
- package/dist/{app-Cw5Vy6H6.d.ts → app-DRFrC8Mw.d.ts} +2 -9
- package/dist/app.d.ts +1 -1
- package/dist/app.js +338 -604
- package/dist/{background-compaction-queue-CJDnWVOJ.js → background-compaction-queue-DrKi7w3d.js} +10 -85
- package/dist/callback-mFlTUWWx.js +75 -0
- package/dist/{catalog-runtime-DMY3VV-D.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 +3 -3
- package/dist/cli/init.js +0 -1
- package/dist/cli/main.js +3 -7
- package/dist/cli/plugins.js +4 -4
- 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-BrXDQefC.js → config-kXB2Y5tl.js} +59 -27
- package/dist/{continue-in-slack-DNXSC9So.js → continue-in-slack-O6pV5004.js} +7 -8
- package/dist/{conversation-feed-DkinDu5o.js → conversation-feed-uNOv_x68.js} +74 -20
- package/dist/{conversation-privacy-DxttrKb9.js → conversation-privacy-L4ja1_W6.js} +1 -1
- package/dist/{conversation-turn-DWw7Xhdr.js → conversation-turn-CeLbHqdw.js} +31 -27
- package/dist/{credential-sync-Bk8wGb8Y.js → credential-sync-I8VBGk05.js} +16 -15
- package/dist/{projection-Cns7XwWa.js → credentialed-Cb6E2phL.js} +16308 -20732
- package/dist/{db-7ETESH44.d.ts → db-BbC5stfa.d.ts} +11 -6
- package/dist/{db-DTxzH7u5.js → db-LAyyX8tk.js} +174 -91
- package/dist/{executor-DqTiYj9S.js → executor-SCub-fAq.js} +117 -97
- package/dist/{html-B9Sl4Axb.js → html-BCZ3Xtb_.js} +6 -6
- package/dist/ingest-BDf3D50j.js +3836 -0
- package/dist/{install-Sg4ePfLl.js → install-DCFJFkC0.js} +2 -2
- package/dist/instrumentation.js +3 -3
- package/dist/{lineage-BHAMpNKr.js → lineage-B_m-4TJw.js} +2 -2
- package/dist/{stop-CYsfc0Ed.js → list-CN2QA2R9.js} +663 -442
- package/dist/{logging-FjclQsXu.js → logging-dQ9ZRGQ8.js} +1 -1
- package/dist/{schedule-BLJ476XQ.js → media-CYm1QD8T.js} +1055 -11
- package/dist/{message-CJ7_RL50.js → message-DSXGj1hM.js} +19 -26
- package/dist/{model-input-CMLh4Cwq.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-RVcbiDjL.js → oauth-callback-server-DHCZC6B4.js} +2 -2
- package/dist/{oauth-relay-Bu9kkaQu.js → oauth-relay-pPMGnDZt.js} +1 -1
- package/dist/{registry-BPwuOP2O.js → registry-CZOzddwu.js} +1 -1
- package/dist/{resolve-BK29bBry.js → resolve-cKOQ14Dh.js} +3 -3
- package/dist/result-DcvEOe1r.js +574 -0
- package/dist/result-event-type-BdIJuZxg.js +48 -0
- package/dist/{runner-BcAE-cJm.js → runner-DBfUW44l.js} +14 -16
- package/dist/{sandbox-egress-signals-C-q0go5b.js → sandbox-egress-signals-BVF_xAm1.js} +1 -1
- package/dist/{schema-DYcJeV7d.d.ts → schema-BEHKxr4I.d.ts} +166 -242
- package/dist/{schema-BLgSZXcL.js → schema-Bk9Nm2E8.js} +106 -121
- package/dist/{service-account-iJoCtkHR.js → service-account-CVYsFjty.js} +3 -3
- package/dist/{service-account-gN0zqf0S.js → service-account-Ts4ulcrV.js} +5 -5
- package/dist/{skills-BoZ80epJ.js → skills-VTnhAJWm.js} +2 -2
- package/dist/{slack-conversation-unfurl-CogYrITA.js → slack-conversation-unfurl-fuLnF1jE.js} +9 -9
- package/dist/{spawn-Dk92r7mX.js → spawn-vxAarlX5.js} +6 -5
- package/dist/start-conversation-CEn2KH1A.js +941 -0
- package/dist/{state-DH3Cmgp3.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-BW2BsQbH.js → thread-context-BkAZDTX2.js} +7 -7
- package/dist/thread-state-DhPndWi1.js +5625 -0
- package/dist/{validation-DrJd0nnq.js → validation-nIzMtAVJ.js} +1 -1
- package/dist/{task-queue-C_zldF5J.js → vercel-queue-hW90XzbG.js} +93 -172
- package/dist/{version-CNKZ8owc.js → version-Brbtz4Qf.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{warmup-BWdHew2H.js → warmup-BDA5myRK.js} +6463 -12290
- package/dist/web-message-id-C6P83ans.js +10 -0
- package/dist/{worker-t9qpu_Zx.js → worker-D63RcaVD.js} +20 -7
- 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/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 +106 -1
- package/package.json +6 -6
- package/skills/design-automation-skill/SKILL.md +108 -0
- package/dist/briefs-BDjnug6Y.js +0 -395
- package/dist/conversation-ca__NDQW.js +0 -1063
- package/dist/prompt-CDqcsDYC.js +0 -910
- package/dist/store-DmmMIrQi.js +0 -335
- package/dist/task-runner-C7oCJQIx.js +0 -294
- package/dist/turn-session-routing-Xh_2nSQe.js +0 -261
- package/dist/web-message-id-Ch5dPq-a.js +0 -306
|
@@ -1,43 +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, 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-
|
|
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
5
|
import { h as startSpan, n as captureMessage } from "./sentry-CPbZjomA.js";
|
|
6
|
-
import { t as JUNIOR_VERSION } from "./version-
|
|
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 { $ as
|
|
9
|
-
import { B as juniorAttachments, C as juniorConversationParticipants, H as juniorConversations, K as juniorUsers, L as juniorCodeChanges, M as juniorConversationEvents,
|
|
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 { a as getStateValues, i as getStateAdapter, o as setStateValues } from "./adapter-
|
|
12
|
-
import { f as actorLogContext, p as credentialContextForActor } from "./registry-
|
|
13
|
-
import { n as pluginCatalogRuntime } from "./catalog-runtime-
|
|
14
|
-
import {
|
|
15
|
-
import { d as PluginMcpClient, u as McpAuthorizationRequiredError, v as getMcpStoredOAuthCredentials } from "./service-account-
|
|
16
|
-
import { i as webActorUserIds } from "./state-
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
21
|
-
import { $r as
|
|
22
|
-
import { m as
|
|
23
|
-
import {
|
|
24
|
-
import {
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
27
|
-
import {
|
|
28
|
-
import {
|
|
29
|
-
import {
|
|
30
|
-
import {
|
|
31
|
-
import {
|
|
32
|
-
import { t as
|
|
33
|
-
import {
|
|
34
|
-
import {
|
|
35
|
-
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";
|
|
36
40
|
import * as z from "zod";
|
|
37
41
|
import pLimit from "p-limit";
|
|
38
42
|
import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
|
|
39
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";
|
|
40
|
-
import { and, asc, count, desc, eq, gt, gte, inArray, isNotNull, isNull, lt, lte, min, ne, not, or, sql } from "drizzle-orm";
|
|
44
|
+
import { and, asc, count, desc, eq, exists, gt, gte, inArray, isNotNull, isNull, lt, lte, min, ne, not, or, sql } from "drizzle-orm";
|
|
41
45
|
import { alias } from "drizzle-orm/pg-core";
|
|
42
46
|
import { Message, ThreadImpl, stringifyMarkdown } from "chat";
|
|
43
47
|
import net from "node:net";
|
|
@@ -416,7 +420,7 @@ function buildSlackLocationUrl(args) {
|
|
|
416
420
|
url.searchParams.set("cid", channelId);
|
|
417
421
|
return url.toString();
|
|
418
422
|
}
|
|
419
|
-
// src/api/conversations/
|
|
423
|
+
// src/api/conversations/location-labels.ts
|
|
420
424
|
/** Format a Slack destination without exposing private channel names. */
|
|
421
425
|
function slackStatsLocationLabel(input) {
|
|
422
426
|
const channelId = input.channel;
|
|
@@ -547,6 +551,7 @@ function conversationSummaryFromStoredConversation(args) {
|
|
|
547
551
|
visibility
|
|
548
552
|
}),
|
|
549
553
|
kind: conversation.kind,
|
|
554
|
+
...canViewPrivateContent && conversation.summary ? { summary: conversation.summary } : void 0,
|
|
550
555
|
...conversation.parentConversationId ? { parentConversationId: conversation.parentConversationId } : void 0,
|
|
551
556
|
isParticipant: args.access?.isParticipant ?? false,
|
|
552
557
|
...visibility ? { visibility } : void 0,
|
|
@@ -634,6 +639,7 @@ function conversationFromRecordRow(row) {
|
|
|
634
639
|
...value.channelName ? { channelName: value.channelName } : void 0,
|
|
635
640
|
...value.source ? { source: value.source } : void 0,
|
|
636
641
|
...value.title ? { title: value.title } : void 0,
|
|
642
|
+
...value.summary ? { summary: value.summary } : void 0,
|
|
637
643
|
...value.transcriptPurgedAt ? { transcriptPurgedAtMs: value.transcriptPurgedAt.getTime() } : void 0,
|
|
638
644
|
...value.stoppedAt ? { stoppedAtMs: value.stoppedAt.getTime() } : void 0,
|
|
639
645
|
...value.deliveryPausedAt ? { deliveryPausedAtMs: value.deliveryPausedAt.getTime() } : void 0
|
|
@@ -684,14 +690,13 @@ async function resolveConversationLink(viewer, url) {
|
|
|
684
690
|
const db = getDb();
|
|
685
691
|
const access = await readViewerAccess(viewer, conversationId);
|
|
686
692
|
if (!access?.canViewPrivateContent) return void 0;
|
|
687
|
-
const [firstTexts, automationTitles,
|
|
693
|
+
const [firstTexts, automationTitles, participants] = await Promise.all([
|
|
688
694
|
readFirstHumanMessageTexts(db, [conversation]),
|
|
689
695
|
readAutomationTitlesByConversationId([conversation]),
|
|
690
|
-
readLatestConversationBrief(db, conversationId),
|
|
691
696
|
readConversationParticipants(db, [conversationId])
|
|
692
697
|
]);
|
|
693
698
|
return conversationObjectCard({
|
|
694
|
-
|
|
699
|
+
description: conversation.summary,
|
|
695
700
|
participants: participants.get(conversationId) ?? [],
|
|
696
701
|
summary: conversationSummaryFromStoredConversation({
|
|
697
702
|
access,
|
|
@@ -2889,14 +2894,14 @@ function readSlackActionToken(message) {
|
|
|
2889
2894
|
const token = slackActionTokenSchema.safeParse(envelope.data.raw?.action_token);
|
|
2890
2895
|
return token.success ? token.data : void 0;
|
|
2891
2896
|
}
|
|
2892
|
-
// src/chat/
|
|
2897
|
+
// src/chat/inbox-items/message-change.ts
|
|
2893
2898
|
const messageChangeRecords = /* @__PURE__ */ new WeakMap();
|
|
2894
2899
|
/** Keep the record of a restored Slack input for its Message write. */
|
|
2895
|
-
function
|
|
2900
|
+
function bindMessageInboxItemChange(message, record) {
|
|
2896
2901
|
if (record) messageChangeRecords.set(message, record);
|
|
2897
2902
|
}
|
|
2898
2903
|
/** Read the record that a restored Slack input carries. */
|
|
2899
|
-
function
|
|
2904
|
+
function getMessageInboxItemChange(message) {
|
|
2900
2905
|
return messageChangeRecords.get(message);
|
|
2901
2906
|
}
|
|
2902
2907
|
// src/chat/slack/assistant-thread/status-render.ts
|
|
@@ -3307,7 +3312,7 @@ function toConversationMessage(args) {
|
|
|
3307
3312
|
const messageHasPotentialImageAttachment = hasPotentialImageAttachment(args.entry.attachments);
|
|
3308
3313
|
const imageAttachmentCount = messageHasPotentialImageAttachment ? countPotentialImageAttachments(args.entry.attachments) : 0;
|
|
3309
3314
|
const authorIdentityId = args.entry.author.isMe ? void 0 : getMessageAuthorIdentityId(args.entry);
|
|
3310
|
-
const reviewItemChange =
|
|
3315
|
+
const reviewItemChange = getMessageInboxItemChange(args.entry);
|
|
3311
3316
|
return {
|
|
3312
3317
|
id: args.entry.id,
|
|
3313
3318
|
role: args.entry.author.isMe ? "assistant" : "user",
|
|
@@ -3476,14 +3481,23 @@ async function persistThreadRuntimeStateWithRetry(conversationId, patch) {
|
|
|
3476
3481
|
* Both are SQL-backed; there is no thread-state fallback.
|
|
3477
3482
|
*/
|
|
3478
3483
|
async function loadPiMessagesForTurn(args) {
|
|
3479
|
-
if (!args.conversationId) return {};
|
|
3484
|
+
if (!args.conversationId) return { seqs: [] };
|
|
3480
3485
|
if (args.activeTurnId) {
|
|
3481
3486
|
const sessionRecord = await getTurnRecord(args.conversationId, args.activeTurnId);
|
|
3482
|
-
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
|
+
}
|
|
3483
3494
|
}
|
|
3484
3495
|
const projection = await loadConversationProjection({ conversationId: args.conversationId });
|
|
3485
|
-
if (projection.messages.length > 0) return {
|
|
3486
|
-
|
|
3496
|
+
if (projection.messages.length > 0) return {
|
|
3497
|
+
piMessages: projection.messages,
|
|
3498
|
+
seqs: projection.seqs
|
|
3499
|
+
};
|
|
3500
|
+
return { seqs: [] };
|
|
3487
3501
|
}
|
|
3488
3502
|
/** Build the Slack caller that prepares input and delivers output for a Turn. */
|
|
3489
3503
|
function createSlackTurn(deps) {
|
|
@@ -3618,12 +3632,12 @@ function createSlackTurn(deps) {
|
|
|
3618
3632
|
const resolveSteeringMessages = async (queuedMessages) => {
|
|
3619
3633
|
return await mapBounded(queuedMessages, async (queued) => {
|
|
3620
3634
|
const attachments = queued.message.attachments;
|
|
3621
|
-
const
|
|
3635
|
+
const inboxItemInput = await loadInboxItemInput(getMessageInboxItemChange(queued.message));
|
|
3622
3636
|
return {
|
|
3623
3637
|
actor: inboundMessageActor(queued),
|
|
3624
|
-
...
|
|
3638
|
+
...inboxItemInput ? { kind: "runtime" } : void 0,
|
|
3625
3639
|
provenance: inboundMessageProvenance(queued, teamId),
|
|
3626
|
-
text:
|
|
3640
|
+
text: inboxItemInput?.text ?? queued.userText,
|
|
3627
3641
|
timestampMs: queued.message.metadata.dateSent.getTime(),
|
|
3628
3642
|
omittedImageAttachmentCount: !canReadImages() && hasPotentialImageAttachment(attachments) ? countPotentialImageAttachments(attachments) : 0,
|
|
3629
3643
|
attachments: await deps.resolveUserAttachments(attachments, {
|
|
@@ -3952,10 +3966,11 @@ function createSlackTurn(deps) {
|
|
|
3952
3966
|
boundaryFailureCode = "agent_run_failed";
|
|
3953
3967
|
};
|
|
3954
3968
|
try {
|
|
3955
|
-
|
|
3969
|
+
const loadedPiMessages = await loadPiMessagesForTurn({
|
|
3956
3970
|
conversationId,
|
|
3957
3971
|
activeTurnId
|
|
3958
|
-
})
|
|
3972
|
+
});
|
|
3973
|
+
let piMessages = loadedPiMessages.piMessages;
|
|
3959
3974
|
const hasHistory = Boolean(piMessages?.length);
|
|
3960
3975
|
const batchedSteeringMessages = (await resolveSteeringMessages((options.queuedMessages ?? []).filter((queued) => queued.explicitMention))).map((steering) => ({
|
|
3961
3976
|
message: buildSteeringPiMessage(steering),
|
|
@@ -4012,7 +4027,7 @@ function createSlackTurn(deps) {
|
|
|
4012
4027
|
const location = (await getConversationStore().get({ conversationId }))?.location;
|
|
4013
4028
|
const savedInput = await savedInputInstruction({
|
|
4014
4029
|
runtime: Boolean(options.execution?.dispatch),
|
|
4015
|
-
reviewItemChange:
|
|
4030
|
+
reviewItemChange: getMessageInboxItemChange(message),
|
|
4016
4031
|
text: effectiveUserText
|
|
4017
4032
|
});
|
|
4018
4033
|
const run = {
|
|
@@ -4031,7 +4046,10 @@ function createSlackTurn(deps) {
|
|
|
4031
4046
|
omittedImageAttachmentCount,
|
|
4032
4047
|
attachments: userAttachments
|
|
4033
4048
|
},
|
|
4034
|
-
history: piMessages
|
|
4049
|
+
history: piMessages ? {
|
|
4050
|
+
messages: piMessages,
|
|
4051
|
+
seqs: loadedPiMessages.seqs
|
|
4052
|
+
} : void 0,
|
|
4035
4053
|
credentialContext,
|
|
4036
4054
|
actor: executionActor,
|
|
4037
4055
|
slackConversation,
|
|
@@ -4155,7 +4173,7 @@ function createSlackTurn(deps) {
|
|
|
4155
4173
|
maxTurns: botConfig.maxConsecutiveAutomatedTurns,
|
|
4156
4174
|
source
|
|
4157
4175
|
});
|
|
4158
|
-
await
|
|
4176
|
+
await stopAtAutomatedTurnLimit({
|
|
4159
4177
|
conversationId,
|
|
4160
4178
|
maxTurns: botConfig.maxConsecutiveAutomatedTurns,
|
|
4161
4179
|
source,
|
|
@@ -5361,7 +5379,7 @@ function restoreMessage(args) {
|
|
|
5361
5379
|
message.attachments = message.attachments.map((attachment) => args.adapter.rehydrateAttachment(attachment));
|
|
5362
5380
|
rehydrateAttachmentFetchers(message);
|
|
5363
5381
|
bindMessageAuthorIdentityId(message, args.record.input.authorIdentityId);
|
|
5364
|
-
|
|
5382
|
+
bindMessageInboxItemChange(message, args.record.input.reviewItemChange);
|
|
5365
5383
|
return message;
|
|
5366
5384
|
}
|
|
5367
5385
|
async function bindSlackActorIdentities(args) {
|
|
@@ -6331,6 +6349,12 @@ async function runPausedTurnInContext(payload, options, runOptions) {
|
|
|
6331
6349
|
turnId: turn.turnId,
|
|
6332
6350
|
errorMessage: "Authorization no longer belongs to this request"
|
|
6333
6351
|
});
|
|
6352
|
+
await getTurnLifecycle().complete({
|
|
6353
|
+
conversationId: payload.conversationId,
|
|
6354
|
+
createdAtMs: Date.now(),
|
|
6355
|
+
outcome: "cancelled",
|
|
6356
|
+
turnId: turn.turnId
|
|
6357
|
+
});
|
|
6334
6358
|
clearPendingAuth(conversation, turn.turnId);
|
|
6335
6359
|
await persistThreadStateById(payload.conversationId, { conversation });
|
|
6336
6360
|
return false;
|
|
@@ -6370,7 +6394,7 @@ async function runPausedTurnInContext(payload, options, runOptions) {
|
|
|
6370
6394
|
});
|
|
6371
6395
|
const source = routing.source;
|
|
6372
6396
|
const routingDestination = routing.destination;
|
|
6373
|
-
const turnMessages = activeTurn
|
|
6397
|
+
const turnMessages = savedTurnMessages(activeTurn, await loadTurnStart(payload.conversationId, payload.turnId)).map(({ message }) => message);
|
|
6374
6398
|
const recordDispatchOutcome = async (dispatchOutcome) => {
|
|
6375
6399
|
if (!dispatch) return;
|
|
6376
6400
|
await recordTurnSummary({
|
|
@@ -6404,7 +6428,10 @@ async function runPausedTurnInContext(payload, options, runOptions) {
|
|
|
6404
6428
|
text: userMessage.text
|
|
6405
6429
|
})
|
|
6406
6430
|
},
|
|
6407
|
-
history: dispatchId ?
|
|
6431
|
+
history: dispatchId ? {
|
|
6432
|
+
messages: activeTurn.piMessages,
|
|
6433
|
+
seqs: activeTurn.piMessageSeqs
|
|
6434
|
+
} : await loadConversationProjection({ conversationId: payload.conversationId }),
|
|
6408
6435
|
actor,
|
|
6409
6436
|
credentialContext,
|
|
6410
6437
|
destination: routingDestination,
|
|
@@ -6799,10 +6826,8 @@ function createConversationWork(options) {
|
|
|
6799
6826
|
await stopLateChildAgents();
|
|
6800
6827
|
return result;
|
|
6801
6828
|
};
|
|
6802
|
-
const run = async (
|
|
6803
|
-
|
|
6804
|
-
if ("skipped" in stopped) return stopped.skipped;
|
|
6805
|
-
const { context } = stopped;
|
|
6829
|
+
const run = async (context) => {
|
|
6830
|
+
await resumeForPersonInput(context.conversationId, context.attempt.messages);
|
|
6806
6831
|
const conversation = await options.conversationStore.get({ conversationId: context.conversationId });
|
|
6807
6832
|
const topLevel = isTopLevelKind(conversation?.kind ?? "root");
|
|
6808
6833
|
return await withLogContext({ rootConversationId: conversation?.rootConversationId ?? (topLevel ? context.conversationId : void 0) }, () => runByKind(context, topLevel));
|
|
@@ -8397,10 +8422,11 @@ const INBOX_SNOOZE_TIMER_INDEX = {
|
|
|
8397
8422
|
/**
|
|
8398
8423
|
* Fire the snooze triggers that one Event matches. A `resolve` trigger
|
|
8399
8424
|
* dismisses the item and cancels its snooze; a `wake` trigger ends the
|
|
8400
|
-
* snooze
|
|
8401
|
-
* that already ended ignores the Event. Returns
|
|
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.
|
|
8402
8428
|
*/
|
|
8403
|
-
async function fireTriggers(db, event, nowMs) {
|
|
8429
|
+
async function fireTriggers(db, event, reason, nowMs) {
|
|
8404
8430
|
const triggers = (await listFiringInboxSnoozeTriggers(db, {
|
|
8405
8431
|
eventTypes: [event.eventType],
|
|
8406
8432
|
identifiers: event.identifiers,
|
|
@@ -8414,12 +8440,13 @@ async function fireTriggers(db, event, nowMs) {
|
|
|
8414
8440
|
snoozeIds: [...resolving],
|
|
8415
8441
|
state: "cancelled"
|
|
8416
8442
|
});
|
|
8417
|
-
await
|
|
8443
|
+
await dismissOpenInboxItems(tx, {
|
|
8418
8444
|
ids: resolvedItemIds,
|
|
8419
8445
|
nowMs,
|
|
8420
8446
|
reason: "A snooze trigger resolved it."
|
|
8421
8447
|
});
|
|
8422
8448
|
return (await settleInboxSnoozes(tx, {
|
|
8449
|
+
reason,
|
|
8423
8450
|
snoozeIds: [...waking],
|
|
8424
8451
|
state: "woken"
|
|
8425
8452
|
})).length;
|
|
@@ -8432,6 +8459,11 @@ async function fireInboxSnoozeTriggers(db, event, nowMs = Date.now()) {
|
|
|
8432
8459
|
eventType: event.eventType,
|
|
8433
8460
|
identifiers: [event.identifier],
|
|
8434
8461
|
namespace: event.namespace
|
|
8462
|
+
}, {
|
|
8463
|
+
eventType: event.eventType,
|
|
8464
|
+
identifier: event.identifier,
|
|
8465
|
+
kind: "event",
|
|
8466
|
+
namespace: event.namespace
|
|
8435
8467
|
}, nowMs);
|
|
8436
8468
|
}
|
|
8437
8469
|
/**
|
|
@@ -8487,7 +8519,7 @@ async function runInboxSnoozeTimers(db, nowMs) {
|
|
|
8487
8519
|
eventType: SNOOZE_TIMER_EVENT_TYPE,
|
|
8488
8520
|
identifiers: timerIds,
|
|
8489
8521
|
namespace: CORE_EVENT_NAMESPACE
|
|
8490
|
-
}, nowMs);
|
|
8522
|
+
}, { kind: "time" }, nowMs);
|
|
8491
8523
|
await mapBounded(timerIds, (id) => updateTimerIndex(state, INBOX_SNOOZE_TIMER_INDEX, {
|
|
8492
8524
|
id,
|
|
8493
8525
|
kind: "remove"
|
|
@@ -8605,10 +8637,10 @@ function createHeartbeatContext(args) {
|
|
|
8605
8637
|
db: getDb(),
|
|
8606
8638
|
embedder: createPluginEmbedder(pluginName),
|
|
8607
8639
|
events: args.events,
|
|
8608
|
-
|
|
8640
|
+
inboxItems: { forConversation: (conversationId) => createPluginInboxItems({
|
|
8609
8641
|
conversationId,
|
|
8610
8642
|
plugin: pluginName,
|
|
8611
|
-
show: args.
|
|
8643
|
+
show: args.showInboxItem ?? (async () => {})
|
|
8612
8644
|
}) },
|
|
8613
8645
|
state: createPluginState(pluginName),
|
|
8614
8646
|
log: createPluginLogger(pluginName),
|
|
@@ -8812,29 +8844,28 @@ function treeIsQuiet(run) {
|
|
|
8812
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)))));
|
|
8813
8845
|
return sql`not exists (${active})`;
|
|
8814
8846
|
}
|
|
8815
|
-
const OPEN_PLAN_ITEM_STATUSES = PLAN_ITEM_STATUSES.filter(isOpenPlanItemStatus);
|
|
8816
8847
|
/**
|
|
8817
8848
|
* True when nothing in the participant row's tree needs a person. No
|
|
8818
|
-
* conversation in it has `needs_input` status: an open action
|
|
8849
|
+
* conversation in it has `needs_input` status: an open action Inbox item
|
|
8819
8850
|
* that it added, a sign-in wait, or work that waits on its starter, such
|
|
8820
|
-
* as an answer that the starter has not read. No open
|
|
8851
|
+
* as an answer that the starter has not read. No open To-do in it is
|
|
8821
8852
|
* assigned to a person. Archive applies to everyone, so input that waits
|
|
8822
8853
|
* on anyone keeps the tree. An archived child counts for nothing, as in
|
|
8823
8854
|
* the tree state.
|
|
8824
8855
|
*/
|
|
8825
8856
|
function treeNeedsNoOne() {
|
|
8826
|
-
const assignedToPerson = getDb().select({ id:
|
|
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)));
|
|
8827
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})`)));
|
|
8828
8859
|
return sql`not exists (${needing})`;
|
|
8829
8860
|
}
|
|
8830
8861
|
/**
|
|
8831
|
-
* True when no open
|
|
8862
|
+
* True when no open Inbox item on the participant row's root or a child
|
|
8832
8863
|
* conversation needs a person. Archive applies to everyone, so a
|
|
8833
8864
|
* conversation that waits on anyone must stay in the feed.
|
|
8834
8865
|
*/
|
|
8835
8866
|
function notWaitingOnAnyone() {
|
|
8836
8867
|
const linked = alias(juniorConversations, "linked_conversation");
|
|
8837
|
-
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))));
|
|
8838
8869
|
return sql`not exists (${waiting})`;
|
|
8839
8870
|
}
|
|
8840
8871
|
/**
|
|
@@ -8856,7 +8887,7 @@ function rootIsUnarchived() {
|
|
|
8856
8887
|
}
|
|
8857
8888
|
/**
|
|
8858
8889
|
* Conditions that a participant row must meet when it is selected and again
|
|
8859
|
-
* 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
|
|
8860
8891
|
* changed setting wins over a stale read.
|
|
8861
8892
|
*/
|
|
8862
8893
|
function archivableRow(run) {
|
|
@@ -8996,7 +9027,7 @@ async function setConversationAutoArchive(viewer, conversationId, autoArchive) {
|
|
|
8996
9027
|
});
|
|
8997
9028
|
return { autoArchive };
|
|
8998
9029
|
}
|
|
8999
|
-
// src/chat/
|
|
9030
|
+
// src/chat/inbox-items/automation-answer.ts
|
|
9000
9031
|
function isStepLabel(label) {
|
|
9001
9032
|
return Object.hasOwn(AUTOMATION_ALERT_STEPS, label);
|
|
9002
9033
|
}
|
|
@@ -9216,31 +9247,31 @@ function createEventAppPublisher(args) {
|
|
|
9216
9247
|
}
|
|
9217
9248
|
};
|
|
9218
9249
|
}
|
|
9219
|
-
// src/chat/
|
|
9250
|
+
// src/chat/inbox-items/plugin-answer.ts
|
|
9220
9251
|
/**
|
|
9221
9252
|
* Give the answer of a plugin item with choices to the plugin that added it,
|
|
9222
9253
|
* so the plugin does the work. The answer starts no Turn. Throws when the
|
|
9223
9254
|
* plugin fails, so the person can retry the same answer.
|
|
9224
9255
|
*/
|
|
9225
|
-
async function
|
|
9256
|
+
async function answerPluginInboxItem(args) {
|
|
9226
9257
|
const { item } = args;
|
|
9227
|
-
const pluginName =
|
|
9258
|
+
const pluginName = inboxItemPlugin(item.dedupeKey);
|
|
9228
9259
|
const choice = item.answer?.values[PLUGIN_CHOICE_FIELD_ID]?.[0];
|
|
9229
9260
|
const conversationId = ownerConversationId(item);
|
|
9230
9261
|
if (!pluginName || !choice || !conversationId) return;
|
|
9231
9262
|
const plugin = getPlugins().find((p) => p.manifest.name === pluginName);
|
|
9232
|
-
const hook = plugin?.hooks?.
|
|
9263
|
+
const hook = plugin?.hooks?.inboxItemAnswered;
|
|
9233
9264
|
if (!plugin || !hook) return;
|
|
9234
9265
|
const events = createEventAppPublisher({ conversationWork: () => ({ queue: args.delivery.queue }) });
|
|
9235
9266
|
await hook({
|
|
9236
9267
|
...basePluginContext(plugin),
|
|
9237
9268
|
choice,
|
|
9238
9269
|
conversationId,
|
|
9239
|
-
dedupeKey: item.dedupeKey.slice(`${
|
|
9270
|
+
dedupeKey: item.dedupeKey.slice(`${PLUGIN_INBOX_ITEM_KEY_PREFIX}${pluginName}:`.length),
|
|
9240
9271
|
events: createPluginEventPublisher(plugin, events),
|
|
9241
9272
|
itemId: item.id,
|
|
9242
9273
|
nowMs: args.nowMs,
|
|
9243
|
-
|
|
9274
|
+
inboxItems: { forConversation: (conversationId) => createPluginInboxItems({
|
|
9244
9275
|
conversationId,
|
|
9245
9276
|
plugin: pluginName,
|
|
9246
9277
|
show: args.delivery.show
|
|
@@ -9249,7 +9280,7 @@ async function answerPluginReviewItem(args) {
|
|
|
9249
9280
|
watches: createPluginConversationWatches(plugin, conversationId)
|
|
9250
9281
|
});
|
|
9251
9282
|
}
|
|
9252
|
-
// src/chat/
|
|
9283
|
+
// src/chat/inbox-items/reply-match.ts
|
|
9253
9284
|
const MATCH_CONFIDENCE_THRESHOLD = .7;
|
|
9254
9285
|
/** A slow decision keeps the items open instead of delaying the close. */
|
|
9255
9286
|
const MATCH_TIMEOUT_MS = 1e4;
|
|
@@ -9284,7 +9315,7 @@ function matchQuestion(item) {
|
|
|
9284
9315
|
* decision call judges each item on its own, so a reply can answer one item,
|
|
9285
9316
|
* several items, or none. A failed decision throws.
|
|
9286
9317
|
*/
|
|
9287
|
-
async function
|
|
9318
|
+
async function matchReplyToInboxItems(args) {
|
|
9288
9319
|
const text = args.text.trim();
|
|
9289
9320
|
if (!text || args.items.length === 0) return /* @__PURE__ */ new Set();
|
|
9290
9321
|
const keys = args.items.map((_, index) => `item_${index}`);
|
|
@@ -9294,7 +9325,7 @@ async function matchReplyToReviewItems(args) {
|
|
|
9294
9325
|
modelId: botConfig.decisionModelId
|
|
9295
9326
|
},
|
|
9296
9327
|
modelId: botConfig.decisionModelId,
|
|
9297
|
-
operation: "
|
|
9328
|
+
operation: "inbox_item_reply_match",
|
|
9298
9329
|
cost: { conversationId: args.conversationId },
|
|
9299
9330
|
questions: Object.fromEntries(args.items.map((item, index) => [keys[index], matchQuestion(item)])),
|
|
9300
9331
|
signal: AbortSignal.timeout(MATCH_TIMEOUT_MS),
|
|
@@ -9312,20 +9343,20 @@ async function matchReplyToReviewItems(args) {
|
|
|
9312
9343
|
}
|
|
9313
9344
|
return matched;
|
|
9314
9345
|
}
|
|
9315
|
-
// src/chat/
|
|
9346
|
+
// src/chat/inbox-items/actions.ts
|
|
9316
9347
|
/** An expected failure of a person action, for the API to report. */
|
|
9317
|
-
var
|
|
9348
|
+
var InboxItemActionError = class extends Error {
|
|
9318
9349
|
code;
|
|
9319
9350
|
constructor(code, message) {
|
|
9320
9351
|
super(message);
|
|
9321
|
-
this.name = "
|
|
9352
|
+
this.name = "InboxItemActionError";
|
|
9322
9353
|
this.code = code;
|
|
9323
9354
|
}
|
|
9324
9355
|
};
|
|
9325
|
-
/** Read one
|
|
9326
|
-
async function
|
|
9327
|
-
const item = await
|
|
9328
|
-
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.");
|
|
9329
9360
|
return item;
|
|
9330
9361
|
}
|
|
9331
9362
|
function closedStatus(action) {
|
|
@@ -9354,17 +9385,17 @@ function isSameClose(item, action, user) {
|
|
|
9354
9385
|
return item.closeReason !== "Replied in thread" && item.closedBy?.userId === user.id && item.status === closedStatus(action) && action === "submit" === Boolean(item.answer);
|
|
9355
9386
|
}
|
|
9356
9387
|
function submittedAnswer(item, answer) {
|
|
9357
|
-
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.");
|
|
9358
9389
|
const normalized = normalizeUserInputAnswer(item.request, {
|
|
9359
9390
|
other: answer?.other,
|
|
9360
9391
|
requestId: item.id,
|
|
9361
9392
|
values: answer?.values ?? {}
|
|
9362
9393
|
});
|
|
9363
|
-
if (isEmptyUserInputAnswer(normalized)) throw new
|
|
9394
|
+
if (isEmptyUserInputAnswer(normalized)) throw new InboxItemActionError("invalid", "The answer is empty.");
|
|
9364
9395
|
return normalized;
|
|
9365
9396
|
}
|
|
9366
9397
|
/**
|
|
9367
|
-
* Do one person action on
|
|
9398
|
+
* Do one person action on an Inbox item and tell its linked Conversations.
|
|
9368
9399
|
* The first submit or dismiss closes the item for every
|
|
9369
9400
|
* assignee. A retry of the same close sends any missing messages again and
|
|
9370
9401
|
* succeeds, so a client can retry after a failure. With `firstCloseOnly`,
|
|
@@ -9374,23 +9405,23 @@ function submittedAnswer(item, answer) {
|
|
|
9374
9405
|
* `exceptConversationId` is the Conversation where the person acted. It gets
|
|
9375
9406
|
* the person's input from its own surface, so it gets no message here.
|
|
9376
9407
|
* `delivery` shows the change and sends the messages; see
|
|
9377
|
-
* `
|
|
9408
|
+
* `deliverInboxItemChange`.
|
|
9378
9409
|
*/
|
|
9379
|
-
async function
|
|
9410
|
+
async function actOnInboxItem(args) {
|
|
9380
9411
|
const { action, user } = args;
|
|
9381
9412
|
const nowMs = args.nowMs ?? Date.now();
|
|
9382
9413
|
const db = getDb();
|
|
9383
|
-
const item = await
|
|
9414
|
+
const item = await readInboxItemForUser(user, args.id);
|
|
9384
9415
|
if (action === "take") {
|
|
9385
|
-
if (item.status !== "open") throw new
|
|
9386
|
-
if (!
|
|
9387
|
-
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, {
|
|
9388
9419
|
id: item.id,
|
|
9389
9420
|
nowMs,
|
|
9390
9421
|
userId: user.id
|
|
9391
|
-
})) throw new
|
|
9392
|
-
const taken = await
|
|
9393
|
-
await
|
|
9422
|
+
})) throw new InboxItemActionError("conflict", "Inbox item is closed.");
|
|
9423
|
+
const taken = await readInboxItemForUser(user, item.id);
|
|
9424
|
+
await deliverInboxItemChange({
|
|
9394
9425
|
change: reviewItemChange(action, user),
|
|
9395
9426
|
delivery: args.delivery,
|
|
9396
9427
|
exceptConversationId: args.exceptConversationId,
|
|
@@ -9402,19 +9433,19 @@ async function actOnReviewItem(args) {
|
|
|
9402
9433
|
let closed = item;
|
|
9403
9434
|
let closedNow = false;
|
|
9404
9435
|
if (item.status === "open") {
|
|
9405
|
-
if (!
|
|
9436
|
+
if (!canActOnInboxItem(item, user.id)) throw new InboxItemActionError("forbidden", "Only an assignee can act on this item.");
|
|
9406
9437
|
const answer = action === "submit" ? submittedAnswer(item, args.answer) : void 0;
|
|
9407
|
-
closedNow = await
|
|
9438
|
+
closedNow = await closeInboxItem(db, {
|
|
9408
9439
|
closedByUserId: user.id,
|
|
9409
9440
|
id: item.id,
|
|
9410
9441
|
nowMs,
|
|
9411
9442
|
status: closedStatus(action),
|
|
9412
9443
|
...answer ? { answer } : void 0
|
|
9413
9444
|
});
|
|
9414
|
-
closed = await
|
|
9445
|
+
closed = await readInboxItemForUser(user, item.id);
|
|
9415
9446
|
}
|
|
9416
|
-
if (args.firstCloseOnly ? !closedNow : !isSameClose(closed, action, user)) throw new
|
|
9417
|
-
if (action === "submit" &&
|
|
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({
|
|
9418
9449
|
delivery: args.delivery,
|
|
9419
9450
|
item: closed,
|
|
9420
9451
|
nowMs
|
|
@@ -9425,11 +9456,11 @@ async function actOnReviewItem(args) {
|
|
|
9425
9456
|
user
|
|
9426
9457
|
});
|
|
9427
9458
|
} catch (error) {
|
|
9428
|
-
if (error instanceof ViewerTaskNotFoundError) throw new
|
|
9429
|
-
if (error instanceof AutomationEditError) throw new
|
|
9459
|
+
if (error instanceof ViewerTaskNotFoundError) throw new InboxItemActionError("not_found", "Automation not found.");
|
|
9460
|
+
if (error instanceof AutomationEditError) throw new InboxItemActionError("invalid", error.message);
|
|
9430
9461
|
throw error;
|
|
9431
9462
|
}
|
|
9432
|
-
await
|
|
9463
|
+
await deliverInboxItemChange({
|
|
9433
9464
|
change: reviewItemChange(action, user),
|
|
9434
9465
|
delivery: args.delivery,
|
|
9435
9466
|
exceptConversationId: args.exceptConversationId,
|
|
@@ -9470,21 +9501,21 @@ function messageAnswer(item, text) {
|
|
|
9470
9501
|
* - The replier is an assigned User, or the item has no assignees. A Slack
|
|
9471
9502
|
* replier without a Junior User closes only items with no assignees.
|
|
9472
9503
|
* - The decision model says that the reply answers this item
|
|
9473
|
-
* (`
|
|
9504
|
+
* (`matchReplyToInboxItems`). Other open items in the thread stay open.
|
|
9474
9505
|
* When the decision fails, all items stay open.
|
|
9475
9506
|
*
|
|
9476
9507
|
* Items assigned to Everyone, or only to other people, stay open. They need
|
|
9477
9508
|
* an answer on the card or the Inbox. Each item closes as `done` with
|
|
9478
|
-
* `
|
|
9509
|
+
* `INBOX_ITEM_REPLIED_REASON`, and the replier closes it. The reply itself
|
|
9479
9510
|
* is the answer in this Conversation, so only the other linked
|
|
9480
9511
|
* Conversations get a message. A click that closes the item first wins.
|
|
9481
9512
|
* A retry of the reply, or a later reply from the same person, delivers
|
|
9482
9513
|
* the items that it closed again: the cards show the close, and only the
|
|
9483
9514
|
* missing messages go. Each message has a key, so a message that was sent
|
|
9484
9515
|
* does not go again. `delivery` shows the change and sends the messages;
|
|
9485
|
-
* see `
|
|
9516
|
+
* see `deliverInboxItemChange`.
|
|
9486
9517
|
*/
|
|
9487
|
-
async function
|
|
9518
|
+
async function closeInboxItemsAnsweredByReply(args) {
|
|
9488
9519
|
const db = getDb();
|
|
9489
9520
|
const items = await listReplyActionItems(db, args.conversationId);
|
|
9490
9521
|
if (items.length === 0) return;
|
|
@@ -9494,13 +9525,13 @@ async function closeReviewItemsAnsweredByReply(args) {
|
|
|
9494
9525
|
const answered = items.filter((candidate) => replyAnswers(candidate, user));
|
|
9495
9526
|
let matched;
|
|
9496
9527
|
try {
|
|
9497
|
-
matched = await
|
|
9528
|
+
matched = await matchReplyToInboxItems({
|
|
9498
9529
|
conversationId: args.conversationId,
|
|
9499
9530
|
items: answered.filter((candidate) => candidate.status === "open"),
|
|
9500
9531
|
text: args.text
|
|
9501
9532
|
});
|
|
9502
9533
|
} catch (error) {
|
|
9503
|
-
logWarn("
|
|
9534
|
+
logWarn("inbox_item.reply_match.failed", {
|
|
9504
9535
|
"exception.message": error instanceof Error ? error.message : String(error),
|
|
9505
9536
|
"gen_ai.conversation.id": args.conversationId
|
|
9506
9537
|
});
|
|
@@ -9511,7 +9542,7 @@ async function closeReviewItemsAnsweredByReply(args) {
|
|
|
9511
9542
|
let closedItem = item;
|
|
9512
9543
|
if (item.status === "open") {
|
|
9513
9544
|
const answer = messageAnswer(item, args.text);
|
|
9514
|
-
if (!await
|
|
9545
|
+
if (!await closeInboxItem(db, {
|
|
9515
9546
|
...answer ? { answer } : void 0,
|
|
9516
9547
|
id: item.id,
|
|
9517
9548
|
nowMs,
|
|
@@ -9519,10 +9550,10 @@ async function closeReviewItemsAnsweredByReply(args) {
|
|
|
9519
9550
|
status: "done",
|
|
9520
9551
|
...user ? { closedByUserId: user.id } : void 0
|
|
9521
9552
|
})) continue;
|
|
9522
|
-
closedItem = await
|
|
9553
|
+
closedItem = await getInboxItem(db, item.id);
|
|
9523
9554
|
if (!closedItem) continue;
|
|
9524
9555
|
}
|
|
9525
|
-
await
|
|
9556
|
+
await deliverInboxItemChange({
|
|
9526
9557
|
change: {
|
|
9527
9558
|
kind: "replied",
|
|
9528
9559
|
who: user ? user.displayName ?? user.email : "A person"
|
|
@@ -9534,81 +9565,6 @@ async function closeReviewItemsAnsweredByReply(args) {
|
|
|
9534
9565
|
});
|
|
9535
9566
|
}
|
|
9536
9567
|
}
|
|
9537
|
-
// src/chat/conversations/stop.ts
|
|
9538
|
-
/**
|
|
9539
|
-
* Stop a Conversation for a person, on every stop path. Every child agent
|
|
9540
|
-
* below it stops, then it and they are stopped Conversations until a person
|
|
9541
|
-
* sends input, and then its Turn stops. A Turn that waits for sign-in ends
|
|
9542
|
-
* too, so a later sign-in does not resume it. Their Watch Events are saved
|
|
9543
|
-
* and start no Turn. Nothing above it changes: a stopped child agent's worker
|
|
9544
|
-
* reports the stop to its parent.
|
|
9545
|
-
*
|
|
9546
|
-
* A stop that comes from a message or a button press, such as the Slack
|
|
9547
|
-
* `stop` keyword or stop button, passes it. Its id is claimed in the mailbox
|
|
9548
|
-
* first, so a redelivery returns `duplicate` and stops nothing, not even
|
|
9549
|
-
* newer work. A stop that fails before its stop request is saved releases
|
|
9550
|
-
* its claim, so a redelivery can stop again. A failed claim check keeps a
|
|
9551
|
-
* claim that an earlier delivery saved. A failure after the stop request is
|
|
9552
|
-
* saved keeps the claim, as does a failed reply: the work is already
|
|
9553
|
-
* stopped, and a redelivery must not stop newer work. Its send time
|
|
9554
|
-
* is the stop time, and only person input sent at or before it is dropped.
|
|
9555
|
-
* So a retry writes the same stop and keeps input that the person sent after
|
|
9556
|
-
* it.
|
|
9557
|
-
*
|
|
9558
|
-
* The child agents and sessions stop first, so a failure leaves the Turn
|
|
9559
|
-
* running and the stop can be retried. A child agent can outlive the parent
|
|
9560
|
-
* Turn, so this runs even when no Turn runs.
|
|
9561
|
-
*/
|
|
9562
|
-
async function stopConversation(args) {
|
|
9563
|
-
if (args.message && (await claimInboundMessage({
|
|
9564
|
-
conversationStore: args.conversationStore,
|
|
9565
|
-
message: args.message,
|
|
9566
|
-
state: args.state
|
|
9567
|
-
})).status === "duplicate") return { status: "duplicate" };
|
|
9568
|
-
let stopSaved = false;
|
|
9569
|
-
try {
|
|
9570
|
-
const nowMs = Date.now();
|
|
9571
|
-
const stoppedAtMs = args.message?.createdAtMs ?? nowMs;
|
|
9572
|
-
await stopChildAgentsBelow(args.conversationId, {
|
|
9573
|
-
nowMs,
|
|
9574
|
-
stoppedAtMs,
|
|
9575
|
-
state: args.state
|
|
9576
|
-
});
|
|
9577
|
-
await markConversationsStopped([args.conversationId], {
|
|
9578
|
-
cancelWatches: false,
|
|
9579
|
-
nowMs: stoppedAtMs,
|
|
9580
|
-
state: args.state
|
|
9581
|
-
});
|
|
9582
|
-
await dropOwnUnreadLoopReplies(args.conversationId, args.state);
|
|
9583
|
-
await cancelSignInWait(args.conversationId);
|
|
9584
|
-
const result = await stopConversationWork({
|
|
9585
|
-
conversationId: args.conversationId,
|
|
9586
|
-
conversationStore: args.conversationStore,
|
|
9587
|
-
nowMs,
|
|
9588
|
-
onStopSaved: () => {
|
|
9589
|
-
stopSaved = true;
|
|
9590
|
-
},
|
|
9591
|
-
sentAtOrBeforeMs: args.message ? stoppedAtMs : void 0,
|
|
9592
|
-
state: args.state
|
|
9593
|
-
});
|
|
9594
|
-
if (result.status === "requested") await ensureConversationWake({
|
|
9595
|
-
conversationId: args.conversationId,
|
|
9596
|
-
conversationStore: args.conversationStore,
|
|
9597
|
-
idempotencyKey: `conversation-stop:${args.conversationId}:${result.runId}`,
|
|
9598
|
-
nowMs,
|
|
9599
|
-
queue: args.queue,
|
|
9600
|
-
replaceExistingWake: true,
|
|
9601
|
-
state: args.state
|
|
9602
|
-
});
|
|
9603
|
-
return result;
|
|
9604
|
-
} catch (error) {
|
|
9605
|
-
if (args.message && !stopSaved) await releaseInboundMessage({
|
|
9606
|
-
message: args.message,
|
|
9607
|
-
state: args.state
|
|
9608
|
-
});
|
|
9609
|
-
throw error;
|
|
9610
|
-
}
|
|
9611
|
-
}
|
|
9612
9568
|
// src/api/mentions.ts
|
|
9613
9569
|
function mentionedSlackUserIds(texts) {
|
|
9614
9570
|
const ids = texts.flatMap((text) => text ? slackMentionedUserIds(text) : []);
|
|
@@ -9864,11 +9820,209 @@ async function requireConversationPendingMessages(conversationId, options = {})
|
|
|
9864
9820
|
if (!report) throwApiError(404, "Conversation not found.");
|
|
9865
9821
|
return report;
|
|
9866
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
|
+
}
|
|
9867
10021
|
// src/api/conversations/cancel-pending-messages.ts
|
|
9868
10022
|
/** Cancel accepted human-facing mailbox rows for one conversation participant. */
|
|
9869
10023
|
async function cancelConversationPendingMessagesForViewer(viewer, conversationId, body = {}) {
|
|
9870
10024
|
if (!await getConversationStore().get({ conversationId })) throwApiError(404, "Conversation not found.");
|
|
9871
|
-
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.");
|
|
9872
10026
|
try {
|
|
9873
10027
|
const result = await cancelHumanFacingPendingMessages({
|
|
9874
10028
|
conversationId,
|
|
@@ -9889,6 +10043,243 @@ async function cancelConversationPendingMessagesForViewer(viewer, conversationId
|
|
|
9889
10043
|
throwApiError(500, "Unable to cancel queued messages.", error);
|
|
9890
10044
|
}
|
|
9891
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
|
+
];
|
|
9892
10283
|
// src/api/conversations/cursor.ts
|
|
9893
10284
|
const CURSOR_CONTEXT = "junior-conversation-report-cursor";
|
|
9894
10285
|
const conversationCursorPayloadSchema = z.object({
|
|
@@ -9994,8 +10385,8 @@ async function createConversationForViewer(viewer, body, services) {
|
|
|
9994
10385
|
throwApiError(500, "Unable to create conversation.", error);
|
|
9995
10386
|
}
|
|
9996
10387
|
}
|
|
9997
|
-
/** Append one
|
|
9998
|
-
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) {
|
|
9999
10390
|
await requireWebMessageConversation(viewer, conversationId, body.idempotencyKey);
|
|
10000
10391
|
const uploads = await verifyUploads({
|
|
10001
10392
|
conversationId,
|
|
@@ -10006,6 +10397,7 @@ async function appendConversationMessageForViewer(viewer, conversationId, body,
|
|
|
10006
10397
|
const append = () => appendAndEnqueueWebMessage({
|
|
10007
10398
|
actor,
|
|
10008
10399
|
conversationId,
|
|
10400
|
+
delivery,
|
|
10009
10401
|
idempotencyKey: body.idempotencyKey,
|
|
10010
10402
|
message: body.message,
|
|
10011
10403
|
uploads
|
|
@@ -10014,11 +10406,11 @@ async function appendConversationMessageForViewer(viewer, conversationId, body,
|
|
|
10014
10406
|
attachmentStorage: services.attachmentStorage,
|
|
10015
10407
|
queue: services.queue
|
|
10016
10408
|
});
|
|
10017
|
-
const closeAnswered = () =>
|
|
10409
|
+
const closeAnswered = () => closeInboxItemsAnsweredByReply({
|
|
10018
10410
|
conversationId,
|
|
10019
10411
|
delivery: {
|
|
10020
10412
|
queue: services.queue,
|
|
10021
|
-
show:
|
|
10413
|
+
show: createSlackInboxItemShow(getProductionSlackAdapter)
|
|
10022
10414
|
},
|
|
10023
10415
|
resolveUser: async () => viewer,
|
|
10024
10416
|
text: body.message
|
|
@@ -10671,15 +11063,6 @@ function eventMentionTexts(data) {
|
|
|
10671
11063
|
default: return [];
|
|
10672
11064
|
}
|
|
10673
11065
|
}
|
|
10674
|
-
function briefMentionTexts(brief) {
|
|
10675
|
-
return [
|
|
10676
|
-
brief.summary,
|
|
10677
|
-
brief.intent,
|
|
10678
|
-
brief.outcome.text,
|
|
10679
|
-
...brief.decisions.flatMap((decision) => [decision.text, decision.by]),
|
|
10680
|
-
...brief.facts
|
|
10681
|
-
];
|
|
10682
|
-
}
|
|
10683
11066
|
function withMentions(value, mentions) {
|
|
10684
11067
|
return mentions.length > 0 ? {
|
|
10685
11068
|
...value,
|
|
@@ -10687,7 +11070,7 @@ function withMentions(value, mentions) {
|
|
|
10687
11070
|
} : value;
|
|
10688
11071
|
}
|
|
10689
11072
|
/**
|
|
10690
|
-
* Attach the people that each event and the
|
|
11073
|
+
* Attach the people that each event and the summary of one conversation
|
|
10691
11074
|
* mention, resolved at read time.
|
|
10692
11075
|
*/
|
|
10693
11076
|
async function attachConversationMentions(executor, conversationId, content) {
|
|
@@ -10696,14 +11079,14 @@ async function attachConversationMentions(executor, conversationId, content) {
|
|
|
10696
11079
|
tenantId,
|
|
10697
11080
|
texts: eventMentionTexts(event.data)
|
|
10698
11081
|
}));
|
|
10699
|
-
if (content.
|
|
11082
|
+
if (content.summary) sources.push({
|
|
10700
11083
|
tenantId,
|
|
10701
|
-
texts:
|
|
11084
|
+
texts: [content.summary]
|
|
10702
11085
|
});
|
|
10703
11086
|
const mentions = await resolveMentions(executor, sources);
|
|
10704
11087
|
return {
|
|
10705
|
-
|
|
10706
|
-
|
|
11088
|
+
events: content.events.map((event, index) => withMentions(event, mentions[index])),
|
|
11089
|
+
summaryMentions: content.summary ? mentions.at(-1) : []
|
|
10707
11090
|
};
|
|
10708
11091
|
}
|
|
10709
11092
|
/**
|
|
@@ -10877,16 +11260,19 @@ const agentTreeRoot = alias(juniorConversations, "detail_agent_tree_root");
|
|
|
10877
11260
|
function agentTreeRootLabel(db, rootConversationId) {
|
|
10878
11261
|
return db.select({ label: sql`row(${agentTreeRoot.title}, ${agentTreeRoot.channelName})::text` }).from(agentTreeRoot).where(eq(agentTreeRoot.conversationId, rootConversationId));
|
|
10879
11262
|
}
|
|
11263
|
+
const SUBTREE = "detail_subtree";
|
|
10880
11264
|
/**
|
|
10881
|
-
* 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
|
|
10882
11267
|
* writes bump only their own row, and the row count changes when a child
|
|
10883
11268
|
* starts, so the parent needs no bump of its own.
|
|
10884
11269
|
*/
|
|
10885
|
-
function
|
|
11270
|
+
function subtreeDetailVersions(conversationIds) {
|
|
10886
11271
|
return getDb().select({
|
|
11272
|
+
conversationId: sql`${conversationSubtreeColumns.scopeConversationId}`.as("conversation_id"),
|
|
10887
11273
|
conversations: sql`count(*)::int`.as("conversations"),
|
|
10888
11274
|
version: sql`coalesce(sum(${juniorConversations.detailVersion}), 0)::text`.as("version")
|
|
10889
|
-
}).from(juniorConversations).innerJoin(conversationSubtree(
|
|
11275
|
+
}).from(juniorConversations).innerJoin(conversationSubtree(conversationIds), eq(conversationSubtreeColumns.conversationId, juniorConversations.conversationId)).groupBy(conversationSubtreeColumns.scopeConversationId).as(SUBTREE);
|
|
10890
11276
|
}
|
|
10891
11277
|
const versionConversation = alias(juniorConversations, "version_conversation");
|
|
10892
11278
|
const versionFork = alias(juniorConversations, "version_fork");
|
|
@@ -10896,7 +11282,8 @@ const versionUser = alias(juniorUsers, "version_user");
|
|
|
10896
11282
|
* Hash the detail state whose writes do not bump `detail_version`: the
|
|
10897
11283
|
* viewer's marks and auto-archive choice on the root, the forks, and the
|
|
10898
11284
|
* matched Slack files. Each part is a lookup by key, so the versions poll
|
|
10899
|
-
* stays one cheap statement.
|
|
11285
|
+
* stays one cheap statement. `conversationId` is the id column of the
|
|
11286
|
+
* outer row.
|
|
10900
11287
|
*/
|
|
10901
11288
|
function viewerStateVersion(db, conversationId, viewerId) {
|
|
10902
11289
|
const root = db.select({ id: sql`coalesce(${versionConversation.rootConversationId}, ${versionConversation.conversationId})` }).from(versionConversation).where(eq(versionConversation.conversationId, conversationId));
|
|
@@ -10911,15 +11298,28 @@ function viewerStateVersion(db, conversationId, viewerId) {
|
|
|
10911
11298
|
))`;
|
|
10912
11299
|
}
|
|
10913
11300
|
/**
|
|
10914
|
-
* Return a query for the change token of
|
|
10915
|
-
* agents, as the viewer sees it,
|
|
10916
|
-
* detail report sends the same token, so the dashboard
|
|
10917
|
-
* 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.
|
|
10918
11319
|
*/
|
|
10919
11320
|
function conversationVersionQuery(db, conversationId, viewerId) {
|
|
10920
|
-
const
|
|
10921
|
-
|
|
10922
|
-
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);
|
|
10923
11323
|
}
|
|
10924
11324
|
/**
|
|
10925
11325
|
* Read the record and the stored rows that the detail state needs in one
|
|
@@ -11351,7 +11751,7 @@ const WATCH_LOOKUP_LIMIT = 50;
|
|
|
11351
11751
|
* a Turn waits on the User to sign in.
|
|
11352
11752
|
*/
|
|
11353
11753
|
function needsUserSql(userId) {
|
|
11354
|
-
return sql`(exists (select 1 from ${
|
|
11754
|
+
return sql`(exists (select 1 from ${juniorInboxItems} where ${and(inboxItemOwnedByConversation(juniorConversations.conversationId), inboxItemNeedsInput(), inboxItemForUser(userId))}) or ${awaitsAuthorizationFrom(juniorConversations.conversationId, userId)})`;
|
|
11355
11755
|
}
|
|
11356
11756
|
/**
|
|
11357
11757
|
* Read the tree state of each Conversation for one viewer, over the
|
|
@@ -11421,7 +11821,7 @@ function projectConversationDetail(args) {
|
|
|
11421
11821
|
}),
|
|
11422
11822
|
annotations: canExposePayload ? args.annotations : [],
|
|
11423
11823
|
sidebarAnnotations: canExposePayload ? args.sidebarAnnotations : void 0,
|
|
11424
|
-
...canExposePayload && args.
|
|
11824
|
+
...canExposePayload && args.summaryMentions ? { summaryMentions: args.summaryMentions } : void 0,
|
|
11425
11825
|
events: args.events,
|
|
11426
11826
|
...args.appended ? { appended: true } : void 0,
|
|
11427
11827
|
...args.appendCursor ? { appendCursor: args.appendCursor } : void 0,
|
|
@@ -11483,7 +11883,7 @@ async function readConversationDetailFromSql(conversationId, options) {
|
|
|
11483
11883
|
limit: options.limit
|
|
11484
11884
|
});
|
|
11485
11885
|
};
|
|
11486
|
-
const [agentTree, annotations, automationTitleByConversation, auxiliaryCostsByConversation,
|
|
11886
|
+
const [agentTree, annotations, automationTitleByConversation, auxiliaryCostsByConversation, firstHumanMessageTextByConversation, modelUsage, metricsByConversation, people, sourceTask, teamDomainByTeamId, treeStateByConversation, page] = await Promise.all([
|
|
11487
11887
|
readConversationAgentTree({
|
|
11488
11888
|
conversationId,
|
|
11489
11889
|
...record.conversation.parentConversationId ? { parentConversationId: record.conversation.parentConversationId } : void 0
|
|
@@ -11497,7 +11897,6 @@ async function readConversationDetailFromSql(conversationId, options) {
|
|
|
11497
11897
|
})),
|
|
11498
11898
|
readAutomationTitlesByConversationId([record.conversation]),
|
|
11499
11899
|
readConversationAuxiliaryCostsFromSql(getDb(), [conversationId]),
|
|
11500
|
-
readLatestConversationBrief(getDb(), conversationId),
|
|
11501
11900
|
readFirstHumanMessageTexts(getDb(), [record.conversation]),
|
|
11502
11901
|
isPurged ? Promise.resolve([]) : readConversationModelUsageFromSql(executor, { conversationId }),
|
|
11503
11902
|
readConversationTreeMetricsFromSql(getDb(), [conversationId]),
|
|
@@ -11512,14 +11911,14 @@ async function readConversationDetailFromSql(conversationId, options) {
|
|
|
11512
11911
|
]);
|
|
11513
11912
|
const firstSeq = page.events[0]?.seq;
|
|
11514
11913
|
const unreadAfterSeq = readPosition !== void 0 && page.previousSeq !== void 0 && firstSeq !== void 0 && readPosition.lastReadSeq + 1 < firstSeq ? readPosition.lastReadSeq : void 0;
|
|
11515
|
-
const
|
|
11516
|
-
const [{
|
|
11914
|
+
const summary = canExposePayload ? record.conversation.summary : void 0;
|
|
11915
|
+
const [{ events, summaryMentions }, unreadPage, sidebarAnnotations] = await Promise.all([
|
|
11517
11916
|
startSpan({
|
|
11518
11917
|
name: "Attach conversation mentions",
|
|
11519
11918
|
op: "function"
|
|
11520
11919
|
}, () => attachConversationMentions(executor, conversationId, {
|
|
11521
|
-
|
|
11522
|
-
|
|
11920
|
+
events: page.events.map(formatConversationEventText),
|
|
11921
|
+
...summary ? { summary } : void 0
|
|
11523
11922
|
})),
|
|
11524
11923
|
options.unreadPage && unreadAfterSeq !== void 0 ? readConversationEventPageAround(executor, {
|
|
11525
11924
|
canExposePayload,
|
|
@@ -11552,12 +11951,7 @@ async function readConversationDetailFromSql(conversationId, options) {
|
|
|
11552
11951
|
sidebarAnnotations,
|
|
11553
11952
|
auxiliaryCosts: auxiliaryCosts?.total,
|
|
11554
11953
|
...childAgentTotals ? { childAgentTotals } : void 0,
|
|
11555
|
-
...
|
|
11556
|
-
content: briefVersion.content,
|
|
11557
|
-
...briefMentions.length > 0 ? { mentions: briefMentions } : void 0,
|
|
11558
|
-
updatedAt: briefVersion.createdAt.toISOString(),
|
|
11559
|
-
version: briefVersion.version
|
|
11560
|
-
} } : void 0,
|
|
11954
|
+
...summaryMentions.length > 0 ? { summaryMentions } : void 0,
|
|
11561
11955
|
durationMs: metrics?.durationMs ?? record.durationMs,
|
|
11562
11956
|
events,
|
|
11563
11957
|
firstHumanMessageText: firstHumanMessageTextByConversation.get(conversationId),
|
|
@@ -11603,97 +11997,21 @@ async function readConversationDetail(conversationId, options = {}) {
|
|
|
11603
11997
|
} : { limit: options.limit }
|
|
11604
11998
|
});
|
|
11605
11999
|
}
|
|
11606
|
-
// src/
|
|
11607
|
-
/**
|
|
11608
|
-
* Pin or unpin one conversation for the signed-in viewer.
|
|
11609
|
-
*
|
|
11610
|
-
* A pin lives on the viewer's participant row, and that row grants send and
|
|
11611
|
-
* control access. So only a participant can pin, the same as archive. A pin
|
|
11612
|
-
* also restores an archived conversation for everyone, because the Pinned
|
|
11613
|
-
* section shows only active conversations. A pin on a child would be a fact
|
|
11614
|
-
* of the child, not of the viewer's root, and no list shows child pins yet,
|
|
11615
|
-
* so only a root can be pinned.
|
|
11616
|
-
*/
|
|
11617
|
-
async function pinConversation(viewer, conversationId, body) {
|
|
11618
|
-
if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(404, "Conversation not found.");
|
|
11619
|
-
const executor = getSqlExecutor();
|
|
11620
|
-
return await executor.transaction(async () => {
|
|
11621
|
-
const db = executor.db();
|
|
11622
|
-
const result = await setPin(db, viewer, conversationId, body.pinned);
|
|
11623
|
-
recordPinUsage(body.pinned ? "pin" : "unpin", await countViewerPins(db, viewer));
|
|
11624
|
-
return result;
|
|
11625
|
-
});
|
|
11626
|
-
}
|
|
11627
|
-
/**
|
|
11628
|
-
* Tag the request span with a pin change and the viewer's pin count after
|
|
11629
|
-
* it. Pins stay manual; this shows how much people use them.
|
|
11630
|
-
*/
|
|
11631
|
-
function recordPinUsage(action, pinnedCount) {
|
|
11632
|
-
setSpanAttributes({
|
|
11633
|
-
"app.conversation.pin.action": action,
|
|
11634
|
-
"app.conversation.pin.count": pinnedCount
|
|
11635
|
-
});
|
|
11636
|
-
}
|
|
11637
|
-
async function countViewerPins(db, viewer) {
|
|
11638
|
-
const [row] = await db.select({ pins: count() }).from(juniorConversationParticipants).where(and(eq(juniorConversationParticipants.userId, viewer.id), isNotNull(juniorConversationParticipants.pinnedAt)));
|
|
11639
|
-
return row?.pins ?? 0;
|
|
11640
|
-
}
|
|
11641
|
-
async function setPin(db, viewer, conversationId, pinned) {
|
|
11642
|
-
const [conversation] = await db.select({
|
|
11643
|
-
archivedAt: juniorConversations.archivedAt,
|
|
11644
|
-
kind: juniorConversations.kind,
|
|
11645
|
-
lastActivityAt: juniorConversations.lastActivityAt,
|
|
11646
|
-
parentConversationId: juniorConversations.parentConversationId,
|
|
11647
|
-
rootConversationId: juniorConversations.rootConversationId
|
|
11648
|
-
}).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId)).limit(1).for("no key update");
|
|
11649
|
-
if (!conversation) throwApiError(404, "Conversation not found.");
|
|
11650
|
-
if (!isTopLevelKind(conversationKindFromRow(conversation))) throwApiError(409, `A child conversation cannot be pinned or unpinned. It uses its root's pin: ${conversation.rootConversationId ?? conversation.parentConversationId}.`);
|
|
11651
|
-
if (!pinned) {
|
|
11652
|
-
await db.update(juniorConversationParticipants).set({
|
|
11653
|
-
pinnedAt: null,
|
|
11654
|
-
pinPosition: null
|
|
11655
|
-
}).where(and(eq(juniorConversationParticipants.userId, viewer.id), eq(juniorConversationParticipants.rootConversationId, conversationId)));
|
|
11656
|
-
return { pinnedAt: null };
|
|
11657
|
-
}
|
|
11658
|
-
if (conversation.archivedAt) await setArchivedAt(db, [conversationId], null);
|
|
11659
|
-
const pinnedAt = /* @__PURE__ */ new Date();
|
|
11660
|
-
await db.insert(juniorConversationParticipants).values({
|
|
11661
|
-
lastMessageAt: conversation.lastActivityAt,
|
|
11662
|
-
pinnedAt,
|
|
11663
|
-
rootConversationId: conversationId,
|
|
11664
|
-
userId: viewer.id
|
|
11665
|
-
}).onConflictDoUpdate({
|
|
11666
|
-
target: [juniorConversationParticipants.userId, juniorConversationParticipants.rootConversationId],
|
|
11667
|
-
set: {
|
|
11668
|
-
pinnedAt,
|
|
11669
|
-
pinPosition: null,
|
|
11670
|
-
unsubscribedAt: null
|
|
11671
|
-
}
|
|
11672
|
-
});
|
|
11673
|
-
return { pinnedAt: pinnedAt.toISOString() };
|
|
11674
|
-
}
|
|
12000
|
+
// src/chat/conversations/sql/listed.ts
|
|
11675
12001
|
/**
|
|
11676
|
-
*
|
|
11677
|
-
*
|
|
11678
|
-
* 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.
|
|
11679
12004
|
*/
|
|
11680
|
-
|
|
11681
|
-
|
|
11682
|
-
const participants = juniorConversationParticipants;
|
|
11683
|
-
const positions = sql.join(ids.map((id, index) => sql`when ${id} then ${index}::integer`), sql` `);
|
|
11684
|
-
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 });
|
|
11685
|
-
recordPinUsage("reorder", updated.length);
|
|
11686
|
-
const updatedIds = new Set(updated.map((row) => row.rootConversationId));
|
|
11687
|
-
return { conversationIds: ids.filter((id) => updatedIds.has(id)) };
|
|
12005
|
+
function notLeadConversation() {
|
|
12006
|
+
return or(isNull(juniorConversations.kind), ne(juniorConversations.kind, "lead"));
|
|
11688
12007
|
}
|
|
11689
|
-
// src/chat/conversations/sql/listed.ts
|
|
11690
12008
|
/**
|
|
11691
12009
|
* Match Conversations that lists and searches may show: roots that are not
|
|
11692
|
-
* an unkept Quick question. Each list adds its own access and
|
|
11693
|
-
* 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.
|
|
11694
12012
|
*/
|
|
11695
12013
|
function listedConversation() {
|
|
11696
|
-
return and(isNull(juniorConversations.parentConversationId), isNull(juniorConversations.quickQuestionAt));
|
|
12014
|
+
return and(isNull(juniorConversations.parentConversationId), isNull(juniorConversations.quickQuestionAt), notLeadConversation());
|
|
11697
12015
|
}
|
|
11698
12016
|
// src/api/conversations/threads.ts
|
|
11699
12017
|
/**
|
|
@@ -11842,29 +12160,6 @@ async function readConversationActivityPreviews(db, conversationIds) {
|
|
|
11842
12160
|
}
|
|
11843
12161
|
return previews;
|
|
11844
12162
|
}
|
|
11845
|
-
// src/api/conversations/feed-brief.ts
|
|
11846
|
-
/**
|
|
11847
|
-
* Read the latest Brief version of each Conversation on a feed page, in one
|
|
11848
|
-
* query. A lateral limit reads one row per Conversation from the
|
|
11849
|
-
* (conversation, version) key, so long Brief histories do not slow the feed.
|
|
11850
|
-
* Callers show the result only when the viewer can see private content.
|
|
11851
|
-
*/
|
|
11852
|
-
async function readConversationFeedBriefs(db, conversationIds) {
|
|
11853
|
-
if (conversationIds.length === 0) return /* @__PURE__ */ new Map();
|
|
11854
|
-
const content = juniorConversationBriefs.content;
|
|
11855
|
-
const latest = db.select({
|
|
11856
|
-
intent: sql`${content}->>'intent'`.as("intent"),
|
|
11857
|
-
status: sql`${content}->'outcome'->>'status'`.as("status"),
|
|
11858
|
-
summary: sql`${content}->>'summary'`.as("summary")
|
|
11859
|
-
}).from(juniorConversationBriefs).where(eq(juniorConversationBriefs.conversationId, juniorConversations.conversationId)).orderBy(desc(juniorConversationBriefs.version)).limit(1).as("latest_brief");
|
|
11860
|
-
const rows = await db.select({
|
|
11861
|
-
conversationId: juniorConversations.conversationId,
|
|
11862
|
-
intent: latest.intent,
|
|
11863
|
-
status: latest.status,
|
|
11864
|
-
summary: latest.summary
|
|
11865
|
-
}).from(juniorConversations).innerJoinLateral(latest, sql`true`).where(inArray(juniorConversations.conversationId, conversationIds));
|
|
11866
|
-
return new Map(rows.map(({ conversationId, ...brief }) => [conversationId, conversationFeedBriefSchema.parse(brief)]));
|
|
11867
|
-
}
|
|
11868
12163
|
// src/api/conversations/feed-links.ts
|
|
11869
12164
|
const RECENT_USE_LIMIT = 20;
|
|
11870
12165
|
const CANDIDATE_LINK_LIMIT = 6;
|
|
@@ -11933,13 +12228,13 @@ function feedMediaSql(db) {
|
|
|
11933
12228
|
}
|
|
11934
12229
|
// src/api/conversations/feed-answer.ts
|
|
11935
12230
|
/**
|
|
11936
|
-
* A feed row column with the viewer's newest answered
|
|
12231
|
+
* A feed row column with the viewer's newest answered Inbox item of its
|
|
11937
12232
|
* Conversation, or null. It is a scalar subquery on the row read, so the
|
|
11938
12233
|
* answer costs no round trip of its own, however many items the viewer
|
|
11939
12234
|
* closed since.
|
|
11940
12235
|
*/
|
|
11941
12236
|
function feedViewerAnswerSql(db, userId) {
|
|
11942
|
-
const latest = db.select({ answer: sql`jsonb_build_object('answer', ${
|
|
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);
|
|
11943
12238
|
return sql`(${latest})`;
|
|
11944
12239
|
}
|
|
11945
12240
|
/**
|
|
@@ -12014,30 +12309,30 @@ function conversationCodeRepositoryFilter(repositoryId, viewerUserId) {
|
|
|
12014
12309
|
)
|
|
12015
12310
|
)`, rootVisibleToViewer(viewerUserId));
|
|
12016
12311
|
}
|
|
12017
|
-
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 }) {
|
|
12018
12313
|
const rows = db.select({
|
|
12019
12314
|
...conversationRecordColumns(),
|
|
12020
12315
|
activityCursor: sql`to_char(${juniorConversations.lastActivityAt} at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`,
|
|
12021
12316
|
lastMessageAt: sql`coalesce(${juniorConversations.lastMessageAt}, ${lastMessageAtSql(db)})`.mapWith(juniorConversations.lastMessageAt),
|
|
12022
12317
|
awaitingAuthorization: treeAwaitsAuthorization(juniorConversations.conversationId),
|
|
12318
|
+
latestTurnFailed: conversationTurnFailedSql(juniorConversations),
|
|
12023
12319
|
links: include.includes("links") ? feedLinksSql(db) : sql`null`,
|
|
12024
12320
|
media: include.includes("media") ? feedMediaSql(db) : sql`null`,
|
|
12025
12321
|
viewerAnswer: filter?.kind === "viewer" ? feedViewerAnswerSql(db, filter.userId) : sql`null`
|
|
12026
|
-
}).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`, sql`
|
|
12027
|
-
select 1
|
|
12028
|
-
from ${juniorConversationBriefs}
|
|
12029
|
-
where ${juniorConversationBriefs.conversationId} = ${juniorConversations.conversationId}
|
|
12030
|
-
and ${includePrivateBriefs ? sql`true` : eq(juniorDestinations.visibility, "public")}
|
|
12031
|
-
and ${juniorConversationBriefs.version} = (
|
|
12032
|
-
select max(${juniorConversationBriefs.version})
|
|
12033
|
-
from ${juniorConversationBriefs}
|
|
12034
|
-
where ${juniorConversationBriefs.conversationId} = ${juniorConversations.conversationId}
|
|
12035
|
-
)
|
|
12036
|
-
and to_tsvector('english', ${juniorConversationBriefs.searchText})
|
|
12037
|
-
@@ websearch_to_tsquery('english', ${query})
|
|
12038
|
-
)`) : void 0)).orderBy(desc(juniorConversations.lastActivityAt), asc(juniorConversations.conversationId)).$dynamic();
|
|
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();
|
|
12039
12323
|
return limit === void 0 ? rows : rows.limit(limit);
|
|
12040
12324
|
}
|
|
12325
|
+
const searchAnnotated = alias(juniorConversations, "search_annotated");
|
|
12326
|
+
/**
|
|
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.
|
|
12331
|
+
*/
|
|
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`)));
|
|
12335
|
+
}
|
|
12041
12336
|
/**
|
|
12042
12337
|
* Feed rows show last activity only as an age in whole minutes. A running
|
|
12043
12338
|
* row shows its running state in place of the age, so it shows no activity.
|
|
@@ -12072,7 +12367,7 @@ const feedAnnotated = alias(juniorConversations, "feed_annotated");
|
|
|
12072
12367
|
* The rows are in feed order, so a move that reorders them moves the token.
|
|
12073
12368
|
* The newest Message of each role stands for the preview and participants.
|
|
12074
12369
|
* Threads and annotations show from the whole tree. Waiting roots outside
|
|
12075
|
-
* the page move the
|
|
12370
|
+
* the page move the Inbox items token.
|
|
12076
12371
|
*/
|
|
12077
12372
|
function conversationFeedVersionQuery(db, userId) {
|
|
12078
12373
|
const pin = juniorConversationParticipants;
|
|
@@ -12081,7 +12376,7 @@ function conversationFeedVersionQuery(db, userId) {
|
|
|
12081
12376
|
count(*) filter (where ${feedTree.archivedAt} is not null),
|
|
12082
12377
|
count(*) filter (where ${feedTree.stoppedAt} is not null),
|
|
12083
12378
|
coalesce(bool_or(${conversationIsActiveSql(feedTree)}) filter (where ${ne(feedTree.conversationId, conversationId)}), false),
|
|
12084
|
-
bool_or(exists (select 1 from ${
|
|
12379
|
+
bool_or(exists (select 1 from ${juniorInboxItems} where ${and(inboxItemOwnedByConversation(feedTree.conversationId), inboxItemNeedsInput(), inboxItemForUser(userId))}) or ${awaitsAuthorizationFrom(feedTree.conversationId, userId)}),
|
|
12085
12380
|
string_agg(concat_ws('/',
|
|
12086
12381
|
${feedTree.conversationId}, ${feedTree.title},
|
|
12087
12382
|
${conversationStatusSql(feedTree)},
|
|
@@ -12163,7 +12458,7 @@ async function readConversationFeedFromSql(options = {}) {
|
|
|
12163
12458
|
} } : void 0,
|
|
12164
12459
|
filter,
|
|
12165
12460
|
include,
|
|
12166
|
-
|
|
12461
|
+
includePrivateMatches: filter?.kind === "viewer",
|
|
12167
12462
|
query,
|
|
12168
12463
|
status
|
|
12169
12464
|
};
|
|
@@ -12188,7 +12483,7 @@ async function readConversationFeedFromSql(options = {}) {
|
|
|
12188
12483
|
firstPage ? conversationRows(db, {
|
|
12189
12484
|
filter,
|
|
12190
12485
|
include,
|
|
12191
|
-
|
|
12486
|
+
includePrivateMatches: true,
|
|
12192
12487
|
status: "active",
|
|
12193
12488
|
waitingForUserId: filter.userId
|
|
12194
12489
|
}) : []
|
|
@@ -12205,7 +12500,7 @@ async function readConversationFeedFromSql(options = {}) {
|
|
|
12205
12500
|
const conversations = rows.map((row) => conversationFromRecordRow(row));
|
|
12206
12501
|
const conversationIds = conversations.map((conversation) => conversation.conversationId);
|
|
12207
12502
|
const conversationTrees = readConversationTrees(db, conversationIds);
|
|
12208
|
-
const [accessRows, tree, participantsByRoot, annotationsByConversation, auxiliaryCostsByRoot, metricsByRoot, participantsByConversation, teamDomainByTeamId, { work: conversationWork, lastUserMessageAt: lastUserMessageAtByConversation }, activityPreviewByConversation,
|
|
12503
|
+
const [accessRows, tree, participantsByRoot, annotationsByConversation, auxiliaryCostsByRoot, metricsByRoot, participantsByConversation, teamDomainByTeamId, { work: conversationWork, lastUserMessageAt: lastUserMessageAtByConversation }, activityPreviewByConversation, automationTitleByConversation, firstHumanMessageTextByConversation, treeStateByConversation, threadRecords] = await Promise.all([
|
|
12209
12504
|
readConversationAccessRows(db, conversationIds),
|
|
12210
12505
|
conversationTrees,
|
|
12211
12506
|
readMemberParticipants(db, conversationIds, options.viewer ? { userId: options.viewer.id } : filter ? feedMember(filter) : void 0),
|
|
@@ -12219,7 +12514,6 @@ async function readConversationFeedFromSql(options = {}) {
|
|
|
12219
12514
|
lastUserMessageAt: await readLastUserMessageAtByConversation(db, work.assignedIds.filter((conversationId) => work.finishedAtById[conversationId]))
|
|
12220
12515
|
})),
|
|
12221
12516
|
readConversationActivityPreviews(db, conversationIds),
|
|
12222
|
-
readConversationFeedBriefs(db, conversationIds),
|
|
12223
12517
|
readAutomationTitlesByConversationId(conversations),
|
|
12224
12518
|
readFirstHumanMessageTexts(db, conversations),
|
|
12225
12519
|
readConversationTreeStates(db, conversationIds, options.viewer?.id),
|
|
@@ -12266,7 +12560,6 @@ async function readConversationFeedFromSql(options = {}) {
|
|
|
12266
12560
|
};
|
|
12267
12561
|
const annotations = access?.canViewPrivateContent ? annotationsByConversation.get(conversation.conversationId) ?? [] : [];
|
|
12268
12562
|
const activityPreview = visibleActivityPreviews.get(conversation.conversationId);
|
|
12269
|
-
const brief = access?.canViewPrivateContent ? briefByConversation.get(conversation.conversationId) : void 0;
|
|
12270
12563
|
const participants = access?.canViewPrivateContent ? participantsByConversation.get(conversation.conversationId) : void 0;
|
|
12271
12564
|
const threads = threadsByRoot.get(conversation.conversationId);
|
|
12272
12565
|
const media = access?.canViewPrivateContent ? row.media : null;
|
|
@@ -12279,11 +12572,11 @@ async function readConversationFeedFromSql(options = {}) {
|
|
|
12279
12572
|
...work,
|
|
12280
12573
|
...treeRead,
|
|
12281
12574
|
...row.awaitingAuthorization ? { awaitingAuthorization: true } : void 0,
|
|
12575
|
+
...row.latestTurnFailed ? { latestTurnFailed: true } : void 0,
|
|
12282
12576
|
...lastMessageAt ? { lastMessageAt } : void 0,
|
|
12283
12577
|
...threads ? { threads } : void 0,
|
|
12284
12578
|
...participants && participants.length > 0 ? { participants } : void 0,
|
|
12285
12579
|
...activityPreview ? { activityPreview } : void 0,
|
|
12286
|
-
...brief ? { brief } : void 0,
|
|
12287
12580
|
...viewerAnswer ? { viewerAnswer } : void 0,
|
|
12288
12581
|
...media?.length ? { media } : void 0,
|
|
12289
12582
|
...links.length > 0 ? { links } : void 0,
|
|
@@ -12315,76 +12608,4 @@ async function readConversationFeedFromSql(options = {}) {
|
|
|
12315
12608
|
async function readConversationFeed(options = {}) {
|
|
12316
12609
|
return readConversationFeedFromSql(options);
|
|
12317
12610
|
}
|
|
12318
|
-
|
|
12319
|
-
/**
|
|
12320
|
-
* Steer the viewer's own queued web messages into the conversation now.
|
|
12321
|
-
*
|
|
12322
|
-
* Only the author can steer a message. Ids that are not the viewer's queued
|
|
12323
|
-
* web messages, or that Junior already read, are left out of the result.
|
|
12324
|
-
*/
|
|
12325
|
-
async function steerConversationPendingMessagesForViewer(viewer, conversationId, body) {
|
|
12326
|
-
if (!await getConversationStore().get({ conversationId })) throwApiError(404, "Conversation not found.");
|
|
12327
|
-
if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(403, "Only conversation participants can steer queued messages.");
|
|
12328
|
-
return {
|
|
12329
|
-
conversationId,
|
|
12330
|
-
steeredInboundMessageIds: (await steerWebPendingMessages({
|
|
12331
|
-
authorIds: webActorUserIds(viewer),
|
|
12332
|
-
conversationId,
|
|
12333
|
-
inboundMessageIds: body.inboundMessageIds
|
|
12334
|
-
})).steeredInboundMessageIds
|
|
12335
|
-
};
|
|
12336
|
-
}
|
|
12337
|
-
// src/api/conversations/stop.ts
|
|
12338
|
-
/**
|
|
12339
|
-
* Stop one Conversation for a participant: its active Turn, its session, and
|
|
12340
|
-
* every child agent below it.
|
|
12341
|
-
*
|
|
12342
|
-
* The stop also removes the human messages queued before it. The viewer's own
|
|
12343
|
-
* web text comes back in the response so the dashboard can restore it to the
|
|
12344
|
-
* composer instead of losing it.
|
|
12345
|
-
*/
|
|
12346
|
-
async function stopConversationTurnForViewer(viewer, conversationId, services) {
|
|
12347
|
-
const conversationStore = getConversationStore();
|
|
12348
|
-
if (!await conversationStore.get({ conversationId })) throwApiError(404, "Conversation not found.");
|
|
12349
|
-
if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(403, "Only conversation participants can stop this turn.");
|
|
12350
|
-
try {
|
|
12351
|
-
const result = await stopConversation({
|
|
12352
|
-
conversationId,
|
|
12353
|
-
conversationStore,
|
|
12354
|
-
queue: services.queue
|
|
12355
|
-
});
|
|
12356
|
-
if (result.status !== "requested") return {
|
|
12357
|
-
conversationId,
|
|
12358
|
-
status: "no_work",
|
|
12359
|
-
stoppedInboundMessageIds: [],
|
|
12360
|
-
stoppedMessages: []
|
|
12361
|
-
};
|
|
12362
|
-
await clearSlackPendingReactions({
|
|
12363
|
-
getSlackAdapter: getProductionSlackAdapter,
|
|
12364
|
-
messages: result.pendingMessages
|
|
12365
|
-
});
|
|
12366
|
-
return {
|
|
12367
|
-
conversationId,
|
|
12368
|
-
status: "requested",
|
|
12369
|
-
stoppedInboundMessageIds: result.pendingMessages.map((message) => message.inboundMessageId),
|
|
12370
|
-
stoppedMessages: viewerWebMessages(result.pendingMessages, viewer)
|
|
12371
|
-
};
|
|
12372
|
-
} catch (error) {
|
|
12373
|
-
throwApiError(500, "Unable to stop the active turn.", error);
|
|
12374
|
-
}
|
|
12375
|
-
}
|
|
12376
|
-
function viewerWebMessages(messages, viewer) {
|
|
12377
|
-
const viewerUserIds = webActorUserIds(viewer);
|
|
12378
|
-
return messages.flatMap((message) => {
|
|
12379
|
-
if (message.source !== "web") return [];
|
|
12380
|
-
const metadata = legacyWebMailboxMetadataSchema.safeParse(message.input.metadata);
|
|
12381
|
-
if (!metadata.success) return [];
|
|
12382
|
-
if (!viewerUserIds.includes(metadata.data.authorUserId)) return [];
|
|
12383
|
-
const text = message.input.text.trim();
|
|
12384
|
-
return text ? [{
|
|
12385
|
-
inboundMessageId: message.inboundMessageId,
|
|
12386
|
-
text
|
|
12387
|
-
}] : [];
|
|
12388
|
-
});
|
|
12389
|
-
}
|
|
12390
|
-
export { GET as $, actOnReviewItem as A, conversationRecordJoins as At, readUserSettings as B, encodeConversationCursor as C, bindMessageAuthorIdentityId as Ct, resolveMentions as D, SubscribedReplyReason as Dt, requireConversationPendingMessages as E, parseContent as Et, ingestEventAutomations as F, IMAGE_WIDTHS as Ft, dispatchScheduledAutomation as G, automationReplyAttribution as H, archiveViewerDoneConversations as I, decodeImageId as It, scheduleInboxSnoozeTimer as J, getScheduledAutomationDispatch as K, runAutoArchiveSweep as L, readReviewItemForUser as M, conversationSummaryFromStoredConversation as Mt, reviewItemChange as N, readFirstHumanMessageTexts as Nt, stopConversation as O, getThreadStopDecision as Ot, createEventAppPublisher as P, createViewerMcp as Pt, backfillCacheWarmingGaps as Q, setConversationAutoArchive as R, decodeConversationCursor as S, createSlackWebApiStatusSender as St, readConversationPendingMessages as T, stripLeadingBotMention as Tt, settleEventAutomationRuns as U, updateUserSettings as V, createHeartbeatContext as W, runSavingsRefillSlice as X, readSavingsRefill as Y, startSavingsRefill as Z, keepQuickQuestionForViewer as _, withNormalizedThreadId as _t, decodePageCursor as a, resolveObjectLinks as at, createConversationForViewer as b, failStoppedDispatch as bt, pinConversation as c, isPublicAddress as ct, readConversationAuxiliaryCostsFromSql as d, createProductionSlackWebhookServices as dt, readHealthReport as et, childAgentTotalsReport as f, getProductionSlackAdapter as ft, forkConversationForViewer as g, normalizeIncomingSlackThreadId as gt, readConversationDetailEtag as h, slackInboundMessageId as ht, readConversationFeed as i, resolveObjectLinkNow as it, closeReviewItemsAnsweredByReply as j, readConversationRecordFromSql as jt, ReviewItemActionError as k, resolvePersonLink as kt, reorderPinnedConversations as l, publicAddressLookup as lt, conversationVersionQuery as m, clearSlackPendingReactions as mt, steerConversationPendingMessagesForViewer as n, readLinkObjectType as nt, encodePageCursor as o, viewerCanViewPluginLink as ot, readConversationTreeMetricsFromSql as p, buildSlackInboundMessage as pt, runInboxSnoozeTimers as q, conversationFeedVersionQuery as r, readObjectLinkTypes as rt, listedConversation as s, guardedFetch as st, stopConversationTurnForViewer as t, OBJECT_LINK_TTL_MS as tt, readConversationDetail as u, createProductionConversationWorkOptions as ut, readConversationEvents as v, AGENT_DISPATCH_MAX_AGE_MS as vt, cancelConversationPendingMessagesForViewer as w, startProcessingReaction as wt, requireWebMessageConversation as x, recordSkippedConversationMessage as xt, appendConversationMessageForViewer as y, enqueueAgentDispatch as yt, DEFAULT_USER_SETTINGS as z };
|
|
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 };
|