clavarium 0.2.488-next.1 → 0.2.490-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.
@@ -61,6 +61,9 @@ set -euo pipefail
61
61
  export LC_ALL=C
62
62
 
63
63
  MULTIPASS="multipass"
64
+ # SERVER LOGS: the journal reader, and how long it is given before what it said by then is shown.
65
+ JOURNALCTL="journalctl"
66
+ LOGS_SECONDS="60"
64
67
  # THE WAY DOWN (vm halt, vm hardstop): how long each step is given before the next, in seconds --
65
68
  # a polite stop, a stop by force asked of the VM manager, SIGTERM to the machine's own qemu, SIGKILL
66
69
  # to it; then how long multipass may take to answer a list, and to see the machine stopped after.
@@ -196,7 +199,8 @@ while [ $# -gt 0 ]; do
196
199
  DATA="$TEST"; MNT="$TEST"; WIFI_STATE="$TEST/wifi"; NM_KEYFILES="$TEST/system-connections"; WIFI_WAIT="3"; WIFI_UP_WAIT="3"; WIFI_STEP="0.2"
197
200
  HAND_STATE="$TEST/network"; NETPLAN_DIR="$TEST/netplan"; HAND_WAIT="3"; SYS_NET="$TEST/sys-net"
198
201
  MESH_DATA="$TEST/mesh"; MESH_STATE="$TEST/meshcentral"; CADDYFILE="$TEST/Caddyfile"; MESH_CADDY="$TEST/clavarium-meshcentral.caddy"
199
- HALT_POLITE="2"; HALT_FORCE="2"; HALT_TERM="1"; HALT_KILL="2"; HALT_LIST="2"; HALT_SETTLE="2"; QEMU_SEEN="$TEST/qemu"; shift 2 ;;
202
+ HALT_POLITE="2"; HALT_FORCE="2"; HALT_TERM="1"; HALT_KILL="2"; HALT_LIST="2"; HALT_SETTLE="2"; QEMU_SEEN="$TEST/qemu"
203
+ JOURNALCTL="$TEST/journalctl"; LOGS_SECONDS="2"; shift 2 ;;
200
204
  *) break ;;
201
205
  esac
202
206
  done
@@ -1216,21 +1220,41 @@ case "$AREA $VERB" in
1216
1220
  # source, over a span; read-only, bounded. The page masks what looks
1217
1221
  # like a secret before showing it.
1218
1222
  # server logs <clavarium|machines|updates|web|signin|tunnel|system> <10m|1|6|24|168|boot>
1223
+ # 17-11: a journal flooded by sudo (a line a second, the server's own calls of this program)
1224
+ # took more than the page waits. The server's unit is read by indexed fields, its own output
1225
+ # only (stdout), not sudo's syslog lines; sudo and PAM session lines are left out of any
1226
+ # source; the read is given LOGS_SECONDS, then what it said by then is shown, with a NOTE
1227
+ # on stderr -- never a bare failure.
1219
1228
  [ $# -eq 2 ] || usage
1229
+ # A unit by its fields: what it wrote, and what systemd said of it.
1230
+ unit() { printf '%s\n' "_SYSTEMD_UNIT=$1" + "UNIT=$1" "_PID=1" +; }
1220
1231
  case "$1" in
1221
- clavarium) units=(-u clavarium.service -u 'clavarium-view-*' -u clavarium-tools-view.service -u clavarium-move-machines.service) ;;
1222
- machines) units=(-u snap.multipass.multipassd.service) ;;
1223
- updates) units=(-u clavarium-update.service -u clavarium-certificate.service) ;;
1224
- web) units=(-u caddy.service -u oauth2-proxy.service) ;;
1225
- signin) units=(-u dex.service) ;;
1226
- tunnel) units=(-u clavarium-tunnel.service) ;;
1227
- system) units=(-k) ;;
1232
+ clavarium) matches=(_SYSTEMD_UNIT=clavarium.service _TRANSPORT=stdout _TRANSPORT=journal + UNIT=clavarium.service _PID=1 +)
1233
+ views=()
1234
+ if [ "$SAY" = "no" ]; then mapfile -t views < <(systemctl list-units --all --plain --no-legend 'clavarium-view-*' 2>/dev/null | awk '$1 ~ /^clavarium-view-[A-Za-z0-9_.@-]+$/ {print $1}' | head -50); fi
1235
+ for u in "${views[@]}" clavarium-tools-view.service clavarium-move-machines.service; do mapfile -t -O "${#matches[@]}" matches < <(unit "$u"); done
1236
+ unset 'matches[-1]' ;;
1237
+ machines) matches=(-u snap.multipass.multipassd.service) ;;
1238
+ updates) matches=(-u clavarium-update.service -u clavarium-certificate.service) ;;
1239
+ web) matches=(-u caddy.service -u oauth2-proxy.service) ;;
1240
+ signin) matches=(-u dex.service) ;;
1241
+ tunnel) matches=(-u clavarium-tunnel.service) ;;
1242
+ system) matches=(-k) ;;
1228
1243
  *) refuse "not a source of logs: $1" ;;
1229
1244
  esac
1230
1245
  case "$2" in 10m) since=(--since "-10min") ;; 1|6|24|168) since=(--since "-$2h") ;; boot) since=(-b) ;; *) refuse "not a span: $2 (10m, 1, 6, 24, 168 hours, or boot)" ;; esac
1231
1246
  # The newest 20000 lines at most: more is too much to read on a page, and to send.
1232
- if [ "$SAY" = "yes" ]; then echo "journalctl ${units[*]} ${since[*]} -o short-iso --no-pager (the last 20000 lines)"; exit 0; fi
1233
- journalctl "${units[@]}" "${since[@]}" -o short-iso --no-pager -n 20000 2>/dev/null | cut -c1-2000 || true
1247
+ if [ "$SAY" = "yes" ]; then echo "journalctl ${matches[*]} ${since[*]} -o short-iso --no-pager -q -n 20000 (sudo and PAM session lines left out; ${LOGS_SECONDS}s at most)"; exit 0; fi
1248
+ out="$(mktemp)"; err="$(mktemp)"
1249
+ trap 'rm -f -- "$out" "$err"' EXIT
1250
+ code=0
1251
+ timeout -k 5 "$LOGS_SECONDS" "$JOURNALCTL" "${matches[@]}" "${since[@]}" -o short-iso --no-pager -q -n 20000 >"$out" 2>"$err" || code=$?
1252
+ grep -avE ' (sudo|pkexec)\[[0-9]+\]: | pam_unix\((sudo|sudo-i|pkexec):session\)' "$out" | cut -c1-2000 || true
1253
+ case "$code" in
1254
+ 0) : ;;
1255
+ 124|137) echo "NOTE: the journal took more than ${LOGS_SECONDS}s: what it said by then" >&2 ;;
1256
+ *) echo "NOTE: journalctl ended with $code: $(grep -av '^$' "$err" | tail -n 1 | cut -c1-200)" >&2 ;;
1257
+ esac
1234
1258
  exit 0 ;;
1235
1259
  "server restart")
1236
1260
  # THIS SERVER STARTED AGAIN, asked from the page: in two seconds, by
@@ -155,31 +155,53 @@ export const SUDOERS = '/etc/sudoers.d/clavarium';
155
155
  export const QUIET_SETTINGS = ['!syslog, !pam_session', '!pam_session'];
156
156
  export const quietLine = (account, setting = QUIET_SETTINGS[0]) => `Defaults:${account} ${setting}`;
157
157
  const QUIET_COMMENT = '# Added by the Clavarium updater: its probes every few seconds are not written to the system log.';
158
- export async function ensureQuietSudo({ file = SUDOERS, run = runCommand } = {}) {
158
+ /* `told(outcome)`: what is in place after this turn, for Settings (sudo-quiet.json beside the state, server/updates.mjs):
159
+ { on: true, setting } or { on: false, why } -- the file missing, no account in it, visudo refusing (its words). */
160
+ export async function ensureQuietSudo({ file = SUDOERS, run = runCommand, told = () => {} } = {}) {
159
161
  let text;
160
- try { text = readFileSync(file, 'utf8'); } catch { return false; }
162
+ try { text = readFileSync(file, 'utf8'); } catch (error) { told({ on: false, why: `${file} not readable (${error.code ?? error.message})` }); return false; }
161
163
  const account = text.match(/^([a-z_][a-z0-9_-]*)\s+ALL=\(root\)\s+NOPASSWD:/m)?.[1];
162
- if (!account) return false;
164
+ if (!account) { told({ on: false, why: `no "<account> ALL=(root) NOPASSWD:" line in ${file}` }); return false; }
165
+ let refusal = '';
163
166
  const accepted = async (candidate) => {
164
167
  rmSync(`${file}.new`, { force: true });
165
168
  writeFileSync(`${file}.new`, candidate, { mode: 0o440 });
166
169
  const r = await run(['visudo', '-cf', `${file}.new`], { timeoutMs: 30_000 });
167
- return r.code === 0 && !/unknown setting|syntax error|parse error/i.test(`${r.stdout}\n${r.stderr}`);
170
+ const said = `${r.stdout ?? ''}\n${r.stderr ?? ''}`;
171
+ const ok = r.code === 0 && !/unknown setting|syntax error|parse error/i.test(said);
172
+ if (!ok) refusal = said.split('\n').map((l) => l.trim()).filter(Boolean).pop()?.slice(0, 200) || `visudo exit ${r.code}`;
173
+ return ok;
168
174
  };
169
175
  /* The rule as it is, without any line of ours. */
170
176
  const base = text.split('\n').filter((l) => l !== QUIET_COMMENT && !l.startsWith(`Defaults:${account} `)).join('\n').replace(/\n*$/, '\n');
171
- const current = QUIET_SETTINGS.map((q) => quietLine(account, q)).find((l) => text.includes(l));
177
+ const current = QUIET_SETTINGS.find((q) => text.includes(quietLine(account, q)));
172
178
  try {
173
- if (current && await accepted(text)) return false; /* ours, and taken as it is */
179
+ if (current && await accepted(text)) { told({ on: true, setting: current, account }); return false; } /* ours, and taken as it is */
180
+ const refused = [];
174
181
  for (const setting of QUIET_SETTINGS) {
175
182
  const next = `${base}${QUIET_COMMENT}\n${quietLine(account, setting)}\n`;
176
- if (await accepted(next)) { renameSync(`${file}.new`, file); return true; }
183
+ if (await accepted(next)) {
184
+ try { renameSync(`${file}.new`, file); } catch (error) { told({ on: false, why: `${file} not replaced (${error.code ?? error.message})` }); throw error; }
185
+ told({ on: true, setting, account }); return true;
186
+ }
187
+ refused.push(`${setting}: ${refusal}`);
177
188
  }
178
189
  /* None taken: the rule alone, as install.sh wrote it -- never a file sudo complains about. */
190
+ told({ on: false, why: `visudo refused ${refused.join('; ')}`.slice(0, 300) });
179
191
  if (current && await accepted(base)) { renameSync(`${file}.new`, file); return true; }
180
192
  return false;
181
193
  } finally { rmSync(`${file}.new`, { force: true }); }
182
194
  }
195
+ /* WHETHER IT WORKS, for Settings (17-11: the owner's journal still had a sudo line a second, the rule said to be
196
+ written): which sudo this is (`sudo --version`, its first line), and how many sudo lines the journal got over
197
+ the last ten minutes -- read by its own field, which the journal indexes: no long read. */
198
+ export async function sudoSeen({ run = runCommand } = {}) {
199
+ const v = await run(['sudo', '--version'], { timeoutMs: 10_000 }).catch(() => ({ code: 1, stdout: '' }));
200
+ const sudo = String(v.stdout ?? '').split('\n')[0].trim().slice(0, 80) || null;
201
+ const j = await run(['journalctl', 'SYSLOG_IDENTIFIER=sudo', '--since', '-10min', '-o', 'cat', '--no-pager', '-q'], { timeoutMs: 20_000 }).catch(() => ({ code: 1, stdout: '' }));
202
+ const lines10m = j.code === 0 ? String(j.stdout ?? '').split('\n').filter((l) => l.trim()).length : null;
203
+ return { sudo, lines10m };
204
+ }
183
205
 
184
206
  /* FFMPEG, kept by the updater: the voice boxes play a radio, a podcast, a music file through it
185
207
  (server/boxes.mjs, listen). Installed by install.sh; added once to a machine installed before. */
@@ -1071,7 +1093,17 @@ async function main(argv) {
1071
1093
  try { const [{ installWatch }, { realSys }] = await Promise.all([import('./doctor.mjs'), import('./online.mjs')]); if (await installWatch(realSys())) console.error('updater: the certificate timer set up'); } catch (error) { console.error(`updater: the certificate timer could not be set up: ${error.message}`); }
1072
1094
  try { if (await u.ensureDropIn()) console.error('updater: the drop-in of the server\'s unit written'); } catch (error) { console.error(`updater: the drop-in could not be written: ${error.message}`); }
1073
1095
  try { if (await ensureFfmpeg()) console.error('updater: ffmpeg installed, for the sounds the voice boxes play'); } catch (error) { console.error(`updater: ffmpeg could not be installed: ${error.message}`); }
1074
- try { if (await ensureQuietSudo()) console.error('updater: sudo no longer logs the host program\'s probes'); } catch (error) { console.error(`updater: sudo could not be made quiet: ${error.message}`); }
1096
+ /* What became of it is kept beside the state, for Settings (server/updates.mjs: sudoQuiet). */
1097
+ {
1098
+ let outcome = { on: false, why: 'not looked at' };
1099
+ try { if (await ensureQuietSudo({ told: (o) => { outcome = o; } })) console.error('updater: sudo no longer logs the host program\'s probes'); } catch (error) { console.error(`updater: sudo could not be made quiet: ${error.message}`); if (outcome.on) outcome = { on: false, why: error.message.slice(0, 200) }; }
1100
+ if (!outcome.on) console.error(`updater: sudo quiet: not applied: ${outcome.why}`);
1101
+ try {
1102
+ const seen = await sudoSeen();
1103
+ writeFileSync(join(PATHS.stateDir, 'sudo-quiet.json.new'), `${JSON.stringify({ ...outcome, ...seen, at: new Date().toISOString() })}\n`, { mode: 0o644 });
1104
+ renameSync(join(PATHS.stateDir, 'sudo-quiet.json.new'), join(PATHS.stateDir, 'sudo-quiet.json'));
1105
+ } catch (error) { console.error(`updater: the sudo quiet state could not be kept: ${error.message}`); }
1106
+ }
1075
1107
  try { if (await ensureProxySettings()) console.error('updater: the sign-in proxy set (one CSRF cookie per sign-in; /api/ext/ for API keys)'); } catch (error) { console.error(`updater: the sign-in proxy could not be set: ${error.message}`); }
1076
1108
  try { const c = await ensureGenericClientId({ run: runCommand }); if (c.changed.length) console.error('updater: the sign-in client id was made generic (nothing names the product in the open)'); } catch (error) { console.error(`updater: the sign-in client id could not be made generic: ${error.message}`); }
1077
1109
  try { if (await ensureTunnel({ run: runCommand })) console.error('updater: the tunnel to the relay notices a cut sooner'); } catch (error) { console.error(`updater: the tunnel could not be set: ${error.message}`); }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.488-next.1",
3
+ "version": "0.2.490-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.488-next.1",
9
+ "version": "0.2.490-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.488-next.1",
3
+ "version": "0.2.490-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
@@ -142,6 +142,8 @@
142
142
  * POST /api/server/machines/<name>/force its machine forced off, as from its conversation (202)
143
143
  * POST /api/server/vm-manager {mode: night|always|ask}: when it hangs, restarted by itself at night (default), always, or never
144
144
  * POST /api/server/vm-manager/restart {confirm: true}: restarted now; every machine is suspended and resumed
145
+ * GET /api/server/load host commands by 5-minute window, event-loop delay
146
+ * POST /api/server/profile {seconds}: this server sampled by its own profiler (2-30 s), what holds it
145
147
  * GET /api/server/logs?source=&span= what the server's programs said POST /api/server/restart POST /api/server/reboot (the whole server)
146
148
  * GET /api/operators who may sign in POST /api/operators {email} -> {email, password}: shown once
147
149
  * POST /api/operators/<email>/password -> {email, password} POST /api/operators/<email>/disable|enable|remove
@@ -478,6 +480,8 @@ export async function handleApi(request, response, conversations, headers, resou
478
480
  }));
479
481
  return send(200, history.together(query.get('span') ?? '1h', machines, { memoryMb: a?.memory?.totalMb, cores: room?.cpu?.cores, diskMb: a?.disk?.sizeMb })), true;
480
482
  }
483
+ /* What this server asked of the host, by 5-minute window, and its own event loop (vm.mjs HostTally). */
484
+ if (pathname === '/api/server/load' && serverLogs) return send(200, serverLogs.load()), true;
481
485
  if (pathname === '/api/server/logs' && serverLogs) { const r = await serverLogs.start(query.get('source') ?? 'clavarium', query.get('span') ?? '10m'); return send(r.pending ? 202 : 200, r), true; }
482
486
  if (pathname === '/api/machines/disks' && machinesMove) return send(200, await machinesMove.disks()), true;
483
487
  if (pathname === '/api/machines/places' && machinesMove) return send(200, await machinesMove.places()), true;
@@ -767,6 +771,7 @@ export async function handleApi(request, response, conversations, headers, resou
767
771
  const reactSet = /^\/api\/conversations\/([^/]+)\/health-react$/.exec(pathname);
768
772
  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; }
769
773
  if (pathname === '/api/machines/move' && machinesMove) return send(202, await machinesMove.move(String(body.to ?? ''))), true;
774
+ if (pathname === '/api/server/profile' && serverLogs) return send(200, await serverLogs.profile(body?.seconds ?? 10)), true;
770
775
  if (pathname === '/api/server/restart' && serverLogs) return send(202, await serverLogs.restart()), true;
771
776
  if (pathname === '/api/server/reboot' && serverLogs) return send(202, await serverLogs.reboot()), true;
772
777
  if (pathname === '/api/machines/grow' && machinesMove) return send(200, await machinesMove.grow(String(body.mount ?? ''))), true;
@@ -13,6 +13,9 @@
13
13
  * moved, restarted, its own updates of the day -- and each
14
14
  * job's log, as Settings shows them (jobs.mjs; secrets
15
15
  * masked) server:jobs r
16
+ * diagnostics the server's load (host commands by 5 min, its event loop),
17
+ * 10 s of its own profiler (what holds it), its logs (as
18
+ * Settings reads them, secrets masked) server:diagnostics r
16
19
  *
17
20
  * a conversation, given ONE BY ONE (never "all, and those to come"):
18
21
  * read read its chat conversation:<name> r
@@ -89,6 +92,7 @@
89
92
  * POST /api/apikeys {label, scopes, conversations: {name: 'read'|'talk'}, days|null}
90
93
  * -> {key, secret}: the secret this once
91
94
  * POST /api/apikeys/<id>/conversations {conversation, level: 'read'|'talk'|null}: one given, changed, taken back
95
+ * POST /api/apikeys/<id>/scopes {scope, on: true|false}: one scope given or taken back afterwards (18-11)
92
96
  * POST /api/apikeys/<id>/rooms {room, level: 'read'|'talk'|null}
93
97
  * POST /api/apikeys/<id>/boxes {box, level: 'state'|'speak'|null}
94
98
  * POST /api/apikeys/<id>/binders {binder, level: 'read'|'write'|null}
@@ -164,6 +168,7 @@ export const EXT_PREFIX = '/api/ext/';
164
168
  /* The scopes a key may be given: [asset, rights] in the table. */
165
169
  export const SCOPES = Object.freeze({ status: { asset: 'server:status', rights: 'r', label: 'Its state (memory, disk, versions)' },
166
170
  jobs: { asset: 'server:jobs', rights: 'r', label: 'Jobs: read what Clavarium does and its logs' },
171
+ diagnostics: { asset: 'server:diagnostics', rights: 'r', label: 'Diagnostics: load, measure, logs' },
167
172
  'create-rooms': { asset: 'server:rooms', rights: 'w', label: 'Create rooms' } });
168
173
  /* What a key may do in one conversation: [rights in the table]. */
169
174
  export const LEVELS = Object.freeze({ read: 'r', talk: 'rw', act: 'rwm' });
@@ -300,6 +305,16 @@ export class ApiKeys {
300
305
  return this.get(id);
301
306
  }
302
307
 
308
+ /* One scope of the server given to a key afterwards, or taken back (18-11: the owner, rather than a new key). */
309
+ setScope(id, scope, on) {
310
+ if (typeof id !== 'string' || !this.#store.get(id)) throw new Refusal(404, 'No such key.');
311
+ if (!Object.hasOwn(SCOPES, scope)) throw new Refusal(400, `Scopes are among: ${Object.keys(SCOPES).join(', ')}.`);
312
+ if (on === true) this.#grants.give(apiKeySubject(id), SCOPES[scope].asset, SCOPES[scope].rights);
313
+ else if (on === false) this.#grants.take(apiKeySubject(id), SCOPES[scope].asset);
314
+ else throw new Refusal(400, 'on: true or false.');
315
+ return this.get(id);
316
+ }
317
+
303
318
  /* A new key: its secret is in the answer, this once. `days`: its life (null: it does not expire).
304
319
  `conversations`: { name: 'read' | 'talk' }, each named -- there is no "all". */
305
320
  create({ label, scopes = [], conversations = {}, rooms = {}, boxes = {}, binders = {}, days = DEFAULT_DAYS } = {}, who = '') {
@@ -566,6 +581,28 @@ export const JOB_LOG_TOOL = {
566
581
  inputSchema: { type: 'object', properties: { id: { type: 'string', description: 'The job\'s id, as clavarium_jobs gives it.' } }, required: ['id'], additionalProperties: false },
567
582
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
568
583
  };
584
+ /* Diagnostics (18-11: to see the owner's server from here when it is slow, without the owner copying). */
585
+ export const LOAD_TOOL = {
586
+ name: 'clavarium_load',
587
+ title: 'Load of this Clavarium',
588
+ description: 'Read-only: what this server asked of the host, by 5-minute window (each kind of command, how many, the time), its own event loop delay (p50/p99/max ms) and processor time. The newest window first.',
589
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
590
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
591
+ };
592
+ export const PROFILE_TOOL = {
593
+ name: 'clavarium_profile',
594
+ title: 'What holds this Clavarium',
595
+ description: 'Read-only: this server sampled by its own profiler for a few seconds (2 to 30, 10 by default): the functions that took the most time themselves (self) and with what they called (total), idle, garbage collection, processor time. Waits that long.',
596
+ inputSchema: { type: 'object', properties: { seconds: { type: 'integer', minimum: 2, maximum: 30 } }, additionalProperties: false },
597
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: false },
598
+ };
599
+ export const LOGS_TOOL = {
600
+ name: 'clavarium_logs',
601
+ title: 'Logs of this Clavarium',
602
+ description: 'Read-only: what one of the server\'s programs said over a span, as Settings reads it (secrets masked). source: clavarium (default), machines, updates, web, signin, tunnel, system. span: 10m (default), 1, 6, 24, 168 (hours) or boot. A big journal takes a while: {pending: true} means ask again in a moment.',
603
+ inputSchema: { type: 'object', properties: { source: { type: 'string' }, span: { type: 'string' } }, additionalProperties: false },
604
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
605
+ };
569
606
  export const CONVERSATIONS_TOOL = {
570
607
  name: 'clavarium_conversations',
571
608
  title: 'Conversations of this key',
@@ -696,10 +733,10 @@ export const BINDER_ARCHIVE_TOOL = tool('clavarium_binder_archive', 'Archive a r
696
733
  'Archive a record (or restore it: "restore": true). Never deleted: only a person deletes. The list must have been given to this key to write.',
697
734
  { binder: BINDER_ARG, record: RECORD_ARG, restore: { type: 'boolean' } }, ['binder', 'record'], true);
698
735
  const BINDER_TOOLS = [BINDERS_TOOL, BINDER_RECORDS_TOOL, BINDER_RECORD_TOOL, BINDER_ADD_TOOL, BINDER_EDIT_TOOL, BINDER_MOVE_TOOL, BINDER_NOTE_TOOL, BINDER_ARCHIVE_TOOL];
699
- export const TOOLS = [STATUS_TOOL, JOBS_TOOL, JOB_LOG_TOOL, CONVERSATIONS_TOOL, READ_TOOL, SAY_TOOL, WAKE_TOOL, SLEEP_TOOL, STOP_TOOL, REMINDERS_TOOL, REMIND_TOOL, REMINDER_CANCEL_TOOL,
736
+ export const TOOLS = [STATUS_TOOL, JOBS_TOOL, JOB_LOG_TOOL, LOAD_TOOL, PROFILE_TOOL, LOGS_TOOL, CONVERSATIONS_TOOL, READ_TOOL, SAY_TOOL, WAKE_TOOL, SLEEP_TOOL, STOP_TOOL, REMINDERS_TOOL, REMIND_TOOL, REMINDER_CANCEL_TOOL,
700
737
  ROOMS_TOOL, ROOM_READ_TOOL, ROOM_SAY_TOOL, ROOM_CREATE_TOOL, ROOM_CHANGE_TOOL, ROOM_REMOVE_TOOL, BOXES_TOOL, BOX_SAY_TOOL, ...BINDER_TOOLS];
701
738
  /* The tools that need a scope of the server: listed only to a key given it. */
702
- const TOOL_SCOPES = Object.freeze({ [STATUS_TOOL.name]: 'status', [JOBS_TOOL.name]: 'jobs', [JOB_LOG_TOOL.name]: 'jobs', [ROOM_CREATE_TOOL.name]: 'create-rooms' });
739
+ const TOOL_SCOPES = Object.freeze({ [STATUS_TOOL.name]: 'status', [JOBS_TOOL.name]: 'jobs', [JOB_LOG_TOOL.name]: 'jobs', [LOAD_TOOL.name]: 'diagnostics', [PROFILE_TOOL.name]: 'diagnostics', [LOGS_TOOL.name]: 'diagnostics', [ROOM_CREATE_TOOL.name]: 'create-rooms' });
703
740
 
704
741
  /* Returns true when the request was under /api/ext/ (answered here). `status()`: the state, as statusOf
705
742
  makes it. `chats`: { list() -> [{ id, name }], read(name, part) -> talk.of's answer, chatOn(name),
@@ -714,8 +751,9 @@ const TOOL_SCOPES = Object.freeze({ [STATUS_TOOL.name]: 'status', [JOBS_TOOL.nam
714
751
  07-11: `reminders`: { of(name) -> { on, plans: [{ id, text, cron, next }] }, set(name, { at, cron, text }, by) -> plan,
715
752
  cancel(name, plan) -> bool } -- a conversation's Docket (dockets.mjs). `binder`: { act(op, args, who) -> { ok, text, data } }
716
753
  -- Binder's keeper, asked as the key (an agent): its rules are Binder's.
717
- 14-11: `jobs`: { list() -> { running, done }, log(id) -> the job with its log | undefined } (jobs.mjs, withUpdates). */
718
- export async function handleExternal(request, response, { keys, status, chats = null, rooms = null, boxes = null, reminders = null, binder = null, jobs = null, events = null, headers = {}, originOk = () => false, version = null }) {
754
+ 14-11: `jobs`: { list() -> { running, done }, log(id) -> the job with its log | undefined } (jobs.mjs, withUpdates).
755
+ 18-11: `diagnostics`: { load() -> HostTally windows, profile(seconds) -> profile.mjs's, logs(source, span) -> serverlogs.mjs start's }. */
756
+ export async function handleExternal(request, response, { keys, status, chats = null, rooms = null, boxes = null, reminders = null, binder = null, jobs = null, diagnostics = null, events = null, headers = {}, originOk = () => false, version = null }) {
719
757
  const url = new URL(request.url ?? '/', 'http://local');
720
758
  const { pathname } = url;
721
759
  if (!pathname.startsWith(EXT_PREFIX) && pathname !== EXT_PREFIX.slice(0, -1)) return false;
@@ -1190,6 +1228,14 @@ export async function handleExternal(request, response, { keys, status, chats =
1190
1228
  return result(await status());
1191
1229
  }
1192
1230
  if (name === JOBS_TOOL.name) return result(jobsListed(id));
1231
+ if (name === LOAD_TOOL.name || name === PROFILE_TOOL.name || name === LOGS_TOOL.name) {
1232
+ if (!keys.may(id, 'diagnostics')) throw new Refusal(403, `This key was not given the scope "${SCOPES.diagnostics.label}".`);
1233
+ if (!diagnostics) throw new Refusal(404, 'Not available on this server.');
1234
+ if (name === LOAD_TOOL.name) return result(diagnostics.load());
1235
+ if (name === PROFILE_TOOL.name) return result(await diagnostics.profile(args.seconds ?? 10));
1236
+ const r = await diagnostics.logs(typeof args.source === 'string' ? args.source : 'clavarium', typeof args.span === 'string' ? args.span : '10m');
1237
+ return result(r.pending ? r : { ...r, text: masked(r.text ?? '') });
1238
+ }
1193
1239
  if (name === JOB_LOG_TOOL.name) {
1194
1240
  if (typeof args.id !== 'string') return fail(-32602, 'id: the id of a job, as clavarium_jobs gives it.');
1195
1241
  return result(jobRead(id, args.id));
@@ -1282,6 +1328,12 @@ export async function handleApiKeys(request, response, keys, originOk, headers =
1282
1328
  events?.add({ kind: 'access', text: `API key "${made.key.label}" made${what.length ? ` (${what.join(', ')})` : ' (no scope)'}`, who: who || null });
1283
1329
  return send(201, made);
1284
1330
  }
1331
+ const scoping = /^\/api\/apikeys\/([0-9a-f-]{36})\/scopes$/.exec(pathname);
1332
+ if (scoping) {
1333
+ const key = keys.setScope(scoping[1], body.scope, body.on);
1334
+ events?.add({ kind: 'access', text: `API key "${key.label}": ${String(body.scope).slice(0, 40)} ${body.on ? 'given' : 'taken back'}`, who: who || null });
1335
+ return send(200, { key });
1336
+ }
1285
1337
  const giving = /^\/api\/apikeys\/([0-9a-f-]{36})\/conversations$/.exec(pathname);
1286
1338
  if (giving) {
1287
1339
  const level = body.level === undefined ? null : body.level;
package/server/grants.mjs CHANGED
@@ -35,7 +35,8 @@
35
35
  * in the table: the owner may do everything, always.
36
36
  *
37
37
  * An API key is not a device and not a conversation: it is given only what
38
- * its scopes name -- "server:status" (read), "server:jobs" (read its jobs and their logs), "server:rooms"
38
+ * its scopes name -- "server:status" (read), "server:jobs" (read its jobs and their logs), "server:diagnostics"
39
+ * (read the server's load, measure what holds it, read its logs, masked), "server:rooms"
39
40
  * (make rooms), and conversations one by one,
40
41
  * their chat to read ("r") or to talk in ("rw"), never their terminal ("x")
41
42
  * -- rooms one by one, their thread to read ("r") or to post in ("rw"), and
@@ -65,9 +66,9 @@ import { Refusal } from './conversations.mjs';
65
66
 
66
67
  export const RIGHTS = Object.freeze({ conversation: 'rwxm', folder: 'rw', mailbox: 'r', git: 'rw', secret: 'x', server: 'rw', room: 'rwm', box: 'rw' });
67
68
  /* What each of the server's own assets takes: its state and its jobs are read, rooms are made. */
68
- const SERVER_RIGHTS = Object.freeze({ 'server:status': 'r', 'server:jobs': 'r', 'server:rooms': 'w' });
69
+ const SERVER_RIGHTS = Object.freeze({ 'server:status': 'r', 'server:jobs': 'r', 'server:rooms': 'w', 'server:diagnostics': 'r' });
69
70
  const SUBJECT = /^(conversation:[a-z]([a-z0-9-]{0,30}[a-z0-9])?|(pairing|apikey):[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/;
70
- const ASSET = /^(conversation|folder|mailbox|git):[a-z]([a-z0-9-]{0,30}[a-z0-9])?$|^secret:[A-Z][A-Z0-9_]{0,39}$|^server:(status|jobs|rooms)$|^(room|box):[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
71
+ const ASSET = /^(conversation|folder|mailbox|git):[a-z]([a-z0-9-]{0,30}[a-z0-9])?$|^secret:[A-Z][A-Z0-9_]{0,39}$|^server:(status|jobs|rooms|diagnostics)$|^(room|box):[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
71
72
 
72
73
  export const typeOf = (asset) => String(asset).split(':')[0];
73
74
  export const nameOf = (asset) => String(asset).slice(String(asset).indexOf(':') + 1);
package/server/main.mjs CHANGED
@@ -28,7 +28,7 @@ import { Store, JsonFile } from './store.mjs';
28
28
  import { Instance } from './instance.mjs';
29
29
  import { loadTools, screenRules } from './tools.mjs';
30
30
  import { SigninHelp, typeInto } from './signinhelp.mjs';
31
- import { Vms, runner } from './vm.mjs';
31
+ import { Vms, runner, HostTally } from './vm.mjs';
32
32
  import { Resources, WORK_TAB } from './resources.mjs';
33
33
  import { download } from './files.mjs';
34
34
  import { makeGate, makeOriginCheck, readOperators } from './gate.mjs';
@@ -80,6 +80,8 @@ import { McpOAuth } from './mcpoauth.mjs';
80
80
  import { Browsers } from './browsers.mjs';
81
81
  import { Accounts } from './accounts.mjs';
82
82
  import { ServerLogs } from './serverlogs.mjs';
83
+ import { Profiler, AutoProfile } from './profile.mjs';
84
+ import { monitorEventLoopDelay } from 'node:perf_hooks';
83
85
  import { History, STEP_MS as HISTORY_STEP_MS } from './history.mjs';
84
86
  import { Events } from './events.mjs';
85
87
  import { Bundles } from './bundle.mjs';
@@ -253,7 +255,7 @@ function serve(port, conversations, resources, { gate = () => 'local', originOk,
253
255
  /* THE DOOR FOR PROGRAMS (apikeys.mjs): an API key is the right, never the gate -- the front lets
254
256
  /api/ext/ through without sign-on, and strips the identity headers there. */
255
257
  if (apikeys && (pathname === '/api/ext' || pathname.startsWith('/api/ext/'))) {
256
- await handleExternal(request, response, { keys: apikeys.keys, status: apikeys.status, chats: apikeys.chats, rooms: apikeys.rooms, boxes: apikeys.boxes, reminders: apikeys.reminders, binder: apikeys.binder, jobs: apikeys.jobs, events, headers: HEADERS, originOk, version: platform?.version ?? null });
258
+ await handleExternal(request, response, { keys: apikeys.keys, status: apikeys.status, chats: apikeys.chats, rooms: apikeys.rooms, boxes: apikeys.boxes, reminders: apikeys.reminders, binder: apikeys.binder, jobs: apikeys.jobs, diagnostics: apikeys.diagnostics, events, headers: HEADERS, originOk, version: platform?.version ?? null });
257
259
  return;
258
260
  }
259
261
  if (door && pathname.startsWith('/c/')) {
@@ -333,11 +335,15 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
333
335
  const originOk = makeOriginCheck(publicOrigin);
334
336
  const instance = new Instance({ file: new JsonFile(`${dataDir}/instance.json`, {}), origin: publicOrigin, given: appName });
335
337
  let repairTerminal = async () => { throw new Error('not ready'); };
336
- const asHost = runner(host);
338
+ /* Every command to the host counted (vm.mjs HostTally): said in the log every 5 minutes, and in Settings
339
+ (Diagnostics, Load). The machines' own commands are counted by Vms, with the same tally. */
340
+ const hostTally = new HostTally({ loop: true });
341
+ const hostRun = runner(host);
342
+ const asHost = hostTally.wrap(hostRun);
337
343
  /* A conversation in a shared machine (#221) says which: the machine its VM operations reach. */
338
344
  const jobs = new Jobs({ path: `${dataDir}/jobs.json` });
339
345
  const conversationStore = new Store(`${dataDir}/conversations.json`, { onChange: (before, after) => jobs.seen(before, after) });
340
- const vms = new Vms(asHost, host, {
346
+ const vms = new Vms(hostRun, host, { tally: hostTally,
341
347
  machineOf: (name) => { const m = conversationStore.get(name)?.sharedMachine; return typeof m === 'string' && m ? m : undefined; },
342
348
  userOf: (name) => { const u = conversationStore.get(name)?.machineUser; return u && Number.isInteger(u.uid) && Number.isInteger(u.gid) ? u : undefined; },
343
349
  });
@@ -834,7 +840,12 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
834
840
  /* All the machines to another disk, from Settings (machinesmove.mjs). */
835
841
  const machinesMove = new MachinesMove({ host: asHost, usedMb: () => capacity.machinesUsedMb() });
836
842
  /* What the server's programs said, and this server started again, from Settings (serverlogs.mjs). */
837
- const serverLogs = new ServerLogs({ host: asHost });
843
+ /* What holds this server: measured on demand (Settings, Load, Measure; MCP), and by itself when its loop is slow (profile.mjs). */
844
+ const profiler = new Profiler();
845
+ const loopWatch = monitorEventLoopDelay({ resolution: 20 }); loopWatch.enable();
846
+ const autoProfile = new AutoProfile({ profiler, file: new JsonFile(`${dataDir}/profiles.json`, {}),
847
+ delay: () => { if (!loopWatch.count) return null; const d = { p50: Math.round(loopWatch.percentile(50) / 1e6), p99: Math.round(loopWatch.percentile(99) / 1e6) }; loopWatch.reset(); return d; } }).start();
848
+ const serverLogs = new ServerLogs({ host: asHost, load: () => ({ ...hostTally.windows(), profiles: autoProfile.kept() }), profiler });
838
849
  /* This server's Wi-Fi, from Settings (wifi.mjs): how a switch ended, said in What happened. */
839
850
  const wifi = new Wifi({ host: asHost, said: (text) => events.add({ kind: 'server', text }) });
840
851
  /* The remote screen (MeshCentral), from Settings (meshcentral.mjs): how a turn-on ended, said in What happened. */
@@ -912,6 +923,8 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
912
923
  const apikeys = { keys: apiKeys, status: () => statusOf({ conversations: all, talk, health, answerer, capacity: briefly, history, platform, updates, components }),
913
924
  /* What Clavarium does (jobs.mjs), as Settings shows it: the list without logs, one job with its log. */
914
925
  jobs: { list: () => withUpdates(all.jobs, all.list(), updates?.about().history ?? []), log: (id) => all.jobs.log(id) },
926
+ /* Diagnostics (scope "diagnostics"): what Settings > Diagnostics > Load and Logs show. */
927
+ diagnostics: { load: () => serverLogs.load(), profile: (seconds) => serverLogs.profile(seconds), logs: (source, span) => serverLogs.start(source, span) },
915
928
  /* A key's conversations (their chat, through talk.mjs): read as the page reads it; a message posted as the page
916
929
  posts one (its secrets lifted the same way), signed with the key's name. */
917
930
  chats: {
@@ -0,0 +1,123 @@
1
+ /* WHAT HOLDS THIS SERVER, measured (18-11: the owner's server waited about a second at every turn of its
2
+ * event loop, with little CPU seen -- Settings, Load): a few seconds of this server sampled by its own
3
+ * V8 profiler (node:inspector, in-process: no port opened), then said in short, the functions that
4
+ * took the most time themselves and with what they called. Text only, nothing kept.
5
+ *
6
+ * profile(seconds) { seconds, sampledMs, idleMs, gcMs, programMs, self: [{ fn, at, ms }], total: [...] }
7
+ * one at a time: asked again while one runs, the same one
8
+ */
9
+ import { Session } from 'node:inspector/promises';
10
+ import { fileURLToPath } from 'node:url';
11
+
12
+ export const PROFILE_MIN_S = 2;
13
+ export const PROFILE_MAX_S = 30;
14
+ export const PROFILE_TOP = 15;
15
+ const APP = fileURLToPath(new URL('..', import.meta.url));
16
+
17
+ /* Where a function is, short: within the application from its folder, a package by its name, else the file's name. */
18
+ export function placeOf(url, line) {
19
+ let path = String(url ?? '');
20
+ if (!path) return '';
21
+ if (path.startsWith('file://')) { try { path = fileURLToPath(path); } catch { /* left as it is */ } }
22
+ const inModules = path.lastIndexOf('/node_modules/');
23
+ if (inModules >= 0) path = path.slice(inModules + '/node_modules/'.length);
24
+ else if (path.startsWith(APP)) path = path.slice(APP.length);
25
+ else if (path.startsWith('/')) path = path.split('/').pop();
26
+ return line >= 0 ? `${path}:${line + 1}` : path;
27
+ }
28
+
29
+ /* A V8 CPU profile told in short: each sample's time to its node, then by function. */
30
+ export function summarize(profile, seconds, top = PROFILE_TOP) {
31
+ const nodes = new Map((profile.nodes ?? []).map((n) => [n.id, n]));
32
+ const selfUs = new Map();
33
+ const samples = profile.samples ?? []; const deltas = profile.timeDeltas ?? [];
34
+ for (let i = 0; i < samples.length; i++) selfUs.set(samples[i], (selfUs.get(samples[i]) ?? 0) + Math.max(0, deltas[i] ?? 0));
35
+ const parent = new Map();
36
+ for (const n of nodes.values()) for (const c of n.children ?? []) parent.set(c, n.id);
37
+ const special = { '(idle)': 0, '(garbage collector)': 0, '(program)': 0, '(root)': 0 };
38
+ const self = new Map(); const total = new Map();
39
+ const keyOf = (n) => { const f = n.callFrame ?? {}; return `${f.functionName || '(anonymous)'}\t${placeOf(f.url, f.lineNumber)}`; };
40
+ for (const [id, us] of selfUs) {
41
+ const n = nodes.get(id); if (!n) continue;
42
+ const name = n.callFrame?.functionName ?? '';
43
+ if (name in special && !n.callFrame?.url) { special[name] += us; continue; }
44
+ const k = keyOf(n); self.set(k, (self.get(k) ?? 0) + us);
45
+ /* Its time counted once to every function above it (a recursive one once). */
46
+ const seen = new Set();
47
+ for (let at = id; at !== undefined; at = parent.get(at)) {
48
+ const up = nodes.get(at); if (!up || (up.callFrame?.functionName === '(root)' && !up.callFrame?.url)) break;
49
+ const uk = keyOf(up); if (seen.has(uk)) continue; seen.add(uk);
50
+ total.set(uk, (total.get(uk) ?? 0) + us);
51
+ }
52
+ }
53
+ const list = (m) => [...m].sort((a, b) => b[1] - a[1]).slice(0, top).map(([k, us]) => { const [fn, at] = k.split('\t'); return { fn, at, ms: Math.round(us / 1000) }; });
54
+ const all = [...selfUs.values()].reduce((a, b) => a + b, 0);
55
+ return {
56
+ seconds, sampledMs: Math.round(all / 1000), idleMs: Math.round(special['(idle)'] / 1000),
57
+ gcMs: Math.round(special['(garbage collector)'] / 1000), programMs: Math.round(special['(program)'] / 1000),
58
+ self: list(self), total: list(total),
59
+ };
60
+ }
61
+
62
+ export class Profiler {
63
+ #running = null; #session; #wait;
64
+ constructor({ session = () => new Session(), wait = (ms) => new Promise((ok) => { setTimeout(ok, ms); }) } = {}) { this.#session = session; this.#wait = wait; }
65
+ profile(seconds = 10) {
66
+ const s = Math.min(PROFILE_MAX_S, Math.max(PROFILE_MIN_S, Math.round(Number(seconds) || 10)));
67
+ if (this.#running) return this.#running;
68
+ this.#running = (async () => {
69
+ const session = this.#session();
70
+ session.connect();
71
+ try {
72
+ await session.post('Profiler.enable');
73
+ await session.post('Profiler.setSamplingInterval', { interval: 1000 });
74
+ await session.post('Profiler.start');
75
+ const began = process.cpuUsage();
76
+ await this.#wait(s * 1000);
77
+ const { profile } = await session.post('Profiler.stop');
78
+ const cpu = process.cpuUsage(began);
79
+ return { ...summarize(profile, s), cpuMs: Math.round((cpu.user + cpu.system) / 1000) };
80
+ } finally {
81
+ try { await session.post('Profiler.disable'); } catch { /* closing anyway */ }
82
+ session.disconnect();
83
+ }
84
+ })().finally(() => { this.#running = null; });
85
+ return this.#running;
86
+ }
87
+ }
88
+
89
+ /* MEASURED BY ITSELF (18-11, the owner: an intermittent stall needs nobody before the screen): every
90
+ WATCH_EVERY_MS the event loop's delay of the last minute is looked at; past SLOW_P50_MS, a measure is
91
+ taken (as Measure 10 s), at most once in AUTO_EVERY_MS (a measure costs a little itself), the last
92
+ AUTO_KEPT kept with when and why, in `file` (JsonFile: they outlive a restart). */
93
+ export const WATCH_EVERY_MS = 60_000;
94
+ export const SLOW_P50_MS = 200;
95
+ export const AUTO_EVERY_MS = 30 * 60_000;
96
+ export const AUTO_KEPT = 5;
97
+ export const AUTO_SECONDS = 10;
98
+ export class AutoProfile {
99
+ #profiler; #file; #now; #delay; #log; #last = 0; #timer = null;
100
+ /* `delay()`: the loop's delay of the last minute, { p50, p99 } in ms, then started again (a histogram of its own). */
101
+ constructor({ profiler, file, now = () => Date.now(), delay, log = (line) => console.log(line) }) {
102
+ this.#profiler = profiler; this.#file = file; this.#now = now; this.#delay = delay; this.#log = log;
103
+ const kept = this.kept(); this.#last = kept[0] ? Date.parse(kept[0].at) || 0 : 0;
104
+ }
105
+ kept() { const v = this.#file?.get(); return Array.isArray(v?.profiles) ? v.profiles : []; }
106
+ start(everyMs = WATCH_EVERY_MS) { this.#timer = setInterval(() => { void this.check(); }, everyMs); this.#timer.unref?.(); return this; }
107
+ stop() { clearInterval(this.#timer); }
108
+ async check() {
109
+ const d = this.#delay();
110
+ if (!d || !(d.p50 > SLOW_P50_MS)) return null;
111
+ if (this.#now() - this.#last < AUTO_EVERY_MS) return null;
112
+ this.#last = this.#now();
113
+ const why = `loop p50 ${d.p50} ms, p99 ${d.p99} ms over the last minute`;
114
+ this.#log(`profile: measuring ${AUTO_SECONDS} s by itself (${why})`);
115
+ try {
116
+ const p = await this.#profiler.profile(AUTO_SECONDS);
117
+ const entry = { at: new Date(this.#last).toISOString(), why, ...p };
118
+ this.#file?.set({ profiles: [entry, ...this.kept()].slice(0, AUTO_KEPT) });
119
+ this.#log(`profile: ${p.self.slice(0, 5).map((f) => `${f.fn} ${f.ms}ms ${f.at}`).join('; ')}`);
120
+ return entry;
121
+ } catch (error) { this.#log(`profile: not measured (${error?.message ?? error})`); return null; }
122
+ }
123
+ }
@@ -6,6 +6,9 @@
6
6
  * read(source, span) { source, span, text, lines, cut } -- what looks like a
7
7
  * secret masked: a value after password=, token:, Bearer...;
8
8
  * any run of 32 letters and digits or more (a key, a token)
9
+ * `note`: why it may be short (the journal too slow, journalctl's last word)
10
+ * load() the host commands of the last windows (vm.mjs HostTally): Settings, Load
11
+ * profile(seconds) this server sampled by its own profiler (profile.mjs): what holds it
9
12
  * restart() this server starts again in two seconds (its machines go on)
10
13
  */
11
14
  import { Refusal } from './conversations.mjs';
@@ -27,9 +30,20 @@ export function mask(text) {
27
30
  export const WAIT_MS = 12_000;
28
31
  export const KEPT_MS = 120_000;
29
32
 
33
+ /* Sudo's and PAM's lines for each call of the host program: a line a second on a busy server, nothing to read
34
+ (the host program leaves them out too: these are for one older than it). */
35
+ export const NOISE = / (sudo|pkexec)\[\d+\]: | pam_unix\((sudo|sudo-i|pkexec):session\)/;
36
+ /* The last line of what it said, without the host program's REFUSED:. */
37
+ const lastWord = (text) => String(text ?? '').trim().split('\n').pop()?.replace(/^(REFUSED|NOTE): /, '').slice(0, 200) ?? '';
38
+
30
39
  export class ServerLogs {
31
- #host; #reads = new Map(); #now;
32
- constructor({ host, now = () => Date.now() }) { this.#host = host; this.#now = now; }
40
+ #host; #reads = new Map(); #now; #load; #profiler;
41
+ constructor({ host, now = () => Date.now(), load = () => ({ everyMs: 0, windows: [] }), profiler = null }) { this.#host = host; this.#now = now; this.#load = load; this.#profiler = profiler; }
42
+ load() { return this.#load(); }
43
+ profile(seconds) {
44
+ if (!this.#profiler) throw new Refusal(404, 'The profiler is not available on this server.');
45
+ return this.#profiler.profile(seconds);
46
+ }
33
47
 
34
48
  /* The same read asked again while it runs is the same read; once done, kept a moment for
35
49
  the page that comes back for it. Resolves { pending: true } past `wait`. */
@@ -54,13 +68,19 @@ export class ServerLogs {
54
68
  if (!SOURCES.includes(source)) throw new Refusal(400, `Not a source of logs: say one of ${SOURCES.join(', ')}.`);
55
69
  if (!SPANS.includes(String(span))) throw new Refusal(400, 'Not a span: 10 minutes (10m), 1, 6, 24 or 168 hours, or since the server started (boot).');
56
70
  const r = await this.#host(['server', 'logs', source, String(span)], { timeoutMs: 120_000, maxBytes: TEXT_MAX * 2 });
57
- if (r.code !== 0) throw new Refusal(502, `The logs could not be read: ${String(r.stderr ?? '').trim().split('\n').pop()?.replace(/^REFUSED: /, '').slice(0, 200) || `exit ${r.code}`}`);
71
+ if (r.code !== 0) {
72
+ const why = r.timedOut ? 'no answer in 120 s' : r.tooLong ? 'more than 8 MB' : lastWord(r.stderr) || `exit ${r.code}`;
73
+ throw new Refusal(502, `The logs could not be read: ${why}`);
74
+ }
75
+ /* What may make it short (the host program's NOTE: lines): said beside it. */
76
+ const note = String(r.stderr ?? '').split('\n').filter((l) => l.startsWith('NOTE: ')).map((l) => l.slice(6).slice(0, 200)).join('; ') || null;
58
77
  let text = String(r.stdout ?? '');
78
+ if (NOISE.test(text)) text = text.split('\n').filter((l) => !NOISE.test(l)).join('\n');
59
79
  /* The newest kept when there is too much: they matter most. */
60
80
  const cut = text.length > TEXT_MAX;
61
81
  if (cut) text = text.slice(text.length - TEXT_MAX).replace(/^[^\n]*\n/, '');
62
82
  text = mask(text);
63
- return { source, span: String(span), text, lines: text ? text.split('\n').filter(Boolean).length : 0, cut };
83
+ return { source, span: String(span), text, lines: text ? text.split('\n').filter(Boolean).length : 0, cut, ...(note ? { note } : {}) };
64
84
  }
65
85
  async restart() {
66
86
  const r = await this.#host(['server', 'restart']);
@@ -57,6 +57,14 @@ export const SETTINGS_WORDS_FR = {
57
57
  'set-binders-max': 'Les agents en font {n} au plus', 'set-admin-1': '1 administrateur', 'set-admins': '{n} administrateurs',
58
58
  'set-backup-now': 'Exporter · importer', 'set-git-key': '1 clé git', 'set-git-keys': '{n} clés git', 'set-restart': 'redémarrer',
59
59
  'set-logs-now': 'Clavarium, machines, système',
60
+ /* Diagnostics › Charge (vm.mjs HostTally): les commandes à l'hôte, par fenêtre de 5 minutes. */
61
+ 'set-ch-s-load': 'Charge', 'set-load-about': 'Commandes à l\'hôte, par 5 minutes', 'set-load-copy': 'Copier',
62
+ 'set-load-open': 'maintenant', 'set-load-line': '{n} commandes · {s} s', 'set-load-loop': 'boucle {p50}/{p99} ms',
63
+ 'set-load-profile': 'Mesurer 10 s', 'set-load-profiling': 'Mesure en cours…', 'set-load-cpu': 'processeur {p} %', 'set-load-auto': 'Mesuré seul à {at}',
64
+ 'set-load-none': 'Rien de compté pour le moment', 'set-load-unread': 'Illisible pour le moment', 'set-load-copied': 'Copié',
65
+ /* Mises à jour: sudo discret (deploy/updater.mjs ensureQuietSudo). */
66
+ 'set-sudo-on': 'Sudo discret : oui ({setting})', 'set-sudo-off': 'Sudo discret : non appliqué : {why}',
67
+ 'set-sudo-seen': '{n} lignes sudo en 10 min',
60
68
  'set-dict-backup': 'Secours en service', 'set-dict-expired': 'Clé expirée', 'set-dict-with-backup': 'avec secours', 'set-dict-server': 'réglée sur le serveur',
61
69
  'set-offline': 'hors ligne',
62
70
  'set-device': '1 appareil', 'set-devices': '{n} appareils', 'set-no-device': 'Aucun appareil', 'set-chat': 'Chat',
@@ -95,11 +103,12 @@ export const SETTINGS_WORDS_FR = {
95
103
  'set-apikeys-never': 'Jamais', 'set-apikeys-cancel': 'Annuler', 'set-apikeys-create': 'Créer', 'set-apikeys-new': 'Nouvelle clé',
96
104
  'set-apikeys-never-by-key': 'Jamais : secrets, clés, comptes, droits', 'set-apikeys-scope-status': 'Son état (mémoire, disque, versions)',
97
105
  'set-apikeys-scope-jobs': 'Tâches : ce que fait Clavarium, ses journaux',
106
+ 'set-apikeys-scope-diagnostics': 'Diagnostics : charge, mesure, journaux',
98
107
  'set-apikeys-scope-create-rooms': 'Créer des salons', 'set-apikeys-act': 'Agir', 'set-apikeys-manage': 'Gérer',
99
108
  'set-apikeys-no-scope': 'Aucune portée', 'set-apikeys-by-you': 'par vous', 'set-apikeys-used': 'Utilisée {when}', 'set-apikeys-unused': 'Jamais utilisée',
100
109
  'set-apikeys-expired': 'Expirée', 'set-apikeys-expires-on': 'Expire le {date}', 'set-apikeys-no-expiry': 'N\'expire pas',
101
110
  'set-apikeys-created': 'Créée le {date}', 'set-apikeys-revoke': 'Révoquer', 'set-apikeys-revoke-q': 'Révoquer maintenant ?',
102
- 'set-apikeys-convs': 'Conversations', 'set-apikeys-convs-hint': 'Une par une : lire, parler ou agir', 'set-apikeys-off': 'Non',
111
+ 'set-apikeys-perms': 'Permissions', 'set-apikeys-convs': 'Conversations', 'set-apikeys-convs-hint': 'Une par une : lire, parler ou agir', 'set-apikeys-off': 'Non',
103
112
  'set-apikeys-read': 'Lire', 'set-apikeys-talk': 'Parler', 'set-apikeys-no-convs': 'Aucune conversation pour l\'instant',
104
113
  'set-apikeys-journal': 'Journal', 'set-apikeys-no-use': 'Aucun appel pour l\'instant',
105
114
  'set-apikeys-rooms': 'Salons', 'set-apikeys-rooms-hint': 'Un par un : lire, parler ou gérer', 'set-apikeys-no-rooms': 'Aucun salon pour l\'instant',
@@ -109,6 +109,9 @@ export class Updates {
109
109
  back: releases.filter((r) => !r.current && (VERSION.test(r.id) || LOCAL.test(r.id))).map((r) => ({ id: r.id, version: r.version })),
110
110
  /* What became of the relay at the updater's last turn (deploy/updater.mjs, relay.json beside the state). */
111
111
  relay: (() => { try { const r = JSON.parse(readFileSync(join(dirname(this.#state), 'relay.json'), 'utf8')); return RELAY_STATES.includes(r.state) ? { state: r.state, version: typeof r.version === 'string' ? r.version : null, why: typeof r.why === 'string' ? r.why.slice(0, 300) : null, at: typeof r.at === 'string' ? r.at : null } : null; } catch { return null; } })(),
112
+ /* Whether sudo keeps the host program's calls out of the system log, at the updater's last turn
113
+ (deploy/updater.mjs ensureQuietSudo, sudoSeen; sudo-quiet.json beside the state). */
114
+ sudoQuiet: (() => { try { const q = JSON.parse(readFileSync(join(dirname(this.#state), 'sudo-quiet.json'), 'utf8')); const str = (x, n) => (typeof x === 'string' ? x.slice(0, n) : null); return typeof q.on === 'boolean' ? { on: q.on, setting: str(q.setting, 60), why: str(q.why, 300), sudo: str(q.sudo, 80), lines10m: Number.isInteger(q.lines10m) ? q.lines10m : null, at: str(q.at, 40) } : null; } catch { return null; } })(),
112
115
  /* `fetch`: nothing of that version ran (npm could not fetch it): the page says it is tried again by itself
113
116
  (app.js, updates-retry-note). Left out before 17-11, every such failure read "It did not start here". */
114
117
  history: (Array.isArray(s.history) ? s.history : []).slice(0, HISTORY_SHOWN).map(({ at, action, from, to, result, why, log, fetch }) => ({ at, action, from, to, result, why: why ?? null, log: typeof log === 'string' ? log : null, fetch: fetch === true })),
package/server/vm.mjs CHANGED
@@ -8,6 +8,7 @@
8
8
  * before it gets here, and it is checked again, because this is where it
9
9
  * turns into a command. */
10
10
  import { execFile } from 'node:child_process';
11
+ import { monitorEventLoopDelay } from 'node:perf_hooks';
11
12
  import { isConversationName } from './names.mjs';
12
13
 
13
14
  /* Where the tool starts, in its VM. At the root rather than in a home
@@ -64,7 +65,9 @@ export function runner(prefix) {
64
65
  return (argv, { input, timeoutMs = 120_000, maxBytes = 8 * 1024 * 1024, onLine, signal } = {}) => new Promise((resolve) => {
65
66
  const all = [...prefix, ...argv];
66
67
  const child = execFile(all[0], all.slice(1), { timeout: timeoutMs, maxBuffer: maxBytes, encoding: 'utf8', ...(signal ? { signal } : {}) },
67
- (error, stdout, stderr) => resolve({ code: error ? (typeof error.code === 'number' ? error.code : 1) : 0, stdout, stderr, ...(error?.name === 'AbortError' ? { aborted: true } : {}) }));
68
+ (error, stdout, stderr) => resolve({ code: error ? (typeof error.code === 'number' ? error.code : 1) : 0, stdout, stderr, ...(error?.name === 'AbortError' ? { aborted: true } : {}),
69
+ /* Why it ended without an exit of its own: cut at `timeoutMs`, or more output than `maxBytes`. */
70
+ ...(error?.killed && error?.name !== 'AbortError' ? { timedOut: true } : {}), ...(error?.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER' ? { tooLong: true } : {}) }));
68
71
  if (onLine) {
69
72
  let rest = '';
70
73
  child.stdout.on('data', (chunk) => {
@@ -104,13 +107,68 @@ export class VmUnknown extends Error {
104
107
  constructor(why) { super(`The VM manager does not answer just now (${why}): try again in a moment.`); this.status = 503; this.retry = true; }
105
108
  }
106
109
 
110
+ /* HOW MUCH THIS SERVER ASKS OF THE HOST (17-11: the owner saw a page wait 10-15 s with an idle CPU --
111
+ every command to a machine goes through the VM manager, one after another): each command counted by
112
+ what it is, with its time; every COUNT_EVERY_MS the tally is said in the log, the busiest first, and
113
+ the last LOAD_KEPT windows kept for Settings (Diagnostics, Load: GET /api/server/load) -- the journal
114
+ may be too big to read there. `loop`: this server's own event loop measured too (its delay, p50/p99:
115
+ a server stalled by itself, not by the host). */
116
+ export const LOAD_KEPT = 12;
117
+ export class HostTally {
118
+ #now; #log; #kinds = new Map(); #from = 0; #beats = [0, 0]; #kept = []; #loop = null; #cpu = null;
119
+ constructor({ now = () => Date.now(), log = (line) => console.log(line), loop = false } = {}) {
120
+ this.#now = now; this.#log = log;
121
+ if (loop) { this.#loop = monitorEventLoopDelay({ resolution: 20 }); this.#loop.enable(); this.#cpu = process.cpuUsage(); }
122
+ }
123
+ /* A look of health answered by its heartbeat (`read`: no command; beat.mjs), or by a command after all. */
124
+ noteBeat(read) { this.#beats[read ? 0 : 1] += 1; }
125
+ /* `run`, each of its commands counted. */
126
+ wrap(run) {
127
+ return async (argv, options) => { const began = this.#now(); try { return await run(argv, options); } finally { this.count(argv, this.#now() - began); } };
128
+ }
129
+ count(argv, ms) {
130
+ const now = this.#now();
131
+ if (!this.#from) this.#from = now;
132
+ const kind = commandKind(argv); const was = this.#kinds.get(kind) ?? [0, 0, 0];
133
+ this.#kinds.set(kind, [was[0] + 1, was[1] + ms, Math.max(was[2], ms)]);
134
+ if (now - this.#from >= COUNT_EVERY_MS) this.#close(now);
135
+ }
136
+ #window(now) {
137
+ const kinds = [...this.#kinds].sort((a, b) => b[1][1] - a[1][1]).map(([kind, [count, ms, maxMs]]) => ({ kind, count, ms, maxMs }));
138
+ const ms = (n) => Math.round(n / 1e6);
139
+ const loop = this.#loop && this.#loop.count ? { p50: ms(this.#loop.percentile(50)), p99: ms(this.#loop.percentile(99)), max: ms(this.#loop.max) } : null;
140
+ /* Its own processor time over the window (user + system, ms), with the loop: a stalled loop with it high is this server's own work. */
141
+ if (loop && this.#cpu) { const c = process.cpuUsage(this.#cpu); loop.cpuMs = Math.round((c.user + c.system) / 1000); }
142
+ return { from: this.#from || now, to: now, commands: kinds.reduce((n, k) => n + k.count, 0), ms: kinds.reduce((n, k) => n + k.ms, 0), kinds, beats: { read: this.#beats[0], fallback: this.#beats[1] }, loop };
143
+ }
144
+ #close(now) {
145
+ const w = this.#window(now);
146
+ const beats = w.beats.read + w.beats.fallback ? `; beat read ${w.beats.read}x, fallback ${w.beats.fallback}x` : '';
147
+ const loop = w.loop ? `; loop p50 ${w.loop.p50}ms p99 ${w.loop.p99}ms${w.loop.cpuMs !== undefined ? ` cpu ${Math.round(w.loop.cpuMs / 1000)}s` : ''}` : '';
148
+ this.#log(`host: ${w.commands} commands in ${Math.round((now - w.from) / 60_000)} min, ${Math.round(w.ms / 1000)} s spent; ${w.kinds.slice(0, 8).map((k) => `${k.kind} ${k.count}x ${Math.round(k.ms / 1000)}s max ${Math.round(k.maxMs / 1000)}s`).join('; ')}${beats}${loop}`);
149
+ this.#kept = [{ ...w, kinds: w.kinds.slice(0, 20) }, ...this.#kept].slice(0, LOAD_KEPT);
150
+ this.#kinds = new Map(); this.#from = now; this.#beats = [0, 0]; this.#loop?.reset(); if (this.#cpu) this.#cpu = process.cpuUsage();
151
+ }
152
+ /* The windows, the newest first: the one under way (`open`), then the closed ones. A window past its
153
+ time with no command since is closed here: an idle server still says so. */
154
+ windows() {
155
+ const now = this.#now();
156
+ if (this.#from && now - this.#from >= COUNT_EVERY_MS) this.#close(now);
157
+ const open = { ...this.#window(now), open: true };
158
+ if (!this.#from) open.from = now;
159
+ return { everyMs: COUNT_EVERY_MS, windows: [{ ...open, kinds: open.kinds.slice(0, 20) }, ...this.#kept] };
160
+ }
161
+ }
162
+
107
163
  export class Vms {
108
164
  /* `run(argv, options)` reaches the host program; `prefix` is the same
109
165
  route as an argument vector, for the one caller that needs a terminal. */
110
- #ask; #snapshot = null; #asking = null; #changed = 0; #now; #freshMs; #machineOf; #userOf;
166
+ #ask; #snapshot = null; #asking = null; #changed = 0; #now; #freshMs; #machineOf; #userOf; tally;
111
167
  /* `freshMs`: how long one answer serves every caller (0: only those asking meanwhile). */
112
168
  /* `machineOf(conversation)`: the shared machine it lives in (#221), or nothing -- its own, `clv-<conversation>`. */
113
- constructor(run, prefix, { now = () => Date.now(), freshMs = STATES_FRESH_MS, machineOf = () => undefined, userOf = () => undefined } = {}) {
169
+ /* `tally`: where its commands are counted (HostTally), shared with the server's other commands to the host. */
170
+ constructor(run, prefix, { now = () => Date.now(), freshMs = STATES_FRESH_MS, machineOf = () => undefined, userOf = () => undefined, tally } = {}) {
171
+ this.tally = tally ?? new HostTally({ now });
114
172
  /* `userOf(conversation)`: its own user in a shared machine, { uid, gid } -- what its mounts are owned by there. */
115
173
  this.#ask = run; this.prefix = prefix; this.#now = now; this.#freshMs = freshMs; this.#machineOf = machineOf; this.#userOf = userOf;
116
174
  /* What changes a machine makes the states asked again (not taken from before it). */
@@ -122,23 +180,9 @@ export class Vms {
122
180
  };
123
181
  }
124
182
 
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
- every command to a machine goes through the VM manager, one after another): each command counted by
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; #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; }
131
- #count(argv, ms) {
132
- const now = this.#now();
133
- if (!this.#tallyFrom) this.#tallyFrom = now;
134
- this.#tally.set(commandKind(argv), [(this.#tally.get(commandKind(argv))?.[0] ?? 0) + 1, (this.#tally.get(commandKind(argv))?.[1] ?? 0) + ms, Math.max(this.#tally.get(commandKind(argv))?.[2] ?? 0, ms)]);
135
- if (now - this.#tallyFrom < COUNT_EVERY_MS) return;
136
- const rows = [...this.#tally].sort((a, b) => b[1][1] - a[1][1]);
137
- const all = rows.reduce((n, [, v]) => n + v[0], 0); const busy = rows.reduce((n, [, v]) => n + v[1], 0);
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];
141
- }
183
+ /* HOW MUCH THIS SERVER ASKS OF THE HOST: the tally (HostTally, below), its own unless one is given. */
184
+ noteBeat(read) { this.tally.noteBeat(read); }
185
+ #count(argv, ms) { this.tally.count(argv, ms); }
142
186
 
143
187
  /* EVERY MACHINE'S STATE, in one question to the VM manager, shared by every caller for a
144
188
  few seconds (and by those who ask while it is being asked). */
package/web/app.js CHANGED
@@ -8384,11 +8384,25 @@
8384
8384
  const more = el('div', 'apikey-more'); more.hidden = true;
8385
8385
  const open = async (kind) => {
8386
8386
  apiKeyOpen = apiKeyOpen?.id === k.id && apiKeyOpen.what === kind ? null : { id: k.id, what: kind };
8387
- for (const b of acts.querySelectorAll('button[data-act="convs"], button[data-act="rooms"], button[data-act="boxes"], button[data-act="binders"], button[data-act="journal"]')) b.setAttribute('aria-expanded', String(apiKeyOpen?.id === k.id && apiKeyOpen.what === b.dataset.act));
8387
+ for (const b of acts.querySelectorAll('button[data-act="scopes"], button[data-act="convs"], button[data-act="rooms"], button[data-act="boxes"], button[data-act="binders"], button[data-act="journal"]')) b.setAttribute('aria-expanded', String(apiKeyOpen?.id === k.id && apiKeyOpen.what === b.dataset.act));
8388
8388
  more.hidden = apiKeyOpen?.id !== k.id;
8389
8389
  more.replaceChildren();
8390
8390
  if (!apiKeyOpen || apiKeyOpen.id !== k.id) return;
8391
8391
  if (kind === 'journal') { more.dataset.what = 'journal'; await paintApiKeyJournal(more, k.id); return; }
8392
+ /* Its scopes of the server, ticked or not, changed afterwards (18-11). */
8393
+ if (kind === 'scopes') {
8394
+ more.dataset.what = 'scopes';
8395
+ for (const sc of got.scopes) {
8396
+ const l = el('label', 'check'); const box = document.createElement('input'); box.type = 'checkbox'; box.value = sc.id; box.checked = k.scopes.includes(sc.id);
8397
+ box.addEventListener('change', async () => {
8398
+ $('apikeys-error').hidden = true;
8399
+ try { await post(`${API}/apikeys/${k.id}/scopes`, { scope: sc.id, on: box.checked }); } catch (error) { $('apikeys-error').textContent = error.message; $('apikeys-error').hidden = false; }
8400
+ await paintApiKeys();
8401
+ });
8402
+ l.append(box, ' ', el('span', '', scopeWord(sc.id))); more.append(l);
8403
+ }
8404
+ return;
8405
+ }
8392
8406
  more.dataset.what = kind;
8393
8407
  if (kind === 'rooms' || kind === 'boxes' || kind === 'binders') {
8394
8408
  more.append(apiKeyOnePicker(kind, new Map((k[kind] ?? []).map((x) => [x.id, x.level])), async (ref, level) => {
@@ -8406,9 +8420,11 @@
8406
8420
  };
8407
8421
  const convs = el('button', '', uiSaid('set-apikeys-convs', 'Conversations')); convs.type = 'button'; convs.dataset.act = 'convs';
8408
8422
  const journal = el('button', '', uiSaid('set-apikeys-journal', 'Journal')); journal.type = 'button'; journal.dataset.act = 'journal';
8423
+ const perms = el('button', '', uiSaid('set-apikeys-perms', 'Permissions')); perms.type = 'button'; perms.dataset.act = 'scopes';
8424
+ perms.addEventListener('click', () => void open('scopes'));
8409
8425
  convs.addEventListener('click', () => void open('convs'));
8410
8426
  journal.addEventListener('click', () => void open('journal'));
8411
- acts.append(convs);
8427
+ acts.append(perms, convs);
8412
8428
  /* Rooms, voice boxes, binders: offered when there are some (or the key has some still). */
8413
8429
  for (const [kind, word] of [['rooms', uiSaid('set-apikeys-rooms', 'Rooms')], ['boxes', uiSaid('set-apikeys-boxes', 'Voice boxes')], ['binders', uiSaid('set-apikeys-binders', 'Binders')]]) {
8414
8430
  if (!apiKeyItems(kind).length && !(k[kind] ?? []).length) continue;
@@ -9063,6 +9079,15 @@
9063
9079
  relayBox.className = asks ? 'callout' : 'hint';
9064
9080
  relayBox.dataset.state = relay.state;
9065
9081
  }
9082
+ /* Whether sudo keeps the host program's calls out of the system log, at the updater's last turn: one line. */
9083
+ const q = u.sudoQuiet;
9084
+ $('updates-sudo').hidden = !q;
9085
+ if (q) {
9086
+ const seen = [Number.isInteger(q.lines10m) ? uiSaid('set-sudo-seen', '{n} sudo lines in 10 min', { n: q.lines10m }) : '', q.sudo ?? ''].filter(Boolean).join(' · ');
9087
+ $('updates-sudo').textContent = [q.on ? uiSaid('set-sudo-on', 'Sudo quiet: on ({setting})', { setting: q.setting ?? '' }) : uiSaid('set-sudo-off', 'Sudo quiet: not applied: {why}', { why: q.why ?? '?' }), seen].filter(Boolean).join(' · ');
9088
+ /* Said loud when the journal still gets them: a line a second or more is the trouble seen 17-11. */
9089
+ $('updates-sudo').className = !q.on || q.lines10m >= 300 ? 'callout' : 'hint';
9090
+ }
9066
9091
  paintUpdatesWhen(u);
9067
9092
  void paintCertificate();
9068
9093
  for (const id of ['updates-check', 'updates-settings', 'updates-back']) $(id).hidden = !u.installed;
@@ -9642,6 +9667,68 @@
9642
9667
  const text = eventsShown.map((e) => `${e.at}\t${e.kind}\t${e.conversation ?? ''}\t${e.text}${e.who ? `\t${e.who}` : ''}`).join('\n');
9643
9668
  try { await navigator.clipboard.writeText(text); $('events-said').textContent = `Copied: ${eventsShown.length} lines.`; } catch { $('events-said').textContent = 'The clipboard is not available here.'; }
9644
9669
  });
9670
+ /* LOAD: what this server asked of the host, by 5-minute window, the busiest commands first, and its own
9671
+ event loop (server/vm.mjs HostTally; GET /api/server/load) -- when the journal is too big to read. */
9672
+ let loadShown = null; let loadTimer;
9673
+ const loadClock = (at) => new Date(at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false });
9674
+ const loadSec = (ms) => (ms >= 10_000 ? Math.round(ms / 1000) : Math.round(ms / 100) / 10);
9675
+ const loadKind = (k) => `${k.kind} ${k.count}× ${loadSec(k.ms)} s (max ${loadSec(k.maxMs)} s)`;
9676
+ const loadHead = (w) => [`${loadClock(w.from)}–${w.open ? uiSaid('set-load-open', 'now') : loadClock(w.to)}`,
9677
+ uiSaid('set-load-line', '{n} commands · {s} s', { n: w.commands, s: loadSec(w.ms) }),
9678
+ w.loop ? uiSaid('set-load-loop', 'loop {p50}/{p99} ms', { p50: w.loop.p50, p99: w.loop.p99 }) : '',
9679
+ w.loop?.cpuMs !== undefined && w.to > w.from ? uiSaid('set-load-cpu', 'CPU {p} %', { p: Math.round((100 * w.loop.cpuMs) / (w.to - w.from)) }) : ''].filter(Boolean).join(' · ');
9680
+ async function paintLoad() {
9681
+ clearTimeout(loadTimer);
9682
+ if (!$('settings-load-top').open) return;
9683
+ const got = await fetch(`${API}/server/load`).then((r) => (r.ok ? r.json() : null)).catch(() => null);
9684
+ if (!got) { $('load-said').textContent = uiSaid('set-load-unread', 'Unreadable for now'); return; }
9685
+ loadShown = got;
9686
+ const rows = (got.windows ?? []).map((w) => {
9687
+ const row = el('div', 'load-row');
9688
+ row.append(el('span', '', loadHead(w)));
9689
+ if (w.kinds?.length) row.append(el('span', 'load-kinds', w.kinds.slice(0, 3).map(loadKind).join(' · ')));
9690
+ return row;
9691
+ });
9692
+ $('load-list').replaceChildren(...rows);
9693
+ /* The measures it took by itself, the newest first: when, why, the functions that held it most. */
9694
+ const auto = (got.profiles ?? []).map((p) => {
9695
+ const row = el('div', 'load-row');
9696
+ row.append(el('span', '', `${uiSaid('set-load-auto', 'Measured by itself at {at}', { at: `${new Date(p.at).toLocaleDateString([], { day: 'numeric', month: 'short' })} ${loadClock(p.at)}` })} · ${p.why}`));
9697
+ row.append(el('span', 'load-kinds', (p.self ?? []).slice(0, 3).map((f) => `${f.fn} ${f.ms} ms`).join(' · ')));
9698
+ return row;
9699
+ });
9700
+ $('load-auto').replaceChildren(...auto); $('load-auto').hidden = !auto.length;
9701
+ const any = (got.windows ?? []).some((w) => w.commands);
9702
+ $('load-said').textContent = any ? '' : uiSaid('set-load-none', 'Nothing counted yet');
9703
+ $('load-copy').hidden = !rows.length;
9704
+ loadTimer = setTimeout(() => { void paintLoad(); }, 30_000);
9705
+ }
9706
+ $('settings-load-top').addEventListener('toggle', () => { void paintLoad(); });
9707
+ $('load-copy').addEventListener('click', async () => {
9708
+ if (!loadShown) return;
9709
+ /* All of it, as text: each window, then every kind it counted. */
9710
+ const line = (f) => ` ${f.ms} ms ${f.fn} ${f.at}`;
9711
+ const autoText = (loadShown.profiles ?? []).map((p) => [`auto ${p.at} · ${p.why} · cpu ${p.cpuMs} ms · idle ${p.idleMs} · gc ${p.gcMs}`, 'self:', ...(p.self ?? []).map(line), 'with what they call:', ...(p.total ?? []).map(line), ''].join('\n'));
9712
+ const text = [...($('load-profile-out').hidden ? [] : [$('load-profile-out').textContent, '']), ...autoText, ...(loadShown.windows ?? []).map((w) => [loadHead(w), ...(w.kinds ?? []).map((k) => ` ${loadKind(k)}`),
9713
+ ...(w.beats && (w.beats.read || w.beats.fallback) ? [` beat read ${w.beats.read}×, fallback ${w.beats.fallback}×`] : []),
9714
+ ...(w.loop ? [` loop max ${w.loop.max} ms`] : [])].join('\n'))].join('\n');
9715
+ try { await navigator.clipboard.writeText(text); $('load-said').textContent = uiSaid('set-load-copied', 'Copied'); } catch { $('load-said').textContent = 'The clipboard is not available here.'; }
9716
+ });
9717
+ /* WHAT HOLDS THE SERVER: 10 s of its own profiler, the functions that took the most time, as text
9718
+ (server/profile.mjs) -- copied with the windows. */
9719
+ $('load-profile').addEventListener('click', async () => {
9720
+ const out = $('load-profile-out'); $('load-profile').disabled = true;
9721
+ $('load-said').textContent = uiSaid('set-load-profiling', 'Measuring…');
9722
+ try {
9723
+ const r = await fetch(`${API}/server/profile`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ seconds: 10 }) });
9724
+ const p = await r.json().catch(() => null);
9725
+ if (!r.ok || !p) { $('load-said').textContent = p?.error ?? `Not measured (${r.status}).`; return; }
9726
+ const line = (f) => ` ${f.ms} ms ${f.fn} ${f.at}`;
9727
+ out.textContent = [`profile ${p.seconds} s · cpu ${p.cpuMs} ms · sampled ${p.sampledMs} ms · idle ${p.idleMs} · gc ${p.gcMs} · program ${p.programMs}`,
9728
+ 'self:', ...p.self.map(line), 'with what they call:', ...p.total.map(line)].join('\n');
9729
+ out.hidden = false; $('load-copy').hidden = false; $('load-said').textContent = '';
9730
+ } catch { $('load-said').textContent = 'Not measured.'; } finally { $('load-profile').disabled = false; }
9731
+ });
9645
9732
  /* WHAT THE SERVER'S PROGRAMS SAID: one source over a span, to read, copy whole or keep as a file. */
9646
9733
  let logsShown = null;
9647
9734
  $('logs-show').addEventListener('click', async () => {
@@ -9661,7 +9748,7 @@
9661
9748
  logsShown = body;
9662
9749
  $('logs-text').textContent = body.text || '';
9663
9750
  $('logs-text').hidden = !body.text; $('logs-acts').hidden = !body.text;
9664
- $('logs-said').textContent = body.lines ? `${body.lines} line${body.lines > 1 ? 's' : ''}${body.cut ? ' (the newest only: there were more)' : ''}.` : 'Nothing was said over that span.';
9751
+ $('logs-said').textContent = `${body.lines ? `${body.lines} line${body.lines > 1 ? 's' : ''}${body.cut ? ' (the newest only: there were more)' : ''}.` : 'Nothing was said over that span.'}${body.note ? ` ${body.note}.` : ''}`;
9665
9752
  /* The newest at the bottom, in sight. */
9666
9753
  $('logs-text').scrollTop = $('logs-text').scrollHeight;
9667
9754
  } catch (error) { $('logs-said').textContent = error.message; }
package/web/index.html CHANGED
@@ -1312,6 +1312,8 @@
1312
1312
  <div class="set-row updates-head"><div class="status-line" id="updates-line"><b id="updates-version">…</b><span id="updates-state" class="hint" role="status"></span></div><div class="set-control"><button type="button" id="updates-check">Check now</button></div></div>
1313
1313
  <p id="updates-news" class="updates-news callout" hidden></p>
1314
1314
  <div id="updates-relay" class="hint" hidden></div>
1315
+ <!-- Whether sudo keeps the host program's calls out of the system log (deploy/updater.mjs ensureQuietSudo). -->
1316
+ <p id="updates-sudo" class="hint" hidden></p>
1315
1317
  <div class="action-row" id="updates-offer" hidden><span class="hint" id="updates-retry-note" hidden></span><button type="button" id="updates-retry-no" hidden>Cancel</button><button type="button" id="updates-retry-yes" class="primary" hidden>Try again</button><button type="button" id="updates-apply" class="primary"></button></div>
1316
1318
  <div id="updates-settings" class="set-rows">
1317
1319
  <div class="set-row"><div class="set-what"><label for="updates-mode">Mode</label><small>When updates are installed</small></div><div class="set-control"><select id="updates-mode"><option value="auto">Automatic, in a window</option><option value="asap">As soon as out</option><option value="ask">Ask me</option><option value="off">Off</option></select></div></div>
@@ -1368,6 +1370,21 @@
1368
1370
  <p class="hint" id="jobs-said" role="status"></p>
1369
1371
  </div>
1370
1372
  </details>
1373
+ <!-- LOAD: what this server asked of the host, by 5-minute window, and its own event loop (server/vm.mjs
1374
+ HostTally; GET /api/server/load) -- readable when the journal is too big to read. -->
1375
+ <details class="chapter" id="settings-load-top" data-chapter="s-load">
1376
+ <summary><span class="chapter-title" data-said="set-ch-s-load">Load</span><span class="chapter-about" data-said="set-load-about">Host commands, by 5 minutes.</span></summary>
1377
+ <div class="chapter-body">
1378
+ <div id="load-list" class="load-list" aria-live="polite"></div>
1379
+ <p class="hint" id="load-said" role="status"></p>
1380
+ <div class="row"><button type="button" id="load-copy" data-said="set-load-copy" hidden>Copy</button>
1381
+ <button type="button" id="load-profile" data-said="set-load-profile">Measure 10 s</button></div>
1382
+ <!-- What holds this server, from its own profiler (server/profile.mjs; POST /api/server/profile). -->
1383
+ <pre id="load-profile-out" class="load-profile" hidden></pre>
1384
+ <!-- The measures it took by itself when its loop was slow (server/profile.mjs AutoProfile). -->
1385
+ <div id="load-auto" class="load-list" hidden></div>
1386
+ </div>
1387
+ </details>
1371
1388
  <!-- WHAT THE SERVER'S PROGRAMS SAID, to read, copy whole or keep (server/serverlogs.mjs);
1372
1389
  and this server started again. -->
1373
1390
  <details class="chapter" id="settings-logs-top" data-chapter="s-logs">
package/web/style.css CHANGED
@@ -1762,6 +1762,11 @@ svg.u-spark .u-oom { fill: var(--danger); stroke: var(--panel); stroke-width: 1.
1762
1762
  /* Settings, Jobs: one line each, as in the badge's list; opened, its log, one line a step. */
1763
1763
  .jobs-list { display: flex; flex-direction: column; margin: 8px 0; font-size: .875rem; }
1764
1764
  .jobs-list h3 { margin: 10px 0 2px; font-size: .8125rem; color: var(--ink2); }
1765
+ /* Settings, Diagnostics, Load: one window a row, its busiest commands under it, small. */
1766
+ .load-list { display: flex; flex-direction: column; gap: 6px; margin: 8px 0; font-size: .875rem; }
1767
+ .load-list .load-row { display: flex; flex-direction: column; min-width: 0; }
1768
+ .load-list .load-kinds { font-size: .75rem; color: var(--ink2); overflow-wrap: anywhere; }
1769
+ .load-profile { font-size: .75rem; white-space: pre-wrap; overflow-wrap: anywhere; max-height: 24rem; overflow: auto; margin: 8px 0; }
1765
1770
  .job-line { border-bottom: 1px solid var(--line); }
1766
1771
  .job-line > summary { display: grid; grid-template-columns: 16px 1fr; gap: 2px 8px; padding: 4px 0; cursor: pointer; list-style: none; }
1767
1772
  .job-line > summary::-webkit-details-marker { display: none; }