clavarium 0.2.487-next.1 → 0.2.488-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/config/machine/clavarium-beat +44 -0
- package/config/machine/clavarium-beat-one +40 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/server/beat.mjs +189 -0
- package/server/copywork.mjs +3 -2
- package/server/health.mjs +39 -8
- package/server/main.mjs +7 -1
- package/server/vm.mjs +6 -3
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
#!/bin/sh
|
|
2
|
+
# THE HEARTBEAT OF A MACHINE (step 6), run as root by its timer (clavarium-beat.timer, every minute or so):
|
|
3
|
+
# for the conversation of a machine of its own, or for each conversation living in a shared one, the look its
|
|
4
|
+
# server made by a command every two minutes (health.mjs, PROBE) is made here, as that conversation's own user,
|
|
5
|
+
# and written into its /work (beat-one). Its server reads it from its own side: no command into the machine.
|
|
6
|
+
#
|
|
7
|
+
# Root reads nothing that a conversation wrote: only its own settings (beat.conf, written at install) and its
|
|
8
|
+
# own counters (/var/lib/clavarium/beat). Each conversation is given a bounded time; a dead /work only stops
|
|
9
|
+
# its beat, and its server then looks the usual way.
|
|
10
|
+
set -u
|
|
11
|
+
lib=/usr/local/lib/clavarium
|
|
12
|
+
state=/var/lib/clavarium/beat
|
|
13
|
+
mode=""; conversation=""; version=""
|
|
14
|
+
[ -r "$lib/beat.conf" ] || exit 0
|
|
15
|
+
while IFS='=' read -r k v; do
|
|
16
|
+
case "$k" in mode) mode=$v ;; conversation) conversation=$v ;; version) version=$v ;; esac
|
|
17
|
+
done < "$lib/beat.conf"
|
|
18
|
+
printf '%s' "$version" | grep -Eq '^[0-9A-Za-z.+-]{1,64}$' || exit 0
|
|
19
|
+
ok_name() { printf '%s' "$1" | grep -Eq '^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$'; }
|
|
20
|
+
mkdir -p "$state"; chmod 700 "$state"
|
|
21
|
+
# Its next number: a beat that does not grow is not a new one (read by its server).
|
|
22
|
+
next() {
|
|
23
|
+
n=$(head -c 20 "$state/$1.seq" 2>/dev/null) || n=0
|
|
24
|
+
case "$n" in ''|*[!0-9]*) n=0 ;; esac
|
|
25
|
+
n=$((n + 1)); printf '%s\n' "$n" > "$state/$1.seq"; printf '%s' "$n"
|
|
26
|
+
}
|
|
27
|
+
case "$mode" in
|
|
28
|
+
own)
|
|
29
|
+
ok_name "$conversation" || exit 0
|
|
30
|
+
n=$(next "$conversation")
|
|
31
|
+
cd / && timeout -k 5 45 runuser -u ubuntu -- env HOME=/home/ubuntu sh "$lib/beat-one" "$conversation" "$n" "$version" </dev/null >/dev/null 2>&1 || true ;;
|
|
32
|
+
shared)
|
|
33
|
+
# Only a conversation whose work is shown here now (the host mounts it at /srv/clavarium/NAME/work);
|
|
34
|
+
# at most 64 of them, one after another.
|
|
35
|
+
i=0
|
|
36
|
+
for d in /srv/clavarium/*/; do
|
|
37
|
+
[ "$i" -lt 64 ] || break
|
|
38
|
+
c=$(basename "$d"); ok_name "$c" || continue
|
|
39
|
+
mountpoint -q "/srv/clavarium/$c/work" 2>/dev/null || continue
|
|
40
|
+
i=$((i + 1)); n=$(next "$c")
|
|
41
|
+
timeout -k 5 45 /usr/local/sbin/clavarium-enter "$c" -- sh "$lib/beat-one" "$c" "$n" "$version" </dev/null >/dev/null 2>&1 || true
|
|
42
|
+
done ;;
|
|
43
|
+
esac
|
|
44
|
+
exit 0
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
#!/bin/sh
|
|
2
|
+
# ONE BEAT OF ONE CONVERSATION, as its own user (ubuntu in a machine of its own, c-NAME behind its door):
|
|
3
|
+
# beat-one NAME SEQ VERSION
|
|
4
|
+
# Runs its server's look (probe.sh, exactly PROBE of health.mjs) with the paths its server expects mounted
|
|
5
|
+
# (/work/.clavarium/expected, written by the server), and writes what it printed, as JSON, to
|
|
6
|
+
# /work/.clavarium/beat.json -- whole or not at all (a file aside, then moved). Its server checks every word
|
|
7
|
+
# of it: the agent is root here, and may write anything there.
|
|
8
|
+
# CLAVARIUM_BEAT_WORK, CLAVARIUM_BEAT_LIB: other places, for its tests only.
|
|
9
|
+
set -u
|
|
10
|
+
name="$1"; seq="$2"; version="$3"
|
|
11
|
+
work="${CLAVARIUM_BEAT_WORK:-/work}"
|
|
12
|
+
lib="${CLAVARIUM_BEAT_LIB:-/usr/local/lib/clavarium}"
|
|
13
|
+
dir="$work/.clavarium"
|
|
14
|
+
[ -d "$work" ] || exit 0
|
|
15
|
+
# A link there is not followed: the agent may have put it.
|
|
16
|
+
[ -L "$dir" ] && exit 0
|
|
17
|
+
mkdir -p "$dir" 2>/dev/null || exit 0
|
|
18
|
+
set --
|
|
19
|
+
if [ -f "$dir/expected" ] && [ ! -L "$dir/expected" ]; then
|
|
20
|
+
n=0
|
|
21
|
+
while IFS= read -r p; do
|
|
22
|
+
[ "$n" -lt 100 ] || break
|
|
23
|
+
printf '%s' "$p" | grep -Eq '^/[A-Za-z0-9._/-]{1,200}$' || continue
|
|
24
|
+
set -- "$@" "$p"; n=$((n + 1))
|
|
25
|
+
done < "$dir/expected"
|
|
26
|
+
fi
|
|
27
|
+
out=$(timeout -k 2 30 sh "$lib/probe.sh" "$@" 2>/dev/null | head -c 12000)
|
|
28
|
+
# Its text as a JSON string: backslash and quote escaped, a tab written \t, lines joined by \n, any other
|
|
29
|
+
# control character left out. Character by character: every awk reads it the same way.
|
|
30
|
+
probe=$(printf '%s\n' "$out" | awk 'BEGIN { for (i = 1; i < 32; i++) drop[sprintf("%c", i)] = 1 }
|
|
31
|
+
{ s = ""; n = length($0)
|
|
32
|
+
for (i = 1; i <= n; i++) { c = substr($0, i, 1)
|
|
33
|
+
if (c == "\\") s = s "\\\\"; else if (c == "\"") s = s "\\\""; else if (c == "\t") s = s "\\t"; else if (!(c in drop)) s = s c }
|
|
34
|
+
all = all (NR > 1 ? "\\n" : "") s }
|
|
35
|
+
END { printf "%s", all }')
|
|
36
|
+
tmp="$dir/.beat.$$"
|
|
37
|
+
printf '{"v":1,"conversation":"%s","seq":%s,"version":"%s","probe":"%s"}\n' "$name" "$seq" "$version" "$probe" > "$tmp" || { rm -f "$tmp"; exit 0; }
|
|
38
|
+
# A share that does not replace a file by a rename: the old one taken away first.
|
|
39
|
+
mv -f "$tmp" "$dir/beat.json" 2>/dev/null || { rm -f "$dir/beat.json"; mv -f "$tmp" "$dir/beat.json"; } || rm -f "$tmp"
|
|
40
|
+
exit 0
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.488-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.488-next.1",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@xterm/addon-fit": "^0.11.0",
|
package/package.json
CHANGED
package/server/beat.mjs
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
/* THE HEARTBEAT OF A MACHINE (step 6, phase 1): its health looked at from inside it, read from here.
|
|
2
|
+
*
|
|
3
|
+
* Every two minutes, each conversation's health was one command into its machine (health.mjs, PROBE): one
|
|
4
|
+
* more line at the VM manager, in front of every other command. Now a timer in the machine (root's,
|
|
5
|
+
* config/machine/clavarium-beat) runs that same probe every minute, as the conversation's own user, and
|
|
6
|
+
* writes what it printed into its work folder, /work/.clavarium/beat.json. The work folder is a folder of
|
|
7
|
+
* THIS server: the beat is read here, as a file (read), with no command at all.
|
|
8
|
+
*
|
|
9
|
+
* WHAT IS IN IT IS THE AGENT'S: it is root in its machine and may write anything there. So the folder must
|
|
10
|
+
* be a folder (never a link), the file a plain file of a few kilobytes, opened without following a link and
|
|
11
|
+
* without waiting (a pipe put there); its words checked one by one; its conversation the one whose folder it
|
|
12
|
+
* is; its age taken from THIS server's clock (the file's time here), never from what it says; its number
|
|
13
|
+
* growing. Nothing in it is ever run: its probe text is read by readProbe, as the probe's output always was.
|
|
14
|
+
*
|
|
15
|
+
* Put in a machine once (ensure): one command at its start or opening, skipped when a fresh beat already
|
|
16
|
+
* says this version. Only with CLAVARIUM_BEAT holding `health` (main.mjs): off, nothing here is used.
|
|
17
|
+
*/
|
|
18
|
+
import { lstatSync, openSync, fstatSync, readSync, closeSync, constants, writeFileSync, renameSync, rmSync, mkdirSync, readFileSync } from 'node:fs';
|
|
19
|
+
import { join } from 'node:path';
|
|
20
|
+
import { randomBytes } from 'node:crypto';
|
|
21
|
+
import { PROBE } from './health.mjs';
|
|
22
|
+
|
|
23
|
+
export const FOLDER = '.clavarium';
|
|
24
|
+
export const BEAT_FILE = 'beat.json';
|
|
25
|
+
export const EXPECTED_FILE = 'expected';
|
|
26
|
+
/* At most this big: a probe of 64 secrets' names is a few kilobytes. */
|
|
27
|
+
export const BEAT_BYTES = 16 * 1024;
|
|
28
|
+
/* Older than this (by this server's clock), it says nothing: its timer beats every minute or so. */
|
|
29
|
+
export const FRESH_MS = 180_000;
|
|
30
|
+
/* A file's time a little ahead of this server's clock is still now (a share's rounding); more is not believed. */
|
|
31
|
+
const AHEAD_MS = 10_000;
|
|
32
|
+
/* Where it is put in the machine (root's, never under /tools or /work). */
|
|
33
|
+
export const LIB = '/usr/local/lib/clavarium';
|
|
34
|
+
export const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
35
|
+
const INSTALL_MS = 90_000;
|
|
36
|
+
const NAME = /^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$/;
|
|
37
|
+
const VERSION_WORD = /^[0-9A-Za-z.+-]{1,64}$/;
|
|
38
|
+
|
|
39
|
+
/* Whether CLAVARIUM_BEAT asks for it (`health`; other words for the later phases). */
|
|
40
|
+
export const beatWanted = (value, what = 'health') => String(value ?? '').split(/[\s,]+/).includes(what);
|
|
41
|
+
|
|
42
|
+
const RUNNER = new URL('../config/machine/clavarium-beat', import.meta.url);
|
|
43
|
+
const ONE = new URL('../config/machine/clavarium-beat-one', import.meta.url);
|
|
44
|
+
export const SERVICE = `[Unit]
|
|
45
|
+
Description=Clavarium heartbeat: its health, for its server
|
|
46
|
+
[Service]
|
|
47
|
+
Type=oneshot
|
|
48
|
+
ExecStart=/bin/sh ${LIB}/beat-all
|
|
49
|
+
TimeoutStartSec=300
|
|
50
|
+
Nice=10
|
|
51
|
+
`;
|
|
52
|
+
export const TIMER = `[Unit]
|
|
53
|
+
Description=Clavarium heartbeat, every minute
|
|
54
|
+
[Timer]
|
|
55
|
+
OnBootSec=20s
|
|
56
|
+
OnUnitActiveSec=60s
|
|
57
|
+
RandomizedDelaySec=10s
|
|
58
|
+
AccuracySec=5s
|
|
59
|
+
[Install]
|
|
60
|
+
WantedBy=timers.target
|
|
61
|
+
`;
|
|
62
|
+
|
|
63
|
+
/* THE ONE COMMAND THAT PUTS IT IN A MACHINE, as root: its scripts and the probe in LIB, its settings, its
|
|
64
|
+
service and timer, started. Its arguments (mode, conversation, version) are checked again there. Each file
|
|
65
|
+
is written aside, then moved: a beat that runs meanwhile finds the old or the new, never half of one. */
|
|
66
|
+
const EOF = 'CLAVARIUM_BEAT_EOF';
|
|
67
|
+
function here(text) {
|
|
68
|
+
if (String(text).split('\n').includes(EOF)) throw new Error('a file of the beat holds its own end mark');
|
|
69
|
+
return `<<'${EOF}'\n${String(text).replace(/\n?$/, '\n')}${EOF}\n`;
|
|
70
|
+
}
|
|
71
|
+
export function installScript() {
|
|
72
|
+
return [
|
|
73
|
+
'set -eu',
|
|
74
|
+
'mode="$1"; name="$2"; version="$3"',
|
|
75
|
+
'case "$mode" in own) printf \'%s\' "$name" | grep -Eq \'^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$\' || exit 64 ;; shared) name=- ;; *) exit 64 ;; esac',
|
|
76
|
+
'printf \'%s\' "$version" | grep -Eq \'^[0-9A-Za-z.+-]{1,64}$\' || exit 64',
|
|
77
|
+
`lib=${LIB}`,
|
|
78
|
+
'mkdir -p "$lib"; chown root:root "$lib"; chmod 755 "$lib"',
|
|
79
|
+
'put() { tmp="$lib/.$1.$$"; cat > "$tmp"; chmod "$2" "$tmp"; mv -f "$tmp" "$lib/$1"; }',
|
|
80
|
+
`put probe.sh 0644 ${here(PROBE)}`,
|
|
81
|
+
`put beat-one 0755 ${here(readFileSync(ONE, 'utf8'))}`,
|
|
82
|
+
`put beat-all 0755 ${here(readFileSync(RUNNER, 'utf8'))}`,
|
|
83
|
+
'printf \'mode=%s\\nconversation=%s\\nversion=%s\\n\' "$mode" "$name" "$version" | put beat.conf 0644',
|
|
84
|
+
`cat > /etc/systemd/system/clavarium-beat.service ${here(SERVICE)}`,
|
|
85
|
+
`cat > /etc/systemd/system/clavarium-beat.timer ${here(TIMER)}`,
|
|
86
|
+
'systemctl daemon-reload',
|
|
87
|
+
'systemctl enable --now clavarium-beat.timer >/dev/null 2>&1',
|
|
88
|
+
'systemctl start --no-block clavarium-beat.service',
|
|
89
|
+
].join('\n');
|
|
90
|
+
}
|
|
91
|
+
export const INSTALL_NAME = 'clavarium-beat-install';
|
|
92
|
+
|
|
93
|
+
export class Beat {
|
|
94
|
+
#vms; #workFolder; #conversations; #now; #version; #seq = new Map(); #expected = new Map(); #tried = new Map(); #installing = new Map();
|
|
95
|
+
/* `on`: CLAVARIUM_BEAT holds `health`. `workFolder(name)`: its work folder on this server.
|
|
96
|
+
`conversations`: get(name) -- whether its work is kept here. */
|
|
97
|
+
constructor({ on = false, vms, workFolder, conversations, now = () => Date.now(), version = VERSION }) {
|
|
98
|
+
this.on = Boolean(on); this.#vms = vms; this.#workFolder = workFolder; this.#conversations = conversations; this.#now = now; this.#version = version;
|
|
99
|
+
}
|
|
100
|
+
get version() { return this.#version; }
|
|
101
|
+
|
|
102
|
+
#dir(name) { if (!NAME.test(String(name))) throw new Error('not a conversation name'); return join(this.#workFolder(name), FOLDER); }
|
|
103
|
+
/* Its folder, a folder of its own (never a link), or null; made when `make` and missing. */
|
|
104
|
+
#folder(name, make = false) {
|
|
105
|
+
let dir;
|
|
106
|
+
try { dir = this.#dir(name); } catch { return null; }
|
|
107
|
+
let s = lstatSync(dir, { throwIfNoEntry: false });
|
|
108
|
+
if (!s && make) { try { mkdirSync(dir, { mode: 0o755 }); } catch { return null; } s = lstatSync(dir, { throwIfNoEntry: false }); }
|
|
109
|
+
return s && s.isDirectory() && !s.isSymbolicLink() ? dir : null;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/* WHAT SHOULD BE MOUNTED, for the beat to look at (resources.expected): written when it changed. */
|
|
113
|
+
expect(name, paths) {
|
|
114
|
+
if (!this.on) return false;
|
|
115
|
+
const text = `${paths.filter((p) => /^\/[A-Za-z0-9._/-]{1,200}$/.test(p)).slice(0, 100).join('\n')}\n`;
|
|
116
|
+
try {
|
|
117
|
+
const dir = this.#folder(name, true);
|
|
118
|
+
if (!dir) return false;
|
|
119
|
+
const at = join(dir, EXPECTED_FILE);
|
|
120
|
+
const s = lstatSync(at, { throwIfNoEntry: false });
|
|
121
|
+
if (this.#expected.get(name) === text && s?.isFile()) return true;
|
|
122
|
+
/* Aside, then moved: a link put at its place is replaced, never followed. */
|
|
123
|
+
const tmp = join(dir, `.expected.${randomBytes(6).toString('hex')}`);
|
|
124
|
+
try { writeFileSync(tmp, text, { flag: 'wx', mode: 0o644 }); renameSync(tmp, at); } catch (error) { rmSync(tmp, { force: true }); throw error; }
|
|
125
|
+
this.#expected.set(name, text);
|
|
126
|
+
return true;
|
|
127
|
+
} catch { return false; }
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/* ITS LAST BEAT: { ok: true, text, version, seq, at } or { ok: false, why }. `peek`: its number not
|
|
131
|
+
taken as seen (the install's look). */
|
|
132
|
+
read(name, { peek = false } = {}) {
|
|
133
|
+
const dir = this.#folder(name);
|
|
134
|
+
if (!dir) return { ok: false, why: 'none' };
|
|
135
|
+
let fd;
|
|
136
|
+
try { fd = openSync(join(dir, BEAT_FILE), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); } catch (error) { return { ok: false, why: error.code === 'ENOENT' ? 'none' : 'unreadable' }; }
|
|
137
|
+
let s; let text;
|
|
138
|
+
try {
|
|
139
|
+
s = fstatSync(fd);
|
|
140
|
+
if (!s.isFile()) return { ok: false, why: 'not a file' };
|
|
141
|
+
if (s.size > BEAT_BYTES) return { ok: false, why: 'too big' };
|
|
142
|
+
const buf = Buffer.alloc(BEAT_BYTES + 1);
|
|
143
|
+
let n = 0;
|
|
144
|
+
for (let got = 1; got > 0 && n <= BEAT_BYTES; n += got) got = readSync(fd, buf, n, BEAT_BYTES + 1 - n, null);
|
|
145
|
+
if (n > BEAT_BYTES) return { ok: false, why: 'too big' };
|
|
146
|
+
text = buf.toString('utf8', 0, n);
|
|
147
|
+
} catch { return { ok: false, why: 'unreadable' }; } finally { closeSync(fd); }
|
|
148
|
+
const age = this.#now() - s.mtimeMs;
|
|
149
|
+
if (age > FRESH_MS) return { ok: false, why: 'stale' };
|
|
150
|
+
if (age < -AHEAD_MS) return { ok: false, why: 'ahead' };
|
|
151
|
+
let j;
|
|
152
|
+
try { j = JSON.parse(text); } catch { return { ok: false, why: 'not json' }; }
|
|
153
|
+
if (!j || typeof j !== 'object' || j.v !== 1) return { ok: false, why: 'not a beat' };
|
|
154
|
+
if (j.conversation !== name) return { ok: false, why: 'another conversation' };
|
|
155
|
+
if (!Number.isSafeInteger(j.seq) || j.seq < 1) return { ok: false, why: 'no number' };
|
|
156
|
+
if (typeof j.version !== 'string' || !VERSION_WORD.test(j.version)) return { ok: false, why: 'no version' };
|
|
157
|
+
if (typeof j.probe !== 'string') return { ok: false, why: 'no probe' };
|
|
158
|
+
/* ITS NUMBER GROWS: the same beat read again (same number, same time) is still it; a smaller one, or
|
|
159
|
+
the same number written again, is not believed -- and the next one is taken as a new start. */
|
|
160
|
+
const last = this.#seq.get(name);
|
|
161
|
+
if (last && !(j.seq > last.seq || (j.seq === last.seq && s.mtimeMs === last.at))) { if (!peek) this.#seq.delete(name); return { ok: false, why: 'number' }; }
|
|
162
|
+
if (!peek) this.#seq.set(name, { seq: j.seq, at: s.mtimeMs });
|
|
163
|
+
return { ok: true, text: j.probe, version: j.version, seq: j.seq, at: s.mtimeMs };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/* PUT IN ITS MACHINE, once: one command, as root. Skipped when its beat is fresh and says this version,
|
|
167
|
+
or when it was tried already for this version (`woke`: its machine has just started -- what was tried
|
|
168
|
+
is forgotten: a fresh beat may still be from before its start, and once it is stale the next call puts
|
|
169
|
+
it again). Never more than
|
|
170
|
+
one at a time per conversation. Resolves with what was done: 'off', 'fresh', 'tried', 'put', 'failed'. */
|
|
171
|
+
ensure(name, { woke = false } = {}) {
|
|
172
|
+
if (!this.on || this.#conversations?.get(name)?.work !== 'kept') return Promise.resolve('off');
|
|
173
|
+
if (woke) this.#tried.delete(name);
|
|
174
|
+
const going = this.#installing.get(name);
|
|
175
|
+
if (going) return going;
|
|
176
|
+
const beat = this.read(name, { peek: true });
|
|
177
|
+
if (beat.ok && beat.version === this.#version) return Promise.resolve('fresh');
|
|
178
|
+
if (this.#tried.get(name) === this.#version) return Promise.resolve('tried');
|
|
179
|
+
this.#tried.set(name, this.#version);
|
|
180
|
+
const mode = this.#vms.shared?.(name) ? 'shared' : 'own';
|
|
181
|
+
const run = this.#vms.execMachine(name, ['sudo', '-n', 'sh', '-c', installScript(), INSTALL_NAME, mode, mode === 'own' ? name : '-', this.#version], { timeoutMs: INSTALL_MS })
|
|
182
|
+
.then((r) => (r.code === 0 ? 'put' : 'failed'), () => 'failed')
|
|
183
|
+
.finally(() => this.#installing.delete(name));
|
|
184
|
+
this.#installing.set(name, run);
|
|
185
|
+
return run;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
forget(name) { this.#seq.delete(name); this.#expected.delete(name); this.#tried.delete(name); }
|
|
189
|
+
}
|
package/server/copywork.mjs
CHANGED
|
@@ -3,12 +3,13 @@
|
|
|
3
3
|
* what belongs to the original alone:
|
|
4
4
|
* .docket its reminders and what woke it: they would fire twice;
|
|
5
5
|
* .tether, .binder its asks to the keepers and their answers, being answered: the copy asks its own;
|
|
6
|
-
* .parley's live files its pulse, its voice boxes, its restart asked, its program (put again by the server)
|
|
6
|
+
* .parley's live files its pulse, its voice boxes, its restart asked, its program (put again by the server);
|
|
7
|
+
* .clavarium its machine's heartbeat and what it looks at (beat.mjs): the copy's machine beats its own.
|
|
7
8
|
* Only plain files, folders and links: anything else (a socket, a pipe) is no work. Its copy keeps their times. */
|
|
8
9
|
import { cp, lstat } from 'node:fs/promises';
|
|
9
10
|
import { relative, sep } from 'node:path';
|
|
10
11
|
|
|
11
|
-
export const NOT_COPIED = Object.freeze(['.docket', '.tether', '.binder', '.clavarium-carry', '.parley/pulse.json', '.parley/speakers.json', '.parley/restart-asked', '.parley/server.mjs']);
|
|
12
|
+
export const NOT_COPIED = Object.freeze(['.docket', '.tether', '.binder', '.clavarium', '.clavarium-carry', '.parley/pulse.json', '.parley/speakers.json', '.parley/restart-asked', '.parley/server.mjs']);
|
|
12
13
|
|
|
13
14
|
/* Whether a path of the work folder (relative, '' for the folder itself) is copied. */
|
|
14
15
|
export function copied(path) {
|
package/server/health.mjs
CHANGED
|
@@ -78,6 +78,9 @@ export const PROBE = [
|
|
|
78
78
|
export const PROBE_NAME = 'clavarium-health';
|
|
79
79
|
|
|
80
80
|
export const EVERY_MS = 120_000;
|
|
81
|
+
/* WITH A HEARTBEAT (beat.mjs), a look by command still, this often, whatever the beat says: what the agent
|
|
82
|
+
wrote in its /work is believed only between two looks of our own. */
|
|
83
|
+
export const SPOT_MS = 30 * 60_000;
|
|
81
84
|
/* The looks of one tick start this far apart, one machine after another (at most a tick shared out
|
|
82
85
|
between them): a burst of probes lines up at the VM manager in front of every other command. */
|
|
83
86
|
export const STAGGER_MS = 5_000;
|
|
@@ -180,7 +183,7 @@ export function judge(record) {
|
|
|
180
183
|
}
|
|
181
184
|
|
|
182
185
|
export class Health {
|
|
183
|
-
#vms; #conversations; #resources; #records = new Map(); #running = new Map(); #quiet = new Map(); #settleMs; #probeMs; #lookMs; #seen; #links;
|
|
186
|
+
#vms; #conversations; #resources; #records = new Map(); #running = new Map(); #quiet = new Map(); #settleMs; #probeMs; #lookMs; #seen; #links; #beat; #now; #execAt = new Map();
|
|
184
187
|
/* Set by the server: told each judgment (the chat of a conversation says what is wrong: talk.mjs). */
|
|
185
188
|
judged = () => {};
|
|
186
189
|
/* Set by the server: told a conversation is forgotten (what else is kept of its machine goes too). */
|
|
@@ -194,8 +197,9 @@ export class Health {
|
|
|
194
197
|
`lookMs`: how long the clock waits for one conversation's look. */
|
|
195
198
|
/* `seen`: a store of the problems its owner marked seen ("Seen"), by conversation. */
|
|
196
199
|
/* `links`: the guard of links its folders cannot serve (linkguard.mjs), or null. */
|
|
197
|
-
|
|
198
|
-
|
|
200
|
+
/* `beat`: the heartbeats read from the work folders (beat.mjs), or null: every look by command. */
|
|
201
|
+
constructor({ vms, conversations, resources, settleMs = 5000, probeMs = PROBE_MS, lookMs = LOOK_MS, seen = null, links = null, beat = null, now = () => Date.now() }) {
|
|
202
|
+
this.#seen = seen; this.#links = links; this.#beat = beat; this.#now = now;
|
|
199
203
|
this.#vms = vms; this.#conversations = conversations; this.#resources = resources; this.#settleMs = settleMs; this.#probeMs = probeMs; this.#lookMs = lookMs;
|
|
200
204
|
}
|
|
201
205
|
|
|
@@ -209,7 +213,7 @@ export class Health {
|
|
|
209
213
|
this.#seen?.put({ name, keys, at: new Date().toISOString() });
|
|
210
214
|
return this.of(name);
|
|
211
215
|
}
|
|
212
|
-
forget(name) { this.#records.delete(name); this.#quiet.delete(name); this.#seen?.remove?.(name); try { this.forgotten(name); } catch { /* told */ } }
|
|
216
|
+
forget(name) { this.#records.delete(name); this.#quiet.delete(name); this.#execAt.delete(name); this.#beat?.forget?.(name); this.#seen?.remove?.(name); try { this.forgotten(name); } catch { /* told */ } }
|
|
213
217
|
|
|
214
218
|
/* The look under way (it may be mounting a folder again), or null. */
|
|
215
219
|
busy(name) { return this.#running.get(name) ?? null; }
|
|
@@ -238,11 +242,20 @@ export class Health {
|
|
|
238
242
|
the VM manager for seconds, and every other machine waits behind it (21-10). */
|
|
239
243
|
const quiet = this.#quiet.get(name);
|
|
240
244
|
if (quiet && !asked && Date.now() < quiet.until) return this.#keep(name, { at, state, answering: false });
|
|
241
|
-
|
|
245
|
+
/* Its heartbeat, when it says enough (#fromBeat): no command. Else the look by command, as always. */
|
|
246
|
+
const beating = Boolean(this.#beat?.on) && c.work === 'kept';
|
|
247
|
+
let facts = beating ? this.#fromBeat(name, paths, asked) : undefined;
|
|
248
|
+
if (beating) this.#vms.noteBeat?.(Boolean(facts));
|
|
242
249
|
if (!facts) {
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
250
|
+
facts = await this.#probe(name, paths);
|
|
251
|
+
if (!facts) {
|
|
252
|
+
const times = (quiet?.times ?? 0) + 1;
|
|
253
|
+
this.#quiet.set(name, { times, until: Date.now() + Math.min(QUIET_MAX_MS, QUIET_MS * 2 ** (times - 1)) });
|
|
254
|
+
return this.#keep(name, { at, state, answering: false });
|
|
255
|
+
}
|
|
256
|
+
this.#execAt.set(name, this.#now());
|
|
257
|
+
/* Its beat put in its machine when it is not there or not of this version (bounded: beat.mjs, ensure). */
|
|
258
|
+
if (beating) void Promise.resolve().then(() => this.#beat.ensure?.(name)).catch(() => {});
|
|
246
259
|
}
|
|
247
260
|
this.#quiet.delete(name);
|
|
248
261
|
try { void Promise.resolve(this.probed(name, facts)).catch(() => {}); } catch { /* told, nothing more */ }
|
|
@@ -314,6 +327,24 @@ export class Health {
|
|
|
314
327
|
return { at: record.at, items, health: this.of(name) };
|
|
315
328
|
}
|
|
316
329
|
|
|
330
|
+
/* ITS HEARTBEAT AS THE PROBE'S ANSWER (beat.mjs), or undefined -- then the look is a command, as before:
|
|
331
|
+
a look asked (its owner, a start, a wake), the first look of a machine or one just back (not seen
|
|
332
|
+
running and answering at the last look), a spot check every SPOT_MS, a beat not newer than our own last
|
|
333
|
+
look, not fresh or not what it should be, or one that does not say each path that should be mounted. */
|
|
334
|
+
#fromBeat(name, paths, asked) {
|
|
335
|
+
this.#beat.expect?.(name, paths);
|
|
336
|
+
if (asked) return undefined;
|
|
337
|
+
const last = this.#records.get(name);
|
|
338
|
+
if (last?.state !== 'Running' || last.answering !== true) return undefined;
|
|
339
|
+
const ours = this.#execAt.get(name);
|
|
340
|
+
if (ours === undefined || this.#now() - ours >= SPOT_MS) return undefined;
|
|
341
|
+
const beat = this.#beat.read(name);
|
|
342
|
+
if (!beat.ok || !(beat.at > ours)) return undefined;
|
|
343
|
+
const facts = readProbe(beat.text, paths);
|
|
344
|
+
if (!facts.memory || paths.some((p) => facts.mounts[p] === undefined)) return undefined;
|
|
345
|
+
return facts;
|
|
346
|
+
}
|
|
347
|
+
|
|
317
348
|
async #probe(name, paths) {
|
|
318
349
|
/* Its output is the agent's: not more than a few pages of it are even taken in. */
|
|
319
350
|
const r = await this.#vms.exec(name, ['sh', '-c', PROBE, PROBE_NAME, ...paths], { timeoutMs: this.#probeMs, maxBytes: PROBE_BYTES * 4 }).catch(() => ({ code: 1, stdout: '' }));
|
package/server/main.mjs
CHANGED
|
@@ -99,6 +99,7 @@ import { RelayJoin, handleRelayJoin, RELAY_JOIN_PATH } from './relayjoin.mjs';
|
|
|
99
99
|
import { WebSocketServer } from 'ws';
|
|
100
100
|
import { attachConsole } from './sshconsole.mjs';
|
|
101
101
|
import { copyWorkFolder } from './copywork.mjs';
|
|
102
|
+
import { Beat, beatWanted } from './beat.mjs';
|
|
102
103
|
import { accessesOf, relinkAccesses } from './carry.mjs';
|
|
103
104
|
import { Jobs, withUpdates } from './jobs.mjs';
|
|
104
105
|
|
|
@@ -442,7 +443,12 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
442
443
|
chat: (name) => Boolean(talk?.brief(name)), say: (name, line) => wakeups.say(name, line), reread: () => talk?.rereadCommand() ?? null });
|
|
443
444
|
/* Why Parley is not in a machine, said once in the log, not at each opening. */
|
|
444
445
|
const parleySaid = new Map();
|
|
446
|
+
/* ITS HEARTBEAT (beat.mjs): with CLAVARIUM_BEAT=health, its health read from its work folder instead of
|
|
447
|
+
a command every two minutes; put in its machine at an opening (once per version), never waited for. */
|
|
448
|
+
const beat = new Beat({ on: beatWanted(env.CLAVARIUM_BEAT, 'health'), vms, workFolder: (name) => folders.workFolder(name), conversations: all });
|
|
449
|
+
if (beat.on) console.log('beat: the health of the machines read from their heartbeat (CLAVARIUM_BEAT)');
|
|
445
450
|
all.prepare = async (name, woke) => {
|
|
451
|
+
void beat.ensure(name, { woke }).catch(() => {});
|
|
446
452
|
await hostReady;
|
|
447
453
|
secrets.check();
|
|
448
454
|
const wanted = secrets.signature(name);
|
|
@@ -689,7 +695,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
689
695
|
try { if (dockets.on(name)) { dockets.post(name, { kind: 'shared-folder', text: line, data: { folder: link.folder, path: link.path } }); return; } } catch { /* typed instead */ }
|
|
690
696
|
if (all.list().find((c) => c.name === name)?.ai === true) void wakeups.say(name, line).catch(() => {});
|
|
691
697
|
};
|
|
692
|
-
const health = new Health({ vms, conversations: all, resources: folders, links: linkGuard, seen: new Store(`${dataDir}/health-seen.json`), ...(healthSettleMs === undefined ? {} : { settleMs: healthSettleMs }) });
|
|
698
|
+
const health = new Health({ vms, conversations: all, resources: folders, links: linkGuard, beat, seen: new Store(`${dataDir}/health-seen.json`), ...(healthSettleMs === undefined ? {} : { settleMs: healthSettleMs }) });
|
|
693
699
|
const stopHealth = health.start(healthEveryMs, { quietMs: quietStartMs });
|
|
694
700
|
/* What is wrong with its machine is said in its chat too, where it happened. */
|
|
695
701
|
/* And what its owner chose that it does on top (healthreact.mjs): its agent told, or a command run. */
|
package/server/vm.mjs
CHANGED
|
@@ -125,7 +125,9 @@ export class Vms {
|
|
|
125
125
|
/* HOW MUCH THIS SERVER ASKS OF THE HOST (17-11: the owner saw a page wait 10-15 s with an idle CPU --
|
|
126
126
|
every command to a machine goes through the VM manager, one after another): each command counted by
|
|
127
127
|
what it is, with its time; every COUNT_EVERY_MS the tally is said in the log, the busiest first. */
|
|
128
|
-
#tally = new Map(); #tallyFrom = 0;
|
|
128
|
+
#tally = new Map(); #tallyFrom = 0; #beats = [0, 0];
|
|
129
|
+
/* A look of health answered by its heartbeat (`read`: no command; beat.mjs), or by a command after all. */
|
|
130
|
+
noteBeat(read) { this.#beats[read ? 0 : 1] += 1; }
|
|
129
131
|
#count(argv, ms) {
|
|
130
132
|
const now = this.#now();
|
|
131
133
|
if (!this.#tallyFrom) this.#tallyFrom = now;
|
|
@@ -133,8 +135,9 @@ export class Vms {
|
|
|
133
135
|
if (now - this.#tallyFrom < COUNT_EVERY_MS) return;
|
|
134
136
|
const rows = [...this.#tally].sort((a, b) => b[1][1] - a[1][1]);
|
|
135
137
|
const all = rows.reduce((n, [, v]) => n + v[0], 0); const busy = rows.reduce((n, [, v]) => n + v[1], 0);
|
|
136
|
-
|
|
137
|
-
this.#
|
|
138
|
+
const beats = this.#beats[0] + this.#beats[1] ? `; beat read ${this.#beats[0]}x, fallback ${this.#beats[1]}x` : '';
|
|
139
|
+
console.log(`host: ${all} commands in ${Math.round((now - this.#tallyFrom) / 60_000)} min, ${Math.round(busy / 1000)} s spent; ${rows.slice(0, 8).map(([k, v]) => `${k} ${v[0]}x ${Math.round(v[1] / 1000)}s max ${Math.round(v[2] / 1000)}s`).join('; ')}${beats}`);
|
|
140
|
+
this.#tally = new Map(); this.#tallyFrom = now; this.#beats = [0, 0];
|
|
138
141
|
}
|
|
139
142
|
|
|
140
143
|
/* EVERY MACHINE'S STATE, in one question to the VM manager, shared by every caller for a
|