clavarium 0.2.91-next.1 → 0.2.92-beta.2
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/launch/guichet.mjs +190 -0
- package/config/tools.json +50 -0
- package/deploy/clavarium-host +55 -1
- package/npm-shrinkwrap.json +14 -14
- package/package.json +4 -4
- package/server/accounts.mjs +78 -2
- package/server/api.mjs +29 -1
- package/server/binders.mjs +6 -3
- package/server/capacity.mjs +55 -4
- package/server/conversations.mjs +39 -0
- package/server/gitkeeper.mjs +5 -1
- package/server/main.mjs +14 -1
- package/server/secret-scan.mjs +12 -2
- package/server/talk.mjs +5 -0
- package/server/tethers.mjs +44 -2
- package/server/tools.mjs +3 -1
- package/server/vm.mjs +4 -1
- package/web/app.js +513 -46
- package/web/index.html +37 -2
- package/web/style.css +78 -1
package/server/capacity.mjs
CHANGED
|
@@ -49,6 +49,13 @@ export const RESERVE_DISK_MAX_MB = 1024 * 1024;
|
|
|
49
49
|
export const RESERVE_MEMORY_MAX_MB = 256 * 1024;
|
|
50
50
|
export const ROOM_MS = 10_000;
|
|
51
51
|
export const USAGE_MS = 5 * 60_000;
|
|
52
|
+
/* A sleeping machine whose qemu still holds at least this much host memory is a
|
|
53
|
+
suspend that did not free it (see the host program's `vm suspend`); the watch
|
|
54
|
+
reclaims it. */
|
|
55
|
+
export const RECLAIM_MIN_MB = 128;
|
|
56
|
+
/* The same machine is not reclaimed again within this, so a stubborn one (rare,
|
|
57
|
+
needs a VM-manager restart) is reported once, not looped on. */
|
|
58
|
+
export const RECLAIM_EVERY_MS = 30 * 60_000;
|
|
52
59
|
/* The page shows its small gauge when disk or memory is fuller than this, or
|
|
53
60
|
when what is free is under this many times the reserve. */
|
|
54
61
|
export const HIGH_PERCENT = 85;
|
|
@@ -92,7 +99,7 @@ const percent = (part, all) => (all > 0 ? Math.round((part / all) * 100) : 0);
|
|
|
92
99
|
export class Capacity {
|
|
93
100
|
/* What the machines take on their disk, as last measured (MB), or undefined. */
|
|
94
101
|
machinesUsedMb() { const u = this.#usage; if (!u) return undefined; return Object.values(u.machines ?? {}).reduce((a, b) => a + b, 0) + (u.shelf ?? 0) + (u.images ?? 0); }
|
|
95
|
-
#run; #store; #conversations; #shelf; #now; #roomMs; #sleep; #alert; #say; #short = { disk: false, memory: false }; #room = null; #roomAt = -Infinity; #usage = null; #usageAt = -Infinity; #going = null; #measuring = null;
|
|
102
|
+
#run; #store; #conversations; #shelf; #now; #roomMs; #sleep; #alert; #say; #reclaim; #reclaimEveryMs; #sweeping = false; #short = { disk: false, memory: false }; #room = null; #roomAt = -Infinity; #usage = null; #usageAt = -Infinity; #going = null; #measuring = null;
|
|
96
103
|
|
|
97
104
|
/* `run(argv)`: the host program. `store`: where the reserve is kept.
|
|
98
105
|
`conversations`: what each machine was given. `shelf`: how large a
|
|
@@ -100,8 +107,8 @@ export class Capacity {
|
|
|
100
107
|
/* `roomMs`: how long what is free is taken as known (ROOM_MS). */
|
|
101
108
|
/* `sleep(name)`, `alert(payload)`, `say(name, text)`: what watch() does
|
|
102
109
|
when what is free falls under the reserve. */
|
|
103
|
-
constructor({ run, store, conversations, shelf = null, now = () => Date.now(), roomMs = ROOM_MS, sleep = null, alert = null, say = null }) {
|
|
104
|
-
this.#roomMs = roomMs; this.#sleep = sleep; this.#alert = alert; this.#say = say;
|
|
110
|
+
constructor({ run, store, conversations, shelf = null, now = () => Date.now(), roomMs = ROOM_MS, sleep = null, alert = null, say = null, reclaim = null, reclaimEveryMs = RECLAIM_EVERY_MS }) {
|
|
111
|
+
this.#roomMs = roomMs; this.#sleep = sleep; this.#alert = alert; this.#say = say; this.#reclaim = reclaim; this.#reclaimEveryMs = reclaimEveryMs;
|
|
105
112
|
this.#run = run; this.#store = store; this.#conversations = conversations; this.#shelf = shelf; this.#now = now;
|
|
106
113
|
}
|
|
107
114
|
|
|
@@ -288,9 +295,53 @@ export class Capacity {
|
|
|
288
295
|
return done;
|
|
289
296
|
}
|
|
290
297
|
|
|
298
|
+
/* WATCHED too, and on its own: machines that are ASLEEP (not awake) yet whose
|
|
299
|
+
qemu still holds the host RAM -- a suspend that did not end the process,
|
|
300
|
+
including ones left stuck before this ran. Each is freed through the host
|
|
301
|
+
program (`vm reclaim`: wake+resleep, then a clean stop if needed), the owner
|
|
302
|
+
told, and not tried again within reclaimEveryMs, so a stubborn one (rare,
|
|
303
|
+
the VM manager would need a restart) is reported once, not looped on. Only
|
|
304
|
+
asleep machines are touched; the others are never disturbed, and the VM
|
|
305
|
+
manager is never restarted. Resolves with what was reclaimed. */
|
|
306
|
+
async reclaimSleepers() {
|
|
307
|
+
if (!this.#reclaim || this.#sweeping) return [];
|
|
308
|
+
this.#sweeping = true;
|
|
309
|
+
try {
|
|
310
|
+
const f = this.#figures(await this.room({ fresh: true }).catch(() => null));
|
|
311
|
+
if (!f) return [];
|
|
312
|
+
const awake = new Set(this.#conversations.awake?.() ?? []);
|
|
313
|
+
const holding = f.machines.filter((m) => m.name && !m.shelf && !awake.has(m.name) && m.rssMb >= RECLAIM_MIN_MB);
|
|
314
|
+
if (!holding.length) return [];
|
|
315
|
+
const now = this.#now();
|
|
316
|
+
const at = this.#store.get('reclaim')?.at ?? {};
|
|
317
|
+
const done = [];
|
|
318
|
+
for (const m of holding) {
|
|
319
|
+
if (at[m.name] && now - at[m.name] < this.#reclaimEveryMs) continue;
|
|
320
|
+
at[m.name] = now;
|
|
321
|
+
this.#store.put({ name: 'reclaim', at });
|
|
322
|
+
const held = m.rssMb;
|
|
323
|
+
const how = await Promise.resolve(this.#reclaim(m.name)).then((x) => String(x || ''), () => '');
|
|
324
|
+
const by = how.includes('resleep') ? ' by waking it and putting it back to sleep'
|
|
325
|
+
: how.includes('stop') ? ' with a clean stop (it will boot when you open it)'
|
|
326
|
+
: '';
|
|
327
|
+
const after = this.#figures(await this.room({ fresh: true }).catch(() => null));
|
|
328
|
+
const freed = !after?.machines.some((x) => x.name === m.name && !awake.has(x.name) && x.rssMb >= RECLAIM_MIN_MB);
|
|
329
|
+
this.#alert?.(freed
|
|
330
|
+
? { title: "Reclaimed a sleeping machine's memory", body: `${m.name} was asleep but still held ${gb(held)} (its sleep had not freed it); its memory was reclaimed${by}.`, url: '/?open=settings&at=resources' }
|
|
331
|
+
: { title: 'A sleeping machine still holds memory', body: `${m.name} was asleep but still held ${gb(held)} and could not be freed; the VM manager may need a restart.`, url: '/?open=settings&at=resources' });
|
|
332
|
+
this.#say?.(m.name, freed
|
|
333
|
+
? `This machine was asleep but still held ${gb(held)} of memory (its sleep had not freed it). Its memory was reclaimed${by}; it still wakes when you open it.`
|
|
334
|
+
: `This machine was asleep but still held ${gb(held)} of memory, and it could not be freed automatically — the VM manager may need a restart.`);
|
|
335
|
+
done.push({ name: m.name, heldMb: held, freed });
|
|
336
|
+
}
|
|
337
|
+
return done;
|
|
338
|
+
} finally { this.#sweeping = false; }
|
|
339
|
+
}
|
|
340
|
+
|
|
291
341
|
/* Watches every `everyMs`; returns what stops it. */
|
|
292
342
|
start(everyMs = WATCH_MS) {
|
|
293
|
-
const
|
|
343
|
+
const tick = () => { void this.watch().catch(() => {}).finally(() => { void this.reclaimSleepers().catch(() => {}); }); };
|
|
344
|
+
const timer = setInterval(tick, everyMs);
|
|
294
345
|
timer.unref?.();
|
|
295
346
|
return () => clearInterval(timer);
|
|
296
347
|
}
|
package/server/conversations.mjs
CHANGED
|
@@ -608,6 +608,18 @@ export class Conversations {
|
|
|
608
608
|
return this.#store.get(name);
|
|
609
609
|
}
|
|
610
610
|
|
|
611
|
+
/* WHICH BINDER ITS CHAT SHOWS BESIDE IT (the side panel), the same on every device:
|
|
612
|
+
'' for the automatic choice (the first binder of batches it was given), '-' for none,
|
|
613
|
+
else a binder's id. Which binders it was given is Binder's: one it no longer has
|
|
614
|
+
falls back to the automatic choice on the page. */
|
|
615
|
+
setTasksBinder(name, given) {
|
|
616
|
+
const c = this.#store.get(name);
|
|
617
|
+
if (!c) throw new Refusal(404, 'No such conversation.');
|
|
618
|
+
if (typeof given !== 'string' || given.length > 100 || !/^(|-|[a-z0-9][a-z0-9._-]*)$/.test(given)) throw new Refusal(400, 'Give a binder\'s id, "-" for none, or nothing for the automatic choice.');
|
|
619
|
+
this.#store.patch(name, { tasksBinder: given || undefined });
|
|
620
|
+
return this.#store.get(name);
|
|
621
|
+
}
|
|
622
|
+
|
|
611
623
|
/* THE NAME A PERSON READS, changed at any time; its identifier stays.
|
|
612
624
|
Kept only when it differs from the identifier: a conversation made
|
|
613
625
|
before free names is read by its identifier, and nothing is rewritten. */
|
|
@@ -1024,6 +1036,11 @@ export class Conversations {
|
|
|
1024
1036
|
const alive = await this.#vms.exec(name, ['tmux', '-L', SOCKET, 'has-session', '-t', `=${SESSION}`]);
|
|
1025
1037
|
/* true: the tool is still there, only the channel to it dropped. */
|
|
1026
1038
|
if (alive.code === 0) return true;
|
|
1039
|
+
/* Before its machine stops (and its kernel's memory of the night with it): why the tool
|
|
1040
|
+
ended, kept on the conversation and said -- a person without access to the server
|
|
1041
|
+
sees it in Machine, and is told at once when it was cut for lack of memory. */
|
|
1042
|
+
const report = await this.exitReport(name).catch(() => null);
|
|
1043
|
+
if (report) { this.#store.patch(name, { lastExit: report }); try { this.onToolExit?.(name, report); } catch { /* telling is best effort */ } }
|
|
1027
1044
|
this.#cancelStop(name);
|
|
1028
1045
|
const timer = setTimeout(() => {
|
|
1029
1046
|
this.#timers.delete(name);
|
|
@@ -1034,6 +1051,28 @@ export class Conversations {
|
|
|
1034
1051
|
return false;
|
|
1035
1052
|
}
|
|
1036
1053
|
|
|
1054
|
+
/* WHY ITS TOOL ENDED, read inside the machine while it still runs: the kernel's kills for
|
|
1055
|
+
lack of memory since it started (with the program's name), its memory, and the last
|
|
1056
|
+
lines of the tool's own log (`logs` in config/tools.json). Read as the machine's
|
|
1057
|
+
ordinary user; dmesg through sudo when it may. Nothing is changed. */
|
|
1058
|
+
async exitReport(name) {
|
|
1059
|
+
const c = this.#store.get(name);
|
|
1060
|
+
if (!c) throw new Refusal(404, 'No such conversation.');
|
|
1061
|
+
if (await this.#vms.state(name) !== 'Running') throw new Refusal(409, 'Its machine is not running.');
|
|
1062
|
+
const tool = this.#tools.find((t) => t.id === c.tool);
|
|
1063
|
+
const logs = Array.isArray(tool?.logs) ? tool.logs.filter((d) => /^[A-Za-z0-9._/-]+$/.test(d)) : [];
|
|
1064
|
+
const script = [
|
|
1065
|
+
'( sudo -n dmesg -T 2>/dev/null || dmesg -T 2>/dev/null ) | grep -E "Killed process|Out of memory|Memory cgroup out of memory" | tail -n 4 | sed "s/^/oom /"',
|
|
1066
|
+
'awk \'/^MemTotal:/{print "memory", int($2/1024)}\' /proc/meminfo',
|
|
1067
|
+
'for d in "$@"; do f=$(ls -t "$HOME/$d"/*.log 2>/dev/null | head -1); [ -n "$f" ] && { echo "logfile $f"; tail -n 25 "$f" | cut -c1-300 | sed "s/^/log /"; }; done; true',
|
|
1068
|
+
].join('\n');
|
|
1069
|
+
const r = await this.#vms.exec(name, ['bash', '-c', script, 'report', ...logs], { timeoutMs: 20_000 });
|
|
1070
|
+
const lines = String(r.stdout ?? '').split('\n');
|
|
1071
|
+
const pick = (p) => lines.filter((l) => l.startsWith(`${p} `)).map((l) => l.slice(p.length + 1));
|
|
1072
|
+
const memoryMb = Number(pick('memory')[0]) || null;
|
|
1073
|
+
return { at: new Date().toISOString(), oom: pick('oom'), memoryMb, logFile: pick('logfile')[0] ?? null, log: pick('log') };
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1037
1076
|
/* ONE FILE OF THE MACHINE'S OWN DISK, read for the person who asked to
|
|
1038
1077
|
see it (a path on their screen, clicked). Only under /work, only a
|
|
1039
1078
|
plain path, only a regular file of a modest size; read as the
|
package/server/gitkeeper.mjs
CHANGED
|
@@ -696,7 +696,11 @@ export class GitKeeper {
|
|
|
696
696
|
/* Its machine did not run them: tried again later, when it may. */
|
|
697
697
|
if (checks.status !== 'unavailable') held.done.set(b, tip.id);
|
|
698
698
|
const why = checks.status === 'failed' ? `the checks failed in the machine of ${conversation}` : checks.status === 'none' ? 'automatic sending needs passing checks, and none is set (no pre-push hook, no check command)' : `the checks could not run: the machine of ${conversation} does not run`;
|
|
699
|
-
|
|
699
|
+
/* On a failure the agent is given the END OF THE CHECK OUTPUT, not only
|
|
700
|
+
that it failed: it is the one that can fix it, and guessing without the
|
|
701
|
+
output wastes its time. */
|
|
702
|
+
const tail = String(checks.output ?? '').trim();
|
|
703
|
+
return once(`checks-${checks.status}`, { what: `Not sent: ${why}.`, tell: true, ...(checks.status === 'failed' ? { ai: `the checks failed for ${plain(b)}, it was not sent${tail ? `. The end of the output:\n\n${tail}` : ''}` } : {}) }), false;
|
|
700
704
|
}
|
|
701
705
|
}
|
|
702
706
|
const checked = s.checks ? 'checks passed' : 'no checks asked for';
|
package/server/main.mjs
CHANGED
|
@@ -411,7 +411,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
411
411
|
/* Connecting a mailbox, calendar or address book by token: the consent happens
|
|
412
412
|
in the owner's browser, the refresh token is kept host-only (never in a
|
|
413
413
|
machine) and a Tether target is made for it: see accounts.mjs. */
|
|
414
|
-
const accounts = new Accounts({ secrets, targets: { put: (spec) => tethers.store().putTarget(spec), all: () => tethers.store().targets() } });
|
|
414
|
+
const accounts = new Accounts({ secrets, targets: { put: (spec) => tethers.store().putTarget(spec), all: () => tethers.store().targets() }, probe: (target, password) => tethers.probe(target, password) });
|
|
415
415
|
/* A calendar target made before it needed the account address (Google CalDAV
|
|
416
416
|
puts it in the URL) carries none. The same account's mailbox or address book
|
|
417
417
|
has it -- they share the one refresh token -- so fill it in from a sibling,
|
|
@@ -470,6 +470,8 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
470
470
|
alert: (payload) => { void alerts.tell(payload); } });
|
|
471
471
|
/* Its machine restarted or built again: said in its chat, and the tool told to read it again. */
|
|
472
472
|
all.renewed = (name, text, running) => talk.renewed(name, text, running);
|
|
473
|
+
/* A Tether call waiting for the owner is said in its conversation's thread, with Accept / Refuse. */
|
|
474
|
+
tethers.announce = (name, event) => { try { return talk.event(name, event); } catch { return null; } };
|
|
473
475
|
/* A device given a conversation that talks through the app talks there too. */
|
|
474
476
|
door.talk = talk;
|
|
475
477
|
/* AFTER AN UPDATE, the machines that run get the new tools at once (parley, docket: they serve from
|
|
@@ -524,8 +526,19 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
524
526
|
const capacity = new Capacity({ run: asHost, store: new Store(`${dataDir}/server.json`), conversations: all, shelf, ...(serverRoomMs === undefined ? {} : { roomMs: serverRoomMs }),
|
|
525
527
|
/* Under the reserve: the machine that takes the most put to sleep, the owner told, and its chat. */
|
|
526
528
|
sleep: (name) => { events.add({ kind: 'machine', text: `Machine of ${name} put to sleep: this server was short of room`, conversation: name }); return all.sleep(name); }, alert: (payload) => { events.add({ kind: 'server', text: `${payload.title}: ${payload.body ?? ''}`.trim() }); void alerts.tell(payload); },
|
|
529
|
+
/* A machine asleep but still holding its RAM (a suspend that did not free it): its memory reclaimed, only that machine touched. */
|
|
530
|
+
reclaim: (name) => { events.add({ kind: 'machine', text: `Machine of ${name}: memory reclaimed (it was asleep but still held RAM)`, conversation: name }); return vms.reclaim(name).then((r) => (r.stdout || '').trim()); },
|
|
527
531
|
say: (name, text) => { try { talk.event(name, { kind: 'machine-problem', text, tone: 'warn', topic: 'Machine' }); } catch { /* its chat may be off */ } } });
|
|
528
532
|
all.room = (ask) => capacity.check(ask);
|
|
533
|
+
/* A tool that ended cut for lack of memory: said in the events, to the owner, and in its chat. */
|
|
534
|
+
all.onToolExit = (name, report) => {
|
|
535
|
+
if (!report?.oom?.length) return;
|
|
536
|
+
const size = report.memoryMb ? ` (${Math.round(report.memoryMb / 1024 * 10) / 10} GB)` : '';
|
|
537
|
+
const text = `Its tool was stopped: the machine ran out of memory${size}. Give it more in Settings → Machine → Memory, or start it fresh.`;
|
|
538
|
+
events.add({ kind: 'machine', text: `Machine of ${name}: its tool was stopped for lack of memory${size}`, conversation: name });
|
|
539
|
+
void alerts.tell({ title: `${name}: its tool ran out of memory`, body: text, url: `/?c=${encodeURIComponent(name)}&open=settings` });
|
|
540
|
+
try { talk.event(name, { kind: 'machine-problem', text, tone: 'warn', topic: 'Machine' }); } catch { /* its chat may be off */ }
|
|
541
|
+
};
|
|
529
542
|
const stopWatch = capacity.start();
|
|
530
543
|
/* The curves of the resources (history.mjs): one look a minute, from what the server knows already. */
|
|
531
544
|
const history = new History({ file: `${dataDir}/history.json` });
|
package/server/secret-scan.mjs
CHANGED
|
@@ -75,15 +75,25 @@ function improbableWord(s, floor = ENTROPY_MIN) {
|
|
|
75
75
|
export const secretRef = (name, at) => `⟨secret:${name}${Number.isFinite(at) ? `@${at}` : ''}⟩`;
|
|
76
76
|
export const SECRET_REF = /⟨secret:(SECRET_[0-9A-F]{10})(?:@(\d+))?⟩/g;
|
|
77
77
|
|
|
78
|
+
/* A URL left alone: the entropy nets skip what falls inside one, so a long
|
|
79
|
+
random-looking path or query (a tracking link, a LinkedIn profile) is not
|
|
80
|
+
taken for a secret. A token with a known shape (sk-..., a JWT) is still
|
|
81
|
+
caught, in a URL or not, because the SHAPES run everywhere. */
|
|
82
|
+
const URL = /\bhttps?:\/\/[^\s<>"'`)\]}]+/gi;
|
|
83
|
+
|
|
78
84
|
export function scan(text) {
|
|
79
85
|
const str = String(text ?? '');
|
|
80
86
|
const found = [];
|
|
87
|
+
const urlSpans = [];
|
|
88
|
+
URL.lastIndex = 0;
|
|
89
|
+
for (let m; (m = URL.exec(str));) urlSpans.push([m.index, m.index + m[0].length]);
|
|
90
|
+
const inUrl = (start, end) => urlSpans.some(([s, e]) => start >= s && end <= e);
|
|
81
91
|
for (const { kind, re } of SHAPES) {
|
|
82
92
|
re.lastIndex = 0;
|
|
83
93
|
for (let m; (m = re.exec(str));) found.push({ start: m.index, end: m.index + m[0].length, value: m[0], kind });
|
|
84
94
|
}
|
|
85
95
|
for (let m; (m = BLOB.exec(str));) {
|
|
86
|
-
if (looksRandom(m[0])) found.push({ start: m.index, end: m.index + m[0].length, value: m[0], kind: 'high-entropy' });
|
|
96
|
+
if (looksRandom(m[0]) && !inUrl(m.index, m.index + m[0].length)) found.push({ start: m.index, end: m.index + m[0].length, value: m[0], kind: 'high-entropy' });
|
|
87
97
|
}
|
|
88
98
|
BLOB.lastIndex = 0;
|
|
89
99
|
/* A word nearby that announces a secret widens the net to shorter runs, on a lower floor. */
|
|
@@ -91,7 +101,7 @@ export function scan(text) {
|
|
|
91
101
|
const wordRe = near ? SHORT_WORD : WORD;
|
|
92
102
|
const floor = near ? ENTROPY_SHORT : ENTROPY_MIN;
|
|
93
103
|
for (let m; (m = wordRe.exec(str));) {
|
|
94
|
-
if (improbableWord(m[0], floor)) found.push({ start: m.index, end: m.index + m[0].length, value: m[0], kind: 'high-entropy' });
|
|
104
|
+
if (improbableWord(m[0], floor) && !inUrl(m.index, m.index + m[0].length)) found.push({ start: m.index, end: m.index + m[0].length, value: m[0], kind: 'high-entropy' });
|
|
95
105
|
}
|
|
96
106
|
wordRe.lastIndex = 0;
|
|
97
107
|
/* Keep left-to-right, and when two matches overlap keep the one that starts
|
package/server/talk.mjs
CHANGED
|
@@ -153,6 +153,11 @@ export const EVENT_LEVELS = Object.freeze({
|
|
|
153
153
|
'docket-failed': 'needs-you',
|
|
154
154
|
'docket-unhandled': 'needs-you',
|
|
155
155
|
'docket-reminder': 'trace',
|
|
156
|
+
/* A Tether call its agent asks the owner to allow (tethers.mjs): offered in the thread with
|
|
157
|
+
Accept / Refuse, the same block a machine problem uses. Its closing line (decided here, from
|
|
158
|
+
Assets, or by the agent) is a trace that carries the call's id, so the buttons close with it. */
|
|
159
|
+
'tether-demande': 'needs-you',
|
|
160
|
+
'tether-done': 'trace',
|
|
156
161
|
});
|
|
157
162
|
const TONES = ['warn', 'bad'];
|
|
158
163
|
/* Bounds of a line: its text, its group (topic), what the grouped line says of it (brief), its buttons. */
|
package/server/tethers.mjs
CHANGED
|
@@ -28,14 +28,47 @@ export const PUMP_MS = 1000;
|
|
|
28
28
|
const AGENT = 'conversation:';
|
|
29
29
|
|
|
30
30
|
export class Tethers {
|
|
31
|
-
#keeper; #resources; #conversations; #secrets; #timers = []; #changes = 0;
|
|
31
|
+
#keeper; #resources; #conversations; #secrets; #timers = []; #changes = 0; #seen = new Map();
|
|
32
|
+
/* Set by the server once the thread is ready (main.mjs): (name, event) => talk.event(...).
|
|
33
|
+
A call waiting for the owner is said in its conversation's thread when there is one. */
|
|
34
|
+
announce = null;
|
|
32
35
|
|
|
33
36
|
/* `resources`: Resources (workFolder). `conversations()`: the names of the conversations.
|
|
34
37
|
`secrets`: the vault, read by name for a connector only (reveal). */
|
|
35
38
|
constructor({ dataDir, resources, conversations, secrets, connectors, now = () => Date.now() }) {
|
|
36
39
|
this.#resources = resources; this.#conversations = conversations; this.#secrets = secrets;
|
|
37
40
|
this.#keeper = keeper(`${dataDir}/tether`, { sides: () => this.#sides(), secrets: (name) => this.#reveal(name), now, ...(connectors ? { connectors } : {}) });
|
|
38
|
-
|
|
41
|
+
/* Every change a page shows -- a new approval waiting, one decided, the targets,
|
|
42
|
+
the journal -- bumps the counter the client watches, so the approvals screen
|
|
43
|
+
sees them all at once, not only when a store change happens to wake it. */
|
|
44
|
+
this.#keeper.onChange(() => { this.#changes++; this.#tellNew(); });
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/* A new call waiting for the owner is said in its conversation's thread -- the same block a
|
|
48
|
+
machine problem uses -- with Accept / Refuse; when it leaves the queue (decided here or from
|
|
49
|
+
Assets, or taken back by the agent) a trace carrying its id closes those buttons. Nothing is
|
|
50
|
+
said until the server wired `announce` (it holds the thread), and nothing to a conversation
|
|
51
|
+
whose chat is off keeps the line waiting for when it opens. */
|
|
52
|
+
#tellNew() {
|
|
53
|
+
if (!this.announce) return;
|
|
54
|
+
let now;
|
|
55
|
+
try { now = this.#keeper.approvals() ?? []; } catch { return; }
|
|
56
|
+
const live = new Set(now.map((r) => r.id));
|
|
57
|
+
for (const r of now) {
|
|
58
|
+
if (this.#seen.has(r.id)) continue;
|
|
59
|
+
const who = r.agent?.id ?? '';
|
|
60
|
+
if (!who.startsWith(AGENT)) continue;
|
|
61
|
+
const name = who.slice(AGENT.length);
|
|
62
|
+
this.#seen.set(r.id, { name, verb: r.verb ?? 'action' });
|
|
63
|
+
const what = [r.verb ?? 'action', r.detail].filter(Boolean).join(' ');
|
|
64
|
+
const text = [what, r.target?.title ? `(${r.target.title})` : '', r.why ? `-- ${r.why}` : ''].filter(Boolean).join(' ');
|
|
65
|
+
try { this.announce(name, { kind: 'tether-demande', text: text || (r.verb ?? 'A Tether call'), topic: 'Demande', tone: 'warn', actions: [`allow:${r.id}`, `deny:${r.id}`] }); } catch { /* its chat is off */ }
|
|
66
|
+
}
|
|
67
|
+
for (const [id, info] of [...this.#seen]) {
|
|
68
|
+
if (live.has(id)) continue;
|
|
69
|
+
this.#seen.delete(id);
|
|
70
|
+
try { this.announce(info.name, { kind: 'tether-done', text: `Request handled: ${info.verb}`, topic: 'Demande', brief: id }); } catch { /* its chat is off */ }
|
|
71
|
+
}
|
|
39
72
|
}
|
|
40
73
|
|
|
41
74
|
/* A secret's value for a connector, by name, from this server's vault; never seen by the agent.
|
|
@@ -77,6 +110,15 @@ export class Tethers {
|
|
|
77
110
|
/* The store behind it, for the Assets page to create/give/remove targets. */
|
|
78
111
|
store() { return this.#keeper.store; }
|
|
79
112
|
|
|
113
|
+
/* A first read of a target not saved yet, its password given here: does the account
|
|
114
|
+
answer? Used when a classic account is connected, before anything is kept. */
|
|
115
|
+
async probe(target, password) {
|
|
116
|
+
const verb = { mail: 'mail.list', calendar: 'calendar.list', contacts: 'contacts.list' }[target.connector];
|
|
117
|
+
const conn = this.#keeper.connectors?.[target.connector];
|
|
118
|
+
if (!verb || !conn) throw new Error(`no ${target.connector} connector`);
|
|
119
|
+
await conn.run(verb, target, {}, { agent: 'person:owner', secret: async () => password });
|
|
120
|
+
}
|
|
121
|
+
|
|
80
122
|
/* What each conversation was given: { name: count } -- the targets it may use. */
|
|
81
123
|
given() {
|
|
82
124
|
const out = {};
|
package/server/tools.mjs
CHANGED
|
@@ -98,13 +98,15 @@ export function readTools(text) {
|
|
|
98
98
|
machine's user (".claude/CLAUDE.md"): a marked block in it points
|
|
99
99
|
the tool to its guide (see guide.mjs). A plain relative path. */
|
|
100
100
|
if (t.instructions !== undefined && !INSTRUCTIONS.test(t.instructions)) throw new Error(`${t.id}: instructions is a relative path in the home, without ".."`);
|
|
101
|
+
/* Where the tool keeps its own log, read when it ends (why it stopped): folders relative to the home. */
|
|
102
|
+
if (t.logs !== undefined && (!Array.isArray(t.logs) || t.logs.some((d) => typeof d !== 'string' || !/^[A-Za-z0-9._/-]+$/.test(d) || d.startsWith('/') || d.split('/').includes('..')))) throw new Error(`${t.id}: logs is a list of folders relative to the home, without ".."`);
|
|
101
103
|
/* Optional: ITS LAUNCHER, a script of config/launch shown at /tools/launch: run at each start,
|
|
102
104
|
given the rights chosen (full, ask) then the command; it sets what the tool needs,
|
|
103
105
|
then runs it. Clavarium knows nothing more of the tool. */
|
|
104
106
|
if (t.launch !== undefined && !/^[a-z][a-z0-9-]{0,40}\.sh$/.test(t.launch)) throw new Error(`${t.id}: launch is the name of a script of config/launch, such as "${t.id}.sh"`);
|
|
105
107
|
/* Repairs an existing machine is given once (see FIXES in conversations.mjs). */
|
|
106
108
|
const fixups = t.install.includes('npm-writable') ? NPM_WRITABLE : [];
|
|
107
|
-
return Object.freeze({ id: t.id, label: t.label, ...(t.instructions ? { instructions: t.instructions } : {}), command: Object.freeze([...t.command]), ...(t.launch ? { launch: t.launch } : {}), ...(t.resume ? { resume: Object.freeze([...t.resume]) } : {}), memoryMb: t.memoryMb, ...(rights ? { rights } : {}), steps: Object.freeze(steps), fixups: Object.freeze(fixups), signin });
|
|
109
|
+
return Object.freeze({ id: t.id, label: t.label, ...(t.instructions ? { instructions: t.instructions } : {}), ...(t.logs ? { logs: Object.freeze([...t.logs]) } : {}), command: Object.freeze([...t.command]), ...(t.launch ? { launch: t.launch } : {}), ...(t.resume ? { resume: Object.freeze([...t.resume]) } : {}), memoryMb: t.memoryMb, ...(rights ? { rights } : {}), steps: Object.freeze(steps), fixups: Object.freeze(fixups), signin });
|
|
108
110
|
});
|
|
109
111
|
}
|
|
110
112
|
|
package/server/vm.mjs
CHANGED
|
@@ -52,7 +52,7 @@ export function runner(prefix) {
|
|
|
52
52
|
}
|
|
53
53
|
|
|
54
54
|
/* The verbs that change a machine: its state is asked again after them. */
|
|
55
|
-
const CHANGES = new Set(['launch', 'clone', 'start', 'stop', 'suspend', 'kill', 'delete', 'purge', 'set', 'rename', 'restore', 'snapshot', 'revive']);
|
|
55
|
+
const CHANGES = new Set(['launch', 'clone', 'start', 'stop', 'suspend', 'kill', 'delete', 'purge', 'set', 'rename', 'restore', 'snapshot', 'revive', 'reclaim']);
|
|
56
56
|
export const STATES_FRESH_MS = 3000;
|
|
57
57
|
/* The VM manager did not say what a machine is in: not an answer about the machine. */
|
|
58
58
|
export class VmUnknown extends Error {
|
|
@@ -181,5 +181,8 @@ export class Vms {
|
|
|
181
181
|
return { memoryMb: mb === undefined ? undefined : Math.round(mb), diskGb: disk === undefined ? undefined : Math.round(disk / 1024), cpus };
|
|
182
182
|
}
|
|
183
183
|
suspend(conversation) { return this.run(['vm', 'suspend', vmName(conversation)], { timeoutMs: 300_000 }); }
|
|
184
|
+
/* Free the RAM of a machine that is asleep but whose qemu still holds it (a
|
|
185
|
+
suspend that did not end the process): wake+resleep, then a clean stop. */
|
|
186
|
+
reclaim(conversation) { return this.run(['vm', 'reclaim', vmName(conversation)], { timeoutMs: 300_000 }); }
|
|
184
187
|
remove(conversation) { return this.run(['vm', 'delete', vmName(conversation)], { timeoutMs: 300_000 }); }
|
|
185
188
|
}
|