@sentry/junior 0.280.0 → 0.281.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.
Files changed (67) hide show
  1. package/dist/{adapter-DVN3iwf9.js → adapter-RVQGEa98.js} +1 -1
  2. package/dist/{admin-Q_UI--9W.js → admin-DQpHx6Og.js} +1 -1
  3. package/dist/{agent-runner-_PYLv4Qo.js → agent-runner-B229gXUY.js} +998 -975
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +5 -5
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +39 -33
  8. package/dist/{app-CL2zzzE0.d.ts → app-BQ9RZS43.d.ts} +2 -2
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +42 -34
  11. package/dist/{assistant-reply-DbebsAxi.js → assistant-reply-DQbtwc6j.js} +1 -1
  12. package/dist/{automation-CPqRFjIa.js → automation-sIsmIXH7.js} +1 -1
  13. package/dist/{background-compaction-queue-B9lmh8Ml.js → background-compaction-queue-oegyrxSe.js} +2 -2
  14. package/dist/{briefs-Dej7V0Bz.js → briefs-BwzGWJgR.js} +4 -8
  15. package/dist/{catalog-runtime-DpN0sWQ6.js → catalog-runtime-ClKzLvbN.js} +1 -1
  16. package/dist/cli/chat.js +14 -14
  17. package/dist/cli/check.js +3 -3
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +4 -4
  20. package/dist/cli/snapshot-create.js +4 -4
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +3 -3
  23. package/dist/{client-h2A2ZPzY.js → client-DkG0Tj53.js} +2 -2
  24. package/dist/{config-CusBFORe.js → config-3AZ11aSM.js} +1 -1
  25. package/dist/{connections-C4h6mGha.js → connections-C0ut_6RW.js} +10 -10
  26. package/dist/{conversation-DExTZw8B.js → conversation-DNtcULyX.js} +29 -8
  27. package/dist/{conversation-pending-messages-Dgz6hrJs.js → conversation-pending-messages-LlFnr9-m.js} +10 -2
  28. package/dist/{conversation-privacy-2cm6OpNg.js → conversation-privacy-DAgeBGLN.js} +1 -1
  29. package/dist/{credential-sync-DK06Jgt-.js → credential-sync-Bg8NPuvj.js} +13 -13
  30. package/dist/{db-Dsvk1Tp1.d.ts → db-BCFM0CUX.d.ts} +1 -1
  31. package/dist/{executor-Cmr0J8W3.js → executor-DLKnzP6S.js} +2 -2
  32. package/dist/instrumentation.js +2 -2
  33. package/dist/{logging-CGnh65_X.js → logging-DHzrobea.js} +1 -1
  34. package/dist/{message-RpAnqHPY.js → message-LR8z5jXJ.js} +9 -9
  35. package/dist/nitro.d.ts +1 -1
  36. package/dist/nitro.js +3 -3
  37. package/dist/{oauth-callback-server-BBnhVKuX.js → oauth-callback-server-EWdpj0_y.js} +2 -2
  38. package/dist/{projection-C1MghKyI.js → projection-Bhz1tp0G.js} +60 -27
  39. package/dist/{prompt-BcHg-BMy.js → prompt-DI6KCtwb.js} +5 -26
  40. package/dist/{registry-DR7DjX9H.js → registry-EjhulgQW.js} +1 -1
  41. package/dist/{resolve-0Ful4oDv.js → resolve-Cw6OW4Fj.js} +3 -3
  42. package/dist/{result-Dd9kCuQ-.js → result-BoD0jevy.js} +9 -9
  43. package/dist/{runner-yiY8gUUu.js → runner-D22bsBDS.js} +11 -11
  44. package/dist/{sandbox-egress-signals-BzQVHCMz.js → sandbox-egress-signals-BG5GYacQ.js} +1 -1
  45. package/dist/{schema-C5pEgfHc.js → schema-BN34Jy-U.js} +3 -3
  46. package/dist/{schema-BkMmF552.d.ts → schema-CsqJzkP5.d.ts} +68 -9
  47. package/dist/{service-account-PIMpWZHF.js → service-account-Dd1nnAQZ.js} +3 -3
  48. package/dist/{service-account-Cu7HFLZQ.js → service-account-xo-CeMqI.js} +3 -3
  49. package/dist/{session-stop-CDEMsNtv.js → session-stop-CHSYB2uw.js} +12 -12
  50. package/dist/{skills-B2xIoe0f.js → skills-BGJr6xtW.js} +2 -2
  51. package/dist/{spawn-C0DySQRV.js → spawn-Cl8WS7zi.js} +2 -2
  52. package/dist/{stop-Dj5-nrAo.js → stop-C9lHWpvl.js} +120 -48
  53. package/dist/{store-QzOfDwKA.js → store-C4z8gOgZ.js} +3 -3
  54. package/dist/{store-Dlio-o6u.js → store-DeTnwVJt.js} +4 -4
  55. package/dist/{task-queue-Cp1V_XW3.js → task-queue-BBos68l0.js} +3 -3
  56. package/dist/{task-runner-CQkkUj3o.js → task-runner-BSF9zO-H.js} +6 -6
  57. package/dist/{thread-state-Bn87cfzE.js → thread-state-DGq1o5JX.js} +4 -4
  58. package/dist/{turn-failure-response-CQebxByj.js → turn-failure-response--9bA4uLP.js} +7 -7
  59. package/dist/{turn-lifecycle-CJJsOhXB.js → turn-lifecycle-t5fimxwQ.js} +1 -1
  60. package/dist/{turn-session-routing-bmG330Cf.js → turn-session-routing-RBtUe-3y.js} +9 -9
  61. package/dist/{validation-D1wcf7hp.js → validation-DrR0leBT.js} +1 -1
  62. package/dist/{version-BeHSXUK6.js → version-D_HFt_Dq.js} +1 -1
  63. package/dist/version.js +1 -1
  64. package/dist/{viewer-BZ0Hp5Nb.js → viewer-DWlpSFdj.js} +7 -5
  65. package/dist/{work-BTcCIbWu.js → work-pPoqtRea.js} +10 -10
  66. package/dist/{worker-D3fDK6zc.js → worker-CoVKgJ-O.js} +6 -6
  67. package/package.json +4 -4
@@ -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, Ma as readConversationAccessFromSql, Mi as uploadFilesToConversation, 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, 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 projectConversationEvents, _r as RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS, ai as create, an as trimTrailingAssistantMessages, ao as saveObjectAnnotations, ba as SANDBOX_REPOS_ROOT, bn as getAgentContextInputLimitTokens, bo as getConfigDefaults, br as STOP_WATCHING_TOOL_NAME, c as recordAgentsInstructionsUpdated, ca as resolveSandboxCommandEnvironment, ci as ensureDockerDaemon, cn as TURN_CONTEXT_TAG, cr as requireReviewItemLinks, da as sleep, 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, fr as automationCreatorUserId, g as recordToolExecutionStarted, gn as estimateRequestOverheadTokens, go as piMessageFromHistoryItem, gr as getSlackToolContext, hi as resolveBaseUrl, hn as calculateContextCompactionTargetTokens, ho as historyItemFromPiMessage, 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, lo as defaultTimezone, m as recordMcpProviderConnected, ma as PluginToolDeniedError, mr as resolveAssignees, na as consumeSandboxEgressAuthRequiredSignal, ni as loadSnapshotsForProfile, nn as normalizeToolNameFromResult, oi as hash, on as REQUEST_CONTEXT_SECTION_TAG, oo as createPluginAnnotations, 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, sr as requireReviewItemAssignees, ta as clearSandboxEgressSignals, ti as invalidateReadySnapshot, tn as isToolResultMessage, to as matchSlackAttachments, tr as PLUGIN_REVIEW_ITEM_KEY_PREFIX, ua as SANDBOX_RUNTIME, un as buildDeterministicTurnId, uo as resolveUserTimezone, va as SANDBOX_DATA_ROOT, vn as getAgentBackgroundCompactionMarkTokens, vo as JUNIOR_NATIVE_EVENT_NAMESPACE, 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, xr as cancelSubscriptions, ya as SANDBOX_JUNIOR_ROOT, yi as normalizeSlackReplyMarkdown, yn as getAgentContextCompactionTriggerTokens, yo as conversationNoteEvent, yr as RESOURCE_WATCH_TOOL_SOURCE, z as createPluginAuthOrchestration, zi as getSlackClient, zr as getDashboardConversationLink } from "./projection-C1MghKyI.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-h2A2ZPzY.js";
4
- import { _ as toPiReasoningLevel, g as TURN_REASONING_LEVELS, n as botConfig, v as normalizeSlackEmojiName } from "./config-CusBFORe.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-CGnh65_X.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-2cm6OpNg.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, Ma as readConversationAccessFromSql, Mi as uploadFilesToConversation, 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, 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 piMessageFromHistoryItem, _r as RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS, ai as create, an as trimTrailingAssistantMessages, ba as SANDBOX_REPOS_ROOT, bn as getAgentContextInputLimitTokens, bo as conversationNoteEvent, br as STOP_WATCHING_TOOL_NAME, c as recordAgentsInstructionsUpdated, ca as resolveSandboxCommandEnvironment, ci as ensureDockerDaemon, cn as TURN_CONTEXT_TAG, cr as requireReviewItemLinks, da as sleep, do as resolveUserTimezone, 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, fr as automationCreatorUserId, g as recordToolExecutionStarted, gn as estimateRequestOverheadTokens, go as historyItemFromPiMessage, 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, oi as hash, on as REQUEST_CONTEXT_SECTION_TAG, oo as saveObjectAnnotations, 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 createPluginAnnotations, sr as requireReviewItemAssignees, ta as clearSandboxEgressSignals, ti as invalidateReadySnapshot, tn as isToolResultMessage, to as matchSlackAttachments, tr as PLUGIN_REVIEW_ITEM_KEY_PREFIX, ua as SANDBOX_RUNTIME, un as buildDeterministicTurnId, uo as defaultTimezone, va as SANDBOX_DATA_ROOT, vn as getAgentBackgroundCompactionMarkTokens, vo as projectConversationEvents, 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 getConfigDefaults, xr as cancelSubscriptions, ya as SANDBOX_JUNIOR_ROOT, yi as normalizeSlackReplyMarkdown, yn as getAgentContextCompactionTriggerTokens, yo as JUNIOR_NATIVE_EVENT_NAMESPACE, yr as RESOURCE_WATCH_TOOL_SOURCE, z as createPluginAuthOrchestration, zi as getSlackClient, zr as getDashboardConversationLink } from "./projection-Bhz1tp0G.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-DkG0Tj53.js";
4
+ import { _ as toPiReasoningLevel, g as TURN_REASONING_LEVELS, n as botConfig, v as normalizeSlackEmojiName } from "./config-3AZ11aSM.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-DHzrobea.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-DAgeBGLN.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-BZ0Hp5Nb.js";
9
- import { A as juniorIdentities, D as juniorAttachments, M as juniorDestinations, N as juniorArtifacts, _ as juniorConversationParticipants, d as juniorAutomations, f as juniorStats, h as juniorAgentInvocations, j as juniorUsers, k as juniorConversations, l as juniorAutomationRuns, m as juniorAgentBindings, s as juniorReviewItemSlackCards, y as juniorConversationBriefs } from "./executor-Cmr0J8W3.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-DWlpSFdj.js";
9
+ import { A as juniorIdentities, D as juniorAttachments, M as juniorDestinations, N as juniorArtifacts, _ as juniorConversationParticipants, d as juniorAutomations, f as juniorStats, h as juniorAgentInvocations, j as juniorUsers, k as juniorConversations, l as juniorAutomationRuns, m as juniorAgentBindings, s as juniorReviewItemSlackCards, y as juniorConversationBriefs } from "./executor-DLKnzP6S.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-DR7DjX9H.js";
13
- import { n as pluginCatalogRuntime } from "./catalog-runtime-DpN0sWQ6.js";
14
- import { a as parseSkillInvocation, i as parseSkillFile, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-B2xIoe0f.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-EjhulgQW.js";
13
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-ClKzLvbN.js";
14
+ import { a as parseSkillInvocation, i as parseSkillFile, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-BGJr6xtW.js";
15
15
  import { a as withLock, i as fenceLock } from "./locks-D-0h111u.js";
16
- import { r as getStateAdapter } from "./adapter-DVN3iwf9.js";
16
+ import { r as getStateAdapter } from "./adapter-RVQGEa98.js";
17
17
  import { i as isValidTimeZone, r as getZonedDateTimeParts, t as getFirstRunAtMs } from "./cadence-R7Em4RjE.js";
18
- import { B as briefLinkSchema, H as conversationBriefSchema, N as removedCardSchema, V as briefOutcomeStatusSchema } from "./conversation-DExTZw8B.js";
19
- import { r as EVENT_AUTHOR_ID } from "./prompt-BcHg-BMy.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-Dlio-o6u.js";
21
- import { i as NO_REPLY_MARKER, n as getAssistantReplyText, o as isNoReplyMarker, r as sanitizeAssistantText, t as decideReply } from "./assistant-reply-DbebsAxi.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-CDEMsNtv.js";
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-DeTnwVJt.js";
21
+ import { i as NO_REPLY_MARKER, n as getAssistantReplyText, o as isNoReplyMarker, r as sanitizeAssistantText, t as decideReply } from "./assistant-reply-DQbtwc6j.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-CHSYB2uw.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-0Ful4oDv.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-B9lmh8Ml.js";
26
- import { D as stopConversationWork, n as appendAndEnqueueExclusiveInboundMessage, r as appendAndEnqueueInboundMessage } from "./store-QzOfDwKA.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-bmG330Cf.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-PIMpWZHF.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-CPqRFjIa.js";
24
+ import { a as setSnapshotSpanAttributes, i as postinstall, n as resolve$1, r as dependencies, s as getSandboxResources } from "./resolve-Cw6OW4Fj.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-oegyrxSe.js";
26
+ import { D as stopConversationWork, n as appendAndEnqueueExclusiveInboundMessage, r as appendAndEnqueueInboundMessage } from "./store-C4z8gOgZ.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-RBtUe-3y.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-Dd1nnAQZ.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";
@@ -7315,7 +7315,7 @@ async function searchTopLevelAgents(args) {
7315
7315
  status: juniorConversations.executionStatus,
7316
7316
  title: juniorConversations.title
7317
7317
  }).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 ? conversationBriefSchema.parse(row.briefContent) : void 0;
7318
+ const brief = row.briefContent ? parseStoredBrief(row.briefContent) : void 0;
7319
7319
  return {
7320
7320
  archived: row.archivedAt !== null,
7321
7321
  conversationId: row.conversationId,
@@ -15469,7 +15469,7 @@ async function searchConversationBriefs(db, args) {
15469
15469
  updatedAt: briefs.createdAt,
15470
15470
  version: briefs.version
15471
15471
  }).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 = conversationBriefSchema.parse(row.content);
15472
+ const content = parseStoredBrief(row.content);
15473
15473
  return {
15474
15474
  conversationId: row.conversationId,
15475
15475
  excerpt: row.excerpt,
@@ -20345,69 +20345,120 @@ function createResumeState(args) {
20345
20345
  }
20346
20346
  };
20347
20347
  }
20348
- // src/chat/services/plan-continuation.ts
20349
- const OPEN_PLAN_TAG = "open-plan";
20350
- function openItems(input) {
20351
- const plan = input && typeof input === "object" ? input.plan : void 0;
20352
- if (!Array.isArray(plan)) return [];
20353
- return plan.flatMap((value) => {
20354
- const item = value;
20355
- if (typeof item?.step !== "string" || item.status !== "pending" && item.status !== "in_progress") return [];
20356
- return [{
20357
- step: item.step,
20358
- status: item.status
20359
- }];
20360
- });
20348
+ // src/chat/agent/context-summary.ts
20349
+ /** Prompt name of the summary request on its `gen_ai.chat` span. */
20350
+ const CONTEXT_COMPACTION_PROMPT_NAME = "junior.context_compaction";
20351
+ const SUMMARY_MAX_TOKENS = 8e3;
20352
+ 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.
20353
+
20354
+ 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.
20355
+
20356
+ ## Goal
20357
+ ## Constraints & preferences
20358
+ ## Progress
20359
+ ### Done
20360
+ ### In progress
20361
+ ### Blocked
20362
+ ## Key decisions
20363
+ ## Open asks
20364
+ User requests that are not complete yet, quoted in the user's exact words.
20365
+ ## References
20366
+ Exact file paths, IDs, URLs, commands, and error text that the work needs. At most 20 items.
20367
+ ## Next steps
20368
+
20369
+ Rules:
20370
+ - Keep the summary under 1,000 words.
20371
+ - Leave out the system prompt, AGENTS.md instructions, tool descriptions, and environment details. They are added again.
20372
+ - Do not mention this request or the summary itself.
20373
+ - 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.`;
20374
+ const SUMMARY_NUDGE = "Do not call tools. Keep the summary short. Return only the summary inside <summary></summary> tags.";
20375
+ /** Raised when the model returns no usable summary after one nudge. */
20376
+ var ContextSummaryError = class extends Error {
20377
+ failure;
20378
+ constructor(failure) {
20379
+ super(`Context summary failed: ${failure}`);
20380
+ this.failure = failure;
20381
+ this.name = "ContextSummaryError";
20382
+ }
20383
+ };
20384
+ /**
20385
+ * Build the model request that the agent loop sends for these messages.
20386
+ *
20387
+ * This repeats the steps of pi-agent-core before each model call
20388
+ * (`streamAssistantResponse` and `createLoopConfig`, which Pi does not
20389
+ * export): transform and convert the messages, then read the model,
20390
+ * reasoning, tools, and request options from the agent. A unit test compares
20391
+ * this request with the one that a real Pi `Agent` loop passes to `streamFn`,
20392
+ * so it fails when Pi changes these steps.
20393
+ */
20394
+ async function buildAgentModelRequest(agent, messages, signal) {
20395
+ const { model, systemPrompt, thinkingLevel, tools } = agent.state;
20396
+ const transformed = agent.transformContext ? await agent.transformContext(messages, signal) : messages;
20397
+ return {
20398
+ model,
20399
+ context: {
20400
+ systemPrompt,
20401
+ messages: await agent.convertToLlm(transformed),
20402
+ tools
20403
+ },
20404
+ options: {
20405
+ reasoning: thinkingLevel === "off" ? void 0 : thinkingLevel,
20406
+ sessionId: agent.sessionId,
20407
+ onPayload: agent.onPayload,
20408
+ onResponse: agent.onResponse,
20409
+ transport: agent.transport,
20410
+ thinkingBudgets: agent.thinkingBudgets,
20411
+ maxRetryDelayMs: agent.maxRetryDelayMs,
20412
+ apiKey: await agent.getApiKey?.(model.provider) || void 0,
20413
+ signal
20414
+ }
20415
+ };
20361
20416
  }
20362
- function messageText$1(message) {
20363
- const content = message.content;
20364
- if (!Array.isArray(content)) return typeof content === "string" ? content : "";
20365
- return content.flatMap((part) => {
20366
- const text = part?.text;
20367
- return typeof text === "string" ? [text] : [];
20368
- }).join("\n");
20417
+ function userText(text) {
20418
+ return {
20419
+ role: "user",
20420
+ content: [{
20421
+ type: "text",
20422
+ text
20423
+ }],
20424
+ timestamp: Date.now()
20425
+ };
20369
20426
  }
20370
- function retainedOpenItems(message) {
20371
- const text = messageText$1(message);
20372
- if (!isCompactionSummaryText(text)) return;
20373
- const continuation = unwrapCurrentInstruction(text) ?? text;
20374
- const open = `<${OPEN_PLAN_TAG}>\n`;
20375
- const close = `\n</${OPEN_PLAN_TAG}>`;
20376
- const closeIndex = continuation.lastIndexOf(close);
20377
- const openIndex = continuation.lastIndexOf(open, closeIndex);
20378
- if (openIndex < 0 || closeIndex < 0) return;
20379
- const payload = continuation.slice(openIndex + open.length, closeIndex);
20380
- try {
20381
- return openItems({ plan: JSON.parse(payload) });
20382
- } catch {
20383
- return;
20384
- }
20427
+ async function complete(request, streamFn, appended) {
20428
+ const message = await (await streamFn(request.model, {
20429
+ ...request.context,
20430
+ messages: [...request.context.messages, ...appended]
20431
+ }, {
20432
+ ...request.options,
20433
+ maxTokens: SUMMARY_MAX_TOKENS
20434
+ })).result();
20435
+ if (message.stopReason === "error" || message.stopReason === "aborted") throw createProviderError(message.errorMessage ?? message.stopReason, { modelId: request.model.id });
20436
+ return message;
20385
20437
  }
20386
- /** Read open items from the latest successful plan state. */
20387
- function latestOpenPlanItems(messages) {
20388
- const successfulCalls = /* @__PURE__ */ new Set();
20389
- for (let messageIndex = messages.length - 1; messageIndex >= 0; messageIndex -= 1) {
20390
- const message = messages[messageIndex];
20391
- if (message.role === "toolResult" && message.toolName === "updatePlan" && typeof message.toolCallId === "string" && message.isError !== true) {
20392
- successfulCalls.add(message.toolCallId);
20393
- continue;
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 [];
20438
+ /** Read the summary, or name why the output is not a usable summary. */
20439
+ function readSummary(message) {
20440
+ if (message.content.some((part) => part.type === "toolCall")) return { failure: "tool_call" };
20441
+ if (message.stopReason === "length") return { failure: "max_tokens" };
20442
+ const text = message.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("").trim();
20443
+ if (!text) return { failure: "empty" };
20444
+ const summary = /<summary>([\s\S]*?)<\/summary>/.exec(text)?.[1]?.trim();
20445
+ return summary ? { summary } : { failure: "missing_summary" };
20406
20446
  }
20407
- /** Append exact open plan state to continuation text. */
20408
- function appendOpenPlan(continuation, messages) {
20409
- const plan = latestOpenPlanItems(messages);
20410
- return plan.length === 0 ? continuation : `${continuation}\n\n<${OPEN_PLAN_TAG}>\n${JSON.stringify(plan)}\n</${OPEN_PLAN_TAG}>`;
20447
+ /**
20448
+ * Ask the agent model for a summary of the request messages.
20449
+ *
20450
+ * A tool call, a stop at the output limit, empty output, or output without
20451
+ * `<summary>` tags gets one nudge. A second failure throws
20452
+ * `ContextSummaryError`, so the caller keeps the full history.
20453
+ */
20454
+ async function requestContextSummary(request, streamFn) {
20455
+ const instruction = userText(SUMMARY_INSTRUCTION);
20456
+ const first = readSummary(await complete(request, streamFn, [instruction]));
20457
+ if ("summary" in first) return first.summary;
20458
+ logWarn("context_compaction.summary.nudged", { "app.compaction.summary_failure": first.failure });
20459
+ const second = readSummary(await complete(request, streamFn, [instruction, userText(SUMMARY_NUDGE)]));
20460
+ if ("summary" in second) return second.summary;
20461
+ throw new ContextSummaryError(second.failure);
20411
20462
  }
20412
20463
  // src/chat/services/context-compaction-telemetry.ts
20413
20464
  /**
@@ -20441,1000 +20492,963 @@ async function measureTurnCompactionWait(setTurnAttributes, callback) {
20441
20492
  if (wait.ms > 0) setTurnAttributes({ "app.turn.compaction_wait_ms": Math.round(wait.ms) });
20442
20493
  }
20443
20494
  }
20444
- // src/chat/services/context-compaction.ts
20495
+ // src/chat/services/background-compaction.ts
20445
20496
  /**
20446
- * Context compaction.
20497
+ * Background compaction: prepare a summary before the history is full.
20447
20498
  *
20448
- * Bounds Pi history for long conversations and commits a history
20449
- * replacement. Capacity compaction gets its summary from the caller, which
20450
- * asks the agent model with the cached request prefix. Mid-turn replacements
20451
- * keep the authored instruction before the summary. Turn-start replacements keep recent user
20452
- * messages, the summary, then the new instruction. Checkpoints can append
20453
- * fresh runtime context; the next replacement removes it again.
20499
+ * After each model request at or above the mark, also in the middle of a
20500
+ * Turn, the Turn appends `compaction_requested` and sends a job. The job
20501
+ * asks the agent model for a summary of the history up to the marked event
20502
+ * and appends `compaction_prepared`. Turns keep the full history until a later
20503
+ * change swaps the summary in. Blocking compaction stays the fallback.
20504
+ *
20505
+ * The summary request repeats the system prompt and tools of the last agent
20506
+ * request, so the provider can read its cached prompt prefix. The job runs in
20507
+ * another request, so the Turn stores them in the State adapter.
20454
20508
  */
20455
- const RETAINED_USER_MESSAGE_TOKENS = 2e4;
20456
- /** Raised when Junior cannot compact history below the active model's hard ceiling. */
20457
- var ContextInputLimitExceededError = class extends Error {
20458
- estimatedTokens;
20459
- inputLimitTokens;
20460
- constructor(estimatedTokens, inputLimitTokens) {
20461
- super(`Agent context is ${estimatedTokens} estimated input tokens, above the ${inputLimitTokens} token limit`);
20462
- this.estimatedTokens = estimatedTokens;
20463
- this.inputLimitTokens = inputLimitTokens;
20464
- this.name = "ContextInputLimitExceededError";
20465
- }
20466
- };
20467
- function textPart(value) {
20468
- if (value && typeof value === "object" && value.type === "text" && typeof value.text === "string") return value.text;
20509
+ /**
20510
+ * Failed or discarded attempts for one History version before background
20511
+ * tries stop.
20512
+ */
20513
+ const MAX_FAILED_ATTEMPTS = 2;
20514
+ /**
20515
+ * A request without a prepared result after this long counts as a failed
20516
+ * attempt, so a later Turn can request again. This covers a lost job.
20517
+ */
20518
+ const REQUEST_TIMEOUT_MS = 6e5;
20519
+ /** The queue drops a message after this long, so the snapshot can go too. */
20520
+ const SNAPSHOT_TTL_MS = QUEUE_SIGNATURE_MAX_AGE_MS;
20521
+ function snapshotKey(message) {
20522
+ return `${backgroundCompactionId(message)}:snapshot`;
20469
20523
  }
20470
- /** Render Pi message text for retained user-message selection. */
20471
- function messageText(message) {
20472
- const content = message.content;
20473
- const unwrapTask = message.role === "user";
20474
- const displayText = (text) => unwrapTask ? unwrapCurrentInstruction(text) ?? text : text;
20475
- if (!Array.isArray(content)) return typeof content === "string" ? displayText(content) : "";
20476
- return content.map(textPart).filter((text) => Boolean(text)).map(displayText).join("\n").trim();
20524
+ /** Provider-reported input of the last model request, cache included. */
20525
+ function lastRequestInputSize(messages) {
20526
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
20527
+ const message = messages[index];
20528
+ if (message.role === "assistant") {
20529
+ const { input, cacheRead, cacheWrite } = message.usage;
20530
+ return input + cacheRead + cacheWrite;
20531
+ }
20532
+ }
20477
20533
  }
20478
- function sanitizeText(text) {
20479
- 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();
20534
+ /**
20535
+ * Return whether a Turn may request a background summary for this History
20536
+ * version. It may not while a request is pending, while a ready summary is
20537
+ * still unused, or after the attempt limit.
20538
+ *
20539
+ * A Turn swaps a ready summary in before its first model request. A swap
20540
+ * makes a new History version. So a ready summary of this version that was
20541
+ * prepared before the Turn started was discarded, for example because the
20542
+ * history after its mark is too large now. It counts as a failed attempt, so
20543
+ * a new request can replace it.
20544
+ */
20545
+ function mayRequest(events, historyVersion, nowMs, turnStartedAtMs) {
20546
+ const outcomes = /* @__PURE__ */ new Map();
20547
+ for (const event of events) if (event.data.type === "compaction_prepared" && event.data.historyVersion === historyVersion) outcomes.set(event.data.markSeq, {
20548
+ outcome: event.data.outcome,
20549
+ createdAtMs: event.createdAtMs
20550
+ });
20551
+ let failed = 0;
20552
+ for (const event of events) {
20553
+ if (event.data.type !== "compaction_requested" || event.data.historyVersion !== historyVersion) continue;
20554
+ const prepared = outcomes.get(event.data.markSeq);
20555
+ if (prepared?.outcome === "ready" && prepared.createdAtMs >= turnStartedAtMs) return false;
20556
+ if (prepared || nowMs - event.createdAtMs >= REQUEST_TIMEOUT_MS) failed += 1;
20557
+ else return false;
20558
+ }
20559
+ return failed < MAX_FAILED_ATTEMPTS;
20480
20560
  }
20481
- function truncateToTokenBudget(text, maxTokens) {
20482
- const maxChars = Math.max(0, maxTokens * 4);
20483
- if (text.length <= maxChars) return text;
20484
- return `${text.slice(0, Math.max(0, maxChars - 3)).trimEnd()}...`;
20561
+ /**
20562
+ * Find the newest background compaction fact of the current History version.
20563
+ * Facts of earlier versions belong to history that a replacement already
20564
+ * removed.
20565
+ */
20566
+ async function loadLatestBackgroundCompaction(conversationId) {
20567
+ const store = getConversationEventStore();
20568
+ const [historyVersion, page] = await Promise.all([store.loadCurrentHistoryVersion(conversationId), store.query(conversationId, {
20569
+ limit: 1,
20570
+ types: ["compaction_requested", "compaction_prepared"]
20571
+ })]);
20572
+ const event = page.events.at(-1);
20573
+ return event && event.historyVersion === historyVersion ? {
20574
+ event,
20575
+ historyVersion
20576
+ } : void 0;
20485
20577
  }
20486
- function isCompactionSummary(text) {
20487
- return isCompactionSummaryText(text);
20578
+ /**
20579
+ * Return whether the newest fact is a pending request or a summary that
20580
+ * became ready in this execution slice. Then `mayRequest` is false too, so a
20581
+ * Turn can skip the full history load. Only one request is pending at a time,
20582
+ * so the newest fact decides it.
20583
+ */
20584
+ function waitsForUse(event, nowMs, turnStartedAtMs) {
20585
+ if (event.data.type === "compaction_requested") return nowMs - event.createdAtMs < REQUEST_TIMEOUT_MS;
20586
+ return event.data.type === "compaction_prepared" && event.data.outcome === "ready" && event.createdAtMs >= turnStartedAtMs;
20488
20587
  }
20489
- function isPayloadHeavy(text) {
20490
- return /<data_base64>[\s\S]*?<\/data_base64>|data:image\/[a-z0-9.+-]+;base64,/i.test(text);
20588
+ /**
20589
+ * Request a background summary when the model request that just ended was at
20590
+ * or above the mark.
20591
+ *
20592
+ * The agent runs it after each model request, so a long Turn gets a summary
20593
+ * before the compaction threshold. `turnStartedAtMs` is when this execution
20594
+ * slice started, before its first model request. Without a queue or below the
20595
+ * mark, it does nothing. A failure here leaves blocking compaction as the
20596
+ * fallback, so it is logged and does not fail the Turn. When the send fails
20597
+ * after the request is written, the request times out and counts as a
20598
+ * failed attempt.
20599
+ */
20600
+ async function requestBackgroundCompaction(args) {
20601
+ if (!args.queue) return;
20602
+ const inputSize = lastRequestInputSize(args.agent.state.messages);
20603
+ if (inputSize === void 0 || inputSize < getAgentBackgroundCompactionMarkTokens(args.modelId)) return;
20604
+ try {
20605
+ await requestAboveMark({
20606
+ ...args,
20607
+ inputSize,
20608
+ queue: args.queue
20609
+ });
20610
+ } catch (error) {
20611
+ logWarn("context_compaction.background.request_failed", { "error.type": error instanceof Error ? error.name : typeof error });
20612
+ }
20491
20613
  }
20492
- /** Build a text-only user message for a replacement history. */
20493
- function userMessage(text) {
20494
- return {
20495
- role: "user",
20496
- content: [{
20497
- type: "text",
20498
- text
20499
- }],
20500
- timestamp: Date.now()
20614
+ async function requestAboveMark(args) {
20615
+ const nowMs = Date.now();
20616
+ const latest = await loadLatestBackgroundCompaction(args.conversationId);
20617
+ if (latest && waitsForUse(latest.event, nowMs, args.turnStartedAtMs)) return;
20618
+ const eventStore = getConversationEventStore();
20619
+ const events = await eventStore.loadCurrentHistory(args.conversationId);
20620
+ const historyVersion = events[0]?.historyVersion;
20621
+ if (historyVersion === void 0 || !mayRequest(events, historyVersion, nowMs, args.turnStartedAtMs)) return;
20622
+ const projection = projectConversationEvents(events);
20623
+ const markSeq = Math.max(projection.seqs.at(-1) ?? -1, projection.replacementSeq ?? -1);
20624
+ if (markSeq < 0) return;
20625
+ const message = {
20626
+ conversationId: args.conversationId,
20627
+ historyVersion,
20628
+ markSeq
20501
20629
  };
20630
+ const { systemPrompt, thinkingLevel, tools } = args.agent.state;
20631
+ const snapshot = {
20632
+ conversationPrivacy: args.conversationPrivacy ?? "private",
20633
+ inputSize: args.inputSize,
20634
+ modelId: args.modelId,
20635
+ systemPrompt,
20636
+ thinkingLevel,
20637
+ tools: tools.map((tool) => ({
20638
+ name: tool.name,
20639
+ label: tool.label,
20640
+ description: tool.description,
20641
+ parameters: tool.parameters,
20642
+ ...tool.constrainedSampling === void 0 ? void 0 : { constrainedSampling: tool.constrainedSampling }
20643
+ }))
20644
+ };
20645
+ await getStateAdapter().set(snapshotKey(message), JSON.parse(JSON.stringify(snapshot)), SNAPSHOT_TTL_MS);
20646
+ if ((await eventStore.append(args.conversationId, [{
20647
+ idempotencyKey: `${backgroundCompactionId(message)}:requested`,
20648
+ createdAtMs: nowMs,
20649
+ data: {
20650
+ type: "compaction_requested",
20651
+ markSeq,
20652
+ historyVersion,
20653
+ modelId: args.modelId
20654
+ }
20655
+ }], { activity: "preserve" })).length === 0) return;
20656
+ await args.queue.send(message);
20657
+ logInfo("context_compaction.background.requested", {
20658
+ "app.compaction.mark_seq": markSeq,
20659
+ "app.compaction.history_version": historyVersion,
20660
+ "app.compaction.input.size": args.inputSize
20661
+ });
20502
20662
  }
20503
- function userMessageContent(message) {
20504
- const content = message.content;
20505
- return Array.isArray(content) ? content : [];
20506
- }
20507
- function hasTurnBootstrap(message) {
20508
- return userMessageContent(message).some((part) => textPart(part)?.startsWith(`<${TURN_CONTEXT_TAG}>`) === true);
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);
20663
+ /** A fixed label for a failed summary. Never raw exception text. */
20664
+ function failureLabel(error, signal) {
20665
+ if (signal.aborted) return "timeout";
20666
+ if (error instanceof ContextSummaryError) return error.failure;
20667
+ const providerError = findProviderError(error);
20668
+ return providerError ? `provider_${providerError.kind}` : "summary_error";
20516
20669
  }
20517
- /** Find the latest session context and keep only its session sections. */
20518
- function latestSessionContext(messages) {
20519
- for (let index = messages.length - 1; index >= 0; index -= 1) {
20520
- const message = messages[index];
20521
- const text = userMessageContent(message).map(textPart).find(isSessionTurnContext);
20522
- if (text) return {
20523
- ...message,
20524
- content: [{
20525
- type: "text",
20526
- text: withoutRequestContext(text)
20527
- }]
20528
- };
20529
- }
20670
+ /**
20671
+ * Run one background compaction job.
20672
+ *
20673
+ * It writes `compaction_prepared` once for the request, with a summary or a
20674
+ * fixed failure label. It writes nothing when the request is no longer in
20675
+ * the current History version, because no Turn could use the summary.
20676
+ * `streamFn` replaces the model stream, for tests.
20677
+ */
20678
+ async function processBackgroundCompaction(message, options = {}) {
20679
+ const startedAtMs = Date.now();
20680
+ await withLogContext({ conversationId: message.conversationId }, () => withCompactionSpan("background", async () => {
20681
+ setSpanAttributes({
20682
+ "app.compaction.mark_seq": message.markSeq,
20683
+ "app.compaction.history_version": message.historyVersion,
20684
+ ...options.enqueuedAtMs === void 0 ? void 0 : { "app.compaction.queue_wait_ms": Math.max(0, startedAtMs - options.enqueuedAtMs) }
20685
+ });
20686
+ const outcome = await prepareSummary(message, options.streamFn);
20687
+ setSpanAttributes({ "app.compaction.outcome": outcome });
20688
+ }));
20530
20689
  }
20531
- function effectiveRuntimeContext(messages) {
20532
- let latestBootstrapIndex = -1;
20533
- for (let index = messages.length - 1; index >= 0; index -= 1) if (hasTurnBootstrap(messages[index])) {
20534
- latestBootstrapIndex = index;
20535
- break;
20690
+ async function prepareSummary(message, streamFn) {
20691
+ const eventStore = getConversationEventStore();
20692
+ const state = getStateAdapter();
20693
+ const events = await eventStore.loadCurrentHistory(message.conversationId);
20694
+ const isThisRequest = (event) => (event.data.type === "compaction_requested" || event.data.type === "compaction_prepared") && event.data.historyVersion === message.historyVersion && event.data.markSeq === message.markSeq;
20695
+ const request = events.find((event) => isThisRequest(event) && event.data.type === "compaction_requested");
20696
+ if (request?.data.type !== "compaction_requested") {
20697
+ await state.delete(snapshotKey(message));
20698
+ return "stale";
20536
20699
  }
20537
- const effectiveMessages = latestBootstrapIndex < 0 ? messages : messages.slice(latestBootstrapIndex);
20538
- return runtimeContextContent(effectiveMessages, effectiveMessages);
20539
- }
20540
- function runtimeContextContent(messages, agentsMessages) {
20541
- const allContent = messages.flatMap(userMessageContent);
20542
- const firstAgentsIndex = allContent.findIndex((part) => textPart(part)?.startsWith("# AGENTS.md instructions") === true);
20543
- const content = allContent.filter((part) => textPart(part)?.startsWith("# AGENTS.md instructions") !== true);
20544
- const visibleAgents = findVisibleAgentsInstructions(agentsMessages);
20545
- if (visibleAgents?.active === true) {
20546
- const insertionIndex = firstAgentsIndex < 0 ? content.length : Math.min(firstAgentsIndex, content.length);
20547
- content.splice(insertionIndex, 0, {
20548
- type: "text",
20549
- text: renderAgentsInstructions({
20550
- directory: visibleAgents.directory,
20551
- text: visibleAgents.text
20552
- })
20700
+ const requested = request.data;
20701
+ if (events.some((event) => isThisRequest(event) && event.data.type === "compaction_prepared")) return "duplicate";
20702
+ const writePrepared = async (result) => {
20703
+ if (await eventStore.loadCurrentHistoryVersion(message.conversationId) !== message.historyVersion) {
20704
+ await state.delete(snapshotKey(message));
20705
+ return "stale";
20706
+ }
20707
+ await eventStore.append(message.conversationId, [{
20708
+ idempotencyKey: `${backgroundCompactionId(message)}:prepared`,
20709
+ createdAtMs: Date.now(),
20710
+ data: {
20711
+ type: "compaction_prepared",
20712
+ markSeq: message.markSeq,
20713
+ historyVersion: message.historyVersion,
20714
+ modelId: requested.modelId,
20715
+ ...result
20716
+ }
20717
+ }], { activity: "preserve" });
20718
+ await state.delete(snapshotKey(message));
20719
+ if (result.outcome === "failed") setSpanAttributes({ "error.type": result.errorType });
20720
+ return result.outcome;
20721
+ };
20722
+ const remainingMs = request.createdAtMs + REQUEST_TIMEOUT_MS - Date.now();
20723
+ if (remainingMs <= 0) return await writePrepared({
20724
+ outcome: "failed",
20725
+ errorType: "timeout"
20726
+ });
20727
+ const snapshot = await state.get(snapshotKey(message));
20728
+ if (!snapshot) return await writePrepared({
20729
+ outcome: "failed",
20730
+ errorType: "snapshot_missing"
20731
+ });
20732
+ setSpanAttributes({ "app.compaction.input.size": snapshot.inputSize });
20733
+ const projection = projectConversationEvents(events, { maxSeq: message.markSeq });
20734
+ const signal = AbortSignal.timeout(remainingMs);
20735
+ let summary;
20736
+ try {
20737
+ summary = await runWithConversationPrivacy(snapshot.conversationPrivacy, async () => {
20738
+ const summaryStreamFn = createTracedStreamFn({
20739
+ conversationPrivacy: snapshot.conversationPrivacy,
20740
+ promptName: CONTEXT_COMPACTION_PROMPT_NAME,
20741
+ ...streamFn ? { base: streamFn } : void 0
20742
+ });
20743
+ return await requestContextSummary(await buildAgentModelRequest(new Agent({
20744
+ getApiKey: getGatewayApiKey,
20745
+ sessionId: message.conversationId,
20746
+ streamFn: summaryStreamFn,
20747
+ initialState: {
20748
+ systemPrompt: snapshot.systemPrompt,
20749
+ model: resolveGatewayModel(snapshot.modelId),
20750
+ thinkingLevel: snapshot.thinkingLevel,
20751
+ tools: snapshot.tools.map((tool) => ({
20752
+ ...tool,
20753
+ execute: async () => {
20754
+ throw new Error("Background compaction does not run tools");
20755
+ }
20756
+ }))
20757
+ }
20758
+ }), projection.messages, signal), summaryStreamFn);
20759
+ });
20760
+ } catch (error) {
20761
+ return await writePrepared({
20762
+ outcome: "failed",
20763
+ errorType: failureLabel(error, signal)
20553
20764
  });
20554
20765
  }
20555
- const latestTimestamp = messages.at(-1)?.timestamp;
20556
- return {
20557
- content,
20558
- timestamp: typeof latestTimestamp === "number" ? latestTimestamp : Date.now()
20559
- };
20560
- }
20561
- function toRuntimeContextMessage(runtimeContext, timestamp) {
20562
- if (runtimeContext.content.length === 0) return;
20563
- return {
20564
- role: "user",
20565
- content: runtimeContext.content,
20566
- timestamp: timestamp ?? runtimeContext.timestamp
20567
- };
20766
+ const outcome = await writePrepared({
20767
+ outcome: "ready",
20768
+ summary
20769
+ });
20770
+ if (outcome === "ready") setSpanAttributes({
20771
+ "app.compaction.summary_chars": summary.length,
20772
+ "app.compaction.ready_ms": Date.now() - request.createdAtMs
20773
+ });
20774
+ return outcome;
20568
20775
  }
20569
- function runtimeContextMessage(messages, timestamp) {
20570
- return toRuntimeContextMessage(effectiveRuntimeContext(messages), timestamp);
20776
+ // src/chat/services/plan-continuation.ts
20777
+ const OPEN_PLAN_TAG = "open-plan";
20778
+ function openItems(input) {
20779
+ const plan = input && typeof input === "object" ? input.plan : void 0;
20780
+ if (!Array.isArray(plan)) return [];
20781
+ return plan.flatMap((value) => {
20782
+ const item = value;
20783
+ if (typeof item?.step !== "string" || item.status !== "pending" && item.status !== "in_progress") return [];
20784
+ return [{
20785
+ step: item.step,
20786
+ status: item.status
20787
+ }];
20788
+ });
20571
20789
  }
20572
- /**
20573
- * Build the runtime context that the current Turn can use after an in-turn
20574
- * replacement.
20575
- *
20576
- * Request context, such as plugin context and disabled tools, is true only for
20577
- * the Turn that received it. From earlier Turns, keep only the latest session
20578
- * context and AGENTS.md instructions.
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);
20790
+ function messageText$1(message) {
20791
+ const content = message.content;
20792
+ if (!Array.isArray(content)) return typeof content === "string" ? content : "";
20793
+ return content.flatMap((part) => {
20794
+ const text = part?.text;
20795
+ return typeof text === "string" ? [text] : [];
20796
+ }).join("\n");
20586
20797
  }
20587
- /**
20588
- * Build the runtime context of summarized history that the kept history
20589
- * does not carry: the latest session context and the AGENTS.md
20590
- * instructions. Request context of earlier Turns is left out.
20591
- */
20592
- function summarizedRuntimeContextMessage(summarized, kept) {
20593
- const earlierContext = retainRuntimeTurnContext(summarized);
20594
- const sessionContext = retainRuntimeTurnContext(kept).some((message) => userMessageContent(message).map(textPart).some(isSessionTurnContext)) ? void 0 : latestSessionContext(earlierContext);
20595
- return toRuntimeContextMessage(runtimeContextContent(sessionContext ? [sessionContext] : [], findVisibleAgentsInstructions(kept) ? [] : earlierContext));
20798
+ function retainedOpenItems(message) {
20799
+ const text = messageText$1(message);
20800
+ if (!isCompactionSummaryText(text)) return;
20801
+ const continuation = unwrapCurrentInstruction(text) ?? text;
20802
+ const open = `<${OPEN_PLAN_TAG}>\n`;
20803
+ const close = `\n</${OPEN_PLAN_TAG}>`;
20804
+ const closeIndex = continuation.lastIndexOf(close);
20805
+ const openIndex = continuation.lastIndexOf(open, closeIndex);
20806
+ if (openIndex < 0 || closeIndex < 0) return;
20807
+ const payload = continuation.slice(openIndex + open.length, closeIndex);
20808
+ try {
20809
+ return openItems({ plan: JSON.parse(payload) });
20810
+ } catch {
20811
+ return;
20812
+ }
20596
20813
  }
20597
- /**
20598
- * Build retained user messages for a compacted Pi replacement history. Each
20599
- * entry keeps the index of its source message.
20600
- */
20601
- function selectRetainedUserMessageEntries(messages, maxTokens = RETAINED_USER_MESSAGE_TOKENS) {
20602
- const selected = [];
20603
- let remaining = maxTokens;
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;
20814
+ /** Read open items from the latest successful plan state. */
20815
+ function latestOpenPlanItems(messages) {
20816
+ const successfulCalls = /* @__PURE__ */ new Set();
20817
+ for (let messageIndex = messages.length - 1; messageIndex >= 0; messageIndex -= 1) {
20818
+ const message = messages[messageIndex];
20819
+ if (message.role === "toolResult" && message.toolName === "updatePlan" && typeof message.toolCallId === "string" && message.isError !== true) {
20820
+ successfulCalls.add(message.toolCallId);
20617
20821
  continue;
20618
20822
  }
20619
- const truncated = truncateToTokenBudget(text, remaining);
20620
- if (truncated) selected.push({
20621
- message: userMessage(truncated),
20622
- sourceIndex
20623
- });
20624
- break;
20823
+ if (message.role === "user") {
20824
+ const retained = retainedOpenItems(messages[messageIndex]);
20825
+ if (retained) return retained;
20826
+ }
20827
+ if (message.role !== "assistant" || !Array.isArray(message.content)) continue;
20828
+ for (let partIndex = message.content.length - 1; partIndex >= 0; partIndex -= 1) {
20829
+ const call = message.content[partIndex];
20830
+ if (call?.type === "toolCall" && call.name === "updatePlan" && typeof call.id === "string" && successfulCalls.has(call.id)) return openItems(call.arguments);
20831
+ }
20625
20832
  }
20626
- return selected.reverse();
20833
+ return [];
20627
20834
  }
20628
- /** Match a message across a durable commit, which can reorder JSON keys. */
20629
- function retainedMessageKey(message) {
20630
- const { role, timestamp } = message;
20631
- return `${String(role)}:${String(timestamp)}:${messageText(message)}`;
20835
+ /** Append exact open plan state to continuation text. */
20836
+ function appendOpenPlan(continuation, messages) {
20837
+ const plan = latestOpenPlanItems(messages);
20838
+ return plan.length === 0 ? continuation : `${continuation}\n\n<${OPEN_PLAN_TAG}>\n${JSON.stringify(plan)}\n</${OPEN_PLAN_TAG}>`;
20632
20839
  }
20840
+ // src/chat/services/context-compaction.ts
20633
20841
  /**
20634
- * Load recent user messages from committed history. Each one keeps its
20635
- * original author and source event.
20842
+ * Context compaction.
20843
+ *
20844
+ * Bounds Pi history for long conversations and commits a history
20845
+ * replacement. Capacity compaction gets its summary from the caller, which
20846
+ * asks the agent model with the cached request prefix. Mid-turn replacements
20847
+ * keep the authored instruction before the summary. Turn-start replacements keep recent user
20848
+ * messages, the summary, then the new instruction. Checkpoints can append
20849
+ * fresh runtime context; the next replacement removes it again.
20636
20850
  */
20637
- async function loadRetainedUserMessages(conversationId, pendingMessages) {
20638
- const projection = await loadConversationProjection({ conversationId });
20639
- const pendingKeys = new Set(pendingMessages.map(retainedMessageKey));
20640
- let pendingStart = projection.messages.findIndex((message) => pendingKeys.has(retainedMessageKey(message)));
20641
- if (pendingStart > 0 && isStandaloneRuntimeContextMessage(projection.messages, pendingStart - 1)) pendingStart -= 1;
20642
- const history = pendingStart === -1 ? projection.messages : projection.messages.slice(0, pendingStart);
20643
- return selectRetainedUserMessageEntries(trimTrailingAssistantMessages(history)).map((entry) => {
20644
- const provenance = projection.provenance[entry.sourceIndex];
20645
- if (!provenance) throw new Error("retained message provenance is missing");
20646
- return {
20647
- message: entry.message,
20648
- provenance,
20649
- sourceEventSeq: projection.seqs[entry.sourceIndex]
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");
20851
+ const RETAINED_USER_MESSAGE_TOKENS = 2e4;
20852
+ /** Raised when Junior cannot compact history below the active model's hard ceiling. */
20853
+ var ContextInputLimitExceededError = class extends Error {
20854
+ estimatedTokens;
20855
+ inputLimitTokens;
20856
+ constructor(estimatedTokens, inputLimitTokens) {
20857
+ super(`Agent context is ${estimatedTokens} estimated input tokens, above the ${inputLimitTokens} token limit`);
20858
+ this.estimatedTokens = estimatedTokens;
20859
+ this.inputLimitTokens = inputLimitTokens;
20860
+ this.name = "ContextInputLimitExceededError";
20861
+ }
20862
+ };
20863
+ function textPart(value) {
20864
+ if (value && typeof value === "object" && value.type === "text" && typeof value.text === "string") return value.text;
20661
20865
  }
20662
- /** Measure provider-visible history without counting host-only message fields. */
20663
- function estimateHistoryTokens(messages) {
20664
- return estimateContextTokens(messages).tokens;
20866
+ /** Render Pi message text for retained user-message selection. */
20867
+ function messageText(message) {
20868
+ const content = message.content;
20869
+ const unwrapTask = message.role === "user";
20870
+ const displayText = (text) => unwrapTask ? unwrapCurrentInstruction(text) ?? text : text;
20871
+ if (!Array.isArray(content)) return typeof content === "string" ? displayText(content) : "";
20872
+ return content.map(textPart).filter((text) => Boolean(text)).map(displayText).join("\n").trim();
20665
20873
  }
20666
- /**
20667
- * Estimate a replacement request from each message's own size. A kept
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);
20874
+ function sanitizeText(text) {
20875
+ 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
20876
  }
20674
- async function loadLastInstruction(conversationId) {
20675
- const event = await getConversationEventStore().loadLatestInstruction(conversationId);
20676
- if (!event) return void 0;
20677
- if (event.data.type === "user_message") {
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
- }
20877
+ function truncateToTokenBudget(text, maxTokens) {
20878
+ const maxChars = Math.max(0, maxTokens * 4);
20879
+ if (text.length <= maxChars) return text;
20880
+ return `${text.slice(0, Math.max(0, maxChars - 3)).trimEnd()}...`;
20685
20881
  }
20686
- function loadCompactionSource(messages) {
20687
- if (messages.length > 0) return {
20688
- estimatedTokens: estimateHistoryTokens(messages),
20689
- messages
20690
- };
20691
- return { reason: "missing_context" };
20882
+ function isCompactionSummary(text) {
20883
+ return isCompactionSummaryText(text);
20692
20884
  }
20693
- /**
20694
- * Replace oversized active history at Pi's next-turn boundary before another
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));
20885
+ function isPayloadHeavy(text) {
20886
+ return /<data_base64>[\s\S]*?<\/data_base64>|data:image\/[a-z0-9.+-]+;base64,/i.test(text);
20713
20887
  }
20714
- async function compactActiveAboveThreshold(args, summarize, source, triggerTokens) {
20715
- const pendingMessages = args.pendingMessages ?? [];
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
- });
20888
+ /** Build a text-only user message for a replacement history. */
20889
+ function userMessage(text) {
20802
20890
  return {
20803
- compacted: true,
20804
- piMessages: messages
20891
+ role: "user",
20892
+ content: [{
20893
+ type: "text",
20894
+ text
20895
+ }],
20896
+ timestamp: Date.now()
20805
20897
  };
20806
20898
  }
20807
- // src/chat/services/tool-result-trimming.ts
20808
- /** Results up to this many text characters stay whole. */
20809
- const MAX_KEPT_RESULT_CHARS = 2e3;
20810
- /** Error results explain failures, so they stay whole up to this size. */
20811
- const MAX_KEPT_ERROR_CHARS = 8e3;
20812
- const EDGE_CHARS = 500;
20813
- function role(message) {
20814
- return message.role;
20899
+ function userMessageContent(message) {
20900
+ const content = message.content;
20901
+ return Array.isArray(content) ? content : [];
20902
+ }
20903
+ function hasTurnBootstrap(message) {
20904
+ return userMessageContent(message).some((part) => textPart(part)?.startsWith(`<${TURN_CONTEXT_TAG}>`) === true);
20905
+ }
20906
+ function isSessionTurnContext(text) {
20907
+ return text?.startsWith(`<runtime-turn-context>`) === true && text.includes(`\n<runtime>\n`);
20815
20908
  }
20816
- function resultParts(message) {
20817
- const content = message.content;
20818
- return Array.isArray(content) ? content : [];
20909
+ /** Remove the sections that only the Turn that received them can use. */
20910
+ function withoutRequestContext(text) {
20911
+ 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
20912
  }
20820
- function resultText(parts) {
20821
- return parts.map((part) => part.type === "text" && typeof part.text === "string" ? part.text : "").join("\n");
20913
+ /** Find the latest session context and keep only its session sections. */
20914
+ function latestSessionContext(messages) {
20915
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
20916
+ const message = messages[index];
20917
+ const text = userMessageContent(message).map(textPart).find(isSessionTurnContext);
20918
+ if (text) return {
20919
+ ...message,
20920
+ content: [{
20921
+ type: "text",
20922
+ text: withoutRequestContext(text)
20923
+ }]
20924
+ };
20925
+ }
20822
20926
  }
20823
- function pointer(seq) {
20824
- return `readConversationEvent({ seq: ${seq} })`;
20927
+ function effectiveRuntimeContext(messages) {
20928
+ let latestBootstrapIndex = -1;
20929
+ for (let index = messages.length - 1; index >= 0; index -= 1) if (hasTurnBootstrap(messages[index])) {
20930
+ latestBootstrapIndex = index;
20931
+ break;
20932
+ }
20933
+ const effectiveMessages = latestBootstrapIndex < 0 ? messages : messages.slice(latestBootstrapIndex);
20934
+ return runtimeContextContent(effectiveMessages, effectiveMessages);
20825
20935
  }
20826
- /** Replace a long result text with a header, its edges, and a read-back pointer. */
20827
- function clearedText(toolName, text, seq) {
20828
- return [
20829
- `[Tool result cleared to save context: ${toolName}, ${text.length.toLocaleString("en-US")} chars. Full result: ${pointer(seq)}`,
20830
- "First 500 chars:",
20831
- text.slice(0, EDGE_CHARS),
20832
- "Last 500 chars:",
20833
- `${text.slice(-500)}]`
20834
- ].join("\n");
20936
+ function runtimeContextContent(messages, agentsMessages) {
20937
+ const allContent = messages.flatMap(userMessageContent);
20938
+ const firstAgentsIndex = allContent.findIndex((part) => textPart(part)?.startsWith("# AGENTS.md instructions") === true);
20939
+ const content = allContent.filter((part) => textPart(part)?.startsWith("# AGENTS.md instructions") !== true);
20940
+ const visibleAgents = findVisibleAgentsInstructions(agentsMessages);
20941
+ if (visibleAgents?.active === true) {
20942
+ const insertionIndex = firstAgentsIndex < 0 ? content.length : Math.min(firstAgentsIndex, content.length);
20943
+ content.splice(insertionIndex, 0, {
20944
+ type: "text",
20945
+ text: renderAgentsInstructions({
20946
+ directory: visibleAgents.directory,
20947
+ text: visibleAgents.text
20948
+ })
20949
+ });
20950
+ }
20951
+ const latestTimestamp = messages.at(-1)?.timestamp;
20952
+ return {
20953
+ content,
20954
+ timestamp: typeof latestTimestamp === "number" ? latestTimestamp : Date.now()
20955
+ };
20835
20956
  }
20836
- function trimResult(message, seq) {
20837
- const parts = resultParts(message);
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
- });
20957
+ function toRuntimeContextMessage(runtimeContext, timestamp) {
20958
+ if (runtimeContext.content.length === 0) return;
20855
20959
  return {
20856
- message: {
20857
- ...message,
20858
- content
20859
- },
20860
- removedChars: Math.max(0, text.length - resultText(content).length)
20960
+ role: "user",
20961
+ content: runtimeContext.content,
20962
+ timestamp: timestamp ?? runtimeContext.timestamp
20861
20963
  };
20862
20964
  }
20965
+ function runtimeContextMessage(messages, timestamp) {
20966
+ return toRuntimeContextMessage(effectiveRuntimeContext(messages), timestamp);
20967
+ }
20863
20968
  /**
20864
- * Trim old tool results in a replacement history.
20969
+ * Build the runtime context that the current Turn can use after an in-turn
20970
+ * replacement.
20865
20971
  *
20866
- * Results after the last Turn instruction belong to the latest Turn and stay
20867
- * whole. Runtime context and summaries are user messages too, so they do not
20868
- * mark a Turn. So do short results, error results up to a cap, and
20869
- * results that have no source event to point to. Images outside the latest
20870
- * Turn become a short note.
20972
+ * Request context, such as plugin context and disabled tools, is true only for
20973
+ * the Turn that received it. From earlier Turns, keep only the latest session
20974
+ * context and AGENTS.md instructions.
20871
20975
  */
20872
- function trimToolResults(entries) {
20873
- let latestInstructionIndex = -1;
20874
- entries.forEach((entry, index) => {
20875
- if (hasCurrentInstruction(entry.message)) latestInstructionIndex = index;
20876
- });
20877
- const trimming = {
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
- };
20976
+ function turnRuntimeContextMessage(messages, turnStartMessageIndex, timestamp) {
20977
+ if (turnStartMessageIndex === void 0) return runtimeContextMessage(retainRuntimeTurnContext(messages), timestamp);
20978
+ const earlierContext = retainRuntimeTurnContext(messages.slice(0, turnStartMessageIndex));
20979
+ const turnContext = retainRuntimeTurnContext(messages.slice(turnStartMessageIndex));
20980
+ const sessionContext = turnContext.some((message) => userMessageContent(message).map(textPart).some(isSessionTurnContext)) ? void 0 : latestSessionContext(earlierContext);
20981
+ return toRuntimeContextMessage(runtimeContextContent(sessionContext ? [sessionContext, ...turnContext] : turnContext, [...earlierContext, ...turnContext]), timestamp);
20895
20982
  }
20896
- // src/chat/services/context-compaction-swap.ts
20897
20983
  /**
20898
- * Prepared-summary swap.
20899
- *
20900
- * A background job writes `compaction_prepared` with a summary of the history
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.
20984
+ * Build the runtime context of summarized history that the kept history
20985
+ * does not carry: the latest session context and the AGENTS.md
20986
+ * instructions. Request context of earlier Turns is left out.
20907
20987
  */
20908
- /** Compare a message across a durable commit, which drops undefined fields. */
20909
- function durableIdentity(message) {
20910
- const { role, timestamp, content, toolCallId } = message;
20911
- return JSON.parse(JSON.stringify({
20912
- role,
20913
- timestamp,
20914
- content,
20915
- toolCallId
20916
- }));
20988
+ function summarizedRuntimeContextMessage(summarized, kept) {
20989
+ const earlierContext = retainRuntimeTurnContext(summarized);
20990
+ const sessionContext = retainRuntimeTurnContext(kept).some((message) => userMessageContent(message).map(textPart).some(isSessionTurnContext)) ? void 0 : latestSessionContext(earlierContext);
20991
+ return toRuntimeContextMessage(runtimeContextContent(sessionContext ? [sessionContext] : [], findVisibleAgentsInstructions(kept) ? [] : earlierContext));
20917
20992
  }
20918
- function committedPrefixLength(messages, committed) {
20919
- const limit = Math.min(messages.length, committed.length);
20920
- for (let index = 0; index < limit; index += 1) if (!isDeepStrictEqual(durableIdentity(messages[index]), durableIdentity(committed[index]))) return index;
20921
- return limit;
20993
+ /**
20994
+ * Build retained user messages for a compacted Pi replacement history. Each
20995
+ * entry keeps the index of its source message.
20996
+ */
20997
+ function selectRetainedUserMessageEntries(messages, maxTokens = RETAINED_USER_MESSAGE_TOKENS) {
20998
+ const selected = [];
20999
+ let remaining = maxTokens;
21000
+ for (let sourceIndex = messages.length - 1; sourceIndex >= 0; sourceIndex -= 1) {
21001
+ if (isStandaloneRuntimeContextMessage(messages, sourceIndex)) continue;
21002
+ const message = stripRuntimeTurnContext([messages[sourceIndex]])[0];
21003
+ if (!message || message.role !== "user" || remaining <= 0) continue;
21004
+ const text = sanitizeText(messageText(message));
21005
+ if (!text || isCompactionSummary(text) || isPayloadHeavy(text)) continue;
21006
+ const tokens = estimateTextTokens(text);
21007
+ if (tokens <= remaining) {
21008
+ selected.push({
21009
+ message: userMessage(text),
21010
+ sourceIndex
21011
+ });
21012
+ remaining -= tokens;
21013
+ continue;
21014
+ }
21015
+ const truncated = truncateToTokenBudget(text, remaining);
21016
+ if (truncated) selected.push({
21017
+ message: userMessage(truncated),
21018
+ sourceIndex
21019
+ });
21020
+ break;
21021
+ }
21022
+ return selected.reverse();
20922
21023
  }
20923
- function discard(reason) {
20924
- setSpanAttributes({
20925
- "app.compaction.outcome": "discarded",
20926
- "app.compaction.discard_reason": reason
21024
+ /** Match a message across a durable commit, which can reorder JSON keys. */
21025
+ function retainedMessageKey(message) {
21026
+ const { role, timestamp } = message;
21027
+ return `${String(role)}:${String(timestamp)}:${messageText(message)}`;
21028
+ }
21029
+ /**
21030
+ * Load recent user messages from committed history. Each one keeps its
21031
+ * original author and source event.
21032
+ */
21033
+ async function loadRetainedUserMessages(conversationId, pendingMessages) {
21034
+ const projection = await loadConversationProjection({ conversationId });
21035
+ const pendingKeys = new Set(pendingMessages.map(retainedMessageKey));
21036
+ let pendingStart = projection.messages.findIndex((message) => pendingKeys.has(retainedMessageKey(message)));
21037
+ if (pendingStart > 0 && isStandaloneRuntimeContextMessage(projection.messages, pendingStart - 1)) pendingStart -= 1;
21038
+ const history = pendingStart === -1 ? projection.messages : projection.messages.slice(0, pendingStart);
21039
+ return selectRetainedUserMessageEntries(trimTrailingAssistantMessages(history)).map((entry) => {
21040
+ const provenance = projection.provenance[entry.sourceIndex];
21041
+ if (!provenance) throw new Error("retained message provenance is missing");
21042
+ return {
21043
+ message: entry.message,
21044
+ provenance,
21045
+ sourceEventSeq: projection.seqs[entry.sourceIndex]
21046
+ };
20927
21047
  });
20928
- return { compacted: false };
21048
+ }
21049
+ /** Keep generated text inside the existing evidence-only prompt boundary. */
21050
+ function renderCompactionSummary(summary) {
21051
+ return [
21052
+ COMPACTION_SUMMARY_PREFIX,
21053
+ "<thread-context authority=\"evidence-only\">",
21054
+ escapeXml(summary),
21055
+ "</thread-context>"
21056
+ ].join("\n");
21057
+ }
21058
+ /** Measure provider-visible history without counting host-only message fields. */
21059
+ function estimateHistoryTokens(messages) {
21060
+ return estimateContextTokens(messages).tokens;
20929
21061
  }
20930
21062
  /**
20931
- * Find the newest background compaction fact of the current History version.
20932
- * Facts of earlier versions belong to history that a replacement already
20933
- * removed.
21063
+ * Estimate a replacement request from each message's own size. A kept
21064
+ * assistant message holds provider usage for the whole request before the
21065
+ * replacement, so usage is ignored here.
20934
21066
  */
20935
- async function loadLatestBackgroundCompaction(conversationId) {
20936
- const store = getConversationEventStore();
20937
- const [historyVersion, page] = await Promise.all([store.loadCurrentHistoryVersion(conversationId), store.query(conversationId, {
20938
- limit: 1,
20939
- types: ["compaction_requested", "compaction_prepared"]
20940
- })]);
20941
- const event = page.events.at(-1);
20942
- return event && event.historyVersion === historyVersion ? {
20943
- event,
20944
- historyVersion
20945
- } : void 0;
21067
+ function estimateReplacementTokens(messages, requestOverheadTokens = 0) {
21068
+ return messages.reduce((total, message) => total + estimateTokens(message), requestOverheadTokens);
21069
+ }
21070
+ async function loadLastInstruction(conversationId) {
21071
+ const event = await getConversationEventStore().loadLatestInstruction(conversationId);
21072
+ if (!event) return void 0;
21073
+ if (event.data.type === "user_message") {
21074
+ if (event.data.provenance.authority !== "instruction") return void 0;
21075
+ return {
21076
+ message: piMessageFromHistoryItem(event.data),
21077
+ provenance: event.data.provenance,
21078
+ sourceEventSeq: event.seq
21079
+ };
21080
+ }
20946
21081
  }
20947
- /**
20948
- * Swap a ready prepared summary into history, or run today's capacity
20949
- * compaction when none can be used.
20950
- */
20951
- async function compactWithPreparedSummary(args, summarize) {
20952
- const swapped = await swapPreparedCompaction(args);
20953
- if (swapped.compacted || swapped.reason === "history_conflict") return swapped;
20954
- return await compactActiveContextIfNeeded(args, summarize);
21082
+ function loadCompactionSource(messages) {
21083
+ if (messages.length > 0) return {
21084
+ estimatedTokens: estimateHistoryTokens(messages),
21085
+ messages
21086
+ };
21087
+ return { reason: "missing_context" };
20955
21088
  }
20956
21089
  /**
20957
- * Replace history with a ready prepared summary. Turn start swaps whenever
20958
- * one is ready. Between model calls, swap only above the compaction
20959
- * threshold.
21090
+ * Replace oversized active history at Pi's next-turn boundary before another
21091
+ * provider request can observe it.
21092
+ *
21093
+ * `summarize` gets the history without pending messages. When it fails, the
21094
+ * history stays as it is, unless the history is at the input limit.
20960
21095
  */
20961
- async function swapPreparedCompaction(args) {
21096
+ async function compactActiveContextIfNeeded(args, summarize) {
20962
21097
  const pendingMessages = args.pendingMessages ?? [];
20963
- const sourceMessages = [...args.piMessages, ...pendingMessages.map((entry) => entry.message)];
21098
+ const source = loadCompactionSource([...args.piMessages, ...pendingMessages.map((entry) => entry.message)]);
21099
+ if ("reason" in source) return {
21100
+ compacted: false,
21101
+ reason: source.reason
21102
+ };
20964
21103
  const triggerTokens = getAgentContextCompactionTriggerTokens(args.modelId);
20965
- const estimatedTokens = estimateHistoryTokens(sourceMessages);
20966
- if (args.mode !== "blocking" && estimatedTokens <= triggerTokens) return {
21104
+ if (source.estimatedTokens <= triggerTokens) return {
20967
21105
  compacted: false,
20968
21106
  reason: "below_threshold"
20969
21107
  };
20970
- const latest = await loadLatestBackgroundCompaction(args.conversationId);
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
- });
21108
+ return await withCompactionSpan(args.mode, () => compactActiveAboveThreshold(args, summarize, source, triggerTokens));
20986
21109
  }
20987
- async function applyPreparedSummary(args, prepared, budget) {
21110
+ async function compactActiveAboveThreshold(args, summarize, source, triggerTokens) {
20988
21111
  const pendingMessages = args.pendingMessages ?? [];
20989
- const projection = await loadConversationProjection({ conversationId: args.conversationId });
20990
- const committedLength = committedPrefixLength(args.piMessages, projection.messages);
20991
- const firstAfterMark = projection.seqs.slice(0, committedLength).findIndex((seq) => seq > prepared.markSeq);
20992
- const markIndex = firstAfterMark === -1 ? committedLength : firstAfterMark;
20993
- const summarized = args.piMessages.slice(0, markIndex);
20994
- const kept = args.piMessages.slice(markIndex);
20995
- if (kept[0]?.role === "toolResult") return discard("split_tool_call");
20996
- const retained = selectRetainedUserMessageEntries(trimTrailingAssistantMessages(summarized)).map((entry) => ({
20997
- message: entry.message,
20998
- provenance: projection.provenance[entry.sourceIndex],
20999
- sourceEventSeq: projection.seqs[entry.sourceIndex]
21000
- }));
21001
- const contextMessage = summarizedRuntimeContextMessage(summarized, [...kept, ...pendingMessages.map((entry) => entry.message)]);
21002
- const { entries: trimmedEntries, trimming } = trimToolResults(kept.map((message, offset) => {
21003
- const index = markIndex + offset;
21004
- return index < committedLength ? {
21005
- message,
21006
- provenance: projection.provenance[index],
21007
- sourceEventSeq: projection.seqs[index]
21008
- } : {
21009
- message,
21010
- provenance: contextProvenance
21112
+ const retainUserMessages = args.mode === "blocking" && pendingMessages.length > 0;
21113
+ await args.onCompactionStart?.();
21114
+ const inputLimitTokens = getAgentContextInputLimitTokens(args.modelId);
21115
+ let summary;
21116
+ try {
21117
+ summary = await summarize(args.piMessages, args.signal);
21118
+ } catch (error) {
21119
+ if (source.estimatedTokens >= inputLimitTokens) throw new ContextInputLimitExceededError(source.estimatedTokens, inputLimitTokens);
21120
+ logWarn("context_compaction.active.summary.failed", {
21121
+ "app.context_input_limit_tokens": inputLimitTokens,
21122
+ "app.context_tokens_estimated": source.estimatedTokens,
21123
+ "exception.message": error instanceof Error ? error.message : String(error)
21124
+ });
21125
+ setSpanAttributes({ "app.compaction.outcome": "summary_failed" });
21126
+ return {
21127
+ compacted: false,
21128
+ reason: "summary_failed"
21011
21129
  };
21130
+ }
21131
+ const summaryMessage = userMessage(appendOpenPlan(renderCompactionSummary(summary), source.messages));
21132
+ const retainedInstruction = pendingMessages.length === 0 && !retainUserMessages ? await loadLastInstruction(args.conversationId) : void 0;
21133
+ const instructionMessages = retainedInstruction ? [retainedInstruction.message] : pendingMessages.map((entry) => entry.message);
21134
+ const instructionProvenance = retainedInstruction ? [retainedInstruction.provenance] : pendingMessages.map((entry) => entry.provenance);
21135
+ const instructionTimestamp = instructionMessages[0]?.timestamp;
21136
+ const contextMessage = turnRuntimeContextMessage(args.runtimeContextMessages ?? args.piMessages, args.turnStartMessageIndex, typeof instructionTimestamp === "number" ? instructionTimestamp : void 0);
21137
+ const contextEntries = contextMessage ? [{
21138
+ message: contextMessage,
21139
+ provenance: contextProvenance
21140
+ }] : [];
21141
+ const instructionEntries = instructionMessages.map((message, index) => ({
21142
+ message,
21143
+ provenance: instructionProvenance[index],
21144
+ ...index === 0 && retainedInstruction ? { sourceEventSeq: retainedInstruction.sourceEventSeq } : void 0
21012
21145
  }));
21013
- const replacement = [
21014
- ...contextMessage ? [{
21015
- message: contextMessage,
21016
- provenance: contextProvenance
21017
- }] : [],
21018
- ...retained,
21019
- {
21020
- message: userMessage(appendOpenPlan(renderCompactionSummary(prepared.summary), summarized)),
21021
- provenance: contextProvenance
21022
- },
21023
- ...trimmedEntries,
21024
- ...pendingMessages
21146
+ const summaryEntry = {
21147
+ message: summaryMessage,
21148
+ provenance: contextProvenance
21149
+ };
21150
+ const retainedUserMessages = retainUserMessages ? await loadRetainedUserMessages(args.conversationId, instructionMessages) : [];
21151
+ const replacement = retainUserMessages ? [
21152
+ ...retainedUserMessages,
21153
+ summaryEntry,
21154
+ ...contextEntries,
21155
+ ...instructionEntries
21156
+ ] : [
21157
+ ...contextEntries,
21158
+ ...instructionEntries,
21159
+ summaryEntry
21025
21160
  ];
21161
+ const retainedMessageCount = retainedUserMessages.length + instructionMessages.length;
21026
21162
  const messages = replacement.map((entry) => entry.message);
21027
- const replacementTokens = estimateReplacementTokens(messages, args.requestOverheadTokens);
21028
- const targetTokens = calculateContextCompactionTargetTokens(budget.triggerTokens);
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");
21163
+ const replacementInputTokens = estimateReplacementTokens(messages, args.requestOverheadTokens);
21164
+ if (replacementInputTokens >= inputLimitTokens) throw new ContextInputLimitExceededError(replacementInputTokens, inputLimitTokens);
21039
21165
  args.signal?.throwIfAborted();
21040
- if ((await getConversationEventStore().replaceHistory(args.conversationId, {
21166
+ await getConversationEventStore().replaceHistory(args.conversationId, {
21041
21167
  createdAtMs: Date.now(),
21042
21168
  data: {
21043
21169
  type: "compaction",
21044
21170
  modelId: args.modelId,
21045
21171
  details: {
21046
21172
  reason: "capacity",
21047
- estimatedInputTokens: budget.estimatedTokens,
21048
- replacementInputTokens: replacementTokens,
21049
- triggerTokens: budget.triggerTokens,
21050
- inputLimitTokens: getAgentContextInputLimitTokens(args.modelId),
21051
- inputMessageCount: args.piMessages.length + pendingMessages.length,
21052
- retainedMessageCount: retained.length + kept.length + pendingMessages.length,
21053
- summaryChars: prepared.summary.length
21173
+ estimatedInputTokens: source.estimatedTokens,
21174
+ replacementInputTokens,
21175
+ triggerTokens,
21176
+ inputLimitTokens,
21177
+ inputMessageCount: source.messages.length,
21178
+ retainedMessageCount,
21179
+ summaryChars: summary.length
21054
21180
  },
21055
- summary: prepared.summary,
21181
+ summary,
21056
21182
  replacementHistory: replacement.map((entry) => ({
21057
21183
  item: historyItemFromPiMessage(entry.message, entry.provenance),
21058
21184
  ...entry.sourceEventSeq === void 0 ? void 0 : { sourceEventSeq: entry.sourceEventSeq }
21059
21185
  }))
21060
21186
  }
21061
- }, { expectedHistoryVersion: budget.historyVersion })).status === "conflict") return {
21062
- ...discard("conflict"),
21063
- reason: "history_conflict"
21064
- };
21065
- setSpanAttributes({
21066
- "app.compaction.outcome": "applied",
21067
- "app.compaction.summary_chars": prepared.summary.length
21187
+ });
21188
+ setSpanAttributes({
21189
+ "app.compaction.outcome": "compacted",
21190
+ "app.compaction.input_messages": source.messages.length,
21191
+ "app.compaction.retained_messages": retainedMessageCount,
21192
+ "app.compaction.summary_chars": summary.length,
21193
+ "app.compaction.input.estimate": source.estimatedTokens,
21194
+ "app.compaction.replacement.estimate": replacementInputTokens,
21195
+ "app.compaction.input_limit": inputLimitTokens,
21196
+ "app.compaction.threshold": triggerTokens
21068
21197
  });
21069
21198
  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()
21199
+ compacted: true,
21200
+ piMessages: messages
21151
21201
  };
21152
21202
  }
21153
- async function complete(request, streamFn, appended) {
21154
- const message = await (await streamFn(request.model, {
21155
- ...request.context,
21156
- messages: [...request.context.messages, ...appended]
21157
- }, {
21158
- ...request.options,
21159
- maxTokens: SUMMARY_MAX_TOKENS
21160
- })).result();
21161
- if (message.stopReason === "error" || message.stopReason === "aborted") throw createProviderError(message.errorMessage ?? message.stopReason, { modelId: request.model.id });
21162
- return message;
21203
+ // src/chat/services/tool-result-trimming.ts
21204
+ /** Results up to this many text characters stay whole. */
21205
+ const MAX_KEPT_RESULT_CHARS = 2e3;
21206
+ /** Error results explain failures, so they stay whole up to this size. */
21207
+ const MAX_KEPT_ERROR_CHARS = 8e3;
21208
+ const EDGE_CHARS = 500;
21209
+ function role(message) {
21210
+ return message.role;
21163
21211
  }
21164
- /** Read the summary, or name why the output is not a usable summary. */
21165
- function readSummary(message) {
21166
- if (message.content.some((part) => part.type === "toolCall")) return { failure: "tool_call" };
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" };
21212
+ function resultParts(message) {
21213
+ const content = message.content;
21214
+ return Array.isArray(content) ? content : [];
21172
21215
  }
21173
- /**
21174
- * Ask the agent model for a summary of the request messages.
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);
21216
+ function resultText(parts) {
21217
+ return parts.map((part) => part.type === "text" && typeof part.text === "string" ? part.text : "").join("\n");
21188
21218
  }
21189
- // src/chat/services/background-compaction.ts
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`;
21219
+ function pointer(seq) {
21220
+ return `readConversationEvent({ seq: ${seq} })`;
21217
21221
  }
21218
- /** Provider-reported input of the last model request, cache included. */
21219
- function lastRequestInputSize(messages) {
21220
- for (let index = messages.length - 1; index >= 0; index -= 1) {
21221
- const message = messages[index];
21222
- if (message.role === "assistant") {
21223
- const { input, cacheRead, cacheWrite } = message.usage;
21224
- return input + cacheRead + cacheWrite;
21225
- }
21226
- }
21222
+ /** Replace a long result text with a header, its edges, and a read-back pointer. */
21223
+ function clearedText(toolName, text, seq) {
21224
+ return [
21225
+ `[Tool result cleared to save context: ${toolName}, ${text.length.toLocaleString("en-US")} chars. Full result: ${pointer(seq)}`,
21226
+ "First 500 chars:",
21227
+ text.slice(0, EDGE_CHARS),
21228
+ "Last 500 chars:",
21229
+ `${text.slice(-500)}]`
21230
+ ].join("\n");
21231
+ }
21232
+ function trimResult(message, seq) {
21233
+ const parts = resultParts(message);
21234
+ const text = resultText(parts);
21235
+ const hasImage = parts.some((part) => part.type === "image");
21236
+ const keptChars = message.isError === true ? MAX_KEPT_ERROR_CHARS : MAX_KEPT_RESULT_CHARS;
21237
+ const clearText = text.length > keptChars;
21238
+ if (!clearText && !hasImage) return;
21239
+ const toolName = String(message.toolName ?? "tool");
21240
+ const content = clearText ? [{
21241
+ type: "text",
21242
+ text: clearedText(toolName, text, seq)
21243
+ }] : parts.map((part) => part.type === "image" ? {
21244
+ type: "text",
21245
+ text: `[image cleared: ${toolName}, seq ${seq}]`
21246
+ } : part);
21247
+ if (clearText && hasImage) content.push({
21248
+ type: "text",
21249
+ text: `[image cleared: ${toolName}, seq ${seq}]`
21250
+ });
21251
+ return {
21252
+ message: {
21253
+ ...message,
21254
+ content
21255
+ },
21256
+ removedChars: Math.max(0, text.length - resultText(content).length)
21257
+ };
21227
21258
  }
21228
21259
  /**
21229
- * Return whether a Turn may request a background summary for this History
21230
- * version. It may not while a request is pending, while a ready summary is
21231
- * still unused, or after the attempt limit.
21260
+ * Trim old tool results in a replacement history.
21232
21261
  *
21233
- * A Turn swaps a ready summary in before its first model request. A swap
21234
- * makes a new History version. So a ready summary of this version that was
21235
- * prepared before the Turn started was discarded, for example because the
21236
- * history after its mark is too large now. It counts as a failed attempt, so
21237
- * a new request can replace it.
21262
+ * Results after the last Turn instruction belong to the latest Turn and stay
21263
+ * whole. Runtime context and summaries are user messages too, so they do not
21264
+ * mark a Turn. So do short results, error results up to a cap, and
21265
+ * results that have no source event to point to. Images outside the latest
21266
+ * Turn become a short note.
21238
21267
  */
21239
- function mayRequest(events, historyVersion, nowMs, turnStartedAtMs) {
21240
- const outcomes = /* @__PURE__ */ new Map();
21241
- for (const event of events) if (event.data.type === "compaction_prepared" && event.data.historyVersion === historyVersion) outcomes.set(event.data.markSeq, {
21242
- outcome: event.data.outcome,
21243
- createdAtMs: event.createdAtMs
21268
+ function trimToolResults(entries) {
21269
+ let latestInstructionIndex = -1;
21270
+ entries.forEach((entry, index) => {
21271
+ if (hasCurrentInstruction(entry.message)) latestInstructionIndex = index;
21244
21272
  });
21245
- let failed = 0;
21246
- for (const event of events) {
21247
- if (event.data.type !== "compaction_requested" || event.data.historyVersion !== historyVersion) continue;
21248
- const prepared = outcomes.get(event.data.markSeq);
21249
- if (prepared?.outcome === "ready" && prepared.createdAtMs >= turnStartedAtMs) return false;
21250
- if (prepared || nowMs - event.createdAtMs >= REQUEST_TIMEOUT_MS) failed += 1;
21251
- else return false;
21252
- }
21253
- return failed < MAX_FAILED_ATTEMPTS;
21273
+ const trimming = {
21274
+ trimmedResults: 0,
21275
+ removedChars: 0
21276
+ };
21277
+ return {
21278
+ entries: entries.map((entry, index) => {
21279
+ if (index > latestInstructionIndex || role(entry.message) !== "toolResult" || entry.sourceEventSeq === void 0) return entry;
21280
+ const result = trimResult(entry.message, entry.sourceEventSeq);
21281
+ if (!result) return entry;
21282
+ trimming.trimmedResults += 1;
21283
+ trimming.removedChars += result.removedChars;
21284
+ return {
21285
+ ...entry,
21286
+ message: result.message
21287
+ };
21288
+ }),
21289
+ trimming
21290
+ };
21254
21291
  }
21292
+ // src/chat/services/context-compaction-swap.ts
21255
21293
  /**
21256
- * Request a background summary when the last model request of a completed
21257
- * Turn was at or above the mark.
21294
+ * Prepared-summary swap.
21258
21295
  *
21259
- * `turnStartedAtMs` is when this execution slice started, before its first
21260
- * model request. Without a queue or below the mark, it does nothing. A failure here leaves
21261
- * blocking compaction as the fallback, so it is logged and does not fail the
21262
- * Turn. When the send fails after the request is written, the request times
21263
- * out and counts as a failed attempt.
21296
+ * A background job writes `compaction_prepared` with a summary of the history
21297
+ * up to `markSeq`. The Turn swaps it in without a model call: retained user
21298
+ * messages, the summary, then every message after the mark. Turn start swaps
21299
+ * a ready summary at once. Between model calls, a swap runs only above the
21300
+ * compaction threshold, in place of a blocking summary call. A summary that
21301
+ * no longer matches the history is discarded, and the Turn carries on as if
21302
+ * none existed.
21264
21303
  */
21265
- async function requestBackgroundCompaction(args) {
21266
- if (!args.queue) return;
21267
- const inputSize = lastRequestInputSize(args.agent.state.messages);
21268
- if (inputSize === void 0 || inputSize < getAgentBackgroundCompactionMarkTokens(args.modelId)) return;
21269
- try {
21270
- await requestAboveMark({
21271
- ...args,
21272
- inputSize,
21273
- queue: args.queue
21274
- });
21275
- } catch (error) {
21276
- logWarn("context_compaction.background.request_failed", { "error.type": error instanceof Error ? error.name : typeof error });
21277
- }
21278
- }
21279
- async function requestAboveMark(args) {
21280
- const nowMs = Date.now();
21281
- const eventStore = getConversationEventStore();
21282
- const events = await eventStore.loadCurrentHistory(args.conversationId);
21283
- const historyVersion = events[0]?.historyVersion;
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
21304
+ /** Compare a message across a durable commit, which drops undefined fields. */
21305
+ function durableIdentity(message) {
21306
+ const { role, timestamp, content, toolCallId } = message;
21307
+ return JSON.parse(JSON.stringify({
21308
+ role,
21309
+ timestamp,
21310
+ content,
21311
+ toolCallId
21312
+ }));
21313
+ }
21314
+ function committedPrefixLength(messages, committed) {
21315
+ const limit = Math.min(messages.length, committed.length);
21316
+ for (let index = 0; index < limit; index += 1) if (!isDeepStrictEqual(durableIdentity(messages[index]), durableIdentity(committed[index]))) return index;
21317
+ return limit;
21318
+ }
21319
+ function discard(reason) {
21320
+ setSpanAttributes({
21321
+ "app.compaction.outcome": "discarded",
21322
+ "app.compaction.discard_reason": reason
21324
21323
  });
21324
+ return { compacted: false };
21325
21325
  }
21326
- /** A fixed label for a failed summary. Never raw exception text. */
21327
- function failureLabel(error, signal) {
21328
- if (signal.aborted) return "timeout";
21329
- if (error instanceof ContextSummaryError) return error.failure;
21330
- const providerError = findProviderError(error);
21331
- return providerError ? `provider_${providerError.kind}` : "summary_error";
21326
+ /**
21327
+ * Swap a ready prepared summary into history, or run today's capacity
21328
+ * compaction when none can be used.
21329
+ */
21330
+ async function compactWithPreparedSummary(args, summarize) {
21331
+ const swapped = await swapPreparedCompaction(args);
21332
+ if (swapped.compacted || swapped.reason === "history_conflict") return swapped;
21333
+ return await compactActiveContextIfNeeded(args, summarize);
21332
21334
  }
21333
21335
  /**
21334
- * Run one background compaction job.
21335
- *
21336
- * It writes `compaction_prepared` once for the request, with a summary or a
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.
21336
+ * Replace history with a ready prepared summary. Turn start swaps whenever
21337
+ * one is ready. Between model calls, swap only above the compaction
21338
+ * threshold.
21340
21339
  */
21341
- async function processBackgroundCompaction(message, options = {}) {
21342
- const startedAtMs = Date.now();
21343
- await withLogContext({ conversationId: message.conversationId }, () => withCompactionSpan("background", async () => {
21344
- setSpanAttributes({
21345
- "app.compaction.mark_seq": message.markSeq,
21346
- "app.compaction.history_version": message.historyVersion,
21347
- ...options.enqueuedAtMs === void 0 ? void 0 : { "app.compaction.queue_wait_ms": Math.max(0, startedAtMs - options.enqueuedAtMs) }
21340
+ async function swapPreparedCompaction(args) {
21341
+ const pendingMessages = args.pendingMessages ?? [];
21342
+ const sourceMessages = [...args.piMessages, ...pendingMessages.map((entry) => entry.message)];
21343
+ const triggerTokens = getAgentContextCompactionTriggerTokens(args.modelId);
21344
+ const estimatedTokens = estimateHistoryTokens(sourceMessages);
21345
+ if (args.mode !== "blocking" && estimatedTokens <= triggerTokens) return {
21346
+ compacted: false,
21347
+ reason: "below_threshold"
21348
+ };
21349
+ const latest = await loadLatestBackgroundCompaction(args.conversationId);
21350
+ if (!latest) return { compacted: false };
21351
+ return await withCompactionSpan(args.mode, async () => {
21352
+ const { event, historyVersion } = latest;
21353
+ if (event.data.type !== "compaction_prepared" || event.data.outcome !== "ready") {
21354
+ setSpanAttributes({ "app.compaction.outcome": "not_ready" });
21355
+ return { compacted: false };
21356
+ }
21357
+ setSpanAttributes({ "app.compaction.prepared.age_ms": Math.max(0, Date.now() - event.createdAtMs) });
21358
+ if (event.data.historyVersion !== historyVersion) return discard("history_version_changed");
21359
+ return await applyPreparedSummary(args, event.data, {
21360
+ estimatedTokens,
21361
+ historyVersion,
21362
+ triggerTokens
21348
21363
  });
21349
- const outcome = await prepareSummary(message, options.streamFn);
21350
- setSpanAttributes({ "app.compaction.outcome": outcome });
21351
- }));
21364
+ });
21352
21365
  }
21353
- async function prepareSummary(message, streamFn) {
21354
- const eventStore = getConversationEventStore();
21355
- const state = getStateAdapter();
21356
- const events = await eventStore.loadCurrentHistory(message.conversationId);
21357
- const isThisRequest = (event) => (event.data.type === "compaction_requested" || event.data.type === "compaction_prepared") && event.data.historyVersion === message.historyVersion && event.data.markSeq === message.markSeq;
21358
- const request = events.find((event) => isThisRequest(event) && event.data.type === "compaction_requested");
21359
- if (request?.data.type !== "compaction_requested") {
21360
- await state.delete(snapshotKey(message));
21361
- return "stale";
21362
- }
21363
- const requested = request.data;
21364
- if (events.some((event) => isThisRequest(event) && event.data.type === "compaction_prepared")) return "duplicate";
21365
- const writePrepared = async (result) => {
21366
- if (await eventStore.loadCurrentHistoryVersion(message.conversationId) !== message.historyVersion) {
21367
- await state.delete(snapshotKey(message));
21368
- return "stale";
21366
+ async function applyPreparedSummary(args, prepared, budget) {
21367
+ const pendingMessages = args.pendingMessages ?? [];
21368
+ const projection = await loadConversationProjection({ conversationId: args.conversationId });
21369
+ const committedLength = committedPrefixLength(args.piMessages, projection.messages);
21370
+ const firstAfterMark = projection.seqs.slice(0, committedLength).findIndex((seq) => seq > prepared.markSeq);
21371
+ const markIndex = firstAfterMark === -1 ? committedLength : firstAfterMark;
21372
+ const summarized = args.piMessages.slice(0, markIndex);
21373
+ const kept = args.piMessages.slice(markIndex);
21374
+ if (kept[0]?.role === "toolResult") return discard("split_tool_call");
21375
+ const retained = selectRetainedUserMessageEntries(trimTrailingAssistantMessages(summarized)).map((entry) => ({
21376
+ message: entry.message,
21377
+ provenance: projection.provenance[entry.sourceIndex],
21378
+ sourceEventSeq: projection.seqs[entry.sourceIndex]
21379
+ }));
21380
+ const contextMessage = summarizedRuntimeContextMessage(summarized, [...kept, ...pendingMessages.map((entry) => entry.message)]);
21381
+ const { entries: trimmedEntries, trimming } = trimToolResults(kept.map((message, offset) => {
21382
+ const index = markIndex + offset;
21383
+ return index < committedLength ? {
21384
+ message,
21385
+ provenance: projection.provenance[index],
21386
+ sourceEventSeq: projection.seqs[index]
21387
+ } : {
21388
+ message,
21389
+ provenance: contextProvenance
21390
+ };
21391
+ }));
21392
+ const replacement = [
21393
+ ...contextMessage ? [{
21394
+ message: contextMessage,
21395
+ provenance: contextProvenance
21396
+ }] : [],
21397
+ ...retained,
21398
+ {
21399
+ message: userMessage(appendOpenPlan(renderCompactionSummary(prepared.summary), summarized)),
21400
+ provenance: contextProvenance
21401
+ },
21402
+ ...trimmedEntries,
21403
+ ...pendingMessages
21404
+ ];
21405
+ const messages = replacement.map((entry) => entry.message);
21406
+ const replacementTokens = estimateReplacementTokens(messages, args.requestOverheadTokens);
21407
+ const targetTokens = calculateContextCompactionTargetTokens(budget.triggerTokens);
21408
+ setSpanAttributes({
21409
+ "app.compaction.input.estimate": budget.estimatedTokens,
21410
+ "app.compaction.replacement.estimate": replacementTokens,
21411
+ "app.compaction.threshold": budget.triggerTokens,
21412
+ "app.compaction.carried_messages": kept.length,
21413
+ "app.compaction.carried.estimate": estimateReplacementTokens(trimmedEntries.map((entry) => entry.message)),
21414
+ "app.compaction.trimmed_results": trimming.trimmedResults,
21415
+ "app.compaction.trimmed_chars": trimming.removedChars
21416
+ });
21417
+ if (replacementTokens > targetTokens) return discard("over_target");
21418
+ args.signal?.throwIfAborted();
21419
+ if ((await getConversationEventStore().replaceHistory(args.conversationId, {
21420
+ createdAtMs: Date.now(),
21421
+ data: {
21422
+ type: "compaction",
21423
+ modelId: args.modelId,
21424
+ details: {
21425
+ reason: "capacity",
21426
+ estimatedInputTokens: budget.estimatedTokens,
21427
+ replacementInputTokens: replacementTokens,
21428
+ triggerTokens: budget.triggerTokens,
21429
+ inputLimitTokens: getAgentContextInputLimitTokens(args.modelId),
21430
+ inputMessageCount: args.piMessages.length + pendingMessages.length,
21431
+ retainedMessageCount: retained.length + kept.length + pendingMessages.length,
21432
+ summaryChars: prepared.summary.length
21433
+ },
21434
+ summary: prepared.summary,
21435
+ replacementHistory: replacement.map((entry) => ({
21436
+ item: historyItemFromPiMessage(entry.message, entry.provenance),
21437
+ ...entry.sourceEventSeq === void 0 ? void 0 : { sourceEventSeq: entry.sourceEventSeq }
21438
+ }))
21369
21439
  }
21370
- await eventStore.append(message.conversationId, [{
21371
- idempotencyKey: `${backgroundCompactionId(message)}:prepared`,
21372
- createdAtMs: Date.now(),
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;
21440
+ }, { expectedHistoryVersion: budget.historyVersion })).status === "conflict") return {
21441
+ ...discard("conflict"),
21442
+ reason: "history_conflict"
21384
21443
  };
21385
- const remainingMs = request.createdAtMs + REQUEST_TIMEOUT_MS - Date.now();
21386
- if (remainingMs <= 0) return await writePrepared({
21387
- outcome: "failed",
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
21444
+ setSpanAttributes({
21445
+ "app.compaction.outcome": "applied",
21446
+ "app.compaction.summary_chars": prepared.summary.length
21436
21447
  });
21437
- return outcome;
21448
+ return {
21449
+ compacted: true,
21450
+ piMessages: messages
21451
+ };
21438
21452
  }
21439
21453
  // src/chat/agent/exclusive-tools.ts
21440
21454
  /** Tools that must be the only tool call in their assistant message. */
@@ -21899,6 +21913,19 @@ async function executeAgentRunInPrivacyContext(run, conversationPrivacy, runLogC
21899
21913
  tools: agent.state.tools
21900
21914
  } };
21901
21915
  };
21916
+ /**
21917
+ * Request a background summary when the model call that just ended was at
21918
+ * or above the mark. It runs after each model call, so a long Turn gets a
21919
+ * summary before it reaches the compaction threshold.
21920
+ */
21921
+ const requestBackgroundCompactionAfterModelCall = async () => await requestBackgroundCompaction({
21922
+ agent,
21923
+ conversationId,
21924
+ conversationPrivacy,
21925
+ modelId: activeModelId,
21926
+ queue: run.environment?.backgroundCompactionQueue,
21927
+ turnStartedAtMs: replyStartedAtMs
21928
+ });
21902
21929
  let assistantMessageDeliveryError;
21903
21930
  /** Deliver one completed tool-free visible message before the agent advances. */
21904
21931
  const deliverAssistantMessage = async (message) => {
@@ -21992,8 +22019,12 @@ async function executeAgentRunInPrivacyContext(run, conversationPrivacy, runLogC
21992
22019
  const stepUpdate = await withSpan("agent.step.prepare", "agent.step.prepare", {}, async () => {
21993
22020
  const contextUpdate = await repositoryInstructionsContext.applyUpdate(nextTurn.context);
21994
22021
  const pendingMessages = await drainSteeringMessages();
21995
- if (nextTurn.toolResults.length === 0 && pendingMessages.length === 0) return contextUpdate;
22022
+ if (nextTurn.toolResults.length === 0 && pendingMessages.length === 0) {
22023
+ await requestBackgroundCompactionAfterModelCall();
22024
+ return contextUpdate;
22025
+ }
21996
22026
  const capacityUpdate = await applyActiveContextCompaction(contextUpdate ? currentAgentMessages() : nextTurn.context.messages, hookSignal, pendingMessages, true);
22027
+ if (!capacityUpdate) await requestBackgroundCompactionAfterModelCall();
21997
22028
  return capacityUpdate ? {
21998
22029
  ...contextUpdate,
21999
22030
  ...capacityUpdate
@@ -22235,14 +22266,6 @@ async function executeAgentRunInPrivacyContext(run, conversationPrivacy, runLogC
22235
22266
  unsubscribe();
22236
22267
  }
22237
22268
  await recordActiveMcpProviders();
22238
- await requestBackgroundCompaction({
22239
- agent,
22240
- conversationId,
22241
- conversationPrivacy,
22242
- modelId: activeModelId,
22243
- queue: run.environment?.backgroundCompactionQueue,
22244
- turnStartedAtMs: replyStartedAtMs
22245
- });
22246
22269
  return {
22247
22270
  status: "completed",
22248
22271
  result: buildTurnResult({