ctxtop 4.1.0 → 4.1.1
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/.antigravity-plugin/plugin.json +1 -1
- package/.claude-plugin/plugin.json +21 -18
- package/CHECKSUMS.sha256 +51 -44
- package/LICENSE +27 -27
- package/README.md +90 -56
- package/SECURITY.md +7 -1
- package/assets/hero-demo.svg +1 -1
- package/bin/ctxtop.mjs +267 -54
- package/config/modelCatalog.json +847 -273
- package/hooks/handlers/hookIpcClient.mjs +8 -4
- package/hooks/handlers/post-model-switch.mjs +39 -2
- package/hooks/handlers/post-tool-use-core.mjs +394 -0
- package/hooks/handlers/post-tool-use.mjs +54 -321
- package/hooks/handlers/pre-model-switch.mjs +115 -5
- package/hooks/handlers/pre-tool-use-core.mjs +680 -0
- package/hooks/handlers/pre-tool-use.mjs +61 -571
- package/hooks/handlers/stop-gate.mjs +20 -8
- package/hooks/handlers/user-prompt-submit.mjs +111 -2
- package/hooks/post_tool_use.mjs +17 -4
- package/hooks/pre_tool_use.mjs +84 -54
- package/hooks.json +56 -56
- package/package.json +4 -3
- package/packages/antigravity/package.json +10 -3
- package/packages/antigravity/src/adapter.mjs +109 -0
- package/packages/antigravity/src/index.mjs +7 -1
- package/packages/claude-code/package.json +10 -3
- package/packages/claude-code/src/adapter.mjs +194 -0
- package/packages/claude-code/src/index.mjs +8 -2
- package/packages/claude-code/src/register.js +726 -0
- package/packages/core/package.json +6 -2
- package/packages/core/src/catalog/detectorCatalog.mjs +558 -0
- package/packages/core/src/catalog/index.mjs +1 -0
- package/packages/core/src/catalog/safeguardGuide.mjs +412 -0
- package/packages/core/src/coach/cacheGravityRouter.mjs +1547 -0
- package/packages/core/src/coach/effortShiftDetector.mjs +316 -0
- package/packages/core/src/coach/microSkills.mjs +1 -0
- package/packages/core/src/coach/promptHygieneGovernor.mjs +1 -0
- package/packages/core/src/coach/repoCalibration.mjs +254 -0
- package/packages/core/src/coach/resumeToolsetAuditor.mjs +321 -0
- package/packages/core/src/coach/savedQuotaLedger.mjs +527 -0
- package/packages/core/src/coach/smartCompactAdvisor.mjs +339 -0
- package/packages/core/src/coach/stateBatonHydrator.mjs +810 -0
- package/packages/core/src/coach/ttlWatchdog.mjs +464 -0
- package/packages/core/src/config/anthropicModelCatalog.json +607 -0
- package/packages/core/src/config/catalogLoader.mjs +1271 -0
- package/packages/core/src/config/horizonConfig.mjs +1055 -0
- package/packages/core/src/control/callTree.mjs +338 -0
- package/packages/core/src/control/coachLatches.mjs +126 -0
- package/packages/core/src/control/controlStateMachine.mjs +205 -0
- package/packages/core/src/control/index.mjs +49 -0
- package/packages/core/src/control/swarmWorktree.mjs +109 -0
- package/packages/core/src/control/toolSuspension.mjs +197 -0
- package/packages/core/src/diagnostics/drift_guard.mjs +382 -0
- package/packages/core/src/diagnostics/index.mjs +9 -0
- package/packages/core/src/diagnostics/micro_skills.mjs +471 -0
- package/packages/core/src/diagnostics/prompt_hygiene_governor.mjs +888 -0
- package/packages/core/src/economics/billingBlocks.mjs +251 -0
- package/packages/core/src/economics/cacheGravity.mjs +371 -0
- package/packages/core/src/economics/cliffBreaker.mjs +256 -0
- package/packages/core/src/economics/driftLatency.mjs +433 -0
- package/packages/core/src/economics/dualTtl.mjs +198 -0
- package/packages/core/src/economics/index.mjs +47 -0
- package/packages/core/src/economics/retentionRadar.mjs +348 -0
- package/packages/core/src/economics/shadowAutoModel.mjs +228 -0
- package/packages/core/src/guards/bucketBAlphaBeta.mjs +860 -0
- package/packages/core/src/guards/bucketBGamma.mjs +442 -0
- package/packages/core/src/guards/bucketBHeuristics.mjs +37 -0
- package/packages/core/src/guards/circuitBreakers.mjs +1202 -0
- package/packages/core/src/guards/det01_03_shell_secret.mjs +1184 -0
- package/packages/core/src/guards/det04_12_thrash_rot.mjs +572 -0
- package/packages/core/src/guards/det13_20_mcp_scope.mjs +913 -0
- package/packages/core/src/guards/docIndexCore.mjs +446 -0
- package/packages/core/src/guards/losslessPostSanitizer.mjs +317 -0
- package/packages/core/src/guards/slopsquatGate.mjs +551 -0
- package/packages/core/src/index.js +27 -0
- package/packages/core/src/index.mjs +25 -1
- package/packages/core/src/telemetry/otelExporter.mjs +187 -0
- package/packages/core/src/telemetry/scopeLockRegistry.mjs +522 -0
- package/packages/core/src/telemetry/sprintMetrics.mjs +327 -0
- package/packages/core/src/telemetry/swarmTopology.mjs +152 -0
- package/packages/core/src/telemetry/telemetryBridge.mjs +1232 -0
- package/packages/core/src/ui/brailleSparkline.mjs +142 -0
- package/packages/core/src/ui/costRadarSvg.mjs +276 -0
- package/packages/core/src/ui/horizonGrid.mjs +475 -0
- package/packages/core/src/ui/horizonPanelHtml.mjs +1502 -0
- package/packages/core/src/ui/modViews.mjs +1558 -0
- package/packages/core/src/ui/pdfReceiptGenerator.mjs +329 -0
- package/packages/core/src/ustf/index.mjs +7 -0
- package/packages/core/src/ustf/normalizer.mjs +512 -0
- package/packages/core/src/ustf/schema.mjs +186 -0
- package/packages/core/src/utils/runtime.mjs +962 -0
- package/packages/engine-node/package.json +6 -2
- package/packages/engine-node/src/db/index.mjs +58 -0
- package/packages/engine-node/src/db/jsonl_fallback.mjs +184 -0
- package/packages/engine-node/src/db/probe.mjs +342 -0
- package/packages/engine-node/src/db/sqlite_wrapper.mjs +122 -0
- package/packages/engine-node/src/index.mjs +11 -1
- package/packages/engine-node/src/ipc/client.mjs +447 -0
- package/packages/engine-node/src/ipc/fast_client.mjs +191 -0
- package/packages/engine-node/src/ipc/index.mjs +24 -0
- package/packages/engine-node/src/ipc/protocol.mjs +177 -0
- package/packages/engine-node/src/ipc/server.mjs +445 -0
- package/packages/engine-node/src/multi_host_mcp.mjs +168 -0
- package/packages/engine-node/src/offloader/index.mjs +6 -0
- package/packages/engine-node/src/offloader/tool_offloader.mjs +241 -0
- package/packages/engine-node/src/rsl/index.mjs +3 -0
- package/packages/engine-node/src/sensors/blindspots.mjs +376 -0
- package/packages/engine-node/src/sensors/git_merge_tree.mjs +223 -0
- package/packages/engine-node/src/sensors/index.mjs +7 -0
- package/packages/engine-node/src/vendor/config/default_flightcheck.json +133 -0
- package/packages/engine-node/src/vendor/config/modelCatalog.json +1359 -0
- package/packages/engine-node/src/vendor/config/platformQuirks.json +19 -0
- package/packages/engine-node/src/vendor/core/atomic_io.mjs +124 -0
- package/packages/engine-node/src/vendor/core/constants.mjs +2150 -0
- package/packages/engine-node/src/vendor/core/doc_indexer.mjs +338 -0
- package/packages/engine-node/src/vendor/core/rsl_clash_auditor.mjs +423 -0
- package/packages/engine-node/src/vendor/core/rsl_distiller.mjs +394 -0
- package/packages/engine-node/src/vendor/core/rsl_ledger.mjs +1029 -0
- package/packages/engine-node/src/vendor/core/rsl_triage.mjs +1051 -0
- package/packages/engine-node/src/vendor/core/shield_manager.mjs +1417 -0
- package/packages/engine-node/src/vendor/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
- package/packages/engine-node/src/vendor/core-isomorphic/catalog/index.mjs +1 -0
- package/packages/engine-node/src/vendor/core-isomorphic/catalog/safeguardGuide.mjs +412 -0
- package/packages/engine-node/src/vendor/core-isomorphic/coach/cacheGravityRouter.mjs +1547 -0
- package/packages/engine-node/src/vendor/core-isomorphic/coach/effortShiftDetector.mjs +316 -0
- package/packages/engine-node/src/vendor/core-isomorphic/coach/microSkills.mjs +1 -0
- package/packages/engine-node/src/vendor/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
- package/packages/engine-node/src/vendor/core-isomorphic/coach/repoCalibration.mjs +254 -0
- package/packages/engine-node/src/vendor/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
- package/packages/engine-node/src/vendor/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
- package/packages/engine-node/src/vendor/core-isomorphic/coach/smartCompactAdvisor.mjs +339 -0
- package/packages/engine-node/src/vendor/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
- package/packages/engine-node/src/vendor/core-isomorphic/coach/ttlWatchdog.mjs +464 -0
- package/packages/engine-node/src/vendor/core-isomorphic/config/anthropicModelCatalog.json +607 -0
- package/packages/engine-node/src/vendor/core-isomorphic/config/catalogLoader.mjs +1271 -0
- package/packages/engine-node/src/vendor/core-isomorphic/config/horizonConfig.mjs +1055 -0
- package/packages/engine-node/src/vendor/core-isomorphic/control/callTree.mjs +338 -0
- package/packages/engine-node/src/vendor/core-isomorphic/control/coachLatches.mjs +126 -0
- package/packages/engine-node/src/vendor/core-isomorphic/control/controlStateMachine.mjs +205 -0
- package/packages/engine-node/src/vendor/core-isomorphic/control/index.mjs +49 -0
- package/packages/engine-node/src/vendor/core-isomorphic/control/swarmWorktree.mjs +109 -0
- package/packages/engine-node/src/vendor/core-isomorphic/control/toolSuspension.mjs +197 -0
- package/packages/engine-node/src/vendor/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
- package/packages/engine-node/src/vendor/core-isomorphic/diagnostics/index.mjs +9 -0
- package/packages/engine-node/src/vendor/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
- package/packages/engine-node/src/vendor/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +888 -0
- package/packages/engine-node/src/vendor/core-isomorphic/economics/billingBlocks.mjs +251 -0
- package/packages/engine-node/src/vendor/core-isomorphic/economics/cacheGravity.mjs +371 -0
- package/packages/engine-node/src/vendor/core-isomorphic/economics/cliffBreaker.mjs +256 -0
- package/packages/engine-node/src/vendor/core-isomorphic/economics/driftLatency.mjs +433 -0
- package/packages/engine-node/src/vendor/core-isomorphic/economics/dualTtl.mjs +198 -0
- package/packages/engine-node/src/vendor/core-isomorphic/economics/index.mjs +47 -0
- package/packages/engine-node/src/vendor/core-isomorphic/economics/retentionRadar.mjs +348 -0
- package/packages/engine-node/src/vendor/core-isomorphic/economics/shadowAutoModel.mjs +228 -0
- package/packages/engine-node/src/vendor/core-isomorphic/guards/bucketBAlphaBeta.mjs +860 -0
- package/packages/engine-node/src/vendor/core-isomorphic/guards/bucketBGamma.mjs +442 -0
- package/packages/engine-node/src/vendor/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
- package/packages/engine-node/src/vendor/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
- package/packages/engine-node/src/vendor/core-isomorphic/guards/det01_03_shell_secret.mjs +1184 -0
- package/packages/engine-node/src/vendor/core-isomorphic/guards/det04_12_thrash_rot.mjs +572 -0
- package/packages/engine-node/src/vendor/core-isomorphic/guards/det13_20_mcp_scope.mjs +913 -0
- package/packages/engine-node/src/vendor/core-isomorphic/guards/docIndexCore.mjs +446 -0
- package/packages/engine-node/src/vendor/core-isomorphic/guards/losslessPostSanitizer.mjs +317 -0
- package/packages/engine-node/src/vendor/core-isomorphic/guards/slopsquatGate.mjs +551 -0
- package/packages/engine-node/src/vendor/core-isomorphic/index.js +27 -0
- package/packages/engine-node/src/vendor/core-isomorphic/telemetry/otelExporter.mjs +187 -0
- package/packages/engine-node/src/vendor/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
- package/packages/engine-node/src/vendor/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
- package/packages/engine-node/src/vendor/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
- package/packages/engine-node/src/vendor/core-isomorphic/telemetry/telemetryBridge.mjs +1232 -0
- package/packages/engine-node/src/vendor/core-isomorphic/ui/brailleSparkline.mjs +142 -0
- package/packages/engine-node/src/vendor/core-isomorphic/ui/costRadarSvg.mjs +276 -0
- package/packages/engine-node/src/vendor/core-isomorphic/ui/horizonGrid.mjs +475 -0
- package/packages/engine-node/src/vendor/core-isomorphic/ui/horizonPanelHtml.mjs +1502 -0
- package/packages/engine-node/src/vendor/core-isomorphic/ui/modViews.mjs +1558 -0
- package/packages/engine-node/src/vendor/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
- package/packages/engine-node/src/vendor/core-isomorphic/ustf/index.mjs +7 -0
- package/packages/engine-node/src/vendor/core-isomorphic/ustf/normalizer.mjs +512 -0
- package/packages/engine-node/src/vendor/core-isomorphic/ustf/schema.mjs +186 -0
- package/packages/engine-node/src/vendor/core-isomorphic/utils/runtime.mjs +962 -0
- package/packages/mcp/package.json +7 -3
- package/packages/mcp/src/server.mjs +115 -14
- package/packages/mcp/src/vendor/config/default_flightcheck.json +133 -0
- package/packages/mcp/src/vendor/config/modelCatalog.json +1359 -0
- package/packages/mcp/src/vendor/config/platformQuirks.json +19 -0
- package/packages/mcp/src/vendor/core/atomic_io.mjs +124 -0
- package/packages/mcp/src/vendor/core/coach/saved_quota_ledger.mjs +615 -0
- package/packages/mcp/src/vendor/core/constants.mjs +2150 -0
- package/packages/mcp/src/vendor/core/doc_indexer.mjs +338 -0
- package/packages/mcp/src/vendor/core/fts5_output_compressor.mjs +596 -0
- package/packages/mcp/src/vendor/core/hook_diagnostics.mjs +158 -0
- package/packages/mcp/src/vendor/core/paths.mjs +311 -0
- package/packages/mcp/src/vendor/core/session_auditor.mjs +1109 -0
- package/packages/mcp/src/vendor/core/sqlite_client.mjs +289 -0
- package/packages/mcp/src/vendor/core/telemetry/scope_lock_registry.mjs +578 -0
- package/packages/mcp/src/vendor/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
- package/packages/mcp/src/vendor/core-isomorphic/catalog/index.mjs +1 -0
- package/packages/mcp/src/vendor/core-isomorphic/catalog/safeguardGuide.mjs +412 -0
- package/packages/mcp/src/vendor/core-isomorphic/coach/cacheGravityRouter.mjs +1547 -0
- package/packages/mcp/src/vendor/core-isomorphic/coach/effortShiftDetector.mjs +316 -0
- package/packages/mcp/src/vendor/core-isomorphic/coach/microSkills.mjs +1 -0
- package/packages/mcp/src/vendor/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
- package/packages/mcp/src/vendor/core-isomorphic/coach/repoCalibration.mjs +254 -0
- package/packages/mcp/src/vendor/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
- package/packages/mcp/src/vendor/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
- package/packages/mcp/src/vendor/core-isomorphic/coach/smartCompactAdvisor.mjs +339 -0
- package/packages/mcp/src/vendor/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
- package/packages/mcp/src/vendor/core-isomorphic/coach/ttlWatchdog.mjs +464 -0
- package/packages/mcp/src/vendor/core-isomorphic/config/anthropicModelCatalog.json +607 -0
- package/packages/mcp/src/vendor/core-isomorphic/config/catalogLoader.mjs +1271 -0
- package/packages/mcp/src/vendor/core-isomorphic/config/horizonConfig.mjs +1055 -0
- package/packages/mcp/src/vendor/core-isomorphic/control/callTree.mjs +338 -0
- package/packages/mcp/src/vendor/core-isomorphic/control/coachLatches.mjs +126 -0
- package/packages/mcp/src/vendor/core-isomorphic/control/controlStateMachine.mjs +205 -0
- package/packages/mcp/src/vendor/core-isomorphic/control/index.mjs +49 -0
- package/packages/mcp/src/vendor/core-isomorphic/control/swarmWorktree.mjs +109 -0
- package/packages/mcp/src/vendor/core-isomorphic/control/toolSuspension.mjs +197 -0
- package/packages/mcp/src/vendor/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
- package/packages/mcp/src/vendor/core-isomorphic/diagnostics/index.mjs +9 -0
- package/packages/mcp/src/vendor/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
- package/packages/mcp/src/vendor/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +888 -0
- package/packages/mcp/src/vendor/core-isomorphic/economics/billingBlocks.mjs +251 -0
- package/packages/mcp/src/vendor/core-isomorphic/economics/cacheGravity.mjs +371 -0
- package/packages/mcp/src/vendor/core-isomorphic/economics/cliffBreaker.mjs +256 -0
- package/packages/mcp/src/vendor/core-isomorphic/economics/driftLatency.mjs +433 -0
- package/packages/mcp/src/vendor/core-isomorphic/economics/dualTtl.mjs +198 -0
- package/packages/mcp/src/vendor/core-isomorphic/economics/index.mjs +47 -0
- package/packages/mcp/src/vendor/core-isomorphic/economics/retentionRadar.mjs +348 -0
- package/packages/mcp/src/vendor/core-isomorphic/economics/shadowAutoModel.mjs +228 -0
- package/packages/mcp/src/vendor/core-isomorphic/guards/bucketBAlphaBeta.mjs +860 -0
- package/packages/mcp/src/vendor/core-isomorphic/guards/bucketBGamma.mjs +442 -0
- package/packages/mcp/src/vendor/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
- package/packages/mcp/src/vendor/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
- package/packages/mcp/src/vendor/core-isomorphic/guards/det01_03_shell_secret.mjs +1184 -0
- package/packages/mcp/src/vendor/core-isomorphic/guards/det04_12_thrash_rot.mjs +572 -0
- package/packages/mcp/src/vendor/core-isomorphic/guards/det13_20_mcp_scope.mjs +913 -0
- package/packages/mcp/src/vendor/core-isomorphic/guards/docIndexCore.mjs +446 -0
- package/packages/mcp/src/vendor/core-isomorphic/guards/losslessPostSanitizer.mjs +317 -0
- package/packages/mcp/src/vendor/core-isomorphic/guards/slopsquatGate.mjs +551 -0
- package/packages/mcp/src/vendor/core-isomorphic/index.js +27 -0
- package/packages/mcp/src/vendor/core-isomorphic/telemetry/otelExporter.mjs +187 -0
- package/packages/mcp/src/vendor/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
- package/packages/mcp/src/vendor/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
- package/packages/mcp/src/vendor/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
- package/packages/mcp/src/vendor/core-isomorphic/telemetry/telemetryBridge.mjs +1232 -0
- package/packages/mcp/src/vendor/core-isomorphic/ui/brailleSparkline.mjs +142 -0
- package/packages/mcp/src/vendor/core-isomorphic/ui/costRadarSvg.mjs +276 -0
- package/packages/mcp/src/vendor/core-isomorphic/ui/horizonGrid.mjs +475 -0
- package/packages/mcp/src/vendor/core-isomorphic/ui/horizonPanelHtml.mjs +1502 -0
- package/packages/mcp/src/vendor/core-isomorphic/ui/modViews.mjs +1558 -0
- package/packages/mcp/src/vendor/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
- package/packages/mcp/src/vendor/core-isomorphic/ustf/index.mjs +7 -0
- package/packages/mcp/src/vendor/core-isomorphic/ustf/normalizer.mjs +512 -0
- package/packages/mcp/src/vendor/core-isomorphic/ustf/schema.mjs +186 -0
- package/packages/mcp/src/vendor/core-isomorphic/utils/runtime.mjs +962 -0
- package/packages/mcp/src/vendor/engine-node/db/probe.mjs +342 -0
- package/packages/mcp/src/vendor/pro/pro_license.mjs +547 -0
- package/packages/pro/package.json +23 -16
- package/packages/pro/src/index.mjs +9 -3
- package/packages/pro/src/pro_license.mjs +547 -0
- package/packages/pro/src/team_finops_pack.mjs +241 -241
- package/packages/pro/workers/polar_webhook_worker.mjs +219 -215
- package/plugin.json +1 -1
- package/sidecars/horizon-daemon/server.mjs +482 -44
- package/src/cli/doctor.mjs +11 -2
- package/src/cli/horizon_hud.mjs +31 -15
- package/src/cli/init.mjs +46 -13
- package/src/config/modelCatalog.json +886 -231
- package/src/core/classifier.mjs +25 -11
- package/src/core/coach/circuit_breakers.mjs +84 -6
- package/src/core/coach/task_quota_router.mjs +8 -0
- package/src/core/code_fold_lite.mjs +169 -0
- package/src/core/config.mjs +44 -0
- package/src/core/constants.mjs +175 -12
- package/src/core/detectors_det01_to_16.mjs +44 -3
- package/src/core/fts5_output_compressor.mjs +272 -35
- package/src/core/horizon_config.mjs +42 -0
- package/src/core/parser.mjs +86 -11
- package/src/core/pro_license.mjs +174 -12
- package/src/core/pruner.mjs +7 -146
- package/src/core/quota.mjs +14 -2
- package/src/core/rsl_distiller.mjs +31 -9
- package/src/core/rsl_ledger.mjs +66 -6
- package/src/core/rsl_triage.mjs +159 -17
- package/src/core/session_auditor.mjs +476 -25
- package/src/core/shadow_auto_ledger.mjs +205 -0
- package/src/core/sqlite_client.mjs +10 -4
- package/src/core/subagents.mjs +18 -2
- package/src/core/task_quota_router.mjs +61 -4
- package/src/core-isomorphic/catalog/safeguardGuide.mjs +412 -0
- package/src/core-isomorphic/coach/effortShiftDetector.mjs +316 -0
- package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +54 -20
- package/src/core-isomorphic/config/anthropicModelCatalog.json +1 -0
- package/src/core-isomorphic/config/catalogLoader.mjs +6 -3
- package/src/core-isomorphic/config/horizonConfig.mjs +1 -1
- package/src/core-isomorphic/economics/cacheGravity.mjs +3 -1
- package/src/core-isomorphic/economics/shadowAutoModel.mjs +228 -0
- package/src/core-isomorphic/guards/bucketBGamma.mjs +1 -1
- package/src/core-isomorphic/telemetry/telemetryBridge.mjs +77 -1
- package/src/core-isomorphic/ui/horizonPanelHtml.mjs +395 -130
- package/src/core-isomorphic/ui/modViews.mjs +62 -8
- package/src/diagnostics/claudeHookCapabilities.mjs +32 -2
- package/src/diagnostics/doctorEngine.mjs +28 -2
- package/src/engine-node/ipc/fast_client.mjs +191 -0
- package/src/engine-node/ipc/index.mjs +2 -0
- package/src/engine-node/multi_host_mcp.mjs +168 -0
- package/src/hooks/antigravity_rsl_hook.mjs +24 -2
- package/src/hooks/claude_rsl_hook.mjs +22 -2
- package/src/hooks/daemon_hook_bridge.mjs +256 -0
- package/src/hooks/fast_hook_ipc.mjs +295 -0
- package/src/hooks/post_invocation.mjs +37 -597
- package/src/hooks/post_invocation_core.mjs +623 -0
- package/src/hooks/pre_invocation.mjs +103 -1668
- package/src/hooks/pre_invocation_core.mjs +1830 -0
- package/src/utils/sessionCalibration.mjs +52 -5
- package/src/webview/advanced_view.html +34 -18
- package/src/webview/horizon_panel.html +3233 -675
- package/src/webview/simple_view.html +1 -1
|
@@ -0,0 +1,1547 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/coach/cacheGravityRouter.mjs
|
|
3
|
+
* Anthropic KV-Cache Flight Computer (`CacheGravityScorer`), `PostCompactMutationQueue`,
|
|
4
|
+
* and `HysteresisLock` for Claude Code Highbeam.
|
|
5
|
+
*
|
|
6
|
+
* Implements the algebraic cross-model break-even equation:
|
|
7
|
+
* C* = [ O * (P_out,curr - P_out,target) ] / [ P_write,target - P_read,curr ]
|
|
8
|
+
* with all rates and thresholds derived dynamically from the price catalog at runtime.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import {
|
|
12
|
+
BUILTIN_CATALOG,
|
|
13
|
+
isKnownCatalogModel,
|
|
14
|
+
normalizeModelId,
|
|
15
|
+
computeTotalPromptTokens,
|
|
16
|
+
resolveEffectiveRates
|
|
17
|
+
} from '../config/catalogLoader.mjs';
|
|
18
|
+
|
|
19
|
+
export const DEFAULT_FALLBACK_INITIAL_PREFIX_TOKENS = 9000;
|
|
20
|
+
export const DEFAULT_REQUESTS_PER_TURN = 1.0;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Per-model `DET-09` capability matrix for mid-session `effort` changes with provenance:
|
|
24
|
+
* - `claude-sonnet-4-6`: invalidates whole prefix (`EF1_46`: 0% cache read, +38.7% cost) -> `yes`
|
|
25
|
+
* - `claude-opus-4-6`: invalidates whole prefix (earlier article experiment) -> `yes`
|
|
26
|
+
* - `claude-sonnet-5-5`: keeps cache (`r2_effort.csv` & R2 rerun, n = 3: 99.3% cache read, thinking 1.47-1.57x) -> `no`
|
|
27
|
+
* - `claude-opus-5-5`: keeps cache (`currency_55.csv` `effort_only_55`: 26,130 vs 26,126 read; behaviour unverified) -> `no`
|
|
28
|
+
* - All other models: `unknown` (warn as before, labelled `"unverified for this model"`).
|
|
29
|
+
*/
|
|
30
|
+
export const MODEL_EFFORT_CACHE_CAPABILITIES = Object.freeze({
|
|
31
|
+
'claude-sonnet-4-6': Object.freeze({
|
|
32
|
+
modelId: 'claude-sonnet-4-6',
|
|
33
|
+
invalidatesCache: 'yes',
|
|
34
|
+
invalidationScope: 'whole_prefix',
|
|
35
|
+
status: 'measured',
|
|
36
|
+
provenance: 'EF1_46 (Sonnet 4.6: 0% cache read, +38.7% cost)'
|
|
37
|
+
}),
|
|
38
|
+
'claude-opus-4-6': Object.freeze({
|
|
39
|
+
modelId: 'claude-opus-4-6',
|
|
40
|
+
invalidatesCache: 'yes',
|
|
41
|
+
invalidationScope: 'whole_prefix',
|
|
42
|
+
status: 'measured',
|
|
43
|
+
provenance: 'earlier article experiment (Opus 4.6 effort-only invalidation)'
|
|
44
|
+
}),
|
|
45
|
+
'claude-sonnet-5-5': Object.freeze({
|
|
46
|
+
modelId: 'claude-sonnet-5-5',
|
|
47
|
+
invalidatesCache: 'no',
|
|
48
|
+
invalidationScope: 'none',
|
|
49
|
+
status: 'measured, n = 3 with behaviour change',
|
|
50
|
+
provenance:
|
|
51
|
+
'r2_effort.csv & R2 behavioural rerun (Sonnet 5.5, n = 3: cache kept 99.3%, thinking 1.47-1.57x control)'
|
|
52
|
+
}),
|
|
53
|
+
'claude-opus-5-5': Object.freeze({
|
|
54
|
+
modelId: 'claude-opus-5-5',
|
|
55
|
+
invalidatesCache: 'no',
|
|
56
|
+
invalidationScope: 'none',
|
|
57
|
+
status: 'measured for cache only; behaviour unverified',
|
|
58
|
+
provenance:
|
|
59
|
+
'currency_55.csv effort_only_55 (Opus 5.5: cache kept 26,130 vs 26,126 control; behaviour unverified)'
|
|
60
|
+
})
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Resolves `DET-09` mid-session `effort` cache-invalidation capability for a model.
|
|
65
|
+
* @param {string} [modelId='']
|
|
66
|
+
* @param {object} [options={}]
|
|
67
|
+
*/
|
|
68
|
+
export function getEffortMutationCacheCapability(modelId = '', options = {}) {
|
|
69
|
+
const known = isKnownCatalogModel(modelId, options);
|
|
70
|
+
const normalized = known ? normalizeModelId(modelId, options) : 'unknown';
|
|
71
|
+
const entry = known ? MODEL_EFFORT_CACHE_CAPABILITIES[normalized] : null;
|
|
72
|
+
if (entry) {
|
|
73
|
+
return entry;
|
|
74
|
+
}
|
|
75
|
+
return {
|
|
76
|
+
modelId: known ? normalized : String(modelId || 'unknown'),
|
|
77
|
+
invalidatesCache: 'unknown',
|
|
78
|
+
invalidationScope: 'unknown',
|
|
79
|
+
status: 'unverified for this model',
|
|
80
|
+
label: 'unverified for this model',
|
|
81
|
+
provenance: 'unverified for this model (not in EF1_46, R2, or currency_55)'
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Placeholder empirical survival prior derived from 496 Antigravity IDE workstation sessions
|
|
87
|
+
* (376 single-prompt/subagent, 120 interactive) measured in API requests (`api_requests`),
|
|
88
|
+
* NOT native Claude Code session logs. Converted to turns using the session's `requestsPerTurn`.
|
|
89
|
+
*/
|
|
90
|
+
export const EMPIRICAL_SESSION_API_CALL_PRIOR = Object.freeze({
|
|
91
|
+
isPlaceholderPrior: true,
|
|
92
|
+
provenance: 'placeholder_antigravity_ide_workstation_logs_not_claude_code',
|
|
93
|
+
unit: 'api_requests',
|
|
94
|
+
note: 'Placeholder distribution derived from 496 Antigravity IDE workstation planner runs (376 subagent/single-prompt, 120 interactive) in API requests, NOT Claude Code telemetry; convert to turns via observed requestsPerTurn.',
|
|
95
|
+
sampleCount: 496,
|
|
96
|
+
interactiveSampleCount: 120,
|
|
97
|
+
unconditionalMedian: 62,
|
|
98
|
+
unconditionalP25: 35,
|
|
99
|
+
unconditionalP75: 96,
|
|
100
|
+
survivalBuckets: Object.freeze([
|
|
101
|
+
{ label: '0-3_requests', maxTurn: 3, remainingMedian: 59 },
|
|
102
|
+
{ label: '4-6_requests', maxTurn: 6, remainingMedian: 57 },
|
|
103
|
+
{ label: '7-12_requests', maxTurn: 12, remainingMedian: 54 },
|
|
104
|
+
{ label: '13-24_requests', maxTurn: 24, remainingMedian: 47 },
|
|
105
|
+
{ label: '25+_requests', maxTurn: Infinity, remainingMedian: 34 }
|
|
106
|
+
])
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Resolves a finite positive API-requests-per-turn ratio from session observations,
|
|
111
|
+
* falling back cleanly to `DEFAULT_REQUESTS_PER_TURN` (1.0).
|
|
112
|
+
*/
|
|
113
|
+
export function resolveRequestsPerTurn(context = {}, options = {}) {
|
|
114
|
+
const explicitRpt = Number(context.requestsPerTurn ?? options.requestsPerTurn);
|
|
115
|
+
if (Number.isFinite(explicitRpt) && explicitRpt > 0) {
|
|
116
|
+
return {
|
|
117
|
+
requestsPerTurn: Number(explicitRpt.toFixed(4)),
|
|
118
|
+
source: 'observed_requests_per_turn'
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
const turns = Math.max(0, Number(context.turnsCompleted ?? context.currentTurn ?? 0));
|
|
122
|
+
const calls = Number(context.apiCallsCompleted ?? options.apiCallsCompleted);
|
|
123
|
+
if (turns > 0 && Number.isFinite(calls) && calls > 0) {
|
|
124
|
+
return {
|
|
125
|
+
requestsPerTurn: Number((calls / turns).toFixed(4)),
|
|
126
|
+
source: 'derived_api_calls_per_turn'
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
return {
|
|
130
|
+
requestsPerTurn: DEFAULT_REQUESTS_PER_TURN,
|
|
131
|
+
source: 'default_1.0'
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Estimates expected remaining **turns** for a running session (`C1e` / `rule_v2`) by combining:
|
|
137
|
+
* 1. Conditional survival remaining **API requests** from local Claude Code transcripts (`>= 5` sessions)
|
|
138
|
+
* or the labeled placeholder 496-session Antigravity prior, converted via `requestsPerTurn`.
|
|
139
|
+
* 2. Context-ceiling compaction bound (using dynamic `contextCeiling`, observed Turn-0/1 prefix,
|
|
140
|
+
* and observed growth per API request -> converted to turns).
|
|
141
|
+
*
|
|
142
|
+
* Returns `expectedRemainingTurns = min(empiricalResidualTurns, turnsUntilCompact)`.
|
|
143
|
+
*
|
|
144
|
+
* @param {object} [context={}]
|
|
145
|
+
* @param {object} [options={}]
|
|
146
|
+
* @returns {object}
|
|
147
|
+
*/
|
|
148
|
+
export function estimateEmpiricalRemainingTurns(context = {}, options = {}) {
|
|
149
|
+
const turnsCompleted = Math.max(0, Number(context.turnsCompleted ?? context.currentTurn ?? 0));
|
|
150
|
+
const cachedTokens = Math.max(0, Number(context.cachedTokens ?? 0));
|
|
151
|
+
const contextCeiling = Math.max(10_000, Number(context.contextCeiling || 200_000));
|
|
152
|
+
const autoCompactLimitTokens = Math.max(
|
|
153
|
+
10_000,
|
|
154
|
+
Number(context.autoCompactLimitTokens || Math.round(contextCeiling * 0.8))
|
|
155
|
+
);
|
|
156
|
+
const rptInfo = resolveRequestsPerTurn(context, options);
|
|
157
|
+
const requestsPerTurn = rptInfo.requestsPerTurn;
|
|
158
|
+
const rawApiCalls = Number(context.apiCallsCompleted ?? options.apiCallsCompleted);
|
|
159
|
+
const apiCallsCompleted =
|
|
160
|
+
Number.isFinite(rawApiCalls) && rawApiCalls >= 0
|
|
161
|
+
? rawApiCalls
|
|
162
|
+
: Math.round(turnsCompleted * requestsPerTurn);
|
|
163
|
+
|
|
164
|
+
let empiricalResidualRequests;
|
|
165
|
+
let priorBucket = '25+_requests';
|
|
166
|
+
let source = 'placeholder_antigravity_496_prior';
|
|
167
|
+
let isPlaceholderPrior = true;
|
|
168
|
+
let priorProvenance = EMPIRICAL_SESSION_API_CALL_PRIOR.provenance;
|
|
169
|
+
const hist = options.historicalSessionApiCalls;
|
|
170
|
+
if (Array.isArray(hist) && hist.length >= 5) {
|
|
171
|
+
source = 'local_transcripts';
|
|
172
|
+
isPlaceholderPrior = false;
|
|
173
|
+
priorProvenance = 'local_claude_code_transcripts';
|
|
174
|
+
const survivors = hist
|
|
175
|
+
.map((n) => Number(n))
|
|
176
|
+
.filter((n) => Number.isFinite(n) && n > apiCallsCompleted)
|
|
177
|
+
.map((n) => n - apiCallsCompleted)
|
|
178
|
+
.sort((a, b) => a - b);
|
|
179
|
+
if (survivors.length > 0) {
|
|
180
|
+
empiricalResidualRequests = survivors[Math.floor((survivors.length - 1) / 2)];
|
|
181
|
+
priorBucket = `local_survivors_${survivors.length}`;
|
|
182
|
+
} else {
|
|
183
|
+
const sorted = hist
|
|
184
|
+
.map((n) => Number(n))
|
|
185
|
+
.filter((n) => Number.isFinite(n) && n > 0)
|
|
186
|
+
.sort((a, b) => a - b);
|
|
187
|
+
empiricalResidualRequests = sorted.length > 0
|
|
188
|
+
? Math.max(1, sorted[Math.floor((sorted.length - 1) * 0.25)])
|
|
189
|
+
: 10;
|
|
190
|
+
priorBucket = 'local_p25_fallback';
|
|
191
|
+
}
|
|
192
|
+
} else {
|
|
193
|
+
const bucket = EMPIRICAL_SESSION_API_CALL_PRIOR.survivalBuckets.find(
|
|
194
|
+
(b) => apiCallsCompleted <= b.maxTurn
|
|
195
|
+
);
|
|
196
|
+
empiricalResidualRequests = bucket ? bucket.remainingMedian : 34;
|
|
197
|
+
priorBucket = bucket ? bucket.label : '25+_requests';
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const baselinePrefix =
|
|
201
|
+
Number(context.initialPrefixTokens) > 0
|
|
202
|
+
? Number(context.initialPrefixTokens)
|
|
203
|
+
: turnsCompleted === 0 && cachedTokens > 0
|
|
204
|
+
? cachedTokens
|
|
205
|
+
: DEFAULT_FALLBACK_INITIAL_PREFIX_TOKENS;
|
|
206
|
+
const explicitGrowthPerTurn = Number(context.contextGrowthPerTurn);
|
|
207
|
+
const observedGrowthPerRequest =
|
|
208
|
+
Number.isFinite(explicitGrowthPerTurn) && explicitGrowthPerTurn > 0 && requestsPerTurn > 0
|
|
209
|
+
? explicitGrowthPerTurn / requestsPerTurn
|
|
210
|
+
: apiCallsCompleted > 0 && cachedTokens > baselinePrefix
|
|
211
|
+
? (cachedTokens - baselinePrefix) / apiCallsCompleted
|
|
212
|
+
: 600;
|
|
213
|
+
const avgDeltaTokensPerCall = Math.min(12_000, Math.max(300, observedGrowthPerRequest));
|
|
214
|
+
const callsUntilCompact =
|
|
215
|
+
cachedTokens >= autoCompactLimitTokens
|
|
216
|
+
? 1
|
|
217
|
+
: Math.max(1, Math.floor((autoCompactLimitTokens - cachedTokens) / avgDeltaTokensPerCall));
|
|
218
|
+
|
|
219
|
+
const expectedRemainingRequests = Math.min(empiricalResidualRequests, callsUntilCompact);
|
|
220
|
+
const expectedRemainingTurns = Number(
|
|
221
|
+
(expectedRemainingRequests / requestsPerTurn).toFixed(2)
|
|
222
|
+
);
|
|
223
|
+
// Prior residual requests are counted before the switch turn executes; 1 turn is consumed by the switch itself.
|
|
224
|
+
const postSwitchRemainingTurns = Number(Math.max(0, expectedRemainingTurns - 1).toFixed(2));
|
|
225
|
+
|
|
226
|
+
return {
|
|
227
|
+
expectedRemainingTurns,
|
|
228
|
+
postSwitchRemainingTurns,
|
|
229
|
+
expectedRemainingRequests,
|
|
230
|
+
empiricalResidual: expectedRemainingRequests,
|
|
231
|
+
empiricalResidualRequests,
|
|
232
|
+
callsUntilCompact,
|
|
233
|
+
requestsPerTurn,
|
|
234
|
+
requestsPerTurnSource: rptInfo.source,
|
|
235
|
+
horizonUnit: 'turns',
|
|
236
|
+
priorNativeUnit: EMPIRICAL_SESSION_API_CALL_PRIOR.unit,
|
|
237
|
+
priorBucket,
|
|
238
|
+
isPlaceholderPrior,
|
|
239
|
+
priorProvenance,
|
|
240
|
+
initialPrefixTokensUsed: baselinePrefix,
|
|
241
|
+
contextCeilingUsed: contextCeiling,
|
|
242
|
+
autoCompactLimitTokensUsed: autoCompactLimitTokens,
|
|
243
|
+
source
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export const FLIGHT_MODES = Object.freeze({
|
|
248
|
+
OFF: 'OFF',
|
|
249
|
+
SILENT: 'SILENT',
|
|
250
|
+
COACH: 'COACH',
|
|
251
|
+
AUTO_PILOT: 'AUTO_PILOT'
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
export const DEFAULT_EXPECTED_OUTPUT_TOKENS = 1500;
|
|
255
|
+
export const DEFAULT_DET09_OUTPUT_DELTA_TOKENS = 800;
|
|
256
|
+
|
|
257
|
+
const PREFIX_INSTRUCTION_FILE_REGEX =
|
|
258
|
+
/(?:^|\/)(?:CLAUDE(?:\.local)?\.md|AGENTS\.md|\.mcp\.json)$|(?:^|\/)\.claude\/(?:CLAUDE\.md|rules\/.+\.md)$/i;
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Checks whether a workspace file path is a top-level prompt-prefix instruction or MCP config file
|
|
262
|
+
* whose mid-session modification invalidates the Anthropic KV-cache prefix (`DET-09`).
|
|
263
|
+
*
|
|
264
|
+
* @param {string} [filePath='']
|
|
265
|
+
* @returns {boolean}
|
|
266
|
+
*/
|
|
267
|
+
export function isPrefixInstructionFile(filePath = '') {
|
|
268
|
+
const norm = String(filePath || '').trim().replace(/\\/g, '/');
|
|
269
|
+
if (!norm) return false;
|
|
270
|
+
return PREFIX_INSTRUCTION_FILE_REGEX.test(norm);
|
|
271
|
+
}
|
|
272
|
+
export const DEFAULT_ADVISORY_COOLDOWN_TURNS = 3;
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* Maps an active model to its natural one-tier downshift peer for cross-model break-even C* (`ISS-006`).
|
|
276
|
+
* Break-even thresholds are computed dynamically from `anthropicModelCatalog.json` rates at runtime.
|
|
277
|
+
* - claude-fable-5-2 / claude-fable-5-1 -> claude-opus-5-5
|
|
278
|
+
* - claude-opus-5-5 -> claude-sonnet-5-5
|
|
279
|
+
* - claude-opus-4-6 / claude-opus-4-5 -> claude-sonnet-4-6
|
|
280
|
+
* - claude-sonnet-5-5 -> claude-haiku-5-5
|
|
281
|
+
* - claude-sonnet-4-6 / claude-sonnet-4-5 -> claude-haiku-4-5
|
|
282
|
+
* - claude-haiku-4-5 -> claude-haiku-5-5
|
|
283
|
+
*
|
|
284
|
+
* @param {string} [modelId='claude-opus-5-5']
|
|
285
|
+
* @returns {string}
|
|
286
|
+
*/
|
|
287
|
+
export function resolveNaturalDownshiftPeer(modelId = 'claude-opus-5-5') {
|
|
288
|
+
const norm = normalizeModelId(modelId);
|
|
289
|
+
switch (norm) {
|
|
290
|
+
case 'claude-mythos-5-2':
|
|
291
|
+
case 'claude-mythos-5-1':
|
|
292
|
+
case 'claude-mythos-5':
|
|
293
|
+
case 'claude-fable-5-2':
|
|
294
|
+
case 'claude-fable-5-1':
|
|
295
|
+
case 'claude-fable-5':
|
|
296
|
+
return 'claude-opus-5-5';
|
|
297
|
+
case 'claude-opus-5-5':
|
|
298
|
+
return 'claude-sonnet-5-5';
|
|
299
|
+
case 'claude-opus-5':
|
|
300
|
+
return 'claude-sonnet-5';
|
|
301
|
+
case 'claude-opus-4-8':
|
|
302
|
+
case 'claude-opus-4-7':
|
|
303
|
+
case 'claude-opus-4-6':
|
|
304
|
+
case 'claude-opus-4-5':
|
|
305
|
+
case 'claude-opus-4-1':
|
|
306
|
+
case 'claude-opus-4-0':
|
|
307
|
+
return 'claude-sonnet-4-6';
|
|
308
|
+
case 'claude-sonnet-5-5':
|
|
309
|
+
case 'claude-sonnet-5':
|
|
310
|
+
return 'claude-haiku-5-5';
|
|
311
|
+
case 'claude-sonnet-4-6':
|
|
312
|
+
case 'claude-sonnet-4-5':
|
|
313
|
+
case 'claude-sonnet-4-0':
|
|
314
|
+
return 'claude-haiku-4-5';
|
|
315
|
+
case 'claude-3-7-sonnet':
|
|
316
|
+
case 'claude-3-5-sonnet':
|
|
317
|
+
case 'claude-3-5-haiku':
|
|
318
|
+
return 'claude-3-5-haiku';
|
|
319
|
+
case 'claude-haiku-4-5':
|
|
320
|
+
case 'claude-haiku-5-5':
|
|
321
|
+
return 'claude-haiku-5-5';
|
|
322
|
+
default:
|
|
323
|
+
return 'claude-sonnet-5-5';
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* Normalizes any flight mode string into `'OFF' | 'SILENT' | 'COACH' | 'AUTO_PILOT'`.
|
|
329
|
+
* @param {string} [rawMode='COACH']
|
|
330
|
+
* @returns {'OFF'|'SILENT'|'COACH'|'AUTO_PILOT'}
|
|
331
|
+
*/
|
|
332
|
+
export function normalizeFlightMode(rawMode = 'COACH') {
|
|
333
|
+
const cleaned = String(rawMode || 'COACH')
|
|
334
|
+
.toUpperCase()
|
|
335
|
+
.trim()
|
|
336
|
+
.replace(/[-\s]+/g, '_');
|
|
337
|
+
if (cleaned === 'OFF' || cleaned === 'DISABLED') return FLIGHT_MODES.OFF;
|
|
338
|
+
if (cleaned === 'SILENT' || cleaned === 'QUIET' || cleaned === 'MUTE') {
|
|
339
|
+
return FLIGHT_MODES.SILENT;
|
|
340
|
+
}
|
|
341
|
+
if (cleaned === 'AUTO_PILOT' || cleaned === 'AUTOPILOT' || cleaned === 'AUTO') {
|
|
342
|
+
return FLIGHT_MODES.AUTO_PILOT;
|
|
343
|
+
}
|
|
344
|
+
return FLIGHT_MODES.COACH;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* Checks whether a flight mode suppresses non-security coach advisories (`OFF` or `SILENT`).
|
|
349
|
+
* @param {string} [mode='COACH']
|
|
350
|
+
* @returns {boolean}
|
|
351
|
+
*/
|
|
352
|
+
export function isSilentOrOffMode(mode = 'COACH') {
|
|
353
|
+
const norm = normalizeFlightMode(mode);
|
|
354
|
+
return norm === FLIGHT_MODES.OFF || norm === FLIGHT_MODES.SILENT;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* Computes the exact cross-model break-even cached token threshold `C*` and USD turn costs.
|
|
359
|
+
*
|
|
360
|
+
* Equation:
|
|
361
|
+
* C* = (O * (P_out,curr - P_out,target)) / (P_write5m,target - P_read,curr)
|
|
362
|
+
*
|
|
363
|
+
* When `cachedTokens > C*` on a warm cache, switching from `currentModel` to `targetModel`
|
|
364
|
+
* costs MORE in cold `1.25x` prefix rewrite than it saves on output tokens.
|
|
365
|
+
*
|
|
366
|
+
* @param {object} [params={}]
|
|
367
|
+
* @param {string} [params.currentModel='claude-opus-5-5']
|
|
368
|
+
* @param {string} [params.targetModel='claude-sonnet-5-5']
|
|
369
|
+
* @param {number} [params.expectedOutputTokens=1500]
|
|
370
|
+
* @param {number} [params.cachedTokens=0]
|
|
371
|
+
* @param {number} [params.uncachedDeltaTokens=0]
|
|
372
|
+
* @param {boolean} [params.cacheWarm=true]
|
|
373
|
+
* @param {'5m'|'1h'} [params.cacheTtlTier='5m']
|
|
374
|
+
* @param {object} [options={}]
|
|
375
|
+
*/
|
|
376
|
+
export function computeBreakEvenCachedTokens(params = {}, options = {}) {
|
|
377
|
+
const rawCurrentModel = params.currentModel ?? 'claude-opus-5-5';
|
|
378
|
+
const rawTargetModel = params.targetModel ?? 'claude-sonnet-5-5';
|
|
379
|
+
const expectedOutputTokens = Math.max(
|
|
380
|
+
0,
|
|
381
|
+
Number(params.expectedOutputTokens ?? DEFAULT_EXPECTED_OUTPUT_TOKENS)
|
|
382
|
+
);
|
|
383
|
+
const cachedTokens = Math.max(0, Number(params.cachedTokens ?? 0));
|
|
384
|
+
const uncachedDeltaTokens = Math.max(0, Number(params.uncachedDeltaTokens ?? 0));
|
|
385
|
+
const uncachedWriteTokens = Math.max(0, Number(params.uncachedWriteTokens ?? 0));
|
|
386
|
+
const request1UncachedTokens = uncachedDeltaTokens + uncachedWriteTokens;
|
|
387
|
+
const cacheWarm = params.cacheWarm !== undefined ? Boolean(params.cacheWarm) : cachedTokens > 0;
|
|
388
|
+
const ttlTier = params.cacheTtlTier === '1h' ? '1h' : '5m';
|
|
389
|
+
|
|
390
|
+
const totalPromptTokens = Math.max(
|
|
391
|
+
cachedTokens + request1UncachedTokens,
|
|
392
|
+
computeTotalPromptTokens(params)
|
|
393
|
+
);
|
|
394
|
+
|
|
395
|
+
const currentKnown =
|
|
396
|
+
params.currentModel !== undefined ? isKnownCatalogModel(rawCurrentModel, options) : true;
|
|
397
|
+
const targetKnown =
|
|
398
|
+
params.targetModel !== undefined ? isKnownCatalogModel(rawTargetModel, options) : true;
|
|
399
|
+
|
|
400
|
+
if (!currentKnown || !targetKnown) {
|
|
401
|
+
const unknownModelIds = [];
|
|
402
|
+
if (!currentKnown) unknownModelIds.push(String(rawCurrentModel));
|
|
403
|
+
if (!targetKnown && String(rawTargetModel) !== String(rawCurrentModel)) {
|
|
404
|
+
unknownModelIds.push(String(rawTargetModel));
|
|
405
|
+
}
|
|
406
|
+
const rawRemaining = params.expectedRemainingTurns ?? options.expectedRemainingTurns;
|
|
407
|
+
const hasExplicitRemaining =
|
|
408
|
+
rawRemaining !== undefined &&
|
|
409
|
+
rawRemaining !== null &&
|
|
410
|
+
Number.isFinite(Number(rawRemaining));
|
|
411
|
+
const useEmpirical = Boolean(
|
|
412
|
+
params.useEmpiricalHorizonPrior ?? options.useEmpiricalHorizonPrior
|
|
413
|
+
);
|
|
414
|
+
return {
|
|
415
|
+
unknownModel: true,
|
|
416
|
+
unknownModelIds,
|
|
417
|
+
currentModel: String(rawCurrentModel || ''),
|
|
418
|
+
targetModel: String(rawTargetModel || ''),
|
|
419
|
+
expectedOutputTokens,
|
|
420
|
+
cachedTokens,
|
|
421
|
+
uncachedDeltaTokens,
|
|
422
|
+
uncachedWriteTokens,
|
|
423
|
+
totalPromptTokens,
|
|
424
|
+
cacheWarm,
|
|
425
|
+
cacheTtlTier: ttlTier,
|
|
426
|
+
writeMultiplierLabel: ttlTier === '1h' ? '2.0x' : '1.25x',
|
|
427
|
+
isCapabilityUpshift: false,
|
|
428
|
+
breakEvenTokens: null,
|
|
429
|
+
rates: null,
|
|
430
|
+
stayOnCurrentModelUSD: null,
|
|
431
|
+
switchToTargetModelUSD: null,
|
|
432
|
+
coldWritePenaltyUSD: null,
|
|
433
|
+
perTurnPostSwitchSavingUSD: null,
|
|
434
|
+
averagePostSwitchSavingUSD: null,
|
|
435
|
+
paybackTurns: null,
|
|
436
|
+
paybackWarmRequests: null,
|
|
437
|
+
switchTurnWarmReads: 0,
|
|
438
|
+
totalWarmReadsToPayback: null,
|
|
439
|
+
asymptoticWarmRequestRatio: null,
|
|
440
|
+
contextGrowthPerTurn: Math.max(0, Number(params.contextGrowthPerTurn ?? 0)),
|
|
441
|
+
expectedRemainingTurns: hasExplicitRemaining ? Math.max(0, Number(rawRemaining)) : null,
|
|
442
|
+
postSwitchRemainingTurns: hasExplicitRemaining ? Math.max(0, Number(rawRemaining)) : null,
|
|
443
|
+
horizonMaxCachedTokens: null,
|
|
444
|
+
horizonNetSavingsUSD: null,
|
|
445
|
+
horizonPriorSource: null,
|
|
446
|
+
ruleVersion: hasExplicitRemaining || useEmpirical ? 'rule_v2' : 'rule_v1',
|
|
447
|
+
shouldHold: false,
|
|
448
|
+
shouldHoldModel: false
|
|
449
|
+
};
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
const currentModel = normalizeModelId(rawCurrentModel);
|
|
453
|
+
const targetModel = normalizeModelId(rawTargetModel);
|
|
454
|
+
const currRates = resolveEffectiveRates(rawCurrentModel, totalPromptTokens, options);
|
|
455
|
+
const targetRates = resolveEffectiveRates(rawTargetModel, totalPromptTokens, options);
|
|
456
|
+
|
|
457
|
+
const pOutCurr = currRates.outputPer1M;
|
|
458
|
+
const pOutTarget = targetRates.outputPer1M;
|
|
459
|
+
const pReadCurr = currRates.readPer1M;
|
|
460
|
+
const pWriteCurr = ttlTier === '1h' ? currRates.write1hPer1M : currRates.write5mPer1M;
|
|
461
|
+
const pWriteTarget = ttlTier === '1h' ? targetRates.write1hPer1M : targetRates.write5mPer1M;
|
|
462
|
+
|
|
463
|
+
const isCapabilityUpshift = pOutCurr <= pOutTarget;
|
|
464
|
+
|
|
465
|
+
// Resolve requests/turn and post-switch turn horizon BEFORE cost math so multi-request turns scale read savings cleanly.
|
|
466
|
+
const observedContextCeilingRaw = Number(
|
|
467
|
+
params.contextCeiling ?? params.contextWindowSize ?? options.contextCeiling
|
|
468
|
+
);
|
|
469
|
+
const resolvedContextCeiling =
|
|
470
|
+
Number.isFinite(observedContextCeilingRaw) && observedContextCeilingRaw >= 10_000
|
|
471
|
+
? Math.round(observedContextCeilingRaw)
|
|
472
|
+
: currRates.contextCeiling;
|
|
473
|
+
const rptInfo = resolveRequestsPerTurn(params, options);
|
|
474
|
+
|
|
475
|
+
const rawRemainingTurns = params.expectedRemainingTurns ?? options.expectedRemainingTurns;
|
|
476
|
+
const hasExplicitRemaining =
|
|
477
|
+
rawRemainingTurns !== undefined &&
|
|
478
|
+
rawRemainingTurns !== null &&
|
|
479
|
+
Number.isFinite(Number(rawRemainingTurns));
|
|
480
|
+
const useEmpiricalHorizonPrior = Boolean(
|
|
481
|
+
params.useEmpiricalHorizonPrior ?? options.useEmpiricalHorizonPrior
|
|
482
|
+
);
|
|
483
|
+
let expectedRemainingTurns = null;
|
|
484
|
+
let postSwitchRemainingTurns = null;
|
|
485
|
+
let expectedRemainingRequests = null;
|
|
486
|
+
let horizonPriorSource = null;
|
|
487
|
+
let priorBucket = null;
|
|
488
|
+
let priorNativeUnit = null;
|
|
489
|
+
let requestsPerTurnUsed = rptInfo.requestsPerTurn;
|
|
490
|
+
let isPlaceholderPrior = false;
|
|
491
|
+
let priorProvenance = null;
|
|
492
|
+
let initialPrefixTokensUsed =
|
|
493
|
+
Number(params.initialPrefixTokens) > 0 ? Number(params.initialPrefixTokens) : null;
|
|
494
|
+
if (hasExplicitRemaining) {
|
|
495
|
+
expectedRemainingTurns = Math.max(0, Number(rawRemainingTurns));
|
|
496
|
+
const explicitIncludesSwitchTurn = Boolean(params.horizonIncludesSwitchTurn);
|
|
497
|
+
postSwitchRemainingTurns = explicitIncludesSwitchTurn
|
|
498
|
+
? Number(Math.max(0, expectedRemainingTurns - 1).toFixed(2))
|
|
499
|
+
: expectedRemainingTurns;
|
|
500
|
+
horizonPriorSource = 'explicit';
|
|
501
|
+
priorBucket = 'explicit_turns';
|
|
502
|
+
priorNativeUnit = 'turns';
|
|
503
|
+
} else if (useEmpiricalHorizonPrior) {
|
|
504
|
+
const prior = estimateEmpiricalRemainingTurns(
|
|
505
|
+
{
|
|
506
|
+
turnsCompleted: params.turnsCompleted ?? params.currentTurn ?? 0,
|
|
507
|
+
apiCallsCompleted: params.apiCallsCompleted,
|
|
508
|
+
requestsPerTurn: params.requestsPerTurn,
|
|
509
|
+
contextGrowthPerTurn: params.contextGrowthPerTurn,
|
|
510
|
+
cachedTokens,
|
|
511
|
+
contextCeiling: resolvedContextCeiling,
|
|
512
|
+
autoCompactLimitTokens: params.autoCompactLimitTokens,
|
|
513
|
+
initialPrefixTokens: params.initialPrefixTokens
|
|
514
|
+
},
|
|
515
|
+
options
|
|
516
|
+
);
|
|
517
|
+
expectedRemainingTurns = prior.expectedRemainingTurns;
|
|
518
|
+
postSwitchRemainingTurns = prior.postSwitchRemainingTurns;
|
|
519
|
+
expectedRemainingRequests = prior.expectedRemainingRequests;
|
|
520
|
+
horizonPriorSource = prior.source;
|
|
521
|
+
priorBucket = prior.priorBucket;
|
|
522
|
+
priorNativeUnit = prior.priorNativeUnit;
|
|
523
|
+
requestsPerTurnUsed = prior.requestsPerTurn;
|
|
524
|
+
isPlaceholderPrior = prior.isPlaceholderPrior;
|
|
525
|
+
priorProvenance = prior.priorProvenance;
|
|
526
|
+
initialPrefixTokensUsed = prior.initialPrefixTokensUsed;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
let breakEvenTokens = 0;
|
|
530
|
+
if (currentModel === targetModel || isCapabilityUpshift) {
|
|
531
|
+
breakEvenTokens = 0;
|
|
532
|
+
} else {
|
|
533
|
+
const numeratorUSD =
|
|
534
|
+
(expectedOutputTokens / 1_000_000) * (pOutCurr - pOutTarget) +
|
|
535
|
+
(request1UncachedTokens / 1_000_000) * (pWriteCurr - pWriteTarget);
|
|
536
|
+
const denominator = pWriteTarget - pReadCurr;
|
|
537
|
+
if (numeratorUSD <= 0) {
|
|
538
|
+
breakEvenTokens = 0;
|
|
539
|
+
} else if (denominator <= 0) {
|
|
540
|
+
breakEvenTokens = Infinity;
|
|
541
|
+
} else {
|
|
542
|
+
breakEvenTokens = Math.round((numeratorUSD * 1_000_000) / denominator);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
// Exact USD switch-turn cost: request 1 pays cache write on cold target (and uncachedWriteTokens even on stay); requests 2..R read at warm rate.
|
|
547
|
+
const effectiveRpt = currentModel === targetModel ? 1 : Math.max(1, requestsPerTurnUsed);
|
|
548
|
+
const extraWarmReadsOnSwitchTurn = Math.max(0, effectiveRpt - 1);
|
|
549
|
+
const combinedReq1Tokens = cachedTokens + request1UncachedTokens;
|
|
550
|
+
const stayPrefixCostUSD = cacheWarm
|
|
551
|
+
? (cachedTokens / 1_000_000) * pReadCurr +
|
|
552
|
+
(request1UncachedTokens / 1_000_000) * pWriteCurr +
|
|
553
|
+
extraWarmReadsOnSwitchTurn * (combinedReq1Tokens / 1_000_000) * pReadCurr
|
|
554
|
+
: (combinedReq1Tokens / 1_000_000) * pWriteCurr +
|
|
555
|
+
extraWarmReadsOnSwitchTurn * (combinedReq1Tokens / 1_000_000) * pReadCurr;
|
|
556
|
+
const stayOutputCostUSD = (expectedOutputTokens / 1_000_000) * pOutCurr;
|
|
557
|
+
const stayOnCurrentModelUSD = stayPrefixCostUSD + stayOutputCostUSD;
|
|
558
|
+
|
|
559
|
+
// Switching to a different model invalidates the isolated per-model cache on Request 1, forcing a cold write
|
|
560
|
+
const switchPrefixCostUSD =
|
|
561
|
+
currentModel === targetModel && cacheWarm
|
|
562
|
+
? stayPrefixCostUSD
|
|
563
|
+
: (combinedReq1Tokens / 1_000_000) * pWriteTarget +
|
|
564
|
+
extraWarmReadsOnSwitchTurn * (combinedReq1Tokens / 1_000_000) * targetRates.readPer1M;
|
|
565
|
+
const switchOutputCostUSD = (expectedOutputTokens / 1_000_000) * pOutTarget;
|
|
566
|
+
const switchToTargetModelUSD = switchPrefixCostUSD + switchOutputCostUSD;
|
|
567
|
+
|
|
568
|
+
const coldWritePenaltyUSD = Number(
|
|
569
|
+
(switchToTargetModelUSD - stayOnCurrentModelUSD).toFixed(6)
|
|
570
|
+
);
|
|
571
|
+
|
|
572
|
+
// Horizon-aware payback (`C1e` / `rule_v2`, opt-in via `expectedRemainingTurns` or `useEmpiricalHorizonPrior`):
|
|
573
|
+
// perTurnPostSwitchSavingUSD = R * ((C + cw_1)/1M) * (P_read,curr - P_read,target)
|
|
574
|
+
// + (Delta_post/1M) * (P_write,curr - P_write,target)
|
|
575
|
+
// + (O/1M) * (P_out,curr - P_out,target)
|
|
576
|
+
// paybackTurns = coldWritePenaltyUSD / perTurnPostSwitchSavingUSD
|
|
577
|
+
// When `expectedRemainingTurns` is unset (`undefined`/`null`), `shouldHoldModel` preserves `rule_v1`.
|
|
578
|
+
const postSwitchDeltaTokens = Math.max(
|
|
579
|
+
0,
|
|
580
|
+
Number(params.postSwitchDeltaTokens ?? uncachedDeltaTokens)
|
|
581
|
+
);
|
|
582
|
+
const contextGrowthPerTurn = Math.max(0, Number(params.contextGrowthPerTurn ?? 0));
|
|
583
|
+
const effectivePostSwitchDeltaTokens =
|
|
584
|
+
contextGrowthPerTurn > 0 && params.postSwitchDeltaTokens === undefined
|
|
585
|
+
? contextGrowthPerTurn
|
|
586
|
+
: postSwitchDeltaTokens;
|
|
587
|
+
|
|
588
|
+
const rawPerTurnPostSwitchSavingUSD =
|
|
589
|
+
currentModel === targetModel || isCapabilityUpshift
|
|
590
|
+
? 0
|
|
591
|
+
: effectiveRpt *
|
|
592
|
+
(combinedReq1Tokens / 1_000_000) *
|
|
593
|
+
(pReadCurr - targetRates.readPer1M) +
|
|
594
|
+
(effectivePostSwitchDeltaTokens / 1_000_000) * (pWriteCurr - pWriteTarget) +
|
|
595
|
+
(expectedOutputTokens / 1_000_000) * (pOutCurr - pOutTarget);
|
|
596
|
+
const perTurnPostSwitchSavingUSD = Number(
|
|
597
|
+
Math.max(0, rawPerTurnPostSwitchSavingUSD).toFixed(6)
|
|
598
|
+
);
|
|
599
|
+
|
|
600
|
+
const growthCoeffA =
|
|
601
|
+
currentModel === targetModel || isCapabilityUpshift || contextGrowthPerTurn <= 0
|
|
602
|
+
? 0
|
|
603
|
+
: 0.5 *
|
|
604
|
+
effectiveRpt *
|
|
605
|
+
(contextGrowthPerTurn / 1_000_000) *
|
|
606
|
+
(pReadCurr - targetRates.readPer1M);
|
|
607
|
+
|
|
608
|
+
const hasHorizonTurns = postSwitchRemainingTurns !== null;
|
|
609
|
+
const averagePostSwitchSavingUSD =
|
|
610
|
+
hasHorizonTurns && postSwitchRemainingTurns > 1 && growthCoeffA !== 0
|
|
611
|
+
? Number(
|
|
612
|
+
Math.max(
|
|
613
|
+
0,
|
|
614
|
+
rawPerTurnPostSwitchSavingUSD + (postSwitchRemainingTurns - 1) * growthCoeffA
|
|
615
|
+
).toFixed(6)
|
|
616
|
+
)
|
|
617
|
+
: perTurnPostSwitchSavingUSD;
|
|
618
|
+
|
|
619
|
+
let paybackTurns;
|
|
620
|
+
if (coldWritePenaltyUSD <= 0) {
|
|
621
|
+
paybackTurns = 0;
|
|
622
|
+
} else if (growthCoeffA > 0) {
|
|
623
|
+
const s0 = Math.max(0, rawPerTurnPostSwitchSavingUSD);
|
|
624
|
+
const bCoeff = s0 - growthCoeffA;
|
|
625
|
+
const disc = bCoeff * bCoeff + 4 * growthCoeffA * coldWritePenaltyUSD;
|
|
626
|
+
paybackTurns =
|
|
627
|
+
disc >= 0
|
|
628
|
+
? Number(((-bCoeff + Math.sqrt(disc)) / (2 * growthCoeffA)).toFixed(4))
|
|
629
|
+
: Infinity;
|
|
630
|
+
} else {
|
|
631
|
+
paybackTurns =
|
|
632
|
+
perTurnPostSwitchSavingUSD > 0
|
|
633
|
+
? Number((coldWritePenaltyUSD / perTurnPostSwitchSavingUSD).toFixed(4))
|
|
634
|
+
: Infinity;
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
const paybackWarmRequests =
|
|
638
|
+
coldWritePenaltyUSD <= 0
|
|
639
|
+
? 0
|
|
640
|
+
: Number.isFinite(paybackTurns)
|
|
641
|
+
? Number((paybackTurns * effectiveRpt).toFixed(2))
|
|
642
|
+
: Infinity;
|
|
643
|
+
const switchTurnWarmReads = extraWarmReadsOnSwitchTurn;
|
|
644
|
+
const totalWarmReadsToPayback =
|
|
645
|
+
coldWritePenaltyUSD <= 0
|
|
646
|
+
? 0
|
|
647
|
+
: Number.isFinite(paybackWarmRequests)
|
|
648
|
+
? Number((switchTurnWarmReads + paybackWarmRequests).toFixed(2))
|
|
649
|
+
: Infinity;
|
|
650
|
+
const warmReadSpread = pReadCurr - targetRates.readPer1M;
|
|
651
|
+
const asymptoticWarmRequestRatio =
|
|
652
|
+
currentModel === targetModel || isCapabilityUpshift || warmReadSpread <= 0
|
|
653
|
+
? null
|
|
654
|
+
: Number(((pWriteTarget - pReadCurr) / warmReadSpread).toFixed(2));
|
|
655
|
+
|
|
656
|
+
// Exact horizon-aware break-even context C_max for post-switch turns H_post and requests/turn R:
|
|
657
|
+
// C_max = (O * (P_out,A - P_out,B) * (H_post + 1)) / ((P_write,B - P_read,A) - ((H_post + 1) * R - 1) * (P_read,A - P_read,B))
|
|
658
|
+
let horizonMaxCachedTokens = null;
|
|
659
|
+
if (hasHorizonTurns) {
|
|
660
|
+
if (currentModel === targetModel || isCapabilityUpshift) {
|
|
661
|
+
horizonMaxCachedTokens = 0;
|
|
662
|
+
} else {
|
|
663
|
+
const warmReadDiffPer1M = pReadCurr - targetRates.readPer1M;
|
|
664
|
+
const postSwitchWarmReadsTotal = (postSwitchRemainingTurns + 1) * effectiveRpt - 1;
|
|
665
|
+
const cMaxDen = (pWriteTarget - pReadCurr) - postSwitchWarmReadsTotal * warmReadDiffPer1M;
|
|
666
|
+
const cMaxNumUSD =
|
|
667
|
+
(expectedOutputTokens / 1_000_000) *
|
|
668
|
+
(pOutCurr - pOutTarget) *
|
|
669
|
+
(postSwitchRemainingTurns + 1);
|
|
670
|
+
if (cMaxDen <= 0) {
|
|
671
|
+
horizonMaxCachedTokens = Infinity;
|
|
672
|
+
} else if (cMaxNumUSD <= 0) {
|
|
673
|
+
horizonMaxCachedTokens = 0;
|
|
674
|
+
} else {
|
|
675
|
+
horizonMaxCachedTokens = Math.round((cMaxNumUSD * 1_000_000) / cMaxDen);
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
const horizonNetSavingsUSD = hasHorizonTurns
|
|
681
|
+
? Number(
|
|
682
|
+
(
|
|
683
|
+
postSwitchRemainingTurns *
|
|
684
|
+
(Math.max(0, rawPerTurnPostSwitchSavingUSD) +
|
|
685
|
+
(postSwitchRemainingTurns > 1 ? (postSwitchRemainingTurns - 1) * growthCoeffA : 0)) -
|
|
686
|
+
coldWritePenaltyUSD
|
|
687
|
+
).toFixed(6)
|
|
688
|
+
)
|
|
689
|
+
: null;
|
|
690
|
+
|
|
691
|
+
const singleTurnShouldHold = Boolean(
|
|
692
|
+
currentModel !== targetModel &&
|
|
693
|
+
!isCapabilityUpshift &&
|
|
694
|
+
cacheWarm &&
|
|
695
|
+
coldWritePenaltyUSD > 0 &&
|
|
696
|
+
cachedTokens > breakEvenTokens
|
|
697
|
+
);
|
|
698
|
+
|
|
699
|
+
// Never hold/deny on capability upshifts, coldWritePenaltyUSD <= 0, or unbounded horizon limit C_max = Infinity
|
|
700
|
+
const shouldHoldModel = hasHorizonTurns
|
|
701
|
+
? Boolean(
|
|
702
|
+
singleTurnShouldHold &&
|
|
703
|
+
horizonMaxCachedTokens !== Infinity &&
|
|
704
|
+
postSwitchRemainingTurns < paybackTurns
|
|
705
|
+
)
|
|
706
|
+
: singleTurnShouldHold;
|
|
707
|
+
|
|
708
|
+
return {
|
|
709
|
+
unknownModel: false,
|
|
710
|
+
unknownModelIds: [],
|
|
711
|
+
currentModel,
|
|
712
|
+
targetModel,
|
|
713
|
+
expectedOutputTokens,
|
|
714
|
+
cachedTokens,
|
|
715
|
+
uncachedDeltaTokens,
|
|
716
|
+
uncachedWriteTokens,
|
|
717
|
+
totalPromptTokens,
|
|
718
|
+
cacheWarm,
|
|
719
|
+
cacheTtlTier: ttlTier,
|
|
720
|
+
writeMultiplierLabel: ttlTier === '1h' ? '2.0x' : '1.25x',
|
|
721
|
+
isCapabilityUpshift,
|
|
722
|
+
breakEvenTokens,
|
|
723
|
+
horizonMaxCachedTokens,
|
|
724
|
+
rates: {
|
|
725
|
+
currentOutputPer1M: pOutCurr,
|
|
726
|
+
targetOutputPer1M: pOutTarget,
|
|
727
|
+
currentReadPer1M: pReadCurr,
|
|
728
|
+
targetReadPer1M: targetRates.readPer1M,
|
|
729
|
+
currentWritePer1M: pWriteCurr,
|
|
730
|
+
targetWritePer1M: pWriteTarget
|
|
731
|
+
},
|
|
732
|
+
stayOnCurrentModelUSD: Number(stayOnCurrentModelUSD.toFixed(6)),
|
|
733
|
+
switchToTargetModelUSD: Number(switchToTargetModelUSD.toFixed(6)),
|
|
734
|
+
coldWritePenaltyUSD,
|
|
735
|
+
perTurnPostSwitchSavingUSD,
|
|
736
|
+
averagePostSwitchSavingUSD,
|
|
737
|
+
paybackTurns,
|
|
738
|
+
paybackWarmRequests,
|
|
739
|
+
switchTurnWarmReads,
|
|
740
|
+
totalWarmReadsToPayback,
|
|
741
|
+
asymptoticWarmRequestRatio,
|
|
742
|
+
contextGrowthPerTurn,
|
|
743
|
+
expectedRemainingTurns,
|
|
744
|
+
postSwitchRemainingTurns,
|
|
745
|
+
expectedRemainingRequests,
|
|
746
|
+
horizonUnit: 'turns',
|
|
747
|
+
priorNativeUnit,
|
|
748
|
+
priorBucket,
|
|
749
|
+
requestsPerTurn: requestsPerTurnUsed,
|
|
750
|
+
isPlaceholderPrior,
|
|
751
|
+
priorProvenance,
|
|
752
|
+
contextCeilingUsed: resolvedContextCeiling,
|
|
753
|
+
initialPrefixTokensUsed,
|
|
754
|
+
horizonNetSavingsUSD,
|
|
755
|
+
horizonPriorSource,
|
|
756
|
+
ruleVersion: hasHorizonTurns ? 'rule_v2' : 'rule_v1',
|
|
757
|
+
shouldHold: shouldHoldModel,
|
|
758
|
+
shouldHoldModel
|
|
759
|
+
};
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
/**
|
|
763
|
+
* Queue for deferring top-level `effort`, `thinking`, `system_prompt`, or `mcp_tools`
|
|
764
|
+
* mutations until immediately after context compaction (`PostCompact`), avoiding mid-session
|
|
765
|
+
* full-prefix cache invalidation (`DET-09`).
|
|
766
|
+
*/
|
|
767
|
+
export class PostCompactMutationQueue {
|
|
768
|
+
/**
|
|
769
|
+
* @param {Array<object>} [initialItems=[]]
|
|
770
|
+
*/
|
|
771
|
+
constructor(initialItems = []) {
|
|
772
|
+
this.items = Array.isArray(initialItems) ? [...initialItems] : [];
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
/**
|
|
776
|
+
* Enqueues or updates a deferred mutation keyed by `(type, key)`.
|
|
777
|
+
* @param {object} mutation
|
|
778
|
+
* @param {'effort'|'thinking'|'speed'|'system_prompt'|'mcp_tools'|'model'} mutation.type
|
|
779
|
+
* @param {string} [mutation.key]
|
|
780
|
+
* @param {any} mutation.value
|
|
781
|
+
* @param {string} [mutation.reason]
|
|
782
|
+
* @param {number} [mutation.avoidedRewritePenaltyUSD]
|
|
783
|
+
* @param {number} [mutation.cachedTokens]
|
|
784
|
+
* @param {number} [mutation.savedTokens]
|
|
785
|
+
* @returns {object} Enqueued entry
|
|
786
|
+
*/
|
|
787
|
+
enqueue(mutation = {}) {
|
|
788
|
+
const type = String(mutation.type || 'effort');
|
|
789
|
+
const key = String(mutation.key || type);
|
|
790
|
+
const entry = {
|
|
791
|
+
type,
|
|
792
|
+
key,
|
|
793
|
+
value: mutation.value,
|
|
794
|
+
reason: mutation.reason || 'Deferred to PostCompact to preserve warm Anthropic prompt cache prefix',
|
|
795
|
+
avoidedRewritePenaltyUSD: Number(mutation.avoidedRewritePenaltyUSD || 0),
|
|
796
|
+
cachedTokens: Math.max(0, Number(mutation.cachedTokens || 0)),
|
|
797
|
+
savedTokens: Math.max(0, Number(mutation.savedTokens || 0)),
|
|
798
|
+
enqueuedAt: mutation.enqueuedAt || Date.now()
|
|
799
|
+
};
|
|
800
|
+
|
|
801
|
+
const existingIdx = this.items.findIndex((item) => item.type === type && item.key === key);
|
|
802
|
+
if (existingIdx >= 0) {
|
|
803
|
+
this.items[existingIdx] = entry;
|
|
804
|
+
} else {
|
|
805
|
+
this.items.push(entry);
|
|
806
|
+
}
|
|
807
|
+
return entry;
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
/**
|
|
811
|
+
* Returns a shallow copy of all pending mutations without removing them.
|
|
812
|
+
* @returns {Array<object>}
|
|
813
|
+
*/
|
|
814
|
+
peekAll() {
|
|
815
|
+
return [...this.items];
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
/**
|
|
819
|
+
* Returns the number of queued mutations.
|
|
820
|
+
* @returns {number}
|
|
821
|
+
*/
|
|
822
|
+
size() {
|
|
823
|
+
return this.items.length;
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
/**
|
|
827
|
+
* Checks whether any mutations are waiting for compaction.
|
|
828
|
+
* @returns {boolean}
|
|
829
|
+
*/
|
|
830
|
+
hasPending() {
|
|
831
|
+
return this.items.length > 0;
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
/**
|
|
835
|
+
* Flushes and returns all queued mutations on `PostCompact` so they apply at zero extra rewrite cost.
|
|
836
|
+
* @param {object} [context={}]
|
|
837
|
+
* @returns {{ flushedCount: number, appliedMutations: Array<object>, totalAvoidedPenaltyUSD: number, flushedAt: number }}
|
|
838
|
+
*/
|
|
839
|
+
flush(context = {}) {
|
|
840
|
+
const appliedMutations = [...this.items];
|
|
841
|
+
this.items = [];
|
|
842
|
+
const totalAvoidedPenaltyUSD = Number(
|
|
843
|
+
appliedMutations
|
|
844
|
+
.reduce((acc, item) => acc + Number(item.avoidedRewritePenaltyUSD || 0), 0)
|
|
845
|
+
.toFixed(6)
|
|
846
|
+
);
|
|
847
|
+
return {
|
|
848
|
+
flushedCount: appliedMutations.length,
|
|
849
|
+
appliedMutations,
|
|
850
|
+
totalAvoidedPenaltyUSD,
|
|
851
|
+
flushedAt: context.nowMs || Date.now()
|
|
852
|
+
};
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
/**
|
|
856
|
+
* Clears the queue.
|
|
857
|
+
*/
|
|
858
|
+
clear() {
|
|
859
|
+
this.items = [];
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
/**
|
|
863
|
+
* Serializes queue for `$.store` or `StateBaton`.
|
|
864
|
+
* @returns {Array<object>}
|
|
865
|
+
*/
|
|
866
|
+
toJSON() {
|
|
867
|
+
return [...this.items];
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
/**
|
|
871
|
+
* Restores a `PostCompactMutationQueue` from serialized array.
|
|
872
|
+
* @param {Array<object>} data
|
|
873
|
+
* @returns {PostCompactMutationQueue}
|
|
874
|
+
*/
|
|
875
|
+
static fromJSON(data) {
|
|
876
|
+
return new PostCompactMutationQueue(Array.isArray(data) ? data : []);
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
/**
|
|
881
|
+
* Hysteresis Lock ensuring loop-triggered escalations (`DET-04` consecutive failures or `DET-05`
|
|
882
|
+
* edit thrashing) stay pinned until active task completion or rewind/branch reset.
|
|
883
|
+
*/
|
|
884
|
+
export class HysteresisLock {
|
|
885
|
+
constructor(initialState = {}) {
|
|
886
|
+
this.locked = Boolean(initialState.locked);
|
|
887
|
+
this.pinnedModel = initialState.pinnedModel || null;
|
|
888
|
+
this.pinnedEffort = initialState.pinnedEffort || null;
|
|
889
|
+
this.reason = initialState.reason || null;
|
|
890
|
+
this.lockedAtTurn = initialState.lockedAtTurn ?? null;
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
/**
|
|
894
|
+
* Pins model/effort due to a loop or thrashing escalation.
|
|
895
|
+
* @param {object} params
|
|
896
|
+
*/
|
|
897
|
+
engage({ model, effort = 'high', reason = 'Loop escalation lock', turn = 0 } = {}) {
|
|
898
|
+
this.locked = true;
|
|
899
|
+
this.pinnedModel = model ? normalizeModelId(model) : this.pinnedModel;
|
|
900
|
+
this.pinnedEffort = effort;
|
|
901
|
+
this.reason = reason;
|
|
902
|
+
this.lockedAtTurn = turn;
|
|
903
|
+
return this.getStatus();
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
/**
|
|
907
|
+
* Releases the lock when the active task completes cleanly.
|
|
908
|
+
*/
|
|
909
|
+
completeActiveTask() {
|
|
910
|
+
this.locked = false;
|
|
911
|
+
this.pinnedModel = null;
|
|
912
|
+
this.pinnedEffort = null;
|
|
913
|
+
this.reason = null;
|
|
914
|
+
this.lockedAtTurn = null;
|
|
915
|
+
return this.getStatus();
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
/**
|
|
919
|
+
* Releases the lock on conversation rewind or git branch reset.
|
|
920
|
+
*/
|
|
921
|
+
resetOnRewindOrBranch() {
|
|
922
|
+
return this.completeActiveTask();
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
/**
|
|
926
|
+
* Returns current lock status.
|
|
927
|
+
*/
|
|
928
|
+
getStatus() {
|
|
929
|
+
return {
|
|
930
|
+
locked: this.locked,
|
|
931
|
+
pinnedModel: this.pinnedModel,
|
|
932
|
+
pinnedEffort: this.pinnedEffort,
|
|
933
|
+
reason: this.reason,
|
|
934
|
+
lockedAtTurn: this.lockedAtTurn
|
|
935
|
+
};
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
/**
|
|
940
|
+
* Anthropic Cache GravityScorer & Flight Computer Router.
|
|
941
|
+
* Supports `OFF | COACH | AUTO_PILOT` modes, 3-turn advisory cooldown,
|
|
942
|
+
* `PreModelSwitch` (`DET-08`) break-even protection, `PostCompactMutationQueue` (`DET-09`),
|
|
943
|
+
* and `Explore`/`Task` Haiku 5.5 subagent leaf delegation.
|
|
944
|
+
*/
|
|
945
|
+
export class CacheGravityRouter {
|
|
946
|
+
/**
|
|
947
|
+
* @param {object} [options={}]
|
|
948
|
+
*/
|
|
949
|
+
constructor(options = {}) {
|
|
950
|
+
this.options = options;
|
|
951
|
+
this.mode = normalizeFlightMode(options.mode || FLIGHT_MODES.COACH);
|
|
952
|
+
this.cooldownTurns = Number(options.cooldownTurns ?? DEFAULT_ADVISORY_COOLDOWN_TURNS);
|
|
953
|
+
this.lastAdvisoryTurn = null;
|
|
954
|
+
this.mutationQueue =
|
|
955
|
+
options.mutationQueue instanceof PostCompactMutationQueue
|
|
956
|
+
? options.mutationQueue
|
|
957
|
+
: new PostCompactMutationQueue(options.queuedMutations || []);
|
|
958
|
+
this.hysteresisLock =
|
|
959
|
+
options.hysteresisLock instanceof HysteresisLock
|
|
960
|
+
? options.hysteresisLock
|
|
961
|
+
: new HysteresisLock(options.hysteresisState || {});
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
/**
|
|
965
|
+
* Updates the Flight Computer operating mode (`OFF | COACH | AUTO_PILOT`).
|
|
966
|
+
* @param {string} mode
|
|
967
|
+
* @returns {'OFF'|'COACH'|'AUTO_PILOT'}
|
|
968
|
+
*/
|
|
969
|
+
setMode(mode) {
|
|
970
|
+
this.mode = normalizeFlightMode(mode);
|
|
971
|
+
return this.mode;
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
/**
|
|
975
|
+
* Checks whether a non-crisis advisory nudge is currently in its 3-turn cooldown window.
|
|
976
|
+
* Unconditional prefix-loss blocks and Haiku 100k cliff crises are exempt from cooldown.
|
|
977
|
+
*
|
|
978
|
+
* @param {number} currentTurn
|
|
979
|
+
* @param {boolean} [isUnconditionalCrisis=false]
|
|
980
|
+
* @returns {boolean}
|
|
981
|
+
*/
|
|
982
|
+
isCooldownActive(currentTurn = 0, isUnconditionalCrisis = false) {
|
|
983
|
+
if (isUnconditionalCrisis) return false;
|
|
984
|
+
if (this.lastAdvisoryTurn === null) return false;
|
|
985
|
+
return currentTurn - this.lastAdvisoryTurn < this.cooldownTurns;
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
/**
|
|
989
|
+
* Evaluates a proposed cross-model switch (`PreModelSwitch` / `DET-08`).
|
|
990
|
+
* When `prompt_cache.warm === true` and `cachedTokens > C*`, blocks main-thread downgrades
|
|
991
|
+
* and recommends offloading routine exploration to an isolated `claude-haiku-5-5` subagent.
|
|
992
|
+
*
|
|
993
|
+
* @param {object} [request={}]
|
|
994
|
+
* @param {string} [request.currentModel='claude-opus-5-5']
|
|
995
|
+
* @param {string} [request.targetModel='claude-sonnet-5-5']
|
|
996
|
+
* @param {number} [request.cachedTokens=0]
|
|
997
|
+
* @param {number} [request.uncachedDeltaTokens=0]
|
|
998
|
+
* @param {number} [request.expectedOutputTokens=1500]
|
|
999
|
+
* @param {boolean} [request.cacheWarm=true]
|
|
1000
|
+
* @param {'5m'|'1h'} [request.cacheTtlTier='5m']
|
|
1001
|
+
* @param {number} [request.currentTurn=0]
|
|
1002
|
+
*/
|
|
1003
|
+
evaluateModelSwitch(request = {}) {
|
|
1004
|
+
const breakEven = computeBreakEvenCachedTokens(request, this.options);
|
|
1005
|
+
const currentTurn = Number(request.currentTurn ?? 0);
|
|
1006
|
+
|
|
1007
|
+
// Check HysteresisLock first
|
|
1008
|
+
if (
|
|
1009
|
+
this.hysteresisLock.locked &&
|
|
1010
|
+
this.hysteresisLock.pinnedModel &&
|
|
1011
|
+
breakEven.targetModel !== this.hysteresisLock.pinnedModel
|
|
1012
|
+
) {
|
|
1013
|
+
const suppressed = isSilentOrOffMode(this.mode);
|
|
1014
|
+
return {
|
|
1015
|
+
detectorId: 'DET-08',
|
|
1016
|
+
mode: this.mode,
|
|
1017
|
+
decision: suppressed ? 'allow' : 'deny',
|
|
1018
|
+
blocked: !suppressed,
|
|
1019
|
+
hysteresisLocked: true,
|
|
1020
|
+
breakEven,
|
|
1021
|
+
recommendedModel: this.hysteresisLock.pinnedModel,
|
|
1022
|
+
subagentDelegation: null,
|
|
1023
|
+
reason: `HysteresisLock active (${this.hysteresisLock.reason}): model pinned to ${this.hysteresisLock.pinnedModel} until active task completes.`
|
|
1024
|
+
};
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
if (isSilentOrOffMode(this.mode)) {
|
|
1028
|
+
return {
|
|
1029
|
+
detectorId: 'DET-08',
|
|
1030
|
+
mode: this.mode,
|
|
1031
|
+
decision: 'allow',
|
|
1032
|
+
blocked: false,
|
|
1033
|
+
hysteresisLocked: false,
|
|
1034
|
+
breakEven,
|
|
1035
|
+
recommendedModel: breakEven.targetModel,
|
|
1036
|
+
subagentDelegation: null,
|
|
1037
|
+
reason: null
|
|
1038
|
+
};
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
if (breakEven.unknownModel) {
|
|
1042
|
+
const unknownList = breakEven.unknownModelIds.join(', ');
|
|
1043
|
+
const warning = `[Highbeam DET-08 Advisory] Prices are unknown for ${unknownList}; passing model switch through without price-based hold.`;
|
|
1044
|
+
return {
|
|
1045
|
+
detectorId: 'DET-08',
|
|
1046
|
+
mode: this.mode,
|
|
1047
|
+
decision: 'allow',
|
|
1048
|
+
blocked: false,
|
|
1049
|
+
advisory: true,
|
|
1050
|
+
unknownModel: true,
|
|
1051
|
+
warning,
|
|
1052
|
+
hysteresisLocked: false,
|
|
1053
|
+
breakEven,
|
|
1054
|
+
recommendedModel: breakEven.targetModel,
|
|
1055
|
+
subagentDelegation: null,
|
|
1056
|
+
reason: warning
|
|
1057
|
+
};
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
const rawMinPenalty =
|
|
1061
|
+
request.minSwitchPenaltyUSD ?? this.options.minSwitchPenaltyUSD;
|
|
1062
|
+
const minSwitchPenaltyUSD =
|
|
1063
|
+
rawMinPenalty !== undefined && rawMinPenalty !== null && Number.isFinite(Number(rawMinPenalty))
|
|
1064
|
+
? Math.max(0, Number(rawMinPenalty))
|
|
1065
|
+
: 0.02;
|
|
1066
|
+
const rawNotablePenalty =
|
|
1067
|
+
request.notableAllowPenaltyUSD ?? this.options.notableAllowPenaltyUSD;
|
|
1068
|
+
const notableAllowPenaltyUSD =
|
|
1069
|
+
rawNotablePenalty !== undefined &&
|
|
1070
|
+
rawNotablePenalty !== null &&
|
|
1071
|
+
Number.isFinite(Number(rawNotablePenalty))
|
|
1072
|
+
? Math.max(0, Number(rawNotablePenalty))
|
|
1073
|
+
: minSwitchPenaltyUSD;
|
|
1074
|
+
const belowMinSwitchPenaltyUSD = Boolean(
|
|
1075
|
+
breakEven.shouldHoldModel && breakEven.coldWritePenaltyUSD < minSwitchPenaltyUSD
|
|
1076
|
+
);
|
|
1077
|
+
|
|
1078
|
+
if (breakEven.shouldHoldModel && !belowMinSwitchPenaltyUSD) {
|
|
1079
|
+
// Unconditional prefix-loss protection: exempt from 3-turn advisory cooldown
|
|
1080
|
+
const writeMultLabel = breakEven.cacheTtlTier === '1h' ? '2.0x' : '1.25x';
|
|
1081
|
+
const subagentDelegation = {
|
|
1082
|
+
agentType: 'Explore',
|
|
1083
|
+
model: 'claude-haiku-5-5',
|
|
1084
|
+
maxContextTokens: 2000,
|
|
1085
|
+
turnCap: 12,
|
|
1086
|
+
tokenCap: 40000,
|
|
1087
|
+
reason: `Delegate routine file search/exploration to an isolated Explore/Task subagent on claude-haiku-5-5 (<2k context) while keeping main-thread ${breakEven.currentModel} cache warm.`
|
|
1088
|
+
};
|
|
1089
|
+
|
|
1090
|
+
const paybackDetail =
|
|
1091
|
+
Number.isFinite(breakEven.paybackWarmRequests) && breakEven.paybackWarmRequests > 0
|
|
1092
|
+
? `; payback ~${breakEven.paybackWarmRequests.toFixed(1)} post-switch warm requests (~${breakEven.paybackTurns.toFixed(1)} turns) at +$${breakEven.perTurnPostSwitchSavingUSD.toFixed(4)}/turn post-switch saving`
|
|
1093
|
+
: '';
|
|
1094
|
+
const horizonDetail =
|
|
1095
|
+
breakEven.postSwitchRemainingTurns !== null
|
|
1096
|
+
? `; estimated post-switch horizon ~${breakEven.postSwitchRemainingTurns} turns`
|
|
1097
|
+
: '';
|
|
1098
|
+
const thresholdClause =
|
|
1099
|
+
breakEven.postSwitchRemainingTurns !== null &&
|
|
1100
|
+
Number.isFinite(breakEven.horizonMaxCachedTokens)
|
|
1101
|
+
? `exceeds horizon break-even C_max = ${breakEven.horizonMaxCachedTokens.toLocaleString()} tokens and `
|
|
1102
|
+
: '';
|
|
1103
|
+
const reasonText =
|
|
1104
|
+
`[DET-08 Warm KV-Cache Hold] Switching from ${breakEven.currentModel} to ${breakEven.targetModel} ` +
|
|
1105
|
+
`with ${breakEven.cachedTokens.toLocaleString()} warm cached tokens ${thresholdClause}incurs a ` +
|
|
1106
|
+
`+$${breakEven.coldWritePenaltyUSD.toFixed(4)} cold ${writeMultLabel} prefix rewrite penalty` +
|
|
1107
|
+
`${paybackDetail}${horizonDetail}. ` +
|
|
1108
|
+
`Keep main thread on ${breakEven.currentModel} or confirm if this session will run past payback ` +
|
|
1109
|
+
`(in headless -p/SDK, override via "DET-08": "warn" in .attention-horizon/config.json or pass expectedRemainingTurns).`;
|
|
1110
|
+
|
|
1111
|
+
// In COACH mode (default), remain 100% advisory and non-blocking unless strictBlock is explicitly set
|
|
1112
|
+
if (this.mode === FLIGHT_MODES.COACH && !request.strictBlock && !this.options.strictBlock) {
|
|
1113
|
+
return {
|
|
1114
|
+
detectorId: 'DET-08',
|
|
1115
|
+
mode: this.mode,
|
|
1116
|
+
decision: 'allow',
|
|
1117
|
+
blocked: false,
|
|
1118
|
+
advisory: true,
|
|
1119
|
+
belowMinSwitchPenaltyUSD: false,
|
|
1120
|
+
minSwitchPenaltyUSD,
|
|
1121
|
+
notableAllowPenaltyUSD,
|
|
1122
|
+
notableAllowNote: null,
|
|
1123
|
+
hysteresisLocked: false,
|
|
1124
|
+
breakEven,
|
|
1125
|
+
recommendedModel: breakEven.currentModel,
|
|
1126
|
+
subagentDelegation,
|
|
1127
|
+
reason: reasonText
|
|
1128
|
+
};
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
// In AUTO_PILOT mode, actively gate the destructive model switch ('ask' or 'deny')
|
|
1132
|
+
const autoDecision =
|
|
1133
|
+
request.autoPilotDecision || this.options.autoPilotDecision || 'deny';
|
|
1134
|
+
|
|
1135
|
+
return {
|
|
1136
|
+
detectorId: 'DET-08',
|
|
1137
|
+
mode: this.mode,
|
|
1138
|
+
decision: autoDecision,
|
|
1139
|
+
blocked: true,
|
|
1140
|
+
advisory: false,
|
|
1141
|
+
belowMinSwitchPenaltyUSD: false,
|
|
1142
|
+
minSwitchPenaltyUSD,
|
|
1143
|
+
notableAllowPenaltyUSD,
|
|
1144
|
+
notableAllowNote: null,
|
|
1145
|
+
hysteresisLocked: false,
|
|
1146
|
+
breakEven,
|
|
1147
|
+
recommendedModel: breakEven.currentModel,
|
|
1148
|
+
subagentDelegation,
|
|
1149
|
+
reason: reasonText
|
|
1150
|
+
};
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
// Advisory evaluation when cache is cold, below C*, suppressed below minSwitchPenaltyUSD, or capability upshift
|
|
1154
|
+
const cooldownSuppressed = this.isCooldownActive(currentTurn, false);
|
|
1155
|
+
if (!cooldownSuppressed && this.mode === FLIGHT_MODES.COACH) {
|
|
1156
|
+
this.lastAdvisoryTurn = currentTurn;
|
|
1157
|
+
}
|
|
1158
|
+
|
|
1159
|
+
const isNotablePenalty = Boolean(
|
|
1160
|
+
!belowMinSwitchPenaltyUSD &&
|
|
1161
|
+
breakEven.currentModel !== breakEven.targetModel &&
|
|
1162
|
+
!breakEven.isCapabilityUpshift &&
|
|
1163
|
+
breakEven.cacheWarm &&
|
|
1164
|
+
breakEven.coldWritePenaltyUSD > 0 &&
|
|
1165
|
+
breakEven.coldWritePenaltyUSD >= notableAllowPenaltyUSD
|
|
1166
|
+
);
|
|
1167
|
+
|
|
1168
|
+
const rawTurnsForDisplay =
|
|
1169
|
+
request.turnsCompleted ?? request.currentTurn ?? breakEven.turnsCompleted;
|
|
1170
|
+
const netDollarDisplaySuppressed = Boolean(
|
|
1171
|
+
request.suppressNetDollarDisplay ??
|
|
1172
|
+
(rawTurnsForDisplay !== undefined &&
|
|
1173
|
+
rawTurnsForDisplay !== null &&
|
|
1174
|
+
Number.isFinite(Number(rawTurnsForDisplay)) &&
|
|
1175
|
+
Number(rawTurnsForDisplay) < 5)
|
|
1176
|
+
);
|
|
1177
|
+
|
|
1178
|
+
let notableAllowNote = null;
|
|
1179
|
+
if (isNotablePenalty) {
|
|
1180
|
+
const paybackFragment =
|
|
1181
|
+
Number.isFinite(breakEven.paybackWarmRequests) && breakEven.paybackWarmRequests > 0
|
|
1182
|
+
? `, pays back in ~${breakEven.paybackWarmRequests.toFixed(1)} post-switch warm requests (~${breakEven.paybackTurns.toFixed(1)} turns)`
|
|
1183
|
+
: '';
|
|
1184
|
+
const cMaxFragment =
|
|
1185
|
+
breakEven.postSwitchRemainingTurns !== null && breakEven.horizonMaxCachedTokens !== null
|
|
1186
|
+
? breakEven.horizonMaxCachedTokens === Infinity
|
|
1187
|
+
? '; horizon limit C_max = unbounded'
|
|
1188
|
+
: `; horizon limit C_max = ${breakEven.horizonMaxCachedTokens.toLocaleString()} tokens`
|
|
1189
|
+
: '';
|
|
1190
|
+
const horizonFragment =
|
|
1191
|
+
breakEven.postSwitchRemainingTurns !== null && Number.isFinite(breakEven.horizonNetSavingsUSD)
|
|
1192
|
+
? netDollarDisplaySuppressed
|
|
1193
|
+
? ` (post-switch horizon ~${breakEven.postSwitchRemainingTurns} turns, <5 observed turns: net USD omitted${cMaxFragment})`
|
|
1194
|
+
: ` (post-switch horizon ~${breakEven.postSwitchRemainingTurns} turns, net ${breakEven.horizonNetSavingsUSD >= 0 ? '+$' : '-$'}${Math.abs(breakEven.horizonNetSavingsUSD).toFixed(4)}${cMaxFragment})`
|
|
1195
|
+
: '';
|
|
1196
|
+
const displayedPerTurnSaving =
|
|
1197
|
+
breakEven.contextGrowthPerTurn > 0 &&
|
|
1198
|
+
breakEven.postSwitchRemainingTurns !== null &&
|
|
1199
|
+
breakEven.postSwitchRemainingTurns > 1
|
|
1200
|
+
? breakEven.averagePostSwitchSavingUSD
|
|
1201
|
+
: breakEven.perTurnPostSwitchSavingUSD;
|
|
1202
|
+
notableAllowNote =
|
|
1203
|
+
`[Highbeam] Allowing ${breakEven.currentModel} -> ${breakEven.targetModel}: ` +
|
|
1204
|
+
`+$${breakEven.coldWritePenaltyUSD.toFixed(4)} cold ${breakEven.writeMultiplierLabel} cache rewrite penalty, ` +
|
|
1205
|
+
`saves ~$${displayedPerTurnSaving.toFixed(4)}/turn${paybackFragment}${horizonFragment}.`;
|
|
1206
|
+
}
|
|
1207
|
+
|
|
1208
|
+
const allowReason = belowMinSwitchPenaltyUSD
|
|
1209
|
+
? `Model switch to ${breakEven.targetModel} permitted silently (cold write penalty +$${breakEven.coldWritePenaltyUSD.toFixed(4)} < minSwitchPenaltyUSD $${minSwitchPenaltyUSD.toFixed(4)}).`
|
|
1210
|
+
: breakEven.isCapabilityUpshift && breakEven.currentModel !== breakEven.targetModel
|
|
1211
|
+
? `Capability upshift from ${breakEven.currentModel} to ${breakEven.targetModel} permitted without warm-cache hold.`
|
|
1212
|
+
: breakEven.postSwitchRemainingTurns !== null &&
|
|
1213
|
+
(breakEven.horizonMaxCachedTokens === Infinity ||
|
|
1214
|
+
(breakEven.cachedTokens > breakEven.breakEvenTokens &&
|
|
1215
|
+
breakEven.postSwitchRemainingTurns >= breakEven.paybackTurns))
|
|
1216
|
+
? `Model switch to ${breakEven.targetModel} permitted under horizon payback (${breakEven.postSwitchRemainingTurns} post-switch turns >= ~${breakEven.paybackWarmRequests} warm requests (~${breakEven.paybackTurns} turns); horizon limit ${breakEven.horizonMaxCachedTokens === Infinity ? 'C_max = unbounded' : `C_max = ${breakEven.horizonMaxCachedTokens.toLocaleString()} tokens`}${netDollarDisplaySuppressed ? '' : `; projected net saving ${breakEven.horizonNetSavingsUSD >= 0 ? '+$' : '-$'}${Math.abs(breakEven.horizonNetSavingsUSD).toFixed(4)}`}).`
|
|
1217
|
+
: `Model switch to ${breakEven.targetModel} immediate switch-turn output credit offsets cold rewrite (cached ${breakEven.cachedTokens.toLocaleString()} <= ${breakEven.breakEvenTokens.toLocaleString()} tokens).`;
|
|
1218
|
+
|
|
1219
|
+
return {
|
|
1220
|
+
detectorId: 'DET-08',
|
|
1221
|
+
mode: this.mode,
|
|
1222
|
+
decision: 'allow',
|
|
1223
|
+
blocked: false,
|
|
1224
|
+
advisory: false,
|
|
1225
|
+
belowMinSwitchPenaltyUSD,
|
|
1226
|
+
minSwitchPenaltyUSD,
|
|
1227
|
+
notableAllowPenaltyUSD,
|
|
1228
|
+
notableAllowNote,
|
|
1229
|
+
netDollarDisplaySuppressed,
|
|
1230
|
+
cooldownSuppressed,
|
|
1231
|
+
hysteresisLocked: false,
|
|
1232
|
+
breakEven,
|
|
1233
|
+
recommendedModel: breakEven.targetModel,
|
|
1234
|
+
subagentDelegation: null,
|
|
1235
|
+
reason: allowReason
|
|
1236
|
+
};
|
|
1237
|
+
}
|
|
1238
|
+
|
|
1239
|
+
/**
|
|
1240
|
+
* Evaluates a mid-session top-level `effort`, `thinking`, `system_prompt`, or `mcp_tools`
|
|
1241
|
+
* mutation (`DET-09`). Because Claude Code does not expose a native `/effort` pre-hook,
|
|
1242
|
+
* this acts as an advisory/post-hoc warning or host-mediated `PostCompactMutationQueue` entry
|
|
1243
|
+
* rather than an interactive `/effort` TUI blocker.
|
|
1244
|
+
*
|
|
1245
|
+
* @param {object} [mutationRequest={}]
|
|
1246
|
+
* @param {'effort'|'thinking'|'speed'|'system_prompt'|'mcp_tools'} [mutationRequest.type='effort']
|
|
1247
|
+
* @param {string} [mutationRequest.key]
|
|
1248
|
+
* @param {any} mutationRequest.value
|
|
1249
|
+
* @param {string} [mutationRequest.currentModel='claude-opus-5-5']
|
|
1250
|
+
* @param {number} [mutationRequest.cachedTokens=0]
|
|
1251
|
+
* @param {boolean} [mutationRequest.cacheWarm=true]
|
|
1252
|
+
* @param {'5m'|'1h'} [mutationRequest.cacheTtlTier='5m']
|
|
1253
|
+
*/
|
|
1254
|
+
interceptTopLevelMutation(mutationRequest = {}) {
|
|
1255
|
+
const explicitModel = mutationRequest.currentModel ?? mutationRequest.modelId;
|
|
1256
|
+
const targetFilePath = String(
|
|
1257
|
+
mutationRequest.filePath || mutationRequest.file_path || mutationRequest.path || ''
|
|
1258
|
+
).trim();
|
|
1259
|
+
|
|
1260
|
+
if (
|
|
1261
|
+
targetFilePath &&
|
|
1262
|
+
(!mutationRequest.type || mutationRequest.type === 'file_edit') &&
|
|
1263
|
+
!isPrefixInstructionFile(targetFilePath)
|
|
1264
|
+
) {
|
|
1265
|
+
return {
|
|
1266
|
+
detectorId: 'DET-09',
|
|
1267
|
+
triggered: false,
|
|
1268
|
+
queued: false,
|
|
1269
|
+
decision: 'allow',
|
|
1270
|
+
avoidedRewritePenaltyUSD: 0,
|
|
1271
|
+
queueSize: this.mutationQueue.size(),
|
|
1272
|
+
reason: null
|
|
1273
|
+
};
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
const mutationType =
|
|
1277
|
+
mutationRequest.type || (targetFilePath ? 'system_prompt' : 'effort');
|
|
1278
|
+
|
|
1279
|
+
if (explicitModel !== undefined && !isKnownCatalogModel(explicitModel, this.options)) {
|
|
1280
|
+
const effortCap = mutationType === 'effort'
|
|
1281
|
+
? getEffortMutationCacheCapability(explicitModel, this.options)
|
|
1282
|
+
: null;
|
|
1283
|
+
if (isSilentOrOffMode(this.mode)) {
|
|
1284
|
+
return {
|
|
1285
|
+
detectorId: 'DET-09',
|
|
1286
|
+
triggered: false,
|
|
1287
|
+
queued: false,
|
|
1288
|
+
decision: 'allow',
|
|
1289
|
+
unknownModel: true,
|
|
1290
|
+
effortCacheCapability: effortCap,
|
|
1291
|
+
avoidedRewritePenaltyUSD: null,
|
|
1292
|
+
queueSize: this.mutationQueue.size(),
|
|
1293
|
+
reason: null
|
|
1294
|
+
};
|
|
1295
|
+
}
|
|
1296
|
+
const effortClause =
|
|
1297
|
+
mutationType === 'effort' ? ' (effort cache behavior unverified for this model)' : '';
|
|
1298
|
+
const warning = `[Highbeam DET-09 Advisory] Prices are unknown for ${String(explicitModel)}${effortClause}; passing mutation through without price-based hold.`;
|
|
1299
|
+
return {
|
|
1300
|
+
detectorId: 'DET-09',
|
|
1301
|
+
triggered: false,
|
|
1302
|
+
queued: false,
|
|
1303
|
+
decision: 'allow',
|
|
1304
|
+
advisory: true,
|
|
1305
|
+
unknownModel: true,
|
|
1306
|
+
effortCacheCapability: effortCap,
|
|
1307
|
+
warning,
|
|
1308
|
+
avoidedRewritePenaltyUSD: null,
|
|
1309
|
+
queueSize: this.mutationQueue.size(),
|
|
1310
|
+
reason: warning
|
|
1311
|
+
};
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
const rawModel = explicitModel || 'claude-opus-5-5';
|
|
1315
|
+
const modelId = normalizeModelId(rawModel);
|
|
1316
|
+
const effortCap =
|
|
1317
|
+
mutationType === 'effort' ? getEffortMutationCacheCapability(modelId, this.options) : null;
|
|
1318
|
+
|
|
1319
|
+
if (effortCap && effortCap.invalidatesCache === 'no') {
|
|
1320
|
+
return {
|
|
1321
|
+
detectorId: 'DET-09',
|
|
1322
|
+
triggered: false,
|
|
1323
|
+
queued: false,
|
|
1324
|
+
decision: 'allow',
|
|
1325
|
+
advisory: false,
|
|
1326
|
+
effortCacheCapability: effortCap,
|
|
1327
|
+
avoidedRewritePenaltyUSD: 0,
|
|
1328
|
+
queueSize: this.mutationQueue.size(),
|
|
1329
|
+
reason: null
|
|
1330
|
+
};
|
|
1331
|
+
}
|
|
1332
|
+
|
|
1333
|
+
const cachedTokens = Math.max(0, Number(mutationRequest.cachedTokens ?? 0));
|
|
1334
|
+
const hasTtlField =
|
|
1335
|
+
mutationRequest.ttlRemainingSeconds !== undefined &&
|
|
1336
|
+
mutationRequest.ttlRemainingSeconds !== null;
|
|
1337
|
+
const ttlRemainingSeconds = hasTtlField ? Number(mutationRequest.ttlRemainingSeconds) : null;
|
|
1338
|
+
const ttlExpired = hasTtlField && ttlRemainingSeconds <= 0;
|
|
1339
|
+
|
|
1340
|
+
const cacheWarm = ttlExpired
|
|
1341
|
+
? false
|
|
1342
|
+
: mutationRequest.cacheWarm !== undefined
|
|
1343
|
+
? Boolean(mutationRequest.cacheWarm)
|
|
1344
|
+
: cachedTokens > 0;
|
|
1345
|
+
|
|
1346
|
+
const ttlTier = mutationRequest.cacheTtlTier === '1h' ? '1h' : '5m';
|
|
1347
|
+
const totalPromptTokens = Math.max(cachedTokens, computeTotalPromptTokens(mutationRequest));
|
|
1348
|
+
const rates = resolveEffectiveRates(rawModel, totalPromptTokens, this.options);
|
|
1349
|
+
const writeRate = ttlTier === '1h' ? rates.write1hPer1M : rates.write5mPer1M;
|
|
1350
|
+
|
|
1351
|
+
if (isSilentOrOffMode(this.mode) || !cacheWarm || cachedTokens === 0) {
|
|
1352
|
+
return {
|
|
1353
|
+
detectorId: 'DET-09',
|
|
1354
|
+
triggered: false,
|
|
1355
|
+
queued: false,
|
|
1356
|
+
decision: 'allow',
|
|
1357
|
+
effortCacheCapability: effortCap,
|
|
1358
|
+
avoidedRewritePenaltyUSD: 0,
|
|
1359
|
+
queueSize: this.mutationQueue.size(),
|
|
1360
|
+
reason: 'Cache is cold or router is OFF/SILENT; top-level mutation may apply immediately.'
|
|
1361
|
+
};
|
|
1362
|
+
}
|
|
1363
|
+
|
|
1364
|
+
const avoidedRewritePenaltyUSD = Number(
|
|
1365
|
+
((cachedTokens / 1_000_000) * (writeRate - rates.readPer1M)).toFixed(6)
|
|
1366
|
+
);
|
|
1367
|
+
|
|
1368
|
+
const enableDet09Threshold = Boolean(
|
|
1369
|
+
mutationRequest.enableDet09Threshold ?? this.options.enableDet09Threshold ?? false
|
|
1370
|
+
);
|
|
1371
|
+
const det09BreakEven = computeDet09BreakEvenTokens(
|
|
1372
|
+
{
|
|
1373
|
+
...mutationRequest,
|
|
1374
|
+
currentModel: rawModel,
|
|
1375
|
+
cachedTokens,
|
|
1376
|
+
cacheTtlTier: ttlTier,
|
|
1377
|
+
totalPromptTokens
|
|
1378
|
+
},
|
|
1379
|
+
this.options
|
|
1380
|
+
);
|
|
1381
|
+
|
|
1382
|
+
if (enableDet09Threshold && cachedTokens <= det09BreakEven.breakEvenTokens) {
|
|
1383
|
+
return {
|
|
1384
|
+
detectorId: 'DET-09',
|
|
1385
|
+
triggered: false,
|
|
1386
|
+
queued: false,
|
|
1387
|
+
decision: 'allow',
|
|
1388
|
+
belowBreakEvenThreshold: true,
|
|
1389
|
+
effortCacheCapability: effortCap,
|
|
1390
|
+
breakEvenTokens: det09BreakEven.breakEvenTokens,
|
|
1391
|
+
avoidedRewritePenaltyUSD,
|
|
1392
|
+
queueSize: this.mutationQueue.size(),
|
|
1393
|
+
reason:
|
|
1394
|
+
`Top-level mutation within DET-09 break-even threshold ` +
|
|
1395
|
+
`(cached ${cachedTokens.toLocaleString()} <= C*_mut ${det09BreakEven.breakEvenTokens.toLocaleString()} tokens).`
|
|
1396
|
+
};
|
|
1397
|
+
}
|
|
1398
|
+
|
|
1399
|
+
const effortLabel =
|
|
1400
|
+
effortCap?.invalidatesCache === 'unknown'
|
|
1401
|
+
? ' (unverified for this model)'
|
|
1402
|
+
: effortCap?.provenance
|
|
1403
|
+
? ` (${effortCap.provenance})`
|
|
1404
|
+
: '';
|
|
1405
|
+
const entry = this.mutationQueue.enqueue({
|
|
1406
|
+
type: mutationType,
|
|
1407
|
+
key: mutationRequest.key || targetFilePath || mutationType,
|
|
1408
|
+
value: mutationRequest.value,
|
|
1409
|
+
cachedTokens,
|
|
1410
|
+
avoidedRewritePenaltyUSD,
|
|
1411
|
+
reason:
|
|
1412
|
+
`[DET-09 Top-Level Mutation Deferred] Mutating top-level ${mutationType}${effortLabel} ` +
|
|
1413
|
+
`while ${cachedTokens.toLocaleString()} tokens are warm on ${modelId} would invalidate the ` +
|
|
1414
|
+
`Anthropic prompt cache prefix (+$${avoidedRewritePenaltyUSD.toFixed(4)} rewrite spike). ` +
|
|
1415
|
+
`Queued in PostCompactMutationQueue to apply after next compaction.`
|
|
1416
|
+
});
|
|
1417
|
+
|
|
1418
|
+
return {
|
|
1419
|
+
detectorId: 'DET-09',
|
|
1420
|
+
triggered: true,
|
|
1421
|
+
queued: true,
|
|
1422
|
+
decision: 'defer',
|
|
1423
|
+
effortCacheCapability: effortCap,
|
|
1424
|
+
entry,
|
|
1425
|
+
breakEvenTokens: enableDet09Threshold ? det09BreakEven.breakEvenTokens : 0,
|
|
1426
|
+
avoidedRewritePenaltyUSD,
|
|
1427
|
+
queueSize: this.mutationQueue.size(),
|
|
1428
|
+
reason: entry.reason
|
|
1429
|
+
};
|
|
1430
|
+
}
|
|
1431
|
+
}
|
|
1432
|
+
|
|
1433
|
+
/**
|
|
1434
|
+
* Computes the `DET-09` warm-prefix mutation break-even threshold `C*_mut` (`C1d`):
|
|
1435
|
+
* C*_mut = (Delta_O * P_out) / (P_write - P_read)
|
|
1436
|
+
* Below `C*_mut`, the one-time cold prefix rewrite penalty `(C / 1M) * (P_write - P_read)`
|
|
1437
|
+
* is smaller than the per-turn output-equivalent cost of deferring the mutation.
|
|
1438
|
+
*
|
|
1439
|
+
* @param {object} [params={}]
|
|
1440
|
+
* @param {object} [options={}]
|
|
1441
|
+
*/
|
|
1442
|
+
export function computeDet09BreakEvenTokens(params = {}, options = {}) {
|
|
1443
|
+
const explicitMin = params.det09MinCachedTokens ?? options.det09MinCachedTokens;
|
|
1444
|
+
const rawModel = params.currentModel || params.modelId || 'claude-opus-5-5';
|
|
1445
|
+
const ttlTier = params.cacheTtlTier === '1h' ? '1h' : '5m';
|
|
1446
|
+
const totalPromptTokens = Math.max(
|
|
1447
|
+
Number(params.cachedTokens ?? 0),
|
|
1448
|
+
computeTotalPromptTokens(params)
|
|
1449
|
+
);
|
|
1450
|
+
const rates = resolveEffectiveRates(rawModel, totalPromptTokens, options);
|
|
1451
|
+
if (rates.unknownModel) {
|
|
1452
|
+
return {
|
|
1453
|
+
unknownModel: true,
|
|
1454
|
+
breakEvenTokens: null,
|
|
1455
|
+
outputDeltaTokens: null,
|
|
1456
|
+
writeRatePer1M: null,
|
|
1457
|
+
readRatePer1M: null,
|
|
1458
|
+
outputRatePer1M: null
|
|
1459
|
+
};
|
|
1460
|
+
}
|
|
1461
|
+
const writeRate = ttlTier === '1h' ? rates.write1hPer1M : rates.write5mPer1M;
|
|
1462
|
+
const denominator = writeRate - rates.readPer1M;
|
|
1463
|
+
|
|
1464
|
+
if (explicitMin !== undefined && explicitMin !== null && Number.isFinite(Number(explicitMin))) {
|
|
1465
|
+
return {
|
|
1466
|
+
breakEvenTokens: Math.max(0, Math.round(Number(explicitMin))),
|
|
1467
|
+
outputDeltaTokens: null,
|
|
1468
|
+
writeRatePer1M: writeRate,
|
|
1469
|
+
readRatePer1M: rates.readPer1M,
|
|
1470
|
+
outputRatePer1M: rates.outputPer1M
|
|
1471
|
+
};
|
|
1472
|
+
}
|
|
1473
|
+
|
|
1474
|
+
const effortTable = BUILTIN_CATALOG.effortExpectedOutputTokens || {};
|
|
1475
|
+
const currEff = String(params.currentEffort || '').toLowerCase().trim();
|
|
1476
|
+
const nextEff = String(params.value || '').toLowerCase().trim();
|
|
1477
|
+
let outputDeltaTokens = Number(
|
|
1478
|
+
params.det09OutputDeltaTokens ?? options.det09OutputDeltaTokens ?? NaN
|
|
1479
|
+
);
|
|
1480
|
+
if (!Number.isFinite(outputDeltaTokens) || outputDeltaTokens < 0) {
|
|
1481
|
+
if (
|
|
1482
|
+
effortTable[currEff] !== undefined &&
|
|
1483
|
+
effortTable[nextEff] !== undefined &&
|
|
1484
|
+
effortTable[currEff] !== effortTable[nextEff]
|
|
1485
|
+
) {
|
|
1486
|
+
outputDeltaTokens = Math.abs(effortTable[nextEff] - effortTable[currEff]);
|
|
1487
|
+
} else {
|
|
1488
|
+
outputDeltaTokens = DEFAULT_DET09_OUTPUT_DELTA_TOKENS;
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
|
|
1492
|
+
const breakEvenTokens =
|
|
1493
|
+
denominator <= 0
|
|
1494
|
+
? Infinity
|
|
1495
|
+
: Math.max(0, Math.round((outputDeltaTokens * rates.outputPer1M) / denominator));
|
|
1496
|
+
|
|
1497
|
+
return {
|
|
1498
|
+
breakEvenTokens,
|
|
1499
|
+
outputDeltaTokens,
|
|
1500
|
+
writeRatePer1M: writeRate,
|
|
1501
|
+
readRatePer1M: rates.readPer1M,
|
|
1502
|
+
outputRatePer1M: rates.outputPer1M
|
|
1503
|
+
};
|
|
1504
|
+
}
|
|
1505
|
+
|
|
1506
|
+
/**
|
|
1507
|
+
* Convenience functional wrapper for `DET-09` Warm-Prefix Mutation Fence (`PostCompactMutationQueue`).
|
|
1508
|
+
*
|
|
1509
|
+
* @param {object} [mutationRequest={}]
|
|
1510
|
+
* @param {object} [options={}]
|
|
1511
|
+
*/
|
|
1512
|
+
export function evaluateDet09PrefixMutationFence(mutationRequest = {}, options = {}) {
|
|
1513
|
+
const router = new CacheGravityRouter(options);
|
|
1514
|
+
return router.interceptTopLevelMutation(mutationRequest);
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
/**
|
|
1518
|
+
* Convenience functional wrapper for `DET-08` `PreModelSwitch` evaluation.
|
|
1519
|
+
* @param {object} [request={}]
|
|
1520
|
+
* @param {object} [options={}]
|
|
1521
|
+
*/
|
|
1522
|
+
export function evaluatePreModelSwitch(request = {}, options = {}) {
|
|
1523
|
+
const router = new CacheGravityRouter(options);
|
|
1524
|
+
return router.evaluateModelSwitch(request);
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
export default {
|
|
1528
|
+
FLIGHT_MODES,
|
|
1529
|
+
DEFAULT_EXPECTED_OUTPUT_TOKENS,
|
|
1530
|
+
DEFAULT_DET09_OUTPUT_DELTA_TOKENS,
|
|
1531
|
+
DEFAULT_ADVISORY_COOLDOWN_TURNS,
|
|
1532
|
+
MODEL_EFFORT_CACHE_CAPABILITIES,
|
|
1533
|
+
getEffortMutationCacheCapability,
|
|
1534
|
+
EMPIRICAL_SESSION_API_CALL_PRIOR,
|
|
1535
|
+
estimateEmpiricalRemainingTurns,
|
|
1536
|
+
normalizeFlightMode,
|
|
1537
|
+
isSilentOrOffMode,
|
|
1538
|
+
isPrefixInstructionFile,
|
|
1539
|
+
resolveNaturalDownshiftPeer,
|
|
1540
|
+
computeBreakEvenCachedTokens,
|
|
1541
|
+
computeDet09BreakEvenTokens,
|
|
1542
|
+
evaluatePreModelSwitch,
|
|
1543
|
+
evaluateDet09PrefixMutationFence,
|
|
1544
|
+
PostCompactMutationQueue,
|
|
1545
|
+
HysteresisLock,
|
|
1546
|
+
CacheGravityRouter
|
|
1547
|
+
};
|