@cortex-agent/server 2026.10.6 → 2026.10.15-2

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 (843) hide show
  1. package/README.md +200 -170
  2. package/defaults/AGENTS.md +2 -1
  3. package/defaults/board/board.css +111 -0
  4. package/defaults/board/scaffold.html +76 -0
  5. package/defaults/config/environments/creative.json +0 -2
  6. package/defaults/config/environments/main.json +2 -9
  7. package/defaults/config/hooks/05-memory-ref-tracker.json +1 -2
  8. package/defaults/config/hooks/06-rules-loader.json +1 -2
  9. package/defaults/config/hooks/07-session-activity-tracker.json +1 -2
  10. package/defaults/config/hooks/08-agents-md-injector-post-tool.json +1 -2
  11. package/defaults/config/hooks/10-agents-md-injector-session-start.json +1 -2
  12. package/defaults/config/hooks/12-session-new-hook.json +1 -2
  13. package/defaults/config/hooks/13-status-md-guard.json +1 -2
  14. package/defaults/gitignore +5 -3
  15. package/defaults/hooks/agents-md-injector.mjs +22 -137
  16. package/defaults/hooks/cortex-context-lib.d.mts +53 -0
  17. package/defaults/hooks/cortex-context-lib.mjs +269 -0
  18. package/defaults/hooks/cortex-hook-api.mjs +0 -1
  19. package/defaults/hooks/git-support.mjs +33 -0
  20. package/defaults/hooks/memory-ref-tracker.mjs +2 -1
  21. package/defaults/hooks/new-session-hook.mjs +3 -17
  22. package/defaults/hooks/overlay/register.mjs +14 -0
  23. package/defaults/hooks/overlay/resolve.mjs +26 -0
  24. package/defaults/hooks/rules-loader.mjs +22 -99
  25. package/defaults/hooks/session-activity-tracker.mjs +0 -1
  26. package/defaults/hooks/status-md-guard.mjs +0 -1
  27. package/defaults/plugins/cortex-board/plugin.json +6 -0
  28. package/defaults/plugins/cortex-board/skills/board/SKILL.md +92 -0
  29. package/defaults/plugins/cortex-system/plugin.json +2 -2
  30. package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +4 -12
  31. package/defaults/plugins/cortex-system/skills/schedule/SKILL.md +37 -172
  32. package/defaults/plugins/cortex-system/skills/user-learn/SKILL.md +2 -8
  33. package/defaults/rules/experiment-format.md +4 -10
  34. package/defaults/rules/meta-conventions.md +6 -6
  35. package/dist/agent-adapter/browser-mcp-server.d.ts +3 -4
  36. package/dist/agent-adapter/browser-mcp-server.js +3 -4
  37. package/dist/agent-adapter/claude/adapter.d.ts +18 -119
  38. package/dist/agent-adapter/claude/adapter.js +41 -322
  39. package/dist/agent-adapter/claude/compact-window.d.ts +1 -0
  40. package/dist/agent-adapter/claude/compact-window.js +4 -6
  41. package/dist/agent-adapter/claude/defaults.d.ts +3 -14
  42. package/dist/agent-adapter/claude/defaults.js +4 -18
  43. package/dist/agent-adapter/claude/engine.d.ts +2 -5
  44. package/dist/agent-adapter/claude/engine.js +11 -69
  45. package/dist/agent-adapter/claude/event-translator.d.ts +1 -1
  46. package/dist/agent-adapter/claude/event-translator.js +10 -20
  47. package/dist/agent-adapter/claude/hooks-builder.d.ts +0 -8
  48. package/dist/agent-adapter/claude/hooks-builder.js +3 -29
  49. package/dist/agent-adapter/claude/mcp-config.js +4 -4
  50. package/dist/agent-adapter/claude/session-options.d.ts +74 -0
  51. package/dist/agent-adapter/claude/session-options.js +157 -0
  52. package/dist/agent-adapter/claude/spawn-args.d.ts +10 -23
  53. package/dist/agent-adapter/claude/spawn-args.js +39 -29
  54. package/dist/agent-adapter/claude/transcript-path.d.ts +2 -1
  55. package/dist/agent-adapter/claude/transcript-path.js +4 -3
  56. package/dist/agent-adapter/claude/turn-machine.d.ts +0 -3
  57. package/dist/agent-adapter/claude/turn-machine.js +6 -19
  58. package/dist/agent-adapter/continuation-phase.d.ts +18 -15
  59. package/dist/agent-adapter/continuation-phase.js +31 -61
  60. package/dist/agent-adapter/engine-injections.d.ts +47 -0
  61. package/dist/agent-adapter/engine-injections.js +80 -0
  62. package/dist/agent-adapter/normalize/event-types.d.ts +2 -45
  63. package/dist/agent-adapter/normalize/event-types.js +1 -56
  64. package/dist/agent-adapter/pi/adapter.d.ts +3 -1
  65. package/dist/agent-adapter/pi/adapter.js +8 -13
  66. package/dist/agent-adapter/pi/agent-dir.d.ts +1 -1
  67. package/dist/agent-adapter/pi/agent-dir.js +3 -3
  68. package/dist/agent-adapter/pi/background-subagent.d.ts +7 -2
  69. package/dist/agent-adapter/pi/child-runner.d.ts +4 -11
  70. package/dist/agent-adapter/pi/child-runner.js +4 -14
  71. package/dist/agent-adapter/pi/child-session.d.ts +2 -0
  72. package/dist/agent-adapter/pi/child-session.js +13 -6
  73. package/dist/agent-adapter/pi/engine.d.ts +2 -5
  74. package/dist/agent-adapter/pi/engine.js +8 -63
  75. package/dist/agent-adapter/pi/event-parser.js +1 -1
  76. package/dist/agent-adapter/pi/extensions.d.ts +2 -0
  77. package/dist/agent-adapter/pi/extensions.js +16 -2
  78. package/dist/agent-adapter/pi/hook-bridge.js +6 -5
  79. package/dist/agent-adapter/pi/mcp-bridge.js +13 -8
  80. package/dist/agent-adapter/pi/native-tool-policy.d.ts +3 -0
  81. package/dist/agent-adapter/pi/native-tool-policy.js +11 -0
  82. package/dist/agent-adapter/pi/pi-session.d.ts +3 -0
  83. package/dist/agent-adapter/pi/pi-session.js +8 -4
  84. package/dist/agent-adapter/pi/providers-config.d.ts +2 -2
  85. package/dist/agent-adapter/pi/providers-config.js +1 -1
  86. package/dist/agent-adapter/pi/quota-sink.d.ts +3 -3
  87. package/dist/agent-adapter/pi/quota-sink.js +3 -3
  88. package/dist/agent-adapter/pi/runtime-settings.js +13 -0
  89. package/dist/agent-adapter/pi/runtime.d.ts +2 -0
  90. package/dist/agent-adapter/pi/runtime.js +7 -1
  91. package/dist/agent-adapter/pi/session-options.d.ts +10 -7
  92. package/dist/agent-adapter/pi/session-options.js +17 -16
  93. package/dist/agent-adapter/pi/subagent.d.ts +2 -0
  94. package/dist/agent-adapter/pi/subagent.js +15 -10
  95. package/dist/agent-adapter/pi/tool-shims.js +14 -26
  96. package/dist/agent-adapter/pi/web-fetch.js +2 -3
  97. package/dist/agent-adapter/pi/web-search.js +5 -25
  98. package/dist/agent-adapter/run-events.d.ts +1 -15
  99. package/dist/agent-adapter/run-events.js +0 -2
  100. package/dist/agent-adapter/types.d.ts +13 -20
  101. package/dist/client-bundle/client.mjs +4859 -0
  102. package/dist/client-bundle/cortex-run-watcher.mjs +4 -0
  103. package/dist/client-bundle/manifest.json +5 -0
  104. package/dist/core/agents/roles.d.ts +14 -11
  105. package/dist/core/agents/roles.js +43 -37
  106. package/dist/core/agents/subagent/catalog.d.ts +15 -6
  107. package/dist/core/agents/subagent/catalog.js +23 -61
  108. package/dist/core/agents/subagent/model-spec.d.ts +28 -0
  109. package/dist/core/agents/subagent/model-spec.js +39 -0
  110. package/dist/core/agents/subagent/schema.d.ts +2 -2
  111. package/dist/core/agents/subagent/schema.js +4 -6
  112. package/dist/core/atomic-write.js +6 -127
  113. package/dist/core/board-action.d.ts +19 -0
  114. package/dist/core/board-action.js +24 -0
  115. package/dist/core/builtin-layer.d.ts +22 -0
  116. package/dist/core/builtin-layer.js +45 -0
  117. package/dist/core/claude-credentials.d.ts +46 -9
  118. package/dist/core/claude-credentials.js +117 -64
  119. package/dist/core/codex-quota.d.ts +1 -1
  120. package/dist/core/codex-quota.js +1 -1
  121. package/dist/core/codex-token.d.ts +4 -0
  122. package/dist/core/codex-token.js +26 -0
  123. package/dist/core/debug-mode.d.ts +1 -1
  124. package/dist/core/debug-mode.js +2 -2
  125. package/dist/core/exec-async.d.ts +3 -1
  126. package/dist/core/exec-async.js +2 -1
  127. package/dist/core/file-lock.d.ts +15 -0
  128. package/dist/core/file-lock.js +164 -0
  129. package/dist/core/format-duration.d.ts +7 -0
  130. package/dist/core/format-duration.js +23 -0
  131. package/dist/core/gateway-generator.d.ts +27 -21
  132. package/dist/core/gateway-generator.js +116 -120
  133. package/dist/core/git-availability.d.ts +2 -0
  134. package/dist/core/git-availability.js +43 -0
  135. package/dist/core/hook-bus.d.ts +3 -1
  136. package/dist/core/hook-bus.js +7 -8
  137. package/dist/core/hook-scripts.d.ts +19 -0
  138. package/dist/core/hook-scripts.js +30 -0
  139. package/dist/core/json-repository.d.ts +25 -2
  140. package/dist/core/json-repository.js +68 -42
  141. package/dist/core/locales/en.d.ts +102 -106
  142. package/dist/core/locales/slices/commands.d.ts +47 -34
  143. package/dist/core/locales/slices/commands.js +96 -70
  144. package/dist/core/locales/slices/init.d.ts +12 -20
  145. package/dist/core/locales/slices/init.js +25 -55
  146. package/dist/core/locales/slices/interactions.d.ts +3 -3
  147. package/dist/core/locales/slices/interactions.js +6 -6
  148. package/dist/core/locales/slices/notices.d.ts +4 -4
  149. package/dist/core/locales/slices/notices.js +8 -8
  150. package/dist/core/locales/slices/scheduling.d.ts +9 -10
  151. package/dist/core/locales/slices/scheduling.js +18 -20
  152. package/dist/core/locales/slices/startup.d.ts +2 -0
  153. package/dist/core/locales/slices/startup.js +4 -0
  154. package/dist/core/locales/slices/status.d.ts +6 -4
  155. package/dist/core/locales/slices/status.js +12 -8
  156. package/dist/core/locales/slices/tui.d.ts +0 -1
  157. package/dist/core/locales/slices/tui.js +0 -2
  158. package/dist/core/locales/slices/uiextra.d.ts +12 -8
  159. package/dist/core/locales/slices/uiextra.js +24 -16
  160. package/dist/core/locales/slices/uimsg.d.ts +7 -22
  161. package/dist/core/locales/slices/uimsg.js +16 -46
  162. package/dist/core/mcp-bundles.d.ts +1 -1
  163. package/dist/core/mcp-bundles.js +1 -0
  164. package/dist/core/mcp-tool-gate.d.ts +3 -0
  165. package/dist/core/mcp-tool-gate.js +8 -6
  166. package/dist/core/media-types.d.ts +5 -0
  167. package/dist/core/media-types.js +24 -0
  168. package/dist/core/models-generator.d.ts +29 -0
  169. package/dist/core/models-generator.js +82 -0
  170. package/dist/core/paths.d.ts +21 -4
  171. package/dist/core/paths.js +21 -4
  172. package/dist/core/pi-sdk.d.ts +9 -0
  173. package/dist/core/pi-sdk.js +28 -0
  174. package/dist/core/private-dir.d.ts +13 -0
  175. package/dist/core/private-dir.js +48 -0
  176. package/dist/core/process-command-line.d.ts +6 -0
  177. package/dist/core/process-command-line.js +39 -0
  178. package/dist/core/run-registry.d.ts +2 -0
  179. package/dist/core/run-registry.js +1 -1
  180. package/dist/core/settings-spec.d.ts +5 -14
  181. package/dist/core/settings-spec.js +6 -18
  182. package/dist/core/short-session-id.d.ts +2 -0
  183. package/dist/core/short-session-id.js +4 -0
  184. package/dist/core/singleton-lock.d.ts +19 -3
  185. package/dist/core/singleton-lock.js +91 -15
  186. package/dist/core/status-format.d.ts +6 -7
  187. package/dist/core/status-format.js +9 -15
  188. package/dist/core/subagent-spawn.d.ts +40 -0
  189. package/dist/core/subagent-spawn.js +47 -0
  190. package/dist/core/team-action.d.ts +28 -0
  191. package/dist/core/team-action.js +65 -0
  192. package/dist/{agent-adapter/normalize → core}/todo.d.ts +1 -2
  193. package/dist/{agent-adapter/normalize → core}/todo.js +1 -1
  194. package/dist/core/types/agent-types.d.ts +0 -2
  195. package/dist/core/types/environment-types.d.ts +7 -21
  196. package/dist/core/utils.d.ts +6 -0
  197. package/dist/core/utils.js +14 -0
  198. package/dist/core/workspace-filenames.d.ts +9 -0
  199. package/dist/core/workspace-filenames.js +61 -0
  200. package/dist/domain/agents/agent-state.d.ts +11 -56
  201. package/dist/domain/agents/agent-state.js +48 -123
  202. package/dist/domain/agents/agent-switch.d.ts +2 -24
  203. package/dist/domain/agents/agent-switch.js +12 -75
  204. package/dist/domain/agents/config.d.ts +12 -111
  205. package/dist/domain/agents/config.js +56 -443
  206. package/dist/domain/agents/engine-selection.d.ts +21 -0
  207. package/dist/domain/agents/engine-selection.js +37 -0
  208. package/dist/domain/agents/environments/entities.d.ts +1 -0
  209. package/dist/domain/agents/environments/entities.js +1 -1
  210. package/dist/domain/agents/environments/file-refs.d.ts +4 -3
  211. package/dist/domain/agents/environments/file-refs.js +14 -11
  212. package/dist/domain/agents/environments/index.d.ts +2 -1
  213. package/dist/domain/agents/environments/index.js +2 -1
  214. package/dist/domain/agents/environments/registry.d.ts +3 -3
  215. package/dist/domain/agents/environments/registry.js +10 -7
  216. package/dist/domain/agents/environments/resolve.d.ts +11 -0
  217. package/dist/domain/agents/environments/resolve.js +36 -0
  218. package/dist/domain/agents/environments/schema.d.ts +2 -2
  219. package/dist/domain/agents/environments/schema.js +7 -4
  220. package/dist/domain/agents/environments/system-prompt.d.ts +37 -0
  221. package/dist/domain/agents/environments/system-prompt.js +110 -0
  222. package/dist/domain/agents/index.d.ts +2 -1
  223. package/dist/domain/agents/index.js +3 -7
  224. package/dist/domain/agents/model-selection.d.ts +18 -70
  225. package/dist/domain/agents/model-selection.js +100 -150
  226. package/dist/domain/agents/models.d.ts +12 -0
  227. package/dist/domain/agents/models.js +94 -0
  228. package/dist/domain/agents/subagent/background-spend.d.ts +17 -0
  229. package/dist/domain/agents/subagent/background-spend.js +42 -0
  230. package/dist/domain/agents/subagent/runner.d.ts +6 -18
  231. package/dist/domain/agents/subagent/runner.js +20 -81
  232. package/dist/domain/auth/anthropic-env.d.ts +20 -0
  233. package/dist/domain/auth/anthropic-env.js +132 -0
  234. package/dist/domain/auth/auth-status.d.ts +4 -5
  235. package/dist/domain/auth/auth-status.js +26 -64
  236. package/dist/domain/auth/auth-watch.js +36 -21
  237. package/dist/domain/auth/cc-auth-cli.d.ts +1 -0
  238. package/dist/domain/auth/cc-auth-cli.js +42 -20
  239. package/dist/domain/auth/cc-login.d.ts +1 -1
  240. package/dist/domain/auth/cc-login.js +9 -2
  241. package/dist/domain/auth/cc-subscription.js +8 -7
  242. package/dist/domain/auth/claude-account-credentials.d.ts +13 -0
  243. package/dist/domain/auth/claude-account-credentials.js +22 -0
  244. package/dist/domain/auth/claude-user-settings.d.ts +17 -20
  245. package/dist/domain/auth/claude-user-settings.js +68 -163
  246. package/dist/domain/auth/codex-credentials.d.ts +13 -0
  247. package/dist/domain/auth/codex-credentials.js +25 -0
  248. package/dist/domain/auth/gateway-sync.d.ts +6 -26
  249. package/dist/domain/auth/gateway-sync.js +31 -43
  250. package/dist/domain/auth/login-flow.d.ts +14 -2
  251. package/dist/domain/auth/login-flow.js +86 -20
  252. package/dist/domain/auth/login-service.d.ts +6 -5
  253. package/dist/domain/auth/login-service.js +14 -42
  254. package/dist/domain/auth/logout.d.ts +1 -1
  255. package/dist/domain/auth/logout.js +67 -34
  256. package/dist/domain/auth/pi-login.d.ts +2 -0
  257. package/dist/domain/auth/pi-login.js +19 -11
  258. package/dist/domain/auth/pi-oauth.d.ts +2 -0
  259. package/dist/domain/auth/pi-oauth.js +24 -13
  260. package/dist/domain/auth/pi-runtime.d.ts +6 -0
  261. package/dist/{core/types → domain/benchmark}/benchmark-types.d.ts +1 -1
  262. package/dist/domain/benchmark/identity.d.ts +3 -5
  263. package/dist/domain/benchmark/identity.js +0 -1
  264. package/dist/domain/benchmark/production-attempt-identity.d.ts +6 -5
  265. package/dist/domain/benchmark/production-attempt-identity.js +33 -36
  266. package/dist/{core → domain/benchmark}/production-benchmark-evidence.d.ts +1 -1
  267. package/dist/domain/benchmark/session-evidence.d.ts +3 -2
  268. package/dist/domain/benchmark/session-evidence.js +8 -1
  269. package/dist/domain/boards/board-context.d.ts +17 -0
  270. package/dist/domain/boards/board-context.js +11 -0
  271. package/dist/domain/boards/board-paths.d.ts +18 -0
  272. package/dist/domain/boards/board-paths.js +32 -0
  273. package/dist/domain/boards/board-service.d.ts +50 -0
  274. package/dist/domain/boards/board-service.js +146 -0
  275. package/dist/domain/boards/board-watcher.d.ts +36 -0
  276. package/dist/domain/boards/board-watcher.js +284 -0
  277. package/dist/domain/{commissions → boards}/decision-projection.d.ts +11 -9
  278. package/dist/domain/boards/decision-projection.js +44 -0
  279. package/dist/domain/costs/account-reset.d.ts +30 -0
  280. package/dist/domain/costs/account-reset.js +98 -0
  281. package/dist/domain/costs/aistatus-config.d.ts +27 -0
  282. package/dist/domain/costs/aistatus-config.js +56 -0
  283. package/dist/domain/costs/claude-account.d.ts +34 -0
  284. package/dist/domain/costs/claude-account.js +149 -0
  285. package/dist/domain/costs/codex-account.d.ts +55 -0
  286. package/dist/domain/costs/codex-account.js +155 -0
  287. package/dist/domain/costs/cost-tracker.d.ts +2 -0
  288. package/dist/domain/costs/cost-tracker.js +4 -0
  289. package/dist/domain/costs/gateway-manager.js +2 -3
  290. package/dist/domain/costs/rate-limit-throttle.d.ts +14 -10
  291. package/dist/domain/costs/rate-limit-throttle.js +66 -25
  292. package/dist/domain/costs/reset-account.d.ts +34 -0
  293. package/dist/domain/costs/reset-account.js +5 -0
  294. package/dist/domain/costs/resume-registry.d.ts +1 -1
  295. package/dist/domain/costs/resume-registry.js +1 -8
  296. package/dist/domain/costs/usage-service.d.ts +24 -0
  297. package/dist/domain/costs/usage-service.js +206 -45
  298. package/dist/domain/costs/usage-store.d.ts +27 -0
  299. package/dist/domain/costs/usage-store.js +18 -1
  300. package/dist/domain/executions/registry.d.ts +18 -3
  301. package/dist/domain/executions/registry.js +40 -9
  302. package/dist/domain/mcp/bundled-server.js +15 -14
  303. package/dist/domain/mcp/feishu/file.js +2 -2
  304. package/dist/domain/mcp/tools/catalog-owner.d.ts +3 -0
  305. package/dist/domain/mcp/tools/catalog-owner.js +23 -0
  306. package/dist/domain/mcp/tools/context.d.ts +20 -13
  307. package/dist/domain/mcp/tools/context.js +42 -14
  308. package/dist/domain/mcp/tools/cost.js +1 -1
  309. package/dist/domain/mcp/tools/executions.js +2 -8
  310. package/dist/domain/mcp/tools/interaction-ask.js +7 -8
  311. package/dist/domain/mcp/tools/interaction-plan.js +2 -2
  312. package/dist/domain/mcp/tools/remote-devices.d.ts +9 -0
  313. package/dist/domain/mcp/tools/remote-devices.js +28 -0
  314. package/dist/domain/mcp/tools/remote-ops.js +19 -14
  315. package/dist/domain/mcp/tools/slack.js +2 -2
  316. package/dist/domain/mcp/tools/subagent.d.ts +0 -4
  317. package/dist/domain/mcp/tools/subagent.js +11 -21
  318. package/dist/domain/mcp/tools/time.js +2 -2
  319. package/dist/domain/mcp/tools/ui-board.d.ts +12 -0
  320. package/dist/domain/mcp/tools/ui-board.js +48 -0
  321. package/dist/domain/mcp/tools/ui-decision.js +8 -20
  322. package/dist/domain/mcp/tools/ui-file.js +6 -6
  323. package/dist/domain/mcp/tools/ui-view.js +7 -17
  324. package/dist/domain/mcp/tools/waitpoint.d.ts +25 -0
  325. package/dist/domain/mcp/tools/waitpoint.js +33 -45
  326. package/dist/domain/mcp/tools/workers.d.ts +2 -0
  327. package/dist/domain/mcp/tools/workers.js +33 -40
  328. package/dist/domain/memory/agents-md-injector.d.ts +4 -2
  329. package/dist/domain/memory/agents-md-injector.js +30 -128
  330. package/dist/domain/memory/consolidate.d.ts +2 -0
  331. package/dist/domain/memory/consolidate.js +36 -78
  332. package/dist/domain/memory/index-regen.d.ts +24 -7
  333. package/dist/domain/memory/index-regen.js +201 -265
  334. package/dist/domain/memory/rules-loader.d.ts +4 -3
  335. package/dist/domain/memory/rules-loader.js +7 -46
  336. package/dist/domain/memory/watcher.d.ts +8 -1
  337. package/dist/domain/memory/watcher.js +108 -34
  338. package/dist/domain/pi-providers/custom-provider-model.d.ts +1 -1
  339. package/dist/domain/pi-providers/custom-provider-model.js +1 -1
  340. package/dist/domain/pi-providers/custom-provider-service.js +15 -1
  341. package/dist/domain/pi-providers/gateway-route-store.js +5 -5
  342. package/dist/domain/plugins/authoring.d.ts +8 -8
  343. package/dist/domain/plugins/authoring.js +154 -43
  344. package/dist/domain/plugins/builtin.d.ts +25 -0
  345. package/dist/domain/plugins/builtin.js +44 -0
  346. package/dist/domain/plugins/catalog-types.d.ts +16 -2
  347. package/dist/domain/plugins/catalog-types.js +18 -1
  348. package/dist/domain/plugins/catalog.d.ts +36 -2
  349. package/dist/domain/plugins/catalog.js +165 -8
  350. package/dist/domain/plugins/conversation-skills.d.ts +10 -0
  351. package/dist/domain/plugins/conversation-skills.js +22 -0
  352. package/dist/domain/plugins/runtime-gc.d.ts +10 -0
  353. package/dist/domain/plugins/runtime-gc.js +68 -0
  354. package/dist/domain/plugins/runtime.d.ts +5 -0
  355. package/dist/domain/plugins/runtime.js +129 -82
  356. package/dist/domain/plugins/skill.d.ts +6 -2
  357. package/dist/domain/plugins/skill.js +4 -2
  358. package/dist/domain/remote/client-bootstrap.js +8 -14
  359. package/dist/domain/remote/client-hot-reload.d.ts +2 -1
  360. package/dist/domain/remote/client-hot-reload.js +53 -24
  361. package/dist/domain/remote/client-lifecycle.d.ts +32 -0
  362. package/dist/domain/remote/client-lifecycle.js +382 -0
  363. package/dist/domain/remote/client-manager.d.ts +22 -43
  364. package/dist/domain/remote/client-manager.js +189 -570
  365. package/dist/domain/remote/client-pids.d.ts +13 -0
  366. package/dist/domain/remote/client-pids.js +43 -0
  367. package/dist/domain/remote/client-protocol.d.ts +1 -0
  368. package/dist/domain/remote/client-protocol.js +1 -0
  369. package/dist/domain/remote/client-remove.js +2 -10
  370. package/dist/domain/remote/client-ssh-tunnel.d.ts +2 -0
  371. package/dist/domain/remote/client-ssh-tunnel.js +79 -13
  372. package/dist/domain/remote/device-port.d.ts +2 -1
  373. package/dist/domain/remote/local-client-install.d.ts +32 -0
  374. package/dist/domain/remote/local-client-install.js +168 -0
  375. package/dist/domain/remote/local-client-stop.d.ts +37 -0
  376. package/dist/domain/remote/local-client-stop.js +101 -0
  377. package/dist/domain/remote/owned-local-launch.d.ts +22 -0
  378. package/dist/domain/remote/owned-local-launch.js +75 -0
  379. package/dist/domain/remote/package-client-bundle.d.ts +14 -0
  380. package/dist/domain/remote/package-client-bundle.js +37 -0
  381. package/dist/domain/remote/reverse-stream.d.ts +3 -12
  382. package/dist/domain/remote/ssh-exec.d.ts +10 -0
  383. package/dist/domain/remote/ssh-exec.js +25 -0
  384. package/dist/domain/runs/adapters.js +2 -0
  385. package/dist/domain/runs/attempt.d.ts +4 -4
  386. package/dist/domain/runs/attempt.js +26 -20
  387. package/dist/domain/runs/builders.d.ts +3 -8
  388. package/dist/domain/runs/builders.js +11 -13
  389. package/dist/domain/runs/compact.d.ts +9 -18
  390. package/dist/domain/runs/compact.js +20 -75
  391. package/dist/domain/runs/config-resolver.d.ts +20 -78
  392. package/dist/domain/runs/config-resolver.js +27 -138
  393. package/dist/domain/runs/engine-spec.d.ts +4 -22
  394. package/dist/domain/runs/engine-spec.js +18 -44
  395. package/dist/domain/runs/engines.d.ts +14 -5
  396. package/dist/domain/runs/engines.js +30 -12
  397. package/dist/domain/runs/events.d.ts +1 -1
  398. package/dist/domain/runs/fallback.d.ts +7 -36
  399. package/dist/domain/runs/fallback.js +12 -68
  400. package/dist/domain/runs/mode-env.d.ts +16 -0
  401. package/dist/domain/runs/mode-env.js +48 -0
  402. package/dist/domain/runs/notices.d.ts +1 -6
  403. package/dist/domain/runs/notices.js +3 -16
  404. package/dist/domain/runs/prompt.d.ts +13 -19
  405. package/dist/domain/runs/prompt.js +37 -93
  406. package/dist/domain/runs/request.d.ts +13 -7
  407. package/dist/domain/runs/retryable-errors.d.ts +5 -0
  408. package/dist/domain/runs/retryable-errors.js +22 -0
  409. package/dist/domain/runs/run.d.ts +52 -31
  410. package/dist/domain/runs/run.js +117 -117
  411. package/dist/domain/runs/service.d.ts +1 -1
  412. package/dist/domain/runs/service.js +11 -10
  413. package/dist/domain/runs/spec-loader.d.ts +8 -10
  414. package/dist/domain/runs/spec-loader.js +5 -7
  415. package/dist/domain/runs/spend.d.ts +16 -0
  416. package/dist/domain/runs/spend.js +31 -0
  417. package/dist/domain/scheduling/builtin-job-migration.js +4 -5
  418. package/dist/domain/scheduling/builtin-jobs.d.ts +1 -2
  419. package/dist/domain/scheduling/builtin-jobs.js +5 -5
  420. package/dist/domain/scheduling/jobs/scheduled-task.d.ts +3 -2
  421. package/dist/domain/scheduling/jobs/scheduled-task.js +37 -30
  422. package/dist/domain/scheduling/runner.d.ts +11 -2
  423. package/dist/domain/scheduling/runner.js +7 -2
  424. package/dist/domain/scheduling/schedule-ops.d.ts +15 -0
  425. package/dist/domain/scheduling/schedule-ops.js +43 -0
  426. package/dist/domain/scheduling/schedule-selection.d.ts +3 -0
  427. package/dist/domain/scheduling/schedule-selection.js +16 -0
  428. package/dist/domain/scheduling/schedule-spec.d.ts +79 -0
  429. package/dist/domain/scheduling/schedule-spec.js +169 -0
  430. package/dist/domain/scheduling/scheduler.d.ts +30 -13
  431. package/dist/domain/scheduling/scheduler.js +165 -373
  432. package/dist/domain/sessions/session-backup.d.ts +3 -2
  433. package/dist/domain/sessions/session-backup.js +8 -7
  434. package/dist/domain/sessions/session-hooks.d.ts +28 -10
  435. package/dist/domain/sessions/session-hooks.js +71 -66
  436. package/dist/domain/sessions/session-lifecycle.d.ts +28 -65
  437. package/dist/domain/sessions/session-lifecycle.js +41 -119
  438. package/dist/domain/sessions/session-retention.d.ts +3 -2
  439. package/dist/domain/sessions/session-retention.js +69 -76
  440. package/dist/domain/sessions/team.d.ts +8 -0
  441. package/dist/domain/sessions/team.js +9 -0
  442. package/dist/domain/system/doctor.d.ts +9 -1
  443. package/dist/domain/system/doctor.js +55 -57
  444. package/dist/domain/system/rebuild-hold.d.ts +2 -0
  445. package/dist/domain/system/rebuild-hold.js +10 -5
  446. package/dist/domain/system/server-update-check.d.ts +5 -1
  447. package/dist/domain/system/server-update-check.js +17 -19
  448. package/dist/domain/system/server-update-coordinator.d.ts +4 -1
  449. package/dist/domain/system/server-update-coordinator.js +21 -3
  450. package/dist/domain/system/server-update-install.d.ts +16 -0
  451. package/dist/domain/system/server-update-install.js +65 -0
  452. package/dist/domain/system/update-ui-state.d.ts +8 -1
  453. package/dist/domain/system/update-ui-state.js +16 -2
  454. package/dist/domain/tui-session/tui-session-service.js +14 -15
  455. package/dist/domain/tui-session/types.d.ts +3 -7
  456. package/dist/domain/ui-service/app-router.d.ts +99 -117
  457. package/dist/domain/ui-service/app-router.js +31 -24
  458. package/dist/domain/ui-service/contract.parity.d.ts +19 -0
  459. package/dist/domain/ui-service/contract.parity.js +1 -0
  460. package/dist/domain/ui-service/input-schemas.d.ts +106 -212
  461. package/dist/domain/ui-service/input-schemas.js +106 -107
  462. package/dist/domain/ui-service/mutate/approvals.d.ts +5 -5
  463. package/dist/domain/ui-service/mutate/auth.d.ts +7 -7
  464. package/dist/domain/ui-service/mutate/auth.js +21 -20
  465. package/dist/domain/ui-service/mutate/config.d.ts +3 -11
  466. package/dist/domain/ui-service/mutate/config.js +0 -22
  467. package/dist/domain/ui-service/mutate/custom-providers.d.ts +3 -3
  468. package/dist/domain/ui-service/mutate/environments.d.ts +8 -4
  469. package/dist/domain/ui-service/mutate/environments.js +16 -1
  470. package/dist/domain/ui-service/mutate/executions.js +2 -0
  471. package/dist/domain/ui-service/mutate/hooks.d.ts +6 -6
  472. package/dist/domain/ui-service/mutate/hooks.js +4 -4
  473. package/dist/domain/ui-service/mutate/issues.d.ts +3 -3
  474. package/dist/domain/ui-service/mutate/models.d.ts +10 -0
  475. package/dist/domain/ui-service/mutate/models.js +118 -0
  476. package/dist/domain/ui-service/mutate/notes.d.ts +6 -6
  477. package/dist/domain/ui-service/mutate/plugin-packages.d.ts +10 -9
  478. package/dist/domain/ui-service/mutate/plugin-packages.js +20 -4
  479. package/dist/domain/ui-service/mutate/plugins.d.ts +2 -2
  480. package/dist/domain/ui-service/mutate/plugins.js +3 -8
  481. package/dist/domain/ui-service/mutate/schedules.d.ts +3 -3
  482. package/dist/domain/ui-service/mutate/schedules.js +14 -61
  483. package/dist/domain/ui-service/mutate/session-metadata.js +0 -6
  484. package/dist/domain/ui-service/mutate/sessions.d.ts +16 -28
  485. package/dist/domain/ui-service/mutate/sessions.js +37 -241
  486. package/dist/domain/ui-service/mutate/system.d.ts +10 -7
  487. package/dist/domain/ui-service/mutate/system.js +19 -17
  488. package/dist/domain/ui-service/mutate/usage-sharing.d.ts +8 -0
  489. package/dist/domain/ui-service/mutate/usage-sharing.js +16 -0
  490. package/dist/domain/ui-service/mutate/waitpoints.d.ts +2 -2
  491. package/dist/domain/ui-service/mutate/waitpoints.js +0 -3
  492. package/dist/domain/ui-service/plugins-shared.d.ts +11 -8
  493. package/dist/domain/ui-service/plugins-shared.js +55 -29
  494. package/dist/domain/ui-service/query/approvals.d.ts +2 -2
  495. package/dist/domain/ui-service/query/auth.d.ts +3 -3
  496. package/dist/domain/ui-service/query/boards.d.ts +14 -0
  497. package/dist/domain/ui-service/query/{commissions.js → boards.js} +39 -26
  498. package/dist/domain/ui-service/query/config.d.ts +6 -5
  499. package/dist/domain/ui-service/query/config.js +34 -51
  500. package/dist/domain/ui-service/query/cost.d.ts +2 -2
  501. package/dist/domain/ui-service/query/custom-providers.d.ts +2 -2
  502. package/dist/domain/ui-service/query/environments.d.ts +3 -3
  503. package/dist/domain/ui-service/query/environments.js +2 -1
  504. package/dist/domain/ui-service/query/executions.d.ts +3 -3
  505. package/dist/domain/ui-service/query/executions.js +0 -14
  506. package/dist/domain/ui-service/query/hooks.d.ts +5 -3
  507. package/dist/domain/ui-service/query/hooks.js +19 -22
  508. package/dist/domain/ui-service/query/issues.d.ts +2 -2
  509. package/dist/domain/ui-service/query/machine-detail.d.ts +2 -2
  510. package/dist/domain/ui-service/query/machine-detail.js +6 -24
  511. package/dist/domain/ui-service/query/machines.d.ts +2 -2
  512. package/dist/domain/ui-service/query/machines.js +0 -10
  513. package/dist/domain/ui-service/query/memory.d.ts +3 -3
  514. package/dist/domain/ui-service/query/memory.js +5 -4
  515. package/dist/domain/ui-service/query/models.d.ts +2 -2
  516. package/dist/domain/ui-service/query/models.js +2 -2
  517. package/dist/domain/ui-service/query/notes.d.ts +2 -2
  518. package/dist/domain/ui-service/query/plugin-source.d.ts +3 -3
  519. package/dist/domain/ui-service/query/plugin-source.js +2 -2
  520. package/dist/domain/ui-service/query/plugins.d.ts +2 -2
  521. package/dist/domain/ui-service/query/plugins.js +2 -2
  522. package/dist/domain/ui-service/query/schedules.d.ts +2 -2
  523. package/dist/domain/ui-service/query/schedules.js +1 -2
  524. package/dist/domain/ui-service/query/sessions.d.ts +6 -6
  525. package/dist/domain/ui-service/query/sessions.js +41 -52
  526. package/dist/domain/ui-service/query/skills.d.ts +5 -2
  527. package/dist/domain/ui-service/query/skills.js +14 -4
  528. package/dist/domain/ui-service/query/system.d.ts +6 -7
  529. package/dist/domain/ui-service/query/system.js +6 -33
  530. package/dist/domain/ui-service/query/usage-sharing.d.ts +4 -0
  531. package/dist/domain/ui-service/query/usage-sharing.js +5 -0
  532. package/dist/domain/ui-service/query/waitpoints.d.ts +4 -24
  533. package/dist/domain/ui-service/query/waitpoints.js +7 -80
  534. package/dist/domain/ui-service/query-input-schemas.d.ts +8 -10
  535. package/dist/domain/ui-service/query-input-schemas.js +13 -6
  536. package/dist/domain/ui-service/types.d.ts +228 -944
  537. package/dist/domain/ui-service/ui-service.d.ts +507 -1
  538. package/dist/domain/ui-service/ui-service.js +35 -31
  539. package/dist/domain/waitpoints/notices.d.ts +9 -5
  540. package/dist/domain/waitpoints/notices.js +49 -34
  541. package/dist/domain/waitpoints/service.d.ts +23 -7
  542. package/dist/domain/waitpoints/service.js +88 -50
  543. package/dist/domain/waitpoints/view.d.ts +29 -0
  544. package/dist/domain/waitpoints/view.js +97 -0
  545. package/dist/entry/admin-channel-hot-reload.js +5 -6
  546. package/dist/entry/app.js +92 -317
  547. package/dist/entry/auth-login-cli.js +1 -2
  548. package/dist/entry/cli-help.d.ts +2 -0
  549. package/dist/entry/cli-help.js +73 -5
  550. package/dist/entry/cli.js +89 -185
  551. package/dist/entry/daemon.d.ts +9 -0
  552. package/dist/entry/daemon.js +17 -19
  553. package/dist/entry/feishu-login.d.ts +1 -0
  554. package/dist/entry/feishu-login.js +3 -3
  555. package/dist/entry/hook-cli.d.ts +4 -2
  556. package/dist/entry/hook-cli.js +8 -17
  557. package/dist/entry/init-auth.js +1 -1
  558. package/dist/entry/init-git.d.ts +6 -0
  559. package/dist/entry/init-git.js +36 -0
  560. package/dist/entry/init-local-client.d.ts +11 -0
  561. package/dist/entry/init-local-client.js +34 -0
  562. package/dist/entry/init.d.ts +24 -28
  563. package/dist/entry/init.js +154 -459
  564. package/dist/entry/local-ui.js +10 -7
  565. package/dist/entry/memory-cli.d.ts +3 -0
  566. package/dist/entry/memory-cli.js +79 -0
  567. package/dist/entry/schedule-cli.d.ts +10 -0
  568. package/dist/entry/schedule-cli.js +166 -0
  569. package/dist/entry/shutdown.d.ts +32 -0
  570. package/dist/entry/shutdown.js +74 -0
  571. package/dist/entry/signal-cli.js +4 -3
  572. package/dist/entry/start-ui-http.js +10 -261
  573. package/dist/entry/ui-service-wiring.d.ts +12 -0
  574. package/dist/entry/ui-service-wiring.js +142 -0
  575. package/dist/events/event-types.d.ts +15 -23
  576. package/dist/orchestration/agent-decision-send.d.ts +2 -1
  577. package/dist/orchestration/agent-decision-send.js +7 -6
  578. package/dist/orchestration/agent-file-send.d.ts +0 -2
  579. package/dist/orchestration/agent-file-send.js +2 -17
  580. package/dist/orchestration/agent-runner.d.ts +0 -6
  581. package/dist/orchestration/agent-runner.js +68 -99
  582. package/dist/orchestration/agent-view-send.js +2 -1
  583. package/dist/orchestration/attachments-store.js +4 -4
  584. package/dist/orchestration/benchmark-session-webhook.js +14 -2
  585. package/dist/orchestration/board-webhook.d.ts +7 -0
  586. package/dist/orchestration/board-webhook.js +38 -0
  587. package/dist/orchestration/busy-tracker.d.ts +3 -0
  588. package/dist/orchestration/busy-tracker.js +12 -5
  589. package/dist/orchestration/conversation-request.d.ts +65 -69
  590. package/dist/orchestration/conversation-request.js +130 -171
  591. package/dist/orchestration/edit-retry.d.ts +7 -6
  592. package/dist/orchestration/edit-retry.js +53 -63
  593. package/dist/orchestration/injection-ledger.d.ts +56 -0
  594. package/dist/orchestration/injection-ledger.js +270 -0
  595. package/dist/orchestration/interactions/ask-user-resume.js +33 -50
  596. package/dist/orchestration/interactions/interaction-handlers.js +11 -10
  597. package/dist/orchestration/mid-turn-inject.d.ts +4 -4
  598. package/dist/orchestration/mid-turn-inject.js +3 -4
  599. package/dist/orchestration/outputs-store.d.ts +0 -9
  600. package/dist/orchestration/outputs-store.js +1 -57
  601. package/dist/orchestration/pending-injection-recovery.d.ts +2 -2
  602. package/dist/orchestration/pending-injection-recovery.js +1 -2
  603. package/dist/orchestration/pi-background-subagent.js +3 -1
  604. package/dist/orchestration/resume-target-sink.d.ts +3 -3
  605. package/dist/orchestration/resume-target-sink.js +6 -4
  606. package/dist/orchestration/routing/commands/cancel.d.ts +4 -1
  607. package/dist/orchestration/routing/commands/cancel.js +14 -11
  608. package/dist/orchestration/routing/commands/index.d.ts +5 -1
  609. package/dist/orchestration/routing/commands/index.js +5 -5
  610. package/dist/orchestration/routing/commands/login-notice.d.ts +2 -0
  611. package/dist/orchestration/routing/commands/login-notice.js +10 -19
  612. package/dist/orchestration/routing/commands/login.js +4 -4
  613. package/dist/orchestration/routing/commands/mode.d.ts +5 -40
  614. package/dist/orchestration/routing/commands/mode.js +112 -272
  615. package/dist/orchestration/routing/commands/restart.d.ts +3 -7
  616. package/dist/orchestration/routing/commands/restart.js +6 -21
  617. package/dist/orchestration/routing/commands/schedule.d.ts +3 -1
  618. package/dist/orchestration/routing/commands/schedule.js +174 -100
  619. package/dist/orchestration/routing/commands/session.d.ts +11 -0
  620. package/dist/orchestration/routing/commands/session.js +42 -21
  621. package/dist/orchestration/routing/commands/status.js +1 -1
  622. package/dist/orchestration/routing/commands/usage-format.d.ts +5 -0
  623. package/dist/orchestration/routing/commands/usage-format.js +104 -0
  624. package/dist/orchestration/routing/commands/usage-reset.d.ts +20 -0
  625. package/dist/orchestration/routing/commands/usage-reset.js +123 -0
  626. package/dist/orchestration/routing/commands/usage.d.ts +2 -2
  627. package/dist/orchestration/routing/commands/usage.js +17 -101
  628. package/dist/orchestration/routing/edit-handler.d.ts +0 -1
  629. package/dist/orchestration/routing/edit-handler.js +4 -5
  630. package/dist/orchestration/routing/message-router.js +2 -4
  631. package/dist/orchestration/routing/webhook.d.ts +7 -1
  632. package/dist/orchestration/routing/webhook.js +304 -503
  633. package/dist/orchestration/session-compact.d.ts +7 -18
  634. package/dist/orchestration/session-compact.js +24 -14
  635. package/dist/orchestration/session-events.d.ts +17 -7
  636. package/dist/orchestration/session-events.js +6 -4
  637. package/dist/{core → orchestration}/session-retention-liveness.d.ts +3 -3
  638. package/dist/orchestration/session-rewind.d.ts +1 -1
  639. package/dist/orchestration/session-rewind.js +1 -1
  640. package/dist/orchestration/status-helpers.d.ts +1 -5
  641. package/dist/orchestration/status-helpers.js +3 -20
  642. package/dist/orchestration/subagent-attribution.js +0 -1
  643. package/dist/orchestration/subagent-webhook.js +9 -34
  644. package/dist/orchestration/team-delivery.d.ts +22 -5
  645. package/dist/orchestration/team-delivery.js +88 -28
  646. package/dist/orchestration/team-inbox.d.ts +18 -0
  647. package/dist/orchestration/team-inbox.js +49 -0
  648. package/dist/orchestration/team-state.d.ts +32 -6
  649. package/dist/orchestration/team-state.js +88 -15
  650. package/dist/orchestration/team-webhook.d.ts +21 -12
  651. package/dist/orchestration/team-webhook.js +63 -65
  652. package/dist/orchestration/transcript-sink.d.ts +6 -102
  653. package/dist/orchestration/transcript-sink.js +61 -317
  654. package/dist/orchestration/turn/background-hold.d.ts +15 -9
  655. package/dist/orchestration/turn/background-hold.js +39 -53
  656. package/dist/orchestration/turn/hold-render-platform.d.ts +5 -11
  657. package/dist/orchestration/turn/hold-render-platform.js +16 -51
  658. package/dist/orchestration/turn/hold-render-web.d.ts +3 -18
  659. package/dist/orchestration/turn/hold-render-web.js +2 -19
  660. package/dist/orchestration/turn/terminal.d.ts +12 -8
  661. package/dist/orchestration/turn/terminal.js +46 -44
  662. package/dist/orchestration/turn/turn-prep.d.ts +4 -13
  663. package/dist/orchestration/turn/turn-prep.js +13 -2
  664. package/dist/orchestration/turn/turn-tracking.d.ts +3 -3
  665. package/dist/orchestration/turn/turn-tracking.js +11 -8
  666. package/dist/orchestration/turn/turn.d.ts +1 -7
  667. package/dist/orchestration/turn/turn.js +49 -117
  668. package/dist/orchestration/turn-notify.d.ts +0 -1
  669. package/dist/orchestration/turn-notify.js +2 -2
  670. package/dist/orchestration/waitpoint-ingress.d.ts +10 -5
  671. package/dist/orchestration/waitpoint-ingress.js +47 -23
  672. package/dist/orchestration/waitpoint-notifier.d.ts +11 -0
  673. package/dist/orchestration/waitpoint-notifier.js +40 -12
  674. package/dist/orchestration/waitpoint-remote-drain.js +22 -30
  675. package/dist/orchestration/waitpoint-sweep.d.ts +6 -4
  676. package/dist/orchestration/waitpoint-sweep.js +13 -9
  677. package/dist/platform/adapter.d.ts +4 -0
  678. package/dist/platform/adapters/composite-adapter.d.ts +7 -6
  679. package/dist/platform/adapters/composite-adapter.js +16 -34
  680. package/dist/platform/adapters/feishu.d.ts +1 -0
  681. package/dist/platform/adapters/feishu.js +1 -0
  682. package/dist/platform/adapters/index.js +1 -5
  683. package/dist/platform/adapters/slack.d.ts +1 -0
  684. package/dist/platform/adapters/slack.js +1 -0
  685. package/dist/platform/adapters/tui/ports.d.ts +0 -2
  686. package/dist/platform/adapters/tui/tui-gateway.d.ts +2 -1
  687. package/dist/platform/adapters/tui/tui-gateway.js +30 -81
  688. package/dist/platform/browser/display.d.ts +8 -5
  689. package/dist/platform/browser/display.js +63 -44
  690. package/dist/platform/browser/managed-browser.d.ts +1 -1
  691. package/dist/platform/browser/managed-browser.js +127 -41
  692. package/dist/platform/index.d.ts +2 -2
  693. package/dist/platform/index.js +1 -1
  694. package/dist/platform/output-stream-helpers.d.ts +3 -1
  695. package/dist/platform/output-stream-helpers.js +11 -0
  696. package/dist/platform/testing.d.ts +3 -1
  697. package/dist/platform/testing.js +3 -1
  698. package/dist/platform/tool-trace.d.ts +1 -1
  699. package/dist/platform/tool-trace.js +2 -2
  700. package/dist/platform/tui/protocol.d.ts +0 -1
  701. package/dist/platform/tui/protocol.js +1 -1
  702. package/dist/platform/ui-http/device-ports.d.ts +7 -2
  703. package/dist/platform/ui-http/device-ports.js +68 -40
  704. package/dist/platform/ui-http/file-routes.d.ts +23 -0
  705. package/dist/platform/ui-http/file-routes.js +224 -0
  706. package/dist/platform/ui-http/http-json.d.ts +18 -2
  707. package/dist/platform/ui-http/http-json.js +96 -20
  708. package/dist/platform/ui-http/listening-ports.d.ts +13 -9
  709. package/dist/platform/ui-http/listening-ports.js +23 -9
  710. package/dist/platform/ui-http/port-forward.js +7 -17
  711. package/dist/platform/ui-http/ui-auth-routes.d.ts +0 -7
  712. package/dist/platform/ui-http/ui-auth-routes.js +14 -35
  713. package/dist/platform/ui-http/ui-http-server.d.ts +4 -12
  714. package/dist/platform/ui-http/ui-http-server.js +53 -28
  715. package/dist/platform/ui-http/ui-ota.d.ts +4 -2
  716. package/dist/platform/ui-http/ui-ota.js +49 -3
  717. package/dist/store/board-migration.d.ts +21 -0
  718. package/dist/store/board-migration.js +217 -0
  719. package/dist/store/board-repo.d.ts +35 -0
  720. package/dist/store/{commission-repo.js → board-repo.js} +19 -19
  721. package/dist/store/builtin-overlay-migration.d.ts +11 -0
  722. package/dist/store/builtin-overlay-migration.js +308 -0
  723. package/dist/store/claude-transcript-migration.d.ts +32 -0
  724. package/dist/store/claude-transcript-migration.js +119 -0
  725. package/dist/store/conversation-history-reader.js +12 -0
  726. package/dist/store/conversation-history-repo.d.ts +25 -2
  727. package/dist/store/conversation-history-repo.js +12 -1
  728. package/dist/store/conversation-ledger-repo.d.ts +6 -11
  729. package/dist/store/conversation-ledger-repo.js +4 -11
  730. package/dist/store/cost-repo.js +2 -1
  731. package/dist/store/execution-repo.d.ts +0 -1
  732. package/dist/store/execution-repo.js +12 -3
  733. package/dist/store/hook-registry.d.ts +33 -9
  734. package/dist/store/hook-registry.js +69 -34
  735. package/dist/store/hook-writer.d.ts +8 -12
  736. package/dist/store/hook-writer.js +40 -35
  737. package/dist/store/models-repo.d.ts +18 -0
  738. package/dist/store/models-repo.js +74 -0
  739. package/dist/store/pending-injection-repo.d.ts +2 -2
  740. package/dist/store/pending-injection-repo.js +6 -1
  741. package/dist/store/provider-state-repo.d.ts +3 -3
  742. package/dist/store/retention-candidate-repo.d.ts +1 -1
  743. package/dist/store/retire-profiles-migration.d.ts +28 -0
  744. package/dist/store/retire-profiles-migration.js +335 -0
  745. package/dist/store/schedule-repo.d.ts +7 -15
  746. package/dist/store/schedule-repo.js +9 -18
  747. package/dist/store/session-registry-import.js +4 -4
  748. package/dist/store/session-registry-journal.d.ts +21 -29
  749. package/dist/store/session-registry-journal.js +87 -58
  750. package/dist/store/session-registry-repo.d.ts +26 -39
  751. package/dist/store/session-registry-repo.js +60 -107
  752. package/dist/store/session-totals-repo.d.ts +1 -1
  753. package/dist/store/team-inbox-repo.d.ts +34 -0
  754. package/dist/store/team-inbox-repo.js +72 -0
  755. package/dist/store/version-migrations.d.ts +5 -6
  756. package/dist/store/version-migrations.js +67 -35
  757. package/dist/store/waitpoint-repo.d.ts +13 -5
  758. package/dist/store/waitpoint-repo.js +5 -0
  759. package/dist/tui/App.d.ts +2 -2
  760. package/dist/tui/App.js +12 -8
  761. package/dist/tui/components/SessionPicker.d.ts +0 -1
  762. package/dist/tui/components/SessionPicker.js +2 -1
  763. package/dist/tui/index.js +3 -4
  764. package/dist/tui/logic.d.ts +0 -1
  765. package/dist/tui/logic.js +5 -10
  766. package/dist/tui/slash-commands.js +2 -2
  767. package/dist/tui/turn-status.js +1 -1
  768. package/package.json +5 -5
  769. package/web/dist/assets/index-Cgx3gdHV.css +1 -0
  770. package/web/dist/assets/index-CpZWBVHr.js +494 -0
  771. package/web/dist/assets/{index-CDjsmgsy.js → index-DaViXAg-.js} +1 -1
  772. package/web/dist/assets/pdf-worker-Hp15W1QJ.js +57 -0
  773. package/web/dist/assets/pdf.worker.min-DnhTvCwe.js +55 -0
  774. package/web/dist/index.html +2 -2
  775. package/web/dist/theme.css +0 -8
  776. package/defaults/plugins/cortex-commission/.claude-plugin/plugin.json +0 -5
  777. package/defaults/plugins/cortex-commission/plugin.json +0 -6
  778. package/defaults/plugins/cortex-commission/skills/commission/SKILL.md +0 -62
  779. package/defaults/plugins/cortex-feishu/.claude-plugin/plugin.json +0 -5
  780. package/defaults/plugins/cortex-system/.claude-plugin/plugin.json +0 -5
  781. package/dist/agent-adapter/claude/tmux-control.d.ts +0 -31
  782. package/dist/agent-adapter/claude/tmux-control.js +0 -46
  783. package/dist/agent-adapter/mcp-private-dir.d.ts +0 -1
  784. package/dist/agent-adapter/mcp-private-dir.js +0 -24
  785. package/dist/core/profile-generator.d.ts +0 -70
  786. package/dist/core/profile-generator.js +0 -210
  787. package/dist/domain/agents/environments/slot-config.d.ts +0 -14
  788. package/dist/domain/agents/environments/slot-config.js +0 -78
  789. package/dist/domain/agents/profile-manager.d.ts +0 -120
  790. package/dist/domain/agents/profile-manager.js +0 -303
  791. package/dist/domain/agents/profile-switch.d.ts +0 -53
  792. package/dist/domain/agents/profile-switch.js +0 -66
  793. package/dist/domain/commissions/commission-context.d.ts +0 -45
  794. package/dist/domain/commissions/commission-context.js +0 -45
  795. package/dist/domain/commissions/commission-draft.d.ts +0 -88
  796. package/dist/domain/commissions/commission-draft.js +0 -115
  797. package/dist/domain/commissions/commission-finalize.d.ts +0 -51
  798. package/dist/domain/commissions/commission-finalize.js +0 -104
  799. package/dist/domain/commissions/commission-paths.d.ts +0 -10
  800. package/dist/domain/commissions/commission-paths.js +0 -32
  801. package/dist/domain/commissions/decision-projection.js +0 -43
  802. package/dist/domain/mcp/tools/commission-tools.d.ts +0 -31
  803. package/dist/domain/mcp/tools/commission-tools.js +0 -234
  804. package/dist/domain/mcp/tools/schedule.d.ts +0 -9
  805. package/dist/domain/mcp/tools/schedule.js +0 -202
  806. package/dist/domain/memory/skill-scanner.d.ts +0 -6
  807. package/dist/domain/memory/skill-scanner.js +0 -116
  808. package/dist/domain/scheduling/jobs/memory-index-regen.d.ts +0 -2
  809. package/dist/domain/scheduling/jobs/memory-index-regen.js +0 -17
  810. package/dist/domain/scheduling/schedule-cli.d.ts +0 -13
  811. package/dist/domain/scheduling/schedule-cli.js +0 -260
  812. package/dist/domain/scheduling/schedule-command.d.ts +0 -4
  813. package/dist/domain/scheduling/schedule-command.js +0 -243
  814. package/dist/domain/ui-service/mutate/commissions.d.ts +0 -4
  815. package/dist/domain/ui-service/mutate/commissions.js +0 -26
  816. package/dist/domain/ui-service/mutate/profiles.d.ts +0 -36
  817. package/dist/domain/ui-service/mutate/profiles.js +0 -153
  818. package/dist/domain/ui-service/query/commissions.d.ts +0 -12
  819. package/dist/hooks/agents-md-injector.mjs +0 -392
  820. package/dist/hooks/cortex-hook-api.mjs +0 -78
  821. package/dist/hooks/memory-ref-tracker.mjs +0 -152
  822. package/dist/hooks/new-session-hook.mjs +0 -77
  823. package/dist/hooks/rules-loader.mjs +0 -204
  824. package/dist/hooks/session-activity-tracker.mjs +0 -142
  825. package/dist/hooks/status-md-guard.mjs +0 -182
  826. package/dist/platform/adapters/tui/tui-conduit-state.d.ts +0 -8
  827. package/dist/platform/adapters/tui/tui-conduit-state.js +0 -10
  828. package/dist/platform/ui-http/browser-status.d.ts +0 -17
  829. package/dist/platform/ui-http/browser-status.js +0 -38
  830. package/dist/store/commission-repo.d.ts +0 -34
  831. package/dist/store/hook-sync.d.ts +0 -14
  832. package/dist/store/hook-sync.js +0 -180
  833. package/dist/store/plugin-sync.d.ts +0 -30
  834. package/dist/store/plugin-sync.js +0 -151
  835. package/dist/store/profile-repo.d.ts +0 -18
  836. package/dist/store/profile-repo.js +0 -86
  837. package/web/dist/assets/index-BU_kY1rV.js +0 -449
  838. package/web/dist/assets/index-DzPDbcY1.css +0 -1
  839. package/web/dist/assets/pdf-worker-DIEXcFxP.js +0 -55
  840. package/web/dist/assets/pdf.worker.min-DqNZU1-t.js +0 -53
  841. /package/dist/{core/types → domain/benchmark}/benchmark-types.js +0 -0
  842. /package/dist/{core → domain/benchmark}/production-benchmark-evidence.js +0 -0
  843. /package/dist/{core → orchestration}/session-retention-liveness.js +0 -0
@@ -0,0 +1,4859 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __cortexCreateRequire } from "node:module";
3
+ const require = __cortexCreateRequire(import.meta.url);
4
+ var __create = Object.create;
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
11
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
12
+ }) : x)(function(x) {
13
+ if (typeof require !== "undefined") return require.apply(this, arguments);
14
+ throw Error('Dynamic require of "' + x + '" is not supported');
15
+ });
16
+ var __commonJS = (cb, mod) => function __require2() {
17
+ try {
18
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
19
+ } catch (e) {
20
+ throw mod = 0, e;
21
+ }
22
+ };
23
+ var __copyProps = (to, from, except, desc) => {
24
+ if (from && typeof from === "object" || typeof from === "function") {
25
+ for (let key of __getOwnPropNames(from))
26
+ if (!__hasOwnProp.call(to, key) && key !== except)
27
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
28
+ }
29
+ return to;
30
+ };
31
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
32
+ // If the importer is in node compatibility mode or this is not an ESM
33
+ // file that has been converted to a CommonJS file using a Babel-
34
+ // compatible transform (i.e. "__esModule" has not been set), then set
35
+ // "default" to the CommonJS "module.exports" for node compatibility.
36
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
37
+ mod
38
+ ));
39
+
40
+ // node_modules/ws/lib/constants.js
41
+ var require_constants = __commonJS({
42
+ "node_modules/ws/lib/constants.js"(exports, module) {
43
+ "use strict";
44
+ var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
45
+ var hasBlob = typeof Blob !== "undefined";
46
+ if (hasBlob) BINARY_TYPES.push("blob");
47
+ module.exports = {
48
+ BINARY_TYPES,
49
+ CLOSE_TIMEOUT: 3e4,
50
+ EMPTY_BUFFER: Buffer.alloc(0),
51
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
52
+ hasBlob,
53
+ kForOnEventAttribute: /* @__PURE__ */ Symbol("kIsForOnEventAttribute"),
54
+ kListener: /* @__PURE__ */ Symbol("kListener"),
55
+ kStatusCode: /* @__PURE__ */ Symbol("status-code"),
56
+ kWebSocket: /* @__PURE__ */ Symbol("websocket"),
57
+ NOOP: () => {
58
+ }
59
+ };
60
+ }
61
+ });
62
+
63
+ // node_modules/ws/lib/buffer-util.js
64
+ var require_buffer_util = __commonJS({
65
+ "node_modules/ws/lib/buffer-util.js"(exports, module) {
66
+ "use strict";
67
+ var { EMPTY_BUFFER } = require_constants();
68
+ var FastBuffer = Buffer[Symbol.species];
69
+ function concat(list, totalLength) {
70
+ if (list.length === 0) return EMPTY_BUFFER;
71
+ if (list.length === 1) return list[0];
72
+ const target = Buffer.allocUnsafe(totalLength);
73
+ let offset = 0;
74
+ for (let i = 0; i < list.length; i++) {
75
+ const buf = list[i];
76
+ target.set(buf, offset);
77
+ offset += buf.length;
78
+ }
79
+ if (offset < totalLength) {
80
+ return new FastBuffer(target.buffer, target.byteOffset, offset);
81
+ }
82
+ return target;
83
+ }
84
+ function _mask(source, mask, output, offset, length) {
85
+ for (let i = 0; i < length; i++) {
86
+ output[offset + i] = source[i] ^ mask[i & 3];
87
+ }
88
+ }
89
+ function _unmask(buffer, mask) {
90
+ for (let i = 0; i < buffer.length; i++) {
91
+ buffer[i] ^= mask[i & 3];
92
+ }
93
+ }
94
+ function toArrayBuffer(buf) {
95
+ if (buf.length === buf.buffer.byteLength) {
96
+ return buf.buffer;
97
+ }
98
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
99
+ }
100
+ function toBuffer(data) {
101
+ toBuffer.readOnly = true;
102
+ if (Buffer.isBuffer(data)) return data;
103
+ let buf;
104
+ if (data instanceof ArrayBuffer) {
105
+ buf = new FastBuffer(data);
106
+ } else if (ArrayBuffer.isView(data)) {
107
+ buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
108
+ } else {
109
+ buf = Buffer.from(data);
110
+ toBuffer.readOnly = false;
111
+ }
112
+ return buf;
113
+ }
114
+ module.exports = {
115
+ concat,
116
+ mask: _mask,
117
+ toArrayBuffer,
118
+ toBuffer,
119
+ unmask: _unmask
120
+ };
121
+ if (!process.env.WS_NO_BUFFER_UTIL) {
122
+ try {
123
+ const bufferUtil = __require("bufferutil");
124
+ module.exports.mask = function(source, mask, output, offset, length) {
125
+ if (length < 48) _mask(source, mask, output, offset, length);
126
+ else bufferUtil.mask(source, mask, output, offset, length);
127
+ };
128
+ module.exports.unmask = function(buffer, mask) {
129
+ if (buffer.length < 32) _unmask(buffer, mask);
130
+ else bufferUtil.unmask(buffer, mask);
131
+ };
132
+ } catch (e) {
133
+ }
134
+ }
135
+ }
136
+ });
137
+
138
+ // node_modules/ws/lib/limiter.js
139
+ var require_limiter = __commonJS({
140
+ "node_modules/ws/lib/limiter.js"(exports, module) {
141
+ "use strict";
142
+ var kDone = /* @__PURE__ */ Symbol("kDone");
143
+ var kRun = /* @__PURE__ */ Symbol("kRun");
144
+ var Limiter = class {
145
+ /**
146
+ * Creates a new `Limiter`.
147
+ *
148
+ * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
149
+ * to run concurrently
150
+ */
151
+ constructor(concurrency) {
152
+ this[kDone] = () => {
153
+ this.pending--;
154
+ this[kRun]();
155
+ };
156
+ this.concurrency = concurrency || Infinity;
157
+ this.jobs = [];
158
+ this.pending = 0;
159
+ }
160
+ /**
161
+ * Adds a job to the queue.
162
+ *
163
+ * @param {Function} job The job to run
164
+ * @public
165
+ */
166
+ add(job) {
167
+ this.jobs.push(job);
168
+ this[kRun]();
169
+ }
170
+ /**
171
+ * Removes a job from the queue and runs it if possible.
172
+ *
173
+ * @private
174
+ */
175
+ [kRun]() {
176
+ if (this.pending === this.concurrency) return;
177
+ if (this.jobs.length) {
178
+ const job = this.jobs.shift();
179
+ this.pending++;
180
+ job(this[kDone]);
181
+ }
182
+ }
183
+ };
184
+ module.exports = Limiter;
185
+ }
186
+ });
187
+
188
+ // node_modules/ws/lib/permessage-deflate.js
189
+ var require_permessage_deflate = __commonJS({
190
+ "node_modules/ws/lib/permessage-deflate.js"(exports, module) {
191
+ "use strict";
192
+ var zlib = __require("zlib");
193
+ var bufferUtil = require_buffer_util();
194
+ var Limiter = require_limiter();
195
+ var { kStatusCode } = require_constants();
196
+ var FastBuffer = Buffer[Symbol.species];
197
+ var TRAILER = Buffer.from([0, 0, 255, 255]);
198
+ var kPerMessageDeflate = /* @__PURE__ */ Symbol("permessage-deflate");
199
+ var kTotalLength = /* @__PURE__ */ Symbol("total-length");
200
+ var kCallback = /* @__PURE__ */ Symbol("callback");
201
+ var kBuffers = /* @__PURE__ */ Symbol("buffers");
202
+ var kError = /* @__PURE__ */ Symbol("error");
203
+ var zlibLimiter;
204
+ var PerMessageDeflate2 = class {
205
+ /**
206
+ * Creates a PerMessageDeflate instance.
207
+ *
208
+ * @param {Object} [options] Configuration options
209
+ * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
210
+ * for, or request, a custom client window size
211
+ * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
212
+ * acknowledge disabling of client context takeover
213
+ * @param {Number} [options.concurrencyLimit=10] The number of concurrent
214
+ * calls to zlib
215
+ * @param {Boolean} [options.isServer=false] Create the instance in either
216
+ * server or client mode
217
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
218
+ * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
219
+ * use of a custom server window size
220
+ * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
221
+ * disabling of server context takeover
222
+ * @param {Number} [options.threshold=1024] Size (in bytes) below which
223
+ * messages should not be compressed if context takeover is disabled
224
+ * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
225
+ * deflate
226
+ * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
227
+ * inflate
228
+ */
229
+ constructor(options) {
230
+ this._options = options || {};
231
+ this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
232
+ this._maxPayload = this._options.maxPayload | 0;
233
+ this._isServer = !!this._options.isServer;
234
+ this._deflate = null;
235
+ this._inflate = null;
236
+ this.params = null;
237
+ if (!zlibLimiter) {
238
+ const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
239
+ zlibLimiter = new Limiter(concurrency);
240
+ }
241
+ }
242
+ /**
243
+ * @type {String}
244
+ */
245
+ static get extensionName() {
246
+ return "permessage-deflate";
247
+ }
248
+ /**
249
+ * Create an extension negotiation offer.
250
+ *
251
+ * @return {Object} Extension parameters
252
+ * @public
253
+ */
254
+ offer() {
255
+ const params = {};
256
+ if (this._options.serverNoContextTakeover) {
257
+ params.server_no_context_takeover = true;
258
+ }
259
+ if (this._options.clientNoContextTakeover) {
260
+ params.client_no_context_takeover = true;
261
+ }
262
+ if (this._options.serverMaxWindowBits) {
263
+ params.server_max_window_bits = this._options.serverMaxWindowBits;
264
+ }
265
+ if (this._options.clientMaxWindowBits) {
266
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
267
+ } else if (this._options.clientMaxWindowBits == null) {
268
+ params.client_max_window_bits = true;
269
+ }
270
+ return params;
271
+ }
272
+ /**
273
+ * Accept an extension negotiation offer/response.
274
+ *
275
+ * @param {Array} configurations The extension negotiation offers/reponse
276
+ * @return {Object} Accepted configuration
277
+ * @public
278
+ */
279
+ accept(configurations) {
280
+ configurations = this.normalizeParams(configurations);
281
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
282
+ return this.params;
283
+ }
284
+ /**
285
+ * Releases all resources used by the extension.
286
+ *
287
+ * @public
288
+ */
289
+ cleanup() {
290
+ if (this._inflate) {
291
+ this._inflate.close();
292
+ this._inflate = null;
293
+ }
294
+ if (this._deflate) {
295
+ const callback = this._deflate[kCallback];
296
+ this._deflate.close();
297
+ this._deflate = null;
298
+ if (callback) {
299
+ callback(
300
+ new Error(
301
+ "The deflate stream was closed while data was being processed"
302
+ )
303
+ );
304
+ }
305
+ }
306
+ }
307
+ /**
308
+ * Accept an extension negotiation offer.
309
+ *
310
+ * @param {Array} offers The extension negotiation offers
311
+ * @return {Object} Accepted configuration
312
+ * @private
313
+ */
314
+ acceptAsServer(offers) {
315
+ const opts = this._options;
316
+ const accepted = offers.find((params) => {
317
+ if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) {
318
+ return false;
319
+ }
320
+ return true;
321
+ });
322
+ if (!accepted) {
323
+ throw new Error("None of the extension offers can be accepted");
324
+ }
325
+ if (opts.serverNoContextTakeover) {
326
+ accepted.server_no_context_takeover = true;
327
+ }
328
+ if (opts.clientNoContextTakeover) {
329
+ accepted.client_no_context_takeover = true;
330
+ }
331
+ if (typeof opts.serverMaxWindowBits === "number") {
332
+ accepted.server_max_window_bits = opts.serverMaxWindowBits;
333
+ }
334
+ if (typeof opts.clientMaxWindowBits === "number") {
335
+ accepted.client_max_window_bits = opts.clientMaxWindowBits;
336
+ } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
337
+ delete accepted.client_max_window_bits;
338
+ }
339
+ return accepted;
340
+ }
341
+ /**
342
+ * Accept the extension negotiation response.
343
+ *
344
+ * @param {Array} response The extension negotiation response
345
+ * @return {Object} Accepted configuration
346
+ * @private
347
+ */
348
+ acceptAsClient(response) {
349
+ const params = response[0];
350
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
351
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
352
+ }
353
+ if (!params.client_max_window_bits) {
354
+ if (typeof this._options.clientMaxWindowBits === "number") {
355
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
356
+ }
357
+ } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
358
+ throw new Error(
359
+ 'Unexpected or invalid parameter "client_max_window_bits"'
360
+ );
361
+ }
362
+ return params;
363
+ }
364
+ /**
365
+ * Normalize parameters.
366
+ *
367
+ * @param {Array} configurations The extension negotiation offers/reponse
368
+ * @return {Array} The offers/response with normalized parameters
369
+ * @private
370
+ */
371
+ normalizeParams(configurations) {
372
+ configurations.forEach((params) => {
373
+ Object.keys(params).forEach((key) => {
374
+ let value = params[key];
375
+ if (value.length > 1) {
376
+ throw new Error(`Parameter "${key}" must have only a single value`);
377
+ }
378
+ value = value[0];
379
+ if (key === "client_max_window_bits") {
380
+ if (value !== true) {
381
+ const num = +value;
382
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
383
+ throw new TypeError(
384
+ `Invalid value for parameter "${key}": ${value}`
385
+ );
386
+ }
387
+ value = num;
388
+ } else if (!this._isServer) {
389
+ throw new TypeError(
390
+ `Invalid value for parameter "${key}": ${value}`
391
+ );
392
+ }
393
+ } else if (key === "server_max_window_bits") {
394
+ const num = +value;
395
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
396
+ throw new TypeError(
397
+ `Invalid value for parameter "${key}": ${value}`
398
+ );
399
+ }
400
+ value = num;
401
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
402
+ if (value !== true) {
403
+ throw new TypeError(
404
+ `Invalid value for parameter "${key}": ${value}`
405
+ );
406
+ }
407
+ } else {
408
+ throw new Error(`Unknown parameter "${key}"`);
409
+ }
410
+ params[key] = value;
411
+ });
412
+ });
413
+ return configurations;
414
+ }
415
+ /**
416
+ * Decompress data. Concurrency limited.
417
+ *
418
+ * @param {Buffer} data Compressed data
419
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
420
+ * @param {Function} callback Callback
421
+ * @public
422
+ */
423
+ decompress(data, fin, callback) {
424
+ zlibLimiter.add((done) => {
425
+ this._decompress(data, fin, (err, result) => {
426
+ done();
427
+ callback(err, result);
428
+ });
429
+ });
430
+ }
431
+ /**
432
+ * Compress data. Concurrency limited.
433
+ *
434
+ * @param {(Buffer|String)} data Data to compress
435
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
436
+ * @param {Function} callback Callback
437
+ * @public
438
+ */
439
+ compress(data, fin, callback) {
440
+ zlibLimiter.add((done) => {
441
+ this._compress(data, fin, (err, result) => {
442
+ done();
443
+ callback(err, result);
444
+ });
445
+ });
446
+ }
447
+ /**
448
+ * Decompress data.
449
+ *
450
+ * @param {Buffer} data Compressed data
451
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
452
+ * @param {Function} callback Callback
453
+ * @private
454
+ */
455
+ _decompress(data, fin, callback) {
456
+ const endpoint = this._isServer ? "client" : "server";
457
+ if (!this._inflate) {
458
+ const key = `${endpoint}_max_window_bits`;
459
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
460
+ this._inflate = zlib.createInflateRaw({
461
+ ...this._options.zlibInflateOptions,
462
+ windowBits
463
+ });
464
+ this._inflate[kPerMessageDeflate] = this;
465
+ this._inflate[kTotalLength] = 0;
466
+ this._inflate[kBuffers] = [];
467
+ this._inflate.on("error", inflateOnError);
468
+ this._inflate.on("data", inflateOnData);
469
+ }
470
+ this._inflate[kCallback] = callback;
471
+ this._inflate.write(data);
472
+ if (fin) this._inflate.write(TRAILER);
473
+ this._inflate.flush(() => {
474
+ const err = this._inflate[kError];
475
+ if (err) {
476
+ this._inflate.close();
477
+ this._inflate = null;
478
+ callback(err);
479
+ return;
480
+ }
481
+ const data2 = bufferUtil.concat(
482
+ this._inflate[kBuffers],
483
+ this._inflate[kTotalLength]
484
+ );
485
+ if (this._inflate._readableState.endEmitted) {
486
+ this._inflate.close();
487
+ this._inflate = null;
488
+ } else {
489
+ this._inflate[kTotalLength] = 0;
490
+ this._inflate[kBuffers] = [];
491
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
492
+ this._inflate.reset();
493
+ }
494
+ }
495
+ callback(null, data2);
496
+ });
497
+ }
498
+ /**
499
+ * Compress data.
500
+ *
501
+ * @param {(Buffer|String)} data Data to compress
502
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
503
+ * @param {Function} callback Callback
504
+ * @private
505
+ */
506
+ _compress(data, fin, callback) {
507
+ const endpoint = this._isServer ? "server" : "client";
508
+ if (!this._deflate) {
509
+ const key = `${endpoint}_max_window_bits`;
510
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
511
+ this._deflate = zlib.createDeflateRaw({
512
+ ...this._options.zlibDeflateOptions,
513
+ windowBits
514
+ });
515
+ this._deflate[kTotalLength] = 0;
516
+ this._deflate[kBuffers] = [];
517
+ this._deflate.on("data", deflateOnData);
518
+ }
519
+ this._deflate[kCallback] = callback;
520
+ this._deflate.write(data);
521
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
522
+ if (!this._deflate) {
523
+ return;
524
+ }
525
+ let data2 = bufferUtil.concat(
526
+ this._deflate[kBuffers],
527
+ this._deflate[kTotalLength]
528
+ );
529
+ if (fin) {
530
+ data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
531
+ }
532
+ this._deflate[kCallback] = null;
533
+ this._deflate[kTotalLength] = 0;
534
+ this._deflate[kBuffers] = [];
535
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
536
+ this._deflate.reset();
537
+ }
538
+ callback(null, data2);
539
+ });
540
+ }
541
+ };
542
+ module.exports = PerMessageDeflate2;
543
+ function deflateOnData(chunk) {
544
+ this[kBuffers].push(chunk);
545
+ this[kTotalLength] += chunk.length;
546
+ }
547
+ function inflateOnData(chunk) {
548
+ this[kTotalLength] += chunk.length;
549
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
550
+ this[kBuffers].push(chunk);
551
+ return;
552
+ }
553
+ this[kError] = new RangeError("Max payload size exceeded");
554
+ this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
555
+ this[kError][kStatusCode] = 1009;
556
+ this.removeListener("data", inflateOnData);
557
+ this.reset();
558
+ }
559
+ function inflateOnError(err) {
560
+ this[kPerMessageDeflate]._inflate = null;
561
+ if (this[kError]) {
562
+ this[kCallback](this[kError]);
563
+ return;
564
+ }
565
+ err[kStatusCode] = 1007;
566
+ this[kCallback](err);
567
+ }
568
+ }
569
+ });
570
+
571
+ // node_modules/ws/lib/validation.js
572
+ var require_validation = __commonJS({
573
+ "node_modules/ws/lib/validation.js"(exports, module) {
574
+ "use strict";
575
+ var { isUtf8 } = __require("buffer");
576
+ var { hasBlob } = require_constants();
577
+ var tokenChars = [
578
+ 0,
579
+ 0,
580
+ 0,
581
+ 0,
582
+ 0,
583
+ 0,
584
+ 0,
585
+ 0,
586
+ 0,
587
+ 0,
588
+ 0,
589
+ 0,
590
+ 0,
591
+ 0,
592
+ 0,
593
+ 0,
594
+ // 0 - 15
595
+ 0,
596
+ 0,
597
+ 0,
598
+ 0,
599
+ 0,
600
+ 0,
601
+ 0,
602
+ 0,
603
+ 0,
604
+ 0,
605
+ 0,
606
+ 0,
607
+ 0,
608
+ 0,
609
+ 0,
610
+ 0,
611
+ // 16 - 31
612
+ 0,
613
+ 1,
614
+ 0,
615
+ 1,
616
+ 1,
617
+ 1,
618
+ 1,
619
+ 1,
620
+ 0,
621
+ 0,
622
+ 1,
623
+ 1,
624
+ 0,
625
+ 1,
626
+ 1,
627
+ 0,
628
+ // 32 - 47
629
+ 1,
630
+ 1,
631
+ 1,
632
+ 1,
633
+ 1,
634
+ 1,
635
+ 1,
636
+ 1,
637
+ 1,
638
+ 1,
639
+ 0,
640
+ 0,
641
+ 0,
642
+ 0,
643
+ 0,
644
+ 0,
645
+ // 48 - 63
646
+ 0,
647
+ 1,
648
+ 1,
649
+ 1,
650
+ 1,
651
+ 1,
652
+ 1,
653
+ 1,
654
+ 1,
655
+ 1,
656
+ 1,
657
+ 1,
658
+ 1,
659
+ 1,
660
+ 1,
661
+ 1,
662
+ // 64 - 79
663
+ 1,
664
+ 1,
665
+ 1,
666
+ 1,
667
+ 1,
668
+ 1,
669
+ 1,
670
+ 1,
671
+ 1,
672
+ 1,
673
+ 1,
674
+ 0,
675
+ 0,
676
+ 0,
677
+ 1,
678
+ 1,
679
+ // 80 - 95
680
+ 1,
681
+ 1,
682
+ 1,
683
+ 1,
684
+ 1,
685
+ 1,
686
+ 1,
687
+ 1,
688
+ 1,
689
+ 1,
690
+ 1,
691
+ 1,
692
+ 1,
693
+ 1,
694
+ 1,
695
+ 1,
696
+ // 96 - 111
697
+ 1,
698
+ 1,
699
+ 1,
700
+ 1,
701
+ 1,
702
+ 1,
703
+ 1,
704
+ 1,
705
+ 1,
706
+ 1,
707
+ 1,
708
+ 0,
709
+ 1,
710
+ 0,
711
+ 1,
712
+ 0
713
+ // 112 - 127
714
+ ];
715
+ function isValidStatusCode(code) {
716
+ return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
717
+ }
718
+ function _isValidUTF8(buf) {
719
+ const len = buf.length;
720
+ let i = 0;
721
+ while (i < len) {
722
+ if ((buf[i] & 128) === 0) {
723
+ i++;
724
+ } else if ((buf[i] & 224) === 192) {
725
+ if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
726
+ return false;
727
+ }
728
+ i += 2;
729
+ } else if ((buf[i] & 240) === 224) {
730
+ if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
731
+ buf[i] === 237 && (buf[i + 1] & 224) === 160) {
732
+ return false;
733
+ }
734
+ i += 3;
735
+ } else if ((buf[i] & 248) === 240) {
736
+ if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || // Overlong
737
+ buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
738
+ return false;
739
+ }
740
+ i += 4;
741
+ } else {
742
+ return false;
743
+ }
744
+ }
745
+ return true;
746
+ }
747
+ function isBlob(value) {
748
+ return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File");
749
+ }
750
+ module.exports = {
751
+ isBlob,
752
+ isValidStatusCode,
753
+ isValidUTF8: _isValidUTF8,
754
+ tokenChars
755
+ };
756
+ if (isUtf8) {
757
+ module.exports.isValidUTF8 = function(buf) {
758
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
759
+ };
760
+ } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
761
+ try {
762
+ const isValidUTF8 = __require("utf-8-validate");
763
+ module.exports.isValidUTF8 = function(buf) {
764
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
765
+ };
766
+ } catch (e) {
767
+ }
768
+ }
769
+ }
770
+ });
771
+
772
+ // node_modules/ws/lib/receiver.js
773
+ var require_receiver = __commonJS({
774
+ "node_modules/ws/lib/receiver.js"(exports, module) {
775
+ "use strict";
776
+ var { Writable } = __require("stream");
777
+ var PerMessageDeflate2 = require_permessage_deflate();
778
+ var {
779
+ BINARY_TYPES,
780
+ EMPTY_BUFFER,
781
+ kStatusCode,
782
+ kWebSocket
783
+ } = require_constants();
784
+ var { concat, toArrayBuffer, unmask } = require_buffer_util();
785
+ var { isValidStatusCode, isValidUTF8 } = require_validation();
786
+ var FastBuffer = Buffer[Symbol.species];
787
+ var GET_INFO = 0;
788
+ var GET_PAYLOAD_LENGTH_16 = 1;
789
+ var GET_PAYLOAD_LENGTH_64 = 2;
790
+ var GET_MASK = 3;
791
+ var GET_DATA = 4;
792
+ var INFLATING = 5;
793
+ var DEFER_EVENT = 6;
794
+ var Receiver2 = class extends Writable {
795
+ /**
796
+ * Creates a Receiver instance.
797
+ *
798
+ * @param {Object} [options] Options object
799
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
800
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
801
+ * multiple times in the same tick
802
+ * @param {String} [options.binaryType=nodebuffer] The type for binary data
803
+ * @param {Object} [options.extensions] An object containing the negotiated
804
+ * extensions
805
+ * @param {Boolean} [options.isServer=false] Specifies whether to operate in
806
+ * client or server mode
807
+ * @param {Number} [options.maxBufferedChunks=0] The maximum number of
808
+ * buffered data chunks
809
+ * @param {Number} [options.maxFragments=0] The maximum number of message
810
+ * fragments
811
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
812
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
813
+ * not to skip UTF-8 validation for text and close messages
814
+ */
815
+ constructor(options = {}) {
816
+ super();
817
+ this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
818
+ this._binaryType = options.binaryType || BINARY_TYPES[0];
819
+ this._extensions = options.extensions || {};
820
+ this._isServer = !!options.isServer;
821
+ this._maxBufferedChunks = options.maxBufferedChunks | 0;
822
+ this._maxFragments = options.maxFragments | 0;
823
+ this._maxPayload = options.maxPayload | 0;
824
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
825
+ this[kWebSocket] = void 0;
826
+ this._bufferedBytes = 0;
827
+ this._buffers = [];
828
+ this._compressed = false;
829
+ this._payloadLength = 0;
830
+ this._mask = void 0;
831
+ this._fragmented = 0;
832
+ this._masked = false;
833
+ this._fin = false;
834
+ this._opcode = 0;
835
+ this._totalPayloadLength = 0;
836
+ this._messageLength = 0;
837
+ this._numFragments = 0;
838
+ this._fragments = [];
839
+ this._errored = false;
840
+ this._loop = false;
841
+ this._state = GET_INFO;
842
+ }
843
+ /**
844
+ * Implements `Writable.prototype._write()`.
845
+ *
846
+ * @param {Buffer} chunk The chunk of data to write
847
+ * @param {String} encoding The character encoding of `chunk`
848
+ * @param {Function} cb Callback
849
+ * @private
850
+ */
851
+ _write(chunk, encoding, cb) {
852
+ if (this._opcode === 8 && this._state == GET_INFO) return cb();
853
+ if (this._maxBufferedChunks > 0 && this._buffers.length >= this._maxBufferedChunks) {
854
+ cb(
855
+ this.createError(
856
+ RangeError,
857
+ "Too many buffered chunks",
858
+ false,
859
+ 1008,
860
+ "WS_ERR_TOO_MANY_BUFFERED_PARTS"
861
+ )
862
+ );
863
+ return;
864
+ }
865
+ this._bufferedBytes += chunk.length;
866
+ this._buffers.push(chunk);
867
+ this.startLoop(cb);
868
+ }
869
+ /**
870
+ * Consumes `n` bytes from the buffered data.
871
+ *
872
+ * @param {Number} n The number of bytes to consume
873
+ * @return {Buffer} The consumed bytes
874
+ * @private
875
+ */
876
+ consume(n) {
877
+ this._bufferedBytes -= n;
878
+ if (n === this._buffers[0].length) return this._buffers.shift();
879
+ if (n < this._buffers[0].length) {
880
+ const buf = this._buffers[0];
881
+ this._buffers[0] = new FastBuffer(
882
+ buf.buffer,
883
+ buf.byteOffset + n,
884
+ buf.length - n
885
+ );
886
+ return new FastBuffer(buf.buffer, buf.byteOffset, n);
887
+ }
888
+ const dst = Buffer.allocUnsafe(n);
889
+ do {
890
+ const buf = this._buffers[0];
891
+ const offset = dst.length - n;
892
+ if (n >= buf.length) {
893
+ dst.set(this._buffers.shift(), offset);
894
+ } else {
895
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
896
+ this._buffers[0] = new FastBuffer(
897
+ buf.buffer,
898
+ buf.byteOffset + n,
899
+ buf.length - n
900
+ );
901
+ }
902
+ n -= buf.length;
903
+ } while (n > 0);
904
+ return dst;
905
+ }
906
+ /**
907
+ * Starts the parsing loop.
908
+ *
909
+ * @param {Function} cb Callback
910
+ * @private
911
+ */
912
+ startLoop(cb) {
913
+ this._loop = true;
914
+ do {
915
+ switch (this._state) {
916
+ case GET_INFO:
917
+ this.getInfo(cb);
918
+ break;
919
+ case GET_PAYLOAD_LENGTH_16:
920
+ this.getPayloadLength16(cb);
921
+ break;
922
+ case GET_PAYLOAD_LENGTH_64:
923
+ this.getPayloadLength64(cb);
924
+ break;
925
+ case GET_MASK:
926
+ this.getMask();
927
+ break;
928
+ case GET_DATA:
929
+ this.getData(cb);
930
+ break;
931
+ case INFLATING:
932
+ case DEFER_EVENT:
933
+ this._loop = false;
934
+ return;
935
+ }
936
+ } while (this._loop);
937
+ if (!this._errored) cb();
938
+ }
939
+ /**
940
+ * Reads the first two bytes of a frame.
941
+ *
942
+ * @param {Function} cb Callback
943
+ * @private
944
+ */
945
+ getInfo(cb) {
946
+ if (this._bufferedBytes < 2) {
947
+ this._loop = false;
948
+ return;
949
+ }
950
+ const buf = this.consume(2);
951
+ if ((buf[0] & 48) !== 0) {
952
+ const error = this.createError(
953
+ RangeError,
954
+ "RSV2 and RSV3 must be clear",
955
+ true,
956
+ 1002,
957
+ "WS_ERR_UNEXPECTED_RSV_2_3"
958
+ );
959
+ cb(error);
960
+ return;
961
+ }
962
+ const compressed = (buf[0] & 64) === 64;
963
+ if (compressed && !this._extensions[PerMessageDeflate2.extensionName]) {
964
+ const error = this.createError(
965
+ RangeError,
966
+ "RSV1 must be clear",
967
+ true,
968
+ 1002,
969
+ "WS_ERR_UNEXPECTED_RSV_1"
970
+ );
971
+ cb(error);
972
+ return;
973
+ }
974
+ this._fin = (buf[0] & 128) === 128;
975
+ this._opcode = buf[0] & 15;
976
+ this._payloadLength = buf[1] & 127;
977
+ if (this._opcode === 0) {
978
+ if (compressed) {
979
+ const error = this.createError(
980
+ RangeError,
981
+ "RSV1 must be clear",
982
+ true,
983
+ 1002,
984
+ "WS_ERR_UNEXPECTED_RSV_1"
985
+ );
986
+ cb(error);
987
+ return;
988
+ }
989
+ if (!this._fragmented) {
990
+ const error = this.createError(
991
+ RangeError,
992
+ "invalid opcode 0",
993
+ true,
994
+ 1002,
995
+ "WS_ERR_INVALID_OPCODE"
996
+ );
997
+ cb(error);
998
+ return;
999
+ }
1000
+ this._opcode = this._fragmented;
1001
+ } else if (this._opcode === 1 || this._opcode === 2) {
1002
+ if (this._fragmented) {
1003
+ const error = this.createError(
1004
+ RangeError,
1005
+ `invalid opcode ${this._opcode}`,
1006
+ true,
1007
+ 1002,
1008
+ "WS_ERR_INVALID_OPCODE"
1009
+ );
1010
+ cb(error);
1011
+ return;
1012
+ }
1013
+ this._compressed = compressed;
1014
+ } else if (this._opcode > 7 && this._opcode < 11) {
1015
+ if (!this._fin) {
1016
+ const error = this.createError(
1017
+ RangeError,
1018
+ "FIN must be set",
1019
+ true,
1020
+ 1002,
1021
+ "WS_ERR_EXPECTED_FIN"
1022
+ );
1023
+ cb(error);
1024
+ return;
1025
+ }
1026
+ if (compressed) {
1027
+ const error = this.createError(
1028
+ RangeError,
1029
+ "RSV1 must be clear",
1030
+ true,
1031
+ 1002,
1032
+ "WS_ERR_UNEXPECTED_RSV_1"
1033
+ );
1034
+ cb(error);
1035
+ return;
1036
+ }
1037
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
1038
+ const error = this.createError(
1039
+ RangeError,
1040
+ `invalid payload length ${this._payloadLength}`,
1041
+ true,
1042
+ 1002,
1043
+ "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
1044
+ );
1045
+ cb(error);
1046
+ return;
1047
+ }
1048
+ } else {
1049
+ const error = this.createError(
1050
+ RangeError,
1051
+ `invalid opcode ${this._opcode}`,
1052
+ true,
1053
+ 1002,
1054
+ "WS_ERR_INVALID_OPCODE"
1055
+ );
1056
+ cb(error);
1057
+ return;
1058
+ }
1059
+ if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
1060
+ this._masked = (buf[1] & 128) === 128;
1061
+ if (this._isServer) {
1062
+ if (!this._masked) {
1063
+ const error = this.createError(
1064
+ RangeError,
1065
+ "MASK must be set",
1066
+ true,
1067
+ 1002,
1068
+ "WS_ERR_EXPECTED_MASK"
1069
+ );
1070
+ cb(error);
1071
+ return;
1072
+ }
1073
+ } else if (this._masked) {
1074
+ const error = this.createError(
1075
+ RangeError,
1076
+ "MASK must be clear",
1077
+ true,
1078
+ 1002,
1079
+ "WS_ERR_UNEXPECTED_MASK"
1080
+ );
1081
+ cb(error);
1082
+ return;
1083
+ }
1084
+ if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
1085
+ else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
1086
+ else this.haveLength(cb);
1087
+ }
1088
+ /**
1089
+ * Gets extended payload length (7+16).
1090
+ *
1091
+ * @param {Function} cb Callback
1092
+ * @private
1093
+ */
1094
+ getPayloadLength16(cb) {
1095
+ if (this._bufferedBytes < 2) {
1096
+ this._loop = false;
1097
+ return;
1098
+ }
1099
+ this._payloadLength = this.consume(2).readUInt16BE(0);
1100
+ this.haveLength(cb);
1101
+ }
1102
+ /**
1103
+ * Gets extended payload length (7+64).
1104
+ *
1105
+ * @param {Function} cb Callback
1106
+ * @private
1107
+ */
1108
+ getPayloadLength64(cb) {
1109
+ if (this._bufferedBytes < 8) {
1110
+ this._loop = false;
1111
+ return;
1112
+ }
1113
+ const buf = this.consume(8);
1114
+ const num = buf.readUInt32BE(0);
1115
+ if (num > Math.pow(2, 53 - 32) - 1) {
1116
+ const error = this.createError(
1117
+ RangeError,
1118
+ "Unsupported WebSocket frame: payload length > 2^53 - 1",
1119
+ false,
1120
+ 1009,
1121
+ "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
1122
+ );
1123
+ cb(error);
1124
+ return;
1125
+ }
1126
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
1127
+ this.haveLength(cb);
1128
+ }
1129
+ /**
1130
+ * Payload length has been read.
1131
+ *
1132
+ * @param {Function} cb Callback
1133
+ * @private
1134
+ */
1135
+ haveLength(cb) {
1136
+ if (this._payloadLength && this._opcode < 8) {
1137
+ this._totalPayloadLength += this._payloadLength;
1138
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
1139
+ const error = this.createError(
1140
+ RangeError,
1141
+ "Max payload size exceeded",
1142
+ false,
1143
+ 1009,
1144
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1145
+ );
1146
+ cb(error);
1147
+ return;
1148
+ }
1149
+ }
1150
+ if (this._masked) this._state = GET_MASK;
1151
+ else this._state = GET_DATA;
1152
+ }
1153
+ /**
1154
+ * Reads mask bytes.
1155
+ *
1156
+ * @private
1157
+ */
1158
+ getMask() {
1159
+ if (this._bufferedBytes < 4) {
1160
+ this._loop = false;
1161
+ return;
1162
+ }
1163
+ this._mask = this.consume(4);
1164
+ this._state = GET_DATA;
1165
+ }
1166
+ /**
1167
+ * Reads data bytes.
1168
+ *
1169
+ * @param {Function} cb Callback
1170
+ * @private
1171
+ */
1172
+ getData(cb) {
1173
+ let data = EMPTY_BUFFER;
1174
+ if (this._payloadLength) {
1175
+ if (this._bufferedBytes < this._payloadLength) {
1176
+ this._loop = false;
1177
+ return;
1178
+ }
1179
+ data = this.consume(this._payloadLength);
1180
+ if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
1181
+ unmask(data, this._mask);
1182
+ }
1183
+ }
1184
+ if (this._opcode > 7) {
1185
+ this.controlMessage(data, cb);
1186
+ return;
1187
+ }
1188
+ if (this._maxFragments > 0 && ++this._numFragments > this._maxFragments) {
1189
+ const error = this.createError(
1190
+ RangeError,
1191
+ "Too many message fragments",
1192
+ false,
1193
+ 1008,
1194
+ "WS_ERR_TOO_MANY_BUFFERED_PARTS"
1195
+ );
1196
+ cb(error);
1197
+ return;
1198
+ }
1199
+ if (this._compressed) {
1200
+ this._state = INFLATING;
1201
+ this.decompress(data, cb);
1202
+ return;
1203
+ }
1204
+ if (data.length) {
1205
+ this._messageLength = this._totalPayloadLength;
1206
+ this._fragments.push(data);
1207
+ }
1208
+ this.dataMessage(cb);
1209
+ }
1210
+ /**
1211
+ * Decompresses data.
1212
+ *
1213
+ * @param {Buffer} data Compressed data
1214
+ * @param {Function} cb Callback
1215
+ * @private
1216
+ */
1217
+ decompress(data, cb) {
1218
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
1219
+ perMessageDeflate.decompress(data, this._fin, (err, buf) => {
1220
+ if (err) return cb(err);
1221
+ if (buf.length) {
1222
+ this._messageLength += buf.length;
1223
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
1224
+ const error = this.createError(
1225
+ RangeError,
1226
+ "Max payload size exceeded",
1227
+ false,
1228
+ 1009,
1229
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1230
+ );
1231
+ cb(error);
1232
+ return;
1233
+ }
1234
+ this._fragments.push(buf);
1235
+ }
1236
+ this.dataMessage(cb);
1237
+ if (this._state === GET_INFO) this.startLoop(cb);
1238
+ });
1239
+ }
1240
+ /**
1241
+ * Handles a data message.
1242
+ *
1243
+ * @param {Function} cb Callback
1244
+ * @private
1245
+ */
1246
+ dataMessage(cb) {
1247
+ if (!this._fin) {
1248
+ this._state = GET_INFO;
1249
+ return;
1250
+ }
1251
+ const messageLength = this._messageLength;
1252
+ const fragments = this._fragments;
1253
+ this._totalPayloadLength = 0;
1254
+ this._messageLength = 0;
1255
+ this._fragmented = 0;
1256
+ this._numFragments = 0;
1257
+ this._fragments = [];
1258
+ if (this._opcode === 2) {
1259
+ let data;
1260
+ if (this._binaryType === "nodebuffer") {
1261
+ data = concat(fragments, messageLength);
1262
+ } else if (this._binaryType === "arraybuffer") {
1263
+ data = toArrayBuffer(concat(fragments, messageLength));
1264
+ } else if (this._binaryType === "blob") {
1265
+ data = new Blob(fragments);
1266
+ } else {
1267
+ data = fragments;
1268
+ }
1269
+ if (this._allowSynchronousEvents) {
1270
+ this.emit("message", data, true);
1271
+ this._state = GET_INFO;
1272
+ } else {
1273
+ this._state = DEFER_EVENT;
1274
+ setImmediate(() => {
1275
+ this.emit("message", data, true);
1276
+ this._state = GET_INFO;
1277
+ this.startLoop(cb);
1278
+ });
1279
+ }
1280
+ } else {
1281
+ const buf = concat(fragments, messageLength);
1282
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1283
+ const error = this.createError(
1284
+ Error,
1285
+ "invalid UTF-8 sequence",
1286
+ true,
1287
+ 1007,
1288
+ "WS_ERR_INVALID_UTF8"
1289
+ );
1290
+ cb(error);
1291
+ return;
1292
+ }
1293
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
1294
+ this.emit("message", buf, false);
1295
+ this._state = GET_INFO;
1296
+ } else {
1297
+ this._state = DEFER_EVENT;
1298
+ setImmediate(() => {
1299
+ this.emit("message", buf, false);
1300
+ this._state = GET_INFO;
1301
+ this.startLoop(cb);
1302
+ });
1303
+ }
1304
+ }
1305
+ }
1306
+ /**
1307
+ * Handles a control message.
1308
+ *
1309
+ * @param {Buffer} data Data to handle
1310
+ * @return {(Error|RangeError|undefined)} A possible error
1311
+ * @private
1312
+ */
1313
+ controlMessage(data, cb) {
1314
+ if (this._opcode === 8) {
1315
+ if (data.length === 0) {
1316
+ this._loop = false;
1317
+ this.emit("conclude", 1005, EMPTY_BUFFER);
1318
+ this.end();
1319
+ } else {
1320
+ const code = data.readUInt16BE(0);
1321
+ if (!isValidStatusCode(code)) {
1322
+ const error = this.createError(
1323
+ RangeError,
1324
+ `invalid status code ${code}`,
1325
+ true,
1326
+ 1002,
1327
+ "WS_ERR_INVALID_CLOSE_CODE"
1328
+ );
1329
+ cb(error);
1330
+ return;
1331
+ }
1332
+ const buf = new FastBuffer(
1333
+ data.buffer,
1334
+ data.byteOffset + 2,
1335
+ data.length - 2
1336
+ );
1337
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1338
+ const error = this.createError(
1339
+ Error,
1340
+ "invalid UTF-8 sequence",
1341
+ true,
1342
+ 1007,
1343
+ "WS_ERR_INVALID_UTF8"
1344
+ );
1345
+ cb(error);
1346
+ return;
1347
+ }
1348
+ this._loop = false;
1349
+ this.emit("conclude", code, buf);
1350
+ this.end();
1351
+ }
1352
+ this._state = GET_INFO;
1353
+ return;
1354
+ }
1355
+ if (this._allowSynchronousEvents) {
1356
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1357
+ this._state = GET_INFO;
1358
+ } else {
1359
+ this._state = DEFER_EVENT;
1360
+ setImmediate(() => {
1361
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1362
+ this._state = GET_INFO;
1363
+ this.startLoop(cb);
1364
+ });
1365
+ }
1366
+ }
1367
+ /**
1368
+ * Builds an error object.
1369
+ *
1370
+ * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
1371
+ * @param {String} message The error message
1372
+ * @param {Boolean} prefix Specifies whether or not to add a default prefix to
1373
+ * `message`
1374
+ * @param {Number} statusCode The status code
1375
+ * @param {String} errorCode The exposed error code
1376
+ * @return {(Error|RangeError)} The error
1377
+ * @private
1378
+ */
1379
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
1380
+ this._loop = false;
1381
+ this._errored = true;
1382
+ const err = new ErrorCtor(
1383
+ prefix ? `Invalid WebSocket frame: ${message}` : message
1384
+ );
1385
+ Error.captureStackTrace(err, this.createError);
1386
+ err.code = errorCode;
1387
+ err[kStatusCode] = statusCode;
1388
+ return err;
1389
+ }
1390
+ };
1391
+ module.exports = Receiver2;
1392
+ }
1393
+ });
1394
+
1395
+ // node_modules/ws/lib/sender.js
1396
+ var require_sender = __commonJS({
1397
+ "node_modules/ws/lib/sender.js"(exports, module) {
1398
+ "use strict";
1399
+ var { Duplex } = __require("stream");
1400
+ var { randomFillSync } = __require("crypto");
1401
+ var {
1402
+ types: { isUint8Array }
1403
+ } = __require("util");
1404
+ var PerMessageDeflate2 = require_permessage_deflate();
1405
+ var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
1406
+ var { isBlob, isValidStatusCode } = require_validation();
1407
+ var { mask: applyMask, toBuffer } = require_buffer_util();
1408
+ var kByteLength = /* @__PURE__ */ Symbol("kByteLength");
1409
+ var maskBuffer = Buffer.alloc(4);
1410
+ var RANDOM_POOL_SIZE = 8 * 1024;
1411
+ var randomPool;
1412
+ var randomPoolPointer = RANDOM_POOL_SIZE;
1413
+ var DEFAULT = 0;
1414
+ var DEFLATING = 1;
1415
+ var GET_BLOB_DATA = 2;
1416
+ var Sender2 = class _Sender {
1417
+ /**
1418
+ * Creates a Sender instance.
1419
+ *
1420
+ * @param {Duplex} socket The connection socket
1421
+ * @param {Object} [extensions] An object containing the negotiated extensions
1422
+ * @param {Function} [generateMask] The function used to generate the masking
1423
+ * key
1424
+ */
1425
+ constructor(socket, extensions, generateMask) {
1426
+ this._extensions = extensions || {};
1427
+ if (generateMask) {
1428
+ this._generateMask = generateMask;
1429
+ this._maskBuffer = Buffer.alloc(4);
1430
+ }
1431
+ this._socket = socket;
1432
+ this._firstFragment = true;
1433
+ this._compress = false;
1434
+ this._bufferedBytes = 0;
1435
+ this._queue = [];
1436
+ this._state = DEFAULT;
1437
+ this.onerror = NOOP;
1438
+ this[kWebSocket] = void 0;
1439
+ }
1440
+ /**
1441
+ * Frames a piece of data according to the HyBi WebSocket protocol.
1442
+ *
1443
+ * @param {(Buffer|String)} data The data to frame
1444
+ * @param {Object} options Options object
1445
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1446
+ * FIN bit
1447
+ * @param {Function} [options.generateMask] The function used to generate the
1448
+ * masking key
1449
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1450
+ * `data`
1451
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1452
+ * key
1453
+ * @param {Number} options.opcode The opcode
1454
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1455
+ * modified
1456
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1457
+ * RSV1 bit
1458
+ * @return {(Buffer|String)[]} The framed data
1459
+ * @public
1460
+ */
1461
+ static frame(data, options) {
1462
+ let mask;
1463
+ let merge = false;
1464
+ let offset = 2;
1465
+ let skipMasking = false;
1466
+ if (options.mask) {
1467
+ mask = options.maskBuffer || maskBuffer;
1468
+ if (options.generateMask) {
1469
+ options.generateMask(mask);
1470
+ } else {
1471
+ if (randomPoolPointer === RANDOM_POOL_SIZE) {
1472
+ if (randomPool === void 0) {
1473
+ randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
1474
+ }
1475
+ randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
1476
+ randomPoolPointer = 0;
1477
+ }
1478
+ mask[0] = randomPool[randomPoolPointer++];
1479
+ mask[1] = randomPool[randomPoolPointer++];
1480
+ mask[2] = randomPool[randomPoolPointer++];
1481
+ mask[3] = randomPool[randomPoolPointer++];
1482
+ }
1483
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
1484
+ offset = 6;
1485
+ }
1486
+ let dataLength;
1487
+ if (typeof data === "string") {
1488
+ if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
1489
+ dataLength = options[kByteLength];
1490
+ } else {
1491
+ data = Buffer.from(data);
1492
+ dataLength = data.length;
1493
+ }
1494
+ } else {
1495
+ dataLength = data.length;
1496
+ merge = options.mask && options.readOnly && !skipMasking;
1497
+ }
1498
+ let payloadLength = dataLength;
1499
+ if (dataLength >= 65536) {
1500
+ offset += 8;
1501
+ payloadLength = 127;
1502
+ } else if (dataLength > 125) {
1503
+ offset += 2;
1504
+ payloadLength = 126;
1505
+ }
1506
+ const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
1507
+ target[0] = options.fin ? options.opcode | 128 : options.opcode;
1508
+ if (options.rsv1) target[0] |= 64;
1509
+ target[1] = payloadLength;
1510
+ if (payloadLength === 126) {
1511
+ target.writeUInt16BE(dataLength, 2);
1512
+ } else if (payloadLength === 127) {
1513
+ target[2] = target[3] = 0;
1514
+ target.writeUIntBE(dataLength, 4, 6);
1515
+ }
1516
+ if (!options.mask) return [target, data];
1517
+ target[1] |= 128;
1518
+ target[offset - 4] = mask[0];
1519
+ target[offset - 3] = mask[1];
1520
+ target[offset - 2] = mask[2];
1521
+ target[offset - 1] = mask[3];
1522
+ if (skipMasking) return [target, data];
1523
+ if (merge) {
1524
+ applyMask(data, mask, target, offset, dataLength);
1525
+ return [target];
1526
+ }
1527
+ applyMask(data, mask, data, 0, dataLength);
1528
+ return [target, data];
1529
+ }
1530
+ /**
1531
+ * Sends a close message to the other peer.
1532
+ *
1533
+ * @param {Number} [code] The status code component of the body
1534
+ * @param {(String|Buffer)} [data] The message component of the body
1535
+ * @param {Boolean} [mask=false] Specifies whether or not to mask the message
1536
+ * @param {Function} [cb] Callback
1537
+ * @public
1538
+ */
1539
+ close(code, data, mask, cb) {
1540
+ let buf;
1541
+ if (code === void 0) {
1542
+ buf = EMPTY_BUFFER;
1543
+ } else if (typeof code !== "number" || !isValidStatusCode(code)) {
1544
+ throw new TypeError("First argument must be a valid error code number");
1545
+ } else if (data === void 0 || !data.length) {
1546
+ buf = Buffer.allocUnsafe(2);
1547
+ buf.writeUInt16BE(code, 0);
1548
+ } else {
1549
+ const length = Buffer.byteLength(data);
1550
+ if (length > 123) {
1551
+ throw new RangeError("The message must not be greater than 123 bytes");
1552
+ }
1553
+ buf = Buffer.allocUnsafe(2 + length);
1554
+ buf.writeUInt16BE(code, 0);
1555
+ if (typeof data === "string") {
1556
+ buf.write(data, 2);
1557
+ } else if (isUint8Array(data)) {
1558
+ buf.set(data, 2);
1559
+ } else {
1560
+ throw new TypeError("Second argument must be a string or a Uint8Array");
1561
+ }
1562
+ }
1563
+ const options = {
1564
+ [kByteLength]: buf.length,
1565
+ fin: true,
1566
+ generateMask: this._generateMask,
1567
+ mask,
1568
+ maskBuffer: this._maskBuffer,
1569
+ opcode: 8,
1570
+ readOnly: false,
1571
+ rsv1: false
1572
+ };
1573
+ if (this._state !== DEFAULT) {
1574
+ this.enqueue([this.dispatch, buf, false, options, cb]);
1575
+ } else {
1576
+ this.sendFrame(_Sender.frame(buf, options), cb);
1577
+ }
1578
+ }
1579
+ /**
1580
+ * Sends a ping message to the other peer.
1581
+ *
1582
+ * @param {*} data The message to send
1583
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1584
+ * @param {Function} [cb] Callback
1585
+ * @public
1586
+ */
1587
+ ping(data, mask, cb) {
1588
+ let byteLength;
1589
+ let readOnly;
1590
+ if (typeof data === "string") {
1591
+ byteLength = Buffer.byteLength(data);
1592
+ readOnly = false;
1593
+ } else if (isBlob(data)) {
1594
+ byteLength = data.size;
1595
+ readOnly = false;
1596
+ } else {
1597
+ data = toBuffer(data);
1598
+ byteLength = data.length;
1599
+ readOnly = toBuffer.readOnly;
1600
+ }
1601
+ if (byteLength > 125) {
1602
+ throw new RangeError("The data size must not be greater than 125 bytes");
1603
+ }
1604
+ const options = {
1605
+ [kByteLength]: byteLength,
1606
+ fin: true,
1607
+ generateMask: this._generateMask,
1608
+ mask,
1609
+ maskBuffer: this._maskBuffer,
1610
+ opcode: 9,
1611
+ readOnly,
1612
+ rsv1: false
1613
+ };
1614
+ if (isBlob(data)) {
1615
+ if (this._state !== DEFAULT) {
1616
+ this.enqueue([this.getBlobData, data, false, options, cb]);
1617
+ } else {
1618
+ this.getBlobData(data, false, options, cb);
1619
+ }
1620
+ } else if (this._state !== DEFAULT) {
1621
+ this.enqueue([this.dispatch, data, false, options, cb]);
1622
+ } else {
1623
+ this.sendFrame(_Sender.frame(data, options), cb);
1624
+ }
1625
+ }
1626
+ /**
1627
+ * Sends a pong message to the other peer.
1628
+ *
1629
+ * @param {*} data The message to send
1630
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1631
+ * @param {Function} [cb] Callback
1632
+ * @public
1633
+ */
1634
+ pong(data, mask, cb) {
1635
+ let byteLength;
1636
+ let readOnly;
1637
+ if (typeof data === "string") {
1638
+ byteLength = Buffer.byteLength(data);
1639
+ readOnly = false;
1640
+ } else if (isBlob(data)) {
1641
+ byteLength = data.size;
1642
+ readOnly = false;
1643
+ } else {
1644
+ data = toBuffer(data);
1645
+ byteLength = data.length;
1646
+ readOnly = toBuffer.readOnly;
1647
+ }
1648
+ if (byteLength > 125) {
1649
+ throw new RangeError("The data size must not be greater than 125 bytes");
1650
+ }
1651
+ const options = {
1652
+ [kByteLength]: byteLength,
1653
+ fin: true,
1654
+ generateMask: this._generateMask,
1655
+ mask,
1656
+ maskBuffer: this._maskBuffer,
1657
+ opcode: 10,
1658
+ readOnly,
1659
+ rsv1: false
1660
+ };
1661
+ if (isBlob(data)) {
1662
+ if (this._state !== DEFAULT) {
1663
+ this.enqueue([this.getBlobData, data, false, options, cb]);
1664
+ } else {
1665
+ this.getBlobData(data, false, options, cb);
1666
+ }
1667
+ } else if (this._state !== DEFAULT) {
1668
+ this.enqueue([this.dispatch, data, false, options, cb]);
1669
+ } else {
1670
+ this.sendFrame(_Sender.frame(data, options), cb);
1671
+ }
1672
+ }
1673
+ /**
1674
+ * Sends a data message to the other peer.
1675
+ *
1676
+ * @param {*} data The message to send
1677
+ * @param {Object} options Options object
1678
+ * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
1679
+ * or text
1680
+ * @param {Boolean} [options.compress=false] Specifies whether or not to
1681
+ * compress `data`
1682
+ * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
1683
+ * last one
1684
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1685
+ * `data`
1686
+ * @param {Function} [cb] Callback
1687
+ * @public
1688
+ */
1689
+ send(data, options, cb) {
1690
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
1691
+ let opcode = options.binary ? 2 : 1;
1692
+ let rsv1 = options.compress;
1693
+ let byteLength;
1694
+ let readOnly;
1695
+ if (typeof data === "string") {
1696
+ byteLength = Buffer.byteLength(data);
1697
+ readOnly = false;
1698
+ } else if (isBlob(data)) {
1699
+ byteLength = data.size;
1700
+ readOnly = false;
1701
+ } else {
1702
+ data = toBuffer(data);
1703
+ byteLength = data.length;
1704
+ readOnly = toBuffer.readOnly;
1705
+ }
1706
+ if (this._firstFragment) {
1707
+ this._firstFragment = false;
1708
+ if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
1709
+ rsv1 = byteLength >= perMessageDeflate._threshold;
1710
+ }
1711
+ this._compress = rsv1;
1712
+ } else {
1713
+ rsv1 = false;
1714
+ opcode = 0;
1715
+ }
1716
+ if (options.fin) this._firstFragment = true;
1717
+ const opts = {
1718
+ [kByteLength]: byteLength,
1719
+ fin: options.fin,
1720
+ generateMask: this._generateMask,
1721
+ mask: options.mask,
1722
+ maskBuffer: this._maskBuffer,
1723
+ opcode,
1724
+ readOnly,
1725
+ rsv1
1726
+ };
1727
+ if (isBlob(data)) {
1728
+ if (this._state !== DEFAULT) {
1729
+ this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
1730
+ } else {
1731
+ this.getBlobData(data, this._compress, opts, cb);
1732
+ }
1733
+ } else if (this._state !== DEFAULT) {
1734
+ this.enqueue([this.dispatch, data, this._compress, opts, cb]);
1735
+ } else {
1736
+ this.dispatch(data, this._compress, opts, cb);
1737
+ }
1738
+ }
1739
+ /**
1740
+ * Gets the contents of a blob as binary data.
1741
+ *
1742
+ * @param {Blob} blob The blob
1743
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1744
+ * the data
1745
+ * @param {Object} options Options object
1746
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1747
+ * FIN bit
1748
+ * @param {Function} [options.generateMask] The function used to generate the
1749
+ * masking key
1750
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1751
+ * `data`
1752
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1753
+ * key
1754
+ * @param {Number} options.opcode The opcode
1755
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1756
+ * modified
1757
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1758
+ * RSV1 bit
1759
+ * @param {Function} [cb] Callback
1760
+ * @private
1761
+ */
1762
+ getBlobData(blob, compress, options, cb) {
1763
+ this._bufferedBytes += options[kByteLength];
1764
+ this._state = GET_BLOB_DATA;
1765
+ blob.arrayBuffer().then((arrayBuffer) => {
1766
+ if (this._socket.destroyed) {
1767
+ const err = new Error(
1768
+ "The socket was closed while the blob was being read"
1769
+ );
1770
+ process.nextTick(callCallbacks, this, err, cb);
1771
+ return;
1772
+ }
1773
+ this._bufferedBytes -= options[kByteLength];
1774
+ const data = toBuffer(arrayBuffer);
1775
+ if (!compress) {
1776
+ this._state = DEFAULT;
1777
+ this.sendFrame(_Sender.frame(data, options), cb);
1778
+ this.dequeue();
1779
+ } else {
1780
+ this.dispatch(data, compress, options, cb);
1781
+ }
1782
+ }).catch((err) => {
1783
+ process.nextTick(onError, this, err, cb);
1784
+ });
1785
+ }
1786
+ /**
1787
+ * Dispatches a message.
1788
+ *
1789
+ * @param {(Buffer|String)} data The message to send
1790
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1791
+ * `data`
1792
+ * @param {Object} options Options object
1793
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1794
+ * FIN bit
1795
+ * @param {Function} [options.generateMask] The function used to generate the
1796
+ * masking key
1797
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1798
+ * `data`
1799
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1800
+ * key
1801
+ * @param {Number} options.opcode The opcode
1802
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1803
+ * modified
1804
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1805
+ * RSV1 bit
1806
+ * @param {Function} [cb] Callback
1807
+ * @private
1808
+ */
1809
+ dispatch(data, compress, options, cb) {
1810
+ if (!compress) {
1811
+ this.sendFrame(_Sender.frame(data, options), cb);
1812
+ return;
1813
+ }
1814
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
1815
+ this._bufferedBytes += options[kByteLength];
1816
+ this._state = DEFLATING;
1817
+ perMessageDeflate.compress(data, options.fin, (_, buf) => {
1818
+ if (this._socket.destroyed) {
1819
+ const err = new Error(
1820
+ "The socket was closed while data was being compressed"
1821
+ );
1822
+ callCallbacks(this, err, cb);
1823
+ return;
1824
+ }
1825
+ this._bufferedBytes -= options[kByteLength];
1826
+ this._state = DEFAULT;
1827
+ options.readOnly = false;
1828
+ this.sendFrame(_Sender.frame(buf, options), cb);
1829
+ this.dequeue();
1830
+ });
1831
+ }
1832
+ /**
1833
+ * Executes queued send operations.
1834
+ *
1835
+ * @private
1836
+ */
1837
+ dequeue() {
1838
+ while (this._state === DEFAULT && this._queue.length) {
1839
+ const params = this._queue.shift();
1840
+ this._bufferedBytes -= params[3][kByteLength];
1841
+ Reflect.apply(params[0], this, params.slice(1));
1842
+ }
1843
+ }
1844
+ /**
1845
+ * Enqueues a send operation.
1846
+ *
1847
+ * @param {Array} params Send operation parameters.
1848
+ * @private
1849
+ */
1850
+ enqueue(params) {
1851
+ this._bufferedBytes += params[3][kByteLength];
1852
+ this._queue.push(params);
1853
+ }
1854
+ /**
1855
+ * Sends a frame.
1856
+ *
1857
+ * @param {(Buffer | String)[]} list The frame to send
1858
+ * @param {Function} [cb] Callback
1859
+ * @private
1860
+ */
1861
+ sendFrame(list, cb) {
1862
+ if (list.length === 2) {
1863
+ this._socket.cork();
1864
+ this._socket.write(list[0]);
1865
+ this._socket.write(list[1], cb);
1866
+ this._socket.uncork();
1867
+ } else {
1868
+ this._socket.write(list[0], cb);
1869
+ }
1870
+ }
1871
+ };
1872
+ module.exports = Sender2;
1873
+ function callCallbacks(sender, err, cb) {
1874
+ if (typeof cb === "function") cb(err);
1875
+ for (let i = 0; i < sender._queue.length; i++) {
1876
+ const params = sender._queue[i];
1877
+ const callback = params[params.length - 1];
1878
+ if (typeof callback === "function") callback(err);
1879
+ }
1880
+ }
1881
+ function onError(sender, err, cb) {
1882
+ callCallbacks(sender, err, cb);
1883
+ sender.onerror(err);
1884
+ }
1885
+ }
1886
+ });
1887
+
1888
+ // node_modules/ws/lib/event-target.js
1889
+ var require_event_target = __commonJS({
1890
+ "node_modules/ws/lib/event-target.js"(exports, module) {
1891
+ "use strict";
1892
+ var { kForOnEventAttribute, kListener } = require_constants();
1893
+ var kCode = /* @__PURE__ */ Symbol("kCode");
1894
+ var kData = /* @__PURE__ */ Symbol("kData");
1895
+ var kError = /* @__PURE__ */ Symbol("kError");
1896
+ var kMessage = /* @__PURE__ */ Symbol("kMessage");
1897
+ var kReason = /* @__PURE__ */ Symbol("kReason");
1898
+ var kTarget = /* @__PURE__ */ Symbol("kTarget");
1899
+ var kType = /* @__PURE__ */ Symbol("kType");
1900
+ var kWasClean = /* @__PURE__ */ Symbol("kWasClean");
1901
+ var Event = class {
1902
+ /**
1903
+ * Create a new `Event`.
1904
+ *
1905
+ * @param {String} type The name of the event
1906
+ * @throws {TypeError} If the `type` argument is not specified
1907
+ */
1908
+ constructor(type) {
1909
+ this[kTarget] = null;
1910
+ this[kType] = type;
1911
+ }
1912
+ /**
1913
+ * @type {*}
1914
+ */
1915
+ get target() {
1916
+ return this[kTarget];
1917
+ }
1918
+ /**
1919
+ * @type {String}
1920
+ */
1921
+ get type() {
1922
+ return this[kType];
1923
+ }
1924
+ };
1925
+ Object.defineProperty(Event.prototype, "target", { enumerable: true });
1926
+ Object.defineProperty(Event.prototype, "type", { enumerable: true });
1927
+ var CloseEvent = class extends Event {
1928
+ /**
1929
+ * Create a new `CloseEvent`.
1930
+ *
1931
+ * @param {String} type The name of the event
1932
+ * @param {Object} [options] A dictionary object that allows for setting
1933
+ * attributes via object members of the same name
1934
+ * @param {Number} [options.code=0] The status code explaining why the
1935
+ * connection was closed
1936
+ * @param {String} [options.reason=''] A human-readable string explaining why
1937
+ * the connection was closed
1938
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
1939
+ * connection was cleanly closed
1940
+ */
1941
+ constructor(type, options = {}) {
1942
+ super(type);
1943
+ this[kCode] = options.code === void 0 ? 0 : options.code;
1944
+ this[kReason] = options.reason === void 0 ? "" : options.reason;
1945
+ this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
1946
+ }
1947
+ /**
1948
+ * @type {Number}
1949
+ */
1950
+ get code() {
1951
+ return this[kCode];
1952
+ }
1953
+ /**
1954
+ * @type {String}
1955
+ */
1956
+ get reason() {
1957
+ return this[kReason];
1958
+ }
1959
+ /**
1960
+ * @type {Boolean}
1961
+ */
1962
+ get wasClean() {
1963
+ return this[kWasClean];
1964
+ }
1965
+ };
1966
+ Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
1967
+ Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
1968
+ Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
1969
+ var ErrorEvent = class extends Event {
1970
+ /**
1971
+ * Create a new `ErrorEvent`.
1972
+ *
1973
+ * @param {String} type The name of the event
1974
+ * @param {Object} [options] A dictionary object that allows for setting
1975
+ * attributes via object members of the same name
1976
+ * @param {*} [options.error=null] The error that generated this event
1977
+ * @param {String} [options.message=''] The error message
1978
+ */
1979
+ constructor(type, options = {}) {
1980
+ super(type);
1981
+ this[kError] = options.error === void 0 ? null : options.error;
1982
+ this[kMessage] = options.message === void 0 ? "" : options.message;
1983
+ }
1984
+ /**
1985
+ * @type {*}
1986
+ */
1987
+ get error() {
1988
+ return this[kError];
1989
+ }
1990
+ /**
1991
+ * @type {String}
1992
+ */
1993
+ get message() {
1994
+ return this[kMessage];
1995
+ }
1996
+ };
1997
+ Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
1998
+ Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
1999
+ var MessageEvent = class extends Event {
2000
+ /**
2001
+ * Create a new `MessageEvent`.
2002
+ *
2003
+ * @param {String} type The name of the event
2004
+ * @param {Object} [options] A dictionary object that allows for setting
2005
+ * attributes via object members of the same name
2006
+ * @param {*} [options.data=null] The message content
2007
+ */
2008
+ constructor(type, options = {}) {
2009
+ super(type);
2010
+ this[kData] = options.data === void 0 ? null : options.data;
2011
+ }
2012
+ /**
2013
+ * @type {*}
2014
+ */
2015
+ get data() {
2016
+ return this[kData];
2017
+ }
2018
+ };
2019
+ Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
2020
+ var EventTarget = {
2021
+ /**
2022
+ * Register an event listener.
2023
+ *
2024
+ * @param {String} type A string representing the event type to listen for
2025
+ * @param {(Function|Object)} handler The listener to add
2026
+ * @param {Object} [options] An options object specifies characteristics about
2027
+ * the event listener
2028
+ * @param {Boolean} [options.once=false] A `Boolean` indicating that the
2029
+ * listener should be invoked at most once after being added. If `true`,
2030
+ * the listener would be automatically removed when invoked.
2031
+ * @public
2032
+ */
2033
+ addEventListener(type, handler, options = {}) {
2034
+ for (const listener of this.listeners(type)) {
2035
+ if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
2036
+ return;
2037
+ }
2038
+ }
2039
+ let wrapper;
2040
+ if (type === "message") {
2041
+ wrapper = function onMessage(data, isBinary) {
2042
+ const event = new MessageEvent("message", {
2043
+ data: isBinary ? data : data.toString()
2044
+ });
2045
+ event[kTarget] = this;
2046
+ callListener(handler, this, event);
2047
+ };
2048
+ } else if (type === "close") {
2049
+ wrapper = function onClose(code, message) {
2050
+ const event = new CloseEvent("close", {
2051
+ code,
2052
+ reason: message.toString(),
2053
+ wasClean: this._closeFrameReceived && this._closeFrameSent
2054
+ });
2055
+ event[kTarget] = this;
2056
+ callListener(handler, this, event);
2057
+ };
2058
+ } else if (type === "error") {
2059
+ wrapper = function onError(error) {
2060
+ const event = new ErrorEvent("error", {
2061
+ error,
2062
+ message: error.message
2063
+ });
2064
+ event[kTarget] = this;
2065
+ callListener(handler, this, event);
2066
+ };
2067
+ } else if (type === "open") {
2068
+ wrapper = function onOpen() {
2069
+ const event = new Event("open");
2070
+ event[kTarget] = this;
2071
+ callListener(handler, this, event);
2072
+ };
2073
+ } else {
2074
+ return;
2075
+ }
2076
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
2077
+ wrapper[kListener] = handler;
2078
+ if (options.once) {
2079
+ this.once(type, wrapper);
2080
+ } else {
2081
+ this.on(type, wrapper);
2082
+ }
2083
+ },
2084
+ /**
2085
+ * Remove an event listener.
2086
+ *
2087
+ * @param {String} type A string representing the event type to remove
2088
+ * @param {(Function|Object)} handler The listener to remove
2089
+ * @public
2090
+ */
2091
+ removeEventListener(type, handler) {
2092
+ for (const listener of this.listeners(type)) {
2093
+ if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
2094
+ this.removeListener(type, listener);
2095
+ break;
2096
+ }
2097
+ }
2098
+ }
2099
+ };
2100
+ module.exports = {
2101
+ CloseEvent,
2102
+ ErrorEvent,
2103
+ Event,
2104
+ EventTarget,
2105
+ MessageEvent
2106
+ };
2107
+ function callListener(listener, thisArg, event) {
2108
+ if (typeof listener === "object" && listener.handleEvent) {
2109
+ listener.handleEvent.call(listener, event);
2110
+ } else {
2111
+ listener.call(thisArg, event);
2112
+ }
2113
+ }
2114
+ }
2115
+ });
2116
+
2117
+ // node_modules/ws/lib/extension.js
2118
+ var require_extension = __commonJS({
2119
+ "node_modules/ws/lib/extension.js"(exports, module) {
2120
+ "use strict";
2121
+ var { tokenChars } = require_validation();
2122
+ function push(dest, name, elem) {
2123
+ if (dest[name] === void 0) dest[name] = [elem];
2124
+ else dest[name].push(elem);
2125
+ }
2126
+ function parse(header) {
2127
+ const offers = /* @__PURE__ */ Object.create(null);
2128
+ let params = /* @__PURE__ */ Object.create(null);
2129
+ let mustUnescape = false;
2130
+ let isEscaping = false;
2131
+ let inQuotes = false;
2132
+ let extensionName;
2133
+ let paramName;
2134
+ let start = -1;
2135
+ let code = -1;
2136
+ let end = -1;
2137
+ let i = 0;
2138
+ for (; i < header.length; i++) {
2139
+ code = header.charCodeAt(i);
2140
+ if (extensionName === void 0) {
2141
+ if (end === -1 && tokenChars[code] === 1) {
2142
+ if (start === -1) start = i;
2143
+ } else if (i !== 0 && (code === 32 || code === 9)) {
2144
+ if (end === -1 && start !== -1) end = i;
2145
+ } else if (code === 59 || code === 44) {
2146
+ if (start === -1) {
2147
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2148
+ }
2149
+ if (end === -1) end = i;
2150
+ const name = header.slice(start, end);
2151
+ if (code === 44) {
2152
+ push(offers, name, params);
2153
+ params = /* @__PURE__ */ Object.create(null);
2154
+ } else {
2155
+ extensionName = name;
2156
+ }
2157
+ start = end = -1;
2158
+ } else {
2159
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2160
+ }
2161
+ } else if (paramName === void 0) {
2162
+ if (end === -1 && tokenChars[code] === 1) {
2163
+ if (start === -1) start = i;
2164
+ } else if (code === 32 || code === 9) {
2165
+ if (end === -1 && start !== -1) end = i;
2166
+ } else if (code === 59 || code === 44) {
2167
+ if (start === -1) {
2168
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2169
+ }
2170
+ if (end === -1) end = i;
2171
+ push(params, header.slice(start, end), true);
2172
+ if (code === 44) {
2173
+ push(offers, extensionName, params);
2174
+ params = /* @__PURE__ */ Object.create(null);
2175
+ extensionName = void 0;
2176
+ }
2177
+ start = end = -1;
2178
+ } else if (code === 61 && start !== -1 && end === -1) {
2179
+ paramName = header.slice(start, i);
2180
+ start = end = -1;
2181
+ } else {
2182
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2183
+ }
2184
+ } else {
2185
+ if (isEscaping) {
2186
+ if (tokenChars[code] !== 1) {
2187
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2188
+ }
2189
+ if (start === -1) start = i;
2190
+ else if (!mustUnescape) mustUnescape = true;
2191
+ isEscaping = false;
2192
+ } else if (inQuotes) {
2193
+ if (tokenChars[code] === 1) {
2194
+ if (start === -1) start = i;
2195
+ } else if (code === 34 && start !== -1) {
2196
+ inQuotes = false;
2197
+ end = i;
2198
+ } else if (code === 92) {
2199
+ isEscaping = true;
2200
+ } else {
2201
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2202
+ }
2203
+ } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
2204
+ inQuotes = true;
2205
+ } else if (end === -1 && tokenChars[code] === 1) {
2206
+ if (start === -1) start = i;
2207
+ } else if (start !== -1 && (code === 32 || code === 9)) {
2208
+ if (end === -1) end = i;
2209
+ } else if (code === 59 || code === 44) {
2210
+ if (start === -1) {
2211
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2212
+ }
2213
+ if (end === -1) end = i;
2214
+ let value = header.slice(start, end);
2215
+ if (mustUnescape) {
2216
+ value = value.replace(/\\/g, "");
2217
+ mustUnescape = false;
2218
+ }
2219
+ push(params, paramName, value);
2220
+ if (code === 44) {
2221
+ push(offers, extensionName, params);
2222
+ params = /* @__PURE__ */ Object.create(null);
2223
+ extensionName = void 0;
2224
+ }
2225
+ paramName = void 0;
2226
+ start = end = -1;
2227
+ } else {
2228
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2229
+ }
2230
+ }
2231
+ }
2232
+ if (start === -1 || inQuotes || code === 32 || code === 9) {
2233
+ throw new SyntaxError("Unexpected end of input");
2234
+ }
2235
+ if (end === -1) end = i;
2236
+ const token = header.slice(start, end);
2237
+ if (extensionName === void 0) {
2238
+ push(offers, token, params);
2239
+ } else {
2240
+ if (paramName === void 0) {
2241
+ push(params, token, true);
2242
+ } else if (mustUnescape) {
2243
+ push(params, paramName, token.replace(/\\/g, ""));
2244
+ } else {
2245
+ push(params, paramName, token);
2246
+ }
2247
+ push(offers, extensionName, params);
2248
+ }
2249
+ return offers;
2250
+ }
2251
+ function format(extensions) {
2252
+ return Object.keys(extensions).map((extension2) => {
2253
+ let configurations = extensions[extension2];
2254
+ if (!Array.isArray(configurations)) configurations = [configurations];
2255
+ return configurations.map((params) => {
2256
+ return [extension2].concat(
2257
+ Object.keys(params).map((k) => {
2258
+ let values = params[k];
2259
+ if (!Array.isArray(values)) values = [values];
2260
+ return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
2261
+ })
2262
+ ).join("; ");
2263
+ }).join(", ");
2264
+ }).join(", ");
2265
+ }
2266
+ module.exports = { format, parse };
2267
+ }
2268
+ });
2269
+
2270
+ // node_modules/ws/lib/websocket.js
2271
+ var require_websocket = __commonJS({
2272
+ "node_modules/ws/lib/websocket.js"(exports, module) {
2273
+ "use strict";
2274
+ var EventEmitter = __require("events");
2275
+ var https = __require("https");
2276
+ var http = __require("http");
2277
+ var net2 = __require("net");
2278
+ var tls = __require("tls");
2279
+ var { randomBytes, createHash: createHash2 } = __require("crypto");
2280
+ var { Duplex, Readable } = __require("stream");
2281
+ var { URL: URL2 } = __require("url");
2282
+ var PerMessageDeflate2 = require_permessage_deflate();
2283
+ var Receiver2 = require_receiver();
2284
+ var Sender2 = require_sender();
2285
+ var { isBlob } = require_validation();
2286
+ var {
2287
+ BINARY_TYPES,
2288
+ CLOSE_TIMEOUT,
2289
+ EMPTY_BUFFER,
2290
+ GUID,
2291
+ kForOnEventAttribute,
2292
+ kListener,
2293
+ kStatusCode,
2294
+ kWebSocket,
2295
+ NOOP
2296
+ } = require_constants();
2297
+ var {
2298
+ EventTarget: { addEventListener, removeEventListener }
2299
+ } = require_event_target();
2300
+ var { format, parse } = require_extension();
2301
+ var { toBuffer } = require_buffer_util();
2302
+ var kAborted = /* @__PURE__ */ Symbol("kAborted");
2303
+ var protocolVersions = [8, 13];
2304
+ var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
2305
+ var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
2306
+ var WebSocket2 = class _WebSocket extends EventEmitter {
2307
+ /**
2308
+ * Create a new `WebSocket`.
2309
+ *
2310
+ * @param {(String|URL)} address The URL to which to connect
2311
+ * @param {(String|String[])} [protocols] The subprotocols
2312
+ * @param {Object} [options] Connection options
2313
+ */
2314
+ constructor(address, protocols, options) {
2315
+ super();
2316
+ this._binaryType = BINARY_TYPES[0];
2317
+ this._closeCode = 1006;
2318
+ this._closeFrameReceived = false;
2319
+ this._closeFrameSent = false;
2320
+ this._closeMessage = EMPTY_BUFFER;
2321
+ this._closeTimer = null;
2322
+ this._errorEmitted = false;
2323
+ this._extensions = {};
2324
+ this._paused = false;
2325
+ this._protocol = "";
2326
+ this._readyState = _WebSocket.CONNECTING;
2327
+ this._receiver = null;
2328
+ this._sender = null;
2329
+ this._socket = null;
2330
+ if (address !== null) {
2331
+ this._bufferedAmount = 0;
2332
+ this._isServer = false;
2333
+ this._redirects = 0;
2334
+ if (protocols === void 0) {
2335
+ protocols = [];
2336
+ } else if (!Array.isArray(protocols)) {
2337
+ if (typeof protocols === "object" && protocols !== null) {
2338
+ options = protocols;
2339
+ protocols = [];
2340
+ } else {
2341
+ protocols = [protocols];
2342
+ }
2343
+ }
2344
+ initAsClient(this, address, protocols, options);
2345
+ } else {
2346
+ this._autoPong = options.autoPong;
2347
+ this._closeTimeout = options.closeTimeout;
2348
+ this._isServer = true;
2349
+ }
2350
+ }
2351
+ /**
2352
+ * For historical reasons, the custom "nodebuffer" type is used by the default
2353
+ * instead of "blob".
2354
+ *
2355
+ * @type {String}
2356
+ */
2357
+ get binaryType() {
2358
+ return this._binaryType;
2359
+ }
2360
+ set binaryType(type) {
2361
+ if (!BINARY_TYPES.includes(type)) return;
2362
+ this._binaryType = type;
2363
+ if (this._receiver) this._receiver._binaryType = type;
2364
+ }
2365
+ /**
2366
+ * @type {Number}
2367
+ */
2368
+ get bufferedAmount() {
2369
+ if (!this._socket) return this._bufferedAmount;
2370
+ return this._socket._writableState.length + this._sender._bufferedBytes;
2371
+ }
2372
+ /**
2373
+ * @type {String}
2374
+ */
2375
+ get extensions() {
2376
+ return Object.keys(this._extensions).join();
2377
+ }
2378
+ /**
2379
+ * @type {Boolean}
2380
+ */
2381
+ get isPaused() {
2382
+ return this._paused;
2383
+ }
2384
+ /**
2385
+ * @type {Function}
2386
+ */
2387
+ /* istanbul ignore next */
2388
+ get onclose() {
2389
+ return null;
2390
+ }
2391
+ /**
2392
+ * @type {Function}
2393
+ */
2394
+ /* istanbul ignore next */
2395
+ get onerror() {
2396
+ return null;
2397
+ }
2398
+ /**
2399
+ * @type {Function}
2400
+ */
2401
+ /* istanbul ignore next */
2402
+ get onopen() {
2403
+ return null;
2404
+ }
2405
+ /**
2406
+ * @type {Function}
2407
+ */
2408
+ /* istanbul ignore next */
2409
+ get onmessage() {
2410
+ return null;
2411
+ }
2412
+ /**
2413
+ * @type {String}
2414
+ */
2415
+ get protocol() {
2416
+ return this._protocol;
2417
+ }
2418
+ /**
2419
+ * @type {Number}
2420
+ */
2421
+ get readyState() {
2422
+ return this._readyState;
2423
+ }
2424
+ /**
2425
+ * @type {String}
2426
+ */
2427
+ get url() {
2428
+ return this._url;
2429
+ }
2430
+ /**
2431
+ * Set up the socket and the internal resources.
2432
+ *
2433
+ * @param {Duplex} socket The network socket between the server and client
2434
+ * @param {Buffer} head The first packet of the upgraded stream
2435
+ * @param {Object} options Options object
2436
+ * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
2437
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
2438
+ * multiple times in the same tick
2439
+ * @param {Function} [options.generateMask] The function used to generate the
2440
+ * masking key
2441
+ * @param {Number} [options.maxBufferedChunks=0] The maximum number of
2442
+ * buffered data chunks
2443
+ * @param {Number} [options.maxFragments=0] The maximum number of message
2444
+ * fragments
2445
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
2446
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
2447
+ * not to skip UTF-8 validation for text and close messages
2448
+ * @private
2449
+ */
2450
+ setSocket(socket, head, options) {
2451
+ const receiver = new Receiver2({
2452
+ allowSynchronousEvents: options.allowSynchronousEvents,
2453
+ binaryType: this.binaryType,
2454
+ extensions: this._extensions,
2455
+ isServer: this._isServer,
2456
+ maxBufferedChunks: options.maxBufferedChunks,
2457
+ maxFragments: options.maxFragments,
2458
+ maxPayload: options.maxPayload,
2459
+ skipUTF8Validation: options.skipUTF8Validation
2460
+ });
2461
+ const sender = new Sender2(socket, this._extensions, options.generateMask);
2462
+ this._receiver = receiver;
2463
+ this._sender = sender;
2464
+ this._socket = socket;
2465
+ receiver[kWebSocket] = this;
2466
+ sender[kWebSocket] = this;
2467
+ socket[kWebSocket] = this;
2468
+ receiver.on("conclude", receiverOnConclude);
2469
+ receiver.on("drain", receiverOnDrain);
2470
+ receiver.on("error", receiverOnError);
2471
+ receiver.on("message", receiverOnMessage);
2472
+ receiver.on("ping", receiverOnPing);
2473
+ receiver.on("pong", receiverOnPong);
2474
+ sender.onerror = senderOnError;
2475
+ if (socket.setTimeout) socket.setTimeout(0);
2476
+ if (socket.setNoDelay) socket.setNoDelay();
2477
+ if (head.length > 0) socket.unshift(head);
2478
+ socket.on("close", socketOnClose);
2479
+ socket.on("data", socketOnData);
2480
+ socket.on("end", socketOnEnd);
2481
+ socket.on("error", socketOnError);
2482
+ this._readyState = _WebSocket.OPEN;
2483
+ this.emit("open");
2484
+ }
2485
+ /**
2486
+ * Emit the `'close'` event.
2487
+ *
2488
+ * @private
2489
+ */
2490
+ emitClose() {
2491
+ if (!this._socket) {
2492
+ this._readyState = _WebSocket.CLOSED;
2493
+ this.emit("close", this._closeCode, this._closeMessage);
2494
+ return;
2495
+ }
2496
+ if (this._extensions[PerMessageDeflate2.extensionName]) {
2497
+ this._extensions[PerMessageDeflate2.extensionName].cleanup();
2498
+ }
2499
+ this._receiver.removeAllListeners();
2500
+ this._readyState = _WebSocket.CLOSED;
2501
+ this.emit("close", this._closeCode, this._closeMessage);
2502
+ }
2503
+ /**
2504
+ * Start a closing handshake.
2505
+ *
2506
+ * +----------+ +-----------+ +----------+
2507
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
2508
+ * | +----------+ +-----------+ +----------+ |
2509
+ * +----------+ +-----------+ |
2510
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
2511
+ * +----------+ +-----------+ |
2512
+ * | | | +---+ |
2513
+ * +------------------------+-->|fin| - - - -
2514
+ * | +---+ | +---+
2515
+ * - - - - -|fin|<---------------------+
2516
+ * +---+
2517
+ *
2518
+ * @param {Number} [code] Status code explaining why the connection is closing
2519
+ * @param {(String|Buffer)} [data] The reason why the connection is
2520
+ * closing
2521
+ * @public
2522
+ */
2523
+ close(code, data) {
2524
+ if (this.readyState === _WebSocket.CLOSED) return;
2525
+ if (this.readyState === _WebSocket.CONNECTING) {
2526
+ const msg = "WebSocket was closed before the connection was established";
2527
+ abortHandshake(this, this._req, msg);
2528
+ return;
2529
+ }
2530
+ if (this.readyState === _WebSocket.CLOSING) {
2531
+ if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
2532
+ this._socket.end();
2533
+ }
2534
+ return;
2535
+ }
2536
+ this._readyState = _WebSocket.CLOSING;
2537
+ this._sender.close(code, data, !this._isServer, (err) => {
2538
+ if (err) return;
2539
+ this._closeFrameSent = true;
2540
+ if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
2541
+ this._socket.end();
2542
+ }
2543
+ });
2544
+ setCloseTimer(this);
2545
+ }
2546
+ /**
2547
+ * Pause the socket.
2548
+ *
2549
+ * @public
2550
+ */
2551
+ pause() {
2552
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
2553
+ return;
2554
+ }
2555
+ this._paused = true;
2556
+ this._socket.pause();
2557
+ }
2558
+ /**
2559
+ * Send a ping.
2560
+ *
2561
+ * @param {*} [data] The data to send
2562
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
2563
+ * @param {Function} [cb] Callback which is executed when the ping is sent
2564
+ * @public
2565
+ */
2566
+ ping(data, mask, cb) {
2567
+ if (this.readyState === _WebSocket.CONNECTING) {
2568
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2569
+ }
2570
+ if (typeof data === "function") {
2571
+ cb = data;
2572
+ data = mask = void 0;
2573
+ } else if (typeof mask === "function") {
2574
+ cb = mask;
2575
+ mask = void 0;
2576
+ }
2577
+ if (typeof data === "number") data = data.toString();
2578
+ if (this.readyState !== _WebSocket.OPEN) {
2579
+ sendAfterClose(this, data, cb);
2580
+ return;
2581
+ }
2582
+ if (mask === void 0) mask = !this._isServer;
2583
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
2584
+ }
2585
+ /**
2586
+ * Send a pong.
2587
+ *
2588
+ * @param {*} [data] The data to send
2589
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
2590
+ * @param {Function} [cb] Callback which is executed when the pong is sent
2591
+ * @public
2592
+ */
2593
+ pong(data, mask, cb) {
2594
+ if (this.readyState === _WebSocket.CONNECTING) {
2595
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2596
+ }
2597
+ if (typeof data === "function") {
2598
+ cb = data;
2599
+ data = mask = void 0;
2600
+ } else if (typeof mask === "function") {
2601
+ cb = mask;
2602
+ mask = void 0;
2603
+ }
2604
+ if (typeof data === "number") data = data.toString();
2605
+ if (this.readyState !== _WebSocket.OPEN) {
2606
+ sendAfterClose(this, data, cb);
2607
+ return;
2608
+ }
2609
+ if (mask === void 0) mask = !this._isServer;
2610
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
2611
+ }
2612
+ /**
2613
+ * Resume the socket.
2614
+ *
2615
+ * @public
2616
+ */
2617
+ resume() {
2618
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
2619
+ return;
2620
+ }
2621
+ this._paused = false;
2622
+ if (!this._receiver._writableState.needDrain) this._socket.resume();
2623
+ }
2624
+ /**
2625
+ * Send a data message.
2626
+ *
2627
+ * @param {*} data The message to send
2628
+ * @param {Object} [options] Options object
2629
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
2630
+ * text
2631
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
2632
+ * `data`
2633
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
2634
+ * last one
2635
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
2636
+ * @param {Function} [cb] Callback which is executed when data is written out
2637
+ * @public
2638
+ */
2639
+ send(data, options, cb) {
2640
+ if (this.readyState === _WebSocket.CONNECTING) {
2641
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2642
+ }
2643
+ if (typeof options === "function") {
2644
+ cb = options;
2645
+ options = {};
2646
+ }
2647
+ if (typeof data === "number") data = data.toString();
2648
+ if (this.readyState !== _WebSocket.OPEN) {
2649
+ sendAfterClose(this, data, cb);
2650
+ return;
2651
+ }
2652
+ const opts = {
2653
+ binary: typeof data !== "string",
2654
+ mask: !this._isServer,
2655
+ compress: true,
2656
+ fin: true,
2657
+ ...options
2658
+ };
2659
+ if (!this._extensions[PerMessageDeflate2.extensionName]) {
2660
+ opts.compress = false;
2661
+ }
2662
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
2663
+ }
2664
+ /**
2665
+ * Forcibly close the connection.
2666
+ *
2667
+ * @public
2668
+ */
2669
+ terminate() {
2670
+ if (this.readyState === _WebSocket.CLOSED) return;
2671
+ if (this.readyState === _WebSocket.CONNECTING) {
2672
+ const msg = "WebSocket was closed before the connection was established";
2673
+ abortHandshake(this, this._req, msg);
2674
+ return;
2675
+ }
2676
+ if (this._socket) {
2677
+ this._readyState = _WebSocket.CLOSING;
2678
+ this._socket.destroy();
2679
+ }
2680
+ }
2681
+ };
2682
+ Object.defineProperty(WebSocket2, "CONNECTING", {
2683
+ enumerable: true,
2684
+ value: readyStates.indexOf("CONNECTING")
2685
+ });
2686
+ Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
2687
+ enumerable: true,
2688
+ value: readyStates.indexOf("CONNECTING")
2689
+ });
2690
+ Object.defineProperty(WebSocket2, "OPEN", {
2691
+ enumerable: true,
2692
+ value: readyStates.indexOf("OPEN")
2693
+ });
2694
+ Object.defineProperty(WebSocket2.prototype, "OPEN", {
2695
+ enumerable: true,
2696
+ value: readyStates.indexOf("OPEN")
2697
+ });
2698
+ Object.defineProperty(WebSocket2, "CLOSING", {
2699
+ enumerable: true,
2700
+ value: readyStates.indexOf("CLOSING")
2701
+ });
2702
+ Object.defineProperty(WebSocket2.prototype, "CLOSING", {
2703
+ enumerable: true,
2704
+ value: readyStates.indexOf("CLOSING")
2705
+ });
2706
+ Object.defineProperty(WebSocket2, "CLOSED", {
2707
+ enumerable: true,
2708
+ value: readyStates.indexOf("CLOSED")
2709
+ });
2710
+ Object.defineProperty(WebSocket2.prototype, "CLOSED", {
2711
+ enumerable: true,
2712
+ value: readyStates.indexOf("CLOSED")
2713
+ });
2714
+ [
2715
+ "binaryType",
2716
+ "bufferedAmount",
2717
+ "extensions",
2718
+ "isPaused",
2719
+ "protocol",
2720
+ "readyState",
2721
+ "url"
2722
+ ].forEach((property) => {
2723
+ Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
2724
+ });
2725
+ ["open", "error", "close", "message"].forEach((method) => {
2726
+ Object.defineProperty(WebSocket2.prototype, `on${method}`, {
2727
+ enumerable: true,
2728
+ get() {
2729
+ for (const listener of this.listeners(method)) {
2730
+ if (listener[kForOnEventAttribute]) return listener[kListener];
2731
+ }
2732
+ return null;
2733
+ },
2734
+ set(handler) {
2735
+ for (const listener of this.listeners(method)) {
2736
+ if (listener[kForOnEventAttribute]) {
2737
+ this.removeListener(method, listener);
2738
+ break;
2739
+ }
2740
+ }
2741
+ if (typeof handler !== "function") return;
2742
+ this.addEventListener(method, handler, {
2743
+ [kForOnEventAttribute]: true
2744
+ });
2745
+ }
2746
+ });
2747
+ });
2748
+ WebSocket2.prototype.addEventListener = addEventListener;
2749
+ WebSocket2.prototype.removeEventListener = removeEventListener;
2750
+ module.exports = WebSocket2;
2751
+ function initAsClient(websocket, address, protocols, options) {
2752
+ const opts = {
2753
+ allowSynchronousEvents: true,
2754
+ autoPong: true,
2755
+ closeTimeout: CLOSE_TIMEOUT,
2756
+ protocolVersion: protocolVersions[1],
2757
+ maxBufferedChunks: 256 * 1024,
2758
+ maxFragments: 16 * 1024,
2759
+ maxPayload: 100 * 1024 * 1024,
2760
+ skipUTF8Validation: false,
2761
+ perMessageDeflate: true,
2762
+ followRedirects: false,
2763
+ maxRedirects: 10,
2764
+ ...options,
2765
+ socketPath: void 0,
2766
+ hostname: void 0,
2767
+ protocol: void 0,
2768
+ timeout: void 0,
2769
+ method: "GET",
2770
+ host: void 0,
2771
+ path: void 0,
2772
+ port: void 0
2773
+ };
2774
+ websocket._autoPong = opts.autoPong;
2775
+ websocket._closeTimeout = opts.closeTimeout;
2776
+ if (!protocolVersions.includes(opts.protocolVersion)) {
2777
+ throw new RangeError(
2778
+ `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
2779
+ );
2780
+ }
2781
+ let parsedUrl;
2782
+ if (address instanceof URL2) {
2783
+ parsedUrl = address;
2784
+ } else {
2785
+ try {
2786
+ parsedUrl = new URL2(address);
2787
+ } catch {
2788
+ throw new SyntaxError(`Invalid URL: ${address}`);
2789
+ }
2790
+ }
2791
+ if (parsedUrl.protocol === "http:") {
2792
+ parsedUrl.protocol = "ws:";
2793
+ } else if (parsedUrl.protocol === "https:") {
2794
+ parsedUrl.protocol = "wss:";
2795
+ }
2796
+ websocket._url = parsedUrl.href;
2797
+ const isSecure = parsedUrl.protocol === "wss:";
2798
+ const isIpcUrl = parsedUrl.protocol === "ws+unix:";
2799
+ let invalidUrlMessage;
2800
+ if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
2801
+ invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
2802
+ } else if (isIpcUrl && !parsedUrl.pathname) {
2803
+ invalidUrlMessage = "The URL's pathname is empty";
2804
+ } else if (parsedUrl.hash) {
2805
+ invalidUrlMessage = "The URL contains a fragment identifier";
2806
+ }
2807
+ if (invalidUrlMessage) {
2808
+ const err = new SyntaxError(invalidUrlMessage);
2809
+ if (websocket._redirects === 0) {
2810
+ throw err;
2811
+ } else {
2812
+ emitErrorAndClose(websocket, err);
2813
+ return;
2814
+ }
2815
+ }
2816
+ const defaultPort = isSecure ? 443 : 80;
2817
+ const key = randomBytes(16).toString("base64");
2818
+ const request = isSecure ? https.request : http.request;
2819
+ const protocolSet = /* @__PURE__ */ new Set();
2820
+ let perMessageDeflate;
2821
+ opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
2822
+ opts.defaultPort = opts.defaultPort || defaultPort;
2823
+ opts.port = parsedUrl.port || defaultPort;
2824
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
2825
+ opts.headers = {
2826
+ ...opts.headers,
2827
+ "Sec-WebSocket-Version": opts.protocolVersion,
2828
+ "Sec-WebSocket-Key": key,
2829
+ Connection: "Upgrade",
2830
+ Upgrade: "websocket"
2831
+ };
2832
+ opts.path = parsedUrl.pathname + parsedUrl.search;
2833
+ opts.timeout = opts.handshakeTimeout;
2834
+ if (opts.perMessageDeflate) {
2835
+ perMessageDeflate = new PerMessageDeflate2({
2836
+ ...opts.perMessageDeflate,
2837
+ isServer: false,
2838
+ maxPayload: opts.maxPayload
2839
+ });
2840
+ opts.headers["Sec-WebSocket-Extensions"] = format({
2841
+ [PerMessageDeflate2.extensionName]: perMessageDeflate.offer()
2842
+ });
2843
+ }
2844
+ if (protocols.length) {
2845
+ for (const protocol of protocols) {
2846
+ if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
2847
+ throw new SyntaxError(
2848
+ "An invalid or duplicated subprotocol was specified"
2849
+ );
2850
+ }
2851
+ protocolSet.add(protocol);
2852
+ }
2853
+ opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
2854
+ }
2855
+ if (opts.origin) {
2856
+ if (opts.protocolVersion < 13) {
2857
+ opts.headers["Sec-WebSocket-Origin"] = opts.origin;
2858
+ } else {
2859
+ opts.headers.Origin = opts.origin;
2860
+ }
2861
+ }
2862
+ if (parsedUrl.username || parsedUrl.password) {
2863
+ opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
2864
+ }
2865
+ if (isIpcUrl) {
2866
+ const parts = opts.path.split(":");
2867
+ opts.socketPath = parts[0];
2868
+ opts.path = parts[1];
2869
+ }
2870
+ let req;
2871
+ if (opts.followRedirects) {
2872
+ if (websocket._redirects === 0) {
2873
+ websocket._originalIpc = isIpcUrl;
2874
+ websocket._originalSecure = isSecure;
2875
+ websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
2876
+ const headers = options && options.headers;
2877
+ options = { ...options, headers: {} };
2878
+ if (headers) {
2879
+ for (const [key2, value] of Object.entries(headers)) {
2880
+ options.headers[key2.toLowerCase()] = value;
2881
+ }
2882
+ }
2883
+ } else if (websocket.listenerCount("redirect") === 0) {
2884
+ const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
2885
+ if (!isSameHost || websocket._originalSecure && !isSecure) {
2886
+ delete opts.headers.authorization;
2887
+ delete opts.headers.cookie;
2888
+ if (!isSameHost) delete opts.headers.host;
2889
+ opts.auth = void 0;
2890
+ }
2891
+ }
2892
+ if (opts.auth && !options.headers.authorization) {
2893
+ options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
2894
+ }
2895
+ req = websocket._req = request(opts);
2896
+ if (websocket._redirects) {
2897
+ websocket.emit("redirect", websocket.url, req);
2898
+ }
2899
+ } else {
2900
+ req = websocket._req = request(opts);
2901
+ }
2902
+ if (opts.timeout) {
2903
+ req.on("timeout", () => {
2904
+ abortHandshake(websocket, req, "Opening handshake has timed out");
2905
+ });
2906
+ }
2907
+ req.on("error", (err) => {
2908
+ if (req === null || req[kAborted]) return;
2909
+ req = websocket._req = null;
2910
+ emitErrorAndClose(websocket, err);
2911
+ });
2912
+ req.on("response", (res) => {
2913
+ const location = res.headers.location;
2914
+ const statusCode = res.statusCode;
2915
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
2916
+ if (++websocket._redirects > opts.maxRedirects) {
2917
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
2918
+ return;
2919
+ }
2920
+ req.abort();
2921
+ let addr;
2922
+ try {
2923
+ addr = new URL2(location, address);
2924
+ } catch (e) {
2925
+ const err = new SyntaxError(`Invalid URL: ${location}`);
2926
+ emitErrorAndClose(websocket, err);
2927
+ return;
2928
+ }
2929
+ initAsClient(websocket, addr, protocols, options);
2930
+ } else if (!websocket.emit("unexpected-response", req, res)) {
2931
+ abortHandshake(
2932
+ websocket,
2933
+ req,
2934
+ `Unexpected server response: ${res.statusCode}`
2935
+ );
2936
+ }
2937
+ });
2938
+ req.on("upgrade", (res, socket, head) => {
2939
+ websocket.emit("upgrade", res);
2940
+ if (websocket.readyState !== WebSocket2.CONNECTING) return;
2941
+ req = websocket._req = null;
2942
+ const upgrade = res.headers.upgrade;
2943
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
2944
+ abortHandshake(websocket, socket, "Invalid Upgrade header");
2945
+ return;
2946
+ }
2947
+ const digest = createHash2("sha1").update(key + GUID).digest("base64");
2948
+ if (res.headers["sec-websocket-accept"] !== digest) {
2949
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
2950
+ return;
2951
+ }
2952
+ const serverProt = res.headers["sec-websocket-protocol"];
2953
+ let protError;
2954
+ if (serverProt !== void 0) {
2955
+ if (!protocolSet.size) {
2956
+ protError = "Server sent a subprotocol but none was requested";
2957
+ } else if (!protocolSet.has(serverProt)) {
2958
+ protError = "Server sent an invalid subprotocol";
2959
+ }
2960
+ } else if (protocolSet.size) {
2961
+ protError = "Server sent no subprotocol";
2962
+ }
2963
+ if (protError) {
2964
+ abortHandshake(websocket, socket, protError);
2965
+ return;
2966
+ }
2967
+ if (serverProt) websocket._protocol = serverProt;
2968
+ const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
2969
+ if (secWebSocketExtensions !== void 0) {
2970
+ if (!perMessageDeflate) {
2971
+ const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
2972
+ abortHandshake(websocket, socket, message);
2973
+ return;
2974
+ }
2975
+ let extensions;
2976
+ try {
2977
+ extensions = parse(secWebSocketExtensions);
2978
+ } catch (err) {
2979
+ const message = "Invalid Sec-WebSocket-Extensions header";
2980
+ abortHandshake(websocket, socket, message);
2981
+ return;
2982
+ }
2983
+ const extensionNames = Object.keys(extensions);
2984
+ if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate2.extensionName) {
2985
+ const message = "Server indicated an extension that was not requested";
2986
+ abortHandshake(websocket, socket, message);
2987
+ return;
2988
+ }
2989
+ try {
2990
+ perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName]);
2991
+ } catch (err) {
2992
+ const message = "Invalid Sec-WebSocket-Extensions header";
2993
+ abortHandshake(websocket, socket, message);
2994
+ return;
2995
+ }
2996
+ websocket._extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
2997
+ }
2998
+ websocket.setSocket(socket, head, {
2999
+ allowSynchronousEvents: opts.allowSynchronousEvents,
3000
+ generateMask: opts.generateMask,
3001
+ maxBufferedChunks: opts.maxBufferedChunks,
3002
+ maxFragments: opts.maxFragments,
3003
+ maxPayload: opts.maxPayload,
3004
+ skipUTF8Validation: opts.skipUTF8Validation
3005
+ });
3006
+ });
3007
+ if (opts.finishRequest) {
3008
+ opts.finishRequest(req, websocket);
3009
+ } else {
3010
+ req.end();
3011
+ }
3012
+ }
3013
+ function emitErrorAndClose(websocket, err) {
3014
+ websocket._readyState = WebSocket2.CLOSING;
3015
+ websocket._errorEmitted = true;
3016
+ websocket.emit("error", err);
3017
+ websocket.emitClose();
3018
+ }
3019
+ function netConnect(options) {
3020
+ options.path = options.socketPath;
3021
+ return net2.connect(options);
3022
+ }
3023
+ function tlsConnect(options) {
3024
+ options.path = void 0;
3025
+ if (!options.servername && options.servername !== "") {
3026
+ options.servername = net2.isIP(options.host) ? "" : options.host;
3027
+ }
3028
+ return tls.connect(options);
3029
+ }
3030
+ function abortHandshake(websocket, stream2, message) {
3031
+ websocket._readyState = WebSocket2.CLOSING;
3032
+ const err = new Error(message);
3033
+ Error.captureStackTrace(err, abortHandshake);
3034
+ if (stream2.setHeader) {
3035
+ stream2[kAborted] = true;
3036
+ stream2.abort();
3037
+ if (stream2.socket && !stream2.socket.destroyed) {
3038
+ stream2.socket.destroy();
3039
+ }
3040
+ process.nextTick(emitErrorAndClose, websocket, err);
3041
+ } else {
3042
+ stream2.destroy(err);
3043
+ stream2.once("error", websocket.emit.bind(websocket, "error"));
3044
+ stream2.once("close", websocket.emitClose.bind(websocket));
3045
+ }
3046
+ }
3047
+ function sendAfterClose(websocket, data, cb) {
3048
+ if (data) {
3049
+ const length = isBlob(data) ? data.size : toBuffer(data).length;
3050
+ if (websocket._socket) websocket._sender._bufferedBytes += length;
3051
+ else websocket._bufferedAmount += length;
3052
+ }
3053
+ if (cb) {
3054
+ const err = new Error(
3055
+ `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
3056
+ );
3057
+ process.nextTick(cb, err);
3058
+ }
3059
+ }
3060
+ function receiverOnConclude(code, reason) {
3061
+ const websocket = this[kWebSocket];
3062
+ websocket._closeFrameReceived = true;
3063
+ websocket._closeMessage = reason;
3064
+ websocket._closeCode = code;
3065
+ if (websocket._socket[kWebSocket] === void 0) return;
3066
+ websocket._socket.removeListener("data", socketOnData);
3067
+ process.nextTick(resume, websocket._socket);
3068
+ if (code === 1005) websocket.close();
3069
+ else websocket.close(code, reason);
3070
+ }
3071
+ function receiverOnDrain() {
3072
+ const websocket = this[kWebSocket];
3073
+ if (!websocket.isPaused) websocket._socket.resume();
3074
+ }
3075
+ function receiverOnError(err) {
3076
+ const websocket = this[kWebSocket];
3077
+ if (websocket._socket[kWebSocket] !== void 0) {
3078
+ websocket._socket.removeListener("data", socketOnData);
3079
+ process.nextTick(resume, websocket._socket);
3080
+ websocket.close(err[kStatusCode]);
3081
+ }
3082
+ if (!websocket._errorEmitted) {
3083
+ websocket._errorEmitted = true;
3084
+ websocket.emit("error", err);
3085
+ }
3086
+ }
3087
+ function receiverOnFinish() {
3088
+ this[kWebSocket].emitClose();
3089
+ }
3090
+ function receiverOnMessage(data, isBinary) {
3091
+ this[kWebSocket].emit("message", data, isBinary);
3092
+ }
3093
+ function receiverOnPing(data) {
3094
+ const websocket = this[kWebSocket];
3095
+ if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
3096
+ websocket.emit("ping", data);
3097
+ }
3098
+ function receiverOnPong(data) {
3099
+ this[kWebSocket].emit("pong", data);
3100
+ }
3101
+ function resume(stream2) {
3102
+ stream2.resume();
3103
+ }
3104
+ function senderOnError(err) {
3105
+ const websocket = this[kWebSocket];
3106
+ if (websocket.readyState === WebSocket2.CLOSED) return;
3107
+ if (websocket.readyState === WebSocket2.OPEN) {
3108
+ websocket._readyState = WebSocket2.CLOSING;
3109
+ setCloseTimer(websocket);
3110
+ }
3111
+ this._socket.end();
3112
+ if (!websocket._errorEmitted) {
3113
+ websocket._errorEmitted = true;
3114
+ websocket.emit("error", err);
3115
+ }
3116
+ }
3117
+ function setCloseTimer(websocket) {
3118
+ websocket._closeTimer = setTimeout(
3119
+ websocket._socket.destroy.bind(websocket._socket),
3120
+ websocket._closeTimeout
3121
+ );
3122
+ }
3123
+ function socketOnClose() {
3124
+ const websocket = this[kWebSocket];
3125
+ this.removeListener("close", socketOnClose);
3126
+ this.removeListener("data", socketOnData);
3127
+ this.removeListener("end", socketOnEnd);
3128
+ websocket._readyState = WebSocket2.CLOSING;
3129
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
3130
+ const chunk = this.read(this._readableState.length);
3131
+ websocket._receiver.write(chunk);
3132
+ }
3133
+ websocket._receiver.end();
3134
+ this[kWebSocket] = void 0;
3135
+ clearTimeout(websocket._closeTimer);
3136
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
3137
+ websocket.emitClose();
3138
+ } else {
3139
+ websocket._receiver.on("error", receiverOnFinish);
3140
+ websocket._receiver.on("finish", receiverOnFinish);
3141
+ }
3142
+ }
3143
+ function socketOnData(chunk) {
3144
+ if (!this[kWebSocket]._receiver.write(chunk)) {
3145
+ this.pause();
3146
+ }
3147
+ }
3148
+ function socketOnEnd() {
3149
+ const websocket = this[kWebSocket];
3150
+ websocket._readyState = WebSocket2.CLOSING;
3151
+ websocket._receiver.end();
3152
+ this.end();
3153
+ }
3154
+ function socketOnError() {
3155
+ const websocket = this[kWebSocket];
3156
+ this.removeListener("error", socketOnError);
3157
+ this.on("error", NOOP);
3158
+ if (websocket) {
3159
+ websocket._readyState = WebSocket2.CLOSING;
3160
+ this.destroy();
3161
+ }
3162
+ }
3163
+ }
3164
+ });
3165
+
3166
+ // node_modules/ws/lib/stream.js
3167
+ var require_stream = __commonJS({
3168
+ "node_modules/ws/lib/stream.js"(exports, module) {
3169
+ "use strict";
3170
+ var WebSocket2 = require_websocket();
3171
+ var { Duplex } = __require("stream");
3172
+ function emitClose(stream2) {
3173
+ stream2.emit("close");
3174
+ }
3175
+ function duplexOnEnd() {
3176
+ if (!this.destroyed && this._writableState.finished) {
3177
+ this.destroy();
3178
+ }
3179
+ }
3180
+ function duplexOnError(err) {
3181
+ this.removeListener("error", duplexOnError);
3182
+ this.destroy();
3183
+ if (this.listenerCount("error") === 0) {
3184
+ this.emit("error", err);
3185
+ }
3186
+ }
3187
+ function createWebSocketStream2(ws2, options) {
3188
+ let terminateOnDestroy = true;
3189
+ const duplex = new Duplex({
3190
+ ...options,
3191
+ autoDestroy: false,
3192
+ emitClose: false,
3193
+ objectMode: false,
3194
+ writableObjectMode: false
3195
+ });
3196
+ ws2.on("message", function message(msg, isBinary) {
3197
+ const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
3198
+ if (!duplex.push(data)) ws2.pause();
3199
+ });
3200
+ ws2.once("error", function error(err) {
3201
+ if (duplex.destroyed) return;
3202
+ terminateOnDestroy = false;
3203
+ duplex.destroy(err);
3204
+ });
3205
+ ws2.once("close", function close() {
3206
+ if (duplex.destroyed) return;
3207
+ duplex.push(null);
3208
+ });
3209
+ duplex._destroy = function(err, callback) {
3210
+ if (ws2.readyState === ws2.CLOSED) {
3211
+ callback(err);
3212
+ process.nextTick(emitClose, duplex);
3213
+ return;
3214
+ }
3215
+ let called = false;
3216
+ ws2.once("error", function error(err2) {
3217
+ called = true;
3218
+ callback(err2);
3219
+ });
3220
+ ws2.once("close", function close() {
3221
+ if (!called) callback(err);
3222
+ process.nextTick(emitClose, duplex);
3223
+ });
3224
+ if (terminateOnDestroy) ws2.terminate();
3225
+ };
3226
+ duplex._final = function(callback) {
3227
+ if (ws2.readyState === ws2.CONNECTING) {
3228
+ ws2.once("open", function open() {
3229
+ duplex._final(callback);
3230
+ });
3231
+ return;
3232
+ }
3233
+ if (ws2._socket === null) return;
3234
+ if (ws2._socket._writableState.finished) {
3235
+ callback();
3236
+ if (duplex._readableState.endEmitted) duplex.destroy();
3237
+ } else {
3238
+ ws2._socket.once("finish", function finish() {
3239
+ callback();
3240
+ });
3241
+ ws2.close();
3242
+ }
3243
+ };
3244
+ duplex._read = function() {
3245
+ if (ws2.isPaused) ws2.resume();
3246
+ };
3247
+ duplex._write = function(chunk, encoding, callback) {
3248
+ if (ws2.readyState === ws2.CONNECTING) {
3249
+ ws2.once("open", function open() {
3250
+ duplex._write(chunk, encoding, callback);
3251
+ });
3252
+ return;
3253
+ }
3254
+ ws2.send(chunk, callback);
3255
+ };
3256
+ duplex.on("end", duplexOnEnd);
3257
+ duplex.on("error", duplexOnError);
3258
+ return duplex;
3259
+ }
3260
+ module.exports = createWebSocketStream2;
3261
+ }
3262
+ });
3263
+
3264
+ // node_modules/ws/lib/subprotocol.js
3265
+ var require_subprotocol = __commonJS({
3266
+ "node_modules/ws/lib/subprotocol.js"(exports, module) {
3267
+ "use strict";
3268
+ var { tokenChars } = require_validation();
3269
+ function parse(header) {
3270
+ const protocols = /* @__PURE__ */ new Set();
3271
+ let start = -1;
3272
+ let end = -1;
3273
+ let i = 0;
3274
+ for (i; i < header.length; i++) {
3275
+ const code = header.charCodeAt(i);
3276
+ if (end === -1 && tokenChars[code] === 1) {
3277
+ if (start === -1) start = i;
3278
+ } else if (i !== 0 && (code === 32 || code === 9)) {
3279
+ if (end === -1 && start !== -1) end = i;
3280
+ } else if (code === 44) {
3281
+ if (start === -1) {
3282
+ throw new SyntaxError(`Unexpected character at index ${i}`);
3283
+ }
3284
+ if (end === -1) end = i;
3285
+ const protocol2 = header.slice(start, end);
3286
+ if (protocols.has(protocol2)) {
3287
+ throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
3288
+ }
3289
+ protocols.add(protocol2);
3290
+ start = end = -1;
3291
+ } else {
3292
+ throw new SyntaxError(`Unexpected character at index ${i}`);
3293
+ }
3294
+ }
3295
+ if (start === -1 || end !== -1) {
3296
+ throw new SyntaxError("Unexpected end of input");
3297
+ }
3298
+ const protocol = header.slice(start, i);
3299
+ if (protocols.has(protocol)) {
3300
+ throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
3301
+ }
3302
+ protocols.add(protocol);
3303
+ return protocols;
3304
+ }
3305
+ module.exports = { parse };
3306
+ }
3307
+ });
3308
+
3309
+ // node_modules/ws/lib/websocket-server.js
3310
+ var require_websocket_server = __commonJS({
3311
+ "node_modules/ws/lib/websocket-server.js"(exports, module) {
3312
+ "use strict";
3313
+ var EventEmitter = __require("events");
3314
+ var http = __require("http");
3315
+ var { Duplex } = __require("stream");
3316
+ var { createHash: createHash2 } = __require("crypto");
3317
+ var extension2 = require_extension();
3318
+ var PerMessageDeflate2 = require_permessage_deflate();
3319
+ var subprotocol2 = require_subprotocol();
3320
+ var WebSocket2 = require_websocket();
3321
+ var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
3322
+ var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
3323
+ var RUNNING = 0;
3324
+ var CLOSING = 1;
3325
+ var CLOSED = 2;
3326
+ var WebSocketServer2 = class extends EventEmitter {
3327
+ /**
3328
+ * Create a `WebSocketServer` instance.
3329
+ *
3330
+ * @param {Object} options Configuration options
3331
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
3332
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
3333
+ * multiple times in the same tick
3334
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
3335
+ * automatically send a pong in response to a ping
3336
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
3337
+ * pending connections
3338
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
3339
+ * track clients
3340
+ * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
3341
+ * wait for the closing handshake to finish after `websocket.close()` is
3342
+ * called
3343
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
3344
+ * @param {String} [options.host] The hostname where to bind the server
3345
+ * @param {Number} [options.maxBufferedChunks=262144] The maximum number of
3346
+ * buffered data chunks
3347
+ * @param {Number} [options.maxFragments=16384] The maximum number of message
3348
+ * fragments
3349
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
3350
+ * size
3351
+ * @param {Boolean} [options.noServer=false] Enable no server mode
3352
+ * @param {String} [options.path] Accept only connections matching this path
3353
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
3354
+ * permessage-deflate
3355
+ * @param {Number} [options.port] The port where to bind the server
3356
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
3357
+ * server to use
3358
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
3359
+ * not to skip UTF-8 validation for text and close messages
3360
+ * @param {Function} [options.verifyClient] A hook to reject connections
3361
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
3362
+ * class to use. It must be the `WebSocket` class or class that extends it
3363
+ * @param {Function} [callback] A listener for the `listening` event
3364
+ */
3365
+ constructor(options, callback) {
3366
+ super();
3367
+ options = {
3368
+ allowSynchronousEvents: true,
3369
+ autoPong: true,
3370
+ maxBufferedChunks: 256 * 1024,
3371
+ maxFragments: 16 * 1024,
3372
+ maxPayload: 100 * 1024 * 1024,
3373
+ skipUTF8Validation: false,
3374
+ perMessageDeflate: false,
3375
+ handleProtocols: null,
3376
+ clientTracking: true,
3377
+ closeTimeout: CLOSE_TIMEOUT,
3378
+ verifyClient: null,
3379
+ noServer: false,
3380
+ backlog: null,
3381
+ // use default (511 as implemented in net.js)
3382
+ server: null,
3383
+ host: null,
3384
+ path: null,
3385
+ port: null,
3386
+ WebSocket: WebSocket2,
3387
+ ...options
3388
+ };
3389
+ if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
3390
+ throw new TypeError(
3391
+ 'One and only one of the "port", "server", or "noServer" options must be specified'
3392
+ );
3393
+ }
3394
+ if (options.port != null) {
3395
+ this._server = http.createServer((req, res) => {
3396
+ const body = http.STATUS_CODES[426];
3397
+ res.writeHead(426, {
3398
+ "Content-Length": body.length,
3399
+ "Content-Type": "text/plain"
3400
+ });
3401
+ res.end(body);
3402
+ });
3403
+ this._server.listen(
3404
+ options.port,
3405
+ options.host,
3406
+ options.backlog,
3407
+ callback
3408
+ );
3409
+ } else if (options.server) {
3410
+ this._server = options.server;
3411
+ }
3412
+ if (this._server) {
3413
+ const emitConnection = this.emit.bind(this, "connection");
3414
+ this._removeListeners = addListeners(this._server, {
3415
+ listening: this.emit.bind(this, "listening"),
3416
+ error: this.emit.bind(this, "error"),
3417
+ upgrade: (req, socket, head) => {
3418
+ this.handleUpgrade(req, socket, head, emitConnection);
3419
+ }
3420
+ });
3421
+ }
3422
+ if (options.perMessageDeflate === true) options.perMessageDeflate = {};
3423
+ if (options.clientTracking) {
3424
+ this.clients = /* @__PURE__ */ new Set();
3425
+ this._shouldEmitClose = false;
3426
+ }
3427
+ this.options = options;
3428
+ this._state = RUNNING;
3429
+ }
3430
+ /**
3431
+ * Returns the bound address, the address family name, and port of the server
3432
+ * as reported by the operating system if listening on an IP socket.
3433
+ * If the server is listening on a pipe or UNIX domain socket, the name is
3434
+ * returned as a string.
3435
+ *
3436
+ * @return {(Object|String|null)} The address of the server
3437
+ * @public
3438
+ */
3439
+ address() {
3440
+ if (this.options.noServer) {
3441
+ throw new Error('The server is operating in "noServer" mode');
3442
+ }
3443
+ if (!this._server) return null;
3444
+ return this._server.address();
3445
+ }
3446
+ /**
3447
+ * Stop the server from accepting new connections and emit the `'close'` event
3448
+ * when all existing connections are closed.
3449
+ *
3450
+ * @param {Function} [cb] A one-time listener for the `'close'` event
3451
+ * @public
3452
+ */
3453
+ close(cb) {
3454
+ if (this._state === CLOSED) {
3455
+ if (cb) {
3456
+ this.once("close", () => {
3457
+ cb(new Error("The server is not running"));
3458
+ });
3459
+ }
3460
+ process.nextTick(emitClose, this);
3461
+ return;
3462
+ }
3463
+ if (cb) this.once("close", cb);
3464
+ if (this._state === CLOSING) return;
3465
+ this._state = CLOSING;
3466
+ if (this.options.noServer || this.options.server) {
3467
+ if (this._server) {
3468
+ this._removeListeners();
3469
+ this._removeListeners = this._server = null;
3470
+ }
3471
+ if (this.clients) {
3472
+ if (!this.clients.size) {
3473
+ process.nextTick(emitClose, this);
3474
+ } else {
3475
+ this._shouldEmitClose = true;
3476
+ }
3477
+ } else {
3478
+ process.nextTick(emitClose, this);
3479
+ }
3480
+ } else {
3481
+ const server = this._server;
3482
+ this._removeListeners();
3483
+ this._removeListeners = this._server = null;
3484
+ server.close(() => {
3485
+ emitClose(this);
3486
+ });
3487
+ }
3488
+ }
3489
+ /**
3490
+ * See if a given request should be handled by this server instance.
3491
+ *
3492
+ * @param {http.IncomingMessage} req Request object to inspect
3493
+ * @return {Boolean} `true` if the request is valid, else `false`
3494
+ * @public
3495
+ */
3496
+ shouldHandle(req) {
3497
+ if (this.options.path) {
3498
+ const index = req.url.indexOf("?");
3499
+ const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
3500
+ if (pathname !== this.options.path) return false;
3501
+ }
3502
+ return true;
3503
+ }
3504
+ /**
3505
+ * Handle a HTTP Upgrade request.
3506
+ *
3507
+ * @param {http.IncomingMessage} req The request object
3508
+ * @param {Duplex} socket The network socket between the server and client
3509
+ * @param {Buffer} head The first packet of the upgraded stream
3510
+ * @param {Function} cb Callback
3511
+ * @public
3512
+ */
3513
+ handleUpgrade(req, socket, head, cb) {
3514
+ socket.on("error", socketOnError);
3515
+ const key = req.headers["sec-websocket-key"];
3516
+ const upgrade = req.headers.upgrade;
3517
+ const version = +req.headers["sec-websocket-version"];
3518
+ if (req.method !== "GET") {
3519
+ const message = "Invalid HTTP method";
3520
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
3521
+ return;
3522
+ }
3523
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
3524
+ const message = "Invalid Upgrade header";
3525
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3526
+ return;
3527
+ }
3528
+ if (key === void 0 || !keyRegex.test(key)) {
3529
+ const message = "Missing or invalid Sec-WebSocket-Key header";
3530
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3531
+ return;
3532
+ }
3533
+ if (version !== 13 && version !== 8) {
3534
+ const message = "Missing or invalid Sec-WebSocket-Version header";
3535
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
3536
+ "Sec-WebSocket-Version": "13, 8"
3537
+ });
3538
+ return;
3539
+ }
3540
+ if (!this.shouldHandle(req)) {
3541
+ abortHandshake(socket, 400);
3542
+ return;
3543
+ }
3544
+ const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
3545
+ let protocols = /* @__PURE__ */ new Set();
3546
+ if (secWebSocketProtocol !== void 0) {
3547
+ try {
3548
+ protocols = subprotocol2.parse(secWebSocketProtocol);
3549
+ } catch (err) {
3550
+ const message = "Invalid Sec-WebSocket-Protocol header";
3551
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3552
+ return;
3553
+ }
3554
+ }
3555
+ const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
3556
+ const extensions = {};
3557
+ if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
3558
+ const perMessageDeflate = new PerMessageDeflate2({
3559
+ ...this.options.perMessageDeflate,
3560
+ isServer: true,
3561
+ maxPayload: this.options.maxPayload
3562
+ });
3563
+ try {
3564
+ const offers = extension2.parse(secWebSocketExtensions);
3565
+ if (offers[PerMessageDeflate2.extensionName]) {
3566
+ perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]);
3567
+ extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
3568
+ }
3569
+ } catch (err) {
3570
+ const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
3571
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3572
+ return;
3573
+ }
3574
+ }
3575
+ if (this.options.verifyClient) {
3576
+ const info = {
3577
+ origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
3578
+ secure: !!(req.socket.authorized || req.socket.encrypted),
3579
+ req
3580
+ };
3581
+ if (this.options.verifyClient.length === 2) {
3582
+ this.options.verifyClient(info, (verified, code, message, headers) => {
3583
+ if (!verified) {
3584
+ return abortHandshake(socket, code || 401, message, headers);
3585
+ }
3586
+ this.completeUpgrade(
3587
+ extensions,
3588
+ key,
3589
+ protocols,
3590
+ req,
3591
+ socket,
3592
+ head,
3593
+ cb
3594
+ );
3595
+ });
3596
+ return;
3597
+ }
3598
+ if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
3599
+ }
3600
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
3601
+ }
3602
+ /**
3603
+ * Upgrade the connection to WebSocket.
3604
+ *
3605
+ * @param {Object} extensions The accepted extensions
3606
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
3607
+ * @param {Set} protocols The subprotocols
3608
+ * @param {http.IncomingMessage} req The request object
3609
+ * @param {Duplex} socket The network socket between the server and client
3610
+ * @param {Buffer} head The first packet of the upgraded stream
3611
+ * @param {Function} cb Callback
3612
+ * @throws {Error} If called more than once with the same socket
3613
+ * @private
3614
+ */
3615
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
3616
+ if (!socket.readable || !socket.writable) return socket.destroy();
3617
+ if (socket[kWebSocket]) {
3618
+ throw new Error(
3619
+ "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
3620
+ );
3621
+ }
3622
+ if (this._state > RUNNING) return abortHandshake(socket, 503);
3623
+ const digest = createHash2("sha1").update(key + GUID).digest("base64");
3624
+ const headers = [
3625
+ "HTTP/1.1 101 Switching Protocols",
3626
+ "Upgrade: websocket",
3627
+ "Connection: Upgrade",
3628
+ `Sec-WebSocket-Accept: ${digest}`
3629
+ ];
3630
+ const ws2 = new this.options.WebSocket(null, void 0, this.options);
3631
+ if (protocols.size) {
3632
+ const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
3633
+ if (protocol) {
3634
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
3635
+ ws2._protocol = protocol;
3636
+ }
3637
+ }
3638
+ if (extensions[PerMessageDeflate2.extensionName]) {
3639
+ const params = extensions[PerMessageDeflate2.extensionName].params;
3640
+ const value = extension2.format({
3641
+ [PerMessageDeflate2.extensionName]: [params]
3642
+ });
3643
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
3644
+ ws2._extensions = extensions;
3645
+ }
3646
+ this.emit("headers", headers, req);
3647
+ socket.write(headers.concat("\r\n").join("\r\n"));
3648
+ socket.removeListener("error", socketOnError);
3649
+ ws2.setSocket(socket, head, {
3650
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
3651
+ maxBufferedChunks: this.options.maxBufferedChunks,
3652
+ maxFragments: this.options.maxFragments,
3653
+ maxPayload: this.options.maxPayload,
3654
+ skipUTF8Validation: this.options.skipUTF8Validation
3655
+ });
3656
+ if (this.clients) {
3657
+ this.clients.add(ws2);
3658
+ ws2.on("close", () => {
3659
+ this.clients.delete(ws2);
3660
+ if (this._shouldEmitClose && !this.clients.size) {
3661
+ process.nextTick(emitClose, this);
3662
+ }
3663
+ });
3664
+ }
3665
+ cb(ws2, req);
3666
+ }
3667
+ };
3668
+ module.exports = WebSocketServer2;
3669
+ function addListeners(server, map) {
3670
+ for (const event of Object.keys(map)) server.on(event, map[event]);
3671
+ return function removeListeners() {
3672
+ for (const event of Object.keys(map)) {
3673
+ server.removeListener(event, map[event]);
3674
+ }
3675
+ };
3676
+ }
3677
+ function emitClose(server) {
3678
+ server._state = CLOSED;
3679
+ server.emit("close");
3680
+ }
3681
+ function socketOnError() {
3682
+ this.destroy();
3683
+ }
3684
+ function abortHandshake(socket, code, message, headers) {
3685
+ message = message || http.STATUS_CODES[code];
3686
+ headers = {
3687
+ Connection: "close",
3688
+ "Content-Type": "text/html",
3689
+ "Content-Length": Buffer.byteLength(message),
3690
+ ...headers
3691
+ };
3692
+ socket.once("finish", socket.destroy);
3693
+ socket.end(
3694
+ `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
3695
+ ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
3696
+ );
3697
+ }
3698
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
3699
+ if (server.listenerCount("wsClientError")) {
3700
+ const err = new Error(message);
3701
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
3702
+ server.emit("wsClientError", err, socket, req);
3703
+ } else {
3704
+ abortHandshake(socket, code, message, headers);
3705
+ }
3706
+ }
3707
+ }
3708
+ });
3709
+
3710
+ // node_modules/ws/wrapper.mjs
3711
+ var import_stream = __toESM(require_stream(), 1);
3712
+ var import_extension = __toESM(require_extension(), 1);
3713
+ var import_permessage_deflate = __toESM(require_permessage_deflate(), 1);
3714
+ var import_receiver = __toESM(require_receiver(), 1);
3715
+ var import_sender = __toESM(require_sender(), 1);
3716
+ var import_subprotocol = __toESM(require_subprotocol(), 1);
3717
+ var import_websocket = __toESM(require_websocket(), 1);
3718
+ var import_websocket_server = __toESM(require_websocket_server(), 1);
3719
+ var wrapper_default = import_websocket.default;
3720
+
3721
+ // src/client.ts
3722
+ import * as fs6 from "fs";
3723
+ import * as path5 from "path";
3724
+ import * as os3 from "os";
3725
+ import { execFileSync as execFileSync3 } from "child_process";
3726
+
3727
+ // src/agents-md-scanner.ts
3728
+ import * as fs from "fs";
3729
+ import * as path2 from "path";
3730
+ import * as os2 from "os";
3731
+
3732
+ // src/paths.ts
3733
+ import * as path from "path";
3734
+ import * as os from "os";
3735
+ var DATA_DIR = process.env.CORTEX_HOME ? path.resolve(process.env.CORTEX_HOME) : path.join(os.homedir(), ".cortex");
3736
+ var CONFIG_DIR = path.join(DATA_DIR, "config");
3737
+ var LOGS_DIR = path.join(DATA_DIR, "logs");
3738
+
3739
+ // src/agents-md-scanner.ts
3740
+ var AGENTS_MD_NAMES = ["AGENTS.md", "AGENTS.local.md"];
3741
+ var DEVICE_ID = os2.hostname();
3742
+ var MAX_FILE_SIZE = 200 * 1024;
3743
+ var MAX_DEPTH = 20;
3744
+ function tryReadEntry(filePath) {
3745
+ try {
3746
+ const stat = fs.statSync(filePath, { throwIfNoEntry: false });
3747
+ if (!stat || !stat.isFile()) return null;
3748
+ if (stat.size > MAX_FILE_SIZE) return null;
3749
+ const content = fs.readFileSync(filePath, "utf8");
3750
+ return { path: filePath, content, mtimeMs: stat.mtimeMs, deviceId: DEVICE_ID };
3751
+ } catch {
3752
+ return null;
3753
+ }
3754
+ }
3755
+ function scanAgentsMDChain(targetFilePath) {
3756
+ const entries = [];
3757
+ const seen = /* @__PURE__ */ new Set();
3758
+ let dir;
3759
+ try {
3760
+ dir = path2.dirname(path2.resolve(targetFilePath));
3761
+ } catch {
3762
+ return entries;
3763
+ }
3764
+ for (let depth = 0; depth < MAX_DEPTH; depth++) {
3765
+ for (const name of AGENTS_MD_NAMES) {
3766
+ const p = path2.join(dir, name);
3767
+ if (seen.has(p)) continue;
3768
+ seen.add(p);
3769
+ const entry = tryReadEntry(p);
3770
+ if (entry) entries.push(entry);
3771
+ }
3772
+ const parent = path2.dirname(dir);
3773
+ if (parent === dir) break;
3774
+ dir = parent;
3775
+ }
3776
+ const homeAgents = path2.join(DATA_DIR, "AGENTS.md");
3777
+ if (!seen.has(homeAgents)) {
3778
+ seen.add(homeAgents);
3779
+ const entry = tryReadEntry(homeAgents);
3780
+ if (entry) entries.push(entry);
3781
+ }
3782
+ return entries;
3783
+ }
3784
+
3785
+ // src/command-exec.ts
3786
+ import { execFileSync, spawn } from "node:child_process";
3787
+ import * as fs2 from "node:fs";
3788
+ import { win32 } from "node:path";
3789
+ var GIT_BASH_PATHS = [
3790
+ "C:\\Program Files\\Git\\bin\\bash.exe",
3791
+ "C:\\Program Files (x86)\\Git\\bin\\bash.exe"
3792
+ ];
3793
+ var DEFAULT_KILL_DEPS = {
3794
+ kill: (pid, signal) => process.kill(pid, signal),
3795
+ execFileSync: (file, args, options) => execFileSync(file, args, options)
3796
+ };
3797
+ var OutputAccumulator = class {
3798
+ head = "";
3799
+ headFull = false;
3800
+ tail = "";
3801
+ totalChars = 0;
3802
+ headSize;
3803
+ tailSize;
3804
+ constructor(maxBytes) {
3805
+ this.headSize = Math.floor(maxBytes * 0.6);
3806
+ this.tailSize = Math.floor(maxBytes * 0.4);
3807
+ }
3808
+ append(data) {
3809
+ this.totalChars += data.length;
3810
+ if (!this.headFull) {
3811
+ this.appendHead(data);
3812
+ return;
3813
+ }
3814
+ this.tail += data;
3815
+ if (this.tail.length > this.tailSize * 2) this.tail = this.tail.slice(-this.tailSize);
3816
+ }
3817
+ toString() {
3818
+ if (!this.headFull) return this.head;
3819
+ const finalTail = this.tail.slice(-this.tailSize);
3820
+ const omitted = this.totalChars - this.head.length - finalTail.length;
3821
+ return `${this.head}
3822
+
3823
+ [... ${omitted} chars truncated ...]
3824
+
3825
+ ${finalTail}`;
3826
+ }
3827
+ appendHead(data) {
3828
+ this.head += data;
3829
+ if (this.head.length <= this.headSize) return;
3830
+ this.tail = this.head.slice(this.headSize);
3831
+ this.head = this.head.slice(0, this.headSize);
3832
+ this.headFull = true;
3833
+ }
3834
+ };
3835
+ function killCommandTree(pid, platform = process.platform, deps = DEFAULT_KILL_DEPS) {
3836
+ try {
3837
+ if (platform === "win32") {
3838
+ deps.execFileSync("taskkill", ["/PID", String(pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
3839
+ return;
3840
+ }
3841
+ deps.kill(-pid, "SIGKILL");
3842
+ } catch {
3843
+ }
3844
+ }
3845
+ function spawnCommand(cmd, args, timeoutMs, maxOutputBytes = 5e5) {
3846
+ const proc = spawn(cmd, args, {
3847
+ stdio: ["pipe", "pipe", "pipe"],
3848
+ env: { ...process.env },
3849
+ detached: process.platform !== "win32",
3850
+ // The client runs without a console on Windows, so a console program (bash, grep, rg)
3851
+ // would otherwise get a new, visible console window for as long as it runs.
3852
+ windowsHide: true
3853
+ });
3854
+ const stdout = new OutputAccumulator(maxOutputBytes);
3855
+ const stderr = new OutputAccumulator(5e4);
3856
+ proc.stdout.on("data", (data) => stdout.append(data.toString()));
3857
+ proc.stderr.on("data", (data) => stderr.append(data.toString()));
3858
+ return monitorCommand(proc, stdout, stderr, timeoutMs);
3859
+ }
3860
+ function execBash(command, timeoutMs) {
3861
+ const shell = resolveBash();
3862
+ if (!shell) {
3863
+ return Promise.resolve({ stdout: "", stderr: "bash not found (git-bash not installed on Windows?)", exitCode: 127 });
3864
+ }
3865
+ return spawnCommand(shell, ["-l", "-c", command], timeoutMs, 2e5);
3866
+ }
3867
+ function execBashBackground(command) {
3868
+ const shell = resolveBash();
3869
+ if (!shell) return { pid: void 0 };
3870
+ const proc = spawn(shell, ["-l", "-c", command], {
3871
+ stdio: "ignore",
3872
+ detached: true,
3873
+ env: { ...process.env },
3874
+ windowsHide: true
3875
+ });
3876
+ proc.unref();
3877
+ return { pid: proc.pid };
3878
+ }
3879
+ function monitorCommand(proc, stdout, stderr, timeoutMs) {
3880
+ return new Promise((resolve5) => {
3881
+ let settled = false;
3882
+ const finish = (result) => {
3883
+ if (settled) return;
3884
+ settled = true;
3885
+ clearTimeout(timer);
3886
+ resolve5(result);
3887
+ };
3888
+ const timer = setTimeout(() => {
3889
+ if (proc.pid) killCommandTree(proc.pid);
3890
+ const message = `Command timed out after ${timeoutMs / 1e3}s`;
3891
+ finish({ stdout: stdout.toString(), stderr: joinStderr(stderr.toString(), message), exitCode: 124 });
3892
+ }, timeoutMs);
3893
+ proc.on("close", (code) => finish({ stdout: stdout.toString(), stderr: stderr.toString(), exitCode: code ?? 1 }));
3894
+ proc.on("error", (error) => finish({ stdout: stdout.toString(), stderr: joinStderr(stderr.toString(), error.message), exitCode: 127 }));
3895
+ });
3896
+ }
3897
+ function resolveBash(posixShell = "/bin/bash") {
3898
+ if (process.platform !== "win32") return posixShell;
3899
+ const selected = process.env.CORTEX_GIT_BASH_PATH;
3900
+ if (selected !== void 0) {
3901
+ if (!selected || !fs2.existsSync(selected)) {
3902
+ throw new Error(`CORTEX_GIT_BASH_PATH points to a missing Git Bash executable: "${selected}"`);
3903
+ }
3904
+ return selected;
3905
+ }
3906
+ return GIT_BASH_PATHS.find((candidate) => fs2.existsSync(candidate)) ?? findBashOnPath();
3907
+ }
3908
+ function findBashOnPath() {
3909
+ const pathKey = Object.keys(process.env).find((key) => key.toUpperCase() === "PATH");
3910
+ const directories = (process.env[pathKey ?? "PATH"] ?? "").split(";").filter(Boolean);
3911
+ const candidates = directories.map((directory) => win32.join(directory.replace(/^"|"$/g, ""), "bash.exe"));
3912
+ return candidates.find((candidate) => fs2.existsSync(candidate)) ?? null;
3913
+ }
3914
+ function joinStderr(stderr, message) {
3915
+ if (!stderr) return message;
3916
+ return `${stderr}${stderr.endsWith("\n") ? "" : "\n"}${message}`;
3917
+ }
3918
+
3919
+ // src/log.ts
3920
+ import fs3 from "node:fs";
3921
+ import path3 from "node:path";
3922
+ var RETENTION_DAYS = 14;
3923
+ var currentDate = "";
3924
+ var stream = null;
3925
+ var lastCleanup = "";
3926
+ function dateTag() {
3927
+ const d = /* @__PURE__ */ new Date();
3928
+ return [
3929
+ d.getFullYear(),
3930
+ String(d.getMonth() + 1).padStart(2, "0"),
3931
+ String(d.getDate()).padStart(2, "0")
3932
+ ].join("");
3933
+ }
3934
+ function getStream() {
3935
+ const tag = dateTag();
3936
+ if (tag !== currentDate || !stream) {
3937
+ stream?.end();
3938
+ try {
3939
+ fs3.mkdirSync(LOGS_DIR, { recursive: true });
3940
+ } catch {
3941
+ }
3942
+ currentDate = tag;
3943
+ stream = fs3.createWriteStream(
3944
+ path3.join(LOGS_DIR, `client-${tag}.log`),
3945
+ { flags: "a" }
3946
+ );
3947
+ if (lastCleanup !== tag) {
3948
+ lastCleanup = tag;
3949
+ cleanOldLogs();
3950
+ }
3951
+ }
3952
+ return stream;
3953
+ }
3954
+ function cleanOldLogs() {
3955
+ try {
3956
+ const cutoff = Date.now() - RETENTION_DAYS * 864e5;
3957
+ for (const f of fs3.readdirSync(LOGS_DIR)) {
3958
+ const m = f.match(/^client-(\d{4})(\d{2})(\d{2})\.log$/);
3959
+ if (!m) continue;
3960
+ const fileDate = new Date(+m[1], +m[2] - 1, +m[3]).getTime();
3961
+ if (fileDate < cutoff) {
3962
+ fs3.unlinkSync(path3.join(LOGS_DIR, f));
3963
+ }
3964
+ }
3965
+ } catch {
3966
+ }
3967
+ }
3968
+ function formatArg(a) {
3969
+ if (a instanceof Error) return a.stack || a.message;
3970
+ if (typeof a === "object" && a !== null) {
3971
+ try {
3972
+ return JSON.stringify(a);
3973
+ } catch {
3974
+ return String(a);
3975
+ }
3976
+ }
3977
+ return String(a);
3978
+ }
3979
+ function write(level, mod, args) {
3980
+ const ts = (/* @__PURE__ */ new Date()).toLocaleTimeString("en-GB", { hour12: false });
3981
+ const prefix = `[${mod} ${ts}]`;
3982
+ switch (level) {
3983
+ case "ERROR":
3984
+ console.error(prefix, ...args);
3985
+ break;
3986
+ case "WARN":
3987
+ console.warn(prefix, ...args);
3988
+ break;
3989
+ default:
3990
+ console.log(prefix, ...args);
3991
+ }
3992
+ const line = `${prefix} ${level} ${args.map(formatArg).join(" ")}
3993
+ `;
3994
+ try {
3995
+ getStream().write(line);
3996
+ } catch {
3997
+ }
3998
+ }
3999
+ function createLogger(mod) {
4000
+ return {
4001
+ info: (...args) => write("INFO", mod, args),
4002
+ warn: (...args) => write("WARN", mod, args),
4003
+ error: (...args) => write("ERROR", mod, args)
4004
+ };
4005
+ }
4006
+ process.on("exit", () => {
4007
+ stream?.end();
4008
+ });
4009
+
4010
+ // src/auth-headers.ts
4011
+ var AUTH_HEADER = "x-cortex-token";
4012
+ function resolveClientToken(cfg, env) {
4013
+ return env.CORTEX_CLIENT_TOKEN?.trim() || cfg.clientToken?.trim() || "";
4014
+ }
4015
+ function buildClientHeaders(token) {
4016
+ const t = token?.trim();
4017
+ return t ? { [AUTH_HEADER]: t } : void 0;
4018
+ }
4019
+
4020
+ // src/reverse-stream.ts
4021
+ import * as net from "net";
4022
+ var log = createLogger("reverse-stream");
4023
+ function isOpenStream(msg) {
4024
+ const m = msg;
4025
+ return !!m && m.type === "open-stream" && typeof m.streamId === "string" && typeof m.host === "string" && Number.isInteger(m.port);
4026
+ }
4027
+ var LOOPBACK = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
4028
+ function isAllowedTarget(host, port) {
4029
+ return LOOPBACK.has(host.toLowerCase()) && port >= 1024 && port <= 65535;
4030
+ }
4031
+ function callbackUrl(controlUrl, streamId) {
4032
+ const url = new URL(controlUrl);
4033
+ url.pathname = "/reverse";
4034
+ url.search = `stream=${encodeURIComponent(streamId)}`;
4035
+ return url.toString();
4036
+ }
4037
+ function openReverseStream(msg, deps) {
4038
+ if (!isAllowedTarget(msg.host, msg.port)) {
4039
+ log.warn(`refusing reverse stream to ${msg.host}:${msg.port} \u2014 only loopback ports \u2265 1024`);
4040
+ return;
4041
+ }
4042
+ const connectWs = deps.connectWs ?? ((url, headers) => new wrapper_default(url, headers ? { headers } : void 0));
4043
+ const connectTcp = deps.connectTcp ?? ((host, port) => net.connect(port, host));
4044
+ const ws2 = connectWs(callbackUrl(deps.controlUrl, msg.streamId), deps.headers);
4045
+ const tcp = connectTcp(msg.host, msg.port);
4046
+ tcp.setNoDelay?.(true);
4047
+ let closed = false;
4048
+ const shutdown2 = (why) => {
4049
+ if (closed) return;
4050
+ closed = true;
4051
+ log.info(`stream ${msg.streamId.slice(0, 8)} closed: ${why}`);
4052
+ try {
4053
+ ws2.close();
4054
+ } catch {
4055
+ }
4056
+ try {
4057
+ tcp.destroy();
4058
+ } catch {
4059
+ }
4060
+ };
4061
+ ws2.on("open", () => log.info(`stream ${msg.streamId.slice(0, 8)} \u2192 ${msg.host}:${msg.port}`));
4062
+ ws2.on("message", (data) => {
4063
+ const buf = Array.isArray(data) ? Buffer.concat(data) : Buffer.from(data);
4064
+ if (!tcp.write(buf)) {
4065
+ ws2.pause?.();
4066
+ tcp.once("drain", () => ws2.resume?.());
4067
+ }
4068
+ });
4069
+ ws2.on("error", (e) => shutdown2(`ws error: ${e.message}`));
4070
+ ws2.on("close", () => shutdown2("ws closed"));
4071
+ tcp.on("data", (chunk) => {
4072
+ if (ws2.readyState !== wrapper_default.OPEN) return;
4073
+ tcp.pause();
4074
+ ws2.send(chunk, (err) => {
4075
+ if (err) shutdown2(`send failed: ${err.message}`);
4076
+ else tcp.resume();
4077
+ });
4078
+ });
4079
+ tcp.on("error", (e) => shutdown2(`tcp error: ${e.message}`));
4080
+ tcp.on("close", () => shutdown2("tcp closed"));
4081
+ }
4082
+
4083
+ // src/file-stream.ts
4084
+ import * as fs4 from "fs";
4085
+ var log2 = createLogger("file-stream");
4086
+ function isOpenFileStream(msg) {
4087
+ const m = msg;
4088
+ return !!m && m.type === "open-file-stream" && typeof m.streamId === "string" && typeof m.path === "string";
4089
+ }
4090
+ var FILE_STREAM_ERROR_CODE = 4010;
4091
+ function openFileStream(msg, deps) {
4092
+ const normalize = deps.normalizePath ?? ((p) => p);
4093
+ const connectWs = deps.connectWs ?? ((url, headers) => new wrapper_default(url, headers ? { headers } : void 0));
4094
+ const openRead = deps.openRead ?? ((p) => fs4.createReadStream(p));
4095
+ const filePath = normalize(msg.path);
4096
+ const short = msg.streamId.slice(0, 8);
4097
+ const ws2 = connectWs(callbackUrl(deps.controlUrl, msg.streamId), deps.headers);
4098
+ let file = null;
4099
+ let closed = false;
4100
+ let sent = 0;
4101
+ const shutdown2 = (code, why) => {
4102
+ if (closed) return;
4103
+ closed = true;
4104
+ log2.info(`file stream ${short} closed after ${sent} bytes: ${why}`);
4105
+ try {
4106
+ ws2.close(code, why.slice(0, 120));
4107
+ } catch {
4108
+ }
4109
+ try {
4110
+ file?.destroy();
4111
+ } catch {
4112
+ }
4113
+ };
4114
+ ws2.on("open", () => {
4115
+ log2.info(`file stream ${short} \u2192 ${filePath}`);
4116
+ let stream2;
4117
+ try {
4118
+ stream2 = openRead(filePath);
4119
+ } catch (e) {
4120
+ shutdown2(FILE_STREAM_ERROR_CODE, `open failed: ${e.message}`);
4121
+ return;
4122
+ }
4123
+ file = stream2;
4124
+ stream2.on("data", (chunk) => {
4125
+ if (ws2.readyState !== wrapper_default.OPEN) {
4126
+ shutdown2(FILE_STREAM_ERROR_CODE, "socket closed mid-transfer");
4127
+ return;
4128
+ }
4129
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
4130
+ stream2.pause();
4131
+ sent += buf.length;
4132
+ ws2.send(buf, (err) => {
4133
+ if (err) shutdown2(FILE_STREAM_ERROR_CODE, `send failed: ${err.message}`);
4134
+ else stream2.resume();
4135
+ });
4136
+ });
4137
+ stream2.on("end", () => shutdown2(1e3, "eof"));
4138
+ stream2.on("error", (e) => shutdown2(FILE_STREAM_ERROR_CODE, `read failed: ${e.message}`));
4139
+ });
4140
+ ws2.on("error", (e) => shutdown2(FILE_STREAM_ERROR_CODE, `ws error: ${e.message}`));
4141
+ ws2.on("close", () => shutdown2(1e3, "ws closed"));
4142
+ }
4143
+
4144
+ // src/server-url.ts
4145
+ function resolveServerUrl(cfg, env) {
4146
+ const envUrl = env.CORTEX_SERVER_URL?.trim();
4147
+ if (envUrl) return envUrl;
4148
+ const cfgUrl = cfg.serverUrl?.trim();
4149
+ if (cfgUrl) return cfgUrl;
4150
+ return `ws://${cfg.serverHost}:${cfg.serverPort || 3002}`;
4151
+ }
4152
+
4153
+ // src/gpu-detect.ts
4154
+ import { execFileSync as execFileSync2 } from "node:child_process";
4155
+ var MAX_PLAUSIBLE_GPUS = 64;
4156
+ var SMI_TIMEOUT_MS = 5e3;
4157
+ function runNvidiaSmi() {
4158
+ return execFileSync2("nvidia-smi", ["--query-gpu=count", "--format=csv,noheader"], {
4159
+ timeout: SMI_TIMEOUT_MS,
4160
+ stdio: "pipe",
4161
+ encoding: "utf-8",
4162
+ windowsHide: true
4163
+ });
4164
+ }
4165
+ var cached = null;
4166
+ function detectGpuCount(run = runNvidiaSmi) {
4167
+ if (cached !== null) return cached;
4168
+ let raw;
4169
+ try {
4170
+ raw = run();
4171
+ } catch {
4172
+ return null;
4173
+ }
4174
+ const count = Number.parseInt(raw.split("\n")[0]?.trim() ?? "", 10);
4175
+ if (!Number.isInteger(count) || count < 0 || count > MAX_PLAUSIBLE_GPUS) return null;
4176
+ cached = count;
4177
+ return count;
4178
+ }
4179
+
4180
+ // src/self-update.ts
4181
+ import * as fs5 from "fs";
4182
+ import * as path4 from "path";
4183
+ import * as crypto from "crypto";
4184
+ import { spawn as spawn2 } from "child_process";
4185
+ var log3 = createLogger("self-update");
4186
+ var CLIENT_INSTALL_DIR = path4.join(DATA_DIR, "client");
4187
+ var BUNDLE_FILES = ["client.mjs", "cortex-run-watcher.mjs"];
4188
+ function hashBundleFiles(dir) {
4189
+ const h = crypto.createHash("sha256");
4190
+ for (const name of BUNDLE_FILES) {
4191
+ const p = path4.join(dir, name);
4192
+ if (!fs5.existsSync(p)) return null;
4193
+ h.update(fs5.readFileSync(p));
4194
+ }
4195
+ return h.digest("hex");
4196
+ }
4197
+ function computeSelfBundleHash(entryPath = process.argv[1]) {
4198
+ if (!entryPath) return "unknown";
4199
+ const entry = path4.resolve(entryPath);
4200
+ const setHash = hashBundleFiles(path4.dirname(entry));
4201
+ if (setHash) return setHash;
4202
+ try {
4203
+ return `entry-${crypto.createHash("sha256").update(fs5.readFileSync(entry)).digest("hex")}`;
4204
+ } catch {
4205
+ return "unknown";
4206
+ }
4207
+ }
4208
+ function validateUpdateMessage(msg) {
4209
+ if (typeof msg.hash !== "string" || !msg.hash) return "missing hash";
4210
+ if (!Array.isArray(msg.files)) return "missing files";
4211
+ for (const name of BUNDLE_FILES) {
4212
+ if (!msg.files.some((f) => f && f.name === name && typeof f.data === "string")) {
4213
+ return `missing file: ${name}`;
4214
+ }
4215
+ }
4216
+ return null;
4217
+ }
4218
+ function swapDirs(root) {
4219
+ const next = path4.join(root, "next");
4220
+ const current = path4.join(root, "current");
4221
+ const previous = path4.join(root, "previous");
4222
+ fs5.rmSync(previous, { recursive: true, force: true });
4223
+ const hadCurrent = fs5.existsSync(current);
4224
+ if (hadCurrent) fs5.renameSync(current, previous);
4225
+ try {
4226
+ fs5.renameSync(next, current);
4227
+ } catch (err) {
4228
+ if (hadCurrent) {
4229
+ try {
4230
+ fs5.renameSync(previous, current);
4231
+ } catch {
4232
+ }
4233
+ }
4234
+ throw err;
4235
+ }
4236
+ }
4237
+ function defaultRespawn(entryPath) {
4238
+ const child = spawn2(process.execPath, [entryPath], {
4239
+ detached: true,
4240
+ stdio: "ignore",
4241
+ env: process.env,
4242
+ windowsHide: true
4243
+ });
4244
+ child.unref();
4245
+ }
4246
+ function handleUpdateMessage(msg, io) {
4247
+ const invalid = validateUpdateMessage(msg);
4248
+ if (invalid) {
4249
+ io.sendResult(false, invalid);
4250
+ return;
4251
+ }
4252
+ try {
4253
+ const next = path4.join(CLIENT_INSTALL_DIR, "next");
4254
+ fs5.rmSync(next, { recursive: true, force: true });
4255
+ fs5.mkdirSync(next, { recursive: true });
4256
+ for (const name of BUNDLE_FILES) {
4257
+ const file = msg.files.find((f) => f.name === name);
4258
+ fs5.writeFileSync(path4.join(next, name), Buffer.from(file.data, "base64"), { mode: 493 });
4259
+ }
4260
+ const got = hashBundleFiles(next);
4261
+ if (got !== msg.hash) {
4262
+ fs5.rmSync(next, { recursive: true, force: true });
4263
+ io.sendResult(false, `hash mismatch: expected ${msg.hash}, got ${got}`);
4264
+ return;
4265
+ }
4266
+ swapDirs(CLIENT_INSTALL_DIR);
4267
+ } catch (err) {
4268
+ io.sendResult(false, err.message);
4269
+ return;
4270
+ }
4271
+ log3.info(`Installed bundle ${msg.hash.slice(0, 12)}${msg.version ? ` (v${msg.version})` : ""} \u2014 restarting`);
4272
+ io.sendResult(true);
4273
+ setTimeout(() => {
4274
+ try {
4275
+ io.closeWs();
4276
+ } catch {
4277
+ }
4278
+ setTimeout(() => {
4279
+ try {
4280
+ io.respawn(path4.join(CLIENT_INSTALL_DIR, "current", "client.mjs"));
4281
+ } catch (err) {
4282
+ log3.error(`Respawn failed: ${err.message}`);
4283
+ }
4284
+ io.exit(0);
4285
+ }, 400);
4286
+ }, 400);
4287
+ }
4288
+
4289
+ // src/client.ts
4290
+ var log4 = createLogger("cortex-client");
4291
+ function getClientHelp() {
4292
+ return [
4293
+ "cortex-client \u2014 remote worker that connects to the Cortex agent server",
4294
+ "",
4295
+ "Usage: cortex-client",
4296
+ "",
4297
+ "cortex-client is a daemon-style worker. Configuration is read from",
4298
+ ` ${path5.join(CONFIG_DIR, "cortex-client.json")}`,
4299
+ "which the agent-server writes during `cortex client-deploy`. There are",
4300
+ "no command-line flags beyond --help.",
4301
+ "",
4302
+ "Config schema (JSON):",
4303
+ " {",
4304
+ ' "serverHost": "<agent-server host or LAN IP>",',
4305
+ ' "serverPort": 3002,',
4306
+ ' "deviceName": "<short device name>"',
4307
+ " }",
4308
+ "",
4309
+ "Behavior:",
4310
+ " \u2022 Opens a WebSocket to ws://<serverHost>:<serverPort> on start.",
4311
+ " \u2022 Receives bash/read/write/edit/glob/grep commands.",
4312
+ " \u2022 Exits if the server rejects the handshake (e.g. device already connected).",
4313
+ " \u2022 Reconnects automatically on transient disconnects.",
4314
+ "",
4315
+ "Options:",
4316
+ " --help, -h Show this help"
4317
+ ].join("\n");
4318
+ }
4319
+ if (process.argv.slice(2).some((a) => a === "--help" || a === "-h")) {
4320
+ process.stdout.write(`${getClientHelp()}
4321
+ `);
4322
+ process.exit(0);
4323
+ }
4324
+ function loadConfig() {
4325
+ const configPath = path5.join(CONFIG_DIR, "cortex-client.json");
4326
+ try {
4327
+ const raw = fs6.readFileSync(configPath, "utf8");
4328
+ const cfg = JSON.parse(raw);
4329
+ if (!cfg.serverHost && !cfg.serverUrl && !process.env.CORTEX_SERVER_URL) {
4330
+ throw new Error("Missing serverHost (or provide serverUrl / CORTEX_SERVER_URL)");
4331
+ }
4332
+ return {
4333
+ // Full WS URL (tunnel route). env CORTEX_SERVER_URL > config serverUrl > ws://host:port.
4334
+ serverUrl: resolveServerUrl(cfg, process.env),
4335
+ deviceName: cfg.deviceName || os3.hostname(),
4336
+ // WS bearer token required by the agent-server gate; env overrides config (see auth-headers.ts).
4337
+ clientToken: resolveClientToken(cfg, process.env)
4338
+ };
4339
+ } catch (err) {
4340
+ log4.error(`Failed to load config from ${configPath}: ${err.message}`);
4341
+ log4.error('Expected format: {"serverHost":"...","serverPort":3002,"deviceName":"..."} or {"serverUrl":"wss://...","deviceName":"..."}');
4342
+ process.exit(1);
4343
+ }
4344
+ }
4345
+ var CONFIG = loadConfig();
4346
+ var SERVER_URL = CONFIG.serverUrl;
4347
+ var DEVICE_NAME = CONFIG.deviceName;
4348
+ var CLIENT_TOKEN = CONFIG.clientToken;
4349
+ var PLATFORM = process.platform;
4350
+ var HEARTBEAT_INTERVAL_MS = 5e3;
4351
+ var BUNDLE_HASH = computeSelfBundleHash();
4352
+ function detectEncoding(buffer) {
4353
+ if (buffer.length >= 2 && buffer[0] === 255 && buffer[1] === 254) return "utf16le";
4354
+ return "utf8";
4355
+ }
4356
+ function detectLineEnding(content) {
4357
+ const crlfCount = (content.match(/\r\n/g) || []).length;
4358
+ const lfOnly = content.replace(/\r\n/g, "").match(/\n/g);
4359
+ const lfCount = lfOnly ? lfOnly.length : 0;
4360
+ return crlfCount > lfCount ? "\r\n" : "\n";
4361
+ }
4362
+ function countWords(text) {
4363
+ let count = 0;
4364
+ const english = text.match(/[a-zA-Z]+/g);
4365
+ if (english) count += english.length;
4366
+ const cjk = text.match(/[一-鿿㐀-䶿豈-﫿]/g);
4367
+ if (cjk) count += cjk.length;
4368
+ return count;
4369
+ }
4370
+ var IMAGE_SIGNATURES = [
4371
+ { bytes: [255, 216, 255], mimeType: "image/jpeg" },
4372
+ { bytes: [137, 80, 78, 71], mimeType: "image/png" },
4373
+ { bytes: [71, 73, 70, 56], mimeType: "image/gif" },
4374
+ { bytes: [82, 73, 70, 70], mimeType: "image/webp" },
4375
+ { bytes: [66, 77], mimeType: "image/bmp" }
4376
+ ];
4377
+ function detectImageType(buffer) {
4378
+ for (const sig of IMAGE_SIGNATURES) {
4379
+ if (buffer.length < sig.bytes.length) continue;
4380
+ if (!sig.bytes.every((b, i) => buffer[i] === b)) continue;
4381
+ if (sig.mimeType === "image/webp") {
4382
+ if (buffer.length >= 12 && buffer.slice(8, 12).toString("ascii") === "WEBP") {
4383
+ return "image/webp";
4384
+ }
4385
+ continue;
4386
+ }
4387
+ return sig.mimeType;
4388
+ }
4389
+ return null;
4390
+ }
4391
+ function extractImageDimensions(buf, mime) {
4392
+ try {
4393
+ if (mime === "image/png" && buf.length >= 24) {
4394
+ return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
4395
+ }
4396
+ if (mime === "image/gif" && buf.length >= 10) {
4397
+ return { width: buf.readUInt16LE(6), height: buf.readUInt16LE(8) };
4398
+ }
4399
+ if (mime === "image/bmp" && buf.length >= 26) {
4400
+ return { width: buf.readInt32LE(18), height: Math.abs(buf.readInt32LE(22)) };
4401
+ }
4402
+ if (mime === "image/webp" && buf.length >= 30) {
4403
+ if (buf.slice(12, 16).toString("ascii") === "VP8 " && buf.length >= 30) {
4404
+ return { width: buf.readUInt16LE(26) & 16383, height: buf.readUInt16LE(28) & 16383 };
4405
+ }
4406
+ if (buf.slice(12, 17).toString("ascii") === "VP8L" && buf.length >= 25) {
4407
+ const bits = buf.readUInt32LE(21);
4408
+ return { width: (bits & 16383) + 1, height: (bits >> 14 & 16383) + 1 };
4409
+ }
4410
+ }
4411
+ if (mime === "image/jpeg") {
4412
+ let offset = 2;
4413
+ while (offset < buf.length - 9) {
4414
+ if (buf[offset] !== 255) break;
4415
+ const marker = buf[offset + 1];
4416
+ if (marker === 192 || marker === 194) {
4417
+ return { width: buf.readUInt16BE(offset + 7), height: buf.readUInt16BE(offset + 5) };
4418
+ }
4419
+ const segLen = buf.readUInt16BE(offset + 2);
4420
+ offset += 2 + segLen;
4421
+ }
4422
+ }
4423
+ } catch {
4424
+ }
4425
+ return null;
4426
+ }
4427
+ function detectCapabilities() {
4428
+ const caps = ["file-stream"];
4429
+ try {
4430
+ execFileSync3("rg", ["--version"], { timeout: 5e3, stdio: "pipe", windowsHide: true });
4431
+ caps.push("rg");
4432
+ } catch {
4433
+ }
4434
+ return caps;
4435
+ }
4436
+ var MAX_READ_WORDS = 25e3;
4437
+ var DEFAULT_READ_LINES = 2e3;
4438
+ var MAX_READ_FILE_SIZE = 10 * 1024 * 1024;
4439
+ function normalizePath(p) {
4440
+ if (PLATFORM !== "win32") return p;
4441
+ const m = p.match(/^\/([A-Za-z])\/(.*)/);
4442
+ if (m) return `${m[1].toUpperCase()}:\\${m[2].replace(/\//g, "\\")}`;
4443
+ return p;
4444
+ }
4445
+ function safeScanAgentsMDs(filePath) {
4446
+ try {
4447
+ return scanAgentsMDChain(filePath);
4448
+ } catch {
4449
+ return [];
4450
+ }
4451
+ }
4452
+ function handleRead(params) {
4453
+ try {
4454
+ const filePath = normalizePath(params.file_path);
4455
+ if (!path5.isAbsolute(filePath)) {
4456
+ return { error: "file_path must be absolute" };
4457
+ }
4458
+ if (!fs6.existsSync(filePath)) {
4459
+ return { error: `File not found: ${filePath}` };
4460
+ }
4461
+ const stat = fs6.statSync(filePath);
4462
+ if (!stat.isFile()) {
4463
+ return { error: `Not a file: ${filePath}` };
4464
+ }
4465
+ if (stat.size > MAX_READ_FILE_SIZE) {
4466
+ return { error: `File too large (${(stat.size / 1024 / 1024).toFixed(1)}MB, max 10MB). Use offset and limit for range reading.` };
4467
+ }
4468
+ const rawBuf = fs6.readFileSync(filePath);
4469
+ const cortexMDs = safeScanAgentsMDs(filePath);
4470
+ const imageType = detectImageType(rawBuf);
4471
+ if (imageType) {
4472
+ const dims = extractImageDimensions(rawBuf, imageType);
4473
+ return {
4474
+ image: {
4475
+ data: rawBuf.toString("base64"),
4476
+ mimeType: imageType,
4477
+ ...dims ? { width: dims.width, height: dims.height } : {},
4478
+ originalSize: rawBuf.length
4479
+ },
4480
+ cortexMDs
4481
+ };
4482
+ }
4483
+ if (rawBuf.length >= 4 && rawBuf[0] === 37 && rawBuf[1] === 80 && rawBuf[2] === 68 && rawBuf[3] === 70) {
4484
+ return { pdf: { data: rawBuf.toString("base64"), originalSize: rawBuf.length }, cortexMDs };
4485
+ }
4486
+ const encoding = detectEncoding(rawBuf);
4487
+ const content = rawBuf.toString(encoding);
4488
+ const lines = content.split("\n");
4489
+ const offset = params.offset || 0;
4490
+ const limit = params.limit || DEFAULT_READ_LINES;
4491
+ const sliced = lines.slice(offset, offset + limit);
4492
+ const numbered = sliced.map((line, i) => `${offset + i + 1} ${line}`).join("\n");
4493
+ const wordCount = countWords(numbered);
4494
+ if (wordCount > MAX_READ_WORDS) {
4495
+ const suggestedLimit = Math.max(1, Math.floor(limit * (MAX_READ_WORDS / wordCount) * 0.9));
4496
+ return {
4497
+ error: `File content too large (~${wordCount} words, limit is ${MAX_READ_WORDS}). Use offset and limit for range reading. Total lines: ${lines.length}. Suggested: limit=${suggestedLimit} to stay within bounds.`
4498
+ };
4499
+ }
4500
+ return { content: numbered, cortexMDs };
4501
+ } catch (err) {
4502
+ return { error: err.message };
4503
+ }
4504
+ }
4505
+ function handleFileStat(params) {
4506
+ try {
4507
+ const filePath = normalizePath(params.file_path);
4508
+ if (!path5.isAbsolute(filePath)) {
4509
+ return { error: "file_path must be absolute" };
4510
+ }
4511
+ const stat = fs6.statSync(filePath);
4512
+ if (!stat.isFile()) {
4513
+ return { error: `Not a file: ${filePath}` };
4514
+ }
4515
+ return { size: stat.size, name: path5.basename(filePath), mtimeMs: stat.mtimeMs };
4516
+ } catch (err) {
4517
+ const e = err;
4518
+ if (e.code === "ENOENT") return { error: `File not found: ${params.file_path}` };
4519
+ return { error: e.message };
4520
+ }
4521
+ }
4522
+ function handleWrite(params) {
4523
+ try {
4524
+ const filePath = normalizePath(params.file_path);
4525
+ if (!path5.isAbsolute(filePath)) {
4526
+ return { error: "file_path must be absolute" };
4527
+ }
4528
+ const dir = path5.dirname(filePath);
4529
+ fs6.mkdirSync(dir, { recursive: true });
4530
+ let content = params.content;
4531
+ if (fs6.existsSync(filePath)) {
4532
+ try {
4533
+ const existing = fs6.readFileSync(filePath, "utf8");
4534
+ const lineEnding = detectLineEnding(existing);
4535
+ if (lineEnding === "\r\n") {
4536
+ content = content.replace(/\r\n/g, "\n").replace(/\n/g, "\r\n");
4537
+ }
4538
+ } catch {
4539
+ }
4540
+ }
4541
+ fs6.writeFileSync(filePath, content, "utf8");
4542
+ return {
4543
+ success: true,
4544
+ cortexMDs: safeScanAgentsMDs(filePath)
4545
+ };
4546
+ } catch (err) {
4547
+ return { error: err.message };
4548
+ }
4549
+ }
4550
+ function handleEdit(params) {
4551
+ try {
4552
+ const filePath = normalizePath(params.file_path);
4553
+ if (!path5.isAbsolute(filePath)) {
4554
+ return { error: "file_path must be absolute" };
4555
+ }
4556
+ const rawBuf = fs6.readFileSync(filePath);
4557
+ const encoding = detectEncoding(rawBuf);
4558
+ const rawContent = rawBuf.toString(encoding);
4559
+ const originalLineEnding = detectLineEnding(rawContent);
4560
+ const content = rawContent.replace(/\r\n/g, "\n");
4561
+ const oldStr = (params.old_string || "").replace(/\r\n/g, "\n");
4562
+ const newStr = (params.new_string || "").replace(/\r\n/g, "\n");
4563
+ if (!oldStr) {
4564
+ return { error: "old_string is required" };
4565
+ }
4566
+ const buildResult = () => ({
4567
+ success: true,
4568
+ cortexMDs: safeScanAgentsMDs(filePath)
4569
+ });
4570
+ if (params.replace_all) {
4571
+ if (!content.includes(oldStr)) {
4572
+ return { error: "old_string not found in file" };
4573
+ }
4574
+ const result2 = content.split(oldStr).join(newStr);
4575
+ const final2 = originalLineEnding === "\r\n" ? result2.replace(/\n/g, "\r\n") : result2;
4576
+ fs6.writeFileSync(filePath, final2, encoding);
4577
+ return buildResult();
4578
+ }
4579
+ const firstIdx = content.indexOf(oldStr);
4580
+ if (firstIdx === -1) {
4581
+ return { error: "old_string not found in file" };
4582
+ }
4583
+ const secondIdx = content.indexOf(oldStr, firstIdx + 1);
4584
+ if (secondIdx !== -1) {
4585
+ return { error: "old_string is not unique in file (found at least 2 occurrences). Provide more context to make it unique, or use replace_all." };
4586
+ }
4587
+ const result = content.replace(oldStr, () => newStr);
4588
+ const final = originalLineEnding === "\r\n" ? result.replace(/\n/g, "\r\n") : result;
4589
+ fs6.writeFileSync(filePath, final, encoding);
4590
+ return buildResult();
4591
+ } catch (err) {
4592
+ return { error: err.message };
4593
+ }
4594
+ }
4595
+ var GLOB_MAX_RESULTS = 500;
4596
+ var VCS_DIRS = /* @__PURE__ */ new Set([".git", ".svn", ".hg", "node_modules", "__pycache__", ".tox", ".mypy_cache"]);
4597
+ async function handleGlob(params) {
4598
+ try {
4599
+ const pattern = params.pattern;
4600
+ const cwd = normalizePath(params.path || (PLATFORM === "win32" ? "C:\\" : process.cwd()));
4601
+ if (!fs6.existsSync(cwd)) {
4602
+ return { error: `Directory not found: ${cwd}` };
4603
+ }
4604
+ const shell = resolveBash("bash");
4605
+ if (!shell) return { files: [], truncated: false };
4606
+ const limit = GLOB_MAX_RESULTS + 1;
4607
+ const result = await spawnCommand(shell, [
4608
+ "-c",
4609
+ `shopt -s globstar nullglob 2>/dev/null; cd -- "$1" 2>/dev/null || exit 1; i=0; for f in $2; do echo "$f"; i=$((i+1)); [ $i -ge ${limit} ] && break; done`,
4610
+ "--",
4611
+ cwd,
4612
+ pattern
4613
+ ], 3e4);
4614
+ return formatGlobResult(result, cwd);
4615
+ } catch (err) {
4616
+ return { error: err.message };
4617
+ }
4618
+ }
4619
+ function formatGlobResult(result, cwd) {
4620
+ if (result.exitCode !== 0 && !result.stdout.trim()) {
4621
+ return { files: [], truncated: false };
4622
+ }
4623
+ let files = result.stdout.trim().split("\n").filter(Boolean);
4624
+ const truncated = files.length > GLOB_MAX_RESULTS;
4625
+ if (truncated) files = files.slice(0, GLOB_MAX_RESULTS);
4626
+ files = files.map((f) => path5.isAbsolute(f) ? f : path5.resolve(cwd, f));
4627
+ files = files.filter((f) => {
4628
+ const parts = path5.relative(cwd, f).split(path5.sep);
4629
+ return !parts.some((p) => VCS_DIRS.has(p));
4630
+ });
4631
+ return { files, truncated };
4632
+ }
4633
+ var GREP_VCS_EXCLUDES = [".git", ".svn", ".hg", "node_modules", "__pycache__"];
4634
+ function buildRgArgs(params) {
4635
+ const args = [];
4636
+ const mode = params.output_mode || "files_with_matches";
4637
+ if (mode === "files_with_matches") {
4638
+ args.push("-l");
4639
+ } else if (mode === "count") {
4640
+ args.push("-c");
4641
+ } else {
4642
+ if (params["-n"] !== false) args.push("-n");
4643
+ if (params["-A"] != null) args.push("-A", String(params["-A"]));
4644
+ if (params["-B"] != null) args.push("-B", String(params["-B"]));
4645
+ const ctx = params["-C"] ?? params.context;
4646
+ if (ctx != null) args.push("-C", String(ctx));
4647
+ }
4648
+ if (params["-i"]) args.push("-i");
4649
+ if (params.multiline) args.push("-U", "--multiline-dotall");
4650
+ if (params.glob) args.push("--glob", params.glob);
4651
+ if (params.type) args.push("--type", params.type);
4652
+ for (const dir of GREP_VCS_EXCLUDES) {
4653
+ args.push("--glob", `!${dir}`);
4654
+ }
4655
+ args.push("--max-columns", "500");
4656
+ args.push("--", params.pattern);
4657
+ if (params.path) args.push(normalizePath(params.path));
4658
+ return args;
4659
+ }
4660
+ async function handleGrepFallback(params) {
4661
+ const args = ["-rn"];
4662
+ const mode = params.output_mode || "files_with_matches";
4663
+ if (mode === "files_with_matches") args.push("-l");
4664
+ else if (mode === "count") args.push("-c");
4665
+ if (params["-i"]) args.push("-i");
4666
+ args.push("--", params.pattern);
4667
+ args.push(normalizePath(params.path || "."));
4668
+ const result = await spawnCommand("grep", args, 3e4);
4669
+ return { output: result.stdout };
4670
+ }
4671
+ async function handleGrep(params) {
4672
+ try {
4673
+ const rgArgs = buildRgArgs(params);
4674
+ const result = await spawnCommand("rg", rgArgs, 3e4);
4675
+ if (result.exitCode === 127 || result.stderr.includes("not found")) {
4676
+ return handleGrepFallback(params);
4677
+ }
4678
+ if (result.exitCode === 2) {
4679
+ return { error: result.stderr.trim() || "grep search error" };
4680
+ }
4681
+ let output = result.stdout;
4682
+ const headLimit = params.head_limit === 0 ? Infinity : params.head_limit ?? 250;
4683
+ const offset = params.offset ?? 0;
4684
+ if (output && (offset > 0 || headLimit < Infinity)) {
4685
+ const lines = output.split("\n");
4686
+ const sliced = lines.slice(offset, offset + headLimit);
4687
+ const remaining = lines.length - offset - sliced.length;
4688
+ output = sliced.join("\n");
4689
+ if (remaining > 0) {
4690
+ output += `
4691
+ [... ${remaining} more entries, use offset to paginate]`;
4692
+ }
4693
+ }
4694
+ return { output: output || "" };
4695
+ } catch (err) {
4696
+ return { error: err.message };
4697
+ }
4698
+ }
4699
+ function settle(result) {
4700
+ return result.error ? { success: false, error: result.error } : { success: true, data: result };
4701
+ }
4702
+ async function handleBashCommand(params) {
4703
+ if (params.run_in_background) {
4704
+ const { pid } = execBashBackground(params.command);
4705
+ return {
4706
+ success: true,
4707
+ data: { stdout: `Background process started with PID ${pid}`, stderr: "", exitCode: 0 }
4708
+ };
4709
+ }
4710
+ const timeout = Math.min(params.timeout || 12e4, 6e5);
4711
+ return { success: true, data: await execBash(params.command, timeout) };
4712
+ }
4713
+ var COMMAND_HANDLERS = {
4714
+ bash: handleBashCommand,
4715
+ read: async (params) => settle(handleRead(params)),
4716
+ "file.stat": async (params) => settle(handleFileStat(params)),
4717
+ write: async (params) => settle(handleWrite(params)),
4718
+ edit: async (params) => settle(handleEdit(params)),
4719
+ glob: async (params) => settle(await handleGlob(params)),
4720
+ grep: async (params) => settle(await handleGrep(params))
4721
+ };
4722
+ async function handleCommand(action, params) {
4723
+ if (!Object.hasOwn(COMMAND_HANDLERS, action)) return { success: false, error: `Unknown action: ${action}` };
4724
+ return COMMAND_HANDLERS[action](params);
4725
+ }
4726
+ var ws = null;
4727
+ var heartbeatTimer = null;
4728
+ var reconnectDelay = 1e3;
4729
+ var MAX_RECONNECT_DELAY = 3e4;
4730
+ function sendFrame(socket, frame) {
4731
+ if (socket && socket.readyState === wrapper_default.OPEN) socket.send(JSON.stringify(frame));
4732
+ }
4733
+ async function runCommand(frame) {
4734
+ const currentWs = ws;
4735
+ log4.info(`Executing ${frame.action}: ${JSON.stringify(frame.params).substring(0, 100)}`);
4736
+ let outcome;
4737
+ try {
4738
+ outcome = await handleCommand(frame.action, frame.params || {});
4739
+ } catch (err) {
4740
+ outcome = { success: false, error: err.message };
4741
+ }
4742
+ sendFrame(currentWs, { type: "result", commandId: frame.commandId, ...outcome });
4743
+ }
4744
+ function applyUpdate(frame) {
4745
+ const currentWs = ws;
4746
+ handleUpdateMessage(frame, {
4747
+ sendResult: (ok, error) => sendFrame(currentWs, {
4748
+ type: "update-result",
4749
+ updateId: frame.updateId,
4750
+ device: DEVICE_NAME,
4751
+ hash: frame.hash,
4752
+ ok,
4753
+ ...error ? { error } : {}
4754
+ }),
4755
+ closeWs: () => {
4756
+ try {
4757
+ currentWs?.close(1e3, "self-update");
4758
+ } catch {
4759
+ }
4760
+ },
4761
+ respawn: defaultRespawn,
4762
+ exit: (code) => process.exit(code)
4763
+ });
4764
+ }
4765
+ function connect2() {
4766
+ const url = SERVER_URL;
4767
+ const headers = buildClientHeaders(CLIENT_TOKEN);
4768
+ log4.info(`Connecting to ${url} as "${DEVICE_NAME}" (${PLATFORM})${headers ? " [token]" : " [no-token]"}...`);
4769
+ ws = headers ? new wrapper_default(url, { headers }) : new wrapper_default(url);
4770
+ ws.on("open", () => {
4771
+ log4.info(`Connected to server`);
4772
+ reconnectDelay = 1e3;
4773
+ const capabilities = detectCapabilities();
4774
+ const gpuCount = detectGpuCount();
4775
+ sendFrame(ws, {
4776
+ type: "hello",
4777
+ device: DEVICE_NAME,
4778
+ platform: PLATFORM,
4779
+ capabilities,
4780
+ gpuCount,
4781
+ bundleHash: BUNDLE_HASH,
4782
+ pid: process.pid
4783
+ });
4784
+ if (heartbeatTimer) clearInterval(heartbeatTimer);
4785
+ heartbeatTimer = setInterval(() => {
4786
+ sendFrame(ws, { type: "heartbeat", device: DEVICE_NAME, timestamp: Date.now() });
4787
+ }, HEARTBEAT_INTERVAL_MS);
4788
+ });
4789
+ ws.on("message", async (raw) => {
4790
+ let msg;
4791
+ try {
4792
+ msg = JSON.parse(raw.toString());
4793
+ } catch {
4794
+ return;
4795
+ }
4796
+ if (isOpenStream(msg)) {
4797
+ openReverseStream(msg, { controlUrl: SERVER_URL, headers: buildClientHeaders(CLIENT_TOKEN) });
4798
+ return;
4799
+ }
4800
+ if (isOpenFileStream(msg)) {
4801
+ openFileStream(msg, {
4802
+ controlUrl: SERVER_URL,
4803
+ headers: buildClientHeaders(CLIENT_TOKEN),
4804
+ normalizePath
4805
+ });
4806
+ return;
4807
+ }
4808
+ const frame = msg;
4809
+ if (frame?.type === "update") {
4810
+ applyUpdate(frame);
4811
+ return;
4812
+ }
4813
+ if (frame?.type === "command" && frame.commandId) {
4814
+ await runCommand(frame);
4815
+ }
4816
+ });
4817
+ ws.on("close", (code, reason) => {
4818
+ log4.info(`Disconnected (code=${code}, reason=${reason?.toString() || "none"})`);
4819
+ cleanup();
4820
+ if (code === 4002 || code === 4005) {
4821
+ const rejection = code === 4005 ? "unknown device" : "device already connected";
4822
+ log4.info(`Server rejected connection (${rejection}). Exiting.`);
4823
+ process.exit(1);
4824
+ }
4825
+ scheduleReconnect();
4826
+ });
4827
+ ws.on("error", (err) => {
4828
+ log4.error(`WebSocket error: ${err.message}`);
4829
+ });
4830
+ }
4831
+ function cleanup() {
4832
+ if (heartbeatTimer) {
4833
+ clearInterval(heartbeatTimer);
4834
+ heartbeatTimer = null;
4835
+ }
4836
+ ws = null;
4837
+ }
4838
+ function scheduleReconnect() {
4839
+ log4.info(`Reconnecting in ${reconnectDelay / 1e3}s...`);
4840
+ setTimeout(() => {
4841
+ reconnectDelay = Math.min(reconnectDelay * 2, MAX_RECONNECT_DELAY);
4842
+ connect2();
4843
+ }, reconnectDelay);
4844
+ }
4845
+ function shutdown() {
4846
+ log4.info("Shutting down...");
4847
+ if (heartbeatTimer) clearInterval(heartbeatTimer);
4848
+ if (ws) {
4849
+ try {
4850
+ ws.close(1e3, "Client shutting down");
4851
+ } catch {
4852
+ }
4853
+ }
4854
+ process.exit(0);
4855
+ }
4856
+ process.on("SIGINT", shutdown);
4857
+ process.on("SIGTERM", shutdown);
4858
+ log4.info(`Starting: device="${DEVICE_NAME}", platform="${PLATFORM}", server=${SERVER_URL}`);
4859
+ connect2();