@nodetool-ai/game-runtime 0.8.5 → 0.8.7

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 (57) hide show
  1. package/dist/.nodetool-build-stamp +1 -1
  2. package/dist/document-ops3d.d.ts +8 -0
  3. package/dist/document-ops3d.d.ts.map +1 -1
  4. package/dist/script-log.d.ts +2 -0
  5. package/dist/script-log.d.ts.map +1 -1
  6. package/dist/script-log.js +8 -0
  7. package/dist/script-log.js.map +1 -1
  8. package/dist/script-persistence.d.ts +5 -0
  9. package/dist/script-persistence.d.ts.map +1 -1
  10. package/dist/script-persistence.js +69 -0
  11. package/dist/script-persistence.js.map +1 -1
  12. package/dist/script-world.d.ts +21 -1
  13. package/dist/script-world.d.ts.map +1 -1
  14. package/dist/script-world.js +74 -15
  15. package/dist/script-world.js.map +1 -1
  16. package/dist/scripts.d.ts +8 -0
  17. package/dist/scripts.d.ts.map +1 -1
  18. package/dist/scripts.js +306 -111
  19. package/dist/scripts.js.map +1 -1
  20. package/dist/scripts3d.d.ts +2 -2
  21. package/dist/scripts3d.d.ts.map +1 -1
  22. package/dist/scripts3d.js +2 -2
  23. package/dist/scripts3d.js.map +1 -1
  24. package/dist/session.d.ts +5 -0
  25. package/dist/session.d.ts.map +1 -1
  26. package/dist/session.js +1 -1
  27. package/dist/session.js.map +1 -1
  28. package/dist/session3d.d.ts +7 -0
  29. package/dist/session3d.d.ts.map +1 -1
  30. package/dist/session3d.js +5 -1
  31. package/dist/session3d.js.map +1 -1
  32. package/dist/spatial3d/camera.js +2 -2
  33. package/dist/spatial3d/camera.js.map +1 -1
  34. package/dist/spatial3d/math.d.ts +5 -0
  35. package/dist/spatial3d/math.d.ts.map +1 -1
  36. package/dist/spatial3d/math.js +9 -0
  37. package/dist/spatial3d/math.js.map +1 -1
  38. package/dist/systems/animation3d.d.ts.map +1 -1
  39. package/dist/systems/animation3d.js +2 -1
  40. package/dist/systems/animation3d.js.map +1 -1
  41. package/dist/systems/gameplay3d.d.ts.map +1 -1
  42. package/dist/systems/gameplay3d.js +2 -1
  43. package/dist/systems/gameplay3d.js.map +1 -1
  44. package/dist/systems/input3d.d.ts.map +1 -1
  45. package/dist/systems/input3d.js +3 -2
  46. package/dist/systems/input3d.js.map +1 -1
  47. package/dist/systems/presentation3d.d.ts.map +1 -1
  48. package/dist/systems/presentation3d.js +41 -13
  49. package/dist/systems/presentation3d.js.map +1 -1
  50. package/dist/systems/scripts3d.d.ts.map +1 -1
  51. package/dist/systems/scripts3d.js +2 -1
  52. package/dist/systems/scripts3d.js.map +1 -1
  53. package/dist/validate3d.d.ts +0 -1
  54. package/dist/validate3d.d.ts.map +1 -1
  55. package/dist/validate3d.js +29 -0
  56. package/dist/validate3d.js.map +1 -1
  57. package/package.json +3 -3
package/dist/scripts.js CHANGED
@@ -4,13 +4,15 @@ import { GameScriptLogCollector, withGameScriptLogs } from "./script-log.js";
4
4
  import { GameScriptSaveCollector } from "./script-saves.js";
5
5
  import { defaultScriptCallClock, startScriptCallTimer } from "./script-clock.js";
6
6
  import { commitScriptHooks, planScriptHooks, scriptHookIssue, SCRIPT_LIFECYCLE_DISPATCH, SCRIPT_SYNCHRONOUS_RESULT } from "./script-lifecycle.js";
7
- import { canPersistGameScript } from "./script-persistence.js";
7
+ import { canPersistGameScript, canReuseGameScript } from "./script-persistence.js";
8
8
  import { gameScriptValue, scriptHandleResult } from "./script-transport.js";
9
- import { ScriptWorldSnapshot } from "./script-world.js";
9
+ import { createScriptWorldBinding, ScriptWorldSnapshot } from "./script-world.js";
10
10
  import { prefabScriptSourceKey, sceneScriptSourceKey, scriptSourceKey } from "./script-source.js";
11
11
  export { scriptSourceKey } from "./script-source.js";
12
12
  const encoder = new TextEncoder();
13
13
  const MAX_SCRIPT_CALL_MS = 20;
14
+ /** The world JSON a script receives when it reads `input.world`. The rest of the tick input keeps the 64 KiB limit. */
15
+ const MAX_SCRIPT_WORLD_BYTES = 1024 * 1024;
14
16
  const finite = z.number().finite();
15
17
  const color = z.string().regex(/^#[0-9a-fA-F]{6}$/);
16
18
  export const gameScriptCommand = z.discriminatedUnion("kind", [
@@ -42,8 +44,9 @@ function evaluate(context, code) {
42
44
  value.dispose();
43
45
  }
44
46
  }
45
- function evaluateSourceKind(context, source) {
46
- return evaluate(context, `((tag) => {
47
+ /** Strict evaluation is for realms that are reused between calls, where writes to frozen built-ins must throw. */
48
+ function evaluateSourceKind(context, source, strict = false) {
49
+ return evaluate(context, `${strict ? '"use strict";' : ""}((tag) => {
47
50
  globalThis.__gameScript = (${source});
48
51
  const check = (value, name) => {
49
52
  if (typeof value === "function" && tag(value) !== "[object Function]") {
@@ -68,11 +71,15 @@ function initializeContext(context, seed, helpers) {
68
71
  return state / 4294967296;
69
72
  };
70
73
  Object.defineProperty(random, "state", { get: () => state });
74
+ globalThis.__gameReseed = (seed) => { state = seed >>> 0; };
71
75
  return random;
72
76
  })(), writable: false, configurable: false
73
77
  });
74
78
  Object.defineProperty(Math, "random", { value: __gameRandom, writable: false, configurable: false });
75
- ${helpers}
79
+ ((reseed) => {
80
+ delete globalThis.__gameReseed;
81
+ return ${helpers};
82
+ })(globalThis.__gameReseed)
76
83
  `, "game-transport.js", { type: "global" }));
77
84
  }
78
85
  function interrupted(budget) {
@@ -89,12 +96,38 @@ function propsOf(table, id) {
89
96
  }
90
97
  function disposeRealm(realm) {
91
98
  realm.setWorldReader(undefined);
99
+ realm.setWorldText(undefined);
100
+ realm.worldBinding?.dispose();
92
101
  realm.worldGetter.dispose();
102
+ realm.worldText.dispose();
93
103
  realm.queryJson.dispose();
94
104
  realm.defineData.dispose();
95
105
  realm.invoke.dispose();
96
106
  realm.context.dispose();
97
107
  }
108
+ /**
109
+ * Freezes every object reachable from the global object, plus the intrinsics only reachable from syntax or iterators,
110
+ * so a reused realm carries no state from one call to the next. `world` becomes an accessor for the call's world API.
111
+ */
112
+ const LOCKDOWN = `((freeze, ownKeys, prototypeOf, descriptor, defineProperty) => (getWorld) => {
113
+ defineProperty(globalThis, "world", { get: () => getWorld(), enumerable: true, configurable: false });
114
+ const seen = new Set();
115
+ const visit = (value) => {
116
+ if ((typeof value !== "object" && typeof value !== "function") || value === null || seen.has(value)) { return; }
117
+ seen.add(value);
118
+ freeze(value);
119
+ visit(prototypeOf(value));
120
+ for (const key of ownKeys(value)) {
121
+ const property = descriptor(value, key);
122
+ if ("value" in property) { visit(property.value); } else { visit(property.get); visit(property.set); }
123
+ }
124
+ };
125
+ visit(globalThis);
126
+ for (const sample of [function* () {}, async function () {}, async function* () {}, (function* () {})(), (async function* () {})(),
127
+ [].values(), new Map().entries(), new Set().values(), ""[Symbol.iterator](), /a/g[Symbol.matchAll]("a")]) { visit(sample); }
128
+ })(Object.freeze, Reflect.ownKeys, Object.getPrototypeOf, Object.getOwnPropertyDescriptor, Object.defineProperty)`;
129
+ /** Bounds the frozen realms kept for reusable sources, about 60 KiB each in the 16 MiB script heap. */
130
+ const REUSABLE_REALM_LIMIT = 32;
98
131
  /** Bounds the validated entry-scene realms held until the first batch, about 30 KiB each. */
99
132
  const PREPARED_REALM_LIMIT = 64;
100
133
  const SCRIPT_BATCH_MS = 50;
@@ -106,8 +139,9 @@ const WARMUP_BATCH_MS = 1000;
106
139
  */
107
140
  const FIRST_BATCH_MS = 1000;
108
141
  const WARMUP_SOURCES = [
109
- ["warmup:fresh", "(input) => { const world = input.world; return { state: { tick: input.tick, entities: world.length, ids: world.map((entity) => entity.id) }, commands: [] }; }"],
110
- ["warmup:persistent", "(input) => ({ state: [input.state, input.world], commands: [] })"]
142
+ ["warmup:persistent", "(input) => ({ state: [input.state, input.world], commands: [] })"],
143
+ ["warmup:reusable", "(input) => { const world = input.world; return { state: { tick: input.tick, entities: world.length, ids: world.map((entity) => entity.id) }, commands: [] }; }"],
144
+ ["warmup:fresh", "(() => (input) => ({ state: { tick: input.tick, entities: input.world.length }, commands: [] }))()"]
111
145
  ];
112
146
  /** Warms the lifecycle-object path, only for documents that use it. */
113
147
  const HOOK_WARMUP_SOURCE = ["warmup:hooks", "({ onStart(input) { after(1, \"tick\"); }, tick() {}, onUpdate(input) { return { state: [input.state, input.world] }; } })"];
@@ -147,6 +181,7 @@ function compileObjectParsers(schema) {
147
181
  }
148
182
  export async function prepareIsolatedGameScripts(document, commandSchema, payloadExpression, options = {}) {
149
183
  const callClock = options.callClock ?? defaultScriptCallClock;
184
+ const skipOverruns = options.overrun === "skip";
150
185
  let envelope = envelopeSchemas.get(commandSchema);
151
186
  if (envelope === undefined) {
152
187
  envelope = z.object({ value: z.strictObject({ state: z.json(), commands: z.array(commandSchema) }), rngState: z.number().int().nonnegative() });
@@ -166,6 +201,9 @@ export async function prepareIsolatedGameScripts(document, commandSchema, payloa
166
201
  // Resolved `input.params` JSON per behavior definition. Values are document data, so this is serialized once per session.
167
202
  const paramsJson = new Map();
168
203
  const persistentSources = new Set();
204
+ // Function sources whose realm is frozen and reused between calls, keyed by source rather than entity.
205
+ const reusableSources = new Set();
206
+ const reusableRealms = new Map();
169
207
  const hookSources = new Set();
170
208
  const eventSources = new Set();
171
209
  const realms = new Map();
@@ -182,6 +220,10 @@ export async function prepareIsolatedGameScripts(document, commandSchema, payloa
182
220
  disposeRealm(realm);
183
221
  }
184
222
  realms.clear();
223
+ for (const realm of reusableRealms.values()) {
224
+ disposeRealm(realm);
225
+ }
226
+ reusableRealms.clear();
185
227
  releasePrepared();
186
228
  };
187
229
  const retain = (keys) => {
@@ -194,20 +236,38 @@ export async function prepareIsolatedGameScripts(document, commandSchema, payloa
194
236
  };
195
237
  // Host-only setup. Creating a context can run a QuickJS cycle collection of earlier disposed contexts.
196
238
  // Only lifecycle-object realms install the hook dispatcher, so function realms evaluate the same helpers as before.
197
- const createRealmShell = (seed, persistent, hooks = false) => {
239
+ // A reusable shell reseeds the random generator from each call's `rngState`, as a fresh shell seeds it on creation.
240
+ const createRealmShell = (seed, persistent, hooks = false, reusable = false) => {
198
241
  const context = runtime.newContext();
199
242
  let invoke;
200
243
  let defineData;
201
244
  let queryJson;
202
245
  let worldGetter;
203
246
  let worldReader;
247
+ let worldText;
248
+ let worldTextReader;
249
+ let worldBinding;
204
250
  try {
251
+ worldBinding = reusable ? createScriptWorldBinding(context) : undefined;
252
+ const binding = worldBinding;
205
253
  worldGetter = persistent ? context.newFunction("legacyWorld", () => {
206
254
  if (!worldReader) {
207
255
  throw new Error("Legacy world read outside an active script call");
208
256
  }
209
257
  return worldReader();
258
+ }) : binding ? context.newFunction("world", () => {
259
+ if (!binding.world) {
260
+ throw new Error("world read outside an active script call");
261
+ }
262
+ return binding.world.dup();
210
263
  }) : context.undefined.dup();
264
+ // The host serializes the world only when a script reads it.
265
+ worldText = persistent ? context.undefined.dup() : context.newFunction("worldText", () => {
266
+ if (!worldTextReader) {
267
+ throw new Error("world read outside an active script call");
268
+ }
269
+ return context.newString(worldTextReader());
270
+ });
211
271
  // Capture pristine helpers together, without introducing bindings visible to user source.
212
272
  const helpers = initializeContext(context, seed, `[
213
273
  ((define) => (object, key, value) => {
@@ -218,16 +278,20 @@ export async function prepareIsolatedGameScripts(document, commandSchema, payloa
218
278
  if (typeof json !== "string" || json.length > 4096) { throw new Error("world query arguments exceed 4096 characters or are not JSON"); }
219
279
  return json;
220
280
  })(JSON.stringify),
221
- ((defineProperty, synchronousResult${hooks ? ", dispatch" : ""}) => (data, getWorld, rngState) => {
222
- ${persistent ? "" : "data = JSON.parse(data);"}
281
+ ((defineProperty, parse, synchronousResult${hooks ? ", dispatch" : ""}) => (data, getWorld, rngState, worldText) => {
282
+ ${persistent ? "" : "data = JSON.parse(data);"}${reusable ? "reseed(rngState);" : ""}
223
283
  const payload = ${payloadExpression};
224
284
  ${persistent ? `defineProperty(payload, "world", {
225
285
  enumerable: true, configurable: true, get: getWorld,
226
286
  set(value) { defineProperty(this, "world", { value, writable: true, enumerable: true, configurable: true }); }
227
- });` : ""}
287
+ });` : `if (payload.world === undefined) defineProperty(payload, "world", {
288
+ enumerable: true, configurable: true,
289
+ get() { const value = parse(worldText()); defineProperty(this, "world", { value, writable: true, enumerable: true, configurable: true }); return value; },
290
+ set(value) { defineProperty(this, "world", { value, writable: true, enumerable: true, configurable: true }); }
291
+ });`}
228
292
  const value = synchronousResult(${hooks ? "dispatch(__gameScript, payload, data.call.steps)" : "__gameScript(payload)"}, "Game script");
229
293
  return JSON.stringify({ value, rngState: ${persistent ? "rngState" : "__gameRandom.state"} });
230
- })(Object.defineProperty, ${SCRIPT_SYNCHRONOUS_RESULT}${hooks ? `, ${SCRIPT_LIFECYCLE_DISPATCH}` : ""})]`);
294
+ })(Object.defineProperty, JSON.parse, ${SCRIPT_SYNCHRONOUS_RESULT}${hooks ? `, ${SCRIPT_LIFECYCLE_DISPATCH}` : ""})]`);
231
295
  try {
232
296
  defineData = context.getProp(helpers, 0);
233
297
  queryJson = context.getProp(helpers, 1);
@@ -236,9 +300,12 @@ export async function prepareIsolatedGameScripts(document, commandSchema, payloa
236
300
  finally {
237
301
  helpers.dispose();
238
302
  }
239
- return { context, invoke, defineData, queryJson, worldGetter, setWorldReader: (reader) => { worldReader = reader; } };
303
+ return { context, invoke, defineData, queryJson, worldGetter, setWorldReader: (reader) => { worldReader = reader; },
304
+ worldText, setWorldText: (reader) => { worldTextReader = reader; }, worldBinding };
240
305
  }
241
306
  catch (error) {
307
+ worldBinding?.dispose();
308
+ worldText?.dispose();
242
309
  worldGetter?.dispose();
243
310
  queryJson?.dispose();
244
311
  defineData?.dispose();
@@ -247,12 +314,21 @@ export async function prepareIsolatedGameScripts(document, commandSchema, payloa
247
314
  throw error;
248
315
  }
249
316
  };
250
- /** Evaluates user source in the shell, which this takes ownership of. */
251
- const loadSource = (shell, sourceKey, source, hooks) => {
317
+ /** Evaluates user source in the shell, which this takes ownership of. A reusable realm is then frozen. */
318
+ const loadSource = (shell, sourceKey, source, hooks, reusable = false) => {
252
319
  try {
253
- if (evaluateSourceKind(shell.context, source) !== (hooks ? "object" : "function")) {
320
+ if (evaluateSourceKind(shell.context, source, reusable) !== (hooks ? "object" : "function")) {
254
321
  throw new Error(`Game script ${sourceKey} must be a ${hooks ? "lifecycle object" : "function expression"}`);
255
322
  }
323
+ if (reusable) {
324
+ const lockdown = scriptHandleResult(shell.context, shell.context.evalCode(LOCKDOWN, "game-lockdown.js", { type: "global" }));
325
+ try {
326
+ scriptHandleResult(shell.context, shell.context.callFunction(lockdown, shell.context.undefined, shell.worldGetter)).dispose();
327
+ }
328
+ finally {
329
+ lockdown.dispose();
330
+ }
331
+ }
256
332
  return { ...shell, sourceKey };
257
333
  }
258
334
  catch (error) {
@@ -308,6 +384,18 @@ export async function prepareIsolatedGameScripts(document, commandSchema, payloa
308
384
  if (persistent) {
309
385
  persistentSources.add(key);
310
386
  }
387
+ if (!persistent && !hooks && canReuseGameScript(behavior.source)) {
388
+ reusableSources.add(key);
389
+ // Freezing a realm takes milliseconds, so it happens here rather than inside a tick budget.
390
+ if (reusableRealms.size < REUSABLE_REALM_LIMIT) {
391
+ try {
392
+ reusableRealms.set(key, loadSource(createRealmShell(0, false, false, true), key, behavior.source, false, true));
393
+ }
394
+ catch {
395
+ reusableSources.delete(key);
396
+ }
397
+ }
398
+ }
311
399
  if (hooks) {
312
400
  hookSources.add(key);
313
401
  }
@@ -348,7 +436,12 @@ export async function prepareIsolatedGameScripts(document, commandSchema, payloa
348
436
  paramsTable += `${counted.size > 0 ? "," : ""}${JSON.stringify(call.sourceKey)}:${params}`;
349
437
  counted.add(call.sourceKey);
350
438
  }
351
- const logical = JSON.stringify({ calls, input, rngState });
439
+ // The world, and the props of entities without a call, are left out: scripts receive them only when they read
440
+ // the world, and its own limit applies then.
441
+ const table = input.props;
442
+ const callerProps = table === undefined ? undefined
443
+ : Object.fromEntries(calls.flatMap((call) => Object.hasOwn(table, call.entityId) ? [[call.entityId, table[call.entityId]]] : []));
444
+ const logical = JSON.stringify({ calls, input: { ...input, world: undefined, props: callerProps }, rngState });
352
445
  const serialized = counted.size === 0 ? logical : `${logical.slice(0, -1)},"params":{${paramsTable}}}`;
353
446
  const inputBytes = encoder.encode(serialized).byteLength;
354
447
  if (inputBytes > 64 * 1024) {
@@ -359,16 +452,17 @@ export async function prepareIsolatedGameScripts(document, commandSchema, payloa
359
452
  const { props: propsTable, ...scriptInput } = input;
360
453
  // Scripts read props on each world entry. The copies exist only in this guest-facing JSON.
361
454
  let worldJson;
362
- const scriptWorldJson = () => worldJson ??= JSON.stringify(propsTable === undefined ? scriptInput.world
363
- : scriptInput.world.map((entity) => ({ ...entity, props: propsOf(propsTable, entity.id) })));
364
- let fullInputJson;
365
- const inputJson = () => {
366
- if (fullInputJson === undefined) {
367
- const { world: _world, ...withoutWorld } = scriptInput;
368
- const rest = JSON.stringify(withoutWorld);
369
- fullInputJson = `${rest.slice(0, -1)}${rest.length > 2 ? "," : ""}"world":${scriptWorldJson()}}`;
455
+ const scriptWorldJson = () => {
456
+ if (worldJson === undefined) {
457
+ const json = JSON.stringify(propsTable === undefined ? scriptInput.world
458
+ : scriptInput.world.map((entity) => ({ ...entity, props: propsOf(propsTable, entity.id) })));
459
+ const bytes = encoder.encode(json).byteLength;
460
+ if (bytes > MAX_SCRIPT_WORLD_BYTES) {
461
+ throw new Error(`Game script world exceeds ${MAX_SCRIPT_WORLD_BYTES / 1024 / 1024} MiB (${bytes} bytes, ${scriptInput.world.length} entities, tick ${input.tick})`);
462
+ }
463
+ worldJson = json;
370
464
  }
371
- return fullInputJson;
465
+ return worldJson;
372
466
  };
373
467
  let persistentInputJson;
374
468
  const inputJsonWithoutWorld = () => {
@@ -400,8 +494,16 @@ export async function prepareIsolatedGameScripts(document, commandSchema, payloa
400
494
  let commandCount = 0;
401
495
  const byEntity = Object.create(null);
402
496
  const results = [];
403
- for (const call of calls) {
497
+ for (const [index, call] of calls.entries()) {
404
498
  const callBudgetMs = Number.isFinite(call.maxTickMs) ? Math.min(MAX_SCRIPT_CALL_MS, call.maxTickMs) : MAX_SCRIPT_CALL_MS;
499
+ if (skipOverruns && performance.now() >= batchDeadline) {
500
+ const skipped = calls.slice(index);
501
+ for (const rest of skipped) {
502
+ results.push({ entityId: rest.entityId, state: rest.state, commands: [] });
503
+ }
504
+ logs.warn(undefined, `${skipped.length} game script ${skipped.length === 1 ? "call" : "calls"} skipped at tick ${input.tick}: ${batchBudget} budget exceeded`);
505
+ break;
506
+ }
405
507
  assertBeforeDeadline(batchDeadline, batchBudget);
406
508
  const source = sources.get(call.sourceKey);
407
509
  if (source === undefined) {
@@ -417,77 +519,140 @@ export async function prepareIsolatedGameScripts(document, commandSchema, payloa
417
519
  };
418
520
  runtime.setInterruptHandler(() => performance.now() >= batchDeadline);
419
521
  const persistent = persistentSources.has(call.sourceKey);
420
- let realm = realms.get(call.stateKey);
421
- let shell;
422
- let worldHandle;
423
- let worldCall;
424
- try {
425
- if (realm && realm.sourceKey !== call.sourceKey) {
426
- disposeRealm(realm);
427
- realms.delete(call.stateKey);
428
- realm = undefined;
429
- }
430
- if (!realm && persistent) {
431
- realm = prepared.get(call.sourceKey);
432
- prepared.delete(call.sourceKey);
433
- }
434
- // Context setup is host work, so it counts against the batch budget only. The call budget starts
435
- // before any user source is evaluated, so the script's own execution limit is unchanged.
436
- const hooks = hookSources.has(call.sourceKey);
437
- if (!realm) {
438
- shell = createRealmShell(nextRngState, persistent, hooks);
439
- }
440
- assertBeforeDeadline(batchDeadline, batchBudget);
441
- callStarted = performance.now();
442
- callExceeded = startScriptCallTimer(callClock, callBudgetMs);
443
- runtime.setInterruptHandler(() => performance.now() >= batchDeadline || callExceeded());
444
- if (shell) {
445
- const loading = shell;
446
- shell = undefined;
447
- realm = loadSource(loading, call.sourceKey, source, hooks);
448
- }
449
- if (!realm) {
450
- throw new Error("Game script realm was not created");
451
- }
452
- if (persistent) {
453
- realms.set(call.stateKey, realm);
454
- }
455
- const { context, invoke, defineData, worldGetter } = realm;
456
- if (!persistent) {
457
- worldCall = getHostWorld().install(context, checkCallDeadline, realm.defineData, realm.queryJson);
458
- }
459
- checkCallDeadline();
460
- // The shared input is serialized once per tick; only the call is serialized per call.
461
- const params = paramsJson.get(call.sourceKey);
462
- const plan = hooks ? planScriptHooks(call.state, call.lifecycle, input.tick) : undefined;
463
- const data = `{"call":${callJson(call, plan)},"input":${persistent ? inputJsonWithoutWorld() : inputJson()},"rngState":${JSON.stringify(nextRngState)}${params === undefined ? "" : `,"params":${params}`}}`;
464
- checkCallDeadline();
465
- const normalized = persistent ? JSON.parse(data) : data;
466
- let argument;
467
- let seed;
468
- let output;
522
+ const hooks = hookSources.has(call.sourceKey);
523
+ let plan;
524
+ /** Runs the call in a retained, reused or fresh realm and returns the guest's output. */
525
+ const guestCall = (reusable) => {
526
+ let realm = reusable ? reusableRealms.get(call.sourceKey) : realms.get(call.stateKey);
527
+ let shell;
528
+ let worldHandle;
529
+ let worldCall;
469
530
  try {
470
- argument = gameScriptValue(context, normalized, defineData, persistent);
471
- seed = context.newNumber(nextRngState);
472
- realm.setWorldReader(() => {
473
- checkCallDeadline();
474
- worldHandle ??= gameScriptValue(context, readLegacyWorld(), defineData, true);
475
- checkCallDeadline();
476
- return worldHandle.dup();
477
- });
478
- const value = scriptHandleResult(context, context.callFunction(invoke, context.undefined, argument, worldGetter, seed));
531
+ if (realm && realm.sourceKey !== call.sourceKey) {
532
+ disposeRealm(realm);
533
+ realms.delete(call.stateKey);
534
+ realm = undefined;
535
+ }
536
+ if (!realm && persistent) {
537
+ realm = prepared.get(call.sourceKey);
538
+ prepared.delete(call.sourceKey);
539
+ }
540
+ // Context setup is host work, so it counts against the batch budget only. The call budget starts
541
+ // before any user source is evaluated, so the script's own execution limit is unchanged.
542
+ // A reusable source is a function expression, so loading and freezing its realm runs no user code.
543
+ if (!realm) {
544
+ shell = createRealmShell(nextRngState, persistent, hooks, reusable);
545
+ }
546
+ if (shell && reusable) {
547
+ const loading = shell;
548
+ shell = undefined;
549
+ realm = loadSource(loading, call.sourceKey, source, false, true);
550
+ reusableRealms.set(call.sourceKey, realm);
551
+ }
552
+ assertBeforeDeadline(batchDeadline, batchBudget);
553
+ callStarted = performance.now();
554
+ callExceeded = startScriptCallTimer(callClock, callBudgetMs);
555
+ runtime.setInterruptHandler(() => performance.now() >= batchDeadline || callExceeded());
556
+ if (shell) {
557
+ const loading = shell;
558
+ shell = undefined;
559
+ realm = loadSource(loading, call.sourceKey, source, hooks);
560
+ }
561
+ if (!realm) {
562
+ throw new Error("Game script realm was not created");
563
+ }
564
+ if (persistent) {
565
+ realms.set(call.stateKey, realm);
566
+ }
567
+ const active = realm;
568
+ const { context, invoke, defineData, worldGetter } = active;
569
+ if (!persistent) {
570
+ worldCall = getHostWorld().install(context, checkCallDeadline, active.defineData, active.queryJson, reusable ? active.worldBinding : undefined);
571
+ }
572
+ checkCallDeadline();
573
+ // The shared input is serialized once per tick; only the call is serialized per call.
574
+ const params = paramsJson.get(call.sourceKey);
575
+ plan = hooks ? planScriptHooks(call.state, call.lifecycle, input.tick) : undefined;
576
+ // A realm receives the world entries only when the script reads `input.world`.
577
+ const data = `{"call":${callJson(call, plan)},"input":${inputJsonWithoutWorld()},"rngState":${JSON.stringify(nextRngState)}${params === undefined ? "" : `,"params":${params}`}}`;
578
+ checkCallDeadline();
579
+ const normalized = persistent ? JSON.parse(data) : data;
580
+ let argument;
581
+ let seed;
582
+ let output;
479
583
  try {
480
- output = context.dump(value);
584
+ argument = gameScriptValue(context, normalized, defineData, persistent);
585
+ seed = context.newNumber(nextRngState);
586
+ active.setWorldText(() => { checkCallDeadline(); return scriptWorldJson(); });
587
+ active.setWorldReader(() => {
588
+ checkCallDeadline();
589
+ worldHandle ??= gameScriptValue(context, readLegacyWorld(), defineData, true);
590
+ checkCallDeadline();
591
+ return worldHandle.dup();
592
+ });
593
+ const value = scriptHandleResult(context, context.callFunction(invoke, context.undefined, argument, worldGetter, seed, active.worldText));
594
+ try {
595
+ output = context.dump(value);
596
+ }
597
+ finally {
598
+ value.dispose();
599
+ }
600
+ worldCall?.assertWithinLimit();
481
601
  }
482
602
  finally {
483
- value.dispose();
603
+ active.setWorldReader(undefined);
604
+ active.setWorldText(undefined);
605
+ argument?.dispose();
606
+ seed?.dispose();
607
+ }
608
+ return output;
609
+ }
610
+ catch (error) {
611
+ worldHandle?.dispose();
612
+ worldHandle = undefined;
613
+ if (shell) {
614
+ disposeRealm(shell);
615
+ shell = undefined;
616
+ }
617
+ // A realm whose call failed is not reused.
618
+ if (reusable && realm) {
619
+ reusableRealms.delete(call.sourceKey);
484
620
  }
485
- worldCall?.assertWithinLimit();
621
+ if (!persistent && realm) {
622
+ disposeRealm(realm);
623
+ realm = undefined;
624
+ }
625
+ throw error;
486
626
  }
487
627
  finally {
488
- realm.setWorldReader(undefined);
489
- argument?.dispose();
490
- seed?.dispose();
628
+ worldCall?.end();
629
+ worldHandle?.dispose();
630
+ if (!persistent && !reusable && realm) {
631
+ disposeRealm(realm);
632
+ }
633
+ }
634
+ };
635
+ try {
636
+ let output;
637
+ if (!reusableSources.has(call.sourceKey) || (!reusableRealms.has(call.sourceKey) && reusableRealms.size >= REUSABLE_REALM_LIMIT)) {
638
+ output = guestCall(false);
639
+ }
640
+ else {
641
+ try {
642
+ output = guestCall(true);
643
+ }
644
+ catch (error) {
645
+ // A frozen Error.prototype strips the message from a host function's error, so a budget that ran out
646
+ // inside one is named here.
647
+ if (performance.now() >= batchDeadline || callExceeded()) {
648
+ checkCallDeadline();
649
+ throw error;
650
+ }
651
+ // Strict mode or a frozen built-in rejected the call. A fresh realm runs it as written, so this source
652
+ // keeps using fresh realms. Either way the call sees only its own input.
653
+ reusableSources.delete(call.sourceKey);
654
+ output = guestCall(false);
655
+ }
491
656
  }
492
657
  if (typeof output !== "string") {
493
658
  throw new Error("Output is not JSON");
@@ -525,32 +690,34 @@ export async function prepareIsolatedGameScripts(document, commandSchema, payloa
525
690
  results.push({ entityId: call.entityId, state: value.state, commands: value.commands });
526
691
  }
527
692
  catch (error) {
528
- // A failed batch cannot retain partially evaluated realms.
529
- worldHandle?.dispose();
530
- worldHandle = undefined;
531
- if (shell) {
532
- disposeRealm(shell);
533
- shell = undefined;
534
- }
535
- if (!persistent && realm) {
536
- disposeRealm(realm);
537
- realm = undefined;
693
+ const batchOverrun = performance.now() >= batchDeadline;
694
+ if (skipOverruns && (batchOverrun || callExceeded())) {
695
+ // The interrupted call may have changed its retained realm, so the next call starts a fresh one.
696
+ const realm = realms.get(call.stateKey);
697
+ if (realm) {
698
+ disposeRealm(realm);
699
+ realms.delete(call.stateKey);
700
+ }
701
+ results.push({ entityId: call.entityId, state: call.state, commands: [] });
702
+ const budget = batchOverrun ? batchBudget : `call ${callBudgetMs} ms`;
703
+ logs.warn(call.entityId, `Game script ${call.sourceKey} for ${call.entityId} skipped at tick ${input.tick}: ${budget} budget exceeded`);
538
704
  }
539
- disposeRealms();
540
- throw new Error(`Game script ${call.sourceKey} for ${call.entityId} at tick ${input.tick} failed: ${error instanceof Error ? error.message : String(error)}`);
541
- }
542
- finally {
543
- worldCall?.end();
544
- worldHandle?.dispose();
545
- if (!persistent && realm) {
546
- disposeRealm(realm);
705
+ else {
706
+ // A failed batch cannot retain partially evaluated realms.
707
+ disposeRealms();
708
+ throw new Error(`Game script ${call.sourceKey} for ${call.entityId} at tick ${input.tick} failed: ${error instanceof Error ? error.message : String(error)}`);
547
709
  }
548
710
  }
549
- checkCallDeadline();
711
+ // With skipping, a batch that ran out of time after this call skips the remaining calls on the next pass.
712
+ if (!skipOverruns) {
713
+ checkCallDeadline();
714
+ }
550
715
  const previous = byEntity[call.entityId] ?? { durationMs: 0, calls: 0 };
551
716
  byEntity[call.entityId] = { durationMs: previous.durationMs + performance.now() - callStarted, calls: previous.calls + 1 };
552
717
  }
553
- assertBeforeDeadline(batchDeadline, batchBudget);
718
+ if (!skipOverruns) {
719
+ assertBeforeDeadline(batchDeadline, batchBudget);
720
+ }
554
721
  const stats = { durationMs: performance.now() - started, commands: commandCount, calls: calls.length, byEntity };
555
722
  const lines = logs.entries();
556
723
  const requests = saves.entries();
@@ -579,6 +746,9 @@ export async function prepareIsolatedGameScripts(document, commandSchema, payloa
579
746
  if (canPersistGameScript(source)) {
580
747
  persistentSources.add(key);
581
748
  }
749
+ else if (canReuseGameScript(source)) {
750
+ reusableSources.add(key);
751
+ }
582
752
  if (key === HOOK_WARMUP_SOURCE[0]) {
583
753
  hookSources.add(key);
584
754
  }
@@ -602,7 +772,13 @@ export async function prepareIsolatedGameScripts(document, commandSchema, payloa
602
772
  for (const [key] of warmups) {
603
773
  sources.delete(key);
604
774
  persistentSources.delete(key);
775
+ reusableSources.delete(key);
605
776
  hookSources.delete(key);
777
+ const realm = reusableRealms.get(key);
778
+ if (realm) {
779
+ disposeRealm(realm);
780
+ reusableRealms.delete(key);
781
+ }
606
782
  }
607
783
  }
608
784
  }
@@ -638,6 +814,25 @@ export async function prepareIsolatedGameScripts(document, commandSchema, payloa
638
814
  else {
639
815
  persistentSources.delete(update.sourceKey);
640
816
  }
817
+ const reused = reusableRealms.get(update.sourceKey);
818
+ if (reused) {
819
+ disposeRealm(reused);
820
+ reusableRealms.delete(update.sourceKey);
821
+ }
822
+ reusableSources.delete(update.sourceKey);
823
+ if (!persistent && canReuseGameScript(update.source)) {
824
+ reusableSources.add(update.sourceKey);
825
+ if (reusableRealms.size < REUSABLE_REALM_LIMIT) {
826
+ const deadline = performance.now() + 100;
827
+ runtime.setInterruptHandler(() => performance.now() >= deadline);
828
+ try {
829
+ reusableRealms.set(update.sourceKey, loadSource(createRealmShell(0, false, false, true), update.sourceKey, update.source, false, true));
830
+ }
831
+ catch {
832
+ reusableSources.delete(update.sourceKey);
833
+ }
834
+ }
835
+ }
641
836
  if (onEvent) {
642
837
  eventSources.add(update.sourceKey);
643
838
  }