virtualmatter 0.6.5 → 0.6.7
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 +37 -6
- package/dist/agent-logs.js +33 -5
- package/dist/agents-md.generated.js +1 -1
- package/dist/files.js +200 -19
- package/dist/ignore.js +12 -0
- package/dist/index.js +222 -22
- package/dist/lock.js +208 -0
- package/dist/log-events.js +2 -2
- package/dist/mcp.js +137 -3
- package/dist/pull.js +2 -2
- package/dist/sync.js +305 -36
- package/dist/world-status.js +161 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -46,8 +46,28 @@ was stopped go out when it starts again.
|
|
|
46
46
|
|
|
47
47
|
Large voxel and terrain files (several GB is normal) are streamed to disk,
|
|
48
48
|
never loaded into memory. Sync does not push a file over 8 MB, the most the
|
|
49
|
-
world accepts in one write
|
|
50
|
-
|
|
49
|
+
world accepts in one write, and it does not pull one either: it cannot keep
|
|
50
|
+
such a file in step, and re-downloading a terrain on every engine save
|
|
51
|
+
competes with the world. It says once that the file changed;
|
|
52
|
+
`npx virtualmatter fetch <path>` downloads it (or run `sync --include-large`).
|
|
53
|
+
|
|
54
|
+
One sync runs per folder. Starting a second one stops the first, and sync
|
|
55
|
+
stops when the process that started it exits (`--keep-alive` keeps it running
|
|
56
|
+
detached). If the world's session moves (an engine restart), sync follows it;
|
|
57
|
+
if the session refuses it for good, sync exits with an error rather than keep
|
|
58
|
+
running while nothing it pushes arrives.
|
|
59
|
+
|
|
60
|
+
Deploying from a script or an agent? `push` is the one-shot alternative to a
|
|
61
|
+
running sync:
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
npx virtualmatter push Scripts/Game.lua Scripts/UI.lua
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
It reports each file as `pushed`, `unchanged` (nothing sent, so no Lua reset),
|
|
68
|
+
`conflict`, `too-large`, `missing` or `failed`, and exits 1 unless every file
|
|
69
|
+
was pushed or unchanged. `fetch [paths...]` is the matching download; neither
|
|
70
|
+
ever overwrites unsynced work.
|
|
51
71
|
|
|
52
72
|
`make`, `pull` and `sync` print the world's editor link ending in `?chat=closed`.
|
|
53
73
|
Open it in any browser to watch changes land live - no install needed.
|
|
@@ -113,7 +133,10 @@ It works before a world is selected: `list_projects`, `create_project`, and
|
|
|
113
133
|
`select_project` (any link or id, optionally mirroring into a folder) pick
|
|
114
134
|
one, then `list_files`, `read_file`, `write_file`, `run_lua`,
|
|
115
135
|
`get_engine_errors`, `capture_screenshot`, `open_native_client`, and
|
|
116
|
-
`world_info` act on it.
|
|
136
|
+
`world_info` act on it. `patch_file` edits a world file by replacing one
|
|
137
|
+
exact snippet, and `push_local_files` / `fetch_files` move files between the
|
|
138
|
+
world and the synced folder the server runs in, so big scripts never travel
|
|
139
|
+
through the conversation. Writes handle etag concurrency internally, and
|
|
117
140
|
written Lua hot-reloads in the engine - so for an agent, writing a script is
|
|
118
141
|
deploying it.
|
|
119
142
|
|
|
@@ -124,10 +147,15 @@ deploying it.
|
|
|
124
147
|
| `make <name> [dir]` (`create`) | Make a world (region defaults to the nearest; `--region`, `--track`, `--description`, `--no-pull`, `--open`, `--json`) and mirror it into `./<slug>`. |
|
|
125
148
|
| `list` (`ls`, `projects`) | Your worlds with framing ids and edit/play URLs (`--json`). |
|
|
126
149
|
| `pull [target] [dir]` | Mirror a world's file tree. `target` is any link to the world (or your website) or a framing id, and always resolves to the world's editor; omitted, it uses this folder's world or your only one. Also writes the harness files: `AGENTS.md`, `CLAUDE.md`, MCP registrations, the world's skill packages copied into `.claude/skills/`, and (macOS, Linux) an executable `./atomo`. |
|
|
127
|
-
| `sync [dir]` | Watch + two-way sync with the live session. Ctrl-C to stop. Refreshes `AGENTS.md` and `.claude/skills/` whenever the world's `Skills/` changes. |
|
|
150
|
+
| `sync [dir]` | Watch + two-way sync with the live session. Ctrl-C to stop. Refreshes `AGENTS.md` and `.claude/skills/` whenever the world's `Skills/` changes. Does not pull files over 8 MB (`--include-large` does); stops with the process that started it (`--keep-alive` does not). |
|
|
151
|
+
| `push [paths...] [--dir <dir>] [--force] [--json]` | One-shot deploy of the named files, or of every file changed since the last sync. Per-file result; unchanged files are not sent. `--force` overwrites a world copy that changed since. Refuses while `sync` runs on the folder. |
|
|
152
|
+
| `fetch [paths...] [--dir <dir>] [--include-large] [--json]` | One-shot download of the named files (any size), or of every file the world changed since the last sync. Never overwrites local edits. |
|
|
153
|
+
| `logs [dir] [--restarts] [--tail N] [--framing <id>] [--json]` | The engine's log. `--restarts` lists every recent engine restart and why: a crash (the engine restarted itself; with the last lines it logged) or a platform stop with its reason (idle, update, restart, out of memory). `--framing` reads a play server listed by `status`. |
|
|
154
|
+
| `status [dir] [--json]` | The world's play servers: whether each matches the editor, which scene they load and when it was last saved, and how the last update went. |
|
|
155
|
+
| `publish [dir] [--played-scene] [--no-wait] [--json]` | Update the play servers with the editor's latest (the project page's Update play servers). Says which scene they will load and warns when the editor's latest work isn't in it; waits and reports each server; exits 1 if any server wasn't updated. |
|
|
128
156
|
| `open [target]` (`client`) | Optional: open a world in the native desktop client, downloading and signing it in on first use. `--install-only`, `--print` (just the download URL), `--force`. |
|
|
129
157
|
| `run-lua [dir] --code "<lua>" [--target server\|client] [--client <id>]` | Execute Lua in the running engine. A client run uses the only connected client unless `--client` names one (list them with `--code "return Server:GetClients()"`). Exit code 3 means the engine did not answer in time and may still be running the code: check its effect before sending code that changes the world again. It is never retried for you. |
|
|
130
|
-
| `errors [dir]` | Recent engine errors. Retried twice when the engine is busy or briefly unreachable, since it only reads. |
|
|
158
|
+
| `errors [dir]` | Recent engine errors. Retried twice when the engine is busy or briefly unreachable, since it only reads. Notes on stderr when the engine restarted in the last hour, since a restart clears the error buffer. |
|
|
131
159
|
| `atomo [--dir <dir>] -- <command> ...` | The engine SDK's `atomo` commands (`run-lua`, `run-lua-client [id]`, `errors`) in atomo's own output format, for tools written against atomo such as the starter builder. The folder's `./atomo` calls this; a bridge timeout exits 3. |
|
|
132
160
|
| `screenshot [dir] [-o out.png] [--client <id>]` | Capture the engine's view; `--client` captures through a connected client, UI included. |
|
|
133
161
|
| `mcp [dir] [--framing <id>]` | Run the stdio MCP server. |
|
|
@@ -148,7 +176,10 @@ deploying it.
|
|
|
148
176
|
harness files the CLI writes (`AGENTS.md`, `CLAUDE.md`, `.mcp.json`,
|
|
149
177
|
`.cursor/`, `.codex/`, `.virtualmatter.json`), and the SDK's in-session tooling at the
|
|
150
178
|
Montage root (`atomo`, `vm_auth.py`, the agent-log hooks) - those only work
|
|
151
|
-
inside a running session.
|
|
179
|
+
inside a running session. It also skips files that exist only mid-write:
|
|
180
|
+
its own `*.vmdownload-*` download temps (a run that was killed leaves them;
|
|
181
|
+
the next sync removes them) and anything ending in `~`, such as the
|
|
182
|
+
engine's `<name>.am~` save temp.
|
|
152
183
|
- The pulled `AGENTS.md` is the platform guide followed by the world's own
|
|
153
184
|
engine SDK guide (its Skills/ table and engine rules), with a header that
|
|
154
185
|
maps every `atomo` command the engine guide mentions to the CLI or MCP
|
package/dist/agent-logs.js
CHANGED
|
@@ -66,6 +66,12 @@ export function enqueue(dir, harness, session, events) {
|
|
|
66
66
|
let queued = 0;
|
|
67
67
|
let batch = [];
|
|
68
68
|
let size = 0;
|
|
69
|
+
// Upload order comes from this persisted counter, not file mtimes: one
|
|
70
|
+
// capture writes its batches within a millisecond or two, and on a
|
|
71
|
+
// filesystem with coarse timestamps they tie, leaving readdir order to
|
|
72
|
+
// decide which half of a conversation reaches the world first.
|
|
73
|
+
const seqFile = path.join(logDir(dir), "seq.json");
|
|
74
|
+
let nextSeq = Number(readJson(seqFile)?.next) || 0;
|
|
69
75
|
const commit = () => {
|
|
70
76
|
if (!batch.length)
|
|
71
77
|
return;
|
|
@@ -81,7 +87,9 @@ export function enqueue(dir, harness, session, events) {
|
|
|
81
87
|
const root = logDir(dir);
|
|
82
88
|
if (!fs.existsSync(path.join(root, "receipts", id)) &&
|
|
83
89
|
!fs.existsSync(path.join(root, "pending", id + ".json"))) {
|
|
84
|
-
|
|
90
|
+
const pending = { ...envelope, seq: nextSeq++ };
|
|
91
|
+
writeJson(seqFile, { next: nextSeq });
|
|
92
|
+
writeJson(path.join(root, "pending", id + ".json"), pending);
|
|
85
93
|
queued += batch.length;
|
|
86
94
|
}
|
|
87
95
|
batch = [];
|
|
@@ -164,20 +172,40 @@ async function flushUnlocked(dir, send) {
|
|
|
164
172
|
const root = logDir(dir), pending = path.join(root, "pending");
|
|
165
173
|
if (!fs.existsSync(pending))
|
|
166
174
|
return 0;
|
|
175
|
+
// Queue order: `seq`, then mtime, then name. A batch queued before `seq`
|
|
176
|
+
// existed sorts first, since it is older than any batch that has one.
|
|
167
177
|
const files = fs
|
|
168
178
|
.readdirSync(pending)
|
|
169
179
|
.filter((f) => f.endsWith(".json"))
|
|
170
|
-
.
|
|
171
|
-
|
|
180
|
+
.map((name) => {
|
|
181
|
+
const file = path.join(pending, name);
|
|
182
|
+
let seq = -1;
|
|
183
|
+
let mtime = 0;
|
|
184
|
+
try {
|
|
185
|
+
const n = Number(readJson(file)?.seq);
|
|
186
|
+
if (Number.isFinite(n))
|
|
187
|
+
seq = n;
|
|
188
|
+
mtime = fs.statSync(file).mtimeMs;
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
/* acknowledged by another flusher, or unreadable: the loop decides */
|
|
192
|
+
}
|
|
193
|
+
return { name, seq, mtime };
|
|
194
|
+
})
|
|
195
|
+
.sort((a, b) => a.seq - b.seq ||
|
|
196
|
+
a.mtime - b.mtime ||
|
|
197
|
+
(a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
|
|
198
|
+
.map((f) => f.name);
|
|
172
199
|
if (!files.length)
|
|
173
200
|
return 0;
|
|
174
201
|
let base;
|
|
175
202
|
let sent = 0;
|
|
176
203
|
for (const name of files) {
|
|
177
204
|
const file = path.join(pending, name);
|
|
178
|
-
const
|
|
179
|
-
if (!
|
|
205
|
+
const stored = readJson(file);
|
|
206
|
+
if (!stored)
|
|
180
207
|
continue; // another flushing process already acknowledged it
|
|
208
|
+
const { seq: _seq, ...e } = stored;
|
|
181
209
|
if (e.version !== 1 ||
|
|
182
210
|
e.api !== apiBase() ||
|
|
183
211
|
e.framing !== requireState(dir).framing_id)
|
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
// frontend/content/agent-briefing.md and AGENTS.source.md. The CLI writes
|
|
4
4
|
// this into a world folder only when it cannot fetch the live copy. After
|
|
5
5
|
// changing either source, run: node frontend/scripts/sync-cli-agents-md.mjs
|
|
6
|
-
export const AGENTS_MD_FALLBACK = "# AGENTS.md - working with a Virtual Matter project\n\nThis file tells a coding agent how to think about a Virtual Matter project. The\n`virtualmatter` CLI drops a copy into every local project mirror it creates\n(`virtualmatter pull`); the canonical copy lives at\nhttps://make.virtualmatter.ai/AGENTS.md.\n\n## The rule that comes before everything else\n\n**Build through the CLI. Never through the website's agent.** If you were asked to\nbuild something in Virtual Matter, handed the domain virtualmatter.ai, or told to run\n`npx virtualmatter make`, the CLI is the path - always, from the first step. Do not\nopen virtualmatter.ai or make.virtualmatter.ai in a browser or under computer use in\norder to reach the built-in agent, and do not type prompts into the agent chat in the\n/edit view. Driving that agent puts two models in a relay where one would do: you spend\ntokens describing the work, it spends its own doing it, and what comes back is chat\nrather than files you can read. It is slower, it costs roughly twice the inference, it\nbills that inference to Virtual Matter's platform credits rather than the subscription\nyou already run on, an anonymous browser session cannot be steered after its first\nturn, and a rendered page gives you no engine errors. Everything that agent can do, you\ndo yourself with the commands below.\n\n**The rule holds whoever is signed in.** Being logged in, having credits to spare, or\nworking in an admin account with no limit at all is not an exemption, and neither is\nbeing told the credits do not matter. What is wasteful is the relay itself - two models\ndoing one model's job - not the bill.\n\n**Playtesting is the exception, and it is encouraged.** Once something is built, open\nthe world and try it: the editor link ending in `?chat=closed`, which `make`, `pull` and\n`sync` print, shows your latest changes live in any browser with no install, with\ncomputer use if that is how you drive a window. The native client\n(`npx virtualmatter open`) is optional, for more memory and frame rate. Looking at your\nwork, walking around in it, and playing it is the point. The rule is about who writes\nthe world, not about who is allowed to see it.\n\n**Every link resolves to the editor, and the editor is the only place you build.** Hand\nthe CLI or MCP server any link to a world - its editor, a play or share link, the\nproject page, an embed's iframe src, or the maker's own website - and it works on that\nworld's editor (its make framing). Play servers show the last published version and are\noverwritten on every publish, so work never goes there, and their /play and /g links\nshow that published copy rather than your latest edits.\n\n## The mental model\n\n- The world itself runs on Virtual Matter servers, not on the maker's machine. There is\n one authoritative server simulation per world session, and any number of connected\n clients (browser WASM or the native client).\n- The project's content is SDK Lua scripts plus assets (voxel data, prefabs, images,\n sounds) under a `Montage/` tree. Virtual Matter can publish that tree to a GitHub repo\n in the maker's account for versioning and remixing; pushing to that repo does not feed\n back into the running world today - live edits happen in the session.\n- Changes hot-reload. Saving a `.lua` file in the live session's Montage tree re-runs\n the module and its `Start()` on a fresh instance inside the running world - no restart,\n no build step.\n- Prefabs are reusable scene-graph snippets: JSON files with a `.prefab` extension in the\n Montage folder, instantiated at runtime via `Server:InsertPrefab(asset)`.\n- There is no local runtime - the world cannot run on the maker's machine. The\n `virtualmatter` CLI (npm) is how you reach it from a local harness, and it needs no\n setup: the first command that needs an account signs you in with a device code.\n `npx virtualmatter make \"My world\"` makes a world and mirrors its Montage tree\n into `./my-world`; `npx virtualmatter pull <any Virtual Matter link>` mirrors an\n existing one (/edit, /play, /g, /p, /projects links all work, with or without a\n readable slug); `npx virtualmatter list` shows your worlds; `npx virtualmatter sync`\n live-pushes saves into the running session (which hot-reloads them);\n `npx virtualmatter run-lua` / `errors` / `screenshot` drive the engine;\n `npx virtualmatter open` optionally opens the world in the native desktop client,\n downloaded and signed in on first use; and `npx virtualmatter mcp` serves\n all of it over MCP. A mirrored folder carries `.mcp.json` and `.cursor/mcp.json`\n (so Claude Code and Cursor register the MCP server on their own), this file, and a\n `CLAUDE.md` that imports it. Folders from virtualmatter 0.5.0 on also carry\n `.codex/config.toml`, which Codex loads once you trust the folder; with an older\n CLI, or if Codex does not list the server, register it once with\n `codex mcp add virtualmatter -- npx -y virtualmatter mcp`. In Claude Code outside a\n mirrored folder, use `claude mcp add virtualmatter -- npx -y virtualmatter mcp`. The\n server works before a world\n is selected (`list_projects`, `create_project`, `select_project`), then exposes\n `list_files`, `read_file`, `write_file`, `run_lua`, `get_engine_errors`,\n `capture_screenshot`, `open_native_client`, and `world_info`.\n- Work through the CLI, not the website - see the rule above. Prompting the built-in\n agent to do your building is the one thing to avoid; opening the world to play it is\n not.\n- Seeing your work: `virtualmatter screenshot` shoots a default overview of the world\n origin, `--target <object>` frames one object by name or id, and `--at x,y,z --rot\n yaw,pitch,roll` places the camera exactly. Y is up and -Z is forward, and the\n rotation really is yaw first: yaw 0 faces -Z, pitch -90 looks straight down, pitch 0\n is the horizon. The MCP `capture_screenshot`\n tool takes the same arguments. Verify a change with a screenshot plus `errors` rather\n than assuming a write worked.\n- A `run-lua` that fails with HTTP 504 (`run-lua timed out`, exit code 3 from CLI\n 0.6.4 on; the MCP `run_lua` tool returns the same text) reached the engine, which\n may still be running it. Do not send code that changes the world again: check its\n effect first, by reading back what it sets or taking a screenshot. Any other\n failure never reached the engine and is safe to retry.\n- The mirrored folder's AGENTS.md is this guide followed by the engine SDK's own agent guide\n (the AGENTS.md that lives in every Montage tree and inside the desktop client's\n Data/Sdk/Montage/). The engine guide assumes an in-session agent driving the engine\n through `atomo`; the merged file maps each `atomo` step to the CLI or MCP equivalent, and\n the `Skills/*.md` references it points at are in the folder. The SDK's own tooling\n (`atomo`, `vm_auth.py`, the agent-log hooks) is not mirrored: it only works inside a\n session. From CLI 0.6.5 on, macOS and Linux folders get their own `./atomo`, which\n serves the guide's `./atomo run-lua`, `run-lua-client` and `errors` through the CLI.\n Sandboxed agents need network access for every CLI command.\n- Worlds with the platform's skill packages carry them in `Skills/atomontage-*`.\n From CLI 0.6.5 on, `pull` and `sync` also copy them into `.claude/skills/`, so Claude\n Code loads them as skills; other harnesses follow the routing table in AGENTS.md.\n Start from `atomontage-game-starters` for any of the 15 homepage starter games: its\n `starterctl.py build <preset>` builds a playable starter in seconds through\n `./atomo`. Where a skill says to hand a live check to the in-game agent, run it\n yourself: never send prompts to the world's built-in agent.\n\n## Reference\n\nThe same facts as terse lists, for quick lookup.\n\n### Project model\n- A project (\"montage\") is one voxel world hosted with Virtual Matter.\n- A project has framings: \"make\" framings (editing sessions) and \"play\"\n framings (public play sessions). A framing is a running session slot\n on a voxel host.\n- Project content = SDK Lua scripts + assets under a Montage/ tree.\n Edits made in the live session hot-reload into the running world.\n The tree can be published to a maker-owned GitHub repo.\n\n### URL shapes (make.virtualmatter.ai)\n- /new builder for people: create a world from a prompt\n (also at https://virtualmatter.ai/); coding agents\n use npx virtualmatter make instead\n- /edit/<framing-id> maker session: live world + agent chat. The chat is\n for people; a coding agent builds with the CLI and\n never prompts it\n (also /edit/<slug>-<framing-id>; the CLI accepts both)\n- /play/<framing-id> play session for a specific framing\n- /g/<id> share URL resolver: 302s to a live session\n\n### APIs (unauthenticated)\n- GET https://make.virtualmatter.ai/api/v1/public/native-clients\n JSON: { iteration, clients: [{ platform, kind, variant, url, filename,\n file_size, branch, commit, match }] } - per-platform native client\n installers (kind \"download\") or store links (kind \"store\", iOS).\n Windows and Linux list two downloads each: variant \"installer\" /\n \"flatpak\" for people, and \"portable\" / \"tarball\", the file tree the\n CLI installs.\n\n### CLI + MCP (npm package \"virtualmatter\", Node >= 20)\n- npx virtualmatter make \"<name>\" make a world, mirror it into ./<slug>\n- npx virtualmatter pull <link> mirror an existing world (any link shape)\n- npx virtualmatter list your worlds with framing ids + URLs\n- npx virtualmatter sync live-push saves into the running world\n- npx virtualmatter open optional: open it in the native client\n- npx virtualmatter mcp stdio MCP server (list_projects,\n create_project, select_project, list_files, read_file, write_file,\n run_lua, get_engine_errors, capture_screenshot, open_native_client,\n world_info)\n- Sign-in happens on first use (device code); no separate login step.\n- These commands are the whole build path. Never prompt the built-in\n agent on the site to do the work; a browser or the native client is\n for playtesting what you built.\n- Any link to a world (editor, play or share link, project page, embed,\n or the maker's own website) resolves to its editor, the only place\n the CLI and MCP server work. Play servers show the last published\n version and are overwritten on publish.\n- Watch changes land live at the editor link ending in ?chat=closed,\n in any browser, no install. The native client is optional.\n- A mirrored folder carries .mcp.json, .cursor/mcp.json, AGENTS.md and\n CLAUDE.md, so Claude Code and Cursor register the server on their own.\n- Codex: folders from 0.5.0 on carry .codex/config.toml, loaded once the\n folder is trusted; otherwise register the server once:\n codex mcp add virtualmatter -- npx -y virtualmatter mcp\n\n## SDK Lua cheat sheet\n\nThe scripting language is Lua 5.4, sandboxed: `os`, `io`, `require`, `package`,\n`dofile`, `loadfile`, `loadstring` are nil. `math`, `string`, `table`, `coroutine`\nremain. No `os.time` - use `Time.time` (sim time), `Time.frame`, or\n`AE:GetDebugTime()` (wall clock).\n\n### Script shape\n\nEvery persistent behavior is a `.lua` file in the Montage tree returning a `self` table:\n\n```lua\nlocal self = {}\nfunction self:Start() end\nfunction self:Update(deltaTime) end\nreturn self\n```\n\nAttach to an object with `obj:AddScript(\"My Folder/Example.lua\", sync)` - the path is\nrelative to the Montage root; `sync = true` replicates the script to clients.\n`obj:FindScript(\"Example\")` returns the live instance.\n\n### Server / client split\n\nThe same script runs on the server and (when synced) on every client. Branch with\n`self.onServer` / `self.onClient`:\n\n```lua\nfunction self:Update(dt)\n if self.onClient then return end -- voxel edits are server-only\n -- authoritative logic here\nend\n```\n\nNothing replicates automatically: set `syncToClients = true` on the script or\nVoxelData component, and use `util:makeNetworkedTable(self, { hp = 100 })` for\nproperties that should sync (server writes, clients read, deltas only).\n`obj.pos` / `obj.rot` do not auto-sync - replicate them yourself.\n\n### RPC\n\n```lua\nself:RPC(\"serverDoSomething\", pos, dir) -- on a client: goes to the server\nfunction self:serverDoSomething(pos, dir, clientID) -- clientID auto-appended\n assert(self.onServer)\nend\n```\n\nOn the server, `self:RPC(...)` fans out to all clients. Reliable, FIFO per direction.\nRequires `self.component.syncToClients = true`.\n\n### Scene and objects (server)\n\n```lua\nlocal ob = Scene:CreateObject(\"Name\")\nob.save = true\nob:AddScript(\"Path/Script.lua\")\nScene:GetObjectByName(\"Name\")\nScene:CloneObject(ob) -- prefer over rebuilding\nob.active = false -- prefer over destroy\nob:AddTag(\"Enemy\"); FindObjectsWithTag(\"Enemy\") -- tags are runtime-only state\n```\n\n### Voxel editing (server only, async)\n\n```lua\nVox:Add(Sphere(pos, 2)):Color(1, 0, 0):Run()\nVox:Add(Box(Vec3(0, -1, 0), Vec3(20, 2, 20))):ForceStatic():Run()\n```\n\nShapes: `Box(center, fullSize)`, `Sphere(center, r)`, `Capsule(p1, p2, r)`,\n`Cylinder(p1, p2, r1[, r2])`. `Run()` is async - chain `:OnFinished(fn)` before\n`:Run()` to read post-commit state. Big edits stall the frame for every client;\nkeep in-game edits small and infrequent.\n\n### Input (event-driven, client input reaches the server)\n\n```lua\nself.component.syncToClients = true\nevents.keyDown.addListener(self, function(key, from) self.keys[key] = true end)\nevents.keyUp.addListener(self, function(key, from) self.keys[key] = false end)\n```\n\nPlayer-driven movement must be client-predicted - never gate the player's own\nfeedback on the server round-trip.\n\n### Physics\n\n```lua\nlocal rb = obj:AddComponent(\"RigidBody\")\nrb:AddImpulse(Vec3(0, 50, 0), obj.pos)\nrb.velocity; rb.mass; rb.gravityScale\n```\n\n### Time and diagnostics\n\n```lua\nTime.dt; Time.time; Time.frame; Time.timeScale\nAE:GetLogValue(\"Raycasts\") -- engine counters, e.g. raycasts this frame\nAE:GetAssets() -- list all assets (APIs take Assets, not paths)\n```\n\n### UI (client-side HUD)\n\nBuild screen UI with the MUI builder: `UI:AddPanel|AddButton|AddLabel|AddSlider|...`\nchained with `:Set{...}`; flexbox-like row-wrap layout.\n\n## Conventions\n\n- Coordinates: Y is up, -Z is forward, X is right.\n- Script files are named in capital case with spaces (`Character Controller.lua`).\n- Check whether a script is already attached before adding it - duplicates run twice.\n- The server is for authority (world edits, spawns, state); clients are for feel\n (prediction, FX, UI).\n\n## Embed or build a world for an existing website\n\nFor a shared project link, fetch `/api/v1/public/embed?target=<encoded-link>`\nand follow `/embed-guide.md`. Use the returned canonical player URL, not the\nmaker's external website URL. Keep the existing website and its design.\n\nFor account discovery or prompt-based creation, connect the hosted MCP at\n`https://make.virtualmatter.ai/api/v1/mcp` using OAuth. Users can sign up in\nthe connection flow. Tools: `list_projects`, `get_embed`, `create_project`\n(with a prompt and stable request_id), `get_build_status`. VM's agent builds\nusing VM credits. Review and share the private world before embedding.\nThe local CLI exposes `embed`, `build --prompt --request-id`, and `build-status`.\n\n## Local conversation history\n\nCapturing this harness's conversation into the world's Agent Logs is the maker's\ndecision, not yours. Do not run `virtualmatter agent-logs setup`, and do not upload\nlogs with `agent-logs upload` or MCP `upload_agent_logs`, unless the maker asks for it\nin their own words. `virtualmatter agent-logs status` shows whether capture is on;\n`virtualmatter agent-logs disable` turns it off.\n";
|
|
6
|
+
export const AGENTS_MD_FALLBACK = "# AGENTS.md - working with a Virtual Matter project\n\nThis file tells a coding agent how to think about a Virtual Matter project. The\n`virtualmatter` CLI drops a copy into every local project mirror it creates\n(`virtualmatter pull`); the canonical copy lives at\nhttps://make.virtualmatter.ai/AGENTS.md.\n\n## The rule that comes before everything else\n\n**Build through the CLI. Never through the website's agent.** If you were asked to\nbuild something in Virtual Matter, handed the domain virtualmatter.ai, or told to run\n`npx virtualmatter make`, the CLI is the path - always, from the first step. Do not\nopen virtualmatter.ai or make.virtualmatter.ai in a browser or under computer use in\norder to reach the built-in agent, and do not type prompts into the agent chat in the\n/edit view. Driving that agent puts two models in a relay where one would do: you spend\ntokens describing the work, it spends its own doing it, and what comes back is chat\nrather than files you can read. It is slower, it costs roughly twice the inference, it\nbills that inference to Virtual Matter's platform credits rather than the subscription\nyou already run on, an anonymous browser session cannot be steered after its first\nturn, and a rendered page gives you no engine errors. Everything that agent can do, you\ndo yourself with the commands below.\n\n**The rule holds whoever is signed in.** Being logged in, having credits to spare, or\nworking in an admin account with no limit at all is not an exemption, and neither is\nbeing told the credits do not matter. What is wasteful is the relay itself - two models\ndoing one model's job - not the bill.\n\n**Playtesting is the exception, and it is encouraged.** Once something is built, open\nthe world and try it: the editor link ending in `?chat=closed`, which `make`, `pull` and\n`sync` print, shows your latest changes live in any browser with no install, with\ncomputer use if that is how you drive a window. The native client\n(`npx virtualmatter open`) is optional, for more memory and frame rate. Looking at your\nwork, walking around in it, and playing it is the point. The rule is about who writes\nthe world, not about who is allowed to see it.\n\n**Every link resolves to the editor, and the editor is the only place you build.** Hand\nthe CLI or MCP server any link to a world - its editor, a play or share link, the\nproject page, an embed's iframe src, or the maker's own website - and it works on that\nworld's editor (its make framing). Play servers show the last published version and are\noverwritten on every publish, so work never goes there, and their /play and /g links\nshow that published copy rather than your latest edits.\n\n## The mental model\n\n- The world itself runs on Virtual Matter servers, not on the maker's machine. There is\n one authoritative server simulation per world session, and any number of connected\n clients (browser WASM or the native client).\n- The project's content is SDK Lua scripts plus assets (voxel data, prefabs, images,\n sounds) under a `Montage/` tree. Virtual Matter can publish that tree to a GitHub repo\n in the maker's account for versioning and remixing; pushing to that repo does not feed\n back into the running world today - live edits happen in the session.\n- Changes hot-reload. Saving a `.lua` file in the live session's Montage tree re-runs\n the module and its `Start()` on a fresh instance inside the running world - no restart,\n no build step.\n- Prefabs are reusable scene-graph snippets: JSON files with a `.prefab` extension in the\n Montage folder, instantiated at runtime via `Server:InsertPrefab(asset)`.\n- There is no local runtime - the world cannot run on the maker's machine. The\n `virtualmatter` CLI (npm) is how you reach it from a local harness, and it needs no\n setup: the first command that needs an account signs you in with a device code.\n `npx virtualmatter make \"My world\"` makes a world and mirrors its Montage tree\n into `./my-world`; `npx virtualmatter pull <any Virtual Matter link>` mirrors an\n existing one (/edit, /play, /g, /p, /projects links all work, with or without a\n readable slug); `npx virtualmatter list` shows your worlds; `npx virtualmatter sync`\n live-pushes saves into the running session (which hot-reloads them), and\n `npx virtualmatter push <files>` deploys named files once, reporting each one - the\n better fit for an agent that saves in quick succession (each script write resets the\n world's Lua, and push skips files that did not change);\n `npx virtualmatter run-lua` / `errors` / `screenshot` drive the engine;\n `npx virtualmatter open` optionally opens the world in the native desktop client,\n downloaded and signed in on first use; and `npx virtualmatter mcp` serves\n all of it over MCP. A mirrored folder carries `.mcp.json` and `.cursor/mcp.json`\n (so Claude Code and Cursor register the MCP server on their own), this file, and a\n `CLAUDE.md` that imports it. Folders from virtualmatter 0.5.0 on also carry\n `.codex/config.toml`, which Codex loads once you trust the folder; with an older\n CLI, or if Codex does not list the server, register it once with\n `codex mcp add virtualmatter -- npx -y virtualmatter mcp`. In Claude Code outside a\n mirrored folder, use `claude mcp add virtualmatter -- npx -y virtualmatter mcp`. The\n server works before a world\n is selected (`list_projects`, `create_project`, `select_project`), then exposes\n `list_files`, `read_file`, `write_file`, `run_lua`, `get_engine_errors`,\n `capture_screenshot`, `open_native_client`, and `world_info`.\n- Work through the CLI, not the website - see the rule above. Prompting the built-in\n agent to do your building is the one thing to avoid; opening the world to play it is\n not.\n- Seeing your work: `virtualmatter screenshot` shoots a default overview of the world\n origin, `--target <object>` frames one object by name or id, and `--at x,y,z --rot\n yaw,pitch,roll` places the camera exactly. Y is up and -Z is forward, and the\n rotation really is yaw first: yaw 0 faces -Z, pitch -90 looks straight down, pitch 0\n is the horizon. The MCP `capture_screenshot`\n tool takes the same arguments. Verify a change with a screenshot plus `errors` rather\n than assuming a write worked.\n- A `run-lua` that fails with HTTP 504 (`run-lua timed out`, exit code 3 from CLI\n 0.6.4 on; the MCP `run_lua` tool returns the same text) reached the engine, which\n may still be running it. Do not send code that changes the world again: check its\n effect first, by reading back what it sets or taking a screenshot. Any other\n failure never reached the engine and is safe to retry.\n- The mirrored folder's AGENTS.md is this guide followed by the engine SDK's own agent guide\n (the AGENTS.md that lives in every Montage tree and inside the desktop client's\n Data/Sdk/Montage/). The engine guide assumes an in-session agent driving the engine\n through `atomo`; the merged file maps each `atomo` step to the CLI or MCP equivalent, and\n the `Skills/*.md` references it points at are in the folder. The SDK's own tooling\n (`atomo`, `vm_auth.py`, the agent-log hooks) is not mirrored: it only works inside a\n session. From CLI 0.6.5 on, macOS and Linux folders get their own `./atomo`, which\n serves the guide's `./atomo run-lua`, `run-lua-client` and `errors` through the CLI.\n Sandboxed agents need network access for every CLI command.\n- Worlds with the platform's skill packages carry them in `Skills/atomontage-*`.\n From CLI 0.6.5 on, `pull` and `sync` also copy them into `.claude/skills/`, so Claude\n Code loads them as skills; other harnesses follow the routing table in AGENTS.md.\n Start from `atomontage-game-starters` for any of the 15 homepage starter games: its\n `starterctl.py build <preset>` builds a playable starter in seconds through\n `./atomo`. Where a skill says to hand a live check to the in-game agent, run it\n yourself: never send prompts to the world's built-in agent.\n\n## Reference\n\nThe same facts as terse lists, for quick lookup.\n\n### Project model\n- A project (\"montage\") is one voxel world hosted with Virtual Matter.\n- A project has framings: \"make\" framings (editing sessions) and \"play\"\n framings (public play sessions). A framing is a running session slot\n on a voxel host.\n- Project content = SDK Lua scripts + assets under a Montage/ tree.\n Edits made in the live session hot-reload into the running world.\n The tree can be published to a maker-owned GitHub repo.\n\n### URL shapes (make.virtualmatter.ai)\n- /new builder for people: create a world from a prompt\n (also at https://virtualmatter.ai/); coding agents\n use npx virtualmatter make instead\n- /edit/<framing-id> maker session: live world + agent chat. The chat is\n for people; a coding agent builds with the CLI and\n never prompts it\n (also /edit/<slug>-<framing-id>; the CLI accepts both)\n- /play/<framing-id> play session for a specific framing\n- /g/<id> share URL resolver: 302s to a live session\n\n### APIs (unauthenticated)\n- GET https://make.virtualmatter.ai/api/v1/public/native-clients\n JSON: { iteration, clients: [{ platform, kind, variant, url, filename,\n file_size, branch, commit, match }] } - per-platform native client\n installers (kind \"download\") or store links (kind \"store\", iOS).\n Windows and Linux list two downloads each: variant \"installer\" /\n \"flatpak\" for people, and \"portable\" / \"tarball\", the file tree the\n CLI installs.\n\n### CLI + MCP (npm package \"virtualmatter\", Node >= 20)\n- npx virtualmatter make \"<name>\" make a world, mirror it into ./<slug>\n- npx virtualmatter pull <link> mirror an existing world (any link shape)\n- npx virtualmatter list your worlds with framing ids + URLs\n- npx virtualmatter sync live-push saves into the running world\n (one per folder; does not pull files too\n large to push back, such as terrain)\n- npx virtualmatter push [files] one-shot deploy, per-file result; exit 1\n on any conflict or failure\n- npx virtualmatter fetch [files] one-shot download; never overwrites\n local edits (conflict -> .remote-conflict)\n- npx virtualmatter logs --restarts why the world restarted (crash + last\n log lines, or the platform's reason)\n- npx virtualmatter publish update the play servers; reports each\n server, says which scene they load\n- npx virtualmatter status play servers vs the editor, last update\n- npx virtualmatter open optional: open it in the native client\n- npx virtualmatter mcp stdio MCP server (list_projects,\n create_project, select_project, list_files, read_file, write_file,\n patch_file, push_local_files, fetch_files, run_lua, get_engine_errors,\n get_engine_logs, capture_screenshot, play_server_status,\n publish_play_servers, open_native_client, world_info)\n- Sign-in happens on first use (device code); no separate login step.\n- These commands are the whole build path. Never prompt the built-in\n agent on the site to do the work; a browser or the native client is\n for playtesting what you built.\n- Any link to a world (editor, play or share link, project page, embed,\n or the maker's own website) resolves to its editor, the only place\n the CLI and MCP server work. Play servers show the last published\n version and are overwritten on publish.\n- Watch changes land live at the editor link ending in ?chat=closed,\n in any browser, no install. The native client is optional.\n- A mirrored folder carries .mcp.json, .cursor/mcp.json, AGENTS.md and\n CLAUDE.md, so Claude Code and Cursor register the server on their own.\n- Codex: folders from 0.5.0 on carry .codex/config.toml, loaded once the\n folder is trusted; otherwise register the server once:\n codex mcp add virtualmatter -- npx -y virtualmatter mcp\n\n## SDK Lua cheat sheet\n\nThe scripting language is Lua 5.4, sandboxed: `os`, `io`, `require`, `package`,\n`dofile`, `loadfile`, `loadstring` are nil. `math`, `string`, `table`, `coroutine`\nremain. No `os.time` - use `Time.time` (sim time), `Time.frame`, or\n`AE:GetDebugTime()` (wall clock).\n\n### Script shape\n\nEvery persistent behavior is a `.lua` file in the Montage tree returning a `self` table:\n\n```lua\nlocal self = {}\nfunction self:Start() end\nfunction self:Update(deltaTime) end\nreturn self\n```\n\nAttach to an object with `obj:AddScript(\"My Folder/Example.lua\", sync)` - the path is\nrelative to the Montage root; `sync = true` replicates the script to clients.\n`obj:FindScript(\"Example\")` returns the live instance.\n\n### Server / client split\n\nThe same script runs on the server and (when synced) on every client. Branch with\n`self.onServer` / `self.onClient`:\n\n```lua\nfunction self:Update(dt)\n if self.onClient then return end -- voxel edits are server-only\n -- authoritative logic here\nend\n```\n\nNothing replicates automatically: set `syncToClients = true` on the script or\nVoxelData component, and use `util:makeNetworkedTable(self, { hp = 100 })` for\nproperties that should sync (server writes, clients read, deltas only).\n`obj.pos` / `obj.rot` do not auto-sync - replicate them yourself.\n\n### RPC\n\n```lua\nself:RPC(\"serverDoSomething\", pos, dir) -- on a client: goes to the server\nfunction self:serverDoSomething(pos, dir, clientID) -- clientID auto-appended\n assert(self.onServer)\nend\n```\n\nOn the server, `self:RPC(...)` fans out to all clients. Reliable, FIFO per direction.\nRequires `self.component.syncToClients = true`.\n\n### Scene and objects (server)\n\n```lua\nlocal ob = Scene:CreateObject(\"Name\")\nob.save = true\nob:AddScript(\"Path/Script.lua\")\nScene:GetObjectByName(\"Name\")\nScene:CloneObject(ob) -- prefer over rebuilding\nob.active = false -- prefer over destroy\nob:AddTag(\"Enemy\"); FindObjectsWithTag(\"Enemy\") -- tags are runtime-only state\n```\n\n### Voxel editing (server only, async)\n\n```lua\nVox:Add(Sphere(pos, 2)):Color(1, 0, 0):Run()\nVox:Add(Box(Vec3(0, -1, 0), Vec3(20, 2, 20))):ForceStatic():Run()\n```\n\nShapes: `Box(center, fullSize)`, `Sphere(center, r)`, `Capsule(p1, p2, r)`,\n`Cylinder(p1, p2, r1[, r2])`. `Run()` is async - chain `:OnFinished(fn)` before\n`:Run()` to read post-commit state. Big edits stall the frame for every client;\nkeep in-game edits small and infrequent.\n\n### Input (event-driven, client input reaches the server)\n\n```lua\nself.component.syncToClients = true\nevents.keyDown.addListener(self, function(key, from) self.keys[key] = true end)\nevents.keyUp.addListener(self, function(key, from) self.keys[key] = false end)\n```\n\nPlayer-driven movement must be client-predicted - never gate the player's own\nfeedback on the server round-trip.\n\n### Physics\n\n```lua\nlocal rb = obj:AddComponent(\"RigidBody\")\nrb:AddImpulse(Vec3(0, 50, 0), obj.pos)\nrb.velocity; rb.mass; rb.gravityScale\n```\n\n### Time and diagnostics\n\n```lua\nTime.dt; Time.time; Time.frame; Time.timeScale\nAE:GetLogValue(\"Raycasts\") -- engine counters, e.g. raycasts this frame\nAE:GetAssets() -- list all assets (APIs take Assets, not paths)\n```\n\n### UI (client-side HUD)\n\nBuild screen UI with the MUI builder: `UI:AddPanel|AddButton|AddLabel|AddSlider|...`\nchained with `:Set{...}`; flexbox-like row-wrap layout.\n\n## 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/files.js
CHANGED
|
@@ -7,7 +7,8 @@ import fs from "node:fs";
|
|
|
7
7
|
import path from "node:path";
|
|
8
8
|
import { Readable, Transform } from "node:stream";
|
|
9
9
|
import { pipeline } from "node:stream/promises";
|
|
10
|
-
import { authorizedFetch } from "./api.js";
|
|
10
|
+
import { authorizedFetch, resolveSession, sessionBaseUrl } from "./api.js";
|
|
11
|
+
import { DOWNLOAD_TEMP_MARKER } from "./ignore.js";
|
|
11
12
|
/**
|
|
12
13
|
* The session API's per-write cap (session-agent server/api/files.py
|
|
13
14
|
* MAX_WRITE_BYTES). A bigger PUT is answered 413, so sync skips such files
|
|
@@ -66,6 +67,28 @@ const RUN_LUA_TIMEOUT = "The engine did not answer in time; it may still be runn
|
|
|
66
67
|
/** How long `engineErrors` waits before each retry of a 503/504; it only reads. */
|
|
67
68
|
const READ_RETRY_DELAYS_MS = [1_000, 3_000];
|
|
68
69
|
const defaultSleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
70
|
+
/**
|
|
71
|
+
* run-lua failed on the network after the request may have gone out ("fetch
|
|
72
|
+
* failed" with no HTTP status). Like a 504, the snippet may or may not have
|
|
73
|
+
* run, so it shares EngineTimeoutError's exit code and is never resent.
|
|
74
|
+
*/
|
|
75
|
+
export class OutcomeUnknownError extends EngineTimeoutError {
|
|
76
|
+
constructor(message) {
|
|
77
|
+
super(message);
|
|
78
|
+
this.name = "OutcomeUnknownError";
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* The session this client talked to refused it and re-resolving the world's
|
|
83
|
+
* session did not help (still 401/403). Long-running callers must stop on
|
|
84
|
+
* this rather than keep "pushing" into a session that drops every write.
|
|
85
|
+
*/
|
|
86
|
+
export class SessionLostError extends Error {
|
|
87
|
+
constructor(message) {
|
|
88
|
+
super(message);
|
|
89
|
+
this.name = "SessionLostError";
|
|
90
|
+
}
|
|
91
|
+
}
|
|
69
92
|
export class ConflictError extends Error {
|
|
70
93
|
filePath;
|
|
71
94
|
constructor(filePath) {
|
|
@@ -74,6 +97,44 @@ export class ConflictError extends Error {
|
|
|
74
97
|
this.name = "ConflictError";
|
|
75
98
|
}
|
|
76
99
|
}
|
|
100
|
+
/** Waits before each retry of a request that failed on the network. */
|
|
101
|
+
const NETWORK_RETRY_DELAYS_MS = [1_000, 3_000];
|
|
102
|
+
/**
|
|
103
|
+
* Network error codes that mean the request never left this machine or never
|
|
104
|
+
* reached the server, so resending cannot run anything twice.
|
|
105
|
+
*/
|
|
106
|
+
const NOT_SENT_CODES = new Set([
|
|
107
|
+
"ECONNREFUSED",
|
|
108
|
+
"ENOTFOUND",
|
|
109
|
+
"EAI_AGAIN",
|
|
110
|
+
"EHOSTUNREACH",
|
|
111
|
+
"ENETUNREACH",
|
|
112
|
+
"UND_ERR_CONNECT_TIMEOUT",
|
|
113
|
+
]);
|
|
114
|
+
/** A fetch rejection (undici's `TypeError: fetch failed`) rather than an HTTP answer. */
|
|
115
|
+
export function isNetworkError(err) {
|
|
116
|
+
return err instanceof TypeError && /fetch failed/i.test(err.message);
|
|
117
|
+
}
|
|
118
|
+
/** Whether a network failure provably happened before the request reached the server. */
|
|
119
|
+
export function failedBeforeSending(err) {
|
|
120
|
+
if (!isNetworkError(err))
|
|
121
|
+
return false;
|
|
122
|
+
const cause = err.cause;
|
|
123
|
+
const code = cause && typeof cause.code === "string" ? cause.code : "";
|
|
124
|
+
return NOT_SENT_CODES.has(code);
|
|
125
|
+
}
|
|
126
|
+
function networkErrorText(err) {
|
|
127
|
+
const cause = err.cause;
|
|
128
|
+
const detail = cause?.code ?? cause?.message;
|
|
129
|
+
return `${err instanceof Error ? err.message : String(err)}${detail ? ` (${String(detail)})` : ""}`;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Statuses that can mean the session URL itself is stale: the world's session
|
|
133
|
+
* was replaced (engine restart, cold start on another host) and the old one is
|
|
134
|
+
* gone or no longer serves this montage. A 404 for a missing file looks the
|
|
135
|
+
* same, which is why a retry only happens when re-resolving MOVED the session.
|
|
136
|
+
*/
|
|
137
|
+
const STALE_SESSION_STATUSES = new Set([401, 403, 404, 502, 503]);
|
|
77
138
|
function tooBigToBuffer(filePath, size, limit) {
|
|
78
139
|
const mb = (n) => `${Math.round(n / (1024 * 1024))} MB`;
|
|
79
140
|
return `${filePath} is ${mb(size)}, too large to read into memory (limit ${mb(limit)}). It is in the folder \`virtualmatter pull\` mirrored - read it from disk.`;
|
|
@@ -105,9 +166,10 @@ export function normalizeEtag(v) {
|
|
|
105
166
|
* place, so the target is either the old file or the whole new one - never a
|
|
106
167
|
* truncated half that a later sync would push back as an edit.
|
|
107
168
|
*/
|
|
108
|
-
export async function streamToFile(res, destAbs) {
|
|
169
|
+
export async function streamToFile(res, destAbs, opts = {}) {
|
|
109
170
|
fs.mkdirSync(path.dirname(destAbs), { recursive: true });
|
|
110
|
-
const tmp = `${destAbs}
|
|
171
|
+
const tmp = `${destAbs}${DOWNLOAD_TEMP_MARKER}${process.pid}-${crypto.randomBytes(4).toString("hex")}`;
|
|
172
|
+
let landed = destAbs;
|
|
111
173
|
const hasher = crypto.createHash("sha256");
|
|
112
174
|
let size = 0;
|
|
113
175
|
const tap = new Transform({
|
|
@@ -122,13 +184,51 @@ export async function streamToFile(res, destAbs) {
|
|
|
122
184
|
? Readable.fromWeb(res.body)
|
|
123
185
|
: Readable.from([]);
|
|
124
186
|
await pipeline(source, tap, fs.createWriteStream(tmp));
|
|
125
|
-
|
|
187
|
+
landed = opts.commitPath?.() ?? destAbs;
|
|
188
|
+
fs.renameSync(tmp, landed);
|
|
126
189
|
}
|
|
127
190
|
catch (err) {
|
|
128
191
|
fs.rmSync(tmp, { force: true });
|
|
129
192
|
throw err;
|
|
130
193
|
}
|
|
131
|
-
return { hash: hasher.digest("hex"), size };
|
|
194
|
+
return { hash: hasher.digest("hex"), size, path: landed };
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Remove download temps a killed CLI left behind under `dir`. Only names with
|
|
198
|
+
* the marker are touched, and only ones older than `minAgeMs`, so a download
|
|
199
|
+
* still streaming in another process is safe. Returns the paths removed.
|
|
200
|
+
*/
|
|
201
|
+
export function removeStaleDownloadTemps(dir, minAgeMs = 10 * 60 * 1000, now = Date.now()) {
|
|
202
|
+
const removed = [];
|
|
203
|
+
const walk = (abs) => {
|
|
204
|
+
let entries;
|
|
205
|
+
try {
|
|
206
|
+
entries = fs.readdirSync(abs, { withFileTypes: true });
|
|
207
|
+
}
|
|
208
|
+
catch {
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
for (const e of entries) {
|
|
212
|
+
const full = path.join(abs, e.name);
|
|
213
|
+
if (e.isDirectory()) {
|
|
214
|
+
if (!e.name.startsWith("."))
|
|
215
|
+
walk(full);
|
|
216
|
+
}
|
|
217
|
+
else if (e.isFile() && e.name.includes(DOWNLOAD_TEMP_MARKER)) {
|
|
218
|
+
try {
|
|
219
|
+
if (now - fs.statSync(full).mtimeMs >= minAgeMs) {
|
|
220
|
+
fs.rmSync(full, { force: true });
|
|
221
|
+
removed.push(full);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
catch {
|
|
225
|
+
/* gone already */
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
};
|
|
230
|
+
walk(dir);
|
|
231
|
+
return removed;
|
|
132
232
|
}
|
|
133
233
|
export class FilesClient {
|
|
134
234
|
sessionBase;
|
|
@@ -136,18 +236,85 @@ export class FilesClient {
|
|
|
136
236
|
fetchFn;
|
|
137
237
|
maxBufferedBytes;
|
|
138
238
|
sleep;
|
|
139
|
-
|
|
239
|
+
refresh;
|
|
240
|
+
constructor(sessionBase, framingId, fetchFn = fetch, maxBufferedBytes = MAX_BUFFERED_BYTES, sleep = defaultSleep, refresh = {}) {
|
|
140
241
|
this.sessionBase = sessionBase;
|
|
141
242
|
this.framingId = framingId;
|
|
142
243
|
this.fetchFn = fetchFn;
|
|
143
244
|
this.maxBufferedBytes = maxBufferedBytes;
|
|
144
245
|
this.sleep = sleep;
|
|
246
|
+
this.refresh = refresh;
|
|
247
|
+
}
|
|
248
|
+
/** The session API base this client currently talks to (it moves when the session is re-resolved). */
|
|
249
|
+
get baseUrl() {
|
|
250
|
+
return this.sessionBase;
|
|
145
251
|
}
|
|
146
252
|
get apiRoot() {
|
|
147
253
|
return `${this.sessionBase}/api/montage/${encodeURIComponent(this.framingId)}`;
|
|
148
254
|
}
|
|
255
|
+
/**
|
|
256
|
+
* One request against the session API, `suffix` relative to the montage
|
|
257
|
+
* root. Two failures are handled here so every command gets them:
|
|
258
|
+
*
|
|
259
|
+
* - "fetch failed" with no HTTP status (a dropped connection, a host
|
|
260
|
+
* mid-restart): retried after a pause when resending is safe. For
|
|
261
|
+
* run-lua that means only when the request provably never left; any
|
|
262
|
+
* other network failure becomes OutcomeUnknownError.
|
|
263
|
+
* - A stale session: after an engine restart the old session URL answers
|
|
264
|
+
* 401/403/404/5xx forever. The session is re-resolved and, when it
|
|
265
|
+
* moved, the request is sent once more to the new one. Still refused
|
|
266
|
+
* with 401/403 -> SessionLostError, so a long-running sync stops loudly
|
|
267
|
+
* instead of dropping every push (B45 in the 2026-10-08 report).
|
|
268
|
+
*/
|
|
269
|
+
async send(suffix, init, resend) {
|
|
270
|
+
let res = await this.fetchRetrying(suffix, init, resend);
|
|
271
|
+
if (!STALE_SESSION_STATUSES.has(res.status) || !this.refresh.reresolve)
|
|
272
|
+
return res;
|
|
273
|
+
let fresh;
|
|
274
|
+
try {
|
|
275
|
+
fresh = await this.refresh.reresolve();
|
|
276
|
+
}
|
|
277
|
+
catch {
|
|
278
|
+
return res; // could not re-resolve: the caller reports the original answer
|
|
279
|
+
}
|
|
280
|
+
if (fresh !== this.sessionBase) {
|
|
281
|
+
await res.body?.cancel();
|
|
282
|
+
const from = this.sessionBase;
|
|
283
|
+
this.sessionBase = fresh;
|
|
284
|
+
this.refresh.onSessionMoved?.(from, fresh);
|
|
285
|
+
res = await this.fetchRetrying(suffix, init, resend);
|
|
286
|
+
}
|
|
287
|
+
if (res.status === 401 || res.status === 403) {
|
|
288
|
+
const detail = await errorDetail(res.clone());
|
|
289
|
+
throw new SessionLostError(`The world's session refused this request (HTTP ${res.status}${detail ? ` - ${detail}` : ""}), ` +
|
|
290
|
+
`even after looking the session up again. Check \`virtualmatter whoami\` and that this account can edit the world.`);
|
|
291
|
+
}
|
|
292
|
+
return res;
|
|
293
|
+
}
|
|
294
|
+
async fetchRetrying(suffix, init, resend) {
|
|
295
|
+
for (let attempt = 0;; attempt++) {
|
|
296
|
+
try {
|
|
297
|
+
return await authorizedFetch(`${this.apiRoot}${suffix}`, init, this.fetchFn);
|
|
298
|
+
}
|
|
299
|
+
catch (err) {
|
|
300
|
+
if (!isNetworkError(err))
|
|
301
|
+
throw err;
|
|
302
|
+
const delay = NETWORK_RETRY_DELAYS_MS[attempt];
|
|
303
|
+
const retryable = resend === "safe" || failedBeforeSending(err);
|
|
304
|
+
if (retryable && delay !== undefined) {
|
|
305
|
+
await this.sleep(delay);
|
|
306
|
+
continue;
|
|
307
|
+
}
|
|
308
|
+
if (resend === "not-if-sent") {
|
|
309
|
+
throw new OutcomeUnknownError(`run-lua lost its connection (${networkErrorText(err)}); the engine may or may not have run this Lua. ` +
|
|
310
|
+
"Do not resend code that changes the world: check its effect first.");
|
|
311
|
+
}
|
|
312
|
+
throw new Error(`Network error talking to the world's session: ${networkErrorText(err)}`);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
}
|
|
149
316
|
async list() {
|
|
150
|
-
const res = await
|
|
317
|
+
const res = await this.send("/files", {}, "safe");
|
|
151
318
|
if (!res.ok)
|
|
152
319
|
throw new Error(`Listing files failed: HTTP ${res.status}`);
|
|
153
320
|
// Server envelope: {files: [...], truncated: bool} (session-agent
|
|
@@ -160,7 +327,7 @@ export class FilesClient {
|
|
|
160
327
|
return body.files;
|
|
161
328
|
}
|
|
162
329
|
async get(filePath) {
|
|
163
|
-
const res = await
|
|
330
|
+
const res = await this.send(`/files/content/${encodePath(filePath)}`, {}, "safe");
|
|
164
331
|
if (!res.ok)
|
|
165
332
|
throw new Error(`Downloading ${filePath} failed: HTTP ${res.status}`);
|
|
166
333
|
const declared = Number(res.headers.get("Content-Length"));
|
|
@@ -181,12 +348,12 @@ export class FilesClient {
|
|
|
181
348
|
}
|
|
182
349
|
return { bytes: Buffer.concat(chunks, size), etag: normalizeEtag(res.headers.get("ETag")) };
|
|
183
350
|
}
|
|
184
|
-
async download(filePath, destAbs) {
|
|
185
|
-
const res = await
|
|
351
|
+
async download(filePath, destAbs, opts = {}) {
|
|
352
|
+
const res = await this.send(`/files/content/${encodePath(filePath)}`, {}, "safe");
|
|
186
353
|
if (!res.ok)
|
|
187
354
|
throw new Error(`Downloading ${filePath} failed: HTTP ${res.status}`);
|
|
188
|
-
const { hash, size } = await streamToFile(res, destAbs);
|
|
189
|
-
return { etag: normalizeEtag(res.headers.get("ETag")), hash, size };
|
|
355
|
+
const { hash, size, path: landed } = await streamToFile(res, destAbs, opts);
|
|
356
|
+
return { etag: normalizeEtag(res.headers.get("ETag")), hash, size, path: landed };
|
|
190
357
|
}
|
|
191
358
|
async put(filePath, body, opts) {
|
|
192
359
|
const headers = { "Content-Type": "application/octet-stream" };
|
|
@@ -194,7 +361,9 @@ export class FilesClient {
|
|
|
194
361
|
headers["If-None-Match"] = "*";
|
|
195
362
|
else if (opts.etag)
|
|
196
363
|
headers["If-Match"] = opts.etag;
|
|
197
|
-
|
|
364
|
+
// Safe to resend: a write that did land turns the resend into a 412, and
|
|
365
|
+
// callers treat a 412 whose remote content equals the body as success.
|
|
366
|
+
const res = await this.send(`/files/content/${encodePath(filePath)}`, { method: "PUT", headers, body: new Uint8Array(body) }, "safe");
|
|
198
367
|
if (res.status === 412)
|
|
199
368
|
throw new ConflictError(filePath);
|
|
200
369
|
if (!res.ok)
|
|
@@ -203,7 +372,7 @@ export class FilesClient {
|
|
|
203
372
|
return parsed.etag;
|
|
204
373
|
}
|
|
205
374
|
async delete(filePath, etag) {
|
|
206
|
-
const res = await
|
|
375
|
+
const res = await this.send(`/files/content/${encodePath(filePath)}`, { method: "DELETE", headers: { "If-Match": etag } }, "safe");
|
|
207
376
|
if (res.status === 412)
|
|
208
377
|
throw new ConflictError(filePath);
|
|
209
378
|
if (!res.ok && res.status !== 404) {
|
|
@@ -214,11 +383,11 @@ export class FilesClient {
|
|
|
214
383
|
const payload = { code, target };
|
|
215
384
|
if (target === "client" && clientId !== undefined)
|
|
216
385
|
payload.client_id = clientId;
|
|
217
|
-
const res = await
|
|
386
|
+
const res = await this.send("/engine/run-lua", {
|
|
218
387
|
method: "POST",
|
|
219
388
|
headers: { "Content-Type": "application/json" },
|
|
220
389
|
body: JSON.stringify(payload),
|
|
221
|
-
},
|
|
390
|
+
}, "not-if-sent");
|
|
222
391
|
if (res.status === 504) {
|
|
223
392
|
// Never retried: the engine may still be running the snippet.
|
|
224
393
|
const detail = (await errorDetail(res)) || RUN_LUA_TIMEOUT;
|
|
@@ -235,7 +404,7 @@ export class FilesClient {
|
|
|
235
404
|
// Reading the error buffer changes nothing, so a busy (504) or briefly
|
|
236
405
|
// unreachable (503) engine is worth another try.
|
|
237
406
|
for (let attempt = 0;; attempt++) {
|
|
238
|
-
const res = await
|
|
407
|
+
const res = await this.send("/engine/errors", {}, "safe");
|
|
239
408
|
if (res.ok) {
|
|
240
409
|
const body = (await res.json());
|
|
241
410
|
return body.output;
|
|
@@ -272,13 +441,25 @@ export class FilesClient {
|
|
|
272
441
|
}
|
|
273
442
|
if (opts.clientId !== undefined)
|
|
274
443
|
body.client_id = opts.clientId;
|
|
275
|
-
const res = await
|
|
444
|
+
const res = await this.send("/engine/screenshot", {
|
|
276
445
|
method: "POST",
|
|
277
446
|
headers: { "Content-Type": "application/json" },
|
|
278
447
|
body: JSON.stringify(body),
|
|
279
|
-
},
|
|
448
|
+
}, "safe");
|
|
280
449
|
if (!res.ok)
|
|
281
450
|
throw new Error(await engineErrorMessage(res, "Screenshot"));
|
|
282
451
|
return Buffer.from(await res.arrayBuffer());
|
|
283
452
|
}
|
|
284
453
|
}
|
|
454
|
+
/**
|
|
455
|
+
* A client for the editor session of `framingId` that follows the session
|
|
456
|
+
* when it moves: an engine restart or cold start replaces it, and a client
|
|
457
|
+
* holding the old URL got 403 on every request until restarted (B45 in the
|
|
458
|
+
* 2026-10-08 breakage report).
|
|
459
|
+
*/
|
|
460
|
+
export function editSessionClient(framingId, session, onSessionMoved = (_from, to) => console.error(`The world's session moved (engine restart?); now talking to ${to}.`)) {
|
|
461
|
+
return new FilesClient(sessionBaseUrl(session), framingId, fetch, MAX_BUFFERED_BYTES, defaultSleep, {
|
|
462
|
+
reresolve: async () => sessionBaseUrl(await resolveSession(framingId, { intent: "edit" })),
|
|
463
|
+
onSessionMoved,
|
|
464
|
+
});
|
|
465
|
+
}
|
package/dist/ignore.js
CHANGED
|
@@ -21,6 +21,13 @@ export function isIgnoredPath(relPath) {
|
|
|
21
21
|
return true;
|
|
22
22
|
if (norm.endsWith(".remote-conflict"))
|
|
23
23
|
return true;
|
|
24
|
+
// Files that only exist mid-write: our own download temps (see
|
|
25
|
+
// streamToFile), and the engine's `<name>.am~` save temp plus editor
|
|
26
|
+
// backups. Syncing them pushed half-downloaded fragments into a world and
|
|
27
|
+
// pulled a half-written 157 MB terrain temp out of one (2026-10-07).
|
|
28
|
+
const base = segments[segments.length - 1];
|
|
29
|
+
if (isTempName(base))
|
|
30
|
+
return true;
|
|
24
31
|
// The SDK's in-session harness tooling at the Montage root. `atomo` only
|
|
25
32
|
// works against a running engine bridge, so the world's copy is never
|
|
26
33
|
// mirrored; `pull` writes the CLI's own `./atomo` wrapper (atomo.ts) in its
|
|
@@ -29,6 +36,11 @@ export function isIgnoredPath(relPath) {
|
|
|
29
36
|
return true;
|
|
30
37
|
return false;
|
|
31
38
|
}
|
|
39
|
+
/** The marker in the name of a download still streaming to disk (`<file>.vmdownload-<pid>-<rand>`). */
|
|
40
|
+
export const DOWNLOAD_TEMP_MARKER = ".vmdownload-";
|
|
41
|
+
export function isTempName(name) {
|
|
42
|
+
return name.includes(DOWNLOAD_TEMP_MARKER) || name.endsWith("~");
|
|
43
|
+
}
|
|
32
44
|
const SDK_HARNESS_FILES = new Set([
|
|
33
45
|
"atomo",
|
|
34
46
|
"atomo.bat",
|