virtualmatter 0.6.8 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/files.js CHANGED
@@ -9,6 +9,8 @@ import { Readable, Transform } from "node:stream";
9
9
  import { pipeline } from "node:stream/promises";
10
10
  import { authorizedFetch, resolveSession, sessionBaseUrl } from "./api.js";
11
11
  import { DOWNLOAD_TEMP_MARKER } from "./ignore.js";
12
+ import { getEngineRestarts } from "./world-status.js";
13
+ import { decodeDepth } from "./depth.js";
12
14
  /**
13
15
  * The session API's per-write cap (session-agent server/api/files.py
14
16
  * MAX_WRITE_BYTES). A bigger PUT is answered 413, so sync skips such files
@@ -89,6 +91,19 @@ export class SessionLostError extends Error {
89
91
  this.name = "SessionLostError";
90
92
  }
91
93
  }
94
+ /**
95
+ * A passive request (sync's remote poll) found the world's session gone and
96
+ * the platform says no engine is running: the world was stopped (typically
97
+ * because nobody was in it), or a new engine is still spawning. Nothing was
98
+ * re-resolved, so nothing was woken. The caller waits for the world to come
99
+ * back instead of starting it.
100
+ */
101
+ export class WorldStoppedError extends Error {
102
+ constructor() {
103
+ super("The world's engine isn't running.");
104
+ this.name = "WorldStoppedError";
105
+ }
106
+ }
92
107
  export class ConflictError extends Error {
93
108
  filePath;
94
109
  constructor(filePath) {
@@ -135,6 +150,23 @@ function networkErrorText(err) {
135
150
  * same, which is why a retry only happens when re-resolving MOVED the session.
136
151
  */
137
152
  const STALE_SESSION_STATUSES = new Set([401, 403, 404, 502, 503]);
153
+ /**
154
+ * How long a request keeps looking for a session the edge cannot reach yet
155
+ * (one that was just spawned, or one the platform still names after its
156
+ * engine stopped) before giving up. A cold start takes 30-60 s, and its
157
+ * route reaches Cloudflare a moment after the platform calls it healthy.
158
+ */
159
+ const SESSION_SETTLE_MS = 180_000;
160
+ /** Pauses between looks while waiting for it; the last one repeats. */
161
+ const SESSION_SETTLE_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 15_000];
162
+ /**
163
+ * Whether the session app itself answered. Its refusals are JSON (FastAPI);
164
+ * a session the edge cannot route to gets Cloudflare's HTML 403 page or
165
+ * Traefik's plain-text 404, which say nothing about this account's access.
166
+ */
167
+ function fromSessionApp(res) {
168
+ return (res.headers.get("content-type") ?? "").toLowerCase().includes("application/json");
169
+ }
138
170
  function tooBigToBuffer(filePath, size, limit) {
139
171
  const mb = (n) => `${Math.round(n / (1024 * 1024))} MB`;
140
172
  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.`;
@@ -261,35 +293,82 @@ export class FilesClient {
261
293
  * run-lua that means only when the request provably never left; any
262
294
  * other network failure becomes OutcomeUnknownError.
263
295
  * - 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).
296
+ * 401/403/404/5xx forever. The session is re-resolved and the request
297
+ * sent to the new one (B45 in the 2026-10-08 report). The session app's
298
+ * own 401/403 (JSON) is a real refusal -> SessionLostError at once, so a
299
+ * long-running sync stops loudly instead of dropping every push. Any
300
+ * other stale answer (Cloudflare's 403 page, Traefik's 404) means the
301
+ * edge cannot reach a session yet: a freshly spawned one's route lands a
302
+ * moment after the platform calls it healthy, and an idle-stopped
303
+ * engine's session can be named for a while after it is gone. That is
304
+ * waited out, re-resolving with backoff, for up to SESSION_SETTLE_MS.
305
+ * `passive` (sync's poll) never re-resolves into a stopped world: it
306
+ * throws WorldStoppedError instead of spawning the engine.
268
307
  */
269
- async send(suffix, init, resend) {
308
+ async send(suffix, init, resend, passive = false) {
270
309
  let res = await this.fetchRetrying(suffix, init, resend);
271
310
  if (!STALE_SESSION_STATUSES.has(res.status) || !this.refresh.reresolve)
272
311
  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) {
312
+ const now = this.refresh.now ?? Date.now;
313
+ const deadline = now() + (this.refresh.settleMs ?? SESSION_SETTLE_MS);
314
+ let waiting = false;
315
+ for (let attempt = 0;; attempt++) {
316
+ if (passive && !fromSessionApp(res) && this.refresh.engineStopped) {
317
+ let stopped = false;
318
+ try {
319
+ stopped = await this.refresh.engineStopped();
320
+ }
321
+ catch {
322
+ stopped = false; // can't tell: carry on as for a running world
323
+ }
324
+ if (stopped) {
325
+ await res.body?.cancel();
326
+ throw new WorldStoppedError();
327
+ }
328
+ }
329
+ let fresh;
330
+ try {
331
+ fresh = await this.refresh.reresolve();
332
+ }
333
+ catch {
334
+ if (attempt === 0)
335
+ return res; // could not re-resolve: the caller reports the original answer
336
+ fresh = this.sessionBase;
337
+ }
338
+ const moved = fresh !== this.sessionBase;
339
+ if (moved) {
340
+ await res.body?.cancel();
341
+ const from = this.sessionBase;
342
+ this.sessionBase = fresh;
343
+ this.refresh.onSessionMoved?.(from, fresh);
344
+ }
345
+ if (moved || attempt > 0)
346
+ res = await this.fetchRetrying(suffix, init, resend);
347
+ if (!STALE_SESSION_STATUSES.has(res.status))
348
+ return res;
349
+ const refusal = res.status === 401 || res.status === 403;
350
+ if (fromSessionApp(res)) {
351
+ if (refusal)
352
+ throw await this.sessionLost(res, "");
353
+ return res; // the session's own answer (a missing file, say): a real reply
354
+ }
355
+ if (now() >= deadline) {
356
+ if (refusal)
357
+ throw await this.sessionLost(res, " for minutes");
358
+ return res;
359
+ }
360
+ if (!waiting) {
361
+ waiting = true;
362
+ this.refresh.onSessionWaiting?.();
363
+ }
281
364
  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);
365
+ await this.sleep(SESSION_SETTLE_DELAYS_MS[Math.min(attempt, SESSION_SETTLE_DELAYS_MS.length - 1)] ?? 15_000);
286
366
  }
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;
367
+ }
368
+ async sessionLost(res, how) {
369
+ const detail = await errorDetail(res.clone());
370
+ return new SessionLostError(`The world's session refused this request (HTTP ${res.status}${detail ? ` - ${detail}` : ""}), ` +
371
+ `even after looking the session up again${how}. Check \`virtualmatter whoami\` and that this account can edit the world.`);
293
372
  }
294
373
  async fetchRetrying(suffix, init, resend) {
295
374
  for (let attempt = 0;; attempt++) {
@@ -313,8 +392,8 @@ export class FilesClient {
313
392
  }
314
393
  }
315
394
  }
316
- async list() {
317
- const res = await this.send("/files", {}, "safe");
395
+ async list(opts = {}) {
396
+ const res = await this.send("/files", {}, "safe", opts.passive === true);
318
397
  if (!res.ok)
319
398
  throw new Error(`Listing files failed: HTTP ${res.status}`);
320
399
  // Server envelope: {files: [...], truncated: bool} (session-agent
@@ -421,26 +500,28 @@ export class FilesClient {
421
500
  }
422
501
  }
423
502
  async screenshot(opts = {}) {
424
- const body = {};
425
- if (opts.target) {
426
- body.target_object_id = opts.target;
427
- if (opts.distance !== undefined)
428
- body.distance = opts.distance;
503
+ const res = await this.requestScreenshot(screenshotBody(opts));
504
+ return Buffer.from(await res.arrayBuffer());
505
+ }
506
+ async screenshotDepth(opts = {}) {
507
+ if (opts.clientId !== undefined) {
508
+ throw new Error("Depth is read from the server's own view; it does not combine with a client capture.");
429
509
  }
430
- else if (opts.at || opts.rot) {
431
- const [px, py, pz] = opts.at ?? [0, 20, 20];
432
- const [rx, ry, rz] = opts.rot ?? [0, -45, 0];
433
- Object.assign(body, {
434
- camera_pos_x: px,
435
- camera_pos_y: py,
436
- camera_pos_z: pz,
437
- camera_rot_x: rx,
438
- camera_rot_y: ry,
439
- camera_rot_z: rz,
440
- });
510
+ const res = await this.requestScreenshot({ ...screenshotBody(opts), depth: true });
511
+ if (!(res.headers.get("Content-Type") ?? "").includes("json")) {
512
+ // A session agent older than depth support ignores the flag and answers a bare image.
513
+ throw new Error("This world's session predates depth capture and answered a plain picture. Restart the world from its editor page so it gets a current session, then try again.");
441
514
  }
442
- if (opts.clientId !== undefined)
443
- body.client_id = opts.clientId;
515
+ const body = (await res.json());
516
+ if (!body.image?.data)
517
+ throw new Error("The screenshot answer has no image.");
518
+ return {
519
+ image: Buffer.from(body.image.data, "base64"),
520
+ mediaType: body.image.media_type ?? "image/png",
521
+ depth: decodeDepth(body.depth),
522
+ };
523
+ }
524
+ async requestScreenshot(body) {
444
525
  const res = await this.send("/engine/screenshot", {
445
526
  method: "POST",
446
527
  headers: { "Content-Type": "application/json" },
@@ -448,8 +529,31 @@ export class FilesClient {
448
529
  }, "safe");
449
530
  if (!res.ok)
450
531
  throw new Error(await engineErrorMessage(res, "Screenshot"));
451
- return Buffer.from(await res.arrayBuffer());
532
+ return res;
533
+ }
534
+ }
535
+ function screenshotBody(opts) {
536
+ const body = {};
537
+ if (opts.target) {
538
+ body.target_object_id = opts.target;
539
+ if (opts.distance !== undefined)
540
+ body.distance = opts.distance;
541
+ }
542
+ else if (opts.at || opts.rot) {
543
+ const [px, py, pz] = opts.at ?? [0, 20, 20];
544
+ const [rx, ry, rz] = opts.rot ?? [0, -45, 0];
545
+ Object.assign(body, {
546
+ camera_pos_x: px,
547
+ camera_pos_y: py,
548
+ camera_pos_z: pz,
549
+ camera_rot_x: rx,
550
+ camera_rot_y: ry,
551
+ camera_rot_z: rz,
552
+ });
452
553
  }
554
+ if (opts.clientId !== undefined)
555
+ body.client_id = opts.clientId;
556
+ return body;
453
557
  }
454
558
  /**
455
559
  * A client for the editor session of `framingId` that follows the session
@@ -461,5 +565,8 @@ export function editSessionClient(framingId, session, onSessionMoved = (_from, t
461
565
  return new FilesClient(sessionBaseUrl(session), framingId, fetch, MAX_BUFFERED_BYTES, defaultSleep, {
462
566
  reresolve: async () => sessionBaseUrl(await resolveSession(framingId, { intent: "edit" })),
463
567
  onSessionMoved,
568
+ onSessionWaiting: () => console.error("The world's session isn't reachable yet (engine starting?); waiting for it, up to 3 minutes."),
569
+ // No live engine row means none is running; reading it never spawns one.
570
+ engineStopped: async () => (await getEngineRestarts(framingId, 0)).running_since === null,
464
571
  });
465
572
  }
package/dist/index.js CHANGED
@@ -4,20 +4,23 @@ import fs from "node:fs";
4
4
  import path from "node:path";
5
5
  import { registerLogCommands } from "./log-commands.js";
6
6
  import { Command } from "commander";
7
- import { createProject, createWebsiteBuild, getWebsiteBuild, getEmbed, defaultRegion, editUrl, fetchNativeClientCatalog, listProjects, playUrl, NotEditFramingError, resolveEditSession, resolveSession, whoami, } from "./api.js";
7
+ import { createProject, createWebsiteBuild, getWebsiteBuild, getEmbed, defaultRegion, editUrl, fetchNativeClientCatalog, listProjects, playUrl, NotEditFramingError, authorizedFetch, resolveEditSession, resolveSession, whoami, } from "./api.js";
8
8
  import { NotLoggedInError, clearCredentials, loadCredentials, pollForToken, saveCredentials, startDeviceFlow, } from "./auth.js";
9
9
  import { openInBrowser } from "./browser.js";
10
10
  import { detectPlatform, ensureClientInstalled, launchClient, seedNativeAuth } from "./client.js";
11
11
  import { apiBase, packageVersion } from "./config.js";
12
12
  import { ENGINE_TIMEOUT_EXIT_CODE, EngineTimeoutError, editSessionClient } from "./files.js";
13
+ import { depthPaths, depthToNpy, depthToPreviewPng, describeDepth } from "./depth.js";
13
14
  import { acquireFolderLock } from "./lock.js";
14
15
  import { runMcpServer } from "./mcp.js";
15
16
  import { defaultErrorsStateFile, runAtomo } from "./atomo.js";
16
17
  import { pullCommand, refreshAgentFiles } from "./pull.js";
17
18
  import { NeedsChoiceError, formatProjectList, makeFramingOf, resolveImplicitTarget, resolveTarget, } from "./resolve.js";
19
+ import { attachAsset, findAsset, getJob, listAssets, listProjectAssets, uploadFile, waitForJob, assetForJob, } from "./assets.js";
20
+ import { assetLine, defaultAssetDeps, humanSize, jobLine, runPlace, runVoxelize, } from "./asset-commands.js";
18
21
  import { loadState, requireState } from "./state.js";
19
22
  import { SyncEngine, runSyncLoop } from "./sync.js";
20
- import { bootSceneNotes, formatRestarts, getDrift, getEngineLog, getEngineRestarts, getPublishRun, playLine, projectForEditor, recentRestartNote, startPublish, waitForPublish, } from "./world-status.js";
23
+ import { bootSceneNotes, formatIterations, formatRestarts, getDrift, getEngineIterations, getEngineLog, getEngineRestarts, getPublishRun, playLine, projectForEditor, publishMovesPlays, recentRestartNote, startPublish, waitForPublish, } from "./world-status.js";
21
24
  const program = new Command();
22
25
  program
23
26
  .name("virtualmatter")
@@ -501,16 +504,24 @@ program
501
504
  }));
502
505
  program
503
506
  .command("status")
504
- .description("The world's play servers: whether each matches the editor, which scene they load, and how the last update went")
507
+ .description("The world's 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")
505
508
  .argument("[dir]", "a synced folder", ".")
506
509
  .option("--json", "machine-readable output")
507
510
  .action((dir, opts) => run(async () => {
508
511
  const project = await projectForEditor(requireState(path.resolve(dir)).framing_id);
509
- const [drift, last] = await Promise.all([getDrift(project.id), getPublishRun(project.id)]);
512
+ const [drift, last, engine] = await Promise.all([
513
+ getDrift(project.id),
514
+ getPublishRun(project.id),
515
+ // advice: a platform without the endpoint still answers the rest
516
+ getEngineIterations(project.id).catch(() => null),
517
+ ]);
510
518
  if (opts.json) {
511
- console.log(JSON.stringify({ project: project.name, montage_id: project.id, drift, last_update: last }, null, 2));
519
+ console.log(JSON.stringify({ project: project.name, montage_id: project.id, engine, drift, last_update: last }, null, 2));
512
520
  return;
513
521
  }
522
+ if (engine)
523
+ for (const line of formatIterations(engine))
524
+ console.log(line);
514
525
  console.log(`${project.name}: ${drift.detail}`);
515
526
  for (const p of drift.plays)
516
527
  console.log(` ${p.region.padEnd(3)} ${p.state.padEnd(11)} ${p.detail} (${p.framing_id})`);
@@ -529,20 +540,42 @@ program
529
540
  .description("Update the world's play servers with the editor's latest (the project page's Update play servers): waits for it and reports each server; exit 1 if any server wasn't updated")
530
541
  .argument("[dir]", "a synced folder", ".")
531
542
  .option("--played-scene", "send the editor's played scene and its terrain, instead of InitScene")
543
+ .option("--init-scene", "send InitScene, and don't ask when the played scene is much newer")
532
544
  .option("--no-wait", "start the update and return without waiting for it")
533
545
  .option("--json", "machine-readable output (the final run)")
534
546
  .action((dir, opts) => run(async () => {
547
+ if (opts.playedScene && opts.initScene)
548
+ fail("Pass --played-scene or --init-scene, not both.");
535
549
  const project = await projectForEditor(requireState(path.resolve(dir)).framing_id);
536
550
  const sendPlayed = opts.playedScene === true;
551
+ let warnings = [];
537
552
  try {
538
- const { facts, warnings } = bootSceneNotes(await getDrift(project.id), sendPlayed);
539
- console.error(facts);
553
+ const notes = bootSceneNotes(await getDrift(project.id), sendPlayed);
554
+ warnings = notes.warnings;
555
+ console.error(notes.facts);
540
556
  for (const w of warnings)
541
557
  console.error(`Warning: ${w}`);
542
558
  }
543
559
  catch {
544
560
  /* the pre-publish check is advice, not a gate */
545
561
  }
562
+ try {
563
+ const moving = publishMovesPlays(await getEngineIterations(project.id));
564
+ if (moving)
565
+ console.error(`Note: ${moving}`);
566
+ }
567
+ catch {
568
+ /* advice too */
569
+ }
570
+ // A person at a terminal gets asked; an agent (no TTY) gets the warning
571
+ // above and decides with --played-scene / --init-scene next time.
572
+ if (warnings.length > 0 && !sendPlayed && !opts.initScene && !opts.json && process.stdin.isTTY && process.stderr.isTTY) {
573
+ if (!(await confirm("Publish InitScene anyway? [y/N] "))) {
574
+ console.error("Not published. Run again with --played-scene to send the played scene, or --init-scene to send InitScene.");
575
+ process.exitCode = 1;
576
+ return;
577
+ }
578
+ }
546
579
  const run0 = await startPublish(project.id, sendPlayed);
547
580
  if (run0.plays.length === 0) {
548
581
  console.error("This world has no play servers yet - add one on the project page, then publish.");
@@ -560,6 +593,17 @@ program
560
593
  if (final.status !== "done")
561
594
  process.exitCode = 1;
562
595
  }));
596
+ /** Ask a yes/no question on the terminal; anything but y/yes is no. */
597
+ async function confirm(question) {
598
+ const { createInterface } = await import("node:readline/promises");
599
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
600
+ try {
601
+ return /^y(es)?$/i.test((await rl.question(question)).trim());
602
+ }
603
+ finally {
604
+ rl.close();
605
+ }
606
+ }
563
607
  /** Parse a --client flag: a positive integer client id. */
564
608
  function clientIdFlag(value) {
565
609
  const n = Number(value);
@@ -577,7 +621,7 @@ function triple(value, flag) {
577
621
  }
578
622
  program
579
623
  .command("screenshot")
580
- .description("Capture a PNG of the world - a default overview, or aimed with --at/--rot or --target")
624
+ .description("Capture a PNG of the world - a default overview, or aimed with --at/--rot or --target. --depth also saves the frame's depth in metres")
581
625
  .argument("[dir]", "a synced folder", ".")
582
626
  .option("-o, --out <file>", "output file", "screenshot.png")
583
627
  .option("--at <x,y,z>", "camera position (default: 0,20,20)")
@@ -585,17 +629,32 @@ program
585
629
  .option("--target <id-or-name>", "frame this object instead of using a camera pose")
586
630
  .option("--distance <meters>", "framing distance for --target (default: from the object's bounds)")
587
631
  .option("--client <id>", "capture through this connected client, UI included; with no --at/--rot/--target it is exactly what that client sees")
632
+ .option("--depth", "also read the frame's depth buffer: <out>.depth.npy (float32 metres along the view axis, height x width, 0 = sky), <out>.depth.png (preview, near is white) and <out>.depth.json (camera and range). Not with --client")
588
633
  .action((dir, opts) => run(async () => {
589
634
  const { client } = await clientForDir(path.resolve(dir));
590
- const png = await client.screenshot({
635
+ const aim = {
591
636
  at: opts.at ? triple(opts.at, "--at") : undefined,
592
637
  rot: opts.rot ? triple(opts.rot, "--rot") : undefined,
593
638
  target: opts.target,
594
639
  distance: opts.distance === undefined ? undefined : Number(opts.distance),
595
640
  clientId: opts.client === undefined ? undefined : clientIdFlag(opts.client),
596
- });
597
- fs.writeFileSync(opts.out, png);
598
- console.log(`Wrote ${opts.out} (${png.length} bytes).`);
641
+ };
642
+ if (!opts.depth) {
643
+ const png = await client.screenshot(aim);
644
+ fs.writeFileSync(opts.out, png);
645
+ console.log(`Wrote ${opts.out} (${png.length} bytes).`);
646
+ return;
647
+ }
648
+ if (aim.clientId !== undefined)
649
+ fail("--depth reads the server's own view; drop --client.");
650
+ const shot = await client.screenshotDepth(aim);
651
+ const files = depthPaths(opts.out);
652
+ fs.writeFileSync(opts.out, shot.image);
653
+ fs.writeFileSync(files.npy, depthToNpy(shot.depth));
654
+ fs.writeFileSync(files.png, depthToPreviewPng(shot.depth));
655
+ fs.writeFileSync(files.json, JSON.stringify(shot.depth.info, null, 2) + "\n");
656
+ console.log(`Wrote ${opts.out} (${shot.image.length} bytes), ${files.npy}, ${files.png} and ${files.json}.`);
657
+ console.log(describeDepth(shot.depth.info));
599
658
  }));
600
659
  /** Install the native client if needed, sign it in, and launch it into a world. */
601
660
  async function openNative(framingId, url, force = false) {
@@ -642,6 +701,130 @@ program
642
701
  console.log(resolved.note);
643
702
  await openNative(resolved.framingId, editUrl(resolved.framingId, resolved.project?.url_slug), opts.force);
644
703
  }));
704
+ // ---------------------------------------------------------------- meshes -> assets -> world
705
+ /** The world a library command acts on: --project, else the synced folder, else the only project. */
706
+ async function worldFor(projectFlag) {
707
+ const resolved = await resolveTargetOrImplicit(projectFlag, process.cwd());
708
+ const project = resolved.project ?? (await projectForEditor(resolved.framingId));
709
+ return { montageId: project.id, framingId: resolved.framingId, name: project.name };
710
+ }
711
+ async function engineFor(world) {
712
+ const { session, framingId } = await resolveEditSession(world.framingId);
713
+ return editSessionClient(framingId, session);
714
+ }
715
+ const assetDeps = defaultAssetDeps(worldFor, engineFor);
716
+ const consoleIO = { out: (line) => console.log(line), err: (line) => console.error(line) };
717
+ program
718
+ .command("upload <file>")
719
+ .description("Upload a 3D file (glb gltf fbx obj stl, ply pts xyz e57 las laz, vox, zip) to your Virtual Matter uploads. Files over 190 MiB go up resumably, up to 10 GiB. Prints the upload id `voxelize` takes")
720
+ .option("--json", "machine-readable output")
721
+ .action((file, opts) => run(async () => {
722
+ let last = -1;
723
+ const upload = await uploadFile(path.resolve(file), {
724
+ onProgress: (sent, total) => {
725
+ const pct = Math.floor((sent / total) * 100);
726
+ if (!opts.json && total > 16 * 1024 * 1024 && pct !== last && pct % 10 === 0) {
727
+ last = pct;
728
+ console.error(` ${pct}% of ${humanSize(total)}`);
729
+ }
730
+ },
731
+ });
732
+ if (opts.json)
733
+ console.log(JSON.stringify(upload, null, 2));
734
+ else
735
+ console.log(`Uploaded ${upload.filename} (${upload.kind}, ${humanSize(upload.size_bytes)}): upload id ${upload.id}`);
736
+ }));
737
+ program
738
+ .command("voxelize <sources...>")
739
+ .description("Voxelize 3D files (uploading them first), folders of them, or upload ids on Virtual Matter's voxelizer, wait, and add the results to your asset library. With --attach they also go into a world's Assets/ folder, and with --place into its scene. A model keeps its own coordinates in metres and --place moves its 0,0,0, so map tiles placed with the same --place line up: voxelize tiles/ --place -1000,0,-1000")
740
+ .option("--vpm <n>", "voxels per metre, rounded to a power of two (default 4 = 25 cm voxels)")
741
+ .option("--scale <n>", "multiply the model's size, or AUTO to fit it to a default size (default 1)")
742
+ .option("--method <m>", "FloodFill (solid, default), ShellOnly, RayCast (open or non-watertight meshes, terrain), Projections, Polymender")
743
+ .option("--rotate <x,y,z>", "rotate the source by these degrees first, e.g. -90,0,0 for a Z-up model")
744
+ .option("--no-shading", "don't bake lighting into the voxel colours")
745
+ .option("--name <name>", "the asset's name (default: the file name; one source only)")
746
+ .option("--attach", "attach the results to a world (--project, else the synced folder here)")
747
+ .option("--place <x,y,z>", "also place each one in the world, its 0,0,0 at this position (implies --attach)")
748
+ .option("--project <link>", "the world for --attach / --place: any link to it or its framing id")
749
+ .option("--no-wait", "return once the jobs are queued; follow them with `virtualmatter jobs <id>`")
750
+ .option("--json", "machine-readable output")
751
+ .action((sources, opts) => run(async () => {
752
+ const code = await runVoxelize(sources, opts, consoleIO, assetDeps);
753
+ if (code !== 0)
754
+ process.exit(code);
755
+ }));
756
+ program
757
+ .command("jobs [job-id]")
758
+ .description("Voxelize jobs: one job's status (with --wait, follow it to the end), or your recent jobs")
759
+ .option("--wait", "follow the job until it finishes")
760
+ .option("--json", "machine-readable output")
761
+ .action((jobId, opts) => run(async () => {
762
+ if (!jobId) {
763
+ const res = await authorizedFetch(`${apiBase()}/api/v1/jobs`);
764
+ if (!res.ok)
765
+ fail(`Listing jobs failed: HTTP ${res.status}`);
766
+ const jobs = (await res.json()).slice(0, 20);
767
+ if (opts.json)
768
+ console.log(JSON.stringify(jobs, null, 2));
769
+ else
770
+ for (const j of jobs)
771
+ console.log(`${j.id} ${j.created_at.slice(0, 16)} ${jobLine(j)}`);
772
+ return;
773
+ }
774
+ const job = opts.wait
775
+ ? await waitForJob(jobId, { onUpdate: (j) => !opts.json && console.error(` ${jobLine(j)}`) })
776
+ : await getJob(jobId);
777
+ const asset = job.status === "succeeded" ? await assetForJob(job.id) : null;
778
+ if (opts.json)
779
+ console.log(JSON.stringify({ job, asset }, null, 2));
780
+ else
781
+ console.log(asset ? `${jobLine(job)}\nAsset: ${assetLine(asset)}` : jobLine(job));
782
+ }));
783
+ program
784
+ .command("assets")
785
+ .description("Your asset library (voxelized models), or with --project the assets attached to one world")
786
+ .option("--project <link>", "list one world's attached assets instead")
787
+ .option("--json", "machine-readable output")
788
+ .action((opts) => run(async () => {
789
+ const assets = opts.project
790
+ ? await listProjectAssets((await worldFor(opts.project)).montageId)
791
+ : (await listAssets()).filter((a) => a.status !== "deleted");
792
+ if (opts.json)
793
+ console.log(JSON.stringify(assets, null, 2));
794
+ else if (assets.length === 0)
795
+ console.log("No assets yet. Make one: npx virtualmatter voxelize <file.glb>");
796
+ else
797
+ for (const a of assets)
798
+ console.log(assetLine(a));
799
+ }));
800
+ program
801
+ .command("attach <asset>")
802
+ .description("Attach a library asset (its id or name) to a world: the platform copies it into the world's Assets/ folder, and keeps it there across restarts")
803
+ .option("--project <link>", "the world: any link to it or its framing id (default: the synced folder here)")
804
+ .option("--json", "machine-readable output")
805
+ .action((ref, opts) => run(async () => {
806
+ const world = await worldFor(opts.project);
807
+ const asset = await findAsset(ref);
808
+ await attachAsset(world.montageId, asset.id);
809
+ if (opts.json)
810
+ console.log(JSON.stringify({ attached: true, asset, project: world.name }, null, 2));
811
+ else
812
+ console.log(`Attached ${asset.name} to ${world.name}. Place it: npx virtualmatter place ${asset.id} --at 0,0,0`);
813
+ }));
814
+ program
815
+ .command("place <asset>")
816
+ .description("Put a library asset (its id or name) into the world's scene as a saved object, attaching it first if needed. The position is where the model's centre goes, in metres")
817
+ .option("--at <x,y,z>", "position (default 0,0,0)")
818
+ .option("--yaw <deg>", "rotation about the vertical axis, degrees")
819
+ .option("--scale <n>", "uniform scale")
820
+ .option("--name <name>", "scene object name (default: the asset's name)")
821
+ .option("--project <link>", "the world: any link to it or its framing id (default: the synced folder here)")
822
+ .option("--json", "machine-readable output")
823
+ .action((ref, opts) => run(async () => {
824
+ const code = await runPlace(ref, opts, consoleIO, assetDeps);
825
+ if (code !== 0)
826
+ process.exit(code);
827
+ }));
645
828
  program
646
829
  .command("mcp")
647
830
  .description("Run the stdio MCP server for coding agents (works with or without a selected world)")