clavarium 0.2.483-next.1 → 0.2.485-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.483-next.1",
3
+ "version": "0.2.485-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.483-next.1",
9
+ "version": "0.2.485-next.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.483-next.1",
3
+ "version": "0.2.485-next.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "A conversation is a VM with a terminal in it. Everything else is a folder.",
@@ -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
- 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
- }
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.#vms.exec(name, [...tmux, 'send-keys', ...to, KEYS.get(key)], { timeoutMs: 30_000 })).code !== 0) return false;
260
+ if (!(await this.#typer.sendKey(name, KEYS.get(key), { why: 'answerer' }))) return false;
262
261
  }
263
262
  return true;
264
263
  }
@@ -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), every AGAIN_MS, at
12
- * most TOLD_MAX times; then its chat says it was not handled.
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
- /* ...this many times at most (the first included); then its chat says so. */
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 || (t.count < TOLD_MAX && now - t.at >= AGAIN_MS);
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, typeInto } from './signinhelp.mjs';
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, escapeCommand } from './talk.mjs';
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
- const answerer = new Answerer({ store: new Store(`${dataDir}/answerer.json`), vms, config: answererConfig(env), conversations: all, dataDir, ...(answerFetcher ? { fetcher: answerFetcher } : {}),
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
- say: (name, line) => wakeups.say(name, line),
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
  };
@@ -562,7 +570,9 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
562
570
  ...(rereadAfterMs === undefined ? {} : { rereadAfterMs }),
563
571
  /* A line typed down the terminal already open when there is one, and
564
572
  what is already known of a machine used instead of asking (talk.mjs). */
565
- terminal: { open: (name) => bridge?.open(name) ?? false, type: (name, line, ms) => bridge?.type(name, line, ms) ?? false, droppedAt: (name) => bridge?.droppedAt(name) },
573
+ /* `settled` (17-11): how long its terminal has been open and quiet -- without it, the line after a restart
574
+ was typed REREAD_AFTER_MS after, into a tool maybe still loading (talk.mjs, READY). */
575
+ typer, terminal: { open: (name) => bridge?.open(name) ?? false, droppedAt: (name) => bridge?.droppedAt(name), settled: (name) => bridge?.settled(name) ?? null },
566
576
  health: { of: (name) => health?.of(name) ?? null },
567
577
  /* A secret pasted in a message is lifted out before the message is kept:
568
578
  it goes to the short-lived vault and the message keeps only a marker
@@ -607,7 +617,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
607
617
  conversations: () => all.list(), tools: () => tools, awake: () => all.awake(), chatOn: (name) => talk.isOn(name),
608
618
  workFolder: (name) => folders.workFolder(name),
609
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 []; } },
610
- post: (name, event) => dockets.post(name, event), type: (name, text) => typeInto(vms, name, text),
620
+ post: (name, event) => dockets.post(name, event), type: (name, text) => typer.typeLine(name, text, { why: 'sign-in', secret: true }),
611
621
  event: (name, line) => talk.event(name, line) });
612
622
  const stopSigninHelp = signinHelp.start();
613
623
  all.signinHelp = signinHelp;
@@ -674,13 +684,13 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
674
684
  /* Its tool told it may install them again: through its docket where its chat is on, else typed to its agent. */
675
685
  const line = toolLine(link);
676
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 */ }
677
- 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(() => {});
678
688
  };
679
689
  const health = new Health({ vms, conversations: all, resources: folders, links: linkGuard, seen: new Store(`${dataDir}/health-seen.json`), ...(healthSettleMs === undefined ? {} : { settleMs: healthSettleMs }) });
680
690
  const stopHealth = health.start(healthEveryMs);
681
691
  /* What is wrong with its machine is said in its chat too, where it happened. */
682
692
  /* And what its owner chose that it does on top (healthreact.mjs): its agent told, or a command run. */
683
- 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),
684
694
  isAgent: (name) => all.list().find((c) => c.name === name)?.ai === true, event: (name, line) => talk.event(name, line) });
685
695
  /* Where its chat is on, its agent is given an event when its disk or memory crosses a level (healthdocket.mjs);
686
696
  not where its owner turned on its own reaction (above): one way of telling it, not two. */
@@ -893,8 +903,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
893
903
  stop: async (name) => {
894
904
  const c = all.get(name);
895
905
  if (c?.phase !== 'ready' || c.asleep === true) throw new Refusal(409, 'This conversation is asleep: nothing to stop.');
896
- const r = await vms.exec(name, escapeCommand(), { timeoutMs: 30_000 });
897
- 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.');
898
907
  return { state: 'awake' };
899
908
  },
900
909
  },
@@ -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, SESSION } from './conversations.mjs';
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
@@ -17,7 +17,8 @@
17
17
  * until the tool has read, never while somebody
18
18
  * types there, never into a machine that does not
19
19
  * run (the message waits, and the line is typed
20
- * when it runs again).
20
+ * when it runs again); still unread a while
21
+ * after, typed again by itself (RENUDGE_MS).
21
22
  * agent-asked, waiting the owner's devices are alerted.
22
23
  * agent-showed a file under /work or in an attached folder is
23
24
  * opened from the page; any other is said to be
@@ -66,8 +67,8 @@ import { featureWords } from './features.mjs';
66
67
  import { settingsWords } from './settingswords.mjs';
67
68
  import { importFile } from './files.mjs';
68
69
  import { KEYS } from 'clavarium-parley/ui';
69
- import { Refusal, SESSION } from './conversations.mjs';
70
- import { SOCKET } from './tmux.mjs';
70
+ import { Refusal } from './conversations.mjs';
71
+ import { TerminalType } from './terminaltype.mjs';
71
72
  import { isConversationName } from './names.mjs';
72
73
 
73
74
  export const FOLDER = '.parley';
@@ -89,18 +90,12 @@ export function partOf(query) {
89
90
  for (const k of ['before', 'from', 'since']) { const v = get(k); if (typeof v === 'string' && PART.test(v)) out[k] = v; }
90
91
  return Object.keys(out).length ? out : null;
91
92
  }
92
- const PANE = `=${SESSION}:`;
93
93
  /* Nothing is typed in a terminal somebody typed in this recently. */
94
94
  export const TYPING_QUIET_MS = 4000;
95
95
  /* A line that waits is tried again this often (a machine that does not run is not touched: only its state is asked). */
96
96
  export const RETRY_MS = 10_000;
97
- /* THE LINE AND ITS ENTER ARE TYPED APART, this long apart. Arriving in one
98
- read, "text" and Enter look like a paste to a tool that guesses pastes from
99
- how fast the keys come (measured in tmux: send-keys of both in one command
100
- gives the program one read, "text\r"): the Enter is then a new line in its
101
- input, not a send. Waited inside the same tmux command (run-shell -d) or
102
- by the terminal bridge: no second call into the machine. */
103
- 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';
104
99
  /* WHAT IS KNOWN, NOT ASKED. Asking the VM manager whether the machine runs
105
100
  costs half a second for every message (measured on a real server). The
106
101
  machine is known to run when its terminal is kept open (it is closed before
@@ -109,22 +104,16 @@ export const ENTER_AFTER_MS = 200;
109
104
  cases only if its terminal was not closed since. Anything else is asked. */
110
105
  export const TYPED_KNOWN_MS = 60_000;
111
106
  export const HEALTH_KNOWN_MS = 150_000;
112
- /* The one tmux command that types a line, waits, and presses Enter: an
113
- argument vector, no shell. tmux reads an argument that ENDS with ";" as the
114
- end of a command: such a last ";" is written "\;", which tmux gives back
115
- as ";" (tried). */
116
- export const enterCommand = () => ['tmux', '-L', SOCKET, 'send-keys', '-t', PANE, 'Enter'];
117
- /* 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). */
118
- export const escapeCommand = () => ['tmux', '-L', SOCKET, 'send-keys', '-t', PANE, 'Escape'];
119
- export function typeCommand(line) {
120
- const text = line.endsWith(';') ? `${line.slice(0, -1)}\\;` : line;
121
- return ['tmux', '-L', SOCKET, 'send-keys', '-t', PANE, '-l', '--', text, ';', 'run-shell', '-d', String(ENTER_AFTER_MS / 1000), ';', 'send-keys', '-t', PANE, 'Enter'];
122
- }
123
107
  /* Added to Parley's invitation, this server's own sentence: a branch can be
124
108
  checked out in one folder only, and /tmp is emptied when the machine
125
109
  restarts, with the work left there. Typed in a terminal: no quote, no
126
110
  backquote, nothing a shell would run. */
127
111
  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
+ /* THE LINE TYPED AGAIN BY ITSELF (17-11): one line lost (a pane in copy mode, a tool drawing a modal)
113
+ 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, then every last one of them -- till the
115
+ tool reads (its read count moves). Kept in its record: a restart of this server goes on. */
116
+ export const RENUDGE_MS = Object.freeze([60_000, 180_000, 600_000]);
128
117
  /* After a restart, the tool is given this long to start before REREAD is typed. */
129
118
  export const REREAD_AFTER_MS = 10_000;
130
119
  /* READY, NOT JUST STARTED. The tool starts when its terminal is opened, which
@@ -222,8 +211,8 @@ export const windowOf = (choice) => { const [kind, n] = String(choice).split(':'
222
211
  const PART = /^[A-Za-z0-9._~-]{1,200}$/;
223
212
  export class Talk {
224
213
  #store; #words; #vms; #conversations; #resources; #toolbox; #warm; #alert; #spoke; #inRoom; #listening = new Map(); #every; #now;
225
- #typedAt = new Map(); #nextTry = new Map(); #trying = new Map(); #timer; #lastLang = 'en'; #rereadAfter;
226
- #terminal; #health; #ranAt = new Map(); #kept; #screen; #dropSecret;
214
+ #typedAt = new Map(); #nextTry = new Map(); #trying = new Map(); #ticking = new Map(); #timer; #lastLang = 'en'; #rereadAfter;
215
+ #terminal; #typer; #health; #ranAt = new Map(); #kept; #screen; #dropSecret; #log;
227
216
 
228
217
  /* `alert({ title, body, url })`: told when the tool asks, or waits.
229
218
  `words`: a store for the owner's choice of words (one record). */
@@ -233,7 +222,10 @@ export class Talk {
233
222
  /* `keptDir`: where each conversation's thread is kept (its own folder),
234
223
  in this server's data -- never in the work folder, which its machine
235
224
  writes. Without it, the bridge folder is all there is. */
236
- 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 }) {
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 }) {
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 });
237
229
  this.#terminal = terminal; this.#health = health; this.#kept = keptDir; this.#screen = screen; this.#dropSecret = dropSecret;
238
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;
239
231
  for (const s of store.all()) if (s.on === true) this.#listen(s.name);
@@ -476,16 +468,15 @@ export class Talk {
476
468
  return this.of(name);
477
469
  }
478
470
 
479
- /* Types a line and Enter in the tool's terminal. Through the terminal the
480
- bridge keeps open into the same tmux pane when there is one (nothing
481
- sent into the machine: the bytes go down a channel already open), or
482
- else one command in the machine. */
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). */
483
477
  async #type(name, line) {
484
- await this.#warm(name);
485
- const down = this.#terminal?.open(name) ? await Promise.resolve(this.#terminal.type(name, line, ENTER_AFTER_MS)).catch(() => false) : false;
486
- if (down === true) { this.#ranAt.set(name, this.#now()); return true; }
487
- /* The line went, its Enter did not (the channel closed meanwhile): the Enter alone, never the line twice. */
488
- const ok = (await this.#vms.exec(name, down === 'enter' ? enterCommand() : typeCommand(line), { timeoutMs: 30_000 })).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' });
489
480
  if (ok) this.#ranAt.set(name, this.#now());
490
481
  return ok;
491
482
  }
@@ -735,6 +726,7 @@ export class Talk {
735
726
  if (!this.#conversations.awake().includes(name)) return later(RETRY_MS);
736
727
  const quiet = this.#now() - (this.#typedAt.get(name) ?? 0);
737
728
  if (quiet < TYPING_QUIET_MS) return later(TYPING_QUIET_MS - quiet + 100);
729
+ if (this.#typer.busy(name)) return later(RETRY_MS);
738
730
  if (!(await this.#runs(name))) return later(RETRY_MS);
739
731
  if (this.#terminal?.settled) {
740
732
  await this.#warm(name);
@@ -749,10 +741,10 @@ export class Talk {
749
741
  this.#store.put({ ...this.#store.get(name), reread: false, renewedText: undefined });
750
742
  return 'told';
751
743
  }
752
- if (!(await this.#type(name, this.rereadLine()).catch(() => false))) return later(RETRY_MS);
744
+ if (!(await this.#type(name, this.rereadLine()).catch((error) => { this.#log(`talk: ${name}: NOT typed: ${error?.message}`); return false; }))) return later(RETRY_MS);
753
745
  /* Reading the whole thread, it reads what waits too: that line is not typed after it. */
754
746
  const waits = this.#parley(name).unread() > 0;
755
- this.#store.put({ ...this.#store.get(name), reread: false, ...(waits ? { pending: false, woke: true, why: null, again: false } : {}), typedAt: new Date(this.#now()).toISOString() });
747
+ this.#store.put({ ...this.#store.get(name), reread: false, ...(waits ? { pending: false, woke: true, why: null, again: false, toldRead: this.#readCount(name), renudged: 0 } : {}), typedAt: new Date(this.#now()).toISOString() });
756
748
  return 'typed';
757
749
  }
758
750
 
@@ -760,6 +752,12 @@ export class Talk {
760
752
  /* Somebody typed in its terminal: nothing is typed over them. */
761
753
  typed(name) { this.#typedAt.set(name, this.#now()); }
762
754
 
755
+ /* How far the tool has read (Parley's read.json: messages read, archived ones counted). Grows only. */
756
+ #readCount(name) { try { return Math.max(0, Number(JSON.parse(readFileSync(`${this.#dir(name)}/read.json`, 'utf8')).lines) || 0); } catch { return 0; } }
757
+ /* TOLD, THEN READ, THEN WRITTEN TO AGAIN before `woke` was put back (the tick's, every second -- or
758
+ never, while a tick waited on another conversation): the line typed was used, the next is owed. */
759
+ #readSince(name, r) { return Number.isInteger(r?.toldRead) && this.#readCount(name) > r.toldRead; }
760
+
763
761
  #want(name) {
764
762
  const r = this.#store.get(name);
765
763
  if (r?.on === true && r.woke !== true) this.#store.put({ ...r, pending: true });
@@ -769,27 +767,30 @@ export class Talk {
769
767
  'typed', 'read' (nothing waits), 'told' (typed already, not read yet),
770
768
  'asleep', 'typing', 'failed' -- the last three wait, and are tried
771
769
  again. `again`: the owner asked to remind it, typed before or not. */
772
- #wake(name, again = false, urgent = false) {
770
+ #wake(name, again = false, urgent = false, renudge = false) {
773
771
  const going = this.#trying.get(name);
774
772
  if (going) return going;
775
- const run = this.#tryWake(name, again, urgent).finally(() => this.#trying.delete(name));
773
+ const run = this.#tryWake(name, again, urgent, renudge).finally(() => this.#trying.delete(name));
776
774
  this.#trying.set(name, run);
777
775
  return run;
778
776
  }
779
- async #tryWake(name, again, urgent = false) {
777
+ async #tryWake(name, again, urgent = false, renudge = false) {
780
778
  const r = this.#store.get(name);
781
779
  if (r?.on !== true) return 'read';
782
- const waits = (why, ms) => { this.#store.put({ ...this.#store.get(name), pending: true, why, again }); this.#nextTry.set(name, this.#now() + ms); return why; };
783
- if (this.#parley(name).unread() === 0) { if (r.pending || r.woke) this.#store.put({ ...r, pending: false, woke: false, why: null, again: false }); return 'read'; }
780
+ const waits = (why, ms) => { this.#store.put({ ...this.#store.get(name), pending: true, why, again, renudge }); this.#nextTry.set(name, this.#now() + ms); return why; };
781
+ if (this.#parley(name).unread() === 0) { if (r.pending || r.woke) this.#store.put({ ...r, pending: false, woke: false, why: null, again: false, renudge: false }); return 'read'; }
784
782
  /* Its machine has just restarted: the line that will be typed tells it to read everything. */
785
783
  if (r.reread === true) { this.#store.put({ ...r, pending: true, why: 'restarting', again }); return 'restarting'; }
786
- if (r.woke === true && !again) { if (r.pending) this.#store.put({ ...r, pending: false, why: null }); return 'told'; }
784
+ if (r.woke === true && !again && !this.#readSince(name, r)) { if (r.pending) this.#store.put({ ...r, pending: false, why: null }); return 'told'; }
787
785
  if (!this.#conversations.awake().includes(name)) return waits('asleep', RETRY_MS);
788
786
  const quiet = this.#now() - (this.#typedAt.get(name) ?? 0);
789
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);
790
790
  if (!(await this.#runs(name))) return waits('asleep', RETRY_MS);
791
- if (!(await this.#type(name, urgent ? URGENT : WAKE).catch(() => false))) return waits('failed', RETRY_MS);
792
- this.#store.put({ ...this.#store.get(name), pending: false, woke: true, why: null, again: false, typedAt: new Date(this.#now()).toISOString() });
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})`);
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);
793
+ this.#store.put({ ...this.#store.get(name), pending: false, woke: true, why: null, again: false, renudge: false, typedAt: new Date(this.#now()).toISOString(), toldRead: this.#readCount(name), renudged: renudge ? (r.renudged ?? 0) + 1 : 0 });
793
794
  return 'typed';
794
795
  }
795
796
 
@@ -801,16 +802,36 @@ export class Talk {
801
802
  return { ...this.of(name), told };
802
803
  }
803
804
 
804
- async #tick() {
805
+ /* NO CONVERSATION WAITS ON ANOTHER: each one's work is started, never awaited in turn -- a machine
806
+ that does not answer (its terminal opening, its state asked) held every conversation after it in
807
+ the store, ticks piling up behind, and their `woke` never put back: their next line was never
808
+ typed. One run at a time for each (#wake's own, and this one's for the rest). */
809
+ #tick() {
805
810
  for (const r of this.#store.all()) {
806
- if (r.on === true) this.#reapForgets(r);
807
- if (r.on === true && r.reread === true) { await this.#tryReread(r.name).catch(() => {}); continue; }
808
- if (r.on !== true || (!r.pending && !r.woke)) continue;
811
+ if (this.#ticking.has(r.name)) continue;
812
+ const run = this.#tickOne(r).catch(() => {}).finally(() => this.#ticking.delete(r.name));
813
+ this.#ticking.set(r.name, run);
814
+ }
815
+ }
816
+ async #tickOne(r) {
817
+ if (r.on === true) this.#reapForgets(r);
818
+ if (r.on === true && r.reread === true) { await this.#tryReread(r.name); return; }
819
+ if (r.on !== true || (!r.pending && !r.woke)) return;
820
+ if (r.woke && !r.pending) {
821
+ let unread;
822
+ try { unread = this.#parley(r.name).unread(); } catch { return; /* its folder went */ }
809
823
  /* It has read: what waited is done, and the next message wakes it again. */
810
- if (r.woke && !r.pending) { try { if (this.#parley(r.name).unread() === 0) this.#store.put({ ...r, woke: false }); } catch { /* its folder went */ } continue; }
811
- if (this.#now() < (this.#nextTry.get(r.name) ?? 0)) continue;
812
- await this.#wake(r.name, r.again === true).catch(() => {});
824
+ if (unread === 0) { this.#store.put({ ...r, woke: false }); return; }
825
+ /* It read since, and more was written: the line is owed now. */
826
+ if (this.#readSince(r.name, r)) { await this.#wake(r.name); return; }
827
+ /* Still unread long after: typed again, RENUDGE_MS apart, the last of them for ever after. */
828
+ const after = RENUDGE_MS[Math.min(r.renudged ?? 0, RENUDGE_MS.length - 1)];
829
+ const at = Date.parse(r.typedAt ?? '');
830
+ 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
+ return;
813
832
  }
833
+ if (this.#now() < (this.#nextTry.get(r.name) ?? 0)) return;
834
+ await this.#wake(r.name, r.again === true, false, r.renudge === true);
814
835
  }
815
836
 
816
837
  /* The agent asked to forget short-lived secrets (parley forget -> forget.jsonl beside its thread): the
@@ -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
+ }
@@ -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, SESSION } from './conversations.mjs';
40
- import { SOCKET } from './tmux.mjs';
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; #pause; #held = new Map(); #busy = false;
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; this.#pause = pause;
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
- /* 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) {
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
- 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;
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(() => this.#free(name)).then(() => this.#type(name, cleanMessage(text)).catch(() => false));
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;