virtualmatter 0.6.5 → 0.6.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +38 -7
- package/dist/agent-logs.js +33 -5
- package/dist/agentfiles.js +2 -2
- package/dist/agents-md.generated.js +1 -1
- package/dist/atomo.js +307 -23
- package/dist/files.js +200 -19
- package/dist/ignore.js +12 -0
- package/dist/index.js +227 -26
- 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/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",
|