@nodetool-ai/game-runtime 0.8.6 → 0.8.8

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