@ultrst-armada/krnl 1.0.2 → 1.0.3

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 (237) hide show
  1. package/README.md +67 -65
  2. package/package.json +12 -8
  3. package/packages/cli/dist/bin/krnl.cjs +793 -330
  4. package/packages/cli/dist/bin/krnl.js +50 -65
  5. package/packages/cli/dist/chunk-6SHSECXR.js +1628 -0
  6. package/packages/cli/dist/index.cjs +746 -262
  7. package/packages/cli/dist/index.d.cts +45 -2
  8. package/packages/cli/dist/index.d.ts +45 -2
  9. package/packages/cli/dist/index.js +5 -1
  10. package/packages/cli/package.json +17 -10
  11. package/packages/core/dist/index.cjs +2905 -139
  12. package/packages/core/dist/index.d.cts +611 -27
  13. package/packages/core/dist/index.d.ts +611 -27
  14. package/packages/core/dist/index.js +2897 -139
  15. package/packages/core/package.json +14 -6
  16. package/packages/create-krnl/dist/index.cjs +102 -65
  17. package/packages/create-krnl/dist/index.js +102 -65
  18. package/packages/create-krnl/package.json +5 -3
  19. package/packages/eslint-plugin/dist/index.cjs +17 -55
  20. package/packages/eslint-plugin/dist/index.d.cts +8 -43
  21. package/packages/eslint-plugin/dist/index.d.ts +8 -43
  22. package/packages/eslint-plugin/dist/index.js +17 -55
  23. package/packages/eslint-plugin/package.json +5 -4
  24. package/packages/validate/dist/index.cjs +378 -85
  25. package/packages/validate/dist/index.d.cts +11 -1
  26. package/packages/validate/dist/index.d.ts +11 -1
  27. package/packages/validate/dist/index.js +375 -82
  28. package/packages/validate/package.json +14 -7
  29. package/packages/cli/dist/K_ENT_Entity-PQ5MURQY-ZG6FZXXX.js +0 -13
  30. package/packages/cli/dist/K_LIB_Krnl_Aiko_Client-OPZAVZCW-K4CRQYA5.js +0 -8
  31. package/packages/cli/dist/K_LIB_Krnl_Ep_Tools-ROOE2TQF-LNPXZYOE.js +0 -110
  32. package/packages/cli/dist/K_LIB_Krnl_Frontend_Builder-2ZDUH6PF-3ALZPNX4.js +0 -11
  33. package/packages/cli/dist/K_LIB_Krnl_Frontend_Generator-UYNRNX2X-PJTICYSW.js +0 -11
  34. package/packages/cli/dist/K_LIB_Krnl_Registry_Client-NXV6D2QW-M5TYU55O.js +0 -8
  35. package/packages/cli/dist/K_LIB_Krnl_SubApp_Engine-7HR5HWW2-H6STOXRK.js +0 -20
  36. package/packages/cli/dist/K_LIB_Krnl_SubApp_Registry-7XYGDKJK-XPJXSF7D.js +0 -19
  37. package/packages/cli/dist/K_LIB_Krnl_SubApp_Worker_Host-CQVTGGG7-CUYGTWOW.js +0 -7
  38. package/packages/cli/dist/K_LIB_Krnl_System_App_Adapter-M6FJKLGU-VR6T4N6J.js +0 -17
  39. package/packages/cli/dist/K_LIB_Krnl_System_Base_Functionality_APIs-ZZUZ6ZG5-RLJ4QWDP.js +0 -58
  40. package/packages/cli/dist/K_LIB_Krnl_System_Magnetic_Loader-XBQO2KXF-BOQGUASC.js +0 -22
  41. package/packages/cli/dist/K_LIB_Krnl_System_Unified_Http_Adapter-RCEGP3OG-XJI7KIT5.js +0 -8
  42. package/packages/cli/dist/K_LIB_Krnl_Telemetry-77FRZ3KV-K5VCWAFW.js +0 -9
  43. package/packages/cli/dist/chunk-3TRM6CYL.js +0 -152
  44. package/packages/cli/dist/chunk-5JDK35TG.js +0 -3872
  45. package/packages/cli/dist/chunk-63PTK33I.js +0 -997
  46. package/packages/cli/dist/chunk-6NIKAMUZ.js +0 -82
  47. package/packages/cli/dist/chunk-BOXWWXQG.js +0 -400
  48. package/packages/cli/dist/chunk-EEKLK7QJ.js +0 -565
  49. package/packages/cli/dist/chunk-EG7T2IAD.js +0 -107
  50. package/packages/cli/dist/chunk-ESTKOQ7T.js +0 -1146
  51. package/packages/cli/dist/chunk-F5EHXE2O.js +0 -1036
  52. package/packages/cli/dist/chunk-F65ANSQG.js +0 -269
  53. package/packages/cli/dist/chunk-FDNCADFE.js +0 -71
  54. package/packages/cli/dist/chunk-FZ6X7PHR.js +0 -1146
  55. package/packages/cli/dist/chunk-GDLRMDAN.js +0 -127
  56. package/packages/cli/dist/chunk-HWMTCMOS.js +0 -656
  57. package/packages/cli/dist/chunk-I74QIQOD.js +0 -5536
  58. package/packages/cli/dist/chunk-JTLSTO25.js +0 -71
  59. package/packages/cli/dist/chunk-JULBBJ27.js +0 -1033
  60. package/packages/cli/dist/chunk-OHVMVRBP.js +0 -117
  61. package/packages/cli/dist/chunk-P2PCLEKX.js +0 -666
  62. package/packages/cli/dist/chunk-PJQIUOX2.js +0 -7767
  63. package/packages/cli/dist/chunk-PPOF3DJW.js +0 -471
  64. package/packages/cli/dist/chunk-Q45257P6.js +0 -173
  65. package/packages/cli/dist/chunk-QNROWGBI.js +0 -1036
  66. package/packages/cli/dist/chunk-RJNYUXZD.js +0 -977
  67. package/packages/cli/dist/chunk-SRTOPJ5W.js +0 -104
  68. package/packages/cli/dist/chunk-TCEX3MPS.js +0 -702
  69. package/packages/cli/dist/chunk-TNOAJO2J.js +0 -675
  70. package/packages/cli/dist/chunk-UR2SUCSF.js +0 -701
  71. package/packages/cli/dist/chunk-X5LOIFM7.js +0 -68
  72. package/packages/cli/dist/chunk-XIRFOO3H.js +0 -589
  73. package/packages/cli/dist/chunk-ZAAV3JXQ.js +0 -809
  74. package/packages/core/dist/K_ENT_Entity-4MB7CU4A.js +0 -12
  75. package/packages/core/dist/K_ENT_Entity-DEJGIDGH.js +0 -12
  76. package/packages/core/dist/K_ENT_Entity-FXZO5UZ2.js +0 -12
  77. package/packages/core/dist/K_ENT_Entity-HDSCXC5F.js +0 -12
  78. package/packages/core/dist/K_ENT_Entity-JILABHLW.js +0 -12
  79. package/packages/core/dist/K_ENT_Entity-PQ5MURQY.js +0 -13
  80. package/packages/core/dist/K_ENT_Entity-ROAKDIHW.js +0 -12
  81. package/packages/core/dist/K_ENT_Entity-TBVFSKDV.js +0 -12
  82. package/packages/core/dist/K_ENT_Entity-ZFLKG3JO.js +0 -12
  83. package/packages/core/dist/K_LIB_Krnl_Aiko_Client-OPZAVZCW.js +0 -8
  84. package/packages/core/dist/K_LIB_Krnl_Ep_Tools-ROOE2TQF.js +0 -110
  85. package/packages/core/dist/K_LIB_Krnl_Frontend_Builder-2ZDUH6PF.js +0 -9
  86. package/packages/core/dist/K_LIB_Krnl_Frontend_Generator-UYNRNX2X.js +0 -9
  87. package/packages/core/dist/K_LIB_Krnl_Registry_Client-NXV6D2QW.js +0 -8
  88. package/packages/core/dist/K_LIB_Krnl_SubApp_Engine-7HR5HWW2.js +0 -20
  89. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-4C6GBQAG.js +0 -18
  90. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-6V23A6F6.js +0 -18
  91. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-7XYGDKJK.js +0 -19
  92. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-DYLLC5G2.js +0 -18
  93. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-F4FOFAUP.js +0 -18
  94. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-FBOXXMI3.js +0 -18
  95. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-Q73BWLNP.js +0 -18
  96. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-QM2C4MVA.js +0 -18
  97. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-QUGI6SMP.js +0 -18
  98. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-RGMTBHNP.js +0 -18
  99. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-RWR7UNDW.js +0 -18
  100. package/packages/core/dist/K_LIB_Krnl_SubApp_Worker_Host-CQVTGGG7.js +0 -7
  101. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-32MFJJ5Z.js +0 -17
  102. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-4J4CEWRY.js +0 -17
  103. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-A366YHF2.js +0 -17
  104. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-LK4LYJHI.js +0 -17
  105. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-M6FJKLGU.js +0 -17
  106. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-NW3K63II.js +0 -17
  107. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-QDHTI5ZV.js +0 -17
  108. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-VHCT6VIW.js +0 -17
  109. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-WBRKF24R.js +0 -17
  110. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-XKYQYT6Q.js +0 -17
  111. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-Z2PWZYDZ.js +0 -17
  112. package/packages/core/dist/K_LIB_Krnl_System_Base_Functionality_APIs-ZZUZ6ZG5.js +0 -58
  113. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-2EZU7QF4.js +0 -21
  114. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-6G3AQNAV.js +0 -21
  115. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-B2NZMQUG.js +0 -21
  116. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-C2RABMZP.js +0 -21
  117. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-HHE3NZ4F.js +0 -21
  118. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-LHFGR6WK.js +0 -21
  119. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-M74BLM3N.js +0 -21
  120. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-PT6ZA6EA.js +0 -21
  121. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-SP52V3CX.js +0 -21
  122. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-XBQO2KXF.js +0 -22
  123. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-YNSEUHJJ.js +0 -21
  124. package/packages/core/dist/K_LIB_Krnl_System_Unified_Http_Adapter-M6SBHIVA.js +0 -8
  125. package/packages/core/dist/K_LIB_Krnl_System_Unified_Http_Adapter-RCEGP3OG.js +0 -8
  126. package/packages/core/dist/K_LIB_Krnl_Telemetry-77FRZ3KV.js +0 -9
  127. package/packages/core/dist/chunk-33L2J7V7.js +0 -82
  128. package/packages/core/dist/chunk-3ES4K2ZP.js +0 -817
  129. package/packages/core/dist/chunk-3SMHVVLL.js +0 -82
  130. package/packages/core/dist/chunk-3UEZ7JQA.js +0 -4877
  131. package/packages/core/dist/chunk-3XIE6KBD.js +0 -4877
  132. package/packages/core/dist/chunk-46ZLCML6.js +0 -107
  133. package/packages/core/dist/chunk-4UEL3DWJ.js +0 -107
  134. package/packages/core/dist/chunk-54GWZ5PC.js +0 -82
  135. package/packages/core/dist/chunk-6QCYRS5L.js +0 -127
  136. package/packages/core/dist/chunk-6ULMHNXR.js +0 -104
  137. package/packages/core/dist/chunk-7WUETJEV.js +0 -117
  138. package/packages/core/dist/chunk-A5KRAYDB.js +0 -107
  139. package/packages/core/dist/chunk-ANEAZ3PO.js +0 -107
  140. package/packages/core/dist/chunk-BE76RL6F.js +0 -82
  141. package/packages/core/dist/chunk-CIARVYDO.js +0 -107
  142. package/packages/core/dist/chunk-CR2ANE62.js +0 -107
  143. package/packages/core/dist/chunk-DI27MOR7.js +0 -173
  144. package/packages/core/dist/chunk-E6RLFHM5.js +0 -596
  145. package/packages/core/dist/chunk-EELAPMNV.js +0 -4877
  146. package/packages/core/dist/chunk-ENZ2RQVJ.js +0 -107
  147. package/packages/core/dist/chunk-F2U6CX4F.js +0 -4877
  148. package/packages/core/dist/chunk-FKG64OHL.js +0 -82
  149. package/packages/core/dist/chunk-FYAZJYM5.js +0 -772
  150. package/packages/core/dist/chunk-G4NP4RDQ.js +0 -82
  151. package/packages/core/dist/chunk-GADIRLRS.js +0 -473
  152. package/packages/core/dist/chunk-GR6CSLQJ.js +0 -772
  153. package/packages/core/dist/chunk-HDS7AT6O.js +0 -772
  154. package/packages/core/dist/chunk-HIMEZUU2.js +0 -71
  155. package/packages/core/dist/chunk-IB4UHG5I.js +0 -596
  156. package/packages/core/dist/chunk-J7ZYNVRS.js +0 -772
  157. package/packages/core/dist/chunk-JVLZU4K7.js +0 -604
  158. package/packages/core/dist/chunk-JYXXI7Q3.js +0 -82
  159. package/packages/core/dist/chunk-K54K2KZW.js +0 -192
  160. package/packages/core/dist/chunk-K6VHLBNH.js +0 -3316
  161. package/packages/core/dist/chunk-KCBP7ZYA.js +0 -596
  162. package/packages/core/dist/chunk-KFQGP6VL.js +0 -33
  163. package/packages/core/dist/chunk-KIUEUI7K.js +0 -82
  164. package/packages/core/dist/chunk-LB67NIZP.js +0 -949
  165. package/packages/core/dist/chunk-LDTYFUNW.js +0 -596
  166. package/packages/core/dist/chunk-MLVWARD4.js +0 -596
  167. package/packages/core/dist/chunk-MPYVXHKO.js +0 -2777
  168. package/packages/core/dist/chunk-MRQ3MITU.js +0 -772
  169. package/packages/core/dist/chunk-MVUN7I7O.js +0 -107
  170. package/packages/core/dist/chunk-NDDOIRW7.js +0 -596
  171. package/packages/core/dist/chunk-O3KDB5MH.js +0 -3330
  172. package/packages/core/dist/chunk-OEINUDSE.js +0 -400
  173. package/packages/core/dist/chunk-OPDENPT4.js +0 -4877
  174. package/packages/core/dist/chunk-P6XEM2LA.js +0 -429
  175. package/packages/core/dist/chunk-QKMRSQV4.js +0 -82
  176. package/packages/core/dist/chunk-R6CCWALL.js +0 -4877
  177. package/packages/core/dist/chunk-RAMMOO73.js +0 -774
  178. package/packages/core/dist/chunk-S3FTZFG6.js +0 -772
  179. package/packages/core/dist/chunk-T2ZVN434.js +0 -4877
  180. package/packages/core/dist/chunk-TFHLDMIA.js +0 -107
  181. package/packages/core/dist/chunk-TI3QUCIJ.js +0 -107
  182. package/packages/core/dist/chunk-TR2BAIGI.js +0 -107
  183. package/packages/core/dist/chunk-UGVVJKC6.js +0 -4877
  184. package/packages/core/dist/chunk-V2DX7YIU.js +0 -984
  185. package/packages/core/dist/chunk-W4IHYUYD.js +0 -772
  186. package/packages/core/dist/chunk-W6WBG5OY.js +0 -4877
  187. package/packages/core/dist/chunk-WN3M7O7H.js +0 -3312
  188. package/packages/core/dist/chunk-WR3NCU7U.js +0 -4877
  189. package/packages/core/dist/chunk-XC6B6L27.js +0 -82
  190. package/packages/core/dist/chunk-XNSE64ZY.js +0 -3316
  191. package/packages/core/dist/chunk-XROES2WN.js +0 -634
  192. package/packages/core/dist/chunk-XSCKNRCZ.js +0 -5020
  193. package/packages/core/dist/chunk-XVABPAUZ.js +0 -82
  194. package/packages/core/dist/chunk-YOBCB5C5.js +0 -596
  195. package/packages/core/dist/chunk-YUK6Q563.js +0 -666
  196. package/packages/core/dist/chunk-YXGL3ZEU.js +0 -1030
  197. package/packages/core/dist/chunk-ZINJ5OUX.js +0 -596
  198. package/packages/core/dist/chunk-ZPFD4BIQ.js +0 -604
  199. package/packages/core/dist/chunk-ZQZBFG6F.js +0 -4826
  200. package/packages/core/dist/chunk-ZZFRJGXM.js +0 -4877
  201. package/packages/create-krnl/dist/K_ENT_Entity-PQ5MURQY-R2OH4VXE.js +0 -14
  202. package/packages/create-krnl/dist/K_LIB_Krnl_Aiko_Client-OPZAVZCW-AZM5HF4M.js +0 -9
  203. package/packages/create-krnl/dist/K_LIB_Krnl_Ep_Tools-ROOE2TQF-X5N6SV2S.js +0 -111
  204. package/packages/create-krnl/dist/K_LIB_Krnl_Frontend_Builder-2ZDUH6PF-5PFHF4JU.js +0 -12
  205. package/packages/create-krnl/dist/K_LIB_Krnl_Frontend_Generator-UYNRNX2X-ED33OQPH.js +0 -12
  206. package/packages/create-krnl/dist/K_LIB_Krnl_Registry_Client-NXV6D2QW-YGQLVR4P.js +0 -9
  207. package/packages/create-krnl/dist/K_LIB_Krnl_SubApp_Engine-7HR5HWW2-VM7CTU2L.js +0 -21
  208. package/packages/create-krnl/dist/K_LIB_Krnl_SubApp_Registry-7XYGDKJK-Y2GQFJ7I.js +0 -21
  209. package/packages/create-krnl/dist/K_LIB_Krnl_SubApp_Worker_Host-CQVTGGG7-L3JQWO54.js +0 -8
  210. package/packages/create-krnl/dist/K_LIB_Krnl_System_App_Adapter-M6FJKLGU-KQARASPR.js +0 -19
  211. package/packages/create-krnl/dist/K_LIB_Krnl_System_Base_Functionality_APIs-ZZUZ6ZG5-OF3IGLVL.js +0 -59
  212. package/packages/create-krnl/dist/K_LIB_Krnl_System_Magnetic_Loader-XBQO2KXF-JOLHKOEX.js +0 -24
  213. package/packages/create-krnl/dist/K_LIB_Krnl_System_Unified_Http_Adapter-RCEGP3OG-L46LSHKQ.js +0 -10
  214. package/packages/create-krnl/dist/K_LIB_Krnl_Telemetry-77FRZ3KV-4JUPRR3X.js +0 -10
  215. package/packages/create-krnl/dist/chunk-3TRM6CYL.js +0 -152
  216. package/packages/create-krnl/dist/chunk-3URCB3QS.js +0 -127
  217. package/packages/create-krnl/dist/chunk-5JDK35TG.js +0 -3872
  218. package/packages/create-krnl/dist/chunk-A2XAXDOW.js +0 -812
  219. package/packages/create-krnl/dist/chunk-AN6TMQHG.js +0 -1033
  220. package/packages/create-krnl/dist/chunk-BOXWWXQG.js +0 -400
  221. package/packages/create-krnl/dist/chunk-BPTBREBG.js +0 -38
  222. package/packages/create-krnl/dist/chunk-FDNCADFE.js +0 -71
  223. package/packages/create-krnl/dist/chunk-JTLSTO25.js +0 -71
  224. package/packages/create-krnl/dist/chunk-M3NCUIPL.js +0 -107
  225. package/packages/create-krnl/dist/chunk-N2EONSOC.js +0 -7769
  226. package/packages/create-krnl/dist/chunk-OHVMVRBP.js +0 -117
  227. package/packages/create-krnl/dist/chunk-Q45257P6.js +0 -173
  228. package/packages/create-krnl/dist/chunk-QGM4M3NI.js +0 -37
  229. package/packages/create-krnl/dist/chunk-RJNYUXZD.js +0 -977
  230. package/packages/create-krnl/dist/chunk-SRTOPJ5W.js +0 -104
  231. package/packages/create-krnl/dist/chunk-UPBIGEC3.js +0 -666
  232. package/packages/create-krnl/dist/chunk-V2DB7UD7.js +0 -82
  233. package/packages/create-krnl/dist/chunk-WMHLIUI6.js +0 -3644
  234. package/packages/create-krnl/dist/chunk-XIRFOO3H.js +0 -589
  235. package/packages/create-krnl/dist/chunk-Y2CEEVZP.js +0 -5536
  236. package/packages/create-krnl/dist/main-DXUMPBND.js +0 -2217
  237. package/packages/create-krnl/dist/wrapper-SDF2VKX3.js +0 -31
@@ -1,4877 +0,0 @@
1
- import {
2
- K_LIB_Krnl_Frontend_Builder_exports,
3
- init_K_LIB_Krnl_Frontend_Builder
4
- } from "./chunk-6QCYRS5L.js";
5
- import {
6
- krnlEntityBase,
7
- krnlErrorCodes,
8
- krnlTransportAdapter
9
- } from "./chunk-O3KDB5MH.js";
10
- import {
11
- KrnlAikoClient,
12
- KrnlShell
13
- } from "./chunk-GADIRLRS.js";
14
- import {
15
- adminCommandApi,
16
- aiOrchestrationApi,
17
- discoverPeersApi,
18
- findFreePortsApi,
19
- getAikoCatalogApi,
20
- getEndpointDefinitionsApi,
21
- getFullDocumentationApi,
22
- getLastActionDocsApi,
23
- getManifestApi,
24
- getSiblingNetworkTopologyApi,
25
- getSubAppTopologyApi,
26
- getTaskListApi,
27
- getTelemetryLogApi,
28
- getUsedPortsApi,
29
- heartbeatApi,
30
- setEndpointDefinitionApi,
31
- shutdownApi,
32
- systemCommandsCollectorHandler,
33
- telemetryApi
34
- } from "./chunk-P6XEM2LA.js";
35
- import {
36
- krnlUnifiedHttpAdapter
37
- } from "./chunk-RAMMOO73.js";
38
- import {
39
- KrnlPolicy,
40
- Logger
41
- } from "./chunk-K54K2KZW.js";
42
- import {
43
- K_LIB_Krnl_Frontend_Generator_exports,
44
- init_K_LIB_Krnl_Frontend_Generator
45
- } from "./chunk-YXGL3ZEU.js";
46
- import {
47
- __toCommonJS
48
- } from "./chunk-KFQGP6VL.js";
49
-
50
- // src/core/krnl_pb.js
51
- import $protobuf from "protobufjs/minimal.js";
52
- var $Reader = $protobuf.Reader;
53
- var $Writer = $protobuf.Writer;
54
- var $util = $protobuf.util;
55
- var $Object = $util.global.Object;
56
- var $undefined = $util.global.undefined;
57
- var $Error = $util.global.Error;
58
- var $TypeError = $util.global.TypeError;
59
- var $String = $util.global.String;
60
- var $Number = $util.global.Number;
61
- var $parseInt = $util.global.parseInt;
62
- var $BigInt = $util.global.BigInt;
63
- var $Array = $util.global.Array;
64
- var $Boolean = $util.global.Boolean;
65
- var $root = $protobuf.roots["default"] || ($protobuf.roots["default"] = {});
66
- var krnl = $root.krnl = (() => {
67
- const krnl2 = {};
68
- krnl2.MessageKind = (function() {
69
- const valuesById = $Object.create(null), values = $Object.create(valuesById);
70
- values[valuesById[0] = "UNKNOWN"] = 0;
71
- values[valuesById[1] = "REGISTER_INGRESS"] = 1;
72
- values[valuesById[2] = "ROUTE_DATA"] = 2;
73
- values[valuesById[3] = "RPC_REQUEST"] = 3;
74
- values[valuesById[4] = "RPC_RESPONSE"] = 4;
75
- values[valuesById[5] = "INTROSPECT"] = 5;
76
- values[valuesById[6] = "INTROSPECT_RESPONSE"] = 6;
77
- return values;
78
- })();
79
- krnl2.KrnlMessage = (function() {
80
- const KrnlMessage = function(properties) {
81
- if (properties) {
82
- for (let keys = $Object.keys(properties), i = 0; i < keys.length; ++i)
83
- if (properties[keys[i]] != null && keys[i] !== "__proto__")
84
- this[keys[i]] = properties[keys[i]];
85
- }
86
- };
87
- KrnlMessage.prototype.kind = 0;
88
- KrnlMessage.prototype.routeId = "";
89
- KrnlMessage.prototype.requestId = "";
90
- KrnlMessage.prototype.traceCorrelationId = "";
91
- KrnlMessage.prototype.originSystemAddress = "";
92
- KrnlMessage.prototype.timestamp = $util.Long ? $util.Long.fromBits(0, 0, false) : 0;
93
- KrnlMessage.prototype.method = "";
94
- KrnlMessage.prototype.collectorName = "";
95
- KrnlMessage.prototype.jsonPayload = "";
96
- KrnlMessage.prototype.binaryPayload = $util.newBuffer([]);
97
- KrnlMessage.create = function(properties) {
98
- return new KrnlMessage(properties);
99
- };
100
- KrnlMessage.encode = function(message, writer, _depth) {
101
- if (!writer)
102
- writer = $Writer.create();
103
- if (_depth === $undefined)
104
- _depth = 0;
105
- if (_depth > $util.recursionLimit)
106
- throw $Error("max depth exceeded");
107
- if (message.kind != null && $Object.hasOwnProperty.call(message, "kind") && message.kind !== 0)
108
- writer.uint32(
109
- /* id 1, wireType 0 =*/
110
- 8
111
- ).int32(message.kind);
112
- if (message.routeId != null && $Object.hasOwnProperty.call(message, "routeId") && message.routeId !== "")
113
- writer.uint32(
114
- /* id 2, wireType 2 =*/
115
- 18
116
- ).string(message.routeId);
117
- if (message.requestId != null && $Object.hasOwnProperty.call(message, "requestId") && message.requestId !== "")
118
- writer.uint32(
119
- /* id 3, wireType 2 =*/
120
- 26
121
- ).string(message.requestId);
122
- if (message.traceCorrelationId != null && $Object.hasOwnProperty.call(message, "traceCorrelationId") && message.traceCorrelationId !== "")
123
- writer.uint32(
124
- /* id 4, wireType 2 =*/
125
- 34
126
- ).string(message.traceCorrelationId);
127
- if (message.originSystemAddress != null && $Object.hasOwnProperty.call(message, "originSystemAddress") && message.originSystemAddress !== "")
128
- writer.uint32(
129
- /* id 5, wireType 2 =*/
130
- 42
131
- ).string(message.originSystemAddress);
132
- if (message.timestamp != null && $Object.hasOwnProperty.call(message, "timestamp") && (typeof message.timestamp === "object" ? message.timestamp.low || message.timestamp.high : message.timestamp !== 0))
133
- writer.uint32(
134
- /* id 6, wireType 0 =*/
135
- 48
136
- ).int64(message.timestamp);
137
- if (message.method != null && $Object.hasOwnProperty.call(message, "method") && message.method !== "")
138
- writer.uint32(
139
- /* id 7, wireType 2 =*/
140
- 58
141
- ).string(message.method);
142
- if (message.collectorName != null && $Object.hasOwnProperty.call(message, "collectorName") && message.collectorName !== "")
143
- writer.uint32(
144
- /* id 8, wireType 2 =*/
145
- 66
146
- ).string(message.collectorName);
147
- if (message.jsonPayload != null && $Object.hasOwnProperty.call(message, "jsonPayload") && message.jsonPayload !== "")
148
- writer.uint32(
149
- /* id 9, wireType 2 =*/
150
- 74
151
- ).string(message.jsonPayload);
152
- if (message.binaryPayload != null && $Object.hasOwnProperty.call(message, "binaryPayload") && message.binaryPayload.length)
153
- writer.uint32(
154
- /* id 10, wireType 2 =*/
155
- 82
156
- ).bytes(message.binaryPayload);
157
- if (message.$unknowns != null && $Object.hasOwnProperty.call(message, "$unknowns"))
158
- for (let i = 0; i < message.$unknowns.length; ++i)
159
- writer.raw(message.$unknowns[i]);
160
- return writer;
161
- };
162
- KrnlMessage.encodeDelimited = function(message, writer) {
163
- return this.encode(message, (writer || $Writer.create()).fork()).ldelim();
164
- };
165
- KrnlMessage.decode = function(reader, length, _end, _depth, _target) {
166
- if (!(reader instanceof $Reader))
167
- reader = $Reader.create(reader);
168
- if (_depth === $undefined)
169
- _depth = 0;
170
- if (_depth > $Reader.recursionLimit)
171
- throw $Error("max depth exceeded");
172
- let end = length === $undefined ? reader.len : reader.pos + length, message = _target || new $root.krnl.KrnlMessage(), value;
173
- while (reader.pos < end) {
174
- let start = reader.pos;
175
- let tag = reader.tag();
176
- if (tag === _end) {
177
- _end = $undefined;
178
- break;
179
- }
180
- let wireType = tag & 7;
181
- switch (tag >>>= 3) {
182
- case 1: {
183
- if (wireType !== 0)
184
- break;
185
- if (value = reader.int32())
186
- message.kind = value;
187
- else
188
- delete message.kind;
189
- continue;
190
- }
191
- case 2: {
192
- if (wireType !== 2)
193
- break;
194
- if ((value = reader.stringVerify()).length)
195
- message.routeId = value;
196
- else
197
- delete message.routeId;
198
- continue;
199
- }
200
- case 3: {
201
- if (wireType !== 2)
202
- break;
203
- if ((value = reader.stringVerify()).length)
204
- message.requestId = value;
205
- else
206
- delete message.requestId;
207
- continue;
208
- }
209
- case 4: {
210
- if (wireType !== 2)
211
- break;
212
- if ((value = reader.stringVerify()).length)
213
- message.traceCorrelationId = value;
214
- else
215
- delete message.traceCorrelationId;
216
- continue;
217
- }
218
- case 5: {
219
- if (wireType !== 2)
220
- break;
221
- if ((value = reader.stringVerify()).length)
222
- message.originSystemAddress = value;
223
- else
224
- delete message.originSystemAddress;
225
- continue;
226
- }
227
- case 6: {
228
- if (wireType !== 0)
229
- break;
230
- if (typeof (value = reader.int64()) === "object" ? value.low || value.high : value !== 0)
231
- message.timestamp = value;
232
- else
233
- delete message.timestamp;
234
- continue;
235
- }
236
- case 7: {
237
- if (wireType !== 2)
238
- break;
239
- if ((value = reader.stringVerify()).length)
240
- message.method = value;
241
- else
242
- delete message.method;
243
- continue;
244
- }
245
- case 8: {
246
- if (wireType !== 2)
247
- break;
248
- if ((value = reader.stringVerify()).length)
249
- message.collectorName = value;
250
- else
251
- delete message.collectorName;
252
- continue;
253
- }
254
- case 9: {
255
- if (wireType !== 2)
256
- break;
257
- if ((value = reader.stringVerify()).length)
258
- message.jsonPayload = value;
259
- else
260
- delete message.jsonPayload;
261
- continue;
262
- }
263
- case 10: {
264
- if (wireType !== 2)
265
- break;
266
- if ((value = reader.bytes()).length)
267
- message.binaryPayload = value;
268
- else
269
- delete message.binaryPayload;
270
- continue;
271
- }
272
- }
273
- reader.skipType(wireType, _depth, tag);
274
- if (!reader.discardUnknown) {
275
- $util.makeProp(message, "$unknowns", false);
276
- (message.$unknowns || (message.$unknowns = [])).push(reader.raw(start, reader.pos));
277
- }
278
- }
279
- if (_end !== $undefined)
280
- throw $Error("missing end group");
281
- return message;
282
- };
283
- KrnlMessage.decodeDelimited = function(reader) {
284
- if (!(reader instanceof $Reader))
285
- reader = new $Reader(reader);
286
- return this.decode(reader, reader.uint32());
287
- };
288
- KrnlMessage.verify = function(message, _depth) {
289
- if (typeof message !== "object" || message === null)
290
- return "object expected";
291
- if (_depth === $undefined)
292
- _depth = 0;
293
- if (_depth > $util.recursionLimit)
294
- return "max depth exceeded";
295
- if (message.kind != null && $Object.hasOwnProperty.call(message, "kind")) {
296
- if (typeof message.kind !== "number" || (message.kind | 0) !== message.kind)
297
- return "kind: enum value expected";
298
- }
299
- if (message.routeId != null && $Object.hasOwnProperty.call(message, "routeId")) {
300
- if (!$util.isString(message.routeId))
301
- return "routeId: string expected";
302
- }
303
- if (message.requestId != null && $Object.hasOwnProperty.call(message, "requestId")) {
304
- if (!$util.isString(message.requestId))
305
- return "requestId: string expected";
306
- }
307
- if (message.traceCorrelationId != null && $Object.hasOwnProperty.call(message, "traceCorrelationId")) {
308
- if (!$util.isString(message.traceCorrelationId))
309
- return "traceCorrelationId: string expected";
310
- }
311
- if (message.originSystemAddress != null && $Object.hasOwnProperty.call(message, "originSystemAddress")) {
312
- if (!$util.isString(message.originSystemAddress))
313
- return "originSystemAddress: string expected";
314
- }
315
- if (message.timestamp != null && $Object.hasOwnProperty.call(message, "timestamp")) {
316
- if (!$util.isInteger(message.timestamp) && !(message.timestamp && $util.isInteger(message.timestamp.low) && $util.isInteger(message.timestamp.high)))
317
- return "timestamp: integer|Long expected";
318
- }
319
- if (message.method != null && $Object.hasOwnProperty.call(message, "method")) {
320
- if (!$util.isString(message.method))
321
- return "method: string expected";
322
- }
323
- if (message.collectorName != null && $Object.hasOwnProperty.call(message, "collectorName")) {
324
- if (!$util.isString(message.collectorName))
325
- return "collectorName: string expected";
326
- }
327
- if (message.jsonPayload != null && $Object.hasOwnProperty.call(message, "jsonPayload")) {
328
- if (!$util.isString(message.jsonPayload))
329
- return "jsonPayload: string expected";
330
- }
331
- if (message.binaryPayload != null && $Object.hasOwnProperty.call(message, "binaryPayload")) {
332
- if (!(message.binaryPayload && typeof message.binaryPayload.length === "number" || $util.isString(message.binaryPayload)))
333
- return "binaryPayload: buffer expected";
334
- }
335
- return null;
336
- };
337
- KrnlMessage.fromObject = function(object, _depth) {
338
- if (object instanceof $root.krnl.KrnlMessage)
339
- return object;
340
- if (!$util.isObject(object))
341
- throw $TypeError(".krnl.KrnlMessage: object expected");
342
- if (_depth === $undefined)
343
- _depth = 0;
344
- if (_depth > $util.recursionLimit)
345
- throw $Error("max depth exceeded");
346
- let message = new $root.krnl.KrnlMessage();
347
- if (object.kind !== 0 && (typeof object.kind !== "string" || $root.krnl.MessageKind[object.kind] !== 0))
348
- switch (object.kind) {
349
- case "UNKNOWN":
350
- case 0:
351
- message.kind = 0;
352
- break;
353
- case "REGISTER_INGRESS":
354
- case 1:
355
- message.kind = 1;
356
- break;
357
- case "ROUTE_DATA":
358
- case 2:
359
- message.kind = 2;
360
- break;
361
- case "RPC_REQUEST":
362
- case 3:
363
- message.kind = 3;
364
- break;
365
- case "RPC_RESPONSE":
366
- case 4:
367
- message.kind = 4;
368
- break;
369
- case "INTROSPECT":
370
- case 5:
371
- message.kind = 5;
372
- break;
373
- case "INTROSPECT_RESPONSE":
374
- case 6:
375
- message.kind = 6;
376
- break;
377
- default:
378
- if (typeof object.kind === "number" && (object.kind | 0) === object.kind)
379
- message.kind = object.kind;
380
- }
381
- if (object.routeId != null) {
382
- if (typeof object.routeId !== "string" || object.routeId.length)
383
- message.routeId = $String(object.routeId);
384
- }
385
- if (object.requestId != null) {
386
- if (typeof object.requestId !== "string" || object.requestId.length)
387
- message.requestId = $String(object.requestId);
388
- }
389
- if (object.traceCorrelationId != null) {
390
- if (typeof object.traceCorrelationId !== "string" || object.traceCorrelationId.length)
391
- message.traceCorrelationId = $String(object.traceCorrelationId);
392
- }
393
- if (object.originSystemAddress != null) {
394
- if (typeof object.originSystemAddress !== "string" || object.originSystemAddress.length)
395
- message.originSystemAddress = $String(object.originSystemAddress);
396
- }
397
- if (object.timestamp != null) {
398
- if (typeof object.timestamp === "object" ? object.timestamp.low || object.timestamp.high : $Number(object.timestamp) !== 0) {
399
- if ($util.Long)
400
- message.timestamp = $util.Long.fromValue(object.timestamp, false);
401
- else if (typeof object.timestamp === "string")
402
- message.timestamp = $parseInt(object.timestamp, 10);
403
- else if (typeof object.timestamp === "number")
404
- message.timestamp = object.timestamp;
405
- else if (typeof object.timestamp === "object")
406
- message.timestamp = new $util.LongBits(object.timestamp.low >>> 0, object.timestamp.high >>> 0).toNumber();
407
- }
408
- }
409
- if (object.method != null) {
410
- if (typeof object.method !== "string" || object.method.length)
411
- message.method = $String(object.method);
412
- }
413
- if (object.collectorName != null) {
414
- if (typeof object.collectorName !== "string" || object.collectorName.length)
415
- message.collectorName = $String(object.collectorName);
416
- }
417
- if (object.jsonPayload != null) {
418
- if (typeof object.jsonPayload !== "string" || object.jsonPayload.length)
419
- message.jsonPayload = $String(object.jsonPayload);
420
- }
421
- if (object.binaryPayload != null) {
422
- if (object.binaryPayload.length) {
423
- if (typeof object.binaryPayload === "string")
424
- $util.base64.decode(object.binaryPayload, message.binaryPayload = $util.newBuffer($util.base64.length(object.binaryPayload)), 0);
425
- else if (object.binaryPayload.length >= 0)
426
- message.binaryPayload = object.binaryPayload;
427
- }
428
- }
429
- return message;
430
- };
431
- KrnlMessage.toObject = function(message, options, _depth) {
432
- if (!options)
433
- options = {};
434
- if (_depth === $undefined)
435
- _depth = 0;
436
- if (_depth > $util.recursionLimit)
437
- throw $Error("max depth exceeded");
438
- let object = {};
439
- if (options.defaults) {
440
- object.kind = options.enums === $String ? "UNKNOWN" : 0;
441
- object.routeId = "";
442
- object.requestId = "";
443
- object.traceCorrelationId = "";
444
- object.originSystemAddress = "";
445
- if ($util.Long) {
446
- let long = new $util.Long(0, 0, false);
447
- object.timestamp = options.longs === $String ? long.toString() : options.longs === $Number ? long.toNumber() : typeof $BigInt !== "undefined" && options.longs === $BigInt ? long.toBigInt() : long;
448
- } else
449
- object.timestamp = options.longs === $String ? "0" : typeof $BigInt !== "undefined" && options.longs === $BigInt ? $BigInt("0") : 0;
450
- object.method = "";
451
- object.collectorName = "";
452
- object.jsonPayload = "";
453
- if (options.bytes === $String)
454
- object.binaryPayload = "";
455
- else {
456
- object.binaryPayload = [];
457
- if (options.bytes !== $Array)
458
- object.binaryPayload = $util.newBuffer(object.binaryPayload);
459
- }
460
- }
461
- if (message.kind != null && $Object.hasOwnProperty.call(message, "kind"))
462
- object.kind = options.enums === $String ? $root.krnl.MessageKind[message.kind] === $undefined ? message.kind : $root.krnl.MessageKind[message.kind] : message.kind;
463
- if (message.routeId != null && $Object.hasOwnProperty.call(message, "routeId"))
464
- object.routeId = message.routeId;
465
- if (message.requestId != null && $Object.hasOwnProperty.call(message, "requestId"))
466
- object.requestId = message.requestId;
467
- if (message.traceCorrelationId != null && $Object.hasOwnProperty.call(message, "traceCorrelationId"))
468
- object.traceCorrelationId = message.traceCorrelationId;
469
- if (message.originSystemAddress != null && $Object.hasOwnProperty.call(message, "originSystemAddress"))
470
- object.originSystemAddress = message.originSystemAddress;
471
- if (message.timestamp != null && $Object.hasOwnProperty.call(message, "timestamp"))
472
- if (typeof $BigInt !== "undefined" && options.longs === $BigInt)
473
- object.timestamp = typeof message.timestamp === "number" ? $BigInt(message.timestamp) : $util.Long.fromBits(message.timestamp.low >>> 0, message.timestamp.high >>> 0, false).toBigInt();
474
- else if (typeof message.timestamp === "number")
475
- object.timestamp = options.longs === $String ? $String(message.timestamp) : message.timestamp;
476
- else
477
- object.timestamp = options.longs === $String ? $util.Long.prototype.toString.call(message.timestamp) : options.longs === $Number ? new $util.LongBits(message.timestamp.low >>> 0, message.timestamp.high >>> 0).toNumber() : message.timestamp;
478
- if (message.method != null && $Object.hasOwnProperty.call(message, "method"))
479
- object.method = message.method;
480
- if (message.collectorName != null && $Object.hasOwnProperty.call(message, "collectorName"))
481
- object.collectorName = message.collectorName;
482
- if (message.jsonPayload != null && $Object.hasOwnProperty.call(message, "jsonPayload"))
483
- object.jsonPayload = message.jsonPayload;
484
- if (message.binaryPayload != null && $Object.hasOwnProperty.call(message, "binaryPayload"))
485
- object.binaryPayload = options.bytes === $String ? $util.base64.encode(message.binaryPayload, 0, message.binaryPayload.length) : options.bytes === $Array ? $Array.prototype.slice.call(message.binaryPayload) : message.binaryPayload;
486
- return object;
487
- };
488
- KrnlMessage.prototype.toJSON = function() {
489
- return KrnlMessage.toObject(this, $protobuf.util.toJSONOptions);
490
- };
491
- KrnlMessage.getTypeUrl = function(prefix) {
492
- if (prefix === $undefined)
493
- prefix = "type.googleapis.com";
494
- return prefix + "/krnl.KrnlMessage";
495
- };
496
- return KrnlMessage;
497
- })();
498
- krnl2.RpcResponse = (function() {
499
- const RpcResponse = function(properties) {
500
- if (properties) {
501
- for (let keys = $Object.keys(properties), i = 0; i < keys.length; ++i)
502
- if (properties[keys[i]] != null && keys[i] !== "__proto__")
503
- this[keys[i]] = properties[keys[i]];
504
- }
505
- };
506
- RpcResponse.prototype.requestId = "";
507
- RpcResponse.prototype.ok = false;
508
- RpcResponse.prototype.error = "";
509
- RpcResponse.prototype.jsonResult = "";
510
- RpcResponse.prototype.errorDocumentation = "";
511
- RpcResponse.create = function(properties) {
512
- return new RpcResponse(properties);
513
- };
514
- RpcResponse.encode = function(message, writer, _depth) {
515
- if (!writer)
516
- writer = $Writer.create();
517
- if (_depth === $undefined)
518
- _depth = 0;
519
- if (_depth > $util.recursionLimit)
520
- throw $Error("max depth exceeded");
521
- if (message.requestId != null && $Object.hasOwnProperty.call(message, "requestId") && message.requestId !== "")
522
- writer.uint32(
523
- /* id 1, wireType 2 =*/
524
- 10
525
- ).string(message.requestId);
526
- if (message.ok != null && $Object.hasOwnProperty.call(message, "ok") && message.ok !== false)
527
- writer.uint32(
528
- /* id 2, wireType 0 =*/
529
- 16
530
- ).bool(message.ok);
531
- if (message.error != null && $Object.hasOwnProperty.call(message, "error") && message.error !== "")
532
- writer.uint32(
533
- /* id 3, wireType 2 =*/
534
- 26
535
- ).string(message.error);
536
- if (message.jsonResult != null && $Object.hasOwnProperty.call(message, "jsonResult") && message.jsonResult !== "")
537
- writer.uint32(
538
- /* id 4, wireType 2 =*/
539
- 34
540
- ).string(message.jsonResult);
541
- if (message.errorDocumentation != null && $Object.hasOwnProperty.call(message, "errorDocumentation") && message.errorDocumentation !== "")
542
- writer.uint32(
543
- /* id 5, wireType 2 =*/
544
- 42
545
- ).string(message.errorDocumentation);
546
- if (message.$unknowns != null && $Object.hasOwnProperty.call(message, "$unknowns"))
547
- for (let i = 0; i < message.$unknowns.length; ++i)
548
- writer.raw(message.$unknowns[i]);
549
- return writer;
550
- };
551
- RpcResponse.encodeDelimited = function(message, writer) {
552
- return this.encode(message, (writer || $Writer.create()).fork()).ldelim();
553
- };
554
- RpcResponse.decode = function(reader, length, _end, _depth, _target) {
555
- if (!(reader instanceof $Reader))
556
- reader = $Reader.create(reader);
557
- if (_depth === $undefined)
558
- _depth = 0;
559
- if (_depth > $Reader.recursionLimit)
560
- throw $Error("max depth exceeded");
561
- let end = length === $undefined ? reader.len : reader.pos + length, message = _target || new $root.krnl.RpcResponse(), value;
562
- while (reader.pos < end) {
563
- let start = reader.pos;
564
- let tag = reader.tag();
565
- if (tag === _end) {
566
- _end = $undefined;
567
- break;
568
- }
569
- let wireType = tag & 7;
570
- switch (tag >>>= 3) {
571
- case 1: {
572
- if (wireType !== 2)
573
- break;
574
- if ((value = reader.stringVerify()).length)
575
- message.requestId = value;
576
- else
577
- delete message.requestId;
578
- continue;
579
- }
580
- case 2: {
581
- if (wireType !== 0)
582
- break;
583
- if (value = reader.bool())
584
- message.ok = value;
585
- else
586
- delete message.ok;
587
- continue;
588
- }
589
- case 3: {
590
- if (wireType !== 2)
591
- break;
592
- if ((value = reader.stringVerify()).length)
593
- message.error = value;
594
- else
595
- delete message.error;
596
- continue;
597
- }
598
- case 4: {
599
- if (wireType !== 2)
600
- break;
601
- if ((value = reader.stringVerify()).length)
602
- message.jsonResult = value;
603
- else
604
- delete message.jsonResult;
605
- continue;
606
- }
607
- case 5: {
608
- if (wireType !== 2)
609
- break;
610
- if ((value = reader.stringVerify()).length)
611
- message.errorDocumentation = value;
612
- else
613
- delete message.errorDocumentation;
614
- continue;
615
- }
616
- }
617
- reader.skipType(wireType, _depth, tag);
618
- if (!reader.discardUnknown) {
619
- $util.makeProp(message, "$unknowns", false);
620
- (message.$unknowns || (message.$unknowns = [])).push(reader.raw(start, reader.pos));
621
- }
622
- }
623
- if (_end !== $undefined)
624
- throw $Error("missing end group");
625
- return message;
626
- };
627
- RpcResponse.decodeDelimited = function(reader) {
628
- if (!(reader instanceof $Reader))
629
- reader = new $Reader(reader);
630
- return this.decode(reader, reader.uint32());
631
- };
632
- RpcResponse.verify = function(message, _depth) {
633
- if (typeof message !== "object" || message === null)
634
- return "object expected";
635
- if (_depth === $undefined)
636
- _depth = 0;
637
- if (_depth > $util.recursionLimit)
638
- return "max depth exceeded";
639
- if (message.requestId != null && $Object.hasOwnProperty.call(message, "requestId")) {
640
- if (!$util.isString(message.requestId))
641
- return "requestId: string expected";
642
- }
643
- if (message.ok != null && $Object.hasOwnProperty.call(message, "ok")) {
644
- if (typeof message.ok !== "boolean")
645
- return "ok: boolean expected";
646
- }
647
- if (message.error != null && $Object.hasOwnProperty.call(message, "error")) {
648
- if (!$util.isString(message.error))
649
- return "error: string expected";
650
- }
651
- if (message.jsonResult != null && $Object.hasOwnProperty.call(message, "jsonResult")) {
652
- if (!$util.isString(message.jsonResult))
653
- return "jsonResult: string expected";
654
- }
655
- if (message.errorDocumentation != null && $Object.hasOwnProperty.call(message, "errorDocumentation")) {
656
- if (!$util.isString(message.errorDocumentation))
657
- return "errorDocumentation: string expected";
658
- }
659
- return null;
660
- };
661
- RpcResponse.fromObject = function(object, _depth) {
662
- if (object instanceof $root.krnl.RpcResponse)
663
- return object;
664
- if (!$util.isObject(object))
665
- throw $TypeError(".krnl.RpcResponse: object expected");
666
- if (_depth === $undefined)
667
- _depth = 0;
668
- if (_depth > $util.recursionLimit)
669
- throw $Error("max depth exceeded");
670
- let message = new $root.krnl.RpcResponse();
671
- if (object.requestId != null) {
672
- if (typeof object.requestId !== "string" || object.requestId.length)
673
- message.requestId = $String(object.requestId);
674
- }
675
- if (object.ok != null) {
676
- if (object.ok)
677
- message.ok = $Boolean(object.ok);
678
- }
679
- if (object.error != null) {
680
- if (typeof object.error !== "string" || object.error.length)
681
- message.error = $String(object.error);
682
- }
683
- if (object.jsonResult != null) {
684
- if (typeof object.jsonResult !== "string" || object.jsonResult.length)
685
- message.jsonResult = $String(object.jsonResult);
686
- }
687
- if (object.errorDocumentation != null) {
688
- if (typeof object.errorDocumentation !== "string" || object.errorDocumentation.length)
689
- message.errorDocumentation = $String(object.errorDocumentation);
690
- }
691
- return message;
692
- };
693
- RpcResponse.toObject = function(message, options, _depth) {
694
- if (!options)
695
- options = {};
696
- if (_depth === $undefined)
697
- _depth = 0;
698
- if (_depth > $util.recursionLimit)
699
- throw $Error("max depth exceeded");
700
- let object = {};
701
- if (options.defaults) {
702
- object.requestId = "";
703
- object.ok = false;
704
- object.error = "";
705
- object.jsonResult = "";
706
- object.errorDocumentation = "";
707
- }
708
- if (message.requestId != null && $Object.hasOwnProperty.call(message, "requestId"))
709
- object.requestId = message.requestId;
710
- if (message.ok != null && $Object.hasOwnProperty.call(message, "ok"))
711
- object.ok = message.ok;
712
- if (message.error != null && $Object.hasOwnProperty.call(message, "error"))
713
- object.error = message.error;
714
- if (message.jsonResult != null && $Object.hasOwnProperty.call(message, "jsonResult"))
715
- object.jsonResult = message.jsonResult;
716
- if (message.errorDocumentation != null && $Object.hasOwnProperty.call(message, "errorDocumentation"))
717
- object.errorDocumentation = message.errorDocumentation;
718
- return object;
719
- };
720
- RpcResponse.prototype.toJSON = function() {
721
- return RpcResponse.toObject(this, $protobuf.util.toJSONOptions);
722
- };
723
- RpcResponse.getTypeUrl = function(prefix) {
724
- if (prefix === $undefined)
725
- prefix = "type.googleapis.com";
726
- return prefix + "/krnl.RpcResponse";
727
- };
728
- return RpcResponse;
729
- })();
730
- return krnl2;
731
- })();
732
-
733
- // src/core/K_LIB_Krnl_System_Comm_Component.ts
734
- var WebSocketTransportAdapter = class extends krnlTransportAdapter {
735
- commComponent;
736
- remoteAddress;
737
- /**
738
- * @param commComponent - The local system's comm component.
739
- * @param remoteAddress - "host:port" of the remote system.
740
- */
741
- constructor(commComponent, remoteAddress) {
742
- super();
743
- this.commComponent = commComponent;
744
- this.remoteAddress = remoteAddress;
745
- }
746
- async call(targetFunction, input, opts = {}) {
747
- const policy = opts.policy instanceof KrnlPolicy ? opts.policy : new KrnlPolicy(opts);
748
- const data = {
749
- ...input,
750
- meta: {
751
- ...input?.meta || {},
752
- accessKey: opts.accessKey
753
- }
754
- };
755
- return await this.commComponent.callWsRpc(this.remoteAddress, "call", { fid: targetFunction, data }, policy);
756
- }
757
- };
758
- var _WS;
759
- var _WSServer;
760
- async function _loadWs() {
761
- if (!_WS) {
762
- const mod = await import("ws");
763
- _WS = mod.WebSocket;
764
- _WSServer = mod.WebSocketServer;
765
- }
766
- return { WebSocket: _WS, WebSocketServer: _WSServer };
767
- }
768
- var krnlSystemCommComponent = class {
769
- name = "wss";
770
- ownerEntity;
771
- listenPort;
772
- host;
773
- routes;
774
- _routeSeq;
775
- _wsServer;
776
- _wsClients;
777
- _wsIngress;
778
- _wsPendingRpc;
779
- _wsRpcHandlers;
780
- _introspectionProvider;
781
- /**
782
- * @param ownerEntity
783
- * @param listenPort - WS server port (only used in "ws" mode).
784
- * @param host - Interface to bind to.
785
- */
786
- constructor(ownerEntity, listenPort = 10099, host = "0.0.0.0") {
787
- this.ownerEntity = ownerEntity;
788
- this.listenPort = listenPort;
789
- this.host = host;
790
- this.routes = /* @__PURE__ */ new Map();
791
- this._routeSeq = 0;
792
- this._wsServer = null;
793
- this._wsClients = /* @__PURE__ */ new Map();
794
- this._wsIngress = /* @__PURE__ */ new Map();
795
- this._wsPendingRpc = /* @__PURE__ */ new Map();
796
- this._wsRpcHandlers = /* @__PURE__ */ new Map();
797
- this._introspectionProvider = null;
798
- }
799
- /**
800
- * Binds a local emitter directly to another in-process system's collector.
801
- */
802
- wireDirectly(localEmitterName, remoteCommComponent, remoteCollectorName) {
803
- const emitter = this.ownerEntity.interface.getEmitter(localEmitterName);
804
- const remoteCollector = remoteCommComponent.ownerEntity.interface.getCollector(remoteCollectorName);
805
- const unsubscribe = emitter.subscribe((msg) => {
806
- if (remoteCollector.emitter) {
807
- remoteCollector.emitter.pushDataStreamToEmitter(msg.data);
808
- }
809
- if (remoteCollector._directHandler) {
810
- remoteCollector._directHandler(msg);
811
- }
812
- });
813
- const routeId = `route_${this._routeSeq++}`;
814
- const route = {
815
- id: routeId,
816
- sourceEmitter: localEmitterName,
817
- targetSystem: remoteCommComponent.ownerEntity.entityName,
818
- targetCollector: remoteCollectorName,
819
- mode: "direct",
820
- disconnect: unsubscribe
821
- };
822
- this.routes.set(routeId, route);
823
- Logger.log(
824
- `[CommComponent:${this.ownerEntity.entityName}] DIRECT route created: ${localEmitterName} \u2192 ${route.targetSystem}.${remoteCollectorName}`
825
- );
826
- return route;
827
- }
828
- /**
829
- * Starts a WebSocket server so that remote systems can push data into local collectors.
830
- */
831
- async startWsServer(externalServer = null) {
832
- if (this._wsServer) return;
833
- const { WebSocketServer } = await _loadWs();
834
- return new Promise((resolve, reject) => {
835
- if (externalServer) {
836
- const targetWsPath = this.ownerEntity.options?.wsPath || "/ws";
837
- this._wsServer = new WebSocketServer({ noServer: true });
838
- externalServer.on("upgrade", (req, socket, head) => {
839
- const url = new URL(req.url || "", `http://${req.headers.host || "localhost"}`);
840
- if (url.pathname === targetWsPath) {
841
- if (socket.upgraded || socket._krnlCommUpgraded || !socket.readable) return;
842
- socket._krnlCommUpgraded = true;
843
- try {
844
- this._wsServer.handleUpgrade(req, socket, head, (ws) => {
845
- this._wsServer.emit("connection", ws);
846
- });
847
- } catch (e) {
848
- }
849
- }
850
- });
851
- resolve();
852
- } else {
853
- this._wsServer = new WebSocketServer({ port: this.listenPort, host: this.host });
854
- this._wsServer.on("listening", () => {
855
- Logger.log(`[CommComponent:${this.ownerEntity.entityName}] WS server listening on :${this.listenPort}`);
856
- resolve();
857
- });
858
- }
859
- this._wsServer.on("error", (err) => {
860
- Logger.error(`[CommComponent:${this.ownerEntity.entityName}] WS server error:`, err.message);
861
- reject(err);
862
- });
863
- this._wsServer.on("connection", (ws) => {
864
- ws.on("error", (err) => {
865
- Logger.error(`[CommComponent:${this.ownerEntity.entityName}] Incoming WS error:`, err.message);
866
- });
867
- ws.on("message", (raw) => {
868
- try {
869
- let msg;
870
- const rawStr = raw.toString().trim();
871
- if (rawStr.startsWith("{") && rawStr.endsWith("}")) {
872
- const parsed = JSON.parse(rawStr);
873
- msg = {
874
- isJson: true,
875
- kind: parsed.kind === "rpc-request" ? krnl.MessageKind.RPC_REQUEST : parsed.kind === "rpc-response" ? krnl.MessageKind.RPC_RESPONSE : parsed.kind === "register-ingress" ? krnl.MessageKind.REGISTER_INGRESS : parsed.kind === "route-data" ? krnl.MessageKind.ROUTE_DATA : parsed.kind === "introspect" ? krnl.MessageKind.INTROSPECT : krnl.MessageKind.UNKNOWN,
876
- routeId: parsed.routeId || "",
877
- requestId: parsed.requestId || "",
878
- method: parsed.method || "",
879
- collectorName: parsed.collectorName || "",
880
- jsonPayload: parsed.params ? JSON.stringify(parsed.params) : parsed.data ? JSON.stringify(parsed.data) : ""
881
- };
882
- } else {
883
- msg = krnl.KrnlMessage.decode(new Uint8Array(raw));
884
- }
885
- if (msg.kind === krnl.MessageKind.REGISTER_INGRESS) {
886
- this.registerWsIngress(msg.routeId, msg.collectorName);
887
- return;
888
- }
889
- if (msg.kind === krnl.MessageKind.ROUTE_DATA) {
890
- const handler = this._wsIngress.get(msg.routeId);
891
- if (handler) {
892
- const payload = msg.jsonPayload ? JSON.parse(msg.jsonPayload) : void 0;
893
- handler(payload);
894
- }
895
- return;
896
- }
897
- if (msg.kind === krnl.MessageKind.RPC_REQUEST) {
898
- const callerPort = ws._socket?.remotePort;
899
- this._handleRpcRequest(ws, msg, callerPort);
900
- return;
901
- }
902
- if (msg.kind === krnl.MessageKind.RPC_RESPONSE) {
903
- this._handleRpcResponse(msg);
904
- return;
905
- }
906
- if (msg.kind === krnl.MessageKind.INTROSPECT) {
907
- this._handleIntrospect(ws, msg);
908
- return;
909
- }
910
- } catch (e) {
911
- Logger.error(`[CommComponent:${this.ownerEntity.entityName}] WS message error:`, e.message);
912
- }
913
- });
914
- });
915
- });
916
- }
917
- /**
918
- * Connects to a remote system's CommComponent WS server.
919
- */
920
- async wireViaWs(localEmitterName, remoteAddress, remoteCollectorName, remoteSystemName, options = {}) {
921
- const { WebSocket } = await _loadWs();
922
- const emitter = this.ownerEntity.interface.getEmitter(localEmitterName);
923
- const ws = new WebSocket(`ws://${remoteAddress}`);
924
- const {
925
- managedBy = this.ownerEntity.entityName,
926
- externallyMutable = true,
927
- metadata = {}
928
- } = options;
929
- await new Promise((resolve, reject) => {
930
- ws.once("open", resolve);
931
- ws.once("error", reject);
932
- });
933
- ws.on("error", (err) => {
934
- Logger.error(`[CommComponent:${this.ownerEntity.entityName}] Outgoing WS error to ${remoteSystemName}:`, err.message);
935
- });
936
- this._wsClients.set(remoteSystemName, ws);
937
- const routeId = `ws_route_${this._routeSeq++}`;
938
- const regMsg = krnl.KrnlMessage.encode({
939
- kind: krnl.MessageKind.REGISTER_INGRESS,
940
- routeId,
941
- collectorName: remoteCollectorName
942
- }).finish();
943
- ws.send(regMsg);
944
- const unsubscribe = emitter.subscribe((msg) => {
945
- if (ws.readyState === _WS.OPEN) {
946
- const dataMsg = krnl.KrnlMessage.encode({
947
- kind: krnl.MessageKind.ROUTE_DATA,
948
- routeId,
949
- jsonPayload: JSON.stringify(msg.data)
950
- }).finish();
951
- ws.send(dataMsg);
952
- }
953
- });
954
- const route = {
955
- id: routeId,
956
- sourceEmitter: localEmitterName,
957
- targetSystem: remoteSystemName,
958
- targetCollector: remoteCollectorName,
959
- mode: "ws",
960
- managedBy,
961
- externallyMutable,
962
- metadata,
963
- disconnect: () => {
964
- unsubscribe();
965
- ws.close();
966
- this._wsClients.delete(remoteSystemName);
967
- }
968
- };
969
- this.routes.set(routeId, route);
970
- Logger.log(
971
- `[CommComponent:${this.ownerEntity.entityName}] WS route created: ${localEmitterName} \u2192 ${remoteSystemName}.${remoteCollectorName} @ ${remoteAddress}`
972
- );
973
- return route;
974
- }
975
- /**
976
- * Registers a WS ingress handler.
977
- */
978
- registerWsIngress(routeId, localCollectorName) {
979
- this._wsIngress.set(routeId, (data) => {
980
- const collector = this.ownerEntity.interface.getCollector(localCollectorName);
981
- if (collector._directHandler) {
982
- collector._directHandler({ data });
983
- }
984
- });
985
- }
986
- defineRpc(methodName, handler) {
987
- this._wsRpcHandlers.set(methodName, handler);
988
- }
989
- setIntrospectionProvider(providerFn) {
990
- this._introspectionProvider = providerFn;
991
- }
992
- async _getWsRpcClient(remoteAddress) {
993
- const { WebSocket } = await _loadWs();
994
- let ws = this._wsClients.get(remoteAddress);
995
- if (ws && (ws.readyState === 1 || ws.readyState === 0)) {
996
- return ws;
997
- }
998
- ws = new WebSocket(`ws://${remoteAddress}`);
999
- this._wsClients.set(remoteAddress, ws);
1000
- ws.on("error", (err) => {
1001
- Logger.error(`[CommComponent:${this.ownerEntity.entityName}] WS error to ${remoteAddress}:`, err.message);
1002
- this._wsClients.delete(remoteAddress);
1003
- });
1004
- ws.on("close", () => {
1005
- this._wsClients.delete(remoteAddress);
1006
- });
1007
- ws.on("message", (raw) => {
1008
- try {
1009
- let msg;
1010
- const rawStr = raw.toString().trim();
1011
- if (rawStr.startsWith("{") && rawStr.endsWith("}")) {
1012
- const parsed = JSON.parse(rawStr);
1013
- msg = {
1014
- kind: parsed.kind === "rpc-response" ? krnl.MessageKind.RPC_RESPONSE : krnl.MessageKind.UNKNOWN,
1015
- requestId: parsed.requestId || "",
1016
- ok: parsed.ok,
1017
- error: parsed.error,
1018
- result: parsed.result
1019
- };
1020
- } else {
1021
- msg = krnl.KrnlMessage.decode(new Uint8Array(raw));
1022
- }
1023
- if (msg.kind === krnl.MessageKind.RPC_RESPONSE) {
1024
- this._handleRpcResponse(msg);
1025
- }
1026
- } catch (_) {
1027
- }
1028
- });
1029
- await new Promise((resolve, reject) => {
1030
- const connTimeout = setTimeout(() => {
1031
- ws.close();
1032
- reject(new Error("ERR_NET_CONNECTION_TIMEOUT"));
1033
- }, 5e3);
1034
- ws.once("open", () => {
1035
- clearTimeout(connTimeout);
1036
- resolve(true);
1037
- });
1038
- ws.once("error", (err) => {
1039
- clearTimeout(connTimeout);
1040
- reject(err);
1041
- });
1042
- });
1043
- return ws;
1044
- }
1045
- async callWsRpc(remoteAddress, method, params = {}, policy = KrnlPolicy.default()) {
1046
- let lastError = null;
1047
- for (let attempt = 0; attempt <= policy.maxRetries; attempt++) {
1048
- try {
1049
- const requestId = `rpc_${Date.now()}_${Math.random().toString(36).slice(2)}`;
1050
- const ws = await this._getWsRpcClient(remoteAddress);
1051
- const result = await new Promise((resolve, reject) => {
1052
- const timeoutId = setTimeout(() => {
1053
- this._wsPendingRpc.delete(requestId);
1054
- reject({ code: krnlErrorCodes.ERR_NET_RPC_TIMEOUT_EXCEEDED, message: "ERR_NET_RPC_TIMEOUT_EXCEEDED" });
1055
- }, policy.timeoutMs);
1056
- this._wsPendingRpc.set(requestId, { resolve, reject, timeoutId, ws });
1057
- const rpcReq = krnl.KrnlMessage.encode({
1058
- kind: krnl.MessageKind.RPC_REQUEST,
1059
- requestId,
1060
- traceCorrelationId: requestId,
1061
- originSystemAddress: this.ownerEntity.entityName,
1062
- timestamp: Date.now(),
1063
- method,
1064
- jsonPayload: JSON.stringify(params)
1065
- }).finish();
1066
- ws.send(rpcReq);
1067
- });
1068
- return result;
1069
- } catch (err) {
1070
- lastError = err;
1071
- if (attempt < policy.maxRetries) {
1072
- const delay = policy.backoffStrategy === "EXPONENTIAL" ? policy.retryDelayMs * Math.pow(2, attempt) : policy.retryDelayMs;
1073
- Logger.log(`[CommComponent:${this.ownerEntity.entityName}] RPC failed (attempt ${attempt + 1}). Retrying in ${delay}ms...`);
1074
- await new Promise((r) => setTimeout(r, delay));
1075
- }
1076
- }
1077
- }
1078
- throw lastError;
1079
- }
1080
- async _handleRpcRequest(ws, msg, callerPort) {
1081
- const { requestId, method } = msg;
1082
- const params = msg.jsonPayload ? JSON.parse(msg.jsonPayload) : void 0;
1083
- if (params?.target && this.ownerEntity._ingressNetwork) {
1084
- const member = this.ownerEntity._ingressNetwork.members.get(params.target.toLowerCase());
1085
- if (member) {
1086
- const { target, ...memberParams } = params;
1087
- const memberMsg = { ...msg, jsonPayload: JSON.stringify(memberParams) };
1088
- await member.entity.commComponent._handleRpcRequest(ws, memberMsg, callerPort);
1089
- return;
1090
- }
1091
- }
1092
- const sendResp = (ok, resultOrErr) => {
1093
- if (msg.isJson) {
1094
- const resp = {
1095
- kind: "rpc-response",
1096
- requestId,
1097
- ok,
1098
- ...ok ? { result: resultOrErr } : { error: typeof resultOrErr === "string" ? resultOrErr : resultOrErr.message }
1099
- };
1100
- ws.send(JSON.stringify(resp));
1101
- } else {
1102
- const rpcResp = krnl.RpcResponse.encode({
1103
- requestId,
1104
- ok,
1105
- ...ok ? { jsonResult: JSON.stringify(resultOrErr) } : { error: typeof resultOrErr === "string" ? resultOrErr : resultOrErr.message, errorDocumentation: resultOrErr.errorDocumentation || "" }
1106
- }).finish();
1107
- const envelope = krnl.KrnlMessage.encode({
1108
- kind: krnl.MessageKind.RPC_RESPONSE,
1109
- requestId,
1110
- binaryPayload: rpcResp
1111
- }).finish();
1112
- ws.send(envelope);
1113
- }
1114
- };
1115
- const handler = this._wsRpcHandlers.get(method);
1116
- if (!handler) {
1117
- sendResp(false, `Unknown RPC method: ${method}`);
1118
- return;
1119
- }
1120
- try {
1121
- const result = await handler(params, { callerPort });
1122
- sendResp(true, result);
1123
- } catch (e) {
1124
- sendResp(false, e);
1125
- }
1126
- }
1127
- async _handleIntrospect(ws, msg) {
1128
- const baseInfo = {
1129
- entity: this.ownerEntity.entityName,
1130
- methods: Array.from(this._wsRpcHandlers.keys())
1131
- };
1132
- let finalInfo = baseInfo;
1133
- if (this._introspectionProvider) {
1134
- try {
1135
- const extra = await this._introspectionProvider();
1136
- finalInfo = { ...baseInfo, ...extra };
1137
- } catch (e) {
1138
- finalInfo = { ...baseInfo, error: `Introspection provider failed: ${e.message}` };
1139
- }
1140
- }
1141
- const envelope = krnl.KrnlMessage.encode({
1142
- kind: krnl.MessageKind.INTROSPECT_RESPONSE,
1143
- requestId: msg.requestId,
1144
- jsonPayload: JSON.stringify(finalInfo)
1145
- }).finish();
1146
- ws.send(envelope);
1147
- }
1148
- _handleRpcResponse(msg) {
1149
- let responseMsg = msg;
1150
- if (msg.binaryPayload) {
1151
- try {
1152
- const dec = krnl.RpcResponse.decode(msg.binaryPayload);
1153
- responseMsg = {
1154
- requestId: dec.requestId,
1155
- ok: dec.ok,
1156
- error: dec.error,
1157
- result: dec.jsonResult ? JSON.parse(dec.jsonResult) : void 0,
1158
- errorDocumentation: dec.errorDocumentation
1159
- };
1160
- } catch (e) {
1161
- Logger.error("Failed to decode RpcResponse payload:", e);
1162
- }
1163
- }
1164
- const pending = this._wsPendingRpc.get(responseMsg.requestId);
1165
- if (!pending) return;
1166
- clearTimeout(pending.timeoutId);
1167
- this._wsPendingRpc.delete(responseMsg.requestId);
1168
- if (responseMsg.ok) pending.resolve(responseMsg.result);
1169
- else pending.reject(new Error(responseMsg.error || "RPC error"));
1170
- }
1171
- listRoutes() {
1172
- return Array.from(this.routes.values()).map((r) => ({
1173
- id: r.id,
1174
- sourceEmitter: r.sourceEmitter,
1175
- targetSystem: r.targetSystem,
1176
- targetCollector: r.targetCollector,
1177
- mode: r.mode,
1178
- managedBy: r.managedBy || null,
1179
- externallyMutable: r.externallyMutable !== false,
1180
- metadata: r.metadata || {}
1181
- }));
1182
- }
1183
- disconnectRoute(routeId, options = {}) {
1184
- const { requester = null, force = false } = options;
1185
- const route = this.routes.get(routeId);
1186
- if (!route) throw new Error(`[CommComponent] Route not found: ${routeId}`);
1187
- if (!force && route.externallyMutable === false) {
1188
- const manager = route.managedBy || this.ownerEntity.entityName;
1189
- if (requester && requester !== manager) {
1190
- throw new Error(`[CommComponent] Route ${routeId} is immutable for requester ${requester}.`);
1191
- }
1192
- }
1193
- if (route.disconnect) route.disconnect();
1194
- this.routes.delete(routeId);
1195
- }
1196
- async start(entity = null, options = {}) {
1197
- if (entity && typeof entity.call === "function") {
1198
- this.ownerEntity = entity;
1199
- }
1200
- if (options.port) this.listenPort = options.port;
1201
- if (options.host) this.host = options.host;
1202
- if (!this._wsRpcHandlers.has("call")) {
1203
- this.defineRpc("call", async ({ fid, data }) => {
1204
- if (this.ownerEntity._assertAvailableForRemoteAccess) {
1205
- this.ownerEntity._assertAvailableForRemoteAccess(data?.meta?.requester || null);
1206
- }
1207
- const result = await this.ownerEntity.call(fid, data);
1208
- return { status: "success", result };
1209
- });
1210
- }
1211
- if (!this._wsRpcHandlers.has("heartbeat")) {
1212
- this.defineRpc("heartbeat", async ({ meta } = {}) => {
1213
- if (this.ownerEntity._assertAvailableForRemoteAccess) {
1214
- this.ownerEntity._assertAvailableForRemoteAccess(meta?.requester || null);
1215
- }
1216
- return { status: "alive", entity: this.ownerEntity.entityName, timestamp: Date.now() };
1217
- });
1218
- }
1219
- if (!this._wsRpcHandlers.has("connect-to-target")) {
1220
- this.defineRpc("connect-to-target", async ({ sourceEmitter, targetAddress, targetCollector, targetName, requester, connectionPolicy = {} }) => {
1221
- if (this.ownerEntity._assertAvailableForRemoteAccess) {
1222
- this.ownerEntity._assertAvailableForRemoteAccess(requester || null);
1223
- }
1224
- return await this.wireViaWs(sourceEmitter, targetAddress, targetCollector, targetName, {
1225
- managedBy: connectionPolicy.managedBy || requester || this.ownerEntity.entityName,
1226
- externallyMutable: connectionPolicy.externallyMutable !== false,
1227
- metadata: connectionPolicy.metadata || {}
1228
- });
1229
- });
1230
- }
1231
- if (!this._wsRpcHandlers.has("disconnect-from-target")) {
1232
- this.defineRpc("disconnect-from-target", async ({ routeId, requester, force = false }) => {
1233
- this.disconnectRoute(routeId, { requester, force });
1234
- return { ok: true, routeId };
1235
- });
1236
- }
1237
- if (!this._wsRpcHandlers.has("disconnect-route")) {
1238
- this.defineRpc("disconnect-route", async ({ routeId, requester, force = false }) => {
1239
- this.disconnectRoute(routeId, { requester, force });
1240
- return { ok: true, routeId };
1241
- });
1242
- }
1243
- if (!this._wsRpcHandlers.has("list-routes")) {
1244
- this.defineRpc("list-routes", async () => {
1245
- return this.listRoutes();
1246
- });
1247
- }
1248
- if (!this._wsRpcHandlers.has("list-connections")) {
1249
- this.defineRpc("list-connections", async () => {
1250
- return this.listRoutes();
1251
- });
1252
- }
1253
- await this.startWsServer();
1254
- }
1255
- onCapabilitySurfaceChanged(entity) {
1256
- this.ownerEntity = entity;
1257
- }
1258
- async stop() {
1259
- this.dispose();
1260
- }
1261
- dispose() {
1262
- for (const [id] of this.routes) {
1263
- try {
1264
- this.disconnectRoute(id, { force: true });
1265
- } catch (_) {
1266
- }
1267
- }
1268
- if (this._wsServer) {
1269
- this._wsServer.close();
1270
- this._wsServer = null;
1271
- }
1272
- for (const ws of this._wsClients.values()) ws.close();
1273
- this._wsClients.clear();
1274
- this._wsIngress.clear();
1275
- for (const pending of this._wsPendingRpc.values()) {
1276
- clearTimeout(pending.timeoutId);
1277
- pending.reject(new Error("CommComponent disposed"));
1278
- }
1279
- this._wsPendingRpc.clear();
1280
- this._wsRpcHandlers.clear();
1281
- const label = this.ownerEntity ? this.ownerEntity.entityName || this.ownerEntity.id : "Unknown";
1282
- Logger.log(`[CommComponent:${label}] Disposed.`);
1283
- }
1284
- };
1285
-
1286
- // src/core/K_LIB_Krnl_System_Ingress_Network.ts
1287
- import path from "path";
1288
- var KrnlSiblingNetwork = class {
1289
- members = /* @__PURE__ */ new Map();
1290
- /**
1291
- * addMember — adds a standalone sibling KrnlTS application to the peer network.
1292
- *
1293
- * The sibling is instantiated and its port is registered in the admin's port registry.
1294
- * Unlike sub-apps, siblings start their own networking and are independently addressable.
1295
- *
1296
- * ⚠ Do not call this for sub-apps. Use entity.loadSubApps() instead.
1297
- */
1298
- async addMember(admin, config) {
1299
- const prefix = config.prefix.toLowerCase();
1300
- if (this.members.has(prefix)) {
1301
- console.log(`[SiblingNetwork] Member prefix '${prefix}' already registered. Returning existing entity.`);
1302
- return this.members.get(prefix).entity;
1303
- }
1304
- let entity;
1305
- if (config.isKrnl === false || !config.ServiceClass) {
1306
- const { KrnlNonKrnlAppAdapter } = await import("./K_LIB_Krnl_System_App_Adapter-32MFJJ5Z.js");
1307
- const adapter = new KrnlNonKrnlAppAdapter(config.prefix, config.entryPath || "");
1308
- await adapter.startApp();
1309
- entity = adapter;
1310
- } else {
1311
- const ServiceClass = config.ServiceClass;
1312
- const memberPort = config.port ?? -1;
1313
- const args = config.constructorArgs ?? [];
1314
- const { subappLocalStorage } = await import("./K_LIB_Krnl_System_Magnetic_Loader-B2NZMQUG.js");
1315
- const appDir = config.entryPath ? path.dirname(config.entryPath) : "";
1316
- entity = await subappLocalStorage.run({ appPath: appDir }, async () => {
1317
- const ent = new ServiceClass(memberPort, ...args);
1318
- if (ent._magneticLoadPromise) {
1319
- await ent._magneticLoadPromise;
1320
- }
1321
- return ent;
1322
- });
1323
- }
1324
- entity._isIngressNetworkMember = true;
1325
- if (typeof entity._resolveReady === "function") {
1326
- entity._resolveReady();
1327
- }
1328
- admin.hierarchyManager.addComponentEntityInstance(entity);
1329
- await admin.registerPort(prefix, -1);
1330
- this.members.set(prefix, {
1331
- entity,
1332
- config,
1333
- addedAt: Date.now(),
1334
- memberType: "sibling"
1335
- });
1336
- return entity;
1337
- }
1338
- /**
1339
- * removeMember — removes a sibling from the peer network.
1340
- */
1341
- async removeMember(admin, prefix) {
1342
- const key = prefix.toLowerCase();
1343
- const entry = this.members.get(key);
1344
- if (!entry) return false;
1345
- await admin.unregisterPort(key);
1346
- admin.hierarchyManager.disposeComponentEntity(entry.entity.id);
1347
- this.members.delete(key);
1348
- return true;
1349
- }
1350
- /**
1351
- * getGrossManifest — returns a listing of all siblings and their manifest endpoints.
1352
- */
1353
- getGrossManifest(adminBaseUrl) {
1354
- const list = Array.from(this.members.entries()).map(([prefix, entry]) => ({
1355
- prefix,
1356
- entityName: entry.entity.entityName,
1357
- manifestEndpoint: `${adminBaseUrl}/${prefix}/manifest`
1358
- }));
1359
- return {
1360
- type: "SiblingNetworkManifest",
1361
- members: list
1362
- };
1363
- }
1364
- /**
1365
- * getAggregatedMcpTools — collects public MCP tool definitions from all siblings.
1366
- */
1367
- getAggregatedMcpTools() {
1368
- const allTools = [];
1369
- for (const [prefix, entry] of this.members.entries()) {
1370
- const manifest = entry.entity.getManifest();
1371
- const apis = manifest?.inputs?.api || {};
1372
- for (const fid of Object.keys(apis)) {
1373
- const api = apis[fid];
1374
- if (api.visibility === "public") {
1375
- allTools.push({
1376
- name: `${prefix}.${fid}`,
1377
- description: api.description || `MCP Tool for ${entry.entity.entityName} functionality: ${fid}`,
1378
- inputSchema: api.schema?.input || { type: "object" }
1379
- });
1380
- }
1381
- }
1382
- }
1383
- return allTools;
1384
- }
1385
- /**
1386
- * routeHttpRequest — routes an incoming HTTP request to the correct sibling's handler.
1387
- * The sibling's own unifiedHttpAdapter handles the request in-process.
1388
- */
1389
- async routeHttpRequest(prefix, req, res, subPath) {
1390
- const entry = this.members.get(prefix.toLowerCase());
1391
- if (!entry) {
1392
- res.writeHead(404, { "Content-Type": "application/json" });
1393
- res.end(JSON.stringify({ status: "error", message: `Sibling network member '${prefix}' not found.` }));
1394
- return;
1395
- }
1396
- const originalUrl = req.url;
1397
- req.url = subPath;
1398
- try {
1399
- await entry.entity.unifiedHttpAdapter._handleRequest(req, res);
1400
- } finally {
1401
- req.url = originalUrl;
1402
- }
1403
- }
1404
- };
1405
- var KrnlIngressNetwork = KrnlSiblingNetwork;
1406
-
1407
- // src/core/K_LIB_Krnl_Frontend_Inspector.ts
1408
- import fs from "fs";
1409
- import path2 from "path";
1410
- var KrnlFrontendInspector = class {
1411
- static manifest(system, frontendDir) {
1412
- const appName = system.entityName || "KrnlTS App";
1413
- const commPort = system.commPort || 10099;
1414
- const frontendUrl = `http://127.0.0.1:${commPort}/frontend/`;
1415
- const cssFile = "frontend/index.css";
1416
- const bundleFile = "frontend/dist/bundle.js";
1417
- const bundleBuilt = fs.existsSync(path2.join(frontendDir, "dist", "bundle.js"));
1418
- const localFuncs = Array.from(system.localFunctionalities?.values() || []);
1419
- const remoteFuncs = Array.from(system.remoteFunctionalities?.values() || []);
1420
- const allFuncs = [...localFuncs, ...remoteFuncs];
1421
- const uiEndpoints = allFuncs.filter((fn) => fn.uiSpec?.ui_component_enabled || fn.ui_spec?.ui_component_enabled);
1422
- const subApps = system._subAppRegistry ? Array.from(system._subAppRegistry.keys()) : [];
1423
- const tabLayout = [];
1424
- uiEndpoints.forEach((ep) => {
1425
- tabLayout.push({
1426
- id: ep.id,
1427
- type: "endpoint",
1428
- icon: "\u2B21",
1429
- hasSharedSlots: (ep.uiSpec?.inputs || []).some((i) => i.sharedComponentId) || (ep.uiSpec?.outputs || []).some((o) => o.sharedComponentId)
1430
- });
1431
- });
1432
- subApps.forEach((sub) => {
1433
- tabLayout.push({
1434
- id: sub,
1435
- type: "subapp",
1436
- icon: "\u{1F4E6}"
1437
- });
1438
- });
1439
- return {
1440
- status: "ok",
1441
- data: {
1442
- appName,
1443
- frontendUrl,
1444
- theme: "glass-brutalism-dark",
1445
- cssFile,
1446
- bundleBuilt,
1447
- bundleFile,
1448
- generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1449
- totalEndpoints: uiEndpoints.length,
1450
- totalSubApps: subApps.length,
1451
- tabLayout
1452
- },
1453
- summary: `App '${appName}' has ${uiEndpoints.length} UI endpoints and ${subApps.length} sub-apps.`
1454
- };
1455
- }
1456
- static source(frontendDir) {
1457
- const htmlPath = path2.join(frontendDir, "index.html");
1458
- if (!fs.existsSync(htmlPath)) {
1459
- return { status: "error", message: "index.html not found" };
1460
- }
1461
- const html = fs.readFileSync(htmlPath, "utf-8");
1462
- const scriptTags = (html.match(/<script/g) || []).length;
1463
- const stylesheetLinks = (html.match(/rel=["']stylesheet["']/g) || []).length;
1464
- const hasReactRoot = html.includes('id="root"') || html.includes('id="app"');
1465
- return {
1466
- status: "ok",
1467
- data: {
1468
- html,
1469
- sizeBytes: Buffer.byteLength(html, "utf-8"),
1470
- scriptTags,
1471
- stylesheetLinks,
1472
- hasReactRoot
1473
- },
1474
- summary: `index.html is ${Buffer.byteLength(html, "utf-8")} bytes. ${scriptTags} script(s), ${stylesheetLinks} stylesheet(s).`
1475
- };
1476
- }
1477
- static domSnapshot(system, frontendDir) {
1478
- const manifest = this.manifest(system, frontendDir);
1479
- const tabs = manifest.data.tabLayout;
1480
- return {
1481
- status: "ok",
1482
- data: {
1483
- tag: "html",
1484
- attrs: { lang: "en", "data-theme": "glass-brutalism" },
1485
- children: [
1486
- {
1487
- tag: "body",
1488
- children: [
1489
- {
1490
- tag: "div",
1491
- class: "krnl-app-shell",
1492
- children: [
1493
- { tag: "header", class: "krnl-header", text: system.entityName },
1494
- {
1495
- tag: "nav",
1496
- class: "krnl-nav-tabs",
1497
- children: tabs.map((t) => ({
1498
- tag: "button",
1499
- class: "krnl-tab-btn",
1500
- title: t.id,
1501
- text: t.icon,
1502
- label: t.id
1503
- }))
1504
- },
1505
- { tag: "main", class: "krnl-main-body", text: "Active Endpoint/Subapp Container Panel" }
1506
- ]
1507
- }
1508
- ]
1509
- }
1510
- ]
1511
- },
1512
- summary: `DOM structure contains header '${system.entityName}', tab bar with ${tabs.length} tabs, and main content area.`
1513
- };
1514
- }
1515
- static a11yTree(system, frontendDir) {
1516
- const endpoints = this.endpoints(system).data;
1517
- const elements = this.elements(system, frontendDir).data;
1518
- const tree = [
1519
- { role: "banner", name: system.entityName, children: [] },
1520
- {
1521
- role: "navigation",
1522
- name: "Tab bar",
1523
- children: endpoints.map((ep) => ({
1524
- role: "tab",
1525
- name: ep.fid,
1526
- selected: true
1527
- }))
1528
- },
1529
- {
1530
- role: "main",
1531
- name: "Endpoint Panel",
1532
- children: endpoints.map((ep) => ({
1533
- role: "group",
1534
- name: ep.fid,
1535
- children: [
1536
- ...(ep.uiSpec?.inputs || []).map((inp) => ({
1537
- role: inp.component === "KrnlTextArea" ? "textbox" : inp.component === "KrnlDropdown" ? "combobox" : "textbox",
1538
- name: inp.field,
1539
- required: true
1540
- })),
1541
- {
1542
- role: "button",
1543
- name: "\u2B21",
1544
- label: `Run ${ep.fid}`
1545
- }
1546
- ]
1547
- }))
1548
- }
1549
- ];
1550
- return {
1551
- status: "ok",
1552
- data: {
1553
- ariaSnapshot: `- banner: heading '${system.entityName}'
1554
- - navigation:
1555
- ${endpoints.map((e) => ` - tab '${e.fid}'`).join("\n")}
1556
- - main:
1557
- ${endpoints.map((e) => ` - group '${e.fid}':
1558
- - button '\u2B21' [title='Run ${e.fid}']`).join("\n")}`,
1559
- tree
1560
- },
1561
- wcagViolations: [],
1562
- summary: `${elements.total} interactive elements mapped in accessibility tree. 0 WCAG violations.`
1563
- };
1564
- }
1565
- static components(system, frontendDir) {
1566
- const endpoints = this.endpoints(system).data;
1567
- const components = endpoints.map((ep) => {
1568
- const inputs = ep.uiSpec?.inputs || [];
1569
- const outputs = ep.uiSpec?.outputs || [];
1570
- const sharedSlots = [
1571
- ...inputs.filter((i) => i.sharedComponentId).map((i) => ({ type: "consumer", slotId: i.sharedComponentId, field: i.field })),
1572
- ...outputs.filter((o) => o.sharedComponentId).map((o) => ({ type: "provider", slotId: o.sharedComponentId, field: o.field }))
1573
- ];
1574
- return {
1575
- id: ep.fid,
1576
- file: `frontend/src/components/${ep.fid}/index.ts`,
1577
- inputs,
1578
- outputs,
1579
- sharedSlots,
1580
- hasPhantomMirroring: true,
1581
- sseUrl: ep.sseUrl,
1582
- apiUrl: ep.apiUrl
1583
- };
1584
- });
1585
- return {
1586
- status: "ok",
1587
- data: {
1588
- framework: "vanjs",
1589
- atoms: ["KrnlButton", "KrnlTextInput", "KrnlNumberInput", "KrnlDropdown", "KrnlToggle", "KrnlTextArea", "KrnlJsonInput", "KrnlJsonViewer", "KrnlCarousel", "KrnlTile", "KrnlSSELog"],
1590
- components
1591
- },
1592
- summary: `${components.length} generated VanJS components.`
1593
- };
1594
- }
1595
- static endpoints(system) {
1596
- const localFuncs = Array.from(system.localFunctionalities?.values() || []);
1597
- const remoteFuncs = Array.from(system.remoteFunctionalities?.values() || []);
1598
- const allFuncs = [...localFuncs, ...remoteFuncs];
1599
- const endpoints = allFuncs.filter((fn) => fn.uiSpec?.ui_component_enabled || fn.ui_spec?.ui_component_enabled).map((fn) => {
1600
- const uiSpec = fn.uiSpec || fn.ui_spec;
1601
- return {
1602
- fid: fn.id,
1603
- uiEnabled: true,
1604
- schema: fn.schema || {},
1605
- uiSpec,
1606
- apiUrl: `/frontend/api/${fn.id}`,
1607
- sseUrl: `/frontend/sse/${fn.id}`,
1608
- uiSpecValid: true,
1609
- uiSpecErrors: []
1610
- };
1611
- });
1612
- return {
1613
- status: "ok",
1614
- data: endpoints,
1615
- summary: `${endpoints.length} active endpoints registered with UI specifications.`
1616
- };
1617
- }
1618
- static elements(system, frontendDir) {
1619
- const endpoints = this.endpoints(system).data;
1620
- const buttons = [];
1621
- const inputs = [];
1622
- const selects = [];
1623
- const toggles = [];
1624
- const textareas = [];
1625
- endpoints.forEach((ep) => {
1626
- buttons.push({
1627
- id: `btn-${ep.fid}-submit`,
1628
- icon: "\u2B21",
1629
- hoverLabel: `Run ${ep.fid}`,
1630
- endpoint: ep.fid,
1631
- hasTitle: true,
1632
- disabled: false
1633
- });
1634
- (ep.uiSpec?.inputs || []).forEach((inp) => {
1635
- const item = {
1636
- id: `input-${ep.fid}-${inp.field}`,
1637
- type: inp.component,
1638
- label: inp.label || inp.field,
1639
- placeholder: inp.placeholder || inp.field,
1640
- required: true,
1641
- endpoint: ep.fid
1642
- };
1643
- if (inp.component === "KrnlDropdown") selects.push(item);
1644
- else if (inp.component === "KrnlToggle") toggles.push(item);
1645
- else if (inp.component === "KrnlTextArea") textareas.push(item);
1646
- else inputs.push(item);
1647
- });
1648
- });
1649
- const total = buttons.length + inputs.length + selects.length + toggles.length + textareas.length;
1650
- return {
1651
- status: "ok",
1652
- data: {
1653
- buttons,
1654
- inputs,
1655
- selects,
1656
- toggles,
1657
- textareas,
1658
- total
1659
- },
1660
- summary: `${total} interactive elements (${buttons.length} buttons, ${inputs.length + selects.length + toggles.length + textareas.length} fields).`
1661
- };
1662
- }
1663
- static forms(system) {
1664
- const endpoints = this.endpoints(system).data;
1665
- const forms = endpoints.map((ep) => ({
1666
- endpointId: ep.fid,
1667
- fields: (ep.uiSpec?.inputs || []).map((inp) => ({
1668
- name: inp.field,
1669
- type: inp.component,
1670
- component: inp.component,
1671
- required: true
1672
- })),
1673
- submitTarget: `/frontend/api/${ep.fid}`,
1674
- method: "POST",
1675
- hasSharedSlotInputs: (ep.uiSpec?.inputs || []).some((i) => i.sharedComponentId)
1676
- }));
1677
- return {
1678
- status: "ok",
1679
- data: forms,
1680
- summary: `${forms.length} forms registered.`
1681
- };
1682
- }
1683
- static sharedSlots(system) {
1684
- const endpoints = this.endpoints(system).data;
1685
- const slotsMap = /* @__PURE__ */ new Map();
1686
- endpoints.forEach((ep) => {
1687
- (ep.uiSpec?.outputs || []).forEach((out) => {
1688
- if (out.sharedComponentId) {
1689
- if (!slotsMap.has(out.sharedComponentId)) {
1690
- slotsMap.set(out.sharedComponentId, { providers: [], consumers: [] });
1691
- }
1692
- slotsMap.get(out.sharedComponentId).providers.push({
1693
- fid: ep.fid,
1694
- field: out.field,
1695
- component: out.component,
1696
- autoFetch: !!out.autoFetch
1697
- });
1698
- }
1699
- });
1700
- (ep.uiSpec?.inputs || []).forEach((inp) => {
1701
- if (inp.sharedComponentId) {
1702
- if (!slotsMap.has(inp.sharedComponentId)) {
1703
- slotsMap.set(inp.sharedComponentId, { providers: [], consumers: [] });
1704
- }
1705
- slotsMap.get(inp.sharedComponentId).consumers.push({
1706
- fid: ep.fid,
1707
- field: inp.field,
1708
- component: inp.component,
1709
- bindMode: inp.bindMode || "selected"
1710
- });
1711
- }
1712
- });
1713
- });
1714
- const slots = [];
1715
- slotsMap.forEach((val, slotId) => {
1716
- const valid = val.providers.length > 0 && val.consumers.length > 0;
1717
- const issues = [];
1718
- if (val.providers.length === 0) issues.push(`Slot '${slotId}' has consumers but no provider endpoint.`);
1719
- if (val.consumers.length === 0) issues.push(`Slot '${slotId}' has providers but no consumer endpoint.`);
1720
- slots.push({
1721
- slotId,
1722
- providers: val.providers,
1723
- consumers: val.consumers,
1724
- valid,
1725
- issues
1726
- });
1727
- });
1728
- return {
1729
- status: "ok",
1730
- data: slots,
1731
- summary: `${slots.length} shared slots configured.`
1732
- };
1733
- }
1734
- static consoleLog(capturedLogs) {
1735
- const logs = capturedLogs.filter((l) => l.level === "log");
1736
- const warns = capturedLogs.filter((l) => l.level === "warn");
1737
- const errors = capturedLogs.filter((l) => l.level === "error");
1738
- return {
1739
- status: "ok",
1740
- data: {
1741
- logs,
1742
- warns,
1743
- errors,
1744
- total: capturedLogs.length
1745
- },
1746
- summary: `${capturedLogs.length} console messages captured (${errors.length} errors, ${warns.length} warnings).`
1747
- };
1748
- }
1749
- static network(interactions) {
1750
- const totalRequests = interactions.length;
1751
- const totalErrors = interactions.filter((i) => i.responseStatus >= 400).length;
1752
- return {
1753
- status: "ok",
1754
- data: {
1755
- requests: interactions,
1756
- totalRequests,
1757
- totalErrors
1758
- },
1759
- summary: `${totalRequests} API calls recorded (${totalErrors} errors).`
1760
- };
1761
- }
1762
- static har(interactions, system) {
1763
- const entries = interactions.map((item, idx) => ({
1764
- pageref: "page_1",
1765
- startedDateTime: item.ts,
1766
- time: item.durationMs,
1767
- request: {
1768
- method: item.method,
1769
- url: item.url,
1770
- httpVersion: "HTTP/1.1",
1771
- headers: [{ name: "Content-Type", value: "application/json" }],
1772
- queryString: [],
1773
- cookies: [],
1774
- headersSize: -1,
1775
- bodySize: JSON.stringify(item.body || {}).length,
1776
- postData: {
1777
- mimeType: "application/json",
1778
- text: JSON.stringify(item.body || {})
1779
- }
1780
- },
1781
- response: {
1782
- status: item.responseStatus,
1783
- statusText: item.responseStatus === 200 ? "OK" : "Error",
1784
- httpVersion: "HTTP/1.1",
1785
- headers: [{ name: "Content-Type", value: "application/json" }],
1786
- cookies: [],
1787
- content: {
1788
- size: JSON.stringify(item.responseBody || {}).length,
1789
- mimeType: "application/json",
1790
- text: JSON.stringify(item.responseBody || {})
1791
- },
1792
- redirectURL: "",
1793
- headersSize: -1,
1794
- bodySize: JSON.stringify(item.responseBody || {}).length
1795
- },
1796
- cache: {},
1797
- timings: {
1798
- send: 0,
1799
- wait: item.durationMs,
1800
- receive: 0
1801
- }
1802
- }));
1803
- return {
1804
- log: {
1805
- version: "1.2",
1806
- creator: { name: "KrnlTS", version: "1.0.0" },
1807
- pages: [
1808
- {
1809
- id: "page_1",
1810
- startedDateTime: (/* @__PURE__ */ new Date()).toISOString(),
1811
- title: system.entityName || "KrnlTS App",
1812
- pageTimings: {}
1813
- }
1814
- ],
1815
- entries
1816
- }
1817
- };
1818
- }
1819
- static audit(system, frontendDir, capturedLogs) {
1820
- const passed = [];
1821
- const warnings = [];
1822
- const failures = [];
1823
- const sourceRes = this.source(frontendDir);
1824
- if (sourceRes.status === "ok" && sourceRes.data) {
1825
- if (sourceRes.data.html.includes("<html lang=")) passed.push({ rule: "html-has-lang", message: "<html lang> is set." });
1826
- else failures.push({ rule: "html-has-lang", message: "<html lang> is missing." });
1827
- if (sourceRes.data.html.includes("<title>")) passed.push({ rule: "document-title", message: "<title> is present." });
1828
- else failures.push({ rule: "document-title", message: "<title> is missing." });
1829
- }
1830
- const elementsRes = this.elements(system, frontendDir);
1831
- const unTitledBtns = elementsRes.data.buttons.filter((b) => !b.hasTitle);
1832
- if (unTitledBtns.length === 0) passed.push({ rule: "buttons-have-title", message: "All buttons have accessible title attributes." });
1833
- else failures.push({ rule: "buttons-have-title", message: `${unTitledBtns.length} buttons are missing title attributes.` });
1834
- const sharedSlotsRes = this.sharedSlots(system);
1835
- const invalidSlots = sharedSlotsRes.data.filter((s) => !s.valid);
1836
- if (invalidSlots.length === 0) passed.push({ rule: "shared-slots-integrity", message: "All shared slots are valid." });
1837
- else failures.push({ rule: "shared-slots-integrity", message: `${invalidSlots.length} shared slots have missing providers or consumers.` });
1838
- const consoleErrors = capturedLogs.filter((l) => l.level === "error");
1839
- if (consoleErrors.length === 0) passed.push({ rule: "no-console-errors", message: "0 console errors reported." });
1840
- else failures.push({ rule: "no-console-errors", message: `${consoleErrors.length} console errors reported.` });
1841
- const totalRules = passed.length + warnings.length + failures.length;
1842
- const score = Math.round(passed.length / Math.max(1, totalRules) * 100);
1843
- return {
1844
- status: "ok",
1845
- data: {
1846
- score,
1847
- categories: {
1848
- accessibility: { score: 95, title: "Accessibility" },
1849
- bestPractices: { score: 100, title: "Best Practices" },
1850
- uiSpec: { score: 100, title: "UI Spec Integrity" }
1851
- },
1852
- passed,
1853
- warnings,
1854
- failures,
1855
- auditRules: totalRules,
1856
- passingRules: passed.length,
1857
- failingRules: failures.length
1858
- },
1859
- summary: `Audit score ${score}/100. ${passed.length} passed, ${failures.length} failed.`
1860
- };
1861
- }
1862
- static telemetry(system, interactions) {
1863
- const fidMap = /* @__PURE__ */ new Map();
1864
- interactions.forEach((item) => {
1865
- const parts = item.url.split("/");
1866
- const fid = parts[parts.length - 1];
1867
- if (!fidMap.has(fid)) fidMap.set(fid, { count: 0, totalDuration: 0 });
1868
- const record = fidMap.get(fid);
1869
- record.count++;
1870
- record.totalDuration += item.durationMs;
1871
- });
1872
- const apiCallHistory = [];
1873
- fidMap.forEach((val, fid) => {
1874
- apiCallHistory.push({
1875
- fid,
1876
- callCount: val.count,
1877
- avgDurationMs: Math.round(val.totalDuration / val.count)
1878
- });
1879
- });
1880
- return {
1881
- status: "ok",
1882
- data: {
1883
- sseActiveStreams: [],
1884
- apiCallHistory,
1885
- phantomExecutions: [],
1886
- totalApiCalls: interactions.length
1887
- },
1888
- summary: `${interactions.length} API telemetry spans captured.`
1889
- };
1890
- }
1891
- static health(system, frontendDir, capturedLogs, interactions) {
1892
- const auditRes = this.audit(system, frontendDir, capturedLogs);
1893
- const healthy = auditRes.data.failures.length === 0;
1894
- return {
1895
- status: "ok",
1896
- data: {
1897
- healthy,
1898
- appName: system.entityName,
1899
- endpointsCount: this.endpoints(system).data.length,
1900
- uiComponentsCount: this.components(system, frontendDir).data.components.length,
1901
- sharedSlotsCount: this.sharedSlots(system).data.length,
1902
- consoleErrors: capturedLogs.filter((l) => l.level === "error").length,
1903
- auditScore: auditRes.data.score,
1904
- issues: auditRes.data.failures
1905
- },
1906
- summary: healthy ? `Frontend is healthy. Audit score ${auditRes.data.score}/100.` : `Frontend has ${auditRes.data.failures.length} health issue(s).`
1907
- };
1908
- }
1909
- };
1910
-
1911
- // src/core/K_LIB_Krnl_System_Frontend.ts
1912
- import fs2 from "fs";
1913
- import path3 from "path";
1914
- var KrnlFrontend = class {
1915
- system;
1916
- options;
1917
- frontendDir;
1918
- subAppFrontendDirs = /* @__PURE__ */ new Map();
1919
- interactionsHistory = [];
1920
- capturedLogs = [];
1921
- constructor(system, options = {}) {
1922
- this.system = system;
1923
- this.options = {
1924
- title: system.entityName,
1925
- theme: "dark",
1926
- enableMonitoringApi: true,
1927
- ...options
1928
- };
1929
- this.frontendDir = options.frontendDir || path3.join(system._entityDataDir, "frontend");
1930
- this._interceptConsole();
1931
- }
1932
- _interceptConsole() {
1933
- const origLog = console.log;
1934
- const origWarn = console.warn;
1935
- const origErr = console.error;
1936
- console.log = (...args) => {
1937
- this.capturedLogs.push({ level: "log", msg: args.map((a) => typeof a === "object" ? JSON.stringify(a) : String(a)).join(" "), ts: (/* @__PURE__ */ new Date()).toISOString() });
1938
- if (this.capturedLogs.length > 500) this.capturedLogs.shift();
1939
- origLog.apply(console, args);
1940
- };
1941
- console.warn = (...args) => {
1942
- this.capturedLogs.push({ level: "warn", msg: args.map((a) => typeof a === "object" ? JSON.stringify(a) : String(a)).join(" "), ts: (/* @__PURE__ */ new Date()).toISOString() });
1943
- if (this.capturedLogs.length > 500) this.capturedLogs.shift();
1944
- origWarn.apply(console, args);
1945
- };
1946
- console.error = (...args) => {
1947
- this.capturedLogs.push({ level: "error", msg: args.map((a) => typeof a === "object" ? JSON.stringify(a) : String(a)).join(" "), ts: (/* @__PURE__ */ new Date()).toISOString() });
1948
- if (this.capturedLogs.length > 500) this.capturedLogs.shift();
1949
- origErr.apply(console, args);
1950
- };
1951
- }
1952
- registerSubAppFrontend(prefix, subFrontendDir) {
1953
- this.subAppFrontendDirs.set(prefix.toLowerCase(), subFrontendDir);
1954
- console.log(`[KrnlFrontend] Registered sub-app frontend '${prefix}' -> ${subFrontendDir}`);
1955
- }
1956
- async handleRequest(req, res, subpath) {
1957
- const rawPath = subpath.split("?")[0];
1958
- const normalized = rawPath.startsWith("/") ? rawPath : "/" + rawPath;
1959
- const cleanPath = normalized.replace(/\/$/, "") || "/";
1960
- if (cleanPath.startsWith("/inspect")) {
1961
- const inspectPath = cleanPath.replace(/^\/inspect\/?/, "");
1962
- res.writeHead(200, { "Content-Type": "application/json" });
1963
- switch (inspectPath) {
1964
- case "manifest":
1965
- res.end(JSON.stringify(KrnlFrontendInspector.manifest(this.system, this.frontendDir)));
1966
- return;
1967
- case "source":
1968
- res.end(JSON.stringify(KrnlFrontendInspector.source(this.frontendDir)));
1969
- return;
1970
- case "dom":
1971
- res.end(JSON.stringify(KrnlFrontendInspector.domSnapshot(this.system, this.frontendDir)));
1972
- return;
1973
- case "a11y":
1974
- res.end(JSON.stringify(KrnlFrontendInspector.a11yTree(this.system, this.frontendDir)));
1975
- return;
1976
- case "components":
1977
- res.end(JSON.stringify(KrnlFrontendInspector.components(this.system, this.frontendDir)));
1978
- return;
1979
- case "endpoints":
1980
- res.end(JSON.stringify(KrnlFrontendInspector.endpoints(this.system)));
1981
- return;
1982
- case "elements":
1983
- res.end(JSON.stringify(KrnlFrontendInspector.elements(this.system, this.frontendDir)));
1984
- return;
1985
- case "forms":
1986
- res.end(JSON.stringify(KrnlFrontendInspector.forms(this.system)));
1987
- return;
1988
- case "shared-slots":
1989
- res.end(JSON.stringify(KrnlFrontendInspector.sharedSlots(this.system)));
1990
- return;
1991
- case "console":
1992
- res.end(JSON.stringify(KrnlFrontendInspector.consoleLog(this.capturedLogs)));
1993
- return;
1994
- case "network":
1995
- res.end(JSON.stringify(KrnlFrontendInspector.network(this.interactionsHistory)));
1996
- return;
1997
- case "har":
1998
- res.end(JSON.stringify(KrnlFrontendInspector.har(this.interactionsHistory, this.system)));
1999
- return;
2000
- case "audit":
2001
- res.end(JSON.stringify(KrnlFrontendInspector.audit(this.system, this.frontendDir, this.capturedLogs)));
2002
- return;
2003
- case "telemetry":
2004
- res.end(JSON.stringify(KrnlFrontendInspector.telemetry(this.system, this.interactionsHistory)));
2005
- return;
2006
- case "health":
2007
- case "":
2008
- res.end(JSON.stringify(KrnlFrontendInspector.health(this.system, this.frontendDir, this.capturedLogs, this.interactionsHistory)));
2009
- return;
2010
- default:
2011
- res.writeHead(404, { "Content-Type": "application/json" });
2012
- res.end(JSON.stringify({ status: "error", message: `Unknown inspect route '/inspect/${inspectPath}'` }));
2013
- return;
2014
- }
2015
- }
2016
- if ((normalized === "/" || normalized === "/index.html") && req.method === "GET") {
2017
- let htmlPath = path3.join(this.frontendDir, "index.html");
2018
- if (!fs2.existsSync(htmlPath)) {
2019
- try {
2020
- const { KrnlFrontendGenerator } = (init_K_LIB_Krnl_Frontend_Generator(), __toCommonJS(K_LIB_Krnl_Frontend_Generator_exports));
2021
- KrnlFrontendGenerator.ensureFrontendSkeleton(this.system, this.frontendDir);
2022
- } catch (_) {
2023
- }
2024
- }
2025
- if (fs2.existsSync(htmlPath)) {
2026
- res.writeHead(200, { "Content-Type": "text/html" });
2027
- res.end(fs2.readFileSync(htmlPath));
2028
- return;
2029
- }
2030
- }
2031
- if (normalized === "/bundle.js" && req.method === "GET") {
2032
- let bundlePath = path3.join(this.frontendDir, "dist", "bundle.js");
2033
- if (!fs2.existsSync(bundlePath)) {
2034
- try {
2035
- const { KrnlFrontendGenerator } = (init_K_LIB_Krnl_Frontend_Generator(), __toCommonJS(K_LIB_Krnl_Frontend_Generator_exports));
2036
- const { KrnlFrontendBuilder } = (init_K_LIB_Krnl_Frontend_Builder(), __toCommonJS(K_LIB_Krnl_Frontend_Builder_exports));
2037
- KrnlFrontendGenerator.generate(this.system, this.frontendDir);
2038
- KrnlFrontendBuilder.build(this.frontendDir);
2039
- } catch (e) {
2040
- console.error("[KrnlFrontend] On-demand bundle build error:", e);
2041
- }
2042
- }
2043
- if (fs2.existsSync(bundlePath)) {
2044
- res.writeHead(200, { "Content-Type": "application/javascript" });
2045
- res.end(fs2.readFileSync(bundlePath));
2046
- return;
2047
- }
2048
- res.writeHead(404, { "Content-Type": "application/javascript" });
2049
- res.end("/* bundle.js not found. Ensure frontend component generation & build completed. */");
2050
- return;
2051
- }
2052
- if ((normalized === "/styles.css" || normalized === "/index.css") && req.method === "GET") {
2053
- const cssPath = path3.join(this.frontendDir, "index.css");
2054
- if (fs2.existsSync(cssPath)) {
2055
- res.writeHead(200, { "Content-Type": "text/css" });
2056
- res.end(fs2.readFileSync(cssPath));
2057
- return;
2058
- }
2059
- const libCssCandidates = [
2060
- path3.resolve(process.cwd(), "dist/frontend/index.css"),
2061
- path3.resolve(process.cwd(), "src/krnl/frontend/index.css"),
2062
- path3.resolve(process.cwd(), "node_modules/krnlts/dist/frontend/index.css"),
2063
- path3.resolve(process.cwd(), "node_modules/krnlts/src/krnl/frontend/index.css")
2064
- ];
2065
- const fallbackCssPath = libCssCandidates.find((c) => fs2.existsSync(c));
2066
- if (fallbackCssPath) {
2067
- res.writeHead(200, { "Content-Type": "text/css" });
2068
- res.end(fs2.readFileSync(fallbackCssPath));
2069
- return;
2070
- }
2071
- res.writeHead(404, { "Content-Type": "text/css" });
2072
- res.end("/* styles.css / index.css not found */");
2073
- return;
2074
- }
2075
- if (normalized.startsWith("/subapps/")) {
2076
- const parts = normalized.split("/").filter(Boolean);
2077
- const prefix = parts[1]?.toLowerCase();
2078
- let subDir = prefix ? this.subAppFrontendDirs.get(prefix) : void 0;
2079
- if (!subDir && prefix) {
2080
- const candidate1 = path3.join(this.system._entityDataDir || ".", "subapps", prefix, "frontend");
2081
- const candidate2 = path3.join(process.cwd(), "subapps", prefix, "frontend");
2082
- if (fs2.existsSync(candidate1)) subDir = candidate1;
2083
- else if (fs2.existsSync(candidate2)) subDir = candidate2;
2084
- }
2085
- if (subDir && fs2.existsSync(subDir)) {
2086
- const fileRel = parts.slice(2).join("/");
2087
- if (fileRel === "styles.css") {
2088
- const cssPath = path3.join(this.frontendDir, "index.css");
2089
- if (fs2.existsSync(cssPath)) {
2090
- res.writeHead(200, { "Content-Type": "text/css" });
2091
- res.end(fs2.readFileSync(cssPath));
2092
- return;
2093
- }
2094
- }
2095
- if (!fileRel || fileRel === "index.html") {
2096
- const subHtml = path3.join(subDir, "index.html");
2097
- if (fs2.existsSync(subHtml)) {
2098
- res.writeHead(200, { "Content-Type": "text/html" });
2099
- res.end(fs2.readFileSync(subHtml));
2100
- return;
2101
- }
2102
- }
2103
- if (fileRel === "bundle.js") {
2104
- const subBundle = path3.join(subDir, "dist", "bundle.js");
2105
- if (fs2.existsSync(subBundle)) {
2106
- res.writeHead(200, { "Content-Type": "application/javascript" });
2107
- res.end(fs2.readFileSync(subBundle));
2108
- return;
2109
- }
2110
- }
2111
- const assetPath = path3.join(subDir, fileRel);
2112
- if (fs2.existsSync(assetPath) && fs2.statSync(assetPath).isFile()) {
2113
- res.writeHead(200);
2114
- res.end(fs2.readFileSync(assetPath));
2115
- return;
2116
- }
2117
- }
2118
- res.writeHead(404, { "Content-Type": "application/json" });
2119
- res.end(JSON.stringify({ status: "error", message: `Sub-app frontend asset '${normalized}' not found.` }));
2120
- return;
2121
- }
2122
- if (normalized.startsWith("/api/")) {
2123
- const parts = normalized.split("/");
2124
- const fid = parts[2];
2125
- if (!fid) {
2126
- res.writeHead(400, { "Content-Type": "application/json" });
2127
- res.end(JSON.stringify({ status: "error", message: "Missing functionality ID" }));
2128
- return;
2129
- }
2130
- const functionality = this.system.resolveLocalFunctionality ? this.system.resolveLocalFunctionality(fid) : this.system.localFunctionalities.get(fid);
2131
- if (!functionality) {
2132
- res.writeHead(404, { "Content-Type": "application/json" });
2133
- res.end(JSON.stringify({ status: "error", message: `Functionality ${fid} not found` }));
2134
- return;
2135
- }
2136
- let body = {};
2137
- if (req.method === "POST") {
2138
- body = await this._readJsonBody(req);
2139
- } else if (req.method === "GET") {
2140
- const url = new URL(req.url || "", `http://${req.headers.host || "localhost"}`);
2141
- body = Object.fromEntries(url.searchParams.entries());
2142
- }
2143
- const startTime = Date.now();
2144
- try {
2145
- const result = await this.system.call(fid, body, {
2146
- unwrap: false,
2147
- callerPort: req.socket?.remotePort,
2148
- accessKey: req.headers["x-krnl-access-key"]
2149
- });
2150
- this.interactionsHistory.push({
2151
- method: req.method || "POST",
2152
- url: req.url || `/frontend/api/${fid}`,
2153
- body,
2154
- responseStatus: 200,
2155
- responseBody: result,
2156
- durationMs: Date.now() - startTime,
2157
- ts: (/* @__PURE__ */ new Date()).toISOString(),
2158
- callerIp: req.socket?.remoteAddress
2159
- });
2160
- if (this.interactionsHistory.length > 200) this.interactionsHistory.shift();
2161
- res.writeHead(200, { "Content-Type": "application/json" });
2162
- res.end(JSON.stringify(result));
2163
- } catch (e) {
2164
- const errResp = {
2165
- status: "error",
2166
- message: e.message,
2167
- errorDocumentation: e.errorDocumentation || null
2168
- };
2169
- this.interactionsHistory.push({
2170
- method: req.method || "POST",
2171
- url: req.url || `/frontend/api/${fid}`,
2172
- body,
2173
- responseStatus: 500,
2174
- responseBody: errResp,
2175
- durationMs: Date.now() - startTime,
2176
- ts: (/* @__PURE__ */ new Date()).toISOString(),
2177
- callerIp: req.socket?.remoteAddress
2178
- });
2179
- if (this.interactionsHistory.length > 200) this.interactionsHistory.shift();
2180
- res.writeHead(200, { "Content-Type": "application/json" });
2181
- res.end(JSON.stringify(errResp));
2182
- }
2183
- return;
2184
- }
2185
- if (normalized.startsWith("/sse/")) {
2186
- const parts = normalized.split("/");
2187
- const fid = parts[2];
2188
- if (!fid) {
2189
- res.writeHead(400);
2190
- res.end("Missing functionality ID");
2191
- return;
2192
- }
2193
- const functionality = this.system.resolveLocalFunctionality ? this.system.resolveLocalFunctionality(fid) : this.system.localFunctionalities.get(fid);
2194
- if (!functionality) {
2195
- res.writeHead(404);
2196
- res.end("Functionality not found");
2197
- return;
2198
- }
2199
- res.writeHead(200, {
2200
- "Content-Type": "text/event-stream",
2201
- "Cache-Control": "no-cache",
2202
- "Connection": "keep-alive"
2203
- });
2204
- const stateEmitter = functionality.emitters?.get("state:changed");
2205
- const unsubscribe = stateEmitter?.subscribe((msg) => {
2206
- res.write(`data: ${JSON.stringify(msg.data || msg)}
2207
-
2208
- `);
2209
- });
2210
- const interval = setInterval(() => {
2211
- if (res.writable) {
2212
- res.write(": keepalive\n\n");
2213
- }
2214
- }, 15e3);
2215
- req.on("close", () => {
2216
- if (unsubscribe) unsubscribe();
2217
- clearInterval(interval);
2218
- res.end();
2219
- });
2220
- return;
2221
- }
2222
- res.writeHead(404, { "Content-Type": "application/json" });
2223
- res.end(JSON.stringify({ status: "error", message: `Frontend route '${subpath}' not found` }));
2224
- }
2225
- _readJsonBody(req) {
2226
- return new Promise((resolve, reject) => {
2227
- let body = "";
2228
- req.on("data", (chunk) => {
2229
- body += chunk.toString();
2230
- });
2231
- req.on("end", () => {
2232
- if (!body) return resolve({});
2233
- try {
2234
- resolve(JSON.parse(body));
2235
- } catch (e) {
2236
- reject(new Error("Invalid JSON body"));
2237
- }
2238
- });
2239
- });
2240
- }
2241
- };
2242
-
2243
- // src/core/K_LIB_Krnl_Boot_Barrier.ts
2244
- var KrnlBootBarrier = class {
2245
- _phase1Complete = false;
2246
- _resolve;
2247
- promise = new Promise((r) => this._resolve = r);
2248
- /**
2249
- * Signals that Phase 1 (developer boot / addLocal registration) has completed.
2250
- */
2251
- signalPhase1Complete() {
2252
- if (!this._phase1Complete) {
2253
- this._phase1Complete = true;
2254
- this._resolve();
2255
- }
2256
- }
2257
- /**
2258
- * Awaited by the magnetic loader before scanning and generating components.
2259
- */
2260
- waitForPhase1() {
2261
- return this.promise;
2262
- }
2263
- };
2264
-
2265
- // src/core/K_LIB_Krnl_Watch_Variables_Tracker.ts
2266
- var KrnlWatchVariablesTracker = class {
2267
- registeredFunctionalities = /* @__PURE__ */ new Map();
2268
- endpointConfigs = /* @__PURE__ */ new Map();
2269
- register(functionalityId, config, functionality) {
2270
- this.registeredFunctionalities.set(functionalityId, functionality);
2271
- this.endpointConfigs.set(functionalityId, config);
2272
- }
2273
- readLiveVars(endpointId) {
2274
- const config = this.endpointConfigs.get(endpointId);
2275
- const functionality = this.registeredFunctionalities.get(endpointId);
2276
- if (!config || !functionality) return {};
2277
- const liveVars = {};
2278
- const keysToRead = [
2279
- ...config.staticWatchVars || [],
2280
- ...config.dynamicWatchVars || []
2281
- ];
2282
- const state = functionality.state || {};
2283
- for (const key of keysToRead) {
2284
- if (key in state) {
2285
- liveVars[key] = state[key];
2286
- }
2287
- }
2288
- return liveVars;
2289
- }
2290
- sharedDynamicVars(endpointA, endpointB) {
2291
- const configA = this.endpointConfigs.get(endpointA);
2292
- const configB = this.endpointConfigs.get(endpointB);
2293
- if (!configA || !configB) return [];
2294
- const dynA = configA.dynamicWatchVars || [];
2295
- const dynB = configB.dynamicWatchVars || [];
2296
- return dynA.filter((v) => dynB.includes(v));
2297
- }
2298
- endpointsForVar(varKey) {
2299
- const matched = [];
2300
- for (const [fid, config] of this.endpointConfigs.entries()) {
2301
- if (config.dynamicWatchVars?.includes(varKey)) {
2302
- matched.push(fid);
2303
- }
2304
- }
2305
- return matched;
2306
- }
2307
- };
2308
-
2309
- // src/core/K_LIB_Krnl_Endpoint_Scheduler.ts
2310
- var KrnlEndpointScheduler = class {
2311
- tracker;
2312
- executing = /* @__PURE__ */ new Set();
2313
- queue = [];
2314
- constructor(tracker) {
2315
- this.tracker = tracker;
2316
- }
2317
- async dispatch(endpointId, task) {
2318
- return new Promise((resolve, reject) => {
2319
- this.queue.push({ endpointId, task, resolve, reject });
2320
- this.drainQueue();
2321
- });
2322
- }
2323
- hasConflict(endpointId) {
2324
- for (const activeEndpoint of this.executing) {
2325
- const shared = this.tracker.sharedDynamicVars(endpointId, activeEndpoint);
2326
- if (shared.length > 0) {
2327
- return true;
2328
- }
2329
- }
2330
- return false;
2331
- }
2332
- release(endpointId) {
2333
- this.executing.delete(endpointId);
2334
- this.drainQueue();
2335
- }
2336
- drainQueue() {
2337
- for (let i = 0; i < this.queue.length; i++) {
2338
- const item = this.queue[i];
2339
- if (!this.hasConflict(item.endpointId)) {
2340
- this.queue.splice(i, 1);
2341
- i--;
2342
- this.executing.add(item.endpointId);
2343
- item.task().then((res) => {
2344
- item.resolve(res);
2345
- this.release(item.endpointId);
2346
- }).catch((err) => {
2347
- item.reject(err);
2348
- this.release(item.endpointId);
2349
- });
2350
- }
2351
- }
2352
- }
2353
- };
2354
-
2355
- // src/core/K_LIB_Krnl_Task_Runner.ts
2356
- var KrnlTaskList = class _KrnlTaskList {
2357
- tasks = [];
2358
- cursor = 0;
2359
- constructor(tasks = [], cursor = 0) {
2360
- this.tasks = tasks;
2361
- this.cursor = cursor;
2362
- }
2363
- static create(items, parentTaskId, nestingDepth = 0) {
2364
- const tasks = items.map((item, idx) => ({
2365
- id: `task_${Date.now()}_${Math.random().toString(36).substring(2, 9)}_${idx}`,
2366
- endpointId: item.endpointId,
2367
- prompt: item.prompt,
2368
- status: "pending",
2369
- parentTaskId,
2370
- nestingDepth
2371
- }));
2372
- return new _KrnlTaskList(tasks);
2373
- }
2374
- getCurrentTask() {
2375
- if (this.cursor >= this.tasks.length) return null;
2376
- return this.tasks[this.cursor];
2377
- }
2378
- markDone(taskId, result) {
2379
- const task = this.tasks.find((t) => t.id === taskId);
2380
- if (task) {
2381
- task.status = "done";
2382
- task.result = result;
2383
- if (this.getCurrentTask()?.id === taskId) {
2384
- this.cursor++;
2385
- }
2386
- return true;
2387
- }
2388
- return false;
2389
- }
2390
- markSkipped(taskId) {
2391
- const task = this.tasks.find((t) => t.id === taskId);
2392
- if (task) {
2393
- task.status = "skipped";
2394
- if (this.getCurrentTask()?.id === taskId) {
2395
- this.cursor++;
2396
- }
2397
- return true;
2398
- }
2399
- return false;
2400
- }
2401
- nest(nestedItems, parentTaskId) {
2402
- const parentTask = this.tasks.find((t) => t.id === parentTaskId);
2403
- const depth = parentTask ? parentTask.nestingDepth + 1 : 1;
2404
- const nestedList = _KrnlTaskList.create(nestedItems, parentTaskId, depth);
2405
- const parentIdx = this.tasks.findIndex((t) => t.id === parentTaskId);
2406
- if (parentIdx !== -1) {
2407
- this.tasks.splice(parentIdx + 1, 0, ...nestedList.tasks);
2408
- } else {
2409
- this.tasks.push(...nestedList.tasks);
2410
- }
2411
- return this;
2412
- }
2413
- async persist(store) {
2414
- if (typeof store.saveTaskList === "function") {
2415
- await store.saveTaskList({
2416
- tasks: this.tasks,
2417
- cursor: this.cursor
2418
- });
2419
- }
2420
- }
2421
- static async load(store) {
2422
- if (typeof store.loadTaskList === "function") {
2423
- const data = await store.loadTaskList();
2424
- if (data) {
2425
- return new _KrnlTaskList(data.tasks, data.cursor);
2426
- }
2427
- }
2428
- return null;
2429
- }
2430
- };
2431
- var KrnlTaskRunner = class {
2432
- system;
2433
- currentList = null;
2434
- isExecuting = false;
2435
- constructor(system) {
2436
- this.system = system;
2437
- }
2438
- setTaskList(list) {
2439
- this.currentList = list;
2440
- }
2441
- getTaskList() {
2442
- return this.currentList;
2443
- }
2444
- async run(list) {
2445
- this.currentList = list;
2446
- await this.executeNext();
2447
- }
2448
- async onSuccess(taskId, result) {
2449
- if (!this.currentList) return;
2450
- this.currentList.markDone(taskId, result);
2451
- if (this.system._aiProfilesStore) {
2452
- await this.currentList.persist(this.system._aiProfilesStore);
2453
- }
2454
- setTimeout(() => {
2455
- this.executeNext().catch((err) => console.error("[TaskRunner] executeNext error:", err));
2456
- }, 0);
2457
- }
2458
- async receiveSkip(taskId) {
2459
- if (!this.currentList) return;
2460
- this.currentList.markSkipped(taskId);
2461
- if (this.system._aiProfilesStore) {
2462
- await this.currentList.persist(this.system._aiProfilesStore);
2463
- }
2464
- setTimeout(() => {
2465
- this.executeNext().catch((err) => console.error("[TaskRunner] executeNext error:", err));
2466
- }, 0);
2467
- }
2468
- async receiveNest(nestedItems, parentTaskId) {
2469
- if (!this.currentList) return;
2470
- this.currentList.nest(nestedItems, parentTaskId);
2471
- if (this.system._aiProfilesStore) {
2472
- await this.currentList.persist(this.system._aiProfilesStore);
2473
- }
2474
- setTimeout(() => {
2475
- this.executeNext().catch((err) => console.error("[TaskRunner] executeNext error:", err));
2476
- }, 0);
2477
- }
2478
- getStatus() {
2479
- if (!this.currentList) return { status: "idle", currentTask: null, tasks: [] };
2480
- const current = this.currentList.getCurrentTask();
2481
- return {
2482
- status: current ? "running" : "complete",
2483
- currentTask: current,
2484
- tasks: this.currentList.tasks,
2485
- cursor: this.currentList.cursor
2486
- };
2487
- }
2488
- async executeNext() {
2489
- if (!this.currentList) return;
2490
- const task = this.currentList.getCurrentTask();
2491
- if (!task) {
2492
- console.log("[TaskRunner] All tasks completed successfully.");
2493
- return;
2494
- }
2495
- task.status = "running";
2496
- if (this.system._aiProfilesStore) {
2497
- await this.currentList.persist(this.system._aiProfilesStore);
2498
- }
2499
- console.log(`[TaskRunner] Event trigger: Executing task ${task.id} (${task.endpointId}) with prompt: "${task.prompt}"`);
2500
- try {
2501
- const orchestrator = this.system._aiOrchestrator;
2502
- if (!orchestrator) {
2503
- throw new Error("Orchestrator not initialized");
2504
- }
2505
- const agent = orchestrator.endpointAgents.get(task.endpointId);
2506
- if (!agent) {
2507
- throw new Error(`Endpoint agent ${task.endpointId} not registered`);
2508
- }
2509
- const scheduler = this.system._aiScheduler || orchestrator.scheduler;
2510
- if (!scheduler) {
2511
- throw new Error("Scheduler not found on system or orchestrator");
2512
- }
2513
- const { result, trace } = await scheduler.dispatch(task.endpointId, async () => {
2514
- return await agent.executeFromNaturalLanguage(task.prompt);
2515
- });
2516
- if (this.system.telemetry && typeof this.system.telemetry.recordAiTrace === "function") {
2517
- this.system.telemetry.recordAiTrace(trace);
2518
- }
2519
- if (result && typeof result === "object" && result._krnlSignal === "QUERY_ORCHESTRATOR") {
2520
- console.log(`[TaskRunner] Detected signal QUERY_ORCHESTRATOR: ${result.query}`);
2521
- await orchestrator.handleQuery(result.query, { taskId: task.id, endpointId: task.endpointId });
2522
- return;
2523
- }
2524
- await this.onSuccess(task.id, result);
2525
- } catch (error) {
2526
- console.error(`[TaskRunner] Task ${task.id} failed:`, error.message || error);
2527
- const orchestrator = this.system._aiOrchestrator;
2528
- if (orchestrator) {
2529
- await orchestrator.escalateTaskFailure(task.id, error.message || String(error));
2530
- }
2531
- }
2532
- }
2533
- };
2534
- function createTaskListTool(runner) {
2535
- return {
2536
- id: "taskListTool",
2537
- description: "create_list(tasks) \u2192 ok | read_list() \u2192 list. use-when: plan/mutate task sequence.",
2538
- schema: {
2539
- input: {
2540
- action: "str: 'create' | 'append' | 'read'",
2541
- tasks: "array?: [{ endpointId: string, prompt: string }] (required for 'create'/'append')"
2542
- },
2543
- output: "obj"
2544
- },
2545
- examples: [
2546
- { input: { action: "create", tasks: [{ endpointId: "StoreKey", prompt: "store api key" }] }, output: { status: "ok", count: 1 } },
2547
- { input: { action: "read" }, output: { tasks: [] } }
2548
- ],
2549
- execute: async (payload) => {
2550
- if (payload.action === "create" && payload.tasks) {
2551
- const list = KrnlTaskList.create(payload.tasks);
2552
- runner.setTaskList(list);
2553
- return { status: "ok", count: payload.tasks.length };
2554
- } else if (payload.action === "append" && payload.tasks) {
2555
- const list = runner.getTaskList() || new KrnlTaskList();
2556
- const newList = KrnlTaskList.create(payload.tasks);
2557
- list.tasks.push(...newList.tasks);
2558
- runner.setTaskList(list);
2559
- return { status: "ok", count: list.tasks.length };
2560
- } else if (payload.action === "read") {
2561
- const list = runner.getTaskList();
2562
- return { tasks: list ? list.tasks : [] };
2563
- }
2564
- throw new Error(`Invalid action: ${payload.action}`);
2565
- }
2566
- };
2567
- }
2568
-
2569
- // src/core/K_LIB_Krnl_Ai_Concepts.ts
2570
- var KrnlPlannerSpec = {
2571
- reasoning: 9,
2572
- planning: 10,
2573
- toolUsage: 8,
2574
- structuredOutput: 9,
2575
- jsonStrictness: 8,
2576
- coding: 2,
2577
- extraction: 6,
2578
- classification: 5,
2579
- summarization: 5,
2580
- creativity: 3,
2581
- determinism: 7,
2582
- context: 8,
2583
- vision: 1,
2584
- multimodal: 1,
2585
- outputComplexity: 6
2586
- };
2587
-
2588
- // src/core/K_LIB_Krnl_Planner_Agent.ts
2589
- var KrnlPlannerAgent = class {
2590
- aikoClient;
2591
- system;
2592
- runner;
2593
- tool;
2594
- constructor(aikoClient, system, runner) {
2595
- this.aikoClient = aikoClient;
2596
- this.system = system;
2597
- this.runner = runner;
2598
- this.tool = createTaskListTool(runner);
2599
- }
2600
- async plan(naturalLanguageRequest, contextData = "") {
2601
- const endpoints = this.system._aiOrchestrator.getAgentSummaries().map((s) => {
2602
- return `- ${s.endpointId}: ${s.description}`;
2603
- }).join("\n");
2604
- const systemPrompt = `respond: caveman/pseudo-code/math only. no NL filler. use symbols for flow (\u2192,\u2229,\u2265,|). output=json unless signal.
2605
- You are a task planner agent. Your spec: reasoning=9, planning=10.
2606
- Goal: produce a sequential list of steps/tasks needed to fulfill the request.
2607
-
2608
- Available endpoints:
2609
- ${endpoints}
2610
-
2611
- Available tools:
2612
- - ${this.tool.id}: ${this.tool.description}
2613
- Schema: ${JSON.stringify(this.tool.schema)}
2614
- Examples: ${JSON.stringify(this.tool.examples)}
2615
-
2616
- Rules:
2617
- 1. Output ONLY tool calls or structured plans.
2618
- 2. If you need more information or context from the host entity/orchestrator before planning, emit:
2619
- {"_krnlSignal": "QUERY_ORCHESTRATOR", "query": "caveman query for info"}
2620
- 3. Otherwise, use taskListTool to create the task list. Call it via a JSON payload.
2621
-
2622
- Current Context:
2623
- ${contextData || "None"}
2624
- `;
2625
- const userPrompt = `Request: "${naturalLanguageRequest}"
2626
- Generate the plan or query context.`;
2627
- const response = await this.aikoClient.infer(KrnlPlannerSpec, systemPrompt, userPrompt);
2628
- let parsed = response.trim();
2629
- if (parsed.startsWith("```")) {
2630
- parsed = parsed.replace(/^```(json)?\n/, "").replace(/\n```$/, "").trim();
2631
- }
2632
- try {
2633
- const data = JSON.parse(parsed);
2634
- if (data && typeof data === "object" && data._krnlSignal === "QUERY_ORCHESTRATOR") {
2635
- return data;
2636
- }
2637
- if (data && data.action === "create" && data.tasks) {
2638
- await this.tool.execute(data);
2639
- const list = this.runner.getTaskList();
2640
- if (list) return list;
2641
- }
2642
- } catch (e) {
2643
- console.warn("[PlannerAgent] Failed to parse response as JSON tool call. Parsing list manually from string.");
2644
- }
2645
- try {
2646
- const data = JSON.parse(parsed);
2647
- if (Array.isArray(data)) {
2648
- await this.tool.execute({ action: "create", tasks: data });
2649
- const list = this.runner.getTaskList();
2650
- if (list) return list;
2651
- }
2652
- } catch (e) {
2653
- }
2654
- throw new Error(`Planner Agent failed to generate a valid plan. Raw output: ${response}`);
2655
- }
2656
- };
2657
-
2658
- // src/core/K_LIB_Krnl_Application_Orchestrator.ts
2659
- var KrnlApplicationOrchestrator = class {
2660
- system;
2661
- aikoClient;
2662
- tracker;
2663
- scheduler;
2664
- routingSpec;
2665
- escalationSpec;
2666
- endpointAgents = /* @__PURE__ */ new Map();
2667
- store;
2668
- taskRunner;
2669
- plannerAgent;
2670
- constructor(system, aikoClient, tracker, scheduler, routingSpec, escalationSpec, store) {
2671
- this.system = system;
2672
- this.aikoClient = aikoClient;
2673
- this.tracker = tracker;
2674
- this.scheduler = scheduler;
2675
- this.routingSpec = routingSpec;
2676
- this.escalationSpec = escalationSpec;
2677
- this.store = store;
2678
- this.taskRunner = new KrnlTaskRunner(system);
2679
- this.plannerAgent = new KrnlPlannerAgent(aikoClient, system, this.taskRunner);
2680
- }
2681
- registerAgent(endpointId, agent) {
2682
- this.endpointAgents.set(endpointId, agent);
2683
- }
2684
- getAgentSummaries() {
2685
- const list = [];
2686
- for (const [fid, agent] of this.endpointAgents.entries()) {
2687
- list.push({
2688
- endpointId: fid,
2689
- intelligenceSpec: agent.definition.intelligenceSpec,
2690
- description: agent.definition.description,
2691
- dynamicWatchVars: agent.definition.dynamicWatchVars,
2692
- staticWatchVars: agent.definition.staticWatchVars,
2693
- systemInstructions: agent.definition.systemInstructions
2694
- });
2695
- }
2696
- return list;
2697
- }
2698
- async handle(naturalLanguageRequest) {
2699
- const endpointId = await this.selectEndpoint(naturalLanguageRequest);
2700
- if (!endpointId) {
2701
- throw new Error(`Orchestrator failed to route request: "${naturalLanguageRequest}"`);
2702
- }
2703
- const agent = this.endpointAgents.get(endpointId);
2704
- if (!agent) {
2705
- throw new Error(`Orchestrator routed request to endpoint "${endpointId}", but no endpoint agent is registered.`);
2706
- }
2707
- try {
2708
- const { result, trace } = await this.scheduler.dispatch(endpointId, async () => {
2709
- return await agent.executeFromNaturalLanguage(naturalLanguageRequest);
2710
- });
2711
- if (this.system.telemetry && this.system.telemetry.recordAiTrace) {
2712
- this.system.telemetry.recordAiTrace(trace);
2713
- }
2714
- return {
2715
- status: "success",
2716
- result,
2717
- endpointId,
2718
- trace
2719
- };
2720
- } catch (escalationObj) {
2721
- if (escalationObj.trace && escalationObj.error) {
2722
- console.warn(`[Orchestrator] Endpoint agent "${endpointId}" failed execution. Initiating orchestrator escalation...`);
2723
- const badModelId = this.aikoClient.lastUsedModelId;
2724
- if (badModelId) {
2725
- console.log(`[Orchestrator] Model ${badModelId} failed to satisfy requirements. Submitting downrank report to Aiko...`);
2726
- await this.aikoClient.downrankModel(badModelId);
2727
- }
2728
- return await this.escalate(endpointId, naturalLanguageRequest, escalationObj.error.message, escalationObj.trace);
2729
- }
2730
- throw escalationObj;
2731
- }
2732
- }
2733
- async selectEndpoint(request) {
2734
- const orchMem = await this.store.getOrchestratorMemory();
2735
- const systemPrompt = this.buildRoutingPrompt(orchMem.memory);
2736
- const userPrompt = `User Request: "${request}"
2737
-
2738
- Which endpoint matches?`;
2739
- try {
2740
- const response = await this.aikoClient.infer(this.routingSpec, systemPrompt, userPrompt);
2741
- const selected = response.trim();
2742
- const logMsg = `Routed request "${request}" to "${selected}" at ${(/* @__PURE__ */ new Date()).toISOString()}`;
2743
- const updatedMem = orchMem.memory ? orchMem.memory + "\n" + logMsg : logMsg;
2744
- const memLines = updatedMem.split("\n").slice(-20).join("\n");
2745
- await this.store.setOrchestratorMemory(memLines);
2746
- if (this.endpointAgents.has(selected)) {
2747
- return selected;
2748
- }
2749
- for (const key of this.endpointAgents.keys()) {
2750
- if (selected.toLowerCase().includes(key.toLowerCase()) || key.toLowerCase().includes(selected.toLowerCase())) {
2751
- return key;
2752
- }
2753
- }
2754
- } catch (e) {
2755
- console.error("[Orchestrator] Aiko routing call failed:", e);
2756
- }
2757
- return null;
2758
- }
2759
- buildRoutingPrompt(orchestratorMemory) {
2760
- const summaries = this.getAgentSummaries().map((s) => {
2761
- return `- ${s.endpointId}: ${s.description}`;
2762
- }).join("\n");
2763
- return `You are a request router for an application. Your job is to analyze the user's natural language request and select the correct API endpoint name.
2764
-
2765
- Available endpoints:
2766
- ${summaries}
2767
-
2768
- Orchestrator Memory (recent routing history & learnings):
2769
- ${orchestratorMemory || "No routing decisions recorded yet."}
2770
-
2771
- Response Rules:
2772
- Reply with ONLY the exact endpoint name from the list above. Write nothing else. No punctuation, no wrapping.`;
2773
- }
2774
- async escalate(failedEndpointId, request, reason, failedTrace) {
2775
- console.log(`[Orchestrator Escalation] Escalating to escalationSpec model to bypass endpoint failure...`);
2776
- const agent = this.endpointAgents.get(failedEndpointId);
2777
- if (!agent) throw new Error("Agent not found for escalation");
2778
- const liveVars = this.tracker.readLiveVars(failedEndpointId);
2779
- const inferredTags = this._inferTagsFromError(reason);
2780
- const priorLearnings = await this.store.searchLearnings(failedEndpointId, inferredTags);
2781
- const learningsPrompt = priorLearnings.map(
2782
- (l) => `prior-learning: prob="${l.problemDescription}" tags=${l.tags.join(",")} sol="${l.solution}"`
2783
- ).join("\n");
2784
- const systemPrompt = `respond: caveman/pseudo-code/math only. no NL filler. use symbols for flow (\u2192,\u2229,\u2265,|). output=json unless signal.
2785
- You are the system orchestrator resolving a failure.
2786
- Endpoint: ${failedEndpointId}
2787
- Purpose: ${agent.definition.description}
2788
- Input Schema (JSON Schema):
2789
- ${JSON.stringify(agent.definition.inputSchema)}
2790
- Live state variables:
2791
- ${JSON.stringify(liveVars)}
2792
-
2793
- Prior learnings on failures:
2794
- ${learningsPrompt || "none"}
2795
-
2796
- The previous attempt failed with reason: "${reason}".
2797
- Your job is to override this, inspect the error, and generate a valid JSON payload matching the input schema.
2798
- Output ONLY raw JSON.`;
2799
- const userPrompt = `User Request: "${request}"
2800
-
2801
- Generate the corrected JSON payload.`;
2802
- try {
2803
- const startTime = Date.now();
2804
- const response = await this.aikoClient.infer(this.escalationSpec, systemPrompt, userPrompt);
2805
- let parsedPayload = response.trim();
2806
- if (parsedPayload.startsWith("```")) {
2807
- parsedPayload = parsedPayload.replace(/^```(json)?\n/, "").replace(/\n```$/, "");
2808
- }
2809
- const payload = JSON.parse(parsedPayload);
2810
- const result = await this.system.call(failedEndpointId, payload, { unwrap: false });
2811
- const learning = {
2812
- id: `learn_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
2813
- concernedEndpoint: failedEndpointId,
2814
- problemDescription: this._compressToLearningField(reason),
2815
- tags: inferredTags,
2816
- solution: this._compressToLearningField(`corrected payload: ${JSON.stringify(payload)}`),
2817
- createdAt: Date.now()
2818
- };
2819
- await this.store.appendLearning(learning);
2820
- const currentSpec = agent.definition.intelligenceSpec;
2821
- const upgradedSpec = { ...currentSpec };
2822
- if (upgradedSpec.reasoning < 10) upgradedSpec.reasoning += 1;
2823
- if (upgradedSpec.planning < 10) upgradedSpec.planning += 1;
2824
- if (upgradedSpec.jsonStrictness < 10) upgradedSpec.jsonStrictness += 1;
2825
- console.log(`[Orchestrator Self-Optimization] Upgrading endpoint "${failedEndpointId}" intelligence requirements to prevent regression.`);
2826
- const defOverride = await this.store.getEndpointDefinition(failedEndpointId) || {};
2827
- defOverride.intelligenceSpec = upgradedSpec;
2828
- await this.store.setEndpointDefinition(failedEndpointId, defOverride);
2829
- if (typeof this.system.initializeAiLayer === "function") {
2830
- await this.system.initializeAiLayer(this.system._entityDataDir);
2831
- }
2832
- const totalLatency = Date.now() - startTime;
2833
- const upgradedTrace = {
2834
- ...failedTrace,
2835
- traceId: `esc_${failedTrace.traceId}`,
2836
- retryCount: failedTrace.retryCount + 1,
2837
- payload,
2838
- executionResult: result,
2839
- latencyMs: totalLatency,
2840
- intelligenceSpec: upgradedSpec,
2841
- failureReason: void 0
2842
- };
2843
- if (this.system.telemetry && this.system.telemetry.recordAiTrace) {
2844
- this.system.telemetry.recordAiTrace(upgradedTrace);
2845
- }
2846
- return {
2847
- status: "success",
2848
- result,
2849
- endpointId: failedEndpointId,
2850
- trace: upgradedTrace
2851
- };
2852
- } catch (e) {
2853
- console.error("[Orchestrator Escalation] Escalation failed:", e.message);
2854
- throw e;
2855
- }
2856
- }
2857
- // Feature 1: Orchestration Entrypoints
2858
- async orchestrate(naturalLanguageRequest) {
2859
- console.log(`[Orchestrator] Planning autonomous task execution for: "${naturalLanguageRequest}"`);
2860
- const taskList = await this.plannerAgent.plan(naturalLanguageRequest);
2861
- if (this.store) {
2862
- await taskList.persist(this.store);
2863
- }
2864
- await this.taskRunner.run(taskList);
2865
- }
2866
- async handleQuery(query, context) {
2867
- console.log(`[Orchestrator] Endpoint agent requested data query: "${query}"`);
2868
- const nestedList = await this.plannerAgent.plan(query, `Context: Parent task ${context.taskId} (${context.endpointId})`);
2869
- await this.taskRunner.receiveNest(nestedList.tasks.map((t) => ({ endpointId: t.endpointId, prompt: t.prompt })), context.taskId);
2870
- }
2871
- _inferTagsFromError(reason) {
2872
- const clean = reason.toLowerCase();
2873
- const tags = [];
2874
- if (clean.includes("validation") || clean.includes("zod")) tags.push("validation");
2875
- if (clean.includes("json") || clean.includes("parse")) tags.push("json-parse");
2876
- if (clean.includes("missing") || clean.includes("required")) tags.push("missing-field");
2877
- if (clean.includes("type")) tags.push("type-mismatch");
2878
- if (clean.includes("network") || clean.includes("fetch") || clean.includes("http")) tags.push("network");
2879
- return tags;
2880
- }
2881
- _compressToLearningField(text) {
2882
- return text.toLowerCase().replace(/\b(the|a|an|and|or|but|is|are|was|were|be|been|being|to|from|by|for|with|about|against|between|into|through|during|before|after|above|below|to|of|at|by|under|over|again|further|then|once|here|there|when|where|why|how|all|any|both|each|few|more|most|other|some|such|no|nor|not|only|own|same|so|than|too|very|s|t|can|will|just|don|should|now)\b/g, "").replace(/\s+/g, " ").trim();
2883
- }
2884
- async escalateTaskFailure(taskId, errorReason) {
2885
- const list = this.taskRunner.getTaskList();
2886
- if (!list) return;
2887
- const task = list.tasks.find((t) => t.id === taskId);
2888
- if (!task) return;
2889
- console.warn(`[Orchestrator] Task ${taskId} failed. Attempting automated resolution...`);
2890
- const agent = this.endpointAgents.get(task.endpointId);
2891
- if (!agent) {
2892
- this.escalateToHuman(taskId, `Agent not found for ${task.endpointId}`);
2893
- return;
2894
- }
2895
- const inferredTags = this._inferTagsFromError(errorReason);
2896
- const priorLearnings = await this.store.searchLearnings(task.endpointId, inferredTags);
2897
- const liveVars = this.tracker.readLiveVars(task.endpointId);
2898
- const learningsPrompt = priorLearnings.map(
2899
- (l) => `prior-learning: prob="${l.problemDescription}" tags=${l.tags.join(",")} sol="${l.solution}"`
2900
- ).join("\n");
2901
- const systemPrompt = `respond: caveman/pseudo-code/math only. no NL filler. use symbols for flow (\u2192,\u2229,\u2265,|). output=json unless signal.
2902
- You are the system orchestrator resolving a failure.
2903
- Endpoint: ${task.endpointId}
2904
- Purpose: ${agent.definition.description}
2905
- Input Schema (JSON Schema):
2906
- ${JSON.stringify(agent.definition.inputSchema)}
2907
- Live state variables:
2908
- ${JSON.stringify(liveVars)}
2909
-
2910
- Prior learnings on failures:
2911
- ${learningsPrompt || "none"}
2912
-
2913
- The previous attempt failed with reason: "${errorReason}".
2914
- Your job is to override this, inspect the error, and generate a valid JSON payload matching the input schema.
2915
- Output ONLY raw JSON.`;
2916
- const userPrompt = `Task Prompt: "${task.prompt}"
2917
-
2918
- Generate corrected JSON payload.`;
2919
- try {
2920
- const response = await this.aikoClient.infer(this.escalationSpec, systemPrompt, userPrompt);
2921
- let parsedPayload = response.trim();
2922
- if (parsedPayload.startsWith("```")) {
2923
- parsedPayload = parsedPayload.replace(/^```(json)?\n/, "").replace(/\n```$/, "");
2924
- }
2925
- const payload = JSON.parse(parsedPayload);
2926
- const result = await this.system.call(task.endpointId, payload, { unwrap: false });
2927
- const learning = {
2928
- id: `learn_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
2929
- concernedEndpoint: task.endpointId,
2930
- problemDescription: this._compressToLearningField(errorReason),
2931
- tags: inferredTags,
2932
- solution: this._compressToLearningField(`corrected payload: ${JSON.stringify(payload)}`),
2933
- createdAt: Date.now()
2934
- };
2935
- await this.store.appendLearning(learning);
2936
- const currentSpec = agent.definition.intelligenceSpec;
2937
- const upgradedSpec = { ...currentSpec };
2938
- if (upgradedSpec.reasoning < 10) upgradedSpec.reasoning += 1;
2939
- if (upgradedSpec.planning < 10) upgradedSpec.planning += 1;
2940
- if (upgradedSpec.jsonStrictness < 10) upgradedSpec.jsonStrictness += 1;
2941
- const defOverride = await this.store.getEndpointDefinition(task.endpointId) || {};
2942
- defOverride.intelligenceSpec = upgradedSpec;
2943
- await this.store.setEndpointDefinition(task.endpointId, defOverride);
2944
- if (typeof this.system.initializeAiLayer === "function") {
2945
- await this.system.initializeAiLayer(this.system._entityDataDir);
2946
- }
2947
- console.log(`[Orchestrator] Automated resolution succeeded for task ${taskId}.`);
2948
- await this.taskRunner.onSuccess(taskId, result);
2949
- } catch (e) {
2950
- console.error(`[Orchestrator] Automated resolution failed: ${e.message}. Escalating to human...`);
2951
- await this.escalateToHuman(taskId, errorReason);
2952
- }
2953
- }
2954
- async escalateToHuman(taskId, errorReason) {
2955
- console.warn(`[HUMAN_ESCALATION] Task ${taskId} cannot be resolved automatically. Reason: ${errorReason}`);
2956
- this.system.interface.getEmitter("system-events")?.pushDataStreamToEmitter({
2957
- type: "needs-human",
2958
- taskId,
2959
- error: errorReason
2960
- });
2961
- }
2962
- async handleHumanResolution(taskId, resolution) {
2963
- console.log(`[Orchestrator] Human resolution received for task ${taskId}: ${resolution.action}`);
2964
- if (resolution.action === "skip") {
2965
- await this.taskRunner.receiveSkip(taskId);
2966
- } else if (resolution.action === "nest" && resolution.tasks) {
2967
- await this.taskRunner.receiveNest(resolution.tasks, taskId);
2968
- } else {
2969
- const list = this.taskRunner.getTaskList();
2970
- if (list) {
2971
- await this.taskRunner.run(list);
2972
- }
2973
- }
2974
- }
2975
- };
2976
-
2977
- // src/core/K_LIB_Krnl_Runtime_Store.ts
2978
- import fs3 from "fs";
2979
- import path4 from "path";
2980
- var KrnlRuntimeStore = class {
2981
- filePath;
2982
- data = {
2983
- endpointDefinitions: {},
2984
- endpointMemories: {},
2985
- orchestratorMemory: { memory: "", lastUpdated: 0 },
2986
- telemetryLog: [],
2987
- learnings: [],
2988
- activeTasks: null
2989
- };
2990
- constructor(appRoot) {
2991
- this.filePath = path4.join(appRoot, "krnl_runtime_state.db");
2992
- }
2993
- async load() {
2994
- try {
2995
- if (fs3.existsSync(this.filePath)) {
2996
- const raw = fs3.readFileSync(this.filePath, "utf-8");
2997
- this.data = JSON.parse(raw);
2998
- if (!this.data.endpointDefinitions) this.data.endpointDefinitions = {};
2999
- if (!this.data.endpointMemories) this.data.endpointMemories = {};
3000
- if (!this.data.orchestratorMemory) this.data.orchestratorMemory = { memory: "", lastUpdated: 0 };
3001
- if (!this.data.telemetryLog) this.data.telemetryLog = [];
3002
- if (!this.data.learnings) this.data.learnings = [];
3003
- if (this.data.activeTasks === void 0) this.data.activeTasks = null;
3004
- } else {
3005
- await this.save();
3006
- }
3007
- } catch (e) {
3008
- console.error("[KrnlRuntimeStore] Failed to load store, initializing empty:", e);
3009
- this.data = {
3010
- endpointDefinitions: {},
3011
- endpointMemories: {},
3012
- orchestratorMemory: { memory: "", lastUpdated: 0 },
3013
- telemetryLog: [],
3014
- learnings: [],
3015
- activeTasks: null
3016
- };
3017
- }
3018
- }
3019
- async getEndpointDefinition(endpointId) {
3020
- return this.data.endpointDefinitions[endpointId] || null;
3021
- }
3022
- async setEndpointDefinition(endpointId, config) {
3023
- this.data.endpointDefinitions[endpointId] = config;
3024
- await this.save();
3025
- }
3026
- async getAllEndpointDefinitions() {
3027
- return this.data.endpointDefinitions;
3028
- }
3029
- async getEndpointMemory(endpointId) {
3030
- return this.data.endpointMemories[endpointId] || "";
3031
- }
3032
- async appendEndpointMemory(endpointId, learning) {
3033
- const existing = this.data.endpointMemories[endpointId] || "";
3034
- const prefix = existing ? existing + "\n" : "";
3035
- this.data.endpointMemories[endpointId] = prefix + `[${(/* @__PURE__ */ new Date()).toISOString()}] ${learning}`;
3036
- await this.save();
3037
- }
3038
- async getOrchestratorMemory() {
3039
- return this.data.orchestratorMemory;
3040
- }
3041
- async setOrchestratorMemory(memory) {
3042
- this.data.orchestratorMemory = {
3043
- memory,
3044
- lastUpdated: Date.now()
3045
- };
3046
- await this.save();
3047
- }
3048
- async appendTelemetry(record) {
3049
- this.data.telemetryLog.push(record);
3050
- if (this.data.telemetryLog.length > 1e3) {
3051
- this.data.telemetryLog.shift();
3052
- }
3053
- await this.save();
3054
- }
3055
- async getTelemetryLog(limit) {
3056
- if (limit && limit > 0) {
3057
- return this.data.telemetryLog.slice(-limit);
3058
- }
3059
- return this.data.telemetryLog;
3060
- }
3061
- async appendLearning(learning) {
3062
- if (!this.data.learnings) this.data.learnings = [];
3063
- this.data.learnings.push(learning);
3064
- await this.appendEndpointMemory(
3065
- learning.concernedEndpoint,
3066
- `Problem: ${learning.problemDescription} | Solution: ${learning.solution}`
3067
- );
3068
- await this.save();
3069
- }
3070
- async searchLearnings(endpointId, tags) {
3071
- const pool = (this.data.learnings || []).filter((l) => l.concernedEndpoint === endpointId);
3072
- if (tags.length === 0) return pool;
3073
- const matched = pool.filter((l) => {
3074
- const intersect = l.tags.filter((t) => tags.includes(t));
3075
- return intersect.length > 0;
3076
- }).sort((a, b) => {
3077
- const intersectA = a.tags.filter((t) => tags.includes(t)).length;
3078
- const intersectB = b.tags.filter((t) => tags.includes(t)).length;
3079
- return intersectB - intersectA;
3080
- });
3081
- return matched.length > 0 ? matched : pool;
3082
- }
3083
- async saveTaskList(listData) {
3084
- this.data.activeTasks = listData;
3085
- await this.save();
3086
- }
3087
- async loadTaskList() {
3088
- return this.data.activeTasks || null;
3089
- }
3090
- async save() {
3091
- try {
3092
- fs3.writeFileSync(this.filePath, JSON.stringify(this.data, null, 2), "utf-8");
3093
- } catch (e) {
3094
- console.error("[KrnlRuntimeStore] Failed to save store:", e);
3095
- }
3096
- }
3097
- };
3098
-
3099
- // src/core/K_LIB_Krnl_Endpoint_Agent.ts
3100
- var KrnlEndpointAgent = class {
3101
- definition;
3102
- aikoClient;
3103
- tracker;
3104
- system;
3105
- tools;
3106
- constructor(definition, aikoClient, tracker, system, tools = {}) {
3107
- this.definition = definition;
3108
- this.aikoClient = aikoClient;
3109
- this.tracker = tracker;
3110
- this.system = system;
3111
- this.tools = tools;
3112
- }
3113
- async executeFromNaturalLanguage(naturalLanguageRequest) {
3114
- const traceId = `trace_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
3115
- const timestamp = Date.now();
3116
- const liveVars = this.tracker.readLiveVars(this.definition.id);
3117
- const startTime = Date.now();
3118
- let aiStartTime = Date.now();
3119
- let aiEndTime = Date.now();
3120
- try {
3121
- const { payload, retryCount, failures, aiTimeMs } = await this.repairLoop(
3122
- naturalLanguageRequest,
3123
- liveVars
3124
- );
3125
- aiEndTime = Date.now();
3126
- const executionStart = Date.now();
3127
- const result = await this.system.call(this.definition.id, payload, {
3128
- unwrap: false
3129
- });
3130
- const totalLatency = Date.now() - startTime;
3131
- const trace = {
3132
- traceId,
3133
- timestamp,
3134
- appName: this.system.entityName,
3135
- endpointId: this.definition.id,
3136
- intelligenceSpec: this.definition.intelligenceSpec,
3137
- promptHash: this.getPromptHash(this.buildSystemPrompt(liveVars), naturalLanguageRequest),
3138
- retryCount,
3139
- validationFailures: failures,
3140
- payload,
3141
- executionResult: result,
3142
- latencyMs: totalLatency,
3143
- aiLatencyMs: aiTimeMs
3144
- };
3145
- return { result, trace };
3146
- } catch (error) {
3147
- const totalLatency = Date.now() - startTime;
3148
- const trace = {
3149
- traceId,
3150
- timestamp,
3151
- appName: this.system.entityName,
3152
- endpointId: this.definition.id,
3153
- intelligenceSpec: this.definition.intelligenceSpec,
3154
- promptHash: this.getPromptHash(this.buildSystemPrompt(liveVars), naturalLanguageRequest),
3155
- retryCount: this.definition.retryConfig?.maxRetries || 4,
3156
- validationFailures: [error.message],
3157
- payload: null,
3158
- executionResult: null,
3159
- latencyMs: totalLatency,
3160
- aiLatencyMs: aiEndTime - aiStartTime,
3161
- failureReason: error.message
3162
- };
3163
- throw { error, trace };
3164
- }
3165
- }
3166
- buildSystemPrompt(liveVars) {
3167
- const toolsDesc = Object.entries(this.tools).map(([name, tool]) => {
3168
- const schemaStr = tool.schema ? `
3169
- Schema: ${JSON.stringify(tool.schema)}` : "";
3170
- const examplesStr = tool.examples ? `
3171
- Examples: ${JSON.stringify(tool.examples)}` : "";
3172
- return `- ${name}: ${tool.description || "Agent helper tool"}${schemaStr}${examplesStr}`;
3173
- }).join("\n");
3174
- return `respond: caveman/pseudo-code/math only. no NL filler. use symbols for flow (\u2192,\u2229,\u2265,|). output=json unless signal.
3175
- You are an endpoint agent representing the raw endpoint "${this.definition.id}".
3176
- Purpose: ${this.definition.description}
3177
- Instructions: ${this.definition.systemInstructions}
3178
- Intelligence Capability Spec: ${JSON.stringify(this.definition.intelligenceSpec)}
3179
-
3180
- Input Schema (JSON Schema format):
3181
- ${JSON.stringify(this.definition.inputSchema, null, 2)}
3182
-
3183
- Examples:
3184
- ${JSON.stringify(this.definition.examples, null, 2)}
3185
-
3186
- Current live state variables:
3187
- ${JSON.stringify(liveVars, null, 2)}
3188
-
3189
- Endpoint Memory (learned experiences from prior executions):
3190
- ${this.definition.memory || "No prior memories recorded yet."}
3191
-
3192
- Available Tools (you can call these internally if needed):
3193
- ${toolsDesc}
3194
-
3195
- Your primary job is to extract, convert, or infer parameters from user requests to produce a valid JSON payload matching the input schema.
3196
- Output ONLY raw, pure JSON. Do not write explanations, markdown blocks, formatting or wrapping.`;
3197
- }
3198
- parsePayload(aiResponse) {
3199
- let cleaned = aiResponse.trim();
3200
- if (cleaned.startsWith("```")) {
3201
- cleaned = cleaned.replace(/^```(json)?\n/, "").replace(/\n```$/, "");
3202
- }
3203
- cleaned = cleaned.trim();
3204
- try {
3205
- return JSON.parse(cleaned);
3206
- } catch (err) {
3207
- const match = cleaned.match(/\{[\s\S]*\}|\[[\s\S]*\]/);
3208
- if (match) {
3209
- try {
3210
- return JSON.parse(match[0].trim());
3211
- } catch (e) {
3212
- }
3213
- }
3214
- throw err;
3215
- }
3216
- }
3217
- validatePayload(payload) {
3218
- const functionality = this.system.localFunctionalities.get(this.definition.id);
3219
- if (!functionality || !functionality.schema || !functionality.schema.input) {
3220
- return { valid: true };
3221
- }
3222
- try {
3223
- const schemaInput = functionality.schema.input;
3224
- if (typeof schemaInput.verify === "function") {
3225
- const verifyError = schemaInput.verify(payload);
3226
- if (verifyError) {
3227
- throw new Error(`Protobuf verification failed: ${verifyError}`);
3228
- }
3229
- } else if (typeof schemaInput.parse === "function") {
3230
- schemaInput.parse(payload);
3231
- } else if (typeof schemaInput === "function") {
3232
- if (!schemaInput(payload)) throw new Error("Input validation check returned false.");
3233
- }
3234
- return { valid: true };
3235
- } catch (e) {
3236
- return { valid: false, error: e.message };
3237
- }
3238
- }
3239
- async repairLoop(request, liveVars) {
3240
- const maxRetries = this.definition.retryConfig?.maxRetries || 4;
3241
- const failures = [];
3242
- let systemPrompt = this.buildSystemPrompt(liveVars);
3243
- let userPrompt = request;
3244
- let aiTimeAccumulator = 0;
3245
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
3246
- const aiCallStart = Date.now();
3247
- let aiResponse = "";
3248
- try {
3249
- aiResponse = await this.aikoClient.infer(this.definition.intelligenceSpec, systemPrompt, userPrompt);
3250
- } catch (err) {
3251
- aiTimeAccumulator += Date.now() - aiCallStart;
3252
- failures.push(`Aiko connection failure: ${err.message}`);
3253
- if (attempt === maxRetries) {
3254
- throw new Error(`Endpoint agent execution failed after connection errors. Last: ${err.message}`);
3255
- }
3256
- continue;
3257
- }
3258
- aiTimeAccumulator += Date.now() - aiCallStart;
3259
- try {
3260
- const payload = this.parsePayload(aiResponse);
3261
- const valResult = this.validatePayload(payload);
3262
- if (valResult.valid) {
3263
- return { payload, retryCount: attempt, failures, aiTimeMs: aiTimeAccumulator };
3264
- } else {
3265
- failures.push(`Validation attempt ${attempt} failed: ${valResult.error}`);
3266
- userPrompt = `${request}
3267
-
3268
- Validation error from previous output:
3269
- ${valResult.error}
3270
-
3271
- Please generate a corrected payload.`;
3272
- }
3273
- } catch (e) {
3274
- failures.push(`JSON Parse attempt ${attempt} failed: ${e.message}`);
3275
- userPrompt = `${request}
3276
-
3277
- Invalid JSON from previous output:
3278
- ${e.message}
3279
-
3280
- Please output clean, valid JSON matching the schema.`;
3281
- }
3282
- if (attempt === maxRetries) {
3283
- throw new Error(`Endpoint agent validation failed after ${maxRetries} retries: ${failures.join(" | ")}`);
3284
- }
3285
- }
3286
- throw new Error("Validation retries exhausted");
3287
- }
3288
- getPromptHash(system, user) {
3289
- let hash = 0;
3290
- const combined = system + user;
3291
- for (let i = 0; i < combined.length; i++) {
3292
- const char = combined.charCodeAt(i);
3293
- hash = (hash << 5) - hash + char;
3294
- hash = hash & hash;
3295
- }
3296
- return `hash_${Math.abs(hash)}`;
3297
- }
3298
- };
3299
-
3300
- // src/core/K_LIB_Krnl_Job_Scheduler.ts
3301
- var KrnlJobScheduler = class {
3302
- tickets = /* @__PURE__ */ new Map();
3303
- ttlMs = 6e4;
3304
- // 60 seconds TTL for ticket cleanup
3305
- constructor() {
3306
- setInterval(() => this.cleanupExpiredTickets(), 3e4);
3307
- }
3308
- /**
3309
- * Create a new execution ticket
3310
- */
3311
- createTicket(fid, type) {
3312
- const id = `job_${type}_${fid}_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`;
3313
- let resolveFn;
3314
- let rejectFn;
3315
- const promise = new Promise((resolve, reject) => {
3316
- resolveFn = resolve;
3317
- rejectFn = reject;
3318
- });
3319
- const ticket = {
3320
- id,
3321
- fid,
3322
- type,
3323
- status: "pending",
3324
- startedAt: Date.now(),
3325
- promise,
3326
- resolve: resolveFn,
3327
- reject: rejectFn
3328
- };
3329
- this.tickets.set(id, ticket);
3330
- return ticket;
3331
- }
3332
- getTicket(id) {
3333
- return this.tickets.get(id) || null;
3334
- }
3335
- markRunning(id) {
3336
- const ticket = this.tickets.get(id);
3337
- if (ticket && ticket.status === "pending") {
3338
- ticket.status = "running";
3339
- }
3340
- }
3341
- markDone(id, result) {
3342
- const ticket = this.tickets.get(id);
3343
- if (ticket && (ticket.status === "pending" || ticket.status === "running")) {
3344
- ticket.status = "done";
3345
- ticket.completedAt = Date.now();
3346
- ticket.result = result;
3347
- ticket.resolve(ticket);
3348
- }
3349
- }
3350
- markError(id, error) {
3351
- const ticket = this.tickets.get(id);
3352
- if (ticket && (ticket.status === "pending" || ticket.status === "running")) {
3353
- ticket.status = "error";
3354
- ticket.completedAt = Date.now();
3355
- ticket.error = error;
3356
- ticket.resolve(ticket);
3357
- }
3358
- }
3359
- resolveTicket(id, status, result, error) {
3360
- if (status === "done") {
3361
- this.markDone(id, result);
3362
- } else {
3363
- this.markError(id, error || "Job failed");
3364
- }
3365
- }
3366
- async waitForTicket(id, timeoutMs = 1e4) {
3367
- const ticket = this.tickets.get(id);
3368
- if (!ticket) {
3369
- throw new Error(`[KrnlJobScheduler] Ticket '${id}' not found.`);
3370
- }
3371
- if (ticket.status === "done" || ticket.status === "error") {
3372
- return ticket;
3373
- }
3374
- let timeoutHandle;
3375
- const timeoutPromise = new Promise((_, reject) => {
3376
- timeoutHandle = setTimeout(() => {
3377
- this.markError(id, `Timeout waiting for job ticket '${id}' after ${timeoutMs}ms`);
3378
- reject(new Error(`[KrnlJobScheduler] Timeout waiting for job ticket '${id}' after ${timeoutMs}ms`));
3379
- }, timeoutMs);
3380
- });
3381
- try {
3382
- const res = await Promise.race([ticket.promise, timeoutPromise]);
3383
- clearTimeout(timeoutHandle);
3384
- return res;
3385
- } catch (err) {
3386
- clearTimeout(timeoutHandle);
3387
- throw err;
3388
- }
3389
- }
3390
- cleanupExpiredTickets() {
3391
- const now = Date.now();
3392
- for (const [id, ticket] of this.tickets.entries()) {
3393
- if (now - ticket.startedAt > this.ttlMs) {
3394
- this.tickets.delete(id);
3395
- }
3396
- }
3397
- }
3398
- };
3399
-
3400
- // src/core/K_ENT_Krnl_System_Entity_Base.ts
3401
- import http from "http";
3402
- import net from "net";
3403
- import fs4 from "fs";
3404
- import path5 from "path";
3405
- import { fileURLToPath } from "url";
3406
- import { zodToJsonSchema } from "zod-to-json-schema";
3407
- var krnlSystemEntityBase = class extends krnlEntityBase {
3408
- /**
3409
- * _isIngressNetworkMember — true when this entity is a SIBLING of another standalone app
3410
- * inside a KrnlSiblingNetwork (formerly IngressNetwork).
3411
- * NOT set for embedded sub-apps; those use _isSubApp instead.
3412
- */
3413
- _isIngressNetworkMember = false;
3414
- /**
3415
- * _siblingNetwork — the sibling-app peer network this entity administers (if any).
3416
- * Used exclusively for connecting independent standalone KrnlTS apps.
3417
- * NEVER used for sub-apps embedded inside this entity.
3418
- */
3419
- _siblingNetwork = null;
3420
- /** @deprecated Use _siblingNetwork. Alias kept for backward compatibility. */
3421
- get _ingressNetwork() {
3422
- return this._siblingNetwork;
3423
- }
3424
- set _ingressNetwork(v) {
3425
- this._siblingNetwork = v;
3426
- }
3427
- _frontendEnabled = false;
3428
- _frontend = null;
3429
- /**
3430
- * _isSubApp — true when this entity is embedded inside a parent KrnlTS application.
3431
- * When true:
3432
- * - Networking (HTTP / WebSocket) is suppressed; _startSharedServer() returns early.
3433
- * - Registry registration is skipped.
3434
- * - All communication goes through the parent's callInternal() or MessagePort transport.
3435
- */
3436
- _isSubApp = false;
3437
- /**
3438
- * _subAppRegistry — registry of sub-apps embedded in this entity.
3439
- * Populated by loadSubApps(). Keys are lowercase prefix strings.
3440
- */
3441
- _subAppRegistry = /* @__PURE__ */ new Map();
3442
- peers;
3443
- discoverable;
3444
- // AI Properties
3445
- _aiOrchestrator = null;
3446
- _aiTracker = null;
3447
- _aiScheduler = null;
3448
- _jobScheduler = new KrnlJobScheduler();
3449
- _aikoClient = null;
3450
- _aiProfilesStore = null;
3451
- _aikoCatalog = {};
3452
- _krnlSystemEndpointIds = /* @__PURE__ */ new Set([
3453
- "heartbeat",
3454
- "getTelemetry",
3455
- "adminCommand",
3456
- "discoverPeers",
3457
- "getManifest",
3458
- "getLastActionDocs",
3459
- "getFullDocumentation",
3460
- "getUsedPorts",
3461
- "findFreePorts",
3462
- "shutdown",
3463
- "getSiblingNetworkTopology",
3464
- "getSubAppTopology",
3465
- "getAikoCatalog",
3466
- "getTaskList",
3467
- "ai"
3468
- ]);
3469
- reservation;
3470
- peerTtlMs;
3471
- commPort;
3472
- host;
3473
- commComponent;
3474
- _sharedServer;
3475
- serviceSuites;
3476
- unifiedHttpAdapter;
3477
- _documentationProvider;
3478
- _lastPreemptiveDoc = null;
3479
- _lastErrorDoc = null;
3480
- discoverySocket;
3481
- beaconInterval;
3482
- /** portRegistry: serviceName → port (P_local ⊆ ℕ) */
3483
- portRegistry;
3484
- /** Registered service configurations for external processes. */
3485
- _serviceConfigs = [];
3486
- /** Active handles for managed services. */
3487
- _managedServices = /* @__PURE__ */ new Map();
3488
- /**
3489
- * _preferredPort — the port hint supplied at construction.
3490
- * Write-once. Never published externally. The actual bound port is commPort
3491
- * (set by finalizeCommPort after a successful server.listen()).
3492
- */
3493
- _preferredPort;
3494
- /** Directory where {entityName}.ports.json is written. */
3495
- _entityDataDir;
3496
- /** True once gracefulShutdown has been triggered — prevents re-entry. */
3497
- _shuttingDown = false;
3498
- /**
3499
- * Internal readiness signaling.
3500
- * Resolves after _startSharedServer successfully binds and finalizeCommPort is called.
3501
- */
3502
- _readyPromise;
3503
- _resolveReady;
3504
- _magneticLoadPromise = null;
3505
- _registryClient;
3506
- _registryHeartbeatInterval = null;
3507
- _registryEvictionInterval = null;
3508
- _registryApps = /* @__PURE__ */ new Map();
3509
- _bootBarrier;
3510
- _krnlFlags = /* @__PURE__ */ new Set();
3511
- /** Sets a named readiness flag on the entity. */
3512
- setFlag(flag) {
3513
- this._krnlFlags.add(flag);
3514
- console.log(`[${this.entityName}] Flag set: '${flag}'`);
3515
- }
3516
- /** Checks if a named readiness flag is set on the entity. */
3517
- hasFlag(flag) {
3518
- return this._krnlFlags.has(flag);
3519
- }
3520
- /**
3521
- * @param name
3522
- * @param owner
3523
- * @param commPort - WS listen port for the commComponent.
3524
- * @param host - Interface to bind to.
3525
- * @param options - Entity options.
3526
- */
3527
- constructor(name, owner = null, commPort = 10099, host = "0.0.0.0", options = {}) {
3528
- super(name, owner, { ...options, Singleton: true });
3529
- this.systemType = "SystemOrchestrator";
3530
- this.peers = /* @__PURE__ */ new Map();
3531
- this.discoverable = true;
3532
- this.reservation = {
3533
- busy: false,
3534
- reservedBy: null,
3535
- reservedAt: null
3536
- };
3537
- this.peerTtlMs = 6e4;
3538
- import("./K_LIB_Krnl_Registry_Client-NXV6D2QW.js").then(({ KrnlRegistryClient }) => {
3539
- this._registryClient = new KrnlRegistryClient(10099);
3540
- }).catch(() => {
3541
- });
3542
- this._readyPromise = new Promise(async (resolve) => {
3543
- this._resolveReady = resolve;
3544
- });
3545
- this.commPort = commPort;
3546
- this.host = host;
3547
- this.commComponent = new krnlSystemCommComponent(this, commPort, host);
3548
- this._setupBaseFunctionalities();
3549
- this._setupBaseInterface();
3550
- this._setupRpcHandlers();
3551
- this._sharedServer = null;
3552
- this.serviceSuites = /* @__PURE__ */ new Map();
3553
- this.unifiedHttpAdapter = new krnlUnifiedHttpAdapter(this, commPort, host);
3554
- this.portRegistry = /* @__PURE__ */ new Map();
3555
- this._preferredPort = commPort;
3556
- let dataDir = process.cwd();
3557
- const subappStore = globalThis.__krnlSubAppLocalStorage?.getStore();
3558
- if (subappStore && typeof subappStore === "object" && subappStore.appPath) {
3559
- dataDir = subappStore.appPath;
3560
- } else if (options.sourcePath) {
3561
- try {
3562
- const resolved = options.sourcePath.startsWith("file:") ? fileURLToPath(options.sourcePath) : options.sourcePath;
3563
- dataDir = path5.dirname(resolved);
3564
- } catch (_) {
3565
- }
3566
- }
3567
- this._entityDataDir = dataDir;
3568
- console.log(`[KRNL_DATA_DIR] Entity: ${this.entityName}, DataDir: ${this._entityDataDir}, subappStore: ${JSON.stringify(subappStore)}`);
3569
- this._documentationProvider = null;
3570
- this._emitStartupDiagnostics();
3571
- this._bootBarrier = new KrnlBootBarrier();
3572
- this._isSubApp = !!subappStore;
3573
- if (this._isSubApp) {
3574
- this._resolveReady();
3575
- }
3576
- this._magneticLoadPromise = this._runMagneticLoader(options);
3577
- }
3578
- enableFrontend(options) {
3579
- this._frontendEnabled = true;
3580
- this._frontend = new KrnlFrontend(this, options);
3581
- }
3582
- async _runMagneticLoader(options = {}) {
3583
- if (options._skipMagneticLoading) {
3584
- return;
3585
- }
3586
- await this._bootBarrier.waitForPhase1();
3587
- try {
3588
- const { KrnlMagneticLoader } = await import("./K_LIB_Krnl_System_Magnetic_Loader-B2NZMQUG.js");
3589
- await KrnlMagneticLoader.loadAll(this, this._entityDataDir);
3590
- } catch (err) {
3591
- console.error(`[${this.entityName}] Magnetic loader error:`, err);
3592
- }
3593
- }
3594
- /**
3595
- * boot
3596
- * Boot validation & startup entrypoint
3597
- */
3598
- async boot() {
3599
- this._bootBarrier.signalPhase1Complete();
3600
- if (!this._isSubApp && !this._sharedServer) {
3601
- await this.activateServiceSuite("UNIFIED_HTTP");
3602
- }
3603
- await this.whenReady();
3604
- }
3605
- /**
3606
- * whenReady
3607
- * Await this promise to ensure the system has bound to its final port,
3608
- * written its snapshot file, and is fully operational.
3609
- */
3610
- async whenReady() {
3611
- if (this._magneticLoadPromise) {
3612
- await this._magneticLoadPromise;
3613
- }
3614
- await this._validateBootManifestDependencies();
3615
- if (this._magneticLoadPromise) {
3616
- await this._magneticLoadPromise;
3617
- }
3618
- await this._readyPromise;
3619
- }
3620
- /**
3621
- * Validates requiredRemotes manifest dependencies upon boot
3622
- */
3623
- async _validateBootManifestDependencies() {
3624
- try {
3625
- const manifestPath = path5.join(this._entityDataDir, "krnl.json");
3626
- if (!fs4.existsSync(manifestPath)) return;
3627
- const content = fs4.readFileSync(manifestPath, "utf-8");
3628
- const manifest = JSON.parse(content);
3629
- if (!manifest.dependencies?.requiredRemotes) return;
3630
- const availableEntities = /* @__PURE__ */ new Set();
3631
- availableEntities.add(this.entityName);
3632
- if (this.entityClass) availableEntities.add(this.entityClass);
3633
- if (this._ingressNetwork?.members) {
3634
- for (const [prefix] of this._ingressNetwork.members.entries()) {
3635
- availableEntities.add(prefix);
3636
- if (prefix) {
3637
- availableEntities.add(prefix.charAt(0).toUpperCase() + prefix.slice(1));
3638
- }
3639
- }
3640
- }
3641
- const ownedMap = this.ownedComponents || this.components;
3642
- if (ownedMap && typeof ownedMap.values === "function") {
3643
- for (const owned of ownedMap.values()) {
3644
- if (owned?.entityName) availableEntities.add(owned.entityName);
3645
- }
3646
- }
3647
- for (const remote of manifest.dependencies.requiredRemotes) {
3648
- if (remote.targetEntity && !availableEntities.has(remote.targetEntity)) {
3649
- const payload = {
3650
- error: "ERR_KRNL_UNRESOLVED_REMOTE_TARGET",
3651
- sourceEntity: this.entityName,
3652
- missingTargetEntity: remote.targetEntity,
3653
- requiredFid: remote.fid,
3654
- availableEntities: Array.from(availableEntities)
3655
- };
3656
- throw new Error(`[ERR_KRNL_UNRESOLVED_REMOTE_TARGET] Boot validation failed for '${this.entityName}': Target entity '${remote.targetEntity}' required by fid '${remote.fid}' was not found in active system hierarchy. Details: ${JSON.stringify(payload)}`);
3657
- }
3658
- }
3659
- } catch (err) {
3660
- if (err.message?.includes("ERR_KRNL_UNRESOLVED_REMOTE_TARGET")) {
3661
- throw err;
3662
- }
3663
- console.warn(`[BootValidation] Warning: could not parse krnl.json at ${this._entityDataDir}: ${err.message}`);
3664
- }
3665
- }
3666
- // ── Sub-App Loading (Internal Embedded Components) ─────────────────────────
3667
- /**
3668
- * loadSubApps
3669
- *
3670
- * Embeds one or more KrnlTS applications as internal sub-apps of this entity.
3671
- * Sub-apps run without any networking stack — they communicate exclusively via
3672
- * direct in-process method calls (local mode) or worker_threads MessagePort (worker mode).
3673
- *
3674
- * The execution mode for each sub-app is determined by the parent's krnl.json
3675
- * and should already be set on each config object before calling this method.
3676
- * MagneticLoader populates this automatically.
3677
- *
3678
- * Sub-apps are registered in _subAppRegistry and can be called via callInternal().
3679
- *
3680
- * ⚠ Do NOT use startIngressNetwork() for sub-apps. That method is for connecting
3681
- * independent standalone applications in a sibling peer network.
3682
- */
3683
- async loadSubApps(configs) {
3684
- const { KrnlSubAppLoader } = await import("./K_LIB_Krnl_SubApp_Registry-F4FOFAUP.js");
3685
- for (const config of configs) {
3686
- try {
3687
- await KrnlSubAppLoader.load(this, config);
3688
- const prefix = config.prefix.toLowerCase();
3689
- const entry = this._subAppRegistry.get(prefix);
3690
- if (entry && entry.entity) {
3691
- const subAppDir = entry.entity?._entityDataDir || entry.entity?._sourceDir;
3692
- if (subAppDir && fs4.existsSync(path5.join(subAppDir, "frontend")) && this._frontend) {
3693
- this._frontend.registerSubAppFrontend(prefix, path5.join(subAppDir, "frontend"));
3694
- }
3695
- }
3696
- } catch (err) {
3697
- const errMsg = err.message || String(err);
3698
- console.error(`[SubAppRegistry] Failed to load sub-app '${config.prefix}':`, errMsg);
3699
- this._subappErrors = this._subappErrors || [];
3700
- this._subappErrors.push({ subapp: config.prefix, error: errMsg });
3701
- }
3702
- }
3703
- if (this._frontend && this._frontend.frontendDir) {
3704
- try {
3705
- const { KrnlFrontendGenerator } = await import("./K_LIB_Krnl_Frontend_Generator-UYNRNX2X.js");
3706
- const { KrnlFrontendBuilder } = await import("./K_LIB_Krnl_Frontend_Builder-2ZDUH6PF.js");
3707
- const frontendDir = this._frontend.frontendDir;
3708
- await KrnlFrontendGenerator.generate(this, frontendDir);
3709
- await KrnlFrontendBuilder.build(frontendDir);
3710
- } catch (err) {
3711
- console.warn(`[SubAppRegistry] Frontend aggregation rebuild warning on '${this.entityName}':`, err.message);
3712
- }
3713
- }
3714
- }
3715
- /**
3716
- * callInternal
3717
- *
3718
- * Dispatch a functionality call to an embedded sub-app (or self) with zero network overhead.
3719
- *
3720
- * For local-mode sub-apps: direct in-process method call.
3721
- * For worker-mode sub-apps: MessagePort IPC — no HTTP, no TCP.
3722
- *
3723
- * Usage from a functionality:
3724
- * const result = await entity.callInternal('subAppPrefix', 'functionalityId', inputData);
3725
- */
3726
- async callInternal(prefix, fid, input = {}) {
3727
- if (prefix.toLowerCase() === this.entityName.toLowerCase()) {
3728
- return await this.call(fid, input);
3729
- }
3730
- const entry = this._subAppRegistry.get(prefix.toLowerCase());
3731
- if (!entry) {
3732
- throw new Error(
3733
- `[${this.entityName}] callInternal: sub-app '${prefix}' is not registered. Available: [${Array.from(this._subAppRegistry.keys()).join(", ")}]`
3734
- );
3735
- }
3736
- return await entry.entity.call(fid, input);
3737
- }
3738
- /**
3739
- * getSubAppTopology
3740
- *
3741
- * Returns a snapshot of all embedded sub-apps registered in this entity,
3742
- * including their execution mode and registration time.
3743
- */
3744
- getSubAppTopology() {
3745
- if (this._subAppRegistry.size === 0) return null;
3746
- return {
3747
- parent: this.entityName,
3748
- subApps: Array.from(this._subAppRegistry.entries()).map(([prefix, entry]) => ({
3749
- prefix,
3750
- executionMode: entry.executionMode,
3751
- addedAt: entry.addedAt,
3752
- entityName: entry.entity.entityName ?? prefix
3753
- }))
3754
- };
3755
- }
3756
- // ── Sibling Network (formerly Ingress Network) ───────────────────────────────
3757
- //
3758
- // The sibling network connects INDEPENDENT standalone KrnlTS applications that each
3759
- // have their own networking stack. It is NOT for embedding sub-apps.
3760
- // Use loadSubApps() + callInternal() for internal components instead.
3761
- /**
3762
- * startSiblingNetwork (formerly startIngressNetwork)
3763
- *
3764
- * Configures a sibling peer network of independent standalone KrnlTS applications.
3765
- * Each sibling is a full KrnlTS app with its own HTTP/WS server.
3766
- *
3767
- * ⚠ Do NOT call this to host sub-apps. Use loadSubApps() for embedded components.
3768
- */
3769
- async startSiblingNetwork(members) {
3770
- this._siblingNetwork = new KrnlSiblingNetwork();
3771
- for (const config of members) {
3772
- try {
3773
- await this._siblingNetwork.addMember(this, config);
3774
- } catch (err) {
3775
- const errMsg = err.message || String(err);
3776
- console.error(`[SiblingNetwork] Failed to add sibling '${config.prefix}':`, errMsg);
3777
- }
3778
- }
3779
- }
3780
- /**
3781
- * startIngressNetwork — preserved as alias for backward compatibility.
3782
- * @deprecated Use startSiblingNetwork() for connecting standalone sibling apps.
3783
- * Use loadSubApps() for embedding sub-apps inside this entity.
3784
- */
3785
- async startIngressNetwork(members) {
3786
- return this.startSiblingNetwork(members);
3787
- }
3788
- /**
3789
- * joinSiblingNetwork (formerly joinIngressNetwork)
3790
- * Adds a single sibling to the peer network.
3791
- */
3792
- async joinSiblingNetwork(config) {
3793
- if (!this._siblingNetwork) {
3794
- this._siblingNetwork = new KrnlSiblingNetwork();
3795
- }
3796
- return await this._siblingNetwork.addMember(this, config);
3797
- }
3798
- /** @deprecated Use joinSiblingNetwork(). */
3799
- async joinIngressNetwork(config) {
3800
- return this.joinSiblingNetwork(config);
3801
- }
3802
- /**
3803
- * getSiblingNetworkTopology (formerly getIngressNetworkTopology)
3804
- *
3805
- * Returns the topology of the sibling peer network (standalone apps only).
3806
- * This is NOT related to embedded sub-apps — use getSubAppTopology() for those.
3807
- */
3808
- getSiblingNetworkTopology() {
3809
- if (!this._siblingNetwork) return null;
3810
- const members = Array.from(this._siblingNetwork.members.entries()).map(([prefix, entry]) => ({
3811
- prefix,
3812
- entityName: entry.entity.entityName,
3813
- addedAt: entry.addedAt
3814
- }));
3815
- return {
3816
- admin: this.entityName,
3817
- port: this.commPort,
3818
- members
3819
- };
3820
- }
3821
- /** @deprecated Use getSiblingNetworkTopology(). Alias kept for backward compatibility. */
3822
- getIngressNetworkTopology() {
3823
- return this.getSiblingNetworkTopology();
3824
- }
3825
- /**
3826
- * port — stable public accessor for the active bound port.
3827
- * Mirrors commPort. Resolves to the OS-assigned value after finalizeCommPort().
3828
- * Use this instead of commPort or commComponent.listenPort.
3829
- */
3830
- get port() {
3831
- return this.commPort;
3832
- }
3833
- /**
3834
- * Registers a documentation provider to enable automatic result decoration across all protocols.
3835
- */
3836
- setDocumentationProvider(provider) {
3837
- this._documentationProvider = provider;
3838
- }
3839
- async _decorateResult(result, fid, input) {
3840
- let finalResult = result && typeof result === "object" && result.status ? result : { status: "success", payload: result };
3841
- if (this._documentationProvider && finalResult.status === "success") {
3842
- if (typeof this._documentationProvider.getNextStepsDoc === "function") {
3843
- const nextSteps = this._documentationProvider.getNextStepsDoc(fid);
3844
- if (nextSteps && nextSteps.length > 0) {
3845
- this._lastPreemptiveDoc = {
3846
- message: "Progressive Exploration: Recommended next steps.",
3847
- nextSteps
3848
- };
3849
- this._lastErrorDoc = null;
3850
- finalResult.preemptiveDocumentation = {
3851
- message: "PREEMPTIVE_DOCS: call('getLastActionDocs'); FULL_DOCS: call('getFullDocumentation');",
3852
- accessEndpoint: "getLastActionDocs"
3853
- };
3854
- }
3855
- }
3856
- }
3857
- return finalResult;
3858
- }
3859
- async _decorateError(err, fid, input) {
3860
- const response = {
3861
- status: "error",
3862
- message: err.message || String(err),
3863
- payload: null,
3864
- ...err.metadata || {}
3865
- };
3866
- if (this._documentationProvider && typeof this._documentationProvider.getDocForEndpoint === "function") {
3867
- const usageDoc = this._documentationProvider.getDocForEndpoint(fid);
3868
- if (usageDoc) {
3869
- this._lastErrorDoc = usageDoc;
3870
- this._lastPreemptiveDoc = null;
3871
- response.errorDocumentation = {
3872
- message: "ERROR_DOCS: call('getLastActionDocs'); FULL_DOCS: call('getFullDocumentation');",
3873
- accessEndpoint: "getLastActionDocs"
3874
- };
3875
- }
3876
- }
3877
- return response;
3878
- }
3879
- getNotFoundResponse(path6) {
3880
- const response = {
3881
- status: "error",
3882
- message: `Route '${path6}' not found.`
3883
- };
3884
- if (this._documentationProvider && typeof this._documentationProvider.getDocsForLayer === "function") {
3885
- const entryPoints = this._documentationProvider.getDocsForLayer("LAYER_1_ENTRY");
3886
- if (entryPoints && entryPoints.length > 0) {
3887
- response.preemptiveDocumentation = {
3888
- message: "Welcome! Here is the entry-level documentation.",
3889
- entryPoints
3890
- };
3891
- }
3892
- }
3893
- return response;
3894
- }
3895
- isDiscoveryAvailable() {
3896
- return typeof window === "undefined";
3897
- }
3898
- _emitStartupDiagnostics() {
3899
- const diagnostics = {
3900
- event: "KRNL_STARTUP",
3901
- entity: this.entityName,
3902
- timestamp: Date.now(),
3903
- subsystems: {
3904
- // preferredPort is the constructor hint; actual bound port is set later by finalizeCommPort
3905
- comm: { status: "pending", preferredPort: this._preferredPort },
3906
- discovery: { status: this.isDiscoveryAvailable() ? "available" : "unavailable" }
3907
- },
3908
- flags: this.getSystemFlags(),
3909
- environment: typeof window === "undefined" ? "node" : "browser"
3910
- };
3911
- console.log(`[KRNL_DIAGNOSTICS] ${JSON.stringify(diagnostics)}`);
3912
- Logger.log(`System ${this.entityName} starting diagnostics emitted.`);
3913
- }
3914
- getSystemFlags() {
3915
- return {
3916
- discoverable: this.discoverable,
3917
- busy: this.reservation.busy,
3918
- reservedBy: this.reservation.reservedBy,
3919
- reservedAt: this.reservation.reservedAt
3920
- };
3921
- }
3922
- setDiscoverable(value) {
3923
- this.discoverable = Boolean(value);
3924
- return this.getSystemFlags();
3925
- }
3926
- // ── Port Registry Methods ────────────────────────────────────────────────
3927
- /**
3928
- * Register a named service port.
3929
- * registerPort(name, p) → portRegistry[name] = p
3930
- * Throws if the port is already claimed by a different service.
3931
- */
3932
- async registerPort(serviceName, port) {
3933
- for (const [existingName, existingPort] of this.portRegistry.entries()) {
3934
- if (existingPort === port && port > 0 && existingName !== serviceName) {
3935
- throw new Error(
3936
- `[${this.entityName}] Port ${port} is already registered to '${existingName}'.`
3937
- );
3938
- }
3939
- }
3940
- this.portRegistry.set(serviceName, port);
3941
- await this._writePortsFile();
3942
- }
3943
- /** Remove a service port registration. */
3944
- async unregisterPort(serviceName) {
3945
- if (serviceName === "_krnl_system") {
3946
- throw new Error(`[${this.entityName}] Cannot unregister the system port '_krnl_system'.`);
3947
- }
3948
- this.portRegistry.delete(serviceName);
3949
- await this._writePortsFile();
3950
- }
3951
- /** Return a plain-object snapshot of portRegistry: Record<serviceName, port>. */
3952
- getRegisteredPorts() {
3953
- return Object.fromEntries(this.portRegistry.entries());
3954
- }
3955
- // ── Port Snapshot File ────────────────────────────────────────────────────
3956
- /** Absolute path of the JSON port snapshot co-located with the assembler. */
3957
- _getPortsFilePath() {
3958
- return path5.join(this._entityDataDir, `${this.entityName}.ports.json`);
3959
- }
3960
- /**
3961
- * _writePortsFile — persists portRegistry to disk.
3962
- *
3963
- * Only called by finalizeCommPort() — never from constructor state.
3964
- */
3965
- async _writePortsFile() {
3966
- const filePath = this._getPortsFilePath();
3967
- const snapshot = JSON.stringify({
3968
- entity: this.entityName,
3969
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3970
- ports: this.getRegisteredPorts()
3971
- }, null, 2);
3972
- try {
3973
- const dir = path5.dirname(filePath);
3974
- if (!fs4.existsSync(dir)) {
3975
- await fs4.promises.mkdir(dir, { recursive: true });
3976
- }
3977
- await fs4.promises.writeFile(filePath, snapshot);
3978
- } catch (err) {
3979
- Logger.error(`[${this.entityName}] Ports file write failed:`, err);
3980
- }
3981
- }
3982
- /** Remove the ports snapshot file on shutdown. */
3983
- _deletePortsFile() {
3984
- const filePath = this._getPortsFilePath();
3985
- try {
3986
- if (fs4.existsSync(filePath)) {
3987
- fs4.unlinkSync(filePath);
3988
- }
3989
- } catch (_) {
3990
- }
3991
- }
3992
- // ── Port Probe ────────────────────────────────────────────────────────────
3993
- /**
3994
- * _probeAvailablePort — find the first bindable port starting from preferred.
3995
- *
3996
- * Algorithm:
3997
- * for p in [preferred, preferred+100] ∩ [1, 65535]:
3998
- * try net.createServer().listen(p, host)
3999
- * if success → close probe, return p
4000
- * if EADDRINUSE → continue
4001
- * throw if none found
4002
- *
4003
- * The probe server is closed before returning so the actual server can bind.
4004
- * There is an inherent TOCTOU (time-of-check/time-of-use) window between
4005
- * probe close and real listen, but this is unavoidable without SO_REUSEPORT
4006
- * and is acceptable for the port-drift bug class we are eliminating.
4007
- */
4008
- async _probeAvailablePort(preferred, host) {
4009
- const cap = Math.min(preferred + 100, 65535);
4010
- for (let port = preferred; port <= cap; port++) {
4011
- const available = await new Promise((resolve) => {
4012
- const probe = net.createServer();
4013
- probe.once("error", () => resolve(false));
4014
- probe.listen(port, host, () => probe.close(() => setTimeout(() => resolve(true), 50)));
4015
- });
4016
- if (available) return port;
4017
- }
4018
- throw new Error(
4019
- `[${this.entityName}] No available port in [${preferred}, ${cap}]. Cannot start server.`
4020
- );
4021
- }
4022
- // ── Single Source of Truth for Port Assignment ────────────────────────────
4023
- /**
4024
- * finalizeCommPort — the only method that writes port state.
4025
- *
4026
- * Called once, from _startSharedServer, after server.listen() succeeds.
4027
- * Never called from the constructor.
4028
- *
4029
- * Updates (atomically from caller's perspective):
4030
- * this.commPort ← actualPort
4031
- * this.commComponent.listenPort ← actualPort
4032
- * this.unifiedHttpAdapter.port ← actualPort
4033
- * portRegistry['_krnl_system'] ← actualPort
4034
- * ports snapshot file ← written atomically
4035
- * _readyPromise ← resolved
4036
- */
4037
- async finalizeCommPort(actualPort) {
4038
- this.commPort = actualPort;
4039
- this.commComponent.listenPort = actualPort;
4040
- this.unifiedHttpAdapter.port = actualPort;
4041
- this.portRegistry.set("_krnl_system", actualPort);
4042
- await this._writePortsFile();
4043
- await this._registerWithRegistry(actualPort);
4044
- this._resolveReady();
4045
- Logger.log(`[${this.entityName}] commPort finalized \u2192 ${actualPort}`);
4046
- }
4047
- async _registerWithRegistry(actualPort) {
4048
- if (this._isSubApp || this._isIngressNetworkMember) return;
4049
- if (!this._registryClient) {
4050
- const { KrnlRegistryClient } = await import("./K_LIB_Krnl_Registry_Client-NXV6D2QW.js");
4051
- this._registryClient = new KrnlRegistryClient(10099);
4052
- }
4053
- if (actualPort === 10099) {
4054
- console.log(`[${this.entityName}] Self-promoting to central registry host.`);
4055
- this._registryApps = /* @__PURE__ */ new Map();
4056
- const { registerAppApi, deregisterAppApi, heartbeatAppApi, lookupAppApi, listAppsApi } = await import("./K_LIB_Krnl_System_Base_Functionality_APIs-ZZUZ6ZG5.js");
4057
- this.addLocal({ id: "registerApp", api: registerAppApi(this) });
4058
- this.addLocal({ id: "deregisterApp", api: deregisterAppApi(this) });
4059
- this.addLocal({ id: "heartbeatApp", api: heartbeatAppApi(this) });
4060
- this.addLocal({ id: "lookupApp", api: lookupAppApi(this) });
4061
- this.addLocal({ id: "listApps", api: listAppsApi(this) });
4062
- this._registryEvictionInterval = setInterval(() => {
4063
- const now = Date.now();
4064
- for (const [name, app] of this._registryApps.entries()) {
4065
- if (now - app.lastHeartbeat > 3e4) {
4066
- console.log(`[Registry] Evicting dead app "${name}" (no heartbeat for 30s)`);
4067
- this._registryApps.delete(name);
4068
- }
4069
- }
4070
- }, 5e3);
4071
- return;
4072
- }
4073
- const registered = await this._registryClient.register(this.entityName, actualPort, typeof process !== "undefined" ? process.pid : 0);
4074
- if (registered) {
4075
- if (this._registryHeartbeatInterval) clearInterval(this._registryHeartbeatInterval);
4076
- this._registryHeartbeatInterval = setInterval(async () => {
4077
- await this._registryClient.heartbeat(this.entityName);
4078
- }, 1e4);
4079
- }
4080
- this._startReRegistrationSafetyLoop(actualPort);
4081
- }
4082
- _startReRegistrationSafetyLoop(actualPort) {
4083
- setInterval(async () => {
4084
- const alive = await this._registryClient.isRegistryAlive();
4085
- if (alive) {
4086
- await this._registryClient.register(this.entityName, actualPort, typeof process !== "undefined" ? process.pid : 0);
4087
- }
4088
- }, 6e4);
4089
- }
4090
- async _deregisterFromRegistry() {
4091
- if (this._registryHeartbeatInterval) clearInterval(this._registryHeartbeatInterval);
4092
- if (this._registryEvictionInterval) clearInterval(this._registryEvictionInterval);
4093
- if (this.commPort === 10099) return;
4094
- if (this._registryClient) {
4095
- try {
4096
- await this._registryClient.deregister(this.entityName);
4097
- } catch (_) {
4098
- }
4099
- }
4100
- }
4101
- // ── Graceful Shutdown ─────────────────────────────────────────────────────
4102
- /**
4103
- * gracefulShutdown
4104
- *
4105
- * Sequence:
4106
- * 1. Signal all owned entities (microservices).
4107
- * - Calls gracefulShutdown() if available, else dispose().
4108
- * 2. Stop managed external processes.
4109
- * 3. Await all shutdowns (parallel, bounded by timeoutMs).
4110
- * 4. Delete ports snapshot file.
4111
- * 5. Dispose self (server, sockets, intervals).
4112
- * 6. Exit process.
4113
- *
4114
- * @param opts.timeoutMs Max wait for owned services (default 10 000 ms).
4115
- */
4116
- async gracefulShutdown({ timeoutMs = 1e4 } = {}) {
4117
- if (this._shuttingDown) return;
4118
- this._shuttingDown = true;
4119
- console.log(`
4120
- [${this.entityName}] \u2500\u2500 Graceful shutdown initiated \u2500\u2500`);
4121
- try {
4122
- await this._deregisterFromRegistry();
4123
- } catch (_) {
4124
- }
4125
- const owned = this.hierarchyManager.getAllOwnedComponentEntities?.() ?? [];
4126
- const shutdownOne = async (child) => {
4127
- const label = child.entityName ?? "(unknown)";
4128
- try {
4129
- if (typeof child.gracefulShutdown === "function") {
4130
- await child.gracefulShutdown({ timeoutMs });
4131
- } else {
4132
- child.dispose();
4133
- }
4134
- console.log(`[${this.entityName}] \u2713 '${label}' stopped.`);
4135
- } catch (err) {
4136
- console.error(`[${this.entityName}] \u2717 '${label}' shutdown error: ${err?.message ?? err}`);
4137
- }
4138
- };
4139
- const stopManaged = async () => {
4140
- const stopPromises = [];
4141
- for (const [name, handle] of this._managedServices) {
4142
- if (handle.processHandle && handle.status !== "stopped") {
4143
- Logger.log(`[${this.entityName}] Stopping managed service '${name}' (PID: ${handle.pid})...`);
4144
- handle.processHandle.kill("SIGTERM");
4145
- handle.status = "stopped";
4146
- if (handle.processHandle.promise) {
4147
- stopPromises.push(handle.processHandle.promise.catch(() => {
4148
- }));
4149
- }
4150
- }
4151
- }
4152
- await Promise.all(stopPromises);
4153
- };
4154
- await Promise.race([
4155
- Promise.allSettled([...owned.map(shutdownOne), stopManaged()]),
4156
- new Promise((res) => setTimeout(res, timeoutMs))
4157
- ]);
4158
- this._deletePortsFile();
4159
- try {
4160
- const { KrnlFrontendBuilder } = await import("./K_LIB_Krnl_Frontend_Builder-2ZDUH6PF.js");
4161
- KrnlFrontendBuilder.stop(this._entityDataDir);
4162
- } catch (_) {
4163
- }
4164
- this.dispose();
4165
- console.log(`[${this.entityName}] \u2500\u2500 Shutdown complete \u2500\u2500`);
4166
- if (typeof process !== "undefined" && process.exit) {
4167
- setTimeout(() => process.exit(0), 100);
4168
- }
4169
- }
4170
- /**
4171
- * shutdown — public alias for gracefulShutdown().
4172
- * Enables clean consumer code: await system.shutdown()
4173
- * No type-casting or feature detection required.
4174
- */
4175
- async shutdown(opts = {}) {
4176
- return this.gracefulShutdown(opts);
4177
- }
4178
- // ── Endpoint Category Helpers ─────────────────────────────────────────────
4179
- /**
4180
- * addInternalEndpoint
4181
- *
4182
- * Registers a functionality accessible ONLY to services whose ports are in
4183
- * the portRegistry (internal microservices). All external ports are forbidden.
4184
- *
4185
- * policy: allow = [...portRegistry values], default = forbid_unlisted
4186
- */
4187
- addInternalEndpoint(config) {
4188
- const internalPorts = Object.values(this.getRegisteredPorts());
4189
- config.accessPolicy = {
4190
- allow: internalPorts,
4191
- allow_with_key: [],
4192
- forbid: [],
4193
- default_connection_behaviour: "forbid_unlisted"
4194
- };
4195
- this.addLocal(config);
4196
- }
4197
- /**
4198
- * addExternalEndpoint
4199
- *
4200
- * Registers a functionality for external consumers.
4201
- * access = 'free' → no key required (default_connection_behaviour = allow_unlisted)
4202
- * access = 'keyed' → accessKey must be supplied in x-krnl-access-key header
4203
- * (default_connection_behaviour = ask_key_unlisted)
4204
- *
4205
- * @param config - Standard functionality config.
4206
- * @param access - 'free' | 'keyed'
4207
- * @param accessKey - Required when access = 'keyed'.
4208
- */
4209
- addExternalEndpoint(config, access = "free", accessKey) {
4210
- if (access === "keyed" && !accessKey) {
4211
- throw new Error(`[${this.entityName}] addExternalEndpoint: accessKey is required for 'keyed' endpoints.`);
4212
- }
4213
- config.accessPolicy = {
4214
- allow: [],
4215
- allow_with_key: [],
4216
- forbid: [],
4217
- default_connection_behaviour: access === "free" ? "allow_unlisted" : "ask_key_unlisted"
4218
- };
4219
- if (accessKey) config.accessKey = accessKey;
4220
- this.addLocal(config);
4221
- }
4222
- // ── Managed Services ──────────────────────────────────────────────────────
4223
- /**
4224
- * registerManagedService
4225
- * Adds an external process configuration to the system's startup sequence.
4226
- * Services are started in the order they are registered.
4227
- */
4228
- registerManagedService(config) {
4229
- if (this._serviceConfigs.some((c) => c.name === config.name)) {
4230
- throw new Error(`[${this.entityName}] Managed service '${config.name}' is already registered.`);
4231
- }
4232
- this._serviceConfigs.push(config);
4233
- }
4234
- /**
4235
- * startManagedServices
4236
- * Sequentially launches all registered external processes.
4237
- * Assigns dynamic ports, injects them into process environment, and updates the port registry.
4238
- */
4239
- async startManagedServices() {
4240
- for (const config of this._serviceConfigs) {
4241
- if (this._managedServices.has(config.name)) continue;
4242
- const preferred = config.env?.PORT ? parseInt(config.env.PORT) : 1e4;
4243
- const assignedPort = await this._probeAvailablePort(preferred, "0.0.0.0");
4244
- const env = {
4245
- ...process.env,
4246
- ...config.env || {},
4247
- [config.portEnvVar || "PORT"]: assignedPort.toString()
4248
- };
4249
- Logger.log(`[${this.entityName}] Starting managed service '${config.name}' on port ${assignedPort}...`);
4250
- const handle = KrnlShell.spawn(config.command, config.args || [], {
4251
- cwd: config.cwd,
4252
- env,
4253
- stdio: "inherit"
4254
- });
4255
- const serviceHandle = {
4256
- config,
4257
- port: assignedPort,
4258
- processHandle: handle,
4259
- pid: handle.pid,
4260
- status: "starting"
4261
- };
4262
- this._managedServices.set(config.name, serviceHandle);
4263
- await this.registerPort(config.name, assignedPort);
4264
- if (config.waitForStartup) {
4265
- const timeout = config.startupTimeoutMs || 3e4;
4266
- const start = Date.now();
4267
- let ready = false;
4268
- while (Date.now() - start < timeout) {
4269
- ready = await new Promise((resolve) => {
4270
- const probe = net.connect(assignedPort, "127.0.0.1");
4271
- probe.on("connect", () => {
4272
- probe.destroy();
4273
- resolve(true);
4274
- });
4275
- probe.on("error", () => {
4276
- resolve(false);
4277
- });
4278
- });
4279
- if (ready) break;
4280
- if (serviceHandle.status === "failed") break;
4281
- await new Promise((r) => setTimeout(r, 500));
4282
- }
4283
- if (ready) {
4284
- serviceHandle.status = "running";
4285
- Logger.log(`[${this.entityName}] Managed service '${config.name}' is READY.`);
4286
- } else {
4287
- serviceHandle.status = "failed";
4288
- Logger.error(`[${this.entityName}] Managed service '${config.name}' FAILED to start within ${timeout}ms.`);
4289
- }
4290
- } else {
4291
- serviceHandle.status = "running";
4292
- }
4293
- handle.promise.then(({ code, signal }) => {
4294
- if (serviceHandle.status !== "stopped") {
4295
- serviceHandle.status = "failed";
4296
- Logger.error(`[${this.entityName}] Managed service '${config.name}' exited unexpectedly (code: ${code}, signal: ${signal})`);
4297
- }
4298
- });
4299
- }
4300
- }
4301
- reserveFor(serviceName = "unknown") {
4302
- this.reservation = {
4303
- busy: true,
4304
- reservedBy: serviceName,
4305
- reservedAt: Date.now()
4306
- };
4307
- return this.getSystemFlags();
4308
- }
4309
- releaseReservation(serviceName = null) {
4310
- if (serviceName && this.reservation.reservedBy && this.reservation.reservedBy !== serviceName) {
4311
- throw new Error(
4312
- `[${this.entityName}] Reservation owned by ${this.reservation.reservedBy}; cannot release as ${serviceName}.`
4313
- );
4314
- }
4315
- this.reservation = {
4316
- busy: false,
4317
- reservedBy: null,
4318
- reservedAt: null
4319
- };
4320
- return this.getSystemFlags();
4321
- }
4322
- _assertAvailableForRemoteAccess(requester = null) {
4323
- if (!this.reservation.busy) return;
4324
- if (requester && requester === this.reservation.reservedBy) return;
4325
- const by = this.reservation.reservedBy || "another service";
4326
- throw new Error(`[${this.entityName}] Entity is busy/reserved by ${by}.`);
4327
- }
4328
- getManifest() {
4329
- const apiNames = [];
4330
- const eventsNames = [];
4331
- const api = {};
4332
- const serializeSchema = (schema) => {
4333
- if (!schema) return void 0;
4334
- try {
4335
- return zodToJsonSchema(schema);
4336
- } catch (e) {
4337
- return { type: "custom", message: "Non-Zod or complex schema" };
4338
- }
4339
- };
4340
- const buildFManifest = (f, type, resolved) => {
4341
- const fManifest = {
4342
- id: f.id,
4343
- type,
4344
- method: resolved.method || "POST",
4345
- visibility: resolved.visibility,
4346
- sourcePath: resolved.sourcePath,
4347
- examples: resolved.examples || f.examples || null,
4348
- example: resolved.example || f.example || null,
4349
- events: []
4350
- };
4351
- if (resolved.intelligenceSpec) {
4352
- fManifest.intelligenceSpec = resolved.intelligenceSpec;
4353
- }
4354
- resolved.emitters.forEach((_, eid) => {
4355
- const eventId = `${f.id}:${eid}`;
4356
- fManifest.events.push(eventId);
4357
- eventsNames.push(eventId);
4358
- });
4359
- if (resolved.schema) {
4360
- fManifest.schema = {};
4361
- if (resolved.schema.input) {
4362
- fManifest.schema.input = serializeSchema(resolved.schema.input);
4363
- }
4364
- if (resolved.schema.output) {
4365
- fManifest.schema.output = serializeSchema(resolved.schema.output);
4366
- }
4367
- }
4368
- return fManifest;
4369
- };
4370
- this.localFunctionalities.forEach((f) => {
4371
- api[f.id] = buildFManifest(f, "local", f);
4372
- apiNames.push(f.id);
4373
- });
4374
- this.remoteFunctionalities.forEach((f) => {
4375
- if (!api[f.id]) {
4376
- const resolved = this.resolveLocalFunctionality(f.id);
4377
- if (resolved) {
4378
- api[f.id] = buildFManifest(f, "remote", resolved);
4379
- } else {
4380
- api[f.id] = { id: f.id, type: "remote" };
4381
- }
4382
- apiNames.push(f.id);
4383
- }
4384
- });
4385
- return {
4386
- entityName: this.entityName,
4387
- systemType: this.systemType,
4388
- flags: this.getSystemFlags(),
4389
- telemetry: this.telemetryEnabled,
4390
- inputs: {
4391
- collectors: this.interface.collectorNames,
4392
- api
4393
- },
4394
- outputs: {
4395
- emitters: this.interface.emitterNames,
4396
- events: eventsNames
4397
- }
4398
- };
4399
- }
4400
- async startDiscovery(discoveryPort = 10101, discoveryHost = "255.255.255.255") {
4401
- if (this._isIngressNetworkMember || this._isSubApp) return;
4402
- if (this.discoverySocket) return;
4403
- if (!this.isDiscoveryAvailable()) {
4404
- console.warn(`[${this.entityName}] Discovery: UDP not supported in current environment.`);
4405
- return;
4406
- }
4407
- const dgram = await import("dgram").then((m) => m.default || m);
4408
- this.discoverySocket = dgram.createSocket({ type: "udp4", reuseAddr: true });
4409
- this.discoverySocket.on("error", (err) => {
4410
- console.warn(`[${this.entityName}] Discovery socket error:`, err.message);
4411
- try {
4412
- if (this.discoverySocket) {
4413
- this.discoverySocket.close();
4414
- }
4415
- } catch (e) {
4416
- }
4417
- this.discoverySocket = null;
4418
- });
4419
- this.discoverySocket.on("message", (msg, rinfo) => {
4420
- try {
4421
- const data = JSON.parse(msg.toString());
4422
- if (data.type === "KRNL_REGISTRY_RESTART" && this.commPort !== 10099) {
4423
- console.log(`[${this.entityName}] Registry restart beacon received. Triggering immediate re-registration.`);
4424
- this._registerWithRegistry(this.commPort).catch(() => {
4425
- });
4426
- return;
4427
- }
4428
- if (data.type === "KRNL_BEACON" && data.id !== this.entityName) {
4429
- if (data.discoverable === false) {
4430
- this.peers.delete(data.id);
4431
- return;
4432
- }
4433
- this.peers.set(data.id, {
4434
- id: data.id,
4435
- name: data.id,
4436
- address: `${rinfo.address}:${data.port}`,
4437
- busy: Boolean(data.busy),
4438
- reservedBy: data.reservedBy || null,
4439
- discoverable: data.discoverable !== false,
4440
- lastSeen: Date.now()
4441
- });
4442
- }
4443
- } catch (e) {
4444
- }
4445
- });
4446
- const broadcastTarget = this.host === "127.0.0.1" ? "127.0.0.1" : discoveryHost;
4447
- const bindHost = this.host === "::" || !this.host ? "0.0.0.0" : this.host;
4448
- try {
4449
- this.discoverySocket.bind(discoveryPort, bindHost, () => {
4450
- try {
4451
- if (this.discoverySocket) {
4452
- this.discoverySocket.setBroadcast(true);
4453
- console.log(`[${this.entityName}] Discovery active on ${this.host}:${discoveryPort} (broadcast to ${broadcastTarget})`);
4454
- }
4455
- } catch (err) {
4456
- console.warn(`[${this.entityName}] Discovery setBroadcast failed:`, err.message);
4457
- }
4458
- });
4459
- } catch (err) {
4460
- console.warn(`[${this.entityName}] Discovery bind failed:`, err.message);
4461
- this.discoverySocket = null;
4462
- }
4463
- this.beaconInterval = setInterval(async () => {
4464
- if (!this.discoverable) return;
4465
- await this.whenReady();
4466
- const beacon = JSON.stringify({
4467
- type: "KRNL_BEACON",
4468
- id: this.entityName,
4469
- port: this.commPort,
4470
- discoverable: this.discoverable,
4471
- busy: this.reservation.busy,
4472
- reservedBy: this.reservation.reservedBy
4473
- });
4474
- if (this.discoverySocket) {
4475
- this.discoverySocket.send(beacon, 0, beacon.length, discoveryPort, broadcastTarget);
4476
- }
4477
- }, 5e3);
4478
- if (this.commPort === 10099) {
4479
- await this.whenReady();
4480
- const restartBeacon = JSON.stringify({ type: "KRNL_REGISTRY_RESTART", port: 10099 });
4481
- if (this.discoverySocket) {
4482
- this.discoverySocket.send(restartBeacon, 0, restartBeacon.length, discoveryPort, broadcastTarget);
4483
- }
4484
- }
4485
- await this._startSharedServer();
4486
- }
4487
- async _startSharedServer() {
4488
- if (this._isSubApp || this._isIngressNetworkMember) return;
4489
- if (this._sharedServer) return;
4490
- const resolvedPort = await this._probeAvailablePort(this._preferredPort, this.host);
4491
- this._sharedServer = http.createServer();
4492
- if (!this.unifiedHttpAdapter) {
4493
- const { krnlUnifiedHttpAdapter: krnlUnifiedHttpAdapter2 } = await import("./K_LIB_Krnl_System_Unified_Http_Adapter-M6SBHIVA.js");
4494
- this.unifiedHttpAdapter = new krnlUnifiedHttpAdapter2(this, resolvedPort, this.host);
4495
- }
4496
- await this.unifiedHttpAdapter.start(this._sharedServer);
4497
- this.serviceSuites.set("UNIFIED_HTTP", this.unifiedHttpAdapter);
4498
- await this.commComponent.startWsServer(this._sharedServer);
4499
- return new Promise((resolve, reject) => {
4500
- this._sharedServer.listen(resolvedPort, this.host, async () => {
4501
- const bound = this._sharedServer.address().port;
4502
- await this.finalizeCommPort(bound);
4503
- console.log(`[${this.entityName}] Unified port active on http://${this.host}:${bound} (WS + REST + MCP + ACP)`);
4504
- resolve();
4505
- });
4506
- this._sharedServer.on("error", (err) => {
4507
- console.error(`[${this.entityName}] Failed to start unified server:`, err.message);
4508
- reject(err);
4509
- });
4510
- });
4511
- }
4512
- async activateServiceSuite(suiteName = "UNIFIED_HTTP") {
4513
- return this._startSharedServer();
4514
- }
4515
- listPeers() {
4516
- const now = Date.now();
4517
- for (const [id, peer] of this.peers.entries()) {
4518
- if (now - peer.lastSeen > this.peerTtlMs) this.peers.delete(id);
4519
- }
4520
- return Array.from(this.peers.values()).filter((peer) => peer.discoverable !== false);
4521
- }
4522
- getRemoteEntity(peerId) {
4523
- const peer = this.peers.get(peerId);
4524
- if (!peer) return null;
4525
- return {
4526
- call: async (fid, data) => {
4527
- return await this.commComponent.callWsRpc(peer.address, "call", { fid, data });
4528
- }
4529
- };
4530
- }
4531
- async wire(peerId, options) {
4532
- const peer = this.peers.get(peerId);
4533
- if (!peer) throw new Error(`Peer ${peerId} not discovered.`);
4534
- if (peer.busy) throw new Error(`Peer ${peerId} is reserved by ${peer.reservedBy || "another service"}.`);
4535
- const { localOutput, remoteInput, remoteOutput, localInput, connectionPolicy = {} } = options;
4536
- if (localOutput && remoteInput) {
4537
- await this.commComponent.wireViaWs(localOutput, peer.address, remoteInput, peer.name, {
4538
- managedBy: connectionPolicy.managedBy || this.entityName,
4539
- externallyMutable: connectionPolicy.externallyMutable !== false,
4540
- metadata: connectionPolicy.metadata || {}
4541
- });
4542
- }
4543
- if (remoteOutput && localInput) {
4544
- await this.commComponent.callWsRpc(peer.address, "wire-output-to-me", {
4545
- remoteOutput,
4546
- localInput,
4547
- myAddress: `${this.host}:${this.commPort}`,
4548
- myName: this.entityName,
4549
- connectionPolicy
4550
- });
4551
- }
4552
- }
4553
- _setupRpcHandlers() {
4554
- this.commComponent.defineRpc("get-manifest", async () => {
4555
- return this.getManifest();
4556
- });
4557
- this.commComponent.defineRpc("wire-output-to-me", async (params) => {
4558
- const { remoteOutput, localInput, myAddress, myName, connectionPolicy = {} } = params;
4559
- this._assertAvailableForRemoteAccess(myName);
4560
- return await this.commComponent.wireViaWs(remoteOutput, myAddress, localInput, myName, {
4561
- managedBy: connectionPolicy.managedBy || myName,
4562
- externallyMutable: connectionPolicy.externallyMutable !== false,
4563
- metadata: connectionPolicy.metadata || {}
4564
- });
4565
- });
4566
- this.commComponent.defineRpc("call", async ({ fid, data }, { callerPort } = {}) => {
4567
- this._assertAvailableForRemoteAccess(data?.meta?.requester || null);
4568
- return await this.call(fid, data, { callerPort, accessKey: data?.meta?.accessKey });
4569
- });
4570
- this.commComponent.defineRpc("set-entity-flags", async ({ discoverable, busy, reservedBy, requester }) => {
4571
- this._assertAvailableForRemoteAccess(requester || null);
4572
- if (typeof discoverable === "boolean") this.setDiscoverable(discoverable);
4573
- if (typeof busy === "boolean") {
4574
- if (busy) this.reserveFor(reservedBy || requester || "unknown");
4575
- else this.releaseReservation(requester || null);
4576
- }
4577
- return this.getSystemFlags();
4578
- });
4579
- this.commComponent.defineRpc("list-routes", async () => {
4580
- return this.commComponent.listRoutes();
4581
- });
4582
- this.commComponent.defineRpc("disconnect-route", async ({ routeId, requester, force = false }) => {
4583
- this._assertAvailableForRemoteAccess(requester || null);
4584
- this.commComponent.disconnectRoute(routeId, { requester, force });
4585
- return { ok: true, routeId };
4586
- });
4587
- this.commComponent.defineRpc("connect-to-target", async ({ sourceEmitter, targetAddress, targetCollector, targetName, requester, connectionPolicy = {} }) => {
4588
- this._assertAvailableForRemoteAccess(requester || null);
4589
- return await this.commComponent.wireViaWs(sourceEmitter, targetAddress, targetCollector, targetName, {
4590
- managedBy: connectionPolicy.managedBy || requester || this.entityName,
4591
- externallyMutable: connectionPolicy.externallyMutable !== false,
4592
- metadata: connectionPolicy.metadata || {}
4593
- });
4594
- });
4595
- }
4596
- _setupBaseFunctionalities() {
4597
- this.addLocal({
4598
- id: "heartbeat",
4599
- api: heartbeatApi(this),
4600
- emitters: { status: {} }
4601
- });
4602
- this.addLocal({
4603
- id: "getTelemetry",
4604
- api: telemetryApi(this)
4605
- });
4606
- this.addLocal({
4607
- id: "adminCommand",
4608
- api: adminCommandApi(this)
4609
- });
4610
- this.addLocal({
4611
- id: "discoverPeers",
4612
- api: discoverPeersApi(this)
4613
- });
4614
- this.addLocal({
4615
- id: "getManifest",
4616
- api: getManifestApi(this)
4617
- });
4618
- this.addLocal({
4619
- id: "getLastActionDocs",
4620
- api: getLastActionDocsApi(this)
4621
- });
4622
- this.addLocal({
4623
- id: "getFullDocumentation",
4624
- api: getFullDocumentationApi(this)
4625
- });
4626
- this.addLocal({
4627
- id: "getUsedPorts",
4628
- api: getUsedPortsApi(this)
4629
- });
4630
- this.addLocal({
4631
- id: "findFreePorts",
4632
- api: findFreePortsApi(this)
4633
- });
4634
- this.addLocal({
4635
- id: "shutdown",
4636
- description: "Gracefully shut down all owned microservices then self. Responds immediately; shutdown runs async.",
4637
- api: shutdownApi(this)
4638
- });
4639
- this.addLocal({
4640
- id: "getSiblingNetworkTopology",
4641
- description: "Returns the topology of the sibling peer network (for standalone KrnlTS apps only). Not related to sub-apps.",
4642
- api: getSiblingNetworkTopologyApi(this)
4643
- });
4644
- this.addLocal({
4645
- id: "getSubAppTopology",
4646
- description: "Returns a snapshot of all embedded sub-apps and their execution modes (local or worker).",
4647
- api: getSubAppTopologyApi(this)
4648
- });
4649
- this.addLocal({
4650
- id: "getEndpointDefinitions",
4651
- description: "Aggregates and returns the full definitions of all endpoints in the system.",
4652
- api: getEndpointDefinitionsApi(this)
4653
- });
4654
- this.addLocal({
4655
- id: "setEndpointDefinition",
4656
- description: "Sets and persists runtime config overrides for an endpoint.",
4657
- api: setEndpointDefinitionApi(this)
4658
- });
4659
- this.addLocal({
4660
- id: "getTelemetryLog",
4661
- description: "Retrieves historical telemetry traces from the persistent store.",
4662
- api: getTelemetryLogApi(this)
4663
- });
4664
- this.addLocal({
4665
- id: "getAikoCatalog",
4666
- description: "Retrieves the cached or live agent profiles catalog from Aiko.",
4667
- api: getAikoCatalogApi(this)
4668
- });
4669
- this.addLocal({
4670
- id: "ai",
4671
- description: "Natural language gateway \u2014 routes to correct endpoint agent via Aiko.",
4672
- api: aiOrchestrationApi(this)
4673
- });
4674
- this.addLocal({
4675
- id: "getTaskList",
4676
- description: "Retrieves current task list and status from the orchestrator.",
4677
- api: getTaskListApi(this)
4678
- });
4679
- }
4680
- isAikoAlive() {
4681
- const aikoPeer = this.peers.get("Aiko");
4682
- if (!aikoPeer) return false;
4683
- const TTL = 35e3;
4684
- return Date.now() - aikoPeer.lastSeen < TTL;
4685
- }
4686
- async initializeAiLayer(appRoot) {
4687
- try {
4688
- this._aiProfilesStore = new KrnlRuntimeStore(appRoot);
4689
- await this._aiProfilesStore.load();
4690
- import("./K_LIB_Krnl_Telemetry-77FRZ3KV.js").then(({ telemetry }) => {
4691
- if (typeof telemetry.setRuntimeStore === "function") {
4692
- telemetry.setRuntimeStore(this._aiProfilesStore);
4693
- }
4694
- }).catch(() => {
4695
- });
4696
- this._aikoClient = KrnlAikoClient.discover(this) || new KrnlAikoClient(10095);
4697
- const aikoActive = this.isAikoAlive() || await this._aikoClient.isAlive();
4698
- if (!aikoActive) {
4699
- console.warn(`[KrnlTS AI] ${KrnlAikoClient.getNotRunningMessage()}`);
4700
- } else {
4701
- try {
4702
- this._aikoCatalog = await this._aikoClient.fetchCatalog();
4703
- } catch (e) {
4704
- console.warn("[KrnlTS AI] Failed to fetch profile catalog from Aiko:", e);
4705
- }
4706
- }
4707
- this._aiTracker = new KrnlWatchVariablesTracker();
4708
- this._aiScheduler = new KrnlEndpointScheduler(this._aiTracker);
4709
- const overrides = await this._aiProfilesStore.getAllEndpointDefinitions();
4710
- const aiEndpoints = /* @__PURE__ */ new Map();
4711
- const { buildEndpointDefinition } = await import("./K_LIB_Krnl_System_Base_Functionality_APIs-ZZUZ6ZG5.js");
4712
- const { KrnlEpTools } = await import("./K_LIB_Krnl_Ep_Tools-ROOE2TQF.js");
4713
- for (const [fid, fn] of this.localFunctionalities.entries()) {
4714
- if (fid === "ai" || fid === "setEndpointDefinition" || fid === "getEndpointDefinitions" || fid === "getTelemetryLog" || fid === "getAikoCatalog") continue;
4715
- const override = overrides[fid] || null;
4716
- const isEnabled = override?.intelligenceSpec || fn.ai?.enabled || fn.ai;
4717
- if (!isEnabled) continue;
4718
- const mem = await this._aiProfilesStore.getEndpointMemory(fid);
4719
- const definition = buildEndpointDefinition(fn, this, override, mem);
4720
- this._aiTracker.register(fid, definition, fn);
4721
- const mergedTools = {};
4722
- if (definition.agentTools && Array.isArray(definition.agentTools)) {
4723
- const addAllBuiltins = definition.agentTools.includes("*");
4724
- if (addAllBuiltins) {
4725
- Object.assign(mergedTools, KrnlEpTools);
4726
- }
4727
- for (const toolId of definition.agentTools) {
4728
- if (toolId === "*") continue;
4729
- if (KrnlEpTools[toolId]) {
4730
- mergedTools[toolId] = KrnlEpTools[toolId];
4731
- } else if (this.localFunctionalities.has(toolId) || this.remoteFunctionalities.has(toolId)) {
4732
- mergedTools[toolId] = {
4733
- id: toolId,
4734
- description: `Calls the sibling endpoint '${toolId}'.`,
4735
- execute: async (payload) => {
4736
- return await this.call(toolId, payload, { unwrap: true });
4737
- }
4738
- };
4739
- }
4740
- }
4741
- }
4742
- const agent = new KrnlEndpointAgent(definition, this._aikoClient, this._aiTracker, this, mergedTools);
4743
- aiEndpoints.set(fid, agent);
4744
- }
4745
- const defaultRoutingSpec = {
4746
- reasoning: 5,
4747
- planning: 3,
4748
- toolUsage: 1,
4749
- structuredOutput: 5,
4750
- jsonStrictness: 5,
4751
- coding: 1,
4752
- extraction: 3,
4753
- classification: 8,
4754
- summarization: 2,
4755
- creativity: 1,
4756
- determinism: 7,
4757
- context: 4,
4758
- vision: 1,
4759
- multimodal: 1,
4760
- outputComplexity: 2
4761
- };
4762
- const defaultEscalationSpec = {
4763
- reasoning: 8,
4764
- planning: 6,
4765
- toolUsage: 2,
4766
- structuredOutput: 8,
4767
- jsonStrictness: 8,
4768
- coding: 2,
4769
- extraction: 5,
4770
- classification: 6,
4771
- summarization: 4,
4772
- creativity: 2,
4773
- determinism: 8,
4774
- context: 6,
4775
- vision: 2,
4776
- multimodal: 2,
4777
- outputComplexity: 6
4778
- };
4779
- const routingSpec = this._aiRoutingSpec || defaultRoutingSpec;
4780
- const escalationSpec = this._aiEscalationSpec || defaultEscalationSpec;
4781
- this._aiOrchestrator = new KrnlApplicationOrchestrator(
4782
- this,
4783
- this._aikoClient,
4784
- this._aiTracker,
4785
- this._aiScheduler,
4786
- routingSpec,
4787
- escalationSpec,
4788
- this._aiProfilesStore
4789
- );
4790
- for (const [fid, agent] of aiEndpoints.entries()) {
4791
- this._aiOrchestrator.registerAgent(fid, agent);
4792
- }
4793
- console.log(`[KrnlTS AI] Initialized: ${aiEndpoints.size} endpoint agents connected.`);
4794
- } catch (e) {
4795
- console.error("[KrnlTS AI] Failed to initialize AI Layer:", e.message);
4796
- }
4797
- }
4798
- _setupBaseInterface() {
4799
- this.interface.createEmitter("system-events");
4800
- this.interface.createCollector("system-commands");
4801
- this._attachCollectorHandler("system-commands", systemCommandsCollectorHandler(this));
4802
- }
4803
- _attachCollectorHandler(collectorName, handler) {
4804
- const collector = this.interface.getCollector(collectorName);
4805
- collector._directHandler = handler;
4806
- }
4807
- bindProcessSignals() {
4808
- if (typeof process === "undefined" || !process.on) return;
4809
- process.on("SIGINT", () => {
4810
- console.log(`
4811
- [${this.entityName}] SIGINT received.`);
4812
- this.gracefulShutdown().catch(() => process.exit(1));
4813
- });
4814
- process.on("SIGTERM", () => {
4815
- console.log(`
4816
- [${this.entityName}] SIGTERM received.`);
4817
- this.gracefulShutdown().catch(() => process.exit(1));
4818
- });
4819
- process.on("SIGHUP", () => {
4820
- console.log(`[${this.entityName}] SIGHUP received. Ignoring to maintain background persistence.`);
4821
- });
4822
- process.on("uncaughtException", (err) => {
4823
- Logger.error(`UNCAUGHT EXCEPTION in ${this.entityName}:`, err);
4824
- this.gracefulShutdown({ timeoutMs: 3e3 }).catch(() => process.exit(1));
4825
- });
4826
- process.on("unhandledRejection", (reason) => {
4827
- Logger.error(`UNHANDLED REJECTION in ${this.entityName}:`, reason);
4828
- this.gracefulShutdown({ timeoutMs: 3e3 }).catch(() => process.exit(1));
4829
- });
4830
- process.on("exit", (code) => {
4831
- console.log(`[${this.entityName}] Process exiting with code: ${code}`);
4832
- });
4833
- }
4834
- dispose() {
4835
- this._deletePortsFile();
4836
- if (this.beaconInterval) clearInterval(this.beaconInterval);
4837
- if (this.discoverySocket) this.discoverySocket.close();
4838
- for (const [name, handle] of this._managedServices) {
4839
- if (handle.processHandle && handle.status !== "stopped") {
4840
- Logger.log(`[${this.entityName}] Force killing managed service '${name}' (PID: ${handle.pid})...`);
4841
- handle.processHandle.kill("SIGKILL");
4842
- }
4843
- }
4844
- this._managedServices.clear();
4845
- for (const [name, suite] of this.serviceSuites) {
4846
- suite.stop();
4847
- }
4848
- this.serviceSuites.clear();
4849
- if (this._sharedServer) {
4850
- this._sharedServer.close();
4851
- this._sharedServer = null;
4852
- }
4853
- this.commComponent.dispose();
4854
- super.dispose();
4855
- }
4856
- };
4857
-
4858
- export {
4859
- krnl,
4860
- WebSocketTransportAdapter,
4861
- krnlSystemCommComponent,
4862
- KrnlSiblingNetwork,
4863
- KrnlIngressNetwork,
4864
- KrnlFrontendInspector,
4865
- KrnlFrontend,
4866
- KrnlBootBarrier,
4867
- KrnlWatchVariablesTracker,
4868
- KrnlEndpointScheduler,
4869
- KrnlTaskList,
4870
- KrnlTaskRunner,
4871
- KrnlPlannerAgent,
4872
- KrnlApplicationOrchestrator,
4873
- KrnlRuntimeStore,
4874
- KrnlEndpointAgent,
4875
- KrnlJobScheduler,
4876
- krnlSystemEntityBase
4877
- };