@ultrst-armada/krnl 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/README.md +95 -2
  2. package/package.json +75 -4
  3. package/packages/cli/dist/K_ENT_Entity-PQ5MURQY-ZG6FZXXX.js +13 -0
  4. package/packages/cli/dist/K_LIB_Krnl_Aiko_Client-OPZAVZCW-K4CRQYA5.js +8 -0
  5. package/packages/cli/dist/K_LIB_Krnl_Ep_Tools-ROOE2TQF-LNPXZYOE.js +110 -0
  6. package/packages/cli/dist/K_LIB_Krnl_Frontend_Builder-2ZDUH6PF-3ALZPNX4.js +11 -0
  7. package/packages/cli/dist/K_LIB_Krnl_Frontend_Generator-UYNRNX2X-PJTICYSW.js +11 -0
  8. package/packages/cli/dist/K_LIB_Krnl_Registry_Client-NXV6D2QW-M5TYU55O.js +8 -0
  9. package/packages/cli/dist/K_LIB_Krnl_SubApp_Engine-7HR5HWW2-H6STOXRK.js +20 -0
  10. package/packages/cli/dist/K_LIB_Krnl_SubApp_Registry-7XYGDKJK-XPJXSF7D.js +19 -0
  11. package/packages/cli/dist/K_LIB_Krnl_SubApp_Worker_Host-CQVTGGG7-CUYGTWOW.js +7 -0
  12. package/packages/cli/dist/K_LIB_Krnl_System_App_Adapter-M6FJKLGU-VR6T4N6J.js +17 -0
  13. package/packages/cli/dist/K_LIB_Krnl_System_Base_Functionality_APIs-ZZUZ6ZG5-RLJ4QWDP.js +58 -0
  14. package/packages/cli/dist/K_LIB_Krnl_System_Magnetic_Loader-XBQO2KXF-BOQGUASC.js +22 -0
  15. package/packages/cli/dist/K_LIB_Krnl_System_Unified_Http_Adapter-RCEGP3OG-XJI7KIT5.js +8 -0
  16. package/packages/cli/dist/K_LIB_Krnl_Telemetry-77FRZ3KV-K5VCWAFW.js +9 -0
  17. package/packages/cli/dist/bin/krnl.cjs +9758 -0
  18. package/packages/cli/dist/bin/krnl.d.cts +1 -0
  19. package/packages/cli/dist/bin/krnl.d.ts +1 -0
  20. package/packages/cli/dist/bin/krnl.js +2006 -0
  21. package/packages/cli/dist/chunk-3TRM6CYL.js +152 -0
  22. package/packages/cli/dist/chunk-5JDK35TG.js +3872 -0
  23. package/packages/cli/dist/chunk-63PTK33I.js +997 -0
  24. package/packages/cli/dist/chunk-6NIKAMUZ.js +82 -0
  25. package/packages/cli/dist/chunk-BOXWWXQG.js +400 -0
  26. package/packages/cli/dist/chunk-EEKLK7QJ.js +565 -0
  27. package/packages/cli/dist/chunk-EG7T2IAD.js +107 -0
  28. package/packages/cli/dist/chunk-F5EHXE2O.js +1036 -0
  29. package/packages/cli/dist/chunk-F65ANSQG.js +269 -0
  30. package/packages/cli/dist/chunk-FDNCADFE.js +71 -0
  31. package/packages/cli/dist/chunk-GDLRMDAN.js +127 -0
  32. package/packages/cli/dist/chunk-HWMTCMOS.js +656 -0
  33. package/packages/cli/dist/chunk-I74QIQOD.js +5536 -0
  34. package/packages/cli/dist/chunk-JTLSTO25.js +71 -0
  35. package/packages/cli/dist/chunk-JULBBJ27.js +1033 -0
  36. package/packages/cli/dist/chunk-OHVMVRBP.js +117 -0
  37. package/packages/cli/dist/chunk-P2PCLEKX.js +666 -0
  38. package/packages/cli/dist/chunk-PJQIUOX2.js +7767 -0
  39. package/packages/cli/dist/chunk-PPOF3DJW.js +471 -0
  40. package/packages/cli/dist/chunk-Q45257P6.js +173 -0
  41. package/packages/cli/dist/chunk-QNROWGBI.js +1036 -0
  42. package/packages/cli/dist/chunk-RJNYUXZD.js +977 -0
  43. package/packages/cli/dist/chunk-SRTOPJ5W.js +104 -0
  44. package/packages/cli/dist/chunk-TCEX3MPS.js +702 -0
  45. package/packages/cli/dist/chunk-TNOAJO2J.js +675 -0
  46. package/packages/cli/dist/chunk-UR2SUCSF.js +701 -0
  47. package/packages/cli/dist/chunk-X5LOIFM7.js +68 -0
  48. package/packages/cli/dist/chunk-XIRFOO3H.js +589 -0
  49. package/packages/cli/dist/chunk-ZAAV3JXQ.js +809 -0
  50. package/packages/cli/dist/index.cjs +7798 -0
  51. package/packages/cli/dist/index.d.cts +7 -0
  52. package/packages/cli/dist/index.d.ts +7 -0
  53. package/packages/cli/dist/index.js +29 -0
  54. package/packages/cli/package.json +34 -0
  55. package/packages/core/dist/K_ENT_Entity-4MB7CU4A.js +12 -0
  56. package/packages/core/dist/K_ENT_Entity-DEJGIDGH.js +12 -0
  57. package/packages/core/dist/K_ENT_Entity-FXZO5UZ2.js +12 -0
  58. package/packages/core/dist/K_ENT_Entity-HDSCXC5F.js +12 -0
  59. package/packages/core/dist/K_ENT_Entity-JILABHLW.js +12 -0
  60. package/packages/core/dist/K_ENT_Entity-PQ5MURQY.js +13 -0
  61. package/packages/core/dist/K_ENT_Entity-ROAKDIHW.js +12 -0
  62. package/packages/core/dist/K_ENT_Entity-TBVFSKDV.js +12 -0
  63. package/packages/core/dist/K_ENT_Entity-ZFLKG3JO.js +12 -0
  64. package/packages/core/dist/K_LIB_Krnl_Aiko_Client-OPZAVZCW.js +8 -0
  65. package/packages/core/dist/K_LIB_Krnl_Ep_Tools-ROOE2TQF.js +110 -0
  66. package/packages/core/dist/K_LIB_Krnl_Frontend_Builder-2ZDUH6PF.js +9 -0
  67. package/packages/core/dist/K_LIB_Krnl_Frontend_Generator-UYNRNX2X.js +9 -0
  68. package/packages/core/dist/K_LIB_Krnl_Registry_Client-NXV6D2QW.js +8 -0
  69. package/packages/core/dist/K_LIB_Krnl_SubApp_Engine-7HR5HWW2.js +20 -0
  70. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-4C6GBQAG.js +18 -0
  71. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-6V23A6F6.js +18 -0
  72. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-7XYGDKJK.js +19 -0
  73. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-DYLLC5G2.js +18 -0
  74. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-F4FOFAUP.js +18 -0
  75. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-FBOXXMI3.js +18 -0
  76. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-Q73BWLNP.js +18 -0
  77. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-QM2C4MVA.js +18 -0
  78. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-QUGI6SMP.js +18 -0
  79. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-RGMTBHNP.js +18 -0
  80. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-RWR7UNDW.js +18 -0
  81. package/packages/core/dist/K_LIB_Krnl_SubApp_Worker_Host-CQVTGGG7.js +7 -0
  82. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-32MFJJ5Z.js +17 -0
  83. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-4J4CEWRY.js +17 -0
  84. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-A366YHF2.js +17 -0
  85. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-LK4LYJHI.js +17 -0
  86. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-M6FJKLGU.js +17 -0
  87. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-NW3K63II.js +17 -0
  88. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-QDHTI5ZV.js +17 -0
  89. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-VHCT6VIW.js +17 -0
  90. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-WBRKF24R.js +17 -0
  91. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-XKYQYT6Q.js +17 -0
  92. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-Z2PWZYDZ.js +17 -0
  93. package/packages/core/dist/K_LIB_Krnl_System_Base_Functionality_APIs-ZZUZ6ZG5.js +58 -0
  94. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-2EZU7QF4.js +21 -0
  95. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-6G3AQNAV.js +21 -0
  96. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-B2NZMQUG.js +21 -0
  97. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-C2RABMZP.js +21 -0
  98. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-HHE3NZ4F.js +21 -0
  99. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-LHFGR6WK.js +21 -0
  100. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-M74BLM3N.js +21 -0
  101. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-PT6ZA6EA.js +21 -0
  102. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-SP52V3CX.js +21 -0
  103. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-XBQO2KXF.js +22 -0
  104. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-YNSEUHJJ.js +21 -0
  105. package/packages/core/dist/K_LIB_Krnl_System_Unified_Http_Adapter-M6SBHIVA.js +8 -0
  106. package/packages/core/dist/K_LIB_Krnl_System_Unified_Http_Adapter-RCEGP3OG.js +8 -0
  107. package/packages/core/dist/K_LIB_Krnl_Telemetry-77FRZ3KV.js +9 -0
  108. package/packages/core/dist/chunk-33L2J7V7.js +82 -0
  109. package/packages/core/dist/chunk-3ES4K2ZP.js +817 -0
  110. package/packages/core/dist/chunk-3SMHVVLL.js +82 -0
  111. package/packages/core/dist/chunk-3UEZ7JQA.js +4877 -0
  112. package/packages/core/dist/chunk-3XIE6KBD.js +4877 -0
  113. package/packages/core/dist/chunk-46ZLCML6.js +107 -0
  114. package/packages/core/dist/chunk-4UEL3DWJ.js +107 -0
  115. package/packages/core/dist/chunk-54GWZ5PC.js +82 -0
  116. package/packages/core/dist/chunk-6QCYRS5L.js +127 -0
  117. package/packages/core/dist/chunk-6ULMHNXR.js +104 -0
  118. package/packages/core/dist/chunk-7WUETJEV.js +117 -0
  119. package/packages/core/dist/chunk-A5KRAYDB.js +107 -0
  120. package/packages/core/dist/chunk-ANEAZ3PO.js +107 -0
  121. package/packages/core/dist/chunk-BE76RL6F.js +82 -0
  122. package/packages/core/dist/chunk-CIARVYDO.js +107 -0
  123. package/packages/core/dist/chunk-CR2ANE62.js +107 -0
  124. package/packages/core/dist/chunk-DI27MOR7.js +173 -0
  125. package/packages/core/dist/chunk-E6RLFHM5.js +596 -0
  126. package/packages/core/dist/chunk-EELAPMNV.js +4877 -0
  127. package/packages/core/dist/chunk-ENZ2RQVJ.js +107 -0
  128. package/packages/core/dist/chunk-F2U6CX4F.js +4877 -0
  129. package/packages/core/dist/chunk-FKG64OHL.js +82 -0
  130. package/packages/core/dist/chunk-FYAZJYM5.js +772 -0
  131. package/packages/core/dist/chunk-G4NP4RDQ.js +82 -0
  132. package/packages/core/dist/chunk-GADIRLRS.js +473 -0
  133. package/packages/core/dist/chunk-GR6CSLQJ.js +772 -0
  134. package/packages/core/dist/chunk-HDS7AT6O.js +772 -0
  135. package/packages/core/dist/chunk-HIMEZUU2.js +71 -0
  136. package/packages/core/dist/chunk-IB4UHG5I.js +596 -0
  137. package/packages/core/dist/chunk-J7ZYNVRS.js +772 -0
  138. package/packages/core/dist/chunk-JVLZU4K7.js +604 -0
  139. package/packages/core/dist/chunk-JYXXI7Q3.js +82 -0
  140. package/packages/core/dist/chunk-K54K2KZW.js +192 -0
  141. package/packages/core/dist/chunk-K6VHLBNH.js +3316 -0
  142. package/packages/core/dist/chunk-KCBP7ZYA.js +596 -0
  143. package/packages/core/dist/chunk-KFQGP6VL.js +33 -0
  144. package/packages/core/dist/chunk-KIUEUI7K.js +82 -0
  145. package/packages/core/dist/chunk-LB67NIZP.js +949 -0
  146. package/packages/core/dist/chunk-LDTYFUNW.js +596 -0
  147. package/packages/core/dist/chunk-MLVWARD4.js +596 -0
  148. package/packages/core/dist/chunk-MPYVXHKO.js +2777 -0
  149. package/packages/core/dist/chunk-MRQ3MITU.js +772 -0
  150. package/packages/core/dist/chunk-MVUN7I7O.js +107 -0
  151. package/packages/core/dist/chunk-NDDOIRW7.js +596 -0
  152. package/packages/core/dist/chunk-O3KDB5MH.js +3330 -0
  153. package/packages/core/dist/chunk-OEINUDSE.js +400 -0
  154. package/packages/core/dist/chunk-OPDENPT4.js +4877 -0
  155. package/packages/core/dist/chunk-P6XEM2LA.js +429 -0
  156. package/packages/core/dist/chunk-QKMRSQV4.js +82 -0
  157. package/packages/core/dist/chunk-R6CCWALL.js +4877 -0
  158. package/packages/core/dist/chunk-RAMMOO73.js +774 -0
  159. package/packages/core/dist/chunk-S3FTZFG6.js +772 -0
  160. package/packages/core/dist/chunk-T2ZVN434.js +4877 -0
  161. package/packages/core/dist/chunk-TFHLDMIA.js +107 -0
  162. package/packages/core/dist/chunk-TI3QUCIJ.js +107 -0
  163. package/packages/core/dist/chunk-TR2BAIGI.js +107 -0
  164. package/packages/core/dist/chunk-UGVVJKC6.js +4877 -0
  165. package/packages/core/dist/chunk-V2DX7YIU.js +984 -0
  166. package/packages/core/dist/chunk-W4IHYUYD.js +772 -0
  167. package/packages/core/dist/chunk-W6WBG5OY.js +4877 -0
  168. package/packages/core/dist/chunk-WN3M7O7H.js +3312 -0
  169. package/packages/core/dist/chunk-WR3NCU7U.js +4877 -0
  170. package/packages/core/dist/chunk-XC6B6L27.js +82 -0
  171. package/packages/core/dist/chunk-XNSE64ZY.js +3316 -0
  172. package/packages/core/dist/chunk-XROES2WN.js +634 -0
  173. package/packages/core/dist/chunk-XSCKNRCZ.js +5020 -0
  174. package/packages/core/dist/chunk-XVABPAUZ.js +82 -0
  175. package/packages/core/dist/chunk-YOBCB5C5.js +596 -0
  176. package/packages/core/dist/chunk-YUK6Q563.js +666 -0
  177. package/packages/core/dist/chunk-YXGL3ZEU.js +1030 -0
  178. package/packages/core/dist/chunk-ZINJ5OUX.js +596 -0
  179. package/packages/core/dist/chunk-ZPFD4BIQ.js +604 -0
  180. package/packages/core/dist/chunk-ZQZBFG6F.js +4826 -0
  181. package/packages/core/dist/chunk-ZZFRJGXM.js +4877 -0
  182. package/packages/core/dist/index.cjs +760 -0
  183. package/packages/core/dist/index.d.cts +360 -0
  184. package/packages/core/dist/index.d.ts +360 -0
  185. package/packages/core/dist/index.js +707 -0
  186. package/packages/core/package.json +34 -0
  187. package/packages/create-krnl/dist/K_ENT_Entity-PQ5MURQY-R2OH4VXE.js +14 -0
  188. package/packages/create-krnl/dist/K_LIB_Krnl_Aiko_Client-OPZAVZCW-AZM5HF4M.js +9 -0
  189. package/packages/create-krnl/dist/K_LIB_Krnl_Ep_Tools-ROOE2TQF-X5N6SV2S.js +111 -0
  190. package/packages/create-krnl/dist/K_LIB_Krnl_Frontend_Builder-2ZDUH6PF-5PFHF4JU.js +12 -0
  191. package/packages/create-krnl/dist/K_LIB_Krnl_Frontend_Generator-UYNRNX2X-ED33OQPH.js +12 -0
  192. package/packages/create-krnl/dist/K_LIB_Krnl_Registry_Client-NXV6D2QW-YGQLVR4P.js +9 -0
  193. package/packages/create-krnl/dist/K_LIB_Krnl_SubApp_Engine-7HR5HWW2-VM7CTU2L.js +21 -0
  194. package/packages/create-krnl/dist/K_LIB_Krnl_SubApp_Registry-7XYGDKJK-Y2GQFJ7I.js +21 -0
  195. package/packages/create-krnl/dist/K_LIB_Krnl_SubApp_Worker_Host-CQVTGGG7-L3JQWO54.js +8 -0
  196. package/packages/create-krnl/dist/K_LIB_Krnl_System_App_Adapter-M6FJKLGU-KQARASPR.js +19 -0
  197. package/packages/create-krnl/dist/K_LIB_Krnl_System_Base_Functionality_APIs-ZZUZ6ZG5-OF3IGLVL.js +59 -0
  198. package/packages/create-krnl/dist/K_LIB_Krnl_System_Magnetic_Loader-XBQO2KXF-JOLHKOEX.js +24 -0
  199. package/packages/create-krnl/dist/K_LIB_Krnl_System_Unified_Http_Adapter-RCEGP3OG-L46LSHKQ.js +10 -0
  200. package/packages/create-krnl/dist/K_LIB_Krnl_Telemetry-77FRZ3KV-4JUPRR3X.js +10 -0
  201. package/packages/create-krnl/dist/chunk-3TRM6CYL.js +152 -0
  202. package/packages/create-krnl/dist/chunk-3URCB3QS.js +127 -0
  203. package/packages/create-krnl/dist/chunk-5JDK35TG.js +3872 -0
  204. package/packages/create-krnl/dist/chunk-A2XAXDOW.js +812 -0
  205. package/packages/create-krnl/dist/chunk-AN6TMQHG.js +1033 -0
  206. package/packages/create-krnl/dist/chunk-BOXWWXQG.js +400 -0
  207. package/packages/create-krnl/dist/chunk-BPTBREBG.js +38 -0
  208. package/packages/create-krnl/dist/chunk-FDNCADFE.js +71 -0
  209. package/packages/create-krnl/dist/chunk-JTLSTO25.js +71 -0
  210. package/packages/create-krnl/dist/chunk-M3NCUIPL.js +107 -0
  211. package/packages/create-krnl/dist/chunk-N2EONSOC.js +7769 -0
  212. package/packages/create-krnl/dist/chunk-OHVMVRBP.js +117 -0
  213. package/packages/create-krnl/dist/chunk-Q45257P6.js +173 -0
  214. package/packages/create-krnl/dist/chunk-QGM4M3NI.js +37 -0
  215. package/packages/create-krnl/dist/chunk-RJNYUXZD.js +977 -0
  216. package/packages/create-krnl/dist/chunk-SRTOPJ5W.js +104 -0
  217. package/packages/create-krnl/dist/chunk-UPBIGEC3.js +666 -0
  218. package/packages/create-krnl/dist/chunk-V2DB7UD7.js +82 -0
  219. package/packages/create-krnl/dist/chunk-WMHLIUI6.js +3644 -0
  220. package/packages/create-krnl/dist/chunk-XIRFOO3H.js +589 -0
  221. package/packages/create-krnl/dist/chunk-Y2CEEVZP.js +5536 -0
  222. package/packages/create-krnl/dist/index.cjs +395 -0
  223. package/packages/create-krnl/dist/index.js +372 -0
  224. package/packages/create-krnl/dist/main-DXUMPBND.js +2217 -0
  225. package/packages/create-krnl/dist/wrapper-SDF2VKX3.js +31 -0
  226. package/packages/create-krnl/package.json +23 -0
  227. package/packages/eslint-plugin/dist/index.cjs +439 -0
  228. package/packages/eslint-plugin/dist/index.d.cts +336 -0
  229. package/packages/eslint-plugin/dist/index.d.ts +336 -0
  230. package/packages/eslint-plugin/dist/index.js +416 -0
  231. package/packages/eslint-plugin/package.json +24 -0
  232. package/packages/validate/dist/index.cjs +499 -0
  233. package/packages/validate/dist/index.d.cts +49 -0
  234. package/packages/validate/dist/index.d.ts +49 -0
  235. package/packages/validate/dist/index.js +462 -0
  236. package/packages/validate/package.json +27 -0
@@ -0,0 +1,809 @@
1
+ import {
2
+ Logger
3
+ } from "./chunk-JTLSTO25.js";
4
+
5
+ // ../core/dist/chunk-3ES4K2ZP.js
6
+ import http from "http";
7
+ import fs from "fs";
8
+ import path from "path";
9
+ import { WebSocketServer, WebSocket } from "ws";
10
+ var KrnlMcpProtocol = class {
11
+ system;
12
+ /**
13
+ * @param system
14
+ */
15
+ constructor(system) {
16
+ this.system = system;
17
+ }
18
+ /**
19
+ * Returns the MCP Tools list based on system functionalities.
20
+ */
21
+ async listTools() {
22
+ if (this.system._ingressNetwork) {
23
+ const tools2 = this.system._ingressNetwork.getAggregatedMcpTools();
24
+ return { tools: tools2 };
25
+ }
26
+ const manifest = this.system.getManifest();
27
+ const apiIds = Object.keys(manifest.inputs?.api || manifest.api || {});
28
+ const tools = apiIds.map((fid) => {
29
+ const functionality = this.system.resolveLocalFunctionality ? this.system.resolveLocalFunctionality(fid) : this.system.localFunctionalities.get(fid);
30
+ const description = functionality?.description || `Execute ${fid} on ${this.system.entityName}`;
31
+ let inputSchema = { type: "object", properties: {} };
32
+ if (functionality?.schema?.input) {
33
+ inputSchema.properties = {
34
+ data: { type: "object", description: "Input data for the functionality" }
35
+ };
36
+ }
37
+ return {
38
+ name: fid,
39
+ description,
40
+ inputSchema
41
+ };
42
+ });
43
+ return { tools };
44
+ }
45
+ /**
46
+ * Handles an MCP JSON-RPC request.
47
+ */
48
+ async handleRequest(rpc, opts = {}) {
49
+ const { method, params, id } = rpc;
50
+ if (method === "tools/list") {
51
+ const result = await this.listTools();
52
+ return { jsonrpc: "2.0", id, result };
53
+ }
54
+ if (method === "tools/call") {
55
+ const { name, arguments: args } = params;
56
+ try {
57
+ let result;
58
+ if (this.system._ingressNetwork && name.includes(".")) {
59
+ const parts = name.split(".");
60
+ const prefix = parts[0].toLowerCase();
61
+ const toolName = parts.slice(1).join(".");
62
+ const entry = this.system._ingressNetwork.members.get(prefix);
63
+ if (entry) {
64
+ result = await entry.entity.call(toolName, args, opts);
65
+ } else {
66
+ throw new Error(`Ingress member for prefix '${prefix}' not found.`);
67
+ }
68
+ } else {
69
+ result = await this.system.call(name, args, opts);
70
+ }
71
+ return {
72
+ jsonrpc: "2.0",
73
+ id,
74
+ result: {
75
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
76
+ }
77
+ };
78
+ } catch (error) {
79
+ return {
80
+ jsonrpc: "2.0",
81
+ id,
82
+ error: {
83
+ code: -32e3,
84
+ message: error.message,
85
+ data: {
86
+ errorDocumentation: error.errorDocumentation || null
87
+ }
88
+ }
89
+ };
90
+ }
91
+ }
92
+ if (method === "initialize") {
93
+ return {
94
+ jsonrpc: "2.0",
95
+ id,
96
+ result: {
97
+ protocolVersion: "2024-11-05",
98
+ capabilities: {
99
+ tools: { listChanged: false }
100
+ },
101
+ serverInfo: {
102
+ name: this.system.entityName,
103
+ version: "1.0.0"
104
+ }
105
+ }
106
+ };
107
+ }
108
+ return {
109
+ jsonrpc: "2.0",
110
+ id,
111
+ error: { code: -32601, message: "Method not found" }
112
+ };
113
+ }
114
+ };
115
+ var KrnlAcpProtocol = class {
116
+ system;
117
+ /**
118
+ * @param system
119
+ */
120
+ constructor(system) {
121
+ this.system = system;
122
+ }
123
+ /**
124
+ * ACP Information endpoint.
125
+ */
126
+ getInfo() {
127
+ const manifest = this.system.getManifest();
128
+ return {
129
+ agentId: this.system.entityName,
130
+ type: manifest.systemType,
131
+ version: "1.0.0",
132
+ protocols: ["ACP", "MCP", "KrnlWS"],
133
+ description: `Krnl System Entity: ${this.system.entityName}`
134
+ };
135
+ }
136
+ /**
137
+ * ACP Capabilities endpoint.
138
+ */
139
+ getCapabilities() {
140
+ const manifest = this.system.getManifest();
141
+ return {
142
+ services: Object.keys(manifest.inputs.api).map((fid) => ({
143
+ id: fid,
144
+ name: fid,
145
+ type: "functionality"
146
+ })),
147
+ events: manifest.outputs.events.map((eid) => ({
148
+ id: eid,
149
+ type: "event"
150
+ }))
151
+ };
152
+ }
153
+ /**
154
+ * ACP Message endpoint handler.
155
+ */
156
+ async handleMessage(payload, opts = {}) {
157
+ const { action, data } = payload;
158
+ try {
159
+ const result = await this.system.call(action, data, opts);
160
+ return {
161
+ status: "success",
162
+ result,
163
+ metadata: {
164
+ processedBy: this.system.entityName,
165
+ timestamp: Date.now()
166
+ }
167
+ };
168
+ } catch (error) {
169
+ return {
170
+ status: "error",
171
+ error: error.message,
172
+ errorDocumentation: error.errorDocumentation || null,
173
+ metadata: {
174
+ processedBy: this.system.entityName,
175
+ timestamp: Date.now()
176
+ }
177
+ };
178
+ }
179
+ }
180
+ };
181
+ var krnlUnifiedHttpAdapter = class {
182
+ name = "https";
183
+ system;
184
+ port;
185
+ host;
186
+ server;
187
+ _isExternalServer;
188
+ mcp;
189
+ acp;
190
+ enableFriendlyRouting;
191
+ wss;
192
+ _latestUiSnapshot;
193
+ _uiWsClients;
194
+ _uiSseClients;
195
+ _uiReadyComponents = /* @__PURE__ */ new Set();
196
+ /**
197
+ * @param system
198
+ * @param port
199
+ * @param host
200
+ */
201
+ constructor(system, port, host = "0.0.0.0") {
202
+ this.system = system;
203
+ this.port = port;
204
+ this.host = host;
205
+ this.server = null;
206
+ this._isExternalServer = false;
207
+ this.mcp = new KrnlMcpProtocol(system);
208
+ this.acp = new KrnlAcpProtocol(system);
209
+ this.enableFriendlyRouting = false;
210
+ this.wss = null;
211
+ this._latestUiSnapshot = {};
212
+ this._uiWsClients = /* @__PURE__ */ new Set();
213
+ this._uiSseClients = /* @__PURE__ */ new Set();
214
+ }
215
+ /**
216
+ * Starts the adapter.
217
+ */
218
+ async start(externalServerOrEntity = null, options = {}) {
219
+ if (externalServerOrEntity && typeof externalServerOrEntity.call === "function") {
220
+ this.system = externalServerOrEntity;
221
+ if (options.port) this.port = options.port;
222
+ if (options.host) this.host = options.host;
223
+ return this.start(null);
224
+ }
225
+ const externalServer = externalServerOrEntity;
226
+ if (this.server) return;
227
+ this.wss = new WebSocketServer({ noServer: true });
228
+ const handleUpgrade = (req, socket, head) => {
229
+ const url = new URL(req.url || "", `http://${req.headers.host || "localhost"}`);
230
+ if (url.pathname === "/agent/ws") {
231
+ if (socket.upgraded || socket._krnlUpgraded || !socket.readable) return;
232
+ socket._krnlUpgraded = true;
233
+ try {
234
+ this.wss.handleUpgrade(req, socket, head, (ws) => {
235
+ this._handleAgentWsClient(ws);
236
+ });
237
+ } catch (err) {
238
+ console.warn("[HttpAdapter] WebSocket handleUpgrade ignored:", err?.message || err);
239
+ }
240
+ }
241
+ };
242
+ if (externalServer) {
243
+ this.server = externalServer;
244
+ this._isExternalServer = true;
245
+ this.server.on("request", (req, res) => {
246
+ this._handleRequest(req, res);
247
+ });
248
+ this.server.on("upgrade", handleUpgrade);
249
+ } else {
250
+ this.server = http.createServer((req, res) => {
251
+ this._handleRequest(req, res);
252
+ });
253
+ this.server.on("upgrade", handleUpgrade);
254
+ return new Promise((resolve, reject) => {
255
+ this.server.listen(this.port, this.host, () => {
256
+ Logger.log(`[${this.system.entityName}] Unified HTTP Adapter active on http://${this.host}:${this.port}`);
257
+ resolve();
258
+ });
259
+ this.server.on("error", reject);
260
+ });
261
+ }
262
+ }
263
+ _handleAgentWsClient(ws) {
264
+ this._uiWsClients.add(ws);
265
+ ws.on("message", (data) => {
266
+ try {
267
+ const msg = JSON.parse(data.toString());
268
+ console.log(`[UnifiedHttpAdapter] WS msg type: '${msg.type}', fid: '${msg.fid || ""}', ticketId: '${msg.ticketId || ""}'`);
269
+ if (msg.type === "state" && msg.snapshot) {
270
+ this._latestUiSnapshot = { ...this._latestUiSnapshot, ...msg.snapshot };
271
+ this._broadcastUiSse(this._latestUiSnapshot);
272
+ } else if (msg.type === "component_ready" && msg.fid) {
273
+ this._uiReadyComponents.add(msg.fid);
274
+ } else if (msg.type === "component_unready" && msg.fid) {
275
+ this._uiReadyComponents.delete(msg.fid);
276
+ } else if (msg.type === "component_ready_all" && Array.isArray(msg.fids)) {
277
+ msg.fids.forEach((f) => this._uiReadyComponents.add(f));
278
+ } else if (msg.type === "job_complete" && msg.ticketId) {
279
+ this.system._jobScheduler.resolveTicket(
280
+ msg.ticketId,
281
+ msg.error ? "failed" : "done",
282
+ msg.result,
283
+ msg.error
284
+ );
285
+ }
286
+ } catch (e) {
287
+ }
288
+ });
289
+ ws.on("close", () => {
290
+ this._uiWsClients.delete(ws);
291
+ });
292
+ ws.on("error", () => {
293
+ this._uiWsClients.delete(ws);
294
+ });
295
+ }
296
+ _broadcastUiSse(data) {
297
+ const payload = `data: ${JSON.stringify(data)}
298
+
299
+ `;
300
+ for (const res of this._uiSseClients) {
301
+ if (res.writable) {
302
+ res.write(payload);
303
+ }
304
+ }
305
+ }
306
+ sendWsTrigger(fid, input, ticketId) {
307
+ const msg = JSON.stringify({ action: "trigger", fid, input, ticketId });
308
+ for (const ws of this._uiWsClients) {
309
+ if (ws.readyState === WebSocket.OPEN) {
310
+ ws.send(msg);
311
+ }
312
+ }
313
+ }
314
+ async _handleRequest(req, res) {
315
+ const url = new URL(req.url || "", `http://${req.headers.host || "localhost"}`);
316
+ const reqPath = url.pathname;
317
+ res.setHeader("Access-Control-Allow-Origin", "*");
318
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
319
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type, Mcp-Session-Id");
320
+ if (req.method === "OPTIONS") {
321
+ res.writeHead(204);
322
+ res.end();
323
+ return;
324
+ }
325
+ if (this.system._subAppRegistry?.size > 0) {
326
+ const segments = reqPath.split("/").filter(Boolean);
327
+ const prefix = segments[0]?.toLowerCase();
328
+ if (prefix && this.system._subAppRegistry.has(prefix)) {
329
+ const entry = this.system._subAppRegistry.get(prefix);
330
+ let subPath = "/" + segments.slice(1).join("/") + url.search;
331
+ if (reqPath.endsWith("/") && !subPath.endsWith("/")) subPath += "/";
332
+ if (entry.executionMode === "worker") {
333
+ const fid = segments[1] ?? "heartbeat";
334
+ const body = req.method === "GET" ? Object.fromEntries(url.searchParams.entries()) : await this._readJsonBody(req);
335
+ try {
336
+ const result = await entry.entity.call(fid, body);
337
+ this._sendJson(res, 200, result);
338
+ } catch (err) {
339
+ this._sendJson(res, 200, { status: "error", message: err.message || String(err) });
340
+ }
341
+ } else {
342
+ const originalUrl = req.url;
343
+ req.url = subPath;
344
+ try {
345
+ await entry.entity.unifiedHttpAdapter._handleRequest(req, res);
346
+ } finally {
347
+ req.url = originalUrl;
348
+ }
349
+ }
350
+ return;
351
+ }
352
+ }
353
+ if (this.system._siblingNetwork) {
354
+ const segments = reqPath.split("/").filter(Boolean);
355
+ const prefix = segments[0]?.toLowerCase();
356
+ if (prefix && this.system._siblingNetwork.members.has(prefix)) {
357
+ if (segments.length === 3 && segments[1] === "frontend" && segments[2] === "default" && !reqPath.endsWith("/")) {
358
+ res.writeHead(302, { "Location": reqPath + "/" + url.search });
359
+ res.end();
360
+ return;
361
+ }
362
+ let subPath = "/" + segments.slice(1).join("/") + url.search;
363
+ if (reqPath.endsWith("/") && !subPath.endsWith("/")) subPath += "/";
364
+ await this.system._siblingNetwork.routeHttpRequest(prefix, req, res, subPath);
365
+ return;
366
+ }
367
+ if (segments[0] && segments[1] && segments[0].toLowerCase() !== "default") {
368
+ const key = `${segments[0].toLowerCase()}/${segments[1].toLowerCase()}`;
369
+ if (this.system._siblingNetwork.members.has(key)) {
370
+ await this.system._siblingNetwork.routeHttpRequest(key, req, res, req.url || "/");
371
+ return;
372
+ }
373
+ }
374
+ }
375
+ const isKrnlRoute = reqPath.startsWith("/call/") || reqPath.startsWith("/sse/") || reqPath.startsWith("/ui") || reqPath.startsWith("/mcp") || reqPath.startsWith("/acp") || reqPath === "/agent/job_complete" || reqPath === "/subapps" || reqPath === "/api/subapps" || reqPath === "/manifest" || reqPath === "/health";
376
+ if (reqPath === "/subapps" || reqPath === "/api/subapps") {
377
+ const subappsList = [];
378
+ if (this.system._subApps && this.system._subApps.size > 0) {
379
+ for (const [id, inst] of this.system._subApps.entries()) {
380
+ subappsList.push({
381
+ id,
382
+ state: inst.state,
383
+ manifest: inst.manifest || null,
384
+ operations: Array.from(inst.operations?.values() || []).map((op) => ({
385
+ name: op.name,
386
+ description: op.description || "",
387
+ method: op.method || "POST",
388
+ metadata: op.metadata || {}
389
+ })),
390
+ ui: inst.registration?.ui || inst.manifest?.ui || null,
391
+ loadedAt: inst.loadedAt,
392
+ readyAt: inst.readyAt,
393
+ error: inst.error ? inst.error.message || String(inst.error) : null
394
+ });
395
+ }
396
+ }
397
+ this._sendJson(res, 200, { status: "success", entity: this.system.entityName, subapps: subappsList });
398
+ return;
399
+ }
400
+ if (!isKrnlRoute) {
401
+ if (reqPath === "/inspect" || reqPath.startsWith("/inspect/") || reqPath === "/frontend" || reqPath.startsWith("/frontend/")) {
402
+ if (!this.system._frontend && this.system._entityDataDir) {
403
+ const frontendDir = path.join(this.system._entityDataDir, "frontend");
404
+ if (fs.existsSync(frontendDir)) {
405
+ this.system.enableFrontend({ frontendDir });
406
+ }
407
+ }
408
+ if (this.system._frontend) {
409
+ const subPath = reqPath.startsWith("/frontend") ? reqPath.slice("/frontend".length) || "/" : reqPath;
410
+ await this.system._frontend.handleRequest(req, res, subPath);
411
+ } else {
412
+ this._sendJson(res, 404, { status: "error", message: "Frontend not enabled." });
413
+ }
414
+ return;
415
+ }
416
+ const isFrontendAsset = reqPath === "/" || reqPath === "/index.html" || reqPath === "/bundle.js" || reqPath === "/styles.css" || reqPath === "/index.css";
417
+ if (isFrontendAsset && req.method === "GET" && (this.system._frontend || this.system._entityDataDir)) {
418
+ if (!this.system._frontend && this.system._entityDataDir) {
419
+ const frontendDir = path.join(this.system._entityDataDir, "frontend");
420
+ if (fs.existsSync(frontendDir)) {
421
+ this.system.enableFrontend({ frontendDir });
422
+ }
423
+ }
424
+ if (this.system._frontend) {
425
+ const assetPath = reqPath === "/" ? "/index.html" : reqPath;
426
+ await this.system._frontend.handleRequest(req, res, assetPath);
427
+ return;
428
+ }
429
+ }
430
+ if (this.enableFriendlyRouting) {
431
+ let fid = reqPath.slice(1);
432
+ if (fid.endsWith("/")) fid = fid.slice(0, -1);
433
+ let resolvedCap = this.system.resolveCapability ? this.system.resolveCapability(fid) : null;
434
+ let functionality = this.system.localFunctionalities.get(fid) || this.system.remoteFunctionalities.get(fid) || (resolvedCap ? resolvedCap.owner.localFunctionalities.get(resolvedCap.fid) : null);
435
+ let resolved = this.system.resolveLocalFunctionality ? this.system.resolveLocalFunctionality(fid) : null;
436
+ if (!functionality) {
437
+ const cleanPath = reqPath.replace(/^\/api\//, "/").slice(1);
438
+ const segments = cleanPath.split("/").filter(Boolean);
439
+ if (segments.length >= 2) {
440
+ const subAppPrefix = segments[0];
441
+ const opSuffix = segments.slice(1).join(".");
442
+ const potentialFid = `${subAppPrefix}.${opSuffix}`;
443
+ const allKeys = Array.from(this.system.localFunctionalities.keys()).concat(
444
+ Array.from(this.system.remoteFunctionalities.keys())
445
+ );
446
+ const match = allKeys.find((k) => k.toLowerCase() === potentialFid.toLowerCase());
447
+ if (match) {
448
+ fid = match;
449
+ resolvedCap = this.system.resolveCapability ? this.system.resolveCapability(fid) : null;
450
+ functionality = this.system.localFunctionalities.get(fid) || this.system.remoteFunctionalities.get(fid) || (resolvedCap ? resolvedCap.owner.localFunctionalities.get(resolvedCap.fid) : null);
451
+ resolved = this.system.resolveLocalFunctionality ? this.system.resolveLocalFunctionality(fid) : null;
452
+ }
453
+ }
454
+ }
455
+ if (functionality) {
456
+ const expectedMethod = (resolved || functionality).method || "POST";
457
+ if (req.method !== expectedMethod) {
458
+ this._sendJson(res, 405, {
459
+ status: "error",
460
+ message: `Method ${req.method} not allowed for ${fid}. Use ${expectedMethod}.`
461
+ });
462
+ return;
463
+ }
464
+ try {
465
+ Logger.log(`[HttpAdapter] Friendly route hit: ${fid} (${req.method})`);
466
+ const input = req.method === "GET" ? Object.fromEntries(url.searchParams.entries()) : await this._readJsonBody(req);
467
+ const data = input && typeof input === "object" && !("data" in input) && Object.keys(input).length > 0 ? { data: input } : input;
468
+ let result;
469
+ if (resolvedCap) {
470
+ result = await resolvedCap.owner.call(resolvedCap.fid, data.data || data, {
471
+ unwrap: false,
472
+ callerPort: req.socket?.remotePort,
473
+ accessKey: req.headers["x-krnl-access-key"]
474
+ });
475
+ } else {
476
+ result = await this.system.call(fid, data.data || data, {
477
+ unwrap: false,
478
+ callerPort: req.socket?.remotePort,
479
+ accessKey: req.headers["x-krnl-access-key"]
480
+ });
481
+ }
482
+ this._sendJson(res, 200, result);
483
+ } catch (e) {
484
+ Logger.error(`[HttpAdapter] Friendly route error (${fid}):`, e.message);
485
+ this._sendJson(res, 200, {
486
+ status: "error",
487
+ message: e.message,
488
+ errorDocumentation: e.errorDocumentation || null
489
+ });
490
+ }
491
+ return;
492
+ }
493
+ }
494
+ const notFoundData = typeof this.system.getNotFoundResponse === "function" ? this.system.getNotFoundResponse(reqPath) : { error: "Route not found", path: reqPath };
495
+ this._sendJson(res, 404, notFoundData);
496
+ return;
497
+ }
498
+ try {
499
+ if (reqPath.startsWith("/ui")) {
500
+ if (reqPath === "/ui/manifest") {
501
+ const activeFids = Array.from(/* @__PURE__ */ new Set([
502
+ ...Object.keys(this._latestUiSnapshot),
503
+ ...this.system.localFunctionalities ? Array.from(this.system.localFunctionalities.keys()) : []
504
+ ]));
505
+ this._sendJson(res, 200, {
506
+ status: "success",
507
+ entity: this.system.entityName,
508
+ uiActive: this._uiWsClients.size > 0,
509
+ endpoints: activeFids
510
+ });
511
+ return;
512
+ }
513
+ if (reqPath === "/ui/state" || reqPath === "/ui/state/") {
514
+ if (this._uiWsClients.size > 0) {
515
+ for (const ws of this._uiWsClients) {
516
+ if (ws.readyState === WebSocket.OPEN) {
517
+ ws.send(JSON.stringify({ action: "query" }));
518
+ }
519
+ }
520
+ await new Promise((r) => setTimeout(r, 100));
521
+ }
522
+ this._sendJson(res, 200, {
523
+ status: "success",
524
+ uiActive: this._uiWsClients.size > 0,
525
+ states: this._latestUiSnapshot
526
+ });
527
+ return;
528
+ }
529
+ if (reqPath.startsWith("/ui/state/")) {
530
+ const fid = reqPath.slice("/ui/state/".length);
531
+ this._sendJson(res, 200, {
532
+ status: "success",
533
+ fid,
534
+ state: this._latestUiSnapshot[fid] || null
535
+ });
536
+ return;
537
+ }
538
+ if (reqPath === "/ui/trigger" && req.method === "POST") {
539
+ const { fid, input, timeoutMs } = await this._readJsonBody(req);
540
+ if (!fid) {
541
+ this._sendJson(res, 400, { status: "error", message: "Missing required field: fid" });
542
+ return;
543
+ }
544
+ const maxWaitMs = timeoutMs || 5e3;
545
+ let readyWait = 0;
546
+ while (!this._uiReadyComponents.has(fid) && readyWait < maxWaitMs) {
547
+ await new Promise((r) => setTimeout(r, 50));
548
+ readyWait += 50;
549
+ }
550
+ if (!this._uiReadyComponents.has(fid) && this._uiWsClients.size === 0) {
551
+ this._sendJson(res, 400, {
552
+ status: "error",
553
+ message: `Endpoint component '${fid}' is not mounted in the UI or no active UI client connected.`
554
+ });
555
+ return;
556
+ }
557
+ const ticket = this.system._jobScheduler.createTicket(fid, "ui_trigger");
558
+ this.system._jobScheduler.markRunning(ticket.id);
559
+ this.sendWsTrigger(fid, input, ticket.id);
560
+ try {
561
+ const finishedTicket = await this.system._jobScheduler.waitForTicket(ticket.id, Math.max(1e3, maxWaitMs - readyWait));
562
+ this._sendJson(res, 200, {
563
+ status: finishedTicket.status === "done" ? "success" : "error",
564
+ fid,
565
+ ticketId: ticket.id,
566
+ uiActive: this._uiWsClients.size > 0,
567
+ result: finishedTicket.result,
568
+ error: finishedTicket.error,
569
+ state: this._latestUiSnapshot[fid] || null
570
+ });
571
+ } catch (err) {
572
+ this._sendJson(res, 200, {
573
+ status: "timeout",
574
+ fid,
575
+ ticketId: ticket.id,
576
+ uiActive: this._uiWsClients.size > 0,
577
+ error: err.message || "Timeout waiting for ticket",
578
+ state: this._latestUiSnapshot[fid] || null
579
+ });
580
+ }
581
+ return;
582
+ }
583
+ if (reqPath === "/ui/subscribe") {
584
+ res.writeHead(200, {
585
+ "Content-Type": "text/event-stream",
586
+ "Cache-Control": "no-cache",
587
+ "Connection": "keep-alive"
588
+ });
589
+ this._uiSseClients.add(res);
590
+ res.write(`data: ${JSON.stringify(this._latestUiSnapshot)}
591
+
592
+ `);
593
+ req.on("close", () => {
594
+ this._uiSseClients.delete(res);
595
+ res.end();
596
+ });
597
+ return;
598
+ }
599
+ }
600
+ if (reqPath === "/agent/job_complete" && req.method === "POST") {
601
+ const { ticketId, fid, result, error } = await this._readJsonBody(req);
602
+ console.log(`[UnifiedHttpAdapter] Received HTTP /agent/job_complete ACK for ticket '${ticketId}', fid '${fid}', error: '${error}'`);
603
+ if (!ticketId) {
604
+ this._sendJson(res, 400, { status: "error", message: "Missing required field: ticketId" });
605
+ return;
606
+ }
607
+ this.system._jobScheduler.resolveTicket(
608
+ ticketId,
609
+ error ? "failed" : "done",
610
+ result,
611
+ error
612
+ );
613
+ this._sendJson(res, 200, { status: "success", ticketId });
614
+ return;
615
+ }
616
+ if (reqPath.startsWith("/call/")) {
617
+ const fid = reqPath.slice("/call/".length);
618
+ const body = await this._readJsonBody(req);
619
+ let result;
620
+ if (this.system.resolveCapability) {
621
+ const resolved = this.system.resolveCapability(fid);
622
+ if (resolved) {
623
+ result = await resolved.owner.call(resolved.fid, body, {
624
+ unwrap: false,
625
+ callerPort: req.socket?.remotePort,
626
+ accessKey: req.headers["x-krnl-access-key"]
627
+ });
628
+ } else {
629
+ result = await this.system.call(fid, body, {
630
+ unwrap: false,
631
+ callerPort: req.socket?.remotePort,
632
+ accessKey: req.headers["x-krnl-access-key"]
633
+ });
634
+ }
635
+ } else {
636
+ result = await this.system.call(fid, body, {
637
+ unwrap: false,
638
+ callerPort: req.socket?.remotePort,
639
+ accessKey: req.headers["x-krnl-access-key"]
640
+ });
641
+ }
642
+ this._sendJson(res, 200, result);
643
+ return;
644
+ }
645
+ if (reqPath.startsWith("/sse/")) {
646
+ const fid = reqPath.split("/")[2];
647
+ this._handleSse(req, res, fid);
648
+ return;
649
+ }
650
+ if (reqPath === "/ai") {
651
+ const { message } = await this._readJsonBody(req);
652
+ if (!this.system._aiOrchestrator) {
653
+ const { KrnlAikoClient } = await import("./K_LIB_Krnl_Aiko_Client-OPZAVZCW-K4CRQYA5.js");
654
+ this._sendJson(res, 200, {
655
+ status: "error",
656
+ message: KrnlAikoClient.getNotRunningMessage()
657
+ });
658
+ return;
659
+ }
660
+ const result = await this.system._aiOrchestrator.handle(message);
661
+ this._sendJson(res, 200, result);
662
+ return;
663
+ }
664
+ if (reqPath === "/ai/manifest") {
665
+ const agents = this.system._aiOrchestrator?.getAgentSummaries() ?? [];
666
+ this._sendJson(res, 200, {
667
+ aiEnabled: !!this.system._aiOrchestrator,
668
+ aikoAlive: this.system.isAikoAlive(),
669
+ endpoints: agents
670
+ });
671
+ return;
672
+ }
673
+ if (reqPath === "/mcp") {
674
+ const body = await this._readJsonBody(req);
675
+ const result = await this.mcp.handleRequest(body, {
676
+ callerPort: req.socket?.remotePort,
677
+ accessKey: req.headers["x-krnl-access-key"]
678
+ });
679
+ this._sendJson(res, 200, result);
680
+ return;
681
+ }
682
+ if (reqPath === "/health") {
683
+ const healthData = { status: "ok", entity: this.system.entityName };
684
+ if (this.system._subappErrors && this.system._subappErrors.length > 0) {
685
+ healthData.status = "issues";
686
+ healthData.issues = this.system._subappErrors;
687
+ }
688
+ this._sendJson(res, 200, healthData);
689
+ return;
690
+ }
691
+ if (reqPath.startsWith("/acp")) {
692
+ if (reqPath === "/acp/info" || reqPath === "/acp") {
693
+ this._sendJson(res, 200, this.acp.getInfo());
694
+ } else if (reqPath === "/acp/capabilities") {
695
+ this._sendJson(res, 200, this.acp.getCapabilities());
696
+ } else if (reqPath === "/acp/messages" && req.method === "POST") {
697
+ const body = await this._readJsonBody(req);
698
+ const result = await this.acp.handleMessage(body, {
699
+ callerPort: req.socket?.remotePort,
700
+ accessKey: req.headers["x-krnl-access-key"]
701
+ });
702
+ this._sendJson(res, 200, result);
703
+ } else {
704
+ this._sendJson(res, 404, { error: "ACP route not found" });
705
+ }
706
+ return;
707
+ }
708
+ if (reqPath === "/manifest") {
709
+ if (this.system._ingressNetwork) {
710
+ this._sendJson(res, 200, this.system._ingressNetwork.getGrossManifest(`http://${req.headers.host}`));
711
+ } else {
712
+ this._sendJson(res, 200, this.system.getManifest());
713
+ }
714
+ return;
715
+ }
716
+ } catch (error) {
717
+ Logger.error(`[HttpAdapter] Fatal handler error ${reqPath}:`, error.message || error);
718
+ this._sendJson(res, 200, {
719
+ status: "error",
720
+ message: error.message || String(error),
721
+ errorDocumentation: error.errorDocumentation || null
722
+ });
723
+ }
724
+ }
725
+ _handleSse(req, res, fid) {
726
+ res.writeHead(200, {
727
+ "Content-Type": "text/event-stream",
728
+ "Cache-Control": "no-cache",
729
+ "Connection": "keep-alive"
730
+ });
731
+ const functionality = this.system.resolveLocalFunctionality ? this.system.resolveLocalFunctionality(fid) : this.system.localFunctionalities.get(fid);
732
+ if (!functionality) {
733
+ res.write(`data: ${JSON.stringify({ error: "Functionality not found" })}
734
+
735
+ `);
736
+ res.end();
737
+ return;
738
+ }
739
+ const stateEmitter = functionality.emitters.get("state:changed");
740
+ const unsubscribe = stateEmitter?.subscribe((msg) => {
741
+ res.write(`data: ${JSON.stringify(msg.data)}
742
+
743
+ `);
744
+ });
745
+ const interval = setInterval(() => {
746
+ if (res.writable) {
747
+ res.write(": keepalive\n\n");
748
+ }
749
+ }, 15e3);
750
+ req.on("close", () => {
751
+ if (unsubscribe) unsubscribe();
752
+ clearInterval(interval);
753
+ res.end();
754
+ });
755
+ }
756
+ _sendJson(res, status, data) {
757
+ res.writeHead(status, { "Content-Type": "application/json" });
758
+ res.end(JSON.stringify(data));
759
+ }
760
+ _readJsonBody(req) {
761
+ return new Promise((resolve, reject) => {
762
+ let body = "";
763
+ req.on("data", (chunk) => {
764
+ body += chunk.toString();
765
+ });
766
+ req.on("end", () => {
767
+ if (!body) return resolve({});
768
+ try {
769
+ resolve(JSON.parse(body));
770
+ } catch (e) {
771
+ reject(new Error("Invalid JSON body"));
772
+ }
773
+ });
774
+ });
775
+ }
776
+ onCapabilitySurfaceChanged(entity) {
777
+ this.system = entity;
778
+ }
779
+ async stop() {
780
+ if (this.wss) {
781
+ for (const ws of this._uiWsClients) {
782
+ try {
783
+ ws.close();
784
+ } catch (_) {
785
+ }
786
+ }
787
+ this._uiWsClients.clear();
788
+ try {
789
+ this.wss.close();
790
+ } catch (_) {
791
+ }
792
+ this.wss = null;
793
+ }
794
+ if (this.server && !this._isExternalServer) {
795
+ await new Promise((resolve) => {
796
+ this.server.close(() => resolve());
797
+ });
798
+ this.server = null;
799
+ }
800
+ }
801
+ dispose() {
802
+ this.stop().catch(() => {
803
+ });
804
+ }
805
+ };
806
+
807
+ export {
808
+ krnlUnifiedHttpAdapter
809
+ };