virtualmatter 0.6.5 → 0.6.8

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
@@ -46,8 +46,28 @@ was stopped go out when it starts again.
46
46
 
47
47
  Large voxel and terrain files (several GB is normal) are streamed to disk,
48
48
  never loaded into memory. Sync does not push a file over 8 MB, the most the
49
- world accepts in one write. It warns once and leaves that file as it is on
50
- both sides.
49
+ world accepts in one write, and it does not pull one either: it cannot keep
50
+ such a file in step, and re-downloading a terrain on every engine save
51
+ competes with the world. It says once that the file changed;
52
+ `npx virtualmatter fetch <path>` downloads it (or run `sync --include-large`).
53
+
54
+ One sync runs per folder. Starting a second one stops the first, and sync
55
+ stops when the process that started it exits (`--keep-alive` keeps it running
56
+ detached). If the world's session moves (an engine restart), sync follows it;
57
+ if the session refuses it for good, sync exits with an error rather than keep
58
+ running while nothing it pushes arrives.
59
+
60
+ Deploying from a script or an agent? `push` is the one-shot alternative to a
61
+ running sync:
62
+
63
+ ```bash
64
+ npx virtualmatter push Scripts/Game.lua Scripts/UI.lua
65
+ ```
66
+
67
+ It reports each file as `pushed`, `unchanged` (nothing sent, so no Lua reset),
68
+ `conflict`, `too-large`, `missing` or `failed`, and exits 1 unless every file
69
+ was pushed or unchanged. `fetch [paths...]` is the matching download; neither
70
+ ever overwrites unsynced work.
51
71
 
52
72
  `make`, `pull` and `sync` print the world's editor link ending in `?chat=closed`.
53
73
  Open it in any browser to watch changes land live - no install needed.
@@ -113,7 +133,10 @@ It works before a world is selected: `list_projects`, `create_project`, and
113
133
  `select_project` (any link or id, optionally mirroring into a folder) pick
114
134
  one, then `list_files`, `read_file`, `write_file`, `run_lua`,
115
135
  `get_engine_errors`, `capture_screenshot`, `open_native_client`, and
116
- `world_info` act on it. Writes handle etag concurrency internally, and
136
+ `world_info` act on it. `patch_file` edits a world file by replacing one
137
+ exact snippet, and `push_local_files` / `fetch_files` move files between the
138
+ world and the synced folder the server runs in, so big scripts never travel
139
+ through the conversation. Writes handle etag concurrency internally, and
117
140
  written Lua hot-reloads in the engine - so for an agent, writing a script is
118
141
  deploying it.
119
142
 
@@ -124,11 +147,16 @@ deploying it.
124
147
  | `make <name> [dir]` (`create`) | Make a world (region defaults to the nearest; `--region`, `--track`, `--description`, `--no-pull`, `--open`, `--json`) and mirror it into `./<slug>`. |
125
148
  | `list` (`ls`, `projects`) | Your worlds with framing ids and edit/play URLs (`--json`). |
126
149
  | `pull [target] [dir]` | Mirror a world's file tree. `target` is any link to the world (or your website) or a framing id, and always resolves to the world's editor; omitted, it uses this folder's world or your only one. Also writes the harness files: `AGENTS.md`, `CLAUDE.md`, MCP registrations, the world's skill packages copied into `.claude/skills/`, and (macOS, Linux) an executable `./atomo`. |
127
- | `sync [dir]` | Watch + two-way sync with the live session. Ctrl-C to stop. Refreshes `AGENTS.md` and `.claude/skills/` whenever the world's `Skills/` changes. |
150
+ | `sync [dir]` | Watch + two-way sync with the live session. Ctrl-C to stop. Refreshes `AGENTS.md` and `.claude/skills/` whenever the world's `Skills/` changes. Does not pull files over 8 MB (`--include-large` does); stops with the process that started it (`--keep-alive` does not). |
151
+ | `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
+ | `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
+ | `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. |
128
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`. |
129
157
  | `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. |
130
- | `errors [dir]` | Recent engine errors. Retried twice when the engine is busy or briefly unreachable, since it only reads. |
131
- | `atomo [--dir <dir>] -- <command> ...` | The engine SDK's `atomo` commands (`run-lua`, `run-lua-client [id]`, `errors`) in atomo's own output format, for tools written against atomo such as the starter builder. The folder's `./atomo` calls this; a bridge timeout exits 3. |
158
+ | `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
+ | `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. |
132
160
  | `screenshot [dir] [-o out.png] [--client <id>]` | Capture the engine's view; `--client` captures through a connected client, UI included. |
133
161
  | `mcp [dir] [--framing <id>]` | Run the stdio MCP server. |
134
162
  | `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. |
@@ -148,7 +176,10 @@ deploying it.
148
176
  harness files the CLI writes (`AGENTS.md`, `CLAUDE.md`, `.mcp.json`,
149
177
  `.cursor/`, `.codex/`, `.virtualmatter.json`), and the SDK's in-session tooling at the
150
178
  Montage root (`atomo`, `vm_auth.py`, the agent-log hooks) - those only work
151
- inside a running session.
179
+ inside a running session. It also skips files that exist only mid-write:
180
+ its own `*.vmdownload-*` download temps (a run that was killed leaves them;
181
+ the next sync removes them) and anything ending in `~`, such as the
182
+ engine's `<name>.am~` save temp.
152
183
  - The pulled `AGENTS.md` is the platform guide followed by the world's own
153
184
  engine SDK guide (its Skills/ table and engine rules), with a header that
154
185
  maps every `atomo` command the engine guide mentions to the CLI or MCP
@@ -66,6 +66,12 @@ export function enqueue(dir, harness, session, events) {
66
66
  let queued = 0;
67
67
  let batch = [];
68
68
  let size = 0;
69
+ // Upload order comes from this persisted counter, not file mtimes: one
70
+ // capture writes its batches within a millisecond or two, and on a
71
+ // filesystem with coarse timestamps they tie, leaving readdir order to
72
+ // decide which half of a conversation reaches the world first.
73
+ const seqFile = path.join(logDir(dir), "seq.json");
74
+ let nextSeq = Number(readJson(seqFile)?.next) || 0;
69
75
  const commit = () => {
70
76
  if (!batch.length)
71
77
  return;
@@ -81,7 +87,9 @@ export function enqueue(dir, harness, session, events) {
81
87
  const root = logDir(dir);
82
88
  if (!fs.existsSync(path.join(root, "receipts", id)) &&
83
89
  !fs.existsSync(path.join(root, "pending", id + ".json"))) {
84
- writeJson(path.join(root, "pending", id + ".json"), envelope);
90
+ const pending = { ...envelope, seq: nextSeq++ };
91
+ writeJson(seqFile, { next: nextSeq });
92
+ writeJson(path.join(root, "pending", id + ".json"), pending);
85
93
  queued += batch.length;
86
94
  }
87
95
  batch = [];
@@ -164,20 +172,40 @@ async function flushUnlocked(dir, send) {
164
172
  const root = logDir(dir), pending = path.join(root, "pending");
165
173
  if (!fs.existsSync(pending))
166
174
  return 0;
175
+ // Queue order: `seq`, then mtime, then name. A batch queued before `seq`
176
+ // existed sorts first, since it is older than any batch that has one.
167
177
  const files = fs
168
178
  .readdirSync(pending)
169
179
  .filter((f) => f.endsWith(".json"))
170
- .sort((a, b) => fs.statSync(path.join(pending, a)).mtimeMs -
171
- fs.statSync(path.join(pending, b)).mtimeMs);
180
+ .map((name) => {
181
+ const file = path.join(pending, name);
182
+ let seq = -1;
183
+ let mtime = 0;
184
+ try {
185
+ const n = Number(readJson(file)?.seq);
186
+ if (Number.isFinite(n))
187
+ seq = n;
188
+ mtime = fs.statSync(file).mtimeMs;
189
+ }
190
+ catch {
191
+ /* acknowledged by another flusher, or unreadable: the loop decides */
192
+ }
193
+ return { name, seq, mtime };
194
+ })
195
+ .sort((a, b) => a.seq - b.seq ||
196
+ a.mtime - b.mtime ||
197
+ (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
198
+ .map((f) => f.name);
172
199
  if (!files.length)
173
200
  return 0;
174
201
  let base;
175
202
  let sent = 0;
176
203
  for (const name of files) {
177
204
  const file = path.join(pending, name);
178
- const e = readJson(file);
179
- if (!e)
205
+ const stored = readJson(file);
206
+ if (!stored)
180
207
  continue; // another flushing process already acknowledged it
208
+ const { seq: _seq, ...e } = stored;
181
209
  if (e.version !== 1 ||
182
210
  e.api !== apiBase() ||
183
211
  e.framing !== requireState(dir).framing_id)
@@ -114,10 +114,10 @@ call them (the starters' \`starterctl.py\`). Everything else maps to the
114
114
  | --- | --- |
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
- | \`atomo errors\` | \`./atomo errors\`, or \`npx virtualmatter errors\` (MCP: \`get_engine_errors\`) |
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
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 |
119
119
  | \`atomo prints\` / \`atomo status\` | not available locally; use \`return\` values from run-lua |
120
- | edit a .lua file, then check \`atomo errors\` | save the file with \`npx virtualmatter sync\` running (or MCP \`write_file\`), then check errors the same way |
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 |
122
122
  | paths under \`/data/persist/Montage/\` | this folder |
123
123
 
@@ -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);\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- 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- 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 run_lua, get_engine_errors, capture_screenshot, open_native_client,\n 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## 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`, 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";
package/dist/atomo.js CHANGED
@@ -9,9 +9,25 @@
9
9
  * (`atomo_cli.py`: `_print_run_lua_payload`, `cmd_errors`), so those tools
10
10
  * parse it unchanged. `pull` writes a `./atomo` wrapper that calls this.
11
11
  */
12
+ import crypto from "node:crypto";
12
13
  import fs from "node:fs";
14
+ import os from "node:os";
13
15
  import path from "node:path";
14
16
  import { EngineTimeoutError } from "./files.js";
17
+ /**
18
+ * atomo's exit status for run-lua, run-lua-client and errors (atomo_cli.py's
19
+ * EXIT_*): a harness marks a non-zero exit as a failed tool call, so a Lua
20
+ * error no longer passes as success with the error only in the text.
21
+ */
22
+ export const ATOMO_EXIT = {
23
+ ok: 0,
24
+ /** run-lua: the snippet raised. errors: an error no earlier check reported. */
25
+ luaError: 1,
26
+ /** Nothing ran: usage, unreachable engine, refused call. Safe to retry once fixed. */
27
+ notRun: 2,
28
+ /** The engine may still be running it (504): check before sending it again. */
29
+ outcomeUnknown: 3,
30
+ };
15
31
  const CLI_EQUIVALENTS = {
16
32
  screenshot: "npx virtualmatter screenshot -o shot.png (aim with --at/--rot or --target)",
17
33
  "screenshot-at": "npx virtualmatter screenshot --at x,y,z -o shot.png",
@@ -47,54 +63,321 @@ export function printRunLuaPayload(output, out) {
47
63
  lines.forEach((line, i) => write(label && i === 0 ? `[${name}] ${line}` : line));
48
64
  }
49
65
  }
50
- /** atomo's errors printing: one labelled stderr line per error, nothing when clean. */
51
- export function printErrors(output, out) {
66
+ /** atomo's exit status for a printed run-lua answer (atomo_cli.py's `_run_lua_status`). */
67
+ export function runLuaStatus(output) {
52
68
  let data;
53
69
  try {
54
70
  data = JSON.parse(output);
55
71
  }
56
72
  catch {
57
- out.stdout(output);
58
- return;
73
+ data = undefined;
59
74
  }
60
- if (!data || typeof data !== "object" || Array.isArray(data)) {
61
- out.stdout(output);
62
- return;
75
+ if (data && typeof data === "object" && !Array.isArray(data)) {
76
+ const errors = Array.isArray(data.error)
77
+ ? data.error.map(String)
78
+ : [];
79
+ if (errors.length === 0)
80
+ return ATOMO_EXIT.ok;
81
+ // the engine had no Lua state yet (loading): the snippet never ran
82
+ if (errors.every((e) => e.startsWith("Error: no lua state")))
83
+ return ATOMO_EXIT.notRun;
84
+ return ATOMO_EXIT.luaError;
63
85
  }
86
+ const text = output.trim();
87
+ // a call relayed between server and client that the other side did not answer in time
88
+ if (/^Error: timeout waiting for (server|client)/.test(text))
89
+ return ATOMO_EXIT.outcomeUnknown;
90
+ if (text.startsWith("Error:"))
91
+ return ATOMO_EXIT.notRun;
92
+ return ATOMO_EXIT.ok;
93
+ }
94
+ /** The engine's error lists, or null when the answer is not the expected JSON. */
95
+ function errorLists(output) {
96
+ let data;
97
+ try {
98
+ data = JSON.parse(output);
99
+ }
100
+ catch {
101
+ return null;
102
+ }
103
+ if (!data || typeof data !== "object" || Array.isArray(data))
104
+ return null;
64
105
  const record = data;
65
106
  const list = (key) => (Array.isArray(record[key]) ? record[key].map(String) : []);
66
- for (const err of list("server_errors"))
107
+ return { server: list("server_errors"), client: list("client_errors") };
108
+ }
109
+ /** atomo's errors printing: one labelled stderr line per error, nothing when clean. */
110
+ export function printErrors(output, out) {
111
+ const lists = errorLists(output);
112
+ if (!lists) {
113
+ out.stdout(output);
114
+ return;
115
+ }
116
+ for (const err of lists.server)
67
117
  out.stderr(`[SERVER ERROR] ${err}`);
68
- for (const err of list("client_errors"))
118
+ for (const err of lists.client)
69
119
  out.stderr(`[CLIENT ERROR] ${err}`);
70
120
  }
71
- /** Run one atomo command; returns the exit code. */
72
- export async function runAtomo(client, argv, out) {
121
+ /**
122
+ * How the engine shows that a script save took effect (atomo_cli.py has the
123
+ * full note). Every .lua save makes the server rebuild its Lua state 0.2 s
124
+ * after the last change it saw, and that rebuild is the only thing that
125
+ * resets Time.frame / Time.time; Time.appFrame / Time.appTime keep counting.
126
+ * `Time.appFrame - Time.frame` is the frame the running state was born in.
127
+ */
128
+ const LUA_STATE_PROBE = "local ok, n = pcall(function() return #Server:GetClients() end) " +
129
+ "return Time.appFrame - Time.frame, Time.frame, Time.time, Time.appTime, Time.appFrame, ok and n or 0";
130
+ const AFTER_RELOAD_TIMEOUT_S = 10;
131
+ const RELOAD_DEBOUNCE_S = 0.2;
132
+ const RELOAD_POLL_MS = 100;
133
+ const START_FRAMES = 3;
134
+ const CLIENT_RELOAD_GRACE_S = 1;
135
+ function parseLuaState(output, answered) {
136
+ try {
137
+ const values = JSON.parse(String(output ?? "")).result ?? [];
138
+ const n = (i) => {
139
+ const v = Number(values[i]);
140
+ if (!Number.isFinite(v))
141
+ throw new Error("not a number");
142
+ return v;
143
+ };
144
+ return {
145
+ id: String(values[0]),
146
+ frame: n(1),
147
+ age: n(2),
148
+ appTime: n(3),
149
+ appFrame: n(4),
150
+ clients: n(5),
151
+ answered,
152
+ };
153
+ }
154
+ catch {
155
+ return null;
156
+ }
157
+ }
158
+ async function probeLuaState(client, now) {
159
+ const output = await client.runLua(LUA_STATE_PROBE, "server");
160
+ return parseLuaState(output, now());
161
+ }
162
+ /** Default record location: one per world, in the OS temp dir. */
163
+ export function defaultErrorsStateFile(key) {
164
+ const hash = crypto.createHash("sha1").update(key).digest("hex").slice(0, 12);
165
+ return path.join(os.tmpdir(), `virtualmatter-atomo-errors-${hash}.json`);
166
+ }
167
+ /**
168
+ * How many of `entries` the previous `errors` did not report. The engine
169
+ * keeps every error until its Lua state is rebuilt and reading does not
170
+ * clear it; a repeat of a known error raises its "(count)", which changes
171
+ * the text. A rebuilt Lua state (new id) starts over.
172
+ */
173
+ export function countNewErrors(stateFile, luaStateId, entries) {
174
+ const current = entries.map((e) => crypto.createHash("sha1").update(e).digest("hex").slice(0, 16));
175
+ if (!stateFile)
176
+ return current.length;
177
+ let previous = {};
178
+ try {
179
+ const parsed = JSON.parse(fs.readFileSync(stateFile, "utf8"));
180
+ if (parsed && typeof parsed === "object")
181
+ previous = parsed;
182
+ }
183
+ catch {
184
+ previous = {};
185
+ }
186
+ const id = luaStateId ?? previous.lua_state ?? null;
187
+ const seen = new Set(previous.lua_state === id && Array.isArray(previous.seen) ? previous.seen : []);
188
+ const fresh = current.filter((h) => !seen.has(h)).length;
189
+ try {
190
+ const tmp = `${stateFile}.${process.pid}.tmp`;
191
+ fs.writeFileSync(tmp, JSON.stringify({ lua_state: id, seen: current, at: Date.now() / 1000 }));
192
+ fs.renameSync(tmp, stateFile);
193
+ }
194
+ catch {
195
+ /* without the record every error counts as new: louder, never silent */
196
+ }
197
+ return fresh;
198
+ }
199
+ /**
200
+ * Wait until the world runs `files` as they are on disk here: first until
201
+ * `sync` has pushed them (the world's copy matches), then until the server's
202
+ * Lua state was rebuilt after that and its Start() has run. Same rules as
203
+ * atomo_cli.py's `_wait_for_reload`, with "saved" meaning "landed in the world".
204
+ */
205
+ async function waitForReload(client, files, timeoutS, out, opts) {
206
+ const now = opts.now ?? (() => Date.now() / 1000);
207
+ const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
208
+ const dir = path.resolve(opts.dir ?? ".");
209
+ const started = now();
210
+ const deadline = started + timeoutS;
211
+ const targets = [];
212
+ for (const arg of files) {
213
+ const abs = [path.resolve(arg), path.resolve(dir, arg)].find((p) => fs.existsSync(p) && fs.statSync(p).isFile());
214
+ const remote = abs === undefined ? "" : path.relative(dir, abs).split(path.sep).join("/");
215
+ if (abs === undefined || remote.startsWith("../") || path.isAbsolute(remote)) {
216
+ out.stderr(`Error: --after-reload: no such file in this synced folder: ${arg}`);
217
+ return { status: ATOMO_EXIT.notRun, state: null };
218
+ }
219
+ targets.push({ arg, remote, bytes: fs.readFileSync(abs) });
220
+ }
221
+ if (!targets.some((t) => t.remote.toLowerCase().endsWith(".lua"))) {
222
+ out.stderr("Note: --after-reload waits for .lua saves only; checking errors now.");
223
+ return { status: ATOMO_EXIT.ok, state: await probeLuaState(client, now) };
224
+ }
225
+ // 1. The world's copy: `sync` pushes a save within a few seconds.
226
+ let lastMismatchSent = null;
227
+ for (const t of targets) {
228
+ for (;;) {
229
+ const sent = now();
230
+ let same = false;
231
+ try {
232
+ same = (await client.get(t.remote)).bytes.equals(t.bytes);
233
+ }
234
+ catch {
235
+ same = false; // not created in the world yet
236
+ }
237
+ if (same)
238
+ break;
239
+ lastMismatchSent = sent;
240
+ if (now() >= deadline) {
241
+ out.stderr(`Error: --after-reload: the world still has an older ${t.remote}. Is \`npx virtualmatter sync\` running? ` +
242
+ `(\`npx virtualmatter push ${t.remote}\` sends it once.)`);
243
+ return { status: ATOMO_EXIT.notRun, state: null };
244
+ }
245
+ await sleep(RELOAD_POLL_MS);
246
+ }
247
+ }
248
+ // 2. The rebuild that followed it.
249
+ let first = null;
250
+ let last = null;
251
+ let bornBeforeWrite = false;
252
+ for (;;) {
253
+ let state = null;
254
+ try {
255
+ state = await probeLuaState(client, now);
256
+ }
257
+ catch (err) {
258
+ // A read-only probe is safe to repeat while a big world rebuilds (504);
259
+ // anything else before the first answer is final.
260
+ if (!(err instanceof EngineTimeoutError) && last === null)
261
+ throw err;
262
+ }
263
+ if (state) {
264
+ last = state;
265
+ if (!first) {
266
+ first = state;
267
+ // Only provable when we saw the old copy: the write came after that read.
268
+ bornBeforeWrite = lastMismatchSent !== null && state.answered - state.age < lastMismatchSent;
269
+ }
270
+ const reloaded = state.id !== first.id;
271
+ let settled = false;
272
+ if (!reloaded) {
273
+ const frames = state.appFrame - first.appFrame;
274
+ const elapsed = state.appTime - first.appTime;
275
+ const frameS = frames > 0 ? elapsed / frames : 0;
276
+ settled = frames >= 4 && elapsed >= RELOAD_DEBOUNCE_S + 3 * frameS + 0.05;
277
+ if (settled && bornBeforeWrite) {
278
+ out.stderr(`Error: --after-reload: the engine has not reloaded Lua since ${targets[targets.length - 1].remote} reached the world. ` +
279
+ "Save the file again; if that does not help, the world may need a restart.");
280
+ return { status: ATOMO_EXIT.notRun, state };
281
+ }
282
+ }
283
+ if ((reloaded || settled) && state.frame >= START_FRAMES && (state.clients === 0 || state.age >= CLIENT_RELOAD_GRACE_S)) {
284
+ out.stdout(`Lua reload confirmed for ${files.join(", ")} (${(now() - started).toFixed(1)}s).`);
285
+ return { status: ATOMO_EXIT.ok, state };
286
+ }
287
+ }
288
+ if (now() >= deadline) {
289
+ out.stderr(`Error: --after-reload: could not confirm a Lua reload within ${timeoutS}s (the engine did not answer or did not advance). ` +
290
+ "The errors below may predate the edit.");
291
+ return { status: ATOMO_EXIT.notRun, state: last };
292
+ }
293
+ await sleep(RELOAD_POLL_MS);
294
+ }
295
+ }
296
+ const ERRORS_USAGE = "Usage: atomo errors [--after-reload <file> [<file> ...]] [--timeout <seconds>]";
297
+ function parseErrorsArgs(args) {
298
+ const files = [];
299
+ let timeout = AFTER_RELOAD_TIMEOUT_S;
300
+ for (let i = 0; i < args.length;) {
301
+ if (args[i] === "--after-reload") {
302
+ const start = ++i;
303
+ while (i < args.length && !args[i].startsWith("--"))
304
+ files.push(args[i++]);
305
+ if (i === start)
306
+ return null;
307
+ }
308
+ else if (args[i] === "--timeout" && i + 1 < args.length) {
309
+ timeout = Number(args[i + 1]);
310
+ if (!(timeout > 0))
311
+ return null;
312
+ i += 2;
313
+ }
314
+ else {
315
+ return null;
316
+ }
317
+ }
318
+ return { files, timeout };
319
+ }
320
+ async function runErrors(client, args, out, opts) {
321
+ const parsed = parseErrorsArgs(args);
322
+ if (!parsed) {
323
+ out.stderr(ERRORS_USAGE);
324
+ return ATOMO_EXIT.notRun;
325
+ }
326
+ let reloadStatus = ATOMO_EXIT.ok;
327
+ let state;
328
+ if (parsed.files.length > 0) {
329
+ const waited = await waitForReload(client, parsed.files, parsed.timeout, out, opts);
330
+ reloadStatus = waited.status;
331
+ state = waited.state;
332
+ if (reloadStatus !== ATOMO_EXIT.ok && state === null)
333
+ return reloadStatus;
334
+ }
335
+ else {
336
+ // before reading the buffer, so a rebuild in between can only make the
337
+ // next check report an error twice, never skip one
338
+ state = await probeLuaState(client, opts.now ?? (() => Date.now() / 1000));
339
+ }
340
+ const output = String((await client.engineErrors()) ?? "");
341
+ const lists = errorLists(output);
342
+ if (!lists) {
343
+ out.stdout(output);
344
+ return ATOMO_EXIT.notRun;
345
+ }
346
+ printErrors(output, out);
347
+ const entries = [...lists.server.map((e) => `server\n${e}`), ...lists.client.map((e) => `client\n${e}`)];
348
+ const fresh = countNewErrors(opts.stateFile, state?.id ?? null, entries);
349
+ if (reloadStatus !== ATOMO_EXIT.ok)
350
+ return reloadStatus;
351
+ return fresh > 0 ? ATOMO_EXIT.luaError : ATOMO_EXIT.ok;
352
+ }
353
+ /** Run one atomo command; returns atomo's exit status (ATOMO_EXIT). */
354
+ export async function runAtomo(client, argv, out, opts = {}) {
73
355
  const [command, ...args] = argv;
74
356
  try {
75
357
  if (command === "run-lua") {
76
358
  if (args.length < 1) {
77
359
  out.stderr("Usage: atomo run-lua '<lua code>'");
78
- return 2;
360
+ return ATOMO_EXIT.notRun;
79
361
  }
80
- printRunLuaPayload(String((await client.runLua(args[0], "server")) ?? ""), out);
81
- return 0;
362
+ const output = String((await client.runLua(args[0], "server")) ?? "");
363
+ printRunLuaPayload(output, out);
364
+ return runLuaStatus(output);
82
365
  }
83
366
  if (command === "run-lua-client") {
84
367
  if (args.length < 1) {
85
368
  out.stderr("Usage: atomo run-lua-client [client_id] '<lua code>'");
86
- return 2;
369
+ return ATOMO_EXIT.notRun;
87
370
  }
88
371
  // atomo's own optional leading integer client id
89
372
  const withId = args.length >= 2 && /^\d+$/.test(args[0]);
90
373
  const clientId = withId ? Number(args[0]) : undefined;
91
374
  const code = withId ? args[1] : args[0];
92
- printRunLuaPayload(String((await client.runLua(code, "client", clientId)) ?? ""), out);
93
- return 0;
375
+ const output = String((await client.runLua(code, "client", clientId)) ?? "");
376
+ printRunLuaPayload(output, out);
377
+ return runLuaStatus(output);
94
378
  }
95
379
  if (command === "errors") {
96
- printErrors(String((await client.engineErrors()) ?? ""), out);
97
- return 0;
380
+ return await runErrors(client, args, out, opts);
98
381
  }
99
382
  }
100
383
  catch (err) {
@@ -102,17 +385,18 @@ export async function runAtomo(client, argv, out) {
102
385
  // atomo's wording for a bridge timeout, which callers treat as
103
386
  // "outcome unknown: check, never resend".
104
387
  out.stderr(`Error: bridge returned HTTP 504: ${err.message}`);
105
- return 3;
388
+ return ATOMO_EXIT.outcomeUnknown;
106
389
  }
390
+ // the request never reached the engine, or the session refused it
107
391
  out.stderr(`Error: ${err instanceof Error ? err.message : String(err)}`);
108
- return 1;
392
+ return ATOMO_EXIT.notRun;
109
393
  }
110
394
  const instead = command ? CLI_EQUIVALENTS[command] : undefined;
111
395
  out.stderr(command
112
396
  ? `atomo ${command} is not available outside a Virtual Matter session.` +
113
397
  (instead ? ` Use instead: ${instead}` : "")
114
- : "Usage: atomo run-lua '<code>' | run-lua-client [client_id] '<code>' | errors");
115
- return 2;
398
+ : "Usage: atomo run-lua '<code>' | run-lua-client [client_id] '<code>' | errors [--after-reload <file>...]");
399
+ return ATOMO_EXIT.notRun;
116
400
  }
117
401
  /** Single-quote a string for /bin/sh. */
118
402
  function shQuote(value) {