ctxtop 0.0.0-stage → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (240) hide show
  1. package/.antigravity-plugin/plugin.json +36 -0
  2. package/.claude-plugin/plugin.json +18 -0
  3. package/CHECKSUMS.sha256 +149 -0
  4. package/LICENSE +27 -0
  5. package/README.md +330 -3
  6. package/SECURITY.md +22 -0
  7. package/agents/ah-flash-scout.md +25 -0
  8. package/assets/advanced_view_loaded_420px.png +0 -0
  9. package/assets/hero-demo.svg +188 -0
  10. package/assets/logo.svg +19 -0
  11. package/assets/simple_view_lean_420px.png +0 -0
  12. package/assets/simple_view_loaded_420px.png +0 -0
  13. package/assets/social-preview.svg +72 -0
  14. package/assets/zone_c_step3_shield_full.png +0 -0
  15. package/bin/ah-statusline.mjs +145 -0
  16. package/bin/cli.mjs +3 -0
  17. package/bin/ctxtop.mjs +1474 -0
  18. package/commands/cost-radar.md +11 -0
  19. package/commands/evolve.md +10 -0
  20. package/commands/handoff.md +10 -0
  21. package/commands/horizon.md +10 -0
  22. package/commands/inspect.md +10 -0
  23. package/commands/precheck.md +10 -0
  24. package/config/default_flightcheck.json +114 -0
  25. package/config/modelCatalog.json +620 -0
  26. package/config/platformQuirks.json +19 -0
  27. package/hooks/handlers/compact-lifecycle.mjs +262 -0
  28. package/hooks/handlers/hookIo.mjs +255 -0
  29. package/hooks/handlers/hookIpcClient.mjs +83 -0
  30. package/hooks/handlers/post-tool-use.mjs +265 -0
  31. package/hooks/handlers/pre-model-switch.mjs +249 -0
  32. package/hooks/handlers/pre-tool-use.mjs +365 -0
  33. package/hooks/handlers/stop-gate.mjs +240 -0
  34. package/hooks/handlers/user-prompt-submit.mjs +143 -0
  35. package/hooks/hooks.json +81 -0
  36. package/hooks/post_invocation.mjs +13 -0
  37. package/hooks/post_tool_use.mjs +17 -0
  38. package/hooks/pre_invocation.mjs +14 -0
  39. package/hooks/pre_tool_use.mjs +97 -0
  40. package/hooks/register.js +687 -0
  41. package/hooks/session_start.mjs +14 -0
  42. package/hooks/stop.mjs +13 -0
  43. package/hooks.json +56 -0
  44. package/package.json +103 -4
  45. package/packages/antigravity/package.json +14 -0
  46. package/packages/antigravity/src/index.mjs +1 -0
  47. package/packages/claude-code/package.json +14 -0
  48. package/packages/claude-code/src/index.mjs +2 -0
  49. package/packages/core/package.json +14 -0
  50. package/packages/core/src/index.mjs +1 -0
  51. package/packages/engine-node/package.json +14 -0
  52. package/packages/engine-node/src/index.mjs +1 -0
  53. package/packages/mcp/package.json +17 -0
  54. package/packages/mcp/src/server.mjs +396 -0
  55. package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
  56. package/packages/pro/README-SIGNING.md +30 -0
  57. package/packages/pro/package.json +16 -0
  58. package/packages/pro/src/index.mjs +3 -0
  59. package/packages/pro/src/team_finops_pack.mjs +241 -0
  60. package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
  61. package/plugin.json +36 -0
  62. package/rules/AGENTS.md +10 -0
  63. package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
  64. package/sidecars/horizon-daemon/server.mjs +2002 -0
  65. package/sidecars/horizon-daemon/sidecar.json +19 -0
  66. package/skills/cost-radar/SKILL.md +21 -0
  67. package/skills/evolve/SKILL.md +21 -0
  68. package/skills/handoff/SKILL.md +42 -0
  69. package/skills/horizon/SKILL.md +17 -0
  70. package/skills/inspect/SKILL.md +18 -0
  71. package/skills/precheck/SKILL.md +44 -0
  72. package/src/adapters/antigravity/index.mjs +79 -0
  73. package/src/adapters/claude-code/index.mjs +155 -0
  74. package/src/cli/cost_radar.mjs +70 -0
  75. package/src/cli/doctor.mjs +351 -0
  76. package/src/cli/horizon_hud.mjs +686 -0
  77. package/src/cli/init.mjs +425 -0
  78. package/src/cli/postmortem.mjs +515 -0
  79. package/src/coach/cacheGravityRouter.mjs +12 -0
  80. package/src/config/modelCatalog.json +620 -0
  81. package/src/config/platformQuirks.json +19 -0
  82. package/src/core/action_queue.mjs +264 -0
  83. package/src/core/ag_bridge.mjs +346 -0
  84. package/src/core/atomic_io.mjs +124 -0
  85. package/src/core/baseline.mjs +607 -0
  86. package/src/core/blindspot_sensors.mjs +399 -0
  87. package/src/core/classifier.mjs +1757 -0
  88. package/src/core/coach/circuit_breakers.mjs +650 -0
  89. package/src/core/coach/contradiction_auditor.mjs +239 -0
  90. package/src/core/coach/effort_advisor.mjs +143 -0
  91. package/src/core/coach/handoff_hydrator.mjs +483 -0
  92. package/src/core/coach/progressive_checkpointer.mjs +551 -0
  93. package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
  94. package/src/core/coach/reflector_queue.mjs +505 -0
  95. package/src/core/coach/saved_quota_ledger.mjs +615 -0
  96. package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
  97. package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
  98. package/src/core/coach/task_quota_router.mjs +955 -0
  99. package/src/core/coach/turn_zero_gate.mjs +574 -0
  100. package/src/core/compaction_coach.mjs +1126 -0
  101. package/src/core/config.mjs +214 -0
  102. package/src/core/constants.mjs +1800 -0
  103. package/src/core/detectors_det01_to_16.mjs +1474 -0
  104. package/src/core/episodic_memory.mjs +135 -0
  105. package/src/core/fts5_output_compressor.mjs +359 -0
  106. package/src/core/git_ledger.mjs +189 -0
  107. package/src/core/handoff_audit.mjs +558 -0
  108. package/src/core/history.mjs +221 -0
  109. package/src/core/hook_diagnostics.mjs +158 -0
  110. package/src/core/horizon_classifier.mjs +326 -0
  111. package/src/core/horizon_config.mjs +802 -0
  112. package/src/core/host_watchdog.mjs +200 -0
  113. package/src/core/layer5_hygiene.mjs +966 -0
  114. package/src/core/log_resolver.mjs +231 -0
  115. package/src/core/mcp_auditor.mjs +138 -0
  116. package/src/core/micro_skills_store.mjs +91 -0
  117. package/src/core/offenders.mjs +161 -0
  118. package/src/core/parser.mjs +1996 -0
  119. package/src/core/path_canonicalizer.mjs +73 -0
  120. package/src/core/paths.mjs +310 -0
  121. package/src/core/prefix_cache_shield.mjs +386 -0
  122. package/src/core/pro_license.mjs +385 -0
  123. package/src/core/prompt_rubric.mjs +518 -0
  124. package/src/core/pruner.mjs +433 -0
  125. package/src/core/quota.mjs +1860 -0
  126. package/src/core/rsi_instinct_engine.mjs +1197 -0
  127. package/src/core/sanitizer.mjs +121 -0
  128. package/src/core/session_forensics.mjs +303 -0
  129. package/src/core/session_timeline.mjs +358 -0
  130. package/src/core/settings.mjs +99 -0
  131. package/src/core/shared/detectors.mjs +1342 -0
  132. package/src/core/shared/fnv1a64.mjs +85 -0
  133. package/src/core/shared/handoff_schema.mjs +123 -0
  134. package/src/core/shared/index.mjs +5 -0
  135. package/src/core/shared/ipi_sanitizer.mjs +165 -0
  136. package/src/core/shared/micro_skills.mjs +1 -0
  137. package/src/core/shared/plugin_validator.mjs +202 -0
  138. package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
  139. package/src/core/sidecar_store.mjs +302 -0
  140. package/src/core/sprint_metrics.mjs +366 -0
  141. package/src/core/sqlite_client.mjs +283 -0
  142. package/src/core/storage_doctor.mjs +358 -0
  143. package/src/core/subagents.mjs +609 -0
  144. package/src/core/swarm_topology.mjs +360 -0
  145. package/src/core/task_quota_router.mjs +1656 -0
  146. package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
  147. package/src/core/telemetry/scope_lock_registry.mjs +578 -0
  148. package/src/core/telemetry/shadow_file_detector.mjs +291 -0
  149. package/src/core/telemetry/trajectory_watcher.mjs +259 -0
  150. package/src/core/timeline_svg.mjs +236 -0
  151. package/src/core/tool_surgeon.mjs +305 -0
  152. package/src/core/trajectory_stitcher.mjs +645 -0
  153. package/src/core/u_shaped_optimizer.mjs +789 -0
  154. package/src/core/wal_hygiene.mjs +233 -0
  155. package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
  156. package/src/core-isomorphic/catalog/index.mjs +1 -0
  157. package/src/core-isomorphic/coach/cacheGravityRouter.mjs +720 -0
  158. package/src/core-isomorphic/coach/microSkills.mjs +1 -0
  159. package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
  160. package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
  161. package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
  162. package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
  163. package/src/core-isomorphic/coach/ttlWatchdog.mjs +457 -0
  164. package/src/core-isomorphic/config/anthropicModelCatalog.json +203 -0
  165. package/src/core-isomorphic/config/catalogLoader.mjs +768 -0
  166. package/src/core-isomorphic/config/horizonConfig.mjs +1009 -0
  167. package/src/core-isomorphic/control/callTree.mjs +338 -0
  168. package/src/core-isomorphic/control/coachLatches.mjs +126 -0
  169. package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
  170. package/src/core-isomorphic/control/index.mjs +49 -0
  171. package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
  172. package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
  173. package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
  174. package/src/core-isomorphic/diagnostics/index.mjs +9 -0
  175. package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
  176. package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +622 -0
  177. package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
  178. package/src/core-isomorphic/economics/cacheGravity.mjs +351 -0
  179. package/src/core-isomorphic/economics/cliffBreaker.mjs +170 -0
  180. package/src/core-isomorphic/economics/driftLatency.mjs +319 -0
  181. package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
  182. package/src/core-isomorphic/economics/index.mjs +47 -0
  183. package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
  184. package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
  185. package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1035 -0
  186. package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +480 -0
  187. package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +603 -0
  188. package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +301 -0
  189. package/src/core-isomorphic/index.js +26 -0
  190. package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
  191. package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
  192. package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
  193. package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
  194. package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1132 -0
  195. package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
  196. package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
  197. package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
  198. package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1181 -0
  199. package/src/core-isomorphic/ui/modViews.mjs +1478 -0
  200. package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
  201. package/src/core-isomorphic/ustf/index.mjs +7 -0
  202. package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
  203. package/src/core-isomorphic/ustf/schema.mjs +186 -0
  204. package/src/core-isomorphic/utils/runtime.mjs +962 -0
  205. package/src/demo/synthetic_states.mjs +661 -0
  206. package/src/diagnostics/bugReportGenerator.mjs +253 -0
  207. package/src/diagnostics/doctorEngine.mjs +203 -0
  208. package/src/engine-node/db/index.mjs +58 -0
  209. package/src/engine-node/db/jsonl_fallback.mjs +184 -0
  210. package/src/engine-node/db/probe.mjs +110 -0
  211. package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
  212. package/src/engine-node/index.mjs +9 -0
  213. package/src/engine-node/ipc/client.mjs +447 -0
  214. package/src/engine-node/ipc/index.mjs +22 -0
  215. package/src/engine-node/ipc/protocol.mjs +177 -0
  216. package/src/engine-node/ipc/server.mjs +445 -0
  217. package/src/engine-node/offloader/index.mjs +6 -0
  218. package/src/engine-node/offloader/tool_offloader.mjs +241 -0
  219. package/src/engine-node/sensors/blindspots.mjs +369 -0
  220. package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
  221. package/src/engine-node/sensors/index.mjs +7 -0
  222. package/src/hooks/portfolio_runtime.mjs +858 -0
  223. package/src/hooks/post_invocation.mjs +419 -0
  224. package/src/hooks/pre_invocation.mjs +1015 -0
  225. package/src/hooks/session_start.mjs +161 -0
  226. package/src/shims/agy_cli_compressor.mjs +705 -0
  227. package/src/shims/agy_git_guard.mjs +749 -0
  228. package/src/shims/ah_log_query.mjs +39 -0
  229. package/src/ui/costRadarSvg.mjs +6 -0
  230. package/src/ui/horizonGrid.mjs +1 -0
  231. package/src/ui/horizonPanelHtml.mjs +1 -0
  232. package/src/ui/horizon_panel.css +167 -0
  233. package/src/ui/horizon_panel.js +212 -0
  234. package/src/ui/modViews.mjs +1 -0
  235. package/src/utils/nodeIo.mjs +59 -0
  236. package/src/utils/runtime.mjs +1 -0
  237. package/src/webview/advanced_view.html +1808 -0
  238. package/src/webview/horizon_panel.html +11389 -0
  239. package/src/webview/registry.mjs +80 -0
  240. package/src/webview/simple_view.html +1370 -0
@@ -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
+ }
@@ -0,0 +1,445 @@
1
+ /**
2
+ * @file src/engine-node/ipc/server.mjs
3
+ * Highbeam Micro-IPC Server.
4
+ *
5
+ * Implements high-throughput, low-latency (<0.8ms SLA) local JSON-RPC 2.0 server
6
+ * over Win32 Named Pipes and POSIX Unix Domain Sockets with non-spinning tool-boundary suspension.
7
+ * Strictly 0 npm dependencies (uses only standard node:* built-ins).
8
+ */
9
+
10
+ import net from 'node:net';
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import {
14
+ resolveIpcPath,
15
+ formatJsonRpcResponse,
16
+ formatJsonRpcError,
17
+ JsonRpcStreamParser,
18
+ JSON_RPC_ERRORS,
19
+ IPC_LIMITS
20
+ } from './protocol.mjs';
21
+
22
+ import {
23
+ CONTROL_STATES,
24
+ createInitialControlState,
25
+ transitionControlState,
26
+ evaluateToolBoundaryLatch
27
+ } from '../../core-isomorphic/control/controlStateMachine.mjs';
28
+
29
+ import { evaluateCoachLatch } from '../../core-isomorphic/control/coachLatches.mjs';
30
+
31
+ export class MicroIpcServer {
32
+ /**
33
+ * @param {object} [options]
34
+ * @param {string} [options.ipcPath]
35
+ * @param {Function} [options.logger]
36
+ */
37
+ constructor(options = {}) {
38
+ this.ipcPath = resolveIpcPath(options);
39
+ this.logger = typeof options.logger === 'function' ? options.logger : null;
40
+ this.server = null;
41
+ this.methods = new Map();
42
+ this.activeSockets = new Set();
43
+
44
+ // In-memory control state cache per session: Map<sessionId, ControlState>
45
+ this.controlStates = new Map();
46
+
47
+ // Non-spinning suspension map per session: Map<sessionId, Array<{ id, resolve, socket, timer }>>
48
+ this.suspensions = new Map();
49
+
50
+ this._registerDefaultMethods();
51
+ }
52
+
53
+ /**
54
+ * Registers default JSON-RPC 2.0 methods.
55
+ * @private
56
+ */
57
+ _registerDefaultMethods() {
58
+ // Ping
59
+ this.registerMethod('daemon.ping', async () => ({
60
+ pong: true,
61
+ timestamp: Date.now(),
62
+ platform: process.platform,
63
+ pid: process.pid
64
+ }));
65
+
66
+ // Control: get state
67
+ this.registerMethod('control.getState', async (params) => {
68
+ const sessionId = params?.sessionId || 'default';
69
+ const state = this.controlStates.get(sessionId) || createInitialControlState(sessionId);
70
+ return state;
71
+ });
72
+
73
+ // Control: transition state
74
+ this.registerMethod('control.transition', async (params) => {
75
+ const sessionId = params?.sessionId || 'default';
76
+ const action = params?.action || 'run';
77
+ const reason = params?.reason || '';
78
+ const current = this.controlStates.get(sessionId) || createInitialControlState(sessionId);
79
+ const next = transitionControlState(current, action, reason, params?.options || {});
80
+ this.controlStates.set(sessionId, next);
81
+
82
+ // Handle unpausing or stepping of suspended requests
83
+ if (action === 'resume' || action === 'run') {
84
+ this.resumeSuspended(sessionId, 'all', 'allow', reason || 'Execution resumed');
85
+ } else if (action === 'step') {
86
+ this.resumeSuspended(sessionId, 'one', 'allow', reason || 'Step executed');
87
+ } else if (action === 'abort') {
88
+ this.resumeSuspended(sessionId, 'all', 'deny', reason || 'Session aborted by user');
89
+ }
90
+
91
+ return next;
92
+ });
93
+
94
+ // Control: check latch
95
+ this.registerMethod('control.checkLatch', async (params) => {
96
+ const sessionId = params?.sessionId || 'default';
97
+ const state = this.controlStates.get(sessionId) || createInitialControlState(sessionId);
98
+ const flightMode = params?.flightMode || 'COACH';
99
+ const detectorVerdict = params?.detectorVerdict || null;
100
+ return evaluateCoachLatch({
101
+ controlState: state,
102
+ flightMode,
103
+ detectorVerdict
104
+ });
105
+ });
106
+
107
+ // Hook: PreToolUse with atomic non-spinning suspension
108
+ this.registerMethod('hook.preToolUse', async (params, socket, id) => {
109
+ const sessionId = params?.sessionId || params?.session_id || 'default';
110
+ const controlState = this.controlStates.get(sessionId) || createInitialControlState(sessionId);
111
+ const flightMode = params?.flightMode || 'COACH';
112
+
113
+ // 1. Evaluate user control state
114
+ const latch = evaluateToolBoundaryLatch(controlState);
115
+
116
+ if (latch.decision === 'deny') {
117
+ return {
118
+ decision: 'deny',
119
+ reason: latch.reason || 'Session aborted by user',
120
+ hookSpecificOutput: {
121
+ permissionDecision: 'deny',
122
+ permissionDecisionReason: latch.reason || 'Session aborted by user'
123
+ }
124
+ };
125
+ }
126
+
127
+ if (latch.decision === 'suspend') {
128
+ // Suspend non-spinning: hold request in suspension map
129
+ return new Promise((resolve) => {
130
+ const timeoutTimer = setTimeout(() => {
131
+ this._removeSuspension(sessionId, id);
132
+ resolve({
133
+ decision: 'deny',
134
+ reason: 'timeout: suspended execution exceeded safety ceiling',
135
+ hookSpecificOutput: {
136
+ permissionDecision: 'deny',
137
+ permissionDecisionReason: 'timeout: suspended execution exceeded safety ceiling'
138
+ }
139
+ });
140
+ }, 600000); // 10 minutes safety timeout
141
+
142
+ if (!this.suspensions.has(sessionId)) {
143
+ this.suspensions.set(sessionId, []);
144
+ }
145
+ this.suspensions.get(sessionId).push({
146
+ id,
147
+ resolve,
148
+ socket,
149
+ timer: timeoutTimer
150
+ });
151
+ });
152
+ }
153
+
154
+ if (latch.decision === 'allow' && latch.consumeStep) {
155
+ // Auto-consume step: transition back to PAUSED
156
+ const next = transitionControlState(controlState, 'consume_step');
157
+ this.controlStates.set(sessionId, next);
158
+ }
159
+
160
+ // 2. Evaluate COACH mode composite latch
161
+ const coachVerdict = evaluateCoachLatch({
162
+ controlState,
163
+ flightMode,
164
+ detectorVerdict: params?.detectorVerdict || null
165
+ });
166
+
167
+ return {
168
+ decision: coachVerdict.decision || 'allow',
169
+ flightMode: coachVerdict.flightMode || flightMode,
170
+ advisory: coachVerdict.advisory || false,
171
+ systemMessage: coachVerdict.systemMessage || null,
172
+ hookSpecificOutput: {
173
+ permissionDecision: coachVerdict.decision === 'block' || coachVerdict.decision === 'deny' ? 'deny' : 'allow',
174
+ permissionDecisionReason: coachVerdict.reason || coachVerdict.systemMessage || null
175
+ }
176
+ };
177
+ });
178
+
179
+ // Hook: PostToolUse
180
+ this.registerMethod('hook.postToolUse', async (params) => {
181
+ return {
182
+ success: true,
183
+ sanitized: false,
184
+ timestamp: Date.now()
185
+ };
186
+ });
187
+ }
188
+
189
+ /**
190
+ * Registers a custom JSON-RPC method handler.
191
+ *
192
+ * @param {string} name
193
+ * @param {Function} handler
194
+ */
195
+ registerMethod(name, handler) {
196
+ if (typeof handler === 'function') {
197
+ this.methods.set(name, handler);
198
+ }
199
+ }
200
+
201
+ /**
202
+ * Resumes suspended requests for a session.
203
+ *
204
+ * @param {string} sessionId
205
+ * @param {'all' | 'one'} mode
206
+ * @param {'allow' | 'deny'} decision
207
+ * @param {string} reason
208
+ */
209
+ resumeSuspended(sessionId, mode = 'all', decision = 'allow', reason = '') {
210
+ const list = this.suspensions.get(sessionId);
211
+ if (!list || list.length === 0) return;
212
+
213
+ if (mode === 'one') {
214
+ const item = list.shift();
215
+ if (item) {
216
+ clearTimeout(item.timer);
217
+ item.resolve({
218
+ decision,
219
+ consumeStep: true,
220
+ reason,
221
+ hookSpecificOutput: {
222
+ permissionDecision: decision,
223
+ permissionDecisionReason: reason
224
+ }
225
+ });
226
+ }
227
+ } else {
228
+ while (list.length > 0) {
229
+ const item = list.shift();
230
+ clearTimeout(item.timer);
231
+ item.resolve({
232
+ decision,
233
+ reason,
234
+ hookSpecificOutput: {
235
+ permissionDecision: decision,
236
+ permissionDecisionReason: reason
237
+ }
238
+ });
239
+ }
240
+ }
241
+ }
242
+
243
+ /**
244
+ * Helper to remove a single suspension entry.
245
+ * @private
246
+ */
247
+ _removeSuspension(sessionId, id) {
248
+ const list = this.suspensions.get(sessionId);
249
+ if (!list) return;
250
+ const idx = list.findIndex((item) => item.id === id);
251
+ if (idx !== -1) {
252
+ clearTimeout(list[idx].timer);
253
+ list.splice(idx, 1);
254
+ }
255
+ }
256
+
257
+ /**
258
+ * Cleans up any pending suspensions and cancels 600s safety timers
259
+ * associated with a disconnected or errored socket.
260
+ * @param {import('node:net').Socket} socket
261
+ * @private
262
+ */
263
+ _cleanupSocketSuspensions(socket) {
264
+ for (const [sessionId, list] of this.suspensions.entries()) {
265
+ const remaining = [];
266
+ for (const item of list) {
267
+ if (item.socket === socket) {
268
+ clearTimeout(item.timer);
269
+ try {
270
+ item.resolve({
271
+ decision: 'deny',
272
+ reason: 'Client socket disconnected'
273
+ });
274
+ } catch (_err) {
275
+ void _err;
276
+ }
277
+ } else {
278
+ remaining.push(item);
279
+ }
280
+ }
281
+ if (remaining.length === 0) {
282
+ this.suspensions.delete(sessionId);
283
+ } else {
284
+ this.suspensions.set(sessionId, remaining);
285
+ }
286
+ }
287
+ }
288
+
289
+ /**
290
+ * Starts listening on the configured pipe or socket path.
291
+ *
292
+ * @returns {Promise<MicroIpcServer>}
293
+ */
294
+ async listen() {
295
+ return new Promise((resolve, reject) => {
296
+ // POSIX socket preparation
297
+ if (process.platform !== 'win32') {
298
+ try {
299
+ const dir = path.dirname(this.ipcPath);
300
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
301
+
302
+ if (fs.existsSync(this.ipcPath)) {
303
+ // Clean stale socket if not active
304
+ try {
305
+ fs.unlinkSync(this.ipcPath);
306
+ } catch (_err) {
307
+ void _err;
308
+ }
309
+ }
310
+ } catch (prepErr) {
311
+ return reject(prepErr);
312
+ }
313
+ }
314
+
315
+ this.server = net.createServer((socket) => {
316
+ this.activeSockets.add(socket);
317
+
318
+ const parser = new JsonRpcStreamParser(
319
+ async (msg) => {
320
+ if (!msg || typeof msg !== 'object' || Array.isArray(msg)) {
321
+ if (!socket.destroyed) {
322
+ socket.write(formatJsonRpcError(null, JSON_RPC_ERRORS.INVALID_REQUEST, 'Invalid Request') + '\n');
323
+ }
324
+ return;
325
+ }
326
+
327
+ const id = msg.id !== undefined ? msg.id : null;
328
+ const method = msg.method;
329
+
330
+ if (!method || typeof method !== 'string') {
331
+ if (!socket.destroyed) {
332
+ socket.write(formatJsonRpcError(id, JSON_RPC_ERRORS.INVALID_REQUEST, 'Missing or invalid method') + '\n');
333
+ }
334
+ return;
335
+ }
336
+
337
+ const handler = this.methods.get(method);
338
+ if (!handler) {
339
+ if (!socket.destroyed) {
340
+ socket.write(formatJsonRpcError(id, JSON_RPC_ERRORS.METHOD_NOT_FOUND, `Method not found: ${method}`) + '\n');
341
+ }
342
+ return;
343
+ }
344
+
345
+ try {
346
+ const result = await handler(msg.params || {}, socket, id);
347
+ if (!socket.destroyed && id !== null) {
348
+ socket.write(formatJsonRpcResponse(id, result));
349
+ }
350
+ } catch (execErr) {
351
+ if (!socket.destroyed && id !== null) {
352
+ socket.write(formatJsonRpcError(id, JSON_RPC_ERRORS.INTERNAL_ERROR, execErr.message) + '\n');
353
+ }
354
+ }
355
+ },
356
+ (parseErr) => {
357
+ // Malformed JSON: return -32700 Parse error without crashing (satisfies test 29.B2)
358
+ if (!socket.destroyed) {
359
+ socket.write(formatJsonRpcError(null, JSON_RPC_ERRORS.PARSE_ERROR, 'Parse error: Invalid JSON'));
360
+ }
361
+ }
362
+ );
363
+
364
+ socket.on('data', (chunk) => parser.feed(chunk));
365
+
366
+ socket.on('error', (err) => {
367
+ this.activeSockets.delete(socket);
368
+ this._cleanupSocketSuspensions(socket);
369
+ // Client socket errors or disconnects mid-transmission handled cleanly without server crash
370
+ try {
371
+ socket.destroy();
372
+ } catch (_err) {
373
+ void _err;
374
+ }
375
+ });
376
+
377
+ socket.on('close', () => {
378
+ this.activeSockets.delete(socket);
379
+ this._cleanupSocketSuspensions(socket);
380
+ });
381
+ });
382
+
383
+ this.server.on('error', (err) => {
384
+ reject(err);
385
+ });
386
+
387
+ this.server.listen(this.ipcPath, () => {
388
+ if (process.platform !== 'win32') {
389
+ try {
390
+ fs.chmodSync(this.ipcPath, 0o600);
391
+ } catch (_err) {
392
+ void _err;
393
+ }
394
+ }
395
+ resolve(this);
396
+ });
397
+ });
398
+ }
399
+
400
+ /**
401
+ * Closes the server and releases all socket resources.
402
+ *
403
+ * @returns {Promise<void>}
404
+ */
405
+ async close() {
406
+ // Release any pending suspensions with an abort reason
407
+ for (const [sessionId, list] of this.suspensions.entries()) {
408
+ for (const item of list) {
409
+ clearTimeout(item.timer);
410
+ item.resolve({
411
+ decision: 'deny',
412
+ reason: 'IPC server shut down'
413
+ });
414
+ }
415
+ }
416
+ this.suspensions.clear();
417
+
418
+ // Close all connected sockets
419
+ for (const socket of this.activeSockets) {
420
+ try {
421
+ socket.destroy();
422
+ } catch (_err) {
423
+ void _err;
424
+ }
425
+ }
426
+ this.activeSockets.clear();
427
+
428
+ return new Promise((resolve) => {
429
+ if (!this.server) return resolve();
430
+ this.server.close(() => {
431
+ if (process.platform !== 'win32') {
432
+ try {
433
+ if (fs.existsSync(this.ipcPath)) {
434
+ fs.unlinkSync(this.ipcPath);
435
+ }
436
+ } catch (_err) {
437
+ void _err;
438
+ }
439
+ }
440
+ this.server = null;
441
+ resolve();
442
+ });
443
+ });
444
+ }
445
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * @file src/engine-node/offloader/index.mjs
3
+ * Lossless tool output offloader.
4
+ */
5
+
6
+ export * from './tool_offloader.mjs';