@genex-ai/cli-demo 0.3.0 → 0.5.0

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 CHANGED
@@ -21,9 +21,13 @@ genex texture "<prompt>" # generate a texture → assets/textures/
21
21
 
22
22
  `genex init` does four things:
23
23
 
24
- 1. **Scaffolds your workspace** — copies the bundled templates (skills, agents,
25
- commands) into `~/.claude`, *merging* into whatever is already there. Existing
26
- files are **never overwritten**.
24
+ 1. **Installs the skills for your coding agents** — copies the bundled templates
25
+ into every agent it detects: Claude Code (`~/.claude`, full set incl.
26
+ agents/ + commands/), Codex (`~/.codex/skills`), and Cursor
27
+ (`~/.cursor/skills`). genex-owned skills (`genex-*`) are **always refreshed**
28
+ to the package version so a stale copy can't linger; your own files are never
29
+ overwritten. Pick agents explicitly with `--agents claude,codex,cursor`, or a
30
+ single custom dir with `--dir`.
27
31
  2. **Authorizes you** — opens the Genex auth site (web) in your browser. If the
28
32
  browser can't open, it prints the URL to open manually.
29
33
  3. **Saves your token** — writes `GENEX_TOKEN` to `~/.genex/env` (per-user;
@@ -107,7 +111,8 @@ npx @genex-ai/cli-demo@latest init
107
111
  genex init [options]
108
112
 
109
113
  Options
110
- --dir <path> Destination workspace (default: ~/.claude)
114
+ --agents <list> Agents to install for: claude,codex,cursor (default: auto-detect)
115
+ --dir <path> Single destination workspace (overrides --agents)
111
116
  --env <path> Token env file (default: ~/.genex/env)
112
117
  --auth-url <url> Override the auth site (default: https://demo-web.glotech.world)
113
118
  --no-auth Only scaffold templates; skip authorization
package/dist/index.js CHANGED
@@ -9,6 +9,7 @@ import { fileURLToPath as fileURLToPath2 } from "url";
9
9
  import path6 from "path";
10
10
 
11
11
  // src/config.ts
12
+ import fs from "fs";
12
13
  import os from "os";
13
14
  import path from "path";
14
15
  import { fileURLToPath } from "url";
@@ -42,45 +43,77 @@ function getTemplatesDir() {
42
43
  const here = path.dirname(fileURLToPath(import.meta.url));
43
44
  return path.resolve(here, "..", "templates");
44
45
  }
45
- function getClaudeDir(override) {
46
- if (override) return path.resolve(override);
47
- return path.join(os.homedir(), ".claude");
46
+ var KNOWN_AGENTS = {
47
+ claude: { label: "Claude Code", dirName: ".claude", full: true },
48
+ codex: { label: "Codex", dirName: ".codex", full: false },
49
+ cursor: { label: "Cursor", dirName: ".cursor", full: false }
50
+ };
51
+ var KNOWN_AGENT_IDS = Object.keys(KNOWN_AGENTS);
52
+ function resolveAgentTargets(opts = {}) {
53
+ if (opts.dir) {
54
+ return [{ id: "custom", label: "workspace", baseDir: path.resolve(opts.dir), full: true }];
55
+ }
56
+ const home = os.homedir();
57
+ let ids;
58
+ if (opts.agents && opts.agents.length > 0) {
59
+ ids = opts.agents.filter((id) => KNOWN_AGENTS[id]);
60
+ } else {
61
+ ids = KNOWN_AGENT_IDS.filter((id) => isDir(path.join(home, KNOWN_AGENTS[id].dirName)));
62
+ if (ids.length === 0) ids = ["claude"];
63
+ }
64
+ return ids.map((id) => {
65
+ const def = KNOWN_AGENTS[id];
66
+ return { id, label: def.label, baseDir: path.join(home, def.dirName), full: def.full };
67
+ });
68
+ }
69
+ function isDir(p) {
70
+ try {
71
+ return fs.statSync(p).isDirectory();
72
+ } catch {
73
+ return false;
74
+ }
48
75
  }
49
76
 
50
77
  // src/lib/copy-templates.ts
51
- import fs from "fs/promises";
78
+ import fs2 from "fs/promises";
52
79
  import path2 from "path";
80
+ function isGenexManaged(rel) {
81
+ return rel.split(path2.sep).some((seg) => seg.startsWith("genex"));
82
+ }
53
83
  async function copyTemplates(srcDir, destDir, opts = {}) {
54
- const result = { copied: [], skipped: [] };
84
+ const result = { copied: [], updated: [], skipped: [] };
55
85
  await walk(srcDir, srcDir, destDir, opts, result);
56
86
  return result;
57
87
  }
58
88
  async function walk(rootSrc, src, dest, opts, result) {
59
- const entries = await fs.readdir(src, { withFileTypes: true });
89
+ const entries = await fs2.readdir(src, { withFileTypes: true });
60
90
  for (const entry of entries) {
61
91
  const srcPath = path2.join(src, entry.name);
62
92
  const destPath = path2.join(dest, entry.name);
63
93
  const rel = path2.relative(rootSrc, srcPath);
64
94
  if (entry.isDirectory()) {
65
- await fs.mkdir(destPath, { recursive: true });
95
+ await fs2.mkdir(destPath, { recursive: true });
66
96
  await walk(rootSrc, srcPath, destPath, opts, result);
67
97
  continue;
68
98
  }
69
99
  if (!entry.isFile()) {
70
100
  continue;
71
101
  }
72
- if (!opts.force && await exists(destPath)) {
102
+ const present = await exists(destPath);
103
+ const mayOverwrite = opts.force || isGenexManaged(rel);
104
+ if (present && !mayOverwrite) {
73
105
  result.skipped.push(rel);
74
106
  continue;
75
107
  }
76
- await fs.mkdir(path2.dirname(destPath), { recursive: true });
77
- await fs.copyFile(srcPath, destPath);
108
+ await fs2.mkdir(path2.dirname(destPath), { recursive: true });
109
+ await fs2.copyFile(srcPath, destPath);
78
110
  result.copied.push(rel);
111
+ if (present) result.updated.push(rel);
79
112
  }
80
113
  }
81
114
  async function exists(p) {
82
115
  try {
83
- await fs.access(p);
116
+ await fs2.access(p);
84
117
  return true;
85
118
  } catch {
86
119
  return false;
@@ -416,7 +449,7 @@ function randomSuffix() {
416
449
  }
417
450
 
418
451
  // src/lib/ssh.ts
419
- import fs2 from "fs/promises";
452
+ import fs3 from "fs/promises";
420
453
  import path3 from "path";
421
454
  import { spawn as spawn2 } from "child_process";
422
455
  var KEY_NAME = "genex_key";
@@ -424,7 +457,7 @@ async function generateSshKeypair(dir, log) {
424
457
  const keyPath = path3.join(dir, KEY_NAME);
425
458
  const pubPath = `${keyPath}.pub`;
426
459
  try {
427
- const existing = (await fs2.readFile(pubPath, "utf8")).trim();
460
+ const existing = (await fs3.readFile(pubPath, "utf8")).trim();
428
461
  if (existing) {
429
462
  log.dim(`Reusing existing deploy key (${KEY_NAME}).`);
430
463
  return { publicKey: existing };
@@ -435,12 +468,12 @@ async function generateSshKeypair(dir, log) {
435
468
  const ok = await runSshKeygen(keyPath, log);
436
469
  if (!ok) return null;
437
470
  try {
438
- const pub = (await fs2.readFile(pubPath, "utf8")).trim();
471
+ const pub = (await fs3.readFile(pubPath, "utf8")).trim();
439
472
  if (!pub) {
440
473
  log.warn("ssh-keygen produced no public key.");
441
474
  return null;
442
475
  }
443
- await fs2.chmod(keyPath, 384).catch(() => {
476
+ await fs3.chmod(keyPath, 384).catch(() => {
444
477
  });
445
478
  return { publicKey: pub };
446
479
  } catch (err) {
@@ -473,7 +506,7 @@ async function writeGitignore(dir, log) {
473
506
  const file = path3.join(dir, ".gitignore");
474
507
  let content = "";
475
508
  try {
476
- content = await fs2.readFile(file, "utf8");
509
+ content = await fs3.readFile(file, "utf8");
477
510
  } catch {
478
511
  }
479
512
  const present = new Set(content.split("\n").map((l) => l.trim()));
@@ -483,23 +516,23 @@ async function writeGitignore(dir, log) {
483
516
  if (next.length > 0 && !next.endsWith("\n")) next += "\n";
484
517
  if (!content.trim()) next += "# genex (deploy key + local metadata \u2014 never publish)\n";
485
518
  next += toAdd.join("\n") + "\n";
486
- await fs2.writeFile(file, next);
519
+ await fs3.writeFile(file, next);
487
520
  log.dim(`Updated .gitignore (${toAdd.join(", ")}).`);
488
521
  }
489
522
 
490
523
  // src/lib/store.ts
491
- import fs4 from "fs/promises";
524
+ import fs5 from "fs/promises";
492
525
  import path5 from "path";
493
526
 
494
527
  // src/lib/env.ts
495
- import fs3 from "fs/promises";
528
+ import fs4 from "fs/promises";
496
529
  import path4 from "path";
497
530
  import { spawn as spawn3 } from "child_process";
498
531
  async function writeEnvVar(envPath, key, value) {
499
532
  let content = "";
500
533
  let existed = false;
501
534
  try {
502
- content = await fs3.readFile(envPath, "utf8");
535
+ content = await fs4.readFile(envPath, "utf8");
503
536
  existed = true;
504
537
  } catch {
505
538
  }
@@ -519,14 +552,14 @@ async function writeEnvVar(envPath, key, value) {
519
552
  next = prefix + assignment + "\n";
520
553
  mode = existed ? "appended" : "created";
521
554
  }
522
- await fs3.mkdir(path4.dirname(envPath), { recursive: true });
523
- await fs3.writeFile(envPath, next, { mode: 384 });
555
+ await fs4.mkdir(path4.dirname(envPath), { recursive: true });
556
+ await fs4.writeFile(envPath, next, { mode: 384 });
524
557
  await restrictFilePermissions(envPath);
525
558
  return { mode, path: envPath };
526
559
  }
527
560
  async function restrictFilePermissions(filePath) {
528
561
  if (process.platform !== "win32") {
529
- await fs3.chmod(filePath, 384).catch(() => {
562
+ await fs4.chmod(filePath, 384).catch(() => {
530
563
  });
531
564
  return;
532
565
  }
@@ -575,7 +608,7 @@ async function readUserToken(envPath) {
575
608
  async function readTokenFromFile(file) {
576
609
  let content;
577
610
  try {
578
- content = await fs4.readFile(file, "utf8");
611
+ content = await fs5.readFile(file, "utf8");
579
612
  } catch {
580
613
  return null;
581
614
  }
@@ -591,7 +624,7 @@ function stripQuotes(v) {
591
624
  }
592
625
  async function readProject(cwd = process.cwd()) {
593
626
  try {
594
- const raw = await fs4.readFile(getProjectMetadataPath(cwd), "utf8");
627
+ const raw = await fs5.readFile(getProjectMetadataPath(cwd), "utf8");
595
628
  return JSON.parse(raw);
596
629
  } catch {
597
630
  return null;
@@ -599,9 +632,9 @@ async function readProject(cwd = process.cwd()) {
599
632
  }
600
633
  async function writeProject(meta, cwd = process.cwd()) {
601
634
  const file = getProjectMetadataPath(cwd);
602
- await fs4.mkdir(path5.dirname(file), { recursive: true });
603
- await fs4.writeFile(file, JSON.stringify(meta, null, 2) + "\n", { mode: 384 });
604
- await fs4.chmod(file, 384).catch(() => {
635
+ await fs5.mkdir(path5.dirname(file), { recursive: true });
636
+ await fs5.writeFile(file, JSON.stringify(meta, null, 2) + "\n", { mode: 384 });
637
+ await fs5.chmod(file, 384).catch(() => {
605
638
  });
606
639
  return { path: file };
607
640
  }
@@ -631,24 +664,24 @@ async function runInit(opts) {
631
664
  log.plain(c.bold("genex init"));
632
665
  log.plain("");
633
666
  const templatesDir = getTemplatesDir();
634
- const claudeDir = getClaudeDir(opts.dir);
635
- log.step(`Setting up your workspace at ${c.cyan(claudeDir)}`);
636
- const { copied, skipped } = await copyTemplates(templatesDir, claudeDir, {
637
- force: opts.force
638
- });
639
- if (copied.length > 0) {
640
- log.success(`Added ${copied.length} file${copied.length === 1 ? "" : "s"}.`);
641
- for (const f of copied) log.dim(` + ${f}`);
642
- }
643
- if (skipped.length > 0) {
644
- log.info(
645
- `Left ${skipped.length} existing file${skipped.length === 1 ? "" : "s"} untouched.`
646
- );
647
- for (const f of skipped) log.dim(` = ${f}`);
648
- }
649
- if (copied.length === 0 && skipped.length === 0) {
650
- log.info("No template files to install.");
651
- }
667
+ const targets = resolveAgentTargets({ dir: opts.dir, agents: opts.agents });
668
+ log.step(
669
+ `Installing Genex skills for: ${targets.map((t) => c.cyan(t.label)).join(", ")}`
670
+ );
671
+ let totalNew = 0;
672
+ let totalUpdated = 0;
673
+ for (const t of targets) {
674
+ const src = t.full ? templatesDir : path6.join(templatesDir, "skills");
675
+ const dest = t.full ? t.baseDir : path6.join(t.baseDir, "skills");
676
+ const { copied, updated } = await copyTemplates(src, dest, { force: opts.force });
677
+ const added = copied.length - updated.length;
678
+ totalNew += added;
679
+ totalUpdated += updated.length;
680
+ log.dim(` ${t.label}: ${added} added, ${updated.length} refreshed \u2192 ${dest}`);
681
+ }
682
+ log.success(
683
+ `Skills ready (${totalNew} added, ${totalUpdated} refreshed across ${targets.length} agent${targets.length === 1 ? "" : "s"}).`
684
+ );
652
685
  log.plain("");
653
686
  if (opts.noAuth) {
654
687
  log.info("Skipping authorization (--no-auth).");
@@ -703,7 +736,7 @@ async function runInit(opts) {
703
736
 
704
737
  // src/lib/deploy.ts
705
738
  import { spawn as spawn4 } from "child_process";
706
- import fs5 from "fs/promises";
739
+ import fs6 from "fs/promises";
707
740
  import os2 from "os";
708
741
  import path7 from "path";
709
742
  function run(cmd, args, env) {
@@ -737,24 +770,24 @@ async function deployGame(sshUrl, opts, log) {
737
770
  log.success("Built.");
738
771
  }
739
772
  const distDir = path7.join(cwd, "dist");
740
- const siteDir = await isDir(distDir) ? distDir : cwd;
773
+ const siteDir = await isDir2(distDir) ? distDir : cwd;
741
774
  if (siteDir === cwd) {
742
775
  await writeGitignore(cwd, log);
743
776
  }
744
777
  const rel = path7.relative(cwd, siteDir) || ".";
745
778
  try {
746
- await fs5.access(path7.join(siteDir, "index.html"));
779
+ await fs6.access(path7.join(siteDir, "index.html"));
747
780
  } catch {
748
781
  log.warn(`No index.html in ${rel} \u2014 GitHub Pages needs one to serve the game.`);
749
782
  }
750
783
  await warnIfAbsolutePaths(siteDir, log);
751
- await fs5.writeFile(path7.join(siteDir, ".nojekyll"), "");
784
+ await fs6.writeFile(path7.join(siteDir, ".nojekyll"), "");
752
785
  const keyPath = path7.resolve(cwd, KEY_NAME);
753
786
  if (!await fileExists(keyPath)) {
754
787
  log.warn(`No deploy key (${KEY_NAME}) here \u2014 run \`genex init\` in this folder first.`);
755
788
  return false;
756
789
  }
757
- const gitDir = await fs5.mkdtemp(path7.join(os2.tmpdir(), "genex-deploy-"));
790
+ const gitDir = await fs6.mkdtemp(path7.join(os2.tmpdir(), "genex-deploy-"));
758
791
  const gitEnv = { GIT_DIR: gitDir, GIT_WORK_TREE: siteDir };
759
792
  try {
760
793
  if ((await run("git", ["init", "-q"], gitEnv)).code !== 0) {
@@ -790,28 +823,28 @@ async function deployGame(sshUrl, opts, log) {
790
823
  if (tail) log.dim(` ${tail}`);
791
824
  return false;
792
825
  } finally {
793
- await fs5.rm(gitDir, { recursive: true, force: true }).catch(() => {
826
+ await fs6.rm(gitDir, { recursive: true, force: true }).catch(() => {
794
827
  });
795
828
  }
796
829
  }
797
830
  async function hasBuildScript(cwd) {
798
831
  try {
799
- const pkg = JSON.parse(await fs5.readFile(path7.join(cwd, "package.json"), "utf8"));
832
+ const pkg = JSON.parse(await fs6.readFile(path7.join(cwd, "package.json"), "utf8"));
800
833
  return Boolean(pkg.scripts?.build);
801
834
  } catch {
802
835
  return false;
803
836
  }
804
837
  }
805
- async function isDir(p) {
838
+ async function isDir2(p) {
806
839
  try {
807
- return (await fs5.stat(p)).isDirectory();
840
+ return (await fs6.stat(p)).isDirectory();
808
841
  } catch {
809
842
  return false;
810
843
  }
811
844
  }
812
845
  async function fileExists(p) {
813
846
  try {
814
- await fs5.access(p);
847
+ await fs6.access(p);
815
848
  return true;
816
849
  } catch {
817
850
  return false;
@@ -820,7 +853,7 @@ async function fileExists(p) {
820
853
  async function warnIfAbsolutePaths(siteDir, log) {
821
854
  let html;
822
855
  try {
823
- html = await fs5.readFile(path7.join(siteDir, "index.html"), "utf8");
856
+ html = await fs6.readFile(path7.join(siteDir, "index.html"), "utf8");
824
857
  } catch {
825
858
  return;
826
859
  }
@@ -918,7 +951,7 @@ async function runPreview(opts) {
918
951
  import path9 from "path";
919
952
 
920
953
  // src/lib/assets.ts
921
- import fs6 from "fs/promises";
954
+ import fs7 from "fs/promises";
922
955
  import path8 from "path";
923
956
  function slugify(input) {
924
957
  const s = input.toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 50).replace(/-+$/g, "");
@@ -928,8 +961,8 @@ async function downloadToFile(url, dest, headers) {
928
961
  const res = await fetch(url, { headers });
929
962
  if (!res.ok) throw new Error(`download failed (HTTP ${res.status}) for ${url}`);
930
963
  const buf = Buffer.from(await res.arrayBuffer());
931
- await fs6.mkdir(path8.dirname(dest), { recursive: true });
932
- await fs6.writeFile(dest, buf);
964
+ await fs7.mkdir(path8.dirname(dest), { recursive: true });
965
+ await fs7.writeFile(dest, buf);
933
966
  return buf.byteLength;
934
967
  }
935
968
 
@@ -1099,7 +1132,8 @@ ${c.bold("Options for the generators (`model` `skybox` `sfx` `texture`)")}
1099
1132
  ${c.bold("Options for `init`")}
1100
1133
  <name> Project name (positional; default: current directory name).
1101
1134
  --name <name> Same as the positional name.
1102
- --dir <path> Destination workspace (default: ~/.claude).
1135
+ --agents <list> Agents to install skills for (claude,codex,cursor; default: auto-detect).
1136
+ --dir <path> Single destination workspace (overrides --agents).
1103
1137
  --env <path> Token env file (default: ~/.genex/env).
1104
1138
  --auth-url <url> Override the auth site (default: ${DEFAULT_AUTH_URL}).
1105
1139
  --api-url <url> Override the API base URL (default: ${DEFAULT_API_URL}).
@@ -1151,6 +1185,7 @@ function parseArgs(argv) {
1151
1185
  "--auth-url",
1152
1186
  "--api-url",
1153
1187
  "--colyseus-url",
1188
+ "--agents",
1154
1189
  "--name",
1155
1190
  "--title",
1156
1191
  "--description",
@@ -1233,6 +1268,9 @@ function applyValueFlag(options, flag, value) {
1233
1268
  case "--colyseus-url":
1234
1269
  options.colyseusUrl = value;
1235
1270
  break;
1271
+ case "--agents":
1272
+ options.agents = value.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
1273
+ break;
1236
1274
  case "--name":
1237
1275
  options.name = value;
1238
1276
  break;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@genex-ai/cli-demo",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "Set up your ~/.claude workspace, authorize, create a game project, generate AI assets, and publish (genex CLI).",
5
5
  "type": "module",
6
6
  "bin": {
@@ -11,11 +11,15 @@ architecture, and team-ready workflows.
11
11
 
12
12
  ## What got installed
13
13
 
14
- Everything under `~/.claude`:
15
-
16
- - **skills/** - reusable Genex skills for 3D browser-game work.
17
- - **agents/** - example subagent definitions.
18
- - **commands/** - example slash commands.
14
+ `genex init` installs the Genex skills into **every coding agent it detects** —
15
+ Claude Code (`~/.claude`), Codex (`~/.codex`), and Cursor (`~/.cursor`) — so the
16
+ same skills are available whichever agent you build with. Re-running `init`
17
+ always refreshes the genex-owned skills to the latest version (your own files
18
+ are never touched).
19
+
20
+ - **skills/** - reusable Genex skills for 3D browser-game work (all agents).
21
+ - **agents/** - example subagent definitions (Claude Code).
22
+ - **commands/** - example slash commands (Claude Code).
19
23
 
20
24
  Start with `$genex-threejs-skill-router` for broad game or graphics requests.
21
25
  It routes the agent to focused skills for cameras, procedural geometry,
@@ -0,0 +1,132 @@
1
+ ---
2
+ name: genex-threejs-multiplayer
3
+ description: Implement realtime multiplayer for Genex Three.js games with `@genex-ai/multiplayer`. Use whenever 2+ players share a world — movement sync, shared scores/rounds, shots/emotes, presence, and persistent worlds. MANDATORY whenever a game has multiplayer: load this before writing any networking code.
4
+ ---
5
+
6
+ # Genex Three.js Multiplayer
7
+
8
+ `@genex-ai/multiplayer` is a **relay**: whatever you write to `me` or `shared` is
9
+ synced to everyone; everything else stays local. The server runs **no physics, no
10
+ prediction, and no interpolation** — you run your own game logic and add your own
11
+ smoothing. This skill covers the API, the smoothing you must add yourself
12
+ (interpolation + prediction), config wiring, and persistent worlds.
13
+
14
+ **This skill is mandatory for any multiplayer game.** Load it before you write a
15
+ single line of networking code. Naïvely snapping every remote player to their last
16
+ raw network position looks terrible — interpolation/prediction are not optional polish.
17
+
18
+ Read [references/realtime-patterns.md](references/realtime-patterns.md) for the
19
+ copy-paste `RemoteInterpolator` + local-prediction helpers and the persistence/config code.
20
+
21
+ ## Install
22
+
23
+ ```bash
24
+ npm i @genex-ai/multiplayer
25
+ ```
26
+
27
+ ## Connect
28
+
29
+ Pick your own per-player state shape (any JSON). `room` is the **project slug**
30
+ (printed by `genex init`) — same id = same room, different ids are fully isolated.
31
+
32
+ ```ts
33
+ import { connect } from "@genex-ai/multiplayer";
34
+
35
+ type State = { x: number; z: number; yaw: number }; // YOUR per-player state
36
+
37
+ const room = await connect<State>({
38
+ url: GENEX.colyseusUrl, // e.g. "wss://demo-colyseus.glotech.world" — see config wiring below
39
+ room: GENEX.slug, // the project slug — everyone with this id shares a room
40
+ name: "ada", // optional display name
41
+ });
42
+ ```
43
+
44
+ ## API surface (exact — do not invent methods)
45
+
46
+ - `room.id` — your own session id.
47
+ - `room.me.set(state)` — publish your state. **Replaces it wholesale** (send the full
48
+ object, not a partial). Call on a **fixed 10–20 Hz tick**, never per render frame —
49
+ one `set` = one network message.
50
+ - `room.players` — a **fresh `Map` each read**, and it **includes you**. Skip yourself
51
+ with `if (id === room.id) continue;`. Each value is `{ id, name, state }`.
52
+ - `room.shared.get(key)` / `room.shared.set(key, value)` / `room.shared.keys()` —
53
+ a key/value store (any JSON) synced to everyone. Use for world state, scores, round.
54
+ - `room.on(event, cb)` → returns an **unsubscribe** function. Events: `'join'` /
55
+ `'change'` `(id, state)` (both also fire for **you** on connect — filter `id === room.id`),
56
+ `'leave'` `(id)`, `'shared'` `(key, value)`, and any custom event name from `send`.
57
+ - `room.send(type, payload)` — fire-and-forget to all **other** clients, not stored in
58
+ state. Use for shots, emotes, chat, pings.
59
+ - `room.leave()` — leave the room.
60
+
61
+ ## The loop you must build (input → local → tick → render)
62
+
63
+ 1. **Input mutates a local object only** (`me.x += …`). Never network on keypress.
64
+ 2. **A fixed tick publishes it:** `setInterval(() => room.me.set(me), 66)` (~15 Hz).
65
+ 3. **Render at your own framerate**, drawing:
66
+ - **yourself** from your *local predicted* state (zero latency — never from the
67
+ echoed server copy of you), and
68
+ - **every other player** through an **interpolator** (render ~100 ms in the past and
69
+ lerp between their last two snapshots) — never snap to raw network state.
70
+ 4. **Create-or-reuse one mesh per id**; remove a player's mesh on `'leave'`.
71
+
72
+ See [references/realtime-patterns.md](references/realtime-patterns.md) for the ready-made
73
+ `RemoteInterpolator` helper and a complete movement example.
74
+
75
+ ## Config wiring (required — the browser can't read `.genex/project.json`)
76
+
77
+ The game runs in the browser; `.genex/project.json` (which holds `slug`, `colyseusUrl`,
78
+ `apiUrl`) is gitignored and not bundled. Surface those values to the client explicitly —
79
+ e.g. a tiny committed `src/genex.config.ts`:
80
+
81
+ ```ts
82
+ // src/genex.config.ts — values from `.genex/project.json` (printed by `genex init`)
83
+ export const GENEX = {
84
+ slug: "my-game-slug",
85
+ colyseusUrl: "wss://demo-colyseus.glotech.world",
86
+ apiUrl: "https://demo-api.glotech.world",
87
+ } as const;
88
+ ```
89
+
90
+ Read `.genex/project.json` once and fill these in. (A Vite `define` / `.env` with
91
+ `VITE_` vars works too — the point is the values must end up in the built JS.)
92
+
93
+ ## Persistent worlds (optional — survives restarts)
94
+
95
+ The relay is in-memory: room state is gone when everyone leaves or the server restarts.
96
+ For a world that persists, save/load one JSON blob keyed by the project slug:
97
+
98
+ ```ts
99
+ // load on boot
100
+ const { data } = await fetch(`${GENEX.apiUrl}/api/projects/${GENEX.slug}/state`).then(r => r.json());
101
+ initWorld(data ?? defaultWorld());
102
+
103
+ // save from ONE authority (e.g. the host client) to avoid races; max 1 MB, last-write-wins
104
+ fetch(`${GENEX.apiUrl}/api/projects/${GENEX.slug}/state`, {
105
+ method: "PUT",
106
+ headers: { "Content-Type": "application/json" },
107
+ body: JSON.stringify(world),
108
+ });
109
+ ```
110
+
111
+ `GET` returns `{ data }` (or `{ data: null }` if never saved). It's public (no auth) and
112
+ size-capped at 1 MB. Don't save every frame — debounce, and elect a single writer.
113
+
114
+ ## Checklist
115
+
116
+ - [ ] `npm i @genex-ai/multiplayer`, and config values wired into the client build.
117
+ - [ ] `room` is the **project slug**.
118
+ - [ ] `me.set` on a fixed **10–20 Hz** tick (not per frame); full object each time.
119
+ - [ ] Skip yourself in `room.players` (`id === room.id`).
120
+ - [ ] Remote players go through interpolation; **you** render from local predicted state.
121
+ - [ ] Create-or-reuse a mesh per id; remove it on `'leave'`.
122
+ - [ ] If the world should persist, save from one authority via the state API.
123
+
124
+ ## Troubleshooting
125
+
126
+ - **Other players stutter / teleport** — you're snapping to raw network state. Use the
127
+ `RemoteInterpolator` (render-delay + lerp).
128
+ - **My own movement feels laggy** — you're rendering yourself from the echoed server
129
+ state. Render yourself from your local predicted object instead.
130
+ - **Too much traffic / desync** — you're calling `me.set` per frame. Move it to the tick.
131
+ - **Players never appear** — `room.players` is empty until the first state patch lands;
132
+ read it in the render loop, and remember it includes you (filter your own id).
@@ -0,0 +1,202 @@
1
+ # Realtime patterns: interpolation, prediction, persistence
2
+
3
+ The `@genex-ai/multiplayer` relay gives you the **latest** state of each player and
4
+ nothing else — no timestamps, no smoothing. These are the pieces you add on top so the
5
+ game feels good. All code is plain TypeScript; nothing here is provided by the package.
6
+
7
+ ## Why you need this
8
+
9
+ - You publish `me.set` at ~15 Hz but render at 60 fps. If you snap each remote player to
10
+ their last received position, they move in visible 15 Hz steps and jump on packet
11
+ jitter. **Fix: interpolation** — render each remote player slightly in the past and
12
+ lerp between their two surrounding snapshots.
13
+ - Your *own* avatar would feel laggy if you waited for the server to echo your position
14
+ back. **Fix: prediction** — apply input locally and render yourself from that
15
+ immediately; the tick still publishes it for everyone else.
16
+
17
+ ## RemoteInterpolator (render-delay interpolation)
18
+
19
+ Buffers timestamped snapshots per remote player and samples a smoothed value ~100 ms in
20
+ the past. Stamp snapshots with the local clock on arrival (we don't get server time).
21
+
22
+ ```ts
23
+ // interpolation.ts
24
+ const RENDER_DELAY_MS = 100; // render remotes this far in the past; raise if jittery
25
+ const BUFFER_MS = 1000; // keep ~1s of history
26
+
27
+ type Vec = { x: number; y: number; z: number; yaw: number };
28
+ type Snap = { t: number; v: Vec };
29
+
30
+ function lerp(a: number, b: number, k: number) {
31
+ return a + (b - a) * k;
32
+ }
33
+ // shortest-arc angle lerp (radians) — avoids spinning the wrong way across ±π
34
+ function lerpAngle(a: number, b: number, k: number) {
35
+ let d = (b - a) % (Math.PI * 2);
36
+ if (d > Math.PI) d -= Math.PI * 2;
37
+ if (d < -Math.PI) d += Math.PI * 2;
38
+ return a + d * k;
39
+ }
40
+
41
+ export class RemoteInterpolator {
42
+ private buffers = new Map<string, Snap[]>();
43
+
44
+ /** Call whenever you read a remote player's latest state (e.g. each frame, or on 'change'). */
45
+ push(id: string, v: Vec, now = performance.now()) {
46
+ let buf = this.buffers.get(id);
47
+ if (!buf) this.buffers.set(id, (buf = []));
48
+ const last = buf[buf.length - 1];
49
+ // de-dupe identical repeats (players is re-read every frame)
50
+ if (last && last.v.x === v.x && last.v.z === v.z && last.v.yaw === v.yaw && last.v.y === v.y) return;
51
+ buf.push({ t: now, v });
52
+ const cutoff = now - BUFFER_MS;
53
+ while (buf.length > 2 && buf[0].t < cutoff) buf.shift();
54
+ }
55
+
56
+ /** Smoothed value to render this frame, or null if we have nothing yet. */
57
+ sample(id: string, now = performance.now()): Vec | null {
58
+ const buf = this.buffers.get(id);
59
+ if (!buf || buf.length === 0) return null;
60
+ const target = now - RENDER_DELAY_MS;
61
+ if (buf.length === 1 || target <= buf[0].t) return buf[0].v;
62
+ if (target >= buf[buf.length - 1].t) return buf[buf.length - 1].v; // clamp (no extrapolation)
63
+ for (let i = 0; i < buf.length - 1; i++) {
64
+ const a = buf[i], b = buf[i + 1];
65
+ if (target >= a.t && target <= b.t) {
66
+ const k = (target - a.t) / (b.t - a.t || 1);
67
+ return {
68
+ x: lerp(a.v.x, b.v.x, k),
69
+ y: lerp(a.v.y, b.v.y, k),
70
+ z: lerp(a.v.z, b.v.z, k),
71
+ yaw: lerpAngle(a.v.yaw, b.v.yaw, k),
72
+ };
73
+ }
74
+ }
75
+ return buf[buf.length - 1].v;
76
+ }
77
+
78
+ remove(id: string) {
79
+ this.buffers.delete(id);
80
+ }
81
+ }
82
+ ```
83
+
84
+ **Tuning:** `RENDER_DELAY_MS` ≈ one tick interval + jitter (100 ms is safe for a 15 Hz
85
+ tick). Lower = more responsive but more stutter on jitter. For sudden teleports (respawn,
86
+ warp) clear that player's buffer and snap, so you don't lerp across the whole map.
87
+
88
+ ## Complete movement example
89
+
90
+ ```ts
91
+ import * as THREE from "three";
92
+ import { connect } from "@genex-ai/multiplayer";
93
+ import { GENEX } from "./genex.config";
94
+ import { RemoteInterpolator } from "./interpolation";
95
+
96
+ type S = { x: number; z: number; yaw: number };
97
+
98
+ const room = await connect<S>({ url: GENEX.colyseusUrl, room: GENEX.slug });
99
+ const interp = new RemoteInterpolator();
100
+
101
+ // --- local player: prediction. Input mutates this; we render yourself from it. ---
102
+ const me = { x: 0, z: 0, yaw: 0 };
103
+ addEventListener("keydown", (e) => {
104
+ if (e.key === "ArrowLeft") me.yaw += 0.1;
105
+ if (e.key === "ArrowRight") me.yaw -= 0.1;
106
+ if (e.key === "ArrowUp") { me.x += Math.sin(me.yaw); me.z += Math.cos(me.yaw); }
107
+ });
108
+
109
+ // --- publish at ~15 Hz (NOT per frame) ---
110
+ const tick = setInterval(() => room.me.set(me), 66);
111
+
112
+ // --- meshes, one per id ---
113
+ const meshes = new Map<string, THREE.Object3D>();
114
+ function meshFor(id: string) {
115
+ let m = meshes.get(id);
116
+ if (!m) { m = new THREE.Mesh(boxGeo, boxMat); scene.add(m); meshes.set(id, m); }
117
+ return m;
118
+ }
119
+ room.on("leave", (id) => {
120
+ const m = meshes.get(id);
121
+ if (m) { scene.remove(m); meshes.delete(id); }
122
+ interp.remove(id);
123
+ });
124
+
125
+ function frame() {
126
+ // yourself: render from local predicted state (zero latency)
127
+ meshFor(room.id).position.set(me.x, 0, me.z);
128
+ meshFor(room.id).rotation.y = me.yaw;
129
+
130
+ // everyone else: feed the interpolator, render the smoothed sample
131
+ for (const [id, p] of room.players) {
132
+ if (id === room.id) continue;
133
+ interp.push(id, { x: p.state.x ?? 0, y: 0, z: p.state.z ?? 0, yaw: p.state.yaw ?? 0 });
134
+ const v = interp.sample(id);
135
+ if (!v) continue;
136
+ const m = meshFor(id);
137
+ m.position.set(v.x, v.y, v.z);
138
+ m.rotation.y = v.yaw;
139
+ }
140
+
141
+ renderer.render(scene, camera);
142
+ requestAnimationFrame(frame);
143
+ }
144
+ frame();
145
+
146
+ // cleanup if you ever tear down: clearInterval(tick); room.leave();
147
+ ```
148
+
149
+ ## Custom events (shots, emotes, chat)
150
+
151
+ For one-off actions that aren't part of continuous state, use `send` — it doesn't belong
152
+ in `me.set` (which is your *current* state, not events):
153
+
154
+ ```ts
155
+ // shooter:
156
+ room.send("shot", { from: room.id, x: me.x, z: me.z, yaw: me.yaw });
157
+
158
+ // everyone else:
159
+ room.on("shot", (msg: any) => spawnTracer(msg.x, msg.z, msg.yaw));
160
+ ```
161
+
162
+ ## Shared room state (scores, round, world)
163
+
164
+ `shared` is for state everyone agrees on, not per-player position:
165
+
166
+ ```ts
167
+ room.shared.set("round", (Number(room.shared.get("round")) || 0) + 1);
168
+ room.on("shared", (key, value) => { if (key === "score") updateScoreboard(value); });
169
+ ```
170
+
171
+ Any client can write any key (demo relay has no auth). For authority (who may change the
172
+ score / advance the round), pick one client — e.g. the first/lowest session id present —
173
+ and let only it write.
174
+
175
+ ## Persistence helper
176
+
177
+ ```ts
178
+ // persistence.ts
179
+ export async function loadWorld<T>(fallback: T): Promise<T> {
180
+ try {
181
+ const { data } = await fetch(`${GENEX.apiUrl}/api/projects/${GENEX.slug}/state`).then(r => r.json());
182
+ return (data as T) ?? fallback;
183
+ } catch { return fallback; }
184
+ }
185
+
186
+ let saveTimer: ReturnType<typeof setTimeout> | null = null;
187
+ export function saveWorld(world: unknown) {
188
+ // debounce: at most one PUT per second, from ONE authority client
189
+ if (saveTimer) return;
190
+ saveTimer = setTimeout(() => {
191
+ saveTimer = null;
192
+ fetch(`${GENEX.apiUrl}/api/projects/${GENEX.slug}/state`, {
193
+ method: "PUT",
194
+ headers: { "Content-Type": "application/json" },
195
+ body: JSON.stringify(world),
196
+ }).catch(() => {});
197
+ }, 1000);
198
+ }
199
+ ```
200
+
201
+ State is one JSON blob per project, max 1 MB, last-write-wins. Save from a single
202
+ authority (host) so concurrent writers don't clobber each other.
@@ -36,6 +36,11 @@ map, execution order, and acceptance gate.
36
36
  | exposure, tone mapping, color grading, LUTs | `$genex-threejs-exposure-color-grading` |
37
37
  | render-target ownership, pass ordering, depth/normal/history signals | `$genex-threejs-image-pipeline` |
38
38
  | fixed-view captures, seed sweeps, browser and GPU evidence | `$genex-threejs-visual-validation` |
39
+ | realtime multiplayer: movement sync, shared state, presence, shots/emotes, persistence | `$genex-threejs-multiplayer` |
40
+
41
+ **Multiplayer is mandatory routing:** if the game has 2+ players sharing a world, loading
42
+ `$genex-threejs-multiplayer` is **required** before any networking code — the relay does no
43
+ interpolation/prediction, and that skill is how you add them.
39
44
 
40
45
  ## Real (AI-generated) assets — `npx genex` commands
41
46
 
@@ -58,6 +63,20 @@ Prefer the **procedural** skills above for abstract/parametric/animated systems
58
63
  **`npx genex` generators** for concrete, describable, photoreal assets. They complement
59
64
  each other.
60
65
 
66
+ **Generate a core asset set by default — don't wait to be asked.** For any game that
67
+ needs concrete objects or surfaces, decide a small core set from the concept and start
68
+ generating it **up front, in parallel** (each `npx genex` is an independent ~1-minute
69
+ job — launch them concurrently in the background, then scaffold the scene while they run
70
+ and wire each asset in as it lands, with a procedural placeholder as fallback until then):
71
+
72
+ - the **hero model** the player controls or chases (`npx genex model`),
73
+ - one key **texture** for the ground/main surface (`npx genex texture --terrain` for ground),
74
+ - a **skybox** when the scene is outdoors (`npx genex skybox`),
75
+ - a **sfx** or two for the core action/feedback (`npx genex sfx`).
76
+
77
+ Skip generation only for purely abstract/geometric games. Keep the set small and
78
+ concept-driven — a richer first build beats a grey-box one.
79
+
61
80
  ## Routing rules
62
81
 
63
82
  - Start from the playable game target: player verb, scene scale, camera distance,
@@ -51,3 +51,11 @@ publishing or multiplayer, inspect the project first. Prefer clean boundaries:
51
51
  - serializable player/session state;
52
52
  - explicit asset loading paths;
53
53
  - one clear start function for local preview and hosted launch.
54
+
55
+ **Multiplayer is mandatory routing.** If the game has 2+ players sharing a world,
56
+ load `$genex-threejs-multiplayer` **before writing any networking code** — it is not
57
+ optional. The `@genex-ai/multiplayer` relay syncs `me`/`shared` but does **no**
58
+ physics, prediction, or interpolation; that skill is how you add interpolation for
59
+ remote players, prediction for the local player, config wiring, and (for save-state
60
+ games) the persistent-world API. Use only the APIs that skill documents — do not
61
+ invent transport methods.