clavarium 0.2.4-next.1 → 0.2.5-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.
@@ -73,6 +73,12 @@ SHELF_MEMORY="1536M"
73
73
  # less than this is free there, so that a new copy cannot fill the host.
74
74
  SHELF_STORE="/var/snap/multipass/common"
75
75
  SHELF_INSTANCES="$SHELF_STORE/data/multipassd/vault/instances"
76
+ SHELF_CACHE="$SHELF_STORE/cache"
77
+ # Moved to another disk (deploy/move-machines.sh, Multipass's own way: its
78
+ # MULTIPASS_STORAGE in a drop-in of its service): <path>/data, <path>/cache.
79
+ # (No drop-in is the usual case: under pipefail a missing file must not stop this program.)
80
+ MOVED_TO="$( { sed -n 's/^Environment=MULTIPASS_STORAGE=\(\/[A-Za-z0-9/._-]*\)$/\1/p' /etc/systemd/system/snap.multipass.multipassd.service.d/override.conf 2>/dev/null || true; } | head -1)"
81
+ if [ -n "$MOVED_TO" ] && [ -d "$MOVED_TO/data" ]; then SHELF_STORE="$MOVED_TO"; SHELF_INSTANCES="$MOVED_TO/data/vault/instances"; SHELF_CACHE="$MOVED_TO/cache"; fi
76
82
  SHELF_MIN_FREE_MB="6144"
77
83
  CONF="/etc/clavarium/host.conf"
78
84
  # THE GIT READER (verb "git read"): an empty root-owned directory used as the
@@ -89,7 +95,7 @@ UPDATER="$CODE/current/app/deploy/updater.mjs"
89
95
  UPDATE_STATE="/var/lib/clavarium/update"
90
96
 
91
97
  refuse() { echo "REFUSED: $*" >&2; exit 78; }
92
- usage() { echo "usage: clavarium-host [--say-only [--data DIR] [--mnt DIR]] <vm|shelf|folder|work|view|tools|mounts|net|git|server|update> <verb> [arguments]" >&2; exit 64; }
98
+ usage() { echo "usage: clavarium-host [--say-only [--data DIR] [--mnt DIR]] <vm|shelf|folder|work|view|tools|mounts|operator|machines|net|git|server|update> <verb> [arguments]" >&2; exit 64; }
93
99
 
94
100
  SAY="no"; DATA=""; MNT=""
95
101
  while [ $# -gt 0 ]; do
@@ -313,12 +319,15 @@ case "$AREA $VERB" in
313
319
  [ $# -eq 1 ] || usage; vm_of "$1"
314
320
  run "$MULTIPASS" stop --force "$1" ;;
315
321
  "vm set")
316
- # <vm> memory <megabytes> | <vm> disk <gigabytes>. The VM manager
322
+ # <vm> memory <megabytes> | <vm> disk <gigabytes> | <vm> cpus <n>. The VM manager
317
323
  # takes it only from a stopped machine, and a disk only ever grows:
318
324
  # both are its own refusals, passed on as they are.
319
325
  vm_of "${1:-}"; [ $# -eq 3 ] || usage
320
326
  case "$2" in
321
327
  memory) memory_ok "$3"; run "$MULTIPASS" set "local.$1.memory=${3}M" ;;
328
+ # Cores: at most those of the host, which they share.
329
+ cpus) [[ "$3" =~ ^[0-9]{1,3}$ ]] && [ "$3" -ge 1 ] && [ "$3" -le "$(nproc)" ] || refuse "cpus out of bounds: $3 (the host has $(nproc))"
330
+ run "$MULTIPASS" set "local.$1.cpus=$3" ;;
322
331
  disk) [[ "$3" =~ ^[0-9]{1,4}$ ]] && [ "$3" -ge 5 ] && [ "$3" -le "$DISK_MAX_GB" ] || refuse "disk out of bounds: $3"
323
332
  # Refused when the host has not the room for it, whatever
324
333
  # the server said (its size unknown: counted from nothing).
@@ -334,8 +343,8 @@ case "$AREA $VERB" in
334
343
  # for its memory, one for its disk. Anything of an unexpected shape
335
344
  # is left out rather than passed on.
336
345
  [ $# -eq 1 ] || usage; vm_of "$1"
337
- if [ "$SAY" = "yes" ]; then printf '%s\n' "$MULTIPASS get local.$1.memory" "$MULTIPASS get local.$1.disk"; exit 0; fi
338
- for key in memory disk; do
346
+ if [ "$SAY" = "yes" ]; then printf '%s\n' "$MULTIPASS get local.$1.memory" "$MULTIPASS get local.$1.disk" "$MULTIPASS get local.$1.cpus"; exit 0; fi
347
+ for key in memory disk cpus; do
339
348
  value="$("$MULTIPASS" get "local.$1.$key" 2>/dev/null | head -1 | tr -d ' ')" || value=""
340
349
  if [[ "$value" =~ ^[0-9]{1,12}(\.[0-9]{1,3})?[A-Za-z]{0,3}$ ]]; then printf '%s %s\n' "$key" "$value"; fi
341
350
  done
@@ -470,7 +479,7 @@ case "$AREA $VERB" in
470
479
  # used <data|folders|work|removed|tools|shelf|images|others> <MB>
471
480
  # used machine <one of our VMs> <MB>
472
481
  [ $# -eq 0 ] || usage
473
- if [ "$SAY" = "yes" ]; then printf '%s\n' "du $DATA $MNT/resources $MNT/work-disks $MNT/removed $MNT/toolbox/files" "du $SHELF_INSTANCES $SHELF_STORE/cache"; exit 0; fi
482
+ if [ "$SAY" = "yes" ]; then printf '%s\n' "du $DATA $MNT/resources $MNT/work-disks $MNT/removed $MNT/toolbox/files" "du $SHELF_INSTANCES $SHELF_CACHE"; exit 0; fi
474
483
  mb() { { timeout 60 du -smx "$@" 2>/dev/null || true; } | awk '$1 ~ /^[0-9]+$/ {s+=$1} END{print s+0}'; }
475
484
  # The data directory may hold the shared folders (MNT the same, or
476
485
  # under it): they are counted once, in their own lines.
@@ -491,7 +500,7 @@ case "$AREA $VERB" in
491
500
  printf 'used shelf %s\n' "$shelf"
492
501
  printf 'used others %s\n' "$(( all > ours ? all - ours : 0 ))"
493
502
  fi
494
- [ -d "$SHELF_STORE/cache" ] && printf 'used images %s\n' "$(mb -- "$SHELF_STORE/cache")"
503
+ [ -d "$SHELF_CACHE" ] && printf 'used images %s\n' "$(mb -- "$SHELF_CACHE")"
495
504
  exit 0 ;;
496
505
  "folder make")
497
506
  # The folder is made here, and given to the account that owns the data
@@ -626,6 +635,46 @@ case "$AREA $VERB" in
626
635
  case "$at" in "$MNT"/views/*|"$MNT"/toolbox/view) unstale "$at" ;; esac
627
636
  done
628
637
  exit 0 ;;
638
+ "operator list"|"operator add"|"operator password"|"operator disable"|"operator enable"|"operator remove"|"operator failures")
639
+ # WHO MAY SIGN IN (deploy/operators.mjs): the operators of the identity
640
+ # provider. A password comes on standard input, never as an argument.
641
+ if [ "$VERB" = "list" ]; then [ $# -eq 0 ] || usage
642
+ elif [ "$VERB" = "failures" ]; then [ $# -eq 1 ] && number "$1" || usage
643
+ else [ $# -eq 1 ] && [[ "$1" =~ ^[a-z0-9._+-]{1,64}@([a-z0-9-]{1,63}\.)+[a-z]{2,24}$ ]] || refuse "not an e-mail address: ${1:-<empty>}"; fi
644
+ run "$UPDATER_NODE" "$CODE/current/app/deploy/operators.mjs" "$VERB" "$@" ;;
645
+ "machines places")
646
+ # WHERE ALL THE MACHINES COULD GO (deploy/move-machines.sh), for the
647
+ # page: each disk mounted where the VM manager may keep them (/mnt,
648
+ # /media, /home), and the one they are on now. Read-only.
649
+ # now <place> <device> <size MB> <free MB>
650
+ # place <mount point> <device> <size MB> <free MB>
651
+ [ $# -eq 0 ] || usage
652
+ if [ "$SAY" = "yes" ]; then echo "findmnt of /mnt /media /home; df $SHELF_STORE"; exit 0; fi
653
+ printf 'now %s %s %s\n' "$SHELF_STORE" "$(stat -c %d -- "$SHELF_STORE")" "$(df -Pm -- "$SHELF_STORE" | awk 'NR==2 {print $2, $4}')"
654
+ findmnt -rn -o TARGET,FSTYPE | while read -r at fs; do
655
+ case "$fs" in ext2|ext3|ext4|xfs|btrfs|f2fs) : ;; *) continue ;; esac
656
+ case "$at" in /mnt|/mnt/*|/media/*|/home) : ;; *) continue ;; esac
657
+ [[ "$at" =~ ^/[A-Za-z0-9/._-]*$ ]] || continue
658
+ printf 'place %s %s %s\n' "$at" "$(stat -c %d -- "$at")" "$(df -Pm -- "$at" | awk 'NR==2 {print $2, $4}')"
659
+ done
660
+ exit 0 ;;
661
+ "machines move")
662
+ # ALL THE MACHINES TO <mount point>/clavarium-machines, in a service of
663
+ # its own: it stops this server on its way (deploy/move-machines.sh).
664
+ [ $# -eq 1 ] || usage
665
+ case "$1" in /mnt|/mnt/*|/media/?*|/home) : ;; *) refuse "not a place the VM manager may use: $1" ;; esac
666
+ [[ "$1" =~ ^/[A-Za-z0-9/._-]+$ ]] && [[ "$1" != *..* ]] || refuse "not a plain path: $1"
667
+ [ "$SAY" = "yes" ] || mountpoint -q "$1" || refuse "not a disk mounted there: $1"
668
+ target="${1%/}/clavarium-machines"
669
+ run systemd-run --quiet --unit=clavarium-move-machines --collect --description="Clavarium - all the machines to $target" \
670
+ bash "$CODE/current/app/deploy/move-machines.sh" --to "$target" ;;
671
+ "machines moving")
672
+ # How the move goes: the state of its service and the end of what it said.
673
+ [ $# -eq 0 ] || usage
674
+ if [ "$SAY" = "yes" ]; then echo "systemctl show clavarium-move-machines; journalctl -u clavarium-move-machines"; exit 0; fi
675
+ printf 'state %s\n' "$(systemctl show -p ActiveState --value clavarium-move-machines.service 2>/dev/null || echo unknown)"
676
+ journalctl -u clavarium-move-machines.service -n 12 -o cat --no-pager 2>/dev/null | sed 's/^/said /' || true
677
+ exit 0 ;;
629
678
  "net taps")
630
679
  [ $# -eq 0 ] || usage
631
680
  run pgrep -a qemu-system ;;
@@ -0,0 +1,109 @@
1
+ #!/bin/bash
2
+ # ---------------------------------------------------------------------------
3
+ # ALL THE MACHINES TO ANOTHER DISK: the whole storage of the VM manager
4
+ # (Multipass), its disks and its images, moved in Multipass's own documented
5
+ # way -- never one machine alone.
6
+ #
7
+ # sudo bash deploy/move-machines.sh --to /mnt/disk2/machines [--dry-run]
8
+ #
9
+ # In order, and nothing is lost on the way: the originals are COPIED, never
10
+ # moved, and stay where they are until you remove them yourself.
11
+ # 1. checks: root; the place under /mnt, /media or /home (the VM manager is
12
+ # confined to those); empty or absent; room for everything, and 10 % more;
13
+ # 2. Clavarium stopped (nothing starts a machine meanwhile), every machine
14
+ # stopped, then the VM manager;
15
+ # 3. copied: <path>/data and <path>/cache; the paths the VM manager wrote in
16
+ # its two files of instances changed to the new place;
17
+ # 4. the VM manager told where (MULTIPASS_STORAGE, in a drop-in of its
18
+ # service), started, and asked for its machines: the same names must come
19
+ # back. If not, everything is put back as it was and said;
20
+ # 5. Clavarium started again: its conversations start their machines as
21
+ # they are opened.
22
+ # Then: once all works, the old copy can go:
23
+ # sudo rm -rf /var/snap/multipass/common/data/multipassd/vault /var/snap/multipass/common/cache/multipassd
24
+ #
25
+ # Exit codes: 0 done (or would be, --dry-run); 64 bad parameters; 78 refused,
26
+ # nothing changed; 1 failed and put back.
27
+ # ---------------------------------------------------------------------------
28
+ set -euo pipefail
29
+
30
+ OLD="/var/snap/multipass/common"
31
+ DROP_DIR="/etc/systemd/system/snap.multipass.multipassd.service.d"
32
+ DROP="$DROP_DIR/override.conf"
33
+ MULTIPASS="/snap/bin/multipass"
34
+
35
+ bad() { echo "move-machines: $*" >&2; echo "usage: sudo bash deploy/move-machines.sh --to /mnt/DISK/PLACE [--dry-run]" >&2; exit 64; }
36
+ refuse() { echo "move-machines: REFUSED: $*" >&2; exit 78; }
37
+ say() { echo "== $*"; }
38
+
39
+ TO=""; DRY="no"
40
+ while [ $# -gt 0 ]; do
41
+ case "$1" in
42
+ --to) TO="${2:-}"; shift 2 || bad "--to needs a place" ;;
43
+ --dry-run) DRY="yes"; shift ;;
44
+ *) bad "unknown: $1" ;;
45
+ esac
46
+ done
47
+ [ -n "$TO" ] || bad "--to is needed"
48
+ case "$TO" in /mnt/?*|/media/?*|/home/?*) : ;; *) refuse "the VM manager can only keep its machines under /mnt, /media or /home: $TO" ;; esac
49
+ [[ "$TO" =~ ^/[A-Za-z0-9/._-]+$ ]] && [[ "$TO" != *..* ]] || refuse "a plain path, please: $TO"
50
+ TO="${TO%/}"
51
+ [ "$(id -u)" -eq 0 ] || refuse "run it as root (sudo)"
52
+ [ -f "$DROP" ] && grep -q '^Environment=MULTIPASS_STORAGE=' "$DROP" && refuse "the machines were moved already (see $DROP): move them back first"
53
+ [ -d "$OLD/data/multipassd" ] || refuse "no storage of the VM manager in $OLD"
54
+ if [ -e "$TO" ] && [ -n "$(ls -A "$TO" 2>/dev/null)" ]; then refuse "$TO is not empty"; fi
55
+
56
+ parent="$TO"; while [ ! -d "$parent" ]; do parent="$(dirname "$parent")"; done
57
+ need_mb=$(( $(du -smx "$OLD/data/multipassd" "$OLD/cache/multipassd" 2>/dev/null | awk '{s+=$1} END{print s+0}') * 11 / 10 + 512 ))
58
+ free_mb="$(df -Pm -- "$parent" | awk 'NR==2 {print $4}')"
59
+ [ "$(stat -c %d "$parent")" != "$(stat -c %d "$OLD")" ] || refuse "$TO is on the disk the machines are on already"
60
+ say "the machines take about $(( need_mb / 1024 )) GB with the margin; $parent has $(( free_mb / 1024 )) GB free"
61
+ [ "$free_mb" -ge "$need_mb" ] || refuse "not enough room on $parent: $free_mb MB free, $need_mb MB needed"
62
+ if [ "$DRY" = "yes" ]; then
63
+ say "would stop Clavarium and every machine, copy $OLD/data/multipassd to $TO/data and $OLD/cache/multipassd to $TO/cache, write $DROP, start again"
64
+ exit 0
65
+ fi
66
+
67
+ was_running="$(systemctl is-active clavarium.service 2>/dev/null || true)"
68
+ names_before="$("$MULTIPASS" list --format csv 2>/dev/null | tail -n +2 | cut -d, -f1 | sort | tr '\n' ' ')"
69
+ put_back() {
70
+ echo "move-machines: putting everything back as it was" >&2
71
+ snap stop multipass >/dev/null 2>&1 || true
72
+ rm -f -- "$DROP"; systemctl daemon-reload
73
+ snap start multipass >/dev/null 2>&1 || true
74
+ [ "$was_running" = "active" ] && systemctl start clavarium.service || true
75
+ echo "move-machines: back on $OLD; the copy in $TO is left for you to look at, or to remove" >&2
76
+ exit 1
77
+ }
78
+
79
+ say "stopping Clavarium, then every machine, then the VM manager"
80
+ systemctl stop clavarium-update.timer clavarium.service 2>/dev/null || true
81
+ timeout 600 "$MULTIPASS" stop --all || echo " (a machine did not stop cleanly: the VM manager stops it)"
82
+ snap stop multipass
83
+ case "$TO" in /mnt/*|/media/*) snap connect multipass:removable-media 2>/dev/null || true ;; esac
84
+
85
+ say "copying (the originals stay where they are)"
86
+ mkdir -p -- "$TO"; chown root:root -- "$TO"; chmod 0755 -- "$TO"
87
+ cp -a -- "$OLD/data/multipassd" "$TO/data" || put_back
88
+ cp -a -- "$OLD/cache/multipassd" "$TO/cache" 2>/dev/null || mkdir -p -- "$TO/cache"
89
+ # The two files where the VM manager wrote where its machines are.
90
+ for f in "$TO/data/multipassd-vm-instances.json" "$TO/data/vault/multipassd-instance-image-records.json"; do
91
+ [ -f "$f" ] || continue
92
+ sed -i -e "s#$OLD/data/multipassd#$TO/data#g" -e "s#$OLD/cache/multipassd#$TO/cache#g" -- "$f" || put_back
93
+ done
94
+
95
+ say "the VM manager on $TO"
96
+ mkdir -p -- "$DROP_DIR"
97
+ printf '[Service]\n# Written by Clavarium (deploy/move-machines.sh): where the machines are.\nEnvironment=MULTIPASS_STORAGE=%s\n' "$TO" > "$DROP"
98
+ systemctl daemon-reload
99
+ snap start multipass || put_back
100
+ for _ in $(seq 1 60); do "$MULTIPASS" list >/dev/null 2>&1 && break; sleep 2; done
101
+ names_after="$("$MULTIPASS" list --format csv 2>/dev/null | tail -n +2 | cut -d, -f1 | sort | tr '\n' ' ')" || names_after=""
102
+ if [ "$names_after" != "$names_before" ]; then echo "move-machines: the VM manager does not list the same machines: before [$names_before], now [$names_after]" >&2; put_back; fi
103
+
104
+ say "Clavarium started again: its conversations start their machines as they are opened"
105
+ systemctl start clavarium.service clavarium-update.timer 2>/dev/null || true
106
+ echo
107
+ echo "Done: the machines are on $TO ($(df -h --output=avail "$TO" | tail -1 | tr -d ' ') free there)."
108
+ echo "Once everything works, the old copy can go:"
109
+ echo " sudo rm -rf $OLD/data/multipassd/vault $OLD/cache/multipassd"
@@ -0,0 +1,155 @@
1
+ /* WHO MAY SIGN IN: the operators of the identity provider (Dex), changed from
2
+ * the page through the host program ("operator ..."), run as root. Never by the
3
+ * server itself: the identity file is root's, and holds the password hashes.
4
+ *
5
+ * node operators.mjs list email<TAB>enabled|disabled, one per line
6
+ * node operators.mjs add EMAIL the password on standard input
7
+ * node operators.mjs password EMAIL the new password on standard input
8
+ * node operators.mjs disable EMAIL | enable EMAIL | remove EMAIL
9
+ * node operators.mjs failures MINUTES email<TAB>count: failed sign-ins lately
10
+ *
11
+ * The identity file is the one install.sh wrote: its operators are the entries
12
+ * after "staticPasswords:", four lines each, in that one form; nothing else of it
13
+ * is touched. A disabled operator's entry is kept aside (DISABLED, root's), so
14
+ * that enabling it gives back the same password. Dex is restarted after a
15
+ * change, and must come back: otherwise the file is put back as it was.
16
+ * A password never sits on a command line: hashed by Caddy, from standard input.
17
+ */
18
+ import { readFileSync, writeFileSync, renameSync, statSync, chownSync, realpathSync } from 'node:fs';
19
+ import { fileURLToPath } from 'node:url';
20
+ import { spawnSync } from 'node:child_process';
21
+ import { randomUUID } from 'node:crypto';
22
+
23
+ export const DEX_CONFIG = '/etc/dex/config.yaml';
24
+ export const DISABLED = '/etc/clavarium/operators-disabled.json';
25
+ const EMAIL = /^[a-z0-9._+-]{1,64}@([a-z0-9-]{1,63}\.)+[a-z]{2,24}$/;
26
+ const MARK = 'staticPasswords:';
27
+
28
+ export class Refused extends Error {}
29
+
30
+ /* The file as [head, entries]: each entry { email, hash, username, userID }. */
31
+ export function parse(text) {
32
+ const at = text.indexOf(`\n${MARK}\n`);
33
+ if (at < 0) throw new Refused('the identity file has no list of operators');
34
+ const head = text.slice(0, at + MARK.length + 2);
35
+ const lines = text.slice(at + MARK.length + 2).split('\n').filter((l) => l.trim() !== '');
36
+ const entries = [];
37
+ for (let i = 0; i < lines.length; i += 4) {
38
+ const [e, h, u, id] = lines.slice(i, i + 4).map((l) => /^\s*-?\s*[a-zA-Z]+: "([^"]*)"$/.exec(l)?.[1]);
39
+ if ([e, h, u, id].some((x) => x === undefined)) throw new Refused('the list of operators is not in the form install.sh writes: not changed here');
40
+ entries.push({ email: e, hash: h, username: u, userID: id });
41
+ }
42
+ return { head, entries };
43
+ }
44
+ export function format({ head, entries }) {
45
+ return head + entries.map((x) => ` - email: "${x.email}"\n hash: "${x.hash}"\n username: "${x.username}"\n userID: "${x.userID}"\n`).join('');
46
+ }
47
+
48
+ /* The verbs, on files and commands given (the tests give their own). */
49
+ export function operators({ config = DEX_CONFIG, disabled = DISABLED, hash = caddyHash, restart = restartDex, journal = dexJournal } = {}) {
50
+ const read = () => parse(readFileSync(config, 'utf8'));
51
+ const aside = () => { try { return JSON.parse(readFileSync(disabled, 'utf8')); } catch { return []; } };
52
+ /* Its owner and mode kept (root, group dex: Dex reads it, nobody else). */
53
+ const write = (file, text) => { const was = statSync(file); writeFileSync(`${file}.new`, text, { mode: was.mode & 0o777 }); if (process.getuid?.() === 0) chownSync(`${file}.new`, was.uid, was.gid); renameSync(`${file}.new`, file); };
54
+ const keep = (list) => { writeFileSync(`${disabled}.new`, `${JSON.stringify(list, null, 2)}\n`, { mode: 0o600 }); renameSync(`${disabled}.new`, disabled); };
55
+ /* A change of the identity file: Dex restarted on it, or the old file back. */
56
+ const change = (next) => {
57
+ const before = readFileSync(config, 'utf8');
58
+ write(config, format(next));
59
+ if (!restart()) { write(config, before); restart(); throw new Refused('the identity provider did not start with the change: nothing was changed'); }
60
+ };
61
+ const email = (x) => { const e = String(x ?? '').trim().toLowerCase(); if (!EMAIL.test(e)) throw new Refused('not an e-mail address'); return e; };
62
+ const enabled = () => read().entries.filter((x) => x.email);
63
+ return {
64
+ list() { return [...enabled().map((x) => ({ email: x.email, enabled: true })), ...aside().map((x) => ({ email: x.email, enabled: false }))]; },
65
+ add(who, password) {
66
+ const e = email(who);
67
+ if (this.list().some((x) => x.email === e)) throw new Refused(`${e} is an operator already`);
68
+ const f = read();
69
+ change({ ...f, entries: [...f.entries, { email: e, hash: hash(password), username: e.split('@')[0], userID: randomUUID() }] });
70
+ },
71
+ password(who, password) {
72
+ const e = email(who);
73
+ const f = read();
74
+ const i = f.entries.findIndex((x) => x.email === e);
75
+ if (i < 0) {
76
+ const list = aside(); const j = list.findIndex((x) => x.email === e);
77
+ if (j < 0) throw new Refused(`${e} is not an operator`);
78
+ list[j] = { ...list[j], hash: hash(password) }; keep(list); return;
79
+ }
80
+ f.entries[i] = { ...f.entries[i], hash: hash(password) };
81
+ change(f);
82
+ },
83
+ disable(who) {
84
+ const e = email(who);
85
+ const f = read();
86
+ const one = f.entries.find((x) => x.email === e);
87
+ if (!one) throw new Refused(`${e} is not an enabled operator`);
88
+ if (f.entries.length === 1) throw new Refused('the last operator cannot be disabled: nobody could sign in any more');
89
+ keep([...aside().filter((x) => x.email !== e), one]);
90
+ change({ ...f, entries: f.entries.filter((x) => x.email !== e) });
91
+ },
92
+ enable(who) {
93
+ const e = email(who);
94
+ const list = aside(); const one = list.find((x) => x.email === e);
95
+ if (!one) throw new Refused(`${e} is not a disabled operator`);
96
+ const f = read();
97
+ change({ ...f, entries: [...f.entries, one] });
98
+ keep(list.filter((x) => x.email !== e));
99
+ },
100
+ remove(who) {
101
+ const e = email(who);
102
+ const f = read();
103
+ if (f.entries.some((x) => x.email === e)) {
104
+ if (f.entries.length === 1) throw new Refused('the last operator cannot be removed: nobody could sign in any more');
105
+ change({ ...f, entries: f.entries.filter((x) => x.email !== e) });
106
+ }
107
+ keep(aside().filter((x) => x.email !== e));
108
+ },
109
+ /* Failed sign-ins in the last minutes, as Dex logs them: { email: count }. */
110
+ failures(minutes) {
111
+ const counts = {};
112
+ for (const m of journal(minutes).matchAll(/msg="failed login attempt[^"]*" user=(\S+)/g)) { const e = m[1].toLowerCase(); counts[e] = (counts[e] ?? 0) + 1; }
113
+ return counts;
114
+ },
115
+ };
116
+ }
117
+
118
+ function caddyHash(password) {
119
+ const p = String(password ?? '');
120
+ if (p.length < 12 || p.length > 200 || /[\r\n\0]/.test(p)) throw new Refused('a password is one line of 12 to 200 characters');
121
+ const r = spawnSync('/usr/local/bin/caddy', ['hash-password'], { input: `${p}\n`, encoding: 'utf8' });
122
+ const h = String(r.stdout ?? '').trim();
123
+ if (r.status !== 0 || !h.startsWith('$2')) throw new Refused('the password could not be hashed');
124
+ return h;
125
+ }
126
+ function restartDex() {
127
+ spawnSync('systemctl', ['restart', 'dex.service']);
128
+ for (let i = 0; i < 20; i += 1) {
129
+ if (spawnSync('systemctl', ['is-active', '--quiet', 'dex.service']).status === 0) return true;
130
+ spawnSync('sleep', ['0.5']);
131
+ }
132
+ return false;
133
+ }
134
+ function dexJournal(minutes) {
135
+ const r = spawnSync('journalctl', ['-u', 'dex.service', '--since', `-${Number(minutes)}min`, '-o', 'cat', '--no-pager'], { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 });
136
+ return String(r.stdout ?? '');
137
+ }
138
+
139
+ /* Run as a command (the path may go through the link "current": compared once resolved). */
140
+ if (process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
141
+ const [verb, arg] = process.argv.slice(2);
142
+ const ops = operators();
143
+ const stdin = () => { try { return readFileSync(0, 'utf8').replace(/\r?\n$/, ''); } catch { return ''; } };
144
+ try {
145
+ if (verb === 'list') for (const o of ops.list()) console.log(`${o.email}\t${o.enabled ? 'enabled' : 'disabled'}`);
146
+ else if (verb === 'add') ops.add(arg, stdin());
147
+ else if (verb === 'password') ops.password(arg, stdin());
148
+ else if (['disable', 'enable', 'remove'].includes(verb)) ops[verb](arg);
149
+ else if (verb === 'failures') { const m = Number(arg); if (!Number.isInteger(m) || m < 1 || m > 1440) throw new Refused('failures MINUTES'); for (const [e, n] of Object.entries(ops.failures(m))) console.log(`${e}\t${n}`); }
150
+ else throw new Refused('list | add EMAIL | password EMAIL | disable EMAIL | enable EMAIL | remove EMAIL | failures MINUTES');
151
+ } catch (error) {
152
+ console.error(error instanceof Refused ? `REFUSED: ${error.message}` : String(error?.message ?? error));
153
+ process.exit(error instanceof Refused ? 78 : 1);
154
+ }
155
+ }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.4-next.1",
3
+ "version": "0.2.5-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.4-next.1",
9
+ "version": "0.2.5-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.4-next.1",
3
+ "version": "0.2.5-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/api.mjs CHANGED
@@ -66,6 +66,10 @@
66
66
  * POST /api/secrets {name, value} create or replace
67
67
  * POST /api/secrets/<NAME>/remove
68
68
  * POST /api/secrets/<NAME>/rename {name}: its value and where it is handed go with it
69
+ * GET /api/conversations/<name>/health-react POST the same {on?, message?, command?}: what it does when its machine is short
70
+ * GET /api/machines/places GET /api/machines/moving POST /api/machines/move {to}: all the machines to another disk
71
+ * GET /api/operators who may sign in POST /api/operators {email} -> {email, password}: shown once
72
+ * POST /api/operators/<email>/password -> {email, password} POST /api/operators/<email>/disable|enable|remove
69
73
  * POST /api/conversations/<name>/secrets {secret, attached}
70
74
  * GET /api/shortcuts
71
75
  * POST /api/shortcuts {label, text, enter}
@@ -116,7 +120,7 @@ function readBody(request, max = BODY_MAX) {
116
120
  }
117
121
 
118
122
  /* Returns true when the request was an API request (answered here). */
119
- export async function handleApi(request, response, conversations, headers, resources, originOk = sameOrigin, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate) {
123
+ export async function handleApi(request, response, conversations, headers, resources, originOk = sameOrigin, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove) {
120
124
  const { pathname } = new URL(request.url ?? '/', 'http://local');
121
125
  if (!pathname.startsWith('/api/')) return false;
122
126
  const send = (status, body) => {
@@ -125,6 +129,8 @@ export async function handleApi(request, response, conversations, headers, resou
125
129
  /* Files are reached THROUGH a conversation: only a folder attached to it,
126
130
  and writing only where the attachment says "write". */
127
131
  const query = new URL(request.url ?? '/', 'http://local').searchParams;
132
+ /* Who asks (behind the edge; '' on this machine alone): see gate.mjs. */
133
+ const identity = String(request.headers['x-forwarded-email'] ?? '').trim().toLowerCase();
128
134
  const attached = (need) => {
129
135
  /* The conversation's own work folder, when the server keeps it. */
130
136
  if (query.get('r') === WORK_TAB && resources) {
@@ -214,6 +220,12 @@ export async function handleApi(request, response, conversations, headers, resou
214
220
  if (pathname === '/api/shelf' && shelf) return send(200, shelf.about()), true;
215
221
  /* Settings, Updates (updates.mjs): what runs, what is out, the mode, what happened. */
216
222
  if (pathname === '/api/updates' && updates) return send(200, updates.about()), true;
223
+ /* Who may sign in (operators.mjs): none in local mode. */
224
+ const reactOf = /^\/api\/conversations\/([^/]+)\/health-react$/.exec(pathname);
225
+ if (reactOf && reacting) return send(200, reacting.settings(decodeURIComponent(reactOf[1]))), true;
226
+ if (pathname === '/api/machines/places' && machinesMove) return send(200, await machinesMove.places()), true;
227
+ if (pathname === '/api/machines/moving' && machinesMove) return send(200, await machinesMove.moving()), true;
228
+ if (pathname === '/api/operators') return send(200, team ? { operators: team.list(), me: identity } : { local: true }), true;
217
229
  if (pathname === '/api/certificate' && certificate) return send(200, await certificate.about({ fresh: query.get('fresh') === '1' })), true;
218
230
  /* This server's disk and memory (capacity.mjs): everything for Settings; only whether it is high for the list. */
219
231
  if (pathname === '/api/server' && capacity) return send(200, await capacity.about()), true;
@@ -307,6 +319,17 @@ export async function handleApi(request, response, conversations, headers, resou
307
319
  if (fetched && mailboxes) return send(200, await mailboxes.sync(fetched[1])), true;
308
320
  if (pathname === '/api/shortcuts' && shortcuts) return send(201, shortcuts.add(body)), true;
309
321
  if (pathname === '/api/secrets' && secrets) { const made = secrets.set(body); setup?.secretAdded(made.name); return send(201, made), true; }
322
+ const reactSet = /^\/api\/conversations\/([^/]+)\/health-react$/.exec(pathname);
323
+ if (reactSet && reacting) { const n = decodeURIComponent(reactSet[1]); if (!conversations.list().some((c) => c.name === n)) throw new Refusal(404, 'No such conversation.'); return send(200, reacting.set(n, body)), true; }
324
+ if (pathname === '/api/machines/move' && machinesMove) return send(202, await machinesMove.move(String(body.to ?? ''))), true;
325
+ if (pathname === '/api/operators' && team) return send(201, await team.add(body.email)), true;
326
+ const op = /^\/api\/operators\/([^/]{3,200})\/(password|disable|enable|remove)$/.exec(pathname);
327
+ if (op && team) {
328
+ const email = decodeURIComponent(op[1]);
329
+ /* Not oneself out: another operator does it, or nobody would see it was a mistake. */
330
+ if (op[2] !== 'password' && op[2] !== 'enable' && email.toLowerCase() === identity) throw new Refusal(409, 'You cannot do that to your own account: ask another operator.');
331
+ return send(200, op[2] === 'password' ? await team.password(email) : { operators: await team[op[2]](email) }), true;
332
+ }
310
333
  const renaming = /^\/api\/secrets\/([A-Z][A-Z0-9_]{0,39})\/rename$/.exec(pathname);
311
334
  if (renaming && secrets) return send(200, secrets.rename(renaming[1], String(body.name ?? '').trim())), true;
312
335
  const dropped = /^\/api\/secrets\/([A-Z][A-Z0-9_]{0,39})\/remove$/.exec(pathname);
@@ -442,7 +465,7 @@ export async function handleApi(request, response, conversations, headers, resou
442
465
  return send(200, await health.check(conversation)), true;
443
466
  }
444
467
  if (machine[2] === 'restart') return send(202, await conversations.restart(conversation)), true;
445
- return send(202, await conversations.resize(conversation, { memoryMb: body.memoryMb, diskGb: body.diskGb })), true;
468
+ return send(202, await conversations.resize(conversation, { memoryMb: body.memoryMb, diskGb: body.diskGb, cpus: body.cpus })), true;
446
469
  }
447
470
  const asking = /^\/api\/conversations\/([^/]+)\/ask-first$/.exec(pathname);
448
471
  if (asking) return send(200, conversations.setAskFirst(decodeURIComponent(asking[1]), body.on)), true;
@@ -87,6 +87,8 @@ export const gb = (mb) => `${(mb / 1024).toFixed(1)} GB`;
87
87
  const percent = (part, all) => (all > 0 ? Math.round((part / all) * 100) : 0);
88
88
 
89
89
  export class Capacity {
90
+ /* What the machines take on their disk, as last measured (MB), or undefined. */
91
+ machinesUsedMb() { const u = this.#usage; if (!u) return undefined; return Object.values(u.machines ?? {}).reduce((a, b) => a + b, 0) + (u.shelf ?? 0) + (u.images ?? 0); }
90
92
  #run; #store; #conversations; #shelf; #now; #roomMs; #sleep; #alert; #say; #short = { disk: false, memory: false }; #room = null; #roomAt = -Infinity; #usage = null; #usageAt = -Infinity; #going = null; #measuring = null;
91
93
 
92
94
  /* `run(argv)`: the host program. `store`: where the reserve is kept.
@@ -12,6 +12,7 @@ import { attachCommand, SOCKET } from './tmux.mjs';
12
12
  import { WORK, VM_USER, SHARING_STEP } from './vm.mjs';
13
13
  import { resumeOrFresh } from './tools.mjs';
14
14
  import { TOOLS_PATH, LAUNCH } from './toolbox.mjs';
15
+ import { availableParallelism } from 'node:os';
15
16
 
16
17
  export const SESSION = 'main';
17
18
  export const STOP_DELAY_MS = 60_000;
@@ -213,7 +214,7 @@ export class Conversations {
213
214
  return this.#store.all().sort((a, b) => order.indexOf(a.name) - order.indexOf(b.name)).map((c) => {
214
215
  const tool = this.#tools.find((t) => t.id === c.tool);
215
216
  /* An AI tool has an instruction file; a shell has none: what is dictated there is never marked. */
216
- return { ...c, rank: order.indexOf(c.name), ...(c.group ? { groupRank: groups.indexOf(c.group) } : {}), toolLabel: tool?.label ?? c.tool, memoryMinMb: tool?.memoryMb, resumes: Boolean(tool?.resume), rights: Boolean(tool?.rights), ai: Boolean(tool?.instructions), voiceMark: Boolean(tool?.instructions) && c.voiceMark !== false };
217
+ return { ...c, rank: order.indexOf(c.name), ...(c.group ? { groupRank: groups.indexOf(c.group) } : {}), toolLabel: tool?.label ?? c.tool, memoryMinMb: tool?.memoryMb, resumes: Boolean(tool?.resume), rights: Boolean(tool?.rights), ai: Boolean(tool?.instructions), voiceMark: Boolean(tool?.instructions) && c.voiceMark !== false, cpus: c.cpus ?? 1, hostCpus: availableParallelism() };
217
218
  });
218
219
  }
219
220
 
@@ -700,19 +701,23 @@ export class Conversations {
700
701
  stopped (cleanly first), set, and started again -- its work folder,
701
702
  its folders and its branches are not touched. A disk only grows.
702
703
  What is recorded afterwards is what the VM manager says it has. */
703
- async resize(name, { memoryMb, diskGb } = {}) {
704
+ async resize(name, { memoryMb, diskGb, cpus: cpusAsked } = {}) {
704
705
  const c = this.#busyCheck(name);
705
706
  const tool = this.#tools.find((t) => t.id === c.tool);
706
707
  const memory = memoryMb === undefined || memoryMb === null || memoryMb === '' ? c.memoryMb : Number(memoryMb);
707
708
  const disk = diskGb === undefined || diskGb === null || diskGb === '' ? c.diskGb ?? DISK_GB : Number(diskGb);
709
+ const cpusNow = c.cpus ?? 1;
710
+ const cpus = cpusAsked === undefined || cpusAsked === null || cpusAsked === '' ? cpusNow : Number(cpusAsked);
711
+ const hostCpus = availableParallelism();
712
+ if (cpus !== cpusNow && (!Number.isInteger(cpus) || cpus < 1 || cpus > hostCpus)) throw new Refusal(400, `Cores: 1 to ${hostCpus}, those of this server, which its machines share.`);
708
713
  const least = tool?.memoryMb ?? 512;
709
714
  /* Memory is checked only when it changes: a machine made when its tool
710
715
  needed less keeps what it has, and its disk can still grow. */
711
716
  if (memory !== c.memoryMb && (!Number.isInteger(memory) || memory < least || memory > MEMORY_MAX_MB)) throw new Refusal(400, `Memory is between ${least} MB (what ${tool?.label ?? 'its tool'} needs) and ${MEMORY_MAX_MB} MB.`);
712
717
  if (!Number.isInteger(disk) || disk > DISK_MAX_GB) throw new Refusal(400, `A disk is at most ${DISK_MAX_GB} GB.`);
713
718
  if (disk < (c.diskGb ?? DISK_GB)) throw new Refusal(400, `A disk can only grow: it has ${c.diskGb ?? DISK_GB} GB.`);
714
- if (memory === c.memoryMb && disk === (c.diskGb ?? DISK_GB)) throw new Refusal(409, 'Nothing to change: it already has this.');
715
- if (c.asleep === true) throw new Refusal(409, 'It is asleep: wake it first, then change its memory or its disk.');
719
+ if (memory === c.memoryMb && disk === (c.diskGb ?? DISK_GB) && cpus === cpusNow) throw new Refusal(409, 'Nothing to change: it already has this.');
720
+ if (c.asleep === true) throw new Refusal(409, 'It is asleep: wake it first, then change its memory, cores or disk.');
716
721
  const release = this.#claim(name, 'restarting', 'Looking at the machine');
717
722
  let state;
718
723
  try {
@@ -733,6 +738,11 @@ export class Conversations {
733
738
  const r = await this.#vms.setMemory(name, memory);
734
739
  if (r.code !== 0) return `its memory could not be set (${firstLine(r.stderr) || firstLine(r.stdout) || `exit ${r.code}`}).`;
735
740
  }
741
+ if (cpus !== cpusNow) {
742
+ this.#store.patch(name, { step: `Setting its cores to ${cpus}` });
743
+ const r = await this.#vms.setCpus(name, cpus);
744
+ if (r.code !== 0) return `its cores could not be set (${firstLine(r.stderr) || firstLine(r.stdout) || `exit ${r.code}`}).`;
745
+ }
736
746
  if (disk !== (c.diskGb ?? DISK_GB)) {
737
747
  this.#store.patch(name, { step: `Growing its disk to ${disk} GB` });
738
748
  const r = await this.#vms.setDisk(name, disk);
@@ -743,7 +753,7 @@ export class Conversations {
743
753
  this.resized = this.#cycle(name, c, set, state === 'Running').then(async (failure) => {
744
754
  await this.reconcile(name);
745
755
  const now = this.#store.get(name);
746
- const said = `${now?.memoryMb ?? memory} MB of memory, ${now?.diskGb ?? disk} GB of disk`;
756
+ const said = `${now?.memoryMb ?? memory} MB of memory, ${now?.cpus ?? cpus} core${(now?.cpus ?? cpus) > 1 ? 's' : ''}, ${now?.diskGb ?? disk} GB of disk`;
747
757
  await this.#settle(name, failure ? `Not changed: ${failure} It has ${said}.` : `It now has ${said}.`, failure ? `Its machine was not changed: ${failure} It has ${said}.` : `Its machine was restarted with ${said}: the tool started again.`, Boolean(failure));
748
758
  });
749
759
  return this.#store.get(name);
@@ -756,6 +766,7 @@ export class Conversations {
756
766
  const patch = {};
757
767
  if (real.memoryMb !== undefined && real.memoryMb !== this.#store.get(name).memoryMb) patch.memoryMb = real.memoryMb;
758
768
  if (real.diskGb !== undefined && real.diskGb !== this.#store.get(name).diskGb) patch.diskGb = real.diskGb;
769
+ if (real.cpus !== undefined && real.cpus !== (this.#store.get(name).cpus ?? 1)) patch.cpus = real.cpus;
759
770
  if (Object.keys(patch).length > 0 && this.#store.get(name)) this.#store.patch(name, patch);
760
771
  }
761
772
  async reconcileAll() {
package/server/gate.mjs CHANGED
@@ -25,10 +25,13 @@ export function readOperators(text) {
25
25
 
26
26
  /* Returns a function: (headers) -> the operator's address, or undefined when
27
27
  the request is not from an operator. In development mode it returns 'local'. */
28
+ /* `operators`: the list, or a function that gives it as it is now (they are
29
+ added and disabled from the page: see operators.mjs). */
28
30
  export function makeGate(operators = []) {
29
- if (operators.length === 0) return () => 'local';
30
- const allowed = new Set(operators);
31
+ if (typeof operators !== 'function' && operators.length === 0) return () => 'local';
32
+ const now = typeof operators === 'function' ? operators : () => operators;
31
33
  return (headers) => {
34
+ const allowed = new Set(now());
32
35
  const value = headers[IDENTITY_HEADER];
33
36
  /* A header sent twice arrives as one string joined by commas: two
34
37
  identities is not an identity. */
@@ -0,0 +1,79 @@
1
+ /* WHAT A CONVERSATION DOES WHEN ITS MACHINE IS SHORT (health.mjs: its disk
2
+ * almost full, its memory almost full), chosen by the owner for each one --
3
+ * never by default. The owner is told either way (talk.mjs, the alert);
4
+ * this is what is done on top of that, once per problem (said again only
5
+ * once it went away and came back):
6
+ *
7
+ * an agent (Claude Code, OpenCode...) is told, in a line the owner can
8
+ * change; {problem} is replaced by
9
+ * what health.mjs found
10
+ * a tool with no agent (a shell) a command of the owner's is run in
11
+ * its machine, as its user, bounded
12
+ *
13
+ * What was said or run is in the conversation's chat (talk.mjs, an event).
14
+ *
15
+ * settings(name) { on, message, command } (message: the default when unset)
16
+ * set(name, body) { on?, message?, command? }
17
+ * judged(name, record) told each judgment by health.mjs
18
+ */
19
+ import { Refusal } from './conversations.mjs';
20
+
21
+ export const KINDS = ['disk', 'memory'];
22
+ export const DEFAULT_MESSAGE = 'Clavarium: {problem} Free some room without losing anything: caches, temporary files, old builds. Then say in one line what you removed.';
23
+ const MESSAGE_MAX = 500;
24
+ const COMMAND_MAX = 500;
25
+ const COMMAND_SECONDS = 120;
26
+
27
+ export class HealthReact {
28
+ #store; #say; #exec; #isAgent; #event;
29
+ /* `say(name, line)`: typed to its agent (wakeups.mjs); `exec(name, argv, options)`: run in its
30
+ machine; `isAgent(name)`: its tool has an agent; `event(name, line)`: said in its chat. */
31
+ constructor({ store, say, exec, isAgent, event = () => {} }) {
32
+ this.#store = store; this.#say = say; this.#exec = exec; this.#isAgent = isAgent; this.#event = event;
33
+ }
34
+ settings(name) {
35
+ const r = this.#store.get(name) ?? {};
36
+ return { on: r.on === true, message: r.message || DEFAULT_MESSAGE, command: r.command ?? '', agent: Boolean(this.#isAgent(name)) };
37
+ }
38
+ set(name, body = {}) {
39
+ const r = { name, ...(this.#store.get(name) ?? {}) };
40
+ if (body.on !== undefined) { if (typeof body.on !== 'boolean') throw new Refusal(400, 'Say true or false.'); r.on = body.on; }
41
+ if (body.message !== undefined) {
42
+ const m = String(body.message).trim();
43
+ if (m.length > MESSAGE_MAX || /[\r\n\0]/.test(m)) throw new Refusal(400, `The message is one line, ${MESSAGE_MAX} characters at most.`);
44
+ r.message = m || undefined;
45
+ }
46
+ if (body.command !== undefined) {
47
+ const c = String(body.command).trim();
48
+ if (c.length > COMMAND_MAX || /[\r\n\0]/.test(c)) throw new Refusal(400, `The command is one line, ${COMMAND_MAX} characters at most.`);
49
+ r.command = c;
50
+ }
51
+ this.#store.put(r);
52
+ return this.settings(name);
53
+ }
54
+ forget(name) { this.#store.remove?.(name); }
55
+
56
+ async judged(name, record) {
57
+ const r = this.#store.get(name);
58
+ if (!r?.on || !record) return;
59
+ const short = (record.problems ?? []).filter((p) => KINDS.includes(p.kind) && (p.level === 'warn' || p.level === 'bad'));
60
+ /* A machine not looked at inside: what was wrong is not known to be gone. */
61
+ if (short.length === 0 && record.state !== 'Running') return;
62
+ const keys = short.map((p) => p.key ?? p.text);
63
+ const before = new Set(r.reacted ?? []);
64
+ const fresh = short.filter((p) => !before.has(p.key ?? p.text));
65
+ if (keys.join('|') !== (r.reacted ?? []).join('|')) this.#store.put({ ...r, reacted: keys });
66
+ if (fresh.length === 0) return;
67
+ const problem = fresh.map((p) => p.text).join(' ');
68
+ if (this.#isAgent(name)) {
69
+ const line = (r.message || DEFAULT_MESSAGE).replaceAll('{problem}', problem);
70
+ const typed = await this.#say(name, line).catch(() => false);
71
+ this.#event(name, { kind: 'machine-problem', topic: 'Machine', tone: 'warn', text: typed ? `Said to its agent: ${line}` : `Not said to its agent (its tool is not running): ${line}` });
72
+ return;
73
+ }
74
+ if (!r.command) return;
75
+ const ran = await this.#exec(name, ['timeout', '-k', '10', String(COMMAND_SECONDS), 'sh', '-c', r.command], { timeoutMs: (COMMAND_SECONDS + 30) * 1000 }).catch((error) => ({ code: -1, stdout: '', stderr: String(error?.message ?? error) }));
76
+ const out = `${ran.stdout ?? ''}${ran.stderr ?? ''}`.trim().split('\n').slice(-3).join(' ').slice(0, 300);
77
+ this.#event(name, { kind: 'machine-problem', topic: 'Machine', tone: ran.code === 0 ? 'warn' : 'bad', text: `Ran: ${r.command} (exit ${ran.code})${out ? `: ${out}` : ''}` });
78
+ }
79
+ }
@@ -0,0 +1,52 @@
1
+ /* ALL THE MACHINES TO ANOTHER DISK, from Settings (deploy/move-machines.sh, run as
2
+ * root in a service of its own by the host program: it stops this server on its
3
+ * way, and starts it again).
4
+ *
5
+ * places() { now: { place, device, sizeMb, freeMb }, places: [{ at, device, sizeMb, freeMb, why }] }
6
+ * why: '' when they may go there, or why not (the same disk, too small)
7
+ * move(at) started; the page loses this server for a while, and finds it again
8
+ * moving() { state, said: [lines] }: how it goes, or how it went
9
+ */
10
+ import { Refusal } from './conversations.mjs';
11
+
12
+ const firstLine = (text) => String(text ?? '').trim().split('\n').filter(Boolean).pop()?.replace(/^REFUSED: /, '').slice(0, 200) ?? '';
13
+ const whole = (x) => (/^\d+$/.test(x ?? '') ? Number(x) : undefined);
14
+
15
+ export class MachinesMove {
16
+ #host; #usedMb;
17
+ /* `usedMb()`: what the machines take now (capacity.mjs, server usage), or undefined. */
18
+ constructor({ host, usedMb = () => undefined }) { this.#host = host; this.#usedMb = usedMb; }
19
+ async places() {
20
+ const r = await this.#host(['machines', 'places']);
21
+ if (r.code !== 0) throw new Refusal(502, `The disks could not be listed: ${firstLine(r.stderr) || `exit ${r.code}`}`);
22
+ let now = null; const places = [];
23
+ for (const p of String(r.stdout).split('\n').map((l) => l.trim().split(' '))) {
24
+ if (p[0] === 'now' && p.length === 5) now = { place: p[1], device: whole(p[2]), sizeMb: whole(p[3]), freeMb: whole(p[4]) };
25
+ if (p[0] === 'place' && p.length === 5) places.push({ at: p[1], device: whole(p[2]), sizeMb: whole(p[3]), freeMb: whole(p[4]) });
26
+ }
27
+ const used = this.#usedMb();
28
+ const need = used === undefined ? undefined : Math.round(used * 1.1) + 512;
29
+ for (const p of places) {
30
+ p.why = now && p.device === now.device ? 'the machines are on this disk already'
31
+ : need !== undefined && p.freeMb < need ? `too small: ${Math.round(p.freeMb / 1024)} GB free, about ${Math.ceil(need / 1024)} GB needed`
32
+ : '';
33
+ }
34
+ return { now, places, needMb: need ?? null };
35
+ }
36
+ async move(at) {
37
+ const { places } = await this.places();
38
+ const p = places.find((x) => x.at === at);
39
+ if (!p) throw new Refusal(404, 'This disk is not one the machines can go to.');
40
+ if (p.why) throw new Refusal(409, `Not there: ${p.why}.`);
41
+ const r = await this.#host(['machines', 'move', at]);
42
+ if (r.code !== 0) throw new Refusal(r.code === 78 ? 400 : 502, firstLine(r.stderr) || `exit ${r.code}`);
43
+ return { started: true, to: `${at.replace(/\/$/, '')}/clavarium-machines` };
44
+ }
45
+ async moving() {
46
+ const r = await this.#host(['machines', 'moving']);
47
+ const lines = String(r.stdout ?? '').split('\n');
48
+ const state = lines.find((l) => l.startsWith('state '))?.slice(6).trim() || 'unknown';
49
+ const said = lines.filter((l) => l.startsWith('said ')).map((l) => l.slice(5)).slice(-12);
50
+ return { state, said, done: said.some((l) => l.startsWith('Done:')), failed: said.some((l) => /REFUSED|putting everything back/.test(l)) };
51
+ }
52
+ }
package/server/main.mjs CHANGED
@@ -56,6 +56,9 @@ import { Capacity } from './capacity.mjs';
56
56
  import { packageFile, PARLEY } from './parley.mjs';
57
57
  import { Updates } from './updates.mjs';
58
58
  import { Certificate } from './certificate.mjs';
59
+ import { Operators } from './operators.mjs';
60
+ import { HealthReact } from './healthreact.mjs';
61
+ import { MachinesMove } from './machinesmove.mjs';
59
62
  import { migrateData } from './dataformat.mjs';
60
63
  import { VmWatch } from './vmwatch.mjs';
61
64
 
@@ -117,7 +120,7 @@ const withoutTmux = (env) => Object.fromEntries(Object.entries(env).filter(([key
117
120
 
118
121
  const REFUSED = 'This Clavarium belongs to someone else: your account is not one of its operators.\n';
119
122
 
120
- function serve(port, conversations, resources, { gate = () => 'local', originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, repair, capacity, updates, instance = new Instance(), certificate } = {}) {
123
+ function serve(port, conversations, resources, { gate = () => 'local', originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, repair, capacity, updates, instance = new Instance(), certificate, team, reacting, machinesMove } = {}) {
121
124
  /* Its manifest carries the name of this Clavarium, or the one a device chose (instance.mjs). */
122
125
  const sendManifest = (response, url) => response.writeHead(200, { ...HEADERS, 'content-type': 'application/manifest+json' }).end(instance.manifest(new URL(url ?? '/', 'http://local').searchParams.get('name') ?? undefined));
123
126
  const sendFile = async (response, file) => {
@@ -155,7 +158,7 @@ function serve(port, conversations, resources, { gate = () => 'local', originOk,
155
158
  response.writeHead(403, { ...HEADERS, 'content-type': 'text/plain; charset=utf-8' }).end(REFUSED);
156
159
  return;
157
160
  }
158
- if (conversations && await handleApi(request, response, conversations, HEADERS, resources, originOk, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate)) return;
161
+ if (conversations && await handleApi(request, response, conversations, HEADERS, resources, originOk, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove)) return;
159
162
  if (pathname === '/manifest.webmanifest' && request.method === 'GET') { sendManifest(response, request.url); return; }
160
163
  const file = FILES[pathname];
161
164
  if (!file || (request.method !== 'GET' && request.method !== 'HEAD')) {
@@ -195,7 +198,9 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
195
198
  /* The data, in the format this code reads, before anything reads it (dataformat.mjs). */
196
199
  const migrated = migrateData(dataDir);
197
200
  if (migrated.ran.length) console.log(`data: format ${migrated.from} -> ${migrated.to}`);
198
- const gate = makeGate(operators);
201
+ /* Who may sign in, kept up to date from the page (operators.mjs); none: this machine only. */
202
+ const team = operators.length ? new Operators({ host: runner(host), store: new Store(`${dataDir}/operators.json`), initial: operators }) : null;
203
+ const gate = makeGate(team ? () => team.allowed() : []);
199
204
  const originOk = makeOriginCheck(publicOrigin);
200
205
  const instance = new Instance({ file: new JsonFile(`${dataDir}/instance.json`, {}), origin: publicOrigin, given: appName });
201
206
  let repairTerminal = async () => { throw new Error('not ready'); };
@@ -363,7 +368,10 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
363
368
  const health = new Health({ vms, conversations: all, resources: folders, ...(healthSettleMs === undefined ? {} : { settleMs: healthSettleMs }) });
364
369
  const stopHealth = health.start(healthEveryMs);
365
370
  /* What is wrong with its machine is said in its chat too, where it happened. */
366
- health.judged = (name, record) => talk.machine(name, record);
371
+ /* And what its owner chose that it does on top (healthreact.mjs): its agent told, or a command run. */
372
+ const reacting = new HealthReact({ store: new Store(`${dataDir}/health-react.json`), say: (name, line) => wakeups.say(name, line), exec: (name, argv, options) => vms.exec(name, argv, options),
373
+ isAgent: (name) => all.list().find((c) => c.name === name)?.ai === true, event: (name, line) => talk.event(name, line) });
374
+ health.judged = (name, record) => { talk.machine(name, record); void reacting.judged(name, record).catch(() => {}); };
367
375
  /* A machine just started: its folders are mounted again (after a build,
368
376
  a restart, a move) or looked at and put back if they came loose (after
369
377
  a wake), before its tool starts in them. */
@@ -375,7 +383,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
375
383
  /* The VM manager, watched: said to the pages when it does not answer, restarted once when stuck (vmwatch.mjs). */
376
384
  const vmWatch = new VmWatch({ run: asHost, store: new Store(`${dataDir}/vm-manager.json`), alert: (payload) => { void alerts.tell(payload)?.catch?.(() => {}); } });
377
385
  const stopVmWatch = vmWatch.start(vmWatchEveryMs);
378
- const platform = { get machines() { return vmWatch.ok; }, answerer: answerer.about(), operators: [...operators], address: publicOrigin ?? null, version: JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version, get dictation() { return voice.current() ? (voice.model ?? 'set') : null; } };
386
+ const platform = { get machines() { return vmWatch.ok; }, answerer: answerer.about(), get operators() { return team ? team.allowed() : [...operators]; }, address: publicOrigin ?? null, version: JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version, get dictation() { return voice.current() ? (voice.model ?? 'set') : null; } };
379
387
  /* Who gets what, and a whole setup in one file: see setup.mjs. */
380
388
  /* Settings, Updates: what the updater (deploy/updater.mjs, as root) wrote, and how to ask it. */
381
389
  const updates = new Updates({ host: asHost, version: platform.version, store: new Store(`${dataDir}/updates.json`), alerts, ...(updateState ? { stateFile: updateState } : {}), ...(updateConf ? { confFile: updateConf } : {}) });
@@ -390,7 +398,14 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
390
398
  const stopWatch = capacity.start();
391
399
  /* The certificate the front serves, said in Settings (certificate.mjs). */
392
400
  const certificate = new Certificate({ origin: publicOrigin, alerts });
393
- const { server, listening } = serve(port, all, folders, { gate, originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, capacity, updates, instance, certificate, repair: (name) => repairTerminal(name) });
401
+ /* All the machines to another disk, from Settings (machinesmove.mjs). */
402
+ const machinesMove = new MachinesMove({ host: asHost, usedMb: () => capacity.machinesUsedMb() });
403
+ if (team) {
404
+ team.useAlerts(alerts);
405
+ void team.refresh().catch((error) => console.error(`operators: ${error.message}`));
406
+ const watching = setInterval(() => { void team.watch().catch(() => {}); }, 60_000); watching.unref?.();
407
+ }
408
+ const { server, listening } = serve(port, all, folders, { gate, originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, repair: (name) => repairTerminal(name) });
394
409
  server.on('close', () => { closing = true; stopVmWatch(); stopShelf(); stopHealth(); stopUpdates(); stopWatch(); clearInterval(mailTimer); clearInterval(answerTimer); clearInterval(wakeTimer); clearInterval(gitTimer); talk.stop(); });
395
410
  let closing = false;
396
411
  bridge = attachBridge(server, {
@@ -0,0 +1,107 @@
1
+ /* THE OPERATORS, from the page: who may sign in, each with a password of their
2
+ * own (deploy/operators.mjs, as root, through the host program).
3
+ *
4
+ * list() [{ email, enabled, locked }]
5
+ * add(email) { email, password }: the password shown once, then never again
6
+ * password(email) { email, password }: a new one, shown once
7
+ * disable / enable / remove the last enabled operator cannot be disabled nor removed
8
+ *
9
+ * Whoever signs in is checked against this list at each request (gate.mjs):
10
+ * an operator added comes in at once, one disabled or removed is out at once,
11
+ * even with a session still open.
12
+ *
13
+ * LOCKED AFTER FAILED ATTEMPTS: FAILS_MAX failed sign-ins within WINDOW_MIN
14
+ * minutes (as the identity provider logs them) disable the address for
15
+ * LOCK_MIN minutes, the owner told; it is enabled again by itself after. The
16
+ * last enabled operator is never locked out: the owner is told instead.
17
+ */
18
+ import { randomBytes } from 'node:crypto';
19
+ import { Refusal } from './conversations.mjs';
20
+
21
+ export const FAILS_MAX = 5;
22
+ export const WINDOW_MIN = 15;
23
+ export const LOCK_MIN = 15;
24
+ const EMAIL = /^[a-z0-9._+-]{1,64}@([a-z0-9-]{1,63}\.)+[a-z]{2,24}$/;
25
+ const firstLine = (text) => String(text ?? '').trim().split('\n').filter(Boolean).pop()?.replace(/^REFUSED: /, '').slice(0, 200) ?? '';
26
+ /* 24 characters a person can read aloud and type: no 0/O, no 1/l/I. */
27
+ export function newPassword() {
28
+ const set = 'abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
29
+ return [...randomBytes(24)].map((b) => set[b % set.length]).join('').replace(/(.{6})(?=.)/g, '$1-');
30
+ }
31
+
32
+ export class Operators {
33
+ #host; #store; #alerts; #now; #list; #said = new Map();
34
+ /* `initial`: the operators the server was started with (--operators), until the host says. */
35
+ constructor({ host, store, alerts, initial = [], now = Date.now }) {
36
+ this.#host = host; this.#store = store; this.#alerts = alerts; this.#now = now;
37
+ this.#list = initial.map((email) => ({ email, enabled: true }));
38
+ }
39
+ /* Those who may come in now: for the gate. */
40
+ allowed() { return this.#list.filter((o) => o.enabled).map((o) => o.email); }
41
+ list() {
42
+ const locks = this.#store.get('locks') ?? {};
43
+ return this.#list.map((o) => ({ ...o, locked: locks[o.email]?.until && new Date(locks[o.email].until) > this.#now() ? locks[o.email].until : null }));
44
+ }
45
+ async refresh() {
46
+ const r = await this.#host(['operator', 'list']);
47
+ if (r.code !== 0) throw new Refusal(502, `Who may sign in could not be read: ${firstLine(r.stderr) || `exit ${r.code}`}`);
48
+ const read = String(r.stdout).split('\n').map((l) => l.split('\t')).filter(([e, s]) => EMAIL.test(e ?? '') && ['enabled', 'disabled'].includes(s));
49
+ if (read.length) this.#list = read.map(([email, state]) => ({ email, enabled: state === 'enabled' }));
50
+ return this.list();
51
+ }
52
+ async #do(argv, input) {
53
+ const r = await this.#host(argv, input === undefined ? {} : { input });
54
+ if (r.code !== 0) throw new Refusal(r.code === 78 ? 400 : 502, firstLine(r.stderr) || `exit ${r.code}`);
55
+ await this.refresh();
56
+ }
57
+ #email(given) {
58
+ const e = String(given ?? '').trim().toLowerCase();
59
+ if (!EMAIL.test(e)) throw new Refusal(400, 'An operator is an e-mail address.');
60
+ return e;
61
+ }
62
+ async add(email) {
63
+ const e = this.#email(email); const password = newPassword();
64
+ await this.#do(['operator', 'add', e], `${password}\n`);
65
+ /* What the identity provider now says, not what was hoped: a password given for nobody is no use. */
66
+ if (!this.#list.some((o) => o.email === e && o.enabled)) throw new Refusal(502, `${e} was not added: the identity provider does not list it.`);
67
+ return { email: e, password };
68
+ }
69
+ async password(email) {
70
+ const e = this.#email(email); const password = newPassword();
71
+ await this.#do(['operator', 'password', e], `${password}\n`);
72
+ return { email: e, password };
73
+ }
74
+ async disable(email) { await this.#do(['operator', 'disable', this.#email(email)]); this.#unlock(this.#email(email)); return this.list(); }
75
+ async enable(email) { await this.#do(['operator', 'enable', this.#email(email)]); this.#unlock(this.#email(email)); return this.list(); }
76
+ async remove(email) { await this.#do(['operator', 'remove', this.#email(email)]); this.#unlock(this.#email(email)); return this.list(); }
77
+ #unlock(email) { const locks = { ...(this.#store.get('locks') ?? {}) }; delete locks[email]; this.#store.put({ name: 'locks', ...locks }); }
78
+
79
+ /* At each turn: too many failed sign-ins lock an address for a while; a lock that is over is lifted. */
80
+ async watch() {
81
+ const locks = { ...(this.#store.get('locks') ?? {}) }; delete locks.name;
82
+ const now = this.#now();
83
+ for (const [email, lock] of Object.entries(locks)) {
84
+ if (new Date(lock.until) > now) continue;
85
+ delete locks[email];
86
+ if (this.#list.some((o) => o.email === email && !o.enabled)) await this.#do(['operator', 'enable', email]).catch(() => {});
87
+ }
88
+ const r = await this.#host(['operator', 'failures', String(WINDOW_MIN)]);
89
+ if (r.code === 0) {
90
+ for (const [email, n] of String(r.stdout).split('\n').map((l) => l.split('\t')).filter(([e]) => EMAIL.test(e ?? ''))) {
91
+ if (Number(n) < FAILS_MAX || locks[email]) continue;
92
+ const one = this.#list.find((o) => o.email === email && o.enabled);
93
+ if (!one) continue;
94
+ if (this.allowed().length === 1) {
95
+ if (this.#said.get(email) !== 'last') { this.#said.set(email, 'last'); this.#tell(`${n} failed sign-ins as ${email}`, 'It is the last operator: not locked out. Change its password if this was not you.'); }
96
+ continue;
97
+ }
98
+ const until = new Date(now + LOCK_MIN * 60_000).toISOString();
99
+ await this.#do(['operator', 'disable', email]).then(() => { locks[email] = { until, fails: Number(n) }; this.#tell(`${email} is locked for ${LOCK_MIN} minutes`, `${n} failed sign-ins in ${WINDOW_MIN} minutes. Enabled again by itself after; or now, from Settings.`); }).catch(() => {});
100
+ }
101
+ }
102
+ this.#store.put({ name: 'locks', ...locks });
103
+ }
104
+ /* Made before the alerts are: given them once they are. */
105
+ useAlerts(alerts) { this.#alerts = alerts; }
106
+ #tell(title, body) { if (this.#alerts) void this.#alerts.tell({ title, body, url: '/?open=settings&at=operators' })?.catch?.(() => {}); }
107
+ }
package/server/vm.mjs CHANGED
@@ -124,6 +124,7 @@ export class Vms {
124
124
  kill(conversation) { return this.run(['vm', 'kill', vmName(conversation)], { timeoutMs: 300_000 }); }
125
125
  /* Memory in megabytes, disk in gigabytes: only on a stopped machine. */
126
126
  setMemory(conversation, mb) { return this.run(['vm', 'set', vmName(conversation), 'memory', String(mb)], { timeoutMs: 120_000 }); }
127
+ setCpus(conversation, n) { return this.run(['vm', 'set', vmName(conversation), 'cpus', String(n)], { timeoutMs: 120_000 }); }
127
128
  setDisk(conversation, gb) { return this.run(['vm', 'set', vmName(conversation), 'disk', String(gb)], { timeoutMs: 600_000 }); }
128
129
  /* What the machine really has: { memoryMb, diskGb }, each undefined when it cannot be told. */
129
130
  async size(conversation) {
@@ -132,7 +133,8 @@ export class Vms {
132
133
  const line = (key) => new RegExp(`^${key} (\\S+)$`, 'm').exec(r.stdout ?? '')?.[1];
133
134
  const mb = megabytes(line('memory'));
134
135
  const disk = megabytes(line('disk'));
135
- return { memoryMb: mb === undefined ? undefined : Math.round(mb), diskGb: disk === undefined ? undefined : Math.round(disk / 1024) };
136
+ const cpus = /^\d{1,3}$/.test(line('cpus') ?? '') ? Number(line('cpus')) : undefined;
137
+ return { memoryMb: mb === undefined ? undefined : Math.round(mb), diskGb: disk === undefined ? undefined : Math.round(disk / 1024), cpus };
136
138
  }
137
139
  suspend(conversation) { return this.run(['vm', 'suspend', vmName(conversation)], { timeoutMs: 300_000 }); }
138
140
  remove(conversation) { return this.run(['vm', 'delete', vmName(conversation)], { timeoutMs: 300_000 }); }
@@ -258,9 +258,16 @@ export class Wakeups {
258
258
  see gitkeeper.mjs), typed as a wake-up is: only into a conversation
259
259
  that is awake, cleaned the same way. Not counted in the owner's cap:
260
260
  the server says each such line once. */
261
+ /* One line at a time into a terminal: two said at once were typed into each other, then sent
262
+ as one (two repositories moving together, seen 20-10). */
263
+ #queue = new Map();
261
264
  async say(name, text) {
262
265
  if (!this.#conversations.awake().includes(name)) return false;
263
- return this.#type(name, cleanMessage(text)).catch(() => false);
266
+ const before = this.#queue.get(name) ?? Promise.resolve();
267
+ const mine = before.then(() => this.#type(name, cleanMessage(text)).catch(() => false));
268
+ this.#queue.set(name, mine);
269
+ void mine.finally(() => { if (this.#queue.get(name) === mine) this.#queue.delete(name); });
270
+ return mine;
264
271
  }
265
272
 
266
273
  /* The address was called. Resolves with 'typed', 'capped', 'asleep',
package/web/app.js CHANGED
@@ -1779,7 +1779,24 @@
1779
1779
  });
1780
1780
  const MEMORY_CHOICES = [768, 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384];
1781
1781
  const DISK_CHOICES = [8, 10, 16, 20, 32, 48, 64, 96, 128, 192, 256];
1782
+ /* WHEN ITS MACHINE IS SHORT: its agent told (a line you can change), or a command run when it has no agent. */
1783
+ async function paintReact(here) {
1784
+ if (!here || DEVICE) return;
1785
+ const s = await fetch(`${API}/conversations/${encodeURIComponent(here.name)}/health-react`).then((r) => (r.ok ? r.json() : null)).catch(() => null);
1786
+ if (!s) return;
1787
+ $('react-on').checked = s.on;
1788
+ $('react-on-label').textContent = s.agent ? 'Also tell its agent' : 'Also run a command in its machine';
1789
+ $('react-message').hidden = !s.agent; $('react-command').hidden = s.agent;
1790
+ $('react-message').value = s.message; $('react-command').value = s.command;
1791
+ $('react-said').textContent = '';
1792
+ }
1793
+ $('react-box').addEventListener('submit', async (event) => {
1794
+ event.preventDefault();
1795
+ try { await post(`${API}/conversations/${encodeURIComponent(current)}/health-react`, { on: $('react-on').checked, message: $('react-message').value, command: $('react-command').value }); $('react-said').textContent = 'Saved.'; }
1796
+ catch (error) { $('react-said').textContent = error.message; }
1797
+ });
1782
1798
  function paintMachine(here) {
1799
+ void paintReact(here);
1783
1800
  /* General: what it is. */
1784
1801
  const facts = $('general-facts'); facts.replaceChildren();
1785
1802
  const fact = (term, value) => { const dt = document.createElement('dt'); dt.textContent = term; const dd = document.createElement('dd'); dd.textContent = value; facts.append(dt, dd); };
@@ -1793,9 +1810,13 @@
1793
1810
  healthLines($('machine-health'), here?.health ?? null);
1794
1811
  $('machine-restarted').textContent = here?.restarted ?? ''; $('machine-restarted').hidden = !here?.restarted;
1795
1812
  /* The choices are not painted over while somebody is choosing. */
1796
- const memory = $('machine-memory'); const disk = $('machine-disk');
1797
- const of = `${here?.name}/${here?.memoryMb}/${here?.diskGb}/${here?.memoryMinMb}`;
1798
- if (here && memory.dataset.of !== of && document.activeElement !== memory && document.activeElement !== disk) {
1813
+ const memory = $('machine-memory'); const disk = $('machine-disk'); const cores = $('machine-cpus');
1814
+ const of = `${here?.name}/${here?.memoryMb}/${here?.diskGb}/${here?.memoryMinMb}/${here?.cpus}`;
1815
+ if (here && memory.dataset.of !== of && document.activeElement !== memory && document.activeElement !== disk && document.activeElement !== cores) {
1816
+ /* Cores: 1 to those of the server, which its machines share. */
1817
+ const most = Math.max(here.hostCpus ?? 1, here.cpus ?? 1);
1818
+ cores.replaceChildren(...Array.from({ length: most }, (_, i) => i + 1).map((n) => { const o = document.createElement('option'); o.value = String(n); o.textContent = `${n}${n === (here.cpus ?? 1) ? ' (now)' : ''}${n === most && n > 1 ? ' (all of this server)' : ''}`; return o; }));
1819
+ cores.value = String(here.cpus ?? 1);
1799
1820
  const least = here.memoryMinMb ?? 512;
1800
1821
  const mems = [...new Set([...MEMORY_CHOICES.filter((m) => m >= least), here.memoryMb])].sort((a, b) => a - b);
1801
1822
  memory.replaceChildren(...mems.map((m) => { const o = document.createElement('option'); o.value = String(m); o.textContent = `${sizeWords(m)}${m === here.memoryMb ? ' (now)' : ''}${m === least ? ' (least for its tool)' : ''}`; return o; }));
@@ -1809,7 +1830,7 @@
1809
1830
  /* Not ready (built, restarted, moved): its sizes are shown, and chosen once it is. */
1810
1831
  $('machine-size').hidden = DEVICE || !here || here.phase === 'failed';
1811
1832
  const waiting = here && (here.phase !== 'ready' || holds(here)) ? (here.phase === 'moving' ? 'Available once it has moved.' : here.phase === 'restarting' || (here.phase === 'ready' && here.progress?.kind !== 'build') ? 'Available once it has restarted.' : 'Available once its machine is built.') : '';
1812
- for (const id of ['machine-memory', 'machine-disk', 'machine-size-apply']) $(id).disabled = Boolean(waiting);
1833
+ for (const id of ['machine-memory', 'machine-cpus', 'machine-disk', 'machine-size-apply']) $(id).disabled = Boolean(waiting);
1813
1834
  $('machine-size').toggleAttribute('data-waiting', Boolean(waiting));
1814
1835
  $('machine-size-wait').textContent = waiting; $('machine-size-wait').hidden = !waiting;
1815
1836
  /* When its tool starts: its last session, or a new one -- for a tool that can take one up. */
@@ -1838,15 +1859,15 @@
1838
1859
  const name = current;
1839
1860
  const here = conversations.find((x) => x.name === name);
1840
1861
  if (!here) return;
1841
- const memoryMb = Number($('machine-memory').value); const diskGb = Number($('machine-disk').value);
1842
- if (memoryMb === here.memoryMb && diskGb === (here.diskGb ?? 8)) { $('panel-error').textContent = 'Nothing to change: choose another memory or disk first.'; $('panel-error').hidden = false; return; }
1862
+ const memoryMb = Number($('machine-memory').value); const diskGb = Number($('machine-disk').value); const cpus = Number($('machine-cpus').value) || (here.cpus ?? 1);
1863
+ if (memoryMb === here.memoryMb && diskGb === (here.diskGb ?? 8) && cpus === (here.cpus ?? 1)) { $('panel-error').textContent = 'Nothing to change: choose another memory, cores or disk first.'; $('panel-error').hidden = false; return; }
1843
1864
  leavePanel();
1844
1865
  const resume = socket && state.dataset.state === 'live' ? () => { notice.hidden = true; focusTerminal(); } : enter;
1845
- const changes = [memoryMb !== here.memoryMb ? `${sizeWords(memoryMb)} of memory (now ${sizeWords(here.memoryMb)})` : '', diskGb !== (here.diskGb ?? 8) ? `a disk of ${diskGb} GB (now ${here.diskGb ?? 8} GB; it can never shrink again)` : ''].filter(Boolean).join(' and ');
1866
+ const changes = [memoryMb !== here.memoryMb ? `${sizeWords(memoryMb)} of memory (now ${sizeWords(here.memoryMb)})` : '', cpus !== (here.cpus ?? 1) ? `${cpus} core${cpus > 1 ? 's' : ''} (now ${here.cpus ?? 1})` : '', diskGb !== (here.diskGb ?? 8) ? `a disk of ${diskGb} GB (now ${here.diskGb ?? 8} GB; it can never shrink again)` : ''].filter(Boolean).join(' and ');
1846
1867
  show(`Give "${name}" ${changes}? ITS MACHINE IS STOPPED CLEANLY, SET, AND STARTED AGAIN: what the tool is doing now is interrupted. Its work folder, its folders and its branches stay.`,
1847
1868
  'Change it', async () => {
1848
1869
  disconnect(); say('restarting', 'connecting'); show('Changing its machine...'); $('notice-spin').hidden = false;
1849
- try { await post(`${API}/conversations/${encodeURIComponent(name)}/machine`, { memoryMb, diskGb }); await refresh(); enter(); }
1870
+ try { await post(`${API}/conversations/${encodeURIComponent(name)}/machine`, { memoryMb, diskGb, cpus }); await refresh(); enter(); }
1850
1871
  catch (error) { show(error.message, 'Back', enter); }
1851
1872
  }, resume);
1852
1873
  });
@@ -3188,6 +3209,41 @@
3188
3209
  $('access-devices-here').addEventListener('click', () => { void openAccessPage('map', { of: current }); });
3189
3210
 
3190
3211
  /* ---------- Settings: this device, and the platform ---------- */
3212
+ /* ADMINISTRATORS: who may sign in (server/operators.mjs); a password is shown once, then never again. */
3213
+ async function paintOperators() {
3214
+ const got = await fetch(`${API}/operators`).then((r) => (r.ok ? r.json() : null)).catch(() => null);
3215
+ $('settings-ch-operators').hidden = !got || got.local === true;
3216
+ if (!got || got.local) return;
3217
+ const rows = $('operators-rows'); rows.replaceChildren();
3218
+ const act = async (path) => {
3219
+ $('operators-error').hidden = true;
3220
+ try { const r = await post(`${API}/operators/${encodeURIComponent(path[0])}/${path[1]}`, {}); if (r?.password) showPassword(r.email, r.password); }
3221
+ catch (error) { $('operators-error').textContent = error.message; $('operators-error').hidden = false; }
3222
+ await paintOperators();
3223
+ };
3224
+ for (const o of got.operators) {
3225
+ const row = el('div', 'folder'); row.dataset.email = o.email;
3226
+ const name = el('b', '', o.email);
3227
+ const state = el('small', 'hint', o.locked ? ` locked until ${new Date(o.locked).toLocaleTimeString([], { timeStyle: 'short' })}` : o.enabled ? (o.email === got.me ? ' you' : '') : ' disabled');
3228
+ name.append(state);
3229
+ const buttons = [['password', 'New password']];
3230
+ if (o.email !== got.me) buttons.push(o.enabled ? ['disable', 'Disable'] : ['enable', 'Enable'], ['remove', 'Remove']);
3231
+ row.append(name, ...buttons.map(([verb, label]) => { const b = el('button', verb === 'remove' ? 'danger' : '', label); b.type = 'button'; b.dataset.act = verb; b.addEventListener('click', () => void act([o.email, verb])); return b; }));
3232
+ rows.append(row);
3233
+ }
3234
+ }
3235
+ function showPassword(email, password) {
3236
+ $('operators-password-for').textContent = email; $('operators-password-value').value = password; $('operators-password').hidden = false;
3237
+ }
3238
+ $('operators-password-copy').addEventListener('click', () => { void copyField($('operators-password-value'), $('operators-password-copy')); });
3239
+ $('operators-password-done').addEventListener('click', () => { $('operators-password-value').value = ''; $('operators-password').hidden = true; });
3240
+ $('operators-new').addEventListener('submit', async (event) => {
3241
+ event.preventDefault();
3242
+ $('operators-error').hidden = true;
3243
+ try { const r = await post(`${API}/operators`, { email: $('operators-email').value.trim() }); showPassword(r.email, r.password); $('operators-email').value = ''; }
3244
+ catch (error) { $('operators-error').textContent = error.message; $('operators-error').hidden = false; }
3245
+ await paintOperators();
3246
+ });
3191
3247
  async function openSettings({ push = true } = {}) {
3192
3248
  enterPlace('settings', push);
3193
3249
  void paintAlerts().catch(() => {});
@@ -3204,10 +3260,11 @@
3204
3260
  row.append(label, remove); list.append(row);
3205
3261
  }
3206
3262
  void paintDictation();
3263
+ void paintOperators();
3207
3264
  /* With no shortcut, one line: how to add one (this is the only place to remove them). */
3208
3265
  $('settings-shortcuts-hint').textContent = saved.length ? 'The ready-made answers under the terminal. They are added there ("+ Shortcut"); they are removed here.' : 'No shortcut yet: add one under the terminal, with "+ Shortcut".';
3209
3266
  $('settings-people').textContent = (platform.operators ?? []).length
3210
- ? `Who may sign in: ${platform.operators.join(', ')} (set when this was installed).`
3267
+ ? `Who may sign in: ${platform.operators.join(', ')} (Settings, Administrators).`
3211
3268
  : 'Development mode: anyone on this machine is the operator.';
3212
3269
  $('settings-address').textContent = `Address: ${platform.address ?? 'not declared'}.`;
3213
3270
  $('settings-about').textContent = `Clavarium ${platform.version ?? ''}`;
@@ -3510,6 +3567,9 @@
3510
3567
  rows.push(['Machines', sum(each)], ...each);
3511
3568
  if (m.othersMb) rows.push(['Other machines', m.othersMb]);
3512
3569
  }
3570
+ /* WHERE EACH WORK FOLDER IS: kept with the shared folders, or on its machine's own disk. */
3571
+ const here = conversations.filter((x) => (x.work === 'disk' ? machines : d.holds.includes('folders'))).map((x) => x.title || x.name);
3572
+ if (here.length) rows.push(['Work folders on this disk', here.length > 6 ? `${here.slice(0, 6).join(', ')} and ${here.length - 6} more` : here.join(', ')]);
3513
3573
  const known = sum(rows.filter(([, , sub]) => !sub));
3514
3574
  const rest = d.sizeMb - d.freeMb - known;
3515
3575
  if (rest > 50) rows.push(['The system and other programs', rest]);
@@ -3519,6 +3579,26 @@
3519
3579
  box.append(block);
3520
3580
  }
3521
3581
  }
3582
+ /* ALL THE MACHINES TO ANOTHER DISK: the disks they may go to, those they may not and why; then how it went. */
3583
+ async function paintMoveMachines() {
3584
+ const [p, m] = await Promise.all([fetch(`${API}/machines/places`).then((r) => (r.ok ? r.json() : null)).catch(() => null), fetch(`${API}/machines/moving`).then((r) => (r.ok ? r.json() : null)).catch(() => null)]);
3585
+ const rows = $('move-machines-rows'); rows.replaceChildren();
3586
+ if (m?.said?.length) $('move-machines-said').textContent = m.done ? `The last move: ${m.said.find((l) => l.startsWith('Done:'))}` : m.failed ? `The last move did not happen: ${m.said.filter(Boolean).at(-1)}` : m.state === 'active' ? `Moving: ${m.said.at(-1)}` : '';
3587
+ if (!p) return;
3588
+ if (!p.places.length) rows.append(el('p', 'hint', 'No other disk is mounted under /mnt or /media: the VM manager can only keep its machines there (or under /home).'));
3589
+ for (const x of p.places) {
3590
+ const row = el('div', 'folder');
3591
+ row.append(el('b', '', x.at), el('small', 'hint', ` ${Math.round(x.freeMb / 1024)} GB free of ${Math.round(x.sizeMb / 1024)} GB${x.why ? ` -- ${x.why}` : ''}`));
3592
+ const go = el('button', 'danger', 'Move them here...'); go.type = 'button'; go.disabled = Boolean(x.why);
3593
+ go.addEventListener('click', () => {
3594
+ if (go.dataset.sure !== 'yes') { go.dataset.sure = 'yes'; go.textContent = `Yes: stop every machine and this server, and move them to ${x.at}`; return; }
3595
+ go.disabled = true;
3596
+ void post(`${API}/machines/move`, { to: x.at }).then(() => { $('move-machines-said').textContent = 'Moving: this server stops now, and comes back by itself. Reload this page in a few minutes.'; }).catch((error) => { $('move-machines-said').textContent = error.message; go.disabled = false; });
3597
+ });
3598
+ row.append(go); rows.append(row);
3599
+ }
3600
+ }
3601
+ $('move-machines-box').addEventListener('toggle', () => { if ($('move-machines-box').open) void paintMoveMachines(); });
3522
3602
  async function paintServer() {
3523
3603
  clearTimeout(serverTimer);
3524
3604
  const r = await fetch(`${API}/server`).then((x) => (x.ok ? x.json() : null)).catch(() => null);
package/web/index.html CHANGED
@@ -191,10 +191,12 @@
191
191
  <div class="row"><div class="levels" id="ask-first" role="group" aria-label="Ask before acting"><button type="button" data-on="false">Off</button><button type="button" data-on="true">On</button></div></div>
192
192
  <p class="hint" id="rights-hint">Off (the default): <b>the tool acts without asking you</b>, with every right inside its own machine: it installs, changes and deletes there as it sees fit. Outside its machine it reaches only what you attached to it, as you attached it. On: it asks you before it acts, as it does by itself. Taken into account the next time the tool starts: restart the machine to apply it now.</p>
193
193
  </div>
194
- <div class="panel-top"><b>Memory and disk</b></div>
194
+ <div class="panel-top"><b>Memory, cores and disk</b></div>
195
195
  <form id="machine-size" autocomplete="off">
196
196
  <label for="machine-memory">Memory</label>
197
197
  <select id="machine-memory"></select>
198
+ <label for="machine-cpus">Cores</label>
199
+ <select id="machine-cpus"></select>
198
200
  <label for="machine-disk">Disk</label>
199
201
  <select id="machine-disk"></select>
200
202
  <p class="hint" id="machine-size-wait" role="status" hidden></p>
@@ -207,6 +209,15 @@
207
209
  <p id="work-moved" class="hint" hidden></p>
208
210
  <button type="button" id="work-move"></button>
209
211
  </div>
212
+ <!-- WHEN ITS MACHINE IS SHORT (server/healthreact.mjs): you are told either way. -->
213
+ <form id="react-box" autocomplete="off">
214
+ <div class="panel-top"><b>When its machine is short of room or memory</b></div>
215
+ <label class="check"><input type="checkbox" id="react-on"> <span id="react-on-label">Also tell its agent</span></label>
216
+ <input id="react-message" maxlength="500" spellcheck="false" aria-label="What its agent is told ({problem}: what was found)">
217
+ <input id="react-command" maxlength="500" spellcheck="false" placeholder="a command, run in its machine: rm -rf ~/.cache/*" aria-label="The command run in its machine" hidden>
218
+ <p class="hint" id="react-hint">You are told either way. Once each time it happens; what was said or run shows in its chat.</p>
219
+ <div class="row"><button type="submit">Save</button><span class="hint" id="react-said" role="status"></span></div>
220
+ </form>
210
221
  </div>
211
222
  </details>
212
223
  <details class="chapter" id="chapter-access" data-chapter="access">
@@ -570,6 +581,17 @@
570
581
  <p class="error" id="instance-error" role="alert" hidden></p>
571
582
  </div>
572
583
  </details>
584
+ <!-- WHO MAY SIGN IN (server/operators.mjs): hidden on this machine alone. -->
585
+ <details class="chapter" id="settings-ch-operators" data-chapter="s-operators" hidden>
586
+ <summary><span class="chapter-title">Administrators</span><span class="chapter-about">Who may sign in, and their passwords.</span></summary>
587
+ <div class="chapter-body">
588
+ <div id="operators-rows"></div>
589
+ <form id="operators-new" class="row" autocomplete="off"><label for="operators-email">Add an administrator</label><input id="operators-email" type="email" placeholder="someone@example.com" spellcheck="false" autocapitalize="off" required><button type="submit">Add</button></form>
590
+ <div id="operators-password" class="as-form" hidden><p><b id="operators-password-for"></b>: its password, shown <b>this once</b>. Give it to them yourself.</p><div class="row"><input id="operators-password-value" readonly spellcheck="false"><button type="button" id="operators-password-copy">Copy</button><button type="button" id="operators-password-done">Done</button></div></div>
591
+ <p class="hint">Five failed sign-ins within 15 minutes lock that address for 15 minutes; you are told. The last administrator is never locked out nor removed.</p>
592
+ <p class="error" id="operators-error" role="alert" hidden></p>
593
+ </div>
594
+ </details>
573
595
  <details class="chapter" id="settings-ch-shortcuts" data-chapter="s-shortcuts">
574
596
  <summary><span class="chapter-title">Shortcuts</span><span class="chapter-about">The ready-made answers under the terminal.</span></summary>
575
597
  <div class="chapter-body">
@@ -628,6 +650,13 @@
628
650
  <div id="settings-server" tabindex="-1">
629
651
  <p id="server-unknown" class="hint" hidden>This server's disk and memory cannot be read just now. Nothing is refused for lack of room while they cannot.</p>
630
652
  <div id="server-disks"></div>
653
+ <!-- ALL THE MACHINES TO ANOTHER DISK (server/machinesmove.mjs). -->
654
+ <details id="move-machines-box">
655
+ <summary>Move all the machines to another disk...</summary>
656
+ <p class="hint">Every machine is stopped, its disk copied to the disk you choose, and started again as its conversation is opened. <b>This server stops meanwhile</b>: this page comes back by itself. It takes from a few minutes to much longer, with the size of the machines. The copy on the disk of now is kept until you remove it.</p>
657
+ <div id="move-machines-rows"></div>
658
+ <p class="hint" id="move-machines-said" role="status"></p>
659
+ </details>
631
660
  <div class="server-block" id="server-memory" hidden>
632
661
  <div class="server-head"><b>Memory</b><span id="server-memory-state" class="server-state"></span><span id="server-memory-figures" class="server-figures"></span></div>
633
662
  <div class="server-meter" id="server-memory-meter" role="meter" aria-label="Memory taken" aria-valuemin="0" aria-valuemax="100"><span class="fill"></span><span class="zone"></span><span class="mark"></span></div>