@sentry/junior 0.285.0 → 0.287.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-CL-HUKgd.js} +1 -1
- package/dist/{admin-DOITMKnn.js → admin-C9urXVfi.js} +2 -1
- package/dist/{agent-runner-BsWhHe4N.js → agent-runner-Bfnw551N.js} +2174 -1323
- package/dist/api/schema.d.ts +2 -2
- package/dist/api/schema.js +7 -7
- package/dist/api.d.ts +1 -1
- package/dist/api.js +73 -112
- package/dist/{app-DyMs9330.d.ts → app-DBY5TnfY.d.ts} +2 -3
- package/dist/app.d.ts +1 -1
- package/dist/app.js +72 -42
- package/dist/{assistant-reply-9Jip5bsr.js → assistant-reply-u_PRYzuz.js} +1 -1
- package/dist/{automation-Mk8aaHzy.js → automation-DksGNDRO.js} +3 -6
- package/dist/{background-compaction-queue-DXkLsWoH.js → background-compaction-queue-CYI909P5.js} +137 -3
- package/dist/{briefs-Cl8-nK9B.js → briefs-DaXiMWzT.js} +6 -5
- package/dist/{catalog-runtime-Bte6jRB2.js → catalog-runtime-BCIuBe4d.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 → config-CkHcUMN7.js} +580 -3
- package/dist/{connections-DA4LT9LL.js → connections-BnIj0wtx.js} +16 -50
- package/dist/{conversation-D8kVoCrP.js → conversation-E7ZPJx2H.js} +22 -6
- package/dist/{conversation-pending-messages-BvROq1bq.js → conversation-pending-messages-DVch6YQw.js} +2 -5
- package/dist/{conversation-privacy-D0j_h70R.js → conversation-privacy-DF1hW0ja.js} +1 -1
- package/dist/{credential-sync-hcsYatw-.js → credential-sync-CzMar9hq.js} +13 -13
- package/dist/{viewer-1Ea81s0b.js → db-DJ11eZqq.js} +64 -367
- package/dist/{db-BhHZSuFw.d.ts → db-YDKKDxlh.d.ts} +4 -4
- package/dist/{executor-BLEMIgIZ.js → executor-BY9TB31g.js} +20 -19
- package/dist/instrumentation.js +2 -2
- package/dist/{logging-BfORLKoq.js → logging-BO5zU6Mt.js} +1 -1
- package/dist/{media-Bu9C6lz0.js → media-Cz1ZiV1U.js} +16 -4
- package/dist/{message-DqjuKzUx.js → message-CsUbuEc8.js} +10 -10
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +2 -3
- package/dist/{oauth-callback-server-CFSRzu1n.js → oauth-callback-server-hiDKK0_n.js} +2 -2
- package/dist/{projection-DliWYrnT.js → projection-CL_YWeGf.js} +352 -356
- package/dist/{prompt-BvIUzY4y.js → prompt-BHOEQSmf.js} +182 -2
- package/dist/{registry-rC7MCxu8.js → registry-BriFLnaJ.js} +1 -1
- package/dist/{reporting-window-B4TwyuJo.js → reporting-window-B3Ze-Qnt.js} +4 -1
- package/dist/{resolve-Biu8Qw3u.js → resolve-Bt6GgAiA.js} +3 -3
- package/dist/{result-DxJMCX47.js → result-Bo1TZu0Q.js} +8 -8
- package/dist/{runner-BQJSFLKg.js → runner-D3YeCQgt.js} +16 -12
- package/dist/{sandbox-egress-signals-6aMxJSDn.js → sandbox-egress-signals-CcnSPP4S.js} +1 -1
- package/dist/{schema-BasXTvi2.js → schema-BWE3RJEB.js} +19 -7
- package/dist/{schema-BUviRAs8.d.ts → schema-C6fsEwjo.d.ts} +90 -8
- package/dist/{service-account-BI5Wgx22.js → service-account-DiQQuuw7.js} +3 -3
- package/dist/{service-account-CAE-_1dR.js → service-account-r6fl0b-9.js} +3 -3
- package/dist/{session-stop-CA-jOJ84.js → session-stop-B2Nut40V.js} +27 -25
- package/dist/{skills-B22duVJU.js → skills-CD5aJdzg.js} +2 -2
- package/dist/spawn-CalgZQiu.js +79 -0
- package/dist/{stop-DioIcEAu.js → stop-kujZLbi0.js} +233 -1127
- package/dist/{store-Dn4W7qgH.js → store-DdIEUL1q.js} +3 -3
- package/dist/{turn-session-routing-CGMKrYOj.js → task-runner-D_RDr2Hu.js} +1440 -993
- package/dist/{store-B26LV6UP.js → turn-failure-response-B5nV1Er-.js} +337 -6
- package/dist/{validation-TzhfQABF.js → validation-K4pqwoVZ.js} +1 -1
- package/dist/{version-DSk8CFvA.js → version-DBvhk1X9.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/viewer-DrMmFUul.js +337 -0
- package/dist/{work-ybG4_q5C.js → work-ljRoODGu.js} +110 -94
- package/dist/{worker-ccSyZRNz.js → worker-CYO1Q0Js.js} +5 -6
- package/migrations/0086_shared_archive.sql +31 -0
- package/migrations/0087_child_location.sql +64 -0
- package/migrations/0088_conversation_unsubscribe.sql +1 -0
- package/migrations/meta/0086_snapshot.json +4366 -0
- package/migrations/meta/0087_snapshot.json +4366 -0
- package/migrations/meta/0088_snapshot.json +4372 -0
- package/migrations/meta/_journal.json +21 -0
- package/package.json +5 -4
- package/dist/config-DqFnykQT.js +0 -579
- package/dist/spawn-BB2_4VYn.js +0 -31
- 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,42 +1,37 @@
|
|
|
1
|
-
import { h as startSpan
|
|
2
|
-
import { $ as
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import { t as JUNIOR_VERSION } from "./version-DSk8CFvA.js";
|
|
1
|
+
import { h as startSpan } from "./sentry-BRTJqumy.js";
|
|
2
|
+
import { $ as pauseLostWorkerTurn, $a as createPluginLogger, $i as postSlackMessage, A as isHumanConversationMessage, Ao as listConversationAnnotationsById, At as moveIdleConversationDestination, Bn as webActorUserIds, C as resolveConversationTitle, Cn as buildDeterministicTurnId, Co as readAttachmentVisionSummary, D as buildConversationContext, Dn as getThreadStopDecision, Dr as canReadReviewItem, En as getSubscribedReplyPreflightDecision, F as trimConversationMessages, Fo as createPluginCache, Gt as buildTurnErrorResponse, Hi as formatSlackLink, I as turnHasReply, In as isExperimentalFeatureEnabled, Ji as deleteSlackMessage, Ki as truncateStatusText, L as upsertConversationMessage, Lo as configValueSchema, M as markConversationMessage, Mr as reviewItemNeedsSomeone, N as normalizeConversationText, No as lookupSlackUser, Nr as reviewItemReaderForUser, O as estimateConversationMessagesTokens, Or as isOnlyAssignee, P as recordDeliveredAssistantMessage, Po as lookupSlackUserNames, Pt as releaseInboundMessage, Q as lostWorkerBeforeFirstSave, Rn as createUserTokenStore, Sn as buildDeterministicAssistantMessageId, Sr as takeReviewItem, T as fallbackShortTitle, Tn as decideSubscribedThreadReply, To as slackAttachmentsVersionQuery, Tr as canActOnReviewItem, U as AuthorizationFlowDisabledError, Vi as escapeSlackMrkdwnText, Wi as normalizeSlackStatusText, Wr as cancelSubscriptions, Y as wasPendingAuthStopped, Yt as persistWithRetry, Z as loadTurnCheckpoint, Zn as getPlugins, a as loadProjection, aa as SlackActionError, ao as conversationIsNotUnsubscribedRoot, at as listTurnSummaries, b as persistConversationMessages, bo as notInheritedByForkChild, ca as getHeaderString, ci as getDashboardConversationLink, co as viewerConversationMembership, d as recordAuthorizationCompleted, da as isDmChannel, dn as trimTrailingAssistantMessages, ea as removeReactionFromMessage, et as saveTurnCheckpoint, fa as normalizeSlackConversationId, fo as readLatestConversationBrief, fr as closeReviewItem, gr as getReviewItem, h as recordSubscribedReplyRoute, ho as readConversationEventPageAround, i as loadConversationProjection, io as conversationIsMemberRoot, it as getTurnRecord, j as latestConversationMessageSeq, k as getConversationMessageSlackTs, ko as listConversationAnnotations, la as getSlackClient, lo as viewerMarksFromParticipant, ma as withSlackRetries, mo as readConversationEventPageAfter, n as commitMessages, no as readConversationAccessFromSql, nt as completeTurnRecord, o as loadTurnProjection, oa as downloadPrivateSlackFile, oo as conversationPinnedForUser, ot as recordTurnSummary, po as readConversationEventPage, q as clearPendingAuth, qi as addReactionToMessage, ro as conversationHasParticipantUser, rt as failTurnRecord, so as conversationViewerMarks, t as commitAcceptedReply, to as createConversationAccessReader, tt as abandonTurnRecord, v as hydrateConversationMessages, vo as buildSentryConversationUrl, vr as listReplyActionItems, wo as recordSlackAttachment, xo as getSlackFileId, y as persistConversationMessageWindow, yr as listWaitingConversations, z as PluginCredentialFailureError, zo as piMessageFromHistoryItem } from "./projection-CL_YWeGf.js";
|
|
3
|
+
import { E as resolveGatewayModel, M as escapeXml, c as getSlackClientSecret, i as getChatConfig, l as getSlackSigningSecret, n as botConfig, o as getSlackBotToken, s as getSlackClientId, v as normalizeSlackEmojiName, z as isProviderRetryError } from "./config-CkHcUMN7.js";
|
|
4
|
+
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-BO5zU6Mt.js";
|
|
5
|
+
import { t as JUNIOR_VERSION } from "./version-DBvhk1X9.js";
|
|
7
6
|
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, Lt as
|
|
7
|
+
import { C as setFirstConversationLocation, D as resolveActorIdentityId, G as hasAgentTurnUsage, I as bindProviderConversation, K as resolveRootConversationId, L as parseSessionSource, O as saveActorAvatar, S as locationFromRow, V as addAgentTurnUsage, W as agentTurnUsageSchema, Y as requireSlackDestination, _ as setArchivedAt, a as getConversationStore, b as withConversationMutationLock, g as readConversationTrees, m as conversationAncestors, o as getDb, p as withConversationEventLock, q as createSlackDestination, r as getConversationEventStore, s as getSqlExecutor, v as loadConversationSlackTenantIds, x as conversationKindFromRow, z as nextDetailVersion } from "./db-DJ11eZqq.js";
|
|
8
|
+
import { A as juniorConversations, 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-BY9TB31g.js";
|
|
9
|
+
import { _ as instructionProvenanceFor, h as contextProvenance, i as isVisionImageMediaType, r as detectImageMediaType } from "./media-Cz1ZiV1U.js";
|
|
10
|
+
import { d as actorLogContext, f as credentialContextForActor } from "./registry-BriFLnaJ.js";
|
|
11
|
+
import { A as runWithSlackInstallation, B as listThreadReplies, Bt as getWebAuthorization, Ct as markConversationRead, Dt as stopChildAgentsBelow, Et as throwApiError, F as resolveSlackChannelIdFromThreadId, I as checkSlackChannelReadAccess, It as getTurnInputSpanAttributes, L as joinPublicChannelForRead, Lt as turnInputTelemetry, M as parseSlackThreadId, N as readSlackRawMessageContext, Nt as AgentRunError, Ot as stopChildAgentsOf, P as resolveSlackChannelIdFromMessage, Pt as executeTurn, R as getConversationInfo, Rt as withTurnSpan, S as createSlackReviewItemShow, St as conversationReadPositionQuery, V as resolveDestinationVisibility, X as readConversationSourceTask, Zt as RetryableDeliveryError, at as deliverReviewItemChange, b as renderAttachmentText, bt as readLastUserMessageAtByConversation, ct as acceptsWebMessages, dt as createAndEnqueueConversation, en as shouldEmitDevAgentTrace, ft as createConversationId, ht as decodeInputImages, i as buildAuthPauseResponse, jt as createConversationTurnWorker, lt as appendAndEnqueueWebMessage, mt as webActorFromUser, n as executeAgentRun, p as latestProgressStatus, pt as recordWebConversationActivity, t as createAgentRunner, x as renderBlockText, yt as storeAttachment } from "./agent-runner-Bfnw551N.js";
|
|
12
|
+
import { a as EVENT_SYSTEM_ACTOR, c as completeDecision, o as isEventConversationMessage, u as completeText } from "./prompt-BHOEQSmf.js";
|
|
13
13
|
import { r as acquireActiveLock } from "./locks-D-0h111u.js";
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import { n as getAssistantReplyText
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
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
|
|
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";
|
|
14
|
+
import { f as identityAvatarUrl, h as readUserAvatarUrls } from "./viewer-DrMmFUul.js";
|
|
15
|
+
import { a as setStateValues, i as getStateValues, r as getStateAdapter } from "./adapter-CL-HUKgd.js";
|
|
16
|
+
import { B as readMessageAttachments, d as conversationEventPageSchema, l as conversationDetailReportSchema, m as conversationFeedSchema } from "./conversation-E7ZPJx2H.js";
|
|
17
|
+
import { a as persistAuthPauseTurnState, at as getConversationTurnBoundaryError, b as getChildAgentLabel, c as getTurnUserSlackMessageTs, ct as isTurnInputDeferredError, d as loadThreadContextTrimFloor, dt as markTurnFailed, ft as startActiveTurn, i as completeAuthPauseTurn, it as TurnInputDeferredError, l as buildDeliveredTurnStatePatch, lt as markTurnClosed, m as loadPendingMessageCards, n as getAgentTurnDiagnosticsAttributes, nt as CooperativeTurnYieldError, o as getTurnUserMessage, ot as isCooperativeTurnYieldError, p as getTurnLifecycle, r as requireTurnFailureEventId, rt as TurnInputCommitLostError, s as getTurnUserReplyAttachmentContext, st as isTurnInputCommitLostError, t as finalizeFailedTurnReplyWithEvent, tt as ConversationTurnBoundaryError, u as buildTurnThreadContext, ut as markTurnCompleted } from "./turn-failure-response-B5nV1Er-.js";
|
|
18
|
+
import { n as getAssistantReplyText } from "./assistant-reply-u_PRYzuz.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-B2Nut40V.js";
|
|
20
|
+
import { b as normalizeUserInputAnswer, p as webMessageId, y as isEmptyUserInputAnswer } from "./reporting-window-B3Ze-Qnt.js";
|
|
21
|
+
import { S as getTurnRequestDeadline, _ as getVercelConversationWorkQueue } from "./background-compaction-queue-CYI909P5.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-DdIEUL1q.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-D_RDr2Hu.js";
|
|
24
|
+
import { d as healthReportSchema, s as conversationPendingMessagesReportSchema } from "./conversation-pending-messages-DVch6YQw.js";
|
|
25
|
+
import { r as endActiveAgentInvocations, s as resolveThreadTurnWork } from "./work-ljRoODGu.js";
|
|
26
|
+
import { a as withAgentInvocationResultActors, n as enqueueAgentInvocationResult, t as createChildConversationWorker } from "./result-Bo1TZu0Q.js";
|
|
27
|
+
import { c as createPausedTurns, d as wakePausedTurn, f as getTurnAuthorization, l as getPausedTurnRequest } from "./connections-BnIj0wtx.js";
|
|
28
|
+
import { t as bindMessageAgent } from "./message-CsUbuEc8.js";
|
|
29
|
+
import { r as readConversationLineage, t as bindSpawnAgent } from "./spawn-CalgZQiu.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";
|
|
37
33
|
import { conversationSidebarAnnotationSchema, createSlackSource, objectTypeSchema } from "@sentry/junior-plugin-api";
|
|
38
34
|
import { alias } from "drizzle-orm/pg-core";
|
|
39
|
-
import { HTTPException } from "hono/http-exception";
|
|
40
35
|
import { Message, ThreadImpl, stringifyMarkdown } from "chat";
|
|
41
36
|
import { SlackFormatConverter, createSlackAdapter } from "@chat-adapter/slack";
|
|
42
37
|
// src/handlers/health.ts
|
|
@@ -267,12 +262,16 @@ function createAgentDispatchConversationWorker(options) {
|
|
|
267
262
|
if (resumesDurableTurn && context.attempt.messages.length > 0) await acknowledge();
|
|
268
263
|
let result;
|
|
269
264
|
if (resumesDurableTurn) {
|
|
270
|
-
await options.resumeTurn(dispatch, {
|
|
265
|
+
await options.resumeTurn(dispatch, {
|
|
266
|
+
shouldYield: context.shouldYield,
|
|
267
|
+
checkIn: context.checkIn
|
|
268
|
+
});
|
|
271
269
|
result = await readDispatchTurnResult(dispatch);
|
|
272
270
|
} else {
|
|
273
271
|
const runtimeResult = await options.runTurn(dispatch, {
|
|
274
272
|
ack: acknowledge,
|
|
275
|
-
shouldYield: context.shouldYield
|
|
273
|
+
shouldYield: context.shouldYield,
|
|
274
|
+
checkIn: context.checkIn
|
|
276
275
|
});
|
|
277
276
|
result = runtimeResult.outcome ? runtimeResult : {
|
|
278
277
|
...runtimeResult,
|
|
@@ -382,83 +381,6 @@ async function listConversationWork(conversationIds) {
|
|
|
382
381
|
unfinishedIds: conversationIds.filter((conversationId) => unfinished.has(conversationId))
|
|
383
382
|
};
|
|
384
383
|
}
|
|
385
|
-
// src/api/http.ts
|
|
386
|
-
const NO_STORE_HEADERS = { "cache-control": "no-store" };
|
|
387
|
-
/** Build response init that keeps personalized API payloads out of shared caches. */
|
|
388
|
-
function noStoreInit(init) {
|
|
389
|
-
if (!init) return { headers: NO_STORE_HEADERS };
|
|
390
|
-
const headers = new Headers(init.headers);
|
|
391
|
-
if (!headers.has("cache-control")) headers.set("cache-control", "no-store");
|
|
392
|
-
return {
|
|
393
|
-
...init,
|
|
394
|
-
headers
|
|
395
|
-
};
|
|
396
|
-
}
|
|
397
|
-
/** Serialize a REST response only after it satisfies its declared schema. */
|
|
398
|
-
function jsonResponse(schema, value, init) {
|
|
399
|
-
return startSpan({
|
|
400
|
-
name: "Write API response",
|
|
401
|
-
op: "serialize"
|
|
402
|
-
}, (span) => {
|
|
403
|
-
const startedAt = performance.now();
|
|
404
|
-
const parsed = schema.parse(value);
|
|
405
|
-
const parsedAt = performance.now();
|
|
406
|
-
const body = JSON.stringify(parsed);
|
|
407
|
-
span.setAttributes({
|
|
408
|
-
"app.api.response.chars": body.length,
|
|
409
|
-
"app.api.response.json_stringify_ms": Math.round(performance.now() - parsedAt),
|
|
410
|
-
"app.api.response.schema_parse_ms": Math.round(parsedAt - startedAt)
|
|
411
|
-
});
|
|
412
|
-
const responseInit = noStoreInit(init);
|
|
413
|
-
const headers = new Headers(responseInit.headers);
|
|
414
|
-
if (!headers.has("content-type")) headers.set("content-type", "application/json");
|
|
415
|
-
return new Response(body, {
|
|
416
|
-
...responseInit,
|
|
417
|
-
headers
|
|
418
|
-
});
|
|
419
|
-
});
|
|
420
|
-
}
|
|
421
|
-
/** Return an empty personalized API response with no-store caching. */
|
|
422
|
-
function emptyResponse(status = 204) {
|
|
423
|
-
return new Response(null, noStoreInit({ status }));
|
|
424
|
-
}
|
|
425
|
-
/** Stop a request with Junior's stable JSON error contract. */
|
|
426
|
-
function throwApiError(status, message, cause) {
|
|
427
|
-
throw new HTTPException(status, {
|
|
428
|
-
...cause === void 0 ? void 0 : { cause },
|
|
429
|
-
message,
|
|
430
|
-
res: jsonResponse(apiErrorSchema, { error: message }, { status })
|
|
431
|
-
});
|
|
432
|
-
}
|
|
433
|
-
// src/api/conversations/user-message-activity.ts
|
|
434
|
-
/**
|
|
435
|
-
* The newest event of one type in the outer Conversation that matches the
|
|
436
|
-
* filter. It walks the message role or user message time index from the
|
|
437
|
-
* newest event. The user message index has only matching entries, so that
|
|
438
|
-
* read stops at the first one.
|
|
439
|
-
*/
|
|
440
|
-
function latestEventAt(db, type, filter) {
|
|
441
|
-
return db.select({ createdAt: juniorConversationEvents.createdAt }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, juniorConversations.conversationId), eq(juniorConversationEvents.type, type), filter)).orderBy(desc(juniorConversationEvents.createdAt), desc(juniorConversationEvents.seq)).limit(1).as(`latest_${type}`);
|
|
442
|
-
}
|
|
443
|
-
/** Read the latest true user message time for each selected conversation. */
|
|
444
|
-
async function readLastUserMessageAtByConversation(db, conversationIds) {
|
|
445
|
-
if (conversationIds.length === 0) return /* @__PURE__ */ new Map();
|
|
446
|
-
const payload = juniorConversationEvents.payload;
|
|
447
|
-
const instruction = latestEventAt(db, "user_message", isUserInstruction(payload));
|
|
448
|
-
const authorKind = sql`(${db.select({ kind: juniorIdentities.kind }).from(juniorIdentities).where(eq(juniorIdentities.id, juniorConversationEvents.actorIdentityId))})`;
|
|
449
|
-
const message = latestEventAt(db, "message", sql`${payload}->>'role' = 'user' and ${authorKind} = 'user'`);
|
|
450
|
-
const rows = await db.select({
|
|
451
|
-
conversationId: juniorConversations.conversationId,
|
|
452
|
-
instructionAt: instruction.createdAt,
|
|
453
|
-
messageAt: message.createdAt
|
|
454
|
-
}).from(juniorConversations).leftJoinLateral(instruction, sql`true`).leftJoinLateral(message, sql`true`).where(inArray(juniorConversations.conversationId, conversationIds));
|
|
455
|
-
const result = /* @__PURE__ */ new Map();
|
|
456
|
-
for (const { conversationId, instructionAt, messageAt } of rows) {
|
|
457
|
-
const times = [instructionAt, messageAt].flatMap((at) => at ? [at.getTime()] : []);
|
|
458
|
-
if (times.length > 0) result.set(conversationId, new Date(Math.max(...times)).toISOString());
|
|
459
|
-
}
|
|
460
|
-
return result;
|
|
461
|
-
}
|
|
462
384
|
// src/api/conversations/auto-archive.ts
|
|
463
385
|
const HOUR_MS = 36e5;
|
|
464
386
|
/** Participant rows checked per page. A run reads pages until none remain. */
|
|
@@ -498,27 +420,44 @@ function treeIsQuiet(cutoff) {
|
|
|
498
420
|
}
|
|
499
421
|
/**
|
|
500
422
|
* True when no open Review item on the participant row's root or a child
|
|
501
|
-
* conversation needs
|
|
502
|
-
* stay in
|
|
423
|
+
* conversation needs a person. Archive applies to everyone, so a
|
|
424
|
+
* conversation that waits on anyone must stay in the feed.
|
|
503
425
|
*/
|
|
504
|
-
function
|
|
426
|
+
function notWaitingOnAnyone() {
|
|
505
427
|
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(
|
|
428
|
+
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
429
|
return sql`not exists (${waiting})`;
|
|
508
430
|
}
|
|
509
431
|
/**
|
|
432
|
+
* True when no subscribed participant of the row's root pinned it or turned
|
|
433
|
+
* auto-archive off for it. Archive applies to everyone, so one person's run
|
|
434
|
+
* must not undo another person's pin or manual restore. A person who
|
|
435
|
+
* unsubscribed no longer keeps it.
|
|
436
|
+
*/
|
|
437
|
+
function noParticipantKeepsRoot() {
|
|
438
|
+
const keeper = alias(juniorConversationParticipants, "keeping_participant");
|
|
439
|
+
const keeping = getDb().select({ userId: keeper.userId }).from(keeper).where(and(eq(keeper.rootConversationId, juniorConversationParticipants.rootConversationId), isNull(keeper.unsubscribedAt), or(isNotNull(keeper.pinnedAt), eq(keeper.autoArchive, false))));
|
|
440
|
+
return sql`not exists (${keeping})`;
|
|
441
|
+
}
|
|
442
|
+
/** True when the participant row's root is not archived. */
|
|
443
|
+
function rootIsUnarchived() {
|
|
444
|
+
const root = alias(juniorConversations, "archive_root");
|
|
445
|
+
const unarchived = getDb().select({ conversationId: root.conversationId }).from(root).where(and(eq(root.conversationId, juniorConversationParticipants.rootConversationId), isNull(root.archivedAt)));
|
|
446
|
+
return sql`exists (${unarchived})`;
|
|
447
|
+
}
|
|
448
|
+
/**
|
|
510
449
|
* Conditions that a participant row must meet when it is selected and again
|
|
511
450
|
* when it is archived, so new activity, a new run, a new Review item, or a
|
|
512
451
|
* changed setting wins over a stale read.
|
|
513
452
|
*/
|
|
514
453
|
function archivableRow(run) {
|
|
515
|
-
return and(eq(juniorConversationParticipants.userId, run.userId), isNull(juniorConversationParticipants.
|
|
454
|
+
return and(eq(juniorConversationParticipants.userId, run.userId), isNull(juniorConversationParticipants.unsubscribedAt), rootIsUnarchived(), noParticipantKeepsRoot(), lte(juniorConversationParticipants.lastMessageAt, runCutoff(run)), runOptsIn(run), run.kind === "scheduled" ? sql`${juniorUsers.autoArchiveGraceHours} <= ${run.graceHours}` : void 0, treeIsQuiet(runCutoff(run)), notWaitingOnAnyone());
|
|
516
455
|
}
|
|
517
456
|
/**
|
|
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.
|
|
457
|
+
* One page of the user's participant rows on unarchived roots that may be
|
|
458
|
+
* done. Pages follow `junior_conversation_participants_user_activity_idx`, so
|
|
459
|
+
* a run reads only rows older than the cutoff. Archive writes during the run
|
|
460
|
+
* do not move `lastMessageAt`, so they do not skip rows.
|
|
522
461
|
*/
|
|
523
462
|
async function selectCandidateRoots(run, after) {
|
|
524
463
|
return await getDb().select({
|
|
@@ -547,9 +486,16 @@ async function selectDoneRoots(rootIds, cutoffMs) {
|
|
|
547
486
|
unfinishedWork: unfinished.has(id)
|
|
548
487
|
}, cutoffMs));
|
|
549
488
|
}
|
|
550
|
-
/**
|
|
489
|
+
/**
|
|
490
|
+
* Archive one root for everyone when it is still archivable for the run's
|
|
491
|
+
* user.
|
|
492
|
+
*/
|
|
551
493
|
async function archiveRoot(run, rootConversationId) {
|
|
552
|
-
|
|
494
|
+
const archivable = getDb().select({ userId: juniorConversationParticipants.userId }).from(juniorConversationParticipants).innerJoin(juniorUsers, eq(juniorUsers.id, juniorConversationParticipants.userId)).where(and(eq(juniorConversationParticipants.rootConversationId, rootConversationId), archivableRow(run)));
|
|
495
|
+
return (await getDb().update(juniorConversations).set({
|
|
496
|
+
archivedAt: run.now,
|
|
497
|
+
detailVersion: nextDetailVersion
|
|
498
|
+
}).where(and(eq(juniorConversations.conversationId, rootConversationId), isNull(juniorConversations.archivedAt), sql`exists (${archivable})`)).returning({ conversationId: juniorConversations.conversationId })).length > 0;
|
|
553
499
|
}
|
|
554
500
|
/** Archive every done conversation of one user and count the rows. */
|
|
555
501
|
async function archiveUserDoneConversations(run) {
|
|
@@ -576,7 +522,7 @@ async function archiveUserDoneConversations(run) {
|
|
|
576
522
|
* conversation. Most users never turn it on, so the sweep reads only these.
|
|
577
523
|
*/
|
|
578
524
|
async function selectAutoArchiveUsers() {
|
|
579
|
-
const optedInConversation = getDb().select({ userId: juniorConversationParticipants.userId }).from(juniorConversationParticipants).where(and(eq(juniorConversationParticipants.userId, juniorUsers.id), eq(juniorConversationParticipants.autoArchive, true),
|
|
525
|
+
const optedInConversation = getDb().select({ userId: juniorConversationParticipants.userId }).from(juniorConversationParticipants).where(and(eq(juniorConversationParticipants.userId, juniorUsers.id), eq(juniorConversationParticipants.autoArchive, true), rootIsUnarchived()));
|
|
580
526
|
return await getDb().select({
|
|
581
527
|
graceHours: juniorUsers.autoArchiveGraceHours,
|
|
582
528
|
id: juniorUsers.id
|
|
@@ -584,7 +530,7 @@ async function selectAutoArchiveUsers() {
|
|
|
584
530
|
}
|
|
585
531
|
/**
|
|
586
532
|
* Run one auto-archive sweep over every user who wants it and return how
|
|
587
|
-
* many participant rows it checked and archived.
|
|
533
|
+
* many participant rows it checked and how many roots it archived.
|
|
588
534
|
*/
|
|
589
535
|
async function runAutoArchiveSweep(args) {
|
|
590
536
|
const now = new Date(args.nowMs);
|
|
@@ -704,7 +650,8 @@ async function matchReplyToReviewItems(args) {
|
|
|
704
650
|
modelId: botConfig.decisionModelId
|
|
705
651
|
},
|
|
706
652
|
modelId: botConfig.decisionModelId,
|
|
707
|
-
|
|
653
|
+
operation: "review_item_reply_match",
|
|
654
|
+
cost: { conversationId: args.conversationId },
|
|
708
655
|
questions: Object.fromEntries(args.items.map((item, index) => [keys[index], matchQuestion(item)])),
|
|
709
656
|
signal: AbortSignal.timeout(MATCH_TIMEOUT_MS),
|
|
710
657
|
state: [
|
|
@@ -1075,6 +1022,9 @@ function buildAttachmentResolutionFailurePromptText(args) {
|
|
|
1075
1022
|
"</attachment>"
|
|
1076
1023
|
].join("\n");
|
|
1077
1024
|
}
|
|
1025
|
+
function visionCost(conversationId) {
|
|
1026
|
+
return conversationId ? { conversationId } : { owner: "none" };
|
|
1027
|
+
}
|
|
1078
1028
|
async function summarizeImageWithVision(args) {
|
|
1079
1029
|
const visionModelId = botConfig.visionModelId;
|
|
1080
1030
|
if (!visionModelId) return;
|
|
@@ -1082,7 +1032,8 @@ async function summarizeImageWithVision(args) {
|
|
|
1082
1032
|
modelId: visionModelId,
|
|
1083
1033
|
temperature: 0,
|
|
1084
1034
|
maxTokens: args.maxTokens,
|
|
1085
|
-
|
|
1035
|
+
operation: "vision_summary",
|
|
1036
|
+
cost: args.cost,
|
|
1086
1037
|
messages: [{
|
|
1087
1038
|
role: "user",
|
|
1088
1039
|
content: [{
|
|
@@ -1229,6 +1180,7 @@ async function resolveUserAttachmentsWithDeps(attachments, context, deps) {
|
|
|
1229
1180
|
try {
|
|
1230
1181
|
const summary = await summarizeImageWithVision({
|
|
1231
1182
|
completeText: deps.completeText,
|
|
1183
|
+
cost: visionCost(context.conversationId),
|
|
1232
1184
|
imageData: data,
|
|
1233
1185
|
mimeType: mediaType,
|
|
1234
1186
|
maxTokens: 220,
|
|
@@ -1292,6 +1244,7 @@ async function summarizeConversationImage(args, deps) {
|
|
|
1292
1244
|
try {
|
|
1293
1245
|
const summary = await summarizeImageWithVision({
|
|
1294
1246
|
completeText: deps.completeText,
|
|
1247
|
+
cost: visionCost(args.context.conversationId),
|
|
1295
1248
|
imageData: args.imageData,
|
|
1296
1249
|
mimeType: args.mimeType,
|
|
1297
1250
|
maxTokens: 220,
|
|
@@ -1877,63 +1830,6 @@ const LEADING_MENTION_BEFORE_STEERING_RE = /^(\s*(?:<@[^>]+>|@[A-Za-z0-9._-]+\b)
|
|
|
1877
1830
|
function stripLeadingSteeringOverride(text) {
|
|
1878
1831
|
return text.replace(LEADING_MENTION_BEFORE_STEERING_RE, "$1").replace(/^\s*!!\s*/, "");
|
|
1879
1832
|
}
|
|
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
1833
|
// src/chat/task-execution/slack-work.ts
|
|
1938
1834
|
const slackConversationRouteSchema = z.enum(["mention", "subscribed"]);
|
|
1939
1835
|
function hasSteeringOverride(text) {
|
|
@@ -2273,12 +2169,14 @@ function createSlackConversationWorker(options) {
|
|
|
2273
2169
|
task: async () => {
|
|
2274
2170
|
await options.runNextPausedTurn(context.conversationId, {
|
|
2275
2171
|
shouldYield: context.shouldYield,
|
|
2172
|
+
checkIn: context.checkIn,
|
|
2276
2173
|
stopSignal: context.stopSignal?.()
|
|
2277
2174
|
});
|
|
2278
2175
|
}
|
|
2279
2176
|
});
|
|
2280
2177
|
} catch (error) {
|
|
2281
2178
|
if (isCooperativeTurnYieldError(error)) return { status: "yielded" };
|
|
2179
|
+
if (isTurnInputCommitLostError(error)) return { status: "lost_lease" };
|
|
2282
2180
|
throw error;
|
|
2283
2181
|
}
|
|
2284
2182
|
return { status: "completed" };
|
|
@@ -2350,6 +2248,7 @@ function createSlackConversationWorker(options) {
|
|
|
2350
2248
|
ack,
|
|
2351
2249
|
isFinalAttempt: context.attempt.isFinalAttempt,
|
|
2352
2250
|
shouldYield: context.shouldYield,
|
|
2251
|
+
checkIn: context.checkIn,
|
|
2353
2252
|
stopSignal: context.stopSignal?.(),
|
|
2354
2253
|
telemetry
|
|
2355
2254
|
});
|
|
@@ -2361,6 +2260,7 @@ function createSlackConversationWorker(options) {
|
|
|
2361
2260
|
ack,
|
|
2362
2261
|
isFinalAttempt: context.attempt.isFinalAttempt,
|
|
2363
2262
|
shouldYield: context.shouldYield,
|
|
2263
|
+
checkIn: context.checkIn,
|
|
2364
2264
|
stopSignal: context.stopSignal?.(),
|
|
2365
2265
|
telemetry
|
|
2366
2266
|
});
|
|
@@ -2975,6 +2875,7 @@ function createSlackTurnRuntime(deps) {
|
|
|
2975
2875
|
drainSteeringMessages,
|
|
2976
2876
|
onTurnStatePersisted: hooks.onTurnStatePersisted,
|
|
2977
2877
|
shouldYield: hooks.shouldYield,
|
|
2878
|
+
checkIn: hooks.checkIn,
|
|
2978
2879
|
stopSignal: hooks.stopSignal
|
|
2979
2880
|
});
|
|
2980
2881
|
});
|
|
@@ -3266,6 +3167,7 @@ function createSlackTurnRuntime(deps) {
|
|
|
3266
3167
|
drainSteeringMessages,
|
|
3267
3168
|
onTurnStatePersisted: hooks.onTurnStatePersisted,
|
|
3268
3169
|
shouldYield: hooks.shouldYield,
|
|
3170
|
+
checkIn: hooks.checkIn,
|
|
3269
3171
|
stopSignal: hooks.stopSignal
|
|
3270
3172
|
});
|
|
3271
3173
|
});
|
|
@@ -3391,7 +3293,6 @@ function createSubscribedReplyPolicy(deps) {
|
|
|
3391
3293
|
}
|
|
3392
3294
|
// src/chat/app/services.ts
|
|
3393
3295
|
function createJuniorRuntimeServices(overrides = {}) {
|
|
3394
|
-
const conversationMemory = createConversationMemoryService({ completeText: overrides.conversationMemory?.completeText ?? completeText });
|
|
3395
3296
|
const visionContext = createVisionContextService({
|
|
3396
3297
|
attachmentStorage: overrides.visionContext?.attachmentStorage,
|
|
3397
3298
|
completeText: overrides.visionContext?.completeText ?? completeText,
|
|
@@ -3404,7 +3305,6 @@ function createJuniorRuntimeServices(overrides = {}) {
|
|
|
3404
3305
|
tracePropagation: overrides.sandbox?.tracePropagation
|
|
3405
3306
|
});
|
|
3406
3307
|
return {
|
|
3407
|
-
conversationMemory,
|
|
3408
3308
|
executeTurn: async (run, saveResult) => await executeTurn(agentRunner, run, saveResult),
|
|
3409
3309
|
subscribedReplyPolicy: createSubscribedReplyPolicy({ completeDecision: overrides.subscribedReplyPolicy?.completeDecision ?? completeDecision }),
|
|
3410
3310
|
visionContext
|
|
@@ -3812,32 +3712,6 @@ async function maybeApplyProviderDefaultConfigRequest(args) {
|
|
|
3812
3712
|
return { text: `Default GitHub repo set to \`${repo}\`.` };
|
|
3813
3713
|
}
|
|
3814
3714
|
// 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
3715
|
/** Return the actor stored with one inbound Slack message. */
|
|
3842
3716
|
function inboundMessageActor(queued) {
|
|
3843
3717
|
const actor = getMessageActorIdentity(queued.message);
|
|
@@ -4220,6 +4094,7 @@ function createSlackTurn(deps) {
|
|
|
4220
4094
|
createdAtMs: Date.now(),
|
|
4221
4095
|
inputMessageIds: [.../* @__PURE__ */ new Set([...(options.queuedMessages ?? []).map((queued) => queued.message.id), preparedState.userMessageId])],
|
|
4222
4096
|
surface: options.execution?.surface ?? "slack",
|
|
4097
|
+
threadContextThroughSeq: latestConversationMessageSeq(preparedState.conversation),
|
|
4223
4098
|
turnId
|
|
4224
4099
|
});
|
|
4225
4100
|
if (conversationId) {
|
|
@@ -4296,7 +4171,6 @@ function createSlackTurn(deps) {
|
|
|
4296
4171
|
surface: options.execution?.surface ?? "slack"
|
|
4297
4172
|
});
|
|
4298
4173
|
};
|
|
4299
|
-
let turnWakeError;
|
|
4300
4174
|
let boundaryFailureCode = "agent_run_failed";
|
|
4301
4175
|
let terminalDispatchFailureOutcome;
|
|
4302
4176
|
const notifyTurnCompleted = async () => {
|
|
@@ -4413,7 +4287,7 @@ function createSlackTurn(deps) {
|
|
|
4413
4287
|
conversationId,
|
|
4414
4288
|
activeTurnId
|
|
4415
4289
|
})).piMessages;
|
|
4416
|
-
const
|
|
4290
|
+
const hasHistory = Boolean(piMessages?.length);
|
|
4417
4291
|
const batchedSteeringMessages = (await resolveSteeringMessages((options.queuedMessages ?? []).filter((queued) => queued.explicitMention))).map((steering) => ({
|
|
4418
4292
|
message: buildSteeringPiMessage(steering),
|
|
4419
4293
|
provenance: steering.provenance
|
|
@@ -4445,7 +4319,13 @@ function createSlackTurn(deps) {
|
|
|
4445
4319
|
const toolChannelId = channelId;
|
|
4446
4320
|
const activeInstructionAuthorId = actor?.userId ?? parseActorUserId(message.author.userId);
|
|
4447
4321
|
const activeInstructionAuthorName = actor?.fullName ?? actor?.userName;
|
|
4448
|
-
const promptConversationContext =
|
|
4322
|
+
const promptConversationContext = await buildTurnThreadContext({
|
|
4323
|
+
conversation: preparedState.conversation,
|
|
4324
|
+
conversationId,
|
|
4325
|
+
excludeMessageIds: [...(options.queuedMessages ?? []).filter((queued) => queued.explicitMention).map((queued) => queued.message.id), ...preparedState.userMessageId ? [preparedState.userMessageId] : []],
|
|
4326
|
+
hasHistory,
|
|
4327
|
+
turnId
|
|
4328
|
+
});
|
|
4449
4329
|
const drainSteeringMessages = options.drainSteeringMessages ? async (accept) => {
|
|
4450
4330
|
let acceptedMessages;
|
|
4451
4331
|
const drained = await options.drainSteeringMessages(async (queuedMessages) => {
|
|
@@ -4479,7 +4359,6 @@ function createSlackTurn(deps) {
|
|
|
4479
4359
|
...activeInstructionAuthorName ? { authorName: activeInstructionAuthorName } : void 0,
|
|
4480
4360
|
...slackMessageTs ? { slackTs: slackMessageTs } : void 0
|
|
4481
4361
|
},
|
|
4482
|
-
includeConversationContextWithHistory: hasDurablePromptHistory,
|
|
4483
4362
|
...savedInput,
|
|
4484
4363
|
context: promptConversationContext,
|
|
4485
4364
|
inboundAttachmentCount: turnAttachments.length,
|
|
@@ -4523,6 +4402,7 @@ function createSlackTurn(deps) {
|
|
|
4523
4402
|
onInputCommitted: options.ack,
|
|
4524
4403
|
drainSteeringMessages,
|
|
4525
4404
|
shouldYield: options.shouldYield,
|
|
4405
|
+
checkIn: options.checkIn,
|
|
4526
4406
|
onSandboxRefChanged: async (sandboxRef) => {
|
|
4527
4407
|
await persistThreadStateById(conversationId, { sandboxRef });
|
|
4528
4408
|
},
|
|
@@ -4695,7 +4575,6 @@ function createSlackTurn(deps) {
|
|
|
4695
4575
|
"app.ai.resume_session_version": outcome.resumeVersion
|
|
4696
4576
|
});
|
|
4697
4577
|
shouldPersistFailureState = true;
|
|
4698
|
-
turnWakeError = scheduleError;
|
|
4699
4578
|
throw scheduleError;
|
|
4700
4579
|
}
|
|
4701
4580
|
return;
|
|
@@ -4734,7 +4613,11 @@ function createSlackTurn(deps) {
|
|
|
4734
4613
|
shouldPersistFailureState = false;
|
|
4735
4614
|
throw error;
|
|
4736
4615
|
}
|
|
4737
|
-
|
|
4616
|
+
const leaseLoss = error instanceof AgentRunError ? error.cause : error;
|
|
4617
|
+
if (isTurnInputCommitLostError(leaseLoss)) {
|
|
4618
|
+
shouldPersistFailureState = false;
|
|
4619
|
+
throw leaseLoss;
|
|
4620
|
+
}
|
|
4738
4621
|
shouldPersistFailureState = true;
|
|
4739
4622
|
const runFailure = error instanceof AgentRunError ? error.cause : error;
|
|
4740
4623
|
if (options.stopSignal?.aborted) {
|
|
@@ -4898,10 +4781,10 @@ function getBackfillText(entry) {
|
|
|
4898
4781
|
}
|
|
4899
4782
|
/**
|
|
4900
4783
|
* Seed durable conversation memory before the current turn so routing and
|
|
4901
|
-
*
|
|
4784
|
+
* trimming can reason over a thread even when no prior app state exists.
|
|
4902
4785
|
*/
|
|
4903
4786
|
async function seedConversationBackfill(thread, conversation, currentTurn, resolveMessageActors) {
|
|
4904
|
-
if (conversation.messages.length > 0 || conversation.
|
|
4787
|
+
if (conversation.messages.length > 0 || conversation.historyFromSeq !== void 0) return "recent_messages";
|
|
4905
4788
|
const seeded = [];
|
|
4906
4789
|
let source = "recent_messages";
|
|
4907
4790
|
let fetchedNewestFirst;
|
|
@@ -4983,6 +4866,7 @@ function createPrepareTurnState(deps) {
|
|
|
4983
4866
|
const shouldHydrateVisionContext = !conversation.vision.backfillCompletedAtMs || messageHasPotentialImageAttachment || hasPendingImageHydration(conversation);
|
|
4984
4867
|
if (isVisionEnabled() && shouldHydrateVisionContext) {
|
|
4985
4868
|
await deps.hydrateConversationVisionContext(conversation, {
|
|
4869
|
+
conversationId,
|
|
4986
4870
|
threadId: args.context.threadId,
|
|
4987
4871
|
channelId: args.context.channelId,
|
|
4988
4872
|
actorId: args.context.actorId,
|
|
@@ -4995,20 +4879,18 @@ function createPrepareTurnState(deps) {
|
|
|
4995
4879
|
conversation,
|
|
4996
4880
|
conversationId
|
|
4997
4881
|
});
|
|
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({
|
|
4882
|
+
if (conversationId) await hydrateConversationMessages({
|
|
5005
4883
|
conversation,
|
|
5006
4884
|
conversationId
|
|
5007
4885
|
});
|
|
5008
|
-
|
|
4886
|
+
if (await trimConversationMessages(conversation, async () => conversationId ? await loadThreadContextTrimFloor(conversationId) : void 0) && conversationId && conversation.historyFromSeq !== void 0) await persistConversationMessageWindow({
|
|
4887
|
+
conversationId,
|
|
4888
|
+
historyFromSeq: conversation.historyFromSeq
|
|
4889
|
+
});
|
|
4890
|
+
const conversationContext = buildConversationContext(conversation, { excludeMessageIds: [userMessageId] }).text;
|
|
5009
4891
|
setSpanAttributes({
|
|
5010
4892
|
"app.backfill_source": backfillSource ?? "none",
|
|
5011
|
-
"app.context_tokens_estimated":
|
|
4893
|
+
"app.context_tokens_estimated": estimateConversationMessagesTokens(conversation)
|
|
5012
4894
|
});
|
|
5013
4895
|
return {
|
|
5014
4896
|
configuration,
|
|
@@ -5093,6 +4975,7 @@ function createSlackDispatchTurnRunner(options) {
|
|
|
5093
4975
|
errorMessage = result.errorMessage;
|
|
5094
4976
|
},
|
|
5095
4977
|
shouldYield: hooks.shouldYield,
|
|
4978
|
+
checkIn: hooks.checkIn,
|
|
5096
4979
|
skipBackfill: true
|
|
5097
4980
|
});
|
|
5098
4981
|
return {
|
|
@@ -5109,7 +4992,6 @@ function clearSkippedTurnIfActive(conversation, messageId) {
|
|
|
5109
4992
|
function createSlackRuntime(options) {
|
|
5110
4993
|
const services = createJuniorRuntimeServices(options.services);
|
|
5111
4994
|
const prepareTurnState = createPrepareTurnState({
|
|
5112
|
-
compactConversationIfNeeded: services.conversationMemory.compactConversationIfNeeded,
|
|
5113
4995
|
hydrateConversationVisionContext: services.visionContext.hydrateConversationVisionContext,
|
|
5114
4996
|
resolveBackfillMessageActors: async (messages, destination) => {
|
|
5115
4997
|
if (destination.platform !== "slack") throw new Error("Slack turn backfill requires a Slack destination");
|
|
@@ -5660,6 +5542,7 @@ async function resumeSlackTurnInContext(args) {
|
|
|
5660
5542
|
await status.clear();
|
|
5661
5543
|
const runError = error instanceof AgentRunError ? error.cause : error;
|
|
5662
5544
|
if (isCooperativeTurnYieldError(runError)) throw runError;
|
|
5545
|
+
if (isTurnInputCommitLostError(runError)) throw runError;
|
|
5663
5546
|
if (!runResultHandled && runArgs.run?.signal?.aborted) stopped = true;
|
|
5664
5547
|
else if (runResultHandled) {
|
|
5665
5548
|
postDeliveryCommitError = error;
|
|
@@ -6003,7 +5886,6 @@ async function runPausedTurnInContext(payload, options, runOptions) {
|
|
|
6003
5886
|
await persistThreadStateById(payload.conversationId, { conversation });
|
|
6004
5887
|
}
|
|
6005
5888
|
const locationConfiguration = getLocationConfigurationService(destination);
|
|
6006
|
-
const conversationContext = dispatchId ? void 0 : buildConversationContext(conversation, { excludeMessageIds: [userMessage.id] });
|
|
6007
5889
|
const sandboxRef = getPersistedSandboxState(currentState);
|
|
6008
5890
|
const routing = await resolveTurnSessionRouting({ conversationId: payload.conversationId });
|
|
6009
5891
|
const source = routing.source;
|
|
@@ -6031,7 +5913,6 @@ async function runPausedTurnInContext(payload, options, runOptions) {
|
|
|
6031
5913
|
initialStatus: latestProgressStatus(turnMessages),
|
|
6032
5914
|
run: {
|
|
6033
5915
|
instruction: {
|
|
6034
|
-
...conversationContext ? { context: conversationContext } : void 0,
|
|
6035
5916
|
...getTurnUserReplyAttachmentContext(userMessage),
|
|
6036
5917
|
...await savedInputInstruction({
|
|
6037
5918
|
runtime: Boolean(dispatchId) || isEventConversationMessage(userMessage),
|
|
@@ -6059,6 +5940,7 @@ async function runPausedTurnInContext(payload, options, runOptions) {
|
|
|
6059
5940
|
},
|
|
6060
5941
|
durability: {
|
|
6061
5942
|
shouldYield: runOptions.shouldYield,
|
|
5943
|
+
checkIn: runOptions.checkIn,
|
|
6062
5944
|
recordPendingAuth: async (nextPendingAuth) => {
|
|
6063
5945
|
conversation.processing.pendingAuth = nextPendingAuth;
|
|
6064
5946
|
await persistThreadStateById(payload.conversationId, { conversation });
|
|
@@ -6192,43 +6074,7 @@ async function failStrandedTurnWithFallback(args) {
|
|
|
6192
6074
|
});
|
|
6193
6075
|
return true;
|
|
6194
6076
|
}
|
|
6195
|
-
/** Recovery resumes a turn at most once after its worker stops checking in. */
|
|
6196
|
-
const MAX_LOST_WORKER_RESUMES = 1;
|
|
6197
6077
|
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
6078
|
/** Resume the first valid paused Slack session for an idle conversation. */
|
|
6233
6079
|
async function runNextPausedTurn(conversationId, options, runOptions = {}) {
|
|
6234
6080
|
return withLogContext({ conversationId }, () => runNextPausedTurnInContext(conversationId, options, runOptions));
|
|
@@ -6308,642 +6154,6 @@ async function runNextPausedTurnInContext(conversationId, options, runOptions) {
|
|
|
6308
6154
|
}
|
|
6309
6155
|
return false;
|
|
6310
6156
|
}
|
|
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
6157
|
// src/chat/providers/slack/system-turn.ts
|
|
6948
6158
|
/**
|
|
6949
6159
|
* Deliver system Turn output to Slack without a webhook Message.
|
|
@@ -7028,15 +6238,19 @@ function createConversationWork(options) {
|
|
|
7028
6238
|
routingContext: buildDispatchRoutingContext(dispatch),
|
|
7029
6239
|
wakePausedTurn: pausedTurns.wake,
|
|
7030
6240
|
...scheduleCompletedPluginTasks ? { scheduleSessionCompletedPluginTasks: scheduleCompletedPluginTasks } : void 0
|
|
7031
|
-
}, {
|
|
6241
|
+
}, {
|
|
6242
|
+
checkIn: hooks.checkIn,
|
|
6243
|
+
shouldYield: hooks.shouldYield
|
|
6244
|
+
});
|
|
7032
6245
|
},
|
|
7033
6246
|
runTurn: runtime.runDispatchTurn
|
|
7034
6247
|
});
|
|
6248
|
+
const enqueueResult = async (invocation) => await enqueueAgentInvocationResult(invocation, {
|
|
6249
|
+
queue: options.queue,
|
|
6250
|
+
state: options.state
|
|
6251
|
+
});
|
|
7035
6252
|
const childWorker = createChildConversationWorker(options.agentRunner, {
|
|
7036
|
-
enqueueResult
|
|
7037
|
-
queue: options.queue,
|
|
7038
|
-
state: options.state
|
|
7039
|
-
}),
|
|
6253
|
+
enqueueResult,
|
|
7040
6254
|
maxAgentDepth: botConfig.maxAgentDepth,
|
|
7041
6255
|
queue: options.queue,
|
|
7042
6256
|
state: options.state
|
|
@@ -7069,7 +6283,17 @@ function createConversationWork(options) {
|
|
|
7069
6283
|
const stopped = await skipInputAfterConversationStop(attemptContext);
|
|
7070
6284
|
if ("skipped" in stopped) return stopped.skipped;
|
|
7071
6285
|
const { context } = stopped;
|
|
7072
|
-
|
|
6286
|
+
const conversation = await options.conversationStore.get({ conversationId: context.conversationId });
|
|
6287
|
+
if (conversation?.kind === "thread") {
|
|
6288
|
+
const threadTurn = await resolveThreadTurnWork(context);
|
|
6289
|
+
if (!threadTurn) return await childWorker(context);
|
|
6290
|
+
if (threadTurn.kind === "mailbox") await endActiveAgentInvocations(context.conversationId, {
|
|
6291
|
+
enqueueResult,
|
|
6292
|
+
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."
|
|
6293
|
+
});
|
|
6294
|
+
return await conversationTurnWorker(context, threadTurn);
|
|
6295
|
+
}
|
|
6296
|
+
if (conversation?.parentConversationId) return await childWorker(context);
|
|
7073
6297
|
const readStopSignal = context.stopSignal;
|
|
7074
6298
|
let stopSignal;
|
|
7075
6299
|
const stopLateChildAgents = async () => {
|
|
@@ -7152,170 +6376,6 @@ function createProductionConversationWorkOptions(options) {
|
|
|
7152
6376
|
waitUntil: options.waitUntil
|
|
7153
6377
|
});
|
|
7154
6378
|
}
|
|
7155
|
-
// src/api/conversations/read-position.ts
|
|
7156
|
-
/**
|
|
7157
|
-
* Read how far the viewer has read one Conversation, if they have read it.
|
|
7158
|
-
*
|
|
7159
|
-
* The viewer saw every Message up to one they wrote, also one sent from
|
|
7160
|
-
* Slack, so the position is at least their latest Message.
|
|
7161
|
-
*/
|
|
7162
|
-
async function readConversationReadPosition(viewer, conversationId) {
|
|
7163
|
-
const [row] = await conversationReadPositionQuery(viewer, conversationId);
|
|
7164
|
-
return row;
|
|
7165
|
-
}
|
|
7166
|
-
/** Select the viewer's read position, so other reads can embed it. */
|
|
7167
|
-
function conversationReadPositionQuery(viewer, conversationId) {
|
|
7168
|
-
return getDb().select({ lastReadSeq: sql`greatest(${juniorConversationReadPositions.lastReadSeq}, (${latestViewerMessageSeq(viewer, conversationId)}))` }).from(juniorConversationReadPositions).where(and(eq(juniorConversationReadPositions.userId, viewer.id), eq(juniorConversationReadPositions.conversationId, conversationId))).limit(1);
|
|
7169
|
-
}
|
|
7170
|
-
/** The seq of the latest Message that one of the viewer's Identities wrote. */
|
|
7171
|
-
function latestViewerMessageSeq(viewer, conversationId) {
|
|
7172
|
-
return getDb().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, viewer.id)));
|
|
7173
|
-
}
|
|
7174
|
-
/**
|
|
7175
|
-
* Move the viewer's read position forward.
|
|
7176
|
-
*
|
|
7177
|
-
* The stored value never goes back, so devices can report in any order. A
|
|
7178
|
-
* value past the last event is cut to the last event, so a bad client cannot
|
|
7179
|
-
* hide messages that arrive later.
|
|
7180
|
-
*/
|
|
7181
|
-
async function markConversationRead(viewer, conversationId, body) {
|
|
7182
|
-
const db = getDb();
|
|
7183
|
-
const [conversation] = await db.select({ lastSeq: max(juniorConversationEvents.seq) }).from(juniorConversations).leftJoin(juniorConversationEvents, eq(juniorConversationEvents.conversationId, juniorConversations.conversationId)).where(eq(juniorConversations.conversationId, conversationId)).groupBy(juniorConversations.conversationId);
|
|
7184
|
-
if (!conversation) throwApiError(404, "Conversation not found.");
|
|
7185
|
-
await db.insert(juniorConversationReadPositions).values({
|
|
7186
|
-
conversationId,
|
|
7187
|
-
lastReadSeq: Math.min(body.lastReadSeq, conversation.lastSeq ?? 0),
|
|
7188
|
-
updatedAt: /* @__PURE__ */ new Date(),
|
|
7189
|
-
userId: viewer.id
|
|
7190
|
-
}).onConflictDoUpdate({
|
|
7191
|
-
target: [juniorConversationReadPositions.userId, juniorConversationReadPositions.conversationId],
|
|
7192
|
-
set: {
|
|
7193
|
-
lastReadSeq: sql`greatest(${juniorConversationReadPositions.lastReadSeq}, excluded.last_read_seq)`,
|
|
7194
|
-
updatedAt: sql`excluded.updated_at`
|
|
7195
|
-
}
|
|
7196
|
-
});
|
|
7197
|
-
return await readConversationReadPosition(viewer, conversationId);
|
|
7198
|
-
}
|
|
7199
|
-
// 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
|
-
/**
|
|
7240
|
-
* Archive or restore one child for everyone. Archive refuses while any
|
|
7241
|
-
* descendant is unarchived, unless `applyToChildren` archives them too.
|
|
7242
|
-
* Restore changes only this child unless `applyToChildren` also restores the
|
|
7243
|
-
* descendants archived with it, and it refuses while an ancestor child is
|
|
7244
|
-
* archived.
|
|
7245
|
-
*/
|
|
7246
|
-
async function setChildArchive(args) {
|
|
7247
|
-
const executor = getSqlExecutor();
|
|
7248
|
-
return await executor.transaction(async () => {
|
|
7249
|
-
const db = executor.db();
|
|
7250
|
-
const [child] = await db.select({
|
|
7251
|
-
lastActivityAt: juniorConversations.lastActivityAt,
|
|
7252
|
-
rootConversationId: juniorConversations.rootConversationId
|
|
7253
|
-
}).from(juniorConversations).where(eq(juniorConversations.conversationId, args.conversationId)).limit(1).for("update");
|
|
7254
|
-
if (!child?.rootConversationId) return { status: "missing" };
|
|
7255
|
-
if (args.archived && child.lastActivityAt.getTime() !== Date.parse(args.lastSeenAt)) return { status: "conflict" };
|
|
7256
|
-
const tree = await readConversationTrees(db, [child.rootConversationId]);
|
|
7257
|
-
const descendants = conversationDescendants(tree, args.conversationId);
|
|
7258
|
-
if (args.archived) {
|
|
7259
|
-
const unarchived = descendants.filter((node) => !node.childArchivedAt);
|
|
7260
|
-
if (unarchived.length > 0 && !args.applyToChildren) return {
|
|
7261
|
-
status: "unarchived_children",
|
|
7262
|
-
unarchivedChildCount: unarchived.length
|
|
7263
|
-
};
|
|
7264
|
-
const archivedAt = /* @__PURE__ */ new Date();
|
|
7265
|
-
await setChildArchivedAt(db, [args.conversationId, ...unarchived.map((node) => node.conversationId)], archivedAt);
|
|
7266
|
-
return {
|
|
7267
|
-
archivedAt: archivedAt.toISOString(),
|
|
7268
|
-
status: "updated"
|
|
7269
|
-
};
|
|
7270
|
-
}
|
|
7271
|
-
const archivedAncestor = conversationAncestors(tree, args.conversationId).filter((node) => node.kind !== "root" && node.childArchivedAt).at(-1);
|
|
7272
|
-
if (archivedAncestor) return {
|
|
7273
|
-
archivedAncestorId: archivedAncestor.conversationId,
|
|
7274
|
-
status: "archived_ancestor"
|
|
7275
|
-
};
|
|
7276
|
-
const archivedAt = tree.get(args.conversationId)?.childArchivedAt?.getTime();
|
|
7277
|
-
await setChildArchivedAt(db, [args.conversationId, ...args.applyToChildren && archivedAt !== void 0 ? descendants.filter((node) => node.childArchivedAt?.getTime() === archivedAt).map((node) => node.conversationId) : []], null);
|
|
7278
|
-
return {
|
|
7279
|
-
archivedAt: null,
|
|
7280
|
-
status: "updated"
|
|
7281
|
-
};
|
|
7282
|
-
});
|
|
7283
|
-
}
|
|
7284
|
-
/**
|
|
7285
|
-
* Archive or restore one conversation. A root archive applies only to the
|
|
7286
|
-
* signed-in viewer and hides its whole tree for that viewer, so it writes no
|
|
7287
|
-
* child rows and ignores `applyToChildren`. A child archive, Thread or Task,
|
|
7288
|
-
* applies to everyone and follows the rules of `setChildArchive`.
|
|
7289
|
-
*/
|
|
7290
|
-
async function archiveConversation(viewer, conversationId, body) {
|
|
7291
|
-
if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(404, "Conversation not found.");
|
|
7292
|
-
const [target] = await getDb().select({
|
|
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({
|
|
7304
|
-
applyToChildren: body.applyToChildren ?? false,
|
|
7305
|
-
archived: body.archived,
|
|
7306
|
-
conversationId,
|
|
7307
|
-
lastSeenAt: body.lastSeenAt
|
|
7308
|
-
});
|
|
7309
|
-
switch (result.status) {
|
|
7310
|
-
case "updated":
|
|
7311
|
-
if (body.archived && isRoot) await markConversationRead(viewer, conversationId, { lastReadSeq: Number.MAX_SAFE_INTEGER });
|
|
7312
|
-
return { archivedAt: result.archivedAt };
|
|
7313
|
-
case "missing": throwApiError(404, "Conversation not found.");
|
|
7314
|
-
case "conflict": throwApiError(409, "Conversation received new activity.");
|
|
7315
|
-
case "unarchived_children": throwApiError(409, result.unarchivedChildCount === 1 ? "1 child conversation is not archived. Pass applyToChildren to archive it too." : `${result.unarchivedChildCount} child conversations are not archived. Pass applyToChildren to archive them too.`);
|
|
7316
|
-
case "archived_ancestor": throwApiError(409, `Conversation ${result.archivedAncestorId} above this one is archived. Restore it first.`);
|
|
7317
|
-
}
|
|
7318
|
-
}
|
|
7319
6379
|
// src/api/mentions.ts
|
|
7320
6380
|
const SLACK_USER_MENTION_RE = /<@([UW][A-Z0-9]+)(?:\|[^<>]*)?>/g;
|
|
7321
6381
|
function mentionedSlackUserIds(texts) {
|
|
@@ -7377,17 +6437,17 @@ async function readMentionedPeople(executor, tenantId, userIds) {
|
|
|
7377
6437
|
return !person?.fullName && !person?.slackUserName;
|
|
7378
6438
|
});
|
|
7379
6439
|
if (tenantId && unnamed.length > 0) {
|
|
7380
|
-
const profiles = await
|
|
7381
|
-
|
|
7382
|
-
const profile = profiles
|
|
7383
|
-
if (!profile?.fullName && !profile?.userName)
|
|
6440
|
+
const profiles = await lookupSlackUserNames(tenantId, unnamed);
|
|
6441
|
+
for (const id of unnamed) {
|
|
6442
|
+
const profile = profiles.get(id);
|
|
6443
|
+
if (!profile?.fullName && !profile?.userName) continue;
|
|
7384
6444
|
people.set(id, {
|
|
7385
6445
|
...people.get(id),
|
|
7386
6446
|
slackUserId: id,
|
|
7387
6447
|
...profile.fullName ? { fullName: profile.fullName } : void 0,
|
|
7388
6448
|
...profile.userName ? { slackUserName: profile.userName } : void 0
|
|
7389
6449
|
});
|
|
7390
|
-
}
|
|
6450
|
+
}
|
|
7391
6451
|
}
|
|
7392
6452
|
return people;
|
|
7393
6453
|
}
|
|
@@ -7668,7 +6728,7 @@ async function createConversationForViewer(viewer, body, services) {
|
|
|
7668
6728
|
async function appendConversationMessageForViewer(viewer, conversationId, body, services) {
|
|
7669
6729
|
const conversation = await getConversationStore().get({ conversationId });
|
|
7670
6730
|
if (!conversation) throwApiError(404, "Conversation not found.");
|
|
7671
|
-
if (!acceptsWebMessages(
|
|
6731
|
+
if (!acceptsWebMessages(conversation)) throwApiError(409, "Conversation does not accept web messages.");
|
|
7672
6732
|
if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(403, "Only conversation participants can add messages.");
|
|
7673
6733
|
const images = parseImages(body.images);
|
|
7674
6734
|
const actor = actorFromViewer(viewer);
|
|
@@ -8390,7 +7450,7 @@ async function attachActivityPreviewMentions(executor, previews) {
|
|
|
8390
7450
|
*/
|
|
8391
7451
|
function selectConversationRecords(db) {
|
|
8392
7452
|
return db.select({
|
|
8393
|
-
conversation:
|
|
7453
|
+
conversation: juniorConversations,
|
|
8394
7454
|
location: juniorDestinations,
|
|
8395
7455
|
identityDisplayName: juniorIdentities.displayName,
|
|
8396
7456
|
identityEmail: juniorIdentities.email,
|
|
@@ -8429,7 +7489,7 @@ function conversationFromRecordRow(row) {
|
|
|
8429
7489
|
...value.executionUpdatedAt ? { updatedAtMs: value.executionUpdatedAt.getTime() } : void 0
|
|
8430
7490
|
},
|
|
8431
7491
|
...value.parentConversationId ? { parentConversationId: value.parentConversationId } : void 0,
|
|
8432
|
-
...value.
|
|
7492
|
+
...value.archivedAt ? { archivedAtMs: value.archivedAt.getTime() } : void 0,
|
|
8433
7493
|
...actor ? { actor } : void 0,
|
|
8434
7494
|
...location ? { location } : void 0,
|
|
8435
7495
|
...value.channelName ? { channelName: value.channelName } : void 0,
|
|
@@ -8594,7 +7654,6 @@ function conversationSummaryFromStoredConversation(args) {
|
|
|
8594
7654
|
}),
|
|
8595
7655
|
kind: conversation.kind,
|
|
8596
7656
|
...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
7657
|
isParticipant: args.access?.isParticipant ?? false,
|
|
8599
7658
|
...visibility ? { visibility } : void 0,
|
|
8600
7659
|
lastProgressAt: new Date(conversation.execution.updatedAtMs ?? conversation.updatedAtMs).toISOString(),
|
|
@@ -8607,7 +7666,7 @@ function conversationSummaryFromStoredConversation(args) {
|
|
|
8607
7666
|
...args.childAgentTotals ? { childAgentTotals: args.childAgentTotals } : void 0,
|
|
8608
7667
|
...actorIdentity ? { actorIdentity } : void 0,
|
|
8609
7668
|
...locationUrl ? { locationUrl } : void 0,
|
|
8610
|
-
archivedAt:
|
|
7669
|
+
archivedAt: conversation.archivedAtMs === void 0 ? null : new Date(conversation.archivedAtMs).toISOString(),
|
|
8611
7670
|
pinnedAt: args.pinnedAtMs === void 0 ? null : new Date(args.pinnedAtMs).toISOString(),
|
|
8612
7671
|
...args.pinPosition === void 0 ? void 0 : { pinPosition: args.pinPosition },
|
|
8613
7672
|
...unread ? { unread: true } : void 0,
|
|
@@ -8698,7 +7757,10 @@ async function conversationEventPageReport(executor, args) {
|
|
|
8698
7757
|
};
|
|
8699
7758
|
}
|
|
8700
7759
|
// src/api/conversations/agent-tree.ts
|
|
8701
|
-
|
|
7760
|
+
/** Name a child the viewer cannot read, or one with no agent label. */
|
|
7761
|
+
function childLabel(kind) {
|
|
7762
|
+
return kind === "thread" ? "Thread" : "Task";
|
|
7763
|
+
}
|
|
8702
7764
|
/**
|
|
8703
7765
|
* Read the agent tree of a child Conversation: its parent chain, root first,
|
|
8704
7766
|
* with the child last. Returns undefined for a root Conversation. Each
|
|
@@ -8734,13 +7796,13 @@ async function readConversationAgentTree(conversation, readAccess) {
|
|
|
8734
7796
|
if (!itemAccess?.canViewPrivateContent) return {
|
|
8735
7797
|
conversationId: id,
|
|
8736
7798
|
kind,
|
|
8737
|
-
label:
|
|
7799
|
+
label: childLabel(kind)
|
|
8738
7800
|
};
|
|
8739
7801
|
const agent = await getChildAgentLabel(id);
|
|
8740
7802
|
return {
|
|
8741
7803
|
conversationId: id,
|
|
8742
7804
|
kind,
|
|
8743
|
-
label: agent?.title ?? agent?.agentName ??
|
|
7805
|
+
label: agent?.title ?? agent?.agentName ?? childLabel(kind)
|
|
8744
7806
|
};
|
|
8745
7807
|
}));
|
|
8746
7808
|
}
|
|
@@ -8797,12 +7859,20 @@ async function readConversationForks(conversationId, links, readAccess) {
|
|
|
8797
7859
|
* events, so they do not count. It walks the message role index from the
|
|
8798
7860
|
* newest Message, so it stops at the first reply that is not quiet.
|
|
8799
7861
|
*/
|
|
8800
|
-
function latestVisibleReply(db) {
|
|
8801
|
-
return db.select({ seq: juniorConversationEvents.seq }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId,
|
|
7862
|
+
function latestVisibleReply(db, conversationId) {
|
|
7863
|
+
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
7864
|
}
|
|
8803
7865
|
/** 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,
|
|
7866
|
+
function viewerMessageSeq(db, userId, conversationId) {
|
|
7867
|
+
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)));
|
|
7868
|
+
}
|
|
7869
|
+
/**
|
|
7870
|
+
* Whether Junior's latest visible reply is after the viewer's read position
|
|
7871
|
+
* in one outer Conversation. The position is at least the viewer's own
|
|
7872
|
+
* latest Message. No reply reads as false.
|
|
7873
|
+
*/
|
|
7874
|
+
function unreadReplySql(db, userId, conversationId, lastReadSeq) {
|
|
7875
|
+
return sql`coalesce((${latestVisibleReply(db, conversationId)}) > greatest(coalesce(${lastReadSeq}, -1), coalesce((${viewerMessageSeq(db, userId, conversationId)}), -1)), false)`;
|
|
8806
7876
|
}
|
|
8807
7877
|
/**
|
|
8808
7878
|
* Return the Conversations that have a visible Junior reply after the
|
|
@@ -8816,8 +7886,7 @@ function viewerMessageSeq(db, userId) {
|
|
|
8816
7886
|
*/
|
|
8817
7887
|
async function readUnreadConversationIds(db, conversationIds, userId) {
|
|
8818
7888
|
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))`));
|
|
7889
|
+
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
7890
|
return new Set(rows.map((row) => row.conversationId));
|
|
8822
7891
|
}
|
|
8823
7892
|
/**
|
|
@@ -8856,10 +7925,10 @@ async function markConversationUnread(viewer, conversationId, body) {
|
|
|
8856
7925
|
return { unreadReply: false };
|
|
8857
7926
|
}
|
|
8858
7927
|
const db = getDb();
|
|
8859
|
-
const reply = latestVisibleReply(db);
|
|
7928
|
+
const reply = latestVisibleReply(db, juniorConversations.conversationId).as("latest_visible_reply");
|
|
8860
7929
|
const [row] = await db.select({
|
|
8861
7930
|
replySeq: reply.seq,
|
|
8862
|
-
viewerSeq: sql`(${viewerMessageSeq(db, viewer.id)})`
|
|
7931
|
+
viewerSeq: sql`(${viewerMessageSeq(db, viewer.id, juniorConversations.conversationId)})`
|
|
8863
7932
|
}).from(juniorConversations).innerJoinLateral(reply, sql`true`).where(eq(juniorConversations.conversationId, rootConversationId));
|
|
8864
7933
|
if (!row || row.viewerSeq !== null && row.viewerSeq >= row.replySeq) throwApiError(409, "Conversation has no reply after your last message.");
|
|
8865
7934
|
if (row.replySeq === 0) {
|
|
@@ -8907,7 +7976,7 @@ const versionUser = alias(juniorUsers, "version_user");
|
|
|
8907
7976
|
*/
|
|
8908
7977
|
function viewerStateVersion(db, conversationId, viewerId) {
|
|
8909
7978
|
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.
|
|
7979
|
+
const participant = db.select({ state: sql`row(${versionParticipant.pinnedAt}, ${versionParticipant.pinPosition}, ${versionParticipant.autoArchive}, ${versionParticipant.unsubscribedAt})::text` }).from(versionParticipant).where(and(eq(versionParticipant.userId, viewerId), eq(versionParticipant.rootConversationId, sql`(${root})`)));
|
|
8911
7980
|
const autoArchiveDefault = db.select({ value: versionUser.autoArchiveDefault }).from(versionUser).where(eq(versionUser.id, viewerId));
|
|
8912
7981
|
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
7982
|
return sql`md5(concat_ws('|',
|
|
@@ -8940,7 +8009,6 @@ async function readDetailStateRow(conversationId, viewer) {
|
|
|
8940
8009
|
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
8010
|
const viewerParticipant = viewer ? and(eq(juniorConversationParticipants.userId, viewer.id), eq(juniorConversationParticipants.rootConversationId, rootConversationId)) : sql`false`;
|
|
8942
8011
|
const [row] = await db.select({
|
|
8943
|
-
archivedAt: juniorConversationParticipants.archivedAt,
|
|
8944
8012
|
attachmentsVersion: sql`(${slackAttachmentsVersionQuery(db, conversationId)})`,
|
|
8945
8013
|
autoArchive: juniorConversationParticipants.autoArchive,
|
|
8946
8014
|
autoArchiveDefault: juniorUsers.autoArchiveDefault,
|
|
@@ -8952,6 +8020,7 @@ async function readDetailStateRow(conversationId, viewer) {
|
|
|
8952
8020
|
pinnedAt: juniorConversationParticipants.pinnedAt,
|
|
8953
8021
|
pinPosition: juniorConversationParticipants.pinPosition,
|
|
8954
8022
|
rootConversationId: sql`${rootConversationId}`,
|
|
8023
|
+
unsubscribedAt: juniorConversationParticipants.unsubscribedAt,
|
|
8955
8024
|
version: sql`(${conversationVersionQuery(db, conversationId, viewer?.id)})`
|
|
8956
8025
|
}).from(detailConversation).leftJoin(forkSource, eq(forkSource.conversationId, detailConversation.forkedFromConversationId)).leftJoin(juniorConversationParticipants, viewerParticipant).leftJoin(juniorUsers, viewer ? eq(juniorUsers.id, viewer.id) : sql`false`).where(eq(detailConversation.conversationId, conversationId));
|
|
8957
8026
|
return row;
|
|
@@ -8989,6 +8058,7 @@ async function readDetailState(conversationId, viewer, readAccess) {
|
|
|
8989
8058
|
...viewer ? { autoArchive: row?.autoArchive ?? row?.autoArchiveDefault ?? false } : void 0,
|
|
8990
8059
|
forks,
|
|
8991
8060
|
...row?.lastReadSeq != null ? { readPosition: { lastReadSeq: row.lastReadSeq } } : void 0,
|
|
8061
|
+
...viewer ? { subscribed: !row?.unsubscribedAt } : void 0,
|
|
8992
8062
|
transcriptVersion,
|
|
8993
8063
|
...viewer && row ? { unreadReply: unreadIds.has(row.rootConversationId) } : void 0,
|
|
8994
8064
|
...viewerMarks ? { viewerMarks } : void 0
|
|
@@ -9025,6 +8095,7 @@ async function readConversationDetailEtag(conversationId, options) {
|
|
|
9025
8095
|
forks: state.forks,
|
|
9026
8096
|
junior: JUNIOR_VERSION,
|
|
9027
8097
|
limit: options.limit ?? null,
|
|
8098
|
+
subscribed: state.subscribed ?? null,
|
|
9028
8099
|
version,
|
|
9029
8100
|
unreadReply: state.unreadReply ?? false,
|
|
9030
8101
|
viewerMarks: state.viewerMarks ?? null
|
|
@@ -9550,7 +8621,6 @@ function projectConversationDetail(args) {
|
|
|
9550
8621
|
return {
|
|
9551
8622
|
...conversationSummaryFromStoredConversation({
|
|
9552
8623
|
access: args.access,
|
|
9553
|
-
archivedAtMs: args.archivedAtMs,
|
|
9554
8624
|
pinnedAtMs: args.pinnedAtMs,
|
|
9555
8625
|
unreadReply: args.unreadReply,
|
|
9556
8626
|
automationTitle: args.automationTitle,
|
|
@@ -9714,6 +8784,7 @@ async function readConversationDetailFromSql(conversationId, options) {
|
|
|
9714
8784
|
...state.forks,
|
|
9715
8785
|
...state.agentTree ? { agentTree: state.agentTree } : void 0,
|
|
9716
8786
|
...report.isParticipant && state.autoArchive !== void 0 ? { autoArchive: state.autoArchive } : void 0,
|
|
8787
|
+
...report.isParticipant && state.subscribed !== void 0 ? { subscribed: state.subscribed } : void 0,
|
|
9717
8788
|
...canContinueInSlack(record.conversation, access) ? { canContinueInSlack: true } : void 0
|
|
9718
8789
|
};
|
|
9719
8790
|
}
|
|
@@ -9744,35 +8815,46 @@ async function readConversationDetail(conversationId, options = {}) {
|
|
|
9744
8815
|
* A pin lives on the viewer's participant row, and that row grants send and
|
|
9745
8816
|
* control access. So only a participant can pin, the same as archive. The
|
|
9746
8817
|
* 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.
|
|
8818
|
+
* archived conversation for everyone, because the Pinned section shows only
|
|
8819
|
+
* active conversations. A pin on a child would be a fact of the child, not
|
|
8820
|
+
* of the viewer's root, and no list shows child pins yet, so only a root can
|
|
8821
|
+
* be pinned.
|
|
9749
8822
|
*/
|
|
9750
8823
|
async function pinConversation(viewer, conversationId, body) {
|
|
9751
8824
|
if (!(await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant) throwApiError(404, "Conversation not found.");
|
|
9752
8825
|
const executor = getSqlExecutor();
|
|
9753
|
-
|
|
9754
|
-
|
|
9755
|
-
|
|
8826
|
+
return await executor.transaction(() => setPin(executor.db(), viewer, conversationId, body.pinned));
|
|
8827
|
+
}
|
|
8828
|
+
async function setPin(db, viewer, conversationId, pinned) {
|
|
8829
|
+
const [conversation] = await db.select({
|
|
8830
|
+
archivedAt: juniorConversations.archivedAt,
|
|
8831
|
+
kind: juniorConversations.kind,
|
|
8832
|
+
lastActivityAt: juniorConversations.lastActivityAt,
|
|
8833
|
+
parentConversationId: juniorConversations.parentConversationId,
|
|
8834
|
+
rootConversationId: juniorConversations.rootConversationId
|
|
8835
|
+
}).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId)).limit(1).for("no key update");
|
|
8836
|
+
if (!conversation) throwApiError(404, "Conversation not found.");
|
|
8837
|
+
if (conversationKindFromRow(conversation) !== "root") throwApiError(409, `A child conversation cannot be pinned or unpinned. It uses its root's pin: ${conversation.rootConversationId ?? conversation.parentConversationId}.`);
|
|
8838
|
+
if (!pinned) {
|
|
9756
8839
|
await db.update(juniorConversationParticipants).set({
|
|
9757
8840
|
pinnedAt: null,
|
|
9758
8841
|
pinPosition: null
|
|
9759
|
-
}).where(and(eq(juniorConversationParticipants.userId, viewer.id), eq(juniorConversationParticipants.rootConversationId,
|
|
8842
|
+
}).where(and(eq(juniorConversationParticipants.userId, viewer.id), eq(juniorConversationParticipants.rootConversationId, conversationId)));
|
|
9760
8843
|
return { pinnedAt: null };
|
|
9761
8844
|
}
|
|
9762
|
-
|
|
9763
|
-
if (!root) throwApiError(404, "Conversation not found.");
|
|
8845
|
+
if (conversation.archivedAt) await setArchivedAt(db, [conversationId], null);
|
|
9764
8846
|
const pinnedAt = /* @__PURE__ */ new Date();
|
|
9765
8847
|
await db.insert(juniorConversationParticipants).values({
|
|
9766
|
-
lastMessageAt:
|
|
8848
|
+
lastMessageAt: conversation.lastActivityAt,
|
|
9767
8849
|
pinnedAt,
|
|
9768
|
-
rootConversationId,
|
|
8850
|
+
rootConversationId: conversationId,
|
|
9769
8851
|
userId: viewer.id
|
|
9770
8852
|
}).onConflictDoUpdate({
|
|
9771
8853
|
target: [juniorConversationParticipants.userId, juniorConversationParticipants.rootConversationId],
|
|
9772
8854
|
set: {
|
|
9773
|
-
archivedAt: null,
|
|
9774
8855
|
pinnedAt,
|
|
9775
|
-
pinPosition: null
|
|
8856
|
+
pinPosition: null,
|
|
8857
|
+
unsubscribedAt: null
|
|
9776
8858
|
}
|
|
9777
8859
|
});
|
|
9778
8860
|
return { pinnedAt: pinnedAt.toISOString() };
|
|
@@ -9794,28 +8876,28 @@ async function reorderPinnedConversations(viewer, body) {
|
|
|
9794
8876
|
/**
|
|
9795
8877
|
* Find where a Thread nests: its nearest ancestor that is a listed root or a
|
|
9796
8878
|
* Thread. A Thread under a Task moves up. Returns undefined when an ancestor
|
|
9797
|
-
*
|
|
8879
|
+
* is archived, because an archive hides its whole subtree.
|
|
9798
8880
|
*/
|
|
9799
8881
|
function findThreadPlacement(threadId, tree, rootIds) {
|
|
9800
8882
|
let placement;
|
|
9801
8883
|
for (const ancestor of conversationAncestors(tree, threadId)) {
|
|
9802
8884
|
if (rootIds.has(ancestor.conversationId)) return placement ?? ancestor.conversationId;
|
|
9803
|
-
if (ancestor.
|
|
8885
|
+
if (ancestor.archivedAt) return void 0;
|
|
9804
8886
|
if (ancestor.kind === "thread") placement ??= ancestor.conversationId;
|
|
9805
8887
|
}
|
|
9806
8888
|
}
|
|
9807
8889
|
/**
|
|
9808
8890
|
* Read the shown Threads of the listed roots for the feed, nested under
|
|
9809
8891
|
* their nearest shown ancestor. A Thread shows when it and every ancestor
|
|
9810
|
-
*
|
|
9811
|
-
*
|
|
9812
|
-
*
|
|
8892
|
+
* have no `archived_at`. The caller passes only unarchived roots, so a root
|
|
8893
|
+
* archive hides its tree with no writes to the children. A Thread uses the
|
|
8894
|
+
* access of its root.
|
|
9813
8895
|
*/
|
|
9814
8896
|
async function readFeedThreads(db, roots) {
|
|
9815
8897
|
if (roots.length === 0) return /* @__PURE__ */ new Map();
|
|
9816
8898
|
const rootIdList = roots.map((root) => root.conversationId);
|
|
9817
8899
|
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.
|
|
8900
|
+
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
8901
|
if (rows.length === 0) return /* @__PURE__ */ new Map();
|
|
9820
8902
|
const threads = rows.map((row) => ({
|
|
9821
8903
|
conversation: conversationFromRecordRow(row),
|
|
@@ -9925,7 +9007,7 @@ function feedMember(filter) {
|
|
|
9925
9007
|
function conversationFeedMembershipFilter(status, filter) {
|
|
9926
9008
|
if (!filter) return status === "archived" ? sql`false` : void 0;
|
|
9927
9009
|
const member = feedMember(filter);
|
|
9928
|
-
return and(conversationIsMemberRoot(member), status === "archived" ?
|
|
9010
|
+
return and(conversationIsMemberRoot(member), status === "archived" ? isNotNull(juniorConversations.archivedAt) : status === "all" ? void 0 : and(isNull(juniorConversations.archivedAt), conversationIsNotUnsubscribedRoot(member)));
|
|
9929
9011
|
}
|
|
9930
9012
|
/**
|
|
9931
9013
|
* Keep root conversations linked to one code repository. A code change can
|
|
@@ -9979,30 +9061,54 @@ async function waitingRowsOutsidePage(db, filter, page) {
|
|
|
9979
9061
|
});
|
|
9980
9062
|
}
|
|
9981
9063
|
const feedTree = alias(juniorConversations, "feed_tree");
|
|
9064
|
+
const feedAnnotated = alias(juniorConversations, "feed_annotated");
|
|
9982
9065
|
/**
|
|
9983
9066
|
* Return a query for a token that changes when the viewer's default feed
|
|
9984
9067
|
* page can change. It reads the same newest page as the feed, so its cost
|
|
9985
9068
|
* does not grow with the viewer's history.
|
|
9986
9069
|
*
|
|
9987
|
-
*
|
|
9988
|
-
*
|
|
9989
|
-
*
|
|
9990
|
-
*
|
|
9991
|
-
*
|
|
9070
|
+
* The token holds only what a feed row shows, so a Task's own writes do not
|
|
9071
|
+
* move it. Each content write moves its Conversation's `last_activity_at`,
|
|
9072
|
+
* so the root's value covers the preview and participants. The row shows
|
|
9073
|
+
* only whether a reply is unread, so a scroll that moves the read position
|
|
9074
|
+
* does not move the token.
|
|
9075
|
+
* Threads and annotations show from the whole tree. Waiting roots outside
|
|
9076
|
+
* the page move the Review items token.
|
|
9992
9077
|
*/
|
|
9993
9078
|
function conversationFeedVersionQuery(db, userId) {
|
|
9994
9079
|
const pin = juniorConversationParticipants;
|
|
9080
|
+
const read = juniorConversationReadPositions;
|
|
9995
9081
|
const page = db.select({
|
|
9996
9082
|
conversationId: juniorConversations.conversationId,
|
|
9083
|
+
channelName: juniorConversations.channelName,
|
|
9084
|
+
executionStatus: juniorConversations.executionStatus,
|
|
9085
|
+
lastActivityAt: juniorConversations.lastActivityAt,
|
|
9086
|
+
lastReadSeq: read.lastReadSeq,
|
|
9997
9087
|
pinnedAt: pin.pinnedAt,
|
|
9998
|
-
pinPosition: pin.pinPosition
|
|
9999
|
-
|
|
9088
|
+
pinPosition: pin.pinPosition,
|
|
9089
|
+
stoppedAt: juniorConversations.stoppedAt,
|
|
9090
|
+
title: juniorConversations.title
|
|
9091
|
+
}).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
9092
|
kind: "viewer",
|
|
10001
9093
|
userId
|
|
10002
9094
|
}))).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(':',
|
|
9095
|
+
const tree = db.select({ version: sql`concat_ws(':',
|
|
9096
|
+
count(*) filter (where ${feedTree.archivedAt} is not null),
|
|
9097
|
+
string_agg(concat_ws('/',
|
|
9098
|
+
${feedTree.conversationId}, ${feedTree.title},
|
|
9099
|
+
${feedTree.executionStatus}, ${feedTree.stoppedAt},
|
|
9100
|
+
${feedTree.lastActivityAt}
|
|
9101
|
+
), ',' order by ${feedTree.conversationId}) filter (
|
|
9102
|
+
where ${feedTree.kind} = 'thread' and ${feedTree.archivedAt} is null
|
|
9103
|
+
)
|
|
9104
|
+
)` }).from(feedTree).where(eq(feedTree.rootConversationId, page.conversationId));
|
|
9105
|
+
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
9106
|
return db.select({ version: sql`md5(coalesce(string_agg(
|
|
10005
|
-
concat_ws('@', ${page.conversationId}, ${page.pinnedAt}, ${page.pinPosition},
|
|
9107
|
+
concat_ws('@', ${page.conversationId}, ${page.pinnedAt}, ${page.pinPosition},
|
|
9108
|
+
${page.title}, ${page.channelName}, ${page.executionStatus},
|
|
9109
|
+
${page.stoppedAt}, ${page.lastActivityAt},
|
|
9110
|
+
${unreadReplySql(db, userId, page.conversationId, page.lastReadSeq)},
|
|
9111
|
+
(${tree}), (${annotations})),
|
|
10006
9112
|
',' order by ${page.conversationId}
|
|
10007
9113
|
), ''))` }).from(page);
|
|
10008
9114
|
}
|
|
@@ -10065,7 +9171,7 @@ async function readConversationFeedFromSql(options = {}) {
|
|
|
10065
9171
|
]);
|
|
10066
9172
|
const visibleActivityPreviews = await attachActivityPreviewMentions(getSqlExecutor(), new Map([...activityPreviewByConversation].filter(([conversationId]) => accessByConversation.get(conversationId)?.canViewPrivateContent)));
|
|
10067
9173
|
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,
|
|
9174
|
+
const [sidebarAnnotationsByConversation, threadsByRoot] = await Promise.all([listConversationSidebarAnnotations(conversationIds, visibleAnnotationsByConversation), readFeedThreads(db, conversations.filter((conversation) => conversation.archivedAtMs === void 0).map(({ conversationId }) => ({
|
|
10069
9175
|
access: accessByConversation.get(conversationId),
|
|
10070
9176
|
conversationId
|
|
10071
9177
|
})))]);
|
|
@@ -10203,4 +9309,4 @@ function viewerWebMessages(messages, viewer) {
|
|
|
10203
9309
|
}] : [];
|
|
10204
9310
|
});
|
|
10205
9311
|
}
|
|
10206
|
-
export {
|
|
9312
|
+
export { readReviewItemForUser as $, createProductionConversationWorkOptions as A, clearSlackPendingReactions as B, createConversationForViewer as C, readConversationPendingMessages as D, cancelConversationPendingMessagesForViewer as E, isAllowedSignInEmail as F, createSlackWebApiStatusSender as G, stripLeadingBotMention as H, readEnvList as I, recordSkippedConversationMessage as J, stopConversation as K, resolveAllowedDomains as L, getProductionSlackAdapter as M, assertNoLegacyAllowedDomains as N, requireConversationPendingMessages as O, isAllowedDomain as P, closeReviewItemsAnsweredByReply as Q, startProcessingReaction as R, appendConversationMessageForViewer as S, encodeConversationCursor as T, normalizeIncomingSlackThreadId as U, slackInboundMessageId as V, withNormalizedThreadId as W, ReviewItemActionError as X, bindMessageAuthorIdentityId as Y, actOnReviewItem as Z, keepQuickQuestionForViewer as _, pinConversation as a, setConversationAutoArchive as at, readConversationRecordFromSql as b, continueConversationInSlackForViewer as c, enqueueAgentDispatch as ct, readConversationTreeMetricsFromSql as d, reviewItemChange as et, conversationVersionQuery as f, forkConversationForViewer as g, reportConversationRead as h, readConversationFeed as i, runAutoArchiveSweep as it, createProductionSlackWebhookServices as j, resolveMentions as k, readConversationAuxiliaryCostsFromSql as l, GET as lt, markConversationUnread as m, steerConversationPendingMessagesForViewer as n, archiveViewerDoneConversations as nt, reorderPinnedConversations as o, updateUserAutoArchiveSettings as ot, readConversationDetailEtag as p, parseContent as q, conversationFeedVersionQuery as r, readUserAutoArchiveSettings as rt, readConversationDetail as s, AGENT_DISPATCH_MAX_AGE_MS as st, stopConversationTurnForViewer as t, DEFAULT_AUTO_ARCHIVE_SETTINGS as tt, childAgentTotalsReport as u, readHealthReport as ut, readConversationEvents as v, decodeConversationCursor as w, readFirstHumanMessageTexts as x, conversationSummaryFromStoredConversation as y, buildSlackInboundMessage as z };
|