virtualmatter 0.6.8 → 0.8.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
@@ -41,8 +41,16 @@ While `sync` runs, saving a Lua script in your editor deploys it - scripts
41
41
  hot-reload in the engine. Sync never overwrites work you have not synced: if
42
42
  a file changed both here and in the live session (while sync ran, or while it
43
43
  was stopped), your copy stays put and the remote version lands next to it as
44
- `<name>.remote-conflict`. Merge, save, and it pushes. Edits made while sync
45
- was stopped go out when it starts again.
44
+ `<name>.remote-conflict`. Merge, save, and it pushes. A world copy that is
45
+ byte-identical to what you last synced is not a conflict, even when its etag
46
+ moved (the engine rewrites some files at boot): your edit just goes out. Edits
47
+ made while sync was stopped go out when it starts again.
48
+
49
+ The platform stops a world's engine when nobody has been in it for a while.
50
+ Sync keeps running through that without starting the world again just to
51
+ poll it: it checks once a minute whether the world is back, and the next file
52
+ you save wakes it and goes out. After an engine restart, sync follows the
53
+ world to its new session and waits for it to become reachable.
46
54
 
47
55
  Large voxel and terrain files (several GB is normal) are streamed to disk,
48
56
  never loaded into memory. Sync does not push a file over 8 MB, the most the
@@ -89,9 +97,31 @@ npx virtualmatter screenshot -o shot.png # default overview
89
97
  npx virtualmatter screenshot --target "Player" -o p.png # frame one object
90
98
  npx virtualmatter screenshot --at 0,30,40 --rot 0,-35,0 # exact camera
91
99
  npx virtualmatter screenshot --client 4 -o ui.png # what client 4 sees, UI included
100
+ npx virtualmatter screenshot --depth -o st.png # + st.depth.npy (metres), .depth.png, .depth.json
92
101
  # --rot is yaw,pitch,roll
93
102
  ```
94
103
 
104
+ ## 3D models: upload, voxelize, place
105
+
106
+ ```bash
107
+ npx virtualmatter voxelize tower.glb --vpm 32 --place 0,0,0 # one model into the world
108
+ npx virtualmatter voxelize tiles/ --vpm 2 --place -1000,0,-1000 # a folder of map tiles
109
+ npx virtualmatter assets # your asset library
110
+ npx virtualmatter place "tower" --at 20,0,5 --yaw 90 # place a library asset again
111
+ npx virtualmatter jobs <job id> --wait # follow a --no-wait job
112
+ ```
113
+
114
+ `voxelize` uploads GLB, glTF, OBJ, FBX, STL, point clouds (PLY, PTS, XYZ, E57,
115
+ LAS, LAZ), MagicaVoxel and zips from disk (files over 190 MiB go up
116
+ resumably, up to 10 GiB), runs Virtual Matter's voxelizer, and keeps the
117
+ result in your asset library. `--attach` copies it into the world's `Assets/`
118
+ folder and `--place x,y,z` also puts it in the scene. Units are metres and a
119
+ model keeps its own coordinates: `--place` says where its 0,0,0 goes, so tiles
120
+ cut from one dataset line up when they share an offset. `--vpm` is voxels per
121
+ metre (a power of two; 2-4 for buildings and terrain, 32-128 for props),
122
+ `--method RayCast` suits open meshes such as terrain, and `--rotate -90,0,0`
123
+ stands a Z-up model upright.
124
+
95
125
  ## If you are a coding agent, read this part
96
126
 
97
127
  Build through these commands, always. Do not open virtualmatter.ai or
@@ -133,7 +163,8 @@ It works before a world is selected: `list_projects`, `create_project`, and
133
163
  `select_project` (any link or id, optionally mirroring into a folder) pick
134
164
  one, then `list_files`, `read_file`, `write_file`, `run_lua`,
135
165
  `get_engine_errors`, `capture_screenshot`, `open_native_client`, and
136
- `world_info` act on it. `patch_file` edits a world file by replacing one
166
+ `world_info` act on it. `voxelize_model`, `get_voxelize_job`, `list_assets`
167
+ and `place_asset` bring 3D files from disk into the world as voxel assets. `patch_file` edits a world file by replacing one
137
168
  exact snippet, and `push_local_files` / `fetch_files` move files between the
138
169
  world and the synced folder the server runs in, so big scripts never travel
139
170
  through the conversation. Writes handle etag concurrency internally, and
@@ -151,13 +182,13 @@ deploying it.
151
182
  | `push [paths...] [--dir <dir>] [--force] [--json]` | One-shot deploy of the named files, or of every file changed since the last sync. Per-file result; unchanged files are not sent. `--force` overwrites a world copy that changed since. Refuses while `sync` runs on the folder. |
152
183
  | `fetch [paths...] [--dir <dir>] [--include-large] [--json]` | One-shot download of the named files (any size), or of every file the world changed since the last sync. Never overwrites local edits. |
153
184
  | `logs [dir] [--restarts] [--tail N] [--framing <id>] [--json]` | The engine's log. `--restarts` lists every recent engine restart and why: a crash (the engine restarted itself; with the last lines it logged) or a platform stop with its reason (idle, update, restart, out of memory). `--framing` reads a play server listed by `status`. |
154
- | `status [dir] [--json]` | The world's play servers: whether each matches the editor, which scene they load and when it was last saved, and how the last update went. |
155
- | `publish [dir] [--played-scene] [--no-wait] [--json]` | Update the play servers with the editor's latest (the project page's Update play servers). Says which scene they will load and warns when the editor's latest work isn't in it; waits and reports each server; exits 1 if any server wasn't updated. |
156
- | `open [target]` (`client`) | Optional: open a world in the native desktop client, downloading and signing it in on first use. `--install-only`, `--print` (just the download URL), `--force`. |
185
+ | `status [dir] [--json]` | The world's engine iteration: what the editor and each play server are set to and what each last booted, any mismatch between them, a move the platform has announced, the last move and who made it, and a link to what changed in the iteration. Then its play servers: whether each matches the editor, which scene they load and when it was last saved, and how the last update went. |
186
+ | `publish [dir] [--played-scene \| --init-scene] [--no-wait] [--json]` | Update the play servers with the editor's latest (the project page's Update play servers). Says which scene they will load and warns when the editor's latest work isn't in it, including a played scene saved a day or more after InitScene; at a terminal it then asks before sending InitScene (`--init-scene` skips the question). Says when it will move the play servers to the editor's engine iteration. Waits and reports each server; exits 1 if any server wasn't updated. |
187
+ | `open [target]` (`client`) | Optional: open a world in the native desktop client, downloading and signing it in on first use. It fetches the client that matches the world's engine iteration and keeps one per iteration, since a client only joins worlds of its own iteration. `--install-only`, `--print` (just the download URL), `--force`. |
157
188
  | `run-lua [dir] --code "<lua>" [--target server\|client] [--client <id>]` | Execute Lua in the running engine. A client run uses the only connected client unless `--client` names one (list them with `--code "return Server:GetClients()"`). Exit code 3 means the engine did not answer in time and may still be running the code: check its effect before sending code that changes the world again. It is never retried for you. |
158
189
  | `errors [dir]` | Recent engine errors. Retried twice when the engine is busy or briefly unreachable, since it only reads. Notes on stderr when the engine restarted in the last hour, since a restart clears the error buffer. |
159
190
  | `atomo [--dir <dir>] -- <command> ...` | The engine SDK's `atomo` commands (`run-lua`, `run-lua-client [id]`, `errors [--after-reload <file>...] [--timeout <s>]`) in atomo's own output format and exit status, for agents following the engine guide and tools written against atomo such as the starter builder. The folder's `./atomo` calls this. Exit 1: the Lua snippet raised, or `errors` printed an error that no earlier check reported; 2: nothing ran; 3: a bridge timeout, the engine may still be running it. `errors --after-reload` waits (default 10 s) until the world has the saved files, which `sync` pushes, and has reloaded them, then reads the errors: run it right after a save instead of sleeping. |
160
- | `screenshot [dir] [-o out.png] [--client <id>]` | Capture the engine's view; `--client` captures through a connected client, UI included. |
191
+ | `screenshot [dir] [-o out.png] [--client <id>] [--depth]` | Capture the engine's view; `--client` captures through a connected client, UI included. `--depth` also reads the frame's depth buffer: `<out>.depth.npy` (float32 metres along the view axis, height x width, 0 = sky), a `.depth.png` preview and a `.depth.json` with the camera. Needs an engine with depth capture (MR !2671 / !2672). |
161
192
  | `mcp [dir] [--framing <id>]` | Run the stdio MCP server. |
162
193
  | `login` / `logout` / `whoami` | Device-code sign-in; every other command signs you in automatically when needed. Tokens live in `~/.config/virtualmatter/credentials.json` (mode 0600) and refresh automatically. |
163
194
 
@@ -115,7 +115,7 @@ call them (the starters' \`starterctl.py\`). Everything else maps to the
115
115
  | \`atomo run-lua '<code>'\` | \`./atomo run-lua '<code>'\`, or \`npx virtualmatter run-lua --code '<code>'\` (MCP: \`run_lua\`) |
116
116
  | \`atomo run-lua-client ...\` | \`./atomo run-lua-client <id> '<code>'\`, or \`npx virtualmatter run-lua --target client --code '<code>'\` |
117
117
  | \`atomo errors\` | \`./atomo errors\` (exits 1 when any error is new since the last check), or \`npx virtualmatter errors\` (MCP: \`get_engine_errors\`) |
118
- | \`atomo screenshot\` / \`screenshot-at\` / \`screenshot-obj\` | \`npx virtualmatter screenshot -o shot.png\` (MCP: \`capture_screenshot\`); aim the camera with run-lua first if needed |
118
+ | \`atomo screenshot\` / \`screenshot-at\` / \`screenshot-obj\` | \`npx virtualmatter screenshot -o shot.png\` (MCP: \`capture_screenshot\`); aim the camera with run-lua first if needed. Add \`--depth\` (MCP: \`depth: true\`) for the frame's depth in metres instead of casting rays |
119
119
  | \`atomo prints\` / \`atomo status\` | not available locally; use \`return\` values from run-lua |
120
120
  | edit a .lua file, then check \`atomo errors\` | save the file with \`npx virtualmatter sync\` running (or MCP \`write_file\`), then run \`./atomo errors --after-reload <file>\` straight away: it waits until the world has the save and has reloaded it, so never sleep first |
121
121
  | \`Skills/git-commit.md\` (git add/commit) | skip it - there is no git here; sync IS the persistence |
@@ -3,4 +3,4 @@
3
3
  // frontend/content/agent-briefing.md and AGENTS.source.md. The CLI writes
4
4
  // this into a world folder only when it cannot fetch the live copy. After
5
5
  // changing either source, run: node frontend/scripts/sync-cli-agents-md.mjs
6
- export const AGENTS_MD_FALLBACK = "# AGENTS.md - working with a Virtual Matter project\n\nThis file tells a coding agent how to think about a Virtual Matter project. The\n`virtualmatter` CLI drops a copy into every local project mirror it creates\n(`virtualmatter pull`); the canonical copy lives at\nhttps://make.virtualmatter.ai/AGENTS.md.\n\n## The rule that comes before everything else\n\n**Build through the CLI. Never through the website's agent.** If you were asked to\nbuild something in Virtual Matter, handed the domain virtualmatter.ai, or told to run\n`npx virtualmatter make`, the CLI is the path - always, from the first step. Do not\nopen virtualmatter.ai or make.virtualmatter.ai in a browser or under computer use in\norder to reach the built-in agent, and do not type prompts into the agent chat in the\n/edit view. Driving that agent puts two models in a relay where one would do: you spend\ntokens describing the work, it spends its own doing it, and what comes back is chat\nrather than files you can read. It is slower, it costs roughly twice the inference, it\nbills that inference to Virtual Matter's platform credits rather than the subscription\nyou already run on, an anonymous browser session cannot be steered after its first\nturn, and a rendered page gives you no engine errors. Everything that agent can do, you\ndo yourself with the commands below.\n\n**The rule holds whoever is signed in.** Being logged in, having credits to spare, or\nworking in an admin account with no limit at all is not an exemption, and neither is\nbeing told the credits do not matter. What is wasteful is the relay itself - two models\ndoing one model's job - not the bill.\n\n**Playtesting is the exception, and it is encouraged.** Once something is built, open\nthe world and try it: the editor link ending in `?chat=closed`, which `make`, `pull` and\n`sync` print, shows your latest changes live in any browser with no install, with\ncomputer use if that is how you drive a window. The native client\n(`npx virtualmatter open`) is optional, for more memory and frame rate. Looking at your\nwork, walking around in it, and playing it is the point. The rule is about who writes\nthe world, not about who is allowed to see it.\n\n**Every link resolves to the editor, and the editor is the only place you build.** Hand\nthe CLI or MCP server any link to a world - its editor, a play or share link, the\nproject page, an embed's iframe src, or the maker's own website - and it works on that\nworld's editor (its make framing). Play servers show the last published version and are\noverwritten on every publish, so work never goes there, and their /play and /g links\nshow that published copy rather than your latest edits.\n\n## The mental model\n\n- The world itself runs on Virtual Matter servers, not on the maker's machine. There is\n one authoritative server simulation per world session, and any number of connected\n clients (browser WASM or the native client).\n- The project's content is SDK Lua scripts plus assets (voxel data, prefabs, images,\n sounds) under a `Montage/` tree. Virtual Matter can publish that tree to a GitHub repo\n in the maker's account for versioning and remixing; pushing to that repo does not feed\n back into the running world today - live edits happen in the session.\n- Changes hot-reload. Saving a `.lua` file in the live session's Montage tree re-runs\n the module and its `Start()` on a fresh instance inside the running world - no restart,\n no build step.\n- Prefabs are reusable scene-graph snippets: JSON files with a `.prefab` extension in the\n Montage folder, instantiated at runtime via `Server:InsertPrefab(asset)`.\n- There is no local runtime - the world cannot run on the maker's machine. The\n `virtualmatter` CLI (npm) is how you reach it from a local harness, and it needs no\n setup: the first command that needs an account signs you in with a device code.\n `npx virtualmatter make \"My world\"` makes a world and mirrors its Montage tree\n into `./my-world`; `npx virtualmatter pull <any Virtual Matter link>` mirrors an\n existing one (/edit, /play, /g, /p, /projects links all work, with or without a\n readable slug); `npx virtualmatter list` shows your worlds; `npx virtualmatter sync`\n live-pushes saves into the running session (which hot-reloads them), and\n `npx virtualmatter push <files>` deploys named files once, reporting each one - the\n better fit for an agent that saves in quick succession (each script write resets the\n world's Lua, and push skips files that did not change);\n `npx virtualmatter run-lua` / `errors` / `screenshot` drive the engine;\n `npx virtualmatter open` optionally opens the world in the native desktop client,\n downloaded and signed in on first use; and `npx virtualmatter mcp` serves\n all of it over MCP. A mirrored folder carries `.mcp.json` and `.cursor/mcp.json`\n (so Claude Code and Cursor register the MCP server on their own), this file, and a\n `CLAUDE.md` that imports it. Folders from virtualmatter 0.5.0 on also carry\n `.codex/config.toml`, which Codex loads once you trust the folder; with an older\n CLI, or if Codex does not list the server, register it once with\n `codex mcp add virtualmatter -- npx -y virtualmatter mcp`. In Claude Code outside a\n mirrored folder, use `claude mcp add virtualmatter -- npx -y virtualmatter mcp`. The\n server works before a world\n is selected (`list_projects`, `create_project`, `select_project`), then exposes\n `list_files`, `read_file`, `write_file`, `run_lua`, `get_engine_errors`,\n `capture_screenshot`, `open_native_client`, and `world_info`.\n- Work through the CLI, not the website - see the rule above. Prompting the built-in\n agent to do your building is the one thing to avoid; opening the world to play it is\n not.\n- Seeing your work: `virtualmatter screenshot` shoots a default overview of the world\n origin, `--target <object>` frames one object by name or id, and `--at x,y,z --rot\n yaw,pitch,roll` places the camera exactly. Y is up and -Z is forward, and the\n rotation really is yaw first: yaw 0 faces -Z, pitch -90 looks straight down, pitch 0\n is the horizon. The MCP `capture_screenshot`\n tool takes the same arguments. Verify a change with a screenshot plus `errors` rather\n than assuming a write worked.\n- A `run-lua` that fails with HTTP 504 (`run-lua timed out`, exit code 3 from CLI\n 0.6.4 on; the MCP `run_lua` tool returns the same text) reached the engine, which\n may still be running it. Do not send code that changes the world again: check its\n effect first, by reading back what it sets or taking a screenshot. Any other\n failure never reached the engine and is safe to retry.\n- The mirrored folder's AGENTS.md is this guide followed by the engine SDK's own agent guide\n (the AGENTS.md that lives in every Montage tree and inside the desktop client's\n Data/Sdk/Montage/). The engine guide assumes an in-session agent driving the engine\n through `atomo`; the merged file maps each `atomo` step to the CLI or MCP equivalent, and\n the `Skills/*.md` references it points at are in the folder. The SDK's own tooling\n (`atomo`, `vm_auth.py`, the agent-log hooks) is not mirrored: it only works inside a\n session. From CLI 0.6.5 on, macOS and Linux folders get their own `./atomo`, which\n serves the guide's `./atomo run-lua`, `run-lua-client` and `errors` through the CLI.\n Sandboxed agents need network access for every CLI command.\n- After saving a `.lua` file with `sync` running, check it with\n `./atomo errors --after-reload <file>` (CLI 0.6.8 on) instead of sleeping: it waits\n until the world has the save and has reloaded it, then lists the errors. `./atomo`\n exits like the engine's own: 1 when `run-lua` raised or `errors` shows an error no\n earlier check reported, 2 when nothing ran, 3 when the engine may still be running it.\n- Worlds with the platform's skill packages carry them in `Skills/atomontage-*`.\n From CLI 0.6.5 on, `pull` and `sync` also copy them into `.claude/skills/`, so Claude\n Code loads them as skills; other harnesses follow the routing table in AGENTS.md.\n Start from `atomontage-game-starters` for any of the 15 homepage starter games: its\n `starterctl.py build <preset>` builds a playable starter in seconds through\n `./atomo`. Where a skill says to hand a live check to the in-game agent, run it\n yourself: never send prompts to the world's built-in agent.\n\n## Reference\n\nThe same facts as terse lists, for quick lookup.\n\n### Project model\n- A project (\"montage\") is one voxel world hosted with Virtual Matter.\n- A project has framings: \"make\" framings (editing sessions) and \"play\"\n framings (public play sessions). A framing is a running session slot\n on a voxel host.\n- Project content = SDK Lua scripts + assets under a Montage/ tree.\n Edits made in the live session hot-reload into the running world.\n The tree can be published to a maker-owned GitHub repo.\n\n### URL shapes (make.virtualmatter.ai)\n- /new builder for people: create a world from a prompt\n (also at https://virtualmatter.ai/); coding agents\n use npx virtualmatter make instead\n- /edit/<framing-id> maker session: live world + agent chat. The chat is\n for people; a coding agent builds with the CLI and\n never prompts it\n (also /edit/<slug>-<framing-id>; the CLI accepts both)\n- /play/<framing-id> play session for a specific framing\n- /g/<id> share URL resolver: 302s to a live session\n\n### APIs (unauthenticated)\n- GET https://make.virtualmatter.ai/api/v1/public/native-clients\n JSON: { iteration, clients: [{ platform, kind, variant, url, filename,\n file_size, branch, commit, match }] } - per-platform native client\n installers (kind \"download\") or store links (kind \"store\", iOS).\n Windows and Linux list two downloads each: variant \"installer\" /\n \"flatpak\" for people, and \"portable\" / \"tarball\", the file tree the\n CLI installs.\n\n### CLI + MCP (npm package \"virtualmatter\", Node >= 20)\n- npx virtualmatter make \"<name>\" make a world, mirror it into ./<slug>\n- npx virtualmatter pull <link> mirror an existing world (any link shape)\n- npx virtualmatter list your worlds with framing ids + URLs\n- npx virtualmatter sync live-push saves into the running world\n (one per folder; does not pull files too\n large to push back, such as terrain)\n- npx virtualmatter push [files] one-shot deploy, per-file result; exit 1\n on any conflict or failure\n- npx virtualmatter fetch [files] one-shot download; never overwrites\n local edits (conflict -> .remote-conflict)\n- npx virtualmatter logs --restarts why the world restarted (crash + last\n log lines, or the platform's reason)\n- npx virtualmatter publish update the play servers; reports each\n server, says which scene they load\n- npx virtualmatter status play servers vs the editor, last update\n- npx virtualmatter open optional: open it in the native client\n- npx virtualmatter mcp stdio MCP server (list_projects,\n create_project, select_project, list_files, read_file, write_file,\n patch_file, push_local_files, fetch_files, run_lua, get_engine_errors,\n get_engine_logs, capture_screenshot, play_server_status,\n publish_play_servers, open_native_client, world_info)\n- Sign-in happens on first use (device code); no separate login step.\n- These commands are the whole build path. Never prompt the built-in\n agent on the site to do the work; a browser or the native client is\n for playtesting what you built.\n- Any link to a world (editor, play or share link, project page, embed,\n or the maker's own website) resolves to its editor, the only place\n the CLI and MCP server work. Play servers show the last published\n version and are overwritten on publish.\n- Watch changes land live at the editor link ending in ?chat=closed,\n in any browser, no install. The native client is optional.\n- A mirrored folder carries .mcp.json, .cursor/mcp.json, AGENTS.md and\n CLAUDE.md, so Claude Code and Cursor register the server on their own.\n- Codex: folders from 0.5.0 on carry .codex/config.toml, loaded once the\n folder is trusted; otherwise register the server once:\n codex mcp add virtualmatter -- npx -y virtualmatter mcp\n\n## SDK Lua cheat sheet\n\nThe scripting language is Lua 5.4, sandboxed: `os`, `io`, `require`, `package`,\n`dofile`, `loadfile`, `loadstring` are nil. `math`, `string`, `table`, `coroutine`\nremain. No `os.time` - use `Time.time` (sim time), `Time.frame`, or\n`AE:GetDebugTime()` (wall clock).\n\n### Script shape\n\nEvery persistent behavior is a `.lua` file in the Montage tree returning a `self` table:\n\n```lua\nlocal self = {}\nfunction self:Start() end\nfunction self:Update(deltaTime) end\nreturn self\n```\n\nAttach to an object with `obj:AddScript(\"My Folder/Example.lua\", sync)` - the path is\nrelative to the Montage root; `sync = true` replicates the script to clients.\n`obj:FindScript(\"Example\")` returns the live instance.\n\n### Server / client split\n\nThe same script runs on the server and (when synced) on every client. Branch with\n`self.onServer` / `self.onClient`:\n\n```lua\nfunction self:Update(dt)\n if self.onClient then return end -- voxel edits are server-only\n -- authoritative logic here\nend\n```\n\nNothing replicates automatically: set `syncToClients = true` on the script or\nVoxelData component, and use `util:makeNetworkedTable(self, { hp = 100 })` for\nproperties that should sync (server writes, clients read, deltas only).\n`obj.pos` / `obj.rot` do not auto-sync - replicate them yourself.\n\n### RPC\n\n```lua\nself:RPC(\"serverDoSomething\", pos, dir) -- on a client: goes to the server\nfunction self:serverDoSomething(pos, dir, clientID) -- clientID auto-appended\n assert(self.onServer)\nend\n```\n\nOn the server, `self:RPC(...)` fans out to all clients. Reliable, FIFO per direction.\nRequires `self.component.syncToClients = true`.\n\n### Scene and objects (server)\n\n```lua\nlocal ob = Scene:CreateObject(\"Name\")\nob.save = true\nob:AddScript(\"Path/Script.lua\")\nScene:GetObjectByName(\"Name\")\nScene:CloneObject(ob) -- prefer over rebuilding\nob.active = false -- prefer over destroy\nob:AddTag(\"Enemy\"); FindObjectsWithTag(\"Enemy\") -- tags are runtime-only state\n```\n\n### Voxel editing (server only, async)\n\n```lua\nVox:Add(Sphere(pos, 2)):Color(1, 0, 0):Run()\nVox:Add(Box(Vec3(0, -1, 0), Vec3(20, 2, 20))):ForceStatic():Run()\n```\n\nShapes: `Box(center, fullSize)`, `Sphere(center, r)`, `Capsule(p1, p2, r)`,\n`Cylinder(p1, p2, r1[, r2])`. `Run()` is async - chain `:OnFinished(fn)` before\n`:Run()` to read post-commit state. Big edits stall the frame for every client;\nkeep in-game edits small and infrequent.\n\n### Input (event-driven, client input reaches the server)\n\n```lua\nself.component.syncToClients = true\nevents.keyDown.addListener(self, function(key, from) self.keys[key] = true end)\nevents.keyUp.addListener(self, function(key, from) self.keys[key] = false end)\n```\n\nPlayer-driven movement must be client-predicted - never gate the player's own\nfeedback on the server round-trip.\n\n### Physics\n\n```lua\nlocal rb = obj:AddComponent(\"RigidBody\")\nrb:AddImpulse(Vec3(0, 50, 0), obj.pos)\nrb.velocity; rb.mass; rb.gravityScale\n```\n\n### Time and diagnostics\n\n```lua\nTime.dt; Time.time; Time.frame; Time.timeScale\nAE:GetLogValue(\"Raycasts\") -- engine counters, e.g. raycasts this frame\nAE:GetAssets() -- list all assets (APIs take Assets, not paths)\n```\n\n### UI (client-side HUD)\n\nBuild screen UI with the MUI builder: `UI:AddPanel|AddButton|AddLabel|AddSlider|...`\nchained with `:Set{...}`; flexbox-like row-wrap layout.\n\n### Engine behaviours that catch people out\n\nEach of these has broken a real game. An error inside a `util:schedule` chain or an\n`Update` stops that loop without anything else visible, so check `errors` after a\nchange even when the world looks fine.\n\n- Object names may hold only letters, digits and single spaces. `Scene:CreateObject`\n rejects `_`, `-`, `.` and leading or trailing spaces with \"Failed to create object.\n Given name was invalid.\"\n- `Cast:Ray` with a zero-length vector throws \"ray is zero length\". Guard every ray\n whose vector can be zero: coincident positions, a target standing on the shooter, a\n projectile at rest.\n- `ForceStatic()` on `Cast:Ray(...)` and `Collide(...)` is server-only; a client gets\n \"ForceStatic() only available on server\". On a client, use a plain ray and skip\n dynamic objects with `Ignore`.\n- The static edit guard's budget is per frame, not per op. About the 4th large op in\n one Lua call throws \"frame voxel budget exhausted\", leaving the earlier ops applied.\n Spread batches over frames and retry a refused op on the next frame, or a reset or\n map build leaves terrain half-edited.\n- Every static `Vox` op (Remove, Add, Paint) costs one 30-50 ms server frame whatever\n its size. Prefer fewer, bigger ops and budget the rate: about 1 op/s keeps the p99\n frame near 33 ms.\n- Static edits reach connected clients seconds to tens of seconds late, and a freshly\n joined client that is still streaming the map can wait 45 s or more. Gameplay must\n not depend on client terrain: hit checks, cover and validation belong on the server.\n- Client terrain rays are LOD-quantised in 0.125-0.25 m steps a few metres from the\n camera. Give client-side terrain checks a tolerance of 0.3 m or more, and use server\n rays for anything authoritative.\n- Setting `child.parent = obj` keeps the child's world transform. Set `localPos` and\n `localRot` after parenting, not before.\n- `Server:GetStreamingStats()` reports `STALLING` and `finalRatioPct = 0` for healthy\n clients too, so it cannot tell you a client has stopped receiving edits.\n- After a map-scale rebuild, the default `screenshot` (rendered by the server's own\n view) can show stale or missing terrain. Check with server rays or with\n `screenshot --client <id>` from a freshly connected client.\n\n## Conventions\n\n- Coordinates: Y is up, -Z is forward, X is right.\n- Script files are named in capital case with spaces (`Character Controller.lua`).\n- Check whether a script is already attached before adding it - duplicates run twice.\n- The server is for authority (world edits, spawns, state); clients are for feel\n (prediction, FX, UI).\n\n## Embed or build a world for an existing website\n\nFor a shared project link, fetch `/api/v1/public/embed?target=<encoded-link>`\nand follow `/embed-guide.md`. Use the returned canonical player URL, not the\nmaker's external website URL. Keep the existing website and its design.\n\nFor account discovery or prompt-based creation, connect the hosted MCP at\n`https://make.virtualmatter.ai/api/v1/mcp` using OAuth. Users can sign up in\nthe connection flow. Tools: `list_projects`, `get_embed`, `create_project`\n(with a prompt and stable request_id), `get_build_status`. VM's agent builds\nusing VM credits. Review and share the private world before embedding.\nThe local CLI exposes `embed`, `build --prompt --request-id`, and `build-status`.\n\n## Local conversation history\n\nCapturing this harness's conversation into the world's Agent Logs is the maker's\ndecision, not yours. Do not run `virtualmatter agent-logs setup`, and do not upload\nlogs with `agent-logs upload` or MCP `upload_agent_logs`, unless the maker asks for it\nin their own words. `virtualmatter agent-logs status` shows whether capture is on;\n`virtualmatter agent-logs disable` turns it off.\n";
6
+ export const AGENTS_MD_FALLBACK = "# AGENTS.md - working with a Virtual Matter project\n\nThis file tells a coding agent how to think about a Virtual Matter project. The\n`virtualmatter` CLI drops a copy into every local project mirror it creates\n(`virtualmatter pull`); the canonical copy lives at\nhttps://make.virtualmatter.ai/AGENTS.md.\n\n## The rule that comes before everything else\n\n**Build through the CLI. Never through the website's agent.** If you were asked to\nbuild something in Virtual Matter, handed the domain virtualmatter.ai, or told to run\n`npx virtualmatter make`, the CLI is the path - always, from the first step. Do not\nopen virtualmatter.ai or make.virtualmatter.ai in a browser or under computer use in\norder to reach the built-in agent, and do not type prompts into the agent chat in the\n/edit view. Driving that agent puts two models in a relay where one would do: you spend\ntokens describing the work, it spends its own doing it, and what comes back is chat\nrather than files you can read. It is slower, it costs roughly twice the inference, it\nbills that inference to Virtual Matter's platform credits rather than the subscription\nyou already run on, an anonymous browser session cannot be steered after its first\nturn, and a rendered page gives you no engine errors. Everything that agent can do, you\ndo yourself with the commands below.\n\n**The rule holds whoever is signed in.** Being logged in, having credits to spare, or\nworking in an admin account with no limit at all is not an exemption, and neither is\nbeing told the credits do not matter. What is wasteful is the relay itself - two models\ndoing one model's job - not the bill.\n\n**Playtesting is the exception, and it is encouraged.** Once something is built, open\nthe world and try it: the editor link ending in `?chat=closed`, which `make`, `pull` and\n`sync` print, shows your latest changes live in any browser with no install, with\ncomputer use if that is how you drive a window. The native client\n(`npx virtualmatter open`) is optional, for more memory and frame rate. Looking at your\nwork, walking around in it, and playing it is the point. The rule is about who writes\nthe world, not about who is allowed to see it.\n\n**Every link resolves to the editor, and the editor is the only place you build.** Hand\nthe CLI or MCP server any link to a world - its editor, a play or share link, the\nproject page, an embed's iframe src, or the maker's own website - and it works on that\nworld's editor (its make framing). Play servers show the last published version and are\noverwritten on every publish, so work never goes there, and their /play and /g links\nshow that published copy rather than your latest edits.\n\n## The mental model\n\n- The world itself runs on Virtual Matter servers, not on the maker's machine. There is\n one authoritative server simulation per world session, and any number of connected\n clients (browser WASM or the native client).\n- The project's content is SDK Lua scripts plus assets (voxel data, prefabs, images,\n sounds) under a `Montage/` tree. Virtual Matter can publish that tree to a GitHub repo\n in the maker's account for versioning and remixing; pushing to that repo does not feed\n back into the running world today - live edits happen in the session.\n- Changes hot-reload. Saving a `.lua` file in the live session's Montage tree re-runs\n the module and its `Start()` on a fresh instance inside the running world - no restart,\n no build step.\n- Prefabs are reusable scene-graph snippets: JSON files with a `.prefab` extension in the\n Montage folder, instantiated at runtime via `Server:InsertPrefab(asset)`.\n- There is no local runtime - the world cannot run on the maker's machine. The\n `virtualmatter` CLI (npm) is how you reach it from a local harness, and it needs no\n setup: the first command that needs an account signs you in with a device code.\n `npx virtualmatter make \"My world\"` makes a world and mirrors its Montage tree\n into `./my-world`; `npx virtualmatter pull <any Virtual Matter link>` mirrors an\n existing one (/edit, /play, /g, /p, /projects links all work, with or without a\n readable slug); `npx virtualmatter list` shows your worlds; `npx virtualmatter sync`\n live-pushes saves into the running session (which hot-reloads them), and\n `npx virtualmatter push <files>` deploys named files once, reporting each one - the\n better fit for an agent that saves in quick succession (each script write resets the\n world's Lua, and push skips files that did not change);\n `npx virtualmatter run-lua` / `errors` / `screenshot` drive the engine;\n `npx virtualmatter open` optionally opens the world in the native desktop client,\n downloaded and signed in on first use; and `npx virtualmatter mcp` serves\n all of it over MCP. A mirrored folder carries `.mcp.json` and `.cursor/mcp.json`\n (so Claude Code and Cursor register the MCP server on their own), this file, and a\n `CLAUDE.md` that imports it. Folders from virtualmatter 0.5.0 on also carry\n `.codex/config.toml`, which Codex loads once you trust the folder; with an older\n CLI, or if Codex does not list the server, register it once with\n `codex mcp add virtualmatter -- npx -y virtualmatter mcp`. In Claude Code outside a\n mirrored folder, use `claude mcp add virtualmatter -- npx -y virtualmatter mcp`. The\n server works before a world\n is selected (`list_projects`, `create_project`, `select_project`), then exposes\n `list_files`, `read_file`, `write_file`, `run_lua`, `get_engine_errors`,\n `capture_screenshot`, `open_native_client`, `world_info`, and the 3D-model tools\n `voxelize_model`, `get_voxelize_job`, `list_assets` and `place_asset`.\n- Work through the CLI, not the website - see the rule above. Prompting the built-in\n agent to do your building is the one thing to avoid; opening the world to play it is\n not.\n- Seeing your work: `virtualmatter screenshot` shoots a default overview of the world\n origin, `--target <object>` frames one object by name or id, and `--at x,y,z --rot\n yaw,pitch,roll` places the camera exactly. Y is up and -Z is forward, and the\n rotation really is yaw first: yaw 0 faces -Z, pitch -90 looks straight down, pitch 0\n is the horizon. The MCP `capture_screenshot`\n tool takes the same arguments. Verify a change with a screenshot plus `errors` rather\n than assuming a write worked.\n- A `run-lua` that fails with HTTP 504 (`run-lua timed out`, exit code 3 from CLI\n 0.6.4 on; the MCP `run_lua` tool returns the same text) reached the engine, which\n may still be running it. Do not send code that changes the world again: check its\n effect first, by reading back what it sets or taking a screenshot. Any other\n failure never reached the engine and is safe to retry.\n- The mirrored folder's AGENTS.md is this guide followed by the engine SDK's own agent guide\n (the AGENTS.md that lives in every Montage tree and inside the desktop client's\n Data/Sdk/Montage/). The engine guide assumes an in-session agent driving the engine\n through `atomo`; the merged file maps each `atomo` step to the CLI or MCP equivalent, and\n the `Skills/*.md` references it points at are in the folder. The SDK's own tooling\n (`atomo`, `vm_auth.py`, the agent-log hooks) is not mirrored: it only works inside a\n session. From CLI 0.6.5 on, macOS and Linux folders get their own `./atomo`, which\n serves the guide's `./atomo run-lua`, `run-lua-client` and `errors` through the CLI.\n Sandboxed agents need network access for every CLI command.\n- After saving a `.lua` file with `sync` running, check it with\n `./atomo errors --after-reload <file>` (CLI 0.6.8 on) instead of sleeping: it waits\n until the world has the save and has reloaded it, then lists the errors. `./atomo`\n exits like the engine's own: 1 when `run-lua` raised or `errors` shows an error no\n earlier check reported, 2 when nothing ran, 3 when the engine may still be running it.\n- 3D models go in through the voxelizer, never through Lua. From CLI 0.7.0 on,\n `npx virtualmatter voxelize <files or folders> --place x,y,z` uploads GLB, OBJ, FBX,\n STL, point clouds (PLY, LAS/LAZ, E57) or zips from disk (resumable, up to 10 GiB),\n voxelizes them on Virtual Matter's voxelizer into the maker's asset library, attaches\n them to the world and places them in the scene; the MCP `voxelize_model` tool does the\n same. `virtualmatter assets` lists the library and `place <asset> --at x,y,z` puts one\n in again. A model keeps its own coordinates in metres and `--place` moves its 0,0,0,\n so map or city tiles voxelized from one dataset line up when placed with the same\n offset (`voxelize tiles/ --vpm 2 --place -1000,0,-1000`). 2-4 voxels per metre suits\n buildings and terrain, 32-128 props. Never paste mesh, footprint or height-grid text\n into a script or rebuild a model out of Lua primitives: that costs credits and engine\n memory and comes out wrong.\n- Worlds with the platform's skill packages carry them in `Skills/atomontage-*`.\n From CLI 0.6.5 on, `pull` and `sync` also copy them into `.claude/skills/`, so Claude\n Code loads them as skills; other harnesses follow the routing table in AGENTS.md.\n Start from `atomontage-game-starters` for any of the 15 homepage starter games: its\n `starterctl.py build <preset>` builds a playable starter in seconds through\n `./atomo`. Where a skill says to hand a live check to the in-game agent, run it\n yourself: never send prompts to the world's built-in agent.\n\n## Reference\n\nThe same facts as terse lists, for quick lookup.\n\n### Project model\n- A project (\"montage\") is one voxel world hosted with Virtual Matter.\n- A project has framings: \"make\" framings (editing sessions) and \"play\"\n framings (public play sessions). A framing is a running session slot\n on a voxel host.\n- Project content = SDK Lua scripts + assets under a Montage/ tree.\n Edits made in the live session hot-reload into the running world.\n The tree can be published to a maker-owned GitHub repo.\n\n### URL shapes (make.virtualmatter.ai)\n- /new builder for people: create a world from a prompt\n (also at https://virtualmatter.ai/); coding agents\n use npx virtualmatter make instead\n- /edit/<framing-id> maker session: live world + agent chat. The chat is\n for people; a coding agent builds with the CLI and\n never prompts it\n (also /edit/<slug>-<framing-id>; the CLI accepts both)\n- /play/<framing-id> play session for a specific framing\n- /g/<id> share URL resolver: 302s to a live session\n\n### APIs (unauthenticated)\n- GET https://make.virtualmatter.ai/api/v1/public/native-clients\n JSON: { iteration, clients: [{ platform, kind, variant, url, filename,\n file_size, branch, commit, match }] } - per-platform native client\n installers (kind \"download\") or store links (kind \"store\", iOS).\n Windows and Linux list two downloads each: variant \"installer\" /\n \"flatpak\" for people, and \"portable\" / \"tarball\", the file tree the\n CLI installs.\n\n### CLI + MCP (npm package \"virtualmatter\", Node >= 20)\n- npx virtualmatter make \"<name>\" make a world, mirror it into ./<slug>\n- npx virtualmatter pull <link> mirror an existing world (any link shape)\n- npx virtualmatter list your worlds with framing ids + URLs\n- npx virtualmatter sync live-push saves into the running world\n (one per folder; does not pull files too\n large to push back, such as terrain)\n- npx virtualmatter push [files] one-shot deploy, per-file result; exit 1\n on any conflict or failure\n- npx virtualmatter fetch [files] one-shot download; never overwrites\n local edits (conflict -> .remote-conflict)\n- npx virtualmatter logs --restarts why the world restarted (crash + last\n log lines, or the platform's reason)\n- npx virtualmatter publish update the play servers; reports each\n server, says which scene they load\n- npx virtualmatter status engine iteration, play servers vs the\n editor, last update\n- npx virtualmatter voxelize <files|folders> [--vpm 4] [--place x,y,z]\n 3D models (glb obj fbx stl, point\n clouds, zip) into voxel assets: upload,\n voxelize, attach, place; real-world\n metres, tiles line up\n- npx virtualmatter assets your asset library (--project: one\n world's attached assets)\n- npx virtualmatter place <asset> --at x,y,z put a library asset in\n the world at real size\n- npx virtualmatter open optional: open it in the native client\n- npx virtualmatter mcp stdio MCP server (list_projects,\n create_project, select_project, list_files, read_file, write_file,\n patch_file, push_local_files, fetch_files, run_lua, get_engine_errors,\n get_engine_logs, capture_screenshot, play_server_status,\n publish_play_servers, open_native_client, world_info, voxelize_model,\n get_voxelize_job, list_assets, place_asset)\n- Sign-in happens on first use (device code); no separate login step.\n- These commands are the whole build path. Never prompt the built-in\n agent on the site to do the work; a browser or the native client is\n for playtesting what you built.\n- Any link to a world (editor, play or share link, project page, embed,\n or the maker's own website) resolves to its editor, the only place\n the CLI and MCP server work. Play servers show the last published\n version and are overwritten on publish.\n- Watch changes land live at the editor link ending in ?chat=closed,\n in any browser, no install. The native client is optional.\n- A mirrored folder carries .mcp.json, .cursor/mcp.json, AGENTS.md and\n CLAUDE.md, so Claude Code and Cursor register the server on their own.\n- Codex: folders from 0.5.0 on carry .codex/config.toml, loaded once the\n folder is trusted; otherwise register the server once:\n codex mcp add virtualmatter -- npx -y virtualmatter mcp\n\n## SDK Lua cheat sheet\n\nThe scripting language is Lua 5.4, sandboxed: `os`, `io`, `require`, `package`,\n`dofile`, `loadfile`, `loadstring` are nil. `math`, `string`, `table`, `coroutine`\nremain. No `os.time` - use `Time.time` (sim time), `Time.frame`, or\n`AE:GetDebugTime()` (wall clock).\n\n### Script shape\n\nEvery persistent behavior is a `.lua` file in the Montage tree returning a `self` table:\n\n```lua\nlocal self = {}\nfunction self:Start() end\nfunction self:Update(deltaTime) end\nreturn self\n```\n\nAttach to an object with `obj:AddScript(script, sync)`; `sync = true` replicates the\nscript to clients. On iteration073 `script` is a path relative to the Montage root\n(`\"My Folder/Example.lua\"`); from iteration076 it must be the script's Asset (see\n\"Worlds on iteration076\" below). `obj:FindScript(\"Example\")` returns the live instance.\n\n### Server / client split\n\nThe same script runs on the server and (when synced) on every client. Branch with\n`self.onServer` / `self.onClient`:\n\n```lua\nfunction self:Update(dt)\n if self.onClient then return end -- voxel edits are server-only\n -- authoritative logic here\nend\n```\n\nNothing replicates automatically: set `syncToClients = true` on the script or\nVoxelData component, and use `util:makeNetworkedTable(self, { hp = 100 })` for\nproperties that should sync (server writes, clients read, deltas only).\n`obj.pos` / `obj.rot` do not auto-sync - replicate them yourself.\n\n### RPC\n\n```lua\nself:RPC(\"serverDoSomething\", pos, dir) -- on a client: goes to the server\nfunction self:serverDoSomething(pos, dir, clientID) -- clientID auto-appended\n assert(self.onServer)\nend\n```\n\nOn the server, `self:RPC(...)` fans out to all clients. Reliable, FIFO per direction.\nRequires `self.component.syncToClients = true`.\n\n### Scene and objects (server)\n\n```lua\nlocal ob = Scene:CreateObject(\"Name\")\nob.save = true\nob:AddScript(scriptAsset) -- a path string on 073, an Asset from 076\nScene:GetObjectByName(\"Name\")\nScene:CloneObject(ob) -- prefer over rebuilding\nob.active = false -- prefer over destroy; clients don't see it\nob:AddTag(\"Enemy\"); FindObjectsWithTag(\"Enemy\") -- tags are runtime-only state\n```\n\n### Voxel editing (server only, async)\n\n```lua\nVox:Add(Sphere(pos, 2)):Color(1, 0, 0):Run()\nVox:Add(Box(Vec3(0, -1, 0), Vec3(20, 2, 20))):ForceStatic():Run()\n```\n\nShapes: `Box(center, fullSize)`, `Sphere(center, r)`, `Capsule(p1, p2, r)`,\n`Cylinder(p1, p2, r1[, r2])`. `Run()` is async - chain `:OnFinished(fn)` before\n`:Run()` to read post-commit state. Big edits stall the frame for every client;\nkeep in-game edits small and infrequent.\n\n### Input (event-driven, client input reaches the server)\n\n```lua\nself.component.syncToClients = true\nevents.keyDown.addListener(self, function(key, from) self.keys[key] = true end)\nevents.keyUp.addListener(self, function(key, from) self.keys[key] = false end)\n```\n\nPlayer-driven movement must be client-predicted - never gate the player's own\nfeedback on the server round-trip.\n\n### Physics\n\n```lua\nlocal rb = obj:AddComponent(\"RigidBody\")\nrb:AddImpulse(Vec3(0, 50, 0), obj.pos)\nrb.velocity; rb.mass; rb.gravityScale\n```\n\n### Time and diagnostics\n\n```lua\nTime.dt; Time.time; Time.frame; Time.timeScale\nAE:GetLogValue(\"Raycasts\") -- engine counters, e.g. raycasts this frame\nAE:GetAssets() -- list all assets (APIs take Assets, not paths)\n```\n\n### UI (client-side HUD)\n\nBuild screen UI with the MUI builder: `UI:AddPanel|AddButton|AddLabel|AddSlider|...`\nchained with `:Set{...}`; flexbox-like row-wrap layout.\n\n### Engine behaviours that catch people out\n\nEach of these has broken a real game. An error inside a `util:schedule` chain or an\n`Update` stops that loop without anything else visible, so check `errors` after a\nchange even when the world looks fine.\n\n- Object names may hold only letters, digits and single spaces. `Scene:CreateObject`\n rejects `_`, `-`, `.` and leading or trailing spaces with \"Failed to create object.\n Given name was invalid.\"\n- `Cast:Ray` with a zero-length vector throws \"ray is zero length\". Guard every ray\n whose vector can be zero: coincident positions, a target standing on the shooter, a\n projectile at rest.\n- Client rays cannot read surfaces. `ForceStatic()` (on `Cast:Ray(...)` and\n `Collide(...)`), `WithNormal()`, `WithColor()` and `WithMaterial()` throw on a client\n (\"... only supported on server\"), and so does reading `hit.normal`, `hit.color` or\n `hit.material`; `hit.obj` is nil for every client hit. On a client, use a plain ray\n and skip dynamic objects with `Ignore`; read surfaces on the server and send what the\n client needs with the event (for example the impact material as an RPC argument). On\n the server, reading `hit.material` without `WithMaterial()` throws.\n- `Audio:PlaySound(asset, nil, ...)` throws, although the position is typed optional.\n Play a non-positional sound with `Audio:PlaySoundRelative(asset, Vec3(0,0,0), volume,\n false)`.\n- `obj.active = false` does not replicate. Clients keep the object active, frozen where\n it last streamed, with its client scripts running and any client-made meshes visible;\n an object created and deactivated in the same frame shows up at (0,0,0). To pool\n objects, also send a park position (a networked-table write in the same frame does\n arrive), move the object there on the client, and skip parked objects in client code.\n- A transform written in `LateUpdate` renders one frame behind the camera. Pose\n anything held against the camera (viewmodels, held items, camera-attached 3D) in\n `Update`, right after the camera moves.\n- Window z-order follows creation order and cannot be set: among `stayOnBottom`\n windows the earliest created draws on top, and toggling `visible` does not reorder\n them. Create windows in the order you want them stacked.\n- A `zNear` written right after `AddComponent(\"Camera\")` is reset to 0.1; write it\n again a frame later.\n- An RPC round trip (client -> server -> client) takes several times what\n `Client:GetPing()` reports (125-192 ms against 30 ms on a local connection), and\n networked tables reach clients at about 13-15 Hz. Measure the round trip your game\n sees with `AE:GetDebugTime()` before gating prediction on it.\n- The static edit guard's budget is per frame, not per op. About the 4th large op in\n one Lua call throws \"frame voxel budget exhausted\", leaving the earlier ops applied.\n Spread batches over frames and retry a refused op on the next frame, or a reset or\n map build leaves terrain half-edited.\n- Every static `Vox` op (Remove, Add, Paint) costs one 30-50 ms server frame whatever\n its size (55-85 ms in a test on iteration076, where `OpBase:Batch()` saved nothing\n on the server and delayed delivery). Prefer fewer, bigger ops and budget the rate:\n about 1 op/s keeps the p99 frame near 33 ms.\n- Static edits reach connected clients seconds to tens of seconds late, and a freshly\n joined client that is still streaming the map can wait 45 s or more. Gameplay must\n not depend on client terrain: hit checks, cover and validation belong on the server.\n- Client terrain rays are LOD-quantised in 0.125-0.25 m steps a few metres from the\n camera. Give client-side terrain checks a tolerance of 0.3 m or more, and use server\n rays for anything authoritative.\n- Setting `child.parent = obj` keeps the child's world transform. Set `localPos` and\n `localRot` after parenting, not before.\n- `Server:GetStreamingStats()` reports `STALLING` and `finalRatioPct = 0` for healthy\n clients too, so it cannot tell you a client has stopped receiving edits.\n- After a map-scale rebuild, the default `screenshot` (rendered by the server's own\n view) can show stale or missing terrain. Check with server rays or with\n `screenshot --client <id>` from a freshly connected client.\n\n### Worlds on iteration076\n\n`print(AE:GetVersion())` through `run-lua` tells you the engine build (76.x is\niteration076). A world moved from 073 keeps running code that 076 rejects, and the\n`pcall` guards games put around engine calls hide every one of these failures:\n\n- `receiveTransform` is a field of `Object` (`obj.receiveTransform = false`), not of\n `VoxelData`. On 076 `vd.receiveTransform` reads nil and writing it throws.\n- `Audio:PlaySound`, `Audio:PlaySoundRelative` and `Object:AddScript` take an Asset,\n not a path (\"expected a AudioFile Asset, got string\"). Resolve each path once and\n cache it: walk `AE:GetAssets()` and keep the asset for which\n `AE:AssetPathInMontage(asset) == path`. A client lists assets as they sync, so a\n lookup there can return nil for a while; retry instead of caching the nil.\n- There is no `Sky` component: `GetComponentByType(\"Sky\")` returns nil. On a client,\n hide the sky with `Client:SetSkyEnabled(false)`, aim the sun with\n `Client:SetSunDirection(azimuth, altitude)`, and turn off the god rays and lens flare\n (on by default) with `AE:SetLogValue(\"Dev/GodRays\", 0)` and\n `AE:SetLogValue(\"Dev/LensFlare\", 0)`. The SDK's `Sky` script turns the sky back on\n for each joining client; to keep it off, call that script's\n `queueSerializedRender(false)` on the server. A fog density above 0 turns VM Sky\n black.\n- Writing a field an engine object does not have throws, and `Widget:Set{...}` throws\n on an unknown key after applying the keys before it. While migrating, do not swallow\n these: keep the error from `pcall` and print it once\n (`local ok, err = pcall(f); if not ok then print(err) end`). Client `print` output\n does not reach the logs, so exercise client paths with\n `virtualmatter run-lua --target client` and return the error.\n- Edited copies of built-in shaders in `Shaders/` are kept as they are on every engine\n move (the boot log says \"maker edit - kept\"), even when the renderer's inputs have\n changed: the 076 `ssao2.fs` declares its own `FogFrame` block and no longer includes\n `common.glsl`. After a move, diff each kept copy against the new built-in, re-apply\n the edit, and check `Client:GetShaderErrors()` on a real client once it has drawn a\n frame. For a look change, prefer `Client:SetVPuzzleShaderDefines` (`#undef NAME` /\n `#define NAME value` lines, for example `CUSTOM_LIGHTING_MODE` or\n `CUSTOM_LIGHTING_MODE_LIGHTPOSTER`): it changes a client's shading without forking a\n shader, and recompiles every effect (about 100 ms) each time you call it.\n- The post-process chain runs in the live render on 076, whatever the engine's\n shaders skill says: depth of field, god rays, lens flare, tone mapping, outline,\n SSR and the SSAO composite (`ssao2.fs`). Switch them per client with\n `AE:SetLogValue`, for example `AE:SetLogValue(\"Dev/EnableDOF\", 1)` or\n `\"Dev/EnableToneMapping\"`. On 073 the chain is not wired and editing its shaders\n does nothing.\n\n### Generated sounds\n\n`Fal:requestTextToSound` returns takes that play quiet and thin: most of their energy\nsits below 20 Hz, with a DC offset and peaks around -25 dBFS. The engine's output\nalso removes most of what is below about 150 Hz and levels sounds by loudness, not\npeak. Before using a take, fetch the mp3 from `Sounds/Generated/`, clean it locally,\nand push it under a new name:\n\n```sh\nffmpeg -i take.mp3 -af \"highpass=f=40,loudnorm=I=-14:TP=-1\" -ac 1 -ar 44100 \"Clean Take.mp3\"\n```\n\nUse mono for one-shots, and match levels by loudness (LUFS), not by peak. A client\nthat has already played a sound keeps its old decoding until it reconnects, so give a\nreplacement a new file name. The generator may also change an asset name's case\n(`ScarGen Carbine 2b` comes back as `Scargen Carbine 2B`).\n\n## Conventions\n\n- Coordinates: Y is up, -Z is forward, X is right.\n- Script files are named in capital case with spaces (`Character Controller.lua`).\n- Check whether a script is already attached before adding it - duplicates run twice.\n- The server is for authority (world edits, spawns, state); clients are for feel\n (prediction, FX, UI).\n\n## Embed or build a world for an existing website\n\nFor a shared project link, fetch `/api/v1/public/embed?target=<encoded-link>`\nand follow `/embed-guide.md`. Use the returned canonical player URL, not the\nmaker's external website URL. Keep the existing website and its design.\n\nFor account discovery or prompt-based creation, connect the hosted MCP at\n`https://make.virtualmatter.ai/api/v1/mcp` using OAuth. Users can sign up in\nthe connection flow. Tools: `list_projects`, `get_embed`, `create_project`\n(with a prompt and stable request_id), `get_build_status`. VM's agent builds\nusing VM credits. Review and share the private world before embedding.\nThe local CLI exposes `embed`, `build --prompt --request-id`, and `build-status`.\n\n## Local conversation history\n\nCapturing this harness's conversation into the world's Agent Logs is the maker's\ndecision, not yours. Do not run `virtualmatter agent-logs setup`, and do not upload\nlogs with `agent-logs upload` or MCP `upload_agent_logs`, unless the maker asks for it\nin their own words. `virtualmatter agent-logs status` shows whether capture is on;\n`virtualmatter agent-logs disable` turns it off.\n";
@@ -0,0 +1,154 @@
1
+ /**
2
+ * The `voxelize` and `place` commands, apart from commander so their output
3
+ * and exit status can be tested. A requested placement that does not happen
4
+ * is a failure (exit 1) in human and --json output alike: scripts and agents
5
+ * read the exit status, and a world missing the objects it was asked for must
6
+ * not look like success.
7
+ */
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+ import { attachAsset, expandSources, findAsset, placeInWorld, voxelizeMany, voxelizeSource, } from "./assets.js";
11
+ export const defaultAssetDeps = (worldFor, engineFor) => ({ worldFor, engineFor, voxelizeSource, attachAsset, findAsset, placeInWorld });
12
+ export function humanSize(bytes) {
13
+ if (bytes >= 1024 * 1024 * 1024)
14
+ return `${(bytes / 1024 ** 3).toFixed(1)} GiB`;
15
+ if (bytes >= 1024 * 1024)
16
+ return `${(bytes / 1024 ** 2).toFixed(1)} MiB`;
17
+ return `${Math.max(1, Math.round(bytes / 1024))} kB`;
18
+ }
19
+ export function assetLine(a) {
20
+ const vpm = a.voxel_size_m ? `${Math.round(1 / a.voxel_size_m)} vpm` : "";
21
+ const size = a.size_bytes ? humanSize(a.size_bytes) : "";
22
+ return `${a.name} ${a.id} ${[vpm, size, a.status].filter(Boolean).join(" ")}`;
23
+ }
24
+ export function jobLine(job) {
25
+ return `${job.status}${job.progress_message ? `: ${job.progress_message}` : ""}${job.error_message ? ` (${job.error_message})` : ""}`;
26
+ }
27
+ /** "x,y,z" -> [x, y, z]; throws naming the flag otherwise. */
28
+ export function parseTriple(value, flag) {
29
+ const parts = value.split(",").map((p) => Number(p.trim()));
30
+ if (parts.length !== 3 || parts.some((n) => !Number.isFinite(n))) {
31
+ throw new Error(`${flag} takes three numbers, e.g. ${flag} 0,20,20`);
32
+ }
33
+ return [parts[0], parts[1], parts[2]];
34
+ }
35
+ export function voxelizeOptions(opts) {
36
+ const out = {};
37
+ if (opts.vpm !== undefined) {
38
+ const vpm = Number(opts.vpm);
39
+ if (!(vpm > 0))
40
+ throw new Error(`--vpm takes voxels per metre, e.g. 4 (got "${opts.vpm}")`);
41
+ out.voxelsPerMeter = vpm;
42
+ }
43
+ if (opts.scale !== undefined) {
44
+ if (opts.scale.toUpperCase() === "AUTO")
45
+ out.scale = "AUTO";
46
+ else {
47
+ const scale = Number(opts.scale);
48
+ if (!(scale > 0))
49
+ throw new Error(`--scale takes a number or AUTO (got "${opts.scale}")`);
50
+ out.scale = scale;
51
+ }
52
+ }
53
+ if (opts.method)
54
+ out.method = opts.method;
55
+ if (opts.name)
56
+ out.assetName = opts.name;
57
+ if (opts.rotate)
58
+ out.rotation = parseTriple(opts.rotate, "--rotate");
59
+ if (opts.shading === false)
60
+ out.applyShading = false;
61
+ return out;
62
+ }
63
+ /** `voxelize <sources...>`. Returns the exit code. */
64
+ export async function runVoxelize(rawSources, opts, io, deps) {
65
+ const place = opts.place ? parseTriple(opts.place, "--place") : undefined;
66
+ const attach = opts.attach || place !== undefined;
67
+ if (attach && opts.wait === false)
68
+ throw new Error("--attach and --place need the finished asset; drop --no-wait");
69
+ const sources = expandSources(rawSources.map((s) => (fs.existsSync(s) ? path.resolve(s) : s)));
70
+ if (opts.name && sources.length > 1)
71
+ throw new Error("--name names one asset; drop it when voxelizing several files");
72
+ const options = voxelizeOptions(opts);
73
+ // Resolve the world (and its engine) once, first: a bad --project fails before
74
+ // an hour of voxelizing, and every source lands in this same world.
75
+ const world = attach ? await deps.worldFor(opts.project) : null;
76
+ const engine = place && world ? await deps.engineFor(world) : null;
77
+ const label = (source) => path.basename(source);
78
+ const log = (line) => {
79
+ if (!opts.json)
80
+ io.err(line);
81
+ };
82
+ const results = await voxelizeMany(sources, async (source) => {
83
+ const voxelized = await deps.voxelizeSource(source, {
84
+ ...options,
85
+ wait: opts.wait,
86
+ onUploadProgress: (sent, total) => {
87
+ if (sent === total)
88
+ log(`${label(source)}: uploaded ${humanSize(total)}`);
89
+ },
90
+ onJobUpdate: (job) => log(`${label(source)}: ${jobLine(job)}`),
91
+ });
92
+ const out = { upload_id: voxelized.upload.id, job: voxelized.job, asset: voxelized.asset };
93
+ if (opts.wait === false)
94
+ return out;
95
+ if (voxelized.job.status !== "succeeded")
96
+ throw new Error(`voxelizing did not finish: ${jobLine(voxelized.job)}`);
97
+ if (!voxelized.asset)
98
+ throw new Error("the job succeeded but no asset is in your library yet; check `virtualmatter assets` in a minute");
99
+ if (world) {
100
+ await deps.attachAsset(world.montageId, voxelized.asset.id);
101
+ out.attached_to = world.name;
102
+ if (place && engine)
103
+ out.placed = await deps.placeInWorld(engine, voxelized.asset, { at: place });
104
+ }
105
+ return out;
106
+ });
107
+ const failedSource = (r) => Boolean(r.error) || r.result?.placed?.placed === false;
108
+ if (opts.json) {
109
+ const rows = results.map((r) => (r.error ? { source: r.source, error: r.error } : { source: r.source, ...r.result }));
110
+ io.out(JSON.stringify(sources.length === 1 ? rows[0] : rows, null, 2));
111
+ }
112
+ else {
113
+ for (const r of results) {
114
+ const out = r.result;
115
+ if (r.error || !out)
116
+ io.out(`${label(r.source)}: FAILED - ${r.error}`);
117
+ else if (opts.wait === false)
118
+ io.out(`${label(r.source)}: queued job ${out.job.id} (follow it: npx virtualmatter jobs ${out.job.id} --wait)`);
119
+ else {
120
+ const placed = out.placed ? (out.placed.placed ? `, placed as "${out.placed.object}"` : `, NOT placed: ${out.placed.reason}`) : "";
121
+ io.out(`${label(r.source)}: ${assetLine(out.asset)}${world ? `, attached to ${world.name}` : ""}${placed}`);
122
+ }
123
+ }
124
+ }
125
+ const failed = results.filter(failedSource).length;
126
+ if (failed) {
127
+ io.err(`${failed} of ${results.length} failed.`);
128
+ return 1;
129
+ }
130
+ return 0;
131
+ }
132
+ /** `place <asset>`. Returns the exit code. */
133
+ export async function runPlace(ref, opts, io, deps) {
134
+ const at = opts.at ? parseTriple(opts.at, "--at") : undefined;
135
+ const world = await deps.worldFor(opts.project);
136
+ const engine = await deps.engineFor(world);
137
+ const asset = await deps.findAsset(ref);
138
+ await deps.attachAsset(world.montageId, asset.id);
139
+ const result = await deps.placeInWorld(engine, asset, {
140
+ at,
141
+ yawDeg: opts.yaw !== undefined ? Number(opts.yaw) : undefined,
142
+ scale: opts.scale !== undefined ? Number(opts.scale) : undefined,
143
+ name: opts.name,
144
+ });
145
+ if (opts.json)
146
+ io.out(JSON.stringify(result, null, 2));
147
+ else if (result.placed)
148
+ io.out(`Placed "${result.object}" (${result.file}) in ${world.name}`);
149
+ if (!result.placed) {
150
+ io.err(`Not placed: ${result.reason}`);
151
+ return 1;
152
+ }
153
+ return 0;
154
+ }