@voicethere/agent 0.36.1 → 0.37.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +11 -11
  2. package/dist/llm/mcp/mcp-tool-source.d.ts +10 -0
  3. package/dist/llm/mcp/mcp-tool-source.d.ts.map +1 -1
  4. package/dist/llm/mcp/mcp-tool-source.js +50 -2
  5. package/dist/llm/mcp/mcp-tool-source.js.map +1 -1
  6. package/dist/templates/flow-agent/agent.js +42 -3
  7. package/dist/templates/game-sync/agent.js +256 -52
  8. package/dist/templates/llm-agent/agent.js +42 -3
  9. package/dist/templates/llm-board/agent.js +42 -3
  10. package/dist/templates/llm-docs-rag/agent.js +42 -3
  11. package/dist/templates/llm-language-switch/agent.js +42 -3
  12. package/dist/templates/llm-language-tutor/agent.js +42 -3
  13. package/dist/templates/llm-mcp-service/agent.js +42 -3
  14. package/dist/templates/llm-store-support/agent.js +42 -3
  15. package/dist/templates/llm-support-sticky-user/agent.js +42 -3
  16. package/dist/templates/registry.d.ts.map +1 -1
  17. package/dist/templates/registry.js +8 -3
  18. package/dist/templates/registry.js.map +1 -1
  19. package/dist/templates/world-sync/agent.js +22 -1
  20. package/dist/templates/world-sync-binary/agent.js +22 -1
  21. package/eject/llm/loop.ts +1 -1
  22. package/package.json +30 -1
  23. package/templates/README.md +11 -11
  24. package/templates/game-sync/README.md +13 -4
  25. package/templates/game-sync/agent.ts +175 -60
  26. package/templates/game-sync/protocol.ts +3 -0
  27. package/templates/game-sync/quantize.ts +53 -0
  28. package/templates/game-sync/redis.ts +51 -1
  29. package/templates/game-sync/sim.ts +6 -0
  30. package/templates/game-sync/world-layout.ts +191 -0
  31. package/templates/redis-sync/README.md +7 -5
  32. package/templates/redis-sync/agent.ts +77 -65
  33. package/templates/redis-sync/quantize.ts +53 -0
  34. package/templates/redis-sync/quantized-frames.vectors.json +249 -0
  35. package/templates/redis-sync/world-layout.ts +278 -116
  36. package/templates/world-sync/README.md +1 -1
  37. package/templates/world-sync/agent.ts +39 -4
  38. package/templates/world-sync-binary/README.md +1 -1
  39. package/templates/world-sync-binary/agent.ts +29 -2
@@ -1543,6 +1543,10 @@ var WorldSnapshotBuffer = class {
1543
1543
  var defaultSnapshot = new WorldSnapshotBuffer();
1544
1544
 
1545
1545
  // templates/world-sync-binary/agent.ts
1546
+ var BROADCAST_HZ = 30;
1547
+ var BROADCAST_INTERVAL_MS = Math.floor(1e3 / BROADCAST_HZ);
1548
+ var dirty = false;
1549
+ var broadcastTimer = null;
1546
1550
  var snapshot = new WorldSnapshotBuffer();
1547
1551
  var indexBySession = /* @__PURE__ */ new Map();
1548
1552
  var sessionIds = [];
@@ -1596,17 +1600,32 @@ function removePeer(sessionId) {
1596
1600
  sessionIds.length = peerCount;
1597
1601
  }
1598
1602
  function broadcastWorld() {
1603
+ dirty = false;
1599
1604
  const payload = snapshot.encodePacked(sessionIds, xyz, peerCount);
1600
1605
  broadCastBinaryToClients(payload, sessionIds, "sync");
1601
1606
  }
1607
+ function startTickIfNeeded() {
1608
+ if (broadcastTimer || peerCount === 0) return;
1609
+ broadcastTimer = setInterval(() => {
1610
+ if (dirty) broadcastWorld();
1611
+ }, BROADCAST_INTERVAL_MS);
1612
+ }
1613
+ function stopTickIfIdle() {
1614
+ if (peerCount > 0 || !broadcastTimer) return;
1615
+ clearInterval(broadcastTimer);
1616
+ broadcastTimer = null;
1617
+ dirty = false;
1618
+ }
1602
1619
  var agent_default = defineAgent({
1603
1620
  onClientJoin({ sessionId }) {
1604
1621
  setPose(sessionId, 0, 0, 0);
1622
+ startTickIfNeeded();
1605
1623
  broadcastWorld();
1606
1624
  },
1607
1625
  onClientLeave({ sessionId }) {
1608
1626
  removePeer(sessionId);
1609
1627
  broadcastWorld();
1628
+ stopTickIfIdle();
1610
1629
  },
1611
1630
  onDataChannelBinary({ sessionId, rawBinary }) {
1612
1631
  let index = indexBySession.get(sessionId);
@@ -1620,9 +1639,11 @@ var agent_default = defineAgent({
1620
1639
  if (!decodePoseInto(rawBinary, xyz, index * POSE_FLOAT_COUNT)) {
1621
1640
  return;
1622
1641
  }
1623
- broadcastWorld();
1642
+ startTickIfNeeded();
1643
+ dirty = true;
1624
1644
  }
1625
1645
  });
1626
1646
  export {
1647
+ BROADCAST_HZ,
1627
1648
  agent_default as default
1628
1649
  };
package/eject/llm/loop.ts CHANGED
@@ -1,4 +1,4 @@
1
- // Copied from @voicethere/agent 0.36.1. Package updates no longer change this file.
1
+ // Copied from @voicethere/agent 0.37.1. Package updates no longer change this file.
2
2
  import { randomUUID } from "node:crypto";
3
3
  import {
4
4
  type AgentHandlers,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@voicethere/agent",
3
- "version": "0.36.1",
3
+ "version": "0.37.1",
4
4
  "description": "VoiceThere customer agent SDK — IPC types and runtime helpers for sandboxed child bundles",
5
5
  "type": "module",
6
6
  "exports": {
@@ -92,6 +92,35 @@
92
92
  "require": "./templates/redis-sync/world-layout.ts",
93
93
  "default": "./templates/redis-sync/world-layout.ts"
94
94
  },
95
+ "./templates/redis-sync/quantize": {
96
+ "types": "./templates/redis-sync/quantize.ts",
97
+ "import": "./templates/redis-sync/quantize.ts",
98
+ "require": "./templates/redis-sync/quantize.ts",
99
+ "default": "./templates/redis-sync/quantize.ts"
100
+ },
101
+ "./templates/game-sync/world-layout": {
102
+ "types": "./templates/game-sync/world-layout.ts",
103
+ "import": "./templates/game-sync/world-layout.ts",
104
+ "require": "./templates/game-sync/world-layout.ts",
105
+ "default": "./templates/game-sync/world-layout.ts"
106
+ },
107
+ "./templates/game-sync/quantize": {
108
+ "types": "./templates/game-sync/quantize.ts",
109
+ "import": "./templates/game-sync/quantize.ts",
110
+ "require": "./templates/game-sync/quantize.ts",
111
+ "default": "./templates/game-sync/quantize.ts"
112
+ },
113
+ "./templates/game-sync/sim": {
114
+ "types": "./templates/game-sync/sim.ts",
115
+ "import": "./templates/game-sync/sim.ts",
116
+ "require": "./templates/game-sync/sim.ts",
117
+ "default": "./templates/game-sync/sim.ts"
118
+ },
119
+ "./templates/redis-sync/quantized-frames.vectors.json": {
120
+ "import": "./templates/redis-sync/quantized-frames.vectors.json",
121
+ "require": "./templates/redis-sync/quantized-frames.vectors.json",
122
+ "default": "./templates/redis-sync/quantized-frames.vectors.json"
123
+ },
95
124
  "./llm/eject/loop.ts": {
96
125
  "types": "./eject/llm/loop.ts",
97
126
  "import": "./eject/llm/loop.ts",
@@ -51,7 +51,7 @@ Three product templates cover positional / world sync, from JSON to Redis:
51
51
  | ------------------- | ------------------------------------------------------------------ | ----------------------------------- |
52
52
  | `world-sync` | `onDataChannelMessage` (JSON) | One agent, in-memory, no Redis |
53
53
  | `world-sync-binary` | `onDataChannelBinary` + `broadCastBinaryToClients` (`ArrayBuffer`) | One agent, in-memory, no Redis |
54
- | `game-sync` | JSON control + binary world snapshots | Redis when `AGENT_REDIS_URL` is set |
54
+ | `game-sync` | JSON control + quantized binary world frames (30 Hz) | Redis when `AGENT_REDIS_URL` is set |
55
55
 
56
56
  See each folder README for the wire format.
57
57
 
@@ -66,9 +66,9 @@ Each folder has its own README. Summary:
66
66
  | `voice-starter` | `voice-starter/` | Every speech event |
67
67
  | `language-switch` | `language-switch/` | Manual `setVoiceLanguage`, or runner auto-switch with a localized echo of the recognized text |
68
68
  | `speaker-gate` | `speaker-gate/` | Caller speaker gate: `auto` listens to the enrolled caller only, `manual` labels every speaker; switch with `setSpeakerGate` |
69
- | `world-sync` | `world-sync/` | JSON pose broadcast |
70
- | `world-sync-binary` | `world-sync-binary/` | Binary pose `ArrayBuffer` |
71
- | `game-sync` | `game-sync/` | Authoritative sim, Redis + binary snapshots |
69
+ | `world-sync` | `world-sync/` | JSON pose broadcast, one snapshot per 30 Hz tick when dirty |
70
+ | `world-sync-binary` | `world-sync-binary/` | Binary pose `ArrayBuffer`, one snapshot per 30 Hz tick when dirty |
71
+ | `game-sync` | `game-sync/` | Authoritative 60 Hz sim, quantized binary snapshots at 30 Hz, Redis when set |
72
72
  | `voice-showcase` | `voice-showcase/` | Conversational landing demo |
73
73
  | `recording-consent` | `recording-consent/` | Recording consent flow |
74
74
  | `positional-tts` | `positional-tts/` | Orbiting TTS |
@@ -88,13 +88,13 @@ Each folder has its own README. Summary:
88
88
 
89
89
  These were the end-to-end test fixtures; the tests resolve entries from the package, build them into ephemeral workdirs, and upload `dist/agent.js`.
90
90
 
91
- | Id | Source | Purpose |
92
- | ----------------- | ----------------------------------------- | ------------------------------------------------------ |
93
- | `echo-smoke` | `echo-smoke/agent.ts` | voice-smoke, agent-smoke, cli-smoke |
94
- | `crash` | `crash/agent.ts` | session-errors-smoke, crash-policy smokes |
95
- | `game-sync-smoke` | `game-sync-smoke/agent.ts` | deploy-smoke, shared-child, idle smokes |
96
- | `redis-sync` | `redis-sync/agent.ts` + `world-layout.ts` | redis-sync-smoke (binary positions + Redis world blob) |
97
- | `mix-smoke` | `mix-smoke/agent.ts` | voice-data-mix-smoke |
91
+ | Id | Source | Purpose |
92
+ | ----------------- | ----------------------------------------- | ----------------------------------------------------------------------------- |
93
+ | `echo-smoke` | `echo-smoke/agent.ts` | voice-smoke, agent-smoke, cli-smoke |
94
+ | `crash` | `crash/agent.ts` | session-errors-smoke, crash-policy smokes |
95
+ | `game-sync-smoke` | `game-sync-smoke/agent.ts` | deploy-smoke, shared-child, idle smokes |
96
+ | `redis-sync` | `redis-sync/agent.ts` + `world-layout.ts` | redis-sync-smoke (quantized keyframe/delta frames at 20 Hz, Redis world blob) |
97
+ | `mix-smoke` | `mix-smoke/agent.ts` | voice-data-mix-smoke |
98
98
 
99
99
  **Note:** Product `echo` is not the same as e2e `echo-smoke` — keep both ids.
100
100
 
@@ -1,10 +1,18 @@
1
1
  # game-sync
2
2
 
3
- Authoritative multi-object world sync for games and simulations. Live objects are capped at **25**. Clients register over JSON; the agent simulates at 60 Hz and broadcasts a **binary** `Float32Array` world snapshot with `sendBinaryToClient`.
3
+ Authoritative multi-object world sync for games and simulations. Live objects are capped at **25**. Clients register over JSON; the agent simulates at 60 Hz and broadcasts a **quantized binary** world frame at 30 Hz (every second sim tick) with `broadCastBinaryToClients`.
4
4
 
5
- When `AGENT_REDIS_URL` is set (Project Redis), the world blob lives at `game-sync:world` and is shared across runner workers. Redis GET bytes are copied into the one in-memory `Float32Array` (the GET reply is the only per-tick allocation); sim, broadcast, and Redis `SET` all use one persistent `Buffer` view of that array. The tick itself is allocation-free: live object ids are collected into a reusable `Int32Array`, tick bodies are module-level functions (no per-tick closures or option objects), and the broadcast is a single `broadCastBinaryToClients` call over a live session array. Without Redis, state is per-worker in memory.
5
+ ## Frame format
6
6
 
7
- This is the most advanced world-sync starter: Redis + binary snapshots + server-side physics.
7
+ `u8 format (2) · u8 version (1) · u16le objectCount`, then one 18 B record per live object: `u16le objectId` and eight `i16le` values `[posX posY posZ posW dirX dirY dirZ dirW]`. Positions are bounded to the 1280 x 720 board and velocities to +-1024 px/s; `z`, `w`, `dirZ` and `dirW` are unit components stored as `round(v x 32767)`. A value outside its range is clamped and counted. A full frame of 25 objects is 454 B (the earlier Float32 snapshot was 900 B). The vectors in `templates/redis-sync/quantized-frames.vectors.json` (`gameSync`) pin the encoding, and `world-layout.ts` exports the encoder and decoder.
8
+
9
+ ## Redis
10
+
11
+ When `AGENT_REDIS_URL` is set (Project Redis), the world blob (float32) lives at `game-sync:world` and is shared across runner workers. World writes (allocate, release, sim commit) take the `game-sync:sim-lock`, which holds a random per-attempt token: it is released by compare-and-delete and every write is conditional on the token, so a pod whose lock expired cannot overwrite a newer world. The world is stored with `game-sync:sim-at` (Redis clock, ms). A step advances by `now - sim-at` and is skipped when that is under one sim interval, so any number of pods simulate wall time once. When the lock is lost twice in a row, a register or unregister answers `{ type: "register_nack" | "unregister_nack", reason: "busy" }` and the client retries. Pods from before 0.37.0 use neither the token-conditional commit nor `game-sync:sim-at`, so do not run old and new game-sync pods side by side in one project; redeploy all pods.
12
+
13
+ Without Redis, state is per-worker in memory. The tick is allocation-free: live object ids go into a reusable `Int32Array`, tick bodies are module-level functions, and the broadcast is one call over a live session array.
14
+
15
+ This is the most advanced world-sync starter: Redis + quantized binary frames + server-side physics.
8
16
 
9
17
  ## Build
10
18
 
@@ -16,6 +24,7 @@ npx @voicethere/agent build --entry templates/game-sync/agent.ts --outfile dist/
16
24
 
17
25
  - `agent.ts` — `defineAgent` wiring, register/unregister, sim loop
18
26
  - `protocol.ts` — JSON control messages
19
- - `world-layout.ts` — Float32Array slot layout
27
+ - `world-layout.ts` — Float32Array slot layout and the quantized frame encoder/decoder
28
+ - `quantize.ts` — int16 quantizer (same content as `redis-sync/quantize.ts`)
20
29
  - `sim.ts` — wall bounce + collisions
21
30
  - `redis.ts` — Lua allocate/release
@@ -6,32 +6,41 @@
6
6
  * - each tracked object uses exactly 9 floats:
7
7
  * [objectId, posX, posY, posZ, posW, dirX, dirY, dirZ, dirW]
8
8
  *
9
- * With project Redis (`AGENT_REDIS_URL`), the world blob is shared across runner
10
- * workers (key `game-sync:world`). World writes (allocate/release Lua, sim SET)
11
- * serialize on `game-sync:sim-lock`; one holder runs physics per tick.
9
+ * With project Redis (`AGENT_REDIS_URL`), the world blob (float32) is shared across
10
+ * runner workers (key `game-sync:world`). World writes (allocate/release Lua, sim
11
+ * commit) serialize on `game-sync:sim-lock`. The lock holds a random per-attempt token:
12
+ * it is released by compare-and-delete, and every world write is conditional on the
13
+ * token. The world is stored with `game-sync:sim-at` (Redis clock, ms); a step takes
14
+ * dt = now - sim-at and is skipped when dt is under one sim interval, so any number of
15
+ * pods simulate wall time once.
12
16
  *
13
17
  * Control messages:
14
18
  * - `{ type: "register" }` -> allocates (or reuses) one 9-float slot
15
19
  * - server replies `{ type: "register_ack", objectId }`
16
20
  * - `{ type: "register_nack", reason: "world_full", maxObjects: 25 }` when cap reached
21
+ * - `{ type: "register_nack", reason: "busy" }` / `{ type: "unregister_nack", reason: "busy" }`
22
+ * when the Redis sim lock was lost twice in a row (the write was skipped; retry later)
17
23
  * - `{ type: "remove", objectId }` or `{ type: "unregister", objectId?: number }` ->
18
24
  * zeros that live slot (objectId required for click-to-remove; omit objectId on
19
25
  * unregister to drop the highest object owned by this session)
20
26
  * - `{ type: "unregister_ack", objectId }` or `{ type: "unregister_nack", reason }`
21
27
  *
22
28
  * Simulation:
23
- * - server-authoritative movement at 60Hz
29
+ * - server-authoritative movement at 60Hz (SIM_HZ)
24
30
  * - wall bounce + object-object elastic collisions on server
25
31
  * - clients render server snapshots; client binary writes are ignored
26
32
  * - with project Redis, the sim loop keeps running with zero connected clients so
27
33
  * objects persist and keep moving after everyone disconnects
28
34
  *
29
35
  * Broadcast:
30
- * - 60Hz world-state broadcast while the sim loop runs (no-op send when 0 sessions)
36
+ * - 30Hz (BROADCAST_HZ, every 2nd sim tick) quantized world frame while the sim loop
37
+ * runs: u8 format 2, u8 version 1, u16le objectCount, then 18 B per live object (see
38
+ * world-layout.ts). Followers relay only when sim-at advanced.
31
39
  *
32
40
  * Build:
33
41
  * npx @voicethere/agent build --entry templates/game-sync/agent.ts
34
42
  */
43
+ import { randomUUID } from "node:crypto";
35
44
  import { Redis } from "ioredis";
36
45
  import {
37
46
  agentLog,
@@ -46,18 +55,27 @@ import {
46
55
  parseRegisterCommand,
47
56
  parseUnregisterCommand,
48
57
  resolveRemoveTarget,
58
+ REGISTER_NACK_REASON_BUSY,
49
59
  REGISTER_NACK_REASON_WORLD_FULL,
60
+ UNREGISTER_NACK_REASON_BUSY,
50
61
  UNREGISTER_NACK_REASON_NOT_FOUND,
51
62
  } from "./protocol.js";
52
63
  import {
53
64
  LUA_ALLOCATE_OBJECT,
65
+ LUA_COMMIT_WORLD,
66
+ LUA_READ_WORLD,
67
+ LUA_RELEASE_LOCK,
54
68
  LUA_RELEASE_OBJECT,
55
69
  REDIS_EVAL_KEYS,
56
70
  } from "./redis.js";
57
71
  import {
58
72
  BOARD_HEIGHT,
59
73
  BOARD_WIDTH,
74
+ BROADCAST_HZ,
75
+ MAX_SPEED,
76
+ MIN_SPEED,
60
77
  OBJECT_RADIUS,
78
+ SIM_HZ,
61
79
  simulateWorldStep,
62
80
  } from "./sim.js";
63
81
  import {
@@ -65,24 +83,31 @@ import {
65
83
  collectActiveObjectIdsInto,
66
84
  countLiveObjects,
67
85
  createEmptyWorldBuffer,
86
+ encodeLiveObjectsInto,
68
87
  findFirstEmptySlot,
69
88
  liveWorldSnapshot,
70
89
  markSlotFree,
71
90
  normalizeWorldBuffer,
72
91
  objectIdToSlot,
92
+ MAX_FRAME_BYTES,
73
93
  planRedisSimTick,
94
+ planRedisStepDtSec,
95
+ REDIS_SIM_AT_KEY,
74
96
  REDIS_SIM_LOCK_KEY,
75
97
  REDIS_WORLD_KEY,
76
98
  slotToObjectId,
77
99
  writeObjectSlot,
78
100
  } from "./world-layout.js";
79
101
 
80
- const BROADCAST_HZ = 60;
81
- const BROADCAST_INTERVAL_MS = Math.floor(1000 / BROADCAST_HZ);
82
- const SIM_LOCK_TTL_MS = BROADCAST_INTERVAL_MS * 2;
102
+ const SIM_INTERVAL_MS = Math.floor(1000 / SIM_HZ);
103
+ /** Every 2nd sim tick broadcasts (60 Hz sim, 30 Hz send). */
104
+ const BROADCAST_EVERY_N_TICKS = Math.round(SIM_HZ / BROADCAST_HZ);
105
+ const SIM_LOCK_TTL_MS = SIM_INTERVAL_MS * 2;
83
106
  const SIM_LOCK_RETRY_MS = 5;
84
- const MIN_SPEED = 90;
85
- const MAX_SPEED = 180;
107
+ /** Allocate/release Lua result when the lock no longer holds this pod's token. */
108
+ const LUA_LOCK_LOST = -3;
109
+ const LOCK_LOST = "lock_lost" as const;
110
+ type LockLost = typeof LOCK_LOST;
86
111
 
87
112
  const connectedSessions = new Set<string>();
88
113
  /** Same members as connectedSessions; array form lets the broadcast skip Set iteration. */
@@ -102,6 +127,14 @@ let redis: Redis | null = null;
102
127
  let broadcastTimer: NodeJS.Timeout | null = null;
103
128
  let worldMutationChain: Promise<void> = Promise.resolve();
104
129
  let lastTickTimeMs = 0;
130
+ let tickCount = 0;
131
+ /** One broadcast scratch frame per pod; the frame sent is a subarray of it (IPC copies synchronously). */
132
+ const frameScratch = Buffer.alloc(MAX_FRAME_BYTES);
133
+ /** From the last Redis read: stored sim-at (0 = none) and Redis' clock, both ms. */
134
+ let lastReadSimAt = 0;
135
+ let lastReadNowMs = 0;
136
+ /** sim-at of the last frame this pod broadcast; followers relay only when it advanced. */
137
+ let lastRelayedSimAt = 0;
105
138
 
106
139
  function withWorldMutation<T>(fn: () => Promise<T>): Promise<T> {
107
140
  const run = worldMutationChain.then(fn);
@@ -118,29 +151,36 @@ function sleep(ms: number): Promise<void> {
118
151
  });
119
152
  }
120
153
 
154
+ async function releaseSimLock(token: string): Promise<void> {
155
+ if (!redis) return;
156
+ // Compare-and-delete: a holder whose TTL lapsed never deletes the next holder's lock.
157
+ await redis.eval(LUA_RELEASE_LOCK, 1, REDIS_SIM_LOCK_KEY, token);
158
+ }
159
+
121
160
  async function withRedisSimLock<T>(
122
- fn: () => Promise<T>,
161
+ fn: (token: string) => Promise<T>,
123
162
  options?: { retryUntilAcquired?: boolean },
124
163
  ): Promise<T | null> {
125
164
  if (!redis) {
126
- return fn();
165
+ return fn("");
127
166
  }
128
167
 
129
168
  const retryUntilAcquired = options?.retryUntilAcquired ?? true;
169
+ const token = randomUUID();
130
170
 
131
171
  while (true) {
132
172
  const lockAcquired = await redis.set(
133
173
  REDIS_SIM_LOCK_KEY,
134
- "1",
174
+ token,
135
175
  "PX",
136
176
  SIM_LOCK_TTL_MS,
137
177
  "NX",
138
178
  );
139
179
  if (lockAcquired === "OK") {
140
180
  try {
141
- return await fn();
181
+ return await fn(token);
142
182
  } finally {
143
- await redis.del(REDIS_SIM_LOCK_KEY);
183
+ await releaseSimLock(token);
144
184
  }
145
185
  }
146
186
  if (!retryUntilAcquired) {
@@ -249,23 +289,30 @@ function registerObjectInMemory(sessionId: string): number | null {
249
289
 
250
290
  async function registerObjectInRedis(
251
291
  sessionId: string,
252
- ): Promise<number | null> {
292
+ token: string,
293
+ ): Promise<number | null | LockLost> {
253
294
  if (!redis) {
254
295
  return registerObjectInMemory(sessionId);
255
296
  }
256
297
 
257
298
  const result = await redis.eval(
258
299
  LUA_ALLOCATE_OBJECT,
259
- 1,
300
+ 2,
260
301
  REDIS_EVAL_KEYS.worldKey,
302
+ REDIS_EVAL_KEYS.lockKey,
261
303
  REDIS_EVAL_KEYS.worldByteLength,
262
304
  REDIS_EVAL_KEYS.slotByteLength,
263
305
  REDIS_EVAL_KEYS.maxSlots,
264
306
  randomInitialTail(),
265
307
  REDIS_EVAL_KEYS.headers,
308
+ token,
266
309
  );
267
310
 
268
311
  const objectId = Number(result);
312
+ if (objectId === LUA_LOCK_LOST) {
313
+ agentLog("warn", "register skipped: sim lock lost before the world write");
314
+ return LOCK_LOST;
315
+ }
269
316
  if (!Number.isFinite(objectId) || objectId < 1) {
270
317
  return null;
271
318
  }
@@ -275,29 +322,51 @@ async function registerObjectInRedis(
275
322
  return objectId;
276
323
  }
277
324
 
278
- async function releaseObjectInRedis(objectId: number): Promise<boolean> {
279
- detachObjectFromSession(objectId);
325
+ async function releaseObjectInRedis(
326
+ objectId: number,
327
+ token: string,
328
+ ): Promise<boolean | LockLost> {
280
329
  if (!redis) {
330
+ detachObjectFromSession(objectId);
281
331
  releaseObjectInMemory(objectId);
282
332
  return true;
283
333
  }
284
334
 
285
335
  const released = await redis.eval(
286
336
  LUA_RELEASE_OBJECT,
287
- 1,
337
+ 2,
288
338
  REDIS_EVAL_KEYS.worldKey,
339
+ REDIS_EVAL_KEYS.lockKey,
289
340
  REDIS_EVAL_KEYS.worldByteLength,
290
341
  REDIS_EVAL_KEYS.slotByteLength,
291
342
  REDIS_EVAL_KEYS.maxSlots,
292
343
  String(objectId),
293
344
  REDIS_EVAL_KEYS.headers,
345
+ token,
294
346
  );
347
+ if (Number(released) === LUA_LOCK_LOST) {
348
+ // Nothing was written and nothing was detached: the owner stays as it was.
349
+ agentLog("warn", "release skipped: sim lock lost before the world write");
350
+ return LOCK_LOST;
351
+ }
352
+ detachObjectFromSession(objectId);
295
353
  if (Number(released) === 1) {
296
354
  await loadWorldFromRedis();
297
355
  }
298
356
  return Number(released) === 1;
299
357
  }
300
358
 
359
+ /** Run a lock-guarded write; when the lock was lost mid-way, retry once with a new token. */
360
+ async function withSimLockRetryOnce<T>(
361
+ fn: (token: string) => Promise<T | LockLost>,
362
+ ): Promise<T | LockLost> {
363
+ for (let attempt = 0; attempt < 2; attempt += 1) {
364
+ const result = await withRedisSimLock(fn);
365
+ if (result !== LOCK_LOST) return result as T;
366
+ }
367
+ return LOCK_LOST;
368
+ }
369
+
301
370
  async function unregisterObject(
302
371
  sessionId: string,
303
372
  objectId?: number,
@@ -309,19 +378,21 @@ async function unregisterObject(
309
378
  }
310
379
 
311
380
  const previousOwner = objectOwners.get(target.objectId) ?? sessionId;
312
- notifyObjectReleased(target.objectId, previousOwner);
313
381
  const released = await withWorldMutation(async () => {
314
382
  if (!redis) {
315
- return releaseObjectInRedis(target.objectId);
383
+ return releaseObjectInRedis(target.objectId, "");
316
384
  }
317
- const result = await withRedisSimLock(() =>
318
- releaseObjectInRedis(target.objectId),
385
+ return withSimLockRetryOnce((token) =>
386
+ releaseObjectInRedis(target.objectId, token),
319
387
  );
320
- return result === true;
321
388
  });
389
+ if (released === LOCK_LOST) {
390
+ return { ok: false, reason: UNREGISTER_NACK_REASON_BUSY };
391
+ }
322
392
  if (!released) {
323
393
  return { ok: false, reason: UNREGISTER_NACK_REASON_NOT_FOUND };
324
394
  }
395
+ notifyObjectReleased(target.objectId, previousOwner);
325
396
  return { ok: true, objectId: target.objectId };
326
397
  }
327
398
 
@@ -359,23 +430,32 @@ function notifyObjectReleased(objectId: number, ownerSessionId: string): void {
359
430
 
360
431
  function broadcastWorldBuffer(): void {
361
432
  if (connectedSessionList.length === 0) return;
362
- // worldStateBytes is already a Buffer: forwarded as-is, one call, no iterator.
363
- broadCastBinaryToClients(worldStateBytes, connectedSessionList, "sync");
433
+ // Live objects only, quantized into the pod's one scratch buffer; one fan-out call.
434
+ const length = encodeLiveObjectsInto(frameScratch, worldState);
435
+ broadCastBinaryToClients(
436
+ frameScratch.subarray(0, length),
437
+ connectedSessionList,
438
+ "sync",
439
+ );
364
440
  }
365
441
 
366
442
  /**
367
- * Copy the Redis blob into `worldState` in place (the GET reply is the only
368
- * per-tick allocation; it is a fresh socket Buffer we cannot avoid).
443
+ * One Lua read of the world, the stored sim-at and Redis' clock. The world is copied into
444
+ * `worldState` in place (the reply is the only per-tick allocation we cannot avoid); sim-at
445
+ * and now land in `lastReadSimAt` / `lastReadNowMs`.
369
446
  */
370
447
  async function loadWorldFromRedis(): Promise<void> {
371
448
  if (!redis) return;
372
- const raw = await redis.getBuffer(REDIS_WORLD_KEY);
373
- normalizeWorldBuffer(raw, worldState);
374
- }
375
-
376
- async function saveWorldToRedis(): Promise<void> {
377
- if (!redis) return;
378
- await redis.set(REDIS_WORLD_KEY, worldStateBytes);
449
+ const reply = (await redis.callBuffer(
450
+ "EVAL",
451
+ LUA_READ_WORLD,
452
+ 2,
453
+ REDIS_WORLD_KEY,
454
+ REDIS_SIM_AT_KEY,
455
+ )) as Buffer[];
456
+ normalizeWorldBuffer(reply[0], worldState);
457
+ lastReadSimAt = reply[1]!.byteLength > 0 ? Number(reply[1]!.toString()) : 0;
458
+ lastReadNowMs = Number(reply[2]!.toString());
379
459
  }
380
460
 
381
461
  /** Live object ids for the current tick; filled in place, never reallocated. */
@@ -392,48 +472,73 @@ function takeTickDtSec(): number {
392
472
  const now = Date.now();
393
473
  const dt = clampSimulationDtSec(
394
474
  lastTickTimeMs === 0 ? 0 : now - lastTickTimeMs,
395
- BROADCAST_HZ,
475
+ SIM_HZ,
396
476
  );
397
477
  lastTickTimeMs = now;
398
478
  return dt;
399
479
  }
400
480
 
401
- function stepWorldInPlace(): void {
402
- const dt = takeTickDtSec();
481
+ function stepWorldInPlace(dtSec: number): void {
403
482
  const count = collectActiveObjectIdsInto(worldState, activeObjectIds);
404
- simulateWorldStep(worldState, dt, activeObjectIds, count);
483
+ simulateWorldStep(worldState, dtSec, activeObjectIds, count);
405
484
  }
406
485
 
407
486
  async function stepWorldInMemory(): Promise<void> {
408
- stepWorldInPlace();
487
+ stepWorldInPlace(takeTickDtSec());
409
488
  }
410
489
 
411
- async function stepWorldWithRedis(): Promise<boolean> {
490
+ type StepOutcome = "stepped" | "skipped" | "lost";
491
+
492
+ /**
493
+ * Leader step under the sim lock: dt comes from the stored sim-at (Redis clock). Below one
494
+ * sim interval another pod already stepped this interval, so skip. The commit writes the
495
+ * world and sim-at together only while the lock still holds `token`.
496
+ */
497
+ async function stepWorldWithRedis(token: string): Promise<StepOutcome> {
498
+ if (!redis) return "lost";
412
499
  await loadWorldFromRedis();
413
- stepWorldInPlace();
414
- await saveWorldToRedis();
415
- broadcastWorldBuffer();
416
- return true;
500
+ const now = lastReadNowMs;
501
+ const dt = planRedisStepDtSec(lastReadSimAt, now);
502
+ if (dt === null) return "skipped";
503
+ stepWorldInPlace(dt);
504
+ const written = await redis.eval(
505
+ LUA_COMMIT_WORLD,
506
+ 3,
507
+ REDIS_SIM_LOCK_KEY,
508
+ REDIS_WORLD_KEY,
509
+ REDIS_SIM_AT_KEY,
510
+ token,
511
+ worldStateBytes,
512
+ String(now),
513
+ );
514
+ if (Number(written) !== 1) return "lost";
515
+ lastReadSimAt = now;
516
+ return "stepped";
417
517
  }
418
518
 
419
519
  async function runRedisTick(): Promise<void> {
420
- const lockResult = await withRedisSimLock(
421
- stepWorldWithRedis,
422
- SIM_LOCK_TRY_ONCE,
423
- );
424
- if (lockResult !== null) return;
425
- takeTickDtSec();
426
- if (planRedisSimTick(SIM_TICK_PLAN_INPUT) === "relay") {
520
+ tickCount += 1;
521
+ const broadcastDue = tickCount % BROADCAST_EVERY_N_TICKS === 0;
522
+ const outcome = await withRedisSimLock(stepWorldWithRedis, SIM_LOCK_TRY_ONCE);
523
+ if (outcome === "lost") return;
524
+ if (outcome === null) {
525
+ if (!broadcastDue) return;
526
+ if (planRedisSimTick(SIM_TICK_PLAN_INPUT) !== "relay") return;
427
527
  await loadWorldFromRedis();
428
- broadcastWorldBuffer();
429
528
  }
529
+ if (!broadcastDue || connectedSessionList.length === 0) return;
530
+ // Relay only when sim-at advanced since this pod's last frame.
531
+ if (lastReadSimAt <= lastRelayedSimAt) return;
532
+ lastRelayedSimAt = lastReadSimAt;
533
+ broadcastWorldBuffer();
430
534
  }
431
535
 
432
536
  // Tick bodies are module-level functions (no per-tick closures or option objects).
433
537
  async function runSimulationTick(): Promise<void> {
434
538
  if (!redis) {
539
+ tickCount += 1;
435
540
  await withWorldMutation(stepWorldInMemory);
436
- broadcastWorldBuffer();
541
+ if (tickCount % BROADCAST_EVERY_N_TICKS === 0) broadcastWorldBuffer();
437
542
  return;
438
543
  }
439
544
  await withWorldMutation(runRedisTick);
@@ -459,8 +564,11 @@ function startBroadcastLoopIfNeeded(): void {
459
564
  if (broadcastTimer) return;
460
565
  if (!redis && connectedSessions.size < 1) return;
461
566
 
462
- broadcastTimer = setInterval(onBroadcastTick, BROADCAST_INTERVAL_MS);
463
- agentLog("info", `world loop started (${BROADCAST_HZ}Hz)`);
567
+ broadcastTimer = setInterval(onBroadcastTick, SIM_INTERVAL_MS);
568
+ agentLog(
569
+ "info",
570
+ `world loop started (sim ${SIM_HZ}Hz, broadcast ${BROADCAST_HZ}Hz)`,
571
+ );
464
572
  }
465
573
 
466
574
  function stopBroadcastLoopIfNeeded(): void {
@@ -542,11 +650,18 @@ defineAgent({
542
650
  if (!redis) {
543
651
  return registerObjectInMemory(ctx.sessionId);
544
652
  }
545
- const result = await withRedisSimLock(() =>
546
- registerObjectInRedis(ctx.sessionId),
653
+ return withSimLockRetryOnce((token) =>
654
+ registerObjectInRedis(ctx.sessionId, token),
547
655
  );
548
- return result;
549
656
  });
657
+ if (objectId === LOCK_LOST) {
658
+ sendToClient(ctx.sessionId, {
659
+ type: "register_nack",
660
+ reason: REGISTER_NACK_REASON_BUSY,
661
+ });
662
+ agentLog("info", `register_nack busy session=${ctx.sessionId}`);
663
+ return;
664
+ }
550
665
  if (objectId === null) {
551
666
  sendToClient(ctx.sessionId, {
552
667
  type: "register_nack",
@@ -5,6 +5,9 @@
5
5
  export const MAX_LIVE_OBJECTS = 25;
6
6
 
7
7
  export const REGISTER_NACK_REASON_WORLD_FULL = "world_full" as const;
8
+ /** Redis sim lock lost twice in a row (another pod held it past our TTL); retry later. */
9
+ export const REGISTER_NACK_REASON_BUSY = "busy" as const;
10
+ export const UNREGISTER_NACK_REASON_BUSY = "busy" as const;
8
11
  export const UNREGISTER_NACK_REASON_NOT_FOUND = "not_found" as const;
9
12
  export const UNREGISTER_NACK_REASON_NOT_OWNER = "not_owner" as const;
10
13