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