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,447 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/engine-node/ipc/client.mjs
|
|
3
|
+
* Highbeam Micro-IPC Client.
|
|
4
|
+
*
|
|
5
|
+
* Implements high-performance (<0.8ms SLA, p95 ~0.13ms) local IPC communication
|
|
6
|
+
* with persistent warm socket reuse, message demultiplexing, and 15ms failover
|
|
7
|
+
* to local in-process fallback execution when daemon is offline.
|
|
8
|
+
* Strictly 0 npm dependencies (uses only standard node:* built-ins).
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import net from 'node:net';
|
|
12
|
+
import {
|
|
13
|
+
resolveIpcPath,
|
|
14
|
+
formatJsonRpcRequest,
|
|
15
|
+
JsonRpcStreamParser,
|
|
16
|
+
IPC_LIMITS
|
|
17
|
+
} from './protocol.mjs';
|
|
18
|
+
|
|
19
|
+
export class MicroIpcClient {
|
|
20
|
+
/**
|
|
21
|
+
* @param {object} [options]
|
|
22
|
+
* @param {string} [options.ipcPath]
|
|
23
|
+
* @param {number} [options.connectTimeoutMs=15]
|
|
24
|
+
* @param {number} [options.requestTimeoutMs=500]
|
|
25
|
+
* @param {boolean} [options.persistent=true]
|
|
26
|
+
*/
|
|
27
|
+
constructor(options = {}) {
|
|
28
|
+
this.ipcPath = resolveIpcPath(options);
|
|
29
|
+
this.connectTimeoutMs = options.connectTimeoutMs ?? IPC_LIMITS.DEFAULT_CONNECT_TIMEOUT_MS;
|
|
30
|
+
this.requestTimeoutMs = options.requestTimeoutMs ?? IPC_LIMITS.DEFAULT_REQUEST_TIMEOUT_MS;
|
|
31
|
+
this.persistent = options.persistent ?? true;
|
|
32
|
+
|
|
33
|
+
// Warm socket management
|
|
34
|
+
this.activeSocket = null;
|
|
35
|
+
this.streamParser = null;
|
|
36
|
+
this.connectingPromise = null;
|
|
37
|
+
|
|
38
|
+
// In-flight pending requests: Map<reqId, { resolve, reject, timer, method }>
|
|
39
|
+
this.pendingRequests = new Map();
|
|
40
|
+
this.isClosed = false;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Returns the warm active socket if connected and writable, or initiates
|
|
45
|
+
* a new connection if none exists or the previous socket was closed.
|
|
46
|
+
*
|
|
47
|
+
* @param {number} connectTimeoutMs
|
|
48
|
+
* @returns {Promise<import('node:net').Socket>}
|
|
49
|
+
* @private
|
|
50
|
+
*/
|
|
51
|
+
async _ensureConnected(connectTimeoutMs) {
|
|
52
|
+
if (this.isClosed) {
|
|
53
|
+
this.isClosed = false;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
if (
|
|
57
|
+
this.activeSocket &&
|
|
58
|
+
!this.activeSocket.destroyed &&
|
|
59
|
+
!this.activeSocket.connecting &&
|
|
60
|
+
this.activeSocket.writable
|
|
61
|
+
) {
|
|
62
|
+
return this.activeSocket;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (this.connectingPromise) {
|
|
66
|
+
return this.connectingPromise;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
this.connectingPromise = this._connect(connectTimeoutMs);
|
|
70
|
+
try {
|
|
71
|
+
return await this.connectingPromise;
|
|
72
|
+
} finally {
|
|
73
|
+
this.connectingPromise = null;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Establishes a new connection to the IPC socket / pipe.
|
|
79
|
+
*
|
|
80
|
+
* @param {number} connectTimeoutMs
|
|
81
|
+
* @returns {Promise<import('node:net').Socket>}
|
|
82
|
+
* @private
|
|
83
|
+
*/
|
|
84
|
+
_connect(connectTimeoutMs) {
|
|
85
|
+
return new Promise((resolve, reject) => {
|
|
86
|
+
let settled = false;
|
|
87
|
+
let connectTimer = null;
|
|
88
|
+
let socket = null;
|
|
89
|
+
|
|
90
|
+
const cleanupTimer = () => {
|
|
91
|
+
if (connectTimer) {
|
|
92
|
+
clearTimeout(connectTimer);
|
|
93
|
+
connectTimer = null;
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
try {
|
|
98
|
+
socket = net.connect(this.ipcPath);
|
|
99
|
+
} catch (err) {
|
|
100
|
+
return reject(err);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Fast connection timeout guard (default 15ms)
|
|
104
|
+
connectTimer = setTimeout(() => {
|
|
105
|
+
if (!settled) {
|
|
106
|
+
settled = true;
|
|
107
|
+
cleanupTimer();
|
|
108
|
+
try {
|
|
109
|
+
socket.destroy();
|
|
110
|
+
} catch (_err) {
|
|
111
|
+
void _err;
|
|
112
|
+
}
|
|
113
|
+
reject(new Error(`[MicroIPC] Connection timeout (${connectTimeoutMs}ms) to ${this.ipcPath}`));
|
|
114
|
+
}
|
|
115
|
+
}, connectTimeoutMs);
|
|
116
|
+
|
|
117
|
+
// Create stream parser attached to this socket
|
|
118
|
+
const parser = new JsonRpcStreamParser(
|
|
119
|
+
(msg) => this._onMessage(msg),
|
|
120
|
+
(parseErr) => this._onParseError(parseErr, socket)
|
|
121
|
+
);
|
|
122
|
+
|
|
123
|
+
socket.on('connect', () => {
|
|
124
|
+
if (settled) return;
|
|
125
|
+
settled = true;
|
|
126
|
+
cleanupTimer();
|
|
127
|
+
|
|
128
|
+
// Unref warm idle socket so it does not keep Node.js event loop alive unnecessarily
|
|
129
|
+
socket.unref();
|
|
130
|
+
|
|
131
|
+
this.activeSocket = socket;
|
|
132
|
+
this.streamParser = parser;
|
|
133
|
+
resolve(socket);
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
socket.on('data', (chunk) => {
|
|
137
|
+
parser.feed(chunk);
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
socket.on('error', (err) => {
|
|
141
|
+
if (!settled) {
|
|
142
|
+
settled = true;
|
|
143
|
+
cleanupTimer();
|
|
144
|
+
reject(err);
|
|
145
|
+
}
|
|
146
|
+
this._handleSocketError(socket, err);
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
socket.on('close', () => {
|
|
150
|
+
if (!settled) {
|
|
151
|
+
settled = true;
|
|
152
|
+
cleanupTimer();
|
|
153
|
+
reject(new Error('[MicroIPC] Socket closed during connection'));
|
|
154
|
+
}
|
|
155
|
+
this._handleSocketClose(socket);
|
|
156
|
+
});
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Handles unexpected socket errors, cleans up active state, and rejects in-flight requests.
|
|
162
|
+
*
|
|
163
|
+
* @param {import('node:net').Socket} socket
|
|
164
|
+
* @param {Error} err
|
|
165
|
+
* @private
|
|
166
|
+
*/
|
|
167
|
+
_handleSocketError(socket, err) {
|
|
168
|
+
if (this.activeSocket === socket) {
|
|
169
|
+
this.activeSocket = null;
|
|
170
|
+
this.streamParser = null;
|
|
171
|
+
}
|
|
172
|
+
const errorMsg = err?.message || 'Unknown socket error';
|
|
173
|
+
this._rejectAllPending(new Error(`[MicroIPC] Socket error: ${errorMsg}`));
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Handles socket close / disconnect events, cleans up active state, and rejects in-flight requests.
|
|
178
|
+
*
|
|
179
|
+
* @param {import('node:net').Socket} socket
|
|
180
|
+
* @private
|
|
181
|
+
*/
|
|
182
|
+
_handleSocketClose(socket) {
|
|
183
|
+
if (this.activeSocket === socket) {
|
|
184
|
+
this.activeSocket = null;
|
|
185
|
+
this.streamParser = null;
|
|
186
|
+
}
|
|
187
|
+
this._rejectAllPending(new Error('[MicroIPC] Socket closed before receiving response'));
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Handles JSON-RPC stream parser errors (e.g. buffer overrun).
|
|
192
|
+
*
|
|
193
|
+
* @param {Error} parseErr
|
|
194
|
+
* @param {import('node:net').Socket} socket
|
|
195
|
+
* @private
|
|
196
|
+
*/
|
|
197
|
+
_onParseError(parseErr, socket) {
|
|
198
|
+
if (this.activeSocket === socket) {
|
|
199
|
+
this.activeSocket = null;
|
|
200
|
+
this.streamParser = null;
|
|
201
|
+
try {
|
|
202
|
+
socket.destroy();
|
|
203
|
+
} catch (_err) {
|
|
204
|
+
void _err;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
this._rejectAllPending(parseErr);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Rejects all currently pending in-flight requests with the given error.
|
|
212
|
+
*
|
|
213
|
+
* @param {Error} error
|
|
214
|
+
* @private
|
|
215
|
+
*/
|
|
216
|
+
_rejectAllPending(error) {
|
|
217
|
+
const entries = Array.from(this.pendingRequests.entries());
|
|
218
|
+
this.pendingRequests.clear();
|
|
219
|
+
for (const [id, pending] of entries) {
|
|
220
|
+
if (pending.timer) {
|
|
221
|
+
clearTimeout(pending.timer);
|
|
222
|
+
pending.timer = null;
|
|
223
|
+
}
|
|
224
|
+
try {
|
|
225
|
+
pending.reject(error);
|
|
226
|
+
} catch (_err) {
|
|
227
|
+
void _err;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Dispatches incoming parsed JSON-RPC responses to their matching pending request.
|
|
234
|
+
*
|
|
235
|
+
* @param {object} msg
|
|
236
|
+
* @private
|
|
237
|
+
*/
|
|
238
|
+
_onMessage(msg) {
|
|
239
|
+
if (!msg || typeof msg !== 'object') return;
|
|
240
|
+
const id = msg.id;
|
|
241
|
+
if (id === null || id === undefined) return;
|
|
242
|
+
|
|
243
|
+
const pending = this.pendingRequests.get(id);
|
|
244
|
+
if (!pending) return;
|
|
245
|
+
|
|
246
|
+
this.pendingRequests.delete(id);
|
|
247
|
+
if (pending.timer) {
|
|
248
|
+
clearTimeout(pending.timer);
|
|
249
|
+
pending.timer = null;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
if (msg.error) {
|
|
253
|
+
const errMsg = typeof msg.error === 'string'
|
|
254
|
+
? msg.error
|
|
255
|
+
: (msg.error.message || 'JSON-RPC Error');
|
|
256
|
+
const err = new Error(errMsg);
|
|
257
|
+
if (typeof msg.error === 'object' && msg.error.code !== undefined) {
|
|
258
|
+
err.code = msg.error.code;
|
|
259
|
+
}
|
|
260
|
+
if (typeof msg.error === 'object' && msg.error.data !== undefined) {
|
|
261
|
+
err.data = msg.error.data;
|
|
262
|
+
}
|
|
263
|
+
pending.reject(err);
|
|
264
|
+
} else {
|
|
265
|
+
pending.resolve(msg.result);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Executes a remote JSON-RPC 2.0 method over the warm local IPC socket/pipe.
|
|
271
|
+
*
|
|
272
|
+
* @param {string} method
|
|
273
|
+
* @param {*} [params={}]
|
|
274
|
+
* @param {object} [options={}]
|
|
275
|
+
* @param {number} [options.connectTimeoutMs]
|
|
276
|
+
* @param {number} [options.requestTimeoutMs]
|
|
277
|
+
* @param {boolean} [options.persistent]
|
|
278
|
+
* @returns {Promise<*>} Result payload
|
|
279
|
+
*/
|
|
280
|
+
async call(method, params = {}, options = {}) {
|
|
281
|
+
const connectTimeout = options.connectTimeoutMs ?? this.connectTimeoutMs;
|
|
282
|
+
const requestTimeout = options.requestTimeoutMs ?? this.requestTimeoutMs;
|
|
283
|
+
const isPersistent = options.persistent ?? this.persistent;
|
|
284
|
+
const id = Date.now() + Math.random().toString(36).slice(2, 8);
|
|
285
|
+
|
|
286
|
+
const socket = await this._ensureConnected(connectTimeout);
|
|
287
|
+
|
|
288
|
+
return new Promise((resolve, reject) => {
|
|
289
|
+
let requestTimer = null;
|
|
290
|
+
|
|
291
|
+
requestTimer = setTimeout(() => {
|
|
292
|
+
if (this.pendingRequests.has(id)) {
|
|
293
|
+
this.pendingRequests.delete(id);
|
|
294
|
+
// When a request times out, destroy the socket to cleanly cancel remote work
|
|
295
|
+
// and trigger server-side suspension cleanup without leaks.
|
|
296
|
+
if (this.activeSocket === socket) {
|
|
297
|
+
this.activeSocket = null;
|
|
298
|
+
this.streamParser = null;
|
|
299
|
+
try {
|
|
300
|
+
socket.destroy();
|
|
301
|
+
} catch (_err) {
|
|
302
|
+
void _err;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
reject(new Error(`[MicroIPC] Request timeout (${requestTimeout}ms) for method ${method}`));
|
|
306
|
+
}
|
|
307
|
+
}, requestTimeout);
|
|
308
|
+
|
|
309
|
+
this.pendingRequests.set(id, {
|
|
310
|
+
resolve: (result) => {
|
|
311
|
+
if (!isPersistent) {
|
|
312
|
+
this.close();
|
|
313
|
+
}
|
|
314
|
+
resolve(result);
|
|
315
|
+
},
|
|
316
|
+
reject: (err) => {
|
|
317
|
+
if (!isPersistent) {
|
|
318
|
+
this.close();
|
|
319
|
+
}
|
|
320
|
+
reject(err);
|
|
321
|
+
},
|
|
322
|
+
timer: requestTimer,
|
|
323
|
+
method
|
|
324
|
+
});
|
|
325
|
+
|
|
326
|
+
try {
|
|
327
|
+
const payload = formatJsonRpcRequest(method, params, id);
|
|
328
|
+
socket.write(payload, (writeErr) => {
|
|
329
|
+
if (writeErr) {
|
|
330
|
+
if (this.pendingRequests.has(id)) {
|
|
331
|
+
this.pendingRequests.delete(id);
|
|
332
|
+
if (requestTimer) {
|
|
333
|
+
clearTimeout(requestTimer);
|
|
334
|
+
requestTimer = null;
|
|
335
|
+
}
|
|
336
|
+
if (this.activeSocket === socket) {
|
|
337
|
+
this.activeSocket = null;
|
|
338
|
+
this.streamParser = null;
|
|
339
|
+
try {
|
|
340
|
+
socket.destroy();
|
|
341
|
+
} catch (_e) {
|
|
342
|
+
void _e;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
reject(writeErr);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
});
|
|
349
|
+
} catch (err) {
|
|
350
|
+
if (this.pendingRequests.has(id)) {
|
|
351
|
+
this.pendingRequests.delete(id);
|
|
352
|
+
if (requestTimer) {
|
|
353
|
+
clearTimeout(requestTimer);
|
|
354
|
+
requestTimer = null;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
if (this.activeSocket === socket) {
|
|
358
|
+
this.activeSocket = null;
|
|
359
|
+
this.streamParser = null;
|
|
360
|
+
try {
|
|
361
|
+
socket.destroy();
|
|
362
|
+
} catch (_e) {
|
|
363
|
+
void _e;
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
reject(err);
|
|
367
|
+
}
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* Calls a remote method, seamlessly falling back to local evaluation if the IPC
|
|
373
|
+
* daemon is unreachable, delayed >15ms, or errors.
|
|
374
|
+
*
|
|
375
|
+
* @param {string} method
|
|
376
|
+
* @param {*} params
|
|
377
|
+
* @param {Function} fallbackFn
|
|
378
|
+
* @param {object} [options]
|
|
379
|
+
* @returns {Promise<{ source: 'ipc' | 'fallback', result: *, fallbackReason?: string }>}
|
|
380
|
+
*/
|
|
381
|
+
async callWithFallback(method, params, fallbackFn, options = {}) {
|
|
382
|
+
try {
|
|
383
|
+
const result = await this.call(method, params, options);
|
|
384
|
+
return { source: 'ipc', result };
|
|
385
|
+
} catch (err) {
|
|
386
|
+
try {
|
|
387
|
+
const fallbackResult = await fallbackFn(params, err);
|
|
388
|
+
return {
|
|
389
|
+
source: 'fallback',
|
|
390
|
+
result: fallbackResult,
|
|
391
|
+
fallbackReason: err.message
|
|
392
|
+
};
|
|
393
|
+
} catch (fallbackErr) {
|
|
394
|
+
throw fallbackErr;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* Pings the IPC daemon. Returns true if responsive within timeout, false otherwise.
|
|
401
|
+
* Defaults to this.requestTimeoutMs or 500ms instead of hardcoded 15ms.
|
|
402
|
+
*
|
|
403
|
+
* @param {number} [timeoutMs]
|
|
404
|
+
* @returns {Promise<boolean>}
|
|
405
|
+
*/
|
|
406
|
+
async ping(timeoutMs = this.requestTimeoutMs ?? 500) {
|
|
407
|
+
const effectiveTimeout = timeoutMs ?? this.requestTimeoutMs ?? 500;
|
|
408
|
+
try {
|
|
409
|
+
await this.call('daemon.ping', {}, { connectTimeoutMs: effectiveTimeout, requestTimeoutMs: effectiveTimeout });
|
|
410
|
+
return true;
|
|
411
|
+
} catch (_err) {
|
|
412
|
+
return false;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* Closes the active socket connection and cleans up pending requests.
|
|
418
|
+
*
|
|
419
|
+
* @returns {Promise<void>}
|
|
420
|
+
*/
|
|
421
|
+
async close() {
|
|
422
|
+
if (this.isClosed) return;
|
|
423
|
+
this.isClosed = true;
|
|
424
|
+
const sock = this.activeSocket;
|
|
425
|
+
this.activeSocket = null;
|
|
426
|
+
this.streamParser = null;
|
|
427
|
+
this.connectingPromise = null;
|
|
428
|
+
|
|
429
|
+
if (sock && !sock.destroyed) {
|
|
430
|
+
try {
|
|
431
|
+
sock.end();
|
|
432
|
+
sock.destroy();
|
|
433
|
+
} catch (_err) {
|
|
434
|
+
void _err;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
this._rejectAllPending(new Error('[MicroIPC] Client closed'));
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/**
|
|
442
|
+
* Alias for close() for stream/socket lifecycle compatibility.
|
|
443
|
+
*/
|
|
444
|
+
destroy() {
|
|
445
|
+
this.close();
|
|
446
|
+
}
|
|
447
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/engine-node/ipc/index.mjs
|
|
3
|
+
* Highbeam Micro-IPC Bridge Barrel.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export {
|
|
7
|
+
resolveIpcPath,
|
|
8
|
+
formatJsonRpcRequest,
|
|
9
|
+
formatJsonRpcResponse,
|
|
10
|
+
formatJsonRpcError,
|
|
11
|
+
JsonRpcStreamParser,
|
|
12
|
+
JSON_RPC_ERRORS,
|
|
13
|
+
IPC_LIMITS
|
|
14
|
+
} from './protocol.mjs';
|
|
15
|
+
|
|
16
|
+
export {
|
|
17
|
+
MicroIpcClient
|
|
18
|
+
} from './client.mjs';
|
|
19
|
+
|
|
20
|
+
export {
|
|
21
|
+
MicroIpcServer
|
|
22
|
+
} from './server.mjs';
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/engine-node/ipc/protocol.mjs
|
|
3
|
+
* Highbeam Micro-IPC Wire Protocol & Stream Parser.
|
|
4
|
+
*
|
|
5
|
+
* Implements Win32 Named-Pipe / POSIX Unix Domain Socket address resolution,
|
|
6
|
+
* JSON-RPC 2.0 framing over newline-delimited streams (\n), and buffer overrun protection.
|
|
7
|
+
* Strictly 0 npm dependencies (uses only standard node:* built-ins).
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import os from 'node:os';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
13
|
+
|
|
14
|
+
export const JSON_RPC_ERRORS = Object.freeze({
|
|
15
|
+
PARSE_ERROR: -32700,
|
|
16
|
+
INVALID_REQUEST: -32600,
|
|
17
|
+
METHOD_NOT_FOUND: -32601,
|
|
18
|
+
INVALID_PARAMS: -32602,
|
|
19
|
+
INTERNAL_ERROR: -32603
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
export const IPC_LIMITS = Object.freeze({
|
|
23
|
+
MAX_BUFFER_SIZE_BYTES: 10 * 1024 * 1024, // 10MB
|
|
24
|
+
DEFAULT_CONNECT_TIMEOUT_MS: 15,
|
|
25
|
+
DEFAULT_REQUEST_TIMEOUT_MS: 500
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Resolves the OS-specific local IPC transport address.
|
|
30
|
+
* Win32: Named Pipe `\\.\pipe\ctxtop-<cleanUsername>`
|
|
31
|
+
* POSIX: Unix Domain Socket `~/.ctxtop/daemon.sock`
|
|
32
|
+
*
|
|
33
|
+
* @param {object} [options]
|
|
34
|
+
* @returns {string} Pipe path or socket filesystem path
|
|
35
|
+
*/
|
|
36
|
+
export function resolveIpcPath(options = {}) {
|
|
37
|
+
if (options.ipcPath || process.env.CTXTOP_IPC_PATH) {
|
|
38
|
+
return options.ipcPath || process.env.CTXTOP_IPC_PATH;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
if (process.platform === 'win32') {
|
|
42
|
+
let rawUser = process.env.USERNAME || process.env.USER;
|
|
43
|
+
if (!rawUser) {
|
|
44
|
+
try {
|
|
45
|
+
rawUser = typeof os.userInfo === 'function' ? os.userInfo()?.username : null;
|
|
46
|
+
} catch (_err) {
|
|
47
|
+
void _err;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
const cleanUser = String(rawUser || 'default').replace(/[^a-zA-Z0-9_-]/g, '_');
|
|
51
|
+
return `\\\\.\\pipe\\ctxtop-${cleanUser}`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const homeDir = options.homeDir || process.env.HOME || os.homedir() || '/tmp';
|
|
55
|
+
return path.join(homeDir, '.ctxtop', 'daemon.sock');
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Creates a standard JSON-RPC 2.0 request payload string.
|
|
60
|
+
*
|
|
61
|
+
* @param {string} method
|
|
62
|
+
* @param {*} [params]
|
|
63
|
+
* @param {string|number} [id]
|
|
64
|
+
* @returns {string} Formatted JSON-RPC request with trailing newline
|
|
65
|
+
*/
|
|
66
|
+
export function formatJsonRpcRequest(method, params = {}, id = null) {
|
|
67
|
+
const reqId = id !== null && id !== undefined ? id : Date.now() + Math.random().toString(36).slice(2, 8);
|
|
68
|
+
const msg = {
|
|
69
|
+
jsonrpc: '2.0',
|
|
70
|
+
id: reqId,
|
|
71
|
+
method: String(method),
|
|
72
|
+
params
|
|
73
|
+
};
|
|
74
|
+
return JSON.stringify(msg) + '\n';
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Creates a standard JSON-RPC 2.0 success response string.
|
|
79
|
+
*
|
|
80
|
+
* @param {string|number} id
|
|
81
|
+
* @param {*} result
|
|
82
|
+
* @returns {string} Formatted JSON-RPC response with trailing newline
|
|
83
|
+
*/
|
|
84
|
+
export function formatJsonRpcResponse(id, result) {
|
|
85
|
+
const msg = {
|
|
86
|
+
jsonrpc: '2.0',
|
|
87
|
+
id: id !== undefined ? id : null,
|
|
88
|
+
result: result !== undefined ? result : null
|
|
89
|
+
};
|
|
90
|
+
return JSON.stringify(msg) + '\n';
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Creates a standard JSON-RPC 2.0 error response string.
|
|
95
|
+
*
|
|
96
|
+
* @param {string|number} id
|
|
97
|
+
* @param {number} code
|
|
98
|
+
* @param {string} message
|
|
99
|
+
* @param {*} [data]
|
|
100
|
+
* @returns {string} Formatted JSON-RPC error response with trailing newline
|
|
101
|
+
*/
|
|
102
|
+
export function formatJsonRpcError(id, code, message, data = undefined) {
|
|
103
|
+
const errObj = {
|
|
104
|
+
code: typeof code === 'number' ? code : JSON_RPC_ERRORS.INTERNAL_ERROR,
|
|
105
|
+
message: String(message || 'Internal error')
|
|
106
|
+
};
|
|
107
|
+
if (data !== undefined) {
|
|
108
|
+
errObj.data = data;
|
|
109
|
+
}
|
|
110
|
+
const msg = {
|
|
111
|
+
jsonrpc: '2.0',
|
|
112
|
+
id: id !== undefined ? id : null,
|
|
113
|
+
error: errObj
|
|
114
|
+
};
|
|
115
|
+
return JSON.stringify(msg) + '\n';
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Streaming parser for newline-delimited JSON-RPC 2.0 messages.
|
|
120
|
+
* Reassembles chunked data, parses individual lines, and guards against buffer overruns.
|
|
121
|
+
*/
|
|
122
|
+
export class JsonRpcStreamParser {
|
|
123
|
+
/**
|
|
124
|
+
* @param {Function} onMessage - Invoked with valid parsed JSON-RPC message object
|
|
125
|
+
* @param {Function} [onError] - Invoked with error when line fails to parse
|
|
126
|
+
* @param {object} [options]
|
|
127
|
+
*/
|
|
128
|
+
constructor(onMessage, onError = null, options = {}) {
|
|
129
|
+
this.onMessage = typeof onMessage === 'function' ? onMessage : () => {};
|
|
130
|
+
this.onError = typeof onError === 'function' ? onError : () => {};
|
|
131
|
+
this.maxBufferSize = options.maxBufferSize || IPC_LIMITS.MAX_BUFFER_SIZE_BYTES;
|
|
132
|
+
this.buffer = '';
|
|
133
|
+
this.decoder = new StringDecoder('utf8');
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Feeds a stream chunk into the parser.
|
|
138
|
+
*
|
|
139
|
+
* @param {Buffer|string} chunk
|
|
140
|
+
*/
|
|
141
|
+
feed(chunk) {
|
|
142
|
+
if (!chunk) return;
|
|
143
|
+
const str = typeof chunk === 'string' ? chunk : this.decoder.write(chunk);
|
|
144
|
+
this.buffer += str;
|
|
145
|
+
|
|
146
|
+
// Buffer overrun protection
|
|
147
|
+
if (this.buffer.length > this.maxBufferSize) {
|
|
148
|
+
this.buffer = '';
|
|
149
|
+
this.decoder = new StringDecoder('utf8');
|
|
150
|
+
this.onError(new Error(`Buffer overrun: payload exceeded ${this.maxBufferSize} bytes`), null);
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
let newlineIndex;
|
|
155
|
+
while ((newlineIndex = this.buffer.indexOf('\n')) !== -1) {
|
|
156
|
+
const line = this.buffer.slice(0, newlineIndex).trim();
|
|
157
|
+
this.buffer = this.buffer.slice(newlineIndex + 1);
|
|
158
|
+
|
|
159
|
+
if (!line) continue;
|
|
160
|
+
|
|
161
|
+
try {
|
|
162
|
+
const parsed = JSON.parse(line);
|
|
163
|
+
this.onMessage(parsed);
|
|
164
|
+
} catch (err) {
|
|
165
|
+
this.onError(err, line);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Resets the accumulator buffer.
|
|
172
|
+
*/
|
|
173
|
+
reset() {
|
|
174
|
+
this.buffer = '';
|
|
175
|
+
this.decoder = new StringDecoder('utf8');
|
|
176
|
+
}
|
|
177
|
+
}
|