clavarium 0.2.0-next.9 → 0.2.1-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.
- package/README.md +3 -2
- package/deploy/clavarium-host +10 -0
- package/deploy/updater.mjs +204 -34
- package/npm-shrinkwrap.json +6 -6
- package/package.json +2 -2
- package/server/api.mjs +14 -4
- package/server/bridge.mjs +36 -7
- package/server/conversations.mjs +2 -1
- package/server/door.mjs +2 -2
- package/server/main.mjs +40 -13
- package/server/secrets.mjs +4 -0
- package/server/talk.mjs +28 -3
- package/server/updates.mjs +2 -2
- package/server/vmwatch.mjs +63 -0
- package/server/voice.mjs +120 -1
- package/web/app.js +101 -9
- package/web/index.html +18 -9
- package/web/style.css +4 -0
- package/web/voice.js +4 -3
package/README.md
CHANGED
|
@@ -30,8 +30,9 @@ Built slice by slice; the plan is in `blueprint/architecture.html`, tab
|
|
|
30
30
|
|
|
31
31
|
- **5 - hands**: one-click shortcuts (sent, or left to complete), and
|
|
32
32
|
dictation: the microphone stays open and each phrase is typed into the
|
|
33
|
-
terminal; "auto" presses Enter once the person has stopped.
|
|
34
|
-
|
|
33
|
+
terminal; "auto" presses Enter once the person has stopped. Its engine is chosen
|
|
34
|
+
in Settings, Dictation (a provider, its key one of the secrets);
|
|
35
|
+
`CLAVARIUM_TRANSCRIPTION_URL` (and `_KEY`) in the environment is the fallback.
|
|
35
36
|
|
|
36
37
|
- **6 - the app and sharing**: the page is installable; a conversation is
|
|
37
38
|
shared with a one-use QR code; the device that scans it makes its own key,
|
package/deploy/clavarium-host
CHANGED
|
@@ -255,6 +255,16 @@ case "$AREA $VERB" in
|
|
|
255
255
|
[ $# -ge 3 ] || usage
|
|
256
256
|
vm="$1"; shift 2
|
|
257
257
|
run "$MULTIPASS" exec "$vm" -- "$@" ;;
|
|
258
|
+
"vm ping")
|
|
259
|
+
# Does the VM manager answer at all? Asked now and then by the server
|
|
260
|
+
# (vmwatch.mjs); bounded, so that a VM manager that hangs is an answer.
|
|
261
|
+
[ $# -eq 0 ] || usage
|
|
262
|
+
run timeout 25 "$MULTIPASS" list --format csv ;;
|
|
263
|
+
"vm revive")
|
|
264
|
+
# The VM manager has not answered for minutes: its daemon restarted.
|
|
265
|
+
# Asked by the server at most once in hours (vmwatch.mjs), never by a page.
|
|
266
|
+
[ $# -eq 0 ] || usage
|
|
267
|
+
run timeout 170 snap restart multipass.multipassd ;;
|
|
258
268
|
"vm info")
|
|
259
269
|
[ $# -eq 1 ] || usage; vm_of "$1"
|
|
260
270
|
run "$MULTIPASS" info "$1" --format json ;;
|
package/deploy/updater.mjs
CHANGED
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
* --------------------------------------------------------------------------- */
|
|
49
49
|
import { spawn } from 'node:child_process';
|
|
50
50
|
import { createHash } from 'node:crypto';
|
|
51
|
-
import { readFileSync, writeFileSync, renameSync, mkdirSync, rmSync, readdirSync, existsSync, symlinkSync, realpathSync, cpSync, openSync, closeSync, statfsSync, chmodSync } from 'node:fs';
|
|
51
|
+
import { readFileSync, writeFileSync, renameSync, mkdirSync, rmSync, readdirSync, existsSync, symlinkSync, realpathSync, cpSync, openSync, closeSync, statfsSync, statSync, chmodSync } from 'node:fs';
|
|
52
52
|
import { dirname, join, basename } from 'node:path';
|
|
53
53
|
import { fileURLToPath } from 'node:url';
|
|
54
54
|
import { fetchParleyArchive, REGISTRY } from './parley-archive.mjs';
|
|
@@ -65,9 +65,22 @@ export const WINDOW = /^([01]\d|2[0-3]):[0-5]\d-([01]\d|2[0-3]):[0-5]\d$/;
|
|
|
65
65
|
export const DEFAULTS = { MODE: 'auto', CHANNEL: 'latest', WINDOW: '02:00-05:00', PORT: '7717' };
|
|
66
66
|
/* A conversation in one of these phases is in the middle of something the restart would cut. */
|
|
67
67
|
const BUSY = ['building', 'moving', 'restarting'];
|
|
68
|
+
/* A busy phase older than this was cut short (the server died under it): it does not hold an update back. */
|
|
69
|
+
const BUSY_STALE_MS = 30 * 60_000;
|
|
70
|
+
/* THE WATCHDOG (each timer turn): down this many turns in a row, or its service failed: one action, at most one an hour. */
|
|
71
|
+
const WATCH_MISSES = 3;
|
|
72
|
+
const WATCH_EVERY_MS = 3600_000;
|
|
73
|
+
/* An update this recent is the first suspect when the server will not stay up. */
|
|
74
|
+
const WATCH_RECENT_MS = 24 * 3600_000;
|
|
68
75
|
const HISTORY_MAX = 30;
|
|
69
76
|
const ASK_EVERY_MS = 6 * 3600_000;
|
|
70
77
|
const PROVENANCE = 'https://slsa.dev/provenance/v1';
|
|
78
|
+
/* What the log of a failure keeps, at most (history entry `log`, shown behind "See the log"). */
|
|
79
|
+
const LOG_MAX = 12_000;
|
|
80
|
+
/* Set beside the server's unit by the updater (root): a crash loop never locks the service out, so a
|
|
81
|
+
restart asked later (an update, the watchdog) still starts it. */
|
|
82
|
+
export const DROP_IN = '/etc/systemd/system/clavarium.service.d/restart.conf';
|
|
83
|
+
export const DROP_IN_TEXT = '# Written by the Clavarium updater: a crash loop never locks the service out.\n[Unit]\nStartLimitIntervalSec=0\n\n[Service]\nRestartSec=3\n';
|
|
71
84
|
|
|
72
85
|
export class Refused extends Error {}
|
|
73
86
|
|
|
@@ -142,16 +155,25 @@ const toHex = (integrity) => Buffer.from(String(integrity).replace(/^sha512-/, '
|
|
|
142
155
|
export class Updater {
|
|
143
156
|
#o; #run; #fetch;
|
|
144
157
|
constructor({ code = PATHS.code, conf = PATHS.conf, stateDir = PATHS.stateDir, data = PATHS.data, hostTarget = PATHS.host, gitReadTarget = PATHS.gitRead, registry = REGISTRY, run = runCommand, fetcher = fetch, now = () => new Date(), log = (line) => console.log(line),
|
|
145
|
-
verifySignatures, restart, health, backup, restoreData, installPrivileged, ensureNode,
|
|
146
|
-
|
|
158
|
+
verifySignatures, restart, health, backup, restoreData, installPrivileged, ensureNode, serviceState, answers, mainPid, pidCwd, diagnose, dropIn = DROP_IN,
|
|
159
|
+
clock = () => Date.now(), sleep = (ms) => new Promise((r) => setTimeout(r, ms)), minFreeMb = 1024, healthMs = 60_000, watchMs = 120_000, settleMs = 10_000 } = {}) {
|
|
160
|
+
this.#o = { code, conf, stateDir, data, hostTarget, gitReadTarget, registry: registry.replace(/\/$/, ''), now, log, minFreeMb, healthMs, watchMs, settleMs, clock, sleep, dropIn };
|
|
147
161
|
this.#run = run; this.#fetch = fetcher;
|
|
148
162
|
this.verifySignatures = verifySignatures ?? ((dir) => this.#npm(['audit', 'signatures'], { cwd: dir, timeoutMs: 300_000 }));
|
|
149
|
-
this.restart = restart ?? (() => this.#
|
|
163
|
+
this.restart = restart ?? (() => this.#restart());
|
|
164
|
+
/* What was seen when the server did not come up: its journal, its unit, who holds its port. */
|
|
165
|
+
this.diagnose = diagnose ?? (() => this.#diagnose());
|
|
150
166
|
this.health = health ?? ((release) => this.#health(release));
|
|
151
167
|
this.backup = backup ?? ((app) => this.#backup(app));
|
|
152
168
|
this.restoreData = restoreData ?? ((app, archive) => this.#restoreData(app, archive));
|
|
153
169
|
this.installPrivileged = installPrivileged ?? ((app) => this.#installPrivileged(app));
|
|
154
170
|
this.ensureNode = ensureNode ?? ((app) => this.#ensureNode(app));
|
|
171
|
+
/* What systemd says of the server: 'active', 'activating', 'failed', 'inactive'... */
|
|
172
|
+
this.serviceState = serviceState ?? (async () => (await this.#run(['systemctl', 'show', '-p', 'ActiveState', '--value', 'clavarium.service'], { timeoutMs: 10_000 })).stdout.trim() || 'unknown');
|
|
173
|
+
/* Does the server answer, on its port, here? */
|
|
174
|
+
this.answers = answers ?? (() => this.#fetch(`http://127.0.0.1:${readConf(this.#o.conf).PORT}/`, { signal: AbortSignal.timeout(5000), redirect: 'manual' }).then((r) => r.status < 500).catch(() => false));
|
|
175
|
+
this.mainPid = mainPid ?? (async () => (await this.#run(['systemctl', 'show', '-p', 'MainPID', '--value', 'clavarium.service'], { timeoutMs: 10_000 })).stdout.trim());
|
|
176
|
+
this.pidCwd = pidCwd ?? ((pid) => { try { return realpathSync(`/proc/${pid}/cwd`); } catch { return ''; } });
|
|
155
177
|
}
|
|
156
178
|
|
|
157
179
|
get releasesDir() { return join(this.#o.code, 'releases'); }
|
|
@@ -340,12 +362,26 @@ export class Updater {
|
|
|
340
362
|
renameSync(`${link}.new`, link);
|
|
341
363
|
}
|
|
342
364
|
|
|
343
|
-
/* A conversation in the middle of a build, a move or a restart: '' or why not now.
|
|
344
|
-
|
|
365
|
+
/* A conversation in the middle of a build, a move or a restart: '' or why not now.
|
|
366
|
+
Only while the server runs (a phase in the file of a server that is down is not going on), and
|
|
367
|
+
only a phase younger than BUSY_STALE_MS (older: cut short; the server settles it when it starts). */
|
|
368
|
+
async busy() {
|
|
369
|
+
const file = join(this.#o.data, 'conversations.json');
|
|
345
370
|
let all = [];
|
|
346
|
-
try { all = JSON.parse(readFileSync(
|
|
347
|
-
const busy = (Array.isArray(all) ? all : []).filter((c) => BUSY.includes(c.phase))
|
|
348
|
-
|
|
371
|
+
try { all = JSON.parse(readFileSync(file, 'utf8')); } catch { return ''; }
|
|
372
|
+
const busy = (Array.isArray(all) ? all : []).filter((c) => c && BUSY.includes(c.phase));
|
|
373
|
+
if (!busy.length) return '';
|
|
374
|
+
const names = (list) => list.slice(0, 3).map((c) => c.name).join(', ');
|
|
375
|
+
const state = await this.serviceState().catch(() => 'unknown');
|
|
376
|
+
if (state !== 'active') { this.#o.log(`busy phases not waited for: the server is ${state} (${names(busy)})`); return ''; }
|
|
377
|
+
let written = this.#o.now().getTime();
|
|
378
|
+
try { written = statSync(file).mtimeMs; } catch { /* now */ }
|
|
379
|
+
const now = this.#o.now().getTime();
|
|
380
|
+
const since = (c) => { const t = Date.parse(c.restartingSince ?? c.buildingSince ?? c.movingSince ?? ''); return Number.isFinite(t) ? t : written; };
|
|
381
|
+
const stale = busy.filter((c) => now - since(c) > BUSY_STALE_MS);
|
|
382
|
+
if (stale.length) this.#o.log(`busy phases older than 30 minutes not waited for: ${names(stale)}`);
|
|
383
|
+
const live = busy.filter((c) => !stale.includes(c));
|
|
384
|
+
return live.length ? `a machine is being built or restarted (${names(live)}): the update waits` : '';
|
|
349
385
|
}
|
|
350
386
|
#dataFormat() { try { return JSON.parse(readFileSync(join(this.#o.data, 'data-format.json'), 'utf8')).format; } catch { return undefined; } }
|
|
351
387
|
|
|
@@ -356,7 +392,9 @@ export class Updater {
|
|
|
356
392
|
try { const fd = openSync(file, 'wx'); writeFileSync(fd, String(process.pid)); closeSync(fd); return () => rmSync(file, { force: true }); } catch (error) {
|
|
357
393
|
if (error.code !== 'EEXIST') throw error;
|
|
358
394
|
const pid = Number(readFileSync(file, 'utf8')) || 0;
|
|
359
|
-
|
|
395
|
+
/* A lock left by a process that is gone (killed, the machine stopped) is taken over. */
|
|
396
|
+
let alive = false; try { if (pid) { process.kill(pid, 0); alive = true; } } catch (e) { alive = e.code === 'EPERM'; }
|
|
397
|
+
if (!alive) this.#o.log(`a stale lock (process ${pid || '?'} is gone): taken over`);
|
|
360
398
|
if (alive) throw new Refused('an update or an installation is running already');
|
|
361
399
|
rmSync(file, { force: true });
|
|
362
400
|
}
|
|
@@ -371,7 +409,7 @@ export class Updater {
|
|
|
371
409
|
/* Asked for the version that runs (a request that waited while it came by itself): done already. */
|
|
372
410
|
if (from && compareVersions(version, from.version) === 0) return;
|
|
373
411
|
if (from && compareVersions(version, from.version) < 0) throw new Refused(`${version} is not newer than ${from.version}`);
|
|
374
|
-
const why = this.busy(); if (why) throw new Refused(why);
|
|
412
|
+
const why = await this.busy(); if (why) throw new Refused(why);
|
|
375
413
|
const unlock = this.#lock();
|
|
376
414
|
try {
|
|
377
415
|
let release;
|
|
@@ -382,7 +420,7 @@ export class Updater {
|
|
|
382
420
|
this.#step('update', version, 'Backing up');
|
|
383
421
|
archive = await this.backup(from?.app ?? release.app);
|
|
384
422
|
} catch (error) { rmSync(release.dir, { recursive: true, force: true }); this.#history({ action: 'update', from: from?.version ?? null, to: version, result: 'failed', why: `the backup failed: ${error.message}` }); throw error; }
|
|
385
|
-
const late = this.busy();
|
|
423
|
+
const late = await this.busy();
|
|
386
424
|
if (late) { this.#history({ action: 'update', from: from?.version ?? null, to: version, result: 'failed', why: late }); throw new Refused(late); }
|
|
387
425
|
const failed = await this.#switchAndCheck(release, 'update', version);
|
|
388
426
|
if (!failed) {
|
|
@@ -390,18 +428,19 @@ export class Updater {
|
|
|
390
428
|
this.prune();
|
|
391
429
|
return this.about();
|
|
392
430
|
}
|
|
393
|
-
/* IT DID NOT COME UP: back to what ran, its data too if it moved. */
|
|
431
|
+
/* IT DID NOT COME UP: what was seen kept, then back to what ran, its data too if it moved. */
|
|
394
432
|
let why2 = failed;
|
|
433
|
+
let log = await this.#seen(`${version} did not come up: ${failed}`);
|
|
395
434
|
if (from) {
|
|
396
435
|
this.#step('update', version, 'Going back');
|
|
397
436
|
this.switchTo(from.id);
|
|
398
437
|
await this.installPrivileged(from.app).catch(() => {});
|
|
399
438
|
if (archive && this.#dataFormat() !== before) { const r = await this.restoreData(from.app, archive).catch((e) => ({ code: 1, stderr: e.message })); if (r?.code) why2 += `; the data backup could not be put back (${lastLine(r)}): ${archive}`; }
|
|
400
439
|
const back = await this.#restartAndCheck(from);
|
|
401
|
-
if (back) why2 += `; ${from.version} did not come back either (${back}): journalctl -u clavarium`;
|
|
440
|
+
if (back) { why2 += `; ${from.version} did not come back either (${back}): journalctl -u clavarium`; log = `${log}\n\n${await this.#seen(`${from.version} did not come back: ${back}`)}`; }
|
|
402
441
|
rmSync(release.dir, { recursive: true, force: true });
|
|
403
442
|
}
|
|
404
|
-
this.#history({ action: 'update', from: from?.version ?? null, to: version, result: from ? 'rolled-back' : 'failed', why: why2 });
|
|
443
|
+
this.#history({ action: 'update', from: from?.version ?? null, to: version, result: from ? 'rolled-back' : 'failed', why: why2, log: log.slice(-LOG_MAX) });
|
|
405
444
|
this.prune();
|
|
406
445
|
return this.about();
|
|
407
446
|
} finally { unlock(); }
|
|
@@ -416,19 +455,20 @@ export class Updater {
|
|
|
416
455
|
if (to.current) throw new Refused(`${id} is the release that runs`);
|
|
417
456
|
const format = this.#dataFormat();
|
|
418
457
|
if (format !== undefined && to.dataFormat < format) throw new Refused(`${to.version} cannot read the data of this version (format ${format}; it reads ${to.dataFormat})`);
|
|
419
|
-
const why = this.busy(); if (why) throw new Refused(why);
|
|
458
|
+
const why = await this.busy(); if (why) throw new Refused(why);
|
|
420
459
|
const unlock = this.#lock();
|
|
421
460
|
try {
|
|
422
461
|
const failed = await this.#switchAndCheck(to, 'back', to.version);
|
|
423
462
|
if (!failed) { this.#history({ action: 'back', from: from?.version ?? null, to: to.version, result: 'done' }); return this.about(); }
|
|
424
463
|
let why2 = failed;
|
|
464
|
+
let log = await this.#seen(`${to.version} did not come up: ${failed}`);
|
|
425
465
|
if (from) {
|
|
426
466
|
this.switchTo(from.id);
|
|
427
467
|
await this.installPrivileged(from.app).catch(() => {});
|
|
428
468
|
const back = await this.#restartAndCheck(from);
|
|
429
|
-
if (back) why2 += `; ${from.version} did not come back either (${back})`;
|
|
469
|
+
if (back) { why2 += `; ${from.version} did not come back either (${back})`; log = `${log}\n\n${await this.#seen(`${from.version} did not come back: ${back}`)}`; }
|
|
430
470
|
}
|
|
431
|
-
this.#history({ action: 'back', from: from?.version ?? null, to: to.version, result: 'failed', why: why2 });
|
|
471
|
+
this.#history({ action: 'back', from: from?.version ?? null, to: to.version, result: 'failed', why: why2, log: log.slice(-LOG_MAX) });
|
|
432
472
|
return this.about();
|
|
433
473
|
} finally { unlock(); }
|
|
434
474
|
}
|
|
@@ -455,7 +495,7 @@ export class Updater {
|
|
|
455
495
|
const all = this.releases();
|
|
456
496
|
const current = all.find((r) => r.current);
|
|
457
497
|
/* The one gone from at the last update or return that worked; else the newest other one. */
|
|
458
|
-
const last = (this.#state().history ?? []).find((h) => h.result === 'done');
|
|
498
|
+
const last = (this.#state().history ?? []).find((h) => h.result === 'done' && h.action !== 'restart');
|
|
459
499
|
const previous = all.find((r) => !r.current && last && r.version === last.from) ?? all.find((r) => !r.current);
|
|
460
500
|
const keep = new Set([current?.id, previous?.id].filter(Boolean));
|
|
461
501
|
for (const r of all) if (!keep.has(r.id)) rmSync(r.dir, { recursive: true, force: true });
|
|
@@ -482,13 +522,63 @@ export class Updater {
|
|
|
482
522
|
if (conf.MODE === 'ask') return `${available} is out: waiting for the owner`;
|
|
483
523
|
/* A version that failed here is not tried again by itself: the owner can, from Settings. */
|
|
484
524
|
if ((state.history ?? []).some((h) => h.to === available && h.action === 'update' && h.result !== 'done')) return `${available} failed here before: not tried again by itself`;
|
|
485
|
-
|
|
525
|
+
const why = await this.busy(); if (why) return why;
|
|
486
526
|
await this.apply(available);
|
|
487
527
|
/* What the history says, not what was hoped: a version that did not start was undone. */
|
|
488
|
-
const last = (this.#state().history ?? [])
|
|
528
|
+
const last = (this.#state().history ?? [])[0];
|
|
489
529
|
return last?.to === available && last.result !== 'done' ? `${available} did not work: back to ${last.from ?? 'nothing'} (${last.why ?? last.result})` : `updated to ${available}`;
|
|
490
530
|
}
|
|
491
531
|
|
|
532
|
+
/* THE WATCHDOG, at each timer turn: the server down (its service failed or stopped, or no answer
|
|
533
|
+
WATCH_MISSES turns in a row) is acted on, once, and said in the history:
|
|
534
|
+
- after an update of less than WATCH_RECENT_MS, with the release before it kept (and able to
|
|
535
|
+
read the data): back to it, by itself ("did not stay up"), not tried again by itself;
|
|
536
|
+
- otherwise: one restart.
|
|
537
|
+
Never more than one action in WATCH_EVERY_MS, so that it never loops. { acted, said } */
|
|
538
|
+
async watchdog() {
|
|
539
|
+
const state = await this.serviceState().catch(() => 'unknown');
|
|
540
|
+
const up = state === 'active' && await this.answers().catch(() => false);
|
|
541
|
+
const w = this.#state().watch ?? {};
|
|
542
|
+
if (up) { if (w.misses) this.#save({ watch: { ...w, misses: 0 } }); return { acted: false, said: 'up' }; }
|
|
543
|
+
const misses = (w.misses ?? 0) + 1;
|
|
544
|
+
this.#save({ watch: { ...w, misses, seen: state } });
|
|
545
|
+
const down = state === 'failed' || state === 'inactive' || misses >= WATCH_MISSES;
|
|
546
|
+
this.#o.log(`watchdog: the server is ${state === 'active' ? 'active but does not answer' : state} (turn ${misses})`);
|
|
547
|
+
if (!down) return { acted: false, said: `the server does not answer (turn ${misses} of ${WATCH_MISSES})` };
|
|
548
|
+
const now = this.#o.now();
|
|
549
|
+
if (w.actedAt && now - new Date(w.actedAt) < WATCH_EVERY_MS) return { acted: false, said: 'the server is down; something was done less than an hour ago: nothing more by itself' };
|
|
550
|
+
let unlock;
|
|
551
|
+
try { unlock = this.#lock(); } catch (error) { if (error instanceof Refused) return { acted: false, said: 'the server is down, but an update runs' }; throw error; }
|
|
552
|
+
try {
|
|
553
|
+
this.#save({ watch: { misses: 0, actedAt: now.toISOString(), seen: state } });
|
|
554
|
+
const log = await this.#seen(`the server was down (${state})`);
|
|
555
|
+
const current = this.current();
|
|
556
|
+
/* The last update or return (a restart by the watchdog is not one). */
|
|
557
|
+
const last = (this.#state().history ?? []).find((h) => h.action !== 'restart');
|
|
558
|
+
const recent = current && last && last.action === 'update' && last.result === 'done' && last.to === current.version && now - new Date(last.at) < WATCH_RECENT_MS;
|
|
559
|
+
const previous = recent ? this.releases().find((r) => !r.current && r.version === last.from) : undefined;
|
|
560
|
+
const format = this.#dataFormat();
|
|
561
|
+
if (previous && (format === undefined || previous.dataFormat >= format)) {
|
|
562
|
+
let why = `${current.version} did not stay up (its service ${state === 'active' ? 'did not answer' : `was ${state}`}): back to ${previous.version}`;
|
|
563
|
+
this.#o.log(`watchdog: ${why}`);
|
|
564
|
+
this.#step('update', current.version, 'Going back');
|
|
565
|
+
let back;
|
|
566
|
+
try { this.switchTo(previous.id); await this.installPrivileged(previous.app).catch(() => {}); back = await this.#restartAndCheck(previous); } catch (error) { back = error.message; }
|
|
567
|
+
if (back) why += `; ${previous.version} did not come back either (${back}): journalctl -u clavarium`;
|
|
568
|
+
else rmSync(current.dir, { recursive: true, force: true });
|
|
569
|
+
this.#history({ action: 'update', from: previous.version, to: current.version, result: 'rolled-back', by: 'watchdog', why, log: log.slice(-LOG_MAX) });
|
|
570
|
+
this.prune();
|
|
571
|
+
return { acted: true, said: why };
|
|
572
|
+
}
|
|
573
|
+
const v = current?.version ?? null;
|
|
574
|
+
this.#o.log(`watchdog: the server is ${state}: restarted once`);
|
|
575
|
+
const failed = current ? await this.#restartAndCheck(current) : await this.restart().then((r) => (r?.code ? lastLine(r) : '')).catch((e) => e.message);
|
|
576
|
+
const why = `the server was down (${state === 'active' ? 'no answer' : state}): restarted by itself${failed ? `; it did not come back (${failed}): journalctl -u clavarium` : ''}`;
|
|
577
|
+
this.#history({ action: 'restart', from: v, to: v, result: failed ? 'failed' : 'done', by: 'watchdog', why, log: log.slice(-LOG_MAX) });
|
|
578
|
+
return { acted: true, said: why };
|
|
579
|
+
} finally { unlock(); }
|
|
580
|
+
}
|
|
581
|
+
|
|
492
582
|
/* What the host program asked (a request file), or the timer's turn. */
|
|
493
583
|
async runOnce() {
|
|
494
584
|
const file = join(this.#o.stateDir, 'request');
|
|
@@ -502,6 +592,9 @@ export class Updater {
|
|
|
502
592
|
await this.check().catch(() => {});
|
|
503
593
|
return r;
|
|
504
594
|
}
|
|
595
|
+
/* The timer's turn: first, is the server up? (it may have died after an update that looked well) */
|
|
596
|
+
const watched = await this.watchdog();
|
|
597
|
+
if (watched.acted) return watched.said;
|
|
505
598
|
return await this.tick();
|
|
506
599
|
} catch (error) {
|
|
507
600
|
if (error instanceof Refused && request) this.#save({ refused: { at: this.#o.now().toISOString(), why: error.message } });
|
|
@@ -509,28 +602,103 @@ export class Updater {
|
|
|
509
602
|
}
|
|
510
603
|
}
|
|
511
604
|
|
|
605
|
+
/* What was seen, as text: never fails (a log that could not be read says so). */
|
|
606
|
+
async #seen(title) {
|
|
607
|
+
const text = await Promise.resolve().then(() => this.diagnose()).catch((e) => `the log could not be read: ${e.message}`);
|
|
608
|
+
return `== ${this.#o.now().toISOString()} ${title}\n${String(text ?? '').trim()}`;
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
/* THE DROP-IN beside the server's unit: written when it differs, then systemd told. true when written. */
|
|
612
|
+
async ensureDropIn() {
|
|
613
|
+
const file = this.#o.dropIn;
|
|
614
|
+
try { if (readFileSync(file, 'utf8') === DROP_IN_TEXT) return false; } catch { /* not there */ }
|
|
615
|
+
mkdirSync(dirname(file), { recursive: true, mode: 0o755 });
|
|
616
|
+
writeFileSync(`${file}.new`, DROP_IN_TEXT, { mode: 0o644 });
|
|
617
|
+
renameSync(`${file}.new`, file);
|
|
618
|
+
if (process.getuid?.() === 0) await this.#run(['systemctl', 'daemon-reload'], { timeoutMs: 60_000 });
|
|
619
|
+
return true;
|
|
620
|
+
}
|
|
621
|
+
|
|
512
622
|
/* ------------------------- the real machine's ways ------------------------- */
|
|
513
|
-
|
|
623
|
+
/* The processes still there after a stop: in the unit's cgroup, or holding its port. [{ pid, state, port }] */
|
|
624
|
+
async #leftovers() {
|
|
625
|
+
const port = readConf(this.#o.conf).PORT;
|
|
626
|
+
const pids = new Map();
|
|
627
|
+
try { for (const p of readFileSync('/sys/fs/cgroup/system.slice/clavarium.service/cgroup.procs', 'utf8').split('\n')) if (/^\d+$/.test(p.trim())) pids.set(p.trim(), false); } catch { /* none */ }
|
|
628
|
+
const ss = await this.#run(['ss', '-Hltnp', `sport = :${port}`], { timeoutMs: 10_000 });
|
|
629
|
+
for (const m of String(ss.stdout).matchAll(/pid=(\d+)/g)) pids.set(m[1], true);
|
|
630
|
+
return [...pids].map(([pid, holds]) => {
|
|
631
|
+
let state = '?';
|
|
632
|
+
try { state = /^State:\s+(\S)/m.exec(readFileSync(`/proc/${pid}/status`, 'utf8'))?.[1] ?? '?'; } catch { state = 'gone'; }
|
|
633
|
+
return { pid: Number(pid), state, port: holds };
|
|
634
|
+
}).filter((p) => p.state !== 'gone');
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/* A RESTART that does not trust the stop: its failures forgotten (reset-failed), stopped, and
|
|
638
|
+
what is left of the old server looked at -- killed, or, when it cannot be (state D: waiting on
|
|
639
|
+
the kernel), said precisely: then nothing would answer on the port before a reboot. */
|
|
640
|
+
async #restart() {
|
|
641
|
+
await this.#run(['systemctl', 'reset-failed', 'clavarium.service'], { timeoutMs: 30_000 });
|
|
642
|
+
await this.#run(['systemctl', 'stop', 'clavarium.service'], { timeoutMs: 120_000 });
|
|
643
|
+
let left = await this.#leftovers();
|
|
644
|
+
for (const p of left.filter((x) => x.state !== 'D')) { try { process.kill(p.pid, 'SIGKILL'); this.#o.log(`a process of the old server was still there: ${p.pid} (state ${p.state}): killed`); } catch { /* gone */ } }
|
|
645
|
+
if (left.length) { await this.#o.sleep(2000); left = await this.#leftovers(); }
|
|
646
|
+
const stuck = left.filter((x) => x.state === 'D' && x.port);
|
|
647
|
+
if (stuck.length) return { code: 1, stderr: `a stuck process holds the port: ${stuck.map((p) => `pid ${p.pid}, state D`).join('; ')} (it waits on the kernel and cannot be killed): the server needs a reboot` };
|
|
648
|
+
if (left.some((x) => x.state === 'D')) this.#o.log(`processes of the old server stuck in state D (not on the port): ${left.map((p) => p.pid).join(', ')}`);
|
|
649
|
+
await this.#run(['systemctl', 'reset-failed', 'clavarium.service'], { timeoutMs: 30_000 });
|
|
650
|
+
return this.#run(['systemctl', 'start', 'clavarium.service'], { timeoutMs: 120_000 });
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
async #diagnose() {
|
|
514
654
|
const port = readConf(this.#o.conf).PORT;
|
|
515
|
-
const
|
|
655
|
+
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()}`; };
|
|
656
|
+
const left = await this.#leftovers().catch(() => []);
|
|
657
|
+
return [
|
|
658
|
+
await part('systemctl status clavarium', ['systemctl', 'status', 'clavarium.service', '--no-pager', '-n', '0']),
|
|
659
|
+
await part(`who listens on ${port}`, ['ss', '-Hltnp', `sport = :${port}`]),
|
|
660
|
+
`-- 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'}`,
|
|
661
|
+
await part('journalctl -u clavarium -n 80', ['journalctl', '-u', 'clavarium.service', '-n', '80', '--no-pager', '-o', 'short-iso']),
|
|
662
|
+
].join('\n');
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
/* Comes up (answers, from this release) within healthMs, then STAYS up: watched until watchMs after
|
|
666
|
+
the restart; one restart by systemd is forgiven if it answers at the end, not two. */
|
|
667
|
+
async #health(release) {
|
|
668
|
+
const { clock, sleep } = this.#o;
|
|
669
|
+
const start = clock();
|
|
516
670
|
const target = realpathSync(release.dir);
|
|
671
|
+
const mine = async () => { const pid = await this.mainPid(); return { pid, ok: !!pid && pid !== '0' && this.pidCwd(pid).startsWith(target) }; };
|
|
517
672
|
let said = 'it did not answer';
|
|
673
|
+
let pid = '';
|
|
518
674
|
for (;;) {
|
|
519
|
-
const
|
|
520
|
-
const answered =
|
|
675
|
+
const state = await this.serviceState().catch(() => 'unknown');
|
|
676
|
+
const answered = state === 'active' && await this.answers().catch(() => false);
|
|
521
677
|
if (answered) {
|
|
522
|
-
const
|
|
523
|
-
|
|
524
|
-
if (cwd.startsWith(target)) break;
|
|
678
|
+
const m = await mine();
|
|
679
|
+
if (m.ok) { pid = m.pid; break; }
|
|
525
680
|
said = 'the server that answers is not this release';
|
|
526
|
-
} else if (active
|
|
527
|
-
if (
|
|
528
|
-
await
|
|
681
|
+
} else if (state !== 'active' && state !== 'activating') said = 'its service stopped';
|
|
682
|
+
if (clock() - start > this.#o.healthMs) return said;
|
|
683
|
+
await sleep(1000);
|
|
529
684
|
}
|
|
530
685
|
/* And it stays up. */
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
686
|
+
const until = Math.max(start + this.#o.watchMs, clock() + this.#o.settleMs);
|
|
687
|
+
let restarts = 0;
|
|
688
|
+
while (clock() < until) {
|
|
689
|
+
await sleep(Math.min(5000, Math.max(1, until - clock())));
|
|
690
|
+
const now = await this.mainPid().catch(() => '');
|
|
691
|
+
if (now && now !== '0' && now !== pid) { restarts += 1; pid = now; }
|
|
692
|
+
if (restarts > 1) return 'the server stopped more than once in its first minutes';
|
|
693
|
+
}
|
|
694
|
+
/* At the end: it answers, from this release (a moment given if it is in its one restart). */
|
|
695
|
+
const last = clock() + this.#o.settleMs;
|
|
696
|
+
for (;;) {
|
|
697
|
+
const state = await this.serviceState().catch(() => 'unknown');
|
|
698
|
+
if (state === 'active' && await this.answers().catch(() => false) && (await mine()).ok) return '';
|
|
699
|
+
if (clock() > last) return restarts ? 'the server stopped soon after it started, and did not answer again' : 'the server stopped soon after it started';
|
|
700
|
+
await sleep(1000);
|
|
701
|
+
}
|
|
534
702
|
}
|
|
535
703
|
|
|
536
704
|
async #backup(app) {
|
|
@@ -554,6 +722,7 @@ export class Updater {
|
|
|
554
722
|
const r = await this.#run(['install', '-o', 'root', '-g', 'root', '-m', '0755', from, to], { timeoutMs: 30_000 });
|
|
555
723
|
if (r.code !== 0) throw new Error(`${to}: ${lastLine(r)}`);
|
|
556
724
|
}
|
|
725
|
+
await this.ensureDropIn().catch((error) => this.#o.log(`the drop-in of the server's unit could not be written: ${error.message}`));
|
|
557
726
|
/* What a release sets up beside itself (the certificate timer): an update does not run install.sh again.
|
|
558
727
|
Best effort: the update does not depend on it; `sudo clavarium doctor` says when it is missing. */
|
|
559
728
|
const node = join(dirname(app), 'node', 'bin', 'node');
|
|
@@ -599,6 +768,7 @@ async function main(argv) {
|
|
|
599
768
|
/* What this release sets up beside itself (the certificate timer), at its first turn: the
|
|
600
769
|
update that brought it ran the PREVIOUS release's code. Idempotent; never stops the turn. */
|
|
601
770
|
try { const [{ installWatch }, { realSys }] = await Promise.all([import('./doctor.mjs'), import('./online.mjs')]); if (await installWatch(realSys())) console.error('updater: the certificate timer set up'); } catch (error) { console.error(`updater: the certificate timer could not be set up: ${error.message}`); }
|
|
771
|
+
try { if (await u.ensureDropIn()) console.error('updater: the drop-in of the server\'s unit written'); } catch (error) { console.error(`updater: the drop-in could not be written: ${error.message}`); }
|
|
602
772
|
const r = await u.runOnce(); console.log(typeof r === 'string' ? r : 'done'); return; }
|
|
603
773
|
case 'set': if (rest.length !== 2) throw new Refused('set <mode|channel|window|port> <value>'); return print(u.set(rest[0], rest[1]));
|
|
604
774
|
case 'prepare': { const r = await u.prepare({ version: value('--version'), fromDir: value('--from-dir') }); console.log(r.id); return; }
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.1-next.1",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "clavarium",
|
|
9
|
-
"version": "0.2.
|
|
9
|
+
"version": "0.2.1-next.1",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@xterm/addon-fit": "^0.11.0",
|
|
13
13
|
"@xterm/xterm": "^6.0.0",
|
|
14
|
-
"clavarium-parley": "0.10.0
|
|
14
|
+
"clavarium-parley": "0.10.0",
|
|
15
15
|
"mermaid": "11.17.2",
|
|
16
16
|
"node-pty": "^1.1.0",
|
|
17
17
|
"pdfjs-dist": "6.4.299",
|
|
@@ -686,9 +686,9 @@
|
|
|
686
686
|
}
|
|
687
687
|
},
|
|
688
688
|
"node_modules/clavarium-parley": {
|
|
689
|
-
"version": "0.10.0
|
|
690
|
-
"resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.10.0
|
|
691
|
-
"integrity": "sha512-
|
|
689
|
+
"version": "0.10.0",
|
|
690
|
+
"resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.10.0.tgz",
|
|
691
|
+
"integrity": "sha512-wzmTDQW3Ug6byVTNF1IWfXRXrjpFXVBfOsfYeEjJ3jWrP3iShxe6mLqsgEpKo9RN0D001PvFOkoiAGm8LDFkoQ==",
|
|
692
692
|
"license": "MIT",
|
|
693
693
|
"bin": {
|
|
694
694
|
"parley": "bin/parley.mjs",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.1-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.",
|
|
@@ -44,7 +44,7 @@
|
|
|
44
44
|
"dependencies": {
|
|
45
45
|
"@xterm/addon-fit": "^0.11.0",
|
|
46
46
|
"@xterm/xterm": "^6.0.0",
|
|
47
|
-
"clavarium-parley": "0.10.0
|
|
47
|
+
"clavarium-parley": "0.10.0",
|
|
48
48
|
"mermaid": "11.17.2",
|
|
49
49
|
"node-pty": "^1.1.0",
|
|
50
50
|
"pdfjs-dist": "6.4.299",
|
package/server/api.mjs
CHANGED
|
@@ -71,6 +71,10 @@
|
|
|
71
71
|
* POST /api/shortcuts/<id>/remove
|
|
72
72
|
* GET /api/voice is dictation available?
|
|
73
73
|
* POST /api/voice the body IS a WAV recording -> {text}
|
|
74
|
+
* GET /api/dictation the engine chosen in Settings (never a key: a secret's name)
|
|
75
|
+
* POST /api/dictation {provider, url, model, secret, language}: chosen, at once
|
|
76
|
+
* POST /api/dictation/off the environment's engine, if any, again
|
|
77
|
+
* POST /api/dictation/try?provider=&url=&model=&secret=&language= a WAV -> {text}, nothing saved
|
|
74
78
|
* GET /api/files?c=<conversation>&r=<resource>&p=<path> a listing
|
|
75
79
|
* GET /api/flows who gets what: devices, conversations, assets, the rights between them, the flows
|
|
76
80
|
* POST /api/flows/name {around, name}: a flow named by the owner ('' gives it back its own)
|
|
@@ -139,14 +143,18 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
139
143
|
return resources.folder(any.name);
|
|
140
144
|
};
|
|
141
145
|
try {
|
|
142
|
-
if (request.method === 'GET' && pathname === '/api/voice') return send(200, { available: voice !== undefined, engine: voice?.model ?? null }), true;
|
|
143
|
-
if (request.method === '
|
|
146
|
+
if (request.method === 'GET' && pathname === '/api/voice') return send(200, { available: voice?.current() !== undefined, engine: voice?.model ?? null }), true;
|
|
147
|
+
if (request.method === 'GET' && pathname === '/api/dictation' && voice) return send(200, voice.about()), true;
|
|
148
|
+
if (request.method === 'POST' && (pathname === '/api/voice' || (pathname === '/api/dictation/try' && voice))) {
|
|
144
149
|
if (!originOk(request.headers) || request.headers['content-type'] !== 'audio/wav') {
|
|
145
150
|
return send(403, { error: 'This request does not come from this site.' }), true;
|
|
146
151
|
}
|
|
147
152
|
const parts = []; let size = 0;
|
|
148
153
|
for await (const chunk of request) { size += chunk.length; if (size > AUDIO_MAX) throw new Refusal(413, 'The recording is too long.'); parts.push(chunk); }
|
|
149
|
-
|
|
154
|
+
const audio = Buffer.concat(parts);
|
|
155
|
+
/* "Try it": the choice in the form, in the address's parameters (no key in it: a secret's name). */
|
|
156
|
+
if (pathname === '/api/dictation/try') return send(200, { text: await voice.try(Object.fromEntries(query), audio) }), true;
|
|
157
|
+
return send(200, { text: voice ? await voice.transcribe(audio) : await transcribe(undefined, audio) }), true;
|
|
150
158
|
}
|
|
151
159
|
if (request.method === 'GET' && pathname === '/api/files') return send(200, await list(attached(), query.get('p') ?? '')), true;
|
|
152
160
|
if (request.method === 'GET' && pathname === '/api/files/machine') {
|
|
@@ -207,7 +215,7 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
207
215
|
if (pathname === '/api/updates' && updates) return send(200, updates.about()), true;
|
|
208
216
|
/* This server's disk and memory (capacity.mjs): everything for Settings; only whether it is high for the list. */
|
|
209
217
|
if (pathname === '/api/server' && capacity) return send(200, await capacity.about()), true;
|
|
210
|
-
if (pathname === '/api/server/brief' && capacity) return send(200, await capacity.brief()), true;
|
|
218
|
+
if (pathname === '/api/server/brief' && capacity) return send(200, { ...(await capacity.brief()), machines: platform?.machines ?? true }), true;
|
|
211
219
|
if (pathname === '/api/alerts' && alerts) return send(200, alerts.about()), true;
|
|
212
220
|
if (pathname === '/api/flows' && setup) return send(200, setup.graph()), true;
|
|
213
221
|
if (pathname === '/api/setup/import' && setup) return send(200, setup.job()), true;
|
|
@@ -438,6 +446,8 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
438
446
|
if (naming) return send(200, conversations.setChatName(decodeURIComponent(naming[1]), body.name)), true;
|
|
439
447
|
/* The list: folders and order, the same on every device (conversations.mjs). */
|
|
440
448
|
if (pathname === '/api/instance' && instance) return send(200, instance.setName(body.name)), true;
|
|
449
|
+
if (pathname === '/api/dictation' && voice) return send(200, voice.set(body)), true;
|
|
450
|
+
if (pathname === '/api/dictation/off' && voice) return send(200, voice.off()), true;
|
|
441
451
|
if (pathname === '/api/order') return send(200, conversations.setOrder({ order: body.order, groups: body.groups })), true;
|
|
442
452
|
if (pathname === '/api/groups/rename') return send(200, conversations.renameGroup(body.from, body.to)), true;
|
|
443
453
|
if (pathname === '/api/groups/move') return send(200, conversations.moveGroup(body.group, body.to)), true;
|
package/server/bridge.mjs
CHANGED
|
@@ -117,6 +117,7 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
|
|
|
117
117
|
*/
|
|
118
118
|
const live = new Map(); /* name -> { terminal, sink, cols, rows, prefixAt } */
|
|
119
119
|
const reopened = new Map(); /* name -> times of recent automatic reopenings */
|
|
120
|
+
const opening = new Map(); /* name -> the opening under way */
|
|
120
121
|
/* name -> when its terminal was last closed for its machine's sake (put
|
|
121
122
|
to sleep, stopped, deleted) or ended by itself: what was known of its
|
|
122
123
|
machine before that is not known any more (talk.mjs). */
|
|
@@ -138,13 +139,27 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
|
|
|
138
139
|
|
|
139
140
|
/* Opens the terminal of `name` and keeps it; `sink` is the screen that
|
|
140
141
|
receives its output, if there is one. */
|
|
141
|
-
|
|
142
|
+
/* ONE OPENING AT A TIME. Opening takes seconds (into the machine, then
|
|
143
|
+
tmux); a second one asked meanwhile -- the server's own `warm` after a
|
|
144
|
+
restart, a line to type, a screen -- used to open another terminal,
|
|
145
|
+
and the newest closed the first: a line typed into the first lost its
|
|
146
|
+
Enter, and was typed again (seen on a real deployment). The one being
|
|
147
|
+
opened is waited for instead (`opening`). */
|
|
148
|
+
function open(name, cols, rows, sink, say = () => {}) {
|
|
149
|
+
const run = openNow(name, cols, rows, sink, say);
|
|
150
|
+
opening.set(name, run);
|
|
151
|
+
const done = () => { if (opening.get(name) === run) opening.delete(name); };
|
|
152
|
+
run.then(done, done);
|
|
153
|
+
return run;
|
|
154
|
+
}
|
|
155
|
+
async function openNow(name, cols, rows, sink, say) {
|
|
142
156
|
const terminal = await spawn(name, cols, rows, say);
|
|
143
157
|
/* While it was being opened another one may have been: the newest wins. */
|
|
144
158
|
if (live.has(name)) close(name);
|
|
145
|
-
const kept = { terminal, sink, cols, rows };
|
|
159
|
+
const kept = { terminal, sink, cols, rows, openedAt: Date.now(), outputAt: Date.now() };
|
|
146
160
|
live.set(name, kept);
|
|
147
161
|
terminal.onData((bytes) => {
|
|
162
|
+
kept.outputAt = Date.now();
|
|
148
163
|
if (kept.sink?.readyState === 1) { kept.sink.send(bytes, { binary: true }); return; }
|
|
149
164
|
if (!kept.sink) { const answer = answerForAbsentScreen(bytes); if (answer) terminal.write(answer); }
|
|
150
165
|
});
|
|
@@ -188,6 +203,11 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
|
|
|
188
203
|
const say = (text, progress) => { if (viewer.readyState === 1) viewer.send(JSON.stringify({ type: 'status', ...(text ? { text } : {}), ...(progress ? { progress } : {}) })); };
|
|
189
204
|
|
|
190
205
|
let kept = live.get(name);
|
|
206
|
+
/* Being opened already (by the server, before any screen): that one is taken. */
|
|
207
|
+
if (!kept && opening.has(name)) {
|
|
208
|
+
kept = await opening.get(name).then(() => live.get(name), () => undefined);
|
|
209
|
+
if (gone) return;
|
|
210
|
+
}
|
|
191
211
|
if (kept) {
|
|
192
212
|
/* Taken as it is. The size is set a line short, then right: that
|
|
193
213
|
makes the tool draw its whole screen for the newcomer. */
|
|
@@ -239,6 +259,7 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
|
|
|
239
259
|
first screen then shows it at once. Does nothing if it is open already. */
|
|
240
260
|
async function warm(name) {
|
|
241
261
|
if (live.has(name)) return;
|
|
262
|
+
if (opening.has(name)) { await opening.get(name).catch(() => {}); return; }
|
|
242
263
|
try { await open(name, 120, 40, null); onLeft(name); } catch { /* it will be opened when a screen asks */ }
|
|
243
264
|
}
|
|
244
265
|
|
|
@@ -248,15 +269,19 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
|
|
|
248
269
|
The line, then Enter `enterAfterMs` later (apart: see ENTER_AFTER_MS in
|
|
249
270
|
talk.mjs). Resolves false when there is no such channel, or when a
|
|
250
271
|
screen pressed tmux's prefix key lately; the caller then uses its
|
|
251
|
-
other way
|
|
272
|
+
other way; 'enter' when the line went but its Enter could not. Nothing
|
|
273
|
+
of it is told to `onTyped`: nobody typed. */
|
|
252
274
|
async function type(name, line, enterAfterMs = 0) {
|
|
253
275
|
const kept = live.get(name);
|
|
254
276
|
if (!kept || Date.now() - (kept.prefixAt ?? -Infinity) < PREFIX_QUIET_MS) return false;
|
|
255
277
|
try { kept.terminal.write(String(line)); } catch { return false; }
|
|
256
278
|
if (enterAfterMs > 0) await new Promise((r) => { setTimeout(r, enterAfterMs).unref?.(); });
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
279
|
+
/* The line is in the tool's input now: its Enter goes down whichever
|
|
280
|
+
terminal is open on the same pane by then. None: 'enter', the
|
|
281
|
+
caller sends the Enter alone -- never the line again. */
|
|
282
|
+
const now = live.get(name);
|
|
283
|
+
try { if (now) { now.terminal.write('\r'); return true; } } catch { /* closed meanwhile */ }
|
|
284
|
+
return 'enter';
|
|
260
285
|
}
|
|
261
286
|
|
|
262
287
|
server.on('close', () => { for (const name of [...live.keys()]) close(name); });
|
|
@@ -267,5 +292,9 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
|
|
|
267
292
|
/* `type(name, line, ms)`: see above. `droppedAt(name)`: when it was last
|
|
268
293
|
closed for its machine's sake, or undefined. */
|
|
269
294
|
const drop = (name) => { dropped.set(name, Date.now()); close(name); };
|
|
270
|
-
|
|
295
|
+
/* `settled(name)`: how long its terminal has been open, and how long
|
|
296
|
+
since anything came out of it -- THAT something came, never what: a
|
|
297
|
+
tool still drawing its first screen is not reading its keyboard yet. */
|
|
298
|
+
const settled = (name) => { const kept = live.get(name); return kept ? { openFor: Date.now() - kept.openedAt, quietFor: Date.now() - kept.outputAt } : null; };
|
|
299
|
+
return { seats, drop, warm, type, settled, open: (name) => live.has(name), droppedAt: (name) => dropped.get(name) };
|
|
271
300
|
}
|