@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
@@ -10755,6 +10755,7 @@ var require_built3 = __commonJS({
10755
10755
 
10756
10756
  // templates/game-sync/agent.ts
10757
10757
  var import_ioredis = __toESM(require_built3(), 1);
10758
+ import { randomUUID as randomUUID2 } from "node:crypto";
10758
10759
 
10759
10760
  // dist/runtime.js
10760
10761
  import { randomUUID } from "node:crypto";
@@ -12147,6 +12148,8 @@ function agentLog(level, message, fieldsOrSessionId, sessionId) {
12147
12148
  // templates/game-sync/protocol.ts
12148
12149
  var MAX_LIVE_OBJECTS = 25;
12149
12150
  var REGISTER_NACK_REASON_WORLD_FULL = "world_full";
12151
+ var REGISTER_NACK_REASON_BUSY = "busy";
12152
+ var UNREGISTER_NACK_REASON_BUSY = "busy";
12150
12153
  var UNREGISTER_NACK_REASON_NOT_FOUND = "not_found";
12151
12154
  function parseRegisterCommand(message) {
12152
12155
  if (!message || typeof message !== "object") return false;
@@ -12188,6 +12191,29 @@ function parseChatCommand(message) {
12188
12191
  return { text };
12189
12192
  }
12190
12193
 
12194
+ // templates/game-sync/quantize.ts
12195
+ var QUANT_MAX = 32767;
12196
+ var QUANT_STEPS = QUANT_MAX * 2;
12197
+ function isQuantizable(v) {
12198
+ return Number.isFinite(v);
12199
+ }
12200
+ function assertQuantizable(v) {
12201
+ if (!Number.isFinite(v)) {
12202
+ throw new RangeError(`cannot quantize non-finite value ${String(v)}`);
12203
+ }
12204
+ }
12205
+ function quantize(v, min, max) {
12206
+ assertQuantizable(v);
12207
+ const clamped = v < min ? min : v > max ? max : v;
12208
+ const q = Math.round((clamped - min) / (max - min) * QUANT_STEPS) - QUANT_MAX;
12209
+ return q + 0;
12210
+ }
12211
+ function quantizeUnit(v) {
12212
+ assertQuantizable(v);
12213
+ const clamped = v < -1 ? -1 : v > 1 ? 1 : v;
12214
+ return Math.round(clamped * QUANT_MAX) + 0;
12215
+ }
12216
+
12191
12217
  // templates/game-sync/world-layout.ts
12192
12218
  var OBJECT_STRIDE = 9;
12193
12219
  var WORLD_FLOAT_COUNT = MAX_LIVE_OBJECTS * OBJECT_STRIDE;
@@ -12195,6 +12221,15 @@ var WORLD_BYTE_LENGTH = WORLD_FLOAT_COUNT * 4;
12195
12221
  var OBJECT_SLOT_BYTE_LENGTH = OBJECT_STRIDE * 4;
12196
12222
  var REDIS_WORLD_KEY = "game-sync:world";
12197
12223
  var REDIS_SIM_LOCK_KEY = "game-sync:sim-lock";
12224
+ var REDIS_SIM_AT_KEY = "game-sync:sim-at";
12225
+ var FRAME_FORMAT_QUANTIZED = 2;
12226
+ var FRAME_VERSION = 1;
12227
+ var FRAME_HEADER_BYTES = 4;
12228
+ var FRAME_RECORD_BYTES = 18;
12229
+ var MAX_FRAME_BYTES = FRAME_HEADER_BYTES + MAX_LIVE_OBJECTS * FRAME_RECORD_BYTES;
12230
+ var BOARD_X_MAX = 1280;
12231
+ var BOARD_Y_MAX = 720;
12232
+ var VELOCITY_LIMIT = 1024;
12198
12233
  function slotToObjectId(slot) {
12199
12234
  return slot + 1;
12200
12235
  }
@@ -12326,6 +12361,72 @@ var OBJECT_ID_HEADERS_BLOB = (() => {
12326
12361
  }
12327
12362
  return blob;
12328
12363
  })();
12364
+ var invalidObjectDrops = 0;
12365
+ var clampedComponents = 0;
12366
+ function quantizeCounted(v, min, max) {
12367
+ if (v < min || v > max) clampedComponents += 1;
12368
+ return quantize(v, min, max);
12369
+ }
12370
+ function quantizeUnitCounted(v) {
12371
+ if (v < -1 || v > 1) clampedComponents += 1;
12372
+ return quantizeUnit(v);
12373
+ }
12374
+ function writeI16(dest, offset, v) {
12375
+ dest[offset] = v & 255;
12376
+ dest[offset + 1] = v >> 8 & 255;
12377
+ }
12378
+ function slotIsQuantizable(world, start) {
12379
+ for (let i = 1; i < OBJECT_STRIDE; i += 1) {
12380
+ if (!isQuantizable(world[start + i])) return false;
12381
+ }
12382
+ return true;
12383
+ }
12384
+ function encodeLiveObjectsInto(dest, world) {
12385
+ let count = 0;
12386
+ let at = FRAME_HEADER_BYTES;
12387
+ for (let slot = 0; slot < MAX_LIVE_OBJECTS; slot += 1) {
12388
+ const start = slot * OBJECT_STRIDE;
12389
+ const objectId = readSlotObjectId(world, slot);
12390
+ if (objectId === 0) continue;
12391
+ if (!slotIsQuantizable(world, start)) {
12392
+ invalidObjectDrops += 1;
12393
+ continue;
12394
+ }
12395
+ dest[at] = objectId & 255;
12396
+ dest[at + 1] = objectId >> 8 & 255;
12397
+ writeI16(dest, at + 2, quantizeCounted(world[start + 1], 0, BOARD_X_MAX));
12398
+ writeI16(dest, at + 4, quantizeCounted(world[start + 2], 0, BOARD_Y_MAX));
12399
+ writeI16(dest, at + 6, quantizeUnitCounted(world[start + 3]));
12400
+ writeI16(dest, at + 8, quantizeUnitCounted(world[start + 4]));
12401
+ writeI16(
12402
+ dest,
12403
+ at + 10,
12404
+ quantizeCounted(world[start + 5], -VELOCITY_LIMIT, VELOCITY_LIMIT)
12405
+ );
12406
+ writeI16(
12407
+ dest,
12408
+ at + 12,
12409
+ quantizeCounted(world[start + 6], -VELOCITY_LIMIT, VELOCITY_LIMIT)
12410
+ );
12411
+ writeI16(dest, at + 14, quantizeUnitCounted(world[start + 7]));
12412
+ writeI16(dest, at + 16, quantizeUnitCounted(world[start + 8]));
12413
+ at += FRAME_RECORD_BYTES;
12414
+ count += 1;
12415
+ }
12416
+ dest[0] = FRAME_FORMAT_QUANTIZED;
12417
+ dest[1] = FRAME_VERSION;
12418
+ dest[2] = count & 255;
12419
+ dest[3] = count >> 8 & 255;
12420
+ return at;
12421
+ }
12422
+ var SIM_STEP_MIN_MS = Math.floor(1e3 / 60) / 2;
12423
+ var SIM_STEP_MAX_SEC = 0.05;
12424
+ function planRedisStepDtSec(simAtMs, nowMs) {
12425
+ if (simAtMs === 0) return 1 / 60;
12426
+ const elapsed = nowMs - simAtMs;
12427
+ if (elapsed < SIM_STEP_MIN_MS) return null;
12428
+ return Math.min(SIM_STEP_MAX_SEC, elapsed / 1e3);
12429
+ }
12329
12430
 
12330
12431
  // templates/game-sync/redis.ts
12331
12432
  var LUA_ALLOCATE_OBJECT = `
@@ -12336,6 +12437,10 @@ local max_slots = tonumber(ARGV[3])
12336
12437
  local tail = ARGV[4]
12337
12438
  local headers = ARGV[5]
12338
12439
 
12440
+ if redis.call('GET', KEYS[2]) ~= ARGV[6] then
12441
+ return -3
12442
+ end
12443
+
12339
12444
  local world = redis.call('GET', key)
12340
12445
  if not world then
12341
12446
  world = string.rep(string.char(0), size)
@@ -12381,6 +12486,10 @@ local max_slots = tonumber(ARGV[3])
12381
12486
  local object_id = tonumber(ARGV[4])
12382
12487
  local headers = ARGV[5]
12383
12488
 
12489
+ if redis.call('GET', KEYS[2]) ~= ARGV[6] then
12490
+ return -3
12491
+ end
12492
+
12384
12493
  if object_id < 1 or object_id > max_slots then
12385
12494
  return 0
12386
12495
  end
@@ -12407,8 +12516,31 @@ world = string.sub(world, 1, off - 1) .. zero_slot .. string.sub(world, off + sl
12407
12516
  redis.call('SET', key, world)
12408
12517
  return 1
12409
12518
  `;
12519
+ var LUA_RELEASE_LOCK = `
12520
+ if redis.call('GET', KEYS[1]) == ARGV[1] then
12521
+ return redis.call('DEL', KEYS[1])
12522
+ end
12523
+ return 0
12524
+ `;
12525
+ var LUA_READ_WORLD = `
12526
+ local world = redis.call('GET', KEYS[1])
12527
+ local sim_at = redis.call('GET', KEYS[2])
12528
+ local t = redis.call('TIME')
12529
+ local now = string.format('%.0f', t[1] * 1000 + math.floor(t[2] / 1000))
12530
+ return { world or '', sim_at or '', now }
12531
+ `;
12532
+ var LUA_COMMIT_WORLD = `
12533
+ if redis.call('GET', KEYS[1]) ~= ARGV[1] then
12534
+ return 0
12535
+ end
12536
+ redis.call('SET', KEYS[2], ARGV[2])
12537
+ redis.call('SET', KEYS[3], ARGV[3])
12538
+ return 1
12539
+ `;
12410
12540
  var REDIS_EVAL_KEYS = {
12411
12541
  worldKey: REDIS_WORLD_KEY,
12542
+ lockKey: REDIS_SIM_LOCK_KEY,
12543
+ simAtKey: REDIS_SIM_AT_KEY,
12412
12544
  worldByteLength: String(WORLD_BYTE_LENGTH),
12413
12545
  slotByteLength: String(OBJECT_SLOT_BYTE_LENGTH),
12414
12546
  maxSlots: String(MAX_LIVE_OBJECTS),
@@ -12416,6 +12548,10 @@ var REDIS_EVAL_KEYS = {
12416
12548
  };
12417
12549
 
12418
12550
  // templates/game-sync/sim.ts
12551
+ var SIM_HZ = 60;
12552
+ var BROADCAST_HZ = 30;
12553
+ var MIN_SPEED = 90;
12554
+ var MAX_SPEED = 180;
12419
12555
  var BOARD_WIDTH = 1280;
12420
12556
  var BOARD_HEIGHT = 720;
12421
12557
  var OBJECT_RADIUS = 25;
@@ -12520,12 +12656,12 @@ function simulateWorldStep(worldState2, dtSec, activeObjectIds2, count = activeO
12520
12656
  }
12521
12657
 
12522
12658
  // templates/game-sync/agent.ts
12523
- var BROADCAST_HZ = 60;
12524
- var BROADCAST_INTERVAL_MS = Math.floor(1e3 / BROADCAST_HZ);
12525
- var SIM_LOCK_TTL_MS = BROADCAST_INTERVAL_MS * 2;
12659
+ var SIM_INTERVAL_MS = Math.floor(1e3 / SIM_HZ);
12660
+ var BROADCAST_EVERY_N_TICKS = Math.round(SIM_HZ / BROADCAST_HZ);
12661
+ var SIM_LOCK_TTL_MS = SIM_INTERVAL_MS * 2;
12526
12662
  var SIM_LOCK_RETRY_MS = 5;
12527
- var MIN_SPEED = 90;
12528
- var MAX_SPEED = 180;
12663
+ var LUA_LOCK_LOST = -3;
12664
+ var LOCK_LOST = "lock_lost";
12529
12665
  var connectedSessions = /* @__PURE__ */ new Set();
12530
12666
  var connectedSessionList = [];
12531
12667
  var objectOwners = /* @__PURE__ */ new Map();
@@ -12541,6 +12677,11 @@ var redis = null;
12541
12677
  var broadcastTimer = null;
12542
12678
  var worldMutationChain = Promise.resolve();
12543
12679
  var lastTickTimeMs = 0;
12680
+ var tickCount = 0;
12681
+ var frameScratch = Buffer.alloc(MAX_FRAME_BYTES);
12682
+ var lastReadSimAt = 0;
12683
+ var lastReadNowMs = 0;
12684
+ var lastRelayedSimAt = 0;
12544
12685
  function withWorldMutation(fn) {
12545
12686
  const run = worldMutationChain.then(fn);
12546
12687
  worldMutationChain = run.then(
@@ -12554,24 +12695,29 @@ function sleep(ms) {
12554
12695
  setTimeout(resolve, ms);
12555
12696
  });
12556
12697
  }
12698
+ async function releaseSimLock(token) {
12699
+ if (!redis) return;
12700
+ await redis.eval(LUA_RELEASE_LOCK, 1, REDIS_SIM_LOCK_KEY, token);
12701
+ }
12557
12702
  async function withRedisSimLock(fn, options) {
12558
12703
  if (!redis) {
12559
- return fn();
12704
+ return fn("");
12560
12705
  }
12561
12706
  const retryUntilAcquired = options?.retryUntilAcquired ?? true;
12707
+ const token = randomUUID2();
12562
12708
  while (true) {
12563
12709
  const lockAcquired = await redis.set(
12564
12710
  REDIS_SIM_LOCK_KEY,
12565
- "1",
12711
+ token,
12566
12712
  "PX",
12567
12713
  SIM_LOCK_TTL_MS,
12568
12714
  "NX"
12569
12715
  );
12570
12716
  if (lockAcquired === "OK") {
12571
12717
  try {
12572
- return await fn();
12718
+ return await fn(token);
12573
12719
  } finally {
12574
- await redis.del(REDIS_SIM_LOCK_KEY);
12720
+ await releaseSimLock(token);
12575
12721
  }
12576
12722
  }
12577
12723
  if (!retryUntilAcquired) {
@@ -12664,21 +12810,27 @@ function registerObjectInMemory(sessionId) {
12664
12810
  attachObjectToSession(sessionId, objectId);
12665
12811
  return objectId;
12666
12812
  }
12667
- async function registerObjectInRedis(sessionId) {
12813
+ async function registerObjectInRedis(sessionId, token) {
12668
12814
  if (!redis) {
12669
12815
  return registerObjectInMemory(sessionId);
12670
12816
  }
12671
12817
  const result = await redis.eval(
12672
12818
  LUA_ALLOCATE_OBJECT,
12673
- 1,
12819
+ 2,
12674
12820
  REDIS_EVAL_KEYS.worldKey,
12821
+ REDIS_EVAL_KEYS.lockKey,
12675
12822
  REDIS_EVAL_KEYS.worldByteLength,
12676
12823
  REDIS_EVAL_KEYS.slotByteLength,
12677
12824
  REDIS_EVAL_KEYS.maxSlots,
12678
12825
  randomInitialTail(),
12679
- REDIS_EVAL_KEYS.headers
12826
+ REDIS_EVAL_KEYS.headers,
12827
+ token
12680
12828
  );
12681
12829
  const objectId = Number(result);
12830
+ if (objectId === LUA_LOCK_LOST) {
12831
+ agentLog("warn", "register skipped: sim lock lost before the world write");
12832
+ return LOCK_LOST;
12833
+ }
12682
12834
  if (!Number.isFinite(objectId) || objectId < 1) {
12683
12835
  return null;
12684
12836
  }
@@ -12686,27 +12838,41 @@ async function registerObjectInRedis(sessionId) {
12686
12838
  await loadWorldFromRedis();
12687
12839
  return objectId;
12688
12840
  }
12689
- async function releaseObjectInRedis(objectId) {
12690
- detachObjectFromSession(objectId);
12841
+ async function releaseObjectInRedis(objectId, token) {
12691
12842
  if (!redis) {
12843
+ detachObjectFromSession(objectId);
12692
12844
  releaseObjectInMemory(objectId);
12693
12845
  return true;
12694
12846
  }
12695
12847
  const released = await redis.eval(
12696
12848
  LUA_RELEASE_OBJECT,
12697
- 1,
12849
+ 2,
12698
12850
  REDIS_EVAL_KEYS.worldKey,
12851
+ REDIS_EVAL_KEYS.lockKey,
12699
12852
  REDIS_EVAL_KEYS.worldByteLength,
12700
12853
  REDIS_EVAL_KEYS.slotByteLength,
12701
12854
  REDIS_EVAL_KEYS.maxSlots,
12702
12855
  String(objectId),
12703
- REDIS_EVAL_KEYS.headers
12856
+ REDIS_EVAL_KEYS.headers,
12857
+ token
12704
12858
  );
12859
+ if (Number(released) === LUA_LOCK_LOST) {
12860
+ agentLog("warn", "release skipped: sim lock lost before the world write");
12861
+ return LOCK_LOST;
12862
+ }
12863
+ detachObjectFromSession(objectId);
12705
12864
  if (Number(released) === 1) {
12706
12865
  await loadWorldFromRedis();
12707
12866
  }
12708
12867
  return Number(released) === 1;
12709
12868
  }
12869
+ async function withSimLockRetryOnce(fn) {
12870
+ for (let attempt = 0; attempt < 2; attempt += 1) {
12871
+ const result = await withRedisSimLock(fn);
12872
+ if (result !== LOCK_LOST) return result;
12873
+ }
12874
+ return LOCK_LOST;
12875
+ }
12710
12876
  async function unregisterObject(sessionId, objectId) {
12711
12877
  const owned = sessionObjects.get(sessionId);
12712
12878
  const target = resolveRemoveTarget(objectId, owned);
@@ -12714,19 +12880,21 @@ async function unregisterObject(sessionId, objectId) {
12714
12880
  return target;
12715
12881
  }
12716
12882
  const previousOwner = objectOwners.get(target.objectId) ?? sessionId;
12717
- notifyObjectReleased(target.objectId, previousOwner);
12718
12883
  const released = await withWorldMutation(async () => {
12719
12884
  if (!redis) {
12720
- return releaseObjectInRedis(target.objectId);
12885
+ return releaseObjectInRedis(target.objectId, "");
12721
12886
  }
12722
- const result = await withRedisSimLock(
12723
- () => releaseObjectInRedis(target.objectId)
12887
+ return withSimLockRetryOnce(
12888
+ (token) => releaseObjectInRedis(target.objectId, token)
12724
12889
  );
12725
- return result === true;
12726
12890
  });
12891
+ if (released === LOCK_LOST) {
12892
+ return { ok: false, reason: UNREGISTER_NACK_REASON_BUSY };
12893
+ }
12727
12894
  if (!released) {
12728
12895
  return { ok: false, reason: UNREGISTER_NACK_REASON_NOT_FOUND };
12729
12896
  }
12897
+ notifyObjectReleased(target.objectId, previousOwner);
12730
12898
  return { ok: true, objectId: target.objectId };
12731
12899
  }
12732
12900
  function broadcastWorldSnapshot() {
@@ -12757,16 +12925,25 @@ function notifyObjectReleased(objectId, ownerSessionId) {
12757
12925
  }
12758
12926
  function broadcastWorldBuffer() {
12759
12927
  if (connectedSessionList.length === 0) return;
12760
- broadCastBinaryToClients(worldStateBytes, connectedSessionList, "sync");
12928
+ const length = encodeLiveObjectsInto(frameScratch, worldState);
12929
+ broadCastBinaryToClients(
12930
+ frameScratch.subarray(0, length),
12931
+ connectedSessionList,
12932
+ "sync"
12933
+ );
12761
12934
  }
12762
12935
  async function loadWorldFromRedis() {
12763
12936
  if (!redis) return;
12764
- const raw = await redis.getBuffer(REDIS_WORLD_KEY);
12765
- normalizeWorldBuffer(raw, worldState);
12766
- }
12767
- async function saveWorldToRedis() {
12768
- if (!redis) return;
12769
- await redis.set(REDIS_WORLD_KEY, worldStateBytes);
12937
+ const reply = await redis.callBuffer(
12938
+ "EVAL",
12939
+ LUA_READ_WORLD,
12940
+ 2,
12941
+ REDIS_WORLD_KEY,
12942
+ REDIS_SIM_AT_KEY
12943
+ );
12944
+ normalizeWorldBuffer(reply[0], worldState);
12945
+ lastReadSimAt = reply[1].byteLength > 0 ? Number(reply[1].toString()) : 0;
12946
+ lastReadNowMs = Number(reply[2].toString());
12770
12947
  }
12771
12948
  var activeObjectIds = new Int32Array(MAX_LIVE_OBJECTS);
12772
12949
  var SIM_LOCK_TRY_ONCE = { retryUntilAcquired: false };
@@ -12775,42 +12952,59 @@ function takeTickDtSec() {
12775
12952
  const now = Date.now();
12776
12953
  const dt = clampSimulationDtSec(
12777
12954
  lastTickTimeMs === 0 ? 0 : now - lastTickTimeMs,
12778
- BROADCAST_HZ
12955
+ SIM_HZ
12779
12956
  );
12780
12957
  lastTickTimeMs = now;
12781
12958
  return dt;
12782
12959
  }
12783
- function stepWorldInPlace() {
12784
- const dt = takeTickDtSec();
12960
+ function stepWorldInPlace(dtSec) {
12785
12961
  const count = collectActiveObjectIdsInto(worldState, activeObjectIds);
12786
- simulateWorldStep(worldState, dt, activeObjectIds, count);
12962
+ simulateWorldStep(worldState, dtSec, activeObjectIds, count);
12787
12963
  }
12788
12964
  async function stepWorldInMemory() {
12789
- stepWorldInPlace();
12965
+ stepWorldInPlace(takeTickDtSec());
12790
12966
  }
12791
- async function stepWorldWithRedis() {
12967
+ async function stepWorldWithRedis(token) {
12968
+ if (!redis) return "lost";
12792
12969
  await loadWorldFromRedis();
12793
- stepWorldInPlace();
12794
- await saveWorldToRedis();
12795
- broadcastWorldBuffer();
12796
- return true;
12970
+ const now = lastReadNowMs;
12971
+ const dt = planRedisStepDtSec(lastReadSimAt, now);
12972
+ if (dt === null) return "skipped";
12973
+ stepWorldInPlace(dt);
12974
+ const written = await redis.eval(
12975
+ LUA_COMMIT_WORLD,
12976
+ 3,
12977
+ REDIS_SIM_LOCK_KEY,
12978
+ REDIS_WORLD_KEY,
12979
+ REDIS_SIM_AT_KEY,
12980
+ token,
12981
+ worldStateBytes,
12982
+ String(now)
12983
+ );
12984
+ if (Number(written) !== 1) return "lost";
12985
+ lastReadSimAt = now;
12986
+ return "stepped";
12797
12987
  }
12798
12988
  async function runRedisTick() {
12799
- const lockResult = await withRedisSimLock(
12800
- stepWorldWithRedis,
12801
- SIM_LOCK_TRY_ONCE
12802
- );
12803
- if (lockResult !== null) return;
12804
- takeTickDtSec();
12805
- if (planRedisSimTick(SIM_TICK_PLAN_INPUT) === "relay") {
12989
+ tickCount += 1;
12990
+ const broadcastDue = tickCount % BROADCAST_EVERY_N_TICKS === 0;
12991
+ const outcome = await withRedisSimLock(stepWorldWithRedis, SIM_LOCK_TRY_ONCE);
12992
+ if (outcome === "lost") return;
12993
+ if (outcome === null) {
12994
+ if (!broadcastDue) return;
12995
+ if (planRedisSimTick(SIM_TICK_PLAN_INPUT) !== "relay") return;
12806
12996
  await loadWorldFromRedis();
12807
- broadcastWorldBuffer();
12808
12997
  }
12998
+ if (!broadcastDue || connectedSessionList.length === 0) return;
12999
+ if (lastReadSimAt <= lastRelayedSimAt) return;
13000
+ lastRelayedSimAt = lastReadSimAt;
13001
+ broadcastWorldBuffer();
12809
13002
  }
12810
13003
  async function runSimulationTick() {
12811
13004
  if (!redis) {
13005
+ tickCount += 1;
12812
13006
  await withWorldMutation(stepWorldInMemory);
12813
- broadcastWorldBuffer();
13007
+ if (tickCount % BROADCAST_EVERY_N_TICKS === 0) broadcastWorldBuffer();
12814
13008
  return;
12815
13009
  }
12816
13010
  await withWorldMutation(runRedisTick);
@@ -12832,8 +13026,11 @@ function onBroadcastTick() {
12832
13026
  function startBroadcastLoopIfNeeded() {
12833
13027
  if (broadcastTimer) return;
12834
13028
  if (!redis && connectedSessions.size < 1) return;
12835
- broadcastTimer = setInterval(onBroadcastTick, BROADCAST_INTERVAL_MS);
12836
- agentLog("info", `world loop started (${BROADCAST_HZ}Hz)`);
13029
+ broadcastTimer = setInterval(onBroadcastTick, SIM_INTERVAL_MS);
13030
+ agentLog(
13031
+ "info",
13032
+ `world loop started (sim ${SIM_HZ}Hz, broadcast ${BROADCAST_HZ}Hz)`
13033
+ );
12837
13034
  }
12838
13035
  function stopBroadcastLoopIfNeeded() {
12839
13036
  if (redis) return;
@@ -12908,11 +13105,18 @@ defineAgent({
12908
13105
  if (!redis) {
12909
13106
  return registerObjectInMemory(ctx.sessionId);
12910
13107
  }
12911
- const result = await withRedisSimLock(
12912
- () => registerObjectInRedis(ctx.sessionId)
13108
+ return withSimLockRetryOnce(
13109
+ (token) => registerObjectInRedis(ctx.sessionId, token)
12913
13110
  );
12914
- return result;
12915
13111
  });
13112
+ if (objectId === LOCK_LOST) {
13113
+ sendToClient(ctx.sessionId, {
13114
+ type: "register_nack",
13115
+ reason: REGISTER_NACK_REASON_BUSY
13116
+ });
13117
+ agentLog("info", `register_nack busy session=${ctx.sessionId}`);
13118
+ return;
13119
+ }
12916
13120
  if (objectId === null) {
12917
13121
  sendToClient(ctx.sessionId, {
12918
13122
  type: "register_nack",
@@ -32639,6 +32639,7 @@ function toolsHash(all) {
32639
32639
  var DEFAULT_BACKOFF_MS = [1e3, 2e3, 4e3, 8e3, 16e3, 3e4];
32640
32640
  var MAX_LIST_PAGES = 10;
32641
32641
  var REQUEST_TIMEOUT_CODE = -32001;
32642
+ var CONNECTION_LOST = Symbol("connection-lost");
32642
32643
  function readPackageVersion() {
32643
32644
  try {
32644
32645
  const require2 = createRequire(import.meta.url);
@@ -32653,12 +32654,23 @@ function errorFields(err) {
32653
32654
  if (err instanceof Error) {
32654
32655
  const code = err.code;
32655
32656
  const name = err.constructor.name || err.name;
32656
- return {
32657
+ const out = {
32657
32658
  error: code !== void 0 ? `${name} ${String(code)}` : name
32658
32659
  };
32660
+ const cause = err.cause;
32661
+ if (cause instanceof Error) {
32662
+ out.cause = cause.constructor.name || cause.name;
32663
+ const causeCode = cause.code;
32664
+ if (causeCode !== void 0)
32665
+ out.causeCode = String(causeCode);
32666
+ }
32667
+ return out;
32659
32668
  }
32660
32669
  return { error: typeof err };
32661
32670
  }
32671
+ function retryableAfterReconnect(tool) {
32672
+ return tool?.annotations?.readOnlyHint === true || tool?.annotations?.idempotentHint === true;
32673
+ }
32662
32674
  function urlOrigin(url2) {
32663
32675
  try {
32664
32676
  return new URL(url2).origin;
@@ -32760,10 +32772,31 @@ var McpToolSource = class {
32760
32772
  return this.cached.map((t) => ({ ...t }));
32761
32773
  }
32762
32774
  async callTool(name, args, opts) {
32775
+ const deadline = Date.now() + opts.timeoutMs;
32776
+ const tool = this.cached.find((t) => t.name === name);
32777
+ const first = await this.callOnce(name, args, opts.signal, opts.timeoutMs);
32778
+ if (first !== CONNECTION_LOST)
32779
+ return first;
32780
+ const unavailable = {
32781
+ isError: true,
32782
+ content: `tool ${name} failed: unavailable`
32783
+ };
32784
+ if (!retryableAfterReconnect(tool) || opts.signal?.aborted)
32785
+ return unavailable;
32786
+ const reconnected = await this.ready(deadline - Date.now());
32787
+ const remaining = deadline - Date.now();
32788
+ if (!reconnected || remaining <= 0 || opts.signal?.aborted)
32789
+ return unavailable;
32790
+ const second = await this.callOnce(name, args, opts.signal, remaining);
32791
+ return second === CONNECTION_LOST ? unavailable : second;
32792
+ }
32793
+ /** One call on the current connection; CONNECTION_LOST when the transport failed. */
32794
+ async callOnce(name, args, signal, timeoutMs) {
32763
32795
  const client = this.client;
32764
32796
  if (this.state !== "ready" || !client || !this.cached.some((t) => t.name === name)) {
32765
32797
  return { isError: true, content: `tool ${name} is not available` };
32766
32798
  }
32799
+ const opts = { signal, timeoutMs };
32767
32800
  try {
32768
32801
  const result = await client.callTool({ name, arguments: args ?? {} }, void 0, { signal: opts.signal, timeout: opts.timeoutMs });
32769
32802
  return mapToolResult(result);
@@ -32779,7 +32812,7 @@ var McpToolSource = class {
32779
32812
  return { isError: true, content: `tool ${name} failed: unavailable` };
32780
32813
  }
32781
32814
  this.connectionLost(client, err);
32782
- return { isError: true, content: `tool ${name} failed: unavailable` };
32815
+ return CONNECTION_LOST;
32783
32816
  }
32784
32817
  }
32785
32818
  async close() {
@@ -32885,7 +32918,13 @@ var McpToolSource = class {
32885
32918
  out.push({
32886
32919
  name: t.name,
32887
32920
  description: t.description ?? "",
32888
- inputSchema: t.inputSchema
32921
+ inputSchema: t.inputSchema,
32922
+ ...t.annotations ? {
32923
+ annotations: {
32924
+ readOnlyHint: t.annotations.readOnlyHint,
32925
+ idempotentHint: t.annotations.idempotentHint
32926
+ }
32927
+ } : {}
32889
32928
  });
32890
32929
  }
32891
32930
  cursor = res.nextCursor;
@@ -32639,6 +32639,7 @@ function toolsHash(all) {
32639
32639
  var DEFAULT_BACKOFF_MS = [1e3, 2e3, 4e3, 8e3, 16e3, 3e4];
32640
32640
  var MAX_LIST_PAGES = 10;
32641
32641
  var REQUEST_TIMEOUT_CODE = -32001;
32642
+ var CONNECTION_LOST = Symbol("connection-lost");
32642
32643
  function readPackageVersion() {
32643
32644
  try {
32644
32645
  const require2 = createRequire(import.meta.url);
@@ -32653,12 +32654,23 @@ function errorFields(err) {
32653
32654
  if (err instanceof Error) {
32654
32655
  const code = err.code;
32655
32656
  const name = err.constructor.name || err.name;
32656
- return {
32657
+ const out = {
32657
32658
  error: code !== void 0 ? `${name} ${String(code)}` : name
32658
32659
  };
32660
+ const cause = err.cause;
32661
+ if (cause instanceof Error) {
32662
+ out.cause = cause.constructor.name || cause.name;
32663
+ const causeCode = cause.code;
32664
+ if (causeCode !== void 0)
32665
+ out.causeCode = String(causeCode);
32666
+ }
32667
+ return out;
32659
32668
  }
32660
32669
  return { error: typeof err };
32661
32670
  }
32671
+ function retryableAfterReconnect(tool) {
32672
+ return tool?.annotations?.readOnlyHint === true || tool?.annotations?.idempotentHint === true;
32673
+ }
32662
32674
  function urlOrigin(url2) {
32663
32675
  try {
32664
32676
  return new URL(url2).origin;
@@ -32760,10 +32772,31 @@ var McpToolSource = class {
32760
32772
  return this.cached.map((t) => ({ ...t }));
32761
32773
  }
32762
32774
  async callTool(name, args, opts) {
32775
+ const deadline = Date.now() + opts.timeoutMs;
32776
+ const tool = this.cached.find((t) => t.name === name);
32777
+ const first = await this.callOnce(name, args, opts.signal, opts.timeoutMs);
32778
+ if (first !== CONNECTION_LOST)
32779
+ return first;
32780
+ const unavailable = {
32781
+ isError: true,
32782
+ content: `tool ${name} failed: unavailable`
32783
+ };
32784
+ if (!retryableAfterReconnect(tool) || opts.signal?.aborted)
32785
+ return unavailable;
32786
+ const reconnected = await this.ready(deadline - Date.now());
32787
+ const remaining = deadline - Date.now();
32788
+ if (!reconnected || remaining <= 0 || opts.signal?.aborted)
32789
+ return unavailable;
32790
+ const second = await this.callOnce(name, args, opts.signal, remaining);
32791
+ return second === CONNECTION_LOST ? unavailable : second;
32792
+ }
32793
+ /** One call on the current connection; CONNECTION_LOST when the transport failed. */
32794
+ async callOnce(name, args, signal, timeoutMs) {
32763
32795
  const client = this.client;
32764
32796
  if (this.state !== "ready" || !client || !this.cached.some((t) => t.name === name)) {
32765
32797
  return { isError: true, content: `tool ${name} is not available` };
32766
32798
  }
32799
+ const opts = { signal, timeoutMs };
32767
32800
  try {
32768
32801
  const result = await client.callTool({ name, arguments: args ?? {} }, void 0, { signal: opts.signal, timeout: opts.timeoutMs });
32769
32802
  return mapToolResult(result);
@@ -32779,7 +32812,7 @@ var McpToolSource = class {
32779
32812
  return { isError: true, content: `tool ${name} failed: unavailable` };
32780
32813
  }
32781
32814
  this.connectionLost(client, err);
32782
- return { isError: true, content: `tool ${name} failed: unavailable` };
32815
+ return CONNECTION_LOST;
32783
32816
  }
32784
32817
  }
32785
32818
  async close() {
@@ -32885,7 +32918,13 @@ var McpToolSource = class {
32885
32918
  out.push({
32886
32919
  name: t.name,
32887
32920
  description: t.description ?? "",
32888
- inputSchema: t.inputSchema
32921
+ inputSchema: t.inputSchema,
32922
+ ...t.annotations ? {
32923
+ annotations: {
32924
+ readOnlyHint: t.annotations.readOnlyHint,
32925
+ idempotentHint: t.annotations.idempotentHint
32926
+ }
32927
+ } : {}
32889
32928
  });
32890
32929
  }
32891
32930
  cursor = res.nextCursor;