@sentry/junior 0.280.0 → 0.282.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-DVN3iwf9.js → adapter-BAqo7eOH.js} +1 -1
- package/dist/{admin-Q_UI--9W.js → admin-DbWpMHh6.js} +1 -1
- package/dist/{agent-runner-_PYLv4Qo.js → agent-runner-h4CDcnDV.js} +1001 -981
- package/dist/api/schema.d.ts +2 -2
- package/dist/api/schema.js +5 -5
- package/dist/api.d.ts +1 -1
- package/dist/api.js +39 -33
- package/dist/{app-CL2zzzE0.d.ts → app-B-0wwAxr.d.ts} +2 -2
- package/dist/app.d.ts +1 -1
- package/dist/app.js +42 -34
- package/dist/{assistant-reply-DbebsAxi.js → assistant-reply-4Wvo95-N.js} +1 -1
- package/dist/{automation-CPqRFjIa.js → automation-sIsmIXH7.js} +1 -1
- package/dist/{background-compaction-queue-B9lmh8Ml.js → background-compaction-queue-CoWqScCC.js} +2 -2
- package/dist/{briefs-Dej7V0Bz.js → briefs-CMiotFo9.js} +4 -8
- package/dist/{catalog-runtime-DpN0sWQ6.js → catalog-runtime-Cpje_Uic.js} +1 -1
- package/dist/cli/chat.js +14 -14
- package/dist/cli/check.js +3 -3
- package/dist/cli/main.js +3 -3
- package/dist/cli/plugins.js +4 -4
- package/dist/cli/snapshot-create.js +4 -4
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +74 -7
- package/dist/{client-h2A2ZPzY.js → client-BHgCXeaF.js} +2 -2
- package/dist/{config-CusBFORe.js → config-DBdBimZ9.js} +1 -1
- package/dist/{connections-C4h6mGha.js → connections-DjY72_uF.js} +10 -10
- package/dist/{conversation-DExTZw8B.js → conversation-DNtcULyX.js} +29 -8
- package/dist/{conversation-pending-messages-Dgz6hrJs.js → conversation-pending-messages-LlFnr9-m.js} +10 -2
- package/dist/{conversation-privacy-2cm6OpNg.js → conversation-privacy-DiDh9KE4.js} +1 -1
- package/dist/{credential-sync-DK06Jgt-.js → credential-sync-DUrQwccr.js} +13 -13
- package/dist/{db-Dsvk1Tp1.d.ts → db-hQsoB16L.d.ts} +2 -1
- package/dist/{executor-Cmr0J8W3.js → executor-CGqJCxgR.js} +14 -3
- package/dist/instrumentation.js +2 -2
- package/dist/{logging-CGnh65_X.js → logging-DapIaJAi.js} +1 -1
- package/dist/{message-RpAnqHPY.js → message-BjN5sKad.js} +9 -9
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +3 -11
- package/dist/{oauth-callback-server-BBnhVKuX.js → oauth-callback-server-DVHKrjJP.js} +2 -2
- package/dist/{projection-C1MghKyI.js → projection-ii_OYu6z.js} +78 -30
- package/dist/{prompt-BcHg-BMy.js → prompt-DI6KCtwb.js} +5 -26
- package/dist/{registry-DR7DjX9H.js → registry-DpjG3yS-.js} +1 -1
- package/dist/{resolve-0Ful4oDv.js → resolve-iMW9Dgo2.js} +3 -3
- package/dist/{result-Dd9kCuQ-.js → result-BrlvfyIj.js} +9 -9
- package/dist/{runner-yiY8gUUu.js → runner-Bg9mr2pB.js} +11 -11
- package/dist/{sandbox-egress-signals-BzQVHCMz.js → sandbox-egress-signals-Bd3lb_Wd.js} +1 -1
- package/dist/{schema-C5pEgfHc.js → schema-BN34Jy-U.js} +3 -3
- package/dist/{schema-BkMmF552.d.ts → schema-CsqJzkP5.d.ts} +68 -9
- package/dist/{service-account-Cu7HFLZQ.js → service-account-Bd1348kw.js} +3 -3
- package/dist/{service-account-PIMpWZHF.js → service-account-Dfl9Pitm.js} +3 -3
- package/dist/{session-stop-CDEMsNtv.js → session-stop-CVEEx_YD.js} +12 -12
- package/dist/{skills-B2xIoe0f.js → skills-DqUUuf4L.js} +2 -2
- package/dist/{spawn-C0DySQRV.js → spawn-e7rQs14T.js} +2 -2
- package/dist/{stop-Dj5-nrAo.js → stop-DtpBUUJq.js} +353 -135
- package/dist/{store-Dlio-o6u.js → store-nETG4KVg.js} +4 -4
- package/dist/{store-QzOfDwKA.js → store-nu3Xx08K.js} +3 -3
- package/dist/{task-queue-Cp1V_XW3.js → task-queue-CYje8WKs.js} +3 -3
- package/dist/{task-runner-CQkkUj3o.js → task-runner-CwegN45x.js} +6 -6
- package/dist/{thread-state-Bn87cfzE.js → thread-state-BDaMl9yd.js} +4 -4
- package/dist/{turn-failure-response-CQebxByj.js → turn-failure-response-CV06tN_R.js} +7 -7
- package/dist/{turn-lifecycle-CJJsOhXB.js → turn-lifecycle-CF2N7ud5.js} +1 -1
- package/dist/{turn-session-routing-bmG330Cf.js → turn-session-routing-BIJGJjVh.js} +9 -9
- package/dist/{validation-D1wcf7hp.js → validation-DXvxEEjq.js} +1 -1
- package/dist/{version-BeHSXUK6.js → version-CzEk1KBX.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{viewer-BZ0Hp5Nb.js → viewer-C2PztlYX.js} +22 -8
- package/dist/{work-BTcCIbWu.js → work-BM_L0Pv9.js} +10 -10
- package/dist/{worker-D3fDK6zc.js → worker-2no53G60.js} +6 -6
- package/migrations/0062_plugin_report_index.sql +3 -3
- package/migrations/0078_plugin_conversation_index.sql +3 -3
- package/migrations/0079_conversation_event_author_index.sql +3 -3
- package/migrations/0080_conversation_event_latest_message_indexes.sql +27 -0
- package/migrations/meta/0080_snapshot.json +4265 -0
- package/migrations/meta/_journal.json +7 -0
- package/package.json +5 -5
|
@@ -1,32 +1,32 @@
|
|
|
1
1
|
import { g as withActiveSpan, i as getActiveSpan, m as startInactiveSpan, v as __exportAll } from "./sentry-BRTJqumy.js";
|
|
2
|
-
import { $i as isWorkspaceSnapshotNotReadyError, $r as updateWorkspace, $t as isStandaloneRuntimeContextMessage, An as createPluginHookRunner, B as authorizationId, Bi as isConversationScopedChannel, Bt as createTurnLimitGate, Ca as sandboxSkillDir, Ci as addReactionToMessage, Da as buildNonInteractiveShellScript, Dn as getOAuthAccountProviders, Dr as findMatchingWatches, Ea as buildCommandScript, Ei as openSlackDirectMessage, Er as deliverWatch, Fi as SlackActionError, Fn as getPluginTools, Ft as TURN_LIMIT_WRAP_UP_MESSAGE, G as canReusePendingAuthLink, Gt as getPiMessageRole, H as AuthorizationFlowDisabledError, Hi as normalizeSlackConversationId, Hr as getDashboardTaskLink, Ht as CODEMODE_TOOL_NAME, Ii as downloadPrivateSlackFile, In as getPluginUserPromptContributions, It as TurnBudgetExceededError, Ji as isAlreadyExistsError, Jn as getReviewItem, Jr as deleteWorkspace, Jt as hasCurrentInstruction, Kn as dismissOpenReviewItems, Kr as renderToolResultNudge, Kt as getTerminalAssistantMessages, L as createPluginEgress, Li as getFilePermalink, Ln as getPlugins, Lt as TurnSliceLimitExceededError,
|
|
3
|
-
import { C as resolveGatewayCredential, S as getGatewayApiKey, _ as createProviderError, a as completeText, c as resolveGatewayModel, d as isCompactionSummaryText, f as renderCurrentInstruction, g as ProviderError, h as escapeXmlText, i as completeObject, l as COMPACTION_SUMMARY_PREFIX, m as escapeXml, n as GEN_AI_SERVER_ADDRESS, p as unwrapCurrentInstruction, t as GEN_AI_PROVIDER_NAME, u as hasCompactedConversationContext, v as findProviderError, x as isProviderRetryError, y as getProviderErrorAttributes } from "./client-
|
|
4
|
-
import { _ as toPiReasoningLevel, g as TURN_REASONING_LEVELS, n as botConfig, v as normalizeSlackEmojiName } from "./config-
|
|
5
|
-
import { B as runWithLogAttributes, C as summarizeMessageText, E as withSpan, K as toOptionalString, S as setTags, T as withLogContext, U as normalizeIdentityEmail, W as isRecord$4, _ as runBestEffort, a as extractGenAiUsageSummary, b as setSpanAttributes, d as logAudit, f as logError, g as normalizeGenAiFinishReason, h as logWarn, i as extractGenAiUsageAttributes, l as getLogContextAttributesForSpan, m as logInfo, p as logException, u as getTracePropagationHeaders, v as serializeGenAiAttribute, x as setSpanStatus } from "./logging-
|
|
6
|
-
import { a as toCanonicalInputMessage, c as toGenAiPayloadMetadata, i as runWithConversationPrivacy, l as toGenAiPayloadTraceAttributes, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-
|
|
2
|
+
import { $i as isWorkspaceSnapshotNotReadyError, $r as updateWorkspace, $t as isStandaloneRuntimeContextMessage, An as createPluginHookRunner, B as authorizationId, Bi as isConversationScopedChannel, Bt as createTurnLimitGate, Ca as sandboxSkillDir, Ci as addReactionToMessage, Da as buildNonInteractiveShellScript, Dn as getOAuthAccountProviders, Dr as findMatchingWatches, Ea as buildCommandScript, Ei as openSlackDirectMessage, Er as deliverWatch, Fi as SlackActionError, Fn as getPluginTools, Ft as TURN_LIMIT_WRAP_UP_MESSAGE, G as canReusePendingAuthLink, Gt as getPiMessageRole, H as AuthorizationFlowDisabledError, Hi as normalizeSlackConversationId, Hr as getDashboardTaskLink, Ht as CODEMODE_TOOL_NAME, Ii as downloadPrivateSlackFile, In as getPluginUserPromptContributions, It as TurnBudgetExceededError, Ji as isAlreadyExistsError, Jn as getReviewItem, Jr as deleteWorkspace, Jt as hasCurrentInstruction, Kn as dismissOpenReviewItems, Kr as renderToolResultNudge, Kt as getTerminalAssistantMessages, L as createPluginEgress, Li as getFilePermalink, Ln as getPlugins, Lt as TurnSliceLimitExceededError, Mi as uploadFilesToConversation, Na as readConversationAccessFromSql, Oa as runNonInteractiveCommand, Or as getWatch, Pn as getPluginSystemPromptContributions, Qi as getWorkspaceSnapshotNotReadyError, Qn as searchReviewItems, Qt as isContinuablePiBoundary, R as PluginCredentialFailureError, Rt as TurnToolCallLimitExceededError, Sa as SANDBOX_WORKSPACE_ROOT, Sn as isExperimentalFeatureEnabled, So as getConfigDefaults, Sr as cancelWatch, T as resolveTaskTitle, Ta as sandboxSkillPathResolution, Ti as getSlackMessagePermalink, Tn as findLegacyWebActorUserId, Tr as createWatch, U as AuthorizationPauseError, Ui as runWithSlackInstallationToken, V as AuthPausePersistenceError, Vr as getDashboardReviewItemLink, Vt as isTurnExecutionLimitExceededError, W as abandonReplacedPendingAuth, Wi as withSlackRetries, Wn as closeReviewItem, Wr as ToolInputError, Wt as extractAssistantText, X as loadTurnCheckpoint, Xi as wrapSandboxSetupError, Xr as getWorkspaceByName, Y as continuableMessages, Yi as throwSandboxOperationError, Yn as insertReviewItem, Yr as getWorkspace, Yt as hasRuntimeTurnContext, Z as saveTurnCheckpoint, Zi as WorkspaceSnapshotNotReadyError, Zr as listWorkspaces, Zt as isAssistantMessage, _a as SANDBOX_COMMAND_PATH, _i as escapeSlackMrkdwnText, _n as estimateTextTokens, _o as historyItemFromPiMessage, _r as RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS, ai as create, an as trimTrailingAssistantMessages, ba as SANDBOX_REPOS_ROOT, bn as getAgentContextInputLimitTokens, bo as JUNIOR_NATIVE_EVENT_NAMESPACE, br as STOP_WATCHING_TOOL_NAME, c as recordAgentsInstructionsUpdated, ca as resolveSandboxCommandEnvironment, ci as ensureDockerDaemon, cn as TURN_CONTEXT_TAG, co as createPluginAnnotations, cr as requireReviewItemLinks, da as sleep, do as defaultTimezone, dr as EVERYONE_ASSIGNEE, ea as workspaceSnapshotNotReadyUserMessage, ei as WorkspaceValidationError, en as isToolResultError, er as updateReviewItemContent, f as recordAuthorizationRequested, fa as tryWorkspaceRepoCheckoutPath, fi as deliverOAuthAuthorization, fo as resolveUserTimezone, fr as automationCreatorUserId, g as recordToolExecutionStarted, gn as estimateRequestOverheadTokens, gr as getSlackToolContext, hi as resolveBaseUrl, hn as calculateContextCompactionTargetTokens, hr as resolveChannelCapabilities, i as loadConversationProjection, ia as createSandboxEgressCredentialToken, ii as setWorkspaceSnapshotBuild, in as stripRuntimeTurnContext, ir as canReadReviewItem, ja as canAccessConversation, ji as updateSlackMessage, ki as postSlackMessage, kr as listWatches, l as recordAttachmentsDelivered, li as getSandboxProvider, m as recordMcpProviderConnected, ma as PluginToolDeniedError, mr as resolveAssignees, na as consumeSandboxEgressAuthRequiredSignal, ni as loadSnapshotsForProfile, nn as normalizeToolNameFromResult, no as matchSlackAttachments, oi as hash, on as REQUEST_CONTEXT_SECTION_TAG, or as readReviewItemAgentScope, p as recordGuardianActionReviewed, pa as workspaceRepoCheckoutPath, pi as formatProviderLabel, pr as resolveAssignee, qi as isAbortError, qn as getOpenReviewItemByDedupeKey, qr as createWorkspace, qt as getUserMessageInstructionText, r as loadConnectedMcpProviders, ra as consumeSandboxEgressPermissionDeniedSignal, ri as setWorkspaceSnapshot, rn as retainRuntimeTurnContext, rr as canAgentChangeReviewItem, sa as buildSandboxEgressNetworkPolicy, si as isStale, sn as SESSION_CONTEXT_SECTION_TAG, so as saveObjectAnnotations, sr as requireReviewItemAssignees, ta as clearSandboxEgressSignals, ti as invalidateReadySnapshot, tn as isToolResultMessage, tr as PLUGIN_REVIEW_ITEM_KEY_PREFIX, ua as SANDBOX_RUNTIME, un as buildDeterministicTurnId, va as SANDBOX_DATA_ROOT, vn as getAgentBackgroundCompactionMarkTokens, vo as piMessageFromHistoryItem, vr as RESOURCE_SUBSCRIPTION_MAX_TTL_MS, w as fallbackShortTitle, wa as sandboxSkillFile, wi as deleteSlackMessage, wn as createUserTokenStore, wr as createTimerWatch, xa as SANDBOX_SKILLS_ROOT, xi as slackMention, xo as conversationNoteEvent, xr as cancelSubscriptions, ya as SANDBOX_JUNIOR_ROOT, yi as normalizeSlackReplyMarkdown, yn as getAgentContextCompactionTriggerTokens, yo as projectConversationEvents, yr as RESOURCE_WATCH_TOOL_SOURCE, z as createPluginAuthOrchestration, zi as getSlackClient, zr as getDashboardConversationLink } from "./projection-ii_OYu6z.js";
|
|
3
|
+
import { C as resolveGatewayCredential, S as getGatewayApiKey, _ as createProviderError, a as completeText, c as resolveGatewayModel, d as isCompactionSummaryText, f as renderCurrentInstruction, g as ProviderError, h as escapeXmlText, i as completeObject, l as COMPACTION_SUMMARY_PREFIX, m as escapeXml, n as GEN_AI_SERVER_ADDRESS, p as unwrapCurrentInstruction, t as GEN_AI_PROVIDER_NAME, u as hasCompactedConversationContext, v as findProviderError, x as isProviderRetryError, y as getProviderErrorAttributes } from "./client-BHgCXeaF.js";
|
|
4
|
+
import { _ as toPiReasoningLevel, g as TURN_REASONING_LEVELS, n as botConfig, v as normalizeSlackEmojiName } from "./config-DBdBimZ9.js";
|
|
5
|
+
import { B as runWithLogAttributes, C as summarizeMessageText, E as withSpan, K as toOptionalString, S as setTags, T as withLogContext, U as normalizeIdentityEmail, W as isRecord$4, _ as runBestEffort, a as extractGenAiUsageSummary, b as setSpanAttributes, d as logAudit, f as logError, g as normalizeGenAiFinishReason, h as logWarn, i as extractGenAiUsageAttributes, l as getLogContextAttributesForSpan, m as logInfo, p as logException, u as getTracePropagationHeaders, v as serializeGenAiAttribute, x as setSpanStatus } from "./logging-DapIaJAi.js";
|
|
6
|
+
import { a as toCanonicalInputMessage, c as toGenAiPayloadMetadata, i as runWithConversationPrivacy, l as toGenAiPayloadTraceAttributes, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-DiDh9KE4.js";
|
|
7
7
|
import { d as parseSlackChannelReferenceId, f as parseSlackTeamId, h as parseSlackMessageTs, n as createSlackActor, o as isUserActor, p as parseSlackUserId, u as parseSlackChannelId } from "./actor-6jsm_v96.js";
|
|
8
|
-
import { C as getSqlExecutor, E as treeHasAnnotationKey, F as SYSTEM_IDENTITY_ID, I as resolveActorIdentityId, S as getDb, T as hasAnnotationKey, X as addAgentTurnUsage, Y as touchConversationDetail, Z as agentTurnCostUsd, a as readActorIdentityFromSql, at as sameDestination, b as getConversationMessageSearchStore, et as hasAgentTurnUsage, f as identityAvatarUrl, h as readUserAvatarUrls, i as readActorIdentity, q as conversationDetailTouch, rt as parseDestination, w as conversationIdsWithAnnotation, x as getConversationStore, y as getConversationEventStore } from "./viewer-
|
|
9
|
-
import { A as
|
|
8
|
+
import { C as getSqlExecutor, E as treeHasAnnotationKey, F as SYSTEM_IDENTITY_ID, I as resolveActorIdentityId, S as getDb, T as hasAnnotationKey, X as addAgentTurnUsage, Y as touchConversationDetail, Z as agentTurnCostUsd, a as readActorIdentityFromSql, at as sameDestination, b as getConversationMessageSearchStore, et as hasAgentTurnUsage, f as identityAvatarUrl, h as readUserAvatarUrls, i as readActorIdentity, q as conversationDetailTouch, rt as parseDestination, w as conversationIdsWithAnnotation, x as getConversationStore, y as getConversationEventStore } from "./viewer-C2PztlYX.js";
|
|
9
|
+
import { A as juniorConversations, M as juniorUsers, N as juniorDestinations, O as juniorAttachments, P as juniorArtifacts, _ as juniorConversationParticipants, d as juniorAutomations, f as juniorStats, h as juniorAgentInvocations, j as juniorIdentities, l as juniorAutomationRuns, m as juniorAgentBindings, s as juniorReviewItemSlackCards, y as juniorConversationBriefs } from "./executor-CGqJCxgR.js";
|
|
10
10
|
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-Dq9_svfQ.js";
|
|
11
11
|
import { a as listReferenceFiles, c as soulPathCandidates, l as worldPathCandidates } from "./package-discovery-DJhGdS4c.js";
|
|
12
|
-
import { c as fetchWithBoundedOAuthErrorBodies, d as actorLogContext, f as credentialContextForActor, g as credentialUserSubjectId, i as resolvePluginHeaderEnvRefs, l as getOAuthProviderErrorAttributes, s as OAuthProviderError } from "./registry-
|
|
13
|
-
import { n as pluginCatalogRuntime } from "./catalog-runtime-
|
|
14
|
-
import { a as parseSkillInvocation, i as parseSkillFile, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-
|
|
12
|
+
import { c as fetchWithBoundedOAuthErrorBodies, d as actorLogContext, f as credentialContextForActor, g as credentialUserSubjectId, i as resolvePluginHeaderEnvRefs, l as getOAuthProviderErrorAttributes, s as OAuthProviderError } from "./registry-DpjG3yS-.js";
|
|
13
|
+
import { n as pluginCatalogRuntime } from "./catalog-runtime-Cpje_Uic.js";
|
|
14
|
+
import { a as parseSkillInvocation, i as parseSkillFile, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-DqUUuf4L.js";
|
|
15
15
|
import { a as withLock, i as fenceLock } from "./locks-D-0h111u.js";
|
|
16
|
-
import { r as getStateAdapter } from "./adapter-
|
|
16
|
+
import { r as getStateAdapter } from "./adapter-BAqo7eOH.js";
|
|
17
17
|
import { i as isValidTimeZone, r as getZonedDateTimeParts, t as getFirstRunAtMs } from "./cadence-R7Em4RjE.js";
|
|
18
|
-
import { B as briefLinkSchema,
|
|
19
|
-
import { r as EVENT_AUTHOR_ID } from "./prompt-
|
|
20
|
-
import { A as AgentInvocationLimitError, G as TurnInputCommitLostError, H as formatAgentTypes, I as CHILD_AGENT_RESULTS, L as PARENT_AGENT_TARGET, M as AgentMessageQueueFullError, N as AgentMessageTargetError, P as AgentNameInUseError, R as agentNameSchema, W as CooperativeTurnYieldError, Y as isTurnInputCommitLostError, _ as getLatestAgentInvocationForConversation, d as getAgentInvocationIdForResult, f as getAgentInvocationMessageId, g as getChildAgentLockName, j as AgentMessagePausedError, n as NON_TERMINAL_AGENT_INVOCATION_STATUSES, v as invocationFromRow, y as isTerminalAgentInvocation, z as AGENT_TYPES } from "./store-
|
|
21
|
-
import { i as NO_REPLY_MARKER, n as getAssistantReplyText, o as isNoReplyMarker, r as sanitizeAssistantText, t as decideReply } from "./assistant-reply-
|
|
22
|
-
import { B as remindMissingAutomationResult, F as automationResultSchema$1, O as resolveSlackReplyTarget, P as FINISH_AUTOMATION_RUN_TOOL_NAME, _ 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, z as readAutomationResult } from "./session-stop-
|
|
18
|
+
import { B as briefLinkSchema, N as removedCardSchema, V as briefOutcomeStatusSchema, W as parseStoredBrief } from "./conversation-DNtcULyX.js";
|
|
19
|
+
import { r as EVENT_AUTHOR_ID } from "./prompt-DI6KCtwb.js";
|
|
20
|
+
import { A as AgentInvocationLimitError, G as TurnInputCommitLostError, H as formatAgentTypes, I as CHILD_AGENT_RESULTS, L as PARENT_AGENT_TARGET, M as AgentMessageQueueFullError, N as AgentMessageTargetError, P as AgentNameInUseError, R as agentNameSchema, W as CooperativeTurnYieldError, Y as isTurnInputCommitLostError, _ as getLatestAgentInvocationForConversation, d as getAgentInvocationIdForResult, f as getAgentInvocationMessageId, g as getChildAgentLockName, j as AgentMessagePausedError, n as NON_TERMINAL_AGENT_INVOCATION_STATUSES, v as invocationFromRow, y as isTerminalAgentInvocation, z as AGENT_TYPES } from "./store-nETG4KVg.js";
|
|
21
|
+
import { i as NO_REPLY_MARKER, n as getAssistantReplyText, o as isNoReplyMarker, r as sanitizeAssistantText, t as decideReply } from "./assistant-reply-4Wvo95-N.js";
|
|
22
|
+
import { B as remindMissingAutomationResult, F as automationResultSchema$1, O as resolveSlackReplyTarget, P as FINISH_AUTOMATION_RUN_TOOL_NAME, _ 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, z as readAutomationResult } from "./session-stop-CVEEx_YD.js";
|
|
23
23
|
import { E 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, w as USER_CUSTOMIZATION_MAX_CHARS, y as userInputRequestSchema } from "./reporting-window-B-QP9zX1.js";
|
|
24
|
-
import { a as setSnapshotSpanAttributes, i as postinstall, n as resolve$1, r as dependencies, s as getSandboxResources } from "./resolve-
|
|
25
|
-
import { f as QUEUE_SIGNATURE_MAX_AGE_MS, g as getTurnRequestDeadline, l as getVercelConversationWorkQueue, n as backgroundCompactionId, o as sendNextWorkspaceSnapshotJob, s as sendWorkspaceSnapshotJob } from "./background-compaction-queue-
|
|
26
|
-
import { D as stopConversationWork, n as appendAndEnqueueExclusiveInboundMessage, r as appendAndEnqueueInboundMessage } from "./store-
|
|
27
|
-
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-
|
|
28
|
-
import { _ as getMcpProviderErrorAttributes, a as serviceAccountOnly, c as createMcpServiceAccountClientProvider, d as PluginMcpClient, f as McpProviderError, g as getMcpAwareTelemetryMessage, h as getMcpAwareErrorType, i as serviceAccountAllows, l as getMcpServiceAccountCredentials, m as McpToolError, p as McpServiceAccountRequiredError, u as McpAuthorizationRequiredError, v as toMcpProviderError } from "./service-account-
|
|
29
|
-
import { A as SCHEDULED_AUTOMATION_SYSTEM_ACTOR, D as taskOutcomeInputSchema, E as automationTitleSchema, F as scheduleIntentFromTool, I as toolScheduleIntentSchema, L as weekdaySchema, N as ScheduleIntentError, P as compileScheduleIntent, T as automationInstructionToolSchema, k as eventAutomationTriggerSchema, l as automationListQuerySchema } from "./automation-
|
|
24
|
+
import { a as setSnapshotSpanAttributes, i as postinstall, n as resolve$1, r as dependencies, s as getSandboxResources } from "./resolve-iMW9Dgo2.js";
|
|
25
|
+
import { f as QUEUE_SIGNATURE_MAX_AGE_MS, g as getTurnRequestDeadline, l as getVercelConversationWorkQueue, n as backgroundCompactionId, o as sendNextWorkspaceSnapshotJob, s as sendWorkspaceSnapshotJob } from "./background-compaction-queue-CoWqScCC.js";
|
|
26
|
+
import { D as stopConversationWork, n as appendAndEnqueueExclusiveInboundMessage, r as appendAndEnqueueInboundMessage } from "./store-nu3Xx08K.js";
|
|
27
|
+
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-BIJGJjVh.js";
|
|
28
|
+
import { _ as getMcpProviderErrorAttributes, a as serviceAccountOnly, c as createMcpServiceAccountClientProvider, d as PluginMcpClient, f as McpProviderError, g as getMcpAwareTelemetryMessage, h as getMcpAwareErrorType, i as serviceAccountAllows, l as getMcpServiceAccountCredentials, m as McpToolError, p as McpServiceAccountRequiredError, u as McpAuthorizationRequiredError, v as toMcpProviderError } from "./service-account-Dfl9Pitm.js";
|
|
29
|
+
import { A as SCHEDULED_AUTOMATION_SYSTEM_ACTOR, D as taskOutcomeInputSchema, E as automationTitleSchema, F as scheduleIntentFromTool, I as toolScheduleIntentSchema, L as weekdaySchema, N as ScheduleIntentError, P as compileScheduleIntent, T as automationInstructionToolSchema, k as eventAutomationTriggerSchema, l as automationListQuerySchema } from "./automation-sIsmIXH7.js";
|
|
30
30
|
import { n as privateTraceResultAttributes } from "./private-trace-result-CE7_lEdq.js";
|
|
31
31
|
import { streamSimple } from "@earendil-works/pi-ai/compat";
|
|
32
32
|
import { createGatewayProvider } from "@ai-sdk/gateway";
|
|
@@ -5266,6 +5266,7 @@ function createWorkspaceSnapshotNotReadyToolResult(cause) {
|
|
|
5266
5266
|
message: workspaceSnapshotNotReadyUserMessage(notReady)
|
|
5267
5267
|
});
|
|
5268
5268
|
}
|
|
5269
|
+
const VERCEL_FIREWALL_CHALLENGE_MARKER = "Vercel Security Checkpoint";
|
|
5269
5270
|
const SANDBOX_TOOL_NAMES = /* @__PURE__ */ new Set([
|
|
5270
5271
|
"bash",
|
|
5271
5272
|
"readFile",
|
|
@@ -5439,6 +5440,7 @@ function createSandbox(options) {
|
|
|
5439
5440
|
"app.sandbox.stderr_bytes": Buffer.byteLength(response.stderr ?? "", "utf8"),
|
|
5440
5441
|
...response.aborted ? { "error.type": "outcome_unknown" } : response.exitCode !== 0 ? { "error.type": "nonzero_exit" } : {}
|
|
5441
5442
|
});
|
|
5443
|
+
if (`${response.stdout ?? ""}${response.stderr ?? ""}`.includes(VERCEL_FIREWALL_CHALLENGE_MARKER)) logWarn("sandbox.egress.challenged", { "app.sandbox.egress_id": activeSessionId });
|
|
5442
5444
|
setSpanStatus(response.exitCode === 0 ? "ok" : "error");
|
|
5443
5445
|
return response;
|
|
5444
5446
|
});
|
|
@@ -7315,7 +7317,7 @@ async function searchTopLevelAgents(args) {
|
|
|
7315
7317
|
status: juniorConversations.executionStatus,
|
|
7316
7318
|
title: juniorConversations.title
|
|
7317
7319
|
}).from(juniorConversations).innerJoin(juniorDestinations, eq(juniorDestinations.id, juniorConversations.destinationId)).leftJoin(juniorConversationParticipants, and(eq(juniorConversationParticipants.rootConversationId, juniorConversations.conversationId), eq(juniorConversationParticipants.userId, viewer?.id ?? ""))).leftJoin(briefs, and(eq(briefs.conversationId, juniorConversations.conversationId), notExists(db.select({ one: sql`1` }).from(newer).where(and(eq(newer.conversationId, briefs.conversationId), gt(newer.version, briefs.version)))))).where(and(...conditions)).orderBy(...order).limit(search.limit)).map((row) => {
|
|
7318
|
-
const brief = row.briefContent ?
|
|
7320
|
+
const brief = row.briefContent ? parseStoredBrief(row.briefContent) : void 0;
|
|
7319
7321
|
return {
|
|
7320
7322
|
archived: row.archivedAt !== null,
|
|
7321
7323
|
conversationId: row.conversationId,
|
|
@@ -15469,7 +15471,7 @@ async function searchConversationBriefs(db, args) {
|
|
|
15469
15471
|
updatedAt: briefs.createdAt,
|
|
15470
15472
|
version: briefs.version
|
|
15471
15473
|
}).from(briefs).innerJoin(juniorConversations, eq(juniorConversations.conversationId, briefs.conversationId)).innerJoin(juniorDestinations, eq(juniorDestinations.id, juniorConversations.destinationId)).where(and(...conditions)).orderBy(desc(rank), desc(briefs.createdAt)).limit(args.limit)).map((row) => {
|
|
15472
|
-
const content =
|
|
15474
|
+
const content = parseStoredBrief(row.content);
|
|
15473
15475
|
return {
|
|
15474
15476
|
conversationId: row.conversationId,
|
|
15475
15477
|
excerpt: row.excerpt,
|
|
@@ -19787,12 +19789,7 @@ async function readRootConversation(args) {
|
|
|
19787
19789
|
};
|
|
19788
19790
|
}
|
|
19789
19791
|
// src/chat/agent/tools.ts
|
|
19790
|
-
/**
|
|
19791
|
-
* Create the run's sandbox handle without acquiring a sandbox.
|
|
19792
|
-
*
|
|
19793
|
-
* It does not depend on the Turn route, so the caller can start sandbox
|
|
19794
|
-
* setup while the router runs.
|
|
19795
|
-
*/
|
|
19792
|
+
/** Create the run's sandbox handle without acquiring a sandbox. */
|
|
19796
19793
|
async function createRunSandbox(args) {
|
|
19797
19794
|
const pluginHooks = createPluginHookRunner({
|
|
19798
19795
|
actor: args.currentActor,
|
|
@@ -20345,69 +20342,120 @@ function createResumeState(args) {
|
|
|
20345
20342
|
}
|
|
20346
20343
|
};
|
|
20347
20344
|
}
|
|
20348
|
-
// src/chat/
|
|
20349
|
-
|
|
20350
|
-
|
|
20351
|
-
|
|
20352
|
-
|
|
20353
|
-
|
|
20354
|
-
|
|
20355
|
-
|
|
20356
|
-
|
|
20357
|
-
|
|
20358
|
-
|
|
20359
|
-
|
|
20360
|
-
|
|
20345
|
+
// src/chat/agent/context-summary.ts
|
|
20346
|
+
/** Prompt name of the summary request on its `gen_ai.chat` span. */
|
|
20347
|
+
const CONTEXT_COMPACTION_PROMPT_NAME = "junior.context_compaction";
|
|
20348
|
+
const SUMMARY_MAX_TOKENS = 8e3;
|
|
20349
|
+
const SUMMARY_INSTRUCTION = `Stop work on the task now. Do not call tools. Write a summary of the conversation so far. The summary replaces the earlier history, and you will continue the work from the summary alone.
|
|
20350
|
+
|
|
20351
|
+
Return only the summary inside <summary></summary> tags. Use these sections in this order. Write each item as one short line that starts with "- ". Write "- None" for an empty section.
|
|
20352
|
+
|
|
20353
|
+
## Goal
|
|
20354
|
+
## Constraints & preferences
|
|
20355
|
+
## Progress
|
|
20356
|
+
### Done
|
|
20357
|
+
### In progress
|
|
20358
|
+
### Blocked
|
|
20359
|
+
## Key decisions
|
|
20360
|
+
## Open asks
|
|
20361
|
+
User requests that are not complete yet, quoted in the user's exact words.
|
|
20362
|
+
## References
|
|
20363
|
+
Exact file paths, IDs, URLs, commands, and error text that the work needs. At most 20 items.
|
|
20364
|
+
## Next steps
|
|
20365
|
+
|
|
20366
|
+
Rules:
|
|
20367
|
+
- Keep the summary under 1,000 words.
|
|
20368
|
+
- Leave out the system prompt, AGENTS.md instructions, tool descriptions, and environment details. They are added again.
|
|
20369
|
+
- Do not mention this request or the summary itself.
|
|
20370
|
+
- If the history contains an earlier summary, update it. Keep the items that are still true, move finished work to Done, and remove stale items. When the earlier summary and newer history disagree, use the newer history.`;
|
|
20371
|
+
const SUMMARY_NUDGE = "Do not call tools. Keep the summary short. Return only the summary inside <summary></summary> tags.";
|
|
20372
|
+
/** Raised when the model returns no usable summary after one nudge. */
|
|
20373
|
+
var ContextSummaryError = class extends Error {
|
|
20374
|
+
failure;
|
|
20375
|
+
constructor(failure) {
|
|
20376
|
+
super(`Context summary failed: ${failure}`);
|
|
20377
|
+
this.failure = failure;
|
|
20378
|
+
this.name = "ContextSummaryError";
|
|
20379
|
+
}
|
|
20380
|
+
};
|
|
20381
|
+
/**
|
|
20382
|
+
* Build the model request that the agent loop sends for these messages.
|
|
20383
|
+
*
|
|
20384
|
+
* This repeats the steps of pi-agent-core before each model call
|
|
20385
|
+
* (`streamAssistantResponse` and `createLoopConfig`, which Pi does not
|
|
20386
|
+
* export): transform and convert the messages, then read the model,
|
|
20387
|
+
* reasoning, tools, and request options from the agent. A unit test compares
|
|
20388
|
+
* this request with the one that a real Pi `Agent` loop passes to `streamFn`,
|
|
20389
|
+
* so it fails when Pi changes these steps.
|
|
20390
|
+
*/
|
|
20391
|
+
async function buildAgentModelRequest(agent, messages, signal) {
|
|
20392
|
+
const { model, systemPrompt, thinkingLevel, tools } = agent.state;
|
|
20393
|
+
const transformed = agent.transformContext ? await agent.transformContext(messages, signal) : messages;
|
|
20394
|
+
return {
|
|
20395
|
+
model,
|
|
20396
|
+
context: {
|
|
20397
|
+
systemPrompt,
|
|
20398
|
+
messages: await agent.convertToLlm(transformed),
|
|
20399
|
+
tools
|
|
20400
|
+
},
|
|
20401
|
+
options: {
|
|
20402
|
+
reasoning: thinkingLevel === "off" ? void 0 : thinkingLevel,
|
|
20403
|
+
sessionId: agent.sessionId,
|
|
20404
|
+
onPayload: agent.onPayload,
|
|
20405
|
+
onResponse: agent.onResponse,
|
|
20406
|
+
transport: agent.transport,
|
|
20407
|
+
thinkingBudgets: agent.thinkingBudgets,
|
|
20408
|
+
maxRetryDelayMs: agent.maxRetryDelayMs,
|
|
20409
|
+
apiKey: await agent.getApiKey?.(model.provider) || void 0,
|
|
20410
|
+
signal
|
|
20411
|
+
}
|
|
20412
|
+
};
|
|
20361
20413
|
}
|
|
20362
|
-
function
|
|
20363
|
-
|
|
20364
|
-
|
|
20365
|
-
|
|
20366
|
-
|
|
20367
|
-
|
|
20368
|
-
|
|
20414
|
+
function userText(text) {
|
|
20415
|
+
return {
|
|
20416
|
+
role: "user",
|
|
20417
|
+
content: [{
|
|
20418
|
+
type: "text",
|
|
20419
|
+
text
|
|
20420
|
+
}],
|
|
20421
|
+
timestamp: Date.now()
|
|
20422
|
+
};
|
|
20369
20423
|
}
|
|
20370
|
-
function
|
|
20371
|
-
const
|
|
20372
|
-
|
|
20373
|
-
|
|
20374
|
-
|
|
20375
|
-
|
|
20376
|
-
|
|
20377
|
-
|
|
20378
|
-
if (
|
|
20379
|
-
|
|
20380
|
-
try {
|
|
20381
|
-
return openItems({ plan: JSON.parse(payload) });
|
|
20382
|
-
} catch {
|
|
20383
|
-
return;
|
|
20384
|
-
}
|
|
20424
|
+
async function complete(request, streamFn, appended) {
|
|
20425
|
+
const message = await (await streamFn(request.model, {
|
|
20426
|
+
...request.context,
|
|
20427
|
+
messages: [...request.context.messages, ...appended]
|
|
20428
|
+
}, {
|
|
20429
|
+
...request.options,
|
|
20430
|
+
maxTokens: SUMMARY_MAX_TOKENS
|
|
20431
|
+
})).result();
|
|
20432
|
+
if (message.stopReason === "error" || message.stopReason === "aborted") throw createProviderError(message.errorMessage ?? message.stopReason, { modelId: request.model.id });
|
|
20433
|
+
return message;
|
|
20385
20434
|
}
|
|
20386
|
-
/** Read
|
|
20387
|
-
function
|
|
20388
|
-
|
|
20389
|
-
|
|
20390
|
-
|
|
20391
|
-
|
|
20392
|
-
|
|
20393
|
-
|
|
20394
|
-
}
|
|
20395
|
-
if (message.role === "user") {
|
|
20396
|
-
const retained = retainedOpenItems(messages[messageIndex]);
|
|
20397
|
-
if (retained) return retained;
|
|
20398
|
-
}
|
|
20399
|
-
if (message.role !== "assistant" || !Array.isArray(message.content)) continue;
|
|
20400
|
-
for (let partIndex = message.content.length - 1; partIndex >= 0; partIndex -= 1) {
|
|
20401
|
-
const call = message.content[partIndex];
|
|
20402
|
-
if (call?.type === "toolCall" && call.name === "updatePlan" && typeof call.id === "string" && successfulCalls.has(call.id)) return openItems(call.arguments);
|
|
20403
|
-
}
|
|
20404
|
-
}
|
|
20405
|
-
return [];
|
|
20435
|
+
/** Read the summary, or name why the output is not a usable summary. */
|
|
20436
|
+
function readSummary(message) {
|
|
20437
|
+
if (message.content.some((part) => part.type === "toolCall")) return { failure: "tool_call" };
|
|
20438
|
+
if (message.stopReason === "length") return { failure: "max_tokens" };
|
|
20439
|
+
const text = message.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("").trim();
|
|
20440
|
+
if (!text) return { failure: "empty" };
|
|
20441
|
+
const summary = /<summary>([\s\S]*?)<\/summary>/.exec(text)?.[1]?.trim();
|
|
20442
|
+
return summary ? { summary } : { failure: "missing_summary" };
|
|
20406
20443
|
}
|
|
20407
|
-
/**
|
|
20408
|
-
|
|
20409
|
-
|
|
20410
|
-
|
|
20444
|
+
/**
|
|
20445
|
+
* Ask the agent model for a summary of the request messages.
|
|
20446
|
+
*
|
|
20447
|
+
* A tool call, a stop at the output limit, empty output, or output without
|
|
20448
|
+
* `<summary>` tags gets one nudge. A second failure throws
|
|
20449
|
+
* `ContextSummaryError`, so the caller keeps the full history.
|
|
20450
|
+
*/
|
|
20451
|
+
async function requestContextSummary(request, streamFn) {
|
|
20452
|
+
const instruction = userText(SUMMARY_INSTRUCTION);
|
|
20453
|
+
const first = readSummary(await complete(request, streamFn, [instruction]));
|
|
20454
|
+
if ("summary" in first) return first.summary;
|
|
20455
|
+
logWarn("context_compaction.summary.nudged", { "app.compaction.summary_failure": first.failure });
|
|
20456
|
+
const second = readSummary(await complete(request, streamFn, [instruction, userText(SUMMARY_NUDGE)]));
|
|
20457
|
+
if ("summary" in second) return second.summary;
|
|
20458
|
+
throw new ContextSummaryError(second.failure);
|
|
20411
20459
|
}
|
|
20412
20460
|
// src/chat/services/context-compaction-telemetry.ts
|
|
20413
20461
|
/**
|
|
@@ -20441,1000 +20489,963 @@ async function measureTurnCompactionWait(setTurnAttributes, callback) {
|
|
|
20441
20489
|
if (wait.ms > 0) setTurnAttributes({ "app.turn.compaction_wait_ms": Math.round(wait.ms) });
|
|
20442
20490
|
}
|
|
20443
20491
|
}
|
|
20444
|
-
// src/chat/services/
|
|
20492
|
+
// src/chat/services/background-compaction.ts
|
|
20445
20493
|
/**
|
|
20446
|
-
*
|
|
20494
|
+
* Background compaction: prepare a summary before the history is full.
|
|
20447
20495
|
*
|
|
20448
|
-
*
|
|
20449
|
-
*
|
|
20450
|
-
* asks the agent model
|
|
20451
|
-
*
|
|
20452
|
-
*
|
|
20453
|
-
*
|
|
20496
|
+
* After each model request at or above the mark, also in the middle of a
|
|
20497
|
+
* Turn, the Turn appends `compaction_requested` and sends a job. The job
|
|
20498
|
+
* asks the agent model for a summary of the history up to the marked event
|
|
20499
|
+
* and appends `compaction_prepared`. Turns keep the full history until a later
|
|
20500
|
+
* change swaps the summary in. Blocking compaction stays the fallback.
|
|
20501
|
+
*
|
|
20502
|
+
* The summary request repeats the system prompt and tools of the last agent
|
|
20503
|
+
* request, so the provider can read its cached prompt prefix. The job runs in
|
|
20504
|
+
* another request, so the Turn stores them in the State adapter.
|
|
20454
20505
|
*/
|
|
20455
|
-
|
|
20456
|
-
|
|
20457
|
-
|
|
20458
|
-
|
|
20459
|
-
|
|
20460
|
-
|
|
20461
|
-
|
|
20462
|
-
|
|
20463
|
-
|
|
20464
|
-
|
|
20506
|
+
/**
|
|
20507
|
+
* Failed or discarded attempts for one History version before background
|
|
20508
|
+
* tries stop.
|
|
20509
|
+
*/
|
|
20510
|
+
const MAX_FAILED_ATTEMPTS = 2;
|
|
20511
|
+
/**
|
|
20512
|
+
* A request without a prepared result after this long counts as a failed
|
|
20513
|
+
* attempt, so a later Turn can request again. This covers a lost job.
|
|
20514
|
+
*/
|
|
20515
|
+
const REQUEST_TIMEOUT_MS = 6e5;
|
|
20516
|
+
/** The queue drops a message after this long, so the snapshot can go too. */
|
|
20517
|
+
const SNAPSHOT_TTL_MS = QUEUE_SIGNATURE_MAX_AGE_MS;
|
|
20518
|
+
function snapshotKey(message) {
|
|
20519
|
+
return `${backgroundCompactionId(message)}:snapshot`;
|
|
20520
|
+
}
|
|
20521
|
+
/** Provider-reported input of the last model request, cache included. */
|
|
20522
|
+
function lastRequestInputSize(messages) {
|
|
20523
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
20524
|
+
const message = messages[index];
|
|
20525
|
+
if (message.role === "assistant") {
|
|
20526
|
+
const { input, cacheRead, cacheWrite } = message.usage;
|
|
20527
|
+
return input + cacheRead + cacheWrite;
|
|
20528
|
+
}
|
|
20465
20529
|
}
|
|
20466
|
-
};
|
|
20467
|
-
function textPart(value) {
|
|
20468
|
-
if (value && typeof value === "object" && value.type === "text" && typeof value.text === "string") return value.text;
|
|
20469
20530
|
}
|
|
20470
|
-
/**
|
|
20471
|
-
|
|
20472
|
-
|
|
20473
|
-
|
|
20474
|
-
|
|
20475
|
-
|
|
20476
|
-
|
|
20531
|
+
/**
|
|
20532
|
+
* Return whether a Turn may request a background summary for this History
|
|
20533
|
+
* version. It may not while a request is pending, while a ready summary is
|
|
20534
|
+
* still unused, or after the attempt limit.
|
|
20535
|
+
*
|
|
20536
|
+
* A Turn swaps a ready summary in before its first model request. A swap
|
|
20537
|
+
* makes a new History version. So a ready summary of this version that was
|
|
20538
|
+
* prepared before the Turn started was discarded, for example because the
|
|
20539
|
+
* history after its mark is too large now. It counts as a failed attempt, so
|
|
20540
|
+
* a new request can replace it.
|
|
20541
|
+
*/
|
|
20542
|
+
function mayRequest(events, historyVersion, nowMs, turnStartedAtMs) {
|
|
20543
|
+
const outcomes = /* @__PURE__ */ new Map();
|
|
20544
|
+
for (const event of events) if (event.data.type === "compaction_prepared" && event.data.historyVersion === historyVersion) outcomes.set(event.data.markSeq, {
|
|
20545
|
+
outcome: event.data.outcome,
|
|
20546
|
+
createdAtMs: event.createdAtMs
|
|
20547
|
+
});
|
|
20548
|
+
let failed = 0;
|
|
20549
|
+
for (const event of events) {
|
|
20550
|
+
if (event.data.type !== "compaction_requested" || event.data.historyVersion !== historyVersion) continue;
|
|
20551
|
+
const prepared = outcomes.get(event.data.markSeq);
|
|
20552
|
+
if (prepared?.outcome === "ready" && prepared.createdAtMs >= turnStartedAtMs) return false;
|
|
20553
|
+
if (prepared || nowMs - event.createdAtMs >= REQUEST_TIMEOUT_MS) failed += 1;
|
|
20554
|
+
else return false;
|
|
20555
|
+
}
|
|
20556
|
+
return failed < MAX_FAILED_ATTEMPTS;
|
|
20477
20557
|
}
|
|
20478
|
-
|
|
20479
|
-
|
|
20480
|
-
|
|
20481
|
-
|
|
20482
|
-
|
|
20483
|
-
|
|
20484
|
-
|
|
20558
|
+
/**
|
|
20559
|
+
* Find the newest background compaction fact of the current History version.
|
|
20560
|
+
* Facts of earlier versions belong to history that a replacement already
|
|
20561
|
+
* removed.
|
|
20562
|
+
*/
|
|
20563
|
+
async function loadLatestBackgroundCompaction(conversationId) {
|
|
20564
|
+
const store = getConversationEventStore();
|
|
20565
|
+
const [historyVersion, page] = await Promise.all([store.loadCurrentHistoryVersion(conversationId), store.query(conversationId, {
|
|
20566
|
+
limit: 1,
|
|
20567
|
+
types: ["compaction_requested", "compaction_prepared"]
|
|
20568
|
+
})]);
|
|
20569
|
+
const event = page.events.at(-1);
|
|
20570
|
+
return event && event.historyVersion === historyVersion ? {
|
|
20571
|
+
event,
|
|
20572
|
+
historyVersion
|
|
20573
|
+
} : void 0;
|
|
20485
20574
|
}
|
|
20486
|
-
|
|
20487
|
-
|
|
20575
|
+
/**
|
|
20576
|
+
* Return whether the newest fact is a pending request or a summary that
|
|
20577
|
+
* became ready in this execution slice. Then `mayRequest` is false too, so a
|
|
20578
|
+
* Turn can skip the full history load. Only one request is pending at a time,
|
|
20579
|
+
* so the newest fact decides it.
|
|
20580
|
+
*/
|
|
20581
|
+
function waitsForUse(event, nowMs, turnStartedAtMs) {
|
|
20582
|
+
if (event.data.type === "compaction_requested") return nowMs - event.createdAtMs < REQUEST_TIMEOUT_MS;
|
|
20583
|
+
return event.data.type === "compaction_prepared" && event.data.outcome === "ready" && event.createdAtMs >= turnStartedAtMs;
|
|
20488
20584
|
}
|
|
20489
|
-
|
|
20490
|
-
|
|
20585
|
+
/**
|
|
20586
|
+
* Request a background summary when the model request that just ended was at
|
|
20587
|
+
* or above the mark.
|
|
20588
|
+
*
|
|
20589
|
+
* The agent runs it after each model request, so a long Turn gets a summary
|
|
20590
|
+
* before the compaction threshold. `turnStartedAtMs` is when this execution
|
|
20591
|
+
* slice started, before its first model request. Without a queue or below the
|
|
20592
|
+
* mark, it does nothing. A failure here leaves blocking compaction as the
|
|
20593
|
+
* fallback, so it is logged and does not fail the Turn. When the send fails
|
|
20594
|
+
* after the request is written, the request times out and counts as a
|
|
20595
|
+
* failed attempt.
|
|
20596
|
+
*/
|
|
20597
|
+
async function requestBackgroundCompaction(args) {
|
|
20598
|
+
if (!args.queue) return;
|
|
20599
|
+
const inputSize = lastRequestInputSize(args.agent.state.messages);
|
|
20600
|
+
if (inputSize === void 0 || inputSize < getAgentBackgroundCompactionMarkTokens(args.modelId)) return;
|
|
20601
|
+
try {
|
|
20602
|
+
await requestAboveMark({
|
|
20603
|
+
...args,
|
|
20604
|
+
inputSize,
|
|
20605
|
+
queue: args.queue
|
|
20606
|
+
});
|
|
20607
|
+
} catch (error) {
|
|
20608
|
+
logWarn("context_compaction.background.request_failed", { "error.type": error instanceof Error ? error.name : typeof error });
|
|
20609
|
+
}
|
|
20491
20610
|
}
|
|
20492
|
-
|
|
20493
|
-
|
|
20494
|
-
|
|
20495
|
-
|
|
20496
|
-
|
|
20497
|
-
|
|
20498
|
-
|
|
20499
|
-
|
|
20500
|
-
|
|
20611
|
+
async function requestAboveMark(args) {
|
|
20612
|
+
const nowMs = Date.now();
|
|
20613
|
+
const latest = await loadLatestBackgroundCompaction(args.conversationId);
|
|
20614
|
+
if (latest && waitsForUse(latest.event, nowMs, args.turnStartedAtMs)) return;
|
|
20615
|
+
const eventStore = getConversationEventStore();
|
|
20616
|
+
const events = await eventStore.loadCurrentHistory(args.conversationId);
|
|
20617
|
+
const historyVersion = events[0]?.historyVersion;
|
|
20618
|
+
if (historyVersion === void 0 || !mayRequest(events, historyVersion, nowMs, args.turnStartedAtMs)) return;
|
|
20619
|
+
const projection = projectConversationEvents(events);
|
|
20620
|
+
const markSeq = Math.max(projection.seqs.at(-1) ?? -1, projection.replacementSeq ?? -1);
|
|
20621
|
+
if (markSeq < 0) return;
|
|
20622
|
+
const message = {
|
|
20623
|
+
conversationId: args.conversationId,
|
|
20624
|
+
historyVersion,
|
|
20625
|
+
markSeq
|
|
20501
20626
|
};
|
|
20627
|
+
const { systemPrompt, thinkingLevel, tools } = args.agent.state;
|
|
20628
|
+
const snapshot = {
|
|
20629
|
+
conversationPrivacy: args.conversationPrivacy ?? "private",
|
|
20630
|
+
inputSize: args.inputSize,
|
|
20631
|
+
modelId: args.modelId,
|
|
20632
|
+
systemPrompt,
|
|
20633
|
+
thinkingLevel,
|
|
20634
|
+
tools: tools.map((tool) => ({
|
|
20635
|
+
name: tool.name,
|
|
20636
|
+
label: tool.label,
|
|
20637
|
+
description: tool.description,
|
|
20638
|
+
parameters: tool.parameters,
|
|
20639
|
+
...tool.constrainedSampling === void 0 ? void 0 : { constrainedSampling: tool.constrainedSampling }
|
|
20640
|
+
}))
|
|
20641
|
+
};
|
|
20642
|
+
await getStateAdapter().set(snapshotKey(message), JSON.parse(JSON.stringify(snapshot)), SNAPSHOT_TTL_MS);
|
|
20643
|
+
if ((await eventStore.append(args.conversationId, [{
|
|
20644
|
+
idempotencyKey: `${backgroundCompactionId(message)}:requested`,
|
|
20645
|
+
createdAtMs: nowMs,
|
|
20646
|
+
data: {
|
|
20647
|
+
type: "compaction_requested",
|
|
20648
|
+
markSeq,
|
|
20649
|
+
historyVersion,
|
|
20650
|
+
modelId: args.modelId
|
|
20651
|
+
}
|
|
20652
|
+
}], { activity: "preserve" })).length === 0) return;
|
|
20653
|
+
await args.queue.send(message);
|
|
20654
|
+
logInfo("context_compaction.background.requested", {
|
|
20655
|
+
"app.compaction.mark_seq": markSeq,
|
|
20656
|
+
"app.compaction.history_version": historyVersion,
|
|
20657
|
+
"app.compaction.input.size": args.inputSize
|
|
20658
|
+
});
|
|
20502
20659
|
}
|
|
20503
|
-
|
|
20504
|
-
|
|
20505
|
-
|
|
20506
|
-
|
|
20507
|
-
|
|
20508
|
-
return
|
|
20509
|
-
}
|
|
20510
|
-
function isSessionTurnContext(text) {
|
|
20511
|
-
return text?.startsWith(`<runtime-turn-context>`) === true && text.includes(`\n<runtime>\n`);
|
|
20512
|
-
}
|
|
20513
|
-
/** Remove the sections that only the Turn that received them can use. */
|
|
20514
|
-
function withoutRequestContext(text) {
|
|
20515
|
-
return Object.values(REQUEST_CONTEXT_SECTION_TAG).reduce((result, tag) => result.replace(new RegExp(`\\n\\n<${tag}>\\n[\\s\\S]*?\\n</${tag}>`, "g"), ""), text);
|
|
20660
|
+
/** A fixed label for a failed summary. Never raw exception text. */
|
|
20661
|
+
function failureLabel(error, signal) {
|
|
20662
|
+
if (signal.aborted) return "timeout";
|
|
20663
|
+
if (error instanceof ContextSummaryError) return error.failure;
|
|
20664
|
+
const providerError = findProviderError(error);
|
|
20665
|
+
return providerError ? `provider_${providerError.kind}` : "summary_error";
|
|
20516
20666
|
}
|
|
20517
|
-
/**
|
|
20518
|
-
|
|
20519
|
-
|
|
20520
|
-
|
|
20521
|
-
|
|
20522
|
-
|
|
20523
|
-
|
|
20524
|
-
|
|
20525
|
-
|
|
20526
|
-
|
|
20527
|
-
|
|
20528
|
-
|
|
20529
|
-
|
|
20667
|
+
/**
|
|
20668
|
+
* Run one background compaction job.
|
|
20669
|
+
*
|
|
20670
|
+
* It writes `compaction_prepared` once for the request, with a summary or a
|
|
20671
|
+
* fixed failure label. It writes nothing when the request is no longer in
|
|
20672
|
+
* the current History version, because no Turn could use the summary.
|
|
20673
|
+
* `streamFn` replaces the model stream, for tests.
|
|
20674
|
+
*/
|
|
20675
|
+
async function processBackgroundCompaction(message, options = {}) {
|
|
20676
|
+
const startedAtMs = Date.now();
|
|
20677
|
+
await withLogContext({ conversationId: message.conversationId }, () => withCompactionSpan("background", async () => {
|
|
20678
|
+
setSpanAttributes({
|
|
20679
|
+
"app.compaction.mark_seq": message.markSeq,
|
|
20680
|
+
"app.compaction.history_version": message.historyVersion,
|
|
20681
|
+
...options.enqueuedAtMs === void 0 ? void 0 : { "app.compaction.queue_wait_ms": Math.max(0, startedAtMs - options.enqueuedAtMs) }
|
|
20682
|
+
});
|
|
20683
|
+
const outcome = await prepareSummary(message, options.streamFn);
|
|
20684
|
+
setSpanAttributes({ "app.compaction.outcome": outcome });
|
|
20685
|
+
}));
|
|
20530
20686
|
}
|
|
20531
|
-
function
|
|
20532
|
-
|
|
20533
|
-
|
|
20534
|
-
|
|
20535
|
-
|
|
20687
|
+
async function prepareSummary(message, streamFn) {
|
|
20688
|
+
const eventStore = getConversationEventStore();
|
|
20689
|
+
const state = getStateAdapter();
|
|
20690
|
+
const events = await eventStore.loadCurrentHistory(message.conversationId);
|
|
20691
|
+
const isThisRequest = (event) => (event.data.type === "compaction_requested" || event.data.type === "compaction_prepared") && event.data.historyVersion === message.historyVersion && event.data.markSeq === message.markSeq;
|
|
20692
|
+
const request = events.find((event) => isThisRequest(event) && event.data.type === "compaction_requested");
|
|
20693
|
+
if (request?.data.type !== "compaction_requested") {
|
|
20694
|
+
await state.delete(snapshotKey(message));
|
|
20695
|
+
return "stale";
|
|
20536
20696
|
}
|
|
20537
|
-
const
|
|
20538
|
-
|
|
20539
|
-
|
|
20540
|
-
|
|
20541
|
-
|
|
20542
|
-
|
|
20543
|
-
|
|
20544
|
-
|
|
20545
|
-
|
|
20546
|
-
|
|
20547
|
-
|
|
20548
|
-
|
|
20549
|
-
|
|
20550
|
-
|
|
20551
|
-
|
|
20552
|
-
|
|
20697
|
+
const requested = request.data;
|
|
20698
|
+
if (events.some((event) => isThisRequest(event) && event.data.type === "compaction_prepared")) return "duplicate";
|
|
20699
|
+
const writePrepared = async (result) => {
|
|
20700
|
+
if (await eventStore.loadCurrentHistoryVersion(message.conversationId) !== message.historyVersion) {
|
|
20701
|
+
await state.delete(snapshotKey(message));
|
|
20702
|
+
return "stale";
|
|
20703
|
+
}
|
|
20704
|
+
await eventStore.append(message.conversationId, [{
|
|
20705
|
+
idempotencyKey: `${backgroundCompactionId(message)}:prepared`,
|
|
20706
|
+
createdAtMs: Date.now(),
|
|
20707
|
+
data: {
|
|
20708
|
+
type: "compaction_prepared",
|
|
20709
|
+
markSeq: message.markSeq,
|
|
20710
|
+
historyVersion: message.historyVersion,
|
|
20711
|
+
modelId: requested.modelId,
|
|
20712
|
+
...result
|
|
20713
|
+
}
|
|
20714
|
+
}], { activity: "preserve" });
|
|
20715
|
+
await state.delete(snapshotKey(message));
|
|
20716
|
+
if (result.outcome === "failed") setSpanAttributes({ "error.type": result.errorType });
|
|
20717
|
+
return result.outcome;
|
|
20718
|
+
};
|
|
20719
|
+
const remainingMs = request.createdAtMs + REQUEST_TIMEOUT_MS - Date.now();
|
|
20720
|
+
if (remainingMs <= 0) return await writePrepared({
|
|
20721
|
+
outcome: "failed",
|
|
20722
|
+
errorType: "timeout"
|
|
20723
|
+
});
|
|
20724
|
+
const snapshot = await state.get(snapshotKey(message));
|
|
20725
|
+
if (!snapshot) return await writePrepared({
|
|
20726
|
+
outcome: "failed",
|
|
20727
|
+
errorType: "snapshot_missing"
|
|
20728
|
+
});
|
|
20729
|
+
setSpanAttributes({ "app.compaction.input.size": snapshot.inputSize });
|
|
20730
|
+
const projection = projectConversationEvents(events, { maxSeq: message.markSeq });
|
|
20731
|
+
const signal = AbortSignal.timeout(remainingMs);
|
|
20732
|
+
let summary;
|
|
20733
|
+
try {
|
|
20734
|
+
summary = await runWithConversationPrivacy(snapshot.conversationPrivacy, async () => {
|
|
20735
|
+
const summaryStreamFn = createTracedStreamFn({
|
|
20736
|
+
conversationPrivacy: snapshot.conversationPrivacy,
|
|
20737
|
+
promptName: CONTEXT_COMPACTION_PROMPT_NAME,
|
|
20738
|
+
...streamFn ? { base: streamFn } : void 0
|
|
20739
|
+
});
|
|
20740
|
+
return await requestContextSummary(await buildAgentModelRequest(new Agent({
|
|
20741
|
+
getApiKey: getGatewayApiKey,
|
|
20742
|
+
sessionId: message.conversationId,
|
|
20743
|
+
streamFn: summaryStreamFn,
|
|
20744
|
+
initialState: {
|
|
20745
|
+
systemPrompt: snapshot.systemPrompt,
|
|
20746
|
+
model: resolveGatewayModel(snapshot.modelId),
|
|
20747
|
+
thinkingLevel: snapshot.thinkingLevel,
|
|
20748
|
+
tools: snapshot.tools.map((tool) => ({
|
|
20749
|
+
...tool,
|
|
20750
|
+
execute: async () => {
|
|
20751
|
+
throw new Error("Background compaction does not run tools");
|
|
20752
|
+
}
|
|
20753
|
+
}))
|
|
20754
|
+
}
|
|
20755
|
+
}), projection.messages, signal), summaryStreamFn);
|
|
20756
|
+
});
|
|
20757
|
+
} catch (error) {
|
|
20758
|
+
return await writePrepared({
|
|
20759
|
+
outcome: "failed",
|
|
20760
|
+
errorType: failureLabel(error, signal)
|
|
20553
20761
|
});
|
|
20554
20762
|
}
|
|
20555
|
-
const
|
|
20556
|
-
|
|
20557
|
-
|
|
20558
|
-
|
|
20559
|
-
|
|
20560
|
-
|
|
20561
|
-
|
|
20562
|
-
|
|
20563
|
-
return
|
|
20564
|
-
role: "user",
|
|
20565
|
-
content: runtimeContext.content,
|
|
20566
|
-
timestamp: timestamp ?? runtimeContext.timestamp
|
|
20567
|
-
};
|
|
20763
|
+
const outcome = await writePrepared({
|
|
20764
|
+
outcome: "ready",
|
|
20765
|
+
summary
|
|
20766
|
+
});
|
|
20767
|
+
if (outcome === "ready") setSpanAttributes({
|
|
20768
|
+
"app.compaction.summary_chars": summary.length,
|
|
20769
|
+
"app.compaction.ready_ms": Date.now() - request.createdAtMs
|
|
20770
|
+
});
|
|
20771
|
+
return outcome;
|
|
20568
20772
|
}
|
|
20569
|
-
|
|
20570
|
-
|
|
20773
|
+
// src/chat/services/plan-continuation.ts
|
|
20774
|
+
const OPEN_PLAN_TAG = "open-plan";
|
|
20775
|
+
function openItems(input) {
|
|
20776
|
+
const plan = input && typeof input === "object" ? input.plan : void 0;
|
|
20777
|
+
if (!Array.isArray(plan)) return [];
|
|
20778
|
+
return plan.flatMap((value) => {
|
|
20779
|
+
const item = value;
|
|
20780
|
+
if (typeof item?.step !== "string" || item.status !== "pending" && item.status !== "in_progress") return [];
|
|
20781
|
+
return [{
|
|
20782
|
+
step: item.step,
|
|
20783
|
+
status: item.status
|
|
20784
|
+
}];
|
|
20785
|
+
});
|
|
20571
20786
|
}
|
|
20572
|
-
|
|
20573
|
-
|
|
20574
|
-
|
|
20575
|
-
|
|
20576
|
-
|
|
20577
|
-
|
|
20578
|
-
|
|
20579
|
-
*/
|
|
20580
|
-
function turnRuntimeContextMessage(messages, turnStartMessageIndex, timestamp) {
|
|
20581
|
-
if (turnStartMessageIndex === void 0) return runtimeContextMessage(retainRuntimeTurnContext(messages), timestamp);
|
|
20582
|
-
const earlierContext = retainRuntimeTurnContext(messages.slice(0, turnStartMessageIndex));
|
|
20583
|
-
const turnContext = retainRuntimeTurnContext(messages.slice(turnStartMessageIndex));
|
|
20584
|
-
const sessionContext = turnContext.some((message) => userMessageContent(message).map(textPart).some(isSessionTurnContext)) ? void 0 : latestSessionContext(earlierContext);
|
|
20585
|
-
return toRuntimeContextMessage(runtimeContextContent(sessionContext ? [sessionContext, ...turnContext] : turnContext, [...earlierContext, ...turnContext]), timestamp);
|
|
20787
|
+
function messageText$1(message) {
|
|
20788
|
+
const content = message.content;
|
|
20789
|
+
if (!Array.isArray(content)) return typeof content === "string" ? content : "";
|
|
20790
|
+
return content.flatMap((part) => {
|
|
20791
|
+
const text = part?.text;
|
|
20792
|
+
return typeof text === "string" ? [text] : [];
|
|
20793
|
+
}).join("\n");
|
|
20586
20794
|
}
|
|
20587
|
-
|
|
20588
|
-
|
|
20589
|
-
|
|
20590
|
-
|
|
20591
|
-
|
|
20592
|
-
|
|
20593
|
-
const
|
|
20594
|
-
const
|
|
20595
|
-
|
|
20795
|
+
function retainedOpenItems(message) {
|
|
20796
|
+
const text = messageText$1(message);
|
|
20797
|
+
if (!isCompactionSummaryText(text)) return;
|
|
20798
|
+
const continuation = unwrapCurrentInstruction(text) ?? text;
|
|
20799
|
+
const open = `<${OPEN_PLAN_TAG}>\n`;
|
|
20800
|
+
const close = `\n</${OPEN_PLAN_TAG}>`;
|
|
20801
|
+
const closeIndex = continuation.lastIndexOf(close);
|
|
20802
|
+
const openIndex = continuation.lastIndexOf(open, closeIndex);
|
|
20803
|
+
if (openIndex < 0 || closeIndex < 0) return;
|
|
20804
|
+
const payload = continuation.slice(openIndex + open.length, closeIndex);
|
|
20805
|
+
try {
|
|
20806
|
+
return openItems({ plan: JSON.parse(payload) });
|
|
20807
|
+
} catch {
|
|
20808
|
+
return;
|
|
20809
|
+
}
|
|
20596
20810
|
}
|
|
20597
|
-
/**
|
|
20598
|
-
|
|
20599
|
-
|
|
20600
|
-
|
|
20601
|
-
|
|
20602
|
-
|
|
20603
|
-
|
|
20604
|
-
for (let sourceIndex = messages.length - 1; sourceIndex >= 0; sourceIndex -= 1) {
|
|
20605
|
-
if (isStandaloneRuntimeContextMessage(messages, sourceIndex)) continue;
|
|
20606
|
-
const message = stripRuntimeTurnContext([messages[sourceIndex]])[0];
|
|
20607
|
-
if (!message || message.role !== "user" || remaining <= 0) continue;
|
|
20608
|
-
const text = sanitizeText(messageText(message));
|
|
20609
|
-
if (!text || isCompactionSummary(text) || isPayloadHeavy(text)) continue;
|
|
20610
|
-
const tokens = estimateTextTokens(text);
|
|
20611
|
-
if (tokens <= remaining) {
|
|
20612
|
-
selected.push({
|
|
20613
|
-
message: userMessage(text),
|
|
20614
|
-
sourceIndex
|
|
20615
|
-
});
|
|
20616
|
-
remaining -= tokens;
|
|
20811
|
+
/** Read open items from the latest successful plan state. */
|
|
20812
|
+
function latestOpenPlanItems(messages) {
|
|
20813
|
+
const successfulCalls = /* @__PURE__ */ new Set();
|
|
20814
|
+
for (let messageIndex = messages.length - 1; messageIndex >= 0; messageIndex -= 1) {
|
|
20815
|
+
const message = messages[messageIndex];
|
|
20816
|
+
if (message.role === "toolResult" && message.toolName === "updatePlan" && typeof message.toolCallId === "string" && message.isError !== true) {
|
|
20817
|
+
successfulCalls.add(message.toolCallId);
|
|
20617
20818
|
continue;
|
|
20618
20819
|
}
|
|
20619
|
-
|
|
20620
|
-
|
|
20621
|
-
|
|
20622
|
-
|
|
20623
|
-
|
|
20624
|
-
|
|
20820
|
+
if (message.role === "user") {
|
|
20821
|
+
const retained = retainedOpenItems(messages[messageIndex]);
|
|
20822
|
+
if (retained) return retained;
|
|
20823
|
+
}
|
|
20824
|
+
if (message.role !== "assistant" || !Array.isArray(message.content)) continue;
|
|
20825
|
+
for (let partIndex = message.content.length - 1; partIndex >= 0; partIndex -= 1) {
|
|
20826
|
+
const call = message.content[partIndex];
|
|
20827
|
+
if (call?.type === "toolCall" && call.name === "updatePlan" && typeof call.id === "string" && successfulCalls.has(call.id)) return openItems(call.arguments);
|
|
20828
|
+
}
|
|
20625
20829
|
}
|
|
20626
|
-
return
|
|
20830
|
+
return [];
|
|
20627
20831
|
}
|
|
20628
|
-
/**
|
|
20629
|
-
function
|
|
20630
|
-
const
|
|
20631
|
-
return `${
|
|
20832
|
+
/** Append exact open plan state to continuation text. */
|
|
20833
|
+
function appendOpenPlan(continuation, messages) {
|
|
20834
|
+
const plan = latestOpenPlanItems(messages);
|
|
20835
|
+
return plan.length === 0 ? continuation : `${continuation}\n\n<${OPEN_PLAN_TAG}>\n${JSON.stringify(plan)}\n</${OPEN_PLAN_TAG}>`;
|
|
20632
20836
|
}
|
|
20837
|
+
// src/chat/services/context-compaction.ts
|
|
20633
20838
|
/**
|
|
20634
|
-
*
|
|
20635
|
-
*
|
|
20839
|
+
* Context compaction.
|
|
20840
|
+
*
|
|
20841
|
+
* Bounds Pi history for long conversations and commits a history
|
|
20842
|
+
* replacement. Capacity compaction gets its summary from the caller, which
|
|
20843
|
+
* asks the agent model with the cached request prefix. Mid-turn replacements
|
|
20844
|
+
* keep the authored instruction before the summary. Turn-start replacements keep recent user
|
|
20845
|
+
* messages, the summary, then the new instruction. Checkpoints can append
|
|
20846
|
+
* fresh runtime context; the next replacement removes it again.
|
|
20636
20847
|
*/
|
|
20637
|
-
|
|
20638
|
-
|
|
20639
|
-
|
|
20640
|
-
|
|
20641
|
-
|
|
20642
|
-
|
|
20643
|
-
|
|
20644
|
-
|
|
20645
|
-
|
|
20646
|
-
|
|
20647
|
-
|
|
20648
|
-
|
|
20649
|
-
|
|
20650
|
-
|
|
20651
|
-
});
|
|
20652
|
-
}
|
|
20653
|
-
/** Keep generated text inside the existing evidence-only prompt boundary. */
|
|
20654
|
-
function renderCompactionSummary(summary) {
|
|
20655
|
-
return [
|
|
20656
|
-
COMPACTION_SUMMARY_PREFIX,
|
|
20657
|
-
"<thread-context authority=\"evidence-only\">",
|
|
20658
|
-
escapeXml(summary),
|
|
20659
|
-
"</thread-context>"
|
|
20660
|
-
].join("\n");
|
|
20848
|
+
const RETAINED_USER_MESSAGE_TOKENS = 2e4;
|
|
20849
|
+
/** Raised when Junior cannot compact history below the active model's hard ceiling. */
|
|
20850
|
+
var ContextInputLimitExceededError = class extends Error {
|
|
20851
|
+
estimatedTokens;
|
|
20852
|
+
inputLimitTokens;
|
|
20853
|
+
constructor(estimatedTokens, inputLimitTokens) {
|
|
20854
|
+
super(`Agent context is ${estimatedTokens} estimated input tokens, above the ${inputLimitTokens} token limit`);
|
|
20855
|
+
this.estimatedTokens = estimatedTokens;
|
|
20856
|
+
this.inputLimitTokens = inputLimitTokens;
|
|
20857
|
+
this.name = "ContextInputLimitExceededError";
|
|
20858
|
+
}
|
|
20859
|
+
};
|
|
20860
|
+
function textPart(value) {
|
|
20861
|
+
if (value && typeof value === "object" && value.type === "text" && typeof value.text === "string") return value.text;
|
|
20661
20862
|
}
|
|
20662
|
-
/**
|
|
20663
|
-
function
|
|
20664
|
-
|
|
20863
|
+
/** Render Pi message text for retained user-message selection. */
|
|
20864
|
+
function messageText(message) {
|
|
20865
|
+
const content = message.content;
|
|
20866
|
+
const unwrapTask = message.role === "user";
|
|
20867
|
+
const displayText = (text) => unwrapTask ? unwrapCurrentInstruction(text) ?? text : text;
|
|
20868
|
+
if (!Array.isArray(content)) return typeof content === "string" ? displayText(content) : "";
|
|
20869
|
+
return content.map(textPart).filter((text) => Boolean(text)).map(displayText).join("\n").trim();
|
|
20665
20870
|
}
|
|
20666
|
-
|
|
20667
|
-
|
|
20668
|
-
* assistant message holds provider usage for the whole request before the
|
|
20669
|
-
* replacement, so usage is ignored here.
|
|
20670
|
-
*/
|
|
20671
|
-
function estimateReplacementTokens(messages, requestOverheadTokens = 0) {
|
|
20672
|
-
return messages.reduce((total, message) => total + estimateTokens(message), requestOverheadTokens);
|
|
20871
|
+
function sanitizeText(text) {
|
|
20872
|
+
return text.replace(/<data_base64>[\s\S]*?<\/data_base64>/g, "<data_base64>[omitted]</data_base64>").replace(/data:image\/[a-z0-9.+-]+;base64,[a-z0-9+/=]+/gi, "[image data omitted]").replaceAll("\0", " ").trim();
|
|
20673
20873
|
}
|
|
20674
|
-
|
|
20675
|
-
const
|
|
20676
|
-
if (
|
|
20677
|
-
|
|
20678
|
-
if (event.data.provenance.authority !== "instruction") return void 0;
|
|
20679
|
-
return {
|
|
20680
|
-
message: piMessageFromHistoryItem(event.data),
|
|
20681
|
-
provenance: event.data.provenance,
|
|
20682
|
-
sourceEventSeq: event.seq
|
|
20683
|
-
};
|
|
20684
|
-
}
|
|
20874
|
+
function truncateToTokenBudget(text, maxTokens) {
|
|
20875
|
+
const maxChars = Math.max(0, maxTokens * 4);
|
|
20876
|
+
if (text.length <= maxChars) return text;
|
|
20877
|
+
return `${text.slice(0, Math.max(0, maxChars - 3)).trimEnd()}...`;
|
|
20685
20878
|
}
|
|
20686
|
-
function
|
|
20687
|
-
|
|
20688
|
-
estimatedTokens: estimateHistoryTokens(messages),
|
|
20689
|
-
messages
|
|
20690
|
-
};
|
|
20691
|
-
return { reason: "missing_context" };
|
|
20879
|
+
function isCompactionSummary(text) {
|
|
20880
|
+
return isCompactionSummaryText(text);
|
|
20692
20881
|
}
|
|
20693
|
-
|
|
20694
|
-
|
|
20695
|
-
* provider request can observe it.
|
|
20696
|
-
*
|
|
20697
|
-
* `summarize` gets the history without pending messages. When it fails, the
|
|
20698
|
-
* history stays as it is, unless the history is at the input limit.
|
|
20699
|
-
*/
|
|
20700
|
-
async function compactActiveContextIfNeeded(args, summarize) {
|
|
20701
|
-
const pendingMessages = args.pendingMessages ?? [];
|
|
20702
|
-
const source = loadCompactionSource([...args.piMessages, ...pendingMessages.map((entry) => entry.message)]);
|
|
20703
|
-
if ("reason" in source) return {
|
|
20704
|
-
compacted: false,
|
|
20705
|
-
reason: source.reason
|
|
20706
|
-
};
|
|
20707
|
-
const triggerTokens = getAgentContextCompactionTriggerTokens(args.modelId);
|
|
20708
|
-
if (source.estimatedTokens <= triggerTokens) return {
|
|
20709
|
-
compacted: false,
|
|
20710
|
-
reason: "below_threshold"
|
|
20711
|
-
};
|
|
20712
|
-
return await withCompactionSpan(args.mode, () => compactActiveAboveThreshold(args, summarize, source, triggerTokens));
|
|
20882
|
+
function isPayloadHeavy(text) {
|
|
20883
|
+
return /<data_base64>[\s\S]*?<\/data_base64>|data:image\/[a-z0-9.+-]+;base64,/i.test(text);
|
|
20713
20884
|
}
|
|
20714
|
-
|
|
20715
|
-
|
|
20716
|
-
const retainUserMessages = args.mode === "blocking" && pendingMessages.length > 0;
|
|
20717
|
-
await args.onCompactionStart?.();
|
|
20718
|
-
const inputLimitTokens = getAgentContextInputLimitTokens(args.modelId);
|
|
20719
|
-
let summary;
|
|
20720
|
-
try {
|
|
20721
|
-
summary = await summarize(args.piMessages, args.signal);
|
|
20722
|
-
} catch (error) {
|
|
20723
|
-
if (source.estimatedTokens >= inputLimitTokens) throw new ContextInputLimitExceededError(source.estimatedTokens, inputLimitTokens);
|
|
20724
|
-
logWarn("context_compaction.active.summary.failed", {
|
|
20725
|
-
"app.context_input_limit_tokens": inputLimitTokens,
|
|
20726
|
-
"app.context_tokens_estimated": source.estimatedTokens,
|
|
20727
|
-
"exception.message": error instanceof Error ? error.message : String(error)
|
|
20728
|
-
});
|
|
20729
|
-
setSpanAttributes({ "app.compaction.outcome": "summary_failed" });
|
|
20730
|
-
return {
|
|
20731
|
-
compacted: false,
|
|
20732
|
-
reason: "summary_failed"
|
|
20733
|
-
};
|
|
20734
|
-
}
|
|
20735
|
-
const summaryMessage = userMessage(appendOpenPlan(renderCompactionSummary(summary), source.messages));
|
|
20736
|
-
const retainedInstruction = pendingMessages.length === 0 && !retainUserMessages ? await loadLastInstruction(args.conversationId) : void 0;
|
|
20737
|
-
const instructionMessages = retainedInstruction ? [retainedInstruction.message] : pendingMessages.map((entry) => entry.message);
|
|
20738
|
-
const instructionProvenance = retainedInstruction ? [retainedInstruction.provenance] : pendingMessages.map((entry) => entry.provenance);
|
|
20739
|
-
const instructionTimestamp = instructionMessages[0]?.timestamp;
|
|
20740
|
-
const contextMessage = turnRuntimeContextMessage(args.runtimeContextMessages ?? args.piMessages, args.turnStartMessageIndex, typeof instructionTimestamp === "number" ? instructionTimestamp : void 0);
|
|
20741
|
-
const contextEntries = contextMessage ? [{
|
|
20742
|
-
message: contextMessage,
|
|
20743
|
-
provenance: contextProvenance
|
|
20744
|
-
}] : [];
|
|
20745
|
-
const instructionEntries = instructionMessages.map((message, index) => ({
|
|
20746
|
-
message,
|
|
20747
|
-
provenance: instructionProvenance[index],
|
|
20748
|
-
...index === 0 && retainedInstruction ? { sourceEventSeq: retainedInstruction.sourceEventSeq } : void 0
|
|
20749
|
-
}));
|
|
20750
|
-
const summaryEntry = {
|
|
20751
|
-
message: summaryMessage,
|
|
20752
|
-
provenance: contextProvenance
|
|
20753
|
-
};
|
|
20754
|
-
const retainedUserMessages = retainUserMessages ? await loadRetainedUserMessages(args.conversationId, instructionMessages) : [];
|
|
20755
|
-
const replacement = retainUserMessages ? [
|
|
20756
|
-
...retainedUserMessages,
|
|
20757
|
-
summaryEntry,
|
|
20758
|
-
...contextEntries,
|
|
20759
|
-
...instructionEntries
|
|
20760
|
-
] : [
|
|
20761
|
-
...contextEntries,
|
|
20762
|
-
...instructionEntries,
|
|
20763
|
-
summaryEntry
|
|
20764
|
-
];
|
|
20765
|
-
const retainedMessageCount = retainedUserMessages.length + instructionMessages.length;
|
|
20766
|
-
const messages = replacement.map((entry) => entry.message);
|
|
20767
|
-
const replacementInputTokens = estimateReplacementTokens(messages, args.requestOverheadTokens);
|
|
20768
|
-
if (replacementInputTokens >= inputLimitTokens) throw new ContextInputLimitExceededError(replacementInputTokens, inputLimitTokens);
|
|
20769
|
-
args.signal?.throwIfAborted();
|
|
20770
|
-
await getConversationEventStore().replaceHistory(args.conversationId, {
|
|
20771
|
-
createdAtMs: Date.now(),
|
|
20772
|
-
data: {
|
|
20773
|
-
type: "compaction",
|
|
20774
|
-
modelId: args.modelId,
|
|
20775
|
-
details: {
|
|
20776
|
-
reason: "capacity",
|
|
20777
|
-
estimatedInputTokens: source.estimatedTokens,
|
|
20778
|
-
replacementInputTokens,
|
|
20779
|
-
triggerTokens,
|
|
20780
|
-
inputLimitTokens,
|
|
20781
|
-
inputMessageCount: source.messages.length,
|
|
20782
|
-
retainedMessageCount,
|
|
20783
|
-
summaryChars: summary.length
|
|
20784
|
-
},
|
|
20785
|
-
summary,
|
|
20786
|
-
replacementHistory: replacement.map((entry) => ({
|
|
20787
|
-
item: historyItemFromPiMessage(entry.message, entry.provenance),
|
|
20788
|
-
...entry.sourceEventSeq === void 0 ? void 0 : { sourceEventSeq: entry.sourceEventSeq }
|
|
20789
|
-
}))
|
|
20790
|
-
}
|
|
20791
|
-
});
|
|
20792
|
-
setSpanAttributes({
|
|
20793
|
-
"app.compaction.outcome": "compacted",
|
|
20794
|
-
"app.compaction.input_messages": source.messages.length,
|
|
20795
|
-
"app.compaction.retained_messages": retainedMessageCount,
|
|
20796
|
-
"app.compaction.summary_chars": summary.length,
|
|
20797
|
-
"app.compaction.input.estimate": source.estimatedTokens,
|
|
20798
|
-
"app.compaction.replacement.estimate": replacementInputTokens,
|
|
20799
|
-
"app.compaction.input_limit": inputLimitTokens,
|
|
20800
|
-
"app.compaction.threshold": triggerTokens
|
|
20801
|
-
});
|
|
20885
|
+
/** Build a text-only user message for a replacement history. */
|
|
20886
|
+
function userMessage(text) {
|
|
20802
20887
|
return {
|
|
20803
|
-
|
|
20804
|
-
|
|
20888
|
+
role: "user",
|
|
20889
|
+
content: [{
|
|
20890
|
+
type: "text",
|
|
20891
|
+
text
|
|
20892
|
+
}],
|
|
20893
|
+
timestamp: Date.now()
|
|
20805
20894
|
};
|
|
20806
20895
|
}
|
|
20807
|
-
|
|
20808
|
-
|
|
20809
|
-
|
|
20810
|
-
|
|
20811
|
-
|
|
20812
|
-
|
|
20813
|
-
|
|
20814
|
-
|
|
20896
|
+
function userMessageContent(message) {
|
|
20897
|
+
const content = message.content;
|
|
20898
|
+
return Array.isArray(content) ? content : [];
|
|
20899
|
+
}
|
|
20900
|
+
function hasTurnBootstrap(message) {
|
|
20901
|
+
return userMessageContent(message).some((part) => textPart(part)?.startsWith(`<${TURN_CONTEXT_TAG}>`) === true);
|
|
20902
|
+
}
|
|
20903
|
+
function isSessionTurnContext(text) {
|
|
20904
|
+
return text?.startsWith(`<runtime-turn-context>`) === true && text.includes(`\n<runtime>\n`);
|
|
20815
20905
|
}
|
|
20816
|
-
|
|
20817
|
-
|
|
20818
|
-
return
|
|
20906
|
+
/** Remove the sections that only the Turn that received them can use. */
|
|
20907
|
+
function withoutRequestContext(text) {
|
|
20908
|
+
return Object.values(REQUEST_CONTEXT_SECTION_TAG).reduce((result, tag) => result.replace(new RegExp(`\\n\\n<${tag}>\\n[\\s\\S]*?\\n</${tag}>`, "g"), ""), text);
|
|
20819
20909
|
}
|
|
20820
|
-
|
|
20821
|
-
|
|
20910
|
+
/** Find the latest session context and keep only its session sections. */
|
|
20911
|
+
function latestSessionContext(messages) {
|
|
20912
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
20913
|
+
const message = messages[index];
|
|
20914
|
+
const text = userMessageContent(message).map(textPart).find(isSessionTurnContext);
|
|
20915
|
+
if (text) return {
|
|
20916
|
+
...message,
|
|
20917
|
+
content: [{
|
|
20918
|
+
type: "text",
|
|
20919
|
+
text: withoutRequestContext(text)
|
|
20920
|
+
}]
|
|
20921
|
+
};
|
|
20922
|
+
}
|
|
20822
20923
|
}
|
|
20823
|
-
function
|
|
20824
|
-
|
|
20924
|
+
function effectiveRuntimeContext(messages) {
|
|
20925
|
+
let latestBootstrapIndex = -1;
|
|
20926
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) if (hasTurnBootstrap(messages[index])) {
|
|
20927
|
+
latestBootstrapIndex = index;
|
|
20928
|
+
break;
|
|
20929
|
+
}
|
|
20930
|
+
const effectiveMessages = latestBootstrapIndex < 0 ? messages : messages.slice(latestBootstrapIndex);
|
|
20931
|
+
return runtimeContextContent(effectiveMessages, effectiveMessages);
|
|
20825
20932
|
}
|
|
20826
|
-
|
|
20827
|
-
|
|
20828
|
-
|
|
20829
|
-
|
|
20830
|
-
|
|
20831
|
-
|
|
20832
|
-
|
|
20833
|
-
|
|
20834
|
-
|
|
20933
|
+
function runtimeContextContent(messages, agentsMessages) {
|
|
20934
|
+
const allContent = messages.flatMap(userMessageContent);
|
|
20935
|
+
const firstAgentsIndex = allContent.findIndex((part) => textPart(part)?.startsWith("# AGENTS.md instructions") === true);
|
|
20936
|
+
const content = allContent.filter((part) => textPart(part)?.startsWith("# AGENTS.md instructions") !== true);
|
|
20937
|
+
const visibleAgents = findVisibleAgentsInstructions(agentsMessages);
|
|
20938
|
+
if (visibleAgents?.active === true) {
|
|
20939
|
+
const insertionIndex = firstAgentsIndex < 0 ? content.length : Math.min(firstAgentsIndex, content.length);
|
|
20940
|
+
content.splice(insertionIndex, 0, {
|
|
20941
|
+
type: "text",
|
|
20942
|
+
text: renderAgentsInstructions({
|
|
20943
|
+
directory: visibleAgents.directory,
|
|
20944
|
+
text: visibleAgents.text
|
|
20945
|
+
})
|
|
20946
|
+
});
|
|
20947
|
+
}
|
|
20948
|
+
const latestTimestamp = messages.at(-1)?.timestamp;
|
|
20949
|
+
return {
|
|
20950
|
+
content,
|
|
20951
|
+
timestamp: typeof latestTimestamp === "number" ? latestTimestamp : Date.now()
|
|
20952
|
+
};
|
|
20835
20953
|
}
|
|
20836
|
-
function
|
|
20837
|
-
|
|
20838
|
-
const text = resultText(parts);
|
|
20839
|
-
const hasImage = parts.some((part) => part.type === "image");
|
|
20840
|
-
const keptChars = message.isError === true ? MAX_KEPT_ERROR_CHARS : MAX_KEPT_RESULT_CHARS;
|
|
20841
|
-
const clearText = text.length > keptChars;
|
|
20842
|
-
if (!clearText && !hasImage) return;
|
|
20843
|
-
const toolName = String(message.toolName ?? "tool");
|
|
20844
|
-
const content = clearText ? [{
|
|
20845
|
-
type: "text",
|
|
20846
|
-
text: clearedText(toolName, text, seq)
|
|
20847
|
-
}] : parts.map((part) => part.type === "image" ? {
|
|
20848
|
-
type: "text",
|
|
20849
|
-
text: `[image cleared: ${toolName}, seq ${seq}]`
|
|
20850
|
-
} : part);
|
|
20851
|
-
if (clearText && hasImage) content.push({
|
|
20852
|
-
type: "text",
|
|
20853
|
-
text: `[image cleared: ${toolName}, seq ${seq}]`
|
|
20854
|
-
});
|
|
20954
|
+
function toRuntimeContextMessage(runtimeContext, timestamp) {
|
|
20955
|
+
if (runtimeContext.content.length === 0) return;
|
|
20855
20956
|
return {
|
|
20856
|
-
|
|
20857
|
-
|
|
20858
|
-
|
|
20859
|
-
},
|
|
20860
|
-
removedChars: Math.max(0, text.length - resultText(content).length)
|
|
20957
|
+
role: "user",
|
|
20958
|
+
content: runtimeContext.content,
|
|
20959
|
+
timestamp: timestamp ?? runtimeContext.timestamp
|
|
20861
20960
|
};
|
|
20862
20961
|
}
|
|
20962
|
+
function runtimeContextMessage(messages, timestamp) {
|
|
20963
|
+
return toRuntimeContextMessage(effectiveRuntimeContext(messages), timestamp);
|
|
20964
|
+
}
|
|
20863
20965
|
/**
|
|
20864
|
-
*
|
|
20966
|
+
* Build the runtime context that the current Turn can use after an in-turn
|
|
20967
|
+
* replacement.
|
|
20865
20968
|
*
|
|
20866
|
-
*
|
|
20867
|
-
*
|
|
20868
|
-
*
|
|
20869
|
-
* results that have no source event to point to. Images outside the latest
|
|
20870
|
-
* Turn become a short note.
|
|
20969
|
+
* Request context, such as plugin context and disabled tools, is true only for
|
|
20970
|
+
* the Turn that received it. From earlier Turns, keep only the latest session
|
|
20971
|
+
* context and AGENTS.md instructions.
|
|
20871
20972
|
*/
|
|
20872
|
-
function
|
|
20873
|
-
|
|
20874
|
-
|
|
20875
|
-
|
|
20876
|
-
|
|
20877
|
-
|
|
20878
|
-
trimmedResults: 0,
|
|
20879
|
-
removedChars: 0
|
|
20880
|
-
};
|
|
20881
|
-
return {
|
|
20882
|
-
entries: entries.map((entry, index) => {
|
|
20883
|
-
if (index > latestInstructionIndex || role(entry.message) !== "toolResult" || entry.sourceEventSeq === void 0) return entry;
|
|
20884
|
-
const result = trimResult(entry.message, entry.sourceEventSeq);
|
|
20885
|
-
if (!result) return entry;
|
|
20886
|
-
trimming.trimmedResults += 1;
|
|
20887
|
-
trimming.removedChars += result.removedChars;
|
|
20888
|
-
return {
|
|
20889
|
-
...entry,
|
|
20890
|
-
message: result.message
|
|
20891
|
-
};
|
|
20892
|
-
}),
|
|
20893
|
-
trimming
|
|
20894
|
-
};
|
|
20973
|
+
function turnRuntimeContextMessage(messages, turnStartMessageIndex, timestamp) {
|
|
20974
|
+
if (turnStartMessageIndex === void 0) return runtimeContextMessage(retainRuntimeTurnContext(messages), timestamp);
|
|
20975
|
+
const earlierContext = retainRuntimeTurnContext(messages.slice(0, turnStartMessageIndex));
|
|
20976
|
+
const turnContext = retainRuntimeTurnContext(messages.slice(turnStartMessageIndex));
|
|
20977
|
+
const sessionContext = turnContext.some((message) => userMessageContent(message).map(textPart).some(isSessionTurnContext)) ? void 0 : latestSessionContext(earlierContext);
|
|
20978
|
+
return toRuntimeContextMessage(runtimeContextContent(sessionContext ? [sessionContext, ...turnContext] : turnContext, [...earlierContext, ...turnContext]), timestamp);
|
|
20895
20979
|
}
|
|
20896
|
-
// src/chat/services/context-compaction-swap.ts
|
|
20897
20980
|
/**
|
|
20898
|
-
*
|
|
20899
|
-
*
|
|
20900
|
-
*
|
|
20901
|
-
* up to `markSeq`. The Turn swaps it in without a model call: retained user
|
|
20902
|
-
* messages, the summary, then every message after the mark. Turn start swaps
|
|
20903
|
-
* a ready summary at once. Between model calls, a swap runs only above the
|
|
20904
|
-
* compaction threshold, in place of a blocking summary call. A summary that
|
|
20905
|
-
* no longer matches the history is discarded, and the Turn carries on as if
|
|
20906
|
-
* none existed.
|
|
20981
|
+
* Build the runtime context of summarized history that the kept history
|
|
20982
|
+
* does not carry: the latest session context and the AGENTS.md
|
|
20983
|
+
* instructions. Request context of earlier Turns is left out.
|
|
20907
20984
|
*/
|
|
20908
|
-
|
|
20909
|
-
|
|
20910
|
-
const
|
|
20911
|
-
return
|
|
20912
|
-
role,
|
|
20913
|
-
timestamp,
|
|
20914
|
-
content,
|
|
20915
|
-
toolCallId
|
|
20916
|
-
}));
|
|
20985
|
+
function summarizedRuntimeContextMessage(summarized, kept) {
|
|
20986
|
+
const earlierContext = retainRuntimeTurnContext(summarized);
|
|
20987
|
+
const sessionContext = retainRuntimeTurnContext(kept).some((message) => userMessageContent(message).map(textPart).some(isSessionTurnContext)) ? void 0 : latestSessionContext(earlierContext);
|
|
20988
|
+
return toRuntimeContextMessage(runtimeContextContent(sessionContext ? [sessionContext] : [], findVisibleAgentsInstructions(kept) ? [] : earlierContext));
|
|
20917
20989
|
}
|
|
20918
|
-
|
|
20919
|
-
|
|
20920
|
-
|
|
20921
|
-
|
|
20990
|
+
/**
|
|
20991
|
+
* Build retained user messages for a compacted Pi replacement history. Each
|
|
20992
|
+
* entry keeps the index of its source message.
|
|
20993
|
+
*/
|
|
20994
|
+
function selectRetainedUserMessageEntries(messages, maxTokens = RETAINED_USER_MESSAGE_TOKENS) {
|
|
20995
|
+
const selected = [];
|
|
20996
|
+
let remaining = maxTokens;
|
|
20997
|
+
for (let sourceIndex = messages.length - 1; sourceIndex >= 0; sourceIndex -= 1) {
|
|
20998
|
+
if (isStandaloneRuntimeContextMessage(messages, sourceIndex)) continue;
|
|
20999
|
+
const message = stripRuntimeTurnContext([messages[sourceIndex]])[0];
|
|
21000
|
+
if (!message || message.role !== "user" || remaining <= 0) continue;
|
|
21001
|
+
const text = sanitizeText(messageText(message));
|
|
21002
|
+
if (!text || isCompactionSummary(text) || isPayloadHeavy(text)) continue;
|
|
21003
|
+
const tokens = estimateTextTokens(text);
|
|
21004
|
+
if (tokens <= remaining) {
|
|
21005
|
+
selected.push({
|
|
21006
|
+
message: userMessage(text),
|
|
21007
|
+
sourceIndex
|
|
21008
|
+
});
|
|
21009
|
+
remaining -= tokens;
|
|
21010
|
+
continue;
|
|
21011
|
+
}
|
|
21012
|
+
const truncated = truncateToTokenBudget(text, remaining);
|
|
21013
|
+
if (truncated) selected.push({
|
|
21014
|
+
message: userMessage(truncated),
|
|
21015
|
+
sourceIndex
|
|
21016
|
+
});
|
|
21017
|
+
break;
|
|
21018
|
+
}
|
|
21019
|
+
return selected.reverse();
|
|
20922
21020
|
}
|
|
20923
|
-
|
|
20924
|
-
|
|
20925
|
-
|
|
20926
|
-
|
|
21021
|
+
/** Match a message across a durable commit, which can reorder JSON keys. */
|
|
21022
|
+
function retainedMessageKey(message) {
|
|
21023
|
+
const { role, timestamp } = message;
|
|
21024
|
+
return `${String(role)}:${String(timestamp)}:${messageText(message)}`;
|
|
21025
|
+
}
|
|
21026
|
+
/**
|
|
21027
|
+
* Load recent user messages from committed history. Each one keeps its
|
|
21028
|
+
* original author and source event.
|
|
21029
|
+
*/
|
|
21030
|
+
async function loadRetainedUserMessages(conversationId, pendingMessages) {
|
|
21031
|
+
const projection = await loadConversationProjection({ conversationId });
|
|
21032
|
+
const pendingKeys = new Set(pendingMessages.map(retainedMessageKey));
|
|
21033
|
+
let pendingStart = projection.messages.findIndex((message) => pendingKeys.has(retainedMessageKey(message)));
|
|
21034
|
+
if (pendingStart > 0 && isStandaloneRuntimeContextMessage(projection.messages, pendingStart - 1)) pendingStart -= 1;
|
|
21035
|
+
const history = pendingStart === -1 ? projection.messages : projection.messages.slice(0, pendingStart);
|
|
21036
|
+
return selectRetainedUserMessageEntries(trimTrailingAssistantMessages(history)).map((entry) => {
|
|
21037
|
+
const provenance = projection.provenance[entry.sourceIndex];
|
|
21038
|
+
if (!provenance) throw new Error("retained message provenance is missing");
|
|
21039
|
+
return {
|
|
21040
|
+
message: entry.message,
|
|
21041
|
+
provenance,
|
|
21042
|
+
sourceEventSeq: projection.seqs[entry.sourceIndex]
|
|
21043
|
+
};
|
|
20927
21044
|
});
|
|
20928
|
-
|
|
21045
|
+
}
|
|
21046
|
+
/** Keep generated text inside the existing evidence-only prompt boundary. */
|
|
21047
|
+
function renderCompactionSummary(summary) {
|
|
21048
|
+
return [
|
|
21049
|
+
COMPACTION_SUMMARY_PREFIX,
|
|
21050
|
+
"<thread-context authority=\"evidence-only\">",
|
|
21051
|
+
escapeXml(summary),
|
|
21052
|
+
"</thread-context>"
|
|
21053
|
+
].join("\n");
|
|
21054
|
+
}
|
|
21055
|
+
/** Measure provider-visible history without counting host-only message fields. */
|
|
21056
|
+
function estimateHistoryTokens(messages) {
|
|
21057
|
+
return estimateContextTokens(messages).tokens;
|
|
20929
21058
|
}
|
|
20930
21059
|
/**
|
|
20931
|
-
*
|
|
20932
|
-
*
|
|
20933
|
-
*
|
|
21060
|
+
* Estimate a replacement request from each message's own size. A kept
|
|
21061
|
+
* assistant message holds provider usage for the whole request before the
|
|
21062
|
+
* replacement, so usage is ignored here.
|
|
20934
21063
|
*/
|
|
20935
|
-
|
|
20936
|
-
|
|
20937
|
-
|
|
20938
|
-
|
|
20939
|
-
|
|
20940
|
-
|
|
20941
|
-
|
|
20942
|
-
|
|
20943
|
-
|
|
20944
|
-
|
|
20945
|
-
|
|
21064
|
+
function estimateReplacementTokens(messages, requestOverheadTokens = 0) {
|
|
21065
|
+
return messages.reduce((total, message) => total + estimateTokens(message), requestOverheadTokens);
|
|
21066
|
+
}
|
|
21067
|
+
async function loadLastInstruction(conversationId) {
|
|
21068
|
+
const event = await getConversationEventStore().loadLatestInstruction(conversationId);
|
|
21069
|
+
if (!event) return void 0;
|
|
21070
|
+
if (event.data.type === "user_message") {
|
|
21071
|
+
if (event.data.provenance.authority !== "instruction") return void 0;
|
|
21072
|
+
return {
|
|
21073
|
+
message: piMessageFromHistoryItem(event.data),
|
|
21074
|
+
provenance: event.data.provenance,
|
|
21075
|
+
sourceEventSeq: event.seq
|
|
21076
|
+
};
|
|
21077
|
+
}
|
|
20946
21078
|
}
|
|
20947
|
-
|
|
20948
|
-
|
|
20949
|
-
|
|
20950
|
-
|
|
20951
|
-
|
|
20952
|
-
|
|
20953
|
-
if (swapped.compacted || swapped.reason === "history_conflict") return swapped;
|
|
20954
|
-
return await compactActiveContextIfNeeded(args, summarize);
|
|
21079
|
+
function loadCompactionSource(messages) {
|
|
21080
|
+
if (messages.length > 0) return {
|
|
21081
|
+
estimatedTokens: estimateHistoryTokens(messages),
|
|
21082
|
+
messages
|
|
21083
|
+
};
|
|
21084
|
+
return { reason: "missing_context" };
|
|
20955
21085
|
}
|
|
20956
21086
|
/**
|
|
20957
|
-
* Replace
|
|
20958
|
-
*
|
|
20959
|
-
*
|
|
21087
|
+
* Replace oversized active history at Pi's next-turn boundary before another
|
|
21088
|
+
* provider request can observe it.
|
|
21089
|
+
*
|
|
21090
|
+
* `summarize` gets the history without pending messages. When it fails, the
|
|
21091
|
+
* history stays as it is, unless the history is at the input limit.
|
|
20960
21092
|
*/
|
|
20961
|
-
async function
|
|
21093
|
+
async function compactActiveContextIfNeeded(args, summarize) {
|
|
20962
21094
|
const pendingMessages = args.pendingMessages ?? [];
|
|
20963
|
-
const
|
|
21095
|
+
const source = loadCompactionSource([...args.piMessages, ...pendingMessages.map((entry) => entry.message)]);
|
|
21096
|
+
if ("reason" in source) return {
|
|
21097
|
+
compacted: false,
|
|
21098
|
+
reason: source.reason
|
|
21099
|
+
};
|
|
20964
21100
|
const triggerTokens = getAgentContextCompactionTriggerTokens(args.modelId);
|
|
20965
|
-
|
|
20966
|
-
if (args.mode !== "blocking" && estimatedTokens <= triggerTokens) return {
|
|
21101
|
+
if (source.estimatedTokens <= triggerTokens) return {
|
|
20967
21102
|
compacted: false,
|
|
20968
21103
|
reason: "below_threshold"
|
|
20969
21104
|
};
|
|
20970
|
-
|
|
20971
|
-
if (!latest) return { compacted: false };
|
|
20972
|
-
return await withCompactionSpan(args.mode, async () => {
|
|
20973
|
-
const { event, historyVersion } = latest;
|
|
20974
|
-
if (event.data.type !== "compaction_prepared" || event.data.outcome !== "ready") {
|
|
20975
|
-
setSpanAttributes({ "app.compaction.outcome": "not_ready" });
|
|
20976
|
-
return { compacted: false };
|
|
20977
|
-
}
|
|
20978
|
-
setSpanAttributes({ "app.compaction.prepared.age_ms": Math.max(0, Date.now() - event.createdAtMs) });
|
|
20979
|
-
if (event.data.historyVersion !== historyVersion) return discard("history_version_changed");
|
|
20980
|
-
return await applyPreparedSummary(args, event.data, {
|
|
20981
|
-
estimatedTokens,
|
|
20982
|
-
historyVersion,
|
|
20983
|
-
triggerTokens
|
|
20984
|
-
});
|
|
20985
|
-
});
|
|
21105
|
+
return await withCompactionSpan(args.mode, () => compactActiveAboveThreshold(args, summarize, source, triggerTokens));
|
|
20986
21106
|
}
|
|
20987
|
-
async function
|
|
21107
|
+
async function compactActiveAboveThreshold(args, summarize, source, triggerTokens) {
|
|
20988
21108
|
const pendingMessages = args.pendingMessages ?? [];
|
|
20989
|
-
const
|
|
20990
|
-
|
|
20991
|
-
const
|
|
20992
|
-
|
|
20993
|
-
|
|
20994
|
-
|
|
20995
|
-
|
|
20996
|
-
|
|
20997
|
-
|
|
20998
|
-
|
|
20999
|
-
|
|
21000
|
-
|
|
21001
|
-
|
|
21002
|
-
|
|
21003
|
-
|
|
21004
|
-
|
|
21005
|
-
|
|
21006
|
-
provenance: projection.provenance[index],
|
|
21007
|
-
sourceEventSeq: projection.seqs[index]
|
|
21008
|
-
} : {
|
|
21009
|
-
message,
|
|
21010
|
-
provenance: contextProvenance
|
|
21109
|
+
const retainUserMessages = args.mode === "blocking" && pendingMessages.length > 0;
|
|
21110
|
+
await args.onCompactionStart?.();
|
|
21111
|
+
const inputLimitTokens = getAgentContextInputLimitTokens(args.modelId);
|
|
21112
|
+
let summary;
|
|
21113
|
+
try {
|
|
21114
|
+
summary = await summarize(args.piMessages, args.signal);
|
|
21115
|
+
} catch (error) {
|
|
21116
|
+
if (source.estimatedTokens >= inputLimitTokens) throw new ContextInputLimitExceededError(source.estimatedTokens, inputLimitTokens);
|
|
21117
|
+
logWarn("context_compaction.active.summary.failed", {
|
|
21118
|
+
"app.context_input_limit_tokens": inputLimitTokens,
|
|
21119
|
+
"app.context_tokens_estimated": source.estimatedTokens,
|
|
21120
|
+
"exception.message": error instanceof Error ? error.message : String(error)
|
|
21121
|
+
});
|
|
21122
|
+
setSpanAttributes({ "app.compaction.outcome": "summary_failed" });
|
|
21123
|
+
return {
|
|
21124
|
+
compacted: false,
|
|
21125
|
+
reason: "summary_failed"
|
|
21011
21126
|
};
|
|
21127
|
+
}
|
|
21128
|
+
const summaryMessage = userMessage(appendOpenPlan(renderCompactionSummary(summary), source.messages));
|
|
21129
|
+
const retainedInstruction = pendingMessages.length === 0 && !retainUserMessages ? await loadLastInstruction(args.conversationId) : void 0;
|
|
21130
|
+
const instructionMessages = retainedInstruction ? [retainedInstruction.message] : pendingMessages.map((entry) => entry.message);
|
|
21131
|
+
const instructionProvenance = retainedInstruction ? [retainedInstruction.provenance] : pendingMessages.map((entry) => entry.provenance);
|
|
21132
|
+
const instructionTimestamp = instructionMessages[0]?.timestamp;
|
|
21133
|
+
const contextMessage = turnRuntimeContextMessage(args.runtimeContextMessages ?? args.piMessages, args.turnStartMessageIndex, typeof instructionTimestamp === "number" ? instructionTimestamp : void 0);
|
|
21134
|
+
const contextEntries = contextMessage ? [{
|
|
21135
|
+
message: contextMessage,
|
|
21136
|
+
provenance: contextProvenance
|
|
21137
|
+
}] : [];
|
|
21138
|
+
const instructionEntries = instructionMessages.map((message, index) => ({
|
|
21139
|
+
message,
|
|
21140
|
+
provenance: instructionProvenance[index],
|
|
21141
|
+
...index === 0 && retainedInstruction ? { sourceEventSeq: retainedInstruction.sourceEventSeq } : void 0
|
|
21012
21142
|
}));
|
|
21013
|
-
const
|
|
21014
|
-
|
|
21015
|
-
|
|
21016
|
-
|
|
21017
|
-
|
|
21018
|
-
|
|
21019
|
-
|
|
21020
|
-
|
|
21021
|
-
|
|
21022
|
-
|
|
21023
|
-
|
|
21024
|
-
...
|
|
21143
|
+
const summaryEntry = {
|
|
21144
|
+
message: summaryMessage,
|
|
21145
|
+
provenance: contextProvenance
|
|
21146
|
+
};
|
|
21147
|
+
const retainedUserMessages = retainUserMessages ? await loadRetainedUserMessages(args.conversationId, instructionMessages) : [];
|
|
21148
|
+
const replacement = retainUserMessages ? [
|
|
21149
|
+
...retainedUserMessages,
|
|
21150
|
+
summaryEntry,
|
|
21151
|
+
...contextEntries,
|
|
21152
|
+
...instructionEntries
|
|
21153
|
+
] : [
|
|
21154
|
+
...contextEntries,
|
|
21155
|
+
...instructionEntries,
|
|
21156
|
+
summaryEntry
|
|
21025
21157
|
];
|
|
21158
|
+
const retainedMessageCount = retainedUserMessages.length + instructionMessages.length;
|
|
21026
21159
|
const messages = replacement.map((entry) => entry.message);
|
|
21027
|
-
const
|
|
21028
|
-
|
|
21029
|
-
setSpanAttributes({
|
|
21030
|
-
"app.compaction.input.estimate": budget.estimatedTokens,
|
|
21031
|
-
"app.compaction.replacement.estimate": replacementTokens,
|
|
21032
|
-
"app.compaction.threshold": budget.triggerTokens,
|
|
21033
|
-
"app.compaction.carried_messages": kept.length,
|
|
21034
|
-
"app.compaction.carried.estimate": estimateReplacementTokens(trimmedEntries.map((entry) => entry.message)),
|
|
21035
|
-
"app.compaction.trimmed_results": trimming.trimmedResults,
|
|
21036
|
-
"app.compaction.trimmed_chars": trimming.removedChars
|
|
21037
|
-
});
|
|
21038
|
-
if (replacementTokens > targetTokens) return discard("over_target");
|
|
21160
|
+
const replacementInputTokens = estimateReplacementTokens(messages, args.requestOverheadTokens);
|
|
21161
|
+
if (replacementInputTokens >= inputLimitTokens) throw new ContextInputLimitExceededError(replacementInputTokens, inputLimitTokens);
|
|
21039
21162
|
args.signal?.throwIfAborted();
|
|
21040
|
-
|
|
21163
|
+
await getConversationEventStore().replaceHistory(args.conversationId, {
|
|
21041
21164
|
createdAtMs: Date.now(),
|
|
21042
21165
|
data: {
|
|
21043
21166
|
type: "compaction",
|
|
21044
21167
|
modelId: args.modelId,
|
|
21045
21168
|
details: {
|
|
21046
21169
|
reason: "capacity",
|
|
21047
|
-
estimatedInputTokens:
|
|
21048
|
-
replacementInputTokens
|
|
21049
|
-
triggerTokens
|
|
21050
|
-
inputLimitTokens
|
|
21051
|
-
inputMessageCount:
|
|
21052
|
-
retainedMessageCount
|
|
21053
|
-
summaryChars:
|
|
21170
|
+
estimatedInputTokens: source.estimatedTokens,
|
|
21171
|
+
replacementInputTokens,
|
|
21172
|
+
triggerTokens,
|
|
21173
|
+
inputLimitTokens,
|
|
21174
|
+
inputMessageCount: source.messages.length,
|
|
21175
|
+
retainedMessageCount,
|
|
21176
|
+
summaryChars: summary.length
|
|
21054
21177
|
},
|
|
21055
|
-
summary
|
|
21178
|
+
summary,
|
|
21056
21179
|
replacementHistory: replacement.map((entry) => ({
|
|
21057
21180
|
item: historyItemFromPiMessage(entry.message, entry.provenance),
|
|
21058
21181
|
...entry.sourceEventSeq === void 0 ? void 0 : { sourceEventSeq: entry.sourceEventSeq }
|
|
21059
21182
|
}))
|
|
21060
21183
|
}
|
|
21061
|
-
}
|
|
21062
|
-
|
|
21063
|
-
|
|
21064
|
-
|
|
21065
|
-
|
|
21066
|
-
"app.compaction.
|
|
21067
|
-
"app.compaction.
|
|
21184
|
+
});
|
|
21185
|
+
setSpanAttributes({
|
|
21186
|
+
"app.compaction.outcome": "compacted",
|
|
21187
|
+
"app.compaction.input_messages": source.messages.length,
|
|
21188
|
+
"app.compaction.retained_messages": retainedMessageCount,
|
|
21189
|
+
"app.compaction.summary_chars": summary.length,
|
|
21190
|
+
"app.compaction.input.estimate": source.estimatedTokens,
|
|
21191
|
+
"app.compaction.replacement.estimate": replacementInputTokens,
|
|
21192
|
+
"app.compaction.input_limit": inputLimitTokens,
|
|
21193
|
+
"app.compaction.threshold": triggerTokens
|
|
21068
21194
|
});
|
|
21069
21195
|
return {
|
|
21070
|
-
compacted: true,
|
|
21071
|
-
piMessages: messages
|
|
21072
|
-
};
|
|
21073
|
-
}
|
|
21074
|
-
// src/chat/agent/context-summary.ts
|
|
21075
|
-
/** Prompt name of the summary request on its `gen_ai.chat` span. */
|
|
21076
|
-
const CONTEXT_COMPACTION_PROMPT_NAME = "junior.context_compaction";
|
|
21077
|
-
const SUMMARY_MAX_TOKENS = 8e3;
|
|
21078
|
-
const SUMMARY_INSTRUCTION = `Stop work on the task now. Do not call tools. Write a summary of the conversation so far. The summary replaces the earlier history, and you will continue the work from the summary alone.
|
|
21079
|
-
|
|
21080
|
-
Return only the summary inside <summary></summary> tags. Use these sections in this order. Write each item as one short line that starts with "- ". Write "- None" for an empty section.
|
|
21081
|
-
|
|
21082
|
-
## Goal
|
|
21083
|
-
## Constraints & preferences
|
|
21084
|
-
## Progress
|
|
21085
|
-
### Done
|
|
21086
|
-
### In progress
|
|
21087
|
-
### Blocked
|
|
21088
|
-
## Key decisions
|
|
21089
|
-
## Open asks
|
|
21090
|
-
User requests that are not complete yet, quoted in the user's exact words.
|
|
21091
|
-
## References
|
|
21092
|
-
Exact file paths, IDs, URLs, commands, and error text that the work needs. At most 20 items.
|
|
21093
|
-
## Next steps
|
|
21094
|
-
|
|
21095
|
-
Rules:
|
|
21096
|
-
- Keep the summary under 1,000 words.
|
|
21097
|
-
- Leave out the system prompt, AGENTS.md instructions, tool descriptions, and environment details. They are added again.
|
|
21098
|
-
- Do not mention this request or the summary itself.
|
|
21099
|
-
- If the history contains an earlier summary, update it. Keep the items that are still true, move finished work to Done, and remove stale items. When the earlier summary and newer history disagree, use the newer history.`;
|
|
21100
|
-
const SUMMARY_NUDGE = "Do not call tools. Keep the summary short. Return only the summary inside <summary></summary> tags.";
|
|
21101
|
-
/** Raised when the model returns no usable summary after one nudge. */
|
|
21102
|
-
var ContextSummaryError = class extends Error {
|
|
21103
|
-
failure;
|
|
21104
|
-
constructor(failure) {
|
|
21105
|
-
super(`Context summary failed: ${failure}`);
|
|
21106
|
-
this.failure = failure;
|
|
21107
|
-
this.name = "ContextSummaryError";
|
|
21108
|
-
}
|
|
21109
|
-
};
|
|
21110
|
-
/**
|
|
21111
|
-
* Build the model request that the agent loop sends for these messages.
|
|
21112
|
-
*
|
|
21113
|
-
* This repeats the steps of pi-agent-core before each model call
|
|
21114
|
-
* (`streamAssistantResponse` and `createLoopConfig`, which Pi does not
|
|
21115
|
-
* export): transform and convert the messages, then read the model,
|
|
21116
|
-
* reasoning, tools, and request options from the agent. A unit test compares
|
|
21117
|
-
* this request with the one that a real Pi `Agent` loop passes to `streamFn`,
|
|
21118
|
-
* so it fails when Pi changes these steps.
|
|
21119
|
-
*/
|
|
21120
|
-
async function buildAgentModelRequest(agent, messages, signal) {
|
|
21121
|
-
const { model, systemPrompt, thinkingLevel, tools } = agent.state;
|
|
21122
|
-
const transformed = agent.transformContext ? await agent.transformContext(messages, signal) : messages;
|
|
21123
|
-
return {
|
|
21124
|
-
model,
|
|
21125
|
-
context: {
|
|
21126
|
-
systemPrompt,
|
|
21127
|
-
messages: await agent.convertToLlm(transformed),
|
|
21128
|
-
tools
|
|
21129
|
-
},
|
|
21130
|
-
options: {
|
|
21131
|
-
reasoning: thinkingLevel === "off" ? void 0 : thinkingLevel,
|
|
21132
|
-
sessionId: agent.sessionId,
|
|
21133
|
-
onPayload: agent.onPayload,
|
|
21134
|
-
onResponse: agent.onResponse,
|
|
21135
|
-
transport: agent.transport,
|
|
21136
|
-
thinkingBudgets: agent.thinkingBudgets,
|
|
21137
|
-
maxRetryDelayMs: agent.maxRetryDelayMs,
|
|
21138
|
-
apiKey: await agent.getApiKey?.(model.provider) || void 0,
|
|
21139
|
-
signal
|
|
21140
|
-
}
|
|
21141
|
-
};
|
|
21142
|
-
}
|
|
21143
|
-
function userText(text) {
|
|
21144
|
-
return {
|
|
21145
|
-
role: "user",
|
|
21146
|
-
content: [{
|
|
21147
|
-
type: "text",
|
|
21148
|
-
text
|
|
21149
|
-
}],
|
|
21150
|
-
timestamp: Date.now()
|
|
21196
|
+
compacted: true,
|
|
21197
|
+
piMessages: messages
|
|
21151
21198
|
};
|
|
21152
21199
|
}
|
|
21153
|
-
|
|
21154
|
-
|
|
21155
|
-
|
|
21156
|
-
|
|
21157
|
-
|
|
21158
|
-
|
|
21159
|
-
|
|
21160
|
-
|
|
21161
|
-
if (message.stopReason === "error" || message.stopReason === "aborted") throw createProviderError(message.errorMessage ?? message.stopReason, { modelId: request.model.id });
|
|
21162
|
-
return message;
|
|
21200
|
+
// src/chat/services/tool-result-trimming.ts
|
|
21201
|
+
/** Results up to this many text characters stay whole. */
|
|
21202
|
+
const MAX_KEPT_RESULT_CHARS = 2e3;
|
|
21203
|
+
/** Error results explain failures, so they stay whole up to this size. */
|
|
21204
|
+
const MAX_KEPT_ERROR_CHARS = 8e3;
|
|
21205
|
+
const EDGE_CHARS = 500;
|
|
21206
|
+
function role(message) {
|
|
21207
|
+
return message.role;
|
|
21163
21208
|
}
|
|
21164
|
-
|
|
21165
|
-
|
|
21166
|
-
|
|
21167
|
-
if (message.stopReason === "length") return { failure: "max_tokens" };
|
|
21168
|
-
const text = message.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("").trim();
|
|
21169
|
-
if (!text) return { failure: "empty" };
|
|
21170
|
-
const summary = /<summary>([\s\S]*?)<\/summary>/.exec(text)?.[1]?.trim();
|
|
21171
|
-
return summary ? { summary } : { failure: "missing_summary" };
|
|
21209
|
+
function resultParts(message) {
|
|
21210
|
+
const content = message.content;
|
|
21211
|
+
return Array.isArray(content) ? content : [];
|
|
21172
21212
|
}
|
|
21173
|
-
|
|
21174
|
-
|
|
21175
|
-
*
|
|
21176
|
-
* A tool call, a stop at the output limit, empty output, or output without
|
|
21177
|
-
* `<summary>` tags gets one nudge. A second failure throws
|
|
21178
|
-
* `ContextSummaryError`, so the caller keeps the full history.
|
|
21179
|
-
*/
|
|
21180
|
-
async function requestContextSummary(request, streamFn) {
|
|
21181
|
-
const instruction = userText(SUMMARY_INSTRUCTION);
|
|
21182
|
-
const first = readSummary(await complete(request, streamFn, [instruction]));
|
|
21183
|
-
if ("summary" in first) return first.summary;
|
|
21184
|
-
logWarn("context_compaction.summary.nudged", { "app.compaction.summary_failure": first.failure });
|
|
21185
|
-
const second = readSummary(await complete(request, streamFn, [instruction, userText(SUMMARY_NUDGE)]));
|
|
21186
|
-
if ("summary" in second) return second.summary;
|
|
21187
|
-
throw new ContextSummaryError(second.failure);
|
|
21213
|
+
function resultText(parts) {
|
|
21214
|
+
return parts.map((part) => part.type === "text" && typeof part.text === "string" ? part.text : "").join("\n");
|
|
21188
21215
|
}
|
|
21189
|
-
|
|
21190
|
-
|
|
21191
|
-
* Background compaction: prepare a summary before the history is full.
|
|
21192
|
-
*
|
|
21193
|
-
* When a Turn completes and its last model request was at or above the mark,
|
|
21194
|
-
* the Turn appends `compaction_requested` and sends a job. The job asks the
|
|
21195
|
-
* agent model for a summary of the history up to the marked event and
|
|
21196
|
-
* appends `compaction_prepared`. Turns keep the full history until a later
|
|
21197
|
-
* change swaps the summary in. Blocking compaction stays the fallback.
|
|
21198
|
-
*
|
|
21199
|
-
* The summary request repeats the system prompt and tools of the last agent
|
|
21200
|
-
* request, so the provider can read its cached prompt prefix. The job runs in
|
|
21201
|
-
* another request, so the Turn stores them in the State adapter.
|
|
21202
|
-
*/
|
|
21203
|
-
/**
|
|
21204
|
-
* Failed or discarded attempts for one History version before background
|
|
21205
|
-
* tries stop.
|
|
21206
|
-
*/
|
|
21207
|
-
const MAX_FAILED_ATTEMPTS = 2;
|
|
21208
|
-
/**
|
|
21209
|
-
* A request without a prepared result after this long counts as a failed
|
|
21210
|
-
* attempt, so a later Turn can request again. This covers a lost job.
|
|
21211
|
-
*/
|
|
21212
|
-
const REQUEST_TIMEOUT_MS = 6e5;
|
|
21213
|
-
/** The queue drops a message after this long, so the snapshot can go too. */
|
|
21214
|
-
const SNAPSHOT_TTL_MS = QUEUE_SIGNATURE_MAX_AGE_MS;
|
|
21215
|
-
function snapshotKey(message) {
|
|
21216
|
-
return `${backgroundCompactionId(message)}:snapshot`;
|
|
21216
|
+
function pointer(seq) {
|
|
21217
|
+
return `readConversationEvent({ seq: ${seq} })`;
|
|
21217
21218
|
}
|
|
21218
|
-
/**
|
|
21219
|
-
function
|
|
21220
|
-
|
|
21221
|
-
|
|
21222
|
-
|
|
21223
|
-
|
|
21224
|
-
|
|
21225
|
-
}
|
|
21226
|
-
|
|
21219
|
+
/** Replace a long result text with a header, its edges, and a read-back pointer. */
|
|
21220
|
+
function clearedText(toolName, text, seq) {
|
|
21221
|
+
return [
|
|
21222
|
+
`[Tool result cleared to save context: ${toolName}, ${text.length.toLocaleString("en-US")} chars. Full result: ${pointer(seq)}`,
|
|
21223
|
+
"First 500 chars:",
|
|
21224
|
+
text.slice(0, EDGE_CHARS),
|
|
21225
|
+
"Last 500 chars:",
|
|
21226
|
+
`${text.slice(-500)}]`
|
|
21227
|
+
].join("\n");
|
|
21228
|
+
}
|
|
21229
|
+
function trimResult(message, seq) {
|
|
21230
|
+
const parts = resultParts(message);
|
|
21231
|
+
const text = resultText(parts);
|
|
21232
|
+
const hasImage = parts.some((part) => part.type === "image");
|
|
21233
|
+
const keptChars = message.isError === true ? MAX_KEPT_ERROR_CHARS : MAX_KEPT_RESULT_CHARS;
|
|
21234
|
+
const clearText = text.length > keptChars;
|
|
21235
|
+
if (!clearText && !hasImage) return;
|
|
21236
|
+
const toolName = String(message.toolName ?? "tool");
|
|
21237
|
+
const content = clearText ? [{
|
|
21238
|
+
type: "text",
|
|
21239
|
+
text: clearedText(toolName, text, seq)
|
|
21240
|
+
}] : parts.map((part) => part.type === "image" ? {
|
|
21241
|
+
type: "text",
|
|
21242
|
+
text: `[image cleared: ${toolName}, seq ${seq}]`
|
|
21243
|
+
} : part);
|
|
21244
|
+
if (clearText && hasImage) content.push({
|
|
21245
|
+
type: "text",
|
|
21246
|
+
text: `[image cleared: ${toolName}, seq ${seq}]`
|
|
21247
|
+
});
|
|
21248
|
+
return {
|
|
21249
|
+
message: {
|
|
21250
|
+
...message,
|
|
21251
|
+
content
|
|
21252
|
+
},
|
|
21253
|
+
removedChars: Math.max(0, text.length - resultText(content).length)
|
|
21254
|
+
};
|
|
21227
21255
|
}
|
|
21228
21256
|
/**
|
|
21229
|
-
*
|
|
21230
|
-
* version. It may not while a request is pending, while a ready summary is
|
|
21231
|
-
* still unused, or after the attempt limit.
|
|
21257
|
+
* Trim old tool results in a replacement history.
|
|
21232
21258
|
*
|
|
21233
|
-
*
|
|
21234
|
-
*
|
|
21235
|
-
*
|
|
21236
|
-
*
|
|
21237
|
-
*
|
|
21259
|
+
* Results after the last Turn instruction belong to the latest Turn and stay
|
|
21260
|
+
* whole. Runtime context and summaries are user messages too, so they do not
|
|
21261
|
+
* mark a Turn. So do short results, error results up to a cap, and
|
|
21262
|
+
* results that have no source event to point to. Images outside the latest
|
|
21263
|
+
* Turn become a short note.
|
|
21238
21264
|
*/
|
|
21239
|
-
function
|
|
21240
|
-
|
|
21241
|
-
|
|
21242
|
-
|
|
21243
|
-
createdAtMs: event.createdAtMs
|
|
21265
|
+
function trimToolResults(entries) {
|
|
21266
|
+
let latestInstructionIndex = -1;
|
|
21267
|
+
entries.forEach((entry, index) => {
|
|
21268
|
+
if (hasCurrentInstruction(entry.message)) latestInstructionIndex = index;
|
|
21244
21269
|
});
|
|
21245
|
-
|
|
21246
|
-
|
|
21247
|
-
|
|
21248
|
-
|
|
21249
|
-
|
|
21250
|
-
|
|
21251
|
-
|
|
21252
|
-
|
|
21253
|
-
|
|
21270
|
+
const trimming = {
|
|
21271
|
+
trimmedResults: 0,
|
|
21272
|
+
removedChars: 0
|
|
21273
|
+
};
|
|
21274
|
+
return {
|
|
21275
|
+
entries: entries.map((entry, index) => {
|
|
21276
|
+
if (index > latestInstructionIndex || role(entry.message) !== "toolResult" || entry.sourceEventSeq === void 0) return entry;
|
|
21277
|
+
const result = trimResult(entry.message, entry.sourceEventSeq);
|
|
21278
|
+
if (!result) return entry;
|
|
21279
|
+
trimming.trimmedResults += 1;
|
|
21280
|
+
trimming.removedChars += result.removedChars;
|
|
21281
|
+
return {
|
|
21282
|
+
...entry,
|
|
21283
|
+
message: result.message
|
|
21284
|
+
};
|
|
21285
|
+
}),
|
|
21286
|
+
trimming
|
|
21287
|
+
};
|
|
21254
21288
|
}
|
|
21289
|
+
// src/chat/services/context-compaction-swap.ts
|
|
21255
21290
|
/**
|
|
21256
|
-
*
|
|
21257
|
-
* Turn was at or above the mark.
|
|
21291
|
+
* Prepared-summary swap.
|
|
21258
21292
|
*
|
|
21259
|
-
*
|
|
21260
|
-
*
|
|
21261
|
-
*
|
|
21262
|
-
*
|
|
21263
|
-
*
|
|
21293
|
+
* A background job writes `compaction_prepared` with a summary of the history
|
|
21294
|
+
* up to `markSeq`. The Turn swaps it in without a model call: retained user
|
|
21295
|
+
* messages, the summary, then every message after the mark. Turn start swaps
|
|
21296
|
+
* a ready summary at once. Between model calls, a swap runs only above the
|
|
21297
|
+
* compaction threshold, in place of a blocking summary call. A summary that
|
|
21298
|
+
* no longer matches the history is discarded, and the Turn carries on as if
|
|
21299
|
+
* none existed.
|
|
21264
21300
|
*/
|
|
21265
|
-
|
|
21266
|
-
|
|
21267
|
-
const
|
|
21268
|
-
|
|
21269
|
-
|
|
21270
|
-
|
|
21271
|
-
|
|
21272
|
-
|
|
21273
|
-
|
|
21274
|
-
|
|
21275
|
-
|
|
21276
|
-
|
|
21277
|
-
|
|
21278
|
-
|
|
21279
|
-
|
|
21280
|
-
|
|
21281
|
-
|
|
21282
|
-
|
|
21283
|
-
|
|
21284
|
-
if (historyVersion === void 0 || !mayRequest(events, historyVersion, nowMs, args.turnStartedAtMs)) return;
|
|
21285
|
-
const projection = projectConversationEvents(events);
|
|
21286
|
-
const markSeq = Math.max(projection.seqs.at(-1) ?? -1, projection.replacementSeq ?? -1);
|
|
21287
|
-
if (markSeq < 0) return;
|
|
21288
|
-
const message = {
|
|
21289
|
-
conversationId: args.conversationId,
|
|
21290
|
-
historyVersion,
|
|
21291
|
-
markSeq
|
|
21292
|
-
};
|
|
21293
|
-
const { systemPrompt, thinkingLevel, tools } = args.agent.state;
|
|
21294
|
-
const snapshot = {
|
|
21295
|
-
conversationPrivacy: args.conversationPrivacy ?? "private",
|
|
21296
|
-
inputSize: args.inputSize,
|
|
21297
|
-
modelId: args.modelId,
|
|
21298
|
-
systemPrompt,
|
|
21299
|
-
thinkingLevel,
|
|
21300
|
-
tools: tools.map((tool) => ({
|
|
21301
|
-
name: tool.name,
|
|
21302
|
-
label: tool.label,
|
|
21303
|
-
description: tool.description,
|
|
21304
|
-
parameters: tool.parameters,
|
|
21305
|
-
...tool.constrainedSampling === void 0 ? void 0 : { constrainedSampling: tool.constrainedSampling }
|
|
21306
|
-
}))
|
|
21307
|
-
};
|
|
21308
|
-
await getStateAdapter().set(snapshotKey(message), JSON.parse(JSON.stringify(snapshot)), SNAPSHOT_TTL_MS);
|
|
21309
|
-
if ((await eventStore.append(args.conversationId, [{
|
|
21310
|
-
idempotencyKey: `${backgroundCompactionId(message)}:requested`,
|
|
21311
|
-
createdAtMs: nowMs,
|
|
21312
|
-
data: {
|
|
21313
|
-
type: "compaction_requested",
|
|
21314
|
-
markSeq,
|
|
21315
|
-
historyVersion,
|
|
21316
|
-
modelId: args.modelId
|
|
21317
|
-
}
|
|
21318
|
-
}], { activity: "preserve" })).length === 0) return;
|
|
21319
|
-
await args.queue.send(message);
|
|
21320
|
-
logInfo("context_compaction.background.requested", {
|
|
21321
|
-
"app.compaction.mark_seq": markSeq,
|
|
21322
|
-
"app.compaction.history_version": historyVersion,
|
|
21323
|
-
"app.compaction.input.size": args.inputSize
|
|
21301
|
+
/** Compare a message across a durable commit, which drops undefined fields. */
|
|
21302
|
+
function durableIdentity(message) {
|
|
21303
|
+
const { role, timestamp, content, toolCallId } = message;
|
|
21304
|
+
return JSON.parse(JSON.stringify({
|
|
21305
|
+
role,
|
|
21306
|
+
timestamp,
|
|
21307
|
+
content,
|
|
21308
|
+
toolCallId
|
|
21309
|
+
}));
|
|
21310
|
+
}
|
|
21311
|
+
function committedPrefixLength(messages, committed) {
|
|
21312
|
+
const limit = Math.min(messages.length, committed.length);
|
|
21313
|
+
for (let index = 0; index < limit; index += 1) if (!isDeepStrictEqual(durableIdentity(messages[index]), durableIdentity(committed[index]))) return index;
|
|
21314
|
+
return limit;
|
|
21315
|
+
}
|
|
21316
|
+
function discard(reason) {
|
|
21317
|
+
setSpanAttributes({
|
|
21318
|
+
"app.compaction.outcome": "discarded",
|
|
21319
|
+
"app.compaction.discard_reason": reason
|
|
21324
21320
|
});
|
|
21321
|
+
return { compacted: false };
|
|
21325
21322
|
}
|
|
21326
|
-
/**
|
|
21327
|
-
|
|
21328
|
-
|
|
21329
|
-
|
|
21330
|
-
|
|
21331
|
-
|
|
21323
|
+
/**
|
|
21324
|
+
* Swap a ready prepared summary into history, or run today's capacity
|
|
21325
|
+
* compaction when none can be used.
|
|
21326
|
+
*/
|
|
21327
|
+
async function compactWithPreparedSummary(args, summarize) {
|
|
21328
|
+
const swapped = await swapPreparedCompaction(args);
|
|
21329
|
+
if (swapped.compacted || swapped.reason === "history_conflict") return swapped;
|
|
21330
|
+
return await compactActiveContextIfNeeded(args, summarize);
|
|
21332
21331
|
}
|
|
21333
21332
|
/**
|
|
21334
|
-
*
|
|
21335
|
-
*
|
|
21336
|
-
*
|
|
21337
|
-
* fixed failure label. It writes nothing when the request is no longer in
|
|
21338
|
-
* the current History version, because no Turn could use the summary.
|
|
21339
|
-
* `streamFn` replaces the model stream, for tests.
|
|
21333
|
+
* Replace history with a ready prepared summary. Turn start swaps whenever
|
|
21334
|
+
* one is ready. Between model calls, swap only above the compaction
|
|
21335
|
+
* threshold.
|
|
21340
21336
|
*/
|
|
21341
|
-
async function
|
|
21342
|
-
const
|
|
21343
|
-
|
|
21344
|
-
|
|
21345
|
-
|
|
21346
|
-
|
|
21347
|
-
|
|
21337
|
+
async function swapPreparedCompaction(args) {
|
|
21338
|
+
const pendingMessages = args.pendingMessages ?? [];
|
|
21339
|
+
const sourceMessages = [...args.piMessages, ...pendingMessages.map((entry) => entry.message)];
|
|
21340
|
+
const triggerTokens = getAgentContextCompactionTriggerTokens(args.modelId);
|
|
21341
|
+
const estimatedTokens = estimateHistoryTokens(sourceMessages);
|
|
21342
|
+
if (args.mode !== "blocking" && estimatedTokens <= triggerTokens) return {
|
|
21343
|
+
compacted: false,
|
|
21344
|
+
reason: "below_threshold"
|
|
21345
|
+
};
|
|
21346
|
+
const latest = await loadLatestBackgroundCompaction(args.conversationId);
|
|
21347
|
+
if (!latest) return { compacted: false };
|
|
21348
|
+
return await withCompactionSpan(args.mode, async () => {
|
|
21349
|
+
const { event, historyVersion } = latest;
|
|
21350
|
+
if (event.data.type !== "compaction_prepared" || event.data.outcome !== "ready") {
|
|
21351
|
+
setSpanAttributes({ "app.compaction.outcome": "not_ready" });
|
|
21352
|
+
return { compacted: false };
|
|
21353
|
+
}
|
|
21354
|
+
setSpanAttributes({ "app.compaction.prepared.age_ms": Math.max(0, Date.now() - event.createdAtMs) });
|
|
21355
|
+
if (event.data.historyVersion !== historyVersion) return discard("history_version_changed");
|
|
21356
|
+
return await applyPreparedSummary(args, event.data, {
|
|
21357
|
+
estimatedTokens,
|
|
21358
|
+
historyVersion,
|
|
21359
|
+
triggerTokens
|
|
21348
21360
|
});
|
|
21349
|
-
|
|
21350
|
-
setSpanAttributes({ "app.compaction.outcome": outcome });
|
|
21351
|
-
}));
|
|
21361
|
+
});
|
|
21352
21362
|
}
|
|
21353
|
-
async function
|
|
21354
|
-
const
|
|
21355
|
-
const
|
|
21356
|
-
const
|
|
21357
|
-
const
|
|
21358
|
-
const
|
|
21359
|
-
|
|
21360
|
-
|
|
21361
|
-
|
|
21362
|
-
|
|
21363
|
-
|
|
21364
|
-
|
|
21365
|
-
|
|
21366
|
-
|
|
21367
|
-
|
|
21368
|
-
|
|
21363
|
+
async function applyPreparedSummary(args, prepared, budget) {
|
|
21364
|
+
const pendingMessages = args.pendingMessages ?? [];
|
|
21365
|
+
const projection = await loadConversationProjection({ conversationId: args.conversationId });
|
|
21366
|
+
const committedLength = committedPrefixLength(args.piMessages, projection.messages);
|
|
21367
|
+
const firstAfterMark = projection.seqs.slice(0, committedLength).findIndex((seq) => seq > prepared.markSeq);
|
|
21368
|
+
const markIndex = firstAfterMark === -1 ? committedLength : firstAfterMark;
|
|
21369
|
+
const summarized = args.piMessages.slice(0, markIndex);
|
|
21370
|
+
const kept = args.piMessages.slice(markIndex);
|
|
21371
|
+
if (kept[0]?.role === "toolResult") return discard("split_tool_call");
|
|
21372
|
+
const retained = selectRetainedUserMessageEntries(trimTrailingAssistantMessages(summarized)).map((entry) => ({
|
|
21373
|
+
message: entry.message,
|
|
21374
|
+
provenance: projection.provenance[entry.sourceIndex],
|
|
21375
|
+
sourceEventSeq: projection.seqs[entry.sourceIndex]
|
|
21376
|
+
}));
|
|
21377
|
+
const contextMessage = summarizedRuntimeContextMessage(summarized, [...kept, ...pendingMessages.map((entry) => entry.message)]);
|
|
21378
|
+
const { entries: trimmedEntries, trimming } = trimToolResults(kept.map((message, offset) => {
|
|
21379
|
+
const index = markIndex + offset;
|
|
21380
|
+
return index < committedLength ? {
|
|
21381
|
+
message,
|
|
21382
|
+
provenance: projection.provenance[index],
|
|
21383
|
+
sourceEventSeq: projection.seqs[index]
|
|
21384
|
+
} : {
|
|
21385
|
+
message,
|
|
21386
|
+
provenance: contextProvenance
|
|
21387
|
+
};
|
|
21388
|
+
}));
|
|
21389
|
+
const replacement = [
|
|
21390
|
+
...contextMessage ? [{
|
|
21391
|
+
message: contextMessage,
|
|
21392
|
+
provenance: contextProvenance
|
|
21393
|
+
}] : [],
|
|
21394
|
+
...retained,
|
|
21395
|
+
{
|
|
21396
|
+
message: userMessage(appendOpenPlan(renderCompactionSummary(prepared.summary), summarized)),
|
|
21397
|
+
provenance: contextProvenance
|
|
21398
|
+
},
|
|
21399
|
+
...trimmedEntries,
|
|
21400
|
+
...pendingMessages
|
|
21401
|
+
];
|
|
21402
|
+
const messages = replacement.map((entry) => entry.message);
|
|
21403
|
+
const replacementTokens = estimateReplacementTokens(messages, args.requestOverheadTokens);
|
|
21404
|
+
const targetTokens = calculateContextCompactionTargetTokens(budget.triggerTokens);
|
|
21405
|
+
setSpanAttributes({
|
|
21406
|
+
"app.compaction.input.estimate": budget.estimatedTokens,
|
|
21407
|
+
"app.compaction.replacement.estimate": replacementTokens,
|
|
21408
|
+
"app.compaction.threshold": budget.triggerTokens,
|
|
21409
|
+
"app.compaction.carried_messages": kept.length,
|
|
21410
|
+
"app.compaction.carried.estimate": estimateReplacementTokens(trimmedEntries.map((entry) => entry.message)),
|
|
21411
|
+
"app.compaction.trimmed_results": trimming.trimmedResults,
|
|
21412
|
+
"app.compaction.trimmed_chars": trimming.removedChars
|
|
21413
|
+
});
|
|
21414
|
+
if (replacementTokens > targetTokens) return discard("over_target");
|
|
21415
|
+
args.signal?.throwIfAborted();
|
|
21416
|
+
if ((await getConversationEventStore().replaceHistory(args.conversationId, {
|
|
21417
|
+
createdAtMs: Date.now(),
|
|
21418
|
+
data: {
|
|
21419
|
+
type: "compaction",
|
|
21420
|
+
modelId: args.modelId,
|
|
21421
|
+
details: {
|
|
21422
|
+
reason: "capacity",
|
|
21423
|
+
estimatedInputTokens: budget.estimatedTokens,
|
|
21424
|
+
replacementInputTokens: replacementTokens,
|
|
21425
|
+
triggerTokens: budget.triggerTokens,
|
|
21426
|
+
inputLimitTokens: getAgentContextInputLimitTokens(args.modelId),
|
|
21427
|
+
inputMessageCount: args.piMessages.length + pendingMessages.length,
|
|
21428
|
+
retainedMessageCount: retained.length + kept.length + pendingMessages.length,
|
|
21429
|
+
summaryChars: prepared.summary.length
|
|
21430
|
+
},
|
|
21431
|
+
summary: prepared.summary,
|
|
21432
|
+
replacementHistory: replacement.map((entry) => ({
|
|
21433
|
+
item: historyItemFromPiMessage(entry.message, entry.provenance),
|
|
21434
|
+
...entry.sourceEventSeq === void 0 ? void 0 : { sourceEventSeq: entry.sourceEventSeq }
|
|
21435
|
+
}))
|
|
21369
21436
|
}
|
|
21370
|
-
|
|
21371
|
-
|
|
21372
|
-
|
|
21373
|
-
data: {
|
|
21374
|
-
type: "compaction_prepared",
|
|
21375
|
-
markSeq: message.markSeq,
|
|
21376
|
-
historyVersion: message.historyVersion,
|
|
21377
|
-
modelId: requested.modelId,
|
|
21378
|
-
...result
|
|
21379
|
-
}
|
|
21380
|
-
}], { activity: "preserve" });
|
|
21381
|
-
await state.delete(snapshotKey(message));
|
|
21382
|
-
if (result.outcome === "failed") setSpanAttributes({ "error.type": result.errorType });
|
|
21383
|
-
return result.outcome;
|
|
21437
|
+
}, { expectedHistoryVersion: budget.historyVersion })).status === "conflict") return {
|
|
21438
|
+
...discard("conflict"),
|
|
21439
|
+
reason: "history_conflict"
|
|
21384
21440
|
};
|
|
21385
|
-
|
|
21386
|
-
|
|
21387
|
-
|
|
21388
|
-
errorType: "timeout"
|
|
21389
|
-
});
|
|
21390
|
-
const snapshot = await state.get(snapshotKey(message));
|
|
21391
|
-
if (!snapshot) return await writePrepared({
|
|
21392
|
-
outcome: "failed",
|
|
21393
|
-
errorType: "snapshot_missing"
|
|
21394
|
-
});
|
|
21395
|
-
setSpanAttributes({ "app.compaction.input.size": snapshot.inputSize });
|
|
21396
|
-
const projection = projectConversationEvents(events, { maxSeq: message.markSeq });
|
|
21397
|
-
const signal = AbortSignal.timeout(remainingMs);
|
|
21398
|
-
let summary;
|
|
21399
|
-
try {
|
|
21400
|
-
summary = await runWithConversationPrivacy(snapshot.conversationPrivacy, async () => {
|
|
21401
|
-
const summaryStreamFn = createTracedStreamFn({
|
|
21402
|
-
conversationPrivacy: snapshot.conversationPrivacy,
|
|
21403
|
-
promptName: CONTEXT_COMPACTION_PROMPT_NAME,
|
|
21404
|
-
...streamFn ? { base: streamFn } : void 0
|
|
21405
|
-
});
|
|
21406
|
-
return await requestContextSummary(await buildAgentModelRequest(new Agent({
|
|
21407
|
-
getApiKey: getGatewayApiKey,
|
|
21408
|
-
sessionId: message.conversationId,
|
|
21409
|
-
streamFn: summaryStreamFn,
|
|
21410
|
-
initialState: {
|
|
21411
|
-
systemPrompt: snapshot.systemPrompt,
|
|
21412
|
-
model: resolveGatewayModel(snapshot.modelId),
|
|
21413
|
-
thinkingLevel: snapshot.thinkingLevel,
|
|
21414
|
-
tools: snapshot.tools.map((tool) => ({
|
|
21415
|
-
...tool,
|
|
21416
|
-
execute: async () => {
|
|
21417
|
-
throw new Error("Background compaction does not run tools");
|
|
21418
|
-
}
|
|
21419
|
-
}))
|
|
21420
|
-
}
|
|
21421
|
-
}), projection.messages, signal), summaryStreamFn);
|
|
21422
|
-
});
|
|
21423
|
-
} catch (error) {
|
|
21424
|
-
return await writePrepared({
|
|
21425
|
-
outcome: "failed",
|
|
21426
|
-
errorType: failureLabel(error, signal)
|
|
21427
|
-
});
|
|
21428
|
-
}
|
|
21429
|
-
const outcome = await writePrepared({
|
|
21430
|
-
outcome: "ready",
|
|
21431
|
-
summary
|
|
21432
|
-
});
|
|
21433
|
-
if (outcome === "ready") setSpanAttributes({
|
|
21434
|
-
"app.compaction.summary_chars": summary.length,
|
|
21435
|
-
"app.compaction.ready_ms": Date.now() - request.createdAtMs
|
|
21441
|
+
setSpanAttributes({
|
|
21442
|
+
"app.compaction.outcome": "applied",
|
|
21443
|
+
"app.compaction.summary_chars": prepared.summary.length
|
|
21436
21444
|
});
|
|
21437
|
-
return
|
|
21445
|
+
return {
|
|
21446
|
+
compacted: true,
|
|
21447
|
+
piMessages: messages
|
|
21448
|
+
};
|
|
21438
21449
|
}
|
|
21439
21450
|
// src/chat/agent/exclusive-tools.ts
|
|
21440
21451
|
/** Tools that must be the only tool call in their assistant message. */
|
|
@@ -21899,6 +21910,19 @@ async function executeAgentRunInPrivacyContext(run, conversationPrivacy, runLogC
|
|
|
21899
21910
|
tools: agent.state.tools
|
|
21900
21911
|
} };
|
|
21901
21912
|
};
|
|
21913
|
+
/**
|
|
21914
|
+
* Request a background summary when the model call that just ended was at
|
|
21915
|
+
* or above the mark. It runs after each model call, so a long Turn gets a
|
|
21916
|
+
* summary before it reaches the compaction threshold.
|
|
21917
|
+
*/
|
|
21918
|
+
const requestBackgroundCompactionAfterModelCall = async () => await requestBackgroundCompaction({
|
|
21919
|
+
agent,
|
|
21920
|
+
conversationId,
|
|
21921
|
+
conversationPrivacy,
|
|
21922
|
+
modelId: activeModelId,
|
|
21923
|
+
queue: run.environment?.backgroundCompactionQueue,
|
|
21924
|
+
turnStartedAtMs: replyStartedAtMs
|
|
21925
|
+
});
|
|
21902
21926
|
let assistantMessageDeliveryError;
|
|
21903
21927
|
/** Deliver one completed tool-free visible message before the agent advances. */
|
|
21904
21928
|
const deliverAssistantMessage = async (message) => {
|
|
@@ -21992,8 +22016,12 @@ async function executeAgentRunInPrivacyContext(run, conversationPrivacy, runLogC
|
|
|
21992
22016
|
const stepUpdate = await withSpan("agent.step.prepare", "agent.step.prepare", {}, async () => {
|
|
21993
22017
|
const contextUpdate = await repositoryInstructionsContext.applyUpdate(nextTurn.context);
|
|
21994
22018
|
const pendingMessages = await drainSteeringMessages();
|
|
21995
|
-
if (nextTurn.toolResults.length === 0 && pendingMessages.length === 0)
|
|
22019
|
+
if (nextTurn.toolResults.length === 0 && pendingMessages.length === 0) {
|
|
22020
|
+
await requestBackgroundCompactionAfterModelCall();
|
|
22021
|
+
return contextUpdate;
|
|
22022
|
+
}
|
|
21996
22023
|
const capacityUpdate = await applyActiveContextCompaction(contextUpdate ? currentAgentMessages() : nextTurn.context.messages, hookSignal, pendingMessages, true);
|
|
22024
|
+
if (!capacityUpdate) await requestBackgroundCompactionAfterModelCall();
|
|
21997
22025
|
return capacityUpdate ? {
|
|
21998
22026
|
...contextUpdate,
|
|
21999
22027
|
...capacityUpdate
|
|
@@ -22235,14 +22263,6 @@ async function executeAgentRunInPrivacyContext(run, conversationPrivacy, runLogC
|
|
|
22235
22263
|
unsubscribe();
|
|
22236
22264
|
}
|
|
22237
22265
|
await recordActiveMcpProviders();
|
|
22238
|
-
await requestBackgroundCompaction({
|
|
22239
|
-
agent,
|
|
22240
|
-
conversationId,
|
|
22241
|
-
conversationPrivacy,
|
|
22242
|
-
modelId: activeModelId,
|
|
22243
|
-
queue: run.environment?.backgroundCompactionQueue,
|
|
22244
|
-
turnStartedAtMs: replyStartedAtMs
|
|
22245
|
-
});
|
|
22246
22266
|
return {
|
|
22247
22267
|
status: "completed",
|
|
22248
22268
|
result: buildTurnResult({
|