@sentry/junior 0.285.0 → 0.286.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapter-DN5AB4VU.js → adapter-JQZaJ-B_.js} +1 -1
- package/dist/{admin-DOITMKnn.js → admin-Dm2bimJ-.js} +1 -1
- package/dist/{agent-runner-BsWhHe4N.js → agent-runner-DGCwOEyL.js} +1567 -1048
- package/dist/api/schema.d.ts +1 -1
- package/dist/api/schema.js +5 -5
- package/dist/api.d.ts +1 -1
- package/dist/api.js +70 -92
- package/dist/{app-DyMs9330.d.ts → app-BKq0JzWx.d.ts} +2 -3
- package/dist/app.d.ts +1 -1
- package/dist/app.js +37 -40
- package/dist/{assistant-reply-9Jip5bsr.js → assistant-reply-CAPafcUY.js} +1 -1
- package/dist/{automation-Mk8aaHzy.js → automation-B-jJN_gM.js} +1 -1
- package/dist/{background-compaction-queue-DXkLsWoH.js → background-compaction-queue-Btu2oab_.js} +137 -3
- package/dist/{briefs-Cl8-nK9B.js → briefs-UMeYehUe.js} +4 -4
- package/dist/{catalog-runtime-Bte6jRB2.js → catalog-runtime-Bym8GVdh.js} +1 -1
- package/dist/cli/chat.js +14 -14
- package/dist/cli/check.js +3 -3
- package/dist/cli/main.js +3 -3
- package/dist/cli/plugins.js +4 -4
- package/dist/cli/snapshot-create.js +5 -6
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +3 -3
- package/dist/{client-DDbBucBw.js → client-B0aAs7wC.js} +2 -2
- package/dist/{config-DqFnykQT.js → config-B9f9Lqo5.js} +1 -1
- package/dist/{connections-DA4LT9LL.js → connections-CQ7p0aNJ.js} +16 -50
- package/dist/{conversation-D8kVoCrP.js → conversation-BusI2uzj.js} +15 -6
- package/dist/{conversation-pending-messages-BvROq1bq.js → conversation-pending-messages-DwehU0Fd.js} +1 -1
- package/dist/{conversation-privacy-D0j_h70R.js → conversation-privacy-Cd_nZZBM.js} +1 -1
- package/dist/{credential-sync-hcsYatw-.js → credential-sync-DmiJi_At.js} +13 -13
- package/dist/{db-BhHZSuFw.d.ts → db-C5zi4ecs.d.ts} +4 -4
- package/dist/{executor-BLEMIgIZ.js → executor-Dipi2Ixl.js} +11 -17
- package/dist/instrumentation.js +2 -2
- package/dist/{logging-BfORLKoq.js → logging-CMFhLLj4.js} +1 -1
- package/dist/{media-Bu9C6lz0.js → media-B-BpXo41.js} +14 -2
- package/dist/{message-DqjuKzUx.js → message-D1xLljUF.js} +9 -9
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +2 -3
- package/dist/{oauth-callback-server-CFSRzu1n.js → oauth-callback-server-DCAFIUQr.js} +2 -2
- package/dist/{projection-DliWYrnT.js → projection-CoeMNxJ4.js} +286 -212
- package/dist/{prompt-BvIUzY4y.js → prompt-C9OQEfan.js} +1 -1
- package/dist/{registry-rC7MCxu8.js → registry-u-sFYtx_.js} +1 -1
- package/dist/{resolve-Biu8Qw3u.js → resolve-DYqgL3Eo.js} +3 -3
- package/dist/{result-DxJMCX47.js → result-CescSwAw.js} +8 -8
- package/dist/{runner-BQJSFLKg.js → runner-Cr67a8TB.js} +16 -12
- package/dist/{sandbox-egress-signals-6aMxJSDn.js → sandbox-egress-signals-DLOazy5W.js} +1 -1
- package/dist/{schema-BasXTvi2.js → schema-BUSi3sgv.js} +5 -5
- package/dist/{schema-BUviRAs8.d.ts → schema-Ih60j59-.d.ts} +44 -7
- package/dist/{service-account-BI5Wgx22.js → service-account-CGEqz9wG.js} +3 -3
- package/dist/{service-account-CAE-_1dR.js → service-account-CsKxktLk.js} +3 -3
- package/dist/{session-stop-CA-jOJ84.js → session-stop-CGz5DByb.js} +22 -20
- package/dist/{skills-B22duVJU.js → skills-COCqf61f.js} +2 -2
- package/dist/{spawn-BB2_4VYn.js → spawn-C8F_iXWO.js} +13 -2
- package/dist/{stop-DioIcEAu.js → stop-GyFZkHuQ.js} +242 -952
- package/dist/{store-Dn4W7qgH.js → store-D0-8plWp.js} +3 -3
- package/dist/{turn-session-routing-CGMKrYOj.js → task-runner-xPuQmEot.js} +1439 -993
- package/dist/{store-B26LV6UP.js → turn-failure-response-BOviBdT-.js} +331 -5
- package/dist/{validation-TzhfQABF.js → validation-DZDKorGz.js} +1 -1
- package/dist/{version-DSk8CFvA.js → version-BTIz7fGi.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{viewer-1Ea81s0b.js → viewer-CH-ASQzh.js} +39 -36
- package/dist/{work-ybG4_q5C.js → work-C75_IM5e.js} +92 -87
- package/dist/{worker-ccSyZRNz.js → worker-Dl47I729.js} +6 -6
- package/migrations/0086_shared_archive.sql +31 -0
- package/migrations/0087_child_location.sql +64 -0
- package/migrations/meta/0086_snapshot.json +4366 -0
- package/migrations/meta/0087_snapshot.json +4366 -0
- package/migrations/meta/_journal.json +14 -0
- package/package.json +5 -4
- package/dist/task-queue-Bt0IoR2i.js +0 -139
- package/dist/task-runner-D8lddjzp.js +0 -290
- package/dist/thread-state-CrFk3K_7.js +0 -173
- package/dist/turn-failure-response-DaJ04qVj.js +0 -224
- package/dist/turn-lifecycle-C2mXS7AZ.js +0 -58
|
@@ -1,32 +1,32 @@
|
|
|
1
|
-
import { g as withActiveSpan, i as getActiveSpan, m as startInactiveSpan, v as __exportAll } from "./sentry-BRTJqumy.js";
|
|
2
|
-
import { $t as
|
|
3
|
-
import { C as resolveGatewayCredential, S as getGatewayApiKey, _ as createProviderError, a as completeText, c as resolveGatewayModel, d as isCompactionSummaryText, g as ProviderError, i as completeObject, l as COMPACTION_SUMMARY_PREFIX, m as escapeXml, n as GEN_AI_SERVER_ADDRESS, p as unwrapCurrentInstruction, t as GEN_AI_PROVIDER_NAME, u as hasCompactedConversationContext, v as findProviderError, x as isProviderRetryError, y as getProviderErrorAttributes } from "./client-
|
|
4
|
-
import { _ as toPiReasoningLevel, g as TURN_REASONING_LEVELS, n as botConfig, v as normalizeSlackEmojiName } from "./config-
|
|
5
|
-
import { B as runWithLogAttributes, C as summarizeMessageText, E as withSpan, K as toOptionalString, S as setTags, T as withLogContext, U as normalizeIdentityEmail, W as isRecord$4, _ as runBestEffort, a as extractGenAiUsageSummary, b as setSpanAttributes, d as logAudit, f as logError, g as normalizeGenAiFinishReason, h as logWarn, i as extractGenAiUsageAttributes, l as getLogContextAttributesForSpan, m as logInfo, o as getActiveTraceContext, p as logException, u as getTracePropagationHeaders, v as serializeGenAiAttribute, x as setSpanStatus } from "./logging-
|
|
6
|
-
import { a as toCanonicalInputMessage, c as toGenAiPayloadMetadata, i as runWithConversationPrivacy, l as toGenAiPayloadTraceAttributes, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-
|
|
1
|
+
import { g as withActiveSpan, i as getActiveSpan, m as startInactiveSpan, r as continueTrace, v as __exportAll } from "./sentry-BRTJqumy.js";
|
|
2
|
+
import { $i as updateSlackMessage, $t as getUserMessageInstructionText, Aa as resolveSandboxCommandEnvironment, Ai as ensureDockerDaemon, An as getAgentBackgroundCompactionMarkTokens, B as createPluginAuthOrchestration, Ba as SANDBOX_DATA_ROOT, Bo as getConfigDefaults, Br as RESOURCE_WATCH_TOOL_SOURCE, Ca as clearSandboxEgressSignals, Ci as invalidateReadySnapshot, Di as create, Dn as calculateContextCompactionTargetTokens, Dr as readReviewItemAgentScope, E as resolveTaskTitle, Ea as createSandboxEgressCredentialToken, Ei as setWorkspaceSnapshotBuild, Fa as workspaceRepoCheckoutPath, Fi as formatProviderLabel, Fo as historyItemFromPiMessage, Fr as resolveAssignees, G as abandonReplacedPendingAuth, Ga as sandboxSkillFile, Gi as addReactionToMessage, Gr as createTimerWatch, H as AuthPausePersistenceError, Ha as SANDBOX_SKILLS_ROOT, Hn as createPluginHookRunner, Ht as TurnBudgetExceededError, Ia as PluginToolDeniedError, In as createUserTokenStore, Io as piMessageFromHistoryItem, Ir as resolveChannelCapabilities, Ja as buildNonInteractiveShellScript, Ji as openSlackDirectMessage, Jr as findMatchingWatches, Jt as CODEMODE_TOOL_NAME, K as canReusePendingAuthLink, Ka as sandboxSkillPathResolution, Ki as deleteSlackMessage, Kr as createWatch, Kt as createTurnLimitGate, L as upsertConversationMessage, Li as resolveBaseUrl, Ln as findLegacyWebActorUserId, Lo as projectConversationEvents, Lr as getSlackToolContext, M as markConversationMessage, Ma as SANDBOX_RUNTIME, Mn as getAgentContextInputLimitTokens, Mr as EVERYONE_ASSIGNEE, N as normalizeConversationText, Na as sleep, Nr as automationCreatorUserId, Oi as hash, On as estimateRequestOverheadTokens, Oo as defaultTimezone, Or as requireReviewItemAssignees, P as recordDeliveredAssistantMessage, Pa as tryWorkspaceRepoCheckoutPath, Pi as deliverOAuthAuthorization, Pn as isExperimentalFeatureEnabled, Pr as resolveAssignee, Qa as canAccessConversation, Qt as getTerminalAssistantMessages, R as createPluginEgress, Rr as RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS, Sa as workspaceSnapshotNotReadyUserMessage, Si as WorkspaceValidationError, Sn as buildDeterministicTurnId, Sr as PLUGIN_REVIEW_ITEM_KEY_PREFIX, T as fallbackShortTitle, Ta as consumeSandboxEgressPermissionDeniedSignal, Ti as setWorkspaceSnapshot, To as createPluginAnnotations, Tr as canReadReviewItem, U as AuthorizationFlowDisabledError, Ua as SANDBOX_WORKSPACE_ROOT, Ui as slackMention, Ur as cancelWatch, Ut as TurnSliceLimitExceededError, V as authorizationId, Va as SANDBOX_REPOS_ROOT, Vi as normalizeSlackReplyMarkdown, Vr as STOP_WATCHING_TOOL_NAME, Vt as TURN_LIMIT_WRAP_UP_MESSAGE, W as AuthorizationPauseError, Wa as sandboxSkillDir, Wt as TurnToolCallLimitExceededError, X as continuableMessages, Xr as listWatches, Xt as extractAssistantText, Ya as runNonInteractiveCommand, Yn as getPlugins, Yr as getWatch, Yt as persistWithRetry, Z as loadTurnCheckpoint, Zi as postSlackMessage, Zt as getPiMessageRole, _a as throwSandboxOperationError, _i as getWorkspace, a as loadProjection, aa as getFilePermalink, an as isStandaloneRuntimeContextMessage, b as persistConversationMessages, ba as getWorkspaceSnapshotNotReadyError, c as recordAgentsInstructionsUpdated, ca as isConversationScopedChannel, ci as getDashboardReviewItemLink, cn as normalizeToolNameFromResult, da as runWithSlackInstallationToken, dn as trimTrailingAssistantMessages, ea as uploadFilesToConversation, eo as readConversationAccessFromSql, et as saveTurnCheckpoint, f as recordAuthorizationRequested, fa as withSlackRetries, fi as ToolInputError, fn as REQUEST_CONTEXT_SECTION_TAG, fr as dismissOpenReviewItems, g as recordToolExecutionStarted, ga as isAlreadyExistsError, gi as deleteWorkspace, ha as isAbortError, hi as createWorkspace, hr as insertReviewItem, i as loadConversationProjection, ia as downloadPrivateSlackFile, ii as verifyTimerWatchCredentialSubject, in as isContinuablePiBoundary, it as getTurnRecord, j as latestConversationMessageSeq, ji as getSandboxProvider, jn as getAgentContextCompactionTriggerTokens, ka as buildSandboxEgressNetworkPolicy, ki as isStale, kn as estimateTextTokens, ko as resolveUserTimezone, kr as requireReviewItemLinks, l as recordAttachmentsDelivered, ln as retainRuntimeTurnContext, m as recordMcpProviderConnected, mi as renderToolResultNudge, mn as TURN_CONTEXT_TAG, mr as getReviewItem, oi as getDashboardConversationLink, on as isToolResultError, p as recordGuardianActionReviewed, pr as getOpenReviewItemByDedupeKey, q as clearPendingAuth, qa as buildCommandScript, qi as getSlackMessagePermalink, qn as getPluginTools, qr as deliverWatch, qt as isTurnExecutionLimitExceededError, r as loadConnectedMcpProviders, ra as SlackActionError, rn as isAssistantMessage, sa as getSlackClient, sn as isToolResultMessage, t as commitAcceptedReply, tn as hasTurnInput, tt as abandonTurnRecord, ua as normalizeSlackConversationId, ui as getDashboardTaskLink, un as stripRuntimeTurnContext, ur as closeReviewItem, v as hydrateConversationMessages, va as wrapSandboxSetupError, vi as getWorkspaceByName, wa as consumeSandboxEgressAuthRequiredSignal, wi as loadSnapshotsForProfile, wo as saveObjectAnnotations, wr as canAgentChangeReviewItem, xa as isWorkspaceSnapshotNotReadyError, xi as updateWorkspace, xr as updateReviewItemContent, ya as WorkspaceSnapshotNotReadyError, yi as listWorkspaces, yo as matchSlackAttachments, yr as searchReviewItems, z as PluginCredentialFailureError, za as SANDBOX_COMMAND_PATH, zi as escapeSlackMrkdwnText, zn as getOAuthAccountProviders, zr as RESOURCE_SUBSCRIPTION_MAX_TTL_MS } from "./projection-CoeMNxJ4.js";
|
|
3
|
+
import { C as resolveGatewayCredential, S as getGatewayApiKey, _ as createProviderError, a as completeText, c as resolveGatewayModel, d as isCompactionSummaryText, g as ProviderError, i as completeObject, l as COMPACTION_SUMMARY_PREFIX, m as escapeXml, n as GEN_AI_SERVER_ADDRESS, p as unwrapCurrentInstruction, t as GEN_AI_PROVIDER_NAME, u as hasCompactedConversationContext, v as findProviderError, x as isProviderRetryError, y as getProviderErrorAttributes } from "./client-B0aAs7wC.js";
|
|
4
|
+
import { _ as toPiReasoningLevel, g as TURN_REASONING_LEVELS, n as botConfig, v as normalizeSlackEmojiName } from "./config-B9f9Lqo5.js";
|
|
5
|
+
import { B as runWithLogAttributes, C as summarizeMessageText, E as withSpan, K as toOptionalString, S as setTags, T as withLogContext, U as normalizeIdentityEmail, W as isRecord$4, _ as runBestEffort, a as extractGenAiUsageSummary, b as setSpanAttributes, d as logAudit, f as logError, g as normalizeGenAiFinishReason, h as logWarn, i as extractGenAiUsageAttributes, l as getLogContextAttributesForSpan, m as logInfo, o as getActiveTraceContext, p as logException, u as getTracePropagationHeaders, v as serializeGenAiAttribute, x as setSpanStatus } from "./logging-CMFhLLj4.js";
|
|
6
|
+
import { a as toCanonicalInputMessage, c as toGenAiPayloadMetadata, i as runWithConversationPrivacy, l as toGenAiPayloadTraceAttributes, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-Cd_nZZBM.js";
|
|
7
7
|
import { d as parseSlackChannelReferenceId, f as parseSlackTeamId, h as parseSlackMessageTs, n as createSlackActor, o as isUserActor, p as parseSlackUserId, u as parseSlackChannelId } from "./actor-6jsm_v96.js";
|
|
8
|
-
import { $ as
|
|
9
|
-
import {
|
|
10
|
-
import { _ as instructionProvenanceFor, a as KNOWN_CONVERSATION_EVENT_TYPES, g as instructionActors, h as contextProvenance, m as agentInstructionProvenance, r as detectImageMediaType, v as sameActorIdentity } from "./media-
|
|
8
|
+
import { $ as conversationDetailTouch, C as getSqlExecutor, E as treeHasAnnotationKey, H as resolveActorIdentityId, L as conversationKindFromRow, S as getDb, T as hasAnnotationKey, V as SYSTEM_IDENTITY_ID, a as readActorIdentityFromSql, b as getConversationMessageSearchStore, dt as sameDestination, f as identityAvatarUrl, h as readUserAvatarUrls, i as readActorIdentity, lt as parseDestination, nt as addAgentTurnUsage, ot as hasAgentTurnUsage, rt as agentTurnCostUsd, tt as touchConversationDetail, w as conversationIdsWithAnnotation, x as getConversationStore, y as getConversationEventStore } from "./viewer-CH-ASQzh.js";
|
|
9
|
+
import { A as juniorConversations, M as juniorUsers, N as juniorDestinations, P as juniorArtifacts, b as juniorConversationBriefs, c as juniorReviewItemSlackCards, f as juniorAutomations, g as juniorAgentInvocations, h as juniorAgentBindings, j as juniorIdentities, k as juniorAttachments, p as juniorStats, u as juniorAutomationRuns } from "./executor-Dipi2Ixl.js";
|
|
10
|
+
import { _ as instructionProvenanceFor, a as KNOWN_CONVERSATION_EVENT_TYPES, g as instructionActors, h as contextProvenance, m as agentInstructionProvenance, r as detectImageMediaType, v as sameActorIdentity } from "./media-B-BpXo41.js";
|
|
11
11
|
import { a as listReferenceFiles } from "./package-discovery-DJhGdS4c.js";
|
|
12
|
-
import { c as fetchWithBoundedOAuthErrorBodies, d as actorLogContext, f as credentialContextForActor, g as credentialUserSubjectId, i as resolvePluginHeaderEnvRefs, l as getOAuthProviderErrorAttributes, s as OAuthProviderError } from "./registry-
|
|
13
|
-
import { n as pluginCatalogRuntime } from "./catalog-runtime-
|
|
14
|
-
import { a as parseSkillInvocation, i as parseSkillFile, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-
|
|
12
|
+
import { c as fetchWithBoundedOAuthErrorBodies, d as actorLogContext, f as credentialContextForActor, g as credentialUserSubjectId, i as resolvePluginHeaderEnvRefs, l as getOAuthProviderErrorAttributes, s as OAuthProviderError } from "./registry-u-sFYtx_.js";
|
|
13
|
+
import { n as pluginCatalogRuntime } from "./catalog-runtime-Bym8GVdh.js";
|
|
14
|
+
import { a as parseSkillInvocation, i as parseSkillFile, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-COCqf61f.js";
|
|
15
15
|
import { a as withLock, i as fenceLock } from "./locks-D-0h111u.js";
|
|
16
|
-
import { r as getStateAdapter } from "./adapter-
|
|
16
|
+
import { r as getStateAdapter } from "./adapter-JQZaJ-B_.js";
|
|
17
17
|
import { i as getFirstRunAtMs, o as getZonedDateTimeParts, s as isValidTimeZone } from "./schedule-BTp__wrw.js";
|
|
18
|
-
import { F as removedCardSchema, H as briefLinkSchema, U as briefOutcomeStatusSchema, q as parseStoredBrief } from "./conversation-
|
|
19
|
-
import { r as EVENT_AUTHOR_ID } from "./prompt-
|
|
20
|
-
import { C as
|
|
21
|
-
import { i as NO_REPLY_MARKER, n as getAssistantReplyText, o as isNoReplyMarker, r as sanitizeAssistantText, t as decideReply } from "./assistant-reply-
|
|
22
|
-
import { $ as
|
|
18
|
+
import { B as readMessageAttachments, F as removedCardSchema, H as briefLinkSchema, U as briefOutcomeStatusSchema, q as parseStoredBrief } from "./conversation-BusI2uzj.js";
|
|
19
|
+
import { o as isEventConversationMessage, r as EVENT_AUTHOR_ID } from "./prompt-C9OQEfan.js";
|
|
20
|
+
import { $ as parseAgentInvocationResultMessageId, C as isTerminalAgentInvocation, F as PARENT_AGENT_TARGET, H as formatAgentTypes, K as getAgentInvocationIdForResult, L as agentNameSchema, P as CHILD_AGENT_RESULTS, S as invocationFromRow, X as getChildAgentLockName, ct as markTurnClosed, dt as startActiveTurn, f as ConversationTurnLifecycleService, g as NON_TERMINAL_AGENT_INVOCATION_STATUSES, i as completeAuthPauseTurn, it as getConversationTurnBoundaryError, l as buildDeliveredTurnStatePatch, m as loadPendingMessageCards, nt as TurnInputCommitLostError, o as getTurnUserMessage, ot as isTurnInputCommitLostError, q as getAgentInvocationMessageId, t as finalizeFailedTurnReplyWithEvent, tt as CooperativeTurnYieldError, u as buildTurnThreadContext, ut as markTurnFailed, x as getLatestAgentInvocationForConversation, z as AGENT_TYPES } from "./turn-failure-response-BOviBdT-.js";
|
|
21
|
+
import { i as NO_REPLY_MARKER, n as getAssistantReplyText, o as isNoReplyMarker, r as sanitizeAssistantText, t as decideReply } from "./assistant-reply-CAPafcUY.js";
|
|
22
|
+
import { $ as withoutSavedSteeringMessages, A as requireSlackChannelMessageScope, B as maybePostAutomatedTurnLimitNotice, C as enqueueEventNotification, D as timerWatchCredentialSubject, E as renderEventBatchInputs, F as WORKSPACE_SNAPSHOT_FAILED_EVENT, H as resolveSlackReplyTarget, I as WORKSPACE_SNAPSHOT_READY_EVENT, J as assemblePrompt, K as recordFinishedTurnForAutomatedLimit, L as workspaceSnapshotFinishedEvent, O as getEventCatalog, P as slackChannelMessageTrigger, Q as loadPromptTurnContext, R as workspaceSnapshotWatch, S as EVENT_WAIT_MS, T as isEventMailboxMetadata, X as buildSteeringPiMessage, Y as buildPromptInput, Z as instructionForInputs, _ as sourceFromTurnInput, at as readBlockedReport, b as conversationSubtree, c as loadReviewItemInput, d as getAuthPausedConversationTurnId, dt as readAutomationResult, f as getEventBatchDelayMs, ft as remindMissingAutomationResult, it as REPORT_BLOCKED_TOOL_NAME, nt as addConversationNote, ot as FINISH_AUTOMATION_RUN_TOOL_NAME, p as listActiveMailboxTurns, r as markConversationsStopped, rt as JUNIOR_PERSONALITY, s as eventReviewItemInputs, st as automationResultSchema$1, t as getConversationStoppedAtMs, tt as saveUserCustomization, v as turnInputFactsFromConversationMessage, w as eventBatchMessageMeta, x as conversationSubtreeColumns, y as legacyWebMailboxMetadataSchema } from "./session-stop-CGz5DByb.js";
|
|
23
23
|
import { E as userCustomizationTextSchema, _ as formatUserInputAnswer, b as userInputRequestSchema, g as buttonUserInputField, h as USER_INPUT_NOTE, m as USER_INPUT_LIMITS, p as webMessageId, s as sumUtcHoursIntoSixHours, w as USER_CUSTOMIZATION_MAX_CHARS, y as normalizeUserInputAnswer } from "./reporting-window-B4TwyuJo.js";
|
|
24
|
-
import { a as setSnapshotSpanAttributes, i as postinstall, n as resolve$1, r as dependencies, s as getSandboxResources } from "./resolve-
|
|
25
|
-
import {
|
|
26
|
-
import { O as stopConversationWork, _ as getConversationWorkState, n as appendAndEnqueueExclusiveInboundMessage, r as appendAndEnqueueInboundMessage } from "./store-
|
|
27
|
-
import { $ as
|
|
28
|
-
import { _ as getMcpProviderErrorAttributes, a as serviceAccountOnly, c as createMcpServiceAccountClientProvider, d as PluginMcpClient, f as McpProviderError, g as getMcpAwareTelemetryMessage, h as getMcpAwareErrorType, i as serviceAccountAllows, l as getMcpServiceAccountCredentials, m as McpToolError, p as McpServiceAccountRequiredError, u as McpAuthorizationRequiredError, v as toMcpProviderError } from "./service-account-
|
|
29
|
-
import { A as SCHEDULED_AUTOMATION_SYSTEM_ACTOR, D as taskOutcomeInputSchema, E as automationTitleSchema, F as scheduleIntentFromTool, I as toolScheduleIntentSchema, L as weekdaySchema, N as ScheduleIntentError, P as compileScheduleIntent, T as automationInstructionToolSchema, k as eventAutomationTriggerSchema, l as automationListQuerySchema } from "./automation-
|
|
24
|
+
import { a as setSnapshotSpanAttributes, i as postinstall, n as resolve$1, r as dependencies, s as getSandboxResources } from "./resolve-DYqgL3Eo.js";
|
|
25
|
+
import { S as getTurnRequestDeadline, _ as getVercelConversationWorkQueue, b as QUEUE_SIGNATURE_MAX_AGE_MS, h as sendWorkspaceSnapshotJob, m as sendNextWorkspaceSnapshotJob, n as backgroundCompactionId } from "./background-compaction-queue-Btu2oab_.js";
|
|
26
|
+
import { O as stopConversationWork, _ as getConversationWorkState, n as appendAndEnqueueExclusiveInboundMessage, r as appendAndEnqueueInboundMessage } from "./store-D0-8plWp.js";
|
|
27
|
+
import { $ as readAutomationExecutionByConversationId, At as registeredEventTriggerProblems, B as setEventAutomationStatus, C as deleteScheduledAutomation, Ct as describeRegisteredEventTrigger, D as saveScheduledAutomation, Dt as eventWatchUnavailable, E as readScheduledAutomation, Et as eventNamespaceSchema, G as listAutomationVersions, I as getEventAutomation, K as readAutomationVersion, L as listDeletedEventAutomationsCreatedBy, Mt as registeredResourceTypeSchema, N as createEventAutomation, Nt as requireEventIdentifier, Ot as hasEventCatalogEntries, P as deleteEventAutomation, Pt as requireValidEventTrigger, R as parseEventAutomationRow, S as createScheduledAutomation, St as automationEventCatalog, T as parseScheduledAutomationRow, U as automationDefinition, X as requireAutomationRevision, Y as automationRevision, Z as emptyAutomationRunWindows, _t as getPersistedThreadState, at as readAutomationExecutions, bt as coerceThreadConversationState, d as getDispatchRecord, et as readAutomationExecutionDays, gt as getPersistedSandboxState, it as readAutomationExecutionSummaries, jt as registeredEventTypeSchema, kt as registeredEventMatchSchema, l as getDispatchIdForConversation, n as scheduleSessionCompletedPluginTasks, nt as readAutomationExecutionStatusDays, ot as readAutomationRuns, pt as resolveConversationRouting, q as sameDefinitionValue, rt as readAutomationExecutionStatusHours, t as processPluginTask, tt as readAutomationExecutionHours, u as getDispatchInputMessageId, yt as persistThreadStateById, z as saveEventAutomation } from "./task-runner-xPuQmEot.js";
|
|
28
|
+
import { _ as getMcpProviderErrorAttributes, a as serviceAccountOnly, c as createMcpServiceAccountClientProvider, d as PluginMcpClient, f as McpProviderError, g as getMcpAwareTelemetryMessage, h as getMcpAwareErrorType, i as serviceAccountAllows, l as getMcpServiceAccountCredentials, m as McpToolError, p as McpServiceAccountRequiredError, u as McpAuthorizationRequiredError, v as toMcpProviderError } from "./service-account-CGEqz9wG.js";
|
|
29
|
+
import { A as SCHEDULED_AUTOMATION_SYSTEM_ACTOR, D as taskOutcomeInputSchema, E as automationTitleSchema, F as scheduleIntentFromTool, I as toolScheduleIntentSchema, L as weekdaySchema, N as ScheduleIntentError, P as compileScheduleIntent, T as automationInstructionToolSchema, k as eventAutomationTriggerSchema, l as automationListQuerySchema } from "./automation-B-jJN_gM.js";
|
|
30
30
|
import { n as privateTraceResultAttributes } from "./private-trace-result-CE7_lEdq.js";
|
|
31
31
|
import { streamSimple } from "@earendil-works/pi-ai/compat";
|
|
32
32
|
import { createGatewayProvider } from "@ai-sdk/gateway";
|
|
@@ -41,6 +41,7 @@ import { PluginToolInputError, agentEventKeys, agentEventMatchKey, agentEventMat
|
|
|
41
41
|
import { alias } from "drizzle-orm/pg-core";
|
|
42
42
|
import { Agent, estimateContextTokens, estimateTokens } from "@earendil-works/pi-agent-core";
|
|
43
43
|
import fs from "node:fs/promises";
|
|
44
|
+
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
44
45
|
import http from "node:http";
|
|
45
46
|
import dns from "node:dns/promises";
|
|
46
47
|
import net from "node:net";
|
|
@@ -1076,48 +1077,6 @@ function projectTimedOutToolResult(result) {
|
|
|
1076
1077
|
isError: false
|
|
1077
1078
|
};
|
|
1078
1079
|
}
|
|
1079
|
-
// src/chat/conversations/lineage.ts
|
|
1080
|
-
/**
|
|
1081
|
-
* Read the parent chain of a Conversation in one query, root first, with the
|
|
1082
|
-
* Conversation last. Returns an empty list when the Conversation is missing.
|
|
1083
|
-
*
|
|
1084
|
-
* The chain stops at a parent that is missing or that is already in the
|
|
1085
|
-
* chain. Then the first entry still has a `parentConversationId`, so callers
|
|
1086
|
-
* can tell a broken chain from one that ends at a root.
|
|
1087
|
-
*/
|
|
1088
|
-
async function readConversationLineage(conversationId) {
|
|
1089
|
-
const lineage = sql`(
|
|
1090
|
-
with recursive lineage(conversation_id, parent_conversation_id, depth, path) as (
|
|
1091
|
-
select selected.conversation_id, selected.parent_conversation_id, 0, array[selected.conversation_id]
|
|
1092
|
-
from junior_conversations selected
|
|
1093
|
-
where selected.conversation_id = ${conversationId}
|
|
1094
|
-
union all
|
|
1095
|
-
select parent.conversation_id, parent.parent_conversation_id, lineage.depth + 1, lineage.path || parent.conversation_id
|
|
1096
|
-
from junior_conversations parent
|
|
1097
|
-
join lineage on parent.conversation_id = lineage.parent_conversation_id
|
|
1098
|
-
where parent.conversation_id <> all(lineage.path)
|
|
1099
|
-
)
|
|
1100
|
-
select conversation_id, depth from lineage
|
|
1101
|
-
) conversation_lineage`;
|
|
1102
|
-
return (await getDb().select({
|
|
1103
|
-
conversationId: juniorConversations.conversationId,
|
|
1104
|
-
destination: juniorDestinations,
|
|
1105
|
-
kind: juniorConversations.kind,
|
|
1106
|
-
location: juniorConversations.location,
|
|
1107
|
-
parentConversationId: juniorConversations.parentConversationId,
|
|
1108
|
-
sessionSource: juniorConversations.sessionSource
|
|
1109
|
-
}).from(juniorConversations).innerJoin(lineage, eq(sql`conversation_lineage.conversation_id`, juniorConversations.conversationId)).leftJoin(juniorDestinations, eq(juniorDestinations.id, juniorConversations.destinationId)).orderBy(desc(sql`conversation_lineage.depth`))).map((row) => {
|
|
1110
|
-
const location = locationFromRow(row.location, row.destination, parseSessionSource(row.sessionSource));
|
|
1111
|
-
const visibility = visibilityFromLocationRow(row.destination);
|
|
1112
|
-
return {
|
|
1113
|
-
conversationId: row.conversationId,
|
|
1114
|
-
kind: conversationKindFromRow(row),
|
|
1115
|
-
...location ? { location } : void 0,
|
|
1116
|
-
...row.parentConversationId ? { parentConversationId: row.parentConversationId } : void 0,
|
|
1117
|
-
...visibility ? { visibility } : void 0
|
|
1118
|
-
};
|
|
1119
|
-
});
|
|
1120
|
-
}
|
|
1121
1080
|
// src/chat/agent/types.ts
|
|
1122
1081
|
/** Resume the agent turn after a transient or ambiguous delivery failure. */
|
|
1123
1082
|
var RetryableDeliveryError = class extends Error {
|
|
@@ -1136,8 +1095,11 @@ function actorFromRun(run) {
|
|
|
1136
1095
|
if (run.actor) return run.actor;
|
|
1137
1096
|
if (run.credentialContext && !("type" in run.credentialContext.actor)) return run.credentialContext.actor;
|
|
1138
1097
|
}
|
|
1139
|
-
/**
|
|
1140
|
-
|
|
1098
|
+
/**
|
|
1099
|
+
* Reject contradictory provider coordinates before the run touches state.
|
|
1100
|
+
* `conversationKind` comes from the stored Conversation, never from the Run.
|
|
1101
|
+
*/
|
|
1102
|
+
function assertRunConsistency(run, conversationKind) {
|
|
1141
1103
|
const { destination, source } = run;
|
|
1142
1104
|
switch (source.kind) {
|
|
1143
1105
|
case "slack":
|
|
@@ -1153,6 +1115,7 @@ function assertRunConsistency(run) {
|
|
|
1153
1115
|
if (run.surface !== "internal" && source.conversationId !== run.conversationId) throw new TypeError("Web source and run conversation IDs do not match");
|
|
1154
1116
|
switch (destination.platform) {
|
|
1155
1117
|
case "local":
|
|
1118
|
+
if (conversationKind === "thread") break;
|
|
1156
1119
|
if (source.conversationId !== destination.conversationId) throw new TypeError("Source and destination conversation IDs do not match");
|
|
1157
1120
|
if (run.surface !== "internal" && destination.conversationId !== run.conversationId) throw new TypeError("Source, destination, and run conversation IDs do not match");
|
|
1158
1121
|
}
|
|
@@ -2596,7 +2559,7 @@ function createSandboxRuntime(options) {
|
|
|
2596
2559
|
const timeoutMs = options.timeoutMs ?? 18e5;
|
|
2597
2560
|
const traceContext = options.traceContext ?? {};
|
|
2598
2561
|
let activeWorkspace = options.workspace;
|
|
2599
|
-
let dependencyProfileHash = options.sandboxRef?.profileHash ?? hash("
|
|
2562
|
+
let dependencyProfileHash = options.sandboxRef?.profileHash ?? hash("node24", activeWorkspace);
|
|
2600
2563
|
const resolveCommandEnv = options.commandEnv ?? (async () => ({}));
|
|
2601
2564
|
const withSandboxSpan = (name, op, attributes, callback) => withSpan(name, op, traceContext, callback, attributes);
|
|
2602
2565
|
/** Drop unavailable live state; keep the durable hint for reacquire. */
|
|
@@ -3145,9 +3108,6 @@ function createSandboxRuntime(options) {
|
|
|
3145
3108
|
};
|
|
3146
3109
|
}
|
|
3147
3110
|
// src/chat/tools/sandbox/file-utils.ts
|
|
3148
|
-
const RIPGREP_EXCLUDED_GLOBS = ["!**/.git/**", "!**/node_modules/**"];
|
|
3149
|
-
const DEFAULT_SEARCH_COMMAND_TIMEOUT_MS = 3e4;
|
|
3150
|
-
const SKIPPED_DIRECTORIES = /* @__PURE__ */ new Set([".git", "node_modules"]);
|
|
3151
3111
|
/** Normalize model-supplied numeric knobs before they reach filesystem tools. */
|
|
3152
3112
|
function positiveInteger$1(value) {
|
|
3153
3113
|
if (typeof value !== "number" || !Number.isFinite(value)) return;
|
|
@@ -3165,47 +3125,6 @@ function isMissingPathError(error) {
|
|
|
3165
3125
|
if (candidate.code === "ENOENT") return true;
|
|
3166
3126
|
return typeof candidate.message === "string" && candidate.message.startsWith("File not found:");
|
|
3167
3127
|
}
|
|
3168
|
-
/** Reject an expected missing search/list path through the tool-error channel. */
|
|
3169
|
-
function missingPathSearchResult(params) {
|
|
3170
|
-
const textPath = params.displayPath ?? params.missingPath ?? params.path;
|
|
3171
|
-
throw new ToolInputError(`Path not found: ${textPath}`);
|
|
3172
|
-
}
|
|
3173
|
-
function escapeRegExp(value) {
|
|
3174
|
-
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
3175
|
-
}
|
|
3176
|
-
function globToRegExp(pattern) {
|
|
3177
|
-
let source = "";
|
|
3178
|
-
for (let index = 0; index < pattern.length; index += 1) {
|
|
3179
|
-
const char = pattern.charAt(index);
|
|
3180
|
-
const next = pattern[index + 1];
|
|
3181
|
-
if (char === "*" && next === "*") {
|
|
3182
|
-
if (pattern[index + 2] === "/") {
|
|
3183
|
-
source += "(?:.*/)?";
|
|
3184
|
-
index += 2;
|
|
3185
|
-
continue;
|
|
3186
|
-
}
|
|
3187
|
-
source += ".*";
|
|
3188
|
-
index += 1;
|
|
3189
|
-
continue;
|
|
3190
|
-
}
|
|
3191
|
-
if (char === "*") {
|
|
3192
|
-
source += "[^/]*";
|
|
3193
|
-
continue;
|
|
3194
|
-
}
|
|
3195
|
-
if (char === "?") {
|
|
3196
|
-
source += "[^/]";
|
|
3197
|
-
continue;
|
|
3198
|
-
}
|
|
3199
|
-
source += escapeRegExp(char);
|
|
3200
|
-
}
|
|
3201
|
-
return new RegExp(`^${source}$`);
|
|
3202
|
-
}
|
|
3203
|
-
function matchesGlob(relativePath, pattern) {
|
|
3204
|
-
const matcher = globToRegExp(pattern);
|
|
3205
|
-
if (matcher.test(relativePath)) return true;
|
|
3206
|
-
if (pattern.startsWith("**/") && matchesGlob(relativePath, pattern.slice(3))) return true;
|
|
3207
|
-
return !pattern.includes("/") && matcher.test(path.posix.basename(relativePath));
|
|
3208
|
-
}
|
|
3209
3128
|
const SANDBOX_FILE_ROOTS = [SANDBOX_WORKSPACE_ROOT, "/tmp"];
|
|
3210
3129
|
/** Keep sandbox filesystem tools scoped to the workspace root and /tmp. */
|
|
3211
3130
|
function resolveWorkspacePath(input, fallback = ".") {
|
|
@@ -3215,89 +3134,6 @@ function resolveWorkspacePath(input, fallback = ".") {
|
|
|
3215
3134
|
if (!SANDBOX_FILE_ROOTS.some((root) => normalized === root || normalized.startsWith(`${root}/`))) throw new ToolInputError(`Path must stay within ${SANDBOX_FILE_ROOTS.join(" or ")}: ${requested}`);
|
|
3216
3135
|
return normalized;
|
|
3217
3136
|
}
|
|
3218
|
-
/** Anchor ripgrep paths and globs to the requested search root. */
|
|
3219
|
-
function getRipgrepSearchLocation(root, rootIsDirectory) {
|
|
3220
|
-
if (rootIsDirectory) return {
|
|
3221
|
-
cwd: root,
|
|
3222
|
-
target: "."
|
|
3223
|
-
};
|
|
3224
|
-
return {
|
|
3225
|
-
cwd: path.posix.dirname(root),
|
|
3226
|
-
target: path.posix.basename(root)
|
|
3227
|
-
};
|
|
3228
|
-
}
|
|
3229
|
-
/** Share bounded workspace traversal across search tools so their skip rules stay aligned. */
|
|
3230
|
-
async function collectFiles(params) {
|
|
3231
|
-
const files = [];
|
|
3232
|
-
let limitReached = false;
|
|
3233
|
-
let missingPath;
|
|
3234
|
-
const visit = async (dirPath) => {
|
|
3235
|
-
if (missingPath) return;
|
|
3236
|
-
let entries;
|
|
3237
|
-
try {
|
|
3238
|
-
entries = (await params.fs.readdir(dirPath)).sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
|
|
3239
|
-
} catch (error) {
|
|
3240
|
-
if (isMissingPathError(error)) {
|
|
3241
|
-
missingPath = dirPath;
|
|
3242
|
-
return;
|
|
3243
|
-
}
|
|
3244
|
-
throw error;
|
|
3245
|
-
}
|
|
3246
|
-
for (const entry of entries) {
|
|
3247
|
-
const fullPath = path.posix.join(dirPath, entry);
|
|
3248
|
-
let stat;
|
|
3249
|
-
try {
|
|
3250
|
-
stat = await params.fs.stat(fullPath);
|
|
3251
|
-
} catch (error) {
|
|
3252
|
-
if (isMissingPathError(error)) {
|
|
3253
|
-
missingPath = fullPath;
|
|
3254
|
-
return;
|
|
3255
|
-
}
|
|
3256
|
-
throw error;
|
|
3257
|
-
}
|
|
3258
|
-
if (stat.isDirectory()) {
|
|
3259
|
-
if (!SKIPPED_DIRECTORIES.has(entry)) await visit(fullPath);
|
|
3260
|
-
if (limitReached) return;
|
|
3261
|
-
continue;
|
|
3262
|
-
}
|
|
3263
|
-
const relativePath = path.posix.relative(params.root, fullPath);
|
|
3264
|
-
if (!params.pattern || matchesGlob(relativePath, params.pattern)) {
|
|
3265
|
-
files.push(fullPath);
|
|
3266
|
-
if (params.limit && files.length >= params.limit) {
|
|
3267
|
-
limitReached = true;
|
|
3268
|
-
return;
|
|
3269
|
-
}
|
|
3270
|
-
}
|
|
3271
|
-
}
|
|
3272
|
-
};
|
|
3273
|
-
let stat;
|
|
3274
|
-
try {
|
|
3275
|
-
stat = await params.fs.stat(params.root);
|
|
3276
|
-
} catch (error) {
|
|
3277
|
-
if (isMissingPathError(error)) return {
|
|
3278
|
-
files,
|
|
3279
|
-
limitReached: false,
|
|
3280
|
-
missingPath: params.root,
|
|
3281
|
-
missingRoot: true
|
|
3282
|
-
};
|
|
3283
|
-
throw error;
|
|
3284
|
-
}
|
|
3285
|
-
if (!stat.isDirectory()) {
|
|
3286
|
-
const relativePath = path.posix.basename(params.root);
|
|
3287
|
-
return {
|
|
3288
|
-
files: !params.pattern || matchesGlob(relativePath, params.pattern) ? [params.root] : [],
|
|
3289
|
-
limitReached: false,
|
|
3290
|
-
missingRoot: false
|
|
3291
|
-
};
|
|
3292
|
-
}
|
|
3293
|
-
await visit(params.root);
|
|
3294
|
-
return {
|
|
3295
|
-
files,
|
|
3296
|
-
limitReached,
|
|
3297
|
-
missingPath,
|
|
3298
|
-
missingRoot: missingPath === params.root
|
|
3299
|
-
};
|
|
3300
|
-
}
|
|
3301
3137
|
// src/chat/tools/sandbox/text-edits.ts
|
|
3302
3138
|
const MAX_DIFF_LINE_CHARS = 4e3;
|
|
3303
3139
|
/** Preserve a text artifact's dominant line-ending style across rewrites. */
|
|
@@ -3558,501 +3394,6 @@ function createEditFileTool() {
|
|
|
3558
3394
|
}
|
|
3559
3395
|
});
|
|
3560
3396
|
}
|
|
3561
|
-
// src/chat/tools/sandbox/find-files.ts
|
|
3562
|
-
const DEFAULT_FIND_LIMIT = 100;
|
|
3563
|
-
/** Find workspace files with structured limits instead of ad hoc shell output. */
|
|
3564
|
-
async function findFiles(params) {
|
|
3565
|
-
if (!params.pattern.trim()) throw new ToolInputError("pattern is required");
|
|
3566
|
-
const root = resolveWorkspacePath(params.path);
|
|
3567
|
-
const limit = positiveInteger$1(params.limit) ?? DEFAULT_FIND_LIMIT;
|
|
3568
|
-
if (params.runCommand) return await findFilesWithRipgrep({
|
|
3569
|
-
fs: params.fs,
|
|
3570
|
-
limit,
|
|
3571
|
-
onTelemetry: params.onTelemetry,
|
|
3572
|
-
path: params.path,
|
|
3573
|
-
pattern: params.pattern,
|
|
3574
|
-
root,
|
|
3575
|
-
runCommand: params.runCommand
|
|
3576
|
-
});
|
|
3577
|
-
const { files, limitReached, missingPath, missingRoot } = await collectFiles({
|
|
3578
|
-
fs: params.fs,
|
|
3579
|
-
root,
|
|
3580
|
-
pattern: params.pattern,
|
|
3581
|
-
limit
|
|
3582
|
-
});
|
|
3583
|
-
if (missingPath) return missingPathSearchResult({
|
|
3584
|
-
path: params.path ?? ".",
|
|
3585
|
-
...missingRoot ? { displayPath: params.path ?? "." } : { missingPath }
|
|
3586
|
-
});
|
|
3587
|
-
const relativePaths = files.map((filePath) => path.posix.relative(root, filePath));
|
|
3588
|
-
const body = relativePaths.length > 0 ? relativePaths.join("\n") : "No files found matching pattern";
|
|
3589
|
-
const notices = [];
|
|
3590
|
-
if (limitReached) notices.push(`${limit} results limit reached. Refine pattern or raise limit.`);
|
|
3591
|
-
const text = notices.length > 0 ? `${body}\n\n[${notices.join(" ")}]` : body;
|
|
3592
|
-
return makeStructuredToolOutput({
|
|
3593
|
-
target: params.path ?? ".",
|
|
3594
|
-
path: params.path ?? ".",
|
|
3595
|
-
truncated: limitReached,
|
|
3596
|
-
files: relativePaths,
|
|
3597
|
-
file_count: relativePaths.length,
|
|
3598
|
-
...notices.length > 0 ? { truncation_reasons: notices } : void 0,
|
|
3599
|
-
...limitReached ? { result_limit_reached: limit } : void 0
|
|
3600
|
-
}, { content: [{
|
|
3601
|
-
type: "text",
|
|
3602
|
-
text
|
|
3603
|
-
}] });
|
|
3604
|
-
}
|
|
3605
|
-
async function findFilesWithRipgrep(params) {
|
|
3606
|
-
let rootIsDirectory;
|
|
3607
|
-
try {
|
|
3608
|
-
rootIsDirectory = (await params.fs.stat(params.root)).isDirectory();
|
|
3609
|
-
} catch (error) {
|
|
3610
|
-
if (isMissingPathError(error)) return missingPathSearchResult({
|
|
3611
|
-
path: params.path ?? ".",
|
|
3612
|
-
displayPath: params.path ?? "."
|
|
3613
|
-
});
|
|
3614
|
-
throw error;
|
|
3615
|
-
}
|
|
3616
|
-
const location = getRipgrepSearchLocation(params.root, rootIsDirectory);
|
|
3617
|
-
const ripgrepArgs = [
|
|
3618
|
-
"--files",
|
|
3619
|
-
"--null",
|
|
3620
|
-
"--hidden",
|
|
3621
|
-
"--glob",
|
|
3622
|
-
params.pattern
|
|
3623
|
-
];
|
|
3624
|
-
for (const excludedGlob of RIPGREP_EXCLUDED_GLOBS) ripgrepArgs.push("--glob", excludedGlob);
|
|
3625
|
-
ripgrepArgs.push("--", location.target);
|
|
3626
|
-
const result = await params.runCommand({
|
|
3627
|
-
cmd: "bash",
|
|
3628
|
-
args: [
|
|
3629
|
-
"-c",
|
|
3630
|
-
[
|
|
3631
|
-
`rg "$@" | head -z -n ${params.limit + 1}`,
|
|
3632
|
-
"statuses=(\"${PIPESTATUS[@]}\")",
|
|
3633
|
-
"if (( statuses[1] != 0 )); then",
|
|
3634
|
-
" exit \"${statuses[1]}\"",
|
|
3635
|
-
"fi",
|
|
3636
|
-
"if (( statuses[0] == 0 || statuses[0] == 1 || statuses[0] == 141 )); then",
|
|
3637
|
-
" exit 0",
|
|
3638
|
-
"fi",
|
|
3639
|
-
"exit \"${statuses[0]}\""
|
|
3640
|
-
].join("\n"),
|
|
3641
|
-
"find-files",
|
|
3642
|
-
...ripgrepArgs
|
|
3643
|
-
],
|
|
3644
|
-
cwd: location.cwd,
|
|
3645
|
-
timeoutMs: DEFAULT_SEARCH_COMMAND_TIMEOUT_MS
|
|
3646
|
-
});
|
|
3647
|
-
if (result.exitCode !== 0) {
|
|
3648
|
-
const detail = result.stderr.trim() || result.stdout.trim() || "command failed";
|
|
3649
|
-
if (/error parsing glob|invalid glob/i.test(detail)) throw new ToolInputError(`Invalid glob pattern: ${params.pattern}`, { cause: new Error(detail) });
|
|
3650
|
-
throw new Error(`ripgrep file search failed: ${detail}`);
|
|
3651
|
-
}
|
|
3652
|
-
const allPaths = result.stdout.split("\0").filter(Boolean).map((filePath) => {
|
|
3653
|
-
const absolute = filePath.startsWith("/") ? path.posix.normalize(filePath) : path.posix.resolve(location.cwd, filePath);
|
|
3654
|
-
return rootIsDirectory ? path.posix.relative(params.root, absolute) : path.posix.basename(absolute);
|
|
3655
|
-
});
|
|
3656
|
-
const limitReached = allPaths.length > params.limit;
|
|
3657
|
-
const relativePaths = allPaths.slice(0, params.limit);
|
|
3658
|
-
const body = relativePaths.length > 0 ? relativePaths.join("\n") : "No files found matching pattern";
|
|
3659
|
-
const notices = [];
|
|
3660
|
-
if (limitReached) notices.push(`${params.limit} results limit reached. Refine pattern or raise limit.`);
|
|
3661
|
-
const text = notices.length > 0 ? `${body}\n\n[${notices.join(" ")}]` : body;
|
|
3662
|
-
const response = makeStructuredToolOutput({
|
|
3663
|
-
target: params.path ?? ".",
|
|
3664
|
-
path: params.path ?? ".",
|
|
3665
|
-
truncated: limitReached,
|
|
3666
|
-
files: relativePaths,
|
|
3667
|
-
file_count: relativePaths.length,
|
|
3668
|
-
...notices.length > 0 ? { truncation_reasons: notices } : void 0,
|
|
3669
|
-
...limitReached ? { result_limit_reached: params.limit } : void 0
|
|
3670
|
-
}, { content: [{
|
|
3671
|
-
type: "text",
|
|
3672
|
-
text
|
|
3673
|
-
}] });
|
|
3674
|
-
params.onTelemetry?.({
|
|
3675
|
-
emittedLineCount: relativePaths.length,
|
|
3676
|
-
limit: params.limit,
|
|
3677
|
-
limitReached,
|
|
3678
|
-
parsedRecordCount: allPaths.length,
|
|
3679
|
-
rawOutputBytes: Buffer.byteLength(result.stdout, "utf8"),
|
|
3680
|
-
resultBytes: response.content.reduce((total, item) => total + (item.type === "text" ? Buffer.byteLength(item.text, "utf8") : 0), 0),
|
|
3681
|
-
resultCount: relativePaths.length
|
|
3682
|
-
});
|
|
3683
|
-
return response;
|
|
3684
|
-
}
|
|
3685
|
-
/** Create the sandbox file discovery tool definition exposed to the agent. */
|
|
3686
|
-
function createFindFilesTool() {
|
|
3687
|
-
return zodTool({
|
|
3688
|
-
description: "Find sandbox workspace files by glob pattern. Returns bounded paths relative to the search root and skips dependency/cache directories.",
|
|
3689
|
-
annotations: {
|
|
3690
|
-
destructiveHint: false,
|
|
3691
|
-
idempotentHint: true,
|
|
3692
|
-
openWorldHint: false,
|
|
3693
|
-
readOnlyHint: true
|
|
3694
|
-
},
|
|
3695
|
-
inputSchema: z.object({
|
|
3696
|
-
pattern: z.string().min(1).describe("Glob pattern to match, for example '*.ts', '**/*.json', or 'src/**/*.test.ts'."),
|
|
3697
|
-
path: z.string().min(1).describe("Directory or file path in the sandbox workspace. Defaults to the workspace root.").optional(),
|
|
3698
|
-
limit: z.coerce.number().int().min(1).describe("Maximum number of file paths to return. Defaults to 100.").optional()
|
|
3699
|
-
}),
|
|
3700
|
-
outputSchema: juniorToolOutputSchema,
|
|
3701
|
-
execute: async () => {
|
|
3702
|
-
throw new Error("findFiles can only run when sandbox execution is enabled.");
|
|
3703
|
-
}
|
|
3704
|
-
});
|
|
3705
|
-
}
|
|
3706
|
-
// src/chat/tools/sandbox/grep.ts
|
|
3707
|
-
const DEFAULT_GREP_LIMIT = 100;
|
|
3708
|
-
const MAX_GREP_LINE_CHARS = 500;
|
|
3709
|
-
const booleanInput$2 = (description) => z.preprocess((value) => value === "true" ? true : value === "false" ? false : value, z.boolean()).describe(description);
|
|
3710
|
-
function truncateGrepLine(value) {
|
|
3711
|
-
if (value.length <= MAX_GREP_LINE_CHARS) return {
|
|
3712
|
-
line: value,
|
|
3713
|
-
truncated: false
|
|
3714
|
-
};
|
|
3715
|
-
return {
|
|
3716
|
-
line: `${value.slice(0, MAX_GREP_LINE_CHARS)}... [line truncated]`,
|
|
3717
|
-
truncated: true
|
|
3718
|
-
};
|
|
3719
|
-
}
|
|
3720
|
-
function lineMatches(params) {
|
|
3721
|
-
if (!params.literal) return Boolean(params.regex?.test(params.line));
|
|
3722
|
-
if (params.ignoreCase) return params.line.toLowerCase().includes(params.pattern.toLowerCase());
|
|
3723
|
-
return params.line.includes(params.pattern);
|
|
3724
|
-
}
|
|
3725
|
-
/** Search workspace file contents with bounded, line-numbered output. */
|
|
3726
|
-
async function grepFiles(params) {
|
|
3727
|
-
if (!params.pattern) throw new ToolInputError("pattern is required");
|
|
3728
|
-
const root = resolveWorkspacePath(params.path);
|
|
3729
|
-
const limit = positiveInteger$1(params.limit) ?? DEFAULT_GREP_LIMIT;
|
|
3730
|
-
const context = positiveInteger$1(params.context) ?? 0;
|
|
3731
|
-
if (params.runCommand) return await grepFilesWithRipgrep({
|
|
3732
|
-
context,
|
|
3733
|
-
fs: params.fs,
|
|
3734
|
-
glob: params.glob,
|
|
3735
|
-
ignoreCase: params.ignoreCase,
|
|
3736
|
-
limit,
|
|
3737
|
-
literal: params.literal,
|
|
3738
|
-
onTelemetry: params.onTelemetry,
|
|
3739
|
-
path: params.path,
|
|
3740
|
-
pattern: params.pattern,
|
|
3741
|
-
root,
|
|
3742
|
-
runCommand: params.runCommand
|
|
3743
|
-
});
|
|
3744
|
-
let regex;
|
|
3745
|
-
if (!params.literal) try {
|
|
3746
|
-
regex = new RegExp(params.pattern, params.ignoreCase ? "i" : "");
|
|
3747
|
-
} catch (error) {
|
|
3748
|
-
throw new ToolInputError(`Invalid regex pattern: ${params.pattern}`, { cause: error });
|
|
3749
|
-
}
|
|
3750
|
-
const { files, missingPath, missingRoot } = await collectFiles({
|
|
3751
|
-
fs: params.fs,
|
|
3752
|
-
root,
|
|
3753
|
-
pattern: params.glob
|
|
3754
|
-
});
|
|
3755
|
-
if (missingPath) return missingPathSearchResult({
|
|
3756
|
-
path: params.path ?? ".",
|
|
3757
|
-
...missingRoot ? { displayPath: params.path ?? "." } : { missingPath }
|
|
3758
|
-
});
|
|
3759
|
-
const output = [];
|
|
3760
|
-
let matchCount = 0;
|
|
3761
|
-
let matchLimitReached = false;
|
|
3762
|
-
let lineTruncated = false;
|
|
3763
|
-
for (const filePath of files) {
|
|
3764
|
-
if (matchLimitReached) break;
|
|
3765
|
-
let content;
|
|
3766
|
-
try {
|
|
3767
|
-
content = await params.fs.readFile(filePath, { encoding: "utf8" });
|
|
3768
|
-
} catch (error) {
|
|
3769
|
-
if (isMissingPathError(error)) return missingPathSearchResult({
|
|
3770
|
-
path: params.path ?? ".",
|
|
3771
|
-
missingPath: filePath
|
|
3772
|
-
});
|
|
3773
|
-
throw error;
|
|
3774
|
-
}
|
|
3775
|
-
if (content.includes("\0")) continue;
|
|
3776
|
-
const lines = normalizeToLf$1(content).split("\n");
|
|
3777
|
-
const relativePath = files.length === 1 && filePath === root ? path.posix.basename(filePath) : path.posix.relative(root, filePath);
|
|
3778
|
-
const matchedLines = [];
|
|
3779
|
-
for (const [lineIndex, line] of lines.entries()) {
|
|
3780
|
-
if (!lineMatches({
|
|
3781
|
-
ignoreCase: params.ignoreCase,
|
|
3782
|
-
line,
|
|
3783
|
-
literal: params.literal,
|
|
3784
|
-
pattern: params.pattern,
|
|
3785
|
-
regex
|
|
3786
|
-
})) continue;
|
|
3787
|
-
if (matchCount >= limit) {
|
|
3788
|
-
matchLimitReached = true;
|
|
3789
|
-
break;
|
|
3790
|
-
}
|
|
3791
|
-
matchCount += 1;
|
|
3792
|
-
matchedLines.push(lineIndex);
|
|
3793
|
-
}
|
|
3794
|
-
const matchedLineSet = new Set(matchedLines);
|
|
3795
|
-
const emittedLines = /* @__PURE__ */ new Set();
|
|
3796
|
-
for (const lineIndex of matchedLines) {
|
|
3797
|
-
const start = Math.max(0, lineIndex - context);
|
|
3798
|
-
const end = Math.min(lines.length - 1, lineIndex + context);
|
|
3799
|
-
for (let current = start; current <= end; current += 1) {
|
|
3800
|
-
if (emittedLines.has(current)) continue;
|
|
3801
|
-
emittedLines.add(current);
|
|
3802
|
-
const truncated = truncateGrepLine(lines[current] ?? "");
|
|
3803
|
-
lineTruncated ||= truncated.truncated;
|
|
3804
|
-
const separator = matchedLineSet.has(current) ? ":" : "-";
|
|
3805
|
-
output.push(`${relativePath}${separator}${current + 1}${separator} ${truncated.line}`);
|
|
3806
|
-
}
|
|
3807
|
-
}
|
|
3808
|
-
}
|
|
3809
|
-
const body = output.length > 0 ? output.join("\n") : "No matches found";
|
|
3810
|
-
const notices = [];
|
|
3811
|
-
if (matchLimitReached) notices.push(`${limit} matches limit reached. Refine pattern or raise limit.`);
|
|
3812
|
-
if (lineTruncated) notices.push(`Some lines were truncated to ${MAX_GREP_LINE_CHARS} characters.`);
|
|
3813
|
-
return makeStructuredToolOutput({
|
|
3814
|
-
target: params.path ?? ".",
|
|
3815
|
-
path: params.path ?? ".",
|
|
3816
|
-
truncated: matchLimitReached || lineTruncated,
|
|
3817
|
-
context,
|
|
3818
|
-
...params.glob ? { glob: params.glob } : void 0,
|
|
3819
|
-
line_count: output.length,
|
|
3820
|
-
lines: body === "No matches found" ? [] : body.split("\n"),
|
|
3821
|
-
match_count: matchCount,
|
|
3822
|
-
pattern: params.pattern,
|
|
3823
|
-
...notices.length > 0 ? { truncation_reasons: notices } : void 0,
|
|
3824
|
-
...matchLimitReached ? { match_limit_reached: limit } : void 0,
|
|
3825
|
-
...lineTruncated ? { line_truncated: true } : void 0
|
|
3826
|
-
});
|
|
3827
|
-
}
|
|
3828
|
-
function decodeRipgrepText(value) {
|
|
3829
|
-
if (typeof value?.text === "string") return value.text;
|
|
3830
|
-
if (typeof value?.bytes === "string") return Buffer.from(value.bytes, "base64").toString("utf8");
|
|
3831
|
-
return "";
|
|
3832
|
-
}
|
|
3833
|
-
async function grepFilesWithRipgrep(params) {
|
|
3834
|
-
let rootIsDirectory;
|
|
3835
|
-
try {
|
|
3836
|
-
rootIsDirectory = (await params.fs.stat(params.root)).isDirectory();
|
|
3837
|
-
} catch (error) {
|
|
3838
|
-
if (isMissingPathError(error)) return missingPathSearchResult({
|
|
3839
|
-
path: params.path ?? ".",
|
|
3840
|
-
displayPath: params.path ?? "."
|
|
3841
|
-
});
|
|
3842
|
-
throw error;
|
|
3843
|
-
}
|
|
3844
|
-
const location = getRipgrepSearchLocation(params.root, rootIsDirectory);
|
|
3845
|
-
const args = [
|
|
3846
|
-
"--json",
|
|
3847
|
-
"--line-number",
|
|
3848
|
-
"--hidden",
|
|
3849
|
-
"--max-count",
|
|
3850
|
-
String(params.limit + 1)
|
|
3851
|
-
];
|
|
3852
|
-
if (params.ignoreCase) args.push("--ignore-case");
|
|
3853
|
-
if (params.literal) args.push("--fixed-strings");
|
|
3854
|
-
if (params.glob) args.push("--glob", params.glob);
|
|
3855
|
-
for (const excludedGlob of RIPGREP_EXCLUDED_GLOBS) args.push("--glob", excludedGlob);
|
|
3856
|
-
if (params.context > 0) args.push("--context", String(params.context));
|
|
3857
|
-
args.push("--", params.pattern, location.target);
|
|
3858
|
-
const result = await params.runCommand({
|
|
3859
|
-
cmd: "rg",
|
|
3860
|
-
args,
|
|
3861
|
-
cwd: location.cwd,
|
|
3862
|
-
timeoutMs: DEFAULT_SEARCH_COMMAND_TIMEOUT_MS
|
|
3863
|
-
});
|
|
3864
|
-
if (result.exitCode !== 0 && result.exitCode !== 1) {
|
|
3865
|
-
const detail = result.stderr.trim() || result.stdout.trim() || "command failed";
|
|
3866
|
-
if (/error parsing glob/i.test(detail)) throw new ToolInputError(`Invalid glob: ${params.glob ?? ""}`, { cause: new Error(detail) });
|
|
3867
|
-
if (/regex parse error|error parsing regex|is not allowed in a regex/i.test(detail)) throw new ToolInputError(`Invalid regex pattern: ${params.pattern}`, { cause: new Error(detail) });
|
|
3868
|
-
throw new Error(`ripgrep search failed: ${detail}`);
|
|
3869
|
-
}
|
|
3870
|
-
const recordsByPath = /* @__PURE__ */ new Map();
|
|
3871
|
-
const pathOrder = [];
|
|
3872
|
-
let totalMatches = 0;
|
|
3873
|
-
let parsedRecordCount = 0;
|
|
3874
|
-
for (const rawLine of normalizeToLf$1(result.stdout).split("\n")) {
|
|
3875
|
-
if (!rawLine) continue;
|
|
3876
|
-
let record;
|
|
3877
|
-
try {
|
|
3878
|
-
record = JSON.parse(rawLine);
|
|
3879
|
-
} catch (error) {
|
|
3880
|
-
throw new Error("ripgrep returned invalid JSON output", { cause: error });
|
|
3881
|
-
}
|
|
3882
|
-
parsedRecordCount += 1;
|
|
3883
|
-
if (record.type !== "match" && record.type !== "context") continue;
|
|
3884
|
-
const line = record.data?.line_number;
|
|
3885
|
-
const rawPath = decodeRipgrepText(record.data?.path);
|
|
3886
|
-
if (!line || !rawPath) continue;
|
|
3887
|
-
const absolutePath = rawPath.startsWith("/") ? path.posix.normalize(rawPath) : path.posix.resolve(location.cwd, rawPath);
|
|
3888
|
-
const displayPath = rootIsDirectory ? path.posix.relative(params.root, absolutePath) : path.posix.basename(absolutePath);
|
|
3889
|
-
let records = recordsByPath.get(displayPath);
|
|
3890
|
-
if (!records) {
|
|
3891
|
-
records = [];
|
|
3892
|
-
recordsByPath.set(displayPath, records);
|
|
3893
|
-
pathOrder.push(displayPath);
|
|
3894
|
-
}
|
|
3895
|
-
const matched = record.type === "match";
|
|
3896
|
-
if (matched) totalMatches += 1;
|
|
3897
|
-
records.push({
|
|
3898
|
-
line,
|
|
3899
|
-
matched,
|
|
3900
|
-
text: decodeRipgrepText(record.data?.lines).replace(/\r?\n$/, "")
|
|
3901
|
-
});
|
|
3902
|
-
}
|
|
3903
|
-
let remainingMatches = params.limit;
|
|
3904
|
-
const output = [];
|
|
3905
|
-
let lineTruncated = false;
|
|
3906
|
-
for (const displayPath of pathOrder) {
|
|
3907
|
-
const records = recordsByPath.get(displayPath) ?? [];
|
|
3908
|
-
const selectedMatchLines = [];
|
|
3909
|
-
for (const record of records) if (record.matched && remainingMatches > 0) {
|
|
3910
|
-
selectedMatchLines.push(record.line);
|
|
3911
|
-
remainingMatches -= 1;
|
|
3912
|
-
}
|
|
3913
|
-
if (selectedMatchLines.length === 0) continue;
|
|
3914
|
-
const selectedMatchSet = new Set(selectedMatchLines);
|
|
3915
|
-
const emittedLines = /* @__PURE__ */ new Set();
|
|
3916
|
-
for (const record of records) {
|
|
3917
|
-
if (emittedLines.has(record.line)) continue;
|
|
3918
|
-
if (!selectedMatchLines.some((matchLine) => Math.abs(record.line - matchLine) <= params.context)) continue;
|
|
3919
|
-
emittedLines.add(record.line);
|
|
3920
|
-
const truncated = truncateGrepLine(record.text);
|
|
3921
|
-
lineTruncated ||= truncated.truncated;
|
|
3922
|
-
const separator = selectedMatchSet.has(record.line) ? ":" : "-";
|
|
3923
|
-
output.push(`${displayPath}${separator}${record.line}${separator} ${truncated.line}`);
|
|
3924
|
-
}
|
|
3925
|
-
}
|
|
3926
|
-
const matchCount = Math.min(totalMatches, params.limit);
|
|
3927
|
-
const matchLimitReached = totalMatches > params.limit;
|
|
3928
|
-
const body = output.length > 0 ? output.join("\n") : "No matches found";
|
|
3929
|
-
const notices = [];
|
|
3930
|
-
if (matchLimitReached) notices.push(`${params.limit} matches limit reached. Refine pattern or raise limit.`);
|
|
3931
|
-
if (lineTruncated) notices.push(`Some lines were truncated to ${MAX_GREP_LINE_CHARS} characters.`);
|
|
3932
|
-
const response = makeStructuredToolOutput({
|
|
3933
|
-
target: params.path ?? ".",
|
|
3934
|
-
path: params.path ?? ".",
|
|
3935
|
-
truncated: matchLimitReached || lineTruncated,
|
|
3936
|
-
context: params.context,
|
|
3937
|
-
...params.glob ? { glob: params.glob } : void 0,
|
|
3938
|
-
line_count: output.length,
|
|
3939
|
-
lines: body === "No matches found" ? [] : body.split("\n"),
|
|
3940
|
-
match_count: matchCount,
|
|
3941
|
-
pattern: params.pattern,
|
|
3942
|
-
...notices.length > 0 ? { truncation_reasons: notices } : void 0,
|
|
3943
|
-
...matchLimitReached ? { match_limit_reached: params.limit } : void 0,
|
|
3944
|
-
...lineTruncated ? { line_truncated: true } : void 0
|
|
3945
|
-
});
|
|
3946
|
-
params.onTelemetry?.({
|
|
3947
|
-
emittedLineCount: output.length,
|
|
3948
|
-
limit: params.limit,
|
|
3949
|
-
limitReached: matchLimitReached,
|
|
3950
|
-
parsedRecordCount,
|
|
3951
|
-
rawOutputBytes: Buffer.byteLength(result.stdout, "utf8"),
|
|
3952
|
-
resultBytes: response.content.reduce((total, item) => total + (item.type === "text" ? Buffer.byteLength(item.text, "utf8") : 0), 0),
|
|
3953
|
-
resultCount: matchCount
|
|
3954
|
-
});
|
|
3955
|
-
return response;
|
|
3956
|
-
}
|
|
3957
|
-
/** Create the sandbox grep tool definition exposed to the agent. */
|
|
3958
|
-
function createGrepTool() {
|
|
3959
|
-
return zodTool({
|
|
3960
|
-
description: "Search sandbox workspace file contents. Returns bounded matching lines with file paths and line numbers. Respects path/glob filters and includes truncation notices.",
|
|
3961
|
-
annotations: {
|
|
3962
|
-
destructiveHint: false,
|
|
3963
|
-
idempotentHint: true,
|
|
3964
|
-
openWorldHint: false,
|
|
3965
|
-
readOnlyHint: true
|
|
3966
|
-
},
|
|
3967
|
-
inputSchema: z.object({
|
|
3968
|
-
pattern: z.string().min(1).describe("Regex pattern or literal text to search for."),
|
|
3969
|
-
path: z.string().min(1).describe("Directory or file path in the sandbox workspace. Defaults to the workspace root.").optional(),
|
|
3970
|
-
glob: z.string().min(1).describe("Optional glob filter such as '*.ts' or '**/*.test.ts'.").optional(),
|
|
3971
|
-
ignore_case: booleanInput$2("Whether matching should ignore case.").optional(),
|
|
3972
|
-
literal: booleanInput$2("Treat pattern as literal text instead of regex.").optional(),
|
|
3973
|
-
context: z.coerce.number().int().min(0).describe("Number of surrounding context lines to include.").optional(),
|
|
3974
|
-
limit: z.coerce.number().int().min(1).describe("Maximum matches to return. Defaults to 100.").optional()
|
|
3975
|
-
}),
|
|
3976
|
-
outputSchema: juniorToolOutputSchema,
|
|
3977
|
-
execute: async () => {
|
|
3978
|
-
throw new Error("grep can only run when sandbox execution is enabled.");
|
|
3979
|
-
}
|
|
3980
|
-
});
|
|
3981
|
-
}
|
|
3982
|
-
// src/chat/tools/sandbox/list-dir.ts
|
|
3983
|
-
const DEFAULT_LIST_LIMIT = 500;
|
|
3984
|
-
/** List workspace directories without forcing the model through shell output. */
|
|
3985
|
-
async function listDir(params) {
|
|
3986
|
-
const dirPath = resolveWorkspacePath(params.path);
|
|
3987
|
-
const limit = positiveInteger$1(params.limit) ?? DEFAULT_LIST_LIMIT;
|
|
3988
|
-
let stat;
|
|
3989
|
-
try {
|
|
3990
|
-
stat = await params.fs.stat(dirPath);
|
|
3991
|
-
} catch (error) {
|
|
3992
|
-
if (isMissingPathError(error)) return missingPathSearchResult({ path: params.path ?? "." });
|
|
3993
|
-
throw error;
|
|
3994
|
-
}
|
|
3995
|
-
if (!stat.isDirectory()) throw new ToolInputError(`Not a directory: ${params.path ?? "."}`);
|
|
3996
|
-
let entries;
|
|
3997
|
-
try {
|
|
3998
|
-
entries = (await params.fs.readdir(dirPath)).sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
|
|
3999
|
-
} catch (error) {
|
|
4000
|
-
if (isMissingPathError(error)) return missingPathSearchResult({ path: params.path ?? "." });
|
|
4001
|
-
throw error;
|
|
4002
|
-
}
|
|
4003
|
-
const output = [];
|
|
4004
|
-
let entryLimitReached = false;
|
|
4005
|
-
for (const entry of entries) {
|
|
4006
|
-
if (output.length >= limit) {
|
|
4007
|
-
entryLimitReached = true;
|
|
4008
|
-
break;
|
|
4009
|
-
}
|
|
4010
|
-
const entryPath = path.posix.join(dirPath, entry);
|
|
4011
|
-
try {
|
|
4012
|
-
const entryStat = await params.fs.stat(entryPath);
|
|
4013
|
-
output.push(`${entry}${entryStat.isDirectory() ? "/" : ""}`);
|
|
4014
|
-
} catch (error) {
|
|
4015
|
-
if (isMissingPathError(error)) return missingPathSearchResult({
|
|
4016
|
-
path: params.path ?? ".",
|
|
4017
|
-
missingPath: entryPath
|
|
4018
|
-
});
|
|
4019
|
-
throw error;
|
|
4020
|
-
}
|
|
4021
|
-
}
|
|
4022
|
-
const body = output.length > 0 ? output.join("\n") : "(empty directory)";
|
|
4023
|
-
const notices = [];
|
|
4024
|
-
if (entryLimitReached) notices.push(`${limit} entries limit reached. Use a higher limit to continue.`);
|
|
4025
|
-
return makeStructuredToolOutput({
|
|
4026
|
-
target: params.path ?? ".",
|
|
4027
|
-
path: params.path ?? ".",
|
|
4028
|
-
truncated: entryLimitReached,
|
|
4029
|
-
entries: body === "(empty directory)" ? [] : body.split("\n"),
|
|
4030
|
-
entry_count: output.length,
|
|
4031
|
-
total_entries: entries.length,
|
|
4032
|
-
...notices.length > 0 ? { truncation_reasons: notices } : void 0,
|
|
4033
|
-
...entryLimitReached ? { entry_limit_reached: limit } : void 0
|
|
4034
|
-
});
|
|
4035
|
-
}
|
|
4036
|
-
/** Create the sandbox directory listing tool definition exposed to the agent. */
|
|
4037
|
-
function createListDirTool() {
|
|
4038
|
-
return zodTool({
|
|
4039
|
-
description: "List a sandbox workspace directory. Returns sorted entries with '/' suffixes for directories and bounded truncation notices.",
|
|
4040
|
-
annotations: {
|
|
4041
|
-
destructiveHint: false,
|
|
4042
|
-
idempotentHint: true,
|
|
4043
|
-
openWorldHint: false,
|
|
4044
|
-
readOnlyHint: true
|
|
4045
|
-
},
|
|
4046
|
-
inputSchema: z.object({
|
|
4047
|
-
path: z.string().min(1).describe("Directory path in the sandbox workspace. Defaults to the workspace root.").optional(),
|
|
4048
|
-
limit: z.coerce.number().int().min(1).describe("Maximum entries to return. Defaults to 500.").optional()
|
|
4049
|
-
}),
|
|
4050
|
-
outputSchema: juniorToolOutputSchema,
|
|
4051
|
-
execute: async () => {
|
|
4052
|
-
throw new Error("listDir can only run when sandbox execution is enabled.");
|
|
4053
|
-
}
|
|
4054
|
-
});
|
|
4055
|
-
}
|
|
4056
3397
|
const FULL_RESULT_DIR = "/tmp/jr";
|
|
4057
3398
|
function fullResultPath(toolCallId) {
|
|
4058
3399
|
const id = createHash("sha256").update(toolCallId).digest("hex").slice(0, 8);
|
|
@@ -4074,8 +3415,8 @@ function headAndTail(text, chars) {
|
|
|
4074
3415
|
};
|
|
4075
3416
|
}
|
|
4076
3417
|
/**
|
|
4077
|
-
* Pretty-print JSON so the saved file has many lines. readFile pages by line
|
|
4078
|
-
*
|
|
3418
|
+
* Pretty-print JSON so the saved file has many lines. readFile pages by line,
|
|
3419
|
+
* so one long line is hard to read.
|
|
4079
3420
|
*/
|
|
4080
3421
|
function fileText(text) {
|
|
4081
3422
|
try {
|
|
@@ -4221,7 +3562,7 @@ function missingFileResult(path) {
|
|
|
4221
3562
|
/** Create the sandbox read tool definition exposed to the agent. */
|
|
4222
3563
|
function createReadFileTool() {
|
|
4223
3564
|
return zodTool({
|
|
4224
|
-
description: "Read a bounded line range from a file in the sandbox workspace. Use when you need exact file contents to verify facts or make edits safely.
|
|
3565
|
+
description: "Read a bounded line range from a file in the sandbox workspace. Use when you need exact file contents to verify facts or make edits safely. Use bash (rg, find, ls) for broad discovery.",
|
|
4225
3566
|
annotations: {
|
|
4226
3567
|
destructiveHint: false,
|
|
4227
3568
|
idempotentHint: true,
|
|
@@ -4259,9 +3600,6 @@ const SANDBOX_TOOL_NAMES = /* @__PURE__ */ new Set([
|
|
|
4259
3600
|
"bash",
|
|
4260
3601
|
"readFile",
|
|
4261
3602
|
"editFile",
|
|
4262
|
-
"grep",
|
|
4263
|
-
"findFiles",
|
|
4264
|
-
"listDir",
|
|
4265
3603
|
"writeFile"
|
|
4266
3604
|
]);
|
|
4267
3605
|
function parseEnv(raw) {
|
|
@@ -4350,28 +3688,16 @@ function createSandbox(options) {
|
|
|
4350
3688
|
onWorkspacePrepare: options.prepareWorkspace,
|
|
4351
3689
|
onSandboxRefChanged: options.onSandboxRefChanged
|
|
4352
3690
|
});
|
|
4353
|
-
const createToolCallContext = (signal
|
|
3691
|
+
const createToolCallContext = (signal) => {
|
|
4354
3692
|
let fileSystemPromise;
|
|
4355
|
-
let commandRunnerPromise;
|
|
4356
3693
|
return {
|
|
4357
3694
|
signal,
|
|
4358
|
-
setToolCallSpanAttributes,
|
|
4359
3695
|
fileSystem() {
|
|
4360
3696
|
signal?.throwIfAborted();
|
|
4361
3697
|
return fileSystemPromise ??= runtime.tools(signal).then(({ fs }) => {
|
|
4362
3698
|
signal?.throwIfAborted();
|
|
4363
3699
|
return bindSandboxFileSystem(fs, signal);
|
|
4364
3700
|
});
|
|
4365
|
-
},
|
|
4366
|
-
commandRunner() {
|
|
4367
|
-
signal?.throwIfAborted();
|
|
4368
|
-
return commandRunnerPromise ??= runtime.tools(signal).then(({ runCommand }) => {
|
|
4369
|
-
signal?.throwIfAborted();
|
|
4370
|
-
return async (input) => await runCommand({
|
|
4371
|
-
...input,
|
|
4372
|
-
...signal ? { signal } : void 0
|
|
4373
|
-
});
|
|
4374
|
-
});
|
|
4375
3701
|
}
|
|
4376
3702
|
};
|
|
4377
3703
|
};
|
|
@@ -4380,21 +3706,6 @@ function createSandbox(options) {
|
|
|
4380
3706
|
await runtime.refreshNetworkPolicy(getTracePropagationHeaders());
|
|
4381
3707
|
return await callback(setSpanAttributes);
|
|
4382
3708
|
});
|
|
4383
|
-
const searchTelemetryAttributes = (telemetry) => ({
|
|
4384
|
-
"app.sandbox.search.raw_output_bytes": telemetry.rawOutputBytes,
|
|
4385
|
-
"app.sandbox.search.parsed_records": telemetry.parsedRecordCount,
|
|
4386
|
-
"app.sandbox.search.result_count": telemetry.resultCount,
|
|
4387
|
-
"app.sandbox.search.emitted_lines": telemetry.emittedLineCount,
|
|
4388
|
-
"app.sandbox.search.result_bytes": telemetry.resultBytes,
|
|
4389
|
-
"app.sandbox.search.limit": telemetry.limit,
|
|
4390
|
-
"app.sandbox.search.limit_reached": telemetry.limitReached
|
|
4391
|
-
});
|
|
4392
|
-
const recordSearchTelemetry = (telemetry, setSearchSpanAttributes, setToolCallSpanAttributes) => {
|
|
4393
|
-
const attributes = searchTelemetryAttributes(telemetry);
|
|
4394
|
-
for (const setAttributes of [setSearchSpanAttributes, setToolCallSpanAttributes]) try {
|
|
4395
|
-
setAttributes?.(attributes);
|
|
4396
|
-
} catch {}
|
|
4397
|
-
};
|
|
4398
3709
|
const logSandboxBootRequest = (trigger, details = {}) => {
|
|
4399
3710
|
if (runtime.sandboxRef()) return;
|
|
4400
3711
|
logInfo("sandbox.boot.requested", {
|
|
@@ -4552,66 +3863,9 @@ function createSandbox(options) {
|
|
|
4552
3863
|
return response;
|
|
4553
3864
|
});
|
|
4554
3865
|
};
|
|
4555
|
-
const executeGrepTool = async (rawInput, context) => {
|
|
4556
|
-
const pattern = String(rawInput.pattern ?? "");
|
|
4557
|
-
if (!pattern) throw new ToolInputError("pattern is required");
|
|
4558
|
-
logSandboxBootRequest("tool.grep");
|
|
4559
|
-
const contextLines = positiveInteger$1(rawInput.context);
|
|
4560
|
-
const limit = positiveInteger$1(rawInput.limit);
|
|
4561
|
-
const fileSystem = await context.fileSystem();
|
|
4562
|
-
return await withSandboxToolSpan("sandbox.grep", "sandbox.fs.search", { "app.sandbox.pattern.length": pattern.length }, async (setSearchSpanAttributes) => {
|
|
4563
|
-
const response = await grepFiles({
|
|
4564
|
-
fs: fileSystem,
|
|
4565
|
-
runCommand: await context.commandRunner(),
|
|
4566
|
-
onTelemetry: (telemetry) => recordSearchTelemetry(telemetry, setSearchSpanAttributes, context.setToolCallSpanAttributes),
|
|
4567
|
-
pattern,
|
|
4568
|
-
...typeof rawInput.path === "string" ? { path: rawInput.path } : void 0,
|
|
4569
|
-
...typeof rawInput.glob === "string" ? { glob: rawInput.glob } : void 0,
|
|
4570
|
-
...typeof rawInput.ignoreCase === "boolean" ? { ignoreCase: rawInput.ignoreCase } : void 0,
|
|
4571
|
-
...typeof rawInput.literal === "boolean" ? { literal: rawInput.literal } : void 0,
|
|
4572
|
-
...contextLines ? { context: contextLines } : void 0,
|
|
4573
|
-
...limit ? { limit } : void 0
|
|
4574
|
-
});
|
|
4575
|
-
setSpanStatus("ok");
|
|
4576
|
-
return response;
|
|
4577
|
-
});
|
|
4578
|
-
};
|
|
4579
|
-
const executeFindFilesTool = async (rawInput, context) => {
|
|
4580
|
-
const pattern = String(rawInput.pattern ?? "");
|
|
4581
|
-
if (!pattern) throw new ToolInputError("pattern is required");
|
|
4582
|
-
logSandboxBootRequest("tool.findFiles");
|
|
4583
|
-
const limit = positiveInteger$1(rawInput.limit);
|
|
4584
|
-
const fileSystem = await context.fileSystem();
|
|
4585
|
-
return await withSandboxToolSpan("sandbox.findFiles", "sandbox.fs.find", { "app.sandbox.pattern.length": pattern.length }, async (setSearchSpanAttributes) => {
|
|
4586
|
-
const response = await findFiles({
|
|
4587
|
-
fs: fileSystem,
|
|
4588
|
-
runCommand: await context.commandRunner(),
|
|
4589
|
-
onTelemetry: (telemetry) => recordSearchTelemetry(telemetry, setSearchSpanAttributes, context.setToolCallSpanAttributes),
|
|
4590
|
-
pattern,
|
|
4591
|
-
...typeof rawInput.path === "string" ? { path: rawInput.path } : void 0,
|
|
4592
|
-
...limit ? { limit } : void 0
|
|
4593
|
-
});
|
|
4594
|
-
setSpanStatus("ok");
|
|
4595
|
-
return response;
|
|
4596
|
-
});
|
|
4597
|
-
};
|
|
4598
|
-
const executeListDirTool = async (rawInput, context) => {
|
|
4599
|
-
logSandboxBootRequest("tool.listDir");
|
|
4600
|
-
const limit = positiveInteger$1(rawInput.limit);
|
|
4601
|
-
const fileSystem = await context.fileSystem();
|
|
4602
|
-
return await withSandboxToolSpan("sandbox.listDir", "sandbox.fs.list", {}, async () => {
|
|
4603
|
-
const response = await listDir({
|
|
4604
|
-
fs: fileSystem,
|
|
4605
|
-
...typeof rawInput.path === "string" ? { path: rawInput.path } : void 0,
|
|
4606
|
-
...limit ? { limit } : void 0
|
|
4607
|
-
});
|
|
4608
|
-
setSpanStatus("ok");
|
|
4609
|
-
return response;
|
|
4610
|
-
});
|
|
4611
|
-
};
|
|
4612
3866
|
const execute = async (params) => {
|
|
4613
3867
|
const rawInput = params.input ?? {};
|
|
4614
|
-
const context = createToolCallContext(params.signal
|
|
3868
|
+
const context = createToolCallContext(params.signal);
|
|
4615
3869
|
const bashCommand = params.toolName === "bash" ? String(rawInput.command ?? "").trim() : void 0;
|
|
4616
3870
|
if (params.toolName === "bash") {
|
|
4617
3871
|
if (!bashCommand) throw new ToolInputError("command is required");
|
|
@@ -4620,9 +3874,6 @@ function createSandbox(options) {
|
|
|
4620
3874
|
if (bashCommand !== void 0) return await executeBashTool(rawInput, bashCommand, context);
|
|
4621
3875
|
if (params.toolName === "readFile") return await executeReadFileTool(rawInput, context);
|
|
4622
3876
|
if (params.toolName === "editFile") return await executeEditFileTool(rawInput, context);
|
|
4623
|
-
if (params.toolName === "grep") return await executeGrepTool(rawInput, context);
|
|
4624
|
-
if (params.toolName === "findFiles") return await executeFindFilesTool(rawInput, context);
|
|
4625
|
-
if (params.toolName === "listDir") return await executeListDirTool(rawInput, context);
|
|
4626
3877
|
if (params.toolName === "writeFile") return await executeWriteFileTool(rawInput, context);
|
|
4627
3878
|
} catch (error) {
|
|
4628
3879
|
params.signal?.throwIfAborted();
|
|
@@ -5211,6 +4462,8 @@ var McpToolManager = class {
|
|
|
5211
4462
|
serviceAccountProviders = /* @__PURE__ */ new Set();
|
|
5212
4463
|
clientPromisesByProvider = /* @__PURE__ */ new Map();
|
|
5213
4464
|
toolsByProvider = /* @__PURE__ */ new Map();
|
|
4465
|
+
/** Clients of forgotten providers. `close()` still owns their transports. */
|
|
4466
|
+
forgottenClients = [];
|
|
5214
4467
|
options;
|
|
5215
4468
|
constructor(plugins, options = {}) {
|
|
5216
4469
|
this.options = options;
|
|
@@ -5247,13 +4500,18 @@ var McpToolManager = class {
|
|
|
5247
4500
|
}
|
|
5248
4501
|
async close() {
|
|
5249
4502
|
let firstError;
|
|
5250
|
-
for (const client of [
|
|
4503
|
+
for (const client of [
|
|
4504
|
+
...this.clientsByProvider.values(),
|
|
4505
|
+
...this.actorClientsByProvider.values(),
|
|
4506
|
+
...this.forgottenClients
|
|
4507
|
+
]) try {
|
|
5251
4508
|
await client.close();
|
|
5252
4509
|
} catch (error) {
|
|
5253
4510
|
firstError ??= error;
|
|
5254
4511
|
}
|
|
5255
4512
|
this.clientsByProvider.clear();
|
|
5256
4513
|
this.actorClientsByProvider.clear();
|
|
4514
|
+
this.forgottenClients.length = 0;
|
|
5257
4515
|
this.serviceAccountProviders.clear();
|
|
5258
4516
|
this.toolsByProvider.clear();
|
|
5259
4517
|
this.activeProviders.clear();
|
|
@@ -5444,6 +4702,10 @@ var McpToolManager = class {
|
|
|
5444
4702
|
return true;
|
|
5445
4703
|
}
|
|
5446
4704
|
forgetProvider(provider) {
|
|
4705
|
+
for (const clients of [this.clientsByProvider, this.actorClientsByProvider]) {
|
|
4706
|
+
const client = clients.get(provider);
|
|
4707
|
+
if (client) this.forgottenClients.push(client);
|
|
4708
|
+
}
|
|
5447
4709
|
this.clientsByProvider.delete(provider);
|
|
5448
4710
|
this.actorClientsByProvider.delete(provider);
|
|
5449
4711
|
this.serviceAccountProviders.delete(provider);
|
|
@@ -5529,11 +4791,19 @@ function createBashTool() {
|
|
|
5529
4791
|
}
|
|
5530
4792
|
});
|
|
5531
4793
|
}
|
|
4794
|
+
// src/chat/sandbox/tool-source.ts
|
|
4795
|
+
/** Deferred tool catalog source for sandbox preview URLs. */
|
|
4796
|
+
const SANDBOX_TOOL_SOURCE = {
|
|
4797
|
+
id: "sandbox",
|
|
4798
|
+
description: "Create public preview URLs for servers in the sandbox."
|
|
4799
|
+
};
|
|
5532
4800
|
// src/chat/tools/sandbox/create-preview.ts
|
|
5533
4801
|
const outputSchema$6 = juniorToolOutputSchema.extend({ url: z.string().url() });
|
|
5534
4802
|
/** Create a tool that gives a running sandbox server a public preview URL. */
|
|
5535
4803
|
function createCreatePreviewTool(createPreview) {
|
|
5536
4804
|
return zodTool({
|
|
4805
|
+
exposure: "deferred",
|
|
4806
|
+
source: SANDBOX_TOOL_SOURCE,
|
|
5537
4807
|
annotations: {
|
|
5538
4808
|
destructiveHint: false,
|
|
5539
4809
|
idempotentHint: true,
|
|
@@ -5568,6 +4838,12 @@ async function readSandboxImage(path, readFile, maxBytes) {
|
|
|
5568
4838
|
mimeType
|
|
5569
4839
|
};
|
|
5570
4840
|
}
|
|
4841
|
+
// src/chat/artifacts/tool-source.ts
|
|
4842
|
+
/** Deferred tool catalog source for generated and published images. */
|
|
4843
|
+
const IMAGES_TOOL_SOURCE = {
|
|
4844
|
+
id: "images",
|
|
4845
|
+
description: "Generate images, and publish or unpublish public image URLs."
|
|
4846
|
+
};
|
|
5571
4847
|
// src/chat/tools/web/image-generate.ts
|
|
5572
4848
|
const MAX_REQUEST_IMAGE_BYTES = 3145728;
|
|
5573
4849
|
const MAX_SOURCE_IMAGE_BYTES = 26214400;
|
|
@@ -5692,6 +4968,8 @@ function extensionForMediaType$1(mediaType) {
|
|
|
5692
4968
|
/** Create the image tool with sandbox artifact guidance matched to file-send capability. */
|
|
5693
4969
|
function createImageGenerateTool(hooks, options, deps = {}) {
|
|
5694
4970
|
return zodTool({
|
|
4971
|
+
exposure: "deferred",
|
|
4972
|
+
source: IMAGES_TOOL_SOURCE,
|
|
5695
4973
|
annotations: {
|
|
5696
4974
|
destructiveHint: false,
|
|
5697
4975
|
idempotentHint: false,
|
|
@@ -6261,8 +5539,8 @@ async function listAgentRelatives(input) {
|
|
|
6261
5539
|
// src/chat/agent-invocations/search-top-level.ts
|
|
6262
5540
|
/**
|
|
6263
5541
|
* Search public root Conversations in the tenant of `requesterConversationId`.
|
|
6264
|
-
* `viewer
|
|
6265
|
-
*
|
|
5542
|
+
* `viewer` is the person of the current Turn. Newest activity first, or best
|
|
5543
|
+
* match for a query.
|
|
6266
5544
|
*/
|
|
6267
5545
|
async function searchTopLevelAgents(args) {
|
|
6268
5546
|
const { requesterConversationId, search, viewer } = args;
|
|
@@ -6285,19 +5563,19 @@ async function searchTopLevelAgents(args) {
|
|
|
6285
5563
|
eq(juniorDestinations.visibility, "public"),
|
|
6286
5564
|
search.annotation ? treeHasAnnotationKey(juniorConversations.conversationId, search.annotation) : void 0,
|
|
6287
5565
|
search.conversationIds ? inArray(juniorConversations.conversationId, [...search.conversationIds]) : void 0,
|
|
6288
|
-
|
|
5566
|
+
search.includeArchived ? void 0 : isNull(juniorConversations.archivedAt),
|
|
6289
5567
|
query ? or(sql`${searchVector} @@ ${tsquery}`, ilike(juniorConversations.title, `%${escapeLike(query)}%`)) : void 0
|
|
6290
5568
|
];
|
|
6291
5569
|
const newestFirst = desc(juniorConversations.lastActivityAt);
|
|
6292
5570
|
const order = query ? [desc(sql`coalesce(ts_rank_cd(${searchVector}, ${tsquery}), 0)`), newestFirst] : [newestFirst];
|
|
6293
5571
|
return (await db.select({
|
|
6294
|
-
archivedAt:
|
|
5572
|
+
archivedAt: juniorConversations.archivedAt,
|
|
6295
5573
|
briefContent: briefs.content,
|
|
6296
5574
|
conversationId: juniorConversations.conversationId,
|
|
6297
5575
|
lastActivityAt: juniorConversations.lastActivityAt,
|
|
6298
5576
|
status: juniorConversations.executionStatus,
|
|
6299
5577
|
title: juniorConversations.title
|
|
6300
|
-
}).from(juniorConversations).innerJoin(juniorDestinations, eq(juniorDestinations.id, juniorConversations.destinationId)).leftJoin(
|
|
5578
|
+
}).from(juniorConversations).innerJoin(juniorDestinations, eq(juniorDestinations.id, juniorConversations.destinationId)).leftJoin(briefs, and(eq(briefs.conversationId, juniorConversations.conversationId), notExists(db.select({ one: sql`1` }).from(newer).where(and(eq(newer.conversationId, briefs.conversationId), gt(newer.version, briefs.version)))))).where(and(...conditions)).orderBy(...order).limit(search.limit)).map((row) => {
|
|
6301
5579
|
const brief = row.briefContent ? parseStoredBrief(row.briefContent) : void 0;
|
|
6302
5580
|
return {
|
|
6303
5581
|
archived: row.archivedAt !== null,
|
|
@@ -6312,6 +5590,12 @@ async function searchTopLevelAgents(args) {
|
|
|
6312
5590
|
function escapeLike(value) {
|
|
6313
5591
|
return value.replace(/[\\%_]/g, (match) => `\\${match}`);
|
|
6314
5592
|
}
|
|
5593
|
+
// src/chat/agent-invocations/tool-source.ts
|
|
5594
|
+
/** Deferred tool catalog source for finding and stopping agents. */
|
|
5595
|
+
const AGENTS_TOOL_SOURCE = {
|
|
5596
|
+
id: "agents",
|
|
5597
|
+
description: "Find related agents, or stop a child agent."
|
|
5598
|
+
};
|
|
6315
5599
|
// src/chat/tools/runtime/search-agents.ts
|
|
6316
5600
|
const TASK_MAX_LENGTH = 1e3;
|
|
6317
5601
|
const ERROR_MAX_LENGTH = 500;
|
|
@@ -6365,7 +5649,7 @@ const listedAgentSchema = z.object({
|
|
|
6365
5649
|
title: z.string().optional().describe("Short display title of the latest task, or of a top-level conversation"),
|
|
6366
5650
|
summary: z.string().optional().describe("Summary from the latest Brief of a top-level conversation"),
|
|
6367
5651
|
dashboard_url: z.string().url().optional().describe("Dashboard link of a top-level conversation"),
|
|
6368
|
-
archived: z.literal(true).optional().describe("
|
|
5652
|
+
archived: z.literal(true).optional().describe("The conversation is archived."),
|
|
6369
5653
|
error: z.string().optional().describe("Why the agent is blocked, failed, or stopped"),
|
|
6370
5654
|
updated_at: z.string().describe("Time of the latest change")
|
|
6371
5655
|
}).strict();
|
|
@@ -6412,7 +5696,7 @@ const searchAgentsInputSchema = z.object({
|
|
|
6412
5696
|
conversation_ids: z.array(z.string().trim().min(1)).min(1).max(CONVERSATION_IDS_MAX).nullable().optional().describe("Return only these conversation IDs."),
|
|
6413
5697
|
annotation: z.string().trim().min(1).max(256).nullable().optional().describe("Linked resource key, such as owner/repo#123 for a pull request. Matches that key, or nested children that continue with #. Matches a conversation when it or one of its child agents created, changed, or read the resource."),
|
|
6414
5698
|
query: z.string().trim().min(1).max(200).nullable().optional().describe("Words to match. relatives: the name, title, or task. top_level: the latest Brief or the title."),
|
|
6415
|
-
include_archived: z.boolean().nullable().optional().describe("Include conversations
|
|
5699
|
+
include_archived: z.boolean().nullable().optional().describe("Include archived conversations. Default false. This changes only top_level results."),
|
|
6416
5700
|
limit: z.number().int().min(1).max(TOP_LEVEL_MAX_LIMIT).nullable().optional().describe(`Maximum top_level results. Default ${TOP_LEVEL_DEFAULT_LIMIT}; max ${TOP_LEVEL_MAX_LIMIT}. Relatives are not limited.`)
|
|
6417
5701
|
}).strict();
|
|
6418
5702
|
/**
|
|
@@ -6422,6 +5706,8 @@ const searchAgentsInputSchema = z.object({
|
|
|
6422
5706
|
*/
|
|
6423
5707
|
function createSearchAgentsTool(context) {
|
|
6424
5708
|
return zodTool({
|
|
5709
|
+
exposure: "deferred",
|
|
5710
|
+
source: AGENTS_TOOL_SOURCE,
|
|
6425
5711
|
description: "Search the agents that this conversation can see, with the state recorded by the runtime. Relatives are the child agents it started and, for a child agent, itself, its parent, and its siblings. Top-level agents are other public root conversations in this workspace. messageAgent can send to one only when this conversation is public too. Results of child agents arrive as new tasks, not through this tool.",
|
|
6426
5712
|
annotations: {
|
|
6427
5713
|
destructiveHint: false,
|
|
@@ -6488,6 +5774,16 @@ var AgentInvocationLimitError = class extends Error {
|
|
|
6488
5774
|
this.name = "AgentInvocationLimitError";
|
|
6489
5775
|
}
|
|
6490
5776
|
};
|
|
5777
|
+
/**
|
|
5778
|
+
* The Conversation that calls spawnAgent is too deep to start child agents,
|
|
5779
|
+
* or its parent chain does not end at a root.
|
|
5780
|
+
*/
|
|
5781
|
+
var AgentDepthLimitError = class extends Error {
|
|
5782
|
+
constructor(maxAgentDepth) {
|
|
5783
|
+
super(`This agent cannot start child agents: only ${maxAgentDepth} level(s) of child agents can start their own`);
|
|
5784
|
+
this.name = "AgentDepthLimitError";
|
|
5785
|
+
}
|
|
5786
|
+
};
|
|
6491
5787
|
/** A child agent already has the maximum number of open tasks. */
|
|
6492
5788
|
var AgentMessageQueueFullError = class extends Error {
|
|
6493
5789
|
constructor(limit) {
|
|
@@ -6616,18 +5912,912 @@ function createSpawnAgentTool(spawnAgent) {
|
|
|
6616
5912
|
} catch (error) {
|
|
6617
5913
|
if (error instanceof AgentNameInUseError) throw new ToolInputError(`${error.message}. Use messageAgent to give it more work, or choose a different name.`, { cause: error });
|
|
6618
5914
|
if (error instanceof AgentInvocationLimitError) throw new ToolInputError(`${error.message}. Wait for active children to finish before spawning more.`, { cause: error });
|
|
5915
|
+
if (error instanceof AgentDepthLimitError) throw new ToolInputError(`${error.message}. Do the work in this agent instead.`, { cause: error });
|
|
6619
5916
|
throw error;
|
|
6620
5917
|
}
|
|
6621
5918
|
return { conversation_id: result.childConversationId };
|
|
6622
5919
|
}
|
|
6623
5920
|
});
|
|
6624
5921
|
}
|
|
5922
|
+
// src/chat/conversations/web-authorization.ts
|
|
5923
|
+
const WEB_AUTHORIZATION_PREFIX = "junior:web_authorization:v1";
|
|
5924
|
+
const WEB_AUTHORIZATION_TTL_MS = 864e5;
|
|
5925
|
+
function authorizationKey(conversationId, actorId) {
|
|
5926
|
+
return `${WEB_AUTHORIZATION_PREFIX}:${conversationId}:${actorId}`;
|
|
5927
|
+
}
|
|
5928
|
+
/** Build authorization delivery for one web turn. */
|
|
5929
|
+
function createWebAuthorization(args) {
|
|
5930
|
+
return {
|
|
5931
|
+
createState: async () => randomUUID(),
|
|
5932
|
+
deliver: async (request) => {
|
|
5933
|
+
await getStateAdapter().set(authorizationKey(args.conversationId, args.actorId), JSON.stringify({
|
|
5934
|
+
...request,
|
|
5935
|
+
...args
|
|
5936
|
+
}), WEB_AUTHORIZATION_TTL_MS);
|
|
5937
|
+
}
|
|
5938
|
+
};
|
|
5939
|
+
}
|
|
5940
|
+
/** Read the pending authorization request for one web actor. */
|
|
5941
|
+
async function getWebAuthorization(args) {
|
|
5942
|
+
const value = await getStateAdapter().get(authorizationKey(args.conversationId, args.actorId));
|
|
5943
|
+
if (typeof value !== "string") return void 0;
|
|
5944
|
+
try {
|
|
5945
|
+
const parsed = JSON.parse(value);
|
|
5946
|
+
if (parsed.actorId !== args.actorId || parsed.conversationId !== args.conversationId || typeof parsed.authorizationUrl !== "string" || typeof parsed.label !== "string" || typeof parsed.completionText !== "string") return;
|
|
5947
|
+
return parsed;
|
|
5948
|
+
} catch {
|
|
5949
|
+
return;
|
|
5950
|
+
}
|
|
5951
|
+
}
|
|
5952
|
+
/** Remove a web authorization request after the parked turn continues. */
|
|
5953
|
+
async function deleteWebAuthorization(args) {
|
|
5954
|
+
await getStateAdapter().delete(authorizationKey(args.conversationId, args.actorId));
|
|
5955
|
+
}
|
|
5956
|
+
// src/chat/task-execution/assistant-message.ts
|
|
5957
|
+
/** Store one assistant Message and its Agent history. */
|
|
5958
|
+
async function commitAssistantMessage(args) {
|
|
5959
|
+
const conversationMessageId = recordDeliveredAssistantMessage({
|
|
5960
|
+
cards: args.cards,
|
|
5961
|
+
conversation: args.conversation,
|
|
5962
|
+
...args.quiet ? { quiet: args.quiet } : void 0,
|
|
5963
|
+
sessionId: args.sessionId,
|
|
5964
|
+
source: args.source,
|
|
5965
|
+
text: args.text,
|
|
5966
|
+
userMessageId: args.userMessageId
|
|
5967
|
+
});
|
|
5968
|
+
if (args.deliveryResult?.providerMessageId) markConversationMessage(args.conversation, conversationMessageId, { slackTs: args.deliveryResult.providerMessageId });
|
|
5969
|
+
try {
|
|
5970
|
+
await persistWithRetry(() => commitAcceptedReply({
|
|
5971
|
+
...args.agentMessage ? { agentMessage: args.agentMessage } : void 0,
|
|
5972
|
+
conversation: args.conversation,
|
|
5973
|
+
conversationMessageId,
|
|
5974
|
+
conversationId: args.conversationId,
|
|
5975
|
+
providerConversationBindings: args.deliveryResult?.providerConversationBindings
|
|
5976
|
+
}));
|
|
5977
|
+
} catch (error) {
|
|
5978
|
+
logException(error, "conversation.assistant.message_persist.failed");
|
|
5979
|
+
}
|
|
5980
|
+
}
|
|
5981
|
+
// src/chat/services/context-compaction-telemetry.ts
|
|
5982
|
+
/**
|
|
5983
|
+
* Context compaction telemetry.
|
|
5984
|
+
*
|
|
5985
|
+
* Each compaction gets one `agent.context_compaction` span. The span and its
|
|
5986
|
+
* children, such as the summary `gen_ai.chat` span, carry
|
|
5987
|
+
* `app.compaction.mode`. The `chat.turn` span sums the time that the Turn
|
|
5988
|
+
* waited on compaction, with summary calls and prepared-summary swaps apart.
|
|
5989
|
+
*
|
|
5990
|
+
* Attribute keys do not contain "token": Sentry data scrubbing removes the
|
|
5991
|
+
* values of keys that match it.
|
|
5992
|
+
*/
|
|
5993
|
+
const turnCompactionWait = new AsyncLocalStorage();
|
|
5994
|
+
/** Run one compaction in its span and add its time to the Turn wait. */
|
|
5995
|
+
async function withCompactionSpan(mode, work, callback) {
|
|
5996
|
+
const startedAtMs = performance.now();
|
|
5997
|
+
try {
|
|
5998
|
+
return await runWithLogAttributes({ "app.compaction.mode": mode }, () => withSpan("agent.context_compaction", "agent.context_compaction", {}, callback));
|
|
5999
|
+
} finally {
|
|
6000
|
+
const wait = turnCompactionWait.getStore();
|
|
6001
|
+
if (wait) wait[work] += performance.now() - startedAtMs;
|
|
6002
|
+
}
|
|
6003
|
+
}
|
|
6004
|
+
/** Run one `chat.turn` callback and record its compaction wait, if any. */
|
|
6005
|
+
async function measureTurnCompactionWait(setTurnAttributes, callback) {
|
|
6006
|
+
const wait = {
|
|
6007
|
+
summary: 0,
|
|
6008
|
+
swap: 0
|
|
6009
|
+
};
|
|
6010
|
+
try {
|
|
6011
|
+
return await turnCompactionWait.run(wait, callback);
|
|
6012
|
+
} finally {
|
|
6013
|
+
setTurnAttributes({
|
|
6014
|
+
...wait.summary > 0 ? { "app.turn.compaction_wait_ms": Math.round(wait.summary) } : void 0,
|
|
6015
|
+
...wait.swap > 0 ? { "app.turn.compaction_swap_wait_ms": Math.round(wait.swap) } : void 0
|
|
6016
|
+
});
|
|
6017
|
+
}
|
|
6018
|
+
}
|
|
6019
|
+
/**
|
|
6020
|
+
* Log the provider-reported input of the first model request after a
|
|
6021
|
+
* replacement. It shows when the replacement was still above the threshold.
|
|
6022
|
+
*/
|
|
6023
|
+
function logInputAfterCompaction(args) {
|
|
6024
|
+
logInfo("context_compaction.next_request.completed", {
|
|
6025
|
+
"app.compaction.mode": args.mode,
|
|
6026
|
+
"app.compaction.next_input.size": args.inputSize,
|
|
6027
|
+
"app.compaction.next_input.over_threshold": args.inputSize > args.threshold,
|
|
6028
|
+
"app.compaction.threshold": args.threshold
|
|
6029
|
+
});
|
|
6030
|
+
}
|
|
6031
|
+
// src/chat/task-execution/turn-telemetry.ts
|
|
6032
|
+
/** Read the turn input timing facts from a mailbox batch, oldest first. */
|
|
6033
|
+
function turnInputTelemetry(messages) {
|
|
6034
|
+
const oldest = messages[0];
|
|
6035
|
+
if (!oldest) return void 0;
|
|
6036
|
+
return {
|
|
6037
|
+
count: messages.length,
|
|
6038
|
+
oldestCreatedAtMs: oldest.createdAtMs,
|
|
6039
|
+
oldestReceivedAtMs: oldest.receivedAtMs,
|
|
6040
|
+
traceContexts: messages.flatMap((message) => message.traceContext ?? [])
|
|
6041
|
+
};
|
|
6042
|
+
}
|
|
6043
|
+
const SENTRY_TRACE_PATTERN = /^([0-9a-f]{32})-([0-9a-f]{16})(?:-([01]))?$/;
|
|
6044
|
+
function spanLinks({ sentryTrace }) {
|
|
6045
|
+
const [, traceId, spanId, sampled] = SENTRY_TRACE_PATTERN.exec(sentryTrace) ?? [];
|
|
6046
|
+
return traceId && spanId ? [{ context: {
|
|
6047
|
+
traceId,
|
|
6048
|
+
spanId,
|
|
6049
|
+
traceFlags: sampled === "1" ? 1 : 0
|
|
6050
|
+
} }] : [];
|
|
6051
|
+
}
|
|
6052
|
+
/**
|
|
6053
|
+
* Run a `chat.turn` span in the trace of the first trace context.
|
|
6054
|
+
*
|
|
6055
|
+
* The span links to the other trace contexts and to the span that was active,
|
|
6056
|
+
* such as the worker span. Without a trace context, the span is a child of the
|
|
6057
|
+
* active span. A malformed trace context starts a new trace. The span records
|
|
6058
|
+
* how long the Turn waited on context compaction.
|
|
6059
|
+
*/
|
|
6060
|
+
async function withTurnSpan(context, input, callback) {
|
|
6061
|
+
const [parent, ...others] = input?.traceContexts ?? [];
|
|
6062
|
+
if (!parent) return await withSpan("chat.turn", "chat.turn", context, (set) => measureTurnCompactionWait(set, () => callback(set)));
|
|
6063
|
+
const activeSpan = getActiveSpan();
|
|
6064
|
+
const links = [...others.flatMap(spanLinks), ...activeSpan ? [{ context: activeSpan.spanContext() }] : []];
|
|
6065
|
+
const { baggage, sentryTrace } = parent;
|
|
6066
|
+
return await continueTrace({
|
|
6067
|
+
baggage,
|
|
6068
|
+
sentryTrace
|
|
6069
|
+
}, () => withSpan("chat.turn", "chat.turn", context, async (setSpanAttributes) => {
|
|
6070
|
+
getActiveSpan()?.addLinks(links);
|
|
6071
|
+
return await measureTurnCompactionWait(setSpanAttributes, () => callback(setSpanAttributes));
|
|
6072
|
+
}));
|
|
6073
|
+
}
|
|
6074
|
+
/**
|
|
6075
|
+
* Build the `chat.turn` timing attributes for the oldest input message.
|
|
6076
|
+
*
|
|
6077
|
+
* The provider, the ingress host, and the worker host use separate clocks. A negative
|
|
6078
|
+
* duration is clock skew, not latency, so it is left out.
|
|
6079
|
+
*/
|
|
6080
|
+
function getTurnInputSpanAttributes(input, turnStartedAtMs) {
|
|
6081
|
+
const attributes = { "app.turn.input_count": input.count };
|
|
6082
|
+
const deliveryLagMs = input.oldestReceivedAtMs - input.oldestCreatedAtMs;
|
|
6083
|
+
if (deliveryLagMs >= 0) attributes["app.turn.delivery_lag_ms"] = Math.round(deliveryLagMs);
|
|
6084
|
+
const waitMs = turnStartedAtMs - input.oldestReceivedAtMs;
|
|
6085
|
+
if (waitMs >= 0) attributes["app.turn.wait_ms"] = Math.round(waitMs);
|
|
6086
|
+
return attributes;
|
|
6087
|
+
}
|
|
6088
|
+
// src/chat/runtime/turn-execution.ts
|
|
6089
|
+
/** An error thrown while the agent advances a Run. */
|
|
6090
|
+
var AgentRunError = class extends Error {
|
|
6091
|
+
constructor(cause) {
|
|
6092
|
+
super(cause instanceof Error ? cause.message : "Agent Run failed", { cause });
|
|
6093
|
+
this.name = "AgentRunError";
|
|
6094
|
+
}
|
|
6095
|
+
};
|
|
6096
|
+
/**
|
|
6097
|
+
* Run the agent and finish the Turn after the caller saves its result.
|
|
6098
|
+
*
|
|
6099
|
+
* A paused Run, or a Run waiting for authorization, leaves the Turn open. A
|
|
6100
|
+
* save error also leaves the Turn open so the worker can retry or recover it.
|
|
6101
|
+
*/
|
|
6102
|
+
async function executeTurn(agentRunner, run, saveResult) {
|
|
6103
|
+
let outcome;
|
|
6104
|
+
try {
|
|
6105
|
+
outcome = await agentRunner.run(run);
|
|
6106
|
+
} catch (error) {
|
|
6107
|
+
throw new AgentRunError(error);
|
|
6108
|
+
}
|
|
6109
|
+
if (outcome.status !== "completed") return outcome;
|
|
6110
|
+
const saved = await saveResult(outcome.result);
|
|
6111
|
+
await finishTurn(run.conversationId, run.turnId, saved);
|
|
6112
|
+
return { status: "completed" };
|
|
6113
|
+
}
|
|
6114
|
+
/** Record the terminal lifecycle event of a Turn from its saved result. */
|
|
6115
|
+
async function finishTurn(conversationId, turnId, saved) {
|
|
6116
|
+
const lifecycle = new ConversationTurnLifecycleService(getConversationEventStore());
|
|
6117
|
+
const common = {
|
|
6118
|
+
conversationId,
|
|
6119
|
+
createdAtMs: saved.finishedAtMs ?? Date.now(),
|
|
6120
|
+
turnId
|
|
6121
|
+
};
|
|
6122
|
+
if (saved.outcome === "failed") await lifecycle.fail({
|
|
6123
|
+
...common,
|
|
6124
|
+
...saved.eventId ? { eventId: saved.eventId } : void 0,
|
|
6125
|
+
failureCode: saved.failureCode,
|
|
6126
|
+
...saved.failureReason ? { failureReason: saved.failureReason } : void 0
|
|
6127
|
+
});
|
|
6128
|
+
else await lifecycle.complete({
|
|
6129
|
+
...common,
|
|
6130
|
+
outcome: saved.outcome
|
|
6131
|
+
});
|
|
6132
|
+
}
|
|
6133
|
+
// src/chat/task-execution/supersede-turns.ts
|
|
6134
|
+
/**
|
|
6135
|
+
* End every open mailbox Turn other than `keepTurnId`, so new input runs in
|
|
6136
|
+
* the only open Turn. New input starts only when no yielded Turn waits, so an
|
|
6137
|
+
* open Turn here waits for OAuth or was left open by a failed or stopped Run.
|
|
6138
|
+
* The caller persists `conversation`. Returns false when `isStopped` turns
|
|
6139
|
+
* true first.
|
|
6140
|
+
*/
|
|
6141
|
+
async function supersedeOpenMailboxTurns(args) {
|
|
6142
|
+
const pendingAuthorizationActorId = args.conversation.processing.pendingAuth?.actorId;
|
|
6143
|
+
const superseded = (await listActiveMailboxTurns(args.conversationId)).filter((record) => record.turnId !== args.keepTurnId);
|
|
6144
|
+
for (const stale of superseded) {
|
|
6145
|
+
if (args.isStopped?.()) return false;
|
|
6146
|
+
await abandonTurnRecord({
|
|
6147
|
+
conversationId: args.conversationId,
|
|
6148
|
+
turnId: stale.turnId,
|
|
6149
|
+
errorMessage: "Turn superseded by new input"
|
|
6150
|
+
});
|
|
6151
|
+
markTurnClosed({
|
|
6152
|
+
conversation: args.conversation,
|
|
6153
|
+
nowMs: Date.now(),
|
|
6154
|
+
sessionId: stale.turnId
|
|
6155
|
+
});
|
|
6156
|
+
}
|
|
6157
|
+
if (superseded.some((record) => record.state === "paused" && record.resumeReason === "auth") && pendingAuthorizationActorId) await deleteWebAuthorization({
|
|
6158
|
+
actorId: pendingAuthorizationActorId,
|
|
6159
|
+
conversationId: args.conversationId
|
|
6160
|
+
});
|
|
6161
|
+
return true;
|
|
6162
|
+
}
|
|
6163
|
+
// src/chat/task-execution/mailbox-input.ts
|
|
6164
|
+
/**
|
|
6165
|
+
* Return the Turn inputs of web Messages, one per non-empty Message, in
|
|
6166
|
+
* order. Each one becomes its own prompt content part. A Message that
|
|
6167
|
+
* records an answer or a dismiss becomes its Review item tag. A batch with
|
|
6168
|
+
* only attachments keeps one empty input, so the prompt still has an
|
|
6169
|
+
* instruction.
|
|
6170
|
+
*/
|
|
6171
|
+
async function webTurnInputs(messages) {
|
|
6172
|
+
const flat = (await Promise.all(messages.map(async (message) => {
|
|
6173
|
+
const reviewItem = await loadReviewItemInput(message.reviewItemChange);
|
|
6174
|
+
if (reviewItem) return [{
|
|
6175
|
+
kind: "runtime",
|
|
6176
|
+
text: reviewItem
|
|
6177
|
+
}];
|
|
6178
|
+
const text = message.text.trim();
|
|
6179
|
+
return text ? [{
|
|
6180
|
+
kind: "person",
|
|
6181
|
+
text
|
|
6182
|
+
}] : [];
|
|
6183
|
+
}))).flat();
|
|
6184
|
+
return flat.length ? flat : [{
|
|
6185
|
+
kind: "person",
|
|
6186
|
+
text: ""
|
|
6187
|
+
}];
|
|
6188
|
+
}
|
|
6189
|
+
/**
|
|
6190
|
+
* Build the transcript Message for one web mailbox Message. Each web Message
|
|
6191
|
+
* keeps its own transcript Message and Review item change record, so the
|
|
6192
|
+
* dashboard shows what each Message did even when several share a Turn.
|
|
6193
|
+
*/
|
|
6194
|
+
function webConversationMessage(message, author) {
|
|
6195
|
+
const attachments = readMessageAttachments(message.input.attachments);
|
|
6196
|
+
const { reviewItemChange } = message.input;
|
|
6197
|
+
return {
|
|
6198
|
+
id: message.inboundMessageId,
|
|
6199
|
+
role: "user",
|
|
6200
|
+
text: normalizeConversationText(message.input.text),
|
|
6201
|
+
createdAtMs: message.createdAtMs,
|
|
6202
|
+
author,
|
|
6203
|
+
...message.input.authorIdentityId ? { authorIdentityId: message.input.authorIdentityId } : void 0,
|
|
6204
|
+
meta: {
|
|
6205
|
+
...attachments.length ? { attachments } : void 0,
|
|
6206
|
+
explicitMention: true,
|
|
6207
|
+
...reviewItemChange ? { reviewItemChanges: [reviewItemChange] } : void 0,
|
|
6208
|
+
source: "web"
|
|
6209
|
+
}
|
|
6210
|
+
};
|
|
6211
|
+
}
|
|
6212
|
+
/**
|
|
6213
|
+
* Return the saved input Messages of a resumed Turn in input order. A web
|
|
6214
|
+
* batch saves each Message apart. An older Turn saved one joined Message, so
|
|
6215
|
+
* its other input ids have no saved Message.
|
|
6216
|
+
*/
|
|
6217
|
+
function savedTurnInputMessages(conversation, turnMessage, inputMessageIds) {
|
|
6218
|
+
const saved = (inputMessageIds ?? []).flatMap((id) => conversation.messages.find((message) => message.id === id && message.role === "user") ?? []);
|
|
6219
|
+
return saved.some((message) => message.id === turnMessage.id) ? saved : [turnMessage];
|
|
6220
|
+
}
|
|
6221
|
+
// src/chat/task-execution/web-steering.ts
|
|
6222
|
+
async function steeringMessageFromWeb(message, actor) {
|
|
6223
|
+
const storedAttachments = readMessageAttachments(message.input.attachments);
|
|
6224
|
+
const reviewItemInput = await loadReviewItemInput(message.input.reviewItemChange);
|
|
6225
|
+
return {
|
|
6226
|
+
actor: {
|
|
6227
|
+
authorId: actor.userId,
|
|
6228
|
+
...actor.fullName ? { authorName: actor.fullName } : void 0
|
|
6229
|
+
},
|
|
6230
|
+
...reviewItemInput ? { kind: "runtime" } : void 0,
|
|
6231
|
+
provenance: instructionProvenanceFor(actor),
|
|
6232
|
+
text: reviewItemInput ?? message.input.text.trim(),
|
|
6233
|
+
timestampMs: message.createdAtMs,
|
|
6234
|
+
...storedAttachments.length ? { storedAttachments } : void 0
|
|
6235
|
+
};
|
|
6236
|
+
}
|
|
6237
|
+
/**
|
|
6238
|
+
* Drain steered web messages into the active web Turn.
|
|
6239
|
+
*
|
|
6240
|
+
* Only messages from the Turn Actor join. Steered messages from another
|
|
6241
|
+
* participant stay pending and start their own Turn next, so they never act
|
|
6242
|
+
* with this Actor's credentials.
|
|
6243
|
+
*/
|
|
6244
|
+
function createWebSteeringDrain(args) {
|
|
6245
|
+
const { actor, author, context, conversation, turnId } = args;
|
|
6246
|
+
return async (accept) => {
|
|
6247
|
+
const accepted = [];
|
|
6248
|
+
await context.attempt.drain(async (pending) => {
|
|
6249
|
+
const joining = pending.filter((message) => message.source === "web" && message.input.authorId === actor.userId && legacyWebMailboxMetadataSchema.safeParse(message.input.metadata).success);
|
|
6250
|
+
if (joining.length === 0) return [];
|
|
6251
|
+
for (const message of joining) upsertConversationMessage(conversation, webConversationMessage(message, author));
|
|
6252
|
+
await persistConversationMessages({
|
|
6253
|
+
conversation,
|
|
6254
|
+
conversationId: context.conversationId
|
|
6255
|
+
});
|
|
6256
|
+
const saved = (await getTurnRecord(context.conversationId, turnId))?.piMessages ?? [];
|
|
6257
|
+
const messages = withoutSavedSteeringMessages(saved, await Promise.all(joining.map((message) => steeringMessageFromWeb(message, actor))), buildSteeringPiMessage);
|
|
6258
|
+
if (messages.length > 0) {
|
|
6259
|
+
await accept(messages);
|
|
6260
|
+
accepted.push(...messages);
|
|
6261
|
+
}
|
|
6262
|
+
return joining.map((message) => message.inboundMessageId);
|
|
6263
|
+
});
|
|
6264
|
+
return accepted;
|
|
6265
|
+
};
|
|
6266
|
+
}
|
|
6267
|
+
// src/chat/conversations/destination.ts
|
|
6268
|
+
function requireLocalDestination(conversationId) {
|
|
6269
|
+
const parsed = localDestinationSchema.safeParse({
|
|
6270
|
+
platform: "local",
|
|
6271
|
+
conversationId
|
|
6272
|
+
});
|
|
6273
|
+
if (!parsed.success) throw new Error(`Invalid local conversation id: ${conversationId}`);
|
|
6274
|
+
return parsed.data;
|
|
6275
|
+
}
|
|
6276
|
+
/**
|
|
6277
|
+
* Keep a stored Destination, or create the temporary local Destination.
|
|
6278
|
+
*
|
|
6279
|
+
* TODO(dcramer): Delete this module after Conversation and AgentRun use
|
|
6280
|
+
* Location, and web and event Turns no longer need a local
|
|
6281
|
+
* Destination.
|
|
6282
|
+
*/
|
|
6283
|
+
function resolveConversationDestination(args) {
|
|
6284
|
+
return args.existing ?? requireLocalDestination(args.conversationId);
|
|
6285
|
+
}
|
|
6286
|
+
// src/chat/task-execution/conversation-turn.ts
|
|
6287
|
+
/** Run a mailbox Turn and store its assistant Messages. */
|
|
6288
|
+
function stableHex$1(...parts) {
|
|
6289
|
+
return createHash("sha256").update(parts.join("\0")).digest("hex").slice(0, 24);
|
|
6290
|
+
}
|
|
6291
|
+
function captureConversationTurnFailure(args) {
|
|
6292
|
+
const eventId = logException(args.error, `conversation.turn.${args.failureCode}`, {
|
|
6293
|
+
conversationId: args.conversationId,
|
|
6294
|
+
...args.runId ? { runId: args.runId } : void 0,
|
|
6295
|
+
turnId: args.turnId
|
|
6296
|
+
});
|
|
6297
|
+
return typeof eventId === "string" ? eventId : void 0;
|
|
6298
|
+
}
|
|
6299
|
+
/** Return the saved timer creator subject when it is still valid here. */
|
|
6300
|
+
function resumedTimerWatchCredentialSubject(conversationId, subject) {
|
|
6301
|
+
if (subject?.binding.type !== "timer-watch") return void 0;
|
|
6302
|
+
return verifyTimerWatchCredentialSubject({
|
|
6303
|
+
conversationId,
|
|
6304
|
+
subject,
|
|
6305
|
+
watchId: subject.binding.watchId
|
|
6306
|
+
}) ? subject : void 0;
|
|
6307
|
+
}
|
|
6308
|
+
function hasLostTurnInputCommit(error) {
|
|
6309
|
+
const cause = getConversationTurnBoundaryError(error)?.cause ?? error;
|
|
6310
|
+
return isTurnInputCommitLostError(error) || isTurnInputCommitLostError(cause);
|
|
6311
|
+
}
|
|
6312
|
+
async function completeCancelledConversationTurn(args) {
|
|
6313
|
+
const pendingAuthorization = args.conversation.processing.pendingAuth?.sessionId === args.turnId ? args.conversation.processing.pendingAuth : void 0;
|
|
6314
|
+
await abandonTurnRecord({
|
|
6315
|
+
conversationId: args.conversationId,
|
|
6316
|
+
turnId: args.turnId,
|
|
6317
|
+
errorMessage: "Turn cancelled"
|
|
6318
|
+
});
|
|
6319
|
+
clearPendingAuth(args.conversation, args.turnId);
|
|
6320
|
+
markConversationMessage(args.conversation, args.userMessageId, {
|
|
6321
|
+
replied: false,
|
|
6322
|
+
skippedReason: "turn cancelled"
|
|
6323
|
+
});
|
|
6324
|
+
markTurnClosed({
|
|
6325
|
+
conversation: args.conversation,
|
|
6326
|
+
nowMs: Date.now(),
|
|
6327
|
+
sessionId: args.turnId
|
|
6328
|
+
});
|
|
6329
|
+
if (pendingAuthorization) await deleteWebAuthorization({
|
|
6330
|
+
actorId: pendingAuthorization.actorId,
|
|
6331
|
+
conversationId: args.conversationId
|
|
6332
|
+
});
|
|
6333
|
+
await persistThreadStateById(args.conversationId, {
|
|
6334
|
+
conversation: args.conversation,
|
|
6335
|
+
sandboxRef: args.sandboxRef
|
|
6336
|
+
});
|
|
6337
|
+
await new ConversationTurnLifecycleService(getConversationEventStore()).complete({
|
|
6338
|
+
conversationId: args.conversationId,
|
|
6339
|
+
createdAtMs: Date.now(),
|
|
6340
|
+
outcome: "cancelled",
|
|
6341
|
+
turnId: args.turnId
|
|
6342
|
+
});
|
|
6343
|
+
await args.acknowledge();
|
|
6344
|
+
}
|
|
6345
|
+
/**
|
|
6346
|
+
* Cancel a Turn that waits for sign-in outside its worker, with the same
|
|
6347
|
+
* cleanup as a stopped resume. A tree stop calls this, because its stop wake
|
|
6348
|
+
* can go to queued input before the paused Turn.
|
|
6349
|
+
*/
|
|
6350
|
+
async function cancelSignInPausedTurn(args) {
|
|
6351
|
+
if (!await abandonTurnRecord({
|
|
6352
|
+
conversationId: args.conversationId,
|
|
6353
|
+
errorMessage: "Turn cancelled",
|
|
6354
|
+
onlyIfAuthPaused: true,
|
|
6355
|
+
turnId: args.turnId
|
|
6356
|
+
})) return;
|
|
6357
|
+
const conversation = coerceThreadConversationState(await getPersistedThreadState(args.conversationId));
|
|
6358
|
+
await hydrateConversationMessages({
|
|
6359
|
+
conversation,
|
|
6360
|
+
conversationId: args.conversationId
|
|
6361
|
+
});
|
|
6362
|
+
await completeCancelledConversationTurn({
|
|
6363
|
+
acknowledge: async () => {},
|
|
6364
|
+
conversation,
|
|
6365
|
+
conversationId: args.conversationId,
|
|
6366
|
+
turnId: args.turnId,
|
|
6367
|
+
userMessageId: getTurnUserMessage(conversation, args.turnId)?.id
|
|
6368
|
+
});
|
|
6369
|
+
}
|
|
6370
|
+
/**
|
|
6371
|
+
* Return the author Identity id that every batched input shares.
|
|
6372
|
+
* A batch with more than one author has no single author yet.
|
|
6373
|
+
*/
|
|
6374
|
+
function sharedAuthorIdentityId(messages) {
|
|
6375
|
+
const ids = new Set(messages.map((message) => message.input.authorIdentityId));
|
|
6376
|
+
return ids.size === 1 ? [...ids][0] : void 0;
|
|
6377
|
+
}
|
|
6378
|
+
/**
|
|
6379
|
+
* Create the shared mailbox worker for web and event Turns.
|
|
6380
|
+
*/
|
|
6381
|
+
function createConversationTurnWorker(agentRunner, deliverMessage) {
|
|
6382
|
+
return async (context, resolved) => {
|
|
6383
|
+
if (resolved.kind === "mailbox") {
|
|
6384
|
+
const delayMs = getEventBatchDelayMs(resolved.batch.map((entry) => entry.message));
|
|
6385
|
+
if (delayMs > 0) return {
|
|
6386
|
+
status: "deferred",
|
|
6387
|
+
delayMs
|
|
6388
|
+
};
|
|
6389
|
+
}
|
|
6390
|
+
const lifecycle = new ConversationTurnLifecycleService(getConversationEventStore());
|
|
6391
|
+
const isResume = resolved.kind === "resume";
|
|
6392
|
+
let turnInputFacts;
|
|
6393
|
+
let inputs = [];
|
|
6394
|
+
let attachments = [];
|
|
6395
|
+
let turnId = "";
|
|
6396
|
+
let userMessageId = "";
|
|
6397
|
+
let startedAtMs = Date.now();
|
|
6398
|
+
let inputMessageIds = [];
|
|
6399
|
+
let eventMeta = {};
|
|
6400
|
+
let authorIdentityId;
|
|
6401
|
+
let webInputMessages = [];
|
|
6402
|
+
const storedConversation = await getConversationStore().get({ conversationId: context.conversationId });
|
|
6403
|
+
const isThread = storedConversation?.kind === "thread";
|
|
6404
|
+
const visibility = isThread ? storedConversation.visibility ?? "private" : storedConversation?.visibility;
|
|
6405
|
+
const mailboxDestination = resolved.kind === "mailbox" ? resolved.batch[0]?.message.destination : void 0;
|
|
6406
|
+
const destination = resolveConversationDestination({
|
|
6407
|
+
conversationId: context.conversationId,
|
|
6408
|
+
existing: context.destination ?? mailboxDestination ?? storedConversation?.destination
|
|
6409
|
+
});
|
|
6410
|
+
if (resolved.kind === "mailbox") {
|
|
6411
|
+
const first = resolved.batch[0];
|
|
6412
|
+
const messages = resolved.batch.map((entry) => entry.message);
|
|
6413
|
+
const firstMetadata = first.message.input.metadata;
|
|
6414
|
+
if (isEventMailboxMetadata(firstMetadata)) {
|
|
6415
|
+
inputs = renderEventBatchInputs(messages, await eventReviewItemInputs(messages)).map((text) => ({
|
|
6416
|
+
kind: "runtime",
|
|
6417
|
+
text
|
|
6418
|
+
}));
|
|
6419
|
+
eventMeta = eventBatchMessageMeta(messages);
|
|
6420
|
+
} else {
|
|
6421
|
+
inputs = await webTurnInputs(messages.map((message) => message.input));
|
|
6422
|
+
webInputMessages = resolved.batch.map((entry) => webConversationMessage(entry.message, entry.author));
|
|
6423
|
+
}
|
|
6424
|
+
attachments = resolved.batch.flatMap((entry) => readMessageAttachments(entry.message.input.attachments));
|
|
6425
|
+
startedAtMs = first.message.createdAtMs;
|
|
6426
|
+
userMessageId = first.message.inboundMessageId;
|
|
6427
|
+
turnId = buildDeterministicTurnId(userMessageId);
|
|
6428
|
+
inputMessageIds = resolved.batch.map((entry) => entry.message.inboundMessageId);
|
|
6429
|
+
authorIdentityId = sharedAuthorIdentityId(messages);
|
|
6430
|
+
turnInputFacts = first;
|
|
6431
|
+
} else turnId = resolved.turnId;
|
|
6432
|
+
const persisted = await getPersistedThreadState(context.conversationId);
|
|
6433
|
+
const conversation = coerceThreadConversationState(persisted);
|
|
6434
|
+
await hydrateConversationMessages({
|
|
6435
|
+
conversation,
|
|
6436
|
+
conversationId: context.conversationId
|
|
6437
|
+
});
|
|
6438
|
+
const savedTurn = isResume ? await getTurnRecord(context.conversationId, turnId) : void 0;
|
|
6439
|
+
let savedMessageIsEvent = false;
|
|
6440
|
+
if (isResume) {
|
|
6441
|
+
const userMessage = getTurnUserMessage(conversation, turnId);
|
|
6442
|
+
if (!userMessage) throw new Error(`Unable to locate the persisted user message for Turn "${turnId}"`);
|
|
6443
|
+
savedMessageIsEvent = isEventConversationMessage(userMessage);
|
|
6444
|
+
turnInputFacts = turnInputFactsFromConversationMessage(userMessage, {
|
|
6445
|
+
conversationId: context.conversationId,
|
|
6446
|
+
location: storedConversation?.location,
|
|
6447
|
+
savedActor: savedTurn?.actor,
|
|
6448
|
+
savedSource: savedTurn?.source,
|
|
6449
|
+
visibility: storedConversation?.visibility
|
|
6450
|
+
});
|
|
6451
|
+
const turnInputs = savedTurnInputMessages(conversation, userMessage, await lifecycle.loadInputMessageIds(context.conversationId, turnId));
|
|
6452
|
+
userMessageId = userMessage.id;
|
|
6453
|
+
inputs = savedMessageIsEvent ? [{
|
|
6454
|
+
kind: "runtime",
|
|
6455
|
+
text: userMessage.text
|
|
6456
|
+
}] : await webTurnInputs(turnInputs.map((message) => ({
|
|
6457
|
+
reviewItemChange: message.meta?.reviewItemChanges?.[0],
|
|
6458
|
+
text: message.text
|
|
6459
|
+
})));
|
|
6460
|
+
attachments = turnInputs.flatMap((message) => message.meta?.attachments ?? []);
|
|
6461
|
+
startedAtMs = userMessage.createdAtMs;
|
|
6462
|
+
inputMessageIds = turnInputs.map((message) => message.id);
|
|
6463
|
+
}
|
|
6464
|
+
if (!turnInputFacts) throw new Error(`Resumed Turn is missing an Actor for Conversation ${context.conversationId}`);
|
|
6465
|
+
const { actor, author } = turnInputFacts;
|
|
6466
|
+
const instructionInputs = instructionForInputs(inputs);
|
|
6467
|
+
const { text } = instructionInputs;
|
|
6468
|
+
let credentialSubject;
|
|
6469
|
+
if (actor.platform === "system") credentialSubject = resolved.kind === "mailbox" ? timerWatchCredentialSubject(context.conversationId, resolved.batch.map((entry) => entry.message)) : resumedTimerWatchCredentialSubject(context.conversationId, savedTurn?.credentialSubject);
|
|
6470
|
+
const source = sourceFromTurnInput({
|
|
6471
|
+
conversationId: context.conversationId,
|
|
6472
|
+
source: turnInputFacts.source,
|
|
6473
|
+
visibility
|
|
6474
|
+
});
|
|
6475
|
+
const webActor = actor.platform === "web" ? actor : void 0;
|
|
6476
|
+
const disabledFeatures = [...webActor ? [] : ["interactive-auth"], ...isThread ? ["subagents"] : []];
|
|
6477
|
+
const conversationLocation = storedConversation?.location;
|
|
6478
|
+
const isEventTurn = source.kind === "event" || savedMessageIsEvent;
|
|
6479
|
+
const deliverToProvider = Boolean(conversationLocation) && isEventTurn && storedConversation?.kind === "root";
|
|
6480
|
+
const surface = deliverToProvider ? "slack" : "api";
|
|
6481
|
+
const inputTelemetry = resolved.kind === "mailbox" ? turnInputTelemetry(resolved.batch.map((entry) => entry.message)) : void 0;
|
|
6482
|
+
const turnTrace = inputTelemetry ?? (savedTurn?.traceContext ? { traceContexts: [savedTurn.traceContext] } : void 0);
|
|
6483
|
+
return await withTurnSpan({
|
|
6484
|
+
conversationId: context.conversationId,
|
|
6485
|
+
platform: actor.platform,
|
|
6486
|
+
...webActor ? {
|
|
6487
|
+
userId: webActor.userId,
|
|
6488
|
+
...webActor.userName ? { userName: webActor.userName } : void 0
|
|
6489
|
+
} : void 0
|
|
6490
|
+
}, turnTrace, async (setTurnSpanAttributes) => {
|
|
6491
|
+
if (inputTelemetry) setTurnSpanAttributes(getTurnInputSpanAttributes(inputTelemetry, Date.now()));
|
|
6492
|
+
let acknowledged = isResume || context.attempt.messages.length === 0;
|
|
6493
|
+
const acknowledge = async () => {
|
|
6494
|
+
if (acknowledged) return;
|
|
6495
|
+
try {
|
|
6496
|
+
await context.attempt.ack();
|
|
6497
|
+
} catch {
|
|
6498
|
+
throw new TurnInputCommitLostError(`Conversation work lease lost before mailbox Message acknowledgement for ${context.conversationId}`);
|
|
6499
|
+
}
|
|
6500
|
+
acknowledged = true;
|
|
6501
|
+
};
|
|
6502
|
+
let sandboxRef = getPersistedSandboxState(persisted);
|
|
6503
|
+
const initialSandboxRef = sandboxRef;
|
|
6504
|
+
const stopSignal = context.stopSignal?.();
|
|
6505
|
+
const completeCancelledTurn = async () => {
|
|
6506
|
+
try {
|
|
6507
|
+
await completeCancelledConversationTurn({
|
|
6508
|
+
acknowledge,
|
|
6509
|
+
conversation,
|
|
6510
|
+
conversationId: context.conversationId,
|
|
6511
|
+
sandboxRef,
|
|
6512
|
+
turnId,
|
|
6513
|
+
userMessageId
|
|
6514
|
+
});
|
|
6515
|
+
} catch (error) {
|
|
6516
|
+
if (hasLostTurnInputCommit(error)) return { status: "lost_lease" };
|
|
6517
|
+
throw error;
|
|
6518
|
+
}
|
|
6519
|
+
return { status: "completed" };
|
|
6520
|
+
};
|
|
6521
|
+
if (isResume) {
|
|
6522
|
+
if (stopSignal?.aborted) return await completeCancelledTurn();
|
|
6523
|
+
} else {
|
|
6524
|
+
for (const [index, message] of webInputMessages.entries()) upsertConversationMessage(conversation, index === 0 ? {
|
|
6525
|
+
...message,
|
|
6526
|
+
meta: {
|
|
6527
|
+
...message.meta,
|
|
6528
|
+
replied: false
|
|
6529
|
+
}
|
|
6530
|
+
} : message);
|
|
6531
|
+
if (webInputMessages.length === 0) upsertConversationMessage(conversation, {
|
|
6532
|
+
id: userMessageId,
|
|
6533
|
+
role: "user",
|
|
6534
|
+
text: normalizeConversationText(text),
|
|
6535
|
+
createdAtMs: startedAtMs,
|
|
6536
|
+
author,
|
|
6537
|
+
...authorIdentityId ? { authorIdentityId } : void 0,
|
|
6538
|
+
meta: {
|
|
6539
|
+
...attachments.length ? { attachments } : void 0,
|
|
6540
|
+
explicitMention: true,
|
|
6541
|
+
replied: false,
|
|
6542
|
+
...eventMeta
|
|
6543
|
+
}
|
|
6544
|
+
});
|
|
6545
|
+
await persistConversationMessages({
|
|
6546
|
+
conversation,
|
|
6547
|
+
conversationId: context.conversationId
|
|
6548
|
+
});
|
|
6549
|
+
await lifecycle.start({
|
|
6550
|
+
conversationId: context.conversationId,
|
|
6551
|
+
createdAtMs: Date.now(),
|
|
6552
|
+
inputMessageIds,
|
|
6553
|
+
surface,
|
|
6554
|
+
threadContextThroughSeq: latestConversationMessageSeq(conversation),
|
|
6555
|
+
turnId
|
|
6556
|
+
});
|
|
6557
|
+
if (stopSignal?.aborted) return await completeCancelledTurn();
|
|
6558
|
+
startActiveTurn({
|
|
6559
|
+
conversation,
|
|
6560
|
+
nextTurnId: turnId
|
|
6561
|
+
});
|
|
6562
|
+
}
|
|
6563
|
+
let currentRunId;
|
|
6564
|
+
let assistantMessageDelivered = false;
|
|
6565
|
+
let failureCode = "persistence_failed";
|
|
6566
|
+
let modelFailureEventId;
|
|
6567
|
+
let modelFailureCaptureAttempted = false;
|
|
6568
|
+
let completedSuccessfully = false;
|
|
6569
|
+
const deliverAssistantMessage = async (value) => {
|
|
6570
|
+
const agentMessage = typeof value === "string" ? void 0 : value;
|
|
6571
|
+
const decision = agentMessage ? decideReply(agentMessage) : void 0;
|
|
6572
|
+
const replyText = typeof value === "string" ? value : decision?.kind === "deliver" ? decision.text : void 0;
|
|
6573
|
+
if (!replyText?.trim()) return;
|
|
6574
|
+
failureCode = "delivery_failed";
|
|
6575
|
+
const cards = await loadPendingMessageCards(context.conversationId);
|
|
6576
|
+
const quiet = decision?.kind === "deliver" && decision.quiet === true && isEventTurn && cards.length === 0;
|
|
6577
|
+
let deliveryResult;
|
|
6578
|
+
if (deliverToProvider && !quiet) {
|
|
6579
|
+
if (!conversationLocation || !deliverMessage) throw new Error(`Conversation ${context.conversationId} cannot deliver to its Location`);
|
|
6580
|
+
deliveryResult = await deliverMessage({
|
|
6581
|
+
cards,
|
|
6582
|
+
conversationId: context.conversationId,
|
|
6583
|
+
location: conversationLocation,
|
|
6584
|
+
text: replyText
|
|
6585
|
+
});
|
|
6586
|
+
}
|
|
6587
|
+
await commitAssistantMessage({
|
|
6588
|
+
cards,
|
|
6589
|
+
...agentMessage ? { agentMessage } : void 0,
|
|
6590
|
+
conversation,
|
|
6591
|
+
conversationId: context.conversationId,
|
|
6592
|
+
...deliveryResult ? { deliveryResult } : void 0,
|
|
6593
|
+
...quiet ? { quiet } : void 0,
|
|
6594
|
+
sessionId: turnId,
|
|
6595
|
+
...deliveryResult ? { source: "slack" } : source.kind === "web" ? { source: "web" } : void 0,
|
|
6596
|
+
text: replyText,
|
|
6597
|
+
userMessageId
|
|
6598
|
+
});
|
|
6599
|
+
assistantMessageDelivered = true;
|
|
6600
|
+
failureCode = "agent_run_failed";
|
|
6601
|
+
};
|
|
6602
|
+
try {
|
|
6603
|
+
if (stopSignal?.aborted) return await completeCancelledTurn();
|
|
6604
|
+
if (!isResume && !await supersedeOpenMailboxTurns({
|
|
6605
|
+
conversation,
|
|
6606
|
+
conversationId: context.conversationId,
|
|
6607
|
+
isStopped: () => Boolean(stopSignal?.aborted),
|
|
6608
|
+
keepTurnId: turnId
|
|
6609
|
+
})) return await completeCancelledTurn();
|
|
6610
|
+
await persistThreadStateById(context.conversationId, { conversation });
|
|
6611
|
+
if (stopSignal?.aborted) return await completeCancelledTurn();
|
|
6612
|
+
const piMessages = await loadProjection({ conversationId: context.conversationId });
|
|
6613
|
+
failureCode = "agent_run_failed";
|
|
6614
|
+
currentRunId = `conversation-run:${stableHex$1(turnId, String(startedAtMs))}`;
|
|
6615
|
+
setTags({ runId: currentRunId });
|
|
6616
|
+
const outcome = await executeTurn(agentRunner, {
|
|
6617
|
+
conversationId: context.conversationId,
|
|
6618
|
+
turnId,
|
|
6619
|
+
runId: currentRunId,
|
|
6620
|
+
instruction: {
|
|
6621
|
+
...instructionInputs,
|
|
6622
|
+
storedAttachments: attachments,
|
|
6623
|
+
context: await buildTurnThreadContext({
|
|
6624
|
+
conversation,
|
|
6625
|
+
conversationId: context.conversationId,
|
|
6626
|
+
excludeMessageIds: inputMessageIds,
|
|
6627
|
+
hasHistory: piMessages.length > 0,
|
|
6628
|
+
turnId
|
|
6629
|
+
})
|
|
6630
|
+
},
|
|
6631
|
+
history: piMessages,
|
|
6632
|
+
actor,
|
|
6633
|
+
credentialContext: credentialContextForActor(actor, credentialSubject),
|
|
6634
|
+
destination,
|
|
6635
|
+
source,
|
|
6636
|
+
...conversationLocation ? { location: conversationLocation } : void 0,
|
|
6637
|
+
surface,
|
|
6638
|
+
...stopSignal ? { signal: stopSignal } : void 0,
|
|
6639
|
+
...webActor ? { authorization: createWebAuthorization({
|
|
6640
|
+
actorId: webActor.userId,
|
|
6641
|
+
conversationId: context.conversationId
|
|
6642
|
+
}) } : void 0,
|
|
6643
|
+
...disabledFeatures.length > 0 ? { disabledFeatures } : void 0,
|
|
6644
|
+
state: {
|
|
6645
|
+
pendingAuth: conversation.processing.pendingAuth,
|
|
6646
|
+
sandboxRef
|
|
6647
|
+
},
|
|
6648
|
+
delivery: deliverAssistantMessage,
|
|
6649
|
+
durability: {
|
|
6650
|
+
...webActor ? { drainSteeringMessages: createWebSteeringDrain({
|
|
6651
|
+
actor: webActor,
|
|
6652
|
+
author,
|
|
6653
|
+
context,
|
|
6654
|
+
conversation,
|
|
6655
|
+
turnId
|
|
6656
|
+
}) } : void 0,
|
|
6657
|
+
onInputCommitted: acknowledge,
|
|
6658
|
+
shouldYield: context.shouldYield,
|
|
6659
|
+
checkIn: context.checkIn,
|
|
6660
|
+
onSandboxRefChanged: async (nextSandboxRef) => {
|
|
6661
|
+
sandboxRef = nextSandboxRef;
|
|
6662
|
+
await persistThreadStateById(context.conversationId, {
|
|
6663
|
+
conversation,
|
|
6664
|
+
sandboxRef
|
|
6665
|
+
});
|
|
6666
|
+
},
|
|
6667
|
+
recordPendingAuth: async (pendingAuth) => {
|
|
6668
|
+
conversation.processing.pendingAuth = pendingAuth;
|
|
6669
|
+
await persistThreadStateById(context.conversationId, {
|
|
6670
|
+
conversation,
|
|
6671
|
+
sandboxRef
|
|
6672
|
+
});
|
|
6673
|
+
}
|
|
6674
|
+
}
|
|
6675
|
+
}, async (result) => {
|
|
6676
|
+
if (stopSignal?.aborted) throw stopSignal.reason ?? new DOMException("Turn cancelled", "AbortError");
|
|
6677
|
+
modelFailureCaptureAttempted = result.diagnostics.outcome !== "success";
|
|
6678
|
+
const finalized = finalizeFailedTurnReplyWithEvent({
|
|
6679
|
+
reply: result,
|
|
6680
|
+
logException
|
|
6681
|
+
});
|
|
6682
|
+
const modelFailureReason = finalized.failureReason;
|
|
6683
|
+
const reply = finalized.reply;
|
|
6684
|
+
modelFailureEventId = finalized.eventId;
|
|
6685
|
+
if (reply.diagnostics.outcome !== "success") await deliverAssistantMessage(reply.text);
|
|
6686
|
+
const completedState = buildDeliveredTurnStatePatch({
|
|
6687
|
+
conversation,
|
|
6688
|
+
reply,
|
|
6689
|
+
sessionId: turnId,
|
|
6690
|
+
userMessageId
|
|
6691
|
+
});
|
|
6692
|
+
await persistThreadStateById(context.conversationId, {
|
|
6693
|
+
conversation: completedState.conversation,
|
|
6694
|
+
sandboxRef: reply.sandboxRef ?? sandboxRef
|
|
6695
|
+
});
|
|
6696
|
+
if (reply.piMessages?.length) {
|
|
6697
|
+
const latest = await getTurnRecord(context.conversationId, turnId);
|
|
6698
|
+
await saveTurnCheckpoint({
|
|
6699
|
+
mode: "completed",
|
|
6700
|
+
conversationId: context.conversationId,
|
|
6701
|
+
turnId,
|
|
6702
|
+
sliceId: latest?.sliceId ?? 1,
|
|
6703
|
+
messages: reply.piMessages,
|
|
6704
|
+
durationMs: reply.diagnostics.durationMs,
|
|
6705
|
+
usage: reply.diagnostics.usage,
|
|
6706
|
+
destination,
|
|
6707
|
+
source,
|
|
6708
|
+
actor,
|
|
6709
|
+
surface
|
|
6710
|
+
});
|
|
6711
|
+
}
|
|
6712
|
+
const automatedTurnLimit = await recordFinishedTurnForAutomatedLimit({
|
|
6713
|
+
conversationId: context.conversationId,
|
|
6714
|
+
maxTurns: botConfig.maxConsecutiveAutomatedTurns,
|
|
6715
|
+
source
|
|
6716
|
+
});
|
|
6717
|
+
await maybePostAutomatedTurnLimitNotice({
|
|
6718
|
+
conversationId: context.conversationId,
|
|
6719
|
+
maxTurns: botConfig.maxConsecutiveAutomatedTurns,
|
|
6720
|
+
source,
|
|
6721
|
+
update: automatedTurnLimit
|
|
6722
|
+
});
|
|
6723
|
+
completedSuccessfully = reply.diagnostics.outcome === "success";
|
|
6724
|
+
return completedSuccessfully ? { outcome: assistantMessageDelivered ? "success" : "no_reply" } : {
|
|
6725
|
+
...modelFailureEventId ? { eventId: modelFailureEventId } : void 0,
|
|
6726
|
+
failureCode: "model_execution_failed",
|
|
6727
|
+
...modelFailureReason ? { failureReason: modelFailureReason } : void 0,
|
|
6728
|
+
outcome: "failed"
|
|
6729
|
+
};
|
|
6730
|
+
});
|
|
6731
|
+
if (outcome.status !== "completed" && stopSignal?.aborted) return await completeCancelledTurn();
|
|
6732
|
+
if (outcome.status === "suspended") return { status: "yielded" };
|
|
6733
|
+
if (outcome.status === "awaiting_auth") {
|
|
6734
|
+
completeAuthPauseTurn({
|
|
6735
|
+
conversation,
|
|
6736
|
+
sessionId: turnId
|
|
6737
|
+
});
|
|
6738
|
+
await persistThreadStateById(context.conversationId, {
|
|
6739
|
+
conversation,
|
|
6740
|
+
sandboxRef
|
|
6741
|
+
});
|
|
6742
|
+
await acknowledge();
|
|
6743
|
+
return { status: "paused" };
|
|
6744
|
+
}
|
|
6745
|
+
if (completedSuccessfully && !isThread) try {
|
|
6746
|
+
await scheduleSessionCompletedPluginTasks({
|
|
6747
|
+
conversationId: context.conversationId,
|
|
6748
|
+
sessionId: turnId
|
|
6749
|
+
}, { send: async (message) => {
|
|
6750
|
+
try {
|
|
6751
|
+
await processPluginTask(message);
|
|
6752
|
+
} catch (error) {
|
|
6753
|
+
logException(error, "conversation.plugin.session_completion_task.failed", {
|
|
6754
|
+
conversationId: context.conversationId,
|
|
6755
|
+
pluginName: message.plugin,
|
|
6756
|
+
taskName: message.name,
|
|
6757
|
+
turnId
|
|
6758
|
+
});
|
|
6759
|
+
}
|
|
6760
|
+
} });
|
|
6761
|
+
} catch (error) {
|
|
6762
|
+
logException(error, "conversation.plugin.session_completion_task.failed", {
|
|
6763
|
+
conversationId: context.conversationId,
|
|
6764
|
+
turnId
|
|
6765
|
+
});
|
|
6766
|
+
}
|
|
6767
|
+
await acknowledge();
|
|
6768
|
+
return { status: "completed" };
|
|
6769
|
+
} catch (error) {
|
|
6770
|
+
const failure = error instanceof AgentRunError ? error.cause : error;
|
|
6771
|
+
if (hasLostTurnInputCommit(failure)) return { status: "lost_lease" };
|
|
6772
|
+
if (stopSignal?.aborted) return await completeCancelledTurn();
|
|
6773
|
+
if (!context.attempt.isFinalAttempt) throw failure;
|
|
6774
|
+
const failureEventId = modelFailureCaptureAttempted && failureCode === "agent_run_failed" ? modelFailureEventId : captureConversationTurnFailure({
|
|
6775
|
+
conversationId: context.conversationId,
|
|
6776
|
+
error: failure,
|
|
6777
|
+
failureCode,
|
|
6778
|
+
runId: currentRunId,
|
|
6779
|
+
turnId
|
|
6780
|
+
});
|
|
6781
|
+
try {
|
|
6782
|
+
markTurnFailed({
|
|
6783
|
+
conversation,
|
|
6784
|
+
nowMs: Date.now(),
|
|
6785
|
+
sessionId: turnId,
|
|
6786
|
+
userMessageId,
|
|
6787
|
+
markConversationMessage
|
|
6788
|
+
});
|
|
6789
|
+
await persistThreadStateById(context.conversationId, {
|
|
6790
|
+
conversation,
|
|
6791
|
+
sandboxRef: initialSandboxRef ?? null
|
|
6792
|
+
});
|
|
6793
|
+
} catch (persistenceError) {
|
|
6794
|
+
captureConversationTurnFailure({
|
|
6795
|
+
conversationId: context.conversationId,
|
|
6796
|
+
error: persistenceError,
|
|
6797
|
+
failureCode: "persistence_failed",
|
|
6798
|
+
runId: currentRunId,
|
|
6799
|
+
turnId
|
|
6800
|
+
});
|
|
6801
|
+
}
|
|
6802
|
+
await lifecycle.fail({
|
|
6803
|
+
conversationId: context.conversationId,
|
|
6804
|
+
createdAtMs: Date.now(),
|
|
6805
|
+
...failureEventId ? { eventId: failureEventId } : void 0,
|
|
6806
|
+
failureCode,
|
|
6807
|
+
turnId
|
|
6808
|
+
});
|
|
6809
|
+
await acknowledge();
|
|
6810
|
+
return { status: "completed" };
|
|
6811
|
+
}
|
|
6812
|
+
});
|
|
6813
|
+
};
|
|
6814
|
+
}
|
|
6625
6815
|
// src/chat/agent-invocations/markers.ts
|
|
6626
6816
|
/**
|
|
6627
6817
|
* Dashboard records for agent invocations. The parent Conversation gets one
|
|
6628
6818
|
* `subagent_started` and one `subagent_ended` event for each agent invocation.
|
|
6629
6819
|
* The child Conversation gets `message` events for its input and its result,
|
|
6630
|
-
* because a child
|
|
6820
|
+
* because a child posts nothing to its Location.
|
|
6631
6821
|
*/
|
|
6632
6822
|
const SUBAGENT_KIND = "agent";
|
|
6633
6823
|
/**
|
|
@@ -6807,13 +6997,25 @@ async function skipUnreadResults(conversationId, nowMs, state) {
|
|
|
6807
6997
|
updatedAt: new Date(nowMs)
|
|
6808
6998
|
}).where(and(eq(juniorAgentInvocations.parentConversationId, conversationId), inArray(juniorAgentInvocations.invocationId, invocationIds), eq(juniorAgentInvocations.parentMailboxStatus, "appended")));
|
|
6809
6999
|
}
|
|
7000
|
+
/**
|
|
7001
|
+
* A Thread can hold a person's Turn that waits for sign-in. The stop ends
|
|
7002
|
+
* that Turn here, because no worker holds it. Then a later sign-in callback
|
|
7003
|
+
* cannot resume a stopped Thread.
|
|
7004
|
+
*/
|
|
6810
7005
|
async function finishStoppedTree(tree, conversationIdsToStop, options) {
|
|
6811
7006
|
for (const invocation of tree.stopped) await recordSubagentEnded(invocation);
|
|
6812
7007
|
await markConversationsStopped(conversationIdsToStop, options);
|
|
6813
|
-
for (const conversationId of conversationIdsToStop)
|
|
6814
|
-
conversationId
|
|
6815
|
-
|
|
6816
|
-
|
|
7008
|
+
for (const conversationId of conversationIdsToStop) {
|
|
7009
|
+
const pausedTurnId = await getAuthPausedConversationTurnId(conversationId);
|
|
7010
|
+
if (pausedTurnId) await cancelSignInPausedTurn({
|
|
7011
|
+
conversationId,
|
|
7012
|
+
turnId: pausedTurnId
|
|
7013
|
+
});
|
|
7014
|
+
await stopConversationWork({
|
|
7015
|
+
conversationId,
|
|
7016
|
+
state: options.state
|
|
7017
|
+
});
|
|
7018
|
+
}
|
|
6817
7019
|
}
|
|
6818
7020
|
/**
|
|
6819
7021
|
* List one child Conversation and every Conversation below it, child first.
|
|
@@ -6897,6 +7099,8 @@ const stopAgentOutputSchema = juniorToolOutputSchema.extend({
|
|
|
6897
7099
|
/** Create the tool that stops one child agent of one conversation. */
|
|
6898
7100
|
function createStopAgentTool(conversationId) {
|
|
6899
7101
|
return zodTool({
|
|
7102
|
+
exposure: "deferred",
|
|
7103
|
+
source: AGENTS_TOOL_SOURCE,
|
|
6900
7104
|
description: "Stop a child agent that this conversation started, and every child agent it started. Use it when the child agent's work is no longer needed or goes in the wrong direction. A stopped child agent sends no result. To give it new work later, use messageAgent.",
|
|
6901
7105
|
annotations: {
|
|
6902
7106
|
destructiveHint: true,
|
|
@@ -7327,25 +7531,6 @@ async function loadInputImages(args) {
|
|
|
7327
7531
|
};
|
|
7328
7532
|
}));
|
|
7329
7533
|
}
|
|
7330
|
-
// src/chat/conversations/destination.ts
|
|
7331
|
-
function requireLocalDestination(conversationId) {
|
|
7332
|
-
const parsed = localDestinationSchema.safeParse({
|
|
7333
|
-
platform: "local",
|
|
7334
|
-
conversationId
|
|
7335
|
-
});
|
|
7336
|
-
if (!parsed.success) throw new Error(`Invalid local conversation id: ${conversationId}`);
|
|
7337
|
-
return parsed.data;
|
|
7338
|
-
}
|
|
7339
|
-
/**
|
|
7340
|
-
* Keep a stored Destination, or create the temporary local Destination.
|
|
7341
|
-
*
|
|
7342
|
-
* TODO(dcramer): Delete this module after Conversation and AgentRun use
|
|
7343
|
-
* Location, and web and event Turns no longer need a local
|
|
7344
|
-
* Destination.
|
|
7345
|
-
*/
|
|
7346
|
-
function resolveConversationDestination(args) {
|
|
7347
|
-
return args.existing ?? requireLocalDestination(args.conversationId);
|
|
7348
|
-
}
|
|
7349
7534
|
// src/chat/conversations/web-input.ts
|
|
7350
7535
|
function normalizeEmail(email) {
|
|
7351
7536
|
return email.trim().toLowerCase();
|
|
@@ -7380,9 +7565,11 @@ function storedActorFromWeb(actor) {
|
|
|
7380
7565
|
}
|
|
7381
7566
|
/**
|
|
7382
7567
|
* Return whether a person can add a web Message to an existing
|
|
7383
|
-
* Conversation: a dashboard Conversation
|
|
7568
|
+
* Conversation: a dashboard Conversation, a Slack thread, or a Thread.
|
|
7384
7569
|
*/
|
|
7385
|
-
function acceptsWebMessages(
|
|
7570
|
+
function acceptsWebMessages(conversation) {
|
|
7571
|
+
if (conversation.kind !== "root") return conversation.kind === "thread";
|
|
7572
|
+
const { conversationId, destination } = conversation;
|
|
7386
7573
|
if (destination?.platform === "slack") return true;
|
|
7387
7574
|
return destination?.platform === "local" && conversationId.startsWith("local:web:");
|
|
7388
7575
|
}
|
|
@@ -7404,17 +7591,13 @@ function buildWebInboundMessage(args) {
|
|
|
7404
7591
|
const text = args.message.trim();
|
|
7405
7592
|
if (!text && !args.attachments?.length) throw new Error("Web Message must not be empty");
|
|
7406
7593
|
if (!args.actor.email) throw new Error("Web Actor requires a verified email");
|
|
7407
|
-
const destination = resolveConversationDestination({
|
|
7408
|
-
conversationId: args.conversationId,
|
|
7409
|
-
existing: args.destination
|
|
7410
|
-
});
|
|
7411
7594
|
const nowMs = args.nowMs ?? Date.now();
|
|
7412
7595
|
const traceContext = getActiveTraceContext();
|
|
7413
7596
|
return {
|
|
7414
7597
|
conversationId: args.conversationId,
|
|
7415
7598
|
createdAtMs: args.createdAtMs ?? nowMs,
|
|
7416
7599
|
delivery: "defer",
|
|
7417
|
-
destination,
|
|
7600
|
+
...args.destination ? { destination: args.destination } : void 0,
|
|
7418
7601
|
inboundMessageId: args.messageId,
|
|
7419
7602
|
input: {
|
|
7420
7603
|
authorId: args.actor.userId,
|
|
@@ -7436,7 +7619,11 @@ function buildWebInboundMessage(args) {
|
|
|
7436
7619
|
...traceContext ? { traceContext } : void 0
|
|
7437
7620
|
};
|
|
7438
7621
|
}
|
|
7439
|
-
/**
|
|
7622
|
+
/**
|
|
7623
|
+
* Record web activity and create a Conversation root when needed. Returns the
|
|
7624
|
+
* Destination for the Message's work. A child's work keeps none, so its
|
|
7625
|
+
* workers read the Conversation.
|
|
7626
|
+
*/
|
|
7440
7627
|
async function recordWebConversationActivity(args) {
|
|
7441
7628
|
const store = args.conversationStore ?? getConversationStore();
|
|
7442
7629
|
const existing = await store.get({ conversationId: args.conversationId });
|
|
@@ -7456,7 +7643,7 @@ async function recordWebConversationActivity(args) {
|
|
|
7456
7643
|
...source ? { sessionSource: source } : void 0,
|
|
7457
7644
|
...isNewRoot ? { visibility } : void 0
|
|
7458
7645
|
});
|
|
7459
|
-
return destination;
|
|
7646
|
+
return existing && existing.kind !== "root" ? void 0 : destination;
|
|
7460
7647
|
}
|
|
7461
7648
|
/** Create a Conversation from web input and enqueue its first Message. */
|
|
7462
7649
|
async function createAndEnqueueConversation(input, options) {
|
|
@@ -7522,6 +7709,7 @@ async function appendAndEnqueueWebMessage(input, options) {
|
|
|
7522
7709
|
try {
|
|
7523
7710
|
result = await enqueueTo(destination);
|
|
7524
7711
|
} catch (error) {
|
|
7712
|
+
if (!destination) throw error;
|
|
7525
7713
|
const stored = await (options.conversationStore ?? getConversationStore()).get({ conversationId: input.conversationId });
|
|
7526
7714
|
const current = resolveConversationDestination({
|
|
7527
7715
|
conversationId: input.conversationId,
|
|
@@ -7641,7 +7829,7 @@ async function sendOne(args) {
|
|
|
7641
7829
|
const record = reviewItemChangeRecord(args.item, args.change);
|
|
7642
7830
|
if ("user" in args.change) {
|
|
7643
7831
|
const conversation = await getConversationStore().get({ conversationId: args.conversationId });
|
|
7644
|
-
if (acceptsWebMessages(
|
|
7832
|
+
if (conversation && acceptsWebMessages(conversation)) {
|
|
7645
7833
|
await appendAndEnqueueWebMessage({
|
|
7646
7834
|
actor: webActorFromUser(args.change.user),
|
|
7647
7835
|
conversationId: args.conversationId,
|
|
@@ -8238,6 +8426,8 @@ function searchableResourceTypes(catalog) {
|
|
|
8238
8426
|
/** Create the read-only tool that searches enabled event types. */
|
|
8239
8427
|
function createSearchEventTypesTool(catalog) {
|
|
8240
8428
|
return zodTool({
|
|
8429
|
+
exposure: "deferred",
|
|
8430
|
+
source: RESOURCE_WATCH_TOOL_SOURCE,
|
|
8241
8431
|
annotations: {
|
|
8242
8432
|
destructiveHint: false,
|
|
8243
8433
|
idempotentHint: true,
|
|
@@ -10118,6 +10308,12 @@ function scheduledAutomationRunAttributes(task, run, extras = {}) {
|
|
|
10118
10308
|
function logScheduledAutomationRunSkipped(task, run, extras = {}) {
|
|
10119
10309
|
logInfo("scheduled_automation.run.skipped", scheduledAutomationRunAttributes(task, run, extras));
|
|
10120
10310
|
}
|
|
10311
|
+
// src/chat/automations/tool-source.ts
|
|
10312
|
+
/** Deferred tool catalog source for the Automation tools. */
|
|
10313
|
+
const AUTOMATIONS_TOOL_SOURCE = {
|
|
10314
|
+
id: "automations",
|
|
10315
|
+
description: "Create, find, change, delete, or run scheduled and event automations."
|
|
10316
|
+
};
|
|
10121
10317
|
// src/chat/automations/tools/create.ts
|
|
10122
10318
|
/** Compile a schedule in the timezone that the request or creator uses. */
|
|
10123
10319
|
async function compileSchedule(caller, creator, destination, trigger, nowMs) {
|
|
@@ -10209,6 +10405,8 @@ async function readReplayedAutomation(kind, id) {
|
|
|
10209
10405
|
function createAutomationTool(context, catalog) {
|
|
10210
10406
|
const trigger = automationTriggerSchema(catalog);
|
|
10211
10407
|
return zodTool({
|
|
10408
|
+
exposure: "deferred",
|
|
10409
|
+
source: AUTOMATIONS_TOOL_SOURCE,
|
|
10212
10410
|
approvalMode: "review",
|
|
10213
10411
|
annotations: {
|
|
10214
10412
|
destructiveHint: false,
|
|
@@ -10285,6 +10483,8 @@ function createAutomationTool(context, catalog) {
|
|
|
10285
10483
|
/** Create the tool that deletes one Automation. */
|
|
10286
10484
|
function createDeleteAutomationTool(context, catalog) {
|
|
10287
10485
|
return zodTool({
|
|
10486
|
+
exposure: "deferred",
|
|
10487
|
+
source: AUTOMATIONS_TOOL_SOURCE,
|
|
10288
10488
|
approvalMode: "review",
|
|
10289
10489
|
annotations: {
|
|
10290
10490
|
destructiveHint: true,
|
|
@@ -10312,6 +10512,8 @@ function createDeleteAutomationTool(context, catalog) {
|
|
|
10312
10512
|
/** Create the tool that marks an active scheduled Automation due now. */
|
|
10313
10513
|
function createRunAutomationNowTool(context, catalog) {
|
|
10314
10514
|
return zodTool({
|
|
10515
|
+
exposure: "deferred",
|
|
10516
|
+
source: AUTOMATIONS_TOOL_SOURCE,
|
|
10315
10517
|
approvalMode: "review",
|
|
10316
10518
|
annotations: {
|
|
10317
10519
|
destructiveHint: false,
|
|
@@ -10351,6 +10553,8 @@ function createRunAutomationNowTool(context, catalog) {
|
|
|
10351
10553
|
*/
|
|
10352
10554
|
function createSearchAutomationsTool(context, catalog) {
|
|
10353
10555
|
return zodTool({
|
|
10556
|
+
exposure: "deferred",
|
|
10557
|
+
source: AUTOMATIONS_TOOL_SOURCE,
|
|
10354
10558
|
annotations: {
|
|
10355
10559
|
destructiveHint: false,
|
|
10356
10560
|
idempotentHint: true,
|
|
@@ -10706,7 +10910,19 @@ async function updateEvent(current, input, editor, catalog) {
|
|
|
10706
10910
|
/** Create the tool that edits, pauses, resumes, or moves one Automation. */
|
|
10707
10911
|
function createUpdateAutomationTool(context, catalog) {
|
|
10708
10912
|
const trigger = automationTriggerChangesSchema(catalog);
|
|
10913
|
+
const inputSchema = z.object({
|
|
10914
|
+
automation_id: z.string().min(1).describe("ID of the automation, from searchAutomations or its dashboard URL."),
|
|
10915
|
+
title: automationTitleSchema.optional(),
|
|
10916
|
+
instruction: automationInstructionToolSchema.nullable().optional(),
|
|
10917
|
+
trigger: trigger.nullable().describe("Replacement trigger of the same type. For an event trigger, match changes only the filters that it names. Omit or use null to keep the trigger.").optional(),
|
|
10918
|
+
outcomes: z.array(taskOutcomeInputSchema).max(5).nullable().describe("Replacement messages to send after successful work. Use an empty list to send nothing. Omit or use null to leave unchanged.").optional(),
|
|
10919
|
+
credential_mode: z.enum(["system", "creator"]).nullable().describe("Set creator to make the automation creator's credentials available, or system to disable them. Creator always means the automation's createdBy actor, never the current requester. Only that creator may enable creator mode. Omit or use null to leave unchanged.").optional(),
|
|
10920
|
+
status: z.enum(["active", "paused"]).nullable().describe("Set active to resume a paused or blocked automation, or paused to stop it. When it uses its creator's credentials, only the creator can resume it. Omit or use null to leave unchanged.").optional(),
|
|
10921
|
+
destination: slackChannelRefParam.nullable().describe("Where to move a scheduled automation. Set \"current_conversation\" for the channel or DM of this conversation, or name a public Slack channel by id, mention, or known name. Omit to keep its destination.").optional()
|
|
10922
|
+
}).strict();
|
|
10709
10923
|
return zodTool({
|
|
10924
|
+
exposure: "deferred",
|
|
10925
|
+
source: AUTOMATIONS_TOOL_SOURCE,
|
|
10710
10926
|
approvalMode: "review",
|
|
10711
10927
|
annotations: {
|
|
10712
10928
|
destructiveHint: true,
|
|
@@ -10716,16 +10932,7 @@ function createUpdateAutomationTool(context, catalog) {
|
|
|
10716
10932
|
},
|
|
10717
10933
|
executionMode: "sequential",
|
|
10718
10934
|
description: "Update the title, instruction, trigger, outcomes, credential use, or status of a scheduled or event automation. Anyone in the workspace can update anything on an automation in a public channel, including its outcomes and destination. Automations in private channels and DMs can be updated from there or by their creator, and only their creator can move them. Only the creator can enable creator credentials. A non-creator who changes the instruction, trigger, outcomes, or destination switches it to system credentials. The trigger type cannot change. Set destination to move a scheduled automation to this conversation or to a public channel.",
|
|
10719
|
-
inputSchema
|
|
10720
|
-
automation_id: z.string().min(1).describe("ID of the automation, from searchAutomations or its dashboard URL."),
|
|
10721
|
-
title: automationTitleSchema.optional(),
|
|
10722
|
-
instruction: automationInstructionToolSchema.nullable().optional(),
|
|
10723
|
-
trigger: trigger.nullable().describe("Replacement trigger of the same type. For an event trigger, match changes only the filters that it names. Omit or use null to keep the trigger.").optional(),
|
|
10724
|
-
outcomes: z.array(taskOutcomeInputSchema).max(5).nullable().describe("Replacement messages to send after successful work. Use an empty list to send nothing. Omit or use null to leave unchanged.").optional(),
|
|
10725
|
-
credential_mode: z.enum(["system", "creator"]).nullable().describe("Set creator to make the automation creator's credentials available, or system to disable them. Creator always means the automation's createdBy actor, never the current requester. Only that creator may enable creator mode. Omit or use null to leave unchanged.").optional(),
|
|
10726
|
-
status: z.enum(["active", "paused"]).nullable().describe("Set active to resume a paused or blocked automation, or paused to stop it. When it uses its creator's credentials, only the creator can resume it. Omit or use null to leave unchanged.").optional(),
|
|
10727
|
-
destination: slackChannelRefParam.nullable().describe("Where to move a scheduled automation. Set \"current_conversation\" for the channel or DM of this conversation, or name a public Slack channel by id, mention, or known name. Omit to keep its destination.").optional()
|
|
10728
|
-
}).strict(),
|
|
10935
|
+
inputSchema,
|
|
10729
10936
|
prepareArguments(args) {
|
|
10730
10937
|
return Object.fromEntries(Object.entries(args).filter(([, value]) => value != null));
|
|
10731
10938
|
},
|
|
@@ -10791,10 +10998,18 @@ function createAutomationTools(context, catalog) {
|
|
|
10791
10998
|
runAutomationNow: createRunAutomationNowTool(automationContext, catalog)
|
|
10792
10999
|
}, automationToolsDisabledReason(context));
|
|
10793
11000
|
}
|
|
11001
|
+
// src/chat/slack/tool-support/tool-source.ts
|
|
11002
|
+
/** Deferred tool catalog source for less common Slack actions. */
|
|
11003
|
+
const SLACK_TOOL_SOURCE = {
|
|
11004
|
+
id: "slack",
|
|
11005
|
+
description: "Slack canvases, Slack lists, emoji reactions, and joining public channels."
|
|
11006
|
+
};
|
|
10794
11007
|
// src/chat/slack/tools/channel-join.ts
|
|
10795
11008
|
/** Create a tool that joins one public Slack channel. */
|
|
10796
11009
|
function createSlackChannelJoinTool(context) {
|
|
10797
11010
|
return zodTool({
|
|
11011
|
+
exposure: "deferred",
|
|
11012
|
+
source: SLACK_TOOL_SOURCE,
|
|
10798
11013
|
description: "Join a public Slack channel.",
|
|
10799
11014
|
annotations: {
|
|
10800
11015
|
destructiveHint: false,
|
|
@@ -11516,6 +11731,8 @@ function createOperationKey(toolName, input) {
|
|
|
11516
11731
|
/** Create the tool that reacts to the current inbound Slack message. */
|
|
11517
11732
|
function createSlackMessageAddReactionTool(context, state) {
|
|
11518
11733
|
return zodTool({
|
|
11734
|
+
exposure: "deferred",
|
|
11735
|
+
source: SLACK_TOOL_SOURCE,
|
|
11519
11736
|
approvalMode: "approve",
|
|
11520
11737
|
annotations: {
|
|
11521
11738
|
destructiveHint: false,
|
|
@@ -12474,6 +12691,8 @@ async function readCanvas(canvasIdOrUrl) {
|
|
|
12474
12691
|
/** Create a tool that provisions a new Slack canvas in the active channel. */
|
|
12475
12692
|
function createSlackCanvasCreateTool(context, state) {
|
|
12476
12693
|
return zodTool({
|
|
12694
|
+
exposure: "deferred",
|
|
12695
|
+
source: SLACK_TOOL_SOURCE,
|
|
12477
12696
|
annotations: {
|
|
12478
12697
|
destructiveHint: false,
|
|
12479
12698
|
idempotentHint: false,
|
|
@@ -12558,6 +12777,8 @@ const slackCanvasEditOutputSchema = juniorToolOutputSchema.extend({
|
|
|
12558
12777
|
/** Create a tool that edits a Slack canvas like a markdown file. */
|
|
12559
12778
|
function createSlackCanvasEditTool(state) {
|
|
12560
12779
|
return zodTool({
|
|
12780
|
+
exposure: "deferred",
|
|
12781
|
+
source: SLACK_TOOL_SOURCE,
|
|
12561
12782
|
annotations: {
|
|
12562
12783
|
destructiveHint: true,
|
|
12563
12784
|
idempotentHint: true,
|
|
@@ -12642,6 +12863,8 @@ function canvasLines(content, offset, limit) {
|
|
|
12642
12863
|
*/
|
|
12643
12864
|
function createSlackCanvasReadTool() {
|
|
12644
12865
|
return zodTool({
|
|
12866
|
+
exposure: "deferred",
|
|
12867
|
+
source: SLACK_TOOL_SOURCE,
|
|
12645
12868
|
description: "Read a Slack canvas as markdown. Returns the whole canvas unless you set offset or limit.",
|
|
12646
12869
|
annotations: {
|
|
12647
12870
|
destructiveHint: false,
|
|
@@ -12688,6 +12911,8 @@ function createSlackCanvasReadTool() {
|
|
|
12688
12911
|
/** Create a tool that deliberately replaces a Slack canvas body. */
|
|
12689
12912
|
function createSlackCanvasWriteTool(state) {
|
|
12690
12913
|
return zodTool({
|
|
12914
|
+
exposure: "deferred",
|
|
12915
|
+
source: SLACK_TOOL_SOURCE,
|
|
12691
12916
|
annotations: {
|
|
12692
12917
|
destructiveHint: true,
|
|
12693
12918
|
idempotentHint: true,
|
|
@@ -12912,6 +13137,8 @@ function parseRequiredSlackUserIdParam(field, value) {
|
|
|
12912
13137
|
/** Create a tool that appends items to an explicit Slack list. */
|
|
12913
13138
|
function createSlackListAddItemsTool(state) {
|
|
12914
13139
|
return zodTool({
|
|
13140
|
+
exposure: "deferred",
|
|
13141
|
+
source: SLACK_TOOL_SOURCE,
|
|
12915
13142
|
annotations: {
|
|
12916
13143
|
destructiveHint: false,
|
|
12917
13144
|
idempotentHint: false,
|
|
@@ -12960,6 +13187,8 @@ function createSlackListAddItemsTool(state) {
|
|
|
12960
13187
|
/** Create a tool that provisions a new Slack todo list. */
|
|
12961
13188
|
function createSlackListCreateTool(state) {
|
|
12962
13189
|
return zodTool({
|
|
13190
|
+
exposure: "deferred",
|
|
13191
|
+
source: SLACK_TOOL_SOURCE,
|
|
12963
13192
|
annotations: {
|
|
12964
13193
|
destructiveHint: false,
|
|
12965
13194
|
idempotentHint: false,
|
|
@@ -12991,6 +13220,8 @@ function createSlackListCreateTool(state) {
|
|
|
12991
13220
|
/** Create a tool that reads items from an explicit Slack list. */
|
|
12992
13221
|
function createSlackListGetItemsTool() {
|
|
12993
13222
|
return zodTool({
|
|
13223
|
+
exposure: "deferred",
|
|
13224
|
+
source: SLACK_TOOL_SOURCE,
|
|
12994
13225
|
description: "Read items from a Slack list.",
|
|
12995
13226
|
annotations: {
|
|
12996
13227
|
destructiveHint: false,
|
|
@@ -13030,6 +13261,8 @@ const updateListItemInputSchema = z.union([z.object({
|
|
|
13030
13261
|
/** Create a tool that updates an item in an explicit Slack list. */
|
|
13031
13262
|
function createSlackListUpdateItemTool(state) {
|
|
13032
13263
|
return zodTool({
|
|
13264
|
+
exposure: "deferred",
|
|
13265
|
+
source: SLACK_TOOL_SOURCE,
|
|
13033
13266
|
annotations: {
|
|
13034
13267
|
destructiveHint: true,
|
|
13035
13268
|
idempotentHint: true,
|
|
@@ -13933,6 +14166,10 @@ function createOperatorTools(context) {
|
|
|
13933
14166
|
}) };
|
|
13934
14167
|
}
|
|
13935
14168
|
// src/chat/tools/user-customization.ts
|
|
14169
|
+
const USER_CUSTOMIZATION_TOOL_SOURCE = {
|
|
14170
|
+
id: "user-customization",
|
|
14171
|
+
description: "Save how replies change for the current user."
|
|
14172
|
+
};
|
|
13936
14173
|
/**
|
|
13937
14174
|
* Build the tool that saves the current user's customization when the app
|
|
13938
14175
|
* enables `user-customization`. An Agent invocation never gets it, because
|
|
@@ -13942,6 +14179,8 @@ function createUserCustomizationTools(context) {
|
|
|
13942
14179
|
if (!isExperimentalFeatureEnabled("user-customization")) return {};
|
|
13943
14180
|
if (context.agentInvocationId) return {};
|
|
13944
14181
|
return { updateUserCustomization: zodTool({
|
|
14182
|
+
exposure: "deferred",
|
|
14183
|
+
source: USER_CUSTOMIZATION_TOOL_SOURCE,
|
|
13945
14184
|
executionMode: "sequential",
|
|
13946
14185
|
annotations: {
|
|
13947
14186
|
destructiveHint: false,
|
|
@@ -14111,6 +14350,8 @@ const outputSchema$1 = juniorToolOutputSchema.extend({
|
|
|
14111
14350
|
/** Create a tool that publishes one sandbox image at a public internet URL. */
|
|
14112
14351
|
function createPublishImageTool(args) {
|
|
14113
14352
|
return zodTool({
|
|
14353
|
+
exposure: "deferred",
|
|
14354
|
+
source: IMAGES_TOOL_SOURCE,
|
|
14114
14355
|
annotations: {
|
|
14115
14356
|
destructiveHint: false,
|
|
14116
14357
|
idempotentHint: true,
|
|
@@ -14152,6 +14393,8 @@ const outputSchema = juniorToolOutputSchema.extend({
|
|
|
14152
14393
|
/** Create a tool that stops serving one previously published public image. */
|
|
14153
14394
|
function createUnpublishImageTool(args) {
|
|
14154
14395
|
return zodTool({
|
|
14396
|
+
exposure: "deferred",
|
|
14397
|
+
source: IMAGES_TOOL_SOURCE,
|
|
14155
14398
|
annotations: {
|
|
14156
14399
|
destructiveHint: true,
|
|
14157
14400
|
idempotentHint: true,
|
|
@@ -15222,6 +15465,10 @@ async function readStats(start, end) {
|
|
|
15222
15465
|
return await getDb().select().from(juniorStats).where(and(gte(juniorStats.date, start), lte(juniorStats.date, end))).orderBy(asc(juniorStats.date), asc(juniorStats.namespace), asc(juniorStats.metric), asc(juniorStats.name));
|
|
15223
15466
|
}
|
|
15224
15467
|
// src/chat/workspaces/tools.ts
|
|
15468
|
+
const WORKSPACES_TOOL_SOURCE = {
|
|
15469
|
+
id: "workspaces",
|
|
15470
|
+
description: "Create, replace, or delete Workspace recipes."
|
|
15471
|
+
};
|
|
15225
15472
|
/** Record optional reporting without changing the switchWorkspace outcome. */
|
|
15226
15473
|
async function tryRecordWorkspaceSwitchStat(workspace) {
|
|
15227
15474
|
if (!process.env.DATABASE_URL) return;
|
|
@@ -15342,6 +15589,8 @@ function createWorkspaceWriteTools(providers) {
|
|
|
15342
15589
|
const { providerNames, workspaceInputSchema } = workspaceWriteSchemas(providers);
|
|
15343
15590
|
return {
|
|
15344
15591
|
createWorkspace: zodTool({
|
|
15592
|
+
exposure: "deferred",
|
|
15593
|
+
source: WORKSPACES_TOOL_SOURCE,
|
|
15345
15594
|
approvalMode: "review",
|
|
15346
15595
|
describeProposal: (input) => describeWorkspaceWrite("Create", input),
|
|
15347
15596
|
executionMode: "sequential",
|
|
@@ -15360,6 +15609,8 @@ function createWorkspaceWriteTools(providers) {
|
|
|
15360
15609
|
}
|
|
15361
15610
|
}),
|
|
15362
15611
|
updateWorkspace: zodTool({
|
|
15612
|
+
exposure: "deferred",
|
|
15613
|
+
source: WORKSPACES_TOOL_SOURCE,
|
|
15363
15614
|
approvalMode: "review",
|
|
15364
15615
|
describeProposal: ({ id: _id, ...input }) => describeWorkspaceWrite("Replace", input),
|
|
15365
15616
|
executionMode: "sequential",
|
|
@@ -15386,6 +15637,8 @@ function createWorkspaceWriteTools(providers) {
|
|
|
15386
15637
|
}
|
|
15387
15638
|
}),
|
|
15388
15639
|
deleteWorkspace: zodTool({
|
|
15640
|
+
exposure: "deferred",
|
|
15641
|
+
source: WORKSPACES_TOOL_SOURCE,
|
|
15389
15642
|
approvalMode: "review",
|
|
15390
15643
|
describeProposal: ({ id }) => `Delete Workspace ${id}.`,
|
|
15391
15644
|
executionMode: "sequential",
|
|
@@ -15532,9 +15785,6 @@ function createTools(availableSkills, hooks = {}, context, options = {}) {
|
|
|
15532
15785
|
bash: createBashTool(),
|
|
15533
15786
|
readFile: createReadFileTool(),
|
|
15534
15787
|
editFile: createEditFileTool(),
|
|
15535
|
-
grep: createGrepTool(),
|
|
15536
|
-
findFiles: createFindFilesTool(),
|
|
15537
|
-
listDir: createListDirTool(),
|
|
15538
15788
|
writeFile: createWriteFileTool(),
|
|
15539
15789
|
webSearch: createWebSearchTool(botConfig.webSearchModelId, hooks.toolOverrides?.webSearch),
|
|
15540
15790
|
webFetch: createWebFetchTool(hooks, { canSendFilesToActiveConversation }),
|
|
@@ -15743,24 +15993,6 @@ function buildSandboxInput(toolName, params) {
|
|
|
15743
15993
|
path: String(params.path ?? ""),
|
|
15744
15994
|
edits: Array.isArray(params.edits) ? params.edits : []
|
|
15745
15995
|
};
|
|
15746
|
-
if (toolName === "grep") return {
|
|
15747
|
-
pattern: String(params.pattern ?? ""),
|
|
15748
|
-
...typeof params.path === "string" ? { path: params.path } : void 0,
|
|
15749
|
-
...typeof params.glob === "string" ? { glob: params.glob } : void 0,
|
|
15750
|
-
...typeof params.ignore_case === "boolean" ? { ignoreCase: params.ignore_case } : void 0,
|
|
15751
|
-
...typeof params.literal === "boolean" ? { literal: params.literal } : void 0,
|
|
15752
|
-
...optionalNumber(params.context) ? { context: optionalNumber(params.context) } : void 0,
|
|
15753
|
-
...optionalNumber(params.limit) ? { limit: optionalNumber(params.limit) } : void 0
|
|
15754
|
-
};
|
|
15755
|
-
if (toolName === "findFiles") return {
|
|
15756
|
-
pattern: String(params.pattern ?? ""),
|
|
15757
|
-
...typeof params.path === "string" ? { path: params.path } : void 0,
|
|
15758
|
-
...optionalNumber(params.limit) ? { limit: optionalNumber(params.limit) } : void 0
|
|
15759
|
-
};
|
|
15760
|
-
if (toolName === "listDir") return {
|
|
15761
|
-
...typeof params.path === "string" ? { path: params.path } : void 0,
|
|
15762
|
-
...optionalNumber(params.limit) ? { limit: optionalNumber(params.limit) } : void 0
|
|
15763
|
-
};
|
|
15764
15996
|
if (toolName === "writeFile") return {
|
|
15765
15997
|
path: String(params.path ?? ""),
|
|
15766
15998
|
content: String(params.content ?? "")
|
|
@@ -16245,11 +16477,11 @@ function createExecuteToolTool() {
|
|
|
16245
16477
|
openWorldHint: true,
|
|
16246
16478
|
readOnlyHint: false
|
|
16247
16479
|
},
|
|
16248
|
-
description: "Execute
|
|
16480
|
+
description: "Execute a catalog tool by exact tool_name. Use it for a tool that is not in your tool list: one that searchTools returned, or one that a skill, tool result, or error names. Put tool-specific parameters inside arguments.",
|
|
16249
16481
|
executionMode: "sequential",
|
|
16250
16482
|
exposure: "modelOnly",
|
|
16251
16483
|
inputSchema: z.object({
|
|
16252
|
-
tool_name: z.string().min(1).describe("Exact catalog tool_name
|
|
16484
|
+
tool_name: z.string().min(1).describe("Exact catalog tool_name, from searchTools or as named by a skill, tool result, or error."),
|
|
16253
16485
|
arguments: z.record(z.string(), z.unknown()).describe("Arguments matching the selected catalog tool schema, for example { \"query\": \"...\" }.").optional()
|
|
16254
16486
|
}).strict(),
|
|
16255
16487
|
outputSchema: juniorToolOutputSchema,
|
|
@@ -16299,8 +16531,91 @@ const SEARCH_FIELD_WEIGHTS = [
|
|
|
16299
16531
|
4,
|
|
16300
16532
|
1
|
|
16301
16533
|
];
|
|
16534
|
+
const MIN_RELATIVE_SCORE = .3;
|
|
16302
16535
|
const BM25_K1 = 1.2;
|
|
16303
|
-
const BM25_B =
|
|
16536
|
+
const BM25_B = [
|
|
16537
|
+
.75,
|
|
16538
|
+
.3,
|
|
16539
|
+
.75
|
|
16540
|
+
];
|
|
16541
|
+
const SYNONYM_WEIGHT = .6;
|
|
16542
|
+
const NAME_MATCH_BOOST = 1;
|
|
16543
|
+
const NO_MATCH_NOTE = "No tool fits this query. Try other words, or search with only source to list its tools.";
|
|
16544
|
+
const SEARCH_SYNONYM_GROUPS = [
|
|
16545
|
+
[
|
|
16546
|
+
"get",
|
|
16547
|
+
"fetch",
|
|
16548
|
+
"read",
|
|
16549
|
+
"view",
|
|
16550
|
+
"show",
|
|
16551
|
+
"retrieve",
|
|
16552
|
+
"look"
|
|
16553
|
+
],
|
|
16554
|
+
[
|
|
16555
|
+
"update",
|
|
16556
|
+
"edit",
|
|
16557
|
+
"change",
|
|
16558
|
+
"modify",
|
|
16559
|
+
"set",
|
|
16560
|
+
"rename"
|
|
16561
|
+
],
|
|
16562
|
+
[
|
|
16563
|
+
"create",
|
|
16564
|
+
"add",
|
|
16565
|
+
"new",
|
|
16566
|
+
"make",
|
|
16567
|
+
"write"
|
|
16568
|
+
],
|
|
16569
|
+
[
|
|
16570
|
+
"delete",
|
|
16571
|
+
"remove",
|
|
16572
|
+
"archive",
|
|
16573
|
+
"forget",
|
|
16574
|
+
"drop",
|
|
16575
|
+
"discard"
|
|
16576
|
+
],
|
|
16577
|
+
[
|
|
16578
|
+
"search",
|
|
16579
|
+
"find",
|
|
16580
|
+
"query",
|
|
16581
|
+
"lookup",
|
|
16582
|
+
"look"
|
|
16583
|
+
],
|
|
16584
|
+
[
|
|
16585
|
+
"list",
|
|
16586
|
+
"show",
|
|
16587
|
+
"all",
|
|
16588
|
+
"enumerate"
|
|
16589
|
+
],
|
|
16590
|
+
[
|
|
16591
|
+
"comment",
|
|
16592
|
+
"reply",
|
|
16593
|
+
"respond"
|
|
16594
|
+
],
|
|
16595
|
+
[
|
|
16596
|
+
"stop",
|
|
16597
|
+
"cancel",
|
|
16598
|
+
"unwatch",
|
|
16599
|
+
"unsubscribe"
|
|
16600
|
+
],
|
|
16601
|
+
[
|
|
16602
|
+
"watch",
|
|
16603
|
+
"subscribe",
|
|
16604
|
+
"monitor",
|
|
16605
|
+
"follow"
|
|
16606
|
+
],
|
|
16607
|
+
[
|
|
16608
|
+
"save",
|
|
16609
|
+
"store",
|
|
16610
|
+
"remember",
|
|
16611
|
+
"memorize"
|
|
16612
|
+
]
|
|
16613
|
+
];
|
|
16614
|
+
const SEARCH_ABBREVIATIONS = {
|
|
16615
|
+
pr: ["pull", "request"],
|
|
16616
|
+
repo: ["repository"],
|
|
16617
|
+
msg: ["message"]
|
|
16618
|
+
};
|
|
16304
16619
|
const SEARCH_STOP_WORDS = /* @__PURE__ */ new Set([
|
|
16305
16620
|
"a",
|
|
16306
16621
|
"an",
|
|
@@ -16345,13 +16660,6 @@ const searchToolsSourceSchema = z.object({
|
|
|
16345
16660
|
const searchToolsToolSchema = z.object({
|
|
16346
16661
|
tool_name: z.string(),
|
|
16347
16662
|
description: z.string(),
|
|
16348
|
-
exposure: z.enum([
|
|
16349
|
-
"direct",
|
|
16350
|
-
"deferred",
|
|
16351
|
-
"modelOnly",
|
|
16352
|
-
"codemode",
|
|
16353
|
-
"hidden"
|
|
16354
|
-
]),
|
|
16355
16663
|
source: z.string().optional(),
|
|
16356
16664
|
input_schema: z.unknown(),
|
|
16357
16665
|
call_notes: z.array(z.string()),
|
|
@@ -16366,20 +16674,62 @@ const searchToolsOutputSchema = juniorToolOutputSchema.extend({
|
|
|
16366
16674
|
total_matches: z.number().int().nonnegative(),
|
|
16367
16675
|
returned_tools: z.number().int().nonnegative(),
|
|
16368
16676
|
execution_tool: z.literal("executeTool"),
|
|
16369
|
-
tools: z.array(searchToolsToolSchema)
|
|
16677
|
+
tools: z.array(searchToolsToolSchema),
|
|
16678
|
+
note: z.string().optional()
|
|
16370
16679
|
}).strict();
|
|
16371
|
-
function
|
|
16680
|
+
function stem(term) {
|
|
16681
|
+
if (term.length <= 3) return term;
|
|
16682
|
+
let stemmed = term;
|
|
16683
|
+
if (stemmed.endsWith("ies")) stemmed = `${stemmed.slice(0, -3)}y`;
|
|
16684
|
+
else if (/(?:ss|us|ch|sh|x|z)es$/.test(stemmed)) stemmed = stemmed.slice(0, -2);
|
|
16685
|
+
else if (/[^sui]s$/.test(stemmed)) stemmed = stemmed.slice(0, -1);
|
|
16686
|
+
const verbSuffix = /(?:ed|ing)$/.exec(stemmed);
|
|
16687
|
+
if (verbSuffix && stemmed.length - verbSuffix[0].length >= 3) stemmed = stemmed.slice(0, -verbSuffix[0].length);
|
|
16688
|
+
if (stemmed.length > 3 && stemmed.endsWith("e")) stemmed = stemmed.slice(0, -1);
|
|
16689
|
+
return stemmed;
|
|
16690
|
+
}
|
|
16691
|
+
function camelCaseWords(chunk) {
|
|
16692
|
+
return chunk.replace(/([a-z\d])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").toLowerCase().split(/\s+/);
|
|
16693
|
+
}
|
|
16694
|
+
function rawTerms(value) {
|
|
16372
16695
|
const chunks = value.match(/[\p{L}\p{N}]+/gu) ?? [];
|
|
16373
16696
|
const result = [];
|
|
16374
16697
|
for (const chunk of chunks) {
|
|
16375
16698
|
result.push(chunk.toLowerCase());
|
|
16376
|
-
const expanded = chunk
|
|
16699
|
+
const expanded = camelCaseWords(chunk);
|
|
16377
16700
|
if (expanded.length > 1) result.push(...expanded);
|
|
16378
16701
|
}
|
|
16379
16702
|
return result;
|
|
16380
16703
|
}
|
|
16704
|
+
function nameParts(name) {
|
|
16705
|
+
const words = (name.match(/[\p{L}\p{N}]+/gu) ?? []).flatMap(camelCaseWords).filter((word) => !SEARCH_STOP_WORDS.has(word)).map(stem);
|
|
16706
|
+
return {
|
|
16707
|
+
action: words[0],
|
|
16708
|
+
objects: words.slice(1)
|
|
16709
|
+
};
|
|
16710
|
+
}
|
|
16711
|
+
function expandAbbreviation(term) {
|
|
16712
|
+
return SEARCH_ABBREVIATIONS[term]?.map(stem) ?? [term];
|
|
16713
|
+
}
|
|
16714
|
+
function terms(value) {
|
|
16715
|
+
return rawTerms(value).map(stem);
|
|
16716
|
+
}
|
|
16717
|
+
const synonymsByTerm = /* @__PURE__ */ new Map();
|
|
16718
|
+
for (const group of SEARCH_SYNONYM_GROUPS) {
|
|
16719
|
+
const stems = group.map(stem);
|
|
16720
|
+
for (const term of stems) {
|
|
16721
|
+
const synonyms = synonymsByTerm.get(term) ?? /* @__PURE__ */ new Set();
|
|
16722
|
+
for (const synonym of stems) if (synonym !== term) synonyms.add(synonym);
|
|
16723
|
+
synonymsByTerm.set(term, synonyms);
|
|
16724
|
+
}
|
|
16725
|
+
}
|
|
16381
16726
|
function queryTerms(query) {
|
|
16382
|
-
return [...new Set(
|
|
16727
|
+
return [...new Set(rawTerms(query).filter((term) => term.length >= 2 && !SEARCH_STOP_WORDS.has(term)).map(stem).flatMap(expandAbbreviation))].map((term) => {
|
|
16728
|
+
const weights = /* @__PURE__ */ new Map();
|
|
16729
|
+
for (const synonym of synonymsByTerm.get(term) ?? []) weights.set(synonym, SYNONYM_WEIGHT);
|
|
16730
|
+
weights.set(term, 1);
|
|
16731
|
+
return weights;
|
|
16732
|
+
});
|
|
16383
16733
|
}
|
|
16384
16734
|
/** Summarize catalog descriptions before rendering them into model-visible data. */
|
|
16385
16735
|
function summarizeModelVisibleDescription(description) {
|
|
@@ -16387,14 +16737,26 @@ function summarizeModelVisibleDescription(description) {
|
|
|
16387
16737
|
if (normalized.length <= MODEL_VISIBLE_DESCRIPTION_CAP) return normalized;
|
|
16388
16738
|
return `${normalized.slice(0, 177).trimEnd()}...`;
|
|
16389
16739
|
}
|
|
16390
|
-
function
|
|
16391
|
-
|
|
16392
|
-
|
|
16393
|
-
|
|
16394
|
-
|
|
16395
|
-
|
|
16396
|
-
|
|
16397
|
-
|
|
16740
|
+
function parameterText(schema) {
|
|
16741
|
+
if (Array.isArray(schema)) return schema.flatMap(parameterText);
|
|
16742
|
+
if (!schema || typeof schema !== "object") return [];
|
|
16743
|
+
const record = schema;
|
|
16744
|
+
const text = [];
|
|
16745
|
+
if (typeof record.description === "string") text.push(record.description);
|
|
16746
|
+
const properties = record.properties;
|
|
16747
|
+
if (properties && typeof properties === "object") for (const [name, property] of Object.entries(properties)) text.push(name, ...parameterText(property));
|
|
16748
|
+
for (const key of [
|
|
16749
|
+
"items",
|
|
16750
|
+
"anyOf",
|
|
16751
|
+
"oneOf",
|
|
16752
|
+
"allOf"
|
|
16753
|
+
]) text.push(...parameterText(record[key]));
|
|
16754
|
+
return text;
|
|
16755
|
+
}
|
|
16756
|
+
function withoutToolReferences(text, name, toolNames) {
|
|
16757
|
+
return text.split(/(?<=[.!?])\s+/).filter((sentence) => !(sentence.match(/[\w-]+/g) ?? []).some((word) => word !== name && toolNames.has(word))).join(" ");
|
|
16758
|
+
}
|
|
16759
|
+
function searchableToolFields(name, definition, toolNames) {
|
|
16398
16760
|
return [
|
|
16399
16761
|
terms([
|
|
16400
16762
|
name,
|
|
@@ -16402,64 +16764,91 @@ function searchableToolFields(name, definition) {
|
|
|
16402
16764
|
definition.identity?.name,
|
|
16403
16765
|
definition.identity?.plugin
|
|
16404
16766
|
].filter(Boolean).join(" ")),
|
|
16405
|
-
terms([
|
|
16767
|
+
terms(withoutToolReferences([
|
|
16406
16768
|
definition.description,
|
|
16407
16769
|
definition.promptSnippet,
|
|
16408
16770
|
...definition.promptGuidelines ?? []
|
|
16409
|
-
].filter(Boolean).join(" ")),
|
|
16410
|
-
terms([
|
|
16411
|
-
definition.source?.id,
|
|
16412
|
-
definition.source?.description,
|
|
16413
|
-
schemaText(definition.inputSchema),
|
|
16414
|
-
schemaText(definition.annotations ?? {})
|
|
16415
|
-
].filter(Boolean).join(" "))
|
|
16771
|
+
].filter(Boolean).join(" "), name, toolNames)),
|
|
16772
|
+
terms([definition.source?.id, ...parameterText(definition.inputSchema)].filter(Boolean).join(" "))
|
|
16416
16773
|
];
|
|
16417
16774
|
}
|
|
16418
16775
|
function prepareSearchDocuments(tools, source) {
|
|
16776
|
+
const toolNames = new Set(Object.keys(tools));
|
|
16419
16777
|
return Object.entries(tools).filter(([, definition]) => source ? definition.source?.id === source : true).map(([name, definition]) => ({
|
|
16420
16778
|
name,
|
|
16421
|
-
fields: searchableToolFields(name, definition)
|
|
16779
|
+
fields: searchableToolFields(name, definition, toolNames),
|
|
16780
|
+
...nameParts(definition.identity?.name ?? name)
|
|
16422
16781
|
}));
|
|
16423
16782
|
}
|
|
16424
16783
|
function averageFieldLengths(documents) {
|
|
16425
16784
|
if (documents.length === 0) return SEARCH_FIELD_WEIGHTS.map(() => 0);
|
|
16426
16785
|
return SEARCH_FIELD_WEIGHTS.map((_, fieldIndex) => documents.reduce((total, document) => total + document.fields[fieldIndex].length, 0) / documents.length);
|
|
16427
16786
|
}
|
|
16428
|
-
function
|
|
16429
|
-
const
|
|
16430
|
-
|
|
16431
|
-
const
|
|
16432
|
-
|
|
16433
|
-
|
|
16434
|
-
|
|
16435
|
-
}
|
|
16436
|
-
|
|
16437
|
-
|
|
16438
|
-
|
|
16439
|
-
|
|
16440
|
-
const
|
|
16441
|
-
|
|
16442
|
-
|
|
16443
|
-
|
|
16444
|
-
|
|
16445
|
-
|
|
16446
|
-
|
|
16447
|
-
|
|
16448
|
-
|
|
16787
|
+
function scoreQueryTerms(query, documents) {
|
|
16788
|
+
const documentTerms = documents.map((document) => new Set(document.fields.flat()));
|
|
16789
|
+
return query.map((weights) => {
|
|
16790
|
+
const documentFrequency = documentTerms.filter((terms) => [...weights.keys()].some((term) => terms.has(term))).length;
|
|
16791
|
+
return {
|
|
16792
|
+
weights,
|
|
16793
|
+
inverseDocumentFrequency: Math.log(1 + (documents.length - documentFrequency + .5) / (documentFrequency + .5))
|
|
16794
|
+
};
|
|
16795
|
+
});
|
|
16796
|
+
}
|
|
16797
|
+
function weightedTermFrequency(document, term, averageLengths) {
|
|
16798
|
+
return document.fields.reduce((weighted, field, fieldIndex) => {
|
|
16799
|
+
const termFrequency = field.filter((candidate) => candidate === term).length;
|
|
16800
|
+
if (termFrequency === 0) return weighted;
|
|
16801
|
+
const averageLength = averageLengths[fieldIndex] ?? 0;
|
|
16802
|
+
const lengthRatio = averageLength === 0 ? 1 : field.length / averageLength;
|
|
16803
|
+
return weighted + SEARCH_FIELD_WEIGHTS[fieldIndex] * (termFrequency / (1 - BM25_B[fieldIndex] + BM25_B[fieldIndex] * lengthRatio));
|
|
16804
|
+
}, 0);
|
|
16805
|
+
}
|
|
16806
|
+
function scoreSearchDocument(document, query, averageLengths) {
|
|
16807
|
+
return query.reduce((score, { weights, inverseDocumentFrequency }) => {
|
|
16808
|
+
let best = 0;
|
|
16809
|
+
for (const [term, weight] of weights) {
|
|
16810
|
+
const frequency = weightedTermFrequency(document, term, averageLengths);
|
|
16811
|
+
best = Math.max(best, weight * frequency * 2.2 / (frequency + BM25_K1));
|
|
16812
|
+
}
|
|
16813
|
+
return score + inverseDocumentFrequency * best;
|
|
16449
16814
|
}, 0);
|
|
16450
16815
|
}
|
|
16816
|
+
function nameMatch(document, query) {
|
|
16817
|
+
const { action, objects } = document;
|
|
16818
|
+
if (!action || objects.length === 0) return 0;
|
|
16819
|
+
let best = 0;
|
|
16820
|
+
query.forEach((term, actionIndex) => {
|
|
16821
|
+
const actionWeight = term.get(action) ?? 0;
|
|
16822
|
+
if (actionWeight === 0) return;
|
|
16823
|
+
const covered = objects.filter((object) => query.some((other, index) => index !== actionIndex && other.has(object))).length;
|
|
16824
|
+
best = Math.max(best, actionWeight * covered / objects.length);
|
|
16825
|
+
});
|
|
16826
|
+
return best;
|
|
16827
|
+
}
|
|
16828
|
+
function namesActionAndObject(documents, query) {
|
|
16829
|
+
const actionTerms = query.flatMap((term, index) => documents.some(({ action }) => action && term.has(action)) ? [index] : []);
|
|
16830
|
+
return query.some((term, index) => documents.some(({ objects }) => objects.some((object) => term.has(object))) && actionTerms.some((actionIndex) => actionIndex !== index));
|
|
16831
|
+
}
|
|
16451
16832
|
/** Rank matching catalog tools while keeping source filtering deterministic. */
|
|
16452
16833
|
function searchCatalogTools(tools, query, source) {
|
|
16453
16834
|
const documents = prepareSearchDocuments(tools, source);
|
|
16454
16835
|
if (!query.trim()) return documents.map(({ name }) => name).sort((left, right) => left.localeCompare(right));
|
|
16455
16836
|
const searchTerms = queryTerms(query);
|
|
16456
16837
|
if (searchTerms.length === 0) return [];
|
|
16838
|
+
const scoredTerms = scoreQueryTerms(searchTerms, documents);
|
|
16457
16839
|
const averageLengths = averageFieldLengths(documents);
|
|
16458
|
-
const
|
|
16459
|
-
|
|
16840
|
+
const matched = documents.map((document) => ({
|
|
16841
|
+
document,
|
|
16842
|
+
score: scoreSearchDocument(document, scoredTerms, averageLengths),
|
|
16843
|
+
nameMatch: nameMatch(document, searchTerms)
|
|
16844
|
+
})).filter(({ score }) => score > 0);
|
|
16845
|
+
if (!matched.some(({ nameMatch }) => nameMatch > 0) && namesActionAndObject(documents, searchTerms)) return [];
|
|
16846
|
+
const scored = matched.map(({ document, score, nameMatch }) => ({
|
|
16460
16847
|
name: document.name,
|
|
16461
|
-
score:
|
|
16462
|
-
})).
|
|
16848
|
+
score: score * (1 + NAME_MATCH_BOOST * nameMatch)
|
|
16849
|
+
})).sort((left, right) => right.score - left.score || left.name.localeCompare(right.name));
|
|
16850
|
+
const minScore = (scored[0]?.score ?? 0) * MIN_RELATIVE_SCORE;
|
|
16851
|
+
return scored.filter(({ score }) => score >= minScore).map(({ name }) => name);
|
|
16463
16852
|
}
|
|
16464
16853
|
function callNotes(definition) {
|
|
16465
16854
|
return [...definition.promptSnippet?.trim() ? [definition.promptSnippet.trim()] : [], ...definition.promptGuidelines?.map((guideline) => guideline.trim()).filter(Boolean) ?? []];
|
|
@@ -16494,15 +16883,18 @@ function toolMetadata(name, definition, includeSource) {
|
|
|
16494
16883
|
return {
|
|
16495
16884
|
tool_name: name,
|
|
16496
16885
|
description: summarizeModelVisibleDescription(definition.description),
|
|
16497
|
-
exposure: effectiveToolExposure(definition),
|
|
16498
16886
|
...includeSource && definition.source ? { source: definition.source.id } : void 0,
|
|
16499
16887
|
input_schema: definition.inputSchema,
|
|
16500
16888
|
call_notes: callNotes(definition),
|
|
16501
16889
|
annotations: definition.annotations ?? {}
|
|
16502
16890
|
};
|
|
16503
16891
|
}
|
|
16504
|
-
/**
|
|
16505
|
-
|
|
16892
|
+
/**
|
|
16893
|
+
* Create the model-visible search tool for the executable tool catalog.
|
|
16894
|
+
* Direct tools stay out of results: the model already has their schemas.
|
|
16895
|
+
*/
|
|
16896
|
+
function createSearchToolsTool(allCatalogTools) {
|
|
16897
|
+
const catalogTools = Object.fromEntries(Object.entries(allCatalogTools).filter(([, definition]) => effectiveToolExposure(definition) !== "direct"));
|
|
16506
16898
|
const knownSources = sourceSummaries(catalogTools);
|
|
16507
16899
|
return zodTool({
|
|
16508
16900
|
description: renderSearchToolsDescription(knownSources),
|
|
@@ -16534,7 +16926,7 @@ function createSearchToolsTool(catalogTools) {
|
|
|
16534
16926
|
const totalEligibleTools = sourceExists ? searchCatalogTools(catalogTools, "", requestedSource).length : 0;
|
|
16535
16927
|
const includePerToolSource = requestedSource === null;
|
|
16536
16928
|
const renderedTools = matches.map((name) => toolMetadata(name, catalogTools[name], includePerToolSource));
|
|
16537
|
-
|
|
16929
|
+
const result = {
|
|
16538
16930
|
query: query ?? null,
|
|
16539
16931
|
source: requestedSource,
|
|
16540
16932
|
sources,
|
|
@@ -16545,6 +16937,8 @@ function createSearchToolsTool(catalogTools) {
|
|
|
16545
16937
|
execution_tool: "executeTool",
|
|
16546
16938
|
tools: renderedTools
|
|
16547
16939
|
};
|
|
16940
|
+
if (allMatches.length === 0 && (query ?? "").trim()) result.note = NO_MATCH_NOTE;
|
|
16941
|
+
return result;
|
|
16548
16942
|
}
|
|
16549
16943
|
});
|
|
16550
16944
|
}
|
|
@@ -17183,8 +17577,7 @@ function createToolPipeline(options) {
|
|
|
17183
17577
|
const result = await untilPreempted(isSandbox ? sandboxTools.execute({
|
|
17184
17578
|
toolName,
|
|
17185
17579
|
input: sandboxInput,
|
|
17186
|
-
...signal ? { signal } : void 0
|
|
17187
|
-
...toolName === "grep" || toolName === "findFiles" ? { setToolCallSpanAttributes: setSpanAttributes } : void 0
|
|
17580
|
+
...signal ? { signal } : void 0
|
|
17188
17581
|
}) : Promise.resolve(toolDef.execute(executionInput, {
|
|
17189
17582
|
experimental_context: sandbox,
|
|
17190
17583
|
...signal ? { signal } : void 0,
|
|
@@ -18521,6 +18914,39 @@ function buildToolActionEvidence(messages, options = {}) {
|
|
|
18521
18914
|
omittedEntries: included.filter((value) => !value).length
|
|
18522
18915
|
};
|
|
18523
18916
|
}
|
|
18917
|
+
// src/chat/conversations/lineage.ts
|
|
18918
|
+
/**
|
|
18919
|
+
* Read the parent chain of a Conversation in one query, root first, with the
|
|
18920
|
+
* Conversation last. Returns an empty list when the Conversation is missing.
|
|
18921
|
+
*
|
|
18922
|
+
* The chain stops at a parent that is missing or that is already in the
|
|
18923
|
+
* chain. Then the first entry still has a `parentConversationId`, so callers
|
|
18924
|
+
* can tell a broken chain from one that ends at a root.
|
|
18925
|
+
*/
|
|
18926
|
+
async function readConversationLineage(conversationId) {
|
|
18927
|
+
const lineage = sql`(
|
|
18928
|
+
with recursive lineage(conversation_id, parent_conversation_id, depth, path) as (
|
|
18929
|
+
select selected.conversation_id, selected.parent_conversation_id, 0, array[selected.conversation_id]
|
|
18930
|
+
from junior_conversations selected
|
|
18931
|
+
where selected.conversation_id = ${conversationId}
|
|
18932
|
+
union all
|
|
18933
|
+
select parent.conversation_id, parent.parent_conversation_id, lineage.depth + 1, lineage.path || parent.conversation_id
|
|
18934
|
+
from junior_conversations parent
|
|
18935
|
+
join lineage on parent.conversation_id = lineage.parent_conversation_id
|
|
18936
|
+
where parent.conversation_id <> all(lineage.path)
|
|
18937
|
+
)
|
|
18938
|
+
select conversation_id, depth from lineage
|
|
18939
|
+
) conversation_lineage`;
|
|
18940
|
+
return (await getDb().select({
|
|
18941
|
+
conversationId: juniorConversations.conversationId,
|
|
18942
|
+
kind: juniorConversations.kind,
|
|
18943
|
+
parentConversationId: juniorConversations.parentConversationId
|
|
18944
|
+
}).from(juniorConversations).innerJoin(lineage, eq(sql`conversation_lineage.conversation_id`, juniorConversations.conversationId)).orderBy(desc(sql`conversation_lineage.depth`))).map((row) => ({
|
|
18945
|
+
conversationId: row.conversationId,
|
|
18946
|
+
kind: conversationKindFromRow(row),
|
|
18947
|
+
...row.parentConversationId ? { parentConversationId: row.parentConversationId } : void 0
|
|
18948
|
+
}));
|
|
18949
|
+
}
|
|
18524
18950
|
// src/chat/agent-invocations/root-conversation.ts
|
|
18525
18951
|
/**
|
|
18526
18952
|
* Most root context messages that Guardian reads, newest first. Codex uses
|
|
@@ -19410,38 +19836,6 @@ async function requestContextSummary(request, streamFn) {
|
|
|
19410
19836
|
if ("summary" in second) return second.summary;
|
|
19411
19837
|
throw new ContextSummaryError(second.failure);
|
|
19412
19838
|
}
|
|
19413
|
-
// src/chat/services/context-compaction-telemetry.ts
|
|
19414
|
-
/**
|
|
19415
|
-
* Context compaction telemetry.
|
|
19416
|
-
*
|
|
19417
|
-
* Each compaction gets one `agent.context_compaction` span. The span and its
|
|
19418
|
-
* children, such as the summary `gen_ai.chat` span, carry
|
|
19419
|
-
* `app.compaction.mode`. The `chat.turn` span sums the time that the Turn
|
|
19420
|
-
* waited on compaction.
|
|
19421
|
-
*
|
|
19422
|
-
* Attribute keys do not contain "token": Sentry data scrubbing removes the
|
|
19423
|
-
* values of keys that match it.
|
|
19424
|
-
*/
|
|
19425
|
-
const turnCompactionWait = new AsyncLocalStorage();
|
|
19426
|
-
/** Run one compaction in its span and add its time to the Turn wait. */
|
|
19427
|
-
async function withCompactionSpan(mode, callback) {
|
|
19428
|
-
const startedAtMs = performance.now();
|
|
19429
|
-
try {
|
|
19430
|
-
return await runWithLogAttributes({ "app.compaction.mode": mode }, () => withSpan("agent.context_compaction", "agent.context_compaction", {}, callback));
|
|
19431
|
-
} finally {
|
|
19432
|
-
const wait = turnCompactionWait.getStore();
|
|
19433
|
-
if (wait) wait.ms += performance.now() - startedAtMs;
|
|
19434
|
-
}
|
|
19435
|
-
}
|
|
19436
|
-
/** Run one `chat.turn` callback and record its compaction wait, if any. */
|
|
19437
|
-
async function measureTurnCompactionWait(setTurnAttributes, callback) {
|
|
19438
|
-
const wait = { ms: 0 };
|
|
19439
|
-
try {
|
|
19440
|
-
return await turnCompactionWait.run(wait, callback);
|
|
19441
|
-
} finally {
|
|
19442
|
-
if (wait.ms > 0) setTurnAttributes({ "app.turn.compaction_wait_ms": Math.round(wait.ms) });
|
|
19443
|
-
}
|
|
19444
|
-
}
|
|
19445
19839
|
// src/chat/services/background-compaction.ts
|
|
19446
19840
|
/**
|
|
19447
19841
|
* Background compaction: prepare a summary before the history is full.
|
|
@@ -19457,8 +19851,7 @@ async function measureTurnCompactionWait(setTurnAttributes, callback) {
|
|
|
19457
19851
|
* another request, so the Turn stores them in the State adapter.
|
|
19458
19852
|
*/
|
|
19459
19853
|
/**
|
|
19460
|
-
* Failed
|
|
19461
|
-
* tries stop.
|
|
19854
|
+
* Failed attempts for one History version before background tries stop.
|
|
19462
19855
|
*/
|
|
19463
19856
|
const MAX_FAILED_ATTEMPTS = 2;
|
|
19464
19857
|
/**
|
|
@@ -19483,26 +19876,17 @@ function lastRequestInputSize(messages) {
|
|
|
19483
19876
|
}
|
|
19484
19877
|
/**
|
|
19485
19878
|
* Return whether a Turn may request a background summary for this History
|
|
19486
|
-
* version. It may not while a request is pending, while a ready summary
|
|
19487
|
-
*
|
|
19488
|
-
*
|
|
19489
|
-
* A Turn swaps a ready summary in before its first model request. A swap
|
|
19490
|
-
* makes a new History version. So a ready summary of this version that was
|
|
19491
|
-
* prepared before the Turn started was discarded, for example because the
|
|
19492
|
-
* history after its mark is too large now. It counts as a failed attempt, so
|
|
19493
|
-
* a new request can replace it.
|
|
19879
|
+
* version. It may not while a request is pending, while a ready summary
|
|
19880
|
+
* waits for the compaction threshold, or after the attempt limit.
|
|
19494
19881
|
*/
|
|
19495
|
-
function mayRequest(events, historyVersion, nowMs
|
|
19882
|
+
function mayRequest(events, historyVersion, nowMs) {
|
|
19496
19883
|
const outcomes = /* @__PURE__ */ new Map();
|
|
19497
|
-
for (const event of events) if (event.data.type === "compaction_prepared" && event.data.historyVersion === historyVersion) outcomes.set(event.data.markSeq,
|
|
19498
|
-
outcome: event.data.outcome,
|
|
19499
|
-
createdAtMs: event.createdAtMs
|
|
19500
|
-
});
|
|
19884
|
+
for (const event of events) if (event.data.type === "compaction_prepared" && event.data.historyVersion === historyVersion) outcomes.set(event.data.markSeq, event.data.outcome);
|
|
19501
19885
|
let failed = 0;
|
|
19502
19886
|
for (const event of events) {
|
|
19503
19887
|
if (event.data.type !== "compaction_requested" || event.data.historyVersion !== historyVersion) continue;
|
|
19504
19888
|
const prepared = outcomes.get(event.data.markSeq);
|
|
19505
|
-
if (prepared
|
|
19889
|
+
if (prepared === "ready") return false;
|
|
19506
19890
|
if (prepared || nowMs - event.createdAtMs >= REQUEST_TIMEOUT_MS) failed += 1;
|
|
19507
19891
|
else return false;
|
|
19508
19892
|
}
|
|
@@ -19526,26 +19910,23 @@ async function loadLatestBackgroundCompaction(conversationId) {
|
|
|
19526
19910
|
} : void 0;
|
|
19527
19911
|
}
|
|
19528
19912
|
/**
|
|
19529
|
-
* Return whether the newest fact is a pending request or a summary
|
|
19530
|
-
*
|
|
19531
|
-
*
|
|
19532
|
-
* so the newest fact decides it.
|
|
19913
|
+
* Return whether the newest fact is a pending request or a ready summary.
|
|
19914
|
+
* Then `mayRequest` is false too, so a Turn can skip the full history load.
|
|
19915
|
+
* Only one request is pending at a time, so the newest fact decides it.
|
|
19533
19916
|
*/
|
|
19534
|
-
function waitsForUse(event, nowMs
|
|
19917
|
+
function waitsForUse(event, nowMs) {
|
|
19535
19918
|
if (event.data.type === "compaction_requested") return nowMs - event.createdAtMs < REQUEST_TIMEOUT_MS;
|
|
19536
|
-
return event.data.type === "compaction_prepared" && event.data.outcome === "ready"
|
|
19919
|
+
return event.data.type === "compaction_prepared" && event.data.outcome === "ready";
|
|
19537
19920
|
}
|
|
19538
19921
|
/**
|
|
19539
19922
|
* Request a background summary when the model request that just ended was at
|
|
19540
19923
|
* or above the mark.
|
|
19541
19924
|
*
|
|
19542
19925
|
* The agent runs it after each model request, so a long Turn gets a summary
|
|
19543
|
-
* before the compaction threshold.
|
|
19544
|
-
*
|
|
19545
|
-
*
|
|
19546
|
-
*
|
|
19547
|
-
* after the request is written, the request times out and counts as a
|
|
19548
|
-
* failed attempt.
|
|
19926
|
+
* before the compaction threshold. Without a queue or below the mark, it does
|
|
19927
|
+
* nothing. A failure here leaves blocking compaction as the fallback, so it
|
|
19928
|
+
* is logged and does not fail the Turn. When the send fails after the request
|
|
19929
|
+
* is written, the request times out and counts as a failed attempt.
|
|
19549
19930
|
*/
|
|
19550
19931
|
async function requestBackgroundCompaction(args) {
|
|
19551
19932
|
if (!args.queue) return;
|
|
@@ -19564,11 +19945,11 @@ async function requestBackgroundCompaction(args) {
|
|
|
19564
19945
|
async function requestAboveMark(args) {
|
|
19565
19946
|
const nowMs = Date.now();
|
|
19566
19947
|
const latest = await loadLatestBackgroundCompaction(args.conversationId);
|
|
19567
|
-
if (latest && waitsForUse(latest.event, nowMs
|
|
19948
|
+
if (latest && waitsForUse(latest.event, nowMs)) return;
|
|
19568
19949
|
const eventStore = getConversationEventStore();
|
|
19569
19950
|
const events = await eventStore.loadCurrentHistory(args.conversationId);
|
|
19570
19951
|
const historyVersion = events[0]?.historyVersion;
|
|
19571
|
-
if (historyVersion === void 0 || !mayRequest(events, historyVersion, nowMs
|
|
19952
|
+
if (historyVersion === void 0 || !mayRequest(events, historyVersion, nowMs)) return;
|
|
19572
19953
|
const projection = projectConversationEvents(events);
|
|
19573
19954
|
const markSeq = Math.max(projection.seqs.at(-1) ?? -1, projection.replacementSeq ?? -1);
|
|
19574
19955
|
if (markSeq < 0) return;
|
|
@@ -19627,7 +20008,7 @@ function failureLabel(error, signal) {
|
|
|
19627
20008
|
*/
|
|
19628
20009
|
async function processBackgroundCompaction(message, options = {}) {
|
|
19629
20010
|
const startedAtMs = Date.now();
|
|
19630
|
-
await withLogContext({ conversationId: message.conversationId }, () => withCompactionSpan("background", async () => {
|
|
20011
|
+
await withLogContext({ conversationId: message.conversationId }, () => withCompactionSpan("background", "summary", async () => {
|
|
19631
20012
|
setSpanAttributes({
|
|
19632
20013
|
"app.compaction.mark_seq": message.markSeq,
|
|
19633
20014
|
"app.compaction.history_version": message.historyVersion,
|
|
@@ -20005,9 +20386,69 @@ function renderCompactionSummary(summary) {
|
|
|
20005
20386
|
"</thread-context>"
|
|
20006
20387
|
].join("\n");
|
|
20007
20388
|
}
|
|
20008
|
-
|
|
20009
|
-
|
|
20010
|
-
return
|
|
20389
|
+
function timestampOf(message) {
|
|
20390
|
+
const { timestamp } = message;
|
|
20391
|
+
return typeof timestamp === "number" ? timestamp : void 0;
|
|
20392
|
+
}
|
|
20393
|
+
/** Find the latest compaction summary in history. */
|
|
20394
|
+
function latestSummaryIndex(messages) {
|
|
20395
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
20396
|
+
const message = messages[index];
|
|
20397
|
+
if (message.role === "user" && hasCompactedConversationContext([message])) return index;
|
|
20398
|
+
}
|
|
20399
|
+
return -1;
|
|
20400
|
+
}
|
|
20401
|
+
/** Find when the latest compaction summary in history was written. */
|
|
20402
|
+
function latestSummaryTimestamp(messages) {
|
|
20403
|
+
const index = latestSummaryIndex(messages);
|
|
20404
|
+
return index < 0 ? void 0 : timestampOf(messages[index]);
|
|
20405
|
+
}
|
|
20406
|
+
/**
|
|
20407
|
+
* Read the input size that the provider reported for one model call. Output
|
|
20408
|
+
* is left out: it is not part of the request that the call measured.
|
|
20409
|
+
*/
|
|
20410
|
+
function measuredInputTokens(message) {
|
|
20411
|
+
const { role, stopReason, usage } = message;
|
|
20412
|
+
if (role !== "assistant" || !usage || stopReason === "aborted" || stopReason === "error") return;
|
|
20413
|
+
const tokens = (usage.input ?? 0) + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
|
|
20414
|
+
return tokens > 0 ? tokens : void 0;
|
|
20415
|
+
}
|
|
20416
|
+
/**
|
|
20417
|
+
* Measure provider-visible history without counting host-only message fields.
|
|
20418
|
+
*
|
|
20419
|
+
* Provider usage counts the request that produced it. A replacement keeps
|
|
20420
|
+
* assistant messages that are older than its summary, and their usage counts
|
|
20421
|
+
* the history before the replacement. So when the latest usage is older than
|
|
20422
|
+
* the latest summary, estimate each message by size.
|
|
20423
|
+
*/
|
|
20424
|
+
function estimateHistoryTokens(messages, requestOverheadTokens = 0) {
|
|
20425
|
+
const estimate = estimateContextTokens(messages);
|
|
20426
|
+
const summaryAt = latestSummaryTimestamp(messages);
|
|
20427
|
+
const usageAt = estimate.lastUsageIndex === null ? void 0 : timestampOf(messages[estimate.lastUsageIndex]);
|
|
20428
|
+
if (usageAt !== void 0 && (summaryAt === void 0 || usageAt > summaryAt)) return estimate.tokens;
|
|
20429
|
+
return estimateReplacementTokens(messages, requestOverheadTokens);
|
|
20430
|
+
}
|
|
20431
|
+
/**
|
|
20432
|
+
* Read the provider-reported input of the first model call after the latest
|
|
20433
|
+
* full compaction. That request held only the summary and the kept context,
|
|
20434
|
+
* so another full compaction of the same context cannot get much below it.
|
|
20435
|
+
* A swap also keeps agent history from before its summary. A full compaction
|
|
20436
|
+
* can still drop that history, so a swap gives no such size.
|
|
20437
|
+
*/
|
|
20438
|
+
function measuredReplacementTokens(messages) {
|
|
20439
|
+
const summaryIndex = latestSummaryIndex(messages);
|
|
20440
|
+
if (summaryIndex < 0) return void 0;
|
|
20441
|
+
const summaryAt = timestampOf(messages[summaryIndex]);
|
|
20442
|
+
if (summaryAt === void 0) return void 0;
|
|
20443
|
+
for (const message of messages.slice(summaryIndex + 1)) {
|
|
20444
|
+
const timestamp = timestampOf(message);
|
|
20445
|
+
if (timestamp === void 0 || timestamp <= summaryAt) {
|
|
20446
|
+
if (message.role !== "user") return void 0;
|
|
20447
|
+
continue;
|
|
20448
|
+
}
|
|
20449
|
+
const tokens = measuredInputTokens(message);
|
|
20450
|
+
if (tokens !== void 0) return tokens;
|
|
20451
|
+
}
|
|
20011
20452
|
}
|
|
20012
20453
|
/**
|
|
20013
20454
|
* Estimate a replacement request from each message's own size. A kept
|
|
@@ -20029,9 +20470,9 @@ async function loadLastInstruction(conversationId) {
|
|
|
20029
20470
|
};
|
|
20030
20471
|
}
|
|
20031
20472
|
}
|
|
20032
|
-
function loadCompactionSource(messages) {
|
|
20473
|
+
function loadCompactionSource(messages, requestOverheadTokens) {
|
|
20033
20474
|
if (messages.length > 0) return {
|
|
20034
|
-
estimatedTokens: estimateHistoryTokens(messages),
|
|
20475
|
+
estimatedTokens: estimateHistoryTokens(messages, requestOverheadTokens),
|
|
20035
20476
|
messages
|
|
20036
20477
|
};
|
|
20037
20478
|
return { reason: "missing_context" };
|
|
@@ -20045,7 +20486,7 @@ function loadCompactionSource(messages) {
|
|
|
20045
20486
|
*/
|
|
20046
20487
|
async function compactActiveContextIfNeeded(args, summarize) {
|
|
20047
20488
|
const pendingMessages = args.pendingMessages ?? [];
|
|
20048
|
-
const source = loadCompactionSource([...args.piMessages, ...pendingMessages.map((entry) => entry.message)]);
|
|
20489
|
+
const source = loadCompactionSource([...args.piMessages, ...pendingMessages.map((entry) => entry.message)], args.requestOverheadTokens);
|
|
20049
20490
|
if ("reason" in source) return {
|
|
20050
20491
|
compacted: false,
|
|
20051
20492
|
reason: source.reason
|
|
@@ -20055,30 +20496,27 @@ async function compactActiveContextIfNeeded(args, summarize) {
|
|
|
20055
20496
|
compacted: false,
|
|
20056
20497
|
reason: "below_threshold"
|
|
20057
20498
|
};
|
|
20058
|
-
return await withCompactionSpan(args.mode, () => compactActiveAboveThreshold(args, summarize, source, triggerTokens));
|
|
20499
|
+
return await withCompactionSpan(args.mode, "summary", () => compactActiveAboveThreshold(args, summarize, source, triggerTokens));
|
|
20059
20500
|
}
|
|
20060
20501
|
async function compactActiveAboveThreshold(args, summarize, source, triggerTokens) {
|
|
20061
20502
|
const pendingMessages = args.pendingMessages ?? [];
|
|
20062
20503
|
const retainUserMessages = args.mode === "blocking" && pendingMessages.length > 0;
|
|
20063
|
-
await args.onCompactionStart?.();
|
|
20064
20504
|
const inputLimitTokens = getAgentContextInputLimitTokens(args.modelId);
|
|
20065
|
-
|
|
20066
|
-
|
|
20067
|
-
|
|
20068
|
-
|
|
20069
|
-
|
|
20070
|
-
|
|
20071
|
-
"app.context_input_limit_tokens": inputLimitTokens,
|
|
20072
|
-
"app.context_tokens_estimated": source.estimatedTokens,
|
|
20073
|
-
"exception.message": error instanceof Error ? error.message : String(error)
|
|
20505
|
+
const skip = (reason) => {
|
|
20506
|
+
setSpanAttributes({
|
|
20507
|
+
"app.compaction.outcome": "skipped",
|
|
20508
|
+
"app.compaction.skip_reason": reason,
|
|
20509
|
+
"app.compaction.input.estimate": source.estimatedTokens,
|
|
20510
|
+
"app.compaction.threshold": triggerTokens
|
|
20074
20511
|
});
|
|
20075
|
-
setSpanAttributes({ "app.compaction.outcome": "summary_failed" });
|
|
20076
20512
|
return {
|
|
20077
20513
|
compacted: false,
|
|
20078
|
-
reason: "
|
|
20514
|
+
reason: "over_target"
|
|
20079
20515
|
};
|
|
20080
|
-
}
|
|
20081
|
-
const
|
|
20516
|
+
};
|
|
20517
|
+
const belowInputLimit = source.estimatedTokens < inputLimitTokens;
|
|
20518
|
+
const measuredTokens = measuredReplacementTokens(source.messages);
|
|
20519
|
+
if (belowInputLimit && measuredTokens !== void 0 && measuredTokens > triggerTokens) return skip("last_over_threshold");
|
|
20082
20520
|
const retainedInstruction = pendingMessages.length === 0 && !retainUserMessages ? await loadLastInstruction(args.conversationId) : void 0;
|
|
20083
20521
|
const instructionMessages = retainedInstruction ? [retainedInstruction.message] : pendingMessages.map((entry) => entry.message);
|
|
20084
20522
|
const instructionProvenance = retainedInstruction ? [retainedInstruction.provenance] : pendingMessages.map((entry) => entry.provenance);
|
|
@@ -20093,11 +20531,34 @@ async function compactActiveAboveThreshold(args, summarize, source, triggerToken
|
|
|
20093
20531
|
provenance: instructionProvenance[index],
|
|
20094
20532
|
...index === 0 && retainedInstruction ? { sourceEventSeq: retainedInstruction.sourceEventSeq } : void 0
|
|
20095
20533
|
}));
|
|
20534
|
+
const retainedUserMessages = retainUserMessages ? await loadRetainedUserMessages(args.conversationId, instructionMessages) : [];
|
|
20535
|
+
const keptTokens = estimateReplacementTokens([
|
|
20536
|
+
...retainedUserMessages,
|
|
20537
|
+
...contextEntries,
|
|
20538
|
+
...instructionEntries
|
|
20539
|
+
].map((entry) => entry.message), args.requestOverheadTokens);
|
|
20540
|
+
if (belowInputLimit && keptTokens > calculateContextCompactionTargetTokens(triggerTokens)) return skip("over_target");
|
|
20541
|
+
await args.onCompactionStart?.();
|
|
20542
|
+
let summary;
|
|
20543
|
+
try {
|
|
20544
|
+
summary = await summarize(args.piMessages, args.signal);
|
|
20545
|
+
} catch (error) {
|
|
20546
|
+
if (source.estimatedTokens >= inputLimitTokens) throw new ContextInputLimitExceededError(source.estimatedTokens, inputLimitTokens);
|
|
20547
|
+
logWarn("context_compaction.active.summary.failed", {
|
|
20548
|
+
"app.context_input_limit_tokens": inputLimitTokens,
|
|
20549
|
+
"app.context_tokens_estimated": source.estimatedTokens,
|
|
20550
|
+
"exception.message": error instanceof Error ? error.message : String(error)
|
|
20551
|
+
});
|
|
20552
|
+
setSpanAttributes({ "app.compaction.outcome": "summary_failed" });
|
|
20553
|
+
return {
|
|
20554
|
+
compacted: false,
|
|
20555
|
+
reason: "summary_failed"
|
|
20556
|
+
};
|
|
20557
|
+
}
|
|
20096
20558
|
const summaryEntry = {
|
|
20097
|
-
message:
|
|
20559
|
+
message: userMessage(appendOpenPlan(renderCompactionSummary(summary), source.messages)),
|
|
20098
20560
|
provenance: contextProvenance
|
|
20099
20561
|
};
|
|
20100
|
-
const retainedUserMessages = retainUserMessages ? await loadRetainedUserMessages(args.conversationId, instructionMessages) : [];
|
|
20101
20562
|
const replacement = retainUserMessages ? [
|
|
20102
20563
|
...retainedUserMessages,
|
|
20103
20564
|
summaryEntry,
|
|
@@ -20245,12 +20706,21 @@ function trimToolResults(entries) {
|
|
|
20245
20706
|
*
|
|
20246
20707
|
* A background job writes `compaction_prepared` with a summary of the history
|
|
20247
20708
|
* up to `markSeq`. The Turn swaps it in without a model call: retained user
|
|
20248
|
-
* messages, the summary, then every message after the mark.
|
|
20249
|
-
*
|
|
20250
|
-
*
|
|
20251
|
-
* no longer matches the history is
|
|
20252
|
-
* none existed.
|
|
20709
|
+
* messages, the summary, then every message after the mark. A swap runs only
|
|
20710
|
+
* above the compaction threshold, at Turn start or between model calls, in
|
|
20711
|
+
* place of a blocking summary call. Below it, a swap would only rewrite the
|
|
20712
|
+
* provider's prompt cache. A summary that no longer matches the history is
|
|
20713
|
+
* discarded, and the Turn carries on as if none existed.
|
|
20714
|
+
*
|
|
20715
|
+
* A summary that is still running replaces the blocking summary too, for a
|
|
20716
|
+
* limited time from its request. Below the input limit, the Turn defers: the
|
|
20717
|
+
* next model call gets the full history, and a later check swaps the summary
|
|
20718
|
+
* in. At the input limit, the Turn polls for it. The time counts from the
|
|
20719
|
+
* durable request, so a yield or a new request does not reset it.
|
|
20253
20720
|
*/
|
|
20721
|
+
/** How long after its request a running summary replaces a blocking one. */
|
|
20722
|
+
const RUNNING_SUMMARY_WAIT_MS = 45e3;
|
|
20723
|
+
const RUNNING_SUMMARY_POLL_MS = 1e3;
|
|
20254
20724
|
/** Compare a message across a durable commit, which drops undefined fields. */
|
|
20255
20725
|
function durableIdentity(message) {
|
|
20256
20726
|
const { role, timestamp, content, toolCallId } = message;
|
|
@@ -20274,39 +20744,72 @@ function discard(reason) {
|
|
|
20274
20744
|
return { compacted: false };
|
|
20275
20745
|
}
|
|
20276
20746
|
/**
|
|
20277
|
-
* Swap a ready prepared summary into history,
|
|
20278
|
-
* compaction when none can be used.
|
|
20747
|
+
* Swap a ready prepared summary into history, defer to one that is still
|
|
20748
|
+
* running, or run today's capacity compaction when none can be used.
|
|
20279
20749
|
*/
|
|
20280
20750
|
async function compactWithPreparedSummary(args, summarize) {
|
|
20281
20751
|
const swapped = await swapPreparedCompaction(args);
|
|
20282
|
-
if (swapped.compacted || swapped.reason === "history_conflict") return swapped;
|
|
20752
|
+
if (swapped.compacted || swapped.reason === "history_conflict" || swapped.reason === "deferred") return swapped;
|
|
20283
20753
|
return await compactActiveContextIfNeeded(args, summarize);
|
|
20284
20754
|
}
|
|
20285
20755
|
/**
|
|
20286
|
-
*
|
|
20287
|
-
*
|
|
20288
|
-
|
|
20756
|
+
* Poll until the running summary of `request` has a result, the History
|
|
20757
|
+
* changes, or the wait ends. Return the newest fact at that time.
|
|
20758
|
+
*/
|
|
20759
|
+
async function waitForRunningSummary(conversationId, request, waitUntilMs, signal) {
|
|
20760
|
+
let latest = request;
|
|
20761
|
+
while (latest?.event.seq === request.event.seq && Date.now() < waitUntilMs) {
|
|
20762
|
+
await setTimeout$1(Math.min(RUNNING_SUMMARY_POLL_MS, waitUntilMs - Date.now()), void 0, { signal });
|
|
20763
|
+
latest = await loadLatestBackgroundCompaction(conversationId);
|
|
20764
|
+
}
|
|
20765
|
+
return latest;
|
|
20766
|
+
}
|
|
20767
|
+
/**
|
|
20768
|
+
* Replace history above the compaction threshold with a ready prepared
|
|
20769
|
+
* summary, or defer to one that is still running.
|
|
20289
20770
|
*/
|
|
20290
20771
|
async function swapPreparedCompaction(args) {
|
|
20291
20772
|
const pendingMessages = args.pendingMessages ?? [];
|
|
20292
20773
|
const sourceMessages = [...args.piMessages, ...pendingMessages.map((entry) => entry.message)];
|
|
20293
20774
|
const triggerTokens = getAgentContextCompactionTriggerTokens(args.modelId);
|
|
20294
|
-
const estimatedTokens = estimateHistoryTokens(sourceMessages);
|
|
20295
|
-
if (
|
|
20775
|
+
const estimatedTokens = estimateHistoryTokens(sourceMessages, args.requestOverheadTokens);
|
|
20776
|
+
if (estimatedTokens <= triggerTokens) return {
|
|
20296
20777
|
compacted: false,
|
|
20297
20778
|
reason: "below_threshold"
|
|
20298
20779
|
};
|
|
20299
|
-
const
|
|
20300
|
-
if (!
|
|
20301
|
-
return await withCompactionSpan(args.mode, async () => {
|
|
20302
|
-
|
|
20303
|
-
if (event.data.type
|
|
20780
|
+
const first = await loadLatestBackgroundCompaction(args.conversationId);
|
|
20781
|
+
if (!first) return { compacted: false };
|
|
20782
|
+
return await withCompactionSpan(args.mode, "swap", async () => {
|
|
20783
|
+
let latest = first;
|
|
20784
|
+
if (first.event.data.type === "compaction_requested") {
|
|
20785
|
+
const waitUntilMs = first.event.createdAtMs + RUNNING_SUMMARY_WAIT_MS;
|
|
20786
|
+
setSpanAttributes({ "app.compaction.request.age_ms": Math.max(0, Date.now() - first.event.createdAtMs) });
|
|
20787
|
+
if (Date.now() < waitUntilMs) {
|
|
20788
|
+
if (estimatedTokens < getAgentContextInputLimitTokens(args.modelId)) {
|
|
20789
|
+
setSpanAttributes({ "app.compaction.outcome": "deferred" });
|
|
20790
|
+
return {
|
|
20791
|
+
compacted: false,
|
|
20792
|
+
reason: "deferred"
|
|
20793
|
+
};
|
|
20794
|
+
}
|
|
20795
|
+
await args.onCompactionStart?.();
|
|
20796
|
+
latest = await waitForRunningSummary(args.conversationId, first, waitUntilMs, args.signal);
|
|
20797
|
+
setSpanAttributes({ "app.compaction.wait.timed_out": latest?.event.seq === first.event.seq });
|
|
20798
|
+
if (latest?.historyVersion !== first.historyVersion) return {
|
|
20799
|
+
...discard("history_version_changed"),
|
|
20800
|
+
reason: "history_conflict"
|
|
20801
|
+
};
|
|
20802
|
+
}
|
|
20803
|
+
}
|
|
20804
|
+
const prepared = latest?.event.data;
|
|
20805
|
+
if (!latest || prepared?.type !== "compaction_prepared" || prepared.outcome !== "ready") {
|
|
20304
20806
|
setSpanAttributes({ "app.compaction.outcome": "not_ready" });
|
|
20305
20807
|
return { compacted: false };
|
|
20306
20808
|
}
|
|
20809
|
+
const { event, historyVersion } = latest;
|
|
20307
20810
|
setSpanAttributes({ "app.compaction.prepared.age_ms": Math.max(0, Date.now() - event.createdAtMs) });
|
|
20308
|
-
if (
|
|
20309
|
-
return await applyPreparedSummary(args,
|
|
20811
|
+
if (prepared.historyVersion !== historyVersion) return discard("history_version_changed");
|
|
20812
|
+
return await applyPreparedSummary(args, prepared, {
|
|
20310
20813
|
estimatedTokens,
|
|
20311
20814
|
historyVersion,
|
|
20312
20815
|
triggerTokens
|
|
@@ -20424,14 +20927,6 @@ function exclusiveToolName(toolCalls) {
|
|
|
20424
20927
|
* artifacts, and transcript state for destination-owned completion.
|
|
20425
20928
|
*/
|
|
20426
20929
|
const AGENT_ABORT_SETTLE_GRACE_MS = 5e3;
|
|
20427
|
-
/** Read visibility from the Conversation, or from its nearest parent with one. */
|
|
20428
|
-
async function readRunConversationVisibility(conversationId) {
|
|
20429
|
-
const lineage = await readConversationLineage(conversationId);
|
|
20430
|
-
for (let index = lineage.length - 1; index >= 0; index -= 1) {
|
|
20431
|
-
const visibility = lineage[index].visibility;
|
|
20432
|
-
if (visibility) return visibility;
|
|
20433
|
-
}
|
|
20434
|
-
}
|
|
20435
20930
|
/** Preserve delivery-error ownership across the agent generation boundary. */
|
|
20436
20931
|
var AssistantMessageDeliveryError = class extends Error {
|
|
20437
20932
|
originalError;
|
|
@@ -20475,7 +20970,8 @@ function waitForAbortSettlement(promise, timeoutMs) {
|
|
|
20475
20970
|
*/
|
|
20476
20971
|
async function executeAgentRun(run, streamFn) {
|
|
20477
20972
|
if (!run.destination) throw new TypeError("Assistant reply generation requires a destination");
|
|
20478
|
-
const
|
|
20973
|
+
const conversation = await getConversationStore().get({ conversationId: run.conversationId });
|
|
20974
|
+
const visibility = conversation?.visibility;
|
|
20479
20975
|
const conversationPrivacy = resolveConversationPrivacy({ visibility });
|
|
20480
20976
|
const actor = actorFromRun(run);
|
|
20481
20977
|
const runLogContext = {
|
|
@@ -20487,15 +20983,14 @@ async function executeAgentRun(run, streamFn) {
|
|
|
20487
20983
|
runId: run.runId,
|
|
20488
20984
|
assistantUserName: botConfig.userName
|
|
20489
20985
|
};
|
|
20490
|
-
return withLogContext(runLogContext, () => runWithConversationPrivacy(conversationPrivacy, () => executeAgentRunInPrivacyContext(run, conversationPrivacy, runLogContext, streamFn)));
|
|
20986
|
+
return withLogContext(runLogContext, () => runWithConversationPrivacy(conversationPrivacy, () => executeAgentRunInPrivacyContext(run, conversation?.kind, conversationPrivacy, runLogContext, streamFn)));
|
|
20491
20987
|
}
|
|
20492
|
-
async function executeAgentRunInPrivacyContext(run, conversationPrivacy, runLogContext, streamFn) {
|
|
20988
|
+
async function executeAgentRunInPrivacyContext(run, conversationKind, conversationPrivacy, runLogContext, streamFn) {
|
|
20493
20989
|
const conversationId = run.conversationId;
|
|
20494
20990
|
const turnId = run.turnId;
|
|
20495
20991
|
const requireAutomationResult = run.dispatch?.declaresResult === true;
|
|
20496
20992
|
const input = {
|
|
20497
20993
|
actor: run.instruction.actor,
|
|
20498
|
-
includeConversationContextWithPiMessages: run.instruction.includeConversationContextWithHistory,
|
|
20499
20994
|
messageText: run.instruction.text,
|
|
20500
20995
|
userAttachments: run.instruction.attachments ? [...run.instruction.attachments] : void 0,
|
|
20501
20996
|
inboundAttachmentCount: run.instruction.inboundAttachmentCount,
|
|
@@ -20554,7 +21049,7 @@ async function executeAgentRunInPrivacyContext(run, conversationPrivacy, runLogC
|
|
|
20554
21049
|
const authorization = run.authorization;
|
|
20555
21050
|
const durability = run.durability ?? {};
|
|
20556
21051
|
signal?.throwIfAborted();
|
|
20557
|
-
assertRunConsistency(run);
|
|
21052
|
+
assertRunConsistency(run, conversationKind);
|
|
20558
21053
|
const replyStartedAtMs = Date.now();
|
|
20559
21054
|
const configuredTurnDeadlineAtMs = replyStartedAtMs + botConfig.turnTimeoutMs;
|
|
20560
21055
|
const policyTurnDeadlineAtMs = typeof policy.turnDeadlineAtMs === "number" && Number.isFinite(policy.turnDeadlineAtMs) ? Math.floor(policy.turnDeadlineAtMs) : void 0;
|
|
@@ -20591,6 +21086,9 @@ async function executeAgentRunInPrivacyContext(run, conversationPrivacy, runLogC
|
|
|
20591
21086
|
});
|
|
20592
21087
|
connectedMcpProviders.add(provider);
|
|
20593
21088
|
};
|
|
21089
|
+
const requireConversationLease = async (action) => {
|
|
21090
|
+
if (durability.checkIn && !await durability.checkIn()) throw new TurnInputCommitLostError(`Conversation Lease lost before ${action} for conversation=${conversationId} turn=${turnId}`);
|
|
21091
|
+
};
|
|
20594
21092
|
const recordActiveMcpProviders = async () => {
|
|
20595
21093
|
if (!mcpToolManager) return;
|
|
20596
21094
|
for (const provider of mcpToolManager.getActiveProviders()) await recordConnectedMcpProvider(provider);
|
|
@@ -20686,10 +21184,7 @@ async function executeAgentRunInPrivacyContext(run, conversationPrivacy, runLogC
|
|
|
20686
21184
|
resumed: resumedFromSessionRecord,
|
|
20687
21185
|
skillSandbox
|
|
20688
21186
|
});
|
|
20689
|
-
const { contextContentParts, userContentParts } = buildPromptInput({
|
|
20690
|
-
instruction: run.instruction,
|
|
20691
|
-
history: run.history
|
|
20692
|
-
});
|
|
21187
|
+
const { contextContentParts, userContentParts } = buildPromptInput({ instruction: run.instruction });
|
|
20693
21188
|
const preAgentPromptMessages = () => existingSessionRecord?.piMessages ?? [...input.piMessages ?? []];
|
|
20694
21189
|
const runSandbox = await createRunSandbox({
|
|
20695
21190
|
availableSkills,
|
|
@@ -20829,6 +21324,19 @@ async function executeAgentRunInPrivacyContext(run, conversationPrivacy, runLogC
|
|
|
20829
21324
|
promptName: CONTEXT_COMPACTION_PROMPT_NAME,
|
|
20830
21325
|
...streamFn ? { base: streamFn } : void 0
|
|
20831
21326
|
});
|
|
21327
|
+
let replacementAwaitingInput;
|
|
21328
|
+
/** Log the first provider-reported input after a replacement. */
|
|
21329
|
+
const logFirstInputAfterReplacement = () => {
|
|
21330
|
+
if (!replacementAwaitingInput) return;
|
|
21331
|
+
const inputSize = lastRequestInputSize(agent.state.messages.slice(replacementAwaitingInput.messageCount));
|
|
21332
|
+
if (!inputSize) return;
|
|
21333
|
+
logInputAfterCompaction({
|
|
21334
|
+
inputSize,
|
|
21335
|
+
mode: replacementAwaitingInput.mode,
|
|
21336
|
+
threshold: getAgentContextCompactionTriggerTokens(activeModelId)
|
|
21337
|
+
});
|
|
21338
|
+
replacementAwaitingInput = void 0;
|
|
21339
|
+
};
|
|
20832
21340
|
/** Commit and adopt an active capacity replacement before another model call. */
|
|
20833
21341
|
const applyActiveContextCompaction = async (messages, hookSignal, pendingMessages, clearSteeringQueueOnCommit = false, pairPendingRuntimeContext = false, mode = "active") => {
|
|
20834
21342
|
const compaction = await compactWithPreparedSummary({
|
|
@@ -20855,6 +21363,10 @@ async function executeAgentRunInPrivacyContext(run, conversationPrivacy, runLogC
|
|
|
20855
21363
|
throw error;
|
|
20856
21364
|
}
|
|
20857
21365
|
agent.state.messages = replacement;
|
|
21366
|
+
replacementAwaitingInput = {
|
|
21367
|
+
messageCount: replacement.length,
|
|
21368
|
+
mode
|
|
21369
|
+
};
|
|
20858
21370
|
runResume.setBeforeMessageCount(replacement.length);
|
|
20859
21371
|
runResume.adoptCommittedBoundary(replacement);
|
|
20860
21372
|
if (clearSteeringQueueOnCommit && pendingMessages?.length) agent.clearSteeringQueue();
|
|
@@ -20874,14 +21386,14 @@ async function executeAgentRunInPrivacyContext(run, conversationPrivacy, runLogC
|
|
|
20874
21386
|
conversationId,
|
|
20875
21387
|
conversationPrivacy,
|
|
20876
21388
|
modelId: activeModelId,
|
|
20877
|
-
queue: run.environment?.backgroundCompactionQueue
|
|
20878
|
-
turnStartedAtMs: replyStartedAtMs
|
|
21389
|
+
queue: run.environment?.backgroundCompactionQueue
|
|
20879
21390
|
});
|
|
20880
21391
|
let assistantMessageDeliveryError;
|
|
20881
21392
|
/** Deliver one completed tool-free visible message before the agent advances. */
|
|
20882
21393
|
const deliverAssistantMessage = async (message) => {
|
|
20883
21394
|
if (decideReply(message).kind !== "deliver" || !delivery) return;
|
|
20884
21395
|
try {
|
|
21396
|
+
await requireConversationLease("reply");
|
|
20885
21397
|
await delivery(message);
|
|
20886
21398
|
acceptedToolFreeAssistant = true;
|
|
20887
21399
|
} catch (error) {
|
|
@@ -20966,6 +21478,7 @@ async function executeAgentRunInPrivacyContext(run, conversationPrivacy, runLogC
|
|
|
20966
21478
|
},
|
|
20967
21479
|
prepareNextTurnWithContext: async (nextTurn, hookSignal) => {
|
|
20968
21480
|
try {
|
|
21481
|
+
logFirstInputAfterReplacement();
|
|
20969
21482
|
if (hookSignal?.aborted) return;
|
|
20970
21483
|
const stepUpdate = await withSpan("agent.step.prepare", "agent.step.prepare", {}, async () => {
|
|
20971
21484
|
const contextUpdate = await repositoryInstructionsContext.applyUpdate(nextTurn.context);
|
|
@@ -20998,7 +21511,10 @@ async function executeAgentRunInPrivacyContext(run, conversationPrivacy, runLogC
|
|
|
20998
21511
|
});
|
|
20999
21512
|
const unsubscribe = agent.subscribe((event) => {
|
|
21000
21513
|
if (event.type === "tool_execution_start") return recordParentToolExecutionStart(event);
|
|
21001
|
-
if (event.type === "turn_end" && event.toolResults.length > 0) return runResume.persistSafeBoundary([...agent.state.messages]).then(() => void 0)
|
|
21514
|
+
if (event.type === "turn_end" && event.toolResults.length > 0) return requireConversationLease("save").then(() => runResume.persistSafeBoundary([...agent.state.messages])).then(() => void 0, (error) => {
|
|
21515
|
+
pendingPiHookError ??= error instanceof Error ? error : new Error(String(error));
|
|
21516
|
+
throw error;
|
|
21517
|
+
});
|
|
21002
21518
|
if (event.type === "message_end" && isAssistantMessage(event.message)) {
|
|
21003
21519
|
if (event.message.stopReason === "error" || event.message.stopReason === "aborted") return;
|
|
21004
21520
|
return deliverAssistantMessage(event.message);
|
|
@@ -21216,6 +21732,7 @@ async function executeAgentRunInPrivacyContext(run, conversationPrivacy, runLogC
|
|
|
21216
21732
|
} finally {
|
|
21217
21733
|
unsubscribe();
|
|
21218
21734
|
}
|
|
21735
|
+
await requireConversationLease("save");
|
|
21219
21736
|
await recordActiveMcpProviders();
|
|
21220
21737
|
return {
|
|
21221
21738
|
status: "completed",
|
|
@@ -21238,9 +21755,11 @@ async function executeAgentRunInPrivacyContext(run, conversationPrivacy, runLogC
|
|
|
21238
21755
|
} catch (error) {
|
|
21239
21756
|
if (error instanceof AssistantMessageDeliveryError && !(error.originalError instanceof RetryableDeliveryError)) throw error.originalError;
|
|
21240
21757
|
const runError = error instanceof AssistantMessageDeliveryError ? error.originalError : error;
|
|
21758
|
+
if (isTurnInputCommitLostError(runError)) throw runError;
|
|
21241
21759
|
if (runError instanceof AuthPausePersistenceError || isTurnExecutionLimitExceededError(runError)) throw runError;
|
|
21242
21760
|
if (resume && runError instanceof AuthorizationPauseError) return await resume.parkForAuth(runError, turnUsage);
|
|
21243
21761
|
if (resume?.timedOut && acceptedToolFreeAssistant && agent) {
|
|
21762
|
+
await requireConversationLease("save");
|
|
21244
21763
|
await recordActiveMcpProviders();
|
|
21245
21764
|
const piMessages = [...agent.state.messages];
|
|
21246
21765
|
return {
|
|
@@ -21354,4 +21873,4 @@ function createAgentRunner(execute, options) {
|
|
|
21354
21873
|
return await execute(nextRun, streamFn);
|
|
21355
21874
|
} };
|
|
21356
21875
|
}
|
|
21357
|
-
export { readViewerAutomationSummary as $, runWithSlackInstallation as A,
|
|
21876
|
+
export { readViewerAutomationSummary as $, runWithSlackInstallation as A, turnInputTelemetry as At, listThreadReplies as B, listChildAgents as Bt, readSlackReviewItemCardConversationId as C, recordSubagentStarted as Ct, parseSlackReviewItemClick as D, executeTurn as Dt, buildSlackReviewItemModal as E, AgentRunError as Et, resolveSlackChannelIdFromThreadId as F, AgentInvocationLimitError as Ft, changeViewerAutomationLifecycle as G, actorFromRun as Gt, logScheduledAutomationRunSkipped as H, processWorkspaceSnapshotJob as Ht, checkSlackChannelReadAccess as I, AgentMessagePausedError as It, updateViewerAutomation as J, deleteViewerTask as K, toolInvocationDestination as Kt, joinPublicChannelForRead as L, AgentMessageQueueFullError as Lt, parseSlackThreadId as M, deleteWebAuthorization as Mt, readSlackRawMessageContext as N, getWebAuthorization as Nt, parseSlackReviewItemFormTarget as O, finishTurn as Ot, resolveSlackChannelIdFromMessage as P, AgentDepthLimitError as Pt, readViewerAutomationRuns as Q, getConversationInfo as R, AgentMessageTargetError as Rt, createSlackReviewItemShow as S, recordSubagentEnded as St, SLACK_REVIEW_ITEM_VIEW_ID as T, supersedeOpenMailboxTurns as Tt, scheduledAutomationRunAttributes as U, ingestEvent as Ut, resolveDestinationVisibility as V, listUnreportedSiblingAgents as Vt, activateViewerAutomationVersion as W, RetryableDeliveryError as Wt, readConversationSourceTask as X, ViewerTaskNotFoundError as Y, readViewerAutomationExecutions as Z, readPublicArtifact as _, readLiveAttachment as _t, buildAuthPauseResponse as a, deliverReviewItemChange as at, renderAttachmentText as b, stopChildAgentsBelow as bt, deleteMcpAuthSessionsForUserProvider as c, acceptsWebMessages as ct, getMcpAuthSession as d, createAndEnqueueConversation as dt, readViewerAutomationVersions as et, getMcpStoredOAuthCredentials as f, createConversationId as ft, publicArtifactHeaders as g, collectAttachmentGarbage as gt, readStats as h, decodeInputImages as ht, readConversationLineage as i, listOwnedWatches as it, verifySlackSignature as j, withTurnSpan as jt, parseSlackUserInputSubmission as k, getTurnInputSpanAttributes as kt, deleteMcpServerSessionId as l, appendAndEnqueueWebMessage as lt, latestProgressStatus as m, webActorFromUser as mt, executeAgentRun as n, AutomationEditError as nt, finalizeMcpAuthorization as o, renderReviewItemMessage as ot, putMcpStoredOAuthCredentials as p, recordWebConversationActivity as pt, readViewerAutomationEdit as q, shouldEmitDevAgentTrace as qt, processBackgroundCompaction as r, effectiveTaskOutcomes as rt, deleteMcpAuthSession as s, reviewItemChangeRecord as st, createAgentRunner as t, readViewerAutomations as tt, deleteMcpStoredOAuthCredentials as u, conversationTurnIdForMessage as ut, unpublishedArtifactHeaders as v, requestAttachmentDeletion as vt, syncReviewItemSlackCards as w, createConversationTurnWorker as wt, renderBlockText as x, stopChildAgentsOf as xt, lookupSlackUserProfile as y, storeAttachment as yt, joinPublicChannel as z, AgentNameInUseError as zt };
|