@holoscript/core 6.0.3 → 6.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (368) hide show
  1. package/README.md +40 -40
  2. package/bin/holoscript.cjs +3 -0
  3. package/dist/GLTFPipeline-SFIORFJU.js +16 -0
  4. package/dist/GLTFPipeline-VNNDPONV.cjs +37 -0
  5. package/dist/{HoloScriptPlusParser-BZR5DELQ.js → HoloScriptPlusParser-7FBIFUFC.js} +6 -5
  6. package/dist/{HoloScriptPlusParser-SBMYDNXO.cjs → HoloScriptPlusParser-A2W7OCN2.cjs} +17 -16
  7. package/dist/HoloScriptPlusParser-F2Z56FJR.js +10 -0
  8. package/dist/HoloScriptPlusParser-WKHRIH6T.cjs +27 -0
  9. package/dist/{USDZExporter-MHEHXZB4.cjs → USDZExporter-3FWJ25JI.cjs} +344 -16
  10. package/dist/{USDZExporter-YA55ZS35.js → USDZExporter-D2HQLQYK.js} +344 -16
  11. package/dist/agents/index.cjs +19 -0
  12. package/dist/agents/index.d.ts +100 -0
  13. package/dist/agents/index.js +17 -0
  14. package/dist/chunk-22W6NGYN.js +725 -0
  15. package/dist/{chunk-XSUZMPVQ.cjs → chunk-27MPVJVZ.cjs} +64 -28
  16. package/dist/{chunk-W76ETJTI.js → chunk-2A7FURVO.js} +44 -8
  17. package/dist/{chunk-C7BNX4XJ.js → chunk-2B7WVIDZ.js} +11 -8
  18. package/dist/chunk-2BSMSUCE.js +1941 -0
  19. package/dist/chunk-2HLIGOKU.cjs +5546 -0
  20. package/dist/{chunk-GC3YU46J.js → chunk-2M2DPHKB.js} +4 -4
  21. package/dist/{chunk-A6GO3DPZ.cjs → chunk-2YSNA2F2.cjs} +321 -49
  22. package/dist/{chunk-ZL6VJ6SN.js → chunk-33XCOVE3.js} +5 -5
  23. package/dist/chunk-3FOKASKO.cjs +348 -0
  24. package/dist/{chunk-XSF76QRU.js → chunk-4C57PR42.js} +3 -3
  25. package/dist/chunk-4N4SXXWF.js +769 -0
  26. package/dist/chunk-4PDEPEQW.cjs +41 -0
  27. package/dist/chunk-4R6SBXDB.js +45 -0
  28. package/dist/chunk-4SY77NA4.cjs +413 -0
  29. package/dist/{chunk-74YCHHTE.js → chunk-4UUKPCY4.js} +670 -116
  30. package/dist/{chunk-VZNKJZTT.cjs → chunk-52ULD552.cjs} +178 -113
  31. package/dist/{chunk-65RFOWZI.js → chunk-5CKA5SXU.js} +441 -23
  32. package/dist/chunk-5FSKKMR7.cjs +2092 -0
  33. package/dist/{chunk-FF3Q7ADR.js → chunk-5JEU52DW.js} +5 -3
  34. package/dist/chunk-5N54COB6.cjs +327 -0
  35. package/dist/chunk-5S7RKFGR.cjs +446 -0
  36. package/dist/{chunk-EJA7G2C4.cjs → chunk-5WUNN6ZN.cjs} +2 -2
  37. package/dist/{chunk-ELLQPFAF.js → chunk-6ASWLXXN.js} +24 -10
  38. package/dist/chunk-6CTRH7HT.cjs +1985 -0
  39. package/dist/{chunk-ARNKA274.cjs → chunk-6EX3I5P4.cjs} +6 -6
  40. package/dist/chunk-6FGQNDR4.js +5731 -0
  41. package/dist/{chunk-X4YVN7H3.cjs → chunk-6KMK2UXT.cjs} +152 -56
  42. package/dist/{chunk-KUJRR4FJ.js → chunk-6L4VE27M.js} +36 -24
  43. package/dist/{chunk-RT7LJRSF.cjs → chunk-6S6TKNEA.cjs} +7357 -8312
  44. package/dist/chunk-77V4GTCA.js +596 -0
  45. package/dist/{chunk-XH7SE4HH.cjs → chunk-7AD52FRS.cjs} +19 -19
  46. package/dist/chunk-7OPW2KO7.cjs +639 -0
  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-WN3YF33G.cjs → chunk-AO4I2Z7M.cjs} +15 -17
  51. package/dist/{chunk-TSWTWZ42.cjs → chunk-BPICAGBV.cjs} +376 -209
  52. package/dist/chunk-BRQJKJGT.cjs +20 -0
  53. package/dist/{chunk-3FXV5S25.cjs → chunk-C37BHB7N.cjs} +6 -3
  54. package/dist/{chunk-XNMEH2BI.js → chunk-CBJY23VL.js} +3 -3
  55. package/dist/chunk-CIWWXYHZ.cjs +50 -0
  56. package/dist/{chunk-NTMZSDXM.cjs → chunk-DIL6DDDN.cjs} +101 -45
  57. package/dist/chunk-DMXC24WV.js +404 -0
  58. package/dist/{chunk-SPDELRRV.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-7N3JIJMT.js → chunk-EMMC5CSQ.js} +12 -8
  63. package/dist/{chunk-EUFLX2PI.js → chunk-EOBB6A4B.js} +7263 -8214
  64. package/dist/chunk-EOFNVCM6.js +325 -0
  65. package/dist/{chunk-NKRKT6V2.js → chunk-ER4GATIU.js} +11 -10
  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-HBZYCASG.js → chunk-FXKTYFYA.js} +203 -36
  74. package/dist/chunk-GCMWDSBZ.cjs +729 -0
  75. package/dist/chunk-GJNCFRJU.cjs +125 -0
  76. package/dist/{chunk-I3XGTIHM.cjs → chunk-GMP623FG.cjs} +16 -13
  77. package/dist/{chunk-CNVM7J3M.js → chunk-GN3KDX4W.js} +149 -53
  78. package/dist/{chunk-WFJIDI2N.cjs → chunk-GQYKQSTC.cjs} +10 -10
  79. package/dist/chunk-GTU2Z2WW.cjs +262 -0
  80. package/dist/chunk-GZG4KA4E.js +529 -0
  81. package/dist/{chunk-DIEDKX5B.cjs → chunk-H3MGK7TX.cjs} +45 -33
  82. package/dist/{chunk-DN7UFU63.cjs → chunk-H5DZIHJP.cjs} +14 -17
  83. package/dist/{chunk-DH5G2JUA.cjs → chunk-HANL7K2Q.cjs} +66 -53
  84. package/dist/{chunk-EGIZHYJP.cjs → chunk-HCCQLAA4.cjs} +2 -13
  85. package/dist/{chunk-HHS6FMOU.cjs → chunk-HGVXZDSK.cjs} +178 -29
  86. package/dist/{chunk-LBPEZQAF.js → chunk-HRODTEEO.js} +30 -10
  87. package/dist/{chunk-ZGTGVSTZ.js → chunk-HYNTS5CP.js} +2 -2
  88. package/dist/{chunk-RE3OKSYF.cjs → chunk-HZCQO4JM.cjs} +6 -6
  89. package/dist/{chunk-NCUHGRTZ.js → chunk-I2O7TW6B.js} +12 -8
  90. package/dist/chunk-IHESJZSW.js +4490 -0
  91. package/dist/{chunk-7H5UNJZD.cjs → chunk-IRWWS72C.cjs} +64 -22
  92. package/dist/{chunk-EMO7HAKJ.cjs → chunk-IVIA7K75.cjs} +691 -133
  93. package/dist/chunk-IVY74O6C.js +247 -0
  94. package/dist/chunk-J32ZJZJH.js +554 -0
  95. package/dist/chunk-JD7CIZ33.js +1949 -0
  96. package/dist/{chunk-7X2IEJIE.cjs → chunk-JIYN45TV.cjs} +41 -42
  97. package/dist/{chunk-XDXZM3ZP.cjs → chunk-KHPCJRI3.cjs} +24 -21
  98. package/dist/chunk-KKFZ3B6J.cjs +557 -0
  99. package/dist/chunk-KPJL34Y7.cjs +186 -0
  100. package/dist/{chunk-7KPI4EKH.cjs → chunk-KQTPCYTG.cjs} +130 -50
  101. package/dist/{chunk-F5LVGHNT.js → chunk-KX76JUQY.js} +3 -3
  102. package/dist/chunk-L4LFINPO.js +623 -0
  103. package/dist/{chunk-2UX5LRAP.cjs → chunk-L63H3SQ4.cjs} +46 -32
  104. package/dist/{chunk-NLPSZT4C.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-PQLGZKMC.cjs → chunk-MJVIRCUV.cjs} +31 -27
  109. package/dist/{chunk-AC4BSHFV.js → chunk-MSMIFMBL.js} +135 -18
  110. package/dist/{chunk-56IF4NTA.js → chunk-MXFUTKCO.js} +18 -18
  111. package/dist/{chunk-NRUB55IT.cjs → chunk-MXJ5SS53.cjs} +450 -32
  112. package/dist/chunk-MXWNGCRS.js +2176 -0
  113. package/dist/chunk-MYY4PMWX.cjs +264 -0
  114. package/dist/chunk-N75IH2HY.js +258 -0
  115. package/dist/chunk-NG77ATEW.cjs +778 -0
  116. package/dist/chunk-NW5G5FBQ.js +215 -0
  117. package/dist/{chunk-4FCZDTD5.js → chunk-OEFY723R.js} +29 -16
  118. package/dist/chunk-OEV5RMZO.cjs +3042 -0
  119. package/dist/{chunk-VSXOIUCF.cjs → chunk-OIQYIIO3.cjs} +7 -7
  120. package/dist/{chunk-32TWR3HE.js → chunk-OL46QLBJ.js} +3 -12
  121. package/dist/chunk-OPZ7XDDI.js +487 -0
  122. package/dist/chunk-OSYNRVOV.cjs +243 -0
  123. package/dist/{chunk-HUFNKFA6.js → chunk-P7YIA5LN.js} +93 -13
  124. package/dist/chunk-PGANYCAG.cjs +220 -0
  125. package/dist/{chunk-CO2VM2DK.js → chunk-QAVXL2IH.js} +62 -20
  126. package/dist/{chunk-BO2OKHIY.js → chunk-QCCBXSCE.js} +1640 -1311
  127. package/dist/{chunk-WYH4GVZ5.js → chunk-QPOQ7VPI.js} +16 -13
  128. package/dist/{chunk-V42NTCFH.js → chunk-QTPMJRGS.js} +2331 -17
  129. package/dist/{chunk-FEFHPUEM.cjs → chunk-QWNQ523V.cjs} +1705 -1382
  130. package/dist/{chunk-VK5AXKO3.js → chunk-R3IVNY6P.js} +166 -101
  131. package/dist/chunk-R75BSDH7.cjs +50 -0
  132. package/dist/{chunk-AIUXRS74.cjs → chunk-RMHC2VG7.cjs} +2358 -41
  133. package/dist/chunk-RUXGBKPS.cjs +4517 -0
  134. package/dist/{chunk-PLMYCCA4.js → chunk-S5IFXW6E.js} +113 -9
  135. package/dist/{chunk-27LWW5FU.cjs → chunk-S6YWHCKV.cjs} +5 -5
  136. package/dist/{chunk-SUCBB66F.js → chunk-SIEXCILW.js} +3 -3
  137. package/dist/{chunk-CLYEIWA5.cjs → chunk-SLU6UPJI.cjs} +5 -3
  138. package/dist/{chunk-H6WMMLQK.cjs → chunk-T5J7ZKP3.cjs} +454 -61
  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-BU5ZAFMC.js → chunk-U4NBQJBY.js} +11 -13
  145. package/dist/{chunk-Y5MUAYTO.js → chunk-UD3DSHZM.js} +10 -13
  146. package/dist/chunk-UDMYRFDZ.js +3038 -0
  147. package/dist/{chunk-PPULB4GG.cjs → chunk-UOIGFQXC.cjs} +90 -68
  148. package/dist/{chunk-EPWRXL6S.js → chunk-URG2SJLK.js} +41 -42
  149. package/dist/{chunk-VJVCD5T5.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-4SMUJFHL.js → chunk-VMLKSV26.js} +9 -6
  153. package/dist/{chunk-HKCVM6OK.cjs → chunk-VSK7W3O5.cjs} +47 -27
  154. package/dist/chunk-VVKVQZI6.js +55 -0
  155. package/dist/{chunk-KDB6BUMB.js → chunk-W55Z7QIX.js} +172 -25
  156. package/dist/{chunk-BY3B7ZYV.cjs → chunk-W6P2GBHH.cjs} +3 -3
  157. package/dist/{chunk-PBA6NXCT.cjs → chunk-W6RW64BB.cjs} +11 -8
  158. package/dist/chunk-WDT3JTGM.cjs +483 -0
  159. package/dist/{chunk-26TLYBFD.js → chunk-WKX5AMOY.js} +3 -3
  160. package/dist/chunk-WNNE3PO3.js +34 -0
  161. package/dist/chunk-WRLUBRKS.cjs +1943 -0
  162. package/dist/chunk-WRNEH5MO.js +3169 -0
  163. package/dist/{chunk-54FHG2MX.js → chunk-WRWEX5ZF.js} +7 -4
  164. package/dist/chunk-X3GJPRVK.cjs +3246 -0
  165. package/dist/{chunk-4KJ2R7VP.cjs → chunk-XFXGA5IW.cjs} +126 -22
  166. package/dist/{chunk-L3Z2HIWJ.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-KYM4XRFG.js → chunk-XMWZG36H.js} +4 -4
  170. package/dist/{chunk-BKIGPPVM.js → chunk-XSFNHP2E.js} +6 -3
  171. package/dist/{chunk-ODGMVILH.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-CMYAWUX3.js → chunk-YIMN575O.js} +445 -53
  176. package/dist/chunk-YIVFJNYV.js +176 -0
  177. package/dist/{chunk-V2ILLPHK.cjs → chunk-YKGPCZEE.cjs} +10 -10
  178. package/dist/chunk-YQELFNJV.js +39 -0
  179. package/dist/chunk-YSCKYJOB.cjs +2196 -0
  180. package/dist/chunk-Z5XMPRNC.cjs +5390 -0
  181. package/dist/{chunk-3FYZOR7S.cjs → chunk-ZDSYWBIE.cjs} +18 -18
  182. package/dist/{chunk-CQDOF3G7.cjs → chunk-ZKSS47EV.cjs} +24 -19
  183. package/dist/chunk-ZUL5AVTX.cjs +1993 -0
  184. package/dist/chunk-ZXBZVXDW.js +5386 -0
  185. package/dist/{chunk-AW7WAELW.js → chunk-ZZ7RO2UQ.js} +314 -46
  186. package/dist/cli/holoscript-runner.cjs +203 -206
  187. package/dist/cli/holoscript-runner.js +147 -150
  188. package/dist/codebase/index.cjs +1 -1
  189. package/dist/codebase/index.d.ts +25 -0
  190. package/dist/codebase/index.js +1 -1
  191. package/dist/compiler/agent-inference.cjs +10 -8
  192. package/dist/compiler/agent-inference.js +6 -4
  193. package/dist/compiler/android-xr.cjs +12 -8
  194. package/dist/compiler/android-xr.js +10 -6
  195. package/dist/compiler/android.cjs +12 -9
  196. package/dist/compiler/android.js +10 -7
  197. package/dist/compiler/ar.cjs +9 -7
  198. package/dist/compiler/ar.js +7 -5
  199. package/dist/compiler/babylon.cjs +12 -9
  200. package/dist/compiler/babylon.js +11 -8
  201. package/dist/compiler/business-quest.cjs +43 -0
  202. package/dist/compiler/business-quest.js +4 -0
  203. package/dist/compiler/coco.cjs +1 -1
  204. package/dist/compiler/coco.js +1 -1
  205. package/dist/compiler/context.cjs +25 -0
  206. package/dist/compiler/context.d.ts +28 -0
  207. package/dist/compiler/context.js +8 -0
  208. package/dist/compiler/domain-block-utils.cjs +161 -151
  209. package/dist/compiler/domain-block-utils.js +7 -5
  210. package/dist/compiler/dtdl.cjs +10 -8
  211. package/dist/compiler/dtdl.js +7 -5
  212. package/dist/compiler/gltf-pipeline.cjs +9 -9
  213. package/dist/compiler/gltf-pipeline.js +2 -2
  214. package/dist/compiler/godot.cjs +9 -7
  215. package/dist/compiler/godot.js +8 -6
  216. package/dist/compiler/incremental.cjs +12 -8
  217. package/dist/compiler/incremental.js +7 -3
  218. package/dist/compiler/index.cjs +5152 -814
  219. package/dist/compiler/index.d.ts +404 -21
  220. package/dist/compiler/index.js +5063 -859
  221. package/dist/compiler/ios.cjs +11 -9
  222. package/dist/compiler/ios.js +9 -7
  223. package/dist/compiler/llm-provider-capabilities.cjs +25 -0
  224. package/dist/compiler/llm-provider-capabilities.d.ts +43 -0
  225. package/dist/compiler/llm-provider-capabilities.js +8 -0
  226. package/dist/compiler/multi-layer.cjs +14 -17
  227. package/dist/compiler/multi-layer.js +13 -10
  228. package/dist/compiler/nodetoy.cjs +5 -5
  229. package/dist/compiler/nodetoy.js +2 -2
  230. package/dist/compiler/openxr.cjs +10 -7
  231. package/dist/compiler/openxr.js +9 -6
  232. package/dist/compiler/playcanvas.cjs +10 -8
  233. package/dist/compiler/playcanvas.js +9 -7
  234. package/dist/compiler/r3f.cjs +17 -14
  235. package/dist/compiler/r3f.d.ts +22 -0
  236. package/dist/compiler/r3f.js +12 -9
  237. package/dist/compiler/remotion.cjs +1 -1
  238. package/dist/compiler/remotion.js +1 -1
  239. package/dist/compiler/reproducibility.cjs +1 -1
  240. package/dist/compiler/reproducibility.js +1 -1
  241. package/dist/compiler/sdf.cjs +10 -8
  242. package/dist/compiler/sdf.js +8 -6
  243. package/dist/compiler/semantic-scene.cjs +7 -7
  244. package/dist/compiler/semantic-scene.js +2 -2
  245. package/dist/compiler/state.cjs +9 -6
  246. package/dist/compiler/state.js +7 -4
  247. package/dist/compiler/trait-composition.cjs +11 -8
  248. package/dist/compiler/trait-composition.js +7 -4
  249. package/dist/compiler/unity.cjs +10 -7
  250. package/dist/compiler/unity.js +9 -6
  251. package/dist/compiler/unreal.cjs +11 -8
  252. package/dist/compiler/unreal.js +9 -6
  253. package/dist/compiler/urdf.cjs +20 -14
  254. package/dist/compiler/urdf.js +8 -6
  255. package/dist/compiler/usd-physics.cjs +10 -8
  256. package/dist/compiler/usd-physics.js +7 -5
  257. package/dist/compiler/visionos.cjs +10 -7
  258. package/dist/compiler/visionos.js +9 -6
  259. package/dist/compiler/vrchat.cjs +10 -8
  260. package/dist/compiler/vrchat.js +8 -6
  261. package/dist/compiler/vrr.cjs +10 -8
  262. package/dist/compiler/vrr.js +8 -6
  263. package/dist/compiler/wasm.cjs +13 -11
  264. package/dist/compiler/wasm.js +8 -6
  265. package/dist/compiler/webgpu.cjs +9 -7
  266. package/dist/compiler/webgpu.js +8 -6
  267. package/dist/constants.d.ts +4 -0
  268. package/dist/coordinators/index.cjs +1266 -0
  269. package/dist/coordinators/index.d.ts +260 -0
  270. package/dist/coordinators/index.js +1259 -0
  271. package/dist/debugger.cjs +9 -7
  272. package/dist/debugger.js +7 -5
  273. package/dist/entries/interop.cjs +23 -21
  274. package/dist/entries/interop.d.ts +9 -0
  275. package/dist/entries/interop.js +5 -3
  276. package/dist/entries/scripting.cjs +18 -17
  277. package/dist/entries/scripting.d.ts +7 -0
  278. package/dist/entries/scripting.js +8 -7
  279. package/dist/hololand/index.cjs +146 -0
  280. package/dist/hololand/index.d.ts +70 -0
  281. package/dist/hololand/index.js +5 -0
  282. package/dist/index.cjs +21396 -39967
  283. package/dist/index.d.ts +1496 -40
  284. package/dist/index.js +21066 -40142
  285. package/dist/math/tropical-spmv.cjs +45 -0
  286. package/dist/math/tropical-spmv.js +4 -0
  287. package/dist/math/vec3.cjs +14 -14
  288. package/dist/math/vec3.js +2 -2
  289. package/dist/ml-dsa-FSKBTE3W.cjs +1265 -0
  290. package/dist/ml-dsa-Z7JDKW4L.js +1265 -0
  291. package/dist/paper-0c-spike/index.cjs +150 -0
  292. package/dist/paper-0c-spike/index.d.ts +29 -0
  293. package/dist/paper-0c-spike/index.js +141 -0
  294. package/dist/parser.cjs +45 -10
  295. package/dist/parser.d.ts +11 -0
  296. package/dist/parser.js +10 -7
  297. package/dist/{playwright-7DTEQCBD.cjs → playwright-3AT3AKTV.cjs} +1985 -1985
  298. package/dist/{playwright-BIZXMLD2.js → playwright-VZPDVUEQ.js} +3 -3
  299. package/dist/reconstruction/index.cjs +153 -0
  300. package/dist/reconstruction/index.d.ts +105 -0
  301. package/dist/reconstruction/index.js +8 -0
  302. package/dist/runtime.cjs +7 -5
  303. package/dist/runtime.js +6 -4
  304. package/dist/self-improvement/index.cjs +563 -0
  305. package/dist/self-improvement/index.d.ts +0 -48
  306. package/dist/self-improvement/index.js +545 -0
  307. package/dist/storage/index.cjs +10 -9
  308. package/dist/storage/index.d.ts +24 -0
  309. package/dist/storage/index.js +3 -2
  310. package/dist/testing.cjs +25 -0
  311. package/dist/testing.d.ts +70 -0
  312. package/dist/testing.js +4 -0
  313. package/dist/tools/index.d.ts +33 -0
  314. package/dist/traitDocs/traitDocs.cjs +33 -0
  315. package/dist/traitDocs/traitDocs.d.ts +69 -0
  316. package/dist/traitDocs/traitDocs.js +7 -0
  317. package/dist/traits/botanical-lotus.cjs +41 -0
  318. package/dist/traits/botanical-lotus.d.ts +172 -0
  319. package/dist/traits/botanical-lotus.js +4 -0
  320. package/dist/traits/engines/index.cjs +520 -0
  321. package/dist/traits/engines/index.d.ts +111 -0
  322. package/dist/traits/engines/index.js +380 -0
  323. package/dist/traits/index.cjs +14387 -4320
  324. package/dist/traits/index.d.ts +197 -0
  325. package/dist/traits/index.js +16455 -6958
  326. package/dist/traits/simulation-solver-factory.cjs +13 -0
  327. package/dist/traits/simulation-solver-factory.d.ts +23 -0
  328. package/dist/traits/simulation-solver-factory.js +4 -0
  329. package/dist/traits/webcam-gaze.cjs +35 -0
  330. package/dist/traits/webcam-gaze.d.ts +17 -0
  331. package/dist/traits/webcam-gaze.js +4 -0
  332. package/dist/type-checker.cjs +6 -5
  333. package/dist/type-checker.js +4 -3
  334. package/dist/world/index.cjs +947 -0
  335. package/dist/world/index.d.ts +147 -0
  336. package/dist/world/index.js +939 -0
  337. package/dist/world-model/index.cjs +1446 -0
  338. package/dist/world-model/index.d.ts +119 -0
  339. package/dist/world-model/index.js +1414 -0
  340. package/dist/wot/index.cjs +7 -7
  341. package/dist/wot/index.js +2 -2
  342. package/package.json +150 -23
  343. package/dist/GLTFPipeline-3KLWWUQO.cjs +0 -34
  344. package/dist/GLTFPipeline-LYII2ZVQ.js +0 -13
  345. package/dist/chunk-3KEU5QYY.cjs +0 -175
  346. package/dist/chunk-6OQBLABR.js +0 -5240
  347. package/dist/chunk-6WNCRE6F.js +0 -126
  348. package/dist/chunk-C2QHVHZF.js +0 -4066
  349. package/dist/chunk-CN4NOESF.cjs +0 -416
  350. package/dist/chunk-DXVCEFZB.js +0 -2027
  351. package/dist/chunk-ENV7K6XA.js +0 -282
  352. package/dist/chunk-H7XMORZI.js +0 -2731
  353. package/dist/chunk-HAN4V3PF.cjs +0 -2037
  354. package/dist/chunk-HF4OFY25.cjs +0 -4097
  355. package/dist/chunk-LER4WXW5.cjs +0 -286
  356. package/dist/chunk-M6FU6S22.js +0 -2911
  357. package/dist/chunk-MWEFR6YQ.js +0 -1857
  358. package/dist/chunk-PJMOXFPR.cjs +0 -1861
  359. package/dist/chunk-QHVVVN47.cjs +0 -2033
  360. package/dist/chunk-QWKUKVRE.js +0 -2026
  361. package/dist/chunk-UITWA6DV.cjs +0 -2829
  362. package/dist/chunk-UQW6SLM5.js +0 -172
  363. package/dist/chunk-WUXIRGZP.cjs +0 -2915
  364. package/dist/chunk-X67XRI2T.js +0 -410
  365. package/dist/chunk-Y7VK5TH3.cjs +0 -129
  366. package/dist/chunk-YCMQQQ5U.cjs +0 -5244
  367. package/dist/post-quantum-JTTAAGO3.cjs +0 -6
  368. package/dist/post-quantum-RVPVDEPI.js +0 -4
@@ -1,6 +1,11 @@
1
- import { __esm } from './chunk-32TWR3HE.js';
1
+ import { init_traitDocs, getTraitDoc, formatTraitDocCompact } from './chunk-THCK6ECW.js';
2
+ import { init_AgentRiskRegistry, getAgentRiskRegistry, TIER_COMPOSITION_RISK_CAP, isDangerousOperation } from './chunk-N75IH2HY.js';
3
+ import { init_safeJsonParse, safeJsonParse, readJson } from './chunk-VVKVQZI6.js';
4
+ import { __esm } from './chunk-OL46QLBJ.js';
2
5
  import * as crypto3 from 'crypto';
6
+ import { createHash } from 'crypto';
3
7
  import { promisify } from 'util';
8
+ import { z } from 'zod';
4
9
  import jwt from 'jsonwebtoken';
5
10
  import path from 'path';
6
11
 
@@ -181,6 +186,60 @@ var init_AgentIdentity = __esm({
181
186
  });
182
187
 
183
188
  // src/traits/CultureTraits.ts
189
+ function normalizeNormProvenance(value) {
190
+ if (!value) return { ...UNKNOWN_NORM_PROVENANCE };
191
+ return {
192
+ source: value.source ?? "unknown",
193
+ ...value.sourceAgentId !== void 0 && { sourceAgentId: value.sourceAgentId },
194
+ ...value.sourceCorpus !== void 0 && { sourceCorpus: value.sourceCorpus },
195
+ ...value.declarationSite !== void 0 && { declarationSite: value.declarationSite },
196
+ ...value.originInteractionId !== void 0 && {
197
+ originInteractionId: value.originInteractionId
198
+ },
199
+ ...value.confidenceClassification !== void 0 && {
200
+ confidenceClassification: value.confidenceClassification
201
+ },
202
+ ...value.recordedAtIso !== void 0 && { recordedAtIso: value.recordedAtIso }
203
+ };
204
+ }
205
+ function serializeNormProvenance(value) {
206
+ return normalizeNormProvenance(value);
207
+ }
208
+ function deserializeNormProvenance(value) {
209
+ if (!value || typeof value !== "object") return { ...UNKNOWN_NORM_PROVENANCE };
210
+ const obj = value;
211
+ const knownSources = [
212
+ "agent",
213
+ "corpus",
214
+ "declaration_site",
215
+ "builtin",
216
+ "observation",
217
+ "unknown"
218
+ ];
219
+ const rawSource = obj.source;
220
+ const source = typeof rawSource === "string" && knownSources.includes(rawSource) ? rawSource : "unknown";
221
+ const result = { source };
222
+ if (typeof obj.sourceAgentId === "string") result.sourceAgentId = obj.sourceAgentId;
223
+ if (typeof obj.sourceCorpus === "string") result.sourceCorpus = obj.sourceCorpus;
224
+ if (obj.declarationSite && typeof obj.declarationSite === "object") {
225
+ const site = obj.declarationSite;
226
+ if (typeof site.file === "string") {
227
+ result.declarationSite = {
228
+ file: site.file,
229
+ ...typeof site.line === "number" && { line: site.line },
230
+ ...typeof site.column === "number" && { column: site.column }
231
+ };
232
+ }
233
+ }
234
+ if (typeof obj.originInteractionId === "string") {
235
+ result.originInteractionId = obj.originInteractionId;
236
+ }
237
+ if (obj.confidenceClassification === "genuine" || obj.confidenceClassification === "confabulated" || obj.confidenceClassification === "bullshitted") {
238
+ result.confidenceClassification = obj.confidenceClassification;
239
+ }
240
+ if (typeof obj.recordedAtIso === "string") result.recordedAtIso = obj.recordedAtIso;
241
+ return result;
242
+ }
184
243
  function getBuiltinNorm(id) {
185
244
  return BUILTIN_NORMS.find((n) => n.id === id);
186
245
  }
@@ -205,9 +264,17 @@ function getFamilyCompatibility(familyA, familyB) {
205
264
  }
206
265
  return { rating: "compatible", reason: "No known incompatibility between these families." };
207
266
  }
208
- var BUILTIN_NORMS, CULTURAL_FAMILY_COMPATIBILITY, CONTRADICTORY_NORM_PAIRS, customContradictoryNorms;
267
+ var UNKNOWN_NORM_PROVENANCE, BUILTIN_NORM_PROVENANCE, BUILTIN_NORMS, CULTURAL_FAMILY_COMPATIBILITY, CONTRADICTORY_NORM_PAIRS, customContradictoryNorms;
209
268
  var init_CultureTraits = __esm({
210
269
  "src/traits/CultureTraits.ts"() {
270
+ UNKNOWN_NORM_PROVENANCE = Object.freeze({
271
+ source: "unknown"
272
+ });
273
+ BUILTIN_NORM_PROVENANCE = Object.freeze({
274
+ source: "builtin",
275
+ sourceCorpus: "@holoscript/core/BUILTIN_NORMS",
276
+ confidenceClassification: "genuine"
277
+ });
211
278
  BUILTIN_NORMS = [
212
279
  // Safety norms
213
280
  {
@@ -219,7 +286,8 @@ var init_CultureTraits = __esm({
219
286
  scope: "world",
220
287
  activationThreshold: 0,
221
288
  strength: "strong",
222
- forbiddenEffects: ["agent:kill", "inventory:destroy", "physics:teleport"]
289
+ forbiddenEffects: ["agent:kill", "inventory:destroy", "physics:teleport"],
290
+ provenance: BUILTIN_NORM_PROVENANCE
223
291
  },
224
292
  {
225
293
  id: "resource_sharing",
@@ -230,7 +298,8 @@ var init_CultureTraits = __esm({
230
298
  scope: "zone",
231
299
  activationThreshold: 0.5,
232
300
  strength: "moderate",
233
- requiredEffects: ["inventory:give"]
301
+ requiredEffects: ["inventory:give"],
302
+ provenance: BUILTIN_NORM_PROVENANCE
234
303
  },
235
304
  {
236
305
  id: "zone_respect",
@@ -242,7 +311,8 @@ var init_CultureTraits = __esm({
242
311
  activationThreshold: 0.3,
243
312
  strength: "moderate",
244
313
  requiredEffects: ["agent:communicate"],
245
- forbiddenEffects: ["authority:zone"]
314
+ forbiddenEffects: ["authority:zone"],
315
+ provenance: BUILTIN_NORM_PROVENANCE
246
316
  },
247
317
  {
248
318
  id: "fair_trade",
@@ -253,7 +323,8 @@ var init_CultureTraits = __esm({
253
323
  scope: "world",
254
324
  activationThreshold: 0,
255
325
  strength: "strong",
256
- requiredEffects: ["inventory:trade", "agent:communicate"]
326
+ requiredEffects: ["inventory:trade", "agent:communicate"],
327
+ provenance: BUILTIN_NORM_PROVENANCE
257
328
  },
258
329
  {
259
330
  id: "greeting_convention",
@@ -264,7 +335,8 @@ var init_CultureTraits = __esm({
264
335
  scope: "session",
265
336
  activationThreshold: 0.6,
266
337
  strength: "weak",
267
- requiredEffects: ["agent:communicate"]
338
+ requiredEffects: ["agent:communicate"],
339
+ provenance: BUILTIN_NORM_PROVENANCE
268
340
  },
269
341
  {
270
342
  id: "noise_courtesy",
@@ -275,7 +347,8 @@ var init_CultureTraits = __esm({
275
347
  scope: "zone",
276
348
  activationThreshold: 0.4,
277
349
  strength: "moderate",
278
- forbiddenEffects: ["audio:global"]
350
+ forbiddenEffects: ["audio:global"],
351
+ provenance: BUILTIN_NORM_PROVENANCE
279
352
  },
280
353
  {
281
354
  id: "spawn_limits",
@@ -286,8 +359,9 @@ var init_CultureTraits = __esm({
286
359
  scope: "zone",
287
360
  activationThreshold: 0,
288
361
  strength: "strong",
289
- forbiddenEffects: ["render:spawn"]
362
+ forbiddenEffects: ["render:spawn"],
290
363
  // Catches excessive spawning via budget
364
+ provenance: BUILTIN_NORM_PROVENANCE
291
365
  },
292
366
  {
293
367
  id: "metanorm_enforcement",
@@ -298,7 +372,8 @@ var init_CultureTraits = __esm({
298
372
  scope: "world",
299
373
  activationThreshold: 0.7,
300
374
  strength: "weak",
301
- requiredEffects: ["agent:communicate", "agent:observe"]
375
+ requiredEffects: ["agent:communicate", "agent:observe"],
376
+ provenance: BUILTIN_NORM_PROVENANCE
302
377
  }
303
378
  ];
304
379
  CULTURAL_FAMILY_COMPATIBILITY = [
@@ -375,10 +450,18 @@ function getKeystore(config) {
375
450
  }
376
451
  return globalKeystore;
377
452
  }
378
- var DEFAULT_TOKEN_LIFETIME, ENCRYPTION_ALGORITHM, KEY_LENGTH, IV_LENGTH, SALT_LENGTH, AgentKeystore, globalKeystore;
453
+ var SerializedCredentialSchema, DEFAULT_TOKEN_LIFETIME, ENCRYPTION_ALGORITHM, KEY_LENGTH, IV_LENGTH, SALT_LENGTH, AgentKeystore, globalKeystore;
379
454
  var init_AgentKeystore = __esm({
380
455
  "src/compiler/identity/AgentKeystore.ts"() {
381
456
  init_AgentIdentity();
457
+ init_safeJsonParse();
458
+ SerializedCredentialSchema = z.object({
459
+ role: z.string(),
460
+ token: z.string(),
461
+ keyPair: z.unknown(),
462
+ createdAt: z.string(),
463
+ expiresAt: z.string()
464
+ });
382
465
  DEFAULT_TOKEN_LIFETIME = 24 * 60 * 60 * 1e3;
383
466
  ENCRYPTION_ALGORITHM = "aes-256-gcm";
384
467
  KEY_LENGTH = 32;
@@ -509,7 +592,21 @@ var init_AgentKeystore = __esm({
509
592
  return this.getCredential(role);
510
593
  }
511
594
  const decrypted = this.decrypt(encrypted);
512
- const parsed = JSON.parse(decrypted);
595
+ const parseResult = safeJsonParse(decrypted, SerializedCredentialSchema);
596
+ if (!parseResult.ok) {
597
+ this.logAudit({
598
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
599
+ event: "key_parse_failed",
600
+ agentRole: role,
601
+ details: {
602
+ source: "storage",
603
+ error: parseResult.error.message,
604
+ kind: parseResult.error.kind
605
+ }
606
+ });
607
+ return null;
608
+ }
609
+ const parsed = parseResult.value;
513
610
  const credential = {
514
611
  role: parsed.role,
515
612
  token: parsed.token,
@@ -704,6 +801,7 @@ function getCapabilityTokenIssuer(config) {
704
801
  var HoloScriptCapabilitySemantics, CapabilityTokenIssuer, globalCapabilityIssuer;
705
802
  var init_CapabilityTokenIssuer = __esm({
706
803
  "src/compiler/identity/CapabilityTokenIssuer.ts"() {
804
+ init_safeJsonParse();
707
805
  init_AgentIdentity();
708
806
  init_CapabilityToken();
709
807
  HoloScriptCapabilitySemantics = class {
@@ -828,7 +926,8 @@ var init_CapabilityTokenIssuer = __esm({
828
926
  }
829
927
  }
830
928
  const now = Math.floor(Date.now() / 1e3);
831
- const requestedLifetime = lifetimeSec ?? this.defaultLifetimeSec;
929
+ const parentRemainingLifetime = Math.max(0, parentPayload.exp - now);
930
+ const requestedLifetime = lifetimeSec ?? Math.min(this.defaultLifetimeSec, parentRemainingLifetime);
832
931
  const childExp = now + requestedLifetime;
833
932
  if (this.strictExpiration && childExp > parentPayload.exp) {
834
933
  throw new Error(
@@ -941,7 +1040,7 @@ var init_CapabilityTokenIssuer = __esm({
941
1040
  }
942
1041
  let payload;
943
1042
  try {
944
- payload = JSON.parse(base64urlDecode(payloadB64).toString("utf-8"));
1043
+ payload = readJson(base64urlDecode(payloadB64).toString("utf-8"));
945
1044
  } catch {
946
1045
  return {
947
1046
  valid: false,
@@ -3325,6 +3424,7 @@ var init_AgentRBAC = __esm({
3325
3424
  init_AgentTokenIssuer();
3326
3425
  init_CulturalCompatibilityChecker();
3327
3426
  init_ConfabulationValidator();
3427
+ init_AgentRiskRegistry();
3328
3428
  RESOURCE_PERMISSION_MAP = {
3329
3429
  ["source_file" /* SOURCE_FILE */]: {
3330
3430
  read: "read:source" /* READ_SOURCE */,
@@ -3589,6 +3689,122 @@ var init_AgentRBAC = __esm({
3589
3689
  return validator.validateComposition(composition);
3590
3690
  }
3591
3691
  // ===========================================================================
3692
+ // CONFABULATION RISK TIER GATE (v1.2.0)
3693
+ //
3694
+ // Sibling of the per-composition schema gate. Where the schema gate asks
3695
+ // "is THIS composition structurally valid?", the risk-tier gate asks
3696
+ // "given this AGENT's history, should we tighten the per-composition
3697
+ // threshold or block dangerous ops outright?"
3698
+ //
3699
+ // Pipeline:
3700
+ // 1. Standard RBAC check (token, role, scope, workflow).
3701
+ // 2. Confabulation schema validation against the supplied composition.
3702
+ // 3. Look up the agent's current risk tier in the AgentRiskRegistry.
3703
+ // 4. If the op is dangerous (write/transform/execute), apply the tier's
3704
+ // composition risk cap. Quarantined agents are blocked outright.
3705
+ // 5. Record the validation outcome back into the registry so the agent's
3706
+ // tier evolves with their behavior.
3707
+ // ===========================================================================
3708
+ /**
3709
+ * Check access with both the schema gate AND the per-agent risk tier gate.
3710
+ *
3711
+ * Use this as the primary enforcement point for any AI-generated content
3712
+ * that will land in a downstream compiler target.
3713
+ *
3714
+ * @param request - Standard resource access request.
3715
+ * @param composition - Composition the agent wants to commit/transform.
3716
+ * @param options - Optional registry override + per-call confabulation config.
3717
+ * @returns Extended access decision including risk tier and applied cap.
3718
+ */
3719
+ checkAccessWithRiskGate(request, composition, options) {
3720
+ const registry = options?.registry ?? getAgentRiskRegistry();
3721
+ const dryRun = options?.dryRun ?? false;
3722
+ const rbacDecision = this.checkAccess(request);
3723
+ if (!rbacDecision.allowed) {
3724
+ return rbacDecision;
3725
+ }
3726
+ const verification = this.tokenIssuer.verifyToken(request.token);
3727
+ const agentId = verification.valid && verification.payload ? verification.payload.sub : void 0;
3728
+ if (!agentId) {
3729
+ return {
3730
+ allowed: false,
3731
+ reason: "Risk gate cannot identify agent (missing sub claim)",
3732
+ agentRole: rbacDecision.agentRole
3733
+ };
3734
+ }
3735
+ const validator = options?.confabConfig ? new ConfabulationValidator(options.confabConfig) : getConfabulationValidator();
3736
+ const confabResult = validator.validateComposition(composition);
3737
+ const tier = registry.getTier(agentId);
3738
+ const riskScore = registry.getScore(agentId);
3739
+ const cap = TIER_COMPOSITION_RISK_CAP[tier];
3740
+ if (isDangerousOperation(request.operation)) {
3741
+ if (tier === "quarantined" /* QUARANTINED */) {
3742
+ return {
3743
+ allowed: false,
3744
+ reason: `Agent ${agentId} is quarantined (risk score: ${riskScore.toFixed(1)}). Dangerous operation '${request.operation}' on '${request.resourceType}' blocked.`,
3745
+ agentRole: rbacDecision.agentRole,
3746
+ confabulation: confabResult,
3747
+ agentId,
3748
+ riskTier: tier,
3749
+ riskScore,
3750
+ appliedRiskCap: cap
3751
+ };
3752
+ }
3753
+ if (confabResult.riskScore > cap) {
3754
+ if (!dryRun) {
3755
+ registry.recordValidation(agentId, confabResult);
3756
+ }
3757
+ return {
3758
+ allowed: false,
3759
+ reason: `Composition risk ${confabResult.riskScore} exceeds tier ${tier} cap ${cap} for dangerous operation '${request.operation}' on '${request.resourceType}'. Agent ${agentId} (score: ${riskScore.toFixed(1)}). ${confabResult.errors.length} confabulation error(s).`,
3760
+ agentRole: rbacDecision.agentRole,
3761
+ confabulation: confabResult,
3762
+ agentId,
3763
+ riskTier: tier,
3764
+ riskScore,
3765
+ appliedRiskCap: cap
3766
+ };
3767
+ }
3768
+ } else {
3769
+ if (!confabResult.valid) {
3770
+ if (!dryRun) {
3771
+ registry.recordValidation(agentId, confabResult);
3772
+ }
3773
+ return {
3774
+ allowed: false,
3775
+ reason: `Confabulation detected (risk score: ${confabResult.riskScore}/100, ${confabResult.errors.length} error(s)): ` + confabResult.errors.map((e) => e.message).join("; "),
3776
+ agentRole: rbacDecision.agentRole,
3777
+ confabulation: confabResult,
3778
+ agentId,
3779
+ riskTier: tier,
3780
+ riskScore,
3781
+ appliedRiskCap: cap
3782
+ };
3783
+ }
3784
+ }
3785
+ if (!dryRun) {
3786
+ registry.recordValidation(agentId, confabResult);
3787
+ }
3788
+ return {
3789
+ ...rbacDecision,
3790
+ confabulation: confabResult,
3791
+ agentId,
3792
+ riskTier: tier,
3793
+ riskScore,
3794
+ appliedRiskCap: cap
3795
+ };
3796
+ }
3797
+ /**
3798
+ * Look up an agent's current risk tier without performing an access check.
3799
+ * Useful for dashboards and pre-flight checks.
3800
+ */
3801
+ getAgentRiskTier(token, registry) {
3802
+ const verification = this.tokenIssuer.verifyToken(token);
3803
+ if (!verification.valid || !verification.payload) return null;
3804
+ const reg = registry ?? getAgentRiskRegistry();
3805
+ return reg.getTier(verification.payload.sub);
3806
+ }
3807
+ // ===========================================================================
3592
3808
  // CULTURAL PROFILE INTEGRATION
3593
3809
  // ===========================================================================
3594
3810
  /**
@@ -3640,6 +3856,2104 @@ var init_AgentRBAC = __esm({
3640
3856
  }
3641
3857
  });
3642
3858
 
3643
- export { BUILTIN_NORMS, HOLOSCRIPT_RESOURCE_SCHEME, HoloScriptCapabilitySemantics, criticalMassForChange, getBuiltinNorm, getCapabilityTokenIssuer, getRBAC, getTokenIssuer, init_AgentRBAC, init_AgentTokenIssuer, init_CapabilityToken, init_CapabilityTokenIssuer, init_CultureTraits, normsByCategory };
3644
- //# sourceMappingURL=chunk-V42NTCFH.js.map
3645
- //# sourceMappingURL=chunk-V42NTCFH.js.map
3859
+ // src/compiler/identity/ANSNamespace.ts
3860
+ function isValidCompilerName(name) {
3861
+ return ALL_COMPILER_NAMES.includes(name);
3862
+ }
3863
+ var ANSDomain, ANSRiskTier, ANSCapabilityPath, COMPILER_DOMAIN_MAP, COMPILER_ANS_MAP, ALL_COMPILER_NAMES;
3864
+ var init_ANSNamespace = __esm({
3865
+ "src/compiler/identity/ANSNamespace.ts"() {
3866
+ ANSDomain = {
3867
+ GAMEDEV: "gamedev",
3868
+ SOCIAL_VR: "social-vr",
3869
+ XR: "xr",
3870
+ MOBILE: "mobile",
3871
+ WEB3D: "web3d",
3872
+ RUNTIME: "runtime",
3873
+ SHADER: "shader",
3874
+ ROBOTICS: "robotics",
3875
+ INTERCHANGE: "interchange",
3876
+ IOT: "iot",
3877
+ WEB3: "web3",
3878
+ AI: "ai",
3879
+ NEUROMORPHIC: "neuromorphic",
3880
+ META: "meta",
3881
+ MIXIN: "mixin"
3882
+ };
3883
+ ANSRiskTier = {
3884
+ STANDARD: "STANDARD",
3885
+ HIGH: "HIGH",
3886
+ CRITICAL: "CRITICAL"
3887
+ };
3888
+ ({
3889
+ [ANSDomain.GAMEDEV]: ANSRiskTier.STANDARD,
3890
+ [ANSDomain.SOCIAL_VR]: ANSRiskTier.HIGH,
3891
+ [ANSDomain.XR]: ANSRiskTier.HIGH,
3892
+ [ANSDomain.MOBILE]: ANSRiskTier.HIGH,
3893
+ [ANSDomain.WEB3D]: ANSRiskTier.STANDARD,
3894
+ [ANSDomain.RUNTIME]: ANSRiskTier.HIGH,
3895
+ [ANSDomain.SHADER]: ANSRiskTier.STANDARD,
3896
+ [ANSDomain.ROBOTICS]: ANSRiskTier.CRITICAL,
3897
+ [ANSDomain.INTERCHANGE]: ANSRiskTier.STANDARD,
3898
+ [ANSDomain.IOT]: ANSRiskTier.HIGH,
3899
+ [ANSDomain.WEB3]: ANSRiskTier.CRITICAL,
3900
+ [ANSDomain.AI]: ANSRiskTier.HIGH,
3901
+ [ANSDomain.NEUROMORPHIC]: ANSRiskTier.HIGH,
3902
+ [ANSDomain.META]: ANSRiskTier.STANDARD,
3903
+ [ANSDomain.MIXIN]: ANSRiskTier.STANDARD
3904
+ });
3905
+ ANSCapabilityPath = {
3906
+ // ── gamedev ──────────────────────────────────────────────────────────
3907
+ UNITY: "/compile/gamedev/unity",
3908
+ UNREAL: "/compile/gamedev/unreal",
3909
+ GODOT: "/compile/gamedev/godot",
3910
+ // ── social-vr ────────────────────────────────────────────────────────
3911
+ VRCHAT: "/compile/social-vr/vrchat",
3912
+ // ── xr ───────────────────────────────────────────────────────────────
3913
+ OPENXR: "/compile/xr/openxr",
3914
+ OPENXR_SPATIAL_ENTITIES: "/compile/xr/openxr-spatial-entities",
3915
+ VISIONOS: "/compile/xr/visionos",
3916
+ AR: "/compile/xr/ar",
3917
+ ANDROID_XR: "/compile/xr/android-xr",
3918
+ AI_GLASSES: "/compile/xr/ai-glasses",
3919
+ QUILT: "/compile/xr/quilt",
3920
+ MV_HEVC: "/compile/xr/mv-hevc",
3921
+ // ── mobile ───────────────────────────────────────────────────────────
3922
+ ANDROID: "/compile/mobile/android",
3923
+ IOS: "/compile/mobile/ios",
3924
+ // ── web3d ────────────────────────────────────────────────────────────
3925
+ BABYLON: "/compile/web3d/babylon",
3926
+ WEBGPU: "/compile/web3d/webgpu",
3927
+ R3F: "/compile/web3d/r3f",
3928
+ PLAYCANVAS: "/compile/web3d/playcanvas",
3929
+ THREEJS: "/compile/web3d/threejs",
3930
+ // ── runtime ──────────────────────────────────────────────────────────
3931
+ WASM: "/compile/runtime/wasm",
3932
+ NODE_SERVICE: "/compile/runtime/node-service",
3933
+ NEXTJS_API: "/compile/runtime/nextjs-api",
3934
+ // ── shader ───────────────────────────────────────────────────────────
3935
+ TSL: "/compile/shader/tsl",
3936
+ // ── robotics ─────────────────────────────────────────────────────────
3937
+ URDF: "/compile/robotics/urdf",
3938
+ SDF: "/compile/robotics/sdf",
3939
+ // ── interchange ──────────────────────────────────────────────────────
3940
+ USD: "/compile/interchange/usd",
3941
+ GLTF: "/compile/interchange/gltf",
3942
+ GAUSSIAN_SPLATTING: "/compile/interchange/3dgs",
3943
+ // ── iot ──────────────────────────────────────────────────────────────
3944
+ DTDL: "/compile/iot/dtdl",
3945
+ // ── web3 ─────────────────────────────────────────────────────────────
3946
+ NFT_MARKETPLACE: "/compile/web3/nft-marketplace",
3947
+ // ── ai ───────────────────────────────────────────────────────────────
3948
+ SCM: "/compile/ai/scm",
3949
+ VRR: "/compile/ai/vrr",
3950
+ A2A_AGENT_CARD: "/compile/ai/a2a-agent-card",
3951
+ AGENT_INFERENCE: "/compile/ai/agent-inference",
3952
+ // ── neuromorphic ─────────────────────────────────────────────────────
3953
+ NIR: "/compile/neuromorphic/nir",
3954
+ // ── meta ─────────────────────────────────────────────────────────────
3955
+ MULTI_LAYER: "/compile/meta/multi-layer",
3956
+ INCREMENTAL: "/compile/meta/incremental",
3957
+ STATE: "/compile/meta/state",
3958
+ TRAIT_COMPOSITION: "/compile/meta/trait-composition",
3959
+ // ── mixin ────────────────────────────────────────────────────────────
3960
+ DOMAIN_BLOCK: "/compile/mixin/domain-block"
3961
+ };
3962
+ COMPILER_DOMAIN_MAP = {
3963
+ // gamedev
3964
+ unity: ANSDomain.GAMEDEV,
3965
+ unreal: ANSDomain.GAMEDEV,
3966
+ godot: ANSDomain.GAMEDEV,
3967
+ // social-vr
3968
+ vrchat: ANSDomain.SOCIAL_VR,
3969
+ // xr
3970
+ openxr: ANSDomain.XR,
3971
+ "openxr-spatial-entities": ANSDomain.XR,
3972
+ visionos: ANSDomain.XR,
3973
+ ar: ANSDomain.XR,
3974
+ "android-xr": ANSDomain.XR,
3975
+ "ai-glasses": ANSDomain.XR,
3976
+ quilt: ANSDomain.XR,
3977
+ "mv-hevc": ANSDomain.XR,
3978
+ // mobile
3979
+ android: ANSDomain.MOBILE,
3980
+ ios: ANSDomain.MOBILE,
3981
+ // web3d
3982
+ babylon: ANSDomain.WEB3D,
3983
+ webgpu: ANSDomain.WEB3D,
3984
+ r3f: ANSDomain.WEB3D,
3985
+ playcanvas: ANSDomain.WEB3D,
3986
+ threejs: ANSDomain.WEB3D,
3987
+ // runtime
3988
+ wasm: ANSDomain.RUNTIME,
3989
+ "node-service": ANSDomain.RUNTIME,
3990
+ "nextjs-api": ANSDomain.RUNTIME,
3991
+ // shader
3992
+ tsl: ANSDomain.SHADER,
3993
+ // robotics
3994
+ urdf: ANSDomain.ROBOTICS,
3995
+ sdf: ANSDomain.ROBOTICS,
3996
+ // interchange
3997
+ usd: ANSDomain.INTERCHANGE,
3998
+ gltf: ANSDomain.INTERCHANGE,
3999
+ "3dgs": ANSDomain.INTERCHANGE,
4000
+ // iot
4001
+ dtdl: ANSDomain.IOT,
4002
+ // web3
4003
+ "nft-marketplace": ANSDomain.WEB3,
4004
+ // ai
4005
+ scm: ANSDomain.AI,
4006
+ vrr: ANSDomain.AI,
4007
+ "a2a-agent-card": ANSDomain.AI,
4008
+ "agent-inference": ANSDomain.AI,
4009
+ // neuromorphic
4010
+ nir: ANSDomain.NEUROMORPHIC,
4011
+ // meta
4012
+ "multi-layer": ANSDomain.META,
4013
+ incremental: ANSDomain.META,
4014
+ state: ANSDomain.META,
4015
+ "trait-composition": ANSDomain.META,
4016
+ // mixin
4017
+ "domain-block": ANSDomain.MIXIN
4018
+ };
4019
+ COMPILER_ANS_MAP = {
4020
+ unity: ANSCapabilityPath.UNITY,
4021
+ unreal: ANSCapabilityPath.UNREAL,
4022
+ godot: ANSCapabilityPath.GODOT,
4023
+ vrchat: ANSCapabilityPath.VRCHAT,
4024
+ openxr: ANSCapabilityPath.OPENXR,
4025
+ "openxr-spatial-entities": ANSCapabilityPath.OPENXR_SPATIAL_ENTITIES,
4026
+ visionos: ANSCapabilityPath.VISIONOS,
4027
+ ar: ANSCapabilityPath.AR,
4028
+ "android-xr": ANSCapabilityPath.ANDROID_XR,
4029
+ "ai-glasses": ANSCapabilityPath.AI_GLASSES,
4030
+ quilt: ANSCapabilityPath.QUILT,
4031
+ "mv-hevc": ANSCapabilityPath.MV_HEVC,
4032
+ android: ANSCapabilityPath.ANDROID,
4033
+ ios: ANSCapabilityPath.IOS,
4034
+ babylon: ANSCapabilityPath.BABYLON,
4035
+ webgpu: ANSCapabilityPath.WEBGPU,
4036
+ r3f: ANSCapabilityPath.R3F,
4037
+ playcanvas: ANSCapabilityPath.PLAYCANVAS,
4038
+ threejs: ANSCapabilityPath.THREEJS,
4039
+ wasm: ANSCapabilityPath.WASM,
4040
+ "node-service": ANSCapabilityPath.NODE_SERVICE,
4041
+ "nextjs-api": ANSCapabilityPath.NEXTJS_API,
4042
+ tsl: ANSCapabilityPath.TSL,
4043
+ urdf: ANSCapabilityPath.URDF,
4044
+ sdf: ANSCapabilityPath.SDF,
4045
+ usd: ANSCapabilityPath.USD,
4046
+ gltf: ANSCapabilityPath.GLTF,
4047
+ "3dgs": ANSCapabilityPath.GAUSSIAN_SPLATTING,
4048
+ dtdl: ANSCapabilityPath.DTDL,
4049
+ "nft-marketplace": ANSCapabilityPath.NFT_MARKETPLACE,
4050
+ scm: ANSCapabilityPath.SCM,
4051
+ vrr: ANSCapabilityPath.VRR,
4052
+ "a2a-agent-card": ANSCapabilityPath.A2A_AGENT_CARD,
4053
+ "agent-inference": ANSCapabilityPath.AGENT_INFERENCE,
4054
+ nir: ANSCapabilityPath.NIR,
4055
+ "multi-layer": ANSCapabilityPath.MULTI_LAYER,
4056
+ incremental: ANSCapabilityPath.INCREMENTAL,
4057
+ state: ANSCapabilityPath.STATE,
4058
+ "trait-composition": ANSCapabilityPath.TRAIT_COMPOSITION,
4059
+ "domain-block": ANSCapabilityPath.DOMAIN_BLOCK
4060
+ };
4061
+ ALL_COMPILER_NAMES = Object.keys(
4062
+ COMPILER_DOMAIN_MAP
4063
+ );
4064
+ Object.values(ANSDomain);
4065
+ }
4066
+ });
4067
+
4068
+ // src/compiler/CompilerDocumentationGenerator.ts
4069
+ var CompilerDocumentationGenerator;
4070
+ var init_CompilerDocumentationGenerator = __esm({
4071
+ "src/compiler/CompilerDocumentationGenerator.ts"() {
4072
+ init_traitDocs();
4073
+ CompilerDocumentationGenerator = class {
4074
+ constructor(options = {}) {
4075
+ this.options = {
4076
+ serviceUrl: options.serviceUrl ?? "http://localhost:3000",
4077
+ serviceVersion: options.serviceVersion ?? "1.0.0",
4078
+ maxLlmsTxtTokens: options.maxLlmsTxtTokens ?? 800,
4079
+ includeTraitDocs: options.includeTraitDocs ?? true,
4080
+ includeExamples: options.includeExamples ?? true,
4081
+ mcpTransportType: options.mcpTransportType ?? "streamable-http",
4082
+ contactRepository: options.contactRepository ?? "",
4083
+ contactDocumentation: options.contactDocumentation ?? ""
4084
+ };
4085
+ }
4086
+ getObjectType(obj) {
4087
+ const typeProperty = obj.properties?.find(
4088
+ (property) => property.key === "geometry" || property.key === "shape" || property.key === "type"
4089
+ )?.value;
4090
+ return typeof typeProperty === "string" ? typeProperty : "Object";
4091
+ }
4092
+ /**
4093
+ * Generate all three documentation outputs for a compilation
4094
+ *
4095
+ * @param composition - Parsed HoloScript composition AST
4096
+ * @param targetName - Compiler target (e.g., 'r3f', 'unity', 'unreal')
4097
+ * @param compiledCode - The compiled output code
4098
+ * @returns Triple-output documentation bundle
4099
+ */
4100
+ generate(composition, targetName, compiledCode, generationMeta) {
4101
+ return {
4102
+ llmsTxt: this.generateLlmsTxt(composition, targetName, compiledCode),
4103
+ wellKnownMcp: this.generateMCPServerCard(composition, targetName, generationMeta),
4104
+ markdownDocs: this.generateMarkdownDocs(composition, targetName, compiledCode)
4105
+ };
4106
+ }
4107
+ // ===========================================================================
4108
+ // LLMS.TXT GENERATION
4109
+ // ===========================================================================
4110
+ /**
4111
+ * Generate llms.txt format documentation (max 800 tokens)
4112
+ *
4113
+ * llms.txt is a standardized format for AI-readable project documentation.
4114
+ * It provides a concise overview optimized for LLM context windows.
4115
+ *
4116
+ * Includes: scene description, trait list, export targets, API surface,
4117
+ * MCP tool manifest summary, and state management.
4118
+ *
4119
+ * @see https://llmstxt.org/
4120
+ */
4121
+ generateLlmsTxt(composition, targetName, compiledCode) {
4122
+ const sections = [];
4123
+ sections.push(`# ${composition.name || "HoloScript Composition"}`);
4124
+ sections.push("");
4125
+ sections.push("## Scene Description");
4126
+ sections.push(`Compiled for: ${targetName}`);
4127
+ sections.push(`Objects: ${composition.objects?.length || 0}`);
4128
+ sections.push(`Lights: ${composition.lights?.length || 0}`);
4129
+ sections.push(`Spatial Groups: ${composition.spatialGroups?.length || 0}`);
4130
+ sections.push(`Templates: ${composition.templates?.length || 0}`);
4131
+ sections.push("");
4132
+ const traits = this.extractTraits(composition);
4133
+ if (traits.length > 0) {
4134
+ sections.push("## Traits Used");
4135
+ const traitsByCategory = this.groupTraitsByCategory(traits);
4136
+ for (const [category, categoryTraits] of Object.entries(traitsByCategory)) {
4137
+ sections.push(`- ${category}: ${categoryTraits.join(", ")}`);
4138
+ }
4139
+ sections.push("");
4140
+ }
4141
+ sections.push("## Export Capabilities");
4142
+ sections.push(`Primary target: ${targetName}`);
4143
+ sections.push(
4144
+ "Compatible targets: unity, unreal, godot, r3f, webgpu, babylon, openxr, vrchat, wasm, gltf, usd"
4145
+ );
4146
+ sections.push("");
4147
+ if (typeof compiledCode === "object") {
4148
+ sections.push("## API Surface");
4149
+ const files = Object.keys(compiledCode);
4150
+ sections.push(`Generated files: ${files.length}`);
4151
+ sections.push(`- ${files.slice(0, 5).join("\n- ")}`);
4152
+ if (files.length > 5) {
4153
+ sections.push(`- ... and ${files.length - 5} more`);
4154
+ }
4155
+ sections.push("");
4156
+ }
4157
+ const mcpTools = this.extractMCPTools(composition, targetName);
4158
+ if (mcpTools.length > 0) {
4159
+ sections.push("## MCP Tools");
4160
+ sections.push(`Available tools: ${mcpTools.length}`);
4161
+ for (const tool of mcpTools.slice(0, 8)) {
4162
+ sections.push(`- ${tool.name}: ${tool.description}`);
4163
+ }
4164
+ if (mcpTools.length > 8) {
4165
+ sections.push(`- ... and ${mcpTools.length - 8} more`);
4166
+ }
4167
+ sections.push("");
4168
+ }
4169
+ if (composition.state) {
4170
+ const stateObj = composition.state;
4171
+ let stateProps = [];
4172
+ if (stateObj.properties && Array.isArray(stateObj.properties)) {
4173
+ stateProps = stateObj.properties.map((p) => p.key);
4174
+ } else {
4175
+ stateProps = Object.keys(stateObj);
4176
+ }
4177
+ if (stateProps.length > 0) {
4178
+ sections.push("## State Management");
4179
+ sections.push(`State properties: ${stateProps.length}`);
4180
+ sections.push(`- ${stateProps.slice(0, 5).join(", ")}`);
4181
+ if (stateProps.length > 5) {
4182
+ sections.push(` ... and ${stateProps.length - 5} more`);
4183
+ }
4184
+ sections.push("");
4185
+ }
4186
+ }
4187
+ if (composition.environment) {
4188
+ const env = composition.environment;
4189
+ sections.push("## Environment");
4190
+ sections.push(`Background: ${env.background || "default"}`);
4191
+ if (env.fog) {
4192
+ sections.push("Fog: enabled");
4193
+ }
4194
+ sections.push("");
4195
+ }
4196
+ const fullText = sections.join("\n");
4197
+ const maxChars = this.options.maxLlmsTxtTokens * 4;
4198
+ if (fullText.length > maxChars) {
4199
+ return fullText.substring(0, maxChars) + "\n\n... (truncated to fit token limit)";
4200
+ }
4201
+ return fullText;
4202
+ }
4203
+ // ===========================================================================
4204
+ // .WELL-KNOWN/MCP GENERATION
4205
+ // ===========================================================================
4206
+ /**
4207
+ * Generate MCP server card conforming to SEP-1649 and SEP-1960
4208
+ *
4209
+ * Produces a server card that satisfies both specification proposals:
4210
+ * - SEP-1649: serverInfo nested object, transport with endpoint, protocolVersion
4211
+ * - SEP-1960: endpoints object, authentication, capabilities as booleans
4212
+ *
4213
+ * The card includes legacy compatibility fields (name, version at root)
4214
+ * for backward compatibility with v1.0.0 consumers.
4215
+ */
4216
+ generateMCPServerCard(composition, targetName, generationMeta) {
4217
+ const tools = this.extractMCPTools(composition, targetName);
4218
+ const sanitizedName = this.sanitizeServiceName(composition.name || "holoscript-composition");
4219
+ const compositionTitle = composition.name || "Untitled";
4220
+ const traitCount = this.extractTraits(composition).length;
4221
+ const objectCount = composition.objects?.length || 0;
4222
+ const endpoints = {};
4223
+ const transportType = this.options.mcpTransportType;
4224
+ const mcpUrl = `${this.options.serviceUrl}/mcp`;
4225
+ if (transportType === "streamable-http" || transportType === "http") {
4226
+ endpoints.streamable_http = mcpUrl;
4227
+ } else if (transportType === "sse") {
4228
+ endpoints.sse = mcpUrl;
4229
+ } else if (transportType === "websocket" || transportType === "ws") {
4230
+ endpoints.websocket = mcpUrl;
4231
+ } else {
4232
+ endpoints.streamable_http = mcpUrl;
4233
+ }
4234
+ endpoints.health = `${this.options.serviceUrl}/health`;
4235
+ endpoints.render = `${this.options.serviceUrl}/api/render`;
4236
+ const holoscriptMeta = {
4237
+ compiler_target: targetName,
4238
+ generated_at: (/* @__PURE__ */ new Date()).toISOString()
4239
+ };
4240
+ if (generationMeta?.compilationDigest) {
4241
+ holoscriptMeta.compilation_digest = generationMeta.compilationDigest;
4242
+ }
4243
+ return {
4244
+ // SEP-1960 fields
4245
+ mcpVersion: "2025-03-26",
4246
+ // SEP-1649 fields
4247
+ protocolVersion: "2025-06-18",
4248
+ serverInfo: {
4249
+ name: sanitizedName,
4250
+ title: `HoloScript: ${compositionTitle}`,
4251
+ version: this.options.serviceVersion
4252
+ },
4253
+ description: `HoloScript composition "${compositionTitle}" compiled for ${targetName} \u2014 ${objectCount} objects, ${traitCount} unique traits`,
4254
+ transport: {
4255
+ type: transportType,
4256
+ endpoint: mcpUrl,
4257
+ authentication: null
4258
+ },
4259
+ capabilities: {
4260
+ tools: {
4261
+ count: tools.length
4262
+ },
4263
+ resources: false,
4264
+ prompts: false,
4265
+ sampling: false,
4266
+ roots: false
4267
+ },
4268
+ tools,
4269
+ endpoints,
4270
+ authentication: {
4271
+ required: false,
4272
+ methods: ["none"]
4273
+ },
4274
+ contact: {
4275
+ repository: this.options.contactRepository || void 0,
4276
+ documentation: this.options.contactDocumentation || void 0
4277
+ },
4278
+ documentation: this.options.contactDocumentation || void 0,
4279
+ _meta: {
4280
+ holoscript: holoscriptMeta
4281
+ },
4282
+ // Legacy compatibility (v1.0.0)
4283
+ name: sanitizedName,
4284
+ version: this.options.serviceVersion
4285
+ };
4286
+ }
4287
+ /**
4288
+ * Extract MCP tool manifest from composition
4289
+ */
4290
+ extractMCPTools(composition, targetName) {
4291
+ const tools = [];
4292
+ tools.push({
4293
+ name: "compile_composition",
4294
+ description: `Compile this HoloScript composition to ${targetName} format`,
4295
+ inputSchema: {
4296
+ type: "object",
4297
+ properties: {
4298
+ options: {
4299
+ type: "object",
4300
+ description: "Compiler options"
4301
+ }
4302
+ }
4303
+ }
4304
+ });
4305
+ tools.push({
4306
+ name: "render_preview",
4307
+ description: `Render a preview of this composition as PNG/JPEG`,
4308
+ inputSchema: {
4309
+ type: "object",
4310
+ properties: {
4311
+ width: { type: "number", description: "Image width in pixels" },
4312
+ height: { type: "number", description: "Image height in pixels" },
4313
+ format: { type: "string", enum: ["png", "jpeg", "webp"] }
4314
+ }
4315
+ }
4316
+ });
4317
+ if (composition.templates && composition.templates.length > 0) {
4318
+ for (const template of composition.templates.slice(0, 10)) {
4319
+ tools.push({
4320
+ name: `instantiate_${this.sanitizeToolName(template.name)}`,
4321
+ description: `Instantiate the "${template.name}" template with custom properties`,
4322
+ inputSchema: {
4323
+ type: "object",
4324
+ properties: {
4325
+ properties: {
4326
+ type: "object",
4327
+ description: "Template properties to override"
4328
+ },
4329
+ position: {
4330
+ type: "object",
4331
+ description: "Spatial position",
4332
+ properties: [{ type: "number" }, { type: "number" }, { type: "number" }]
4333
+ }
4334
+ }
4335
+ }
4336
+ });
4337
+ }
4338
+ }
4339
+ if (composition.state) {
4340
+ tools.push({
4341
+ name: "update_state",
4342
+ description: "Update composition state properties",
4343
+ inputSchema: {
4344
+ type: "object",
4345
+ properties: {
4346
+ updates: {
4347
+ type: "object",
4348
+ description: "State property updates"
4349
+ }
4350
+ }
4351
+ }
4352
+ });
4353
+ }
4354
+ tools.push({
4355
+ name: "list_traits",
4356
+ description: "List all traits used in this composition with their configurations",
4357
+ inputSchema: {
4358
+ type: "object",
4359
+ properties: {
4360
+ category: {
4361
+ type: "string",
4362
+ description: "Filter by trait category (visual, physics, audio, etc.)"
4363
+ }
4364
+ }
4365
+ }
4366
+ });
4367
+ if (composition.objects && composition.objects.length > 0) {
4368
+ tools.push({
4369
+ name: "query_objects",
4370
+ description: `Query scene objects by name, type, or trait (${composition.objects.length} objects available)`,
4371
+ inputSchema: {
4372
+ type: "object",
4373
+ properties: {
4374
+ name: { type: "string", description: "Filter by object name (glob pattern)" },
4375
+ trait: { type: "string", description: "Filter by trait name" }
4376
+ }
4377
+ }
4378
+ });
4379
+ }
4380
+ return tools;
4381
+ }
4382
+ // ===========================================================================
4383
+ // MARKDOWN DOCUMENTATION GENERATION
4384
+ // ===========================================================================
4385
+ /**
4386
+ * Generate comprehensive markdown documentation bundle
4387
+ *
4388
+ * Includes: composition metadata, scene graph, trait documentation,
4389
+ * state management, logic handlers, MCP tool manifests, and compilation output.
4390
+ */
4391
+ generateMarkdownDocs(composition, targetName, compiledCode) {
4392
+ const sections = [];
4393
+ sections.push(`# ${composition.name || "HoloScript Composition"}`);
4394
+ sections.push("");
4395
+ sections.push(`**Target:** ${targetName}`);
4396
+ sections.push(`**Generated:** ${(/* @__PURE__ */ new Date()).toISOString()}`);
4397
+ sections.push(`**Version:** ${this.options.serviceVersion}`);
4398
+ sections.push("");
4399
+ sections.push("## Table of Contents");
4400
+ sections.push("");
4401
+ sections.push("- [Overview](#overview)");
4402
+ sections.push("- [Scene Graph](#scene-graph)");
4403
+ sections.push("- [Traits](#traits)");
4404
+ if (composition.state) {
4405
+ sections.push("- [State Management](#state-management)");
4406
+ }
4407
+ if (composition.logic) {
4408
+ sections.push("- [Logic Handlers](#logic-handlers)");
4409
+ }
4410
+ sections.push("- [MCP Tool Manifest](#mcp-tool-manifest)");
4411
+ sections.push("- [Compilation Output](#compilation-output)");
4412
+ sections.push("");
4413
+ sections.push("## Overview");
4414
+ sections.push("");
4415
+ sections.push(
4416
+ `This composition contains ${composition.objects?.length || 0} objects, ${composition.lights?.length || 0} lights, and ${composition.spatialGroups?.length || 0} spatial groups.`
4417
+ );
4418
+ sections.push("");
4419
+ if (composition.templates && composition.templates.length > 0) {
4420
+ sections.push(`**Templates:** ${composition.templates.length}`);
4421
+ }
4422
+ if (composition.imports && composition.imports.length > 0) {
4423
+ sections.push(`**Imports:** ${composition.imports.length}`);
4424
+ }
4425
+ if (composition.traitDefinitions && composition.traitDefinitions.length > 0) {
4426
+ sections.push(`**Custom Traits:** ${composition.traitDefinitions.length}`);
4427
+ }
4428
+ sections.push("");
4429
+ sections.push("## Scene Graph");
4430
+ sections.push("");
4431
+ if (composition.objects && composition.objects.length > 0) {
4432
+ sections.push("### Objects");
4433
+ sections.push("");
4434
+ sections.push("| Name | Type | Position | Traits |");
4435
+ sections.push("|------|------|----------|--------|");
4436
+ for (const obj of composition.objects.slice(0, 20)) {
4437
+ const objRec = obj;
4438
+ const transform = objRec.transform;
4439
+ const pos = objRec.position || transform?.position;
4440
+ const posStr = pos ? `(${pos[0]}, ${pos[1]}, ${pos[2]})` : "N/A";
4441
+ const traitNames = obj.traits ? this.extractTraitNames(obj.traits).join(", ") || "none" : "none";
4442
+ sections.push(`| ${obj.name} | ${this.getObjectType(obj)} | ${posStr} | ${traitNames} |`);
4443
+ }
4444
+ if (composition.objects.length > 20) {
4445
+ sections.push(`| ... | ... | ... | *${composition.objects.length - 20} more objects* |`);
4446
+ }
4447
+ sections.push("");
4448
+ }
4449
+ if (composition.lights && composition.lights.length > 0) {
4450
+ sections.push("### Lights");
4451
+ sections.push("");
4452
+ sections.push("| Name | Type |");
4453
+ sections.push("|------|------|");
4454
+ for (const light of composition.lights) {
4455
+ const lightRec = light;
4456
+ sections.push(
4457
+ `| ${light.name || "unnamed"} | ${lightRec.lightType || "unknown"} |`
4458
+ );
4459
+ }
4460
+ sections.push("");
4461
+ }
4462
+ const traits = this.extractTraits(composition);
4463
+ if (traits.length > 0) {
4464
+ sections.push("## Traits");
4465
+ sections.push("");
4466
+ sections.push(`This composition uses ${traits.length} unique traits:`);
4467
+ sections.push("");
4468
+ const traitsByCategory = this.groupTraitsByCategory(traits);
4469
+ for (const [category, categoryTraits] of Object.entries(traitsByCategory)) {
4470
+ sections.push(`### ${category}`);
4471
+ sections.push("");
4472
+ for (const trait of categoryTraits) {
4473
+ sections.push(`- **${trait}**`);
4474
+ if (this.options.includeTraitDocs) {
4475
+ const doc = this.getTraitDocumentation(trait);
4476
+ if (doc) {
4477
+ for (const line of doc.split("\n")) {
4478
+ sections.push(line === "" ? "" : ` ${line}`);
4479
+ }
4480
+ }
4481
+ }
4482
+ }
4483
+ sections.push("");
4484
+ }
4485
+ }
4486
+ if (composition.traitDefinitions && composition.traitDefinitions.length > 0) {
4487
+ sections.push("### Custom Trait Definitions");
4488
+ sections.push("");
4489
+ for (const traitDef of composition.traitDefinitions) {
4490
+ const traitDefRec = traitDef;
4491
+ const extendsClause = traitDefRec.extends ? ` extends ${traitDefRec.extends}` : "";
4492
+ sections.push(`- **${traitDef.name}**${extendsClause}`);
4493
+ }
4494
+ sections.push("");
4495
+ }
4496
+ if (composition.state) {
4497
+ sections.push("## State Management");
4498
+ sections.push("");
4499
+ sections.push("### State Properties");
4500
+ sections.push("");
4501
+ sections.push("| Property | Type | Default Value |");
4502
+ sections.push("|----------|------|---------------|");
4503
+ const stateObj = composition.state;
4504
+ if (stateObj.properties) {
4505
+ for (const prop of stateObj.properties) {
4506
+ const typeOf = typeof prop.value;
4507
+ const defaultValue = JSON.stringify(prop.value).substring(0, 50);
4508
+ sections.push(`| ${prop.key} | ${typeOf} | ${defaultValue} |`);
4509
+ }
4510
+ } else {
4511
+ for (const [key, value] of Object.entries(stateObj)) {
4512
+ const typeOf = typeof value;
4513
+ const defaultValue = JSON.stringify(value).substring(0, 50);
4514
+ sections.push(`| ${key} | ${typeOf} | ${defaultValue} |`);
4515
+ }
4516
+ }
4517
+ sections.push("");
4518
+ }
4519
+ if (composition.logic) {
4520
+ sections.push("## Logic Handlers");
4521
+ sections.push("");
4522
+ const logic = composition.logic;
4523
+ if (logic.on_start) {
4524
+ sections.push("### on_start");
4525
+ sections.push("");
4526
+ sections.push("Executed when the composition initializes.");
4527
+ sections.push("");
4528
+ }
4529
+ if (logic.on_update) {
4530
+ sections.push("### on_update");
4531
+ sections.push("");
4532
+ sections.push("Executed every frame.");
4533
+ sections.push("");
4534
+ }
4535
+ }
4536
+ const mcpTools = this.extractMCPTools(composition, targetName);
4537
+ sections.push("## MCP Tool Manifest");
4538
+ sections.push("");
4539
+ sections.push(
4540
+ `This compilation exposes ${mcpTools.length} MCP tools for programmatic interaction:`
4541
+ );
4542
+ sections.push("");
4543
+ sections.push("| Tool | Description | Input Schema |");
4544
+ sections.push("|------|-------------|-------------|");
4545
+ for (const tool of mcpTools) {
4546
+ const schemaStr = tool.inputSchema ? "`" + JSON.stringify(
4547
+ Object.keys(
4548
+ tool.inputSchema.properties || {}
4549
+ )
4550
+ ) + "`" : "none";
4551
+ sections.push(`| \`${tool.name}\` | ${tool.description} | ${schemaStr} |`);
4552
+ }
4553
+ sections.push("");
4554
+ sections.push("### Discovery");
4555
+ sections.push("");
4556
+ sections.push(`Server card available at: \`${this.options.serviceUrl}/.well-known/mcp\``);
4557
+ sections.push("");
4558
+ sections.push("```json");
4559
+ sections.push(`{`);
4560
+ sections.push(` "mcpVersion": "2025-03-26",`);
4561
+ sections.push(` "protocolVersion": "2025-06-18",`);
4562
+ sections.push(` "serverInfo": {`);
4563
+ sections.push(
4564
+ ` "name": "${this.sanitizeServiceName(composition.name || "holoscript-composition")}",`
4565
+ );
4566
+ sections.push(` "version": "${this.options.serviceVersion}"`);
4567
+ sections.push(` }`);
4568
+ sections.push(`}`);
4569
+ sections.push("```");
4570
+ sections.push("");
4571
+ sections.push("## Compilation Output");
4572
+ sections.push("");
4573
+ if (typeof compiledCode === "string") {
4574
+ const lineCount = compiledCode.split("\n").length;
4575
+ sections.push(`Generated ${lineCount} lines of ${targetName} code.`);
4576
+ } else {
4577
+ sections.push(`Generated ${Object.keys(compiledCode).length} files:`);
4578
+ sections.push("");
4579
+ for (const [filename, content] of Object.entries(compiledCode)) {
4580
+ const lineCount = content.split("\n").length;
4581
+ sections.push(`- **${filename}** (${lineCount} lines)`);
4582
+ }
4583
+ }
4584
+ sections.push("");
4585
+ sections.push("---");
4586
+ sections.push("");
4587
+ sections.push("*Generated by HoloScript Compiler Documentation Generator v2.0.0*");
4588
+ sections.push("");
4589
+ return sections.join("\n");
4590
+ }
4591
+ // ===========================================================================
4592
+ // HELPER METHODS
4593
+ // ===========================================================================
4594
+ /**
4595
+ * Extract trait names from a traits field.
4596
+ *
4597
+ * Handles both formats:
4598
+ * - HoloObjectTrait[] (canonical parser output: array of { name, config })
4599
+ * - Map<string, unknown> (R3F compiler output: Map with trait names as keys)
4600
+ */
4601
+ extractTraitNames(traits) {
4602
+ if (!traits) return [];
4603
+ if (traits instanceof Map) {
4604
+ return Array.from(traits.keys());
4605
+ }
4606
+ if (Array.isArray(traits)) {
4607
+ return traits.map((t) => typeof t === "string" ? t : t?.name).filter((name) => typeof name === "string");
4608
+ }
4609
+ return [];
4610
+ }
4611
+ /**
4612
+ * Extract all unique traits from a composition
4613
+ */
4614
+ extractTraits(composition) {
4615
+ const traitSet = /* @__PURE__ */ new Set();
4616
+ if (composition.objects) {
4617
+ for (const obj of composition.objects) {
4618
+ for (const name of this.extractTraitNames(obj.traits)) {
4619
+ traitSet.add(name);
4620
+ }
4621
+ }
4622
+ }
4623
+ if (composition.templates) {
4624
+ for (const template of composition.templates) {
4625
+ for (const name of this.extractTraitNames(template.traits)) {
4626
+ traitSet.add(name);
4627
+ }
4628
+ }
4629
+ }
4630
+ return Array.from(traitSet).sort();
4631
+ }
4632
+ /**
4633
+ * Group traits by category (visual, physics, audio, etc.)
4634
+ */
4635
+ groupTraitsByCategory(traits) {
4636
+ const categories = {
4637
+ Visual: [],
4638
+ Physics: [],
4639
+ Audio: [],
4640
+ Interaction: [],
4641
+ AI: [],
4642
+ Animation: [],
4643
+ Network: [],
4644
+ Other: []
4645
+ };
4646
+ for (const trait of traits) {
4647
+ const category = this.categorizeTrait(trait);
4648
+ categories[category].push(trait);
4649
+ }
4650
+ return Object.fromEntries(
4651
+ Object.entries(categories).filter(([_, traits2]) => traits2.length > 0)
4652
+ );
4653
+ }
4654
+ /**
4655
+ * Categorize a trait by name pattern
4656
+ */
4657
+ categorizeTrait(trait) {
4658
+ if (!trait) return "Other";
4659
+ const lower = trait.toLowerCase();
4660
+ if (lower.includes("material") || lower.includes("color") || lower.includes("texture") || lower.includes("glow") || lower.includes("emissive") || lower.includes("shader") || lower.includes("pbr") || lower.includes("light") || lower.includes("shadow") || lower.includes("fog") || lower.includes("transparency") || lower.includes("opacity")) {
4661
+ return "Visual";
4662
+ }
4663
+ if (lower.includes("physics") || lower.includes("collider") || lower.includes("rigidbody") || lower.includes("gravity") || lower.includes("fluid") || lower.includes("constraint") || lower.includes("joint")) {
4664
+ return "Physics";
4665
+ }
4666
+ if (lower.includes("audio") || lower.includes("sound") || lower.includes("music") || lower.includes("spatial_audio")) {
4667
+ return "Audio";
4668
+ }
4669
+ if (lower.includes("clickable") || lower.includes("draggable") || lower.includes("interactive") || lower.includes("hover") || lower.includes("grab") || lower.includes("pointer") || lower.includes("selectable")) {
4670
+ return "Interaction";
4671
+ }
4672
+ if (lower.includes("ai") || lower.includes("npc") || lower.includes("behavior") || lower.includes("pathfinding") || lower.includes("agent") || lower.includes("decision")) {
4673
+ return "AI";
4674
+ }
4675
+ if (lower.includes("anim") || lower.includes("rotate") || lower.includes("move") || lower.includes("orbit") || lower.includes("keyframe") || lower.includes("tween") || lower.includes("spring")) {
4676
+ return "Animation";
4677
+ }
4678
+ if (lower.includes("network") || lower.includes("sync") || lower.includes("multiplayer") || lower.includes("replicated") || lower.includes("authority") || lower.includes("lobby")) {
4679
+ return "Network";
4680
+ }
4681
+ return "Other";
4682
+ }
4683
+ /** Resolve trait docs from the shared LSP trait database (now in @holoscript/core). */
4684
+ getTraitDocumentation(trait) {
4685
+ const doc = getTraitDoc(trait);
4686
+ if (!doc) return null;
4687
+ return formatTraitDocCompact(doc);
4688
+ }
4689
+ /**
4690
+ * Sanitize composition name for use as a service name
4691
+ */
4692
+ sanitizeServiceName(name) {
4693
+ return name.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
4694
+ }
4695
+ /**
4696
+ * Sanitize template name for use as a tool name
4697
+ */
4698
+ sanitizeToolName(name) {
4699
+ return name.toLowerCase().replace(/[^a-z0-9_]/g, "_").replace(/_+/g, "_").replace(/^_|_$/g, "");
4700
+ }
4701
+ };
4702
+ }
4703
+ });
4704
+
4705
+ // src/compiler/identity/CapabilityRBAC.ts
4706
+ function getCapabilityRBAC(config) {
4707
+ if (!globalCapabilityRBAC) {
4708
+ globalCapabilityRBAC = new CapabilityRBAC(config);
4709
+ }
4710
+ return globalCapabilityRBAC;
4711
+ }
4712
+ var RESOURCE_TYPE_TO_URI, OPERATION_TO_ACTION_SUFFIX, CapabilityRBAC, globalCapabilityRBAC;
4713
+ var init_CapabilityRBAC = __esm({
4714
+ "src/compiler/identity/CapabilityRBAC.ts"() {
4715
+ init_AgentRBAC();
4716
+ init_CapabilityToken();
4717
+ init_CapabilityTokenIssuer();
4718
+ RESOURCE_TYPE_TO_URI = {
4719
+ ["source_file" /* SOURCE_FILE */]: `${HOLOSCRIPT_RESOURCE_SCHEME}source`,
4720
+ ["ast" /* AST */]: `${HOLOSCRIPT_RESOURCE_SCHEME}ast`,
4721
+ ["ir" /* IR */]: `${HOLOSCRIPT_RESOURCE_SCHEME}ir`,
4722
+ ["code" /* CODE */]: `${HOLOSCRIPT_RESOURCE_SCHEME}code`,
4723
+ ["output" /* OUTPUT */]: `${HOLOSCRIPT_RESOURCE_SCHEME}output`,
4724
+ ["config" /* CONFIG */]: `${HOLOSCRIPT_RESOURCE_SCHEME}config`
4725
+ };
4726
+ OPERATION_TO_ACTION_SUFFIX = {
4727
+ read: "read",
4728
+ write: "write",
4729
+ execute: "execute",
4730
+ transform: "transform"
4731
+ };
4732
+ CapabilityRBAC = class {
4733
+ constructor(config = {}) {
4734
+ this.denialCounter = 0;
4735
+ this.rbac = config.rbac ?? getRBAC();
4736
+ this.capabilityIssuer = config.capabilityIssuer ?? getCapabilityTokenIssuer();
4737
+ this.strategy = config.strategy ?? "capability-first";
4738
+ this.semantics = new HoloScriptCapabilitySemantics();
4739
+ }
4740
+ buildDenialReceipt(request, deniedBy, opts) {
4741
+ const resourceUri = request.resourceType ? this.buildResourceUri(request.resourceType, request.resourcePath) : "unknown";
4742
+ const action = request.resourceType && request.operation ? this.buildAction(request.resourceType, request.operation) : request.operation || "unknown";
4743
+ return {
4744
+ auditId: `deny-${++this.denialCounter}-${Date.now()}`,
4745
+ deniedAction: action,
4746
+ requestedResource: resourceUri,
4747
+ deniedBy,
4748
+ requiredCapability: opts?.requiredCapability,
4749
+ suggestedFix: opts?.suggestedFix,
4750
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
4751
+ };
4752
+ }
4753
+ // -----------------------------------------------------------------------
4754
+ // Core access check
4755
+ // -----------------------------------------------------------------------
4756
+ /**
4757
+ * Check access using dual-mode resolution.
4758
+ *
4759
+ * Depending on the configured strategy, this will try JWT and/or UCAN
4760
+ * verification and return the result.
4761
+ */
4762
+ checkAccess(request) {
4763
+ const hasCapability = !!request.capabilityToken && !!request.issuerPublicKey;
4764
+ const hasJwt = !!request.token;
4765
+ switch (this.strategy) {
4766
+ case "capability-only":
4767
+ if (!hasCapability) {
4768
+ return {
4769
+ allowed: false,
4770
+ reason: "Capability token required (strategy: capability-only)",
4771
+ mode: "capability",
4772
+ denial: this.buildDenialReceipt(request, "no-token", {
4773
+ suggestedFix: "Provide a UCAN capability token with issuerPublicKey"
4774
+ })
4775
+ };
4776
+ }
4777
+ return this.checkCapability(request);
4778
+ case "rbac-only":
4779
+ if (!hasJwt) {
4780
+ return {
4781
+ allowed: false,
4782
+ reason: "JWT token required (strategy: rbac-only)",
4783
+ mode: "rbac",
4784
+ denial: this.buildDenialReceipt(request, "no-token", {
4785
+ suggestedFix: "Provide a JWT RBAC token"
4786
+ })
4787
+ };
4788
+ }
4789
+ return this.checkRBAC(request);
4790
+ case "rbac-first":
4791
+ if (hasJwt) {
4792
+ const rbacResult = this.checkRBAC(request);
4793
+ if (rbacResult.allowed) return rbacResult;
4794
+ }
4795
+ if (hasCapability) {
4796
+ return this.checkCapability(request);
4797
+ }
4798
+ return {
4799
+ allowed: false,
4800
+ reason: "No valid token provided",
4801
+ mode: "rbac",
4802
+ denial: this.buildDenialReceipt(request, "no-token", {
4803
+ suggestedFix: "Provide a JWT token or UCAN capability token"
4804
+ })
4805
+ };
4806
+ case "capability-first":
4807
+ default:
4808
+ if (hasCapability) {
4809
+ const capResult = this.checkCapability(request);
4810
+ if (capResult.allowed) return capResult;
4811
+ }
4812
+ if (hasJwt) {
4813
+ return this.checkRBAC(request);
4814
+ }
4815
+ return {
4816
+ allowed: false,
4817
+ reason: "No valid token provided",
4818
+ mode: "capability",
4819
+ denial: this.buildDenialReceipt(request, "no-token", {
4820
+ suggestedFix: "Provide a UCAN capability token or JWT token"
4821
+ })
4822
+ };
4823
+ }
4824
+ }
4825
+ // -----------------------------------------------------------------------
4826
+ // UCAN capability check
4827
+ // -----------------------------------------------------------------------
4828
+ /**
4829
+ * Verify access using a UCAN capability token.
4830
+ */
4831
+ checkCapability(request) {
4832
+ const { capabilityToken, issuerPublicKey, resourceType, operation, resourcePath } = request;
4833
+ if (!capabilityToken || !issuerPublicKey) {
4834
+ return {
4835
+ allowed: false,
4836
+ reason: "Missing capability token or issuer public key",
4837
+ mode: "capability",
4838
+ denial: this.buildDenialReceipt(request, "capability", {
4839
+ suggestedFix: "Provide both capabilityToken and issuerPublicKey"
4840
+ })
4841
+ };
4842
+ }
4843
+ const verification = this.capabilityIssuer.verify(capabilityToken, issuerPublicKey);
4844
+ if (!verification.valid) {
4845
+ return {
4846
+ allowed: false,
4847
+ reason: `Capability token verification failed: ${verification.error}`,
4848
+ mode: "capability",
4849
+ capabilityVerification: verification,
4850
+ denial: this.buildDenialReceipt(request, "capability", {
4851
+ requiredCapability: "valid-signature",
4852
+ suggestedFix: `Re-issue capability token: ${verification.error}`
4853
+ })
4854
+ };
4855
+ }
4856
+ if (verification.chain && !verification.chain.verified) {
4857
+ return {
4858
+ allowed: false,
4859
+ reason: "Capability token chain verification failed (attenuation invariant violation)",
4860
+ mode: "capability",
4861
+ capabilityVerification: verification,
4862
+ errorCode: "ATTENUATION_VIOLATION",
4863
+ denial: this.buildDenialReceipt(request, "capability", {
4864
+ requiredCapability: "valid-attenuation-chain",
4865
+ suggestedFix: "Ensure delegated capabilities do not exceed parent scope"
4866
+ })
4867
+ };
4868
+ }
4869
+ const resourceUri = this.buildResourceUri(resourceType, resourcePath);
4870
+ const action = this.buildAction(resourceType, operation);
4871
+ const matchedCapability = capabilityToken.payload.att.find(
4872
+ (cap) => this.semantics.canAccess(cap, resourceUri, action)
4873
+ );
4874
+ if (!matchedCapability) {
4875
+ return {
4876
+ allowed: false,
4877
+ reason: `No capability grants access to resource "${resourceUri}" with action "${action}"`,
4878
+ mode: "capability",
4879
+ capabilityVerification: verification,
4880
+ denial: this.buildDenialReceipt(request, "capability", {
4881
+ requiredCapability: `${resourceUri}#${action}`,
4882
+ suggestedFix: `Add capability { with: "${resourceUri}", can: "${action}" } to token`
4883
+ })
4884
+ };
4885
+ }
4886
+ return {
4887
+ allowed: true,
4888
+ mode: "capability",
4889
+ matchedCapability,
4890
+ capabilityVerification: verification
4891
+ };
4892
+ }
4893
+ // -----------------------------------------------------------------------
4894
+ // Legacy JWT RBAC check (delegates to existing AgentRBAC)
4895
+ // -----------------------------------------------------------------------
4896
+ /**
4897
+ * Verify access using the legacy JWT RBAC system.
4898
+ */
4899
+ checkRBAC(request) {
4900
+ const decision = this.rbac.checkAccess(request);
4901
+ const result = {
4902
+ ...decision,
4903
+ mode: "rbac"
4904
+ };
4905
+ if (!decision.allowed) {
4906
+ result.denial = this.buildDenialReceipt(request, "rbac", {
4907
+ requiredCapability: `${request.resourceType}/${request.operation}`,
4908
+ suggestedFix: decision.reason ? `RBAC denied: ${decision.reason}` : "Ensure JWT token grants the required role/permission"
4909
+ });
4910
+ }
4911
+ return result;
4912
+ }
4913
+ // -----------------------------------------------------------------------
4914
+ // URI / action building
4915
+ // -----------------------------------------------------------------------
4916
+ /**
4917
+ * Build a UCAN resource URI from a ResourceType and optional path.
4918
+ */
4919
+ buildResourceUri(resourceType, resourcePath) {
4920
+ const base = RESOURCE_TYPE_TO_URI[resourceType];
4921
+ if (resourcePath) {
4922
+ return `${base}/${resourcePath}`;
4923
+ }
4924
+ return base;
4925
+ }
4926
+ /**
4927
+ * Build a UCAN action string from a ResourceType and operation.
4928
+ */
4929
+ buildAction(resourceType, operation) {
4930
+ const prefixMap = {
4931
+ ["source_file" /* SOURCE_FILE */]: "source",
4932
+ ["ast" /* AST */]: "ast",
4933
+ ["ir" /* IR */]: "ir",
4934
+ ["code" /* CODE */]: "code",
4935
+ ["output" /* OUTPUT */]: "output",
4936
+ ["config" /* CONFIG */]: "config"
4937
+ };
4938
+ const prefix = prefixMap[resourceType];
4939
+ const suffix = OPERATION_TO_ACTION_SUFFIX[operation] ?? operation;
4940
+ return `${prefix}/${suffix}`;
4941
+ }
4942
+ // -----------------------------------------------------------------------
4943
+ // Convenience methods (matching AgentRBAC API)
4944
+ // -----------------------------------------------------------------------
4945
+ /**
4946
+ * Check if agent can read source (dual-mode).
4947
+ */
4948
+ canReadSource(tokenOrCapability, filePath) {
4949
+ if (typeof tokenOrCapability === "string") {
4950
+ return this.checkAccess({
4951
+ token: tokenOrCapability,
4952
+ resourceType: "source_file" /* SOURCE_FILE */,
4953
+ operation: "read",
4954
+ resourcePath: filePath
4955
+ });
4956
+ }
4957
+ return this.checkAccess({
4958
+ token: "",
4959
+ capabilityToken: tokenOrCapability.token,
4960
+ issuerPublicKey: tokenOrCapability.publicKey,
4961
+ resourceType: "source_file" /* SOURCE_FILE */,
4962
+ operation: "read",
4963
+ resourcePath: filePath
4964
+ });
4965
+ }
4966
+ /**
4967
+ * Check if agent can modify AST (dual-mode).
4968
+ */
4969
+ canModifyAST(tokenOrCapability) {
4970
+ if (typeof tokenOrCapability === "string") {
4971
+ return this.checkAccess({
4972
+ token: tokenOrCapability,
4973
+ resourceType: "ast" /* AST */,
4974
+ operation: "write"
4975
+ });
4976
+ }
4977
+ return this.checkAccess({
4978
+ token: "",
4979
+ capabilityToken: tokenOrCapability.token,
4980
+ issuerPublicKey: tokenOrCapability.publicKey,
4981
+ resourceType: "ast" /* AST */,
4982
+ operation: "write"
4983
+ });
4984
+ }
4985
+ /**
4986
+ * Check if agent can generate code (dual-mode).
4987
+ */
4988
+ canGenerateCode(tokenOrCapability) {
4989
+ if (typeof tokenOrCapability === "string") {
4990
+ return this.checkAccess({
4991
+ token: tokenOrCapability,
4992
+ resourceType: "code" /* CODE */,
4993
+ operation: "write"
4994
+ });
4995
+ }
4996
+ return this.checkAccess({
4997
+ token: "",
4998
+ capabilityToken: tokenOrCapability.token,
4999
+ issuerPublicKey: tokenOrCapability.publicKey,
5000
+ resourceType: "code" /* CODE */,
5001
+ operation: "write"
5002
+ });
5003
+ }
5004
+ /**
5005
+ * Check if agent can export output (dual-mode).
5006
+ */
5007
+ canExport(tokenOrCapability, outputPath) {
5008
+ if (typeof tokenOrCapability === "string") {
5009
+ return this.checkAccess({
5010
+ token: tokenOrCapability,
5011
+ resourceType: "output" /* OUTPUT */,
5012
+ operation: "write",
5013
+ resourcePath: outputPath
5014
+ });
5015
+ }
5016
+ return this.checkAccess({
5017
+ token: "",
5018
+ capabilityToken: tokenOrCapability.token,
5019
+ issuerPublicKey: tokenOrCapability.publicKey,
5020
+ resourceType: "output" /* OUTPUT */,
5021
+ operation: "write",
5022
+ resourcePath: outputPath
5023
+ });
5024
+ }
5025
+ // -----------------------------------------------------------------------
5026
+ // Accessors
5027
+ // -----------------------------------------------------------------------
5028
+ /**
5029
+ * Get the underlying AgentRBAC instance.
5030
+ */
5031
+ getRBAC() {
5032
+ return this.rbac;
5033
+ }
5034
+ /**
5035
+ * Get the CapabilityTokenIssuer instance.
5036
+ */
5037
+ getCapabilityIssuer() {
5038
+ return this.capabilityIssuer;
5039
+ }
5040
+ /**
5041
+ * Get the current resolution strategy.
5042
+ */
5043
+ getStrategy() {
5044
+ return this.strategy;
5045
+ }
5046
+ };
5047
+ globalCapabilityRBAC = null;
5048
+ }
5049
+ });
5050
+
5051
+ // src/compiler/identity/SpatialMemoryZones.ts
5052
+ function getSpatialZoneEnforcer(config) {
5053
+ if (!globalSpatialZoneEnforcer) {
5054
+ globalSpatialZoneEnforcer = new SpatialZoneEnforcer(config);
5055
+ }
5056
+ return globalSpatialZoneEnforcer;
5057
+ }
5058
+ var SpatialZoneEnforcer, globalSpatialZoneEnforcer;
5059
+ var init_SpatialMemoryZones = __esm({
5060
+ "src/compiler/identity/SpatialMemoryZones.ts"() {
5061
+ init_AgentTokenIssuer();
5062
+ SpatialZoneEnforcer = class {
5063
+ constructor(config = {}) {
5064
+ this.zones = /* @__PURE__ */ new Map();
5065
+ this.policies = /* @__PURE__ */ new Map();
5066
+ this.auditLog = [];
5067
+ this.tokenIssuer = config.tokenIssuer ?? getTokenIssuer();
5068
+ this.maxAuditEntries = config.maxAuditEntries ?? 1e4;
5069
+ }
5070
+ // -----------------------------------------------------------------------
5071
+ // Zone Management
5072
+ // -----------------------------------------------------------------------
5073
+ /**
5074
+ * Register a spatial zone.
5075
+ */
5076
+ registerZone(zone) {
5077
+ this.zones.set(zone.id, zone);
5078
+ }
5079
+ /**
5080
+ * Get a registered zone by ID.
5081
+ */
5082
+ getZone(zoneId) {
5083
+ return this.zones.get(zoneId);
5084
+ }
5085
+ /**
5086
+ * Remove a registered zone and its policy.
5087
+ */
5088
+ removeZone(zoneId) {
5089
+ this.policies.delete(zoneId);
5090
+ return this.zones.delete(zoneId);
5091
+ }
5092
+ /**
5093
+ * Get all registered zone IDs.
5094
+ */
5095
+ getRegisteredZoneIds() {
5096
+ return Array.from(this.zones.keys());
5097
+ }
5098
+ // -----------------------------------------------------------------------
5099
+ // Policy Management
5100
+ // -----------------------------------------------------------------------
5101
+ /**
5102
+ * Set the access policy for a zone.
5103
+ */
5104
+ setPolicy(policy) {
5105
+ if (!this.zones.has(policy.zoneId)) {
5106
+ throw new Error(`Cannot set policy for unregistered zone: ${policy.zoneId}`);
5107
+ }
5108
+ this.policies.set(policy.zoneId, policy);
5109
+ }
5110
+ /**
5111
+ * Get the policy for a zone.
5112
+ */
5113
+ getPolicy(zoneId) {
5114
+ return this.policies.get(zoneId);
5115
+ }
5116
+ // -----------------------------------------------------------------------
5117
+ // Access Checks
5118
+ // -----------------------------------------------------------------------
5119
+ /**
5120
+ * Check if an agent (identified by JWT token) can perform a spatial
5121
+ * operation in a given zone.
5122
+ *
5123
+ * @param agentToken JWT token issued by `AgentTokenIssuer`
5124
+ * @param zoneId Target zone identifier
5125
+ * @param operation The spatial permission required
5126
+ * @returns Access decision with reason
5127
+ */
5128
+ checkZoneAccess(agentToken, zoneId, operation) {
5129
+ const verificationResult = this.tokenIssuer.verifyToken(agentToken);
5130
+ if (!verificationResult.valid || !verificationResult.payload) {
5131
+ const decision2 = {
5132
+ allowed: false,
5133
+ reason: `Token verification failed: ${verificationResult.error ?? "unknown error"}`
5134
+ };
5135
+ this.recordAudit("unknown", "unknown", zoneId, operation, false, decision2.reason);
5136
+ return decision2;
5137
+ }
5138
+ const payload = verificationResult.payload;
5139
+ const agentId = payload.sub;
5140
+ const agentRole = payload.agent_role;
5141
+ const zone = this.zones.get(zoneId);
5142
+ if (!zone) {
5143
+ const decision2 = {
5144
+ allowed: false,
5145
+ reason: `Zone not found: ${zoneId}`,
5146
+ agentRole,
5147
+ agentId
5148
+ };
5149
+ this.recordAudit(agentId, agentRole, zoneId, operation, false, decision2.reason);
5150
+ return decision2;
5151
+ }
5152
+ const grantedPermissions = this.resolvePermissions(agentId, agentRole, zoneId, zone);
5153
+ const allowed = grantedPermissions.includes(operation);
5154
+ const reason = allowed ? `Access granted: agent ${agentId} has ${operation} in zone ${zoneId}` : `Access denied: agent ${agentId} lacks ${operation} in zone ${zoneId}`;
5155
+ const decision = {
5156
+ allowed,
5157
+ reason,
5158
+ agentRole,
5159
+ agentId
5160
+ };
5161
+ this.recordAudit(agentId, agentRole, zoneId, operation, allowed, reason);
5162
+ return decision;
5163
+ }
5164
+ /**
5165
+ * Get all zone IDs that an agent can access (for at least one operation).
5166
+ *
5167
+ * @param agentToken JWT token
5168
+ * @returns Array of accessible zone IDs
5169
+ */
5170
+ getAccessibleZones(agentToken) {
5171
+ const verificationResult = this.tokenIssuer.verifyToken(agentToken);
5172
+ if (!verificationResult.valid || !verificationResult.payload) {
5173
+ return [];
5174
+ }
5175
+ const payload = verificationResult.payload;
5176
+ const agentId = payload.sub;
5177
+ const agentRole = payload.agent_role;
5178
+ const accessibleZones = [];
5179
+ for (const [zoneId, zone] of this.zones) {
5180
+ const permissions = this.resolvePermissions(agentId, agentRole, zoneId, zone);
5181
+ if (permissions.length > 0) {
5182
+ accessibleZones.push(zoneId);
5183
+ }
5184
+ }
5185
+ return accessibleZones;
5186
+ }
5187
+ /**
5188
+ * Validate whether an agent can perform a spatial operation at a
5189
+ * specific 3D position. The position is checked against all registered
5190
+ * zones to find the enclosing zone(s), then permissions are evaluated.
5191
+ *
5192
+ * @param agentToken JWT token
5193
+ * @param position 3D position to check
5194
+ * @param operation Required spatial permission
5195
+ * @returns Access decision (aggregated across matching zones)
5196
+ */
5197
+ validateSpatialOperation(agentToken, position, operation) {
5198
+ const verificationResult = this.tokenIssuer.verifyToken(agentToken);
5199
+ if (!verificationResult.valid || !verificationResult.payload) {
5200
+ const decision2 = {
5201
+ allowed: false,
5202
+ reason: `Token verification failed: ${verificationResult.error ?? "unknown error"}`
5203
+ };
5204
+ this.recordAudit("unknown", "unknown", "*position*", operation, false, decision2.reason);
5205
+ return decision2;
5206
+ }
5207
+ const payload = verificationResult.payload;
5208
+ const agentId = payload.sub;
5209
+ const agentRole = payload.agent_role;
5210
+ const containingZones = this.findZonesContainingPosition(position);
5211
+ if (containingZones.length === 0) {
5212
+ const decision2 = {
5213
+ allowed: false,
5214
+ reason: `No registered zone contains position (${position[0]}, ${position[1]}, ${position[2]})`,
5215
+ agentRole,
5216
+ agentId
5217
+ };
5218
+ this.recordAudit(agentId, agentRole, "*no-zone*", operation, false, decision2.reason);
5219
+ return decision2;
5220
+ }
5221
+ for (const zone of containingZones) {
5222
+ const permissions = this.resolvePermissions(agentId, agentRole, zone.id, zone);
5223
+ if (permissions.includes(operation)) {
5224
+ const decision2 = {
5225
+ allowed: true,
5226
+ reason: `Access granted via zone ${zone.id} at position (${position[0]}, ${position[1]}, ${position[2]})`,
5227
+ agentRole,
5228
+ agentId
5229
+ };
5230
+ this.recordAudit(agentId, agentRole, zone.id, operation, true, decision2.reason);
5231
+ return decision2;
5232
+ }
5233
+ }
5234
+ const zoneIds = containingZones.map((z2) => z2.id).join(", ");
5235
+ const decision = {
5236
+ allowed: false,
5237
+ reason: `Access denied in all containing zones [${zoneIds}] at position (${position[0]}, ${position[1]}, ${position[2]})`,
5238
+ agentRole,
5239
+ agentId
5240
+ };
5241
+ this.recordAudit(agentId, agentRole, containingZones[0].id, operation, false, decision.reason);
5242
+ return decision;
5243
+ }
5244
+ // -----------------------------------------------------------------------
5245
+ // Audit Trail
5246
+ // -----------------------------------------------------------------------
5247
+ /**
5248
+ * Get the full GDPR audit trail.
5249
+ */
5250
+ getAuditLog() {
5251
+ return this.auditLog;
5252
+ }
5253
+ /**
5254
+ * Get audit entries for a specific agent (GDPR data subject access).
5255
+ */
5256
+ getAuditEntriesForAgent(agentId) {
5257
+ return this.auditLog.filter((entry) => entry.agentId === agentId);
5258
+ }
5259
+ /**
5260
+ * Get audit entries for a specific zone.
5261
+ */
5262
+ getAuditEntriesForZone(zoneId) {
5263
+ return this.auditLog.filter((entry) => entry.zoneId === zoneId);
5264
+ }
5265
+ /**
5266
+ * Clear audit entries for a specific agent (GDPR right-to-erasure).
5267
+ *
5268
+ * @returns Number of entries removed
5269
+ */
5270
+ eraseAuditEntriesForAgent(agentId) {
5271
+ const before = this.auditLog.length;
5272
+ this.auditLog = this.auditLog.filter((entry) => entry.agentId !== agentId);
5273
+ return before - this.auditLog.length;
5274
+ }
5275
+ /**
5276
+ * Clear all audit entries.
5277
+ */
5278
+ clearAuditLog() {
5279
+ this.auditLog = [];
5280
+ }
5281
+ // -----------------------------------------------------------------------
5282
+ // Internal Helpers
5283
+ // -----------------------------------------------------------------------
5284
+ /**
5285
+ * Resolve the effective spatial permissions for an agent in a zone.
5286
+ *
5287
+ * Resolution order:
5288
+ * 1. Agent-specific overrides (highest priority)
5289
+ * 2. Role-based permissions from policy
5290
+ * 3. Policy default permissions
5291
+ * 4. Classification-based fallback (if no policy exists)
5292
+ */
5293
+ resolvePermissions(agentId, agentRole, zoneId, zone) {
5294
+ const policy = this.policies.get(zoneId);
5295
+ if (policy) {
5296
+ if (policy.agentOverrides[agentId]) {
5297
+ return policy.agentOverrides[agentId];
5298
+ }
5299
+ if (policy.rolePermissions[agentRole]) {
5300
+ return policy.rolePermissions[agentRole];
5301
+ }
5302
+ return policy.defaultPermissions;
5303
+ }
5304
+ return this.getClassificationDefaults(zone.classification);
5305
+ }
5306
+ /**
5307
+ * Get default permissions based on zone classification.
5308
+ */
5309
+ getClassificationDefaults(classification) {
5310
+ switch (classification) {
5311
+ case "public":
5312
+ return ["spatial:read" /* SPATIAL_READ */];
5313
+ case "restricted":
5314
+ return ["spatial:read" /* SPATIAL_READ */];
5315
+ case "private":
5316
+ return [];
5317
+ case "sensitive":
5318
+ return [];
5319
+ default:
5320
+ return [];
5321
+ }
5322
+ }
5323
+ /**
5324
+ * Find all zones whose bounds contain the given position.
5325
+ *
5326
+ * Named zones (no explicit bounds) are NOT included in positional
5327
+ * lookups because their bounds are resolved at runtime.
5328
+ */
5329
+ findZonesContainingPosition(position) {
5330
+ const result = [];
5331
+ for (const zone of this.zones.values()) {
5332
+ if (!zone.bounds) continue;
5333
+ if (this.isPositionInBounds(position, zone.bounds)) {
5334
+ result.push(zone);
5335
+ }
5336
+ }
5337
+ return result;
5338
+ }
5339
+ /**
5340
+ * Check if a 3D position is within the given bounds.
5341
+ *
5342
+ * For geospatial bounds: x=lat, y=lon, z=alt
5343
+ * For local bounds: x=X, y=Y, z=Z
5344
+ * Named bounds always return false (resolved at runtime).
5345
+ */
5346
+ isPositionInBounds(position, bounds) {
5347
+ switch (bounds.type) {
5348
+ case "geospatial": {
5349
+ const inLat = position[0] >= bounds.minLat && position[0] <= bounds.maxLat;
5350
+ const inLon = position[1] >= bounds.minLon && position[1] <= bounds.maxLon;
5351
+ let inAlt = true;
5352
+ if (bounds.minAlt !== void 0 && bounds.maxAlt !== void 0) {
5353
+ inAlt = position[2] >= bounds.minAlt && position[2] <= bounds.maxAlt;
5354
+ }
5355
+ return inLat && inLon && inAlt;
5356
+ }
5357
+ case "local": {
5358
+ return position[0] >= bounds.minX && position[0] <= bounds.maxX && position[1] >= bounds.minY && position[1] <= bounds.maxY && position[2] >= bounds.minZ && position[2] <= bounds.maxZ;
5359
+ }
5360
+ case "named":
5361
+ return false;
5362
+ default:
5363
+ return false;
5364
+ }
5365
+ }
5366
+ /**
5367
+ * Record a GDPR audit entry.
5368
+ */
5369
+ recordAudit(agentId, agentRole, zoneId, operation, allowed, reason) {
5370
+ const entry = {
5371
+ timestamp: Date.now(),
5372
+ agentId,
5373
+ agentRole,
5374
+ zoneId,
5375
+ operation,
5376
+ allowed,
5377
+ reason
5378
+ };
5379
+ this.auditLog.push(entry);
5380
+ if (this.auditLog.length > this.maxAuditEntries) {
5381
+ this.auditLog = this.auditLog.slice(-this.maxAuditEntries);
5382
+ }
5383
+ }
5384
+ };
5385
+ globalSpatialZoneEnforcer = null;
5386
+ }
5387
+ });
5388
+ function isCapabilityTokenCredential(token) {
5389
+ if (!token || typeof token === "string") return false;
5390
+ return typeof token === "object" && "capabilityToken" in token && "issuerPublicKey" in token && token.capabilityToken != null && typeof token.issuerPublicKey === "string";
5391
+ }
5392
+ function escapeCStyle(value) {
5393
+ return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/'/g, "\\'").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t").replace(/\0/g, "\\0");
5394
+ }
5395
+ function escapeGDScript(value) {
5396
+ return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/'/g, "\\'").replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/\0/g, "");
5397
+ }
5398
+ function escapeJSX(value) {
5399
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;").replace(/\{/g, "&#123;").replace(/\}/g, "&#125;");
5400
+ }
5401
+ function escapeXML(value) {
5402
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
5403
+ }
5404
+ function escapeShader(value) {
5405
+ return value.replace(/\\/g, "").replace(/\*/g, "").replace(/\//g, "").replace(/#/g, "").replace(/\n/g, " ").replace(/\r/g, "");
5406
+ }
5407
+ function escapePython(value) {
5408
+ return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/'/g, "\\'").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t").replace(/\0/g, "\\x00");
5409
+ }
5410
+ function escapeLua(value) {
5411
+ return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/'/g, "\\'").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\0/g, "\\0");
5412
+ }
5413
+ function escapeUSD(value) {
5414
+ return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r");
5415
+ }
5416
+ function escapeJSON(value) {
5417
+ return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t").replace(/[\x00-\x1f]/g, (ch) => "\\u" + ch.charCodeAt(0).toString(16).padStart(4, "0"));
5418
+ }
5419
+ function escapeStringValue(value, target) {
5420
+ if (!value) return value;
5421
+ switch (target) {
5422
+ case "Solidity":
5423
+ case "CSharp":
5424
+ case "Swift":
5425
+ case "Kotlin":
5426
+ case "TypeScript":
5427
+ case "Rust":
5428
+ return escapeCStyle(value);
5429
+ case "GDScript":
5430
+ return escapeGDScript(value);
5431
+ case "JSX":
5432
+ return escapeJSX(value);
5433
+ case "XML":
5434
+ return escapeXML(value);
5435
+ case "GLSL":
5436
+ case "HLSL":
5437
+ case "WGSL":
5438
+ return escapeShader(value);
5439
+ case "Python":
5440
+ return escapePython(value);
5441
+ case "Lua":
5442
+ return escapeLua(value);
5443
+ case "USD":
5444
+ return escapeUSD(value);
5445
+ case "JSON":
5446
+ return escapeJSON(value);
5447
+ default:
5448
+ return value;
5449
+ }
5450
+ }
5451
+ function createTestCompilerToken() {
5452
+ return "";
5453
+ }
5454
+ var COMPILER_CLASS_TO_ANS_NAME, UnauthorizedCompilerAccessError, CompilerBase;
5455
+ var init_CompilerBase = __esm({
5456
+ "src/compiler/CompilerBase.ts"() {
5457
+ init_AgentRBAC();
5458
+ init_CapabilityRBAC();
5459
+ init_ANSNamespace();
5460
+ init_SpatialMemoryZones();
5461
+ init_CompilerDocumentationGenerator();
5462
+ COMPILER_CLASS_TO_ANS_NAME = {
5463
+ UnityCompiler: "unity",
5464
+ UnrealCompiler: "unreal",
5465
+ GodotCompiler: "godot",
5466
+ VRChatCompiler: "vrchat",
5467
+ OpenXRCompiler: "openxr",
5468
+ OpenXRSpatialEntitiesCompiler: "openxr-spatial-entities",
5469
+ VisionOSCompiler: "visionos",
5470
+ ARCompiler: "ar",
5471
+ AndroidXRCompiler: "android-xr",
5472
+ AIGlassesCompiler: "ai-glasses",
5473
+ AndroidCompiler: "android",
5474
+ IOSCompiler: "ios",
5475
+ BabylonCompiler: "babylon",
5476
+ WebGPUCompiler: "webgpu",
5477
+ R3FCompiler: "r3f",
5478
+ PlayCanvasCompiler: "playcanvas",
5479
+ ThreeJSCompiler: "threejs",
5480
+ WASMCompiler: "wasm",
5481
+ TSLCompiler: "tsl",
5482
+ URDFCompiler: "urdf",
5483
+ SDFCompiler: "sdf",
5484
+ USDPhysicsCompiler: "usd",
5485
+ GLTFPipeline: "gltf",
5486
+ GaussianSplattingCompiler: "3dgs",
5487
+ DTDLCompiler: "dtdl",
5488
+ NFTMarketplaceCompiler: "nft-marketplace",
5489
+ SCMCompiler: "scm",
5490
+ VRRCompiler: "vrr",
5491
+ A2AAgentCardCompiler: "a2a-agent-card",
5492
+ MultiLayerCompiler: "multi-layer",
5493
+ IncrementalCompiler: "incremental",
5494
+ StateCompiler: "state",
5495
+ TraitCompositionCompiler: "trait-composition",
5496
+ DomainBlockCompilerMixin: "domain-block",
5497
+ NIRCompiler: "nir",
5498
+ URDFToUSDZConverter: "urdf",
5499
+ QuiltCompiler: "quilt",
5500
+ MVHEVCCompiler: "mv-hevc",
5501
+ NodeServiceCompiler: "node-service",
5502
+ NextJSAPICompiler: "nextjs-api",
5503
+ MCPConfigCompiler: "domain-block",
5504
+ AgentInferenceCompiler: "agent-inference"
5505
+ };
5506
+ UnauthorizedCompilerAccessError = class extends Error {
5507
+ constructor(decision, operation, compilerName) {
5508
+ super(
5509
+ `[${compilerName}] Unauthorized ${operation}: ${decision.reason || "Access denied"}
5510
+ Required Permission: ${decision.requiredPermission || "unknown"}`
5511
+ );
5512
+ this.decision = decision;
5513
+ this.operation = operation;
5514
+ this.compilerName = compilerName;
5515
+ this.name = "UnauthorizedCompilerAccessError";
5516
+ }
5517
+ };
5518
+ CompilerBase = class {
5519
+ constructor() {
5520
+ this.rbac = getRBAC();
5521
+ /**
5522
+ * Lazy-initialized CapabilityRBAC adapter for UCAN token verification.
5523
+ * Only created when a UCAN capability token is first encountered.
5524
+ */
5525
+ this._capabilityRBAC = null;
5526
+ /**
5527
+ * Lazy-initialized SpatialZoneEnforcer for compile-time spatial zone checks.
5528
+ * Only created when spatial zone validation is first invoked.
5529
+ */
5530
+ this._spatialZoneEnforcer = null;
5531
+ /**
5532
+ * Lazy-initialized documentation generator for triple-output compilation.
5533
+ * Only created when generateDocs option is enabled.
5534
+ */
5535
+ this._documentationGenerator = null;
5536
+ }
5537
+ /**
5538
+ * Sanitizes a string value for injection into a specific compiler target language.
5539
+ * Mitigates Cross-Agent Compilation Injection attacks (e.g. CWE-94).
5540
+ *
5541
+ * @param value The raw string value from the AST
5542
+ * @param target The compilation target language
5543
+ * @returns The escaped/sanitized string safe for interpolation
5544
+ */
5545
+ escapeStringValue(value, target) {
5546
+ return escapeStringValue(value, target);
5547
+ }
5548
+ // =========================================================================
5549
+ // P3 Migration Bridge: Dual-mode token support
5550
+ // =========================================================================
5551
+ /**
5552
+ * Get or create the CapabilityRBAC adapter instance.
5553
+ *
5554
+ * Lazily initialized to avoid overhead when only JWT tokens are used.
5555
+ */
5556
+ getCapabilityRBAC() {
5557
+ if (!this._capabilityRBAC) {
5558
+ this._capabilityRBAC = getCapabilityRBAC();
5559
+ }
5560
+ return this._capabilityRBAC;
5561
+ }
5562
+ /**
5563
+ * Get or create the SpatialZoneEnforcer instance.
5564
+ *
5565
+ * Lazily initialized to avoid overhead when spatial zones are not in use.
5566
+ */
5567
+ getSpatialZoneEnforcer() {
5568
+ if (!this._spatialZoneEnforcer) {
5569
+ this._spatialZoneEnforcer = getSpatialZoneEnforcer();
5570
+ }
5571
+ return this._spatialZoneEnforcer;
5572
+ }
5573
+ /**
5574
+ * Get or create the CompilerDocumentationGenerator instance.
5575
+ *
5576
+ * Lazily initialized to avoid overhead when documentation generation is disabled.
5577
+ *
5578
+ * @param options - Documentation generator options
5579
+ */
5580
+ getDocumentationGenerator(options) {
5581
+ if (!this._documentationGenerator) {
5582
+ this._documentationGenerator = new CompilerDocumentationGenerator(options);
5583
+ }
5584
+ return this._documentationGenerator;
5585
+ }
5586
+ /**
5587
+ * Generate triple-output documentation for a compilation result.
5588
+ *
5589
+ * This is a utility method that subclasses can call after successful compilation
5590
+ * to generate llms.txt, .well-known/mcp, and markdown documentation.
5591
+ *
5592
+ * @param composition - Parsed HoloScript composition AST
5593
+ * @param compiledCode - The compiled output code
5594
+ * @param options - Documentation generator options
5595
+ * @returns Triple-output documentation bundle
5596
+ *
5597
+ * @example
5598
+ * ```typescript
5599
+ * compile(composition: HoloComposition, agentToken: string, options?: MyCompilerOptions): CompilationResult {
5600
+ * this.validateCompilerAccess(agentToken);
5601
+ * const code = this.performCompilation(composition);
5602
+ *
5603
+ * if (options?.generateDocs) {
5604
+ * const docs = this.generateDocumentation(composition, code, options.docsOptions);
5605
+ * return { output: code, documentation: docs };
5606
+ * }
5607
+ *
5608
+ * return { output: code };
5609
+ * }
5610
+ * ```
5611
+ */
5612
+ generateDocumentation(composition, compiledCode, options, generationMeta) {
5613
+ const generator = this.getDocumentationGenerator(options);
5614
+ return generator.generate(composition, this.compilerName, compiledCode, generationMeta);
5615
+ }
5616
+ /**
5617
+ * Normalize primary compiler output for llms.txt / markdown (avoid huge/binary payloads).
5618
+ */
5619
+ serializeOutputForDocumentation(output) {
5620
+ if (typeof output === "string") {
5621
+ return output.length > 2e5 ? output.slice(0, 2e5) : output;
5622
+ }
5623
+ if (output && typeof output === "object") {
5624
+ const rec = output;
5625
+ if ("gltf" in rec || "buffers" in rec) {
5626
+ return {
5627
+ _kind: "binary_or_gltf_bundle",
5628
+ keys: Object.keys(rec).join(",")
5629
+ };
5630
+ }
5631
+ const vals = Object.values(rec);
5632
+ if (vals.length > 0 && vals.every((v) => typeof v === "string")) {
5633
+ return rec;
5634
+ }
5635
+ try {
5636
+ const json = JSON.stringify(output);
5637
+ return json.length > 2e5 ? json.slice(0, 2e5) : json;
5638
+ } catch {
5639
+ return { _kind: "non_serializable", keys: Object.keys(rec).join(",") };
5640
+ }
5641
+ }
5642
+ return String(output);
5643
+ }
5644
+ /** Short digest for MCP card `_meta.holoscript.compilation_digest`. */
5645
+ digestForDocumentation(docPayload) {
5646
+ const payload = typeof docPayload === "string" ? docPayload : JSON.stringify(docPayload);
5647
+ return createHash("sha256").update(payload).digest("hex").slice(0, 16);
5648
+ }
5649
+ /**
5650
+ * When `generateDocs` is set on {@link BaseCompilerOptions}, returns a {@link CompilationResult}
5651
+ * with `documentation` (llms.txt, .well-known/mcp, markdown); otherwise returns `output` unchanged.
5652
+ */
5653
+ withTripleOutputIfRequested(composition, output, opts) {
5654
+ if (!opts?.generateDocs) {
5655
+ return output;
5656
+ }
5657
+ const docPayload = this.serializeOutputForDocumentation(output);
5658
+ const generationMeta = {
5659
+ compilationDigest: this.digestForDocumentation(docPayload)
5660
+ };
5661
+ const documentation = this.generateDocumentation(
5662
+ composition,
5663
+ docPayload,
5664
+ opts.docsOptions,
5665
+ generationMeta
5666
+ );
5667
+ return { output, documentation };
5668
+ }
5669
+ /**
5670
+ * Get the ANS capability namespace path for this compiler.
5671
+ *
5672
+ * Subclasses MAY override this to specify their exact ANS namespace.
5673
+ * The default implementation derives it from `compilerName` using the
5674
+ * `COMPILER_CLASS_TO_ANS_NAME` lookup table.
5675
+ *
5676
+ * @returns The ANS capability path (e.g., "/compile/web3d/r3f"), or
5677
+ * `undefined` if the compiler has no registered ANS namespace.
5678
+ *
5679
+ * @example
5680
+ * ```typescript
5681
+ * // Default: derives from compilerName
5682
+ * class R3FCompiler extends CompilerBase {
5683
+ * protected readonly compilerName = 'R3FCompiler';
5684
+ * // getRequiredCapability() returns '/compile/web3d/r3f' automatically
5685
+ * }
5686
+ *
5687
+ * // Override: explicit namespace
5688
+ * class CustomCompiler extends CompilerBase {
5689
+ * protected readonly compilerName = 'CustomCompiler';
5690
+ * protected getRequiredCapability(): string | undefined {
5691
+ * return '/compile/web3d/r3f';
5692
+ * }
5693
+ * }
5694
+ * ```
5695
+ */
5696
+ getRequiredCapability() {
5697
+ const ansName = COMPILER_CLASS_TO_ANS_NAME[this.compilerName];
5698
+ if (ansName && isValidCompilerName(ansName)) {
5699
+ return COMPILER_ANS_MAP[ansName];
5700
+ }
5701
+ if (process.env["NODE_ENV"] !== "test") {
5702
+ console.warn(
5703
+ `[CompilerBase] Compiler '${this.compilerName}' has no ANS namespace entry. Add it to COMPILER_CLASS_TO_ANS_NAME to enable UCAN capability enforcement.`
5704
+ );
5705
+ }
5706
+ return void 0;
5707
+ }
5708
+ // =========================================================================
5709
+ // Legacy JWT RBAC validation (unchanged from v1.0.0)
5710
+ // =========================================================================
5711
+ /**
5712
+ * Validate agent can read AST
5713
+ * Skips validation when no token is provided.
5714
+ * In production (`NODE_ENV=production`) a warning is emitted when no token is
5715
+ * supplied — callers should always authenticate compiler access in production.
5716
+ *
5717
+ * @param agentToken - Agent JWT token (optional)
5718
+ * @throws UnauthorizedCompilerAccessError if token is provided but invalid
5719
+ */
5720
+ validateASTAccess(agentToken) {
5721
+ if (!agentToken) {
5722
+ if (process.env["NODE_ENV"] === "production") {
5723
+ console.warn(
5724
+ `[${this.compilerName}] validateASTAccess called without a token in production. All compiler calls should be authenticated. Pass an agent token to enforce RBAC.`
5725
+ );
5726
+ }
5727
+ return;
5728
+ }
5729
+ const decision = this.rbac.checkAccess({
5730
+ token: agentToken,
5731
+ resourceType: "ast" /* AST */,
5732
+ operation: "read",
5733
+ expectedWorkflowStep: "generate_assembly" /* GENERATE_ASSEMBLY */
5734
+ });
5735
+ if (!decision.allowed) {
5736
+ throw new UnauthorizedCompilerAccessError(decision, "AST access", this.compilerName);
5737
+ }
5738
+ }
5739
+ /**
5740
+ * Validate agent can generate code
5741
+ * Skips validation when no token is provided.
5742
+ * In production (`NODE_ENV=production`) a warning is emitted when no token is
5743
+ * supplied — callers should always authenticate compiler access in production.
5744
+ *
5745
+ * @param agentToken - Agent JWT token (optional)
5746
+ * @throws UnauthorizedCompilerAccessError if token is provided but invalid
5747
+ */
5748
+ validateCodeGeneration(agentToken) {
5749
+ if (!agentToken) {
5750
+ if (process.env["NODE_ENV"] === "production") {
5751
+ console.warn(
5752
+ `[${this.compilerName}] validateCodeGeneration called without a token in production. All compiler calls should be authenticated. Pass an agent token to enforce RBAC.`
5753
+ );
5754
+ }
5755
+ return;
5756
+ }
5757
+ const decision = this.rbac.checkAccess({
5758
+ token: agentToken,
5759
+ resourceType: "code" /* CODE */,
5760
+ operation: "write",
5761
+ expectedWorkflowStep: "generate_assembly" /* GENERATE_ASSEMBLY */
5762
+ });
5763
+ if (!decision.allowed) {
5764
+ throw new UnauthorizedCompilerAccessError(decision, "code generation", this.compilerName);
5765
+ }
5766
+ }
5767
+ /**
5768
+ * Validate agent can write to output path
5769
+ * Skips validation when no token is provided.
5770
+ * In production (`NODE_ENV=production`) a warning is emitted when no token is
5771
+ * supplied — callers should always authenticate compiler access in production.
5772
+ *
5773
+ * @param agentToken - Agent JWT token (optional)
5774
+ * @param outputPath - Target output file path
5775
+ * @throws UnauthorizedCompilerAccessError if token is provided but invalid
5776
+ */
5777
+ validateOutputPath(agentToken, outputPath) {
5778
+ if (!agentToken) {
5779
+ if (process.env["NODE_ENV"] === "production") {
5780
+ console.warn(
5781
+ `[${this.compilerName}] validateOutputPath called without a token in production. All compiler calls should be authenticated. Pass an agent token to enforce RBAC.`
5782
+ );
5783
+ }
5784
+ return;
5785
+ }
5786
+ const decision = this.rbac.checkAccess({
5787
+ token: agentToken,
5788
+ resourceType: "output" /* OUTPUT */,
5789
+ operation: "write",
5790
+ resourcePath: outputPath,
5791
+ expectedWorkflowStep: "serialize" /* SERIALIZE */
5792
+ });
5793
+ if (!decision.allowed) {
5794
+ throw new UnauthorizedCompilerAccessError(
5795
+ decision,
5796
+ `output write to '${outputPath}'`,
5797
+ this.compilerName
5798
+ );
5799
+ }
5800
+ }
5801
+ // =========================================================================
5802
+ // UCAN Capability Token validation (P3 Migration Bridge)
5803
+ // =========================================================================
5804
+ /**
5805
+ * Validate compiler access using a UCAN capability token.
5806
+ *
5807
+ * Checks that the capability token grants access to the required resources
5808
+ * (AST read, CODE write, and optionally OUTPUT write) using the
5809
+ * CapabilityRBAC adapter.
5810
+ *
5811
+ * @param credential - UCAN capability token credential
5812
+ * @param outputPath - Optional output path for scope validation
5813
+ * @throws UnauthorizedCompilerAccessError if any capability check fails
5814
+ */
5815
+ validateCapabilityAccess(credential, outputPath) {
5816
+ const capRBAC = this.getCapabilityRBAC();
5817
+ const astDecision = capRBAC.checkAccess({
5818
+ token: "",
5819
+ capabilityToken: credential.capabilityToken,
5820
+ issuerPublicKey: credential.issuerPublicKey,
5821
+ resourceType: "ast" /* AST */,
5822
+ operation: "read"
5823
+ });
5824
+ if (!astDecision.allowed) {
5825
+ throw new UnauthorizedCompilerAccessError(astDecision, "AST access", this.compilerName);
5826
+ }
5827
+ const codeDecision = capRBAC.checkAccess({
5828
+ token: "",
5829
+ capabilityToken: credential.capabilityToken,
5830
+ issuerPublicKey: credential.issuerPublicKey,
5831
+ resourceType: "code" /* CODE */,
5832
+ operation: "write"
5833
+ });
5834
+ if (!codeDecision.allowed) {
5835
+ throw new UnauthorizedCompilerAccessError(codeDecision, "code generation", this.compilerName);
5836
+ }
5837
+ if (outputPath) {
5838
+ const outputDecision = capRBAC.checkAccess({
5839
+ token: "",
5840
+ capabilityToken: credential.capabilityToken,
5841
+ issuerPublicKey: credential.issuerPublicKey,
5842
+ resourceType: "output" /* OUTPUT */,
5843
+ operation: "write",
5844
+ resourcePath: outputPath
5845
+ });
5846
+ if (!outputDecision.allowed) {
5847
+ throw new UnauthorizedCompilerAccessError(
5848
+ outputDecision,
5849
+ `output write to '${outputPath}'`,
5850
+ this.compilerName
5851
+ );
5852
+ }
5853
+ }
5854
+ }
5855
+ // =========================================================================
5856
+ // Spatial Memory Zone validation
5857
+ // =========================================================================
5858
+ /**
5859
+ * Validate spatial zone access for the current compilation.
5860
+ *
5861
+ * This step runs **after** RBAC/UCAN token verification and enforces
5862
+ * compile-time spatial zone permissions when zones are registered.
5863
+ *
5864
+ * **Backward compatible**: When no zones are registered in the global
5865
+ * SpatialZoneEnforcer, this method is a no-op.
5866
+ *
5867
+ * **Non-blocking**: Zone enforcement failures are logged as warnings
5868
+ * but do NOT throw or block compilation. This allows gradual rollout
5869
+ * of spatial zone policies without breaking existing pipelines.
5870
+ *
5871
+ * @param agentToken - JWT token string (spatial zones use JWT verification)
5872
+ */
5873
+ validateSpatialZoneAccess(agentToken) {
5874
+ if (!agentToken) return;
5875
+ const enforcer = this.getSpatialZoneEnforcer();
5876
+ const zoneIds = enforcer.getRegisteredZoneIds();
5877
+ if (zoneIds.length === 0) return;
5878
+ for (const zoneId of zoneIds) {
5879
+ const decision = enforcer.checkZoneAccess(
5880
+ agentToken,
5881
+ zoneId,
5882
+ "spatial:read" /* SPATIAL_READ */
5883
+ );
5884
+ if (!decision.allowed) {
5885
+ console.warn(
5886
+ `[${this.compilerName}] Spatial zone access warning: agent ${decision.agentId ?? "unknown"} denied SPATIAL_READ in zone "${zoneId}": ${decision.reason}`
5887
+ );
5888
+ }
5889
+ }
5890
+ }
5891
+ // =========================================================================
5892
+ // Dual-mode access validation (P3 Migration Bridge)
5893
+ // =========================================================================
5894
+ /**
5895
+ * Validate all compiler permissions in single call (dual-mode).
5896
+ *
5897
+ * **P3 Migration Bridge**: This method now accepts both JWT RBAC tokens
5898
+ * (string) and UCAN capability tokens (CapabilityTokenCredential).
5899
+ *
5900
+ * Token routing:
5901
+ * - `undefined` / `null` / empty string: Skip all validation (backwards compatibility)
5902
+ * - `string` (non-empty): Route to legacy JWT RBAC via AgentRBAC.checkAccess()
5903
+ * - `CapabilityTokenCredential`: Route to UCAN via CapabilityRBAC.checkAccess()
5904
+ *
5905
+ * Convenience method combining AST access + code generation + optional output validation.
5906
+ * Skips ALL validation when no token is provided (backwards compatibility / testing).
5907
+ *
5908
+ * @param agentToken - JWT token string OR UCAN CapabilityTokenCredential (optional)
5909
+ * @param outputPath - Optional output path
5910
+ * @throws UnauthorizedCompilerAccessError if any validation fails
5911
+ */
5912
+ validateCompilerAccess(agentToken, outputPath) {
5913
+ if (!agentToken) return;
5914
+ if (isCapabilityTokenCredential(agentToken)) {
5915
+ this.validateCapabilityAccess(agentToken, outputPath);
5916
+ return;
5917
+ }
5918
+ this.validateASTAccess(agentToken);
5919
+ this.validateCodeGeneration(agentToken);
5920
+ if (outputPath) {
5921
+ this.validateOutputPath(agentToken, outputPath);
5922
+ }
5923
+ this.validateSpatialZoneAccess(agentToken);
5924
+ }
5925
+ // =========================================================================
5926
+ // Cultural compatibility validation
5927
+ // =========================================================================
5928
+ /**
5929
+ * Extract cultural profile from an agent token.
5930
+ *
5931
+ * @param agentToken - JWT token string (capability tokens do not carry cultural profiles)
5932
+ * @returns The cultural profile if present, or null
5933
+ */
5934
+ extractCulturalProfile(agentToken) {
5935
+ if (!agentToken) return null;
5936
+ return this.rbac.extractCulturalProfile(agentToken);
5937
+ }
5938
+ /**
5939
+ * Validate cultural compatibility across multiple agent tokens.
5940
+ *
5941
+ * Subclasses can call this during multi-agent compilation to ensure
5942
+ * all participating agents have compatible cultural profiles before
5943
+ * proceeding with code generation.
5944
+ *
5945
+ * @param agentTokens - Map of agent name to JWT token
5946
+ * @param normSets - Optional map of agent name to norm_set arrays
5947
+ * @returns Cultural compatibility result, or null if fewer than 2 agents
5948
+ * have cultural profiles
5949
+ */
5950
+ validateCulturalCompatibility(agentTokens, normSets) {
5951
+ return this.rbac.validateCulturalCompatibility(agentTokens, normSets);
5952
+ }
5953
+ };
5954
+ }
5955
+ });
5956
+
5957
+ export { ANSCapabilityPath, BUILTIN_NORMS, BUILTIN_NORM_PROVENANCE, CompilerBase, CompilerDocumentationGenerator, UNKNOWN_NORM_PROVENANCE, UnauthorizedCompilerAccessError, createTestCompilerToken, criticalMassForChange, deserializeNormProvenance, escapeStringValue, getBuiltinNorm, getRBAC, init_ANSNamespace, init_AgentRBAC, init_CompilerBase, init_CompilerDocumentationGenerator, init_CultureTraits, isCapabilityTokenCredential, normalizeNormProvenance, normsByCategory, serializeNormProvenance };
5958
+ //# sourceMappingURL=chunk-QTPMJRGS.js.map
5959
+ //# sourceMappingURL=chunk-QTPMJRGS.js.map