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/dist/index.js CHANGED
@@ -1,25 +1,27 @@
1
1
  #!/usr/bin/env node
2
- /** virtualmatter - the CLI coding agents (and humans) install to build with Virtual Matter. */
2
+ /** virtualmatter - the CLI coding agents (and humans) install to make with Virtual Matter. */
3
3
  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, sessionBaseUrl, whoami, } from "./api.js";
7
+ import { createProject, createWebsiteBuild, getWebsiteBuild, getEmbed, defaultRegion, editUrl, fetchNativeClientCatalog, listProjects, playUrl, NotEditFramingError, 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
- import { ENGINE_TIMEOUT_EXIT_CODE, EngineTimeoutError, FilesClient } from "./files.js";
12
+ import { ENGINE_TIMEOUT_EXIT_CODE, EngineTimeoutError, editSessionClient } from "./files.js";
13
+ import { acquireFolderLock } from "./lock.js";
13
14
  import { runMcpServer } from "./mcp.js";
14
15
  import { runAtomo } from "./atomo.js";
15
16
  import { pullCommand, refreshAgentFiles } from "./pull.js";
16
17
  import { NeedsChoiceError, formatProjectList, makeFramingOf, resolveImplicitTarget, resolveTarget, } from "./resolve.js";
17
18
  import { loadState, requireState } from "./state.js";
18
19
  import { SyncEngine, runSyncLoop } from "./sync.js";
20
+ import { bootSceneNotes, formatRestarts, getDrift, getEngineLog, getEngineRestarts, getPublishRun, playLine, projectForEditor, recentRestartNote, startPublish, waitForPublish, } from "./world-status.js";
19
21
  const program = new Command();
20
22
  program
21
23
  .name("virtualmatter")
22
- .description("Build with Virtual Matter from your terminal or coding agent: list and create worlds, mirror their files, live-sync edits, run Lua, capture screenshots, open the native client, and expose it all over MCP.")
24
+ .description("Make with Virtual Matter from your terminal or coding agent: list and create worlds, mirror their files, live-sync edits, run Lua, capture screenshots, open the native client, and expose it all over MCP.")
23
25
  .version(packageVersion())
24
26
  // `npx virtualmatter --help` is the first command an external agent runs, so
25
27
  // it is the earliest place to head off driving the website instead.
@@ -96,7 +98,7 @@ async function clientForDir(dir) {
96
98
  // play server can safely run against the editor instead - with a warning,
97
99
  // because the folder itself still needs re-mirroring before `sync`.
98
100
  const { session, framingId } = await resolveEditSession(state.framing_id, (err) => console.error(`Note: ${err.message} Running against the editor instead. To fix this folder, mirror the editor: npx virtualmatter pull ${err.editUrl} <new-folder>`));
99
- return { client: new FilesClient(sessionBaseUrl(session), framingId), framingId };
101
+ return { client: editSessionClient(framingId, session), framingId };
100
102
  }
101
103
  /** A target from the argument, else from the folder, else the only project. */
102
104
  async function resolveTargetOrImplicit(target, dir) {
@@ -277,23 +279,18 @@ program
277
279
  const result = await pullCommand(resolved.framingId, dest);
278
280
  reportPull(result, dest, resolved.watchUrl ?? `${editUrl(result.framingId, resolved.project?.url_slug)}?chat=closed`);
279
281
  }));
280
- program
281
- .command("sync")
282
- .description("Two-way sync: watch the folder, push local edits, pull remote changes")
283
- .argument("[dir]", "a folder previously created by `virtualmatter pull`", ".")
284
- .action((dir) => run(async () => {
285
- const abs = path.resolve(dir);
286
- const state = requireState(abs);
287
- let session;
282
+ /**
283
+ * The editor session for a synced folder, refusing a folder mirrored from a
284
+ * play server: syncing into that server is lost on the next publish, and its
285
+ * files are the PUBLISHED copy - possibly older than the editor - so syncing
286
+ * them into the editor could overwrite newer work. Neither is safe to guess
287
+ * at: stop and say how to get a right folder.
288
+ */
289
+ async function editSessionForFolder(framingId) {
288
290
  try {
289
- session = await resolveSession(state.framing_id, { intent: "edit" });
291
+ return await resolveSession(framingId, { intent: "edit" });
290
292
  }
291
293
  catch (err) {
292
- // A folder mirrored from a play server (older CLIs took /play links at
293
- // face value). Syncing into that server is lost on the next publish,
294
- // and its files are the PUBLISHED copy - possibly older than the
295
- // editor - so syncing them into the editor could overwrite newer work.
296
- // Neither is safe to guess at: stop and say how to get a right folder.
297
294
  if (err instanceof NotEditFramingError) {
298
295
  fail([
299
296
  "This folder was mirrored from a play server, not the world's editor.",
@@ -306,8 +303,44 @@ program
306
303
  }
307
304
  throw err;
308
305
  }
309
- const client = new FilesClient(sessionBaseUrl(session), state.framing_id);
310
- const engine = new SyncEngine(client, abs, state);
306
+ }
307
+ /** Print per-file outcomes (or JSON); returns how many need attention. */
308
+ function reportOutcomes(outcomes, good, verb, json) {
309
+ if (json) {
310
+ console.log(JSON.stringify(outcomes, null, 2));
311
+ return outcomes.filter((o) => !good.includes(o.status)).length;
312
+ }
313
+ let bad = 0;
314
+ for (const o of outcomes) {
315
+ const ok = good.includes(o.status);
316
+ if (!ok)
317
+ bad++;
318
+ const line = `${o.status.padEnd(12)} ${o.path}${o.detail ? ` (${o.detail})` : ""}`;
319
+ if (ok)
320
+ console.log(line);
321
+ else
322
+ console.error(line);
323
+ }
324
+ const counts = new Map();
325
+ for (const o of outcomes)
326
+ counts.set(o.status, (counts.get(o.status) ?? 0) + 1);
327
+ const summary = [...counts.entries()].map(([k, n]) => `${n} ${k}`).join(", ");
328
+ console.log(outcomes.length === 0 ? `Nothing to ${verb}.` : summary);
329
+ return bad;
330
+ }
331
+ program
332
+ .command("sync")
333
+ .description("Two-way sync: watch the folder, push local edits, pull remote changes. Files too large to push back (terrain, voxel data) are not pulled; one sync per folder")
334
+ .argument("[dir]", "a folder previously created by `virtualmatter pull`", ".")
335
+ .option("--include-large", "also pull files too large to push back (terrain and voxel data, often hundreds of MB)")
336
+ .option("--keep-alive", "keep running after the process that started sync exits (by default it stops with it)")
337
+ .action((dir, opts) => run(async () => {
338
+ const abs = path.resolve(dir);
339
+ const state = requireState(abs);
340
+ await acquireFolderLock(abs, "sync");
341
+ const session = await editSessionForFolder(state.framing_id);
342
+ const client = editSessionClient(state.framing_id, session);
343
+ const engine = new SyncEngine(client, abs, state, { includeLarge: opts.includeLarge });
311
344
  console.log(`Syncing ${abs} with framing ${state.framing_id}. Ctrl-C to stop.`);
312
345
  console.log(`Watch changes land live in any browser: ${editUrl(state.framing_id)}?chat=closed`);
313
346
  await runSyncLoop(engine, abs, {
@@ -318,7 +351,66 @@ program
318
351
  if (skills.removed.length > 0)
319
352
  console.log(`skills: removed ${skills.removed.join(", ")} (the world withdrew them)`);
320
353
  },
354
+ keepAlive: opts.keepAlive,
355
+ });
356
+ }));
357
+ /** Paths given on the command line, relative to the synced folder (posix). */
358
+ function folderPaths(abs, paths) {
359
+ return paths.map((p) => {
360
+ const rel = path.relative(abs, path.resolve(p)).replace(/\\/g, "/");
361
+ if (rel.startsWith("..") || path.isAbsolute(rel))
362
+ fail(`${p} is outside the synced folder ${abs}.`);
363
+ return rel;
321
364
  });
365
+ }
366
+ program
367
+ .command("push")
368
+ .description("One-shot deploy: push these files (default: every file changed here since the last sync) and report each one. Unchanged files are not sent, so they do not reset the world's Lua")
369
+ .argument("[paths...]", "files to push, relative to the current directory")
370
+ .option("--dir <dir>", "the synced folder", ".")
371
+ .option("--force", "overwrite the world's copy even if it changed since your last sync")
372
+ .option("--json", "machine-readable output")
373
+ .action((paths, opts) => run(async () => {
374
+ const abs = path.resolve(opts.dir);
375
+ const state = requireState(abs);
376
+ const release = await acquireFolderLock(abs, "push");
377
+ try {
378
+ const session = await editSessionForFolder(state.framing_id);
379
+ const engine = new SyncEngine(editSessionClient(state.framing_id, session), abs, state, {
380
+ logger: { info: () => { }, warn: (m) => console.error(m) },
381
+ });
382
+ const outcomes = await engine.pushPaths(paths.length > 0 ? folderPaths(abs, paths) : null, { force: opts.force });
383
+ if (reportOutcomes(outcomes, ["pushed", "unchanged"], "push", opts.json) > 0)
384
+ process.exitCode = 1;
385
+ }
386
+ finally {
387
+ release();
388
+ }
389
+ }));
390
+ program
391
+ .command("fetch")
392
+ .description("One-shot download into a synced folder: these files (default: every file the world changed since the last sync). Never overwrites local edits - a file changed on both sides gets a .remote-conflict copy. Named files are fetched whatever their size")
393
+ .argument("[paths...]", "files to fetch, relative to the current directory")
394
+ .option("--dir <dir>", "the synced folder", ".")
395
+ .option("--include-large", "with no paths, also fetch files too large to push back")
396
+ .option("--json", "machine-readable output")
397
+ .action((paths, opts) => run(async () => {
398
+ const abs = path.resolve(opts.dir);
399
+ const state = requireState(abs);
400
+ const release = await acquireFolderLock(abs, "fetch");
401
+ try {
402
+ const session = await editSessionForFolder(state.framing_id);
403
+ const engine = new SyncEngine(editSessionClient(state.framing_id, session), abs, state, {
404
+ logger: { info: () => { }, warn: (m) => console.error(m) },
405
+ includeLarge: opts.includeLarge,
406
+ });
407
+ const outcomes = await engine.fetchPaths(paths.length > 0 ? folderPaths(abs, paths) : null);
408
+ if (reportOutcomes(outcomes, ["pulled", "unchanged", "skipped-large"], "fetch", opts.json) > 0)
409
+ process.exitCode = 1;
410
+ }
411
+ finally {
412
+ release();
413
+ }
322
414
  }));
323
415
  program
324
416
  .command("run-lua")
@@ -356,9 +448,117 @@ program
356
448
  .description("Show recent engine errors")
357
449
  .argument("[dir]", "a synced folder", ".")
358
450
  .action((dir) => run(async () => {
359
- const { client } = await clientForDir(path.resolve(dir));
451
+ const { client, framingId } = await clientForDir(path.resolve(dir));
452
+ // A restart clears the engine's error buffer, so "no errors" right
453
+ // after a crash means nothing. Best-effort: never blocks the errors.
454
+ try {
455
+ const note = recentRestartNote(await getEngineRestarts(framingId, 0));
456
+ if (note)
457
+ console.error(note);
458
+ }
459
+ catch {
460
+ /* the history is a courtesy here */
461
+ }
360
462
  console.log(JSON.stringify(await client.engineErrors(), null, 2));
361
463
  }));
464
+ /** The folder's world (its editor), or the framing named with --framing (e.g. a play server from `status`). */
465
+ function targetFraming(dir, framing) {
466
+ return framing ?? requireState(path.resolve(dir)).framing_id;
467
+ }
468
+ program
469
+ .command("logs")
470
+ .description("The engine's log: its last lines, or with --restarts every recent restart and why (a crash with the last lines it logged, or a platform stop with its reason)")
471
+ .argument("[dir]", "a synced folder", ".")
472
+ .option("--restarts", "list recent engine restarts and why they happened")
473
+ .option("--tail <n>", "lines to show (per restart with --restarts)", "")
474
+ .option("--framing <id>", "another framing of the world, such as a play server listed by `status`")
475
+ .option("--json", "machine-readable output")
476
+ .action((dir, opts) => run(async () => {
477
+ const framingId = targetFraming(dir, opts.framing);
478
+ const tail = opts.tail === "" ? (opts.restarts ? 20 : 100) : Number(opts.tail);
479
+ if (!Number.isInteger(tail) || tail < 0)
480
+ fail("--tail takes a whole number of lines");
481
+ if (opts.restarts) {
482
+ const history = await getEngineRestarts(framingId, Math.min(tail, 200));
483
+ if (opts.json)
484
+ console.log(JSON.stringify(history, null, 2));
485
+ else
486
+ for (const line of formatRestarts(history))
487
+ console.log(line);
488
+ return;
489
+ }
490
+ const log = await getEngineLog(framingId, Math.max(1, Math.min(tail, 2000)));
491
+ if (opts.json) {
492
+ console.log(JSON.stringify(log, null, 2));
493
+ return;
494
+ }
495
+ if (!log.log_file)
496
+ fail("This world has no engine log yet.");
497
+ console.error(`== ${log.log_file} (last ${log.lines.length} lines)`);
498
+ for (const line of log.lines)
499
+ console.log(line);
500
+ }));
501
+ program
502
+ .command("status")
503
+ .description("The world's play servers: whether each matches the editor, which scene they load, and how the last update went")
504
+ .argument("[dir]", "a synced folder", ".")
505
+ .option("--json", "machine-readable output")
506
+ .action((dir, opts) => run(async () => {
507
+ const project = await projectForEditor(requireState(path.resolve(dir)).framing_id);
508
+ const [drift, last] = await Promise.all([getDrift(project.id), getPublishRun(project.id)]);
509
+ if (opts.json) {
510
+ console.log(JSON.stringify({ project: project.name, montage_id: project.id, drift, last_update: last }, null, 2));
511
+ return;
512
+ }
513
+ console.log(`${project.name}: ${drift.detail}`);
514
+ for (const p of drift.plays)
515
+ console.log(` ${p.region.padEnd(3)} ${p.state.padEnd(11)} ${p.detail} (${p.framing_id})`);
516
+ if (drift.plays.length === 0)
517
+ console.log(" No play servers yet - add one on the project page to publish.");
518
+ console.log(bootSceneNotes(drift, last?.send_played_scene ?? false).facts);
519
+ if (last) {
520
+ console.log(`Last update: ${last.status}${last.error ? ` - ${last.error}` : ""} (${last.updated_at})`);
521
+ if (last.status !== "done")
522
+ for (const p of last.plays)
523
+ console.log(` ${playLine(p)}`);
524
+ }
525
+ }));
526
+ program
527
+ .command("publish")
528
+ .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")
529
+ .argument("[dir]", "a synced folder", ".")
530
+ .option("--played-scene", "send the editor's played scene and its terrain, instead of InitScene")
531
+ .option("--no-wait", "start the update and return without waiting for it")
532
+ .option("--json", "machine-readable output (the final run)")
533
+ .action((dir, opts) => run(async () => {
534
+ const project = await projectForEditor(requireState(path.resolve(dir)).framing_id);
535
+ const sendPlayed = opts.playedScene === true;
536
+ try {
537
+ const { facts, warnings } = bootSceneNotes(await getDrift(project.id), sendPlayed);
538
+ console.error(facts);
539
+ for (const w of warnings)
540
+ console.error(`Warning: ${w}`);
541
+ }
542
+ catch {
543
+ /* the pre-publish check is advice, not a gate */
544
+ }
545
+ const run0 = await startPublish(project.id, sendPlayed);
546
+ if (run0.plays.length === 0) {
547
+ console.error("This world has no play servers yet - add one on the project page, then publish.");
548
+ }
549
+ if (!opts.wait) {
550
+ console.log(opts.json ? JSON.stringify(run0, null, 2) : `Update started (${run0.id}). Follow it: npx virtualmatter status`);
551
+ return;
552
+ }
553
+ console.error(`Updating ${run0.plays.length} play server${run0.plays.length === 1 ? "" : "s"} of ${project.name} ...`);
554
+ const final = await waitForPublish(project.id, (line) => console.error(line));
555
+ if (opts.json)
556
+ console.log(JSON.stringify(final, null, 2));
557
+ else
558
+ console.log(final.status === "done" ? "Play servers updated." : `Update failed: ${final.error ?? "see above"}`);
559
+ if (final.status !== "done")
560
+ process.exitCode = 1;
561
+ }));
362
562
  /** Parse a --client flag: a positive integer client id. */
363
563
  function clientIdFlag(value) {
364
564
  const n = Number(value);
package/dist/lock.js ADDED
@@ -0,0 +1,208 @@
1
+ /**
2
+ * One CLI process per mirrored folder.
3
+ *
4
+ * Stopping a backgrounded `npx virtualmatter sync` killed only the npx
5
+ * wrapper and left its node child running, so three syncs once ran on the
6
+ * same folder at the same time: they pulled the same 370 MB terrain in
7
+ * parallel, reported false conflicts against each other, ping-ponged scene
8
+ * files and re-pushed unchanged scripts, each push resetting the world's Lua
9
+ * (2026-10-07). A lock file in the folder makes a second process notice the
10
+ * first. A new `sync` stops an earlier one it can positively identify as a
11
+ * virtualmatter process; `push` and `fetch` never stop anything - they refuse
12
+ * while a sync owns the folder, since it already does their job and both
13
+ * would write the same state file.
14
+ */
15
+ import { spawnSync } from "node:child_process";
16
+ import fs from "node:fs";
17
+ import os from "node:os";
18
+ import path from "node:path";
19
+ /** Dotfile, so pull/sync never mirror it (see ignore.ts). */
20
+ export const LOCK_FILE = ".virtualmatter.lock";
21
+ export class FolderBusyError extends Error {
22
+ constructor(message) {
23
+ super(message);
24
+ this.name = "FolderBusyError";
25
+ }
26
+ }
27
+ export function processAlive(pid) {
28
+ try {
29
+ process.kill(pid, 0);
30
+ return true;
31
+ }
32
+ catch (err) {
33
+ // EPERM: it exists, it just belongs to someone else
34
+ return err.code === "EPERM";
35
+ }
36
+ }
37
+ /** The full command line of a process, or null when it cannot be read. */
38
+ export function processCommandLine(pid) {
39
+ try {
40
+ if (process.platform === "win32") {
41
+ const res = spawnSync("powershell.exe", ["-NoProfile", "-Command", `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CommandLine`], { encoding: "utf8", timeout: 5000, windowsHide: true });
42
+ return res.status === 0 ? res.stdout.trim() || null : null;
43
+ }
44
+ const res = spawnSync("ps", ["-o", "command=", "-p", String(pid)], { encoding: "utf8", timeout: 5000 });
45
+ return res.status === 0 ? res.stdout.trim() || null : null;
46
+ }
47
+ catch {
48
+ return null;
49
+ }
50
+ }
51
+ function looksLikeVirtualmatter(pid) {
52
+ const cmd = processCommandLine(pid);
53
+ if (cmd === null)
54
+ return null;
55
+ return /virtualmatter/i.test(cmd);
56
+ }
57
+ export const defaultLockDeps = {
58
+ pid: process.pid,
59
+ host: os.hostname(),
60
+ now: () => new Date(),
61
+ isAlive: processAlive,
62
+ isVirtualmatter: looksLikeVirtualmatter,
63
+ kill: (pid, signal) => process.kill(pid, signal),
64
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
65
+ };
66
+ export function lockPath(dir) {
67
+ return path.join(dir, LOCK_FILE);
68
+ }
69
+ export function readLock(dir) {
70
+ try {
71
+ const raw = JSON.parse(fs.readFileSync(lockPath(dir), "utf8"));
72
+ if (typeof raw.pid !== "number")
73
+ return null;
74
+ return {
75
+ pid: raw.pid,
76
+ command: raw.command ?? "sync",
77
+ host: raw.host ?? "",
78
+ started_at: raw.started_at ?? "",
79
+ };
80
+ }
81
+ catch {
82
+ return null;
83
+ }
84
+ }
85
+ function describe(lock) {
86
+ return `a virtualmatter ${lock.command} (pid ${lock.pid}${lock.started_at ? `, started ${lock.started_at}` : ""})`;
87
+ }
88
+ function stopHint(lock) {
89
+ return process.platform === "win32" ? `taskkill /PID ${lock.pid} /F` : `kill ${lock.pid}`;
90
+ }
91
+ /**
92
+ * Take the folder for `command`. Returns a release function (also run on
93
+ * exit). A lock left by a process that is gone, or whose pid now belongs to
94
+ * something else, is replaced silently.
95
+ */
96
+ export async function acquireFolderLock(dir, command, opts = {}) {
97
+ const deps = { ...defaultLockDeps, ...opts.deps };
98
+ const log = opts.log ?? ((m) => console.error(m));
99
+ for (let attempt = 0; attempt < 3; attempt++) {
100
+ const held = readLock(dir);
101
+ if (held && held.pid !== deps.pid) {
102
+ if (held.host && held.host !== deps.host) {
103
+ throw new FolderBusyError(`This folder is in use by ${describe(held)} on another machine (${held.host}). ` +
104
+ `Stop it there, or delete ${LOCK_FILE} if that process is gone.`);
105
+ }
106
+ if (deps.isAlive(held.pid)) {
107
+ const ours = deps.isVirtualmatter(held.pid);
108
+ if (ours !== false) {
109
+ if (command !== "sync" || held.command !== "sync" || ours === null) {
110
+ const what = held.command === "sync"
111
+ ? "It already pushes every save, so there is nothing for this command to do while it runs."
112
+ : "Wait for it to finish.";
113
+ throw new FolderBusyError(`This folder is in use by ${describe(held)}. ${what} To stop it: ${stopHint(held)}`);
114
+ }
115
+ await stopProcess(held, deps, log);
116
+ }
117
+ // ours === false: the pid was reused by an unrelated process - stale lock
118
+ }
119
+ fs.rmSync(lockPath(dir), { force: true });
120
+ }
121
+ const info = { pid: deps.pid, command, host: deps.host, started_at: deps.now().toISOString() };
122
+ try {
123
+ if (held?.pid === deps.pid)
124
+ fs.rmSync(lockPath(dir), { force: true });
125
+ fs.writeFileSync(lockPath(dir), JSON.stringify(info) + "\n", { flag: "wx" });
126
+ }
127
+ catch (err) {
128
+ if (err.code === "EEXIST")
129
+ continue; // another process won the race: look again
130
+ throw err;
131
+ }
132
+ let released = false;
133
+ const release = () => {
134
+ if (released)
135
+ return;
136
+ released = true;
137
+ // a long-lived MCP server takes and releases the lock per call
138
+ process.removeListener("exit", release);
139
+ if (readLock(dir)?.pid === deps.pid)
140
+ fs.rmSync(lockPath(dir), { force: true });
141
+ };
142
+ process.once("exit", release);
143
+ return release;
144
+ }
145
+ throw new FolderBusyError(`Could not take ${LOCK_FILE} in ${dir}: another virtualmatter process keeps claiming it.`);
146
+ }
147
+ async function stopProcess(held, deps, log) {
148
+ log(`Stopping ${describe(held)} still running for this folder - two syncs on one folder fight each other.`);
149
+ try {
150
+ deps.kill(held.pid, "SIGTERM");
151
+ }
152
+ catch {
153
+ /* already gone */
154
+ }
155
+ for (let waited = 0; waited < 5000 && deps.isAlive(held.pid); waited += 250)
156
+ await deps.sleep(250);
157
+ if (deps.isAlive(held.pid)) {
158
+ try {
159
+ deps.kill(held.pid, "SIGKILL");
160
+ }
161
+ catch {
162
+ /* already gone */
163
+ }
164
+ for (let waited = 0; waited < 2000 && deps.isAlive(held.pid); waited += 250)
165
+ await deps.sleep(250);
166
+ }
167
+ if (deps.isAlive(held.pid)) {
168
+ throw new FolderBusyError(`${describe(held)} did not stop. Stop it yourself (${stopHint(held)}) and run this again.`);
169
+ }
170
+ }
171
+ /**
172
+ * The processes whose exit should stop a running sync: its parent, and when
173
+ * that parent is only the shell a package runner wrapped it in, the runner
174
+ * too. Killing the `npx` wrapper is how a "stopped" sync used to keep
175
+ * running as an orphan. Unix only; elsewhere just the parent.
176
+ */
177
+ export function supervisingPids() {
178
+ const parent = process.ppid;
179
+ if (process.platform === "win32")
180
+ return [parent];
181
+ const res = spawnSync("ps", ["-o", "ppid=,command=", "-p", String(parent)], { encoding: "utf8", timeout: 5000 });
182
+ if (res.status !== 0)
183
+ return [parent];
184
+ const m = /^\s*(\d+)\s+(.*)$/.exec(res.stdout.trim());
185
+ if (!m)
186
+ return [parent];
187
+ const grandparent = Number(m[1]);
188
+ const isWrapperShell = /(^|\/)(ba|da|z)?sh -c /.test(m[2]) && /virtualmatter/i.test(m[2]);
189
+ return isWrapperShell && grandparent > 1 ? [parent, grandparent] : [parent];
190
+ }
191
+ /**
192
+ * Call `onOrphaned` once any of `pids` exits (or this process is re-parented
193
+ * away from the first one). Returns a stop function.
194
+ */
195
+ export function watchSupervisors(pids, onOrphaned, deps = {}) {
196
+ const isAlive = deps.isAlive ?? processAlive;
197
+ const ppid = deps.ppid ?? (() => process.ppid);
198
+ const first = pids[0];
199
+ const timer = setInterval(() => {
200
+ const gone = (first !== undefined && ppid() !== first) || pids.some((p) => !isAlive(p));
201
+ if (gone) {
202
+ clearInterval(timer);
203
+ onOrphaned();
204
+ }
205
+ }, deps.intervalMs ?? 2000);
206
+ timer.unref();
207
+ return () => clearInterval(timer);
208
+ }
@@ -71,9 +71,9 @@ function text(value) {
71
71
  if (Array.isArray(value))
72
72
  return value
73
73
  .map((b) => typeof b === "string"
74
- ? b
74
+ ? scrub(b)
75
75
  : b && /^(text|input_text|output_text)$/.test(b.type)
76
- ? (b.text ?? "")
76
+ ? scrub(b.text ?? "")
77
77
  : "[non-text content omitted]")
78
78
  .join("\n")
79
79
  .slice(0, 32000);