clavarium 0.2.227-beta.1 → 0.2.228-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/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/server/answerer.mjs +9 -10
- package/server/dockets.mjs +10 -5
- package/server/main.mjs +22 -15
- package/server/signinhelp.mjs +1 -9
- package/server/talk.mjs +19 -44
- package/server/terminaltype.mjs +135 -0
- package/server/wakeups.mjs +19 -20
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.228-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.228-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,6 +40,7 @@ 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';
|
|
43
44
|
import { isConversationName } from './names.mjs';
|
|
44
45
|
|
|
45
46
|
export const TICK_MS = 8000;
|
|
@@ -179,12 +180,14 @@ const PANE = `=${SESSION}:`;
|
|
|
179
180
|
const fingerprint = (screen) => createHash('sha256').update(screen).digest('hex');
|
|
180
181
|
|
|
181
182
|
export class Answerer {
|
|
182
|
-
#store; #vms; #config; #fetcher; #dir; #conversations; #seen = new Map(); #busy = new Set(); #turn = 0; #now; #onNeeds;
|
|
183
|
+
#store; #vms; #config; #fetcher; #dir; #conversations; #seen = new Map(); #busy = new Set(); #turn = 0; #now; #onNeeds; #typer;
|
|
183
184
|
|
|
184
185
|
/* `conversations`: asked which conversations exist and are awake. */
|
|
185
186
|
/* `onNeeds(name, why)`: it stopped and waits for its owner, who must be told. */
|
|
186
|
-
constructor({ store, vms, config, conversations, dataDir, fetcher = fetch, now = () => new Date(), onNeeds = () => {} }) {
|
|
187
|
+
constructor({ store, vms, config, conversations, dataDir, fetcher = fetch, now = () => new Date(), onNeeds = () => {}, typer = null }) {
|
|
187
188
|
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: () => {} });
|
|
188
191
|
this.#store = store; this.#vms = vms; this.#config = config; this.#conversations = conversations; this.#fetcher = fetcher; this.#now = now;
|
|
189
192
|
this.#dir = `${dataDir}/answerer`;
|
|
190
193
|
mkdirSync(this.#dir, { recursive: true, mode: 0o700 });
|
|
@@ -249,16 +252,12 @@ export class Answerer {
|
|
|
249
252
|
return lines.slice(-SCREEN_LINES).join('\n').slice(-SCREEN_MAX);
|
|
250
253
|
}
|
|
251
254
|
|
|
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. */
|
|
252
257
|
async #type(name, answer) {
|
|
253
|
-
|
|
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
|
-
}
|
|
258
|
+
if (answer.action === 'text') return this.#typer.typeLine(name, answer.text, { why: 'answerer', what: 'its answer', hold: 0 });
|
|
260
259
|
for (const key of answer.keys) {
|
|
261
|
-
if ((await this.#
|
|
260
|
+
if (!(await this.#typer.sendKey(name, KEYS.get(key), { why: 'answerer' }))) return false;
|
|
262
261
|
}
|
|
263
262
|
return true;
|
|
264
263
|
}
|
package/server/dockets.mjs
CHANGED
|
@@ -8,8 +8,9 @@
|
|
|
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),
|
|
12
|
-
*
|
|
11
|
+
* idle (its pulse, Parley's, says it is not in a turn), AGAIN_MS apart, then
|
|
12
|
+
* further apart (AGAIN_STEPS_MS), never given up -- as the chat's own line is
|
|
13
|
+
* (talk.mjs, RENUDGE_MS); told TOLD_MAX times, its chat says it is not handled.
|
|
13
14
|
*
|
|
14
15
|
* THE TOOL'S OWN REMINDERS (docket remind --at/--in/--cron) are turned into
|
|
15
16
|
* events here (tick), and told the same way. Its owner sees them in the
|
|
@@ -49,7 +50,11 @@ export function copyPlans(fromWork, toWork, now = Date.now()) {
|
|
|
49
50
|
export const TICK_MS = 5000;
|
|
50
51
|
/* An event not acknowledged is told again after this long, the tool idle... */
|
|
51
52
|
export const AGAIN_MS = 30 * 60_000;
|
|
52
|
-
/* ...
|
|
53
|
+
/* ...then these long after the last time, the last of them for ever after (17-11: told three times at
|
|
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. */
|
|
53
58
|
export const TOLD_MAX = 3;
|
|
54
59
|
|
|
55
60
|
/* AN ANSWER NEVER SHOWN (15-11, #362): the note of a sign-in a companion did for another conversation is
|
|
@@ -168,12 +173,12 @@ export class Dockets {
|
|
|
168
173
|
const told = Object.fromEntries(Object.entries(record.told ?? {}).filter(([id]) => waiting.some((e) => e.id === id)));
|
|
169
174
|
const due = waiting.filter((e) => {
|
|
170
175
|
const t = told[e.id];
|
|
171
|
-
return !t ||
|
|
176
|
+
return !t || now - t.at >= againAfter(t.count);
|
|
172
177
|
});
|
|
173
178
|
/* Told again only while it is not in a turn: a busy tool reads its docket when its turn ends. */
|
|
174
179
|
const fresh = due.filter((e) => !told[e.id]);
|
|
175
180
|
if (due.length && (fresh.length || this.#idle(name))) {
|
|
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 };
|
|
181
|
+
if (await this.#say(name, WAKE).catch(() => false)) for (const e of due) told[e.id] = { ...told[e.id], count: (told[e.id]?.count ?? 0) + 1, at: now };
|
|
177
182
|
}
|
|
178
183
|
for (const e of waiting) {
|
|
179
184
|
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
|
|
30
|
+
import { SigninHelp } 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,7 +46,9 @@ 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
|
|
49
|
+
import { Talk } from './talk.mjs';
|
|
50
|
+
import { TerminalType } from './terminaltype.mjs';
|
|
51
|
+
import { WAKE as DOCKET_WAKE } from 'clavarium-docket/host';
|
|
50
52
|
import { Toolbox } from './toolbox.mjs';
|
|
51
53
|
import { Guide, commonText } from './guide.mjs';
|
|
52
54
|
import { SignInMailboxes } from './signin.mjs';
|
|
@@ -430,7 +432,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
430
432
|
its machine at a start and when a setting changes. `talk` and
|
|
431
433
|
`wakeups` are made below; only asked once the server runs. */
|
|
432
434
|
const guide = new Guide({ store: new Store(`${dataDir}/guide.json`), vms, conversations: all, resources: folders, secrets, toolbox, tools,
|
|
433
|
-
chat: (name) => Boolean(talk?.brief(name)), say: (name, line) => wakeups.say(name, line), reread: () => talk?.rereadCommand() ?? null });
|
|
435
|
+
chat: (name) => Boolean(talk?.brief(name)), say: (name, line) => wakeups.say(name, line, { why: 'guide' }), reread: () => talk?.rereadCommand() ?? null });
|
|
434
436
|
/* Why Parley is not in a machine, said once in the log, not at each opening. */
|
|
435
437
|
const parleySaid = new Map();
|
|
436
438
|
all.prepare = async (name, woke) => {
|
|
@@ -473,16 +475,23 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
473
475
|
/* Several models answer a tool's simple questions in the owner's place, where the owner asked: see answerer.mjs. */
|
|
474
476
|
/* The owner's devices are told when something waits for them: see alerts.mjs. */
|
|
475
477
|
const alerts = new Alerts({ store: new Store(`${dataDir}/alerts.json`), keyFile: `${dataDir}/alerts-keys.json`, subject: publicOrigin, ...(alertSend ? { send: alertSend } : {}) });
|
|
476
|
-
|
|
478
|
+
/* WHO IS TYPING in a terminal from a screen (wakeups.mjs): nothing of this server is typed over them. */
|
|
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 } : {}),
|
|
477
486
|
onNeeds: (name, why) => { void alerts.tell({ title: `${instance.name()}: ${name} waits for you`, body: why, url: `/?c=${name}` }); } });
|
|
478
487
|
const answerTimer = answerer.start(answerEveryMs);
|
|
479
488
|
/* A tool is told to get to work when something arrives, or by the clock: see wakeups.mjs. */
|
|
480
|
-
let bridge;
|
|
481
489
|
/* A wake-up typed is said in its chat (talk, made below: called only once a wake-up fires). */
|
|
482
490
|
/* Where its chat is on, what wakes a tool is an event it acknowledges: see dockets.mjs. */
|
|
483
491
|
let signinHelp = null;
|
|
484
492
|
const dockets = new Dockets({ store: new Store(`${dataDir}/dockets.json`), resources: folders,
|
|
485
|
-
|
|
493
|
+
/* Its one line, WAKE, is a doorbell: heard once the tool acknowledges (dockets.mjs). */
|
|
494
|
+
say: (name, line) => (line === DOCKET_WAKE ? wakeups.ring(name, 'docket') : wakeups.say(name, line, { why: 'docket' })),
|
|
486
495
|
event: (name, line) => talk.event(name, line),
|
|
487
496
|
alert: (message) => { void alerts.tell({ ...message, title: `${instance.name()}: ${message.title}` }); },
|
|
488
497
|
/* Not in a turn: its pulse ended, or is old (Parley's own measure). */
|
|
@@ -490,11 +499,10 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
490
499
|
awake: () => all.awake(), chatOn: (name) => talk.isOn(name),
|
|
491
500
|
/* A sign-in a companion did for another conversation (signinhelp.mjs, made below): its answer typed there. */
|
|
492
501
|
acked: (name, e) => signinHelp?.acked(name, e) });
|
|
493
|
-
const typingWatch = new TypingWatch();
|
|
494
502
|
/* WHO WOKE IT (16-11): this server opens a terminal for others (a wake-up, a key); said once it wakes one. */
|
|
495
503
|
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'; } };
|
|
496
504
|
all.woken = (name, by, was) => events.add({ kind: 'machine', text: `Machine of ${name}: woken by ${by} (it was ${was})`, conversation: 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),
|
|
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), typer,
|
|
498
506
|
fired: (name, { text }) => talk.event(name, { kind: 'wakeup', text, topic: 'Wake-up' }) });
|
|
499
507
|
const wakeTimer = wakeups.start(wakeEveryMs);
|
|
500
508
|
const docketTimer = dockets.start(wakeEveryMs);
|
|
@@ -546,7 +554,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
546
554
|
for (const conversation of writers) {
|
|
547
555
|
let path = null;
|
|
548
556
|
if (full) { try { path = talk.keepText(conversation, 'git-remote-refused.txt', full); } catch { path = null; } }
|
|
549
|
-
if (await wakeups.say(conversation, path ? `${line.replace(/\.$/, '')}; all it said: ${path}.` : line) === true) heard = true;
|
|
557
|
+
if (await wakeups.say(conversation, path ? `${line.replace(/\.$/, '')}; all it said: ${path}.` : line, { why: 'git keeper' }) === true) heard = true;
|
|
550
558
|
}
|
|
551
559
|
return heard;
|
|
552
560
|
};
|
|
@@ -564,7 +572,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
564
572
|
what is already known of a machine used instead of asking (talk.mjs). */
|
|
565
573
|
/* `settled` (17-11): how long its terminal has been open and quiet -- without it, the line after a restart
|
|
566
574
|
was typed REREAD_AFTER_MS after, into a tool maybe still loading (talk.mjs, READY). */
|
|
567
|
-
terminal: { open: (name) => bridge?.open(name) ?? false,
|
|
575
|
+
typer, terminal: { open: (name) => bridge?.open(name) ?? false, droppedAt: (name) => bridge?.droppedAt(name), settled: (name) => bridge?.settled(name) ?? null },
|
|
568
576
|
health: { of: (name) => health?.of(name) ?? null },
|
|
569
577
|
/* A secret pasted in a message is lifted out before the message is kept:
|
|
570
578
|
it goes to the short-lived vault and the message keeps only a marker
|
|
@@ -609,7 +617,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
609
617
|
conversations: () => all.list(), tools: () => tools, awake: () => all.awake(), chatOn: (name) => talk.isOn(name),
|
|
610
618
|
workFolder: (name) => folders.workFolder(name),
|
|
611
619
|
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 []; } },
|
|
612
|
-
post: (name, event) => dockets.post(name, event), type: (name, text) =>
|
|
620
|
+
post: (name, event) => dockets.post(name, event), type: (name, text) => typer.typeLine(name, text, { why: 'sign-in', secret: true }),
|
|
613
621
|
event: (name, line) => talk.event(name, line) });
|
|
614
622
|
const stopSigninHelp = signinHelp.start();
|
|
615
623
|
all.signinHelp = signinHelp;
|
|
@@ -676,13 +684,13 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
676
684
|
/* Its tool told it may install them again: through its docket where its chat is on, else typed to its agent. */
|
|
677
685
|
const line = toolLine(link);
|
|
678
686
|
try { if (dockets.on(name)) { dockets.post(name, { kind: 'shared-folder', text: line, data: { folder: link.folder, path: link.path } }); return; } } catch { /* typed instead */ }
|
|
679
|
-
if (all.list().find((c) => c.name === name)?.ai === true) void wakeups.say(name, line).catch(() => {});
|
|
687
|
+
if (all.list().find((c) => c.name === name)?.ai === true) void wakeups.say(name, line, { why: 'link guard' }).catch(() => {});
|
|
680
688
|
};
|
|
681
689
|
const health = new Health({ vms, conversations: all, resources: folders, links: linkGuard, seen: new Store(`${dataDir}/health-seen.json`), ...(healthSettleMs === undefined ? {} : { settleMs: healthSettleMs }) });
|
|
682
690
|
const stopHealth = health.start(healthEveryMs);
|
|
683
691
|
/* What is wrong with its machine is said in its chat too, where it happened. */
|
|
684
692
|
/* And what its owner chose that it does on top (healthreact.mjs): its agent told, or a command run. */
|
|
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),
|
|
693
|
+
const reacting = new HealthReact({ store: new Store(`${dataDir}/health-react.json`), say: (name, line) => wakeups.say(name, line, { why: 'health' }), exec: (name, argv, options) => vms.exec(name, argv, options),
|
|
686
694
|
isAgent: (name) => all.list().find((c) => c.name === name)?.ai === true, event: (name, line) => talk.event(name, line) });
|
|
687
695
|
/* Where its chat is on, its agent is given an event when its disk or memory crosses a level (healthdocket.mjs);
|
|
688
696
|
not where its owner turned on its own reaction (above): one way of telling it, not two. */
|
|
@@ -895,8 +903,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
895
903
|
stop: async (name) => {
|
|
896
904
|
const c = all.get(name);
|
|
897
905
|
if (c?.phase !== 'ready' || c.asleep === true) throw new Refusal(409, 'This conversation is asleep: nothing to stop.');
|
|
898
|
-
|
|
899
|
-
if (r.code !== 0) throw new Refusal(502, 'Its turn could not be stopped.');
|
|
906
|
+
if (!(await typer.sendKey(name, 'Escape', { why: 'API key' }))) throw new Refusal(502, 'Its turn could not be stopped.');
|
|
900
907
|
return { state: 'awake' };
|
|
901
908
|
},
|
|
902
909
|
},
|
package/server/signinhelp.mjs
CHANGED
|
@@ -30,8 +30,7 @@
|
|
|
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
|
|
34
|
-
import { SOCKET } from './tmux.mjs';
|
|
33
|
+
import { Refusal } from './conversations.mjs';
|
|
35
34
|
|
|
36
35
|
export const KIND = 'signin-help';
|
|
37
36
|
export const ASK = 'signin-ask.json';
|
|
@@ -58,13 +57,6 @@ export function linkAllowed(link, domains = []) {
|
|
|
58
57
|
}
|
|
59
58
|
const cut = (s, n) => { const t = String(s ?? '').replace(/\s+/g, ' ').trim(); return t.length > n ? `${t.slice(0, n - 1)}…` : t; };
|
|
60
59
|
|
|
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
|
-
|
|
68
60
|
export class SigninHelp {
|
|
69
61
|
#store; #conversations; #tools; #awake; #chatOn; #work; #browsers; #post; #type; #event; #now;
|
|
70
62
|
/* 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
|
|
71
|
-
import {
|
|
70
|
+
import { Refusal } from './conversations.mjs';
|
|
71
|
+
import { TerminalType } from './terminaltype.mjs';
|
|
72
72
|
import { isConversationName } from './names.mjs';
|
|
73
73
|
|
|
74
74
|
export const FOLDER = '.parley';
|
|
@@ -90,18 +90,12 @@ 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}:`;
|
|
94
93
|
/* Nothing is typed in a terminal somebody typed in this recently. */
|
|
95
94
|
export const TYPING_QUIET_MS = 4000;
|
|
96
95
|
/* A line that waits is tried again this often (a machine that does not run is not touched: only its state is asked). */
|
|
97
96
|
export const RETRY_MS = 10_000;
|
|
98
|
-
/*
|
|
99
|
-
|
|
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;
|
|
97
|
+
/* How a line is typed (copy mode left, the line, a pause, Enter: one command): terminaltype.mjs. */
|
|
98
|
+
export { ENTER_AFTER_MS, typeCommand, TYPED_AT, enterCommand, escapeCommand } from './terminaltype.mjs';
|
|
105
99
|
/* WHAT IS KNOWN, NOT ASKED. Asking the VM manager whether the machine runs
|
|
106
100
|
costs half a second for every message (measured on a real server). The
|
|
107
101
|
machine is known to run when its terminal is kept open (it is closed before
|
|
@@ -110,24 +104,6 @@ export const ENTER_AFTER_MS = 200;
|
|
|
110
104
|
cases only if its terminal was not closed since. Anything else is asked. */
|
|
111
105
|
export const TYPED_KNOWN_MS = 60_000;
|
|
112
106
|
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;
|
|
131
107
|
/* Added to Parley's invitation, this server's own sentence: a branch can be
|
|
132
108
|
checked out in one folder only, and /tmp is emptied when the machine
|
|
133
109
|
restarts, with the work left there. Typed in a terminal: no quote, no
|
|
@@ -236,7 +212,7 @@ const PART = /^[A-Za-z0-9._~-]{1,200}$/;
|
|
|
236
212
|
export class Talk {
|
|
237
213
|
#store; #words; #vms; #conversations; #resources; #toolbox; #warm; #alert; #spoke; #inRoom; #listening = new Map(); #every; #now;
|
|
238
214
|
#typedAt = new Map(); #nextTry = new Map(); #trying = new Map(); #ticking = new Map(); #timer; #lastLang = 'en'; #rereadAfter;
|
|
239
|
-
#terminal; #health; #ranAt = new Map(); #kept; #screen; #dropSecret; #log;
|
|
215
|
+
#terminal; #typer; #health; #ranAt = new Map(); #kept; #screen; #dropSecret; #log;
|
|
240
216
|
|
|
241
217
|
/* `alert({ title, body, url })`: told when the tool asks, or waits.
|
|
242
218
|
`words`: a store for the owner's choice of words (one record). */
|
|
@@ -246,8 +222,10 @@ export class Talk {
|
|
|
246
222
|
/* `keptDir`: where each conversation's thread is kept (its own folder),
|
|
247
223
|
in this server's data -- never in the work folder, which its machine
|
|
248
224
|
writes. Without it, the bridge folder is all there is. */
|
|
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) }) {
|
|
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), typer = null }) {
|
|
250
226
|
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 });
|
|
251
229
|
this.#terminal = terminal; this.#health = health; this.#kept = keptDir; this.#screen = screen; this.#dropSecret = dropSecret;
|
|
252
230
|
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;
|
|
253
231
|
for (const s of store.all()) if (s.on === true) this.#listen(s.name);
|
|
@@ -490,22 +468,16 @@ export class Talk {
|
|
|
490
468
|
return this.of(name);
|
|
491
469
|
}
|
|
492
470
|
|
|
493
|
-
/* Types a line and Enter in the tool's terminal
|
|
494
|
-
|
|
495
|
-
bytes down it
|
|
496
|
-
|
|
497
|
-
and each one lost, with why. */
|
|
471
|
+
/* Types a line and Enter in the tool's terminal, as every line of this server is (terminaltype.mjs):
|
|
472
|
+
copy mode left, the line, a pause, Enter, by one command in the machine (17-11: the terminal the
|
|
473
|
+
bridge keeps open cannot leave copy mode -- bytes down it were copy-mode keys while the pane was
|
|
474
|
+
scrolled back, and the line was lost, said typed); that terminal only when the command fails. Each
|
|
475
|
+
line said in the log, and each one lost, with why. */
|
|
476
|
+
/* WAKE and URGENT are the chat's doorbells (ring): heard once its read count moves (RENUDGE_MS). */
|
|
498
477
|
async #type(name, line) {
|
|
499
|
-
const
|
|
500
|
-
await this.#
|
|
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);
|
|
478
|
+
const bell = line === WAKE ? 'chat' : line === URGENT ? 'chat-urgent' : null;
|
|
479
|
+
const ok = bell ? await this.#typer.ring(name, bell) : await this.#typer.typeLine(name, line, { why: 'talk' });
|
|
507
480
|
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'}`);
|
|
509
481
|
return ok;
|
|
510
482
|
}
|
|
511
483
|
|
|
@@ -754,6 +726,7 @@ export class Talk {
|
|
|
754
726
|
if (!this.#conversations.awake().includes(name)) return later(RETRY_MS);
|
|
755
727
|
const quiet = this.#now() - (this.#typedAt.get(name) ?? 0);
|
|
756
728
|
if (quiet < TYPING_QUIET_MS) return later(TYPING_QUIET_MS - quiet + 100);
|
|
729
|
+
if (this.#typer.busy(name)) return later(RETRY_MS);
|
|
757
730
|
if (!(await this.#runs(name))) return later(RETRY_MS);
|
|
758
731
|
if (this.#terminal?.settled) {
|
|
759
732
|
await this.#warm(name);
|
|
@@ -812,6 +785,8 @@ export class Talk {
|
|
|
812
785
|
if (!this.#conversations.awake().includes(name)) return waits('asleep', RETRY_MS);
|
|
813
786
|
const quiet = this.#now() - (this.#typedAt.get(name) ?? 0);
|
|
814
787
|
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);
|
|
815
790
|
if (!(await this.#runs(name))) return waits('asleep', RETRY_MS);
|
|
816
791
|
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})`);
|
|
817
792
|
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);
|
|
@@ -0,0 +1,135 @@
|
|
|
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
|
+
}
|
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
|
|
40
|
-
import {
|
|
39
|
+
import { Refusal } from './conversations.mjs';
|
|
40
|
+
import { TerminalType, HOLD_MAX_MS } from './terminaltype.mjs';
|
|
41
41
|
import { isConversationName } from './names.mjs';
|
|
42
42
|
|
|
43
43
|
export const TICK_MS = 5000;
|
|
@@ -96,9 +96,6 @@ 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;
|
|
102
99
|
|
|
103
100
|
/* WHO IS TYPING IN A TERMINAL, from what screens send (bridge.mjs onTyped).
|
|
104
101
|
Busy: a key in the last seconds, or a line begun and not yet sent
|
|
@@ -150,22 +147,23 @@ const FIRED_SHOWN = 120;
|
|
|
150
147
|
const sameDay = (a, b) => a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
|
|
151
148
|
|
|
152
149
|
export class Wakeups {
|
|
153
|
-
#store; #vms; #conversations; #resources; #warm; #now; #fired; #docket; #typing; #
|
|
150
|
+
#store; #vms; #conversations; #resources; #warm; #now; #fired; #docket; #typing; #typer; #held = new Map(); #busy = false;
|
|
154
151
|
|
|
155
152
|
/* `warm(name)`: opens the terminal of a machine that runs, if it is not open.
|
|
156
153
|
`fired(name, { text, item })`: a wake-up was typed (its chat says so: Talk.event). */
|
|
157
154
|
/* `docket`: { on(name), post(name, {kind, text, data}) } (dockets.mjs), or none: typed always. */
|
|
158
155
|
/* `typing(name)`: someone is typing in its terminal from a screen (see TypingWatch): a line is held until it is free. */
|
|
159
|
-
constructor({ store, vms, conversations, resources, warm = async () => {}, now = () => new Date(), fired = () => {}, docket = null, typing = () => false, pause = (ms) => new Promise((ok) => setTimeout(ok, ms)) }) {
|
|
156
|
+
constructor({ store, vms, conversations, resources, warm = async () => {}, now = () => new Date(), fired = () => {}, docket = null, typing = () => false, pause = (ms) => new Promise((ok) => setTimeout(ok, ms)), typer = null }) {
|
|
160
157
|
this.#store = store; this.#vms = vms; this.#conversations = conversations; this.#resources = resources; this.#warm = warm; this.#now = now; this.#fired = fired; this.#docket = docket;
|
|
161
|
-
this.#typing = typing;
|
|
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: () => {} });
|
|
162
161
|
}
|
|
163
162
|
/* 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. */
|
|
164
163
|
async #deliver(name, item, text) {
|
|
165
164
|
if (this.#docket?.on(name)) {
|
|
166
165
|
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 */ }
|
|
167
166
|
}
|
|
168
|
-
await this.#free(name);
|
|
169
167
|
const typed = await this.#type(name, text).catch(() => false);
|
|
170
168
|
return { ok: typed, what: typed ? `Typed: ${text}` : 'Could not be typed: is its tool running?' };
|
|
171
169
|
}
|
|
@@ -321,16 +319,10 @@ export class Wakeups {
|
|
|
321
319
|
return withFiles(item.message, arrived);
|
|
322
320
|
}
|
|
323
321
|
|
|
324
|
-
/*
|
|
325
|
-
async #
|
|
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) {
|
|
322
|
+
/* Its terminal opened first (who woke it is said), then typed as every line of this server is (terminaltype.mjs). */
|
|
323
|
+
async #type(name, text, why = 'wake-up') {
|
|
330
324
|
await this.#warm(name);
|
|
331
|
-
|
|
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;
|
|
325
|
+
return this.#typer.typeLine(name, text, { why });
|
|
334
326
|
}
|
|
335
327
|
|
|
336
328
|
/* A line from this server itself (a repository that could not be read,
|
|
@@ -340,10 +332,17 @@ export class Wakeups {
|
|
|
340
332
|
/* One line at a time into a terminal: two said at once were typed into each other, then sent
|
|
341
333
|
as one (two repositories moving together, seen 20-10). */
|
|
342
334
|
#queue = new Map();
|
|
343
|
-
async say(name, text) {
|
|
335
|
+
async say(name, text, { why = 'server line' } = {}) {
|
|
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) {
|
|
344
343
|
if (!this.#conversations.awake().includes(name)) return false;
|
|
345
344
|
const before = this.#queue.get(name) ?? Promise.resolve();
|
|
346
|
-
const mine = before.then(
|
|
345
|
+
const mine = before.then(type).catch(() => false);
|
|
347
346
|
this.#queue.set(name, mine);
|
|
348
347
|
void mine.finally(() => { if (this.#queue.get(name) === mine) this.#queue.delete(name); });
|
|
349
348
|
return mine;
|