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