@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.
- package/README.md +11 -11
- package/dist/llm/mcp/mcp-tool-source.d.ts +10 -0
- package/dist/llm/mcp/mcp-tool-source.d.ts.map +1 -1
- package/dist/llm/mcp/mcp-tool-source.js +50 -2
- package/dist/llm/mcp/mcp-tool-source.js.map +1 -1
- package/dist/templates/flow-agent/agent.js +42 -3
- package/dist/templates/game-sync/agent.js +256 -52
- package/dist/templates/llm-agent/agent.js +42 -3
- package/dist/templates/llm-board/agent.js +42 -3
- package/dist/templates/llm-docs-rag/agent.js +42 -3
- package/dist/templates/llm-language-switch/agent.js +42 -3
- package/dist/templates/llm-language-tutor/agent.js +42 -3
- package/dist/templates/llm-mcp-service/agent.js +42 -3
- package/dist/templates/llm-store-support/agent.js +42 -3
- package/dist/templates/llm-support-sticky-user/agent.js +42 -3
- package/dist/templates/registry.d.ts.map +1 -1
- package/dist/templates/registry.js +8 -3
- package/dist/templates/registry.js.map +1 -1
- package/dist/templates/world-sync/agent.js +22 -1
- package/dist/templates/world-sync-binary/agent.js +22 -1
- package/eject/llm/loop.ts +1 -1
- package/package.json +30 -1
- package/templates/README.md +11 -11
- package/templates/game-sync/README.md +13 -4
- package/templates/game-sync/agent.ts +175 -60
- package/templates/game-sync/protocol.ts +3 -0
- package/templates/game-sync/quantize.ts +53 -0
- package/templates/game-sync/redis.ts +51 -1
- package/templates/game-sync/sim.ts +6 -0
- package/templates/game-sync/world-layout.ts +191 -0
- package/templates/redis-sync/README.md +7 -5
- package/templates/redis-sync/agent.ts +77 -65
- package/templates/redis-sync/quantize.ts +53 -0
- package/templates/redis-sync/quantized-frames.vectors.json +249 -0
- package/templates/redis-sync/world-layout.ts +278 -116
- package/templates/world-sync/README.md +1 -1
- package/templates/world-sync/agent.ts +39 -4
- package/templates/world-sync-binary/README.md +1 -1
- package/templates/world-sync-binary/agent.ts +29 -2
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* int16 quantizer shared by the data-sync templates (plan 2026-11-20-sync-template-efficiency).
|
|
3
|
+
*
|
|
4
|
+
* A bounded range [min, max] maps onto [-32767, 32767] (-32768 is never produced), so the
|
|
5
|
+
* step is (max - min) / 65534 and a round trip is off by at most half a step. Values outside
|
|
6
|
+
* the range are clamped. NaN and +-Infinity are not quantizable: callers check
|
|
7
|
+
* {@link isQuantizable} and drop (and count) the pose instead of encoding it.
|
|
8
|
+
*
|
|
9
|
+
* game-sync carries a same-content copy of this file (templates are self-contained
|
|
10
|
+
* workspaces; a test keeps the two copies identical).
|
|
11
|
+
*/
|
|
12
|
+
export const QUANT_MAX = 32767;
|
|
13
|
+
export const QUANT_STEPS = QUANT_MAX * 2;
|
|
14
|
+
|
|
15
|
+
export function isQuantizable(v: number): boolean {
|
|
16
|
+
return Number.isFinite(v);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function assertQuantizable(v: number): void {
|
|
20
|
+
if (!Number.isFinite(v)) {
|
|
21
|
+
throw new RangeError(`cannot quantize non-finite value ${String(v)}`);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Quantize `v` clamped to [min, max] into an int16 in [-32767, 32767]. */
|
|
26
|
+
export function quantize(v: number, min: number, max: number): number {
|
|
27
|
+
assertQuantizable(v);
|
|
28
|
+
const clamped = v < min ? min : v > max ? max : v;
|
|
29
|
+
const q =
|
|
30
|
+
Math.round(((clamped - min) / (max - min)) * QUANT_STEPS) - QUANT_MAX;
|
|
31
|
+
// `+ 0` turns -0 into 0.
|
|
32
|
+
return q + 0;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function dequantize(q: number, min: number, max: number): number {
|
|
36
|
+
return min + ((q + QUANT_MAX) / QUANT_STEPS) * (max - min);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Quantize a unit component (direction, rotation) in [-1, 1]. */
|
|
40
|
+
export function quantizeUnit(v: number): number {
|
|
41
|
+
assertQuantizable(v);
|
|
42
|
+
const clamped = v < -1 ? -1 : v > 1 ? 1 : v;
|
|
43
|
+
return Math.round(clamped * QUANT_MAX) + 0;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function dequantizeUnit(q: number): number {
|
|
47
|
+
return q / QUANT_MAX;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Size of one quantization step for [min, max]. */
|
|
51
|
+
export function quantStep(min: number, max: number): number {
|
|
52
|
+
return (max - min) / QUANT_STEPS;
|
|
53
|
+
}
|
|
@@ -6,6 +6,8 @@ import {
|
|
|
6
6
|
OBJECT_ID_HEADERS_BLOB,
|
|
7
7
|
OBJECT_SLOT_BYTE_LENGTH,
|
|
8
8
|
WORLD_BYTE_LENGTH,
|
|
9
|
+
REDIS_SIM_AT_KEY,
|
|
10
|
+
REDIS_SIM_LOCK_KEY,
|
|
9
11
|
REDIS_WORLD_KEY,
|
|
10
12
|
} from "./world-layout.js";
|
|
11
13
|
|
|
@@ -17,6 +19,8 @@ export { OBJECT_ID_HEADERS_BLOB };
|
|
|
17
19
|
*
|
|
18
20
|
* ARGV[4] = 32-byte tail (8 floats: pos + dir without objectId header)
|
|
19
21
|
* ARGV[5] = 100-byte objectId header lookup blob
|
|
22
|
+
* ARGV[6] = sim-lock token; KEYS[2] = sim-lock key. Returns -3 (writes nothing) when the
|
|
23
|
+
* lock no longer holds this token (TTL lapsed and another pod took it).
|
|
20
24
|
*/
|
|
21
25
|
export const LUA_ALLOCATE_OBJECT = `
|
|
22
26
|
local key = KEYS[1]
|
|
@@ -26,6 +30,10 @@ local max_slots = tonumber(ARGV[3])
|
|
|
26
30
|
local tail = ARGV[4]
|
|
27
31
|
local headers = ARGV[5]
|
|
28
32
|
|
|
33
|
+
if redis.call('GET', KEYS[2]) ~= ARGV[6] then
|
|
34
|
+
return -3
|
|
35
|
+
end
|
|
36
|
+
|
|
29
37
|
local world = redis.call('GET', key)
|
|
30
38
|
if not world then
|
|
31
39
|
world = string.rep(string.char(0), size)
|
|
@@ -66,7 +74,8 @@ return object_id
|
|
|
66
74
|
|
|
67
75
|
/**
|
|
68
76
|
* Zero the fixed slot for objectId when the header matches.
|
|
69
|
-
* Returns 1 on success, 0 when slot empty or objectId mismatch
|
|
77
|
+
* Returns 1 on success, 0 when slot empty or objectId mismatch, -3 (writes nothing) when
|
|
78
|
+
* the sim lock (KEYS[2]) no longer holds the token in ARGV[6].
|
|
70
79
|
*/
|
|
71
80
|
export const LUA_RELEASE_OBJECT = `
|
|
72
81
|
local key = KEYS[1]
|
|
@@ -76,6 +85,10 @@ local max_slots = tonumber(ARGV[3])
|
|
|
76
85
|
local object_id = tonumber(ARGV[4])
|
|
77
86
|
local headers = ARGV[5]
|
|
78
87
|
|
|
88
|
+
if redis.call('GET', KEYS[2]) ~= ARGV[6] then
|
|
89
|
+
return -3
|
|
90
|
+
end
|
|
91
|
+
|
|
79
92
|
if object_id < 1 or object_id > max_slots then
|
|
80
93
|
return 0
|
|
81
94
|
end
|
|
@@ -103,8 +116,45 @@ redis.call('SET', key, world)
|
|
|
103
116
|
return 1
|
|
104
117
|
`;
|
|
105
118
|
|
|
119
|
+
/** Release the sim lock only while it still holds this token (KEYS[1] = lock, ARGV[1] = token). */
|
|
120
|
+
export const LUA_RELEASE_LOCK = `
|
|
121
|
+
if redis.call('GET', KEYS[1]) == ARGV[1] then
|
|
122
|
+
return redis.call('DEL', KEYS[1])
|
|
123
|
+
end
|
|
124
|
+
return 0
|
|
125
|
+
`;
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* One round trip for a tick: the world, the stored sim time and Redis' own clock (ms), so
|
|
129
|
+
* every pod measures dt against the same clock whatever its local skew.
|
|
130
|
+
* KEYS = world, sim-at. Returns {world or '', sim-at or '', now}.
|
|
131
|
+
*/
|
|
132
|
+
export const LUA_READ_WORLD = `
|
|
133
|
+
local world = redis.call('GET', KEYS[1])
|
|
134
|
+
local sim_at = redis.call('GET', KEYS[2])
|
|
135
|
+
local t = redis.call('TIME')
|
|
136
|
+
local now = string.format('%.0f', t[1] * 1000 + math.floor(t[2] / 1000))
|
|
137
|
+
return { world or '', sim_at or '', now }
|
|
138
|
+
`;
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Conditional world write: only while the lock holds the token, SET the world and sim-at
|
|
142
|
+
* together. KEYS = lock, world, sim-at; ARGV = token, world bytes, sim-at ms.
|
|
143
|
+
* Returns 1 when written, 0 when the lock was lost (nothing written).
|
|
144
|
+
*/
|
|
145
|
+
export const LUA_COMMIT_WORLD = `
|
|
146
|
+
if redis.call('GET', KEYS[1]) ~= ARGV[1] then
|
|
147
|
+
return 0
|
|
148
|
+
end
|
|
149
|
+
redis.call('SET', KEYS[2], ARGV[2])
|
|
150
|
+
redis.call('SET', KEYS[3], ARGV[3])
|
|
151
|
+
return 1
|
|
152
|
+
`;
|
|
153
|
+
|
|
106
154
|
export const REDIS_EVAL_KEYS = {
|
|
107
155
|
worldKey: REDIS_WORLD_KEY,
|
|
156
|
+
lockKey: REDIS_SIM_LOCK_KEY,
|
|
157
|
+
simAtKey: REDIS_SIM_AT_KEY,
|
|
108
158
|
worldByteLength: String(WORLD_BYTE_LENGTH),
|
|
109
159
|
slotByteLength: String(OBJECT_SLOT_BYTE_LENGTH),
|
|
110
160
|
maxSlots: String(MAX_LIVE_OBJECTS),
|
|
@@ -3,6 +3,12 @@
|
|
|
3
3
|
*/
|
|
4
4
|
import { objectIdToSlot } from "./world-layout.js";
|
|
5
5
|
|
|
6
|
+
/** Physics steps per second; the world broadcasts every SIM_HZ / BROADCAST_HZ-th step. */
|
|
7
|
+
export const SIM_HZ = 60;
|
|
8
|
+
export const BROADCAST_HZ = 30;
|
|
9
|
+
/** Initial speed range (px/s) of a new object; collisions can raise one component to MAX_SPEED x sqrt(2). */
|
|
10
|
+
export const MIN_SPEED = 90;
|
|
11
|
+
export const MAX_SPEED = 180;
|
|
6
12
|
export const BOARD_WIDTH = 1280;
|
|
7
13
|
export const BOARD_HEIGHT = 720;
|
|
8
14
|
export const OBJECT_RADIUS = 25;
|
|
@@ -6,6 +6,13 @@
|
|
|
6
6
|
* Empty slot: objectId === 0
|
|
7
7
|
*/
|
|
8
8
|
import { MAX_LIVE_OBJECTS } from "./protocol.js";
|
|
9
|
+
import {
|
|
10
|
+
dequantize,
|
|
11
|
+
dequantizeUnit,
|
|
12
|
+
isQuantizable,
|
|
13
|
+
quantize,
|
|
14
|
+
quantizeUnit,
|
|
15
|
+
} from "./quantize.js";
|
|
9
16
|
|
|
10
17
|
export const OBJECT_STRIDE = 9;
|
|
11
18
|
export const WORLD_FLOAT_COUNT = MAX_LIVE_OBJECTS * OBJECT_STRIDE;
|
|
@@ -14,6 +21,31 @@ export const OBJECT_SLOT_BYTE_LENGTH = OBJECT_STRIDE * 4;
|
|
|
14
21
|
|
|
15
22
|
export const REDIS_WORLD_KEY = "game-sync:world";
|
|
16
23
|
export const REDIS_SIM_LOCK_KEY = "game-sync:sim-lock";
|
|
24
|
+
/** Redis time (ms) at which the stored world was last stepped; written with the world. */
|
|
25
|
+
export const REDIS_SIM_AT_KEY = "game-sync:sim-at";
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Broadcast frame (agent -> client, quantized int16; the Redis world stays float32):
|
|
29
|
+
* u8 format (2) · u8 version (1) · u16le objectCount · objectCount x 18 B
|
|
30
|
+
* record = u16le objectId · 8 x i16le [posX posY posZ posW dirX dirY dirZ dirW]
|
|
31
|
+
* Live objects only. Bounds below: x in [0, BOARD_X_MAX], y in [0, BOARD_Y_MAX] (they equal
|
|
32
|
+
* BOARD_WIDTH / BOARD_HEIGHT in sim.ts), dirX/dirY (velocity, px/s) in [-VELOCITY_LIMIT,
|
|
33
|
+
* VELOCITY_LIMIT]; z, w and dirZ/dirW are unit components (round(v x 32767)).
|
|
34
|
+
* Matching test vectors: templates/redis-sync/quantized-frames.vectors.json, `gameSync`.
|
|
35
|
+
*/
|
|
36
|
+
export const FRAME_FORMAT_QUANTIZED = 2;
|
|
37
|
+
export const FRAME_VERSION = 1;
|
|
38
|
+
export const FRAME_HEADER_BYTES = 4;
|
|
39
|
+
export const FRAME_RECORD_BYTES = 18;
|
|
40
|
+
export const MAX_FRAME_BYTES =
|
|
41
|
+
FRAME_HEADER_BYTES + MAX_LIVE_OBJECTS * FRAME_RECORD_BYTES;
|
|
42
|
+
export const BOARD_X_MAX = 1280;
|
|
43
|
+
export const BOARD_Y_MAX = 720;
|
|
44
|
+
/**
|
|
45
|
+
* Elastic collisions can pass energy to one object (about 900 px/s with 25 objects), so the
|
|
46
|
+
* range is 1024; a component beyond it is clamped and counted ({@link getClampedComponentCount}).
|
|
47
|
+
*/
|
|
48
|
+
export const VELOCITY_LIMIT = 1024;
|
|
17
49
|
|
|
18
50
|
export function slotToObjectId(slot: number): number {
|
|
19
51
|
return slot + 1;
|
|
@@ -279,3 +311,162 @@ export function objectIdHeaderBytes(objectId: number): Buffer {
|
|
|
279
311
|
const index = objectId - 1;
|
|
280
312
|
return OBJECT_ID_HEADERS_BLOB.subarray(index * 4, index * 4 + 4);
|
|
281
313
|
}
|
|
314
|
+
|
|
315
|
+
/** Thrown for a frame with an unknown format or version byte, or a bad length. Never guessed. */
|
|
316
|
+
export class WorldFrameError extends Error {
|
|
317
|
+
constructor(message: string) {
|
|
318
|
+
super(message);
|
|
319
|
+
this.name = "WorldFrameError";
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
export type DecodedObject = {
|
|
324
|
+
objectId: number;
|
|
325
|
+
/** Raw quantized [posX posY posZ posW dirX dirY dirZ dirW]. */
|
|
326
|
+
q: number[];
|
|
327
|
+
};
|
|
328
|
+
|
|
329
|
+
/** Objects dropped by {@link encodeLiveObjectsInto} for a non-finite component. */
|
|
330
|
+
let invalidObjectDrops = 0;
|
|
331
|
+
/** Components {@link encodeLiveObjectsInto} clamped to their quantization range. */
|
|
332
|
+
let clampedComponents = 0;
|
|
333
|
+
|
|
334
|
+
export function getClampedComponentCount(): number {
|
|
335
|
+
return clampedComponents;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
function quantizeCounted(v: number, min: number, max: number): number {
|
|
339
|
+
if (v < min || v > max) clampedComponents += 1;
|
|
340
|
+
return quantize(v, min, max);
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
function quantizeUnitCounted(v: number): number {
|
|
344
|
+
if (v < -1 || v > 1) clampedComponents += 1;
|
|
345
|
+
return quantizeUnit(v);
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
export function invalidObjectDropCount(): number {
|
|
349
|
+
return invalidObjectDrops;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
function writeI16(dest: Uint8Array, offset: number, v: number): void {
|
|
353
|
+
dest[offset] = v & 0xff;
|
|
354
|
+
dest[offset + 1] = (v >> 8) & 0xff;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function readI16(src: Uint8Array, offset: number): number {
|
|
358
|
+
const v = src[offset]! | (src[offset + 1]! << 8);
|
|
359
|
+
return v >= 0x8000 ? v - 0x10000 : v;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
function slotIsQuantizable(world: Float32Array, start: number): boolean {
|
|
363
|
+
for (let i = 1; i < OBJECT_STRIDE; i += 1) {
|
|
364
|
+
if (!isQuantizable(world[start + i]!)) return false;
|
|
365
|
+
}
|
|
366
|
+
return true;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* Quantize every live slot of `world` into `dest` (capacity >= MAX_FRAME_BYTES) and return
|
|
371
|
+
* the frame length. No allocation. A live slot with a non-finite component is dropped and
|
|
372
|
+
* counted ({@link invalidObjectDropCount}); it is never encoded.
|
|
373
|
+
*/
|
|
374
|
+
export function encodeLiveObjectsInto(
|
|
375
|
+
dest: Uint8Array,
|
|
376
|
+
world: Float32Array,
|
|
377
|
+
): number {
|
|
378
|
+
let count = 0;
|
|
379
|
+
let at = FRAME_HEADER_BYTES;
|
|
380
|
+
for (let slot = 0; slot < MAX_LIVE_OBJECTS; slot += 1) {
|
|
381
|
+
const start = slot * OBJECT_STRIDE;
|
|
382
|
+
const objectId = readSlotObjectId(world, slot);
|
|
383
|
+
if (objectId === 0) continue;
|
|
384
|
+
if (!slotIsQuantizable(world, start)) {
|
|
385
|
+
invalidObjectDrops += 1;
|
|
386
|
+
continue;
|
|
387
|
+
}
|
|
388
|
+
dest[at] = objectId & 0xff;
|
|
389
|
+
dest[at + 1] = (objectId >> 8) & 0xff;
|
|
390
|
+
writeI16(dest, at + 2, quantizeCounted(world[start + 1]!, 0, BOARD_X_MAX));
|
|
391
|
+
writeI16(dest, at + 4, quantizeCounted(world[start + 2]!, 0, BOARD_Y_MAX));
|
|
392
|
+
writeI16(dest, at + 6, quantizeUnitCounted(world[start + 3]!));
|
|
393
|
+
writeI16(dest, at + 8, quantizeUnitCounted(world[start + 4]!));
|
|
394
|
+
writeI16(
|
|
395
|
+
dest,
|
|
396
|
+
at + 10,
|
|
397
|
+
quantizeCounted(world[start + 5]!, -VELOCITY_LIMIT, VELOCITY_LIMIT),
|
|
398
|
+
);
|
|
399
|
+
writeI16(
|
|
400
|
+
dest,
|
|
401
|
+
at + 12,
|
|
402
|
+
quantizeCounted(world[start + 6]!, -VELOCITY_LIMIT, VELOCITY_LIMIT),
|
|
403
|
+
);
|
|
404
|
+
writeI16(dest, at + 14, quantizeUnitCounted(world[start + 7]!));
|
|
405
|
+
writeI16(dest, at + 16, quantizeUnitCounted(world[start + 8]!));
|
|
406
|
+
at += FRAME_RECORD_BYTES;
|
|
407
|
+
count += 1;
|
|
408
|
+
}
|
|
409
|
+
dest[0] = FRAME_FORMAT_QUANTIZED;
|
|
410
|
+
dest[1] = FRAME_VERSION;
|
|
411
|
+
dest[2] = count & 0xff;
|
|
412
|
+
dest[3] = (count >> 8) & 0xff;
|
|
413
|
+
return at;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
export function decodeLiveObjectsFrame(data: Uint8Array): DecodedObject[] {
|
|
417
|
+
if (data.byteLength < FRAME_HEADER_BYTES) {
|
|
418
|
+
throw new WorldFrameError(`frame too short: ${data.byteLength} bytes`);
|
|
419
|
+
}
|
|
420
|
+
if (data[0] !== FRAME_FORMAT_QUANTIZED) {
|
|
421
|
+
throw new WorldFrameError(`unknown frame format ${data[0]}`);
|
|
422
|
+
}
|
|
423
|
+
if (data[1] !== FRAME_VERSION) {
|
|
424
|
+
throw new WorldFrameError(`unknown frame version ${data[1]}`);
|
|
425
|
+
}
|
|
426
|
+
const count = data[2]! | (data[3]! << 8);
|
|
427
|
+
if (data.byteLength !== FRAME_HEADER_BYTES + count * FRAME_RECORD_BYTES) {
|
|
428
|
+
throw new WorldFrameError(
|
|
429
|
+
`frame length ${data.byteLength} does not match objectCount ${count}`,
|
|
430
|
+
);
|
|
431
|
+
}
|
|
432
|
+
const objects: DecodedObject[] = [];
|
|
433
|
+
for (let i = 0; i < count; i += 1) {
|
|
434
|
+
const o = FRAME_HEADER_BYTES + i * FRAME_RECORD_BYTES;
|
|
435
|
+
const q: number[] = [];
|
|
436
|
+
for (let c = 0; c < 8; c += 1) q.push(readI16(data, o + 2 + c * 2));
|
|
437
|
+
objects.push({ objectId: data[o]! | (data[o + 1]! << 8), q });
|
|
438
|
+
}
|
|
439
|
+
return objects;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/** Dequantize raw components to [posX posY posZ posW dirX dirY dirZ dirW]. */
|
|
443
|
+
export function dequantizeObject(q: readonly number[]): number[] {
|
|
444
|
+
return [
|
|
445
|
+
dequantize(q[0]!, 0, BOARD_X_MAX),
|
|
446
|
+
dequantize(q[1]!, 0, BOARD_Y_MAX),
|
|
447
|
+
dequantizeUnit(q[2]!),
|
|
448
|
+
dequantizeUnit(q[3]!),
|
|
449
|
+
dequantize(q[4]!, -VELOCITY_LIMIT, VELOCITY_LIMIT),
|
|
450
|
+
dequantize(q[5]!, -VELOCITY_LIMIT, VELOCITY_LIMIT),
|
|
451
|
+
dequantizeUnit(q[6]!),
|
|
452
|
+
dequantizeUnit(q[7]!),
|
|
453
|
+
];
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/** A step is skipped when less than half a 60 Hz interval has passed since the stored sim-at. */
|
|
457
|
+
export const SIM_STEP_MIN_MS = Math.floor(1000 / 60) / 2;
|
|
458
|
+
export const SIM_STEP_MAX_SEC = 0.05;
|
|
459
|
+
|
|
460
|
+
/**
|
|
461
|
+
* dt (s) to step from the stored sim-at, or null to skip. No lower clamp, so the sum of
|
|
462
|
+
* dt equals Redis wall time whatever the timer jitter. No stored sim-at: one interval.
|
|
463
|
+
*/
|
|
464
|
+
export function planRedisStepDtSec(
|
|
465
|
+
simAtMs: number,
|
|
466
|
+
nowMs: number,
|
|
467
|
+
): number | null {
|
|
468
|
+
if (simAtMs === 0) return 1 / 60;
|
|
469
|
+
const elapsed = nowMs - simAtMs;
|
|
470
|
+
if (elapsed < SIM_STEP_MIN_MS) return null;
|
|
471
|
+
return Math.min(SIM_STEP_MAX_SEC, elapsed / 1000);
|
|
472
|
+
}
|
|
@@ -2,13 +2,15 @@
|
|
|
2
2
|
|
|
3
3
|
Redis-backed world buffer sync for redis-sync-smoke (Advanced tier + project Redis). Not seeded on project create.
|
|
4
4
|
|
|
5
|
-
Clients publish a 12-byte `Float32Array([clientIndex, x, y])` on `voicethere-sync`.
|
|
5
|
+
Clients publish a 12-byte `Float32Array([clientIndex, x, y])` on `voicethere-sync`. The agent quantizes the pose once (int16 over the board, see `BOARD_MIN`/`BOARD_MAX`) and writes only that slot to Redis with `SETRANGE`. Each pod ticks at 20 Hz: one Redis GET, a diff against the world it last broadcast, and one `broadCastBinaryToClients` call with the changed slots. An empty delta is not sent. Buffers are allocated once per pod.
|
|
6
6
|
|
|
7
7
|
## Protocol
|
|
8
8
|
|
|
9
|
-
- **Inbound (12 bytes):** little-endian `float32` `[clientIndex, x, y]` via `onDataChannelBinary
|
|
10
|
-
- **Outbound:**
|
|
11
|
-
- **
|
|
9
|
+
- **Inbound (12 bytes):** little-endian `float32` `[clientIndex, x, y]` via `onDataChannelBinary`. Non-finite values and an index of 128 or more are dropped and counted.
|
|
10
|
+
- **Outbound frame:** `u8 kind (1 keyframe, 2 delta) · u8 version (1) · u16le slotCount`, then `slotCount` x 6 B slots: `u8 clientIndex · u8 active · i16le x · i16le y`. A keyframe carries every active slot and replaces the client world; a delta carries slots changed since the last broadcast, and a slot that left goes out once with `active = 0`. A decoder that sees an unknown kind or version throws `SyncFrameError`.
|
|
11
|
+
- **Keyframes:** a joining session gets one built from the last-broadcast world, and every session gets one each second (`KEYFRAME_INTERVAL_MS`).
|
|
12
|
+
- **Redis:** key `e2e:redis-sync:world:v2`, 128 x 6 B = 768 B, one `SETRANGE` of 6 B per position update (no Lua).
|
|
13
|
+
- **Test vectors:** `quantized-frames.vectors.json` (encoded frames and their decode), also exported as `@voicethere/agent/templates/redis-sync/quantized-frames.vectors.json`.
|
|
12
14
|
|
|
13
15
|
Reuse one `Float32Array(3)` on the client (`sendSyncBinary`).
|
|
14
16
|
|
|
@@ -20,4 +22,4 @@ npx @voicethere/agent build --entry templates/redis-sync/agent.ts --outfile dist
|
|
|
20
22
|
|
|
21
23
|
## Sources
|
|
22
24
|
|
|
23
|
-
- `agent.ts`, `world-layout.ts`
|
|
25
|
+
- `agent.ts`, `world-layout.ts`, `quantize.ts`
|
|
@@ -1,15 +1,18 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Redis-backed world
|
|
2
|
+
* Redis-backed world sync for redis-sync-smoke (Advanced tier + project Redis).
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
* Each client owns a fixed slot and publishes a 12-byte `ArrayBuffer`
|
|
6
|
-
* `Float32Array([clientIndex, x, y])` on the sync DataChannel.
|
|
7
|
-
*
|
|
8
|
-
* voicethere-sync to all local sessions (no pub/sub). Clients patch out of sync;
|
|
9
|
-
* the 20Hz server tick is the authoritative sync path.
|
|
4
|
+
* The world is a 128-slot x 6 B blob in Redis (`e2e:redis-sync:world:v2`, layout in
|
|
5
|
+
* `world-layout.ts`). Each client owns a fixed slot and publishes a 12-byte `ArrayBuffer`
|
|
6
|
+
* `Float32Array([clientIndex, x, y])` on the sync DataChannel. The agent quantizes the pose
|
|
7
|
+
* once and writes only that slot with `SETRANGE` (atomic, no read-modify-write).
|
|
10
8
|
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
9
|
+
* Each runner pod runs a 20Hz loop: one Redis GET, a diff against the world it last
|
|
10
|
+
* broadcast, and one delta frame (changed slots only) to all local sessions; an empty delta is
|
|
11
|
+
* not sent. A joining session gets a keyframe built from the same last-broadcast world, and
|
|
12
|
+
* every session gets a keyframe every KEYFRAME_INTERVAL_MS as a safety net.
|
|
13
|
+
*
|
|
14
|
+
* Buffers are allocated once per pod: two 768 B worlds swapped by reference and one frame
|
|
15
|
+
* scratch buffer (the send path copies synchronously, see test/binary-send-copy.test.ts).
|
|
13
16
|
*
|
|
14
17
|
* Build:
|
|
15
18
|
* npx @voicethere/agent build --entry templates/redis-sync/agent.ts --outfile dist/agent.js
|
|
@@ -25,55 +28,47 @@ import {
|
|
|
25
28
|
import {
|
|
26
29
|
createEmptyWorldBuffer,
|
|
27
30
|
decodePositionBuffer,
|
|
31
|
+
encodeDeltaInto,
|
|
32
|
+
encodeKeyframeInto,
|
|
33
|
+
encodeSlotInto,
|
|
34
|
+
MAX_FRAME_BYTES,
|
|
28
35
|
normalizeWorldBuffer,
|
|
29
|
-
peerSlotOffset,
|
|
30
|
-
PEER_SLOT_BYTE_LENGTH,
|
|
31
|
-
PEER_STRIDE,
|
|
32
36
|
REDIS_WORLD_KEY,
|
|
33
|
-
|
|
37
|
+
slotOffset,
|
|
38
|
+
SLOT_BYTES,
|
|
34
39
|
writePeerSlot,
|
|
35
|
-
LUA_PATCH_PEER_SLOT,
|
|
36
40
|
} from "./world-layout.js";
|
|
37
41
|
|
|
38
42
|
const WORLD_BROADCAST_HZ = 20;
|
|
39
43
|
const WORLD_BROADCAST_INTERVAL_MS = Math.floor(1000 / WORLD_BROADCAST_HZ);
|
|
44
|
+
export const KEYFRAME_INTERVAL_MS = 1000;
|
|
45
|
+
const KEYFRAME_EVERY_TICKS = Math.round(
|
|
46
|
+
KEYFRAME_INTERVAL_MS / WORLD_BROADCAST_INTERVAL_MS,
|
|
47
|
+
);
|
|
40
48
|
|
|
41
49
|
const connectedSessions = new Set<string>();
|
|
42
50
|
/** Same members as connectedSessions; array form for the per-tick broadcast. */
|
|
43
51
|
const connectedSessionList: string[] = [];
|
|
44
52
|
const sessionClientIndex = new Map<string, number>();
|
|
45
|
-
/**
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
);
|
|
53
|
+
/** `world` is filled by the Redis GET (or memory-mode writes); `lastSent` is what was broadcast. */
|
|
54
|
+
let world = createEmptyWorldBuffer();
|
|
55
|
+
let lastSent = createEmptyWorldBuffer();
|
|
56
|
+
/** One frame scratch buffer; the frame sent is a subarray of it. */
|
|
57
|
+
const frameScratch = Buffer.allocUnsafe(MAX_FRAME_BYTES);
|
|
58
|
+
const slotScratch = Buffer.allocUnsafe(SLOT_BYTES);
|
|
52
59
|
let redis: Redis | null = null;
|
|
53
60
|
let broadcastTimer: NodeJS.Timeout | null = null;
|
|
61
|
+
let tickCount = 0;
|
|
62
|
+
let tickInFlight = false;
|
|
63
|
+
let droppedPoses = 0;
|
|
54
64
|
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
PEER_SLOT.byteOffset,
|
|
59
|
-
PEER_SLOT.byteLength,
|
|
60
|
-
);
|
|
61
|
-
|
|
62
|
-
function encodePeerSlot(
|
|
63
|
-
clientIndex: number,
|
|
64
|
-
x: number,
|
|
65
|
-
y: number,
|
|
66
|
-
active: number,
|
|
67
|
-
): Buffer {
|
|
68
|
-
PEER_SLOT[0] = clientIndex;
|
|
69
|
-
PEER_SLOT[1] = x;
|
|
70
|
-
PEER_SLOT[2] = y;
|
|
71
|
-
PEER_SLOT[3] = active;
|
|
72
|
-
return PEER_SLOT_BUF;
|
|
65
|
+
/** Number of inbound poses dropped as invalid (non-finite or out-of-range index). */
|
|
66
|
+
export function getDroppedPoseCount(): number {
|
|
67
|
+
return droppedPoses;
|
|
73
68
|
}
|
|
74
69
|
|
|
75
|
-
function
|
|
76
|
-
const payload =
|
|
70
|
+
function sendFrame(length: number, targetSessionId?: string): void {
|
|
71
|
+
const payload = frameScratch.subarray(0, length);
|
|
77
72
|
if (targetSessionId) {
|
|
78
73
|
try {
|
|
79
74
|
sendBinaryToClient(targetSessionId, payload, "sync");
|
|
@@ -88,7 +83,6 @@ function broadcastWorldBuffer(targetSessionId?: string): void {
|
|
|
88
83
|
}
|
|
89
84
|
if (connectedSessionList.length === 0) return;
|
|
90
85
|
try {
|
|
91
|
-
// payload is already a Buffer: forwarded as-is, one call, no Set iterator.
|
|
92
86
|
broadCastBinaryToClients(payload, connectedSessionList, "sync");
|
|
93
87
|
} catch (error: unknown) {
|
|
94
88
|
const detail = error instanceof Error ? error.message : String(error);
|
|
@@ -96,18 +90,35 @@ function broadcastWorldBuffer(targetSessionId?: string): void {
|
|
|
96
90
|
}
|
|
97
91
|
}
|
|
98
92
|
|
|
99
|
-
/**
|
|
93
|
+
/** Remember what this tick broadcast: swap with Redis, copy in memory mode (world is the state). */
|
|
94
|
+
function commitLastSent(): void {
|
|
95
|
+
if (redis) {
|
|
96
|
+
const previous = lastSent;
|
|
97
|
+
lastSent = world;
|
|
98
|
+
world = previous;
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
lastSent.set(world);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Copy the Redis blob into `world` in place; the GET reply is the only allocation. */
|
|
100
105
|
async function loadWorldFromRedis(): Promise<void> {
|
|
101
106
|
if (!redis) return;
|
|
102
107
|
const raw = await redis.getBuffer(REDIS_WORLD_KEY);
|
|
103
|
-
normalizeWorldBuffer(raw,
|
|
108
|
+
normalizeWorldBuffer(raw, world);
|
|
104
109
|
}
|
|
105
110
|
|
|
106
|
-
async function
|
|
107
|
-
targetSessionId?: string,
|
|
108
|
-
): Promise<void> {
|
|
111
|
+
async function broadcastTick(): Promise<void> {
|
|
109
112
|
await loadWorldFromRedis();
|
|
110
|
-
|
|
113
|
+
if (connectedSessionList.length === 0) return;
|
|
114
|
+
tickCount += 1;
|
|
115
|
+
if (tickCount % KEYFRAME_EVERY_TICKS === 0) {
|
|
116
|
+
sendFrame(encodeKeyframeInto(frameScratch, world));
|
|
117
|
+
} else {
|
|
118
|
+
const length = encodeDeltaInto(frameScratch, world, lastSent);
|
|
119
|
+
if (length > 0) sendFrame(length);
|
|
120
|
+
}
|
|
121
|
+
commitLastSent();
|
|
111
122
|
}
|
|
112
123
|
|
|
113
124
|
function logBroadcastError(error: unknown): void {
|
|
@@ -116,7 +127,13 @@ function logBroadcastError(error: unknown): void {
|
|
|
116
127
|
}
|
|
117
128
|
|
|
118
129
|
function onBroadcastTick(): void {
|
|
119
|
-
|
|
130
|
+
if (tickInFlight) return;
|
|
131
|
+
tickInFlight = true;
|
|
132
|
+
void broadcastTick()
|
|
133
|
+
.catch(logBroadcastError)
|
|
134
|
+
.finally(() => {
|
|
135
|
+
tickInFlight = false;
|
|
136
|
+
});
|
|
120
137
|
}
|
|
121
138
|
|
|
122
139
|
function startBroadcastLoopIfNeeded(): void {
|
|
@@ -143,24 +160,14 @@ async function patchWorldSlot(
|
|
|
143
160
|
active: number,
|
|
144
161
|
): Promise<void> {
|
|
145
162
|
if (!redis) {
|
|
146
|
-
writePeerSlot(
|
|
163
|
+
writePeerSlot(world, clientIndex, x, y, active);
|
|
147
164
|
return;
|
|
148
165
|
}
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
const slot = encodePeerSlot(clientIndex, x, y, active);
|
|
152
|
-
if (slot.byteLength !== PEER_SLOT_BYTE_LENGTH) {
|
|
153
|
-
throw new Error(
|
|
154
|
-
`peer slot encode length ${slot.byteLength} != ${PEER_SLOT_BYTE_LENGTH}`,
|
|
155
|
-
);
|
|
156
|
-
}
|
|
157
|
-
await redis.eval(
|
|
158
|
-
LUA_PATCH_PEER_SLOT,
|
|
159
|
-
1,
|
|
166
|
+
const slot = encodeSlotInto(slotScratch, clientIndex, x, y, active);
|
|
167
|
+
await redis.setrange(
|
|
160
168
|
REDIS_WORLD_KEY,
|
|
161
|
-
|
|
162
|
-
slot,
|
|
163
|
-
String(WORLD_BYTE_LENGTH),
|
|
169
|
+
slotOffset(clientIndex),
|
|
170
|
+
slot as Buffer,
|
|
164
171
|
);
|
|
165
172
|
}
|
|
166
173
|
|
|
@@ -192,7 +199,8 @@ defineAgent({
|
|
|
192
199
|
connectedSessionList.push(sessionId);
|
|
193
200
|
}
|
|
194
201
|
startBroadcastLoopIfNeeded();
|
|
195
|
-
|
|
202
|
+
// Keyframe from the last-broadcast world: the same baseline the next shared delta applies to.
|
|
203
|
+
sendFrame(encodeKeyframeInto(frameScratch, lastSent), sessionId);
|
|
196
204
|
},
|
|
197
205
|
|
|
198
206
|
async onClientLeave({ sessionId }) {
|
|
@@ -219,6 +227,10 @@ defineAgent({
|
|
|
219
227
|
async onDataChannelBinary(ctx) {
|
|
220
228
|
const position = decodePositionBuffer(ctx.rawBinary);
|
|
221
229
|
if (!position) {
|
|
230
|
+
if (ctx.rawBinary && ctx.rawBinary.byteLength >= 12) {
|
|
231
|
+
droppedPoses += 1;
|
|
232
|
+
agentLog("warn", `dropped invalid pose (total ${droppedPoses})`);
|
|
233
|
+
}
|
|
222
234
|
return;
|
|
223
235
|
}
|
|
224
236
|
sessionClientIndex.set(ctx.sessionId, position.clientIndex);
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* int16 quantizer shared by the data-sync templates (plan 2026-11-20-sync-template-efficiency).
|
|
3
|
+
*
|
|
4
|
+
* A bounded range [min, max] maps onto [-32767, 32767] (-32768 is never produced), so the
|
|
5
|
+
* step is (max - min) / 65534 and a round trip is off by at most half a step. Values outside
|
|
6
|
+
* the range are clamped. NaN and +-Infinity are not quantizable: callers check
|
|
7
|
+
* {@link isQuantizable} and drop (and count) the pose instead of encoding it.
|
|
8
|
+
*
|
|
9
|
+
* game-sync carries a same-content copy of this file (templates are self-contained
|
|
10
|
+
* workspaces; a test keeps the two copies identical).
|
|
11
|
+
*/
|
|
12
|
+
export const QUANT_MAX = 32767;
|
|
13
|
+
export const QUANT_STEPS = QUANT_MAX * 2;
|
|
14
|
+
|
|
15
|
+
export function isQuantizable(v: number): boolean {
|
|
16
|
+
return Number.isFinite(v);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function assertQuantizable(v: number): void {
|
|
20
|
+
if (!Number.isFinite(v)) {
|
|
21
|
+
throw new RangeError(`cannot quantize non-finite value ${String(v)}`);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Quantize `v` clamped to [min, max] into an int16 in [-32767, 32767]. */
|
|
26
|
+
export function quantize(v: number, min: number, max: number): number {
|
|
27
|
+
assertQuantizable(v);
|
|
28
|
+
const clamped = v < min ? min : v > max ? max : v;
|
|
29
|
+
const q =
|
|
30
|
+
Math.round(((clamped - min) / (max - min)) * QUANT_STEPS) - QUANT_MAX;
|
|
31
|
+
// `+ 0` turns -0 into 0.
|
|
32
|
+
return q + 0;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function dequantize(q: number, min: number, max: number): number {
|
|
36
|
+
return min + ((q + QUANT_MAX) / QUANT_STEPS) * (max - min);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Quantize a unit component (direction, rotation) in [-1, 1]. */
|
|
40
|
+
export function quantizeUnit(v: number): number {
|
|
41
|
+
assertQuantizable(v);
|
|
42
|
+
const clamped = v < -1 ? -1 : v > 1 ? 1 : v;
|
|
43
|
+
return Math.round(clamped * QUANT_MAX) + 0;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function dequantizeUnit(q: number): number {
|
|
47
|
+
return q / QUANT_MAX;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Size of one quantization step for [min, max]. */
|
|
51
|
+
export function quantStep(min: number, max: number): number {
|
|
52
|
+
return (max - min) / QUANT_STEPS;
|
|
53
|
+
}
|