@sentry/junior 0.272.0 → 0.274.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-BDYDi1F9.js → adapter-4qThDhgF.js} +1 -1
- package/dist/{admin-Dj7EFycG.js → admin-c7ASvs6x.js} +1 -1
- package/dist/{agent-runner-Cl6Usx2Y.js → agent-runner-CLHM48dh.js} +780 -396
- 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 +58 -575
- package/dist/{app-DjZblE2J.d.ts → app-BlmPpPoR.d.ts} +4 -9
- package/dist/app.d.ts +1 -1
- package/dist/app.js +673 -127
- package/dist/{assistant-reply-DN2w6JL_.js → assistant-reply-2IwdFWuQ.js} +1 -1
- package/dist/{automation-CV7g5h3A.js → automation-BGrd03QO.js} +1 -1
- package/dist/{briefs-PysAqnjV.js → briefs-C1-NOh8m.js} +4 -4
- package/dist/{catalog-runtime-BNeCWIaF.js → catalog-runtime-BnIJimKZ.js} +1 -1
- package/dist/cli/chat.js +15 -15
- package/dist/cli/check.js +3 -3
- package/dist/cli/init.js +1 -1
- package/dist/cli/main.js +3 -3
- package/dist/cli/plugins.js +4 -4
- package/dist/cli/snapshot-create.js +4 -4
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +3 -3
- package/dist/{client-FRphcDWW.js → client-C0ZIxoDr.js} +63 -5
- package/dist/{reporting-schema-CZREhYc-.js → common-Eu6sx09c.js} +4 -1
- package/dist/{config-BUP9wjiR.js → config-DS-QLVSL.js} +6 -14
- package/dist/{connections-CesHau9u.js → connections-Djb6ANAh.js} +11 -11
- package/dist/{conversation-BtQzLoK8.js → conversation-BjTo9ZFL.js} +11 -1
- package/dist/{conversation-privacy-DiGvA9a3.js → conversation-privacy-3IMUZSHC.js} +1 -1
- package/dist/{credential-sync-D2odJC30.js → credential-sync-ig88EB_v.js} +15 -16
- package/dist/{db-BPLmOwXf.d.ts → db-BMZhoYKj.d.ts} +1 -1
- package/dist/{executor-DGDpyegI.js → executor-C2moGIHS.js} +2 -2
- package/dist/instrumentation.js +114 -3
- package/dist/{job-queue-CjB97sii.js → job-queue-Bh9sFO9t.js} +3 -3
- package/dist/{logging-CjkDr-jP.js → logging-DYRS7E8s.js} +14 -2
- package/dist/{media-U6Tuz6Mi.js → media-DstkkoNP.js} +21 -2
- package/dist/{message-D9y8PKA1.js → message-CicNrhCv.js} +9 -9
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +3 -3
- package/dist/{oauth-callback-server-02Pej6hj.js → oauth-callback-server-BXyrepfY.js} +2 -2
- package/dist/{credentialed-CgTulRDH.js → projection-CMRrv9Pt.js} +4595 -51
- package/dist/{prompt-vfceH0c-.js → prompt-JEWUUpLW.js} +1 -1
- package/dist/{registry-7XgwNgQe.js → registry-D92WLl5I.js} +2 -2
- package/dist/{resolve-CuuxNfWG.js → resolve-C-Dh14ps.js} +3 -3
- package/dist/{result-BRhb6iN1.js → result-DZ8TCQkd.js} +9 -9
- package/dist/{runner-DaWCofuS.js → runner-BBmhrQTM.js} +11 -11
- package/dist/{sandbox-egress-signals-Bn6FA1UC.js → sandbox-egress-signals-Cehpq6hC.js} +1 -1
- package/dist/{schema-D5VLF4NT.js → schema-CX9XGKCm.js} +18 -9
- package/dist/{schema-CNjAzYOw.d.ts → schema-DfdHlBnb.d.ts} +22 -2
- package/dist/{service-account-H45LIAG2.js → service-account-Bapo6l0R.js} +3 -3
- package/dist/{service-account-D9vrsi8d.js → service-account-Ce1465Fn.js} +3 -3
- package/dist/{session-stop-HKl0ECX0.js → session-stop-CI5qJU7a.js} +11 -11
- package/dist/{skills-CsiKu3-g.js → skills-D-d79XQ6.js} +2 -2
- package/dist/{spawn-DqjBxqWh.js → spawn-C_FETz5x.js} +2 -2
- package/dist/{list-JZUP1yog.js → stop-CmwFHwiN.js} +1003 -436
- package/dist/{store-DyVKH0QB.js → store-BIQYXvoV.js} +4 -4
- package/dist/{store-CPF2kzbu.js → store-BvI3yBGS.js} +3 -3
- package/dist/{task-queue-BbQXCcNX.js → task-queue-BdB0pab8.js} +4 -4
- package/dist/{task-runner-ChzW5E7R.js → task-runner-DQr2QfvJ.js} +7 -7
- package/dist/{thread-state-Ds8JTsX6.js → thread-state-ngCvtWNa.js} +4 -5
- package/dist/{turn-failure-response-DCMvjsA0.js → turn-failure-response-BDT3sT2v.js} +7 -8
- package/dist/{turn-lifecycle-DM_77q33.js → turn-lifecycle-B7O6rZEX.js} +1 -1
- package/dist/turn-session-routing-DIeqG2pO.js +1625 -0
- package/dist/{validation-DcGelbBi.js → validation-D3Xik64v.js} +1 -1
- package/dist/{version-C48azPKq.js → version-BoWLhNzj.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{viewer-BCRuO8Wg.js → viewer-D25XOUHc.js} +41 -20
- package/dist/{work-zxkmbJAp.js → work-D12-wcf4.js} +11 -39
- package/dist/{worker-CNNxHF1V.js → worker-DGxfDtES.js} +6 -6
- package/package.json +4 -4
- package/dist/turn-session-routing-BV_gX7n3.js +0 -6072
- package/dist/{oauth-relay-CTygMkNx.js → oauth-relay-C6ZAyJgf.js} +1 -1
|
@@ -1,43 +1,44 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-nwUcYXjP.js";
|
|
2
|
-
import { $ as
|
|
3
|
-
import { _ as
|
|
4
|
-
import {
|
|
5
|
-
import { B as
|
|
2
|
+
import { $ as loadTurnCheckpoint, $n as canAgentChangeReviewItem, $r as isAlreadyExistsError, $t as isAssistantMessage, Ai as findMatchingWatches, An as getPluginSystemPromptContributions, Ar as formatProviderLabel, B as createPluginEgress, Ba as matchSlackAttachments, Bn as closeReviewItem, Br as addReactionToMessage, Bt as TurnSliceLimitExceededError, Ci as STOP_WATCHING_TOOL_NAME, Cn as getOAuthAccountProviders, Cr as hash, D as fallbackShortTitle, Di as createTimerWatch, En as createPluginHookRunner, Er as getSandboxProvider, G as AuthorizationFlowDisabledError, Ga as createPluginAnnotations, Gi as getSlackClient, Gn as insertReviewItem, Gt as CODEMODE_TOOL_NAME, H as createPluginAuthOrchestration, Hi as downloadPrivateSlackFile, Hn as dismissOpenReviewItems, Hr as getSlackMessagePermalink, Ir as normalizeSlackReplyMarkdown, J as canReusePendingAuthLink, Ja as defaultTimezone, Ji as normalizeSlackConversationId, Jn as searchReviewItems, Jr as updateSlackMessage, Jt as getPiMessageRole, K as AuthorizationPauseError, Ki as isConversationScopedChannel, Kr as postSlackMessage, Mi as listWatches, Mn as getPluginUserPromptContributions, Mr as resolveBaseUrl, Nn as getPlugins, O as resolveTaskTitle, Oi as createWatch, Pr as escapeSlackMrkdwnText, Q as continuableMessages, Qr as isAbortError, Rr as slackMention, Rt as TURN_LIMIT_WRAP_UP_MESSAGE, Si as RESOURCE_WATCH_TOOL_SOURCE, Sn as createUserTokenStore, Sr as create, Ti as cancelWatch, Tr as ensureDockerDaemon, U as authorizationId, Ui as getFilePermalink, Un as getOpenReviewItemByDedupeKey, Ur as openSlackDirectMessage, Ut as createTurnLimitGate, V as PluginCredentialFailureError, Vi as SlackActionError, Vr as deleteSlackMessage, Vt as TurnToolCallLimitExceededError, W as AuthPausePersistenceError, Wa as saveObjectAnnotations, Wn as getReviewItem, Wt as isTurnExecutionLimitExceededError, Xi as withSlackRetries, Xn as updateReviewItemContent, Xt as getUserMessageInstructionText, Ya as resolveUserTimezone, Yi as runWithSlackInstallationToken, Yr as uploadFilesToConversation, Yt as getTerminalAssistantMessages, Zi as sleep, Zn as PLUGIN_REVIEW_ITEM_KEY_PREFIX, Zt as hasRuntimeTurnContext, _a as sandboxSkillDir, _i as workspaceRepoCheckoutPath, _n as getAgentContextCompactionTriggerTokens, _r as WorkspaceValidationError, a as loadLastModelProfile, ai as workspaceSnapshotNotReadyUserMessage, an as stripRuntimeTurnContext, bi as RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS, bn as isExperimentalFeatureEnabled, br as setWorkspaceSnapshot, c as loadTurnRoute, ca as buildCommandScript, ci as consumeSandboxEgressPermissionDeniedSignal, cn as SESSION_CONTEXT_SECTION_TAG, cr as resolveAssignee, d as recordAttachmentsDelivered, da as SANDBOX_COMMAND_PATH, dn as buildDeterministicTurnId, dr as deleteWorkspace, ei as throwSandboxOperationError, en as isContinuablePiBoundary, eo as historyItemFromPiMessage, er as canReadReviewItem, et as saveTurnCheckpoint, fa as SANDBOX_DATA_ROOT, fi as buildSandboxEgressNetworkPolicy, fr as getWorkspace, g as recordMcpProviderConnected, ga as SANDBOX_WORKSPACE_ROOT, gi as tryWorkspaceRepoCheckoutPath, gn as estimateTextTokens, gr as updateWorkspace, h as recordGuardianActionReviewed, ha as SANDBOX_SKILLS_ROOT, hi as SANDBOX_RUNTIME, i as loadConversationProjection, ia as getDashboardTaskLink, ii as isWorkspaceSnapshotNotReadyError, in as retainRuntimeTurnContext, io as getConfigDefaults, ir as requireReviewItemLinks, ji as getWatch, jn as getPluginTools, ki as deliverWatch, kr as deliverOAuthAuthorization, l as openConversationProjection, la as buildNonInteractiveShellScript, li as createSandboxEgressCredentialToken, ln as TURN_CONTEXT_TAG, lr as resolveAssignees, m as recordAuthorizationRequested, ma as SANDBOX_REPOS_ROOT, mr as listWorkspaces, ni as WorkspaceSnapshotNotReadyError, nn as isToolResultMessage, no as JUNIOR_NATIVE_EVENT_NAMESPACE, nr as readReviewItemAgentScope, oa as ToolInputError, oi as clearSandboxEgressSignals, on as trimTrailingAssistantMessages, or as EVERYONE_ASSIGNEE, pa as SANDBOX_JUNIOR_ROOT, pi as resolveSandboxCommandEnvironment, pr as getWorkspaceByName, q as abandonReplacedPendingAuth, qt as extractAssistantText, r as loadConnectedMcpProviders, ra as getDashboardReviewItemLink, ri as getWorkspaceSnapshotNotReadyError, rn as normalizeToolNameFromResult, ro as conversationNoteEvent, rr as requireReviewItemAssignees, sa as PluginToolDeniedError, si as consumeSandboxEgressAuthRequiredSignal, sn as REQUEST_CONTEXT_SECTION_TAG, sr as automationCreatorUserId, ta as getDashboardConversationLink, ti as wrapSandboxSetupError, tn as isToolResultError, to as piMessageFromHistoryItem, u as recordAgentsInstructionsUpdated, ua as runNonInteractiveCommand, ur as createWorkspace, v as recordToolExecutionStarted, va as sandboxSkillFile, vi as resolveChannelCapabilities, vn as getAgentContextInputLimitTokens, vr as invalidateReadySnapshot, wi as cancelSubscriptions, wr as isStale, xi as RESOURCE_SUBSCRIPTION_MAX_TTL_MS, xr as setWorkspaceSnapshotBuild, y as recordTurnRoute, ya as sandboxSkillPathResolution, yi as getSlackToolContext, yr as loadSnapshotsForProfile, zt as TurnBudgetExceededError } from "./projection-CMRrv9Pt.js";
|
|
3
|
+
import { S as resolveGatewayCredential, _ as findProviderError, a as completeText, b as isProviderRetryError, c as resolveGatewayModel, d as isCompactionSummaryText, f as renderCurrentInstruction, g as createProviderError, h 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 getProviderErrorAttributes, x as getGatewayApiKey } from "./client-C0ZIxoDr.js";
|
|
4
|
+
import { _ as normalizeSlackEmojiName, n as botConfig } from "./config-DS-QLVSL.js";
|
|
5
|
+
import { B as normalizeIdentityEmail, C as summarizeMessageText, E as withSpan, L as runWithLogAttributes, S as setTags, T as withLogContext, U as toOptionalString, V as isRecord$4, _ as runBestEffort, a as extractGenAiUsageSummary, b as setSpanAttributes, f as logError, g as normalizeGenAiFinishReason, h as logWarn, i as extractGenAiUsageAttributes, l as getLogContextAttributesForSpan, m as logInfo, p as logException, u as getTracePropagationHeaders, v as serializeGenAiAttribute, x as setSpanStatus } from "./logging-DYRS7E8s.js";
|
|
6
6
|
import { g as withActiveSpan, i as getActiveSpan, m as startInactiveSpan } from "./sentry-MDkYAVPV.js";
|
|
7
|
-
import { a as toCanonicalInputMessage, c as toGenAiPayloadMetadata, i as runWithConversationPrivacy, l as toGenAiPayloadTraceAttributes, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes, t as canExposeConversationPayload } from "./conversation-privacy-
|
|
7
|
+
import { a as toCanonicalInputMessage, c as toGenAiPayloadMetadata, i as runWithConversationPrivacy, l as toGenAiPayloadTraceAttributes, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes, t as canExposeConversationPayload } from "./conversation-privacy-3IMUZSHC.js";
|
|
8
8
|
import { a as formatModelProfile, c as modelProfileSchema, l as profileConfig, n as ModelProfileNotConfiguredError, o as formatModelProfiles, r as boundProfile, s as modelIdForProfile, u as TURN_REASONING_LEVELS } from "./model-profile-B998sjVd.js";
|
|
9
9
|
import { d as parseSlackChannelReferenceId, f as parseSlackTeamId, h as parseSlackMessageTs, n as createSlackActor, o as isUserActor, p as parseSlackUserId, u as parseSlackChannelId } from "./actor-B4DYygOB.js";
|
|
10
|
-
import { C as getSqlExecutor,
|
|
10
|
+
import { $ as sameDestination, C as getSqlExecutor, G as agentTurnCostUsd, J as hasAgentTurnUsage, M as SYSTEM_IDENTITY_ID, N as resolveActorIdentityId, S as getDb, W as addAgentTurnUsage, Z as parseDestination, a as readActorIdentityFromSql, b as getConversationMessageSearchStore, f as identityAvatarUrl, h as readUserAvatarUrls, i as readActorIdentity, x as getConversationStore, y as getConversationEventStore } from "./viewer-D25XOUHc.js";
|
|
11
11
|
import { a as juniorAgentInvocations, c as juniorIdentities, d as juniorDestinations, i as juniorAgentBindings, l as juniorUsers, s as juniorConversations } from "./agent-invocations-C1RNOCs8.js";
|
|
12
|
-
import { E as juniorArtifacts, S as juniorConversationAnnotations, T as juniorAttachments, _ as juniorConversationBriefs, d as juniorAutomations, f as juniorStats, l as juniorAutomationRuns, s as juniorReviewItemSlackCards } from "./executor-
|
|
13
|
-
import { _ as sameActorIdentity, g as instructionProvenanceFor, h as instructionActors, i as KNOWN_CONVERSATION_EVENT_TYPES, m as contextProvenance, n as detectImageMediaType, p as agentInstructionProvenance, r as isVisionImageMediaType } from "./media-
|
|
12
|
+
import { E as juniorArtifacts, S as juniorConversationAnnotations, T as juniorAttachments, _ as juniorConversationBriefs, d as juniorAutomations, f as juniorStats, l as juniorAutomationRuns, s as juniorReviewItemSlackCards } from "./executor-C2moGIHS.js";
|
|
13
|
+
import { _ as sameActorIdentity, g as instructionProvenanceFor, h as instructionActors, i as KNOWN_CONVERSATION_EVENT_TYPES, m as contextProvenance, n as detectImageMediaType, p as agentInstructionProvenance, r as isVisionImageMediaType } from "./media-DstkkoNP.js";
|
|
14
14
|
import { a as listReferenceFiles, c as soulPathCandidates, l as worldPathCandidates } from "./package-discovery-DJBompdd.js";
|
|
15
|
-
import { c as fetchWithBoundedOAuthErrorBodies, d as actorLogContext, f as credentialContextForActor, g as credentialUserSubjectId, i as resolvePluginHeaderEnvRefs, l as getOAuthProviderErrorAttributes, s as OAuthProviderError } from "./registry-
|
|
16
|
-
import { n as pluginCatalogRuntime } from "./catalog-runtime-
|
|
17
|
-
import { a as parseSkillInvocation, i as parseSkillFile, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-
|
|
18
|
-
import { $ as loadSnapshotsForProfile, $n as sandboxSkillDir, $t as workspaceRepoCheckoutPath, A as updateReviewItemContent, An as normalizeSlackConversationId, B as EVERYONE_ASSIGNEE, Bn as getDashboardTaskLink, Bt as clearSandboxEgressSignals, C as getOpenReviewItemByDedupeKey, Cn as SlackActionError, Ct as openSlackDirectMessage, Dn as getSlackClient, Et as postSlackMessage, Ft as wrapSandboxSetupError, G as deleteWorkspace, Gn as buildNonInteractiveShellScript, H as resolveAssignee, Hn as ToolInputError, Ht as consumeSandboxEgressPermissionDeniedSignal, I as readReviewItemAgentScope, Ir as conversationNoteEvent, It as WorkspaceSnapshotNotReadyError, J as listWorkspaces, Jn as SANDBOX_DATA_ROOT, Jt as resolveSandboxCommandEnvironment, K as getWorkspace, Kn as runNonInteractiveCommand, L as requireReviewItemAssignees, Ln as getDashboardConversationLink, Lt as getWorkspaceSnapshotNotReadyError, Mn as withSlackRetries, Mr as JUNIOR_NATIVE_EVENT_NAMESPACE, Mt as isAbortError, N as canAgentChangeReviewItem, Nn as sleep, Nt as isAlreadyExistsError, O as searchReviewItems, On as isConversationScopedChannel, Or as defaultTimezone, Ot as updateSlackMessage, P as canReadReviewItem, Pt as throwSandboxOperationError, Q as invalidateReadySnapshot, Qn as SANDBOX_WORKSPACE_ROOT, Qt as tryWorkspaceRepoCheckoutPath, R as requireReviewItemLinks, Rt as isWorkspaceSnapshotNotReadyError, S as dismissOpenReviewItems, St as getSlackMessagePermalink, T as insertReviewItem, Tn as getFilePermalink, Tr as createPluginAnnotations, U as resolveAssignees, Un as PluginToolDeniedError, Ut as createSandboxEgressCredentialToken, V as automationCreatorUserId, Vt as consumeSandboxEgressAuthRequiredSignal, W as createWorkspace, Wn as buildCommandScript, X as updateWorkspace, Xn as SANDBOX_REPOS_ROOT, Yn as SANDBOX_JUNIOR_ROOT, Z as WorkspaceValidationError, Zn as SANDBOX_SKILLS_ROOT, Zt as SANDBOX_RUNTIME, an as STOP_WATCHING_TOOL_NAME, at as ensureDockerDaemon, b as closeReviewItem, br as matchSlackAttachments, bt as addReactionToMessage, d as getPluginTools, dn as deliverWatch, en as resolveChannelCapabilities, er as sandboxSkillFile, et as setWorkspaceSnapshot, f as getPluginUserPromptContributions, fn as findMatchingWatches, ft as resolveBaseUrl, gt as normalizeSlackReplyMarkdown, in as RESOURCE_WATCH_TOOL_SOURCE, it as isStale, j as PLUGIN_REVIEW_ITEM_KEY_PREFIX, jn as runWithSlackInstallationToken, kr as resolveUserTimezone, kt as uploadFilesToConversation, ln as createTimerWatch, lt as deliverOAuthAuthorization, mn as listWatches, mt as escapeSlackMrkdwnText, n as createUserTokenStore, nn as RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS, nt as create, o as createPluginHookRunner, on as cancelSubscriptions, ot as getSandboxProvider, p as getPlugins, pn as getWatch, q as getWorkspaceByName, qn as SANDBOX_COMMAND_PATH, qt as buildSandboxEgressNetworkPolicy, r as getOAuthAccountProviders, rn as RESOURCE_SUBSCRIPTION_MAX_TTL_MS, rt as hash, sn as cancelWatch, tn as getSlackToolContext, tr as sandboxSkillPathResolution, tt as setWorkspaceSnapshotBuild, u as getPluginSystemPromptContributions, un as createWatch, ut as formatProviderLabel, vt as slackMention, w as getReviewItem, wn as downloadPrivateSlackFile, wr as saveObjectAnnotations, xt as deleteSlackMessage, zn as getDashboardReviewItemLink, zt as workspaceSnapshotNotReadyUserMessage } from "./credentialed-CgTulRDH.js";
|
|
15
|
+
import { c as fetchWithBoundedOAuthErrorBodies, d as actorLogContext, f as credentialContextForActor, g as credentialUserSubjectId, i as resolvePluginHeaderEnvRefs, l as getOAuthProviderErrorAttributes, s as OAuthProviderError } from "./registry-D92WLl5I.js";
|
|
16
|
+
import { n as pluginCatalogRuntime } from "./catalog-runtime-BnIJimKZ.js";
|
|
17
|
+
import { a as parseSkillInvocation, i as parseSkillFile, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-D-d79XQ6.js";
|
|
19
18
|
import { a as withLock, i as fenceLock } from "./locks-D-0h111u.js";
|
|
20
|
-
import { r as getStateAdapter } from "./adapter-
|
|
19
|
+
import { r as getStateAdapter } from "./adapter-4qThDhgF.js";
|
|
21
20
|
import { i as isValidTimeZone, r as getZonedDateTimeParts, t as getFirstRunAtMs } from "./cadence-R7Em4RjE.js";
|
|
22
|
-
import { J as briefOutcomeStatusSchema, V as removedCardSchema, Y as conversationBriefSchema, q as briefLinkSchema } from "./conversation-
|
|
23
|
-
import { r as EVENT_AUTHOR_ID } from "./prompt-
|
|
24
|
-
import { A as AgentMessagePausedError, F as CHILD_AGENT_RESULTS, I as PARENT_AGENT_TARGET, J as isTurnInputCommitLostError, L as agentNameSchema, M as AgentMessageTargetError, N as AgentNameInUseError, R as AGENT_TYPES, U as CooperativeTurnYieldError, V as formatAgentTypes, W as TurnInputCommitLostError, _ as invocationFromRow, d as getAgentInvocationMessageId, g as getLatestAgentInvocationForConversation, h as getChildAgentLockName, j as AgentMessageQueueFullError, k as AgentInvocationLimitError, t as NON_TERMINAL_AGENT_INVOCATION_STATUSES, u as getAgentInvocationIdForResult, v as isTerminalAgentInvocation } from "./store-
|
|
25
|
-
import { a as isNoReplyMarker, i as NO_REPLY_MARKER, n as getAssistantReplyText, r as sanitizeAssistantText, t as decideReply } from "./assistant-reply-
|
|
26
|
-
import { E as resolveSlackReplyTarget, L as readAutomationResult, M as FINISH_AUTOMATION_RUN_TOOL_NAME, N as automationResultSchema$1, R as remindMissingAutomationResult, _ as slackChannelMessageTrigger, a as EVENT_WAIT_MS, b as workspaceSnapshotFinishedEvent, d as getEventCatalog, n as markConversationsStopped, o as enqueueEventNotification, p as requireSlackChannelMessageScope, t as getConversationStoppedAtMs, v as WORKSPACE_SNAPSHOT_FAILED_EVENT, x as workspaceSnapshotWatch, y as WORKSPACE_SNAPSHOT_READY_EVENT } from "./session-stop-
|
|
21
|
+
import { J as briefOutcomeStatusSchema, V as removedCardSchema, Y as conversationBriefSchema, q as briefLinkSchema } from "./conversation-BjTo9ZFL.js";
|
|
22
|
+
import { r as EVENT_AUTHOR_ID } from "./prompt-JEWUUpLW.js";
|
|
23
|
+
import { A as AgentMessagePausedError, F as CHILD_AGENT_RESULTS, I as PARENT_AGENT_TARGET, J as isTurnInputCommitLostError, L as agentNameSchema, M as AgentMessageTargetError, N as AgentNameInUseError, R as AGENT_TYPES, U as CooperativeTurnYieldError, V as formatAgentTypes, W as TurnInputCommitLostError, _ as invocationFromRow, d as getAgentInvocationMessageId, g as getLatestAgentInvocationForConversation, h as getChildAgentLockName, j as AgentMessageQueueFullError, k as AgentInvocationLimitError, t as NON_TERMINAL_AGENT_INVOCATION_STATUSES, u as getAgentInvocationIdForResult, v as isTerminalAgentInvocation } from "./store-BIQYXvoV.js";
|
|
24
|
+
import { a as isNoReplyMarker, i as NO_REPLY_MARKER, n as getAssistantReplyText, r as sanitizeAssistantText, t as decideReply } from "./assistant-reply-2IwdFWuQ.js";
|
|
25
|
+
import { E as resolveSlackReplyTarget, L as readAutomationResult, M as FINISH_AUTOMATION_RUN_TOOL_NAME, N as automationResultSchema$1, R as remindMissingAutomationResult, _ as slackChannelMessageTrigger, a as EVENT_WAIT_MS, b as workspaceSnapshotFinishedEvent, d as getEventCatalog, n as markConversationsStopped, o as enqueueEventNotification, p as requireSlackChannelMessageScope, t as getConversationStoppedAtMs, v as WORKSPACE_SNAPSHOT_FAILED_EVENT, x as workspaceSnapshotWatch, y as WORKSPACE_SNAPSHOT_READY_EVENT } from "./session-stop-CI5qJU7a.js";
|
|
27
26
|
import { C as userCustomizationTextSchema, b as webMessageId, g as formatUserInputAnswer, h as buttonUserInputField, m as USER_INPUT_NOTE, p as USER_INPUT_LIMITS, s as sumUtcHoursIntoSixHours, v as normalizeUserInputAnswer, x as USER_CUSTOMIZATION_MAX_CHARS, y as userInputRequestSchema } from "./reporting-window-DgHgwQB3.js";
|
|
28
|
-
import { a as setSnapshotSpanAttributes, i as postinstall, n as resolve$1, r as dependencies, s as getSandboxResources } from "./resolve-
|
|
29
|
-
import { a as getVercelConversationWorkQueue, f as getTurnRequestDeadline, n as sendNextWorkspaceSnapshotJob, r as sendWorkspaceSnapshotJob } from "./job-queue-
|
|
30
|
-
import { D as stopConversationWork, n as appendAndEnqueueExclusiveInboundMessage, r as appendAndEnqueueInboundMessage } from "./store-
|
|
31
|
-
import {
|
|
32
|
-
import {
|
|
27
|
+
import { a as setSnapshotSpanAttributes, i as postinstall, n as resolve$1, r as dependencies, s as getSandboxResources } from "./resolve-C-Dh14ps.js";
|
|
28
|
+
import { a as getVercelConversationWorkQueue, f as getTurnRequestDeadline, n as sendNextWorkspaceSnapshotJob, r as sendWorkspaceSnapshotJob } from "./job-queue-Bh9sFO9t.js";
|
|
29
|
+
import { D as stopConversationWork, n as appendAndEnqueueExclusiveInboundMessage, r as appendAndEnqueueInboundMessage } from "./store-BvI3yBGS.js";
|
|
30
|
+
import { $ as saveEventAutomation, A as readAutomationRuns, B as readScheduledAutomation, C as readAutomationExecutionByConversationId, Ct as requireEventIdentifier, D as readAutomationExecutionStatusHours, E as readAutomationExecutionStatusDays, I as createScheduledAutomation, J as deleteEventAutomation, L as deleteScheduledAutomation, O as readAutomationExecutionSummaries, Q as parseEventAutomationRow, St as registeredResourceTypeSchema, T as readAutomationExecutionHours, V as saveScheduledAutomation, X as getEventAutomation, Z as listDeletedEventAutomationsCreatedBy, _t as eventWatchUnavailable, at as listAutomationVersions, bt as registeredEventTriggerProblems, c as getDispatchIdForConversation, et as setEventAutomationStatus, ft as automationEventCatalog, gt as eventNamespaceSchema, k as readAutomationExecutions, l as getDispatchInputMessageId, lt as automationRevision, ot as readAutomationVersion, pt as describeRegisteredEventTrigger, q as createEventAutomation, rt as automationDefinition, st as sameDefinitionValue, t as resolveConversationRouting, u as getDispatchRecord, ut as requireAutomationRevision, vt as hasEventCatalogEntries, w as readAutomationExecutionDays, wt as requireValidEventTrigger, x as emptyAutomationRunWindows, xt as registeredEventTypeSchema, yt as registeredEventMatchSchema, z as parseScheduledAutomationRow } from "./turn-session-routing-DIeqG2pO.js";
|
|
31
|
+
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-Bapo6l0R.js";
|
|
32
|
+
import { A as SCHEDULED_AUTOMATION_SYSTEM_ACTOR, D as taskOutcomeInputSchema, E as automationTitleSchema, F as scheduleIntentSchema, I as weekdaySchema, N as ScheduleIntentError, P as compileScheduleIntent, T as automationInstructionToolSchema, k as eventAutomationTriggerSchema, l as automationListQuerySchema } from "./automation-BGrd03QO.js";
|
|
33
33
|
import { n as privateTraceResultAttributes } from "./private-trace-result-CE7_lEdq.js";
|
|
34
34
|
import { streamSimple } from "@earendil-works/pi-ai/compat";
|
|
35
35
|
import { createGatewayProvider } from "@ai-sdk/gateway";
|
|
36
36
|
import { NoImageGeneratedError, generateImage, generateText } from "ai";
|
|
37
37
|
import path from "node:path";
|
|
38
38
|
import { isDeepStrictEqual } from "node:util";
|
|
39
|
-
import {
|
|
39
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
40
40
|
import { createHash, randomBytes, randomInt, randomUUID } from "node:crypto";
|
|
41
|
+
import { z } from "zod";
|
|
41
42
|
import { and, asc, count, desc, eq, exists, gt, gte, inArray, isNotNull, isNull, lt, lte, ne, notExists, notInArray, or, sql } from "drizzle-orm";
|
|
42
43
|
import { PluginToolInputError, createWebSource, eventMatchFieldSchema, eventMatchSchema, eventReachSchema, eventSchema, eventTriggerText, localDestinationSchema, missingToolAnnotationKeys, ownedObjectAnnotationSchema, sourceSchema, stableEventMatchKey, watchResultSchema } from "@sentry/junior-plugin-api";
|
|
43
44
|
import { alias } from "drizzle-orm/pg-core";
|
|
@@ -48,6 +49,7 @@ import http from "node:http";
|
|
|
48
49
|
import dns from "node:dns/promises";
|
|
49
50
|
import net from "node:net";
|
|
50
51
|
import { SignJWT, importPKCS8 } from "jose";
|
|
52
|
+
import { performance as performance$1 } from "node:perf_hooks";
|
|
51
53
|
import { createAssistantMessageEventStream, isRetryableAssistantError } from "@earendil-works/pi-ai";
|
|
52
54
|
import { Bash, defineCommand } from "just-bash";
|
|
53
55
|
import { structuredPatch } from "diff";
|
|
@@ -202,172 +204,6 @@ var SkillSandbox = class {
|
|
|
202
204
|
throw new Error("No active skill is loaded. Call loadSkill first or pass skill_name explicitly.");
|
|
203
205
|
}
|
|
204
206
|
};
|
|
205
|
-
// src/chat/tools/sandbox/file-utils.ts
|
|
206
|
-
const MAX_TEXT_CHARS = 6e4;
|
|
207
|
-
const RIPGREP_EXCLUDED_GLOBS = ["!**/.git/**", "!**/node_modules/**"];
|
|
208
|
-
const DEFAULT_SEARCH_COMMAND_TIMEOUT_MS = 3e4;
|
|
209
|
-
const SKIPPED_DIRECTORIES = /* @__PURE__ */ new Set([".git", "node_modules"]);
|
|
210
|
-
/** Normalize model-supplied numeric knobs before they reach filesystem tools. */
|
|
211
|
-
function positiveInteger$1(value) {
|
|
212
|
-
if (typeof value !== "number" || !Number.isFinite(value)) return;
|
|
213
|
-
const integer = Math.floor(value);
|
|
214
|
-
return integer > 0 ? integer : void 0;
|
|
215
|
-
}
|
|
216
|
-
/** Compare and slice text in one line-ending space while preserving callers' output rules. */
|
|
217
|
-
function normalizeToLf$1(value) {
|
|
218
|
-
return value.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
219
|
-
}
|
|
220
|
-
/** Keep tool output inside the model-facing budget with an explicit notice. */
|
|
221
|
-
function truncateText$1(value, maxChars = MAX_TEXT_CHARS) {
|
|
222
|
-
if (value.length <= maxChars) return {
|
|
223
|
-
content: value,
|
|
224
|
-
truncated: false
|
|
225
|
-
};
|
|
226
|
-
const removed = value.length - maxChars;
|
|
227
|
-
return {
|
|
228
|
-
content: `${value.slice(0, maxChars)}\n\n[output truncated: ${removed} characters removed]`,
|
|
229
|
-
truncated: true
|
|
230
|
-
};
|
|
231
|
-
}
|
|
232
|
-
/** Detect model-facing missing paths without swallowing sandbox lifecycle/API failures. */
|
|
233
|
-
function isMissingPathError(error) {
|
|
234
|
-
if (!error || typeof error !== "object") return false;
|
|
235
|
-
const candidate = error;
|
|
236
|
-
if (candidate.code === "ENOENT") return true;
|
|
237
|
-
return typeof candidate.message === "string" && candidate.message.startsWith("File not found:");
|
|
238
|
-
}
|
|
239
|
-
/** Reject an expected missing search/list path through the tool-error channel. */
|
|
240
|
-
function missingPathSearchResult(params) {
|
|
241
|
-
const textPath = params.displayPath ?? params.missingPath ?? params.path;
|
|
242
|
-
throw new ToolInputError(`Path not found: ${textPath}`);
|
|
243
|
-
}
|
|
244
|
-
function escapeRegExp(value) {
|
|
245
|
-
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
246
|
-
}
|
|
247
|
-
function globToRegExp(pattern) {
|
|
248
|
-
let source = "";
|
|
249
|
-
for (let index = 0; index < pattern.length; index += 1) {
|
|
250
|
-
const char = pattern.charAt(index);
|
|
251
|
-
const next = pattern[index + 1];
|
|
252
|
-
if (char === "*" && next === "*") {
|
|
253
|
-
if (pattern[index + 2] === "/") {
|
|
254
|
-
source += "(?:.*/)?";
|
|
255
|
-
index += 2;
|
|
256
|
-
continue;
|
|
257
|
-
}
|
|
258
|
-
source += ".*";
|
|
259
|
-
index += 1;
|
|
260
|
-
continue;
|
|
261
|
-
}
|
|
262
|
-
if (char === "*") {
|
|
263
|
-
source += "[^/]*";
|
|
264
|
-
continue;
|
|
265
|
-
}
|
|
266
|
-
if (char === "?") {
|
|
267
|
-
source += "[^/]";
|
|
268
|
-
continue;
|
|
269
|
-
}
|
|
270
|
-
source += escapeRegExp(char);
|
|
271
|
-
}
|
|
272
|
-
return new RegExp(`^${source}$`);
|
|
273
|
-
}
|
|
274
|
-
function matchesGlob(relativePath, pattern) {
|
|
275
|
-
const matcher = globToRegExp(pattern);
|
|
276
|
-
if (matcher.test(relativePath)) return true;
|
|
277
|
-
if (pattern.startsWith("**/") && matchesGlob(relativePath, pattern.slice(3))) return true;
|
|
278
|
-
return !pattern.includes("/") && matcher.test(path.posix.basename(relativePath));
|
|
279
|
-
}
|
|
280
|
-
/** Keep sandbox filesystem tools scoped to the mounted workspace root. */
|
|
281
|
-
function resolveWorkspacePath(input, fallback = ".") {
|
|
282
|
-
const requested = (input ?? "").trim() || fallback;
|
|
283
|
-
const absolute = requested.startsWith("/") ? requested : path.posix.join(SANDBOX_WORKSPACE_ROOT, requested);
|
|
284
|
-
const normalized = path.posix.normalize(absolute);
|
|
285
|
-
if (normalized !== SANDBOX_WORKSPACE_ROOT && !normalized.startsWith(`${SANDBOX_WORKSPACE_ROOT}/`)) throw new ToolInputError(`Path must stay within ${SANDBOX_WORKSPACE_ROOT}: ${requested}`);
|
|
286
|
-
return normalized;
|
|
287
|
-
}
|
|
288
|
-
/** Anchor ripgrep paths and globs to the requested search root. */
|
|
289
|
-
function getRipgrepSearchLocation(root, rootIsDirectory) {
|
|
290
|
-
if (rootIsDirectory) return {
|
|
291
|
-
cwd: root,
|
|
292
|
-
target: "."
|
|
293
|
-
};
|
|
294
|
-
return {
|
|
295
|
-
cwd: path.posix.dirname(root),
|
|
296
|
-
target: path.posix.basename(root)
|
|
297
|
-
};
|
|
298
|
-
}
|
|
299
|
-
/** Share bounded workspace traversal across search tools so their skip rules stay aligned. */
|
|
300
|
-
async function collectFiles(params) {
|
|
301
|
-
const files = [];
|
|
302
|
-
let limitReached = false;
|
|
303
|
-
let missingPath;
|
|
304
|
-
const visit = async (dirPath) => {
|
|
305
|
-
if (missingPath) return;
|
|
306
|
-
let entries;
|
|
307
|
-
try {
|
|
308
|
-
entries = (await params.fs.readdir(dirPath)).sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
|
|
309
|
-
} catch (error) {
|
|
310
|
-
if (isMissingPathError(error)) {
|
|
311
|
-
missingPath = dirPath;
|
|
312
|
-
return;
|
|
313
|
-
}
|
|
314
|
-
throw error;
|
|
315
|
-
}
|
|
316
|
-
for (const entry of entries) {
|
|
317
|
-
const fullPath = path.posix.join(dirPath, entry);
|
|
318
|
-
let stat;
|
|
319
|
-
try {
|
|
320
|
-
stat = await params.fs.stat(fullPath);
|
|
321
|
-
} catch (error) {
|
|
322
|
-
if (isMissingPathError(error)) {
|
|
323
|
-
missingPath = fullPath;
|
|
324
|
-
return;
|
|
325
|
-
}
|
|
326
|
-
throw error;
|
|
327
|
-
}
|
|
328
|
-
if (stat.isDirectory()) {
|
|
329
|
-
if (!SKIPPED_DIRECTORIES.has(entry)) await visit(fullPath);
|
|
330
|
-
if (limitReached) return;
|
|
331
|
-
continue;
|
|
332
|
-
}
|
|
333
|
-
const relativePath = path.posix.relative(params.root, fullPath);
|
|
334
|
-
if (!params.pattern || matchesGlob(relativePath, params.pattern)) {
|
|
335
|
-
files.push(fullPath);
|
|
336
|
-
if (params.limit && files.length >= params.limit) {
|
|
337
|
-
limitReached = true;
|
|
338
|
-
return;
|
|
339
|
-
}
|
|
340
|
-
}
|
|
341
|
-
}
|
|
342
|
-
};
|
|
343
|
-
let stat;
|
|
344
|
-
try {
|
|
345
|
-
stat = await params.fs.stat(params.root);
|
|
346
|
-
} catch (error) {
|
|
347
|
-
if (isMissingPathError(error)) return {
|
|
348
|
-
files,
|
|
349
|
-
limitReached: false,
|
|
350
|
-
missingPath: params.root,
|
|
351
|
-
missingRoot: true
|
|
352
|
-
};
|
|
353
|
-
throw error;
|
|
354
|
-
}
|
|
355
|
-
if (!stat.isDirectory()) {
|
|
356
|
-
const relativePath = path.posix.basename(params.root);
|
|
357
|
-
return {
|
|
358
|
-
files: !params.pattern || matchesGlob(relativePath, params.pattern) ? [params.root] : [],
|
|
359
|
-
limitReached: false,
|
|
360
|
-
missingRoot: false
|
|
361
|
-
};
|
|
362
|
-
}
|
|
363
|
-
await visit(params.root);
|
|
364
|
-
return {
|
|
365
|
-
files,
|
|
366
|
-
limitReached,
|
|
367
|
-
missingPath,
|
|
368
|
-
missingRoot: missingPath === params.root
|
|
369
|
-
};
|
|
370
|
-
}
|
|
371
207
|
// src/chat/repository-instructions.ts
|
|
372
208
|
const AGENTS_FILENAME = "AGENTS.md";
|
|
373
209
|
const MAX_REPOSITORY_INSTRUCTIONS_BYTES = 32768;
|
|
@@ -382,81 +218,207 @@ const REPOSITORY_SKILLS_HEADER = [
|
|
|
382
218
|
].join("\n");
|
|
383
219
|
const AGENTS_REPLACEMENT_NOTICE = "These AGENTS.md instructions replace all previously provided AGENTS.md instructions.";
|
|
384
220
|
const AGENTS_REMOVAL_NOTICE = "The previously provided AGENTS.md instructions no longer apply.";
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
221
|
+
/**
|
|
222
|
+
* Read limit for each AGENTS.md and SKILL.md file. It is 3 bytes past the
|
|
223
|
+
* budget: a UTF-8 character has at most 4 bytes, so a character cut at this
|
|
224
|
+
* limit starts after the budget, and the budgeted text is the same as with a
|
|
225
|
+
* full read.
|
|
226
|
+
*/
|
|
227
|
+
const FILE_READ_LIMIT_BYTES = 32771;
|
|
228
|
+
/**
|
|
229
|
+
* Print every path and file that the instructions read needs, one record per
|
|
230
|
+
* line. The cwd is the workspace root, and all paths are relative to it.
|
|
231
|
+
*
|
|
232
|
+
* Arguments: the file read limit, then `repos` to read every Git worktree in
|
|
233
|
+
* it or "", then one group for each selected directory. A group holds the
|
|
234
|
+
* directories from the selected directory up to the workspace root, then "".
|
|
235
|
+
* A group stops at its first directory with `.git`.
|
|
236
|
+
*
|
|
237
|
+
* Records: `R <dir>` for a Git worktree in repos/, `G <dir>/.git`, `D <path>`
|
|
238
|
+
* for a directory in a skill root, `E <path>` for another entry in a skill
|
|
239
|
+
* root, and `F <base64> <path>` for an AGENTS.md or SKILL.md file. File
|
|
240
|
+
* tests follow symlinks like `stat -L`. Globs skip dot entries like `ls -1`,
|
|
241
|
+
* which the Vercel Sandbox `readdir` runs.
|
|
242
|
+
*/
|
|
243
|
+
const READ_SCRIPT = `
|
|
244
|
+
limit=$1
|
|
245
|
+
repos=$2
|
|
246
|
+
shift 2
|
|
247
|
+
|
|
248
|
+
nl='
|
|
249
|
+
'
|
|
250
|
+
# A glob result is an entry when it exists. Like the lines of \`ls -1\`, a
|
|
251
|
+
# name with a line break does not name an entry.
|
|
252
|
+
listed() {
|
|
253
|
+
case $1 in *"$nl"*) return 1 ;; esac
|
|
254
|
+
[ -e "$1" ] || [ -L "$1" ]
|
|
393
255
|
}
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
256
|
+
|
|
257
|
+
emit_file() {
|
|
258
|
+
[ -f "$1" ] || return 0
|
|
259
|
+
if [ ! -r "$1" ]; then
|
|
260
|
+
printf 'cannot read %s\\n' "$1" >&2
|
|
261
|
+
exit 1
|
|
262
|
+
fi
|
|
263
|
+
printf 'F '
|
|
264
|
+
head -c "$limit" < "$1" | base64 | tr -d '\\n'
|
|
265
|
+
printf ' %s\\n' "$1"
|
|
401
266
|
}
|
|
402
|
-
|
|
267
|
+
|
|
268
|
+
emit_skills() {
|
|
269
|
+
for entry in "$1/.agents/skills"/* "$1/.claude/skills"/*; do
|
|
270
|
+
listed "$entry" || continue
|
|
271
|
+
# The first skill root wins for each name. Skip entries that it shadows.
|
|
272
|
+
case $entry in
|
|
273
|
+
"$1/.claude/skills/"*) listed "$1/.agents/skills/\${entry##*/}" && continue ;;
|
|
274
|
+
esac
|
|
275
|
+
if [ -d "$entry" ]; then
|
|
276
|
+
printf 'D %s\\n' "$entry"
|
|
277
|
+
emit_file "$entry/SKILL.md"
|
|
278
|
+
else
|
|
279
|
+
printf 'E %s\\n' "$entry"
|
|
280
|
+
fi
|
|
281
|
+
done
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
if [ -n "$repos" ]; then
|
|
285
|
+
for repo in "$repos"/*; do
|
|
286
|
+
if listed "$repo" && [ -d "$repo" ] && [ -e "$repo/.git" ]; then
|
|
287
|
+
printf 'R %s\\n' "$repo"
|
|
288
|
+
set -- "$@" "$repo" ""
|
|
289
|
+
fi
|
|
290
|
+
done
|
|
291
|
+
fi
|
|
292
|
+
|
|
293
|
+
found=
|
|
294
|
+
for dir in "$@"; do
|
|
295
|
+
if [ -z "$dir" ]; then
|
|
296
|
+
found=
|
|
297
|
+
elif [ -z "$found" ]; then
|
|
298
|
+
emit_file "$dir/AGENTS.md"
|
|
299
|
+
if [ -e "$dir/.git" ]; then
|
|
300
|
+
printf 'G %s/.git\\n' "$dir"
|
|
301
|
+
emit_skills "$dir"
|
|
302
|
+
found=1
|
|
303
|
+
fi
|
|
304
|
+
fi
|
|
305
|
+
done
|
|
306
|
+
`;
|
|
307
|
+
const BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/;
|
|
308
|
+
function compareStrings(left, right) {
|
|
309
|
+
return left < right ? -1 : left > right ? 1 : 0;
|
|
310
|
+
}
|
|
311
|
+
/** Directories that the Git root search checks, from cwd up to the workspace root. */
|
|
312
|
+
function gitRootCandidates(cwd) {
|
|
313
|
+
const candidates = [];
|
|
403
314
|
let current = cwd;
|
|
404
315
|
for (;;) {
|
|
405
|
-
|
|
406
|
-
if (current === SANDBOX_WORKSPACE_ROOT) return;
|
|
316
|
+
candidates.push(current);
|
|
317
|
+
if (current === SANDBOX_WORKSPACE_ROOT) return candidates;
|
|
407
318
|
const parent = path.posix.dirname(current);
|
|
408
|
-
if (parent === current || parent !== SANDBOX_WORKSPACE_ROOT && !parent.startsWith(`${SANDBOX_WORKSPACE_ROOT}/`)) return;
|
|
319
|
+
if (parent === current || parent !== SANDBOX_WORKSPACE_ROOT && !parent.startsWith(`${SANDBOX_WORKSPACE_ROOT}/`)) return candidates;
|
|
409
320
|
current = parent;
|
|
410
321
|
}
|
|
411
322
|
}
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
323
|
+
function findGitRoot(tree, cwd) {
|
|
324
|
+
return gitRootCandidates(cwd).find((directory) => tree.gitMarkers.has(path.posix.join(directory, ".git")));
|
|
325
|
+
}
|
|
326
|
+
function invalidOutput() {
|
|
327
|
+
return /* @__PURE__ */ new Error("Repository instructions read printed invalid output");
|
|
328
|
+
}
|
|
329
|
+
function parseRepositoryTree(stdout) {
|
|
330
|
+
const tree = {
|
|
331
|
+
entries: /* @__PURE__ */ new Map(),
|
|
332
|
+
files: /* @__PURE__ */ new Map(),
|
|
333
|
+
gitMarkers: /* @__PURE__ */ new Set(),
|
|
334
|
+
repositories: []
|
|
335
|
+
};
|
|
336
|
+
const lines = stdout.split("\n");
|
|
337
|
+
if (lines.pop() !== "") throw invalidOutput();
|
|
338
|
+
for (const line of lines) {
|
|
339
|
+
const kind = line.slice(0, 2);
|
|
340
|
+
let target = line.slice(2);
|
|
341
|
+
let content = "";
|
|
342
|
+
if (kind === "F ") {
|
|
343
|
+
const separator = target.indexOf(" ");
|
|
344
|
+
if (separator < 0) throw invalidOutput();
|
|
345
|
+
content = target.slice(0, separator);
|
|
346
|
+
target = target.slice(separator + 1);
|
|
347
|
+
if (!BASE64_PATTERN.test(content)) throw invalidOutput();
|
|
348
|
+
}
|
|
349
|
+
if (!target) throw invalidOutput();
|
|
350
|
+
const absolute = path.posix.join(SANDBOX_WORKSPACE_ROOT, target);
|
|
351
|
+
switch (kind) {
|
|
352
|
+
case "R ":
|
|
353
|
+
tree.repositories.push(absolute);
|
|
354
|
+
break;
|
|
355
|
+
case "G ":
|
|
356
|
+
tree.gitMarkers.add(absolute);
|
|
357
|
+
break;
|
|
358
|
+
case "D ":
|
|
359
|
+
case "E ": {
|
|
360
|
+
const root = path.posix.dirname(absolute);
|
|
361
|
+
const entries = tree.entries.get(root) ?? /* @__PURE__ */ new Map();
|
|
362
|
+
entries.set(path.posix.basename(absolute), kind === "D ");
|
|
363
|
+
tree.entries.set(root, entries);
|
|
364
|
+
break;
|
|
365
|
+
}
|
|
366
|
+
case "F ":
|
|
367
|
+
tree.files.set(absolute, Buffer.from(content, "base64").toString("utf8"));
|
|
368
|
+
break;
|
|
369
|
+
default: throw invalidOutput();
|
|
370
|
+
}
|
|
420
371
|
}
|
|
421
|
-
|
|
372
|
+
tree.repositories.sort(compareStrings);
|
|
373
|
+
return tree;
|
|
422
374
|
}
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
375
|
+
/** Read what the selected directories need with one sandbox command. */
|
|
376
|
+
async function readRepositoryTree(args) {
|
|
377
|
+
const relative = (target) => path.posix.relative(SANDBOX_WORKSPACE_ROOT, target) || ".";
|
|
378
|
+
const result = await args.runCommand({
|
|
379
|
+
cmd: "sh",
|
|
380
|
+
args: [
|
|
381
|
+
"-c",
|
|
382
|
+
READ_SCRIPT,
|
|
383
|
+
"sh",
|
|
384
|
+
String(FILE_READ_LIMIT_BYTES),
|
|
385
|
+
args.discover ? relative(SANDBOX_REPOS_ROOT) : "",
|
|
386
|
+
...args.directories.flatMap((directory) => [...gitRootCandidates(directory).map(relative), ""])
|
|
387
|
+
],
|
|
388
|
+
cwd: SANDBOX_WORKSPACE_ROOT
|
|
389
|
+
});
|
|
390
|
+
if (result.exitCode !== 0) throw new Error(`Repository instructions read failed with exit code ${result.exitCode}: ${result.stderr.trim()}`);
|
|
391
|
+
return parseRepositoryTree(result.stdout);
|
|
431
392
|
}
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
} catch (error) {
|
|
436
|
-
if (isMissingPathError(error)) return [];
|
|
437
|
-
throw error;
|
|
438
|
-
}
|
|
393
|
+
function readInstructionFile(tree, filePath) {
|
|
394
|
+
const content = tree.files.get(filePath);
|
|
395
|
+
return content?.trim() ? content : void 0;
|
|
439
396
|
}
|
|
440
397
|
/** Read model-invocable skills from the repository skill directories. */
|
|
441
|
-
|
|
442
|
-
const roots = REPOSITORY_SKILL_ROOTS.map((root) => path.posix.join(gitRoot, root));
|
|
443
|
-
const listings = await Promise.all(roots.map(async (root) => await readOptionalDirectory(fs, root)));
|
|
398
|
+
function readRepositorySkills(tree, gitRoot) {
|
|
444
399
|
const candidates = /* @__PURE__ */ new Map();
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
400
|
+
for (const root of REPOSITORY_SKILL_ROOTS) {
|
|
401
|
+
const rootPath = path.posix.join(gitRoot, root);
|
|
402
|
+
const entries = [...tree.entries.get(rootPath) ?? []].sort(([left], [right]) => compareStrings(left, right));
|
|
403
|
+
for (const [name, directory] of entries) if (!candidates.has(name)) candidates.set(name, {
|
|
404
|
+
directory,
|
|
405
|
+
path: path.posix.join(rootPath, name)
|
|
406
|
+
});
|
|
407
|
+
}
|
|
408
|
+
const skills = [];
|
|
409
|
+
for (const [name, candidate] of candidates) {
|
|
410
|
+
if (!candidate.directory) continue;
|
|
411
|
+
const filePath = path.posix.join(candidate.path, "SKILL.md");
|
|
412
|
+
const raw = readInstructionFile(tree, filePath);
|
|
452
413
|
const parsed = raw ? parseSkillFile(raw, name) : void 0;
|
|
453
|
-
if (!parsed?.ok || parsed.skill.disableModelInvocation)
|
|
454
|
-
|
|
414
|
+
if (!parsed?.ok || parsed.skill.disableModelInvocation) continue;
|
|
415
|
+
skills.push({
|
|
455
416
|
description: parsed.skill.description.replace(/\s+/g, " ").trim(),
|
|
456
417
|
name,
|
|
457
418
|
path: filePath
|
|
458
|
-
};
|
|
459
|
-
}
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
return skills.sort((left, right) => compareStrings(left.name, right.name));
|
|
460
422
|
}
|
|
461
423
|
function sourceBytes(sources) {
|
|
462
424
|
return sources.reduce((total, source) => total + Buffer.byteLength(source.content, "utf8"), 0);
|
|
@@ -465,7 +427,7 @@ function skillListBytes(skills) {
|
|
|
465
427
|
return skills.reduce((total, skill) => total + repositorySkillBytes(skill), 0);
|
|
466
428
|
}
|
|
467
429
|
/** Read root-to-cwd AGENTS.md files within the byte budget. */
|
|
468
|
-
|
|
430
|
+
function readAgentsSources(args) {
|
|
469
431
|
const directories = [];
|
|
470
432
|
let current = args.cwd;
|
|
471
433
|
for (;;) {
|
|
@@ -479,7 +441,7 @@ async function readAgentsSources(args) {
|
|
|
479
441
|
for (const directory of directories) {
|
|
480
442
|
if (remaining <= 0) break;
|
|
481
443
|
const filePath = path.posix.join(directory, AGENTS_FILENAME);
|
|
482
|
-
const content =
|
|
444
|
+
const content = readInstructionFile(args.tree, filePath);
|
|
483
445
|
if (!content) continue;
|
|
484
446
|
const bytes = Buffer.from(content, "utf8");
|
|
485
447
|
const bounded = bytes.length <= remaining ? content : bytes.subarray(0, remaining).toString("utf8");
|
|
@@ -492,11 +454,11 @@ async function readAgentsSources(args) {
|
|
|
492
454
|
return sources;
|
|
493
455
|
}
|
|
494
456
|
/** Read repository skills that fit the byte budget, keeping each entry whole. */
|
|
495
|
-
|
|
457
|
+
function readRepositorySkillsWithinBudget(args) {
|
|
496
458
|
const skills = [];
|
|
497
459
|
let remaining = args.maxBytes;
|
|
498
460
|
if (remaining <= 0) return skills;
|
|
499
|
-
for (const skill of
|
|
461
|
+
for (const skill of readRepositorySkills(args.tree, args.gitRoot)) {
|
|
500
462
|
const bytes = repositorySkillBytes(skill);
|
|
501
463
|
if (bytes > remaining) break;
|
|
502
464
|
skills.push(skill);
|
|
@@ -556,19 +518,33 @@ function mergeRepositoryInstructions(bundles) {
|
|
|
556
518
|
text
|
|
557
519
|
};
|
|
558
520
|
}
|
|
559
|
-
/**
|
|
560
|
-
|
|
561
|
-
|
|
521
|
+
/**
|
|
522
|
+
* Read AGENTS.md instructions and repository skills for the selected
|
|
523
|
+
* directories with one sandbox command. Without directories, use every Git
|
|
524
|
+
* worktree under repos/.
|
|
525
|
+
*/
|
|
526
|
+
async function readRepositoryInstructions(args) {
|
|
527
|
+
const selected = [...new Set((args.directories ?? []).filter((directory) => directory === SANDBOX_WORKSPACE_ROOT || directory.startsWith(`${SANDBOX_WORKSPACE_ROOT}/`)))].sort(compareStrings);
|
|
528
|
+
if (args.directories && selected.length === 0) return {
|
|
529
|
+
directories: args.directories,
|
|
530
|
+
instructions: void 0
|
|
531
|
+
};
|
|
532
|
+
const tree = await readRepositoryTree({
|
|
533
|
+
directories: selected,
|
|
534
|
+
discover: !args.directories,
|
|
535
|
+
runCommand: args.runCommand
|
|
536
|
+
});
|
|
537
|
+
const cwds = args.directories ? selected : tree.repositories;
|
|
562
538
|
let remaining = MAX_REPOSITORY_INSTRUCTIONS_BYTES;
|
|
563
539
|
const repositories = [];
|
|
564
|
-
for (const directory of
|
|
565
|
-
const gitRoot =
|
|
540
|
+
for (const directory of cwds) {
|
|
541
|
+
const gitRoot = findGitRoot(tree, directory);
|
|
566
542
|
if (!gitRoot) continue;
|
|
567
|
-
const sources =
|
|
543
|
+
const sources = readAgentsSources({
|
|
568
544
|
cwd: directory,
|
|
569
|
-
fs: args.fs,
|
|
570
545
|
gitRoot,
|
|
571
|
-
maxBytes: remaining
|
|
546
|
+
maxBytes: remaining,
|
|
547
|
+
tree
|
|
572
548
|
});
|
|
573
549
|
remaining -= sourceBytes(sources);
|
|
574
550
|
repositories.push({
|
|
@@ -579,16 +555,19 @@ async function resolveRepositoryInstructionsForDirectories(args) {
|
|
|
579
555
|
}
|
|
580
556
|
const bundles = [];
|
|
581
557
|
for (const repository of repositories) {
|
|
582
|
-
const skills =
|
|
583
|
-
fs: args.fs,
|
|
558
|
+
const skills = readRepositorySkillsWithinBudget({
|
|
584
559
|
gitRoot: repository.gitRoot,
|
|
585
|
-
maxBytes: remaining
|
|
560
|
+
maxBytes: remaining,
|
|
561
|
+
tree
|
|
586
562
|
});
|
|
587
563
|
remaining -= skillListBytes(skills);
|
|
588
564
|
const bundle = buildRepositoryInstructions(repository.directory, repository.sources, skills);
|
|
589
565
|
if (bundle) bundles.push(bundle);
|
|
590
566
|
}
|
|
591
|
-
return
|
|
567
|
+
return {
|
|
568
|
+
directories: args.directories ?? cwds,
|
|
569
|
+
instructions: mergeRepositoryInstructions(bundles)
|
|
570
|
+
};
|
|
592
571
|
}
|
|
593
572
|
/** Render repository instructions with Codex's exact model-visible wrapper. */
|
|
594
573
|
function renderAgentsInstructions(args) {
|
|
@@ -725,6 +704,7 @@ function buildChatEndAttributes(message, mode) {
|
|
|
725
704
|
Object.assign(attributes, extractGenAiUsageAttributes(message));
|
|
726
705
|
if (message.stopReason) attributes["gen_ai.response.finish_reasons"] = [normalizeGenAiFinishReason(message.stopReason)];
|
|
727
706
|
if (message.model) attributes["gen_ai.response.model"] = message.model;
|
|
707
|
+
if (message.responseId) attributes["gen_ai.response.id"] = message.responseId;
|
|
728
708
|
if (message.stopReason === "error") {
|
|
729
709
|
const providerError = createProviderError(message.errorMessage ?? "");
|
|
730
710
|
Object.assign(attributes, getProviderErrorAttributes(providerError));
|
|
@@ -761,6 +741,22 @@ function createResponseTiming(requestStartedAtMs) {
|
|
|
761
741
|
}
|
|
762
742
|
};
|
|
763
743
|
}
|
|
744
|
+
function traceResponseHeaders(span, options) {
|
|
745
|
+
const eventLoopStart = performance$1.eventLoopUtilization();
|
|
746
|
+
const onResponse = options?.onResponse;
|
|
747
|
+
return {
|
|
748
|
+
...options,
|
|
749
|
+
onResponse: async (response, model) => {
|
|
750
|
+
try {
|
|
751
|
+
const vercelId = response.headers["x-vercel-id"];
|
|
752
|
+
if (vercelId) span.setAttribute("app.ai.gateway.vercel_id", vercelId);
|
|
753
|
+
const { utilization } = performance$1.eventLoopUtilization(eventLoopStart);
|
|
754
|
+
span.setAttribute("app.ai.event_loop.utilization", Math.round(utilization * 1e3) / 1e3);
|
|
755
|
+
} catch {}
|
|
756
|
+
await onResponse?.(response, model);
|
|
757
|
+
}
|
|
758
|
+
};
|
|
759
|
+
}
|
|
764
760
|
function relayStream(source, onEvent) {
|
|
765
761
|
const relayed = createAssistantMessageEventStream();
|
|
766
762
|
const finished = (async () => {
|
|
@@ -801,7 +797,7 @@ function createTracedStreamFn(baseOrOptions = streamSimple) {
|
|
|
801
797
|
});
|
|
802
798
|
try {
|
|
803
799
|
const requestStartedAtMs = Date.now();
|
|
804
|
-
const stream = await withActiveSpan(span, () => Promise.resolve(base(model, context, options)));
|
|
800
|
+
const stream = await withActiveSpan(span, () => Promise.resolve(base(model, context, traceResponseHeaders(span, options))));
|
|
805
801
|
const responseTiming = createResponseTiming(requestStartedAtMs);
|
|
806
802
|
const relay = relayStream(stream, responseTiming.observe);
|
|
807
803
|
relay.finished.then(() => stream.result()).then((finalMessage) => {
|
|
@@ -3961,9 +3957,10 @@ function createSandboxRuntime(options) {
|
|
|
3961
3957
|
withSpan: withSandboxSpan
|
|
3962
3958
|
});
|
|
3963
3959
|
};
|
|
3960
|
+
const ensureDocker = async (targetSandbox) => await withSandboxSpan("sandbox.docker.ensure", "sandbox.docker.ensure", {}, async () => await ensureDockerDaemon(targetSandbox));
|
|
3964
3961
|
const prepareSandbox = async (targetSandbox) => {
|
|
3965
3962
|
await syncSkills(targetSandbox);
|
|
3966
|
-
await
|
|
3963
|
+
await ensureDocker(targetSandbox);
|
|
3967
3964
|
await options.onSandboxPrepare?.(targetSandbox);
|
|
3968
3965
|
};
|
|
3969
3966
|
const applyNetworkPolicy = async (targetSandbox, traceHeaders) => {
|
|
@@ -4187,10 +4184,17 @@ function createSandboxRuntime(options) {
|
|
|
4187
4184
|
}
|
|
4188
4185
|
throw new Error("sandbox restore failed", { cause: error });
|
|
4189
4186
|
}
|
|
4190
|
-
let networkPolicyKey;
|
|
4191
4187
|
try {
|
|
4192
|
-
|
|
4193
|
-
|
|
4188
|
+
const steps = await Promise.allSettled([
|
|
4189
|
+
applyNetworkPolicy(hintedSandbox),
|
|
4190
|
+
syncSkills(hintedSandbox),
|
|
4191
|
+
ensureDocker(hintedSandbox)
|
|
4192
|
+
]);
|
|
4193
|
+
const failures = steps.flatMap((step) => step.status === "rejected" ? [step.reason] : []);
|
|
4194
|
+
if (failures.length > 0) throw failures.find((error) => getSandboxProvider().errors.isUnavailable(error)) ?? failures[0];
|
|
4195
|
+
const [policy] = steps;
|
|
4196
|
+
const networkPolicyKey = policy.status === "fulfilled" ? policy.value : void 0;
|
|
4197
|
+
await options.onSandboxPrepare?.(hintedSandbox);
|
|
4194
4198
|
dependencyProfileHash = ref.profileHash ?? dependencyProfileHash;
|
|
4195
4199
|
await persistSandboxRef({
|
|
4196
4200
|
...ref,
|
|
@@ -4212,17 +4216,26 @@ function createSandboxRuntime(options) {
|
|
|
4212
4216
|
const cachedSandbox = await tryReuseCachedSandbox();
|
|
4213
4217
|
if (cachedSandbox) {
|
|
4214
4218
|
setSpanAttributes({ "app.sandbox.acquire.outcome": "memory" });
|
|
4215
|
-
return
|
|
4219
|
+
return {
|
|
4220
|
+
session: cachedSandbox,
|
|
4221
|
+
fresh: false
|
|
4222
|
+
};
|
|
4216
4223
|
}
|
|
4217
4224
|
signal?.throwIfAborted();
|
|
4218
4225
|
const hintedSandbox = await tryRestoreHintedSandbox(signal);
|
|
4219
4226
|
if (hintedSandbox) {
|
|
4220
4227
|
setSpanAttributes({ "app.sandbox.acquire.outcome": "resumed" });
|
|
4221
|
-
return
|
|
4228
|
+
return {
|
|
4229
|
+
session: hintedSandbox,
|
|
4230
|
+
fresh: true
|
|
4231
|
+
};
|
|
4222
4232
|
}
|
|
4223
4233
|
const createdSandbox = await createFreshSandbox(signal);
|
|
4224
4234
|
setSpanAttributes({ "app.sandbox.acquire.outcome": "created" });
|
|
4225
|
-
return
|
|
4235
|
+
return {
|
|
4236
|
+
session: createdSandbox,
|
|
4237
|
+
fresh: true
|
|
4238
|
+
};
|
|
4226
4239
|
});
|
|
4227
4240
|
};
|
|
4228
4241
|
const getOrAcquireSandbox = async (signal) => {
|
|
@@ -4378,10 +4391,12 @@ function createSandboxRuntime(options) {
|
|
|
4378
4391
|
};
|
|
4379
4392
|
};
|
|
4380
4393
|
const ensureReadySandbox = async (signal) => {
|
|
4381
|
-
const session = await getOrAcquireSandbox(signal);
|
|
4382
|
-
signal?.throwIfAborted();
|
|
4383
|
-
await probeSession(session);
|
|
4394
|
+
const { session, fresh } = await getOrAcquireSandbox(signal);
|
|
4384
4395
|
signal?.throwIfAborted();
|
|
4396
|
+
if (!fresh) {
|
|
4397
|
+
await probeSession(session);
|
|
4398
|
+
signal?.throwIfAborted();
|
|
4399
|
+
}
|
|
4385
4400
|
await extendKeepAlive(session);
|
|
4386
4401
|
startKeepAlive(session);
|
|
4387
4402
|
return session;
|
|
@@ -4428,7 +4443,7 @@ function createSandboxRuntime(options) {
|
|
|
4428
4443
|
await stopSession(previous?.session);
|
|
4429
4444
|
},
|
|
4430
4445
|
async acquire(signal) {
|
|
4431
|
-
return await getOrAcquireSandbox(signal);
|
|
4446
|
+
return (await getOrAcquireSandbox(signal)).session;
|
|
4432
4447
|
},
|
|
4433
4448
|
async tools(signal) {
|
|
4434
4449
|
return createToolExecutors(await ensureReadySandbox(signal));
|
|
@@ -4447,6 +4462,172 @@ function createSandboxRuntime(options) {
|
|
|
4447
4462
|
}
|
|
4448
4463
|
};
|
|
4449
4464
|
}
|
|
4465
|
+
// src/chat/tools/sandbox/file-utils.ts
|
|
4466
|
+
const MAX_TEXT_CHARS = 6e4;
|
|
4467
|
+
const RIPGREP_EXCLUDED_GLOBS = ["!**/.git/**", "!**/node_modules/**"];
|
|
4468
|
+
const DEFAULT_SEARCH_COMMAND_TIMEOUT_MS = 3e4;
|
|
4469
|
+
const SKIPPED_DIRECTORIES = /* @__PURE__ */ new Set([".git", "node_modules"]);
|
|
4470
|
+
/** Normalize model-supplied numeric knobs before they reach filesystem tools. */
|
|
4471
|
+
function positiveInteger$1(value) {
|
|
4472
|
+
if (typeof value !== "number" || !Number.isFinite(value)) return;
|
|
4473
|
+
const integer = Math.floor(value);
|
|
4474
|
+
return integer > 0 ? integer : void 0;
|
|
4475
|
+
}
|
|
4476
|
+
/** Compare and slice text in one line-ending space while preserving callers' output rules. */
|
|
4477
|
+
function normalizeToLf$1(value) {
|
|
4478
|
+
return value.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
4479
|
+
}
|
|
4480
|
+
/** Keep tool output inside the model-facing budget with an explicit notice. */
|
|
4481
|
+
function truncateText$1(value, maxChars = MAX_TEXT_CHARS) {
|
|
4482
|
+
if (value.length <= maxChars) return {
|
|
4483
|
+
content: value,
|
|
4484
|
+
truncated: false
|
|
4485
|
+
};
|
|
4486
|
+
const removed = value.length - maxChars;
|
|
4487
|
+
return {
|
|
4488
|
+
content: `${value.slice(0, maxChars)}\n\n[output truncated: ${removed} characters removed]`,
|
|
4489
|
+
truncated: true
|
|
4490
|
+
};
|
|
4491
|
+
}
|
|
4492
|
+
/** Detect model-facing missing paths without swallowing sandbox lifecycle/API failures. */
|
|
4493
|
+
function isMissingPathError(error) {
|
|
4494
|
+
if (!error || typeof error !== "object") return false;
|
|
4495
|
+
const candidate = error;
|
|
4496
|
+
if (candidate.code === "ENOENT") return true;
|
|
4497
|
+
return typeof candidate.message === "string" && candidate.message.startsWith("File not found:");
|
|
4498
|
+
}
|
|
4499
|
+
/** Reject an expected missing search/list path through the tool-error channel. */
|
|
4500
|
+
function missingPathSearchResult(params) {
|
|
4501
|
+
const textPath = params.displayPath ?? params.missingPath ?? params.path;
|
|
4502
|
+
throw new ToolInputError(`Path not found: ${textPath}`);
|
|
4503
|
+
}
|
|
4504
|
+
function escapeRegExp(value) {
|
|
4505
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
4506
|
+
}
|
|
4507
|
+
function globToRegExp(pattern) {
|
|
4508
|
+
let source = "";
|
|
4509
|
+
for (let index = 0; index < pattern.length; index += 1) {
|
|
4510
|
+
const char = pattern.charAt(index);
|
|
4511
|
+
const next = pattern[index + 1];
|
|
4512
|
+
if (char === "*" && next === "*") {
|
|
4513
|
+
if (pattern[index + 2] === "/") {
|
|
4514
|
+
source += "(?:.*/)?";
|
|
4515
|
+
index += 2;
|
|
4516
|
+
continue;
|
|
4517
|
+
}
|
|
4518
|
+
source += ".*";
|
|
4519
|
+
index += 1;
|
|
4520
|
+
continue;
|
|
4521
|
+
}
|
|
4522
|
+
if (char === "*") {
|
|
4523
|
+
source += "[^/]*";
|
|
4524
|
+
continue;
|
|
4525
|
+
}
|
|
4526
|
+
if (char === "?") {
|
|
4527
|
+
source += "[^/]";
|
|
4528
|
+
continue;
|
|
4529
|
+
}
|
|
4530
|
+
source += escapeRegExp(char);
|
|
4531
|
+
}
|
|
4532
|
+
return new RegExp(`^${source}$`);
|
|
4533
|
+
}
|
|
4534
|
+
function matchesGlob(relativePath, pattern) {
|
|
4535
|
+
const matcher = globToRegExp(pattern);
|
|
4536
|
+
if (matcher.test(relativePath)) return true;
|
|
4537
|
+
if (pattern.startsWith("**/") && matchesGlob(relativePath, pattern.slice(3))) return true;
|
|
4538
|
+
return !pattern.includes("/") && matcher.test(path.posix.basename(relativePath));
|
|
4539
|
+
}
|
|
4540
|
+
/** Keep sandbox filesystem tools scoped to the mounted workspace root. */
|
|
4541
|
+
function resolveWorkspacePath(input, fallback = ".") {
|
|
4542
|
+
const requested = (input ?? "").trim() || fallback;
|
|
4543
|
+
const absolute = requested.startsWith("/") ? requested : path.posix.join(SANDBOX_WORKSPACE_ROOT, requested);
|
|
4544
|
+
const normalized = path.posix.normalize(absolute);
|
|
4545
|
+
if (normalized !== SANDBOX_WORKSPACE_ROOT && !normalized.startsWith(`${SANDBOX_WORKSPACE_ROOT}/`)) throw new ToolInputError(`Path must stay within ${SANDBOX_WORKSPACE_ROOT}: ${requested}`);
|
|
4546
|
+
return normalized;
|
|
4547
|
+
}
|
|
4548
|
+
/** Anchor ripgrep paths and globs to the requested search root. */
|
|
4549
|
+
function getRipgrepSearchLocation(root, rootIsDirectory) {
|
|
4550
|
+
if (rootIsDirectory) return {
|
|
4551
|
+
cwd: root,
|
|
4552
|
+
target: "."
|
|
4553
|
+
};
|
|
4554
|
+
return {
|
|
4555
|
+
cwd: path.posix.dirname(root),
|
|
4556
|
+
target: path.posix.basename(root)
|
|
4557
|
+
};
|
|
4558
|
+
}
|
|
4559
|
+
/** Share bounded workspace traversal across search tools so their skip rules stay aligned. */
|
|
4560
|
+
async function collectFiles(params) {
|
|
4561
|
+
const files = [];
|
|
4562
|
+
let limitReached = false;
|
|
4563
|
+
let missingPath;
|
|
4564
|
+
const visit = async (dirPath) => {
|
|
4565
|
+
if (missingPath) return;
|
|
4566
|
+
let entries;
|
|
4567
|
+
try {
|
|
4568
|
+
entries = (await params.fs.readdir(dirPath)).sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
|
|
4569
|
+
} catch (error) {
|
|
4570
|
+
if (isMissingPathError(error)) {
|
|
4571
|
+
missingPath = dirPath;
|
|
4572
|
+
return;
|
|
4573
|
+
}
|
|
4574
|
+
throw error;
|
|
4575
|
+
}
|
|
4576
|
+
for (const entry of entries) {
|
|
4577
|
+
const fullPath = path.posix.join(dirPath, entry);
|
|
4578
|
+
let stat;
|
|
4579
|
+
try {
|
|
4580
|
+
stat = await params.fs.stat(fullPath);
|
|
4581
|
+
} catch (error) {
|
|
4582
|
+
if (isMissingPathError(error)) {
|
|
4583
|
+
missingPath = fullPath;
|
|
4584
|
+
return;
|
|
4585
|
+
}
|
|
4586
|
+
throw error;
|
|
4587
|
+
}
|
|
4588
|
+
if (stat.isDirectory()) {
|
|
4589
|
+
if (!SKIPPED_DIRECTORIES.has(entry)) await visit(fullPath);
|
|
4590
|
+
if (limitReached) return;
|
|
4591
|
+
continue;
|
|
4592
|
+
}
|
|
4593
|
+
const relativePath = path.posix.relative(params.root, fullPath);
|
|
4594
|
+
if (!params.pattern || matchesGlob(relativePath, params.pattern)) {
|
|
4595
|
+
files.push(fullPath);
|
|
4596
|
+
if (params.limit && files.length >= params.limit) {
|
|
4597
|
+
limitReached = true;
|
|
4598
|
+
return;
|
|
4599
|
+
}
|
|
4600
|
+
}
|
|
4601
|
+
}
|
|
4602
|
+
};
|
|
4603
|
+
let stat;
|
|
4604
|
+
try {
|
|
4605
|
+
stat = await params.fs.stat(params.root);
|
|
4606
|
+
} catch (error) {
|
|
4607
|
+
if (isMissingPathError(error)) return {
|
|
4608
|
+
files,
|
|
4609
|
+
limitReached: false,
|
|
4610
|
+
missingPath: params.root,
|
|
4611
|
+
missingRoot: true
|
|
4612
|
+
};
|
|
4613
|
+
throw error;
|
|
4614
|
+
}
|
|
4615
|
+
if (!stat.isDirectory()) {
|
|
4616
|
+
const relativePath = path.posix.basename(params.root);
|
|
4617
|
+
return {
|
|
4618
|
+
files: !params.pattern || matchesGlob(relativePath, params.pattern) ? [params.root] : [],
|
|
4619
|
+
limitReached: false,
|
|
4620
|
+
missingRoot: false
|
|
4621
|
+
};
|
|
4622
|
+
}
|
|
4623
|
+
await visit(params.root);
|
|
4624
|
+
return {
|
|
4625
|
+
files,
|
|
4626
|
+
limitReached,
|
|
4627
|
+
missingPath,
|
|
4628
|
+
missingRoot: missingPath === params.root
|
|
4629
|
+
};
|
|
4630
|
+
}
|
|
4450
4631
|
// src/chat/tools/sandbox/text-edits.ts
|
|
4451
4632
|
const MAX_DIFF_LINE_CHARS = 4e3;
|
|
4452
4633
|
/** Preserve a text artifact's dominant line-ending style across rewrites. */
|
|
@@ -5706,13 +5887,12 @@ function createSandbox(options) {
|
|
|
5706
5887
|
return {
|
|
5707
5888
|
async captureRepositoryInstructions() {
|
|
5708
5889
|
if (!runtime.sandboxRef()) return;
|
|
5709
|
-
const {
|
|
5890
|
+
const { runCommand } = await runtime.tools();
|
|
5710
5891
|
const workspaceDirectories = activeWorkspace?.repos.map((repo) => tryWorkspaceRepoCheckoutPath(repo.repo)).filter((checkoutPath) => Boolean(checkoutPath)).map((checkoutPath) => `${SANDBOX_WORKSPACE_ROOT}/${checkoutPath}`) ?? [];
|
|
5711
5892
|
return await withSandboxSpan("sandbox.repository_instructions.read", "sandbox.repository_instructions.read", {}, async (setSpanAttributes) => {
|
|
5712
|
-
const directories
|
|
5713
|
-
|
|
5714
|
-
|
|
5715
|
-
fs
|
|
5893
|
+
const { directories, instructions } = await readRepositoryInstructions({
|
|
5894
|
+
...workspaceDirectories.length > 0 ? { directories: workspaceDirectories } : void 0,
|
|
5895
|
+
runCommand
|
|
5716
5896
|
});
|
|
5717
5897
|
setSpanAttributes({
|
|
5718
5898
|
"app.repository_instructions.repo_count": directories.length,
|
|
@@ -8491,8 +8671,8 @@ const REVIEW_DESK_TOOL_SOURCE = {
|
|
|
8491
8671
|
id: "review-desk",
|
|
8492
8672
|
description: "Update and search Review items: work on the review desk that needs a person."
|
|
8493
8673
|
};
|
|
8494
|
-
const DEFAULT_LIMIT$
|
|
8495
|
-
const MAX_LIMIT$
|
|
8674
|
+
const DEFAULT_LIMIT$5 = 10;
|
|
8675
|
+
const MAX_LIMIT$4 = 25;
|
|
8496
8676
|
const assigneesSchema = z.array(z.string().trim().min(1).max(320)).min(1).max(20).describe("Who can act on the item. Each entry is `everyone`, an email, or a mention such as `<@U123>`. Everyone means any person who can see the item.");
|
|
8497
8677
|
const subjectSchema = z.object({
|
|
8498
8678
|
id: z.string().trim().min(1).max(500).describe("Stable id of the thing the item is about, such as a pull request URL. Search matches it exactly."),
|
|
@@ -8794,7 +8974,7 @@ function createSearchReviewItemsTool(context, services) {
|
|
|
8794
8974
|
assignee: z.string().trim().min(1).max(320).nullable().optional().describe("`everyone`, an email, or a mention such as `<@U123>`."),
|
|
8795
8975
|
automation_id: z.string().trim().min(1).nullable().optional(),
|
|
8796
8976
|
conversation_id: z.string().trim().min(1).nullable().optional(),
|
|
8797
|
-
limit: z.number().int().min(1).max(MAX_LIMIT$
|
|
8977
|
+
limit: z.number().int().min(1).max(MAX_LIMIT$4).nullable().optional().describe(`Default ${DEFAULT_LIMIT$5}; max ${MAX_LIMIT$4}.`)
|
|
8798
8978
|
}).strict(),
|
|
8799
8979
|
outputSchema: juniorToolOutputSchema,
|
|
8800
8980
|
execute: async (input) => {
|
|
@@ -8807,7 +8987,7 @@ function createSearchReviewItemsTool(context, services) {
|
|
|
8807
8987
|
"dismissed"
|
|
8808
8988
|
] : [status];
|
|
8809
8989
|
const items = await searchReviewItems(db, scope.reader, {
|
|
8810
|
-
limit: input.limit ?? DEFAULT_LIMIT$
|
|
8990
|
+
limit: input.limit ?? DEFAULT_LIMIT$5,
|
|
8811
8991
|
statuses,
|
|
8812
8992
|
...input.assignee ? { assignee: await resolveAssignee(db, input.assignee, scope.tenant, services.findMentionedUserId) } : void 0,
|
|
8813
8993
|
...input.automation_id ? { automationId: input.automation_id } : void 0,
|
|
@@ -11810,11 +11990,11 @@ function createSlackConversationBriefSearchPort(teamId) {
|
|
|
11810
11990
|
/** Deferred tool catalog source for retained Junior conversations. */
|
|
11811
11991
|
const CONVERSATIONS_TOOL_SOURCE = {
|
|
11812
11992
|
id: "conversations",
|
|
11813
|
-
description: "Search messages and events in retained conversations."
|
|
11993
|
+
description: "Search and read messages and events in retained conversations."
|
|
11814
11994
|
};
|
|
11815
11995
|
// src/chat/slack/tools/conversation-message-search.ts
|
|
11816
|
-
const DEFAULT_LIMIT$
|
|
11817
|
-
const MAX_LIMIT$
|
|
11996
|
+
const DEFAULT_LIMIT$4 = 20;
|
|
11997
|
+
const MAX_LIMIT$3 = 50;
|
|
11818
11998
|
const conversationMessageSearchOutputSchema = juniorToolOutputSchema.extend({
|
|
11819
11999
|
after: z.string().datetime().optional(),
|
|
11820
12000
|
annotation: z.string().min(1).optional(),
|
|
@@ -11879,7 +12059,7 @@ function createSlackConversationMessageSearchTool(scope, currentConversationId)
|
|
|
11879
12059
|
before: z.string().datetime().nullable().describe("Include conversations active before this timestamp.").optional(),
|
|
11880
12060
|
channel_id: slackChannelRefParam.nullable().optional(),
|
|
11881
12061
|
query: z.string().trim().min(1).max(200).nullable().describe("Words or phrase to match in message text.").optional(),
|
|
11882
|
-
limit: z.number().int().min(1).max(MAX_LIMIT$
|
|
12062
|
+
limit: z.number().int().min(1).max(MAX_LIMIT$3).describe(`Maximum conversations. Default ${DEFAULT_LIMIT$4}; max ${MAX_LIMIT$3}.`).nullable().optional()
|
|
11883
12063
|
}).strict(),
|
|
11884
12064
|
outputSchema: conversationMessageSearchOutputSchema,
|
|
11885
12065
|
execute: async (input) => {
|
|
@@ -11892,7 +12072,7 @@ function createSlackConversationMessageSearchTool(scope, currentConversationId)
|
|
|
11892
12072
|
const matches = await getConversationMessageSearchStore().search({
|
|
11893
12073
|
currentConversationId,
|
|
11894
12074
|
filters,
|
|
11895
|
-
limit: input.limit ?? DEFAULT_LIMIT$
|
|
12075
|
+
limit: input.limit ?? DEFAULT_LIMIT$4,
|
|
11896
12076
|
scope
|
|
11897
12077
|
});
|
|
11898
12078
|
const matchesOutput = await Promise.all(matches.map(async (match) => {
|
|
@@ -11927,7 +12107,7 @@ function createSlackConversationMessageSearchTool(scope, currentConversationId)
|
|
|
11927
12107
|
});
|
|
11928
12108
|
}
|
|
11929
12109
|
// src/chat/slack/tools/public-search.ts
|
|
11930
|
-
const DEFAULT_LIMIT$
|
|
12110
|
+
const DEFAULT_LIMIT$3 = 10;
|
|
11931
12111
|
const DEFAULT_CONTENT_TYPES = ["messages"];
|
|
11932
12112
|
const CONTENT_TYPES = [
|
|
11933
12113
|
"messages",
|
|
@@ -12190,7 +12370,7 @@ function createSlackPublicSearchTool(actionToken) {
|
|
|
12190
12370
|
channel_types: ["public_channel"],
|
|
12191
12371
|
content_types: normalizedContentTypes,
|
|
12192
12372
|
include_bots: true,
|
|
12193
|
-
limit: limit ?? DEFAULT_LIMIT$
|
|
12373
|
+
limit: limit ?? DEFAULT_LIMIT$3,
|
|
12194
12374
|
...normalizedAfter !== void 0 ? { after: normalizedAfter } : void 0,
|
|
12195
12375
|
...normalizedBefore !== void 0 ? { before: normalizedBefore } : void 0,
|
|
12196
12376
|
...cursor ? { cursor } : void 0,
|
|
@@ -14916,6 +15096,198 @@ function createLoadAttachmentTool(args) {
|
|
|
14916
15096
|
}
|
|
14917
15097
|
});
|
|
14918
15098
|
}
|
|
15099
|
+
// src/chat/conversations/event-access.ts
|
|
15100
|
+
/**
|
|
15101
|
+
* Read access to a Conversation's durable event log for model-facing tools.
|
|
15102
|
+
* The current Conversation tree is always readable. Other Conversations are
|
|
15103
|
+
* readable only when they are public and in the same Slack workspace.
|
|
15104
|
+
*/
|
|
15105
|
+
/**
|
|
15106
|
+
* Throw a repairable tool error unless the active context may read the event
|
|
15107
|
+
* log of `conversationId`.
|
|
15108
|
+
*/
|
|
15109
|
+
async function assertCanReadConversationEvents(context, conversationId) {
|
|
15110
|
+
const conversationStore = getConversationStore();
|
|
15111
|
+
const target = await conversationStore.get({ conversationId });
|
|
15112
|
+
if (!target) throw new ToolInputError(`Conversation not found: ${conversationId}`);
|
|
15113
|
+
if (target.transcriptPurgedAtMs !== void 0) throw new ToolInputError(`Conversation transcript was purged: ${conversationId}`);
|
|
15114
|
+
const accessScope = await resolveAccessScope(conversationStore, context, context.conversationId);
|
|
15115
|
+
const targetRootConversationId = await resolveRootConversationId(conversationStore, conversationId, target.parentConversationId);
|
|
15116
|
+
const targetRoot = targetRootConversationId === conversationId ? target : await conversationStore.get({ conversationId: targetRootConversationId });
|
|
15117
|
+
assertScopeCanReadTarget({
|
|
15118
|
+
accessScope,
|
|
15119
|
+
targetConversationId: conversationId,
|
|
15120
|
+
targetRootConversationId,
|
|
15121
|
+
targetVisibility: targetRoot?.visibility ?? target.visibility,
|
|
15122
|
+
targetDestination: targetRoot?.destination ?? target.destination
|
|
15123
|
+
});
|
|
15124
|
+
}
|
|
15125
|
+
async function resolveAccessScope(conversationStore, context, currentConversationId) {
|
|
15126
|
+
const current = await conversationStore.get({ conversationId: currentConversationId });
|
|
15127
|
+
const currentRootConversationId = current ? await resolveRootConversationId(conversationStore, currentConversationId, current.parentConversationId) : currentConversationId;
|
|
15128
|
+
if (context.location?.provider === "slack") return {
|
|
15129
|
+
currentConversationId,
|
|
15130
|
+
currentRootConversationId,
|
|
15131
|
+
provider: "slack",
|
|
15132
|
+
providerTenantId: context.location.teamId
|
|
15133
|
+
};
|
|
15134
|
+
if (context.source.kind === "slack") return {
|
|
15135
|
+
currentConversationId,
|
|
15136
|
+
currentRootConversationId,
|
|
15137
|
+
provider: "slack",
|
|
15138
|
+
providerTenantId: context.source.teamId
|
|
15139
|
+
};
|
|
15140
|
+
if (context.destination.platform === "slack" && "teamId" in context.destination) return {
|
|
15141
|
+
currentConversationId,
|
|
15142
|
+
currentRootConversationId,
|
|
15143
|
+
provider: "slack",
|
|
15144
|
+
providerTenantId: context.destination.teamId
|
|
15145
|
+
};
|
|
15146
|
+
return {
|
|
15147
|
+
currentConversationId,
|
|
15148
|
+
currentRootConversationId
|
|
15149
|
+
};
|
|
15150
|
+
}
|
|
15151
|
+
async function resolveRootConversationId(conversationStore, conversationId, parentConversationId) {
|
|
15152
|
+
if (!parentConversationId) return conversationId;
|
|
15153
|
+
let cursor = parentConversationId;
|
|
15154
|
+
const seen = /* @__PURE__ */ new Set([conversationId]);
|
|
15155
|
+
while (cursor) {
|
|
15156
|
+
if (seen.has(cursor)) return conversationId;
|
|
15157
|
+
seen.add(cursor);
|
|
15158
|
+
const parent = await conversationStore.get({ conversationId: cursor });
|
|
15159
|
+
if (!parent) return conversationId;
|
|
15160
|
+
if (!parent.parentConversationId) return parent.conversationId;
|
|
15161
|
+
cursor = parent.parentConversationId;
|
|
15162
|
+
}
|
|
15163
|
+
return conversationId;
|
|
15164
|
+
}
|
|
15165
|
+
function assertScopeCanReadTarget(args) {
|
|
15166
|
+
const { accessScope, targetConversationId, targetRootConversationId, targetVisibility, targetDestination } = args;
|
|
15167
|
+
if (targetConversationId === accessScope.currentConversationId || targetRootConversationId !== void 0 && targetRootConversationId === accessScope.currentRootConversationId) return;
|
|
15168
|
+
if (!canExposeConversationPayload(targetVisibility ? { visibility: targetVisibility } : {})) throw new ToolInputError(`Conversation events are not accessible: ${targetConversationId}`);
|
|
15169
|
+
if (accessScope.provider === "slack" && targetDestination?.platform === "slack" && accessScope.providerTenantId && targetDestination.teamId === accessScope.providerTenantId) return;
|
|
15170
|
+
throw new ToolInputError(`Conversation events are not accessible: ${targetConversationId}`);
|
|
15171
|
+
}
|
|
15172
|
+
/** Replace replacement history with its item count; the original events stay readable by seq. */
|
|
15173
|
+
function stripReplacementHistory(data) {
|
|
15174
|
+
if (data.type === "unknown") return {
|
|
15175
|
+
...data,
|
|
15176
|
+
payload: stripReplacementHistoryField(data.payload)
|
|
15177
|
+
};
|
|
15178
|
+
if (data.type === "compaction" || data.type === "handoff") return stripReplacementHistoryField(data);
|
|
15179
|
+
return data;
|
|
15180
|
+
}
|
|
15181
|
+
function stripReplacementHistoryField(value) {
|
|
15182
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return value;
|
|
15183
|
+
const { replacementHistory, ...rest } = value;
|
|
15184
|
+
if (replacementHistory === void 0) return value;
|
|
15185
|
+
return {
|
|
15186
|
+
...rest,
|
|
15187
|
+
replacement_history_count: Array.isArray(replacementHistory) ? replacementHistory.length : 0
|
|
15188
|
+
};
|
|
15189
|
+
}
|
|
15190
|
+
// src/chat/tools/read-conversation-event.ts
|
|
15191
|
+
const DEFAULT_LIMIT$2 = 2e4;
|
|
15192
|
+
const MAX_LIMIT$2 = 5e4;
|
|
15193
|
+
const readConversationEventOutputSchema = juniorToolOutputSchema.extend({
|
|
15194
|
+
conversation_id: z.string().min(1),
|
|
15195
|
+
seq: z.number().int().nonnegative(),
|
|
15196
|
+
history_version: z.number().int().nonnegative(),
|
|
15197
|
+
created_at: z.iso.datetime(),
|
|
15198
|
+
type: z.string().min(1).describe("Event type."),
|
|
15199
|
+
tool_name: z.string().min(1).optional().describe("Tool that produced a tool_result event."),
|
|
15200
|
+
is_error: z.boolean().optional().describe("Whether a tool_result event was an error."),
|
|
15201
|
+
text: z.string().describe("Event text from offset, at most limit chars."),
|
|
15202
|
+
offset: z.number().int().nonnegative(),
|
|
15203
|
+
total_chars: z.number().int().nonnegative(),
|
|
15204
|
+
has_more: z.boolean().describe("Whether text continues after this slice.")
|
|
15205
|
+
});
|
|
15206
|
+
/** Create a deferred tool that reads one full event of a conversation log. */
|
|
15207
|
+
function createReadConversationEventTool(context) {
|
|
15208
|
+
return zodTool({
|
|
15209
|
+
description: "Read the full text of one conversation event by seq, in pages. Works for events from earlier history versions, such as cleared tool results.",
|
|
15210
|
+
exposure: "deferred",
|
|
15211
|
+
source: CONVERSATIONS_TOOL_SOURCE,
|
|
15212
|
+
annotations: {
|
|
15213
|
+
destructiveHint: false,
|
|
15214
|
+
idempotentHint: true,
|
|
15215
|
+
openWorldHint: false,
|
|
15216
|
+
readOnlyHint: true
|
|
15217
|
+
},
|
|
15218
|
+
inputSchema: z.object({
|
|
15219
|
+
seq: z.number().int().nonnegative().describe("Event sequence number."),
|
|
15220
|
+
conversation_id: z.string().trim().min(1).nullable().describe("Conversation ID. Omit or null for the current conversation.").optional(),
|
|
15221
|
+
offset: z.number().int().nonnegative().nullable().describe("First char to return. Default 0.").optional(),
|
|
15222
|
+
limit: z.number().int().min(1).max(MAX_LIMIT$2).nullable().describe(`Maximum chars. Default ${DEFAULT_LIMIT$2}; max ${MAX_LIMIT$2}.`).optional()
|
|
15223
|
+
}).strict(),
|
|
15224
|
+
outputSchema: readConversationEventOutputSchema,
|
|
15225
|
+
execute: async (input) => {
|
|
15226
|
+
const conversationId = input.conversation_id?.trim() || context.conversationId;
|
|
15227
|
+
const offset = input.offset ?? 0;
|
|
15228
|
+
const limit = input.limit ?? DEFAULT_LIMIT$2;
|
|
15229
|
+
await assertCanReadConversationEvents(context, conversationId);
|
|
15230
|
+
const event = (await getConversationEventStore().query(conversationId, {
|
|
15231
|
+
afterSeq: input.seq - 1,
|
|
15232
|
+
beforeSeq: input.seq + 1,
|
|
15233
|
+
limit: 1
|
|
15234
|
+
})).events[0];
|
|
15235
|
+
if (!event) throw new ToolInputError(`Conversation event not found: seq ${input.seq} in ${conversationId}`);
|
|
15236
|
+
const text = eventText(event.data);
|
|
15237
|
+
if (offset > 0 && offset >= text.length) throw new ToolInputError(`offset ${offset} is past the end of the event text (${text.length} chars)`);
|
|
15238
|
+
const slice = text.slice(offset, offset + limit);
|
|
15239
|
+
return {
|
|
15240
|
+
conversation_id: conversationId,
|
|
15241
|
+
seq: event.seq,
|
|
15242
|
+
history_version: event.historyVersion,
|
|
15243
|
+
created_at: new Date(event.createdAtMs).toISOString(),
|
|
15244
|
+
type: event.data.type === "unknown" ? event.data.originalType : event.data.type,
|
|
15245
|
+
...toolResultFields(event.data),
|
|
15246
|
+
text: slice,
|
|
15247
|
+
offset,
|
|
15248
|
+
total_chars: text.length,
|
|
15249
|
+
has_more: offset + slice.length < text.length
|
|
15250
|
+
};
|
|
15251
|
+
}
|
|
15252
|
+
});
|
|
15253
|
+
}
|
|
15254
|
+
function toolResultFields(data) {
|
|
15255
|
+
if (data.type !== "tool_result") return void 0;
|
|
15256
|
+
return {
|
|
15257
|
+
...typeof data.toolName === "string" && data.toolName ? { tool_name: data.toolName } : void 0,
|
|
15258
|
+
...typeof data.isError === "boolean" ? { is_error: data.isError } : void 0
|
|
15259
|
+
};
|
|
15260
|
+
}
|
|
15261
|
+
/**
|
|
15262
|
+
* Render agent history items as the text the model saw, and messages as their
|
|
15263
|
+
* text. Other events render as JSON without replacement history, which stays
|
|
15264
|
+
* readable through its original events.
|
|
15265
|
+
*/
|
|
15266
|
+
function eventText(data) {
|
|
15267
|
+
switch (data.type) {
|
|
15268
|
+
case "user_message":
|
|
15269
|
+
case "assistant_message":
|
|
15270
|
+
case "tool_result": return contentText$1(data.content);
|
|
15271
|
+
case "message":
|
|
15272
|
+
case "message_updated": return data.text;
|
|
15273
|
+
default: return JSON.stringify(stripReplacementHistory(data), null, 2);
|
|
15274
|
+
}
|
|
15275
|
+
}
|
|
15276
|
+
function contentText$1(content) {
|
|
15277
|
+
if (typeof content === "string") return content;
|
|
15278
|
+
if (!Array.isArray(content)) return "";
|
|
15279
|
+
return content.map(contentPartText).join("\n");
|
|
15280
|
+
}
|
|
15281
|
+
function contentPartText(part) {
|
|
15282
|
+
if (!part || typeof part !== "object") return "";
|
|
15283
|
+
const value = part;
|
|
15284
|
+
switch (value.type) {
|
|
15285
|
+
case "text": return typeof value.text === "string" ? value.text : "";
|
|
15286
|
+
case "image": return `[image: ${typeof value.mimeType === "string" ? value.mimeType : "unknown type"}]`;
|
|
15287
|
+
case "toolCall": return `[tool call: ${String(value.name)} ${JSON.stringify(value.arguments ?? {})}]`;
|
|
15288
|
+
default: return "";
|
|
15289
|
+
}
|
|
15290
|
+
}
|
|
14919
15291
|
// src/chat/tools/search-conversation-events.ts
|
|
14920
15292
|
const DEFAULT_LIMIT$1 = 25;
|
|
14921
15293
|
const MAX_LIMIT$1 = 100;
|
|
@@ -14929,7 +15301,7 @@ const projectedEventSchema = z.object({
|
|
|
14929
15301
|
history_version: z.number().int().nonnegative().describe("Agent history generation after replacement."),
|
|
14930
15302
|
created_at: z.iso.datetime().describe("When the event was recorded."),
|
|
14931
15303
|
idempotency_key: z.string().min(1).optional().describe("Retry-stable event identity, when assigned."),
|
|
14932
|
-
data: z.record(z.string(), z.unknown()).describe("Bounded event data.")
|
|
15304
|
+
data: z.record(z.string(), z.unknown()).describe("Bounded event data. Read an omitted payload with readConversationEvent.")
|
|
14933
15305
|
}).strict();
|
|
14934
15306
|
const searchConversationEventsOutputSchema = juniorToolOutputSchema.extend({
|
|
14935
15307
|
conversation_id: z.string().min(1),
|
|
@@ -14966,20 +15338,7 @@ function createSearchConversationEventsTool(context) {
|
|
|
14966
15338
|
const limit = input.limit ?? DEFAULT_LIMIT$1;
|
|
14967
15339
|
const types = input.types ?? void 0;
|
|
14968
15340
|
if (afterSeq !== void 0 && beforeSeq !== void 0 && afterSeq >= beforeSeq) throw new ToolInputError("after_seq must be less than before_seq when both are provided");
|
|
14969
|
-
|
|
14970
|
-
const target = await conversationStore.get({ conversationId });
|
|
14971
|
-
if (!target) throw new ToolInputError(`Conversation not found: ${conversationId}`);
|
|
14972
|
-
if (target.transcriptPurgedAtMs !== void 0) throw new ToolInputError(`Conversation transcript was purged: ${conversationId}`);
|
|
14973
|
-
const accessScope = await resolveAccessScope(conversationStore, context, currentConversationId);
|
|
14974
|
-
const targetRootConversationId = await resolveRootConversationId(conversationStore, conversationId, target.parentConversationId);
|
|
14975
|
-
const targetRoot = targetRootConversationId === conversationId ? target : await conversationStore.get({ conversationId: targetRootConversationId });
|
|
14976
|
-
assertCanSearchConversationEvents({
|
|
14977
|
-
accessScope,
|
|
14978
|
-
targetConversationId: conversationId,
|
|
14979
|
-
targetRootConversationId,
|
|
14980
|
-
targetVisibility: targetRoot?.visibility ?? target.visibility,
|
|
14981
|
-
targetDestination: targetRoot?.destination ?? target.destination
|
|
14982
|
-
});
|
|
15341
|
+
await assertCanReadConversationEvents(context, conversationId);
|
|
14983
15342
|
const page = await getConversationEventStore().query(conversationId, {
|
|
14984
15343
|
limit,
|
|
14985
15344
|
...afterSeq === void 0 ? void 0 : { afterSeq },
|
|
@@ -14999,53 +15358,6 @@ function createSearchConversationEventsTool(context) {
|
|
|
14999
15358
|
}
|
|
15000
15359
|
});
|
|
15001
15360
|
}
|
|
15002
|
-
async function resolveAccessScope(conversationStore, context, currentConversationId) {
|
|
15003
|
-
const current = await conversationStore.get({ conversationId: currentConversationId });
|
|
15004
|
-
const currentRootConversationId = current ? await resolveRootConversationId(conversationStore, currentConversationId, current.parentConversationId) : currentConversationId;
|
|
15005
|
-
if (context.location?.provider === "slack") return {
|
|
15006
|
-
currentConversationId,
|
|
15007
|
-
currentRootConversationId,
|
|
15008
|
-
provider: "slack",
|
|
15009
|
-
providerTenantId: context.location.teamId
|
|
15010
|
-
};
|
|
15011
|
-
if (context.source.kind === "slack") return {
|
|
15012
|
-
currentConversationId,
|
|
15013
|
-
currentRootConversationId,
|
|
15014
|
-
provider: "slack",
|
|
15015
|
-
providerTenantId: context.source.teamId
|
|
15016
|
-
};
|
|
15017
|
-
if (context.destination.platform === "slack" && "teamId" in context.destination) return {
|
|
15018
|
-
currentConversationId,
|
|
15019
|
-
currentRootConversationId,
|
|
15020
|
-
provider: "slack",
|
|
15021
|
-
providerTenantId: context.destination.teamId
|
|
15022
|
-
};
|
|
15023
|
-
return {
|
|
15024
|
-
currentConversationId,
|
|
15025
|
-
currentRootConversationId
|
|
15026
|
-
};
|
|
15027
|
-
}
|
|
15028
|
-
async function resolveRootConversationId(conversationStore, conversationId, parentConversationId) {
|
|
15029
|
-
if (!parentConversationId) return conversationId;
|
|
15030
|
-
let cursor = parentConversationId;
|
|
15031
|
-
const seen = /* @__PURE__ */ new Set([conversationId]);
|
|
15032
|
-
while (cursor) {
|
|
15033
|
-
if (seen.has(cursor)) return conversationId;
|
|
15034
|
-
seen.add(cursor);
|
|
15035
|
-
const parent = await conversationStore.get({ conversationId: cursor });
|
|
15036
|
-
if (!parent) return conversationId;
|
|
15037
|
-
if (!parent.parentConversationId) return parent.conversationId;
|
|
15038
|
-
cursor = parent.parentConversationId;
|
|
15039
|
-
}
|
|
15040
|
-
return conversationId;
|
|
15041
|
-
}
|
|
15042
|
-
function assertCanSearchConversationEvents(args) {
|
|
15043
|
-
const { accessScope, targetConversationId, targetRootConversationId, targetVisibility, targetDestination } = args;
|
|
15044
|
-
if (targetConversationId === accessScope.currentConversationId || targetRootConversationId !== void 0 && targetRootConversationId === accessScope.currentRootConversationId) return;
|
|
15045
|
-
if (!canExposeConversationPayload(targetVisibility ? { visibility: targetVisibility } : {})) throw new ToolInputError(`Conversation events are not accessible: ${targetConversationId}`);
|
|
15046
|
-
if (accessScope.provider === "slack" && targetDestination?.platform === "slack" && accessScope.providerTenantId && targetDestination.teamId === accessScope.providerTenantId) return;
|
|
15047
|
-
throw new ToolInputError(`Conversation events are not accessible: ${targetConversationId}`);
|
|
15048
|
-
}
|
|
15049
15361
|
function projectEventsForTool(page, options) {
|
|
15050
15362
|
const projected = page.events.map(projectEvent);
|
|
15051
15363
|
const events = [];
|
|
@@ -15109,23 +15421,6 @@ function eventIdentity(data) {
|
|
|
15109
15421
|
return typeof value === "string" ? [[key, value.slice(0, MAX_IDENTITY_CHARS)]] : [];
|
|
15110
15422
|
}));
|
|
15111
15423
|
}
|
|
15112
|
-
function stripReplacementHistory(data) {
|
|
15113
|
-
if (data.type === "unknown") return {
|
|
15114
|
-
...data,
|
|
15115
|
-
payload: stripReplacementHistoryField(data.payload)
|
|
15116
|
-
};
|
|
15117
|
-
if (data.type === "compaction" || data.type === "handoff") return stripReplacementHistoryField(data);
|
|
15118
|
-
return data;
|
|
15119
|
-
}
|
|
15120
|
-
function stripReplacementHistoryField(value) {
|
|
15121
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return value;
|
|
15122
|
-
const { replacementHistory, ...rest } = value;
|
|
15123
|
-
if (replacementHistory === void 0) return value;
|
|
15124
|
-
return {
|
|
15125
|
-
...rest,
|
|
15126
|
-
replacement_history_count: Array.isArray(replacementHistory) ? replacementHistory.length : 0
|
|
15127
|
-
};
|
|
15128
|
-
}
|
|
15129
15424
|
// src/chat/briefs/search.ts
|
|
15130
15425
|
/** Search the latest Brief of each public root Conversation in one scope. */
|
|
15131
15426
|
async function searchConversationBriefs(db, args) {
|
|
@@ -16239,6 +16534,7 @@ function createTools(availableSkills, hooks = {}, context, options = {}) {
|
|
|
16239
16534
|
...createUserCustomizationTools(context)
|
|
16240
16535
|
};
|
|
16241
16536
|
tools.searchConversationEvents = createSearchConversationEventsTool(context);
|
|
16537
|
+
tools.readConversationEvent = createReadConversationEventTool(context);
|
|
16242
16538
|
if (context.conversationPrivacy === "public") tools.searchConversationBriefs = createSearchConversationBriefsTool(slackContext ? {
|
|
16243
16539
|
kind: "public_provider_tenant",
|
|
16244
16540
|
provider: "slack",
|
|
@@ -16717,6 +17013,12 @@ function createToolActionReview(options) {
|
|
|
16717
17013
|
const pendingRejections = /* @__PURE__ */ new Map();
|
|
16718
17014
|
let consecutiveRejections = 0;
|
|
16719
17015
|
/**
|
|
17016
|
+
* Rejection state of each attempt, so an attempt counts only once. Pi runs
|
|
17017
|
+
* a `codemode` call alone, so no other attempt changes the count while
|
|
17018
|
+
* its batches run.
|
|
17019
|
+
*/
|
|
17020
|
+
const attempts = /* @__PURE__ */ new Map();
|
|
17021
|
+
/**
|
|
16720
17022
|
* Review one action and record its decision. Gate state does not change
|
|
16721
17023
|
* here, so concurrent reviews in one batch cannot corrupt it.
|
|
16722
17024
|
*/
|
|
@@ -16743,8 +17045,50 @@ function createToolActionReview(options) {
|
|
|
16743
17045
|
};
|
|
16744
17046
|
}
|
|
16745
17047
|
};
|
|
17048
|
+
/**
|
|
17049
|
+
* Count each attempt in the batch once, in batch order. An attempt with a
|
|
17050
|
+
* rejection adds one to the count from before the attempt, also when it
|
|
17051
|
+
* has allowed actions or spans several batches. An attempt with only
|
|
17052
|
+
* allowed actions resets the count. Skipped and unavailable actions do not
|
|
17053
|
+
* change it. Return the attempt state of each action.
|
|
17054
|
+
*/
|
|
17055
|
+
const countAttempts = (actions, steps) => {
|
|
17056
|
+
const states = actions.map((action) => {
|
|
17057
|
+
const id = action.attemptId ?? action.toolCallId;
|
|
17058
|
+
let state = attempts.get(id);
|
|
17059
|
+
if (!state) {
|
|
17060
|
+
state = {
|
|
17061
|
+
before: consecutiveRejections,
|
|
17062
|
+
exhausted: false,
|
|
17063
|
+
rejected: false
|
|
17064
|
+
};
|
|
17065
|
+
attempts.set(id, state);
|
|
17066
|
+
}
|
|
17067
|
+
return state;
|
|
17068
|
+
});
|
|
17069
|
+
states.forEach((state, index) => {
|
|
17070
|
+
const step = steps[index];
|
|
17071
|
+
if (step.kind !== "reviewed" || state.rejected) return;
|
|
17072
|
+
if (step.decision.decision === "allow") {
|
|
17073
|
+
consecutiveRejections = 0;
|
|
17074
|
+
return;
|
|
17075
|
+
}
|
|
17076
|
+
state.rejected = true;
|
|
17077
|
+
consecutiveRejections = state.before + 1;
|
|
17078
|
+
if (consecutiveRejections < MAX_CONSECUTIVE_REJECTIONS) return;
|
|
17079
|
+
state.exhausted = true;
|
|
17080
|
+
logException(new ToolActionReviewLimitError(), "guardian.action_review.exhausted", {
|
|
17081
|
+
"app.guardian.decision": step.decision.decision,
|
|
17082
|
+
"app.guardian.risk_level": step.decision.riskLevel,
|
|
17083
|
+
"app.guardian.user_authorization": step.decision.userAuthorization,
|
|
17084
|
+
"gen_ai.tool.name": step.proposal.tool.name,
|
|
17085
|
+
"gen_ai.tool.call.id": actions[index].toolCallId
|
|
17086
|
+
});
|
|
17087
|
+
});
|
|
17088
|
+
return states;
|
|
17089
|
+
};
|
|
16746
17090
|
/** Apply one review step to gate state and return the action's result. */
|
|
16747
|
-
const settle = (toolCallId, step) => {
|
|
17091
|
+
const settle = (toolCallId, step, exhausted) => {
|
|
16748
17092
|
if (step.kind === "skipped") return { allowed: true };
|
|
16749
17093
|
if (step.kind === "unavailable") {
|
|
16750
17094
|
options.onFatal(step.error);
|
|
@@ -16754,24 +17098,12 @@ function createToolActionReview(options) {
|
|
|
16754
17098
|
};
|
|
16755
17099
|
}
|
|
16756
17100
|
const { decision, proposal } = step;
|
|
16757
|
-
if (decision.decision === "allow") {
|
|
16758
|
-
|
|
16759
|
-
|
|
16760
|
-
|
|
16761
|
-
decision
|
|
16762
|
-
};
|
|
16763
|
-
}
|
|
17101
|
+
if (decision.decision === "allow") return {
|
|
17102
|
+
allowed: true,
|
|
17103
|
+
decision
|
|
17104
|
+
};
|
|
16764
17105
|
const reviewedAction = projectedRejection(proposal, decision);
|
|
16765
17106
|
addPriorRejection(priorRejections, reviewedAction);
|
|
16766
|
-
consecutiveRejections += 1;
|
|
16767
|
-
const exhausted = consecutiveRejections >= MAX_CONSECUTIVE_REJECTIONS;
|
|
16768
|
-
if (exhausted) logException(new ToolActionReviewLimitError(), "guardian.action_review.exhausted", {
|
|
16769
|
-
"app.guardian.decision": decision.decision,
|
|
16770
|
-
"app.guardian.risk_level": decision.riskLevel,
|
|
16771
|
-
"app.guardian.user_authorization": decision.userAuthorization,
|
|
16772
|
-
"gen_ai.tool.name": proposal.tool.name,
|
|
16773
|
-
"gen_ai.tool.call.id": toolCallId
|
|
16774
|
-
});
|
|
16775
17107
|
pendingRejections.set(toolCallId, {
|
|
16776
17108
|
decision: decision.decision,
|
|
16777
17109
|
priorRejection: reviewedAction,
|
|
@@ -16798,7 +17130,8 @@ function createToolActionReview(options) {
|
|
|
16798
17130
|
return await withSpan("guardian.action_review", "guardian.action_review", {}, async () => {
|
|
16799
17131
|
const rejections = [...priorRejections];
|
|
16800
17132
|
const steps = await mapConcurrent(actions, MAX_CONCURRENT_REVIEWS, (action) => reviewStep(action, rejections, signal));
|
|
16801
|
-
|
|
17133
|
+
const states = countAttempts(actions, steps);
|
|
17134
|
+
return new Map(actions.map((action, index) => [action.toolCallId, settle(action.toolCallId, steps[index], states[index].exhausted)]));
|
|
16802
17135
|
}, { "app.guardian.batch.size": actions.length });
|
|
16803
17136
|
},
|
|
16804
17137
|
projectToolResult(toolCallId, result) {
|
|
@@ -17506,6 +17839,7 @@ async function runCodeModeScript(run) {
|
|
|
17506
17839
|
});
|
|
17507
17840
|
return await run.pipeline.reviewScriptCalls(actions.map((action) => ({
|
|
17508
17841
|
...action,
|
|
17842
|
+
attemptId: run.toolCallId,
|
|
17509
17843
|
script: {
|
|
17510
17844
|
source: run.source,
|
|
17511
17845
|
calls: earlier
|
|
@@ -17668,7 +18002,8 @@ function renderScriptTools(tools) {
|
|
|
17668
18002
|
"declare const tools: {",
|
|
17669
18003
|
...shown.map((entry) => entry.text),
|
|
17670
18004
|
"};",
|
|
17671
|
-
...omitted > 0 ? [`${omitted} more tools are not declared here.
|
|
18005
|
+
...omitted > 0 ? [`${omitted} more tools are not declared here. To find one, call ${SEARCH_TOOLS_NAME} directly before the script. Then call each result as \`tools.<tool_name>(args)\`, with its input_schema. A script cannot call ${SEARCH_TOOLS_NAME} or ${EXECUTE_TOOL_NAME}.`] : [],
|
|
18006
|
+
...Object.hasOwn(tools, "callMcpTool") ? ["Call an MCP tool as `tools.callMcpTool({ tool_name, arguments })`. `tools.mcp__<provider>__<tool>` does not exist."] : []
|
|
17672
18007
|
].join("\n");
|
|
17673
18008
|
}
|
|
17674
18009
|
function renderDescription(tools) {
|
|
@@ -20031,6 +20366,38 @@ function appendOpenPlan(continuation, messages) {
|
|
|
20031
20366
|
const plan = latestOpenPlanItems(messages);
|
|
20032
20367
|
return plan.length === 0 ? continuation : `${continuation}\n\n<${OPEN_PLAN_TAG}>\n${JSON.stringify(plan)}\n</${OPEN_PLAN_TAG}>`;
|
|
20033
20368
|
}
|
|
20369
|
+
// src/chat/services/context-compaction-telemetry.ts
|
|
20370
|
+
/**
|
|
20371
|
+
* Context compaction telemetry.
|
|
20372
|
+
*
|
|
20373
|
+
* Each compaction gets one `agent.context_compaction` span. The span and its
|
|
20374
|
+
* children, such as the summary `gen_ai.chat` span, carry
|
|
20375
|
+
* `app.compaction.mode`. The `chat.turn` span sums the time that the Turn
|
|
20376
|
+
* waited on compaction.
|
|
20377
|
+
*
|
|
20378
|
+
* Attribute keys do not contain "token": Sentry data scrubbing removes the
|
|
20379
|
+
* values of keys that match it.
|
|
20380
|
+
*/
|
|
20381
|
+
const turnCompactionWait = new AsyncLocalStorage();
|
|
20382
|
+
/** Run one compaction in its span and add its time to the Turn wait. */
|
|
20383
|
+
async function withCompactionSpan(mode, callback) {
|
|
20384
|
+
const startedAtMs = performance.now();
|
|
20385
|
+
try {
|
|
20386
|
+
return await runWithLogAttributes({ "app.compaction.mode": mode }, () => withSpan("agent.context_compaction", "agent.context_compaction", {}, callback));
|
|
20387
|
+
} finally {
|
|
20388
|
+
const wait = turnCompactionWait.getStore();
|
|
20389
|
+
if (wait) wait.ms += performance.now() - startedAtMs;
|
|
20390
|
+
}
|
|
20391
|
+
}
|
|
20392
|
+
/** Run one `chat.turn` callback and record its compaction wait, if any. */
|
|
20393
|
+
async function measureTurnCompactionWait(setTurnAttributes, callback) {
|
|
20394
|
+
const wait = { ms: 0 };
|
|
20395
|
+
try {
|
|
20396
|
+
return await turnCompactionWait.run(wait, callback);
|
|
20397
|
+
} finally {
|
|
20398
|
+
if (wait.ms > 0) setTurnAttributes({ "app.turn.compaction_wait_ms": Math.round(wait.ms) });
|
|
20399
|
+
}
|
|
20400
|
+
}
|
|
20034
20401
|
// src/chat/services/context-compaction.ts
|
|
20035
20402
|
const RETAINED_USER_MESSAGE_TOKENS = 2e4;
|
|
20036
20403
|
const MAX_SUMMARY_CHARS = 6e3;
|
|
@@ -20290,6 +20657,9 @@ async function maybeCompactWithDeps(args, deps) {
|
|
|
20290
20657
|
compacted: false,
|
|
20291
20658
|
reason: "below_threshold"
|
|
20292
20659
|
};
|
|
20660
|
+
return await withCompactionSpan("blocking", () => compactAboveThreshold(args, deps, source, triggerTokens));
|
|
20661
|
+
}
|
|
20662
|
+
async function compactAboveThreshold(args, deps, source, triggerTokens) {
|
|
20293
20663
|
await args.onCompactionStart?.();
|
|
20294
20664
|
let summary;
|
|
20295
20665
|
try {
|
|
@@ -20300,6 +20670,7 @@ async function maybeCompactWithDeps(args, deps) {
|
|
|
20300
20670
|
}, deps);
|
|
20301
20671
|
} catch (error) {
|
|
20302
20672
|
logWarn("context_compaction.summary.failed", { "exception.message": error instanceof Error ? error.message : String(error) });
|
|
20673
|
+
setSpanAttributes({ "app.compaction.outcome": "summary_failed" });
|
|
20303
20674
|
return {
|
|
20304
20675
|
compacted: false,
|
|
20305
20676
|
reason: "summary_failed"
|
|
@@ -20354,11 +20725,14 @@ async function writeCompactedThreadContext(args, sourceMessages, summary, contex
|
|
|
20354
20725
|
}
|
|
20355
20726
|
});
|
|
20356
20727
|
setSpanAttributes({
|
|
20728
|
+
"app.compaction.outcome": "compacted",
|
|
20357
20729
|
"app.compaction.input_messages": sourceMessages.length,
|
|
20358
20730
|
"app.compaction.retained_messages": replacement.length - 1,
|
|
20359
20731
|
"app.compaction.summary_chars": summary.length,
|
|
20360
|
-
|
|
20361
|
-
"app.
|
|
20732
|
+
"app.compaction.input.estimate": context.estimatedTokens,
|
|
20733
|
+
"app.compaction.replacement.estimate": replacementInputTokens,
|
|
20734
|
+
"app.compaction.input_limit": context.inputLimitTokens,
|
|
20735
|
+
...context.triggerTokens !== void 0 ? { "app.compaction.threshold": context.triggerTokens } : void 0
|
|
20362
20736
|
});
|
|
20363
20737
|
return {
|
|
20364
20738
|
compacted: true,
|
|
@@ -20371,6 +20745,9 @@ function createContextCompactor(deps) {
|
|
|
20371
20745
|
}
|
|
20372
20746
|
/** Compact the active conversation and durably bind its selected handoff profile. */
|
|
20373
20747
|
async function compactContextForHandoff(args, deps) {
|
|
20748
|
+
return await withCompactionSpan("handoff", () => compactForHandoff(args, deps));
|
|
20749
|
+
}
|
|
20750
|
+
async function compactForHandoff(args, deps) {
|
|
20374
20751
|
const retainedInstruction = await loadLastInstruction(args.conversationId);
|
|
20375
20752
|
const contextMessage = runtimeContextMessage(args.runtimeContext, retainedInstruction?.message.timestamp);
|
|
20376
20753
|
if (!contextMessage) throw new Error("Handoff requires the current runtime turn context");
|
|
@@ -20422,6 +20799,10 @@ async function compactActiveContextIfNeeded(args, deps) {
|
|
|
20422
20799
|
compacted: false,
|
|
20423
20800
|
reason: "below_threshold"
|
|
20424
20801
|
};
|
|
20802
|
+
return await withCompactionSpan("active", () => compactActiveAboveThreshold(args, deps, source, triggerTokens));
|
|
20803
|
+
}
|
|
20804
|
+
async function compactActiveAboveThreshold(args, deps, source, triggerTokens) {
|
|
20805
|
+
const pendingMessages = args.pendingMessages ?? [];
|
|
20425
20806
|
await args.onCompactionStart?.();
|
|
20426
20807
|
const inputLimitTokens = getAgentContextInputLimitTokens(args.modelId);
|
|
20427
20808
|
let summary;
|
|
@@ -20437,6 +20818,7 @@ async function compactActiveContextIfNeeded(args, deps) {
|
|
|
20437
20818
|
"app.context_tokens_estimated": source.estimatedTokens,
|
|
20438
20819
|
"exception.message": error instanceof Error ? error.message : String(error)
|
|
20439
20820
|
});
|
|
20821
|
+
setSpanAttributes({ "app.compaction.outcome": "summary_failed" });
|
|
20440
20822
|
return {
|
|
20441
20823
|
compacted: false,
|
|
20442
20824
|
reason: "summary_failed"
|
|
@@ -20491,13 +20873,14 @@ async function compactActiveContextIfNeeded(args, deps) {
|
|
|
20491
20873
|
}
|
|
20492
20874
|
});
|
|
20493
20875
|
setSpanAttributes({
|
|
20876
|
+
"app.compaction.outcome": "compacted",
|
|
20494
20877
|
"app.compaction.input_messages": source.messages.length,
|
|
20495
|
-
"app.compaction.replacement_tokens": replacementInputTokens,
|
|
20496
20878
|
"app.compaction.retained_messages": instructionMessages.length,
|
|
20497
20879
|
"app.compaction.summary_chars": summary.length,
|
|
20498
|
-
"app.compaction.
|
|
20499
|
-
"app.
|
|
20500
|
-
"app.
|
|
20880
|
+
"app.compaction.input.estimate": source.estimatedTokens,
|
|
20881
|
+
"app.compaction.replacement.estimate": replacementInputTokens,
|
|
20882
|
+
"app.compaction.input_limit": inputLimitTokens,
|
|
20883
|
+
"app.compaction.threshold": triggerTokens
|
|
20501
20884
|
});
|
|
20502
20885
|
return {
|
|
20503
20886
|
compacted: true,
|
|
@@ -21260,6 +21643,7 @@ async function executeAgentRunInPrivacyContext(run, conversationPrivacy, runLogC
|
|
|
21260
21643
|
};
|
|
21261
21644
|
agent = new Agent({
|
|
21262
21645
|
getApiKey: getGatewayApiKey,
|
|
21646
|
+
sessionId: conversationId,
|
|
21263
21647
|
streamFn: createTracedStreamFn({
|
|
21264
21648
|
conversationPrivacy,
|
|
21265
21649
|
...streamFn ? { base: streamFn } : void 0
|
|
@@ -21713,4 +22097,4 @@ function createAgentRunner(execute, options) {
|
|
|
21713
22097
|
return await execute(nextRun, streamFn);
|
|
21714
22098
|
} };
|
|
21715
22099
|
}
|
|
21716
|
-
export {
|
|
22100
|
+
export { readViewerAutomations as $, runWithSlackInstallation as A, readUserCustomization as At, logScheduledAutomationRunSkipped as B, readSlackReviewItemCardConversationId as C, listUnreportedSiblingAgents as Ct, parseSlackReviewItemClick as D, ingestEvent as Dt, buildSlackReviewItemModal as E, processWorkspaceSnapshotJob as Et, resolveSlackChannelIdFromThreadId as F, readBlockedReport as Ft, readViewerAutomationEdit as G, activateViewerAutomationVersion as H, getConversationInfo as I, shouldEmitDevAgentTrace as It, readConversationSourceTask as J, updateViewerAutomation as K, joinPublicChannel as L, parseSlackThreadId as M, RetryableDeliveryError as Mt, readSlackRawMessageContext as N, actorFromRun as Nt, parseSlackReviewItemFormTarget as O, buildSteeringPiMessage as Ot, resolveSlackChannelIdFromMessage as P, toolInvocationDestination as Pt, readViewerAutomationVersions as Q, listThreadReplies as R, createSlackReviewItemShow as S, listChildAgents as St, SLACK_REVIEW_ITEM_VIEW_ID as T, conversationSubtreeColumns as Tt, changeViewerAutomationLifecycle as U, scheduledAutomationRunAttributes as V, deleteViewerTask as W, readViewerAutomationRuns as X, readViewerAutomationExecutions as Y, readViewerAutomationSummary as Z, readPublicArtifact as _, storeAttachment as _t, buildAuthPauseResponse as a, acceptsWebMessages as at, renderAttachmentText as b, recordSubagentEnded as bt, deleteMcpAuthSessionsForUserProvider as c, createAndEnqueueConversation as ct, getMcpAuthSession as d, webActorFromEmail as dt, AutomationEditError as et, getMcpStoredOAuthCredentials as f, resolveConversationDestination as ft, publicArtifactHeaders as g, requestAttachmentDeletion as gt, readStats as h, readLiveAttachment as ht, measureTurnCompactionWait as i, renderReviewItemMessage as it, verifySlackSignature as j, saveUserCustomization as jt, parseSlackUserInputSubmission as k, withoutSavedSteeringMessages as kt, deleteMcpServerSessionId as l, createConversationId as lt, latestProgressStatus as m, collectAttachmentGarbage as mt, executeAgentRun as n, listOwnedWatches as nt, finalizeMcpAuthorization as o, appendAndEnqueueWebMessage as ot, putMcpStoredOAuthCredentials as p, decodeInputImages as pt, ViewerTaskNotFoundError as q, createContextCompactor as r, deliverReviewItemChange as rt, deleteMcpAuthSession as s, conversationTurnIdForMessage as st, createAgentRunner as t, effectiveTaskOutcomes as tt, deleteMcpStoredOAuthCredentials as u, recordWebConversationActivity as ut, unpublishedArtifactHeaders as v, stopChildAgentsOf as vt, syncReviewItemSlackCards as w, conversationSubtree as wt, renderBlockText as x, recordSubagentStarted as xt, lookupSlackUserProfile as y, stopConversationSession as yt, resolveDestinationVisibility as z };
|