@sentry/junior 0.311.0 → 0.313.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-B1wujchl.js → adapter-CYAvJzZS.js} +1 -1
- package/dist/{adapter-context-G2M0y6rP.js → adapter-context-CVsHoVSf.js} +2 -2
- package/dist/{admin-DCiBhUT1.js → admin-Cyhb4TwZ.js} +1 -1
- package/dist/{agent-runner-BVHPUIc8.js → agent-runner-B5y9MsT-.js} +3487 -3493
- 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 +294 -311
- package/dist/{app-Cw5Vy6H6.d.ts → app-DA8-hCMj.d.ts} +2 -9
- package/dist/app.d.ts +1 -1
- package/dist/app.js +336 -604
- package/dist/{background-compaction-queue-CJDnWVOJ.js → background-compaction-queue-iZXadLV3.js} +60 -85
- package/dist/{catalog-runtime-DMY3VV-D.js → catalog-runtime-kkE3hvCX.js} +1 -1
- package/dist/channel-access-mt7K6dPh.js +221 -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-CWbwKj0j.js} +59 -27
- package/dist/{continue-in-slack-DNXSC9So.js → continue-in-slack-CxyFzdlF.js} +7 -8
- package/dist/{conversation-feed-DkinDu5o.js → conversation-feed-BEXLD3Me.js} +86 -21
- package/dist/{conversation-privacy-DxttrKb9.js → conversation-privacy-BrMiDN61.js} +1 -1
- package/dist/{conversation-turn-DWw7Xhdr.js → conversation-turn-B35eu0uz.js} +78 -56
- package/dist/{credential-sync-Bk8wGb8Y.js → credential-sync-DWTOEQrm.js} +15 -15
- package/dist/{projection-Cns7XwWa.js → credentialed-Dyv8b-lu.js} +16306 -20732
- package/dist/{db-7ETESH44.d.ts → db-DYGcXYl3.d.ts} +11 -6
- package/dist/{db-DTxzH7u5.js → db-PwSRzWWn.js} +181 -100
- package/dist/{executor-DqTiYj9S.js → executor-CgWyWfYz.js} +117 -99
- package/dist/{html-B9Sl4Axb.js → html-DidUcRhI.js} +6 -6
- package/dist/ingest-B0AggUEC.js +7931 -0
- package/dist/{install-Sg4ePfLl.js → install-2urLLXNt.js} +2 -2
- package/dist/instrumentation.js +3 -3
- package/dist/{lineage-BHAMpNKr.js → lineage-BXplQAVH.js} +2 -2
- package/dist/{stop-CYsfc0Ed.js → list-DyIyReSV.js} +709 -475
- package/dist/{logging-FjclQsXu.js → logging-DNt-qOIO.js} +1 -1
- package/dist/{schedule-BLJ476XQ.js → media-B0pZJ0bG.js} +1058 -11
- package/dist/{message-CJ7_RL50.js → message-Z5YKC-Af.js} +35 -28
- package/dist/{model-input-CMLh4Cwq.js → model-input-BhPJYdSV.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-ByvDdcdY.js} +2 -2
- package/dist/{oauth-relay-Bu9kkaQu.js → oauth-relay-D-kK0yoN.js} +1 -1
- package/dist/{registry-BPwuOP2O.js → registry-POH4bZC4.js} +1 -1
- package/dist/reporting-window-C4dbzDiR.js +124 -0
- package/dist/request-deadline-BUiRYQYj.js +24 -0
- package/dist/{resolve-BK29bBry.js → resolve-CWtBNSKP.js} +3 -3
- package/dist/{runner-BcAE-cJm.js → runner-CsZ_VRxp.js} +14 -16
- package/dist/{sandbox-egress-signals-C-q0go5b.js → sandbox-egress-signals-FbCk1FkN.js} +1 -1
- package/dist/{schema-DYcJeV7d.d.ts → schema-DBf18QPS.d.ts} +2773 -3630
- package/dist/{schema-BLgSZXcL.js → schema-DojR2uCL.js} +106 -121
- package/dist/{service-account-iJoCtkHR.js → service-account-CDYb9hfX.js} +3 -3
- package/dist/{service-account-gN0zqf0S.js → service-account-o15pZWcJ.js} +5 -5
- package/dist/{skills-BoZ80epJ.js → skills-B0jP4whm.js} +2 -2
- package/dist/{slack-conversation-unfurl-CogYrITA.js → slack-conversation-unfurl-D26t9kBC.js} +9 -9
- package/dist/{spawn-Dk92r7mX.js → spawn-BjljgExZ.js} +14 -32
- package/dist/start-conversation-DbVujrwO.js +755 -0
- package/dist/{state-DH3Cmgp3.js → state-BTawTCme.js} +4 -4
- package/dist/statuses-BKwqCPhj.js +69 -0
- package/dist/store-CjXrp-Up.js +492 -0
- package/dist/task-queue-Cwlatjz3.js +90 -0
- package/dist/task-runner--Ke8KSMf.js +1432 -0
- package/dist/{thread-context-BW2BsQbH.js → thread-context-B8exINEe.js} +6 -7
- package/dist/turn-membership-DTR3SaKD.js +5859 -0
- package/dist/{validation-DrJd0nnq.js → validation-Ce0qbMlT.js} +1 -1
- package/dist/{task-queue-C_zldF5J.js → vercel-queue-q4z8w5QO.js} +93 -172
- package/dist/{version-CNKZ8owc.js → version-DFh4n9nr.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{warmup-BWdHew2H.js → warmup-D5hzqTcp.js} +4853 -13605
- package/dist/web-message-id-C6P83ans.js +10 -0
- package/dist/{worker-t9qpu_Zx.js → worker-CDg9Lbpg.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/0158_keep_legacy_archive_columns.sql +5 -0
- package/migrations/0159_conversation_embeddings_fk_validate.sql +5 -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/0158_snapshot.json +6515 -0
- package/migrations/meta/0159_snapshot.json +6515 -0
- package/migrations/meta/_journal.json +120 -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,46 @@
|
|
|
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-Dyv8b-lu.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-CWbwKj0j.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-DNt-qOIO.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-DFh4n9nr.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 saveActorAvatar, A as isTopLevelKind, An as agentTurnUsageSchema, Cn as conversationPinnedForUser, Ct as isPluginInboxItem, Dn as addAgentTurnUsage, En as viewerMarksFromParticipant, F as turnBehavior, Fn as nextDetailVersion, Gt as identityAvatarUrl, H as parseSessionSource, L as locationFromRow, Ln as createSlackDestination, M as postsRunNotices, Mn as resolveRootConversationId, Q as conversationTurnFailedSql, Qt as resolveActorIdentityId, Sn as conversationIsNotUnsubscribedRoot, St as isOnlyAssignee, T as deliversFinalText, Tn as rootVisibleToViewer, U as conversationCostOf, Wt as hasUserPhoto, X as conversationIsActiveSql, Xt as userAvatarUrlsFromJoinedPhotos, Yt as userAvatarUrlsFromIdentities, Z as conversationStatusSql, _ as readConversationTrees, _n as createConversationAccessReader, _t as inboxItemPlugin, a as getConversationStore, b as loadConversationSlackTenantIds, et as executionIsActive, f as copyMessageLinks, ft as inboxItemForUser, gn as conversationAccessFromRows, gt as inboxItemOwnedByConversation, h as conversationAncestors, it as treeAwaitsAuthorization, jn as hasAgentTurnUsage, m as withConversationEventLock, mn as canAddConversationMessages, 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, un as readCachedUserByEmail, ut as canUserReadInboxItem, v as setArchivedAt, vn as readConversationAccessFromSql, wn as readMemberParticipants, x as lastMessageAtSql, xn as conversationIsMemberRoot, xt as isAutomationAlertItem, y as conversationSlackTenantId, yn as readConversationAccessRows, zn as requireSlackDestination } from "./db-PwSRzWWn.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, q as juniorDestinations, x as juniorAgentInvocations } from "./executor-CgWyWfYz.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 { _ as
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
-
import { d as
|
|
21
|
-
import {
|
|
22
|
-
import { m as
|
|
23
|
-
import {
|
|
24
|
-
import {
|
|
25
|
-
import {
|
|
26
|
-
import { t as
|
|
27
|
-
import {
|
|
28
|
-
import {
|
|
29
|
-
import {
|
|
30
|
-
import {
|
|
31
|
-
import {
|
|
32
|
-
import { t as
|
|
33
|
-
import {
|
|
34
|
-
import {
|
|
35
|
-
import { r as
|
|
11
|
+
import { a as getStateValues, i as getStateAdapter, o as setStateValues } from "./adapter-CYAvJzZS.js";
|
|
12
|
+
import { f as actorLogContext, p as credentialContextForActor } from "./registry-POH4bZC4.js";
|
|
13
|
+
import { n as pluginCatalogRuntime } from "./catalog-runtime-kkE3hvCX.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-B5y9MsT-.js";
|
|
15
|
+
import { d as PluginMcpClient, u as McpAuthorizationRequiredError, v as getMcpStoredOAuthCredentials } from "./service-account-o15pZWcJ.js";
|
|
16
|
+
import { i as webActorUserIds } from "./state-BTawTCme.js";
|
|
17
|
+
import { $t as abandonTurnRecord, Ct as recordDeliveredAssistantMessage, Et as upsertConversationMessage, G as buildDeterministicAssistantMessageId, Ht as AuthorizationFlowDisabledError, In as finalizeFailedTurnReplyWithEvent, J as commitMessages, K as buildDeterministicTurnId, Kt as clearPendingAuth, Ln as getAgentTurnDiagnosticsAttributes, Lt as createPluginEgress, M as getConversation, Mn as buildTurnErrorResponse, Mt as isEventConversationMessage, N as getConversationWorkState, Q as loadTurnProjection, Qt as saveTurnCheckpoint, Rn as requireTurnFailureEventId, Rt as PluginCredentialFailureError, St as normalizeConversationText, Tn as loadTurnStart, Tt as turnHasReply, X as loadConversationProjection, Xt as lostWorkerBeforeFirstSave, Yt as loadTurnCheckpoint, Zt as pauseLostWorkerTurn, _ as appendAndEnqueueInboundMessage, _t as estimateConversationMessagesTokens, an as recordTurnSummary, b as cancelHumanFacingPendingMessages, bn as canShareTurn, bt as latestConversationMessageSeq, c as notInheritedByForkChild, d as getPersistedThreadState, dr as persistWithRetry, dt as persistConversationMessageWindow, en as completeTurnRecord, f as persistThreadRuntimeState, fr as configValueSchema, ft as persistConversationMessages, gt as buildConversationContext, i as resolveTurnResumeRouting, in as listTurnSummaries, kt as EVENT_SYSTEM_ACTOR, l as getLocationConfigurationService, m as coerceThreadConversationState, mr as piMessageFromHistoryItem, mt as resolveConversationTitle, n as savedTurnMessages, nt as recordAuthorizationCompleted, p as persistThreadStateById, q as commitAcceptedReply, r as resolveConversationRouting, rn as getTurnRecord, st as recordSubscribedReplyRoute, tn as failTurnRecord, tr as getAssistantReplyText, u as getPersistedSandboxState, ut as hydrateConversationMessages, vt as getConversationMessageSlackTs, wn as getTurnLifecycle, wt as trimConversationMessages, xt as markConversationMessage, yn as canJoinTurn, yt as isHumanConversationMessage } from "./turn-membership-DTR3SaKD.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-B0pZJ0bG.js";
|
|
19
|
+
import { f as readJuniorSecret, t as getVercelConversationWorkQueue } from "./vercel-queue-q4z8w5QO.js";
|
|
20
|
+
import { $t as markTurnCompleted, Bt as getTurnUserMessage, D as resolveSlackReplyTarget, E as stopAtAutomatedTurnLimit, Et as eventAuthorText, F as createChildConversationWorker, Fn as conversationSubtree, Gt as CooperativeTurnYieldError, Ht as getTurnUserReplyAttachmentContext, I as createDeliverToParent, In as conversationSubtreeColumns, It as resumeForPersonInput, Jt as getConversationTurnBoundaryError, Kt as TurnInputCommitLostError, M as stopConversation, Nt as resolveBotSlackTeamId, O as sendSlackReply, P as stopChildAgentsOf, Qt as markTurnClosed, R as enqueueAgentInvocationResult, Rn as isExperimentalFeatureEnabled, S as recordFailedDispatchTurn, T as getTurnAuthorization, Ut as getTurnUserSlackMessageTs, V as withAgentInvocationResultActors, Wt as ConversationTurnBoundaryError, Xt as isTurnInputCommitLostError, Yt as isCooperativeTurnYieldError, Zt as isTurnInputDeferredError, _n as renderTaskInput, b as createPausedTurns, c as resolveMailboxTurnWork, d as legacyWebMailboxMetadataSchema, dn as instructionActorFor, en as markTurnFailed, gt as recordFinishedTurnForAutomatedLimit, hn as withoutSavedSteeringMessages, in as getWebAuthorization, it as getChildAgentLabel, jt as resolveEventAuthor, on as loadInboxItemInput, qt as TurnInputDeferredError, sn as savedInputInstruction, t as ingestEvent, tn as startActiveTurn, un as buildSteeringPiMessage, vt as AgentRunError, x as getPausedTurnRequest, y as supersedeTurnForInput, yt as executeTurn } from "./ingest-B0AggUEC.js";
|
|
21
|
+
import { Ar as gapSegment, At as parseSlackMessageReference, Bt as readSlackRawMessageContext, Ct as setConversationSubscription, Er as MINUTE_MS, Et as throwApiError, Fn as readConversationSourceTask, Jn as findAutomationSkill, Kn as AutomationEditError, Mn as takeViewerAutomationAlertStep, Or as NO_REPLY_GAP_MS, Ot as renderAttachmentText, Pn as ViewerTaskNotFoundError, Tt as jsonResponse, Vt as resolveSlackChannelIdFromMessage, Xn as effectiveTaskOutcomes, Yn as missingAutomationSkillReason, br as connectedState, ct as archiveConversation, i as GLOBAL_GAPS_TTL_MS, ir as historyPeriodSavings, kt as renderBlockText, l as isConversationWorkDone, lr as replaceHistorySavings, lt as conversationReadPositionQuery, mt as deliverInboxItemChange, n as CONVERSATION_STATE_TTL_MS, nr as addHistoryWarmupCost, o as segmentGapsKey, r as GLOBAL_GAPS_MAX, rr as firstLiveSavingsDate, st as readLastUserMessageAtByConversation, t as ANSWER_TOOL_ENDINGS, tr as addHistoryPeriod, u as listConversationWork, xr as providerCacheTtlMs, zt as parseSlackThreadId } from "./warmup-D5hzqTcp.js";
|
|
22
|
+
import { C as recordSlackAttachment, _ as verifyAttachmentUploads, d as recordWebConversationActivity, f as webActorFromUser, l as createAndEnqueueConversation, m as AttachmentUploadError, o as acceptsWebMessages, s as appendAndEnqueueWebMessage, u as createConversationId, w as slackAttachmentsVersionQuery, x as readAttachmentVisionSummary, y as getSlackFileId } from "./start-conversation-DbVujrwO.js";
|
|
23
|
+
import { a as isConversationMember, i as getConversationInfo, l as listThreadReplies, o as isPublicSlackChannel, r as getChannelMessage } from "./channel-access-mt7K6dPh.js";
|
|
24
|
+
import { r as isFileAttachment, s as storeAttachment } from "./store-CjXrp-Up.js";
|
|
25
|
+
import { f as OPEN_TODO_STATUSES } from "./statuses-BKwqCPhj.js";
|
|
26
|
+
import { t as getTurnRequestDeadline } from "./request-deadline-BUiRYQYj.js";
|
|
27
|
+
import { t as webMessageId } from "./web-message-id-C6P83ans.js";
|
|
28
|
+
import { t as runWithSlackInstallation } from "./adapter-context-CVsHoVSf.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-BEXLD3Me.js";
|
|
30
|
+
import { a as withTurnSpan, i as turnInputTelemetry, n as createConversationTurnWorker, r as getTurnInputSpanAttributes } from "./conversation-turn-B35eu0uz.js";
|
|
31
|
+
import { n as attachmentFactLines, r as buildStoredAttachmentPromptText } from "./model-input-BhPJYdSV.js";
|
|
32
|
+
import { t as bindMessageAgent } from "./message-Z5YKC-Af.js";
|
|
33
|
+
import { t as readConversationLineage } from "./lineage-BXplQAVH.js";
|
|
34
|
+
import { t as bindSpawnAgent } from "./spawn-BjljgExZ.js";
|
|
35
|
+
import { a as buildDeliveredTurnStatePatch, i as persistAuthPauseTurnState, n as loadThreadContextTrimFloor, o as loadPendingMessageCards, r as completeAuthPauseTurn, t as buildTurnThreadContext } from "./thread-context-B8exINEe.js";
|
|
36
|
+
import { a as readConversationEventPage, n as scheduleSessionCompletedPluginTasks, o as readConversationEventPageAfter, s as readConversationEventPageAround } from "./task-runner--Ke8KSMf.js";
|
|
37
|
+
import { s as sendVercelPluginTask } from "./task-queue-Cwlatjz3.js";
|
|
38
|
+
import { r as canContinueInSlack } from "./continue-in-slack-CxyFzdlF.js";
|
|
36
39
|
import * as z from "zod";
|
|
37
40
|
import pLimit from "p-limit";
|
|
38
41
|
import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
|
|
39
42
|
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";
|
|
43
|
+
import { and, asc, count, desc, eq, exists, gt, gte, inArray, isNotNull, isNull, lt, lte, min, ne, not, or, sql } from "drizzle-orm";
|
|
41
44
|
import { alias } from "drizzle-orm/pg-core";
|
|
42
45
|
import { Message, ThreadImpl, stringifyMarkdown } from "chat";
|
|
43
46
|
import net from "node:net";
|
|
@@ -416,7 +419,7 @@ function buildSlackLocationUrl(args) {
|
|
|
416
419
|
url.searchParams.set("cid", channelId);
|
|
417
420
|
return url.toString();
|
|
418
421
|
}
|
|
419
|
-
// src/api/conversations/
|
|
422
|
+
// src/api/conversations/location-labels.ts
|
|
420
423
|
/** Format a Slack destination without exposing private channel names. */
|
|
421
424
|
function slackStatsLocationLabel(input) {
|
|
422
425
|
const channelId = input.channel;
|
|
@@ -547,6 +550,7 @@ function conversationSummaryFromStoredConversation(args) {
|
|
|
547
550
|
visibility
|
|
548
551
|
}),
|
|
549
552
|
kind: conversation.kind,
|
|
553
|
+
...canViewPrivateContent && conversation.summary ? { summary: conversation.summary } : void 0,
|
|
550
554
|
...conversation.parentConversationId ? { parentConversationId: conversation.parentConversationId } : void 0,
|
|
551
555
|
isParticipant: args.access?.isParticipant ?? false,
|
|
552
556
|
...visibility ? { visibility } : void 0,
|
|
@@ -634,6 +638,7 @@ function conversationFromRecordRow(row) {
|
|
|
634
638
|
...value.channelName ? { channelName: value.channelName } : void 0,
|
|
635
639
|
...value.source ? { source: value.source } : void 0,
|
|
636
640
|
...value.title ? { title: value.title } : void 0,
|
|
641
|
+
...value.summary ? { summary: value.summary } : void 0,
|
|
637
642
|
...value.transcriptPurgedAt ? { transcriptPurgedAtMs: value.transcriptPurgedAt.getTime() } : void 0,
|
|
638
643
|
...value.stoppedAt ? { stoppedAtMs: value.stoppedAt.getTime() } : void 0,
|
|
639
644
|
...value.deliveryPausedAt ? { deliveryPausedAtMs: value.deliveryPausedAt.getTime() } : void 0
|
|
@@ -684,14 +689,13 @@ async function resolveConversationLink(viewer, url) {
|
|
|
684
689
|
const db = getDb();
|
|
685
690
|
const access = await readViewerAccess(viewer, conversationId);
|
|
686
691
|
if (!access?.canViewPrivateContent) return void 0;
|
|
687
|
-
const [firstTexts, automationTitles,
|
|
692
|
+
const [firstTexts, automationTitles, participants] = await Promise.all([
|
|
688
693
|
readFirstHumanMessageTexts(db, [conversation]),
|
|
689
694
|
readAutomationTitlesByConversationId([conversation]),
|
|
690
|
-
readLatestConversationBrief(db, conversationId),
|
|
691
695
|
readConversationParticipants(db, [conversationId])
|
|
692
696
|
]);
|
|
693
697
|
return conversationObjectCard({
|
|
694
|
-
|
|
698
|
+
description: conversation.summary,
|
|
695
699
|
participants: participants.get(conversationId) ?? [],
|
|
696
700
|
summary: conversationSummaryFromStoredConversation({
|
|
697
701
|
access,
|
|
@@ -2889,14 +2893,14 @@ function readSlackActionToken(message) {
|
|
|
2889
2893
|
const token = slackActionTokenSchema.safeParse(envelope.data.raw?.action_token);
|
|
2890
2894
|
return token.success ? token.data : void 0;
|
|
2891
2895
|
}
|
|
2892
|
-
// src/chat/
|
|
2896
|
+
// src/chat/inbox-items/message-change.ts
|
|
2893
2897
|
const messageChangeRecords = /* @__PURE__ */ new WeakMap();
|
|
2894
2898
|
/** Keep the record of a restored Slack input for its Message write. */
|
|
2895
|
-
function
|
|
2899
|
+
function bindMessageInboxItemChange(message, record) {
|
|
2896
2900
|
if (record) messageChangeRecords.set(message, record);
|
|
2897
2901
|
}
|
|
2898
2902
|
/** Read the record that a restored Slack input carries. */
|
|
2899
|
-
function
|
|
2903
|
+
function getMessageInboxItemChange(message) {
|
|
2900
2904
|
return messageChangeRecords.get(message);
|
|
2901
2905
|
}
|
|
2902
2906
|
// src/chat/slack/assistant-thread/status-render.ts
|
|
@@ -3307,7 +3311,7 @@ function toConversationMessage(args) {
|
|
|
3307
3311
|
const messageHasPotentialImageAttachment = hasPotentialImageAttachment(args.entry.attachments);
|
|
3308
3312
|
const imageAttachmentCount = messageHasPotentialImageAttachment ? countPotentialImageAttachments(args.entry.attachments) : 0;
|
|
3309
3313
|
const authorIdentityId = args.entry.author.isMe ? void 0 : getMessageAuthorIdentityId(args.entry);
|
|
3310
|
-
const reviewItemChange =
|
|
3314
|
+
const reviewItemChange = getMessageInboxItemChange(args.entry);
|
|
3311
3315
|
return {
|
|
3312
3316
|
id: args.entry.id,
|
|
3313
3317
|
role: args.entry.author.isMe ? "assistant" : "user",
|
|
@@ -3476,14 +3480,23 @@ async function persistThreadRuntimeStateWithRetry(conversationId, patch) {
|
|
|
3476
3480
|
* Both are SQL-backed; there is no thread-state fallback.
|
|
3477
3481
|
*/
|
|
3478
3482
|
async function loadPiMessagesForTurn(args) {
|
|
3479
|
-
if (!args.conversationId) return {};
|
|
3483
|
+
if (!args.conversationId) return { seqs: [] };
|
|
3480
3484
|
if (args.activeTurnId) {
|
|
3481
3485
|
const sessionRecord = await getTurnRecord(args.conversationId, args.activeTurnId);
|
|
3482
|
-
if (sessionRecord?.piMessages.length)
|
|
3486
|
+
if (sessionRecord?.piMessages.length) {
|
|
3487
|
+
const piMessages = trimTrailingAssistantMessages(sessionRecord.piMessages);
|
|
3488
|
+
return {
|
|
3489
|
+
piMessages,
|
|
3490
|
+
seqs: sessionRecord.piMessageSeqs.slice(0, piMessages.length)
|
|
3491
|
+
};
|
|
3492
|
+
}
|
|
3483
3493
|
}
|
|
3484
3494
|
const projection = await loadConversationProjection({ conversationId: args.conversationId });
|
|
3485
|
-
if (projection.messages.length > 0) return {
|
|
3486
|
-
|
|
3495
|
+
if (projection.messages.length > 0) return {
|
|
3496
|
+
piMessages: projection.messages,
|
|
3497
|
+
seqs: projection.seqs
|
|
3498
|
+
};
|
|
3499
|
+
return { seqs: [] };
|
|
3487
3500
|
}
|
|
3488
3501
|
/** Build the Slack caller that prepares input and delivers output for a Turn. */
|
|
3489
3502
|
function createSlackTurn(deps) {
|
|
@@ -3618,12 +3631,12 @@ function createSlackTurn(deps) {
|
|
|
3618
3631
|
const resolveSteeringMessages = async (queuedMessages) => {
|
|
3619
3632
|
return await mapBounded(queuedMessages, async (queued) => {
|
|
3620
3633
|
const attachments = queued.message.attachments;
|
|
3621
|
-
const
|
|
3634
|
+
const inboxItemInput = await loadInboxItemInput(getMessageInboxItemChange(queued.message));
|
|
3622
3635
|
return {
|
|
3623
3636
|
actor: inboundMessageActor(queued),
|
|
3624
|
-
...
|
|
3637
|
+
...inboxItemInput ? { kind: "runtime" } : void 0,
|
|
3625
3638
|
provenance: inboundMessageProvenance(queued, teamId),
|
|
3626
|
-
text:
|
|
3639
|
+
text: inboxItemInput?.text ?? queued.userText,
|
|
3627
3640
|
timestampMs: queued.message.metadata.dateSent.getTime(),
|
|
3628
3641
|
omittedImageAttachmentCount: !canReadImages() && hasPotentialImageAttachment(attachments) ? countPotentialImageAttachments(attachments) : 0,
|
|
3629
3642
|
attachments: await deps.resolveUserAttachments(attachments, {
|
|
@@ -3952,10 +3965,11 @@ function createSlackTurn(deps) {
|
|
|
3952
3965
|
boundaryFailureCode = "agent_run_failed";
|
|
3953
3966
|
};
|
|
3954
3967
|
try {
|
|
3955
|
-
|
|
3968
|
+
const loadedPiMessages = await loadPiMessagesForTurn({
|
|
3956
3969
|
conversationId,
|
|
3957
3970
|
activeTurnId
|
|
3958
|
-
})
|
|
3971
|
+
});
|
|
3972
|
+
let piMessages = loadedPiMessages.piMessages;
|
|
3959
3973
|
const hasHistory = Boolean(piMessages?.length);
|
|
3960
3974
|
const batchedSteeringMessages = (await resolveSteeringMessages((options.queuedMessages ?? []).filter((queued) => queued.explicitMention))).map((steering) => ({
|
|
3961
3975
|
message: buildSteeringPiMessage(steering),
|
|
@@ -4012,7 +4026,7 @@ function createSlackTurn(deps) {
|
|
|
4012
4026
|
const location = (await getConversationStore().get({ conversationId }))?.location;
|
|
4013
4027
|
const savedInput = await savedInputInstruction({
|
|
4014
4028
|
runtime: Boolean(options.execution?.dispatch),
|
|
4015
|
-
reviewItemChange:
|
|
4029
|
+
reviewItemChange: getMessageInboxItemChange(message),
|
|
4016
4030
|
text: effectiveUserText
|
|
4017
4031
|
});
|
|
4018
4032
|
const run = {
|
|
@@ -4031,7 +4045,10 @@ function createSlackTurn(deps) {
|
|
|
4031
4045
|
omittedImageAttachmentCount,
|
|
4032
4046
|
attachments: userAttachments
|
|
4033
4047
|
},
|
|
4034
|
-
history: piMessages
|
|
4048
|
+
history: piMessages ? {
|
|
4049
|
+
messages: piMessages,
|
|
4050
|
+
seqs: loadedPiMessages.seqs
|
|
4051
|
+
} : void 0,
|
|
4035
4052
|
credentialContext,
|
|
4036
4053
|
actor: executionActor,
|
|
4037
4054
|
slackConversation,
|
|
@@ -4155,7 +4172,7 @@ function createSlackTurn(deps) {
|
|
|
4155
4172
|
maxTurns: botConfig.maxConsecutiveAutomatedTurns,
|
|
4156
4173
|
source
|
|
4157
4174
|
});
|
|
4158
|
-
await
|
|
4175
|
+
await stopAtAutomatedTurnLimit({
|
|
4159
4176
|
conversationId,
|
|
4160
4177
|
maxTurns: botConfig.maxConsecutiveAutomatedTurns,
|
|
4161
4178
|
source,
|
|
@@ -5361,7 +5378,7 @@ function restoreMessage(args) {
|
|
|
5361
5378
|
message.attachments = message.attachments.map((attachment) => args.adapter.rehydrateAttachment(attachment));
|
|
5362
5379
|
rehydrateAttachmentFetchers(message);
|
|
5363
5380
|
bindMessageAuthorIdentityId(message, args.record.input.authorIdentityId);
|
|
5364
|
-
|
|
5381
|
+
bindMessageInboxItemChange(message, args.record.input.reviewItemChange);
|
|
5365
5382
|
return message;
|
|
5366
5383
|
}
|
|
5367
5384
|
async function bindSlackActorIdentities(args) {
|
|
@@ -6331,6 +6348,12 @@ async function runPausedTurnInContext(payload, options, runOptions) {
|
|
|
6331
6348
|
turnId: turn.turnId,
|
|
6332
6349
|
errorMessage: "Authorization no longer belongs to this request"
|
|
6333
6350
|
});
|
|
6351
|
+
await getTurnLifecycle().complete({
|
|
6352
|
+
conversationId: payload.conversationId,
|
|
6353
|
+
createdAtMs: Date.now(),
|
|
6354
|
+
outcome: "cancelled",
|
|
6355
|
+
turnId: turn.turnId
|
|
6356
|
+
});
|
|
6334
6357
|
clearPendingAuth(conversation, turn.turnId);
|
|
6335
6358
|
await persistThreadStateById(payload.conversationId, { conversation });
|
|
6336
6359
|
return false;
|
|
@@ -6370,7 +6393,7 @@ async function runPausedTurnInContext(payload, options, runOptions) {
|
|
|
6370
6393
|
});
|
|
6371
6394
|
const source = routing.source;
|
|
6372
6395
|
const routingDestination = routing.destination;
|
|
6373
|
-
const turnMessages = activeTurn
|
|
6396
|
+
const turnMessages = savedTurnMessages(activeTurn, await loadTurnStart(payload.conversationId, payload.turnId)).map(({ message }) => message);
|
|
6374
6397
|
const recordDispatchOutcome = async (dispatchOutcome) => {
|
|
6375
6398
|
if (!dispatch) return;
|
|
6376
6399
|
await recordTurnSummary({
|
|
@@ -6404,7 +6427,10 @@ async function runPausedTurnInContext(payload, options, runOptions) {
|
|
|
6404
6427
|
text: userMessage.text
|
|
6405
6428
|
})
|
|
6406
6429
|
},
|
|
6407
|
-
history: dispatchId ?
|
|
6430
|
+
history: dispatchId ? {
|
|
6431
|
+
messages: activeTurn.piMessages,
|
|
6432
|
+
seqs: activeTurn.piMessageSeqs
|
|
6433
|
+
} : await loadConversationProjection({ conversationId: payload.conversationId }),
|
|
6408
6434
|
actor,
|
|
6409
6435
|
credentialContext,
|
|
6410
6436
|
destination: routingDestination,
|
|
@@ -6799,10 +6825,8 @@ function createConversationWork(options) {
|
|
|
6799
6825
|
await stopLateChildAgents();
|
|
6800
6826
|
return result;
|
|
6801
6827
|
};
|
|
6802
|
-
const run = async (
|
|
6803
|
-
|
|
6804
|
-
if ("skipped" in stopped) return stopped.skipped;
|
|
6805
|
-
const { context } = stopped;
|
|
6828
|
+
const run = async (context) => {
|
|
6829
|
+
await resumeForPersonInput(context.conversationId, context.attempt.messages);
|
|
6806
6830
|
const conversation = await options.conversationStore.get({ conversationId: context.conversationId });
|
|
6807
6831
|
const topLevel = isTopLevelKind(conversation?.kind ?? "root");
|
|
6808
6832
|
return await withLogContext({ rootConversationId: conversation?.rootConversationId ?? (topLevel ? context.conversationId : void 0) }, () => runByKind(context, topLevel));
|
|
@@ -8397,10 +8421,11 @@ const INBOX_SNOOZE_TIMER_INDEX = {
|
|
|
8397
8421
|
/**
|
|
8398
8422
|
* Fire the snooze triggers that one Event matches. A `resolve` trigger
|
|
8399
8423
|
* dismisses the item and cancels its snooze; a `wake` trigger ends the
|
|
8400
|
-
* snooze
|
|
8401
|
-
* that already ended ignores the Event. Returns
|
|
8424
|
+
* snooze, which records `reason`. When one Event fires both on a snooze,
|
|
8425
|
+
* `resolve` wins. A snooze that already ended ignores the Event. Returns
|
|
8426
|
+
* the number of items woken.
|
|
8402
8427
|
*/
|
|
8403
|
-
async function fireTriggers(db, event, nowMs) {
|
|
8428
|
+
async function fireTriggers(db, event, reason, nowMs) {
|
|
8404
8429
|
const triggers = (await listFiringInboxSnoozeTriggers(db, {
|
|
8405
8430
|
eventTypes: [event.eventType],
|
|
8406
8431
|
identifiers: event.identifiers,
|
|
@@ -8414,12 +8439,13 @@ async function fireTriggers(db, event, nowMs) {
|
|
|
8414
8439
|
snoozeIds: [...resolving],
|
|
8415
8440
|
state: "cancelled"
|
|
8416
8441
|
});
|
|
8417
|
-
await
|
|
8442
|
+
await dismissOpenInboxItems(tx, {
|
|
8418
8443
|
ids: resolvedItemIds,
|
|
8419
8444
|
nowMs,
|
|
8420
8445
|
reason: "A snooze trigger resolved it."
|
|
8421
8446
|
});
|
|
8422
8447
|
return (await settleInboxSnoozes(tx, {
|
|
8448
|
+
reason,
|
|
8423
8449
|
snoozeIds: [...waking],
|
|
8424
8450
|
state: "woken"
|
|
8425
8451
|
})).length;
|
|
@@ -8432,6 +8458,11 @@ async function fireInboxSnoozeTriggers(db, event, nowMs = Date.now()) {
|
|
|
8432
8458
|
eventType: event.eventType,
|
|
8433
8459
|
identifiers: [event.identifier],
|
|
8434
8460
|
namespace: event.namespace
|
|
8461
|
+
}, {
|
|
8462
|
+
eventType: event.eventType,
|
|
8463
|
+
identifier: event.identifier,
|
|
8464
|
+
kind: "event",
|
|
8465
|
+
namespace: event.namespace
|
|
8435
8466
|
}, nowMs);
|
|
8436
8467
|
}
|
|
8437
8468
|
/**
|
|
@@ -8487,7 +8518,7 @@ async function runInboxSnoozeTimers(db, nowMs) {
|
|
|
8487
8518
|
eventType: SNOOZE_TIMER_EVENT_TYPE,
|
|
8488
8519
|
identifiers: timerIds,
|
|
8489
8520
|
namespace: CORE_EVENT_NAMESPACE
|
|
8490
|
-
}, nowMs);
|
|
8521
|
+
}, { kind: "time" }, nowMs);
|
|
8491
8522
|
await mapBounded(timerIds, (id) => updateTimerIndex(state, INBOX_SNOOZE_TIMER_INDEX, {
|
|
8492
8523
|
id,
|
|
8493
8524
|
kind: "remove"
|
|
@@ -8605,10 +8636,10 @@ function createHeartbeatContext(args) {
|
|
|
8605
8636
|
db: getDb(),
|
|
8606
8637
|
embedder: createPluginEmbedder(pluginName),
|
|
8607
8638
|
events: args.events,
|
|
8608
|
-
|
|
8639
|
+
inboxItems: { forConversation: (conversationId) => createPluginInboxItems({
|
|
8609
8640
|
conversationId,
|
|
8610
8641
|
plugin: pluginName,
|
|
8611
|
-
show: args.
|
|
8642
|
+
show: args.showInboxItem ?? (async () => {})
|
|
8612
8643
|
}) },
|
|
8613
8644
|
state: createPluginState(pluginName),
|
|
8614
8645
|
log: createPluginLogger(pluginName),
|
|
@@ -8806,38 +8837,29 @@ function runCutoff(run) {
|
|
|
8806
8837
|
/**
|
|
8807
8838
|
* True when the participant row's root and every child conversation are idle
|
|
8808
8839
|
* and had no activity after the cutoff. Child activity does not move the
|
|
8809
|
-
* root's `lastActivityAt`, so the whole tree is checked.
|
|
8840
|
+
* root's `lastActivityAt`, so the whole tree is checked. A stopped
|
|
8841
|
+
* conversation counts from its stop: held input still saves Messages, which
|
|
8842
|
+
* would keep it from ever being quiet.
|
|
8810
8843
|
*/
|
|
8811
8844
|
function treeIsQuiet(run) {
|
|
8812
|
-
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.
|
|
8845
|
+
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(sql`coalesce(${juniorConversations.stoppedAt}, ${juniorConversations.lastActivityAt})`, runCutoff(run)))));
|
|
8813
8846
|
return sql`not exists (${active})`;
|
|
8814
8847
|
}
|
|
8815
|
-
const OPEN_PLAN_ITEM_STATUSES = PLAN_ITEM_STATUSES.filter(isOpenPlanItemStatus);
|
|
8816
8848
|
/**
|
|
8817
8849
|
* True when nothing in the participant row's tree needs a person. No
|
|
8818
|
-
* conversation in it has `needs_input` status: an open action
|
|
8850
|
+
* conversation in it has `needs_input` status: an open action Inbox item
|
|
8819
8851
|
* 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
|
|
8852
|
+
* as an answer that the starter has not read. No open To-do in it is
|
|
8821
8853
|
* assigned to a person. Archive applies to everyone, so input that waits
|
|
8822
8854
|
* on anyone keeps the tree. An archived child counts for nothing, as in
|
|
8823
8855
|
* the tree state.
|
|
8824
8856
|
*/
|
|
8825
8857
|
function treeNeedsNoOne() {
|
|
8826
|
-
const assignedToPerson = getDb().select({ id:
|
|
8858
|
+
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
8859
|
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
8860
|
return sql`not exists (${needing})`;
|
|
8829
8861
|
}
|
|
8830
8862
|
/**
|
|
8831
|
-
* True when no open Review item on the participant row's root or a child
|
|
8832
|
-
* conversation needs a person. Archive applies to everyone, so a
|
|
8833
|
-
* conversation that waits on anyone must stay in the feed.
|
|
8834
|
-
*/
|
|
8835
|
-
function notWaitingOnAnyone() {
|
|
8836
|
-
const linked = alias(juniorConversations, "linked_conversation");
|
|
8837
|
-
const waiting = getDb().select({ itemId: juniorReviewItemConversations.itemId }).from(juniorReviewItemConversations).innerJoin(juniorReviewItems, eq(juniorReviewItems.id, juniorReviewItemConversations.itemId)).innerJoin(linked, eq(linked.conversationId, juniorReviewItemConversations.conversationId)).where(and(reviewItemNeedsSomeone(), or(eq(linked.conversationId, juniorConversationParticipants.rootConversationId), eq(linked.rootConversationId, juniorConversationParticipants.rootConversationId))));
|
|
8838
|
-
return sql`not exists (${waiting})`;
|
|
8839
|
-
}
|
|
8840
|
-
/**
|
|
8841
8863
|
* True when no subscribed participant of the row's root pinned it or turned
|
|
8842
8864
|
* auto-archive off for it. Archive applies to everyone, so one person's run
|
|
8843
8865
|
* must not undo another person's pin or manual restore. A person who
|
|
@@ -8848,19 +8870,22 @@ function noParticipantKeepsRoot() {
|
|
|
8848
8870
|
const keeping = getDb().select({ userId: keeper.userId }).from(keeper).where(and(eq(keeper.rootConversationId, juniorConversationParticipants.rootConversationId), isNull(keeper.unsubscribedAt), or(isNotNull(keeper.pinnedAt), eq(keeper.autoArchive, false))));
|
|
8849
8871
|
return sql`not exists (${keeping})`;
|
|
8850
8872
|
}
|
|
8851
|
-
/**
|
|
8852
|
-
|
|
8873
|
+
/**
|
|
8874
|
+
* True when the participant row's root is not archived and is not a Lead.
|
|
8875
|
+
* The Lead is the dashboard home, not a feed row, so it is never archived.
|
|
8876
|
+
*/
|
|
8877
|
+
function rootIsArchivable() {
|
|
8853
8878
|
const root = alias(juniorConversations, "archive_root");
|
|
8854
|
-
const
|
|
8855
|
-
return sql`exists (${
|
|
8879
|
+
const eligible = getDb().select({ conversationId: root.conversationId }).from(root).where(and(eq(root.conversationId, juniorConversationParticipants.rootConversationId), isNull(root.archivedAt), or(isNull(root.kind), ne(root.kind, "lead"))));
|
|
8880
|
+
return sql`exists (${eligible})`;
|
|
8856
8881
|
}
|
|
8857
8882
|
/**
|
|
8858
8883
|
* 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
|
|
8884
|
+
* when it is archived, so new activity, a new run, a new Inbox item, or a
|
|
8860
8885
|
* changed setting wins over a stale read.
|
|
8861
8886
|
*/
|
|
8862
8887
|
function archivableRow(run) {
|
|
8863
|
-
return and(eq(juniorConversationParticipants.userId, run.userId), isNull(juniorConversationParticipants.unsubscribedAt),
|
|
8888
|
+
return and(eq(juniorConversationParticipants.userId, run.userId), isNull(juniorConversationParticipants.unsubscribedAt), rootIsArchivable(), noParticipantKeepsRoot(), lte(juniorConversationParticipants.lastMessageAt, runCutoff(run)), runOptsIn(run), run.kind === "scheduled" ? sql`${juniorUsers.autoArchiveGraceHours} <= ${run.graceHours}` : void 0, treeIsQuiet(run), treeNeedsNoOne());
|
|
8864
8889
|
}
|
|
8865
8890
|
/**
|
|
8866
8891
|
* One page of the user's participant rows on unarchived roots that may be
|
|
@@ -8902,10 +8927,7 @@ async function selectDoneRoots(rootIds, cutoffMs) {
|
|
|
8902
8927
|
async function archiveRoots(run, rootConversationIds) {
|
|
8903
8928
|
if (rootConversationIds.length === 0) return 0;
|
|
8904
8929
|
const archivable = getDb().select({ userId: juniorConversationParticipants.userId }).from(juniorConversationParticipants).innerJoin(juniorUsers, eq(juniorUsers.id, juniorConversationParticipants.userId)).where(and(eq(juniorConversationParticipants.rootConversationId, juniorConversations.conversationId), archivableRow(run)));
|
|
8905
|
-
return
|
|
8906
|
-
archivedAt: run.now,
|
|
8907
|
-
detailVersion: nextDetailVersion
|
|
8908
|
-
}).where(and(inArray(juniorConversations.conversationId, rootConversationIds), isNull(juniorConversations.archivedAt), sql`exists (${archivable})`)).returning({ conversationId: juniorConversations.conversationId })).length;
|
|
8930
|
+
return await setArchivedAt(getDb(), rootConversationIds, run.now, and(isNull(juniorConversations.archivedAt), sql`exists (${archivable})`));
|
|
8909
8931
|
}
|
|
8910
8932
|
/** Archive every done conversation of one user and count the rows. */
|
|
8911
8933
|
async function archiveUserDoneConversations(run) {
|
|
@@ -8932,7 +8954,7 @@ async function archiveUserDoneConversations(run) {
|
|
|
8932
8954
|
* conversation. Most users never turn it on, so the sweep reads only these.
|
|
8933
8955
|
*/
|
|
8934
8956
|
async function selectAutoArchiveUsers() {
|
|
8935
|
-
const optedInConversation = getDb().select({ userId: juniorConversationParticipants.userId }).from(juniorConversationParticipants).where(and(eq(juniorConversationParticipants.userId, juniorUsers.id), eq(juniorConversationParticipants.autoArchive, true),
|
|
8957
|
+
const optedInConversation = getDb().select({ userId: juniorConversationParticipants.userId }).from(juniorConversationParticipants).where(and(eq(juniorConversationParticipants.userId, juniorUsers.id), eq(juniorConversationParticipants.autoArchive, true), rootIsArchivable()));
|
|
8936
8958
|
return await getDb().select({
|
|
8937
8959
|
graceHours: juniorUsers.autoArchiveGraceHours,
|
|
8938
8960
|
id: juniorUsers.id
|
|
@@ -8996,7 +9018,7 @@ async function setConversationAutoArchive(viewer, conversationId, autoArchive) {
|
|
|
8996
9018
|
});
|
|
8997
9019
|
return { autoArchive };
|
|
8998
9020
|
}
|
|
8999
|
-
// src/chat/
|
|
9021
|
+
// src/chat/inbox-items/automation-answer.ts
|
|
9000
9022
|
function isStepLabel(label) {
|
|
9001
9023
|
return Object.hasOwn(AUTOMATION_ALERT_STEPS, label);
|
|
9002
9024
|
}
|
|
@@ -9216,31 +9238,31 @@ function createEventAppPublisher(args) {
|
|
|
9216
9238
|
}
|
|
9217
9239
|
};
|
|
9218
9240
|
}
|
|
9219
|
-
// src/chat/
|
|
9241
|
+
// src/chat/inbox-items/plugin-answer.ts
|
|
9220
9242
|
/**
|
|
9221
9243
|
* Give the answer of a plugin item with choices to the plugin that added it,
|
|
9222
9244
|
* so the plugin does the work. The answer starts no Turn. Throws when the
|
|
9223
9245
|
* plugin fails, so the person can retry the same answer.
|
|
9224
9246
|
*/
|
|
9225
|
-
async function
|
|
9247
|
+
async function answerPluginInboxItem(args) {
|
|
9226
9248
|
const { item } = args;
|
|
9227
|
-
const pluginName =
|
|
9249
|
+
const pluginName = inboxItemPlugin(item.dedupeKey);
|
|
9228
9250
|
const choice = item.answer?.values[PLUGIN_CHOICE_FIELD_ID]?.[0];
|
|
9229
9251
|
const conversationId = ownerConversationId(item);
|
|
9230
9252
|
if (!pluginName || !choice || !conversationId) return;
|
|
9231
9253
|
const plugin = getPlugins().find((p) => p.manifest.name === pluginName);
|
|
9232
|
-
const hook = plugin?.hooks?.
|
|
9254
|
+
const hook = plugin?.hooks?.inboxItemAnswered;
|
|
9233
9255
|
if (!plugin || !hook) return;
|
|
9234
9256
|
const events = createEventAppPublisher({ conversationWork: () => ({ queue: args.delivery.queue }) });
|
|
9235
9257
|
await hook({
|
|
9236
9258
|
...basePluginContext(plugin),
|
|
9237
9259
|
choice,
|
|
9238
9260
|
conversationId,
|
|
9239
|
-
dedupeKey: item.dedupeKey.slice(`${
|
|
9261
|
+
dedupeKey: item.dedupeKey.slice(`${PLUGIN_INBOX_ITEM_KEY_PREFIX}${pluginName}:`.length),
|
|
9240
9262
|
events: createPluginEventPublisher(plugin, events),
|
|
9241
9263
|
itemId: item.id,
|
|
9242
9264
|
nowMs: args.nowMs,
|
|
9243
|
-
|
|
9265
|
+
inboxItems: { forConversation: (conversationId) => createPluginInboxItems({
|
|
9244
9266
|
conversationId,
|
|
9245
9267
|
plugin: pluginName,
|
|
9246
9268
|
show: args.delivery.show
|
|
@@ -9249,7 +9271,7 @@ async function answerPluginReviewItem(args) {
|
|
|
9249
9271
|
watches: createPluginConversationWatches(plugin, conversationId)
|
|
9250
9272
|
});
|
|
9251
9273
|
}
|
|
9252
|
-
// src/chat/
|
|
9274
|
+
// src/chat/inbox-items/reply-match.ts
|
|
9253
9275
|
const MATCH_CONFIDENCE_THRESHOLD = .7;
|
|
9254
9276
|
/** A slow decision keeps the items open instead of delaying the close. */
|
|
9255
9277
|
const MATCH_TIMEOUT_MS = 1e4;
|
|
@@ -9284,7 +9306,7 @@ function matchQuestion(item) {
|
|
|
9284
9306
|
* decision call judges each item on its own, so a reply can answer one item,
|
|
9285
9307
|
* several items, or none. A failed decision throws.
|
|
9286
9308
|
*/
|
|
9287
|
-
async function
|
|
9309
|
+
async function matchReplyToInboxItems(args) {
|
|
9288
9310
|
const text = args.text.trim();
|
|
9289
9311
|
if (!text || args.items.length === 0) return /* @__PURE__ */ new Set();
|
|
9290
9312
|
const keys = args.items.map((_, index) => `item_${index}`);
|
|
@@ -9294,7 +9316,7 @@ async function matchReplyToReviewItems(args) {
|
|
|
9294
9316
|
modelId: botConfig.decisionModelId
|
|
9295
9317
|
},
|
|
9296
9318
|
modelId: botConfig.decisionModelId,
|
|
9297
|
-
operation: "
|
|
9319
|
+
operation: "inbox_item_reply_match",
|
|
9298
9320
|
cost: { conversationId: args.conversationId },
|
|
9299
9321
|
questions: Object.fromEntries(args.items.map((item, index) => [keys[index], matchQuestion(item)])),
|
|
9300
9322
|
signal: AbortSignal.timeout(MATCH_TIMEOUT_MS),
|
|
@@ -9312,20 +9334,20 @@ async function matchReplyToReviewItems(args) {
|
|
|
9312
9334
|
}
|
|
9313
9335
|
return matched;
|
|
9314
9336
|
}
|
|
9315
|
-
// src/chat/
|
|
9337
|
+
// src/chat/inbox-items/actions.ts
|
|
9316
9338
|
/** An expected failure of a person action, for the API to report. */
|
|
9317
|
-
var
|
|
9339
|
+
var InboxItemActionError = class extends Error {
|
|
9318
9340
|
code;
|
|
9319
9341
|
constructor(code, message) {
|
|
9320
9342
|
super(message);
|
|
9321
|
-
this.name = "
|
|
9343
|
+
this.name = "InboxItemActionError";
|
|
9322
9344
|
this.code = code;
|
|
9323
9345
|
}
|
|
9324
9346
|
};
|
|
9325
|
-
/** Read one
|
|
9326
|
-
async function
|
|
9327
|
-
const item = await
|
|
9328
|
-
if (!item || !await
|
|
9347
|
+
/** Read one Inbox item that a User can see, or fail as not found. */
|
|
9348
|
+
async function readInboxItemForUser(user, id) {
|
|
9349
|
+
const item = await getInboxItem(getDb(), id);
|
|
9350
|
+
if (!item || !await canUserReadInboxItem(item, user)) throw new InboxItemActionError("not_found", "Inbox item not found.");
|
|
9329
9351
|
return item;
|
|
9330
9352
|
}
|
|
9331
9353
|
function closedStatus(action) {
|
|
@@ -9354,17 +9376,17 @@ function isSameClose(item, action, user) {
|
|
|
9354
9376
|
return item.closeReason !== "Replied in thread" && item.closedBy?.userId === user.id && item.status === closedStatus(action) && action === "submit" === Boolean(item.answer);
|
|
9355
9377
|
}
|
|
9356
9378
|
function submittedAnswer(item, answer) {
|
|
9357
|
-
if (item.kind !== "action" || !item.request) throw new
|
|
9379
|
+
if (item.kind !== "action" || !item.request) throw new InboxItemActionError("invalid", "Only an action item takes an answer.");
|
|
9358
9380
|
const normalized = normalizeUserInputAnswer(item.request, {
|
|
9359
9381
|
other: answer?.other,
|
|
9360
9382
|
requestId: item.id,
|
|
9361
9383
|
values: answer?.values ?? {}
|
|
9362
9384
|
});
|
|
9363
|
-
if (isEmptyUserInputAnswer(normalized)) throw new
|
|
9385
|
+
if (isEmptyUserInputAnswer(normalized)) throw new InboxItemActionError("invalid", "The answer is empty.");
|
|
9364
9386
|
return normalized;
|
|
9365
9387
|
}
|
|
9366
9388
|
/**
|
|
9367
|
-
* Do one person action on
|
|
9389
|
+
* Do one person action on an Inbox item and tell its linked Conversations.
|
|
9368
9390
|
* The first submit or dismiss closes the item for every
|
|
9369
9391
|
* assignee. A retry of the same close sends any missing messages again and
|
|
9370
9392
|
* succeeds, so a client can retry after a failure. With `firstCloseOnly`,
|
|
@@ -9374,23 +9396,23 @@ function submittedAnswer(item, answer) {
|
|
|
9374
9396
|
* `exceptConversationId` is the Conversation where the person acted. It gets
|
|
9375
9397
|
* the person's input from its own surface, so it gets no message here.
|
|
9376
9398
|
* `delivery` shows the change and sends the messages; see
|
|
9377
|
-
* `
|
|
9399
|
+
* `deliverInboxItemChange`.
|
|
9378
9400
|
*/
|
|
9379
|
-
async function
|
|
9401
|
+
async function actOnInboxItem(args) {
|
|
9380
9402
|
const { action, user } = args;
|
|
9381
9403
|
const nowMs = args.nowMs ?? Date.now();
|
|
9382
9404
|
const db = getDb();
|
|
9383
|
-
const item = await
|
|
9405
|
+
const item = await readInboxItemForUser(user, args.id);
|
|
9384
9406
|
if (action === "take") {
|
|
9385
|
-
if (item.status !== "open") throw new
|
|
9386
|
-
if (!
|
|
9387
|
-
if (!isOnlyAssignee(item, user.id) && !await
|
|
9407
|
+
if (item.status !== "open") throw new InboxItemActionError("conflict", "Inbox item is closed.");
|
|
9408
|
+
if (!canActOnInboxItem(item, user.id)) throw new InboxItemActionError("forbidden", "Only an assignee can take this item.");
|
|
9409
|
+
if (!isOnlyAssignee(item, user.id) && !await takeInboxItem(db, {
|
|
9388
9410
|
id: item.id,
|
|
9389
9411
|
nowMs,
|
|
9390
9412
|
userId: user.id
|
|
9391
|
-
})) throw new
|
|
9392
|
-
const taken = await
|
|
9393
|
-
await
|
|
9413
|
+
})) throw new InboxItemActionError("conflict", "Inbox item is closed.");
|
|
9414
|
+
const taken = await readInboxItemForUser(user, item.id);
|
|
9415
|
+
await deliverInboxItemChange({
|
|
9394
9416
|
change: reviewItemChange(action, user),
|
|
9395
9417
|
delivery: args.delivery,
|
|
9396
9418
|
exceptConversationId: args.exceptConversationId,
|
|
@@ -9402,19 +9424,19 @@ async function actOnReviewItem(args) {
|
|
|
9402
9424
|
let closed = item;
|
|
9403
9425
|
let closedNow = false;
|
|
9404
9426
|
if (item.status === "open") {
|
|
9405
|
-
if (!
|
|
9427
|
+
if (!canActOnInboxItem(item, user.id)) throw new InboxItemActionError("forbidden", "Only an assignee can act on this item.");
|
|
9406
9428
|
const answer = action === "submit" ? submittedAnswer(item, args.answer) : void 0;
|
|
9407
|
-
closedNow = await
|
|
9429
|
+
closedNow = await closeInboxItem(db, {
|
|
9408
9430
|
closedByUserId: user.id,
|
|
9409
9431
|
id: item.id,
|
|
9410
9432
|
nowMs,
|
|
9411
9433
|
status: closedStatus(action),
|
|
9412
9434
|
...answer ? { answer } : void 0
|
|
9413
9435
|
});
|
|
9414
|
-
closed = await
|
|
9436
|
+
closed = await readInboxItemForUser(user, item.id);
|
|
9415
9437
|
}
|
|
9416
|
-
if (args.firstCloseOnly ? !closedNow : !isSameClose(closed, action, user)) throw new
|
|
9417
|
-
if (action === "submit" &&
|
|
9438
|
+
if (args.firstCloseOnly ? !closedNow : !isSameClose(closed, action, user)) throw new InboxItemActionError("conflict", "Inbox item is closed.");
|
|
9439
|
+
if (action === "submit" && isPluginInboxItem(closed)) await answerPluginInboxItem({
|
|
9418
9440
|
delivery: args.delivery,
|
|
9419
9441
|
item: closed,
|
|
9420
9442
|
nowMs
|
|
@@ -9425,11 +9447,11 @@ async function actOnReviewItem(args) {
|
|
|
9425
9447
|
user
|
|
9426
9448
|
});
|
|
9427
9449
|
} catch (error) {
|
|
9428
|
-
if (error instanceof ViewerTaskNotFoundError) throw new
|
|
9429
|
-
if (error instanceof AutomationEditError) throw new
|
|
9450
|
+
if (error instanceof ViewerTaskNotFoundError) throw new InboxItemActionError("not_found", "Automation not found.");
|
|
9451
|
+
if (error instanceof AutomationEditError) throw new InboxItemActionError("invalid", error.message);
|
|
9430
9452
|
throw error;
|
|
9431
9453
|
}
|
|
9432
|
-
await
|
|
9454
|
+
await deliverInboxItemChange({
|
|
9433
9455
|
change: reviewItemChange(action, user),
|
|
9434
9456
|
delivery: args.delivery,
|
|
9435
9457
|
exceptConversationId: args.exceptConversationId,
|
|
@@ -9470,21 +9492,21 @@ function messageAnswer(item, text) {
|
|
|
9470
9492
|
* - The replier is an assigned User, or the item has no assignees. A Slack
|
|
9471
9493
|
* replier without a Junior User closes only items with no assignees.
|
|
9472
9494
|
* - The decision model says that the reply answers this item
|
|
9473
|
-
* (`
|
|
9495
|
+
* (`matchReplyToInboxItems`). Other open items in the thread stay open.
|
|
9474
9496
|
* When the decision fails, all items stay open.
|
|
9475
9497
|
*
|
|
9476
9498
|
* Items assigned to Everyone, or only to other people, stay open. They need
|
|
9477
9499
|
* an answer on the card or the Inbox. Each item closes as `done` with
|
|
9478
|
-
* `
|
|
9500
|
+
* `INBOX_ITEM_REPLIED_REASON`, and the replier closes it. The reply itself
|
|
9479
9501
|
* is the answer in this Conversation, so only the other linked
|
|
9480
9502
|
* Conversations get a message. A click that closes the item first wins.
|
|
9481
9503
|
* A retry of the reply, or a later reply from the same person, delivers
|
|
9482
9504
|
* the items that it closed again: the cards show the close, and only the
|
|
9483
9505
|
* missing messages go. Each message has a key, so a message that was sent
|
|
9484
9506
|
* does not go again. `delivery` shows the change and sends the messages;
|
|
9485
|
-
* see `
|
|
9507
|
+
* see `deliverInboxItemChange`.
|
|
9486
9508
|
*/
|
|
9487
|
-
async function
|
|
9509
|
+
async function closeInboxItemsAnsweredByReply(args) {
|
|
9488
9510
|
const db = getDb();
|
|
9489
9511
|
const items = await listReplyActionItems(db, args.conversationId);
|
|
9490
9512
|
if (items.length === 0) return;
|
|
@@ -9494,13 +9516,13 @@ async function closeReviewItemsAnsweredByReply(args) {
|
|
|
9494
9516
|
const answered = items.filter((candidate) => replyAnswers(candidate, user));
|
|
9495
9517
|
let matched;
|
|
9496
9518
|
try {
|
|
9497
|
-
matched = await
|
|
9519
|
+
matched = await matchReplyToInboxItems({
|
|
9498
9520
|
conversationId: args.conversationId,
|
|
9499
9521
|
items: answered.filter((candidate) => candidate.status === "open"),
|
|
9500
9522
|
text: args.text
|
|
9501
9523
|
});
|
|
9502
9524
|
} catch (error) {
|
|
9503
|
-
logWarn("
|
|
9525
|
+
logWarn("inbox_item.reply_match.failed", {
|
|
9504
9526
|
"exception.message": error instanceof Error ? error.message : String(error),
|
|
9505
9527
|
"gen_ai.conversation.id": args.conversationId
|
|
9506
9528
|
});
|
|
@@ -9511,7 +9533,7 @@ async function closeReviewItemsAnsweredByReply(args) {
|
|
|
9511
9533
|
let closedItem = item;
|
|
9512
9534
|
if (item.status === "open") {
|
|
9513
9535
|
const answer = messageAnswer(item, args.text);
|
|
9514
|
-
if (!await
|
|
9536
|
+
if (!await closeInboxItem(db, {
|
|
9515
9537
|
...answer ? { answer } : void 0,
|
|
9516
9538
|
id: item.id,
|
|
9517
9539
|
nowMs,
|
|
@@ -9519,10 +9541,10 @@ async function closeReviewItemsAnsweredByReply(args) {
|
|
|
9519
9541
|
status: "done",
|
|
9520
9542
|
...user ? { closedByUserId: user.id } : void 0
|
|
9521
9543
|
})) continue;
|
|
9522
|
-
closedItem = await
|
|
9544
|
+
closedItem = await getInboxItem(db, item.id);
|
|
9523
9545
|
if (!closedItem) continue;
|
|
9524
9546
|
}
|
|
9525
|
-
await
|
|
9547
|
+
await deliverInboxItemChange({
|
|
9526
9548
|
change: {
|
|
9527
9549
|
kind: "replied",
|
|
9528
9550
|
who: user ? user.displayName ?? user.email : "A person"
|
|
@@ -9534,81 +9556,6 @@ async function closeReviewItemsAnsweredByReply(args) {
|
|
|
9534
9556
|
});
|
|
9535
9557
|
}
|
|
9536
9558
|
}
|
|
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
9559
|
// src/api/mentions.ts
|
|
9613
9560
|
function mentionedSlackUserIds(texts) {
|
|
9614
9561
|
const ids = texts.flatMap((text) => text ? slackMentionedUserIds(text) : []);
|
|
@@ -9864,11 +9811,209 @@ async function requireConversationPendingMessages(conversationId, options = {})
|
|
|
9864
9811
|
if (!report) throwApiError(404, "Conversation not found.");
|
|
9865
9812
|
return report;
|
|
9866
9813
|
}
|
|
9814
|
+
// src/api/mcp/conversation.ts
|
|
9815
|
+
/** Own the MCP view of one Conversation, shared by the conversation tools. */
|
|
9816
|
+
/** MCP view of one Conversation. It omits dashboard-only fields. */
|
|
9817
|
+
const mcpConversationSchema = z.object({
|
|
9818
|
+
conversationId: z.string(),
|
|
9819
|
+
title: z.string(),
|
|
9820
|
+
summary: z.string().optional().describe("What was asked and what happened, as of the last Turn."),
|
|
9821
|
+
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."),
|
|
9822
|
+
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."),
|
|
9823
|
+
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`."),
|
|
9824
|
+
watching: z.boolean().optional().describe("True when one of them has an active Watch or a pending Timer. It is not work."),
|
|
9825
|
+
surface: conversationSurfaceSchema.describe("Where it started: `slack`, `api` (the dashboard or MCP), `scheduler` (an automation), or `internal`."),
|
|
9826
|
+
channelName: z.string().optional().describe("Slack channel name."),
|
|
9827
|
+
locationUrl: z.string().optional().describe("Slack thread link."),
|
|
9828
|
+
startedAt: z.string(),
|
|
9829
|
+
lastSeenAt: z.string().describe("Time of the newest activity. archiveConversation takes this value."),
|
|
9830
|
+
archivedAt: z.string().optional().describe("Set when anyone archived it. Archive applies to everyone."),
|
|
9831
|
+
pinnedAt: z.string().optional().describe("Set when you pinned it."),
|
|
9832
|
+
url: z.string().optional().describe("Dashboard link.")
|
|
9833
|
+
}).strict();
|
|
9834
|
+
/** Map a Conversation summary to its MCP view. */
|
|
9835
|
+
function mcpConversation(summary) {
|
|
9836
|
+
return {
|
|
9837
|
+
conversationId: summary.conversationId,
|
|
9838
|
+
title: summary.displayTitle,
|
|
9839
|
+
summary: summary.summary,
|
|
9840
|
+
status: summary.status,
|
|
9841
|
+
turnActive: summary.turnActive,
|
|
9842
|
+
treeState: summary.treeState,
|
|
9843
|
+
watching: summary.watching,
|
|
9844
|
+
surface: summary.surface,
|
|
9845
|
+
channelName: summary.channelNameRedacted ? void 0 : summary.channelName,
|
|
9846
|
+
locationUrl: summary.locationUrl,
|
|
9847
|
+
startedAt: summary.startedAt,
|
|
9848
|
+
lastSeenAt: summary.lastSeenAt,
|
|
9849
|
+
archivedAt: summary.archivedAt ?? void 0,
|
|
9850
|
+
pinnedAt: summary.pinnedAt ?? void 0,
|
|
9851
|
+
url: getDashboardConversationLink(summary.conversationId)
|
|
9852
|
+
};
|
|
9853
|
+
}
|
|
9854
|
+
/** Conversation id param shared by the conversation tools. */
|
|
9855
|
+
const mcpConversationIdSchema = z.string().min(1).describe("Conversation id from searchConversations or createConversation.");
|
|
9856
|
+
const mcpAttachmentsSchema = z.array(z.object({
|
|
9857
|
+
filename: z.string(),
|
|
9858
|
+
contentType: z.string(),
|
|
9859
|
+
bytes: z.number().int()
|
|
9860
|
+
}).strict()).optional();
|
|
9861
|
+
function mcpAttachments(attachments) {
|
|
9862
|
+
return attachments?.length ? attachments.map(({ bytes, contentType, filename }) => ({
|
|
9863
|
+
bytes,
|
|
9864
|
+
contentType,
|
|
9865
|
+
filename
|
|
9866
|
+
})) : void 0;
|
|
9867
|
+
}
|
|
9868
|
+
function mcpAuthor(identity) {
|
|
9869
|
+
return identity?.fullName ?? identity?.slackUserName ?? identity?.email;
|
|
9870
|
+
}
|
|
9871
|
+
/** MCP view of one user or assistant Message. */
|
|
9872
|
+
const mcpMessageSchema = z.object({
|
|
9873
|
+
seq: z.number().int().describe("Position in the transcript. markConversationRead takes this value."),
|
|
9874
|
+
messageId: z.string().describe("For a message that you sent, the `messageId` that sendMessage or createConversation returned."),
|
|
9875
|
+
createdAt: z.string(),
|
|
9876
|
+
role: z.enum(["assistant", "user"]),
|
|
9877
|
+
author: z.string().optional(),
|
|
9878
|
+
text: z.string(),
|
|
9879
|
+
attachments: mcpAttachmentsSchema
|
|
9880
|
+
}).strict();
|
|
9881
|
+
/**
|
|
9882
|
+
* Keep the user and assistant Messages of a report event page, in order.
|
|
9883
|
+
* System Messages and Messages with no text or attachment are left out.
|
|
9884
|
+
*/
|
|
9885
|
+
function mcpMessages(events) {
|
|
9886
|
+
return events.flatMap((event) => {
|
|
9887
|
+
const data = event.data;
|
|
9888
|
+
if (data.type !== "message" || data.role === "system") return [];
|
|
9889
|
+
const text = data.text ?? "";
|
|
9890
|
+
const attachments = mcpAttachments(data.attachments);
|
|
9891
|
+
if (!text && !attachments) return [];
|
|
9892
|
+
const author = mcpAuthor(data.actorIdentity);
|
|
9893
|
+
return [{
|
|
9894
|
+
seq: event.seq,
|
|
9895
|
+
messageId: data.messageId,
|
|
9896
|
+
createdAt: event.createdAt,
|
|
9897
|
+
role: data.role,
|
|
9898
|
+
...author ? { author } : void 0,
|
|
9899
|
+
text,
|
|
9900
|
+
...attachments ? { attachments } : void 0
|
|
9901
|
+
}];
|
|
9902
|
+
});
|
|
9903
|
+
}
|
|
9904
|
+
/** Message text param shared by the tools that send a message. */
|
|
9905
|
+
const mcpMessageTextSchema = z.string().trim().min(1).max(32e3).describe("Message text.");
|
|
9906
|
+
/**
|
|
9907
|
+
* Idempotency key param shared by the tools that send a message. A retry
|
|
9908
|
+
* with the same key sends nothing new.
|
|
9909
|
+
*/
|
|
9910
|
+
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.");
|
|
9911
|
+
/**
|
|
9912
|
+
* MCP view of one accepted user Message that no Turn has read yet. It is not
|
|
9913
|
+
* in the transcript, so it has no `seq`.
|
|
9914
|
+
*/
|
|
9915
|
+
const mcpPendingMessageSchema = z.object({
|
|
9916
|
+
messageId: z.string(),
|
|
9917
|
+
createdAt: z.string(),
|
|
9918
|
+
author: z.string().optional(),
|
|
9919
|
+
text: z.string(),
|
|
9920
|
+
attachments: mcpAttachmentsSchema,
|
|
9921
|
+
delivery: conversationPendingMessageDeliverySchema.describe("`defer` waits for the running turn to end. `interrupt` joins the running turn at its next safe step.")
|
|
9922
|
+
}).strict();
|
|
9923
|
+
/** Pending Messages field shared by `getConversation` and the send tools. */
|
|
9924
|
+
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.");
|
|
9925
|
+
/** Authorization that a parked Turn waits for. */
|
|
9926
|
+
const mcpAuthorizationSchema = z.object({
|
|
9927
|
+
label: z.string(),
|
|
9928
|
+
url: z.string()
|
|
9929
|
+
}).strict().describe("Set when a turn waits for you to connect an account. Open `url` in a browser to continue.");
|
|
9930
|
+
/**
|
|
9931
|
+
* Read the Messages that wait for a Turn and the authorization that a parked
|
|
9932
|
+
* Turn waits for. The caller must check that `user` is a participant.
|
|
9933
|
+
*/
|
|
9934
|
+
async function readMcpPendingWork(user, conversationId) {
|
|
9935
|
+
const report = await readConversationPendingMessages(conversationId, { viewer: user });
|
|
9936
|
+
const pendingMessages = (report?.messages ?? []).flatMap((message) => {
|
|
9937
|
+
if (message.text === void 0) return [];
|
|
9938
|
+
const author = mcpAuthor(message.actorIdentity);
|
|
9939
|
+
const attachments = mcpAttachments(message.attachments);
|
|
9940
|
+
return [{
|
|
9941
|
+
messageId: message.messageId,
|
|
9942
|
+
createdAt: message.createdAt,
|
|
9943
|
+
...author ? { author } : void 0,
|
|
9944
|
+
text: message.text,
|
|
9945
|
+
...attachments ? { attachments } : void 0,
|
|
9946
|
+
delivery: message.delivery
|
|
9947
|
+
}];
|
|
9948
|
+
});
|
|
9949
|
+
const authorization = report?.authorization;
|
|
9950
|
+
return {
|
|
9951
|
+
pendingMessages,
|
|
9952
|
+
...authorization ? { authorization: {
|
|
9953
|
+
label: authorization.label,
|
|
9954
|
+
url: authorization.authorizationUrl
|
|
9955
|
+
} } : void 0
|
|
9956
|
+
};
|
|
9957
|
+
}
|
|
9958
|
+
/**
|
|
9959
|
+
* Read pending work for a send result. The message already landed, so a
|
|
9960
|
+
* failed read drops these optional fields instead of turning the accepted
|
|
9961
|
+
* send into a tool error that a client may retry.
|
|
9962
|
+
*/
|
|
9963
|
+
async function readMcpPendingWorkAfterSend(user, conversationId) {
|
|
9964
|
+
try {
|
|
9965
|
+
return await readMcpPendingWork(user, conversationId);
|
|
9966
|
+
} catch (error) {
|
|
9967
|
+
logException(error, "mcp.pending_work.read.failed", { "gen_ai.conversation.id": conversationId });
|
|
9968
|
+
return {};
|
|
9969
|
+
}
|
|
9970
|
+
}
|
|
9971
|
+
/** `cursor` result field shared by getConversation and the send tools. */
|
|
9972
|
+
const mcpCursorSchema = z.string().describe("Pass as `after` to getConversation to read the messages that come after this point.");
|
|
9973
|
+
/** Result of a tool that sends a message. */
|
|
9974
|
+
const mcpAcceptedMessageSchema = {
|
|
9975
|
+
conversationId: z.string(),
|
|
9976
|
+
messageId: z.string().describe("Id of your message in `pendingMessages`, and later in the transcript."),
|
|
9977
|
+
status: z.enum(["accepted", "duplicate"]).describe("`duplicate` when the idempotency key was already used."),
|
|
9978
|
+
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."),
|
|
9979
|
+
authorization: mcpAuthorizationSchema.optional(),
|
|
9980
|
+
cursor: mcpCursorSchema,
|
|
9981
|
+
url: z.string().optional().describe("Dashboard link.")
|
|
9982
|
+
};
|
|
9983
|
+
// src/api/operation.ts
|
|
9984
|
+
/** Define an operation and keep its input and output types. */
|
|
9985
|
+
function defineApiOperation(operation) {
|
|
9986
|
+
return operation;
|
|
9987
|
+
}
|
|
9988
|
+
async function readJsonBody(context) {
|
|
9989
|
+
const text = await context.req.text();
|
|
9990
|
+
if (!text) return {};
|
|
9991
|
+
try {
|
|
9992
|
+
return JSON.parse(text);
|
|
9993
|
+
} catch (error) {
|
|
9994
|
+
throwApiError(400, "Invalid request body.", error);
|
|
9995
|
+
}
|
|
9996
|
+
}
|
|
9997
|
+
/**
|
|
9998
|
+
* Serve an operation as a REST handler after `requireViewer`. Route params
|
|
9999
|
+
* win over body fields of the same name.
|
|
10000
|
+
*/
|
|
10001
|
+
function apiOperationHandler(operation, services) {
|
|
10002
|
+
return async (context) => {
|
|
10003
|
+
const body = await readJsonBody(context);
|
|
10004
|
+
const input = operation.input.safeParse(typeof body === "object" && body !== null && !Array.isArray(body) ? {
|
|
10005
|
+
...body,
|
|
10006
|
+
...context.req.param()
|
|
10007
|
+
} : body);
|
|
10008
|
+
if (!input.success) throwApiError(400, "Invalid request body.", input.error);
|
|
10009
|
+
return jsonResponse(operation.output, await operation.run(context.get("viewer"), input.data, services));
|
|
10010
|
+
};
|
|
10011
|
+
}
|
|
9867
10012
|
// src/api/conversations/cancel-pending-messages.ts
|
|
9868
10013
|
/** Cancel accepted human-facing mailbox rows for one conversation participant. */
|
|
9869
10014
|
async function cancelConversationPendingMessagesForViewer(viewer, conversationId, body = {}) {
|
|
9870
10015
|
if (!await getConversationStore().get({ conversationId })) throwApiError(404, "Conversation not found.");
|
|
9871
|
-
if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(
|
|
10016
|
+
if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(404, "Conversation not found.");
|
|
9872
10017
|
try {
|
|
9873
10018
|
const result = await cancelHumanFacingPendingMessages({
|
|
9874
10019
|
conversationId,
|
|
@@ -9889,6 +10034,243 @@ async function cancelConversationPendingMessagesForViewer(viewer, conversationId
|
|
|
9889
10034
|
throwApiError(500, "Unable to cancel queued messages.", error);
|
|
9890
10035
|
}
|
|
9891
10036
|
}
|
|
10037
|
+
// src/api/conversations/pin.ts
|
|
10038
|
+
/**
|
|
10039
|
+
* Pin or unpin one conversation for the signed-in viewer.
|
|
10040
|
+
*
|
|
10041
|
+
* A pin lives on the viewer's participant row, and that row grants send and
|
|
10042
|
+
* control access. So only a participant can pin, the same as archive. A pin
|
|
10043
|
+
* also restores an archived conversation for everyone, because the Pinned
|
|
10044
|
+
* section shows only active conversations. A pin on a child would be a fact
|
|
10045
|
+
* of the child, not of the viewer's root, and no list shows child pins yet,
|
|
10046
|
+
* so only a root can be pinned.
|
|
10047
|
+
*/
|
|
10048
|
+
async function pinConversation(viewer, conversationId, body) {
|
|
10049
|
+
if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(404, "Conversation not found.");
|
|
10050
|
+
const executor = getSqlExecutor();
|
|
10051
|
+
return await executor.transaction(async () => {
|
|
10052
|
+
const db = executor.db();
|
|
10053
|
+
const result = await setPin(db, viewer, conversationId, body.pinned);
|
|
10054
|
+
recordPinUsage(body.pinned ? "pin" : "unpin", await countViewerPins(db, viewer));
|
|
10055
|
+
return result;
|
|
10056
|
+
});
|
|
10057
|
+
}
|
|
10058
|
+
/**
|
|
10059
|
+
* Tag the request span with a pin change and the viewer's pin count after
|
|
10060
|
+
* it. Pins stay manual; this shows how much people use them.
|
|
10061
|
+
*/
|
|
10062
|
+
function recordPinUsage(action, pinnedCount) {
|
|
10063
|
+
setSpanAttributes({
|
|
10064
|
+
"app.conversation.pin.action": action,
|
|
10065
|
+
"app.conversation.pin.count": pinnedCount
|
|
10066
|
+
});
|
|
10067
|
+
}
|
|
10068
|
+
async function countViewerPins(db, viewer) {
|
|
10069
|
+
const [row] = await db.select({ pins: count() }).from(juniorConversationParticipants).where(and(eq(juniorConversationParticipants.userId, viewer.id), isNotNull(juniorConversationParticipants.pinnedAt)));
|
|
10070
|
+
return row?.pins ?? 0;
|
|
10071
|
+
}
|
|
10072
|
+
async function setPin(db, viewer, conversationId, pinned) {
|
|
10073
|
+
const [conversation] = await db.select({
|
|
10074
|
+
archivedAt: juniorConversations.archivedAt,
|
|
10075
|
+
kind: juniorConversations.kind,
|
|
10076
|
+
lastActivityAt: juniorConversations.lastActivityAt,
|
|
10077
|
+
parentConversationId: juniorConversations.parentConversationId,
|
|
10078
|
+
rootConversationId: juniorConversations.rootConversationId
|
|
10079
|
+
}).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId)).limit(1).for("no key update");
|
|
10080
|
+
if (!conversation) throwApiError(404, "Conversation not found.");
|
|
10081
|
+
if (!isTopLevelKind(conversationKindFromRow(conversation))) throwApiError(409, `A child conversation cannot be pinned or unpinned. It uses its root's pin: ${conversation.rootConversationId ?? conversation.parentConversationId}.`);
|
|
10082
|
+
if (!pinned) {
|
|
10083
|
+
await db.update(juniorConversationParticipants).set({
|
|
10084
|
+
pinnedAt: null,
|
|
10085
|
+
pinPosition: null
|
|
10086
|
+
}).where(and(eq(juniorConversationParticipants.userId, viewer.id), eq(juniorConversationParticipants.rootConversationId, conversationId)));
|
|
10087
|
+
return { pinnedAt: null };
|
|
10088
|
+
}
|
|
10089
|
+
if (conversation.archivedAt) await setArchivedAt(db, [conversationId], null);
|
|
10090
|
+
const pinnedAt = /* @__PURE__ */ new Date();
|
|
10091
|
+
await db.insert(juniorConversationParticipants).values({
|
|
10092
|
+
lastMessageAt: conversation.lastActivityAt,
|
|
10093
|
+
pinnedAt,
|
|
10094
|
+
rootConversationId: conversationId,
|
|
10095
|
+
userId: viewer.id
|
|
10096
|
+
}).onConflictDoUpdate({
|
|
10097
|
+
target: [juniorConversationParticipants.userId, juniorConversationParticipants.rootConversationId],
|
|
10098
|
+
set: {
|
|
10099
|
+
pinnedAt,
|
|
10100
|
+
pinPosition: null,
|
|
10101
|
+
unsubscribedAt: null
|
|
10102
|
+
}
|
|
10103
|
+
});
|
|
10104
|
+
return { pinnedAt: pinnedAt.toISOString() };
|
|
10105
|
+
}
|
|
10106
|
+
/**
|
|
10107
|
+
* Save the viewer's Pinned order. Each listed pin takes its index as its
|
|
10108
|
+
* place. The update reads only the viewer's own pinned rows, so an id that
|
|
10109
|
+
* the viewer did not pin changes nothing and grants nothing.
|
|
10110
|
+
*/
|
|
10111
|
+
async function reorderPinnedConversations(viewer, body) {
|
|
10112
|
+
const ids = body.conversationIds;
|
|
10113
|
+
const participants = juniorConversationParticipants;
|
|
10114
|
+
const positions = sql.join(ids.map((id, index) => sql`when ${id} then ${index}::integer`), sql` `);
|
|
10115
|
+
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 });
|
|
10116
|
+
recordPinUsage("reorder", updated.length);
|
|
10117
|
+
const updatedIds = new Set(updated.map((row) => row.rootConversationId));
|
|
10118
|
+
return { conversationIds: ids.filter((id) => updatedIds.has(id)) };
|
|
10119
|
+
}
|
|
10120
|
+
// src/api/conversations/stop.ts
|
|
10121
|
+
/**
|
|
10122
|
+
* Stop one Conversation for a participant: its active Turn, its session, and
|
|
10123
|
+
* every child agent below it.
|
|
10124
|
+
*
|
|
10125
|
+
* The stop also removes the human messages queued before it. The viewer's own
|
|
10126
|
+
* web text comes back in the response so the dashboard can restore it to the
|
|
10127
|
+
* composer instead of losing it.
|
|
10128
|
+
*/
|
|
10129
|
+
async function stopConversationTurnForViewer(viewer, conversationId, services) {
|
|
10130
|
+
const conversationStore = getConversationStore();
|
|
10131
|
+
if (!await conversationStore.get({ conversationId })) throwApiError(404, "Conversation not found.");
|
|
10132
|
+
if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(404, "Conversation not found.");
|
|
10133
|
+
try {
|
|
10134
|
+
const result = await stopConversation({
|
|
10135
|
+
conversationId,
|
|
10136
|
+
conversationStore,
|
|
10137
|
+
queue: services.queue
|
|
10138
|
+
});
|
|
10139
|
+
if (result.status !== "requested") return {
|
|
10140
|
+
conversationId,
|
|
10141
|
+
status: "no_work",
|
|
10142
|
+
stoppedInboundMessageIds: [],
|
|
10143
|
+
stoppedMessages: []
|
|
10144
|
+
};
|
|
10145
|
+
await clearSlackPendingReactions({
|
|
10146
|
+
getSlackAdapter: getProductionSlackAdapter,
|
|
10147
|
+
messages: result.pendingMessages
|
|
10148
|
+
});
|
|
10149
|
+
return {
|
|
10150
|
+
conversationId,
|
|
10151
|
+
status: "requested",
|
|
10152
|
+
stoppedInboundMessageIds: result.pendingMessages.map((message) => message.inboundMessageId),
|
|
10153
|
+
stoppedMessages: viewerWebMessages(result.pendingMessages, viewer)
|
|
10154
|
+
};
|
|
10155
|
+
} catch (error) {
|
|
10156
|
+
throwApiError(500, "Unable to stop the active turn.", error);
|
|
10157
|
+
}
|
|
10158
|
+
}
|
|
10159
|
+
function viewerWebMessages(messages, viewer) {
|
|
10160
|
+
const viewerUserIds = webActorUserIds(viewer);
|
|
10161
|
+
return messages.flatMap((message) => {
|
|
10162
|
+
if (message.source !== "web") return [];
|
|
10163
|
+
const metadata = legacyWebMailboxMetadataSchema.safeParse(message.input.metadata);
|
|
10164
|
+
if (!metadata.success) return [];
|
|
10165
|
+
if (!viewerUserIds.includes(metadata.data.authorUserId)) return [];
|
|
10166
|
+
const text = message.input.text.trim();
|
|
10167
|
+
return text ? [{
|
|
10168
|
+
inboundMessageId: message.inboundMessageId,
|
|
10169
|
+
text
|
|
10170
|
+
}] : [];
|
|
10171
|
+
});
|
|
10172
|
+
}
|
|
10173
|
+
// src/api/conversations/operations.ts
|
|
10174
|
+
/** Own the Conversation operations that the REST API and MCP share. */
|
|
10175
|
+
const conversationIdInput = { conversationId: mcpConversationIdSchema };
|
|
10176
|
+
const writeAnnotations = {
|
|
10177
|
+
destructiveHint: false,
|
|
10178
|
+
idempotentHint: true,
|
|
10179
|
+
readOnlyHint: false
|
|
10180
|
+
};
|
|
10181
|
+
/** Archive or restore one Conversation, and optionally its children. */
|
|
10182
|
+
const archiveConversationOperation = defineApiOperation({
|
|
10183
|
+
name: "archiveConversation",
|
|
10184
|
+
title: "Archive conversation",
|
|
10185
|
+
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.",
|
|
10186
|
+
scope: "conversations:manage",
|
|
10187
|
+
input: archiveConversationBodySchema.extend(conversationIdInput),
|
|
10188
|
+
output: archiveConversationResponseSchema,
|
|
10189
|
+
annotations: writeAnnotations,
|
|
10190
|
+
run: (viewer, { conversationId, ...body }) => archiveConversation(viewer, conversationId, body)
|
|
10191
|
+
});
|
|
10192
|
+
/** Archive every done Conversation of the viewer once. */
|
|
10193
|
+
const archiveDoneConversationsOperation = defineApiOperation({
|
|
10194
|
+
name: "archiveDoneConversations",
|
|
10195
|
+
title: "Archive done conversations",
|
|
10196
|
+
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.",
|
|
10197
|
+
scope: "conversations:manage",
|
|
10198
|
+
input: z.object({}).strict(),
|
|
10199
|
+
output: archiveDoneConversationsResponseSchema,
|
|
10200
|
+
annotations: writeAnnotations,
|
|
10201
|
+
run: (viewer) => archiveViewerDoneConversations(viewer)
|
|
10202
|
+
});
|
|
10203
|
+
/** Pin or unpin one top-level Conversation for the viewer. */
|
|
10204
|
+
const pinConversationOperation = defineApiOperation({
|
|
10205
|
+
name: "pinConversation",
|
|
10206
|
+
title: "Pin conversation",
|
|
10207
|
+
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.",
|
|
10208
|
+
scope: "conversations:manage",
|
|
10209
|
+
input: pinConversationBodySchema.extend(conversationIdInput),
|
|
10210
|
+
output: pinConversationResponseSchema,
|
|
10211
|
+
annotations: writeAnnotations,
|
|
10212
|
+
run: (viewer, { conversationId, ...body }) => pinConversation(viewer, conversationId, body)
|
|
10213
|
+
});
|
|
10214
|
+
/** Override the viewer's auto-archive default for one Conversation. */
|
|
10215
|
+
const setConversationAutoArchiveOperation = defineApiOperation({
|
|
10216
|
+
name: "setConversationAutoArchive",
|
|
10217
|
+
title: "Set conversation auto-archive",
|
|
10218
|
+
description: "Turn auto-archive on or off for one of your conversations. This overrides your default for that conversation only.",
|
|
10219
|
+
scope: "conversations:manage",
|
|
10220
|
+
input: conversationAutoArchiveSchema.extend(conversationIdInput),
|
|
10221
|
+
output: conversationAutoArchiveSchema,
|
|
10222
|
+
annotations: writeAnnotations,
|
|
10223
|
+
run: (viewer, { autoArchive, conversationId }) => setConversationAutoArchive(viewer, conversationId, autoArchive)
|
|
10224
|
+
});
|
|
10225
|
+
/** Subscribe or unsubscribe the viewer. It never changes another person. */
|
|
10226
|
+
const setConversationSubscriptionOperation = defineApiOperation({
|
|
10227
|
+
name: "setConversationSubscription",
|
|
10228
|
+
title: "Set conversation subscription",
|
|
10229
|
+
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.",
|
|
10230
|
+
scope: "conversations:manage",
|
|
10231
|
+
input: conversationSubscriptionBodySchema.extend(conversationIdInput),
|
|
10232
|
+
output: conversationSubscriptionResponseSchema,
|
|
10233
|
+
annotations: writeAnnotations,
|
|
10234
|
+
run: (viewer, { conversationId, ...body }) => setConversationSubscription(viewer, conversationId, body)
|
|
10235
|
+
});
|
|
10236
|
+
/** Stop the running Turn and every child agent below it. */
|
|
10237
|
+
const stopConversationOperation = defineApiOperation({
|
|
10238
|
+
name: "stopConversation",
|
|
10239
|
+
title: "Stop conversation",
|
|
10240
|
+
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.",
|
|
10241
|
+
scope: "conversations:manage",
|
|
10242
|
+
input: z.object(conversationIdInput).strict(),
|
|
10243
|
+
output: stopConversationTurnResponseSchema,
|
|
10244
|
+
annotations: {
|
|
10245
|
+
...writeAnnotations,
|
|
10246
|
+
destructiveHint: true
|
|
10247
|
+
},
|
|
10248
|
+
run: (viewer, { conversationId }, services) => stopConversationTurnForViewer(viewer, conversationId, services)
|
|
10249
|
+
});
|
|
10250
|
+
/** Drop the messages that wait for the running Turn. The Turn continues. */
|
|
10251
|
+
const cancelQueuedMessagesOperation = defineApiOperation({
|
|
10252
|
+
name: "cancelQueuedMessages",
|
|
10253
|
+
title: "Cancel queued messages",
|
|
10254
|
+
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.",
|
|
10255
|
+
scope: "conversations:manage",
|
|
10256
|
+
input: cancelConversationPendingMessagesBodySchema.extend(conversationIdInput),
|
|
10257
|
+
output: cancelConversationPendingMessagesResponseSchema,
|
|
10258
|
+
annotations: {
|
|
10259
|
+
...writeAnnotations,
|
|
10260
|
+
destructiveHint: true
|
|
10261
|
+
},
|
|
10262
|
+
run: (viewer, { conversationId, ...body }) => cancelConversationPendingMessagesForViewer(viewer, conversationId, body)
|
|
10263
|
+
});
|
|
10264
|
+
/** Every Conversation operation, for the MCP server. */
|
|
10265
|
+
const conversationOperations = [
|
|
10266
|
+
cancelQueuedMessagesOperation,
|
|
10267
|
+
archiveConversationOperation,
|
|
10268
|
+
archiveDoneConversationsOperation,
|
|
10269
|
+
pinConversationOperation,
|
|
10270
|
+
setConversationAutoArchiveOperation,
|
|
10271
|
+
setConversationSubscriptionOperation,
|
|
10272
|
+
stopConversationOperation
|
|
10273
|
+
];
|
|
9892
10274
|
// src/api/conversations/cursor.ts
|
|
9893
10275
|
const CURSOR_CONTEXT = "junior-conversation-report-cursor";
|
|
9894
10276
|
const conversationCursorPayloadSchema = z.object({
|
|
@@ -9994,8 +10376,8 @@ async function createConversationForViewer(viewer, body, services) {
|
|
|
9994
10376
|
throwApiError(500, "Unable to create conversation.", error);
|
|
9995
10377
|
}
|
|
9996
10378
|
}
|
|
9997
|
-
/** Append one
|
|
9998
|
-
async function appendConversationMessageForViewer(viewer, conversationId, body, services) {
|
|
10379
|
+
/** Append one viewer message to an existing conversation. */
|
|
10380
|
+
async function appendConversationMessageForViewer(viewer, conversationId, body, services, delivery) {
|
|
9999
10381
|
await requireWebMessageConversation(viewer, conversationId, body.idempotencyKey);
|
|
10000
10382
|
const uploads = await verifyUploads({
|
|
10001
10383
|
conversationId,
|
|
@@ -10006,6 +10388,7 @@ async function appendConversationMessageForViewer(viewer, conversationId, body,
|
|
|
10006
10388
|
const append = () => appendAndEnqueueWebMessage({
|
|
10007
10389
|
actor,
|
|
10008
10390
|
conversationId,
|
|
10391
|
+
delivery,
|
|
10009
10392
|
idempotencyKey: body.idempotencyKey,
|
|
10010
10393
|
message: body.message,
|
|
10011
10394
|
uploads
|
|
@@ -10014,11 +10397,11 @@ async function appendConversationMessageForViewer(viewer, conversationId, body,
|
|
|
10014
10397
|
attachmentStorage: services.attachmentStorage,
|
|
10015
10398
|
queue: services.queue
|
|
10016
10399
|
});
|
|
10017
|
-
const closeAnswered = () =>
|
|
10400
|
+
const closeAnswered = () => closeInboxItemsAnsweredByReply({
|
|
10018
10401
|
conversationId,
|
|
10019
10402
|
delivery: {
|
|
10020
10403
|
queue: services.queue,
|
|
10021
|
-
show:
|
|
10404
|
+
show: createSlackInboxItemShow(getProductionSlackAdapter)
|
|
10022
10405
|
},
|
|
10023
10406
|
resolveUser: async () => viewer,
|
|
10024
10407
|
text: body.message
|
|
@@ -10671,15 +11054,6 @@ function eventMentionTexts(data) {
|
|
|
10671
11054
|
default: return [];
|
|
10672
11055
|
}
|
|
10673
11056
|
}
|
|
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
11057
|
function withMentions(value, mentions) {
|
|
10684
11058
|
return mentions.length > 0 ? {
|
|
10685
11059
|
...value,
|
|
@@ -10687,7 +11061,7 @@ function withMentions(value, mentions) {
|
|
|
10687
11061
|
} : value;
|
|
10688
11062
|
}
|
|
10689
11063
|
/**
|
|
10690
|
-
* Attach the people that each event and the
|
|
11064
|
+
* Attach the people that each event and the summary of one conversation
|
|
10691
11065
|
* mention, resolved at read time.
|
|
10692
11066
|
*/
|
|
10693
11067
|
async function attachConversationMentions(executor, conversationId, content) {
|
|
@@ -10696,14 +11070,14 @@ async function attachConversationMentions(executor, conversationId, content) {
|
|
|
10696
11070
|
tenantId,
|
|
10697
11071
|
texts: eventMentionTexts(event.data)
|
|
10698
11072
|
}));
|
|
10699
|
-
if (content.
|
|
11073
|
+
if (content.summary) sources.push({
|
|
10700
11074
|
tenantId,
|
|
10701
|
-
texts:
|
|
11075
|
+
texts: [content.summary]
|
|
10702
11076
|
});
|
|
10703
11077
|
const mentions = await resolveMentions(executor, sources);
|
|
10704
11078
|
return {
|
|
10705
|
-
|
|
10706
|
-
|
|
11079
|
+
events: content.events.map((event, index) => withMentions(event, mentions[index])),
|
|
11080
|
+
summaryMentions: content.summary ? mentions.at(-1) : []
|
|
10707
11081
|
};
|
|
10708
11082
|
}
|
|
10709
11083
|
/**
|
|
@@ -10877,16 +11251,19 @@ const agentTreeRoot = alias(juniorConversations, "detail_agent_tree_root");
|
|
|
10877
11251
|
function agentTreeRootLabel(db, rootConversationId) {
|
|
10878
11252
|
return db.select({ label: sql`row(${agentTreeRoot.title}, ${agentTreeRoot.channelName})::text` }).from(agentTreeRoot).where(eq(agentTreeRoot.conversationId, rootConversationId));
|
|
10879
11253
|
}
|
|
11254
|
+
const SUBTREE = "detail_subtree";
|
|
10880
11255
|
/**
|
|
10881
|
-
* Sum the detail versions of
|
|
11256
|
+
* Sum the detail versions of each Conversation and its child agents, one
|
|
11257
|
+
* row per Conversation found, in one pass over all their trees. Child
|
|
10882
11258
|
* writes bump only their own row, and the row count changes when a child
|
|
10883
11259
|
* starts, so the parent needs no bump of its own.
|
|
10884
11260
|
*/
|
|
10885
|
-
function
|
|
11261
|
+
function subtreeDetailVersions(conversationIds) {
|
|
10886
11262
|
return getDb().select({
|
|
11263
|
+
conversationId: sql`${conversationSubtreeColumns.scopeConversationId}`.as("conversation_id"),
|
|
10887
11264
|
conversations: sql`count(*)::int`.as("conversations"),
|
|
10888
11265
|
version: sql`coalesce(sum(${juniorConversations.detailVersion}), 0)::text`.as("version")
|
|
10889
|
-
}).from(juniorConversations).innerJoin(conversationSubtree(
|
|
11266
|
+
}).from(juniorConversations).innerJoin(conversationSubtree(conversationIds), eq(conversationSubtreeColumns.conversationId, juniorConversations.conversationId)).groupBy(conversationSubtreeColumns.scopeConversationId).as(SUBTREE);
|
|
10890
11267
|
}
|
|
10891
11268
|
const versionConversation = alias(juniorConversations, "version_conversation");
|
|
10892
11269
|
const versionFork = alias(juniorConversations, "version_fork");
|
|
@@ -10896,7 +11273,8 @@ const versionUser = alias(juniorUsers, "version_user");
|
|
|
10896
11273
|
* Hash the detail state whose writes do not bump `detail_version`: the
|
|
10897
11274
|
* viewer's marks and auto-archive choice on the root, the forks, and the
|
|
10898
11275
|
* matched Slack files. Each part is a lookup by key, so the versions poll
|
|
10899
|
-
* stays one cheap statement.
|
|
11276
|
+
* stays one cheap statement. `conversationId` is the id column of the
|
|
11277
|
+
* outer row.
|
|
10900
11278
|
*/
|
|
10901
11279
|
function viewerStateVersion(db, conversationId, viewerId) {
|
|
10902
11280
|
const root = db.select({ id: sql`coalesce(${versionConversation.rootConversationId}, ${versionConversation.conversationId})` }).from(versionConversation).where(eq(versionConversation.conversationId, conversationId));
|
|
@@ -10911,15 +11289,28 @@ function viewerStateVersion(db, conversationId, viewerId) {
|
|
|
10911
11289
|
))`;
|
|
10912
11290
|
}
|
|
10913
11291
|
/**
|
|
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.
|
|
11292
|
+
* Return a query for the change token of each Conversation and its child
|
|
11293
|
+
* agents, as the viewer sees it, one row per Conversation found. A missing
|
|
11294
|
+
* one has no row. The detail report sends the same token, so the dashboard
|
|
11295
|
+
* can find a stale detail without asking for the report. All ids share
|
|
11296
|
+
* one plan, so a longer list adds no subquery per id.
|
|
11297
|
+
*/
|
|
11298
|
+
function conversationVersionsQuery(db, conversationIds, viewerId) {
|
|
11299
|
+
const subtree = subtreeDetailVersions(conversationIds);
|
|
11300
|
+
const rowConversationId = sql`${sql.identifier(SUBTREE)}.${sql.identifier("conversation_id")}`;
|
|
11301
|
+
const viewerState = viewerId ? viewerStateVersion(db, rowConversationId, viewerId) : sql`null`;
|
|
11302
|
+
return db.select({
|
|
11303
|
+
conversationId: subtree.conversationId,
|
|
11304
|
+
version: sql`concat_ws(':', ${subtree.conversations}, ${subtree.version}, ${viewerState})`.as("version")
|
|
11305
|
+
}).from(subtree);
|
|
11306
|
+
}
|
|
11307
|
+
/**
|
|
11308
|
+
* Return a query for the `conversationVersionsQuery` token of one
|
|
11309
|
+
* Conversation, or a null token when it is missing.
|
|
10918
11310
|
*/
|
|
10919
11311
|
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);
|
|
11312
|
+
const versions = conversationVersionsQuery(db, [conversationId], viewerId).as("detail_token");
|
|
11313
|
+
return db.select({ version: versions.version }).from(versions);
|
|
10923
11314
|
}
|
|
10924
11315
|
/**
|
|
10925
11316
|
* Read the record and the stored rows that the detail state needs in one
|
|
@@ -11351,7 +11742,7 @@ const WATCH_LOOKUP_LIMIT = 50;
|
|
|
11351
11742
|
* a Turn waits on the User to sign in.
|
|
11352
11743
|
*/
|
|
11353
11744
|
function needsUserSql(userId) {
|
|
11354
|
-
return sql`(exists (select 1 from ${
|
|
11745
|
+
return sql`(exists (select 1 from ${juniorInboxItems} where ${and(inboxItemOwnedByConversation(juniorConversations.conversationId), inboxItemNeedsInput(), inboxItemForUser(userId))}) or ${awaitsAuthorizationFrom(juniorConversations.conversationId, userId)})`;
|
|
11355
11746
|
}
|
|
11356
11747
|
/**
|
|
11357
11748
|
* Read the tree state of each Conversation for one viewer, over the
|
|
@@ -11421,7 +11812,7 @@ function projectConversationDetail(args) {
|
|
|
11421
11812
|
}),
|
|
11422
11813
|
annotations: canExposePayload ? args.annotations : [],
|
|
11423
11814
|
sidebarAnnotations: canExposePayload ? args.sidebarAnnotations : void 0,
|
|
11424
|
-
...canExposePayload && args.
|
|
11815
|
+
...canExposePayload && args.summaryMentions ? { summaryMentions: args.summaryMentions } : void 0,
|
|
11425
11816
|
events: args.events,
|
|
11426
11817
|
...args.appended ? { appended: true } : void 0,
|
|
11427
11818
|
...args.appendCursor ? { appendCursor: args.appendCursor } : void 0,
|
|
@@ -11483,7 +11874,7 @@ async function readConversationDetailFromSql(conversationId, options) {
|
|
|
11483
11874
|
limit: options.limit
|
|
11484
11875
|
});
|
|
11485
11876
|
};
|
|
11486
|
-
const [agentTree, annotations, automationTitleByConversation, auxiliaryCostsByConversation,
|
|
11877
|
+
const [agentTree, annotations, automationTitleByConversation, auxiliaryCostsByConversation, firstHumanMessageTextByConversation, modelUsage, metricsByConversation, people, sourceTask, teamDomainByTeamId, treeStateByConversation, page] = await Promise.all([
|
|
11487
11878
|
readConversationAgentTree({
|
|
11488
11879
|
conversationId,
|
|
11489
11880
|
...record.conversation.parentConversationId ? { parentConversationId: record.conversation.parentConversationId } : void 0
|
|
@@ -11497,7 +11888,6 @@ async function readConversationDetailFromSql(conversationId, options) {
|
|
|
11497
11888
|
})),
|
|
11498
11889
|
readAutomationTitlesByConversationId([record.conversation]),
|
|
11499
11890
|
readConversationAuxiliaryCostsFromSql(getDb(), [conversationId]),
|
|
11500
|
-
readLatestConversationBrief(getDb(), conversationId),
|
|
11501
11891
|
readFirstHumanMessageTexts(getDb(), [record.conversation]),
|
|
11502
11892
|
isPurged ? Promise.resolve([]) : readConversationModelUsageFromSql(executor, { conversationId }),
|
|
11503
11893
|
readConversationTreeMetricsFromSql(getDb(), [conversationId]),
|
|
@@ -11512,14 +11902,14 @@ async function readConversationDetailFromSql(conversationId, options) {
|
|
|
11512
11902
|
]);
|
|
11513
11903
|
const firstSeq = page.events[0]?.seq;
|
|
11514
11904
|
const unreadAfterSeq = readPosition !== void 0 && page.previousSeq !== void 0 && firstSeq !== void 0 && readPosition.lastReadSeq + 1 < firstSeq ? readPosition.lastReadSeq : void 0;
|
|
11515
|
-
const
|
|
11516
|
-
const [{
|
|
11905
|
+
const summary = canExposePayload ? record.conversation.summary : void 0;
|
|
11906
|
+
const [{ events, summaryMentions }, unreadPage, sidebarAnnotations] = await Promise.all([
|
|
11517
11907
|
startSpan({
|
|
11518
11908
|
name: "Attach conversation mentions",
|
|
11519
11909
|
op: "function"
|
|
11520
11910
|
}, () => attachConversationMentions(executor, conversationId, {
|
|
11521
|
-
|
|
11522
|
-
|
|
11911
|
+
events: page.events.map(formatConversationEventText),
|
|
11912
|
+
...summary ? { summary } : void 0
|
|
11523
11913
|
})),
|
|
11524
11914
|
options.unreadPage && unreadAfterSeq !== void 0 ? readConversationEventPageAround(executor, {
|
|
11525
11915
|
canExposePayload,
|
|
@@ -11552,12 +11942,7 @@ async function readConversationDetailFromSql(conversationId, options) {
|
|
|
11552
11942
|
sidebarAnnotations,
|
|
11553
11943
|
auxiliaryCosts: auxiliaryCosts?.total,
|
|
11554
11944
|
...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,
|
|
11945
|
+
...summaryMentions.length > 0 ? { summaryMentions } : void 0,
|
|
11561
11946
|
durationMs: metrics?.durationMs ?? record.durationMs,
|
|
11562
11947
|
events,
|
|
11563
11948
|
firstHumanMessageText: firstHumanMessageTextByConversation.get(conversationId),
|
|
@@ -11603,97 +11988,21 @@ async function readConversationDetail(conversationId, options = {}) {
|
|
|
11603
11988
|
} : { limit: options.limit }
|
|
11604
11989
|
});
|
|
11605
11990
|
}
|
|
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
|
-
}
|
|
11991
|
+
// src/chat/conversations/sql/listed.ts
|
|
11675
11992
|
/**
|
|
11676
|
-
*
|
|
11677
|
-
*
|
|
11678
|
-
* the viewer did not pin changes nothing and grants nothing.
|
|
11993
|
+
* Match Conversations that are not a Lead. The dashboard home opens the
|
|
11994
|
+
* Lead, so lists leave it out. Older rows have no kind.
|
|
11679
11995
|
*/
|
|
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)) };
|
|
11996
|
+
function notLeadConversation() {
|
|
11997
|
+
return or(isNull(juniorConversations.kind), ne(juniorConversations.kind, "lead"));
|
|
11688
11998
|
}
|
|
11689
|
-
// src/chat/conversations/sql/listed.ts
|
|
11690
11999
|
/**
|
|
11691
12000
|
* 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.
|
|
12001
|
+
* an unkept Quick question or a Lead. Each list adds its own access and
|
|
12002
|
+
* scope filters. Structural root checks, such as retention, do not use this.
|
|
11694
12003
|
*/
|
|
11695
12004
|
function listedConversation() {
|
|
11696
|
-
return and(isNull(juniorConversations.parentConversationId), isNull(juniorConversations.quickQuestionAt));
|
|
12005
|
+
return and(isNull(juniorConversations.parentConversationId), isNull(juniorConversations.quickQuestionAt), notLeadConversation());
|
|
11697
12006
|
}
|
|
11698
12007
|
// src/api/conversations/threads.ts
|
|
11699
12008
|
/**
|
|
@@ -11733,16 +12042,20 @@ async function readFeedThreadRecords(db, rootIds) {
|
|
|
11733
12042
|
* Nest the shown Threads of `readFeedThreadRecords` under their nearest shown
|
|
11734
12043
|
* ancestor. A Thread shows when it and every ancestor have no
|
|
11735
12044
|
* `archived_at`. A Thread uses the access of its root. `tree` holds the
|
|
11736
|
-
* trees of at least the listed roots.
|
|
12045
|
+
* trees of at least the listed roots. Each root lists at most
|
|
12046
|
+
* `CONVERSATION_FEED_THREAD_LIMIT` Threads, depth first in activity order,
|
|
12047
|
+
* so a kept Thread always has its parent.
|
|
11737
12048
|
*/
|
|
11738
12049
|
function nestFeedThreads(records, tree, accessByRoot) {
|
|
11739
12050
|
if (!records) return /* @__PURE__ */ new Map();
|
|
11740
12051
|
const { firstHumanMessageTexts, rootIds, threads } = records;
|
|
11741
12052
|
const childrenByParent = /* @__PURE__ */ new Map();
|
|
12053
|
+
const placedByRoot = /* @__PURE__ */ new Map();
|
|
11742
12054
|
for (const { conversation, row } of threads) {
|
|
11743
12055
|
const parentId = findThreadPlacement(conversation.conversationId, tree, rootIds);
|
|
11744
12056
|
if (!parentId) continue;
|
|
11745
12057
|
const rootId = row.conversation.rootConversationId;
|
|
12058
|
+
if (rootId) placedByRoot.set(rootId, (placedByRoot.get(rootId) ?? 0) + 1);
|
|
11746
12059
|
const summary = conversationSummaryFromStoredConversation({
|
|
11747
12060
|
access: rootId ? accessByRoot.get(rootId) : void 0,
|
|
11748
12061
|
conversation,
|
|
@@ -11755,16 +12068,26 @@ function nestFeedThreads(records, tree, accessByRoot) {
|
|
|
11755
12068
|
siblings.push(summary);
|
|
11756
12069
|
childrenByParent.set(parentId, siblings);
|
|
11757
12070
|
}
|
|
11758
|
-
const nest = (items) => items.
|
|
12071
|
+
const nest = (items, budget) => items.flatMap((item) => {
|
|
12072
|
+
if (budget.left === 0) return [];
|
|
12073
|
+
budget.left -= 1;
|
|
11759
12074
|
const children = childrenByParent.get(item.conversationId);
|
|
11760
|
-
|
|
12075
|
+
const nested = children ? nest(children, budget) : [];
|
|
12076
|
+
return [nested.length > 0 ? {
|
|
11761
12077
|
...item,
|
|
11762
|
-
threads:
|
|
11763
|
-
} : item;
|
|
12078
|
+
threads: nested
|
|
12079
|
+
} : item];
|
|
11764
12080
|
});
|
|
11765
12081
|
return new Map([...rootIds].flatMap((rootId) => {
|
|
11766
12082
|
const children = childrenByParent.get(rootId);
|
|
11767
|
-
|
|
12083
|
+
if (!children) return [];
|
|
12084
|
+
const budget = { left: 100 };
|
|
12085
|
+
const nested = nest(children, budget);
|
|
12086
|
+
const shown = 100 - budget.left;
|
|
12087
|
+
return [[rootId, {
|
|
12088
|
+
omittedThreadCount: (placedByRoot.get(rootId) ?? 0) - shown,
|
|
12089
|
+
threads: nested
|
|
12090
|
+
}]];
|
|
11768
12091
|
}));
|
|
11769
12092
|
}
|
|
11770
12093
|
// src/api/conversations/priority.ts
|
|
@@ -11842,29 +12165,6 @@ async function readConversationActivityPreviews(db, conversationIds) {
|
|
|
11842
12165
|
}
|
|
11843
12166
|
return previews;
|
|
11844
12167
|
}
|
|
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
12168
|
// src/api/conversations/feed-links.ts
|
|
11869
12169
|
const RECENT_USE_LIMIT = 20;
|
|
11870
12170
|
const CANDIDATE_LINK_LIMIT = 6;
|
|
@@ -11933,13 +12233,13 @@ function feedMediaSql(db) {
|
|
|
11933
12233
|
}
|
|
11934
12234
|
// src/api/conversations/feed-answer.ts
|
|
11935
12235
|
/**
|
|
11936
|
-
* A feed row column with the viewer's newest answered
|
|
12236
|
+
* A feed row column with the viewer's newest answered Inbox item of its
|
|
11937
12237
|
* Conversation, or null. It is a scalar subquery on the row read, so the
|
|
11938
12238
|
* answer costs no round trip of its own, however many items the viewer
|
|
11939
12239
|
* closed since.
|
|
11940
12240
|
*/
|
|
11941
12241
|
function feedViewerAnswerSql(db, userId) {
|
|
11942
|
-
const latest = db.select({ answer: sql`jsonb_build_object('answer', ${
|
|
12242
|
+
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
12243
|
return sql`(${latest})`;
|
|
11944
12244
|
}
|
|
11945
12245
|
/**
|
|
@@ -12014,30 +12314,30 @@ function conversationCodeRepositoryFilter(repositoryId, viewerUserId) {
|
|
|
12014
12314
|
)
|
|
12015
12315
|
)`, rootVisibleToViewer(viewerUserId));
|
|
12016
12316
|
}
|
|
12017
|
-
async function conversationRows(db, { codeRepository, conversationIds, cursor, filter, include = [],
|
|
12317
|
+
async function conversationRows(db, { codeRepository, conversationIds, cursor, filter, include = [], includePrivateMatches = false, limit, pinnedForUserId, query, status, waitingForUserId }) {
|
|
12018
12318
|
const rows = db.select({
|
|
12019
12319
|
...conversationRecordColumns(),
|
|
12020
12320
|
activityCursor: sql`to_char(${juniorConversations.lastActivityAt} at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`,
|
|
12021
12321
|
lastMessageAt: sql`coalesce(${juniorConversations.lastMessageAt}, ${lastMessageAtSql(db)})`.mapWith(juniorConversations.lastMessageAt),
|
|
12022
12322
|
awaitingAuthorization: treeAwaitsAuthorization(juniorConversations.conversationId),
|
|
12323
|
+
latestTurnFailed: conversationTurnFailedSql(juniorConversations),
|
|
12023
12324
|
links: include.includes("links") ? feedLinksSql(db) : sql`null`,
|
|
12024
12325
|
media: include.includes("media") ? feedMediaSql(db) : sql`null`,
|
|
12025
12326
|
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();
|
|
12327
|
+
}).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
12328
|
return limit === void 0 ? rows : rows.limit(limit);
|
|
12040
12329
|
}
|
|
12330
|
+
const searchAnnotated = alias(juniorConversations, "search_annotated");
|
|
12331
|
+
/**
|
|
12332
|
+
* Match a root whose tree has an Annotation with the text in its label or
|
|
12333
|
+
* title, such as `getsentry/roach#12`. The feed shows the annotations of
|
|
12334
|
+
* the whole tree, so search reads the same rows. Private annotations match
|
|
12335
|
+
* only where the feed shows them.
|
|
12336
|
+
*/
|
|
12337
|
+
function annotationMatch(db, query, includePrivate) {
|
|
12338
|
+
const annotation = juniorConversationAnnotations.annotation;
|
|
12339
|
+
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`)));
|
|
12340
|
+
}
|
|
12041
12341
|
/**
|
|
12042
12342
|
* Feed rows show last activity only as an age in whole minutes. A running
|
|
12043
12343
|
* row shows its running state in place of the age, so it shows no activity.
|
|
@@ -12072,7 +12372,7 @@ const feedAnnotated = alias(juniorConversations, "feed_annotated");
|
|
|
12072
12372
|
* The rows are in feed order, so a move that reorders them moves the token.
|
|
12073
12373
|
* The newest Message of each role stands for the preview and participants.
|
|
12074
12374
|
* Threads and annotations show from the whole tree. Waiting roots outside
|
|
12075
|
-
* the page move the
|
|
12375
|
+
* the page move the Inbox items token.
|
|
12076
12376
|
*/
|
|
12077
12377
|
function conversationFeedVersionQuery(db, userId) {
|
|
12078
12378
|
const pin = juniorConversationParticipants;
|
|
@@ -12081,7 +12381,7 @@ function conversationFeedVersionQuery(db, userId) {
|
|
|
12081
12381
|
count(*) filter (where ${feedTree.archivedAt} is not null),
|
|
12082
12382
|
count(*) filter (where ${feedTree.stoppedAt} is not null),
|
|
12083
12383
|
coalesce(bool_or(${conversationIsActiveSql(feedTree)}) filter (where ${ne(feedTree.conversationId, conversationId)}), false),
|
|
12084
|
-
bool_or(exists (select 1 from ${
|
|
12384
|
+
bool_or(exists (select 1 from ${juniorInboxItems} where ${and(inboxItemOwnedByConversation(feedTree.conversationId), inboxItemNeedsInput(), inboxItemForUser(userId))}) or ${awaitsAuthorizationFrom(feedTree.conversationId, userId)}),
|
|
12085
12385
|
string_agg(concat_ws('/',
|
|
12086
12386
|
${feedTree.conversationId}, ${feedTree.title},
|
|
12087
12387
|
${conversationStatusSql(feedTree)},
|
|
@@ -12163,7 +12463,7 @@ async function readConversationFeedFromSql(options = {}) {
|
|
|
12163
12463
|
} } : void 0,
|
|
12164
12464
|
filter,
|
|
12165
12465
|
include,
|
|
12166
|
-
|
|
12466
|
+
includePrivateMatches: filter?.kind === "viewer",
|
|
12167
12467
|
query,
|
|
12168
12468
|
status
|
|
12169
12469
|
};
|
|
@@ -12188,7 +12488,12 @@ async function readConversationFeedFromSql(options = {}) {
|
|
|
12188
12488
|
firstPage ? conversationRows(db, {
|
|
12189
12489
|
filter,
|
|
12190
12490
|
include,
|
|
12191
|
-
|
|
12491
|
+
includePrivateMatches: true,
|
|
12492
|
+
limit: limit + 50 + 1,
|
|
12493
|
+
pinnedForUserId: {
|
|
12494
|
+
pinned: false,
|
|
12495
|
+
userId: filter.userId
|
|
12496
|
+
},
|
|
12192
12497
|
status: "active",
|
|
12193
12498
|
waitingForUserId: filter.userId
|
|
12194
12499
|
}) : []
|
|
@@ -12196,16 +12501,19 @@ async function readConversationFeedFromSql(options = {}) {
|
|
|
12196
12501
|
const page = pageRows.slice(0, limit);
|
|
12197
12502
|
const lastRow = pageRows.length > limit ? page.at(-1) : void 0;
|
|
12198
12503
|
const rows = [...pinnedRows, ...page];
|
|
12504
|
+
let waitingRowsTruncated = false;
|
|
12199
12505
|
if (firstPage) {
|
|
12200
12506
|
const loaded = new Set(rows.map((row) => row.conversation.conversationId));
|
|
12201
12507
|
const outsidePage = waitingRows.filter((row) => !loaded.has(row.conversation.conversationId));
|
|
12202
|
-
|
|
12203
|
-
|
|
12508
|
+
waitingRowsTruncated = outsidePage.length > 50;
|
|
12509
|
+
const waiting = outsidePage.slice(0, 50);
|
|
12510
|
+
options.onWaitingRows?.(waiting.length);
|
|
12511
|
+
rows.push(...waiting);
|
|
12204
12512
|
}
|
|
12205
12513
|
const conversations = rows.map((row) => conversationFromRecordRow(row));
|
|
12206
12514
|
const conversationIds = conversations.map((conversation) => conversation.conversationId);
|
|
12207
12515
|
const conversationTrees = readConversationTrees(db, conversationIds);
|
|
12208
|
-
const [accessRows, tree, participantsByRoot, annotationsByConversation, auxiliaryCostsByRoot, metricsByRoot, participantsByConversation, teamDomainByTeamId, { work: conversationWork, lastUserMessageAt: lastUserMessageAtByConversation }, activityPreviewByConversation,
|
|
12516
|
+
const [accessRows, tree, participantsByRoot, annotationsByConversation, auxiliaryCostsByRoot, metricsByRoot, participantsByConversation, teamDomainByTeamId, { work: conversationWork, lastUserMessageAt: lastUserMessageAtByConversation }, activityPreviewByConversation, automationTitleByConversation, firstHumanMessageTextByConversation, treeStateByConversation, threadRecords] = await Promise.all([
|
|
12209
12517
|
readConversationAccessRows(db, conversationIds),
|
|
12210
12518
|
conversationTrees,
|
|
12211
12519
|
readMemberParticipants(db, conversationIds, options.viewer ? { userId: options.viewer.id } : filter ? feedMember(filter) : void 0),
|
|
@@ -12219,7 +12527,6 @@ async function readConversationFeedFromSql(options = {}) {
|
|
|
12219
12527
|
lastUserMessageAt: await readLastUserMessageAtByConversation(db, work.assignedIds.filter((conversationId) => work.finishedAtById[conversationId]))
|
|
12220
12528
|
})),
|
|
12221
12529
|
readConversationActivityPreviews(db, conversationIds),
|
|
12222
|
-
readConversationFeedBriefs(db, conversationIds),
|
|
12223
12530
|
readAutomationTitlesByConversationId(conversations),
|
|
12224
12531
|
readFirstHumanMessageTexts(db, conversations),
|
|
12225
12532
|
readConversationTreeStates(db, conversationIds, options.viewer?.id),
|
|
@@ -12264,13 +12571,11 @@ async function readConversationFeedFromSql(options = {}) {
|
|
|
12264
12571
|
...conversationWork.finishedAtById[conversation.conversationId] ? { finishedWorkAt: conversationWork.finishedAtById[conversation.conversationId] } : void 0,
|
|
12265
12572
|
...unfinishedWork.has(conversation.conversationId) ? { unfinishedWork: true } : void 0
|
|
12266
12573
|
};
|
|
12267
|
-
const annotations = access?.canViewPrivateContent ? annotationsByConversation.get(conversation.conversationId) ?? [] : [];
|
|
12268
12574
|
const activityPreview = visibleActivityPreviews.get(conversation.conversationId);
|
|
12269
|
-
const brief = access?.canViewPrivateContent ? briefByConversation.get(conversation.conversationId) : void 0;
|
|
12270
12575
|
const participants = access?.canViewPrivateContent ? participantsByConversation.get(conversation.conversationId) : void 0;
|
|
12271
12576
|
const threads = threadsByRoot.get(conversation.conversationId);
|
|
12272
12577
|
const media = access?.canViewPrivateContent ? row.media : null;
|
|
12273
|
-
const links = access?.canViewPrivateContent && row.links ? pickFeedLinks(conversation.conversationId, row.links, annotationUrls(
|
|
12578
|
+
const links = access?.canViewPrivateContent && row.links ? pickFeedLinks(conversation.conversationId, row.links, annotationUrls(visibleAnnotationsByConversation.get(conversation.conversationId))) : [];
|
|
12274
12579
|
const lastMessageAt = row.lastMessageAt?.toISOString();
|
|
12275
12580
|
const treeRead = treeStateByConversation.get(conversation.conversationId);
|
|
12276
12581
|
const viewerAnswer = access?.canViewPrivateContent ? feedViewerAnswer(row.viewerAnswer) : void 0;
|
|
@@ -12279,15 +12584,15 @@ async function readConversationFeedFromSql(options = {}) {
|
|
|
12279
12584
|
...work,
|
|
12280
12585
|
...treeRead,
|
|
12281
12586
|
...row.awaitingAuthorization ? { awaitingAuthorization: true } : void 0,
|
|
12587
|
+
...row.latestTurnFailed ? { latestTurnFailed: true } : void 0,
|
|
12282
12588
|
...lastMessageAt ? { lastMessageAt } : void 0,
|
|
12283
|
-
...threads ? { threads } : void 0,
|
|
12589
|
+
...threads ? { threads: threads.threads } : void 0,
|
|
12590
|
+
...threads?.omittedThreadCount ? { omittedThreadCount: threads.omittedThreadCount } : void 0,
|
|
12284
12591
|
...participants && participants.length > 0 ? { participants } : void 0,
|
|
12285
12592
|
...activityPreview ? { activityPreview } : void 0,
|
|
12286
|
-
...brief ? { brief } : void 0,
|
|
12287
12593
|
...viewerAnswer ? { viewerAnswer } : void 0,
|
|
12288
12594
|
...media?.length ? { media } : void 0,
|
|
12289
12595
|
...links.length > 0 ? { links } : void 0,
|
|
12290
|
-
...annotations.length > 0 ? { annotations } : void 0,
|
|
12291
12596
|
...sidebarAnnotationsByConversation[conversation.conversationId] ? { sidebarAnnotations: sidebarAnnotationsByConversation[conversation.conversationId] } : void 0,
|
|
12292
12597
|
isPriority: isConversationPriority({
|
|
12293
12598
|
lastSeenAt: summary.lastSeenAt,
|
|
@@ -12301,7 +12606,8 @@ async function readConversationFeedFromSql(options = {}) {
|
|
|
12301
12606
|
at: lastRow.activityCursor,
|
|
12302
12607
|
conversationId: lastRow.conversation.conversationId
|
|
12303
12608
|
}) } : void 0,
|
|
12304
|
-
source: "conversation_index"
|
|
12609
|
+
source: "conversation_index",
|
|
12610
|
+
...waitingRowsTruncated ? { waitingRowsTruncated: true } : void 0
|
|
12305
12611
|
};
|
|
12306
12612
|
}
|
|
12307
12613
|
/**
|
|
@@ -12315,76 +12621,4 @@ async function readConversationFeedFromSql(options = {}) {
|
|
|
12315
12621
|
async function readConversationFeed(options = {}) {
|
|
12316
12622
|
return readConversationFeedFromSql(options);
|
|
12317
12623
|
}
|
|
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 };
|
|
12624
|
+
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 };
|