@ultrst-armada/krnl 0.0.0-stage → 1.0.0

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