@slayzone/cli 0.43.0 → 0.44.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.
Files changed (2) hide show
  1. package/dist/slay.js +186 -16
  2. package/package.json +1 -1
package/dist/slay.js CHANGED
@@ -51345,12 +51345,18 @@ ${envEntries}
51345
51345
  </plist>
51346
51346
  `;
51347
51347
  }
51348
+ function systemdStopRecord(spec) {
51349
+ if (spec.kind === "hub") return "";
51350
+ const script = 'mkdir -p "$1" && printf "%%s [systemd] service stopped result=%%s exit=%%s status=%%s\\n" "$$(date -u +%%Y-%%m-%%dT%%H:%%M:%%SZ)" "$$SERVICE_RESULT" "$$EXIT_CODE" "$$EXIT_STATUS" >> "$1/computer.log"';
51351
+ return `ExecStopPost=-/bin/sh -c '${script}' sh "${(0, import_node_path14.join)(spec.root, "logs")}"
51352
+ `;
51353
+ }
51348
51354
  function renderSystemdUnit(spec) {
51349
51355
  assertValidServiceName(spec.kind, spec.name);
51350
51356
  const kind = KINDS[spec.kind];
51351
51357
  const exec = [spec.command, ...spec.args].join(" ");
51352
51358
  const envLines = unitEnv(spec).map(([k, v]) => `Environment=${k}=${v}`).join("\n");
51353
- const agentIsolation = spec.kind === "hub" ? "" : "\nDelegate=memory\nDelegateSubgroup=supervisor\nOOMPolicy=continue";
51359
+ const agentIsolation = spec.kind === "hub" ? "" : "\nDelegate=memory\nDelegateSubgroup=supervisor";
51354
51360
  return `[Unit]
51355
51361
  Description=${kind.description} (${spec.name})
51356
51362
  Documentation=https://github.com/debuglebowski/slayzone
@@ -51364,7 +51370,10 @@ ExecStart=${exec}
51364
51370
  Restart=on-failure
51365
51371
  RestartSec=2
51366
51372
  OOMScoreAdjust=-750${agentIsolation}
51367
- # stdout/stderr go to journald; read them with \`${kind.logsCommand} ${spec.name}\`.
51373
+ # A process the kernel OOM-kills (an agent's build, a headless browser) must not take
51374
+ # the whole service down with it: systemd's default (OOMPolicy=stop) did, twice a day.
51375
+ OOMPolicy=continue
51376
+ ${systemdStopRecord(spec)}# stdout/stderr go to journald; read them with \`${kind.logsCommand} ${spec.name}\`.
51368
51377
  StandardOutput=journal
51369
51378
  StandardError=journal
51370
51379
 
@@ -51465,45 +51474,205 @@ function readUnitSecrets(kind, name, backend, unitDir = defaultUnitDir(backend))
51465
51474
  // ../../shared/platform/src/computer-launcher.ts
51466
51475
  var import_node_fs15 = require("node:fs");
51467
51476
  var import_node_path15 = require("node:path");
51477
+
51478
+ // ../../shared/platform/src/computer-endpoints.ts
51479
+ var UNIX_SOCKET_PATH_MAX_BYTES = {
51480
+ darwin: 104,
51481
+ linux: 108
51482
+ };
51483
+ var HOST_SUPERSEDED_EXIT_CODE = 79;
51484
+ var ENDPOINT_IN_USE_LISTEN_ERRORS = ["EADDRINUSE", "EEXIST"];
51485
+
51486
+ // ../../shared/platform/src/computer-launcher.ts
51468
51487
  var import_node_fs16 = require("node:fs");
51469
51488
  var COMPUTER_LAUNCHER = String.raw`#!/usr/bin/env node
51470
51489
  const fs = require('node:fs'), path = require('node:path'), cp = require('node:child_process');
51490
+ const net = require('node:net'), os = require('node:os'), crypto = require('node:crypto');
51471
51491
  const root = process.env.SLAYZONE_ROOT;
51472
51492
  if (!root) throw Error('computer launcher requires SLAYZONE_ROOT');
51473
51493
  const role = process.argv.includes('--session-host') ? 'host' : 'supervisor';
51474
51494
  const dir = path.join(root, 'computer-runtime'), pointer = path.join(dir, role === 'host' ? 'host-release.json' : 'supervisor.json');
51475
- let child, stopping = false, healthy = false, timer, probation, killTimer;
51495
+ // Restart delay after consecutive failures: 2s doubling to 60s, reset once a child is healthy.
51496
+ const BACKOFF_MIN_MS = 2000, BACKOFF_MAX_MS = 60000, LOG_MAX_BYTES = 5 * 1024 * 1024;
51497
+ // A session host that found another live host on its control endpoint (computer-endpoints.ts).
51498
+ const SUPERSEDED_EXIT = ${HOST_SUPERSEDED_EXIT_CODE};
51499
+ // This root's endpoints, derived exactly as computer-endpoints.ts derives them.
51500
+ const endpointKey = crypto.createHash('sha256').update(path.resolve(root)).digest('hex').slice(0, 24);
51501
+ const endpointDir = process.platform === 'win32' ? null : path.join(os.tmpdir(), 'slay-computer-' + (process.getuid ? process.getuid() : 'user') + '-' + endpointKey);
51502
+ const endpoints = endpointDir
51503
+ ? {control: path.join(endpointDir, 'control.sock'), launcher: path.join(endpointDir, 'l.sock')}
51504
+ : {control: '\\\\.\\pipe\\slay-computer-' + endpointKey, launcher: '\\\\.\\pipe\\slay-computer-launcher-' + endpointKey};
51505
+ // Longest Unix socket path Node accepts (computer-endpoints.ts UNIX_SOCKET_PATH_MAX_BYTES):
51506
+ // a longer one fails listen/connect with a bare EINVAL, so it is refused by name first.
51507
+ const SOCKET_PATH_MAX = ${JSON.stringify(UNIX_SOCKET_PATH_MAX_BYTES)}[process.platform] || 104;
51508
+ // listen errors meaning the endpoint path is already held (computer-endpoints.ts
51509
+ // ENDPOINT_IN_USE_LISTEN_ERRORS): EADDRINUSE, or EEXIST when macOS sees another
51510
+ // launcher bind the same path at the same moment. Either way: probe, never bail.
51511
+ const IN_USE_LISTEN_ERRORS = ${JSON.stringify(ENDPOINT_IN_USE_LISTEN_ERRORS)};
51512
+ function socketPathError(p) {
51513
+ const bytes = Buffer.byteLength(p);
51514
+ return bytes <= SOCKET_PATH_MAX ? null : 'computer endpoint ' + p + ' is ' + bytes + ' bytes, over the ' + SOCKET_PATH_MAX + '-byte Unix socket path limit on ' + process.platform + '; point TMPDIR at a shorter directory';
51515
+ }
51516
+ if (process.argv.includes('--print-endpoints')) { process.stdout.write(JSON.stringify(endpoints) + '\n'); return; }
51517
+ let child, stopping = false, healthy = false, timer, probation, killTimer, failures = 0, nextTimer, lock;
51518
+ // What a waiting supervisor asks over the launcher endpoint (queryHostLauncher).
51519
+ const status = {state: 'starting', childPid: null, nextLaunchAt: null, lastExit: null};
51476
51520
  function read() { return JSON.parse(fs.readFileSync(pointer, 'utf8')); }
51521
+ // Every start and exit of the child, timestamped, to stderr and to logs/computer.log
51522
+ // (shared by every computer process). Before, an exit left no trace at all here.
51523
+ function log(msg) {
51524
+ const line = new Date().toISOString() + ' [launcher ' + process.pid + '] ' + role + ' ' + msg + '\n';
51525
+ try { process.stderr.write(line); } catch {}
51526
+ try { const logs = path.join(root, 'logs'); fs.mkdirSync(logs, {recursive: true, mode: 0o700}); fs.appendFileSync(path.join(logs, 'computer.log'), line, {mode: 0o600}); } catch {}
51527
+ }
51528
+ // The session host's launcher writes, for its whole life, to the host.log it was started
51529
+ // with: rotated only when a host was spawned, it grew without bound (32 MB). Copy, then
51530
+ // truncate in place: every holder of the file appends, so all keep writing to its start.
51531
+ function rotateHostLog() {
51532
+ if (role !== 'host') return;
51533
+ try {
51534
+ const file = path.join(dir, 'host.log'), out = fs.fstatSync(1), st = fs.statSync(file);
51535
+ if (out.ino !== st.ino || out.dev !== st.dev || st.size <= LOG_MAX_BYTES) return;
51536
+ fs.copyFileSync(file, file + '.1'); fs.truncateSync(file, 0);
51537
+ } catch {}
51538
+ }
51539
+ setInterval(rotateHostLog, 600000).unref();
51540
+ // ── One session-host launcher per root ──────────────────────────────────────────
51541
+ // The launcher endpoint is held for this launcher's whole life: a second launcher for
51542
+ // the root finds it live and stops before starting any child. (Two once ran at once,
51543
+ // one restarting an EADDRINUSE-failing child forever, rolling back good releases.)
51544
+ function prepareEndpointDir() {
51545
+ if (!endpointDir) return;
51546
+ try { fs.mkdirSync(endpointDir, {mode: 0o700}); } catch (e) { if (e.code !== 'EEXIST') throw e; }
51547
+ const st = fs.lstatSync(endpointDir);
51548
+ if (st.isSymbolicLink() || !st.isDirectory() || (process.getuid && st.uid !== process.getuid()) || (st.mode & 0o077))
51549
+ throw Error('unsafe computer endpoint directory ' + endpointDir + ': must be a directory owned by this user with mode 0700');
51550
+ }
51551
+ // live / stale / absent as probeEndpoint (computer-endpoints.ts) tells them; any other
51552
+ // connect error says nothing about an owner and is passed on (cb(null, err)).
51553
+ function probe(cb) {
51554
+ const s = net.connect(endpoints.launcher); let done = false;
51555
+ const fin = (r, err) => { if (done) return; done = true; clearTimeout(t); s.destroy(); cb(r, err); };
51556
+ const t = setTimeout(() => fin('live'), 2000);
51557
+ s.once('connect', () => fin('live'));
51558
+ s.once('error', (e) => e.code === 'ENOENT' ? fin('absent') : e.code === 'ECONNREFUSED' ? fin('stale') : e.code === 'EAGAIN' ? fin('live') : fin(null, e));
51559
+ }
51560
+ function serveStatus(socket) {
51561
+ let buf = '';
51562
+ socket.setEncoding('utf8'); socket.on('error', () => {}); socket.setTimeout(2000, () => socket.destroy());
51563
+ socket.on('data', (chunk) => {
51564
+ buf += chunk; const end = buf.indexOf('\n');
51565
+ if (end < 0) { if (buf.length > 1024) socket.destroy(); return; }
51566
+ let command; try { command = JSON.parse(buf.slice(0, end)).command; } catch {}
51567
+ if (command === 'launch-now' && status.state === 'backoff' && !stopping) { clearTimeout(nextTimer); log('launching now, at a waiting supervisor\'s request'); launch(); }
51568
+ socket.end(JSON.stringify(status) + '\n');
51569
+ });
51570
+ }
51571
+ function bail(msg) { log(msg + '; stopping'); process.exit(1); }
51572
+ // Every bind of the launcher endpoint happens inside one short critical section (an
51573
+ // atomic mkdir of the guard). listen() on a Unix socket is bind() then listen(): in
51574
+ // between, the file exists but refuses connections, exactly like one whose launcher
51575
+ // died. With binds serialized, a refusing socket seen while holding the guard can only
51576
+ // be a dead launcher's, so replacing it is safe. (2026-11-27: under full CPU load a
51577
+ // launcher probed a winner preempted in that gap, "took over" its live endpoint, and
51578
+ // two launchers each ran a host.) Windows: named pipes are exclusive; no guard needed.
51579
+ // The guard keeps its old name so an older launcher.cjs still running excludes with it.
51580
+ const GUARD_STALE_MS = 10000;
51581
+ function acquire(then, attempt) {
51582
+ attempt = attempt || 0;
51583
+ if (attempt > 50) return bail('cannot take the launcher endpoint ' + endpoints.launcher);
51584
+ if (endpointDir) { const tooLong = socketPathError(endpoints.launcher) || socketPathError(endpoints.control); if (tooLong) return bail(tooLong); }
51585
+ try { prepareEndpointDir(); } catch (e) { return bail(e.message); }
51586
+ const retry = (ms) => setTimeout(() => acquire(then, attempt + 1), ms);
51587
+ const guard = endpointDir ? endpoints.launcher + '.takeover' : null;
51588
+ if (guard) {
51589
+ try { fs.mkdirSync(guard, {mode: 0o700}); } catch (e) {
51590
+ // ENOENT: a launcher exiting just removed the (empty) endpoint directory.
51591
+ if (e.code === 'ENOENT') return retry(0);
51592
+ if (e.code !== 'EEXIST') return bail('cannot take ' + guard + ': ' + e.message);
51593
+ // Held for a bind (milliseconds). Waiting on it is not a failed attempt: it ends
51594
+ // when the holder finishes, or GUARD_STALE_MS after a holder that died holding it.
51595
+ try { if (Date.now() - fs.statSync(guard).mtimeMs > GUARD_STALE_MS) fs.rmdirSync(guard); } catch {}
51596
+ return setTimeout(() => acquire(then, attempt), 25);
51597
+ }
51598
+ }
51599
+ const unguard = () => { if (guard) try { fs.rmdirSync(guard); } catch {} };
51600
+ const won = (server, how) => { unguard(); if (how) log(how); lock = server; then(); };
51601
+ const server = net.createServer(serveStatus);
51602
+ server.once('error', (err) => {
51603
+ if (!IN_USE_LISTEN_ERRORS.includes(err.code)) { unguard(); return bail('cannot bind ' + endpoints.launcher + ': ' + err.message); }
51604
+ probe((state, probeErr) => {
51605
+ if (probeErr) { unguard(); return bail('cannot probe ' + endpoints.launcher + ': ' + (probeErr.code || probeErr.message)); }
51606
+ if (state === 'live') { unguard(); log('launcher already running for this root; superseded, stopping'); process.exit(0); }
51607
+ if (state === 'absent' || !guard) { unguard(); return retry(50); }
51608
+ // Stale: its launcher died (no live one binds without the guard this one holds).
51609
+ try { fs.unlinkSync(endpoints.launcher); } catch {}
51610
+ const taken = net.createServer(serveStatus);
51611
+ taken.once('error', () => { unguard(); retry(0); });
51612
+ taken.listen(endpoints.launcher, () => won(taken, 'took over a launcher endpoint left by a dead launcher'));
51613
+ });
51614
+ });
51615
+ server.listen(endpoints.launcher, () => won(server));
51616
+ }
51617
+ // Ends this launcher: frees its endpoint (and the directory, once empty), then exits.
51618
+ function release(code) {
51619
+ status.state = 'stopping'; status.nextLaunchAt = null; clearTimeout(nextTimer);
51620
+ process.exitCode = code;
51621
+ if (!lock) return;
51622
+ lock.close(() => { if (endpointDir) try { fs.rmdirSync(endpointDir); } catch {} });
51623
+ lock = undefined;
51624
+ }
51477
51625
  function launch() {
51478
51626
  if (stopping) return;
51627
+ rotateHostLog();
51479
51628
  const state = read(); let timedOut = false; healthy = false; probation = undefined;
51629
+ const startedAt = Date.now();
51480
51630
  child = cp.fork(state.current.entry, [role === 'host' ? '--session-host' : '--supervisor'], {env: {...process.env, SLAYZONE_NONINTERACTIVE:'1'}, stdio:['inherit','inherit','inherit','ipc']});
51631
+ status.state = 'running'; status.childPid = child.pid; status.nextLaunchAt = null;
51632
+ log(state.current.version + ' started pid=' + child.pid + (failures ? ' (after ' + failures + ' consecutive failures)' : ''));
51481
51633
  timer = setTimeout(() => {
51482
51634
  timedOut = true;
51483
- process.stderr.write('[computer-launcher] ' + role + ' ' + state.current.version + ' startup timed out; restarting\n');
51635
+ log(state.current.version + ' startup timed out; restarting');
51484
51636
  // A supervisor SIGTERM means explicit shutdown, including its persistent host.
51485
51637
  // Crash only the supervisor; its connectors stop on IPC loss and work survives.
51486
51638
  if (role === 'supervisor') child.kill('SIGKILL');
51487
51639
  else { child.kill('SIGTERM'); killTimer = setTimeout(() => child.kill('SIGKILL'), 10000); }
51488
51640
  }, 90000);
51489
- child.on('message', m => { if (m && m.type === 'supervisor-ready') {clearTimeout(timer); if (!probation) probation = setTimeout(() => {healthy = true;}, 60000);} });
51490
- child.on('error', () => {});
51491
- child.on('exit', (code) => {
51641
+ child.on('message', m => { if (m && m.type === 'supervisor-ready') {clearTimeout(timer); if (!probation) probation = setTimeout(() => {healthy = true; failures = 0;}, 60000);} });
51642
+ child.on('error', (err) => { log(state.current.version + ' child error: ' + (err && err.message)); });
51643
+ child.on('exit', (code, signal) => {
51492
51644
  clearTimeout(timer); clearTimeout(probation); clearTimeout(killTimer);
51493
- if (stopping) {process.exitCode = code || 0; return;}
51494
- if (code === 75 && !timedOut) {launch(); return;}
51645
+ const ended = state.current.version + ' pid=' + child.pid + ' exited code=' + code + ' signal=' + signal + ' after ' + (Date.now() - startedAt) + 'ms';
51646
+ status.childPid = null; status.lastExit = {version: state.current.version, code, signal, at: Date.now()};
51647
+ if (stopping) {log(ended + '; stopping'); release(code || 0); return;}
51648
+ // Another live host owns the endpoint: not a failure of this release (no
51649
+ // quarantine, no rollback), and nothing to restart. This launcher is redundant.
51650
+ if (role === 'host' && code === SUPERSEDED_EXIT && !timedOut) {log(ended + '; superseded by a live session host, stopping'); stopping = true; release(0); return;}
51651
+ if (code === 75 && !timedOut) {log(ended + '; relaunching (requested)'); launch(); return;}
51495
51652
  const failed = timedOut || code !== 0;
51653
+ let rolledBack = '';
51496
51654
  if (!healthy && failed && state.previous) {
51497
51655
  fs.writeFileSync(path.join(dir, role + '-quarantine.json'), JSON.stringify({version: state.current.version, until: Date.now() + 900000}), {mode:0o600});
51498
51656
  const temp = pointer + '.tmp';
51499
51657
  fs.writeFileSync(temp, JSON.stringify({current:state.previous}) + '\n', {mode:0o600}); fs.renameSync(temp,pointer);
51658
+ rolledBack = '; quarantined, rolled back to ' + state.previous.version;
51500
51659
  }
51501
- if (!failed) return;
51502
- setTimeout(launch, 2000);
51660
+ if (!failed) {log(ended + '; not restarting'); release(0); return;}
51661
+ failures += 1;
51662
+ const delay = Math.min(BACKOFF_MIN_MS * Math.pow(2, failures - 1), BACKOFF_MAX_MS);
51663
+ log(ended + rolledBack + '; restarting in ' + delay + 'ms (failure ' + failures + ')');
51664
+ status.state = 'backoff'; status.nextLaunchAt = Date.now() + delay;
51665
+ nextTimer = setTimeout(launch, delay);
51503
51666
  });
51504
51667
  }
51505
- for (const signal of ['SIGINT','SIGTERM']) process.on(signal, () => {stopping = true; child?.kill(signal);});
51506
- launch();
51668
+ for (const signal of ['SIGINT','SIGTERM']) process.on(signal, () => {
51669
+ stopping = true; log('received ' + signal + ', stopping');
51670
+ // No child up (backing off, or not started yet): nothing to wait for.
51671
+ if (child && child.exitCode === null && child.signalCode === null) child.kill(signal);
51672
+ else release(0);
51673
+ });
51674
+ if (role === 'host') acquire(() => (stopping ? release(0) : launch()));
51675
+ else launch();
51507
51676
  `;
51508
51677
  function ensureComputerLauncher(root, release, forceUpgrade = false) {
51509
51678
  const dir = (0, import_node_path15.join)(root, "computer-runtime");
@@ -51547,7 +51716,7 @@ var import_node_child_process4 = require("node:child_process");
51547
51716
  var import_node_fs17 = require("node:fs");
51548
51717
  var import_node_module = require("node:module");
51549
51718
  var import_node_path16 = require("node:path");
51550
- var CLI_VERSION = true ? "0.43.0" : "";
51719
+ var CLI_VERSION = true ? "0.44.0" : "";
51551
51720
  function fail(message) {
51552
51721
  console.error(message);
51553
51722
  process.exit(1);
@@ -52238,7 +52407,8 @@ var nodeHubTransport = (request2) => new Promise((resolve2, reject) => {
52238
52407
  let text = "";
52239
52408
  res.setEncoding("utf8");
52240
52409
  res.on("data", (chunk) => {
52241
- if (text.length < request2.maxResponseChars) text += chunk;
52410
+ if (text.length < request2.maxResponseChars)
52411
+ text += chunk.slice(0, request2.maxResponseChars - text.length);
52242
52412
  });
52243
52413
  res.on(
52244
52414
  "end",
@@ -54251,7 +54421,7 @@ function updateCommand() {
54251
54421
  }
54252
54422
 
54253
54423
  // src/index.ts
54254
- var program2 = new Command().enablePositionalOptions().name("slay").description("SlayZone CLI").version("0.43.0").option("--dev", "Use development database (slayzone.dev.data.sqlite)").option("--hub <name|port>", "Target a specific hub on this machine (see `slay hub ls`)").showSuggestionAfterError(true).showHelpAfterError(true).hook("preAction", async (thisCommand) => {
54424
+ var program2 = new Command().enablePositionalOptions().name("slay").description("SlayZone CLI").version("0.44.0").option("--dev", "Use development database (slayzone.dev.data.sqlite)").option("--hub <name|port>", "Target a specific hub on this machine (see `slay hub ls`)").showSuggestionAfterError(true).showHelpAfterError(true).hook("preAction", async (thisCommand) => {
54255
54425
  const root = thisCommand.parent ?? thisCommand;
54256
54426
  const opts = root.opts();
54257
54427
  if (opts.dev) process.env.SLAYZONE_DEV = "1";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@slayzone/cli",
3
- "version": "0.43.0",
3
+ "version": "0.44.0",
4
4
  "description": "SlayZone CLI — run, list and target SlayZone hubs; drive tasks, ptys and projects",
5
5
  "license": "GPL-3.0-only",
6
6
  "private": false,