ctxtop 0.0.0-stage → 4.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.antigravity-plugin/plugin.json +36 -0
- package/.claude-plugin/plugin.json +18 -0
- package/CHECKSUMS.sha256 +166 -0
- package/LICENSE +27 -0
- package/README.md +350 -2
- package/SECURITY.md +22 -0
- package/agents/ah-flash-scout.md +25 -0
- package/assets/advanced_view_loaded_420px.png +0 -0
- package/assets/hero-demo.svg +188 -0
- package/assets/logo.svg +19 -0
- package/assets/simple_view_lean_420px.png +0 -0
- package/assets/simple_view_loaded_420px.png +0 -0
- package/assets/social-preview.svg +72 -0
- package/assets/zone_c_step3_shield_full.png +0 -0
- package/bin/ah-statusline.mjs +175 -0
- package/bin/cli.mjs +3 -0
- package/bin/ctxtop.mjs +1799 -0
- package/commands/cost-radar.md +11 -0
- package/commands/evolve.md +10 -0
- package/commands/handoff.md +10 -0
- package/commands/horizon.md +10 -0
- package/commands/inspect.md +10 -0
- package/commands/precheck.md +10 -0
- package/config/default_flightcheck.json +133 -0
- package/config/modelCatalog.json +785 -0
- package/config/platformQuirks.json +19 -0
- package/hooks/handlers/compact-lifecycle.mjs +577 -0
- package/hooks/handlers/config-change.mjs +402 -0
- package/hooks/handlers/hookIo.mjs +311 -0
- package/hooks/handlers/hookIpcClient.mjs +83 -0
- package/hooks/handlers/post-model-switch.mjs +111 -0
- package/hooks/handlers/post-tool-use.mjs +366 -0
- package/hooks/handlers/pre-model-switch.mjs +1048 -0
- package/hooks/handlers/pre-tool-use.mjs +632 -0
- package/hooks/handlers/stop-gate.mjs +526 -0
- package/hooks/handlers/user-prompt-submit.mjs +367 -0
- package/hooks/hooks.json +131 -0
- package/hooks/post_invocation.mjs +13 -0
- package/hooks/post_tool_use.mjs +25 -0
- package/hooks/pre_invocation.mjs +14 -0
- package/hooks/pre_tool_use.mjs +97 -0
- package/hooks/register.js +726 -0
- package/hooks/session_start.mjs +24 -0
- package/hooks/stop.mjs +23 -0
- package/hooks.json +56 -0
- package/package.json +110 -4
- package/packages/antigravity/package.json +14 -0
- package/packages/antigravity/src/index.mjs +1 -0
- package/packages/claude-code/package.json +14 -0
- package/packages/claude-code/src/index.mjs +2 -0
- package/packages/core/package.json +14 -0
- package/packages/core/src/index.mjs +1 -0
- package/packages/engine-node/package.json +14 -0
- package/packages/engine-node/src/index.mjs +1 -0
- package/packages/mcp/package.json +17 -0
- package/packages/mcp/src/server.mjs +396 -0
- package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
- package/packages/pro/README-SIGNING.md +30 -0
- package/packages/pro/package.json +16 -0
- package/packages/pro/src/index.mjs +3 -0
- package/packages/pro/src/team_finops_pack.mjs +241 -0
- package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
- package/plugin.json +36 -0
- package/rules/AGENTS.md +10 -0
- package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
- package/sidecars/horizon-daemon/server.mjs +2038 -0
- package/sidecars/horizon-daemon/sidecar.json +19 -0
- package/skills/cost-radar/SKILL.md +21 -0
- package/skills/evolve/SKILL.md +21 -0
- package/skills/handoff/SKILL.md +50 -0
- package/skills/horizon/SKILL.md +17 -0
- package/skills/inspect/SKILL.md +18 -0
- package/skills/precheck/SKILL.md +44 -0
- package/src/adapters/antigravity/index.mjs +109 -0
- package/src/adapters/claude-code/index.mjs +194 -0
- package/src/cli/cost_radar.mjs +70 -0
- package/src/cli/doctor.mjs +351 -0
- package/src/cli/horizon_hud.mjs +888 -0
- package/src/cli/init.mjs +425 -0
- package/src/cli/postmortem.mjs +515 -0
- package/src/coach/cacheGravityRouter.mjs +12 -0
- package/src/config/modelCatalog.json +704 -0
- package/src/config/platformQuirks.json +19 -0
- package/src/core/action_queue.mjs +264 -0
- package/src/core/ag_bridge.mjs +346 -0
- package/src/core/atomic_io.mjs +124 -0
- package/src/core/baseline.mjs +607 -0
- package/src/core/blindspot_sensors.mjs +399 -0
- package/src/core/bucket_b_runtime.mjs +1200 -0
- package/src/core/classifier.mjs +1757 -0
- package/src/core/coach/circuit_breakers.mjs +650 -0
- package/src/core/coach/contradiction_auditor.mjs +239 -0
- package/src/core/coach/effort_advisor.mjs +143 -0
- package/src/core/coach/handoff_hydrator.mjs +483 -0
- package/src/core/coach/progressive_checkpointer.mjs +551 -0
- package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
- package/src/core/coach/reflector_queue.mjs +505 -0
- package/src/core/coach/saved_quota_ledger.mjs +615 -0
- package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
- package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
- package/src/core/coach/task_quota_router.mjs +955 -0
- package/src/core/coach/turn_zero_gate.mjs +574 -0
- package/src/core/compaction_coach.mjs +1126 -0
- package/src/core/config.mjs +214 -0
- package/src/core/constants.mjs +1987 -0
- package/src/core/detectors_det01_to_16.mjs +1523 -0
- package/src/core/doc_indexer.mjs +338 -0
- package/src/core/episodic_memory.mjs +135 -0
- package/src/core/fts5_output_compressor.mjs +359 -0
- package/src/core/git_ledger.mjs +189 -0
- package/src/core/handoff_audit.mjs +558 -0
- package/src/core/history.mjs +221 -0
- package/src/core/hook_diagnostics.mjs +158 -0
- package/src/core/horizon_classifier.mjs +326 -0
- package/src/core/horizon_config.mjs +802 -0
- package/src/core/host_watchdog.mjs +200 -0
- package/src/core/layer5_hygiene.mjs +1084 -0
- package/src/core/log_resolver.mjs +231 -0
- package/src/core/mcp_auditor.mjs +138 -0
- package/src/core/micro_skills_store.mjs +91 -0
- package/src/core/offenders.mjs +161 -0
- package/src/core/parser.mjs +1997 -0
- package/src/core/path_canonicalizer.mjs +73 -0
- package/src/core/paths.mjs +311 -0
- package/src/core/prefix_cache_shield.mjs +386 -0
- package/src/core/pro_license.mjs +385 -0
- package/src/core/prompt_rubric.mjs +518 -0
- package/src/core/pruner.mjs +433 -0
- package/src/core/quota.mjs +1860 -0
- package/src/core/rsi_instinct_engine.mjs +1197 -0
- package/src/core/rsl_clash_auditor.mjs +423 -0
- package/src/core/rsl_distiller.mjs +372 -0
- package/src/core/rsl_ledger.mjs +969 -0
- package/src/core/rsl_triage.mjs +909 -0
- package/src/core/sanitizer.mjs +121 -0
- package/src/core/session_auditor.mjs +658 -0
- package/src/core/session_forensics.mjs +303 -0
- package/src/core/session_timeline.mjs +358 -0
- package/src/core/settings.mjs +99 -0
- package/src/core/shared/detectors.mjs +1342 -0
- package/src/core/shared/fnv1a64.mjs +85 -0
- package/src/core/shared/handoff_schema.mjs +123 -0
- package/src/core/shared/index.mjs +5 -0
- package/src/core/shared/ipi_sanitizer.mjs +165 -0
- package/src/core/shared/micro_skills.mjs +1 -0
- package/src/core/shared/plugin_validator.mjs +202 -0
- package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
- package/src/core/shield_manager.mjs +1417 -0
- package/src/core/sidecar_store.mjs +302 -0
- package/src/core/sprint_metrics.mjs +366 -0
- package/src/core/sqlite_client.mjs +283 -0
- package/src/core/storage_doctor.mjs +358 -0
- package/src/core/subagents.mjs +609 -0
- package/src/core/swarm_topology.mjs +360 -0
- package/src/core/task_quota_router.mjs +1656 -0
- package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
- package/src/core/telemetry/scope_lock_registry.mjs +578 -0
- package/src/core/telemetry/shadow_file_detector.mjs +291 -0
- package/src/core/telemetry/trajectory_watcher.mjs +259 -0
- package/src/core/timeline_svg.mjs +236 -0
- package/src/core/tool_surgeon.mjs +305 -0
- package/src/core/trajectory_stitcher.mjs +645 -0
- package/src/core/u_shaped_optimizer.mjs +789 -0
- package/src/core/wal_hygiene.mjs +233 -0
- package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
- package/src/core-isomorphic/catalog/index.mjs +1 -0
- package/src/core-isomorphic/coach/cacheGravityRouter.mjs +1547 -0
- package/src/core-isomorphic/coach/microSkills.mjs +1 -0
- package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
- package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
- package/src/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
- package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
- package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +305 -0
- package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
- package/src/core-isomorphic/coach/ttlWatchdog.mjs +464 -0
- package/src/core-isomorphic/config/anthropicModelCatalog.json +606 -0
- package/src/core-isomorphic/config/catalogLoader.mjs +1268 -0
- package/src/core-isomorphic/config/horizonConfig.mjs +1055 -0
- package/src/core-isomorphic/control/callTree.mjs +338 -0
- package/src/core-isomorphic/control/coachLatches.mjs +126 -0
- package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
- package/src/core-isomorphic/control/index.mjs +49 -0
- package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
- package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
- package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
- package/src/core-isomorphic/diagnostics/index.mjs +9 -0
- package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
- package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +888 -0
- package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
- package/src/core-isomorphic/economics/cacheGravity.mjs +369 -0
- package/src/core-isomorphic/economics/cliffBreaker.mjs +256 -0
- package/src/core-isomorphic/economics/driftLatency.mjs +433 -0
- package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
- package/src/core-isomorphic/economics/index.mjs +47 -0
- package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
- package/src/core-isomorphic/guards/bucketBAlphaBeta.mjs +860 -0
- package/src/core-isomorphic/guards/bucketBGamma.mjs +442 -0
- package/src/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
- package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
- package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1184 -0
- package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +572 -0
- package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +913 -0
- package/src/core-isomorphic/guards/docIndexCore.mjs +446 -0
- package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +317 -0
- package/src/core-isomorphic/guards/slopsquatGate.mjs +551 -0
- package/src/core-isomorphic/index.js +27 -0
- package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
- package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
- package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
- package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
- package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1156 -0
- package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
- package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
- package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
- package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1237 -0
- package/src/core-isomorphic/ui/modViews.mjs +1504 -0
- package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
- package/src/core-isomorphic/ustf/index.mjs +7 -0
- package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
- package/src/core-isomorphic/ustf/schema.mjs +186 -0
- package/src/core-isomorphic/utils/runtime.mjs +962 -0
- package/src/demo/synthetic_states.mjs +661 -0
- package/src/diagnostics/bugReportGenerator.mjs +253 -0
- package/src/diagnostics/claudeHookCapabilities.mjs +396 -0
- package/src/diagnostics/doctorEngine.mjs +295 -0
- package/src/engine-node/db/index.mjs +58 -0
- package/src/engine-node/db/jsonl_fallback.mjs +184 -0
- package/src/engine-node/db/probe.mjs +342 -0
- package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
- package/src/engine-node/index.mjs +12 -0
- package/src/engine-node/ipc/client.mjs +447 -0
- package/src/engine-node/ipc/index.mjs +22 -0
- package/src/engine-node/ipc/protocol.mjs +177 -0
- package/src/engine-node/ipc/server.mjs +445 -0
- package/src/engine-node/offloader/index.mjs +6 -0
- package/src/engine-node/offloader/tool_offloader.mjs +241 -0
- package/src/engine-node/sensors/blindspots.mjs +376 -0
- package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
- package/src/engine-node/sensors/index.mjs +7 -0
- package/src/hooks/antigravity_rsl_hook.mjs +250 -0
- package/src/hooks/claude_rsl_hook.mjs +288 -0
- package/src/hooks/portfolio_runtime.mjs +858 -0
- package/src/hooks/post_invocation.mjs +611 -0
- package/src/hooks/pre_invocation.mjs +1725 -0
- package/src/hooks/session_start.mjs +199 -0
- package/src/shims/agy_cli_compressor.mjs +705 -0
- package/src/shims/agy_git_guard.mjs +749 -0
- package/src/shims/ah_log_query.mjs +39 -0
- package/src/ui/costRadarSvg.mjs +6 -0
- package/src/ui/horizonGrid.mjs +1 -0
- package/src/ui/horizonPanelHtml.mjs +1 -0
- package/src/ui/horizon_panel.css +167 -0
- package/src/ui/horizon_panel.js +212 -0
- package/src/ui/modViews.mjs +1 -0
- package/src/utils/modelSwitchTelemetry.mjs +308 -0
- package/src/utils/nodeIo.mjs +59 -0
- package/src/utils/runtime.mjs +1 -0
- package/src/utils/sessionCalibration.mjs +657 -0
- package/src/webview/advanced_view.html +1808 -0
- package/src/webview/horizon_panel.html +12397 -0
- package/src/webview/registry.mjs +80 -0
- package/src/webview/simple_view.html +1370 -0
|
@@ -0,0 +1,2038 @@
|
|
|
1
|
+
import http from 'node:http';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import crypto from 'node:crypto';
|
|
5
|
+
import { execFile } from 'node:child_process';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { getHomeDir, getDaemonPortFile, ensureSupportedNodeVersion } from '../../src/core/paths.mjs';
|
|
8
|
+
import { resolveSurfaceTag, resolveModelCeiling } from '../../src/core/constants.mjs';
|
|
9
|
+
import { runCLI } from '../../src/cli/horizon_hud.mjs';
|
|
10
|
+
import { buildCostRadarFromState } from '../../src/cli/cost_radar.mjs';
|
|
11
|
+
import { findSessionDirectory } from '../../src/core/parser.mjs';
|
|
12
|
+
import { loadSettings, saveSettings, SETTINGS_LIMITS } from '../../src/core/settings.mjs';
|
|
13
|
+
import { pruneSessionTranscript } from '../../src/core/pruner.mjs';
|
|
14
|
+
import { inspectHostProcesses, reapOrphanProcesses } from '../../src/core/host_watchdog.mjs';
|
|
15
|
+
import { generateHandoffMarkdown } from '../../src/core/handoff_audit.mjs';
|
|
16
|
+
import { registerCliDampeningHook, promoteRuleWithAttentionZone } from '../../src/core/layer5_hygiene.mjs';
|
|
17
|
+
import { exportSanitizedSnapshot } from '../../src/core/sanitizer.mjs';
|
|
18
|
+
import { executeToolOutputSurgery } from '../../src/core/tool_surgeon.mjs';
|
|
19
|
+
import { buildGitCommitTokenLedger } from '../../src/core/git_ledger.mjs';
|
|
20
|
+
import { synthesizeResumeHerePack } from '../../src/core/episodic_memory.mjs';
|
|
21
|
+
import { getFlightcheckDir } from '../../src/core/sidecar_store.mjs';
|
|
22
|
+
import { PrefixCacheShield } from '../../src/core/prefix_cache_shield.mjs';
|
|
23
|
+
import { CompactionCoach, assessCompactionState, trimUncachedTail } from '../../src/core/compaction_coach.mjs';
|
|
24
|
+
import { RsiInstinctEngine } from '../../src/core/rsi_instinct_engine.mjs';
|
|
25
|
+
import { getRslSummary } from '../../src/core/rsl_ledger.mjs';
|
|
26
|
+
import { UShapedAttentionOptimizer } from '../../src/core/u_shaped_optimizer.mjs';
|
|
27
|
+
import {
|
|
28
|
+
evaluateTaskAndQuotaRoute,
|
|
29
|
+
actuateRoutingRecommendation,
|
|
30
|
+
CacheGravityScorer,
|
|
31
|
+
TaskMdDirectiveWatcher,
|
|
32
|
+
ModelSelectorActuator
|
|
33
|
+
} from '../../src/core/task_quota_router.mjs';
|
|
34
|
+
import { loadHorizonConfig } from '../../src/core/horizon_config.mjs';
|
|
35
|
+
import { TrajectoryWatcher } from '../../src/core/telemetry/trajectory_watcher.mjs';
|
|
36
|
+
import { detectShadowedFileBloat } from '../../src/core/telemetry/shadow_file_detector.mjs';
|
|
37
|
+
import { CacheTtlWatchdog } from '../../src/core/telemetry/cache_ttl_watchdog.mjs';
|
|
38
|
+
import {
|
|
39
|
+
loadRegistry as loadScopeLockRegistry,
|
|
40
|
+
detectScopeCollision,
|
|
41
|
+
deriveSessionClaimedPaths
|
|
42
|
+
} from '../../src/core/telemetry/scope_lock_registry.mjs';
|
|
43
|
+
import { HysteresisLock, TurnBoundaryActuationQueue } from '../../src/core/coach/task_quota_router.mjs';
|
|
44
|
+
import { CircuitBreakers } from '../../src/core/coach/circuit_breakers.mjs';
|
|
45
|
+
import { SubagentPhantomAuditor } from '../../src/core/coach/subagent_phantom_auditor.mjs';
|
|
46
|
+
import { TurnZeroGate } from '../../src/core/coach/turn_zero_gate.mjs';
|
|
47
|
+
import { HandoffHydrationLauncher } from '../../src/core/coach/handoff_hydrator.mjs';
|
|
48
|
+
import {
|
|
49
|
+
SavedQuotaReceiptLedger,
|
|
50
|
+
SAVINGS_EVENT_TYPES,
|
|
51
|
+
computeUnifiedSavings
|
|
52
|
+
} from '../../src/core/coach/saved_quota_ledger.mjs';
|
|
53
|
+
import { applyAutoFixToTimeline } from '../../src/core/session_timeline.mjs';
|
|
54
|
+
import {
|
|
55
|
+
getProEntitlementStatus,
|
|
56
|
+
requireProFeature,
|
|
57
|
+
activateProLicense,
|
|
58
|
+
activateLocalTrial
|
|
59
|
+
} from '../../src/core/pro_license.mjs';
|
|
60
|
+
import { generateCorporateExpenseReceipt } from '../../src/core-isomorphic/ui/pdfReceiptGenerator.mjs';
|
|
61
|
+
import { DETECTOR_CATALOG } from '../../src/core-isomorphic/catalog/detectorCatalog.mjs';
|
|
62
|
+
import { ProgressiveCheckpointer } from '../../src/core/coach/progressive_checkpointer.mjs';
|
|
63
|
+
import { atomicWriteFileSync } from '../../src/core/atomic_io.mjs';
|
|
64
|
+
import { MicroIpcServer } from '../../src/engine-node/ipc/server.mjs';
|
|
65
|
+
|
|
66
|
+
export const HORIZON_CSRF_TOKEN = crypto.randomBytes(32).toString('hex');
|
|
67
|
+
export const MAX_REQUEST_BODY_BYTES = 1_048_576; // 1 MB
|
|
68
|
+
export const MAX_SSE_CLIENTS = 16;
|
|
69
|
+
export const MAX_DAEMON_DIAGNOSTICS = 50;
|
|
70
|
+
|
|
71
|
+
const daemonDiagnostics = [];
|
|
72
|
+
let daemonDiagnosticTotalCount = 0;
|
|
73
|
+
|
|
74
|
+
export function recordDaemonDiagnostic(operation, err) {
|
|
75
|
+
const entry = {
|
|
76
|
+
timestamp: new Date().toISOString(),
|
|
77
|
+
operation: String(operation || 'unknown').slice(0, 96),
|
|
78
|
+
name: err && typeof err === 'object' && err.name ? String(err.name).slice(0, 48) : 'Error',
|
|
79
|
+
code: err && typeof err === 'object' && err.code ? String(err.code) : null,
|
|
80
|
+
message: String(err instanceof Error ? err.message : (err ?? 'Unknown error')).slice(0, 240)
|
|
81
|
+
};
|
|
82
|
+
daemonDiagnosticTotalCount += 1;
|
|
83
|
+
daemonDiagnostics.push(entry);
|
|
84
|
+
while (daemonDiagnostics.length > MAX_DAEMON_DIAGNOSTICS) {
|
|
85
|
+
daemonDiagnostics.shift();
|
|
86
|
+
}
|
|
87
|
+
return entry;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function getDaemonDiagnostics() {
|
|
91
|
+
return {
|
|
92
|
+
count: daemonDiagnostics.length,
|
|
93
|
+
totalRecorded: daemonDiagnosticTotalCount,
|
|
94
|
+
recent: [...daemonDiagnostics]
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function clearDaemonDiagnostics() {
|
|
99
|
+
daemonDiagnostics.length = 0;
|
|
100
|
+
daemonDiagnosticTotalCount = 0;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function isValidCsrfToken(candidate) {
|
|
104
|
+
if (typeof candidate !== 'string' || candidate.length !== HORIZON_CSRF_TOKEN.length) {
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
const a = Buffer.from(candidate, 'utf8');
|
|
108
|
+
const b = Buffer.from(HORIZON_CSRF_TOKEN, 'utf8');
|
|
109
|
+
return a.length === b.length && crypto.timingSafeEqual(a, b);
|
|
110
|
+
}
|
|
111
|
+
import { ContradictionAuditor } from '../../src/core/coach/contradiction_auditor.mjs';
|
|
112
|
+
import { ReflectorQueue } from '../../src/core/coach/reflector_queue.mjs';
|
|
113
|
+
import { PromptDecomposerCoach } from '../../src/core/coach/prompt_decomposer_coach.mjs';
|
|
114
|
+
import { getFts5CompressionStats } from '../../src/core/fts5_output_compressor.mjs';
|
|
115
|
+
|
|
116
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
117
|
+
if (process.argv.includes('--demo')) {
|
|
118
|
+
process.env.HORIZON_DEMO = '1';
|
|
119
|
+
}
|
|
120
|
+
const isDemoMode = process.env.HORIZON_DEMO === '1' || process.argv.includes('--demo');
|
|
121
|
+
|
|
122
|
+
const EXPLICIT_PORT = parseInt(
|
|
123
|
+
process.env.ANTIGRAVITY_SIDECAR_WEB_PORT ||
|
|
124
|
+
process.env.PORT ||
|
|
125
|
+
'0',
|
|
126
|
+
10
|
|
127
|
+
);
|
|
128
|
+
const DEFAULT_PORT_START = 62935;
|
|
129
|
+
const DEFAULT_PORT_MAX = 62945;
|
|
130
|
+
const BIND_HOST = '127.0.0.1';
|
|
131
|
+
const clients = new Set();
|
|
132
|
+
|
|
133
|
+
const defaultCacheDir = path.join(getHomeDir(), '.gemini', 'antigravity', 'cache', 'agy-horizon');
|
|
134
|
+
const runtimeDir = path.join(getHomeDir(), '.gemini', 'runtime');
|
|
135
|
+
const stateFile = path.join(defaultCacheDir, 'latest.state.json');
|
|
136
|
+
|
|
137
|
+
const sidePaneHtml = path.resolve(__dirname, '../../src/ui/sidepane.html');
|
|
138
|
+
const horizonPanelHtml = path.resolve(__dirname, '../../src/webview/horizon_panel.html');
|
|
139
|
+
|
|
140
|
+
function getHtmlMtimeMs() {
|
|
141
|
+
const target = fs.existsSync(horizonPanelHtml) ? horizonPanelHtml : (fs.existsSync(sidePaneHtml) ? sidePaneHtml : null);
|
|
142
|
+
if (target) {
|
|
143
|
+
try {
|
|
144
|
+
return fs.statSync(target).mtimeMs;
|
|
145
|
+
} catch (err) {
|
|
146
|
+
if (err?.code !== 'ENOENT') recordDaemonDiagnostic('getHtmlMtimeMs', err);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return 0;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
let lastEvalMs = 0;
|
|
153
|
+
let cachedLiveState = null;
|
|
154
|
+
let pinnedConversationId = null;
|
|
155
|
+
let activeLockfiles = [];
|
|
156
|
+
|
|
157
|
+
const prefixCacheShield = new PrefixCacheShield();
|
|
158
|
+
const compactionCoach = new CompactionCoach({ prefixCacheShield, prefixShield: prefixCacheShield });
|
|
159
|
+
let rsiEngine = null;
|
|
160
|
+
try {
|
|
161
|
+
rsiEngine = new RsiInstinctEngine({ prefixCacheShield, prefixShield: prefixCacheShield });
|
|
162
|
+
} catch (err) {
|
|
163
|
+
recordDaemonDiagnostic('init:RsiInstinctEngine', err);
|
|
164
|
+
rsiEngine = null;
|
|
165
|
+
}
|
|
166
|
+
const uShapedOptimizer = new UShapedAttentionOptimizer({ prefixCacheShield, prefixShield: prefixCacheShield });
|
|
167
|
+
const cacheGravityScorer = new CacheGravityScorer();
|
|
168
|
+
const modelSelectorActuator = new ModelSelectorActuator({ cacheGravityScorer });
|
|
169
|
+
const taskMdWatcher = new TaskMdDirectiveWatcher({ cacheGravityScorer, actuator: modelSelectorActuator });
|
|
170
|
+
const hysteresisLock = new HysteresisLock();
|
|
171
|
+
const turnBoundaryQueue = new TurnBoundaryActuationQueue();
|
|
172
|
+
const circuitBreakers = new CircuitBreakers({ hysteresisLock });
|
|
173
|
+
const trajectoryWatcher = new TrajectoryWatcher({ hysteresisLock, circuitBreaker: circuitBreakers });
|
|
174
|
+
const handoffHydrator = new HandoffHydrationLauncher();
|
|
175
|
+
const cacheTtlWatchdog = new CacheTtlWatchdog({
|
|
176
|
+
onPreSnapshot: () => {
|
|
177
|
+
try {
|
|
178
|
+
const wsDir = cachedLiveState?.workspace?.canonicalPath || process.cwd();
|
|
179
|
+
handoffHydrator.preStageOnTtlSnapshot({
|
|
180
|
+
workspaceDir: wsDir,
|
|
181
|
+
sessionId: cachedLiveState?.sessionId || pinnedConversationId || 'default-session',
|
|
182
|
+
writeToDisk: true,
|
|
183
|
+
writeDocsHandoff: false
|
|
184
|
+
});
|
|
185
|
+
} catch (err) {
|
|
186
|
+
recordDaemonDiagnostic('cacheTtlWatchdog:onPreSnapshot', err);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
});
|
|
190
|
+
const subagentPhantomAuditor = new SubagentPhantomAuditor();
|
|
191
|
+
const turnZeroGate = new TurnZeroGate();
|
|
192
|
+
const progressiveCheckpointer = new ProgressiveCheckpointer({
|
|
193
|
+
checkpointDir: path.join(getFlightcheckDir(), 'checkpoints'),
|
|
194
|
+
captureGitStat: false
|
|
195
|
+
});
|
|
196
|
+
const contradictionAuditor = new ContradictionAuditor();
|
|
197
|
+
const reflectorQueue = new ReflectorQueue({ prefixCacheShield });
|
|
198
|
+
prefixCacheShield.attachReflectorQueue(reflectorQueue);
|
|
199
|
+
const promptDecomposerCoach = new PromptDecomposerCoach();
|
|
200
|
+
let savedQuotaLedger = null;
|
|
201
|
+
try {
|
|
202
|
+
savedQuotaLedger = new SavedQuotaReceiptLedger();
|
|
203
|
+
} catch (err) {
|
|
204
|
+
recordDaemonDiagnostic('init:SavedQuotaReceiptLedger', err);
|
|
205
|
+
savedQuotaLedger = null;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
let cachedTaskMdMeta = { path: '', mtimeMs: -1, content: '' };
|
|
209
|
+
function getCachedTaskMdContent(wsDir) {
|
|
210
|
+
if (!wsDir) return '';
|
|
211
|
+
const candidate = path.join(wsDir, 'task.md');
|
|
212
|
+
try {
|
|
213
|
+
if (!fs.existsSync(candidate)) return '';
|
|
214
|
+
const st = fs.statSync(candidate);
|
|
215
|
+
if (cachedTaskMdMeta.path === candidate && cachedTaskMdMeta.mtimeMs === st.mtimeMs) {
|
|
216
|
+
return cachedTaskMdMeta.content;
|
|
217
|
+
}
|
|
218
|
+
const content = fs.readFileSync(candidate, 'utf8');
|
|
219
|
+
cachedTaskMdMeta = { path: candidate, mtimeMs: st.mtimeMs, content };
|
|
220
|
+
return content;
|
|
221
|
+
} catch (err) {
|
|
222
|
+
if (err?.code !== 'ENOENT') recordDaemonDiagnostic('getCachedTaskMdContent', err);
|
|
223
|
+
return '';
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
let lastBreakerSessionKey = null;
|
|
228
|
+
let lastBreakerStepCount = 0;
|
|
229
|
+
|
|
230
|
+
function syncLiveCircuitBreakers(state, sessionKey) {
|
|
231
|
+
const steps = Array.isArray(state?.steps) ? state.steps : [];
|
|
232
|
+
if (sessionKey !== lastBreakerSessionKey) {
|
|
233
|
+
circuitBreakers.purgeRewoundTurns(0);
|
|
234
|
+
lastBreakerSessionKey = sessionKey;
|
|
235
|
+
lastBreakerStepCount = 0;
|
|
236
|
+
} else if (steps.length < lastBreakerStepCount) {
|
|
237
|
+
circuitBreakers.purgeRewoundTurns(steps.length);
|
|
238
|
+
lastBreakerStepCount = steps.length;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
for (let idx = lastBreakerStepCount; idx < steps.length; idx++) {
|
|
242
|
+
const st = steps[idx] || {};
|
|
243
|
+
const calls = Array.isArray(st.toolCalls) ? st.toolCalls : [];
|
|
244
|
+
if (calls.length === 0) continue;
|
|
245
|
+
|
|
246
|
+
const nextSt = steps[idx + 1] || null;
|
|
247
|
+
const nextHasOwnCalls = Array.isArray(nextSt?.toolCalls) && nextSt.toolCalls.length > 0;
|
|
248
|
+
const isPairedNext = Boolean(
|
|
249
|
+
nextSt &&
|
|
250
|
+
!nextHasOwnCalls &&
|
|
251
|
+
nextSt.type !== 'USER_INPUT' &&
|
|
252
|
+
nextSt.source !== 'USER_EXPLICIT'
|
|
253
|
+
);
|
|
254
|
+
|
|
255
|
+
const exitCode = isPairedNext && typeof nextSt.exitCode === 'number'
|
|
256
|
+
? nextSt.exitCode
|
|
257
|
+
: (typeof st.exitCode === 'number'
|
|
258
|
+
? st.exitCode
|
|
259
|
+
: ((st.status === 'ERROR' || (isPairedNext && nextSt.status === 'ERROR')) ? 1 : 0));
|
|
260
|
+
const failed = Boolean(st.status === 'ERROR' || (isPairedNext && nextSt.status === 'ERROR') || exitCode !== 0);
|
|
261
|
+
|
|
262
|
+
for (const c of calls) {
|
|
263
|
+
const toolName = String(c?.name || c?.tool || '').toLowerCase();
|
|
264
|
+
const args = c?.args || {};
|
|
265
|
+
const filePath = args.Path || args.path || args.TargetFile || args.AbsolutePath || '';
|
|
266
|
+
const chunks = Array.isArray(args.ReplacementChunks) ? args.ReplacementChunks : null;
|
|
267
|
+
const chunksOld = chunks
|
|
268
|
+
? chunks.map((ch) => String(ch?.TargetContent ?? ch?.Target ?? '')).filter(Boolean).join('\n')
|
|
269
|
+
: undefined;
|
|
270
|
+
const chunksNew = chunks
|
|
271
|
+
? chunks.map((ch) => String(ch?.ReplacementContent ?? ch?.Replacement ?? '')).filter(Boolean).join('\n')
|
|
272
|
+
: undefined;
|
|
273
|
+
const previousContent = args.Target !== undefined
|
|
274
|
+
? args.Target
|
|
275
|
+
: (args.TargetContent !== undefined ? args.TargetContent : chunksOld);
|
|
276
|
+
const newContent = args.Content !== undefined
|
|
277
|
+
? args.Content
|
|
278
|
+
: (args.CodeContent !== undefined
|
|
279
|
+
? args.CodeContent
|
|
280
|
+
: (args.Replacement !== undefined
|
|
281
|
+
? args.Replacement
|
|
282
|
+
: (args.ReplacementContent !== undefined ? args.ReplacementContent : chunksNew)));
|
|
283
|
+
circuitBreakers.recordTurn({
|
|
284
|
+
turnIndex: Number.isFinite(st.stepIndex) ? st.stepIndex : idx,
|
|
285
|
+
toolName,
|
|
286
|
+
args,
|
|
287
|
+
exitCode,
|
|
288
|
+
failed,
|
|
289
|
+
filePath,
|
|
290
|
+
previousContent,
|
|
291
|
+
newContent
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
lastBreakerStepCount = steps.length;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function buildCoachState(state, targetConvId) {
|
|
299
|
+
try {
|
|
300
|
+
const sessionKey = targetConvId || state?.sessionId || 'default';
|
|
301
|
+
const wsDir = state?.workspace?.canonicalPath || process.cwd();
|
|
302
|
+
const taskMdContent = state?.taskMdContent || getCachedTaskMdContent(wsDir);
|
|
303
|
+
const livePrompt = String(state?.lastUserPrompt || '');
|
|
304
|
+
|
|
305
|
+
const ttlSec = Math.max(0, Number(state?.quota?.cache?.ttlRemainingSec ?? state?.cache?.ttlRemainingSec ?? 0) || 0);
|
|
306
|
+
// Single source of truth for cache warmth: classifier `sessionRisk.isCacheTrulyWarm`
|
|
307
|
+
// (requires real cache-read evidence). A cold/busted cache contributes 0 warm tokens,
|
|
308
|
+
// so Coach never defends a prefix that is not actually resident.
|
|
309
|
+
const cacheBlock = state?.quota?.cache || state?.cache || {};
|
|
310
|
+
const totalActive = Number(state?.window?.totalActiveTokens || state?.tokens?.total || 0);
|
|
311
|
+
const trulyWarm = typeof state?.sessionRisk?.isCacheTrulyWarm === 'boolean'
|
|
312
|
+
? state.sessionRisk.isCacheTrulyWarm
|
|
313
|
+
: (ttlSec > 0 && Number(cacheBlock.cacheReadTokens || 0) > 0 && !cacheBlock.prefixBustDetected);
|
|
314
|
+
const cachedTokens = trulyWarm
|
|
315
|
+
? Math.max(Number(cacheBlock.lastTurnCacheReadTokens || 0), totalActive)
|
|
316
|
+
: 0;
|
|
317
|
+
const session = {
|
|
318
|
+
cachedTokens,
|
|
319
|
+
cacheTtlSeconds: ttlSec,
|
|
320
|
+
ttlRemainingSeconds: ttlSec,
|
|
321
|
+
turnCount: Number(state?.window?.turnCount ?? state?.turnCount ?? 0)
|
|
322
|
+
};
|
|
323
|
+
|
|
324
|
+
syncLiveCircuitBreakers(state, sessionKey);
|
|
325
|
+
|
|
326
|
+
let scopeCollisionAlert = null;
|
|
327
|
+
try {
|
|
328
|
+
const registry = loadScopeLockRegistry(wsDir);
|
|
329
|
+
if (Array.isArray(registry.leases) && registry.leases.length > 0) {
|
|
330
|
+
const stepEditedPaths = [];
|
|
331
|
+
for (const st of (Array.isArray(state?.steps) ? state.steps : [])) {
|
|
332
|
+
for (const c of (Array.isArray(st?.toolCalls) ? st.toolCalls : [])) {
|
|
333
|
+
if (/write|edit|replace|create|patch/i.test(String(c?.name || ''))) {
|
|
334
|
+
const p = c?.args?.Path || c?.args?.path || c?.args?.TargetFile || c?.args?.AbsolutePath;
|
|
335
|
+
if (p) stepEditedPaths.push(path.isAbsolute(p) ? path.relative(wsDir, p) : String(p));
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
const claimed = Array.from(new Set([
|
|
340
|
+
...deriveSessionClaimedPaths({ workspaceDir: wsDir, taskMdContent }),
|
|
341
|
+
...stepEditedPaths
|
|
342
|
+
]));
|
|
343
|
+
const collision = detectScopeCollision(sessionKey, claimed, registry.leases);
|
|
344
|
+
if (collision) {
|
|
345
|
+
const shortId = String(sessionKey).slice(0, 8);
|
|
346
|
+
const worktreeCommand = `git worktree add ../${path.basename(wsDir)}-worktree-${shortId} -b feature-parallel-${shortId}`;
|
|
347
|
+
scopeCollisionAlert = {
|
|
348
|
+
detectorId: 'DET-20',
|
|
349
|
+
name: 'Scope Lock Collision',
|
|
350
|
+
severity: 'WARN',
|
|
351
|
+
conflictingTrajectoryId: collision.trajectoryId,
|
|
352
|
+
conflictingPid: collision.pid,
|
|
353
|
+
overlappingPaths: collision.overlappingPaths,
|
|
354
|
+
worktreeCommand,
|
|
355
|
+
message: `🚨 DET-20 Scope Collision: [${collision.overlappingPaths.join(', ')}] leased by "${collision.trajectoryId}" (PID ${collision.pid}). Isolate via git worktree.`
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
} catch (err) {
|
|
360
|
+
if (err?.code !== 'ENOENT') recordDaemonDiagnostic('buildCoachState:scopeCollision', err);
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
const shieldStatus = prefixCacheShield.getStatus(session);
|
|
364
|
+
const compactionEval = assessCompactionState({
|
|
365
|
+
totalTokens: cachedTokens,
|
|
366
|
+
cachedTokens,
|
|
367
|
+
cacheTtlSeconds: ttlSec,
|
|
368
|
+
turnCount: session.turnCount,
|
|
369
|
+
reclaimableWasteTokens: Number(state?.metrics?.sludgeTokens || 0)
|
|
370
|
+
});
|
|
371
|
+
|
|
372
|
+
const clusters = rsiEngine?.getDomainClusters ? rsiEngine.getDomainClusters() : [];
|
|
373
|
+
const horizonCfg = loadHorizonConfig({ cwd: wsDir });
|
|
374
|
+
const configuredFlightMode = String(horizonCfg.flightMode || 'COACH').toUpperCase();
|
|
375
|
+
const effectiveRouterMode = modelSelectorActuator.mode === 'autopilot' || configuredFlightMode === 'AUTO_PILOT'
|
|
376
|
+
? 'autopilot'
|
|
377
|
+
: (configuredFlightMode === 'OFF' ? 'off' : modelSelectorActuator.mode);
|
|
378
|
+
const effectiveFlightMode = effectiveRouterMode === 'autopilot'
|
|
379
|
+
? 'AUTO_PILOT'
|
|
380
|
+
: configuredFlightMode;
|
|
381
|
+
|
|
382
|
+
const resolvedEffort = String(
|
|
383
|
+
state?.activeEffort ||
|
|
384
|
+
state?.activeEffortProfile?.shortLabel ||
|
|
385
|
+
state?.activeEffortProfile?.tier ||
|
|
386
|
+
'auto'
|
|
387
|
+
).toLowerCase();
|
|
388
|
+
const taskRoute = evaluateTaskAndQuotaRoute({
|
|
389
|
+
prompt: livePrompt,
|
|
390
|
+
taskMdContent,
|
|
391
|
+
activeModel: state?.model?.id || state?.model?.rawLabel || state?.activeModel || 'gemini-4-argon',
|
|
392
|
+
activeEffort: resolvedEffort === 'standard' ? 'auto' : resolvedEffort,
|
|
393
|
+
cachedTokens,
|
|
394
|
+
cacheTtlSeconds: ttlSec,
|
|
395
|
+
routerMode: effectiveRouterMode
|
|
396
|
+
});
|
|
397
|
+
|
|
398
|
+
const det17ShadowBloat = detectShadowedFileBloat(state?.steps || []);
|
|
399
|
+
const elapsedIdleSec = Math.max(0, 300 - ttlSec);
|
|
400
|
+
const ttlWatchdogState = cacheTtlWatchdog.evaluateElapsed(elapsedIdleSec, {
|
|
401
|
+
sessionId: sessionKey,
|
|
402
|
+
cachedTokens,
|
|
403
|
+
flightMode: effectiveFlightMode
|
|
404
|
+
});
|
|
405
|
+
const subagentAudit = subagentPhantomAuditor.auditTrajectories(state?.subagents?.invocations || []);
|
|
406
|
+
const fts5SavedTokens = getFts5CompressionStats().savedTokens;
|
|
407
|
+
const liveCacheReadTok = Math.max(0, Number(state?.quota?.cache?.cacheReadTokens || 0));
|
|
408
|
+
const liveStepKey = Number(state?.window?.stepCount || state?.window?.turnCount || 0);
|
|
409
|
+
if (savedQuotaLedger && liveCacheReadTok > 0 && !Boolean(state?.demoMeta || process.env.HORIZON_DEMO === '1')) {
|
|
410
|
+
try {
|
|
411
|
+
savedQuotaLedger.recordSaving({
|
|
412
|
+
sessionId: sessionKey,
|
|
413
|
+
eventType: SAVINGS_EVENT_TYPES.CACHE_HIT_PRESERVED,
|
|
414
|
+
tokensSaved: Math.round(liveCacheReadTok * 0.95),
|
|
415
|
+
dedupeKey: `cachehit:${sessionKey}:step:${liveStepKey}`,
|
|
416
|
+
detail: `95% KV cache hit on ${Math.round(liveCacheReadTok / 1000)}k tokens (step ${liveStepKey})`
|
|
417
|
+
});
|
|
418
|
+
} catch (err) {
|
|
419
|
+
recordDaemonDiagnostic('buildCoachState:cacheHitLedger', err);
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
const ledgerSummary = savedQuotaLedger
|
|
423
|
+
? savedQuotaLedger.getSummary(sessionKey)
|
|
424
|
+
: {
|
|
425
|
+
totalArgonEquivTokensSaved: 0,
|
|
426
|
+
formattedSavedK: '0.0k',
|
|
427
|
+
statusBarText: '$(shield) Horizon: +0.0k Argon-equiv tokens saved (0 Cold Prefills • 0 Downshifts • 0 CLI Compress)',
|
|
428
|
+
footerText: '🛡️ Horizon: +0.0k Argon-equiv tokens saved (0 Cold Prefills • 0 Downshifts • 0 CLI Compress)',
|
|
429
|
+
displayFooterText: '🛡️ Tokens Saved: +0.0k (0 Cold Prefills · 0 Downshifts · 0 CLI Compress)'
|
|
430
|
+
};
|
|
431
|
+
const unifiedSavings = computeUnifiedSavings(state, {
|
|
432
|
+
ledger: savedQuotaLedger,
|
|
433
|
+
sessionId: sessionKey,
|
|
434
|
+
fts5SavedTokens
|
|
435
|
+
});
|
|
436
|
+
if (state && typeof state === 'object') {
|
|
437
|
+
state.savings = unifiedSavings;
|
|
438
|
+
try {
|
|
439
|
+
const keepDemoLog = Boolean(state.demoMeta && state.autoFixLog);
|
|
440
|
+
if (!keepDemoLog) {
|
|
441
|
+
state.autoFixLog = savedQuotaLedger
|
|
442
|
+
? savedQuotaLedger.listRecentEvents(sessionKey, 20)
|
|
443
|
+
: { total: 0, items: [] };
|
|
444
|
+
}
|
|
445
|
+
if (state.sessionTimeline) {
|
|
446
|
+
applyAutoFixToTimeline(state.sessionTimeline, state.autoFixLog.items);
|
|
447
|
+
}
|
|
448
|
+
} catch (err) {
|
|
449
|
+
recordDaemonDiagnostic('buildCoachState:autoFixLog', err);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
const ckptEval = progressiveCheckpointer.evaluateAndSnapshot({
|
|
454
|
+
sessionId: sessionKey,
|
|
455
|
+
totalTokens: cachedTokens,
|
|
456
|
+
maxTokens: Number(state?.window?.maxTokens) || resolveModelCeiling(
|
|
457
|
+
state?.model?.id || state?.model?.rawLabel || state?.activeModel || 'gemini-4-argon',
|
|
458
|
+
null,
|
|
459
|
+
{ useLegacyDefault: false }
|
|
460
|
+
),
|
|
461
|
+
taskMdContent,
|
|
462
|
+
agentsMdContent: state?.agentsMdContent || '',
|
|
463
|
+
userConstraints: state?.userConstraints || [],
|
|
464
|
+
writeToDisk: !Boolean(state?.demoMeta || process.env.HORIZON_DEMO === '1')
|
|
465
|
+
});
|
|
466
|
+
const latestCkpt = progressiveCheckpointer.getLatestCheckpoint(sessionKey);
|
|
467
|
+
const evaporationCheck = latestCkpt && state?.contextSummary
|
|
468
|
+
? progressiveCheckpointer.detectConstraintEvaporation(state.contextSummary, sessionKey, latestCkpt)
|
|
469
|
+
: null;
|
|
470
|
+
|
|
471
|
+
reflectorQueue.setWorkspaceDir(wsDir);
|
|
472
|
+
const stagedLearnings = reflectorQueue.listItems();
|
|
473
|
+
const promptAdvisory = promptDecomposerCoach.evaluate(livePrompt);
|
|
474
|
+
|
|
475
|
+
const combinedAlerts = [...circuitBreakers.activeAlerts];
|
|
476
|
+
if (scopeCollisionAlert) combinedAlerts.push(scopeCollisionAlert);
|
|
477
|
+
const thinkingDrift = state?.quota?.thinkingDrift || null;
|
|
478
|
+
const det30Mode = String(horizonCfg?.detectors?.['DET-30'] || 'default').toLowerCase();
|
|
479
|
+
if (thinkingDrift?.loop?.triggered && det30Mode !== 'off') {
|
|
480
|
+
combinedAlerts.push({
|
|
481
|
+
detectorId: 'DET-30',
|
|
482
|
+
name: 'thinking-drift-loop',
|
|
483
|
+
severity: thinkingDrift.loop.severity === 'critical' ? 'CRITICAL' : 'WARN',
|
|
484
|
+
message: thinkingDrift.loop.message
|
|
485
|
+
});
|
|
486
|
+
}
|
|
487
|
+
const primaryTripped = combinedAlerts.length > 0 ? combinedAlerts[combinedAlerts.length - 1] : null;
|
|
488
|
+
const trippedIds = new Set(combinedAlerts.map((a) => a.detectorId));
|
|
489
|
+
const cfgDetectors = horizonCfg?.detectors || {};
|
|
490
|
+
const guardList = Object.values(DETECTOR_CATALOG).map((meta) => {
|
|
491
|
+
const cfgMode = String(cfgDetectors[meta.id] || 'default').toLowerCase();
|
|
492
|
+
const mode = cfgMode === 'default' ? String(meta.defaultMode || 'advisory') : cfgMode;
|
|
493
|
+
return { id: meta.id, name: meta.name, mode, severity: meta.severity || 'WARN', tripped: trippedIds.has(meta.id) };
|
|
494
|
+
}).filter((g) => g.mode !== 'off');
|
|
495
|
+
|
|
496
|
+
return {
|
|
497
|
+
prefixCacheShield: shieldStatus,
|
|
498
|
+
detectors: {
|
|
499
|
+
active: true,
|
|
500
|
+
totalCount: guardList.length,
|
|
501
|
+
list: guardList,
|
|
502
|
+
tripped: primaryTripped
|
|
503
|
+
? {
|
|
504
|
+
detectorId: primaryTripped.detectorId,
|
|
505
|
+
reason: primaryTripped.message || primaryTripped.name,
|
|
506
|
+
severity: primaryTripped.severity || 'WARN',
|
|
507
|
+
revertAction: primaryTripped.revertAction || null,
|
|
508
|
+
worktreeCommand: primaryTripped.worktreeCommand || null
|
|
509
|
+
}
|
|
510
|
+
: null,
|
|
511
|
+
summary: combinedAlerts.length > 0
|
|
512
|
+
? `${combinedAlerts.length} breaker${combinedAlerts.length === 1 ? '' : 's'} tripped (${combinedAlerts.map(a => a.detectorId).join(', ')})`
|
|
513
|
+
: `${guardList.length} guards quiet`
|
|
514
|
+
},
|
|
515
|
+
scopeCollision: scopeCollisionAlert,
|
|
516
|
+
thinkingDrift,
|
|
517
|
+
prefixRetention: state?.quota?.cache?.prefixRetention || null,
|
|
518
|
+
det17ShadowBloat,
|
|
519
|
+
ttlWatchdog: ttlWatchdogState,
|
|
520
|
+
hysteresisLock: hysteresisLock.getStatus(),
|
|
521
|
+
turnBoundaryQueue: {
|
|
522
|
+
languageServerState: turnBoundaryQueue.languageServerState,
|
|
523
|
+
queuedCount: turnBoundaryQueue.queue.length
|
|
524
|
+
},
|
|
525
|
+
circuitBreakerAlerts: combinedAlerts,
|
|
526
|
+
subagentAudit,
|
|
527
|
+
turnZeroGate: {
|
|
528
|
+
lockedByInvariant1: turnZeroGate.isWarmPrefixLocked(session),
|
|
529
|
+
queuedCount: turnZeroGate.queuedMutations.length,
|
|
530
|
+
activeMcpProfile: turnZeroGate.activeMcpProfile
|
|
531
|
+
},
|
|
532
|
+
checkpoints: {
|
|
533
|
+
latest: latestCkpt,
|
|
534
|
+
evaporationCheck,
|
|
535
|
+
allBands: progressiveCheckpointer.listCheckpoints(targetConvId || state?.sessionId || 'default')
|
|
536
|
+
},
|
|
537
|
+
reflectorQueue: {
|
|
538
|
+
projectHash: reflectorQueue.projectHash,
|
|
539
|
+
items: stagedLearnings,
|
|
540
|
+
stagedCount: stagedLearnings.filter((it) => it.status === 'staged').length,
|
|
541
|
+
approvedCount: stagedLearnings.filter((it) => it.status === 'approved').length
|
|
542
|
+
},
|
|
543
|
+
promptAdvisory,
|
|
544
|
+
savedQuotaLedger: ledgerSummary,
|
|
545
|
+
savings: unifiedSavings,
|
|
546
|
+
proEntitlement: getProEntitlementStatus(),
|
|
547
|
+
fts5Compressor: {
|
|
548
|
+
active: true,
|
|
549
|
+
savedTokens: fts5SavedTokens
|
|
550
|
+
},
|
|
551
|
+
compactionCoach: compactionEval,
|
|
552
|
+
rsiEngine: {
|
|
553
|
+
clusters,
|
|
554
|
+
readyToEvolveCount: clusters.length,
|
|
555
|
+
globalCandidates: rsiEngine?.getGlobalPromotionCandidates ? rsiEngine.getGlobalPromotionCandidates() : []
|
|
556
|
+
},
|
|
557
|
+
uShapedAttention: (() => {
|
|
558
|
+
try {
|
|
559
|
+
const ruleScan = uShapedOptimizer.scanWorkspaceAndGlobalRules();
|
|
560
|
+
return {
|
|
561
|
+
healthScore: ruleScan?.avgPrimacyPct || 94,
|
|
562
|
+
middleTroughRiskCount: ruleScan?.totalMiddleTroughRisk || 0,
|
|
563
|
+
recencyMirrorActive: Boolean(fs.existsSync(path.join(wsDir || '.', 'task.md')) && fs.readFileSync(path.join(wsDir || '.', 'task.md'), 'utf8').includes('## Active Guardrail Pin'))
|
|
564
|
+
};
|
|
565
|
+
} catch (err) {
|
|
566
|
+
if (err?.code !== 'ENOENT') recordDaemonDiagnostic('buildCoachState:uShapedAttention', err);
|
|
567
|
+
return {
|
|
568
|
+
healthScore: 94,
|
|
569
|
+
middleTroughRiskCount: 0,
|
|
570
|
+
recencyMirrorActive: false
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
})(),
|
|
574
|
+
rsl: (() => {
|
|
575
|
+
try {
|
|
576
|
+
const rslSummary = getRslSummary(wsDir);
|
|
577
|
+
if (state && typeof state === 'object') {
|
|
578
|
+
state.rsl = rslSummary;
|
|
579
|
+
const telDir = path.join(wsDir, '.agents', 'telemetry');
|
|
580
|
+
let shardCount = Array.isArray(state.sessionMeta?.specShards) ? state.sessionMeta.specShards.length : 0;
|
|
581
|
+
if (shardCount === 0 && fs.existsSync(telDir)) {
|
|
582
|
+
const pFiles = fs.readdirSync(telDir).filter((n) => n.startsWith('prompt_state.') && n.endsWith('.json'));
|
|
583
|
+
for (const pf of pFiles.slice(0, 3)) {
|
|
584
|
+
try {
|
|
585
|
+
const ps = JSON.parse(fs.readFileSync(path.join(telDir, pf), 'utf8'));
|
|
586
|
+
shardCount = Math.max(shardCount, Array.isArray(ps?.specShards) ? ps.specShards.length : 0);
|
|
587
|
+
} catch (parseErr) {
|
|
588
|
+
recordDaemonDiagnostic('buildCoachState:promptState', parseErr);
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
state.shardedSpecCount = shardCount;
|
|
593
|
+
}
|
|
594
|
+
return rslSummary;
|
|
595
|
+
} catch (err) {
|
|
596
|
+
if (err?.code !== 'ENOENT') recordDaemonDiagnostic('buildCoachState:rsl', err);
|
|
597
|
+
return null;
|
|
598
|
+
}
|
|
599
|
+
})(),
|
|
600
|
+
taskQuotaRouter: taskRoute
|
|
601
|
+
};
|
|
602
|
+
} catch (err) {
|
|
603
|
+
recordDaemonDiagnostic('buildCoachState', err);
|
|
604
|
+
return null;
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
function getWorkspaceHash(wsPath = process.cwd()) {
|
|
609
|
+
return crypto.createHash('sha1').update(String(wsPath).toLowerCase()).digest('hex').slice(0, 10);
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
function writeRuntimeLockfile(boundPort, workspacePath = process.cwd()) {
|
|
613
|
+
try {
|
|
614
|
+
const homeDir = getHomeDir();
|
|
615
|
+
fs.mkdirSync(runtimeDir, { recursive: true });
|
|
616
|
+
const ctxtopPortFile = getDaemonPortFile(homeDir);
|
|
617
|
+
const ctxtopDir = path.dirname(ctxtopPortFile);
|
|
618
|
+
const ctxtopJsonFile = path.join(ctxtopDir, 'daemon.json');
|
|
619
|
+
fs.mkdirSync(ctxtopDir, { recursive: true });
|
|
620
|
+
|
|
621
|
+
const wsHash = getWorkspaceHash(workspacePath);
|
|
622
|
+
const payload = JSON.stringify({
|
|
623
|
+
pid: process.pid,
|
|
624
|
+
port: boundPort,
|
|
625
|
+
host: BIND_HOST,
|
|
626
|
+
workspace: workspacePath,
|
|
627
|
+
workspaceHash: wsHash,
|
|
628
|
+
startedAt: new Date().toISOString()
|
|
629
|
+
}, null, 2);
|
|
630
|
+
|
|
631
|
+
const wsPortFile = path.join(runtimeDir, `horizon-${wsHash}.port`);
|
|
632
|
+
const wsJsonFile = path.join(runtimeDir, `horizon-${wsHash}.json`);
|
|
633
|
+
const latestJsonFile = path.join(runtimeDir, 'horizon-latest.json');
|
|
634
|
+
|
|
635
|
+
atomicWriteFileSync(wsPortFile, String(boundPort), { encoding: 'utf8' });
|
|
636
|
+
atomicWriteFileSync(wsJsonFile, payload, { encoding: 'utf8' });
|
|
637
|
+
atomicWriteFileSync(latestJsonFile, payload, { encoding: 'utf8' });
|
|
638
|
+
atomicWriteFileSync(ctxtopPortFile, String(boundPort), { encoding: 'utf8' });
|
|
639
|
+
atomicWriteFileSync(ctxtopJsonFile, payload, { encoding: 'utf8' });
|
|
640
|
+
activeLockfiles = [wsPortFile, wsJsonFile, ctxtopPortFile, ctxtopJsonFile];
|
|
641
|
+
} catch (err) {
|
|
642
|
+
recordDaemonDiagnostic('writeRuntimeLockfile', err);
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
function cleanupRuntimeLockfiles() {
|
|
647
|
+
for (const f of activeLockfiles) {
|
|
648
|
+
try {
|
|
649
|
+
if (fs.existsSync(f)) fs.unlinkSync(f);
|
|
650
|
+
} catch (err) {
|
|
651
|
+
if (err?.code !== 'ENOENT') recordDaemonDiagnostic('cleanupRuntimeLockfiles', err);
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
process.on('exit', cleanupRuntimeLockfiles);
|
|
657
|
+
process.on('SIGINT', () => { cleanupRuntimeLockfiles(); process.exit(0); });
|
|
658
|
+
process.on('SIGTERM', () => { cleanupRuntimeLockfiles(); process.exit(0); });
|
|
659
|
+
|
|
660
|
+
async function refreshLiveState(force = false, explicitConvId = null) {
|
|
661
|
+
const now = Date.now();
|
|
662
|
+
const htmlMtimeMs = getHtmlMtimeMs();
|
|
663
|
+
const targetConvId = explicitConvId || pinnedConversationId || process.env.ANTIGRAVITY_CONVERSATION_ID || null;
|
|
664
|
+
if (!force && !explicitConvId && cachedLiveState && (now - lastEvalMs) < 1000) {
|
|
665
|
+
if (cachedLiveState) {
|
|
666
|
+
cachedLiveState.uiMtimeMs = htmlMtimeMs;
|
|
667
|
+
try {
|
|
668
|
+
cachedLiveState.coachState = buildCoachState(cachedLiveState, targetConvId);
|
|
669
|
+
} catch (err) {
|
|
670
|
+
recordDaemonDiagnostic('refreshLiveState:cachedCoachState', err);
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
return cachedLiveState;
|
|
674
|
+
}
|
|
675
|
+
try {
|
|
676
|
+
const [resLive, hostHealth] = await Promise.all([
|
|
677
|
+
runCLI({
|
|
678
|
+
silent: true,
|
|
679
|
+
useNativeCeiling: true,
|
|
680
|
+
stdinData: targetConvId ? { conversation_id: targetConvId } : null
|
|
681
|
+
}),
|
|
682
|
+
inspectHostProcesses({ force: false }).catch((err) => {
|
|
683
|
+
recordDaemonDiagnostic('refreshLiveState:inspectHostProcesses', err);
|
|
684
|
+
return null;
|
|
685
|
+
})
|
|
686
|
+
]);
|
|
687
|
+
if (resLive && resLive.state) {
|
|
688
|
+
resLive.state.pinnedConversationId = pinnedConversationId;
|
|
689
|
+
resLive.state.hostHealth = hostHealth;
|
|
690
|
+
resLive.state.uiMtimeMs = htmlMtimeMs;
|
|
691
|
+
try {
|
|
692
|
+
const wsPath = resLive.state.workspace?.canonicalPath || process.cwd();
|
|
693
|
+
resLive.state.gitLedger = buildGitCommitTokenLedger(wsPath, []);
|
|
694
|
+
} catch (err) {
|
|
695
|
+
if (err?.code !== 'ENOENT') recordDaemonDiagnostic('refreshLiveState:gitLedger', err);
|
|
696
|
+
}
|
|
697
|
+
cachedLiveState = resLive.state;
|
|
698
|
+
lastEvalMs = now;
|
|
699
|
+
try {
|
|
700
|
+
cachedLiveState.coachState = buildCoachState(cachedLiveState, targetConvId);
|
|
701
|
+
} catch (err) {
|
|
702
|
+
recordDaemonDiagnostic('refreshLiveState:liveCoachState', err);
|
|
703
|
+
}
|
|
704
|
+
if (
|
|
705
|
+
cachedLiveState?.coachState?.taskQuotaRouter &&
|
|
706
|
+
(modelSelectorActuator.mode === 'autopilot' || cachedLiveState.coachState.taskQuotaRouter.routerMode === 'autopilot')
|
|
707
|
+
) {
|
|
708
|
+
try {
|
|
709
|
+
cachedLiveState.coachState.autoPilotActuation = await actuateRoutingRecommendation(
|
|
710
|
+
cachedLiveState.coachState.taskQuotaRouter,
|
|
711
|
+
{
|
|
712
|
+
actuator: modelSelectorActuator,
|
|
713
|
+
flightMode: 'AUTO_PILOT',
|
|
714
|
+
sessionId: targetConvId || cachedLiveState.sessionId || 'default_session',
|
|
715
|
+
cachedTokens: Number(cachedLiveState?.window?.totalActiveTokens || 0),
|
|
716
|
+
cacheTtlSeconds: Number(cachedLiveState?.quota?.cache?.ttlRemainingSec || 0)
|
|
717
|
+
}
|
|
718
|
+
);
|
|
719
|
+
} catch (err) {
|
|
720
|
+
recordDaemonDiagnostic('refreshLiveState:autoPilotActuation', err);
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
return cachedLiveState;
|
|
724
|
+
}
|
|
725
|
+
} catch (err) {
|
|
726
|
+
recordDaemonDiagnostic('refreshLiveState:runCLI', err);
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
if (fs.existsSync(stateFile)) {
|
|
730
|
+
try {
|
|
731
|
+
cachedLiveState = JSON.parse(fs.readFileSync(stateFile, 'utf8'));
|
|
732
|
+
cachedLiveState.uiMtimeMs = htmlMtimeMs;
|
|
733
|
+
if (!cachedLiveState.hostHealth) {
|
|
734
|
+
cachedLiveState.hostHealth = await inspectHostProcesses({ force: false }).catch((err) => {
|
|
735
|
+
recordDaemonDiagnostic('refreshLiveState:stateFileHostProcesses', err);
|
|
736
|
+
return null;
|
|
737
|
+
});
|
|
738
|
+
}
|
|
739
|
+
try {
|
|
740
|
+
cachedLiveState.coachState = buildCoachState(cachedLiveState, targetConvId);
|
|
741
|
+
} catch (err) {
|
|
742
|
+
recordDaemonDiagnostic('refreshLiveState:stateFileCoachState', err);
|
|
743
|
+
}
|
|
744
|
+
return cachedLiveState;
|
|
745
|
+
} catch (err) {
|
|
746
|
+
if (err?.code !== 'ENOENT') recordDaemonDiagnostic('refreshLiveState:readStateFile', err);
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
// Fallback to FlightCheck session sidecar if present (strictly real UUID sessions, never synthetic test fixtures)
|
|
751
|
+
const fcSessionsDir = path.join(getHomeDir(), '.gemini', 'flightcheck', 'sessions');
|
|
752
|
+
if (fs.existsSync(fcSessionsDir)) {
|
|
753
|
+
try {
|
|
754
|
+
const uuidSidecarRe = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.sidecar\.json$/i;
|
|
755
|
+
const files = fs.readdirSync(fcSessionsDir)
|
|
756
|
+
.filter(f => uuidSidecarRe.test(f))
|
|
757
|
+
.map(f => ({ name: f, time: fs.statSync(path.join(fcSessionsDir, f)).mtimeMs }))
|
|
758
|
+
.sort((a, b) => b.time - a.time);
|
|
759
|
+
if (files.length > 0) {
|
|
760
|
+
cachedLiveState = JSON.parse(fs.readFileSync(path.join(fcSessionsDir, files[0].name), 'utf8'));
|
|
761
|
+
cachedLiveState.uiMtimeMs = htmlMtimeMs;
|
|
762
|
+
try {
|
|
763
|
+
cachedLiveState.coachState = buildCoachState(cachedLiveState, targetConvId);
|
|
764
|
+
} catch (err) {
|
|
765
|
+
recordDaemonDiagnostic('refreshLiveState:sidecarCoachState', err);
|
|
766
|
+
}
|
|
767
|
+
return cachedLiveState;
|
|
768
|
+
}
|
|
769
|
+
} catch (err) {
|
|
770
|
+
if (err?.code !== 'ENOENT') recordDaemonDiagnostic('refreshLiveState:readSidecarFallback', err);
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
if (!cachedLiveState && isDemoMode) {
|
|
775
|
+
try {
|
|
776
|
+
const demoRes = await runCLI({ silent: true, demo: true, useNativeCeiling: true });
|
|
777
|
+
if (demoRes && demoRes.state) {
|
|
778
|
+
cachedLiveState = demoRes.state;
|
|
779
|
+
}
|
|
780
|
+
} catch (err) {
|
|
781
|
+
if (err?.code !== 'ENOENT') recordDaemonDiagnostic('refreshLiveState:demoFallback', err);
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
if (cachedLiveState) {
|
|
786
|
+
cachedLiveState.uiMtimeMs = htmlMtimeMs;
|
|
787
|
+
try {
|
|
788
|
+
cachedLiveState.coachState = buildCoachState(cachedLiveState, targetConvId);
|
|
789
|
+
} catch (err) {
|
|
790
|
+
recordDaemonDiagnostic('refreshLiveState:finalCoachState', err);
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
return cachedLiveState;
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
const LOCAL_HOSTNAMES = new Set(['127.0.0.1', 'localhost', '[::1]']);
|
|
797
|
+
|
|
798
|
+
const LOOPBACK_ORIGIN_RE = /^http:\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i;
|
|
799
|
+
const IDE_WEBVIEW_ORIGIN_RE = /^(vscode-webview|antigravity):\/\//i;
|
|
800
|
+
|
|
801
|
+
export function isAllowedOriginHeader(origin) {
|
|
802
|
+
if (origin === undefined || origin === '') return true;
|
|
803
|
+
if (origin === 'null') return false;
|
|
804
|
+
const s = String(origin);
|
|
805
|
+
return LOOPBACK_ORIGIN_RE.test(s) || IDE_WEBVIEW_ORIGIN_RE.test(s);
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
/**
|
|
809
|
+
* Allows only requests addressed to this loopback daemon (Host check blocks DNS rebinding)
|
|
810
|
+
* and, when a browser sends an Origin header, only strict local loopback pages or IDE webviews
|
|
811
|
+
* (explicitly rejecting `Origin: null` sandboxed iframes).
|
|
812
|
+
*/
|
|
813
|
+
export function isAllowedLocalRequest(req) {
|
|
814
|
+
const hostHeader = String(req.headers.host || '').toLowerCase();
|
|
815
|
+
const hostMatch = hostHeader.match(/^(\[[^\]]+\]|[^:]+)(?::(\d+))?$/);
|
|
816
|
+
if (!hostMatch || !LOCAL_HOSTNAMES.has(hostMatch[1])) return false;
|
|
817
|
+
|
|
818
|
+
const sidecarToken = process.env.ANTIGRAVITY_SIDECAR_UI_TOKEN;
|
|
819
|
+
if (sidecarToken && req.headers['x-sidecar-token'] === sidecarToken) {
|
|
820
|
+
return true;
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
return isAllowedOriginHeader(req.headers.origin);
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
/**
|
|
827
|
+
* Reads an HTTP request body up to `maxBytes` (default 1 MB).
|
|
828
|
+
* Responds with `413 Payload Too Large` and destroys the socket on oversized payloads.
|
|
829
|
+
*/
|
|
830
|
+
function readRequestBody(req, res, maxBytes = MAX_REQUEST_BODY_BYTES) {
|
|
831
|
+
return new Promise((resolve) => {
|
|
832
|
+
const declaredLen = Number(req.headers['content-length']);
|
|
833
|
+
if (Number.isFinite(declaredLen) && declaredLen > maxBytes) {
|
|
834
|
+
res.writeHead(413, { 'Content-Type': 'application/json', 'Connection': 'close' });
|
|
835
|
+
res.end(
|
|
836
|
+
JSON.stringify({ success: false, error: `Payload Too Large (max ${maxBytes} bytes)` }),
|
|
837
|
+
() => {
|
|
838
|
+
try {
|
|
839
|
+
req.destroy();
|
|
840
|
+
} catch (err) {
|
|
841
|
+
if (err?.code !== 'ERR_STREAM_DESTROYED') recordDaemonDiagnostic('readRequestBody:destroy413Header', err);
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
);
|
|
845
|
+
resolve(null);
|
|
846
|
+
return;
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
const chunks = [];
|
|
850
|
+
let totalBytes = 0;
|
|
851
|
+
let aborted = false;
|
|
852
|
+
|
|
853
|
+
req.on('data', (chunk) => {
|
|
854
|
+
if (aborted) return;
|
|
855
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), 'utf8');
|
|
856
|
+
totalBytes += buf.length;
|
|
857
|
+
if (totalBytes > maxBytes) {
|
|
858
|
+
aborted = true;
|
|
859
|
+
try {
|
|
860
|
+
req.pause();
|
|
861
|
+
} catch (err) {
|
|
862
|
+
recordDaemonDiagnostic('readRequestBody:pause', err);
|
|
863
|
+
}
|
|
864
|
+
res.writeHead(413, { 'Content-Type': 'application/json', 'Connection': 'close' });
|
|
865
|
+
res.end(
|
|
866
|
+
JSON.stringify({ success: false, error: `Payload Too Large (max ${maxBytes} bytes)` }),
|
|
867
|
+
() => {
|
|
868
|
+
try {
|
|
869
|
+
req.destroy();
|
|
870
|
+
} catch (err) {
|
|
871
|
+
if (err?.code !== 'ERR_STREAM_DESTROYED') recordDaemonDiagnostic('readRequestBody:destroy413Stream', err);
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
);
|
|
875
|
+
resolve(null);
|
|
876
|
+
return;
|
|
877
|
+
}
|
|
878
|
+
chunks.push(buf);
|
|
879
|
+
});
|
|
880
|
+
|
|
881
|
+
req.on('end', () => {
|
|
882
|
+
if (aborted) return;
|
|
883
|
+
resolve(Buffer.concat(chunks).toString('utf8'));
|
|
884
|
+
});
|
|
885
|
+
|
|
886
|
+
req.on('error', () => {
|
|
887
|
+
if (aborted) return;
|
|
888
|
+
aborted = true;
|
|
889
|
+
resolve(null);
|
|
890
|
+
});
|
|
891
|
+
});
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
const RULE_FILE_RE = /(^|[\\/])(AGENTS\.md|GEMINI\.md)$|[\\/]\.agents[\\/]rules[\\/][^\\/]+\.md$/i;
|
|
895
|
+
|
|
896
|
+
function parseJsonBodyOrSend400(bodyStr, res, routeName) {
|
|
897
|
+
const trimmed = String(bodyStr ?? '').trim();
|
|
898
|
+
if (!trimmed) return {};
|
|
899
|
+
try {
|
|
900
|
+
const parsed = JSON.parse(trimmed);
|
|
901
|
+
return parsed && typeof parsed === 'object' ? parsed : {};
|
|
902
|
+
} catch (err) {
|
|
903
|
+
recordDaemonDiagnostic(`${routeName}:parseBody`, err);
|
|
904
|
+
if (!res.headersSent) {
|
|
905
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
906
|
+
res.end(JSON.stringify({ ok: false, success: false, error: err?.message || 'Invalid JSON' }));
|
|
907
|
+
}
|
|
908
|
+
return null;
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
function sendRouteError500(res, routeName, err) {
|
|
913
|
+
recordDaemonDiagnostic(routeName, err);
|
|
914
|
+
if (!res.headersSent) {
|
|
915
|
+
res.writeHead(500, { 'Content-Type': 'application/json' });
|
|
916
|
+
res.end(JSON.stringify({ ok: false, success: false, error: String(err?.message || err) }));
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
const server = http.createServer(async (req, res) => {
|
|
921
|
+
try {
|
|
922
|
+
const url = new URL(req.url, `http://${req.headers.host || '127.0.0.1'}`);
|
|
923
|
+
|
|
924
|
+
const isStaticUiAsset = req.method === 'GET' && (
|
|
925
|
+
url.pathname === '/' ||
|
|
926
|
+
url.pathname === '/index.html' ||
|
|
927
|
+
url.pathname === '/widget' ||
|
|
928
|
+
url.pathname === '/widget.html' ||
|
|
929
|
+
url.pathname === '/simple' ||
|
|
930
|
+
url.pathname === '/simple.html' ||
|
|
931
|
+
url.pathname === '/advanced' ||
|
|
932
|
+
url.pathname === '/advanced.html' ||
|
|
933
|
+
url.pathname === '/preload.js' ||
|
|
934
|
+
url.pathname === '/favicon.ico'
|
|
935
|
+
);
|
|
936
|
+
|
|
937
|
+
// Host header is always verified (blocks DNS rebinding).
|
|
938
|
+
// Origin is strictly enforced for API / mutation endpoints.
|
|
939
|
+
const hostHeader = String(req.headers.host || '').toLowerCase();
|
|
940
|
+
const hostMatch = hostHeader.match(/^(\[[^\]]+\]|[^:]+)(?::(\d+))?$/);
|
|
941
|
+
const isHostValid = hostMatch && LOCAL_HOSTNAMES.has(hostMatch[1]);
|
|
942
|
+
const sidecarToken = process.env.ANTIGRAVITY_SIDECAR_UI_TOKEN;
|
|
943
|
+
const hasValidTokenQuery = Boolean(sidecarToken && url.searchParams.get('token') === sidecarToken);
|
|
944
|
+
|
|
945
|
+
if (!isHostValid || (!isStaticUiAsset && !hasValidTokenQuery && !isAllowedLocalRequest(req))) {
|
|
946
|
+
res.writeHead(403, { 'Content-Type': 'application/json' });
|
|
947
|
+
res.end(JSON.stringify({ success: false, error: 'Forbidden: cross-origin or non-local request' }));
|
|
948
|
+
return;
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
// Emit CORS headers ONLY echoing the specific validated origin (never wildcard '*')
|
|
952
|
+
const origin = req.headers.origin;
|
|
953
|
+
if (origin && isAllowedOriginHeader(origin)) {
|
|
954
|
+
res.setHeader('Access-Control-Allow-Origin', origin);
|
|
955
|
+
res.setHeader('Vary', 'Origin');
|
|
956
|
+
}
|
|
957
|
+
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
|
|
958
|
+
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, X-Sidecar-Token, X-Horizon-CSRF');
|
|
959
|
+
|
|
960
|
+
if (req.method === 'OPTIONS') {
|
|
961
|
+
res.writeHead(204);
|
|
962
|
+
res.end();
|
|
963
|
+
return;
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
if (url.pathname === '/api/csrf-token' && req.method === 'GET') {
|
|
967
|
+
res.writeHead(200, {
|
|
968
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
969
|
+
'Cache-Control': 'no-store'
|
|
970
|
+
});
|
|
971
|
+
res.end(JSON.stringify({ ok: true, csrfToken: HORIZON_CSRF_TOKEN }));
|
|
972
|
+
return;
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
// Enforce per-boot random CSRF token on browser-originated mutating POST requests
|
|
976
|
+
if (req.method === 'POST') {
|
|
977
|
+
const providedCsrf = req.headers['x-horizon-csrf'];
|
|
978
|
+
const isBrowserOriginated = Boolean(req.headers.origin);
|
|
979
|
+
const hasValidSidecarHeader = Boolean(sidecarToken && req.headers['x-sidecar-token'] === sidecarToken);
|
|
980
|
+
if (isBrowserOriginated && !hasValidSidecarHeader && !isValidCsrfToken(providedCsrf)) {
|
|
981
|
+
res.writeHead(403, { 'Content-Type': 'application/json' });
|
|
982
|
+
res.end(JSON.stringify({ success: false, error: 'Forbidden: missing or invalid X-Horizon-CSRF token' }));
|
|
983
|
+
return;
|
|
984
|
+
}
|
|
985
|
+
if (!isBrowserOriginated && providedCsrf !== undefined && !isValidCsrfToken(providedCsrf)) {
|
|
986
|
+
res.writeHead(403, { 'Content-Type': 'application/json' });
|
|
987
|
+
res.end(JSON.stringify({ success: false, error: 'Forbidden: invalid X-Horizon-CSRF token' }));
|
|
988
|
+
return;
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
if (url.pathname === '/favicon.ico') {
|
|
993
|
+
res.writeHead(204, { 'Cache-Control': 'public, max-age=86400' });
|
|
994
|
+
res.end();
|
|
995
|
+
return;
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
if (url.pathname === '/api/health') {
|
|
999
|
+
const addr = server.address();
|
|
1000
|
+
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
1001
|
+
res.end(JSON.stringify({
|
|
1002
|
+
ok: true,
|
|
1003
|
+
pid: process.pid,
|
|
1004
|
+
port: addr ? addr.port : 0,
|
|
1005
|
+
workspace: cachedLiveState?.workspace?.canonicalPath || process.cwd(),
|
|
1006
|
+
pinnedConversationId,
|
|
1007
|
+
diagnostics: getDaemonDiagnostics()
|
|
1008
|
+
}));
|
|
1009
|
+
return;
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
if (url.pathname === '/preload.js') {
|
|
1013
|
+
const candidates = [
|
|
1014
|
+
path.join(getHomeDir(), '.gemini', 'antigravity', 'lib', 'node_modules', 'sidecar_sdk', 'preload.js'),
|
|
1015
|
+
path.join(getHomeDir(), '.gemini', 'config', 'node_modules', 'sidecar_sdk', 'preload.js')
|
|
1016
|
+
];
|
|
1017
|
+
const target = candidates.find(p => fs.existsSync(p));
|
|
1018
|
+
res.writeHead(200, { 'Content-Type': 'application/javascript; charset=utf-8' });
|
|
1019
|
+
res.end(target ? fs.readFileSync(target) : '// no preload');
|
|
1020
|
+
return;
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
if (url.pathname === '/simple' || url.pathname === '/simple.html') {
|
|
1024
|
+
const qConv = url.searchParams.get('conversationId');
|
|
1025
|
+
if (qConv && qConv !== 'auto') {
|
|
1026
|
+
pinnedConversationId = qConv;
|
|
1027
|
+
}
|
|
1028
|
+
const initState = await refreshLiveState(false, pinnedConversationId);
|
|
1029
|
+
res.writeHead(200, {
|
|
1030
|
+
'Content-Type': 'text/html; charset=utf-8',
|
|
1031
|
+
'Cache-Control': 'no-store, no-cache, must-revalidate'
|
|
1032
|
+
});
|
|
1033
|
+
const simpleViewHtml = path.resolve(__dirname, '../../src/webview/simple_view.html');
|
|
1034
|
+
if (fs.existsSync(simpleViewHtml)) {
|
|
1035
|
+
let html = fs.readFileSync(simpleViewHtml, 'utf8');
|
|
1036
|
+
const mtimeMs = fs.statSync(simpleViewHtml).mtimeMs;
|
|
1037
|
+
const mtimeScript = `<script id="liveInitialMtime">window.__INITIAL_UI_MTIME__ = ${mtimeMs}; window.__HORIZON_CSRF_TOKEN__ = ${JSON.stringify(HORIZON_CSRF_TOKEN)};</script>`;
|
|
1038
|
+
if (initState) {
|
|
1039
|
+
initState.uiMtimeMs = mtimeMs;
|
|
1040
|
+
const safeJson = JSON.stringify(initState)
|
|
1041
|
+
.replace(/</g, '\\u003c')
|
|
1042
|
+
.replace(/\u2028/g, '\\u2028')
|
|
1043
|
+
.replace(/\u2029/g, '\\u2029');
|
|
1044
|
+
const stateScript = `<script id="liveInitialState">window.__LIVE_INITIAL_STATE__ = ${safeJson};</script>`;
|
|
1045
|
+
html = html.replace(
|
|
1046
|
+
'<script id="precomputedCatalogScript">',
|
|
1047
|
+
() => `${mtimeScript}\n${stateScript}\n<script id="precomputedCatalogScript">`
|
|
1048
|
+
);
|
|
1049
|
+
} else {
|
|
1050
|
+
html = html.replace(
|
|
1051
|
+
'<script id="precomputedCatalogScript">',
|
|
1052
|
+
() => `${mtimeScript}\n<script id="precomputedCatalogScript">`
|
|
1053
|
+
);
|
|
1054
|
+
}
|
|
1055
|
+
res.end(html);
|
|
1056
|
+
} else {
|
|
1057
|
+
res.end('<h1>Highbeam Simple View</h1>');
|
|
1058
|
+
}
|
|
1059
|
+
return;
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
if (url.pathname === '/advanced' || url.pathname === '/advanced.html') {
|
|
1063
|
+
const qConv = url.searchParams.get('conversationId');
|
|
1064
|
+
if (qConv && qConv !== 'auto') {
|
|
1065
|
+
pinnedConversationId = qConv;
|
|
1066
|
+
}
|
|
1067
|
+
const initState = await refreshLiveState(false, pinnedConversationId);
|
|
1068
|
+
res.writeHead(200, {
|
|
1069
|
+
'Content-Type': 'text/html; charset=utf-8',
|
|
1070
|
+
'Cache-Control': 'no-store, no-cache, must-revalidate'
|
|
1071
|
+
});
|
|
1072
|
+
const advancedViewHtml = path.resolve(__dirname, '../../src/webview/advanced_view.html');
|
|
1073
|
+
if (fs.existsSync(advancedViewHtml)) {
|
|
1074
|
+
let html = fs.readFileSync(advancedViewHtml, 'utf8');
|
|
1075
|
+
const mtimeMs = fs.statSync(advancedViewHtml).mtimeMs;
|
|
1076
|
+
const mtimeScript = `<script id="liveInitialMtime">window.__INITIAL_UI_MTIME__ = ${mtimeMs}; window.__HORIZON_CSRF_TOKEN__ = ${JSON.stringify(HORIZON_CSRF_TOKEN)};</script>`;
|
|
1077
|
+
if (initState) {
|
|
1078
|
+
initState.uiMtimeMs = mtimeMs;
|
|
1079
|
+
const safeJson = JSON.stringify(initState)
|
|
1080
|
+
.replace(/</g, '\\u003c')
|
|
1081
|
+
.replace(/\u2028/g, '\\u2028')
|
|
1082
|
+
.replace(/\u2029/g, '\\u2029');
|
|
1083
|
+
const stateScript = `<script id="liveInitialState">window.__LIVE_INITIAL_STATE__ = ${safeJson};</script>`;
|
|
1084
|
+
html = html.replace(
|
|
1085
|
+
'<script id="precomputedCatalogScript">',
|
|
1086
|
+
() => `${mtimeScript}\n${stateScript}\n<script id="precomputedCatalogScript">`
|
|
1087
|
+
);
|
|
1088
|
+
} else {
|
|
1089
|
+
html = html.replace(
|
|
1090
|
+
'<script id="precomputedCatalogScript">',
|
|
1091
|
+
() => `${mtimeScript}\n<script id="precomputedCatalogScript">`
|
|
1092
|
+
);
|
|
1093
|
+
}
|
|
1094
|
+
res.end(html);
|
|
1095
|
+
} else {
|
|
1096
|
+
res.end('<h1>Highbeam Advanced View</h1>');
|
|
1097
|
+
}
|
|
1098
|
+
return;
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
if (url.pathname === '/' || url.pathname === '/index.html' || url.pathname === '/widget' || url.pathname === '/widget.html') {
|
|
1102
|
+
const qConv = url.searchParams.get('conversationId');
|
|
1103
|
+
if (qConv && qConv !== 'auto') {
|
|
1104
|
+
pinnedConversationId = qConv;
|
|
1105
|
+
}
|
|
1106
|
+
const initState = await refreshLiveState(false, pinnedConversationId);
|
|
1107
|
+
res.writeHead(200, {
|
|
1108
|
+
'Content-Type': 'text/html; charset=utf-8',
|
|
1109
|
+
'Cache-Control': 'no-store, no-cache, must-revalidate'
|
|
1110
|
+
});
|
|
1111
|
+
const rawHtmlPath = fs.existsSync(horizonPanelHtml)
|
|
1112
|
+
? horizonPanelHtml
|
|
1113
|
+
: (fs.existsSync(sidePaneHtml) ? sidePaneHtml : null);
|
|
1114
|
+
if (rawHtmlPath) {
|
|
1115
|
+
let html = fs.readFileSync(rawHtmlPath, 'utf8');
|
|
1116
|
+
const mtimeMs = getHtmlMtimeMs();
|
|
1117
|
+
const mtimeScript = `<script id="liveInitialMtime">window.__INITIAL_UI_MTIME__ = ${mtimeMs}; window.__HORIZON_CSRF_TOKEN__ = ${JSON.stringify(HORIZON_CSRF_TOKEN)};</script>`;
|
|
1118
|
+
if (initState) {
|
|
1119
|
+
initState.uiMtimeMs = mtimeMs;
|
|
1120
|
+
const safeJson = JSON.stringify(initState)
|
|
1121
|
+
.replace(/</g, '\\u003c')
|
|
1122
|
+
.replace(/\u2028/g, '\\u2028')
|
|
1123
|
+
.replace(/\u2029/g, '\\u2029');
|
|
1124
|
+
const stateScript = `<script id="liveInitialState">window.__LIVE_INITIAL_STATE__ = ${safeJson};</script>`;
|
|
1125
|
+
html = html.replace(
|
|
1126
|
+
'<script id="precomputedCatalogScript">',
|
|
1127
|
+
() => `${mtimeScript}\n${stateScript}\n<script id="precomputedCatalogScript">`
|
|
1128
|
+
);
|
|
1129
|
+
} else {
|
|
1130
|
+
html = html.replace(
|
|
1131
|
+
'<script id="precomputedCatalogScript">',
|
|
1132
|
+
() => `${mtimeScript}\n<script id="precomputedCatalogScript">`
|
|
1133
|
+
);
|
|
1134
|
+
}
|
|
1135
|
+
res.end(html);
|
|
1136
|
+
} else {
|
|
1137
|
+
res.end('<h1>Highbeam Side-Pane</h1>');
|
|
1138
|
+
}
|
|
1139
|
+
return;
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
if (url.pathname === '/api/state') {
|
|
1143
|
+
const qConv = url.searchParams.get('conversationId');
|
|
1144
|
+
const qScenario = url.searchParams.get('scenario');
|
|
1145
|
+
if (qScenario) {
|
|
1146
|
+
process.env.HORIZON_DEMO = '1';
|
|
1147
|
+
process.env.HORIZON_DEMO_SCENARIO = qScenario;
|
|
1148
|
+
}
|
|
1149
|
+
if (qConv) {
|
|
1150
|
+
pinnedConversationId = qConv === 'auto' ? null : qConv;
|
|
1151
|
+
}
|
|
1152
|
+
const forceEval = Boolean(qConv || qScenario || url.searchParams.get('force') === '1');
|
|
1153
|
+
const state = await refreshLiveState(forceEval, pinnedConversationId);
|
|
1154
|
+
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
1155
|
+
res.end(JSON.stringify(state || {}));
|
|
1156
|
+
return;
|
|
1157
|
+
}
|
|
1158
|
+
|
|
1159
|
+
// Route: GET /api/cost-radar (Sprint 2.2 HTML/SVG timeline artifact, loopback only)
|
|
1160
|
+
if (url.pathname === '/api/cost-radar' && req.method === 'GET') {
|
|
1161
|
+
try {
|
|
1162
|
+
const state = await refreshLiveState(false, pinnedConversationId);
|
|
1163
|
+
const { html, summary } = buildCostRadarFromState(state || {});
|
|
1164
|
+
if (url.searchParams.get('format') === 'json') {
|
|
1165
|
+
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
|
|
1166
|
+
res.end(JSON.stringify({ ok: true, ...summary }));
|
|
1167
|
+
} else {
|
|
1168
|
+
res.writeHead(200, {
|
|
1169
|
+
'Content-Type': 'text/html; charset=utf-8',
|
|
1170
|
+
'Cache-Control': 'no-store',
|
|
1171
|
+
'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'; img-src data:"
|
|
1172
|
+
});
|
|
1173
|
+
res.end(html);
|
|
1174
|
+
}
|
|
1175
|
+
} catch (err) {
|
|
1176
|
+
sendRouteError500(res, 'GET /api/cost-radar', err);
|
|
1177
|
+
}
|
|
1178
|
+
return;
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
if (url.pathname === '/api/stream') {
|
|
1182
|
+
if (clients.size >= MAX_SSE_CLIENTS) {
|
|
1183
|
+
res.writeHead(429, { 'Content-Type': 'application/json' });
|
|
1184
|
+
res.end(JSON.stringify({ success: false, error: `SSE client cap reached (max ${MAX_SSE_CLIENTS})` }));
|
|
1185
|
+
return;
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
res.writeHead(200, {
|
|
1189
|
+
'Content-Type': 'text/event-stream',
|
|
1190
|
+
'Cache-Control': 'no-cache',
|
|
1191
|
+
'Connection': 'keep-alive'
|
|
1192
|
+
});
|
|
1193
|
+
|
|
1194
|
+
clients.add(res);
|
|
1195
|
+
const current = await refreshLiveState(true);
|
|
1196
|
+
if (current) {
|
|
1197
|
+
res.write(`data: ${JSON.stringify(current)}\n\n`);
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
req.on('close', () => {
|
|
1201
|
+
clients.delete(res);
|
|
1202
|
+
});
|
|
1203
|
+
return;
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
if (url.pathname === '/api/settings') {
|
|
1207
|
+
if (req.method === 'GET') {
|
|
1208
|
+
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
1209
|
+
res.end(JSON.stringify({ settings: loadSettings(defaultCacheDir), limits: SETTINGS_LIMITS }));
|
|
1210
|
+
return;
|
|
1211
|
+
}
|
|
1212
|
+
if (req.method === 'POST') {
|
|
1213
|
+
const bodyStr = await readRequestBody(req, res);
|
|
1214
|
+
if (bodyStr === null) return;
|
|
1215
|
+
const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/settings');
|
|
1216
|
+
if (body === null) return;
|
|
1217
|
+
const patch = {};
|
|
1218
|
+
for (const k of ['safeLimitTokens', 'reminderAtPct', 'modelOverrides']) {
|
|
1219
|
+
if (body && body[k] !== undefined) patch[k] = body[k];
|
|
1220
|
+
}
|
|
1221
|
+
try {
|
|
1222
|
+
const settings = saveSettings(defaultCacheDir, patch);
|
|
1223
|
+
const nextState = await refreshLiveState(true, pinnedConversationId);
|
|
1224
|
+
broadcastState(nextState);
|
|
1225
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
1226
|
+
res.end(JSON.stringify({ success: true, settings, state: nextState }));
|
|
1227
|
+
} catch (e) {
|
|
1228
|
+
sendRouteError500(res, 'POST /api/settings', e);
|
|
1229
|
+
}
|
|
1230
|
+
return;
|
|
1231
|
+
}
|
|
1232
|
+
res.writeHead(405);
|
|
1233
|
+
res.end('Method Not Allowed');
|
|
1234
|
+
return;
|
|
1235
|
+
}
|
|
1236
|
+
|
|
1237
|
+
// Route: POST /api/prune (Prefix-Safe Surgical Context Pruner & AST Folder)
|
|
1238
|
+
if (url.pathname === '/api/prune' && req.method === 'POST') {
|
|
1239
|
+
const bodyStr = await readRequestBody(req, res);
|
|
1240
|
+
if (bodyStr === null) return;
|
|
1241
|
+
const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/prune');
|
|
1242
|
+
if (body === null) return;
|
|
1243
|
+
const targetConvId = body.conversationId || pinnedConversationId || cachedLiveState?.sessionId || null;
|
|
1244
|
+
const sessionInfo = findSessionDirectory(targetConvId);
|
|
1245
|
+
if (!sessionInfo || !sessionInfo.sessionDir) {
|
|
1246
|
+
res.writeHead(404, { 'Content-Type': 'application/json' });
|
|
1247
|
+
res.end(JSON.stringify({ success: false, error: 'Active session directory not found' }));
|
|
1248
|
+
return;
|
|
1249
|
+
}
|
|
1250
|
+
const pruneResult = pruneSessionTranscript(sessionInfo.sessionDir, {
|
|
1251
|
+
dryRun: Boolean(body.dryRun),
|
|
1252
|
+
forceHotCache: Boolean(body.forceHotCache),
|
|
1253
|
+
cacheDir: defaultCacheDir
|
|
1254
|
+
});
|
|
1255
|
+
const nextState = await refreshLiveState(true, targetConvId);
|
|
1256
|
+
broadcastState(nextState);
|
|
1257
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
1258
|
+
res.end(JSON.stringify({ ...pruneResult, state: nextState }));
|
|
1259
|
+
return;
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
// Route: POST /api/host/reap (Host Process & Zombie Subagent/MCP Watchdog)
|
|
1263
|
+
if (url.pathname === '/api/host/reap' && req.method === 'POST') {
|
|
1264
|
+
const bodyStr = await readRequestBody(req, res);
|
|
1265
|
+
if (bodyStr === null) return;
|
|
1266
|
+
const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/host/reap');
|
|
1267
|
+
if (body === null) return;
|
|
1268
|
+
const reapResult = await reapOrphanProcesses(body.pids || null);
|
|
1269
|
+
const nextState = await refreshLiveState(true, pinnedConversationId);
|
|
1270
|
+
broadcastState(nextState);
|
|
1271
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
1272
|
+
res.end(JSON.stringify({ ...reapResult, state: nextState }));
|
|
1273
|
+
return;
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
// Route: POST /api/open-brain (Dual-Target Session Jump: Alt+Click opens ~/.gemini/<surface>/brain/<uuid>/)
|
|
1277
|
+
if (url.pathname === '/api/open-brain' && req.method === 'POST') {
|
|
1278
|
+
const bodyStr = await readRequestBody(req, res);
|
|
1279
|
+
if (bodyStr === null) return;
|
|
1280
|
+
const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/open-brain');
|
|
1281
|
+
if (body === null) return;
|
|
1282
|
+
const targetConvId = body.conversationId || pinnedConversationId || cachedLiveState?.sessionId || null;
|
|
1283
|
+
const requestedSurface = ['antigravity', 'antigravity-ide', 'antigravity-cli'].includes(body.surface)
|
|
1284
|
+
? body.surface
|
|
1285
|
+
: null;
|
|
1286
|
+
const sessionInfo = findSessionDirectory(targetConvId);
|
|
1287
|
+
const safeId = String(targetConvId || sessionInfo?.sessionId || '').replace(/[^a-zA-Z0-9_-]/g, '');
|
|
1288
|
+
const matchedInfo = (sessionInfo && sessionInfo.sessionId === safeId) ? sessionInfo : null;
|
|
1289
|
+
const surfaceName = requestedSurface || matchedInfo?.storeName || sessionInfo?.storeName || cachedLiveState?.storeSource || 'antigravity';
|
|
1290
|
+
|
|
1291
|
+
let resolvedBrainDir = null;
|
|
1292
|
+
if (matchedInfo && matchedInfo.sessionDir && fs.existsSync(matchedInfo.sessionDir)) {
|
|
1293
|
+
resolvedBrainDir = matchedInfo.sessionDir;
|
|
1294
|
+
} else if (safeId) {
|
|
1295
|
+
const directBrainDir = path.join(getHomeDir(), '.gemini', surfaceName, 'brain', safeId);
|
|
1296
|
+
if (fs.existsSync(directBrainDir)) {
|
|
1297
|
+
resolvedBrainDir = directBrainDir;
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
let fallbackUsed = false;
|
|
1301
|
+
|
|
1302
|
+
if (!resolvedBrainDir || !fs.existsSync(resolvedBrainDir)) {
|
|
1303
|
+
const convDir = path.join(getHomeDir(), '.gemini', surfaceName, 'conversations');
|
|
1304
|
+
if (fs.existsSync(convDir)) {
|
|
1305
|
+
resolvedBrainDir = convDir;
|
|
1306
|
+
fallbackUsed = true;
|
|
1307
|
+
} else {
|
|
1308
|
+
const surfaceRoot = path.join(getHomeDir(), '.gemini', surfaceName);
|
|
1309
|
+
if (fs.existsSync(surfaceRoot)) {
|
|
1310
|
+
resolvedBrainDir = surfaceRoot;
|
|
1311
|
+
fallbackUsed = true;
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
|
|
1316
|
+
if (!resolvedBrainDir || !fs.existsSync(resolvedBrainDir)) {
|
|
1317
|
+
res.writeHead(404, { 'Content-Type': 'application/json' });
|
|
1318
|
+
res.end(JSON.stringify({ success: false, error: 'Session brain directory not found' }));
|
|
1319
|
+
return;
|
|
1320
|
+
}
|
|
1321
|
+
|
|
1322
|
+
if (!body.dryRun && process.env.HORIZON_TEST_NO_SPAWN !== '1') {
|
|
1323
|
+
try {
|
|
1324
|
+
const onSpawnDone = (spawnErr) => {
|
|
1325
|
+
if (spawnErr) recordDaemonDiagnostic('POST /api/open-brain:execFile', spawnErr);
|
|
1326
|
+
};
|
|
1327
|
+
if (process.platform === 'win32') {
|
|
1328
|
+
execFile('explorer.exe', [resolvedBrainDir], onSpawnDone);
|
|
1329
|
+
} else if (process.platform === 'darwin') {
|
|
1330
|
+
execFile('open', [resolvedBrainDir], onSpawnDone);
|
|
1331
|
+
} else {
|
|
1332
|
+
execFile('xdg-open', [resolvedBrainDir], onSpawnDone);
|
|
1333
|
+
}
|
|
1334
|
+
} catch (err) {
|
|
1335
|
+
recordDaemonDiagnostic('POST /api/open-brain:spawn', err);
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
1340
|
+
res.end(JSON.stringify({
|
|
1341
|
+
success: true,
|
|
1342
|
+
conversationId: safeId,
|
|
1343
|
+
surface: surfaceName,
|
|
1344
|
+
surfaceTag: resolveSurfaceTag(surfaceName),
|
|
1345
|
+
brainDir: resolvedBrainDir,
|
|
1346
|
+
fallbackUsed
|
|
1347
|
+
}));
|
|
1348
|
+
return;
|
|
1349
|
+
}
|
|
1350
|
+
|
|
1351
|
+
// Route: POST /api/handoff or /api/handoff/generate (The Baton Pass /handoff Markdown Generator)
|
|
1352
|
+
if ((url.pathname === '/api/handoff' || url.pathname === '/api/handoff/generate') && req.method === 'POST') {
|
|
1353
|
+
const bodyStr = await readRequestBody(req, res);
|
|
1354
|
+
if (bodyStr === null) return;
|
|
1355
|
+
const body = parseJsonBodyOrSend400(bodyStr, res, `POST ${url.pathname}`);
|
|
1356
|
+
if (body === null) return;
|
|
1357
|
+
const targetConvId = body.conversationId || pinnedConversationId || cachedLiveState?.sessionId || null;
|
|
1358
|
+
const state = await refreshLiveState(false, targetConvId) || cachedLiveState || {};
|
|
1359
|
+
const handoffRes = generateHandoffMarkdown(state, {
|
|
1360
|
+
timestamp: body.timestamp || null,
|
|
1361
|
+
workspacePath: body.workspacePath || state?.workspace?.canonicalPath || process.cwd(),
|
|
1362
|
+
writeToDisk: body.writeToDisk !== false
|
|
1363
|
+
});
|
|
1364
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
1365
|
+
res.end(JSON.stringify(handoffRes));
|
|
1366
|
+
return;
|
|
1367
|
+
}
|
|
1368
|
+
|
|
1369
|
+
// Route: POST /api/hooks/dampen (Fail-Open CLI Command Dampening Hook in .agents/hooks.json)
|
|
1370
|
+
if (url.pathname === '/api/hooks/dampen' && req.method === 'POST') {
|
|
1371
|
+
const bodyStr = await readRequestBody(req, res);
|
|
1372
|
+
if (bodyStr === null) return;
|
|
1373
|
+
const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/hooks/dampen');
|
|
1374
|
+
if (body === null) return;
|
|
1375
|
+
const wsPath = body.workspacePath || cachedLiveState?.workspace?.canonicalPath || process.cwd();
|
|
1376
|
+
const hookRes = registerCliDampeningHook(wsPath, {
|
|
1377
|
+
command: body.command || '',
|
|
1378
|
+
maxLines: body.maxLines || 100,
|
|
1379
|
+
logFile: body.logFile || '.agents/tmp/cli_stdout.log',
|
|
1380
|
+
writeToDisk: body.writeToDisk !== false
|
|
1381
|
+
});
|
|
1382
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
1383
|
+
res.end(JSON.stringify(hookRes));
|
|
1384
|
+
return;
|
|
1385
|
+
}
|
|
1386
|
+
|
|
1387
|
+
// Route: POST /api/rules/promote (Attention-Aware Rule Promotion in Primacy/Recency zones)
|
|
1388
|
+
if (url.pathname === '/api/rules/promote' && req.method === 'POST') {
|
|
1389
|
+
const bodyStr = await readRequestBody(req, res);
|
|
1390
|
+
if (bodyStr === null) return;
|
|
1391
|
+
const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/rules/promote');
|
|
1392
|
+
if (body === null) return;
|
|
1393
|
+
const wsPath = body.targetPath || body.workspacePath || cachedLiveState?.workspace?.canonicalPath || process.cwd();
|
|
1394
|
+
// Only rule files may be written: a directory target, or an explicit AGENTS.md / GEMINI.md / .agents/rules/*.md file.
|
|
1395
|
+
let isDirTarget = false;
|
|
1396
|
+
try {
|
|
1397
|
+
isDirTarget = fs.existsSync(wsPath) && fs.statSync(wsPath).isDirectory();
|
|
1398
|
+
} catch (err) {
|
|
1399
|
+
if (err?.code !== 'ENOENT') recordDaemonDiagnostic('POST /api/rules/promote:statTarget', err);
|
|
1400
|
+
}
|
|
1401
|
+
const badTarget = !isDirTarget && !RULE_FILE_RE.test(String(wsPath));
|
|
1402
|
+
const badFileName = body.targetFileName != null && !/^[\w.-]+\.md$/i.test(String(body.targetFileName));
|
|
1403
|
+
if (badTarget || badFileName) {
|
|
1404
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
1405
|
+
res.end(JSON.stringify({ success: false, error: 'Rule promotion target must be a rule file (AGENTS.md, GEMINI.md, .agents/rules/*.md)' }));
|
|
1406
|
+
return;
|
|
1407
|
+
}
|
|
1408
|
+
const fallbackRule = cachedLiveState?.brainSignals?.userCorrectionTexts?.[0] ||
|
|
1409
|
+
'Follow all in-chat user corrections and architectural constraints.';
|
|
1410
|
+
const resolvedRuleText = body.ruleText || fallbackRule;
|
|
1411
|
+
|
|
1412
|
+
const liveCachedTokens = Number(
|
|
1413
|
+
body.cachedTokens ??
|
|
1414
|
+
cachedLiveState?.window?.totalActiveTokens ??
|
|
1415
|
+
cachedLiveState?.tokens?.total ??
|
|
1416
|
+
0
|
|
1417
|
+
);
|
|
1418
|
+
const liveTtlSec = Math.max(0, Number(
|
|
1419
|
+
body.cacheTtlSeconds ??
|
|
1420
|
+
cachedLiveState?.quota?.cache?.ttlRemainingSec ??
|
|
1421
|
+
cachedLiveState?.cache?.ttlRemainingSec ??
|
|
1422
|
+
0
|
|
1423
|
+
) || 0);
|
|
1424
|
+
const liveTurnCount = Number(
|
|
1425
|
+
body.turnCount ??
|
|
1426
|
+
cachedLiveState?.window?.turnCount ??
|
|
1427
|
+
cachedLiveState?.turnCount ??
|
|
1428
|
+
1
|
|
1429
|
+
);
|
|
1430
|
+
const shieldStatus = prefixCacheShield.getStatus({
|
|
1431
|
+
cachedTokens: liveCachedTokens,
|
|
1432
|
+
cacheTtlSeconds: liveTtlSec,
|
|
1433
|
+
turnCount: liveTurnCount
|
|
1434
|
+
});
|
|
1435
|
+
|
|
1436
|
+
if (shieldStatus.locked && body.writeToDisk !== false && !body.forceHotCache) {
|
|
1437
|
+
try {
|
|
1438
|
+
const targetWsDir = isDirTarget ? wsPath : path.dirname(wsPath);
|
|
1439
|
+
reflectorQueue.setWorkspaceDir(targetWsDir);
|
|
1440
|
+
reflectorQueue.enqueue({
|
|
1441
|
+
directive_action: resolvedRuleText,
|
|
1442
|
+
domain: 'rules',
|
|
1443
|
+
sessionId: cachedLiveState?.sessionId || pinnedConversationId || 'default-session'
|
|
1444
|
+
});
|
|
1445
|
+
} catch (err) {
|
|
1446
|
+
recordDaemonDiagnostic('POST /api/rules/promote:enqueueStaged', err);
|
|
1447
|
+
}
|
|
1448
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
1449
|
+
res.end(JSON.stringify({
|
|
1450
|
+
success: false,
|
|
1451
|
+
staged: true,
|
|
1452
|
+
requiresConfirmation: true,
|
|
1453
|
+
ttlRemainingSec: liveTtlSec,
|
|
1454
|
+
cachedTokens: liveCachedTokens,
|
|
1455
|
+
reason: `Warm prompt cache active (${liveTtlSec}s TTL). Rule promotion staged until cache expires to protect your 95% KV discount.`
|
|
1456
|
+
}));
|
|
1457
|
+
return;
|
|
1458
|
+
}
|
|
1459
|
+
|
|
1460
|
+
const promoRes = promoteRuleWithAttentionZone(wsPath, resolvedRuleText, {
|
|
1461
|
+
zone: body.zone || 'primacy',
|
|
1462
|
+
targetFileName: body.targetFileName || null,
|
|
1463
|
+
maxLines: body.maxLines || 200,
|
|
1464
|
+
writeToDisk: body.writeToDisk !== false
|
|
1465
|
+
});
|
|
1466
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
1467
|
+
res.end(JSON.stringify(promoRes));
|
|
1468
|
+
return;
|
|
1469
|
+
}
|
|
1470
|
+
|
|
1471
|
+
// Route: POST /api/export/sanitized (Zero-PII Sanitized Snapshot Exporter)
|
|
1472
|
+
if (url.pathname === '/api/export/sanitized' && req.method === 'POST') {
|
|
1473
|
+
const bodyStr = await readRequestBody(req, res);
|
|
1474
|
+
if (bodyStr === null) return;
|
|
1475
|
+
const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/export/sanitized');
|
|
1476
|
+
if (body === null) return;
|
|
1477
|
+
const targetState = body.state || cachedLiveState || (await refreshLiveState(true, pinnedConversationId)) || {};
|
|
1478
|
+
const outPath = path.join(defaultCacheDir, `sanitized_snapshot_${Date.now()}.json`);
|
|
1479
|
+
const expRes = exportSanitizedSnapshot(targetState, {
|
|
1480
|
+
format: body.format || 'json',
|
|
1481
|
+
outputPath: outPath
|
|
1482
|
+
});
|
|
1483
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
1484
|
+
res.end(JSON.stringify(expRes));
|
|
1485
|
+
return;
|
|
1486
|
+
}
|
|
1487
|
+
|
|
1488
|
+
// Route: POST /api/surgeon (Offline Tool-Output Surgeon)
|
|
1489
|
+
if (url.pathname === '/api/surgeon' && req.method === 'POST') {
|
|
1490
|
+
const bodyStr = await readRequestBody(req, res);
|
|
1491
|
+
if (bodyStr === null) return;
|
|
1492
|
+
const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/surgeon');
|
|
1493
|
+
if (body === null) return;
|
|
1494
|
+
const targetConvId = body.conversationId || pinnedConversationId || cachedLiveState?.sessionId || null;
|
|
1495
|
+
const sessionInfo = findSessionDirectory(targetConvId);
|
|
1496
|
+
const transcriptFile = body.transcriptPath ||
|
|
1497
|
+
(sessionInfo?.sessionDir ? path.join(sessionInfo.sessionDir, '.system_generated', 'logs', 'transcript_full.jsonl') : null);
|
|
1498
|
+
const surgRes = executeToolOutputSurgery(transcriptFile, { dryRun: Boolean(body.dryRun) });
|
|
1499
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
1500
|
+
res.end(JSON.stringify(surgRes));
|
|
1501
|
+
return;
|
|
1502
|
+
}
|
|
1503
|
+
|
|
1504
|
+
// Route: GET /api/memory/resume (SQLite FTS5 Episodic Memory Resume Pack)
|
|
1505
|
+
if (url.pathname === '/api/memory/resume' && req.method === 'GET') {
|
|
1506
|
+
const query = url.searchParams.get('q') || '';
|
|
1507
|
+
const wsPath = url.searchParams.get('workspace') || cachedLiveState?.workspace?.canonicalPath || process.cwd();
|
|
1508
|
+
const epDbPath = path.join(getFlightcheckDir(), 'episodic_memory.db');
|
|
1509
|
+
const pack = await synthesizeResumeHerePack(epDbPath, { workspacePath: wsPath, query });
|
|
1510
|
+
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
1511
|
+
res.end(JSON.stringify(pack));
|
|
1512
|
+
return;
|
|
1513
|
+
}
|
|
1514
|
+
|
|
1515
|
+
// Helper: Resolve live or caller-supplied warm-cache state for ISS-041 PrefixCacheShield fencing
|
|
1516
|
+
const resolveRouteCacheContext = (body = {}) => {
|
|
1517
|
+
const cachedTokens = body.cachedTokens !== undefined
|
|
1518
|
+
? Number(body.cachedTokens || 0)
|
|
1519
|
+
: Number(cachedLiveState?.window?.totalActiveTokens ?? cachedLiveState?.tokens?.total ?? 0);
|
|
1520
|
+
const cacheTtlSeconds = body.cacheTtlSeconds !== undefined
|
|
1521
|
+
? Number(body.cacheTtlSeconds || 0)
|
|
1522
|
+
: Number(cachedLiveState?.quota?.cache?.ttlRemainingSec ?? cachedLiveState?.cache?.ttlRemainingSec ?? 0);
|
|
1523
|
+
const cacheState = body.cacheState || body.options?.cacheState || null;
|
|
1524
|
+
const cacheWarm = body.cacheWarm === true || body.options?.cacheWarm === true;
|
|
1525
|
+
return {
|
|
1526
|
+
cachedTokens,
|
|
1527
|
+
cacheTtlSeconds,
|
|
1528
|
+
ttlRemainingSeconds: cacheTtlSeconds,
|
|
1529
|
+
...(cacheState ? { cacheState } : {}),
|
|
1530
|
+
...(cacheWarm ? { cacheWarm: true } : {})
|
|
1531
|
+
};
|
|
1532
|
+
};
|
|
1533
|
+
|
|
1534
|
+
// Route: POST /api/shield/flush (Flush PrefixCacheShield staged deltas — fenced when cache is warm unless force=true)
|
|
1535
|
+
if (url.pathname === '/api/shield/flush' && req.method === 'POST') {
|
|
1536
|
+
const bodyStr = await readRequestBody(req, res);
|
|
1537
|
+
if (bodyStr === null) return;
|
|
1538
|
+
const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/shield/flush');
|
|
1539
|
+
if (body === null) return;
|
|
1540
|
+
const sessCtx = resolveRouteCacheContext(body);
|
|
1541
|
+
const forceFlush = body.force === true || body.forceColdBust === true;
|
|
1542
|
+
if (!forceFlush && prefixCacheShield.isPrefixLocked(sessCtx)) {
|
|
1543
|
+
const shieldState = prefixCacheShield.getStatus(sessCtx);
|
|
1544
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
1545
|
+
res.end(JSON.stringify({
|
|
1546
|
+
success: true,
|
|
1547
|
+
flushed: false,
|
|
1548
|
+
deferred: true,
|
|
1549
|
+
reason: 'CACHE_WARM_FENCE',
|
|
1550
|
+
queuedCount: shieldState.queuedCount,
|
|
1551
|
+
ttlRemainingSec: sessCtx.cacheTtlSeconds,
|
|
1552
|
+
cachedTokens: sessCtx.cachedTokens
|
|
1553
|
+
}));
|
|
1554
|
+
return;
|
|
1555
|
+
}
|
|
1556
|
+
const resPayload = prefixCacheShield._flushAllNow('MANUAL_FLUSH');
|
|
1557
|
+
const nextState = await refreshLiveState(true, pinnedConversationId);
|
|
1558
|
+
broadcastState(nextState);
|
|
1559
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
1560
|
+
res.end(JSON.stringify({ success: true, deferred: false, ...resPayload, state: nextState }));
|
|
1561
|
+
return;
|
|
1562
|
+
}
|
|
1563
|
+
|
|
1564
|
+
// Route: POST /api/tail/trim (Read-Only Host Transcript Analysis -> Staged Plugin Output)
|
|
1565
|
+
if (url.pathname === '/api/tail/trim' && req.method === 'POST') {
|
|
1566
|
+
const bodyStr = await readRequestBody(req, res);
|
|
1567
|
+
if (bodyStr === null) return;
|
|
1568
|
+
const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/tail/trim');
|
|
1569
|
+
if (body === null) return;
|
|
1570
|
+
const targetConvId = body.conversationId || pinnedConversationId || cachedLiveState?.sessionId || null;
|
|
1571
|
+
const sessionInfo = findSessionDirectory(targetConvId);
|
|
1572
|
+
const transcriptFile = body.transcriptPath || (sessionInfo?.sessionDir
|
|
1573
|
+
? path.join(sessionInfo.sessionDir, '.system_generated', 'logs', 'transcript_full.jsonl')
|
|
1574
|
+
: null);
|
|
1575
|
+
let trimRes = {
|
|
1576
|
+
trimmed: false,
|
|
1577
|
+
message: 'No transcript found',
|
|
1578
|
+
hostTranscriptMutated: false,
|
|
1579
|
+
persistBlockedReason: body.persist ? 'HOST_TRANSCRIPT_READONLY_GUARD' : null
|
|
1580
|
+
};
|
|
1581
|
+
if (transcriptFile && fs.existsSync(transcriptFile)) {
|
|
1582
|
+
try {
|
|
1583
|
+
// Strictly read-only ('r') on host Antigravity transcript logs (AGENTS.md Invariant 4 & ISS-040)
|
|
1584
|
+
const fd = fs.openSync(transcriptFile, 'r');
|
|
1585
|
+
let rawTranscript = '';
|
|
1586
|
+
try {
|
|
1587
|
+
rawTranscript = fs.readFileSync(fd, 'utf8');
|
|
1588
|
+
} finally {
|
|
1589
|
+
fs.closeSync(fd);
|
|
1590
|
+
}
|
|
1591
|
+
const lines = rawTranscript.trim().split('\n').filter(Boolean);
|
|
1592
|
+
const steps = lines.map(l => JSON.parse(l));
|
|
1593
|
+
const offloadDir = body.cwd
|
|
1594
|
+
? path.join(body.cwd, '.agents', 'tmp')
|
|
1595
|
+
: path.join(defaultCacheDir, 'staged_trims', 'offloads');
|
|
1596
|
+
trimRes = trimUncachedTail(steps, {
|
|
1597
|
+
cachedTokens: cachedLiveState?.window?.totalActiveTokens || 50000,
|
|
1598
|
+
...(body.cwd ? { cwd: body.cwd } : { offloadDir })
|
|
1599
|
+
});
|
|
1600
|
+
if (trimRes && typeof trimRes === 'object') {
|
|
1601
|
+
trimRes.hostTranscriptMutated = false;
|
|
1602
|
+
trimRes.persistBlockedReason = body.persist ? 'HOST_TRANSCRIPT_READONLY_GUARD' : null;
|
|
1603
|
+
}
|
|
1604
|
+
if (trimRes && trimRes.modifiedCount > 0 && trimRes.headBytesPreserved) {
|
|
1605
|
+
const safeSessionSlug = String(sessionInfo?.sessionId || targetConvId || 'session').replace(/[^a-zA-Z0-9_-]/g, '_');
|
|
1606
|
+
const stagedDir = path.join(defaultCacheDir, 'staged_trims');
|
|
1607
|
+
const stagedFullPath = path.join(stagedDir, `${safeSessionSlug}.transcript_full.staged.jsonl`);
|
|
1608
|
+
const serialized = trimRes.prunedSteps.map(s => JSON.stringify(s)).join('\n') + '\n';
|
|
1609
|
+
atomicWriteFileSync(stagedFullPath, serialized, { encoding: 'utf8' });
|
|
1610
|
+
trimRes.trimmed = true;
|
|
1611
|
+
trimRes.stagedOnly = true;
|
|
1612
|
+
trimRes.hostTranscriptMutated = false;
|
|
1613
|
+
trimRes.stagedPath = stagedFullPath;
|
|
1614
|
+
if (savedQuotaLedger && Number(trimRes.tokensSaved) > 0) {
|
|
1615
|
+
try {
|
|
1616
|
+
savedQuotaLedger.recordSaving({
|
|
1617
|
+
sessionId: String(sessionInfo?.sessionId || targetConvId || 'default-session'),
|
|
1618
|
+
eventType: SAVINGS_EVENT_TYPES.COMPACTION_RECLAIMED,
|
|
1619
|
+
tokensSaved: Math.round(Number(trimRes.tokensSaved)),
|
|
1620
|
+
dedupeKey: `tailtrim:${safeSessionSlug}:${trimRes.modifiedCount}`,
|
|
1621
|
+
detail: `Trimmed ${trimRes.modifiedCount} uncached tail step(s)`
|
|
1622
|
+
});
|
|
1623
|
+
} catch (err) {
|
|
1624
|
+
recordDaemonDiagnostic('POST /api/tail/trim:ledger', err);
|
|
1625
|
+
}
|
|
1626
|
+
}
|
|
1627
|
+
|
|
1628
|
+
// Also stage companion transcript.jsonl preview without mutating host logs
|
|
1629
|
+
const compactFile = path.join(path.dirname(transcriptFile), 'transcript.jsonl');
|
|
1630
|
+
if (fs.existsSync(compactFile)) {
|
|
1631
|
+
try {
|
|
1632
|
+
const cFd = fs.openSync(compactFile, 'r');
|
|
1633
|
+
let rawCompact = '';
|
|
1634
|
+
try {
|
|
1635
|
+
rawCompact = fs.readFileSync(cFd, 'utf8');
|
|
1636
|
+
} finally {
|
|
1637
|
+
fs.closeSync(cFd);
|
|
1638
|
+
}
|
|
1639
|
+
const cLines = rawCompact.trim().split('\n').filter(Boolean);
|
|
1640
|
+
const cSteps = cLines.map(l => JSON.parse(l));
|
|
1641
|
+
const cRes = trimUncachedTail(cSteps, {
|
|
1642
|
+
cachedTokens: cachedLiveState?.window?.totalActiveTokens || 50000,
|
|
1643
|
+
...(body.cwd ? { cwd: body.cwd } : { offloadDir })
|
|
1644
|
+
});
|
|
1645
|
+
if (cRes && cRes.modifiedCount > 0 && cRes.headBytesPreserved) {
|
|
1646
|
+
const stagedCompactPath = path.join(stagedDir, `${safeSessionSlug}.transcript.staged.jsonl`);
|
|
1647
|
+
atomicWriteFileSync(
|
|
1648
|
+
stagedCompactPath,
|
|
1649
|
+
cRes.prunedSteps.map(s => JSON.stringify(s)).join('\n') + '\n',
|
|
1650
|
+
{ encoding: 'utf8' }
|
|
1651
|
+
);
|
|
1652
|
+
trimRes.stagedCompactPath = stagedCompactPath;
|
|
1653
|
+
}
|
|
1654
|
+
} catch (err) {
|
|
1655
|
+
recordDaemonDiagnostic('POST /api/tail/trim:stageCompact', err);
|
|
1656
|
+
}
|
|
1657
|
+
}
|
|
1658
|
+
}
|
|
1659
|
+
} catch (e) {
|
|
1660
|
+
recordDaemonDiagnostic('POST /api/tail/trim:readOrStage', e);
|
|
1661
|
+
trimRes = { trimmed: false, hostTranscriptMutated: false, error: String(e?.message || e) };
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
const nextState = await refreshLiveState(true, targetConvId);
|
|
1665
|
+
broadcastState(nextState);
|
|
1666
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
1667
|
+
res.end(JSON.stringify({ success: true, ...trimRes, state: nextState }));
|
|
1668
|
+
return;
|
|
1669
|
+
}
|
|
1670
|
+
|
|
1671
|
+
// Route: POST /api/rsi/evolve & POST /api/instincts/promote (Synthesize / Promote Instincts via PrefixCacheShield fence)
|
|
1672
|
+
if ((url.pathname === '/api/rsi/evolve' || url.pathname === '/api/instincts/promote') && req.method === 'POST') {
|
|
1673
|
+
const bodyStr = await readRequestBody(req, res);
|
|
1674
|
+
if (bodyStr === null) return;
|
|
1675
|
+
const body = parseJsonBodyOrSend400(bodyStr, res, `POST ${url.pathname}`);
|
|
1676
|
+
if (body === null) return;
|
|
1677
|
+
const sessCtx = resolveRouteCacheContext(body);
|
|
1678
|
+
const forceColdBust = Boolean(body.force || body.forceColdBust || body.options?.forceColdBust);
|
|
1679
|
+
let evolveRes = null;
|
|
1680
|
+
try {
|
|
1681
|
+
if (body.ruleText && url.pathname === '/api/instincts/promote') {
|
|
1682
|
+
const wsPath = body.workspacePath || cachedLiveState?.workspace?.canonicalPath || process.cwd();
|
|
1683
|
+
evolveRes = promoteRuleWithAttentionZone(wsPath, body.ruleText, {
|
|
1684
|
+
...sessCtx,
|
|
1685
|
+
...(body.options || {}),
|
|
1686
|
+
zone: body.zone || 'primacy',
|
|
1687
|
+
targetFileName: body.targetFileName || 'AGENTS.md',
|
|
1688
|
+
prefixCacheShield,
|
|
1689
|
+
forceColdBust
|
|
1690
|
+
});
|
|
1691
|
+
} else {
|
|
1692
|
+
const domain = body.domain || 'general';
|
|
1693
|
+
evolveRes = rsiEngine?.evolveDomainToSkill
|
|
1694
|
+
? rsiEngine.evolveDomainToSkill(domain, {
|
|
1695
|
+
...sessCtx,
|
|
1696
|
+
...(body.options || {}),
|
|
1697
|
+
prefixCacheShield,
|
|
1698
|
+
forceColdBust
|
|
1699
|
+
})
|
|
1700
|
+
: { error: 'RSI engine not initialized' };
|
|
1701
|
+
}
|
|
1702
|
+
} catch (err) {
|
|
1703
|
+
recordDaemonDiagnostic(`POST ${url.pathname}`, err);
|
|
1704
|
+
evolveRes = { success: false, error: String(err?.message || err) };
|
|
1705
|
+
}
|
|
1706
|
+
const nextState = await refreshLiveState(true, pinnedConversationId);
|
|
1707
|
+
broadcastState(nextState);
|
|
1708
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
1709
|
+
res.end(JSON.stringify({ success: !evolveRes?.error, ...evolveRes, state: nextState }));
|
|
1710
|
+
return;
|
|
1711
|
+
}
|
|
1712
|
+
|
|
1713
|
+
// Route: POST /api/rules/u-curve-optimize & POST /api/ushape/reorder (Reorder Rules via PrefixCacheShield fence)
|
|
1714
|
+
if ((url.pathname === '/api/rules/u-curve-optimize' || url.pathname === '/api/ushape/reorder') && req.method === 'POST') {
|
|
1715
|
+
const bodyStr = await readRequestBody(req, res);
|
|
1716
|
+
if (bodyStr === null) return;
|
|
1717
|
+
const body = parseJsonBodyOrSend400(bodyStr, res, `POST ${url.pathname}`);
|
|
1718
|
+
if (body === null) return;
|
|
1719
|
+
const wsPath = body.workspacePath || cachedLiveState?.workspace?.canonicalPath || process.cwd();
|
|
1720
|
+
const targetRule = body.filePath || path.join(wsPath, 'AGENTS.md');
|
|
1721
|
+
const sessCtx = resolveRouteCacheContext(body);
|
|
1722
|
+
const forceColdBust = Boolean(body.force || body.forceColdBust || body.options?.forceColdBust);
|
|
1723
|
+
let optRes = null;
|
|
1724
|
+
try {
|
|
1725
|
+
optRes = uShapedOptimizer.optimizeRuleFile(targetRule, {
|
|
1726
|
+
...sessCtx,
|
|
1727
|
+
...(body.options || {}),
|
|
1728
|
+
prefixCacheShield,
|
|
1729
|
+
forceColdBust
|
|
1730
|
+
});
|
|
1731
|
+
} catch (err) {
|
|
1732
|
+
recordDaemonDiagnostic(`POST ${url.pathname}`, err);
|
|
1733
|
+
optRes = { success: false, error: String(err?.message || err) };
|
|
1734
|
+
}
|
|
1735
|
+
const nextState = await refreshLiveState(true, pinnedConversationId);
|
|
1736
|
+
broadcastState(nextState);
|
|
1737
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
1738
|
+
res.end(JSON.stringify({ success: !optRes?.error, ...optRes, state: nextState }));
|
|
1739
|
+
return;
|
|
1740
|
+
}
|
|
1741
|
+
|
|
1742
|
+
// Route: POST /api/rsi/queue-action (Approve or dismiss staged learning in ReflectorQueue)
|
|
1743
|
+
if (url.pathname === '/api/rsi/queue-action' && req.method === 'POST') {
|
|
1744
|
+
const bodyStr = await readRequestBody(req, res);
|
|
1745
|
+
if (bodyStr === null) return;
|
|
1746
|
+
const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/rsi/queue-action');
|
|
1747
|
+
if (body === null) return;
|
|
1748
|
+
const itemId = body.id || body.itemId || null;
|
|
1749
|
+
const action = String(body.action || 'approve').toLowerCase();
|
|
1750
|
+
const activeWsDir = body.workspacePath || cachedLiveState?.workspace?.canonicalPath || process.cwd();
|
|
1751
|
+
reflectorQueue.setWorkspaceDir(activeWsDir);
|
|
1752
|
+
let actionRes = null;
|
|
1753
|
+
if (action === 'approve') {
|
|
1754
|
+
actionRes = reflectorQueue.approve(itemId);
|
|
1755
|
+
} else {
|
|
1756
|
+
actionRes = reflectorQueue.dismiss(itemId);
|
|
1757
|
+
}
|
|
1758
|
+
const nextState = await refreshLiveState(true, pinnedConversationId);
|
|
1759
|
+
broadcastState(nextState);
|
|
1760
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
1761
|
+
res.end(JSON.stringify({ success: Boolean(actionRes), ...actionRes, state: nextState }));
|
|
1762
|
+
return;
|
|
1763
|
+
}
|
|
1764
|
+
|
|
1765
|
+
// Route: POST /api/checkpoint/evaporation-check
|
|
1766
|
+
if (url.pathname === '/api/checkpoint/evaporation-check' && req.method === 'POST') {
|
|
1767
|
+
const bodyStr = await readRequestBody(req, res);
|
|
1768
|
+
if (bodyStr === null) return;
|
|
1769
|
+
const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/checkpoint/evaporation-check');
|
|
1770
|
+
if (body === null) return;
|
|
1771
|
+
const targetConvId = body.conversationId || pinnedConversationId || cachedLiveState?.sessionId || 'default';
|
|
1772
|
+
const evapRes = progressiveCheckpointer.detectConstraintEvaporation(
|
|
1773
|
+
body.summaryText || '',
|
|
1774
|
+
targetConvId
|
|
1775
|
+
);
|
|
1776
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
1777
|
+
res.end(JSON.stringify({ success: true, ...evapRes }));
|
|
1778
|
+
return;
|
|
1779
|
+
}
|
|
1780
|
+
|
|
1781
|
+
// Route: POST /api/router/unlock-hysteresis (1-click manual unlock for HysteresisLock)
|
|
1782
|
+
if (url.pathname === '/api/router/unlock-hysteresis' && req.method === 'POST') {
|
|
1783
|
+
const unlockRes = hysteresisLock.unlock('MANUAL_UI_UNLOCK');
|
|
1784
|
+
const nextState = await refreshLiveState(true, pinnedConversationId);
|
|
1785
|
+
broadcastState(nextState);
|
|
1786
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
1787
|
+
res.end(JSON.stringify({ success: true, ...unlockRes, hysteresisLock: hysteresisLock.getStatus(), state: nextState }));
|
|
1788
|
+
return;
|
|
1789
|
+
}
|
|
1790
|
+
|
|
1791
|
+
// Route: POST /api/license/activate (Offline Ed25519 Pro license or 14-day local trial activation)
|
|
1792
|
+
if (url.pathname === '/api/license/activate' && req.method === 'POST') {
|
|
1793
|
+
const bodyStr = await readRequestBody(req, res);
|
|
1794
|
+
if (bodyStr === null) return;
|
|
1795
|
+
const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/license/activate');
|
|
1796
|
+
if (body === null) return;
|
|
1797
|
+
const actRes = body.trial
|
|
1798
|
+
? activateLocalTrial()
|
|
1799
|
+
: activateProLicense(body.licenseKey || '');
|
|
1800
|
+
const nextState = await refreshLiveState(true, pinnedConversationId);
|
|
1801
|
+
broadcastState(nextState);
|
|
1802
|
+
res.writeHead(actRes.ok ? 200 : 400, { 'Content-Type': 'application/json' });
|
|
1803
|
+
res.end(JSON.stringify({ success: Boolean(actRes.ok), ...actRes, state: nextState }));
|
|
1804
|
+
return;
|
|
1805
|
+
}
|
|
1806
|
+
|
|
1807
|
+
// Route: GET /api/receipt/export (1-Click Corporate Expense Receipt in PDF 1.4, HTML, or Markdown)
|
|
1808
|
+
if (url.pathname === '/api/receipt/export' && req.method === 'GET') {
|
|
1809
|
+
const fmt = String(url.searchParams.get('format') || 'pdf').toLowerCase();
|
|
1810
|
+
const sessionKey = pinnedConversationId || cachedLiveState?.sessionId || 'default';
|
|
1811
|
+
const ledgerSum = savedQuotaLedger ? savedQuotaLedger.getSummary(sessionKey) : {};
|
|
1812
|
+
const unified = cachedLiveState?.savings || {};
|
|
1813
|
+
const rcpt = generateCorporateExpenseReceipt({
|
|
1814
|
+
sessionSavedTokens: Number(unified.totalSavedTokens || ledgerSum.totalArgonEquivTokensSaved || 0),
|
|
1815
|
+
sessionSavedUSD: Number(unified.estimatedSavedUSD || (Number(ledgerSum.totalArgonEquivTokensSaved || 0) * 0.000015) || 0),
|
|
1816
|
+
workspace30dSavedTokens: Number(unified.totalSavedTokens || ledgerSum.totalArgonEquivTokensSaved || 0),
|
|
1817
|
+
workspace30dSavedUSD: Number(unified.estimatedSavedUSD || (Number(ledgerSum.totalArgonEquivTokensSaved || 0) * 0.000015) || 0)
|
|
1818
|
+
});
|
|
1819
|
+
if (fmt === 'pdf') {
|
|
1820
|
+
const proCheck = requireProFeature('corporate_expense_receipts', {
|
|
1821
|
+
strict: url.searchParams.get('strict') === '1'
|
|
1822
|
+
});
|
|
1823
|
+
if (!proCheck.allowed) {
|
|
1824
|
+
res.writeHead(402, { 'Content-Type': 'application/json' });
|
|
1825
|
+
res.end(
|
|
1826
|
+
JSON.stringify({
|
|
1827
|
+
ok: false,
|
|
1828
|
+
requiresPro: true,
|
|
1829
|
+
shadowSavedUSD: rcpt.workspace30dSavedUSD,
|
|
1830
|
+
upgradeHint: proCheck.upgradeHint
|
|
1831
|
+
})
|
|
1832
|
+
);
|
|
1833
|
+
return;
|
|
1834
|
+
}
|
|
1835
|
+
const buf = Buffer.from(rcpt.pdfBytes);
|
|
1836
|
+
res.writeHead(200, {
|
|
1837
|
+
'Content-Type': 'application/pdf',
|
|
1838
|
+
'Content-Disposition': `attachment; filename="attention-horizon-receipt-${rcpt.receiptId}.pdf"`,
|
|
1839
|
+
'Content-Length': buf.length
|
|
1840
|
+
});
|
|
1841
|
+
res.end(buf);
|
|
1842
|
+
return;
|
|
1843
|
+
}
|
|
1844
|
+
if (fmt === 'html') {
|
|
1845
|
+
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
1846
|
+
res.end(rcpt.html);
|
|
1847
|
+
return;
|
|
1848
|
+
}
|
|
1849
|
+
res.writeHead(200, { 'Content-Type': 'text/markdown; charset=utf-8' });
|
|
1850
|
+
res.end(rcpt.markdown);
|
|
1851
|
+
return;
|
|
1852
|
+
}
|
|
1853
|
+
|
|
1854
|
+
// Route: POST /api/router/mode (Set Coach / Auto-Pilot mode)
|
|
1855
|
+
if (url.pathname === '/api/router/mode' && req.method === 'POST') {
|
|
1856
|
+
const bodyStr = await readRequestBody(req, res);
|
|
1857
|
+
if (bodyStr === null) return;
|
|
1858
|
+
const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/router/mode');
|
|
1859
|
+
if (body === null) return;
|
|
1860
|
+
const mode = body.mode || 'coach';
|
|
1861
|
+
const modeRes = modelSelectorActuator.setMode(mode);
|
|
1862
|
+
cacheTtlWatchdog.setFlightMode(
|
|
1863
|
+
modeRes.mode === 'autopilot' ? 'AUTO_PILOT' : (modeRes.mode === 'off' ? 'OFF' : 'COACH')
|
|
1864
|
+
);
|
|
1865
|
+
const nextState = await refreshLiveState(true, pinnedConversationId);
|
|
1866
|
+
broadcastState(nextState);
|
|
1867
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
1868
|
+
res.end(JSON.stringify({ success: true, ...modeRes, state: nextState }));
|
|
1869
|
+
return;
|
|
1870
|
+
}
|
|
1871
|
+
|
|
1872
|
+
// Route: POST /api/router/actuate (Actuate model/effort change)
|
|
1873
|
+
if (url.pathname === '/api/router/actuate' && req.method === 'POST') {
|
|
1874
|
+
const bodyStr = await readRequestBody(req, res);
|
|
1875
|
+
if (bodyStr === null) return;
|
|
1876
|
+
const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/router/actuate');
|
|
1877
|
+
if (body === null) return;
|
|
1878
|
+
const actuateRes = await modelSelectorActuator.evaluateAndActuate({
|
|
1879
|
+
...body,
|
|
1880
|
+
forceActuate: true
|
|
1881
|
+
});
|
|
1882
|
+
if (savedQuotaLedger && actuateRes && (actuateRes.actuated || actuateRes.changed)) {
|
|
1883
|
+
try {
|
|
1884
|
+
const estTok = Math.max(1500, Math.round(Number(cachedLiveState?.window?.totalActiveTokens || 20000) * 0.2));
|
|
1885
|
+
savedQuotaLedger.recordSaving({
|
|
1886
|
+
sessionId: String(pinnedConversationId || cachedLiveState?.sessionId || 'default-session'),
|
|
1887
|
+
eventType: SAVINGS_EVENT_TYPES.EFFORT_DOWNSHIFT,
|
|
1888
|
+
tokensSaved: estTok,
|
|
1889
|
+
detail: `Actuated model/effort shift to ${actuateRes.targetModel || body.recommendedModel || 'leaner tier'}`
|
|
1890
|
+
});
|
|
1891
|
+
} catch (err) {
|
|
1892
|
+
recordDaemonDiagnostic('POST /api/router/actuate:ledger', err);
|
|
1893
|
+
}
|
|
1894
|
+
}
|
|
1895
|
+
const nextState = await refreshLiveState(true, pinnedConversationId);
|
|
1896
|
+
broadcastState(nextState);
|
|
1897
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
1898
|
+
res.end(JSON.stringify({ success: true, ...actuateRes, state: nextState }));
|
|
1899
|
+
return;
|
|
1900
|
+
}
|
|
1901
|
+
|
|
1902
|
+
// Route: POST /api/savings/receipt (Export plain-English verified Tokens Saved receipt)
|
|
1903
|
+
if (url.pathname === '/api/savings/receipt' && req.method === 'POST') {
|
|
1904
|
+
const bodyStr = await readRequestBody(req, res);
|
|
1905
|
+
if (bodyStr === null) return;
|
|
1906
|
+
const body = bodyStr ? parseJsonBodyOrSend400(bodyStr, res, 'POST /api/savings/receipt') : {};
|
|
1907
|
+
if (body === null) return;
|
|
1908
|
+
const targetSession = body.conversationId || body.sessionId || pinnedConversationId || cachedLiveState?.sessionId || 'default';
|
|
1909
|
+
const liveSavings = cachedLiveState?.savings || computeUnifiedSavings(cachedLiveState || {}, {
|
|
1910
|
+
ledger: savedQuotaLedger,
|
|
1911
|
+
sessionId: targetSession,
|
|
1912
|
+
fts5SavedTokens: getFts5CompressionStats().savedTokens
|
|
1913
|
+
});
|
|
1914
|
+
const receipt = savedQuotaLedger
|
|
1915
|
+
? savedQuotaLedger.copyPlainSavingsReceipt({ sessionId: targetSession, liveSavings })
|
|
1916
|
+
: { ok: false, markdown: '' };
|
|
1917
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
1918
|
+
res.end(JSON.stringify({ success: true, ...receipt, receiptMarkdown: receipt.markdown || '', savings: liveSavings }));
|
|
1919
|
+
return;
|
|
1920
|
+
}
|
|
1921
|
+
|
|
1922
|
+
if (url.pathname === '/api/action' && req.method === 'POST') {
|
|
1923
|
+
const bodyStr = await readRequestBody(req, res);
|
|
1924
|
+
if (bodyStr === null) return;
|
|
1925
|
+
const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/action');
|
|
1926
|
+
if (body === null) return;
|
|
1927
|
+
if (body.action === 'select_session') {
|
|
1928
|
+
pinnedConversationId = (!body.conversationId || body.conversationId === 'auto') ? null : body.conversationId;
|
|
1929
|
+
const nextState = await refreshLiveState(true, pinnedConversationId);
|
|
1930
|
+
broadcastState(nextState);
|
|
1931
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
1932
|
+
res.end(JSON.stringify({ success: true, state: nextState }));
|
|
1933
|
+
return;
|
|
1934
|
+
}
|
|
1935
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
1936
|
+
res.end(JSON.stringify({ success: true, action: body.action }));
|
|
1937
|
+
return;
|
|
1938
|
+
}
|
|
1939
|
+
|
|
1940
|
+
res.writeHead(404);
|
|
1941
|
+
res.end('Not Found');
|
|
1942
|
+
} catch (err) {
|
|
1943
|
+
sendRouteError500(res, `${req.method || 'HTTP'} ${req.url || '/'}`, err);
|
|
1944
|
+
}
|
|
1945
|
+
});
|
|
1946
|
+
|
|
1947
|
+
function broadcastState(state) {
|
|
1948
|
+
if (!state || clients.size === 0) return;
|
|
1949
|
+
const payload = `data: ${JSON.stringify(state)}\n\n`;
|
|
1950
|
+
for (const client of clients) {
|
|
1951
|
+
try {
|
|
1952
|
+
client.write(payload);
|
|
1953
|
+
} catch (err) {
|
|
1954
|
+
clients.delete(client);
|
|
1955
|
+
recordDaemonDiagnostic('broadcastState:write', err);
|
|
1956
|
+
}
|
|
1957
|
+
}
|
|
1958
|
+
}
|
|
1959
|
+
|
|
1960
|
+
setInterval(async () => {
|
|
1961
|
+
if (clients.size > 0) {
|
|
1962
|
+
try {
|
|
1963
|
+
const state = await refreshLiveState(true);
|
|
1964
|
+
broadcastState(state);
|
|
1965
|
+
} catch (err) {
|
|
1966
|
+
recordDaemonDiagnostic('sseBroadcastInterval', err);
|
|
1967
|
+
}
|
|
1968
|
+
}
|
|
1969
|
+
}, 2000).unref();
|
|
1970
|
+
|
|
1971
|
+
export function startServer(port = EXPLICIT_PORT) {
|
|
1972
|
+
return new Promise((resolve, reject) => {
|
|
1973
|
+
const candidates = port > 0
|
|
1974
|
+
? [port]
|
|
1975
|
+
: [...Array.from({ length: DEFAULT_PORT_MAX - DEFAULT_PORT_START + 1 }, (_, i) => DEFAULT_PORT_START + i), 0];
|
|
1976
|
+
|
|
1977
|
+
let idx = 0;
|
|
1978
|
+
const tryListen = () => {
|
|
1979
|
+
const candidatePort = candidates[idx++];
|
|
1980
|
+
const onError = (err) => {
|
|
1981
|
+
server.removeListener('listening', onListening);
|
|
1982
|
+
if (err.code === 'EADDRINUSE' && idx < candidates.length) {
|
|
1983
|
+
tryListen();
|
|
1984
|
+
} else {
|
|
1985
|
+
reject(err);
|
|
1986
|
+
}
|
|
1987
|
+
};
|
|
1988
|
+
const onListening = () => {
|
|
1989
|
+
server.removeListener('error', onError);
|
|
1990
|
+
const boundPort = server.address().port;
|
|
1991
|
+
writeRuntimeLockfile(boundPort);
|
|
1992
|
+
cacheTtlWatchdog.startPolling(1000);
|
|
1993
|
+
|
|
1994
|
+
let ipcServer = null;
|
|
1995
|
+
try {
|
|
1996
|
+
ipcServer = new MicroIpcServer();
|
|
1997
|
+
ipcServer.listen().catch((ipcErr) => {
|
|
1998
|
+
recordDaemonDiagnostic('ipcServer:listen', ipcErr);
|
|
1999
|
+
});
|
|
2000
|
+
} catch (ipcErr) {
|
|
2001
|
+
recordDaemonDiagnostic('ipcServer:init', ipcErr);
|
|
2002
|
+
}
|
|
2003
|
+
|
|
2004
|
+
server.once('close', () => {
|
|
2005
|
+
cacheTtlWatchdog.stopPolling();
|
|
2006
|
+
if (ipcServer) {
|
|
2007
|
+
ipcServer.close().catch((err) => {
|
|
2008
|
+
recordDaemonDiagnostic('ipcServer:close', err);
|
|
2009
|
+
});
|
|
2010
|
+
}
|
|
2011
|
+
});
|
|
2012
|
+
console.log(`[Horizon Daemon] Listening on http://${BIND_HOST}:${boundPort}`);
|
|
2013
|
+
resolve({ server, port: boundPort, ipcServer });
|
|
2014
|
+
};
|
|
2015
|
+
server.once('error', onError);
|
|
2016
|
+
server.once('listening', onListening);
|
|
2017
|
+
server.listen(candidatePort, BIND_HOST);
|
|
2018
|
+
};
|
|
2019
|
+
|
|
2020
|
+
tryListen();
|
|
2021
|
+
});
|
|
2022
|
+
}
|
|
2023
|
+
|
|
2024
|
+
function isDaemonMain(argv1 = process.argv[1], metaUrl = import.meta.url) {
|
|
2025
|
+
if (!argv1) return false;
|
|
2026
|
+
try {
|
|
2027
|
+
return fs.realpathSync(argv1) === fs.realpathSync(fileURLToPath(metaUrl));
|
|
2028
|
+
} catch (err) {
|
|
2029
|
+
if (err?.code !== 'ENOENT') recordDaemonDiagnostic('isDaemonMain:realpath', err);
|
|
2030
|
+
return path.resolve(argv1) === path.resolve(fileURLToPath(metaUrl));
|
|
2031
|
+
}
|
|
2032
|
+
}
|
|
2033
|
+
|
|
2034
|
+
const isMain = isDaemonMain();
|
|
2035
|
+
if (isMain) {
|
|
2036
|
+
ensureSupportedNodeVersion();
|
|
2037
|
+
startServer();
|
|
2038
|
+
}
|