virtualmatter 0.8.0 → 0.10.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 +15 -1
- package/dist/admin.js +167 -0
- package/dist/agents-md.generated.js +1 -1
- package/dist/asset-commands.js +8 -0
- package/dist/assets.js +75 -1
- package/dist/index.js +14 -4
- package/dist/mcp.js +44 -1
- package/dist/server-lifecycle.js +410 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -106,6 +106,7 @@ npx virtualmatter screenshot --depth -o st.png # + st.depth.npy (metr
|
|
|
106
106
|
```bash
|
|
107
107
|
npx virtualmatter voxelize tower.glb --vpm 32 --place 0,0,0 # one model into the world
|
|
108
108
|
npx virtualmatter voxelize tiles/ --vpm 2 --place -1000,0,-1000 # a folder of map tiles
|
|
109
|
+
npx virtualmatter voxelize scan.zip --vpm 128 --place 0,0,0 # a zip of slice images (CT, MRI) as one volume
|
|
109
110
|
npx virtualmatter assets # your asset library
|
|
110
111
|
npx virtualmatter place "tower" --at 20,0,5 --yaw 90 # place a library asset again
|
|
111
112
|
npx virtualmatter jobs <job id> --wait # follow a --no-wait job
|
|
@@ -122,6 +123,17 @@ metre (a power of two; 2-4 for buildings and terrain, 32-128 for props),
|
|
|
122
123
|
`--method RayCast` suits open meshes such as terrain, and `--rotate -90,0,0`
|
|
123
124
|
stands a Z-up model upright.
|
|
124
125
|
|
|
126
|
+
A zip that holds only images, or a `stack.json`, is voxelized as an image
|
|
127
|
+
stack: the slices in name order become one solid volume, one pixel per voxel,
|
|
128
|
+
solid where the pixel is brighter than `--threshold` (default 0.5). `stack.json`
|
|
129
|
+
at the zip's root splits it into layers, each a folder of slices with its own
|
|
130
|
+
threshold and either one colour or a folder of colour slices:
|
|
131
|
+
`{"layers": [{"images": "bone", "threshold": 0.5, "color": [244, 235, 221]},
|
|
132
|
+
{"images": "muscle", "colorImages": "muscle_rgb"}], "size": [512, 512, 400]}`.
|
|
133
|
+
`size` resamples the stack (for slices spaced wider than their pixels), and
|
|
134
|
+
`transformation` (three rows) reorients it. Voxelize one zip per part you want
|
|
135
|
+
to show and hide on its own, and place them at the same position.
|
|
136
|
+
|
|
125
137
|
## If you are a coding agent, read this part
|
|
126
138
|
|
|
127
139
|
Build through these commands, always. Do not open virtualmatter.ai or
|
|
@@ -163,7 +175,7 @@ It works before a world is selected: `list_projects`, `create_project`, and
|
|
|
163
175
|
`select_project` (any link or id, optionally mirroring into a folder) pick
|
|
164
176
|
one, then `list_files`, `read_file`, `write_file`, `run_lua`,
|
|
165
177
|
`get_engine_errors`, `capture_screenshot`, `open_native_client`, and
|
|
166
|
-
`world_info` act on it. `voxelize_model`, `get_voxelize_job`, `list_assets`
|
|
178
|
+
`world_info` act on it. `restart_server`, `stop_server`, `start_server` and `server_status` control and read the editor server (same behaviour and exit codes as the commands; `server_status` never starts a stopped server). For platform admins, `admin_list_worlds` and `admin_get` read across every account (read-only). `voxelize_model`, `get_voxelize_job`, `list_assets`
|
|
167
179
|
and `place_asset` bring 3D files from disk into the world as voxel assets. `patch_file` edits a world file by replacing one
|
|
168
180
|
exact snippet, and `push_local_files` / `fetch_files` move files between the
|
|
169
181
|
world and the synced folder the server runs in, so big scripts never travel
|
|
@@ -189,6 +201,8 @@ deploying it.
|
|
|
189
201
|
| `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. |
|
|
190
202
|
| `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. |
|
|
191
203
|
| `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). |
|
|
204
|
+
| `restart\|stop\|start [target]` | The world's editor server, by a synced folder or any world link. `restart` is the web editor's Restart button: a clean engine process, which is what returns memory. It lets the engine save first (`--force` skips that for a stuck engine), then waits until the engine answers Lua and prints the seconds taken and `Server:GetMemoryUsage()` (`--no-wait`, `--timeout <s>`, default 900). `stop` leaves it stopped until someone opens the world or runs `start`. `start --reset-terrain` recovers a world stopped for running out of memory by swapping its terrain for an empty grid. Asks before disconnecting connected clients (`--yes` to skip; refused when not on a terminal). Never touches play servers. Owner only. Exit 0 done, 1 failed, 2 nothing done, 3 sent but outcome unknown. `--json` for a result object. |
|
|
205
|
+
| `admin worlds\|users\|get <path>` | Platform admins only, read-only. `admin worlds [--search] [--owner]` lists every account's worlds with owner and edit/play links; `admin users [--search]` lists accounts; `admin get <path> [--query key=value]` prints any admin API read as JSON (`framings`, `sessions`, `hosts`). All take `--json` where a table is the default. A maker account gets a clear "not an admin" error. |
|
|
192
206
|
| `mcp [dir] [--framing <id>]` | Run the stdio MCP server. |
|
|
193
207
|
| `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. |
|
|
194
208
|
|
package/dist/admin.js
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { authorizedFetch, editUrl, playUrl } from "./api.js";
|
|
2
|
+
import { apiBase } from "./config.js";
|
|
3
|
+
const ADMIN_PREFIX = "/api/v1/admin/";
|
|
4
|
+
export class NotAdminError extends Error {
|
|
5
|
+
constructor(status) {
|
|
6
|
+
super(`This account is not a Virtual Matter admin (HTTP ${status}). Check who is signed in: npx virtualmatter whoami`);
|
|
7
|
+
this.name = "NotAdminError";
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* The admin API URL for `path`: "framings", "/framings" and
|
|
12
|
+
* "/api/v1/admin/framings" all name the same list. Anything that would leave
|
|
13
|
+
* the admin API (another host, `..`, a different API root) is refused, so the
|
|
14
|
+
* signed-in token is only ever sent to the platform's admin reads.
|
|
15
|
+
*/
|
|
16
|
+
export function adminUrl(path, query = {}) {
|
|
17
|
+
const raw = path.trim();
|
|
18
|
+
if (!raw)
|
|
19
|
+
throw new Error("Give an admin API path, for example: framings");
|
|
20
|
+
if (/^[a-z][a-z0-9+.-]*:/i.test(raw) || raw.startsWith("//")) {
|
|
21
|
+
throw new Error("Give a path under the admin API, not a full URL.");
|
|
22
|
+
}
|
|
23
|
+
const q = raw.indexOf("?");
|
|
24
|
+
const pathPart = q < 0 ? raw : raw.slice(0, q);
|
|
25
|
+
const queryPart = q < 0 ? "" : raw.slice(q + 1);
|
|
26
|
+
let rel = pathPart.replace(/^\/+/, "");
|
|
27
|
+
if (rel.startsWith(ADMIN_PREFIX.slice(1)))
|
|
28
|
+
rel = rel.slice(ADMIN_PREFIX.length - 1);
|
|
29
|
+
const segments = rel.split("/").filter((s) => s.length > 0);
|
|
30
|
+
if (segments.length === 0)
|
|
31
|
+
throw new Error("Give an admin API path, for example: framings");
|
|
32
|
+
let decoded;
|
|
33
|
+
try {
|
|
34
|
+
decoded = segments.map((s) => decodeURIComponent(s));
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
throw new Error(`Not a valid admin API path: ${path}`);
|
|
38
|
+
}
|
|
39
|
+
if (decoded.some((s) => s === "." || s === ".." || /[\\/]/.test(s))) {
|
|
40
|
+
throw new Error(`Not a valid admin API path: ${path}`);
|
|
41
|
+
}
|
|
42
|
+
const url = new URL(`${apiBase()}${ADMIN_PREFIX}${decoded.map(encodeURIComponent).join("/")}`);
|
|
43
|
+
for (const [k, v] of new URLSearchParams(queryPart))
|
|
44
|
+
url.searchParams.append(k, v);
|
|
45
|
+
for (const [k, v] of Object.entries(query))
|
|
46
|
+
url.searchParams.set(k, v);
|
|
47
|
+
return url.toString();
|
|
48
|
+
}
|
|
49
|
+
/** GET one admin API path and return its JSON. */
|
|
50
|
+
export async function adminGet(path, query = {}, fetchFn = fetch) {
|
|
51
|
+
const url = adminUrl(path, query);
|
|
52
|
+
const res = await authorizedFetch(url, {}, fetchFn);
|
|
53
|
+
if (res.status === 401 || res.status === 403)
|
|
54
|
+
throw new NotAdminError(res.status);
|
|
55
|
+
if (res.status === 404)
|
|
56
|
+
throw new Error(`No admin API read at ${new URL(url).pathname}.`);
|
|
57
|
+
if (!res.ok)
|
|
58
|
+
throw new Error(`GET ${new URL(url).pathname} failed: HTTP ${res.status}`);
|
|
59
|
+
return res.json();
|
|
60
|
+
}
|
|
61
|
+
export function worldSummary(row) {
|
|
62
|
+
const make = row.framings?.find((f) => f.kind === "make") ?? null;
|
|
63
|
+
const play = row.framings?.find((f) => f.kind === "play") ?? null;
|
|
64
|
+
return {
|
|
65
|
+
name: row.name,
|
|
66
|
+
id: row.id,
|
|
67
|
+
owner_handle: row.owner_handle,
|
|
68
|
+
owner_email: row.owner_email,
|
|
69
|
+
region: row.region,
|
|
70
|
+
tier: row.tier,
|
|
71
|
+
visibility: row.visibility,
|
|
72
|
+
framing_id: make?.id ?? null,
|
|
73
|
+
edit_url: make ? editUrl(make.id, row.url_slug) : null,
|
|
74
|
+
play_framing_id: play?.id ?? null,
|
|
75
|
+
play_url: play ? playUrl(play.id) : null,
|
|
76
|
+
updated_at: row.updated_at,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
/** Case-insensitive "contains" over the listed fields; no needle keeps every row. */
|
|
80
|
+
export function matchRows(rows, needle, fields) {
|
|
81
|
+
const n = needle?.trim().toLowerCase();
|
|
82
|
+
if (!n)
|
|
83
|
+
return rows;
|
|
84
|
+
return rows.filter((row) => fields(row).some((v) => typeof v === "string" && v.toLowerCase().includes(n)));
|
|
85
|
+
}
|
|
86
|
+
/** Every account's worlds, newest first, with their edit and play links. */
|
|
87
|
+
export async function listAdminWorlds(filter = {}, fetchFn = fetch) {
|
|
88
|
+
let rows = (await adminGet("montages", {}, fetchFn));
|
|
89
|
+
rows = matchRows(rows, filter.search, (r) => [
|
|
90
|
+
r.name,
|
|
91
|
+
r.url_slug,
|
|
92
|
+
r.id,
|
|
93
|
+
r.public_id,
|
|
94
|
+
...(r.framings ?? []).map((f) => f.id),
|
|
95
|
+
]);
|
|
96
|
+
rows = matchRows(rows, filter.owner, (r) => [r.owner_handle, r.owner_email]);
|
|
97
|
+
return rows.map(worldSummary);
|
|
98
|
+
}
|
|
99
|
+
export async function listAdminUsers(search, fetchFn = fetch) {
|
|
100
|
+
const rows = (await adminGet("users", {}, fetchFn));
|
|
101
|
+
return matchRows(rows, search, (u) => [u.handle, u.username, u.email, u.first_name, u.last_name, u.id]);
|
|
102
|
+
}
|
|
103
|
+
function table(header, rows) {
|
|
104
|
+
const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? "").length)));
|
|
105
|
+
const line = (cells) => cells.map((c, i) => c.padEnd(widths[i] ?? 0)).join(" ").trimEnd();
|
|
106
|
+
return [line(header), ...rows.map(line)].join("\n");
|
|
107
|
+
}
|
|
108
|
+
export function formatWorlds(worlds) {
|
|
109
|
+
return table(["NAME", "OWNER", "REGION", "EDIT"], worlds.map((w) => [w.name, w.owner_handle, w.region, w.edit_url ?? "-"]));
|
|
110
|
+
}
|
|
111
|
+
export function formatUsers(users) {
|
|
112
|
+
return table(["HANDLE", "EMAIL", "WORLDS", "CREDITS", "LAST SEEN"], users.map((u) => [
|
|
113
|
+
u.handle,
|
|
114
|
+
u.email,
|
|
115
|
+
String(u.project_count),
|
|
116
|
+
String(u.credits_balance),
|
|
117
|
+
String(u.last_seen_at).slice(0, 10),
|
|
118
|
+
]));
|
|
119
|
+
}
|
|
120
|
+
function parseQuery(pairs) {
|
|
121
|
+
const out = {};
|
|
122
|
+
for (const pair of pairs) {
|
|
123
|
+
const eq = pair.indexOf("=");
|
|
124
|
+
if (eq <= 0)
|
|
125
|
+
throw new Error(`--query takes key=value (got ${JSON.stringify(pair)})`);
|
|
126
|
+
out[pair.slice(0, eq)] = pair.slice(eq + 1);
|
|
127
|
+
}
|
|
128
|
+
return out;
|
|
129
|
+
}
|
|
130
|
+
export function registerAdminCommands(program, run) {
|
|
131
|
+
const admin = program
|
|
132
|
+
.command("admin")
|
|
133
|
+
.description("Read across every account's worlds (platform admins only; read-only)");
|
|
134
|
+
admin
|
|
135
|
+
.command("worlds")
|
|
136
|
+
.alias("projects")
|
|
137
|
+
.description("Every account's worlds with their owner and edit/play links")
|
|
138
|
+
.option("--search <text>", "only worlds whose name, slug or an id contains this")
|
|
139
|
+
.option("--owner <text>", "only worlds whose owner's handle or email contains this")
|
|
140
|
+
.option("--json", "machine-readable output")
|
|
141
|
+
.action((opts) => run(async () => {
|
|
142
|
+
const worlds = await listAdminWorlds({ search: opts.search, owner: opts.owner });
|
|
143
|
+
if (opts.json)
|
|
144
|
+
console.log(JSON.stringify(worlds, null, 2));
|
|
145
|
+
else
|
|
146
|
+
console.log(worlds.length ? formatWorlds(worlds) : "No worlds match.");
|
|
147
|
+
}));
|
|
148
|
+
admin
|
|
149
|
+
.command("users")
|
|
150
|
+
.description("Every account: handle, email, world count, credits, last seen")
|
|
151
|
+
.option("--search <text>", "only accounts whose handle, name or email contains this")
|
|
152
|
+
.option("--json", "machine-readable output")
|
|
153
|
+
.action((opts) => run(async () => {
|
|
154
|
+
const users = await listAdminUsers(opts.search);
|
|
155
|
+
if (opts.json)
|
|
156
|
+
console.log(JSON.stringify(users, null, 2));
|
|
157
|
+
else
|
|
158
|
+
console.log(users.length ? formatUsers(users) : "No accounts match.");
|
|
159
|
+
}));
|
|
160
|
+
admin
|
|
161
|
+
.command("get <path>")
|
|
162
|
+
.description("GET any admin API read as JSON, e.g. framings, sessions, hosts, analytics/frame-time")
|
|
163
|
+
.option("--query <key=value...>", "query parameters", (v, acc) => [...acc, v], [])
|
|
164
|
+
.action((path, opts) => run(async () => {
|
|
165
|
+
console.log(JSON.stringify(await adminGet(path, parseQuery(opts.query)), null, 2));
|
|
166
|
+
}));
|
|
167
|
+
}
|
|
@@ -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`, `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";
|
|
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 restart restart the editor server: a clean engine\n process (the only thing that returns\n memory; Server:ReloadScene() does not).\n Saves first, waits until Lua answers,\n prints the time and Server:GetMemoryUsage().\n --force for a stuck engine, --yes when\n clients are connected. Never a play server\n- npx virtualmatter stop | start stop the editor server and leave it\n stopped / start a stopped one. Exit 3 =\n sent, outcome unknown: check status first\n- npx virtualmatter publish update the play servers; reports each\n server, says which scene they load\n- npx virtualmatter status editor server running or stopped, engine\n iteration, play servers vs the editor,\n 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";
|
package/dist/asset-commands.js
CHANGED
|
@@ -58,6 +58,14 @@ export function voxelizeOptions(opts) {
|
|
|
58
58
|
out.rotation = parseTriple(opts.rotate, "--rotate");
|
|
59
59
|
if (opts.shading === false)
|
|
60
60
|
out.applyShading = false;
|
|
61
|
+
if (opts.imageStack)
|
|
62
|
+
out.imageStack = true;
|
|
63
|
+
if (opts.threshold !== undefined) {
|
|
64
|
+
const threshold = Number(opts.threshold);
|
|
65
|
+
if (!(threshold > 0 && threshold < 1))
|
|
66
|
+
throw new Error(`--threshold takes a number between 0 and 1 (got "${opts.threshold}")`);
|
|
67
|
+
out.threshold = threshold;
|
|
68
|
+
}
|
|
61
69
|
return out;
|
|
62
70
|
}
|
|
63
71
|
/** `voxelize <sources...>`. Returns the exit code. */
|
package/dist/assets.js
CHANGED
|
@@ -157,6 +157,13 @@ export function voxelizeParameters(kind, opts) {
|
|
|
157
157
|
return shared;
|
|
158
158
|
if (kind === "voxel")
|
|
159
159
|
return {};
|
|
160
|
+
if (kind === "bundle" && opts.imageStack) {
|
|
161
|
+
// Slices carry no outside light worth baking: shading is on only when asked for.
|
|
162
|
+
const image_stack = { voxel_size_m, apply_shading: opts.applyShading === true };
|
|
163
|
+
if (opts.threshold !== undefined)
|
|
164
|
+
image_stack.threshold = opts.threshold;
|
|
165
|
+
return { inner_kind: "image_stack", image_stack };
|
|
166
|
+
}
|
|
160
167
|
if (kind === "bundle")
|
|
161
168
|
return { inner_kind: "mesh", mesh };
|
|
162
169
|
throw new Error(`Uploads of kind ${kind} cannot be voxelized.`);
|
|
@@ -338,13 +345,80 @@ export async function voxelizeSource(source, opts = {}) {
|
|
|
338
345
|
const upload = UUID_RE.test(source) && !fs.existsSync(source)
|
|
339
346
|
? await getUpload(source, opts.fetchFn)
|
|
340
347
|
: await uploadFile(source, { onProgress: opts.onUploadProgress, fetchFn: opts.fetchFn });
|
|
341
|
-
|
|
348
|
+
const isLocalZip = fs.existsSync(source) && source.toLowerCase().endsWith(".zip");
|
|
349
|
+
const imageStack = opts.imageStack ?? (isLocalZip && zipIsImageStack(source));
|
|
350
|
+
let job = await startVoxelize(upload, { ...opts, imageStack }, opts.fetchFn);
|
|
342
351
|
if (opts.wait === false)
|
|
343
352
|
return { upload, job, asset: null };
|
|
344
353
|
job = await waitForJob(job.id, { fetchFn: opts.fetchFn, onUpdate: opts.onJobUpdate, timeoutMs: opts.waitTimeoutMs });
|
|
345
354
|
const asset = job.status === "succeeded" ? await assetForJob(job.id, opts.fetchFn) : null;
|
|
346
355
|
return { upload, job, asset };
|
|
347
356
|
}
|
|
357
|
+
const STACK_IMAGE_EXTENSIONS = new Set(["png", "jpg", "jpeg", "tif", "tiff", "bmp", "tga"]);
|
|
358
|
+
/** The file names in a zip, read from its central directory; null when it cannot be read. */
|
|
359
|
+
export function zipEntryNames(filePath) {
|
|
360
|
+
const fd = fs.openSync(filePath, "r");
|
|
361
|
+
try {
|
|
362
|
+
const size = fs.fstatSync(fd).size;
|
|
363
|
+
const read = (offset, length) => {
|
|
364
|
+
const buf = Buffer.alloc(length);
|
|
365
|
+
fs.readSync(fd, buf, 0, length, offset);
|
|
366
|
+
return buf;
|
|
367
|
+
};
|
|
368
|
+
// The end record sits in the last 22 bytes plus an optional comment of up to 64 KiB.
|
|
369
|
+
const tailLength = Math.min(size, 22 + 0xffff);
|
|
370
|
+
const tailStart = size - tailLength;
|
|
371
|
+
const tail = read(tailStart, tailLength);
|
|
372
|
+
let end = -1;
|
|
373
|
+
for (let i = tail.length - 22; i >= 0; i--) {
|
|
374
|
+
if (tail.readUInt32LE(i) === 0x06054b50) {
|
|
375
|
+
end = i;
|
|
376
|
+
break;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
if (end < 0)
|
|
380
|
+
return null;
|
|
381
|
+
let dirSize = tail.readUInt32LE(end + 12);
|
|
382
|
+
let dirOffset = tail.readUInt32LE(end + 16);
|
|
383
|
+
// Zip64 (over 4 GiB or 65,535 entries): the real numbers are in the record its locator points at.
|
|
384
|
+
if (end >= 20 && tail.readUInt32LE(end - 20) === 0x07064b50) {
|
|
385
|
+
const record = read(Number(tail.readBigUInt64LE(end - 20 + 8)), 56);
|
|
386
|
+
if (record.readUInt32LE(0) !== 0x06064b50)
|
|
387
|
+
return null;
|
|
388
|
+
dirSize = Number(record.readBigUInt64LE(40));
|
|
389
|
+
dirOffset = Number(record.readBigUInt64LE(48));
|
|
390
|
+
}
|
|
391
|
+
if (dirOffset + dirSize > size)
|
|
392
|
+
return null;
|
|
393
|
+
const dir = read(dirOffset, dirSize);
|
|
394
|
+
const names = [];
|
|
395
|
+
for (let at = 0; at + 46 <= dir.length && dir.readUInt32LE(at) === 0x02014b50;) {
|
|
396
|
+
const nameLength = dir.readUInt16LE(at + 28);
|
|
397
|
+
names.push(dir.toString("utf8", at + 46, at + 46 + nameLength));
|
|
398
|
+
at += 46 + nameLength + dir.readUInt16LE(at + 30) + dir.readUInt16LE(at + 32);
|
|
399
|
+
}
|
|
400
|
+
return names;
|
|
401
|
+
}
|
|
402
|
+
catch {
|
|
403
|
+
return null;
|
|
404
|
+
}
|
|
405
|
+
finally {
|
|
406
|
+
fs.closeSync(fd);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* Whether a zip is a stack of slice images rather than a set of 3D models: it
|
|
411
|
+
* has a stack.json, or every file in it is an image. A textured model's zip
|
|
412
|
+
* always has a model file too, so it stays a mesh bundle.
|
|
413
|
+
*/
|
|
414
|
+
export function zipIsImageStack(filePath) {
|
|
415
|
+
const names = zipEntryNames(filePath)?.filter((n) => !n.endsWith("/") && !n.startsWith("__MACOSX/") && !path.posix.basename(n).startsWith("."));
|
|
416
|
+
if (!names || names.length === 0)
|
|
417
|
+
return false;
|
|
418
|
+
if (names.some((n) => path.posix.basename(n) === "stack.json" && n.split("/").length <= 2))
|
|
419
|
+
return true;
|
|
420
|
+
return names.every((n) => STACK_IMAGE_EXTENSIONS.has(n.split(".").pop().toLowerCase()));
|
|
421
|
+
}
|
|
348
422
|
/** File extensions the platform accepts as uploads (backend services/uploads.py). */
|
|
349
423
|
export const UPLOAD_EXTENSIONS = new Set([
|
|
350
424
|
"glb", "gltf", "fbx", "obj", "stl",
|
package/dist/index.js
CHANGED
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
import fs from "node:fs";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import { registerLogCommands } from "./log-commands.js";
|
|
6
|
+
import { describeEngineState, getEngineState, registerLifecycleCommands } from "./server-lifecycle.js";
|
|
7
|
+
import { registerAdminCommands } from "./admin.js";
|
|
6
8
|
import { Command } from "commander";
|
|
7
9
|
import { createProject, createWebsiteBuild, getWebsiteBuild, getEmbed, defaultRegion, editUrl, fetchNativeClientCatalog, listProjects, playUrl, NotEditFramingError, authorizedFetch, resolveEditSession, resolveSession, whoami, } from "./api.js";
|
|
8
10
|
import { NotLoggedInError, clearCredentials, loadCredentials, pollForToken, saveCredentials, startDeviceFlow, } from "./auth.js";
|
|
@@ -504,21 +506,25 @@ program
|
|
|
504
506
|
}));
|
|
505
507
|
program
|
|
506
508
|
.command("status")
|
|
507
|
-
.description("
|
|
509
|
+
.description("Whether the world's editor server is running or stopped, its engine iteration (editor and each play server, and any announced move), its play servers: whether each matches the editor, which scene they load, and how the last update went")
|
|
508
510
|
.argument("[dir]", "a synced folder", ".")
|
|
509
511
|
.option("--json", "machine-readable output")
|
|
510
512
|
.action((dir, opts) => run(async () => {
|
|
511
|
-
const
|
|
512
|
-
const
|
|
513
|
+
const framingId = requireState(path.resolve(dir)).framing_id;
|
|
514
|
+
const project = await projectForEditor(framingId);
|
|
515
|
+
const [drift, last, engine, server] = await Promise.all([
|
|
513
516
|
getDrift(project.id),
|
|
514
517
|
getPublishRun(project.id),
|
|
515
518
|
// advice: a platform without the endpoint still answers the rest
|
|
516
519
|
getEngineIterations(project.id).catch(() => null),
|
|
520
|
+
getEngineState(framingId).catch(() => null),
|
|
517
521
|
]);
|
|
518
522
|
if (opts.json) {
|
|
519
|
-
console.log(JSON.stringify({ project: project.name, montage_id: project.id, engine, drift, last_update: last }, null, 2));
|
|
523
|
+
console.log(JSON.stringify({ project: project.name, montage_id: project.id, server, engine, drift, last_update: last }, null, 2));
|
|
520
524
|
return;
|
|
521
525
|
}
|
|
526
|
+
if (server)
|
|
527
|
+
console.log(describeEngineState(server));
|
|
522
528
|
if (engine)
|
|
523
529
|
for (const line of formatIterations(engine))
|
|
524
530
|
console.log(line);
|
|
@@ -742,6 +748,8 @@ program
|
|
|
742
748
|
.option("--method <m>", "FloodFill (solid, default), ShellOnly, RayCast (open or non-watertight meshes, terrain), Projections, Polymender")
|
|
743
749
|
.option("--rotate <x,y,z>", "rotate the source by these degrees first, e.g. -90,0,0 for a Z-up model")
|
|
744
750
|
.option("--no-shading", "don't bake lighting into the voxel colours")
|
|
751
|
+
.option("--image-stack", "the zip is a stack of slice images (CT, MRI, any volume): one pixel becomes one voxel. Detected on its own when the zip holds only images or a stack.json")
|
|
752
|
+
.option("--threshold <0..1>", "image stacks: a voxel is solid where the slice value is above this (default 0.5)")
|
|
745
753
|
.option("--name <name>", "the asset's name (default: the file name; one source only)")
|
|
746
754
|
.option("--attach", "attach the results to a world (--project, else the synced folder here)")
|
|
747
755
|
.option("--place <x,y,z>", "also place each one in the world, its 0,0,0 at this position (implies --attach)")
|
|
@@ -834,6 +842,8 @@ program
|
|
|
834
842
|
await runMcpServer(path.resolve(dir), opts.framing);
|
|
835
843
|
}));
|
|
836
844
|
registerLogCommands(program);
|
|
845
|
+
registerLifecycleCommands(program, run);
|
|
846
|
+
registerAdminCommands(program, run);
|
|
837
847
|
program.parseAsync(process.argv).catch((err) => {
|
|
838
848
|
fail(err instanceof Error ? err.message : String(err));
|
|
839
849
|
});
|
package/dist/mcp.js
CHANGED
|
@@ -18,6 +18,8 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
|
18
18
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
19
19
|
import { z } from "zod";
|
|
20
20
|
import { createProject, createWebsiteBuild, getWebsiteBuild, getEmbed, defaultRegion, editUrl, listProjects, playUrl, resolveEditSession, resolveSession, sessionBaseUrl, } from "./api.js";
|
|
21
|
+
import { adminGet, listAdminWorlds } from "./admin.js";
|
|
22
|
+
import { describeEngineState, getEngineState, runLifecycle } from "./server-lifecycle.js";
|
|
21
23
|
import { attachAsset, findAsset, getJob, assetForJob, listAssets, listProjectAssets, placeInWorld, voxelizeSource, } from "./assets.js";
|
|
22
24
|
import { ensureClientInstalled, launchClient, seedNativeAuth } from "./client.js";
|
|
23
25
|
import { packageVersion } from "./config.js";
|
|
@@ -252,6 +254,14 @@ export async function runMcpServer(dir, framingFlag) {
|
|
|
252
254
|
description: "Check a VM build by build_id. Do not create another project to check progress. Review the world and enable sharing before embedding.",
|
|
253
255
|
inputSchema: { build_id: z.string() },
|
|
254
256
|
}, async ({ build_id }) => textResult(JSON.stringify(await getWebsiteBuild(build_id))));
|
|
257
|
+
server.registerTool("admin_list_worlds", {
|
|
258
|
+
description: "Platform admins only, read-only: every account's worlds with owner handle and email, region, tier, and edit/play URLs. Filter with search (name, slug or an id) and owner (handle or email). A maker account gets a not-an-admin error. Use this to find another account's world instead of calling the admin API by hand.",
|
|
259
|
+
inputSchema: { search: z.string().optional(), owner: z.string().optional() },
|
|
260
|
+
}, async ({ search, owner }) => textResult(JSON.stringify(await listAdminWorlds({ search, owner }), null, 2)));
|
|
261
|
+
server.registerTool("admin_get", {
|
|
262
|
+
description: "Platform admins only, read-only: GET one admin API read and return its JSON. path is relative to /api/v1/admin, for example framings, users, sessions, hosts, hosts/metrics, analytics/frame-time. query holds optional query parameters. It cannot change anything and cannot reach outside the admin API.",
|
|
263
|
+
inputSchema: { path: z.string(), query: z.record(z.string()).optional() },
|
|
264
|
+
}, async ({ path: adminPath, query }) => textResult(JSON.stringify(await adminGet(adminPath, query ?? {}), null, 2)));
|
|
255
265
|
server.registerTool("list_projects", {
|
|
256
266
|
description: "List the signed-in maker's Virtual Matter projects (worlds): name, id, region, the editing framing id, and edit/play URLs. Call this to find a world to work in, then select_project.",
|
|
257
267
|
inputSchema: {},
|
|
@@ -409,6 +419,39 @@ export async function runMcpServer(dir, framingFlag) {
|
|
|
409
419
|
return textResult(JSON.stringify(await getEngineRestarts(framing, Math.min(tail ?? 20, 200)), null, 2));
|
|
410
420
|
return textResult(JSON.stringify(await getEngineLog(framing, Math.max(1, tail ?? 100)), null, 2));
|
|
411
421
|
});
|
|
422
|
+
const lifecycleTool = (verb, description, extra) => server.registerTool(`${verb}_server`, { description, inputSchema: extra }, async (args) => {
|
|
423
|
+
const notes = [];
|
|
424
|
+
const result = await runLifecycle(verb, ctx.requireFraming(), {
|
|
425
|
+
force: args.force === true,
|
|
426
|
+
yes: args.yes === true,
|
|
427
|
+
noWait: args.wait === false,
|
|
428
|
+
timeoutS: typeof args.timeout_seconds === "number" ? args.timeout_seconds : undefined,
|
|
429
|
+
resetTerrain: args.reset_terrain === true,
|
|
430
|
+
}, { log: (line) => notes.push(line) });
|
|
431
|
+
return { ...textResult(JSON.stringify({ ...result, notes }, null, 2)), isError: result.exitCode !== 0 };
|
|
432
|
+
});
|
|
433
|
+
const lifecycleExits = "The result's exitCode is 0 done, 1 the platform reported a failure, 2 nothing was done, 3 sent but the outcome is unknown (check server_status before sending it again).";
|
|
434
|
+
const force = z.boolean().optional().describe("Stop without letting the engine save, for a stuck engine. Unsaved changes are lost");
|
|
435
|
+
const yes = z.boolean().optional().describe("Go ahead although clients are connected (they are disconnected). Without it the call is refused and says how many");
|
|
436
|
+
const wait = z.boolean().optional().describe("Wait until the engine answers Lua again (default true). A large world loads for minutes");
|
|
437
|
+
const timeout_seconds = z.number().positive().optional().describe("How long to wait (default 900)");
|
|
438
|
+
lifecycleTool("restart", `Restart the selected world's editor server: the same operation as the web editor's Restart button, and the only way to get a clean engine process (Server:ReloadScene() reloads inside the same process and returns no memory). The engine saves first unless force is set. Waits until the engine answers Lua, then returns the seconds taken and Server:GetMemoryUsage(). Never restarts play servers. ${lifecycleExits}`, { force, yes, wait, timeout_seconds });
|
|
439
|
+
lifecycleTool("stop", `Stop the selected world's editor server and leave it stopped, letting the engine save first unless force is set. It starts again when someone opens the world, or with start_server. ${lifecycleExits}`, { force, yes, timeout_seconds });
|
|
440
|
+
lifecycleTool("start", `Start the selected world's editor server if it is stopped and wait until it answers Lua; a running server is left alone. ${lifecycleExits}`, {
|
|
441
|
+
wait,
|
|
442
|
+
timeout_seconds,
|
|
443
|
+
reset_terrain: z
|
|
444
|
+
.boolean()
|
|
445
|
+
.optional()
|
|
446
|
+
.describe("Only for a world stopped after running out of memory: swap its terrain for an empty grid (the old one is kept in a backup folder on the server), then start. Never set it unless the maker asked"),
|
|
447
|
+
});
|
|
448
|
+
server.registerTool("server_status", {
|
|
449
|
+
description: "Whether the selected world's editor server is running, starting or stopped, how many clients are connected, and whether it was stopped for running out of memory. Reading it never starts a stopped server.",
|
|
450
|
+
inputSchema: {},
|
|
451
|
+
}, async () => {
|
|
452
|
+
const state = await getEngineState(ctx.requireFraming());
|
|
453
|
+
return textResult(JSON.stringify({ ...state, summary: describeEngineState(state) }, null, 2));
|
|
454
|
+
});
|
|
412
455
|
server.registerTool("play_server_status", {
|
|
413
456
|
description: "The selected world's engine iteration (the editor's and each play server's, what each last booted, any mismatch between them, an announced platform move, and a link to what changed in the API) and its play servers (what visitors play): whether each still matches the editor, which scene they load and when the editor last saved it, and how the last update went (per server). Use it before and after publish_play_servers, and when engine behaviour looks different from what you expect.",
|
|
414
457
|
inputSchema: {},
|
|
@@ -554,7 +597,7 @@ export async function runMcpServer(dir, framingFlag) {
|
|
|
554
597
|
*/
|
|
555
598
|
const captureWorld = () => captureWorldTarget(ctx.requireFraming());
|
|
556
599
|
server.registerTool("voxelize_model", {
|
|
557
|
-
description: "Turn a 3D file on this machine (glb gltf fbx obj stl; ply pts xyz e57 las laz point clouds; vox; zip) into a voxel asset in the maker's library, on Virtual Matter's voxelizer: uploads it (resumable, up to 10 GiB), voxelizes it, and waits. With attach=true it also goes into the selected world's Assets/ folder, and with place it is put in the scene. The asset keeps the source's own coordinates in metres: place moves the source's 0,0,0, so map tiles placed with the same offset line up. Voxelizing takes seconds for a small model and can take an hour for a huge one; with wait=false it returns the job at once (poll get_voxelize_job). If placement fails the result says placed:false with the reason.",
|
|
600
|
+
description: "Turn a 3D file on this machine (glb gltf fbx obj stl; ply pts xyz e57 las laz point clouds; vox; zip of models, or a zip of slice images such as CT or MRI, which becomes one solid volume with one voxel per pixel) into a voxel asset in the maker's library, on Virtual Matter's voxelizer: uploads it (resumable, up to 10 GiB), voxelizes it, and waits. With attach=true it also goes into the selected world's Assets/ folder, and with place it is put in the scene. The asset keeps the source's own coordinates in metres: place moves the source's 0,0,0, so map tiles placed with the same offset line up. Voxelizing takes seconds for a small model and can take an hour for a huge one; with wait=false it returns the job at once (poll get_voxelize_job). If placement fails the result says placed:false with the reason.",
|
|
558
601
|
inputSchema: {
|
|
559
602
|
path: z.string().describe("Local file path, or an upload id to voxelize again"),
|
|
560
603
|
voxels_per_meter: z.number().positive().optional().describe("Rounded to a power of two. Default 4 (25 cm voxels); city blocks 2-4, props 32-128"),
|
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stop, start and restart a world's editor server: `virtualmatter restart`,
|
|
3
|
+
* `stop`, `start` and the MCP tools of the same names.
|
|
4
|
+
*
|
|
5
|
+
* These call the same platform routes as the web editor's Restart button, so
|
|
6
|
+
* a CLI restart is the same operation and reads the same way in
|
|
7
|
+
* `logs --restarts` ("Restarted from the CLI."). Editor only: the platform
|
|
8
|
+
* refuses a play server, which restarts when the world is published.
|
|
9
|
+
*
|
|
10
|
+
* Exit codes follow the rest of the CLI (see ATOMO_EXIT): 0 done, 1 the
|
|
11
|
+
* platform reported a failure, 2 nothing was done, 3 the request was sent but
|
|
12
|
+
* the outcome is not known yet.
|
|
13
|
+
*/
|
|
14
|
+
import fs from "node:fs";
|
|
15
|
+
import path from "node:path";
|
|
16
|
+
import readline from "node:readline";
|
|
17
|
+
import { authorizedFetch, resolveEditSession } from "./api.js";
|
|
18
|
+
import { NotLoggedInError } from "./auth.js";
|
|
19
|
+
import { apiBase } from "./config.js";
|
|
20
|
+
import { EngineTimeoutError, editSessionClient } from "./files.js";
|
|
21
|
+
import { resolveTarget } from "./resolve.js";
|
|
22
|
+
import { requireState } from "./state.js";
|
|
23
|
+
export const LIFECYCLE_EXIT = { done: 0, failed: 1, notDone: 2, unknown: 3 };
|
|
24
|
+
/** A refusal or failure with the exit code it maps to. */
|
|
25
|
+
export class LifecycleError extends Error {
|
|
26
|
+
exitCode;
|
|
27
|
+
constructor(message, exitCode) {
|
|
28
|
+
super(message);
|
|
29
|
+
this.exitCode = exitCode;
|
|
30
|
+
this.name = "LifecycleError";
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
const NO_PERMISSION = "No such world, or this account may not stop or start its server: only the world's owner can. Check who is signed in: npx virtualmatter whoami";
|
|
34
|
+
function framingPath(framingId, tail) {
|
|
35
|
+
return `${apiBase()}/api/v1/framings/${encodeURIComponent(framingId)}/${tail}`;
|
|
36
|
+
}
|
|
37
|
+
/** The platform's `detail` when the body is its own JSON error; null for a proxy's page. */
|
|
38
|
+
async function platformDetail(res) {
|
|
39
|
+
try {
|
|
40
|
+
const body = (await res.json());
|
|
41
|
+
if (typeof body.detail === "string")
|
|
42
|
+
return body.detail;
|
|
43
|
+
return body.detail ? JSON.stringify(body.detail) : null;
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
export async function getEngineState(framingId, fetchFn = fetch) {
|
|
50
|
+
const res = await authorizedFetch(framingPath(framingId, "engine-state"), {}, fetchFn);
|
|
51
|
+
if (res.status === 401 || res.status === 403 || res.status === 404)
|
|
52
|
+
throw new LifecycleError(NO_PERMISSION, LIFECYCLE_EXIT.notDone);
|
|
53
|
+
if (!res.ok) {
|
|
54
|
+
const detail = await platformDetail(res);
|
|
55
|
+
throw new LifecycleError(`Reading the server's state failed: HTTP ${res.status}${detail ? ` - ${detail}` : ""}`, LIFECYCLE_EXIT.notDone);
|
|
56
|
+
}
|
|
57
|
+
return (await res.json());
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* POST one lifecycle verb. The platform answers only once the old engine has
|
|
61
|
+
* stopped and the new one is up, which can outlast a gateway in front of it;
|
|
62
|
+
* that is reported as `unknown`, never as a failure, because the stop may
|
|
63
|
+
* well be in progress.
|
|
64
|
+
*/
|
|
65
|
+
export async function sendVerb(verb, framingId, force, fetchFn = fetch) {
|
|
66
|
+
let res;
|
|
67
|
+
try {
|
|
68
|
+
res = await authorizedFetch(framingPath(framingId, verb), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ source: "cli", force }) }, fetchFn);
|
|
69
|
+
}
|
|
70
|
+
catch (err) {
|
|
71
|
+
if (err instanceof NotLoggedInError)
|
|
72
|
+
throw err;
|
|
73
|
+
return { outcome: "unknown", why: err instanceof Error ? err.message : String(err) };
|
|
74
|
+
}
|
|
75
|
+
if (res.ok) {
|
|
76
|
+
// The platform has acted by the time it answers 2xx. If the connection
|
|
77
|
+
// drops while the body is read, or the body is not the platform's own,
|
|
78
|
+
// what it did is unknown: reconcile from the engine state, never resend.
|
|
79
|
+
let body;
|
|
80
|
+
try {
|
|
81
|
+
body = (await res.json());
|
|
82
|
+
}
|
|
83
|
+
catch (err) {
|
|
84
|
+
return { outcome: "unknown", why: `the answer could not be read (${err instanceof Error ? err.message : String(err)})` };
|
|
85
|
+
}
|
|
86
|
+
if (!body || typeof body.status !== "string")
|
|
87
|
+
return { outcome: "unknown", why: "the answer was not the platform's" };
|
|
88
|
+
return { outcome: "done", status: body.status, graceful: body.graceful === true };
|
|
89
|
+
}
|
|
90
|
+
const detail = await platformDetail(res);
|
|
91
|
+
if (res.status === 401 || res.status === 403 || res.status === 404) {
|
|
92
|
+
// 404 with no platform body is a platform that predates these routes.
|
|
93
|
+
if (res.status === 404 && detail !== "Framing not found" && verb !== "restart") {
|
|
94
|
+
throw new LifecycleError(`This platform has no ${verb} yet.`, LIFECYCLE_EXIT.notDone);
|
|
95
|
+
}
|
|
96
|
+
throw new LifecycleError(NO_PERMISSION, LIFECYCLE_EXIT.notDone);
|
|
97
|
+
}
|
|
98
|
+
if (detail === null && res.status >= 500)
|
|
99
|
+
return { outcome: "unknown", why: `HTTP ${res.status} from a gateway` };
|
|
100
|
+
// 409 and 422 are refused before anything is touched.
|
|
101
|
+
const code = res.status === 409 || res.status === 422 ? LIFECYCLE_EXIT.notDone : LIFECYCLE_EXIT.failed;
|
|
102
|
+
throw new LifecycleError(`${verb} failed: HTTP ${res.status}${detail ? ` - ${detail}` : ""}`, code);
|
|
103
|
+
}
|
|
104
|
+
/** Release the out-of-memory hold, swapping the terrain for the empty grid first. */
|
|
105
|
+
export async function resetTerrainAfterOom(framingId, fetchFn = fetch) {
|
|
106
|
+
const unanswered = (why) => new LifecycleError(`The terrain reset was sent but the platform did not answer (${why}), so the server was not started. Check with npx virtualmatter status before sending it again.`, LIFECYCLE_EXIT.unknown);
|
|
107
|
+
let res;
|
|
108
|
+
try {
|
|
109
|
+
res = await authorizedFetch(framingPath(framingId, "engine-oom/retry?reset_terrain=true"), { method: "POST" }, fetchFn);
|
|
110
|
+
}
|
|
111
|
+
catch (err) {
|
|
112
|
+
if (err instanceof NotLoggedInError)
|
|
113
|
+
throw err;
|
|
114
|
+
throw unanswered(err instanceof Error ? err.message : String(err));
|
|
115
|
+
}
|
|
116
|
+
if (res.ok)
|
|
117
|
+
return;
|
|
118
|
+
const detail = await platformDetail(res);
|
|
119
|
+
if (res.status === 401 || res.status === 403 || res.status === 404)
|
|
120
|
+
throw new LifecycleError(NO_PERMISSION, LIFECYCLE_EXIT.notDone);
|
|
121
|
+
if (detail === null && res.status >= 500)
|
|
122
|
+
throw unanswered(`HTTP ${res.status} from a gateway`);
|
|
123
|
+
throw new LifecycleError(`Resetting the terrain failed: HTTP ${res.status}${detail ? ` - ${detail}` : ""}`, LIFECYCLE_EXIT.failed);
|
|
124
|
+
}
|
|
125
|
+
const MEMORY_LUA = "return Server:GetMemoryUsage()";
|
|
126
|
+
/** Ask the engine for its memory use; throws while it is not answering. */
|
|
127
|
+
export async function probeEngine(framingId) {
|
|
128
|
+
const quiet = () => undefined;
|
|
129
|
+
const { session, framingId: editor } = await resolveEditSession(framingId, quiet);
|
|
130
|
+
const output = await editSessionClient(editor, session, quiet).runLua(MEMORY_LUA, "server");
|
|
131
|
+
return memoryReading(String(output ?? ""));
|
|
132
|
+
}
|
|
133
|
+
/** The value out of run-lua's `{"result":[...]}` envelope; other output is passed through as it came. */
|
|
134
|
+
export function memoryReading(output) {
|
|
135
|
+
const text = output.trim();
|
|
136
|
+
try {
|
|
137
|
+
const parsed = JSON.parse(text);
|
|
138
|
+
if (Array.isArray(parsed?.result) && parsed.result.length > 0)
|
|
139
|
+
return parsed.result.map(String).join(", ");
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
// not the envelope
|
|
143
|
+
}
|
|
144
|
+
return text;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Wait until the engine answers Lua again. A large world loads for minutes,
|
|
148
|
+
* during which run-lua answers HTTP 504 and the session 503: every failure
|
|
149
|
+
* here means "still loading" until the deadline.
|
|
150
|
+
*/
|
|
151
|
+
export async function waitForEngine(framingId, timeoutMs, deps = {}) {
|
|
152
|
+
const probe = deps.probe ?? probeEngine;
|
|
153
|
+
const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
154
|
+
const now = deps.now ?? Date.now;
|
|
155
|
+
const deadline = now() + timeoutMs;
|
|
156
|
+
let last = "no answer yet";
|
|
157
|
+
for (;;) {
|
|
158
|
+
try {
|
|
159
|
+
return { answered: true, memory: await probe(framingId) };
|
|
160
|
+
}
|
|
161
|
+
catch (err) {
|
|
162
|
+
if (err instanceof NotLoggedInError)
|
|
163
|
+
throw err;
|
|
164
|
+
last = err instanceof EngineTimeoutError ? "the engine is still loading (HTTP 504)" : err instanceof Error ? err.message : String(err);
|
|
165
|
+
}
|
|
166
|
+
if (now() >= deadline)
|
|
167
|
+
return { answered: false, last };
|
|
168
|
+
await sleep(Math.min(deps.intervalMs ?? 5000, Math.max(0, deadline - now())));
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
const DEFAULT_TIMEOUT_S = 900;
|
|
172
|
+
function plural(n, word) {
|
|
173
|
+
return `${n} ${word}${n === 1 ? "" : "s"}`;
|
|
174
|
+
}
|
|
175
|
+
/** One lifecycle command, start to finish. Never throws a LifecycleError: it becomes the result. */
|
|
176
|
+
export async function runLifecycle(verb, framingId, opts = {}, deps = {}) {
|
|
177
|
+
try {
|
|
178
|
+
return await lifecycle(verb, framingId, opts, deps);
|
|
179
|
+
}
|
|
180
|
+
catch (err) {
|
|
181
|
+
if (!(err instanceof LifecycleError))
|
|
182
|
+
throw err;
|
|
183
|
+
return { exitCode: err.exitCode, verb, outcome: err.exitCode === LIFECYCLE_EXIT.failed ? "failed" : err.exitCode === LIFECYCLE_EXIT.unknown ? "sent" : "refused", message: err.message };
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
async function lifecycle(verb, framingId, opts, deps) {
|
|
187
|
+
const log = deps.log ?? (() => undefined);
|
|
188
|
+
const now = deps.now ?? Date.now;
|
|
189
|
+
const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
190
|
+
const timeoutS = opts.timeoutS ?? DEFAULT_TIMEOUT_S;
|
|
191
|
+
if (!(timeoutS > 0))
|
|
192
|
+
throw new LifecycleError("--timeout takes a number of seconds above 0.", LIFECYCLE_EXIT.notDone);
|
|
193
|
+
if (opts.resetTerrain && verb !== "start")
|
|
194
|
+
throw new LifecycleError("--reset-terrain only applies to start.", LIFECYCLE_EXIT.notDone);
|
|
195
|
+
const refuse = (message) => {
|
|
196
|
+
throw new LifecycleError(message, LIFECYCLE_EXIT.notDone);
|
|
197
|
+
};
|
|
198
|
+
const state = await getEngineState(framingId, deps.fetchFn);
|
|
199
|
+
if (state.kind !== "make") {
|
|
200
|
+
refuse("That is a play server. These commands only stop and start a world's editor server; play servers restart when you publish (npx virtualmatter publish).");
|
|
201
|
+
}
|
|
202
|
+
if (verb === "stop" && state.state === "stopped") {
|
|
203
|
+
return { exitCode: LIFECYCLE_EXIT.done, verb, outcome: "already_stopped", message: "The server is already stopped." };
|
|
204
|
+
}
|
|
205
|
+
if (verb === "start" && state.state !== "stopped" && opts.resetTerrain) {
|
|
206
|
+
refuse("The server is running, so its terrain was left alone. --reset-terrain is only for a world stopped after running out of memory.");
|
|
207
|
+
}
|
|
208
|
+
if (verb === "start" && state.state === "stopped") {
|
|
209
|
+
if (state.out_of_memory && !opts.resetTerrain) {
|
|
210
|
+
refuse("This world's server was stopped because it ran out of memory, and it stays stopped until the world is smaller. " +
|
|
211
|
+
"`start --reset-terrain` swaps its terrain for an empty grid (the old terrain is kept in a backup folder on the server) and starts it.");
|
|
212
|
+
}
|
|
213
|
+
if (!state.out_of_memory && opts.resetTerrain) {
|
|
214
|
+
refuse("This world was not stopped for running out of memory, so its terrain was left alone. Start it without --reset-terrain.");
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
const stops = verb !== "start" && state.state !== "stopped";
|
|
218
|
+
if (stops && state.connected_clients > 0 && !opts.yes) {
|
|
219
|
+
const who = `${plural(state.connected_clients, "client")} connected to this server will be disconnected`;
|
|
220
|
+
if (!deps.confirm)
|
|
221
|
+
refuse(`${who}. Nothing was stopped; pass --yes to go ahead.`);
|
|
222
|
+
else if (!(await deps.confirm(`${who}. Continue?`)))
|
|
223
|
+
refuse("Nothing was stopped.");
|
|
224
|
+
}
|
|
225
|
+
if (stops && opts.force)
|
|
226
|
+
log("Forcing the stop: the engine is not given time to save, so unsaved changes are lost.");
|
|
227
|
+
else if (stops && !state.saves_on_stop) {
|
|
228
|
+
log("This world does not keep scene changes between sessions (a project setting), so nothing is saved when its server stops.");
|
|
229
|
+
}
|
|
230
|
+
const startedAt = now();
|
|
231
|
+
if (verb === "start" && opts.resetTerrain) {
|
|
232
|
+
log("Swapping the terrain for the empty grid ...");
|
|
233
|
+
await resetTerrainAfterOom(framingId, deps.fetchFn);
|
|
234
|
+
}
|
|
235
|
+
log(verb === "stop" ? "Stopping the server ..." : verb === "start" ? "Starting the server ..." : "Restarting the server ...");
|
|
236
|
+
const sent = await sendVerb(verb, framingId, opts.force === true, deps.fetchFn);
|
|
237
|
+
const clients = { connected_clients: state.connected_clients };
|
|
238
|
+
if (verb === "stop") {
|
|
239
|
+
if (sent.outcome === "done") {
|
|
240
|
+
const saved = sent.status === "stopped" ? (sent.graceful ? " It was given time to save first." : " It was stopped without saving.") : "";
|
|
241
|
+
return { exitCode: LIFECYCLE_EXIT.done, verb, outcome: sent.status, message: `The server is stopped.${saved} Start it again with: npx virtualmatter start`, ...clients };
|
|
242
|
+
}
|
|
243
|
+
// The stop may still be saving: watch the state until it is down.
|
|
244
|
+
log(`No answer from the platform yet (${sent.why}); checking whether the server stopped ...`);
|
|
245
|
+
const deadline = startedAt + timeoutS * 1000;
|
|
246
|
+
for (;;) {
|
|
247
|
+
const s = await getEngineState(framingId, deps.fetchFn).catch(() => null);
|
|
248
|
+
if (s?.state === "stopped")
|
|
249
|
+
return { exitCode: LIFECYCLE_EXIT.done, verb, outcome: "stopped", message: "The server is stopped.", ...clients };
|
|
250
|
+
if (now() >= deadline) {
|
|
251
|
+
return { exitCode: LIFECYCLE_EXIT.unknown, verb, outcome: "sent", message: `The stop was sent but the server was still up after ${timeoutS} s. Check it with: npx virtualmatter status`, ...clients };
|
|
252
|
+
}
|
|
253
|
+
await sleep(Math.min(deps.intervalMs ?? 5000, Math.max(0, deadline - now())));
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
if (sent.outcome === "done" && sent.status === "already_running") {
|
|
257
|
+
log("The server is already running.");
|
|
258
|
+
}
|
|
259
|
+
else if (sent.outcome === "done") {
|
|
260
|
+
log(sent.status === "restarted" ? `The old engine stopped${sent.graceful ? " after saving" : " without saving"}; the new one is up and loading the world.` : "The engine is up and loading the world.");
|
|
261
|
+
}
|
|
262
|
+
else {
|
|
263
|
+
log(`No answer from the platform yet (${sent.why}); it may still be working. Waiting for the engine ...`);
|
|
264
|
+
}
|
|
265
|
+
const outcome = sent.outcome === "done" ? sent.status : "sent";
|
|
266
|
+
if (opts.noWait) {
|
|
267
|
+
const exitCode = sent.outcome === "done" ? LIFECYCLE_EXIT.done : LIFECYCLE_EXIT.unknown;
|
|
268
|
+
const message = sent.outcome === "done"
|
|
269
|
+
? "Not waiting for the world to load. run-lua answers HTTP 504 until it has."
|
|
270
|
+
: "The request was sent but the platform has not answered. Check it with: npx virtualmatter status";
|
|
271
|
+
return { exitCode, verb, outcome, message, ...clients };
|
|
272
|
+
}
|
|
273
|
+
if (sent.outcome === "unknown") {
|
|
274
|
+
// Nothing says the restart happened: the engine that was running before
|
|
275
|
+
// may still be the one answering. `running_since` is the engine row's
|
|
276
|
+
// creation time, so a different value is a different engine; only then
|
|
277
|
+
// does a Lua answer mean the restart is complete. A start replaces
|
|
278
|
+
// nothing, so any engine that is up, the original one included, is the
|
|
279
|
+
// outcome it asked for.
|
|
280
|
+
const deadline = startedAt + timeoutS * 1000;
|
|
281
|
+
for (;;) {
|
|
282
|
+
const s = await getEngineState(framingId, deps.fetchFn).catch(() => null);
|
|
283
|
+
const up = s !== null && s.state !== "stopped";
|
|
284
|
+
if (up && (verb === "start" || (s.running_since !== null && s.running_since !== state.running_since)))
|
|
285
|
+
break;
|
|
286
|
+
if (now() >= deadline) {
|
|
287
|
+
const what = verb === "restart" ? "the engine that was running was not replaced" : "no engine came up";
|
|
288
|
+
return {
|
|
289
|
+
exitCode: LIFECYCLE_EXIT.unknown,
|
|
290
|
+
verb,
|
|
291
|
+
outcome,
|
|
292
|
+
seconds: Math.round((now() - startedAt) / 1000),
|
|
293
|
+
message: `The ${verb} was sent but the platform never answered, and ${what} within ${timeoutS} s. Check with npx virtualmatter status before sending it again.`,
|
|
294
|
+
...clients,
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
await sleep(Math.min(deps.intervalMs ?? 5000, Math.max(0, deadline - now())));
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
const remaining = Math.max(1000, startedAt + timeoutS * 1000 - now());
|
|
301
|
+
const waited = await waitForEngine(framingId, remaining, deps);
|
|
302
|
+
const seconds = Math.round((now() - startedAt) / 1000);
|
|
303
|
+
if (!waited.answered) {
|
|
304
|
+
return {
|
|
305
|
+
exitCode: LIFECYCLE_EXIT.unknown,
|
|
306
|
+
verb,
|
|
307
|
+
outcome,
|
|
308
|
+
seconds,
|
|
309
|
+
message: `The engine did not answer within ${timeoutS} s (${waited.last}). A large world can take longer: check with npx virtualmatter status, or wait again with npx virtualmatter start.`,
|
|
310
|
+
...clients,
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
return { exitCode: LIFECYCLE_EXIT.done, verb, outcome, seconds, memory: waited.memory, message: `The engine answered after ${seconds} s.`, ...clients };
|
|
314
|
+
}
|
|
315
|
+
/** The framing a command acts on: a synced folder, or any link to the world. */
|
|
316
|
+
export async function lifecycleTarget(target, cwd = process.cwd()) {
|
|
317
|
+
const arg = target ?? ".";
|
|
318
|
+
const abs = path.resolve(cwd, arg);
|
|
319
|
+
if (fs.existsSync(abs) && fs.statSync(abs).isDirectory()) {
|
|
320
|
+
try {
|
|
321
|
+
return requireState(abs).framing_id;
|
|
322
|
+
}
|
|
323
|
+
catch (err) {
|
|
324
|
+
throw new LifecycleError(err instanceof Error ? err.message : String(err), LIFECYCLE_EXIT.notDone);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
try {
|
|
328
|
+
return (await resolveTarget(arg)).framingId;
|
|
329
|
+
}
|
|
330
|
+
catch (err) {
|
|
331
|
+
if (err instanceof NotLoggedInError)
|
|
332
|
+
throw err;
|
|
333
|
+
throw new LifecycleError(err instanceof Error ? err.message : String(err), LIFECYCLE_EXIT.notDone);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
function askOnTerminal(question) {
|
|
337
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
|
|
338
|
+
return new Promise((resolve) => rl.question(`${question} [y/N] `, (answer) => {
|
|
339
|
+
rl.close();
|
|
340
|
+
resolve(/^y(es)?$/i.test(answer.trim()));
|
|
341
|
+
}));
|
|
342
|
+
}
|
|
343
|
+
/** One line for `status`: is the editor server up. */
|
|
344
|
+
export function describeEngineState(state) {
|
|
345
|
+
if (state.state === "running") {
|
|
346
|
+
return `Editor server: running since ${state.running_since ?? "?"}, ${plural(state.connected_clients, "client")} connected.`;
|
|
347
|
+
}
|
|
348
|
+
if (state.state === "starting")
|
|
349
|
+
return "Editor server: starting.";
|
|
350
|
+
if (state.out_of_memory) {
|
|
351
|
+
return "Editor server: stopped after running out of memory. It stays stopped until the world is smaller: npx virtualmatter start --reset-terrain swaps the terrain for an empty grid and starts it.";
|
|
352
|
+
}
|
|
353
|
+
return "Editor server: stopped. Start it with: npx virtualmatter start";
|
|
354
|
+
}
|
|
355
|
+
export function registerLifecycleCommands(program, run) {
|
|
356
|
+
const exits = "Exit 0 done, 1 the platform reported a failure, 2 nothing was done, 3 sent but the outcome is unknown";
|
|
357
|
+
const action = (verb) => (target, flags) => run(async () => {
|
|
358
|
+
let result;
|
|
359
|
+
try {
|
|
360
|
+
const timeoutS = flags.timeout === undefined ? undefined : Number(flags.timeout);
|
|
361
|
+
if (timeoutS !== undefined && !(timeoutS > 0))
|
|
362
|
+
throw new LifecycleError("--timeout takes a number of seconds above 0.", LIFECYCLE_EXIT.notDone);
|
|
363
|
+
const framingId = await lifecycleTarget(target);
|
|
364
|
+
result = await runLifecycle(verb, framingId, { force: flags.force, yes: flags.yes, noWait: flags.wait === false, timeoutS, resetTerrain: flags.resetTerrain }, { confirm: process.stdin.isTTY && !flags.json ? askOnTerminal : undefined, log: (line) => console.error(line) });
|
|
365
|
+
}
|
|
366
|
+
catch (err) {
|
|
367
|
+
if (err instanceof NotLoggedInError && process.env.VIRTUALMATTER_NO_AUTO_LOGIN) {
|
|
368
|
+
result = { exitCode: LIFECYCLE_EXIT.notDone, verb, outcome: "refused", message: err.message };
|
|
369
|
+
}
|
|
370
|
+
else if (err instanceof LifecycleError) {
|
|
371
|
+
result = { exitCode: err.exitCode, verb, outcome: "refused", message: err.message };
|
|
372
|
+
}
|
|
373
|
+
else
|
|
374
|
+
throw err;
|
|
375
|
+
}
|
|
376
|
+
if (flags.json)
|
|
377
|
+
console.log(JSON.stringify(result, null, 2));
|
|
378
|
+
else {
|
|
379
|
+
(result.exitCode === 0 ? console.log : console.error)(result.message);
|
|
380
|
+
if (result.memory)
|
|
381
|
+
console.log(`Server:GetMemoryUsage(): ${result.memory}`);
|
|
382
|
+
}
|
|
383
|
+
process.exitCode = result.exitCode;
|
|
384
|
+
});
|
|
385
|
+
const common = (cmd) => cmd
|
|
386
|
+
.argument("[target]", "a synced folder, or any link to the world", ".")
|
|
387
|
+
.option("--json", "machine-readable output");
|
|
388
|
+
common(program
|
|
389
|
+
.command("restart")
|
|
390
|
+
.description(`Restart the world's editor server (the web editor's Restart button): a clean process, which is what returns memory. Lets the engine save first, then waits until it answers Lua again and prints the time taken and Server:GetMemoryUsage(). Never restarts play servers. ${exits}`))
|
|
391
|
+
.option("--force", "stop without letting the engine save, for a stuck engine; unsaved changes are lost")
|
|
392
|
+
.option("--yes", "do not ask before disconnecting connected clients")
|
|
393
|
+
.option("--no-wait", "return once the new engine is up, without waiting for the world to load")
|
|
394
|
+
.option("--timeout <seconds>", "how long to wait for the engine to answer (default 900)")
|
|
395
|
+
.action(action("restart"));
|
|
396
|
+
common(program
|
|
397
|
+
.command("stop")
|
|
398
|
+
.description(`Stop the world's editor server and leave it stopped, letting the engine save first. It starts again when someone opens the world or with start. ${exits}`))
|
|
399
|
+
.option("--force", "stop without letting the engine save, for a stuck engine; unsaved changes are lost")
|
|
400
|
+
.option("--yes", "do not ask before disconnecting connected clients")
|
|
401
|
+
.option("--timeout <seconds>", "how long to wait for the stop when the platform does not answer (default 900)")
|
|
402
|
+
.action(action("stop"));
|
|
403
|
+
common(program
|
|
404
|
+
.command("start")
|
|
405
|
+
.description(`Start the world's editor server if it is stopped, wait until it answers Lua, and print the time taken and Server:GetMemoryUsage(). A running server is left alone. ${exits}`))
|
|
406
|
+
.option("--no-wait", "return once the engine is up, without waiting for the world to load")
|
|
407
|
+
.option("--timeout <seconds>", "how long to wait for the engine to answer (default 900)")
|
|
408
|
+
.option("--reset-terrain", "only for a world stopped after running out of memory: swap its terrain for an empty grid (the old one is kept in a backup folder on the server), then start")
|
|
409
|
+
.action(action("start"));
|
|
410
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "virtualmatter",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"description": "CLI + MCP server for building with Virtual Matter - list and create worlds, sync their files, run Lua, capture screenshots, open the native client, and wire coding agents into a live session.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|