clavarium 0.2.484-next.1 → 0.2.486-next.1

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.
@@ -89,6 +89,11 @@ const ASK_EVERY_MS = 6 * 3600_000;
89
89
  had it): nothing of it ran here, so it is tried again by itself, this long after, this many times at most. */
90
90
  export const FETCH_AGAIN_MS = 30 * 60_000;
91
91
  export const FETCH_TRIES = 3;
92
+ /* NOT RACING THE REGISTRY (17-11: 0.2.228-beta.1 asked of npm the minute it was tagged, refused; the same
93
+ install worked 20 minutes later): a version is installed by itself only once it has been out this long --
94
+ since its time in the registry (`time`), or since this updater first saw it when the registry says none.
95
+ Asked by the owner (Update, Try again): at once. */
96
+ export const RELEASE_SETTLE_MS = 10 * 60_000;
92
97
  /* Between "Switching" said in state.json and the server stopped: the pages ask the server every
93
98
  10 seconds at most (app.js), and the server says it in each answer (updates.mjs, notice): each
94
99
  gives way to the maintenance page before the server goes. */
@@ -96,6 +101,8 @@ export const NOTICE_MS = 15_000;
96
101
  const PROVENANCE = 'https://slsa.dev/provenance/v1';
97
102
  /* What the log of a failure keeps, at most (history entry `log`, shown behind "See the log"). */
98
103
  const LOG_MAX = 12_000;
104
+ /* Of npm's own debug log (in its cache, which goes with the attempt): the last lines kept in the history. */
105
+ const NPM_LOG_LINES = 40;
99
106
  /* Set beside the server's unit by the updater (root): a crash loop never locks the service out, so a
100
107
  restart asked later (an update, the watchdog) still starts it. */
101
108
  export const DROP_IN = '/etc/systemd/system/clavarium.service.d/restart.conf';
@@ -263,6 +270,37 @@ export async function ensureMaintenance({ caddyfile = CADDYFILE, caddy = CADDY,
263
270
  }
264
271
 
265
272
  export class Refused extends Error {}
273
+ /* NOTHING OF THE VERSION RAN: npm could not install it, or the registry did not answer about it (not there
274
+ yet, a mirror behind, the network). Said in the history as `fetch: true`, tried again by itself later.
275
+ `log`: what npm said, for "See the log". */
276
+ export class FetchFailed extends Error {
277
+ constructor(message, { log } = {}) { super(message); this.log = log; }
278
+ }
279
+
280
+ /* WHAT A LOG MUST NEVER SHOW: npm's debug log can carry the registry's credentials (an .npmrc token, an
281
+ Authorization header, a URL with a password). Each is put as ***. */
282
+ export function redact(text) {
283
+ return String(text ?? '')
284
+ .replace(/\b(proxy-authorization|authorization)(["']?\s*[:=]\s*["']?)(?:(bearer|basic|token)\s+)?[^\s"',;}]+/gi, (_, k, sep, scheme) => `${k}${sep}${scheme ? `${scheme} ` : ''}***`)
285
+ .replace(/\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]{6,}/gi, '$1 ***')
286
+ .replace(/((?:_authToken|_auth|_password|authToken|token|password|passwd|secret|otp)["']?\s*[=:]\s*["']?)[^\s"',;}]+/gi, '$1***')
287
+ .replace(/\bnpm_[A-Za-z0-9]{16,}\b/g, 'npm_***')
288
+ .replace(/\bgh[opsur]_[A-Za-z0-9]{16,}\b/g, 'gh*_***')
289
+ .replace(/(\/\/)[^\s/@:]+:[^\s/@]+@/g, '$1***@');
290
+ }
291
+
292
+ /* The end of npm's own debug log, from the cache it was given: the last lines that say something (its
293
+ `silly` lines, its call stack and its pointer to itself left out), each bounded, credentials taken out. '' when there is none. */
294
+ export function npmLogTail(cache, lines = NPM_LOG_LINES) {
295
+ const dir = join(cache, '_logs');
296
+ let name;
297
+ try { name = readdirSync(dir).filter((f) => f.endsWith('.log')).sort().pop(); } catch { return ''; }
298
+ if (!name) return '';
299
+ let text = '';
300
+ try { text = readFileSync(join(dir, name), 'utf8'); } catch { return ''; }
301
+ const kept = text.split('\n').filter((l) => l.trim() && !/^\d+\s+silly\b|^\d+\s+verbose stack\s+at |A complete log of this run can be found in/.test(l)).slice(-lines).map((l) => (l.length > 500 ? `${l.slice(0, 500)}...` : l));
302
+ return redact(kept.join('\n'));
303
+ }
266
304
 
267
305
  /* SEMANTIC VERSIONS, compared as npm does: a pre-release comes before its release. */
268
306
  export function compareVersions(a, b) {
@@ -328,7 +366,19 @@ export function runCommand(argv, { cwd, env = process.env, timeoutMs = 900_000 }
328
366
  });
329
367
  }
330
368
 
331
- const lastLine = (r) => String(r.stderr || r.stdout || '').trim().split('\n').filter((l) => l.trim() && !/^npm (notice|warn)/.test(l)).pop()?.slice(0, 300) ?? `exit ${r.code}`;
369
+ /* npm's lines that say nothing of why: its notices, its warnings, its pointer to a log that is gone with
370
+ its cache, its empty error lines. */
371
+ const NPM_NOISE = /^npm (notice|warn)|A complete log of this run can be found in|^npm (error|ERR!)\s*$/;
372
+ const lastLine = (r) => redact(String(r.stderr || r.stdout || '').trim().split('\n').filter((l) => l.trim() && !NPM_NOISE.test(l)).pop()?.slice(0, 300) ?? `exit ${r.code}`);
373
+ /* Why npm failed, in one line: its error code and its first words of explanation ("code ETARGET: notarget
374
+ No matching version found for ..."), else its last line that says something. */
375
+ function npmWhy(r) {
376
+ const errors = String(r.stderr || r.stdout || '').split('\n').map((l) => /^npm (?:error|ERR!) (.+)$/.exec(l.trim())?.[1]?.trim()).filter((l) => l && !NPM_NOISE.test(`npm error ${l}`));
377
+ const code = errors.find((l) => /^code \S+$/.test(l));
378
+ const said = errors.find((l) => !/^(code|errno|syscall|path|dest|signal|command|cwd) /.test(l));
379
+ if (!code && !said) return lastLine(r);
380
+ return redact([code, said].filter(Boolean).join(': ').slice(0, 300));
381
+ }
332
382
  const stamp = (d) => d.toISOString().replace(/[-:]/g, '').replace('T', '-').slice(0, 15);
333
383
  const toHex = (integrity) => Buffer.from(String(integrity).replace(/^sha512-/, ''), 'base64').toString('hex');
334
384
 
@@ -336,8 +386,8 @@ export class Updater {
336
386
  #o; #run; #fetch;
337
387
  constructor({ code = PATHS.code, conf = PATHS.conf, stateDir = PATHS.stateDir, data = PATHS.data, hostTarget = PATHS.host, gitReadTarget = PATHS.gitRead, tunnelTarget = PATHS.tunnel, registry = REGISTRY, run = runCommand, fetcher = fetch, now = () => new Date(), log = (line) => console.log(line),
338
388
  verifySignatures, restart, health, backup, restoreData, installPrivileged, ensureNode, serviceState, answers, restarts, mainPid, pidCwd, diagnose, dropIn = DROP_IN,
339
- clock = () => Date.now(), sleep = (ms) => new Promise((r) => setTimeout(r, ms)), minFreeMb = 1024, healthMs = 60_000, watchMs = 120_000, settleMs = 10_000, noticeMs = NOTICE_MS } = {}) {
340
- this.#o = { code, conf, stateDir, data, hostTarget, gitReadTarget, tunnelTarget, registry: registry.replace(/\/$/, ''), now, log, minFreeMb, healthMs, watchMs, settleMs, noticeMs, clock, sleep, dropIn };
389
+ clock = () => Date.now(), sleep = (ms) => new Promise((r) => setTimeout(r, ms)), minFreeMb = 1024, healthMs = 60_000, watchMs = 120_000, settleMs = 10_000, noticeMs = NOTICE_MS, releaseSettleMs = RELEASE_SETTLE_MS } = {}) {
390
+ this.#o = { code, conf, stateDir, data, hostTarget, gitReadTarget, tunnelTarget, registry: registry.replace(/\/$/, ''), now, log, minFreeMb, healthMs, watchMs, settleMs, noticeMs, releaseSettleMs, clock, sleep, dropIn };
341
391
  this.#run = run; this.#fetch = fetcher;
342
392
  this.verifySignatures = verifySignatures ?? ((dir) => this.#npm(['audit', 'signatures'], { cwd: dir, timeoutMs: 300_000 }));
343
393
  this.restart = restart ?? (() => this.#restart());
@@ -403,10 +453,12 @@ export class Updater {
403
453
 
404
454
  set(key, value) { writeConf(this.#o.conf, key, value); return this.about(); }
405
455
 
456
+ /* The registry not answering, or not with what was asked: a fetch failure (FetchFailed), not the release's fault. */
406
457
  async #json(url) {
407
- const answer = await this.#fetch(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(60_000) });
408
- if (!answer.ok) throw new Error(`the registry answered ${answer.status} for ${url}`);
409
- return answer.json();
458
+ let answer;
459
+ try { answer = await this.#fetch(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(60_000) }); } catch (error) { throw new FetchFailed(`the registry could not be reached for ${url}: ${error.cause?.code ?? error.message}`); }
460
+ if (!answer.ok) throw new FetchFailed(`the registry answered ${answer.status} for ${url}`);
461
+ try { return await answer.json(); } catch (error) { throw new FetchFailed(`the registry's answer for ${url} was cut: ${error.message}`); }
410
462
  }
411
463
  #packument(name) { return this.#json(`${this.#o.registry}/${name}`); }
412
464
 
@@ -424,7 +476,11 @@ export class Updater {
424
476
  if (conf.CHANNEL === 'beta' && tags.beta && (!candidate || compareVersions(tags.beta, candidate) > 0)) candidate = tags.beta;
425
477
  if (candidate && (!VERSION.test(candidate) || !p.versions?.[candidate])) candidate = undefined;
426
478
  const available = candidate && (!current || compareVersions(candidate, current.version) > 0) ? candidate : null;
427
- this.#save({ checkedAt: this.#o.now().toISOString(), available, checkError: null });
479
+ /* Since when it is out (RELEASE_SETTLE_MS): the registry's time for it, and when it was first seen here. */
480
+ const was = this.#state().outSince;
481
+ const published = Date.parse(p.time?.[available] ?? '');
482
+ const outSince = available ? { version: available, seenAt: was?.version === available && was.seenAt ? was.seenAt : this.#o.now().toISOString(), publishedAt: Number.isFinite(published) ? new Date(published).toISOString() : null } : null;
483
+ this.#save({ checkedAt: this.#o.now().toISOString(), available, checkError: null, outSince });
428
484
  return available;
429
485
  } catch (error) {
430
486
  this.#save({ checkedAt: this.#o.now().toISOString(), checkError: `The registry could not be asked: ${error.message}` });
@@ -442,6 +498,12 @@ export class Updater {
442
498
  }
443
499
 
444
500
  #npmEnv(nodeDir) { return { ...process.env, PATH: `${nodeDir ? `${nodeDir}/bin:` : ''}${dirname(process.execPath)}:${process.env.PATH ?? '/usr/bin:/bin'}`, npm_config_update_notifier: 'false', npm_config_fund: 'false', npm_config_audit: 'false' }; }
501
+ /* What npm said when it failed, for "See the log": its own words, then the end of its debug log. */
502
+ #npmFailure(r, what) {
503
+ const said = redact(String(r.stderr || r.stdout || '').trim().split('\n').filter((l) => !/A complete log of this run can be found in/.test(l)).slice(-20).join('\n'));
504
+ const tail = npmLogTail(join(this.#o.stateDir, 'npm-cache'));
505
+ return [`== ${this.#o.now().toISOString()} ${what} failed (exit ${r.code})`, `-- what npm said\n${said || '(nothing)'}`, ...(tail ? [`-- the end of npm's debug log\n${tail}`] : [])].join('\n').slice(-LOG_MAX);
506
+ }
445
507
  #npm(args, { cwd, nodeDir, timeoutMs = 900_000 } = {}) {
446
508
  const npm = nodeDir ? join(nodeDir, 'bin', 'npm') : join(dirname(process.execPath), 'npm');
447
509
  return this.#run([npm, ...args, '--registry', `${this.#o.registry}/`, '--cache', join(this.#o.stateDir, 'npm-cache'), '--loglevel=error'], { cwd, env: this.#npmEnv(nodeDir), timeoutMs });
@@ -465,9 +527,12 @@ export class Updater {
465
527
  this.#step(action, id, 'Fetching');
466
528
  writeFileSync(join(tmp, 'package.json'), `${JSON.stringify({ name: 'clavarium-release', private: true, dependencies: { [NAME]: version } }, null, 2)}\n`);
467
529
  const got = await this.#npm(['install', '--ignore-scripts', '--no-audit', '--no-fund', '--save-exact'], { cwd: tmp });
468
- if (got.code !== 0) throw new Error(`npm could not install ${NAME}@${version}: ${lastLine(got)}`);
530
+ /* Whatever made it fail (not there yet, a mirror behind, the network, a cut archive), nothing of it ran:
531
+ a fetch failure, with what npm said kept (its debug log goes with its cache, below). */
532
+ if (got.code !== 0) throw new FetchFailed(`npm could not install ${NAME}@${version}: ${npmWhy(got)}`, { log: this.#npmFailure(got, `npm install ${NAME}@${version}`) });
469
533
  app = join(tmp, 'node_modules', NAME);
470
- const manifest = JSON.parse(readFileSync(join(app, 'package.json'), 'utf8'));
534
+ let manifest;
535
+ try { manifest = JSON.parse(readFileSync(join(app, 'package.json'), 'utf8')); } catch (error) { throw new FetchFailed(`npm could not install ${NAME}@${version}: it left no package (${error.code ?? error.message})`, { log: this.#npmFailure(got, `npm install ${NAME}@${version}`) }); }
471
536
  if (manifest.name !== NAME || manifest.version !== version) throw new Error(`npm installed ${manifest.name}@${manifest.version}, not ${NAME}@${version}`);
472
537
  this.#step(action, id, 'Checking');
473
538
  await this.verify(tmp, version);
@@ -514,6 +579,8 @@ export class Updater {
514
579
  const own = entry(NAME);
515
580
  const p = await this.#packument(NAME);
516
581
  const dist = p.versions?.[version]?.dist;
582
+ /* Installed, but not listed by the registry that was asked next (a mirror behind): fetched again later. */
583
+ if (own && !dist) throw new FetchFailed(`the registry does not list ${NAME}@${version} yet`);
517
584
  if (!own || !dist || own.version !== version || own.integrity !== dist.integrity) throw new Error(`${NAME}@${version} as installed is not the archive the registry lists`);
518
585
  for (const name of Object.keys(REPOS)) {
519
586
  const e = name === NAME ? own : entry(name);
@@ -606,7 +673,11 @@ export class Updater {
606
673
  const unlock = this.#lock();
607
674
  try {
608
675
  let release;
609
- try { release = await this.prepare({ version }); } catch (error) { this.#history({ action: 'update', from: from?.version ?? null, to: version, result: 'failed', why: error.message, ...(/^npm could not install /.test(error.message) ? { fetch: true } : {}) }); throw error; }
676
+ try { release = await this.prepare({ version }); } catch (error) {
677
+ const fetched = error instanceof FetchFailed || /^npm could not install /.test(error.message);
678
+ this.#history({ action: 'update', from: from?.version ?? null, to: version, result: 'failed', why: error.message, ...(fetched ? { fetch: true } : {}), ...(typeof error.log === 'string' && error.log ? { log: error.log.slice(-LOG_MAX) } : {}) });
679
+ throw error;
680
+ }
610
681
  const before = this.#dataFormat();
611
682
  let archive;
612
683
  try {
@@ -725,6 +796,10 @@ export class Updater {
725
796
  if (failed.length >= FETCH_TRIES) return `${available} could not be fetched ${failed.length} times: not tried again by itself`;
726
797
  const lastAt = Math.max(...failed.map((h) => new Date(h.at ?? 0).getTime()), -Infinity);
727
798
  if (failed.length && now - lastAt < FETCH_AGAIN_MS) return `${available} could not be fetched: tried again later`;
799
+ /* Just out: every mirror given time to have it (RELEASE_SETTLE_MS). */
800
+ const out = this.#state().outSince;
801
+ const outAt = Math.min(...[out?.version === available ? out.seenAt : null, out?.version === available ? out.publishedAt : null].map((t) => Date.parse(t ?? '')).filter(Number.isFinite), now.getTime());
802
+ if (now - outAt < this.#o.releaseSettleMs) return `${available} is just out: installed by itself from ${new Date(outAt + this.#o.releaseSettleMs).toISOString()}`;
728
803
  const why = await this.busy(); if (why) return why;
729
804
  await this.apply(available);
730
805
  /* What the history says, not what was hoped: a version that did not start was undone. */
@@ -869,11 +944,19 @@ export class Updater {
869
944
  const port = readConf(this.#o.conf).PORT;
870
945
  const part = async (title, argv) => { const r = await this.#run(argv, { timeoutMs: 20_000 }); return `-- ${title}\n${String(r.stdout || r.stderr || `exit ${r.code}`).trim()}`; };
871
946
  const left = await this.#leftovers().catch(() => []);
947
+ /* WHAT THE SERVER ITSELF SAID (17-11): the unit's journal is mostly the sudo lines of the host program it
948
+ runs (a hundred a minute), its own words lost among them -- the owner saw only those, and no reason.
949
+ Read further back, the sudo and PAM lines left out, the last of the rest kept. */
950
+ const serverSaid = async () => {
951
+ const r = await this.#run(['journalctl', '-u', 'clavarium.service', '-n', '4000', '--no-pager', '-o', 'short-iso'], { timeoutMs: 20_000 });
952
+ const lines = String(r.stdout || '').split('\n').filter((l) => l.trim() && !/ (sudo|pkexec)\[\d+\]: | pam_unix\(/.test(l));
953
+ return `-- what the server said (journalctl -u clavarium, sudo lines left out)\n${lines.slice(-80).join('\n').trim() || String(r.stderr || `exit ${r.code}`).trim()}`;
954
+ };
872
955
  return [
873
956
  await part('systemctl status clavarium', ['systemctl', 'status', 'clavarium.service', '--no-pager', '-n', '0']),
874
957
  await part(`who listens on ${port}`, ['ss', '-Hltnp', `sport = :${port}`]),
875
958
  `-- processes of the server's unit or on its port\n${left.map((p) => `pid ${p.pid} state ${p.state}${p.port ? ' (holds the port)' : ''}`).join('\n') || 'none'}`,
876
- await part('journalctl -u clavarium -n 80', ['journalctl', '-u', 'clavarium.service', '-n', '80', '--no-pager', '-o', 'short-iso']),
959
+ await serverSaid(),
877
960
  ].join('\n');
878
961
  }
879
962
 
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.484-next.1",
3
+ "version": "0.2.486-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.484-next.1",
9
+ "version": "0.2.486-next.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.484-next.1",
3
+ "version": "0.2.486-next.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "A conversation is a VM with a terminal in it. Everything else is a folder.",
package/server/talk.mjs CHANGED
@@ -135,8 +135,8 @@ export const TYPED_AT = 3 + LEAVE_MODE.length + 5;
135
135
  export const BRANCHES = 'Check out your branches in the main folder of the repository or under /work, never in /tmp: a branch can be checked out in one folder only, and /tmp is emptied when the machine restarts. The checks before sending run in a copy made at exactly the commit to send (CLAVARIUM_CHECK_COPY, CLAVARIUM_CHECK_HEAD): never write a check that needs the main folder on a branch or at that commit.';
136
136
  /* THE LINE TYPED AGAIN BY ITSELF (17-11): one line lost (a pane in copy mode, a tool drawing a modal)
137
137
  silenced every later one, the tool "told" till it read. A message still unread this long after its
138
- line was typed has it typed again, these long after the last, then every last one of them -- till the
139
- tool reads (its read count moves). Kept in its record: a restart of this server goes on. */
138
+ line was typed has it typed again, these long after the last -- three times at most, then no more
139
+ (never a reminder without end): the owner's "Remind it" is there. Kept in its record: a restart of this server goes on. */
140
140
  export const RENUDGE_MS = Object.freeze([60_000, 180_000, 600_000]);
141
141
  /* After a restart, the tool is given this long to start before REREAD is typed. */
142
142
  export const REREAD_AFTER_MS = 10_000;
@@ -849,8 +849,10 @@ export class Talk {
849
849
  if (unread === 0) { this.#store.put({ ...r, woke: false }); return; }
850
850
  /* It read since, and more was written: the line is owed now. */
851
851
  if (this.#readSince(r.name, r)) { await this.#wake(r.name); return; }
852
- /* Still unread long after: typed again, RENUDGE_MS apart, the last of them for ever after. */
853
- const after = RENUDGE_MS[Math.min(r.renudged ?? 0, RENUDGE_MS.length - 1)];
852
+ /* Still unread long after: typed again, RENUDGE_MS apart -- AS MANY TIMES AS THERE ARE, NO MORE (17-11,
853
+ the owner: never a reminder without end). Then it waits: its chat keeps "Remind it" for the owner. */
854
+ if ((r.renudged ?? 0) >= RENUDGE_MS.length) return;
855
+ const after = RENUDGE_MS[r.renudged ?? 0];
854
856
  const at = Date.parse(r.typedAt ?? '');
855
857
  if (Number.isFinite(at) && this.#now() - at >= after && this.#now() >= (this.#nextTry.get(r.name) ?? 0)) await this.#wake(r.name, true, false, true);
856
858
  return;
@@ -109,7 +109,9 @@ export class Updates {
109
109
  back: releases.filter((r) => !r.current && (VERSION.test(r.id) || LOCAL.test(r.id))).map((r) => ({ id: r.id, version: r.version })),
110
110
  /* What became of the relay at the updater's last turn (deploy/updater.mjs, relay.json beside the state). */
111
111
  relay: (() => { try { const r = JSON.parse(readFileSync(join(dirname(this.#state), 'relay.json'), 'utf8')); return RELAY_STATES.includes(r.state) ? { state: r.state, version: typeof r.version === 'string' ? r.version : null, why: typeof r.why === 'string' ? r.why.slice(0, 300) : null, at: typeof r.at === 'string' ? r.at : null } : null; } catch { return null; } })(),
112
- history: (Array.isArray(s.history) ? s.history : []).slice(0, HISTORY_SHOWN).map(({ at, action, from, to, result, why, log }) => ({ at, action, from, to, result, why: why ?? null, log: typeof log === 'string' ? log : null })),
112
+ /* `fetch`: nothing of that version ran (npm could not fetch it): the page says it is tried again by itself
113
+ (app.js, updates-retry-note). Left out before 17-11, every such failure read "It did not start here". */
114
+ history: (Array.isArray(s.history) ? s.history : []).slice(0, HISTORY_SHOWN).map(({ at, action, from, to, result, why, log, fetch }) => ({ at, action, from, to, result, why: why ?? null, log: typeof log === 'string' ? log : null, fetch: fetch === true })),
113
115
  };
114
116
  }
115
117
 
package/server/vm.mjs CHANGED
@@ -80,6 +80,19 @@ export function runner(prefix) {
80
80
 
81
81
  /* The verbs that change a machine: its state is asked again after them. */
82
82
  export const TRIM_MS = 120_000;
83
+ export const COUNT_EVERY_MS = 5 * 60_000;
84
+ /* What a command to the host is, for the tally: its verb, and for a command in a machine the program it runs
85
+ (past `sudo -n clavarium-enter <name> --`, `timeout ...`, `sh -c`'s script left out). Never its arguments. */
86
+ export function commandKind(argv) {
87
+ const a = argv.map(String);
88
+ if (a[0] !== 'vm' || a[1] !== 'exec') return a.slice(0, 2).join(' ');
89
+ let rest = a.slice(a.indexOf('--') + 1);
90
+ if (rest[0] === 'sudo' && rest[1] === '-n') rest = rest.slice(2);
91
+ if (rest[0] === 'clavarium-enter') rest = rest.slice(rest.indexOf('--') + 1);
92
+ if (rest[0] === 'timeout') rest = rest.slice(rest.findIndex((x, i) => i > 0 && !/^(-k|\d+)$/.test(x)));
93
+ const prog = rest[0] === 'sh' ? `sh:${(rest[3] ?? rest[2] ?? '').split('/').pop()}` : rest[0] === 'tmux' ? `tmux ${rest.find((x) => /^(send-keys|if-shell|capture-pane|has-session|kill-server|new-session)$/.test(x)) ?? ''}` : rest[0];
94
+ return `vm exec ${String(prog ?? '').slice(0, 40)}`;
95
+ }
83
96
  const CHANGES = new Set(['launch', 'clone', 'start', 'stop', 'suspend', 'kill', 'halt', 'hardstop', 'delete', 'purge', 'set', 'rename', 'restore', 'snapshot', 'revive', 'reclaim']);
84
97
  export const STATES_FRESH_MS = 3000;
85
98
  /* The VM manager did not say what a machine is in: not an answer about the machine. */
@@ -100,10 +113,26 @@ export class Vms {
100
113
  this.run = async (argv, options) => {
101
114
  const changes = argv[0] === 'vm' && CHANGES.has(argv[1]);
102
115
  if (changes) this.#snapshot = null;
103
- try { return await this.#ask(argv, options); } finally { if (changes) this.#snapshot = null; }
116
+ const began = this.#now();
117
+ try { return await this.#ask(argv, options); } finally { if (changes) this.#snapshot = null; this.#count(argv, this.#now() - began); }
104
118
  };
105
119
  }
106
120
 
121
+ /* HOW MUCH THIS SERVER ASKS OF THE HOST (17-11: the owner saw a page wait 10-15 s with an idle CPU --
122
+ every command to a machine goes through the VM manager, one after another): each command counted by
123
+ what it is, with its time; every COUNT_EVERY_MS the tally is said in the log, the busiest first. */
124
+ #tally = new Map(); #tallyFrom = 0;
125
+ #count(argv, ms) {
126
+ const now = this.#now();
127
+ if (!this.#tallyFrom) this.#tallyFrom = now;
128
+ this.#tally.set(commandKind(argv), [(this.#tally.get(commandKind(argv))?.[0] ?? 0) + 1, (this.#tally.get(commandKind(argv))?.[1] ?? 0) + ms, Math.max(this.#tally.get(commandKind(argv))?.[2] ?? 0, ms)]);
129
+ if (now - this.#tallyFrom < COUNT_EVERY_MS) return;
130
+ const rows = [...this.#tally].sort((a, b) => b[1][1] - a[1][1]);
131
+ const all = rows.reduce((n, [, v]) => n + v[0], 0); const busy = rows.reduce((n, [, v]) => n + v[1], 0);
132
+ console.log(`host: ${all} commands in ${Math.round((now - this.#tallyFrom) / 60_000)} min, ${Math.round(busy / 1000)} s spent; ${rows.slice(0, 8).map(([k, v]) => `${k} ${v[0]}x ${Math.round(v[1] / 1000)}s max ${Math.round(v[2] / 1000)}s`).join('; ')}`);
133
+ this.#tally = new Map(); this.#tallyFrom = now;
134
+ }
135
+
107
136
  /* EVERY MACHINE'S STATE, in one question to the VM manager, shared by every caller for a
108
137
  few seconds (and by those who ask while it is being asked). */
109
138
  async #states(fresh = false) {