@holoscript/core 6.0.4 → 6.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (351) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +3 -3
  3. package/bin/holoscript.cjs +3 -0
  4. package/dist/GLTFPipeline-SFIORFJU.js +16 -0
  5. package/dist/GLTFPipeline-VNNDPONV.cjs +37 -0
  6. package/dist/{HoloScriptPlusParser-BN6KVRCM.js → HoloScriptPlusParser-7FBIFUFC.js} +6 -5
  7. package/dist/{HoloScriptPlusParser-NC5FE6AL.cjs → HoloScriptPlusParser-A2W7OCN2.cjs} +17 -16
  8. package/dist/HoloScriptPlusParser-F2Z56FJR.js +10 -0
  9. package/dist/HoloScriptPlusParser-WKHRIH6T.cjs +27 -0
  10. package/dist/{USDZExporter-UWGWNMMD.cjs → USDZExporter-3FWJ25JI.cjs} +344 -16
  11. package/dist/{USDZExporter-NTMBNTDB.js → USDZExporter-D2HQLQYK.js} +344 -16
  12. package/dist/agents/index.cjs +19 -0
  13. package/dist/agents/index.d.ts +100 -0
  14. package/dist/agents/index.js +17 -0
  15. package/dist/chunk-22W6NGYN.js +725 -0
  16. package/dist/{chunk-5OEOHAAW.cjs → chunk-27MPVJVZ.cjs} +64 -28
  17. package/dist/{chunk-RVYPEYPX.js → chunk-2A7FURVO.js} +44 -8
  18. package/dist/{chunk-XCWFGZAA.js → chunk-2B7WVIDZ.js} +11 -8
  19. package/dist/{chunk-NDQNIJEH.js → chunk-2BSMSUCE.js} +250 -24
  20. package/dist/chunk-2HLIGOKU.cjs +5546 -0
  21. package/dist/{chunk-EONILVMF.js → chunk-2M2DPHKB.js} +4 -4
  22. package/dist/{chunk-G7CT3EMP.cjs → chunk-2YSNA2F2.cjs} +319 -47
  23. package/dist/{chunk-IWI6J7FX.js → chunk-33XCOVE3.js} +5 -5
  24. package/dist/chunk-3FOKASKO.cjs +348 -0
  25. package/dist/{chunk-DXJQDCFL.js → chunk-4C57PR42.js} +3 -3
  26. package/dist/{chunk-MPXBVFHQ.js → chunk-4N4SXXWF.js} +4 -3
  27. package/dist/chunk-4PDEPEQW.cjs +41 -0
  28. package/dist/chunk-4R6HPSHJ.js +2176 -0
  29. package/dist/chunk-4R6SBXDB.js +45 -0
  30. package/dist/chunk-4SY77NA4.cjs +413 -0
  31. package/dist/{chunk-YCXFCXDS.js → chunk-4UUKPCY4.js} +668 -110
  32. package/dist/{chunk-LGGRPKTV.cjs → chunk-52ULD552.cjs} +114 -35
  33. package/dist/{chunk-L4G4RLXX.js → chunk-5CKA5SXU.js} +438 -22
  34. package/dist/chunk-5FSKKMR7.cjs +2092 -0
  35. package/dist/{chunk-FF3Q7ADR.js → chunk-5JEU52DW.js} +5 -3
  36. package/dist/chunk-5N54COB6.cjs +327 -0
  37. package/dist/chunk-5S7RKFGR.cjs +446 -0
  38. package/dist/{chunk-KED34ILP.js → chunk-6ASWLXXN.js} +21 -9
  39. package/dist/chunk-6CTRH7HT.cjs +1985 -0
  40. package/dist/{chunk-CAUCGUEA.cjs → chunk-6EX3I5P4.cjs} +6 -6
  41. package/dist/chunk-6FGQNDR4.js +5731 -0
  42. package/dist/{chunk-72EQECGT.cjs → chunk-6KMK2UXT.cjs} +122 -46
  43. package/dist/{chunk-G4VZTCIB.js → chunk-6L4VE27M.js} +33 -23
  44. package/dist/{chunk-ATSKSYVE.cjs → chunk-6S6TKNEA.cjs} +6478 -1738
  45. package/dist/chunk-77V4GTCA.js +596 -0
  46. package/dist/{chunk-ZP4D3CSX.cjs → chunk-7AD52FRS.cjs} +16 -16
  47. package/dist/chunk-A6KINLZJ.js +236 -0
  48. package/dist/chunk-AIA52I7T.cjs +543 -0
  49. package/dist/chunk-AIX25INK.cjs +602 -0
  50. package/dist/{chunk-B5TCIAPQ.cjs → chunk-AO4I2Z7M.cjs} +17 -18
  51. package/dist/{chunk-Q5SJOGHQ.cjs → chunk-BPICAGBV.cjs} +324 -199
  52. package/dist/chunk-BRQJKJGT.cjs +20 -0
  53. package/dist/{chunk-3FXV5S25.cjs → chunk-C37BHB7N.cjs} +6 -3
  54. package/dist/{chunk-XUTX5CBW.js → chunk-CBJY23VL.js} +3 -3
  55. package/dist/chunk-CIWWXYHZ.cjs +50 -0
  56. package/dist/{chunk-XXINBTZK.cjs → chunk-DIL6DDDN.cjs} +101 -45
  57. package/dist/chunk-DMXC24WV.js +404 -0
  58. package/dist/{chunk-PMGODDJA.cjs → chunk-DTGBOSEM.cjs} +12 -12
  59. package/dist/chunk-E7JP3BS3.cjs +61 -0
  60. package/dist/{chunk-HJJLD366.js → chunk-EKBKLK7P.js} +3 -3
  61. package/dist/chunk-EKYL4PE3.cjs +404 -0
  62. package/dist/{chunk-UPJBDCVF.js → chunk-EMMC5CSQ.js} +12 -8
  63. package/dist/{chunk-GGHSW2NN.js → chunk-EOBB6A4B.js} +6389 -1718
  64. package/dist/chunk-EOFNVCM6.js +325 -0
  65. package/dist/{chunk-FHQVYCH2.js → chunk-ER4GATIU.js} +7 -7
  66. package/dist/{chunk-N5FTS757.cjs → chunk-EXKSFGSX.cjs} +7 -148
  67. package/dist/{chunk-LK5IAVH6.cjs → chunk-EXUP2BUM.cjs} +27 -27
  68. package/dist/chunk-FDSGHPAK.js +130 -0
  69. package/dist/chunk-FEWUHQNM.cjs +144 -0
  70. package/dist/{chunk-5TOFIR6L.js → chunk-FGGJQRLZ.js} +5 -142
  71. package/dist/chunk-FHP6LXJS.js +415 -0
  72. package/dist/{chunk-7LCYLPW2.cjs → chunk-FJPADH77.cjs} +7 -4
  73. package/dist/{chunk-T36DDXSF.js → chunk-FXKTYFYA.js} +150 -25
  74. package/dist/chunk-G2LS3RFO.js +623 -0
  75. package/dist/chunk-GCMWDSBZ.cjs +729 -0
  76. package/dist/chunk-GJNCFRJU.cjs +125 -0
  77. package/dist/{chunk-Q4QX3AET.cjs → chunk-GMP623FG.cjs} +16 -13
  78. package/dist/{chunk-XD6IYDUX.js → chunk-GN3KDX4W.js} +119 -43
  79. package/dist/{chunk-QLEAOI3Q.cjs → chunk-GQYKQSTC.cjs} +10 -10
  80. package/dist/chunk-GTU2Z2WW.cjs +262 -0
  81. package/dist/chunk-GZG4KA4E.js +529 -0
  82. package/dist/{chunk-BND3ST2K.cjs → chunk-H3MGK7TX.cjs} +42 -32
  83. package/dist/{chunk-XRKWN5PL.cjs → chunk-H5DZIHJP.cjs} +14 -18
  84. package/dist/{chunk-Z34RLXRA.cjs → chunk-HANL7K2Q.cjs} +65 -50
  85. package/dist/{chunk-3SAK5KFL.cjs → chunk-HCCQLAA4.cjs} +2 -11
  86. package/dist/{chunk-LXJ4667L.cjs → chunk-HGVXZDSK.cjs} +108 -20
  87. package/dist/{chunk-3FJCK5XA.js → chunk-HRODTEEO.js} +30 -10
  88. package/dist/{chunk-HQUEA5R6.cjs → chunk-HZCQO4JM.cjs} +6 -6
  89. package/dist/{chunk-S565K7NK.js → chunk-I2O7TW6B.js} +12 -8
  90. package/dist/chunk-IHESJZSW.js +4490 -0
  91. package/dist/{chunk-FSF7EQVA.cjs → chunk-IRWWS72C.cjs} +63 -22
  92. package/dist/{chunk-5O6TQC6M.cjs → chunk-IVIA7K75.cjs} +689 -127
  93. package/dist/chunk-IVY74O6C.js +247 -0
  94. package/dist/chunk-J32ZJZJH.js +554 -0
  95. package/dist/chunk-J56PTA46.cjs +639 -0
  96. package/dist/chunk-JD7CIZ33.js +1949 -0
  97. package/dist/{chunk-T7LEXZUZ.cjs → chunk-JIYN45TV.cjs} +14 -15
  98. package/dist/{chunk-FFKU7BTK.cjs → chunk-KHPCJRI3.cjs} +24 -21
  99. package/dist/chunk-KKFZ3B6J.cjs +557 -0
  100. package/dist/chunk-KPJL34Y7.cjs +186 -0
  101. package/dist/{chunk-HE7ULERA.cjs → chunk-KQTPCYTG.cjs} +128 -44
  102. package/dist/{chunk-OFKWH2IP.js → chunk-KX76JUQY.js} +3 -3
  103. package/dist/{chunk-33LSUQDD.cjs → chunk-L63H3SQ4.cjs} +43 -31
  104. package/dist/{chunk-K6EKD26I.js → chunk-LAOCQJ2M.js} +64 -8
  105. package/dist/chunk-LM2VU56C.cjs +37 -0
  106. package/dist/chunk-M56JSP4A.js +400 -0
  107. package/dist/chunk-MBOOR7X4.js +18 -0
  108. package/dist/{chunk-XWPNTWDN.cjs → chunk-MJVIRCUV.cjs} +31 -27
  109. package/dist/{chunk-SDAMZIRE.js → chunk-MSMIFMBL.js} +135 -18
  110. package/dist/{chunk-56IF4NTA.js → chunk-MXFUTKCO.js} +18 -18
  111. package/dist/{chunk-6UEHYZ7V.cjs → chunk-MXJ5SS53.cjs} +447 -31
  112. package/dist/chunk-MYY4PMWX.cjs +264 -0
  113. package/dist/chunk-N75IH2HY.js +258 -0
  114. package/dist/{chunk-GVUR45UF.cjs → chunk-NG77ATEW.cjs} +7 -6
  115. package/dist/chunk-NW5G5FBQ.js +215 -0
  116. package/dist/{chunk-E3FWRT3Z.js → chunk-OEFY723R.js} +28 -13
  117. package/dist/chunk-OEV5RMZO.cjs +3042 -0
  118. package/dist/{chunk-X4ZF6CNE.cjs → chunk-OIQYIIO3.cjs} +7 -7
  119. package/dist/{chunk-2CWOLHTE.js → chunk-OL46QLBJ.js} +3 -11
  120. package/dist/chunk-OPZ7XDDI.js +487 -0
  121. package/dist/chunk-OSYNRVOV.cjs +243 -0
  122. package/dist/{chunk-TEWCN33Y.js → chunk-P7YIA5LN.js} +91 -7
  123. package/dist/chunk-PGANYCAG.cjs +220 -0
  124. package/dist/{chunk-CS2EMTGF.js → chunk-QAVXL2IH.js} +62 -21
  125. package/dist/{chunk-T4NKMBDL.js → chunk-QCCBXSCE.js} +1666 -756
  126. package/dist/{chunk-F4IULT7N.js → chunk-QPOQ7VPI.js} +16 -13
  127. package/dist/{chunk-6XSERL6L.js → chunk-QTPMJRGS.js} +3108 -2827
  128. package/dist/{chunk-F3HH56EB.cjs → chunk-QWNQ523V.cjs} +1730 -823
  129. package/dist/{chunk-R7MA7QWV.js → chunk-R3IVNY6P.js} +102 -23
  130. package/dist/chunk-R75BSDH7.cjs +50 -0
  131. package/dist/chunk-RAXUF5DF.cjs +2196 -0
  132. package/dist/{chunk-BF2235SI.cjs → chunk-RMHC2VG7.cjs} +2876 -2592
  133. package/dist/chunk-RUXGBKPS.cjs +4517 -0
  134. package/dist/{chunk-UERJ3YJV.js → chunk-S5IFXW6E.js} +113 -9
  135. package/dist/{chunk-27LWW5FU.cjs → chunk-S6YWHCKV.cjs} +5 -5
  136. package/dist/{chunk-WB4Z63GG.js → chunk-SIEXCILW.js} +3 -3
  137. package/dist/{chunk-CLYEIWA5.cjs → chunk-SLU6UPJI.cjs} +5 -3
  138. package/dist/{chunk-LZ266PCM.cjs → chunk-T5J7ZKP3.cjs} +446 -60
  139. package/dist/chunk-TDCNJHWO.js +341 -0
  140. package/dist/{chunk-IHOUYQIA.js → chunk-TG7O4WBC.js} +5 -5
  141. package/dist/chunk-THCK6ECW.js +2085 -0
  142. package/dist/chunk-TJHVSBP2.js +439 -0
  143. package/dist/chunk-TK74TR4H.js +5541 -0
  144. package/dist/{chunk-CDPGV4DN.js → chunk-U4NBQJBY.js} +14 -15
  145. package/dist/{chunk-NOZZ46QU.js → chunk-UD3DSHZM.js} +10 -14
  146. package/dist/chunk-UDMYRFDZ.js +3038 -0
  147. package/dist/{chunk-WDW67DZB.cjs → chunk-UOIGFQXC.cjs} +90 -68
  148. package/dist/{chunk-BU7VWW2K.js → chunk-URG2SJLK.js} +14 -15
  149. package/dist/{chunk-EQV4R3EV.cjs → chunk-V73NPPTM.cjs} +152 -35
  150. package/dist/chunk-VECQYRXL.js +474 -0
  151. package/dist/chunk-VEXPG4WN.js +1989 -0
  152. package/dist/{chunk-LDP5OK6G.js → chunk-VMLKSV26.js} +5 -5
  153. package/dist/{chunk-5BGSECRJ.cjs → chunk-VSK7W3O5.cjs} +47 -27
  154. package/dist/chunk-VVKVQZI6.js +55 -0
  155. package/dist/{chunk-YQK5JNFK.js → chunk-W55Z7QIX.js} +103 -15
  156. package/dist/{chunk-KSGXLT74.cjs → chunk-W6P2GBHH.cjs} +3 -3
  157. package/dist/{chunk-IBDG74G2.cjs → chunk-W6RW64BB.cjs} +7 -7
  158. package/dist/chunk-WDT3JTGM.cjs +483 -0
  159. package/dist/{chunk-HPS76H7Q.js → chunk-WKX5AMOY.js} +3 -3
  160. package/dist/chunk-WNNE3PO3.js +34 -0
  161. package/dist/{chunk-XG23EUQX.cjs → chunk-WRLUBRKS.cjs} +538 -312
  162. package/dist/{chunk-IFNQFCTM.js → chunk-WRNEH5MO.js} +79 -8
  163. package/dist/{chunk-54FHG2MX.js → chunk-WRWEX5ZF.js} +7 -4
  164. package/dist/{chunk-KCQ5NDYC.cjs → chunk-X3GJPRVK.cjs} +154 -80
  165. package/dist/{chunk-7AGYRWKW.cjs → chunk-XFXGA5IW.cjs} +126 -22
  166. package/dist/{chunk-TQSZUOW5.cjs → chunk-XHIV6326.cjs} +4 -4
  167. package/dist/chunk-XJAN7CZG.cjs +432 -0
  168. package/dist/chunk-XL6INWKT.js +121 -0
  169. package/dist/{chunk-E3UALNFA.js → chunk-XMWZG36H.js} +4 -4
  170. package/dist/{chunk-BKIGPPVM.js → chunk-XSFNHP2E.js} +6 -3
  171. package/dist/{chunk-H5Z7NASB.js → chunk-XT6JY5W5.js} +25 -3
  172. package/dist/chunk-XXZJEFKW.cjs +490 -0
  173. package/dist/chunk-Y3MWXQSB.cjs +5737 -0
  174. package/dist/chunk-YF2I3MV3.js +46 -0
  175. package/dist/{chunk-V3NN3HPP.js → chunk-YIMN575O.js} +437 -52
  176. package/dist/chunk-YIVFJNYV.js +176 -0
  177. package/dist/{chunk-MD6KDHVE.cjs → chunk-YKGPCZEE.cjs} +10 -10
  178. package/dist/chunk-YQELFNJV.js +39 -0
  179. package/dist/chunk-Z5XMPRNC.cjs +5390 -0
  180. package/dist/{chunk-3FYZOR7S.cjs → chunk-ZDSYWBIE.cjs} +18 -18
  181. package/dist/{chunk-6TZPZCOJ.cjs → chunk-ZKSS47EV.cjs} +24 -19
  182. package/dist/chunk-ZUL5AVTX.cjs +1993 -0
  183. package/dist/chunk-ZXBZVXDW.js +5386 -0
  184. package/dist/{chunk-DMG7C4H2.js → chunk-ZZ7RO2UQ.js} +312 -44
  185. package/dist/cli/holoscript-runner.cjs +200 -204
  186. package/dist/cli/holoscript-runner.js +144 -148
  187. package/dist/codebase/index.cjs +1 -1
  188. package/dist/codebase/index.js +1 -1
  189. package/dist/compiler/agent-inference.cjs +10 -7
  190. package/dist/compiler/agent-inference.js +6 -3
  191. package/dist/compiler/android-xr.cjs +12 -7
  192. package/dist/compiler/android-xr.js +10 -5
  193. package/dist/compiler/android.cjs +12 -8
  194. package/dist/compiler/android.js +10 -6
  195. package/dist/compiler/ar.cjs +9 -6
  196. package/dist/compiler/ar.js +7 -4
  197. package/dist/compiler/babylon.cjs +12 -8
  198. package/dist/compiler/babylon.js +11 -7
  199. package/dist/compiler/business-quest.cjs +43 -0
  200. package/dist/compiler/business-quest.js +4 -0
  201. package/dist/compiler/coco.cjs +1 -1
  202. package/dist/compiler/coco.js +1 -1
  203. package/dist/compiler/context.cjs +25 -0
  204. package/dist/compiler/context.d.ts +28 -0
  205. package/dist/compiler/context.js +8 -0
  206. package/dist/compiler/domain-block-utils.cjs +155 -152
  207. package/dist/compiler/domain-block-utils.js +7 -4
  208. package/dist/compiler/dtdl.cjs +10 -7
  209. package/dist/compiler/dtdl.js +7 -4
  210. package/dist/compiler/gltf-pipeline.cjs +9 -9
  211. package/dist/compiler/gltf-pipeline.js +2 -2
  212. package/dist/compiler/godot.cjs +9 -6
  213. package/dist/compiler/godot.js +8 -5
  214. package/dist/compiler/incremental.cjs +12 -7
  215. package/dist/compiler/incremental.js +7 -2
  216. package/dist/compiler/index.cjs +3550 -268
  217. package/dist/compiler/index.d.ts +404 -21
  218. package/dist/compiler/index.js +3280 -138
  219. package/dist/compiler/ios.cjs +11 -8
  220. package/dist/compiler/ios.js +9 -6
  221. package/dist/compiler/llm-provider-capabilities.cjs +25 -0
  222. package/dist/compiler/llm-provider-capabilities.d.ts +43 -0
  223. package/dist/compiler/llm-provider-capabilities.js +8 -0
  224. package/dist/compiler/multi-layer.cjs +14 -10
  225. package/dist/compiler/multi-layer.js +13 -9
  226. package/dist/compiler/nodetoy.cjs +5 -5
  227. package/dist/compiler/nodetoy.js +2 -2
  228. package/dist/compiler/openxr.cjs +10 -6
  229. package/dist/compiler/openxr.js +9 -5
  230. package/dist/compiler/playcanvas.cjs +10 -7
  231. package/dist/compiler/playcanvas.js +9 -6
  232. package/dist/compiler/r3f.cjs +17 -13
  233. package/dist/compiler/r3f.d.ts +22 -0
  234. package/dist/compiler/r3f.js +12 -8
  235. package/dist/compiler/remotion.cjs +1 -1
  236. package/dist/compiler/remotion.js +1 -1
  237. package/dist/compiler/reproducibility.cjs +1 -1
  238. package/dist/compiler/reproducibility.js +1 -1
  239. package/dist/compiler/sdf.cjs +10 -7
  240. package/dist/compiler/sdf.js +8 -5
  241. package/dist/compiler/semantic-scene.cjs +1 -1
  242. package/dist/compiler/semantic-scene.js +1 -1
  243. package/dist/compiler/state.cjs +9 -5
  244. package/dist/compiler/state.js +7 -3
  245. package/dist/compiler/trait-composition.cjs +11 -7
  246. package/dist/compiler/trait-composition.js +7 -3
  247. package/dist/compiler/unity.cjs +10 -6
  248. package/dist/compiler/unity.js +9 -5
  249. package/dist/compiler/unreal.cjs +11 -7
  250. package/dist/compiler/unreal.js +9 -5
  251. package/dist/compiler/urdf.cjs +20 -13
  252. package/dist/compiler/urdf.js +8 -5
  253. package/dist/compiler/usd-physics.cjs +10 -7
  254. package/dist/compiler/usd-physics.js +7 -4
  255. package/dist/compiler/visionos.cjs +10 -6
  256. package/dist/compiler/visionos.js +9 -5
  257. package/dist/compiler/vrchat.cjs +10 -7
  258. package/dist/compiler/vrchat.js +8 -5
  259. package/dist/compiler/vrr.cjs +10 -7
  260. package/dist/compiler/vrr.js +8 -5
  261. package/dist/compiler/wasm.cjs +13 -10
  262. package/dist/compiler/wasm.js +8 -5
  263. package/dist/compiler/webgpu.cjs +9 -6
  264. package/dist/compiler/webgpu.js +8 -5
  265. package/dist/constants.d.ts +3 -2
  266. package/dist/coordinators/index.cjs +1266 -0
  267. package/dist/coordinators/index.d.ts +260 -0
  268. package/dist/coordinators/index.js +1259 -0
  269. package/dist/debugger.cjs +9 -7
  270. package/dist/debugger.js +7 -5
  271. package/dist/entries/interop.cjs +23 -21
  272. package/dist/entries/interop.js +5 -3
  273. package/dist/entries/scripting.cjs +18 -18
  274. package/dist/entries/scripting.js +8 -8
  275. package/dist/hololand/index.cjs +146 -0
  276. package/dist/hololand/index.d.ts +70 -0
  277. package/dist/hololand/index.js +5 -0
  278. package/dist/index.cjs +20332 -18121
  279. package/dist/index.d.ts +1477 -40
  280. package/dist/index.js +19451 -17638
  281. package/dist/math/tropical-spmv.cjs +45 -0
  282. package/dist/math/tropical-spmv.js +4 -0
  283. package/dist/math/vec3.cjs +14 -14
  284. package/dist/math/vec3.js +2 -2
  285. package/dist/{ml-dsa-PHCWUBPX.cjs → ml-dsa-FSKBTE3W.cjs} +177 -90
  286. package/dist/{ml-dsa-WYLJHJO6.js → ml-dsa-Z7JDKW4L.js} +158 -71
  287. package/dist/paper-0c-spike/index.cjs +150 -0
  288. package/dist/paper-0c-spike/index.d.ts +29 -0
  289. package/dist/paper-0c-spike/index.js +141 -0
  290. package/dist/parser.cjs +45 -11
  291. package/dist/parser.d.ts +11 -0
  292. package/dist/parser.js +10 -8
  293. package/dist/{playwright-RL6GY4F7.cjs → playwright-3AT3AKTV.cjs} +1985 -1985
  294. package/dist/{playwright-5OSAPTNH.js → playwright-VZPDVUEQ.js} +3 -3
  295. package/dist/reconstruction/index.cjs +153 -0
  296. package/dist/reconstruction/index.d.ts +105 -0
  297. package/dist/reconstruction/index.js +8 -0
  298. package/dist/runtime.cjs +7 -5
  299. package/dist/runtime.js +6 -4
  300. package/dist/self-improvement/index.cjs +563 -0
  301. package/dist/self-improvement/index.js +545 -0
  302. package/dist/storage/index.cjs +10 -9
  303. package/dist/storage/index.js +3 -2
  304. package/dist/testing.cjs +25 -0
  305. package/dist/testing.d.ts +70 -0
  306. package/dist/testing.js +4 -0
  307. package/dist/tools/index.d.ts +22 -1
  308. package/dist/traitDocs/traitDocs.cjs +33 -0
  309. package/dist/traitDocs/traitDocs.d.ts +69 -0
  310. package/dist/traitDocs/traitDocs.js +7 -0
  311. package/dist/traits/botanical-lotus.cjs +41 -0
  312. package/dist/traits/botanical-lotus.d.ts +172 -0
  313. package/dist/traits/botanical-lotus.js +4 -0
  314. package/dist/traits/engines/index.cjs +520 -0
  315. package/dist/traits/engines/index.js +380 -0
  316. package/dist/traits/index.cjs +17630 -7881
  317. package/dist/traits/index.d.ts +197 -0
  318. package/dist/traits/index.js +16573 -7193
  319. package/dist/traits/simulation-solver-factory.cjs +13 -0
  320. package/dist/traits/simulation-solver-factory.d.ts +23 -0
  321. package/dist/traits/simulation-solver-factory.js +4 -0
  322. package/dist/traits/webcam-gaze.cjs +35 -0
  323. package/dist/traits/webcam-gaze.d.ts +17 -0
  324. package/dist/traits/webcam-gaze.js +4 -0
  325. package/dist/type-checker.cjs +6 -5
  326. package/dist/type-checker.js +4 -3
  327. package/dist/world/index.cjs +947 -0
  328. package/dist/world/index.d.ts +147 -0
  329. package/dist/world/index.js +939 -0
  330. package/dist/world-model/index.cjs +1446 -0
  331. package/dist/world-model/index.d.ts +119 -0
  332. package/dist/world-model/index.js +1414 -0
  333. package/dist/wot/index.cjs +29 -0
  334. package/dist/wot/index.js +4 -0
  335. package/package.json +153 -61
  336. package/dist/GLTFPipeline-DEN36VNK.js +0 -12
  337. package/dist/GLTFPipeline-YPCAK236.cjs +0 -33
  338. package/dist/chunk-4XSNJCLC.cjs +0 -1859
  339. package/dist/chunk-A7PIMZGU.js +0 -263
  340. package/dist/chunk-BWFJEM5A.js +0 -5419
  341. package/dist/chunk-CBJSLA2E.cjs +0 -5423
  342. package/dist/chunk-K3JDKWGI.cjs +0 -270
  343. package/dist/chunk-LSW7P7ML.js +0 -3675
  344. package/dist/chunk-MEASWI2Y.js +0 -126
  345. package/dist/chunk-NCUKG4SK.cjs +0 -3075
  346. package/dist/chunk-Q5JT3YML.cjs +0 -129
  347. package/dist/chunk-QGKNANZ3.js +0 -3071
  348. package/dist/chunk-S2N5TNMA.js +0 -1855
  349. package/dist/chunk-TSH3MSQU.cjs +0 -129
  350. package/dist/chunk-WGMEAYBG.js +0 -126
  351. package/dist/chunk-X6SEAXAX.cjs +0 -3681
@@ -0,0 +1,4490 @@
1
+ import { HoloScriptCodeParser } from './chunk-URG2SJLK.js';
2
+ import { ReactiveState, ExpressionEvaluator, createState } from './chunk-XL6INWKT.js';
3
+ import { JEPAPredictor, jepObjectiveHandler, mitosisHandler, orbitalHandler } from './chunk-77V4GTCA.js';
4
+ import { logger } from './chunk-PHENW4MQ.js';
5
+ import { init_safeJsonParse, readJson } from './chunk-VVKVQZI6.js';
6
+ import { WebSocketServer, WebSocket } from 'ws';
7
+ import { AttentionEngine, TimeManager } from '@holoscript/engine/orbital';
8
+ import { StateSynchronizer } from '@holoscript/mesh';
9
+ import * as engineRuntime from '@holoscript/engine/runtime';
10
+ import { MemoryConsolidator } from '@holoscript/framework/learning';
11
+
12
+ // src/HoloScriptRuntime.ts
13
+ init_safeJsonParse();
14
+
15
+ // src/runtime/physics-math.ts
16
+ var GRAVITY = 9.81;
17
+ var ARC_MIN_DISTANCE = 0.1;
18
+ function calculateArc(start, end, speed) {
19
+ const dx = end[0] - start[0];
20
+ const dz = end[2] - start[2];
21
+ const dy = end[1] - start[1];
22
+ const dist = Math.sqrt(dx * dx + dz * dz);
23
+ if (dist < ARC_MIN_DISTANCE) return [0, speed, 0];
24
+ const t = dist / speed;
25
+ const vx = dx / t;
26
+ const vz = dz / t;
27
+ const vy = dy / t + 0.5 * GRAVITY * t;
28
+ return [vx, vy, vz];
29
+ }
30
+
31
+ // src/runtime/condition-evaluator.ts
32
+ var SUSPICIOUS_KEYWORDS = [
33
+ "eval",
34
+ "process",
35
+ "require",
36
+ "__proto__",
37
+ "constructor"
38
+ ];
39
+ function evaluateCondition(condition, evaluate) {
40
+ if (!condition) return false;
41
+ const condStr = String(condition);
42
+ if (SUSPICIOUS_KEYWORDS.some((kw) => condStr.toLowerCase().includes(kw))) {
43
+ logger.warn("Suspicious condition blocked", { condition });
44
+ return false;
45
+ }
46
+ try {
47
+ if (condStr.trim().toLowerCase() === "true") return true;
48
+ if (condStr.trim().toLowerCase() === "false") return false;
49
+ const comparisonPatterns = [
50
+ { regex: /^(.+?)\s*(===|!==)\s*(.+)$/ },
51
+ { regex: /^(.+?)\s*(==|!=|>=|<=|>|<)\s*(.+)$/ },
52
+ { regex: /^(.+?)\s*(&&)\s*(.+)$/, logical: "and" },
53
+ { regex: /^(.+?)\s*(\|\|)\s*(.+)$/, logical: "or" }
54
+ ];
55
+ for (const { regex, logical } of comparisonPatterns) {
56
+ const match = condStr.match(regex);
57
+ if (match) {
58
+ const [, leftExpr, operator, rightExpr] = match;
59
+ const left = evaluate(leftExpr.trim());
60
+ const right = evaluate(rightExpr.trim());
61
+ if (logical === "and") return Boolean(left) && Boolean(right);
62
+ if (logical === "or") return Boolean(left) || Boolean(right);
63
+ switch (operator) {
64
+ case "===":
65
+ return left === right;
66
+ case "!==":
67
+ return left !== right;
68
+ case "==":
69
+ return left == right;
70
+ case "!=":
71
+ return left != right;
72
+ case ">=":
73
+ return Number(left) >= Number(right);
74
+ case "<=":
75
+ return Number(left) <= Number(right);
76
+ case ">":
77
+ return Number(left) > Number(right);
78
+ case "<":
79
+ return Number(left) < Number(right);
80
+ }
81
+ }
82
+ }
83
+ if (condStr.startsWith("!")) {
84
+ return !evaluateCondition(condStr.slice(1).trim(), evaluate);
85
+ }
86
+ const value = evaluate(condStr.trim());
87
+ return Boolean(value);
88
+ } catch (error) {
89
+ logger.error("Condition evaluation error", { condition, error });
90
+ return false;
91
+ }
92
+ }
93
+
94
+ // src/runtime/particle-effects.ts
95
+ var DATA_TYPE_COLORS = {
96
+ string: "#ff6b35",
97
+ number: "#4ecdc4",
98
+ boolean: "#45b7d1",
99
+ object: "#96ceb4",
100
+ array: "#ffeaa7",
101
+ any: "#dda0dd",
102
+ move: "#ff69b4"
103
+ };
104
+ var DEFAULT_DATA_TYPE_COLOR = "#ffffff";
105
+ var CONNECTION_STREAM_STEPS = 20;
106
+ var FLOW_STREAM_MAX_COUNT = 50;
107
+ var DATAVIZ_ARRAY_MAX = 100;
108
+ var DATAVIZ_OBJECT_MAX = 50;
109
+ var DATAVIZ_OBJECT_KEY_MULT = 5;
110
+ var FLOW_STREAM_DEFAULT_COUNT = 10;
111
+ var DATAVIZ_DEFAULT_COUNT = 10;
112
+ var EXECUTION_EFFECT_COUNT = 30;
113
+ var CONNECTION_STREAM_LIFETIME_MS = 5e3;
114
+ var PARTICLE_DEFAULT_LIFETIME_MS = 3e3;
115
+ var PARTICLE_DEFAULT_SPEED = 0.01;
116
+ var CONNECTION_STREAM_SPEED = 0.02;
117
+ var FLOW_STREAM_COLOR = "#45b7d1";
118
+ var EXECUTION_EFFECT_COLOR = "#ff4500";
119
+ var DATAVIZ_COLOR = "#32cd32";
120
+ function getDataTypeColor(dataType) {
121
+ return DATA_TYPE_COLORS[dataType] ?? DEFAULT_DATA_TYPE_COLOR;
122
+ }
123
+ function createParticleEffect(particleSystems, name, position, color, count, maxParticlesPerSystem) {
124
+ const limitedCount = Math.min(count, maxParticlesPerSystem);
125
+ const particles = [];
126
+ for (let i = 0; i < limitedCount; i++) {
127
+ particles.push([
128
+ position[0] + (Math.random() - 0.5) * 2,
129
+ position[1] + (Math.random() - 0.5) * 2,
130
+ position[2] + (Math.random() - 0.5) * 2
131
+ ]);
132
+ }
133
+ particleSystems.set(name, {
134
+ particles,
135
+ color,
136
+ lifetime: PARTICLE_DEFAULT_LIFETIME_MS,
137
+ speed: PARTICLE_DEFAULT_SPEED
138
+ });
139
+ }
140
+ function createConnectionStream(particleSystems, from, to, fromPos, toPos, dataType) {
141
+ const streamName = `connection_${from}_${to}`;
142
+ const particles = [];
143
+ for (let i = 0; i <= CONNECTION_STREAM_STEPS; i++) {
144
+ const t = i / CONNECTION_STREAM_STEPS;
145
+ particles.push([
146
+ fromPos[0] + (toPos[0] - fromPos[0]) * t,
147
+ fromPos[1] + (toPos[1] - fromPos[1]) * t,
148
+ fromPos[2] + (toPos[2] - fromPos[2]) * t
149
+ ]);
150
+ }
151
+ particleSystems.set(streamName, {
152
+ particles,
153
+ color: getDataTypeColor(dataType),
154
+ lifetime: CONNECTION_STREAM_LIFETIME_MS,
155
+ speed: CONNECTION_STREAM_SPEED
156
+ });
157
+ }
158
+ function createFlowingStream(particleSystems, name, position, data, maxParticlesPerSystem) {
159
+ const count = Array.isArray(data) ? Math.min(data.length, FLOW_STREAM_MAX_COUNT) : FLOW_STREAM_DEFAULT_COUNT;
160
+ createParticleEffect(
161
+ particleSystems,
162
+ `${name}_flow`,
163
+ position,
164
+ FLOW_STREAM_COLOR,
165
+ count,
166
+ maxParticlesPerSystem
167
+ );
168
+ }
169
+ function createExecutionEffect(particleSystems, name, position, maxParticlesPerSystem) {
170
+ createParticleEffect(
171
+ particleSystems,
172
+ `${name}_execution`,
173
+ position,
174
+ EXECUTION_EFFECT_COLOR,
175
+ EXECUTION_EFFECT_COUNT,
176
+ maxParticlesPerSystem
177
+ );
178
+ }
179
+ function updateParticles(particleSystems, deltaTime) {
180
+ for (const [name, system] of particleSystems) {
181
+ system.lifetime -= deltaTime;
182
+ system.particles.forEach((particle) => {
183
+ particle[0] += (Math.random() - 0.5) * system.speed;
184
+ particle[1] += (Math.random() - 0.5) * system.speed;
185
+ particle[2] += (Math.random() - 0.5) * system.speed;
186
+ });
187
+ if (system.lifetime <= 0) {
188
+ particleSystems.delete(name);
189
+ }
190
+ }
191
+ }
192
+ function createDataVisualization(particleSystems, name, data, position, maxParticlesPerSystem) {
193
+ let count = DATAVIZ_DEFAULT_COUNT;
194
+ if (Array.isArray(data)) {
195
+ count = Math.min(data.length, DATAVIZ_ARRAY_MAX);
196
+ } else if (typeof data === "object" && data !== null) {
197
+ count = Math.min(Object.keys(data).length * DATAVIZ_OBJECT_KEY_MULT, DATAVIZ_OBJECT_MAX);
198
+ }
199
+ createParticleEffect(
200
+ particleSystems,
201
+ `${name}_visualization`,
202
+ position,
203
+ DATAVIZ_COLOR,
204
+ count,
205
+ maxParticlesPerSystem
206
+ );
207
+ }
208
+
209
+ // src/runtime/transformation.ts
210
+ var TAKE_DEFAULT_COUNT = 10;
211
+ async function applyTransformation(data, transform, ctx) {
212
+ const params = transform.parameters || {};
213
+ switch (transform.operation) {
214
+ case "filter": {
215
+ if (!Array.isArray(data)) return data;
216
+ const predicate = params.predicate;
217
+ if (predicate) {
218
+ return data.filter((item) => {
219
+ ctx.setVariable("_item", item);
220
+ return ctx.evaluateCondition(predicate);
221
+ });
222
+ }
223
+ return data.filter((item) => item !== null && item !== void 0);
224
+ }
225
+ case "map": {
226
+ if (!Array.isArray(data)) return data;
227
+ const mapper = params.mapper;
228
+ if (mapper) {
229
+ return data.map((item) => {
230
+ ctx.setVariable("_item", item);
231
+ return ctx.evaluateExpression(mapper);
232
+ });
233
+ }
234
+ return data.map((item) => ({ value: item, processed: true }));
235
+ }
236
+ case "reduce": {
237
+ if (!Array.isArray(data)) return data;
238
+ const initial = params.initial ?? 0;
239
+ const reducer = params.reducer;
240
+ if (reducer) {
241
+ return data.reduce((acc, item) => {
242
+ ctx.setVariable("_acc", acc);
243
+ ctx.setVariable("_item", item);
244
+ return ctx.evaluateExpression(reducer);
245
+ }, initial);
246
+ }
247
+ return data.reduce((acc, item) => acc + (typeof item === "number" ? item : 0), 0);
248
+ }
249
+ case "sort": {
250
+ if (!Array.isArray(data)) return data;
251
+ const key = params.key;
252
+ const desc = params.descending;
253
+ const sorted = [...data].sort((a, b) => {
254
+ const aVal = key ? a[key] : a;
255
+ const bVal = key ? b[key] : b;
256
+ if (aVal < bVal) return desc ? 1 : -1;
257
+ if (aVal > bVal) return desc ? -1 : 1;
258
+ return 0;
259
+ });
260
+ return sorted;
261
+ }
262
+ case "sum":
263
+ return Array.isArray(data) ? data.reduce((sum, item) => sum + (typeof item === "number" ? item : 0), 0) : data;
264
+ case "count":
265
+ return Array.isArray(data) ? data.length : 1;
266
+ case "unique":
267
+ return Array.isArray(data) ? Array.from(new Set(data)) : data;
268
+ case "flatten":
269
+ return Array.isArray(data) ? data.flat() : data;
270
+ case "reverse":
271
+ return Array.isArray(data) ? [...data].reverse() : data;
272
+ case "take": {
273
+ if (!Array.isArray(data)) return data;
274
+ const count = Number(params.count) || TAKE_DEFAULT_COUNT;
275
+ return data.slice(0, count);
276
+ }
277
+ case "skip": {
278
+ if (!Array.isArray(data)) return data;
279
+ const count = Number(params.count) || 0;
280
+ return data.slice(count);
281
+ }
282
+ default:
283
+ logger.warn("Unknown transformation", { operation: transform.operation });
284
+ return data;
285
+ }
286
+ }
287
+
288
+ // src/runtime/easing.ts
289
+ function applyEasing(t, easing) {
290
+ switch (easing) {
291
+ case "easeIn":
292
+ return t * t;
293
+ case "easeOut":
294
+ return t * (2 - t);
295
+ case "easeInOut":
296
+ return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
297
+ case "easeInQuad":
298
+ return t * t;
299
+ case "easeOutQuad":
300
+ return t * (2 - t);
301
+ case "easeInOutQuad":
302
+ return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
303
+ case "linear":
304
+ default:
305
+ return t;
306
+ }
307
+ }
308
+
309
+ // src/runtime/animation-system.ts
310
+ function updateAnimations(animations, setVariable, now) {
311
+ for (const [key, anim] of animations) {
312
+ const elapsed = now - anim.startTime;
313
+ let progress = Math.min(elapsed / anim.duration, 1);
314
+ progress = applyEasing(progress, anim.easing);
315
+ const currentValue = anim.from + (anim.to - anim.from) * progress;
316
+ if (anim.yoyo && progress >= 1) {
317
+ anim.startTime = now;
318
+ [anim.from, anim.to] = [anim.to, anim.from];
319
+ }
320
+ setVariable(`${anim.target}.${anim.property}`, currentValue);
321
+ if (progress >= 1 && !anim.loop && !anim.yoyo) {
322
+ animations.delete(key);
323
+ } else if (progress >= 1 && anim.loop) {
324
+ anim.startTime = now;
325
+ }
326
+ }
327
+ }
328
+ function broadcast(wss, type, payload) {
329
+ if (!wss) return;
330
+ const message = JSON.stringify({ type, payload });
331
+ wss.clients.forEach((client) => {
332
+ if (client.readyState === WebSocket.OPEN) {
333
+ client.send(message);
334
+ }
335
+ });
336
+ }
337
+ function handleTimeControl(timeManager, command, value) {
338
+ if (!timeManager) return;
339
+ switch (command) {
340
+ case "play":
341
+ timeManager.play();
342
+ break;
343
+ case "pause":
344
+ timeManager.pause();
345
+ break;
346
+ case "toggle":
347
+ timeManager.togglePause();
348
+ break;
349
+ case "setSpeed":
350
+ if (typeof value === "number") {
351
+ timeManager.setTimeScale(value);
352
+ }
353
+ break;
354
+ case "setDate":
355
+ if (value) {
356
+ timeManager.setDate(new Date(value));
357
+ }
358
+ break;
359
+ case "syncRealTime":
360
+ timeManager.setDate(/* @__PURE__ */ new Date());
361
+ timeManager.setTimeScale(1);
362
+ timeManager.play();
363
+ break;
364
+ }
365
+ }
366
+
367
+ // src/runtime/holo-statement-executor.ts
368
+ var MAX_ITERATIONS = 1e3;
369
+ async function executeHoloProgram(statements, scopeOverride, ctx) {
370
+ const results = [];
371
+ ctx.telemetry.setGauge("execution_depth", ctx.telemetry.executionDepth());
372
+ for (const stmt of statements) {
373
+ ctx.telemetry.incrementCounter("statements_executed", 1, { type: stmt.type });
374
+ const res = await ctx.telemetry.measureLatency(
375
+ `execute_stmt_${stmt.type}`,
376
+ () => executeHoloStatement(stmt, scopeOverride, ctx)
377
+ );
378
+ results.push(res);
379
+ const last = results[results.length - 1];
380
+ if (last.success && last.output !== void 0 && stmt.type === "ReturnStatement") {
381
+ break;
382
+ }
383
+ }
384
+ return results;
385
+ }
386
+ async function executeHoloStatement(stmt, scopeOverride, ctx) {
387
+ try {
388
+ switch (stmt.type) {
389
+ case "Assignment": {
390
+ const value = await ctx.evaluateHoloExpression(stmt.value, scopeOverride);
391
+ let finalValue = value;
392
+ if (stmt.operator !== "=") {
393
+ const current = ctx.getVariable(stmt.target, scopeOverride);
394
+ if (stmt.operator === "+=")
395
+ finalValue = Number(current) + Number(value);
396
+ else if (stmt.operator === "-=")
397
+ finalValue = Number(current) - Number(value);
398
+ else if (stmt.operator === "*=")
399
+ finalValue = Number(current) * Number(value);
400
+ else if (stmt.operator === "/=")
401
+ finalValue = Number(current) / Number(value);
402
+ }
403
+ ctx.setVariable(stmt.target, finalValue, scopeOverride);
404
+ return { success: true };
405
+ }
406
+ case "IfStatement": {
407
+ const condition = await ctx.evaluateHoloExpression(stmt.condition, scopeOverride);
408
+ if (condition) {
409
+ await executeHoloProgram(stmt.consequent, scopeOverride, ctx);
410
+ } else if (stmt.alternate) {
411
+ await executeHoloProgram(stmt.alternate, scopeOverride, ctx);
412
+ }
413
+ return { success: true };
414
+ }
415
+ case "WhileStatement": {
416
+ let iter = 0;
417
+ while (await ctx.evaluateHoloExpression(stmt.condition, scopeOverride)) {
418
+ if (iter++ > MAX_ITERATIONS) return { success: false, error: "Infinite loop" };
419
+ await executeHoloProgram(stmt.body, scopeOverride, ctx);
420
+ }
421
+ return { success: true };
422
+ }
423
+ case "ClassicForStatement": {
424
+ if (stmt.init) await executeHoloStatement(stmt.init, scopeOverride, ctx);
425
+ let iter = 0;
426
+ while (!stmt.test || await ctx.evaluateHoloExpression(stmt.test, scopeOverride)) {
427
+ if (iter++ > MAX_ITERATIONS) return { success: false, error: "Infinite loop" };
428
+ await executeHoloProgram(stmt.body, scopeOverride, ctx);
429
+ if (stmt.update) await executeHoloStatement(stmt.update, scopeOverride, ctx);
430
+ }
431
+ return { success: true };
432
+ }
433
+ case "VariableDeclaration": {
434
+ const value = stmt.value ? await ctx.evaluateHoloExpression(stmt.value, scopeOverride) : void 0;
435
+ const scope = scopeOverride || ctx.currentScope;
436
+ scope.variables.set(stmt.name, value);
437
+ return { success: true };
438
+ }
439
+ case "EmitStatement": {
440
+ const data = stmt.data ? await ctx.evaluateHoloExpression(stmt.data, scopeOverride) : void 0;
441
+ ctx.emit(stmt.event, data);
442
+ return { success: true };
443
+ }
444
+ case "AwaitStatement": {
445
+ const value = await ctx.evaluateHoloExpression(stmt.expression, scopeOverride);
446
+ if (value instanceof Promise) await value;
447
+ return { success: true };
448
+ }
449
+ case "ReturnStatement": {
450
+ const value = stmt.value ? await ctx.evaluateHoloExpression(stmt.value, scopeOverride) : null;
451
+ return { success: true, output: value };
452
+ }
453
+ case "ExpressionStatement": {
454
+ const val = await ctx.evaluateHoloExpression(stmt.expression, scopeOverride);
455
+ return { success: true, output: val };
456
+ }
457
+ default:
458
+ return {
459
+ success: false,
460
+ error: `Unknown stmt type: ${stmt.type}`
461
+ };
462
+ }
463
+ } catch (err) {
464
+ const errMsg = err instanceof Error ? err.message : String(err);
465
+ console.error(`[EXEC_ERROR] Statement ${stmt.type} failed:`, errMsg);
466
+ return { success: false, error: errMsg };
467
+ }
468
+ }
469
+
470
+ // src/runtime/debug-executor.ts
471
+ var DEBUG_HOLOGRAM = {
472
+ shape: "pyramid",
473
+ color: "#ff1493",
474
+ size: 0.8,
475
+ glow: true,
476
+ interactive: true
477
+ };
478
+ async function executeDebug(node, ctx) {
479
+ const debugInfo = {
480
+ variables: Object.fromEntries(ctx.scopeVariables),
481
+ contextVariables: Object.fromEntries(ctx.contextVariables),
482
+ functions: Array.from(ctx.functions.keys()),
483
+ connections: ctx.connections.length,
484
+ callStack: [...ctx.callStack],
485
+ uiElements: Array.from(ctx.uiElements.keys()),
486
+ animations: Array.from(ctx.animations.keys()),
487
+ executionHistory: ctx.executionHistory.slice(-10)
488
+ };
489
+ const debugOrb = { ...DEBUG_HOLOGRAM };
490
+ ctx.setHologramState(`debug_${node.target || "program"}`, debugOrb);
491
+ ctx.logInfo("Debug info", debugInfo);
492
+ return {
493
+ success: true,
494
+ output: debugInfo,
495
+ hologram: debugOrb
496
+ };
497
+ }
498
+
499
+ // src/runtime/io-node-executors.ts
500
+ async function executeServerNode(node, ctx) {
501
+ if (ctx.isPublicMode) {
502
+ return {
503
+ success: false,
504
+ error: "SecurityViolation: Server creation blocked in public mode.",
505
+ executionTime: 0
506
+ };
507
+ }
508
+ ctx.logInfo(`Starting server on port ${node.port}`);
509
+ return {
510
+ success: true,
511
+ output: `Server listening on port ${node.port}`,
512
+ hologram: node.hologram,
513
+ executionTime: 0
514
+ };
515
+ }
516
+ async function executeDatabaseNode(node, ctx) {
517
+ if (ctx.isPublicMode) {
518
+ return {
519
+ success: false,
520
+ error: "SecurityViolation: DB access blocked in public mode.",
521
+ executionTime: 0
522
+ };
523
+ }
524
+ ctx.logInfo(`Executing Query: ${node.query}`);
525
+ return {
526
+ success: true,
527
+ output: `Query executed: ${node.query}`,
528
+ hologram: node.hologram,
529
+ executionTime: 0
530
+ };
531
+ }
532
+ async function executeFetchNode(node, ctx) {
533
+ if (ctx.isPublicMode) {
534
+ return {
535
+ success: false,
536
+ error: "SecurityViolation: External fetch blocked in public mode.",
537
+ executionTime: 0
538
+ };
539
+ }
540
+ ctx.logInfo(`Fetching: ${node.url}`);
541
+ return {
542
+ success: true,
543
+ output: `Fetched data from ${node.url}`,
544
+ hologram: node.hologram,
545
+ executionTime: 0
546
+ };
547
+ }
548
+
549
+ // src/runtime/declaration-executors.ts
550
+ async function executeStateDeclaration(node, ctx) {
551
+ const stateDirective = node.directives?.find((d) => d.type === "state");
552
+ if (stateDirective) {
553
+ ctx.updateState(stateDirective.body);
554
+ }
555
+ return { success: true, output: "State updated" };
556
+ }
557
+ async function executeMemoryDefinition(node, ctx) {
558
+ const startTime = Date.now();
559
+ const config = {};
560
+ for (const [key, val] of Object.entries(node.properties || {})) {
561
+ if (typeof val === "string") {
562
+ config[key] = ctx.evaluateExpression(val);
563
+ } else {
564
+ config[key] = val;
565
+ }
566
+ }
567
+ return {
568
+ success: true,
569
+ output: {
570
+ type: node.type,
571
+ config
572
+ },
573
+ executionTime: Date.now() - startTime
574
+ };
575
+ }
576
+
577
+ // src/runtime/orb-executor.ts
578
+ function isOrbData(v) {
579
+ return v !== null && typeof v === "object" && v.__type === "orb";
580
+ }
581
+ var DEFAULT_HOLOGRAM_COLOR = "#ffffff";
582
+ var DEFAULT_HOLOGRAM_SIZE = 1;
583
+ var DEFAULT_HOLOGRAM_SHAPE = "sphere";
584
+ var CREATION_PUFF_COLOR = "#00ffff";
585
+ var CREATION_PUFF_COUNT = 20;
586
+ function normalizePosition(position) {
587
+ if (!position) return [0, 0, 0];
588
+ if (Array.isArray(position)) {
589
+ return [
590
+ Number(position[0]) || 0,
591
+ Number(position[1]) || 0,
592
+ Number(position[2]) || 0
593
+ ];
594
+ }
595
+ const p = position;
596
+ return [Number(p[0]) || 0, Number(p[1]) || 0, Number(p[2]) || 0];
597
+ }
598
+ async function executeOrb(node, ctx) {
599
+ const scale = ctx.getCurrentScale() || 1;
600
+ const existingRaw = ctx.getVariable(node.name);
601
+ const existingOrb = isOrbData(existingRaw) ? existingRaw : void 0;
602
+ const isUpdate = !!existingOrb;
603
+ const pos = normalizePosition(node.position);
604
+ const adjustedPos = [pos[0] * scale, pos[1] * scale, pos[2] * scale];
605
+ if (node.position) {
606
+ ctx.setSpatialPosition(node.name, adjustedPos);
607
+ }
608
+ const evaluatedProperties = {};
609
+ if (Array.isArray(node.properties)) {
610
+ for (const prop of node.properties) {
611
+ const val = prop.value;
612
+ evaluatedProperties[prop.key] = typeof val === "string" ? ctx.evaluateExpression(val) : val;
613
+ }
614
+ } else if (node.properties) {
615
+ for (const [key, val] of Object.entries(node.properties)) {
616
+ evaluatedProperties[key] = typeof val === "string" ? ctx.evaluateExpression(val) : val;
617
+ }
618
+ }
619
+ const orbNodeExt = node;
620
+ if (orbNodeExt.template) {
621
+ const tpl = ctx.getTemplate(orbNodeExt.template);
622
+ if (tpl) {
623
+ if (tpl.properties) {
624
+ for (const [key, val] of Object.entries(tpl.properties)) {
625
+ if (evaluatedProperties[key] === void 0) {
626
+ evaluatedProperties[key] = typeof val === "string" ? ctx.evaluateExpression(val) : val;
627
+ }
628
+ }
629
+ }
630
+ if (tpl.directives) {
631
+ const existingDirectives = node.directives || [];
632
+ node.directives = [...tpl.directives, ...existingDirectives];
633
+ }
634
+ }
635
+ }
636
+ const hologram = node.hologram ? {
637
+ ...node.hologram,
638
+ size: (node.hologram.size || Number(evaluatedProperties.size) || Number(evaluatedProperties.scale) || DEFAULT_HOLOGRAM_SIZE) * scale
639
+ } : {
640
+ color: evaluatedProperties.color || DEFAULT_HOLOGRAM_COLOR,
641
+ size: (Number(evaluatedProperties.size) || Number(evaluatedProperties.scale) || DEFAULT_HOLOGRAM_SIZE) * scale,
642
+ shape: evaluatedProperties.geometry || DEFAULT_HOLOGRAM_SHAPE,
643
+ glow: !!evaluatedProperties.glow,
644
+ interactive: !!evaluatedProperties.interactive
645
+ };
646
+ if (isUpdate && node.template) {
647
+ const tpl = ctx.getTemplate(node.template);
648
+ const oldTpl = existingOrb?._templateRef;
649
+ if (tpl && oldTpl && tpl.version !== void 0 && oldTpl.version !== void 0) {
650
+ if (Number(tpl.version) > Number(oldTpl.version)) {
651
+ logger.info(
652
+ `Template version increase detected for ${node.name}: ${oldTpl.version} -> ${tpl.version}`
653
+ );
654
+ const migrations = tpl.migrations || [];
655
+ const migration = migrations.find((m) => m.fromVersion === Number(oldTpl.version));
656
+ if (migration) {
657
+ logger.info(`Executing migration from version ${oldTpl.version} for ${node.name}`);
658
+ await ctx.executeMigrationBlock(
659
+ existingOrb,
660
+ migration
661
+ );
662
+ }
663
+ }
664
+ }
665
+ }
666
+ const orbData = isUpdate ? existingOrb : {
667
+ __type: "orb",
668
+ id: node.name,
669
+ name: node.name,
670
+ created: Date.now(),
671
+ // Methods bound to this orb — fire-and-forget through builtins registry
672
+ show: () => ctx.getBuiltinFunction("show")([node.name]),
673
+ hide: () => ctx.getBuiltinFunction("hide")([node.name]),
674
+ pulse: (opts) => ctx.getBuiltinFunction("pulse")([node.name, opts])
675
+ };
676
+ if (isUpdate) {
677
+ orbData.properties = {
678
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
679
+ ...orbData.properties,
680
+ ...evaluatedProperties
681
+ };
682
+ } else {
683
+ orbData.properties = evaluatedProperties;
684
+ }
685
+ orbData.directives = node.directives || [];
686
+ orbData.position = adjustedPos;
687
+ orbData.hologram = hologram;
688
+ orbData._templateRef = node.template ? ctx.getTemplate(node.template) : void 0;
689
+ if (!isUpdate) {
690
+ ctx.setVariable(node.name, orbData);
691
+ }
692
+ if (hologram) {
693
+ ctx.setHologramState(node.name, hologram);
694
+ }
695
+ if (node.directives) {
696
+ ctx.applyDirectives(orbData);
697
+ }
698
+ if (!isUpdate) {
699
+ ctx.createParticleEffect(`${node.name}_creation`, adjustedPos, CREATION_PUFF_COLOR, CREATION_PUFF_COUNT);
700
+ }
701
+ if (ctx.isAgent(node)) {
702
+ if (!isUpdate || !ctx.getAgentRuntime(node.name)) {
703
+ const agentRuntime = ctx.acquireAgentRuntime();
704
+ agentRuntime.reset(node, ctx.parentRuntime);
705
+ ctx.setAgentRuntime(node.name, agentRuntime);
706
+ orbData.state = agentRuntime.getState();
707
+ node.directives?.filter((d) => d.type === "method").forEach((m) => {
708
+ orbData[m.name] = (...args) => agentRuntime.executeAction(m.name, args);
709
+ });
710
+ }
711
+ }
712
+ logger.info(isUpdate ? "Orb updated" : "Orb created", {
713
+ name: node.name,
714
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
715
+ properties: Object.keys(orbData.properties),
716
+ scale
717
+ });
718
+ ctx.broadcast(isUpdate ? "orb_updated" : "orb_created", {
719
+ orb: {
720
+ id: node.name,
721
+ name: node.name,
722
+ position: adjustedPos,
723
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
724
+ properties: orbData.properties,
725
+ hologram,
726
+ traits: node.directives?.filter((d) => d.type === "trait").map((d) => d.name) || []
727
+ }
728
+ });
729
+ return {
730
+ success: true,
731
+ output: orbData,
732
+ hologram,
733
+ spatialPosition: adjustedPos
734
+ };
735
+ }
736
+
737
+ // src/runtime/narrative-executors.ts
738
+ async function executeNarrative(node, ctx) {
739
+ const startTime = Date.now();
740
+ logger.info(`[Narrative] Initializing narrative: ${node.id}`);
741
+ for (const quest of node.quests) {
742
+ ctx.quests.set(quest.id, quest);
743
+ }
744
+ if (node.startNode) {
745
+ logger.info(`[Narrative] Auto-starting at node: ${node.startNode}`);
746
+ }
747
+ return {
748
+ success: true,
749
+ output: `Narrative ${node.id} initialized with ${node.quests.length} quests`,
750
+ executionTime: Date.now() - startTime
751
+ };
752
+ }
753
+ async function executeQuest(node, ctx) {
754
+ const startTime = Date.now();
755
+ logger.info(`[Narrative] Starting quest: ${node.title}`, { questId: node.id });
756
+ ctx.setActiveQuestId(node.id);
757
+ ctx.quests.set(node.id, node);
758
+ return {
759
+ success: true,
760
+ output: `Quest ${node.id} started`,
761
+ executionTime: Date.now() - startTime
762
+ };
763
+ }
764
+ async function executeDialogue(node, ctx) {
765
+ const startTime = Date.now();
766
+ logger.info(`[Narrative] Dialogue: ${node.speaker} says "${node.text}"`);
767
+ ctx.setDialogueState({
768
+ currentNodeId: node.id,
769
+ speaker: node.speaker
770
+ });
771
+ return {
772
+ success: true,
773
+ output: `Dialogue node ${node.id} executed`,
774
+ executionTime: Date.now() - startTime
775
+ };
776
+ }
777
+
778
+ // src/runtime/graph-executors.ts
779
+ var FUNCTION_DEFAULT_HOLOGRAM = {
780
+ shape: "cube",
781
+ color: "#ff6b35",
782
+ size: 1.5,
783
+ glow: true,
784
+ interactive: true
785
+ };
786
+ var CONNECTION_HOLOGRAM_SIZE = 0.1;
787
+ var GATE_HOLOGRAM_SIZE = 1;
788
+ async function executeFunction(node, ctx) {
789
+ ctx.functions.set(node.name, node);
790
+ const hologram = {
791
+ ...FUNCTION_DEFAULT_HOLOGRAM,
792
+ ...node.hologram
793
+ };
794
+ ctx.hologramState.set(node.name, hologram);
795
+ logger.info("Function defined", {
796
+ name: node.name,
797
+ params: node.parameters.map((p) => p.name)
798
+ });
799
+ return {
800
+ success: true,
801
+ output: `Function '${node.name}' defined with ${node.parameters.length} parameter(s)`,
802
+ hologram,
803
+ spatialPosition: node.position
804
+ };
805
+ }
806
+ async function executeConnection(node, ctx) {
807
+ ctx.connections.push(node);
808
+ const fromPos = ctx.spatialMemory.get(node.from);
809
+ const toPos = ctx.spatialMemory.get(node.to);
810
+ if (fromPos && toPos) {
811
+ ctx.createConnectionStream(node.from, node.to, fromPos, toPos, node.dataType);
812
+ }
813
+ if (node.bidirectional) {
814
+ ctx.on(`${node.from}.changed`, async (data) => {
815
+ ctx.setVariable(node.to, data);
816
+ ctx.emit(`${node.to}.changed`, data);
817
+ });
818
+ ctx.on(`${node.to}.changed`, async (data) => {
819
+ ctx.setVariable(node.from, data);
820
+ ctx.emit(`${node.from}.changed`, data);
821
+ });
822
+ }
823
+ logger.info("Connection created", { from: node.from, to: node.to, dataType: node.dataType });
824
+ return {
825
+ success: true,
826
+ output: `Connected '${node.from}' to '${node.to}' (${node.dataType})`,
827
+ hologram: {
828
+ shape: "cylinder",
829
+ color: ctx.getDataTypeColor(node.dataType),
830
+ size: CONNECTION_HOLOGRAM_SIZE,
831
+ glow: true,
832
+ interactive: false
833
+ }
834
+ };
835
+ }
836
+ async function executeGate(node, ctx) {
837
+ try {
838
+ const condition = ctx.evaluateCondition(node.condition);
839
+ const path = condition ? node.truePath : node.falsePath;
840
+ logger.info("Gate evaluation", { condition: node.condition, result: condition });
841
+ if (path.length > 0) {
842
+ const subResults = await ctx.executeProgram(path, ctx.callStackDepth() + 1);
843
+ const lastResult = subResults[subResults.length - 1];
844
+ const selectedPathContainsReturn = path.some((n) => n.type === "return");
845
+ if (selectedPathContainsReturn && lastResult?.success && lastResult.output !== void 0) {
846
+ return lastResult;
847
+ }
848
+ }
849
+ return {
850
+ success: true,
851
+ output: `Gate: took ${condition ? "true" : "false"} path`,
852
+ hologram: {
853
+ shape: "pyramid",
854
+ color: condition ? "#00ff00" : "#ff0000",
855
+ size: GATE_HOLOGRAM_SIZE,
856
+ glow: true,
857
+ interactive: true
858
+ }
859
+ };
860
+ } catch (error) {
861
+ return {
862
+ success: false,
863
+ error: `Gate execution failed: ${error}`
864
+ };
865
+ }
866
+ }
867
+ async function executeStream(node, ctx) {
868
+ let data = ctx.getVariable(node.source);
869
+ logger.info("Stream processing", {
870
+ name: node.name,
871
+ source: node.source,
872
+ transforms: node.transformations.length
873
+ });
874
+ for (const transform of node.transformations) {
875
+ data = await ctx.applyTransformation(data, transform);
876
+ }
877
+ ctx.setVariable(`${node.name}_result`, data);
878
+ ctx.createFlowingStream(node.name, node.position || [0, 0, 0], data);
879
+ return {
880
+ success: true,
881
+ output: `Stream '${node.name}' processed ${Array.isArray(data) ? data.length : 1} item(s)`,
882
+ hologram: node.hologram,
883
+ spatialPosition: node.position
884
+ };
885
+ }
886
+
887
+ // src/runtime/simple-executors.ts
888
+ async function executeStateMachine(node, ctx) {
889
+ ctx.stateMachines.set(node.name, node);
890
+ return {
891
+ success: true,
892
+ output: { registered: node.name }
893
+ };
894
+ }
895
+ async function executeExpressionStatement(node, ctx) {
896
+ const value = ctx.evaluateExpression(node.expression);
897
+ return {
898
+ success: true,
899
+ output: value
900
+ };
901
+ }
902
+ async function executeCall(node, ctx) {
903
+ const funcName = node.target || "";
904
+ const args = node.args || [];
905
+ return ctx.callFunction(funcName, args);
906
+ }
907
+ async function executeEnvironment(node, ctx) {
908
+ ctx.setEnvironment({
909
+ ...ctx.getEnvironment(),
910
+ ...node.settings
911
+ });
912
+ return { success: true, output: "Environment updated" };
913
+ }
914
+ async function executeHoloTemplate(node, ctx) {
915
+ ctx.templates.set(node.name, node);
916
+ return { success: true, output: `Template ${node.name} registered` };
917
+ }
918
+ var NEXUS_HOLOGRAM = {
919
+ shape: "sphere",
920
+ color: "#9b59b6",
921
+ size: 3,
922
+ glow: true,
923
+ interactive: true
924
+ };
925
+ var STRUCTURE_HOLOGRAM = {
926
+ shape: "cube",
927
+ color: "#e74c3c",
928
+ size: 4,
929
+ glow: true,
930
+ interactive: true
931
+ };
932
+ async function executeStructure(node) {
933
+ const hologram = node.hologram || (node.type === "nexus" ? NEXUS_HOLOGRAM : STRUCTURE_HOLOGRAM);
934
+ return {
935
+ success: true,
936
+ output: { type: node.type, created: true },
937
+ hologram,
938
+ spatialPosition: node.position
939
+ };
940
+ }
941
+ async function executeAssignment(node, ctx) {
942
+ const value = ctx.evaluateExpression(String(node.value));
943
+ ctx.setVariable(node.name, value);
944
+ return {
945
+ success: true,
946
+ output: { assigned: node.name, value }
947
+ };
948
+ }
949
+ async function executeReturn(node, ctx) {
950
+ const expr = String(node.value || node.expression || "");
951
+ const value = ctx.evaluateExpression(expr);
952
+ return {
953
+ success: true,
954
+ output: value
955
+ };
956
+ }
957
+ async function executeScale(node, ctx) {
958
+ const parent = ctx.getScale();
959
+ const newMultiplier = parent.multiplier * node.multiplier;
960
+ ctx.setScale(newMultiplier, node.magnitude);
961
+ logger.info("Scale context entering", {
962
+ magnitude: node.magnitude,
963
+ multiplier: newMultiplier
964
+ });
965
+ ctx.emit("scale:change", { multiplier: newMultiplier, magnitude: node.magnitude });
966
+ const results = await ctx.executeProgram(node.body, ctx.executionStackDepth());
967
+ ctx.setScale(parent.multiplier, parent.magnitude);
968
+ ctx.emit("scale:change", { multiplier: parent.multiplier });
969
+ return {
970
+ success: results.every((r) => r.success),
971
+ output: `Executed scale block: ${node.magnitude}`
972
+ };
973
+ }
974
+ async function executeComposition(node, ctx) {
975
+ if (node.body) {
976
+ const systemResults = await ctx.executeProgram(node.body.systems, ctx.executionStackDepth());
977
+ const configResults = await ctx.executeProgram(node.body.configs, ctx.executionStackDepth());
978
+ const childrenResults = await ctx.executeProgram(node.body.children, ctx.executionStackDepth());
979
+ const allResults = [...systemResults, ...configResults, ...childrenResults];
980
+ return {
981
+ success: allResults.every((r) => r.success),
982
+ output: `Composition ${node.name} executed with specialized blocks`
983
+ };
984
+ }
985
+ return {
986
+ success: (await ctx.executeProgram(node.children, ctx.executionStackDepth())).every(
987
+ (r) => r.success
988
+ ),
989
+ output: `Composition ${node.name} executed`
990
+ };
991
+ }
992
+ async function executeFocus(node, ctx) {
993
+ ctx.focusHistory.push(node.target);
994
+ const results = await ctx.executeProgram(node.body, ctx.executionStackDepth());
995
+ return {
996
+ success: results.every((r) => r.success),
997
+ output: `Focused on ${node.target}`
998
+ };
999
+ }
1000
+
1001
+ // src/runtime/info-executors.ts
1002
+ var VISUALIZE_HOLOGRAM = {
1003
+ shape: "cylinder",
1004
+ color: "#32cd32",
1005
+ size: 1.5,
1006
+ glow: true,
1007
+ interactive: true
1008
+ };
1009
+ async function executeVisualize(node, ctx) {
1010
+ const target = node.target || "";
1011
+ const data = ctx.getVariable(target);
1012
+ if (data === void 0) {
1013
+ return {
1014
+ success: false,
1015
+ error: `No data found for '${target}'`
1016
+ };
1017
+ }
1018
+ ctx.createDataVisualization(target, data, node.position || [0, 0, 0]);
1019
+ return {
1020
+ success: true,
1021
+ output: { visualizing: target, data },
1022
+ hologram: VISUALIZE_HOLOGRAM
1023
+ };
1024
+ }
1025
+ async function executeUIElement(node, ctx) {
1026
+ const element = {
1027
+ type: node.elementType,
1028
+ name: node.name,
1029
+ properties: { ...node.properties },
1030
+ visible: true,
1031
+ enabled: true
1032
+ };
1033
+ if (node.elementType === "textinput") {
1034
+ element.value = node.properties.value || "";
1035
+ } else if (node.elementType === "slider") {
1036
+ element.value = node.properties.value || node.properties.min || 0;
1037
+ } else if (node.elementType === "toggle") {
1038
+ element.value = node.properties.checked || false;
1039
+ }
1040
+ ctx.uiElements.set(node.name, element);
1041
+ if (node.events) {
1042
+ for (const [eventName, handlerName] of Object.entries(node.events)) {
1043
+ ctx.on(`${node.name}.${eventName}`, async () => {
1044
+ await ctx.callFunction(handlerName);
1045
+ });
1046
+ }
1047
+ }
1048
+ logger.info("UI element created", { type: node.elementType, name: node.name });
1049
+ return {
1050
+ success: true,
1051
+ output: element
1052
+ };
1053
+ }
1054
+
1055
+ // src/runtime/holo-value.ts
1056
+ function resolveHoloValue(value) {
1057
+ if (value === null) return null;
1058
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
1059
+ return value;
1060
+ }
1061
+ if (Array.isArray(value)) {
1062
+ return value.map((e) => resolveHoloValue(e));
1063
+ }
1064
+ if (value.__bind) {
1065
+ return value;
1066
+ }
1067
+ const obj = {};
1068
+ for (const k in value) {
1069
+ obj[k] = resolveHoloValue(value[k]);
1070
+ }
1071
+ return obj;
1072
+ }
1073
+
1074
+ // src/runtime/holo-composition-executor.ts
1075
+ async function executeHoloComposition(node, ctx) {
1076
+ for (const template of node.templates) {
1077
+ await executeHoloTemplate(
1078
+ template,
1079
+ ctx.simpleExecutorContext
1080
+ );
1081
+ }
1082
+ if (node.environment) {
1083
+ const envSettings = {};
1084
+ for (const prop of node.environment.properties) {
1085
+ envSettings[prop.key] = resolveHoloValue(prop.value);
1086
+ }
1087
+ ctx.setEnvironment({ ...ctx.getEnvironment(), ...envSettings });
1088
+ }
1089
+ const results = [];
1090
+ for (const object of node.objects) {
1091
+ results.push(await ctx.executeHoloObject(object));
1092
+ }
1093
+ return {
1094
+ success: results.every((r) => r.success),
1095
+ output: `HoloComposition ${node.name} executed`
1096
+ };
1097
+ }
1098
+
1099
+ // src/runtime/system-executors.ts
1100
+ async function setupNetworking(node) {
1101
+ const startTime = Date.now();
1102
+ logger.info("[Networking] Initializing multiplayer fabric...", node.properties);
1103
+ return {
1104
+ success: true,
1105
+ output: "Networking system provisioned",
1106
+ executionTime: Date.now() - startTime
1107
+ };
1108
+ }
1109
+ async function setupPhysics(node) {
1110
+ const startTime = Date.now();
1111
+ logger.info("[Physics] Initializing spatial simulation engine...", node.properties);
1112
+ return {
1113
+ success: true,
1114
+ output: "Physics system provisioned",
1115
+ executionTime: Date.now() - startTime
1116
+ };
1117
+ }
1118
+ async function executeSystem(node) {
1119
+ const startTime = Date.now();
1120
+ const systemId = node.id;
1121
+ const properties = node.properties;
1122
+ logger.info(`[Zero-Config] Provisioning system: ${systemId}`, properties);
1123
+ switch (systemId) {
1124
+ case "Networking":
1125
+ return setupNetworking(node);
1126
+ case "Physics":
1127
+ return setupPhysics(node);
1128
+ default:
1129
+ logger.warn(`[Zero-Config] Unknown system: ${systemId}`);
1130
+ return {
1131
+ success: true,
1132
+ output: `System ${systemId} not recognized, skipping provisioning`,
1133
+ executionTime: Date.now() - startTime
1134
+ };
1135
+ }
1136
+ }
1137
+ async function executeCoreConfig(node, environment) {
1138
+ const startTime = Date.now();
1139
+ logger.info("[Zero-Config] Applying core configuration", node.properties);
1140
+ for (const [key, value] of Object.entries(node.properties)) {
1141
+ environment[key] = value;
1142
+ }
1143
+ return {
1144
+ success: true,
1145
+ output: "Core configuration applied",
1146
+ executionTime: Date.now() - startTime
1147
+ };
1148
+ }
1149
+ async function executeVisualMetadata(node) {
1150
+ logger.info(`[Metadata] Visual metadata processed`, node.properties);
1151
+ return { success: true, output: "Visual metadata applied" };
1152
+ }
1153
+
1154
+ // src/runtime/node-type-registry.ts
1155
+ var NODE_TYPE_HANDLERS = {
1156
+ // Orbs / objects (same handler, both keys)
1157
+ orb: (node, r) => executeOrb(node, r.buildOrbExecutorContext()),
1158
+ object: (node, r) => executeOrb(node, r.buildOrbExecutorContext()),
1159
+ // Narrative family
1160
+ narrative: (node, r) => executeNarrative(node, r.buildNarrativeContext()),
1161
+ quest: (node, r) => executeQuest(node, r.buildNarrativeContext()),
1162
+ dialogue: (node, r) => executeDialogue(node, r.buildNarrativeContext()),
1163
+ visual_metadata: (node) => executeVisualMetadata(node),
1164
+ // Graph family
1165
+ method: (node, r) => executeFunction(node, r.buildGraphExecutorContext()),
1166
+ function: (node, r) => executeFunction(node, r.buildGraphExecutorContext()),
1167
+ connection: (node, r) => executeConnection(node, r.buildGraphExecutorContext()),
1168
+ gate: (node, r) => executeGate(node, r.buildGraphExecutorContext()),
1169
+ stream: (node, r) => executeStream(node, r.buildGraphExecutorContext()),
1170
+ // Simple / expression family
1171
+ call: (node, r) => executeCall(
1172
+ node,
1173
+ r.buildSimpleExecutorContext()
1174
+ ),
1175
+ assignment: (node, r) => executeAssignment(
1176
+ node,
1177
+ r.buildSimpleExecutorContext()
1178
+ ),
1179
+ return: (node, r) => executeReturn(node, r.buildSimpleExecutorContext()),
1180
+ "expression-statement": (node, r) => executeExpressionStatement(
1181
+ node,
1182
+ r.buildSimpleExecutorContext()
1183
+ ),
1184
+ scale: (node, r) => executeScale(node, r.buildSimpleExecutorContext()),
1185
+ focus: (node, r) => executeFocus(node, r.buildSimpleExecutorContext()),
1186
+ environment: (node, r) => executeEnvironment(node, r.buildSimpleExecutorContext()),
1187
+ // Info / UI family
1188
+ visualize: (node, r) => executeVisualize(node, r.buildInfoExecutorContext()),
1189
+ "2d-element": (node, r) => executeUIElement(node, r.buildInfoExecutorContext()),
1190
+ // Structure family (nexus + building = same handler)
1191
+ nexus: (node) => executeStructure(node),
1192
+ building: (node) => executeStructure(node),
1193
+ // Capitalization-sensitive branches (composition vs Composition, template vs Template)
1194
+ composition: (node, r) => executeComposition(node, r.buildSimpleExecutorContext()),
1195
+ Composition: (node, r) => executeHoloComposition(
1196
+ node,
1197
+ r.buildHoloCompositionContext()
1198
+ ),
1199
+ template: (node, r) => r.executeTemplate(node),
1200
+ Template: (node, r) => executeHoloTemplate(
1201
+ node,
1202
+ r.buildSimpleExecutorContext()
1203
+ ),
1204
+ // State family
1205
+ "state-machine": (node, r) => executeStateMachine(node, r.buildSimpleExecutorContext()),
1206
+ "state-declaration": (node, r) => r.executeStateDeclaration(
1207
+ node
1208
+ ),
1209
+ // System
1210
+ system: (node) => executeSystem(node),
1211
+ core_config: (node, r) => executeCoreConfig(
1212
+ node,
1213
+ r.context.environment
1214
+ ),
1215
+ // Migration: accepted but no executor — plain success record
1216
+ migration: async () => ({
1217
+ success: true,
1218
+ output: "Migration block registered"
1219
+ }),
1220
+ // IO family (slice 32 delegates)
1221
+ server: (node, r) => r.executeServerNode(node),
1222
+ database: (node, r) => r.executeDatabaseNode(node),
1223
+ fetch: (node, r) => r.executeFetchNode(node),
1224
+ execute: (node, r) => r.executeTarget(node),
1225
+ // Memory family
1226
+ memory: (node, r) => r.executeMemory(node),
1227
+ "semantic-memory": (node, r) => r.executeMemoryDefinition(
1228
+ node
1229
+ ),
1230
+ "episodic-memory": (node, r) => r.executeMemoryDefinition(
1231
+ node
1232
+ ),
1233
+ "procedural-memory": (node, r) => r.executeMemoryDefinition(
1234
+ node
1235
+ ),
1236
+ // Control-flow family
1237
+ for: (node, r) => r.executeForLoop(
1238
+ node
1239
+ ),
1240
+ forEach: (node, r) => r.executeForEachLoop(
1241
+ node
1242
+ ),
1243
+ while: (node, r) => r.executeWhileLoop(
1244
+ node
1245
+ ),
1246
+ if: (node, r) => r.executeIfStatement(
1247
+ node
1248
+ ),
1249
+ match: (node, r) => r.executeMatch(
1250
+ node
1251
+ ),
1252
+ // Debug + generic
1253
+ debug: (node, r) => r.executeDebug(node),
1254
+ generic: (node, r) => r.executeGeneric(node)
1255
+ };
1256
+ async function dispatchNode(node, runtime) {
1257
+ const nodeType = node.type;
1258
+ const handler = NODE_TYPE_HANDLERS[nodeType];
1259
+ if (!handler) {
1260
+ return {
1261
+ success: false,
1262
+ error: `Unknown node type: ${node.type}`
1263
+ };
1264
+ }
1265
+ return handler(node, runtime);
1266
+ }
1267
+
1268
+ // src/runtime/system-variables.ts
1269
+ init_safeJsonParse();
1270
+ var DEFAULT_USER = {
1271
+ id: "user_123",
1272
+ name: "Alpha Explorer",
1273
+ level: 42,
1274
+ rank: "Legendary",
1275
+ achievements: ["First World", "Spirit Guide"],
1276
+ preferences: { theme: "holographic", language: "en" }
1277
+ };
1278
+ var DEFAULT_LOCATION = {
1279
+ city: "Neo Tokyo",
1280
+ region: "Holo-Sector 7",
1281
+ coordinates: { lat: 35.6895, lng: 139.6917 },
1282
+ altitude: 450
1283
+ };
1284
+ var DEFAULT_WEATHER = {
1285
+ condition: "Neon Mist",
1286
+ temperature: 24,
1287
+ humidity: 65,
1288
+ windSpeed: 12,
1289
+ unit: "C"
1290
+ };
1291
+ var DEFAULT_WALLET = {
1292
+ address: "0xHolo...42ff",
1293
+ balance: 1337.5,
1294
+ currency: "HOLO",
1295
+ network: "MainNet"
1296
+ };
1297
+ var DEFAULT_CHAT_STATUS = {
1298
+ active: true,
1299
+ typing: false,
1300
+ version: "1.0.0-brittney"
1301
+ };
1302
+ function updateSystemVariables(ctx) {
1303
+ const now = /* @__PURE__ */ new Date();
1304
+ ctx.setVariable("$time", now.toLocaleTimeString());
1305
+ ctx.setVariable("$date", now.toLocaleDateString());
1306
+ ctx.setVariable("$timestamp", now.getTime());
1307
+ ctx.setVariable("$hour", now.getHours());
1308
+ ctx.setVariable("$minute", now.getMinutes());
1309
+ ctx.setVariable("$second", now.getSeconds());
1310
+ if (ctx.getVariable("$user") === void 0) {
1311
+ ctx.setVariable("$user", DEFAULT_USER);
1312
+ }
1313
+ if (ctx.getVariable("$location") === void 0) {
1314
+ ctx.setVariable("$location", DEFAULT_LOCATION);
1315
+ }
1316
+ if (ctx.getVariable("$weather") === void 0) {
1317
+ ctx.setVariable("$weather", DEFAULT_WEATHER);
1318
+ }
1319
+ if (ctx.getVariable("$wallet") === void 0) {
1320
+ ctx.setVariable("$wallet", DEFAULT_WALLET);
1321
+ }
1322
+ if (ctx.getVariable("$ai_config") === void 0) {
1323
+ let configuredCount = 0;
1324
+ if (ctx.brittneyApiKeysJson) {
1325
+ try {
1326
+ const keys = readJson(ctx.brittneyApiKeysJson);
1327
+ configuredCount = Object.values(keys).filter((k) => !!k).length;
1328
+ } catch (_e) {
1329
+ }
1330
+ }
1331
+ ctx.setVariable("$ai_config", {
1332
+ status: configuredCount > 0 ? "configured" : "pending",
1333
+ providerCount: configuredCount,
1334
+ lastUpdated: Date.now()
1335
+ });
1336
+ }
1337
+ if (ctx.getVariable("$chat_status") === void 0) {
1338
+ ctx.setVariable("$chat_status", DEFAULT_CHAT_STATUS);
1339
+ }
1340
+ }
1341
+
1342
+ // src/runtime/context-factory.ts
1343
+ function createEmptyContext() {
1344
+ return {
1345
+ variables: /* @__PURE__ */ new Map(),
1346
+ functions: /* @__PURE__ */ new Map(),
1347
+ exports: /* @__PURE__ */ new Map(),
1348
+ connections: [],
1349
+ spatialMemory: /* @__PURE__ */ new Map(),
1350
+ hologramState: /* @__PURE__ */ new Map(),
1351
+ executionStack: [],
1352
+ currentScale: 1,
1353
+ scaleMagnitude: "standard",
1354
+ focusHistory: [],
1355
+ environment: {},
1356
+ templates: /* @__PURE__ */ new Map(),
1357
+ // HS+ State
1358
+ state: createState({}),
1359
+ // Phase 13: State Machines
1360
+ stateMachines: /* @__PURE__ */ new Map(),
1361
+ // Narrative & Story State
1362
+ quests: /* @__PURE__ */ new Map(),
1363
+ completedQuests: /* @__PURE__ */ new Set()
1364
+ };
1365
+ }
1366
+
1367
+ // src/runtime/holo-object-executor.ts
1368
+ var DEFAULT_SHAPE = "sphere";
1369
+ var DEFAULT_COLOR = "#ffffff";
1370
+ var DEFAULT_SIZE = 1;
1371
+ async function executeHoloObject(node, ctx) {
1372
+ const properties = {};
1373
+ for (const prop of node.properties) {
1374
+ properties[prop.key] = resolveHoloValue(prop.value);
1375
+ }
1376
+ if (node.state) {
1377
+ for (const prop of node.state.properties) {
1378
+ properties[prop.key] = resolveHoloValue(prop.value);
1379
+ }
1380
+ }
1381
+ const position = properties.position;
1382
+ const hologram = {
1383
+ shape: properties.geometry || DEFAULT_SHAPE,
1384
+ color: properties.color || DEFAULT_COLOR,
1385
+ size: properties.scale || properties.size || DEFAULT_SIZE,
1386
+ glow: properties.glow || false,
1387
+ // interactive defaults to true unless explicitly set false
1388
+ interactive: properties.interactive !== false
1389
+ };
1390
+ const template = node.template ? ctx.getTemplate(node.template) : void 0;
1391
+ const orbNode = {
1392
+ type: "orb",
1393
+ name: node.name,
1394
+ position,
1395
+ hologram,
1396
+ properties,
1397
+ // @ts-expect-error — directive shape is intentionally loose here;
1398
+ // downstream dispatch normalizes.
1399
+ directives: [
1400
+ ...node.directives || [],
1401
+ ...(node.traits || []).map((t) => ({
1402
+ type: "trait",
1403
+ name: t.name,
1404
+ ...t.config
1405
+ })),
1406
+ ...template?.directives || []
1407
+ ],
1408
+ traits: new Map(
1409
+ (node.traits || []).map((t) => [t.name, t.config])
1410
+ ),
1411
+ children: node.children || []
1412
+ };
1413
+ if (template) {
1414
+ if (template.state) {
1415
+ for (const prop of template.state.properties) {
1416
+ if (properties[prop.key] === void 0) {
1417
+ properties[prop.key] = resolveHoloValue(prop.value);
1418
+ }
1419
+ }
1420
+ }
1421
+ for (const prop of template.properties) {
1422
+ if (properties[prop.key] === void 0) {
1423
+ properties[prop.key] = resolveHoloValue(prop.value);
1424
+ }
1425
+ }
1426
+ }
1427
+ return ctx.executeOrb(orbNode);
1428
+ }
1429
+
1430
+ // src/runtime/skills-directives.ts
1431
+ var TRAIT_UPDATE_DT = 1 / 60;
1432
+ function loadSkill(skill, ctx) {
1433
+ logger.info(`[Procedural] Loading skill: ${skill.name} (${skill.id})`);
1434
+ const existing = ctx.proceduralSkills.get(skill.id);
1435
+ if (existing) {
1436
+ skill.successRate = (existing.successRate + (skill.successRate || 0)) / 2;
1437
+ } else {
1438
+ skill.successRate = skill.successRate || 0;
1439
+ }
1440
+ ctx.proceduralSkills.set(skill.id, skill);
1441
+ ctx.broadcastSkill(skill);
1442
+ }
1443
+ var AGENT_TRAIT_NAMES = /* @__PURE__ */ new Set(["llm_agent", "agent", "companion"]);
1444
+ function isAgent(node) {
1445
+ return !!node.directives?.some(
1446
+ (d) => d.type === "trait" && AGENT_TRAIT_NAMES.has(d.name)
1447
+ );
1448
+ }
1449
+ function applyDirectives(node, ctx) {
1450
+ if (!node.directives) return;
1451
+ for (const d of node.directives) {
1452
+ if (d.type === "trait") {
1453
+ logger.info(`Applying trait ${d.name} to ${node.type}`);
1454
+ const handler = ctx.traitHandlers.get(d.name);
1455
+ if (handler) {
1456
+ handler.onAttach?.(node, d.config || {}, {
1457
+ emit: (event, payload) => ctx.emit(event, payload),
1458
+ getScaleMultiplier: () => ctx.getCurrentScale() || 1
1459
+ });
1460
+ }
1461
+ if (d.name === "chat") {
1462
+ ctx.emit("show-chat", d.config);
1463
+ }
1464
+ } else if (d.type === "state") {
1465
+ if (node && node.__type === "orb") {
1466
+ const stateBody = d.body;
1467
+ const existingProps = node.properties || {};
1468
+ for (const [key, val] of Object.entries(stateBody)) {
1469
+ if (existingProps[key] === void 0) {
1470
+ existingProps[key] = val;
1471
+ }
1472
+ }
1473
+ node.properties = existingProps;
1474
+ }
1475
+ ctx.state.update(d.body);
1476
+ } else if (d.type === "lifecycle") {
1477
+ if (d.hook === "on_mount" || d.hook === "mount") {
1478
+ ctx.evaluateExpression(d.body);
1479
+ }
1480
+ }
1481
+ }
1482
+ }
1483
+ function updateTraits(julianDate, ctx) {
1484
+ const delta = TRAIT_UPDATE_DT;
1485
+ for (const [name, value] of ctx.variables.entries()) {
1486
+ if (value && typeof value === "object" && value.__type === "orb") {
1487
+ const orb = value;
1488
+ if (!orb.directives) continue;
1489
+ for (const d of orb.directives || []) {
1490
+ if (d.type !== "trait") continue;
1491
+ const handler = ctx.traitHandlers.get(d.name);
1492
+ if (!handler || !handler.onUpdate) continue;
1493
+ const traitNode = orb;
1494
+ handler.onUpdate(
1495
+ traitNode,
1496
+ d.config || {},
1497
+ {
1498
+ emit: (event, payload) => {
1499
+ if (event === "position_update") {
1500
+ const posPayload = payload;
1501
+ if (posPayload?.position) {
1502
+ const p = posPayload.position;
1503
+ const tuple = Array.isArray(p) ? p : [p[0], p[1], p[2]];
1504
+ ctx.setOrbPosition(name, tuple);
1505
+ }
1506
+ }
1507
+ return ctx.emit(event, payload);
1508
+ },
1509
+ getScaleMultiplier: () => ctx.getCurrentScale() || 1,
1510
+ julianDate,
1511
+ getNode: (nodeName) => ctx.variables.get(nodeName),
1512
+ getState: () => ctx.getState(),
1513
+ setState: (updates) => ctx.setState(updates)
1514
+ },
1515
+ delta
1516
+ );
1517
+ }
1518
+ }
1519
+ }
1520
+ }
1521
+
1522
+ // src/runtime/primitives.ts
1523
+ function handleShop(args, emit2) {
1524
+ const config = args[0] || {};
1525
+ emit2("shop", config);
1526
+ return { success: true, type: "shop", config };
1527
+ }
1528
+ function handleInventory(args, emit2) {
1529
+ const item = args[0];
1530
+ const action = args[1] || "add";
1531
+ emit2("inventory", { item, action });
1532
+ return { success: true, item, action };
1533
+ }
1534
+ function handlePurchase(args, emit2) {
1535
+ const productId = args[0];
1536
+ emit2("purchase", { productId });
1537
+ return { success: true, productId, status: "pending" };
1538
+ }
1539
+ function handlePresence(args, emit2) {
1540
+ const config = args[0] || {};
1541
+ emit2("presence", config);
1542
+ return { success: true, active: true };
1543
+ }
1544
+ function handleInvite(args, emit2) {
1545
+ const userId = args[0];
1546
+ emit2("invite", { userId });
1547
+ return { success: true, userId };
1548
+ }
1549
+ function handleShare(args, emit2) {
1550
+ const scriptId = args[0];
1551
+ const targetUserId = args[1];
1552
+ emit2("share", { scriptId, targetUserId });
1553
+ return { success: true, scriptId };
1554
+ }
1555
+ function handlePhysics(args, emit2) {
1556
+ const config = args[0] || {};
1557
+ emit2("physics", config);
1558
+ return {
1559
+ success: true,
1560
+ enabled: config.enabled !== false
1561
+ };
1562
+ }
1563
+ function handleGravity(args, emit2) {
1564
+ const value = args[0] ?? 9.81;
1565
+ emit2("gravity", { value });
1566
+ return { success: true, value };
1567
+ }
1568
+ function handleCollide(args, emit2) {
1569
+ const target = args[0];
1570
+ const handler = args[1];
1571
+ emit2("collide", { target, handler });
1572
+ return { success: true, target };
1573
+ }
1574
+ function handleAnimate(args, emit2) {
1575
+ const options = args[0] || {};
1576
+ emit2("animate", options);
1577
+ return { success: true, options };
1578
+ }
1579
+
1580
+ // src/runtime/builtins-registry.ts
1581
+ var SHOW_PARTICLES = 15;
1582
+ var PULSATE_PARTICLES = 30;
1583
+ var SPAWN_PARTICLES = 25;
1584
+ var DESPAWN_PARTICLES = 30;
1585
+ var DEFAULT_PULSATE_DURATION_MS = 1e3;
1586
+ var DEFAULT_PULSATE_COLOR = "#ffffff";
1587
+ var SPAWN_COLOR = "#00ff00";
1588
+ var DESPAWN_COLOR = "#ff0000";
1589
+ function createBuiltinsMap(ctx, customFunctions) {
1590
+ const builtins = /* @__PURE__ */ new Map();
1591
+ if (customFunctions) {
1592
+ for (const [name, func] of Object.entries(customFunctions)) {
1593
+ builtins.set(name, func);
1594
+ }
1595
+ }
1596
+ builtins.set("show", (args) => {
1597
+ const target = String(args[0]);
1598
+ const element = ctx.uiElements.get(target);
1599
+ if (element) element.visible = true;
1600
+ const hologram = ctx.hologramState.get(target);
1601
+ if (hologram) {
1602
+ ctx.createParticleEffect(`${target}_show`, [0, 0, 0], hologram.color, SHOW_PARTICLES);
1603
+ }
1604
+ logger.info("show", { target });
1605
+ return { shown: target };
1606
+ });
1607
+ builtins.set("hide", (args) => {
1608
+ const target = String(args[0]);
1609
+ const element = ctx.uiElements.get(target);
1610
+ if (element) element.visible = false;
1611
+ logger.info("hide", { target });
1612
+ return { hidden: target };
1613
+ });
1614
+ builtins.set("pulsate", (args) => {
1615
+ const target = String(args[0]);
1616
+ const options = args[1] || {};
1617
+ const duration = Number(options.duration) || DEFAULT_PULSATE_DURATION_MS;
1618
+ const color = String(options.color || DEFAULT_PULSATE_COLOR);
1619
+ const position = ctx.spatialMemory.get(target) || [0, 0, 0];
1620
+ ctx.createParticleEffect(`${target}_pulse`, position, color, PULSATE_PARTICLES);
1621
+ return { pulsing: target, duration };
1622
+ });
1623
+ builtins.set("animate", (args) => {
1624
+ const target = String(args[0]);
1625
+ const options = args[1] || {};
1626
+ const animation = {
1627
+ target,
1628
+ property: String(options.property || "position[1]"),
1629
+ from: Number(options.from || 0),
1630
+ to: Number(options.to || 1),
1631
+ duration: Number(options.duration || 1e3),
1632
+ startTime: Date.now(),
1633
+ easing: String(options.easing || "linear"),
1634
+ loop: Boolean(options.loop),
1635
+ yoyo: Boolean(options.yoyo)
1636
+ };
1637
+ ctx.animations.set(`${target}_${animation.property}`, animation);
1638
+ return { animating: target, animation };
1639
+ });
1640
+ builtins.set("spawn", async (args) => {
1641
+ const config = args[0];
1642
+ if (typeof config === "string") {
1643
+ const target = config;
1644
+ const position2 = args[1] || [0, 0, 0];
1645
+ ctx.spatialMemory.set(target, position2);
1646
+ ctx.createParticleEffect(`${target}_spawn`, position2, SPAWN_COLOR, SPAWN_PARTICLES);
1647
+ return { spawned: target, at: position2 };
1648
+ }
1649
+ const spawnConfig = config;
1650
+ const templateName = String(spawnConfig.template);
1651
+ const id = String(spawnConfig.id || `${templateName}_${Date.now()}`);
1652
+ const position = spawnConfig.position || [0, 0, 0];
1653
+ const template = ctx.templates.get(templateName);
1654
+ if (!template) {
1655
+ logger.error(`[Mitosis] Template ${templateName} not found`);
1656
+ return { error: `Template ${templateName} not found` };
1657
+ }
1658
+ const spawnNode = {
1659
+ type: "orb",
1660
+ name: id,
1661
+ position,
1662
+ properties: { ...spawnConfig.config || {} },
1663
+ children: template.children,
1664
+ traits: template.traits,
1665
+ directives: template.directives
1666
+ };
1667
+ const holoTpl = template;
1668
+ if (holoTpl.state) {
1669
+ for (const prop of holoTpl.state.properties) {
1670
+ if (spawnNode.properties[prop.key] === void 0) {
1671
+ spawnNode.properties[prop.key] = resolveHoloValue(prop.value);
1672
+ }
1673
+ }
1674
+ }
1675
+ for (const prop of holoTpl.properties) {
1676
+ if (spawnNode.properties[prop.key] === void 0) {
1677
+ spawnNode.properties[prop.key] = resolveHoloValue(prop.value);
1678
+ }
1679
+ }
1680
+ await ctx.executeOrb(spawnNode);
1681
+ if (spawnConfig.parentId || spawnConfig.parent_id) {
1682
+ const parentId = String(spawnConfig.parentId || spawnConfig.parent_id);
1683
+ await ctx.emit(`mitosis_spawned`, { parentId, childId: id });
1684
+ await ctx.emit(`${parentId}.mitosis_spawned`, { childId: id });
1685
+ }
1686
+ return { spawned: id, template: templateName };
1687
+ });
1688
+ builtins.set("notifyParent", async (args) => {
1689
+ const parentId = String(args[0]);
1690
+ const data = args[1];
1691
+ await ctx.emit(`mitosis_child_complete`, {
1692
+ parentId,
1693
+ childId: args[2] || "unknown",
1694
+ result: data
1695
+ });
1696
+ await ctx.emit(`${parentId}.mitosis_child_complete`, {
1697
+ childId: args[2] || "unknown",
1698
+ result: data
1699
+ });
1700
+ return { notified: parentId };
1701
+ });
1702
+ builtins.set("despawn", (args) => {
1703
+ const target = String(args[0]);
1704
+ if (ctx.hologramState.has(target)) {
1705
+ const pos = ctx.spatialMemory.get(target) || [0, 0, 0];
1706
+ ctx.createParticleEffect(`${target}_despawn`, pos, DESPAWN_COLOR, DESPAWN_PARTICLES);
1707
+ ctx.hologramState.delete(target);
1708
+ ctx.variables.delete(target);
1709
+ ctx.spatialMemory.delete(target);
1710
+ logger.info("despawn", { target });
1711
+ return { despawned: target };
1712
+ }
1713
+ return { msg: "Target not found", target };
1714
+ });
1715
+ builtins.set("move", (args) => {
1716
+ const target = String(args[0]);
1717
+ const position = args[1] || [0, 0, 0];
1718
+ const current = ctx.spatialMemory.get(target);
1719
+ if (current) {
1720
+ ctx.spatialMemory.set(target, position);
1721
+ ctx.createConnectionStream(target, `${target}_dest`, current, position, "move");
1722
+ }
1723
+ return { moved: target, to: position };
1724
+ });
1725
+ builtins.set("set", (args) => {
1726
+ const target = String(args[0]);
1727
+ const value = args[1];
1728
+ ctx.setVariable(target, value);
1729
+ return { set: target, value };
1730
+ });
1731
+ builtins.set("get", (args) => {
1732
+ const target = String(args[0]);
1733
+ return ctx.getVariable(target);
1734
+ });
1735
+ builtins.set("add", (args) => Number(args[0]) + Number(args[1]));
1736
+ builtins.set("subtract", (args) => Number(args[0]) - Number(args[1]));
1737
+ builtins.set("multiply", (args) => Number(args[0]) * Number(args[1]));
1738
+ builtins.set(
1739
+ "divide",
1740
+ (args) => Number(args[1]) !== 0 ? Number(args[0]) / Number(args[1]) : 0
1741
+ );
1742
+ builtins.set("mod", (args) => Number(args[0]) % Number(args[1]));
1743
+ builtins.set("abs", (args) => Math.abs(Number(args[0])));
1744
+ builtins.set("floor", (args) => Math.floor(Number(args[0])));
1745
+ builtins.set("ceil", (args) => Math.ceil(Number(args[0])));
1746
+ builtins.set("round", (args) => Math.round(Number(args[0])));
1747
+ builtins.set("min", (args) => Math.min(...args.map(Number)));
1748
+ builtins.set("max", (args) => Math.max(...args.map(Number)));
1749
+ builtins.set("random", () => Math.random());
1750
+ builtins.set("concat", (args) => args.map(String).join(""));
1751
+ builtins.set("length", (args) => {
1752
+ const val = args[0];
1753
+ if (typeof val === "string") return val.length;
1754
+ if (Array.isArray(val)) return val.length;
1755
+ return 0;
1756
+ });
1757
+ builtins.set(
1758
+ "substring",
1759
+ (args) => String(args[0]).substring(Number(args[1]), Number(args[2]))
1760
+ );
1761
+ builtins.set("wait", async (args) => {
1762
+ const ms = Number(args[0]) || 0;
1763
+ await new Promise((resolve) => setTimeout(resolve, ms));
1764
+ return { waited: ms };
1765
+ });
1766
+ builtins.set("print", (args) => {
1767
+ console.log(`[HoloScript]`, ...args);
1768
+ return { printed: args.join(" ") };
1769
+ });
1770
+ builtins.set("uppercase", (args) => String(args[0]).toUpperCase());
1771
+ builtins.set("lowercase", (args) => String(args[0]).toLowerCase());
1772
+ builtins.set("push", (args) => {
1773
+ const arr = args[0];
1774
+ if (Array.isArray(arr)) {
1775
+ arr.push(args[1]);
1776
+ return arr;
1777
+ }
1778
+ return [args[0], args[1]];
1779
+ });
1780
+ builtins.set("pop", (args) => {
1781
+ const arr = args[0];
1782
+ if (Array.isArray(arr)) return arr.pop();
1783
+ return void 0;
1784
+ });
1785
+ builtins.set("at", (args) => {
1786
+ const arr = args[0];
1787
+ const index = Number(args[1]);
1788
+ if (Array.isArray(arr)) return arr[index];
1789
+ return void 0;
1790
+ });
1791
+ builtins.set("showSettings", () => {
1792
+ void ctx.emit("show-settings");
1793
+ return true;
1794
+ });
1795
+ builtins.set("openChat", (args) => {
1796
+ const config = args[0] || {};
1797
+ void ctx.emit("show-chat", config);
1798
+ return true;
1799
+ });
1800
+ builtins.set("log", (args) => {
1801
+ logger.info("HoloScript log", { args });
1802
+ return args[0];
1803
+ });
1804
+ builtins.set("print", (args) => {
1805
+ const message = args.map(String).join(" ");
1806
+ logger.info("print", { message });
1807
+ return message;
1808
+ });
1809
+ builtins.set("typeof", (args) => typeof args[0]);
1810
+ builtins.set("isArray", (args) => Array.isArray(args[0]));
1811
+ builtins.set(
1812
+ "isNumber",
1813
+ (args) => typeof args[0] === "number" && !isNaN(args[0])
1814
+ );
1815
+ builtins.set("isString", (args) => typeof args[0] === "string");
1816
+ const emitFn = (event, data) => {
1817
+ void ctx.emit(event, data);
1818
+ };
1819
+ builtins.set("shop", (args) => handleShop(args, emitFn));
1820
+ builtins.set("inventory", (args) => handleInventory(args, emitFn));
1821
+ builtins.set("purchase", (args) => handlePurchase(args, emitFn));
1822
+ builtins.set("presence", (args) => handlePresence(args, emitFn));
1823
+ builtins.set("invite", (args) => handleInvite(args, emitFn));
1824
+ builtins.set("share", (args) => handleShare(args, emitFn));
1825
+ builtins.set("physics", (args) => handlePhysics(args, emitFn));
1826
+ builtins.set("gravity", (args) => handleGravity(args, emitFn));
1827
+ builtins.set("collide", (args) => handleCollide(args, emitFn));
1828
+ builtins.set("animate", (args) => handleAnimate(args, emitFn));
1829
+ builtins.set("calculate_arc", (args) => ctx.calculateArc(args));
1830
+ builtins.set(
1831
+ "sleep",
1832
+ (args) => new Promise((resolve) => setTimeout(resolve, Number(args[0]) || 0))
1833
+ );
1834
+ builtins.set("think", async (args) => {
1835
+ const activeNode = ctx.executionStack[ctx.executionStack.length - 1];
1836
+ if (!activeNode) return "No context";
1837
+ const agentId = activeNode.name;
1838
+ const agentRuntime = ctx.agentRuntimes.get(agentId);
1839
+ if (agentRuntime) {
1840
+ return await agentRuntime.think(String(args[0] || ""));
1841
+ }
1842
+ return "Thinking only available for agents.";
1843
+ });
1844
+ return builtins;
1845
+ }
1846
+
1847
+ // src/runtime/event-system.ts
1848
+ function onEvent(event, handler, ctx) {
1849
+ const handlers = ctx.eventHandlers.get(event) || [];
1850
+ handlers.push(handler);
1851
+ ctx.eventHandlers.set(event, handlers);
1852
+ }
1853
+ function offEvent(event, handler, ctx) {
1854
+ if (!handler) {
1855
+ ctx.eventHandlers.delete(event);
1856
+ } else {
1857
+ const handlers = ctx.eventHandlers.get(event) || [];
1858
+ ctx.eventHandlers.set(
1859
+ event,
1860
+ handlers.filter((h) => h !== handler)
1861
+ );
1862
+ }
1863
+ }
1864
+ async function emit(event, data, ctx) {
1865
+ logger.info(`[Runtime] Emitting event: ${event}`, data);
1866
+ if (event.includes(".")) {
1867
+ const [target, eventName] = event.split(".");
1868
+ const agent = ctx.agentRuntimes.get(target);
1869
+ if (agent) {
1870
+ await agent.onEvent(eventName, data);
1871
+ }
1872
+ const orb = ctx.variables.get(target);
1873
+ if (orb && typeof orb === "object" && orb.__type === "orb") {
1874
+ await forwardToTraits(orb, eventName, data, ctx);
1875
+ }
1876
+ }
1877
+ const orbs = Array.from(ctx.variables.values()).filter(
1878
+ (v) => v && typeof v === "object" && v.__type === "orb"
1879
+ );
1880
+ for (const agent of ctx.agentRuntimes.values()) {
1881
+ await agent.onEvent(event, data);
1882
+ }
1883
+ for (const variable of orbs) {
1884
+ await forwardToTraits(variable, event, data, ctx);
1885
+ }
1886
+ const handlers = ctx.eventHandlers.get(event) || [];
1887
+ for (const handler of handlers) {
1888
+ try {
1889
+ await handler(data);
1890
+ } catch (error) {
1891
+ logger.error("Event handler error", { event, error });
1892
+ }
1893
+ }
1894
+ await ctx.globalBusEmit(event, data);
1895
+ if (data && typeof data === "object" && data.id) {
1896
+ ctx.sendStateMachineEvent(data.id, event);
1897
+ }
1898
+ }
1899
+ async function forwardToTraits(orb, event, data, ctx) {
1900
+ if (!orb.directives) return;
1901
+ for (const d of orb.directives) {
1902
+ if (d.type !== "trait") continue;
1903
+ const handler = ctx.traitHandlers.get(d.name);
1904
+ if (!handler || !handler.onEvent) continue;
1905
+ const traitNode = orb;
1906
+ const eventPayload = {
1907
+ type: event,
1908
+ ...data && typeof data === "object" ? data : {}
1909
+ };
1910
+ await handler.onEvent(
1911
+ traitNode,
1912
+ d.config || {},
1913
+ {
1914
+ emit: async (e, p) => await emit(e, p, ctx),
1915
+ getScaleMultiplier: () => ctx.getCurrentScale() || 1
1916
+ },
1917
+ eventPayload
1918
+ );
1919
+ }
1920
+ }
1921
+ async function triggerUIEvent(elementName, eventType, data, ctx) {
1922
+ const element = ctx.uiElements.get(elementName);
1923
+ if (!element) {
1924
+ logger.warn("UI element not found", { elementName });
1925
+ return;
1926
+ }
1927
+ if (eventType === "change" && data !== void 0) {
1928
+ element.value = data;
1929
+ }
1930
+ await emit(`${elementName}.${eventType}`, data, ctx);
1931
+ }
1932
+
1933
+ // src/runtime/state-invalidation.ts
1934
+ var StateInvalidationRegistry = class {
1935
+ constructor() {
1936
+ this.records = /* @__PURE__ */ new Map();
1937
+ }
1938
+ /** Record an invalidation for `key`. No-op on an empty/invalid key. */
1939
+ record(key, nodeId) {
1940
+ if (typeof key !== "string" || key.length === 0) return;
1941
+ this.records.set(key, { key, at: Date.now(), nodeId });
1942
+ }
1943
+ /** True if `key` has an outstanding (unacknowledged) invalidation. */
1944
+ wasInvalidated(key) {
1945
+ return this.records.has(key);
1946
+ }
1947
+ /** Peek the invalidation record without acknowledging it. */
1948
+ get(key) {
1949
+ return this.records.get(key);
1950
+ }
1951
+ /**
1952
+ * Read-and-clear: returns the record (if any) and removes it, so a reader
1953
+ * that has refetched the value acknowledges the invalidation exactly once.
1954
+ */
1955
+ consume(key) {
1956
+ const record = this.records.get(key);
1957
+ this.records.delete(key);
1958
+ return record;
1959
+ }
1960
+ /** All outstanding invalidations. */
1961
+ list() {
1962
+ return Array.from(this.records.values());
1963
+ }
1964
+ /** Drop all outstanding invalidations. */
1965
+ clear() {
1966
+ this.records.clear();
1967
+ }
1968
+ /** Count of outstanding invalidations. */
1969
+ get size() {
1970
+ return this.records.size;
1971
+ }
1972
+ };
1973
+ var defaultStateInvalidationRegistry = new StateInvalidationRegistry();
1974
+ function makeStateInvalidationHandler(registry) {
1975
+ return (data) => {
1976
+ const payload = data ?? {};
1977
+ if (typeof payload.key === "string") {
1978
+ const nodeId = payload.node && typeof payload.node.id === "string" ? payload.node.id : void 0;
1979
+ registry.record(payload.key, nodeId);
1980
+ }
1981
+ };
1982
+ }
1983
+ function attachStateInvalidationConsumer(ctx, registry = defaultStateInvalidationRegistry) {
1984
+ onEvent("persistent_expired", makeStateInvalidationHandler(registry), ctx);
1985
+ return registry;
1986
+ }
1987
+
1988
+ // src/runtime/ui-commands.ts
1989
+ var SHOW_PARTICLE_COUNT = 15;
1990
+ var HIDE_PARTICLE_COUNT = 10;
1991
+ var CREATE_PARTICLE_COUNT = 20;
1992
+ var PULSE_PARTICLE_COUNT = 30;
1993
+ var DELETE_PARTICLE_COUNT = 15;
1994
+ var HIDE_COLOR = "#ff0000";
1995
+ var DELETE_COLOR = "#ff0000";
1996
+ var PULSE_COLOR = "#ffff00";
1997
+ var DEFAULT_SHOW_HOLOGRAM = {
1998
+ shape: "orb",
1999
+ color: "#00ffff",
2000
+ size: 0.8,
2001
+ glow: true,
2002
+ interactive: true
2003
+ };
2004
+ var DEFAULT_CREATE_COLOR = "#00ffff";
2005
+ var DEFAULT_CREATE_SIZE = 1;
2006
+ var DEFAULT_ANIMATE_PROPERTY = "position[1]";
2007
+ var DEFAULT_ANIMATE_DURATION_MS = 1e3;
2008
+ var DEFAULT_PULSE_DURATION_MS = 500;
2009
+ var PULSE_SCALE_FROM = 1;
2010
+ var PULSE_SCALE_TO = 1.5;
2011
+ async function executeShowCommand(target, node, ctx) {
2012
+ const hologram = node.hologram || DEFAULT_SHOW_HOLOGRAM;
2013
+ const position = node.position || [0, 0, 0];
2014
+ ctx.spatialMemory.set(target, position);
2015
+ ctx.createParticleEffect(`${target}_show`, position, hologram.color, SHOW_PARTICLE_COUNT);
2016
+ logger.info("Show command executed", { target, position });
2017
+ return { showed: target, hologram, position };
2018
+ }
2019
+ async function executeHideCommand(target, _node, ctx) {
2020
+ const position = ctx.spatialMemory.get(target) || [0, 0, 0];
2021
+ ctx.createParticleEffect(`${target}_hide`, position, HIDE_COLOR, HIDE_PARTICLE_COUNT);
2022
+ logger.info("Hide command executed", { target });
2023
+ return { hidden: target };
2024
+ }
2025
+ async function executeCreateCommand(tokens, node, ctx) {
2026
+ if (tokens.length < 2) {
2027
+ return { error: "Create command requires shape and name" };
2028
+ }
2029
+ const shape = tokens[0];
2030
+ const name = tokens[1];
2031
+ const position = node.position || [0, 0, 0];
2032
+ const hologram = {
2033
+ shape,
2034
+ color: node.hologram?.color || DEFAULT_CREATE_COLOR,
2035
+ size: node.hologram?.size || DEFAULT_CREATE_SIZE,
2036
+ glow: node.hologram?.glow !== false,
2037
+ interactive: node.hologram?.interactive !== false
2038
+ };
2039
+ ctx.spatialMemory.set(name, position);
2040
+ ctx.createParticleEffect(`${name}_create`, position, hologram.color, CREATE_PARTICLE_COUNT);
2041
+ logger.info("Create command executed", { shape, name, position });
2042
+ return { created: name, shape, hologram, position };
2043
+ }
2044
+ async function executeAnimateCommand(target, tokens, _node, ctx) {
2045
+ const property = tokens[0] || DEFAULT_ANIMATE_PROPERTY;
2046
+ const duration = parseInt(tokens[1] || String(DEFAULT_ANIMATE_DURATION_MS), 10);
2047
+ const animation = {
2048
+ target,
2049
+ property,
2050
+ from: 0,
2051
+ to: 1,
2052
+ duration,
2053
+ startTime: Date.now(),
2054
+ easing: "ease-in-out"
2055
+ };
2056
+ ctx.animations.set(`${target}_${property}`, animation);
2057
+ logger.info("Animate command executed", { target, property, duration });
2058
+ return { animating: target, animation };
2059
+ }
2060
+ async function executePulseCommand(target, tokens, _node, ctx) {
2061
+ const duration = parseInt(tokens[0] || String(DEFAULT_PULSE_DURATION_MS), 10);
2062
+ const position = ctx.spatialMemory.get(target) || [0, 0, 0];
2063
+ ctx.createParticleEffect(`${target}_pulse`, position, PULSE_COLOR, PULSE_PARTICLE_COUNT);
2064
+ const animation = {
2065
+ target,
2066
+ property: "scale",
2067
+ from: PULSE_SCALE_FROM,
2068
+ to: PULSE_SCALE_TO,
2069
+ duration,
2070
+ startTime: Date.now(),
2071
+ easing: "sine",
2072
+ yoyo: true,
2073
+ loop: true
2074
+ };
2075
+ ctx.animations.set(`${target}_pulse`, animation);
2076
+ logger.info("Pulse command executed", { target, duration });
2077
+ return { pulsing: target, duration };
2078
+ }
2079
+ async function executeMoveCommand(target, tokens, _node, ctx) {
2080
+ const x = parseFloat(tokens[0] || "0");
2081
+ const y = parseFloat(tokens[1] || "0");
2082
+ const z = parseFloat(tokens[2] || "0");
2083
+ const position = [x, y, z];
2084
+ const current = ctx.spatialMemory.get(target);
2085
+ if (current) {
2086
+ ctx.spatialMemory.set(target, position);
2087
+ ctx.createConnectionStream(target, `${target}_move`, current, position, "movement");
2088
+ } else {
2089
+ ctx.spatialMemory.set(target, position);
2090
+ }
2091
+ logger.info("Move command executed", { target, position });
2092
+ return { moved: target, to: position };
2093
+ }
2094
+ async function executeDeleteCommand(target, _node, ctx) {
2095
+ const position = ctx.spatialMemory.get(target);
2096
+ if (position) {
2097
+ ctx.createParticleEffect(`${target}_delete`, position, DELETE_COLOR, DELETE_PARTICLE_COUNT);
2098
+ ctx.spatialMemory.delete(target);
2099
+ }
2100
+ logger.info("Delete command executed", { target });
2101
+ return { deleted: target };
2102
+ }
2103
+
2104
+ // src/runtime/pattern-match.ts
2105
+ var WILDCARD_PATTERNS = /* @__PURE__ */ new Set(["_", "else", "default"]);
2106
+ var TYPE_PATTERNS = {
2107
+ string: (v) => typeof v === "string",
2108
+ number: (v) => typeof v === "number",
2109
+ boolean: (v) => typeof v === "boolean",
2110
+ array: (v) => Array.isArray(v),
2111
+ object: (v) => typeof v === "object" && v !== null
2112
+ };
2113
+ function patternMatches(pattern, value) {
2114
+ if (typeof pattern === "string" && WILDCARD_PATTERNS.has(pattern)) {
2115
+ return true;
2116
+ }
2117
+ if (pattern === value) {
2118
+ return true;
2119
+ }
2120
+ if (typeof pattern === "string" && pattern in TYPE_PATTERNS) {
2121
+ return TYPE_PATTERNS[pattern](value);
2122
+ }
2123
+ if (Array.isArray(pattern) && pattern.length === 2) {
2124
+ const [min, max] = pattern;
2125
+ if (typeof value === "number" && typeof min === "number" && typeof max === "number" && value >= min && value <= max) {
2126
+ return true;
2127
+ }
2128
+ }
2129
+ return false;
2130
+ }
2131
+
2132
+ // src/runtime/control-flow.ts
2133
+ var WHILE_MAX_ITERATIONS = 1e4;
2134
+ async function executeForLoop(node, ctx) {
2135
+ const startTime = Date.now();
2136
+ const { variable, iterable, body } = node;
2137
+ try {
2138
+ const collection = ctx.evaluateExpression(String(iterable));
2139
+ if (!Array.isArray(collection) && typeof collection !== "object") {
2140
+ return {
2141
+ success: false,
2142
+ error: `Cannot iterate over non-iterable: ${typeof collection}`,
2143
+ executionTime: Date.now() - startTime
2144
+ };
2145
+ }
2146
+ const items = Array.isArray(collection) ? collection : collection && typeof collection === "object" ? Object.entries(collection) : [];
2147
+ let lastResult = { success: true, output: null };
2148
+ for (const item of items) {
2149
+ ctx.variables.set(variable, item);
2150
+ for (const bodyNode of body) {
2151
+ lastResult = await ctx.executeNode(bodyNode);
2152
+ if (!lastResult.success) break;
2153
+ }
2154
+ if (!lastResult.success) break;
2155
+ }
2156
+ ctx.variables.delete(variable);
2157
+ return {
2158
+ success: true,
2159
+ output: lastResult.output,
2160
+ executionTime: Date.now() - startTime
2161
+ };
2162
+ } catch (error) {
2163
+ return {
2164
+ success: false,
2165
+ error: `For loop error: ${error instanceof Error ? error.message : String(error)}`,
2166
+ executionTime: Date.now() - startTime
2167
+ };
2168
+ }
2169
+ }
2170
+ async function executeForEachLoop(node, ctx) {
2171
+ return executeForLoop(
2172
+ { variable: node.variable, iterable: node.collection, body: node.body },
2173
+ ctx
2174
+ );
2175
+ }
2176
+ async function executeWhileLoop(node, ctx) {
2177
+ const startTime = Date.now();
2178
+ const { condition, body } = node;
2179
+ try {
2180
+ let iterations = 0;
2181
+ let lastResult = { success: true, output: null };
2182
+ while (ctx.evaluateCondition(String(condition))) {
2183
+ iterations++;
2184
+ if (iterations > WHILE_MAX_ITERATIONS) {
2185
+ return {
2186
+ success: false,
2187
+ error: `While loop exceeded maximum iterations (${WHILE_MAX_ITERATIONS})`,
2188
+ executionTime: Date.now() - startTime
2189
+ };
2190
+ }
2191
+ for (const bodyNode of body) {
2192
+ lastResult = await ctx.executeNode(bodyNode);
2193
+ if (!lastResult.success) break;
2194
+ }
2195
+ if (!lastResult.success) break;
2196
+ }
2197
+ return {
2198
+ success: true,
2199
+ output: lastResult.output,
2200
+ executionTime: Date.now() - startTime
2201
+ };
2202
+ } catch (error) {
2203
+ return {
2204
+ success: false,
2205
+ error: `While loop error: ${error instanceof Error ? error.message : String(error)}`,
2206
+ executionTime: Date.now() - startTime
2207
+ };
2208
+ }
2209
+ }
2210
+ async function executeIfStatement(node, ctx) {
2211
+ const startTime = Date.now();
2212
+ const { condition, body, elseBody } = node;
2213
+ try {
2214
+ const conditionResult = ctx.evaluateCondition(String(condition));
2215
+ const branchToExecute = conditionResult ? body : elseBody || [];
2216
+ let lastResult = { success: true, output: null };
2217
+ for (const bodyNode of branchToExecute) {
2218
+ lastResult = await ctx.executeNode(bodyNode);
2219
+ if (!lastResult.success) break;
2220
+ }
2221
+ return {
2222
+ success: true,
2223
+ output: lastResult.output,
2224
+ executionTime: Date.now() - startTime
2225
+ };
2226
+ } catch (error) {
2227
+ return {
2228
+ success: false,
2229
+ error: `If statement error: ${error instanceof Error ? error.message : String(error)}`,
2230
+ executionTime: Date.now() - startTime
2231
+ };
2232
+ }
2233
+ }
2234
+ async function executeMatch(node, ctx) {
2235
+ const startTime = Date.now();
2236
+ const { subject, cases } = node;
2237
+ try {
2238
+ const subjectValue = ctx.evaluateExpression(String(subject));
2239
+ for (const matchCase of cases || []) {
2240
+ const patternValue = ctx.evaluateExpression(String(matchCase.pattern));
2241
+ if (patternMatches(patternValue, subjectValue)) {
2242
+ if (matchCase.guard && !ctx.evaluateCondition(String(matchCase.guard))) {
2243
+ continue;
2244
+ }
2245
+ if (Array.isArray(matchCase.body)) {
2246
+ let lastResult = { success: true, output: null };
2247
+ for (const bodyNode of matchCase.body) {
2248
+ lastResult = await ctx.executeNode(bodyNode);
2249
+ if (!lastResult.success) break;
2250
+ }
2251
+ return lastResult;
2252
+ } else {
2253
+ const result = ctx.evaluateExpression(String(matchCase.body));
2254
+ return { success: true, output: result, executionTime: Date.now() - startTime };
2255
+ }
2256
+ }
2257
+ }
2258
+ return {
2259
+ success: false,
2260
+ error: "No pattern matched",
2261
+ executionTime: Date.now() - startTime
2262
+ };
2263
+ } catch (error) {
2264
+ return {
2265
+ success: false,
2266
+ error: `Match expression error: ${error instanceof Error ? error.message : String(error)}`,
2267
+ executionTime: Date.now() - startTime
2268
+ };
2269
+ }
2270
+ }
2271
+
2272
+ // src/runtime/holo-expression.ts
2273
+ var GET_MEMBER_PATH_CACHE = /* @__PURE__ */ new Map();
2274
+ var GET_MEMBER_PATH_MAX = 500;
2275
+ function getMemberPath(expr) {
2276
+ const key = JSON.stringify(expr);
2277
+ const cached = GET_MEMBER_PATH_CACHE.get(key);
2278
+ if (cached !== void 0 || GET_MEMBER_PATH_CACHE.has(key)) {
2279
+ return cached ?? null;
2280
+ }
2281
+ let result = null;
2282
+ if (expr.type === "Identifier") {
2283
+ result = expr.name;
2284
+ } else if (expr.type === "MemberExpression") {
2285
+ const parentPath = getMemberPath(expr.object);
2286
+ if (parentPath) result = `${parentPath}.${expr.property}`;
2287
+ }
2288
+ if (GET_MEMBER_PATH_CACHE.size >= GET_MEMBER_PATH_MAX) {
2289
+ const firstKey = GET_MEMBER_PATH_CACHE.keys().next().value;
2290
+ if (firstKey !== void 0) GET_MEMBER_PATH_CACHE.delete(firstKey);
2291
+ }
2292
+ GET_MEMBER_PATH_CACHE.set(key, result);
2293
+ return result;
2294
+ }
2295
+ async function evaluateHoloExpression(expr, scopeOverride, ctx) {
2296
+ switch (expr.type) {
2297
+ case "Literal":
2298
+ return expr.value;
2299
+ case "Identifier":
2300
+ return ctx.getVariable(expr.name, scopeOverride);
2301
+ case "MemberExpression": {
2302
+ const obj = await evaluateHoloExpression(expr.object, scopeOverride, ctx);
2303
+ if (obj && typeof obj === "object") {
2304
+ return obj[expr.property];
2305
+ }
2306
+ return void 0;
2307
+ }
2308
+ case "CallExpression": {
2309
+ if (!Array.isArray(expr.arguments)) {
2310
+ console.error("[CRITICAL] arguments is not an array for", JSON.stringify(expr));
2311
+ return void 0;
2312
+ }
2313
+ const callee = await evaluateHoloExpression(expr.callee, scopeOverride, ctx);
2314
+ const args = await Promise.all(
2315
+ expr.arguments.map(
2316
+ (a) => evaluateHoloExpression(a, scopeOverride, ctx)
2317
+ )
2318
+ );
2319
+ if (typeof callee === "function") {
2320
+ return callee(...args);
2321
+ }
2322
+ if (expr.callee.type === "Identifier") {
2323
+ const result = await ctx.callFunction(expr.callee.name, args);
2324
+ return result.output;
2325
+ }
2326
+ return void 0;
2327
+ }
2328
+ case "BinaryExpression": {
2329
+ const left = await evaluateHoloExpression(expr.left, scopeOverride, ctx);
2330
+ const right = await evaluateHoloExpression(expr.right, scopeOverride, ctx);
2331
+ switch (expr.operator) {
2332
+ case "+":
2333
+ return Number(left) + Number(right);
2334
+ case "-":
2335
+ return Number(left) - Number(right);
2336
+ case "*":
2337
+ return Number(left) * Number(right);
2338
+ case "/":
2339
+ return Number(left) / Number(right);
2340
+ case "==":
2341
+ return left == right;
2342
+ case "===":
2343
+ return left === right;
2344
+ case "!=":
2345
+ return left != right;
2346
+ case "!==":
2347
+ return left !== right;
2348
+ case "<":
2349
+ return Number(left) < Number(right);
2350
+ case ">":
2351
+ return Number(left) > Number(right);
2352
+ case "<=":
2353
+ return Number(left) <= Number(right);
2354
+ case ">=":
2355
+ return Number(left) >= Number(right);
2356
+ case "&&":
2357
+ return left && right;
2358
+ case "||":
2359
+ return left || right;
2360
+ default:
2361
+ return void 0;
2362
+ }
2363
+ }
2364
+ case "ConditionalExpression": {
2365
+ const test = await evaluateHoloExpression(expr.test, scopeOverride, ctx);
2366
+ return test ? await evaluateHoloExpression(expr.consequent, scopeOverride, ctx) : await evaluateHoloExpression(expr.alternate, scopeOverride, ctx);
2367
+ }
2368
+ case "UpdateExpression": {
2369
+ const val = await evaluateHoloExpression(expr.argument, scopeOverride, ctx);
2370
+ const newVal = expr.operator === "++" ? val + 1 : val - 1;
2371
+ const path = getMemberPath(expr.argument);
2372
+ if (path) {
2373
+ ctx.setVariable(path, newVal, scopeOverride);
2374
+ }
2375
+ return expr.prefix ? newVal : val;
2376
+ }
2377
+ case "ArrayExpression": {
2378
+ return await Promise.all(
2379
+ expr.elements.map((e) => evaluateHoloExpression(e, scopeOverride, ctx))
2380
+ );
2381
+ }
2382
+ case "ObjectExpression": {
2383
+ const obj = {};
2384
+ for (const prop of expr.properties) {
2385
+ obj[prop.key] = await evaluateHoloExpression(prop.value, scopeOverride, ctx);
2386
+ }
2387
+ return obj;
2388
+ }
2389
+ default:
2390
+ return void 0;
2391
+ }
2392
+ }
2393
+
2394
+ // src/events/EventBus.ts
2395
+ var EventBus = class {
2396
+ constructor() {
2397
+ this.listeners = /* @__PURE__ */ new Map();
2398
+ this.history = [];
2399
+ this.maxHistory = 100;
2400
+ this.nextId = 0;
2401
+ this.paused = false;
2402
+ }
2403
+ /**
2404
+ * Subscribe to an event.
2405
+ */
2406
+ on(event, callback, priority = 0) {
2407
+ const id = this.nextId++;
2408
+ const list = this.listeners.get(event) || [];
2409
+ list.push({ callback, priority, once: false, id });
2410
+ list.sort((a, b) => b.priority - a.priority);
2411
+ this.listeners.set(event, list);
2412
+ return id;
2413
+ }
2414
+ /**
2415
+ * Subscribe to an event once (auto-removes after first fire).
2416
+ */
2417
+ once(event, callback, priority = 0) {
2418
+ const id = this.nextId++;
2419
+ const list = this.listeners.get(event) || [];
2420
+ list.push({ callback, priority, once: true, id });
2421
+ list.sort((a, b) => b.priority - a.priority);
2422
+ this.listeners.set(event, list);
2423
+ return id;
2424
+ }
2425
+ /**
2426
+ * Unsubscribe by listener ID.
2427
+ */
2428
+ off(listenerId) {
2429
+ for (const [event, list] of this.listeners) {
2430
+ const idx = list.findIndex((l) => l.id === listenerId);
2431
+ if (idx !== -1) {
2432
+ list.splice(idx, 1);
2433
+ return;
2434
+ }
2435
+ }
2436
+ }
2437
+ /**
2438
+ * Unsubscribe all listeners for an event.
2439
+ */
2440
+ offAll(event) {
2441
+ this.listeners.delete(event);
2442
+ }
2443
+ /**
2444
+ * Emit an event to all subscribers.
2445
+ */
2446
+ emit(event, data) {
2447
+ if (this.paused) return;
2448
+ this.history.push({ event, data, timestamp: Date.now() });
2449
+ if (this.history.length > this.maxHistory) this.history.shift();
2450
+ const list = this.listeners.get(event);
2451
+ if (list) {
2452
+ const toRemove = [];
2453
+ for (const listener of list) {
2454
+ listener.callback(data);
2455
+ if (listener.once) toRemove.push(listener.id);
2456
+ }
2457
+ for (const id of toRemove) {
2458
+ const idx = list.findIndex((l) => l.id === id);
2459
+ if (idx !== -1) list.splice(idx, 1);
2460
+ }
2461
+ }
2462
+ if (event !== "*") {
2463
+ const wildcardList = this.listeners.get("*");
2464
+ if (wildcardList) {
2465
+ for (const listener of wildcardList) {
2466
+ listener.callback({ event, data });
2467
+ }
2468
+ }
2469
+ }
2470
+ }
2471
+ /**
2472
+ * Get event history.
2473
+ */
2474
+ getHistory() {
2475
+ return [...this.history];
2476
+ }
2477
+ /**
2478
+ * Get listener count for an event.
2479
+ */
2480
+ listenerCount(event) {
2481
+ return this.listeners.get(event)?.length || 0;
2482
+ }
2483
+ /**
2484
+ * Pause/resume event emission.
2485
+ */
2486
+ setPaused(paused) {
2487
+ this.paused = paused;
2488
+ }
2489
+ /**
2490
+ * Clear all listeners and history.
2491
+ */
2492
+ clear() {
2493
+ this.listeners.clear();
2494
+ this.history = [];
2495
+ }
2496
+ };
2497
+ var sharedBus = null;
2498
+ function getSharedEventBus() {
2499
+ if (!sharedBus) sharedBus = new EventBus();
2500
+ return sharedBus;
2501
+ }
2502
+ function setSharedEventBus(bus) {
2503
+ sharedBus = bus;
2504
+ }
2505
+
2506
+ // src/monitoring/telemetry.ts
2507
+ var TelemetryRegistry = class {
2508
+ constructor() {
2509
+ this.measurements = [];
2510
+ this.maxHistory = 1e4;
2511
+ }
2512
+ /**
2513
+ * Increments a monotonic counter (e.g., total_nodes_executed)
2514
+ */
2515
+ incrementCounter(name, value = 1, labels) {
2516
+ this.measurements.push({
2517
+ name,
2518
+ type: "counter",
2519
+ value,
2520
+ labels,
2521
+ timestamp: Date.now()
2522
+ });
2523
+ if (this.measurements.length > this.maxHistory) this.measurements.shift();
2524
+ }
2525
+ /**
2526
+ * Records an instantaneous value (e.g., active_agents)
2527
+ */
2528
+ setGauge(name, value, labels) {
2529
+ this.measurements.push({
2530
+ name,
2531
+ type: "gauge",
2532
+ value,
2533
+ labels,
2534
+ timestamp: Date.now()
2535
+ });
2536
+ if (this.measurements.length > this.maxHistory) this.measurements.shift();
2537
+ }
2538
+ /**
2539
+ * Wraps an async function and records its execution latency into a histogram.
2540
+ */
2541
+ async measureLatency(name, fn, labels) {
2542
+ const start = performance.now();
2543
+ try {
2544
+ return await fn();
2545
+ } finally {
2546
+ const duration = performance.now() - start;
2547
+ this.measurements.push({
2548
+ name,
2549
+ type: "histogram",
2550
+ value: duration,
2551
+ labels,
2552
+ timestamp: Date.now()
2553
+ });
2554
+ if (this.measurements.length > this.maxHistory) this.measurements.shift();
2555
+ if (duration > 500) {
2556
+ this.measurements.push({
2557
+ name: "slo_violation_count",
2558
+ type: "counter",
2559
+ value: 1,
2560
+ labels: { ...labels, metric_name: name, threshold: "500ms" },
2561
+ timestamp: Date.now()
2562
+ });
2563
+ }
2564
+ }
2565
+ }
2566
+ /**
2567
+ * Snapshots current aggregations for dashboard export.
2568
+ */
2569
+ getSnapshot() {
2570
+ const snapshot = { counters: {}, histograms: {}, gauges: {} };
2571
+ const histAggregations = {};
2572
+ for (const m of this.measurements) {
2573
+ const key = m.labels ? `${m.name}{${JSON.stringify(m.labels)}}` : m.name;
2574
+ if (m.type === "counter") {
2575
+ snapshot.counters[key] = (snapshot.counters[key] || 0) + m.value;
2576
+ } else if (m.type === "gauge") {
2577
+ snapshot.gauges[key] = m.value;
2578
+ } else if (m.type === "histogram") {
2579
+ if (!histAggregations[key]) histAggregations[key] = { count: 0, sum: 0, max: 0 };
2580
+ histAggregations[key].count++;
2581
+ histAggregations[key].sum += m.value;
2582
+ if (m.value > histAggregations[key].max) histAggregations[key].max = m.value;
2583
+ }
2584
+ }
2585
+ for (const [key, agg] of Object.entries(histAggregations)) {
2586
+ snapshot.histograms[key] = {
2587
+ count: agg.count,
2588
+ sum: agg.sum,
2589
+ avg: agg.count > 0 ? agg.sum / agg.count : 0,
2590
+ max: agg.max
2591
+ };
2592
+ }
2593
+ return snapshot;
2594
+ }
2595
+ };
2596
+ var telemetry = new TelemetryRegistry();
2597
+ function stringProperty(value) {
2598
+ return typeof value === "string" ? value : void 0;
2599
+ }
2600
+ function createDetachedParentRuntime() {
2601
+ const rootScope = { variables: /* @__PURE__ */ new Map() };
2602
+ return {
2603
+ async callFunction(functionName) {
2604
+ return {
2605
+ success: false,
2606
+ error: `Detached hydrated agent cannot call function: ${functionName}`
2607
+ };
2608
+ },
2609
+ getRootScope: () => rootScope,
2610
+ getVariable: () => void 0,
2611
+ async executeProgram() {
2612
+ return [{ success: false, error: "Detached hydrated agent cannot execute programs" }];
2613
+ },
2614
+ emit: async () => void 0,
2615
+ async executeHoloProgram() {
2616
+ return [{ success: false, error: "Detached hydrated agent cannot execute Holo programs" }];
2617
+ },
2618
+ evaluateExpression: () => void 0
2619
+ };
2620
+ }
2621
+ function textToEmbeddingFloat32(text, dim) {
2622
+ const out = new Float32Array(dim);
2623
+ let h = 5381;
2624
+ for (let i = 0; i < text.length; i++) {
2625
+ h = Math.imul(h, 33) ^ text.charCodeAt(i);
2626
+ h = h >>> 0;
2627
+ }
2628
+ for (let d = 0; d < dim; d++) {
2629
+ h = Math.imul(h, 1664525) + 1013904223;
2630
+ h = h >>> 0;
2631
+ out[d] = h / 4294967296 * 2 - 1;
2632
+ }
2633
+ return out;
2634
+ }
2635
+ var HoloScriptAgentRuntime = class _HoloScriptAgentRuntime {
2636
+ /**
2637
+ * Creates a new HoloScript agent runtime instance.
2638
+ *
2639
+ * @param agentNode - The OrbNode representing the agent template
2640
+ * @param parentRuntime - The parent runtime providing global context
2641
+ *
2642
+ * @example
2643
+ * ```typescript
2644
+ * const runtime = new HoloScriptAgentRuntime(miningAgentNode, mainRuntime);
2645
+ * ```
2646
+ */
2647
+ constructor(agentNode, parentRuntime) {
2648
+ this.runningActions = /* @__PURE__ */ new Map();
2649
+ this.isDestroyed = false;
2650
+ // Episodic Memory & Semantic Extraction (Phase 7)
2651
+ this.rawEpisodes = [];
2652
+ this.semanticFacts = [];
2653
+ this.consolidationInterval = null;
2654
+ // JEPA action-planning loop (Phase 8)
2655
+ // Default latentDim=64, condDim=16 (action conditioning). Caller can swap
2656
+ // weights externally via this.jepaPredictor.setWeights() after training.
2657
+ this.jepaPredictor = new JEPAPredictor({ latentDim: 64, condDim: 16 });
2658
+ this.jepaObjectiveNode = {};
2659
+ this.jepaObjectiveAttached = false;
2660
+ if (!agentNode || !parentRuntime) {
2661
+ return;
2662
+ }
2663
+ this.agentNode = agentNode;
2664
+ this.parentRuntime = parentRuntime;
2665
+ this.localState = new ReactiveState(agentNode.properties || {});
2666
+ this.bindDurableIdentity(agentNode.properties || {});
2667
+ this.initializeAgentContext();
2668
+ }
2669
+ /**
2670
+ * Rehydrate an agent identity from substrate-anchored seed data without relying
2671
+ * on the previous neural map. Reactive state, running actions, and episodes
2672
+ * start empty; only durable identity fields and semantic facts are replayed.
2673
+ */
2674
+ static hydrate(seed, parentRuntime = createDetachedParentRuntime()) {
2675
+ const agentNode = {
2676
+ type: "orb",
2677
+ id: seed.handle,
2678
+ name: seed.handle,
2679
+ template: seed.brainCompositionRef,
2680
+ properties: {},
2681
+ directives: []
2682
+ };
2683
+ const runtime = new _HoloScriptAgentRuntime(agentNode, parentRuntime);
2684
+ runtime.applySeed(seed);
2685
+ return runtime;
2686
+ }
2687
+ /**
2688
+ * Reset the runtime for pooling reuse with new agent configuration.
2689
+ *
2690
+ * @param agentNode - New agent node to bind to this runtime
2691
+ * @param parentRuntime - Parent runtime for global context
2692
+ */
2693
+ reset(agentNode, parentRuntime) {
2694
+ this.agentNode = agentNode;
2695
+ this.parentRuntime = parentRuntime;
2696
+ this.localState = new ReactiveState(agentNode.properties || {});
2697
+ this.runningActions.clear();
2698
+ this.isDestroyed = false;
2699
+ this.bindDurableIdentity(agentNode.properties || {});
2700
+ this.initializeAgentContext();
2701
+ }
2702
+ bindDurableIdentity(properties) {
2703
+ this.wallet = stringProperty(properties.wallet);
2704
+ this.handle = stringProperty(properties.handle) ?? this.agentNode.name;
2705
+ this.brainCompositionRef = stringProperty(properties.brainCompositionRef) ?? this.agentNode.template ?? this.agentNode.name;
2706
+ this.memorySnapshotHash = stringProperty(properties.memorySnapshotHash);
2707
+ this.resumeStepId = stringProperty(properties.resumeStepId);
2708
+ }
2709
+ applySeed(seed) {
2710
+ this.wallet = seed.wallet;
2711
+ this.handle = seed.handle;
2712
+ this.brainCompositionRef = seed.brainCompositionRef;
2713
+ this.memorySnapshotHash = seed.memorySnapshotHash;
2714
+ this.resumeStepId = seed.resumeStepId;
2715
+ this.semanticFacts = [...seed.semanticFacts ?? []];
2716
+ this.rawEpisodes = [];
2717
+ this.runningActions.clear();
2718
+ }
2719
+ durable() {
2720
+ return {
2721
+ wallet: this.wallet,
2722
+ handle: this.handle,
2723
+ brainCompositionRef: this.brainCompositionRef,
2724
+ memorySnapshotHash: this.memorySnapshotHash,
2725
+ resumeStepId: this.resumeStepId,
2726
+ semanticFacts: [...this.semanticFacts],
2727
+ annotations: {
2728
+ wallet: "durable",
2729
+ handle: "durable",
2730
+ brainCompositionRef: "durable",
2731
+ memorySnapshotHash: "durable",
2732
+ resumeStepId: "durable",
2733
+ semanticFacts: "durable"
2734
+ }
2735
+ };
2736
+ }
2737
+ losable() {
2738
+ return {
2739
+ reactiveState: this.localState.getSnapshot(),
2740
+ runningActions: Array.from(this.runningActions.keys()),
2741
+ rawEpisodes: [...this.rawEpisodes],
2742
+ annotations: {
2743
+ reactiveState: "losable",
2744
+ runningActions: "losable",
2745
+ rawEpisodes: "losable"
2746
+ }
2747
+ };
2748
+ }
2749
+ /**
2750
+ * Initialize the agent's execution context and memory consolidation.
2751
+ */
2752
+ initializeAgentContext() {
2753
+ ({
2754
+ id: this.agentNode.id || this.agentNode.name,
2755
+ type: this.agentNode.type,
2756
+ state: this.localState.getSnapshot(),
2757
+ properties: this.agentNode.properties});
2758
+ if (!this.consolidationInterval) {
2759
+ this.consolidationInterval = setInterval(() => this.consolidateMemory(), 3e4);
2760
+ }
2761
+ }
2762
+ /**
2763
+ * Records a raw episodic event into the agent's short-term history queue.
2764
+ *
2765
+ * @param action - The action that was performed
2766
+ * @param outcome - The result or outcome of the action
2767
+ * @param entitiesInvolved - List of entity IDs that were involved in the episode
2768
+ *
2769
+ * @example
2770
+ * ```typescript
2771
+ * agentRuntime.recordEpisode('mine_ore', 'collected 5 iron ore', ['ore_deposit_1', 'inventory']);
2772
+ * ```
2773
+ */
2774
+ recordEpisode(action, outcome, entitiesInvolved) {
2775
+ this.rawEpisodes.push({
2776
+ id: `ep_${Date.now()}_${Math.random().toString(36).substring(7)}`,
2777
+ timestamp: Date.now(),
2778
+ action,
2779
+ outcome,
2780
+ entitiesInvolved
2781
+ });
2782
+ }
2783
+ /**
2784
+ * Internal idle tick leveraging the MemoryConsolidator subsystem to offload processing constraints.
2785
+ */
2786
+ consolidateMemory() {
2787
+ if (this.isDestroyed || this.rawEpisodes.length < 5) return;
2788
+ const { newFacts, prunedEpisodes } = MemoryConsolidator.compressEpisodes(this.rawEpisodes);
2789
+ if (newFacts.length > 0) {
2790
+ this.semanticFacts.push(...newFacts);
2791
+ this.rawEpisodes = this.rawEpisodes.filter((e) => !prunedEpisodes.includes(e.id));
2792
+ }
2793
+ this.semanticFacts = MemoryConsolidator.pruneStaleFacts(this.semanticFacts);
2794
+ }
2795
+ /**
2796
+ * Lazily attach the JEPAObjective trait on first use so constructor stays fast.
2797
+ */
2798
+ ensureJepaObjectiveAttached() {
2799
+ if (!this.jepaObjectiveAttached) {
2800
+ const config = this.getJepaObjectiveConfig();
2801
+ jepObjectiveHandler.onAttach?.(
2802
+ this.jepaObjectiveNode,
2803
+ config,
2804
+ this.buildJepaTraitContext()
2805
+ );
2806
+ this.jepaObjectiveAttached = true;
2807
+ }
2808
+ }
2809
+ getJepaObjectiveConfig() {
2810
+ const config = jepObjectiveHandler.defaultConfig;
2811
+ if (!config) {
2812
+ throw new Error("JEPAObjective handler defaultConfig is required for offline training");
2813
+ }
2814
+ return config;
2815
+ }
2816
+ /**
2817
+ * Build a minimal TraitContext for the offline JEPA training call.
2818
+ * Losses are logged via the runtime logger; no external emit dependency.
2819
+ */
2820
+ buildJepaTraitContext() {
2821
+ const agentName = this.agentNode?.name ?? "agent";
2822
+ return {
2823
+ vr: null,
2824
+ physics: null,
2825
+ audio: null,
2826
+ haptics: null,
2827
+ emit: (eventName, payload) => {
2828
+ if (eventName === "jepa:loss") {
2829
+ const p = payload;
2830
+ logger.info(`[JEPA:${agentName}] step=${p.step} totalLoss=${p.totalLoss.toFixed(4)}`);
2831
+ } else if (eventName === "jepa:error") {
2832
+ const e = payload;
2833
+ logger.warn(`[JEPA:${agentName}] error code=${e.code} ${e.message}`);
2834
+ }
2835
+ },
2836
+ getState: () => ({}),
2837
+ setState: () => {
2838
+ },
2839
+ getScaleMultiplier: () => 1,
2840
+ setScaleContext: () => {
2841
+ }
2842
+ };
2843
+ }
2844
+ /**
2845
+ * Store a JEPA training episode and trigger an offline JEPAObjective training
2846
+ * step. Called after each executeAction() to ensure every agent run generates
2847
+ * JEPA training data automatically.
2848
+ *
2849
+ * The (state, action, outcome) tuple is encoded as a `jepa:encode_pair` event
2850
+ * where context = JSON.stringify(state + action) and targetVec is derived from
2851
+ * the outcome string deterministically (same hash used by JEPAPredictor.plan).
2852
+ */
2853
+ trainJepaOffline(stateBefore, action, outcome) {
2854
+ this.ensureJepaObjectiveAttached();
2855
+ const contextStr = JSON.stringify({ state: stateBefore, action });
2856
+ const config = this.getJepaObjectiveConfig();
2857
+ const latentDim = config.latentDim;
2858
+ const outcomeStr = outcome.success ? `success:${String(outcome.output ?? "")}` : `failure:${String(outcome.error ?? "")}`;
2859
+ const targetVec = textToEmbeddingFloat32(outcomeStr, latentDim);
2860
+ jepObjectiveHandler.onEvent?.(
2861
+ this.jepaObjectiveNode,
2862
+ config,
2863
+ this.buildJepaTraitContext(),
2864
+ {
2865
+ type: "jepa:encode_pair",
2866
+ context: contextStr,
2867
+ targetVec,
2868
+ conditioning: void 0
2869
+ }
2870
+ );
2871
+ }
2872
+ /**
2873
+ * Lightweight fork-detection heuristic for runtime adapters.
2874
+ * Scans brain composition ref, template, and string properties for
2875
+ * HS010-blocked keywords, unknown compiler versions, non-canonical imports,
2876
+ * and no-op security traits. Self-contained (no mcp-server imports).
2877
+ */
2878
+ checkForkSandbox() {
2879
+ const sources = [];
2880
+ if (this.brainCompositionRef) sources.push(this.brainCompositionRef);
2881
+ if (this.agentNode.template) sources.push(this.agentNode.template);
2882
+ for (const val of Object.values(this.agentNode.properties || {})) {
2883
+ if (typeof val === "string") sources.push(val);
2884
+ }
2885
+ const directives = this.agentNode.directives;
2886
+ if (directives) {
2887
+ for (const d of directives) {
2888
+ if (typeof d.body === "string") sources.push(d.body);
2889
+ }
2890
+ }
2891
+ const blockedKeywords = [
2892
+ "process",
2893
+ "fs",
2894
+ "require",
2895
+ "eval",
2896
+ "exec",
2897
+ "spawn",
2898
+ "child_process",
2899
+ "constructor",
2900
+ "prototype",
2901
+ "globalThis"
2902
+ ];
2903
+ const canonicalVersions = ["7.0.0", "6.0.2", "6.0.1", "6.0.0"];
2904
+ for (const src of sources) {
2905
+ for (const kw of blockedKeywords) {
2906
+ if (new RegExp(`\\b${kw}\\b`).test(src)) {
2907
+ return { allowed: false, reason: `HS010-blocked-keyword:${kw}` };
2908
+ }
2909
+ }
2910
+ const versionMatch = src.match(/@compiler\s+version\s+["']?([\d.]+)["']?/i);
2911
+ if (versionMatch) {
2912
+ const claimed = versionMatch[1];
2913
+ if (!canonicalVersions.includes(claimed)) {
2914
+ return { allowed: false, reason: `unknown-compiler-version:${claimed}` };
2915
+ }
2916
+ }
2917
+ if (/\bfrom\s+['"](?!@holoscript\/)[@\w\/-]+['"]/.test(src)) {
2918
+ return { allowed: false, reason: "non-canonical-import" };
2919
+ }
2920
+ if (/(?:^|\s)@security_sandbox\b/.test(src) && !/\bimport\s+.*security-sandbox/.test(src)) {
2921
+ return { allowed: false, reason: "no-op-security-trait" };
2922
+ }
2923
+ }
2924
+ return { allowed: true };
2925
+ }
2926
+ /**
2927
+ * Execute an action (method) defined on the agent template.
2928
+ *
2929
+ * @param actionName - Name of the action/method to execute
2930
+ * @param args - Arguments to pass to the action method
2931
+ * @returns Promise resolving to execution result
2932
+ * @throws {Error} When agent is destroyed or action execution fails
2933
+ *
2934
+ * @example
2935
+ * ```typescript
2936
+ * const result = await agentRuntime.executeAction('patrol', ['north_sector']);
2937
+ * if (result.success) {
2938
+ * console.log('Patrol completed:', result.output);
2939
+ * }
2940
+ * ```
2941
+ */
2942
+ async executeAction(actionName, args = []) {
2943
+ if (this.isDestroyed) return { success: false, error: "Agent destroyed" };
2944
+ const forkCheck = this.checkForkSandbox();
2945
+ if (!forkCheck.allowed) {
2946
+ logger.warn(`[Agent:${this.agentNode.name}] ForkSandboxGate blocked action "${actionName}": ${forkCheck.reason}`);
2947
+ return { success: false, error: `ForkSandboxGate: ${forkCheck.reason}` };
2948
+ }
2949
+ const directives = this.agentNode.directives;
2950
+ const action = directives?.find((d) => d.type === "method" && d.name === actionName);
2951
+ if (!action) {
2952
+ return this.parentRuntime.callFunction(actionName, args);
2953
+ }
2954
+ logger.info(`[Agent:${this.agentNode.name}] Executing action: ${actionName}`);
2955
+ const stateBefore = this.localState.getSnapshot();
2956
+ const agentScope = {
2957
+ variables: /* @__PURE__ */ new Map(),
2958
+ parent: this.parentRuntime.getRootScope()
2959
+ };
2960
+ const agentData = this.parentRuntime.getVariable(this.agentNode.name);
2961
+ if (agentData && !agentData.state) {
2962
+ agentData.state = this.localState.getProxy();
2963
+ }
2964
+ agentScope.variables.set(
2965
+ "this",
2966
+ agentData || {
2967
+ id: this.agentNode.name,
2968
+ state: this.localState.getProxy(),
2969
+ properties: this.agentNode.properties
2970
+ }
2971
+ );
2972
+ if (action.parameters && args) {
2973
+ action.parameters.forEach((param, i) => {
2974
+ agentScope.variables.set(param.name, args[i]);
2975
+ });
2976
+ }
2977
+ let executionResult = { success: false, error: "Action did not complete" };
2978
+ try {
2979
+ if (Array.isArray(action.body)) {
2980
+ const results = await this.parentRuntime.executeHoloProgram(action.body, agentScope);
2981
+ const success = results.every((r) => r.success);
2982
+ executionResult = {
2983
+ success,
2984
+ output: results[results.length - 1]?.output,
2985
+ error: results.find((r) => !r.success)?.error
2986
+ };
2987
+ } else {
2988
+ const results = await this.parentRuntime.executeProgram(action.body, 1);
2989
+ const success = results.every((r) => r.success);
2990
+ executionResult = {
2991
+ success,
2992
+ output: results[results.length - 1]?.output,
2993
+ error: results.find((r) => !r.success)?.error
2994
+ };
2995
+ }
2996
+ } finally {
2997
+ this.runningActions.delete(actionName);
2998
+ }
2999
+ const outcomeStr = executionResult.success ? `success:${String(executionResult.output ?? "")}` : `failure:${String(executionResult.error ?? "")}`;
3000
+ this.recordEpisode(actionName, outcomeStr, [this.agentNode.name]);
3001
+ try {
3002
+ this.trainJepaOffline(stateBefore, actionName, executionResult);
3003
+ } catch (trainErr) {
3004
+ logger.warn(
3005
+ `[JEPA:${this.agentNode.name}] trainJepaOffline error: ${String(trainErr)}`
3006
+ );
3007
+ }
3008
+ return executionResult;
3009
+ }
3010
+ /**
3011
+ * Autonomous 'thinking' cycle using LLM for decision making.
3012
+ *
3013
+ * @param prompt - Optional specific prompt for the LLM, defaults to general decision prompt
3014
+ * @returns Promise resolving to the LLM's decision as a string
3015
+ *
3016
+ * @example
3017
+ * ```typescript
3018
+ * const decision = await agentRuntime.think('Should I retreat or continue attacking?');
3019
+ * console.log('Agent decision:', decision);
3020
+ * ```
3021
+ */
3022
+ async think(prompt) {
3023
+ logger.info(`[Agent:${this.agentNode.name}] Thinking...`);
3024
+ const directives = this.agentNode.directives;
3025
+ const candidateActions = (directives ?? []).filter((d) => d.type === "method" && d.name).map((d) => d.name);
3026
+ let jepaSuggestion;
3027
+ if (candidateActions.length > 0) {
3028
+ const stateSnapshot = JSON.stringify(this.localState.getSnapshot());
3029
+ const planResult = this.jepaPredictor.plan(stateSnapshot, candidateActions);
3030
+ jepaSuggestion = planResult.action;
3031
+ logger.info(
3032
+ `[JEPA:${this.agentNode.name}] plan() \u2192 "${planResult.action}" confidence=${planResult.confidence.toFixed(4)}`
3033
+ );
3034
+ }
3035
+ const effectivePrompt = jepaSuggestion ? `${prompt ?? "Decide the next best action based on current state."} JEPA predictor suggests: "${jepaSuggestion}".` : prompt ?? "Decide the next best action based on current state.";
3036
+ const result = await this.parentRuntime.emit("agent_think", {
3037
+ agentId: this.agentNode.name,
3038
+ context: this.localState.getSnapshot(),
3039
+ prompt: effectivePrompt,
3040
+ jepaSuggestion
3041
+ });
3042
+ return result?.decision || jepaSuggestion || "No clear decision made.";
3043
+ }
3044
+ /**
3045
+ * Handle lifecycle events for this specific agent.
3046
+ *
3047
+ * @param eventType - The type of event being handled
3048
+ * @param data - Event data to bind to the execution scope
3049
+ *
3050
+ * @example
3051
+ * ```typescript
3052
+ * await agentRuntime.onEvent('enemy_spotted', {
3053
+ * enemy: 'orc_warrior',
3054
+ * distance: 50
3055
+ * });
3056
+ * ```
3057
+ */
3058
+ async onEvent(eventType, data) {
3059
+ if (this.isDestroyed) return;
3060
+ const directives = this.agentNode.directives;
3061
+ const handler = directives?.find((d) => d.type === "lifecycle" && d.hook === eventType);
3062
+ if (handler) {
3063
+ const eventScope = {
3064
+ variables: /* @__PURE__ */ new Map(),
3065
+ parent: this.parentRuntime.getRootScope()
3066
+ };
3067
+ if (data && typeof data === "object") {
3068
+ for (const [key, val] of Object.entries(data)) {
3069
+ eventScope.variables.set(key, val);
3070
+ }
3071
+ }
3072
+ eventScope.variables.set("eventData", data);
3073
+ directives?.forEach((d) => {
3074
+ if (d.type === "method" && d.name) {
3075
+ eventScope.variables.set(d.name, ((...args) => this.executeAction(d.name, args)));
3076
+ }
3077
+ });
3078
+ const params = handler.parameters;
3079
+ if (params && Array.isArray(params) && data && typeof data === "object") {
3080
+ const dataRecord = data;
3081
+ params.forEach((param) => {
3082
+ if (dataRecord[param.name] !== void 0) {
3083
+ eventScope.variables.set(param.name, dataRecord[param.name]);
3084
+ }
3085
+ });
3086
+ }
3087
+ const agentData = this.parentRuntime.getVariable(this.agentNode.name);
3088
+ if (agentData && !agentData.state) {
3089
+ agentData.state = this.localState.getProxy();
3090
+ }
3091
+ eventScope.variables.set(
3092
+ "this",
3093
+ agentData || {
3094
+ id: this.agentNode.name,
3095
+ state: this.localState.getProxy(),
3096
+ properties: this.agentNode.properties
3097
+ }
3098
+ );
3099
+ try {
3100
+ if (Array.isArray(handler.body)) {
3101
+ await this.parentRuntime.executeHoloProgram(handler.body, eventScope);
3102
+ } else {
3103
+ this.parentRuntime.evaluateExpression(handler.body);
3104
+ }
3105
+ } finally {
3106
+ }
3107
+ }
3108
+ }
3109
+ /**
3110
+ * Clean up the agent runtime, stopping all running processes and timers.
3111
+ */
3112
+ destroy() {
3113
+ this.isDestroyed = true;
3114
+ this.runningActions.clear();
3115
+ if (this.consolidationInterval) {
3116
+ clearInterval(this.consolidationInterval);
3117
+ this.consolidationInterval = null;
3118
+ }
3119
+ logger.info(`[Agent:${this.agentNode?.name ?? "unbound"}] Runtime destroyed.`);
3120
+ }
3121
+ /**
3122
+ * Get the agent's unique identifier.
3123
+ *
3124
+ * @returns The agent's ID or name
3125
+ */
3126
+ get id() {
3127
+ return this.agentNode.id || this.agentNode.name;
3128
+ }
3129
+ /**
3130
+ * Get the agent's current reactive state proxy.
3131
+ *
3132
+ * @returns Proxy object for the agent's state
3133
+ */
3134
+ get state() {
3135
+ return this.localState.getProxy();
3136
+ }
3137
+ /**
3138
+ * Get the agent's current reactive state proxy.
3139
+ *
3140
+ * @returns Proxy object for the agent's state
3141
+ */
3142
+ getState() {
3143
+ return this.localState.getProxy();
3144
+ }
3145
+ };
3146
+
3147
+ // src/extensions/ExtensionRegistry.ts
3148
+ var ExtensionRegistry = class {
3149
+ constructor(runtime) {
3150
+ this.extensions = /* @__PURE__ */ new Map();
3151
+ this.runtime = runtime;
3152
+ }
3153
+ /**
3154
+ * Load an extension into the runtime
3155
+ */
3156
+ loadExtension(extension) {
3157
+ if (this.extensions.has(extension.id)) {
3158
+ logger.warn(`Extension ${extension.id} is already loaded.`);
3159
+ return;
3160
+ }
3161
+ const context = {
3162
+ registerTrait: (name, handler) => {
3163
+ logger.info(`[Extension:${extension.id}] Registering trait: ${name}`);
3164
+ this.runtime.registerTrait(name, handler);
3165
+ },
3166
+ registerFunction: (name, fn) => {
3167
+ logger.info(`[Extension:${extension.id}] Registering function: ${name}`);
3168
+ this.runtime.registerGlobalFunction(name, fn);
3169
+ },
3170
+ logger
3171
+ };
3172
+ try {
3173
+ extension.onLoad(context);
3174
+ this.extensions.set(extension.id, extension);
3175
+ logger.info(`Extension loaded: ${extension.id} v${extension.version}`);
3176
+ } catch (error) {
3177
+ logger.error(`Failed to load extension ${extension.id}:`, {
3178
+ error: error instanceof Error ? error.message : String(error)
3179
+ });
3180
+ throw error;
3181
+ }
3182
+ }
3183
+ /**
3184
+ * Unload an extension
3185
+ */
3186
+ unloadingExtension(id) {
3187
+ const extension = this.extensions.get(id);
3188
+ if (!extension) return;
3189
+ try {
3190
+ const context = {
3191
+ registerTrait: () => {
3192
+ },
3193
+ registerFunction: () => {
3194
+ },
3195
+ logger
3196
+ };
3197
+ extension.onUnload(context);
3198
+ } catch (e) {
3199
+ logger.error(`Error unloading extension ${id}`, {
3200
+ error: e instanceof Error ? e.message : String(e)
3201
+ });
3202
+ }
3203
+ this.extensions.delete(id);
3204
+ logger.info(`Extension unloaded: ${id}`);
3205
+ }
3206
+ getExtension(id) {
3207
+ return this.extensions.get(id);
3208
+ }
3209
+ };
3210
+
3211
+ // src/HoloScriptRuntime.ts
3212
+ var RUNTIME_SECURITY_LIMITS = {
3213
+ maxExecutionDepth: 50,
3214
+ maxTotalNodes: 1e3,
3215
+ maxExecutionTimeMs: 5e3,
3216
+ maxParticlesPerSystem: 1e3,
3217
+ maxCallStackDepth: 100
3218
+ };
3219
+ function isOrbData2(v) {
3220
+ return v !== null && typeof v === "object" && v.__type === "orb";
3221
+ }
3222
+ var HoloScriptRuntime = class {
3223
+ constructor(_importLoader, customFunctions) {
3224
+ this.particleSystems = /* @__PURE__ */ new Map();
3225
+ this.executionHistory = [];
3226
+ this.agentRuntimes = /* @__PURE__ */ new Map();
3227
+ this.startTime = 0;
3228
+ this.nodeCount = 0;
3229
+ this.callStack = [];
3230
+ this.eventHandlers = /* @__PURE__ */ new Map();
3231
+ this.animations = /* @__PURE__ */ new Map();
3232
+ this.uiElements = /* @__PURE__ */ new Map();
3233
+ this.proceduralSkills = /* @__PURE__ */ new Map();
3234
+ this.traitHandlers = /* @__PURE__ */ new Map();
3235
+ this.context = createEmptyContext();
3236
+ this.currentScope = { variables: this.context.variables };
3237
+ this.builtinFunctions = this.initBuiltins(customFunctions);
3238
+ this.agentPool = new engineRuntime.ObjectPool(
3239
+ () => new HoloScriptAgentRuntime(),
3240
+ // Preallocation mode (optional args)
3241
+ (agent) => agent.destroy(),
3242
+ 50
3243
+ );
3244
+ engineRuntime.registerVoiceSynthesizer("default", new engineRuntime.BaseVoiceSynthesizer());
3245
+ engineRuntime.registerEmotionDetector("default", new engineRuntime.LocalEmotionDetector());
3246
+ engineRuntime.registerSpeechRecognizer("default", new engineRuntime.MockSpeechRecognizer());
3247
+ for (const [name, fn] of this.builtinFunctions) {
3248
+ this.context.functions.set(name, ((...spreadArgs) => fn(spreadArgs)));
3249
+ }
3250
+ attachStateInvalidationConsumer(this.buildEventSystemContext(), defaultStateInvalidationRegistry);
3251
+ this.registerFunction("get_attended_entities", (args) => {
3252
+ const topK = typeof args[0] === "number" ? args[0] : 10;
3253
+ const selfRaw = this.context.variables.get("self");
3254
+ const selfNode = isOrbData2(selfRaw) ? selfRaw : void 0;
3255
+ const observerPos = selfNode?.position ?? [0, 0, 0];
3256
+ const entities = [];
3257
+ this.context.spatialMemory.forEach((pos, id) => {
3258
+ if (id !== selfNode?.name) {
3259
+ const entityRaw = this.context.variables.get(id);
3260
+ const entityOrb = isOrbData2(entityRaw) ? entityRaw : void 0;
3261
+ entities.push({
3262
+ id,
3263
+ position: pos,
3264
+ velocity: entityOrb?.velocity,
3265
+ saliencyBase: typeof entityOrb?.saliency === "number" ? entityOrb.saliency : void 0
3266
+ });
3267
+ }
3268
+ });
3269
+ return AttentionEngine.getTopKEntities(
3270
+ observerPos,
3271
+ entities,
3272
+ topK
3273
+ );
3274
+ });
3275
+ this.traitHandlers.set("mitosis", mitosisHandler);
3276
+ this.traitHandlers.set("orbital", orbitalHandler);
3277
+ this.extensionRegistry = new ExtensionRegistry(this);
3278
+ engineRuntime.stateMachineInterpreter.setHookExecutor((code) => this.evaluateExpression(code));
3279
+ engineRuntime.stateMachineInterpreter.setGuardEvaluator((expr) => this.evaluateExpression(expr));
3280
+ }
3281
+ /**
3282
+ * Initialize built-in functions
3283
+ */
3284
+ /** Construct a BuiltinsContext bound to this runtime. (Slice 28) */
3285
+ buildBuiltinsContext() {
3286
+ return {
3287
+ uiElements: this.uiElements,
3288
+ hologramState: this.context.hologramState,
3289
+ spatialMemory: this.context.spatialMemory,
3290
+ animations: this.animations,
3291
+ variables: this.context.variables,
3292
+ templates: this.context.templates,
3293
+ executionStack: this.context.executionStack,
3294
+ agentRuntimes: this.agentRuntimes,
3295
+ createParticleEffect: (name, position, color, count) => this.createParticleEffect(name, position, color, count),
3296
+ createConnectionStream: (from, to, fromPos, toPos, dataType) => this.createConnectionStream(from, to, fromPos, toPos, dataType),
3297
+ emit: (event, data) => this.emit(event, data),
3298
+ setVariable: (name, value) => this.setVariable(name, value),
3299
+ getVariable: (name) => this.getVariable(name),
3300
+ executeOrb: (orbNode) => executeOrb(orbNode, this.buildOrbExecutorContext()),
3301
+ calculateArc: (args) => this.handleCalculateArc(args)
3302
+ };
3303
+ }
3304
+ /**
3305
+ * Initialize built-in functions (W1-T4 slice 28: impl extracted to
3306
+ * ./runtime/builtins-registry). Thin wrapper that constructs the
3307
+ * context bag + delegates to createBuiltinsMap.
3308
+ */
3309
+ initBuiltins(customFunctions) {
3310
+ return createBuiltinsMap(this.buildBuiltinsContext(), customFunctions);
3311
+ }
3312
+ /**
3313
+ * Register a global function from an extension
3314
+ */
3315
+ registerGlobalFunction(name, fn) {
3316
+ this.context.functions.set(name, ((...spreadArgs) => fn(spreadArgs)));
3317
+ }
3318
+ /**
3319
+ * Register a custom trait from an extension
3320
+ */
3321
+ registerTrait(name, handler) {
3322
+ const vrName = name;
3323
+ this.traitHandlers.set(vrName, handler);
3324
+ logger.info(`Registered trait: ${name}`);
3325
+ }
3326
+ /**
3327
+ * Get the extension registry
3328
+ */
3329
+ getExtensionRegistry() {
3330
+ return this.extensionRegistry;
3331
+ }
3332
+ /**
3333
+ * Execute a single AST node.
3334
+ *
3335
+ * W1-T4 slice 34: the 225-LOC switch that used to live here is now a
3336
+ * Map<nodeType, handler> in ./runtime/node-type-registry. This method
3337
+ * keeps only the bookkeeping (executionStack push/pop, executionHistory
3338
+ * append, startTime/executionTime, error catch) — dispatch is a table
3339
+ * lookup. Adding a new node type is a one-line registry entry.
3340
+ */
3341
+ async executeNode(node) {
3342
+ const startTime = Date.now();
3343
+ try {
3344
+ this.context.executionStack.push(node);
3345
+ const result = await dispatchNode(
3346
+ node,
3347
+ this
3348
+ );
3349
+ result.executionTime = Date.now() - startTime;
3350
+ this.executionHistory.push(result);
3351
+ this.context.executionStack.pop();
3352
+ return result;
3353
+ } catch (error) {
3354
+ const execTime = Date.now() - startTime;
3355
+ const errorResult = {
3356
+ success: false,
3357
+ error: error instanceof Error ? error.message : String(error),
3358
+ executionTime: execTime
3359
+ };
3360
+ this.executionHistory.push(errorResult);
3361
+ this.context.executionStack.pop();
3362
+ return errorResult;
3363
+ }
3364
+ }
3365
+ /**
3366
+ * Execute multiple nodes or a single node (unified entry point)
3367
+ */
3368
+ async execute(nodes) {
3369
+ this.startTime = Date.now();
3370
+ this.nodeCount = 0;
3371
+ if (Array.isArray(nodes)) {
3372
+ const results = await this.executeProgram(nodes);
3373
+ const success = results.every((r) => r.success);
3374
+ const lastResult = results[results.length - 1];
3375
+ let output = success ? `Program executed (${results.length} nodes)` : "Program failed";
3376
+ if (lastResult && lastResult.success && lastResult.output !== void 0) {
3377
+ output = lastResult.output;
3378
+ }
3379
+ return {
3380
+ success,
3381
+ output,
3382
+ error: results.find((r) => !r.success)?.error
3383
+ };
3384
+ } else {
3385
+ return this.executeNode(nodes);
3386
+ }
3387
+ }
3388
+ /**
3389
+ * Execute multiple nodes in sequence
3390
+ */
3391
+ async executeProgram(nodes, depth = 0) {
3392
+ if (depth === 0) {
3393
+ this.startTime = Date.now();
3394
+ this.nodeCount = 0;
3395
+ }
3396
+ if (depth > RUNTIME_SECURITY_LIMITS.maxExecutionDepth) {
3397
+ logger.error("Max execution depth exceeded", { depth });
3398
+ return [
3399
+ {
3400
+ success: false,
3401
+ error: `Max execution depth exceeded (${RUNTIME_SECURITY_LIMITS.maxExecutionDepth})`,
3402
+ executionTime: 0
3403
+ }
3404
+ ];
3405
+ }
3406
+ const results = [];
3407
+ for (const node of nodes) {
3408
+ this.nodeCount++;
3409
+ if (this.nodeCount > RUNTIME_SECURITY_LIMITS.maxTotalNodes) {
3410
+ logger.error("Max total nodes exceeded", { count: this.nodeCount });
3411
+ results.push({
3412
+ success: false,
3413
+ error: "Max total nodes exceeded",
3414
+ executionTime: Date.now() - this.startTime
3415
+ });
3416
+ break;
3417
+ }
3418
+ if (Date.now() - this.startTime > RUNTIME_SECURITY_LIMITS.maxExecutionTimeMs) {
3419
+ logger.error("Execution timeout", { duration: Date.now() - this.startTime });
3420
+ results.push({
3421
+ success: false,
3422
+ error: "Execution timeout",
3423
+ executionTime: Date.now() - this.startTime
3424
+ });
3425
+ break;
3426
+ }
3427
+ const result = await this.executeNode(node);
3428
+ results.push(result);
3429
+ if (!result.success && node.type !== "visualize") {
3430
+ break;
3431
+ }
3432
+ if (node.type === "return") {
3433
+ break;
3434
+ }
3435
+ }
3436
+ return results;
3437
+ }
3438
+ /**
3439
+ * Call a function with arguments
3440
+ */
3441
+ async callFunction(name, args = []) {
3442
+ const builtin = this.builtinFunctions.get(name);
3443
+ if (builtin) {
3444
+ try {
3445
+ const result = await builtin(args);
3446
+ return {
3447
+ success: true,
3448
+ output: result
3449
+ };
3450
+ } catch (error) {
3451
+ return {
3452
+ success: false,
3453
+ error: `Built-in function ${name} failed: ${error}`
3454
+ };
3455
+ }
3456
+ }
3457
+ const func = this.context.functions.get(name);
3458
+ if (!func) {
3459
+ return {
3460
+ success: false,
3461
+ error: `Function '${name}' not found`
3462
+ };
3463
+ }
3464
+ if (typeof func === "function") {
3465
+ try {
3466
+ const result = await func(...args);
3467
+ return {
3468
+ success: true,
3469
+ output: result
3470
+ };
3471
+ } catch (error) {
3472
+ return {
3473
+ success: false,
3474
+ error: `Extension function ${name} failed: ${error}`
3475
+ };
3476
+ }
3477
+ }
3478
+ if (this.callStack.length >= RUNTIME_SECURITY_LIMITS.maxCallStackDepth) {
3479
+ return {
3480
+ success: false,
3481
+ error: `Max call stack depth exceeded (${RUNTIME_SECURITY_LIMITS.maxCallStackDepth})`
3482
+ };
3483
+ }
3484
+ const parentScope = this.currentScope;
3485
+ this.currentScope = {
3486
+ variables: /* @__PURE__ */ new Map(),
3487
+ parent: parentScope
3488
+ };
3489
+ func.parameters.forEach((param, index) => {
3490
+ const value = index < args.length ? args[index] : param.defaultValue;
3491
+ this.currentScope.variables.set(param.name, value);
3492
+ });
3493
+ this.callStack.push(name);
3494
+ let returnValue = void 0;
3495
+ try {
3496
+ const results = await this.executeProgram(func.body, this.callStack.length);
3497
+ const lastResult = results[results.length - 1];
3498
+ if (lastResult?.output !== void 0) {
3499
+ returnValue = lastResult.output;
3500
+ }
3501
+ this.createExecutionEffect(name, func.position || [0, 0, 0]);
3502
+ return {
3503
+ success: results.every((r) => r.success),
3504
+ output: returnValue,
3505
+ hologram: func.hologram,
3506
+ spatialPosition: func.position
3507
+ };
3508
+ } finally {
3509
+ this.currentScope = parentScope;
3510
+ this.callStack.pop();
3511
+ }
3512
+ }
3513
+ /**
3514
+ * Set a variable in current scope
3515
+ */
3516
+ setVariable(name, value, scopeOverride) {
3517
+ if (name.includes(".")) {
3518
+ const parts = name.split(".");
3519
+ const objName = parts[0];
3520
+ const propPath = parts.slice(1);
3521
+ let obj = this.getVariable(objName, scopeOverride);
3522
+ if (obj === void 0 || typeof obj !== "object" || obj === null) {
3523
+ obj = {};
3524
+ const scope = scopeOverride || this.currentScope;
3525
+ scope.variables.set(objName, obj);
3526
+ }
3527
+ let current = obj;
3528
+ for (let i = 0; i < propPath.length - 1; i++) {
3529
+ if (current[propPath[i]] === void 0 || typeof current[propPath[i]] !== "object") {
3530
+ current[propPath[i]] = {};
3531
+ }
3532
+ current = current[propPath[i]];
3533
+ }
3534
+ current[propPath[propPath.length - 1]] = value;
3535
+ } else {
3536
+ const scope = scopeOverride || this.currentScope;
3537
+ scope.variables.set(name, value);
3538
+ }
3539
+ if (this.wss && typeof value === "object" && value !== null && value.__type === "orb") {
3540
+ this.broadcast("orb_update", { orb: value });
3541
+ } else if (this.wss && name.includes(".")) {
3542
+ const root = name.split(".")[0];
3543
+ const rootVar = this.getVariable(root, scopeOverride);
3544
+ if (rootVar && typeof rootVar === "object" && rootVar.__type === "orb") {
3545
+ this.broadcast("orb_update", { orb: rootVar });
3546
+ }
3547
+ }
3548
+ }
3549
+ /**
3550
+ * Get a variable from scope chain
3551
+ */
3552
+ getVariable(name, scopeOverride) {
3553
+ if (name.includes(".")) {
3554
+ const parts = name.split(".");
3555
+ let value = this.getVariable(parts[0], scopeOverride);
3556
+ for (let i = 1; i < parts.length && value !== void 0; i++) {
3557
+ if (typeof value === "object" && value !== null) {
3558
+ value = value[parts[i]];
3559
+ } else {
3560
+ return void 0;
3561
+ }
3562
+ }
3563
+ return value;
3564
+ }
3565
+ let scope = scopeOverride || this.currentScope;
3566
+ while (scope) {
3567
+ if (scope.variables.has(name)) {
3568
+ return scope.variables.get(name);
3569
+ }
3570
+ scope = scope.parent;
3571
+ }
3572
+ if (this.context.variables.has(name)) {
3573
+ return this.context.variables.get(name);
3574
+ }
3575
+ if (this.context.functions.has(name)) {
3576
+ return this.context.functions.get(name);
3577
+ }
3578
+ return void 0;
3579
+ }
3580
+ /**
3581
+ * Evaluate an expression in current context
3582
+ */
3583
+ evaluateExpression(expr) {
3584
+ if (!expr || typeof expr !== "string") return expr;
3585
+ const evaluator = new ExpressionEvaluator(this.context.state.getSnapshot());
3586
+ const varContext = {};
3587
+ this.context.variables.forEach((v, k) => varContext[k] = v);
3588
+ evaluator.updateContext(varContext);
3589
+ return evaluator.evaluate(expr);
3590
+ }
3591
+ // ============================================================================
3592
+ // Node Executors
3593
+ // ============================================================================
3594
+ // W1-T4 slice 26: executeOrb extracted to ./runtime/orb-executor.
3595
+ // Closes board task task_1776940471985_57z8.
3596
+ // W1-T4 slice 20: executeFunction / executeConnection / executeGate /
3597
+ // executeStream extracted to ./runtime/graph-executors.
3598
+ /**
3599
+ * Execute State Machine declaration (Phase 13)
3600
+ */
3601
+ // W1-T4 slice 17: executeStateMachine / executeExpressionStatement /
3602
+ // executeCall extracted to ./runtime/simple-executors.
3603
+ // W1-T4 slice 31: executeDebug extracted to ./runtime/debug-executor.
3604
+ // Thin wrapper binds runtime state-map references + logger into a
3605
+ // DebugExecutorContext and forwards to the pure executor.
3606
+ async executeDebug(node) {
3607
+ return executeDebug(node, this.buildDebugExecutorContext());
3608
+ }
3609
+ buildDebugExecutorContext() {
3610
+ return {
3611
+ scopeVariables: this.currentScope.variables,
3612
+ contextVariables: this.context.variables,
3613
+ functions: this.context.functions,
3614
+ connections: this.context.connections,
3615
+ callStack: this.callStack,
3616
+ uiElements: this.uiElements,
3617
+ animations: this.animations,
3618
+ executionHistory: this.executionHistory,
3619
+ setHologramState: (key, hologram) => {
3620
+ this.context.hologramState.set(key, hologram);
3621
+ },
3622
+ logInfo: (message, payload) => {
3623
+ logger.info(message, payload);
3624
+ }
3625
+ };
3626
+ }
3627
+ // W1-T4 slice 22: executeVisualize / executeUIElement extracted to ./runtime/info-executors.
3628
+ /**
3629
+ * Execute generic voice commands
3630
+ * Handles commands like: show, hide, animate, pulse, create
3631
+ */
3632
+ async executeGeneric(_node) {
3633
+ const genericNode = _node;
3634
+ const command = String(genericNode.command || "").trim().toLowerCase();
3635
+ const tokens = command.split(/\s+/);
3636
+ const action = tokens[0];
3637
+ const target = tokens[1];
3638
+ logger.info("Executing generic command", { command, action, target });
3639
+ try {
3640
+ let result;
3641
+ const uiCtx = this.buildUICommandContext();
3642
+ switch (action) {
3643
+ case "show":
3644
+ result = await executeShowCommand(target, genericNode, uiCtx);
3645
+ break;
3646
+ case "hide":
3647
+ result = await executeHideCommand(target, genericNode, uiCtx);
3648
+ break;
3649
+ case "create":
3650
+ case "summon":
3651
+ result = await executeCreateCommand(tokens.slice(1), genericNode, uiCtx);
3652
+ break;
3653
+ case "animate":
3654
+ result = await executeAnimateCommand(target, tokens.slice(2), genericNode, uiCtx);
3655
+ break;
3656
+ case "pulse":
3657
+ result = await executePulseCommand(target, tokens.slice(2), genericNode, uiCtx);
3658
+ break;
3659
+ case "move":
3660
+ result = await executeMoveCommand(target, tokens.slice(2), genericNode, uiCtx);
3661
+ break;
3662
+ case "delete":
3663
+ case "remove":
3664
+ result = await executeDeleteCommand(target, genericNode, uiCtx);
3665
+ break;
3666
+ default:
3667
+ logger.warn("Unknown voice command action", { action, command });
3668
+ result = {
3669
+ executed: false,
3670
+ message: `Unknown command: ${action}`
3671
+ };
3672
+ }
3673
+ return {
3674
+ success: true,
3675
+ output: result
3676
+ };
3677
+ } catch (error) {
3678
+ return {
3679
+ success: false,
3680
+ error: `Generic command execution failed: ${String(error)}`
3681
+ };
3682
+ }
3683
+ }
3684
+ // W1-T4 slice 18: show/hide/create/animate/pulse/move/delete commands
3685
+ // extracted to ./runtime/ui-commands. Methods deleted — dispatch is
3686
+ // inlined above using buildUICommandContext().
3687
+ // W1-T4 slice 19: executeStructure / executeAssignment / executeReturn
3688
+ // added to ./runtime/simple-executors.
3689
+ // ============================================================================
3690
+ // Condition Evaluation
3691
+ // ============================================================================
3692
+ /**
3693
+ * Thin wrapper over the extracted pure evaluator (W1-T4 slice 3,
3694
+ * see ./runtime/condition-evaluator). Callers pass the runtime's
3695
+ * `evaluateExpression` as the expression-resolution callback.
3696
+ */
3697
+ evaluateCondition(condition) {
3698
+ return evaluateCondition(condition, (expr) => this.evaluateExpression(expr));
3699
+ }
3700
+ // ============================================================================
3701
+ // Transformation
3702
+ // ============================================================================
3703
+ /**
3704
+ * Thin wrapper over the extracted pure transformation operations
3705
+ * (W1-T4 slice 5, see ./runtime/transformation). Threads
3706
+ * setVariable / evaluateCondition / evaluateExpression through
3707
+ * a context object so the pure module stays free of `this` binding.
3708
+ */
3709
+ async applyTransformation(data, transform) {
3710
+ return applyTransformation(data, transform, {
3711
+ setVariable: (name, value) => this.setVariable(name, value),
3712
+ evaluateCondition: (expr) => this.evaluateCondition(expr),
3713
+ evaluateExpression: (expr) => this.evaluateExpression(expr)
3714
+ });
3715
+ }
3716
+ // ============================================================================
3717
+ // Event System
3718
+ // ============================================================================
3719
+ /**
3720
+ * Outstanding state invalidations (PersistentTrait TTL expiries). A reader
3721
+ * checks `stateInvalidations.wasInvalidated(key)` before trusting a cached
3722
+ * value and `consume(key)` once it has refetched. Closes the
3723
+ * `persistent_expired`-into-void capability gap.
3724
+ */
3725
+ get stateInvalidations() {
3726
+ return defaultStateInvalidationRegistry;
3727
+ }
3728
+ /** Construct an EventSystemContext bound to this runtime. (Slice 29) */
3729
+ buildEventSystemContext() {
3730
+ return {
3731
+ eventHandlers: this.eventHandlers,
3732
+ agentRuntimes: this.agentRuntimes,
3733
+ variables: this.context.variables,
3734
+ traitHandlers: this.traitHandlers,
3735
+ uiElements: this.uiElements,
3736
+ getCurrentScale: () => this.context.currentScale,
3737
+ // EventBus.emit is sync (returns void) but the EventSystemContext
3738
+ // contract requires Promise<void> so trait-side emits can `await`
3739
+ // through a unified interface. Wrap with Promise.resolve.
3740
+ globalBusEmit: (event, data) => {
3741
+ getSharedEventBus().emit(event, data);
3742
+ return Promise.resolve();
3743
+ },
3744
+ sendStateMachineEvent: (id, event) => engineRuntime.stateMachineInterpreter.sendEvent(id, event)
3745
+ };
3746
+ }
3747
+ /**
3748
+ * Register event handler.
3749
+ * (W1-T4 slice 29: impl extracted to ./runtime/event-system.)
3750
+ */
3751
+ on(event, handler) {
3752
+ onEvent(event, handler, this.buildEventSystemContext());
3753
+ }
3754
+ /**
3755
+ * Register host function. Stays in HSR — direct builtinFunctions
3756
+ * write, not part of the event-system concern.
3757
+ */
3758
+ registerFunction(name, handler) {
3759
+ this.builtinFunctions.set(name, handler);
3760
+ logger.info(`Host function registered: ${name}`);
3761
+ }
3762
+ /**
3763
+ * Remove event handler.
3764
+ * (W1-T4 slice 29: impl extracted to ./runtime/event-system.)
3765
+ */
3766
+ off(event, handler) {
3767
+ offEvent(event, handler, this.buildEventSystemContext());
3768
+ }
3769
+ /**
3770
+ * Emit event through the full 5-stage dispatch.
3771
+ * (W1-T4 slice 29: impl extracted to ./runtime/event-system.)
3772
+ */
3773
+ async emit(event, data) {
3774
+ return emit(event, data, this.buildEventSystemContext());
3775
+ }
3776
+ /**
3777
+ * Trigger UI event — update element.value + fire dotted event.
3778
+ * (W1-T4 slice 29: impl extracted to ./runtime/event-system.)
3779
+ */
3780
+ async triggerUIEvent(elementName, eventType, data) {
3781
+ return triggerUIEvent(elementName, eventType, data, this.buildEventSystemContext());
3782
+ }
3783
+ // W1-T4 slice 29: forwardToTraits extracted to ./runtime/event-system
3784
+ // (private in HSR, now a module function; no wrapper needed — the only
3785
+ // former caller is emit, which now calls the extracted forwardToTraits directly).
3786
+ // ============================================================================
3787
+ // Animation System
3788
+ // ============================================================================
3789
+ /**
3790
+ * Update all animations (W1-T4 slice 6: per-tick lerp extracted to
3791
+ * ./runtime/animation-system). Also ticks system variables — that
3792
+ * coupling lives in HSR because `updateSystemVariables` touches
3793
+ * too much runtime state to cleanly extract yet.
3794
+ */
3795
+ updateAnimations() {
3796
+ updateAnimations(
3797
+ this.animations,
3798
+ (name, value) => this.setVariable(name, value),
3799
+ Date.now()
3800
+ );
3801
+ this.updateSystemVariables();
3802
+ }
3803
+ /**
3804
+ * Update real-life and system variables ($time, $user, etc.)
3805
+ */
3806
+ /**
3807
+ * Update real-life and system variables ($time, $user, etc.)
3808
+ * (W1-T4 slice 9: impl extracted to ./runtime/system-variables).
3809
+ * Threads setVariable/getVariable callbacks plus the already-read
3810
+ * brittney_api_keys JSON string so the pure module has no
3811
+ * hidden dependency on browser `localStorage`.
3812
+ */
3813
+ updateSystemVariables() {
3814
+ const brittneyApiKeysJson = typeof localStorage !== "undefined" ? localStorage.getItem("brittney_api_keys") : null;
3815
+ updateSystemVariables({
3816
+ setVariable: (name, value) => this.setVariable(name, value),
3817
+ getVariable: (name) => this.getVariable(name),
3818
+ brittneyApiKeysJson
3819
+ });
3820
+ }
3821
+ // ==========================================================================
3822
+ // COMMERCE / SOCIAL / PHYSICS / ANIMATION PRIMITIVES
3823
+ // (W1-T4 slice 8: extracted to ./runtime/primitives, registered
3824
+ // inline in initBuiltins via emit-injection — no wrappers needed)
3825
+ //
3826
+ // handleCalculateArc (below) stays — it's structured differently
3827
+ // from the emit-pattern primitives: it does real math via
3828
+ // calculateArc (slice 2), not an event dispatch.
3829
+ // ==========================================================================
3830
+ /**
3831
+ * Handle calculate_arc(start, end, speed)
3832
+ * W1-T4 slice 2: math extracted to ./runtime/physics-math.calculateArc
3833
+ */
3834
+ handleCalculateArc(args) {
3835
+ if (args.length < 3) return [0, 0, 0];
3836
+ const start = args[0];
3837
+ const end = args[1];
3838
+ const speed = args[2];
3839
+ return calculateArc(start, end, speed);
3840
+ }
3841
+ // ============================================================================
3842
+ // Particle Effects (W1-T4 slice 4: impls extracted to ./runtime/particle-effects)
3843
+ //
3844
+ // Methods below are thin wrappers that thread `this.particleSystems`
3845
+ // (the Map) and the security limit into the pure implementations.
3846
+ // Call sites elsewhere in HSR remain unchanged.
3847
+ // ============================================================================
3848
+ createParticleEffect(name, position, color, count) {
3849
+ createParticleEffect(
3850
+ this.particleSystems,
3851
+ name,
3852
+ position,
3853
+ color,
3854
+ count,
3855
+ RUNTIME_SECURITY_LIMITS.maxParticlesPerSystem
3856
+ );
3857
+ }
3858
+ createConnectionStream(from, to, fromPos, toPos, dataType) {
3859
+ createConnectionStream(this.particleSystems, from, to, fromPos, toPos, dataType);
3860
+ }
3861
+ createFlowingStream(name, position, data) {
3862
+ createFlowingStream(
3863
+ this.particleSystems,
3864
+ name,
3865
+ position,
3866
+ data,
3867
+ RUNTIME_SECURITY_LIMITS.maxParticlesPerSystem
3868
+ );
3869
+ }
3870
+ createExecutionEffect(name, position) {
3871
+ createExecutionEffect(
3872
+ this.particleSystems,
3873
+ name,
3874
+ position,
3875
+ RUNTIME_SECURITY_LIMITS.maxParticlesPerSystem
3876
+ );
3877
+ }
3878
+ createDataVisualization(name, data, position) {
3879
+ createDataVisualization(
3880
+ this.particleSystems,
3881
+ name,
3882
+ data,
3883
+ position,
3884
+ RUNTIME_SECURITY_LIMITS.maxParticlesPerSystem
3885
+ );
3886
+ }
3887
+ getDataTypeColor(dataType) {
3888
+ return getDataTypeColor(dataType);
3889
+ }
3890
+ // ============================================================================
3891
+ // Visualizer Server
3892
+ // ============================================================================
3893
+ startVisualizationServer(port = 8080) {
3894
+ try {
3895
+ this.wss = new WebSocketServer({ port });
3896
+ logger.info(`[Visualizer] WebSocket server started on port ${port}`);
3897
+ this.timeManager = new TimeManager(/* @__PURE__ */ new Date());
3898
+ this.timeManager.onUpdate((julianDate, date) => {
3899
+ this.updateTraits(julianDate);
3900
+ this.broadcast("time_update", {
3901
+ julianDate,
3902
+ date: date.toISOString(),
3903
+ timeScale: this.timeManager.getTimeScale(),
3904
+ isPaused: this.timeManager.getIsPaused()
3905
+ });
3906
+ });
3907
+ this.timeManager.start();
3908
+ this.updateTraits(this.timeManager.getJulianDate());
3909
+ this.wss.on("connection", (ws) => {
3910
+ logger.info("[Visualizer] Client connected");
3911
+ const orbs = Array.from(this.context.variables.entries()).filter(
3912
+ ([_, v]) => v && typeof v === "object" && v.__type === "orb"
3913
+ ).map(([id, v]) => {
3914
+ const orbData = v;
3915
+ return {
3916
+ id,
3917
+ name: orbData.name || id,
3918
+ position: Array.isArray(orbData.position) ? [orbData.position[0], orbData.position[1], orbData.position[2]] : orbData.position,
3919
+ properties: orbData.properties || {},
3920
+ hologram: orbData.hologram || (() => {
3921
+ const props = orbData.properties;
3922
+ return {
3923
+ color: props?.color || "#ffffff",
3924
+ size: props?.size || props?.scale || 1,
3925
+ shape: props?.geometry || "sphere",
3926
+ glow: props?.glow || false
3927
+ };
3928
+ })(),
3929
+ traits: orbData.traits || []
3930
+ };
3931
+ });
3932
+ ws.send(
3933
+ JSON.stringify({
3934
+ type: "init",
3935
+ orbs,
3936
+ time: this.timeManager ? this.timeManager.getState() : null
3937
+ })
3938
+ );
3939
+ ws.on("message", (message) => {
3940
+ try {
3941
+ const data = readJson(message.toString());
3942
+ if (data.type === "time_control") {
3943
+ if (typeof data.command === "string") {
3944
+ this.handleTimeControl(data.command, data.value);
3945
+ }
3946
+ }
3947
+ } catch (e) {
3948
+ logger.error("[Visualizer] Failed to parse message", { error: String(e) });
3949
+ }
3950
+ });
3951
+ });
3952
+ } catch (error) {
3953
+ logger.error("[Visualizer] Failed to start server", { error: String(error) });
3954
+ }
3955
+ }
3956
+ /**
3957
+ * Handle time control commands from visualizer
3958
+ * (W1-T4 slice 7: impl extracted to ./runtime/visualizer-server)
3959
+ */
3960
+ handleTimeControl(command, value) {
3961
+ handleTimeControl(this.timeManager, command, value);
3962
+ }
3963
+ /**
3964
+ * Broadcast a typed message to all connected WebSocket clients.
3965
+ * (W1-T4 slice 7: impl extracted to ./runtime/visualizer-server)
3966
+ */
3967
+ broadcast(type, payload) {
3968
+ broadcast(this.wss, type, payload);
3969
+ }
3970
+ // ============================================================================
3971
+ // Public API
3972
+ // ============================================================================
3973
+ getParticleSystems() {
3974
+ return new Map(this.particleSystems);
3975
+ }
3976
+ /**
3977
+ * Advance all particle systems by deltaTime.
3978
+ * (W1-T4 slice 14: impl extracted to ./runtime/particle-effects)
3979
+ */
3980
+ updateParticles(deltaTime) {
3981
+ updateParticles(this.particleSystems, deltaTime);
3982
+ }
3983
+ getContext() {
3984
+ return { ...this.context };
3985
+ }
3986
+ getUIElements() {
3987
+ return new Map(this.uiElements);
3988
+ }
3989
+ getUIElement(name) {
3990
+ return this.uiElements.get(name);
3991
+ }
3992
+ getAnimations() {
3993
+ return new Map(this.animations);
3994
+ }
3995
+ reset() {
3996
+ this.context = createEmptyContext();
3997
+ this.currentScope = { variables: this.context.variables };
3998
+ this.callStack = [];
3999
+ this.particleSystems.clear();
4000
+ this.executionHistory = [];
4001
+ this.eventHandlers.clear();
4002
+ this.animations.clear();
4003
+ this.uiElements.clear();
4004
+ }
4005
+ // W1-T4 slice 10: createEmptyContext extracted to ./runtime/context-factory
4006
+ // (was a private method here; now called directly as module function
4007
+ // at the 2 internal call sites — no wrapper needed).
4008
+ // W1-T4 slice 21: executeScale added to ./runtime/simple-executors.
4009
+ // W1-T4 slice 17: executeFocus / executeEnvironment extracted to ./runtime/simple-executors.
4010
+ // W1-T4 slice 21: executeComposition added to ./runtime/simple-executors.
4011
+ // W1-T4 slice 13: resolveHoloValue extracted to ./runtime/holo-value
4012
+ // (pure recursive helper; private method deleted — 4 internal call
4013
+ // sites now use the imported function directly).
4014
+ // W1-T4 slice 24: executeHoloComposition extracted to ./runtime/holo-composition-executor.
4015
+ // W1-T4 slice 17: executeHoloTemplate extracted to ./runtime/simple-executors.
4016
+ // W1-T4 slice 25: executeHoloObject extracted to ./runtime/holo-object-executor.
4017
+ // Closes board task task_1776940617322_ee53.
4018
+ /**
4019
+ * Execute a block of HoloStatements (HoloNode AST)
4020
+ */
4021
+ // W1-T4 slice 30: executeHoloProgram + executeHoloStatement extracted
4022
+ // to ./runtime/holo-statement-executor. Thin wrappers bind this
4023
+ // runtime's getVariable/setVariable/emit/evaluateHoloExpression +
4024
+ // telemetry into a HoloStatementContext and forward to the pure
4025
+ // recursive executor.
4026
+ async executeHoloProgram(statements, scopeOverride) {
4027
+ return executeHoloProgram(statements, scopeOverride, this.buildHoloStatementContext());
4028
+ }
4029
+ async executeHoloStatement(stmt, scopeOverride) {
4030
+ return executeHoloStatement(stmt, scopeOverride, this.buildHoloStatementContext());
4031
+ }
4032
+ buildHoloStatementContext() {
4033
+ return {
4034
+ currentScope: this.currentScope,
4035
+ getVariable: (name, scope) => this.getVariable(name, scope),
4036
+ setVariable: (name, value, scope) => {
4037
+ this.setVariable(name, value, scope);
4038
+ },
4039
+ emit: (event, data) => {
4040
+ void this.emit(event, data);
4041
+ },
4042
+ evaluateHoloExpression: (expr, scopeOverride) => this.evaluateHoloExpression(expr, scopeOverride),
4043
+ telemetry: {
4044
+ setGauge: (name, value) => {
4045
+ telemetry.setGauge(name, value);
4046
+ },
4047
+ incrementCounter: (name, value, labels) => {
4048
+ telemetry.incrementCounter(name, value, labels);
4049
+ },
4050
+ measureLatency: (name, fn) => telemetry.measureLatency(name, fn),
4051
+ executionDepth: () => this.context.executionStack.length
4052
+ }
4053
+ };
4054
+ }
4055
+ // W1-T4 slice: evaluateHoloExpression + getMemberPath extracted to
4056
+ // ./runtime/holo-expression. Thin wrapper binds this runtime's
4057
+ // getVariable/setVariable/callFunction into a HoloExpressionContext
4058
+ // and forwards to the pure recursive evaluator. Memoization (max 500,
4059
+ // FIFO) is preserved via a module-level cache in the pure module.
4060
+ evaluateHoloExpression(expr, scopeOverride) {
4061
+ return evaluateHoloExpression(expr, scopeOverride, this.buildHoloExpressionContext());
4062
+ }
4063
+ buildHoloExpressionContext() {
4064
+ return {
4065
+ getVariable: (name, scope) => this.getVariable(name, scope),
4066
+ setVariable: (name, value, scope) => this.setVariable(name, value, scope),
4067
+ callFunction: (name, args) => this.callFunction(name, args)
4068
+ };
4069
+ }
4070
+ // W1-T4 slice 16: executeSystem / setupNetworking / setupPhysics /
4071
+ // executeCoreConfig extracted to ./runtime/system-executors. Methods
4072
+ // deleted; dispatch calls the pure functions inline.
4073
+ // =========================================================================
4074
+ // Control Flow Execution (W1-T4 slice 12: impls extracted to
4075
+ // ./runtime/control-flow — wrappers below share a ControlFlowContext
4076
+ // that threads evaluateExpression / evaluateCondition / executeNode /
4077
+ // variables through a narrow boundary).
4078
+ // =========================================================================
4079
+ /** Construct a ControlFlowContext bound to this runtime's state. */
4080
+ buildControlFlowContext() {
4081
+ return {
4082
+ evaluateExpression: (expr) => this.evaluateExpression(expr),
4083
+ evaluateCondition: (expr) => this.evaluateCondition(expr),
4084
+ executeNode: (n) => this.executeNode(n),
4085
+ variables: this.context.variables
4086
+ };
4087
+ }
4088
+ /** @for item in iterable { body } */
4089
+ async executeForLoop(node) {
4090
+ return executeForLoop(node, this.buildControlFlowContext());
4091
+ }
4092
+ /** @forEach item in collection { body } */
4093
+ async executeForEachLoop(node) {
4094
+ return executeForEachLoop(node, this.buildControlFlowContext());
4095
+ }
4096
+ /** @while condition { body } (10k-iteration safety cap) */
4097
+ async executeWhileLoop(node) {
4098
+ return executeWhileLoop(node, this.buildControlFlowContext());
4099
+ }
4100
+ /** @if condition { body } @else { elseBody } */
4101
+ async executeIfStatement(node) {
4102
+ return executeIfStatement(node, this.buildControlFlowContext());
4103
+ }
4104
+ /** @match subject { pattern => result, ... } */
4105
+ async executeMatch(node) {
4106
+ return executeMatch(node, this.buildControlFlowContext());
4107
+ }
4108
+ // W1-T4 slice 11: patternMatches extracted to ./runtime/pattern-match
4109
+ // (pure helper; deleted method — only caller is executeMatch above,
4110
+ // now using patternMatchesPure directly).
4111
+ // W1-T4 slice 15: executeNarrative / executeQuest / executeDialogue
4112
+ // extracted to ./runtime/narrative-executors. Methods deleted —
4113
+ // dispatch calls the pure functions directly with a shared context.
4114
+ /** Construct an OrbExecutorContext bound to this runtime. (Slice 26) */
4115
+ buildOrbExecutorContext() {
4116
+ return {
4117
+ getCurrentScale: () => this.context.currentScale,
4118
+ getVariable: (name) => this.getVariable(name),
4119
+ setVariable: (name, value) => this.setVariable(name, value),
4120
+ setSpatialPosition: (name, pos) => {
4121
+ this.context.spatialMemory.set(name, pos);
4122
+ },
4123
+ evaluateExpression: (expr) => this.evaluateExpression(expr),
4124
+ getTemplate: (name) => this.context.templates.get(name),
4125
+ setHologramState: (name, hologram) => {
4126
+ this.context.hologramState.set(name, hologram);
4127
+ },
4128
+ executeMigrationBlock: (existingOrb, migration) => this.executeMigrationBlock(existingOrb, migration),
4129
+ getBuiltinFunction: (name) => this.builtinFunctions.get(name),
4130
+ applyDirectives: (node) => this.applyDirectives(node),
4131
+ isAgent: (node) => this.isAgent(node),
4132
+ getAgentRuntime: (name) => this.agentRuntimes.get(name),
4133
+ setAgentRuntime: (name, runtime) => {
4134
+ this.agentRuntimes.set(name, runtime);
4135
+ },
4136
+ acquireAgentRuntime: () => this.agentPool.acquire(),
4137
+ parentRuntime: this,
4138
+ createParticleEffect: (name, position, color, count) => this.createParticleEffect(name, position, color, count),
4139
+ broadcast: (event, payload) => this.broadcast(event, payload)
4140
+ };
4141
+ }
4142
+ /** Construct a HoloObjectContext bound to this runtime. (Slice 25) */
4143
+ buildHoloObjectContext() {
4144
+ return {
4145
+ getTemplate: (name) => this.context.templates.get(name),
4146
+ executeOrb: (orbNode) => executeOrb(orbNode, this.buildOrbExecutorContext())
4147
+ };
4148
+ }
4149
+ /** Construct a HoloCompositionContext bound to this runtime. (Slice 24) */
4150
+ buildHoloCompositionContext() {
4151
+ return {
4152
+ simpleExecutorContext: this.buildSimpleExecutorContext(),
4153
+ executeHoloObject: (node) => executeHoloObject(node, this.buildHoloObjectContext()),
4154
+ getEnvironment: () => this.context.environment,
4155
+ setEnvironment: (env) => {
4156
+ this.context.environment = env;
4157
+ }
4158
+ };
4159
+ }
4160
+ /** Construct an InfoExecutorContext bound to this runtime. (Slice 22) */
4161
+ buildInfoExecutorContext() {
4162
+ return {
4163
+ getVariable: (name) => this.getVariable(name),
4164
+ createDataVisualization: (name, data, position) => this.createDataVisualization(name, data, position),
4165
+ uiElements: this.uiElements,
4166
+ on: (event, handler) => this.on(event, handler),
4167
+ callFunction: (name) => this.callFunction(name)
4168
+ };
4169
+ }
4170
+ /** Construct a GraphExecutorContext bound to this runtime. (Slice 20) */
4171
+ buildGraphExecutorContext() {
4172
+ return {
4173
+ functions: this.context.functions,
4174
+ connections: this.context.connections,
4175
+ hologramState: this.context.hologramState,
4176
+ spatialMemory: this.context.spatialMemory,
4177
+ on: (event, handler) => this.on(event, handler),
4178
+ emit: (event, data) => {
4179
+ void this.emit(event, data);
4180
+ },
4181
+ getVariable: (name) => this.getVariable(name),
4182
+ setVariable: (name, value) => this.setVariable(name, value),
4183
+ createConnectionStream: (from, to, fromPos, toPos, dataType) => this.createConnectionStream(from, to, fromPos, toPos, dataType),
4184
+ createFlowingStream: (name, position, data) => this.createFlowingStream(name, position, data),
4185
+ getDataTypeColor: (dataType) => this.getDataTypeColor(dataType),
4186
+ evaluateCondition: (expr) => this.evaluateCondition(expr),
4187
+ executeProgram: (nodes, depth) => this.executeProgram(nodes, depth),
4188
+ callStackDepth: () => this.callStack.length,
4189
+ applyTransformation: (data, transform) => this.applyTransformation(data, transform)
4190
+ };
4191
+ }
4192
+ /** Construct a UICommandContext bound to this runtime. (Slice 18) */
4193
+ buildUICommandContext() {
4194
+ return {
4195
+ spatialMemory: this.context.spatialMemory,
4196
+ animations: this.animations,
4197
+ createParticleEffect: (name, position, color, count) => this.createParticleEffect(name, position, color, count),
4198
+ createConnectionStream: (from, to, fromPos, toPos, dataType) => this.createConnectionStream(from, to, fromPos, toPos, dataType)
4199
+ };
4200
+ }
4201
+ /** Construct a SimpleExecutorContext bound to this runtime. (Slice 17) */
4202
+ buildSimpleExecutorContext() {
4203
+ return {
4204
+ stateMachines: this.context.stateMachines,
4205
+ templates: this.context.templates,
4206
+ getEnvironment: () => this.context.environment,
4207
+ setEnvironment: (env) => {
4208
+ this.context.environment = env;
4209
+ },
4210
+ focusHistory: this.context.focusHistory,
4211
+ executionStackDepth: () => this.context.executionStack.length,
4212
+ evaluateExpression: (expr) => this.evaluateExpression(expr),
4213
+ callFunction: (name, args) => this.callFunction(name, args),
4214
+ executeProgram: (nodes, depth) => this.executeProgram(nodes, depth),
4215
+ setVariable: (name, value) => this.setVariable(name, value),
4216
+ setScale: (multiplier, magnitude) => {
4217
+ this.context.currentScale = multiplier;
4218
+ this.context.scaleMagnitude = magnitude;
4219
+ },
4220
+ getScale: () => ({
4221
+ multiplier: this.context.currentScale,
4222
+ magnitude: this.context.scaleMagnitude
4223
+ }),
4224
+ emit: (event, data) => {
4225
+ void this.emit(event, data);
4226
+ }
4227
+ };
4228
+ }
4229
+ /** Construct a NarrativeContext bound to this runtime's quest/dialogue state. */
4230
+ buildNarrativeContext() {
4231
+ return {
4232
+ quests: this.context.quests,
4233
+ setActiveQuestId: (id) => {
4234
+ this.context.activeQuestId = id;
4235
+ },
4236
+ setDialogueState: (state) => {
4237
+ this.context.dialogueState = state;
4238
+ }
4239
+ };
4240
+ }
4241
+ // W1-T4 slice 16: executeVisualMetadata / setupNetworking / setupPhysics
4242
+ // extracted to ./runtime/system-executors.
4243
+ async executeTemplate(node) {
4244
+ const existing = this.context.templates.get(node.name);
4245
+ if (existing) {
4246
+ node._previousVersion = existing.version;
4247
+ }
4248
+ this.context.templates.set(node.name, node);
4249
+ return {
4250
+ success: true,
4251
+ output: `Template ${node.name} registered (v${node.version || "unknown"})`
4252
+ };
4253
+ }
4254
+ /**
4255
+ * Execute a migration script for an object
4256
+ */
4257
+ async executeMigrationBlock(orb, migration) {
4258
+ logger.info(`Running migration for ${orb.name}...`);
4259
+ const previousScope = this.currentScope;
4260
+ this.currentScope = {
4261
+ variables: /* @__PURE__ */ new Map([
4262
+ ["this", orb],
4263
+ ["self", orb]
4264
+ ]),
4265
+ parent: previousScope
4266
+ };
4267
+ try {
4268
+ const parser = new HoloScriptCodeParser();
4269
+ const result = parser.parse(migration.body);
4270
+ if (result.errors.length > 0) {
4271
+ logger.error(`Migration parse errors for ${orb.name}:`, {
4272
+ errors: result.errors
4273
+ });
4274
+ return;
4275
+ }
4276
+ await this.executeProgram(result.ast, 0);
4277
+ } finally {
4278
+ this.currentScope = previousScope;
4279
+ }
4280
+ logger.info(`Migration complete for ${orb.name}`);
4281
+ }
4282
+ // W1-T4 slice 32: server/database/fetch executors extracted to
4283
+ // ./runtime/io-node-executors. Thin wrappers thread the public-mode
4284
+ // gate + logger into an IoNodeContext and forward to pure functions.
4285
+ async executeServerNode(node) {
4286
+ return executeServerNode(node, this.buildIoNodeContext());
4287
+ }
4288
+ async executeDatabaseNode(node) {
4289
+ return executeDatabaseNode(node, this.buildIoNodeContext());
4290
+ }
4291
+ async executeFetchNode(node) {
4292
+ return executeFetchNode(node, this.buildIoNodeContext());
4293
+ }
4294
+ buildIoNodeContext() {
4295
+ return {
4296
+ isPublicMode: this.context.mode === "public",
4297
+ logInfo: (msg) => {
4298
+ logger.info(msg);
4299
+ }
4300
+ };
4301
+ }
4302
+ async executeTarget(node) {
4303
+ const target = this.context.functions.get(node.target);
4304
+ if (!target) {
4305
+ return {
4306
+ success: false,
4307
+ error: `Function ${node.target} not found`,
4308
+ executionTime: 0
4309
+ };
4310
+ }
4311
+ const result = await executeFunction(target, this.buildGraphExecutorContext());
4312
+ this.createExecutionEffect(node.target, target.position || [0, 0, 0]);
4313
+ return {
4314
+ success: true,
4315
+ output: `Executed ${node.target}`,
4316
+ hologram: {
4317
+ shape: "sphere",
4318
+ color: "#ff4500",
4319
+ size: 1.2,
4320
+ glow: true,
4321
+ interactive: false
4322
+ },
4323
+ executionTime: result.executionTime
4324
+ };
4325
+ }
4326
+ // W1-T4 slice 33: executeStateDeclaration extracted to
4327
+ // ./runtime/declaration-executors. Thin wrapper.
4328
+ async executeStateDeclaration(node) {
4329
+ return executeStateDeclaration(node, this.buildDeclarationContext());
4330
+ }
4331
+ // ============================================================================
4332
+ // Memory Syntactic Execution (Phase 7 / EVOLVE)
4333
+ // ============================================================================
4334
+ async executeMemory(node) {
4335
+ const startTime = Date.now();
4336
+ logger.info(`[Memory] Initializing memory block: ${node.name}`);
4337
+ const memoryState = {
4338
+ id: node.name,
4339
+ type: "agent-memory"
4340
+ };
4341
+ if (node.semantic) {
4342
+ const semResult = await this.executeNode(node.semantic);
4343
+ if (semResult.success) memoryState.semantic = semResult.output;
4344
+ }
4345
+ if (node.episodic) {
4346
+ const epResult = await this.executeNode(node.episodic);
4347
+ if (epResult.success) memoryState.episodic = epResult.output;
4348
+ }
4349
+ if (node.procedural) {
4350
+ const procResult = await this.executeNode(node.procedural);
4351
+ if (procResult.success) memoryState.procedural = procResult.output;
4352
+ }
4353
+ this.context.variables.set(node.name, memoryState);
4354
+ this.emit("memory_initialized", { memoryId: node.name, config: memoryState });
4355
+ return {
4356
+ success: true,
4357
+ output: memoryState,
4358
+ executionTime: Date.now() - startTime
4359
+ };
4360
+ }
4361
+ /**
4362
+ * Load a procedural skill (W1-T4 slice 27: impl extracted to
4363
+ * ./runtime/skills-directives). Kept as public wrapper so external
4364
+ * callers still hit HSR's API surface.
4365
+ */
4366
+ loadSkill(skill) {
4367
+ loadSkill(skill, {
4368
+ proceduralSkills: this.proceduralSkills,
4369
+ broadcastSkill: (s) => StateSynchronizer.getInstance().broadcastSkill(s)
4370
+ });
4371
+ }
4372
+ async executeSkill(skillId, contextVariables = {}) {
4373
+ const skill = this.proceduralSkills.get(skillId);
4374
+ if (!skill) {
4375
+ throw new Error(`[Procedural] Skill '${skillId}' not found.`);
4376
+ }
4377
+ logger.info(`[Procedural] Executing skill: ${skill.name}`);
4378
+ const startTime = Date.now();
4379
+ const previousScope = this.currentScope;
4380
+ this.currentScope = { variables: new Map(previousScope.variables), parent: previousScope };
4381
+ for (const [key, val] of Object.entries(contextVariables)) {
4382
+ this.currentScope.variables.set(key, val);
4383
+ }
4384
+ try {
4385
+ const result = await this.executeNode(skill.action);
4386
+ if (result.success) {
4387
+ skill.successRate = Math.min(100, skill.successRate + 1);
4388
+ } else {
4389
+ skill.successRate = Math.max(0, skill.successRate - 1);
4390
+ }
4391
+ StateSynchronizer.getInstance().broadcastSkill(skill);
4392
+ return {
4393
+ ...result,
4394
+ executionTime: Date.now() - startTime
4395
+ };
4396
+ } finally {
4397
+ this.currentScope = previousScope;
4398
+ }
4399
+ }
4400
+ // W1-T4 slice 33: executeMemoryDefinition extracted to
4401
+ // ./runtime/declaration-executors. Thin wrapper.
4402
+ async executeMemoryDefinition(node) {
4403
+ return executeMemoryDefinition(node, this.buildDeclarationContext());
4404
+ }
4405
+ buildDeclarationContext() {
4406
+ return {
4407
+ updateState: (body) => {
4408
+ this.context.state.update(body);
4409
+ },
4410
+ evaluateExpression: (expr) => this.evaluateExpression(expr)
4411
+ };
4412
+ }
4413
+ /**
4414
+ * Walk orb directives applying trait / state / lifecycle handlers.
4415
+ * (W1-T4 slice 27: impl extracted to ./runtime/skills-directives.)
4416
+ */
4417
+ applyDirectives(node) {
4418
+ applyDirectives(node, {
4419
+ traitHandlers: this.traitHandlers,
4420
+ emit: (event, payload) => {
4421
+ void this.emit(event, payload);
4422
+ },
4423
+ getCurrentScale: () => this.context.currentScale,
4424
+ state: this.context.state,
4425
+ evaluateExpression: (expr) => this.evaluateExpression(expr)
4426
+ });
4427
+ }
4428
+ getExecutionHistory() {
4429
+ return [...this.executionHistory];
4430
+ }
4431
+ getHologramStates() {
4432
+ return new Map(this.context.hologramState);
4433
+ }
4434
+ getCallStack() {
4435
+ return [...this.callStack];
4436
+ }
4437
+ getState() {
4438
+ return this.context.state.getSnapshot();
4439
+ }
4440
+ getRootScope() {
4441
+ return this.currentScope;
4442
+ }
4443
+ /**
4444
+ * Predicate: is this orb an agent? (W1-T4 slice 27: extracted.)
4445
+ */
4446
+ isAgent(node) {
4447
+ return isAgent(node);
4448
+ }
4449
+ /**
4450
+ * Get current simulation time (Julian date) for orbital calculations
4451
+ */
4452
+ getSimulationTime() {
4453
+ return this.timeManager?.getJulianDate() || 0;
4454
+ }
4455
+ /**
4456
+ * Set orb position and broadcast update
4457
+ */
4458
+ setOrbPosition(orbName, position) {
4459
+ const orb = this.context.variables.get(orbName);
4460
+ if (orb && typeof orb === "object" && orb.__type === "orb") {
4461
+ orb.position = position;
4462
+ this.broadcast("orb_update", {
4463
+ orb: {
4464
+ id: orbName,
4465
+ name: orbName,
4466
+ position
4467
+ }
4468
+ });
4469
+ }
4470
+ }
4471
+ /**
4472
+ * Per-frame trait update — dispatches onUpdate on all active
4473
+ * orbs (W1-T4 slice 27: impl extracted to ./runtime/skills-directives).
4474
+ */
4475
+ updateTraits(julianDate) {
4476
+ updateTraits(julianDate, {
4477
+ variables: this.context.variables,
4478
+ traitHandlers: this.traitHandlers,
4479
+ emit: (event, payload) => this.emit(event, payload),
4480
+ getCurrentScale: () => this.context.currentScale,
4481
+ setOrbPosition: (name, position) => this.setOrbPosition(name, position),
4482
+ getState: () => this.getState(),
4483
+ setState: (updates) => this.context.state.update(updates)
4484
+ });
4485
+ }
4486
+ };
4487
+
4488
+ export { EventBus, HoloScriptAgentRuntime, HoloScriptRuntime, getSharedEventBus, setSharedEventBus, telemetry };
4489
+ //# sourceMappingURL=chunk-IHESJZSW.js.map
4490
+ //# sourceMappingURL=chunk-IHESJZSW.js.map