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