clavarium 0.2.228-beta.1 → 0.2.229-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/deploy/updater.mjs +94 -11
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/server/answerer.mjs +10 -9
- package/server/dockets.mjs +5 -10
- package/server/main.mjs +15 -22
- package/server/signinhelp.mjs +9 -1
- package/server/talk.mjs +50 -23
- package/server/updates.mjs +3 -1
- package/server/vm.mjs +30 -1
- package/server/wakeups.mjs +20 -19
- package/server/terminaltype.mjs +0 -135
package/deploy/updater.mjs
CHANGED
|
@@ -89,6 +89,11 @@ const ASK_EVERY_MS = 6 * 3600_000;
|
|
|
89
89
|
had it): nothing of it ran here, so it is tried again by itself, this long after, this many times at most. */
|
|
90
90
|
export const FETCH_AGAIN_MS = 30 * 60_000;
|
|
91
91
|
export const FETCH_TRIES = 3;
|
|
92
|
+
/* NOT RACING THE REGISTRY (17-11: 0.2.228-beta.1 asked of npm the minute it was tagged, refused; the same
|
|
93
|
+
install worked 20 minutes later): a version is installed by itself only once it has been out this long --
|
|
94
|
+
since its time in the registry (`time`), or since this updater first saw it when the registry says none.
|
|
95
|
+
Asked by the owner (Update, Try again): at once. */
|
|
96
|
+
export const RELEASE_SETTLE_MS = 10 * 60_000;
|
|
92
97
|
/* Between "Switching" said in state.json and the server stopped: the pages ask the server every
|
|
93
98
|
10 seconds at most (app.js), and the server says it in each answer (updates.mjs, notice): each
|
|
94
99
|
gives way to the maintenance page before the server goes. */
|
|
@@ -96,6 +101,8 @@ export const NOTICE_MS = 15_000;
|
|
|
96
101
|
const PROVENANCE = 'https://slsa.dev/provenance/v1';
|
|
97
102
|
/* What the log of a failure keeps, at most (history entry `log`, shown behind "See the log"). */
|
|
98
103
|
const LOG_MAX = 12_000;
|
|
104
|
+
/* Of npm's own debug log (in its cache, which goes with the attempt): the last lines kept in the history. */
|
|
105
|
+
const NPM_LOG_LINES = 40;
|
|
99
106
|
/* Set beside the server's unit by the updater (root): a crash loop never locks the service out, so a
|
|
100
107
|
restart asked later (an update, the watchdog) still starts it. */
|
|
101
108
|
export const DROP_IN = '/etc/systemd/system/clavarium.service.d/restart.conf';
|
|
@@ -263,6 +270,37 @@ export async function ensureMaintenance({ caddyfile = CADDYFILE, caddy = CADDY,
|
|
|
263
270
|
}
|
|
264
271
|
|
|
265
272
|
export class Refused extends Error {}
|
|
273
|
+
/* NOTHING OF THE VERSION RAN: npm could not install it, or the registry did not answer about it (not there
|
|
274
|
+
yet, a mirror behind, the network). Said in the history as `fetch: true`, tried again by itself later.
|
|
275
|
+
`log`: what npm said, for "See the log". */
|
|
276
|
+
export class FetchFailed extends Error {
|
|
277
|
+
constructor(message, { log } = {}) { super(message); this.log = log; }
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/* WHAT A LOG MUST NEVER SHOW: npm's debug log can carry the registry's credentials (an .npmrc token, an
|
|
281
|
+
Authorization header, a URL with a password). Each is put as ***. */
|
|
282
|
+
export function redact(text) {
|
|
283
|
+
return String(text ?? '')
|
|
284
|
+
.replace(/\b(proxy-authorization|authorization)(["']?\s*[:=]\s*["']?)(?:(bearer|basic|token)\s+)?[^\s"',;}]+/gi, (_, k, sep, scheme) => `${k}${sep}${scheme ? `${scheme} ` : ''}***`)
|
|
285
|
+
.replace(/\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]{6,}/gi, '$1 ***')
|
|
286
|
+
.replace(/((?:_authToken|_auth|_password|authToken|token|password|passwd|secret|otp)["']?\s*[=:]\s*["']?)[^\s"',;}]+/gi, '$1***')
|
|
287
|
+
.replace(/\bnpm_[A-Za-z0-9]{16,}\b/g, 'npm_***')
|
|
288
|
+
.replace(/\bgh[opsur]_[A-Za-z0-9]{16,}\b/g, 'gh*_***')
|
|
289
|
+
.replace(/(\/\/)[^\s/@:]+:[^\s/@]+@/g, '$1***@');
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/* The end of npm's own debug log, from the cache it was given: the last lines that say something (its
|
|
293
|
+
`silly` lines, its call stack and its pointer to itself left out), each bounded, credentials taken out. '' when there is none. */
|
|
294
|
+
export function npmLogTail(cache, lines = NPM_LOG_LINES) {
|
|
295
|
+
const dir = join(cache, '_logs');
|
|
296
|
+
let name;
|
|
297
|
+
try { name = readdirSync(dir).filter((f) => f.endsWith('.log')).sort().pop(); } catch { return ''; }
|
|
298
|
+
if (!name) return '';
|
|
299
|
+
let text = '';
|
|
300
|
+
try { text = readFileSync(join(dir, name), 'utf8'); } catch { return ''; }
|
|
301
|
+
const kept = text.split('\n').filter((l) => l.trim() && !/^\d+\s+silly\b|^\d+\s+verbose stack\s+at |A complete log of this run can be found in/.test(l)).slice(-lines).map((l) => (l.length > 500 ? `${l.slice(0, 500)}...` : l));
|
|
302
|
+
return redact(kept.join('\n'));
|
|
303
|
+
}
|
|
266
304
|
|
|
267
305
|
/* SEMANTIC VERSIONS, compared as npm does: a pre-release comes before its release. */
|
|
268
306
|
export function compareVersions(a, b) {
|
|
@@ -328,7 +366,19 @@ export function runCommand(argv, { cwd, env = process.env, timeoutMs = 900_000 }
|
|
|
328
366
|
});
|
|
329
367
|
}
|
|
330
368
|
|
|
331
|
-
|
|
369
|
+
/* npm's lines that say nothing of why: its notices, its warnings, its pointer to a log that is gone with
|
|
370
|
+
its cache, its empty error lines. */
|
|
371
|
+
const NPM_NOISE = /^npm (notice|warn)|A complete log of this run can be found in|^npm (error|ERR!)\s*$/;
|
|
372
|
+
const lastLine = (r) => redact(String(r.stderr || r.stdout || '').trim().split('\n').filter((l) => l.trim() && !NPM_NOISE.test(l)).pop()?.slice(0, 300) ?? `exit ${r.code}`);
|
|
373
|
+
/* Why npm failed, in one line: its error code and its first words of explanation ("code ETARGET: notarget
|
|
374
|
+
No matching version found for ..."), else its last line that says something. */
|
|
375
|
+
function npmWhy(r) {
|
|
376
|
+
const errors = String(r.stderr || r.stdout || '').split('\n').map((l) => /^npm (?:error|ERR!) (.+)$/.exec(l.trim())?.[1]?.trim()).filter((l) => l && !NPM_NOISE.test(`npm error ${l}`));
|
|
377
|
+
const code = errors.find((l) => /^code \S+$/.test(l));
|
|
378
|
+
const said = errors.find((l) => !/^(code|errno|syscall|path|dest|signal|command|cwd) /.test(l));
|
|
379
|
+
if (!code && !said) return lastLine(r);
|
|
380
|
+
return redact([code, said].filter(Boolean).join(': ').slice(0, 300));
|
|
381
|
+
}
|
|
332
382
|
const stamp = (d) => d.toISOString().replace(/[-:]/g, '').replace('T', '-').slice(0, 15);
|
|
333
383
|
const toHex = (integrity) => Buffer.from(String(integrity).replace(/^sha512-/, ''), 'base64').toString('hex');
|
|
334
384
|
|
|
@@ -336,8 +386,8 @@ export class Updater {
|
|
|
336
386
|
#o; #run; #fetch;
|
|
337
387
|
constructor({ code = PATHS.code, conf = PATHS.conf, stateDir = PATHS.stateDir, data = PATHS.data, hostTarget = PATHS.host, gitReadTarget = PATHS.gitRead, tunnelTarget = PATHS.tunnel, registry = REGISTRY, run = runCommand, fetcher = fetch, now = () => new Date(), log = (line) => console.log(line),
|
|
338
388
|
verifySignatures, restart, health, backup, restoreData, installPrivileged, ensureNode, serviceState, answers, restarts, mainPid, pidCwd, diagnose, dropIn = DROP_IN,
|
|
339
|
-
clock = () => Date.now(), sleep = (ms) => new Promise((r) => setTimeout(r, ms)), minFreeMb = 1024, healthMs = 60_000, watchMs = 120_000, settleMs = 10_000, noticeMs = NOTICE_MS } = {}) {
|
|
340
|
-
this.#o = { code, conf, stateDir, data, hostTarget, gitReadTarget, tunnelTarget, registry: registry.replace(/\/$/, ''), now, log, minFreeMb, healthMs, watchMs, settleMs, noticeMs, clock, sleep, dropIn };
|
|
389
|
+
clock = () => Date.now(), sleep = (ms) => new Promise((r) => setTimeout(r, ms)), minFreeMb = 1024, healthMs = 60_000, watchMs = 120_000, settleMs = 10_000, noticeMs = NOTICE_MS, releaseSettleMs = RELEASE_SETTLE_MS } = {}) {
|
|
390
|
+
this.#o = { code, conf, stateDir, data, hostTarget, gitReadTarget, tunnelTarget, registry: registry.replace(/\/$/, ''), now, log, minFreeMb, healthMs, watchMs, settleMs, noticeMs, releaseSettleMs, clock, sleep, dropIn };
|
|
341
391
|
this.#run = run; this.#fetch = fetcher;
|
|
342
392
|
this.verifySignatures = verifySignatures ?? ((dir) => this.#npm(['audit', 'signatures'], { cwd: dir, timeoutMs: 300_000 }));
|
|
343
393
|
this.restart = restart ?? (() => this.#restart());
|
|
@@ -403,10 +453,12 @@ export class Updater {
|
|
|
403
453
|
|
|
404
454
|
set(key, value) { writeConf(this.#o.conf, key, value); return this.about(); }
|
|
405
455
|
|
|
456
|
+
/* The registry not answering, or not with what was asked: a fetch failure (FetchFailed), not the release's fault. */
|
|
406
457
|
async #json(url) {
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
458
|
+
let answer;
|
|
459
|
+
try { answer = await this.#fetch(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(60_000) }); } catch (error) { throw new FetchFailed(`the registry could not be reached for ${url}: ${error.cause?.code ?? error.message}`); }
|
|
460
|
+
if (!answer.ok) throw new FetchFailed(`the registry answered ${answer.status} for ${url}`);
|
|
461
|
+
try { return await answer.json(); } catch (error) { throw new FetchFailed(`the registry's answer for ${url} was cut: ${error.message}`); }
|
|
410
462
|
}
|
|
411
463
|
#packument(name) { return this.#json(`${this.#o.registry}/${name}`); }
|
|
412
464
|
|
|
@@ -424,7 +476,11 @@ export class Updater {
|
|
|
424
476
|
if (conf.CHANNEL === 'beta' && tags.beta && (!candidate || compareVersions(tags.beta, candidate) > 0)) candidate = tags.beta;
|
|
425
477
|
if (candidate && (!VERSION.test(candidate) || !p.versions?.[candidate])) candidate = undefined;
|
|
426
478
|
const available = candidate && (!current || compareVersions(candidate, current.version) > 0) ? candidate : null;
|
|
427
|
-
|
|
479
|
+
/* Since when it is out (RELEASE_SETTLE_MS): the registry's time for it, and when it was first seen here. */
|
|
480
|
+
const was = this.#state().outSince;
|
|
481
|
+
const published = Date.parse(p.time?.[available] ?? '');
|
|
482
|
+
const outSince = available ? { version: available, seenAt: was?.version === available && was.seenAt ? was.seenAt : this.#o.now().toISOString(), publishedAt: Number.isFinite(published) ? new Date(published).toISOString() : null } : null;
|
|
483
|
+
this.#save({ checkedAt: this.#o.now().toISOString(), available, checkError: null, outSince });
|
|
428
484
|
return available;
|
|
429
485
|
} catch (error) {
|
|
430
486
|
this.#save({ checkedAt: this.#o.now().toISOString(), checkError: `The registry could not be asked: ${error.message}` });
|
|
@@ -442,6 +498,12 @@ export class Updater {
|
|
|
442
498
|
}
|
|
443
499
|
|
|
444
500
|
#npmEnv(nodeDir) { return { ...process.env, PATH: `${nodeDir ? `${nodeDir}/bin:` : ''}${dirname(process.execPath)}:${process.env.PATH ?? '/usr/bin:/bin'}`, npm_config_update_notifier: 'false', npm_config_fund: 'false', npm_config_audit: 'false' }; }
|
|
501
|
+
/* What npm said when it failed, for "See the log": its own words, then the end of its debug log. */
|
|
502
|
+
#npmFailure(r, what) {
|
|
503
|
+
const said = redact(String(r.stderr || r.stdout || '').trim().split('\n').filter((l) => !/A complete log of this run can be found in/.test(l)).slice(-20).join('\n'));
|
|
504
|
+
const tail = npmLogTail(join(this.#o.stateDir, 'npm-cache'));
|
|
505
|
+
return [`== ${this.#o.now().toISOString()} ${what} failed (exit ${r.code})`, `-- what npm said\n${said || '(nothing)'}`, ...(tail ? [`-- the end of npm's debug log\n${tail}`] : [])].join('\n').slice(-LOG_MAX);
|
|
506
|
+
}
|
|
445
507
|
#npm(args, { cwd, nodeDir, timeoutMs = 900_000 } = {}) {
|
|
446
508
|
const npm = nodeDir ? join(nodeDir, 'bin', 'npm') : join(dirname(process.execPath), 'npm');
|
|
447
509
|
return this.#run([npm, ...args, '--registry', `${this.#o.registry}/`, '--cache', join(this.#o.stateDir, 'npm-cache'), '--loglevel=error'], { cwd, env: this.#npmEnv(nodeDir), timeoutMs });
|
|
@@ -465,9 +527,12 @@ export class Updater {
|
|
|
465
527
|
this.#step(action, id, 'Fetching');
|
|
466
528
|
writeFileSync(join(tmp, 'package.json'), `${JSON.stringify({ name: 'clavarium-release', private: true, dependencies: { [NAME]: version } }, null, 2)}\n`);
|
|
467
529
|
const got = await this.#npm(['install', '--ignore-scripts', '--no-audit', '--no-fund', '--save-exact'], { cwd: tmp });
|
|
468
|
-
|
|
530
|
+
/* Whatever made it fail (not there yet, a mirror behind, the network, a cut archive), nothing of it ran:
|
|
531
|
+
a fetch failure, with what npm said kept (its debug log goes with its cache, below). */
|
|
532
|
+
if (got.code !== 0) throw new FetchFailed(`npm could not install ${NAME}@${version}: ${npmWhy(got)}`, { log: this.#npmFailure(got, `npm install ${NAME}@${version}`) });
|
|
469
533
|
app = join(tmp, 'node_modules', NAME);
|
|
470
|
-
|
|
534
|
+
let manifest;
|
|
535
|
+
try { manifest = JSON.parse(readFileSync(join(app, 'package.json'), 'utf8')); } catch (error) { throw new FetchFailed(`npm could not install ${NAME}@${version}: it left no package (${error.code ?? error.message})`, { log: this.#npmFailure(got, `npm install ${NAME}@${version}`) }); }
|
|
471
536
|
if (manifest.name !== NAME || manifest.version !== version) throw new Error(`npm installed ${manifest.name}@${manifest.version}, not ${NAME}@${version}`);
|
|
472
537
|
this.#step(action, id, 'Checking');
|
|
473
538
|
await this.verify(tmp, version);
|
|
@@ -514,6 +579,8 @@ export class Updater {
|
|
|
514
579
|
const own = entry(NAME);
|
|
515
580
|
const p = await this.#packument(NAME);
|
|
516
581
|
const dist = p.versions?.[version]?.dist;
|
|
582
|
+
/* Installed, but not listed by the registry that was asked next (a mirror behind): fetched again later. */
|
|
583
|
+
if (own && !dist) throw new FetchFailed(`the registry does not list ${NAME}@${version} yet`);
|
|
517
584
|
if (!own || !dist || own.version !== version || own.integrity !== dist.integrity) throw new Error(`${NAME}@${version} as installed is not the archive the registry lists`);
|
|
518
585
|
for (const name of Object.keys(REPOS)) {
|
|
519
586
|
const e = name === NAME ? own : entry(name);
|
|
@@ -606,7 +673,11 @@ export class Updater {
|
|
|
606
673
|
const unlock = this.#lock();
|
|
607
674
|
try {
|
|
608
675
|
let release;
|
|
609
|
-
try { release = await this.prepare({ version }); } catch (error) {
|
|
676
|
+
try { release = await this.prepare({ version }); } catch (error) {
|
|
677
|
+
const fetched = error instanceof FetchFailed || /^npm could not install /.test(error.message);
|
|
678
|
+
this.#history({ action: 'update', from: from?.version ?? null, to: version, result: 'failed', why: error.message, ...(fetched ? { fetch: true } : {}), ...(typeof error.log === 'string' && error.log ? { log: error.log.slice(-LOG_MAX) } : {}) });
|
|
679
|
+
throw error;
|
|
680
|
+
}
|
|
610
681
|
const before = this.#dataFormat();
|
|
611
682
|
let archive;
|
|
612
683
|
try {
|
|
@@ -725,6 +796,10 @@ export class Updater {
|
|
|
725
796
|
if (failed.length >= FETCH_TRIES) return `${available} could not be fetched ${failed.length} times: not tried again by itself`;
|
|
726
797
|
const lastAt = Math.max(...failed.map((h) => new Date(h.at ?? 0).getTime()), -Infinity);
|
|
727
798
|
if (failed.length && now - lastAt < FETCH_AGAIN_MS) return `${available} could not be fetched: tried again later`;
|
|
799
|
+
/* Just out: every mirror given time to have it (RELEASE_SETTLE_MS). */
|
|
800
|
+
const out = this.#state().outSince;
|
|
801
|
+
const outAt = Math.min(...[out?.version === available ? out.seenAt : null, out?.version === available ? out.publishedAt : null].map((t) => Date.parse(t ?? '')).filter(Number.isFinite), now.getTime());
|
|
802
|
+
if (now - outAt < this.#o.releaseSettleMs) return `${available} is just out: installed by itself from ${new Date(outAt + this.#o.releaseSettleMs).toISOString()}`;
|
|
728
803
|
const why = await this.busy(); if (why) return why;
|
|
729
804
|
await this.apply(available);
|
|
730
805
|
/* What the history says, not what was hoped: a version that did not start was undone. */
|
|
@@ -869,11 +944,19 @@ export class Updater {
|
|
|
869
944
|
const port = readConf(this.#o.conf).PORT;
|
|
870
945
|
const part = async (title, argv) => { const r = await this.#run(argv, { timeoutMs: 20_000 }); return `-- ${title}\n${String(r.stdout || r.stderr || `exit ${r.code}`).trim()}`; };
|
|
871
946
|
const left = await this.#leftovers().catch(() => []);
|
|
947
|
+
/* WHAT THE SERVER ITSELF SAID (17-11): the unit's journal is mostly the sudo lines of the host program it
|
|
948
|
+
runs (a hundred a minute), its own words lost among them -- the owner saw only those, and no reason.
|
|
949
|
+
Read further back, the sudo and PAM lines left out, the last of the rest kept. */
|
|
950
|
+
const serverSaid = async () => {
|
|
951
|
+
const r = await this.#run(['journalctl', '-u', 'clavarium.service', '-n', '4000', '--no-pager', '-o', 'short-iso'], { timeoutMs: 20_000 });
|
|
952
|
+
const lines = String(r.stdout || '').split('\n').filter((l) => l.trim() && !/ (sudo|pkexec)\[\d+\]: | pam_unix\(/.test(l));
|
|
953
|
+
return `-- what the server said (journalctl -u clavarium, sudo lines left out)\n${lines.slice(-80).join('\n').trim() || String(r.stderr || `exit ${r.code}`).trim()}`;
|
|
954
|
+
};
|
|
872
955
|
return [
|
|
873
956
|
await part('systemctl status clavarium', ['systemctl', 'status', 'clavarium.service', '--no-pager', '-n', '0']),
|
|
874
957
|
await part(`who listens on ${port}`, ['ss', '-Hltnp', `sport = :${port}`]),
|
|
875
958
|
`-- processes of the server's unit or on its port\n${left.map((p) => `pid ${p.pid} state ${p.state}${p.port ? ' (holds the port)' : ''}`).join('\n') || 'none'}`,
|
|
876
|
-
await
|
|
959
|
+
await serverSaid(),
|
|
877
960
|
].join('\n');
|
|
878
961
|
}
|
|
879
962
|
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.229-beta.1",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "clavarium",
|
|
9
|
-
"version": "0.2.
|
|
9
|
+
"version": "0.2.229-beta.1",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@xterm/addon-fit": "^0.11.0",
|
package/package.json
CHANGED
package/server/answerer.mjs
CHANGED
|
@@ -40,7 +40,6 @@ import { appendFileSync, readFileSync, writeFileSync, mkdirSync, statSync, rmSyn
|
|
|
40
40
|
import { createHash } from 'node:crypto';
|
|
41
41
|
import { Refusal, SESSION } from './conversations.mjs';
|
|
42
42
|
import { SOCKET } from './tmux.mjs';
|
|
43
|
-
import { TerminalType } from './terminaltype.mjs';
|
|
44
43
|
import { isConversationName } from './names.mjs';
|
|
45
44
|
|
|
46
45
|
export const TICK_MS = 8000;
|
|
@@ -180,14 +179,12 @@ const PANE = `=${SESSION}:`;
|
|
|
180
179
|
const fingerprint = (screen) => createHash('sha256').update(screen).digest('hex');
|
|
181
180
|
|
|
182
181
|
export class Answerer {
|
|
183
|
-
#store; #vms; #config; #fetcher; #dir; #conversations; #seen = new Map(); #busy = new Set(); #turn = 0; #now; #onNeeds;
|
|
182
|
+
#store; #vms; #config; #fetcher; #dir; #conversations; #seen = new Map(); #busy = new Set(); #turn = 0; #now; #onNeeds;
|
|
184
183
|
|
|
185
184
|
/* `conversations`: asked which conversations exist and are awake. */
|
|
186
185
|
/* `onNeeds(name, why)`: it stopped and waits for its owner, who must be told. */
|
|
187
|
-
constructor({ store, vms, config, conversations, dataDir, fetcher = fetch, now = () => new Date(), onNeeds = () => {}
|
|
186
|
+
constructor({ store, vms, config, conversations, dataDir, fetcher = fetch, now = () => new Date(), onNeeds = () => {} }) {
|
|
188
187
|
this.#onNeeds = onNeeds;
|
|
189
|
-
/* `typer`: the server's one TerminalType (main.mjs), or one of its own. */
|
|
190
|
-
this.#typer = typer ?? new TerminalType({ vms, log: () => {} });
|
|
191
188
|
this.#store = store; this.#vms = vms; this.#config = config; this.#conversations = conversations; this.#fetcher = fetcher; this.#now = now;
|
|
192
189
|
this.#dir = `${dataDir}/answerer`;
|
|
193
190
|
mkdirSync(this.#dir, { recursive: true, mode: 0o700 });
|
|
@@ -252,12 +249,16 @@ export class Answerer {
|
|
|
252
249
|
return lines.slice(-SCREEN_LINES).join('\n').slice(-SCREEN_MAX);
|
|
253
250
|
}
|
|
254
251
|
|
|
255
|
-
/* Typed as every line of this server is (terminaltype.mjs): copy mode left first. Never while
|
|
256
|
-
somebody types there (`hold` 0): the answer is for the screen read, not one changed meanwhile. */
|
|
257
252
|
async #type(name, answer) {
|
|
258
|
-
|
|
253
|
+
const to = ['-t', PANE];
|
|
254
|
+
const tmux = ['tmux', '-L', SOCKET];
|
|
255
|
+
if (answer.action === 'text') {
|
|
256
|
+
const typed = await this.#vms.exec(name, [...tmux, 'send-keys', ...to, '-l', '--', answer.text], { timeoutMs: 30_000 });
|
|
257
|
+
if (typed.code !== 0) return false;
|
|
258
|
+
return (await this.#vms.exec(name, [...tmux, 'send-keys', ...to, 'Enter'], { timeoutMs: 30_000 })).code === 0;
|
|
259
|
+
}
|
|
259
260
|
for (const key of answer.keys) {
|
|
260
|
-
if (
|
|
261
|
+
if ((await this.#vms.exec(name, [...tmux, 'send-keys', ...to, KEYS.get(key)], { timeoutMs: 30_000 })).code !== 0) return false;
|
|
261
262
|
}
|
|
262
263
|
return true;
|
|
263
264
|
}
|
package/server/dockets.mjs
CHANGED
|
@@ -8,9 +8,8 @@
|
|
|
8
8
|
* Where the chat is off, a wake-up types its line as before.
|
|
9
9
|
*
|
|
10
10
|
* NOTHING IS LOST: an event not acknowledged is told again, when the tool is
|
|
11
|
-
* idle (its pulse, Parley's, says it is not in a turn), AGAIN_MS
|
|
12
|
-
*
|
|
13
|
-
* (talk.mjs, RENUDGE_MS); told TOLD_MAX times, its chat says it is not handled.
|
|
11
|
+
* idle (its pulse, Parley's, says it is not in a turn), every AGAIN_MS, at
|
|
12
|
+
* most TOLD_MAX times; then its chat says it was not handled.
|
|
14
13
|
*
|
|
15
14
|
* THE TOOL'S OWN REMINDERS (docket remind --at/--in/--cron) are turned into
|
|
16
15
|
* events here (tick), and told the same way. Its owner sees them in the
|
|
@@ -50,11 +49,7 @@ export function copyPlans(fromWork, toWork, now = Date.now()) {
|
|
|
50
49
|
export const TICK_MS = 5000;
|
|
51
50
|
/* An event not acknowledged is told again after this long, the tool idle... */
|
|
52
51
|
export const AGAIN_MS = 30 * 60_000;
|
|
53
|
-
/* ...
|
|
54
|
-
most, it was then silent for good -- one line lost, and the event waited unseen). */
|
|
55
|
-
export const AGAIN_STEPS_MS = Object.freeze([AGAIN_MS, 60 * 60_000, 120 * 60_000]);
|
|
56
|
-
const againAfter = (count) => AGAIN_STEPS_MS[Math.min(Math.max(count, 1), AGAIN_STEPS_MS.length) - 1];
|
|
57
|
-
/* Told this many times (the first included): its chat says it is not handled, once; it is still told. */
|
|
52
|
+
/* ...this many times at most (the first included); then its chat says so. */
|
|
58
53
|
export const TOLD_MAX = 3;
|
|
59
54
|
|
|
60
55
|
/* AN ANSWER NEVER SHOWN (15-11, #362): the note of a sign-in a companion did for another conversation is
|
|
@@ -173,12 +168,12 @@ export class Dockets {
|
|
|
173
168
|
const told = Object.fromEntries(Object.entries(record.told ?? {}).filter(([id]) => waiting.some((e) => e.id === id)));
|
|
174
169
|
const due = waiting.filter((e) => {
|
|
175
170
|
const t = told[e.id];
|
|
176
|
-
return !t || now - t.at >=
|
|
171
|
+
return !t || (t.count < TOLD_MAX && now - t.at >= AGAIN_MS);
|
|
177
172
|
});
|
|
178
173
|
/* Told again only while it is not in a turn: a busy tool reads its docket when its turn ends. */
|
|
179
174
|
const fresh = due.filter((e) => !told[e.id]);
|
|
180
175
|
if (due.length && (fresh.length || this.#idle(name))) {
|
|
181
|
-
if (await this.#say(name, WAKE).catch(() => false)) for (const e of due) told[e.id] = {
|
|
176
|
+
if (await this.#say(name, WAKE).catch(() => false)) for (const e of due) told[e.id] = { count: (told[e.id]?.count ?? 0) + 1, at: now };
|
|
182
177
|
}
|
|
183
178
|
for (const e of waiting) {
|
|
184
179
|
const t = told[e.id];
|
package/server/main.mjs
CHANGED
|
@@ -27,7 +27,7 @@ import { Conversations, DRAWN_MS, Refusal } from './conversations.mjs';
|
|
|
27
27
|
import { Store, JsonFile } from './store.mjs';
|
|
28
28
|
import { Instance } from './instance.mjs';
|
|
29
29
|
import { loadTools, screenRules } from './tools.mjs';
|
|
30
|
-
import { SigninHelp } from './signinhelp.mjs';
|
|
30
|
+
import { SigninHelp, typeInto } from './signinhelp.mjs';
|
|
31
31
|
import { Vms, runner } from './vm.mjs';
|
|
32
32
|
import { Resources, WORK_TAB } from './resources.mjs';
|
|
33
33
|
import { download } from './files.mjs';
|
|
@@ -46,9 +46,7 @@ import { Dockets, copyPlans } from './dockets.mjs';
|
|
|
46
46
|
import { PULSE_MS } from 'clavarium-parley/ui';
|
|
47
47
|
import { Wakeups, TypingWatch, CALL_PATH } from './wakeups.mjs';
|
|
48
48
|
import { Alerts } from './alerts.mjs';
|
|
49
|
-
import { Talk } from './talk.mjs';
|
|
50
|
-
import { TerminalType } from './terminaltype.mjs';
|
|
51
|
-
import { WAKE as DOCKET_WAKE } from 'clavarium-docket/host';
|
|
49
|
+
import { Talk, escapeCommand } from './talk.mjs';
|
|
52
50
|
import { Toolbox } from './toolbox.mjs';
|
|
53
51
|
import { Guide, commonText } from './guide.mjs';
|
|
54
52
|
import { SignInMailboxes } from './signin.mjs';
|
|
@@ -432,7 +430,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
432
430
|
its machine at a start and when a setting changes. `talk` and
|
|
433
431
|
`wakeups` are made below; only asked once the server runs. */
|
|
434
432
|
const guide = new Guide({ store: new Store(`${dataDir}/guide.json`), vms, conversations: all, resources: folders, secrets, toolbox, tools,
|
|
435
|
-
chat: (name) => Boolean(talk?.brief(name)), say: (name, line) => wakeups.say(name, line
|
|
433
|
+
chat: (name) => Boolean(talk?.brief(name)), say: (name, line) => wakeups.say(name, line), reread: () => talk?.rereadCommand() ?? null });
|
|
436
434
|
/* Why Parley is not in a machine, said once in the log, not at each opening. */
|
|
437
435
|
const parleySaid = new Map();
|
|
438
436
|
all.prepare = async (name, woke) => {
|
|
@@ -475,23 +473,16 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
475
473
|
/* Several models answer a tool's simple questions in the owner's place, where the owner asked: see answerer.mjs. */
|
|
476
474
|
/* The owner's devices are told when something waits for them: see alerts.mjs. */
|
|
477
475
|
const alerts = new Alerts({ store: new Store(`${dataDir}/alerts.json`), keyFile: `${dataDir}/alerts-keys.json`, subject: publicOrigin, ...(alertSend ? { send: alertSend } : {}) });
|
|
478
|
-
|
|
479
|
-
const typingWatch = new TypingWatch();
|
|
480
|
-
let bridge;
|
|
481
|
-
/* THE ONE WAY THIS SERVER TYPES into a tool's terminal (terminaltype.mjs): its terminal warmed, copy mode
|
|
482
|
-
left, the line and its Enter in one command, the bridge's terminal only when that fails, each line said. */
|
|
483
|
-
const typer = new TerminalType({ vms, warm: (name) => bridge?.warm(name), typing: (name) => typingWatch.busy(name),
|
|
484
|
-
terminal: { open: (name) => bridge?.open(name) ?? false, type: (name, line, ms) => bridge?.type(name, line, ms) ?? false } });
|
|
485
|
-
const answerer = new Answerer({ typer, store: new Store(`${dataDir}/answerer.json`), vms, config: answererConfig(env), conversations: all, dataDir, ...(answerFetcher ? { fetcher: answerFetcher } : {}),
|
|
476
|
+
const answerer = new Answerer({ store: new Store(`${dataDir}/answerer.json`), vms, config: answererConfig(env), conversations: all, dataDir, ...(answerFetcher ? { fetcher: answerFetcher } : {}),
|
|
486
477
|
onNeeds: (name, why) => { void alerts.tell({ title: `${instance.name()}: ${name} waits for you`, body: why, url: `/?c=${name}` }); } });
|
|
487
478
|
const answerTimer = answerer.start(answerEveryMs);
|
|
488
479
|
/* A tool is told to get to work when something arrives, or by the clock: see wakeups.mjs. */
|
|
480
|
+
let bridge;
|
|
489
481
|
/* A wake-up typed is said in its chat (talk, made below: called only once a wake-up fires). */
|
|
490
482
|
/* Where its chat is on, what wakes a tool is an event it acknowledges: see dockets.mjs. */
|
|
491
483
|
let signinHelp = null;
|
|
492
484
|
const dockets = new Dockets({ store: new Store(`${dataDir}/dockets.json`), resources: folders,
|
|
493
|
-
|
|
494
|
-
say: (name, line) => (line === DOCKET_WAKE ? wakeups.ring(name, 'docket') : wakeups.say(name, line, { why: 'docket' })),
|
|
485
|
+
say: (name, line) => wakeups.say(name, line),
|
|
495
486
|
event: (name, line) => talk.event(name, line),
|
|
496
487
|
alert: (message) => { void alerts.tell({ ...message, title: `${instance.name()}: ${message.title}` }); },
|
|
497
488
|
/* Not in a turn: its pulse ended, or is old (Parley's own measure). */
|
|
@@ -499,10 +490,11 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
499
490
|
awake: () => all.awake(), chatOn: (name) => talk.isOn(name),
|
|
500
491
|
/* A sign-in a companion did for another conversation (signinhelp.mjs, made below): its answer typed there. */
|
|
501
492
|
acked: (name, e) => signinHelp?.acked(name, e) });
|
|
493
|
+
const typingWatch = new TypingWatch();
|
|
502
494
|
/* WHO WOKE IT (16-11): this server opens a terminal for others (a wake-up, a key); said once it wakes one. */
|
|
503
495
|
const wakeWhy = { why: new Map(), set(name, by) { this.why.set(name, by); }, take(name) { const by = this.why.get(name); this.why.delete(name); return by ?? 'the server'; } };
|
|
504
496
|
all.woken = (name, by, was) => events.add({ kind: 'machine', text: `Machine of ${name}: woken by ${by} (it was ${was})`, conversation: name });
|
|
505
|
-
const wakeups = new Wakeups({ store: new Store(`${dataDir}/wakeups.json`), vms, conversations: all, resources: folders, warm: (name) => { if (!all.awake().includes(name)) wakeWhy.set(name, 'its wake-up'); return bridge?.warm(name); }, docket: dockets, typing: (name) => typingWatch.busy(name),
|
|
497
|
+
const wakeups = new Wakeups({ store: new Store(`${dataDir}/wakeups.json`), vms, conversations: all, resources: folders, warm: (name) => { if (!all.awake().includes(name)) wakeWhy.set(name, 'its wake-up'); return bridge?.warm(name); }, docket: dockets, typing: (name) => typingWatch.busy(name),
|
|
506
498
|
fired: (name, { text }) => talk.event(name, { kind: 'wakeup', text, topic: 'Wake-up' }) });
|
|
507
499
|
const wakeTimer = wakeups.start(wakeEveryMs);
|
|
508
500
|
const docketTimer = dockets.start(wakeEveryMs);
|
|
@@ -554,7 +546,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
554
546
|
for (const conversation of writers) {
|
|
555
547
|
let path = null;
|
|
556
548
|
if (full) { try { path = talk.keepText(conversation, 'git-remote-refused.txt', full); } catch { path = null; } }
|
|
557
|
-
if (await wakeups.say(conversation, path ? `${line.replace(/\.$/, '')}; all it said: ${path}.` : line
|
|
549
|
+
if (await wakeups.say(conversation, path ? `${line.replace(/\.$/, '')}; all it said: ${path}.` : line) === true) heard = true;
|
|
558
550
|
}
|
|
559
551
|
return heard;
|
|
560
552
|
};
|
|
@@ -572,7 +564,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
572
564
|
what is already known of a machine used instead of asking (talk.mjs). */
|
|
573
565
|
/* `settled` (17-11): how long its terminal has been open and quiet -- without it, the line after a restart
|
|
574
566
|
was typed REREAD_AFTER_MS after, into a tool maybe still loading (talk.mjs, READY). */
|
|
575
|
-
|
|
567
|
+
terminal: { open: (name) => bridge?.open(name) ?? false, type: (name, line, ms) => bridge?.type(name, line, ms) ?? false, droppedAt: (name) => bridge?.droppedAt(name), settled: (name) => bridge?.settled(name) ?? null },
|
|
576
568
|
health: { of: (name) => health?.of(name) ?? null },
|
|
577
569
|
/* A secret pasted in a message is lifted out before the message is kept:
|
|
578
570
|
it goes to the short-lived vault and the message keeps only a marker
|
|
@@ -617,7 +609,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
617
609
|
conversations: () => all.list(), tools: () => tools, awake: () => all.awake(), chatOn: (name) => talk.isOn(name),
|
|
618
610
|
workFolder: (name) => folders.workFolder(name),
|
|
619
611
|
browsers: (name) => { try { return tethers.store().targets().filter((t) => t.kind === 'browser').map((t) => ({ id: t.id, level: t.grants?.[`conversation:${name}`]?.level ?? '' })).filter((b) => b.level); } catch { return []; } },
|
|
620
|
-
post: (name, event) => dockets.post(name, event), type: (name, text) =>
|
|
612
|
+
post: (name, event) => dockets.post(name, event), type: (name, text) => typeInto(vms, name, text),
|
|
621
613
|
event: (name, line) => talk.event(name, line) });
|
|
622
614
|
const stopSigninHelp = signinHelp.start();
|
|
623
615
|
all.signinHelp = signinHelp;
|
|
@@ -684,13 +676,13 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
684
676
|
/* Its tool told it may install them again: through its docket where its chat is on, else typed to its agent. */
|
|
685
677
|
const line = toolLine(link);
|
|
686
678
|
try { if (dockets.on(name)) { dockets.post(name, { kind: 'shared-folder', text: line, data: { folder: link.folder, path: link.path } }); return; } } catch { /* typed instead */ }
|
|
687
|
-
if (all.list().find((c) => c.name === name)?.ai === true) void wakeups.say(name, line
|
|
679
|
+
if (all.list().find((c) => c.name === name)?.ai === true) void wakeups.say(name, line).catch(() => {});
|
|
688
680
|
};
|
|
689
681
|
const health = new Health({ vms, conversations: all, resources: folders, links: linkGuard, seen: new Store(`${dataDir}/health-seen.json`), ...(healthSettleMs === undefined ? {} : { settleMs: healthSettleMs }) });
|
|
690
682
|
const stopHealth = health.start(healthEveryMs);
|
|
691
683
|
/* What is wrong with its machine is said in its chat too, where it happened. */
|
|
692
684
|
/* And what its owner chose that it does on top (healthreact.mjs): its agent told, or a command run. */
|
|
693
|
-
const reacting = new HealthReact({ store: new Store(`${dataDir}/health-react.json`), say: (name, line) => wakeups.say(name, line
|
|
685
|
+
const reacting = new HealthReact({ store: new Store(`${dataDir}/health-react.json`), say: (name, line) => wakeups.say(name, line), exec: (name, argv, options) => vms.exec(name, argv, options),
|
|
694
686
|
isAgent: (name) => all.list().find((c) => c.name === name)?.ai === true, event: (name, line) => talk.event(name, line) });
|
|
695
687
|
/* Where its chat is on, its agent is given an event when its disk or memory crosses a level (healthdocket.mjs);
|
|
696
688
|
not where its owner turned on its own reaction (above): one way of telling it, not two. */
|
|
@@ -903,7 +895,8 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
903
895
|
stop: async (name) => {
|
|
904
896
|
const c = all.get(name);
|
|
905
897
|
if (c?.phase !== 'ready' || c.asleep === true) throw new Refusal(409, 'This conversation is asleep: nothing to stop.');
|
|
906
|
-
|
|
898
|
+
const r = await vms.exec(name, escapeCommand(), { timeoutMs: 30_000 });
|
|
899
|
+
if (r.code !== 0) throw new Refusal(502, 'Its turn could not be stopped.');
|
|
907
900
|
return { state: 'awake' };
|
|
908
901
|
},
|
|
909
902
|
},
|
package/server/signinhelp.mjs
CHANGED
|
@@ -30,7 +30,8 @@
|
|
|
30
30
|
import { lstatSync, readFileSync, writeFileSync, renameSync, rmSync } from 'node:fs';
|
|
31
31
|
import { join } from 'node:path';
|
|
32
32
|
import { CODE } from '../config/launch/screen-watch.mjs';
|
|
33
|
-
import { Refusal } from './conversations.mjs';
|
|
33
|
+
import { Refusal, SESSION } from './conversations.mjs';
|
|
34
|
+
import { SOCKET } from './tmux.mjs';
|
|
34
35
|
|
|
35
36
|
export const KIND = 'signin-help';
|
|
36
37
|
export const ASK = 'signin-ask.json';
|
|
@@ -57,6 +58,13 @@ export function linkAllowed(link, domains = []) {
|
|
|
57
58
|
}
|
|
58
59
|
const cut = (s, n) => { const t = String(s ?? '').replace(/\s+/g, ' ').trim(); return t.length > n ? `${t.slice(0, n - 1)}…` : t; };
|
|
59
60
|
|
|
61
|
+
/* The code typed into the tool, then Enter -- as screen-watch types a code the person pastes. Never logged. */
|
|
62
|
+
export async function typeInto(vms, name, text) {
|
|
63
|
+
const tmux = ['tmux', '-L', SOCKET, 'send-keys', '-t', `=${SESSION}:`];
|
|
64
|
+
if ((await vms.exec(name, [...tmux, '-l', '--', text], { timeoutMs: 30_000 })).code !== 0) return false;
|
|
65
|
+
return (await vms.exec(name, [...tmux, 'Enter'], { timeoutMs: 30_000 })).code === 0;
|
|
66
|
+
}
|
|
67
|
+
|
|
60
68
|
export class SigninHelp {
|
|
61
69
|
#store; #conversations; #tools; #awake; #chatOn; #work; #browsers; #post; #type; #event; #now;
|
|
62
70
|
/* asker -> { id (its ask), companion, event (the docket event's id), at, file, code (a code is awaited) } */
|
package/server/talk.mjs
CHANGED
|
@@ -67,8 +67,8 @@ import { featureWords } from './features.mjs';
|
|
|
67
67
|
import { settingsWords } from './settingswords.mjs';
|
|
68
68
|
import { importFile } from './files.mjs';
|
|
69
69
|
import { KEYS } from 'clavarium-parley/ui';
|
|
70
|
-
import { Refusal } from './conversations.mjs';
|
|
71
|
-
import {
|
|
70
|
+
import { Refusal, SESSION } from './conversations.mjs';
|
|
71
|
+
import { SOCKET } from './tmux.mjs';
|
|
72
72
|
import { isConversationName } from './names.mjs';
|
|
73
73
|
|
|
74
74
|
export const FOLDER = '.parley';
|
|
@@ -90,12 +90,18 @@ export function partOf(query) {
|
|
|
90
90
|
for (const k of ['before', 'from', 'since']) { const v = get(k); if (typeof v === 'string' && PART.test(v)) out[k] = v; }
|
|
91
91
|
return Object.keys(out).length ? out : null;
|
|
92
92
|
}
|
|
93
|
+
const PANE = `=${SESSION}:`;
|
|
93
94
|
/* Nothing is typed in a terminal somebody typed in this recently. */
|
|
94
95
|
export const TYPING_QUIET_MS = 4000;
|
|
95
96
|
/* A line that waits is tried again this often (a machine that does not run is not touched: only its state is asked). */
|
|
96
97
|
export const RETRY_MS = 10_000;
|
|
97
|
-
/*
|
|
98
|
-
|
|
98
|
+
/* THE LINE AND ITS ENTER ARE TYPED APART, this long apart. Arriving in one
|
|
99
|
+
read, "text" and Enter look like a paste to a tool that guesses pastes from
|
|
100
|
+
how fast the keys come (measured in tmux: send-keys of both in one command
|
|
101
|
+
gives the program one read, "text\r"): the Enter is then a new line in its
|
|
102
|
+
input, not a send. Waited inside the same tmux command (run-shell -d) or
|
|
103
|
+
by the terminal bridge: no second call into the machine. */
|
|
104
|
+
export const ENTER_AFTER_MS = 200;
|
|
99
105
|
/* WHAT IS KNOWN, NOT ASKED. Asking the VM manager whether the machine runs
|
|
100
106
|
costs half a second for every message (measured on a real server). The
|
|
101
107
|
machine is known to run when its terminal is kept open (it is closed before
|
|
@@ -104,6 +110,24 @@ export { ENTER_AFTER_MS, typeCommand, TYPED_AT, enterCommand, escapeCommand } fr
|
|
|
104
110
|
cases only if its terminal was not closed since. Anything else is asked. */
|
|
105
111
|
export const TYPED_KNOWN_MS = 60_000;
|
|
106
112
|
export const HEALTH_KNOWN_MS = 150_000;
|
|
113
|
+
/* The one tmux command that types a line, waits, and presses Enter: an
|
|
114
|
+
argument vector, no shell. tmux reads an argument that ENDS with ";" as the
|
|
115
|
+
end of a command: such a last ";" is written "\;", which tmux gives back
|
|
116
|
+
as ";" (tried). */
|
|
117
|
+
export const enterCommand = () => ['tmux', '-L', SOCKET, 'send-keys', '-t', PANE, 'Enter'];
|
|
118
|
+
/* Escape, alone: what the Esc key of the page's key row sends -- a tool's current turn stopped (an API key that may act, apikeys.mjs). */
|
|
119
|
+
export const escapeCommand = () => ['tmux', '-L', SOCKET, 'send-keys', '-t', PANE, 'Escape'];
|
|
120
|
+
/* A PANE SCROLLED BACK IS IN COPY MODE (`mouse on`: the wheel of any screen puts it there, and it stays
|
|
121
|
+
there when that screen goes away): the keys of a line typed then are copy-mode commands, the line never
|
|
122
|
+
reaches the tool and its Enter only leaves the mode (tried with tmux 3.4). The mode is left first, in
|
|
123
|
+
the same command -- nothing is done to a pane that is not in a mode (no shell: -F reads a format). */
|
|
124
|
+
const LEAVE_MODE = ['if-shell', '-F', '-t', PANE, '#{pane_in_mode}', `send-keys -t ${PANE} -X cancel`, ';'];
|
|
125
|
+
export function typeCommand(line) {
|
|
126
|
+
const text = line.endsWith(';') ? `${line.slice(0, -1)}\\;` : line;
|
|
127
|
+
return ['tmux', '-L', SOCKET, ...LEAVE_MODE, 'send-keys', '-t', PANE, '-l', '--', text, ';', 'run-shell', '-d', String(ENTER_AFTER_MS / 1000), ';', 'send-keys', '-t', PANE, 'Enter'];
|
|
128
|
+
}
|
|
129
|
+
/* Where the line is in typeCommand's argument vector. */
|
|
130
|
+
export const TYPED_AT = 3 + LEAVE_MODE.length + 5;
|
|
107
131
|
/* Added to Parley's invitation, this server's own sentence: a branch can be
|
|
108
132
|
checked out in one folder only, and /tmp is emptied when the machine
|
|
109
133
|
restarts, with the work left there. Typed in a terminal: no quote, no
|
|
@@ -111,8 +135,8 @@ export const HEALTH_KNOWN_MS = 150_000;
|
|
|
111
135
|
export const BRANCHES = 'Check out your branches in the main folder of the repository or under /work, never in /tmp: a branch can be checked out in one folder only, and /tmp is emptied when the machine restarts. The checks before sending run in a copy made at exactly the commit to send (CLAVARIUM_CHECK_COPY, CLAVARIUM_CHECK_HEAD): never write a check that needs the main folder on a branch or at that commit.';
|
|
112
136
|
/* THE LINE TYPED AGAIN BY ITSELF (17-11): one line lost (a pane in copy mode, a tool drawing a modal)
|
|
113
137
|
silenced every later one, the tool "told" till it read. A message still unread this long after its
|
|
114
|
-
line was typed has it typed again, these long after the last
|
|
115
|
-
|
|
138
|
+
line was typed has it typed again, these long after the last -- three times at most, then no more
|
|
139
|
+
(never a reminder without end): the owner's "Remind it" is there. Kept in its record: a restart of this server goes on. */
|
|
116
140
|
export const RENUDGE_MS = Object.freeze([60_000, 180_000, 600_000]);
|
|
117
141
|
/* After a restart, the tool is given this long to start before REREAD is typed. */
|
|
118
142
|
export const REREAD_AFTER_MS = 10_000;
|
|
@@ -212,7 +236,7 @@ const PART = /^[A-Za-z0-9._~-]{1,200}$/;
|
|
|
212
236
|
export class Talk {
|
|
213
237
|
#store; #words; #vms; #conversations; #resources; #toolbox; #warm; #alert; #spoke; #inRoom; #listening = new Map(); #every; #now;
|
|
214
238
|
#typedAt = new Map(); #nextTry = new Map(); #trying = new Map(); #ticking = new Map(); #timer; #lastLang = 'en'; #rereadAfter;
|
|
215
|
-
#terminal; #
|
|
239
|
+
#terminal; #health; #ranAt = new Map(); #kept; #screen; #dropSecret; #log;
|
|
216
240
|
|
|
217
241
|
/* `alert({ title, body, url })`: told when the tool asks, or waits.
|
|
218
242
|
`words`: a store for the owner's choice of words (one record). */
|
|
@@ -222,10 +246,8 @@ export class Talk {
|
|
|
222
246
|
/* `keptDir`: where each conversation's thread is kept (its own folder),
|
|
223
247
|
in this server's data -- never in the work folder, which its machine
|
|
224
248
|
writes. Without it, the bridge folder is all there is. */
|
|
225
|
-
constructor({ store, words, vms, conversations, resources, toolbox = null, warm = async () => {}, alert = () => {}, spoke = () => {}, inRoom = () => {}, listenEveryMs = 2000, now = () => Date.now(), rereadAfterMs = REREAD_AFTER_MS, terminal = null, health = null, keptDir = null, screen = null, dropSecret = null, log = (line) => console.log(line)
|
|
249
|
+
constructor({ store, words, vms, conversations, resources, toolbox = null, warm = async () => {}, alert = () => {}, spoke = () => {}, inRoom = () => {}, listenEveryMs = 2000, now = () => Date.now(), rereadAfterMs = REREAD_AFTER_MS, terminal = null, health = null, keptDir = null, screen = null, dropSecret = null, log = (line) => console.log(line) }) {
|
|
226
250
|
this.#log = log;
|
|
227
|
-
/* `typer`: the server's one TerminalType (main.mjs), or one of its own made of what is given here. */
|
|
228
|
-
this.#typer = typer ?? new TerminalType({ vms, terminal, warm, log });
|
|
229
251
|
this.#terminal = terminal; this.#health = health; this.#kept = keptDir; this.#screen = screen; this.#dropSecret = dropSecret;
|
|
230
252
|
this.#store = store; this.#words = words; this.#vms = vms; this.#conversations = conversations; this.#resources = resources; this.#toolbox = toolbox; this.#warm = warm; this.#alert = alert; this.#spoke = spoke; this.#inRoom = inRoom; this.#every = listenEveryMs; this.#now = now; this.#rereadAfter = rereadAfterMs;
|
|
231
253
|
for (const s of store.all()) if (s.on === true) this.#listen(s.name);
|
|
@@ -468,16 +490,22 @@ export class Talk {
|
|
|
468
490
|
return this.of(name);
|
|
469
491
|
}
|
|
470
492
|
|
|
471
|
-
/* Types a line and Enter in the tool's terminal
|
|
472
|
-
copy mode
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
/* WAKE and URGENT are the chat's doorbells (ring): heard once its read count moves (RENUDGE_MS). */
|
|
493
|
+
/* Types a line and Enter in the tool's terminal. BY ONE COMMAND IN THE MACHINE FIRST (17-11): it
|
|
494
|
+
leaves copy mode before it types (typeCommand), which the terminal the bridge keeps open cannot --
|
|
495
|
+
bytes down it are copy-mode keys while the pane is scrolled back, and the line was lost, said
|
|
496
|
+
typed. That terminal, into the same tmux pane, when the command fails. Each line said in the log,
|
|
497
|
+
and each one lost, with why. */
|
|
477
498
|
async #type(name, line) {
|
|
478
|
-
const
|
|
479
|
-
|
|
499
|
+
const what = line === WAKE ? 'wake' : line === URGENT ? 'urgent' : line.length > 60 ? `${line.slice(0, 60)}...` : line;
|
|
500
|
+
await this.#warm(name);
|
|
501
|
+
const ran = await this.#vms.exec(name, typeCommand(line), { timeoutMs: 30_000 }).catch((error) => ({ code: -1, stderr: error?.message }));
|
|
502
|
+
if (ran.code === 0) { this.#ranAt.set(name, this.#now()); this.#log(`talk: ${name}: typed (${what})`); return true; }
|
|
503
|
+
const why = `exit ${ran.code}${ran.stderr ? `: ${String(ran.stderr).trim().slice(0, 200)}` : ''}`;
|
|
504
|
+
const down = this.#terminal?.open(name) ? await Promise.resolve(this.#terminal.type(name, line, ENTER_AFTER_MS)).catch(() => false) : false;
|
|
505
|
+
/* The line went, its Enter did not (the channel closed meanwhile): the Enter alone, never the line twice. */
|
|
506
|
+
const ok = down === true || (down === 'enter' && (await this.#vms.exec(name, enterCommand(), { timeoutMs: 30_000 }).catch(() => ({ code: -1 }))).code === 0);
|
|
480
507
|
if (ok) this.#ranAt.set(name, this.#now());
|
|
508
|
+
this.#log(ok ? `talk: ${name}: typed down its terminal (${what}), the command in the machine failed (${why})` : `talk: ${name}: NOT typed (${what}): ${why}; ${this.#terminal?.open(name) ? 'its terminal refused too' : 'no terminal open'}`);
|
|
481
509
|
return ok;
|
|
482
510
|
}
|
|
483
511
|
|
|
@@ -726,7 +754,6 @@ export class Talk {
|
|
|
726
754
|
if (!this.#conversations.awake().includes(name)) return later(RETRY_MS);
|
|
727
755
|
const quiet = this.#now() - (this.#typedAt.get(name) ?? 0);
|
|
728
756
|
if (quiet < TYPING_QUIET_MS) return later(TYPING_QUIET_MS - quiet + 100);
|
|
729
|
-
if (this.#typer.busy(name)) return later(RETRY_MS);
|
|
730
757
|
if (!(await this.#runs(name))) return later(RETRY_MS);
|
|
731
758
|
if (this.#terminal?.settled) {
|
|
732
759
|
await this.#warm(name);
|
|
@@ -785,8 +812,6 @@ export class Talk {
|
|
|
785
812
|
if (!this.#conversations.awake().includes(name)) return waits('asleep', RETRY_MS);
|
|
786
813
|
const quiet = this.#now() - (this.#typedAt.get(name) ?? 0);
|
|
787
814
|
if (quiet < TYPING_QUIET_MS) return waits('typing', TYPING_QUIET_MS - quiet + 100);
|
|
788
|
-
/* A line left half typed there (TypingWatch): the line waits, never typed into it. */
|
|
789
|
-
if (this.#typer.busy(name)) return waits('typing', RETRY_MS);
|
|
790
815
|
if (!(await this.#runs(name))) return waits('asleep', RETRY_MS);
|
|
791
816
|
if (renudge) this.#log(`talk: ${name}: still unread ${Math.round((this.#now() - Date.parse(r.typedAt ?? '')) / 1000)} s after its line: typed again (${(r.renudged ?? 0) + 1})`);
|
|
792
817
|
if (!(await this.#type(name, urgent ? URGENT : WAKE).catch((error) => { this.#log(`talk: ${name}: NOT typed: ${error?.message}`); return false; }))) return waits('failed', RETRY_MS);
|
|
@@ -824,8 +849,10 @@ export class Talk {
|
|
|
824
849
|
if (unread === 0) { this.#store.put({ ...r, woke: false }); return; }
|
|
825
850
|
/* It read since, and more was written: the line is owed now. */
|
|
826
851
|
if (this.#readSince(r.name, r)) { await this.#wake(r.name); return; }
|
|
827
|
-
/* Still unread long after: typed again, RENUDGE_MS apart
|
|
828
|
-
|
|
852
|
+
/* Still unread long after: typed again, RENUDGE_MS apart -- AS MANY TIMES AS THERE ARE, NO MORE (17-11,
|
|
853
|
+
the owner: never a reminder without end). Then it waits: its chat keeps "Remind it" for the owner. */
|
|
854
|
+
if ((r.renudged ?? 0) >= RENUDGE_MS.length) return;
|
|
855
|
+
const after = RENUDGE_MS[r.renudged ?? 0];
|
|
829
856
|
const at = Date.parse(r.typedAt ?? '');
|
|
830
857
|
if (Number.isFinite(at) && this.#now() - at >= after && this.#now() >= (this.#nextTry.get(r.name) ?? 0)) await this.#wake(r.name, true, false, true);
|
|
831
858
|
return;
|
package/server/updates.mjs
CHANGED
|
@@ -109,7 +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
|
-
|
|
112
|
+
/* `fetch`: nothing of that version ran (npm could not fetch it): the page says it is tried again by itself
|
|
113
|
+
(app.js, updates-retry-note). Left out before 17-11, every such failure read "It did not start here". */
|
|
114
|
+
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 })),
|
|
113
115
|
};
|
|
114
116
|
}
|
|
115
117
|
|
package/server/vm.mjs
CHANGED
|
@@ -80,6 +80,19 @@ export function runner(prefix) {
|
|
|
80
80
|
|
|
81
81
|
/* The verbs that change a machine: its state is asked again after them. */
|
|
82
82
|
export const TRIM_MS = 120_000;
|
|
83
|
+
export const COUNT_EVERY_MS = 5 * 60_000;
|
|
84
|
+
/* What a command to the host is, for the tally: its verb, and for a command in a machine the program it runs
|
|
85
|
+
(past `sudo -n clavarium-enter <name> --`, `timeout ...`, `sh -c`'s script left out). Never its arguments. */
|
|
86
|
+
export function commandKind(argv) {
|
|
87
|
+
const a = argv.map(String);
|
|
88
|
+
if (a[0] !== 'vm' || a[1] !== 'exec') return a.slice(0, 2).join(' ');
|
|
89
|
+
let rest = a.slice(a.indexOf('--') + 1);
|
|
90
|
+
if (rest[0] === 'sudo' && rest[1] === '-n') rest = rest.slice(2);
|
|
91
|
+
if (rest[0] === 'clavarium-enter') rest = rest.slice(rest.indexOf('--') + 1);
|
|
92
|
+
if (rest[0] === 'timeout') rest = rest.slice(rest.findIndex((x, i) => i > 0 && !/^(-k|\d+)$/.test(x)));
|
|
93
|
+
const prog = rest[0] === 'sh' ? `sh:${(rest[3] ?? rest[2] ?? '').split('/').pop()}` : rest[0] === 'tmux' ? `tmux ${rest.find((x) => /^(send-keys|if-shell|capture-pane|has-session|kill-server|new-session)$/.test(x)) ?? ''}` : rest[0];
|
|
94
|
+
return `vm exec ${String(prog ?? '').slice(0, 40)}`;
|
|
95
|
+
}
|
|
83
96
|
const CHANGES = new Set(['launch', 'clone', 'start', 'stop', 'suspend', 'kill', 'halt', 'hardstop', 'delete', 'purge', 'set', 'rename', 'restore', 'snapshot', 'revive', 'reclaim']);
|
|
84
97
|
export const STATES_FRESH_MS = 3000;
|
|
85
98
|
/* The VM manager did not say what a machine is in: not an answer about the machine. */
|
|
@@ -100,10 +113,26 @@ export class Vms {
|
|
|
100
113
|
this.run = async (argv, options) => {
|
|
101
114
|
const changes = argv[0] === 'vm' && CHANGES.has(argv[1]);
|
|
102
115
|
if (changes) this.#snapshot = null;
|
|
103
|
-
|
|
116
|
+
const began = this.#now();
|
|
117
|
+
try { return await this.#ask(argv, options); } finally { if (changes) this.#snapshot = null; this.#count(argv, this.#now() - began); }
|
|
104
118
|
};
|
|
105
119
|
}
|
|
106
120
|
|
|
121
|
+
/* HOW MUCH THIS SERVER ASKS OF THE HOST (17-11: the owner saw a page wait 10-15 s with an idle CPU --
|
|
122
|
+
every command to a machine goes through the VM manager, one after another): each command counted by
|
|
123
|
+
what it is, with its time; every COUNT_EVERY_MS the tally is said in the log, the busiest first. */
|
|
124
|
+
#tally = new Map(); #tallyFrom = 0;
|
|
125
|
+
#count(argv, ms) {
|
|
126
|
+
const now = this.#now();
|
|
127
|
+
if (!this.#tallyFrom) this.#tallyFrom = now;
|
|
128
|
+
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)]);
|
|
129
|
+
if (now - this.#tallyFrom < COUNT_EVERY_MS) return;
|
|
130
|
+
const rows = [...this.#tally].sort((a, b) => b[1][1] - a[1][1]);
|
|
131
|
+
const all = rows.reduce((n, [, v]) => n + v[0], 0); const busy = rows.reduce((n, [, v]) => n + v[1], 0);
|
|
132
|
+
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('; ')}`);
|
|
133
|
+
this.#tally = new Map(); this.#tallyFrom = now;
|
|
134
|
+
}
|
|
135
|
+
|
|
107
136
|
/* EVERY MACHINE'S STATE, in one question to the VM manager, shared by every caller for a
|
|
108
137
|
few seconds (and by those who ask while it is being asked). */
|
|
109
138
|
async #states(fresh = false) {
|
package/server/wakeups.mjs
CHANGED
|
@@ -36,8 +36,8 @@
|
|
|
36
36
|
*/
|
|
37
37
|
import { lstatSync, readdirSync } from 'node:fs';
|
|
38
38
|
import { randomUUID, randomBytes, createHash } from 'node:crypto';
|
|
39
|
-
import { Refusal } from './conversations.mjs';
|
|
40
|
-
import {
|
|
39
|
+
import { Refusal, SESSION } from './conversations.mjs';
|
|
40
|
+
import { SOCKET } from './tmux.mjs';
|
|
41
41
|
import { isConversationName } from './names.mjs';
|
|
42
42
|
|
|
43
43
|
export const TICK_MS = 5000;
|
|
@@ -96,6 +96,9 @@ export function cron(line) {
|
|
|
96
96
|
return (date) => minute.has(date.getMinutes()) && hour.has(date.getHours()) && month.has(date.getMonth() + 1)
|
|
97
97
|
&& (anyDay && anyWeekday ? true : anyDay ? weekday.has(date.getDay()) : anyWeekday ? day.has(date.getDate()) : day.has(date.getDate()) || weekday.has(date.getDay()));
|
|
98
98
|
}
|
|
99
|
+
const PANE = `=${SESSION}:`;
|
|
100
|
+
const HOLD_STEP_MS = 1000;
|
|
101
|
+
const HOLD_MAX_MS = 5 * 60_000;
|
|
99
102
|
|
|
100
103
|
/* WHO IS TYPING IN A TERMINAL, from what screens send (bridge.mjs onTyped).
|
|
101
104
|
Busy: a key in the last seconds, or a line begun and not yet sent
|
|
@@ -147,23 +150,22 @@ const FIRED_SHOWN = 120;
|
|
|
147
150
|
const sameDay = (a, b) => a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
|
|
148
151
|
|
|
149
152
|
export class Wakeups {
|
|
150
|
-
#store; #vms; #conversations; #resources; #warm; #now; #fired; #docket; #typing; #
|
|
153
|
+
#store; #vms; #conversations; #resources; #warm; #now; #fired; #docket; #typing; #pause; #held = new Map(); #busy = false;
|
|
151
154
|
|
|
152
155
|
/* `warm(name)`: opens the terminal of a machine that runs, if it is not open.
|
|
153
156
|
`fired(name, { text, item })`: a wake-up was typed (its chat says so: Talk.event). */
|
|
154
157
|
/* `docket`: { on(name), post(name, {kind, text, data}) } (dockets.mjs), or none: typed always. */
|
|
155
158
|
/* `typing(name)`: someone is typing in its terminal from a screen (see TypingWatch): a line is held until it is free. */
|
|
156
|
-
constructor({ store, vms, conversations, resources, warm = async () => {}, now = () => new Date(), fired = () => {}, docket = null, typing = () => false, pause = (ms) => new Promise((ok) => setTimeout(ok, ms))
|
|
159
|
+
constructor({ store, vms, conversations, resources, warm = async () => {}, now = () => new Date(), fired = () => {}, docket = null, typing = () => false, pause = (ms) => new Promise((ok) => setTimeout(ok, ms)) }) {
|
|
157
160
|
this.#store = store; this.#vms = vms; this.#conversations = conversations; this.#resources = resources; this.#warm = warm; this.#now = now; this.#fired = fired; this.#docket = docket;
|
|
158
|
-
this.#typing = typing;
|
|
159
|
-
/* `typer`: the server's one TerminalType (main.mjs): every line typed the same way, said in the log. */
|
|
160
|
-
this.#typer = typer ?? new TerminalType({ vms, typing, now: () => this.#now().getTime(), pause, log: () => {} });
|
|
161
|
+
this.#typing = typing; this.#pause = pause;
|
|
161
162
|
}
|
|
162
163
|
/* Where its chat is on, posted to its docket (told at its next tick); else typed. Resolves with what to say of it, and whether it went. */
|
|
163
164
|
async #deliver(name, item, text) {
|
|
164
165
|
if (this.#docket?.on(name)) {
|
|
165
166
|
try { this.#docket.post(name, { kind: item.kind, text, data: { wakeup: item.id } }); return { ok: true, what: `Posted to its docket: ${text}` }; } catch { /* its folder: typed instead */ }
|
|
166
167
|
}
|
|
168
|
+
await this.#free(name);
|
|
167
169
|
const typed = await this.#type(name, text).catch(() => false);
|
|
168
170
|
return { ok: typed, what: typed ? `Typed: ${text}` : 'Could not be typed: is its tool running?' };
|
|
169
171
|
}
|
|
@@ -319,10 +321,16 @@ export class Wakeups {
|
|
|
319
321
|
return withFiles(item.message, arrived);
|
|
320
322
|
}
|
|
321
323
|
|
|
322
|
-
/*
|
|
323
|
-
async #
|
|
324
|
+
/* Typed into a command being typed, both were broken (seen 24-10): wait for the line to be free, a while at most. */
|
|
325
|
+
async #free(name) {
|
|
326
|
+
for (const start = this.#now().getTime(); this.#typing(name) && this.#now().getTime() - start < HOLD_MAX_MS;) await this.#pause(HOLD_STEP_MS);
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
async #type(name, text) {
|
|
324
330
|
await this.#warm(name);
|
|
325
|
-
|
|
331
|
+
const tmux = ['tmux', '-L', SOCKET, 'send-keys', '-t', PANE];
|
|
332
|
+
if ((await this.#vms.exec(name, [...tmux, '-l', '--', text], { timeoutMs: 30_000 })).code !== 0) return false;
|
|
333
|
+
return (await this.#vms.exec(name, [...tmux, 'Enter'], { timeoutMs: 30_000 })).code === 0;
|
|
326
334
|
}
|
|
327
335
|
|
|
328
336
|
/* A line from this server itself (a repository that could not be read,
|
|
@@ -332,17 +340,10 @@ export class Wakeups {
|
|
|
332
340
|
/* One line at a time into a terminal: two said at once were typed into each other, then sent
|
|
333
341
|
as one (two repositories moving together, seen 20-10). */
|
|
334
342
|
#queue = new Map();
|
|
335
|
-
async say(name, text
|
|
336
|
-
return this.#inTurn(name, () => this.#type(name, cleanMessage(text), why));
|
|
337
|
-
}
|
|
338
|
-
/* A doorbell (terminaltype.mjs, DOORBELLS: the docket's), in the same queue as every line. */
|
|
339
|
-
async ring(name, source) {
|
|
340
|
-
return this.#inTurn(name, async () => { await this.#warm(name); return this.#typer.ring(name, source); });
|
|
341
|
-
}
|
|
342
|
-
#inTurn(name, type) {
|
|
343
|
+
async say(name, text) {
|
|
343
344
|
if (!this.#conversations.awake().includes(name)) return false;
|
|
344
345
|
const before = this.#queue.get(name) ?? Promise.resolve();
|
|
345
|
-
const mine = before.then(type).catch(() => false);
|
|
346
|
+
const mine = before.then(() => this.#free(name)).then(() => this.#type(name, cleanMessage(text)).catch(() => false));
|
|
346
347
|
this.#queue.set(name, mine);
|
|
347
348
|
void mine.finally(() => { if (this.#queue.get(name) === mine) this.#queue.delete(name); });
|
|
348
349
|
return mine;
|
package/server/terminaltype.mjs
DELETED
|
@@ -1,135 +0,0 @@
|
|
|
1
|
-
/* TYPED INTO A TOOL'S TERMINAL: the one way this server types there (17-11).
|
|
2
|
-
*
|
|
3
|
-
* Any tool (Claude Code, Vibe, OpenCode...) runs in the tmux pane of its
|
|
4
|
-
* conversation's machine. What this server types there -- the chat's line
|
|
5
|
-
* (talk.mjs), a wake-up and the docket's line (wakeups.mjs, dockets.mjs), a
|
|
6
|
-
* server line (gitkeeper.mjs, guide.mjs...), an answer (answerer.mjs), a
|
|
7
|
-
* sign-in code (signinhelp.mjs), the Esc of an API key (apikeys.mjs) -- goes
|
|
8
|
-
* through here, typed the same way:
|
|
9
|
-
*
|
|
10
|
-
* WARM FIRST the terminal of a machine that runs is opened, if it
|
|
11
|
-
* is not (the tool is started with it).
|
|
12
|
-
* NEVER OVER A PERSON a line waits while somebody types in that terminal
|
|
13
|
-
* from a screen (TypingWatch, wakeups.mjs), a while at most
|
|
14
|
-
* (or is not typed, for what is only right now: an answer):
|
|
15
|
-
* typed into a command being typed, both were broken (seen 24-10).
|
|
16
|
-
* ONE COMMAND copy mode left, the line, a pause, Enter: one tmux
|
|
17
|
-
* command in the machine (typeCommand).
|
|
18
|
-
* ELSE ITS TERMINAL the terminal the bridge keeps open on the same pane,
|
|
19
|
-
* only when that command failed.
|
|
20
|
-
* SAID IN THE LOG each line typed, each one lost, with why.
|
|
21
|
-
*
|
|
22
|
-
* TWO WAYS INTO A TOOL, AND ONLY TWO: its files (.parley, .docket: what is
|
|
23
|
-
* to be read, the content itself) and its terminal. What is typed there is a
|
|
24
|
-
* DOORBELL (ring): one short line, never content, that sends the tool to its
|
|
25
|
-
* files -- its delivery known from what the tool writes there (Parley's read
|
|
26
|
-
* count, talk.mjs; the docket's acknowledgements, dockets.mjs), rung again
|
|
27
|
-
* until then. typeLine types real text, for the few lines that are content
|
|
28
|
-
* (a wake-up's own words, set by its owner; an answer; a sign-in code): the
|
|
29
|
-
* same command, the same log.
|
|
30
|
-
*
|
|
31
|
-
* What a person types from the page's terminal never comes here: that is the
|
|
32
|
-
* person typing, down the bridge (bridge.mjs).
|
|
33
|
-
*/
|
|
34
|
-
import { WAKE as CHAT_WAKE, URGENT as CHAT_URGENT } from 'clavarium-parley/host';
|
|
35
|
-
import { WAKE as DOCKET_WAKE } from 'clavarium-docket/host';
|
|
36
|
-
import { SESSION } from './conversations.mjs';
|
|
37
|
-
import { SOCKET } from './tmux.mjs';
|
|
38
|
-
|
|
39
|
-
const PANE = `=${SESSION}:`;
|
|
40
|
-
/* THE LINE AND ITS ENTER ARE TYPED APART, this long apart. Arriving in one
|
|
41
|
-
read, "text" and Enter look like a paste to a tool that guesses pastes from
|
|
42
|
-
how fast the keys come (measured in tmux: send-keys of both in one command
|
|
43
|
-
gives the program one read, "text\r"): the Enter is then a new line in its
|
|
44
|
-
input, not a send. Waited inside the same tmux command (run-shell -d) or
|
|
45
|
-
by the terminal bridge: no second call into the machine. */
|
|
46
|
-
export const ENTER_AFTER_MS = 200;
|
|
47
|
-
/* A line waits this long at most for the person typing to stop, looked at this often. */
|
|
48
|
-
export const HOLD_MAX_MS = 5 * 60_000;
|
|
49
|
-
export const HOLD_STEP_MS = 1000;
|
|
50
|
-
/* A PANE SCROLLED BACK IS IN COPY MODE (`mouse on`: the wheel of any screen puts it there, and it stays
|
|
51
|
-
there when that screen goes away): the keys of a line typed then are copy-mode commands, the line never
|
|
52
|
-
reaches the tool and its Enter only leaves the mode (tried with tmux 3.4). The mode is left first, in
|
|
53
|
-
the same command -- nothing is done to a pane that is not in a mode (no shell: -F reads a format). */
|
|
54
|
-
const LEAVE_MODE = ['if-shell', '-F', '-t', PANE, '#{pane_in_mode}', `send-keys -t ${PANE} -X cancel`, ';'];
|
|
55
|
-
/* The one tmux command that types a line, waits, and presses Enter: an
|
|
56
|
-
argument vector, no shell. tmux reads an argument that ENDS with ";" as the
|
|
57
|
-
end of a command: such a last ";" is written "\;", which tmux gives back
|
|
58
|
-
as ";" (tried). */
|
|
59
|
-
export function typeCommand(line) {
|
|
60
|
-
const text = line.endsWith(';') ? `${line.slice(0, -1)}\\;` : line;
|
|
61
|
-
return ['tmux', '-L', SOCKET, ...LEAVE_MODE, 'send-keys', '-t', PANE, '-l', '--', text, ';', 'run-shell', '-d', String(ENTER_AFTER_MS / 1000), ';', 'send-keys', '-t', PANE, 'Enter'];
|
|
62
|
-
}
|
|
63
|
-
/* Where the line is in typeCommand's argument vector. */
|
|
64
|
-
export const TYPED_AT = 3 + LEAVE_MODE.length + 5;
|
|
65
|
-
/* One key alone (a tmux key name: Enter, Escape, Up, y...), copy mode left first in the same command. */
|
|
66
|
-
export const keyCommand = (key) => ['tmux', '-L', SOCKET, ...LEAVE_MODE, 'send-keys', '-t', PANE, key];
|
|
67
|
-
export const enterCommand = () => keyCommand('Enter');
|
|
68
|
-
/* Escape, alone: what the Esc key of the page's key row sends -- a tool's current turn stopped (an API key that may act, apikeys.mjs). */
|
|
69
|
-
export const escapeCommand = () => keyCommand('Escape');
|
|
70
|
-
|
|
71
|
-
/* THE DOORBELLS, by what rings: its line, who says it in the log, how the log names it. */
|
|
72
|
-
export const DOORBELLS = Object.freeze({
|
|
73
|
-
chat: Object.freeze({ line: CHAT_WAKE, why: 'talk', what: 'wake' }),
|
|
74
|
-
'chat-urgent': Object.freeze({ line: CHAT_URGENT, why: 'talk', what: 'urgent' }),
|
|
75
|
-
docket: Object.freeze({ line: DOCKET_WAKE, why: 'docket', what: 'wake' }),
|
|
76
|
-
});
|
|
77
|
-
|
|
78
|
-
const cut = (line) => (line.length > 60 ? `${line.slice(0, 60)}...` : line);
|
|
79
|
-
|
|
80
|
-
export class TerminalType {
|
|
81
|
-
#vms; #terminal; #warm; #typing; #log; #now; #pause;
|
|
82
|
-
|
|
83
|
-
/* `vms.exec(name, argv, options)`: a command in the machine. `terminal`: the bridge's { open(name),
|
|
84
|
-
type(name, line, ms) } (bridge.mjs), or none. `warm(name)`: opens its terminal. `typing(name)`:
|
|
85
|
-
somebody types there now (TypingWatch). `log(line)`: the server's log. */
|
|
86
|
-
constructor({ vms, terminal = null, warm = async () => {}, typing = () => false, log = (line) => console.log(line), now = () => Date.now(), pause = (ms) => new Promise((ok) => { setTimeout(ok, ms).unref?.(); }) }) {
|
|
87
|
-
this.#vms = vms; this.#terminal = terminal; this.#warm = warm; this.#typing = typing; this.#log = log; this.#now = now; this.#pause = pause;
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/* Whether somebody types in its terminal now. */
|
|
91
|
-
busy(name) { try { return this.#typing(name) === true; } catch { return false; } }
|
|
92
|
-
|
|
93
|
-
async #exec(name, argv) {
|
|
94
|
-
return this.#vms.exec(name, argv, { timeoutMs: 30_000 }).catch((error) => ({ code: -1, stderr: error?.message }));
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
/* Types `line` and Enter. Resolves true when it went. `why`: who types, the log's first word.
|
|
98
|
-
`what`: how the log names it (the line cut short by default; `secret`: never named). `hold`:
|
|
99
|
-
how long it waits for the person typing there before it types anyway; 0: it is then not typed. */
|
|
100
|
-
async typeLine(name, line, { why = 'server', what, secret = false, hold = HOLD_MAX_MS } = {}) {
|
|
101
|
-
const text = String(line);
|
|
102
|
-
const named = secret ? 'not shown' : what ?? cut(text);
|
|
103
|
-
await Promise.resolve(this.#warm(name)).catch(() => {});
|
|
104
|
-
if (hold <= 0 && this.busy(name)) { this.#log(`${why}: ${name}: NOT typed (${named}): somebody types there`); return false; }
|
|
105
|
-
/* Held a while at most: a line left half typed does not keep the server silent. */
|
|
106
|
-
const start = this.#now();
|
|
107
|
-
while (this.busy(name) && this.#now() - start < hold) await this.#pause(HOLD_STEP_MS);
|
|
108
|
-
const held = this.busy(name) ? `, after ${Math.round(hold / 1000)} s with somebody typing there` : '';
|
|
109
|
-
const ran = await this.#exec(name, typeCommand(text));
|
|
110
|
-
if (ran.code === 0) { this.#log(`${why}: ${name}: typed (${named})${held}`); return true; }
|
|
111
|
-
const failed = `exit ${ran.code}${ran.stderr ? `: ${String(ran.stderr).trim().slice(0, 200)}` : ''}`;
|
|
112
|
-
const open = Boolean(this.#terminal?.open(name));
|
|
113
|
-
const down = open ? await Promise.resolve(this.#terminal.type(name, text, ENTER_AFTER_MS)).catch(() => false) : false;
|
|
114
|
-
/* The line went, its Enter did not (the channel closed meanwhile): the Enter alone, never the line twice. */
|
|
115
|
-
const ok = down === true || (down === 'enter' && (await this.#exec(name, enterCommand())).code === 0);
|
|
116
|
-
this.#log(ok ? `${why}: ${name}: typed down its terminal (${named}), the command in the machine failed (${failed})` : `${why}: ${name}: NOT typed (${named}): ${failed}; ${open ? 'its terminal refused too' : 'no terminal open'}`);
|
|
117
|
-
return ok;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
/* The doorbell of `source` (DOORBELLS): typed as any line is. Whether it was heard is the caller's to
|
|
121
|
-
know, from the tool's files, and to ring again. Resolves true when it was typed. */
|
|
122
|
-
async ring(name, source) {
|
|
123
|
-
const bell = DOORBELLS[source];
|
|
124
|
-
if (!bell) throw new RangeError(`No such doorbell: ${source}`);
|
|
125
|
-
return this.typeLine(name, bell.line, { why: bell.why, what: bell.what });
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
/* One key alone (a tmux key name), now: an act asked for, not a line -- it does not wait for the person. */
|
|
129
|
-
async sendKey(name, key, { why = 'server' } = {}) {
|
|
130
|
-
const ran = await this.#exec(name, keyCommand(String(key)));
|
|
131
|
-
if (ran.code === 0) { this.#log(`${why}: ${name}: key ${key}`); return true; }
|
|
132
|
-
this.#log(`${why}: ${name}: key ${key} NOT sent: exit ${ran.code}${ran.stderr ? `: ${String(ran.stderr).trim().slice(0, 200)}` : ''}`);
|
|
133
|
-
return false;
|
|
134
|
-
}
|
|
135
|
-
}
|