@vybestack/llxprt-code-core 0.11.0 → 0.12.0-nightly.260910.2aac6841e
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/prompt-config/defaults/default-prompts.json +3 -3
- package/dist/src/config/agentClientLifecycle.d.ts +4 -3
- package/dist/src/config/agentClientLifecycle.js +27 -14
- package/dist/src/config/agentClientLifecycle.js.map +1 -1
- package/dist/src/config/config.d.ts +2 -5
- package/dist/src/config/config.js +10 -23
- package/dist/src/config/config.js.map +1 -1
- package/dist/src/config/configBase.d.ts +5 -1
- package/dist/src/config/configBase.js +27 -6
- package/dist/src/config/configBase.js.map +1 -1
- package/dist/src/config/configBaseCore.d.ts +26 -8
- package/dist/src/config/configBaseCore.js +30 -26
- package/dist/src/config/configBaseCore.js.map +1 -1
- package/dist/src/config/configMcpRuntime.d.ts +16 -0
- package/dist/src/config/configMcpRuntime.js +31 -0
- package/dist/src/config/configMcpRuntime.js.map +1 -0
- package/dist/src/config/configMediaDefaults.d.ts +10 -0
- package/dist/src/config/configMediaDefaults.js +17 -0
- package/dist/src/config/configMediaDefaults.js.map +1 -0
- package/dist/src/config/configTestHarness.d.ts +4 -0
- package/dist/src/config/configTypes.d.ts +4 -54
- package/dist/src/config/configTypes.js +6 -82
- package/dist/src/config/configTypes.js.map +1 -1
- package/dist/src/config/index.d.ts +1 -2
- package/dist/src/config/index.js +1 -2
- package/dist/src/config/index.js.map +1 -1
- package/dist/src/config/models.d.ts +0 -4
- package/dist/src/config/models.js +0 -4
- package/dist/src/config/models.js.map +1 -1
- package/dist/src/config/toolRegistryFactory.d.ts +2 -2
- package/dist/src/core/clientContract.d.ts +4 -6
- package/dist/src/core/compression/transcriptPathNotice.d.ts +22 -0
- package/dist/src/core/compression/transcriptPathNotice.js +29 -0
- package/dist/src/core/compression/transcriptPathNotice.js.map +1 -0
- package/dist/src/core/contentGenerator.d.ts +2 -5
- package/dist/src/core/contentGenerator.js +10 -24
- package/dist/src/core/contentGenerator.js.map +1 -1
- package/dist/src/core/logger.d.ts +66 -0
- package/dist/src/core/logger.js +345 -30
- package/dist/src/core/logger.js.map +1 -1
- package/dist/src/core/prompts.d.ts +0 -1
- package/dist/src/core/prompts.js +5 -79
- package/dist/src/core/prompts.js.map +1 -1
- package/dist/src/core/turn.d.ts +3 -3
- package/dist/src/hooks/hookTranslator.js +5 -4
- package/dist/src/hooks/hookTranslator.js.map +1 -1
- package/dist/src/index.d.ts +8 -6
- package/dist/src/index.js +8 -6
- package/dist/src/index.js.map +1 -1
- package/dist/src/llm-types/index.d.ts +1 -1
- package/dist/src/llm-types/modelEnvelope.d.ts +2 -1
- package/dist/src/llm-types/modelEnvelope.js +17 -1
- package/dist/src/llm-types/modelEnvelope.js.map +1 -1
- package/dist/src/models/schema.d.ts +40 -40
- package/dist/src/policy/policies/read-only.toml +0 -5
- package/dist/src/prompt-config/TemplateEngine.js +0 -3
- package/dist/src/prompt-config/TemplateEngine.js.map +1 -1
- package/dist/src/prompt-config/defaults/providers/gemini/core.md +0 -2
- package/dist/src/prompt-config/defaults/providers/gemini/models/gemini-2.5-flash/core.md +0 -2
- package/dist/src/prompt-config/defaults/providers/gemini/models/gemini-2.5-flash/gemini-2-5-flash/core.md +0 -2
- package/dist/src/prompt-config/prompt-loader.d.ts +1 -1
- package/dist/src/prompt-config/prompt-loader.js +4 -4
- package/dist/src/prompt-config/prompt-loader.js.map +1 -1
- package/dist/src/prompt-config/types.d.ts +0 -1
- package/dist/src/recording/CheckpointService.d.ts +4 -0
- package/dist/src/recording/CheckpointService.js +67 -46
- package/dist/src/recording/CheckpointService.js.map +1 -1
- package/dist/src/recording/HistoryMutationService.d.ts +1 -1
- package/dist/src/recording/HistoryMutationService.js +27 -4
- package/dist/src/recording/HistoryMutationService.js.map +1 -1
- package/dist/src/recording/RecordingIntegration.d.ts +36 -2
- package/dist/src/recording/RecordingIntegration.js +224 -7
- package/dist/src/recording/RecordingIntegration.js.map +1 -1
- package/dist/src/recording/ReplayEngine.d.ts +8 -10
- package/dist/src/recording/ReplayEngine.js +161 -95
- package/dist/src/recording/ReplayEngine.js.map +1 -1
- package/dist/src/recording/SessionDiscovery.d.ts +4 -2
- package/dist/src/recording/SessionDiscovery.js +13 -5
- package/dist/src/recording/SessionDiscovery.js.map +1 -1
- package/dist/src/recording/SessionRecordingService.d.ts +23 -3
- package/dist/src/recording/SessionRecordingService.js +209 -51
- package/dist/src/recording/SessionRecordingService.js.map +1 -1
- package/dist/src/recording/SessionTransitionService.d.ts +7 -0
- package/dist/src/recording/SessionTransitionService.js +66 -13
- package/dist/src/recording/SessionTransitionService.js.map +1 -1
- package/dist/src/recording/index.d.ts +1 -0
- package/dist/src/recording/index.js +1 -0
- package/dist/src/recording/index.js.map +1 -1
- package/dist/src/recording/janitor/cleanupTypes.d.ts +3 -0
- package/dist/src/recording/janitor/cleanupTypes.js.map +1 -1
- package/dist/src/recording/janitor/mediaReclamation.d.ts +23 -0
- package/dist/src/recording/janitor/mediaReclamation.js +195 -0
- package/dist/src/recording/janitor/mediaReclamation.js.map +1 -0
- package/dist/src/recording/janitor/sessionJanitor.js +47 -1
- package/dist/src/recording/janitor/sessionJanitor.js.map +1 -1
- package/dist/src/recording/janitor/sessionScanner.d.ts +12 -9
- package/dist/src/recording/janitor/sessionScanner.js +248 -193
- package/dist/src/recording/janitor/sessionScanner.js.map +1 -1
- package/dist/src/recording/replay-test-helpers.d.ts +10 -1
- package/dist/src/recording/replay-test-helpers.js +24 -2
- package/dist/src/recording/replay-test-helpers.js.map +1 -1
- package/dist/src/recording/replayCheckpointMetadata.d.ts +28 -0
- package/dist/src/recording/replayCheckpointMetadata.js +96 -0
- package/dist/src/recording/replayCheckpointMetadata.js.map +1 -0
- package/dist/src/recording/replayErrorFormatting.d.ts +6 -0
- package/dist/src/recording/replayErrorFormatting.js +38 -0
- package/dist/src/recording/replayErrorFormatting.js.map +1 -0
- package/dist/src/recording/resumeSession.d.ts +3 -0
- package/dist/src/recording/resumeSession.js +7 -1
- package/dist/src/recording/resumeSession.js.map +1 -1
- package/dist/src/recording/semanticMediaPurgeReplayValidation.d.ts +14 -0
- package/dist/src/recording/semanticMediaPurgeReplayValidation.js +24 -0
- package/dist/src/recording/semanticMediaPurgeReplayValidation.js.map +1 -0
- package/dist/src/recording/session-media-package-blobs.d.ts +8 -0
- package/dist/src/recording/session-media-package-blobs.js +72 -0
- package/dist/src/recording/session-media-package-blobs.js.map +1 -0
- package/dist/src/recording/session-media-package-import.d.ts +26 -0
- package/dist/src/recording/session-media-package-import.js +124 -0
- package/dist/src/recording/session-media-package-import.js.map +1 -0
- package/dist/src/recording/session-media-package-state.d.ts +19 -0
- package/dist/src/recording/session-media-package-state.js +56 -0
- package/dist/src/recording/session-media-package-state.js.map +1 -0
- package/dist/src/recording/session-media-package-validation.d.ts +59 -0
- package/dist/src/recording/session-media-package-validation.js +286 -0
- package/dist/src/recording/session-media-package-validation.js.map +1 -0
- package/dist/src/recording/session-media-package-writer.d.ts +18 -0
- package/dist/src/recording/session-media-package-writer.js +70 -0
- package/dist/src/recording/session-media-package-writer.js.map +1 -0
- package/dist/src/recording/session-media-package.d.ts +27 -0
- package/dist/src/recording/session-media-package.js +366 -0
- package/dist/src/recording/session-media-package.js.map +1 -0
- package/dist/src/recording/types.d.ts +34 -2
- package/dist/src/recording/types.js.map +1 -1
- package/dist/src/runtime/AgentRuntimeContext.d.ts +22 -5
- package/dist/src/runtime/AgentRuntimeLoader.d.ts +6 -0
- package/dist/src/runtime/AgentRuntimeLoader.js +25 -6
- package/dist/src/runtime/AgentRuntimeLoader.js.map +1 -1
- package/dist/src/runtime/contracts/PromptEstimation.d.ts +1 -0
- package/dist/src/runtime/contracts/PromptEstimation.js.map +1 -1
- package/dist/src/runtime/contracts/RuntimeProvider.d.ts +3 -2
- package/dist/src/runtime/contracts/RuntimeProviderManager.d.ts +0 -2
- package/dist/src/runtime/createAgentRuntimeContext.js +28 -1
- package/dist/src/runtime/createAgentRuntimeContext.js.map +1 -1
- package/dist/src/runtime/providerRuntimeContext.d.ts +12 -0
- package/dist/src/runtime/providerRuntimeContext.js +3 -0
- package/dist/src/runtime/providerRuntimeContext.js.map +1 -1
- package/dist/src/runtime/runtimeAdapters.js +2 -2
- package/dist/src/runtime/runtimeAdapters.js.map +1 -1
- package/dist/src/services/history/ContentConverters.d.ts +11 -7
- package/dist/src/services/history/ContentConverters.js +11 -7
- package/dist/src/services/history/ContentConverters.js.map +1 -1
- package/dist/src/services/history/HistoryService.d.ts +18 -180
- package/dist/src/services/history/HistoryService.js +53 -523
- package/dist/src/services/history/HistoryService.js.map +1 -1
- package/dist/src/services/history/HistoryServiceCore.d.ts +278 -0
- package/dist/src/services/history/HistoryServiceCore.js +727 -0
- package/dist/src/services/history/HistoryServiceCore.js.map +1 -0
- package/dist/src/services/history/IContent.d.ts +118 -16
- package/dist/src/services/history/IContent.js +284 -4
- package/dist/src/services/history/IContent.js.map +1 -1
- package/dist/src/services/history/contentSize.js +22 -2
- package/dist/src/services/history/contentSize.js.map +1 -1
- package/dist/src/services/history/historyChronology.d.ts +7 -0
- package/dist/src/services/history/historyChronology.js +35 -3
- package/dist/src/services/history/historyChronology.js.map +1 -1
- package/dist/src/services/history/historyCloneUtils.d.ts +5 -4
- package/dist/src/services/history/historyCloneUtils.js +23 -16
- package/dist/src/services/history/historyCloneUtils.js.map +1 -1
- package/dist/src/services/history/historyCompressionQueue.d.ts +33 -0
- package/dist/src/services/history/historyCompressionQueue.js +81 -0
- package/dist/src/services/history/historyCompressionQueue.js.map +1 -0
- package/dist/src/services/history/historyEventTypes.d.ts +3 -0
- package/dist/src/services/history/historyMutationFailure.d.ts +15 -0
- package/dist/src/services/history/historyMutationFailure.js +22 -0
- package/dist/src/services/history/historyMutationFailure.js.map +1 -1
- package/dist/src/services/history/historyProviderPipeline.d.ts +1 -1
- package/dist/src/services/history/historyProviderPipeline.js +15 -5
- package/dist/src/services/history/historyProviderPipeline.js.map +1 -1
- package/dist/src/services/history/historyTokenEstimation.js +10 -6
- package/dist/src/services/history/historyTokenEstimation.js.map +1 -1
- package/dist/src/services/history/historyToolNormalization.d.ts +2 -0
- package/dist/src/services/history/historyToolNormalization.js +26 -9
- package/dist/src/services/history/historyToolNormalization.js.map +1 -1
- package/dist/src/services/history/provider-file-binding.d.ts +11 -0
- package/dist/src/services/history/provider-file-binding.js +70 -0
- package/dist/src/services/history/provider-file-binding.js.map +1 -0
- package/dist/src/services/history/semantic-media-purge.d.ts +66 -0
- package/dist/src/services/history/semantic-media-purge.js +404 -0
- package/dist/src/services/history/semantic-media-purge.js.map +1 -0
- package/dist/src/storage/SessionPersistenceService.d.ts +53 -2
- package/dist/src/storage/SessionPersistenceService.js +435 -23
- package/dist/src/storage/SessionPersistenceService.js.map +1 -1
- package/dist/src/storage/history-media-ownership.d.ts +38 -0
- package/dist/src/storage/history-media-ownership.js +136 -0
- package/dist/src/storage/history-media-ownership.js.map +1 -0
- package/dist/src/storage/local-media-store-child.d.ts +6 -0
- package/dist/src/storage/local-media-store-child.js +140 -0
- package/dist/src/storage/local-media-store-child.js.map +1 -0
- package/dist/src/storage/local-media-store-files.d.ts +44 -0
- package/dist/src/storage/local-media-store-files.js +460 -0
- package/dist/src/storage/local-media-store-files.js.map +1 -0
- package/dist/src/storage/local-media-store-lock-recovery.d.ts +15 -0
- package/dist/src/storage/local-media-store-lock-recovery.js +112 -0
- package/dist/src/storage/local-media-store-lock-recovery.js.map +1 -0
- package/dist/src/storage/local-media-store-persistence.d.ts +48 -0
- package/dist/src/storage/local-media-store-persistence.js +443 -0
- package/dist/src/storage/local-media-store-persistence.js.map +1 -0
- package/dist/src/storage/local-media-store-quota.d.ts +6 -0
- package/dist/src/storage/local-media-store-quota.js +66 -0
- package/dist/src/storage/local-media-store-quota.js.map +1 -0
- package/dist/src/storage/local-media-store-reservations.d.ts +55 -0
- package/dist/src/storage/local-media-store-reservations.js +377 -0
- package/dist/src/storage/local-media-store-reservations.js.map +1 -0
- package/dist/src/storage/local-media-store-types.d.ts +110 -0
- package/dist/src/storage/local-media-store-types.js +35 -0
- package/dist/src/storage/local-media-store-types.js.map +1 -0
- package/dist/src/storage/local-media-store-validation.d.ts +34 -0
- package/dist/src/storage/local-media-store-validation.js +449 -0
- package/dist/src/storage/local-media-store-validation.js.map +1 -0
- package/dist/src/storage/local-media-store.d.ts +47 -0
- package/dist/src/storage/local-media-store.js +353 -0
- package/dist/src/storage/local-media-store.js.map +1 -0
- package/dist/src/storage/media-admission-service.d.ts +49 -0
- package/dist/src/storage/media-admission-service.js +333 -0
- package/dist/src/storage/media-admission-service.js.map +1 -0
- package/dist/src/storage/media-lifecycle-metrics.d.ts +75 -0
- package/dist/src/storage/media-lifecycle-metrics.js +105 -0
- package/dist/src/storage/media-lifecycle-metrics.js.map +1 -0
- package/dist/src/storage/media-reference-lifecycle.d.ts +16 -0
- package/dist/src/storage/media-reference-lifecycle.js +84 -0
- package/dist/src/storage/media-reference-lifecycle.js.map +1 -0
- package/dist/src/storage/request-media-resolver.d.ts +67 -0
- package/dist/src/storage/request-media-resolver.js +325 -0
- package/dist/src/storage/request-media-resolver.js.map +1 -0
- package/dist/src/storage/session-media-service-factories.d.ts +19 -0
- package/dist/src/storage/session-media-service-factories.js +34 -0
- package/dist/src/storage/session-media-service-factories.js.map +1 -0
- package/dist/src/storage/session-persistence-helpers.d.ts +10 -0
- package/dist/src/storage/session-persistence-helpers.js +46 -0
- package/dist/src/storage/session-persistence-helpers.js.map +1 -0
- package/dist/src/test-utils/config.d.ts +2 -0
- package/dist/src/test-utils/config.js +5 -5
- package/dist/src/test-utils/config.js.map +1 -1
- package/dist/src/test-utils/runtime.d.ts +2 -0
- package/dist/src/test-utils/runtime.js +1 -2
- package/dist/src/test-utils/runtime.js.map +1 -1
- package/dist/src/tools-adapters/CoreShellToolHostAdapter.js +1 -9
- package/dist/src/tools-adapters/CoreShellToolHostAdapter.js.map +1 -1
- package/dist/src/tools-adapters/CoreSkillServiceAdapter.d.ts +0 -2
- package/dist/src/tools-adapters/CoreSkillServiceAdapter.js +0 -17
- package/dist/src/tools-adapters/CoreSkillServiceAdapter.js.map +1 -1
- package/dist/src/tools-adapters/CoreToolHostAdapter.d.ts +0 -21
- package/dist/src/tools-adapters/CoreToolHostAdapter.js +0 -8
- package/dist/src/tools-adapters/CoreToolHostAdapter.js.map +1 -1
- package/dist/src/utils/environmentContext.d.ts +8 -9
- package/dist/src/utils/environmentContext.js +11 -22
- package/dist/src/utils/environmentContext.js.map +1 -1
- package/dist/src/utils/errorParsing.d.ts +1 -2
- package/dist/src/utils/errorParsing.js +22 -41
- package/dist/src/utils/errorParsing.js.map +1 -1
- package/dist/src/utils/generateContentResponseUtilities.js +12 -0
- package/dist/src/utils/generateContentResponseUtilities.js.map +1 -1
- package/dist/src/utils/summarizer.d.ts +1 -2
- package/dist/src/utils/summarizer.js +6 -5
- package/dist/src/utils/summarizer.js.map +1 -1
- package/dist/src/utils/tool-utils.js +7 -1
- package/dist/src/utils/tool-utils.js.map +1 -1
- package/index.ts +0 -4
- package/package.json +38 -30
- package/src/config/agentClientLifecycle.ts +53 -22
- package/src/config/config.ts +11 -26
- package/src/config/configBase.ts +46 -7
- package/src/config/configBaseCore.ts +38 -36
- package/src/config/configMcpRuntime.ts +46 -0
- package/src/config/configMediaDefaults.ts +19 -0
- package/src/config/configTypes.ts +13 -53
- package/src/config/index.ts +1 -4
- package/src/config/models.ts +0 -6
- package/src/config/toolRegistryFactory.ts +2 -2
- package/src/core/clientContract.ts +4 -6
- package/src/core/compression/transcriptPathNotice.ts +31 -0
- package/src/core/contentGenerator.ts +15 -39
- package/src/core/logger.ts +370 -39
- package/src/core/prompts.ts +4 -114
- package/src/core/turn.ts +3 -3
- package/src/hooks/hookTranslator.ts +6 -4
- package/src/index.ts +7 -7
- package/src/llm-types/index.ts +5 -0
- package/src/llm-types/modelEnvelope.ts +26 -2
- package/src/policy/policies/read-only.toml +0 -5
- package/src/prompt-config/TemplateEngine.ts +0 -3
- package/src/prompt-config/defaults/providers/gemini/core.md +0 -2
- package/src/prompt-config/defaults/providers/gemini/models/gemini-2.5-flash/core.md +0 -2
- package/src/prompt-config/defaults/providers/gemini/models/gemini-2.5-flash/gemini-2-5-flash/core.md +0 -2
- package/src/prompt-config/prompt-loader.ts +7 -8
- package/src/prompt-config/types.ts +0 -1
- package/src/recording/CheckpointService.ts +110 -45
- package/src/recording/HistoryMutationService.ts +28 -3
- package/src/recording/RecordingIntegration.ts +258 -11
- package/src/recording/ReplayEngine.ts +220 -110
- package/src/recording/SessionDiscovery.ts +30 -4
- package/src/recording/SessionRecordingService.ts +253 -55
- package/src/recording/SessionTransitionService.ts +75 -12
- package/src/recording/index.ts +7 -0
- package/src/recording/janitor/cleanupTypes.ts +4 -0
- package/src/recording/janitor/mediaReclamation.ts +295 -0
- package/src/recording/janitor/sessionJanitor.ts +54 -1
- package/src/recording/janitor/sessionScanner.ts +319 -227
- package/src/recording/replay-test-helpers.ts +33 -2
- package/src/recording/replayCheckpointMetadata.ts +115 -0
- package/src/recording/replayErrorFormatting.ts +43 -0
- package/src/recording/resumeSession.ts +10 -0
- package/src/recording/semanticMediaPurgeReplayValidation.ts +35 -0
- package/src/recording/session-media-package-blobs.ts +116 -0
- package/src/recording/session-media-package-import.ts +189 -0
- package/src/recording/session-media-package-state.ts +120 -0
- package/src/recording/session-media-package-validation.ts +400 -0
- package/src/recording/session-media-package-writer.ts +117 -0
- package/src/recording/session-media-package.ts +692 -0
- package/src/recording/types.ts +37 -2
- package/src/runtime/AgentRuntimeContext.ts +28 -5
- package/src/runtime/AgentRuntimeLoader.ts +32 -7
- package/src/runtime/contracts/PromptEstimation.ts +1 -0
- package/src/runtime/contracts/RuntimeProvider.ts +3 -8
- package/src/runtime/contracts/RuntimeProviderManager.ts +0 -2
- package/src/runtime/createAgentRuntimeContext.ts +43 -1
- package/src/runtime/providerRuntimeContext.ts +22 -0
- package/src/runtime/runtimeAdapters.ts +2 -2
- package/src/services/history/ContentConverters.ts +11 -7
- package/src/services/history/HistoryService.ts +71 -696
- package/src/services/history/HistoryServiceCore.ts +1055 -0
- package/src/services/history/IContent.ts +460 -20
- package/src/services/history/contentSize.ts +22 -2
- package/src/services/history/historyChronology.ts +53 -3
- package/src/services/history/historyCloneUtils.ts +26 -22
- package/src/services/history/historyCompressionQueue.ts +102 -0
- package/src/services/history/historyEventTypes.ts +9 -0
- package/src/services/history/historyMutationFailure.ts +33 -0
- package/src/services/history/historyProviderPipeline.ts +19 -5
- package/src/services/history/historyTokenEstimation.ts +9 -5
- package/src/services/history/historyToolNormalization.ts +43 -11
- package/src/services/history/provider-file-binding.ts +115 -0
- package/src/services/history/semantic-media-purge.ts +593 -0
- package/src/storage/SessionPersistenceService.ts +667 -30
- package/src/storage/history-media-ownership.ts +185 -0
- package/src/storage/local-media-store-child.ts +163 -0
- package/src/storage/local-media-store-files.ts +643 -0
- package/src/storage/local-media-store-lock-recovery.ts +159 -0
- package/src/storage/local-media-store-persistence.ts +737 -0
- package/src/storage/local-media-store-quota.ts +111 -0
- package/src/storage/local-media-store-reservations.ts +485 -0
- package/src/storage/local-media-store-types.ts +161 -0
- package/src/storage/local-media-store-validation.ts +643 -0
- package/src/storage/local-media-store.ts +696 -0
- package/src/storage/media-admission-service.ts +512 -0
- package/src/storage/media-lifecycle-metrics.ts +228 -0
- package/src/storage/media-reference-lifecycle.ts +164 -0
- package/src/storage/request-media-resolver.ts +491 -0
- package/src/storage/session-media-service-factories.ts +48 -0
- package/src/storage/session-persistence-helpers.ts +85 -0
- package/src/test-utils/config.ts +7 -5
- package/src/test-utils/runtime.ts +3 -2
- package/src/tools-adapters/CoreShellToolHostAdapter.ts +1 -11
- package/src/tools-adapters/CoreSkillServiceAdapter.ts +0 -23
- package/src/tools-adapters/CoreToolHostAdapter.ts +0 -36
- package/src/utils/environmentContext.ts +11 -30
- package/src/utils/errorParsing.ts +19 -69
- package/src/utils/generateContentResponseUtilities.ts +28 -1
- package/src/utils/summarizer.ts +8 -10
- package/src/utils/tool-utils.ts +7 -1
- package/dist/src/code_assist/codeAssist.d.ts +0 -19
- package/dist/src/code_assist/codeAssist.js +0 -41
- package/dist/src/code_assist/codeAssist.js.map +0 -1
- package/dist/src/code_assist/contentGeneratorAdapters.d.ts +0 -49
- package/dist/src/code_assist/contentGeneratorAdapters.js +0 -197
- package/dist/src/code_assist/contentGeneratorAdapters.js.map +0 -1
- package/dist/src/code_assist/converter.d.ts +0 -74
- package/dist/src/code_assist/converter.js +0 -158
- package/dist/src/code_assist/converter.js.map +0 -1
- package/dist/src/code_assist/googleGenAIWrapper.d.ts +0 -27
- package/dist/src/code_assist/googleGenAIWrapper.js +0 -46
- package/dist/src/code_assist/googleGenAIWrapper.js.map +0 -1
- package/dist/src/code_assist/oauth-credential-storage.d.ts +0 -30
- package/dist/src/code_assist/oauth-credential-storage.js +0 -135
- package/dist/src/code_assist/oauth-credential-storage.js.map +0 -1
- package/dist/src/code_assist/server.d.ts +0 -44
- package/dist/src/code_assist/server.js +0 -154
- package/dist/src/code_assist/server.js.map +0 -1
- package/dist/src/code_assist/setup.d.ts +0 -20
- package/dist/src/code_assist/setup.js +0 -126
- package/dist/src/code_assist/setup.js.map +0 -1
- package/dist/src/code_assist/types.d.ts +0 -161
- package/dist/src/code_assist/types.js +0 -46
- package/dist/src/code_assist/types.js.map +0 -1
- package/dist/src/utils/getFolderStructure.d.ts +0 -31
- package/dist/src/utils/getFolderStructure.js +0 -240
- package/dist/src/utils/getFolderStructure.js.map +0 -1
- package/dist/src/utils/installationManager.d.ts +0 -16
- package/dist/src/utils/installationManager.js +0 -51
- package/dist/src/utils/installationManager.js.map +0 -1
- package/dist/src/utils/llm-edit-fixer.d.ts +0 -25
- package/dist/src/utils/llm-edit-fixer.js +0 -120
- package/dist/src/utils/llm-edit-fixer.js.map +0 -1
- package/src/code_assist/codeAssist.ts +0 -59
- package/src/code_assist/contentGeneratorAdapters.ts +0 -275
- package/src/code_assist/converter.ts +0 -288
- package/src/code_assist/googleGenAIWrapper.ts +0 -90
- package/src/code_assist/oauth-credential-storage.ts +0 -171
- package/src/code_assist/server.ts +0 -263
- package/src/code_assist/setup.ts +0 -189
- package/src/code_assist/types.ts +0 -201
- package/src/utils/getFolderStructure.ts +0 -382
- package/src/utils/installationManager.ts +0 -59
- package/src/utils/llm-edit-fixer.ts +0 -157
|
@@ -0,0 +1,727 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright 2026 Vybestack LLC
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
import { finalizeMutationEffects } from './historyMutationFailure.js';
|
|
17
|
+
import { CompressionOperationQueue } from './historyCompressionQueue.js';
|
|
18
|
+
import { EventEmitter } from 'events';
|
|
19
|
+
import { DebugLogger } from '../../debug/index.js';
|
|
20
|
+
import { randomUUID } from 'crypto';
|
|
21
|
+
import { canonicalizeToolCallId } from './canonicalToolIds.js';
|
|
22
|
+
import { estimateContentTokens as estimateContentTokensImpl, estimateTokensForContents as estimateTokensForContentsImpl, simpleTokenEstimateForText, } from './historyTokenEstimation.js';
|
|
23
|
+
import { validateDensityResult, applyDensityMutations, } from './densityValidation.js';
|
|
24
|
+
import { logContentAdded, logQueuedDuringCompression, } from './curationDebugLogger.js';
|
|
25
|
+
import { getTokenizerForModel } from './historyTokenizerAdapter.js';
|
|
26
|
+
import { ChronologyStamper, } from './historyChronology.js';
|
|
27
|
+
import { combineMutationFailures, } from './historyMutationFailure.js';
|
|
28
|
+
/**
|
|
29
|
+
* Service for managing conversation history in a provider-agnostic way.
|
|
30
|
+
* All history is stored as IContent. Providers are responsible for converting
|
|
31
|
+
* to/from their own formats.
|
|
32
|
+
*/
|
|
33
|
+
export class HistoryServiceCore extends EventEmitter {
|
|
34
|
+
history = [];
|
|
35
|
+
totalTokens = 0;
|
|
36
|
+
baseTokenOffset = 0;
|
|
37
|
+
tokenizerCache = new Map();
|
|
38
|
+
tokenizerLock = Promise.resolve();
|
|
39
|
+
pendingTokenizerFailure;
|
|
40
|
+
syncGeneration = 0;
|
|
41
|
+
historyMutationInProgress = false;
|
|
42
|
+
historyMutationQueue = [];
|
|
43
|
+
batchParticipants = new Set();
|
|
44
|
+
mediaOwner;
|
|
45
|
+
ownershipSettlement = Promise.resolve();
|
|
46
|
+
ownershipFailure;
|
|
47
|
+
logger = new DebugLogger('llxprt:history:service');
|
|
48
|
+
chronology = new ChronologyStamper();
|
|
49
|
+
/**
|
|
50
|
+
* Monotonic cache anchor: the highest chronology `seq` that must remain in
|
|
51
|
+
* the preserved head across every subsequent middle-out compression. Once a
|
|
52
|
+
* head entry is preserved by one compression, no later compression may drop
|
|
53
|
+
* it, which keeps the provider-visible prefix byte-identical (#3070).
|
|
54
|
+
*
|
|
55
|
+
* Survives atomic compression replacement; reset explicitly by session-reset
|
|
56
|
+
* and history-restore paths.
|
|
57
|
+
*/
|
|
58
|
+
cacheAnchorSeq = 0;
|
|
59
|
+
/**
|
|
60
|
+
* @plan:PLAN-20260603-ISSUE1584.P05
|
|
61
|
+
* @requirement:REQ-DEP-001
|
|
62
|
+
* @pseudocode component-boundaries.md C-CB-01, lines 10-15
|
|
63
|
+
*
|
|
64
|
+
* Injected tokenizer factory. When provided, HistoryService uses the factory
|
|
65
|
+
* to obtain tokenizers instead of constructing provider tokenizers directly.
|
|
66
|
+
* This eliminates the core→providers import dependency on the injection path.
|
|
67
|
+
*/
|
|
68
|
+
tokenizerFactory;
|
|
69
|
+
activeTokenizationModel = 'gpt-4.1';
|
|
70
|
+
activeTokenizationProvider;
|
|
71
|
+
isCompressing = false;
|
|
72
|
+
/**
|
|
73
|
+
* True while a rebuild scope is running, so operations queued during the
|
|
74
|
+
* rebuild are tagged 'rebuild' and replayed before streaming work (#3338,
|
|
75
|
+
* #3264). Held here rather than in the subclass because this class owns the
|
|
76
|
+
* queue the tag is applied to.
|
|
77
|
+
*/
|
|
78
|
+
inRebuildScope = false;
|
|
79
|
+
pendingOperations = new CompressionOperationQueue((pendingCount) => this.logger.error('History compression queue exceeded its high-water mark; the compression lock is being held for an unexpectedly long time. No operations are dropped.', { pendingCount }));
|
|
80
|
+
/**
|
|
81
|
+
* @plan:PLAN-20260603-ISSUE1584.P05
|
|
82
|
+
* @requirement:REQ-DEP-001
|
|
83
|
+
* @pseudocode component-boundaries.md C-CB-01, lines 10-15
|
|
84
|
+
*
|
|
85
|
+
* Set the tokenizer factory for injection-based tokenizer resolution.
|
|
86
|
+
* When set, getTokenizerForModel will prefer the factory over
|
|
87
|
+
* constructing provider tokenizers directly.
|
|
88
|
+
*/
|
|
89
|
+
setTokenizerFactory(factory) {
|
|
90
|
+
this.tokenizerFactory = factory;
|
|
91
|
+
this.tokenizerCache.clear();
|
|
92
|
+
}
|
|
93
|
+
setActiveTokenizationTarget(modelName, activeProvider) {
|
|
94
|
+
this.activeTokenizationModel = modelName;
|
|
95
|
+
this.activeTokenizationProvider = activeProvider;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Get or create tokenizer for a specific model.
|
|
99
|
+
*
|
|
100
|
+
* @plan:PLAN-20260603-ISSUE1584.P05
|
|
101
|
+
* @requirement:REQ-DEP-001
|
|
102
|
+
* @pseudocode component-boundaries.md C-CB-01, lines 10-15
|
|
103
|
+
*
|
|
104
|
+
* When a RuntimeTokenizerFactory is injected, it is preferred over
|
|
105
|
+
* direct provider tokenizer construction. This removes the core→providers
|
|
106
|
+
* dependency when using the injection path.
|
|
107
|
+
*/
|
|
108
|
+
getTokenizerForModel(modelName, activeProvider) {
|
|
109
|
+
return getTokenizerForModel(activeProvider, modelName, {
|
|
110
|
+
tokenizerCache: this.tokenizerCache,
|
|
111
|
+
tokenizerFactory: this.tokenizerFactory,
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Generate a new canonical history tool ID.
|
|
116
|
+
* Format: hist_tool_<hash>
|
|
117
|
+
*/
|
|
118
|
+
generateHistoryId(turnKey, callIndex, providerName, rawId, toolName) {
|
|
119
|
+
return canonicalizeToolCallId({
|
|
120
|
+
providerName,
|
|
121
|
+
rawId,
|
|
122
|
+
toolName,
|
|
123
|
+
turnKey,
|
|
124
|
+
callIndex,
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Get a callback suitable for passing into converters
|
|
129
|
+
* which will generate normalized history IDs on demand.
|
|
130
|
+
*/
|
|
131
|
+
getIdGeneratorCallback(turnKey) {
|
|
132
|
+
let callIndex = 0;
|
|
133
|
+
const stableTurnKey = turnKey ?? this.generateTurnKey();
|
|
134
|
+
return () => this.generateHistoryId(stableTurnKey, callIndex++);
|
|
135
|
+
}
|
|
136
|
+
generateTurnKey() {
|
|
137
|
+
return `turn_${randomUUID()}`;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Get the current total token count including base offset (system prompt).
|
|
141
|
+
*
|
|
142
|
+
* This value is used for compression threshold calculations and should always
|
|
143
|
+
* reflect the total context size that will be sent to the API.
|
|
144
|
+
*
|
|
145
|
+
* @returns baseTokenOffset + totalTokens (history tokens)
|
|
146
|
+
*/
|
|
147
|
+
getTotalTokens() {
|
|
148
|
+
return this.baseTokenOffset + this.totalTokens;
|
|
149
|
+
}
|
|
150
|
+
getBaseTokenOffset() {
|
|
151
|
+
return this.baseTokenOffset;
|
|
152
|
+
}
|
|
153
|
+
async estimateTokensForText(text, modelName = this.activeTokenizationModel) {
|
|
154
|
+
if (!text) {
|
|
155
|
+
return 0;
|
|
156
|
+
}
|
|
157
|
+
const tokenizer = this.getTokenizerForModel(modelName, this.activeTokenizationProvider);
|
|
158
|
+
try {
|
|
159
|
+
return await tokenizer.countTokens(text);
|
|
160
|
+
}
|
|
161
|
+
catch (error) {
|
|
162
|
+
if (tokenizer.fallbackPolicy === 'deny') {
|
|
163
|
+
throw error;
|
|
164
|
+
}
|
|
165
|
+
this.logger.debug('Error counting tokens for raw text, using fallback:', error);
|
|
166
|
+
return simpleTokenEstimateForText(text);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Set a base offset that is always included in the total token count.
|
|
171
|
+
* Useful for accounting for system prompts or other fixed overhead.
|
|
172
|
+
*
|
|
173
|
+
* The system prompt token count should be set once at chat start using this method.
|
|
174
|
+
* This offset is included in getTotalTokens() to ensure compression threshold
|
|
175
|
+
* calculations account for the full context size (system prompt + history).
|
|
176
|
+
*
|
|
177
|
+
* NOTE: The system prompt itself is NEVER compressed - only conversation history
|
|
178
|
+
* returned by getCurated() is subject to compression.
|
|
179
|
+
*
|
|
180
|
+
* @param offset - Number of tokens in the system prompt or fixed overhead
|
|
181
|
+
*/
|
|
182
|
+
setBaseTokenOffset(offset) {
|
|
183
|
+
const normalized = Math.max(0, Math.floor(offset));
|
|
184
|
+
const delta = normalized - this.baseTokenOffset;
|
|
185
|
+
this.baseTokenOffset = normalized;
|
|
186
|
+
if (delta !== 0) {
|
|
187
|
+
this.emit('tokensUpdated', {
|
|
188
|
+
totalTokens: this.getTotalTokens(),
|
|
189
|
+
addedTokens: delta,
|
|
190
|
+
contentId: null,
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Sync the total token count to match actual prompt tokens from a provider.
|
|
196
|
+
* This adjusts the baseTokenOffset so estimates align with the real count.
|
|
197
|
+
*/
|
|
198
|
+
syncTotalTokens(actualTotal) {
|
|
199
|
+
if (!Number.isFinite(actualTotal)) {
|
|
200
|
+
this.logger.debug('Skipping syncTotalTokens for non-finite value', {
|
|
201
|
+
actualTotal,
|
|
202
|
+
});
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
const normalized = Math.max(0, Math.floor(actualTotal));
|
|
206
|
+
const generation = this.syncGeneration;
|
|
207
|
+
this.observeTokenizerOperation(this.runSerializedTokenOperation(() => {
|
|
208
|
+
if (generation !== this.syncGeneration)
|
|
209
|
+
return;
|
|
210
|
+
const currentTotal = this.getTotalTokens();
|
|
211
|
+
const drift = normalized - currentTotal;
|
|
212
|
+
if (drift === 0) {
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
this.baseTokenOffset += drift;
|
|
216
|
+
this.emit('tokensUpdated', {
|
|
217
|
+
totalTokens: this.getTotalTokens(),
|
|
218
|
+
addedTokens: drift,
|
|
219
|
+
contentId: null,
|
|
220
|
+
});
|
|
221
|
+
}));
|
|
222
|
+
}
|
|
223
|
+
runSerializedTokenOperation(operation) {
|
|
224
|
+
const result = this.tokenizerLock.then(operation);
|
|
225
|
+
this.tokenizerLock = result.then(() => undefined, () => undefined);
|
|
226
|
+
return result;
|
|
227
|
+
}
|
|
228
|
+
observeTokenizerOperation(operation) {
|
|
229
|
+
void operation.catch((error) => {
|
|
230
|
+
this.pendingTokenizerFailure ??= { error };
|
|
231
|
+
this.logger.error('Asynchronous token accounting failed', error);
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
invalidatePendingSyncs() {
|
|
235
|
+
this.syncGeneration++;
|
|
236
|
+
}
|
|
237
|
+
runSynchronousHistoryMutation(execute) {
|
|
238
|
+
if (this.historyMutationInProgress) {
|
|
239
|
+
this.historyMutationQueue.push({ kind: 'synchronous', execute });
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
this.historyMutationInProgress = true;
|
|
243
|
+
let failure = { failed: false };
|
|
244
|
+
try {
|
|
245
|
+
execute();
|
|
246
|
+
}
|
|
247
|
+
catch (error) {
|
|
248
|
+
failure = { failed: true, error };
|
|
249
|
+
}
|
|
250
|
+
const queuedFailure = this.drainSynchronousHistoryMutations();
|
|
251
|
+
this.historyMutationInProgress = false;
|
|
252
|
+
this.processHistoryMutationQueue();
|
|
253
|
+
const combinedFailure = combineMutationFailures(failure, queuedFailure);
|
|
254
|
+
if (combinedFailure.failed)
|
|
255
|
+
throw combinedFailure.error;
|
|
256
|
+
}
|
|
257
|
+
drainSynchronousHistoryMutations() {
|
|
258
|
+
let failure = { failed: false };
|
|
259
|
+
while (this.historyMutationQueue[0]?.kind === 'synchronous') {
|
|
260
|
+
const mutation = this.historyMutationQueue.shift();
|
|
261
|
+
if (mutation?.kind !== 'synchronous')
|
|
262
|
+
break;
|
|
263
|
+
try {
|
|
264
|
+
mutation.execute();
|
|
265
|
+
}
|
|
266
|
+
catch (error) {
|
|
267
|
+
failure = combineMutationFailures(failure, { failed: true, error });
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
return failure;
|
|
271
|
+
}
|
|
272
|
+
enqueueAsynchronousHistoryMutation(execute) {
|
|
273
|
+
return new Promise((resolve, reject) => {
|
|
274
|
+
this.historyMutationQueue.push({
|
|
275
|
+
kind: 'asynchronous',
|
|
276
|
+
execute,
|
|
277
|
+
resolve,
|
|
278
|
+
reject,
|
|
279
|
+
});
|
|
280
|
+
this.processHistoryMutationQueue();
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
processHistoryMutationQueue() {
|
|
284
|
+
if (this.historyMutationInProgress)
|
|
285
|
+
return;
|
|
286
|
+
const mutation = this.historyMutationQueue.shift();
|
|
287
|
+
if (mutation === undefined)
|
|
288
|
+
return;
|
|
289
|
+
if (mutation.kind === 'synchronous') {
|
|
290
|
+
this.runSynchronousHistoryMutation(mutation.execute);
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
this.historyMutationInProgress = true;
|
|
294
|
+
void mutation.execute().then(() => this.completeAsynchronousHistoryMutation(mutation, { failed: false }), (error) => this.completeAsynchronousHistoryMutation(mutation, {
|
|
295
|
+
failed: true,
|
|
296
|
+
error,
|
|
297
|
+
}));
|
|
298
|
+
}
|
|
299
|
+
completeAsynchronousHistoryMutation(mutation, failure) {
|
|
300
|
+
const queuedFailure = this.drainSynchronousHistoryMutations();
|
|
301
|
+
this.historyMutationInProgress = false;
|
|
302
|
+
const result = combineMutationFailures(failure, queuedFailure);
|
|
303
|
+
if (result.failed)
|
|
304
|
+
mutation.reject(result.error);
|
|
305
|
+
else
|
|
306
|
+
mutation.resolve();
|
|
307
|
+
this.processHistoryMutationQueue();
|
|
308
|
+
}
|
|
309
|
+
resetTokenAccounting() {
|
|
310
|
+
this.invalidatePendingSyncs();
|
|
311
|
+
this.baseTokenOffset = 0;
|
|
312
|
+
this.emit('tokensUpdated', {
|
|
313
|
+
totalTokens: this.getTotalTokens(),
|
|
314
|
+
addedTokens: 0,
|
|
315
|
+
contentId: null,
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Add content to the history.
|
|
320
|
+
* Zero-block turns are rejected at insertion (issue #2410): they corrupt
|
|
321
|
+
* provider-facing history (z.ai rejects empty human turns with HTTP 400
|
|
322
|
+
* error 1213). All other content with a valid speaker is accepted.
|
|
323
|
+
*/
|
|
324
|
+
add(content, modelName) {
|
|
325
|
+
if (this.isCompressing) {
|
|
326
|
+
logQueuedDuringCompression(this.logger, content);
|
|
327
|
+
this.queueCompressionOperation(() => {
|
|
328
|
+
this.runSynchronousHistoryMutation(() => {
|
|
329
|
+
this.addInternal(content, modelName);
|
|
330
|
+
});
|
|
331
|
+
});
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
this.runSynchronousHistoryMutation(() => {
|
|
335
|
+
this.addInternal(content, modelName);
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* Queues an operation that arrived while compression held the history lock.
|
|
340
|
+
*
|
|
341
|
+
* Operations are never dropped and never rejected: `add()` is on the
|
|
342
|
+
* streaming path, so failing here would lose conversation content and could
|
|
343
|
+
* break a turn. `startCompression`/`endCompression` are balanced in a
|
|
344
|
+
* `finally` by the only caller (`CompressionHandler.performCompression`), so
|
|
345
|
+
* the lock is always released and the queue is bounded by how long a single
|
|
346
|
+
* compression takes. Crossing the high-water mark is reported once so an
|
|
347
|
+
* unbalanced lock would be diagnosable rather than silent (issue #2852).
|
|
348
|
+
*/
|
|
349
|
+
queueCompressionOperation(operation) {
|
|
350
|
+
this.pendingOperations.enqueue(operation, this.inRebuildScope ? 'rebuild' : 'streaming');
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* Runs a rebuild synchronously so operations queued inside it are replayed
|
|
354
|
+
* before streaming work.
|
|
355
|
+
*
|
|
356
|
+
* The callback returns `undefined` rather than `void` on purpose. An async
|
|
357
|
+
* function returns `Promise<void>`, which is not assignable to `undefined`,
|
|
358
|
+
* so the synchronous contract fails at compile time; an `await` inside the
|
|
359
|
+
* scope would exit it and mis-tag the remaining work as streaming (#3338).
|
|
360
|
+
*/
|
|
361
|
+
rebuildWith(callback) {
|
|
362
|
+
const previousScope = this.inRebuildScope;
|
|
363
|
+
this.inRebuildScope = true;
|
|
364
|
+
try {
|
|
365
|
+
callback();
|
|
366
|
+
}
|
|
367
|
+
finally {
|
|
368
|
+
this.inRebuildScope = previousScope;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
addInternal(content, modelName) {
|
|
372
|
+
// Reject zero-block turns: a Content with no blocks corrupts provider-
|
|
373
|
+
// facing history (notably z.ai rejects empty human turns with HTTP 400
|
|
374
|
+
// error 1213, issue #2410). This is a systemic safety net — earlier
|
|
375
|
+
// layers should prevent these from reaching history, but we enforce the
|
|
376
|
+
// invariant here as the last line of defense.
|
|
377
|
+
const hasValidSpeaker = ['human', 'ai', 'tool'].includes(content.speaker);
|
|
378
|
+
const hasBlocks = Array.isArray(content.blocks) && content.blocks.length > 0;
|
|
379
|
+
const accepted = hasValidSpeaker && hasBlocks;
|
|
380
|
+
if (accepted) {
|
|
381
|
+
// Stamp chronology only once the content is known to be accepted, so a
|
|
382
|
+
// rejected turn never consumes a sequence number (#1721).
|
|
383
|
+
this.chronology.stamp(content);
|
|
384
|
+
}
|
|
385
|
+
logContentAdded(this.logger, content, modelName);
|
|
386
|
+
if (!accepted) {
|
|
387
|
+
this.logger.debug(hasValidSpeaker
|
|
388
|
+
? 'Content rejected - zero blocks (issue #2410):'
|
|
389
|
+
: 'Content rejected - invalid speaker:', content.speaker);
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
const generation = this.syncGeneration;
|
|
393
|
+
this.history.push(content);
|
|
394
|
+
try {
|
|
395
|
+
this.emit('contentAdded', content);
|
|
396
|
+
this.mediaOwner?.adopt([content]);
|
|
397
|
+
}
|
|
398
|
+
catch (error) {
|
|
399
|
+
// Roll back the insertion. The consumed chronology sequence number is
|
|
400
|
+
// intentionally NOT reclaimed: sequence numbers are never reused, and
|
|
401
|
+
// the resulting gap truthfully records that an item was removed.
|
|
402
|
+
this.history.pop();
|
|
403
|
+
throw error;
|
|
404
|
+
}
|
|
405
|
+
// Update token count asynchronously but atomically
|
|
406
|
+
this.observeTokenizerOperation(this.updateTokenCount(content, modelName, generation));
|
|
407
|
+
}
|
|
408
|
+
/**
|
|
409
|
+
* Atomically update token count for new content
|
|
410
|
+
*/
|
|
411
|
+
updateTokenCount(content, modelName, generation = this.syncGeneration) {
|
|
412
|
+
return this.runSerializedTokenOperation(async () => {
|
|
413
|
+
// Always derive token counts from the stored content to avoid double counting
|
|
414
|
+
// when providers attach aggregate usage metadata (which already includes prompt tokens).
|
|
415
|
+
const defaultModel = modelName ?? this.activeTokenizationModel;
|
|
416
|
+
const contentTokens = await this.estimateContentTokens(content, defaultModel);
|
|
417
|
+
if (generation !== this.syncGeneration)
|
|
418
|
+
return;
|
|
419
|
+
// Atomically update the total
|
|
420
|
+
this.totalTokens += contentTokens;
|
|
421
|
+
// Emit event with updated count
|
|
422
|
+
const eventData = {
|
|
423
|
+
totalTokens: this.getTotalTokens(),
|
|
424
|
+
addedTokens: contentTokens,
|
|
425
|
+
contentId: content.metadata?.id,
|
|
426
|
+
};
|
|
427
|
+
this.logger.debug('Emitting tokensUpdated:', eventData);
|
|
428
|
+
this.emit('tokensUpdated', eventData);
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
/**
|
|
432
|
+
* Estimate token count for content using tokenizer
|
|
433
|
+
*/
|
|
434
|
+
async estimateContentTokens(content, modelName) {
|
|
435
|
+
return estimateContentTokensImpl(content, modelName, this.tokenizerProvider(), this.logger);
|
|
436
|
+
}
|
|
437
|
+
/** Provide the TokenizerProvider interface for the token estimation helpers. */
|
|
438
|
+
tokenizerProvider(activeProvider = this.activeTokenizationProvider) {
|
|
439
|
+
return {
|
|
440
|
+
getTokenizerForModel: (modelName) => this.getTokenizerForModel(modelName, activeProvider),
|
|
441
|
+
activeProvider,
|
|
442
|
+
};
|
|
443
|
+
}
|
|
444
|
+
/**
|
|
445
|
+
* Add multiple contents to the history.
|
|
446
|
+
*
|
|
447
|
+
* Iterates a snapshot because `add` appends to `this.history`: if `contents`
|
|
448
|
+
* aliases the backing array (`getRawHistory()`), a live iterator would keep
|
|
449
|
+
* consuming its own appends and never terminate. `replaceAll` is already
|
|
450
|
+
* immune the same way — its `filter` produces a fresh array before use.
|
|
451
|
+
*/
|
|
452
|
+
addAll(contents, modelName) {
|
|
453
|
+
for (const content of [...contents]) {
|
|
454
|
+
this.add(content, modelName);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
addBatch(contents, modelName, options = {}) {
|
|
458
|
+
const batch = [...contents];
|
|
459
|
+
return this.enqueueAsynchronousHistoryMutation(async () => {
|
|
460
|
+
this.validateBatch(batch);
|
|
461
|
+
if (batch.length === 0)
|
|
462
|
+
return;
|
|
463
|
+
await this.waitForTokenUpdates();
|
|
464
|
+
const addedTokens = await this.estimateTokensForContents(batch, modelName);
|
|
465
|
+
await this.commitHistoryMutation({
|
|
466
|
+
nextHistory: [...this.history, ...batch],
|
|
467
|
+
nextHistoryTokens: this.totalTokens + addedTokens,
|
|
468
|
+
publishedContents: batch,
|
|
469
|
+
options,
|
|
470
|
+
});
|
|
471
|
+
});
|
|
472
|
+
}
|
|
473
|
+
replaceBatch(contents, modelName, options = {}) {
|
|
474
|
+
const replacement = [...contents];
|
|
475
|
+
return this.enqueueAsynchronousHistoryMutation(async () => {
|
|
476
|
+
this.validateBatch(replacement);
|
|
477
|
+
await this.waitForTokenUpdates();
|
|
478
|
+
const replacementTokens = await this.estimateTokensForContents(replacement, modelName);
|
|
479
|
+
await this.commitHistoryMutation({
|
|
480
|
+
nextHistory: replacement,
|
|
481
|
+
nextHistoryTokens: replacementTokens,
|
|
482
|
+
publishedContents: replacement,
|
|
483
|
+
options,
|
|
484
|
+
});
|
|
485
|
+
});
|
|
486
|
+
}
|
|
487
|
+
transformAll(transform, modelName, options = {}) {
|
|
488
|
+
return this.enqueueAsynchronousHistoryMutation(async () => {
|
|
489
|
+
const replacement = [...(await transform([...this.history]))];
|
|
490
|
+
this.validateBatch(replacement);
|
|
491
|
+
await this.waitForTokenUpdates();
|
|
492
|
+
const replacementTokens = await this.estimateTokensForContents(replacement, modelName);
|
|
493
|
+
await this.commitHistoryMutation({
|
|
494
|
+
nextHistory: replacement,
|
|
495
|
+
nextHistoryTokens: replacementTokens,
|
|
496
|
+
options,
|
|
497
|
+
});
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
registerBatchParticipant(participant) {
|
|
501
|
+
this.batchParticipants.add(participant);
|
|
502
|
+
return () => {
|
|
503
|
+
this.batchParticipants.delete(participant);
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
registerMediaOwner(owner) {
|
|
507
|
+
this.mediaOwner = owner;
|
|
508
|
+
owner.adopt(this.history);
|
|
509
|
+
}
|
|
510
|
+
settleMediaOwnership() {
|
|
511
|
+
return this.enqueueAsynchronousHistoryMutation(async () => {
|
|
512
|
+
await this.mediaOwner?.reconcile([...this.history], () => this.history);
|
|
513
|
+
});
|
|
514
|
+
}
|
|
515
|
+
async waitForOwnershipSettlement() {
|
|
516
|
+
let settlement;
|
|
517
|
+
do {
|
|
518
|
+
settlement = this.ownershipSettlement;
|
|
519
|
+
await settlement;
|
|
520
|
+
} while (settlement !== this.ownershipSettlement);
|
|
521
|
+
const failure = this.ownershipFailure;
|
|
522
|
+
this.ownershipFailure = undefined;
|
|
523
|
+
if (failure !== undefined)
|
|
524
|
+
throw failure;
|
|
525
|
+
}
|
|
526
|
+
observeOwnershipOperation(operation) {
|
|
527
|
+
const observed = operation.then(() => undefined, (error) => {
|
|
528
|
+
this.ownershipFailure =
|
|
529
|
+
this.ownershipFailure === undefined
|
|
530
|
+
? error
|
|
531
|
+
: new AggregateError([this.ownershipFailure, error], 'Multiple history media ownership operations failed');
|
|
532
|
+
});
|
|
533
|
+
this.ownershipSettlement = this.ownershipSettlement.then(() => observed);
|
|
534
|
+
}
|
|
535
|
+
enqueueSynchronousOwnershipReconcile(previous, getNext) {
|
|
536
|
+
const owner = this.mediaOwner;
|
|
537
|
+
if (owner === undefined)
|
|
538
|
+
return;
|
|
539
|
+
this.observeOwnershipOperation(this.enqueueAsynchronousHistoryMutation(() => owner.reconcile(previous, getNext)));
|
|
540
|
+
}
|
|
541
|
+
enqueueSynchronousOwnershipReleaseAll() {
|
|
542
|
+
const owner = this.mediaOwner;
|
|
543
|
+
if (owner === undefined)
|
|
544
|
+
return;
|
|
545
|
+
this.observeOwnershipOperation(this.enqueueAsynchronousHistoryMutation(() => owner.releaseAll()));
|
|
546
|
+
}
|
|
547
|
+
replaceAll(contents, modelName, options = {}) {
|
|
548
|
+
const accepted = [...contents].filter((content) => ['human', 'ai', 'tool'].includes(content.speaker) &&
|
|
549
|
+
Array.isArray(content.blocks) &&
|
|
550
|
+
content.blocks.length > 0);
|
|
551
|
+
return this.enqueueAsynchronousHistoryMutation(async () => {
|
|
552
|
+
await this.waitForTokenUpdates();
|
|
553
|
+
const replacementTokens = await this.estimateTokensForContents(accepted, modelName);
|
|
554
|
+
await this.commitHistoryMutation({
|
|
555
|
+
nextHistory: accepted,
|
|
556
|
+
nextHistoryTokens: replacementTokens,
|
|
557
|
+
options,
|
|
558
|
+
});
|
|
559
|
+
});
|
|
560
|
+
}
|
|
561
|
+
validateBatch(contents) {
|
|
562
|
+
for (const [index, content] of contents.entries()) {
|
|
563
|
+
const validSpeaker = ['human', 'ai', 'tool'].includes(content.speaker);
|
|
564
|
+
const validBlocks = Array.isArray(content.blocks) && content.blocks.length > 0;
|
|
565
|
+
if (!validSpeaker || !validBlocks) {
|
|
566
|
+
throw new Error(`History batch entry ${index} is invalid: ${validSpeaker ? 'content has no blocks' : 'speaker is invalid'}`);
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
stampHistory(contents) {
|
|
571
|
+
const state = this.chronology.snapshot();
|
|
572
|
+
const entries = contents.map((content) => ({
|
|
573
|
+
content,
|
|
574
|
+
hadMetadata: content.metadata !== undefined,
|
|
575
|
+
chronology: content.metadata?.chronology,
|
|
576
|
+
}));
|
|
577
|
+
for (const content of contents) {
|
|
578
|
+
this.chronology.stamp(content);
|
|
579
|
+
}
|
|
580
|
+
return { state, entries };
|
|
581
|
+
}
|
|
582
|
+
restoreChronology(input) {
|
|
583
|
+
this.chronology.restore(input.state);
|
|
584
|
+
for (const entry of input.entries) {
|
|
585
|
+
if (!entry.hadMetadata) {
|
|
586
|
+
delete entry.content.metadata;
|
|
587
|
+
}
|
|
588
|
+
else if (entry.chronology === undefined) {
|
|
589
|
+
if (entry.content.metadata?.chronology !== undefined) {
|
|
590
|
+
delete entry.content.metadata.chronology;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
else if (entry.content.metadata !== undefined &&
|
|
594
|
+
entry.content.metadata.chronology !== entry.chronology) {
|
|
595
|
+
entry.content.metadata.chronology = entry.chronology;
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
async prepareMutationEffects(effects, publication, previousHistory, nextHistory, adopted) {
|
|
600
|
+
if (this.mediaOwner !== undefined) {
|
|
601
|
+
effects.push(await this.mediaOwner.prepareReplacement({
|
|
602
|
+
previous: previousHistory,
|
|
603
|
+
next: nextHistory,
|
|
604
|
+
adopted,
|
|
605
|
+
}));
|
|
606
|
+
}
|
|
607
|
+
if (publication !== undefined) {
|
|
608
|
+
for (const participant of this.batchParticipants) {
|
|
609
|
+
effects.push(await participant(publication));
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
async rollbackMutationEffects(effects) {
|
|
614
|
+
const failures = [];
|
|
615
|
+
for (const effect of [...effects].reverse()) {
|
|
616
|
+
try {
|
|
617
|
+
await effect.rollback();
|
|
618
|
+
}
|
|
619
|
+
catch (error) {
|
|
620
|
+
failures.push(error);
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
return failures;
|
|
624
|
+
}
|
|
625
|
+
async commitHistoryMutation(input) {
|
|
626
|
+
const previousHistory = this.history;
|
|
627
|
+
const previousTokens = this.totalTokens;
|
|
628
|
+
const chronology = this.stampHistory(input.nextHistory);
|
|
629
|
+
const nextHistory = [...input.nextHistory];
|
|
630
|
+
const addedTokens = input.nextHistoryTokens - previousTokens;
|
|
631
|
+
const publication = input.publishedContents === undefined
|
|
632
|
+
? undefined
|
|
633
|
+
: {
|
|
634
|
+
contents: input.publishedContents,
|
|
635
|
+
nextHistory,
|
|
636
|
+
addedTokens,
|
|
637
|
+
totalTokens: this.baseTokenOffset + input.nextHistoryTokens,
|
|
638
|
+
};
|
|
639
|
+
const effects = [];
|
|
640
|
+
let historyPublished = false;
|
|
641
|
+
try {
|
|
642
|
+
await this.prepareMutationEffects(effects, publication, previousHistory, nextHistory, input.options.adoptedOwners ?? []);
|
|
643
|
+
for (const effect of effects) {
|
|
644
|
+
await effect.publish();
|
|
645
|
+
}
|
|
646
|
+
this.invalidatePendingSyncs();
|
|
647
|
+
this.history = nextHistory;
|
|
648
|
+
this.totalTokens = input.nextHistoryTokens;
|
|
649
|
+
historyPublished = true;
|
|
650
|
+
if (input.publishedContents !== undefined) {
|
|
651
|
+
this.emit('contentBatchAdded', input.publishedContents);
|
|
652
|
+
}
|
|
653
|
+
this.emit('tokensUpdated', {
|
|
654
|
+
totalTokens: this.getTotalTokens(),
|
|
655
|
+
addedTokens,
|
|
656
|
+
contentId: null,
|
|
657
|
+
});
|
|
658
|
+
await input.options.afterPublication?.();
|
|
659
|
+
await finalizeMutationEffects(effects);
|
|
660
|
+
}
|
|
661
|
+
catch (error) {
|
|
662
|
+
if (historyPublished) {
|
|
663
|
+
this.invalidatePendingSyncs();
|
|
664
|
+
this.history = previousHistory;
|
|
665
|
+
this.totalTokens = previousTokens;
|
|
666
|
+
}
|
|
667
|
+
this.restoreChronology(chronology);
|
|
668
|
+
const rollbackFailures = await this.rollbackMutationEffects(effects);
|
|
669
|
+
if (rollbackFailures.length === 0)
|
|
670
|
+
throw error;
|
|
671
|
+
throw new AggregateError([error, ...rollbackFailures], 'History mutation and rollback failed');
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
/**
|
|
675
|
+
* Estimate total tokens for hypothetical contents without mutating history.
|
|
676
|
+
*/
|
|
677
|
+
async estimateTokensForContents(contents, modelName) {
|
|
678
|
+
return estimateTokensForContentsImpl([...contents], modelName, this.tokenizerProvider(), this.logger);
|
|
679
|
+
}
|
|
680
|
+
/**
|
|
681
|
+
* Wait for any in-flight token updates to complete.
|
|
682
|
+
*/
|
|
683
|
+
async waitForTokenUpdates() {
|
|
684
|
+
await this.tokenizerLock;
|
|
685
|
+
const failure = this.pendingTokenizerFailure;
|
|
686
|
+
this.pendingTokenizerFailure = undefined;
|
|
687
|
+
if (failure !== undefined)
|
|
688
|
+
throw failure.error;
|
|
689
|
+
}
|
|
690
|
+
/**
|
|
691
|
+
* Apply a density optimization result to the raw history.
|
|
692
|
+
*
|
|
693
|
+
* @plan PLAN-20260211-HIGHDENSITY.P08
|
|
694
|
+
* @requirement REQ-HD-003.1, REQ-HD-003.2, REQ-HD-003.3, REQ-HD-001.6, REQ-HD-001.7
|
|
695
|
+
* @pseudocode history-service.md lines 20-82
|
|
696
|
+
*/
|
|
697
|
+
async applyDensityResult(result) {
|
|
698
|
+
await this.enqueueAsynchronousHistoryMutation(async () => {
|
|
699
|
+
validateDensityResult(result, this.history.length);
|
|
700
|
+
const nextHistory = [...this.history];
|
|
701
|
+
// Each density replacement takes over the chronology position of the item
|
|
702
|
+
// it replaces, so the surviving history keeps an unbroken sequence.
|
|
703
|
+
// densityValidation stays free of chronology knowledge.
|
|
704
|
+
for (const [index, replacement] of result.replacements) {
|
|
705
|
+
const replacedMarker = this.history[index].metadata?.chronology;
|
|
706
|
+
if (replacedMarker !== undefined) {
|
|
707
|
+
this.chronology.inherit(replacement, replacedMarker);
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
applyDensityMutations(nextHistory, result);
|
|
711
|
+
await this.waitForTokenUpdates();
|
|
712
|
+
const replacementTokens = await this.estimateTokensForContents(nextHistory);
|
|
713
|
+
await this.commitHistoryMutation({
|
|
714
|
+
nextHistory,
|
|
715
|
+
nextHistoryTokens: replacementTokens,
|
|
716
|
+
options: {},
|
|
717
|
+
});
|
|
718
|
+
this.logger.debug('Density: applied result', {
|
|
719
|
+
replacements: result.replacements.size,
|
|
720
|
+
removals: result.removals.length,
|
|
721
|
+
newHistoryLength: this.history.length,
|
|
722
|
+
metadata: result.metadata,
|
|
723
|
+
});
|
|
724
|
+
});
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
//# sourceMappingURL=HistoryServiceCore.js.map
|