@holoscript/core 6.0.3 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (244) hide show
  1. package/README.md +40 -40
  2. package/dist/codebase/index.d.ts +25 -0
  3. package/dist/compiler/index.d.ts +82 -0
  4. package/dist/constants.d.ts +4 -0
  5. package/dist/coordinators/index.d.ts +189 -0
  6. package/dist/entries/interop.d.ts +9 -0
  7. package/dist/entries/scripting.d.ts +7 -0
  8. package/dist/index.d.ts +520 -19
  9. package/dist/paper-0c-spike/index.d.ts +29 -0
  10. package/dist/reconstruction/index.d.ts +78 -0
  11. package/dist/self-improvement/index.d.ts +0 -48
  12. package/dist/storage/index.d.ts +24 -0
  13. package/dist/tools/index.d.ts +33 -0
  14. package/dist/traitDocs/traitDocs.d.ts +69 -0
  15. package/dist/traits/index.d.ts +61 -0
  16. package/package.json +102 -19
  17. package/dist/GLTFPipeline-3KLWWUQO.cjs +0 -34
  18. package/dist/GLTFPipeline-LYII2ZVQ.js +0 -13
  19. package/dist/HoloScriptPlusParser-BZR5DELQ.js +0 -692
  20. package/dist/HoloScriptPlusParser-SBMYDNXO.cjs +0 -697
  21. package/dist/USDZExporter-MHEHXZB4.cjs +0 -709
  22. package/dist/USDZExporter-YA55ZS35.js +0 -707
  23. package/dist/chunk-26TLYBFD.js +0 -309
  24. package/dist/chunk-27LWW5FU.cjs +0 -410
  25. package/dist/chunk-2UX5LRAP.cjs +0 -833
  26. package/dist/chunk-32TWR3HE.js +0 -70
  27. package/dist/chunk-3FXV5S25.cjs +0 -633
  28. package/dist/chunk-3FYZOR7S.cjs +0 -69
  29. package/dist/chunk-3KEU5QYY.cjs +0 -175
  30. package/dist/chunk-4FCZDTD5.js +0 -610
  31. package/dist/chunk-4KJ2R7VP.cjs +0 -507
  32. package/dist/chunk-4SMUJFHL.js +0 -1213
  33. package/dist/chunk-54FHG2MX.js +0 -655
  34. package/dist/chunk-56IF4NTA.js +0 -56
  35. package/dist/chunk-5GLCTO44.js +0 -161
  36. package/dist/chunk-5TOFIR6L.js +0 -407
  37. package/dist/chunk-65RFOWZI.js +0 -765
  38. package/dist/chunk-6OQBLABR.js +0 -5240
  39. package/dist/chunk-6WNCRE6F.js +0 -126
  40. package/dist/chunk-74YCHHTE.js +0 -1872
  41. package/dist/chunk-7H5UNJZD.cjs +0 -1973
  42. package/dist/chunk-7KPI4EKH.cjs +0 -701
  43. package/dist/chunk-7LCYLPW2.cjs +0 -663
  44. package/dist/chunk-7N3JIJMT.js +0 -1395
  45. package/dist/chunk-7X2IEJIE.cjs +0 -2526
  46. package/dist/chunk-A6GO3DPZ.cjs +0 -1002
  47. package/dist/chunk-AC4BSHFV.js +0 -765
  48. package/dist/chunk-AIUXRS74.cjs +0 -3681
  49. package/dist/chunk-ARNKA274.cjs +0 -130
  50. package/dist/chunk-AW7WAELW.js +0 -975
  51. package/dist/chunk-BKIGPPVM.js +0 -629
  52. package/dist/chunk-BO2OKHIY.js +0 -6055
  53. package/dist/chunk-BU5ZAFMC.js +0 -115
  54. package/dist/chunk-BY3B7ZYV.cjs +0 -457
  55. package/dist/chunk-C2QHVHZF.js +0 -4066
  56. package/dist/chunk-C7BNX4XJ.js +0 -1043
  57. package/dist/chunk-CLYEIWA5.cjs +0 -408
  58. package/dist/chunk-CMYAWUX3.js +0 -4455
  59. package/dist/chunk-CN4NOESF.cjs +0 -416
  60. package/dist/chunk-CNVM7J3M.js +0 -883
  61. package/dist/chunk-CO2VM2DK.js +0 -1965
  62. package/dist/chunk-CQDOF3G7.cjs +0 -1404
  63. package/dist/chunk-DH5G2JUA.cjs +0 -614
  64. package/dist/chunk-DIEDKX5B.cjs +0 -660
  65. package/dist/chunk-DN7UFU63.cjs +0 -172
  66. package/dist/chunk-DXVCEFZB.js +0 -2027
  67. package/dist/chunk-EGIZHYJP.cjs +0 -85
  68. package/dist/chunk-EJA7G2C4.cjs +0 -428
  69. package/dist/chunk-ELLQPFAF.js +0 -830
  70. package/dist/chunk-EMO7HAKJ.cjs +0 -1875
  71. package/dist/chunk-ENV7K6XA.js +0 -282
  72. package/dist/chunk-EPWRXL6S.js +0 -2522
  73. package/dist/chunk-EUFLX2PI.js +0 -56956
  74. package/dist/chunk-F5LVGHNT.js +0 -449
  75. package/dist/chunk-FEFHPUEM.cjs +0 -6122
  76. package/dist/chunk-FF3Q7ADR.js +0 -380
  77. package/dist/chunk-GC3YU46J.js +0 -762
  78. package/dist/chunk-H6WMMLQK.cjs +0 -4492
  79. package/dist/chunk-H7XMORZI.js +0 -2731
  80. package/dist/chunk-HAN4V3PF.cjs +0 -2037
  81. package/dist/chunk-HBZYCASG.js +0 -4208
  82. package/dist/chunk-HF4OFY25.cjs +0 -4097
  83. package/dist/chunk-HHS6FMOU.cjs +0 -3813
  84. package/dist/chunk-HJJLD366.js +0 -1169
  85. package/dist/chunk-HKCVM6OK.cjs +0 -2237
  86. package/dist/chunk-HUFNKFA6.js +0 -698
  87. package/dist/chunk-I3XGTIHM.cjs +0 -1505
  88. package/dist/chunk-I6XZ5DZF.cjs +0 -488
  89. package/dist/chunk-IHOUYQIA.js +0 -406
  90. package/dist/chunk-ILRBGFVD.cjs +0 -72
  91. package/dist/chunk-KDB6BUMB.js +0 -3666
  92. package/dist/chunk-KUJRR4FJ.js +0 -657
  93. package/dist/chunk-KYM4XRFG.js +0 -421
  94. package/dist/chunk-L3Z2HIWJ.cjs +0 -793
  95. package/dist/chunk-LBPEZQAF.js +0 -2232
  96. package/dist/chunk-LER4WXW5.cjs +0 -286
  97. package/dist/chunk-LK5IAVH6.cjs +0 -1173
  98. package/dist/chunk-M6FU6S22.js +0 -2911
  99. package/dist/chunk-MWEFR6YQ.js +0 -1857
  100. package/dist/chunk-N5FTS757.cjs +0 -415
  101. package/dist/chunk-NCUHGRTZ.js +0 -752
  102. package/dist/chunk-NKRKT6V2.js +0 -69
  103. package/dist/chunk-NLPSZT4C.js +0 -630
  104. package/dist/chunk-NRUB55IT.cjs +0 -771
  105. package/dist/chunk-NTMZSDXM.cjs +0 -633
  106. package/dist/chunk-ODGMVILH.js +0 -9662
  107. package/dist/chunk-PBA6NXCT.cjs +0 -1216
  108. package/dist/chunk-PHENW4MQ.js +0 -65
  109. package/dist/chunk-PJMOXFPR.cjs +0 -1861
  110. package/dist/chunk-PLMYCCA4.js +0 -504
  111. package/dist/chunk-PPULB4GG.cjs +0 -9728
  112. package/dist/chunk-PQLGZKMC.cjs +0 -755
  113. package/dist/chunk-Q56TT7IL.js +0 -483
  114. package/dist/chunk-QHVVVN47.cjs +0 -2033
  115. package/dist/chunk-QWKUKVRE.js +0 -2026
  116. package/dist/chunk-RE3OKSYF.cjs +0 -424
  117. package/dist/chunk-RT7LJRSF.cjs +0 -57378
  118. package/dist/chunk-SPDELRRV.cjs +0 -319
  119. package/dist/chunk-SUCBB66F.js +0 -229
  120. package/dist/chunk-TSWTWZ42.cjs +0 -4214
  121. package/dist/chunk-UITWA6DV.cjs +0 -2829
  122. package/dist/chunk-UQW6SLM5.js +0 -172
  123. package/dist/chunk-V2ILLPHK.cjs +0 -237
  124. package/dist/chunk-V42NTCFH.js +0 -3645
  125. package/dist/chunk-VJ3L7CHT.cjs +0 -169
  126. package/dist/chunk-VJVCD5T5.cjs +0 -769
  127. package/dist/chunk-VK5AXKO3.js +0 -746
  128. package/dist/chunk-VSXOIUCF.cjs +0 -473
  129. package/dist/chunk-VZNKJZTT.cjs +0 -749
  130. package/dist/chunk-W76ETJTI.js +0 -678
  131. package/dist/chunk-WFJIDI2N.cjs +0 -424
  132. package/dist/chunk-WN3YF33G.cjs +0 -118
  133. package/dist/chunk-WUXIRGZP.cjs +0 -2915
  134. package/dist/chunk-WYH4GVZ5.js +0 -1488
  135. package/dist/chunk-X4YVN7H3.cjs +0 -888
  136. package/dist/chunk-X67XRI2T.js +0 -410
  137. package/dist/chunk-XDXZM3ZP.cjs +0 -1046
  138. package/dist/chunk-XH7SE4HH.cjs +0 -72
  139. package/dist/chunk-XNMEH2BI.js +0 -126
  140. package/dist/chunk-XSF76QRU.js +0 -468
  141. package/dist/chunk-XSUZMPVQ.cjs +0 -682
  142. package/dist/chunk-XUILI4KB.cjs +0 -430
  143. package/dist/chunk-Y5MUAYTO.js +0 -167
  144. package/dist/chunk-Y7VK5TH3.cjs +0 -129
  145. package/dist/chunk-YCMQQQ5U.cjs +0 -5244
  146. package/dist/chunk-YYXH45E2.js +0 -426
  147. package/dist/chunk-ZGTGVSTZ.js +0 -422
  148. package/dist/chunk-ZL6VJ6SN.js +0 -421
  149. package/dist/cli/holoscript-runner.cjs +0 -2258
  150. package/dist/cli/holoscript-runner.js +0 -2233
  151. package/dist/codebase/index.cjs +0 -336
  152. package/dist/codebase/index.js +0 -331
  153. package/dist/compiler/agent-inference.cjs +0 -29
  154. package/dist/compiler/agent-inference.js +0 -6
  155. package/dist/compiler/android-xr.cjs +0 -20
  156. package/dist/compiler/android-xr.js +0 -10
  157. package/dist/compiler/android.cjs +0 -21
  158. package/dist/compiler/android.js +0 -11
  159. package/dist/compiler/ar.cjs +0 -21
  160. package/dist/compiler/ar.js +0 -9
  161. package/dist/compiler/babylon.cjs +0 -18
  162. package/dist/compiler/babylon.js +0 -12
  163. package/dist/compiler/coco.cjs +0 -27
  164. package/dist/compiler/coco.js +0 -4
  165. package/dist/compiler/domain-block-utils.cjs +0 -595
  166. package/dist/compiler/domain-block-utils.js +0 -9
  167. package/dist/compiler/dtdl.cjs +0 -25
  168. package/dist/compiler/dtdl.js +0 -9
  169. package/dist/compiler/gltf-pipeline.cjs +0 -39
  170. package/dist/compiler/gltf-pipeline.js +0 -4
  171. package/dist/compiler/godot.cjs +0 -16
  172. package/dist/compiler/godot.js +0 -10
  173. package/dist/compiler/incremental.cjs +0 -30
  174. package/dist/compiler/incremental.js +0 -5
  175. package/dist/compiler/index.cjs +0 -1522
  176. package/dist/compiler/index.js +0 -1321
  177. package/dist/compiler/ios.cjs +0 -21
  178. package/dist/compiler/ios.js +0 -11
  179. package/dist/compiler/multi-layer.cjs +0 -27
  180. package/dist/compiler/multi-layer.js +0 -12
  181. package/dist/compiler/nodetoy.cjs +0 -23
  182. package/dist/compiler/nodetoy.js +0 -4
  183. package/dist/compiler/openxr.cjs +0 -16
  184. package/dist/compiler/openxr.js +0 -10
  185. package/dist/compiler/playcanvas.cjs +0 -17
  186. package/dist/compiler/playcanvas.js +0 -11
  187. package/dist/compiler/r3f.cjs +0 -35
  188. package/dist/compiler/r3f.js +0 -13
  189. package/dist/compiler/remotion.cjs +0 -23
  190. package/dist/compiler/remotion.js +0 -4
  191. package/dist/compiler/reproducibility.cjs +0 -39
  192. package/dist/compiler/reproducibility.js +0 -4
  193. package/dist/compiler/sdf.cjs +0 -22
  194. package/dist/compiler/sdf.js +0 -10
  195. package/dist/compiler/semantic-scene.cjs +0 -31
  196. package/dist/compiler/semantic-scene.js +0 -4
  197. package/dist/compiler/state.cjs +0 -18
  198. package/dist/compiler/state.js +0 -8
  199. package/dist/compiler/trait-composition.cjs +0 -27
  200. package/dist/compiler/trait-composition.js +0 -6
  201. package/dist/compiler/unity.cjs +0 -16
  202. package/dist/compiler/unity.js +0 -10
  203. package/dist/compiler/unreal.cjs +0 -20
  204. package/dist/compiler/unreal.js +0 -10
  205. package/dist/compiler/urdf.cjs +0 -46
  206. package/dist/compiler/urdf.js +0 -10
  207. package/dist/compiler/usd-physics.cjs +0 -24
  208. package/dist/compiler/usd-physics.js +0 -7
  209. package/dist/compiler/visionos.cjs +0 -16
  210. package/dist/compiler/visionos.js +0 -10
  211. package/dist/compiler/vrchat.cjs +0 -20
  212. package/dist/compiler/vrchat.js +0 -10
  213. package/dist/compiler/vrr.cjs +0 -22
  214. package/dist/compiler/vrr.js +0 -10
  215. package/dist/compiler/wasm.cjs +0 -34
  216. package/dist/compiler/wasm.js +0 -10
  217. package/dist/compiler/webgpu.cjs +0 -16
  218. package/dist/compiler/webgpu.js +0 -10
  219. package/dist/debugger.cjs +0 -21
  220. package/dist/debugger.js +0 -8
  221. package/dist/entries/interop.cjs +0 -62
  222. package/dist/entries/interop.js +0 -5
  223. package/dist/entries/scripting.cjs +0 -67
  224. package/dist/entries/scripting.js +0 -10
  225. package/dist/index.cjs +0 -61703
  226. package/dist/index.js +0 -58652
  227. package/dist/math/vec3.cjs +0 -57
  228. package/dist/math/vec3.js +0 -4
  229. package/dist/parser.cjs +0 -26
  230. package/dist/parser.js +0 -9
  231. package/dist/playwright-7DTEQCBD.cjs +0 -98673
  232. package/dist/playwright-BIZXMLD2.js +0 -98660
  233. package/dist/post-quantum-JTTAAGO3.cjs +0 -6
  234. package/dist/post-quantum-RVPVDEPI.js +0 -4
  235. package/dist/runtime.cjs +0 -16
  236. package/dist/runtime.js +0 -7
  237. package/dist/storage/index.cjs +0 -37
  238. package/dist/storage/index.js +0 -4
  239. package/dist/traits/index.cjs +0 -14331
  240. package/dist/traits/index.js +0 -12126
  241. package/dist/type-checker.cjs +0 -18
  242. package/dist/type-checker.js +0 -5
  243. package/dist/wot/index.cjs +0 -29
  244. package/dist/wot/index.js +0 -4
@@ -1,4066 +0,0 @@
1
- import { HoloScriptCodeParser } from './chunk-EPWRXL6S.js';
2
- import { mitosisHandler, orbitalHandler, WebSocketTransport } from './chunk-ENV7K6XA.js';
3
- import { logger } from './chunk-PHENW4MQ.js';
4
- import { __decorateClass } from './chunk-32TWR3HE.js';
5
- import { WebSocketServer, WebSocket } from 'ws';
6
- import { AttentionEngine, TimeManager } from '@holoscript/engine/orbital';
7
- import * as fs from 'fs';
8
- import * as path from 'path';
9
- import { stateMachineInterpreter } from '@holoscript/engine/runtime/StateMachineInterpreter';
10
- import { MemoryConsolidator } from '@holoscript/framework';
11
- import { BaseVoiceSynthesizer } from '@holoscript/engine/runtime/BaseVoiceSynthesizer';
12
- import { registerVoiceSynthesizer } from '@holoscript/engine/runtime/VoiceSynthesizer';
13
- import { LocalEmotionDetector } from '@holoscript/engine/runtime/LocalEmotionDetector';
14
- import { registerEmotionDetector } from '@holoscript/engine/runtime/EmotionDetector';
15
- import { MockSpeechRecognizer } from '@holoscript/engine/runtime/MockSpeechRecognizer';
16
- import { registerSpeechRecognizer } from '@holoscript/engine/runtime/SpeechRecognizer';
17
- import { MethodMemoize, ObjectPool } from '@holoscript/engine/runtime/RuntimeOptimization';
18
-
19
- // src/ReactiveState.ts
20
- var ReactiveState = class {
21
- constructor(initialState = {}) {
22
- this.subscribers = /* @__PURE__ */ new Set();
23
- this.state = { ...initialState };
24
- this.proxy = this.createReactiveProxy(this.state);
25
- }
26
- createReactiveProxy(target) {
27
- const self = this;
28
- return new Proxy(target, {
29
- get(obj, key) {
30
- const val = obj[key];
31
- if (val && typeof val === "object" && !Array.isArray(val)) {
32
- return self.createReactiveProxy(val);
33
- }
34
- return val;
35
- },
36
- set(obj, key, value) {
37
- const oldVal = obj[key];
38
- obj[key] = value;
39
- if (oldVal !== value) {
40
- self.notify();
41
- }
42
- return true;
43
- }
44
- });
45
- }
46
- get(key) {
47
- return this.proxy[key];
48
- }
49
- set(key, value) {
50
- this.proxy[key] = value;
51
- }
52
- has(key) {
53
- return this.proxy[key] !== void 0;
54
- }
55
- update(updates) {
56
- Object.assign(this.proxy, updates);
57
- }
58
- subscribe(callback) {
59
- this.subscribers.add(callback);
60
- return () => this.subscribers.delete(callback);
61
- }
62
- getSnapshot() {
63
- return { ...this.state };
64
- }
65
- getProxy() {
66
- return this.proxy;
67
- }
68
- notify() {
69
- this.subscribers.forEach((cb) => cb(this.getSnapshot()));
70
- }
71
- };
72
- var ExpressionEvaluator = class {
73
- constructor(context = {}) {
74
- this.context = context;
75
- }
76
- evaluate(expression) {
77
- if (typeof expression !== "string") return expression;
78
- const dangerousPatterns = [
79
- /\beval\s*\(/,
80
- /\brequire\s*\(/,
81
- /\bimport\s*\(/,
82
- /\bprocess\b/,
83
- /\bglobalThis?\b/,
84
- /\b__dirname\b/,
85
- /\b__filename\b/,
86
- /\bfs\b/,
87
- /\bchild_process\b/,
88
- // Prototype chain / constructor escape
89
- /\bconstructor\b/,
90
- /\b__proto__\b/,
91
- /\bprototype\b/,
92
- /\bObject\s*\.\s*(create|definePropert|getProto|assign|setProto)/,
93
- /\bReflect\b/,
94
- /\bProxy\b/,
95
- /\bFunction\b/,
96
- /\barguments\b/
97
- ];
98
- for (const pattern of dangerousPatterns) {
99
- if (pattern.test(expression)) {
100
- return void 0;
101
- }
102
- }
103
- if (expression.includes("${")) {
104
- const trimmed = expression.trim();
105
- const match = trimmed.match(/^\$\{([^}]+)\}$/);
106
- if (match) {
107
- return this.evaluate(match[1]);
108
- }
109
- return this.interpolate(expression);
110
- }
111
- const keys = Object.keys(this.context);
112
- const values = Object.values(this.context);
113
- try {
114
- const fn = new Function(...keys, `"use strict"; return (${expression});`);
115
- return fn.call(null, ...values);
116
- } catch (_e) {
117
- return expression;
118
- }
119
- }
120
- interpolate(str) {
121
- return str.replace(/\$\{([^}]+)\}/g, (_, expr) => {
122
- const val = this.evaluate(expr);
123
- return val !== void 0 ? String(val) : "";
124
- });
125
- }
126
- updateContext(updates) {
127
- Object.assign(this.context, updates);
128
- }
129
- setContext(context) {
130
- this.context = { ...context };
131
- }
132
- };
133
- function createState(initial = {}) {
134
- return new ReactiveState(initial);
135
- }
136
-
137
- // src/events/EventBus.ts
138
- var EventBus = class {
139
- constructor() {
140
- this.listeners = /* @__PURE__ */ new Map();
141
- this.history = [];
142
- this.maxHistory = 100;
143
- this.nextId = 0;
144
- this.paused = false;
145
- }
146
- /**
147
- * Subscribe to an event.
148
- */
149
- on(event, callback, priority = 0) {
150
- const id = this.nextId++;
151
- const list = this.listeners.get(event) || [];
152
- list.push({ callback, priority, once: false, id });
153
- list.sort((a, b) => b.priority - a.priority);
154
- this.listeners.set(event, list);
155
- return id;
156
- }
157
- /**
158
- * Subscribe to an event once (auto-removes after first fire).
159
- */
160
- once(event, callback, priority = 0) {
161
- const id = this.nextId++;
162
- const list = this.listeners.get(event) || [];
163
- list.push({ callback, priority, once: true, id });
164
- list.sort((a, b) => b.priority - a.priority);
165
- this.listeners.set(event, list);
166
- return id;
167
- }
168
- /**
169
- * Unsubscribe by listener ID.
170
- */
171
- off(listenerId) {
172
- for (const [event, list] of this.listeners) {
173
- const idx = list.findIndex((l) => l.id === listenerId);
174
- if (idx !== -1) {
175
- list.splice(idx, 1);
176
- return;
177
- }
178
- }
179
- }
180
- /**
181
- * Unsubscribe all listeners for an event.
182
- */
183
- offAll(event) {
184
- this.listeners.delete(event);
185
- }
186
- /**
187
- * Emit an event to all subscribers.
188
- */
189
- emit(event, data) {
190
- if (this.paused) return;
191
- this.history.push({ event, data, timestamp: Date.now() });
192
- if (this.history.length > this.maxHistory) this.history.shift();
193
- const list = this.listeners.get(event);
194
- if (list) {
195
- const toRemove = [];
196
- for (const listener of list) {
197
- listener.callback(data);
198
- if (listener.once) toRemove.push(listener.id);
199
- }
200
- for (const id of toRemove) {
201
- const idx = list.findIndex((l) => l.id === id);
202
- if (idx !== -1) list.splice(idx, 1);
203
- }
204
- }
205
- if (event !== "*") {
206
- const wildcardList = this.listeners.get("*");
207
- if (wildcardList) {
208
- for (const listener of wildcardList) {
209
- listener.callback({ event, data });
210
- }
211
- }
212
- }
213
- }
214
- /**
215
- * Get event history.
216
- */
217
- getHistory() {
218
- return [...this.history];
219
- }
220
- /**
221
- * Get listener count for an event.
222
- */
223
- listenerCount(event) {
224
- return this.listeners.get(event)?.length || 0;
225
- }
226
- /**
227
- * Pause/resume event emission.
228
- */
229
- setPaused(paused) {
230
- this.paused = paused;
231
- }
232
- /**
233
- * Clear all listeners and history.
234
- */
235
- clear() {
236
- this.listeners.clear();
237
- this.history = [];
238
- }
239
- };
240
- var sharedBus = null;
241
- function getSharedEventBus() {
242
- if (!sharedBus) sharedBus = new EventBus();
243
- return sharedBus;
244
- }
245
- function setSharedEventBus(bus) {
246
- sharedBus = bus;
247
- }
248
-
249
- // src/network/PriorityScorer.ts
250
- var PriorityScorer = class {
251
- /**
252
- * Scores a raw delta based on simulated heuristics returning a priority class.
253
- * Lower is more important.
254
- */
255
- static score(delta) {
256
- let basePriority = 50;
257
- if (delta.field === "x" || delta.field === "y" || delta.field === "z") {
258
- basePriority -= 40;
259
- }
260
- if (delta.field === "health" || delta.field === "status") {
261
- basePriority -= 50;
262
- }
263
- if (typeof delta.newValue === "string" && delta.newValue.length > 50) {
264
- basePriority += 30;
265
- }
266
- basePriority = Math.max(0, Math.min(100, basePriority));
267
- return {
268
- ...delta,
269
- priority: basePriority
270
- };
271
- }
272
- };
273
-
274
- // src/network/SpatialSharder.ts
275
- var SpatialSharder = class {
276
- /**
277
- * Maps an absolute position to a unique Shard ID string.
278
- */
279
- static getShardId(x, y, z) {
280
- const sx = Math.floor(x / this.SHARD_SIZE);
281
- const sy = Math.floor(y / this.SHARD_SIZE);
282
- const sz = Math.floor(z / this.SHARD_SIZE);
283
- return `shard_${sx}_${sy}_${sz}`;
284
- }
285
- /**
286
- * Calculates all overlapping shards for a given bounding sphere or interaction radius.
287
- */
288
- static getOverlappingShards(x, y, z, radius) {
289
- const shards = /* @__PURE__ */ new Set();
290
- const minX = Math.floor((x - radius) / this.SHARD_SIZE);
291
- const maxX = Math.floor((x + radius) / this.SHARD_SIZE);
292
- const minY = Math.floor((y - radius) / this.SHARD_SIZE);
293
- const maxY = Math.floor((y + radius) / this.SHARD_SIZE);
294
- const minZ = Math.floor((z - radius) / this.SHARD_SIZE);
295
- const maxZ = Math.floor((z + radius) / this.SHARD_SIZE);
296
- for (let ix = minX; ix <= maxX; ix++) {
297
- for (let iy = minY; iy <= maxY; iy++) {
298
- for (let iz = minZ; iz <= maxZ; iz++) {
299
- shards.add(`shard_${ix}_${iy}_${iz}`);
300
- }
301
- }
302
- }
303
- return Array.from(shards);
304
- }
305
- };
306
- SpatialSharder.SHARD_SIZE = 100;
307
- var TransactionLog = class {
308
- constructor(logPath) {
309
- this.writeQueue = [];
310
- this.isWriting = false;
311
- this.sequenceId = 0;
312
- this.logFile = logPath || path.resolve(process.cwd(), ".data", "state_transaction.wal");
313
- const dir = path.dirname(this.logFile);
314
- if (!fs.existsSync(dir)) {
315
- fs.mkdirSync(dir, { recursive: true });
316
- }
317
- }
318
- /**
319
- * Appends an active delta directly to the offline WAL buffer.
320
- */
321
- append(delta) {
322
- const stampedDelta = { ...delta, _seq: ++this.sequenceId };
323
- this.writeQueue.push(stampedDelta);
324
- this.flush();
325
- }
326
- async flush() {
327
- if (this.isWriting || this.writeQueue.length === 0) return;
328
- this.isWriting = true;
329
- const toWrite = this.writeQueue.splice(0, this.writeQueue.length);
330
- const dataStr = toWrite.map((d) => JSON.stringify(d)).join("\n") + "\n";
331
- try {
332
- await fs.promises.appendFile(this.logFile, dataStr, "utf-8");
333
- } catch (error) {
334
- this.writeQueue.unshift(...toWrite);
335
- } finally {
336
- this.isWriting = false;
337
- if (this.writeQueue.length > 0) {
338
- this.flush();
339
- }
340
- }
341
- }
342
- /**
343
- * Recover the state strictly from the raw disk array.
344
- */
345
- async recover() {
346
- if (!fs.existsSync(this.logFile)) {
347
- return [];
348
- }
349
- try {
350
- const data = await fs.promises.readFile(this.logFile, "utf-8");
351
- const lines = data.split("\n").filter((l) => l.trim().length > 0);
352
- const recoveredDeltas = lines.map((line) => {
353
- const parsed = JSON.parse(line);
354
- if (parsed._seq && parsed._seq > this.sequenceId) {
355
- this.sequenceId = parsed._seq;
356
- }
357
- return parsed;
358
- });
359
- return recoveredDeltas;
360
- } catch (error) {
361
- return [];
362
- }
363
- }
364
- async truncate() {
365
- if (fs.existsSync(this.logFile)) {
366
- await fs.promises.unlink(this.logFile);
367
- }
368
- this.sequenceId = 0;
369
- }
370
- };
371
-
372
- // src/network/StateSynchronizer.ts
373
- var StateSynchronizer = class _StateSynchronizer {
374
- constructor() {
375
- // Subscriber maps bound by entity ID (who is interested in what)
376
- this.globalSubscribers = /* @__PURE__ */ new Set();
377
- this.subscriberOptions = /* @__PURE__ */ new Map();
378
- this.entitySubscribers = /* @__PURE__ */ new Map();
379
- // Spatial culling position tracking
380
- this.entityPositions = /* @__PURE__ */ new Map();
381
- this.entityShards = /* @__PURE__ */ new Map();
382
- // Procedural Skill Syncer Mesh
383
- this.skillSubscribers = /* @__PURE__ */ new Set();
384
- // Adaptive Batching Metrics
385
- this.pendingBatch = [];
386
- this.batchTimer = null;
387
- this.currentBatchWindowMs = 50;
388
- // Persistent Storage (WAL)
389
- this.wal = new TransactionLog();
390
- // Active Transport Mesh
391
- this.transport = null;
392
- this.initializedMesh = false;
393
- }
394
- static getInstance() {
395
- if (!_StateSynchronizer.instance) {
396
- _StateSynchronizer.instance = new _StateSynchronizer();
397
- }
398
- return _StateSynchronizer.instance;
399
- }
400
- /**
401
- * Bootstraps the local synchronization node over WebSockets.
402
- */
403
- initializeMesh() {
404
- if (this.initializedMesh) return;
405
- this.initializedMesh = true;
406
- this.transport = new WebSocketTransport({
407
- roomId: "local_actor",
408
- serverUrl: "ws://127.0.0.1:8080"
409
- });
410
- this.transport.connect();
411
- this.transport.onMessage("state-sync", (msg) => {
412
- const payload = msg.payload;
413
- if (payload && payload.agent_updates && Array.isArray(payload.agent_updates)) {
414
- const inboundDeltas = [];
415
- for (const update of payload.agent_updates) {
416
- inboundDeltas.push({
417
- entityId: update.id,
418
- field: "x",
419
- newValue: update.x,
420
- oldValue: 0,
421
- timestamp: payload.timestamp
422
- });
423
- inboundDeltas.push({
424
- entityId: update.id,
425
- field: "y",
426
- newValue: update.y,
427
- oldValue: 0,
428
- timestamp: payload.timestamp
429
- });
430
- inboundDeltas.push({
431
- entityId: update.id,
432
- field: "z",
433
- newValue: update.z,
434
- oldValue: 0,
435
- timestamp: payload.timestamp
436
- });
437
- }
438
- if (inboundDeltas.length > 0) {
439
- this.dispatchToSubscribers(inboundDeltas);
440
- }
441
- }
442
- });
443
- }
444
- dispatchToSubscribers(deltas) {
445
- const publicDeltasToDispatch = deltas.filter((delta) => {
446
- const isPrivate = delta.field.includes("private_") || delta.field.includes("_secure");
447
- return !isPrivate;
448
- });
449
- this.globalSubscribers.forEach((sub) => {
450
- sub(publicDeltasToDispatch);
451
- });
452
- const entityGroups = /* @__PURE__ */ new Map();
453
- for (const delta of deltas) {
454
- let arr = entityGroups.get(delta.entityId);
455
- if (!arr) {
456
- arr = [];
457
- entityGroups.set(delta.entityId, arr);
458
- }
459
- arr.push(delta);
460
- }
461
- for (const [entityId, entityDeltas] of entityGroups.entries()) {
462
- const scopedListeners = this.entitySubscribers.get(entityId);
463
- if (scopedListeners) {
464
- scopedListeners.forEach((sub) => sub(entityDeltas));
465
- }
466
- }
467
- }
468
- /**
469
- * Enqueue a burst of pre-computed deltas. Rather than instant transmission,
470
- * they are loaded into an adaptive batch prioritized by the PriorityScorer.
471
- */
472
- broadcastDeltas(deltas) {
473
- if (deltas.length === 0) return;
474
- for (const delta of deltas) {
475
- this.pendingBatch.push(PriorityScorer.score(delta));
476
- }
477
- if (!this.batchTimer) {
478
- this.scheduleNextFlush();
479
- }
480
- }
481
- scheduleNextFlush() {
482
- if (this.pendingBatch.length > 500) {
483
- this.currentBatchWindowMs = Math.min(200, this.currentBatchWindowMs + 10);
484
- } else if (this.pendingBatch.length < 100) {
485
- this.currentBatchWindowMs = Math.max(10, this.currentBatchWindowMs - 10);
486
- }
487
- this.batchTimer = setTimeout(() => this.flushDeltas(), this.currentBatchWindowMs);
488
- }
489
- flushDeltas() {
490
- this.batchTimer = null;
491
- if (this.pendingBatch.length === 0) return;
492
- this.pendingBatch.sort((a, b) => a.priority - b.priority);
493
- const deltasToDispatch = this.pendingBatch.splice(0, this.pendingBatch.length);
494
- for (const delta of deltasToDispatch) {
495
- if (delta.field === "x" || delta.field === "y" || delta.field === "z") {
496
- let pos = this.entityPositions.get(delta.entityId);
497
- if (!pos) {
498
- pos = { x: 0, y: 0, z: 0 };
499
- this.entityPositions.set(delta.entityId, pos);
500
- }
501
- pos[delta.field] = delta.newValue;
502
- this.entityShards.set(delta.entityId, SpatialSharder.getShardId(pos.x, pos.y, pos.z));
503
- }
504
- this.wal.append(delta);
505
- }
506
- if (this.transport) {
507
- this.transport.sendMessage({
508
- type: "state-sync",
509
- payload: {
510
- deltas: deltasToDispatch.map((d) => ({
511
- id: d.entityId,
512
- field: d.field,
513
- value: d.newValue,
514
- time: d.timestamp
515
- }))
516
- }
517
- });
518
- }
519
- const publicDeltasToDispatch = deltasToDispatch.filter((delta) => {
520
- const isPrivate = delta.field.includes("private_") || delta.field.includes("_secure");
521
- return !isPrivate;
522
- });
523
- this.globalSubscribers.forEach((sub) => {
524
- const options = this.subscriberOptions.get(sub);
525
- if (!options || !options.position || !options.interactionRadius) {
526
- if (publicDeltasToDispatch.length > 0) sub(publicDeltasToDispatch);
527
- return;
528
- }
529
- const targetShards = new Set(
530
- SpatialSharder.getOverlappingShards(
531
- options.position.x,
532
- options.position.y,
533
- options.position.z,
534
- options.interactionRadius
535
- )
536
- );
537
- const culledDeltas = publicDeltasToDispatch.filter((delta) => {
538
- const entityPos = this.entityPositions.get(delta.entityId);
539
- if (!entityPos) return true;
540
- const entityShard = this.entityShards.get(delta.entityId);
541
- if (entityShard && !targetShards.has(entityShard)) {
542
- return false;
543
- }
544
- const dx = entityPos.x - options.position.x;
545
- const dy = entityPos.y - options.position.y;
546
- const dz = entityPos.z - options.position.z;
547
- const distSq = dx * dx + dy * dy + dz * dz;
548
- const r = options.interactionRadius;
549
- return distSq <= r * r;
550
- });
551
- if (culledDeltas.length > 0) {
552
- sub(culledDeltas);
553
- }
554
- });
555
- const entityGroups = /* @__PURE__ */ new Map();
556
- for (const delta of deltasToDispatch) {
557
- let arr = entityGroups.get(delta.entityId);
558
- if (!arr) {
559
- arr = [];
560
- entityGroups.set(delta.entityId, arr);
561
- }
562
- arr.push(delta);
563
- }
564
- for (const [entityId, entityDeltas] of entityGroups.entries()) {
565
- const scopedListeners = this.entitySubscribers.get(entityId);
566
- if (scopedListeners) {
567
- scopedListeners.forEach((sub) => sub(entityDeltas));
568
- }
569
- }
570
- if (this.pendingBatch.length > 0) {
571
- this.scheduleNextFlush();
572
- }
573
- }
574
- /**
575
- * Subscribe to all global state deltas (e.g. Server sync bridges).
576
- */
577
- subscribeGlobal(callback, options) {
578
- this.globalSubscribers.add(callback);
579
- if (options) {
580
- this.subscriberOptions.set(callback, options);
581
- }
582
- return () => {
583
- this.globalSubscribers.delete(callback);
584
- this.subscriberOptions.delete(callback);
585
- };
586
- }
587
- /**
588
- * Subscribe to targeted changes restricted strictly to a specific Entity.
589
- */
590
- subscribeEntity(entityId, callback) {
591
- let scopedListeners = this.entitySubscribers.get(entityId);
592
- if (!scopedListeners) {
593
- scopedListeners = /* @__PURE__ */ new Set();
594
- this.entitySubscribers.set(entityId, scopedListeners);
595
- }
596
- scopedListeners.add(callback);
597
- return () => {
598
- const listeners = this.entitySubscribers.get(entityId);
599
- if (listeners) {
600
- listeners.delete(callback);
601
- if (listeners.size === 0) {
602
- this.entitySubscribers.delete(entityId);
603
- }
604
- }
605
- };
606
- }
607
- /**
608
- * Broadcast a procedural skill mutation recursively so all agents merge success rates.
609
- */
610
- broadcastSkill(skill) {
611
- this.skillSubscribers.forEach((sub) => sub(skill));
612
- }
613
- /**
614
- * Listen globally for procedurally acquired skills bouncing across the instance.
615
- */
616
- subscribeSkills(callback) {
617
- this.skillSubscribers.add(callback);
618
- return () => this.skillSubscribers.delete(callback);
619
- }
620
- /**
621
- * Recovery API reading `.wal` states sequentially mapping offline CRDT histories completely locally.
622
- */
623
- async recoverFromLog() {
624
- const deltas = await this.wal.recover();
625
- if (deltas.length > 0) {
626
- for (const d of deltas) {
627
- if (d.field === "x" || d.field === "y" || d.field === "z") {
628
- let pos = this.entityPositions.get(d.entityId);
629
- if (!pos) {
630
- pos = { x: 0, y: 0, z: 0 };
631
- this.entityPositions.set(d.entityId, pos);
632
- }
633
- pos[d.field] = d.newValue;
634
- }
635
- }
636
- }
637
- return deltas;
638
- }
639
- async clearLog() {
640
- await this.wal.truncate();
641
- }
642
- };
643
-
644
- // src/monitoring/telemetry.ts
645
- var TelemetryRegistry = class {
646
- constructor() {
647
- this.measurements = [];
648
- this.maxHistory = 1e4;
649
- }
650
- /**
651
- * Increments a monotonic counter (e.g., total_nodes_executed)
652
- */
653
- incrementCounter(name, value = 1, labels) {
654
- this.measurements.push({
655
- name,
656
- type: "counter",
657
- value,
658
- labels,
659
- timestamp: Date.now()
660
- });
661
- if (this.measurements.length > this.maxHistory) this.measurements.shift();
662
- }
663
- /**
664
- * Records an instantaneous value (e.g., active_agents)
665
- */
666
- setGauge(name, value, labels) {
667
- this.measurements.push({
668
- name,
669
- type: "gauge",
670
- value,
671
- labels,
672
- timestamp: Date.now()
673
- });
674
- if (this.measurements.length > this.maxHistory) this.measurements.shift();
675
- }
676
- /**
677
- * Wraps an async function and records its execution latency into a histogram.
678
- */
679
- async measureLatency(name, fn, labels) {
680
- const start = performance.now();
681
- try {
682
- return await fn();
683
- } finally {
684
- const duration = performance.now() - start;
685
- this.measurements.push({
686
- name,
687
- type: "histogram",
688
- value: duration,
689
- labels,
690
- timestamp: Date.now()
691
- });
692
- if (this.measurements.length > this.maxHistory) this.measurements.shift();
693
- if (duration > 500) {
694
- this.measurements.push({
695
- name: "slo_violation_count",
696
- type: "counter",
697
- value: 1,
698
- labels: { ...labels, metric_name: name, threshold: "500ms" },
699
- timestamp: Date.now()
700
- });
701
- }
702
- }
703
- }
704
- /**
705
- * Snapshots current aggregations for dashboard export.
706
- */
707
- getSnapshot() {
708
- const snapshot = { counters: {}, histograms: {}, gauges: {} };
709
- const histAggregations = {};
710
- for (const m of this.measurements) {
711
- const key = m.labels ? `${m.name}{${JSON.stringify(m.labels)}}` : m.name;
712
- if (m.type === "counter") {
713
- snapshot.counters[key] = (snapshot.counters[key] || 0) + m.value;
714
- } else if (m.type === "gauge") {
715
- snapshot.gauges[key] = m.value;
716
- } else if (m.type === "histogram") {
717
- if (!histAggregations[key]) histAggregations[key] = { count: 0, sum: 0, max: 0 };
718
- histAggregations[key].count++;
719
- histAggregations[key].sum += m.value;
720
- if (m.value > histAggregations[key].max) histAggregations[key].max = m.value;
721
- }
722
- }
723
- for (const [key, agg] of Object.entries(histAggregations)) {
724
- snapshot.histograms[key] = {
725
- count: agg.count,
726
- sum: agg.sum,
727
- avg: agg.count > 0 ? agg.sum / agg.count : 0,
728
- max: agg.max
729
- };
730
- }
731
- return snapshot;
732
- }
733
- };
734
- var telemetry = new TelemetryRegistry();
735
- var HoloScriptAgentRuntime = class {
736
- /**
737
- * Creates a new HoloScript agent runtime instance.
738
- *
739
- * @param agentNode - The OrbNode representing the agent template
740
- * @param parentRuntime - The parent runtime providing global context
741
- *
742
- * @example
743
- * ```typescript
744
- * const runtime = new HoloScriptAgentRuntime(miningAgentNode, mainRuntime);
745
- * ```
746
- */
747
- constructor(agentNode, parentRuntime) {
748
- this.runningActions = /* @__PURE__ */ new Map();
749
- this.isDestroyed = false;
750
- // Episodic Memory & Semantic Extraction (Phase 7)
751
- this.rawEpisodes = [];
752
- this.semanticFacts = [];
753
- this.consolidationInterval = null;
754
- if (!agentNode || !parentRuntime) {
755
- return;
756
- }
757
- this.agentNode = agentNode;
758
- this.parentRuntime = parentRuntime;
759
- this.localState = new ReactiveState(agentNode.properties || {});
760
- this.initializeAgentContext();
761
- }
762
- /**
763
- * Reset the runtime for pooling reuse with new agent configuration.
764
- *
765
- * @param agentNode - New agent node to bind to this runtime
766
- * @param parentRuntime - Parent runtime for global context
767
- */
768
- reset(agentNode, parentRuntime) {
769
- this.agentNode = agentNode;
770
- this.parentRuntime = parentRuntime;
771
- this.localState = new ReactiveState(agentNode.properties || {});
772
- this.runningActions.clear();
773
- this.isDestroyed = false;
774
- this.initializeAgentContext();
775
- }
776
- /**
777
- * Initialize the agent's execution context and memory consolidation.
778
- */
779
- initializeAgentContext() {
780
- ({
781
- id: this.agentNode.id || this.agentNode.name,
782
- type: this.agentNode.type,
783
- state: this.localState.getSnapshot(),
784
- properties: this.agentNode.properties});
785
- if (!this.consolidationInterval) {
786
- this.consolidationInterval = setInterval(() => this.consolidateMemory(), 3e4);
787
- }
788
- }
789
- /**
790
- * Records a raw episodic event into the agent's short-term history queue.
791
- *
792
- * @param action - The action that was performed
793
- * @param outcome - The result or outcome of the action
794
- * @param entitiesInvolved - List of entity IDs that were involved in the episode
795
- *
796
- * @example
797
- * ```typescript
798
- * agentRuntime.recordEpisode('mine_ore', 'collected 5 iron ore', ['ore_deposit_1', 'inventory']);
799
- * ```
800
- */
801
- recordEpisode(action, outcome, entitiesInvolved) {
802
- this.rawEpisodes.push({
803
- id: `ep_${Date.now()}_${Math.random().toString(36).substring(7)}`,
804
- timestamp: Date.now(),
805
- action,
806
- outcome,
807
- entitiesInvolved
808
- });
809
- }
810
- /**
811
- * Internal idle tick leveraging the MemoryConsolidator subsystem to offload processing constraints.
812
- */
813
- consolidateMemory() {
814
- if (this.isDestroyed || this.rawEpisodes.length < 5) return;
815
- const { newFacts, prunedEpisodes } = MemoryConsolidator.compressEpisodes(this.rawEpisodes);
816
- if (newFacts.length > 0) {
817
- this.semanticFacts.push(...newFacts);
818
- this.rawEpisodes = this.rawEpisodes.filter((e) => !prunedEpisodes.includes(e.id));
819
- }
820
- }
821
- /**
822
- * Execute an action (method) defined on the agent template.
823
- *
824
- * @param actionName - Name of the action/method to execute
825
- * @param args - Arguments to pass to the action method
826
- * @returns Promise resolving to execution result
827
- * @throws {Error} When agent is destroyed or action execution fails
828
- *
829
- * @example
830
- * ```typescript
831
- * const result = await agentRuntime.executeAction('patrol', ['north_sector']);
832
- * if (result.success) {
833
- * console.log('Patrol completed:', result.output);
834
- * }
835
- * ```
836
- */
837
- async executeAction(actionName, args = []) {
838
- if (this.isDestroyed) return { success: false, error: "Agent destroyed" };
839
- const directives = this.agentNode.directives;
840
- const action = directives?.find((d) => d.type === "method" && d.name === actionName);
841
- if (!action) {
842
- return this.parentRuntime.callFunction(actionName, args);
843
- }
844
- logger.info(`[Agent:${this.agentNode.name}] Executing action: ${actionName}`);
845
- const agentScope = {
846
- variables: /* @__PURE__ */ new Map(),
847
- parent: this.parentRuntime.getRootScope()
848
- };
849
- const agentData = this.parentRuntime.getVariable(this.agentNode.name);
850
- if (agentData && !agentData.state) {
851
- agentData.state = this.localState.getProxy();
852
- }
853
- agentScope.variables.set(
854
- "this",
855
- agentData || {
856
- id: this.agentNode.name,
857
- state: this.localState.getProxy(),
858
- properties: this.agentNode.properties
859
- }
860
- );
861
- if (action.parameters && args) {
862
- action.parameters.forEach((param, i) => {
863
- agentScope.variables.set(param.name, args[i]);
864
- });
865
- }
866
- try {
867
- if (Array.isArray(action.body)) {
868
- const results = await this.parentRuntime.executeHoloProgram(action.body, agentScope);
869
- const success = results.every((r) => r.success);
870
- return {
871
- success,
872
- output: results[results.length - 1]?.output,
873
- error: results.find((r) => !r.success)?.error
874
- };
875
- } else {
876
- const results = await this.parentRuntime.executeProgram(action.body, 1);
877
- const success = results.every((r) => r.success);
878
- return {
879
- success,
880
- output: results[results.length - 1]?.output,
881
- // @ts-expect-error During migration
882
- error: results.find((r) => !r.success)?.error
883
- };
884
- }
885
- } finally {
886
- this.runningActions.delete(actionName);
887
- }
888
- }
889
- /**
890
- * Autonomous 'thinking' cycle using LLM for decision making.
891
- *
892
- * @param prompt - Optional specific prompt for the LLM, defaults to general decision prompt
893
- * @returns Promise resolving to the LLM's decision as a string
894
- *
895
- * @example
896
- * ```typescript
897
- * const decision = await agentRuntime.think('Should I retreat or continue attacking?');
898
- * console.log('Agent decision:', decision);
899
- * ```
900
- */
901
- async think(prompt) {
902
- logger.info(`[Agent:${this.agentNode.name}] Thinking...`);
903
- const result = await this.parentRuntime.emit("agent_think", {
904
- agentId: this.agentNode.name,
905
- context: this.localState.getSnapshot(),
906
- prompt: prompt || "Decide the next best action based on current state."
907
- });
908
- return result?.decision || "No clear decision made.";
909
- }
910
- /**
911
- * Handle lifecycle events for this specific agent.
912
- *
913
- * @param eventType - The type of event being handled
914
- * @param data - Event data to bind to the execution scope
915
- *
916
- * @example
917
- * ```typescript
918
- * await agentRuntime.onEvent('enemy_spotted', {
919
- * enemy: 'orc_warrior',
920
- * distance: 50
921
- * });
922
- * ```
923
- */
924
- async onEvent(eventType, data) {
925
- if (this.isDestroyed) return;
926
- const directives = this.agentNode.directives;
927
- const handler = directives?.find((d) => d.type === "lifecycle" && d.hook === eventType);
928
- if (handler) {
929
- const eventScope = {
930
- variables: /* @__PURE__ */ new Map(),
931
- parent: this.parentRuntime.getRootScope()
932
- };
933
- if (data && typeof data === "object") {
934
- for (const [key, val] of Object.entries(data)) {
935
- eventScope.variables.set(key, val);
936
- }
937
- }
938
- eventScope.variables.set("eventData", data);
939
- directives?.forEach((d) => {
940
- if (d.type === "method" && d.name) {
941
- eventScope.variables.set(d.name, ((...args) => this.executeAction(d.name, args)));
942
- }
943
- });
944
- const params = handler.parameters;
945
- if (params && Array.isArray(params) && data && typeof data === "object") {
946
- const dataRecord = data;
947
- params.forEach((param) => {
948
- if (dataRecord[param.name] !== void 0) {
949
- eventScope.variables.set(param.name, dataRecord[param.name]);
950
- }
951
- });
952
- }
953
- const agentData = this.parentRuntime.getVariable(this.agentNode.name);
954
- if (agentData && !agentData.state) {
955
- agentData.state = this.localState.getProxy();
956
- }
957
- eventScope.variables.set(
958
- "this",
959
- agentData || {
960
- id: this.agentNode.name,
961
- state: this.localState.getProxy(),
962
- properties: this.agentNode.properties
963
- }
964
- );
965
- try {
966
- if (Array.isArray(handler.body)) {
967
- await this.parentRuntime.executeHoloProgram(handler.body, eventScope);
968
- } else {
969
- this.parentRuntime.evaluateExpression(handler.body);
970
- }
971
- } finally {
972
- }
973
- }
974
- }
975
- /**
976
- * Clean up the agent runtime, stopping all running processes and timers.
977
- */
978
- destroy() {
979
- this.isDestroyed = true;
980
- this.runningActions.clear();
981
- if (this.consolidationInterval) {
982
- clearInterval(this.consolidationInterval);
983
- this.consolidationInterval = null;
984
- }
985
- logger.info(`[Agent:${this.agentNode.name}] Runtime destroyed.`);
986
- }
987
- /**
988
- * Get the agent's unique identifier.
989
- *
990
- * @returns The agent's ID or name
991
- */
992
- get id() {
993
- return this.agentNode.id || this.agentNode.name;
994
- }
995
- /**
996
- * Get the agent's current reactive state proxy.
997
- *
998
- * @returns Proxy object for the agent's state
999
- */
1000
- get state() {
1001
- return this.localState.getProxy();
1002
- }
1003
- /**
1004
- * Get the agent's current reactive state proxy.
1005
- *
1006
- * @returns Proxy object for the agent's state
1007
- */
1008
- getState() {
1009
- return this.localState.getProxy();
1010
- }
1011
- };
1012
-
1013
- // src/extensions/ExtensionRegistry.ts
1014
- var ExtensionRegistry = class {
1015
- constructor(runtime) {
1016
- this.extensions = /* @__PURE__ */ new Map();
1017
- this.runtime = runtime;
1018
- }
1019
- /**
1020
- * Load an extension into the runtime
1021
- */
1022
- loadExtension(extension) {
1023
- if (this.extensions.has(extension.id)) {
1024
- logger.warn(`Extension ${extension.id} is already loaded.`);
1025
- return;
1026
- }
1027
- const context = {
1028
- registerTrait: (name, handler) => {
1029
- logger.info(`[Extension:${extension.id}] Registering trait: ${name}`);
1030
- this.runtime.registerTrait(name, handler);
1031
- },
1032
- registerFunction: (name, fn) => {
1033
- logger.info(`[Extension:${extension.id}] Registering function: ${name}`);
1034
- this.runtime.registerGlobalFunction(name, fn);
1035
- },
1036
- logger
1037
- };
1038
- try {
1039
- extension.onLoad(context);
1040
- this.extensions.set(extension.id, extension);
1041
- logger.info(`Extension loaded: ${extension.id} v${extension.version}`);
1042
- } catch (error) {
1043
- logger.error(`Failed to load extension ${extension.id}:`, {
1044
- error: error instanceof Error ? error.message : String(error)
1045
- });
1046
- throw error;
1047
- }
1048
- }
1049
- /**
1050
- * Unload an extension
1051
- */
1052
- unloadingExtension(id) {
1053
- const extension = this.extensions.get(id);
1054
- if (!extension) return;
1055
- try {
1056
- const context = {
1057
- registerTrait: () => {
1058
- },
1059
- registerFunction: () => {
1060
- },
1061
- logger
1062
- };
1063
- extension.onUnload(context);
1064
- } catch (e) {
1065
- logger.error(`Error unloading extension ${id}`, {
1066
- error: e instanceof Error ? e.message : String(e)
1067
- });
1068
- }
1069
- this.extensions.delete(id);
1070
- logger.info(`Extension unloaded: ${id}`);
1071
- }
1072
- getExtension(id) {
1073
- return this.extensions.get(id);
1074
- }
1075
- };
1076
- var RUNTIME_SECURITY_LIMITS = {
1077
- maxExecutionDepth: 50,
1078
- maxTotalNodes: 1e3,
1079
- maxExecutionTimeMs: 5e3,
1080
- maxParticlesPerSystem: 1e3,
1081
- maxCallStackDepth: 100
1082
- };
1083
- function isOrbData(v) {
1084
- return v !== null && typeof v === "object" && v.__type === "orb";
1085
- }
1086
- var HoloScriptRuntime = class {
1087
- constructor(_importLoader, customFunctions) {
1088
- this.particleSystems = /* @__PURE__ */ new Map();
1089
- this.executionHistory = [];
1090
- this.agentRuntimes = /* @__PURE__ */ new Map();
1091
- this.startTime = 0;
1092
- this.nodeCount = 0;
1093
- this.callStack = [];
1094
- this.eventHandlers = /* @__PURE__ */ new Map();
1095
- this.animations = /* @__PURE__ */ new Map();
1096
- this.uiElements = /* @__PURE__ */ new Map();
1097
- this.proceduralSkills = /* @__PURE__ */ new Map();
1098
- this.traitHandlers = /* @__PURE__ */ new Map();
1099
- this.context = this.createEmptyContext();
1100
- this.currentScope = { variables: this.context.variables };
1101
- this.builtinFunctions = this.initBuiltins(customFunctions);
1102
- this.agentPool = new ObjectPool(
1103
- () => new HoloScriptAgentRuntime(),
1104
- // Preallocation mode (optional args)
1105
- (agent) => agent.destroy(),
1106
- 50
1107
- );
1108
- registerVoiceSynthesizer("default", new BaseVoiceSynthesizer());
1109
- registerEmotionDetector("default", new LocalEmotionDetector());
1110
- registerSpeechRecognizer("default", new MockSpeechRecognizer());
1111
- for (const [name, fn] of this.builtinFunctions) {
1112
- this.context.functions.set(name, ((...spreadArgs) => fn(spreadArgs)));
1113
- }
1114
- this.registerFunction("get_attended_entities", (args) => {
1115
- const topK = typeof args[0] === "number" ? args[0] : 10;
1116
- const selfRaw = this.context.variables.get("self");
1117
- const selfNode = isOrbData(selfRaw) ? selfRaw : void 0;
1118
- const observerPos = selfNode?.position ?? { x: 0, y: 0, z: 0 };
1119
- const entities = [];
1120
- this.context.spatialMemory.forEach((pos, id) => {
1121
- if (id !== selfNode?.name) {
1122
- const entityRaw = this.context.variables.get(id);
1123
- const entityOrb = isOrbData(entityRaw) ? entityRaw : void 0;
1124
- entities.push({
1125
- id,
1126
- position: pos,
1127
- velocity: entityOrb?.velocity,
1128
- saliencyBase: typeof entityOrb?.saliency === "number" ? entityOrb.saliency : void 0
1129
- });
1130
- }
1131
- });
1132
- return AttentionEngine.getTopKEntities(observerPos, entities, topK);
1133
- });
1134
- this.traitHandlers.set("mitosis", mitosisHandler);
1135
- this.traitHandlers.set("orbital", orbitalHandler);
1136
- this.extensionRegistry = new ExtensionRegistry(this);
1137
- stateMachineInterpreter.setHookExecutor(
1138
- (code, context) => {
1139
- for (const [key, value] of Object.entries(context)) {
1140
- this.context.variables.set(key, value);
1141
- }
1142
- return this.evaluateExpression(code);
1143
- }
1144
- );
1145
- }
1146
- /**
1147
- * Initialize built-in functions
1148
- */
1149
- initBuiltins(customFunctions) {
1150
- const builtins = /* @__PURE__ */ new Map();
1151
- if (customFunctions) {
1152
- for (const [name, func] of Object.entries(customFunctions)) {
1153
- builtins.set(name, func);
1154
- }
1155
- }
1156
- builtins.set("show", (args) => {
1157
- const target = String(args[0]);
1158
- const element = this.uiElements.get(target);
1159
- if (element) element.visible = true;
1160
- const hologram = this.context.hologramState.get(target);
1161
- if (hologram) {
1162
- this.createParticleEffect(`${target}_show`, { x: 0, y: 0, z: 0 }, hologram.color, 15);
1163
- }
1164
- logger.info("show", { target });
1165
- return { shown: target };
1166
- });
1167
- builtins.set("hide", (args) => {
1168
- const target = String(args[0]);
1169
- const element = this.uiElements.get(target);
1170
- if (element) element.visible = false;
1171
- logger.info("hide", { target });
1172
- return { hidden: target };
1173
- });
1174
- builtins.set("pulsate", (args) => {
1175
- const target = String(args[0]);
1176
- const options = args[1] || {};
1177
- const duration = Number(options.duration) || 1e3;
1178
- const color = String(options.color || "#ffffff");
1179
- const position = this.context.spatialMemory.get(target) || { x: 0, y: 0, z: 0 };
1180
- this.createParticleEffect(`${target}_pulse`, position, color, 30);
1181
- return { pulsing: target, duration };
1182
- });
1183
- builtins.set("animate", (args) => {
1184
- const target = String(args[0]);
1185
- const options = args[1] || {};
1186
- const animation = {
1187
- target,
1188
- property: String(options.property || "position.y"),
1189
- from: Number(options.from || 0),
1190
- to: Number(options.to || 1),
1191
- duration: Number(options.duration || 1e3),
1192
- startTime: Date.now(),
1193
- easing: String(options.easing || "linear"),
1194
- loop: Boolean(options.loop),
1195
- yoyo: Boolean(options.yoyo)
1196
- };
1197
- this.animations.set(`${target}_${animation.property}`, animation);
1198
- return { animating: target, animation };
1199
- });
1200
- builtins.set("spawn", async (args) => {
1201
- const config = args[0];
1202
- if (typeof config === "string") {
1203
- const target = config;
1204
- const position2 = args[1] || { x: 0, y: 0, z: 0 };
1205
- this.context.spatialMemory.set(target, position2);
1206
- this.createParticleEffect(`${target}_spawn`, position2, "#00ff00", 25);
1207
- return { spawned: target, at: position2 };
1208
- }
1209
- const spawnConfig = config;
1210
- const templateName = String(spawnConfig.template);
1211
- const id = String(spawnConfig.id || `${templateName}_${Date.now()}`);
1212
- const position = spawnConfig.position || { x: 0, y: 0, z: 0 };
1213
- const template = this.context.templates.get(templateName);
1214
- if (!template) {
1215
- logger.error(`[Mitosis] Template ${templateName} not found`);
1216
- return { error: `Template ${templateName} not found` };
1217
- }
1218
- const spawnNode = {
1219
- type: "orb",
1220
- name: id,
1221
- position,
1222
- properties: { ...spawnConfig.config || {} },
1223
- // Initial state from config
1224
- children: template.children,
1225
- traits: template.traits,
1226
- directives: template.directives
1227
- };
1228
- const holoTpl = template;
1229
- if (holoTpl.state) {
1230
- for (const prop of holoTpl.state.properties) {
1231
- if (spawnNode.properties[prop.key] === void 0) {
1232
- spawnNode.properties[prop.key] = this.resolveHoloValue(prop.value);
1233
- }
1234
- }
1235
- }
1236
- for (const prop of holoTpl.properties) {
1237
- if (spawnNode.properties[prop.key] === void 0) {
1238
- spawnNode.properties[prop.key] = this.resolveHoloValue(prop.value);
1239
- }
1240
- }
1241
- await this.executeOrb(spawnNode);
1242
- if (spawnConfig.parentId || spawnConfig.parent_id) {
1243
- const parentId = String(spawnConfig.parentId || spawnConfig.parent_id);
1244
- await this.emit(`mitosis_spawned`, { parentId, childId: id });
1245
- await this.emit(`${parentId}.mitosis_spawned`, { childId: id });
1246
- }
1247
- return { spawned: id, template: templateName };
1248
- });
1249
- builtins.set("notifyParent", async (args) => {
1250
- const parentId = String(args[0]);
1251
- const data = args[1];
1252
- await this.emit(`mitosis_child_complete`, {
1253
- parentId,
1254
- childId: args[2] || "unknown",
1255
- result: data
1256
- });
1257
- await this.emit(`${parentId}.mitosis_child_complete`, {
1258
- childId: args[2] || "unknown",
1259
- result: data
1260
- });
1261
- return { notified: parentId };
1262
- });
1263
- builtins.set("despawn", (args) => {
1264
- const target = String(args[0]);
1265
- if (this.context.hologramState.has(target)) {
1266
- const pos = this.context.spatialMemory.get(target) || { x: 0, y: 0, z: 0 };
1267
- this.createParticleEffect(`${target}_despawn`, pos, "#ff0000", 30);
1268
- this.context.hologramState.delete(target);
1269
- this.context.variables.delete(target);
1270
- this.context.spatialMemory.delete(target);
1271
- logger.info("despawn", { target });
1272
- return { despawned: target };
1273
- }
1274
- return { msg: "Target not found", target };
1275
- });
1276
- builtins.set("move", (args) => {
1277
- const target = String(args[0]);
1278
- const position = args[1] || { x: 0, y: 0, z: 0 };
1279
- const current = this.context.spatialMemory.get(target);
1280
- if (current) {
1281
- this.context.spatialMemory.set(target, position);
1282
- this.createConnectionStream(target, `${target}_dest`, current, position, "move");
1283
- }
1284
- return { moved: target, to: position };
1285
- });
1286
- builtins.set("set", (args) => {
1287
- const target = String(args[0]);
1288
- const value = args[1];
1289
- this.setVariable(target, value);
1290
- return { set: target, value };
1291
- });
1292
- builtins.set("get", (args) => {
1293
- const target = String(args[0]);
1294
- return this.getVariable(target);
1295
- });
1296
- builtins.set("add", (args) => Number(args[0]) + Number(args[1]));
1297
- builtins.set("subtract", (args) => Number(args[0]) - Number(args[1]));
1298
- builtins.set("multiply", (args) => Number(args[0]) * Number(args[1]));
1299
- builtins.set(
1300
- "divide",
1301
- (args) => Number(args[1]) !== 0 ? Number(args[0]) / Number(args[1]) : 0
1302
- );
1303
- builtins.set("mod", (args) => Number(args[0]) % Number(args[1]));
1304
- builtins.set("abs", (args) => Math.abs(Number(args[0])));
1305
- builtins.set("floor", (args) => Math.floor(Number(args[0])));
1306
- builtins.set("ceil", (args) => Math.ceil(Number(args[0])));
1307
- builtins.set("round", (args) => Math.round(Number(args[0])));
1308
- builtins.set("min", (args) => Math.min(...args.map(Number)));
1309
- builtins.set("max", (args) => Math.max(...args.map(Number)));
1310
- builtins.set("random", () => Math.random());
1311
- builtins.set("concat", (args) => args.map(String).join(""));
1312
- builtins.set("length", (args) => {
1313
- const val = args[0];
1314
- if (typeof val === "string") return val.length;
1315
- if (Array.isArray(val)) return val.length;
1316
- return 0;
1317
- });
1318
- builtins.set(
1319
- "substring",
1320
- (args) => String(args[0]).substring(Number(args[1]), Number(args[2]))
1321
- );
1322
- builtins.set("wait", async (args) => {
1323
- const ms = Number(args[0]) || 0;
1324
- await new Promise((resolve2) => setTimeout(resolve2, ms));
1325
- return { waited: ms };
1326
- });
1327
- builtins.set("print", (args) => {
1328
- console.log(`[HoloScript]`, ...args);
1329
- return { printed: args.join(" ") };
1330
- });
1331
- builtins.set("uppercase", (args) => String(args[0]).toUpperCase());
1332
- builtins.set("lowercase", (args) => String(args[0]).toLowerCase());
1333
- builtins.set("push", (args) => {
1334
- const arr = args[0];
1335
- if (Array.isArray(arr)) {
1336
- arr.push(args[1]);
1337
- return arr;
1338
- }
1339
- return [args[0], args[1]];
1340
- });
1341
- builtins.set("pop", (args) => {
1342
- const arr = args[0];
1343
- if (Array.isArray(arr)) return arr.pop();
1344
- return void 0;
1345
- });
1346
- builtins.set("at", (args) => {
1347
- const arr = args[0];
1348
- const index = Number(args[1]);
1349
- if (Array.isArray(arr)) return arr[index];
1350
- return void 0;
1351
- });
1352
- builtins.set("showSettings", () => {
1353
- this.emit("show-settings");
1354
- return true;
1355
- });
1356
- builtins.set("openChat", (args) => {
1357
- const config = args[0] || {};
1358
- this.emit("show-chat", config);
1359
- return true;
1360
- });
1361
- builtins.set("log", (args) => {
1362
- logger.info("HoloScript log", { args });
1363
- return args[0];
1364
- });
1365
- builtins.set("print", (args) => {
1366
- const message = args.map(String).join(" ");
1367
- logger.info("print", { message });
1368
- return message;
1369
- });
1370
- builtins.set("typeof", (args) => typeof args[0]);
1371
- builtins.set("isArray", (args) => Array.isArray(args[0]));
1372
- builtins.set(
1373
- "isNumber",
1374
- (args) => typeof args[0] === "number" && !isNaN(args[0])
1375
- );
1376
- builtins.set("isString", (args) => typeof args[0] === "string");
1377
- builtins.set("shop", (args) => this.handleShop(args));
1378
- builtins.set("inventory", (args) => this.handleInventory(args));
1379
- builtins.set("purchase", (args) => this.handlePurchase(args));
1380
- builtins.set("presence", (args) => this.handlePresence(args));
1381
- builtins.set("invite", (args) => this.handleInvite(args));
1382
- builtins.set("share", (args) => this.handleShare(args));
1383
- builtins.set("physics", (args) => this.handlePhysics(args));
1384
- builtins.set("gravity", (args) => this.handleGravity(args));
1385
- builtins.set("collide", (args) => this.handleCollide(args));
1386
- builtins.set("animate", (args) => this.handleAnimate(args));
1387
- builtins.set("calculate_arc", (args) => this.handleCalculateArc(args));
1388
- builtins.set(
1389
- "sleep",
1390
- (args) => new Promise((resolve2) => setTimeout(resolve2, Number(args[0]) || 0))
1391
- );
1392
- builtins.set("think", async (args) => {
1393
- const activeNode = this.context.executionStack[this.context.executionStack.length - 1];
1394
- if (!activeNode) return "No context";
1395
- const agentId = activeNode.name;
1396
- const agentRuntime = this.agentRuntimes.get(agentId);
1397
- if (agentRuntime) {
1398
- return await agentRuntime.think(String(args[0] || ""));
1399
- }
1400
- return "Thinking only available for agents.";
1401
- });
1402
- return builtins;
1403
- }
1404
- /**
1405
- * Register a global function from an extension
1406
- */
1407
- registerGlobalFunction(name, fn) {
1408
- this.context.functions.set(name, ((...spreadArgs) => fn(spreadArgs)));
1409
- }
1410
- /**
1411
- * Register a custom trait from an extension
1412
- */
1413
- registerTrait(name, handler) {
1414
- const vrName = name;
1415
- this.traitHandlers.set(vrName, handler);
1416
- logger.info(`Registered trait: ${name}`);
1417
- }
1418
- /**
1419
- * Get the extension registry
1420
- */
1421
- getExtensionRegistry() {
1422
- return this.extensionRegistry;
1423
- }
1424
- /**
1425
- * Execute a single AST node
1426
- */
1427
- async executeNode(node) {
1428
- const startTime = Date.now();
1429
- try {
1430
- this.context.executionStack.push(node);
1431
- let result;
1432
- const nodeType = node.type;
1433
- switch (nodeType) {
1434
- case "orb":
1435
- case "object":
1436
- result = await this.executeOrb(node);
1437
- break;
1438
- case "narrative":
1439
- result = await this.executeNarrative(node);
1440
- break;
1441
- case "quest":
1442
- result = await this.executeQuest(node);
1443
- break;
1444
- case "dialogue":
1445
- result = await this.executeDialogue(node);
1446
- break;
1447
- case "visual_metadata":
1448
- result = await this.executeVisualMetadata(node);
1449
- break;
1450
- case "method":
1451
- case "function":
1452
- result = await this.executeFunction(node);
1453
- break;
1454
- case "connection":
1455
- result = await this.executeConnection(node);
1456
- break;
1457
- case "gate":
1458
- result = await this.executeGate(node);
1459
- break;
1460
- case "stream":
1461
- result = await this.executeStream(node);
1462
- break;
1463
- case "call":
1464
- result = await this.executeCall(node);
1465
- break;
1466
- case "debug":
1467
- result = await this.executeDebug(node);
1468
- break;
1469
- case "visualize":
1470
- result = await this.executeVisualize(node);
1471
- break;
1472
- case "2d-element":
1473
- result = await this.executeUIElement(node);
1474
- break;
1475
- case "nexus":
1476
- case "building":
1477
- result = await this.executeStructure(node);
1478
- break;
1479
- case "assignment":
1480
- result = await this.executeAssignment(node);
1481
- break;
1482
- case "return":
1483
- result = await this.executeReturn(node);
1484
- break;
1485
- case "memory":
1486
- result = await this.executeMemory(node);
1487
- break;
1488
- case "semantic-memory":
1489
- case "episodic-memory":
1490
- case "procedural-memory":
1491
- result = await this.executeMemoryDefinition(
1492
- node
1493
- );
1494
- break;
1495
- case "generic":
1496
- result = await this.executeGeneric(node);
1497
- break;
1498
- case "expression-statement":
1499
- result = await this.executeExpressionStatement(node);
1500
- break;
1501
- case "scale":
1502
- result = await this.executeScale(node);
1503
- break;
1504
- case "focus":
1505
- result = await this.executeFocus(node);
1506
- break;
1507
- case "environment":
1508
- result = await this.executeEnvironment(node);
1509
- break;
1510
- case "composition":
1511
- case "Composition":
1512
- if (node.type === "Composition") {
1513
- result = await this.executeHoloComposition(node);
1514
- } else {
1515
- result = await this.executeComposition(node);
1516
- }
1517
- break;
1518
- case "template":
1519
- case "Template":
1520
- if (node.type === "Template") {
1521
- result = await this.executeHoloTemplate(node);
1522
- } else {
1523
- result = await this.executeTemplate(node);
1524
- }
1525
- break;
1526
- case "migration":
1527
- result = { success: true, output: "Migration block registered" };
1528
- break;
1529
- case "server":
1530
- result = await this.executeServerNode(node);
1531
- break;
1532
- case "database":
1533
- result = await this.executeDatabaseNode(node);
1534
- break;
1535
- case "fetch":
1536
- result = await this.executeFetchNode(node);
1537
- break;
1538
- case "execute":
1539
- result = await this.executeTarget(node);
1540
- break;
1541
- case "state-declaration":
1542
- result = await this.executeStateDeclaration(
1543
- node
1544
- );
1545
- break;
1546
- case "state-machine":
1547
- result = await this.executeStateMachine(node);
1548
- break;
1549
- case "system":
1550
- result = await this.executeSystem(node);
1551
- break;
1552
- case "core_config":
1553
- result = await this.executeCoreConfig(node);
1554
- break;
1555
- case "for":
1556
- result = await this.executeForLoop(
1557
- node
1558
- );
1559
- break;
1560
- case "forEach":
1561
- result = await this.executeForEachLoop(
1562
- node
1563
- );
1564
- break;
1565
- case "while":
1566
- result = await this.executeWhileLoop(
1567
- node
1568
- );
1569
- break;
1570
- case "if":
1571
- result = await this.executeIfStatement(
1572
- node
1573
- );
1574
- break;
1575
- case "match":
1576
- result = await this.executeMatch(
1577
- node
1578
- );
1579
- break;
1580
- default:
1581
- result = {
1582
- success: false,
1583
- error: `Unknown node type: ${node.type}`,
1584
- executionTime: Date.now() - startTime
1585
- };
1586
- }
1587
- result.executionTime = Date.now() - startTime;
1588
- this.executionHistory.push(result);
1589
- this.context.executionStack.pop();
1590
- return result;
1591
- } catch (error) {
1592
- const execTime = Date.now() - startTime;
1593
- const errorResult = {
1594
- success: false,
1595
- error: error instanceof Error ? error.message : String(error),
1596
- executionTime: execTime
1597
- };
1598
- this.executionHistory.push(errorResult);
1599
- this.context.executionStack.pop();
1600
- return errorResult;
1601
- }
1602
- }
1603
- /**
1604
- * Execute multiple nodes or a single node (unified entry point)
1605
- */
1606
- async execute(nodes) {
1607
- this.startTime = Date.now();
1608
- this.nodeCount = 0;
1609
- if (Array.isArray(nodes)) {
1610
- const results = await this.executeProgram(nodes);
1611
- const success = results.every((r) => r.success);
1612
- const lastResult = results[results.length - 1];
1613
- let output = success ? `Program executed (${results.length} nodes)` : "Program failed";
1614
- if (lastResult && lastResult.success && lastResult.output !== void 0) {
1615
- output = lastResult.output;
1616
- }
1617
- return {
1618
- success,
1619
- output,
1620
- error: results.find((r) => !r.success)?.error
1621
- };
1622
- } else {
1623
- return this.executeNode(nodes);
1624
- }
1625
- }
1626
- /**
1627
- * Execute multiple nodes in sequence
1628
- */
1629
- async executeProgram(nodes, depth = 0) {
1630
- if (depth === 0) {
1631
- this.startTime = Date.now();
1632
- this.nodeCount = 0;
1633
- }
1634
- if (depth > RUNTIME_SECURITY_LIMITS.maxExecutionDepth) {
1635
- logger.error("Max execution depth exceeded", { depth });
1636
- return [
1637
- {
1638
- success: false,
1639
- error: `Max execution depth exceeded (${RUNTIME_SECURITY_LIMITS.maxExecutionDepth})`,
1640
- executionTime: 0
1641
- }
1642
- ];
1643
- }
1644
- const results = [];
1645
- for (const node of nodes) {
1646
- this.nodeCount++;
1647
- if (this.nodeCount > RUNTIME_SECURITY_LIMITS.maxTotalNodes) {
1648
- logger.error("Max total nodes exceeded", { count: this.nodeCount });
1649
- results.push({
1650
- success: false,
1651
- error: "Max total nodes exceeded",
1652
- executionTime: Date.now() - this.startTime
1653
- });
1654
- break;
1655
- }
1656
- if (Date.now() - this.startTime > RUNTIME_SECURITY_LIMITS.maxExecutionTimeMs) {
1657
- logger.error("Execution timeout", { duration: Date.now() - this.startTime });
1658
- results.push({
1659
- success: false,
1660
- error: "Execution timeout",
1661
- executionTime: Date.now() - this.startTime
1662
- });
1663
- break;
1664
- }
1665
- const result = await this.executeNode(node);
1666
- results.push(result);
1667
- if (!result.success && node.type !== "visualize") {
1668
- break;
1669
- }
1670
- if (node.type === "return") {
1671
- break;
1672
- }
1673
- }
1674
- return results;
1675
- }
1676
- /**
1677
- * Call a function with arguments
1678
- */
1679
- async callFunction(name, args = []) {
1680
- const builtin = this.builtinFunctions.get(name);
1681
- if (builtin) {
1682
- try {
1683
- const result = await builtin(args);
1684
- return {
1685
- success: true,
1686
- output: result
1687
- };
1688
- } catch (error) {
1689
- return {
1690
- success: false,
1691
- error: `Built-in function ${name} failed: ${error}`
1692
- };
1693
- }
1694
- }
1695
- const func = this.context.functions.get(name);
1696
- if (!func) {
1697
- return {
1698
- success: false,
1699
- error: `Function '${name}' not found`
1700
- };
1701
- }
1702
- if (typeof func === "function") {
1703
- try {
1704
- const result = await func(...args);
1705
- return {
1706
- success: true,
1707
- output: result
1708
- };
1709
- } catch (error) {
1710
- return {
1711
- success: false,
1712
- error: `Extension function ${name} failed: ${error}`
1713
- };
1714
- }
1715
- }
1716
- if (this.callStack.length >= RUNTIME_SECURITY_LIMITS.maxCallStackDepth) {
1717
- return {
1718
- success: false,
1719
- error: `Max call stack depth exceeded (${RUNTIME_SECURITY_LIMITS.maxCallStackDepth})`
1720
- };
1721
- }
1722
- const parentScope = this.currentScope;
1723
- this.currentScope = {
1724
- variables: /* @__PURE__ */ new Map(),
1725
- parent: parentScope
1726
- };
1727
- func.parameters.forEach((param, index) => {
1728
- const value = index < args.length ? args[index] : param.defaultValue;
1729
- this.currentScope.variables.set(param.name, value);
1730
- });
1731
- this.callStack.push(name);
1732
- let returnValue = void 0;
1733
- try {
1734
- const results = await this.executeProgram(func.body, this.callStack.length);
1735
- const lastResult = results[results.length - 1];
1736
- if (lastResult?.output !== void 0) {
1737
- returnValue = lastResult.output;
1738
- }
1739
- this.createExecutionEffect(name, func.position || { x: 0, y: 0, z: 0 });
1740
- return {
1741
- success: results.every((r) => r.success),
1742
- output: returnValue,
1743
- hologram: func.hologram,
1744
- spatialPosition: func.position
1745
- };
1746
- } finally {
1747
- this.currentScope = parentScope;
1748
- this.callStack.pop();
1749
- }
1750
- }
1751
- /**
1752
- * Set a variable in current scope
1753
- */
1754
- setVariable(name, value, scopeOverride) {
1755
- if (name.includes(".")) {
1756
- const parts = name.split(".");
1757
- const objName = parts[0];
1758
- const propPath = parts.slice(1);
1759
- let obj = this.getVariable(objName, scopeOverride);
1760
- if (obj === void 0 || typeof obj !== "object" || obj === null) {
1761
- obj = {};
1762
- const scope = scopeOverride || this.currentScope;
1763
- scope.variables.set(objName, obj);
1764
- }
1765
- let current = obj;
1766
- for (let i = 0; i < propPath.length - 1; i++) {
1767
- if (current[propPath[i]] === void 0 || typeof current[propPath[i]] !== "object") {
1768
- current[propPath[i]] = {};
1769
- }
1770
- current = current[propPath[i]];
1771
- }
1772
- current[propPath[propPath.length - 1]] = value;
1773
- } else {
1774
- const scope = scopeOverride || this.currentScope;
1775
- scope.variables.set(name, value);
1776
- }
1777
- if (this.wss && typeof value === "object" && value !== null && value.__type === "orb") {
1778
- this.broadcast("orb_update", { orb: value });
1779
- } else if (this.wss && name.includes(".")) {
1780
- const root = name.split(".")[0];
1781
- const rootVar = this.getVariable(root, scopeOverride);
1782
- if (rootVar && typeof rootVar === "object" && rootVar.__type === "orb") {
1783
- this.broadcast("orb_update", { orb: rootVar });
1784
- }
1785
- }
1786
- }
1787
- /**
1788
- * Get a variable from scope chain
1789
- */
1790
- getVariable(name, scopeOverride) {
1791
- if (name.includes(".")) {
1792
- const parts = name.split(".");
1793
- let value = this.getVariable(parts[0], scopeOverride);
1794
- for (let i = 1; i < parts.length && value !== void 0; i++) {
1795
- if (typeof value === "object" && value !== null) {
1796
- value = value[parts[i]];
1797
- } else {
1798
- return void 0;
1799
- }
1800
- }
1801
- return value;
1802
- }
1803
- let scope = scopeOverride || this.currentScope;
1804
- while (scope) {
1805
- if (scope.variables.has(name)) {
1806
- return scope.variables.get(name);
1807
- }
1808
- scope = scope.parent;
1809
- }
1810
- if (this.context.variables.has(name)) {
1811
- return this.context.variables.get(name);
1812
- }
1813
- if (this.context.functions.has(name)) {
1814
- return this.context.functions.get(name);
1815
- }
1816
- return void 0;
1817
- }
1818
- /**
1819
- * Evaluate an expression in current context
1820
- */
1821
- evaluateExpression(expr) {
1822
- if (!expr || typeof expr !== "string") return expr;
1823
- const evaluator = new ExpressionEvaluator(this.context.state.getSnapshot());
1824
- const varContext = {};
1825
- this.context.variables.forEach((v, k) => varContext[k] = v);
1826
- evaluator.updateContext(varContext);
1827
- return evaluator.evaluate(expr);
1828
- }
1829
- // ============================================================================
1830
- // Node Executors
1831
- // ============================================================================
1832
- async executeOrb(node) {
1833
- const scale = this.context.currentScale || 1;
1834
- const existingRaw = this.context.variables.get(node.name);
1835
- const existingOrb = isOrbData(existingRaw) ? existingRaw : void 0;
1836
- const isUpdate = !!existingOrb;
1837
- let pos = { x: 0, y: 0, z: 0 };
1838
- if (Array.isArray(node.position)) {
1839
- pos = {
1840
- x: Number(node.position[0]) || 0,
1841
- y: Number(node.position[1]) || 0,
1842
- z: Number(node.position[2]) || 0
1843
- };
1844
- } else if (node.position) {
1845
- pos = {
1846
- x: Number(node.position.x) || 0,
1847
- y: Number(node.position.y) || 0,
1848
- z: Number(node.position.z) || 0
1849
- };
1850
- }
1851
- const adjustedPos = {
1852
- x: pos.x * scale,
1853
- y: pos.y * scale,
1854
- z: pos.z * scale
1855
- };
1856
- if (node.position) {
1857
- this.context.spatialMemory.set(node.name, adjustedPos);
1858
- }
1859
- const evaluatedProperties = {};
1860
- if (Array.isArray(node.properties)) {
1861
- for (const prop of node.properties) {
1862
- const key = prop.key;
1863
- const val = prop.value;
1864
- if (typeof val === "string") {
1865
- evaluatedProperties[key] = this.evaluateExpression(val);
1866
- } else {
1867
- evaluatedProperties[key] = val;
1868
- }
1869
- }
1870
- } else if (node.properties) {
1871
- for (const [key, val] of Object.entries(node.properties)) {
1872
- if (typeof val === "string") {
1873
- evaluatedProperties[key] = this.evaluateExpression(val);
1874
- } else {
1875
- evaluatedProperties[key] = val;
1876
- }
1877
- }
1878
- }
1879
- const orbNodeExt = node;
1880
- if (orbNodeExt.template) {
1881
- const tpl = this.context.templates.get(orbNodeExt.template);
1882
- if (tpl) {
1883
- if (tpl.properties) {
1884
- for (const [key, val] of Object.entries(tpl.properties)) {
1885
- if (evaluatedProperties[key] === void 0) {
1886
- if (typeof val === "string") {
1887
- evaluatedProperties[key] = this.evaluateExpression(val);
1888
- } else {
1889
- evaluatedProperties[key] = val;
1890
- }
1891
- }
1892
- }
1893
- }
1894
- if (tpl.directives) {
1895
- const existingDirectives = node.directives || [];
1896
- node.directives = [...tpl.directives, ...existingDirectives];
1897
- }
1898
- }
1899
- }
1900
- const hologram = node.hologram ? {
1901
- ...node.hologram,
1902
- size: (node.hologram.size || Number(evaluatedProperties.size) || Number(evaluatedProperties.scale) || 1) * scale
1903
- } : {
1904
- color: evaluatedProperties.color || "#ffffff",
1905
- size: (Number(evaluatedProperties.size) || Number(evaluatedProperties.scale) || 1) * scale,
1906
- shape: evaluatedProperties.geometry || "sphere",
1907
- glow: !!evaluatedProperties.glow,
1908
- interactive: !!evaluatedProperties.interactive
1909
- };
1910
- if (isUpdate && node.template) {
1911
- const tpl = this.context.templates.get(node.template);
1912
- const oldTpl = existingOrb?._templateRef;
1913
- if (tpl && oldTpl && tpl.version !== void 0 && oldTpl.version !== void 0) {
1914
- if (Number(tpl.version) > Number(oldTpl.version)) {
1915
- logger.info(
1916
- `Template version increase detected for ${node.name}: ${oldTpl.version} -> ${tpl.version}`
1917
- );
1918
- const migrations = tpl.migrations || [];
1919
- const migration = migrations.find((m) => m.fromVersion === Number(oldTpl.version));
1920
- if (migration) {
1921
- logger.info(`Executing migration from version ${oldTpl.version} for ${node.name}`);
1922
- await this.executeMigrationBlock(existingOrb, migration);
1923
- }
1924
- }
1925
- }
1926
- }
1927
- const orbData = isUpdate ? existingOrb : {
1928
- __type: "orb",
1929
- id: node.name,
1930
- name: node.name,
1931
- created: Date.now(),
1932
- // Methods bound to this orb
1933
- show: () => this.builtinFunctions.get("show")([node.name]),
1934
- hide: () => this.builtinFunctions.get("hide")([node.name]),
1935
- pulse: (opts) => this.builtinFunctions.get("pulse")([node.name, opts])
1936
- };
1937
- if (isUpdate) {
1938
- orbData.properties = {
1939
- // @ts-expect-error During migration
1940
- ...orbData.properties,
1941
- ...evaluatedProperties
1942
- };
1943
- } else {
1944
- orbData.properties = evaluatedProperties;
1945
- }
1946
- orbData.directives = node.directives || [];
1947
- orbData.position = adjustedPos;
1948
- orbData.hologram = hologram;
1949
- orbData._templateRef = node.template ? this.context.templates.get(node.template) : void 0;
1950
- if (!isUpdate) {
1951
- this.context.variables.set(node.name, orbData);
1952
- }
1953
- if (hologram) {
1954
- this.context.hologramState.set(node.name, hologram);
1955
- }
1956
- if (node.directives) {
1957
- this.applyDirectives(orbData);
1958
- }
1959
- if (!isUpdate) {
1960
- this.createParticleEffect(`${node.name}_creation`, adjustedPos, "#00ffff", 20);
1961
- }
1962
- if (this.isAgent(node)) {
1963
- if (!isUpdate || !this.agentRuntimes.has(node.name)) {
1964
- const agentRuntime = this.agentPool.acquire();
1965
- agentRuntime.reset(node, this);
1966
- this.agentRuntimes.set(node.name, agentRuntime);
1967
- orbData.state = agentRuntime.getState();
1968
- node.directives?.filter((d) => d.type === "method").forEach((m) => {
1969
- orbData[m.name] = (...args) => agentRuntime.executeAction(m.name, args);
1970
- });
1971
- }
1972
- }
1973
- logger.info(isUpdate ? "Orb updated" : "Orb created", {
1974
- name: node.name,
1975
- // @ts-expect-error During migration
1976
- properties: Object.keys(orbData.properties),
1977
- scale
1978
- });
1979
- this.broadcast(isUpdate ? "orb_updated" : "orb_created", {
1980
- orb: {
1981
- id: node.name,
1982
- name: node.name,
1983
- position: adjustedPos,
1984
- // @ts-expect-error During migration
1985
- properties: orbData.properties,
1986
- hologram,
1987
- traits: node.directives?.filter((d) => d.type === "trait").map((d) => d.name) || []
1988
- }
1989
- });
1990
- return {
1991
- success: true,
1992
- output: orbData,
1993
- hologram,
1994
- spatialPosition: adjustedPos
1995
- };
1996
- }
1997
- async executeFunction(node) {
1998
- this.context.functions.set(node.name, node);
1999
- const hologram = {
2000
- shape: "cube",
2001
- color: "#ff6b35",
2002
- size: 1.5,
2003
- glow: true,
2004
- interactive: true,
2005
- ...node.hologram
2006
- };
2007
- this.context.hologramState.set(node.name, hologram);
2008
- logger.info("Function defined", {
2009
- name: node.name,
2010
- params: node.parameters.map((p) => p.name)
2011
- });
2012
- return {
2013
- success: true,
2014
- output: `Function '${node.name}' defined with ${node.parameters.length} parameter(s)`,
2015
- hologram,
2016
- spatialPosition: node.position
2017
- };
2018
- }
2019
- async executeConnection(node) {
2020
- this.context.connections.push(node);
2021
- const fromPos = this.context.spatialMemory.get(node.from);
2022
- const toPos = this.context.spatialMemory.get(node.to);
2023
- if (fromPos && toPos) {
2024
- this.createConnectionStream(node.from, node.to, fromPos, toPos, node.dataType);
2025
- }
2026
- if (node.bidirectional) {
2027
- this.on(`${node.from}.changed`, async (data) => {
2028
- this.setVariable(node.to, data);
2029
- this.emit(`${node.to}.changed`, data);
2030
- });
2031
- this.on(`${node.to}.changed`, async (data) => {
2032
- this.setVariable(node.from, data);
2033
- this.emit(`${node.from}.changed`, data);
2034
- });
2035
- }
2036
- logger.info("Connection created", { from: node.from, to: node.to, dataType: node.dataType });
2037
- return {
2038
- success: true,
2039
- output: `Connected '${node.from}' to '${node.to}' (${node.dataType})`,
2040
- hologram: {
2041
- shape: "cylinder",
2042
- color: this.getDataTypeColor(node.dataType),
2043
- size: 0.1,
2044
- glow: true,
2045
- interactive: false
2046
- }
2047
- };
2048
- }
2049
- async executeGate(node) {
2050
- try {
2051
- const condition = this.evaluateCondition(node.condition);
2052
- const path2 = condition ? node.truePath : node.falsePath;
2053
- logger.info("Gate evaluation", { condition: node.condition, result: condition });
2054
- if (path2.length > 0) {
2055
- const subResults = await this.executeProgram(path2, this.callStack.length + 1);
2056
- const lastResult = subResults[subResults.length - 1];
2057
- if (lastResult && lastResult.success && lastResult.output !== void 0) {
2058
- return lastResult;
2059
- }
2060
- }
2061
- return {
2062
- success: true,
2063
- output: `Gate: took ${condition ? "true" : "false"} path`,
2064
- hologram: {
2065
- shape: "pyramid",
2066
- color: condition ? "#00ff00" : "#ff0000",
2067
- size: 1,
2068
- glow: true,
2069
- interactive: true
2070
- }
2071
- };
2072
- } catch (error) {
2073
- return {
2074
- success: false,
2075
- error: `Gate execution failed: ${error}`
2076
- };
2077
- }
2078
- }
2079
- async executeStream(node) {
2080
- let data = this.getVariable(node.source);
2081
- logger.info("Stream processing", {
2082
- name: node.name,
2083
- source: node.source,
2084
- transforms: node.transformations.length
2085
- });
2086
- for (const transform of node.transformations) {
2087
- data = await this.applyTransformation(data, transform);
2088
- }
2089
- this.setVariable(`${node.name}_result`, data);
2090
- this.createFlowingStream(node.name, node.position || { x: 0, y: 0, z: 0 }, data);
2091
- return {
2092
- success: true,
2093
- output: `Stream '${node.name}' processed ${Array.isArray(data) ? data.length : 1} item(s)`,
2094
- hologram: node.hologram,
2095
- spatialPosition: node.position
2096
- };
2097
- }
2098
- /**
2099
- * Execute State Machine declaration (Phase 13)
2100
- */
2101
- async executeStateMachine(node) {
2102
- this.context.stateMachines.set(node.name, node);
2103
- logger.info(`State machine registered: ${node.name}`);
2104
- return {
2105
- success: true,
2106
- output: { registered: node.name }
2107
- };
2108
- }
2109
- async executeExpressionStatement(node) {
2110
- const value = this.evaluateExpression(node.expression);
2111
- return {
2112
- success: true,
2113
- output: value
2114
- };
2115
- }
2116
- async executeCall(node) {
2117
- const funcName = node.target || "";
2118
- const args = node.args || [];
2119
- return this.callFunction(funcName, args);
2120
- }
2121
- async executeDebug(node) {
2122
- const debugInfo = {
2123
- variables: Object.fromEntries(this.currentScope.variables),
2124
- contextVariables: Object.fromEntries(this.context.variables),
2125
- functions: Array.from(this.context.functions.keys()),
2126
- connections: this.context.connections.length,
2127
- callStack: [...this.callStack],
2128
- uiElements: Array.from(this.uiElements.keys()),
2129
- animations: Array.from(this.animations.keys()),
2130
- executionHistory: this.executionHistory.slice(-10)
2131
- };
2132
- const debugOrb = {
2133
- shape: "pyramid",
2134
- color: "#ff1493",
2135
- size: 0.8,
2136
- glow: true,
2137
- interactive: true
2138
- };
2139
- this.context.hologramState.set(`debug_${node.target || "program"}`, debugOrb);
2140
- logger.info("Debug info", debugInfo);
2141
- return {
2142
- success: true,
2143
- output: debugInfo,
2144
- hologram: debugOrb
2145
- };
2146
- }
2147
- async executeVisualize(node) {
2148
- const target = node.target || "";
2149
- const data = this.getVariable(target);
2150
- if (data === void 0) {
2151
- return {
2152
- success: false,
2153
- error: `No data found for '${target}'`
2154
- };
2155
- }
2156
- const visHologram = {
2157
- shape: "cylinder",
2158
- color: "#32cd32",
2159
- size: 1.5,
2160
- glow: true,
2161
- interactive: true
2162
- };
2163
- this.createDataVisualization(target, data, node.position || { x: 0, y: 0, z: 0 });
2164
- return {
2165
- success: true,
2166
- output: { visualizing: target, data },
2167
- hologram: visHologram
2168
- };
2169
- }
2170
- async executeUIElement(node) {
2171
- const element = {
2172
- type: node.elementType,
2173
- name: node.name,
2174
- properties: { ...node.properties },
2175
- visible: true,
2176
- enabled: true
2177
- };
2178
- if (node.elementType === "textinput") {
2179
- element.value = node.properties.value || "";
2180
- } else if (node.elementType === "slider") {
2181
- element.value = node.properties.value || node.properties.min || 0;
2182
- } else if (node.elementType === "toggle") {
2183
- element.value = node.properties.checked || false;
2184
- }
2185
- this.uiElements.set(node.name, element);
2186
- if (node.events) {
2187
- for (const [eventName, handlerName] of Object.entries(node.events)) {
2188
- this.on(`${node.name}.${eventName}`, async () => {
2189
- await this.callFunction(handlerName);
2190
- });
2191
- }
2192
- }
2193
- logger.info("UI element created", { type: node.elementType, name: node.name });
2194
- return {
2195
- success: true,
2196
- output: element
2197
- };
2198
- }
2199
- /**
2200
- * Execute generic voice commands
2201
- * Handles commands like: show, hide, animate, pulse, create
2202
- */
2203
- async executeGeneric(_node) {
2204
- const genericNode = _node;
2205
- const command = String(genericNode.command || "").trim().toLowerCase();
2206
- const tokens = command.split(/\s+/);
2207
- const action = tokens[0];
2208
- const target = tokens[1];
2209
- logger.info("Executing generic command", { command, action, target });
2210
- try {
2211
- let result;
2212
- switch (action) {
2213
- case "show":
2214
- result = await this.executeShowCommand(target, genericNode);
2215
- break;
2216
- case "hide":
2217
- result = await this.executeHideCommand(target, genericNode);
2218
- break;
2219
- case "create":
2220
- case "summon":
2221
- result = await this.executeCreateCommand(tokens.slice(1), genericNode);
2222
- break;
2223
- case "animate":
2224
- result = await this.executeAnimateCommand(target, tokens.slice(2), genericNode);
2225
- break;
2226
- case "pulse":
2227
- result = await this.executePulseCommand(target, tokens.slice(2), genericNode);
2228
- break;
2229
- case "move":
2230
- result = await this.executeMoveCommand(target, tokens.slice(2), genericNode);
2231
- break;
2232
- case "delete":
2233
- case "remove":
2234
- result = await this.executeDeleteCommand(target, genericNode);
2235
- break;
2236
- default:
2237
- logger.warn("Unknown voice command action", { action, command });
2238
- result = {
2239
- executed: false,
2240
- message: `Unknown command: ${action}`
2241
- };
2242
- }
2243
- return {
2244
- success: true,
2245
- output: result
2246
- };
2247
- } catch (error) {
2248
- return {
2249
- success: false,
2250
- error: `Generic command execution failed: ${String(error)}`
2251
- };
2252
- }
2253
- }
2254
- /**
2255
- * Execute 'show' command
2256
- */
2257
- async executeShowCommand(target, _node) {
2258
- const hologram = _node.hologram || {
2259
- shape: "orb",
2260
- color: "#00ffff",
2261
- size: 0.8,
2262
- glow: true,
2263
- interactive: true
2264
- };
2265
- const position = _node.position || { x: 0, y: 0, z: 0 };
2266
- this.context.spatialMemory.set(target, position);
2267
- this.createParticleEffect(`${target}_show`, position, hologram.color, 15);
2268
- logger.info("Show command executed", { target, position });
2269
- return {
2270
- showed: target,
2271
- hologram,
2272
- position
2273
- };
2274
- }
2275
- /**
2276
- * Execute 'hide' command
2277
- */
2278
- async executeHideCommand(target, _node) {
2279
- const position = this.context.spatialMemory.get(target) || { x: 0, y: 0, z: 0 };
2280
- this.createParticleEffect(`${target}_hide`, position, "#ff0000", 10);
2281
- logger.info("Hide command executed", { target });
2282
- return {
2283
- hidden: target
2284
- };
2285
- }
2286
- /**
2287
- * Execute 'create' command
2288
- */
2289
- async executeCreateCommand(tokens, _node) {
2290
- if (tokens.length < 2) {
2291
- return { error: "Create command requires shape and name" };
2292
- }
2293
- const shape = tokens[0];
2294
- const name = tokens[1];
2295
- const position = _node.position || { x: 0, y: 0, z: 0 };
2296
- const hologram = {
2297
- shape,
2298
- color: _node.hologram?.color || "#00ffff",
2299
- size: _node.hologram?.size || 1,
2300
- glow: _node.hologram?.glow !== false,
2301
- interactive: _node.hologram?.interactive !== false
2302
- };
2303
- this.context.spatialMemory.set(name, position);
2304
- this.createParticleEffect(`${name}_create`, position, hologram.color, 20);
2305
- logger.info("Create command executed", { shape, name, position });
2306
- return {
2307
- created: name,
2308
- shape,
2309
- hologram,
2310
- position
2311
- };
2312
- }
2313
- /**
2314
- * Execute 'animate' command
2315
- */
2316
- async executeAnimateCommand(target, tokens, _node) {
2317
- const property = tokens[0] || "position.y";
2318
- const duration = parseInt(tokens[1] || "1000", 10);
2319
- const animation = {
2320
- target,
2321
- property,
2322
- from: 0,
2323
- to: 1,
2324
- duration,
2325
- startTime: Date.now(),
2326
- easing: "ease-in-out"
2327
- };
2328
- this.animations.set(`${target}_${property}`, animation);
2329
- logger.info("Animate command executed", { target, property, duration });
2330
- return {
2331
- animating: target,
2332
- animation
2333
- };
2334
- }
2335
- /**
2336
- * Execute 'pulse' command
2337
- */
2338
- async executePulseCommand(target, tokens, _node) {
2339
- const duration = parseInt(tokens[0] || "500", 10);
2340
- const position = this.context.spatialMemory.get(target) || { x: 0, y: 0, z: 0 };
2341
- this.createParticleEffect(`${target}_pulse`, position, "#ffff00", 30);
2342
- const animation = {
2343
- target,
2344
- property: "scale",
2345
- from: 1,
2346
- to: 1.5,
2347
- duration,
2348
- startTime: Date.now(),
2349
- easing: "sine",
2350
- yoyo: true,
2351
- loop: true
2352
- };
2353
- this.animations.set(`${target}_pulse`, animation);
2354
- logger.info("Pulse command executed", { target, duration });
2355
- return {
2356
- pulsing: target,
2357
- duration
2358
- };
2359
- }
2360
- /**
2361
- * Execute 'move' command
2362
- */
2363
- async executeMoveCommand(target, tokens, _node) {
2364
- const x = parseFloat(tokens[0] || "0");
2365
- const y = parseFloat(tokens[1] || "0");
2366
- const z = parseFloat(tokens[2] || "0");
2367
- const position = { x, y, z };
2368
- const current = this.context.spatialMemory.get(target);
2369
- if (current) {
2370
- this.context.spatialMemory.set(target, position);
2371
- this.createConnectionStream(target, `${target}_move`, current, position, "movement");
2372
- } else {
2373
- this.context.spatialMemory.set(target, position);
2374
- }
2375
- logger.info("Move command executed", { target, position });
2376
- return {
2377
- moved: target,
2378
- to: position
2379
- };
2380
- }
2381
- /**
2382
- * Execute 'delete' command
2383
- */
2384
- async executeDeleteCommand(target, _node) {
2385
- const position = this.context.spatialMemory.get(target);
2386
- if (position) {
2387
- this.createParticleEffect(`${target}_delete`, position, "#ff0000", 15);
2388
- this.context.spatialMemory.delete(target);
2389
- }
2390
- logger.info("Delete command executed", { target });
2391
- return {
2392
- deleted: target
2393
- };
2394
- }
2395
- async executeStructure(node) {
2396
- const hologram = node.hologram || {
2397
- shape: node.type === "nexus" ? "sphere" : "cube",
2398
- color: node.type === "nexus" ? "#9b59b6" : "#e74c3c",
2399
- size: node.type === "nexus" ? 3 : 4,
2400
- glow: true,
2401
- interactive: true
2402
- };
2403
- return {
2404
- success: true,
2405
- output: { type: node.type, created: true },
2406
- hologram,
2407
- spatialPosition: node.position
2408
- };
2409
- }
2410
- async executeAssignment(node) {
2411
- const value = this.evaluateExpression(String(node.value));
2412
- this.setVariable(node.name, value);
2413
- return {
2414
- success: true,
2415
- output: { assigned: node.name, value }
2416
- };
2417
- }
2418
- async executeReturn(node) {
2419
- const expr = String(node.value || node.expression || "");
2420
- const value = this.evaluateExpression(expr);
2421
- return {
2422
- success: true,
2423
- output: value
2424
- };
2425
- }
2426
- // ============================================================================
2427
- // Condition Evaluation
2428
- // ============================================================================
2429
- evaluateCondition(condition) {
2430
- if (!condition) return false;
2431
- const condStr = String(condition);
2432
- const suspiciousKeywords = ["eval", "process", "require", "__proto__", "constructor"];
2433
- if (suspiciousKeywords.some((kw) => condStr.toLowerCase().includes(kw))) {
2434
- logger.warn("Suspicious condition blocked", { condition });
2435
- return false;
2436
- }
2437
- try {
2438
- if (condStr.trim().toLowerCase() === "true") return true;
2439
- if (condStr.trim().toLowerCase() === "false") return false;
2440
- const comparisonPatterns = [
2441
- { regex: /^(.+?)\s*(===|!==)\s*(.+)$/ },
2442
- { regex: /^(.+?)\s*(==|!=|>=|<=|>|<)\s*(.+)$/ },
2443
- { regex: /^(.+?)\s*(&&)\s*(.+)$/, logical: "and" },
2444
- { regex: /^(.+?)\s*(\|\|)\s*(.+)$/, logical: "or" }
2445
- ];
2446
- for (const { regex, logical } of comparisonPatterns) {
2447
- const match = condStr.match(regex);
2448
- if (match) {
2449
- const [, leftExpr, operator, rightExpr] = match;
2450
- const left = this.evaluateExpression(leftExpr.trim());
2451
- const right = this.evaluateExpression(rightExpr.trim());
2452
- if (logical === "and") return Boolean(left) && Boolean(right);
2453
- if (logical === "or") return Boolean(left) || Boolean(right);
2454
- switch (operator) {
2455
- case "===":
2456
- return left === right;
2457
- case "!==":
2458
- return left !== right;
2459
- case "==":
2460
- return left == right;
2461
- case "!=":
2462
- return left != right;
2463
- case ">=":
2464
- return Number(left) >= Number(right);
2465
- case "<=":
2466
- return Number(left) <= Number(right);
2467
- case ">":
2468
- return Number(left) > Number(right);
2469
- case "<":
2470
- return Number(left) < Number(right);
2471
- }
2472
- }
2473
- }
2474
- if (condStr.startsWith("!")) {
2475
- return !this.evaluateCondition(condStr.slice(1).trim());
2476
- }
2477
- const value = this.evaluateExpression(condStr.trim());
2478
- return Boolean(value);
2479
- } catch (error) {
2480
- logger.error("Condition evaluation error", { condition, error });
2481
- return false;
2482
- }
2483
- }
2484
- // ============================================================================
2485
- // Transformation
2486
- // ============================================================================
2487
- async applyTransformation(data, transform) {
2488
- const params = transform.parameters || {};
2489
- switch (transform.operation) {
2490
- case "filter": {
2491
- if (!Array.isArray(data)) return data;
2492
- const predicate = params.predicate;
2493
- if (predicate) {
2494
- return data.filter((item) => {
2495
- this.setVariable("_item", item);
2496
- return this.evaluateCondition(predicate);
2497
- });
2498
- }
2499
- return data.filter((item) => item !== null && item !== void 0);
2500
- }
2501
- case "map": {
2502
- if (!Array.isArray(data)) return data;
2503
- const mapper = params.mapper;
2504
- if (mapper) {
2505
- return data.map((item) => {
2506
- this.setVariable("_item", item);
2507
- return this.evaluateExpression(mapper);
2508
- });
2509
- }
2510
- return data.map((item) => ({ value: item, processed: true }));
2511
- }
2512
- case "reduce": {
2513
- if (!Array.isArray(data)) return data;
2514
- const initial = params.initial ?? 0;
2515
- const reducer = params.reducer;
2516
- if (reducer) {
2517
- return data.reduce((acc, item) => {
2518
- this.setVariable("_acc", acc);
2519
- this.setVariable("_item", item);
2520
- return this.evaluateExpression(reducer);
2521
- }, initial);
2522
- }
2523
- return data.reduce((acc, item) => acc + (typeof item === "number" ? item : 0), 0);
2524
- }
2525
- case "sort": {
2526
- if (!Array.isArray(data)) return data;
2527
- const key = params.key;
2528
- const desc = params.descending;
2529
- const sorted = [...data].sort((a, b) => {
2530
- const aVal = key ? a[key] : a;
2531
- const bVal = key ? b[key] : b;
2532
- if (aVal < bVal) return desc ? 1 : -1;
2533
- if (aVal > bVal) return desc ? -1 : 1;
2534
- return 0;
2535
- });
2536
- return sorted;
2537
- }
2538
- case "sum":
2539
- return Array.isArray(data) ? data.reduce((sum, item) => sum + (typeof item === "number" ? item : 0), 0) : data;
2540
- case "count":
2541
- return Array.isArray(data) ? data.length : 1;
2542
- case "unique":
2543
- return Array.isArray(data) ? Array.from(new Set(data)) : data;
2544
- case "flatten":
2545
- return Array.isArray(data) ? data.flat() : data;
2546
- case "reverse":
2547
- return Array.isArray(data) ? [...data].reverse() : data;
2548
- case "take": {
2549
- if (!Array.isArray(data)) return data;
2550
- const count = Number(params.count) || 10;
2551
- return data.slice(0, count);
2552
- }
2553
- case "skip": {
2554
- if (!Array.isArray(data)) return data;
2555
- const count = Number(params.count) || 0;
2556
- return data.slice(count);
2557
- }
2558
- default:
2559
- logger.warn("Unknown transformation", { operation: transform.operation });
2560
- return data;
2561
- }
2562
- }
2563
- // ============================================================================
2564
- // Event System
2565
- // ============================================================================
2566
- /**
2567
- * Register event handler
2568
- */
2569
- on(event, handler) {
2570
- const handlers = this.eventHandlers.get(event) || [];
2571
- handlers.push(handler);
2572
- this.eventHandlers.set(event, handlers);
2573
- }
2574
- /**
2575
- * Register host function
2576
- */
2577
- registerFunction(name, handler) {
2578
- this.builtinFunctions.set(name, handler);
2579
- logger.info(`Host function registered: ${name}`);
2580
- }
2581
- /**
2582
- * Remove event handler
2583
- */
2584
- off(event, handler) {
2585
- if (!handler) {
2586
- this.eventHandlers.delete(event);
2587
- } else {
2588
- const handlers = this.eventHandlers.get(event) || [];
2589
- this.eventHandlers.set(
2590
- event,
2591
- handlers.filter((h) => h !== handler)
2592
- );
2593
- }
2594
- }
2595
- /**
2596
- * Emit event
2597
- */
2598
- async emit(event, data) {
2599
- logger.info(`[Runtime] Emitting event: ${event}`, data);
2600
- if (event.includes(".")) {
2601
- const [target, eventName] = event.split(".");
2602
- const agent = this.agentRuntimes.get(target);
2603
- if (agent) {
2604
- await agent.onEvent(eventName, data);
2605
- }
2606
- const orb = this.context.variables.get(target);
2607
- if (orb && typeof orb === "object" && orb.__type === "orb") {
2608
- this.forwardToTraits(orb, eventName, data);
2609
- }
2610
- }
2611
- const orbs = Array.from(this.context.variables.values()).filter(
2612
- (v) => v && typeof v === "object" && v.__type === "orb"
2613
- );
2614
- for (const agent of this.agentRuntimes.values()) {
2615
- await agent.onEvent(event, data);
2616
- }
2617
- for (const variable of orbs) {
2618
- await this.forwardToTraits(variable, event, data);
2619
- }
2620
- const handlers = this.eventHandlers.get(event) || [];
2621
- for (const handler of handlers) {
2622
- try {
2623
- await handler(data);
2624
- } catch (error) {
2625
- logger.error("Event handler error", { event, error });
2626
- }
2627
- }
2628
- await getSharedEventBus().emit(event, data);
2629
- if (data && typeof data === "object" && data.id) {
2630
- stateMachineInterpreter.sendEvent(data.id, event);
2631
- }
2632
- }
2633
- async forwardToTraits(orb, event, data) {
2634
- if (orb.directives) {
2635
- for (const d of orb.directives) {
2636
- if (d.type === "trait") {
2637
- const handler = this.traitHandlers.get(d.name);
2638
- if (handler && handler.onEvent) {
2639
- const traitNode = orb;
2640
- const eventPayload = {
2641
- type: event,
2642
- ...data && typeof data === "object" ? data : {}
2643
- };
2644
- await handler.onEvent(
2645
- traitNode,
2646
- d.config || {},
2647
- {
2648
- emit: async (e, p) => await this.emit(e, p),
2649
- getScaleMultiplier: () => this.context.currentScale || 1
2650
- },
2651
- eventPayload
2652
- );
2653
- }
2654
- }
2655
- }
2656
- }
2657
- }
2658
- /**
2659
- * Trigger UI event
2660
- */
2661
- async triggerUIEvent(elementName, eventType, data) {
2662
- const element = this.uiElements.get(elementName);
2663
- if (!element) {
2664
- logger.warn("UI element not found", { elementName });
2665
- return;
2666
- }
2667
- if (eventType === "change" && data !== void 0) {
2668
- element.value = data;
2669
- }
2670
- await this.emit(`${elementName}.${eventType}`, data);
2671
- }
2672
- // ============================================================================
2673
- // Animation System
2674
- // ============================================================================
2675
- /**
2676
- * Update all animations
2677
- */
2678
- updateAnimations() {
2679
- const now = Date.now();
2680
- for (const [key, anim] of this.animations) {
2681
- const elapsed = now - anim.startTime;
2682
- let progress = Math.min(elapsed / anim.duration, 1);
2683
- progress = this.applyEasing(progress, anim.easing);
2684
- const currentValue = anim.from + (anim.to - anim.from) * progress;
2685
- if (anim.yoyo && progress >= 1) {
2686
- anim.startTime = now;
2687
- [anim.from, anim.to] = [anim.to, anim.from];
2688
- }
2689
- this.setVariable(`${anim.target}.${anim.property}`, currentValue);
2690
- if (progress >= 1 && !anim.loop && !anim.yoyo) {
2691
- this.animations.delete(key);
2692
- } else if (progress >= 1 && anim.loop) {
2693
- anim.startTime = now;
2694
- }
2695
- }
2696
- this.updateSystemVariables();
2697
- }
2698
- /**
2699
- * Update real-life and system variables ($time, $user, etc.)
2700
- */
2701
- updateSystemVariables() {
2702
- const now = /* @__PURE__ */ new Date();
2703
- this.setVariable("$time", now.toLocaleTimeString());
2704
- this.setVariable("$date", now.toLocaleDateString());
2705
- this.setVariable("$timestamp", now.getTime());
2706
- this.setVariable("$hour", now.getHours());
2707
- this.setVariable("$minute", now.getMinutes());
2708
- this.setVariable("$second", now.getSeconds());
2709
- if (this.getVariable("$user") === void 0) {
2710
- this.setVariable("$user", {
2711
- id: "user_123",
2712
- name: "Alpha Explorer",
2713
- level: 42,
2714
- rank: "Legendary",
2715
- achievements: ["First World", "Spirit Guide"],
2716
- preferences: { theme: "holographic", language: "en" }
2717
- });
2718
- }
2719
- if (this.getVariable("$location") === void 0) {
2720
- this.setVariable("$location", {
2721
- city: "Neo Tokyo",
2722
- region: "Holo-Sector 7",
2723
- coordinates: { lat: 35.6895, lng: 139.6917 },
2724
- altitude: 450
2725
- });
2726
- }
2727
- if (this.getVariable("$weather") === void 0) {
2728
- this.setVariable("$weather", {
2729
- condition: "Neon Mist",
2730
- temperature: 24,
2731
- humidity: 65,
2732
- windSpeed: 12,
2733
- unit: "C"
2734
- });
2735
- }
2736
- if (this.getVariable("$wallet") === void 0) {
2737
- this.setVariable("$wallet", {
2738
- address: "0xHolo...42ff",
2739
- balance: 1337.5,
2740
- currency: "HOLO",
2741
- network: "MainNet"
2742
- });
2743
- }
2744
- if (this.getVariable("$ai_config") === void 0) {
2745
- const savedKeys = typeof localStorage !== "undefined" ? localStorage.getItem("brittney_api_keys") : null;
2746
- let configuredCount = 0;
2747
- if (savedKeys) {
2748
- try {
2749
- const keys = JSON.parse(savedKeys);
2750
- configuredCount = Object.values(keys).filter((k) => !!k).length;
2751
- } catch (_e) {
2752
- }
2753
- }
2754
- this.setVariable("$ai_config", {
2755
- status: configuredCount > 0 ? "configured" : "pending",
2756
- providerCount: configuredCount,
2757
- lastUpdated: Date.now()
2758
- });
2759
- }
2760
- if (this.getVariable("$chat_status") === void 0) {
2761
- this.setVariable("$chat_status", {
2762
- active: true,
2763
- typing: false,
2764
- version: "1.0.0-brittney"
2765
- });
2766
- }
2767
- }
2768
- // ==========================================================================
2769
- // COMMERCE PRIMITIVES
2770
- // ==========================================================================
2771
- handleShop(args) {
2772
- const config = args[0] || {};
2773
- this.emit("shop", config);
2774
- return { success: true, type: "shop", config };
2775
- }
2776
- handleInventory(args) {
2777
- const item = args[0];
2778
- const action = args[1] || "add";
2779
- this.emit("inventory", { item, action });
2780
- return { success: true, item, action };
2781
- }
2782
- handlePurchase(args) {
2783
- const productId = args[0];
2784
- this.emit("purchase", { productId });
2785
- return { success: true, productId, status: "pending" };
2786
- }
2787
- // ==========================================================================
2788
- // SOCIAL PRIMITIVES
2789
- // ==========================================================================
2790
- handlePresence(args) {
2791
- const config = args[0] || {};
2792
- this.emit("presence", config);
2793
- return { success: true, active: true };
2794
- }
2795
- handleInvite(args) {
2796
- const userId = args[0];
2797
- this.emit("invite", { userId });
2798
- return { success: true, userId };
2799
- }
2800
- handleShare(args) {
2801
- const scriptId = args[0];
2802
- const targetUserId = args[1];
2803
- this.emit("share", { scriptId, targetUserId });
2804
- return { success: true, scriptId };
2805
- }
2806
- // ==========================================================================
2807
- // PHYSICS PRIMITIVES
2808
- // ==========================================================================
2809
- handlePhysics(args) {
2810
- const config = args[0] || {};
2811
- this.emit("physics", config);
2812
- return { success: true, enabled: config.enabled !== false };
2813
- }
2814
- handleGravity(args) {
2815
- const value = args[0] ?? 9.81;
2816
- this.emit("gravity", { value });
2817
- return { success: true, value };
2818
- }
2819
- handleCollide(args) {
2820
- const target = args[0];
2821
- const handler = args[1];
2822
- this.emit("collide", { target, handler });
2823
- return { success: true, target };
2824
- }
2825
- /**
2826
- * Handle calculate_arc(start, end, speed)
2827
- */
2828
- handleCalculateArc(args) {
2829
- if (args.length < 3) return { x: 0, y: 0, z: 0 };
2830
- const start = args[0];
2831
- const end = args[1];
2832
- const speed = args[2];
2833
- const dx = end.x - start.x;
2834
- const dz = end.z - start.z;
2835
- const dy = end.y - start.y;
2836
- const dist = Math.sqrt(dx * dx + dz * dz);
2837
- if (dist < 0.1) return { x: 0, y: speed, z: 0 };
2838
- const t = dist / speed;
2839
- const vx = dx / t;
2840
- const vz = dz / t;
2841
- const vy = dy / t + 0.5 * 9.81 * t;
2842
- return { x: vx, y: vy, z: vz };
2843
- }
2844
- handleAnimate(args) {
2845
- const options = args[0] || {};
2846
- this.emit("animate", options);
2847
- return { success: true, options };
2848
- }
2849
- applyEasing(t, easing) {
2850
- switch (easing) {
2851
- case "easeIn":
2852
- return t * t;
2853
- case "easeOut":
2854
- return t * (2 - t);
2855
- case "easeInOut":
2856
- return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
2857
- case "easeInQuad":
2858
- return t * t;
2859
- case "easeOutQuad":
2860
- return t * (2 - t);
2861
- case "easeInOutQuad":
2862
- return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
2863
- case "linear":
2864
- default:
2865
- return t;
2866
- }
2867
- }
2868
- // ============================================================================
2869
- // Particle Effects
2870
- // ============================================================================
2871
- createParticleEffect(name, position, color, count) {
2872
- const limitedCount = Math.min(count, RUNTIME_SECURITY_LIMITS.maxParticlesPerSystem);
2873
- const particles = [];
2874
- for (let i = 0; i < limitedCount; i++) {
2875
- particles.push({
2876
- x: position.x + (Math.random() - 0.5) * 2,
2877
- y: position.y + (Math.random() - 0.5) * 2,
2878
- z: position.z + (Math.random() - 0.5) * 2
2879
- });
2880
- }
2881
- this.particleSystems.set(name, {
2882
- particles,
2883
- color,
2884
- lifetime: 3e3,
2885
- speed: 0.01
2886
- });
2887
- }
2888
- createConnectionStream(from, to, fromPos, toPos, dataType) {
2889
- const streamName = `connection_${from}_${to}`;
2890
- const particles = [];
2891
- const steps = 20;
2892
- for (let i = 0; i <= steps; i++) {
2893
- const t = i / steps;
2894
- particles.push({
2895
- x: fromPos.x + (toPos.x - fromPos.x) * t,
2896
- y: fromPos.y + (toPos.y - fromPos.y) * t,
2897
- z: fromPos.z + (toPos.z - fromPos.z) * t
2898
- });
2899
- }
2900
- this.particleSystems.set(streamName, {
2901
- particles,
2902
- color: this.getDataTypeColor(dataType),
2903
- lifetime: 5e3,
2904
- speed: 0.02
2905
- });
2906
- }
2907
- createFlowingStream(name, position, data) {
2908
- const count = Array.isArray(data) ? Math.min(data.length, 50) : 10;
2909
- this.createParticleEffect(`${name}_flow`, position, "#45b7d1", count);
2910
- }
2911
- createExecutionEffect(name, position) {
2912
- this.createParticleEffect(`${name}_execution`, position, "#ff4500", 30);
2913
- }
2914
- createDataVisualization(name, data, position) {
2915
- let count = 10;
2916
- if (Array.isArray(data)) {
2917
- count = Math.min(data.length, 100);
2918
- } else if (typeof data === "object" && data !== null) {
2919
- count = Math.min(Object.keys(data).length * 5, 50);
2920
- }
2921
- this.createParticleEffect(`${name}_visualization`, position, "#32cd32", count);
2922
- }
2923
- getDataTypeColor(dataType) {
2924
- const colors = {
2925
- string: "#ff6b35",
2926
- number: "#4ecdc4",
2927
- boolean: "#45b7d1",
2928
- object: "#96ceb4",
2929
- array: "#ffeaa7",
2930
- any: "#dda0dd",
2931
- move: "#ff69b4"
2932
- };
2933
- return colors[dataType] || "#ffffff";
2934
- }
2935
- // ============================================================================
2936
- // Visualizer Server
2937
- // ============================================================================
2938
- startVisualizationServer(port = 8080) {
2939
- try {
2940
- this.wss = new WebSocketServer({ port });
2941
- logger.info(`[Visualizer] WebSocket server started on port ${port}`);
2942
- this.timeManager = new TimeManager(/* @__PURE__ */ new Date());
2943
- this.timeManager.onUpdate((julianDate, date) => {
2944
- this.updateTraits(julianDate);
2945
- this.broadcast("time_update", {
2946
- julianDate,
2947
- date: date.toISOString(),
2948
- timeScale: this.timeManager.getTimeScale(),
2949
- isPaused: this.timeManager.getIsPaused()
2950
- });
2951
- });
2952
- this.timeManager.start();
2953
- this.updateTraits(this.timeManager.getJulianDate());
2954
- this.wss.on("connection", (ws) => {
2955
- logger.info("[Visualizer] Client connected");
2956
- const orbs = Array.from(this.context.variables.entries()).filter(
2957
- ([_, v]) => v && typeof v === "object" && v.__type === "orb"
2958
- ).map(([id, v]) => {
2959
- const orbData = v;
2960
- return {
2961
- id,
2962
- name: orbData.name || id,
2963
- position: Array.isArray(orbData.position) ? { x: orbData.position[0], y: orbData.position[1], z: orbData.position[2] } : orbData.position,
2964
- properties: orbData.properties || {},
2965
- hologram: orbData.hologram || (() => {
2966
- const props = orbData.properties;
2967
- return {
2968
- color: props?.color || "#ffffff",
2969
- size: props?.size || props?.scale || 1,
2970
- shape: props?.geometry || "sphere",
2971
- glow: props?.glow || false
2972
- };
2973
- })(),
2974
- traits: orbData.traits || []
2975
- };
2976
- });
2977
- ws.send(
2978
- JSON.stringify({
2979
- type: "init",
2980
- orbs,
2981
- time: this.timeManager ? this.timeManager.getState() : null
2982
- })
2983
- );
2984
- ws.on("message", (message) => {
2985
- try {
2986
- const data = JSON.parse(message.toString());
2987
- if (data.type === "time_control") {
2988
- this.handleTimeControl(data.command, data.value);
2989
- }
2990
- } catch (e) {
2991
- logger.error("[Visualizer] Failed to parse message", { error: String(e) });
2992
- }
2993
- });
2994
- });
2995
- } catch (error) {
2996
- logger.error("[Visualizer] Failed to start server", { error: String(error) });
2997
- }
2998
- }
2999
- /**
3000
- * Handle time control commands from visualizer
3001
- */
3002
- handleTimeControl(command, value) {
3003
- if (!this.timeManager) return;
3004
- switch (command) {
3005
- case "play":
3006
- this.timeManager.play();
3007
- break;
3008
- case "pause":
3009
- this.timeManager.pause();
3010
- break;
3011
- case "toggle":
3012
- this.timeManager.togglePause();
3013
- break;
3014
- case "setSpeed":
3015
- if (typeof value === "number") {
3016
- this.timeManager.setTimeScale(value);
3017
- }
3018
- break;
3019
- case "setDate":
3020
- if (value) {
3021
- this.timeManager.setDate(new Date(value));
3022
- }
3023
- break;
3024
- case "syncRealTime":
3025
- this.timeManager.setDate(/* @__PURE__ */ new Date());
3026
- this.timeManager.setTimeScale(1);
3027
- this.timeManager.play();
3028
- break;
3029
- }
3030
- }
3031
- broadcast(type, payload) {
3032
- if (!this.wss) return;
3033
- const message = JSON.stringify({ type, payload });
3034
- this.wss.clients.forEach((client) => {
3035
- if (client.readyState === WebSocket.OPEN) {
3036
- client.send(message);
3037
- }
3038
- });
3039
- }
3040
- // ============================================================================
3041
- // Public API
3042
- // ============================================================================
3043
- getParticleSystems() {
3044
- return new Map(this.particleSystems);
3045
- }
3046
- updateParticles(deltaTime) {
3047
- for (const [name, system] of this.particleSystems) {
3048
- system.lifetime -= deltaTime;
3049
- system.particles.forEach((particle) => {
3050
- particle.x += (Math.random() - 0.5) * system.speed;
3051
- particle.y += (Math.random() - 0.5) * system.speed;
3052
- particle.z += (Math.random() - 0.5) * system.speed;
3053
- });
3054
- if (system.lifetime <= 0) {
3055
- this.particleSystems.delete(name);
3056
- }
3057
- }
3058
- }
3059
- getContext() {
3060
- return { ...this.context };
3061
- }
3062
- getUIElements() {
3063
- return new Map(this.uiElements);
3064
- }
3065
- getUIElement(name) {
3066
- return this.uiElements.get(name);
3067
- }
3068
- getAnimations() {
3069
- return new Map(this.animations);
3070
- }
3071
- reset() {
3072
- this.context = this.createEmptyContext();
3073
- this.currentScope = { variables: this.context.variables };
3074
- this.callStack = [];
3075
- this.particleSystems.clear();
3076
- this.executionHistory = [];
3077
- this.eventHandlers.clear();
3078
- this.animations.clear();
3079
- this.uiElements.clear();
3080
- }
3081
- createEmptyContext() {
3082
- return {
3083
- variables: /* @__PURE__ */ new Map(),
3084
- functions: /* @__PURE__ */ new Map(),
3085
- exports: /* @__PURE__ */ new Map(),
3086
- connections: [],
3087
- spatialMemory: /* @__PURE__ */ new Map(),
3088
- hologramState: /* @__PURE__ */ new Map(),
3089
- executionStack: [],
3090
- currentScale: 1,
3091
- scaleMagnitude: "standard",
3092
- focusHistory: [],
3093
- environment: {},
3094
- templates: /* @__PURE__ */ new Map(),
3095
- // HS+ State
3096
- state: createState({}),
3097
- // Phase 13: State Machines
3098
- stateMachines: /* @__PURE__ */ new Map(),
3099
- // Narrative & Story State
3100
- quests: /* @__PURE__ */ new Map(),
3101
- completedQuests: /* @__PURE__ */ new Set()
3102
- };
3103
- }
3104
- async executeScale(node) {
3105
- const parentScale = this.context.currentScale;
3106
- this.context.currentScale *= node.multiplier;
3107
- this.context.scaleMagnitude = node.magnitude;
3108
- logger.info("Scale context entering", {
3109
- magnitude: node.magnitude,
3110
- multiplier: this.context.currentScale
3111
- });
3112
- this.emit("scale:change", { multiplier: this.context.currentScale, magnitude: node.magnitude });
3113
- const results = await this.executeProgram(node.body, this.context.executionStack.length);
3114
- this.context.currentScale = parentScale;
3115
- this.emit("scale:change", { multiplier: this.context.currentScale });
3116
- return {
3117
- success: results.every((r) => r.success),
3118
- output: `Executed scale block: ${node.magnitude}`
3119
- };
3120
- }
3121
- async executeFocus(node) {
3122
- this.context.focusHistory.push(node.target);
3123
- const results = await this.executeProgram(node.body, this.context.executionStack.length);
3124
- return {
3125
- success: results.every((r) => r.success),
3126
- output: `Focused on ${node.target}`
3127
- };
3128
- }
3129
- async executeEnvironment(node) {
3130
- this.context.environment = { ...this.context.environment, ...node.settings };
3131
- return { success: true, output: "Environment updated" };
3132
- }
3133
- async executeComposition(node) {
3134
- if (node.body) {
3135
- const systemResults = await this.executeProgram(
3136
- node.body.systems,
3137
- this.context.executionStack.length
3138
- );
3139
- const configResults = await this.executeProgram(
3140
- node.body.configs,
3141
- this.context.executionStack.length
3142
- );
3143
- const childrenResults = await this.executeProgram(
3144
- node.body.children,
3145
- this.context.executionStack.length
3146
- );
3147
- const allResults = [...systemResults, ...configResults, ...childrenResults];
3148
- return {
3149
- success: allResults.every((r) => r.success),
3150
- output: `Composition ${node.name} executed with specialized blocks`
3151
- };
3152
- }
3153
- return {
3154
- success: (await this.executeProgram(node.children, this.context.executionStack.length)).every(
3155
- (r) => r.success
3156
- ),
3157
- output: `Composition ${node.name} executed`
3158
- };
3159
- }
3160
- resolveHoloValue(value) {
3161
- if (value === null) return null;
3162
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
3163
- return value;
3164
- }
3165
- if (Array.isArray(value)) {
3166
- return value.map((e) => this.resolveHoloValue(e));
3167
- }
3168
- if (value.__bind) {
3169
- return value;
3170
- }
3171
- const obj = {};
3172
- for (const k in value) {
3173
- obj[k] = this.resolveHoloValue(value[k]);
3174
- }
3175
- return obj;
3176
- }
3177
- async executeHoloComposition(node) {
3178
- for (const template of node.templates) {
3179
- await this.executeHoloTemplate(template);
3180
- }
3181
- if (node.environment) {
3182
- const envSettings = {};
3183
- for (const prop of node.environment.properties) {
3184
- envSettings[prop.key] = this.resolveHoloValue(prop.value);
3185
- }
3186
- this.context.environment = { ...this.context.environment, ...envSettings };
3187
- }
3188
- const results = [];
3189
- for (const object of node.objects) {
3190
- results.push(await this.executeHoloObject(object));
3191
- }
3192
- return {
3193
- success: results.every((r) => r.success),
3194
- output: `HoloComposition ${node.name} executed`
3195
- };
3196
- }
3197
- async executeHoloTemplate(node) {
3198
- this.context.templates.set(node.name, node);
3199
- return { success: true, output: `Template ${node.name} registered` };
3200
- }
3201
- async executeHoloObject(node) {
3202
- const properties = {};
3203
- for (const prop of node.properties) {
3204
- properties[prop.key] = this.resolveHoloValue(prop.value);
3205
- }
3206
- if (node.state) {
3207
- for (const prop of node.state.properties) {
3208
- properties[prop.key] = this.resolveHoloValue(prop.value);
3209
- }
3210
- }
3211
- const position = properties.position;
3212
- const hologram = {
3213
- shape: properties.geometry || "sphere",
3214
- color: properties.color || "#ffffff",
3215
- size: properties.scale || properties.size || 1,
3216
- glow: properties.glow || false,
3217
- interactive: properties.interactive !== false
3218
- };
3219
- const orbNode = {
3220
- type: "orb",
3221
- name: node.name,
3222
- position,
3223
- // Direct property for executeOrb
3224
- hologram,
3225
- // Direct property for executeOrb
3226
- properties,
3227
- // @ts-expect-error
3228
- directives: [
3229
- ...node.directives || [],
3230
- ...(node.traits || []).map((t) => ({ type: "trait", name: t.name, ...t.config })),
3231
- ...node.template ? this.context.templates.get(node.template)?.directives || [] : []
3232
- // Inherit template directives/traits
3233
- ],
3234
- traits: new Map((node.traits || []).map((t) => [t.name, t.config])),
3235
- children: node.children || []
3236
- };
3237
- if (node.template) {
3238
- const tpl = this.context.templates.get(node.template);
3239
- if (tpl) {
3240
- if (tpl.state) {
3241
- for (const prop of tpl.state.properties) {
3242
- if (properties[prop.key] === void 0) {
3243
- properties[prop.key] = this.resolveHoloValue(prop.value);
3244
- }
3245
- }
3246
- }
3247
- for (const prop of tpl.properties) {
3248
- if (properties[prop.key] === void 0) {
3249
- properties[prop.key] = this.resolveHoloValue(prop.value);
3250
- }
3251
- }
3252
- }
3253
- }
3254
- return this.executeOrb(orbNode);
3255
- }
3256
- /**
3257
- * Execute a block of HoloStatements (HoloNode AST)
3258
- */
3259
- async executeHoloProgram(statements, scopeOverride) {
3260
- const results = [];
3261
- telemetry.setGauge("execution_depth", this.context.executionStack.length);
3262
- for (const stmt of statements) {
3263
- telemetry.incrementCounter("statements_executed", 1, { type: stmt.type });
3264
- const res = await telemetry.measureLatency(
3265
- `execute_stmt_${stmt.type}`,
3266
- () => this.executeHoloStatement(stmt, scopeOverride)
3267
- );
3268
- results.push(res);
3269
- const last = results[results.length - 1];
3270
- if (last.success && last.output !== void 0 && stmt.type === "ReturnStatement") {
3271
- break;
3272
- }
3273
- }
3274
- return results;
3275
- }
3276
- async executeHoloStatement(stmt, scopeOverride) {
3277
- try {
3278
- switch (stmt.type) {
3279
- case "Assignment": {
3280
- const value = await this.evaluateHoloExpression(stmt.value, scopeOverride);
3281
- let finalValue = value;
3282
- if (stmt.operator !== "=") {
3283
- const current = this.getVariable(stmt.target, scopeOverride);
3284
- if (stmt.operator === "+=")
3285
- finalValue = Number(current) + Number(value);
3286
- else if (stmt.operator === "-=")
3287
- finalValue = Number(current) - Number(value);
3288
- else if (stmt.operator === "*=")
3289
- finalValue = Number(current) * Number(value);
3290
- else if (stmt.operator === "/=")
3291
- finalValue = Number(current) / Number(value);
3292
- }
3293
- this.setVariable(stmt.target, finalValue, scopeOverride);
3294
- return { success: true };
3295
- }
3296
- case "IfStatement": {
3297
- const condition = await this.evaluateHoloExpression(stmt.condition, scopeOverride);
3298
- if (condition) {
3299
- await this.executeHoloProgram(stmt.consequent, scopeOverride);
3300
- } else if (stmt.alternate) {
3301
- await this.executeHoloProgram(stmt.alternate, scopeOverride);
3302
- }
3303
- return { success: true };
3304
- }
3305
- case "WhileStatement": {
3306
- const MAX_ITERATIONS = 1e3;
3307
- let iter = 0;
3308
- while (await this.evaluateHoloExpression(stmt.condition, scopeOverride)) {
3309
- if (iter++ > MAX_ITERATIONS) return { success: false, error: "Infinite loop" };
3310
- await this.executeHoloProgram(stmt.body, scopeOverride);
3311
- }
3312
- return { success: true };
3313
- }
3314
- case "ClassicForStatement": {
3315
- if (stmt.init) await this.executeHoloStatement(stmt.init, scopeOverride);
3316
- const MAX_ITERATIONS = 1e3;
3317
- let iter = 0;
3318
- while (!stmt.test || await this.evaluateHoloExpression(stmt.test, scopeOverride)) {
3319
- if (iter++ > MAX_ITERATIONS) return { success: false, error: "Infinite loop" };
3320
- await this.executeHoloProgram(stmt.body, scopeOverride);
3321
- if (stmt.update) await this.executeHoloStatement(stmt.update, scopeOverride);
3322
- }
3323
- return { success: true };
3324
- }
3325
- case "VariableDeclaration": {
3326
- const value = stmt.value ? await this.evaluateHoloExpression(stmt.value, scopeOverride) : void 0;
3327
- const scope = scopeOverride || this.currentScope;
3328
- scope.variables.set(stmt.name, value);
3329
- return { success: true };
3330
- }
3331
- case "EmitStatement": {
3332
- const data = stmt.data ? await this.evaluateHoloExpression(stmt.data, scopeOverride) : void 0;
3333
- this.emit(stmt.event, data);
3334
- return { success: true };
3335
- }
3336
- case "AwaitStatement": {
3337
- const value = await this.evaluateHoloExpression(stmt.expression, scopeOverride);
3338
- if (value instanceof Promise) await value;
3339
- return { success: true };
3340
- }
3341
- case "ReturnStatement": {
3342
- const value = stmt.value ? await this.evaluateHoloExpression(stmt.value, scopeOverride) : null;
3343
- return { success: true, output: value };
3344
- }
3345
- case "ExpressionStatement": {
3346
- const val = await this.evaluateHoloExpression(stmt.expression, scopeOverride);
3347
- return { success: true, output: val };
3348
- }
3349
- default:
3350
- return {
3351
- success: false,
3352
- error: `Unknown stmt type: ${stmt.type}`
3353
- };
3354
- }
3355
- } catch (err) {
3356
- const errMsg = err instanceof Error ? err.message : String(err);
3357
- console.error(`[EXEC_ERROR] Statement ${stmt.type} failed:`, errMsg);
3358
- return { success: false, error: errMsg };
3359
- }
3360
- }
3361
- async evaluateHoloExpression(expr, scopeOverride) {
3362
- switch (expr.type) {
3363
- case "Literal":
3364
- return expr.value;
3365
- case "Identifier":
3366
- return this.getVariable(expr.name, scopeOverride);
3367
- case "MemberExpression": {
3368
- const obj = await this.evaluateHoloExpression(expr.object, scopeOverride);
3369
- if (obj && typeof obj === "object") {
3370
- return obj[expr.property];
3371
- }
3372
- return void 0;
3373
- }
3374
- case "CallExpression": {
3375
- if (!Array.isArray(expr.arguments)) {
3376
- console.error("[CRITICAL] arguments is not an array for", JSON.stringify(expr));
3377
- return void 0;
3378
- }
3379
- const callee = await this.evaluateHoloExpression(expr.callee, scopeOverride);
3380
- const args = await Promise.all(
3381
- expr.arguments.map((a) => this.evaluateHoloExpression(a, scopeOverride))
3382
- );
3383
- if (typeof callee === "function") {
3384
- return callee(...args);
3385
- }
3386
- if (expr.callee.type === "Identifier") {
3387
- const result = await this.callFunction(expr.callee.name, args);
3388
- return result.output;
3389
- }
3390
- return void 0;
3391
- }
3392
- case "BinaryExpression": {
3393
- const left = await this.evaluateHoloExpression(expr.left, scopeOverride);
3394
- const right = await this.evaluateHoloExpression(expr.right, scopeOverride);
3395
- switch (expr.operator) {
3396
- case "+":
3397
- return Number(left) + Number(right);
3398
- case "-":
3399
- return Number(left) - Number(right);
3400
- case "*":
3401
- return Number(left) * Number(right);
3402
- case "/":
3403
- return Number(left) / Number(right);
3404
- case "==":
3405
- return left == right;
3406
- case "===":
3407
- return left === right;
3408
- case "!=":
3409
- return left != right;
3410
- case "!==":
3411
- return left !== right;
3412
- case "<":
3413
- return Number(left) < Number(right);
3414
- case ">":
3415
- return Number(left) > Number(right);
3416
- case "<=":
3417
- return Number(left) <= Number(right);
3418
- case ">=":
3419
- return Number(left) >= Number(right);
3420
- case "&&":
3421
- return left && right;
3422
- case "||":
3423
- return left || right;
3424
- default:
3425
- return void 0;
3426
- }
3427
- }
3428
- case "ConditionalExpression": {
3429
- const test = await this.evaluateHoloExpression(expr.test, scopeOverride);
3430
- return test ? await this.evaluateHoloExpression(expr.consequent, scopeOverride) : await this.evaluateHoloExpression(expr.alternate, scopeOverride);
3431
- }
3432
- case "UpdateExpression": {
3433
- const val = await this.evaluateHoloExpression(expr.argument, scopeOverride);
3434
- const newVal = expr.operator === "++" ? val + 1 : val - 1;
3435
- const path2 = this.getMemberPath(expr.argument);
3436
- if (path2) {
3437
- this.setVariable(path2, newVal, scopeOverride);
3438
- }
3439
- return expr.prefix ? newVal : val;
3440
- }
3441
- case "ArrayExpression": {
3442
- return await Promise.all(
3443
- expr.elements.map((e) => this.evaluateHoloExpression(e, scopeOverride))
3444
- );
3445
- }
3446
- case "ObjectExpression": {
3447
- const obj = {};
3448
- for (const prop of expr.properties) {
3449
- obj[prop.key] = await this.evaluateHoloExpression(prop.value, scopeOverride);
3450
- }
3451
- return obj;
3452
- }
3453
- default:
3454
- return void 0;
3455
- }
3456
- }
3457
- getMemberPath(expr) {
3458
- if (expr.type === "Identifier") return expr.name;
3459
- if (expr.type === "MemberExpression") {
3460
- const parentPath = this.getMemberPath(expr.object);
3461
- if (parentPath) return `${parentPath}.${expr.property}`;
3462
- }
3463
- return null;
3464
- }
3465
- async executeSystem(node) {
3466
- const startTime = Date.now();
3467
- const systemId = node.id;
3468
- const properties = node.properties;
3469
- logger.info(`[Zero-Config] Provisioning system: ${systemId}`, properties);
3470
- switch (systemId) {
3471
- case "Networking":
3472
- return this.setupNetworking(node);
3473
- case "Physics":
3474
- return this.setupPhysics(node);
3475
- default:
3476
- logger.warn(`[Zero-Config] Unknown system: ${systemId}`);
3477
- return {
3478
- success: true,
3479
- output: `System ${systemId} not recognized, skipping provisioning`,
3480
- executionTime: Date.now() - startTime
3481
- };
3482
- }
3483
- }
3484
- async executeCoreConfig(node) {
3485
- const startTime = Date.now();
3486
- logger.info("[Zero-Config] Applying core configuration", node.properties);
3487
- for (const [key, value] of Object.entries(node.properties)) {
3488
- this.context.environment[key] = value;
3489
- }
3490
- return {
3491
- success: true,
3492
- output: "Core configuration applied",
3493
- executionTime: Date.now() - startTime
3494
- };
3495
- }
3496
- // =========================================================================
3497
- // Control Flow Execution
3498
- // =========================================================================
3499
- /**
3500
- * Execute a for loop: @for item in collection { ... }
3501
- */
3502
- async executeForLoop(node) {
3503
- const startTime = Date.now();
3504
- const { variable, iterable, body } = node;
3505
- try {
3506
- const collection = this.evaluateExpression(String(iterable));
3507
- if (!Array.isArray(collection) && typeof collection !== "object") {
3508
- return {
3509
- success: false,
3510
- error: `Cannot iterate over non-iterable: ${typeof collection}`,
3511
- executionTime: Date.now() - startTime
3512
- };
3513
- }
3514
- const items = Array.isArray(collection) ? collection : collection && typeof collection === "object" ? Object.entries(collection) : [];
3515
- let lastResult = { success: true, output: null };
3516
- for (const item of items) {
3517
- this.context.variables.set(variable, item);
3518
- for (const bodyNode of body) {
3519
- lastResult = await this.executeNode(bodyNode);
3520
- if (!lastResult.success) break;
3521
- }
3522
- if (!lastResult.success) break;
3523
- }
3524
- this.context.variables.delete(variable);
3525
- return {
3526
- success: true,
3527
- output: lastResult.output,
3528
- executionTime: Date.now() - startTime
3529
- };
3530
- } catch (error) {
3531
- return {
3532
- success: false,
3533
- error: `For loop error: ${error instanceof Error ? error.message : String(error)}`,
3534
- executionTime: Date.now() - startTime
3535
- };
3536
- }
3537
- }
3538
- /**
3539
- * Execute a forEach loop: @forEach item in collection { ... }
3540
- */
3541
- async executeForEachLoop(node) {
3542
- return this.executeForLoop({
3543
- variable: node.variable,
3544
- iterable: node.collection,
3545
- body: node.body
3546
- });
3547
- }
3548
- /**
3549
- * Execute a while loop: @while condition { ... }
3550
- */
3551
- async executeWhileLoop(node) {
3552
- const startTime = Date.now();
3553
- const { condition, body } = node;
3554
- const MAX_ITERATIONS = 1e4;
3555
- try {
3556
- let iterations = 0;
3557
- let lastResult = { success: true, output: null };
3558
- while (this.evaluateCondition(String(condition))) {
3559
- iterations++;
3560
- if (iterations > MAX_ITERATIONS) {
3561
- return {
3562
- success: false,
3563
- error: `While loop exceeded maximum iterations (${MAX_ITERATIONS})`,
3564
- executionTime: Date.now() - startTime
3565
- };
3566
- }
3567
- for (const bodyNode of body) {
3568
- lastResult = await this.executeNode(bodyNode);
3569
- if (!lastResult.success) break;
3570
- }
3571
- if (!lastResult.success) break;
3572
- }
3573
- return {
3574
- success: true,
3575
- output: lastResult.output,
3576
- executionTime: Date.now() - startTime
3577
- };
3578
- } catch (error) {
3579
- return {
3580
- success: false,
3581
- error: `While loop error: ${error instanceof Error ? error.message : String(error)}`,
3582
- executionTime: Date.now() - startTime
3583
- };
3584
- }
3585
- }
3586
- /**
3587
- * Execute an if statement: @if condition { ... } @else { ... }
3588
- */
3589
- async executeIfStatement(node) {
3590
- const startTime = Date.now();
3591
- const { condition, body, elseBody } = node;
3592
- try {
3593
- const conditionResult = this.evaluateCondition(String(condition));
3594
- const branchToExecute = conditionResult ? body : elseBody || [];
3595
- let lastResult = { success: true, output: null };
3596
- for (const bodyNode of branchToExecute) {
3597
- lastResult = await this.executeNode(bodyNode);
3598
- if (!lastResult.success) break;
3599
- }
3600
- return {
3601
- success: true,
3602
- output: lastResult.output,
3603
- executionTime: Date.now() - startTime
3604
- };
3605
- } catch (error) {
3606
- return {
3607
- success: false,
3608
- error: `If statement error: ${error instanceof Error ? error.message : String(error)}`,
3609
- executionTime: Date.now() - startTime
3610
- };
3611
- }
3612
- }
3613
- /**
3614
- * Execute a match expression: @match subject { pattern => result, ... }
3615
- */
3616
- async executeMatch(node) {
3617
- const startTime = Date.now();
3618
- const { subject, cases } = node;
3619
- try {
3620
- const subjectValue = this.evaluateExpression(String(subject));
3621
- for (const matchCase of cases || []) {
3622
- const patternValue = this.evaluateExpression(String(matchCase.pattern));
3623
- if (this.patternMatches(patternValue, subjectValue)) {
3624
- if (matchCase.guard && !this.evaluateCondition(String(matchCase.guard))) {
3625
- continue;
3626
- }
3627
- if (Array.isArray(matchCase.body)) {
3628
- let lastResult = { success: true, output: null };
3629
- for (const bodyNode of matchCase.body) {
3630
- lastResult = await this.executeNode(bodyNode);
3631
- if (!lastResult.success) break;
3632
- }
3633
- return lastResult;
3634
- } else {
3635
- const result = this.evaluateExpression(String(matchCase.body));
3636
- return { success: true, output: result, executionTime: Date.now() - startTime };
3637
- }
3638
- }
3639
- }
3640
- return {
3641
- success: false,
3642
- error: "No pattern matched",
3643
- executionTime: Date.now() - startTime
3644
- };
3645
- } catch (error) {
3646
- return {
3647
- success: false,
3648
- error: `Match expression error: ${error instanceof Error ? error.message : String(error)}`,
3649
- executionTime: Date.now() - startTime
3650
- };
3651
- }
3652
- }
3653
- /**
3654
- * Check if a pattern matches a value
3655
- */
3656
- patternMatches(pattern, value) {
3657
- if (pattern === "_" || pattern === "else" || pattern === "default") {
3658
- return true;
3659
- }
3660
- if (pattern === value) {
3661
- return true;
3662
- }
3663
- if (pattern === "string" && typeof value === "string") return true;
3664
- if (pattern === "number" && typeof value === "number") return true;
3665
- if (pattern === "boolean" && typeof value === "boolean") return true;
3666
- if (pattern === "array" && Array.isArray(value)) return true;
3667
- if (pattern === "object" && typeof value === "object" && value !== null) return true;
3668
- if (Array.isArray(pattern) && pattern.length === 2) {
3669
- const [min, max] = pattern;
3670
- if (typeof value === "number" && typeof min === "number" && typeof max === "number" && value >= min && value <= max) {
3671
- return true;
3672
- }
3673
- }
3674
- return false;
3675
- }
3676
- async executeNarrative(node) {
3677
- const startTime = Date.now();
3678
- logger.info(`[Narrative] Initializing narrative: ${node.id}`);
3679
- for (const quest of node.quests) {
3680
- this.context.quests.set(quest.id, quest);
3681
- }
3682
- if (node.startNode) {
3683
- logger.info(`[Narrative] Auto-starting at node: ${node.startNode}`);
3684
- }
3685
- return {
3686
- success: true,
3687
- output: `Narrative ${node.id} initialized with ${node.quests.length} quests`,
3688
- executionTime: Date.now() - startTime
3689
- };
3690
- }
3691
- async executeQuest(node) {
3692
- const startTime = Date.now();
3693
- logger.info(`[Narrative] Starting quest: ${node.title}`, { questId: node.id });
3694
- this.context.activeQuestId = node.id;
3695
- this.context.quests.set(node.id, node);
3696
- return {
3697
- success: true,
3698
- output: `Quest ${node.id} started`,
3699
- executionTime: Date.now() - startTime
3700
- };
3701
- }
3702
- async executeDialogue(node) {
3703
- const startTime = Date.now();
3704
- logger.info(`[Narrative] Dialogue: ${node.speaker} says "${node.text}"`);
3705
- this.context.dialogueState = {
3706
- currentNodeId: node.id,
3707
- speaker: node.speaker
3708
- };
3709
- return {
3710
- success: true,
3711
- output: `Dialogue node ${node.id} executed`,
3712
- executionTime: Date.now() - startTime
3713
- };
3714
- }
3715
- async executeVisualMetadata(node) {
3716
- logger.info(`[Metadata] Visual metadata processed`, node.properties);
3717
- return { success: true, output: "Visual metadata applied" };
3718
- }
3719
- async setupNetworking(node) {
3720
- const startTime = Date.now();
3721
- logger.info("[Networking] Initializing multiplayer fabric...", node.properties);
3722
- return {
3723
- success: true,
3724
- output: "Networking system provisioned",
3725
- executionTime: Date.now() - startTime
3726
- };
3727
- }
3728
- async setupPhysics(node) {
3729
- const startTime = Date.now();
3730
- logger.info("[Physics] Initializing spatial simulation engine...", node.properties);
3731
- return {
3732
- success: true,
3733
- output: "Physics system provisioned",
3734
- executionTime: Date.now() - startTime
3735
- };
3736
- }
3737
- async executeTemplate(node) {
3738
- const existing = this.context.templates.get(node.name);
3739
- if (existing) {
3740
- node._previousVersion = existing.version;
3741
- }
3742
- this.context.templates.set(node.name, node);
3743
- return {
3744
- success: true,
3745
- output: `Template ${node.name} registered (v${node.version || "unknown"})`
3746
- };
3747
- }
3748
- /**
3749
- * Execute a migration script for an object
3750
- */
3751
- async executeMigrationBlock(orb, migration) {
3752
- logger.info(`Running migration for ${orb.name}...`);
3753
- const previousScope = this.currentScope;
3754
- this.currentScope = {
3755
- variables: /* @__PURE__ */ new Map([
3756
- ["this", orb],
3757
- ["self", orb]
3758
- ]),
3759
- parent: previousScope
3760
- };
3761
- try {
3762
- const parser = new HoloScriptCodeParser();
3763
- const result = parser.parse(migration.body);
3764
- if (result.errors.length > 0) {
3765
- logger.error(`Migration parse errors for ${orb.name}:`, { errors: result.errors });
3766
- return;
3767
- }
3768
- await this.executeProgram(result.ast, 0);
3769
- } finally {
3770
- this.currentScope = previousScope;
3771
- }
3772
- logger.info(`Migration complete for ${orb.name}`);
3773
- }
3774
- async executeServerNode(node) {
3775
- if (this.context.mode === "public") {
3776
- return {
3777
- success: false,
3778
- error: "SecurityViolation: Server creation blocked in public mode.",
3779
- executionTime: 0
3780
- };
3781
- }
3782
- logger.info(`Starting server on port ${node.port}`);
3783
- return {
3784
- success: true,
3785
- output: `Server listening on port ${node.port}`,
3786
- hologram: node.hologram,
3787
- executionTime: 0
3788
- };
3789
- }
3790
- async executeDatabaseNode(node) {
3791
- if (this.context.mode === "public") {
3792
- return {
3793
- success: false,
3794
- error: "SecurityViolation: DB access blocked in public mode.",
3795
- executionTime: 0
3796
- };
3797
- }
3798
- logger.info(`Executing Query: ${node.query}`);
3799
- return {
3800
- success: true,
3801
- output: `Query executed: ${node.query}`,
3802
- hologram: node.hologram,
3803
- executionTime: 0
3804
- };
3805
- }
3806
- async executeFetchNode(node) {
3807
- if (this.context.mode === "public") {
3808
- return {
3809
- success: false,
3810
- error: "SecurityViolation: External fetch blocked in public mode.",
3811
- executionTime: 0
3812
- };
3813
- }
3814
- logger.info(`Fetching: ${node.url}`);
3815
- return {
3816
- success: true,
3817
- output: `Fetched data from ${node.url}`,
3818
- hologram: node.hologram,
3819
- executionTime: 0
3820
- };
3821
- }
3822
- async executeTarget(node) {
3823
- const target = this.context.functions.get(node.target);
3824
- if (!target) {
3825
- return {
3826
- success: false,
3827
- error: `Function ${node.target} not found`,
3828
- executionTime: 0
3829
- };
3830
- }
3831
- const result = await this.executeFunction(target);
3832
- this.createExecutionEffect(node.target, target.position || { x: 0, y: 0, z: 0 });
3833
- return {
3834
- success: true,
3835
- output: `Executed ${node.target}`,
3836
- hologram: {
3837
- shape: "sphere",
3838
- color: "#ff4500",
3839
- size: 1.2,
3840
- glow: true,
3841
- interactive: false
3842
- },
3843
- executionTime: result.executionTime
3844
- };
3845
- }
3846
- async executeStateDeclaration(node) {
3847
- const stateDirective = node.directives?.find((d) => d.type === "state");
3848
- if (stateDirective) {
3849
- this.context.state.update(stateDirective.body);
3850
- }
3851
- return { success: true, output: "State updated" };
3852
- }
3853
- // ============================================================================
3854
- // Memory Syntactic Execution (Phase 7 / EVOLVE)
3855
- // ============================================================================
3856
- async executeMemory(node) {
3857
- const startTime = Date.now();
3858
- logger.info(`[Memory] Initializing memory block: ${node.name}`);
3859
- const memoryState = {
3860
- id: node.name,
3861
- type: "agent-memory"
3862
- };
3863
- if (node.semantic) {
3864
- const semResult = await this.executeNode(node.semantic);
3865
- if (semResult.success) memoryState.semantic = semResult.output;
3866
- }
3867
- if (node.episodic) {
3868
- const epResult = await this.executeNode(node.episodic);
3869
- if (epResult.success) memoryState.episodic = epResult.output;
3870
- }
3871
- if (node.procedural) {
3872
- const procResult = await this.executeNode(node.procedural);
3873
- if (procResult.success) memoryState.procedural = procResult.output;
3874
- }
3875
- this.context.variables.set(node.name, memoryState);
3876
- this.emit("memory_initialized", { memoryId: node.name, config: memoryState });
3877
- return {
3878
- success: true,
3879
- output: memoryState,
3880
- executionTime: Date.now() - startTime
3881
- };
3882
- }
3883
- loadSkill(skill) {
3884
- logger.info(`[Procedural] Loading skill: ${skill.name} (${skill.id})`);
3885
- const existing = this.proceduralSkills.get(skill.id);
3886
- if (existing) {
3887
- skill.successRate = (existing.successRate + (skill.successRate || 0)) / 2;
3888
- } else {
3889
- skill.successRate = skill.successRate || 0;
3890
- }
3891
- this.proceduralSkills.set(skill.id, skill);
3892
- StateSynchronizer.getInstance().broadcastSkill(skill);
3893
- }
3894
- async executeSkill(skillId, contextVariables = {}) {
3895
- const skill = this.proceduralSkills.get(skillId);
3896
- if (!skill) {
3897
- throw new Error(`[Procedural] Skill '${skillId}' not found.`);
3898
- }
3899
- logger.info(`[Procedural] Executing skill: ${skill.name}`);
3900
- const startTime = Date.now();
3901
- const previousScope = this.currentScope;
3902
- this.currentScope = { variables: new Map(previousScope.variables), parent: previousScope };
3903
- for (const [key, val] of Object.entries(contextVariables)) {
3904
- this.currentScope.variables.set(key, val);
3905
- }
3906
- try {
3907
- const result = await this.executeNode(skill.action);
3908
- if (result.success) {
3909
- skill.successRate = Math.min(100, skill.successRate + 1);
3910
- } else {
3911
- skill.successRate = Math.max(0, skill.successRate - 1);
3912
- }
3913
- StateSynchronizer.getInstance().broadcastSkill(skill);
3914
- return {
3915
- ...result,
3916
- executionTime: Date.now() - startTime
3917
- };
3918
- } finally {
3919
- this.currentScope = previousScope;
3920
- }
3921
- }
3922
- async executeMemoryDefinition(node) {
3923
- const startTime = Date.now();
3924
- const config = {};
3925
- for (const [key, val] of Object.entries(node.properties || {})) {
3926
- if (typeof val === "string") {
3927
- config[key] = this.evaluateExpression(val);
3928
- } else {
3929
- config[key] = val;
3930
- }
3931
- }
3932
- return {
3933
- success: true,
3934
- output: {
3935
- type: node.type,
3936
- config
3937
- },
3938
- executionTime: Date.now() - startTime
3939
- };
3940
- }
3941
- applyDirectives(node) {
3942
- if (!node.directives) return;
3943
- for (const d of node.directives) {
3944
- if (d.type === "trait") {
3945
- logger.info(`Applying trait ${d.name} to ${node.type}`);
3946
- const handler = this.traitHandlers.get(d.name);
3947
- if (handler) {
3948
- handler.onAttach?.(node, d.config || {}, {
3949
- emit: (event, payload) => this.emit(event, payload),
3950
- getScaleMultiplier: () => this.context.currentScale || 1
3951
- });
3952
- }
3953
- if (d.name === "chat") {
3954
- this.emit("show-chat", d.config);
3955
- }
3956
- } else if (d.type === "state") {
3957
- if (node && node.__type === "orb") {
3958
- const stateBody = d.body;
3959
- const existingProps = node.properties || {};
3960
- for (const [key, val] of Object.entries(stateBody)) {
3961
- if (existingProps[key] === void 0) {
3962
- existingProps[key] = val;
3963
- }
3964
- }
3965
- node.properties = existingProps;
3966
- }
3967
- this.context.state.update(d.body);
3968
- } else if (d.type === "lifecycle") {
3969
- if (d.hook === "on_mount" || d.hook === "mount") {
3970
- this.evaluateExpression(d.body);
3971
- }
3972
- }
3973
- }
3974
- }
3975
- getExecutionHistory() {
3976
- return [...this.executionHistory];
3977
- }
3978
- getHologramStates() {
3979
- return new Map(this.context.hologramState);
3980
- }
3981
- getCallStack() {
3982
- return [...this.callStack];
3983
- }
3984
- getState() {
3985
- return this.context.state.getSnapshot();
3986
- }
3987
- getRootScope() {
3988
- return this.currentScope;
3989
- }
3990
- isAgent(node) {
3991
- return !!node.directives?.some(
3992
- (d) => d.type === "trait" && (d.name === "llm_agent" || d.name === "agent" || d.name === "companion")
3993
- );
3994
- }
3995
- /**
3996
- * Get current simulation time (Julian date) for orbital calculations
3997
- */
3998
- getSimulationTime() {
3999
- return this.timeManager?.getJulianDate() || 0;
4000
- }
4001
- /**
4002
- * Set orb position and broadcast update
4003
- */
4004
- setOrbPosition(orbName, position) {
4005
- const orb = this.context.variables.get(orbName);
4006
- if (orb && typeof orb === "object" && orb.__type === "orb") {
4007
- orb.position = position;
4008
- this.broadcast("orb_update", {
4009
- orb: {
4010
- id: orbName,
4011
- name: orbName,
4012
- position
4013
- }
4014
- });
4015
- }
4016
- }
4017
- /**
4018
- * Update all orbs that have traits with an onUpdate method
4019
- */
4020
- updateTraits(julianDate) {
4021
- const delta = 1 / 60;
4022
- for (const [name, value] of this.context.variables.entries()) {
4023
- if (value && typeof value === "object" && value.__type === "orb") {
4024
- const orb = value;
4025
- if (orb.directives) {
4026
- for (const d of orb.directives || []) {
4027
- if (d.type === "trait") {
4028
- const handler = this.traitHandlers.get(d.name);
4029
- if (handler && handler.onUpdate) {
4030
- const traitNode = orb;
4031
- handler.onUpdate(
4032
- traitNode,
4033
- d.config || {},
4034
- {
4035
- emit: (event, payload) => {
4036
- if (event === "position_update") {
4037
- const posPayload = payload;
4038
- if (posPayload?.position) {
4039
- this.setOrbPosition(name, posPayload.position);
4040
- }
4041
- }
4042
- return this.emit(event, payload);
4043
- },
4044
- getScaleMultiplier: () => this.context.currentScale || 1,
4045
- julianDate,
4046
- getNode: (nodeName) => this.context.variables.get(nodeName),
4047
- getState: () => this.getState(),
4048
- setState: (updates) => this.context.state.update(updates)
4049
- },
4050
- delta
4051
- );
4052
- }
4053
- }
4054
- }
4055
- }
4056
- }
4057
- }
4058
- }
4059
- };
4060
- __decorateClass([
4061
- MethodMemoize(500)
4062
- ], HoloScriptRuntime.prototype, "getMemberPath", 1);
4063
-
4064
- export { EventBus, HoloScriptRuntime, PriorityScorer, SpatialSharder, StateSynchronizer, TransactionLog, getSharedEventBus, setSharedEventBus, telemetry };
4065
- //# sourceMappingURL=chunk-C2QHVHZF.js.map
4066
- //# sourceMappingURL=chunk-C2QHVHZF.js.map