@sentry/junior 0.312.0 → 0.313.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapter-iIq7ihf7.js → adapter-CYAvJzZS.js} +1 -1
- package/dist/{adapter-context-BRjEWRy1.js → adapter-context-CVsHoVSf.js} +2 -2
- package/dist/{admin-DhInw5K9.js → admin-Cyhb4TwZ.js} +1 -1
- package/dist/{agent-runner-C9iDurwX.js → agent-runner-B5y9MsT-.js} +93 -45
- package/dist/api/schema.d.ts +1 -1
- package/dist/api/schema.js +4 -4
- package/dist/api.d.ts +1 -1
- package/dist/api.js +40 -40
- package/dist/{app-DRFrC8Mw.d.ts → app-DA8-hCMj.d.ts} +2 -2
- package/dist/app.d.ts +1 -1
- package/dist/app.js +31 -33
- package/dist/{background-compaction-queue-DrKi7w3d.js → background-compaction-queue-iZXadLV3.js} +56 -6
- package/dist/{catalog-runtime-D7xapBAX.js → catalog-runtime-kkE3hvCX.js} +1 -1
- package/dist/{channel-access-CJGfNTdn.js → channel-access-mt7K6dPh.js} +2 -2
- package/dist/cli/chat.js +16 -16
- package/dist/cli/check.js +3 -3
- package/dist/cli/main.js +2 -2
- package/dist/cli/plugins.js +4 -4
- package/dist/cli/snapshot-create.js +5 -5
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +3 -3
- package/dist/{config-kXB2Y5tl.js → config-CWbwKj0j.js} +3 -3
- package/dist/{continue-in-slack-O6pV5004.js → continue-in-slack-CxyFzdlF.js} +6 -6
- package/dist/{conversation-feed-uNOv_x68.js → conversation-feed-BEXLD3Me.js} +13 -2
- package/dist/{conversation-privacy-L4ja1_W6.js → conversation-privacy-BrMiDN61.js} +1 -1
- package/dist/{conversation-turn-CeLbHqdw.js → conversation-turn-B35eu0uz.js} +63 -45
- package/dist/{credential-sync-I8VBGk05.js → credential-sync-DWTOEQrm.js} +15 -16
- package/dist/{credentialed-Cb6E2phL.js → credentialed-Dyv8b-lu.js} +12 -14
- package/dist/{db-BbC5stfa.d.ts → db-DYGcXYl3.d.ts} +1 -1
- package/dist/{db-LAyyX8tk.js → db-PwSRzWWn.js} +17 -19
- package/dist/{executor-SCub-fAq.js → executor-CgWyWfYz.js} +2 -4
- package/dist/{html-BCZ3Xtb_.js → html-DidUcRhI.js} +6 -6
- package/dist/ingest-B0AggUEC.js +7931 -0
- package/dist/{install-DCFJFkC0.js → install-2urLLXNt.js} +2 -2
- package/dist/instrumentation.js +2 -2
- package/dist/{lineage-B_m-4TJw.js → lineage-BXplQAVH.js} +2 -2
- package/dist/{list-CN2QA2R9.js → list-DyIyReSV.js} +82 -69
- package/dist/{logging-dQ9ZRGQ8.js → logging-DNt-qOIO.js} +1 -1
- package/dist/{media-CYm1QD8T.js → media-B0pZJ0bG.js} +9 -6
- package/dist/{message-DSXGj1hM.js → message-Z5YKC-Af.js} +23 -9
- package/dist/{model-input--TrP9hYV.js → model-input-BhPJYdSV.js} +3 -3
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +4 -4
- package/dist/{oauth-callback-server-DHCZC6B4.js → oauth-callback-server-ByvDdcdY.js} +2 -2
- package/dist/{oauth-relay-pPMGnDZt.js → oauth-relay-D-kK0yoN.js} +1 -1
- package/dist/{registry-CZOzddwu.js → registry-POH4bZC4.js} +1 -1
- package/dist/{statuses-_cRJHXK7.js → reporting-window-C4dbzDiR.js} +1 -27
- package/dist/request-deadline-BUiRYQYj.js +24 -0
- package/dist/{resolve-cKOQ14Dh.js → resolve-CWtBNSKP.js} +3 -3
- package/dist/{runner-DBfUW44l.js → runner-CsZ_VRxp.js} +8 -8
- package/dist/{sandbox-egress-signals-BVF_xAm1.js → sandbox-egress-signals-FbCk1FkN.js} +1 -1
- package/dist/{schema-BEHKxr4I.d.ts → schema-DBf18QPS.d.ts} +131 -912
- package/dist/{schema-Bk9Nm2E8.js → schema-DojR2uCL.js} +4 -4
- package/dist/{service-account-CVYsFjty.js → service-account-CDYb9hfX.js} +3 -3
- package/dist/{service-account-Ts4ulcrV.js → service-account-o15pZWcJ.js} +5 -5
- package/dist/{skills-VTnhAJWm.js → skills-B0jP4whm.js} +2 -2
- package/dist/{slack-conversation-unfurl-fuLnF1jE.js → slack-conversation-unfurl-D26t9kBC.js} +8 -8
- package/dist/{spawn-vxAarlX5.js → spawn-BjljgExZ.js} +14 -33
- package/dist/{start-conversation-CEn2KH1A.js → start-conversation-DbVujrwO.js} +10 -196
- package/dist/{state-C1P3_Ywk.js → state-BTawTCme.js} +4 -4
- package/dist/{result-event-type-BdIJuZxg.js → statuses-BKwqCPhj.js} +25 -4
- package/dist/{store-DFZaN-Ix.js → store-CjXrp-Up.js} +3 -3
- package/dist/{task-queue-Cx4Lmjyk.js → task-queue-Cwlatjz3.js} +4 -4
- package/dist/{task-runner-CbTwFA6k.js → task-runner--Ke8KSMf.js} +11 -11
- package/dist/{thread-context-BkAZDTX2.js → thread-context-B8exINEe.js} +6 -7
- package/dist/{thread-state-DhPndWi1.js → turn-membership-DTR3SaKD.js} +251 -17
- package/dist/{validation-nIzMtAVJ.js → validation-Ce0qbMlT.js} +1 -1
- package/dist/{vercel-queue-hW90XzbG.js → vercel-queue-q4z8w5QO.js} +2 -2
- package/dist/{version-Brbtz4Qf.js → version-DFh4n9nr.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{warmup-BDA5myRK.js → warmup-D5hzqTcp.js} +44 -2969
- package/dist/{worker-D63RcaVD.js → worker-CDg9Lbpg.js} +6 -6
- package/migrations/0158_keep_legacy_archive_columns.sql +5 -0
- package/migrations/0159_conversation_embeddings_fk_validate.sql +5 -0
- package/migrations/meta/0158_snapshot.json +6515 -0
- package/migrations/meta/0159_snapshot.json +6515 -0
- package/migrations/meta/_journal.json +14 -0
- package/package.json +5 -5
- package/dist/callback-mFlTUWWx.js +0 -75
- package/dist/child-message-DcsritGf.js +0 -179
- package/dist/ingest-BDf3D50j.js +0 -3836
- package/dist/result-DcvEOe1r.js +0 -574
|
@@ -1,30 +1,29 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
|
|
2
|
-
import {
|
|
3
|
-
import { B as requestPrefixAttributes, G as gatewayRoutingAttributes, H as estimateRequestOverheadTokens, J as isCompactionSummaryText, K as COMPACTION_SUMMARY_PREFIX, O as resolveGatewayModel, R as fenceLock, U as estimateTextTokens, V as estimateMessagesTokens, W as textCharsForTokens, Z as unwrapCurrentInstruction, b as GEN_AI_SERVER_ADDRESS, ct as findProviderError, ft as isProviderRetryError, g as TURN_REASONING_LEVELS, lt as getProviderErrorAttributes, n as botConfig,
|
|
4
|
-
import { E as withSpan, G as runWithLogAttributes,
|
|
2
|
+
import { $n as replyTextSchema, Dt as EVENT_AUTHOR_ID, Ft as getAgentContextCompactionTriggerTokens, It as getAgentContextInputLimitTokens, Nt as calculateContextCompactionTargetTokens, Pt as getAgentBackgroundCompactionMarkTokens, X as loadConversationProjection, Yn as REPLY_TOOL_NAME, _ as appendAndEnqueueInboundMessage, _n as withIdleConversation, ar as isLegacyNoReplyMarker, hr as projectConversationEvents, ir as findLegacyNoReplyMarker, lr as REPORT_BLOCKED_TOOL_NAME, mr as piMessageFromHistoryItem, pr as historyItemFromPiMessage, rr as NO_REPLY_TOOL_NAME } from "./turn-membership-DTR3SaKD.js";
|
|
3
|
+
import { B as requestPrefixAttributes, G as gatewayRoutingAttributes, H as estimateRequestOverheadTokens, J as isCompactionSummaryText, K as COMPACTION_SUMMARY_PREFIX, O as resolveGatewayModel, R as fenceLock, U as estimateTextTokens, V as estimateMessagesTokens, W as textCharsForTokens, Z as unwrapCurrentInstruction, b as GEN_AI_SERVER_ADDRESS, ct as findProviderError, ft as isProviderRetryError, g as TURN_REASONING_LEVELS, lt as getProviderErrorAttributes, n as botConfig, ot as createAssistantProviderError, pt as getGatewayApiKey, q as hasCompactedConversationContext, r as getChatConfig, rt as renderThreadContext, st as createProviderError, y as GEN_AI_PROVIDER_NAME, z as withLock } from "./config-CWbwKj0j.js";
|
|
4
|
+
import { E as withSpan, G as runWithLogAttributes, T as withLogContext, Y as toOptionalString, a as extractGenAiUsageSummary, b as setSpanAttributes, g as normalizeGenAiFinishReason, h as logWarn, i as extractGenAiUsageAttributes, l as getLogContextAttributesForSpan, m as logInfo, p as logException, v as serializeGenAiAttribute, z as getDeploymentId } from "./logging-DNt-qOIO.js";
|
|
5
5
|
import { g as withActiveSpan, h as startSpan, m as startInactiveSpan, n as captureMessage, u as sentry_exports } from "./sentry-CPbZjomA.js";
|
|
6
6
|
import { t as mapBounded } from "./fan-out-Cod-yEHG.js";
|
|
7
|
-
import {
|
|
8
|
-
import { n as pluginCatalogRuntime } from "./catalog-runtime-
|
|
9
|
-
import {
|
|
10
|
-
import { $ as SEARCHABLE_EVENT_TYPES, $a as WORKSPACE_SNAPSHOT_FAILED_EVENT, $o as registeredResourceTypeSchema, Aa as ownerConversationId, An as workspaceRepoCheckoutPath, Ao as getSlackClient, At as RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS, Bt as listWorkspaces, Ca as dismissOpenInboxItems, Da as insertInboxItem, Do as downloadPrivateSlackFile, Eo as SlackActionError, Gi as setEventAutomationStatus, Gn as embedConversationQuery, Go as describeRegisteredEventTrigger, Gt as loadSnapshotsForProfile, H as fuseRankedLists, Hi as listDeletedEventAutomationsCreatedBy, Ht as updateWorkspace, It as createWorkspace, Ja as requireSlackChannelMessageScope, Ji as automationDefinition, Jn as createPluginAnnotations, Jo as eventWatchUnavailable, Jt as create, Ka as getEventCatalog, Kr as getSlackMessagePermalink, Kt as setWorkspaceSnapshot, Lt as deleteWorkspace, Mr as getDispatchInputMessageId, Mt as RESOURCE_WATCH_TOOL_SOURCE, Na as updateInboxItemContent, Nr as getDispatchRecord, Nt as STOP_WATCHING_TOOL_NAME,
|
|
11
|
-
import {
|
|
12
|
-
import { $t as formatUserInputAnswer, Bt as toolScheduleIntentSchema, Ct as removedCardSchema, Gt as isValidTimeZone, Ht as getFirstRunAtMs, Lt as ScheduleIntentError, Rt as compileScheduleIntent, Vt as weekdaySchema, Wt as getZonedDateTimeParts, an as automationTaskDescription, b as automationListQuerySchema, ct as AGENT_TYPES, dt as formatAgentTypes, l as apiErrorSchema,
|
|
7
|
+
import { At as automationCreatorUserId, Ct as isPluginInboxItem, Dt as requireInboxItemLinks, Et as requireInboxItemAssignees, Gt as identityAvatarUrl, I as watchRepeatsChildResults, In as touchConversationDetail, Jt as readUserAvatarUrls, K as usdToMicroUsd, Mn as resolveRootConversationId, Mt as resolveAssignees, N as promptModeTurnTools, Nn as rootConversationIsArchived, On as agentTurnCostUsd, Ot as EVERYONE_ASSIGNEE, S as userMessageQueries, Tt as readInboxItemAgentScope, Z as conversationStatusSql, Zt as SYSTEM_IDENTITY_ID, _ as readConversationTrees, a as getConversationStore, at as AUTOMATION_INBOX_ITEM_KEY_PREFIX, bn as readableSlackTeamId, ct as canAgentChangeInboxItem, d as eventFromRow, dn as ToolInputError, g as conversationDescendants, h as conversationAncestors, hn as canReadConversation, i as getConversationMessageSearchStore, jt as resolveAssignee, kt as activeParticipantUserIds, lt as canReadInboxItem, mn as canAddConversationMessages, o as getDb, ot as PLUGIN_INBOX_ITEM_KEY_PREFIX, r as getConversationEventStore, s as getSqlExecutor, v as setArchivedAt, vn as readConversationAccessFromSql } from "./db-PwSRzWWn.js";
|
|
8
|
+
import { n as pluginCatalogRuntime } from "./catalog-runtime-kkE3hvCX.js";
|
|
9
|
+
import { An as parseTodoRef, Bn as buildDeploymentSystemPrompt, Cn as listParentTodoIds, Dn as renderTodoAssignee, En as TODO_DELTA_TAG, G as AgentDepthLimitError, Gn as findVisibleAgentsInstructions, J as AgentMessageTargetError, K as AgentInvocationLimitError, Mn as todoRef, N as stopChildAgent, Nn as todoRefSchema, On as renderTodosSnapshot, Pn as addConversationNote, Qn as withAgentRequest, Rn as isExperimentalFeatureEnabled, X as AgentStoppedError, Xn as foldSystemMessages, Y as AgentNameInUseError, Yn as foldLeadingSystemMessages, Z as findChildAgentConversationId, Zn as readAgentHistory, a as listDescendantAgents, at as getLatestAgentInvocationForConversation, bn as changeTodos, dt as CHILD_AGENT_RESULTS, ft as PARENT_AGENT_TARGET, h as readLastParentMessageAtMs, i as listChildAgents, jn as todoOutputSchema, kn as outputTodo, pt as agentNameSchema, q as AgentMessageQueueFullError, qn as renderAgentsInstructions, r as listAgentRelatives, st as listOpenAgentInvocations, t as ingestEvent, tt as NON_TERMINAL_AGENT_INVOCATION_STATUSES, ut as CHILD_AGENT_KINDS, wn as listTodos, xn as closeTodosForChild, xt as EVENT_WAIT_MS, yn as saveUserCustomization } from "./ingest-B0AggUEC.js";
|
|
10
|
+
import { $ as SEARCHABLE_EVENT_TYPES, $a as WORKSPACE_SNAPSHOT_FAILED_EVENT, $o as registeredResourceTypeSchema, Aa as ownerConversationId, An as workspaceRepoCheckoutPath, Ao as getSlackClient, At as RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS, Bt as listWorkspaces, Ca as dismissOpenInboxItems, Da as insertInboxItem, Do as downloadPrivateSlackFile, Eo as SlackActionError, Gi as setEventAutomationStatus, Gn as embedConversationQuery, Go as describeRegisteredEventTrigger, Gt as loadSnapshotsForProfile, H as fuseRankedLists, Hi as listDeletedEventAutomationsCreatedBy, Ht as updateWorkspace, It as createWorkspace, Ja as requireSlackChannelMessageScope, Ji as automationDefinition, Jn as createPluginAnnotations, Jo as eventWatchUnavailable, Jt as create, Ka as getEventCatalog, Kr as getSlackMessagePermalink, Kt as setWorkspaceSnapshot, Lt as deleteWorkspace, Mr as getDispatchInputMessageId, Mt as RESOURCE_WATCH_TOOL_SOURCE, Na as updateInboxItemContent, Nr as getDispatchRecord, Nt as STOP_WATCHING_TOOL_NAME, On as SANDBOX_RUNTIME, Oo as getFilePermalink, Ot as getSlackToolContext, Po as normalizeSlackConversationId, Qa as slackChannelMessageTrigger, Qi as sameDefinitionValue, Qo as registeredEventTypeSchema, Qt as getSandboxProvider, Rn as searchConversations, Ro as withSlackRetries, Rt as getWorkspace, Ta as getOpenInboxItemByDedupeKey, Ui as parseEventAutomationRow, Ut as WorkspaceValidationError, Wi as saveEventAutomation, Wo as automationEventCatalog, Wt as invalidateReadySnapshot, X as searchedEventTextSql, Xi as listAutomationVersions, Xo as registeredEventMatchSchema, Xt as isStale, Y as lexemesSql, Yo as hasEventCatalogEntries, Z as seqIn, Zi as readAutomationVersion, Zn as defaultTimezone, Zo as registeredEventTriggerProblems, _ as getStaticPluginToolDefinitions, _a as fallbackShortTitle, _r as SANDBOX_WORKSPACE_ROOT, _t as retainRuntimeTurnContext, aa as readAutomationExecutionStatusDays, ao as publishConversationStatus, as as createPluginCache, bi as saveScheduledAutomation, bn as createSandboxEgressCredentialToken, bt as CAPABILITY_SECTION_TAG, c as createPluginHookRunner, ca as readAutomationExecutions, cr as userLookupIdentityProviders, cs as completeText, ea as automationRevision, eo as WORKSPACE_SNAPSHOT_READY_EVENT, es as requireEventIdentifier, et as callsToolSql, gi as deleteScheduledAutomation, go as listWatches, h as getPlugins, hn as isWorkspaceSnapshotNotReadyError, ia as readAutomationExecutionByConversationId, ir as lookupUsers, ja as searchInboxItems, ji as getDashboardTaskLink, jo as isConversationScopedChannel, jr as getDispatchIdForConversation, jt as RESOURCE_SUBSCRIPTION_MAX_TTL_MS, la as readAutomationRowStats, ln as isAbortError, lo as createTimerWatch, lt as hasTurnInput, mr as SANDBOX_REPOS_ROOT, na as emptyAutomationRunWindows, no as workspaceSnapshotWatch, nr as isSlackUserNotFound, nt as excerptTerms, oa as readAutomationExecutionStatusHours, pn as WorkspaceSnapshotNotReadyError, po as getWatch, pt as isStandaloneRuntimeContextMessage, qn as saveObjectAnnotations, qo as eventNamespaceSchema, qr as openSlackDirectMessage, qt as setWorkspaceSnapshotBuild, rr as looksLikeEmail, sa as readAutomationExecutionSummaries, so as cancelWatch, ta as requireAutomationRevision, to as workspaceSnapshotFinishedEvent, ts as requireValidEventTrigger, tt as eventExcerpt, ua as readAutomationRuns, ui as slackMention, uo as createWatch, us as searchWeb, vi as parseScheduledAutomationRow, vo as turnEvents, vt as stripRuntimeTurnContext, wa as getInboxItem, wi as getDashboardConversationLink, wn as buildSandboxEgressNetworkPolicy, wr as createPluginLogger, xa as closeInboxItem, xt as REQUEST_CONTEXT_SECTION_TAG, ya as resolveTaskTitle, yt as trimTrailingAssistantMessages, zi as deleteEventAutomation, zo as sleep, zt as getWorkspaceByName } from "./credentialed-Dyv8b-lu.js";
|
|
11
|
+
import { D as zodToolDefinition, E as zodTool, b as matchSlackAttachments, f as webActorFromUser, k as juniorToolOutputSchema, n as startConversationToolDefinition, o as acceptsWebMessages, s as appendAndEnqueueWebMessage } from "./start-conversation-DbVujrwO.js";
|
|
12
|
+
import { $t as formatUserInputAnswer, Bt as toolScheduleIntentSchema, Ct as removedCardSchema, Gt as isValidTimeZone, Ht as getFirstRunAtMs, Lt as ScheduleIntentError, Rt as compileScheduleIntent, Vt as weekdaySchema, Wt as getZonedDateTimeParts, an as automationTaskDescription, b as automationListQuerySchema, ct as AGENT_TYPES, dt as formatAgentTypes, l as apiErrorSchema, nn as userInputRequestSchema, on as automationTaskSchema, qt as eventAutomationTriggerSchema, rn as automationSkillNameSchema, sn as automationTaskText } from "./media-B0pZJ0bG.js";
|
|
13
13
|
import { d as parseSlackChannelReferenceId, f as parseSlackTeamId, o as isUserActor, p as parseSlackUserId, u as parseSlackChannelId, v as parseSlackMessageTs } from "./actor-BsBdxDXQ.js";
|
|
14
|
-
import { C as juniorConversationParticipants, D as juniorConversationEventEmbeddings, E as juniorConversationEventLexemes, H as juniorConversations, K as juniorUsers, M as juniorConversationEvents, S as juniorConversationReadPositions, U as juniorIdentities, _ as juniorAutomationRuns, at as guardedCosineDistance,
|
|
15
|
-
import { t as discoverSkills } from "./skills-
|
|
16
|
-
import {
|
|
17
|
-
import { c as listChannelMessages, l as listThreadReplies, n as joinPublicChannelForRead, s as joinPublicChannel, t as checkSlackChannelReadAccess } from "./channel-access-
|
|
18
|
-
import {
|
|
19
|
-
import { d as
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
22
|
-
import { n as
|
|
23
|
-
import { a as getStateValues, i as getStateAdapter, o as setStateValues } from "./adapter-
|
|
24
|
-
import { c as QUEUE_SIGNATURE_MAX_AGE_MS, t as getVercelConversationWorkQueue } from "./vercel-queue-
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
27
|
-
import { a as toCanonicalInputMessage, i as runWithConversationPrivacy, o as toCanonicalOutputMessage, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-L4ja1_W6.js";
|
|
14
|
+
import { C as juniorConversationParticipants, D as juniorConversationEventEmbeddings, E as juniorConversationEventLexemes, H as juniorConversations, K as juniorUsers, M as juniorConversationEvents, S as juniorConversationReadPositions, U as juniorIdentities, _ as juniorAutomationRuns, at as guardedCosineDistance, g as juniorAutomations, l as juniorStats, q as juniorDestinations } from "./executor-CgWyWfYz.js";
|
|
15
|
+
import { t as discoverSkills } from "./skills-B0jP4whm.js";
|
|
16
|
+
import { s as sumUtcHoursIntoSixHours } from "./reporting-window-C4dbzDiR.js";
|
|
17
|
+
import { c as listChannelMessages, l as listThreadReplies, n as joinPublicChannelForRead, s as joinPublicChannel, t as checkSlackChannelReadAccess } from "./channel-access-mt7K6dPh.js";
|
|
18
|
+
import { d as userCustomizationTextSchema, g as isOpenTodoStatus, l as USER_CUSTOMIZATION_MAX_CHARS, m as TODO_STATUSES, p as SELF_TODO_ASSIGNEE } from "./statuses-BKwqCPhj.js";
|
|
19
|
+
import { d as contextProvenance, t as KNOWN_CONVERSATION_EVENT_TYPES } from "./history-CYstOMKX.js";
|
|
20
|
+
import { p as credentialContextForActor } from "./registry-POH4bZC4.js";
|
|
21
|
+
import { t as getTurnRequestDeadline } from "./request-deadline-BUiRYQYj.js";
|
|
22
|
+
import { n as postinstall, o as getSandboxResources, t as dependencies } from "./install-2urLLXNt.js";
|
|
23
|
+
import { a as getStateValues, i as getStateAdapter, o as setStateValues } from "./adapter-CYAvJzZS.js";
|
|
24
|
+
import { c as QUEUE_SIGNATURE_MAX_AGE_MS, t as getVercelConversationWorkQueue } from "./vercel-queue-q4z8w5QO.js";
|
|
25
|
+
import { f as sendNextWorkspaceSnapshotJob, l as sendCacheWarmup, n as backgroundCompactionId, p as sendWorkspaceSnapshotJob } from "./background-compaction-queue-iZXadLV3.js";
|
|
26
|
+
import { a as toCanonicalInputMessage, i as runWithConversationPrivacy, o as toCanonicalOutputMessage, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-BrMiDN61.js";
|
|
28
27
|
import * as z from "zod";
|
|
29
28
|
import pLimit from "p-limit";
|
|
30
29
|
import { streamSimple } from "@earendil-works/pi-ai/compat";
|
|
@@ -33,9 +32,9 @@ import { isDeepStrictEqual, promisify } from "node:util";
|
|
|
33
32
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
34
33
|
import { createHash, randomUUID } from "node:crypto";
|
|
35
34
|
import { createAssistantMessageEventStream, getInitialSystemMessage, getSystemMessageText as getSystemMessageText$1, mergeClientIdentity } from "@earendil-works/pi-ai";
|
|
36
|
-
import {
|
|
35
|
+
import { agentEventKeys, agentEventMatchKey, agentEventMatchSchema, declaredEventKeys, escapeTagTextAndQuotes, eventMatchFieldSchema, eventTriggerText, findTag, ownedObjectAnnotationSchema, renderInlineTag, stableEventMatchKey, startsWithTag, stripTags, watchResultSchema } from "@sentry/junior-plugin-api";
|
|
37
36
|
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
38
|
-
import { and, asc, count, desc, eq,
|
|
37
|
+
import { and, asc, count, desc, eq, gt, gte, inArray, isNotNull, isNull, lt, lte, max, min, ne, not, notInArray, or, sql } from "drizzle-orm";
|
|
39
38
|
import { alias, unionAll } from "drizzle-orm/pg-core";
|
|
40
39
|
import { Agent, DEFAULT_AGENT_IDENTITY } from "@earendil-works/pi-agent-core";
|
|
41
40
|
import http from "node:http";
|
|
@@ -4338,29 +4337,12 @@ function richTextField(columnId, value) {
|
|
|
4338
4337
|
}]
|
|
4339
4338
|
};
|
|
4340
4339
|
}
|
|
4341
|
-
const DEFAULT_TODO_SCHEMA = [
|
|
4342
|
-
|
|
4343
|
-
|
|
4344
|
-
|
|
4345
|
-
|
|
4346
|
-
|
|
4347
|
-
},
|
|
4348
|
-
{
|
|
4349
|
-
key: "completed",
|
|
4350
|
-
name: "Completed",
|
|
4351
|
-
type: "checkbox"
|
|
4352
|
-
},
|
|
4353
|
-
{
|
|
4354
|
-
key: "assignee",
|
|
4355
|
-
name: "Assignee",
|
|
4356
|
-
type: "user"
|
|
4357
|
-
},
|
|
4358
|
-
{
|
|
4359
|
-
key: "due_date",
|
|
4360
|
-
name: "Due Date",
|
|
4361
|
-
type: "date"
|
|
4362
|
-
}
|
|
4363
|
-
];
|
|
4340
|
+
const DEFAULT_TODO_SCHEMA = [{
|
|
4341
|
+
key: "task",
|
|
4342
|
+
name: "Task",
|
|
4343
|
+
type: "text",
|
|
4344
|
+
is_primary_column: true
|
|
4345
|
+
}];
|
|
4364
4346
|
/** Create a new Slack todo list with the default schema. */
|
|
4365
4347
|
async function createTodoList(name) {
|
|
4366
4348
|
const client = getSlackClient();
|
|
@@ -5498,9 +5480,9 @@ async function updateConversationSubscription(person, conversationId, subscribed
|
|
|
5498
5480
|
subscribed: false
|
|
5499
5481
|
};
|
|
5500
5482
|
const archivedAt = /* @__PURE__ */ new Date();
|
|
5501
|
-
await
|
|
5483
|
+
await setArchivedAt(db, inConversationTree(rootConversationId), archivedAt, isNull(juniorConversations.archivedAt));
|
|
5502
5484
|
if (await hasSubscriber(db, rootConversationId)) {
|
|
5503
|
-
await
|
|
5485
|
+
await setArchivedAt(db, inConversationTree(rootConversationId), null, eq(juniorConversations.archivedAt, archivedAt));
|
|
5504
5486
|
return {
|
|
5505
5487
|
archivedAt: null,
|
|
5506
5488
|
subscribed: false
|
|
@@ -5547,28 +5529,8 @@ async function hasSubscriber(db, rootConversationId) {
|
|
|
5547
5529
|
const [subscriber] = await db.select({ userId: juniorConversationParticipants.userId }).from(juniorConversationParticipants).where(and(eq(juniorConversationParticipants.rootConversationId, rootConversationId), isNull(juniorConversationParticipants.unsubscribedAt))).limit(1);
|
|
5548
5530
|
return Boolean(subscriber);
|
|
5549
5531
|
}
|
|
5550
|
-
/**
|
|
5551
|
-
* Archive the root and each descendant that is not archived. Descendants
|
|
5552
|
-
* that are already archived keep their own time. The test runs on the
|
|
5553
|
-
* latest row, so a descendant that a Turn restores while this waits is
|
|
5554
|
-
* archived too. A child that a Turn adds while this runs stays unarchived,
|
|
5555
|
-
* and its next Message restores the root.
|
|
5556
|
-
*/
|
|
5557
|
-
async function archiveTree(db, rootConversationId, archivedAt) {
|
|
5558
|
-
await db.update(juniorConversations).set({
|
|
5559
|
-
archivedAt: sql`coalesce(${juniorConversations.archivedAt}, ${archivedAt.toISOString()}::timestamptz)`,
|
|
5560
|
-
detailVersion: nextDetailVersion
|
|
5561
|
-
}).where(inConversationTree(rootConversationId));
|
|
5562
|
-
}
|
|
5563
|
-
/** Undo `archiveTree`: restore only what it archived at `archivedAt`. */
|
|
5564
|
-
async function restoreTree(db, rootConversationId, archivedAt) {
|
|
5565
|
-
await db.update(juniorConversations).set({
|
|
5566
|
-
archivedAt: null,
|
|
5567
|
-
detailVersion: nextDetailVersion
|
|
5568
|
-
}).where(and(inConversationTree(rootConversationId), eq(juniorConversations.archivedAt, archivedAt)));
|
|
5569
|
-
}
|
|
5570
5532
|
function inConversationTree(rootConversationId) {
|
|
5571
|
-
return
|
|
5533
|
+
return sql`(${eq(juniorConversations.conversationId, rootConversationId)} or ${eq(juniorConversations.rootConversationId, rootConversationId)})`;
|
|
5572
5534
|
}
|
|
5573
5535
|
const setConversationSubscriptionToolDefinition = zodToolDefinition({
|
|
5574
5536
|
exposure: "deferred",
|
|
@@ -5613,2899 +5575,6 @@ function createSetConversationSubscriptionTool(context) {
|
|
|
5613
5575
|
}
|
|
5614
5576
|
});
|
|
5615
5577
|
}
|
|
5616
|
-
// src/chat/conversations/agent-config.ts
|
|
5617
|
-
/**
|
|
5618
|
-
* The agent settings that every Turn of one Conversation keeps, for any
|
|
5619
|
-
* kind: its Agent type, its reasoning level, and whether it started with its
|
|
5620
|
-
* parent's history. A kind sets only the fields that apply to it.
|
|
5621
|
-
*/
|
|
5622
|
-
const agentConfigSchema = z.object({
|
|
5623
|
-
agentType: agentTypeSchema.optional(),
|
|
5624
|
-
fork: z.literal(true).optional(),
|
|
5625
|
-
reasoningLevel: z.enum(TURN_REASONING_LEVELS).optional()
|
|
5626
|
-
}).strict();
|
|
5627
|
-
/**
|
|
5628
|
-
* Read the agent config that one Conversation stores, or undefined when it
|
|
5629
|
-
* stores none. Today only a child that a spawn created without an Agent
|
|
5630
|
-
* invocation row stores one. A child that an Agent invocation names reads
|
|
5631
|
-
* its settings from its row first.
|
|
5632
|
-
*/
|
|
5633
|
-
async function readAgentConfig(conversationId) {
|
|
5634
|
-
const [row] = await getSqlExecutor().db().select({ agentConfig: juniorConversations.agentConfig }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId));
|
|
5635
|
-
return row?.agentConfig ? agentConfigSchema.parse(row.agentConfig) : void 0;
|
|
5636
|
-
}
|
|
5637
|
-
// src/chat/runtime/turn-execution.ts
|
|
5638
|
-
/** An error thrown while the agent advances a Run. */
|
|
5639
|
-
var AgentRunError = class extends Error {
|
|
5640
|
-
constructor(cause) {
|
|
5641
|
-
super(cause instanceof Error ? cause.message : "Agent Run failed", { cause });
|
|
5642
|
-
this.name = "AgentRunError";
|
|
5643
|
-
}
|
|
5644
|
-
};
|
|
5645
|
-
/**
|
|
5646
|
-
* Run the agent and finish the Turn after the caller saves its result.
|
|
5647
|
-
*
|
|
5648
|
-
* A paused Run, or a Run waiting for authorization, leaves the Turn open. A
|
|
5649
|
-
* save error also leaves the Turn open so the worker can retry or recover it.
|
|
5650
|
-
*/
|
|
5651
|
-
async function executeTurn(agentRunner, run, saveResult) {
|
|
5652
|
-
let outcome;
|
|
5653
|
-
try {
|
|
5654
|
-
outcome = await agentRunner.run(run);
|
|
5655
|
-
} catch (error) {
|
|
5656
|
-
throw new AgentRunError(error);
|
|
5657
|
-
}
|
|
5658
|
-
if (outcome.status !== "completed") return outcome;
|
|
5659
|
-
const saved = await saveResult(outcome.result);
|
|
5660
|
-
await finishTurn(run.conversationId, run.turnId, saved);
|
|
5661
|
-
return { status: "completed" };
|
|
5662
|
-
}
|
|
5663
|
-
/** Record the terminal lifecycle event of a Turn from its saved result. */
|
|
5664
|
-
async function finishTurn(conversationId, turnId, saved) {
|
|
5665
|
-
const lifecycle = getTurnLifecycle();
|
|
5666
|
-
const common = {
|
|
5667
|
-
conversationId,
|
|
5668
|
-
createdAtMs: saved.finishedAtMs ?? Date.now(),
|
|
5669
|
-
turnId
|
|
5670
|
-
};
|
|
5671
|
-
if (saved.outcome === "failed") await lifecycle.fail({
|
|
5672
|
-
...common,
|
|
5673
|
-
...saved.eventId ? { eventId: saved.eventId } : void 0,
|
|
5674
|
-
failureCode: saved.failureCode,
|
|
5675
|
-
...saved.failureReason ? { failureReason: saved.failureReason } : void 0
|
|
5676
|
-
});
|
|
5677
|
-
else await lifecycle.complete({
|
|
5678
|
-
...common,
|
|
5679
|
-
outcome: saved.outcome
|
|
5680
|
-
});
|
|
5681
|
-
}
|
|
5682
|
-
// src/chat/services/automated-turn-limit.ts
|
|
5683
|
-
const AUTOMATED_TURN_LIMIT_PREFIX = "junior:automated_turn_limit:v1";
|
|
5684
|
-
const AUTOMATED_TURN_LIMIT_LOCK_TTL_MS = 5e3;
|
|
5685
|
-
const AUTOMATED_TURN_LIMIT_LOCK_WAIT_MS = 2e3;
|
|
5686
|
-
const AUTOMATED_TURN_LIMIT_LOCK_RETRY_MS = 25;
|
|
5687
|
-
/**
|
|
5688
|
-
* Stored consecutive automated-turn count for one Conversation. Parsing
|
|
5689
|
-
* strips the fields of the old pause, so its count still applies.
|
|
5690
|
-
*/
|
|
5691
|
-
const automatedTurnLimitStateSchema = z.object({
|
|
5692
|
-
consecutiveAutomatedTurns: z.number().int().nonnegative(),
|
|
5693
|
-
updatedAtMs: z.number().finite().nonnegative()
|
|
5694
|
-
});
|
|
5695
|
-
function sleep(ms) {
|
|
5696
|
-
return new Promise((resolve) => {
|
|
5697
|
-
setTimeout(resolve, ms).unref?.();
|
|
5698
|
-
});
|
|
5699
|
-
}
|
|
5700
|
-
function conversationKey$1(conversationId) {
|
|
5701
|
-
return `${AUTOMATED_TURN_LIMIT_PREFIX}:conversation:${conversationId}`;
|
|
5702
|
-
}
|
|
5703
|
-
function lockKey(key) {
|
|
5704
|
-
return `${key}:lock`;
|
|
5705
|
-
}
|
|
5706
|
-
function parseState(value) {
|
|
5707
|
-
const parsed = automatedTurnLimitStateSchema.safeParse(value);
|
|
5708
|
-
return parsed.success ? parsed.data : void 0;
|
|
5709
|
-
}
|
|
5710
|
-
async function acquireConversationLock(state, key, waitDeadlineMs = Date.now() + AUTOMATED_TURN_LIMIT_LOCK_WAIT_MS) {
|
|
5711
|
-
while (true) {
|
|
5712
|
-
const lock = await state.acquireLock(lockKey(key), AUTOMATED_TURN_LIMIT_LOCK_TTL_MS);
|
|
5713
|
-
if (lock) return lock;
|
|
5714
|
-
if (Date.now() >= waitDeadlineMs) throw new Error(`Could not acquire automated turn limit lock for ${key}`);
|
|
5715
|
-
await sleep(AUTOMATED_TURN_LIMIT_LOCK_RETRY_MS);
|
|
5716
|
-
}
|
|
5717
|
-
}
|
|
5718
|
-
async function withConversationLock(state, key, callback) {
|
|
5719
|
-
const lock = await acquireConversationLock(state, key);
|
|
5720
|
-
try {
|
|
5721
|
-
return await callback();
|
|
5722
|
-
} finally {
|
|
5723
|
-
await state.releaseLock(lock);
|
|
5724
|
-
}
|
|
5725
|
-
}
|
|
5726
|
-
function emptyState(nowMs) {
|
|
5727
|
-
return {
|
|
5728
|
-
consecutiveAutomatedTurns: 0,
|
|
5729
|
-
updatedAtMs: nowMs
|
|
5730
|
-
};
|
|
5731
|
-
}
|
|
5732
|
-
/** True when this Source starts an automated Turn rather than a user Turn. */
|
|
5733
|
-
function isAutomatedTurnSource(source) {
|
|
5734
|
-
if (!source) return false;
|
|
5735
|
-
return source.kind === "event" || source.kind === "event_automation" || source.kind === "scheduled_automation" || source.kind === "plugin_dispatch" || source.kind === "agent_invocation";
|
|
5736
|
-
}
|
|
5737
|
-
/** Plain notice when automatic updates stop until the user replies. */
|
|
5738
|
-
function buildAutomatedTurnLimitResponse(args) {
|
|
5739
|
-
return `I stopped automatic updates after ${args.maxTurns} automated turns without a new message from you. Turns with no reply also count. Send a message or @mention me in this thread to continue.`;
|
|
5740
|
-
}
|
|
5741
|
-
/** Count one finished automated Turn toward the consecutive-turn limit. */
|
|
5742
|
-
async function countAutomatedTurn(args) {
|
|
5743
|
-
if (args.maxTurns < 1) throw new Error("Automated turn limit must be at least 1");
|
|
5744
|
-
const state = args.state ?? getStateAdapter();
|
|
5745
|
-
await state.connect();
|
|
5746
|
-
const nowMs = args.nowMs ?? Date.now();
|
|
5747
|
-
const key = conversationKey$1(args.conversationId);
|
|
5748
|
-
return await withConversationLock(state, key, async () => {
|
|
5749
|
-
const consecutiveAutomatedTurns = (parseState(await state.get(key)) ?? emptyState(nowMs)).consecutiveAutomatedTurns + 1;
|
|
5750
|
-
await state.set(key, {
|
|
5751
|
-
consecutiveAutomatedTurns,
|
|
5752
|
-
updatedAtMs: nowMs
|
|
5753
|
-
}, JUNIOR_THREAD_STATE_TTL_MS);
|
|
5754
|
-
return {
|
|
5755
|
-
consecutiveAutomatedTurns,
|
|
5756
|
-
reached: consecutiveAutomatedTurns >= args.maxTurns
|
|
5757
|
-
};
|
|
5758
|
-
});
|
|
5759
|
-
}
|
|
5760
|
-
/** Clear the consecutive automated-turn count after a user-owned Turn. */
|
|
5761
|
-
async function resetAutomatedTurnLimit(args) {
|
|
5762
|
-
const state = args.state ?? getStateAdapter();
|
|
5763
|
-
await state.connect();
|
|
5764
|
-
const key = conversationKey$1(args.conversationId);
|
|
5765
|
-
await withConversationLock(state, key, async () => {
|
|
5766
|
-
await state.delete(key);
|
|
5767
|
-
});
|
|
5768
|
-
}
|
|
5769
|
-
/**
|
|
5770
|
-
* Update consecutive automated-turn counts after one finished Turn.
|
|
5771
|
-
*
|
|
5772
|
-
* Automated Turns count on the Conversation. User Turns clear that count.
|
|
5773
|
-
*/
|
|
5774
|
-
async function recordFinishedTurnForAutomatedLimit(args) {
|
|
5775
|
-
const nowMs = args.nowMs ?? Date.now();
|
|
5776
|
-
if (isAutomatedTurnSource(args.source)) return await countAutomatedTurn({
|
|
5777
|
-
conversationId: args.conversationId,
|
|
5778
|
-
maxTurns: args.maxTurns,
|
|
5779
|
-
nowMs,
|
|
5780
|
-
state: args.state
|
|
5781
|
-
});
|
|
5782
|
-
await resetAutomatedTurnLimit({
|
|
5783
|
-
conversationId: args.conversationId,
|
|
5784
|
-
nowMs,
|
|
5785
|
-
state: args.state
|
|
5786
|
-
});
|
|
5787
|
-
}
|
|
5788
|
-
// src/chat/agent-invocations/markers.ts
|
|
5789
|
-
/**
|
|
5790
|
-
* Dashboard records for agent invocations. The parent Conversation gets one
|
|
5791
|
-
* `subagent_started` and one `subagent_ended` event for each agent invocation.
|
|
5792
|
-
* The child Conversation gets `message` events for its input and its result,
|
|
5793
|
-
* because a child posts nothing to its Location.
|
|
5794
|
-
*/
|
|
5795
|
-
const SUBAGENT_KIND = "agent";
|
|
5796
|
-
/**
|
|
5797
|
-
* Record in the parent Conversation that one agent invocation started, and
|
|
5798
|
-
* record its input as a user message in the child Conversation. The dashboard
|
|
5799
|
-
* pairs the parent event with `subagent_ended` to show the child and its
|
|
5800
|
-
* status. It must be written before the child mailbox append, so the child
|
|
5801
|
-
* cannot end first. An agent wrote the input, not a person, so the message
|
|
5802
|
-
* names its agent invocation instead of an author. Input from Events, such as
|
|
5803
|
-
* the child's own Watch Events, passes their Event fields, so the dashboard
|
|
5804
|
-
* shows it as an Event, as on a root.
|
|
5805
|
-
*/
|
|
5806
|
-
async function recordSubagentStarted(invocation, eventMeta) {
|
|
5807
|
-
const eventStore = getConversationEventStore();
|
|
5808
|
-
const messageId = getAgentInvocationMessageId(invocation.invocationId);
|
|
5809
|
-
await eventStore.append(invocation.childConversationId, [{
|
|
5810
|
-
idempotencyKey: `message:${messageId}`,
|
|
5811
|
-
data: {
|
|
5812
|
-
type: "message",
|
|
5813
|
-
messageId,
|
|
5814
|
-
role: "user",
|
|
5815
|
-
text: invocation.input,
|
|
5816
|
-
meta: {
|
|
5817
|
-
...eventMeta,
|
|
5818
|
-
agentInvocationId: invocation.invocationId
|
|
5819
|
-
}
|
|
5820
|
-
},
|
|
5821
|
-
createdAtMs: invocation.createdAtMs
|
|
5822
|
-
}]);
|
|
5823
|
-
await eventStore.append(invocation.parentConversationId, [{
|
|
5824
|
-
idempotencyKey: `subagent_started:${invocation.invocationId}`,
|
|
5825
|
-
data: {
|
|
5826
|
-
type: "subagent_started",
|
|
5827
|
-
subagentInvocationId: invocation.invocationId,
|
|
5828
|
-
subagentKind: SUBAGENT_KIND,
|
|
5829
|
-
childConversationId: invocation.childConversationId,
|
|
5830
|
-
...invocation.agentName ? { agentName: invocation.agentName } : void 0,
|
|
5831
|
-
...invocation.parentToolCallId ? {
|
|
5832
|
-
parentToolCallId: invocation.parentToolCallId,
|
|
5833
|
-
task: invocation.input
|
|
5834
|
-
} : void 0,
|
|
5835
|
-
...invocation.title ? { title: invocation.title } : void 0,
|
|
5836
|
-
...invocation.reasoningLevel ? { reasoningLevel: invocation.reasoningLevel } : void 0
|
|
5837
|
-
},
|
|
5838
|
-
createdAtMs: invocation.createdAtMs
|
|
5839
|
-
}]);
|
|
5840
|
-
}
|
|
5841
|
-
const SUBAGENT_OUTCOMES = {
|
|
5842
|
-
blocked: "blocked",
|
|
5843
|
-
completed: "success",
|
|
5844
|
-
failed: "error",
|
|
5845
|
-
stopped: "aborted"
|
|
5846
|
-
};
|
|
5847
|
-
/**
|
|
5848
|
-
* Record in the parent Conversation how one agent invocation ended, and record
|
|
5849
|
-
* a completed result as an assistant message in the child Conversation. The
|
|
5850
|
-
* heartbeat result repair also calls this, because the child work can be
|
|
5851
|
-
* acknowledged before the worker reports the result.
|
|
5852
|
-
*/
|
|
5853
|
-
async function recordSubagentEnded(invocation) {
|
|
5854
|
-
const eventStore = getConversationEventStore();
|
|
5855
|
-
await eventStore.append(invocation.parentConversationId, [{
|
|
5856
|
-
idempotencyKey: `subagent_ended:${invocation.invocationId}`,
|
|
5857
|
-
data: {
|
|
5858
|
-
type: "subagent_ended",
|
|
5859
|
-
subagentInvocationId: invocation.invocationId,
|
|
5860
|
-
outcome: SUBAGENT_OUTCOMES[invocation.status]
|
|
5861
|
-
},
|
|
5862
|
-
createdAtMs: invocation.terminalAtMs
|
|
5863
|
-
}]);
|
|
5864
|
-
const result = invocation.status === "completed" ? invocation.result.trim() : "";
|
|
5865
|
-
if (!result) return;
|
|
5866
|
-
const messageId = `agent-invocation:${invocation.invocationId}:reply`;
|
|
5867
|
-
await eventStore.append(invocation.childConversationId, [{
|
|
5868
|
-
idempotencyKey: `message:${messageId}`,
|
|
5869
|
-
data: {
|
|
5870
|
-
type: "message",
|
|
5871
|
-
messageId,
|
|
5872
|
-
role: "assistant",
|
|
5873
|
-
text: result
|
|
5874
|
-
},
|
|
5875
|
-
createdAtMs: invocation.terminalAtMs
|
|
5876
|
-
}]);
|
|
5877
|
-
}
|
|
5878
|
-
// src/chat/agent-invocations/stop.ts
|
|
5879
|
-
/**
|
|
5880
|
-
* Stop one child agent of a parent Conversation and every child agent below
|
|
5881
|
-
* it. The parent gets no result. SQL stops the work first. Then each
|
|
5882
|
-
* Conversation in the tree stops through `stopConversationTree`, which keeps
|
|
5883
|
-
* their Watches and holds their automated input.
|
|
5884
|
-
*
|
|
5885
|
-
* Returns undefined when the child does not belong to the parent.
|
|
5886
|
-
*/
|
|
5887
|
-
async function stopChildAgent(args) {
|
|
5888
|
-
const [latest, stoppedAtMs] = await Promise.all([getLatestAgentInvocationForConversation(args.childConversationId), getConversationStoppedAtMs(args.childConversationId)]);
|
|
5889
|
-
const wasStopped = latest ? latest.status === "stopped" || isChildAgentSessionStopped(latest, stoppedAtMs) : stoppedAtMs !== void 0;
|
|
5890
|
-
const tree = await stopChildAgentInvocations(args);
|
|
5891
|
-
if (!tree) return;
|
|
5892
|
-
await finishStoppedTree(tree, tree.conversationIds, {
|
|
5893
|
-
stoppedAtMs: Date.now(),
|
|
5894
|
-
state: args.state
|
|
5895
|
-
});
|
|
5896
|
-
await dropUnreadLoopReplies([args.parentConversationId, ...tree.conversationIds], tree.conversationIds, args.state);
|
|
5897
|
-
return { stopped: tree.stopped.length > 0 || !wasStopped };
|
|
5898
|
-
}
|
|
5899
|
-
/**
|
|
5900
|
-
* Stop the child agents of a Conversation whose run saw its stop. A child
|
|
5901
|
-
* agent's worker calls this after it records its own stop, and the root work
|
|
5902
|
-
* path in `app/conversation-work.ts` calls it for a root. So this sends no
|
|
5903
|
-
* stop request to that Conversation.
|
|
5904
|
-
*
|
|
5905
|
-
* The worker can see its stop late. The stop already reached every child
|
|
5906
|
-
* agent that existed then, so this stops only child agents that this
|
|
5907
|
-
* Conversation spawned or gave new work to after its stop, even when they
|
|
5908
|
-
* already finished, and everything below them. When the stop already ended,
|
|
5909
|
-
* because a person or the parent gave the Conversation new input, this does
|
|
5910
|
-
* nothing.
|
|
5911
|
-
*
|
|
5912
|
-
* Only a person's stop of this Conversation itself leaves child agents to
|
|
5913
|
-
* stop here: an agent stop, or a stop of a Conversation above it, stops this
|
|
5914
|
-
* Conversation's own agent invocations first, so it cannot spawn more.
|
|
5915
|
-
*/
|
|
5916
|
-
async function stopChildAgentsOf(conversationId, state) {
|
|
5917
|
-
const stoppedAtMs = await getConversationStoppedAtMs(conversationId);
|
|
5918
|
-
if (stoppedAtMs === void 0) return;
|
|
5919
|
-
const nowMs = Date.now();
|
|
5920
|
-
const tree = await stopAgentInvocationTree(conversationId, nowMs, {
|
|
5921
|
-
includeRoot: false,
|
|
5922
|
-
taskedAfterMs: stoppedAtMs
|
|
5923
|
-
});
|
|
5924
|
-
const stoppedIds = tree.conversationIds.filter((id) => id !== conversationId);
|
|
5925
|
-
await finishStoppedTree(tree, stoppedIds, {
|
|
5926
|
-
nowMs,
|
|
5927
|
-
stoppedAtMs,
|
|
5928
|
-
state
|
|
5929
|
-
});
|
|
5930
|
-
await dropUnreadLoopReplies(tree.conversationIds, stoppedIds, state);
|
|
5931
|
-
await dropOwnUnreadLoopReplies(conversationId, state);
|
|
5932
|
-
}
|
|
5933
|
-
/**
|
|
5934
|
-
* Stop every child agent below a Conversation that a person stops. The
|
|
5935
|
-
* Conversation's own agent invocations stay as they are: when it is a child
|
|
5936
|
-
* agent, its worker records the stop and reports it to its parent. Call it
|
|
5937
|
-
* through `stopConversation`, which stops the Conversation's Turn next.
|
|
5938
|
-
*
|
|
5939
|
-
* The Conversation's run sees its stop only at its next stop signal check.
|
|
5940
|
-
* When it does, `stopChildAgentsOf` stops the child agents that it spawned or
|
|
5941
|
-
* gave new work to before then, at the time of this stop. So input that ends
|
|
5942
|
-
* this stop ends theirs too.
|
|
5943
|
-
*/
|
|
5944
|
-
async function stopChildAgentsBelow(conversationId, options) {
|
|
5945
|
-
const { nowMs, queue, stoppedAtMs, state } = options;
|
|
5946
|
-
const tree = await stopAgentInvocationTree(conversationId, nowMs, { includeRoot: false });
|
|
5947
|
-
const stoppedIds = tree.conversationIds.filter((id) => id !== conversationId);
|
|
5948
|
-
await finishStoppedTree(tree, stoppedIds, {
|
|
5949
|
-
nowMs,
|
|
5950
|
-
queue,
|
|
5951
|
-
stoppedAtMs,
|
|
5952
|
-
state
|
|
5953
|
-
});
|
|
5954
|
-
await dropUnreadLoopReplies(tree.conversationIds, stoppedIds, state);
|
|
5955
|
-
}
|
|
5956
|
-
/**
|
|
5957
|
-
* Drop the unread replies that Turns on the Conversation loop of the stopped
|
|
5958
|
-
* Conversations left in each mailbox of `mailboxIds`. Such a reply names
|
|
5959
|
-
* no work that the stop skips, so the stop drops it by its sender fields.
|
|
5960
|
-
* A reply sent after the stop is dropped when it is read, while the sender
|
|
5961
|
-
* is stopped. Call this after the stop is stored.
|
|
5962
|
-
*
|
|
5963
|
-
* A reply that a running Turn already took leaves the mailbox like one that
|
|
5964
|
-
* it read: the Turn's own ack removes nothing more.
|
|
5965
|
-
*/
|
|
5966
|
-
async function dropUnreadLoopReplies(mailboxIds, stoppedIds, state) {
|
|
5967
|
-
const stopped = new Set(stoppedIds);
|
|
5968
|
-
await mapBounded(mailboxIds, async (conversationId) => {
|
|
5969
|
-
const messages = (await getConversationWorkState({
|
|
5970
|
-
conversationId,
|
|
5971
|
-
state
|
|
5972
|
-
}))?.messages ?? [];
|
|
5973
|
-
const senders = await readChildMessageSenders(messages);
|
|
5974
|
-
const inboundMessageIds = messages.flatMap((message, index) => {
|
|
5975
|
-
const sender = senders[index];
|
|
5976
|
-
return sender && !ownAgentInvocation(sender) && stopped.has(sender.conversationId) ? [message.inboundMessageId] : [];
|
|
5977
|
-
});
|
|
5978
|
-
if (inboundMessageIds.length > 0) await dropPendingMessages({
|
|
5979
|
-
conversationId,
|
|
5980
|
-
inboundMessageIds,
|
|
5981
|
-
state
|
|
5982
|
-
});
|
|
5983
|
-
});
|
|
5984
|
-
}
|
|
5985
|
-
/**
|
|
5986
|
-
* Drop the unread loop replies that a Conversation that a person stopped
|
|
5987
|
-
* left in its parent's mailbox, outside its tree. Call this after its stop
|
|
5988
|
-
* is stored: the parent mailbox lock then drops a later reply.
|
|
5989
|
-
*/
|
|
5990
|
-
async function dropOwnUnreadLoopReplies(conversationId, state) {
|
|
5991
|
-
await dropUnreadLoopReplies((await getSqlExecutor().db().select({ id: juniorConversations.parentConversationId }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId))).flatMap((parent) => parent.id ? [parent.id] : []), [conversationId], state);
|
|
5992
|
-
}
|
|
5993
|
-
/**
|
|
5994
|
-
* A Thread can hold a person's Turn that waits for sign-in. The stop ends
|
|
5995
|
-
* that Turn here, because no worker holds it. Then a later sign-in callback
|
|
5996
|
-
* cannot resume a stopped Thread.
|
|
5997
|
-
*/
|
|
5998
|
-
async function finishStoppedTree(tree, conversationIdsToStop, options) {
|
|
5999
|
-
for (const invocation of tree.stopped) await recordSubagentEnded(invocation);
|
|
6000
|
-
await stopConversationTree(conversationIdsToStop, options);
|
|
6001
|
-
}
|
|
6002
|
-
/**
|
|
6003
|
-
* List one child Conversation and every Conversation below it, child first.
|
|
6004
|
-
* It takes the create lock of each Conversation before it reads that
|
|
6005
|
-
* Conversation's children, so no child agent can start in the tree until the
|
|
6006
|
-
* caller's transaction ends.
|
|
6007
|
-
*/
|
|
6008
|
-
async function lockAgentConversationTree(childConversationId) {
|
|
6009
|
-
const executor = getSqlExecutor();
|
|
6010
|
-
const conversationIds = [childConversationId];
|
|
6011
|
-
let parents = conversationIds;
|
|
6012
|
-
while (parents.length > 0) {
|
|
6013
|
-
for (const parent of parents) await executor.withLock(getChildAgentLockName(parent), async () => void 0);
|
|
6014
|
-
const rows = await executor.db().selectDistinct({ childConversationId: juniorAgentInvocations.childConversationId }).from(juniorAgentInvocations).where(inArray(juniorAgentInvocations.parentConversationId, parents));
|
|
6015
|
-
const withoutInvocations = await executor.db().select({ childConversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(inArray(juniorConversations.parentConversationId, parents), isNotNull(juniorConversations.agentConfig)));
|
|
6016
|
-
parents = [...new Set([...rows, ...withoutInvocations].map((row) => row.childConversationId))].filter((id) => !conversationIds.includes(id));
|
|
6017
|
-
conversationIds.push(...parents);
|
|
6018
|
-
}
|
|
6019
|
-
return conversationIds;
|
|
6020
|
-
}
|
|
6021
|
-
/**
|
|
6022
|
-
* Keep a Conversation, the child agents that it spawned or gave new work to
|
|
6023
|
-
* after `taskedAfterMs`, and every Conversation below those child agents.
|
|
6024
|
-
*/
|
|
6025
|
-
async function withChildAgentsTaskedAfter(conversationId, conversationIds, taskedAfterMs) {
|
|
6026
|
-
const links = await getSqlExecutor().db().selectDistinct({
|
|
6027
|
-
childConversationId: juniorAgentInvocations.childConversationId,
|
|
6028
|
-
parentConversationId: juniorAgentInvocations.parentConversationId
|
|
6029
|
-
}).from(juniorAgentInvocations).where(and(inArray(juniorAgentInvocations.parentConversationId, [...conversationIds]), or(ne(juniorAgentInvocations.parentConversationId, conversationId), gt(juniorAgentInvocations.createdAt, new Date(taskedAfterMs)))));
|
|
6030
|
-
const withoutInvocations = await getSqlExecutor().db().select({
|
|
6031
|
-
childConversationId: juniorConversations.conversationId,
|
|
6032
|
-
parentConversationId: juniorConversations.parentConversationId
|
|
6033
|
-
}).from(juniorConversations).where(and(inArray(juniorConversations.parentConversationId, [...conversationIds]), isNotNull(juniorConversations.agentConfig), or(ne(juniorConversations.parentConversationId, conversationId), gt(juniorConversations.createdAt, new Date(taskedAfterMs)))));
|
|
6034
|
-
const kept = [conversationId];
|
|
6035
|
-
for (let index = 0; index < kept.length; index += 1) for (const link of [...links, ...withoutInvocations]) if (link.parentConversationId === kept[index] && !kept.includes(link.childConversationId)) kept.push(link.childConversationId);
|
|
6036
|
-
return kept;
|
|
6037
|
-
}
|
|
6038
|
-
/**
|
|
6039
|
-
* Stop the agent invocations of one direct child agent and of every child
|
|
6040
|
-
* agent below it. Returns undefined when the child does not belong to the
|
|
6041
|
-
* parent.
|
|
6042
|
-
*/
|
|
6043
|
-
async function stopChildAgentInvocations(args) {
|
|
6044
|
-
const db = getSqlExecutor().db();
|
|
6045
|
-
const [owned, child] = await Promise.all([db.select({ invocationId: juniorAgentInvocations.invocationId }).from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.parentConversationId, args.parentConversationId), eq(juniorAgentInvocations.childConversationId, args.childConversationId))).limit(1), db.select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(eq(juniorConversations.conversationId, args.childConversationId), eq(juniorConversations.parentConversationId, args.parentConversationId), isNotNull(juniorConversations.agentConfig)))]);
|
|
6046
|
-
if (owned.length === 0 && child.length === 0) return;
|
|
6047
|
-
return await stopAgentInvocationTree(args.childConversationId, args.nowMs);
|
|
6048
|
-
}
|
|
6049
|
-
/**
|
|
6050
|
-
* Stop the agent invocations of one agent Conversation and of every child
|
|
6051
|
-
* agent below it. Open agent invocations become `stopped`. Results that would
|
|
6052
|
-
* still start or report work in the tree become `skipped`. With
|
|
6053
|
-
* `includeRoot: false`, the agent invocations of the Conversation itself stay
|
|
6054
|
-
* as they are, and only `pending` results sent to it become `skipped`. With
|
|
6055
|
-
* `taskedAfterMs`, only the direct child agents that got an agent invocation
|
|
6056
|
-
* after that time, and the Conversations below them, stop.
|
|
6057
|
-
*/
|
|
6058
|
-
async function stopAgentInvocationTree(conversationId, nowMs = Date.now(), options = { includeRoot: true }) {
|
|
6059
|
-
return await getSqlExecutor().withLock(getChildAgentLockName(conversationId), () => stopLockedAgentInvocationTree(conversationId, nowMs, options));
|
|
6060
|
-
}
|
|
6061
|
-
async function stopLockedAgentInvocationTree(conversationId, nowMs, options) {
|
|
6062
|
-
const db = getSqlExecutor().db();
|
|
6063
|
-
const now = new Date(nowMs);
|
|
6064
|
-
const lockedIds = await lockAgentConversationTree(conversationId);
|
|
6065
|
-
const conversationIds = options.taskedAfterMs === void 0 ? lockedIds : await withChildAgentsTaskedAfter(conversationId, lockedIds, options.taskedAfterMs);
|
|
6066
|
-
const stoppedChildIds = options.includeRoot ? conversationIds : conversationIds.filter((id) => id !== conversationId);
|
|
6067
|
-
const stopped = await db.update(juniorAgentInvocations).set({
|
|
6068
|
-
errorMessage: "Stopped by the parent conversation",
|
|
6069
|
-
parentMailboxStatus: "skipped",
|
|
6070
|
-
result: null,
|
|
6071
|
-
status: "stopped",
|
|
6072
|
-
terminalAt: now,
|
|
6073
|
-
updatedAt: now
|
|
6074
|
-
}).where(and(inArray(juniorAgentInvocations.childConversationId, stoppedChildIds), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES))).returning();
|
|
6075
|
-
await db.update(juniorAgentInvocations).set({
|
|
6076
|
-
parentMailboxStatus: "skipped",
|
|
6077
|
-
updatedAt: now
|
|
6078
|
-
}).where(or(and(inArray(juniorAgentInvocations.parentConversationId, stoppedChildIds), inArray(juniorAgentInvocations.parentMailboxStatus, ["pending", "appended"])), and(eq(juniorAgentInvocations.parentConversationId, conversationId), eq(juniorAgentInvocations.parentMailboxStatus, "pending")), and(inArray(juniorAgentInvocations.childConversationId, stoppedChildIds), eq(juniorAgentInvocations.parentMailboxStatus, "replaced"))));
|
|
6079
|
-
return {
|
|
6080
|
-
conversationIds,
|
|
6081
|
-
stopped: stopped.map(invocationFromRow).filter(isTerminalAgentInvocation)
|
|
6082
|
-
};
|
|
6083
|
-
}
|
|
6084
|
-
// src/chat/conversations/stop.ts
|
|
6085
|
-
/**
|
|
6086
|
-
* Stop a Conversation for a person, on every stop path. Every child agent
|
|
6087
|
-
* below it stops, then it and they are stopped Conversations until a person
|
|
6088
|
-
* sends input, and then its Turn stops. A Turn that waits for sign-in ends
|
|
6089
|
-
* too, so a later sign-in does not resume it. Their automated input is held.
|
|
6090
|
-
* Nothing above it changes: a stopped child agent's worker
|
|
6091
|
-
* reports the stop to its parent.
|
|
6092
|
-
*
|
|
6093
|
-
* A stop that comes from a message or a button press, such as the Slack
|
|
6094
|
-
* `stop` keyword or stop button, passes it. Its id is claimed in the mailbox
|
|
6095
|
-
* first, so a redelivery returns `duplicate` and stops nothing, not even
|
|
6096
|
-
* newer work. A stop that fails before its stop request is saved releases
|
|
6097
|
-
* its claim, so a redelivery can stop again. A failed claim check keeps a
|
|
6098
|
-
* claim that an earlier delivery saved. A failure after the stop request is
|
|
6099
|
-
* saved keeps the claim, as does a failed reply: the work is already
|
|
6100
|
-
* stopped, and a redelivery must not stop newer work. Its send time
|
|
6101
|
-
* is the stop time, and only person input sent at or before it is dropped.
|
|
6102
|
-
* So a retry writes the same stop and keeps input that the person sent after
|
|
6103
|
-
* it.
|
|
6104
|
-
*
|
|
6105
|
-
* The child agents and sessions stop first, so a failure leaves the Turn
|
|
6106
|
-
* running and the stop can be retried. A child agent can outlive the parent
|
|
6107
|
-
* Turn, so this runs even when no Turn runs.
|
|
6108
|
-
*/
|
|
6109
|
-
async function stopConversation(args) {
|
|
6110
|
-
if (args.message && (await claimInboundMessage({
|
|
6111
|
-
conversationStore: args.conversationStore,
|
|
6112
|
-
message: args.message,
|
|
6113
|
-
state: args.state
|
|
6114
|
-
})).status === "duplicate") return { status: "duplicate" };
|
|
6115
|
-
let stopSaved = false;
|
|
6116
|
-
try {
|
|
6117
|
-
const nowMs = Date.now();
|
|
6118
|
-
const stoppedAtMs = args.message?.createdAtMs ?? nowMs;
|
|
6119
|
-
const result = await stopConversationAndChildAgents({
|
|
6120
|
-
conversationId: args.conversationId,
|
|
6121
|
-
conversationStore: args.conversationStore,
|
|
6122
|
-
nowMs,
|
|
6123
|
-
onStopSaved: () => {
|
|
6124
|
-
stopSaved = true;
|
|
6125
|
-
},
|
|
6126
|
-
queue: args.queue,
|
|
6127
|
-
sentAtOrBeforeMs: args.message ? stoppedAtMs : void 0,
|
|
6128
|
-
state: args.state,
|
|
6129
|
-
stoppedAtMs
|
|
6130
|
-
});
|
|
6131
|
-
if (result.status === "requested") await ensureConversationWake({
|
|
6132
|
-
conversationId: args.conversationId,
|
|
6133
|
-
conversationStore: args.conversationStore,
|
|
6134
|
-
idempotencyKey: `conversation-stop:${args.conversationId}:${result.runId}`,
|
|
6135
|
-
nowMs,
|
|
6136
|
-
queue: args.queue,
|
|
6137
|
-
replaceExistingWake: true,
|
|
6138
|
-
state: args.state
|
|
6139
|
-
});
|
|
6140
|
-
return result;
|
|
6141
|
-
} catch (error) {
|
|
6142
|
-
if (args.message && !stopSaved) await releaseInboundMessage({
|
|
6143
|
-
message: args.message,
|
|
6144
|
-
state: args.state
|
|
6145
|
-
});
|
|
6146
|
-
throw error;
|
|
6147
|
-
}
|
|
6148
|
-
}
|
|
6149
|
-
/**
|
|
6150
|
-
* Stop a Conversation and every child agent below it, through
|
|
6151
|
-
* `stopConversationTree`. A person's stop and the automated-turn limit call
|
|
6152
|
-
* this. The child agents stop first, so a failure leaves the Conversation
|
|
6153
|
-
* running and the stop can be retried.
|
|
6154
|
-
*/
|
|
6155
|
-
async function stopConversationAndChildAgents(args) {
|
|
6156
|
-
const { conversationId, ...options } = args;
|
|
6157
|
-
await stopChildAgentsBelow(conversationId, {
|
|
6158
|
-
nowMs: options.nowMs,
|
|
6159
|
-
queue: options.queue,
|
|
6160
|
-
stoppedAtMs: options.stoppedAtMs,
|
|
6161
|
-
state: options.state
|
|
6162
|
-
});
|
|
6163
|
-
const [result] = await stopConversationTree([conversationId], options);
|
|
6164
|
-
if (!result) throw new Error("Stop returned no result");
|
|
6165
|
-
await dropOwnUnreadLoopReplies(conversationId, options.state);
|
|
6166
|
-
return result;
|
|
6167
|
-
}
|
|
6168
|
-
// src/chat/slack/annotation-ref.ts
|
|
6169
|
-
const KEY_DIGEST_LENGTH = 22;
|
|
6170
|
-
const legacyRefSchema = z.tuple([
|
|
6171
|
-
z.string().min(1),
|
|
6172
|
-
z.string().min(1),
|
|
6173
|
-
z.string().min(1)
|
|
6174
|
-
]);
|
|
6175
|
-
function decodeLegacyAnnotationRef(id) {
|
|
6176
|
-
try {
|
|
6177
|
-
return legacyRefSchema.safeParse(JSON.parse(Buffer.from(id, "base64url").toString("utf8"))).data;
|
|
6178
|
-
} catch {
|
|
6179
|
-
return;
|
|
6180
|
-
}
|
|
6181
|
-
}
|
|
6182
|
-
/** Return the fixed-size digest that identifies one annotation in a reference. */
|
|
6183
|
-
function annotationKeyDigest(plugin, key) {
|
|
6184
|
-
return createHash("sha256").update(JSON.stringify([plugin, key])).digest("base64url").slice(0, KEY_DIGEST_LENGTH);
|
|
6185
|
-
}
|
|
6186
|
-
/**
|
|
6187
|
-
* Build the Slack `external_ref.id` for an annotation, or null when the
|
|
6188
|
-
* Conversation ID is too long for Slack's limit.
|
|
6189
|
-
*/
|
|
6190
|
-
function encodeAnnotationRef(conversationId, plugin, key) {
|
|
6191
|
-
const id = annotationKeyDigest(plugin, key) + Buffer.from(conversationId, "utf8").toString("base64url");
|
|
6192
|
-
return slackExternalRefIdSchema.safeParse(id).success ? id : null;
|
|
6193
|
-
}
|
|
6194
|
-
/**
|
|
6195
|
-
* Split a current or legacy annotation `external_ref.id` into its
|
|
6196
|
-
* Conversation ID and key digest.
|
|
6197
|
-
*/
|
|
6198
|
-
function decodeAnnotationRef(id) {
|
|
6199
|
-
const legacy = decodeLegacyAnnotationRef(id);
|
|
6200
|
-
if (legacy) {
|
|
6201
|
-
const [conversationId, plugin, key] = legacy;
|
|
6202
|
-
return {
|
|
6203
|
-
conversationId,
|
|
6204
|
-
keyDigest: annotationKeyDigest(plugin, key)
|
|
6205
|
-
};
|
|
6206
|
-
}
|
|
6207
|
-
const keyDigest = id.slice(0, KEY_DIGEST_LENGTH);
|
|
6208
|
-
const encoded = id.slice(KEY_DIGEST_LENGTH);
|
|
6209
|
-
const conversationId = Buffer.from(encoded, "base64url").toString("utf8");
|
|
6210
|
-
if (!conversationId || Buffer.from(conversationId, "utf8").toString("base64url") !== encoded) return null;
|
|
6211
|
-
return {
|
|
6212
|
-
conversationId,
|
|
6213
|
-
keyDigest
|
|
6214
|
-
};
|
|
6215
|
-
}
|
|
6216
|
-
// src/chat/slack/automation-card.ts
|
|
6217
|
-
function preview(text, length) {
|
|
6218
|
-
const compact = text.replace(/\s+/g, " ").trim();
|
|
6219
|
-
return compact.length > length ? `${compact.slice(0, length - 1)}…` : compact;
|
|
6220
|
-
}
|
|
6221
|
-
/** Show an Automation as a native Work Object, not an operation receipt. */
|
|
6222
|
-
function renderSlackAutomationCard(card) {
|
|
6223
|
-
const title = preview(card.title, 160);
|
|
6224
|
-
const iconUrl = getDashboardObjectIconLink("workflow");
|
|
6225
|
-
const trigger = preview(card.trigger, 500);
|
|
6226
|
-
const warning = card.warning ? preview(card.warning, 500) : null;
|
|
6227
|
-
const text = [
|
|
6228
|
-
"Automation",
|
|
6229
|
-
card.url ? formatSlackLink(card.url, title) : escapeSlackMrkdwnText(title),
|
|
6230
|
-
escapeSlackMrkdwnText(trigger),
|
|
6231
|
-
warning ? escapeSlackMrkdwnText(warning) : null
|
|
6232
|
-
].filter(Boolean).join("\n");
|
|
6233
|
-
if (!card.url) return {
|
|
6234
|
-
entity: null,
|
|
6235
|
-
text
|
|
6236
|
-
};
|
|
6237
|
-
return {
|
|
6238
|
-
text,
|
|
6239
|
-
entity: {
|
|
6240
|
-
entity_type: "slack#/entities/item",
|
|
6241
|
-
external_ref: {
|
|
6242
|
-
id: card.id,
|
|
6243
|
-
type: "automation"
|
|
6244
|
-
},
|
|
6245
|
-
url: card.url,
|
|
6246
|
-
entity_payload: {
|
|
6247
|
-
attributes: {
|
|
6248
|
-
title: { text: title },
|
|
6249
|
-
display_type: "Automation",
|
|
6250
|
-
product_icon: iconUrl ? {
|
|
6251
|
-
url: iconUrl,
|
|
6252
|
-
alt_text: "Automation"
|
|
6253
|
-
} : void 0
|
|
6254
|
-
},
|
|
6255
|
-
custom_fields: [{
|
|
6256
|
-
key: "trigger",
|
|
6257
|
-
label: "When",
|
|
6258
|
-
type: "string",
|
|
6259
|
-
value: trigger,
|
|
6260
|
-
long: true
|
|
6261
|
-
}, ...warning ? [{
|
|
6262
|
-
key: "warning",
|
|
6263
|
-
label: "Needs attention",
|
|
6264
|
-
type: "string",
|
|
6265
|
-
value: warning,
|
|
6266
|
-
long: true
|
|
6267
|
-
}] : []]
|
|
6268
|
-
}
|
|
6269
|
-
}
|
|
6270
|
-
};
|
|
6271
|
-
}
|
|
6272
|
-
// src/chat/slack/object-card.ts
|
|
6273
|
-
function descriptionPreview(value) {
|
|
6274
|
-
const text = value?.replace(/\r\n/g, "\n").trim() ?? "";
|
|
6275
|
-
const preview = text.split("\n").slice(0, 6).join("\n").slice(0, 500);
|
|
6276
|
-
return preview.length < text.length ? `${preview.slice(0, 499).trimEnd()}…` : preview;
|
|
6277
|
-
}
|
|
6278
|
-
/** Render a compact Task or Item preview, or the saved facts for its detail panel. */
|
|
6279
|
-
function renderSlackObjectCard(card, conversationId, surface = "preview") {
|
|
6280
|
-
if (card.objectType === "automation" && card.plugin === "junior") return renderSlackAutomationCard({
|
|
6281
|
-
id: card.key,
|
|
6282
|
-
title: card.title,
|
|
6283
|
-
url: card.url,
|
|
6284
|
-
trigger: card.trigger ?? "",
|
|
6285
|
-
warning: card.warning ?? null
|
|
6286
|
-
});
|
|
6287
|
-
const presentation = objectPresentation(card);
|
|
6288
|
-
const type = card.displayType ?? presentation.label;
|
|
6289
|
-
const iconUrl = getDashboardObjectIconLink(presentation.icon);
|
|
6290
|
-
const title = card.title.slice(0, 160);
|
|
6291
|
-
const details = surface === "details";
|
|
6292
|
-
const deployment = card.objectType === "deployment" || card.objectType === "item" && card.facts?.type === "deployment";
|
|
6293
|
-
const calendarEvent = card.objectType === "calendar_event";
|
|
6294
|
-
const status = details || deployment || calendarEvent ? card.status : void 0;
|
|
6295
|
-
const warning = details || deployment ? card.warning : void 0;
|
|
6296
|
-
const facts = objectFactFields(card.facts).filter((field) => details || calendarEvent || deployment && field.key === "environment");
|
|
6297
|
-
const description = details ? card.description?.trim() ?? "" : calendarEvent ? "" : descriptionPreview(card.description);
|
|
6298
|
-
const text = [
|
|
6299
|
-
escapeSlackMrkdwnText(type),
|
|
6300
|
-
card.url ? formatSlackLink(card.url, title) : escapeSlackMrkdwnText(title),
|
|
6301
|
-
escapeSlackMrkdwnText(card.label),
|
|
6302
|
-
status ? escapeSlackMrkdwnText(status) : null,
|
|
6303
|
-
description ? escapeSlackMrkdwnText(description) : null,
|
|
6304
|
-
warning ? escapeSlackMrkdwnText(`Needs attention: ${warning}`) : null,
|
|
6305
|
-
...facts.map((field) => escapeSlackMrkdwnText(`${field.label}: ${field.value}`))
|
|
6306
|
-
].filter(Boolean).join("\n");
|
|
6307
|
-
const refId = encodeAnnotationRef(conversationId, card.plugin, card.key);
|
|
6308
|
-
if (!card.url || !refId) return {
|
|
6309
|
-
entity: null,
|
|
6310
|
-
text
|
|
6311
|
-
};
|
|
6312
|
-
const task = card.objectType === "task";
|
|
6313
|
-
const attributes = {
|
|
6314
|
-
title: { text: title },
|
|
6315
|
-
display_id: card.label,
|
|
6316
|
-
display_type: type,
|
|
6317
|
-
product_icon: iconUrl ? {
|
|
6318
|
-
url: iconUrl,
|
|
6319
|
-
alt_text: `${type}${status ? `: ${status}` : ""}`
|
|
6320
|
-
} : void 0,
|
|
6321
|
-
product_name: card.plugin
|
|
6322
|
-
};
|
|
6323
|
-
const customFields = [
|
|
6324
|
-
...description ? [{
|
|
6325
|
-
key: "description",
|
|
6326
|
-
label: "Description",
|
|
6327
|
-
type: "string",
|
|
6328
|
-
value: description,
|
|
6329
|
-
long: true,
|
|
6330
|
-
format: "markdown"
|
|
6331
|
-
}] : [],
|
|
6332
|
-
...facts.map((field) => ({
|
|
6333
|
-
...field,
|
|
6334
|
-
type: "string"
|
|
6335
|
-
})),
|
|
6336
|
-
...warning ? [{
|
|
6337
|
-
key: "warning",
|
|
6338
|
-
label: "Needs attention",
|
|
6339
|
-
type: "string",
|
|
6340
|
-
value: warning
|
|
6341
|
-
}] : []
|
|
6342
|
-
];
|
|
6343
|
-
return {
|
|
6344
|
-
text,
|
|
6345
|
-
entity: {
|
|
6346
|
-
...task ? {
|
|
6347
|
-
entity_type: "slack#/entities/task",
|
|
6348
|
-
entity_payload: {
|
|
6349
|
-
attributes,
|
|
6350
|
-
display_order: [...status ? ["status"] : [], ...customFields.map((field) => field.key)],
|
|
6351
|
-
fields: status ? { status: { value: status } } : void 0,
|
|
6352
|
-
custom_fields: customFields
|
|
6353
|
-
}
|
|
6354
|
-
} : {
|
|
6355
|
-
entity_type: "slack#/entities/item",
|
|
6356
|
-
entity_payload: {
|
|
6357
|
-
attributes,
|
|
6358
|
-
display_order: [...status ? ["status"] : [], ...customFields.map((field) => field.key)],
|
|
6359
|
-
custom_fields: [...status ? [{
|
|
6360
|
-
key: "status",
|
|
6361
|
-
label: "Status",
|
|
6362
|
-
type: "string",
|
|
6363
|
-
value: status
|
|
6364
|
-
}] : [], ...customFields]
|
|
6365
|
-
}
|
|
6366
|
-
},
|
|
6367
|
-
external_ref: {
|
|
6368
|
-
id: refId,
|
|
6369
|
-
type: "annotation"
|
|
6370
|
-
},
|
|
6371
|
-
url: card.url
|
|
6372
|
-
}
|
|
6373
|
-
};
|
|
6374
|
-
}
|
|
6375
|
-
// src/chat/slack/cards.ts
|
|
6376
|
-
/** Select the Slack object renderer for a built-in card. */
|
|
6377
|
-
function renderSlackCard(card, conversationId) {
|
|
6378
|
-
switch (card.kind) {
|
|
6379
|
-
case "object": return renderSlackObjectCard(card, conversationId);
|
|
6380
|
-
case "automation": return renderSlackAutomationCard(card);
|
|
6381
|
-
}
|
|
6382
|
-
}
|
|
6383
|
-
// src/chat/slack/footer.ts
|
|
6384
|
-
/** Render compact reply attribution for the Slack footer. */
|
|
6385
|
-
function formatReplyAttribution(attribution) {
|
|
6386
|
-
return attribution.detail ? `${attribution.label} · ${attribution.detail}` : attribution.label;
|
|
6387
|
-
}
|
|
6388
|
-
/**
|
|
6389
|
-
* Build the compact conversation footer for visible Slack reply surfaces.
|
|
6390
|
-
*
|
|
6391
|
-
* Detailed turn metrics stay in the dashboard instead of Slack-visible copy.
|
|
6392
|
-
*/
|
|
6393
|
-
function buildSlackReplyFooter(args) {
|
|
6394
|
-
const items = [];
|
|
6395
|
-
const conversationId = args.conversationId?.trim();
|
|
6396
|
-
if (conversationId) {
|
|
6397
|
-
const idItem = {
|
|
6398
|
-
label: "ID",
|
|
6399
|
-
value: conversationId
|
|
6400
|
-
};
|
|
6401
|
-
const conversationUrl = getPluginSlackConversationLink(conversationId)?.url ?? getDashboardConversationLink(conversationId) ?? buildSentryConversationUrl(conversationId);
|
|
6402
|
-
if (conversationUrl) idItem.url = conversationUrl;
|
|
6403
|
-
items.push(idItem);
|
|
6404
|
-
}
|
|
6405
|
-
return items.length > 0 || args.replyAttribution ? {
|
|
6406
|
-
...args.replyAttribution ? { attribution: args.replyAttribution } : void 0,
|
|
6407
|
-
items
|
|
6408
|
-
} : void 0;
|
|
6409
|
-
}
|
|
6410
|
-
/** Build Slack blocks for a reply chunk using the Slack-flavored markdown block for the body. */
|
|
6411
|
-
function buildSlackReplyBlocks(text, footer) {
|
|
6412
|
-
const blocks = text.trim() ? [{
|
|
6413
|
-
type: "markdown",
|
|
6414
|
-
text
|
|
6415
|
-
}] : [];
|
|
6416
|
-
if (footer && (footer.attribution || footer.items.length > 0)) {
|
|
6417
|
-
const attributionElements = footer.attribution ? [{
|
|
6418
|
-
type: "plain_text",
|
|
6419
|
-
text: formatReplyAttribution(footer.attribution)
|
|
6420
|
-
}] : [];
|
|
6421
|
-
blocks.push({
|
|
6422
|
-
type: "context",
|
|
6423
|
-
elements: [...attributionElements, ...footer.items.map((item) => ({
|
|
6424
|
-
type: "mrkdwn",
|
|
6425
|
-
text: item.url ? `*${escapeSlackMrkdwnText(item.label)}:* ${formatSlackLink(item.url, item.value)}` : `*${escapeSlackMrkdwnText(item.label)}:* ${escapeSlackMrkdwnText(item.value)}`
|
|
6426
|
-
}))]
|
|
6427
|
-
});
|
|
6428
|
-
}
|
|
6429
|
-
return blocks.length ? blocks : void 0;
|
|
6430
|
-
}
|
|
6431
|
-
// src/chat/slack/output.ts
|
|
6432
|
-
const MAX_INLINE_CHARS = 4e3;
|
|
6433
|
-
function getFenceContinuation(text) {
|
|
6434
|
-
let open;
|
|
6435
|
-
for (const line of text.split("\n")) {
|
|
6436
|
-
const trimmed = line.trimStart();
|
|
6437
|
-
const openerMatch = trimmed.match(/^(`{3,}|~{3,})(.*)$/);
|
|
6438
|
-
if (!openerMatch?.[1]) continue;
|
|
6439
|
-
if (!open) {
|
|
6440
|
-
open = {
|
|
6441
|
-
fence: openerMatch[1],
|
|
6442
|
-
openerLine: trimmed
|
|
6443
|
-
};
|
|
6444
|
-
continue;
|
|
6445
|
-
}
|
|
6446
|
-
if (new RegExp(`^${open.fence}\\s*$`).test(trimmed)) open = void 0;
|
|
6447
|
-
}
|
|
6448
|
-
if (!open) return null;
|
|
6449
|
-
return {
|
|
6450
|
-
closeSuffix: text.endsWith("\n") ? open.fence : `\n${open.fence}`,
|
|
6451
|
-
reopenPrefix: `${open.openerLine}\n`
|
|
6452
|
-
};
|
|
6453
|
-
}
|
|
6454
|
-
function findSplitIndex(text, maxChars) {
|
|
6455
|
-
const bounded = text.slice(0, maxChars);
|
|
6456
|
-
const newlineIndex = bounded.lastIndexOf("\n");
|
|
6457
|
-
if (newlineIndex > 0) return newlineIndex;
|
|
6458
|
-
const spaceIndex = bounded.lastIndexOf(" ");
|
|
6459
|
-
if (spaceIndex > 0) return spaceIndex;
|
|
6460
|
-
return maxChars;
|
|
6461
|
-
}
|
|
6462
|
-
function takePrefix(text, maxChars) {
|
|
6463
|
-
const prefix = text.slice(0, findSplitIndex(text, maxChars)).trimEnd() || text.slice(0, maxChars);
|
|
6464
|
-
return {
|
|
6465
|
-
prefix,
|
|
6466
|
-
rest: text.slice(prefix.length).trimStart()
|
|
6467
|
-
};
|
|
6468
|
-
}
|
|
6469
|
-
/**
|
|
6470
|
-
* Keep a pipe table readable when a split lands inside it. Each post renders
|
|
6471
|
-
* on its own, so rows without the header and delimiter rows show as text.
|
|
6472
|
-
* Move a table that starts mid-post to the next post. Repeat the header rows
|
|
6473
|
-
* when one table is longer than a post.
|
|
6474
|
-
*/
|
|
6475
|
-
function splitOutsideTable(text, prefix, rest) {
|
|
6476
|
-
const lines = prefix.split("\n");
|
|
6477
|
-
const gap = text.slice(prefix.length, text.length - rest.length);
|
|
6478
|
-
if (!isTableRow(lines.at(-1) ?? "") || !isTableRow(rest) || /\n\s*\n/.test(gap)) return {
|
|
6479
|
-
chunk: prefix,
|
|
6480
|
-
rest
|
|
6481
|
-
};
|
|
6482
|
-
let start = lines.length - 1;
|
|
6483
|
-
while (start > 0 && isTableRow(lines[start - 1] ?? "")) start--;
|
|
6484
|
-
const before = lines.slice(0, start).join("\n").trimEnd();
|
|
6485
|
-
const table = lines.slice(start);
|
|
6486
|
-
if (before) return {
|
|
6487
|
-
chunk: before,
|
|
6488
|
-
rest: `${table.join("\n")}\n${rest}`
|
|
6489
|
-
};
|
|
6490
|
-
if (table.length <= 2) return {
|
|
6491
|
-
chunk: prefix,
|
|
6492
|
-
rest
|
|
6493
|
-
};
|
|
6494
|
-
return {
|
|
6495
|
-
chunk: prefix,
|
|
6496
|
-
rest: `${table.slice(0, 2).join("\n")}\n${rest}`
|
|
6497
|
-
};
|
|
6498
|
-
}
|
|
6499
|
-
/** Take one post that fits the budget, closing a code fence it leaves open. */
|
|
6500
|
-
function takeChunk(text) {
|
|
6501
|
-
let { prefix, rest } = takePrefix(text, MAX_INLINE_CHARS);
|
|
6502
|
-
let carryover = getFenceContinuation(prefix);
|
|
6503
|
-
if (!carryover) return splitOutsideTable(text, prefix, rest);
|
|
6504
|
-
({prefix, rest} = takePrefix(text, MAX_INLINE_CHARS - carryover.closeSuffix.length));
|
|
6505
|
-
carryover = getFenceContinuation(prefix);
|
|
6506
|
-
if (!carryover || !rest) return {
|
|
6507
|
-
chunk: prefix,
|
|
6508
|
-
rest
|
|
6509
|
-
};
|
|
6510
|
-
return {
|
|
6511
|
-
chunk: `${prefix}${carryover.closeSuffix}`,
|
|
6512
|
-
rest: `${carryover.reopenPrefix}${rest}`
|
|
6513
|
-
};
|
|
6514
|
-
}
|
|
6515
|
-
/** Split a normalized Slack reply into thread posts that fit Slack limits. */
|
|
6516
|
-
function splitSlackReplyText(text, format) {
|
|
6517
|
-
const chunks = [];
|
|
6518
|
-
let remaining = normalizeSlackReplyMarkdown(text, format);
|
|
6519
|
-
while (remaining.length > MAX_INLINE_CHARS) {
|
|
6520
|
-
const { chunk, rest } = takeChunk(remaining);
|
|
6521
|
-
chunks.push(chunk);
|
|
6522
|
-
remaining = rest;
|
|
6523
|
-
}
|
|
6524
|
-
if (remaining) chunks.push(remaining);
|
|
6525
|
-
return chunks;
|
|
6526
|
-
}
|
|
6527
|
-
// src/chat/slack/reply.ts
|
|
6528
|
-
/**
|
|
6529
|
-
* Resolve where a Turn posts in Slack.
|
|
6530
|
-
*
|
|
6531
|
-
* The channel is always the Destination channel. The thread comes from the
|
|
6532
|
-
* Turn Source, then the Conversation Location, then the Destination, and each
|
|
6533
|
-
* one counts only when it names that channel. Do not derive the target from
|
|
6534
|
-
* the Conversation id: an Automation or Watch Conversation can own a Slack
|
|
6535
|
-
* thread, and its id is not a Slack thread id.
|
|
6536
|
-
*/
|
|
6537
|
-
function resolveSlackReplyTarget(args) {
|
|
6538
|
-
const { channelId } = args.destination;
|
|
6539
|
-
const sourceThreadTs = args.source?.kind === "slack" && args.source.channelId === channelId ? args.source.threadTs : void 0;
|
|
6540
|
-
const locationThreadTs = args.location?.provider === "slack" && args.location.channelId === channelId ? args.location.threadTs : void 0;
|
|
6541
|
-
const threadTs = sourceThreadTs ?? locationThreadTs ?? args.destination.threadTs;
|
|
6542
|
-
return {
|
|
6543
|
-
channelId,
|
|
6544
|
-
...threadTs ? { threadTs } : void 0
|
|
6545
|
-
};
|
|
6546
|
-
}
|
|
6547
|
-
/** Resolve known people for plugin formatting. Fails open, like the hooks. */
|
|
6548
|
-
async function resolveReplyMentions(text, teamId) {
|
|
6549
|
-
try {
|
|
6550
|
-
return await resolveHandleMentions(text, teamId);
|
|
6551
|
-
} catch (error) {
|
|
6552
|
-
logWarn("slack.reply.mentions.failed", { "exception.message": error instanceof Error ? error.message : String(error) });
|
|
6553
|
-
return;
|
|
6554
|
-
}
|
|
6555
|
-
}
|
|
6556
|
-
/**
|
|
6557
|
-
* Send one destination-visible Slack reply.
|
|
6558
|
-
*
|
|
6559
|
-
* Chunks oversized text, builds compact attribution and conversation footer
|
|
6560
|
-
* context, and posts through the shared Slack outbound boundary. Pass
|
|
6561
|
-
* `formatting` for agent replies so plugin formatting can use Location
|
|
6562
|
-
* defaults, such as a default repository, and mention known people.
|
|
6563
|
-
*/
|
|
6564
|
-
async function sendSlackReply(args) {
|
|
6565
|
-
const format = args.formatting && {
|
|
6566
|
-
configuration: args.formatting.configuration,
|
|
6567
|
-
mentions: await resolveReplyMentions(args.text, args.formatting.teamId)
|
|
6568
|
-
};
|
|
6569
|
-
const posts = splitSlackReplyText(args.text, format).map((text) => ({
|
|
6570
|
-
text,
|
|
6571
|
-
cards: []
|
|
6572
|
-
}));
|
|
6573
|
-
const groups = [];
|
|
6574
|
-
for (const card of args.cards ?? []) {
|
|
6575
|
-
const rendered = renderSlackCard(card, args.conversationId);
|
|
6576
|
-
const slackCard = rendered.entity && !fitsSlackMetadataLimit([rendered.entity]) ? {
|
|
6577
|
-
entity: null,
|
|
6578
|
-
text: rendered.text
|
|
6579
|
-
} : rendered;
|
|
6580
|
-
const group = groups.at(-1);
|
|
6581
|
-
const entities = [...group ?? [], slackCard].flatMap((item) => item.entity ? [item.entity] : []);
|
|
6582
|
-
if (group && group.length < 5 && fitsSlackMetadataLimit(entities)) group.push(slackCard);
|
|
6583
|
-
else groups.push([slackCard]);
|
|
6584
|
-
}
|
|
6585
|
-
for (const [index, group] of groups.entries()) {
|
|
6586
|
-
const lastPost = posts.at(-1);
|
|
6587
|
-
if (index === 0 && lastPost) lastPost.cards = group;
|
|
6588
|
-
else posts.push({
|
|
6589
|
-
text: "",
|
|
6590
|
-
cards: group
|
|
6591
|
-
});
|
|
6592
|
-
}
|
|
6593
|
-
const footer = buildSlackReplyFooter({
|
|
6594
|
-
conversationId: args.conversationId,
|
|
6595
|
-
replyAttribution: args.replyAttribution
|
|
6596
|
-
});
|
|
6597
|
-
const messageTs = [];
|
|
6598
|
-
let threadTs = args.threadTs;
|
|
6599
|
-
for (const [index, post] of posts.entries()) {
|
|
6600
|
-
const { text, cards } = post;
|
|
6601
|
-
const isFinalChunk = index === posts.length - 1;
|
|
6602
|
-
const blocks = buildSlackReplyBlocks(text, void 0) ?? [];
|
|
6603
|
-
for (const card of cards) if (!card.entity) blocks.push({
|
|
6604
|
-
type: "section",
|
|
6605
|
-
text: {
|
|
6606
|
-
type: "mrkdwn",
|
|
6607
|
-
text: card.text
|
|
6608
|
-
}
|
|
6609
|
-
});
|
|
6610
|
-
if (isFinalChunk || !text.trim()) blocks.push(...buildSlackReplyBlocks("", footer) ?? []);
|
|
6611
|
-
const entities = cards.flatMap((card) => card.entity ? [card.entity] : []);
|
|
6612
|
-
const accessibleText = [text, ...cards.map((card) => card.text)].filter(Boolean).join("\n\n");
|
|
6613
|
-
const fallbackText = isFinalChunk && args.replyAttribution ? `${accessibleText}\n\n${escapeSlackMrkdwnText(formatReplyAttribution(args.replyAttribution))}` : accessibleText;
|
|
6614
|
-
const response = await postSlackMessage({
|
|
6615
|
-
channelId: args.channelId,
|
|
6616
|
-
threadTs,
|
|
6617
|
-
text: fallbackText,
|
|
6618
|
-
...blocks.length ? { blocks } : void 0,
|
|
6619
|
-
...entities.length ? { entities } : void 0
|
|
6620
|
-
});
|
|
6621
|
-
if (response.ts) {
|
|
6622
|
-
messageTs.push(response.ts);
|
|
6623
|
-
threadTs ??= response.ts;
|
|
6624
|
-
}
|
|
6625
|
-
}
|
|
6626
|
-
return messageTs;
|
|
6627
|
-
}
|
|
6628
|
-
// src/chat/slack/automated-turn-limit-notice.ts
|
|
6629
|
-
/**
|
|
6630
|
-
* Stop and notice for the consecutive automated-turn limit.
|
|
6631
|
-
*
|
|
6632
|
-
* The notice is best-effort: a failed post must not fail the Turn or undo the
|
|
6633
|
-
* stop.
|
|
6634
|
-
*/
|
|
6635
|
-
/**
|
|
6636
|
-
* Post the stop notice to the Conversation Location when known. A child
|
|
6637
|
-
* agent posts none: its parent sees it as stopped in `listAgents`.
|
|
6638
|
-
*/
|
|
6639
|
-
async function postAutomatedTurnLimitNotice(args) {
|
|
6640
|
-
try {
|
|
6641
|
-
const conversation = await getConversationStore().get({ conversationId: args.conversationId });
|
|
6642
|
-
const location = conversation?.parentConversationId ? void 0 : conversation?.location;
|
|
6643
|
-
if (!location || location.provider !== "slack" || conversation?.deliveryPausedAtMs !== void 0) {
|
|
6644
|
-
logWarn("automated_turn_limit.notice.skipped", {
|
|
6645
|
-
conversationId: args.conversationId,
|
|
6646
|
-
"app.automated_turn_limit.reason": !location ? "missing_location" : location.provider !== "slack" ? "unsupported_location" : "delivery_paused"
|
|
6647
|
-
});
|
|
6648
|
-
return;
|
|
6649
|
-
}
|
|
6650
|
-
await sendSlackReply({
|
|
6651
|
-
...resolveSlackReplyTarget({
|
|
6652
|
-
destination: location,
|
|
6653
|
-
location,
|
|
6654
|
-
source: args.source
|
|
6655
|
-
}),
|
|
6656
|
-
conversationId: args.conversationId,
|
|
6657
|
-
text: buildAutomatedTurnLimitResponse({ maxTurns: args.maxTurns })
|
|
6658
|
-
});
|
|
6659
|
-
} catch (error) {
|
|
6660
|
-
logException(error, "automated_turn_limit.notice.failed", { conversationId: args.conversationId });
|
|
6661
|
-
}
|
|
6662
|
-
}
|
|
6663
|
-
/**
|
|
6664
|
-
* Stop the Conversation tree after a finished Turn reaches the automated-turn
|
|
6665
|
-
* limit, then post the notice. Person input that already waits ends the loop
|
|
6666
|
-
* by itself, so then nothing stops.
|
|
6667
|
-
*/
|
|
6668
|
-
async function stopAtAutomatedTurnLimit(args) {
|
|
6669
|
-
if (!args.update?.reached) return;
|
|
6670
|
-
if (((await getConversationWorkState({ conversationId: args.conversationId }))?.messages ?? []).some((message) => isPersonInput(message.source))) return;
|
|
6671
|
-
const nowMs = Date.now();
|
|
6672
|
-
await stopConversationAndChildAgents({
|
|
6673
|
-
conversationId: args.conversationId,
|
|
6674
|
-
finishedRunOf: args.conversationId,
|
|
6675
|
-
nowMs,
|
|
6676
|
-
stoppedAtMs: nowMs
|
|
6677
|
-
});
|
|
6678
|
-
await postAutomatedTurnLimitNotice({
|
|
6679
|
-
conversationId: args.conversationId,
|
|
6680
|
-
maxTurns: args.maxTurns,
|
|
6681
|
-
source: args.source
|
|
6682
|
-
});
|
|
6683
|
-
}
|
|
6684
|
-
// src/chat/task-execution/authorized-turn.ts
|
|
6685
|
-
/**
|
|
6686
|
-
* OAuth callbacks save readiness, not agent history. The conversation worker
|
|
6687
|
-
* consumes this event under its lease before it resumes the paused Turn.
|
|
6688
|
-
*/
|
|
6689
|
-
const authorizationSchema = z.object({
|
|
6690
|
-
kind: z.enum(["mcp", "plugin"]),
|
|
6691
|
-
provider: z.string().min(1),
|
|
6692
|
-
actorId: z.string().min(1),
|
|
6693
|
-
authorizationId: z.string().min(1),
|
|
6694
|
-
authSessionId: z.string().optional(),
|
|
6695
|
-
scope: z.string().optional(),
|
|
6696
|
-
configuration: z.record(z.string(), z.unknown()).optional(),
|
|
6697
|
-
toolChannelId: z.string().optional()
|
|
6698
|
-
});
|
|
6699
|
-
function authorizationKey(turn) {
|
|
6700
|
-
return `turn:${turn.turnId}:authorization:${turn.version}`;
|
|
6701
|
-
}
|
|
6702
|
-
/** Save authorization for this parked boundary without changing model history. */
|
|
6703
|
-
async function recordTurnAuthorization(args) {
|
|
6704
|
-
const turn = await getTurnRecord(args.conversationId, args.turnId);
|
|
6705
|
-
if (!turn || turn.state !== "paused" || turn.resumeReason !== "auth") return;
|
|
6706
|
-
await getConversationEventStore().append(args.conversationId, [{
|
|
6707
|
-
idempotencyKey: authorizationKey(turn),
|
|
6708
|
-
createdAtMs: Date.now(),
|
|
6709
|
-
data: {
|
|
6710
|
-
type: "structured_event",
|
|
6711
|
-
namespace: "junior",
|
|
6712
|
-
name: "turn_authorized",
|
|
6713
|
-
version: 1,
|
|
6714
|
-
turnId: turn.turnId,
|
|
6715
|
-
content: authorizationSchema.parse(args)
|
|
6716
|
-
}
|
|
6717
|
-
}], { activity: "preserve" });
|
|
6718
|
-
return {
|
|
6719
|
-
conversationId: args.conversationId,
|
|
6720
|
-
destination: args.destination,
|
|
6721
|
-
turnId: turn.turnId,
|
|
6722
|
-
expectedVersion: turn.version
|
|
6723
|
-
};
|
|
6724
|
-
}
|
|
6725
|
-
/** Read authorization for the exact pause; a later auth pause needs its own callback. */
|
|
6726
|
-
async function getTurnAuthorization(turn) {
|
|
6727
|
-
const event = await getConversationEventStore().loadByIdempotencyKey(turn.conversationId, authorizationKey(turn));
|
|
6728
|
-
if (event?.data.type !== "structured_event") return void 0;
|
|
6729
|
-
return authorizationSchema.parse(event.data.content);
|
|
6730
|
-
}
|
|
6731
|
-
// src/chat/task-execution/turn-wake.ts
|
|
6732
|
-
/** Build the worker input for a paused turn. */
|
|
6733
|
-
async function getPausedTurnRequest(args) {
|
|
6734
|
-
const turn = (await loadTurnCheckpoint({
|
|
6735
|
-
conversationId: args.conversationId,
|
|
6736
|
-
turnId: args.turnId
|
|
6737
|
-
})).record;
|
|
6738
|
-
if (!turn || turn.state !== "paused" || turn.resumeReason !== "timeout" && turn.resumeReason !== "yield" && turn.resumeReason !== "retry" && !(turn.resumeReason === "auth" && await getTurnAuthorization(turn)) || turn.resumeReason === "timeout" && turn.sliceId < 2) return;
|
|
6739
|
-
let routing;
|
|
6740
|
-
try {
|
|
6741
|
-
routing = await resolveTurnResumeRouting({
|
|
6742
|
-
conversationId: args.conversationId,
|
|
6743
|
-
conversationStore: args.conversationStore,
|
|
6744
|
-
dispatchId: turn.dispatchId
|
|
6745
|
-
});
|
|
6746
|
-
} catch (error) {
|
|
6747
|
-
const failed = await failTurnRecord({
|
|
6748
|
-
conversationId: args.conversationId,
|
|
6749
|
-
expectedVersion: turn.version,
|
|
6750
|
-
turnId: args.turnId,
|
|
6751
|
-
errorMessage: error instanceof Error ? error.message : String(error)
|
|
6752
|
-
});
|
|
6753
|
-
if (failed) await recordFailedDispatchTurn(failed);
|
|
6754
|
-
return;
|
|
6755
|
-
}
|
|
6756
|
-
return {
|
|
6757
|
-
conversationId: args.conversationId,
|
|
6758
|
-
destination: routing.destination,
|
|
6759
|
-
turnId: args.turnId,
|
|
6760
|
-
expectedVersion: turn.version,
|
|
6761
|
-
traceContext: turn.traceContext
|
|
6762
|
-
};
|
|
6763
|
-
}
|
|
6764
|
-
/**
|
|
6765
|
-
* Record that a resume failed a dispatch turn for good. Without this outcome,
|
|
6766
|
-
* the dispatch runs the turn again, so a failed write is only logged.
|
|
6767
|
-
*/
|
|
6768
|
-
async function recordFailedDispatchTurn(turn) {
|
|
6769
|
-
if (!turn.dispatchId) return;
|
|
6770
|
-
try {
|
|
6771
|
-
const dispatch = await getDispatchRecord(turn.dispatchId);
|
|
6772
|
-
await recordTurnSummary({
|
|
6773
|
-
conversationId: turn.conversationId,
|
|
6774
|
-
destination: dispatch?.destination,
|
|
6775
|
-
dispatchId: turn.dispatchId,
|
|
6776
|
-
dispatchOutcome: "failed",
|
|
6777
|
-
turnId: turn.turnId,
|
|
6778
|
-
sliceId: turn.sliceId,
|
|
6779
|
-
source: dispatch?.source,
|
|
6780
|
-
state: "failed",
|
|
6781
|
-
surface: turn.surface
|
|
6782
|
-
});
|
|
6783
|
-
} catch (error) {
|
|
6784
|
-
logException(error, "agent.continue.dispatch_failure_summary.failed", {
|
|
6785
|
-
"app.ai.conversation_id": turn.conversationId,
|
|
6786
|
-
"app.ai.session_id": turn.turnId
|
|
6787
|
-
});
|
|
6788
|
-
}
|
|
6789
|
-
}
|
|
6790
|
-
/** Wake the conversation worker for a paused turn. */
|
|
6791
|
-
async function wakePausedTurn(request, options = {}) {
|
|
6792
|
-
const nowMs = options.nowMs ?? Date.now();
|
|
6793
|
-
const conversation = await (options.conversationStore ?? getConversationStore()).get({ conversationId: request.conversationId });
|
|
6794
|
-
await requestConversationWork({
|
|
6795
|
-
conversationId: request.conversationId,
|
|
6796
|
-
destination: conversation && !isTopLevelKind(conversation.kind) ? void 0 : request.destination,
|
|
6797
|
-
nowMs,
|
|
6798
|
-
state: options.state
|
|
6799
|
-
});
|
|
6800
|
-
const queue = options.queue ?? getVercelConversationWorkQueue();
|
|
6801
|
-
await ensureConversationWake({
|
|
6802
|
-
conversationId: request.conversationId,
|
|
6803
|
-
idempotencyKey: [
|
|
6804
|
-
"agent-continue",
|
|
6805
|
-
request.conversationId,
|
|
6806
|
-
request.turnId,
|
|
6807
|
-
request.expectedVersion,
|
|
6808
|
-
nowMs
|
|
6809
|
-
].join(":"),
|
|
6810
|
-
nowMs,
|
|
6811
|
-
queue,
|
|
6812
|
-
state: options.state
|
|
6813
|
-
});
|
|
6814
|
-
}
|
|
6815
|
-
/** Create paused Turn operations for one app. */
|
|
6816
|
-
function createPausedTurns(options = {}) {
|
|
6817
|
-
return {
|
|
6818
|
-
get: (args) => getPausedTurnRequest({
|
|
6819
|
-
...args,
|
|
6820
|
-
conversationStore: options.conversationStore
|
|
6821
|
-
}),
|
|
6822
|
-
wake: (request) => wakePausedTurn(request, options)
|
|
6823
|
-
};
|
|
6824
|
-
}
|
|
6825
|
-
/** Record completed authorization and wake the sole execution owner. */
|
|
6826
|
-
async function wakeAuthorizedTurn(args, queue) {
|
|
6827
|
-
const request = await recordTurnAuthorization(args);
|
|
6828
|
-
if (request) await wakePausedTurn(request, { queue });
|
|
6829
|
-
}
|
|
6830
|
-
// src/chat/task-execution/supersede-turns.ts
|
|
6831
|
-
/**
|
|
6832
|
-
* End every open mailbox Turn other than `keepTurnId`, so new input runs in
|
|
6833
|
-
* the only open Turn. New input starts only when no yielded Turn waits, so an
|
|
6834
|
-
* open Turn here waits for OAuth or was left open by a failed or stopped Run.
|
|
6835
|
-
* The caller persists `conversation`. Returns false when `isStopped` turns
|
|
6836
|
-
* true first.
|
|
6837
|
-
*/
|
|
6838
|
-
async function supersedeOpenMailboxTurns(args) {
|
|
6839
|
-
return await supersedeTurns({
|
|
6840
|
-
...args,
|
|
6841
|
-
turns: (await listActiveMailboxTurns(args.conversationId)).filter((record) => record.turnId !== args.keepTurnId)
|
|
6842
|
-
});
|
|
6843
|
-
}
|
|
6844
|
-
/**
|
|
6845
|
-
* End open Turns that new input replaces. A late resume or OAuth callback
|
|
6846
|
-
* for an ended Turn is a no-op. The caller persists `conversation`. Returns
|
|
6847
|
-
* false when `isStopped` turns true first.
|
|
6848
|
-
*/
|
|
6849
|
-
async function supersedeTurns(args) {
|
|
6850
|
-
const pendingAuthorizationActorId = args.conversation.processing.pendingAuth?.actorId;
|
|
6851
|
-
for (const stale of args.turns) {
|
|
6852
|
-
if (args.isStopped?.()) return false;
|
|
6853
|
-
await abandonTurnRecord({
|
|
6854
|
-
conversationId: args.conversationId,
|
|
6855
|
-
turnId: stale.turnId,
|
|
6856
|
-
errorMessage: "Turn superseded by new input"
|
|
6857
|
-
});
|
|
6858
|
-
await getTurnLifecycle().complete({
|
|
6859
|
-
conversationId: args.conversationId,
|
|
6860
|
-
createdAtMs: Date.now(),
|
|
6861
|
-
outcome: "cancelled",
|
|
6862
|
-
turnId: stale.turnId
|
|
6863
|
-
});
|
|
6864
|
-
markTurnClosed({
|
|
6865
|
-
conversation: args.conversation,
|
|
6866
|
-
nowMs: Date.now(),
|
|
6867
|
-
sessionId: stale.turnId
|
|
6868
|
-
});
|
|
6869
|
-
}
|
|
6870
|
-
if (args.turns.some((record) => record.state === "paused" && record.resumeReason === "auth") && pendingAuthorizationActorId) await deleteWebAuthorization({
|
|
6871
|
-
actorId: pendingAuthorizationActorId,
|
|
6872
|
-
conversationId: args.conversationId
|
|
6873
|
-
});
|
|
6874
|
-
return true;
|
|
6875
|
-
}
|
|
6876
|
-
/**
|
|
6877
|
-
* End the Turn that waits for its next Run when `message` cannot join it, so
|
|
6878
|
-
* the message starts its own Turn instead of running with that Turn's Actor.
|
|
6879
|
-
* A stored legacy Turn without an Actor keeps taking the input.
|
|
6880
|
-
*/
|
|
6881
|
-
async function supersedeTurnForInput(args) {
|
|
6882
|
-
const conversation = coerceThreadConversationState(await getPersistedThreadState(args.conversationId));
|
|
6883
|
-
const turnId = conversation.processing.activeTurnId;
|
|
6884
|
-
if (!turnId || !await getPausedTurnRequest({
|
|
6885
|
-
conversationId: args.conversationId,
|
|
6886
|
-
turnId
|
|
6887
|
-
})) return;
|
|
6888
|
-
const turn = await getTurnRecord(args.conversationId, turnId);
|
|
6889
|
-
if (!turn?.actor || canJoinTurn(turn, args.message)) return;
|
|
6890
|
-
await hydrateConversationMessages({
|
|
6891
|
-
conversation,
|
|
6892
|
-
conversationId: args.conversationId
|
|
6893
|
-
});
|
|
6894
|
-
await supersedeTurns({
|
|
6895
|
-
conversation,
|
|
6896
|
-
conversationId: args.conversationId,
|
|
6897
|
-
turns: [turn]
|
|
6898
|
-
});
|
|
6899
|
-
await persistThreadStateById(args.conversationId, { conversation });
|
|
6900
|
-
}
|
|
6901
|
-
// src/chat/agent-invocations/thread-turn.ts
|
|
6902
|
-
/**
|
|
6903
|
-
* A person's Turn in a Thread runs on the Conversation loop. A
|
|
6904
|
-
* person's Turn and an Agent invocation Turn are never open at the same time.
|
|
6905
|
-
*/
|
|
6906
|
-
/**
|
|
6907
|
-
* End a person's open Turn in a Thread before an agent invocation starts, as
|
|
6908
|
-
* new input does on a root. Only a Turn that waits for sign-in or lost its
|
|
6909
|
-
* worker can be open here: a yielded Turn resumes before new input.
|
|
6910
|
-
*/
|
|
6911
|
-
async function supersedeOpenMailboxTurn(conversationId) {
|
|
6912
|
-
if ((await listActiveMailboxTurns(conversationId)).length === 0) return;
|
|
6913
|
-
const conversation = coerceThreadConversationState(await getPersistedThreadState(conversationId));
|
|
6914
|
-
await hydrateConversationMessages({
|
|
6915
|
-
conversation,
|
|
6916
|
-
conversationId
|
|
6917
|
-
});
|
|
6918
|
-
await supersedeOpenMailboxTurns({
|
|
6919
|
-
conversation,
|
|
6920
|
-
conversationId
|
|
6921
|
-
});
|
|
6922
|
-
await persistThreadStateById(conversationId, { conversation });
|
|
6923
|
-
}
|
|
6924
|
-
// src/chat/agent-invocations/types.ts
|
|
6925
|
-
const exactStringSchema = z.string().min(1).refine((value) => value === value.trim());
|
|
6926
|
-
const agentNameSchema = exactStringSchema.max(64);
|
|
6927
|
-
/**
|
|
6928
|
-
* Kind of a new child Conversation. A Thread is a child that people can
|
|
6929
|
-
* message; a Task is one that only its parent messages.
|
|
6930
|
-
*/
|
|
6931
|
-
const CHILD_AGENT_KINDS = ["thread", "task"];
|
|
6932
|
-
/** `messageAgent` target for the parent of a child agent. */
|
|
6933
|
-
const PARENT_AGENT_TARGET = "parent";
|
|
6934
|
-
const agentInvocationMailboxStatusSchema = z.enum(AGENT_INVOCATION_MAILBOX_STATUSES);
|
|
6935
|
-
const agentInvocationParentMailboxStatusSchema = z.enum(AGENT_INVOCATION_PARENT_MAILBOX_STATUSES);
|
|
6936
|
-
const agentBindingSchema = z.object({
|
|
6937
|
-
childConversationId: exactStringSchema,
|
|
6938
|
-
name: agentNameSchema,
|
|
6939
|
-
parentConversationId: exactStringSchema
|
|
6940
|
-
}).strict();
|
|
6941
|
-
const agentInvocationBaseSchema = z.object({
|
|
6942
|
-
actor: actorSchema,
|
|
6943
|
-
agentName: agentNameSchema.optional(),
|
|
6944
|
-
childConversationId: exactStringSchema,
|
|
6945
|
-
createdAtMs: z.number().finite(),
|
|
6946
|
-
credentialContext: credentialContextSchema.optional(),
|
|
6947
|
-
destination: destinationSchema,
|
|
6948
|
-
input: exactStringSchema,
|
|
6949
|
-
invocationId: exactStringSchema,
|
|
6950
|
-
mailboxStatus: agentInvocationMailboxStatusSchema,
|
|
6951
|
-
parentConversationId: exactStringSchema,
|
|
6952
|
-
parentToolCallId: exactStringSchema.optional(),
|
|
6953
|
-
agentType: agentTypeSchema.optional(),
|
|
6954
|
-
/** The child starts with its parent's history. */
|
|
6955
|
-
fork: z.literal(true).optional(),
|
|
6956
|
-
reasoningLevel: z.enum(TURN_REASONING_LEVELS).optional(),
|
|
6957
|
-
source: sourceSchema,
|
|
6958
|
-
title: exactStringSchema.optional(),
|
|
6959
|
-
updatedAtMs: z.number().finite()
|
|
6960
|
-
}).strict();
|
|
6961
|
-
const agentInvocationSchema = z.discriminatedUnion("status", [
|
|
6962
|
-
agentInvocationBaseSchema.extend({ status: z.enum([
|
|
6963
|
-
"pending",
|
|
6964
|
-
"running",
|
|
6965
|
-
"paused"
|
|
6966
|
-
]) }),
|
|
6967
|
-
agentInvocationBaseSchema.extend({
|
|
6968
|
-
parentMailboxStatus: agentInvocationParentMailboxStatusSchema,
|
|
6969
|
-
result: z.string(),
|
|
6970
|
-
status: z.literal("completed"),
|
|
6971
|
-
terminalAtMs: z.number().finite()
|
|
6972
|
-
}),
|
|
6973
|
-
agentInvocationBaseSchema.extend({
|
|
6974
|
-
errorMessage: z.string(),
|
|
6975
|
-
parentMailboxStatus: agentInvocationParentMailboxStatusSchema,
|
|
6976
|
-
status: z.enum([
|
|
6977
|
-
"blocked",
|
|
6978
|
-
"failed",
|
|
6979
|
-
"stopped"
|
|
6980
|
-
]),
|
|
6981
|
-
terminalAtMs: z.number().finite()
|
|
6982
|
-
})
|
|
6983
|
-
]);
|
|
6984
|
-
const createAgentInvocationSchema = z.object({
|
|
6985
|
-
actor: actorSchema,
|
|
6986
|
-
agentName: agentNameSchema.optional(),
|
|
6987
|
-
credentialContext: credentialContextSchema.optional(),
|
|
6988
|
-
destination: destinationSchema,
|
|
6989
|
-
idempotencyKey: exactStringSchema,
|
|
6990
|
-
input: exactStringSchema,
|
|
6991
|
-
kind: z.enum(CHILD_AGENT_KINDS).default("task"),
|
|
6992
|
-
parentConversationId: exactStringSchema,
|
|
6993
|
-
parentToolCallId: exactStringSchema.optional(),
|
|
6994
|
-
agentType: agentTypeSchema.optional(),
|
|
6995
|
-
fork: z.literal(true).optional(),
|
|
6996
|
-
reasoningLevel: z.enum(TURN_REASONING_LEVELS).optional(),
|
|
6997
|
-
title: exactStringSchema.optional()
|
|
6998
|
-
}).strict();
|
|
6999
|
-
/** How a finished task of a child agent ended. A stop is not a result. */
|
|
7000
|
-
const CHILD_AGENT_RESULTS = [
|
|
7001
|
-
"completed",
|
|
7002
|
-
"blocked",
|
|
7003
|
-
"failed"
|
|
7004
|
-
];
|
|
7005
|
-
// src/chat/agent-invocations/bindings.ts
|
|
7006
|
-
function bindingFromRow(row) {
|
|
7007
|
-
return agentBindingSchema.parse({
|
|
7008
|
-
childConversationId: row.childConversationId,
|
|
7009
|
-
name: row.name,
|
|
7010
|
-
parentConversationId: row.parentConversationId
|
|
7011
|
-
});
|
|
7012
|
-
}
|
|
7013
|
-
/** Read one named child binding in its parent-agent scope. */
|
|
7014
|
-
async function getAgentBinding(args) {
|
|
7015
|
-
const rows = await getSqlExecutor().db().select().from(juniorAgentBindings).where(and(eq(juniorAgentBindings.parentConversationId, args.parentConversationId), eq(juniorAgentBindings.name, args.name)));
|
|
7016
|
-
return rows[0] ? bindingFromRow(rows[0]) : void 0;
|
|
7017
|
-
}
|
|
7018
|
-
/**
|
|
7019
|
-
* Find a direct child agent of one parent by name or child Conversation id.
|
|
7020
|
-
* A child that no Agent invocation names stores its agent config.
|
|
7021
|
-
*/
|
|
7022
|
-
async function findChildAgentConversationId(args) {
|
|
7023
|
-
const binding = await getAgentBinding({
|
|
7024
|
-
name: args.target,
|
|
7025
|
-
parentConversationId: args.parentConversationId
|
|
7026
|
-
});
|
|
7027
|
-
if (binding) return binding.childConversationId;
|
|
7028
|
-
const db = getSqlExecutor().db();
|
|
7029
|
-
return (await db.select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(eq(juniorConversations.parentConversationId, args.parentConversationId), eq(juniorConversations.conversationId, args.target), or(isNotNull(juniorConversations.agentConfig), exists(db.select({ invocationId: juniorAgentInvocations.invocationId }).from(juniorAgentInvocations).where(eq(juniorAgentInvocations.childConversationId, args.target)))))).limit(1))[0]?.conversationId;
|
|
7030
|
-
}
|
|
7031
|
-
// src/chat/agent-invocations/errors.ts
|
|
7032
|
-
/** A child agent already uses this name in the parent Conversation. */
|
|
7033
|
-
var AgentNameInUseError = class extends Error {
|
|
7034
|
-
constructor(name) {
|
|
7035
|
-
super(`A child agent named "${name}" already exists`);
|
|
7036
|
-
this.name = "AgentNameInUseError";
|
|
7037
|
-
}
|
|
7038
|
-
};
|
|
7039
|
-
/** Parent already has the maximum number of non-terminal child invocations. */
|
|
7040
|
-
var AgentInvocationLimitError = class extends Error {
|
|
7041
|
-
constructor(limit) {
|
|
7042
|
-
super(`Parent already has ${limit} active child agent invocations (limit ${limit})`);
|
|
7043
|
-
this.name = "AgentInvocationLimitError";
|
|
7044
|
-
}
|
|
7045
|
-
};
|
|
7046
|
-
/**
|
|
7047
|
-
* The Conversation that calls spawnAgent is too deep to start child agents,
|
|
7048
|
-
* or its parent chain does not end at a root.
|
|
7049
|
-
*/
|
|
7050
|
-
var AgentDepthLimitError = class extends Error {
|
|
7051
|
-
constructor(maxAgentDepth) {
|
|
7052
|
-
super(`This agent cannot start child agents: only ${maxAgentDepth} level(s) of child agents can start their own`);
|
|
7053
|
-
this.name = "AgentDepthLimitError";
|
|
7054
|
-
}
|
|
7055
|
-
};
|
|
7056
|
-
/** A child agent already has the maximum number of open tasks. */
|
|
7057
|
-
var AgentMessageQueueFullError = class extends Error {
|
|
7058
|
-
constructor(limit) {
|
|
7059
|
-
super(`The child agent already has ${limit} open tasks`);
|
|
7060
|
-
this.name = "AgentMessageQueueFullError";
|
|
7061
|
-
}
|
|
7062
|
-
};
|
|
7063
|
-
/**
|
|
7064
|
-
* A messageAgent target is not the parent, a child, or a top-level agent that
|
|
7065
|
-
* the sender can message.
|
|
7066
|
-
*/
|
|
7067
|
-
var AgentMessageTargetError = class extends Error {
|
|
7068
|
-
constructor(message) {
|
|
7069
|
-
super(message);
|
|
7070
|
-
this.name = "AgentMessageTargetError";
|
|
7071
|
-
}
|
|
7072
|
-
};
|
|
7073
|
-
/**
|
|
7074
|
-
* Cap the non-terminal Agent invocations of one child, including the one that
|
|
7075
|
-
* runs. Each message to a busy child with a row queues one more. A child with
|
|
7076
|
-
* no row has no cap: its parent messages wait in its mailbox like any input.
|
|
7077
|
-
*/
|
|
7078
|
-
const MAX_OPEN_AGENT_INVOCATIONS_PER_CHILD = 4;
|
|
7079
|
-
/**
|
|
7080
|
-
* Insert one pending agent invocation and read it back. An existing row with
|
|
7081
|
-
* the same id wins, so the caller checks that the row it reads is its own.
|
|
7082
|
-
*/
|
|
7083
|
-
async function insertAgentInvocation(invocation, nowMs) {
|
|
7084
|
-
await getSqlExecutor().db().insert(juniorAgentInvocations).values({
|
|
7085
|
-
...invocation,
|
|
7086
|
-
agentName: invocation.agentName ?? null,
|
|
7087
|
-
agentType: invocation.agentType ?? null,
|
|
7088
|
-
fork: invocation.fork ?? false,
|
|
7089
|
-
credentialContext: invocation.credentialContext ?? null,
|
|
7090
|
-
parentToolCallId: invocation.parentToolCallId ?? null,
|
|
7091
|
-
reasoningLevel: invocation.reasoningLevel ?? null,
|
|
7092
|
-
source: invocation.source ?? { kind: "agent_invocation" },
|
|
7093
|
-
title: invocation.title ?? null,
|
|
7094
|
-
status: "pending",
|
|
7095
|
-
mailboxStatus: "pending",
|
|
7096
|
-
createdAt: new Date(nowMs),
|
|
7097
|
-
updatedAt: new Date(nowMs),
|
|
7098
|
-
terminalAt: null
|
|
7099
|
-
}).onConflictDoNothing();
|
|
7100
|
-
return await getAgentInvocation(invocation.invocationId);
|
|
7101
|
-
}
|
|
7102
|
-
/**
|
|
7103
|
-
* Require every durable creation input to match before replaying one key.
|
|
7104
|
-
* The title is not compared: a retry can generate a different one, and the
|
|
7105
|
-
* stored title wins.
|
|
7106
|
-
*/
|
|
7107
|
-
function sameCreateInput(invocation, input) {
|
|
7108
|
-
return invocation.parentConversationId === input.parentConversationId && invocation.agentName === input.agentName && invocation.input === input.input && invocation.agentType === input.agentType && invocation.fork === input.fork && invocation.reasoningLevel === input.reasoningLevel && JSON.stringify(invocation.actor) === JSON.stringify(input.actor) && JSON.stringify(invocation.credentialContext) === JSON.stringify(input.credentialContext) && JSON.stringify(invocation.destination) === JSON.stringify(input.destination);
|
|
7109
|
-
}
|
|
7110
|
-
/**
|
|
7111
|
-
* A stopped child agent cannot start or give work to child agents until its
|
|
7112
|
-
* parent gives it new work. A Turn on the child's Conversation loop
|
|
7113
|
-
* has no open agent invocation, but it can. A root Conversation has no agent
|
|
7114
|
-
* invocation or agent config, so it always passes. `open` is the parent's open work from
|
|
7115
|
-
* `listOpenAgentInvocations`.
|
|
7116
|
-
*/
|
|
7117
|
-
async function assertCanGiveChildWork(parentConversationId, open) {
|
|
7118
|
-
if (open.some((row) => row.childConversationId === parentConversationId)) return;
|
|
7119
|
-
const latest = await getLatestAgentInvocationForConversation(parentConversationId);
|
|
7120
|
-
if (latest ? isStoppedAgentInvocation(latest) : await readAgentConfig(parentConversationId) !== void 0 && await getConversationStoppedAtMs(parentConversationId) !== void 0) throw new Error(`Agent conversation ${parentConversationId} is stopped and cannot give work to child agents`);
|
|
7121
|
-
}
|
|
7122
|
-
/**
|
|
7123
|
-
* Throw when giving work to one child agent would put its parent over
|
|
7124
|
-
* `MAX_ACTIVE_AGENT_INVOCATIONS_PER_PARENT`. A child agent is active while it
|
|
7125
|
-
* has open work, so a busy child already counts and messages queued for it
|
|
7126
|
-
* do not count again. A new or idle child becomes active. This is the only
|
|
7127
|
-
* place the rule for which child agents count lives. `open` is the parent's
|
|
7128
|
-
* open work from `listOpenAgentInvocations`. A child that no agent
|
|
7129
|
-
* invocation names is active while its listing shows open work.
|
|
7130
|
-
*/
|
|
7131
|
-
async function assertChildAgentCapacity(open, args) {
|
|
7132
|
-
const active = /* @__PURE__ */ new Set([...open.filter((row) => row.parentConversationId === args.parentConversationId).map((row) => row.childConversationId), ...await listOpenChildAgentsWithoutAgentInvocations(args.parentConversationId)]);
|
|
7133
|
-
if (!active.has(args.childConversationId) && active.size >= 8) throw new AgentInvocationLimitError(8);
|
|
7134
|
-
}
|
|
7135
|
-
/**
|
|
7136
|
-
* Create or replay the first invocation of one new child agent. A name gives
|
|
7137
|
-
* the child a stable Conversation id that later messages can address. A name
|
|
7138
|
-
* that is already used throws: later work for that child goes through
|
|
7139
|
-
* `createAgentInvocationForMessage`.
|
|
7140
|
-
*/
|
|
7141
|
-
async function createAgentInvocation(rawInput, nowMs = Date.now()) {
|
|
7142
|
-
const input = createAgentInvocationSchema.parse(rawInput);
|
|
7143
|
-
const invocationId = getAgentInvocationId(input.parentConversationId, input.idempotencyKey);
|
|
7144
|
-
const childConversationId = input.agentName ? getNamedAgentConversationId(input.parentConversationId, input.agentName) : getUnnamedAgentConversationId(invocationId);
|
|
7145
|
-
const lockName = getChildAgentLockName(input.parentConversationId);
|
|
7146
|
-
return await getSqlExecutor().withLock(lockName, async () => {
|
|
7147
|
-
const existing = await getAgentInvocation(invocationId);
|
|
7148
|
-
if (existing) {
|
|
7149
|
-
const child = await getConversationStore().get({ conversationId: existing.childConversationId });
|
|
7150
|
-
if (!sameCreateInput(existing, input) || child?.kind !== input.kind) throw new Error(`Agent invocation idempotency key was reused with different input for ${invocationId}`);
|
|
7151
|
-
return existing;
|
|
7152
|
-
}
|
|
7153
|
-
const open = await listOpenAgentInvocations(input.parentConversationId);
|
|
7154
|
-
await assertCanGiveChildWork(input.parentConversationId, open);
|
|
7155
|
-
if (input.agentName && await getAgentBinding({
|
|
7156
|
-
name: input.agentName,
|
|
7157
|
-
parentConversationId: input.parentConversationId
|
|
7158
|
-
})) throw new AgentNameInUseError(input.agentName);
|
|
7159
|
-
await assertChildAgentCapacity(open, {
|
|
7160
|
-
childConversationId,
|
|
7161
|
-
parentConversationId: input.parentConversationId
|
|
7162
|
-
});
|
|
7163
|
-
await getConversationStore().createChild({
|
|
7164
|
-
childConversationId,
|
|
7165
|
-
kind: input.kind,
|
|
7166
|
-
parentConversationId: input.parentConversationId,
|
|
7167
|
-
nowMs,
|
|
7168
|
-
source: "internal",
|
|
7169
|
-
...input.title ? { title: input.title } : void 0
|
|
7170
|
-
});
|
|
7171
|
-
if (input.agentName) await getSqlExecutor().db().insert(juniorAgentBindings).values({
|
|
7172
|
-
childConversationId,
|
|
7173
|
-
name: input.agentName,
|
|
7174
|
-
parentConversationId: input.parentConversationId
|
|
7175
|
-
});
|
|
7176
|
-
const invocation = await insertAgentInvocation({
|
|
7177
|
-
actor: input.actor,
|
|
7178
|
-
agentName: input.agentName,
|
|
7179
|
-
agentType: input.agentType,
|
|
7180
|
-
childConversationId,
|
|
7181
|
-
credentialContext: input.credentialContext,
|
|
7182
|
-
destination: input.destination,
|
|
7183
|
-
fork: input.fork,
|
|
7184
|
-
input: input.input,
|
|
7185
|
-
invocationId,
|
|
7186
|
-
parentConversationId: input.parentConversationId,
|
|
7187
|
-
parentToolCallId: input.parentToolCallId,
|
|
7188
|
-
reasoningLevel: input.reasoningLevel,
|
|
7189
|
-
title: input.title
|
|
7190
|
-
}, nowMs);
|
|
7191
|
-
if (!invocation || !sameCreateInput(invocation, input)) throw new Error(`Agent invocation creation raced for ${invocationId}`);
|
|
7192
|
-
return invocation;
|
|
7193
|
-
});
|
|
7194
|
-
}
|
|
7195
|
-
/**
|
|
7196
|
-
* Create or replay the agent invocation that gives one input to a child
|
|
7197
|
-
* Conversation: a result or message from its own child agent, or its own
|
|
7198
|
-
* watch events. It continues that Conversation for the same parent as
|
|
7199
|
-
* `latest`, and for the same Actor and credentials unless `runAs` sets them.
|
|
7200
|
-
* It skips the queue and active-count checks because it continues work that
|
|
7201
|
-
* already passed them.
|
|
7202
|
-
*/
|
|
7203
|
-
async function createAgentInvocationFromLatest(args, nowMs = Date.now()) {
|
|
7204
|
-
const { latest } = args;
|
|
7205
|
-
const { actor, credentialContext } = args.runAs ?? latest;
|
|
7206
|
-
const invocation = await insertAgentInvocation({
|
|
7207
|
-
actor,
|
|
7208
|
-
agentName: latest.agentName,
|
|
7209
|
-
agentType: latest.agentType,
|
|
7210
|
-
childConversationId: latest.childConversationId,
|
|
7211
|
-
credentialContext,
|
|
7212
|
-
destination: latest.destination,
|
|
7213
|
-
fork: args.runAs?.fork,
|
|
7214
|
-
input: args.input,
|
|
7215
|
-
invocationId: args.invocationId,
|
|
7216
|
-
parentConversationId: latest.parentConversationId,
|
|
7217
|
-
parentToolCallId: args.runAs?.parentToolCallId,
|
|
7218
|
-
reasoningLevel: latest.reasoningLevel,
|
|
7219
|
-
source: args.runAs?.source
|
|
7220
|
-
}, nowMs);
|
|
7221
|
-
if (!invocation || invocation.childConversationId !== latest.childConversationId) throw new Error(`Agent invocation creation raced for ${args.invocationId}`);
|
|
7222
|
-
return invocation;
|
|
7223
|
-
}
|
|
7224
|
-
/**
|
|
7225
|
-
* Create or replay the agent invocation for one message from a parent to one
|
|
7226
|
-
* of its child agents. The child continues its history. If the child already
|
|
7227
|
-
* has open work, the new agent invocation waits for that work and the parent
|
|
7228
|
-
* gets one report for both. A stopped child starts again.
|
|
7229
|
-
*/
|
|
7230
|
-
async function createAgentInvocationForMessage(input, nowMs = Date.now()) {
|
|
7231
|
-
const invocationId = getAgentInvocationId(input.parentConversationId, input.idempotencyKey);
|
|
7232
|
-
return await getSqlExecutor().withLock(getChildAgentLockName(input.parentConversationId), async () => {
|
|
7233
|
-
const existing = await getAgentInvocation(invocationId);
|
|
7234
|
-
if (existing) {
|
|
7235
|
-
if (existing.childConversationId !== input.childConversationId || existing.input !== input.input) throw new Error(`Agent invocation idempotency key was reused with different input for ${invocationId}`);
|
|
7236
|
-
return {
|
|
7237
|
-
invocation: existing,
|
|
7238
|
-
queued: existing.status === "pending" && (await listOpenAgentInvocations(input.parentConversationId)).some((row) => row.childConversationId === input.childConversationId && row.createdAtMs < existing.createdAtMs)
|
|
7239
|
-
};
|
|
7240
|
-
}
|
|
7241
|
-
const latest = await getLatestAgentInvocationForConversation(input.childConversationId);
|
|
7242
|
-
const child = latest ?? await readChildConversationSender(input.childConversationId);
|
|
7243
|
-
if (!child || child.parentConversationId !== input.parentConversationId) throw new Error(`${input.childConversationId} is not a child agent of ${input.parentConversationId}`);
|
|
7244
|
-
const agentConfig = latest ?? await readAgentConfig(input.childConversationId) ?? {};
|
|
7245
|
-
const open = await listOpenAgentInvocations(input.parentConversationId);
|
|
7246
|
-
await assertCanGiveChildWork(input.parentConversationId, open);
|
|
7247
|
-
const openCount = open.filter((row) => row.childConversationId === input.childConversationId).length;
|
|
7248
|
-
if (latest && openCount >= MAX_OPEN_AGENT_INVOCATIONS_PER_CHILD) throw new AgentMessageQueueFullError(MAX_OPEN_AGENT_INVOCATIONS_PER_CHILD);
|
|
7249
|
-
await assertChildAgentCapacity(open, {
|
|
7250
|
-
childConversationId: input.childConversationId,
|
|
7251
|
-
parentConversationId: input.parentConversationId
|
|
7252
|
-
});
|
|
7253
|
-
const queued = openCount > 0 || !latest && (await listOpenChildAgentsWithoutAgentInvocations(input.parentConversationId)).includes(input.childConversationId);
|
|
7254
|
-
const invocation = await insertAgentInvocation({
|
|
7255
|
-
actor: input.actor,
|
|
7256
|
-
agentName: child.agentName,
|
|
7257
|
-
agentType: agentConfig.agentType,
|
|
7258
|
-
childConversationId: input.childConversationId,
|
|
7259
|
-
credentialContext: input.credentialContext,
|
|
7260
|
-
destination: input.destination,
|
|
7261
|
-
input: input.input,
|
|
7262
|
-
invocationId,
|
|
7263
|
-
parentConversationId: input.parentConversationId,
|
|
7264
|
-
parentToolCallId: input.parentToolCallId,
|
|
7265
|
-
reasoningLevel: agentConfig.reasoningLevel
|
|
7266
|
-
}, nowMs);
|
|
7267
|
-
if (!invocation) throw new Error(`Agent invocation creation raced for ${invocationId}`);
|
|
7268
|
-
return {
|
|
7269
|
-
invocation,
|
|
7270
|
-
queued
|
|
7271
|
-
};
|
|
7272
|
-
});
|
|
7273
|
-
}
|
|
7274
|
-
// src/chat/agent-invocations/turn-end.ts
|
|
7275
|
-
/**
|
|
7276
|
-
* How a terminal agent invocation ends its child Turn. The live save and the
|
|
7277
|
-
* recovery paths both use this, so a status cannot end the Turn two ways.
|
|
7278
|
-
*/
|
|
7279
|
-
function agentInvocationTurnEnd(terminal) {
|
|
7280
|
-
const finishedAtMs = terminal.terminalAtMs;
|
|
7281
|
-
switch (terminal.status) {
|
|
7282
|
-
case "completed": return {
|
|
7283
|
-
finishedAtMs,
|
|
7284
|
-
outcome: terminal.result.trim() ? "success" : "no_reply"
|
|
7285
|
-
};
|
|
7286
|
-
case "stopped": return {
|
|
7287
|
-
finishedAtMs,
|
|
7288
|
-
outcome: "cancelled"
|
|
7289
|
-
};
|
|
7290
|
-
case "blocked": return {
|
|
7291
|
-
finishedAtMs,
|
|
7292
|
-
outcome: "blocked"
|
|
7293
|
-
};
|
|
7294
|
-
case "failed": return {
|
|
7295
|
-
failureCode: "model_execution_failed",
|
|
7296
|
-
finishedAtMs,
|
|
7297
|
-
outcome: "failed"
|
|
7298
|
-
};
|
|
7299
|
-
}
|
|
7300
|
-
}
|
|
7301
|
-
/**
|
|
7302
|
-
* Read how one saved child Turn ends its agent invocation. A saved `reply`
|
|
7303
|
-
* completes it, also when a newer Turn or a lost worker ended the Turn after
|
|
7304
|
-
* that, or the Turn is paused. Returns undefined for a paused Turn without a
|
|
7305
|
-
* `reply`, which can still resume.
|
|
7306
|
-
*/
|
|
7307
|
-
async function savedTurnEnd(turn) {
|
|
7308
|
-
const answer = readTurnAnswer(savedTurnMessages(turn, await loadTurnStart(turn.conversationId, turn.turnId)).map(({ message }) => message));
|
|
7309
|
-
if (answer && "reply" in answer) return {
|
|
7310
|
-
result: answer.reply.text,
|
|
7311
|
-
status: "completed"
|
|
7312
|
-
};
|
|
7313
|
-
if (turn.state === "paused") return;
|
|
7314
|
-
if (turn.state !== "completed" || turn.errorMessage) return {
|
|
7315
|
-
errorMessage: turn.errorMessage ?? "Agent invocation failed",
|
|
7316
|
-
status: "failed"
|
|
7317
|
-
};
|
|
7318
|
-
if (answer && "blocked" in answer) return {
|
|
7319
|
-
errorMessage: answer.blocked.missing,
|
|
7320
|
-
status: "blocked"
|
|
7321
|
-
};
|
|
7322
|
-
return {
|
|
7323
|
-
result: answer ? "" : getTerminalAssistantMessages(turn.piMessages).map(getAssistantReplyText).filter((text) => text !== void 0).join("\n\n"),
|
|
7324
|
-
status: "completed"
|
|
7325
|
-
};
|
|
7326
|
-
}
|
|
7327
|
-
// src/chat/agent-invocations/work.ts
|
|
7328
|
-
const agentInvocationMailboxMetadataSchema = z.object({
|
|
7329
|
-
agentInvocationId: z.string().min(1),
|
|
7330
|
-
kind: z.literal("agent_invocation")
|
|
7331
|
-
}).strict();
|
|
7332
|
-
/** Map a durable invocation's model settings to the child Run policy. */
|
|
7333
|
-
function agentInvocationRunPolicy(invocation) {
|
|
7334
|
-
return {
|
|
7335
|
-
disabledFeatures: ["interactive-auth"],
|
|
7336
|
-
...invocation.reasoningLevel ? { reasoning: invocation.reasoningLevel } : void 0
|
|
7337
|
-
};
|
|
7338
|
-
}
|
|
7339
|
-
/** Build destinationless mailbox work that references one durable invocation. */
|
|
7340
|
-
function buildAgentInvocationInboundMessage(invocation, nowMs = Date.now()) {
|
|
7341
|
-
return {
|
|
7342
|
-
conversationId: invocation.childConversationId,
|
|
7343
|
-
createdAtMs: invocation.createdAtMs,
|
|
7344
|
-
delivery: "defer",
|
|
7345
|
-
inboundMessageId: getAgentInvocationMessageId(invocation.invocationId),
|
|
7346
|
-
input: {
|
|
7347
|
-
authorId: invocation.invocationId,
|
|
7348
|
-
authorIdentityId: SYSTEM_IDENTITY_ID,
|
|
7349
|
-
text: "[agent invocation]",
|
|
7350
|
-
metadata: {
|
|
7351
|
-
agentInvocationId: invocation.invocationId,
|
|
7352
|
-
kind: "agent_invocation"
|
|
7353
|
-
}
|
|
7354
|
-
},
|
|
7355
|
-
receivedAtMs: nowMs,
|
|
7356
|
-
source: "internal"
|
|
7357
|
-
};
|
|
7358
|
-
}
|
|
7359
|
-
/** Append one invocation to its child mailbox and send the normal queue wake. */
|
|
7360
|
-
async function enqueueAgentInvocation(invocation, options) {
|
|
7361
|
-
if (invocation.mailboxStatus === "appended" || isTerminalAgentInvocation(invocation)) return;
|
|
7362
|
-
await recordSubagentStarted(invocation, options.eventMeta);
|
|
7363
|
-
if (invocation.parentToolCallId !== void 0) await resumeConversationTree(invocation.childConversationId, invocation.createdAtMs);
|
|
7364
|
-
const nowMs = options.nowMs ?? Date.now();
|
|
7365
|
-
await appendAndEnqueueInboundMessage({
|
|
7366
|
-
message: buildAgentInvocationInboundMessage(invocation, nowMs),
|
|
7367
|
-
conversationStore: options.conversationStore,
|
|
7368
|
-
nowMs,
|
|
7369
|
-
queue: options.queue,
|
|
7370
|
-
state: options.state
|
|
7371
|
-
});
|
|
7372
|
-
await markAgentInvocationMailboxAppended(invocation.invocationId, nowMs);
|
|
7373
|
-
}
|
|
7374
|
-
/** Create or replay an invocation, then durably schedule its child work. */
|
|
7375
|
-
async function createAndEnqueueAgentInvocation(input, options) {
|
|
7376
|
-
const invocation = await createAgentInvocation(input, options.nowMs);
|
|
7377
|
-
await enqueueAgentInvocation(invocation, options);
|
|
7378
|
-
return await getAgentInvocation(invocation.invocationId) ?? invocation;
|
|
7379
|
-
}
|
|
7380
|
-
/** Require one invocation metadata reference for one leased mailbox attempt. */
|
|
7381
|
-
/** Return whether one mailbox input is a parent task or message for an agent invocation. */
|
|
7382
|
-
function isAgentInvocationInput(message) {
|
|
7383
|
-
return agentInvocationMailboxMetadataSchema.safeParse(message.input.metadata).success;
|
|
7384
|
-
}
|
|
7385
|
-
function invocationIdFromMessages(messages) {
|
|
7386
|
-
if (messages.length === 0) return;
|
|
7387
|
-
const parsed = messages.map((message) => agentInvocationMailboxMetadataSchema.safeParse(message.input.metadata));
|
|
7388
|
-
if (parsed.every((result) => !result.success)) return;
|
|
7389
|
-
if (parsed.some((result) => !result.success)) throw new Error("Conversation mailbox mixes agent invocation and other input");
|
|
7390
|
-
const invocationIds = new Set(parsed.map((result) => {
|
|
7391
|
-
if (!result.success) throw new Error("Agent invocation mailbox metadata failed validation");
|
|
7392
|
-
return result.data.agentInvocationId;
|
|
7393
|
-
}));
|
|
7394
|
-
if (invocationIds.size !== 1) throw new Error("Conversation mailbox contains multiple agent invocations in one attempt");
|
|
7395
|
-
return invocationIds.values().next().value;
|
|
7396
|
-
}
|
|
7397
|
-
/**
|
|
7398
|
-
* Text that the child agent model reads for one agent invocation. A parent
|
|
7399
|
-
* agent task or message becomes one `<parent-agent-task>`. Results of the
|
|
7400
|
-
* child's own child agents already have their own tag.
|
|
7401
|
-
*/
|
|
7402
|
-
function agentInvocationInputText(invocation) {
|
|
7403
|
-
if (!invocation.parentToolCallId) return invocation.input;
|
|
7404
|
-
const instructions = [invocation.fork ? FORK_INSTRUCTIONS : void 0, agentTypeInstructions(invocation.agentType)].filter((text) => text !== void 0);
|
|
7405
|
-
return renderParentAgentTask([...instructions.flatMap((text) => [text, ""]), invocation.input]);
|
|
7406
|
-
}
|
|
7407
|
-
/**
|
|
7408
|
-
* A parent agent task or message is the child's instruction. Another input,
|
|
7409
|
-
* such as a result of the child's own child agent or an Event, is context.
|
|
7410
|
-
*/
|
|
7411
|
-
function agentInvocationProvenance(invocation) {
|
|
7412
|
-
return invocation.parentToolCallId ? agentInstructionProvenance : contextProvenance;
|
|
7413
|
-
}
|
|
7414
|
-
/**
|
|
7415
|
-
* Resolve the agent invocation that owns this work: the one named by its
|
|
7416
|
-
* mailbox input, or for an empty wake the open one. Other work has none.
|
|
7417
|
-
*/
|
|
7418
|
-
async function resolveAgentInvocationId(context) {
|
|
7419
|
-
const mailboxInvocationId = invocationIdFromMessages(context.attempt.messages);
|
|
7420
|
-
if (mailboxInvocationId || context.attempt.messages.length > 0) return mailboxInvocationId;
|
|
7421
|
-
const active = await getActiveAgentInvocationForConversation(context.conversationId);
|
|
7422
|
-
if (active) return active.invocationId;
|
|
7423
|
-
const latest = await getLatestAgentInvocationForConversation(context.conversationId);
|
|
7424
|
-
const turn = latest ? await getTurnRecord(context.conversationId, getAgentInvocationTurnId(latest.invocationId)) : void 0;
|
|
7425
|
-
return turn?.state === "paused" || turn?.state === "running" ? latest?.invocationId : void 0;
|
|
7426
|
-
}
|
|
7427
|
-
/**
|
|
7428
|
-
* Give queued parent messages to the running agent invocation of a child as
|
|
7429
|
-
* steering messages. A message joins only with the Actor and credentials of
|
|
7430
|
-
* the running Turn. The first message that does not match stops the scan, so
|
|
7431
|
-
* it and every later message wait for the current work. Each message that
|
|
7432
|
-
* joins ends as `steered`, and the running agent invocation reports for it.
|
|
7433
|
-
*/
|
|
7434
|
-
function createAgentMessageSteeringDrain(context, running) {
|
|
7435
|
-
const turnId = getAgentInvocationTurnId(running.invocationId);
|
|
7436
|
-
return async (accept) => {
|
|
7437
|
-
const accepted = [];
|
|
7438
|
-
await context.attempt.drain(async (pending) => {
|
|
7439
|
-
const readIds = [];
|
|
7440
|
-
const joining = [];
|
|
7441
|
-
for (const message of pending) {
|
|
7442
|
-
const metadata = agentInvocationMailboxMetadataSchema.safeParse(message.input.metadata);
|
|
7443
|
-
if (!metadata.success) continue;
|
|
7444
|
-
const candidate = await getAgentInvocation(metadata.data.agentInvocationId);
|
|
7445
|
-
if (!candidate?.parentToolCallId || candidate.invocationId === running.invocationId) continue;
|
|
7446
|
-
if (isTerminalAgentInvocation(candidate)) {
|
|
7447
|
-
if (candidate.parentMailboxStatus === "steered") readIds.push(message.inboundMessageId);
|
|
7448
|
-
continue;
|
|
7449
|
-
}
|
|
7450
|
-
if (!sameActorIdentity(candidate.actor, running.actor) || !isDeepStrictEqual(candidate.credentialContext, running.credentialContext)) break;
|
|
7451
|
-
joining.push(candidate);
|
|
7452
|
-
readIds.push(message.inboundMessageId);
|
|
7453
|
-
}
|
|
7454
|
-
if (joining.length === 0) return readIds;
|
|
7455
|
-
const saved = (await getTurnRecord(running.childConversationId, turnId))?.piMessages ?? [];
|
|
7456
|
-
const messages = withoutSavedSteeringMessages(saved, joining.map((candidate) => ({
|
|
7457
|
-
kind: "runtime",
|
|
7458
|
-
provenance: agentInvocationProvenance(candidate),
|
|
7459
|
-
text: agentInvocationInputText(candidate),
|
|
7460
|
-
timestampMs: candidate.createdAtMs
|
|
7461
|
-
})), buildSteeringPiMessage);
|
|
7462
|
-
if (messages.length > 0) {
|
|
7463
|
-
await accept(messages);
|
|
7464
|
-
accepted.push(...messages);
|
|
7465
|
-
}
|
|
7466
|
-
for (const candidate of joining) {
|
|
7467
|
-
const terminal = await markAgentInvocationSteered(candidate.invocationId);
|
|
7468
|
-
if (terminal && isTerminalAgentInvocation(terminal)) await recordSubagentEnded(terminal);
|
|
7469
|
-
}
|
|
7470
|
-
return readIds;
|
|
7471
|
-
}, { deferred: true });
|
|
7472
|
-
return accepted;
|
|
7473
|
-
};
|
|
7474
|
-
}
|
|
7475
|
-
/** Project the terminal invocation into the idempotent turn lifecycle. */
|
|
7476
|
-
async function persistTerminalLifecycle(terminal) {
|
|
7477
|
-
const turnId = getAgentInvocationTurnId(terminal.invocationId);
|
|
7478
|
-
if (terminal.status !== "completed") await abandonTurnRecord({
|
|
7479
|
-
conversationId: terminal.childConversationId,
|
|
7480
|
-
errorMessage: terminal.status === "stopped" ? "Turn cancelled" : terminal.errorMessage,
|
|
7481
|
-
turnId
|
|
7482
|
-
});
|
|
7483
|
-
await finishTurn(terminal.childConversationId, turnId, agentInvocationTurnEnd(terminal));
|
|
7484
|
-
}
|
|
7485
|
-
/**
|
|
7486
|
-
* Stop an invocation whose worker died, or project its terminal turn result.
|
|
7487
|
-
* With `resumeLostWorker`, a Turn whose worker died resumes once from its last
|
|
7488
|
-
* save, as a root Turn does. A second loss stops it.
|
|
7489
|
-
*/
|
|
7490
|
-
async function projectTerminalTurn(invocation, options = {}) {
|
|
7491
|
-
const { resumeLostWorker, ...completeOptions } = options;
|
|
7492
|
-
let turn = await getTurnRecord(invocation.childConversationId, getAgentInvocationTurnId(invocation.invocationId));
|
|
7493
|
-
if (!turn) return;
|
|
7494
|
-
if (resumeLostWorker && turn.state === "running" && await pauseLostWorkerTurn(turn)) return;
|
|
7495
|
-
if (turn.state === "running" || resumeLostWorker && turn.state === "paused" && lostWorkerBeforeFirstSave(turn)) {
|
|
7496
|
-
turn = await failTurnRecord({
|
|
7497
|
-
conversationId: turn.conversationId,
|
|
7498
|
-
expectedVersion: turn.version,
|
|
7499
|
-
turnId: turn.turnId,
|
|
7500
|
-
errorMessage: "Agent invocation lost its worker before it could pause"
|
|
7501
|
-
});
|
|
7502
|
-
if (!turn) return;
|
|
7503
|
-
}
|
|
7504
|
-
const end = await savedTurnEnd(turn);
|
|
7505
|
-
if (!end) return;
|
|
7506
|
-
if (turn.state === "paused") await abandonTurnRecord({
|
|
7507
|
-
conversationId: turn.conversationId,
|
|
7508
|
-
turnId: turn.turnId
|
|
7509
|
-
});
|
|
7510
|
-
return await completeAgentInvocation({
|
|
7511
|
-
...completeOptions,
|
|
7512
|
-
invocationId: invocation.invocationId,
|
|
7513
|
-
...end
|
|
7514
|
-
});
|
|
7515
|
-
}
|
|
7516
|
-
/**
|
|
7517
|
-
* End every running or paused agent invocation of a child before other work
|
|
7518
|
-
* opens a Turn there, so the child has one open Turn. A saved finished Turn
|
|
7519
|
-
* gives its result. Every other one fails with `errorMessage`, because the
|
|
7520
|
-
* newer work does not continue its task. Each reports on its own.
|
|
7521
|
-
*/
|
|
7522
|
-
async function endActiveAgentInvocations(conversationId, options) {
|
|
7523
|
-
for (const active of await listAgentInvocationsForConversation(conversationId, ACTIVE_AGENT_INVOCATION_STATUSES)) {
|
|
7524
|
-
if (active.invocationId === options.exceptInvocationId) continue;
|
|
7525
|
-
const terminal = await projectTerminalTurn(active, { reportNow: true }) ?? await completeAgentInvocation({
|
|
7526
|
-
invocationId: active.invocationId,
|
|
7527
|
-
errorMessage: options.errorMessage,
|
|
7528
|
-
reportNow: true,
|
|
7529
|
-
status: "failed"
|
|
7530
|
-
});
|
|
7531
|
-
if (terminal && isTerminalAgentInvocation(terminal)) {
|
|
7532
|
-
await persistTerminalLifecycle(terminal);
|
|
7533
|
-
await recordSubagentEnded(terminal);
|
|
7534
|
-
await options.enqueueResult?.(terminal);
|
|
7535
|
-
}
|
|
7536
|
-
}
|
|
7537
|
-
}
|
|
7538
|
-
/**
|
|
7539
|
-
* End every agent invocation of a child whose last attempt lost its worker and
|
|
7540
|
-
* whose input reached the child's mailbox. The worker ran no failure path, and
|
|
7541
|
-
* the stop drops the mailbox, so none of them can run. The heartbeat sends
|
|
7542
|
-
* each result.
|
|
7543
|
-
*/
|
|
7544
|
-
async function endAgentInvocationsOfStoppedWork(conversationId, inboundMessageIds) {
|
|
7545
|
-
for (const invocation of await listAgentInvocationsForConversation(conversationId, NON_TERMINAL_AGENT_INVOCATION_STATUSES)) {
|
|
7546
|
-
if (!inboundMessageIds.includes(getAgentInvocationMessageId(invocation.invocationId))) continue;
|
|
7547
|
-
const terminal = await projectTerminalTurn(invocation, { reportNow: true }) ?? await completeAgentInvocation({
|
|
7548
|
-
invocationId: invocation.invocationId,
|
|
7549
|
-
errorMessage: "This task stopped because its worker failed repeatedly.",
|
|
7550
|
-
reportNow: true,
|
|
7551
|
-
status: "failed"
|
|
7552
|
-
});
|
|
7553
|
-
if (terminal && isTerminalAgentInvocation(terminal)) await persistTerminalLifecycle(terminal);
|
|
7554
|
-
}
|
|
7555
|
-
}
|
|
7556
|
-
/** Classify authorization failures that terminally block background work. */
|
|
7557
|
-
function blockingInvocationError(error) {
|
|
7558
|
-
const cause = getConversationTurnBoundaryError(error)?.cause ?? error;
|
|
7559
|
-
return cause instanceof AuthorizationFlowDisabledError || cause instanceof PluginCredentialFailureError ? cause : void 0;
|
|
7560
|
-
}
|
|
7561
|
-
function isInvocationInputCommitLost(error) {
|
|
7562
|
-
const cause = getConversationTurnBoundaryError(error)?.cause ?? error;
|
|
7563
|
-
return isTurnInputCommitLostError(cause);
|
|
7564
|
-
}
|
|
7565
|
-
/**
|
|
7566
|
-
* Save one completed agent result on its child agent invocation. A `reply`
|
|
7567
|
-
* goes to the parent before the Turn is saved, so a lost worker cannot save
|
|
7568
|
-
* the Turn and drop its reply.
|
|
7569
|
-
*/
|
|
7570
|
-
async function saveAgentInvocationResult(args) {
|
|
7571
|
-
const failed = args.result.diagnostics.outcome !== "success";
|
|
7572
|
-
if (args.result.reply) await args.sendReply?.(args.invocation, args.result.reply);
|
|
7573
|
-
await persistThreadStateById(args.invocation.childConversationId, { sandboxRef: args.result.sandboxRef ?? args.sandboxRef });
|
|
7574
|
-
if (args.result.piMessages?.length) await saveTurnCheckpoint({
|
|
7575
|
-
mode: "completed",
|
|
7576
|
-
conversationId: args.invocation.childConversationId,
|
|
7577
|
-
turnId: args.turnId,
|
|
7578
|
-
durationMs: args.result.diagnostics.durationMs,
|
|
7579
|
-
usage: args.result.diagnostics.usage,
|
|
7580
|
-
destination: args.invocation.destination,
|
|
7581
|
-
...failed ? { errorMessage: args.result.diagnostics.errorMessage ?? "Agent invocation failed" } : void 0,
|
|
7582
|
-
messages: args.result.piMessages,
|
|
7583
|
-
actor: args.invocation.actor,
|
|
7584
|
-
source: args.invocation.source,
|
|
7585
|
-
surface: "internal"
|
|
7586
|
-
});
|
|
7587
|
-
if (args.invocation.parentToolCallId) await resetAutomatedTurnLimit({ conversationId: args.invocation.childConversationId });
|
|
7588
|
-
else if (args.invocation.source.kind !== "agent_invocation") {
|
|
7589
|
-
const maxTurns = botConfig.maxConsecutiveAutomatedTurns;
|
|
7590
|
-
await stopAtAutomatedTurnLimit({
|
|
7591
|
-
conversationId: args.invocation.childConversationId,
|
|
7592
|
-
maxTurns,
|
|
7593
|
-
update: await recordFinishedTurnForAutomatedLimit({
|
|
7594
|
-
conversationId: args.invocation.childConversationId,
|
|
7595
|
-
maxTurns,
|
|
7596
|
-
source: args.invocation.source
|
|
7597
|
-
})
|
|
7598
|
-
});
|
|
7599
|
-
}
|
|
7600
|
-
const terminal = await completeAgentInvocation({
|
|
7601
|
-
invocationId: args.invocation.invocationId,
|
|
7602
|
-
...failed ? {
|
|
7603
|
-
errorMessage: args.result.diagnostics.errorMessage ?? "Agent invocation failed",
|
|
7604
|
-
status: "failed"
|
|
7605
|
-
} : args.result.blocked ? {
|
|
7606
|
-
errorMessage: args.result.blocked.missing,
|
|
7607
|
-
status: "blocked"
|
|
7608
|
-
} : {
|
|
7609
|
-
result: args.result.reply?.text ?? "",
|
|
7610
|
-
status: "completed"
|
|
7611
|
-
}
|
|
7612
|
-
});
|
|
7613
|
-
if (!terminal || !isTerminalAgentInvocation(terminal)) throw new Error(`Agent invocation did not finish for ${args.invocation.invocationId}`);
|
|
7614
|
-
return agentInvocationTurnEnd(terminal);
|
|
7615
|
-
}
|
|
7616
|
-
/**
|
|
7617
|
-
* Build the invocation consumer that advances work through the shared runner.
|
|
7618
|
-
* `enqueueResult` sends each terminal result to the parent mailbox. Omit it
|
|
7619
|
-
* only where the parent has no mailbox, such as the local CLI.
|
|
7620
|
-
*/
|
|
7621
|
-
function createAgentInvocationWorker(agentRunner, options = {}) {
|
|
7622
|
-
return async (context, invocationId) => {
|
|
7623
|
-
let invocation = await getAgentInvocation(invocationId);
|
|
7624
|
-
if (!invocation) throw new Error(`Agent invocation is missing for ${invocationId}`);
|
|
7625
|
-
const report = async (terminal) => {
|
|
7626
|
-
await recordSubagentEnded(terminal);
|
|
7627
|
-
await options.enqueueResult?.(terminal);
|
|
7628
|
-
};
|
|
7629
|
-
const finish = async (terminal) => {
|
|
7630
|
-
if (!terminal || !isTerminalAgentInvocation(terminal)) return;
|
|
7631
|
-
if (terminal.parentMailboxStatus !== "steered") await persistTerminalLifecycle(terminal);
|
|
7632
|
-
await report(terminal);
|
|
7633
|
-
};
|
|
7634
|
-
let acknowledged = context.attempt.messages.length === 0;
|
|
7635
|
-
const acknowledge = async () => {
|
|
7636
|
-
if (acknowledged) return;
|
|
7637
|
-
try {
|
|
7638
|
-
await context.attempt.ack();
|
|
7639
|
-
} catch {
|
|
7640
|
-
throw new TurnInputCommitLostError(`Conversation work lease lost before invocation inbox ack for ${context.conversationId}`);
|
|
7641
|
-
}
|
|
7642
|
-
acknowledged = true;
|
|
7643
|
-
};
|
|
7644
|
-
const stopSignal = context.stopSignal?.();
|
|
7645
|
-
const finishStopped = async () => {
|
|
7646
|
-
await finish(await completeAgentInvocation({
|
|
7647
|
-
invocationId,
|
|
7648
|
-
errorMessage: "Agent invocation was stopped",
|
|
7649
|
-
status: "stopped"
|
|
7650
|
-
}));
|
|
7651
|
-
await stopChildAgentsOf(context.conversationId);
|
|
7652
|
-
await acknowledge();
|
|
7653
|
-
return { status: "completed" };
|
|
7654
|
-
};
|
|
7655
|
-
const turnId = getAgentInvocationTurnId(invocation.invocationId);
|
|
7656
|
-
const lifecycle = getTurnLifecycle();
|
|
7657
|
-
let sandboxRef;
|
|
7658
|
-
let history;
|
|
7659
|
-
let location;
|
|
7660
|
-
try {
|
|
7661
|
-
if (invocation.childConversationId !== context.conversationId) throw new Error(`Agent invocation ${invocationId} belongs to ${invocation.childConversationId}, not ${context.conversationId}`);
|
|
7662
|
-
if (context.destination) throw new Error(`Agent invocation conversation ${context.conversationId} must not own a provider destination`);
|
|
7663
|
-
if (isTerminalAgentInvocation(invocation)) {
|
|
7664
|
-
await finish(invocation);
|
|
7665
|
-
await acknowledge();
|
|
7666
|
-
return { status: "completed" };
|
|
7667
|
-
}
|
|
7668
|
-
const projected = await projectTerminalTurn(invocation, { resumeLostWorker: true });
|
|
7669
|
-
if (projected && isTerminalAgentInvocation(projected)) {
|
|
7670
|
-
await finish(projected);
|
|
7671
|
-
await acknowledge();
|
|
7672
|
-
return { status: "completed" };
|
|
7673
|
-
}
|
|
7674
|
-
await endActiveAgentInvocations(invocation.childConversationId, {
|
|
7675
|
-
enqueueResult: options.enqueueResult,
|
|
7676
|
-
errorMessage: "This task was not resumed. Newer work for this child agent started, so this task ended without a result.",
|
|
7677
|
-
exceptInvocationId: invocation.invocationId
|
|
7678
|
-
});
|
|
7679
|
-
await supersedeOpenMailboxTurn(invocation.childConversationId);
|
|
7680
|
-
invocation = await markAgentInvocationRunning(invocation.invocationId) ?? invocation;
|
|
7681
|
-
if (isTerminalAgentInvocation(invocation)) {
|
|
7682
|
-
await finish(invocation);
|
|
7683
|
-
await acknowledge();
|
|
7684
|
-
return { status: "completed" };
|
|
7685
|
-
}
|
|
7686
|
-
if (invocation.fork) await commitForkHistory(invocation);
|
|
7687
|
-
await lifecycle.start({
|
|
7688
|
-
conversationId: invocation.childConversationId,
|
|
7689
|
-
createdAtMs: invocation.createdAtMs,
|
|
7690
|
-
inputMessageIds: [getAgentInvocationMessageId(invocation.invocationId)],
|
|
7691
|
-
surface: "internal",
|
|
7692
|
-
turnId
|
|
7693
|
-
});
|
|
7694
|
-
const [persisted, projection, child] = await Promise.all([
|
|
7695
|
-
getPersistedThreadState(invocation.childConversationId),
|
|
7696
|
-
loadConversationProjection({ conversationId: invocation.childConversationId }),
|
|
7697
|
-
getConversationStore().get({ conversationId: invocation.childConversationId })
|
|
7698
|
-
]);
|
|
7699
|
-
sandboxRef = getPersistedSandboxState(persisted);
|
|
7700
|
-
history = projection;
|
|
7701
|
-
location = child?.location;
|
|
7702
|
-
} catch (error) {
|
|
7703
|
-
if (isInvocationInputCommitLost(error)) return { status: "lost_lease" };
|
|
7704
|
-
if (!context.attempt.isFinalAttempt) throw error;
|
|
7705
|
-
await finish(await completeAgentInvocation({
|
|
7706
|
-
invocationId: invocation.invocationId,
|
|
7707
|
-
errorMessage: error instanceof Error ? error.message : "Agent invocation failed",
|
|
7708
|
-
status: "failed"
|
|
7709
|
-
}));
|
|
7710
|
-
await acknowledge();
|
|
7711
|
-
return { status: "completed" };
|
|
7712
|
-
}
|
|
7713
|
-
let outcome;
|
|
7714
|
-
try {
|
|
7715
|
-
outcome = await executeTurn(agentRunner, {
|
|
7716
|
-
conversationId: invocation.childConversationId,
|
|
7717
|
-
agentInvocationId: invocation.invocationId,
|
|
7718
|
-
parentConversationId: invocation.parentConversationId,
|
|
7719
|
-
turnId,
|
|
7720
|
-
runId: invocation.invocationId,
|
|
7721
|
-
instruction: {
|
|
7722
|
-
...instructionForInputs([{
|
|
7723
|
-
kind: "runtime",
|
|
7724
|
-
text: agentInvocationInputText(invocation),
|
|
7725
|
-
...invocation.parentToolCallId ? { requestText: invocation.input } : void 0
|
|
7726
|
-
}]),
|
|
7727
|
-
provenance: agentInvocationProvenance(invocation)
|
|
7728
|
-
},
|
|
7729
|
-
history,
|
|
7730
|
-
actor: invocation.actor,
|
|
7731
|
-
credentialContext: invocation.credentialContext,
|
|
7732
|
-
destination: invocation.destination,
|
|
7733
|
-
source: invocation.source,
|
|
7734
|
-
...location ? { location } : void 0,
|
|
7735
|
-
surface: "internal",
|
|
7736
|
-
deadlineAtMs: getTurnRequestDeadline()?.deadlineAtMs,
|
|
7737
|
-
...stopSignal ? { signal: stopSignal } : void 0,
|
|
7738
|
-
...agentInvocationRunPolicy(invocation),
|
|
7739
|
-
state: { sandboxRef },
|
|
7740
|
-
durability: {
|
|
7741
|
-
drainSteeringMessages: createAgentMessageSteeringDrain(context, invocation),
|
|
7742
|
-
onInputCommitted: acknowledge,
|
|
7743
|
-
shouldYield: context.shouldYield,
|
|
7744
|
-
checkIn: context.checkIn,
|
|
7745
|
-
checkStop: context.checkStop,
|
|
7746
|
-
onSandboxRefChanged: async (nextSandboxRef) => {
|
|
7747
|
-
sandboxRef = nextSandboxRef;
|
|
7748
|
-
await persistThreadStateById(invocation.childConversationId, { sandboxRef });
|
|
7749
|
-
}
|
|
7750
|
-
}
|
|
7751
|
-
}, async (result) => {
|
|
7752
|
-
if (result.diagnostics.outcome !== "success") stopSignal?.throwIfAborted();
|
|
7753
|
-
return await saveAgentInvocationResult({
|
|
7754
|
-
invocation,
|
|
7755
|
-
result,
|
|
7756
|
-
sandboxRef,
|
|
7757
|
-
sendReply: options.sendReply,
|
|
7758
|
-
turnId
|
|
7759
|
-
});
|
|
7760
|
-
});
|
|
7761
|
-
} catch (error) {
|
|
7762
|
-
const runError = error instanceof AgentRunError ? error.cause : error;
|
|
7763
|
-
if (isInvocationInputCommitLost(runError)) return { status: "lost_lease" };
|
|
7764
|
-
if (stopSignal?.aborted) return await finishStopped();
|
|
7765
|
-
const blocking = blockingInvocationError(runError);
|
|
7766
|
-
if (blocking) {
|
|
7767
|
-
await finish(await completeAgentInvocation({
|
|
7768
|
-
invocationId: invocation.invocationId,
|
|
7769
|
-
errorMessage: blocking.message,
|
|
7770
|
-
status: "blocked"
|
|
7771
|
-
}));
|
|
7772
|
-
await acknowledge();
|
|
7773
|
-
return { status: "completed" };
|
|
7774
|
-
}
|
|
7775
|
-
if (!context.attempt.isFinalAttempt && !isTurnExecutionLimitExceededError(runError)) throw runError;
|
|
7776
|
-
await finish(await completeAgentInvocation({
|
|
7777
|
-
invocationId: invocation.invocationId,
|
|
7778
|
-
errorMessage: runError instanceof Error ? runError.message : "Agent invocation failed",
|
|
7779
|
-
status: "failed"
|
|
7780
|
-
}));
|
|
7781
|
-
await acknowledge();
|
|
7782
|
-
return { status: "completed" };
|
|
7783
|
-
}
|
|
7784
|
-
if (outcome.status !== "completed" && stopSignal?.aborted) return await finishStopped();
|
|
7785
|
-
if (outcome.status === "suspended") {
|
|
7786
|
-
await markAgentInvocationPaused(invocation.invocationId);
|
|
7787
|
-
return { status: "yielded" };
|
|
7788
|
-
}
|
|
7789
|
-
if (outcome.status === "awaiting_auth") {
|
|
7790
|
-
await finish(await completeAgentInvocation({
|
|
7791
|
-
invocationId: invocation.invocationId,
|
|
7792
|
-
errorMessage: `Agent invocation requires ${outcome.providerDisplayName} authorization`,
|
|
7793
|
-
status: "blocked"
|
|
7794
|
-
}));
|
|
7795
|
-
await acknowledge();
|
|
7796
|
-
return { status: "completed" };
|
|
7797
|
-
}
|
|
7798
|
-
let terminal = await getAgentInvocation(invocation.invocationId);
|
|
7799
|
-
if (stopSignal?.aborted) {
|
|
7800
|
-
if (terminal && isTerminalAgentInvocation(terminal) && terminal.parentMailboxStatus === "replaced") terminal = await reportReplacedAgentInvocation(terminal.invocationId);
|
|
7801
|
-
await stopChildAgentsOf(context.conversationId);
|
|
7802
|
-
}
|
|
7803
|
-
if (terminal && isTerminalAgentInvocation(terminal)) await report(terminal);
|
|
7804
|
-
await acknowledge();
|
|
7805
|
-
return { status: "completed" };
|
|
7806
|
-
};
|
|
7807
|
-
}
|
|
7808
|
-
// src/chat/agent-invocations/parent-message.ts
|
|
7809
|
-
/**
|
|
7810
|
-
* A parent agent task or message to a child that no Agent invocation names.
|
|
7811
|
-
* It is an Event from the parent Conversation (`event.identifier`) with the
|
|
7812
|
-
* Actor and grants of the parent's Turn, and the `spawnAgent` or
|
|
7813
|
-
* `messageAgent` tool call that sent it. Its text is the raw task. `fork`
|
|
7814
|
-
* marks the task of a fork spawn.
|
|
7815
|
-
*/
|
|
7816
|
-
const parentMessageSchema = z.object({
|
|
7817
|
-
actor: actorSchema,
|
|
7818
|
-
credentialContext: credentialContextSchema.optional(),
|
|
7819
|
-
event: z.object({
|
|
7820
|
-
eventType: z.literal(AGENT_PARENT_MESSAGE_EVENT_TYPE),
|
|
7821
|
-
identifier: z.string().min(1),
|
|
7822
|
-
namespace: z.literal(AGENT_INVOCATION_EVENT_NAMESPACE)
|
|
7823
|
-
}),
|
|
7824
|
-
fork: z.literal(true).optional(),
|
|
7825
|
-
kind: z.literal("event"),
|
|
7826
|
-
parentToolCallId: z.string().min(1)
|
|
7827
|
-
});
|
|
7828
|
-
/**
|
|
7829
|
-
* Return the author id of every parent message from one parent. It matches
|
|
7830
|
-
* no other input, so a parent message never shares a Turn with another
|
|
7831
|
-
* sender's input.
|
|
7832
|
-
*/
|
|
7833
|
-
function parentMessageAuthorId(parentConversationId) {
|
|
7834
|
-
return `parent-agent:${parentConversationId}`;
|
|
7835
|
-
}
|
|
7836
|
-
/**
|
|
7837
|
-
* Read the parent message that one mailbox input is, if it is one. Check its
|
|
7838
|
-
* sender with `isFromStoredParent` before it gets any authority.
|
|
7839
|
-
*/
|
|
7840
|
-
function readParentMessage(message) {
|
|
7841
|
-
if (message.source !== "event") return;
|
|
7842
|
-
const parsed = parentMessageSchema.safeParse(message.input.metadata);
|
|
7843
|
-
return parsed.success ? parsed.data : void 0;
|
|
7844
|
-
}
|
|
7845
|
-
/**
|
|
7846
|
-
* Return whether a parent message names the stored parent of the child that
|
|
7847
|
-
* received it, with that parent's author id. The caller drops another
|
|
7848
|
-
* message.
|
|
7849
|
-
*/
|
|
7850
|
-
async function isFromStoredParent(message, parentMessage) {
|
|
7851
|
-
return (message.input.authorId === parentMessageAuthorId(parentMessage.event.identifier) ? await getSqlExecutor().db().select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(eq(juniorConversations.conversationId, message.conversationId), eq(juniorConversations.parentConversationId, parentMessage.event.identifier))) : []).length > 0;
|
|
7852
|
-
}
|
|
7853
|
-
/**
|
|
7854
|
-
* Log a parent message that a child dropped: its sender check failed, or a
|
|
7855
|
-
* stop skipped it. Call it once, where the child drops the message.
|
|
7856
|
-
*/
|
|
7857
|
-
function logDroppedParentMessage(message, parentMessage) {
|
|
7858
|
-
logWarn("agent.parent_message.dropped", {
|
|
7859
|
-
"app.conversation_id": message.conversationId,
|
|
7860
|
-
"app.inbound_message_id": message.inboundMessageId,
|
|
7861
|
-
"app.parent_conversation_id": parentMessage.event.identifier
|
|
7862
|
-
});
|
|
7863
|
-
}
|
|
7864
|
-
/**
|
|
7865
|
-
* Render a parent message as the child model reads it, as an Agent
|
|
7866
|
-
* invocation renders its task.
|
|
7867
|
-
*/
|
|
7868
|
-
async function parentMessageText(message, parentMessage) {
|
|
7869
|
-
return agentInvocationInputText({
|
|
7870
|
-
agentType: (await readAgentConfig(message.conversationId))?.agentType,
|
|
7871
|
-
fork: parentMessage.fork,
|
|
7872
|
-
input: message.input.text,
|
|
7873
|
-
parentToolCallId: parentMessage.parentToolCallId
|
|
7874
|
-
});
|
|
7875
|
-
}
|
|
7876
|
-
/**
|
|
7877
|
-
* Return whether a saved transcript Message is a parent message. Only the
|
|
7878
|
-
* root Turn code saves one, after its sender check.
|
|
7879
|
-
*/
|
|
7880
|
-
function isParentMessageMeta(meta) {
|
|
7881
|
-
return meta?.eventNamespace === "junior" && meta.eventType === "agent.parent_message";
|
|
7882
|
-
}
|
|
7883
|
-
/**
|
|
7884
|
-
* Read when the root Turn code last saved a parent message to one child, or
|
|
7885
|
-
* undefined when it saved none.
|
|
7886
|
-
*/
|
|
7887
|
-
async function readLastParentMessageAtMs(conversationId) {
|
|
7888
|
-
const payload = juniorConversationEvents.payload;
|
|
7889
|
-
const [row] = await getSqlExecutor().db().select({ createdAt: juniorConversationEvents.createdAt }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "message"), sql`${payload}->'meta'->>'eventNamespace' = ${AGENT_INVOCATION_EVENT_NAMESPACE}`, sql`${payload}->'meta'->>'eventType' = ${AGENT_PARENT_MESSAGE_EVENT_TYPE}`)).orderBy(desc(juniorConversationEvents.createdAt)).limit(1);
|
|
7890
|
-
return row?.createdAt.getTime();
|
|
7891
|
-
}
|
|
7892
|
-
/**
|
|
7893
|
-
* Commit the parent's history for the first Turn of a fork child, before the
|
|
7894
|
-
* Turn starts. `inputs` passed the sender check.
|
|
7895
|
-
*/
|
|
7896
|
-
async function commitParentMessageFork(args) {
|
|
7897
|
-
const parentMessage = args.inputs.map(readParentMessage).find((input) => input !== void 0);
|
|
7898
|
-
if (parentMessage?.fork) await commitForkHistory({
|
|
7899
|
-
childConversationId: args.conversationId,
|
|
7900
|
-
parentConversationId: parentMessage.event.identifier,
|
|
7901
|
-
parentToolCallId: parentMessage.parentToolCallId
|
|
7902
|
-
});
|
|
7903
|
-
}
|
|
7904
|
-
/**
|
|
7905
|
-
* Apply the agent config of a child agent to one of its Turns on the root
|
|
7906
|
-
* Turn code. Every Turn keeps the reasoning level. A parent message is the
|
|
7907
|
-
* child's instruction, as on an Agent invocation, also when its Turn resumes
|
|
7908
|
-
* (`savedParentMessage`). `inputs` passed the sender check.
|
|
7909
|
-
*/
|
|
7910
|
-
async function childAgentTurnOptions(args) {
|
|
7911
|
-
const options = await readAgentConfig(args.conversationId);
|
|
7912
|
-
return {
|
|
7913
|
-
instruction: args.inputs.map(readParentMessage).find((input) => input !== void 0) || args.savedParentMessage ? { provenance: agentInstructionProvenance } : {},
|
|
7914
|
-
run: options?.reasoningLevel ? { reasoning: options.reasoningLevel } : {}
|
|
7915
|
-
};
|
|
7916
|
-
}
|
|
7917
|
-
// src/chat/agent-invocations/child-input.ts
|
|
7918
|
-
/**
|
|
7919
|
-
* Read the sender that one result, reply, or message Event names: the
|
|
7920
|
-
* finished child work for a result, or the sender for a reply or message.
|
|
7921
|
-
*/
|
|
7922
|
-
function childAgentInput(message) {
|
|
7923
|
-
const metadata = message.input.metadata;
|
|
7924
|
-
if (!isEventMailboxMetadata(metadata) || metadata.event.namespace !== "junior") return;
|
|
7925
|
-
if (metadata.event.eventType === "agent.message") return {
|
|
7926
|
-
kind: "message",
|
|
7927
|
-
senderId: metadata.event.identifier
|
|
7928
|
-
};
|
|
7929
|
-
if (metadata.event.eventType === "agent.reply") return {
|
|
7930
|
-
kind: "reply",
|
|
7931
|
-
senderId: metadata.event.identifier
|
|
7932
|
-
};
|
|
7933
|
-
return isAgentInvocationResultEventType(metadata.event.eventType) ? {
|
|
7934
|
-
kind: "result",
|
|
7935
|
-
senderId: metadata.event.identifier
|
|
7936
|
-
} : void 0;
|
|
7937
|
-
}
|
|
7938
|
-
/**
|
|
7939
|
-
* Route one input to a Conversation. Routing, the stop skips, and the child
|
|
7940
|
-
* agent status all read this, so they agree on which input starts work.
|
|
7941
|
-
*
|
|
7942
|
-
* A parent task or message goes to its agent invocation. `latest` is the
|
|
7943
|
-
* Conversation's newest agent invocation; a root has none. A parent message
|
|
7944
|
-
* that no Agent invocation names is dropped when it does not come from the
|
|
7945
|
-
* stored parent. With an open Agent invocation, that parent message, a Watch
|
|
7946
|
-
* Event, and input from a child agent go to an agent invocation, and so do a
|
|
7947
|
-
* result, and input to a child that waits for its own child agents
|
|
7948
|
-
* (`replaced`). A stopped child drops input from its own child agents, also
|
|
7949
|
-
* input sent before the stop. A stopped Conversation never routes automated
|
|
7950
|
-
* input: `enqueueAutomatedInput` and the stop hold it first.
|
|
7951
|
-
*
|
|
7952
|
-
* TODO(dcramer): Drop the agent invocation route with the legacy child worker
|
|
7953
|
-
* (#3060 step 7).
|
|
7954
|
-
*/
|
|
7955
|
-
async function routeChildInput(message, latest) {
|
|
7956
|
-
if (isPersonInput(message.source)) return "Conversation loop";
|
|
7957
|
-
if (isAgentInvocationInput(message)) return "agent invocation";
|
|
7958
|
-
const open = latest !== void 0 && !isTerminalAgentInvocation(latest);
|
|
7959
|
-
const parentMessage = readParentMessage(message);
|
|
7960
|
-
if (parentMessage) {
|
|
7961
|
-
if (!await isFromStoredParent(message, parentMessage)) return "dropped";
|
|
7962
|
-
return open ? "agent invocation" : "Conversation loop";
|
|
7963
|
-
}
|
|
7964
|
-
const input = childAgentInput(message);
|
|
7965
|
-
if (!input) return open && isEventMailboxMetadata(message.input.metadata) ? "agent invocation" : "Conversation loop";
|
|
7966
|
-
if (latest && isStoppedAgentInvocation(latest)) return "dropped";
|
|
7967
|
-
if (await isSkippedAgentResult(input, message)) return "dropped";
|
|
7968
|
-
if (latest && (open || input.kind === "result" || latest.parentMailboxStatus === "replaced")) return "agent invocation";
|
|
7969
|
-
return "Conversation loop";
|
|
7970
|
-
}
|
|
7971
|
-
/**
|
|
7972
|
-
* Return whether a stop skipped this result or reply, so it starts no work.
|
|
7973
|
-
* A message that a child sent before its stop is still delivered. A reply
|
|
7974
|
-
* that an agent invocation sent names its own work, so it is dropped with
|
|
7975
|
-
* that work. A reply from a Turn on the Conversation loop names no work of
|
|
7976
|
-
* its own: the stop drops it from the parent's mailbox. While the sending
|
|
7977
|
-
* child is stopped, a reply that it sent after the stop is also dropped.
|
|
7978
|
-
*/
|
|
7979
|
-
async function isSkippedAgentResult(input, message) {
|
|
7980
|
-
if (input.kind === "message") return false;
|
|
7981
|
-
const { invocation, sender } = await getChildAgentInputSender(message, input);
|
|
7982
|
-
const skipped = invocation !== void 0 && isTerminalAgentInvocation(invocation) && invocation.parentMailboxStatus === "skipped";
|
|
7983
|
-
if (input.kind === "result") return skipped;
|
|
7984
|
-
if (skipped) {
|
|
7985
|
-
const fields = await readChildMessageSender(message);
|
|
7986
|
-
if (!fields || ownAgentInvocation(fields)) return true;
|
|
7987
|
-
}
|
|
7988
|
-
const senderStoppedAtMs = await getConversationStoppedAtMs(sender.childConversationId);
|
|
7989
|
-
return senderStoppedAtMs !== void 0 && message.createdAtMs >= senderStoppedAtMs;
|
|
7990
|
-
}
|
|
7991
|
-
/**
|
|
7992
|
-
* Read the sender of one child Conversation that no Agent invocation names,
|
|
7993
|
-
* from its parent edge and its binding. A Conversation without a parent has
|
|
7994
|
-
* none.
|
|
7995
|
-
*/
|
|
7996
|
-
async function readChildConversationSender(childConversationId) {
|
|
7997
|
-
const parent = alias(juniorConversations, "parent");
|
|
7998
|
-
const [row] = await getSqlExecutor().db().select({
|
|
7999
|
-
agentName: juniorAgentBindings.name,
|
|
8000
|
-
parentConversationId: parent.conversationId,
|
|
8001
|
-
title: juniorConversations.title
|
|
8002
|
-
}).from(juniorConversations).innerJoin(parent, eq(parent.conversationId, juniorConversations.parentConversationId)).leftJoin(juniorAgentBindings, eq(juniorAgentBindings.childConversationId, juniorConversations.conversationId)).where(eq(juniorConversations.conversationId, childConversationId));
|
|
8003
|
-
return row ? {
|
|
8004
|
-
...row.agentName ? { agentName: row.agentName } : void 0,
|
|
8005
|
-
childConversationId,
|
|
8006
|
-
parentConversationId: row.parentConversationId,
|
|
8007
|
-
...row.title ? { title: row.title } : void 0
|
|
8008
|
-
} : void 0;
|
|
8009
|
-
}
|
|
8010
|
-
/**
|
|
8011
|
-
* Read the sender of one result, reply, or message and check that it is a
|
|
8012
|
-
* child of the Conversation that received it. The Agent invocation that the
|
|
8013
|
-
* input names wins. A reply or message from a child that no Agent invocation
|
|
8014
|
-
* names comes from its child Conversation, and has no `invocation`.
|
|
8015
|
-
*/
|
|
8016
|
-
async function getChildAgentInputSender(message, input) {
|
|
8017
|
-
const invocation = await getAgentInvocation(input.senderId);
|
|
8018
|
-
const sender = invocation ? input.kind === "result" && !isTerminalAgentInvocation(invocation) ? void 0 : invocation : input.kind === "result" ? void 0 : await readChildConversationSender(input.senderId);
|
|
8019
|
-
if (!sender || sender.parentConversationId !== message.conversationId) throw new Error(`Agent invocation ${input.kind} ${input.senderId} does not belong to ${message.conversationId}`);
|
|
8020
|
-
return invocation ? {
|
|
8021
|
-
invocation,
|
|
8022
|
-
sender
|
|
8023
|
-
} : { sender };
|
|
8024
|
-
}
|
|
8025
|
-
// src/chat/agent-invocations/store.ts
|
|
8026
|
-
/** Statuses of a finished agent invocation. */
|
|
8027
|
-
const TERMINAL_AGENT_INVOCATION_STATUSES = [
|
|
8028
|
-
"blocked",
|
|
8029
|
-
"completed",
|
|
8030
|
-
"failed",
|
|
8031
|
-
"stopped"
|
|
8032
|
-
];
|
|
8033
|
-
/** Statuses of an agent invocation that owns its child's Turn. */
|
|
8034
|
-
const ACTIVE_AGENT_INVOCATION_STATUSES = ["running", "paused"];
|
|
8035
|
-
/** Statuses of an agent invocation that has not finished. */
|
|
8036
|
-
const NON_TERMINAL_AGENT_INVOCATION_STATUSES = [
|
|
8037
|
-
"pending",
|
|
8038
|
-
"running",
|
|
8039
|
-
"paused"
|
|
8040
|
-
];
|
|
8041
|
-
/** Parse one agent invocation row. */
|
|
8042
|
-
function invocationFromRow(row) {
|
|
8043
|
-
return agentInvocationSchema.parse({
|
|
8044
|
-
actor: row.actor,
|
|
8045
|
-
...row.agentName ? { agentName: row.agentName } : void 0,
|
|
8046
|
-
childConversationId: row.childConversationId,
|
|
8047
|
-
createdAtMs: row.createdAt.getTime(),
|
|
8048
|
-
...row.credentialContext ? { credentialContext: row.credentialContext } : void 0,
|
|
8049
|
-
destination: row.destination,
|
|
8050
|
-
...row.errorMessage !== null ? { errorMessage: row.errorMessage } : void 0,
|
|
8051
|
-
input: row.input,
|
|
8052
|
-
invocationId: row.invocationId,
|
|
8053
|
-
mailboxStatus: row.mailboxStatus,
|
|
8054
|
-
parentConversationId: row.parentConversationId,
|
|
8055
|
-
...row.parentMailboxStatus ? { parentMailboxStatus: row.parentMailboxStatus } : void 0,
|
|
8056
|
-
...row.parentToolCallId ? { parentToolCallId: row.parentToolCallId } : void 0,
|
|
8057
|
-
...row.agentType ? { agentType: row.agentType } : void 0,
|
|
8058
|
-
...row.fork ? { fork: true } : void 0,
|
|
8059
|
-
...row.reasoningLevel ? { reasoningLevel: row.reasoningLevel } : void 0,
|
|
8060
|
-
...row.result !== null ? { result: row.result } : void 0,
|
|
8061
|
-
source: row.source,
|
|
8062
|
-
status: row.status,
|
|
8063
|
-
...row.terminalAt ? { terminalAtMs: row.terminalAt.getTime() } : void 0,
|
|
8064
|
-
...row.title ? { title: row.title } : void 0,
|
|
8065
|
-
updatedAtMs: row.updatedAt.getTime()
|
|
8066
|
-
});
|
|
8067
|
-
}
|
|
8068
|
-
/** Read one durable agent invocation. */
|
|
8069
|
-
async function getAgentInvocation(invocationId) {
|
|
8070
|
-
const rows = await getSqlExecutor().db().select().from(juniorAgentInvocations).where(eq(juniorAgentInvocations.invocationId, invocationId));
|
|
8071
|
-
return rows[0] ? invocationFromRow(rows[0]) : void 0;
|
|
8072
|
-
}
|
|
8073
|
-
/** List the agent invocations of one child Conversation in the given statuses. */
|
|
8074
|
-
async function listAgentInvocationsForConversation(childConversationId, statuses) {
|
|
8075
|
-
return (await getSqlExecutor().db().select().from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.childConversationId, childConversationId), inArray(juniorAgentInvocations.status, [...statuses]))).orderBy(asc(juniorAgentInvocations.createdAt))).map(invocationFromRow);
|
|
8076
|
-
}
|
|
8077
|
-
/** Resolve the single invocation that may resume for one child conversation. */
|
|
8078
|
-
async function getActiveAgentInvocationForConversation(childConversationId) {
|
|
8079
|
-
const active = await listAgentInvocationsForConversation(childConversationId, ACTIVE_AGENT_INVOCATION_STATUSES);
|
|
8080
|
-
if (active.length > 1) throw new Error(`Child conversation ${childConversationId} has multiple active agent invocations`);
|
|
8081
|
-
return active[0];
|
|
8082
|
-
}
|
|
8083
|
-
/** Read the newest agent invocation of one child Conversation. */
|
|
8084
|
-
async function getLatestAgentInvocationForConversation(childConversationId) {
|
|
8085
|
-
const rows = await getSqlExecutor().db().select().from(juniorAgentInvocations).where(eq(juniorAgentInvocations.childConversationId, childConversationId)).orderBy(desc(juniorAgentInvocations.createdAt)).limit(1);
|
|
8086
|
-
return rows[0] ? invocationFromRow(rows[0]) : void 0;
|
|
8087
|
-
}
|
|
8088
|
-
/**
|
|
8089
|
-
* Read the name, agent type, fork flag, and newest task title of one child
|
|
8090
|
-
* Conversation, for labels. Agent invocations that give a nested result to
|
|
8091
|
-
* the child have no title, so an agent invocation with a title comes first.
|
|
8092
|
-
* Each agent invocation keeps the child's agent type, but only the one that
|
|
8093
|
-
* started a fork has `fork` set, so the flag reads every agent invocation.
|
|
8094
|
-
* A child that no Agent invocation names reads its binding, title, and
|
|
8095
|
-
* agent config.
|
|
8096
|
-
*/
|
|
8097
|
-
async function getChildAgentLabel(childConversationId) {
|
|
8098
|
-
const [row] = await getSqlExecutor().db().select({
|
|
8099
|
-
agentName: juniorAgentInvocations.agentName,
|
|
8100
|
-
agentType: juniorAgentInvocations.agentType,
|
|
8101
|
-
fork: sql`bool_or(${juniorAgentInvocations.fork}) over ()`,
|
|
8102
|
-
title: juniorAgentInvocations.title
|
|
8103
|
-
}).from(juniorAgentInvocations).where(eq(juniorAgentInvocations.childConversationId, childConversationId)).orderBy(sql`${juniorAgentInvocations.title} is null`, desc(juniorAgentInvocations.createdAt)).limit(1);
|
|
8104
|
-
if (row) return row;
|
|
8105
|
-
const [sender, options] = await Promise.all([readChildConversationSender(childConversationId), readAgentConfig(childConversationId)]);
|
|
8106
|
-
return sender && options ? {
|
|
8107
|
-
agentName: sender.agentName ?? null,
|
|
8108
|
-
agentType: options.agentType ?? null,
|
|
8109
|
-
fork: options.fork ?? false,
|
|
8110
|
-
title: sender.title ?? null
|
|
8111
|
-
} : void 0;
|
|
8112
|
-
}
|
|
8113
|
-
/**
|
|
8114
|
-
* List the open agent invocations that run on one Conversation or on its
|
|
8115
|
-
* child agents, oldest first. Open-work checks read this once and filter it.
|
|
8116
|
-
*/
|
|
8117
|
-
async function listOpenAgentInvocations(conversationId) {
|
|
8118
|
-
return (await getSqlExecutor().db().select().from(juniorAgentInvocations).where(and(or(eq(juniorAgentInvocations.childConversationId, conversationId), eq(juniorAgentInvocations.parentConversationId, conversationId)), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES))).orderBy(asc(juniorAgentInvocations.createdAt))).map(invocationFromRow);
|
|
8119
|
-
}
|
|
8120
|
-
/**
|
|
8121
|
-
* Return whether a terminal agent invocation sends its result to the parent.
|
|
8122
|
-
* A child's final response stays in its Conversation, and a `reply` that
|
|
8123
|
-
* reached the parent (one of `parentMessages`) answered for the Agent
|
|
8124
|
-
* invocation. A failure after that, such as a lost worker before the
|
|
8125
|
-
* Turn was saved, is not sent either.
|
|
8126
|
-
*/
|
|
8127
|
-
function sendsResultToParent(invocation, parentMessages) {
|
|
8128
|
-
const replied = hasAgentInvocationReply(parentMessages, invocation.invocationId);
|
|
8129
|
-
switch (invocation.status) {
|
|
8130
|
-
case "completed": return !replied && Boolean(invocation.result?.trim());
|
|
8131
|
-
case "failed": return !replied;
|
|
8132
|
-
default: return true;
|
|
8133
|
-
}
|
|
8134
|
-
}
|
|
8135
|
-
/**
|
|
8136
|
-
* Return whether a child Conversation has work that will start another agent
|
|
8137
|
-
* invocation on it: another open agent invocation, an open child agent, or a
|
|
8138
|
-
* child agent result that is sent but still waits in its mailbox. A child
|
|
8139
|
-
* agent that no Agent invocation names is open as `listAgents` shows it,
|
|
8140
|
-
* and its unread result or reply also waits.
|
|
8141
|
-
*/
|
|
8142
|
-
async function hasOpenChildWork(conversationId, exceptInvocationId) {
|
|
8143
|
-
if ((await listOpenAgentInvocations(conversationId)).some((row) => row.invocationId !== exceptInvocationId) || (await listOpenChildAgentsWithoutAgentInvocations(conversationId)).length > 0) return true;
|
|
8144
|
-
const work = await getConversationWorkState({ conversationId });
|
|
8145
|
-
if ((await readChildMessageSenders(work?.messages ?? [])).some((sender) => sender && !sender.agentInvocationId)) return true;
|
|
8146
|
-
const marked = await getSqlExecutor().db().select({
|
|
8147
|
-
invocationId: juniorAgentInvocations.invocationId,
|
|
8148
|
-
parentMailboxStatus: juniorAgentInvocations.parentMailboxStatus,
|
|
8149
|
-
result: juniorAgentInvocations.result,
|
|
8150
|
-
status: juniorAgentInvocations.status
|
|
8151
|
-
}).from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.parentConversationId, conversationId), inArray(juniorAgentInvocations.parentMailboxStatus, ["pending", "appended"])));
|
|
8152
|
-
if (marked.length === 0) return false;
|
|
8153
|
-
const unread = new Set(work?.messages.map((message) => message.inboundMessageId));
|
|
8154
|
-
const parentMessages = await listChildMessages(work?.execution.inboundMessageIds ?? [], work?.execution.messageSenders ?? {});
|
|
8155
|
-
return marked.some((row) => sendsResultToParent(row, parentMessages) && (row.parentMailboxStatus === "pending" || unread.has(getAgentInvocationResultMessageId(row.invocationId))));
|
|
8156
|
-
}
|
|
8157
|
-
/**
|
|
8158
|
-
* Return whether a child agent still works when its Turn sends a `reply`:
|
|
8159
|
-
* it has open child work, or a message from one of its own child agents
|
|
8160
|
-
* waits in its mailbox. That reply then goes to the parent as a message, not
|
|
8161
|
-
* as the child's result.
|
|
8162
|
-
*/
|
|
8163
|
-
async function childAgentStillWorks(conversationId, exceptInvocationId) {
|
|
8164
|
-
if (await hasOpenChildWork(conversationId, exceptInvocationId)) return true;
|
|
8165
|
-
const work = await getConversationWorkState({ conversationId });
|
|
8166
|
-
return (await readChildMessageSenders(work?.messages ?? [])).some((sender) => sender !== void 0);
|
|
8167
|
-
}
|
|
8168
|
-
/** List bounded invocation records whose mailbox append still needs repair. */
|
|
8169
|
-
async function listPendingAgentInvocationMailboxAppends(limit = 100) {
|
|
8170
|
-
return (await getSqlExecutor().db().select().from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.mailboxStatus, "pending"), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES))).orderBy(asc(juniorAgentInvocations.createdAt)).limit(limit)).map(invocationFromRow);
|
|
8171
|
-
}
|
|
8172
|
-
/** List terminal agent invocation results that still need a parent mailbox append. */
|
|
8173
|
-
async function listPendingAgentInvocationResults(limit = 100) {
|
|
8174
|
-
return (await getSqlExecutor().db().select().from(juniorAgentInvocations).where(eq(juniorAgentInvocations.parentMailboxStatus, "pending")).orderBy(asc(juniorAgentInvocations.terminalAt)).limit(limit)).map(invocationFromRow).filter(isTerminalAgentInvocation);
|
|
8175
|
-
}
|
|
8176
|
-
/**
|
|
8177
|
-
* Send a `replaced` result to the parent now. A stop ended the open work of
|
|
8178
|
-
* the child, so no later agent invocation sends the report.
|
|
8179
|
-
*/
|
|
8180
|
-
async function reportReplacedAgentInvocation(invocationId, nowMs = Date.now()) {
|
|
8181
|
-
await getSqlExecutor().db().update(juniorAgentInvocations).set({
|
|
8182
|
-
parentMailboxStatus: "pending",
|
|
8183
|
-
updatedAt: new Date(nowMs)
|
|
8184
|
-
}).where(and(eq(juniorAgentInvocations.invocationId, invocationId), eq(juniorAgentInvocations.parentMailboxStatus, "replaced")));
|
|
8185
|
-
return await getAgentInvocation(invocationId);
|
|
8186
|
-
}
|
|
8187
|
-
/**
|
|
8188
|
-
* Send the `replaced` result of a child Conversation when its open child work
|
|
8189
|
-
* ended and sent it nothing, such as a helper that ended with `noReply`. No
|
|
8190
|
-
* later agent invocation of the child would send the report. Input from its
|
|
8191
|
-
* own child agents that still waits in its mailbox starts one, so that one
|
|
8192
|
-
* reports instead.
|
|
8193
|
-
*/
|
|
8194
|
-
async function reportReplacedWithoutOpenWork(conversationId, nowMs = Date.now()) {
|
|
8195
|
-
const latest = await getLatestAgentInvocationForConversation(conversationId);
|
|
8196
|
-
if (!latest || !isTerminalAgentInvocation(latest) || latest.parentMailboxStatus !== "replaced" || await hasOpenChildWork(latest.childConversationId, latest.invocationId)) return;
|
|
8197
|
-
if ((await getConversationWorkState({ conversationId }))?.messages.some(isChildAgentInputMessage)) return;
|
|
8198
|
-
return await reportReplacedAgentInvocation(latest.invocationId, nowMs);
|
|
8199
|
-
}
|
|
8200
|
-
function isChildAgentInputMessage(message) {
|
|
8201
|
-
const metadata = message.input.metadata;
|
|
8202
|
-
return isEventMailboxMetadata(metadata) && metadata.event.namespace === "junior" && metadata.event.eventType !== "agent.parent_message";
|
|
8203
|
-
}
|
|
8204
|
-
/** Record that one terminal result is in its parent mailbox. */
|
|
8205
|
-
async function markAgentInvocationParentMailboxAppended(invocationId, nowMs = Date.now()) {
|
|
8206
|
-
await getSqlExecutor().db().update(juniorAgentInvocations).set({
|
|
8207
|
-
parentMailboxStatus: "appended",
|
|
8208
|
-
updatedAt: new Date(nowMs)
|
|
8209
|
-
}).where(and(eq(juniorAgentInvocations.invocationId, invocationId), eq(juniorAgentInvocations.parentMailboxStatus, "pending")));
|
|
8210
|
-
}
|
|
8211
|
-
/** Record that the invocation's idempotent mailbox append completed. */
|
|
8212
|
-
async function markAgentInvocationMailboxAppended(invocationId, nowMs = Date.now()) {
|
|
8213
|
-
await getSqlExecutor().db().update(juniorAgentInvocations).set({
|
|
8214
|
-
mailboxStatus: "appended",
|
|
8215
|
-
updatedAt: new Date(nowMs)
|
|
8216
|
-
}).where(eq(juniorAgentInvocations.invocationId, invocationId));
|
|
8217
|
-
}
|
|
8218
|
-
/** Mark one non-terminal invocation as actively executing. */
|
|
8219
|
-
async function markAgentInvocationRunning(invocationId, nowMs = Date.now()) {
|
|
8220
|
-
await getSqlExecutor().db().update(juniorAgentInvocations).set({
|
|
8221
|
-
status: "running",
|
|
8222
|
-
updatedAt: new Date(nowMs)
|
|
8223
|
-
}).where(and(eq(juniorAgentInvocations.invocationId, invocationId), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES)));
|
|
8224
|
-
return await getAgentInvocation(invocationId);
|
|
8225
|
-
}
|
|
8226
|
-
/** Mark one invocation as waiting for another shared execution slice. */
|
|
8227
|
-
async function markAgentInvocationPaused(invocationId, nowMs = Date.now()) {
|
|
8228
|
-
await getSqlExecutor().db().update(juniorAgentInvocations).set({
|
|
8229
|
-
status: "paused",
|
|
8230
|
-
updatedAt: new Date(nowMs)
|
|
8231
|
-
}).where(and(eq(juniorAgentInvocations.invocationId, invocationId), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES)));
|
|
8232
|
-
}
|
|
8233
|
-
/**
|
|
8234
|
-
* Persist one terminal invocation result without overwriting an earlier
|
|
8235
|
-
* result. The same write marks the result for the parent mailbox. If the
|
|
8236
|
-
* child still has open work, the result is `replaced`: the parent gets one
|
|
8237
|
-
* report, from the agent invocation that finishes the child's work.
|
|
8238
|
-
* `reportNow` sends the result even then, when that open work does not
|
|
8239
|
-
* continue this task.
|
|
8240
|
-
*/
|
|
8241
|
-
async function completeAgentInvocation(args) {
|
|
8242
|
-
const nowMs = args.nowMs ?? Date.now();
|
|
8243
|
-
const current = await getAgentInvocation(args.invocationId);
|
|
8244
|
-
if (!current || isTerminalAgentInvocation(current)) return current;
|
|
8245
|
-
const parentMailboxStatus = !args.reportNow && args.status !== "stopped" && await hasOpenChildWork(current.childConversationId, current.invocationId) ? "replaced" : "pending";
|
|
8246
|
-
await getSqlExecutor().db().update(juniorAgentInvocations).set({
|
|
8247
|
-
status: args.status,
|
|
8248
|
-
result: args.status === "completed" ? args.result : null,
|
|
8249
|
-
errorMessage: args.status === "completed" ? null : args.errorMessage,
|
|
8250
|
-
parentMailboxStatus,
|
|
8251
|
-
terminalAt: new Date(nowMs),
|
|
8252
|
-
updatedAt: new Date(nowMs)
|
|
8253
|
-
}).where(and(eq(juniorAgentInvocations.invocationId, args.invocationId), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES)));
|
|
8254
|
-
return await getAgentInvocation(args.invocationId);
|
|
8255
|
-
}
|
|
8256
|
-
/**
|
|
8257
|
-
* End a pending agent invocation whose input the running agent invocation of
|
|
8258
|
-
* the same child read as a steering message. The running agent invocation
|
|
8259
|
-
* reports for both, so this one is never sent to the parent.
|
|
8260
|
-
*/
|
|
8261
|
-
async function markAgentInvocationSteered(invocationId, nowMs = Date.now()) {
|
|
8262
|
-
await getSqlExecutor().db().update(juniorAgentInvocations).set({
|
|
8263
|
-
status: "completed",
|
|
8264
|
-
result: "",
|
|
8265
|
-
parentMailboxStatus: "steered",
|
|
8266
|
-
terminalAt: new Date(nowMs),
|
|
8267
|
-
updatedAt: new Date(nowMs)
|
|
8268
|
-
}).where(and(eq(juniorAgentInvocations.invocationId, invocationId), eq(juniorAgentInvocations.status, "pending")));
|
|
8269
|
-
return await getAgentInvocation(invocationId);
|
|
8270
|
-
}
|
|
8271
|
-
/** Return whether an agent invocation has finished. */
|
|
8272
|
-
function isTerminalAgentInvocation(invocation) {
|
|
8273
|
-
return TERMINAL_AGENT_INVOCATION_STATUSES.includes(invocation.status);
|
|
8274
|
-
}
|
|
8275
|
-
/**
|
|
8276
|
-
* Return whether the newest agent invocation of a child shows a stop. A tree
|
|
8277
|
-
* stop leaves a `replaced` agent invocation with its finished status and
|
|
8278
|
-
* marks it `skipped`, so that also means stopped.
|
|
8279
|
-
*/
|
|
8280
|
-
function isStoppedAgentInvocation(invocation) {
|
|
8281
|
-
return invocation.status === "stopped" || isTerminalAgentInvocation(invocation) && invocation.parentMailboxStatus === "skipped";
|
|
8282
|
-
}
|
|
8283
|
-
// src/chat/agent-invocations/list.ts
|
|
8284
|
-
function isChildAgentResult(status) {
|
|
8285
|
-
return CHILD_AGENT_RESULTS.includes(status);
|
|
8286
|
-
}
|
|
8287
|
-
const childAgentKindSchema = z.enum(CHILD_AGENT_KINDS);
|
|
8288
|
-
/** Bound the agent invocations that one child agent listing reads. */
|
|
8289
|
-
const CHILD_AGENT_LIST_INVOCATION_LIMIT = 200;
|
|
8290
|
-
/** Return whether a child's session stopped after its latest agent invocation. */
|
|
8291
|
-
function isChildAgentSessionStopped(latest, stoppedAtMs) {
|
|
8292
|
-
return stoppedAtMs !== void 0 && stoppedAtMs >= latest.createdAtMs;
|
|
8293
|
-
}
|
|
8294
|
-
/** Return the child state that one child's agent invocations show. */
|
|
8295
|
-
function childAgentFromInvocations(invocations, resultInvocationIds, facts) {
|
|
8296
|
-
const { stoppedAtMs } = facts;
|
|
8297
|
-
const latest = invocations[0];
|
|
8298
|
-
let current = invocations.find((invocation) => !isTerminalAgentInvocation(invocation) || invocation.parentMailboxStatus !== "steered") ?? latest;
|
|
8299
|
-
for (const invocation of invocations) if (!isTerminalAgentInvocation(invocation)) current = invocation;
|
|
8300
|
-
const tasks = invocations.filter((invocation) => invocation.source.kind === "agent_invocation" && !resultInvocationIds.has(invocation.invocationId));
|
|
8301
|
-
const task = tasks.find((invocation) => invocation.parentToolCallId) ?? tasks[0] ?? invocations[invocations.length - 1];
|
|
8302
|
-
const terminal = isTerminalAgentInvocation(current) ? current : void 0;
|
|
8303
|
-
const lastResult = invocations.filter(isTerminalAgentInvocation).filter((invocation) => invocation.parentMailboxStatus !== "replaced" && invocation.parentMailboxStatus !== "skipped" && invocation.parentMailboxStatus !== "steered").map((invocation) => invocation.status).find(isChildAgentResult);
|
|
8304
|
-
return {
|
|
8305
|
-
...latest.agentName ? { agentName: latest.agentName } : void 0,
|
|
8306
|
-
...facts.archivedAtMs !== void 0 ? { archivedAtMs: facts.archivedAtMs } : void 0,
|
|
8307
|
-
childConversationId: latest.childConversationId,
|
|
8308
|
-
...terminal && terminal.status !== "completed" ? { errorMessage: terminal.errorMessage } : void 0,
|
|
8309
|
-
kind: facts.kind,
|
|
8310
|
-
...lastResult ? { lastResult } : void 0,
|
|
8311
|
-
status: isChildAgentSessionStopped(latest, stoppedAtMs) ? "stopped" : terminal && facts.onConversationLoop ? "running" : terminal?.parentMailboxStatus === "replaced" ? "pending" : terminal?.parentMailboxStatus === "skipped" ? "stopped" : current.status,
|
|
8312
|
-
task: task.input,
|
|
8313
|
-
...task.title ? { title: task.title } : void 0,
|
|
8314
|
-
updatedAtMs: Math.max(...invocations.map((invocation) => invocation.updatedAtMs))
|
|
8315
|
-
};
|
|
8316
|
-
}
|
|
8317
|
-
/**
|
|
8318
|
-
* List the direct child agents of one parent Conversation, with the newest
|
|
8319
|
-
* activity first. The state comes from SQL agent invocation records, not from
|
|
8320
|
-
* model output. A child that no agent invocation names shows the state of
|
|
8321
|
-
* its Turns and mailbox.
|
|
8322
|
-
*/
|
|
8323
|
-
async function listChildAgents(parentConversationId) {
|
|
8324
|
-
const [withInvocations, withoutInvocations] = await Promise.all([listChildAgentsFromInvocations(parentConversationId), listChildAgentsWithoutAgentInvocations(parentConversationId)]);
|
|
8325
|
-
return [...withInvocations, ...withoutInvocations].sort((left, right) => right.updatedAtMs - left.updatedAtMs);
|
|
8326
|
-
}
|
|
8327
|
-
async function listChildAgentsFromInvocations(parentConversationId) {
|
|
8328
|
-
const db = getSqlExecutor().db();
|
|
8329
|
-
const rows = await db.select().from(juniorAgentInvocations).where(eq(juniorAgentInvocations.parentConversationId, parentConversationId)).orderBy(desc(juniorAgentInvocations.createdAt)).limit(CHILD_AGENT_LIST_INVOCATION_LIMIT);
|
|
8330
|
-
if (rows.length === 0) return [];
|
|
8331
|
-
const byChild = /* @__PURE__ */ new Map();
|
|
8332
|
-
for (const invocation of rows.map(invocationFromRow)) {
|
|
8333
|
-
const invocations = byChild.get(invocation.childConversationId) ?? [];
|
|
8334
|
-
invocations.push(invocation);
|
|
8335
|
-
byChild.set(invocation.childConversationId, invocations);
|
|
8336
|
-
}
|
|
8337
|
-
const grandchildren = await db.select({ invocationId: juniorAgentInvocations.invocationId }).from(juniorAgentInvocations).where(inArray(juniorAgentInvocations.parentConversationId, [...byChild.keys()]));
|
|
8338
|
-
const resultInvocationIds = new Set(grandchildren.map((row) => getAgentInvocationIdForResult(row.invocationId)));
|
|
8339
|
-
const conversations = await db.select({
|
|
8340
|
-
archivedAt: juniorConversations.archivedAt,
|
|
8341
|
-
conversationId: juniorConversations.conversationId,
|
|
8342
|
-
executionStatus: juniorConversations.executionStatus,
|
|
8343
|
-
kind: juniorConversations.kind,
|
|
8344
|
-
parentConversationId: juniorConversations.parentConversationId,
|
|
8345
|
-
stoppedAt: juniorConversations.stoppedAt
|
|
8346
|
-
}).from(juniorConversations).where(inArray(juniorConversations.conversationId, [...byChild.keys()]));
|
|
8347
|
-
const active = conversations.filter((row) => row.executionStatus === "pending" || row.executionStatus === "running" || row.executionStatus === "paused");
|
|
8348
|
-
const activeIds = active.map((row) => row.conversationId);
|
|
8349
|
-
const [workStates, mailboxTurnSources] = await Promise.all([getConversationWorkStates(activeIds), listActiveMailboxTurnSources(activeIds)]);
|
|
8350
|
-
const onConversationLoop = new Set((await mapBounded(active, async (row) => await runsOnConversationLoop(conversationKindFromRow(row), byChild.get(row.conversationId)[0], workStates.get(row.conversationId)?.execution.pendingMessages ?? [], mailboxTurnSources.get(row.conversationId) ?? []) ? row.conversationId : void 0)).filter((id) => id !== void 0));
|
|
8351
|
-
const factsByChild = new Map(conversations.map((row) => [row.conversationId, {
|
|
8352
|
-
...row.archivedAt ? { archivedAtMs: row.archivedAt.getTime() } : void 0,
|
|
8353
|
-
kind: conversationKindFromRow(row) === "thread" ? "thread" : "task",
|
|
8354
|
-
...row.stoppedAt ? { stoppedAtMs: row.stoppedAt.getTime() } : void 0,
|
|
8355
|
-
onConversationLoop: onConversationLoop.has(row.conversationId)
|
|
8356
|
-
}]));
|
|
8357
|
-
return [...byChild.entries()].map(([childConversationId, invocations]) => childAgentFromInvocations(invocations, resultInvocationIds, factsByChild.get(childConversationId) ?? { kind: "task" }));
|
|
8358
|
-
}
|
|
8359
|
-
/**
|
|
8360
|
-
* List the ids of the child agents of one parent that no agent invocation
|
|
8361
|
-
* names and that have open work.
|
|
8362
|
-
*/
|
|
8363
|
-
async function listOpenChildAgentsWithoutAgentInvocations(parentConversationId) {
|
|
8364
|
-
return (await listChildAgentsWithoutAgentInvocations(parentConversationId)).filter((child) => NON_TERMINAL_AGENT_INVOCATION_STATUSES.includes(child.status)).map((child) => child.childConversationId);
|
|
8365
|
-
}
|
|
8366
|
-
/**
|
|
8367
|
-
* List the child agents of one parent that no agent invocation names. Each
|
|
8368
|
-
* stores its agent config, so older children of a parent, such as ones
|
|
8369
|
-
* that a removed feature created, are not listed. A child is `running` while
|
|
8370
|
-
* a Turn or mailbox input that answers its parent is open, and is `failed`
|
|
8371
|
-
* when its last Turn failed.
|
|
8372
|
-
*
|
|
8373
|
-
* TODO(dcramer): Make this the only listing when #3060 step 7 drops the
|
|
8374
|
-
* agent invocation table.
|
|
8375
|
-
*/
|
|
8376
|
-
async function listChildAgentsWithoutAgentInvocations(parentConversationId) {
|
|
8377
|
-
const db = getSqlExecutor().db();
|
|
8378
|
-
const rows = await db.select({
|
|
8379
|
-
agentName: juniorAgentBindings.name,
|
|
8380
|
-
archivedAt: juniorConversations.archivedAt,
|
|
8381
|
-
conversationId: juniorConversations.conversationId,
|
|
8382
|
-
executionStatus: juniorConversations.executionStatus,
|
|
8383
|
-
executionUpdatedAt: juniorConversations.executionUpdatedAt,
|
|
8384
|
-
kind: juniorConversations.kind,
|
|
8385
|
-
parentConversationId: juniorConversations.parentConversationId,
|
|
8386
|
-
stoppedAt: juniorConversations.stoppedAt,
|
|
8387
|
-
title: juniorConversations.title,
|
|
8388
|
-
updatedAt: juniorConversations.updatedAt
|
|
8389
|
-
}).from(juniorConversations).leftJoin(juniorAgentBindings, eq(juniorAgentBindings.childConversationId, juniorConversations.conversationId)).where(and(eq(juniorConversations.parentConversationId, parentConversationId), isNotNull(juniorConversations.agentConfig), notExists(db.select({ invocationId: juniorAgentInvocations.invocationId }).from(juniorAgentInvocations).where(eq(juniorAgentInvocations.childConversationId, juniorConversations.conversationId))))).limit(CHILD_AGENT_LIST_INVOCATION_LIMIT);
|
|
8390
|
-
const ids = rows.map((row) => row.conversationId);
|
|
8391
|
-
const [workStates, mailboxTurnSources] = await Promise.all([getConversationWorkStates(ids), listActiveMailboxTurnSources(ids)]);
|
|
8392
|
-
const limit = pLimit(8);
|
|
8393
|
-
return await Promise.all(rows.map(async (row) => {
|
|
8394
|
-
const kind = childAgentKindSchema.parse(row.kind);
|
|
8395
|
-
const stoppedAtMs = row.stoppedAt?.getTime();
|
|
8396
|
-
const running = stoppedAtMs === void 0 && await limit(() => runsOnConversationLoop(kind, void 0, workStates.get(row.conversationId)?.execution.pendingMessages ?? [], mailboxTurnSources.get(row.conversationId) ?? []));
|
|
8397
|
-
return {
|
|
8398
|
-
...row.agentName ? { agentName: row.agentName } : void 0,
|
|
8399
|
-
...row.archivedAt ? { archivedAtMs: row.archivedAt.getTime() } : void 0,
|
|
8400
|
-
childConversationId: row.conversationId,
|
|
8401
|
-
kind,
|
|
8402
|
-
status: stoppedAtMs !== void 0 ? "stopped" : running ? "running" : row.executionStatus === "failed" ? "failed" : "completed",
|
|
8403
|
-
task: row.title ?? "",
|
|
8404
|
-
...row.title ? { title: row.title } : void 0,
|
|
8405
|
-
updatedAtMs: (row.executionUpdatedAt ?? row.updatedAt).getTime()
|
|
8406
|
-
};
|
|
8407
|
-
}));
|
|
8408
|
-
}
|
|
8409
|
-
function answersParent(kind, source) {
|
|
8410
|
-
const personInput = isPersonInput(source);
|
|
8411
|
-
return !personInput && turnBehavior({
|
|
8412
|
-
kind,
|
|
8413
|
-
personInput
|
|
8414
|
-
}).gated;
|
|
8415
|
-
}
|
|
8416
|
-
/**
|
|
8417
|
-
* Return whether a child whose `latest` agent invocation ended has work on
|
|
8418
|
-
* the Conversation loop that will answer its parent: `pending` input that
|
|
8419
|
-
* waits in the mailbox until its Turn commits it, such as a Watch Event in
|
|
8420
|
-
* its debounce window, or an open mailbox Turn that answers.
|
|
8421
|
-
*/
|
|
8422
|
-
async function runsOnConversationLoop(kind, latest, pending, mailboxTurnSources) {
|
|
8423
|
-
for (const message of pending) if (answersParent(kind, message.source) && await routeChildInput(message, latest) === "Conversation loop") return true;
|
|
8424
|
-
return mailboxTurnSources.some((source) => answersParent(kind, source?.kind));
|
|
8425
|
-
}
|
|
8426
|
-
/**
|
|
8427
|
-
* List the ids of a child's open Turns on the Conversation loop. A Turn keeps
|
|
8428
|
-
* its input in the mailbox until it commits it, so before its first
|
|
8429
|
-
* checkpoint its id comes from its first input. Attempt selection can take
|
|
8430
|
-
* any pending input first, so each one gives a candidate id.
|
|
8431
|
-
*/
|
|
8432
|
-
async function listOpenLoopTurnIds(conversationId) {
|
|
8433
|
-
const [turns, work] = await Promise.all([listActiveMailboxTurns(conversationId), getConversationWorkState({ conversationId })]);
|
|
8434
|
-
return [...turns.map((turn) => turn.turnId), ...(work?.execution.pendingMessages ?? []).map((message) => buildDeterministicTurnId(message.inboundMessageId))];
|
|
8435
|
-
}
|
|
8436
|
-
async function listAnsweredLoopChildren(children, parentMessages) {
|
|
8437
|
-
if (children.length === 0 || parentMessages.length === 0) return [];
|
|
8438
|
-
return (await mapBounded(children, async ({ childConversationId }) => {
|
|
8439
|
-
const turnIds = await listOpenLoopTurnIds(childConversationId);
|
|
8440
|
-
return parentMessages.some(({ sender }) => sender.conversationId === childConversationId && turnIds.includes(sender.turnId)) ? childConversationId : void 0;
|
|
8441
|
-
})).filter((id) => id !== void 0);
|
|
8442
|
-
}
|
|
8443
|
-
/**
|
|
8444
|
-
* List the other child agents of one parent whose results have not reached
|
|
8445
|
-
* the parent yet. A child counts while it runs and after it finishes until its
|
|
8446
|
-
* result is appended to the parent mailbox. A running child whose `reply` is
|
|
8447
|
-
* already among `parentMessages`, the child replies and results that reached
|
|
8448
|
-
* the parent's mailbox, has answered, so it does not count.
|
|
8449
|
-
*/
|
|
8450
|
-
async function listUnreportedSiblingAgents(parentConversationId, childConversationId, parentMessages) {
|
|
8451
|
-
const db = getSqlExecutor().db();
|
|
8452
|
-
const [children, pendingResults, openInvocations] = await Promise.all([
|
|
8453
|
-
listChildAgents(parentConversationId),
|
|
8454
|
-
db.select({
|
|
8455
|
-
childConversationId: juniorAgentInvocations.childConversationId,
|
|
8456
|
-
invocationId: juniorAgentInvocations.invocationId,
|
|
8457
|
-
result: juniorAgentInvocations.result,
|
|
8458
|
-
status: juniorAgentInvocations.status
|
|
8459
|
-
}).from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.parentConversationId, parentConversationId), eq(juniorAgentInvocations.parentMailboxStatus, "pending"))),
|
|
8460
|
-
db.select({
|
|
8461
|
-
childConversationId: juniorAgentInvocations.childConversationId,
|
|
8462
|
-
invocationId: juniorAgentInvocations.invocationId
|
|
8463
|
-
}).from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.parentConversationId, parentConversationId), inArray(juniorAgentInvocations.status, [...NON_TERMINAL_AGENT_INVOCATION_STATUSES])))
|
|
8464
|
-
]);
|
|
8465
|
-
const withPendingResult = new Set(pendingResults.filter((row) => sendsResultToParent(row, parentMessages)).map((row) => row.childConversationId));
|
|
8466
|
-
const unanswered = new Set(openInvocations.filter((row) => !hasAgentInvocationReply(parentMessages, row.invocationId)).map((row) => row.childConversationId));
|
|
8467
|
-
const answered = new Set(openInvocations.map((row) => row.childConversationId).filter((child) => !unanswered.has(child)));
|
|
8468
|
-
for (const child of await listAnsweredLoopChildren(children.filter((child) => child.status === "running" && !openInvocations.some((row) => row.childConversationId === child.childConversationId)), parentMessages)) answered.add(child);
|
|
8469
|
-
return children.filter((child) => child.childConversationId !== childConversationId && (NON_TERMINAL_AGENT_INVOCATION_STATUSES.includes(child.status) && !answered.has(child.childConversationId) || withPendingResult.has(child.childConversationId)));
|
|
8470
|
-
}
|
|
8471
|
-
/**
|
|
8472
|
-
* List every child agent below one Conversation, at any depth. A parent owns
|
|
8473
|
-
* the work of its child agents and of their child agents. The list never has
|
|
8474
|
-
* the Conversation itself, its parent, or a sibling.
|
|
8475
|
-
*/
|
|
8476
|
-
async function listDescendantAgents(conversationId) {
|
|
8477
|
-
return (await getSqlExecutor().db().select({
|
|
8478
|
-
conversationId: juniorConversations.conversationId,
|
|
8479
|
-
name: juniorAgentBindings.name
|
|
8480
|
-
}).from(juniorConversations).innerJoin(conversationSubtree([conversationId]), eq(conversationSubtreeColumns.conversationId, juniorConversations.conversationId)).leftJoin(juniorAgentBindings, eq(juniorAgentBindings.childConversationId, juniorConversations.conversationId)).where(ne(juniorConversations.conversationId, conversationId)).orderBy(juniorConversations.conversationId)).map((row) => ({
|
|
8481
|
-
conversationId: row.conversationId,
|
|
8482
|
-
...row.name ? { name: row.name } : void 0
|
|
8483
|
-
}));
|
|
8484
|
-
}
|
|
8485
|
-
/**
|
|
8486
|
-
* List the agents that one Conversation can see. A root Conversation sees
|
|
8487
|
-
* only its child agents. A child agent also sees itself, its parent, and the
|
|
8488
|
-
* other child agents of its parent.
|
|
8489
|
-
*/
|
|
8490
|
-
async function listAgentRelatives(input) {
|
|
8491
|
-
const { conversationId, parentConversationId } = input;
|
|
8492
|
-
const [children, family, parent] = await Promise.all([
|
|
8493
|
-
listChildAgents(conversationId),
|
|
8494
|
-
parentConversationId ? listChildAgents(parentConversationId) : [],
|
|
8495
|
-
parentConversationId ? getConversationStore().get({ conversationId: parentConversationId }) : void 0
|
|
8496
|
-
]);
|
|
8497
|
-
const self = family.find((agent) => agent.childConversationId === conversationId);
|
|
8498
|
-
return {
|
|
8499
|
-
children,
|
|
8500
|
-
...parent ? { parent: {
|
|
8501
|
-
conversationId: parent.conversationId,
|
|
8502
|
-
status: parent.execution.status,
|
|
8503
|
-
updatedAtMs: parent.execution.updatedAtMs ?? parent.updatedAtMs
|
|
8504
|
-
} } : void 0,
|
|
8505
|
-
...self ? { self } : void 0,
|
|
8506
|
-
siblings: family.filter((agent) => agent.childConversationId !== conversationId)
|
|
8507
|
-
};
|
|
8508
|
-
}
|
|
8509
5578
|
// src/chat/events/owned-watches.ts
|
|
8510
5579
|
/**
|
|
8511
5580
|
* Watch ownership for the watch tools. A Conversation owns its own watches and
|
|
@@ -9608,7 +6677,11 @@ function createArchiveAgentTool(conversationId) {
|
|
|
9608
6677
|
const MESSAGE_AGENT_TEXT_MAX_LENGTH = 8e3;
|
|
9609
6678
|
const messageAgentOutputSchema = juniorToolOutputSchema.extend({
|
|
9610
6679
|
conversation_id: z.string().min(1).describe("Target conversation ID"),
|
|
9611
|
-
delivery: z.enum([
|
|
6680
|
+
delivery: z.enum([
|
|
6681
|
+
"started",
|
|
6682
|
+
"queued",
|
|
6683
|
+
"noted"
|
|
6684
|
+
]).describe("started: the child agent starts work on the message now. queued: the target reads the message at its next step or after its current work. noted: this conversation is stopped, so the child agent got the message as a note that it sees when it next runs, and it started no work. Do not send it again.")
|
|
9612
6685
|
});
|
|
9613
6686
|
const messageAgentToolDefinition = zodToolDefinition({
|
|
9614
6687
|
description: `Send a message to your parent agent or to a child agent that this conversation started. Use it to give an existing child agent more work, an answer, or a correction, and to send your parent agent a finding or a question while you keep working. A message to a child continues its history. If the child is still working, it reads the message at its next step or after its current work. A child replies when it has something to report. Its reply arrives later as a new task in this conversation; do not wait or poll for it. Make sure people know what is going on, but post only updates that matter to them. A message to your parent does not end your task. A top-level agent (its conversation is not a child agent, such as a Slack thread) can also message another top-level agent. Both conversations must be public, or both must be private conversations in the same place, such as one private channel or DM. The target runs the message as its own task and sends no result. Use spawnAgent only to start a new child agent.`,
|
|
@@ -9646,6 +6719,7 @@ function createMessageAgentTool(messageAgent) {
|
|
|
9646
6719
|
});
|
|
9647
6720
|
} catch (error) {
|
|
9648
6721
|
if (error instanceof AgentMessageTargetError) throw new ToolInputError(`${error.message}. Use listAgents to find an agent.`, { cause: error });
|
|
6722
|
+
if (error instanceof AgentStoppedError) throw new ToolInputError(`${error.message}. Do not start more work. End this turn.`, { cause: error });
|
|
9649
6723
|
if (error instanceof AgentMessageQueueFullError) throw new ToolInputError(`${error.message}. Wait for its result, then send one message with everything it needs.`, { cause: error });
|
|
9650
6724
|
if (error instanceof AgentInvocationLimitError) throw new ToolInputError(`${error.message}. Wait for active children to finish before you give more work.`, { cause: error });
|
|
9651
6725
|
throw error;
|
|
@@ -9967,6 +7041,7 @@ function createSpawnAgentTool(spawnAgent, titleCost) {
|
|
|
9967
7041
|
} catch (error) {
|
|
9968
7042
|
if (error instanceof AgentNameInUseError) throw new ToolInputError(`${error.message}. Use messageAgent to give it more work, or choose a different name.`, { cause: error });
|
|
9969
7043
|
if (error instanceof AgentInvocationLimitError) throw new ToolInputError(`${error.message}. Wait for active children to finish before spawning more.`, { cause: error });
|
|
7044
|
+
if (error instanceof AgentStoppedError) throw new ToolInputError(`${error.message}. Do not start more work. End this turn.`, { cause: error });
|
|
9970
7045
|
if (error instanceof AgentDepthLimitError) throw new ToolInputError(`${error.message}. Do the work in this agent instead.`, { cause: error });
|
|
9971
7046
|
throw error;
|
|
9972
7047
|
}
|
|
@@ -10870,7 +7945,7 @@ function searchEventTypesToolDefinition(catalog) {
|
|
|
10870
7945
|
openWorldHint: false,
|
|
10871
7946
|
readOnlyHint: true
|
|
10872
7947
|
},
|
|
10873
|
-
description: "Search the event types currently enabled without creating anything. Use only when the user asks what events are supported or the required resource type or event name is unclear. Includes plugin resources and core Workspace snapshot events. namespaces gives the reach of each event. An event automation selects its events with match filters from the match_fields of its namespace. With reach \"all\", match can be left out to run for every resource. With { any_of }, match must set at least one of those filters. With reach \"resource\", only watchEvents can use the event. Use watchEvents for temporary updates in the current conversation; use createAutomation with an event trigger for durable automation.
|
|
7948
|
+
description: "Search the event types currently enabled without creating anything: the events watches and event automations can use. Use only when the user asks what events are supported or the required resource type or event name is unclear. Includes plugin resources and core Workspace snapshot events. namespaces gives the reach of each event. An event automation selects its events with match filters from the match_fields of its namespace. With reach \"all\", match can be left out to run for every resource. With { any_of }, match must set at least one of those filters. With reach \"resource\", only watchEvents can use the event. Use watchEvents for temporary updates in the current conversation; use createAutomation with an event trigger for durable automation. It does not list concrete resources.",
|
|
10874
7949
|
inputSchema: z.object({
|
|
10875
7950
|
query: z.string().nullable().describe("Optional terms matching a namespace, resource type, or event name. Resource types that match more terms come first. Empty lists all enabled event types.").optional(),
|
|
10876
7951
|
namespace: eventNamespaceSchema(catalog).nullable().describe("Optional enabled plugin namespace to search within.").optional(),
|
|
@@ -12393,13 +9468,13 @@ async function resolveWorkspaceSnapshot(params) {
|
|
|
12393
9468
|
if (!getSandboxProvider().errors.isTransient(error)) throw error;
|
|
12394
9469
|
advanced = true;
|
|
12395
9470
|
if (shouldStopForTimeLimit(current.shouldStop)) throw new WorkspaceSnapshotNotReadyError(workspace.name);
|
|
12396
|
-
await sleep
|
|
9471
|
+
await sleep(TRANSIENT_API_RETRY_MS, params.signal);
|
|
12397
9472
|
continue;
|
|
12398
9473
|
}
|
|
12399
9474
|
advanced = true;
|
|
12400
9475
|
if (snapshot) return snapshot;
|
|
12401
9476
|
if (shouldStopForTimeLimit(current.shouldStop)) throw new WorkspaceSnapshotNotReadyError(workspace.name);
|
|
12402
|
-
await sleep
|
|
9477
|
+
await sleep(WAIT_POLL_MS, params.signal);
|
|
12403
9478
|
}
|
|
12404
9479
|
}
|
|
12405
9480
|
// src/chat/sandbox/snapshot/job-runner.ts
|
|
@@ -15179,4 +12254,4 @@ async function runCacheWarmup(message) {
|
|
|
15179
12254
|
}, startedAtMs, warm);
|
|
15180
12255
|
}, attributes);
|
|
15181
12256
|
}
|
|
15182
|
-
export { createSpawnAgentTool as $,
|
|
12257
|
+
export { createSpawnAgentTool as $, createSearchInboxItemsTool as $n, validateAndApplyTextEdits as $t, createWorkspaceTool as A, deleteViewerTask as An, gapSegment as Ar, parseSlackMessageReference as At, createStopWatchingResourcesTool as B, readViewerAutomations as Bn, readSlackRawMessageContext as Bt, createSwitchWorkspaceTool as C, requireToolCaller as Cn, warmupTiming as Cr, setConversationSubscription as Ct, prepareWorkspaceSnapshot as D, automationEditor as Dn, MIN_WARMUP_PREFIX_TOKENS as Dr, createSlackThreadReadTool as Dt, requireReadyWorkspaceSnapshot as E, activateViewerAutomationVersion as En, MINUTE_MS as Er, throwApiError as Et, createWatchEventsTool as F, readConversationSourceTask as Fn, createSlackListAddItemsTool as Ft, bm25Saturation as G, automationCardStatus as Gn, createSlackCanvasWriteTool as Gt, createSearchConversationEventsTool as H, editEventAutomation as Hn, createSlackChannelJoinTool as Ht, createUserLookupTool as I, readViewerAutomationExecutions as In, createSlackConversationMessageSearchTool as It, createReadFileTool as J, findAutomationSkill as Jn, SLACK_TOOL_SOURCE as Jt, createSearchConversationsTool as K, AutomationEditError as Kn, createSlackCanvasReadTool as Kt, createUpdateUserCustomizationTool as L, readViewerAutomationRuns as Ln, createSlackConversationSearchChannelPort as Lt, createWebSearchTool as M, takeViewerAutomationAlertStep as Mn, createSlackListUpdateItemTool as Mt, createWebFetchTool as N, updateViewerAutomation as Nn, createSlackListGetItemsTool as Nt, createListWorkspacesTool as O, changeAutomationLifecycle as On, NO_REPLY_GAP_MS as Or, renderAttachmentText as Ot, createWatchTimerTool as P, ViewerTaskNotFoundError as Pn, createSlackListCreateTool as Pt, createStopAgentTool as Q, resolveTaskOutcomes as Qn, stripBom as Qt, createSubmitFeedbackTool as R, readViewerAutomationSummary as Rn, createSlackChannelListMessagesTool as Rt, createUpdateWorkspaceTool as S, requireToolAutomation as Sn, sendWarmup as Sr, inviteToConversation as St, processWorkspaceSnapshotJob as T, requireToolDestination as Tn, IDLE_HORIZON_MS as Tr, jsonResponse as Tt, bm25InverseDocumentFrequency as U, changedEventMatch as Un, resolveSlackChannelRef as Ut, createSearchEventTypesTool as V, editScheduledAutomation as Vn, resolveSlackChannelIdFromMessage as Vt, bm25NormalizedFrequency as W, requireEventAutomationTrigger as Wn, slackChannelRefParam as Wt, createBashTool as X, effectiveTaskOutcomes as Xn, detectLineEnding as Xt, createEditFileTool as Y, missingAutomationSkillReason as Yn, buildCompactDiff as Yt, createUpdateTodosTool as Z, moveTaskOutcomes as Zn, restoreLineEndings as Zt, CONTEXT_COMPACTION_PROMPT_NAME as _, newAutomationTask as _n, cacheTtlMs as _r, createReadConversationEventTool as _t, recordModelCall as a, createCanvas as an, idlePeriodOutcome as ar, createMessageAgentTool as at, coreToolSlots as b, automationToolContext as bn, connectedState as br, listOwnedWatches as bt, warmup_exports as c, createDeleteAutomationTool as cn, recordWarmupCost as cr, archiveConversation as ct, compactWithPreparedSummary as d, automationSkillToolSchema as dn, incrementStat as dr, reportConversationRead as dt, isMissingPathError as en, SAVINGS_NAMESPACE as er, createListAgentsTool as et, lastRequestInputSize as f, automationToolResult as fn, readStats as fr, createAddInboxItemTool as ft, measureTurnCompactionWait as g, editedAutomationTask as gn, breakerStates as gr, renderInboxItemMessage as gt, createNextInputTracker as h, automationTriggerSchema as hn, breakerOpen as hr, inboxItemChangeRecord as ht, GLOBAL_GAPS_TTL_MS as i, createOperationKey as in, historyPeriodSavings as ir, createNoReplyTool as it, workspaceProviderNames as j, readViewerAutomationEdit as jn, createTracedStreamFn as jr, createSlackPublicSearchTool as jt, createDeleteWorkspaceTool as k, changeViewerAutomationLifecycle as kn, decideWarmup as kr, renderBlockText as kt, isConversationWorkDone as l, AUTOMATIONS_TOOL_SOURCE as ln, replaceHistorySavings as lr, conversationReadPositionQuery as lt, requestBackgroundCompaction as m, automationTriggerChangesSchema as mn, KEY_PREFIX as mr, deliverInboxItemChange as mt, CONVERSATION_STATE_TTL_MS as n, positiveInteger as nn, addHistoryWarmupCost as nr, createReportBlockedTool as nt, segmentGapsKey as o, createSearchAutomationsTool as on, idlePeriodSavings as or, createArchiveAgentTool as ot, processBackgroundCompaction as p, automationToolResultSchema as pn, CACHE_RETENTION as pr, createUpdateInboxItemTool as pt, createWriteFileTool as q, requireAutomationSkill as qn, createSlackCanvasEditTool as qt, GLOBAL_GAPS_MAX as r, resolveWorkspacePath as rn, firstLiveSavingsDate as rr, createReplyTool as rt, stopIdleWarmups as s, createRunAutomationNowTool as sn, recordIdlePeriodSavings as sr, readLastUserMessageAtByConversation as st, ANSWER_TOOL_ENDINGS as t, normalizeToLf as tn, addHistoryPeriod as tr, createReportProgressTool as tt, listConversationWork as u, automationIdForToolCall as un, savingsTotals as ur, markConversationRead as ut, buildAgentModelRequest as v, triggerKind as vn, cachedPrefixTokens as vr, createRunOperatorSqlTool as vt, ensureWorkspaceSnapshotBuild as w, requireToolCreator as wn, warmupTooLate as wr, emptyResponse as wt, enabledMode as x, automationToolsDisabledReason as xn, providerCacheTtlMs as xr, createSetConversationSubscriptionTool as xt, requestContextSummary as y, getConversationAccess as yn, closeBreaker as yr, createListWatchesTool as yt, createSystemTimeTool as z, readViewerAutomationVersions as zn, parseSlackThreadId as zt };
|