@sentry/junior 0.310.0 → 0.311.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 +259 -0
- package/dist/{adapter-context-BhKpjpGD.js → adapter-context-G2M0y6rP.js} +2 -2
- package/dist/{admin-tgZEZAk2.js → admin-DCiBhUT1.js} +1 -2
- package/dist/{agent-runner-D9cvNlQl.js → agent-runner-BVHPUIc8.js} +543 -1703
- package/dist/api/schema.d.ts +2 -2
- package/dist/api/schema.js +7 -6
- package/dist/api.d.ts +21 -3
- package/dist/api.js +1479 -372
- package/dist/{app-B_7Wn0en.d.ts → app-Cw5Vy6H6.d.ts} +14 -3
- package/dist/app.d.ts +2 -2
- package/dist/app.js +232 -506
- package/dist/{background-compaction-queue-BGHqkhkY.js → background-compaction-queue-CJDnWVOJ.js} +4 -4
- package/dist/{briefs-DKxkoruh.js → briefs-BDjnug6Y.js} +3 -3
- package/dist/{catalog-runtime-BxwzbLKY.js → catalog-runtime-DMY3VV-D.js} +1 -1
- package/dist/cli/chat.js +16 -16
- package/dist/cli/check.js +23 -29
- package/dist/cli/init.js +1 -6
- package/dist/cli/main.js +3 -3
- package/dist/cli/plugins.js +8 -7
- package/dist/cli/snapshot-create.js +5 -5
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +3 -3
- package/dist/{config-Dkt2Le2b.js → config-BrXDQefC.js} +239 -5
- package/dist/{continue-in-slack-BWVwePKD.js → continue-in-slack-DNXSC9So.js} +6 -5
- package/dist/{conversation-M9KZ5JxF.js → conversation-ca__NDQW.js} +47 -8
- package/dist/{conversation-feed-Ci6YD1N-.js → conversation-feed-DkinDu5o.js} +15 -6
- package/dist/{conversation-privacy-C39g8BY4.js → conversation-privacy-DxttrKb9.js} +1 -1
- package/dist/{conversation-turn-CBlZIH02.js → conversation-turn-DWw7Xhdr.js} +41 -38
- package/dist/{credential-sync-vGnrB0BY.js → credential-sync-Bk8wGb8Y.js} +15 -16
- package/dist/{db-B4Hjxr-u.d.ts → db-7ETESH44.d.ts} +3 -1
- package/dist/{db-CFZggNoy.js → db-DTxzH7u5.js} +1609 -1040
- package/dist/{executor-BPkZDx5-.js → executor-DqTiYj9S.js} +450 -99
- package/dist/{html-2r2KmLwi.js → html-B9Sl4Axb.js} +6 -6
- package/dist/{install-C-oE6C_u.js → install-Sg4ePfLl.js} +2 -2
- package/dist/instrumentation.js +3 -3
- package/dist/{lineage-CsvrEFQe.js → lineage-BHAMpNKr.js} +2 -2
- package/dist/{logging-D5gkyvnK.js → logging-FjclQsXu.js} +47 -9
- package/dist/{message-DwvJ-I3w.js → message-CJ7_RL50.js} +5 -8
- package/dist/{model-input-MAq2881y.js → model-input-CMLh4Cwq.js} +3 -3
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +3 -3
- package/dist/{oauth-callback-server-DIF6Li06.js → oauth-callback-server-RVcbiDjL.js} +2 -2
- package/dist/{oauth-relay-DPE-wrwO.js → oauth-relay-Bu9kkaQu.js} +1 -1
- package/dist/{projection-jZSlEAXG.js → projection-Cns7XwWa.js} +9445 -5574
- package/dist/{prompt-CaMyeCpA.js → prompt-CDqcsDYC.js} +4 -4
- package/dist/{registry-BBkWFCl8.js → registry-BPwuOP2O.js} +5 -8
- package/dist/{resolve-B38MkHXE.js → resolve-BK29bBry.js} +3 -3
- package/dist/rule-DAxQY-1h.js +20 -0
- package/dist/{runner-11h8PrHh.js → runner-BcAE-cJm.js} +10 -10
- package/dist/{sandbox-egress-signals-CTcACAtJ.js → sandbox-egress-signals-C-q0go5b.js} +1 -1
- package/dist/{schedule-DWxZ3kja.js → schedule-BLJ476XQ.js} +209 -43
- package/dist/{schema-obw5jvR4.js → schema-BLgSZXcL.js} +255 -49
- package/dist/{schema-DriSvB40.d.ts → schema-DYcJeV7d.d.ts} +701 -62
- package/dist/{service-account-Zc5bUcIJ.js → service-account-gN0zqf0S.js} +68 -68
- package/dist/{service-account-Bx93N1n1.js → service-account-iJoCtkHR.js} +3 -3
- package/dist/{skills-C8Npu5zO.js → skills-BoZ80epJ.js} +2 -2
- package/dist/{slack-conversation-unfurl-DlRVA02H.js → slack-conversation-unfurl-CogYrITA.js} +8 -10
- package/dist/{spawn-CXr58R0x.js → spawn-Dk92r7mX.js} +5 -6
- package/dist/{state-CGrGVeQC.js → state-DH3Cmgp3.js} +4 -4
- package/dist/{stop-DYzjRf2U.js → stop-CYsfc0Ed.js} +1063 -313
- package/dist/{store-D4FQ1Nml.js → store-DmmMIrQi.js} +5 -5
- package/dist/{task-queue-CaZffYaH.js → task-queue-C_zldF5J.js} +3 -3
- package/dist/{task-runner-Dm7BHbGp.js → task-runner-C7oCJQIx.js} +20 -13
- package/dist/{thread-context-Dyj1KWaY.js → thread-context-BW2BsQbH.js} +13 -11
- package/dist/{turn-session-routing-CD0BRCex.js → turn-session-routing-Xh_2nSQe.js} +52 -54
- package/dist/{validation-DxVNIxA0.js → validation-DrJd0nnq.js} +1 -1
- package/dist/{version-Cr7Z71yG.js → version-CNKZ8owc.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{warmup-C6LOZ2d2.js → warmup-BWdHew2H.js} +14287 -7195
- package/dist/{web-message-id-BT8Mg8LL.js → web-message-id-Ch5dPq-a.js} +32 -144
- package/dist/{worker-CUBtu1Li.js → worker-t9qpu_Zx.js} +7 -8
- package/migrations/0126_artifact_drop_public.sql +8 -0
- package/migrations/0127_artifact_path.sql +4 -0
- package/migrations/0128_artifact_path_index.sql +1 -0
- package/migrations/0129_review_item_answered_index.sql +1 -0
- package/migrations/0130_review_item_status_index.sql +1 -0
- package/migrations/0131_brief_outcome_status.sql +1 -0
- package/migrations/0132_brief_outcome_status_backfill.sql +7 -0
- package/migrations/0133_brief_created_at_index.sql +1 -0
- package/migrations/0134_slack_person_search_index.sql +1 -0
- package/migrations/0135_code_change_size.sql +3 -0
- package/migrations/0136_merge_conflict_notice_dismiss.sql +16 -0
- package/migrations/0137_inbox_snoozes.sql +27 -0
- package/migrations/0138_code_change_search_index.sql +2 -0
- package/migrations/0139_review_item_owner.sql +22 -0
- package/migrations/0140_review_item_owner_index.sql +1 -0
- package/migrations/0141_memory_core_adoption.sql +89 -0
- package/migrations/0142_memory_core_indexes.sql +17 -0
- package/migrations/meta/0126_snapshot.json +5488 -0
- package/migrations/meta/0127_snapshot.json +5519 -0
- package/migrations/meta/0128_snapshot.json +5519 -0
- package/migrations/meta/0129_snapshot.json +5547 -0
- package/migrations/meta/0130_snapshot.json +5563 -0
- package/migrations/meta/0131_snapshot.json +5569 -0
- package/migrations/meta/0132_snapshot.json +5569 -0
- package/migrations/meta/0133_snapshot.json +5590 -0
- package/migrations/meta/0134_snapshot.json +5606 -0
- package/migrations/meta/0135_snapshot.json +5624 -0
- package/migrations/meta/0136_snapshot.json +5624 -0
- package/migrations/meta/0137_snapshot.json +5864 -0
- package/migrations/meta/0138_snapshot.json +5894 -0
- package/migrations/meta/0139_snapshot.json +5898 -0
- package/migrations/meta/0140_snapshot.json +5919 -0
- package/migrations/meta/0141_snapshot.json +6429 -0
- package/migrations/meta/0142_snapshot.json +6457 -0
- package/migrations/meta/_journal.json +120 -1
- package/package.json +6 -7
- package/dist/result-BaqSZcJb.js +0 -548
- package/dist/session-stop-BfY4rhJs.js +0 -4255
- package/dist/turn-user-message-9IxeEv5v.js +0 -364
- package/dist/users-CaUAYMb3.js +0 -181
- package/dist/viewer-AHldghAD.js +0 -212
|
@@ -1,44 +1,42 @@
|
|
|
1
|
-
import { $ as loadTurnCheckpoint, $
|
|
2
|
-
import { F as textCharsForTokens,
|
|
1
|
+
import { $ as loadTurnCheckpoint, $s as automationVersionOf, A as latestConversationMessageSeq, Ac as listReplyActionItems, Ao as markDispatchCompleted, As as getDashboardLinkFilter, Ba as getSlackFileId, Bc as listFiringInboxSnoozeTriggers, Bi as resolveBaseUrl, Br as createCodeChangePublisher, Bs as blockEventAutomation, Cn as createUserTokenStore, Co as getDispatchRecord, D as estimateConversationMessagesTokens, Da as createPluginLogger, Dn as applyPluginFormatMarkdown, E as buildConversationContext, Ec as dismissOpenReviewItems, Eo as isTerminalDispatchStatus, F as turnHasReply, Fc as takeReviewItem, Ga as slackAttachmentsVersionQuery, H as PluginCredentialFailureError, Ha as readAttachmentVisionSummary, Ht as releaseInboundMessage, I as upsertConversationMessage, In as getPlugins, Is as isDashboardLink, Jo as SlackActionError, Jr as cancelSubscriptions, K as AuthorizationFlowDisabledError, Lc as waitingConversationIdsQuery, Ls as parseDashboardConversationLink, M as normalizeConversationText, Ma as readConversationEventPage, Mc as ownerConversationId, Mo as markDispatchRunning, Ms as getDashboardPersonLink, N as recordDeliveredAssistantMessage, Na as readConversationEventPageAfter, No as notifyAutomationBlocked, O as getConversationMessageSlackTs, Oc as getReviewItem, On as createPluginEventPublisher, Oo as markDispatchAwaitingResume, Or as trimTrailingAssistantMessages, P as trimConversationMessages, Pa as readConversationEventPageAround, Po as addReactionToMessage, Qc as slackChannelMessageRunsAutomation, Qo as getSlackClient, Rc as SNOOZE_TIMER_EVENT_TYPE, Rr as PLUGIN_CHOICE_FIELD_ID, Rs as parseDashboardPersonLink, S as persistConversationMessages, Sl as configValueSchema, So as getDispatchInputMessageId, To as getPluginDispatchProjection, Uc as settleInboxSnoozes, Ur as createPluginConversationWatches, V as createPluginEgress, Vo as removeReactionFromMessage, Vs as collectEventAutomationMatchKeys, Wa as recordSlackAttachment, Ws as findMatchingEventAutomations, X as clearPendingAuth, Xr as collectEventMatchKeys, Xs as admitEventAutomationRun, Yo as downloadPrivateSlackFile, Za as storeAttachment, Zc as slackChannelMessageReplyThreadTs, Zo as getHeaderString, Zs as eventAutomationRunLimitReason, _ as recordSubscribedReplyRoute, _o as claimDispatchMailboxAppend, _s as wrapBareSlackUserIds, as as withSlackRetries, at as failTurnRecord, b as hydrateConversationMessages, bl as createPluginCache, bo as getDispatchConversationId, ci as bindScheduledAutomationCredentialSubject, co as listConversationAnnotations, ct as listTurnSummaries, da as createPluginEmbedder, di as verifyScheduledAutomationCredentialSubject, dn as getAssistantReplyText, ei as findMatchingWatches, es as isDmChannel, et as lostWorkerBeforeFirstSave, f as recordAuthorizationCompleted, fi as verifySlackDirectCredentialSubject, fr as storedMessageJson, gc as recordAutomationExecution, go as buildDispatchId, gs as slackMentionedUserIds, hc as readAutomationTitlesByConversationId, hi as createPluginState, hs as slackMention, i as loadConversationProjection, il as CORE_EVENT_NAMESPACE, is as streamPrivateSlackFile, it as completeTurnRecord, j as markConversationMessage, ja as readLatestConversationBrief, jo as markDispatchFailed, k as isHumanConversationMessage, ko as markDispatchBlocked, ks as getDashboardConversationLink, li as bindSlackDirectCredentialSubject, lo as listConversationAnnotationsById, ls as SLACK_USER_MENTION_RE, lt as recordTurnSummary, mi as updateTimerIndex, mo as lookupSlackUserNames, ms as normalizeSlackStatusText, n as commitMessages, nn as buildTurnErrorResponse, ns as normalizeSlackConversationId, nt as saveTurnCheckpoint, o as loadProjection, pa as basePluginContext, po as lookupSlackUser, qa as isFileAttachment, qc as getEventCatalog, ri as listConversationsWithWatches, rt as abandonTurnRecord, s as loadTurnProjection, sc as existingConversationId, si as bindEventAutomationCredentialSubject, sl as eventGuidance, so as createPluginAnnotations, st as getTurnRecord, t as commitAcceptedReply, ts as isSlackRequestTimeout, tt as pauseLostWorkerTurn, ui as verifyEventAutomationCredentialSubject, vc as AUTOMATION_ALERT_STEPS, vo as confirmDispatchMailboxAppend, vs as truncateStatusText, w as resolveConversationTitle, wc as closeReviewItem, wl as piMessageFromHistoryItem, wo as getDispatchTurnId, x as persistConversationMessageWindow, xc as fallbackShortTitle, xn as persistWithRetry, xo as getDispatchIdForConversation, yc as AUTOMATION_ALERT_STEP_FIELD_ID, yo as createOrGetDispatch, za as notInheritedByForkChild, zr as createPluginReviewItems } from "./projection-Cns7XwWa.js";
|
|
2
|
+
import { F as createCache, G as textCharsForTokens, R as acquireActiveLock, W as estimateTextTokens, c as getSlackClientSecret, i as getChatConfig, k as resolveGatewayModel, l as getSlackSigningSecret, n as botConfig, o as getSlackBotToken, pt as isProviderRetryError, s as getSlackClientId, y as normalizeSlackEmojiName } from "./config-BrXDQefC.js";
|
|
3
3
|
import { t as mapBounded } from "./fan-out-Cod-yEHG.js";
|
|
4
|
-
import { E as withSpan,
|
|
5
|
-
import { h as startSpan } from "./sentry-CPbZjomA.js";
|
|
6
|
-
import { t as JUNIOR_VERSION } from "./version-
|
|
4
|
+
import { E as withSpan, H as buildSentryConversationUrl, J as normalizeIdentityEmail, S as setTags, T as withLogContext, Y as toOptionalString, b as setSpanAttributes, f as logError, h as logWarn, m as logInfo, n as createChatSdkLogger, o as getActiveTraceContext, p as logException, s as getActiveTraceId, t as buildTurnFailureResponse, y as setSentryUser } from "./logging-FjclQsXu.js";
|
|
5
|
+
import { h as startSpan, n as captureMessage } from "./sentry-CPbZjomA.js";
|
|
6
|
+
import { t as JUNIOR_VERSION } from "./version-CNKZ8owc.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 {
|
|
9
|
-
import {
|
|
8
|
+
import { $ as conversationKindFromRow, B as parseSessionSource, Cn as viewerMarksFromParticipant, Dn as agentTurnUsageSchema, F as locationFromRow, Ht as hasUserPhoto, In as requireSlackDestination, J as conversationIsActiveSql, Jt as userAvatarUrlsFromJoinedPhotos, Mn as nextDetailVersion, On as hasAgentTurnUsage, P as turnBehavior, Pn as createSlackDestination, Q as executionIsActive, Sn as rootVisibleToViewer, St as reviewItemPlugin, T as deliversFinalText, Ut as identityAvatarUrl, V as conversationCostOf, Xt as resolveActorIdentityId, Y as conversationStatusSql, Z as conversationWaitsOnUserSql, Zt as saveActorAvatar, _ as readConversationTrees, a as getConversationStore, b as loadConversationSlackTenantIds, bn as conversationPinnedForUser, cn as readCachedUserByEmail, ct as isAutomationAlertItem, et as awaitsAuthorizationFrom, f as copyMessageLinks, fn as canAddConversationMessages, gn as readConversationAccessRows, gt as reviewItemForUser, h as conversationAncestors, hn as readConversationAccessFromSql, it as canActOnReviewItem, j as postsRunNotices, k as isTopLevelKind, kn as resolveRootConversationId, lt as isOnlyAssignee, m as withConversationEventLock, mn as createConversationAccessReader, o as getDb, pn as conversationAccessFromRows, qt as userAvatarUrlsFromIdentities, r as getConversationEventStore, rt as PLUGIN_REVIEW_ITEM_KEY_PREFIX, s as getSqlExecutor, st as canUserReadReviewItem, tt as treeAwaitsAuthorization, ut as isPluginReviewItem, v as setArchivedAt, vn as conversationIsMemberRoot, vt as reviewItemNeedsInput, wn as addAgentTurnUsage, x as lastMessageAtSql, xn as readMemberParticipants, xt as reviewItemOwnedByConversation, y as conversationSlackTenantId, yn as conversationIsNotUnsubscribedRoot, yt as reviewItemNeedsSomeone } from "./db-DTxzH7u5.js";
|
|
9
|
+
import { B as juniorAttachments, C as juniorConversationParticipants, H as juniorConversations, K as juniorUsers, L as juniorCodeChanges, M as juniorConversationEvents, O as juniorConversationBriefs, P as juniorConversationAnnotations, U as juniorIdentities, V as juniorMessageAttachments, _ as juniorAutomationRuns, c as juniorPlanItems, g as juniorAutomations, h as juniorReviewItems, n as isPostgresErrorCode, p as juniorReviewItemConversations, q as juniorDestinations, x as juniorAgentInvocations } from "./executor-DqTiYj9S.js";
|
|
10
10
|
import { d as contextProvenance, p as instructionProvenanceFor, t as KNOWN_CONVERSATION_EVENT_TYPES } from "./history-CYstOMKX.js";
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
21
|
-
import { An as
|
|
22
|
-
import {
|
|
23
|
-
import {
|
|
24
|
-
import {
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
27
|
-
import { t as
|
|
28
|
-
import {
|
|
29
|
-
import {
|
|
30
|
-
import {
|
|
31
|
-
import {
|
|
32
|
-
import { t as
|
|
33
|
-
import { t as
|
|
34
|
-
import {
|
|
35
|
-
import {
|
|
36
|
-
import { n as scheduleSessionCompletedPluginTasks } from "./task-runner-Dm7BHbGp.js";
|
|
37
|
-
import { r as canContinueInSlack } from "./continue-in-slack-BWVwePKD.js";
|
|
11
|
+
import { a as getStateValues, i as getStateAdapter, o as setStateValues } from "./adapter-B1wujchl.js";
|
|
12
|
+
import { f as actorLogContext, p as credentialContextForActor } from "./registry-BPwuOP2O.js";
|
|
13
|
+
import { n as pluginCatalogRuntime } from "./catalog-runtime-DMY3VV-D.js";
|
|
14
|
+
import { C as safeLinkUrl, F as finalizeFailedTurnReplyWithEvent, I as getAgentTurnDiagnosticsAttributes, L as requireTurnFailureEventId, M as RetryableDeliveryError, R as shouldEmitDevAgentTrace, T as canPauseConversationDelivery, a as getMcpOAuthCallbackPath, c as latestProgressStatus, f as resolveDestinationVisibility, h as createSlackReviewItemShow, n as executeAgentRun, o as createClientMetadata, r as buildAuthPauseResponse, s as readMcpClientInformation, t as createAgentRunner } from "./agent-runner-BVHPUIc8.js";
|
|
15
|
+
import { d as PluginMcpClient, u as McpAuthorizationRequiredError, v as getMcpStoredOAuthCredentials } from "./service-account-gN0zqf0S.js";
|
|
16
|
+
import { i as webActorUserIds } from "./state-DH3Cmgp3.js";
|
|
17
|
+
import { _ as JUNIOR_NATIVE_EVENT_NAMESPACE, a as EVENT_SYSTEM_ACTOR, d as completeText, l as completeDecision, s as isEventConversationMessage } from "./prompt-CDqcsDYC.js";
|
|
18
|
+
import { Z as answeredChoices, et as isEmptyUserInputAnswer, st as automationTaskText, tt as normalizeUserInputAnswer } from "./schedule-BLJ476XQ.js";
|
|
19
|
+
import { $ as MAX_ATTACHMENT_BYTES, D as activityPreviewText, rt as readMessageAttachments } from "./conversation-ca__NDQW.js";
|
|
20
|
+
import { d as readJuniorSecret, g as getTurnRequestDeadline, s as sendVercelPluginTask } from "./task-queue-C_zldF5J.js";
|
|
21
|
+
import { $r as instructionActorFor, An as withAgentInvocationResultActors, Ar as markTurnClosed, Ba as takeViewerAutomationAlertStep, Bn as cancelSignInWait, Bt as AttachmentUploadError, C as historyPeriodSavings, Ci as throwApiError, Cr as CooperativeTurnYieldError, Ct as conversationReadPositionQuery, Di as parseSlackMessageReference, Dn as enqueueAgentInvocationResult, Dr as isCooperativeTurnYieldError, Ei as renderBlockText, Er as getConversationTurnBoundaryError, Fr as executeTurn, Ft as createAndEnqueueConversation, Gi as getConversationInfo, Gn as getTurnUserSlackMessageTs, Ha as ViewerTaskNotFoundError, Hn as getTurnUserMessage, Ii as parseSlackThreadId, It as createConversationId, Jr as loadReviewItemInput, Ki as isConversationMember, Kr as skipInputAfterConversationStop, Li as readSlackRawMessageContext, Ln as dropOwnUnreadLoopReplies, Lr as getTurnLifecycle, Lt as recordWebConversationActivity, Mr as markTurnFailed, Mt as acceptsWebMessages, Nr as startActiveTurn, Nt as appendAndEnqueueWebMessage, O as connectedState, Or as isTurnInputCommitLostError, Pr as AgentRunError, Qr as buildSteeringPiMessage, Qt as resolveMailboxTurnWork, Ri as resolveSlackChannelIdFromMessage, Rn as stopChildAgentsBelow, Rt as webActorFromUser, S as firstLiveSavingsDate, Sr as ConversationTurnBoundaryError, Ti as renderAttachmentText, Tn as createDeliverToParent, Tr as TurnInputDeferredError, Ua as readConversationSourceTask, Ut as verifyAttachmentUploads, Wi as getChannelMessage, Wn as getTurnUserReplyAttachmentContext, Wr as markConversationsStopped, Xn as getChildAgentLabel, Yi as listThreadReplies, Yr as savedInputInstruction, _i as conversationSubtreeColumns, _n as maybePostAutomatedTurnLimitNotice, ai as renderTaskInput, ao as effectiveTaskOutcomes, b as addHistoryPeriod, bn as sendSlackReply, c as isConversationWorkDone, cr as supersedeTurnForInput, dr as recordFailedDispatchTurn, fn as resolveEventAuthor, fo as NO_REPLY_GAP_MS, gi as conversationSubtree, gn as resolveBotSlackTeamId, gr as canShareTurn, hi as buildDeterministicTurnId, hr as canJoinTurn, i as GLOBAL_GAPS_TTL_MS, io as missingAutomationSkillReason, jr as markTurnCompleted, k as providerCacheTtlMs, kr as isTurnInputDeferredError, kt as deliverReviewItemChange, l as listConversationWork, lr as createPausedTurns, mi as buildDeterministicAssistantMessageId, mr as getTurnAuthorization, n as CONVERSATION_STATE_TTL_MS, o as segmentGapsKey, oa as isExperimentalFeatureEnabled, pi as recordFinishedTurnForAutomatedLimit, po as gapSegment, qi as isPublicSlackChannel, r as GLOBAL_GAPS_MAX, ri as withoutSavedSteeringMessages, ro as findAutomationSkill, sn as eventAuthorText, t as ANSWER_TOOL_ENDINGS, tn as legacyWebMailboxMetadataSchema, to as AutomationEditError, uo as MINUTE_MS, ur as getPausedTurnRequest, w as replaceHistorySavings, wn as createChildConversationWorker, wr as TurnInputCommitLostError, x as addHistoryWarmupCost, xr as getWebAuthorization, xt as readLastUserMessageAtByConversation, yn as resolveSlackReplyTarget, z as ingestEvent, zn as stopChildAgentsOf } from "./warmup-BWdHew2H.js";
|
|
22
|
+
import { m as isVisionImageMediaType, p as detectImageMediaType, t as webMessageId, v as PLAN_ITEM_STATUSES, x as isOpenPlanItemStatus } from "./web-message-id-Ch5dPq-a.js";
|
|
23
|
+
import { m as getVercelConversationWorkQueue } from "./background-compaction-queue-CJDnWVOJ.js";
|
|
24
|
+
import { D as stopConversationWork, E as steerWebPendingMessages, _ as getConversationWorkState, a as cancelHumanFacingPendingMessages, g as getConversation, h as ensureConversationWake, r as appendAndEnqueueInboundMessage, s as claimInboundMessage } from "./store-DmmMIrQi.js";
|
|
25
|
+
import { a as getPersistedThreadState, c as coerceThreadConversationState, i as getPersistedSandboxState, n as resolveTurnResumeRouting, o as persistThreadRuntimeState, r as getLocationConfigurationService, s as persistThreadStateById, t as resolveConversationRouting } from "./turn-session-routing-Xh_2nSQe.js";
|
|
26
|
+
import { t as runWithSlackInstallation } from "./adapter-context-G2M0y6rP.js";
|
|
27
|
+
import { D as personObjectCard, E as messageObjectCard, O as webPageObjectCard, T as conversationObjectCard, m as healthReportSchema, t as conversationFeedBriefSchema } from "./conversation-feed-DkinDu5o.js";
|
|
28
|
+
import { a as withTurnSpan, i as turnInputTelemetry, n as createConversationTurnWorker, r as getTurnInputSpanAttributes } from "./conversation-turn-DWw7Xhdr.js";
|
|
29
|
+
import { n as attachmentFactLines, r as buildStoredAttachmentPromptText } from "./model-input-CMLh4Cwq.js";
|
|
30
|
+
import { t as bindMessageAgent } from "./message-CJ7_RL50.js";
|
|
31
|
+
import { t as readConversationLineage } from "./lineage-BHAMpNKr.js";
|
|
32
|
+
import { t as bindSpawnAgent } from "./spawn-Dk92r7mX.js";
|
|
33
|
+
import { a as buildDeliveredTurnStatePatch, i as persistAuthPauseTurnState, n as loadThreadContextTrimFloor, o as loadPendingMessageCards, r as completeAuthPauseTurn, t as buildTurnThreadContext } from "./thread-context-BW2BsQbH.js";
|
|
34
|
+
import { n as scheduleSessionCompletedPluginTasks } from "./task-runner-C7oCJQIx.js";
|
|
35
|
+
import { r as canContinueInSlack } from "./continue-in-slack-DNXSC9So.js";
|
|
38
36
|
import * as z from "zod";
|
|
39
37
|
import pLimit from "p-limit";
|
|
40
38
|
import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
|
|
41
|
-
import { conversationSidebarAnnotationSchema, createSlackSource, encodeObjectImageRef, escapeTagText, escapeTagTextAndQuotes, objectAnnotationSchema, objectLinkFilterMatches, objectLinkFilterSpecificity, objectTypeSchema, ownedObjectAnnotationSchema, renderEmptyTag, renderTag } from "@sentry/junior-plugin-api";
|
|
39
|
+
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";
|
|
42
40
|
import { and, asc, count, desc, eq, gt, gte, inArray, isNotNull, isNull, lt, lte, min, ne, not, or, sql } from "drizzle-orm";
|
|
43
41
|
import { alias } from "drizzle-orm/pg-core";
|
|
44
42
|
import { Message, ThreadImpl, stringifyMarkdown } from "chat";
|
|
@@ -202,12 +200,20 @@ async function readFirstHumanMessageTexts(db, conversations) {
|
|
|
202
200
|
return new Map(rows.map((row) => [row.conversationId, row.text]));
|
|
203
201
|
}
|
|
204
202
|
// src/api/conversations/participants.ts
|
|
203
|
+
const userPhotos$1 = alias(juniorIdentities, "user_photos");
|
|
204
|
+
const userPhotoJoin = and(eq(userPhotos$1.userId, juniorIdentities.userId), hasUserPhoto(userPhotos$1));
|
|
205
205
|
const identityColumns = {
|
|
206
206
|
avatarUrl: juniorIdentities.avatarUrl,
|
|
207
207
|
displayName: juniorIdentities.displayName,
|
|
208
208
|
email: juniorIdentities.email,
|
|
209
209
|
handle: juniorIdentities.handle,
|
|
210
210
|
identityId: juniorIdentities.id,
|
|
211
|
+
photo: {
|
|
212
|
+
avatarUrl: userPhotos$1.avatarUrl,
|
|
213
|
+
identityId: userPhotos$1.id,
|
|
214
|
+
provider: userPhotos$1.provider,
|
|
215
|
+
updatedAt: userPhotos$1.updatedAt
|
|
216
|
+
},
|
|
211
217
|
provider: juniorIdentities.provider,
|
|
212
218
|
providerSubjectId: juniorIdentities.providerSubjectId,
|
|
213
219
|
userDisplayName: juniorUsers.displayName,
|
|
@@ -240,15 +246,15 @@ async function readParticipantRows(db, conversationIds) {
|
|
|
240
246
|
const [rootRows, eventRows] = await Promise.all([db.select({
|
|
241
247
|
conversationId: juniorConversations.conversationId,
|
|
242
248
|
...identityColumns
|
|
243
|
-
}).from(juniorConversations).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(inArray(juniorConversations.conversationId, [...conversationIds])), db.select({
|
|
249
|
+
}).from(juniorConversations).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).leftJoin(userPhotos$1, userPhotoJoin).where(inArray(juniorConversations.conversationId, [...conversationIds])), db.select({
|
|
244
250
|
conversationId: authors.conversationId,
|
|
245
251
|
seq: authors.seq,
|
|
246
252
|
...identityColumns
|
|
247
|
-
}).from(authors).innerJoin(juniorIdentities, eq(juniorIdentities.id, authors.actorIdentityId)).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).innerJoin(juniorConversations, eq(juniorConversations.conversationId, authors.conversationId)).innerJoin(juniorConversationParticipants, and(eq(juniorConversationParticipants.userId, juniorIdentities.userId), eq(juniorConversationParticipants.rootConversationId, sql`coalesce(${juniorConversations.rootConversationId}, ${juniorConversations.conversationId})`))).where(inArray(juniorConversations.conversationId, [...conversationIds]))]);
|
|
253
|
+
}).from(authors).innerJoin(juniorIdentities, eq(juniorIdentities.id, authors.actorIdentityId)).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).leftJoin(userPhotos$1, userPhotoJoin).innerJoin(juniorConversations, eq(juniorConversations.conversationId, authors.conversationId)).innerJoin(juniorConversationParticipants, and(eq(juniorConversationParticipants.userId, juniorIdentities.userId), eq(juniorConversationParticipants.rootConversationId, sql`coalesce(${juniorConversations.rootConversationId}, ${juniorConversations.conversationId})`))).where(inArray(juniorConversations.conversationId, [...conversationIds]))]);
|
|
248
254
|
return [...rootRows, ...eventRows.sort((left, right) => left.seq - right.seq)];
|
|
249
255
|
}
|
|
250
|
-
|
|
251
|
-
const userAvatarUrls =
|
|
256
|
+
function groupParticipants(rows) {
|
|
257
|
+
const userAvatarUrls = userAvatarUrlsFromJoinedPhotos(rows);
|
|
252
258
|
const groups = /* @__PURE__ */ new Map();
|
|
253
259
|
for (const row of rows) {
|
|
254
260
|
const participant = participantIdentity(row, userAvatarUrls);
|
|
@@ -263,7 +269,7 @@ async function groupParticipants(db, rows) {
|
|
|
263
269
|
/** Read actor identities in first-appearance order for each Conversation. */
|
|
264
270
|
async function readConversationParticipants(db, conversationIds) {
|
|
265
271
|
if (conversationIds.length === 0) return /* @__PURE__ */ new Map();
|
|
266
|
-
const groups =
|
|
272
|
+
const groups = groupParticipants(await readParticipantRows(db, conversationIds));
|
|
267
273
|
return new Map([...groups].map(([conversationId, group]) => [conversationId, [...group.values()]]));
|
|
268
274
|
}
|
|
269
275
|
/**
|
|
@@ -274,10 +280,11 @@ async function readConversationParticipants(db, conversationIds) {
|
|
|
274
280
|
async function readConversationAuthors(db, conversationId) {
|
|
275
281
|
const rows = await readParticipantRows(db, [conversationId]);
|
|
276
282
|
const userIds = [...new Set(rows.flatMap((row) => row.userId ? [row.userId] : []))];
|
|
277
|
-
const
|
|
283
|
+
const groups = groupParticipants(rows);
|
|
284
|
+
const userIdentities = userIds.length > 0 ? await db.select({
|
|
278
285
|
identityId: juniorIdentities.id,
|
|
279
286
|
userId: juniorIdentities.userId
|
|
280
|
-
}).from(juniorIdentities).where(inArray(juniorIdentities.userId, userIds)) : []
|
|
287
|
+
}).from(juniorIdentities).where(inArray(juniorIdentities.userId, userIds)) : [];
|
|
281
288
|
const group = groups.get(conversationId) ?? /* @__PURE__ */ new Map();
|
|
282
289
|
const authors = {};
|
|
283
290
|
for (const row of [...rows, ...userIdentities]) {
|
|
@@ -469,17 +476,6 @@ function actorIdentityReport(actor) {
|
|
|
469
476
|
};
|
|
470
477
|
return Object.keys(identity).length > 0 ? identity : void 0;
|
|
471
478
|
}
|
|
472
|
-
/**
|
|
473
|
-
* A stopped Conversation shows as `stopped` while no work runs. A Turn that
|
|
474
|
-
* runs before the stop ends, such as one that its parent's new work starts,
|
|
475
|
-
* shows as `active`.
|
|
476
|
-
*/
|
|
477
|
-
function statusFromConversation(conversation) {
|
|
478
|
-
const status = conversation.execution.status;
|
|
479
|
-
if (status !== "idle" && status !== "failed") return "active";
|
|
480
|
-
if (conversation.stoppedAtMs !== void 0) return "stopped";
|
|
481
|
-
return status === "idle" ? "completed" : "failed";
|
|
482
|
-
}
|
|
483
479
|
function titleFromConversation(args) {
|
|
484
480
|
const slackThread = parseSlackThreadId(args.conversation.conversationId);
|
|
485
481
|
const effectiveChannelName = args.conversation.channelName;
|
|
@@ -538,7 +534,7 @@ function conversationSummaryFromStoredConversation(args) {
|
|
|
538
534
|
const slackThread = parseSlackThreadId(conversation.conversationId);
|
|
539
535
|
const channelName = channelNameFromConversation(conversation, canViewPrivateContent, visibility);
|
|
540
536
|
const channelNameRedacted = channelNameRedactedFromConversation(conversation, canViewPrivateContent);
|
|
541
|
-
const status =
|
|
537
|
+
const { status } = args;
|
|
542
538
|
return {
|
|
543
539
|
conversationId: conversation.conversationId,
|
|
544
540
|
cumulativeDurationMs: durationMs,
|
|
@@ -558,6 +554,7 @@ function conversationSummaryFromStoredConversation(args) {
|
|
|
558
554
|
lastSeenAt: new Date(conversation.lastActivityAtMs).toISOString(),
|
|
559
555
|
startedAt: new Date(conversation.createdAtMs).toISOString(),
|
|
560
556
|
status,
|
|
557
|
+
turnActive: executionIsActive(conversation.execution.status),
|
|
561
558
|
surface,
|
|
562
559
|
...args.auxiliaryCosts ? { auxiliaryCosts: args.auxiliaryCosts } : void 0,
|
|
563
560
|
...usage ? { cumulativeUsage: usage } : void 0,
|
|
@@ -573,6 +570,91 @@ function conversationSummaryFromStoredConversation(args) {
|
|
|
573
570
|
...args.locationId && !channelNameRedacted ? { locationId: args.locationId } : void 0
|
|
574
571
|
};
|
|
575
572
|
}
|
|
573
|
+
// src/api/conversations/record.ts
|
|
574
|
+
/**
|
|
575
|
+
* The columns of one Conversation record, for `selectConversationRecords`.
|
|
576
|
+
* Build them for each query: the status binds the app clock.
|
|
577
|
+
*/
|
|
578
|
+
const conversationRecordColumns = () => ({
|
|
579
|
+
conversation: juniorConversations,
|
|
580
|
+
status: conversationStatusSql(juniorConversations),
|
|
581
|
+
location: juniorDestinations,
|
|
582
|
+
identityDisplayName: juniorIdentities.displayName,
|
|
583
|
+
identityEmail: juniorIdentities.email,
|
|
584
|
+
identityHandle: juniorIdentities.handle,
|
|
585
|
+
identityProvider: juniorIdentities.provider,
|
|
586
|
+
identitySubjectId: juniorIdentities.providerSubjectId,
|
|
587
|
+
identityTenantId: juniorIdentities.providerTenantId,
|
|
588
|
+
userDisplayName: juniorUsers.displayName
|
|
589
|
+
});
|
|
590
|
+
/** Left-join conditions from a Conversation to its record tables. */
|
|
591
|
+
const conversationRecordJoins = {
|
|
592
|
+
location: eq(juniorDestinations.id, juniorConversations.destinationId),
|
|
593
|
+
identity: eq(juniorIdentities.id, juniorConversations.actorIdentityId),
|
|
594
|
+
user: eq(juniorUsers.id, juniorIdentities.userId)
|
|
595
|
+
};
|
|
596
|
+
/**
|
|
597
|
+
* Select Conversation rows with their Location and Actor names. Callers add
|
|
598
|
+
* the filter, order, and limit.
|
|
599
|
+
*/
|
|
600
|
+
function selectConversationRecords(db) {
|
|
601
|
+
return db.select(conversationRecordColumns()).from(juniorConversations).leftJoin(juniorDestinations, conversationRecordJoins.location).leftJoin(juniorIdentities, conversationRecordJoins.identity).leftJoin(juniorUsers, conversationRecordJoins.user);
|
|
602
|
+
}
|
|
603
|
+
/** Decode a conversation row with the linked user name and identity-scoped provider fields. */
|
|
604
|
+
function conversationFromRecordRow(row) {
|
|
605
|
+
const value = row.conversation;
|
|
606
|
+
const legacySessionSource = value.sessionSource === null ? void 0 : parseSessionSource(value.sessionSource);
|
|
607
|
+
if (value.sessionSource !== null && !legacySessionSource) throw new Error("Conversation legacy source_json is invalid");
|
|
608
|
+
const actorFullName = row.userDisplayName?.trim() ? row.userDisplayName : row.identityDisplayName;
|
|
609
|
+
const actor = row.identityProvider === "slack" ? {
|
|
610
|
+
platform: "slack",
|
|
611
|
+
...row.identityEmail ? { email: row.identityEmail } : void 0,
|
|
612
|
+
...actorFullName ? { fullName: actorFullName } : void 0,
|
|
613
|
+
...row.identitySubjectId ? { slackUserId: row.identitySubjectId } : void 0,
|
|
614
|
+
...row.identityHandle ? { slackUserName: row.identityHandle } : void 0,
|
|
615
|
+
...row.identityTenantId ? { teamId: row.identityTenantId } : void 0
|
|
616
|
+
} : void 0;
|
|
617
|
+
const location = locationFromRow(value.location, row.location, legacySessionSource);
|
|
618
|
+
return {
|
|
619
|
+
schemaVersion: 1,
|
|
620
|
+
conversationId: value.conversationId,
|
|
621
|
+
createdAtMs: value.createdAt.getTime(),
|
|
622
|
+
kind: conversationKindFromRow(value),
|
|
623
|
+
lastActivityAtMs: value.lastActivityAt.getTime(),
|
|
624
|
+
updatedAtMs: value.updatedAt.getTime(),
|
|
625
|
+
execution: {
|
|
626
|
+
status: value.executionStatus,
|
|
627
|
+
...value.runId ? { runId: value.runId } : void 0,
|
|
628
|
+
...value.executionUpdatedAt ? { updatedAtMs: value.executionUpdatedAt.getTime() } : void 0
|
|
629
|
+
},
|
|
630
|
+
...value.parentConversationId ? { parentConversationId: value.parentConversationId } : void 0,
|
|
631
|
+
...value.archivedAt ? { archivedAtMs: value.archivedAt.getTime() } : void 0,
|
|
632
|
+
...actor ? { actor } : void 0,
|
|
633
|
+
...location ? { location } : void 0,
|
|
634
|
+
...value.channelName ? { channelName: value.channelName } : void 0,
|
|
635
|
+
...value.source ? { source: value.source } : void 0,
|
|
636
|
+
...value.title ? { title: value.title } : void 0,
|
|
637
|
+
...value.transcriptPurgedAt ? { transcriptPurgedAtMs: value.transcriptPurgedAt.getTime() } : void 0,
|
|
638
|
+
...value.stoppedAt ? { stoppedAtMs: value.stoppedAt.getTime() } : void 0,
|
|
639
|
+
...value.deliveryPausedAt ? { deliveryPausedAtMs: value.deliveryPausedAt.getTime() } : void 0
|
|
640
|
+
};
|
|
641
|
+
}
|
|
642
|
+
/** Decode one `selectConversationRecords` row into a Conversation record. */
|
|
643
|
+
function conversationRecordFromRow(row) {
|
|
644
|
+
return {
|
|
645
|
+
conversation: conversationFromRecordRow(row),
|
|
646
|
+
durationMs: row.conversation.durationMs,
|
|
647
|
+
...row.location?.visibility === "public" ? { locationId: row.location.id } : void 0,
|
|
648
|
+
status: row.status,
|
|
649
|
+
usage: row.conversation.usage,
|
|
650
|
+
rootConversationId: row.conversation.rootConversationId
|
|
651
|
+
};
|
|
652
|
+
}
|
|
653
|
+
/** Read one normalized conversation record directly from its SQL row. */
|
|
654
|
+
async function readConversationRecordFromSql(conversationId) {
|
|
655
|
+
const row = (await selectConversationRecords(getDb()).where(eq(juniorConversations.conversationId, conversationId)).limit(1))[0];
|
|
656
|
+
return row ? conversationRecordFromRow(row) : void 0;
|
|
657
|
+
}
|
|
576
658
|
// src/api/objects/conversation.ts
|
|
577
659
|
async function readViewerAccess(viewer, conversationId) {
|
|
578
660
|
return (await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId);
|
|
@@ -596,8 +678,9 @@ async function resolveConversationLink(viewer, url) {
|
|
|
596
678
|
const conversationId = parseDashboardConversationLink(url.href);
|
|
597
679
|
const canonicalUrl = conversationId ? getDashboardConversationLink(conversationId) : void 0;
|
|
598
680
|
if (!conversationId || !canonicalUrl) return void 0;
|
|
599
|
-
const
|
|
600
|
-
if (!
|
|
681
|
+
const record = await readConversationRecordFromSql(conversationId);
|
|
682
|
+
if (!record) return void 0;
|
|
683
|
+
const { conversation } = record;
|
|
601
684
|
const db = getDb();
|
|
602
685
|
const access = await readViewerAccess(viewer, conversationId);
|
|
603
686
|
if (!access?.canViewPrivateContent) return void 0;
|
|
@@ -615,7 +698,8 @@ async function resolveConversationLink(viewer, url) {
|
|
|
615
698
|
automationTitle: automationTitles.get(conversationId),
|
|
616
699
|
conversation,
|
|
617
700
|
durationMs: 0,
|
|
618
|
-
firstHumanMessageText: firstTexts.get(conversationId)
|
|
701
|
+
firstHumanMessageText: firstTexts.get(conversationId),
|
|
702
|
+
status: record.status
|
|
619
703
|
}),
|
|
620
704
|
url: canonicalUrl
|
|
621
705
|
});
|
|
@@ -1212,7 +1296,7 @@ function renderSlackPlainText(mrkdwn, userNames) {
|
|
|
1212
1296
|
function renderTopLevelText(message) {
|
|
1213
1297
|
const blocks = readRawBlocks(message.raw);
|
|
1214
1298
|
const blockText = renderBlockText(blocks);
|
|
1215
|
-
if (Array.isArray(blocks) && blocks.some((block) =>
|
|
1299
|
+
if (Array.isArray(blocks) && blocks.some((block) => typeof block === "object" && block !== null && "type" in block && block.type === "section") && blockText) return blockText;
|
|
1216
1300
|
const rawText = readRawText(message.raw);
|
|
1217
1301
|
if (rawText.trim()) return renderSlackMrkdwn(rawText);
|
|
1218
1302
|
if (message.formatted.children.length > 0) return stringifyMarkdown(message.formatted).trim();
|
|
@@ -3539,7 +3623,7 @@ function createSlackTurn(deps) {
|
|
|
3539
3623
|
actor: inboundMessageActor(queued),
|
|
3540
3624
|
...reviewItemInput ? { kind: "runtime" } : void 0,
|
|
3541
3625
|
provenance: inboundMessageProvenance(queued, teamId),
|
|
3542
|
-
text: reviewItemInput ?? queued.userText,
|
|
3626
|
+
text: reviewItemInput?.text ?? queued.userText,
|
|
3543
3627
|
timestampMs: queued.message.metadata.dateSent.getTime(),
|
|
3544
3628
|
omittedImageAttachmentCount: !canReadImages() && hasPotentialImageAttachment(attachments) ? countPotentialImageAttachments(attachments) : 0,
|
|
3545
3629
|
attachments: await deps.resolveUserAttachments(attachments, {
|
|
@@ -4305,22 +4389,26 @@ const VISION_CACHE_TTL_MS = 6048e5;
|
|
|
4305
4389
|
function visionCacheKey(conversationId) {
|
|
4306
4390
|
return `vision-cache:v${VISION_CACHE_SCHEMA_VERSION}:${conversationId}`;
|
|
4307
4391
|
}
|
|
4392
|
+
const visionCacheSchema = z.object({
|
|
4393
|
+
schemaVersion: z.literal(VISION_CACHE_SCHEMA_VERSION),
|
|
4394
|
+
backfillCompletedAtMs: z.number().optional().catch(void 0),
|
|
4395
|
+
byFileId: z.record(z.string(), z.unknown()).catch({})
|
|
4396
|
+
});
|
|
4397
|
+
const visionSummarySchema = z.object({
|
|
4398
|
+
summary: z.string().refine((summary) => summary.trim() !== ""),
|
|
4399
|
+
analyzedAtMs: z.number()
|
|
4400
|
+
});
|
|
4308
4401
|
function coerceVisionCache(value) {
|
|
4309
|
-
|
|
4310
|
-
|
|
4402
|
+
const parsed = visionCacheSchema.safeParse(value);
|
|
4403
|
+
if (!parsed.success) return { byFileId: {} };
|
|
4311
4404
|
const byFileId = {};
|
|
4312
|
-
for (const [fileId, rawSummary] of Object.entries(
|
|
4313
|
-
if (!fileId.trim()
|
|
4314
|
-
const summary =
|
|
4315
|
-
|
|
4316
|
-
if (!summary || analyzedAtMs === void 0) continue;
|
|
4317
|
-
byFileId[fileId] = {
|
|
4318
|
-
summary,
|
|
4319
|
-
analyzedAtMs
|
|
4320
|
-
};
|
|
4405
|
+
for (const [fileId, rawSummary] of Object.entries(parsed.data.byFileId)) {
|
|
4406
|
+
if (!fileId.trim()) continue;
|
|
4407
|
+
const summary = visionSummarySchema.safeParse(rawSummary);
|
|
4408
|
+
if (summary.success) byFileId[fileId] = summary.data;
|
|
4321
4409
|
}
|
|
4322
4410
|
return {
|
|
4323
|
-
backfillCompletedAtMs:
|
|
4411
|
+
backfillCompletedAtMs: parsed.data.backfillCompletedAtMs,
|
|
4324
4412
|
byFileId
|
|
4325
4413
|
};
|
|
4326
4414
|
}
|
|
@@ -6311,6 +6399,7 @@ async function runPausedTurnInContext(payload, options, runOptions) {
|
|
|
6311
6399
|
...getTurnUserReplyAttachmentContext(userMessage),
|
|
6312
6400
|
...await savedInputInstruction({
|
|
6313
6401
|
runtime: Boolean(dispatchId) || isEventConversationMessage(userMessage),
|
|
6402
|
+
requestText: userMessage.meta?.requestText,
|
|
6314
6403
|
reviewItemChange: userMessage.meta?.reviewItemChanges?.[0],
|
|
6315
6404
|
text: userMessage.text
|
|
6316
6405
|
})
|
|
@@ -6688,12 +6777,8 @@ function createConversationWork(options) {
|
|
|
6688
6777
|
if (dispatchId) return await dispatchWorker(context, dispatchId);
|
|
6689
6778
|
return await destinationWorker(context);
|
|
6690
6779
|
};
|
|
6691
|
-
const
|
|
6692
|
-
|
|
6693
|
-
if ("skipped" in stopped) return stopped.skipped;
|
|
6694
|
-
const { context } = stopped;
|
|
6695
|
-
const conversation = await options.conversationStore.get({ conversationId: context.conversationId });
|
|
6696
|
-
if (!isTopLevelKind(conversation?.kind ?? "root")) return await childWorker(context);
|
|
6780
|
+
const runByKind = async (context, topLevel) => {
|
|
6781
|
+
if (!topLevel) return await childWorker(context);
|
|
6697
6782
|
const readStopSignal = context.stopSignal;
|
|
6698
6783
|
let stopSignal;
|
|
6699
6784
|
const stopLateChildAgents = async () => {
|
|
@@ -6714,6 +6799,14 @@ function createConversationWork(options) {
|
|
|
6714
6799
|
await stopLateChildAgents();
|
|
6715
6800
|
return result;
|
|
6716
6801
|
};
|
|
6802
|
+
const run = async (attemptContext) => {
|
|
6803
|
+
const stopped = await skipInputAfterConversationStop(attemptContext);
|
|
6804
|
+
if ("skipped" in stopped) return stopped.skipped;
|
|
6805
|
+
const { context } = stopped;
|
|
6806
|
+
const conversation = await options.conversationStore.get({ conversationId: context.conversationId });
|
|
6807
|
+
const topLevel = isTopLevelKind(conversation?.kind ?? "root");
|
|
6808
|
+
return await withLogContext({ rootConversationId: conversation?.rootConversationId ?? (topLevel ? context.conversationId : void 0) }, () => runByKind(context, topLevel));
|
|
6809
|
+
};
|
|
6717
6810
|
return {
|
|
6718
6811
|
beforeWorkStops: failStoppedDispatch,
|
|
6719
6812
|
conversationStore: options.conversationStore,
|
|
@@ -7638,6 +7731,16 @@ async function resolveObjectLinkNow(viewer, url) {
|
|
|
7638
7731
|
return await resolveWithLinkType(linkType, viewer, url) ?? void 0;
|
|
7639
7732
|
}
|
|
7640
7733
|
/**
|
|
7734
|
+
* Return whether a link type of `plugin` claims the URL, lets the viewer
|
|
7735
|
+
* see it now, and reads an object there. A missing or deleted object does
|
|
7736
|
+
* not count. Neither does the web page card: it shows what anyone can read
|
|
7737
|
+
* signed out, not what the viewer can see.
|
|
7738
|
+
*/
|
|
7739
|
+
async function viewerCanViewPluginLink(viewer, url, plugin) {
|
|
7740
|
+
const linkType = findObjectLinkType(readObjectLinkTypes(), url);
|
|
7741
|
+
return linkType?.owner === plugin && await linkType.canView(viewer, url) && Boolean(await linkType.resolve(viewer, url));
|
|
7742
|
+
}
|
|
7743
|
+
/**
|
|
7641
7744
|
* Resolve links to object cards for one viewer. A link without a link type,
|
|
7642
7745
|
* without access, or with a failed read gets no card. Nothing is saved on a
|
|
7643
7746
|
* Conversation.
|
|
@@ -8282,57 +8385,374 @@ async function runSavingsRefillSlice(args) {
|
|
|
8282
8385
|
await state.delete(SLICE_LOCK_KEY);
|
|
8283
8386
|
}
|
|
8284
8387
|
}
|
|
8285
|
-
// src/chat/
|
|
8388
|
+
// src/chat/inbox-snoozes/triggers.ts
|
|
8286
8389
|
/**
|
|
8287
|
-
*
|
|
8288
|
-
*
|
|
8289
|
-
* resume after it.
|
|
8390
|
+
* Pending snooze timers. A snooze wakes in one cheap update, so one claim
|
|
8391
|
+
* takes many.
|
|
8290
8392
|
*/
|
|
8291
|
-
const
|
|
8393
|
+
const INBOX_SNOOZE_TIMER_INDEX = {
|
|
8394
|
+
batchSize: 500,
|
|
8395
|
+
key: "junior:inbox-snoozes:due"
|
|
8396
|
+
};
|
|
8292
8397
|
/**
|
|
8293
|
-
*
|
|
8294
|
-
*
|
|
8295
|
-
*
|
|
8296
|
-
*
|
|
8297
|
-
|
|
8398
|
+
* Fire the snooze triggers that one Event matches. A `resolve` trigger
|
|
8399
|
+
* dismisses the item and cancels its snooze; a `wake` trigger ends the
|
|
8400
|
+
* snooze. When one Event fires both on a snooze, `resolve` wins. A snooze
|
|
8401
|
+
* that already ended ignores the Event. Returns the number of items woken.
|
|
8402
|
+
*/
|
|
8403
|
+
async function fireTriggers(db, event, nowMs) {
|
|
8404
|
+
const triggers = (await listFiringInboxSnoozeTriggers(db, {
|
|
8405
|
+
eventTypes: [event.eventType],
|
|
8406
|
+
identifiers: event.identifiers,
|
|
8407
|
+
namespace: event.namespace
|
|
8408
|
+
})).filter((trigger) => eventMatches(trigger.match ?? void 0, event.data));
|
|
8409
|
+
const resolving = new Set(triggers.filter((trigger) => trigger.outcome === "resolve").map((trigger) => trigger.snoozeId));
|
|
8410
|
+
const waking = new Set(triggers.filter((trigger) => !resolving.has(trigger.snoozeId)).map((trigger) => trigger.snoozeId));
|
|
8411
|
+
if (resolving.size === 0 && waking.size === 0) return 0;
|
|
8412
|
+
return db.transaction(async (tx) => {
|
|
8413
|
+
const resolvedItemIds = await settleInboxSnoozes(tx, {
|
|
8414
|
+
snoozeIds: [...resolving],
|
|
8415
|
+
state: "cancelled"
|
|
8416
|
+
});
|
|
8417
|
+
await dismissOpenReviewItems(tx, {
|
|
8418
|
+
ids: resolvedItemIds,
|
|
8419
|
+
nowMs,
|
|
8420
|
+
reason: "A snooze trigger resolved it."
|
|
8421
|
+
});
|
|
8422
|
+
return (await settleInboxSnoozes(tx, {
|
|
8423
|
+
snoozeIds: [...waking],
|
|
8424
|
+
state: "woken"
|
|
8425
|
+
})).length;
|
|
8426
|
+
});
|
|
8427
|
+
}
|
|
8428
|
+
/** Fire the snooze triggers that one published Event matches. */
|
|
8429
|
+
async function fireInboxSnoozeTriggers(db, event, nowMs = Date.now()) {
|
|
8430
|
+
await fireTriggers(db, {
|
|
8431
|
+
data: event.data,
|
|
8432
|
+
eventType: event.eventType,
|
|
8433
|
+
identifiers: [event.identifier],
|
|
8434
|
+
namespace: event.namespace
|
|
8435
|
+
}, nowMs);
|
|
8436
|
+
}
|
|
8437
|
+
/**
|
|
8438
|
+
* Return whether any of these Events fires a snooze trigger. A plugin
|
|
8439
|
+
* batch has one namespace, so this is one read.
|
|
8440
|
+
*/
|
|
8441
|
+
async function hasInboxSnoozeMatch(db, events) {
|
|
8442
|
+
const namespaces = [...new Set(events.map((event) => event.namespace))];
|
|
8443
|
+
return (await mapBounded(namespaces, async (namespace) => {
|
|
8444
|
+
const group = events.filter((event) => event.namespace === namespace);
|
|
8445
|
+
const triggers = await listFiringInboxSnoozeTriggers(db, {
|
|
8446
|
+
eventTypes: [...new Set(group.map((event) => event.eventType))],
|
|
8447
|
+
identifiers: [...new Set(group.map((event) => event.identifier))],
|
|
8448
|
+
namespace
|
|
8449
|
+
});
|
|
8450
|
+
return group.some((event) => triggers.some((trigger) => trigger.eventType === event.eventType && trigger.identifier === event.identifier && eventMatches(trigger.match ?? void 0, event.data)));
|
|
8451
|
+
})).some(Boolean);
|
|
8452
|
+
}
|
|
8453
|
+
/** Return the Event data keys that snooze triggers on these resources match. */
|
|
8454
|
+
async function collectInboxSnoozeMatchKeys(db, input) {
|
|
8455
|
+
const triggers = await listFiringInboxSnoozeTriggers(db, input);
|
|
8456
|
+
return [...new Set(triggers.flatMap((trigger) => Object.keys(trigger.match ?? {})))];
|
|
8457
|
+
}
|
|
8458
|
+
/**
|
|
8459
|
+
* Schedule the timer of a snooze. Its `timer.fired` Event wakes the
|
|
8460
|
+
* snoozes whose triggers name `timerId`. A claimed timer is removed even
|
|
8461
|
+
* when no snooze names it yet, so a caller that schedules before the
|
|
8462
|
+
* snoozes commit wakes them itself if the fire time passed meanwhile.
|
|
8298
8463
|
*/
|
|
8299
|
-
|
|
8300
|
-
|
|
8301
|
-
|
|
8302
|
-
|
|
8303
|
-
|
|
8304
|
-
|
|
8305
|
-
|
|
8464
|
+
async function scheduleInboxSnoozeTimer(timerId, firesAtMs) {
|
|
8465
|
+
const state = getStateAdapter();
|
|
8466
|
+
await state.connect();
|
|
8467
|
+
await updateTimerIndex(state, INBOX_SNOOZE_TIMER_INDEX, {
|
|
8468
|
+
atMs: firesAtMs,
|
|
8469
|
+
id: timerId,
|
|
8470
|
+
kind: "add"
|
|
8471
|
+
});
|
|
8472
|
+
}
|
|
8306
8473
|
/**
|
|
8307
|
-
*
|
|
8308
|
-
*
|
|
8309
|
-
*
|
|
8310
|
-
* events and has not expired.
|
|
8474
|
+
* Fire the snooze timers that are due, as `timer.fired` Events. A failed
|
|
8475
|
+
* pass leaves its claims to expire, so the next heartbeat retries them.
|
|
8476
|
+
* Returns the number of items woken.
|
|
8311
8477
|
*/
|
|
8312
|
-
function
|
|
8313
|
-
const
|
|
8314
|
-
|
|
8315
|
-
|
|
8316
|
-
|
|
8317
|
-
|
|
8318
|
-
|
|
8319
|
-
|
|
8320
|
-
|
|
8321
|
-
|
|
8322
|
-
|
|
8323
|
-
|
|
8324
|
-
|
|
8325
|
-
|
|
8326
|
-
|
|
8327
|
-
|
|
8328
|
-
|
|
8329
|
-
|
|
8330
|
-
|
|
8331
|
-
|
|
8332
|
-
|
|
8333
|
-
|
|
8334
|
-
|
|
8335
|
-
|
|
8478
|
+
async function runInboxSnoozeTimers(db, nowMs) {
|
|
8479
|
+
const state = getStateAdapter();
|
|
8480
|
+
await state.connect();
|
|
8481
|
+
const timerIds = await updateTimerIndex(state, INBOX_SNOOZE_TIMER_INDEX, {
|
|
8482
|
+
kind: "claim",
|
|
8483
|
+
nowMs
|
|
8484
|
+
});
|
|
8485
|
+
if (timerIds.length === 0) return 0;
|
|
8486
|
+
const woken = await fireTriggers(db, {
|
|
8487
|
+
eventType: SNOOZE_TIMER_EVENT_TYPE,
|
|
8488
|
+
identifiers: timerIds,
|
|
8489
|
+
namespace: CORE_EVENT_NAMESPACE
|
|
8490
|
+
}, nowMs);
|
|
8491
|
+
await mapBounded(timerIds, (id) => updateTimerIndex(state, INBOX_SNOOZE_TIMER_INDEX, {
|
|
8492
|
+
id,
|
|
8493
|
+
kind: "remove"
|
|
8494
|
+
}));
|
|
8495
|
+
return woken;
|
|
8496
|
+
}
|
|
8497
|
+
// src/chat/agent-dispatch/validation.ts
|
|
8498
|
+
function hasIssueAtPath(issues, path) {
|
|
8499
|
+
return issues.some((issue) => issue.path.length === path.length && issue.path.every((value, index) => value === path[index]));
|
|
8500
|
+
}
|
|
8501
|
+
function hasIssueUnderPath(issues, path) {
|
|
8502
|
+
return issues.some((issue) => path.every((value, index) => issue.path[index] === value));
|
|
8503
|
+
}
|
|
8504
|
+
function dispatchOptionsErrorMessage(issues) {
|
|
8505
|
+
if (hasIssueAtPath(issues, [])) return issues.some((issue) => issue.code === "unrecognized_keys") ? "Dispatch options must not include unknown fields" : "Dispatch options are required";
|
|
8506
|
+
if (issues.some((issue) => issue.code === "unrecognized_keys" && issue.path[0] === "destination")) return "Dispatch destination must not include unknown fields";
|
|
8507
|
+
if (issues.some((issue) => issue.code === "unrecognized_keys" && issue.path[0] === "credentialSubject")) return "Dispatch credentialSubject binding is runtime-owned";
|
|
8508
|
+
if (hasIssueAtPath(issues, ["destination"])) return "Dispatch destination platform must be slack";
|
|
8509
|
+
if (hasIssueUnderPath(issues, ["destination", "teamId"])) return "Dispatch destination teamId must be a Slack team id";
|
|
8510
|
+
if (hasIssueUnderPath(issues, ["destination", "channelId"])) return "Dispatch destination channelId must be a Slack channel id";
|
|
8511
|
+
if (hasIssueUnderPath(issues, ["idempotencyKey"])) return issues.some((issue) => issue.path[0] === "idempotencyKey" && issue.code === "too_big") ? "Dispatch idempotencyKey exceeds the maximum length" : "Dispatch idempotencyKey is required";
|
|
8512
|
+
if (hasIssueUnderPath(issues, ["input"])) return issues.some((issue) => issue.path[0] === "input" && issue.code === "too_big") ? "Dispatch input exceeds the maximum length" : "Dispatch input is required";
|
|
8513
|
+
if (hasIssueUnderPath(issues, ["credentialSubject", "userId"])) return "Dispatch credentialSubject userId is required";
|
|
8514
|
+
if (hasIssueUnderPath(issues, ["credentialSubject", "allowedWhen"])) return "Dispatch credentialSubject allowedWhen is invalid";
|
|
8515
|
+
if (hasIssueUnderPath(issues, ["credentialSubject"])) return "Dispatch credentialSubject type must be user";
|
|
8516
|
+
const metadataIssue = issues.find((issue) => issue.path[0] === "metadata" && (issue.message === "Dispatch metadata has too many keys" || issue.message === "Dispatch metadata keys must be single-line strings" || issue.message === "Dispatch metadata values must be single-line strings" || issue.message === "Dispatch metadata key exceeds the maximum length" || issue.message === "Dispatch metadata value exceeds the maximum length"));
|
|
8517
|
+
if (metadataIssue) return metadataIssue.message;
|
|
8518
|
+
if (hasIssueUnderPath(issues, ["metadata"])) return "Dispatch metadata values must be strings";
|
|
8519
|
+
if (hasIssueUnderPath(issues, ["replyAttribution"])) return "Dispatch reply attribution is invalid";
|
|
8520
|
+
return "Dispatch options are invalid";
|
|
8521
|
+
}
|
|
8522
|
+
/** Validate plugin-provided dispatch options before core persists them. */
|
|
8523
|
+
function validateDispatchOptions(options) {
|
|
8524
|
+
const parsed = dispatchOptionsSchema.safeParse(options);
|
|
8525
|
+
if (!parsed.success) throw new Error(dispatchOptionsErrorMessage(parsed.error.issues));
|
|
8526
|
+
const { credentialSubject, destination } = parsed.data;
|
|
8527
|
+
if (!isSlackDestination(destination)) throw new Error("Dispatch destination platform must be slack");
|
|
8528
|
+
if (credentialSubject !== void 0) {
|
|
8529
|
+
if (credentialSubject.allowedWhen === "private-direct-conversation" && !isDmChannel(destination.channelId)) throw new Error("Dispatch credentialSubject requires a private direct Slack destination");
|
|
8530
|
+
}
|
|
8531
|
+
}
|
|
8532
|
+
/** Verify runtime-owned access requirements for delegated dispatch credentials. */
|
|
8533
|
+
async function verifyDispatchCredentialSubjectAccess(options, plugin) {
|
|
8534
|
+
if (!options.credentialSubject) return;
|
|
8535
|
+
if (!(options.credentialSubject.allowedWhen === "scheduled-automation" ? verifyScheduledAutomationCredentialSubject({
|
|
8536
|
+
plugin,
|
|
8537
|
+
subject: options.credentialSubject
|
|
8538
|
+
}) : options.credentialSubject.allowedWhen === "event-automation" ? verifyEventAutomationCredentialSubject({
|
|
8539
|
+
plugin,
|
|
8540
|
+
subject: options.credentialSubject
|
|
8541
|
+
}) : verifySlackDirectCredentialSubject({
|
|
8542
|
+
channelId: options.destination.channelId,
|
|
8543
|
+
teamId: options.destination.teamId,
|
|
8544
|
+
subject: options.credentialSubject
|
|
8545
|
+
}))) throw new Error("Dispatch credentialSubject is not valid for this action");
|
|
8546
|
+
}
|
|
8547
|
+
// src/chat/agent-dispatch/context.ts
|
|
8548
|
+
const MAX_DISPATCHES_PER_HEARTBEAT = 25;
|
|
8549
|
+
function bindDispatchCredentialSubject(options, plugin) {
|
|
8550
|
+
const { credentialSubject, ...baseOptions } = options;
|
|
8551
|
+
if (!credentialSubject) return {
|
|
8552
|
+
...baseOptions,
|
|
8553
|
+
source: { kind: "plugin_dispatch" }
|
|
8554
|
+
};
|
|
8555
|
+
if ("binding" in credentialSubject) throw new Error("Dispatch credentialSubject binding is runtime-owned");
|
|
8556
|
+
const boundSubject = credentialSubject.allowedWhen === "scheduled-automation" ? bindScheduledAutomationCredentialSubject({
|
|
8557
|
+
plugin,
|
|
8558
|
+
subject: credentialSubject
|
|
8559
|
+
}) : bindSlackDirectCredentialSubject({
|
|
8560
|
+
channelId: options.destination.channelId,
|
|
8561
|
+
teamId: options.destination.teamId,
|
|
8562
|
+
subject: credentialSubject
|
|
8563
|
+
});
|
|
8564
|
+
if (!boundSubject) throw new Error("Dispatch credentialSubject is not valid for this action");
|
|
8565
|
+
return {
|
|
8566
|
+
...baseOptions,
|
|
8567
|
+
credentialSubject: boundSubject,
|
|
8568
|
+
source: { kind: "plugin_dispatch" }
|
|
8569
|
+
};
|
|
8570
|
+
}
|
|
8571
|
+
/** Verify, persist, and enqueue one idempotent agent dispatch. */
|
|
8572
|
+
async function dispatch(args) {
|
|
8573
|
+
await verifyDispatchCredentialSubjectAccess(args.options, args.plugin);
|
|
8574
|
+
const result = await createOrGetDispatch({
|
|
8575
|
+
plugin: args.plugin,
|
|
8576
|
+
options: args.options,
|
|
8577
|
+
nowMs: args.nowMs
|
|
8578
|
+
});
|
|
8579
|
+
if (!isTerminalDispatchStatus(result.record.status)) await enqueueAgentDispatch(result.record, {
|
|
8580
|
+
queue: args.conversationWorkQueue,
|
|
8581
|
+
nowMs: args.nowMs
|
|
8582
|
+
});
|
|
8583
|
+
return {
|
|
8584
|
+
id: result.record.id,
|
|
8585
|
+
status: result.status
|
|
8586
|
+
};
|
|
8587
|
+
}
|
|
8588
|
+
/** Build the plugin-scoped heartbeat context that gates durable dispatch access. */
|
|
8589
|
+
function createHeartbeatContext(args) {
|
|
8590
|
+
const pluginName = typeof args.plugin === "string" ? args.plugin : args.plugin.manifest.name;
|
|
8591
|
+
let dispatchCount = 0;
|
|
8592
|
+
const assertDispatchBudget = () => {
|
|
8593
|
+
if (dispatchCount >= MAX_DISPATCHES_PER_HEARTBEAT) throw new Error("Plugin heartbeat exceeded the dispatch limit");
|
|
8594
|
+
};
|
|
8595
|
+
return {
|
|
8596
|
+
plugin: { name: pluginName },
|
|
8597
|
+
annotations: { forConversation: (conversationId) => createPluginAnnotations({
|
|
8598
|
+
conversationId,
|
|
8599
|
+
db: getDb(),
|
|
8600
|
+
plugin: pluginName
|
|
8601
|
+
}) },
|
|
8602
|
+
cache: createPluginCache(pluginName),
|
|
8603
|
+
codeChanges: createCodeChangePublisher(pluginName),
|
|
8604
|
+
nowMs: args.nowMs,
|
|
8605
|
+
db: getDb(),
|
|
8606
|
+
embedder: createPluginEmbedder(pluginName),
|
|
8607
|
+
events: args.events,
|
|
8608
|
+
reviewItems: { forConversation: (conversationId) => createPluginReviewItems({
|
|
8609
|
+
conversationId,
|
|
8610
|
+
plugin: pluginName,
|
|
8611
|
+
show: args.showReviewItem ?? (async () => {})
|
|
8612
|
+
}) },
|
|
8613
|
+
state: createPluginState(pluginName),
|
|
8614
|
+
log: createPluginLogger(pluginName),
|
|
8615
|
+
agent: {
|
|
8616
|
+
async dispatch(options) {
|
|
8617
|
+
validateDispatchOptions(options);
|
|
8618
|
+
const dispatchOptions = bindDispatchCredentialSubject(options, pluginName);
|
|
8619
|
+
assertDispatchBudget();
|
|
8620
|
+
const result = await dispatch({
|
|
8621
|
+
conversationWorkQueue: args.conversationWorkQueue,
|
|
8622
|
+
nowMs: args.nowMs,
|
|
8623
|
+
options: dispatchOptions,
|
|
8624
|
+
plugin: pluginName
|
|
8625
|
+
});
|
|
8626
|
+
dispatchCount += 1;
|
|
8627
|
+
return result;
|
|
8628
|
+
},
|
|
8629
|
+
async dispatchForIdentity(options) {
|
|
8630
|
+
assertDispatchBudget();
|
|
8631
|
+
dispatchCount += 1;
|
|
8632
|
+
return await args.dispatchForIdentity(pluginName, options);
|
|
8633
|
+
},
|
|
8634
|
+
async get(id) {
|
|
8635
|
+
return await getPluginDispatchProjection({
|
|
8636
|
+
plugin: pluginName,
|
|
8637
|
+
id
|
|
8638
|
+
});
|
|
8639
|
+
}
|
|
8640
|
+
}
|
|
8641
|
+
};
|
|
8642
|
+
}
|
|
8643
|
+
/** Create and enqueue one core-owned event automation dispatch. */
|
|
8644
|
+
async function dispatchEventAutomation(args) {
|
|
8645
|
+
const plugin = "junior";
|
|
8646
|
+
const { credentialSubject, outcomes, skill, ...unboundOptions } = args.options;
|
|
8647
|
+
validateDispatchOptions({ ...unboundOptions });
|
|
8648
|
+
const boundSubject = credentialSubject ? bindEventAutomationCredentialSubject({
|
|
8649
|
+
plugin,
|
|
8650
|
+
subject: credentialSubject
|
|
8651
|
+
}) : void 0;
|
|
8652
|
+
if (credentialSubject && !boundSubject) throw new Error("Dispatch credentialSubject is not valid for this action");
|
|
8653
|
+
const options = {
|
|
8654
|
+
...unboundOptions,
|
|
8655
|
+
...outcomes !== void 0 ? { outcomes } : void 0,
|
|
8656
|
+
...skill ? { skill } : void 0,
|
|
8657
|
+
...boundSubject ? { credentialSubject: boundSubject } : void 0,
|
|
8658
|
+
source: {
|
|
8659
|
+
kind: "event_automation",
|
|
8660
|
+
automationId: args.automationId,
|
|
8661
|
+
automationRunId: buildDispatchId(plugin, unboundOptions.idempotencyKey)
|
|
8662
|
+
}
|
|
8663
|
+
};
|
|
8664
|
+
return await dispatch({
|
|
8665
|
+
conversationWorkQueue: args.conversationWorkQueue,
|
|
8666
|
+
nowMs: args.nowMs,
|
|
8667
|
+
options,
|
|
8668
|
+
plugin
|
|
8669
|
+
});
|
|
8670
|
+
}
|
|
8671
|
+
/** Create and enqueue one core-owned scheduled automation dispatch. */
|
|
8672
|
+
async function dispatchScheduledAutomation(args) {
|
|
8673
|
+
const plugin = "scheduler";
|
|
8674
|
+
const { credentialSubject, outcomes, skill, ...unboundOptions } = args.options;
|
|
8675
|
+
validateDispatchOptions({ ...unboundOptions });
|
|
8676
|
+
const boundSubject = credentialSubject ? bindScheduledAutomationCredentialSubject({
|
|
8677
|
+
plugin,
|
|
8678
|
+
subject: credentialSubject
|
|
8679
|
+
}) : void 0;
|
|
8680
|
+
if (credentialSubject && !boundSubject) throw new Error("Dispatch credentialSubject is not valid for this action");
|
|
8681
|
+
const options = {
|
|
8682
|
+
...unboundOptions,
|
|
8683
|
+
...outcomes !== void 0 ? { outcomes } : void 0,
|
|
8684
|
+
...skill ? { skill } : void 0,
|
|
8685
|
+
...boundSubject ? { credentialSubject: boundSubject } : void 0,
|
|
8686
|
+
source: {
|
|
8687
|
+
kind: "scheduled_automation",
|
|
8688
|
+
automationId: args.automationId,
|
|
8689
|
+
automationRunId: unboundOptions.idempotencyKey
|
|
8690
|
+
}
|
|
8691
|
+
};
|
|
8692
|
+
return await dispatch({
|
|
8693
|
+
conversationWorkQueue: args.conversationWorkQueue,
|
|
8694
|
+
nowMs: args.nowMs,
|
|
8695
|
+
options,
|
|
8696
|
+
plugin
|
|
8697
|
+
});
|
|
8698
|
+
}
|
|
8699
|
+
/** Read the bounded outcome for one core-owned scheduled automation dispatch. */
|
|
8700
|
+
async function getScheduledAutomationDispatch(id) {
|
|
8701
|
+
return await getPluginDispatchProjection({
|
|
8702
|
+
plugin: "scheduler",
|
|
8703
|
+
id
|
|
8704
|
+
});
|
|
8705
|
+
}
|
|
8706
|
+
// src/chat/event-automations/runs.ts
|
|
8707
|
+
/**
|
|
8708
|
+
* Record a dispatched event automation run with the Automation version it ran,
|
|
8709
|
+
* and link its Conversation when it exists. The dispatch can finish before
|
|
8710
|
+
* this write, so a stored run, or a retry of the same Event, keeps the row it
|
|
8711
|
+
* has.
|
|
8712
|
+
*/
|
|
8713
|
+
async function recordEventAutomationRunStarted(db, args) {
|
|
8714
|
+
const conversationId = getDispatchConversationId({ id: args.dispatchId });
|
|
8715
|
+
await db.insert(juniorAutomationRuns).values({
|
|
8716
|
+
id: args.dispatchId,
|
|
8717
|
+
automationId: args.automation.id,
|
|
8718
|
+
automationVersion: automationVersionOf(args.automation),
|
|
8719
|
+
conversationId: existingConversationId(conversationId),
|
|
8720
|
+
costMicroUsd: conversationCostOf(conversationId),
|
|
8721
|
+
startedAtMs: args.nowMs,
|
|
8722
|
+
status: "running"
|
|
8723
|
+
}).onConflictDoNothing({ target: juniorAutomationRuns.id });
|
|
8724
|
+
}
|
|
8725
|
+
/**
|
|
8726
|
+
* Settle running event automation runs whose dispatch has ended. A run whose
|
|
8727
|
+
* dispatch record is gone fails.
|
|
8728
|
+
*/
|
|
8729
|
+
async function settleEventAutomationRuns(db, nowMs) {
|
|
8730
|
+
const runs = await db.select({
|
|
8731
|
+
automationId: juniorAutomationRuns.automationId,
|
|
8732
|
+
id: juniorAutomationRuns.id
|
|
8733
|
+
}).from(juniorAutomationRuns).innerJoin(juniorAutomations, eq(juniorAutomations.id, juniorAutomationRuns.automationId)).where(and(eq(juniorAutomations.kind, "event"), eq(juniorAutomationRuns.status, "running")));
|
|
8734
|
+
const dispatches = await mapBounded(runs, (run) => getDispatchRecord(run.id));
|
|
8735
|
+
for (const [index, run] of runs.entries()) {
|
|
8736
|
+
const dispatch = dispatches[index];
|
|
8737
|
+
const status = dispatch?.status ?? "failed";
|
|
8738
|
+
if (status !== "blocked" && status !== "completed" && status !== "failed") continue;
|
|
8739
|
+
await recordAutomationExecution(run.automationId, {
|
|
8740
|
+
conversationId: getDispatchConversationId({ id: run.id }),
|
|
8741
|
+
errorMessage: dispatch ? dispatch.errorMessage : "Event automation dispatch record is missing.",
|
|
8742
|
+
executionId: run.id,
|
|
8743
|
+
nowMs: dispatch?.updatedAtMs ?? nowMs,
|
|
8744
|
+
status
|
|
8745
|
+
});
|
|
8746
|
+
}
|
|
8747
|
+
}
|
|
8748
|
+
// src/chat/automations/reply-attribution.ts
|
|
8749
|
+
/** Name the Automation in the footer of the replies that its runs post. */
|
|
8750
|
+
function automationReplyAttribution(title) {
|
|
8751
|
+
const detail = (title ?? "").replace(/\s+/g, " ").trim().slice(0, 128).trim();
|
|
8752
|
+
return detail ? {
|
|
8753
|
+
label: "Automation",
|
|
8754
|
+
detail
|
|
8755
|
+
} : { label: "Automation" };
|
|
8336
8756
|
}
|
|
8337
8757
|
// src/api/user-settings.ts
|
|
8338
8758
|
const userPreferencesSchema = z.object({
|
|
@@ -8384,15 +8804,29 @@ function runCutoff(run) {
|
|
|
8384
8804
|
return /* @__PURE__ */ new Date(run.now.getTime() - run.graceHours * HOUR_MS);
|
|
8385
8805
|
}
|
|
8386
8806
|
/**
|
|
8387
|
-
* True when the participant row's root and every child conversation are idle
|
|
8388
|
-
*
|
|
8389
|
-
*
|
|
8390
|
-
* `lastActivityAt`, so the whole tree is checked.
|
|
8807
|
+
* True when the participant row's root and every child conversation are idle
|
|
8808
|
+
* and had no activity after the cutoff. Child activity does not move the
|
|
8809
|
+
* root's `lastActivityAt`, so the whole tree is checked.
|
|
8391
8810
|
*/
|
|
8392
8811
|
function treeIsQuiet(run) {
|
|
8393
|
-
const active = getDb().select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(or(eq(juniorConversations.conversationId, juniorConversationParticipants.rootConversationId), eq(juniorConversations.rootConversationId, juniorConversationParticipants.rootConversationId)), or(ne(juniorConversations.executionStatus, "idle"), gt(juniorConversations.lastActivityAt, runCutoff(run))
|
|
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.lastActivityAt, runCutoff(run)))));
|
|
8394
8813
|
return sql`not exists (${active})`;
|
|
8395
8814
|
}
|
|
8815
|
+
const OPEN_PLAN_ITEM_STATUSES = PLAN_ITEM_STATUSES.filter(isOpenPlanItemStatus);
|
|
8816
|
+
/**
|
|
8817
|
+
* True when nothing in the participant row's tree needs a person. No
|
|
8818
|
+
* conversation in it has `needs_input` status: an open action Review item
|
|
8819
|
+
* 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 Plan item in it is
|
|
8821
|
+
* assigned to a person. Archive applies to everyone, so input that waits
|
|
8822
|
+
* on anyone keeps the tree. An archived child counts for nothing, as in
|
|
8823
|
+
* the tree state.
|
|
8824
|
+
*/
|
|
8825
|
+
function treeNeedsNoOne() {
|
|
8826
|
+
const assignedToPerson = getDb().select({ id: juniorPlanItems.id }).from(juniorPlanItems).where(and(eq(juniorPlanItems.conversationId, juniorConversations.conversationId), isNotNull(juniorPlanItems.assigneeUserId), inArray(juniorPlanItems.status, OPEN_PLAN_ITEM_STATUSES)));
|
|
8827
|
+
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
|
+
return sql`not exists (${needing})`;
|
|
8829
|
+
}
|
|
8396
8830
|
/**
|
|
8397
8831
|
* True when no open Review item on the participant row's root or a child
|
|
8398
8832
|
* conversation needs a person. Archive applies to everyone, so a
|
|
@@ -8426,7 +8860,7 @@ function rootIsUnarchived() {
|
|
|
8426
8860
|
* changed setting wins over a stale read.
|
|
8427
8861
|
*/
|
|
8428
8862
|
function archivableRow(run) {
|
|
8429
|
-
return and(eq(juniorConversationParticipants.userId, run.userId), isNull(juniorConversationParticipants.unsubscribedAt), rootIsUnarchived(), noParticipantKeepsRoot(), lte(juniorConversationParticipants.lastMessageAt, runCutoff(run)), runOptsIn(run), run.kind === "scheduled" ? sql`${juniorUsers.autoArchiveGraceHours} <= ${run.graceHours}` : void 0, treeIsQuiet(run), notWaitingOnAnyone());
|
|
8863
|
+
return and(eq(juniorConversationParticipants.userId, run.userId), isNull(juniorConversationParticipants.unsubscribedAt), rootIsUnarchived(), noParticipantKeepsRoot(), lte(juniorConversationParticipants.lastMessageAt, runCutoff(run)), runOptsIn(run), run.kind === "scheduled" ? sql`${juniorUsers.autoArchiveGraceHours} <= ${run.graceHours}` : void 0, treeIsQuiet(run), treeNeedsNoOne(), notWaitingOnAnyone());
|
|
8430
8864
|
}
|
|
8431
8865
|
/**
|
|
8432
8866
|
* One page of the user's participant rows on unarchived roots that may be
|
|
@@ -8562,6 +8996,259 @@ async function setConversationAutoArchive(viewer, conversationId, autoArchive) {
|
|
|
8562
8996
|
});
|
|
8563
8997
|
return { autoArchive };
|
|
8564
8998
|
}
|
|
8999
|
+
// src/chat/review-items/automation-answer.ts
|
|
9000
|
+
function isStepLabel(label) {
|
|
9001
|
+
return Object.hasOwn(AUTOMATION_ALERT_STEPS, label);
|
|
9002
|
+
}
|
|
9003
|
+
/**
|
|
9004
|
+
* Take the step that a person picked on an Automation alert, Run again or
|
|
9005
|
+
* Pause, so core does the work. The answer starts no Turn. Throws when the
|
|
9006
|
+
* step fails, so the person can retry the same answer.
|
|
9007
|
+
*/
|
|
9008
|
+
async function answerAutomationAlert(args) {
|
|
9009
|
+
const label = args.item.answer?.values[AUTOMATION_ALERT_STEP_FIELD_ID]?.[0];
|
|
9010
|
+
if (!label || !isStepLabel(label)) return;
|
|
9011
|
+
await takeViewerAutomationAlertStep(args.user, args.item.owner.id, AUTOMATION_ALERT_STEPS[label]);
|
|
9012
|
+
}
|
|
9013
|
+
// src/chat/event-automations/ingest.ts
|
|
9014
|
+
/**
|
|
9015
|
+
* Owns event matching and durable event-automation dispatch.
|
|
9016
|
+
*
|
|
9017
|
+
* Each matching automation is independently idempotent. Aggregate failures propagate
|
|
9018
|
+
* so the provider can retry the original delivery.
|
|
9019
|
+
*/
|
|
9020
|
+
/** Bind provider delivery identity to one automation's durable dispatch. */
|
|
9021
|
+
function eventAutomationDispatchKey(taskId, namespace, eventKey) {
|
|
9022
|
+
return `event-automation:${createHash("sha256").update(`${taskId}\0${namespace}\0${eventKey}`).digest("hex").slice(0, 32)}`;
|
|
9023
|
+
}
|
|
9024
|
+
/** Render plain agent input for one matching event automation. */
|
|
9025
|
+
function eventInput(task, event, outcomes, catalog, author) {
|
|
9026
|
+
const guidance = eventGuidance(catalog, event.namespace, event.eventType);
|
|
9027
|
+
return renderTaskInput({
|
|
9028
|
+
about: task.trigger.label,
|
|
9029
|
+
event: event.eventType,
|
|
9030
|
+
source: event.namespace,
|
|
9031
|
+
creator: slackMention(task.createdBy.slackUserId),
|
|
9032
|
+
instructions: automationTaskText(task.task),
|
|
9033
|
+
...task.task.kind === "skill" ? { skill: task.task.skill } : void 0,
|
|
9034
|
+
outcomes,
|
|
9035
|
+
guidance,
|
|
9036
|
+
trustedSummary: event.trustedSummary,
|
|
9037
|
+
trustedSummaryMaxLength: EVENT_SUMMARY_MAX_LENGTH,
|
|
9038
|
+
verifiedDetails: event.data,
|
|
9039
|
+
authorText: eventAuthorText(author),
|
|
9040
|
+
externalText: event.untrustedText,
|
|
9041
|
+
externalTextMaxLength: EVENT_TEXT_MAX_LENGTH
|
|
9042
|
+
});
|
|
9043
|
+
}
|
|
9044
|
+
/**
|
|
9045
|
+
* Match a normalized event and dispatch every matching automation.
|
|
9046
|
+
*
|
|
9047
|
+
* Plugins publish one copy of an occurrence for each scope, such as a pull
|
|
9048
|
+
* request and its repository. All copies share one event key. An automation
|
|
9049
|
+
* with no identifier matches every copy, and the dispatch key and the run
|
|
9050
|
+
* limit both use the event key, so it runs and counts once.
|
|
9051
|
+
*/
|
|
9052
|
+
async function ingestEventAutomations(input, options) {
|
|
9053
|
+
const event = eventSchema.parse(input);
|
|
9054
|
+
const db = getDb();
|
|
9055
|
+
const nowMs = options.nowMs ?? Date.now();
|
|
9056
|
+
const catalog = getEventCatalog();
|
|
9057
|
+
const [matches = []] = await findMatchingEventAutomations(db, [event], options.teamId, catalog);
|
|
9058
|
+
const tasks = matches.filter((task) => slackChannelMessageRunsAutomation(event, task));
|
|
9059
|
+
if (tasks.length === 0) return { dispatched: 0 };
|
|
9060
|
+
const author = await resolveEventAuthor(event);
|
|
9061
|
+
let dispatched = 0;
|
|
9062
|
+
const errors = [];
|
|
9063
|
+
for (const task of tasks) try {
|
|
9064
|
+
const skill = task.task.kind === "skill" ? task.task.skill : void 0;
|
|
9065
|
+
if (skill && !await findAutomationSkill(skill)) {
|
|
9066
|
+
const reason = missingAutomationSkillReason(skill);
|
|
9067
|
+
if (await blockEventAutomation(db, task.id, reason)) await notifyAutomationBlocked({
|
|
9068
|
+
automationId: task.id,
|
|
9069
|
+
kind: "event",
|
|
9070
|
+
reason
|
|
9071
|
+
});
|
|
9072
|
+
continue;
|
|
9073
|
+
}
|
|
9074
|
+
const idempotencyKey = eventAutomationDispatchKey(task.id, event.namespace, event.eventKey);
|
|
9075
|
+
if (await admitEventAutomationRun({
|
|
9076
|
+
automationId: task.id,
|
|
9077
|
+
nowMs,
|
|
9078
|
+
runKey: idempotencyKey
|
|
9079
|
+
}) === "limited") {
|
|
9080
|
+
const reason = eventAutomationRunLimitReason();
|
|
9081
|
+
logWarn("event_automation.run_limit.exceeded", {
|
|
9082
|
+
"app.task.id": task.id,
|
|
9083
|
+
"app.task.type": "event"
|
|
9084
|
+
});
|
|
9085
|
+
if (await blockEventAutomation(db, task.id, reason)) {
|
|
9086
|
+
captureMessage("Event automation blocked by run limit", {
|
|
9087
|
+
level: "warning",
|
|
9088
|
+
fingerprint: ["event_automation.run_limit.blocked"],
|
|
9089
|
+
tags: {
|
|
9090
|
+
"app.event.namespace": event.namespace,
|
|
9091
|
+
"app.task.type": "event"
|
|
9092
|
+
},
|
|
9093
|
+
extra: {
|
|
9094
|
+
"app.event.event_type": event.eventType,
|
|
9095
|
+
"app.event_automation.max_runs": botConfig.maxEventAutomationRuns,
|
|
9096
|
+
"app.event_automation.run_window_ms": botConfig.eventAutomationRunWindowMs,
|
|
9097
|
+
"app.event_automation.resource_type": task.trigger.resourceType ?? "any",
|
|
9098
|
+
"app.task.id": task.id
|
|
9099
|
+
}
|
|
9100
|
+
});
|
|
9101
|
+
await notifyAutomationBlocked({
|
|
9102
|
+
automationId: task.id,
|
|
9103
|
+
kind: "event",
|
|
9104
|
+
reason
|
|
9105
|
+
});
|
|
9106
|
+
}
|
|
9107
|
+
continue;
|
|
9108
|
+
}
|
|
9109
|
+
const replyThreadTs = slackChannelMessageReplyThreadTs(event);
|
|
9110
|
+
const destination = replyThreadTs ? {
|
|
9111
|
+
...task.destination,
|
|
9112
|
+
threadTs: replyThreadTs
|
|
9113
|
+
} : task.destination;
|
|
9114
|
+
const outcomes = effectiveTaskOutcomes(task.outcomes, destination);
|
|
9115
|
+
const credentialSubject = task.credentialMode === "creator" ? {
|
|
9116
|
+
type: "user",
|
|
9117
|
+
userId: task.createdBy.slackUserId,
|
|
9118
|
+
allowedWhen: "event-automation",
|
|
9119
|
+
taskId: task.id
|
|
9120
|
+
} : void 0;
|
|
9121
|
+
const dispatch = await dispatchEventAutomation({
|
|
9122
|
+
automationId: task.id,
|
|
9123
|
+
conversationWorkQueue: options.queue,
|
|
9124
|
+
nowMs,
|
|
9125
|
+
options: {
|
|
9126
|
+
idempotencyKey,
|
|
9127
|
+
...credentialSubject ? { credentialSubject } : void 0,
|
|
9128
|
+
destination,
|
|
9129
|
+
destinationVisibility: task.destinationVisibility,
|
|
9130
|
+
input: eventInput(task, event, outcomes, catalog, author),
|
|
9131
|
+
...skill ? { skill } : void 0,
|
|
9132
|
+
metadata: { eventAutomationId: task.id },
|
|
9133
|
+
replyAttribution: automationReplyAttribution(task.title),
|
|
9134
|
+
outcomes
|
|
9135
|
+
}
|
|
9136
|
+
});
|
|
9137
|
+
await recordEventAutomationRunStarted(db, {
|
|
9138
|
+
automation: task,
|
|
9139
|
+
dispatchId: dispatch.id,
|
|
9140
|
+
nowMs
|
|
9141
|
+
});
|
|
9142
|
+
if (dispatch.status === "created") dispatched += 1;
|
|
9143
|
+
} catch (error) {
|
|
9144
|
+
errors.push(error);
|
|
9145
|
+
}
|
|
9146
|
+
if (errors.length > 0) throw new AggregateError(errors, "Failed to dispatch one or more event automations");
|
|
9147
|
+
return { dispatched };
|
|
9148
|
+
}
|
|
9149
|
+
// src/chat/events/app-publisher.ts
|
|
9150
|
+
const WATCH_MATCH_CONCURRENCY = 4;
|
|
9151
|
+
/** Build the core event publisher used by plugin routes. */
|
|
9152
|
+
function createEventAppPublisher(args) {
|
|
9153
|
+
return {
|
|
9154
|
+
async hasMatch(events) {
|
|
9155
|
+
const work = args.conversationWork();
|
|
9156
|
+
const eventAutomationTeamId = await resolveBotSlackTeamId();
|
|
9157
|
+
const [subscriptions, tasks, snoozed] = await Promise.all([
|
|
9158
|
+
mapBounded(events, (event) => findMatchingWatches({
|
|
9159
|
+
data: event.data,
|
|
9160
|
+
eventType: event.eventType,
|
|
9161
|
+
namespace: event.namespace,
|
|
9162
|
+
identifier: event.identifier,
|
|
9163
|
+
state: work.state
|
|
9164
|
+
}), WATCH_MATCH_CONCURRENCY),
|
|
9165
|
+
eventAutomationTeamId ? findMatchingEventAutomations(getDb(), events, eventAutomationTeamId, getEventCatalog()) : Promise.resolve([]),
|
|
9166
|
+
hasInboxSnoozeMatch(getDb(), events)
|
|
9167
|
+
]);
|
|
9168
|
+
return snoozed || [...subscriptions, ...tasks].some((matched) => matched.length > 0);
|
|
9169
|
+
},
|
|
9170
|
+
async neededMatchKeys(input) {
|
|
9171
|
+
const work = args.conversationWork();
|
|
9172
|
+
const eventAutomationTeamId = await resolveBotSlackTeamId();
|
|
9173
|
+
const [watchKeys, taskKeys, snoozeKeys] = await Promise.all([
|
|
9174
|
+
collectEventMatchKeys({
|
|
9175
|
+
eventTypes: input.eventTypes,
|
|
9176
|
+
identifiers: input.identifiers,
|
|
9177
|
+
namespace: input.namespace,
|
|
9178
|
+
state: work.state
|
|
9179
|
+
}),
|
|
9180
|
+
eventAutomationTeamId ? collectEventAutomationMatchKeys(getDb(), {
|
|
9181
|
+
catalog: getEventCatalog(),
|
|
9182
|
+
...input.data ? { data: input.data } : void 0,
|
|
9183
|
+
eventTypes: input.eventTypes,
|
|
9184
|
+
identifiers: input.identifiers,
|
|
9185
|
+
namespace: input.namespace,
|
|
9186
|
+
teamId: eventAutomationTeamId
|
|
9187
|
+
}) : Promise.resolve([]),
|
|
9188
|
+
collectInboxSnoozeMatchKeys(getDb(), {
|
|
9189
|
+
eventTypes: input.eventTypes,
|
|
9190
|
+
identifiers: input.identifiers,
|
|
9191
|
+
namespace: input.namespace
|
|
9192
|
+
})
|
|
9193
|
+
]);
|
|
9194
|
+
return [.../* @__PURE__ */ new Set([
|
|
9195
|
+
...watchKeys,
|
|
9196
|
+
...taskKeys,
|
|
9197
|
+
...snoozeKeys
|
|
9198
|
+
])].sort();
|
|
9199
|
+
},
|
|
9200
|
+
async publish(event) {
|
|
9201
|
+
const work = args.conversationWork();
|
|
9202
|
+
const queue = work.queue ?? getVercelConversationWorkQueue();
|
|
9203
|
+
const eventAutomationTeamId = await resolveBotSlackTeamId();
|
|
9204
|
+
await Promise.all([
|
|
9205
|
+
ingestEvent(event, {
|
|
9206
|
+
queue,
|
|
9207
|
+
slackTeamId: eventAutomationTeamId,
|
|
9208
|
+
state: work.state
|
|
9209
|
+
}),
|
|
9210
|
+
eventAutomationTeamId ? ingestEventAutomations(event, {
|
|
9211
|
+
queue,
|
|
9212
|
+
teamId: eventAutomationTeamId
|
|
9213
|
+
}) : Promise.resolve(),
|
|
9214
|
+
fireInboxSnoozeTriggers(getDb(), event)
|
|
9215
|
+
]);
|
|
9216
|
+
}
|
|
9217
|
+
};
|
|
9218
|
+
}
|
|
9219
|
+
// src/chat/review-items/plugin-answer.ts
|
|
9220
|
+
/**
|
|
9221
|
+
* Give the answer of a plugin item with choices to the plugin that added it,
|
|
9222
|
+
* so the plugin does the work. The answer starts no Turn. Throws when the
|
|
9223
|
+
* plugin fails, so the person can retry the same answer.
|
|
9224
|
+
*/
|
|
9225
|
+
async function answerPluginReviewItem(args) {
|
|
9226
|
+
const { item } = args;
|
|
9227
|
+
const pluginName = reviewItemPlugin(item.dedupeKey);
|
|
9228
|
+
const choice = item.answer?.values[PLUGIN_CHOICE_FIELD_ID]?.[0];
|
|
9229
|
+
const conversationId = ownerConversationId(item);
|
|
9230
|
+
if (!pluginName || !choice || !conversationId) return;
|
|
9231
|
+
const plugin = getPlugins().find((p) => p.manifest.name === pluginName);
|
|
9232
|
+
const hook = plugin?.hooks?.reviewItemAnswered;
|
|
9233
|
+
if (!plugin || !hook) return;
|
|
9234
|
+
const events = createEventAppPublisher({ conversationWork: () => ({ queue: args.delivery.queue }) });
|
|
9235
|
+
await hook({
|
|
9236
|
+
...basePluginContext(plugin),
|
|
9237
|
+
choice,
|
|
9238
|
+
conversationId,
|
|
9239
|
+
dedupeKey: item.dedupeKey.slice(`${PLUGIN_REVIEW_ITEM_KEY_PREFIX}${pluginName}:`.length),
|
|
9240
|
+
events: createPluginEventPublisher(plugin, events),
|
|
9241
|
+
itemId: item.id,
|
|
9242
|
+
nowMs: args.nowMs,
|
|
9243
|
+
reviewItems: { forConversation: (conversationId) => createPluginReviewItems({
|
|
9244
|
+
conversationId,
|
|
9245
|
+
plugin: pluginName,
|
|
9246
|
+
show: args.delivery.show
|
|
9247
|
+
}) },
|
|
9248
|
+
state: createPluginState(pluginName),
|
|
9249
|
+
watches: createPluginConversationWatches(plugin, conversationId)
|
|
9250
|
+
});
|
|
9251
|
+
}
|
|
8565
9252
|
// src/chat/review-items/reply-match.ts
|
|
8566
9253
|
const MATCH_CONFIDENCE_THRESHOLD = .7;
|
|
8567
9254
|
/** A slow decision keeps the items open instead of delaying the close. */
|
|
@@ -8661,7 +9348,7 @@ function reviewItemChange(action, user) {
|
|
|
8661
9348
|
}
|
|
8662
9349
|
/**
|
|
8663
9350
|
* Return whether a closed item is the result of this same action. An item
|
|
8664
|
-
* that a person's message closed never matches a card or
|
|
9351
|
+
* that a person's message closed never matches a card or Inbox action.
|
|
8665
9352
|
*/
|
|
8666
9353
|
function isSameClose(item, action, user) {
|
|
8667
9354
|
return item.closeReason !== "Replied in thread" && item.closedBy?.userId === user.id && item.status === closedStatus(action) && action === "submit" === Boolean(item.answer);
|
|
@@ -8727,6 +9414,21 @@ async function actOnReviewItem(args) {
|
|
|
8727
9414
|
closed = await readReviewItemForUser(user, item.id);
|
|
8728
9415
|
}
|
|
8729
9416
|
if (args.firstCloseOnly ? !closedNow : !isSameClose(closed, action, user)) throw new ReviewItemActionError("conflict", "Review item is closed.");
|
|
9417
|
+
if (action === "submit" && isPluginReviewItem(closed)) await answerPluginReviewItem({
|
|
9418
|
+
delivery: args.delivery,
|
|
9419
|
+
item: closed,
|
|
9420
|
+
nowMs
|
|
9421
|
+
});
|
|
9422
|
+
if (action === "submit" && isAutomationAlertItem(closed)) try {
|
|
9423
|
+
await answerAutomationAlert({
|
|
9424
|
+
item: closed,
|
|
9425
|
+
user
|
|
9426
|
+
});
|
|
9427
|
+
} catch (error) {
|
|
9428
|
+
if (error instanceof ViewerTaskNotFoundError) throw new ReviewItemActionError("not_found", "Automation not found.");
|
|
9429
|
+
if (error instanceof AutomationEditError) throw new ReviewItemActionError("invalid", error.message);
|
|
9430
|
+
throw error;
|
|
9431
|
+
}
|
|
8730
9432
|
await deliverReviewItemChange({
|
|
8731
9433
|
change: reviewItemChange(action, user),
|
|
8732
9434
|
delivery: args.delivery,
|
|
@@ -8764,7 +9466,7 @@ function messageAnswer(item, text) {
|
|
|
8764
9466
|
*
|
|
8765
9467
|
* A reply closes an item only when all of these are true:
|
|
8766
9468
|
* - The item is an open `action` item.
|
|
8767
|
-
* - The agent added it in this Conversation
|
|
9469
|
+
* - The agent added it in this Conversation, its owner.
|
|
8768
9470
|
* - The replier is an assigned User, or the item has no assignees. A Slack
|
|
8769
9471
|
* replier without a Junior User closes only items with no assignees.
|
|
8770
9472
|
* - The decision model says that the reply answers this item
|
|
@@ -8772,7 +9474,7 @@ function messageAnswer(item, text) {
|
|
|
8772
9474
|
* When the decision fails, all items stay open.
|
|
8773
9475
|
*
|
|
8774
9476
|
* Items assigned to Everyone, or only to other people, stay open. They need
|
|
8775
|
-
* an answer on the card or the
|
|
9477
|
+
* an answer on the card or the Inbox. Each item closes as `done` with
|
|
8776
9478
|
* `REVIEW_ITEM_REPLIED_REASON`, and the replier closes it. The reply itself
|
|
8777
9479
|
* is the answer in this Conversation, so only the other linked
|
|
8778
9480
|
* Conversations get a message. A click that closes the item first wins.
|
|
@@ -8936,27 +9638,40 @@ async function resolveMentions(executor, sources) {
|
|
|
8936
9638
|
});
|
|
8937
9639
|
});
|
|
8938
9640
|
}
|
|
9641
|
+
const userPhotos = alias(juniorIdentities, "mention_user_photos");
|
|
8939
9642
|
/**
|
|
8940
|
-
* Read current names for mentioned Slack users. Known Junior
|
|
8941
|
-
* first. The email is set only for a linked, verified Junior
|
|
8942
|
-
* that email is the People profile route.
|
|
9643
|
+
* Read current names and photos for mentioned Slack users. Known Junior
|
|
9644
|
+
* identities come first. The email is set only for a linked, verified Junior
|
|
9645
|
+
* user, because that email is the People profile route.
|
|
8943
9646
|
*/
|
|
8944
9647
|
async function readMentionedPeople(executor, tenantId, userIds) {
|
|
8945
9648
|
const rows = await executor.db().select({
|
|
9649
|
+
avatarUrl: juniorIdentities.avatarUrl,
|
|
8946
9650
|
displayName: juniorIdentities.displayName,
|
|
8947
9651
|
emailVerified: juniorIdentities.emailVerified,
|
|
8948
9652
|
handle: juniorIdentities.handle,
|
|
9653
|
+
identityId: juniorIdentities.id,
|
|
9654
|
+
photo: {
|
|
9655
|
+
avatarUrl: userPhotos.avatarUrl,
|
|
9656
|
+
identityId: userPhotos.id,
|
|
9657
|
+
provider: userPhotos.provider,
|
|
9658
|
+
updatedAt: userPhotos.updatedAt
|
|
9659
|
+
},
|
|
8949
9660
|
providerSubjectId: juniorIdentities.providerSubjectId,
|
|
8950
9661
|
userDisplayName: juniorUsers.displayName,
|
|
8951
|
-
userEmail: juniorUsers.primaryEmail
|
|
8952
|
-
|
|
9662
|
+
userEmail: juniorUsers.primaryEmail,
|
|
9663
|
+
userId: juniorIdentities.userId
|
|
9664
|
+
}).from(juniorIdentities).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).leftJoin(userPhotos, and(eq(userPhotos.userId, juniorIdentities.userId), hasUserPhoto(userPhotos))).where(and(eq(juniorIdentities.provider, "slack"), inArray(juniorIdentities.providerSubjectId, userIds), tenantId ? eq(juniorIdentities.providerTenantId, tenantId) : void 0));
|
|
9665
|
+
const userAvatarUrls = userAvatarUrlsFromJoinedPhotos(rows);
|
|
8953
9666
|
const people = /* @__PURE__ */ new Map();
|
|
8954
9667
|
for (const row of rows) {
|
|
8955
9668
|
if (people.has(row.providerSubjectId)) continue;
|
|
8956
9669
|
const fullName = row.userDisplayName?.trim() || row.displayName?.trim();
|
|
8957
9670
|
const email = row.emailVerified ? row.userEmail?.trim() : void 0;
|
|
9671
|
+
const avatarUrl = identityAvatarUrl(row, userAvatarUrls);
|
|
8958
9672
|
people.set(row.providerSubjectId, {
|
|
8959
9673
|
slackUserId: row.providerSubjectId,
|
|
9674
|
+
...avatarUrl ? { avatarUrl } : void 0,
|
|
8960
9675
|
...fullName ? { fullName } : void 0,
|
|
8961
9676
|
...row.handle ? { slackUserName: row.handle } : void 0,
|
|
8962
9677
|
...email ? { email } : void 0
|
|
@@ -9132,7 +9847,7 @@ async function readConversationPendingMessages(conversationId, options = {}) {
|
|
|
9132
9847
|
actorIdentityId
|
|
9133
9848
|
} : message];
|
|
9134
9849
|
}));
|
|
9135
|
-
return
|
|
9850
|
+
return {
|
|
9136
9851
|
...authorization ? { authorization: {
|
|
9137
9852
|
authorizationUrl: authorization.authorizationUrl,
|
|
9138
9853
|
completionText: authorization.completionText,
|
|
@@ -9141,7 +9856,7 @@ async function readConversationPendingMessages(conversationId, options = {}) {
|
|
|
9141
9856
|
conversationId,
|
|
9142
9857
|
generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
9143
9858
|
messages
|
|
9144
|
-
}
|
|
9859
|
+
};
|
|
9145
9860
|
}
|
|
9146
9861
|
/** Load pending mailbox messages or throw a standard API not-found error. */
|
|
9147
9862
|
async function requireConversationPendingMessages(conversationId, options = {}) {
|
|
@@ -9856,7 +10571,8 @@ async function readConversationAgentTree(conversation, readAccess) {
|
|
|
9856
10571
|
if (lineage.length < 2) return;
|
|
9857
10572
|
const ids = lineage.map((entry) => entry.conversationId);
|
|
9858
10573
|
const kindById = new Map(lineage.map((entry) => [entry.conversationId, entry.kind]));
|
|
9859
|
-
const
|
|
10574
|
+
const rootRecord = lineage[0].parentConversationId ? void 0 : await readConversationRecordFromSql(ids[0]);
|
|
10575
|
+
const root = rootRecord?.conversation;
|
|
9860
10576
|
const [access, automationTitleByConversation, firstHumanMessageTextByConversation] = await Promise.all([
|
|
9861
10577
|
readAccess(ids),
|
|
9862
10578
|
readAutomationTitlesByConversationId(root ? [root] : []),
|
|
@@ -9864,7 +10580,7 @@ async function readConversationAgentTree(conversation, readAccess) {
|
|
|
9864
10580
|
]);
|
|
9865
10581
|
return await mapBounded(ids, async (id) => {
|
|
9866
10582
|
const itemAccess = access.get(id);
|
|
9867
|
-
if (root?.conversationId === id) return {
|
|
10583
|
+
if (rootRecord && root?.conversationId === id) return {
|
|
9868
10584
|
conversationId: id,
|
|
9869
10585
|
kind: "root",
|
|
9870
10586
|
label: conversationSummaryFromStoredConversation({
|
|
@@ -9872,7 +10588,8 @@ async function readConversationAgentTree(conversation, readAccess) {
|
|
|
9872
10588
|
automationTitle: automationTitleByConversation.get(id),
|
|
9873
10589
|
conversation: root,
|
|
9874
10590
|
durationMs: 0,
|
|
9875
|
-
firstHumanMessageText: firstHumanMessageTextByConversation.get(id)
|
|
10591
|
+
firstHumanMessageText: firstHumanMessageTextByConversation.get(id),
|
|
10592
|
+
status: rootRecord.status
|
|
9876
10593
|
}).displayTitle
|
|
9877
10594
|
};
|
|
9878
10595
|
const kind = kindById.get(id);
|
|
@@ -9989,96 +10706,19 @@ async function attachConversationMentions(executor, conversationId, content) {
|
|
|
9989
10706
|
events: content.events.map((event, index) => withMentions(event, mentions[index]))
|
|
9990
10707
|
};
|
|
9991
10708
|
}
|
|
9992
|
-
/**
|
|
9993
|
-
|
|
10709
|
+
/**
|
|
10710
|
+
* Attach the people that each activity preview mentions, resolved at read
|
|
10711
|
+
* time. `tenants` holds the Slack workspace of each conversation, which the
|
|
10712
|
+
* feed already read with its rows.
|
|
10713
|
+
*/
|
|
10714
|
+
async function attachActivityPreviewMentions(executor, previews, tenants) {
|
|
9994
10715
|
const entries = [...previews];
|
|
9995
|
-
const tenants = await loadConversationSlackTenantIds(executor, entries.map(([conversationId]) => conversationId));
|
|
9996
10716
|
const mentions = await resolveMentions(executor, entries.map(([conversationId, preview]) => ({
|
|
9997
10717
|
tenantId: tenants.get(conversationId),
|
|
9998
10718
|
texts: [preview.text]
|
|
9999
10719
|
})));
|
|
10000
10720
|
return new Map(entries.map(([conversationId, preview], index) => [conversationId, withMentions(preview, mentions[index])]));
|
|
10001
10721
|
}
|
|
10002
|
-
// src/api/conversations/record.ts
|
|
10003
|
-
/** The columns of one Conversation record, for `selectConversationRecords`. */
|
|
10004
|
-
const conversationRecordColumns = {
|
|
10005
|
-
conversation: juniorConversations,
|
|
10006
|
-
location: juniorDestinations,
|
|
10007
|
-
identityDisplayName: juniorIdentities.displayName,
|
|
10008
|
-
identityEmail: juniorIdentities.email,
|
|
10009
|
-
identityHandle: juniorIdentities.handle,
|
|
10010
|
-
identityProvider: juniorIdentities.provider,
|
|
10011
|
-
identitySubjectId: juniorIdentities.providerSubjectId,
|
|
10012
|
-
identityTenantId: juniorIdentities.providerTenantId,
|
|
10013
|
-
userDisplayName: juniorUsers.displayName
|
|
10014
|
-
};
|
|
10015
|
-
/** Left-join conditions from a Conversation to its record tables. */
|
|
10016
|
-
const conversationRecordJoins = {
|
|
10017
|
-
location: eq(juniorDestinations.id, juniorConversations.destinationId),
|
|
10018
|
-
identity: eq(juniorIdentities.id, juniorConversations.actorIdentityId),
|
|
10019
|
-
user: eq(juniorUsers.id, juniorIdentities.userId)
|
|
10020
|
-
};
|
|
10021
|
-
/**
|
|
10022
|
-
* Select Conversation rows with their Location and Actor names. Callers add
|
|
10023
|
-
* the filter, order, and limit.
|
|
10024
|
-
*/
|
|
10025
|
-
function selectConversationRecords(db) {
|
|
10026
|
-
return db.select(conversationRecordColumns).from(juniorConversations).leftJoin(juniorDestinations, conversationRecordJoins.location).leftJoin(juniorIdentities, conversationRecordJoins.identity).leftJoin(juniorUsers, conversationRecordJoins.user);
|
|
10027
|
-
}
|
|
10028
|
-
/** Decode a conversation row with the linked user name and identity-scoped provider fields. */
|
|
10029
|
-
function conversationFromRecordRow(row) {
|
|
10030
|
-
const value = row.conversation;
|
|
10031
|
-
const legacySessionSource = value.sessionSource === null ? void 0 : parseSessionSource(value.sessionSource);
|
|
10032
|
-
if (value.sessionSource !== null && !legacySessionSource) throw new Error("Conversation legacy source_json is invalid");
|
|
10033
|
-
const actorFullName = row.userDisplayName?.trim() ? row.userDisplayName : row.identityDisplayName;
|
|
10034
|
-
const actor = row.identityProvider === "slack" ? {
|
|
10035
|
-
platform: "slack",
|
|
10036
|
-
...row.identityEmail ? { email: row.identityEmail } : void 0,
|
|
10037
|
-
...actorFullName ? { fullName: actorFullName } : void 0,
|
|
10038
|
-
...row.identitySubjectId ? { slackUserId: row.identitySubjectId } : void 0,
|
|
10039
|
-
...row.identityHandle ? { slackUserName: row.identityHandle } : void 0,
|
|
10040
|
-
...row.identityTenantId ? { teamId: row.identityTenantId } : void 0
|
|
10041
|
-
} : void 0;
|
|
10042
|
-
const location = locationFromRow(value.location, row.location, legacySessionSource);
|
|
10043
|
-
return {
|
|
10044
|
-
schemaVersion: 1,
|
|
10045
|
-
conversationId: value.conversationId,
|
|
10046
|
-
createdAtMs: value.createdAt.getTime(),
|
|
10047
|
-
kind: conversationKindFromRow(value),
|
|
10048
|
-
lastActivityAtMs: value.lastActivityAt.getTime(),
|
|
10049
|
-
updatedAtMs: value.updatedAt.getTime(),
|
|
10050
|
-
execution: {
|
|
10051
|
-
status: value.executionStatus,
|
|
10052
|
-
...value.runId ? { runId: value.runId } : void 0,
|
|
10053
|
-
...value.executionUpdatedAt ? { updatedAtMs: value.executionUpdatedAt.getTime() } : void 0
|
|
10054
|
-
},
|
|
10055
|
-
...value.parentConversationId ? { parentConversationId: value.parentConversationId } : void 0,
|
|
10056
|
-
...value.archivedAt ? { archivedAtMs: value.archivedAt.getTime() } : void 0,
|
|
10057
|
-
...actor ? { actor } : void 0,
|
|
10058
|
-
...location ? { location } : void 0,
|
|
10059
|
-
...value.channelName ? { channelName: value.channelName } : void 0,
|
|
10060
|
-
...value.source ? { source: value.source } : void 0,
|
|
10061
|
-
...value.title ? { title: value.title } : void 0,
|
|
10062
|
-
...value.transcriptPurgedAt ? { transcriptPurgedAtMs: value.transcriptPurgedAt.getTime() } : void 0,
|
|
10063
|
-
...value.stoppedAt ? { stoppedAtMs: value.stoppedAt.getTime() } : void 0,
|
|
10064
|
-
...value.deliveryPausedAt ? { deliveryPausedAtMs: value.deliveryPausedAt.getTime() } : void 0
|
|
10065
|
-
};
|
|
10066
|
-
}
|
|
10067
|
-
/** Decode one `selectConversationRecords` row into a Conversation record. */
|
|
10068
|
-
function conversationRecordFromRow(row) {
|
|
10069
|
-
return {
|
|
10070
|
-
conversation: conversationFromRecordRow(row),
|
|
10071
|
-
durationMs: row.conversation.durationMs,
|
|
10072
|
-
...row.location?.visibility === "public" ? { locationId: row.location.id } : void 0,
|
|
10073
|
-
usage: row.conversation.usage,
|
|
10074
|
-
rootConversationId: row.conversation.rootConversationId
|
|
10075
|
-
};
|
|
10076
|
-
}
|
|
10077
|
-
/** Read one normalized conversation record directly from its SQL row. */
|
|
10078
|
-
async function readConversationRecordFromSql(conversationId) {
|
|
10079
|
-
const row = (await selectConversationRecords(getDb()).where(eq(juniorConversations.conversationId, conversationId)).limit(1))[0];
|
|
10080
|
-
return row ? conversationRecordFromRow(row) : void 0;
|
|
10081
|
-
}
|
|
10082
10722
|
// src/api/conversations/event-list.ts
|
|
10083
10723
|
/** Read one bounded page of reporting events before, after, or around a boundary. */
|
|
10084
10724
|
async function readConversationEvents(conversationId, boundary, options = {}) {
|
|
@@ -10102,14 +10742,14 @@ async function readConversationEvents(conversationId, boundary, options = {}) {
|
|
|
10102
10742
|
...pageArgs,
|
|
10103
10743
|
beforeSeq: position.seq
|
|
10104
10744
|
});
|
|
10105
|
-
return
|
|
10745
|
+
return await conversationEventPageReport(getSqlExecutor(), {
|
|
10106
10746
|
conversationId,
|
|
10107
10747
|
eventHistory: conversationEventHistory({
|
|
10108
10748
|
canExposePayload,
|
|
10109
10749
|
...transcriptPurgedAtMs === void 0 ? void 0 : { transcriptPurgedAtMs }
|
|
10110
10750
|
}),
|
|
10111
10751
|
page
|
|
10112
|
-
})
|
|
10752
|
+
});
|
|
10113
10753
|
}
|
|
10114
10754
|
/** Resolve a page boundary to a direction and an event seq. */
|
|
10115
10755
|
async function boundaryPosition(conversationId, boundary) {
|
|
@@ -10295,7 +10935,7 @@ async function readDetailStateRow(conversationId, viewer) {
|
|
|
10295
10935
|
const forkIds = db.select({ conversationId: fork.conversationId }).from(fork).where(and(eq(fork.forkedFromConversationId, conversationId), isNull(fork.quickQuestionAt))).orderBy(asc(fork.createdAt)).limit(50);
|
|
10296
10936
|
const viewerParticipant = viewer ? and(eq(juniorConversationParticipants.userId, viewer.id), eq(juniorConversationParticipants.rootConversationId, rootConversationId)) : sql`false`;
|
|
10297
10937
|
const [row] = await db.select({
|
|
10298
|
-
...conversationRecordColumns,
|
|
10938
|
+
...conversationRecordColumns(),
|
|
10299
10939
|
agentTreeRootLabel: sql`case when ${juniorConversations.parentConversationId} is null then null else (${agentTreeRootLabel(db, rootConversationId)}) end`,
|
|
10300
10940
|
attachmentsVersion: sql`(${slackAttachmentsVersionQuery(db, conversationId)})`,
|
|
10301
10941
|
autoArchive: juniorConversationParticipants.autoArchive,
|
|
@@ -10698,6 +11338,63 @@ function objectPreviewImages(annotation) {
|
|
|
10698
11338
|
};
|
|
10699
11339
|
});
|
|
10700
11340
|
}
|
|
11341
|
+
// src/api/conversations/tree-state.ts
|
|
11342
|
+
/**
|
|
11343
|
+
* The most Conversations of one tree whose Watches a read checks, newest
|
|
11344
|
+
* activity first. A tree with more children than this can miss a Watch on
|
|
11345
|
+
* an old child.
|
|
11346
|
+
*/
|
|
11347
|
+
const WATCH_LOOKUP_LIMIT = 50;
|
|
11348
|
+
/**
|
|
11349
|
+
* SQL: the Conversation needs input from this User. An open action Review
|
|
11350
|
+
* item that it added is assigned to the User, to Everyone, or to no one, or
|
|
11351
|
+
* a Turn waits on the User to sign in.
|
|
11352
|
+
*/
|
|
11353
|
+
function needsUserSql(userId) {
|
|
11354
|
+
return sql`(exists (select 1 from ${juniorReviewItems} where ${and(reviewItemOwnedByConversation(juniorConversations.conversationId), reviewItemNeedsInput(), reviewItemForUser(userId))}) or ${awaitsAuthorizationFrom(juniorConversations.conversationId, userId)})`;
|
|
11355
|
+
}
|
|
11356
|
+
/**
|
|
11357
|
+
* Read the tree state of each Conversation for one viewer, over the
|
|
11358
|
+
* Conversation and every child Conversation at any depth. When more than
|
|
11359
|
+
* one applies:
|
|
11360
|
+
*
|
|
11361
|
+
* - `needs_you`: the tree's `needs_input` includes the viewer. A Review
|
|
11362
|
+
* item or a sign-in wait anywhere in the tree counts. Only the
|
|
11363
|
+
* Conversation's own wait on its starter counts, and only when the
|
|
11364
|
+
* viewer is the starter. Input that waits on another person is not
|
|
11365
|
+
* shown.
|
|
11366
|
+
* - `working`: a Turn is queued or running anywhere in the tree.
|
|
11367
|
+
* - `done`: anything else.
|
|
11368
|
+
*
|
|
11369
|
+
* `watching` is set when a Conversation in the tree that is not stopped has
|
|
11370
|
+
* an active Watch or a pending Timer. It is not part of the shared status.
|
|
11371
|
+
*
|
|
11372
|
+
* An archived child and its descendants count for nothing, since the feed
|
|
11373
|
+
* hides them. Archive takes a child's descendants with it. The
|
|
11374
|
+
* Conversation itself counts even when it is archived.
|
|
11375
|
+
*
|
|
11376
|
+
* Children use the visibility of their root, so a viewer who can see the
|
|
11377
|
+
* row may see its tree state. It shows no child's content.
|
|
11378
|
+
*
|
|
11379
|
+
* One SQL statement reads the trees, then two batched state reads check
|
|
11380
|
+
* Watches and Timers.
|
|
11381
|
+
*/
|
|
11382
|
+
async function readConversationTreeStates(db, conversationIds, viewerUserId) {
|
|
11383
|
+
if (conversationIds.length === 0) return /* @__PURE__ */ new Map();
|
|
11384
|
+
const scopeId = conversationSubtreeColumns.scopeConversationId;
|
|
11385
|
+
const needsViewer = viewerUserId ? sql`bool_or(${needsUserSql(viewerUserId)} or (${eq(juniorConversations.conversationId, scopeId)} and ${conversationWaitsOnUserSql(juniorConversations, viewerUserId)}))` : sql`false`;
|
|
11386
|
+
const rows = await db.select({
|
|
11387
|
+
conversationId: scopeId,
|
|
11388
|
+
needsViewer,
|
|
11389
|
+
working: sql`bool_or(${conversationIsActiveSql(juniorConversations)})`,
|
|
11390
|
+
watchable: sql`(array_agg(${juniorConversations.conversationId} order by ${desc(juniorConversations.lastActivityAt)}) filter (where ${isNull(juniorConversations.stoppedAt)}))[1:${WATCH_LOOKUP_LIMIT}]`
|
|
11391
|
+
}).from(juniorConversations).innerJoin(conversationSubtree(conversationIds), eq(conversationSubtreeColumns.conversationId, juniorConversations.conversationId)).where(or(eq(juniorConversations.conversationId, scopeId), isNull(juniorConversations.archivedAt))).groupBy(scopeId);
|
|
11392
|
+
const watched = await listConversationsWithWatches({ conversationIds: [...new Set(rows.flatMap((row) => row.watchable ?? []))] });
|
|
11393
|
+
return new Map(rows.map((row) => [row.conversationId, {
|
|
11394
|
+
treeState: row.needsViewer ? "needs_you" : row.working ? "working" : "done",
|
|
11395
|
+
watching: (row.watchable ?? []).some((id) => watched.has(id))
|
|
11396
|
+
}]));
|
|
11397
|
+
}
|
|
10701
11398
|
// src/api/conversations/detail.ts
|
|
10702
11399
|
/** Project stored metadata and a bounded event page into a signed history cursor. */
|
|
10703
11400
|
function projectConversationDetail(args) {
|
|
@@ -10718,6 +11415,7 @@ function projectConversationDetail(args) {
|
|
|
10718
11415
|
durationMs: args.durationMs,
|
|
10719
11416
|
firstHumanMessageText: args.firstHumanMessageText,
|
|
10720
11417
|
...args.locationId ? { locationId: args.locationId } : void 0,
|
|
11418
|
+
status: args.status,
|
|
10721
11419
|
...args.teamDomainByTeamId ? { teamDomainByTeamId: args.teamDomainByTeamId } : void 0,
|
|
10722
11420
|
usage: args.usage
|
|
10723
11421
|
}),
|
|
@@ -10785,7 +11483,7 @@ async function readConversationDetailFromSql(conversationId, options) {
|
|
|
10785
11483
|
limit: options.limit
|
|
10786
11484
|
});
|
|
10787
11485
|
};
|
|
10788
|
-
const [agentTree, annotations, automationTitleByConversation, auxiliaryCostsByConversation, briefVersion, firstHumanMessageTextByConversation, modelUsage, metricsByConversation, people, sourceTask, teamDomainByTeamId, page] = await Promise.all([
|
|
11486
|
+
const [agentTree, annotations, automationTitleByConversation, auxiliaryCostsByConversation, briefVersion, firstHumanMessageTextByConversation, modelUsage, metricsByConversation, people, sourceTask, teamDomainByTeamId, treeStateByConversation, page] = await Promise.all([
|
|
10789
11487
|
readConversationAgentTree({
|
|
10790
11488
|
conversationId,
|
|
10791
11489
|
...record.conversation.parentConversationId ? { parentConversationId: record.conversation.parentConversationId } : void 0
|
|
@@ -10809,6 +11507,7 @@ async function readConversationDetailFromSql(conversationId, options) {
|
|
|
10809
11507
|
...options.viewer ? { viewer: options.viewer } : void 0
|
|
10810
11508
|
}),
|
|
10811
11509
|
resolveSlackTeamDomains(record.conversation.location?.provider === "slack" ? [record.conversation.location.teamId] : []),
|
|
11510
|
+
readConversationTreeStates(getDb(), [conversationId], options.viewer?.id),
|
|
10812
11511
|
readPage()
|
|
10813
11512
|
]);
|
|
10814
11513
|
const firstSeq = page.events[0]?.seq;
|
|
@@ -10866,6 +11565,7 @@ async function readConversationDetailFromSql(conversationId, options) {
|
|
|
10866
11565
|
authors: people.authors,
|
|
10867
11566
|
participants: people.participants,
|
|
10868
11567
|
...sourceTask ? { sourceTask } : void 0,
|
|
11568
|
+
status: record.status,
|
|
10869
11569
|
teamDomainByTeamId,
|
|
10870
11570
|
...page.previousSeq === void 0 ? void 0 : { previousSeq: page.previousSeq },
|
|
10871
11571
|
...readPosition ? { readPosition } : void 0,
|
|
@@ -10880,6 +11580,7 @@ async function readConversationDetailFromSql(conversationId, options) {
|
|
|
10880
11580
|
return {
|
|
10881
11581
|
...report,
|
|
10882
11582
|
...state.forks,
|
|
11583
|
+
...treeStateByConversation.get(conversationId),
|
|
10883
11584
|
...agentTree ? { agentTree } : void 0,
|
|
10884
11585
|
...report.isParticipant && state.autoArchive !== void 0 ? { autoArchive: state.autoArchive } : void 0,
|
|
10885
11586
|
...report.isParticipant && state.subscribed !== void 0 ? { subscribed: state.subscribed } : void 0,
|
|
@@ -10894,18 +11595,13 @@ const DETAIL_LATEST_TURNS = 3;
|
|
|
10894
11595
|
* events hold the latest Turns, up to the default limit.
|
|
10895
11596
|
*/
|
|
10896
11597
|
async function readConversationDetail(conversationId, options = {}) {
|
|
10897
|
-
|
|
11598
|
+
return await readConversationDetailFromSql(conversationId, {
|
|
10898
11599
|
...options,
|
|
10899
11600
|
...options.limit === void 0 ? {
|
|
10900
11601
|
latestTurns: DETAIL_LATEST_TURNS,
|
|
10901
11602
|
limit: 150
|
|
10902
11603
|
} : { limit: options.limit }
|
|
10903
11604
|
});
|
|
10904
|
-
if (!report) return void 0;
|
|
10905
|
-
return startSpan({
|
|
10906
|
-
name: "Validate conversation detail",
|
|
10907
|
-
op: "function"
|
|
10908
|
-
}, () => conversationDetailReportSchema.parse(report));
|
|
10909
11605
|
}
|
|
10910
11606
|
// src/api/conversations/pin.ts
|
|
10911
11607
|
/**
|
|
@@ -11014,24 +11710,34 @@ function findThreadPlacement(threadId, tree, rootIds) {
|
|
|
11014
11710
|
}
|
|
11015
11711
|
}
|
|
11016
11712
|
/**
|
|
11017
|
-
* Read the
|
|
11018
|
-
*
|
|
11019
|
-
*
|
|
11020
|
-
*
|
|
11021
|
-
* access of its root.
|
|
11713
|
+
* Read the stored Threads of the listed roots for the feed, with their
|
|
11714
|
+
* read-time titles. It needs no access, so it can start with the other
|
|
11715
|
+
* feed reads. The caller passes only unarchived roots, so a root archive
|
|
11716
|
+
* hides its tree with no writes to the children.
|
|
11022
11717
|
*/
|
|
11023
|
-
async function
|
|
11024
|
-
if (
|
|
11025
|
-
const
|
|
11026
|
-
|
|
11027
|
-
const [rows, tree] = await Promise.all([selectConversationRecords(db).where(and(inArray(juniorConversations.rootConversationId, rootIdList), eq(juniorConversations.kind, "thread"), isNull(juniorConversations.archivedAt))).orderBy(desc(juniorConversations.lastActivityAt), asc(juniorConversations.conversationId)), readConversationTrees(db, rootIdList)]);
|
|
11028
|
-
if (rows.length === 0) return /* @__PURE__ */ new Map();
|
|
11718
|
+
async function readFeedThreadRecords(db, rootIds) {
|
|
11719
|
+
if (rootIds.length === 0) return void 0;
|
|
11720
|
+
const rows = await selectConversationRecords(db).where(and(inArray(juniorConversations.rootConversationId, rootIds), eq(juniorConversations.kind, "thread"), isNull(juniorConversations.archivedAt))).orderBy(desc(juniorConversations.lastActivityAt), asc(juniorConversations.conversationId));
|
|
11721
|
+
if (rows.length === 0) return void 0;
|
|
11029
11722
|
const threads = rows.map((row) => ({
|
|
11030
11723
|
conversation: conversationFromRecordRow(row),
|
|
11031
11724
|
row
|
|
11032
11725
|
}));
|
|
11033
|
-
|
|
11034
|
-
|
|
11726
|
+
return {
|
|
11727
|
+
firstHumanMessageTexts: await readFirstHumanMessageTexts(db, threads.map(({ conversation }) => conversation)),
|
|
11728
|
+
rootIds: new Set(rootIds),
|
|
11729
|
+
threads
|
|
11730
|
+
};
|
|
11731
|
+
}
|
|
11732
|
+
/**
|
|
11733
|
+
* Nest the shown Threads of `readFeedThreadRecords` under their nearest shown
|
|
11734
|
+
* ancestor. A Thread shows when it and every ancestor have no
|
|
11735
|
+
* `archived_at`. A Thread uses the access of its root. `tree` holds the
|
|
11736
|
+
* trees of at least the listed roots.
|
|
11737
|
+
*/
|
|
11738
|
+
function nestFeedThreads(records, tree, accessByRoot) {
|
|
11739
|
+
if (!records) return /* @__PURE__ */ new Map();
|
|
11740
|
+
const { firstHumanMessageTexts, rootIds, threads } = records;
|
|
11035
11741
|
const childrenByParent = /* @__PURE__ */ new Map();
|
|
11036
11742
|
for (const { conversation, row } of threads) {
|
|
11037
11743
|
const parentId = findThreadPlacement(conversation.conversationId, tree, rootIds);
|
|
@@ -11042,6 +11748,7 @@ async function readFeedThreads(db, roots) {
|
|
|
11042
11748
|
conversation,
|
|
11043
11749
|
durationMs: row.conversation.durationMs,
|
|
11044
11750
|
firstHumanMessageText: firstHumanMessageTexts.get(conversation.conversationId),
|
|
11751
|
+
status: row.status,
|
|
11045
11752
|
...row.conversation.usage ? { usage: row.conversation.usage } : void 0
|
|
11046
11753
|
});
|
|
11047
11754
|
const siblings = childrenByParent.get(parentId) ?? [];
|
|
@@ -11055,9 +11762,9 @@ async function readFeedThreads(db, roots) {
|
|
|
11055
11762
|
threads: nest(children)
|
|
11056
11763
|
} : item;
|
|
11057
11764
|
});
|
|
11058
|
-
return new Map(
|
|
11059
|
-
const children = childrenByParent.get(
|
|
11060
|
-
return children ? [[
|
|
11765
|
+
return new Map([...rootIds].flatMap((rootId) => {
|
|
11766
|
+
const children = childrenByParent.get(rootId);
|
|
11767
|
+
return children ? [[rootId, nest(children)]] : [];
|
|
11061
11768
|
}));
|
|
11062
11769
|
}
|
|
11063
11770
|
// src/api/conversations/priority.ts
|
|
@@ -11096,7 +11803,7 @@ function latestMessage(db, role) {
|
|
|
11096
11803
|
const text = sql`${juniorConversationEvents.payload}->>'text'`;
|
|
11097
11804
|
return db.select({
|
|
11098
11805
|
createdAt: juniorConversationEvents.createdAt,
|
|
11099
|
-
text: text
|
|
11806
|
+
text: sql`left(${text}, ${401})`.as(`${role}_text`)
|
|
11100
11807
|
}).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, juniorConversations.conversationId), eq(juniorConversationEvents.type, "message"), sql`${juniorConversationEvents.payload}->>'role' = ${role}`, isNotNull(sql`nullif(btrim(${text}), '')`))).orderBy(desc(juniorConversationEvents.createdAt), desc(juniorConversationEvents.seq)).limit(1).as(`latest_${role}`);
|
|
11101
11808
|
}
|
|
11102
11809
|
/**
|
|
@@ -11125,11 +11832,11 @@ async function readConversationActivityPreviews(db, conversationIds) {
|
|
|
11125
11832
|
const preview = row.assistantAt && row.assistantText !== null ? {
|
|
11126
11833
|
createdAt: row.assistantAt.toISOString(),
|
|
11127
11834
|
role: "assistant",
|
|
11128
|
-
text: row.assistantText
|
|
11835
|
+
text: activityPreviewText(row.assistantText)
|
|
11129
11836
|
} : row.userAt && row.userText !== null ? {
|
|
11130
11837
|
createdAt: row.userAt.toISOString(),
|
|
11131
11838
|
role: "user",
|
|
11132
|
-
text: row.userText
|
|
11839
|
+
text: activityPreviewText(row.userText)
|
|
11133
11840
|
} : void 0;
|
|
11134
11841
|
if (preview) previews.set(row.conversationId, preview);
|
|
11135
11842
|
}
|
|
@@ -11224,6 +11931,28 @@ function feedMediaSql(db) {
|
|
|
11224
11931
|
const files = db.select({ files: sql`jsonb_agg(jsonb_build_object('contentType', ${recentFiles.contentType}, 'filename', ${recentFiles.filename}, 'id', ${recentFiles.id}) order by ${recentFiles.createdAt} desc, ${recentFiles.id} desc)` }).from(recentFiles);
|
|
11225
11932
|
return sql`(${files})`;
|
|
11226
11933
|
}
|
|
11934
|
+
// src/api/conversations/feed-answer.ts
|
|
11935
|
+
/**
|
|
11936
|
+
* A feed row column with the viewer's newest answered Review item of its
|
|
11937
|
+
* Conversation, or null. It is a scalar subquery on the row read, so the
|
|
11938
|
+
* answer costs no round trip of its own, however many items the viewer
|
|
11939
|
+
* closed since.
|
|
11940
|
+
*/
|
|
11941
|
+
function feedViewerAnswerSql(db, userId) {
|
|
11942
|
+
const latest = db.select({ answer: sql`jsonb_build_object('answer', ${juniorReviewItems.answer}, 'closedAt', ${juniorReviewItems.closedAt}, 'request', ${juniorReviewItems.request})` }).from(juniorReviewItems).where(and(reviewItemOwnedByConversation(juniorConversations.conversationId), eq(juniorReviewItems.closedByUserId, userId), isNotNull(juniorReviewItems.answer), isNotNull(juniorReviewItems.request))).orderBy(desc(juniorReviewItems.closedAt), desc(juniorReviewItems.id)).limit(1);
|
|
11943
|
+
return sql`(${latest})`;
|
|
11944
|
+
}
|
|
11945
|
+
/**
|
|
11946
|
+
* Keep only what a row says about the answer: when it closed and the
|
|
11947
|
+
* options that the viewer picked. Text answers have no choices.
|
|
11948
|
+
*/
|
|
11949
|
+
function feedViewerAnswer(stored) {
|
|
11950
|
+
if (!stored) return void 0;
|
|
11951
|
+
return {
|
|
11952
|
+
choices: answeredChoices(stored.request, stored.answer),
|
|
11953
|
+
closedAt: new Date(stored.closedAt).toISOString()
|
|
11954
|
+
};
|
|
11955
|
+
}
|
|
11227
11956
|
// src/api/page-cursor.ts
|
|
11228
11957
|
/**
|
|
11229
11958
|
* Encode the position after the last row of a page as an opaque `cursor`
|
|
@@ -11283,17 +12012,18 @@ function conversationCodeRepositoryFilter(repositoryId, viewerUserId) {
|
|
|
11283
12012
|
FROM ${juniorCodeChanges}
|
|
11284
12013
|
WHERE ${juniorCodeChanges.repositoryId} = ${repositoryId}
|
|
11285
12014
|
)
|
|
11286
|
-
)`,
|
|
12015
|
+
)`, rootVisibleToViewer(viewerUserId));
|
|
11287
12016
|
}
|
|
11288
|
-
async function conversationRows(db, { codeRepository, conversationIds, cursor, filter, include = [], includePrivateBriefs = false, limit, pinnedForUserId, query, status }) {
|
|
12017
|
+
async function conversationRows(db, { codeRepository, conversationIds, cursor, filter, include = [], includePrivateBriefs = false, limit, pinnedForUserId, query, status, waitingForUserId }) {
|
|
11289
12018
|
const rows = db.select({
|
|
11290
|
-
...conversationRecordColumns,
|
|
12019
|
+
...conversationRecordColumns(),
|
|
11291
12020
|
activityCursor: sql`to_char(${juniorConversations.lastActivityAt} at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`,
|
|
11292
12021
|
lastMessageAt: sql`coalesce(${juniorConversations.lastMessageAt}, ${lastMessageAtSql(db)})`.mapWith(juniorConversations.lastMessageAt),
|
|
11293
12022
|
awaitingAuthorization: treeAwaitsAuthorization(juniorConversations.conversationId),
|
|
11294
12023
|
links: include.includes("links") ? feedLinksSql(db) : sql`null`,
|
|
11295
|
-
media: include.includes("media") ? feedMediaSql(db) : sql`null
|
|
11296
|
-
|
|
12024
|
+
media: include.includes("media") ? feedMediaSql(db) : sql`null`,
|
|
12025
|
+
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`exists (
|
|
11297
12027
|
select 1
|
|
11298
12028
|
from ${juniorConversationBriefs}
|
|
11299
12029
|
where ${juniorConversationBriefs.conversationId} = ${juniorConversations.conversationId}
|
|
@@ -11309,24 +12039,6 @@ async function conversationRows(db, { codeRepository, conversationIds, cursor, f
|
|
|
11309
12039
|
return limit === void 0 ? rows : rows.limit(limit);
|
|
11310
12040
|
}
|
|
11311
12041
|
/**
|
|
11312
|
-
* Read the viewer's active conversations that wait on them but fall outside
|
|
11313
|
-
* the first page. Needs you shows every conversation that waits on the
|
|
11314
|
-
* viewer, so an old one must come back to the feed.
|
|
11315
|
-
*/
|
|
11316
|
-
async function waitingRowsOutsidePage(db, filter, page, include) {
|
|
11317
|
-
const loaded = new Set(page.map((row) => row.conversation.conversationId));
|
|
11318
|
-
const missing = (await listWaitingConversations(db, filter.userId)).map((waiting) => waiting.conversationId).filter((conversationId) => !loaded.has(conversationId));
|
|
11319
|
-
if (missing.length === 0) return [];
|
|
11320
|
-
return await conversationRows(db, {
|
|
11321
|
-
conversationIds: missing,
|
|
11322
|
-
filter,
|
|
11323
|
-
include,
|
|
11324
|
-
includePrivateBriefs: true,
|
|
11325
|
-
limit: missing.length,
|
|
11326
|
-
status: "active"
|
|
11327
|
-
});
|
|
11328
|
-
}
|
|
11329
|
-
/**
|
|
11330
12042
|
* Feed rows show last activity only as an age in whole minutes. A running
|
|
11331
12043
|
* row shows its running state in place of the age, so it shows no activity.
|
|
11332
12044
|
* Every status but `idle` and `failed` shows as running, as in
|
|
@@ -11347,9 +12059,14 @@ const feedAnnotated = alias(juniorConversations, "feed_annotated");
|
|
|
11347
12059
|
* for each feed-row input as `name:token`, separated by spaces, so the
|
|
11348
12060
|
* dashboard can record which inputs moved it.
|
|
11349
12061
|
*
|
|
11350
|
-
* The token holds only what a feed row shows, so a Task
|
|
11351
|
-
*
|
|
11352
|
-
*
|
|
12062
|
+
* The token holds only what a feed row shows, so a Task moves it only when
|
|
12063
|
+
* the tree state moves. Watches and Timers live outside SQL. A Turn makes
|
|
12064
|
+
* or cancels one, and the end of that Turn moves the status or the tree's
|
|
12065
|
+
* work, so a read after it sees the change. A Timer that fires starts a
|
|
12066
|
+
* Turn. A stop anywhere in the tree moves it too, since a stopped
|
|
12067
|
+
* Conversation's Watches start no Turn. A Watch that expires on its own
|
|
12068
|
+
* moves nothing, so its row shows `watching` until the feed reads again. Every Event of a live Turn moves `last_activity_at`, but
|
|
12069
|
+
* a running row shows its running state in place of the age, so the token
|
|
11353
12070
|
* holds no activity for it. Other rows show an age in whole minutes, so the
|
|
11354
12071
|
* token holds its minute. The end of the Turn moves the status.
|
|
11355
12072
|
* The rows are in feed order, so a move that reorders them moves the token.
|
|
@@ -11362,23 +12079,26 @@ function conversationFeedVersionQuery(db, userId) {
|
|
|
11362
12079
|
const conversationId = juniorConversations.conversationId;
|
|
11363
12080
|
const tree = db.select({ version: sql`concat_ws(':',
|
|
11364
12081
|
count(*) filter (where ${feedTree.archivedAt} is not null),
|
|
12082
|
+
count(*) filter (where ${feedTree.stoppedAt} is not null),
|
|
12083
|
+
coalesce(bool_or(${conversationIsActiveSql(feedTree)}) filter (where ${ne(feedTree.conversationId, conversationId)}), false),
|
|
12084
|
+
bool_or(exists (select 1 from ${juniorReviewItems} where ${and(reviewItemOwnedByConversation(feedTree.conversationId), reviewItemNeedsInput(), reviewItemForUser(userId))}) or ${awaitsAuthorizationFrom(feedTree.conversationId, userId)}),
|
|
11365
12085
|
string_agg(concat_ws('/',
|
|
11366
12086
|
${feedTree.conversationId}, ${feedTree.title},
|
|
11367
|
-
${feedTree
|
|
12087
|
+
${conversationStatusSql(feedTree)},
|
|
11368
12088
|
${shownActivityMinute(feedTree.executionStatus, feedTree.lastActivityAt)}
|
|
11369
12089
|
), ',' order by ${feedTree.conversationId}) filter (
|
|
11370
12090
|
where ${feedTree.kind} = 'thread' and ${feedTree.archivedAt} is null
|
|
11371
12091
|
)
|
|
11372
|
-
)` }).from(feedTree).where(eq(feedTree.rootConversationId, conversationId));
|
|
12092
|
+
)` }).from(feedTree).where(or(eq(feedTree.conversationId, conversationId), eq(feedTree.rootConversationId, conversationId)));
|
|
11373
12093
|
const annotations = db.select({ version: sql`concat_ws(':', count(*), max(${juniorConversationAnnotations.updatedAt}))` }).from(juniorConversationAnnotations).innerJoin(feedAnnotated, eq(feedAnnotated.conversationId, juniorConversationAnnotations.conversationId)).where(eq(feedAnnotated.rootConversationId, conversationId));
|
|
11374
12094
|
const page = db.select({
|
|
11375
12095
|
conversationId,
|
|
11376
12096
|
channelName: juniorConversations.channelName,
|
|
11377
|
-
executionStatus: juniorConversations.executionStatus,
|
|
11378
12097
|
lastActivityAt: juniorConversations.lastActivityAt,
|
|
11379
12098
|
pinnedAt: pin.pinnedAt,
|
|
11380
12099
|
pinPosition: pin.pinPosition,
|
|
11381
|
-
|
|
12100
|
+
status: conversationStatusSql(juniorConversations).as("status"),
|
|
12101
|
+
waitsOnViewer: conversationWaitsOnUserSql(juniorConversations, userId).as("waits_on_viewer"),
|
|
11382
12102
|
title: juniorConversations.title,
|
|
11383
12103
|
activity: shownActivityMinute(juniorConversations.executionStatus, juniorConversations.lastActivityAt).as("activity"),
|
|
11384
12104
|
assistantSeq: sql`(${latestMessageSeqQuery(db, "assistant", conversationId)})`.as("assistant_seq"),
|
|
@@ -11394,7 +12114,7 @@ function conversationFeedVersionQuery(db, userId) {
|
|
|
11394
12114
|
order: sql`string_agg(${page.conversationId}, ',' order by ${page.pinnedAt} is not null desc, ${page.lastActivityAt} desc, ${page.conversationId})`,
|
|
11395
12115
|
pin: byRow(page.pinnedAt, page.pinPosition),
|
|
11396
12116
|
title: byRow(page.title, page.channelName),
|
|
11397
|
-
status: byRow(page.
|
|
12117
|
+
status: byRow(page.status, page.waitsOnViewer),
|
|
11398
12118
|
activity: byRow(page.activity),
|
|
11399
12119
|
messages: byRow(page.assistantSeq, page.userSeq),
|
|
11400
12120
|
threads: byRow(page.threads),
|
|
@@ -11447,50 +12167,75 @@ async function readConversationFeedFromSql(options = {}) {
|
|
|
11447
12167
|
query,
|
|
11448
12168
|
status
|
|
11449
12169
|
};
|
|
11450
|
-
const
|
|
11451
|
-
|
|
11452
|
-
|
|
11453
|
-
|
|
11454
|
-
|
|
11455
|
-
|
|
11456
|
-
|
|
11457
|
-
|
|
11458
|
-
|
|
11459
|
-
|
|
11460
|
-
|
|
11461
|
-
|
|
11462
|
-
|
|
11463
|
-
|
|
11464
|
-
|
|
12170
|
+
const firstPage = pinsFirst && !cursor;
|
|
12171
|
+
const [pinnedRows, pageRows, waitingRows] = await Promise.all([
|
|
12172
|
+
firstPage ? conversationRows(db, {
|
|
12173
|
+
...feedQuery,
|
|
12174
|
+
pinnedForUserId: {
|
|
12175
|
+
pinned: true,
|
|
12176
|
+
userId: filter.userId
|
|
12177
|
+
}
|
|
12178
|
+
}) : [],
|
|
12179
|
+
conversationRows(db, {
|
|
12180
|
+
...feedQuery,
|
|
12181
|
+
...cursor ? { cursor } : void 0,
|
|
12182
|
+
limit: limit + 1,
|
|
12183
|
+
...pinsFirst ? { pinnedForUserId: {
|
|
12184
|
+
pinned: false,
|
|
12185
|
+
userId: filter.userId
|
|
12186
|
+
} } : void 0
|
|
12187
|
+
}),
|
|
12188
|
+
firstPage ? conversationRows(db, {
|
|
12189
|
+
filter,
|
|
12190
|
+
include,
|
|
12191
|
+
includePrivateBriefs: true,
|
|
12192
|
+
status: "active",
|
|
12193
|
+
waitingForUserId: filter.userId
|
|
12194
|
+
}) : []
|
|
12195
|
+
]);
|
|
11465
12196
|
const page = pageRows.slice(0, limit);
|
|
11466
12197
|
const lastRow = pageRows.length > limit ? page.at(-1) : void 0;
|
|
11467
12198
|
const rows = [...pinnedRows, ...page];
|
|
11468
|
-
if (
|
|
12199
|
+
if (firstPage) {
|
|
12200
|
+
const loaded = new Set(rows.map((row) => row.conversation.conversationId));
|
|
12201
|
+
const outsidePage = waitingRows.filter((row) => !loaded.has(row.conversation.conversationId));
|
|
12202
|
+
options.onWaitingRows?.(outsidePage.length);
|
|
12203
|
+
rows.push(...outsidePage);
|
|
12204
|
+
}
|
|
11469
12205
|
const conversations = rows.map((row) => conversationFromRecordRow(row));
|
|
11470
12206
|
const conversationIds = conversations.map((conversation) => conversation.conversationId);
|
|
11471
|
-
const
|
|
11472
|
-
|
|
11473
|
-
|
|
12207
|
+
const conversationTrees = readConversationTrees(db, conversationIds);
|
|
12208
|
+
const [accessRows, tree, participantsByRoot, annotationsByConversation, auxiliaryCostsByRoot, metricsByRoot, participantsByConversation, teamDomainByTeamId, { work: conversationWork, lastUserMessageAt: lastUserMessageAtByConversation }, activityPreviewByConversation, briefByConversation, automationTitleByConversation, firstHumanMessageTextByConversation, treeStateByConversation, threadRecords] = await Promise.all([
|
|
12209
|
+
readConversationAccessRows(db, conversationIds),
|
|
12210
|
+
conversationTrees,
|
|
12211
|
+
readMemberParticipants(db, conversationIds, options.viewer ? { userId: options.viewer.id } : filter ? feedMember(filter) : void 0),
|
|
11474
12212
|
listConversationAnnotationsById(db, conversationIds),
|
|
11475
12213
|
readConversationAuxiliaryCostsFromSql(db, conversationIds),
|
|
11476
12214
|
readConversationTreeMetricsFromSql(db, conversationIds),
|
|
11477
12215
|
readConversationParticipants(db, conversationIds),
|
|
11478
12216
|
resolveSlackTeamDomains(conversations.flatMap((conversation) => conversation.location?.provider === "slack" ? [conversation.location.teamId] : [])),
|
|
11479
|
-
listConversationWork(conversationIds).then(async (work) => ({
|
|
12217
|
+
conversationTrees.then((tree) => listConversationWork(conversationIds, tree)).then(async (work) => ({
|
|
11480
12218
|
work,
|
|
11481
12219
|
lastUserMessageAt: await readLastUserMessageAtByConversation(db, work.assignedIds.filter((conversationId) => work.finishedAtById[conversationId]))
|
|
11482
12220
|
})),
|
|
11483
12221
|
readConversationActivityPreviews(db, conversationIds),
|
|
11484
12222
|
readConversationFeedBriefs(db, conversationIds),
|
|
11485
12223
|
readAutomationTitlesByConversationId(conversations),
|
|
11486
|
-
readFirstHumanMessageTexts(db, conversations)
|
|
12224
|
+
readFirstHumanMessageTexts(db, conversations),
|
|
12225
|
+
readConversationTreeStates(db, conversationIds, options.viewer?.id),
|
|
12226
|
+
readFeedThreadRecords(db, conversations.filter((conversation) => conversation.archivedAtMs === void 0).map(({ conversationId }) => conversationId))
|
|
11487
12227
|
]);
|
|
11488
|
-
const
|
|
12228
|
+
const accessByConversation = conversationAccessFromRows(accessRows, options.viewer ? new Set(participantsByRoot.keys()) : /* @__PURE__ */ new Set());
|
|
12229
|
+
const tenantByConversation = new Map(rows.flatMap((row) => {
|
|
12230
|
+
const tenantId = conversationSlackTenantId({
|
|
12231
|
+
providerTenantId: row.location?.providerTenantId,
|
|
12232
|
+
sessionSource: row.conversation.sessionSource
|
|
12233
|
+
});
|
|
12234
|
+
return tenantId ? [[row.conversation.conversationId, tenantId]] : [];
|
|
12235
|
+
}));
|
|
11489
12236
|
const visibleAnnotationsByConversation = new Map(conversationIds.map((conversationId) => [conversationId, accessByConversation.get(conversationId)?.canViewPrivateContent ? annotationsByConversation.get(conversationId) ?? [] : []]));
|
|
11490
|
-
const [
|
|
11491
|
-
|
|
11492
|
-
conversationId
|
|
11493
|
-
})))]);
|
|
12237
|
+
const [visibleActivityPreviews, sidebarAnnotationsByConversation] = await Promise.all([attachActivityPreviewMentions(getSqlExecutor(), new Map([...activityPreviewByConversation].filter(([conversationId]) => accessByConversation.get(conversationId)?.canViewPrivateContent)), tenantByConversation), listConversationSidebarAnnotations(conversationIds, visibleAnnotationsByConversation)]);
|
|
12238
|
+
const threadsByRoot = nestFeedThreads(threadRecords, tree, accessByConversation);
|
|
11494
12239
|
const assignedWork = new Set(conversationWork.assignedIds);
|
|
11495
12240
|
const unfinishedWork = new Set(conversationWork.unfinishedIds);
|
|
11496
12241
|
return {
|
|
@@ -11501,7 +12246,8 @@ async function readConversationFeedFromSql(options = {}) {
|
|
|
11501
12246
|
const auxiliaryCosts = auxiliaryCostsByRoot.get(conversation.conversationId);
|
|
11502
12247
|
const childAgentTotals = childAgentTotalsReport(metrics, auxiliaryCosts);
|
|
11503
12248
|
const summary = conversationSummaryFromStoredConversation({
|
|
11504
|
-
...
|
|
12249
|
+
...filter ? participantsByRoot.get(conversation.conversationId) : void 0,
|
|
12250
|
+
status: row.status,
|
|
11505
12251
|
automationTitle: automationTitleByConversation.get(conversation.conversationId),
|
|
11506
12252
|
conversation,
|
|
11507
12253
|
access,
|
|
@@ -11526,15 +12272,19 @@ async function readConversationFeedFromSql(options = {}) {
|
|
|
11526
12272
|
const media = access?.canViewPrivateContent ? row.media : null;
|
|
11527
12273
|
const links = access?.canViewPrivateContent && row.links ? pickFeedLinks(conversation.conversationId, row.links, annotationUrls(annotations)) : [];
|
|
11528
12274
|
const lastMessageAt = row.lastMessageAt?.toISOString();
|
|
12275
|
+
const treeRead = treeStateByConversation.get(conversation.conversationId);
|
|
12276
|
+
const viewerAnswer = access?.canViewPrivateContent ? feedViewerAnswer(row.viewerAnswer) : void 0;
|
|
11529
12277
|
return {
|
|
11530
12278
|
...summary,
|
|
11531
12279
|
...work,
|
|
12280
|
+
...treeRead,
|
|
11532
12281
|
...row.awaitingAuthorization ? { awaitingAuthorization: true } : void 0,
|
|
11533
12282
|
...lastMessageAt ? { lastMessageAt } : void 0,
|
|
11534
12283
|
...threads ? { threads } : void 0,
|
|
11535
12284
|
...participants && participants.length > 0 ? { participants } : void 0,
|
|
11536
12285
|
...activityPreview ? { activityPreview } : void 0,
|
|
11537
12286
|
...brief ? { brief } : void 0,
|
|
12287
|
+
...viewerAnswer ? { viewerAnswer } : void 0,
|
|
11538
12288
|
...media?.length ? { media } : void 0,
|
|
11539
12289
|
...links.length > 0 ? { links } : void 0,
|
|
11540
12290
|
...annotations.length > 0 ? { annotations } : void 0,
|
|
@@ -11563,7 +12313,7 @@ async function readConversationFeedFromSql(options = {}) {
|
|
|
11563
12313
|
* guarantee, so they are not an authorization boundary.
|
|
11564
12314
|
*/
|
|
11565
12315
|
async function readConversationFeed(options = {}) {
|
|
11566
|
-
return
|
|
12316
|
+
return readConversationFeedFromSql(options);
|
|
11567
12317
|
}
|
|
11568
12318
|
// src/api/conversations/steer-pending-messages.ts
|
|
11569
12319
|
/**
|
|
@@ -11637,4 +12387,4 @@ function viewerWebMessages(messages, viewer) {
|
|
|
11637
12387
|
}] : [];
|
|
11638
12388
|
});
|
|
11639
12389
|
}
|
|
11640
|
-
export {
|
|
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 };
|