virtualmatter 0.7.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -2
- package/dist/admin.js +167 -0
- package/dist/agentfiles.js +1 -1
- package/dist/agents-md.generated.js +1 -1
- package/dist/asset-commands.js +8 -0
- package/dist/assets.js +75 -1
- package/dist/depth.js +119 -0
- package/dist/files.js +45 -19
- package/dist/index.js +35 -9
- package/dist/mcp.js +70 -5
- package/dist/server-lifecycle.js +410 -0
- package/package.json +1 -1
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stop, start and restart a world's editor server: `virtualmatter restart`,
|
|
3
|
+
* `stop`, `start` and the MCP tools of the same names.
|
|
4
|
+
*
|
|
5
|
+
* These call the same platform routes as the web editor's Restart button, so
|
|
6
|
+
* a CLI restart is the same operation and reads the same way in
|
|
7
|
+
* `logs --restarts` ("Restarted from the CLI."). Editor only: the platform
|
|
8
|
+
* refuses a play server, which restarts when the world is published.
|
|
9
|
+
*
|
|
10
|
+
* Exit codes follow the rest of the CLI (see ATOMO_EXIT): 0 done, 1 the
|
|
11
|
+
* platform reported a failure, 2 nothing was done, 3 the request was sent but
|
|
12
|
+
* the outcome is not known yet.
|
|
13
|
+
*/
|
|
14
|
+
import fs from "node:fs";
|
|
15
|
+
import path from "node:path";
|
|
16
|
+
import readline from "node:readline";
|
|
17
|
+
import { authorizedFetch, resolveEditSession } from "./api.js";
|
|
18
|
+
import { NotLoggedInError } from "./auth.js";
|
|
19
|
+
import { apiBase } from "./config.js";
|
|
20
|
+
import { EngineTimeoutError, editSessionClient } from "./files.js";
|
|
21
|
+
import { resolveTarget } from "./resolve.js";
|
|
22
|
+
import { requireState } from "./state.js";
|
|
23
|
+
export const LIFECYCLE_EXIT = { done: 0, failed: 1, notDone: 2, unknown: 3 };
|
|
24
|
+
/** A refusal or failure with the exit code it maps to. */
|
|
25
|
+
export class LifecycleError extends Error {
|
|
26
|
+
exitCode;
|
|
27
|
+
constructor(message, exitCode) {
|
|
28
|
+
super(message);
|
|
29
|
+
this.exitCode = exitCode;
|
|
30
|
+
this.name = "LifecycleError";
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
const NO_PERMISSION = "No such world, or this account may not stop or start its server: only the world's owner can. Check who is signed in: npx virtualmatter whoami";
|
|
34
|
+
function framingPath(framingId, tail) {
|
|
35
|
+
return `${apiBase()}/api/v1/framings/${encodeURIComponent(framingId)}/${tail}`;
|
|
36
|
+
}
|
|
37
|
+
/** The platform's `detail` when the body is its own JSON error; null for a proxy's page. */
|
|
38
|
+
async function platformDetail(res) {
|
|
39
|
+
try {
|
|
40
|
+
const body = (await res.json());
|
|
41
|
+
if (typeof body.detail === "string")
|
|
42
|
+
return body.detail;
|
|
43
|
+
return body.detail ? JSON.stringify(body.detail) : null;
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
export async function getEngineState(framingId, fetchFn = fetch) {
|
|
50
|
+
const res = await authorizedFetch(framingPath(framingId, "engine-state"), {}, fetchFn);
|
|
51
|
+
if (res.status === 401 || res.status === 403 || res.status === 404)
|
|
52
|
+
throw new LifecycleError(NO_PERMISSION, LIFECYCLE_EXIT.notDone);
|
|
53
|
+
if (!res.ok) {
|
|
54
|
+
const detail = await platformDetail(res);
|
|
55
|
+
throw new LifecycleError(`Reading the server's state failed: HTTP ${res.status}${detail ? ` - ${detail}` : ""}`, LIFECYCLE_EXIT.notDone);
|
|
56
|
+
}
|
|
57
|
+
return (await res.json());
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* POST one lifecycle verb. The platform answers only once the old engine has
|
|
61
|
+
* stopped and the new one is up, which can outlast a gateway in front of it;
|
|
62
|
+
* that is reported as `unknown`, never as a failure, because the stop may
|
|
63
|
+
* well be in progress.
|
|
64
|
+
*/
|
|
65
|
+
export async function sendVerb(verb, framingId, force, fetchFn = fetch) {
|
|
66
|
+
let res;
|
|
67
|
+
try {
|
|
68
|
+
res = await authorizedFetch(framingPath(framingId, verb), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ source: "cli", force }) }, fetchFn);
|
|
69
|
+
}
|
|
70
|
+
catch (err) {
|
|
71
|
+
if (err instanceof NotLoggedInError)
|
|
72
|
+
throw err;
|
|
73
|
+
return { outcome: "unknown", why: err instanceof Error ? err.message : String(err) };
|
|
74
|
+
}
|
|
75
|
+
if (res.ok) {
|
|
76
|
+
// The platform has acted by the time it answers 2xx. If the connection
|
|
77
|
+
// drops while the body is read, or the body is not the platform's own,
|
|
78
|
+
// what it did is unknown: reconcile from the engine state, never resend.
|
|
79
|
+
let body;
|
|
80
|
+
try {
|
|
81
|
+
body = (await res.json());
|
|
82
|
+
}
|
|
83
|
+
catch (err) {
|
|
84
|
+
return { outcome: "unknown", why: `the answer could not be read (${err instanceof Error ? err.message : String(err)})` };
|
|
85
|
+
}
|
|
86
|
+
if (!body || typeof body.status !== "string")
|
|
87
|
+
return { outcome: "unknown", why: "the answer was not the platform's" };
|
|
88
|
+
return { outcome: "done", status: body.status, graceful: body.graceful === true };
|
|
89
|
+
}
|
|
90
|
+
const detail = await platformDetail(res);
|
|
91
|
+
if (res.status === 401 || res.status === 403 || res.status === 404) {
|
|
92
|
+
// 404 with no platform body is a platform that predates these routes.
|
|
93
|
+
if (res.status === 404 && detail !== "Framing not found" && verb !== "restart") {
|
|
94
|
+
throw new LifecycleError(`This platform has no ${verb} yet.`, LIFECYCLE_EXIT.notDone);
|
|
95
|
+
}
|
|
96
|
+
throw new LifecycleError(NO_PERMISSION, LIFECYCLE_EXIT.notDone);
|
|
97
|
+
}
|
|
98
|
+
if (detail === null && res.status >= 500)
|
|
99
|
+
return { outcome: "unknown", why: `HTTP ${res.status} from a gateway` };
|
|
100
|
+
// 409 and 422 are refused before anything is touched.
|
|
101
|
+
const code = res.status === 409 || res.status === 422 ? LIFECYCLE_EXIT.notDone : LIFECYCLE_EXIT.failed;
|
|
102
|
+
throw new LifecycleError(`${verb} failed: HTTP ${res.status}${detail ? ` - ${detail}` : ""}`, code);
|
|
103
|
+
}
|
|
104
|
+
/** Release the out-of-memory hold, swapping the terrain for the empty grid first. */
|
|
105
|
+
export async function resetTerrainAfterOom(framingId, fetchFn = fetch) {
|
|
106
|
+
const unanswered = (why) => new LifecycleError(`The terrain reset was sent but the platform did not answer (${why}), so the server was not started. Check with npx virtualmatter status before sending it again.`, LIFECYCLE_EXIT.unknown);
|
|
107
|
+
let res;
|
|
108
|
+
try {
|
|
109
|
+
res = await authorizedFetch(framingPath(framingId, "engine-oom/retry?reset_terrain=true"), { method: "POST" }, fetchFn);
|
|
110
|
+
}
|
|
111
|
+
catch (err) {
|
|
112
|
+
if (err instanceof NotLoggedInError)
|
|
113
|
+
throw err;
|
|
114
|
+
throw unanswered(err instanceof Error ? err.message : String(err));
|
|
115
|
+
}
|
|
116
|
+
if (res.ok)
|
|
117
|
+
return;
|
|
118
|
+
const detail = await platformDetail(res);
|
|
119
|
+
if (res.status === 401 || res.status === 403 || res.status === 404)
|
|
120
|
+
throw new LifecycleError(NO_PERMISSION, LIFECYCLE_EXIT.notDone);
|
|
121
|
+
if (detail === null && res.status >= 500)
|
|
122
|
+
throw unanswered(`HTTP ${res.status} from a gateway`);
|
|
123
|
+
throw new LifecycleError(`Resetting the terrain failed: HTTP ${res.status}${detail ? ` - ${detail}` : ""}`, LIFECYCLE_EXIT.failed);
|
|
124
|
+
}
|
|
125
|
+
const MEMORY_LUA = "return Server:GetMemoryUsage()";
|
|
126
|
+
/** Ask the engine for its memory use; throws while it is not answering. */
|
|
127
|
+
export async function probeEngine(framingId) {
|
|
128
|
+
const quiet = () => undefined;
|
|
129
|
+
const { session, framingId: editor } = await resolveEditSession(framingId, quiet);
|
|
130
|
+
const output = await editSessionClient(editor, session, quiet).runLua(MEMORY_LUA, "server");
|
|
131
|
+
return memoryReading(String(output ?? ""));
|
|
132
|
+
}
|
|
133
|
+
/** The value out of run-lua's `{"result":[...]}` envelope; other output is passed through as it came. */
|
|
134
|
+
export function memoryReading(output) {
|
|
135
|
+
const text = output.trim();
|
|
136
|
+
try {
|
|
137
|
+
const parsed = JSON.parse(text);
|
|
138
|
+
if (Array.isArray(parsed?.result) && parsed.result.length > 0)
|
|
139
|
+
return parsed.result.map(String).join(", ");
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
// not the envelope
|
|
143
|
+
}
|
|
144
|
+
return text;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Wait until the engine answers Lua again. A large world loads for minutes,
|
|
148
|
+
* during which run-lua answers HTTP 504 and the session 503: every failure
|
|
149
|
+
* here means "still loading" until the deadline.
|
|
150
|
+
*/
|
|
151
|
+
export async function waitForEngine(framingId, timeoutMs, deps = {}) {
|
|
152
|
+
const probe = deps.probe ?? probeEngine;
|
|
153
|
+
const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
154
|
+
const now = deps.now ?? Date.now;
|
|
155
|
+
const deadline = now() + timeoutMs;
|
|
156
|
+
let last = "no answer yet";
|
|
157
|
+
for (;;) {
|
|
158
|
+
try {
|
|
159
|
+
return { answered: true, memory: await probe(framingId) };
|
|
160
|
+
}
|
|
161
|
+
catch (err) {
|
|
162
|
+
if (err instanceof NotLoggedInError)
|
|
163
|
+
throw err;
|
|
164
|
+
last = err instanceof EngineTimeoutError ? "the engine is still loading (HTTP 504)" : err instanceof Error ? err.message : String(err);
|
|
165
|
+
}
|
|
166
|
+
if (now() >= deadline)
|
|
167
|
+
return { answered: false, last };
|
|
168
|
+
await sleep(Math.min(deps.intervalMs ?? 5000, Math.max(0, deadline - now())));
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
const DEFAULT_TIMEOUT_S = 900;
|
|
172
|
+
function plural(n, word) {
|
|
173
|
+
return `${n} ${word}${n === 1 ? "" : "s"}`;
|
|
174
|
+
}
|
|
175
|
+
/** One lifecycle command, start to finish. Never throws a LifecycleError: it becomes the result. */
|
|
176
|
+
export async function runLifecycle(verb, framingId, opts = {}, deps = {}) {
|
|
177
|
+
try {
|
|
178
|
+
return await lifecycle(verb, framingId, opts, deps);
|
|
179
|
+
}
|
|
180
|
+
catch (err) {
|
|
181
|
+
if (!(err instanceof LifecycleError))
|
|
182
|
+
throw err;
|
|
183
|
+
return { exitCode: err.exitCode, verb, outcome: err.exitCode === LIFECYCLE_EXIT.failed ? "failed" : err.exitCode === LIFECYCLE_EXIT.unknown ? "sent" : "refused", message: err.message };
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
async function lifecycle(verb, framingId, opts, deps) {
|
|
187
|
+
const log = deps.log ?? (() => undefined);
|
|
188
|
+
const now = deps.now ?? Date.now;
|
|
189
|
+
const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
190
|
+
const timeoutS = opts.timeoutS ?? DEFAULT_TIMEOUT_S;
|
|
191
|
+
if (!(timeoutS > 0))
|
|
192
|
+
throw new LifecycleError("--timeout takes a number of seconds above 0.", LIFECYCLE_EXIT.notDone);
|
|
193
|
+
if (opts.resetTerrain && verb !== "start")
|
|
194
|
+
throw new LifecycleError("--reset-terrain only applies to start.", LIFECYCLE_EXIT.notDone);
|
|
195
|
+
const refuse = (message) => {
|
|
196
|
+
throw new LifecycleError(message, LIFECYCLE_EXIT.notDone);
|
|
197
|
+
};
|
|
198
|
+
const state = await getEngineState(framingId, deps.fetchFn);
|
|
199
|
+
if (state.kind !== "make") {
|
|
200
|
+
refuse("That is a play server. These commands only stop and start a world's editor server; play servers restart when you publish (npx virtualmatter publish).");
|
|
201
|
+
}
|
|
202
|
+
if (verb === "stop" && state.state === "stopped") {
|
|
203
|
+
return { exitCode: LIFECYCLE_EXIT.done, verb, outcome: "already_stopped", message: "The server is already stopped." };
|
|
204
|
+
}
|
|
205
|
+
if (verb === "start" && state.state !== "stopped" && opts.resetTerrain) {
|
|
206
|
+
refuse("The server is running, so its terrain was left alone. --reset-terrain is only for a world stopped after running out of memory.");
|
|
207
|
+
}
|
|
208
|
+
if (verb === "start" && state.state === "stopped") {
|
|
209
|
+
if (state.out_of_memory && !opts.resetTerrain) {
|
|
210
|
+
refuse("This world's server was stopped because it ran out of memory, and it stays stopped until the world is smaller. " +
|
|
211
|
+
"`start --reset-terrain` swaps its terrain for an empty grid (the old terrain is kept in a backup folder on the server) and starts it.");
|
|
212
|
+
}
|
|
213
|
+
if (!state.out_of_memory && opts.resetTerrain) {
|
|
214
|
+
refuse("This world was not stopped for running out of memory, so its terrain was left alone. Start it without --reset-terrain.");
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
const stops = verb !== "start" && state.state !== "stopped";
|
|
218
|
+
if (stops && state.connected_clients > 0 && !opts.yes) {
|
|
219
|
+
const who = `${plural(state.connected_clients, "client")} connected to this server will be disconnected`;
|
|
220
|
+
if (!deps.confirm)
|
|
221
|
+
refuse(`${who}. Nothing was stopped; pass --yes to go ahead.`);
|
|
222
|
+
else if (!(await deps.confirm(`${who}. Continue?`)))
|
|
223
|
+
refuse("Nothing was stopped.");
|
|
224
|
+
}
|
|
225
|
+
if (stops && opts.force)
|
|
226
|
+
log("Forcing the stop: the engine is not given time to save, so unsaved changes are lost.");
|
|
227
|
+
else if (stops && !state.saves_on_stop) {
|
|
228
|
+
log("This world does not keep scene changes between sessions (a project setting), so nothing is saved when its server stops.");
|
|
229
|
+
}
|
|
230
|
+
const startedAt = now();
|
|
231
|
+
if (verb === "start" && opts.resetTerrain) {
|
|
232
|
+
log("Swapping the terrain for the empty grid ...");
|
|
233
|
+
await resetTerrainAfterOom(framingId, deps.fetchFn);
|
|
234
|
+
}
|
|
235
|
+
log(verb === "stop" ? "Stopping the server ..." : verb === "start" ? "Starting the server ..." : "Restarting the server ...");
|
|
236
|
+
const sent = await sendVerb(verb, framingId, opts.force === true, deps.fetchFn);
|
|
237
|
+
const clients = { connected_clients: state.connected_clients };
|
|
238
|
+
if (verb === "stop") {
|
|
239
|
+
if (sent.outcome === "done") {
|
|
240
|
+
const saved = sent.status === "stopped" ? (sent.graceful ? " It was given time to save first." : " It was stopped without saving.") : "";
|
|
241
|
+
return { exitCode: LIFECYCLE_EXIT.done, verb, outcome: sent.status, message: `The server is stopped.${saved} Start it again with: npx virtualmatter start`, ...clients };
|
|
242
|
+
}
|
|
243
|
+
// The stop may still be saving: watch the state until it is down.
|
|
244
|
+
log(`No answer from the platform yet (${sent.why}); checking whether the server stopped ...`);
|
|
245
|
+
const deadline = startedAt + timeoutS * 1000;
|
|
246
|
+
for (;;) {
|
|
247
|
+
const s = await getEngineState(framingId, deps.fetchFn).catch(() => null);
|
|
248
|
+
if (s?.state === "stopped")
|
|
249
|
+
return { exitCode: LIFECYCLE_EXIT.done, verb, outcome: "stopped", message: "The server is stopped.", ...clients };
|
|
250
|
+
if (now() >= deadline) {
|
|
251
|
+
return { exitCode: LIFECYCLE_EXIT.unknown, verb, outcome: "sent", message: `The stop was sent but the server was still up after ${timeoutS} s. Check it with: npx virtualmatter status`, ...clients };
|
|
252
|
+
}
|
|
253
|
+
await sleep(Math.min(deps.intervalMs ?? 5000, Math.max(0, deadline - now())));
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
if (sent.outcome === "done" && sent.status === "already_running") {
|
|
257
|
+
log("The server is already running.");
|
|
258
|
+
}
|
|
259
|
+
else if (sent.outcome === "done") {
|
|
260
|
+
log(sent.status === "restarted" ? `The old engine stopped${sent.graceful ? " after saving" : " without saving"}; the new one is up and loading the world.` : "The engine is up and loading the world.");
|
|
261
|
+
}
|
|
262
|
+
else {
|
|
263
|
+
log(`No answer from the platform yet (${sent.why}); it may still be working. Waiting for the engine ...`);
|
|
264
|
+
}
|
|
265
|
+
const outcome = sent.outcome === "done" ? sent.status : "sent";
|
|
266
|
+
if (opts.noWait) {
|
|
267
|
+
const exitCode = sent.outcome === "done" ? LIFECYCLE_EXIT.done : LIFECYCLE_EXIT.unknown;
|
|
268
|
+
const message = sent.outcome === "done"
|
|
269
|
+
? "Not waiting for the world to load. run-lua answers HTTP 504 until it has."
|
|
270
|
+
: "The request was sent but the platform has not answered. Check it with: npx virtualmatter status";
|
|
271
|
+
return { exitCode, verb, outcome, message, ...clients };
|
|
272
|
+
}
|
|
273
|
+
if (sent.outcome === "unknown") {
|
|
274
|
+
// Nothing says the restart happened: the engine that was running before
|
|
275
|
+
// may still be the one answering. `running_since` is the engine row's
|
|
276
|
+
// creation time, so a different value is a different engine; only then
|
|
277
|
+
// does a Lua answer mean the restart is complete. A start replaces
|
|
278
|
+
// nothing, so any engine that is up, the original one included, is the
|
|
279
|
+
// outcome it asked for.
|
|
280
|
+
const deadline = startedAt + timeoutS * 1000;
|
|
281
|
+
for (;;) {
|
|
282
|
+
const s = await getEngineState(framingId, deps.fetchFn).catch(() => null);
|
|
283
|
+
const up = s !== null && s.state !== "stopped";
|
|
284
|
+
if (up && (verb === "start" || (s.running_since !== null && s.running_since !== state.running_since)))
|
|
285
|
+
break;
|
|
286
|
+
if (now() >= deadline) {
|
|
287
|
+
const what = verb === "restart" ? "the engine that was running was not replaced" : "no engine came up";
|
|
288
|
+
return {
|
|
289
|
+
exitCode: LIFECYCLE_EXIT.unknown,
|
|
290
|
+
verb,
|
|
291
|
+
outcome,
|
|
292
|
+
seconds: Math.round((now() - startedAt) / 1000),
|
|
293
|
+
message: `The ${verb} was sent but the platform never answered, and ${what} within ${timeoutS} s. Check with npx virtualmatter status before sending it again.`,
|
|
294
|
+
...clients,
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
await sleep(Math.min(deps.intervalMs ?? 5000, Math.max(0, deadline - now())));
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
const remaining = Math.max(1000, startedAt + timeoutS * 1000 - now());
|
|
301
|
+
const waited = await waitForEngine(framingId, remaining, deps);
|
|
302
|
+
const seconds = Math.round((now() - startedAt) / 1000);
|
|
303
|
+
if (!waited.answered) {
|
|
304
|
+
return {
|
|
305
|
+
exitCode: LIFECYCLE_EXIT.unknown,
|
|
306
|
+
verb,
|
|
307
|
+
outcome,
|
|
308
|
+
seconds,
|
|
309
|
+
message: `The engine did not answer within ${timeoutS} s (${waited.last}). A large world can take longer: check with npx virtualmatter status, or wait again with npx virtualmatter start.`,
|
|
310
|
+
...clients,
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
return { exitCode: LIFECYCLE_EXIT.done, verb, outcome, seconds, memory: waited.memory, message: `The engine answered after ${seconds} s.`, ...clients };
|
|
314
|
+
}
|
|
315
|
+
/** The framing a command acts on: a synced folder, or any link to the world. */
|
|
316
|
+
export async function lifecycleTarget(target, cwd = process.cwd()) {
|
|
317
|
+
const arg = target ?? ".";
|
|
318
|
+
const abs = path.resolve(cwd, arg);
|
|
319
|
+
if (fs.existsSync(abs) && fs.statSync(abs).isDirectory()) {
|
|
320
|
+
try {
|
|
321
|
+
return requireState(abs).framing_id;
|
|
322
|
+
}
|
|
323
|
+
catch (err) {
|
|
324
|
+
throw new LifecycleError(err instanceof Error ? err.message : String(err), LIFECYCLE_EXIT.notDone);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
try {
|
|
328
|
+
return (await resolveTarget(arg)).framingId;
|
|
329
|
+
}
|
|
330
|
+
catch (err) {
|
|
331
|
+
if (err instanceof NotLoggedInError)
|
|
332
|
+
throw err;
|
|
333
|
+
throw new LifecycleError(err instanceof Error ? err.message : String(err), LIFECYCLE_EXIT.notDone);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
function askOnTerminal(question) {
|
|
337
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
|
|
338
|
+
return new Promise((resolve) => rl.question(`${question} [y/N] `, (answer) => {
|
|
339
|
+
rl.close();
|
|
340
|
+
resolve(/^y(es)?$/i.test(answer.trim()));
|
|
341
|
+
}));
|
|
342
|
+
}
|
|
343
|
+
/** One line for `status`: is the editor server up. */
|
|
344
|
+
export function describeEngineState(state) {
|
|
345
|
+
if (state.state === "running") {
|
|
346
|
+
return `Editor server: running since ${state.running_since ?? "?"}, ${plural(state.connected_clients, "client")} connected.`;
|
|
347
|
+
}
|
|
348
|
+
if (state.state === "starting")
|
|
349
|
+
return "Editor server: starting.";
|
|
350
|
+
if (state.out_of_memory) {
|
|
351
|
+
return "Editor server: stopped after running out of memory. It stays stopped until the world is smaller: npx virtualmatter start --reset-terrain swaps the terrain for an empty grid and starts it.";
|
|
352
|
+
}
|
|
353
|
+
return "Editor server: stopped. Start it with: npx virtualmatter start";
|
|
354
|
+
}
|
|
355
|
+
export function registerLifecycleCommands(program, run) {
|
|
356
|
+
const exits = "Exit 0 done, 1 the platform reported a failure, 2 nothing was done, 3 sent but the outcome is unknown";
|
|
357
|
+
const action = (verb) => (target, flags) => run(async () => {
|
|
358
|
+
let result;
|
|
359
|
+
try {
|
|
360
|
+
const timeoutS = flags.timeout === undefined ? undefined : Number(flags.timeout);
|
|
361
|
+
if (timeoutS !== undefined && !(timeoutS > 0))
|
|
362
|
+
throw new LifecycleError("--timeout takes a number of seconds above 0.", LIFECYCLE_EXIT.notDone);
|
|
363
|
+
const framingId = await lifecycleTarget(target);
|
|
364
|
+
result = await runLifecycle(verb, framingId, { force: flags.force, yes: flags.yes, noWait: flags.wait === false, timeoutS, resetTerrain: flags.resetTerrain }, { confirm: process.stdin.isTTY && !flags.json ? askOnTerminal : undefined, log: (line) => console.error(line) });
|
|
365
|
+
}
|
|
366
|
+
catch (err) {
|
|
367
|
+
if (err instanceof NotLoggedInError && process.env.VIRTUALMATTER_NO_AUTO_LOGIN) {
|
|
368
|
+
result = { exitCode: LIFECYCLE_EXIT.notDone, verb, outcome: "refused", message: err.message };
|
|
369
|
+
}
|
|
370
|
+
else if (err instanceof LifecycleError) {
|
|
371
|
+
result = { exitCode: err.exitCode, verb, outcome: "refused", message: err.message };
|
|
372
|
+
}
|
|
373
|
+
else
|
|
374
|
+
throw err;
|
|
375
|
+
}
|
|
376
|
+
if (flags.json)
|
|
377
|
+
console.log(JSON.stringify(result, null, 2));
|
|
378
|
+
else {
|
|
379
|
+
(result.exitCode === 0 ? console.log : console.error)(result.message);
|
|
380
|
+
if (result.memory)
|
|
381
|
+
console.log(`Server:GetMemoryUsage(): ${result.memory}`);
|
|
382
|
+
}
|
|
383
|
+
process.exitCode = result.exitCode;
|
|
384
|
+
});
|
|
385
|
+
const common = (cmd) => cmd
|
|
386
|
+
.argument("[target]", "a synced folder, or any link to the world", ".")
|
|
387
|
+
.option("--json", "machine-readable output");
|
|
388
|
+
common(program
|
|
389
|
+
.command("restart")
|
|
390
|
+
.description(`Restart the world's editor server (the web editor's Restart button): a clean process, which is what returns memory. Lets the engine save first, then waits until it answers Lua again and prints the time taken and Server:GetMemoryUsage(). Never restarts play servers. ${exits}`))
|
|
391
|
+
.option("--force", "stop without letting the engine save, for a stuck engine; unsaved changes are lost")
|
|
392
|
+
.option("--yes", "do not ask before disconnecting connected clients")
|
|
393
|
+
.option("--no-wait", "return once the new engine is up, without waiting for the world to load")
|
|
394
|
+
.option("--timeout <seconds>", "how long to wait for the engine to answer (default 900)")
|
|
395
|
+
.action(action("restart"));
|
|
396
|
+
common(program
|
|
397
|
+
.command("stop")
|
|
398
|
+
.description(`Stop the world's editor server and leave it stopped, letting the engine save first. It starts again when someone opens the world or with start. ${exits}`))
|
|
399
|
+
.option("--force", "stop without letting the engine save, for a stuck engine; unsaved changes are lost")
|
|
400
|
+
.option("--yes", "do not ask before disconnecting connected clients")
|
|
401
|
+
.option("--timeout <seconds>", "how long to wait for the stop when the platform does not answer (default 900)")
|
|
402
|
+
.action(action("stop"));
|
|
403
|
+
common(program
|
|
404
|
+
.command("start")
|
|
405
|
+
.description(`Start the world's editor server if it is stopped, wait until it answers Lua, and print the time taken and Server:GetMemoryUsage(). A running server is left alone. ${exits}`))
|
|
406
|
+
.option("--no-wait", "return once the engine is up, without waiting for the world to load")
|
|
407
|
+
.option("--timeout <seconds>", "how long to wait for the engine to answer (default 900)")
|
|
408
|
+
.option("--reset-terrain", "only for a world stopped after running out of memory: swap its terrain for an empty grid (the old one is kept in a backup folder on the server), then start")
|
|
409
|
+
.action(action("start"));
|
|
410
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "virtualmatter",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"description": "CLI + MCP server for building with Virtual Matter - list and create worlds, sync their files, run Lua, capture screenshots, open the native client, and wire coding agents into a live session.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|