@sentry/junior 0.285.0 → 0.286.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-DN5AB4VU.js → adapter-JQZaJ-B_.js} +1 -1
- package/dist/{admin-DOITMKnn.js → admin-Dm2bimJ-.js} +1 -1
- package/dist/{agent-runner-BsWhHe4N.js → agent-runner-DGCwOEyL.js} +1567 -1048
- package/dist/api/schema.d.ts +1 -1
- package/dist/api/schema.js +5 -5
- package/dist/api.d.ts +1 -1
- package/dist/api.js +70 -92
- package/dist/{app-DyMs9330.d.ts → app-BKq0JzWx.d.ts} +2 -3
- package/dist/app.d.ts +1 -1
- package/dist/app.js +37 -40
- package/dist/{assistant-reply-9Jip5bsr.js → assistant-reply-CAPafcUY.js} +1 -1
- package/dist/{automation-Mk8aaHzy.js → automation-B-jJN_gM.js} +1 -1
- package/dist/{background-compaction-queue-DXkLsWoH.js → background-compaction-queue-Btu2oab_.js} +137 -3
- package/dist/{briefs-Cl8-nK9B.js → briefs-UMeYehUe.js} +4 -4
- package/dist/{catalog-runtime-Bte6jRB2.js → catalog-runtime-Bym8GVdh.js} +1 -1
- package/dist/cli/chat.js +14 -14
- package/dist/cli/check.js +3 -3
- package/dist/cli/main.js +3 -3
- package/dist/cli/plugins.js +4 -4
- package/dist/cli/snapshot-create.js +5 -6
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +3 -3
- package/dist/{client-DDbBucBw.js → client-B0aAs7wC.js} +2 -2
- package/dist/{config-DqFnykQT.js → config-B9f9Lqo5.js} +1 -1
- package/dist/{connections-DA4LT9LL.js → connections-CQ7p0aNJ.js} +16 -50
- package/dist/{conversation-D8kVoCrP.js → conversation-BusI2uzj.js} +15 -6
- package/dist/{conversation-pending-messages-BvROq1bq.js → conversation-pending-messages-DwehU0Fd.js} +1 -1
- package/dist/{conversation-privacy-D0j_h70R.js → conversation-privacy-Cd_nZZBM.js} +1 -1
- package/dist/{credential-sync-hcsYatw-.js → credential-sync-DmiJi_At.js} +13 -13
- package/dist/{db-BhHZSuFw.d.ts → db-C5zi4ecs.d.ts} +4 -4
- package/dist/{executor-BLEMIgIZ.js → executor-Dipi2Ixl.js} +11 -17
- package/dist/instrumentation.js +2 -2
- package/dist/{logging-BfORLKoq.js → logging-CMFhLLj4.js} +1 -1
- package/dist/{media-Bu9C6lz0.js → media-B-BpXo41.js} +14 -2
- package/dist/{message-DqjuKzUx.js → message-D1xLljUF.js} +9 -9
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +2 -3
- package/dist/{oauth-callback-server-CFSRzu1n.js → oauth-callback-server-DCAFIUQr.js} +2 -2
- package/dist/{projection-DliWYrnT.js → projection-CoeMNxJ4.js} +286 -212
- package/dist/{prompt-BvIUzY4y.js → prompt-C9OQEfan.js} +1 -1
- package/dist/{registry-rC7MCxu8.js → registry-u-sFYtx_.js} +1 -1
- package/dist/{resolve-Biu8Qw3u.js → resolve-DYqgL3Eo.js} +3 -3
- package/dist/{result-DxJMCX47.js → result-CescSwAw.js} +8 -8
- package/dist/{runner-BQJSFLKg.js → runner-Cr67a8TB.js} +16 -12
- package/dist/{sandbox-egress-signals-6aMxJSDn.js → sandbox-egress-signals-DLOazy5W.js} +1 -1
- package/dist/{schema-BasXTvi2.js → schema-BUSi3sgv.js} +5 -5
- package/dist/{schema-BUviRAs8.d.ts → schema-Ih60j59-.d.ts} +44 -7
- package/dist/{service-account-BI5Wgx22.js → service-account-CGEqz9wG.js} +3 -3
- package/dist/{service-account-CAE-_1dR.js → service-account-CsKxktLk.js} +3 -3
- package/dist/{session-stop-CA-jOJ84.js → session-stop-CGz5DByb.js} +22 -20
- package/dist/{skills-B22duVJU.js → skills-COCqf61f.js} +2 -2
- package/dist/{spawn-BB2_4VYn.js → spawn-C8F_iXWO.js} +13 -2
- package/dist/{stop-DioIcEAu.js → stop-GyFZkHuQ.js} +242 -952
- package/dist/{store-Dn4W7qgH.js → store-D0-8plWp.js} +3 -3
- package/dist/{turn-session-routing-CGMKrYOj.js → task-runner-xPuQmEot.js} +1439 -993
- package/dist/{store-B26LV6UP.js → turn-failure-response-BOviBdT-.js} +331 -5
- package/dist/{validation-TzhfQABF.js → validation-DZDKorGz.js} +1 -1
- package/dist/{version-DSk8CFvA.js → version-BTIz7fGi.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{viewer-1Ea81s0b.js → viewer-CH-ASQzh.js} +39 -36
- package/dist/{work-ybG4_q5C.js → work-C75_IM5e.js} +92 -87
- package/dist/{worker-ccSyZRNz.js → worker-Dl47I729.js} +6 -6
- package/migrations/0086_shared_archive.sql +31 -0
- package/migrations/0087_child_location.sql +64 -0
- package/migrations/meta/0086_snapshot.json +4366 -0
- package/migrations/meta/0087_snapshot.json +4366 -0
- package/migrations/meta/_journal.json +14 -0
- package/package.json +5 -4
- package/dist/task-queue-Bt0IoR2i.js +0 -139
- package/dist/task-runner-D8lddjzp.js +0 -290
- package/dist/thread-state-CrFk3K_7.js +0 -173
- package/dist/turn-failure-response-DaJ04qVj.js +0 -224
- package/dist/turn-lifecycle-C2mXS7AZ.js +0 -58
|
@@ -1,36 +1,32 @@
|
|
|
1
|
-
import { h as startSpan
|
|
2
|
-
import { $ as
|
|
3
|
-
import { a as completeText, c as resolveGatewayModel, m as escapeXml, r as completeDecision, x as isProviderRetryError } from "./client-
|
|
4
|
-
import { c as getSlackClientSecret, i as getChatConfig, l as getSlackSigningSecret, n as botConfig, o as getSlackBotToken, s as getSlackClientId, v as normalizeSlackEmojiName } from "./config-
|
|
5
|
-
import { E as withSpan, G as toOptionalNumber, K as toOptionalString, S as setTags, T as withLogContext, W as isRecord, 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-
|
|
6
|
-
import { t as JUNIOR_VERSION } from "./version-
|
|
1
|
+
import { h as startSpan } from "./sentry-BRTJqumy.js";
|
|
2
|
+
import { $ as pauseLostWorkerTurn, $a as createConversationAccessReader, A as isHumanConversationMessage, Ao as lookupSlackUser, Ar as reviewItemNeedsSomeone, At as moveIdleConversationDestination, Bi as formatSlackLink, C as resolveConversationTitle, Cr as canActOnReviewItem, D as buildConversationContext, Do as listConversationAnnotationsById, En as getThreadStopDecision, Eo as listConversationAnnotations, Er as isOnlyAssignee, F as trimConversationMessages, Gi as addReactionToMessage, Gt as buildTurnErrorResponse, Hi as normalizeSlackStatusText, Hr as cancelSubscriptions, I as turnHasReply, In as createUserTokenStore, Io as piMessageFromHistoryItem, Ki as deleteSlackMessage, L as upsertConversationMessage, M as markConversationMessage, Mo as createPluginCache, N as normalizeConversationText, O as estimateConversationMessagesTokens, P as recordDeliveredAssistantMessage, Pn as isExperimentalFeatureEnabled, Po as configValueSchema, Pt as releaseInboundMessage, Q as lostWorkerBeforeFirstSave, Qi as removeReactionFromMessage, Rn as webActorUserIds, Sn as buildDeterministicTurnId, So as slackAttachmentsVersionQuery, T as fallbackShortTitle, Tn as getSubscribedReplyPreflightDecision, Tr as canReadReviewItem, U as AuthorizationFlowDisabledError, Wi as truncateStatusText, Y as wasPendingAuthStopped, Yn as getPlugins, Yt as persistWithRetry, Z as loadTurnCheckpoint, Za as createPluginLogger, Zi as postSlackMessage, _o as notInheritedByForkChild, _r as listWaitingConversations, a as loadProjection, ao as viewerConversationMembership, at as listTurnSummaries, b as persistConversationMessages, bo as readAttachmentVisionSummary, br as takeReviewItem, d as recordAuthorizationCompleted, dn as trimTrailingAssistantMessages, do as readConversationEventPageAfter, eo as readConversationAccessFromSql, et as saveTurnCheckpoint, fa as withSlackRetries, fo as readConversationEventPageAround, gr as listReplyActionItems, h as recordSubscribedReplyRoute, ho as buildSentryConversationUrl, i as loadConversationProjection, ia as downloadPrivateSlackFile, io as conversationViewerMarks, it as getTurnRecord, j as latestConversationMessageSeq, jo as lookupSlackUserNames, jr as reviewItemReaderForUser, k as getConversationMessageSlackTs, la as isDmChannel, lo as readLatestConversationBrief, mr as getReviewItem, n as commitMessages, no as conversationIsMemberRoot, nt as completeTurnRecord, o as loadTurnProjection, oa as getHeaderString, oi as getDashboardConversationLink, oo as viewerMarksFromParticipant, ot as recordTurnSummary, q as clearPendingAuth, ra as SlackActionError, ro as conversationPinnedForUser, rt as failTurnRecord, sa as getSlackClient, t as commitAcceptedReply, to as conversationHasParticipantUser, tt as abandonTurnRecord, ua as normalizeSlackConversationId, uo as readConversationEventPage, ur as closeReviewItem, v as hydrateConversationMessages, vo as getSlackFileId, wn as decideSubscribedThreadReply, xn as buildDeterministicAssistantMessageId, xo as recordSlackAttachment, y as persistConversationMessageWindow, z as PluginCredentialFailureError, zi as escapeSlackMrkdwnText } from "./projection-CoeMNxJ4.js";
|
|
3
|
+
import { a as completeText, c as resolveGatewayModel, m as escapeXml, r as completeDecision, x as isProviderRetryError } from "./client-B0aAs7wC.js";
|
|
4
|
+
import { c as getSlackClientSecret, i as getChatConfig, l as getSlackSigningSecret, n as botConfig, o as getSlackBotToken, s as getSlackClientId, v as normalizeSlackEmojiName } from "./config-B9f9Lqo5.js";
|
|
5
|
+
import { E as withSpan, G as toOptionalNumber, K as toOptionalString, S as setTags, T as withLogContext, W as isRecord, 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-CMFhLLj4.js";
|
|
6
|
+
import { t as JUNIOR_VERSION } from "./version-BTIz7fGi.js";
|
|
7
7
|
import { f as parseSlackTeamId, h as parseSlackMessageTs, i as isActorUserId, n as createSlackActor, o as isUserActor, r as createSlackResumeActor, s as parseActorUserId, t as createActor, u as parseSlackChannelId } from "./actor-6jsm_v96.js";
|
|
8
|
-
import {
|
|
9
|
-
import { A as
|
|
10
|
-
import { _ as instructionProvenanceFor, h as contextProvenance, i as isVisionImageMediaType, r as detectImageMediaType } from "./media-
|
|
11
|
-
import { d as actorLogContext, f as credentialContextForActor } from "./registry-
|
|
12
|
-
import { A as runWithSlackInstallation, B as listThreadReplies, F as resolveSlackChannelIdFromThreadId, I as checkSlackChannelReadAccess, L as joinPublicChannelForRead,
|
|
8
|
+
import { A as conversationAncestors, C as getSqlExecutor, H as resolveActorIdentityId, I as withConversationMutationLock, L as conversationKindFromRow, M as readConversationTrees, N as setArchivedAt, P as loadConversationSlackTenantIds, Q as parseSessionSource, R as locationFromRow, S as getDb, U as saveActorAvatar, Z as bindProviderConversation, at as agentTurnUsageSchema, ct as createSlackDestination, et as nextDetailVersion, f as identityAvatarUrl, h as readUserAvatarUrls, j as conversationDescendants, k as withConversationEventLock, nt as addAgentTurnUsage, ot as hasAgentTurnUsage, st as resolveRootConversationId, ut as requireSlackDestination, x as getConversationStore, y as getConversationEventStore, z as setFirstConversationLocation } from "./viewer-CH-ASQzh.js";
|
|
9
|
+
import { A as juniorConversations, C as isUserInstruction, D as juniorCodeChanges, E as juniorConversationAnnotations, M as juniorUsers, N as juniorDestinations, _ as juniorConversationReadPositions, b as juniorConversationBriefs, j as juniorIdentities, l as juniorReviewItems, s as juniorReviewItemConversations, v as juniorConversationParticipants, w as juniorConversationEvents } from "./executor-Dipi2Ixl.js";
|
|
10
|
+
import { _ as instructionProvenanceFor, h as contextProvenance, i as isVisionImageMediaType, r as detectImageMediaType } from "./media-B-BpXo41.js";
|
|
11
|
+
import { d as actorLogContext, f as credentialContextForActor } from "./registry-u-sFYtx_.js";
|
|
12
|
+
import { A as runWithSlackInstallation, At as turnInputTelemetry, B as listThreadReplies, Dt as executeTurn, Et as AgentRunError, F as resolveSlackChannelIdFromThreadId, I as checkSlackChannelReadAccess, L as joinPublicChannelForRead, M as parseSlackThreadId, N as readSlackRawMessageContext, Nt as getWebAuthorization, P as resolveSlackChannelIdFromMessage, R as getConversationInfo, S as createSlackReviewItemShow, V as resolveDestinationVisibility, Wt as RetryableDeliveryError, X as readConversationSourceTask, a as buildAuthPauseResponse, at as deliverReviewItemChange, b as renderAttachmentText, bt as stopChildAgentsBelow, ct as acceptsWebMessages, dt as createAndEnqueueConversation, ft as createConversationId, ht as decodeInputImages, i as readConversationLineage, jt as withTurnSpan, kt as getTurnInputSpanAttributes, lt as appendAndEnqueueWebMessage, m as latestProgressStatus, mt as webActorFromUser, n as executeAgentRun, pt as recordWebConversationActivity, qt as shouldEmitDevAgentTrace, t as createAgentRunner, wt as createConversationTurnWorker, x as renderBlockText, xt as stopChildAgentsOf, yt as storeAttachment } from "./agent-runner-DGCwOEyL.js";
|
|
13
13
|
import { r as acquireActiveLock } from "./locks-D-0h111u.js";
|
|
14
|
-
import { a as setStateValues, i as getStateValues, r as getStateAdapter } from "./adapter-
|
|
15
|
-
import { B as readMessageAttachments, d as conversationEventPageSchema, l as conversationDetailReportSchema, m as conversationFeedSchema } from "./conversation-
|
|
16
|
-
import { a as EVENT_SYSTEM_ACTOR, o as isEventConversationMessage } from "./prompt-
|
|
17
|
-
import {
|
|
18
|
-
import { n as getAssistantReplyText
|
|
19
|
-
import {
|
|
14
|
+
import { a as setStateValues, i as getStateValues, r as getStateAdapter } from "./adapter-JQZaJ-B_.js";
|
|
15
|
+
import { B as readMessageAttachments, d as conversationEventPageSchema, l as conversationDetailReportSchema, m as conversationFeedSchema } from "./conversation-BusI2uzj.js";
|
|
16
|
+
import { a as EVENT_SYSTEM_ACTOR, o as isEventConversationMessage } from "./prompt-C9OQEfan.js";
|
|
17
|
+
import { a as persistAuthPauseTurnState, at as isCooperativeTurnYieldError, b as getChildAgentLabel, c as getTurnUserSlackMessageTs, ct as markTurnClosed, d as loadThreadContextTrimFloor, dt as startActiveTurn, et as ConversationTurnBoundaryError, i as completeAuthPauseTurn, it as getConversationTurnBoundaryError, l as buildDeliveredTurnStatePatch, lt as markTurnCompleted, m as loadPendingMessageCards, n as getAgentTurnDiagnosticsAttributes, nt as TurnInputCommitLostError, o as getTurnUserMessage, ot as isTurnInputCommitLostError, p as getTurnLifecycle, r as requireTurnFailureEventId, rt as TurnInputDeferredError, s as getTurnUserReplyAttachmentContext, st as isTurnInputDeferredError, t as finalizeFailedTurnReplyWithEvent, tt as CooperativeTurnYieldError, u as buildTurnThreadContext, ut as markTurnFailed } from "./turn-failure-response-BOviBdT-.js";
|
|
18
|
+
import { n as getAssistantReplyText } from "./assistant-reply-CAPafcUY.js";
|
|
19
|
+
import { $ as withoutSavedSteeringMessages, B as maybePostAutomatedTurnLimitNotice, H as resolveSlackReplyTarget, K as recordFinishedTurnForAutomatedLimit, U as sendSlackReply, X as buildSteeringPiMessage, b as conversationSubtree, c as loadReviewItemInput, ct as deliversFinalText, d as getAuthPausedConversationTurnId, g as resolveMailboxTurnWork, l as savedInputInstruction, lt as finishedRunReply, o as skipInputAfterConversationStop, pt as runDispatchOutcome, r as markConversationsStopped, ut as postsRunNotices, x as conversationSubtreeColumns, y as legacyWebMailboxMetadataSchema } from "./session-stop-CGz5DByb.js";
|
|
20
20
|
import { p as webMessageId, v as isEmptyUserInputAnswer, y as normalizeUserInputAnswer } from "./reporting-window-B4TwyuJo.js";
|
|
21
|
-
import {
|
|
22
|
-
import { D as steerWebPendingMessages, O as stopConversationWork, T as requestConversationWork, _ as getConversationWorkState, a as cancelHumanFacingPendingMessages, g as getConversation, h as ensureConversationWake, r as appendAndEnqueueInboundMessage, s as claimInboundMessage } from "./store-
|
|
23
|
-
import { _ as
|
|
24
|
-
import { d as apiErrorSchema, f as healthReportSchema, s as conversationPendingMessagesReportSchema } from "./conversation-pending-messages-
|
|
25
|
-
import {
|
|
26
|
-
import { n as
|
|
27
|
-
import {
|
|
28
|
-
import {
|
|
29
|
-
import {
|
|
30
|
-
import { t as bindMessageAgent } from "./message-DqjuKzUx.js";
|
|
31
|
-
import { t as bindSpawnAgent } from "./spawn-BB2_4VYn.js";
|
|
32
|
-
import { n as scheduleSessionCompletedPluginTasks, t as processPluginTask } from "./task-runner-D8lddjzp.js";
|
|
33
|
-
import { a as persistAuthPauseTurnState, c as getTurnUserSlackMessageTs, i as completeAuthPauseTurn, l as buildDeliveredTurnStatePatch, n as getAgentTurnDiagnosticsAttributes, o as getTurnUserMessage, r as requireTurnFailureEventId, s as getTurnUserReplyAttachmentContext, t as finalizeFailedTurnReplyWithEvent, u as loadPendingMessageCards } from "./turn-failure-response-DaJ04qVj.js";
|
|
21
|
+
import { S as getTurnRequestDeadline, _ as getVercelConversationWorkQueue } from "./background-compaction-queue-Btu2oab_.js";
|
|
22
|
+
import { D as steerWebPendingMessages, O as stopConversationWork, T as requestConversationWork, _ as getConversationWorkState, a as cancelHumanFacingPendingMessages, g as getConversation, h as ensureConversationWake, r as appendAndEnqueueInboundMessage, s as claimInboundMessage } from "./store-D0-8plWp.js";
|
|
23
|
+
import { _ as markDispatchBlocked, _t as getPersistedThreadState, a as claimDispatchMailboxAppend, b as markDispatchRunning, bt as coerceThreadConversationState, c as getDispatchConversationId, d as getDispatchRecord, f as getDispatchTurnId, g as markDispatchAwaitingResume, gt as getPersistedSandboxState, ht as getLocationConfigurationService, m as isTerminalDispatchStatus, mt as resolveTurnSessionRouting, n as scheduleSessionCompletedPluginTasks, o as confirmDispatchMailboxAppend, pt as resolveConversationRouting, st as readAutomationTitlesByConversationId, u as getDispatchInputMessageId, v as markDispatchCompleted, vt as persistThreadRuntimeState, y as markDispatchFailed, yt as persistThreadStateById } from "./task-runner-xPuQmEot.js";
|
|
24
|
+
import { d as apiErrorSchema, f as healthReportSchema, s as conversationPendingMessagesReportSchema } from "./conversation-pending-messages-DwehU0Fd.js";
|
|
25
|
+
import { r as endActiveAgentInvocations, s as resolveThreadTurnWork } from "./work-C75_IM5e.js";
|
|
26
|
+
import { a as withAgentInvocationResultActors, n as enqueueAgentInvocationResult, t as createChildConversationWorker } from "./result-CescSwAw.js";
|
|
27
|
+
import { c as createPausedTurns, d as wakePausedTurn, f as getTurnAuthorization, l as getPausedTurnRequest } from "./connections-CQ7p0aNJ.js";
|
|
28
|
+
import { t as bindMessageAgent } from "./message-D1xLljUF.js";
|
|
29
|
+
import { t as bindSpawnAgent } from "./spawn-C8F_iXWO.js";
|
|
34
30
|
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
|
|
35
31
|
import * as z from "zod";
|
|
36
32
|
import { and, asc, desc, eq, gt, inArray, isNotNull, isNull, lte, max, ne, or, sql } from "drizzle-orm";
|
|
@@ -267,12 +263,16 @@ function createAgentDispatchConversationWorker(options) {
|
|
|
267
263
|
if (resumesDurableTurn && context.attempt.messages.length > 0) await acknowledge();
|
|
268
264
|
let result;
|
|
269
265
|
if (resumesDurableTurn) {
|
|
270
|
-
await options.resumeTurn(dispatch, {
|
|
266
|
+
await options.resumeTurn(dispatch, {
|
|
267
|
+
shouldYield: context.shouldYield,
|
|
268
|
+
checkIn: context.checkIn
|
|
269
|
+
});
|
|
271
270
|
result = await readDispatchTurnResult(dispatch);
|
|
272
271
|
} else {
|
|
273
272
|
const runtimeResult = await options.runTurn(dispatch, {
|
|
274
273
|
ack: acknowledge,
|
|
275
|
-
shouldYield: context.shouldYield
|
|
274
|
+
shouldYield: context.shouldYield,
|
|
275
|
+
checkIn: context.checkIn
|
|
276
276
|
});
|
|
277
277
|
result = runtimeResult.outcome ? runtimeResult : {
|
|
278
278
|
...runtimeResult,
|
|
@@ -498,27 +498,43 @@ function treeIsQuiet(cutoff) {
|
|
|
498
498
|
}
|
|
499
499
|
/**
|
|
500
500
|
* True when no open Review item on the participant row's root or a child
|
|
501
|
-
* conversation needs
|
|
502
|
-
* stay in
|
|
501
|
+
* conversation needs a person. Archive applies to everyone, so a
|
|
502
|
+
* conversation that waits on anyone must stay in the feed.
|
|
503
503
|
*/
|
|
504
|
-
function
|
|
504
|
+
function notWaitingOnAnyone() {
|
|
505
505
|
const linked = alias(juniorConversations, "linked_conversation");
|
|
506
|
-
const waiting = getDb().select({ itemId: juniorReviewItemConversations.itemId }).from(juniorReviewItemConversations).innerJoin(juniorReviewItems, eq(juniorReviewItems.id, juniorReviewItemConversations.itemId)).innerJoin(linked, eq(linked.conversationId, juniorReviewItemConversations.conversationId)).where(and(
|
|
506
|
+
const waiting = getDb().select({ itemId: juniorReviewItemConversations.itemId }).from(juniorReviewItemConversations).innerJoin(juniorReviewItems, eq(juniorReviewItems.id, juniorReviewItemConversations.itemId)).innerJoin(linked, eq(linked.conversationId, juniorReviewItemConversations.conversationId)).where(and(reviewItemNeedsSomeone(), or(eq(linked.conversationId, juniorConversationParticipants.rootConversationId), eq(linked.rootConversationId, juniorConversationParticipants.rootConversationId))));
|
|
507
507
|
return sql`not exists (${waiting})`;
|
|
508
508
|
}
|
|
509
509
|
/**
|
|
510
|
+
* True when no participant of the row's root pinned it or turned
|
|
511
|
+
* auto-archive off for it. Archive applies to everyone, so one person's run
|
|
512
|
+
* must not undo another person's pin or manual restore.
|
|
513
|
+
*/
|
|
514
|
+
function noParticipantKeepsRoot() {
|
|
515
|
+
const keeper = alias(juniorConversationParticipants, "keeping_participant");
|
|
516
|
+
const keeping = getDb().select({ userId: keeper.userId }).from(keeper).where(and(eq(keeper.rootConversationId, juniorConversationParticipants.rootConversationId), or(isNotNull(keeper.pinnedAt), eq(keeper.autoArchive, false))));
|
|
517
|
+
return sql`not exists (${keeping})`;
|
|
518
|
+
}
|
|
519
|
+
/** True when the participant row's root is not archived. */
|
|
520
|
+
function rootIsUnarchived() {
|
|
521
|
+
const root = alias(juniorConversations, "archive_root");
|
|
522
|
+
const unarchived = getDb().select({ conversationId: root.conversationId }).from(root).where(and(eq(root.conversationId, juniorConversationParticipants.rootConversationId), isNull(root.archivedAt)));
|
|
523
|
+
return sql`exists (${unarchived})`;
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
510
526
|
* Conditions that a participant row must meet when it is selected and again
|
|
511
527
|
* when it is archived, so new activity, a new run, a new Review item, or a
|
|
512
528
|
* changed setting wins over a stale read.
|
|
513
529
|
*/
|
|
514
530
|
function archivableRow(run) {
|
|
515
|
-
return and(eq(juniorConversationParticipants.userId, run.userId),
|
|
531
|
+
return and(eq(juniorConversationParticipants.userId, run.userId), rootIsUnarchived(), noParticipantKeepsRoot(), lte(juniorConversationParticipants.lastMessageAt, runCutoff(run)), runOptsIn(run), run.kind === "scheduled" ? sql`${juniorUsers.autoArchiveGraceHours} <= ${run.graceHours}` : void 0, treeIsQuiet(runCutoff(run)), notWaitingOnAnyone());
|
|
516
532
|
}
|
|
517
533
|
/**
|
|
518
|
-
* One page of the user's
|
|
519
|
-
* follow `
|
|
520
|
-
* reads only rows older than the cutoff. Archive writes during the run
|
|
521
|
-
* move `lastMessageAt`, so they do not skip rows.
|
|
534
|
+
* One page of the user's participant rows on unarchived roots that may be
|
|
535
|
+
* done. Pages follow `junior_conversation_participants_user_activity_idx`, so
|
|
536
|
+
* a run reads only rows older than the cutoff. Archive writes during the run
|
|
537
|
+
* do not move `lastMessageAt`, so they do not skip rows.
|
|
522
538
|
*/
|
|
523
539
|
async function selectCandidateRoots(run, after) {
|
|
524
540
|
return await getDb().select({
|
|
@@ -547,9 +563,16 @@ async function selectDoneRoots(rootIds, cutoffMs) {
|
|
|
547
563
|
unfinishedWork: unfinished.has(id)
|
|
548
564
|
}, cutoffMs));
|
|
549
565
|
}
|
|
550
|
-
/**
|
|
566
|
+
/**
|
|
567
|
+
* Archive one root for everyone when it is still archivable for the run's
|
|
568
|
+
* user.
|
|
569
|
+
*/
|
|
551
570
|
async function archiveRoot(run, rootConversationId) {
|
|
552
|
-
|
|
571
|
+
const archivable = getDb().select({ userId: juniorConversationParticipants.userId }).from(juniorConversationParticipants).innerJoin(juniorUsers, eq(juniorUsers.id, juniorConversationParticipants.userId)).where(and(eq(juniorConversationParticipants.rootConversationId, rootConversationId), archivableRow(run)));
|
|
572
|
+
return (await getDb().update(juniorConversations).set({
|
|
573
|
+
archivedAt: run.now,
|
|
574
|
+
detailVersion: nextDetailVersion
|
|
575
|
+
}).where(and(eq(juniorConversations.conversationId, rootConversationId), isNull(juniorConversations.archivedAt), sql`exists (${archivable})`)).returning({ conversationId: juniorConversations.conversationId })).length > 0;
|
|
553
576
|
}
|
|
554
577
|
/** Archive every done conversation of one user and count the rows. */
|
|
555
578
|
async function archiveUserDoneConversations(run) {
|
|
@@ -576,7 +599,7 @@ async function archiveUserDoneConversations(run) {
|
|
|
576
599
|
* conversation. Most users never turn it on, so the sweep reads only these.
|
|
577
600
|
*/
|
|
578
601
|
async function selectAutoArchiveUsers() {
|
|
579
|
-
const optedInConversation = getDb().select({ userId: juniorConversationParticipants.userId }).from(juniorConversationParticipants).where(and(eq(juniorConversationParticipants.userId, juniorUsers.id), eq(juniorConversationParticipants.autoArchive, true),
|
|
602
|
+
const optedInConversation = getDb().select({ userId: juniorConversationParticipants.userId }).from(juniorConversationParticipants).where(and(eq(juniorConversationParticipants.userId, juniorUsers.id), eq(juniorConversationParticipants.autoArchive, true), rootIsUnarchived()));
|
|
580
603
|
return await getDb().select({
|
|
581
604
|
graceHours: juniorUsers.autoArchiveGraceHours,
|
|
582
605
|
id: juniorUsers.id
|
|
@@ -584,7 +607,7 @@ async function selectAutoArchiveUsers() {
|
|
|
584
607
|
}
|
|
585
608
|
/**
|
|
586
609
|
* Run one auto-archive sweep over every user who wants it and return how
|
|
587
|
-
* many participant rows it checked and archived.
|
|
610
|
+
* many participant rows it checked and how many roots it archived.
|
|
588
611
|
*/
|
|
589
612
|
async function runAutoArchiveSweep(args) {
|
|
590
613
|
const now = new Date(args.nowMs);
|
|
@@ -1877,63 +1900,6 @@ const LEADING_MENTION_BEFORE_STEERING_RE = /^(\s*(?:<@[^>]+>|@[A-Za-z0-9._-]+\b)
|
|
|
1877
1900
|
function stripLeadingSteeringOverride(text) {
|
|
1878
1901
|
return text.replace(LEADING_MENTION_BEFORE_STEERING_RE, "$1").replace(/^\s*!!\s*/, "");
|
|
1879
1902
|
}
|
|
1880
|
-
// src/chat/task-execution/turn-telemetry.ts
|
|
1881
|
-
/** Read the turn input timing facts from a mailbox batch, oldest first. */
|
|
1882
|
-
function turnInputTelemetry(messages) {
|
|
1883
|
-
const oldest = messages[0];
|
|
1884
|
-
if (!oldest) return void 0;
|
|
1885
|
-
return {
|
|
1886
|
-
count: messages.length,
|
|
1887
|
-
oldestCreatedAtMs: oldest.createdAtMs,
|
|
1888
|
-
oldestReceivedAtMs: oldest.receivedAtMs,
|
|
1889
|
-
traceContexts: messages.flatMap((message) => message.traceContext ?? [])
|
|
1890
|
-
};
|
|
1891
|
-
}
|
|
1892
|
-
const SENTRY_TRACE_PATTERN = /^([0-9a-f]{32})-([0-9a-f]{16})(?:-([01]))?$/;
|
|
1893
|
-
function spanLinks({ sentryTrace }) {
|
|
1894
|
-
const [, traceId, spanId, sampled] = SENTRY_TRACE_PATTERN.exec(sentryTrace) ?? [];
|
|
1895
|
-
return traceId && spanId ? [{ context: {
|
|
1896
|
-
traceId,
|
|
1897
|
-
spanId,
|
|
1898
|
-
traceFlags: sampled === "1" ? 1 : 0
|
|
1899
|
-
} }] : [];
|
|
1900
|
-
}
|
|
1901
|
-
/**
|
|
1902
|
-
* Run a `chat.turn` span in the trace of the first trace context.
|
|
1903
|
-
*
|
|
1904
|
-
* The span links to the other trace contexts and to the span that was active,
|
|
1905
|
-
* such as the worker span. Without a trace context, the span is a child of the
|
|
1906
|
-
* active span. A malformed trace context starts a new trace. The span records
|
|
1907
|
-
* how long the Turn waited on context compaction.
|
|
1908
|
-
*/
|
|
1909
|
-
async function withTurnSpan(context, input, callback) {
|
|
1910
|
-
const [parent, ...others] = input?.traceContexts ?? [];
|
|
1911
|
-
if (!parent) return await withSpan("chat.turn", "chat.turn", context, (set) => measureTurnCompactionWait(set, () => callback(set)));
|
|
1912
|
-
const activeSpan = getActiveSpan();
|
|
1913
|
-
const links = [...others.flatMap(spanLinks), ...activeSpan ? [{ context: activeSpan.spanContext() }] : []];
|
|
1914
|
-
const { baggage, sentryTrace } = parent;
|
|
1915
|
-
return await continueTrace({
|
|
1916
|
-
baggage,
|
|
1917
|
-
sentryTrace
|
|
1918
|
-
}, () => withSpan("chat.turn", "chat.turn", context, async (setSpanAttributes) => {
|
|
1919
|
-
getActiveSpan()?.addLinks(links);
|
|
1920
|
-
return await measureTurnCompactionWait(setSpanAttributes, () => callback(setSpanAttributes));
|
|
1921
|
-
}));
|
|
1922
|
-
}
|
|
1923
|
-
/**
|
|
1924
|
-
* Build the `chat.turn` timing attributes for the oldest input message.
|
|
1925
|
-
*
|
|
1926
|
-
* The provider, the ingress host, and the worker host use separate clocks. A negative
|
|
1927
|
-
* duration is clock skew, not latency, so it is left out.
|
|
1928
|
-
*/
|
|
1929
|
-
function getTurnInputSpanAttributes(input, turnStartedAtMs) {
|
|
1930
|
-
const attributes = { "app.turn.input_count": input.count };
|
|
1931
|
-
const deliveryLagMs = input.oldestReceivedAtMs - input.oldestCreatedAtMs;
|
|
1932
|
-
if (deliveryLagMs >= 0) attributes["app.turn.delivery_lag_ms"] = Math.round(deliveryLagMs);
|
|
1933
|
-
const waitMs = turnStartedAtMs - input.oldestReceivedAtMs;
|
|
1934
|
-
if (waitMs >= 0) attributes["app.turn.wait_ms"] = Math.round(waitMs);
|
|
1935
|
-
return attributes;
|
|
1936
|
-
}
|
|
1937
1903
|
// src/chat/task-execution/slack-work.ts
|
|
1938
1904
|
const slackConversationRouteSchema = z.enum(["mention", "subscribed"]);
|
|
1939
1905
|
function hasSteeringOverride(text) {
|
|
@@ -2273,12 +2239,14 @@ function createSlackConversationWorker(options) {
|
|
|
2273
2239
|
task: async () => {
|
|
2274
2240
|
await options.runNextPausedTurn(context.conversationId, {
|
|
2275
2241
|
shouldYield: context.shouldYield,
|
|
2242
|
+
checkIn: context.checkIn,
|
|
2276
2243
|
stopSignal: context.stopSignal?.()
|
|
2277
2244
|
});
|
|
2278
2245
|
}
|
|
2279
2246
|
});
|
|
2280
2247
|
} catch (error) {
|
|
2281
2248
|
if (isCooperativeTurnYieldError(error)) return { status: "yielded" };
|
|
2249
|
+
if (isTurnInputCommitLostError(error)) return { status: "lost_lease" };
|
|
2282
2250
|
throw error;
|
|
2283
2251
|
}
|
|
2284
2252
|
return { status: "completed" };
|
|
@@ -2350,6 +2318,7 @@ function createSlackConversationWorker(options) {
|
|
|
2350
2318
|
ack,
|
|
2351
2319
|
isFinalAttempt: context.attempt.isFinalAttempt,
|
|
2352
2320
|
shouldYield: context.shouldYield,
|
|
2321
|
+
checkIn: context.checkIn,
|
|
2353
2322
|
stopSignal: context.stopSignal?.(),
|
|
2354
2323
|
telemetry
|
|
2355
2324
|
});
|
|
@@ -2361,6 +2330,7 @@ function createSlackConversationWorker(options) {
|
|
|
2361
2330
|
ack,
|
|
2362
2331
|
isFinalAttempt: context.attempt.isFinalAttempt,
|
|
2363
2332
|
shouldYield: context.shouldYield,
|
|
2333
|
+
checkIn: context.checkIn,
|
|
2364
2334
|
stopSignal: context.stopSignal?.(),
|
|
2365
2335
|
telemetry
|
|
2366
2336
|
});
|
|
@@ -2975,6 +2945,7 @@ function createSlackTurnRuntime(deps) {
|
|
|
2975
2945
|
drainSteeringMessages,
|
|
2976
2946
|
onTurnStatePersisted: hooks.onTurnStatePersisted,
|
|
2977
2947
|
shouldYield: hooks.shouldYield,
|
|
2948
|
+
checkIn: hooks.checkIn,
|
|
2978
2949
|
stopSignal: hooks.stopSignal
|
|
2979
2950
|
});
|
|
2980
2951
|
});
|
|
@@ -3266,6 +3237,7 @@ function createSlackTurnRuntime(deps) {
|
|
|
3266
3237
|
drainSteeringMessages,
|
|
3267
3238
|
onTurnStatePersisted: hooks.onTurnStatePersisted,
|
|
3268
3239
|
shouldYield: hooks.shouldYield,
|
|
3240
|
+
checkIn: hooks.checkIn,
|
|
3269
3241
|
stopSignal: hooks.stopSignal
|
|
3270
3242
|
});
|
|
3271
3243
|
});
|
|
@@ -3391,7 +3363,6 @@ function createSubscribedReplyPolicy(deps) {
|
|
|
3391
3363
|
}
|
|
3392
3364
|
// src/chat/app/services.ts
|
|
3393
3365
|
function createJuniorRuntimeServices(overrides = {}) {
|
|
3394
|
-
const conversationMemory = createConversationMemoryService({ completeText: overrides.conversationMemory?.completeText ?? completeText });
|
|
3395
3366
|
const visionContext = createVisionContextService({
|
|
3396
3367
|
attachmentStorage: overrides.visionContext?.attachmentStorage,
|
|
3397
3368
|
completeText: overrides.visionContext?.completeText ?? completeText,
|
|
@@ -3404,7 +3375,6 @@ function createJuniorRuntimeServices(overrides = {}) {
|
|
|
3404
3375
|
tracePropagation: overrides.sandbox?.tracePropagation
|
|
3405
3376
|
});
|
|
3406
3377
|
return {
|
|
3407
|
-
conversationMemory,
|
|
3408
3378
|
executeTurn: async (run, saveResult) => await executeTurn(agentRunner, run, saveResult),
|
|
3409
3379
|
subscribedReplyPolicy: createSubscribedReplyPolicy({ completeDecision: overrides.subscribedReplyPolicy?.completeDecision ?? completeDecision }),
|
|
3410
3380
|
visionContext
|
|
@@ -3812,32 +3782,6 @@ async function maybeApplyProviderDefaultConfigRequest(args) {
|
|
|
3812
3782
|
return { text: `Default GitHub repo set to \`${repo}\`.` };
|
|
3813
3783
|
}
|
|
3814
3784
|
// src/chat/providers/slack/input.ts
|
|
3815
|
-
function renderRecentThreadMessageLines(conversationContext, messages) {
|
|
3816
|
-
const messagesForContext = messages.filter((queued) => {
|
|
3817
|
-
if (queued.explicitMention) return false;
|
|
3818
|
-
const slackTs = inboundMessageActor(queued)?.slackTs;
|
|
3819
|
-
return !slackTs || !conversationContext?.includes(`slack_ts="${slackTs}"`);
|
|
3820
|
-
});
|
|
3821
|
-
if (messagesForContext.length === 0) return [];
|
|
3822
|
-
const lines = [];
|
|
3823
|
-
for (const queued of messagesForContext) {
|
|
3824
|
-
const actor = inboundMessageActor(queued);
|
|
3825
|
-
const author = escapeXml(actor?.authorName ?? "user");
|
|
3826
|
-
const attrs = [
|
|
3827
|
-
`role="user"`,
|
|
3828
|
-
`author="${author}"`,
|
|
3829
|
-
actor?.authorId ? `actor_id="${escapeXml(actor.authorId)}"` : void 0,
|
|
3830
|
-
actor?.slackTs ? `slack_ts="${escapeXml(actor.slackTs)}"` : void 0
|
|
3831
|
-
].filter((attr) => Boolean(attr)).join(" ");
|
|
3832
|
-
const text = escapeXml(queued.userText.replace(/\s+/g, " "));
|
|
3833
|
-
lines.push(` <message ${attrs}>`, `[user] ${author}: ${text}`, " </message>");
|
|
3834
|
-
}
|
|
3835
|
-
return lines;
|
|
3836
|
-
}
|
|
3837
|
-
/** Add recent Slack messages to the agent context. */
|
|
3838
|
-
function appendRecentMessagesToContext(conversationContext, messages) {
|
|
3839
|
-
return appendThreadContextMessages(conversationContext, renderRecentThreadMessageLines(conversationContext, messages));
|
|
3840
|
-
}
|
|
3841
3785
|
/** Return the actor stored with one inbound Slack message. */
|
|
3842
3786
|
function inboundMessageActor(queued) {
|
|
3843
3787
|
const actor = getMessageActorIdentity(queued.message);
|
|
@@ -4220,6 +4164,7 @@ function createSlackTurn(deps) {
|
|
|
4220
4164
|
createdAtMs: Date.now(),
|
|
4221
4165
|
inputMessageIds: [.../* @__PURE__ */ new Set([...(options.queuedMessages ?? []).map((queued) => queued.message.id), preparedState.userMessageId])],
|
|
4222
4166
|
surface: options.execution?.surface ?? "slack",
|
|
4167
|
+
threadContextThroughSeq: latestConversationMessageSeq(preparedState.conversation),
|
|
4223
4168
|
turnId
|
|
4224
4169
|
});
|
|
4225
4170
|
if (conversationId) {
|
|
@@ -4296,7 +4241,6 @@ function createSlackTurn(deps) {
|
|
|
4296
4241
|
surface: options.execution?.surface ?? "slack"
|
|
4297
4242
|
});
|
|
4298
4243
|
};
|
|
4299
|
-
let turnWakeError;
|
|
4300
4244
|
let boundaryFailureCode = "agent_run_failed";
|
|
4301
4245
|
let terminalDispatchFailureOutcome;
|
|
4302
4246
|
const notifyTurnCompleted = async () => {
|
|
@@ -4413,7 +4357,7 @@ function createSlackTurn(deps) {
|
|
|
4413
4357
|
conversationId,
|
|
4414
4358
|
activeTurnId
|
|
4415
4359
|
})).piMessages;
|
|
4416
|
-
const
|
|
4360
|
+
const hasHistory = Boolean(piMessages?.length);
|
|
4417
4361
|
const batchedSteeringMessages = (await resolveSteeringMessages((options.queuedMessages ?? []).filter((queued) => queued.explicitMention))).map((steering) => ({
|
|
4418
4362
|
message: buildSteeringPiMessage(steering),
|
|
4419
4363
|
provenance: steering.provenance
|
|
@@ -4445,7 +4389,13 @@ function createSlackTurn(deps) {
|
|
|
4445
4389
|
const toolChannelId = channelId;
|
|
4446
4390
|
const activeInstructionAuthorId = actor?.userId ?? parseActorUserId(message.author.userId);
|
|
4447
4391
|
const activeInstructionAuthorName = actor?.fullName ?? actor?.userName;
|
|
4448
|
-
const promptConversationContext =
|
|
4392
|
+
const promptConversationContext = await buildTurnThreadContext({
|
|
4393
|
+
conversation: preparedState.conversation,
|
|
4394
|
+
conversationId,
|
|
4395
|
+
excludeMessageIds: [...(options.queuedMessages ?? []).filter((queued) => queued.explicitMention).map((queued) => queued.message.id), ...preparedState.userMessageId ? [preparedState.userMessageId] : []],
|
|
4396
|
+
hasHistory,
|
|
4397
|
+
turnId
|
|
4398
|
+
});
|
|
4449
4399
|
const drainSteeringMessages = options.drainSteeringMessages ? async (accept) => {
|
|
4450
4400
|
let acceptedMessages;
|
|
4451
4401
|
const drained = await options.drainSteeringMessages(async (queuedMessages) => {
|
|
@@ -4479,7 +4429,6 @@ function createSlackTurn(deps) {
|
|
|
4479
4429
|
...activeInstructionAuthorName ? { authorName: activeInstructionAuthorName } : void 0,
|
|
4480
4430
|
...slackMessageTs ? { slackTs: slackMessageTs } : void 0
|
|
4481
4431
|
},
|
|
4482
|
-
includeConversationContextWithHistory: hasDurablePromptHistory,
|
|
4483
4432
|
...savedInput,
|
|
4484
4433
|
context: promptConversationContext,
|
|
4485
4434
|
inboundAttachmentCount: turnAttachments.length,
|
|
@@ -4523,6 +4472,7 @@ function createSlackTurn(deps) {
|
|
|
4523
4472
|
onInputCommitted: options.ack,
|
|
4524
4473
|
drainSteeringMessages,
|
|
4525
4474
|
shouldYield: options.shouldYield,
|
|
4475
|
+
checkIn: options.checkIn,
|
|
4526
4476
|
onSandboxRefChanged: async (sandboxRef) => {
|
|
4527
4477
|
await persistThreadStateById(conversationId, { sandboxRef });
|
|
4528
4478
|
},
|
|
@@ -4695,7 +4645,6 @@ function createSlackTurn(deps) {
|
|
|
4695
4645
|
"app.ai.resume_session_version": outcome.resumeVersion
|
|
4696
4646
|
});
|
|
4697
4647
|
shouldPersistFailureState = true;
|
|
4698
|
-
turnWakeError = scheduleError;
|
|
4699
4648
|
throw scheduleError;
|
|
4700
4649
|
}
|
|
4701
4650
|
return;
|
|
@@ -4734,7 +4683,11 @@ function createSlackTurn(deps) {
|
|
|
4734
4683
|
shouldPersistFailureState = false;
|
|
4735
4684
|
throw error;
|
|
4736
4685
|
}
|
|
4737
|
-
|
|
4686
|
+
const leaseLoss = error instanceof AgentRunError ? error.cause : error;
|
|
4687
|
+
if (isTurnInputCommitLostError(leaseLoss)) {
|
|
4688
|
+
shouldPersistFailureState = false;
|
|
4689
|
+
throw leaseLoss;
|
|
4690
|
+
}
|
|
4738
4691
|
shouldPersistFailureState = true;
|
|
4739
4692
|
const runFailure = error instanceof AgentRunError ? error.cause : error;
|
|
4740
4693
|
if (options.stopSignal?.aborted) {
|
|
@@ -4898,10 +4851,10 @@ function getBackfillText(entry) {
|
|
|
4898
4851
|
}
|
|
4899
4852
|
/**
|
|
4900
4853
|
* Seed durable conversation memory before the current turn so routing and
|
|
4901
|
-
*
|
|
4854
|
+
* trimming can reason over a thread even when no prior app state exists.
|
|
4902
4855
|
*/
|
|
4903
4856
|
async function seedConversationBackfill(thread, conversation, currentTurn, resolveMessageActors) {
|
|
4904
|
-
if (conversation.messages.length > 0 || conversation.
|
|
4857
|
+
if (conversation.messages.length > 0 || conversation.historyFromSeq !== void 0) return "recent_messages";
|
|
4905
4858
|
const seeded = [];
|
|
4906
4859
|
let source = "recent_messages";
|
|
4907
4860
|
let fetchedNewestFirst;
|
|
@@ -4995,20 +4948,18 @@ function createPrepareTurnState(deps) {
|
|
|
4995
4948
|
conversation,
|
|
4996
4949
|
conversationId
|
|
4997
4950
|
});
|
|
4998
|
-
await
|
|
4999
|
-
threadId: args.context.threadId,
|
|
5000
|
-
channelId: args.context.channelId,
|
|
5001
|
-
actorId: args.context.actorId,
|
|
5002
|
-
runId: args.context.runId
|
|
5003
|
-
});
|
|
5004
|
-
if (conversationId) await persistConversationMessageSummaries({
|
|
4951
|
+
if (conversationId) await hydrateConversationMessages({
|
|
5005
4952
|
conversation,
|
|
5006
4953
|
conversationId
|
|
5007
4954
|
});
|
|
5008
|
-
|
|
4955
|
+
if (await trimConversationMessages(conversation, async () => conversationId ? await loadThreadContextTrimFloor(conversationId) : void 0) && conversationId && conversation.historyFromSeq !== void 0) await persistConversationMessageWindow({
|
|
4956
|
+
conversationId,
|
|
4957
|
+
historyFromSeq: conversation.historyFromSeq
|
|
4958
|
+
});
|
|
4959
|
+
const conversationContext = buildConversationContext(conversation, { excludeMessageIds: [userMessageId] }).text;
|
|
5009
4960
|
setSpanAttributes({
|
|
5010
4961
|
"app.backfill_source": backfillSource ?? "none",
|
|
5011
|
-
"app.context_tokens_estimated":
|
|
4962
|
+
"app.context_tokens_estimated": estimateConversationMessagesTokens(conversation)
|
|
5012
4963
|
});
|
|
5013
4964
|
return {
|
|
5014
4965
|
configuration,
|
|
@@ -5093,6 +5044,7 @@ function createSlackDispatchTurnRunner(options) {
|
|
|
5093
5044
|
errorMessage = result.errorMessage;
|
|
5094
5045
|
},
|
|
5095
5046
|
shouldYield: hooks.shouldYield,
|
|
5047
|
+
checkIn: hooks.checkIn,
|
|
5096
5048
|
skipBackfill: true
|
|
5097
5049
|
});
|
|
5098
5050
|
return {
|
|
@@ -5109,7 +5061,6 @@ function clearSkippedTurnIfActive(conversation, messageId) {
|
|
|
5109
5061
|
function createSlackRuntime(options) {
|
|
5110
5062
|
const services = createJuniorRuntimeServices(options.services);
|
|
5111
5063
|
const prepareTurnState = createPrepareTurnState({
|
|
5112
|
-
compactConversationIfNeeded: services.conversationMemory.compactConversationIfNeeded,
|
|
5113
5064
|
hydrateConversationVisionContext: services.visionContext.hydrateConversationVisionContext,
|
|
5114
5065
|
resolveBackfillMessageActors: async (messages, destination) => {
|
|
5115
5066
|
if (destination.platform !== "slack") throw new Error("Slack turn backfill requires a Slack destination");
|
|
@@ -5660,6 +5611,7 @@ async function resumeSlackTurnInContext(args) {
|
|
|
5660
5611
|
await status.clear();
|
|
5661
5612
|
const runError = error instanceof AgentRunError ? error.cause : error;
|
|
5662
5613
|
if (isCooperativeTurnYieldError(runError)) throw runError;
|
|
5614
|
+
if (isTurnInputCommitLostError(runError)) throw runError;
|
|
5663
5615
|
if (!runResultHandled && runArgs.run?.signal?.aborted) stopped = true;
|
|
5664
5616
|
else if (runResultHandled) {
|
|
5665
5617
|
postDeliveryCommitError = error;
|
|
@@ -6003,7 +5955,6 @@ async function runPausedTurnInContext(payload, options, runOptions) {
|
|
|
6003
5955
|
await persistThreadStateById(payload.conversationId, { conversation });
|
|
6004
5956
|
}
|
|
6005
5957
|
const locationConfiguration = getLocationConfigurationService(destination);
|
|
6006
|
-
const conversationContext = dispatchId ? void 0 : buildConversationContext(conversation, { excludeMessageIds: [userMessage.id] });
|
|
6007
5958
|
const sandboxRef = getPersistedSandboxState(currentState);
|
|
6008
5959
|
const routing = await resolveTurnSessionRouting({ conversationId: payload.conversationId });
|
|
6009
5960
|
const source = routing.source;
|
|
@@ -6031,7 +5982,6 @@ async function runPausedTurnInContext(payload, options, runOptions) {
|
|
|
6031
5982
|
initialStatus: latestProgressStatus(turnMessages),
|
|
6032
5983
|
run: {
|
|
6033
5984
|
instruction: {
|
|
6034
|
-
...conversationContext ? { context: conversationContext } : void 0,
|
|
6035
5985
|
...getTurnUserReplyAttachmentContext(userMessage),
|
|
6036
5986
|
...await savedInputInstruction({
|
|
6037
5987
|
runtime: Boolean(dispatchId) || isEventConversationMessage(userMessage),
|
|
@@ -6059,6 +6009,7 @@ async function runPausedTurnInContext(payload, options, runOptions) {
|
|
|
6059
6009
|
},
|
|
6060
6010
|
durability: {
|
|
6061
6011
|
shouldYield: runOptions.shouldYield,
|
|
6012
|
+
checkIn: runOptions.checkIn,
|
|
6062
6013
|
recordPendingAuth: async (nextPendingAuth) => {
|
|
6063
6014
|
conversation.processing.pendingAuth = nextPendingAuth;
|
|
6064
6015
|
await persistThreadStateById(payload.conversationId, { conversation });
|
|
@@ -6192,43 +6143,7 @@ async function failStrandedTurnWithFallback(args) {
|
|
|
6192
6143
|
});
|
|
6193
6144
|
return true;
|
|
6194
6145
|
}
|
|
6195
|
-
/** Recovery resumes a turn at most once after its worker stops checking in. */
|
|
6196
|
-
const MAX_LOST_WORKER_RESUMES = 1;
|
|
6197
6146
|
const LOST_WORKER_FAILURE = "Turn lost its worker before reaching a safe boundary";
|
|
6198
|
-
/**
|
|
6199
|
-
* Saved on the paused turn when recovery resumes it. The resumed run replaces
|
|
6200
|
-
* it at its first save.
|
|
6201
|
-
*/
|
|
6202
|
-
const LOST_WORKER_RESUME_MESSAGE = "Turn lost its worker; resuming from its last boundary";
|
|
6203
|
-
/** True when a resumed turn lost its worker again before it saved anything. */
|
|
6204
|
-
function lostWorkerBeforeFirstSave(turn) {
|
|
6205
|
-
return turn.errorMessage === "Turn lost its worker; resuming from its last boundary" && (turn.lostWorkerResumeCount ?? 0) >= MAX_LOST_WORKER_RESUMES;
|
|
6206
|
-
}
|
|
6207
|
-
/**
|
|
6208
|
-
* Pause a turn whose worker stopped checking in, so it resumes from its last
|
|
6209
|
-
* save. Returns false when the turn already used its resume or has no slice
|
|
6210
|
-
* left.
|
|
6211
|
-
*/
|
|
6212
|
-
async function pauseLostWorkerTurn(turn) {
|
|
6213
|
-
if ((turn.lostWorkerResumeCount ?? 0) >= MAX_LOST_WORKER_RESUMES || turn.sliceId + 1 > botConfig.maxSlicesPerTurn) return false;
|
|
6214
|
-
const paused = await saveTurnCheckpoint({
|
|
6215
|
-
mode: "paused",
|
|
6216
|
-
reason: "retry",
|
|
6217
|
-
conversationId: turn.conversationId,
|
|
6218
|
-
turnId: turn.turnId,
|
|
6219
|
-
sliceId: turn.sliceId,
|
|
6220
|
-
messages: turn.piMessages,
|
|
6221
|
-
lostWorkerResumeCount: (turn.lostWorkerResumeCount ?? 0) + 1,
|
|
6222
|
-
errorMessage: LOST_WORKER_RESUME_MESSAGE
|
|
6223
|
-
});
|
|
6224
|
-
if (!paused) return false;
|
|
6225
|
-
logWarn("agent.turn.lost_worker.resumed", {
|
|
6226
|
-
"app.ai.conversation_id": turn.conversationId,
|
|
6227
|
-
"app.ai.session_id": turn.turnId,
|
|
6228
|
-
"app.ai.resume_slice_id": paused.sliceId
|
|
6229
|
-
});
|
|
6230
|
-
return true;
|
|
6231
|
-
}
|
|
6232
6147
|
/** Resume the first valid paused Slack session for an idle conversation. */
|
|
6233
6148
|
async function runNextPausedTurn(conversationId, options, runOptions = {}) {
|
|
6234
6149
|
return withLogContext({ conversationId }, () => runNextPausedTurnInContext(conversationId, options, runOptions));
|
|
@@ -6308,642 +6223,6 @@ async function runNextPausedTurnInContext(conversationId, options, runOptions) {
|
|
|
6308
6223
|
}
|
|
6309
6224
|
return false;
|
|
6310
6225
|
}
|
|
6311
|
-
// src/chat/task-execution/assistant-message.ts
|
|
6312
|
-
/** Store one assistant Message and its Agent history. */
|
|
6313
|
-
async function commitAssistantMessage(args) {
|
|
6314
|
-
const conversationMessageId = recordDeliveredAssistantMessage({
|
|
6315
|
-
cards: args.cards,
|
|
6316
|
-
conversation: args.conversation,
|
|
6317
|
-
...args.quiet ? { quiet: args.quiet } : void 0,
|
|
6318
|
-
sessionId: args.sessionId,
|
|
6319
|
-
source: args.source,
|
|
6320
|
-
text: args.text,
|
|
6321
|
-
userMessageId: args.userMessageId
|
|
6322
|
-
});
|
|
6323
|
-
if (args.deliveryResult?.providerMessageId) markConversationMessage(args.conversation, conversationMessageId, { slackTs: args.deliveryResult.providerMessageId });
|
|
6324
|
-
try {
|
|
6325
|
-
await persistWithRetry(() => commitAcceptedReply({
|
|
6326
|
-
...args.agentMessage ? { agentMessage: args.agentMessage } : void 0,
|
|
6327
|
-
conversation: args.conversation,
|
|
6328
|
-
conversationMessageId,
|
|
6329
|
-
conversationId: args.conversationId,
|
|
6330
|
-
providerConversationBindings: args.deliveryResult?.providerConversationBindings
|
|
6331
|
-
}));
|
|
6332
|
-
} catch (error) {
|
|
6333
|
-
logException(error, "conversation.assistant.message_persist.failed");
|
|
6334
|
-
}
|
|
6335
|
-
}
|
|
6336
|
-
// src/chat/task-execution/mailbox-input.ts
|
|
6337
|
-
/**
|
|
6338
|
-
* Return the Turn inputs of web Messages, one per non-empty Message, in
|
|
6339
|
-
* order. Each one becomes its own prompt content part. A Message that
|
|
6340
|
-
* records an answer or a dismiss becomes its Review item tag. A batch with
|
|
6341
|
-
* only attachments keeps one empty input, so the prompt still has an
|
|
6342
|
-
* instruction.
|
|
6343
|
-
*/
|
|
6344
|
-
async function webTurnInputs(messages) {
|
|
6345
|
-
const flat = (await Promise.all(messages.map(async (message) => {
|
|
6346
|
-
const reviewItem = await loadReviewItemInput(message.reviewItemChange);
|
|
6347
|
-
if (reviewItem) return [{
|
|
6348
|
-
kind: "runtime",
|
|
6349
|
-
text: reviewItem
|
|
6350
|
-
}];
|
|
6351
|
-
const text = message.text.trim();
|
|
6352
|
-
return text ? [{
|
|
6353
|
-
kind: "person",
|
|
6354
|
-
text
|
|
6355
|
-
}] : [];
|
|
6356
|
-
}))).flat();
|
|
6357
|
-
return flat.length ? flat : [{
|
|
6358
|
-
kind: "person",
|
|
6359
|
-
text: ""
|
|
6360
|
-
}];
|
|
6361
|
-
}
|
|
6362
|
-
/**
|
|
6363
|
-
* Build the transcript Message for one web mailbox Message. Each web Message
|
|
6364
|
-
* keeps its own transcript Message and Review item change record, so the
|
|
6365
|
-
* dashboard shows what each Message did even when several share a Turn.
|
|
6366
|
-
*/
|
|
6367
|
-
function webConversationMessage(message, author) {
|
|
6368
|
-
const attachments = readMessageAttachments(message.input.attachments);
|
|
6369
|
-
const { reviewItemChange } = message.input;
|
|
6370
|
-
return {
|
|
6371
|
-
id: message.inboundMessageId,
|
|
6372
|
-
role: "user",
|
|
6373
|
-
text: normalizeConversationText(message.input.text),
|
|
6374
|
-
createdAtMs: message.createdAtMs,
|
|
6375
|
-
author,
|
|
6376
|
-
...message.input.authorIdentityId ? { authorIdentityId: message.input.authorIdentityId } : void 0,
|
|
6377
|
-
meta: {
|
|
6378
|
-
...attachments.length ? { attachments } : void 0,
|
|
6379
|
-
explicitMention: true,
|
|
6380
|
-
...reviewItemChange ? { reviewItemChanges: [reviewItemChange] } : void 0,
|
|
6381
|
-
source: "web"
|
|
6382
|
-
}
|
|
6383
|
-
};
|
|
6384
|
-
}
|
|
6385
|
-
/**
|
|
6386
|
-
* Return the saved input Messages of a resumed Turn in input order. A web
|
|
6387
|
-
* batch saves each Message apart. An older Turn saved one joined Message, so
|
|
6388
|
-
* its other input ids have no saved Message.
|
|
6389
|
-
*/
|
|
6390
|
-
function savedTurnInputMessages(conversation, turnMessage, inputMessageIds) {
|
|
6391
|
-
const saved = (inputMessageIds ?? []).flatMap((id) => conversation.messages.find((message) => message.id === id && message.role === "user") ?? []);
|
|
6392
|
-
return saved.some((message) => message.id === turnMessage.id) ? saved : [turnMessage];
|
|
6393
|
-
}
|
|
6394
|
-
// src/chat/task-execution/web-steering.ts
|
|
6395
|
-
async function steeringMessageFromWeb(message, actor) {
|
|
6396
|
-
const storedAttachments = readMessageAttachments(message.input.attachments);
|
|
6397
|
-
const reviewItemInput = await loadReviewItemInput(message.input.reviewItemChange);
|
|
6398
|
-
return {
|
|
6399
|
-
actor: {
|
|
6400
|
-
authorId: actor.userId,
|
|
6401
|
-
...actor.fullName ? { authorName: actor.fullName } : void 0
|
|
6402
|
-
},
|
|
6403
|
-
...reviewItemInput ? { kind: "runtime" } : void 0,
|
|
6404
|
-
provenance: instructionProvenanceFor(actor),
|
|
6405
|
-
text: reviewItemInput ?? message.input.text.trim(),
|
|
6406
|
-
timestampMs: message.createdAtMs,
|
|
6407
|
-
...storedAttachments.length ? { storedAttachments } : void 0
|
|
6408
|
-
};
|
|
6409
|
-
}
|
|
6410
|
-
/**
|
|
6411
|
-
* Drain steered web messages into the active web Turn.
|
|
6412
|
-
*
|
|
6413
|
-
* Only messages from the Turn Actor join. Steered messages from another
|
|
6414
|
-
* participant stay pending and start their own Turn next, so they never act
|
|
6415
|
-
* with this Actor's credentials.
|
|
6416
|
-
*/
|
|
6417
|
-
function createWebSteeringDrain(args) {
|
|
6418
|
-
const { actor, author, context, conversation, turnId } = args;
|
|
6419
|
-
return async (accept) => {
|
|
6420
|
-
const accepted = [];
|
|
6421
|
-
await context.attempt.drain(async (pending) => {
|
|
6422
|
-
const joining = pending.filter((message) => message.source === "web" && message.input.authorId === actor.userId && legacyWebMailboxMetadataSchema.safeParse(message.input.metadata).success);
|
|
6423
|
-
if (joining.length === 0) return [];
|
|
6424
|
-
for (const message of joining) upsertConversationMessage(conversation, webConversationMessage(message, author));
|
|
6425
|
-
await persistConversationMessages({
|
|
6426
|
-
conversation,
|
|
6427
|
-
conversationId: context.conversationId
|
|
6428
|
-
});
|
|
6429
|
-
const saved = (await getTurnRecord(context.conversationId, turnId))?.piMessages ?? [];
|
|
6430
|
-
const messages = withoutSavedSteeringMessages(saved, await Promise.all(joining.map((message) => steeringMessageFromWeb(message, actor))), buildSteeringPiMessage);
|
|
6431
|
-
if (messages.length > 0) {
|
|
6432
|
-
await accept(messages);
|
|
6433
|
-
accepted.push(...messages);
|
|
6434
|
-
}
|
|
6435
|
-
return joining.map((message) => message.inboundMessageId);
|
|
6436
|
-
});
|
|
6437
|
-
return accepted;
|
|
6438
|
-
};
|
|
6439
|
-
}
|
|
6440
|
-
// src/chat/task-execution/conversation-turn.ts
|
|
6441
|
-
/** Run a mailbox Turn and store its assistant Messages. */
|
|
6442
|
-
function stableHex(...parts) {
|
|
6443
|
-
return createHash("sha256").update(parts.join("\0")).digest("hex").slice(0, 24);
|
|
6444
|
-
}
|
|
6445
|
-
function captureConversationTurnFailure(args) {
|
|
6446
|
-
const eventId = logException(args.error, `conversation.turn.${args.failureCode}`, {
|
|
6447
|
-
conversationId: args.conversationId,
|
|
6448
|
-
...args.runId ? { runId: args.runId } : void 0,
|
|
6449
|
-
turnId: args.turnId
|
|
6450
|
-
});
|
|
6451
|
-
return typeof eventId === "string" ? eventId : void 0;
|
|
6452
|
-
}
|
|
6453
|
-
/** Return the saved timer creator subject when it is still valid here. */
|
|
6454
|
-
function resumedTimerWatchCredentialSubject(conversationId, subject) {
|
|
6455
|
-
if (subject?.binding.type !== "timer-watch") return void 0;
|
|
6456
|
-
return verifyTimerWatchCredentialSubject({
|
|
6457
|
-
conversationId,
|
|
6458
|
-
subject,
|
|
6459
|
-
watchId: subject.binding.watchId
|
|
6460
|
-
}) ? subject : void 0;
|
|
6461
|
-
}
|
|
6462
|
-
function hasLostTurnInputCommit(error) {
|
|
6463
|
-
const cause = getConversationTurnBoundaryError(error)?.cause ?? error;
|
|
6464
|
-
return isTurnInputCommitLostError(error) || isTurnInputCommitLostError(cause);
|
|
6465
|
-
}
|
|
6466
|
-
async function completeCancelledConversationTurn(args) {
|
|
6467
|
-
const pendingAuthorization = args.conversation.processing.pendingAuth?.sessionId === args.turnId ? args.conversation.processing.pendingAuth : void 0;
|
|
6468
|
-
await abandonTurnRecord({
|
|
6469
|
-
conversationId: args.conversationId,
|
|
6470
|
-
turnId: args.turnId,
|
|
6471
|
-
errorMessage: "Turn cancelled"
|
|
6472
|
-
});
|
|
6473
|
-
clearPendingAuth(args.conversation, args.turnId);
|
|
6474
|
-
markConversationMessage(args.conversation, args.userMessageId, {
|
|
6475
|
-
replied: false,
|
|
6476
|
-
skippedReason: "turn cancelled"
|
|
6477
|
-
});
|
|
6478
|
-
markTurnClosed({
|
|
6479
|
-
conversation: args.conversation,
|
|
6480
|
-
nowMs: Date.now(),
|
|
6481
|
-
sessionId: args.turnId
|
|
6482
|
-
});
|
|
6483
|
-
if (pendingAuthorization) await deleteWebAuthorization({
|
|
6484
|
-
actorId: pendingAuthorization.actorId,
|
|
6485
|
-
conversationId: args.conversationId
|
|
6486
|
-
});
|
|
6487
|
-
await persistThreadStateById(args.conversationId, {
|
|
6488
|
-
conversation: args.conversation,
|
|
6489
|
-
sandboxRef: args.sandboxRef
|
|
6490
|
-
});
|
|
6491
|
-
await new ConversationTurnLifecycleService(getConversationEventStore()).complete({
|
|
6492
|
-
conversationId: args.conversationId,
|
|
6493
|
-
createdAtMs: Date.now(),
|
|
6494
|
-
outcome: "cancelled",
|
|
6495
|
-
turnId: args.turnId
|
|
6496
|
-
});
|
|
6497
|
-
await args.acknowledge();
|
|
6498
|
-
}
|
|
6499
|
-
/**
|
|
6500
|
-
* Return the author Identity id that every batched input shares.
|
|
6501
|
-
* A batch with more than one author has no single author yet.
|
|
6502
|
-
*/
|
|
6503
|
-
function sharedAuthorIdentityId(messages) {
|
|
6504
|
-
const ids = new Set(messages.map((message) => message.input.authorIdentityId));
|
|
6505
|
-
return ids.size === 1 ? [...ids][0] : void 0;
|
|
6506
|
-
}
|
|
6507
|
-
/**
|
|
6508
|
-
* Create the shared mailbox worker for web and event Turns.
|
|
6509
|
-
*/
|
|
6510
|
-
function createConversationTurnWorker(agentRunner, deliverMessage) {
|
|
6511
|
-
return async (context, resolved) => {
|
|
6512
|
-
if (resolved.kind === "mailbox") {
|
|
6513
|
-
const delayMs = getEventBatchDelayMs(resolved.batch.map((entry) => entry.message));
|
|
6514
|
-
if (delayMs > 0) return {
|
|
6515
|
-
status: "deferred",
|
|
6516
|
-
delayMs
|
|
6517
|
-
};
|
|
6518
|
-
}
|
|
6519
|
-
const lifecycle = new ConversationTurnLifecycleService(getConversationEventStore());
|
|
6520
|
-
const isResume = resolved.kind === "resume";
|
|
6521
|
-
let turnInputFacts;
|
|
6522
|
-
let inputs = [];
|
|
6523
|
-
let attachments = [];
|
|
6524
|
-
let turnId = "";
|
|
6525
|
-
let userMessageId = "";
|
|
6526
|
-
let startedAtMs = Date.now();
|
|
6527
|
-
let inputMessageIds = [];
|
|
6528
|
-
let eventMeta = {};
|
|
6529
|
-
let authorIdentityId;
|
|
6530
|
-
let webInputMessages = [];
|
|
6531
|
-
const storedConversation = await getConversationStore().get({ conversationId: context.conversationId });
|
|
6532
|
-
const mailboxDestination = resolved.kind === "mailbox" ? resolved.batch[0]?.message.destination : void 0;
|
|
6533
|
-
const destination = resolveConversationDestination({
|
|
6534
|
-
conversationId: context.conversationId,
|
|
6535
|
-
existing: context.destination ?? mailboxDestination ?? storedConversation?.destination
|
|
6536
|
-
});
|
|
6537
|
-
if (resolved.kind === "mailbox") {
|
|
6538
|
-
const first = resolved.batch[0];
|
|
6539
|
-
const messages = resolved.batch.map((entry) => entry.message);
|
|
6540
|
-
const firstMetadata = first.message.input.metadata;
|
|
6541
|
-
if (isEventMailboxMetadata(firstMetadata)) {
|
|
6542
|
-
inputs = renderEventBatchInputs(messages, await eventReviewItemInputs(messages)).map((text) => ({
|
|
6543
|
-
kind: "runtime",
|
|
6544
|
-
text
|
|
6545
|
-
}));
|
|
6546
|
-
eventMeta = eventBatchMessageMeta(messages);
|
|
6547
|
-
} else {
|
|
6548
|
-
inputs = await webTurnInputs(messages.map((message) => message.input));
|
|
6549
|
-
webInputMessages = resolved.batch.map((entry) => webConversationMessage(entry.message, entry.author));
|
|
6550
|
-
}
|
|
6551
|
-
attachments = resolved.batch.flatMap((entry) => readMessageAttachments(entry.message.input.attachments));
|
|
6552
|
-
startedAtMs = first.message.createdAtMs;
|
|
6553
|
-
userMessageId = first.message.inboundMessageId;
|
|
6554
|
-
turnId = buildDeterministicTurnId(userMessageId);
|
|
6555
|
-
inputMessageIds = resolved.batch.map((entry) => entry.message.inboundMessageId);
|
|
6556
|
-
authorIdentityId = sharedAuthorIdentityId(messages);
|
|
6557
|
-
turnInputFacts = first;
|
|
6558
|
-
} else turnId = resolved.turnId;
|
|
6559
|
-
const persisted = await getPersistedThreadState(context.conversationId);
|
|
6560
|
-
const conversation = coerceThreadConversationState(persisted);
|
|
6561
|
-
await hydrateConversationMessages({
|
|
6562
|
-
conversation,
|
|
6563
|
-
conversationId: context.conversationId
|
|
6564
|
-
});
|
|
6565
|
-
const savedTurn = isResume ? await getTurnRecord(context.conversationId, turnId) : void 0;
|
|
6566
|
-
let savedMessageIsEvent = false;
|
|
6567
|
-
if (isResume) {
|
|
6568
|
-
const userMessage = getTurnUserMessage(conversation, turnId);
|
|
6569
|
-
if (!userMessage) throw new Error(`Unable to locate the persisted user message for Turn "${turnId}"`);
|
|
6570
|
-
savedMessageIsEvent = isEventConversationMessage(userMessage);
|
|
6571
|
-
turnInputFacts = turnInputFactsFromConversationMessage(userMessage, {
|
|
6572
|
-
conversationId: context.conversationId,
|
|
6573
|
-
location: storedConversation?.location,
|
|
6574
|
-
savedActor: savedTurn?.actor,
|
|
6575
|
-
savedSource: savedTurn?.source,
|
|
6576
|
-
visibility: storedConversation?.visibility
|
|
6577
|
-
});
|
|
6578
|
-
const turnInputs = savedTurnInputMessages(conversation, userMessage, await lifecycle.loadInputMessageIds(context.conversationId, turnId));
|
|
6579
|
-
userMessageId = userMessage.id;
|
|
6580
|
-
inputs = savedMessageIsEvent ? [{
|
|
6581
|
-
kind: "runtime",
|
|
6582
|
-
text: userMessage.text
|
|
6583
|
-
}] : await webTurnInputs(turnInputs.map((message) => ({
|
|
6584
|
-
reviewItemChange: message.meta?.reviewItemChanges?.[0],
|
|
6585
|
-
text: message.text
|
|
6586
|
-
})));
|
|
6587
|
-
attachments = turnInputs.flatMap((message) => message.meta?.attachments ?? []);
|
|
6588
|
-
startedAtMs = userMessage.createdAtMs;
|
|
6589
|
-
inputMessageIds = turnInputs.map((message) => message.id);
|
|
6590
|
-
}
|
|
6591
|
-
if (!turnInputFacts) throw new Error(`Resumed Turn is missing an Actor for Conversation ${context.conversationId}`);
|
|
6592
|
-
const { actor, author } = turnInputFacts;
|
|
6593
|
-
const instructionInputs = instructionForInputs(inputs);
|
|
6594
|
-
const { text } = instructionInputs;
|
|
6595
|
-
let credentialSubject;
|
|
6596
|
-
if (actor.platform === "system") credentialSubject = resolved.kind === "mailbox" ? timerWatchCredentialSubject(context.conversationId, resolved.batch.map((entry) => entry.message)) : resumedTimerWatchCredentialSubject(context.conversationId, savedTurn?.credentialSubject);
|
|
6597
|
-
const source = sourceFromTurnInput({
|
|
6598
|
-
conversationId: context.conversationId,
|
|
6599
|
-
source: turnInputFacts.source,
|
|
6600
|
-
visibility: storedConversation?.visibility
|
|
6601
|
-
});
|
|
6602
|
-
const webActor = actor.platform === "web" ? actor : void 0;
|
|
6603
|
-
const conversationLocation = storedConversation?.location;
|
|
6604
|
-
const isEventTurn = source.kind === "event" || savedMessageIsEvent;
|
|
6605
|
-
const deliverToProvider = Boolean(conversationLocation) && isEventTurn;
|
|
6606
|
-
const surface = deliverToProvider ? "slack" : "api";
|
|
6607
|
-
const inputTelemetry = resolved.kind === "mailbox" ? turnInputTelemetry(resolved.batch.map((entry) => entry.message)) : void 0;
|
|
6608
|
-
const turnTrace = inputTelemetry ?? (savedTurn?.traceContext ? { traceContexts: [savedTurn.traceContext] } : void 0);
|
|
6609
|
-
return await withTurnSpan({
|
|
6610
|
-
conversationId: context.conversationId,
|
|
6611
|
-
platform: actor.platform,
|
|
6612
|
-
...webActor ? {
|
|
6613
|
-
userId: webActor.userId,
|
|
6614
|
-
...webActor.userName ? { userName: webActor.userName } : void 0
|
|
6615
|
-
} : void 0
|
|
6616
|
-
}, turnTrace, async (setTurnSpanAttributes) => {
|
|
6617
|
-
if (inputTelemetry) setTurnSpanAttributes(getTurnInputSpanAttributes(inputTelemetry, Date.now()));
|
|
6618
|
-
let acknowledged = isResume || context.attempt.messages.length === 0;
|
|
6619
|
-
const acknowledge = async () => {
|
|
6620
|
-
if (acknowledged) return;
|
|
6621
|
-
try {
|
|
6622
|
-
await context.attempt.ack();
|
|
6623
|
-
} catch {
|
|
6624
|
-
throw new TurnInputCommitLostError(`Conversation work lease lost before mailbox Message acknowledgement for ${context.conversationId}`);
|
|
6625
|
-
}
|
|
6626
|
-
acknowledged = true;
|
|
6627
|
-
};
|
|
6628
|
-
let sandboxRef = getPersistedSandboxState(persisted);
|
|
6629
|
-
const initialSandboxRef = sandboxRef;
|
|
6630
|
-
const stopSignal = context.stopSignal?.();
|
|
6631
|
-
const completeCancelledTurn = async () => {
|
|
6632
|
-
try {
|
|
6633
|
-
await completeCancelledConversationTurn({
|
|
6634
|
-
acknowledge,
|
|
6635
|
-
conversation,
|
|
6636
|
-
conversationId: context.conversationId,
|
|
6637
|
-
sandboxRef,
|
|
6638
|
-
turnId,
|
|
6639
|
-
userMessageId
|
|
6640
|
-
});
|
|
6641
|
-
} catch (error) {
|
|
6642
|
-
if (hasLostTurnInputCommit(error)) return { status: "lost_lease" };
|
|
6643
|
-
throw error;
|
|
6644
|
-
}
|
|
6645
|
-
return { status: "completed" };
|
|
6646
|
-
};
|
|
6647
|
-
if (isResume) {
|
|
6648
|
-
if (stopSignal?.aborted) return await completeCancelledTurn();
|
|
6649
|
-
} else {
|
|
6650
|
-
for (const [index, message] of webInputMessages.entries()) upsertConversationMessage(conversation, index === 0 ? {
|
|
6651
|
-
...message,
|
|
6652
|
-
meta: {
|
|
6653
|
-
...message.meta,
|
|
6654
|
-
replied: false
|
|
6655
|
-
}
|
|
6656
|
-
} : message);
|
|
6657
|
-
if (webInputMessages.length === 0) upsertConversationMessage(conversation, {
|
|
6658
|
-
id: userMessageId,
|
|
6659
|
-
role: "user",
|
|
6660
|
-
text: normalizeConversationText(text),
|
|
6661
|
-
createdAtMs: startedAtMs,
|
|
6662
|
-
author,
|
|
6663
|
-
...authorIdentityId ? { authorIdentityId } : void 0,
|
|
6664
|
-
meta: {
|
|
6665
|
-
...attachments.length ? { attachments } : void 0,
|
|
6666
|
-
explicitMention: true,
|
|
6667
|
-
replied: false,
|
|
6668
|
-
...eventMeta
|
|
6669
|
-
}
|
|
6670
|
-
});
|
|
6671
|
-
await persistConversationMessages({
|
|
6672
|
-
conversation,
|
|
6673
|
-
conversationId: context.conversationId
|
|
6674
|
-
});
|
|
6675
|
-
await lifecycle.start({
|
|
6676
|
-
conversationId: context.conversationId,
|
|
6677
|
-
createdAtMs: Date.now(),
|
|
6678
|
-
inputMessageIds,
|
|
6679
|
-
surface,
|
|
6680
|
-
turnId
|
|
6681
|
-
});
|
|
6682
|
-
if (stopSignal?.aborted) return await completeCancelledTurn();
|
|
6683
|
-
startActiveTurn({
|
|
6684
|
-
conversation,
|
|
6685
|
-
nextTurnId: turnId
|
|
6686
|
-
});
|
|
6687
|
-
}
|
|
6688
|
-
let currentRunId;
|
|
6689
|
-
let assistantMessageDelivered = false;
|
|
6690
|
-
let failureCode = "persistence_failed";
|
|
6691
|
-
let modelFailureEventId;
|
|
6692
|
-
let modelFailureCaptureAttempted = false;
|
|
6693
|
-
let completedSuccessfully = false;
|
|
6694
|
-
const deliverAssistantMessage = async (value) => {
|
|
6695
|
-
const agentMessage = typeof value === "string" ? void 0 : value;
|
|
6696
|
-
const decision = agentMessage ? decideReply(agentMessage) : void 0;
|
|
6697
|
-
const replyText = typeof value === "string" ? value : decision?.kind === "deliver" ? decision.text : void 0;
|
|
6698
|
-
if (!replyText?.trim()) return;
|
|
6699
|
-
failureCode = "delivery_failed";
|
|
6700
|
-
const cards = await loadPendingMessageCards(context.conversationId);
|
|
6701
|
-
const quiet = decision?.kind === "deliver" && decision.quiet === true && isEventTurn && cards.length === 0;
|
|
6702
|
-
let deliveryResult;
|
|
6703
|
-
if (deliverToProvider && !quiet) {
|
|
6704
|
-
if (!conversationLocation || !deliverMessage) throw new Error(`Conversation ${context.conversationId} cannot deliver to its Location`);
|
|
6705
|
-
deliveryResult = await deliverMessage({
|
|
6706
|
-
cards,
|
|
6707
|
-
conversationId: context.conversationId,
|
|
6708
|
-
location: conversationLocation,
|
|
6709
|
-
text: replyText
|
|
6710
|
-
});
|
|
6711
|
-
}
|
|
6712
|
-
await commitAssistantMessage({
|
|
6713
|
-
cards,
|
|
6714
|
-
...agentMessage ? { agentMessage } : void 0,
|
|
6715
|
-
conversation,
|
|
6716
|
-
conversationId: context.conversationId,
|
|
6717
|
-
...deliveryResult ? { deliveryResult } : void 0,
|
|
6718
|
-
...quiet ? { quiet } : void 0,
|
|
6719
|
-
sessionId: turnId,
|
|
6720
|
-
...deliveryResult ? { source: "slack" } : source.kind === "web" ? { source: "web" } : void 0,
|
|
6721
|
-
text: replyText,
|
|
6722
|
-
userMessageId
|
|
6723
|
-
});
|
|
6724
|
-
assistantMessageDelivered = true;
|
|
6725
|
-
failureCode = "agent_run_failed";
|
|
6726
|
-
};
|
|
6727
|
-
try {
|
|
6728
|
-
if (stopSignal?.aborted) return await completeCancelledTurn();
|
|
6729
|
-
if (!isResume) {
|
|
6730
|
-
const pendingAuthorizationActorId = conversation.processing.pendingAuth?.actorId;
|
|
6731
|
-
const superseded = (await listActiveMailboxTurns(context.conversationId)).filter((record) => record.turnId !== turnId);
|
|
6732
|
-
for (const stale of superseded) {
|
|
6733
|
-
if (stopSignal?.aborted) return await completeCancelledTurn();
|
|
6734
|
-
await abandonTurnRecord({
|
|
6735
|
-
conversationId: context.conversationId,
|
|
6736
|
-
turnId: stale.turnId,
|
|
6737
|
-
errorMessage: "Turn superseded by new input"
|
|
6738
|
-
});
|
|
6739
|
-
markTurnClosed({
|
|
6740
|
-
conversation,
|
|
6741
|
-
nowMs: Date.now(),
|
|
6742
|
-
sessionId: stale.turnId
|
|
6743
|
-
});
|
|
6744
|
-
}
|
|
6745
|
-
if (superseded.some((record) => record.state === "paused" && record.resumeReason === "auth") && pendingAuthorizationActorId) await deleteWebAuthorization({
|
|
6746
|
-
actorId: pendingAuthorizationActorId,
|
|
6747
|
-
conversationId: context.conversationId
|
|
6748
|
-
});
|
|
6749
|
-
}
|
|
6750
|
-
await persistThreadStateById(context.conversationId, { conversation });
|
|
6751
|
-
if (stopSignal?.aborted) return await completeCancelledTurn();
|
|
6752
|
-
const piMessages = await loadProjection({ conversationId: context.conversationId });
|
|
6753
|
-
failureCode = "agent_run_failed";
|
|
6754
|
-
currentRunId = `conversation-run:${stableHex(turnId, String(startedAtMs))}`;
|
|
6755
|
-
setTags({ runId: currentRunId });
|
|
6756
|
-
const outcome = await executeTurn(agentRunner, {
|
|
6757
|
-
conversationId: context.conversationId,
|
|
6758
|
-
turnId,
|
|
6759
|
-
runId: currentRunId,
|
|
6760
|
-
instruction: {
|
|
6761
|
-
...instructionInputs,
|
|
6762
|
-
storedAttachments: attachments,
|
|
6763
|
-
context: buildConversationContext(conversation, { excludeMessageIds: inputMessageIds })
|
|
6764
|
-
},
|
|
6765
|
-
history: piMessages,
|
|
6766
|
-
actor,
|
|
6767
|
-
credentialContext: credentialContextForActor(actor, credentialSubject),
|
|
6768
|
-
destination,
|
|
6769
|
-
source,
|
|
6770
|
-
...conversationLocation ? { location: conversationLocation } : void 0,
|
|
6771
|
-
surface,
|
|
6772
|
-
...stopSignal ? { signal: stopSignal } : void 0,
|
|
6773
|
-
...webActor ? { authorization: createWebAuthorization({
|
|
6774
|
-
actorId: webActor.userId,
|
|
6775
|
-
conversationId: context.conversationId
|
|
6776
|
-
}) } : { disabledFeatures: ["interactive-auth"] },
|
|
6777
|
-
state: {
|
|
6778
|
-
pendingAuth: conversation.processing.pendingAuth,
|
|
6779
|
-
sandboxRef
|
|
6780
|
-
},
|
|
6781
|
-
delivery: deliverAssistantMessage,
|
|
6782
|
-
durability: {
|
|
6783
|
-
...webActor ? { drainSteeringMessages: createWebSteeringDrain({
|
|
6784
|
-
actor: webActor,
|
|
6785
|
-
author,
|
|
6786
|
-
context,
|
|
6787
|
-
conversation,
|
|
6788
|
-
turnId
|
|
6789
|
-
}) } : void 0,
|
|
6790
|
-
onInputCommitted: acknowledge,
|
|
6791
|
-
shouldYield: context.shouldYield,
|
|
6792
|
-
onSandboxRefChanged: async (nextSandboxRef) => {
|
|
6793
|
-
sandboxRef = nextSandboxRef;
|
|
6794
|
-
await persistThreadStateById(context.conversationId, {
|
|
6795
|
-
conversation,
|
|
6796
|
-
sandboxRef
|
|
6797
|
-
});
|
|
6798
|
-
},
|
|
6799
|
-
recordPendingAuth: async (pendingAuth) => {
|
|
6800
|
-
conversation.processing.pendingAuth = pendingAuth;
|
|
6801
|
-
await persistThreadStateById(context.conversationId, {
|
|
6802
|
-
conversation,
|
|
6803
|
-
sandboxRef
|
|
6804
|
-
});
|
|
6805
|
-
}
|
|
6806
|
-
}
|
|
6807
|
-
}, async (result) => {
|
|
6808
|
-
if (stopSignal?.aborted) throw stopSignal.reason ?? new DOMException("Turn cancelled", "AbortError");
|
|
6809
|
-
modelFailureCaptureAttempted = result.diagnostics.outcome !== "success";
|
|
6810
|
-
const finalized = finalizeFailedTurnReplyWithEvent({
|
|
6811
|
-
reply: result,
|
|
6812
|
-
logException
|
|
6813
|
-
});
|
|
6814
|
-
const modelFailureReason = finalized.failureReason;
|
|
6815
|
-
const reply = finalized.reply;
|
|
6816
|
-
modelFailureEventId = finalized.eventId;
|
|
6817
|
-
if (reply.diagnostics.outcome !== "success") await deliverAssistantMessage(reply.text);
|
|
6818
|
-
const completedState = buildDeliveredTurnStatePatch({
|
|
6819
|
-
conversation,
|
|
6820
|
-
reply,
|
|
6821
|
-
sessionId: turnId,
|
|
6822
|
-
userMessageId
|
|
6823
|
-
});
|
|
6824
|
-
await persistThreadStateById(context.conversationId, {
|
|
6825
|
-
conversation: completedState.conversation,
|
|
6826
|
-
sandboxRef: reply.sandboxRef ?? sandboxRef
|
|
6827
|
-
});
|
|
6828
|
-
if (reply.piMessages?.length) {
|
|
6829
|
-
const latest = await getTurnRecord(context.conversationId, turnId);
|
|
6830
|
-
await saveTurnCheckpoint({
|
|
6831
|
-
mode: "completed",
|
|
6832
|
-
conversationId: context.conversationId,
|
|
6833
|
-
turnId,
|
|
6834
|
-
sliceId: latest?.sliceId ?? 1,
|
|
6835
|
-
messages: reply.piMessages,
|
|
6836
|
-
durationMs: reply.diagnostics.durationMs,
|
|
6837
|
-
usage: reply.diagnostics.usage,
|
|
6838
|
-
destination,
|
|
6839
|
-
source,
|
|
6840
|
-
actor,
|
|
6841
|
-
surface
|
|
6842
|
-
});
|
|
6843
|
-
}
|
|
6844
|
-
const automatedTurnLimit = await recordFinishedTurnForAutomatedLimit({
|
|
6845
|
-
conversationId: context.conversationId,
|
|
6846
|
-
maxTurns: botConfig.maxConsecutiveAutomatedTurns,
|
|
6847
|
-
source
|
|
6848
|
-
});
|
|
6849
|
-
await maybePostAutomatedTurnLimitNotice({
|
|
6850
|
-
conversationId: context.conversationId,
|
|
6851
|
-
maxTurns: botConfig.maxConsecutiveAutomatedTurns,
|
|
6852
|
-
source,
|
|
6853
|
-
update: automatedTurnLimit
|
|
6854
|
-
});
|
|
6855
|
-
completedSuccessfully = reply.diagnostics.outcome === "success";
|
|
6856
|
-
return completedSuccessfully ? { outcome: assistantMessageDelivered ? "success" : "no_reply" } : {
|
|
6857
|
-
...modelFailureEventId ? { eventId: modelFailureEventId } : void 0,
|
|
6858
|
-
failureCode: "model_execution_failed",
|
|
6859
|
-
...modelFailureReason ? { failureReason: modelFailureReason } : void 0,
|
|
6860
|
-
outcome: "failed"
|
|
6861
|
-
};
|
|
6862
|
-
});
|
|
6863
|
-
if (outcome.status !== "completed" && stopSignal?.aborted) return await completeCancelledTurn();
|
|
6864
|
-
if (outcome.status === "suspended") return { status: "yielded" };
|
|
6865
|
-
if (outcome.status === "awaiting_auth") {
|
|
6866
|
-
completeAuthPauseTurn({
|
|
6867
|
-
conversation,
|
|
6868
|
-
sessionId: turnId
|
|
6869
|
-
});
|
|
6870
|
-
await persistThreadStateById(context.conversationId, {
|
|
6871
|
-
conversation,
|
|
6872
|
-
sandboxRef
|
|
6873
|
-
});
|
|
6874
|
-
await acknowledge();
|
|
6875
|
-
return { status: "paused" };
|
|
6876
|
-
}
|
|
6877
|
-
if (completedSuccessfully) try {
|
|
6878
|
-
await scheduleSessionCompletedPluginTasks({
|
|
6879
|
-
conversationId: context.conversationId,
|
|
6880
|
-
sessionId: turnId
|
|
6881
|
-
}, { send: async (message) => {
|
|
6882
|
-
try {
|
|
6883
|
-
await processPluginTask(message);
|
|
6884
|
-
} catch (error) {
|
|
6885
|
-
logException(error, "conversation.plugin.session_completion_task.failed", {
|
|
6886
|
-
conversationId: context.conversationId,
|
|
6887
|
-
pluginName: message.plugin,
|
|
6888
|
-
taskName: message.name,
|
|
6889
|
-
turnId
|
|
6890
|
-
});
|
|
6891
|
-
}
|
|
6892
|
-
} });
|
|
6893
|
-
} catch (error) {
|
|
6894
|
-
logException(error, "conversation.plugin.session_completion_task.failed", {
|
|
6895
|
-
conversationId: context.conversationId,
|
|
6896
|
-
turnId
|
|
6897
|
-
});
|
|
6898
|
-
}
|
|
6899
|
-
await acknowledge();
|
|
6900
|
-
return { status: "completed" };
|
|
6901
|
-
} catch (error) {
|
|
6902
|
-
const failure = error instanceof AgentRunError ? error.cause : error;
|
|
6903
|
-
if (hasLostTurnInputCommit(failure)) return { status: "lost_lease" };
|
|
6904
|
-
if (stopSignal?.aborted) return await completeCancelledTurn();
|
|
6905
|
-
if (!context.attempt.isFinalAttempt) throw failure;
|
|
6906
|
-
const failureEventId = modelFailureCaptureAttempted && failureCode === "agent_run_failed" ? modelFailureEventId : captureConversationTurnFailure({
|
|
6907
|
-
conversationId: context.conversationId,
|
|
6908
|
-
error: failure,
|
|
6909
|
-
failureCode,
|
|
6910
|
-
runId: currentRunId,
|
|
6911
|
-
turnId
|
|
6912
|
-
});
|
|
6913
|
-
try {
|
|
6914
|
-
markTurnFailed({
|
|
6915
|
-
conversation,
|
|
6916
|
-
nowMs: Date.now(),
|
|
6917
|
-
sessionId: turnId,
|
|
6918
|
-
userMessageId,
|
|
6919
|
-
markConversationMessage
|
|
6920
|
-
});
|
|
6921
|
-
await persistThreadStateById(context.conversationId, {
|
|
6922
|
-
conversation,
|
|
6923
|
-
sandboxRef: initialSandboxRef ?? null
|
|
6924
|
-
});
|
|
6925
|
-
} catch (persistenceError) {
|
|
6926
|
-
captureConversationTurnFailure({
|
|
6927
|
-
conversationId: context.conversationId,
|
|
6928
|
-
error: persistenceError,
|
|
6929
|
-
failureCode: "persistence_failed",
|
|
6930
|
-
runId: currentRunId,
|
|
6931
|
-
turnId
|
|
6932
|
-
});
|
|
6933
|
-
}
|
|
6934
|
-
await lifecycle.fail({
|
|
6935
|
-
conversationId: context.conversationId,
|
|
6936
|
-
createdAtMs: Date.now(),
|
|
6937
|
-
...failureEventId ? { eventId: failureEventId } : void 0,
|
|
6938
|
-
failureCode,
|
|
6939
|
-
turnId
|
|
6940
|
-
});
|
|
6941
|
-
await acknowledge();
|
|
6942
|
-
return { status: "completed" };
|
|
6943
|
-
}
|
|
6944
|
-
});
|
|
6945
|
-
};
|
|
6946
|
-
}
|
|
6947
6226
|
// src/chat/providers/slack/system-turn.ts
|
|
6948
6227
|
/**
|
|
6949
6228
|
* Deliver system Turn output to Slack without a webhook Message.
|
|
@@ -7028,15 +6307,19 @@ function createConversationWork(options) {
|
|
|
7028
6307
|
routingContext: buildDispatchRoutingContext(dispatch),
|
|
7029
6308
|
wakePausedTurn: pausedTurns.wake,
|
|
7030
6309
|
...scheduleCompletedPluginTasks ? { scheduleSessionCompletedPluginTasks: scheduleCompletedPluginTasks } : void 0
|
|
7031
|
-
}, {
|
|
6310
|
+
}, {
|
|
6311
|
+
checkIn: hooks.checkIn,
|
|
6312
|
+
shouldYield: hooks.shouldYield
|
|
6313
|
+
});
|
|
7032
6314
|
},
|
|
7033
6315
|
runTurn: runtime.runDispatchTurn
|
|
7034
6316
|
});
|
|
6317
|
+
const enqueueResult = async (invocation) => await enqueueAgentInvocationResult(invocation, {
|
|
6318
|
+
queue: options.queue,
|
|
6319
|
+
state: options.state
|
|
6320
|
+
});
|
|
7035
6321
|
const childWorker = createChildConversationWorker(options.agentRunner, {
|
|
7036
|
-
enqueueResult
|
|
7037
|
-
queue: options.queue,
|
|
7038
|
-
state: options.state
|
|
7039
|
-
}),
|
|
6322
|
+
enqueueResult,
|
|
7040
6323
|
maxAgentDepth: botConfig.maxAgentDepth,
|
|
7041
6324
|
queue: options.queue,
|
|
7042
6325
|
state: options.state
|
|
@@ -7069,7 +6352,17 @@ function createConversationWork(options) {
|
|
|
7069
6352
|
const stopped = await skipInputAfterConversationStop(attemptContext);
|
|
7070
6353
|
if ("skipped" in stopped) return stopped.skipped;
|
|
7071
6354
|
const { context } = stopped;
|
|
7072
|
-
|
|
6355
|
+
const conversation = await options.conversationStore.get({ conversationId: context.conversationId });
|
|
6356
|
+
if (conversation?.kind === "thread") {
|
|
6357
|
+
const threadTurn = await resolveThreadTurnWork(context);
|
|
6358
|
+
if (!threadTurn) return await childWorker(context);
|
|
6359
|
+
if (threadTurn.kind === "mailbox") await endActiveAgentInvocations(context.conversationId, {
|
|
6360
|
+
enqueueResult,
|
|
6361
|
+
errorMessage: "A person sent a Message in this Thread, so this task ended without a result. Send messageAgent again if you still need this work."
|
|
6362
|
+
});
|
|
6363
|
+
return await conversationTurnWorker(context, threadTurn);
|
|
6364
|
+
}
|
|
6365
|
+
if (conversation?.parentConversationId) return await childWorker(context);
|
|
7073
6366
|
const readStopSignal = context.stopSignal;
|
|
7074
6367
|
let stopSignal;
|
|
7075
6368
|
const stopLateChildAgents = async () => {
|
|
@@ -7197,84 +6490,55 @@ async function markConversationRead(viewer, conversationId, body) {
|
|
|
7197
6490
|
return await readConversationReadPosition(viewer, conversationId);
|
|
7198
6491
|
}
|
|
7199
6492
|
// src/api/conversations/archive.ts
|
|
7200
|
-
async function setViewerArchive(args) {
|
|
7201
|
-
const executor = getSqlExecutor();
|
|
7202
|
-
return await executor.transaction(async () => {
|
|
7203
|
-
const db = executor.db();
|
|
7204
|
-
const [root] = await db.select({ lastActivityAt: juniorConversations.lastActivityAt }).from(juniorConversations).where(eq(juniorConversations.conversationId, args.rootConversationId)).limit(1).for("update");
|
|
7205
|
-
if (!root) return { status: "missing" };
|
|
7206
|
-
if (args.archived) {
|
|
7207
|
-
if (root.lastActivityAt.getTime() !== Date.parse(args.lastSeenAt)) return { status: "conflict" };
|
|
7208
|
-
const archivedAt = /* @__PURE__ */ new Date();
|
|
7209
|
-
const lastMessageAt = new Date(args.lastSeenAt);
|
|
7210
|
-
await db.with(conversationDetailTouch(db, [args.rootConversationId])).insert(juniorConversationParticipants).values({
|
|
7211
|
-
archivedAt,
|
|
7212
|
-
lastMessageAt,
|
|
7213
|
-
rootConversationId: args.rootConversationId,
|
|
7214
|
-
userId: args.userId
|
|
7215
|
-
}).onConflictDoUpdate({
|
|
7216
|
-
target: [juniorConversationParticipants.userId, juniorConversationParticipants.rootConversationId],
|
|
7217
|
-
set: {
|
|
7218
|
-
archivedAt,
|
|
7219
|
-
pinnedAt: null,
|
|
7220
|
-
pinPosition: null,
|
|
7221
|
-
lastMessageAt: sql`greatest(${juniorConversationParticipants.lastMessageAt}, excluded.last_message_at)`
|
|
7222
|
-
}
|
|
7223
|
-
});
|
|
7224
|
-
return {
|
|
7225
|
-
archivedAt: archivedAt.toISOString(),
|
|
7226
|
-
status: "updated"
|
|
7227
|
-
};
|
|
7228
|
-
}
|
|
7229
|
-
await db.with(conversationDetailTouch(db, [args.rootConversationId])).update(juniorConversationParticipants).set({
|
|
7230
|
-
archivedAt: null,
|
|
7231
|
-
autoArchive: false
|
|
7232
|
-
}).where(and(eq(juniorConversationParticipants.userId, args.userId), eq(juniorConversationParticipants.rootConversationId, args.rootConversationId), isNotNull(juniorConversationParticipants.archivedAt)));
|
|
7233
|
-
return {
|
|
7234
|
-
archivedAt: null,
|
|
7235
|
-
status: "updated"
|
|
7236
|
-
};
|
|
7237
|
-
});
|
|
7238
|
-
}
|
|
7239
6493
|
/**
|
|
7240
|
-
* Archive or restore one child for everyone. Archive
|
|
7241
|
-
* descendant is unarchived, unless `applyToChildren`
|
|
7242
|
-
* Restore changes only this
|
|
7243
|
-
* descendants archived with it, and it
|
|
7244
|
-
* archived.
|
|
6494
|
+
* Archive or restore one Conversation, root or child, for everyone. Archive
|
|
6495
|
+
* refuses while any descendant is unarchived, unless `applyToChildren`
|
|
6496
|
+
* archives them too. Restore changes only this Conversation unless
|
|
6497
|
+
* `applyToChildren` also restores the descendants archived with it, and it
|
|
6498
|
+
* refuses while an ancestor is archived.
|
|
7245
6499
|
*/
|
|
7246
|
-
async function
|
|
6500
|
+
async function setArchive(args) {
|
|
7247
6501
|
const executor = getSqlExecutor();
|
|
7248
6502
|
return await executor.transaction(async () => {
|
|
7249
6503
|
const db = executor.db();
|
|
7250
|
-
const [
|
|
6504
|
+
const [target] = await db.select({
|
|
7251
6505
|
lastActivityAt: juniorConversations.lastActivityAt,
|
|
7252
6506
|
rootConversationId: juniorConversations.rootConversationId
|
|
7253
6507
|
}).from(juniorConversations).where(eq(juniorConversations.conversationId, args.conversationId)).limit(1).for("update");
|
|
7254
|
-
if (!
|
|
7255
|
-
if (args.archived &&
|
|
7256
|
-
const
|
|
6508
|
+
if (!target) return { status: "missing" };
|
|
6509
|
+
if (args.archived && target.lastActivityAt.getTime() !== Date.parse(args.lastSeenAt)) return { status: "conflict" };
|
|
6510
|
+
const rootConversationId = target.rootConversationId ?? args.conversationId;
|
|
6511
|
+
const tree = await readConversationTrees(db, [rootConversationId]);
|
|
7257
6512
|
const descendants = conversationDescendants(tree, args.conversationId);
|
|
7258
6513
|
if (args.archived) {
|
|
7259
|
-
const unarchived = descendants.filter((node) => !node.
|
|
6514
|
+
const unarchived = descendants.filter((node) => !node.archivedAt);
|
|
7260
6515
|
if (unarchived.length > 0 && !args.applyToChildren) return {
|
|
7261
6516
|
status: "unarchived_children",
|
|
7262
6517
|
unarchivedChildCount: unarchived.length
|
|
7263
6518
|
};
|
|
7264
6519
|
const archivedAt = /* @__PURE__ */ new Date();
|
|
7265
|
-
await
|
|
6520
|
+
await setArchivedAt(db, [args.conversationId, ...unarchived.map((node) => node.conversationId)], archivedAt);
|
|
7266
6521
|
return {
|
|
7267
6522
|
archivedAt: archivedAt.toISOString(),
|
|
7268
6523
|
status: "updated"
|
|
7269
6524
|
};
|
|
7270
6525
|
}
|
|
7271
|
-
const archivedAncestor = conversationAncestors(tree, args.conversationId).filter((node) => node.
|
|
6526
|
+
const archivedAncestor = conversationAncestors(tree, args.conversationId).filter((node) => node.archivedAt).at(-1);
|
|
7272
6527
|
if (archivedAncestor) return {
|
|
7273
6528
|
archivedAncestorId: archivedAncestor.conversationId,
|
|
7274
6529
|
status: "archived_ancestor"
|
|
7275
6530
|
};
|
|
7276
|
-
const archivedAt = tree.get(args.conversationId)?.
|
|
7277
|
-
await
|
|
6531
|
+
const archivedAt = tree.get(args.conversationId)?.archivedAt?.getTime();
|
|
6532
|
+
await setArchivedAt(db, [args.conversationId, ...args.applyToChildren && archivedAt !== void 0 ? descendants.filter((node) => node.archivedAt?.getTime() === archivedAt).map((node) => node.conversationId) : []], null);
|
|
6533
|
+
if (args.conversationId === rootConversationId) await db.insert(juniorConversationParticipants).values({
|
|
6534
|
+
autoArchive: false,
|
|
6535
|
+
lastMessageAt: target.lastActivityAt,
|
|
6536
|
+
rootConversationId,
|
|
6537
|
+
userId: args.userId
|
|
6538
|
+
}).onConflictDoUpdate({
|
|
6539
|
+
target: [juniorConversationParticipants.userId, juniorConversationParticipants.rootConversationId],
|
|
6540
|
+
set: { autoArchive: false }
|
|
6541
|
+
});
|
|
7278
6542
|
return {
|
|
7279
6543
|
archivedAt: null,
|
|
7280
6544
|
status: "updated"
|
|
@@ -7282,33 +6546,21 @@ async function setChildArchive(args) {
|
|
|
7282
6546
|
});
|
|
7283
6547
|
}
|
|
7284
6548
|
/**
|
|
7285
|
-
* Archive or restore one
|
|
7286
|
-
*
|
|
7287
|
-
* child rows and ignores `applyToChildren`. A child archive, Thread or Task,
|
|
7288
|
-
* applies to everyone and follows the rules of `setChildArchive`.
|
|
6549
|
+
* Archive or restore one Conversation for everyone. Only a participant may
|
|
6550
|
+
* do it. The rules are those of `setArchive`.
|
|
7289
6551
|
*/
|
|
7290
6552
|
async function archiveConversation(viewer, conversationId, body) {
|
|
7291
6553
|
if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(404, "Conversation not found.");
|
|
7292
|
-
const
|
|
7293
|
-
kind: juniorConversations.kind,
|
|
7294
|
-
parentConversationId: juniorConversations.parentConversationId
|
|
7295
|
-
}).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId)).limit(1);
|
|
7296
|
-
if (!target) throwApiError(404, "Conversation not found.");
|
|
7297
|
-
const isRoot = conversationKindFromRow(target) === "root";
|
|
7298
|
-
const result = isRoot ? await setViewerArchive({
|
|
7299
|
-
archived: body.archived,
|
|
7300
|
-
lastSeenAt: body.lastSeenAt,
|
|
7301
|
-
rootConversationId: conversationId,
|
|
7302
|
-
userId: viewer.id
|
|
7303
|
-
}) : await setChildArchive({
|
|
6554
|
+
const result = await setArchive({
|
|
7304
6555
|
applyToChildren: body.applyToChildren ?? false,
|
|
7305
6556
|
archived: body.archived,
|
|
7306
6557
|
conversationId,
|
|
7307
|
-
lastSeenAt: body.lastSeenAt
|
|
6558
|
+
lastSeenAt: body.lastSeenAt,
|
|
6559
|
+
userId: viewer.id
|
|
7308
6560
|
});
|
|
7309
6561
|
switch (result.status) {
|
|
7310
6562
|
case "updated":
|
|
7311
|
-
if (body.archived
|
|
6563
|
+
if (body.archived) await markConversationRead(viewer, conversationId, { lastReadSeq: Number.MAX_SAFE_INTEGER });
|
|
7312
6564
|
return { archivedAt: result.archivedAt };
|
|
7313
6565
|
case "missing": throwApiError(404, "Conversation not found.");
|
|
7314
6566
|
case "conflict": throwApiError(409, "Conversation received new activity.");
|
|
@@ -7377,17 +6629,17 @@ async function readMentionedPeople(executor, tenantId, userIds) {
|
|
|
7377
6629
|
return !person?.fullName && !person?.slackUserName;
|
|
7378
6630
|
});
|
|
7379
6631
|
if (tenantId && unnamed.length > 0) {
|
|
7380
|
-
const profiles = await
|
|
7381
|
-
|
|
7382
|
-
const profile = profiles
|
|
7383
|
-
if (!profile?.fullName && !profile?.userName)
|
|
6632
|
+
const profiles = await lookupSlackUserNames(tenantId, unnamed);
|
|
6633
|
+
for (const id of unnamed) {
|
|
6634
|
+
const profile = profiles.get(id);
|
|
6635
|
+
if (!profile?.fullName && !profile?.userName) continue;
|
|
7384
6636
|
people.set(id, {
|
|
7385
6637
|
...people.get(id),
|
|
7386
6638
|
slackUserId: id,
|
|
7387
6639
|
...profile.fullName ? { fullName: profile.fullName } : void 0,
|
|
7388
6640
|
...profile.userName ? { slackUserName: profile.userName } : void 0
|
|
7389
6641
|
});
|
|
7390
|
-
}
|
|
6642
|
+
}
|
|
7391
6643
|
}
|
|
7392
6644
|
return people;
|
|
7393
6645
|
}
|
|
@@ -7668,7 +6920,7 @@ async function createConversationForViewer(viewer, body, services) {
|
|
|
7668
6920
|
async function appendConversationMessageForViewer(viewer, conversationId, body, services) {
|
|
7669
6921
|
const conversation = await getConversationStore().get({ conversationId });
|
|
7670
6922
|
if (!conversation) throwApiError(404, "Conversation not found.");
|
|
7671
|
-
if (!acceptsWebMessages(
|
|
6923
|
+
if (!acceptsWebMessages(conversation)) throwApiError(409, "Conversation does not accept web messages.");
|
|
7672
6924
|
if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(403, "Only conversation participants can add messages.");
|
|
7673
6925
|
const images = parseImages(body.images);
|
|
7674
6926
|
const actor = actorFromViewer(viewer);
|
|
@@ -8390,7 +7642,7 @@ async function attachActivityPreviewMentions(executor, previews) {
|
|
|
8390
7642
|
*/
|
|
8391
7643
|
function selectConversationRecords(db) {
|
|
8392
7644
|
return db.select({
|
|
8393
|
-
conversation:
|
|
7645
|
+
conversation: juniorConversations,
|
|
8394
7646
|
location: juniorDestinations,
|
|
8395
7647
|
identityDisplayName: juniorIdentities.displayName,
|
|
8396
7648
|
identityEmail: juniorIdentities.email,
|
|
@@ -8429,7 +7681,7 @@ function conversationFromRecordRow(row) {
|
|
|
8429
7681
|
...value.executionUpdatedAt ? { updatedAtMs: value.executionUpdatedAt.getTime() } : void 0
|
|
8430
7682
|
},
|
|
8431
7683
|
...value.parentConversationId ? { parentConversationId: value.parentConversationId } : void 0,
|
|
8432
|
-
...value.
|
|
7684
|
+
...value.archivedAt ? { archivedAtMs: value.archivedAt.getTime() } : void 0,
|
|
8433
7685
|
...actor ? { actor } : void 0,
|
|
8434
7686
|
...location ? { location } : void 0,
|
|
8435
7687
|
...value.channelName ? { channelName: value.channelName } : void 0,
|
|
@@ -8594,7 +7846,6 @@ function conversationSummaryFromStoredConversation(args) {
|
|
|
8594
7846
|
}),
|
|
8595
7847
|
kind: conversation.kind,
|
|
8596
7848
|
...conversation.parentConversationId ? { parentConversationId: conversation.parentConversationId } : void 0,
|
|
8597
|
-
...conversation.kind !== "root" ? { childArchivedAt: conversation.childArchivedAtMs === void 0 ? null : new Date(conversation.childArchivedAtMs).toISOString() } : void 0,
|
|
8598
7849
|
isParticipant: args.access?.isParticipant ?? false,
|
|
8599
7850
|
...visibility ? { visibility } : void 0,
|
|
8600
7851
|
lastProgressAt: new Date(conversation.execution.updatedAtMs ?? conversation.updatedAtMs).toISOString(),
|
|
@@ -8607,7 +7858,7 @@ function conversationSummaryFromStoredConversation(args) {
|
|
|
8607
7858
|
...args.childAgentTotals ? { childAgentTotals: args.childAgentTotals } : void 0,
|
|
8608
7859
|
...actorIdentity ? { actorIdentity } : void 0,
|
|
8609
7860
|
...locationUrl ? { locationUrl } : void 0,
|
|
8610
|
-
archivedAt:
|
|
7861
|
+
archivedAt: conversation.archivedAtMs === void 0 ? null : new Date(conversation.archivedAtMs).toISOString(),
|
|
8611
7862
|
pinnedAt: args.pinnedAtMs === void 0 ? null : new Date(args.pinnedAtMs).toISOString(),
|
|
8612
7863
|
...args.pinPosition === void 0 ? void 0 : { pinPosition: args.pinPosition },
|
|
8613
7864
|
...unread ? { unread: true } : void 0,
|
|
@@ -8698,7 +7949,10 @@ async function conversationEventPageReport(executor, args) {
|
|
|
8698
7949
|
};
|
|
8699
7950
|
}
|
|
8700
7951
|
// src/api/conversations/agent-tree.ts
|
|
8701
|
-
|
|
7952
|
+
/** Name a child the viewer cannot read, or one with no agent label. */
|
|
7953
|
+
function childLabel(kind) {
|
|
7954
|
+
return kind === "thread" ? "Thread" : "Task";
|
|
7955
|
+
}
|
|
8702
7956
|
/**
|
|
8703
7957
|
* Read the agent tree of a child Conversation: its parent chain, root first,
|
|
8704
7958
|
* with the child last. Returns undefined for a root Conversation. Each
|
|
@@ -8734,13 +7988,13 @@ async function readConversationAgentTree(conversation, readAccess) {
|
|
|
8734
7988
|
if (!itemAccess?.canViewPrivateContent) return {
|
|
8735
7989
|
conversationId: id,
|
|
8736
7990
|
kind,
|
|
8737
|
-
label:
|
|
7991
|
+
label: childLabel(kind)
|
|
8738
7992
|
};
|
|
8739
7993
|
const agent = await getChildAgentLabel(id);
|
|
8740
7994
|
return {
|
|
8741
7995
|
conversationId: id,
|
|
8742
7996
|
kind,
|
|
8743
|
-
label: agent?.title ?? agent?.agentName ??
|
|
7997
|
+
label: agent?.title ?? agent?.agentName ?? childLabel(kind)
|
|
8744
7998
|
};
|
|
8745
7999
|
}));
|
|
8746
8000
|
}
|
|
@@ -8797,12 +8051,20 @@ async function readConversationForks(conversationId, links, readAccess) {
|
|
|
8797
8051
|
* events, so they do not count. It walks the message role index from the
|
|
8798
8052
|
* newest Message, so it stops at the first reply that is not quiet.
|
|
8799
8053
|
*/
|
|
8800
|
-
function latestVisibleReply(db) {
|
|
8801
|
-
return db.select({ seq: juniorConversationEvents.seq }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId,
|
|
8054
|
+
function latestVisibleReply(db, conversationId) {
|
|
8055
|
+
return db.select({ seq: juniorConversationEvents.seq }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "message"), sql`${juniorConversationEvents.payload}->>'role' = 'assistant'`, sql`(${juniorConversationEvents.payload}->'meta'->>'quiet') is distinct from 'true'`)).orderBy(desc(juniorConversationEvents.createdAt), desc(juniorConversationEvents.seq)).limit(1);
|
|
8802
8056
|
}
|
|
8803
8057
|
/** The seq of the user's latest Message in the outer Conversation. */
|
|
8804
|
-
function viewerMessageSeq(db, userId) {
|
|
8805
|
-
return db.select({ seq: max(juniorConversationEvents.seq) }).from(juniorConversationEvents).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversationEvents.actorIdentityId)).where(and(eq(juniorConversationEvents.conversationId,
|
|
8058
|
+
function viewerMessageSeq(db, userId, conversationId) {
|
|
8059
|
+
return db.select({ seq: max(juniorConversationEvents.seq) }).from(juniorConversationEvents).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversationEvents.actorIdentityId)).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "message"), eq(juniorIdentities.userId, userId)));
|
|
8060
|
+
}
|
|
8061
|
+
/**
|
|
8062
|
+
* Whether Junior's latest visible reply is after the viewer's read position
|
|
8063
|
+
* in one outer Conversation. The position is at least the viewer's own
|
|
8064
|
+
* latest Message. No reply reads as false.
|
|
8065
|
+
*/
|
|
8066
|
+
function unreadReplySql(db, userId, conversationId, lastReadSeq) {
|
|
8067
|
+
return sql`coalesce((${latestVisibleReply(db, conversationId)}) > greatest(coalesce(${lastReadSeq}, -1), coalesce((${viewerMessageSeq(db, userId, conversationId)}), -1)), false)`;
|
|
8806
8068
|
}
|
|
8807
8069
|
/**
|
|
8808
8070
|
* Return the Conversations that have a visible Junior reply after the
|
|
@@ -8816,8 +8078,7 @@ function viewerMessageSeq(db, userId) {
|
|
|
8816
8078
|
*/
|
|
8817
8079
|
async function readUnreadConversationIds(db, conversationIds, userId) {
|
|
8818
8080
|
if (conversationIds.length === 0) return /* @__PURE__ */ new Set();
|
|
8819
|
-
const
|
|
8820
|
-
const rows = await db.select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).leftJoin(juniorConversationReadPositions, and(eq(juniorConversationReadPositions.conversationId, juniorConversations.conversationId), eq(juniorConversationReadPositions.userId, userId))).innerJoinLateral(reply, sql`true`).where(and(inArray(juniorConversations.conversationId, [...conversationIds]), sql`${reply.seq} > greatest(coalesce(${juniorConversationReadPositions.lastReadSeq}, -1), coalesce((${viewerMessageSeq(db, userId)}), -1))`));
|
|
8081
|
+
const rows = await db.select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).leftJoin(juniorConversationReadPositions, and(eq(juniorConversationReadPositions.conversationId, juniorConversations.conversationId), eq(juniorConversationReadPositions.userId, userId))).where(and(inArray(juniorConversations.conversationId, [...conversationIds]), unreadReplySql(db, userId, juniorConversations.conversationId, juniorConversationReadPositions.lastReadSeq)));
|
|
8821
8082
|
return new Set(rows.map((row) => row.conversationId));
|
|
8822
8083
|
}
|
|
8823
8084
|
/**
|
|
@@ -8856,10 +8117,10 @@ async function markConversationUnread(viewer, conversationId, body) {
|
|
|
8856
8117
|
return { unreadReply: false };
|
|
8857
8118
|
}
|
|
8858
8119
|
const db = getDb();
|
|
8859
|
-
const reply = latestVisibleReply(db);
|
|
8120
|
+
const reply = latestVisibleReply(db, juniorConversations.conversationId).as("latest_visible_reply");
|
|
8860
8121
|
const [row] = await db.select({
|
|
8861
8122
|
replySeq: reply.seq,
|
|
8862
|
-
viewerSeq: sql`(${viewerMessageSeq(db, viewer.id)})`
|
|
8123
|
+
viewerSeq: sql`(${viewerMessageSeq(db, viewer.id, juniorConversations.conversationId)})`
|
|
8863
8124
|
}).from(juniorConversations).innerJoinLateral(reply, sql`true`).where(eq(juniorConversations.conversationId, rootConversationId));
|
|
8864
8125
|
if (!row || row.viewerSeq !== null && row.viewerSeq >= row.replySeq) throwApiError(409, "Conversation has no reply after your last message.");
|
|
8865
8126
|
if (row.replySeq === 0) {
|
|
@@ -8907,7 +8168,7 @@ const versionUser = alias(juniorUsers, "version_user");
|
|
|
8907
8168
|
*/
|
|
8908
8169
|
function viewerStateVersion(db, conversationId, viewerId) {
|
|
8909
8170
|
const root = db.select({ id: sql`coalesce(${versionConversation.rootConversationId}, ${versionConversation.conversationId})` }).from(versionConversation).where(eq(versionConversation.conversationId, conversationId));
|
|
8910
|
-
const participant = db.select({ state: sql`row(${versionParticipant.pinnedAt}, ${versionParticipant.pinPosition}, ${versionParticipant.
|
|
8171
|
+
const participant = db.select({ state: sql`row(${versionParticipant.pinnedAt}, ${versionParticipant.pinPosition}, ${versionParticipant.autoArchive})::text` }).from(versionParticipant).where(and(eq(versionParticipant.userId, viewerId), eq(versionParticipant.rootConversationId, sql`(${root})`)));
|
|
8911
8172
|
const autoArchiveDefault = db.select({ value: versionUser.autoArchiveDefault }).from(versionUser).where(eq(versionUser.id, viewerId));
|
|
8912
8173
|
const forks = db.select({ ids: sql`string_agg(${versionFork.conversationId}, ',' order by ${versionFork.conversationId})` }).from(versionFork).where(and(eq(versionFork.forkedFromConversationId, conversationId), isNull(versionFork.quickQuestionAt)));
|
|
8913
8174
|
return sql`md5(concat_ws('|',
|
|
@@ -8940,7 +8201,6 @@ async function readDetailStateRow(conversationId, viewer) {
|
|
|
8940
8201
|
const forkIds = db.select({ conversationId: fork.conversationId }).from(fork).where(and(eq(fork.forkedFromConversationId, conversationId), isNull(fork.quickQuestionAt))).orderBy(asc(fork.createdAt)).limit(50);
|
|
8941
8202
|
const viewerParticipant = viewer ? and(eq(juniorConversationParticipants.userId, viewer.id), eq(juniorConversationParticipants.rootConversationId, rootConversationId)) : sql`false`;
|
|
8942
8203
|
const [row] = await db.select({
|
|
8943
|
-
archivedAt: juniorConversationParticipants.archivedAt,
|
|
8944
8204
|
attachmentsVersion: sql`(${slackAttachmentsVersionQuery(db, conversationId)})`,
|
|
8945
8205
|
autoArchive: juniorConversationParticipants.autoArchive,
|
|
8946
8206
|
autoArchiveDefault: juniorUsers.autoArchiveDefault,
|
|
@@ -9550,7 +8810,6 @@ function projectConversationDetail(args) {
|
|
|
9550
8810
|
return {
|
|
9551
8811
|
...conversationSummaryFromStoredConversation({
|
|
9552
8812
|
access: args.access,
|
|
9553
|
-
archivedAtMs: args.archivedAtMs,
|
|
9554
8813
|
pinnedAtMs: args.pinnedAtMs,
|
|
9555
8814
|
unreadReply: args.unreadReply,
|
|
9556
8815
|
automationTitle: args.automationTitle,
|
|
@@ -9744,33 +9003,40 @@ async function readConversationDetail(conversationId, options = {}) {
|
|
|
9744
9003
|
* A pin lives on the viewer's participant row, and that row grants send and
|
|
9745
9004
|
* control access. So only a participant can pin, the same as archive. The
|
|
9746
9005
|
* root actor may have no row yet, so pinning adds it. A pin also restores an
|
|
9747
|
-
* archived conversation, because the Pinned section shows only
|
|
9748
|
-
* conversations.
|
|
9006
|
+
* archived conversation for everyone, because the Pinned section shows only
|
|
9007
|
+
* active conversations. A pin on a child would be a fact of the child, not
|
|
9008
|
+
* of the viewer's root, and no list shows child pins yet, so only a root can
|
|
9009
|
+
* be pinned.
|
|
9749
9010
|
*/
|
|
9750
9011
|
async function pinConversation(viewer, conversationId, body) {
|
|
9751
9012
|
if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(404, "Conversation not found.");
|
|
9752
|
-
const
|
|
9753
|
-
const
|
|
9754
|
-
|
|
9013
|
+
const db = getSqlExecutor().db();
|
|
9014
|
+
const [conversation] = await db.select({
|
|
9015
|
+
archivedAt: juniorConversations.archivedAt,
|
|
9016
|
+
kind: juniorConversations.kind,
|
|
9017
|
+
lastActivityAt: juniorConversations.lastActivityAt,
|
|
9018
|
+
parentConversationId: juniorConversations.parentConversationId,
|
|
9019
|
+
rootConversationId: juniorConversations.rootConversationId
|
|
9020
|
+
}).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId)).limit(1);
|
|
9021
|
+
if (!conversation) throwApiError(404, "Conversation not found.");
|
|
9022
|
+
if (conversationKindFromRow(conversation) !== "root") throwApiError(409, `A child conversation cannot be pinned or unpinned. It uses its root's pin: ${conversation.rootConversationId ?? conversation.parentConversationId}.`);
|
|
9755
9023
|
if (!body.pinned) {
|
|
9756
9024
|
await db.update(juniorConversationParticipants).set({
|
|
9757
9025
|
pinnedAt: null,
|
|
9758
9026
|
pinPosition: null
|
|
9759
|
-
}).where(and(eq(juniorConversationParticipants.userId, viewer.id), eq(juniorConversationParticipants.rootConversationId,
|
|
9027
|
+
}).where(and(eq(juniorConversationParticipants.userId, viewer.id), eq(juniorConversationParticipants.rootConversationId, conversationId)));
|
|
9760
9028
|
return { pinnedAt: null };
|
|
9761
9029
|
}
|
|
9762
|
-
|
|
9763
|
-
if (!root) throwApiError(404, "Conversation not found.");
|
|
9030
|
+
if (conversation.archivedAt) await setArchivedAt(db, [conversationId], null);
|
|
9764
9031
|
const pinnedAt = /* @__PURE__ */ new Date();
|
|
9765
9032
|
await db.insert(juniorConversationParticipants).values({
|
|
9766
|
-
lastMessageAt:
|
|
9033
|
+
lastMessageAt: conversation.lastActivityAt,
|
|
9767
9034
|
pinnedAt,
|
|
9768
|
-
rootConversationId,
|
|
9035
|
+
rootConversationId: conversationId,
|
|
9769
9036
|
userId: viewer.id
|
|
9770
9037
|
}).onConflictDoUpdate({
|
|
9771
9038
|
target: [juniorConversationParticipants.userId, juniorConversationParticipants.rootConversationId],
|
|
9772
9039
|
set: {
|
|
9773
|
-
archivedAt: null,
|
|
9774
9040
|
pinnedAt,
|
|
9775
9041
|
pinPosition: null
|
|
9776
9042
|
}
|
|
@@ -9794,28 +9060,28 @@ async function reorderPinnedConversations(viewer, body) {
|
|
|
9794
9060
|
/**
|
|
9795
9061
|
* Find where a Thread nests: its nearest ancestor that is a listed root or a
|
|
9796
9062
|
* Thread. A Thread under a Task moves up. Returns undefined when an ancestor
|
|
9797
|
-
*
|
|
9063
|
+
* is archived, because an archive hides its whole subtree.
|
|
9798
9064
|
*/
|
|
9799
9065
|
function findThreadPlacement(threadId, tree, rootIds) {
|
|
9800
9066
|
let placement;
|
|
9801
9067
|
for (const ancestor of conversationAncestors(tree, threadId)) {
|
|
9802
9068
|
if (rootIds.has(ancestor.conversationId)) return placement ?? ancestor.conversationId;
|
|
9803
|
-
if (ancestor.
|
|
9069
|
+
if (ancestor.archivedAt) return void 0;
|
|
9804
9070
|
if (ancestor.kind === "thread") placement ??= ancestor.conversationId;
|
|
9805
9071
|
}
|
|
9806
9072
|
}
|
|
9807
9073
|
/**
|
|
9808
9074
|
* Read the shown Threads of the listed roots for the feed, nested under
|
|
9809
9075
|
* their nearest shown ancestor. A Thread shows when it and every ancestor
|
|
9810
|
-
*
|
|
9811
|
-
*
|
|
9812
|
-
*
|
|
9076
|
+
* have no `archived_at`. The caller passes only unarchived roots, so a root
|
|
9077
|
+
* archive hides its tree with no writes to the children. A Thread uses the
|
|
9078
|
+
* access of its root.
|
|
9813
9079
|
*/
|
|
9814
9080
|
async function readFeedThreads(db, roots) {
|
|
9815
9081
|
if (roots.length === 0) return /* @__PURE__ */ new Map();
|
|
9816
9082
|
const rootIdList = roots.map((root) => root.conversationId);
|
|
9817
9083
|
const rootIds = new Set(rootIdList);
|
|
9818
|
-
const [rows, tree] = await Promise.all([selectConversationRecords(db).where(and(inArray(juniorConversations.rootConversationId, rootIdList), eq(juniorConversations.kind, "thread"), isNull(juniorConversations.
|
|
9084
|
+
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)]);
|
|
9819
9085
|
if (rows.length === 0) return /* @__PURE__ */ new Map();
|
|
9820
9086
|
const threads = rows.map((row) => ({
|
|
9821
9087
|
conversation: conversationFromRecordRow(row),
|
|
@@ -9925,7 +9191,7 @@ function feedMember(filter) {
|
|
|
9925
9191
|
function conversationFeedMembershipFilter(status, filter) {
|
|
9926
9192
|
if (!filter) return status === "archived" ? sql`false` : void 0;
|
|
9927
9193
|
const member = feedMember(filter);
|
|
9928
|
-
return and(conversationIsMemberRoot(member), status === "archived" ?
|
|
9194
|
+
return and(conversationIsMemberRoot(member), status === "archived" ? isNotNull(juniorConversations.archivedAt) : status === "all" ? void 0 : isNull(juniorConversations.archivedAt));
|
|
9929
9195
|
}
|
|
9930
9196
|
/**
|
|
9931
9197
|
* Keep root conversations linked to one code repository. A code change can
|
|
@@ -9979,30 +9245,54 @@ async function waitingRowsOutsidePage(db, filter, page) {
|
|
|
9979
9245
|
});
|
|
9980
9246
|
}
|
|
9981
9247
|
const feedTree = alias(juniorConversations, "feed_tree");
|
|
9248
|
+
const feedAnnotated = alias(juniorConversations, "feed_annotated");
|
|
9982
9249
|
/**
|
|
9983
9250
|
* Return a query for a token that changes when the viewer's default feed
|
|
9984
9251
|
* page can change. It reads the same newest page as the feed, so its cost
|
|
9985
9252
|
* does not grow with the viewer's history.
|
|
9986
9253
|
*
|
|
9987
|
-
*
|
|
9988
|
-
*
|
|
9989
|
-
*
|
|
9990
|
-
*
|
|
9991
|
-
*
|
|
9254
|
+
* The token holds only what a feed row shows, so a Task's own writes do not
|
|
9255
|
+
* move it. Each content write moves its Conversation's `last_activity_at`,
|
|
9256
|
+
* so the root's value covers the preview and participants. The row shows
|
|
9257
|
+
* only whether a reply is unread, so a scroll that moves the read position
|
|
9258
|
+
* does not move the token.
|
|
9259
|
+
* Threads and annotations show from the whole tree. Waiting roots outside
|
|
9260
|
+
* the page move the Review items token.
|
|
9992
9261
|
*/
|
|
9993
9262
|
function conversationFeedVersionQuery(db, userId) {
|
|
9994
9263
|
const pin = juniorConversationParticipants;
|
|
9264
|
+
const read = juniorConversationReadPositions;
|
|
9995
9265
|
const page = db.select({
|
|
9996
9266
|
conversationId: juniorConversations.conversationId,
|
|
9267
|
+
channelName: juniorConversations.channelName,
|
|
9268
|
+
executionStatus: juniorConversations.executionStatus,
|
|
9269
|
+
lastActivityAt: juniorConversations.lastActivityAt,
|
|
9270
|
+
lastReadSeq: read.lastReadSeq,
|
|
9997
9271
|
pinnedAt: pin.pinnedAt,
|
|
9998
|
-
pinPosition: pin.pinPosition
|
|
9999
|
-
|
|
9272
|
+
pinPosition: pin.pinPosition,
|
|
9273
|
+
stoppedAt: juniorConversations.stoppedAt,
|
|
9274
|
+
title: juniorConversations.title
|
|
9275
|
+
}).from(juniorConversations).leftJoin(pin, and(eq(pin.rootConversationId, juniorConversations.conversationId), eq(pin.userId, userId))).leftJoin(read, and(eq(read.conversationId, juniorConversations.conversationId), eq(read.userId, userId))).where(and(isNull(juniorConversations.parentConversationId), isNull(juniorConversations.quickQuestionAt), conversationFeedMembershipFilter("active", {
|
|
10000
9276
|
kind: "viewer",
|
|
10001
9277
|
userId
|
|
10002
9278
|
}))).orderBy(desc(isNotNull(pin.pinnedAt)), desc(juniorConversations.lastActivityAt), asc(juniorConversations.conversationId)).limit(CONVERSATION_FEED_LIMIT).as("feed_page");
|
|
10003
|
-
const tree = db.select({ version: sql`concat_ws(':',
|
|
9279
|
+
const tree = db.select({ version: sql`concat_ws(':',
|
|
9280
|
+
count(*) filter (where ${feedTree.archivedAt} is not null),
|
|
9281
|
+
string_agg(concat_ws('/',
|
|
9282
|
+
${feedTree.conversationId}, ${feedTree.title},
|
|
9283
|
+
${feedTree.executionStatus}, ${feedTree.stoppedAt},
|
|
9284
|
+
${feedTree.lastActivityAt}
|
|
9285
|
+
), ',' order by ${feedTree.conversationId}) filter (
|
|
9286
|
+
where ${feedTree.kind} = 'thread' and ${feedTree.archivedAt} is null
|
|
9287
|
+
)
|
|
9288
|
+
)` }).from(feedTree).where(eq(feedTree.rootConversationId, page.conversationId));
|
|
9289
|
+
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, page.conversationId));
|
|
10004
9290
|
return db.select({ version: sql`md5(coalesce(string_agg(
|
|
10005
|
-
concat_ws('@', ${page.conversationId}, ${page.pinnedAt}, ${page.pinPosition},
|
|
9291
|
+
concat_ws('@', ${page.conversationId}, ${page.pinnedAt}, ${page.pinPosition},
|
|
9292
|
+
${page.title}, ${page.channelName}, ${page.executionStatus},
|
|
9293
|
+
${page.stoppedAt}, ${page.lastActivityAt},
|
|
9294
|
+
${unreadReplySql(db, userId, page.conversationId, page.lastReadSeq)},
|
|
9295
|
+
(${tree}), (${annotations})),
|
|
10006
9296
|
',' order by ${page.conversationId}
|
|
10007
9297
|
), ''))` }).from(page);
|
|
10008
9298
|
}
|
|
@@ -10065,7 +9355,7 @@ async function readConversationFeedFromSql(options = {}) {
|
|
|
10065
9355
|
]);
|
|
10066
9356
|
const visibleActivityPreviews = await attachActivityPreviewMentions(getSqlExecutor(), new Map([...activityPreviewByConversation].filter(([conversationId]) => accessByConversation.get(conversationId)?.canViewPrivateContent)));
|
|
10067
9357
|
const visibleAnnotationsByConversation = new Map(conversationIds.map((conversationId) => [conversationId, accessByConversation.get(conversationId)?.canViewPrivateContent ? annotationsByConversation.get(conversationId) ?? [] : []]));
|
|
10068
|
-
const [sidebarAnnotationsByConversation, threadsByRoot] = await Promise.all([listConversationSidebarAnnotations(conversationIds, visibleAnnotationsByConversation), readFeedThreads(db,
|
|
9358
|
+
const [sidebarAnnotationsByConversation, threadsByRoot] = await Promise.all([listConversationSidebarAnnotations(conversationIds, visibleAnnotationsByConversation), readFeedThreads(db, conversations.filter((conversation) => conversation.archivedAtMs === void 0).map(({ conversationId }) => ({
|
|
10069
9359
|
access: accessByConversation.get(conversationId),
|
|
10070
9360
|
conversationId
|
|
10071
9361
|
})))]);
|