clavarium 0.2.156-next.1 → 0.2.159-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,20 +1,20 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.156-next.1",
3
+ "version": "0.2.159-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.156-next.1",
9
+ "version": "0.2.159-next.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
13
13
  "@xterm/xterm": "^6.0.0",
14
14
  "clavarium-binder": "0.1.43-next.1",
15
15
  "clavarium-docket": "0.1.1",
16
- "clavarium-parley": "0.17.30-next.1",
17
- "clavarium-tether": "0.1.0-next.34",
16
+ "clavarium-parley": "0.17.31-next.1",
17
+ "clavarium-tether": "0.1.0-next.38",
18
18
  "mermaid": "11.17.2",
19
19
  "node-pty": "^1.1.0",
20
20
  "pdfjs-dist": "6.4.299",
@@ -28,6 +28,9 @@
28
28
  },
29
29
  "engines": {
30
30
  "node": ">=22"
31
+ },
32
+ "optionalDependencies": {
33
+ "sherpa-onnx-node": "1.12.40"
31
34
  }
32
35
  },
33
36
  "node_modules/@antfu/install-pkg": {
@@ -660,6 +663,7 @@
660
663
  "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz",
661
664
  "integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==",
662
665
  "license": "MIT",
666
+ "optional": true,
663
667
  "dependencies": {
664
668
  "safer-buffer": "~2.1.0"
665
669
  }
@@ -681,6 +685,7 @@
681
685
  "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz",
682
686
  "integrity": "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==",
683
687
  "license": "BSD-3-Clause",
688
+ "optional": true,
684
689
  "dependencies": {
685
690
  "tweetnacl": "^0.14.3"
686
691
  }
@@ -742,9 +747,9 @@
742
747
  }
743
748
  },
744
749
  "node_modules/clavarium-parley": {
745
- "version": "0.17.30-next.1",
746
- "resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.30-next.1.tgz",
747
- "integrity": "sha512-lJHL3Jbrh4D1wgb+JMfnlUzTLVaLE6JEHQq3uXJHVYnK/uJGdL7kYyUYHknIyvpCkavDCxm2/PRr3/t3rfWFPQ==",
750
+ "version": "0.17.31-next.1",
751
+ "resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.31-next.1.tgz",
752
+ "integrity": "sha512-UN3s3ciAXkWcEKWjoilsM7dI61vvoh7SuonvbA9KJ13cl6VUATmOmmY/o0r/i2/P0y3/avNvCLholFSumrPg0A==",
748
753
  "license": "MIT",
749
754
  "bin": {
750
755
  "parley": "bin/parley.mjs",
@@ -755,9 +760,9 @@
755
760
  }
756
761
  },
757
762
  "node_modules/clavarium-tether": {
758
- "version": "0.1.0-next.34",
759
- "resolved": "https://registry.npmjs.org/clavarium-tether/-/clavarium-tether-0.1.0-next.34.tgz",
760
- "integrity": "sha512-6AOHSkdeHE+K5W9NK3q282Hwx9QcETaxNAJb6rDyrEa8ddAHKjKkokJDsAYB/xjRI8Z0txl8GpQb0f4sfFC43Q==",
763
+ "version": "0.1.0-next.38",
764
+ "resolved": "https://registry.npmjs.org/clavarium-tether/-/clavarium-tether-0.1.0-next.38.tgz",
765
+ "integrity": "sha512-hIbCNROr+CmYpYAviKffHT3L51wucGJn5tHZLZ4K7NGM1uCwS6Oaq3dauF/eFtsD0QIyaRO9+2+G0HIA1q4HjA==",
761
766
  "license": "MIT",
762
767
  "bin": {
763
768
  "tether": "bin/cli.mjs",
@@ -1870,11 +1875,105 @@
1870
1875
  "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==",
1871
1876
  "license": "ISC"
1872
1877
  },
1878
+ "node_modules/sherpa-onnx-darwin-arm64": {
1879
+ "version": "1.13.8",
1880
+ "resolved": "https://registry.npmjs.org/sherpa-onnx-darwin-arm64/-/sherpa-onnx-darwin-arm64-1.13.8.tgz",
1881
+ "integrity": "sha512-FPNgJMgnWVl/KhRTIhG3KL3A4Om63Rn4YKXc9/uHY7SzLcvqLJLc/h7UBWJwduXvv7K18t5NpxHR6XgXn4sjWw==",
1882
+ "cpu": [
1883
+ "arm64"
1884
+ ],
1885
+ "license": "Apache-2.0",
1886
+ "optional": true,
1887
+ "os": [
1888
+ "darwin"
1889
+ ]
1890
+ },
1891
+ "node_modules/sherpa-onnx-darwin-x64": {
1892
+ "version": "1.13.8",
1893
+ "resolved": "https://registry.npmjs.org/sherpa-onnx-darwin-x64/-/sherpa-onnx-darwin-x64-1.13.8.tgz",
1894
+ "integrity": "sha512-7BLRpjM6w4f9W46/nmkmq8lEKUayhebvcpslCVQ+6QN2uReYlZEMDZlSpXMjme+hUFrPfRz8P3UNq8ep/4d19g==",
1895
+ "cpu": [
1896
+ "x64"
1897
+ ],
1898
+ "license": "Apache-2.0",
1899
+ "optional": true,
1900
+ "os": [
1901
+ "darwin"
1902
+ ]
1903
+ },
1904
+ "node_modules/sherpa-onnx-linux-arm64": {
1905
+ "version": "1.13.8",
1906
+ "resolved": "https://registry.npmjs.org/sherpa-onnx-linux-arm64/-/sherpa-onnx-linux-arm64-1.13.8.tgz",
1907
+ "integrity": "sha512-Tlg7a70b/Wge3OF8IgTHF9jhSVCsLyKQKhwc4BsJ5A+dL/SrFtGBjzuHp4XeLhiiOT7afCxX5PdSn/D4c8Lnuw==",
1908
+ "cpu": [
1909
+ "arm64"
1910
+ ],
1911
+ "license": "Apache-2.0",
1912
+ "optional": true,
1913
+ "os": [
1914
+ "linux"
1915
+ ]
1916
+ },
1917
+ "node_modules/sherpa-onnx-linux-x64": {
1918
+ "version": "1.13.8",
1919
+ "resolved": "https://registry.npmjs.org/sherpa-onnx-linux-x64/-/sherpa-onnx-linux-x64-1.13.8.tgz",
1920
+ "integrity": "sha512-6plnhjagsSeTntCgnlag86hWbs/uZE9Crms1LgOb68/1nKsIQjMd+WG519m+aPwT6TrsBOiEMzrx41t8sL5L5g==",
1921
+ "cpu": [
1922
+ "x64"
1923
+ ],
1924
+ "license": "Apache-2.0",
1925
+ "optional": true,
1926
+ "os": [
1927
+ "linux"
1928
+ ]
1929
+ },
1930
+ "node_modules/sherpa-onnx-node": {
1931
+ "version": "1.12.40",
1932
+ "resolved": "https://registry.npmjs.org/sherpa-onnx-node/-/sherpa-onnx-node-1.12.40.tgz",
1933
+ "integrity": "sha512-xazIjdHXG3T9DdojS2QjTu9yWyLcnXxgRQBNIocvu73l9N8AoS9zse3zaSU0VbQWlyn+lXdcqKUGEicYhbGMpg==",
1934
+ "license": "Apache-2.0",
1935
+ "optional": true,
1936
+ "optionalDependencies": {
1937
+ "sherpa-onnx-darwin-arm64": "^1.12.40",
1938
+ "sherpa-onnx-darwin-x64": "^1.12.40",
1939
+ "sherpa-onnx-linux-arm64": "^1.12.40",
1940
+ "sherpa-onnx-linux-x64": "^1.12.40",
1941
+ "sherpa-onnx-win-ia32": "^1.12.40",
1942
+ "sherpa-onnx-win-x64": "^1.12.40"
1943
+ }
1944
+ },
1945
+ "node_modules/sherpa-onnx-win-ia32": {
1946
+ "version": "1.13.8",
1947
+ "resolved": "https://registry.npmjs.org/sherpa-onnx-win-ia32/-/sherpa-onnx-win-ia32-1.13.8.tgz",
1948
+ "integrity": "sha512-H0Ojln9hfvM+pxWqW0cnjB/XK8/JPq4/k0IWu2JpY5Z458M3zv+XC3Hu+wmot3AoH/K1Bgt23n/tTKtPV9x8qg==",
1949
+ "cpu": [
1950
+ "ia32"
1951
+ ],
1952
+ "license": "Apache-2.0",
1953
+ "optional": true,
1954
+ "os": [
1955
+ "win32"
1956
+ ]
1957
+ },
1958
+ "node_modules/sherpa-onnx-win-x64": {
1959
+ "version": "1.13.8",
1960
+ "resolved": "https://registry.npmjs.org/sherpa-onnx-win-x64/-/sherpa-onnx-win-x64-1.13.8.tgz",
1961
+ "integrity": "sha512-oZF1c9VPOKtMwn83Bboc5XSWL+76BRoyB3eUuVnCknBKxwSULZU2Foia9VHWzU+n4I12rPsP6z6H9Rp1hD9o8g==",
1962
+ "cpu": [
1963
+ "x64"
1964
+ ],
1965
+ "license": "Apache-2.0",
1966
+ "optional": true,
1967
+ "os": [
1968
+ "win32"
1969
+ ]
1970
+ },
1873
1971
  "node_modules/ssh2": {
1874
1972
  "version": "1.17.0",
1875
1973
  "resolved": "https://registry.npmjs.org/ssh2/-/ssh2-1.17.0.tgz",
1876
1974
  "integrity": "sha512-wPldCk3asibAjQ/kziWQQt1Wh3PgDFpC0XpwclzKcdT1vql6KeYxf5LIt4nlFkUeR8WuphYMKqUA56X4rjbfgQ==",
1877
1975
  "hasInstallScript": true,
1976
+ "optional": true,
1878
1977
  "dependencies": {
1879
1978
  "asn1": "^0.2.6",
1880
1979
  "bcrypt-pbkdf": "^1.0.2"
@@ -1947,7 +2046,8 @@
1947
2046
  "version": "0.14.5",
1948
2047
  "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz",
1949
2048
  "integrity": "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==",
1950
- "license": "Unlicense"
2049
+ "license": "Unlicense",
2050
+ "optional": true
1951
2051
  },
1952
2052
  "node_modules/uuid": {
1953
2053
  "version": "14.0.3",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.156-next.1",
3
+ "version": "0.2.159-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.",
@@ -46,8 +46,8 @@
46
46
  "@xterm/xterm": "^6.0.0",
47
47
  "clavarium-binder": "0.1.43-next.1",
48
48
  "clavarium-docket": "0.1.1",
49
- "clavarium-parley": "0.17.30-next.1",
50
- "clavarium-tether": "0.1.0-next.34",
49
+ "clavarium-parley": "0.17.31-next.1",
50
+ "clavarium-tether": "0.1.0-next.38",
51
51
  "mermaid": "11.17.2",
52
52
  "node-pty": "^1.1.0",
53
53
  "pdfjs-dist": "6.4.299",
@@ -58,5 +58,8 @@
58
58
  },
59
59
  "publishConfig": {
60
60
  "access": "public"
61
+ },
62
+ "optionalDependencies": {
63
+ "sherpa-onnx-node": "1.12.40"
61
64
  }
62
65
  }
package/server/api.mjs CHANGED
@@ -455,7 +455,7 @@ export async function handleApi(request, response, conversations, headers, resou
455
455
  /* Assets > Access: the owner sets a conversation's level and rules on a
456
456
  target, decides a call that waited, or removes a target. Each is an op the
457
457
  keeper runs as the owner (person), never as an agent. */
458
- const tetherOp = /^\/api\/tether\/(level|allow|unallow|decide|remove-target|stop|resume)$/.exec(pathname);
458
+ const tetherOp = /^\/api\/tether\/(level|allow|unallow|decide|remove-target|stop|resume|job-done|job-file)$/.exec(pathname);
459
459
  if (tetherOp && tethers) { const r = await tethers.act(tetherOp[1], body, ''); if (!r.ok) throw new Refusal(400, r.text); return send(200, r.data ?? { ok: true }), true; }
460
460
  /* A mailbox's signature (Markdown), added under what the agent sends from it. */
461
461
  if (pathname === '/api/tether/signature' && tethers) {
@@ -500,10 +500,12 @@ export async function handleApi(request, response, conversations, headers, resou
500
500
  return send(200, op[2] === 'password' ? await team.password(email) : { operators: await team[op[2]](email) }), true;
501
501
  }
502
502
  const renaming = /^\/api\/secrets\/([A-Z][A-Z0-9_]{0,39})\/rename$/.exec(pathname);
503
- if (renaming && secrets) return send(200, secrets.rename(renaming[1], String(body.name ?? '').trim())), true;
503
+ /* Its machines that run get the new name or value now, as a secret given to them does. */
504
+ const redeliver = async (name) => { for (const c of conversations.list()) if (c.phase === 'ready' && !c.asleep && secrets.of(c.name).includes(name)) await secrets.deliver(c.name).catch(() => {}); };
505
+ if (renaming && secrets) { const done = secrets.rename(renaming[1], String(body.name ?? '').trim()); await redeliver(String(body.name ?? '').trim()); return send(200, done), true; }
504
506
  /* A new value (never sent back) and/or a new expiry, in place. */
505
507
  const replacing = /^\/api\/secrets\/([A-Z][A-Z0-9_]{0,39})\/replace$/.exec(pathname);
506
- if (replacing && secrets) return send(200, secrets.replace(replacing[1], { value: body.value, expires: body.expires })), true;
508
+ if (replacing && secrets) { const done = secrets.replace(replacing[1], { value: body.value, expires: body.expires }); await redeliver(replacing[1]); return send(200, done), true; }
507
509
  const dropped = /^\/api\/secrets\/([A-Z][A-Z0-9_]{0,39})\/remove$/.exec(pathname);
508
510
  if (dropped && secrets) { secrets.remove(dropped[1]); return send(200, { ok: true }), true; }
509
511
  if (pathname === '/api/alerts' && alerts) return send(201, alerts.add(body.subscription, body.label)), true;
@@ -0,0 +1,286 @@
1
+ /* VOICE BOXES: a small speaker in a room, bound to one conversation.
2
+ *
3
+ * A press on its button, a sentence: the box streams it here, the dictation
4
+ * engine (voice.mjs) turns it into text, and the text is said in the box's
5
+ * conversation as the person's own message, the room named. What the tool
6
+ * then says or asks there is read aloud (speech.mjs) and played by the box.
7
+ * Protocol v1: DEVICES.md.
8
+ *
9
+ * code the operator asks for a pairing code for a conversation: 8
10
+ * characters, one use, CODE_MINUTES
11
+ * pair the box gives the code: it gets an id and a key, once. Only
12
+ * the key's SHA-256 is kept
13
+ * link the box connects to /c/api/box/ws with its key; a withdrawn
14
+ * key gets 401 and the box goes back to its setup
15
+ *
16
+ * Both are under /c/: the edge lets them through without sign-on, as the
17
+ * device door. Nothing is kept of the audio, here or on the box.
18
+ */
19
+ import { randomBytes, randomUUID, createHash, timingSafeEqual } from 'node:crypto';
20
+ import { Refusal } from './conversations.mjs';
21
+
22
+ export const CODE_MINUTES = 10;
23
+ export const PAIR_PATH = '/c/api/box/pair';
24
+ export const LINK_PATH = '/c/api/box/ws';
25
+ export const SENTENCE_MAX = 15 * 32_000 + 32_000; /* 15 s of 16 kHz 16-bit mono, and some slack */
26
+ export const ANSWER_MINUTES = 5; /* after a sentence, what the tool says is spoken */
27
+ export const TRIES_PER_MINUTE = 10;
28
+ export const NAME_MAX = 40;
29
+ const ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; /* nothing read two ways: no 0/O, 1/I */
30
+
31
+ export const hashOf = (key) => createHash('sha256').update(String(key)).digest('hex');
32
+
33
+ export function newCode() {
34
+ const bytes = randomBytes(8);
35
+ const s = [...bytes].map((b) => ALPHABET[b % ALPHABET.length]).join('');
36
+ return `${s.slice(0, 4)}-${s.slice(4)}`;
37
+ }
38
+ const plainCode = (code) => String(code ?? '').toUpperCase().replace(/[^A-Z0-9]/g, '');
39
+
40
+ /* A WAV header for 16 kHz, 16-bit mono PCM: what the dictation engine is given. */
41
+ export function wavOf(pcm, rate = 16_000) {
42
+ const h = Buffer.alloc(44);
43
+ h.write('RIFF', 0); h.writeUInt32LE(36 + pcm.length, 4); h.write('WAVE', 8);
44
+ h.write('fmt ', 12); h.writeUInt32LE(16, 16); h.writeUInt16LE(1, 20); h.writeUInt16LE(1, 22);
45
+ h.writeUInt32LE(rate, 24); h.writeUInt32LE(rate * 2, 28); h.writeUInt16LE(2, 32); h.writeUInt16LE(16, 34);
46
+ h.write('data', 36); h.writeUInt32LE(pcm.length, 40);
47
+ return Buffer.concat([h, pcm]);
48
+ }
49
+
50
+ /* Text for the ear: what a written message holds and a voice should not read. */
51
+ export function forSpeech(text) {
52
+ return String(text ?? '')
53
+ .replace(/```[\s\S]*?```/g, ' ')
54
+ .replace(/`([^`]*)`/g, '$1')
55
+ .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
56
+ .replace(/https?:\/\/\S+/g, ' ')
57
+ .replace(/[*_#>|~]+/g, ' ')
58
+ .replace(/\s+/g, ' ')
59
+ .trim()
60
+ .slice(0, 1500);
61
+ }
62
+
63
+ export class Boxes {
64
+ #file; #codes = new Map(); #links = new Map(); #tries = []; #now;
65
+ #exists; #hear; #say; #speak; #log;
66
+
67
+ /* file: a JsonFile holding [{ id, name, conversation, keyHash, firmware, createdAt, seenAt }].
68
+ exists(conversation), hear(wav) -> text, say(conversation, text, room), speak(text) -> PCM 16 kHz. */
69
+ constructor({ file, exists = () => true, hear, say, speak, now = () => Date.now(), log = () => {} }) {
70
+ this.#file = file; this.#exists = exists; this.#hear = hear; this.#say = say; this.#speak = speak; this.#now = now; this.#log = log;
71
+ }
72
+
73
+ #all() { const v = this.#file.get(); return Array.isArray(v) ? v : []; }
74
+ #save(list) { this.#file.set(list); }
75
+
76
+ /* What the operator sees: never the key, nor its hash. */
77
+ all() {
78
+ return this.#all().map(({ keyHash, ...b }) => ({ ...b, online: this.#links.has(b.id), muted: this.#links.get(b.id)?.muted ?? null, volume: this.#links.get(b.id)?.volume ?? null }));
79
+ }
80
+
81
+ code(conversation, name) {
82
+ if (!this.#exists(conversation)) throw new Refusal(404, 'No such conversation.');
83
+ const code = newCode();
84
+ const label = String(name ?? '').trim().slice(0, NAME_MAX);
85
+ this.#codes.set(plainCode(code), { conversation, name: label, until: this.#now() + CODE_MINUTES * 60_000 });
86
+ return { code, minutes: CODE_MINUTES };
87
+ }
88
+
89
+ pair(body) {
90
+ const now = this.#now();
91
+ this.#tries = this.#tries.filter((t) => t > now - 60_000);
92
+ if (this.#tries.length >= TRIES_PER_MINUTE) throw new Refusal(429, 'Too many tries: wait a minute.');
93
+ this.#tries.push(now);
94
+ for (const [c, v] of this.#codes) if (v.until < now) this.#codes.delete(c);
95
+ const wanted = this.#codes.get(plainCode(body?.code));
96
+ if (!wanted) throw new Refusal(403, 'Unknown or expired code.');
97
+ this.#codes.delete(plainCode(body.code));
98
+ const key = randomBytes(32).toString('base64url');
99
+ const name = wanted.name || String(body.room ?? '').trim().slice(0, NAME_MAX) || 'Voice box';
100
+ const box = {
101
+ id: randomUUID(), name, conversation: wanted.conversation, keyHash: hashOf(key),
102
+ type: String(body.type ?? '').slice(0, 40), firmware: String(body.firmware ?? '').slice(0, 20),
103
+ capabilities: Array.isArray(body.capabilities) ? body.capabilities.map(String).slice(0, 20) : [],
104
+ createdAt: new Date(now).toISOString(), seenAt: null,
105
+ };
106
+ this.#save([...this.#all(), box]);
107
+ this.#log(`voice box paired: ${name} (${box.conversation})`);
108
+ return { id: box.id, key, name };
109
+ }
110
+
111
+ byKey(key) {
112
+ if (!key) return undefined;
113
+ const h = Buffer.from(hashOf(key), 'hex');
114
+ return this.#all().find((b) => timingSafeEqual(Buffer.from(b.keyHash, 'hex'), h));
115
+ }
116
+
117
+ rename(id, name) {
118
+ const label = String(name ?? '').trim().slice(0, NAME_MAX);
119
+ if (!label) throw new Refusal(400, 'A name, please.');
120
+ this.#change(id, { name: label });
121
+ }
122
+
123
+ move(id, conversation) {
124
+ if (!this.#exists(conversation)) throw new Refusal(404, 'No such conversation.');
125
+ this.#change(id, { conversation });
126
+ }
127
+
128
+ /* Withdrawn: its link closes now, and its key opens nothing any more. */
129
+ revoke(id) {
130
+ const list = this.#all();
131
+ if (!list.some((b) => b.id === id)) throw new Refusal(404, 'No such voice box.');
132
+ this.#save(list.filter((b) => b.id !== id));
133
+ this.#links.get(id)?.socket.close(4001, 'withdrawn');
134
+ }
135
+
136
+ /* A conversation removed or renamed: its boxes follow, or are left without one. */
137
+ conversationRenamed(from, to) { for (const b of this.#all()) if (b.conversation === from) this.#change(b.id, { conversation: to }); }
138
+
139
+ #change(id, changes) {
140
+ const list = this.#all();
141
+ const i = list.findIndex((b) => b.id === id);
142
+ if (i < 0) throw new Refusal(404, 'No such voice box.');
143
+ list[i] = { ...list[i], ...changes };
144
+ this.#save(list);
145
+ }
146
+
147
+ /* A command to a box (led, volume, wifi.scan, wifi.join, alert, reboot): resolves with its answer. */
148
+ command(id, message, timeoutMs = 30_000) {
149
+ const link = this.#links.get(id);
150
+ if (!link) return Promise.reject(new Refusal(409, 'This voice box is not connected.'));
151
+ const ask = randomUUID();
152
+ return new Promise((resolve, reject) => {
153
+ const timer = setTimeout(() => { link.waiting.delete(ask); reject(new Refusal(504, 'The voice box did not answer.')); }, timeoutMs);
154
+ timer.unref?.();
155
+ link.waiting.set(ask, (answer) => { clearTimeout(timer); resolve(answer); });
156
+ link.send({ ...message, id: ask });
157
+ });
158
+ }
159
+
160
+ /* The tool said or asked something in a conversation: spoken by its boxes that were just talked to. */
161
+ async agentSaid(conversation, text) {
162
+ const words = forSpeech(text);
163
+ if (!words) return;
164
+ const now = this.#now();
165
+ const boxes = [...this.#links.values()].filter((l) => l.box().conversation === conversation && l.heardAt > now - ANSWER_MINUTES * 60_000);
166
+ if (boxes.length === 0) return;
167
+ let pcm;
168
+ try { pcm = await this.#speak(words); } catch (error) { this.#log(`voice box: no voice for the answer (${error.message})`); for (const l of boxes) l.send({ t: 'cue', name: 'error' }); return; }
169
+ for (const l of boxes) l.play(pcm);
170
+ }
171
+
172
+ /* A box connected with its key: speaks protocol v1 on `socket` (a ws WebSocket). */
173
+ accept(socket, box) {
174
+ this.#links.get(box.id)?.socket.close(4000, 'replaced');
175
+ const send = (o) => { if (socket.readyState === 1) socket.send(JSON.stringify(o)); };
176
+ const link = {
177
+ socket, send, waiting: new Map(), heardAt: 0, muted: null, volume: null,
178
+ box: () => this.#all().find((b) => b.id === box.id) ?? box,
179
+ play: (pcm) => {
180
+ send({ t: 'speak.start', rate: 16_000 });
181
+ for (let at = 0; at < pcm.length; at += 640) if (socket.readyState === 1) socket.send(pcm.subarray(at, at + 640));
182
+ send({ t: 'speak.end' });
183
+ },
184
+ };
185
+ this.#links.set(box.id, link);
186
+ let sentence = null; let size = 0;
187
+ const seen = () => { try { this.#change(box.id, { seenAt: new Date(this.#now()).toISOString() }); } catch { /* withdrawn meanwhile */ } };
188
+ seen();
189
+ socket.on('message', (data, binary) => {
190
+ if (binary) {
191
+ if (!sentence || link.muted) return;
192
+ size += data.length;
193
+ if (size <= SENTENCE_MAX) sentence.push(Buffer.from(data));
194
+ return;
195
+ }
196
+ let m;
197
+ try { m = JSON.parse(String(data)); } catch { return; }
198
+ if (!m || typeof m !== 'object') return;
199
+ if (m.t === 'ping') { send({ t: 'pong' }); return; }
200
+ if (m.t === 'hello') { link.muted = m.muted === true; link.volume = Number.isFinite(m.volume) ? m.volume : null; this.#change(box.id, { firmware: String(m.firmware ?? '').slice(0, 20) }); seen(); return; }
201
+ if (m.t === 'listen.start') { sentence = []; size = 0; return; }
202
+ if (m.t === 'listen.end' && sentence) {
203
+ const pcm = Buffer.concat(sentence);
204
+ sentence = null;
205
+ void this.#heard(link, pcm);
206
+ return;
207
+ }
208
+ if (m.t === 'event') {
209
+ if (m.name === 'mute.on') link.muted = true;
210
+ if (m.name === 'mute.off') link.muted = false;
211
+ return;
212
+ }
213
+ if ((m.t === 'ack' || m.t === 'wifi.scan.result') && typeof m.id === 'string') { link.waiting.get(m.id)?.(m); link.waiting.delete(m.id); }
214
+ });
215
+ socket.on('close', () => { if (this.#links.get(box.id) === link) this.#links.delete(box.id); });
216
+ socket.on('error', () => {});
217
+ }
218
+
219
+ async #heard(link, pcm) {
220
+ if (pcm.length < 16_000) { link.send({ t: 'cue', name: 'done' }); return; } /* under half a second: a press, not a sentence */
221
+ link.send({ t: 'cue', name: 'thinking' });
222
+ let text;
223
+ try { text = String(await this.#hear(wavOf(pcm)) ?? '').trim(); } catch (error) { this.#log(`voice box: dictation failed (${error.message})`); link.send({ t: 'cue', name: 'error' }); return; }
224
+ if (!text) { link.send({ t: 'cue', name: 'error' }); return; }
225
+ const box = link.box();
226
+ try { await this.#say(box.conversation, text, box.name); } catch (error) { this.#log(`voice box: not said in ${box.conversation} (${error.message})`); link.send({ t: 'cue', name: 'error' }); return; }
227
+ link.heardAt = this.#now();
228
+ }
229
+
230
+ /* Wires the box link on an HTTP server: the key in Authorization, else 401. */
231
+ attach(server, WebSocketServer) {
232
+ const wss = new WebSocketServer({ noServer: true, maxPayload: 64 * 1024 });
233
+ server.on('upgrade', (request, socket, head) => {
234
+ const { pathname } = new URL(request.url ?? '/', 'http://local');
235
+ if (pathname !== LINK_PATH) return;
236
+ const key = /^Bearer (\S+)$/.exec(request.headers.authorization ?? '')?.[1];
237
+ const box = this.byKey(key);
238
+ if (!box) { socket.end('HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\nConnection: close\r\n\r\n'); return; }
239
+ wss.handleUpgrade(request, socket, head, (ws) => this.accept(ws, box));
240
+ });
241
+ return wss;
242
+ }
243
+ }
244
+
245
+ /* The operator's side, behind the sign-on:
246
+ * GET /api/boxes the boxes, online or not
247
+ * POST /api/boxes/code {conversation, name?} -> {code, minutes}
248
+ * POST /api/boxes/<id>/rename {name}
249
+ * POST /api/boxes/<id>/move {conversation}
250
+ * POST /api/boxes/<id>/revoke
251
+ * POST /api/boxes/<id>/volume {level 0-100}
252
+ * POST /api/boxes/<id>/wifi-scan -> {networks}
253
+ * POST /api/boxes/<id>/wifi-join {ssid, password}: the password goes to the box, and is kept nowhere here
254
+ * POST /api/boxes/<id>/alert {text?}
255
+ * POST /api/boxes/<id>/reboot
256
+ */
257
+ export async function handleBoxes(request, response, boxes, originOk, headers = {}) {
258
+ const { pathname } = new URL(request.url ?? '/', 'http://local');
259
+ const send = (status, body) => { response.writeHead(status, { ...headers, 'content-type': 'application/json; charset=utf-8' }).end(JSON.stringify(body)); return true; };
260
+ try {
261
+ if (request.method === 'GET' && pathname === '/api/boxes') return send(200, boxes.all());
262
+ if (request.method !== 'POST') return false;
263
+ if (!originOk(request.headers)) return send(403, { error: 'This request does not come from this site.' });
264
+ let text = '';
265
+ for await (const piece of request) { text += piece; if (text.length > 8192) return send(413, { error: 'Too long.' }); }
266
+ const body = text ? JSON.parse(text) : {};
267
+ if (pathname === '/api/boxes/code') return send(201, boxes.code(String(body.conversation ?? ''), body.name));
268
+ const m = /^\/api\/boxes\/([0-9a-f-]{36})\/([a-z-]+)$/.exec(pathname);
269
+ if (!m) return false;
270
+ const [, id, what] = m;
271
+ const answered = (a) => send(a?.ok === false ? 502 : 200, a?.ok === false ? { error: `The voice box said: ${a.detail ?? 'no'}.` } : { ok: true });
272
+ switch (what) {
273
+ case 'rename': boxes.rename(id, body.name); return send(200, { ok: true });
274
+ case 'move': boxes.move(id, String(body.conversation ?? '')); return send(200, { ok: true });
275
+ case 'revoke': boxes.revoke(id); return send(200, { ok: true });
276
+ case 'volume': return answered(await boxes.command(id, { t: 'volume', level: Math.round(Number(body.level)) }));
277
+ case 'wifi-scan': { const r = await boxes.command(id, { t: 'wifi.scan' }); return send(200, { networks: Array.isArray(r.networks) ? r.networks : [] }); }
278
+ case 'wifi-join': return answered(await boxes.command(id, { t: 'wifi.join', ssid: String(body.ssid ?? ''), password: String(body.password ?? '') }, 90_000));
279
+ case 'alert': return answered(await boxes.command(id, { t: 'alert', text: String(body.text ?? '').slice(0, 300) }, 10 * 60_000));
280
+ case 'reboot': return answered(await boxes.command(id, { t: 'reboot' }));
281
+ default: return false;
282
+ }
283
+ } catch (error) {
284
+ return send(error.status ?? (error instanceof SyntaxError ? 400 : 500), { error: error instanceof SyntaxError ? 'Not JSON.' : error.message });
285
+ }
286
+ }
@@ -20,7 +20,9 @@
20
20
  * after them -- never in the folder the tool works in, which may be on
21
21
  * another branch or hold changes not committed. What was checked is always
22
22
  * what would be sent. A copy has no installed dependencies: a check that
23
- * needs them installs them ("npm ci && npm test").
23
+ * needs them installs them ("npm ci && npm test"). They are told so: CLAVARIUM_CHECK_COPY (the
24
+ * copy), CLAVARIUM_CHECK_HEAD (the commit sent), CLAVARIUM_CHECK_REPOSITORY (the main folder,
25
+ * never to be required on a branch or at that commit).
24
26
  *
25
27
  * Bounded: a time limit (killed after it), and only the end of the output
26
28
  * comes back.
@@ -65,6 +67,9 @@ git cat-file -e "$head^{commit}" 2>/dev/null || { echo "The commit to send ($hea
65
67
  git worktree add --detach --quiet "$tmp/at" "$head" >/dev/null 2>&1 || { echo "A copy at the commit to send ($head) could not be made. Look again."; exit ${MOVED}; }
66
68
  made="$tmp/at"; cd "$made" || exit ${MOVED}
67
69
  where="Checked in a copy made at this commit, then taken away."
70
+ # Said to the checks: they run in a copy, at exactly this commit -- never in the main
71
+ # folder, whatever branch it is on. A check needs nothing else to know what is sent.
72
+ export CLAVARIUM_CHECK_COPY="$made" CLAVARIUM_CHECK_HEAD="$head" CLAVARIUM_CHECK_REPOSITORY="$repo"
68
73
  [ "$(git rev-parse --verify --quiet HEAD)" = "$head" ] || { echo "What would be checked is not the commit to send ($head). Look again."; exit ${MOVED}; }
69
74
  status=0; ran=0
70
75
  {
package/server/main.mjs CHANGED
@@ -76,6 +76,9 @@ import { Events } from './events.mjs';
76
76
  import { Bundles } from './bundle.mjs';
77
77
  import { migrateData } from './dataformat.mjs';
78
78
  import { VmWatch } from './vmwatch.mjs';
79
+ import { Boxes, handleBoxes, PAIR_PATH as BOX_PAIR_PATH } from './boxes.mjs';
80
+ import { Speech } from './speech.mjs';
81
+ import { WebSocketServer } from 'ws';
79
82
 
80
83
  const ROOT = fileURLToPath(new URL('..', import.meta.url));
81
84
  const MAINTENANCE = 'deploy/maintenance.html';
@@ -98,6 +101,12 @@ export const FILES = {
98
101
  /* The review's diff, drawn by diff2html (vendored, pinned: web/vendor/diff2html/LICENSE). */
99
102
  '/vendor/diff2html.js': ['web/vendor/diff2html/diff2html-ui-slim.min.js', 'text/javascript; charset=utf-8'],
100
103
  '/vendor/diff2html.css': ['web/vendor/diff2html/diff2html.min.css', 'text/css; charset=utf-8'],
104
+ /* Tether's own module that flashes a device from this browser (ui/device-flash.js), and what it loads. */
105
+ '/vendor/tether/jobs.js': [packageFile('clavarium-tether', 'ui/jobs.js'), 'text/javascript; charset=utf-8'],
106
+ '/vendor/tether/device-flash.js': [packageFile('clavarium-tether', 'ui/device-flash.js'), 'text/javascript; charset=utf-8'],
107
+ '/vendor/tether/improv.js': [packageFile('clavarium-tether', 'ui/improv.js'), 'text/javascript; charset=utf-8'],
108
+ '/vendor/tether/vendor/esptool-0.6.1.js': [packageFile('clavarium-tether', 'ui/vendor/esptool-0.6.1.js'), 'text/javascript; charset=utf-8'],
109
+ '/vendor/tether/vendor/web-serial-polyfill-1.0.15.js': [packageFile('clavarium-tether', 'ui/vendor/web-serial-polyfill-1.0.15.js'), 'text/javascript; charset=utf-8'],
101
110
  '/vendor/xterm.js': [packageFile('@xterm/xterm', 'lib/xterm.js'), 'text/javascript; charset=utf-8'],
102
111
  '/vendor/xterm.css': [packageFile('@xterm/xterm', 'css/xterm.css'), 'text/css; charset=utf-8'],
103
112
  '/vendor/fit.js': [packageFile('@xterm/addon-fit', 'lib/addon-fit.js'), 'text/javascript; charset=utf-8'],
@@ -158,7 +167,7 @@ const withoutTmux = (env) => Object.fromEntries(Object.entries(env).filter(([key
158
167
 
159
168
  const REFUSED = 'This Clavarium belongs to someone else: your account is not one of its operators.\n';
160
169
 
161
- function serve(port, conversations, resources, { gate = () => 'local', originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, repair, capacity, updates, instance = new Instance(), certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral, tethers, accounts, groups } = {}) {
170
+ function serve(port, conversations, resources, { gate = () => 'local', originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, repair, capacity, updates, instance = new Instance(), certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral, tethers, accounts, groups, boxes } = {}) {
162
171
  /* Its manifest carries the name of this Clavarium, or the one a device chose (instance.mjs). */
163
172
  const sendManifest = (response, url) => response.writeHead(200, { ...HEADERS, 'content-type': 'application/manifest+json' }).end(instance.manifest(new URL(url ?? '/', 'http://local').searchParams.get('name') ?? undefined));
164
173
  const sendFile = async (response, file) => {
@@ -188,6 +197,16 @@ function serve(port, conversations, resources, { gate = () => 'local', originOk,
188
197
  say(happened === 'typed' ? 202 : happened === 'capped' ? 429 : 409, { woken: happened === 'typed', why: happened });
189
198
  return;
190
199
  }
200
+ /* A voice box pairing: under /c/, no sign-on; the one-use code is the right (boxes.mjs). */
201
+ if (boxes && pathname === BOX_PAIR_PATH) {
202
+ const say = (status, body) => response.writeHead(status, { ...HEADERS, 'content-type': 'application/json; charset=utf-8' }).end(JSON.stringify(body));
203
+ if (request.method !== 'POST') { say(405, { error: 'Call this address with POST.' }); return; }
204
+ let text = ''; let over = false;
205
+ for await (const piece of request) { text += piece; if (text.length > 4096) { over = true; break; } }
206
+ if (over) { say(413, { error: 'Too long.' }); return; }
207
+ try { say(200, boxes.pair(JSON.parse(text || '{}'))); } catch (error) { say(error.status ?? 400, { error: error instanceof SyntaxError ? 'Not JSON.' : error.message }); }
208
+ return;
209
+ }
191
210
  if (door && pathname.startsWith('/c/')) {
192
211
  if (await handleDoor(request, response, door)) return;
193
212
  if (pathname === '/c/manifest.webmanifest' && request.method === 'GET') { sendManifest(response, request.url); return; }
@@ -201,6 +220,7 @@ function serve(port, conversations, resources, { gate = () => 'local', originOk,
201
220
  response.writeHead(403, { ...HEADERS, 'content-type': 'text/plain; charset=utf-8' }).end(REFUSED);
202
221
  return;
203
222
  }
223
+ if (boxes && pathname.startsWith('/api/boxes') && await handleBoxes(request, response, boxes, originOk, HEADERS)) return;
204
224
  if (conversations && await handleApi(request, response, conversations, HEADERS, resources, originOk, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral, tethers, accounts, groups)) return;
205
225
  if (pathname === '/manifest.webmanifest' && request.method === 'GET') { sendManifest(response, request.url); return; }
206
226
  const file = FILES[pathname];
@@ -446,7 +466,9 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
446
466
  checks: new GitChecks({ vms, conversations: all, resources: folders }) });
447
467
  const gitTimer = gitKeeper.start(gitEveryMs);
448
468
  /* A conversation with a tool on a screen that is not its terminal: see talk.mjs. */
449
- const talk = new Talk({ store: talkStore, words: new Store(`${dataDir}/talk-words.json`), keptDir: `${dataDir}/talk-kept`, vms, conversations: all, resources: folders, toolbox, warm: (name) => bridge?.warm(name), ...(talkEveryMs ? { listenEveryMs: talkEveryMs } : {}),
469
+ /* Voice boxes: what the tool says in their conversation is read aloud (boxes.mjs). */
470
+ let boxes;
471
+ const talk = new Talk({ spoke: (name, text) => { void boxes?.agentSaid(name, text); }, store: talkStore, words: new Store(`${dataDir}/talk-words.json`), keptDir: `${dataDir}/talk-kept`, vms, conversations: all, resources: folders, toolbox, warm: (name) => bridge?.warm(name), ...(talkEveryMs ? { listenEveryMs: talkEveryMs } : {}),
450
472
  ...(rereadAfterMs === undefined ? {} : { rereadAfterMs }),
451
473
  /* A line typed down the terminal already open when there is one, and
452
474
  what is already known of a machine used instead of asking (talk.mjs). */
@@ -549,6 +571,14 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
549
571
  const history = new History({ file: `${dataDir}/history.json` });
550
572
  const historyLook = () => capacity.room().then((room) => history.sample(room, all.list().filter((c) => c.phase === 'ready').map((c) => ({ name: c.name, vm: `clv-${c.name}`, cores: c.cpus ?? 1, memoryMb: c.memoryMb, health: health.of(c.name) })))).catch(() => {});
551
573
  const historyTimer = setInterval(() => { void historyLook(); }, historyEveryMs); historyTimer.unref?.();
574
+ /* THE SECRETS' GUARD: each minute, every machine that runs is looked at -- the names in its
575
+ /run/secrets against those it should hold now, and what was last put there against what would
576
+ be now. A missing one is put back, one too many taken away, a new value given: whatever path
577
+ changed them (a page, an expiry, a machine restarted behind our back). */
578
+ const secretsGuard = async () => {
579
+ for (const name of all.awake()) { const now = await secrets.reconcile(name, delivered.get(name)).catch(() => null); if (now !== null) delivered.set(name, now); }
580
+ };
581
+ const secretsTimer = setInterval(() => { void secretsGuard().catch(() => {}); }, 60_000); secretsTimer.unref?.();
552
582
  /* The certificate the front serves, said in Settings (certificate.mjs). */
553
583
  const certificate = new Certificate({ origin: publicOrigin, alerts });
554
584
  /* All the machines to another disk, from Settings (machinesmove.mjs). */
@@ -564,9 +594,18 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
564
594
  void team.refresh().catch((error) => console.error(`operators: ${error.message}`));
565
595
  const watching = setInterval(() => { void team.watch().catch(() => {}); }, 60_000); watching.unref?.();
566
596
  }
567
- const { server, listening } = serve(port, all, folders, { gate, originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, wifi, binders, meshcentral, tethers, accounts, groups, bundles: new Bundles({ dir: `${dataDir}/imports`, folder: (name) => folders.folder(name) }), repair: (name) => repairTerminal(name) });
568
- server.on('close', () => { closing = true; stopBinders(); stopTethers(); clearInterval(historyTimer); history.save(); stopVmWatch(); stopShelf(); stopHealth(); stopUpdates(); stopWatch(); clearInterval(mailTimer); clearInterval(expiryTimer); clearInterval(answerTimer); clearInterval(wakeTimer); clearInterval(docketTimer); dockets.stop(); clearInterval(gitTimer); talk.stop(); });
597
+ const speech = new Speech({ dir: `${dataDir}/voices`, log: (line) => events.add({ kind: 'server', text: line }) });
598
+ boxes = new Boxes({ file: new JsonFile(`${dataDir}/boxes.json`, []),
599
+ exists: (name) => all.list().some((c) => c.name === name),
600
+ hear: (wav) => voice.transcribe(wav),
601
+ /* Said as the person's own message, the room named (one speaker for now). */
602
+ say: (name, text, room) => talk.say(name, `[${room}] ${text}`, undefined, undefined, 'voice'),
603
+ speak: (text) => speech.speak(text),
604
+ log: (line) => events.add({ kind: 'server', text: line }) });
605
+ const { server, listening } = serve(port, all, folders, { gate, originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, wifi, binders, meshcentral, tethers, accounts, groups, boxes, bundles: new Bundles({ dir: `${dataDir}/imports`, folder: (name) => folders.folder(name) }), repair: (name) => repairTerminal(name) });
606
+ server.on('close', () => { closing = true; stopBinders(); stopTethers(); clearInterval(historyTimer); clearInterval(secretsTimer); history.save(); stopVmWatch(); stopShelf(); stopHealth(); stopUpdates(); stopWatch(); clearInterval(mailTimer); clearInterval(expiryTimer); clearInterval(answerTimer); clearInterval(wakeTimer); clearInterval(docketTimer); dockets.stop(); clearInterval(gitTimer); talk.stop(); });
569
607
  let closing = false;
608
+ boxes.attach(server, WebSocketServer);
570
609
  bridge = attachBridge(server, {
571
610
  onRejoin: (name) => all.rejoin(name),
572
611
  onTyped: (name, data) => { answerer.typed(name, data); talk.typed(name); all.touch(name); typingWatch.typed(name, data); },
@@ -262,6 +262,20 @@ export class Secrets {
262
262
  return this.#given(conversation).map((s) => `${s.name}=${s.sealed}`).sort().join('|');
263
263
  }
264
264
 
265
+ /* THE GUARD (main.mjs, each minute, for each machine that runs): the names in its /run/secrets
266
+ against those it should hold, and `last` (the signature of what was last put there) against
267
+ what it would be now. Delivered again when either differs. Resolves with the signature now
268
+ there, or null when the machine could not be looked at. */
269
+ async reconcile(conversation, last) {
270
+ const seen = await this.#vms.exec(conversation, ['sh', '-c', `ls -1 ${SECRETS_DIR} 2>/dev/null; true`], { timeoutMs: 10_000 }).catch(() => null);
271
+ if (!seen || seen.code !== 0) return null;
272
+ const there = String(seen.stdout ?? '').split('\n').map((x) => x.trim()).filter(Boolean).sort().join('|');
273
+ const wanted = this.signature(conversation);
274
+ if (there === this.given(conversation).sort().join('|') && last === wanted) return wanted;
275
+ await this.deliver(conversation);
276
+ return wanted;
277
+ }
278
+
265
279
  /* Puts in the VM exactly the secrets attached NOW and not expired, and the
266
280
  runner. Called each time the conversation is opened: a detached or
267
281
  expired secret disappears from the VM, a new one appears, and a
package/server/setup.mjs CHANGED
@@ -304,6 +304,8 @@ export class Setup {
304
304
  calendar, an address book -- with the conversations they were given to. */
305
305
  const TCAT = { mail: 'mailbox', calendar: 'agenda', contacts: 'contacts' };
306
306
  for (const t of p.tethers?.store?.().targets() ?? []) {
307
+ /* The USB device of the owner's browser is not an asset: nothing of it to show or carry. */
308
+ if (t.kind === 'device') continue;
307
309
  const kind = TCAT[t.kind] ?? 'mailbox';
308
310
  nodes.push({ id: `connexion:${t.id}`, kind, name: t.title, sub: `${t.kind} (live)`, tether: true, record: t });
309
311
  for (const [agent, grant] of Object.entries(t.grants ?? {})) {
@@ -0,0 +1,88 @@
1
+ /* SPEECH: text read aloud, for the voice boxes (boxes.mjs).
2
+ *
3
+ * On this server, with nothing sent anywhere: a Piper voice (open, French by
4
+ * default) run by sherpa-onnx. The voice is fetched once, the first time it is
5
+ * needed, into the data folder; then it works offline. About 0.3 s of work for
6
+ * 4 s of speech on one core.
7
+ *
8
+ * Out: PCM 16 kHz, 16-bit, mono, little-endian -- what a box plays.
9
+ */
10
+ import { existsSync, mkdirSync, createWriteStream, rmSync, renameSync } from 'node:fs';
11
+ import { pipeline } from 'node:stream/promises';
12
+ import { Readable } from 'node:stream';
13
+ import { execFile } from 'node:child_process';
14
+ import { promisify } from 'node:util';
15
+
16
+ export const VOICES = Object.freeze({
17
+ fr: 'vits-piper-fr_FR-siwis-medium',
18
+ en: 'vits-piper-en_US-amy-medium',
19
+ });
20
+ export const VOICE_URL = (name) => `https://github.com/k2-fsa/sherpa-onnx/releases/download/tts-models/${name}.tar.bz2`;
21
+ export const RATE = 16_000;
22
+
23
+ /* Float samples at `from` Hz -> 16-bit PCM at 16 kHz (linear interpolation: speech, not music). */
24
+ export function toPcm16k(samples, from) {
25
+ const n = Math.floor(samples.length * RATE / from);
26
+ const out = Buffer.alloc(n * 2);
27
+ for (let i = 0; i < n; i++) {
28
+ const x = i * from / RATE;
29
+ const j = Math.floor(x);
30
+ const a = samples[j] ?? 0;
31
+ const b = samples[j + 1] ?? a;
32
+ const v = Math.max(-1, Math.min(1, a + (b - a) * (x - j)));
33
+ out.writeInt16LE(Math.round(v * 32767), i * 2);
34
+ }
35
+ return out;
36
+ }
37
+
38
+ export class Speech {
39
+ #dir; #lang; #engine = null; #loading = null; #fetch; #log;
40
+
41
+ constructor({ dir, lang = 'fr', fetcher = fetch, log = () => {} }) {
42
+ this.#dir = dir; this.#lang = VOICES[lang] ? lang : 'fr'; this.#fetch = fetcher; this.#log = log;
43
+ }
44
+
45
+ get voice() { return VOICES[this.#lang]; }
46
+
47
+ async #voiceFolder() {
48
+ const name = this.voice;
49
+ const folder = `${this.#dir}/${name}`;
50
+ if (existsSync(`${folder}/tokens.txt`)) return folder;
51
+ mkdirSync(this.#dir, { recursive: true });
52
+ const archive = `${this.#dir}/${name}.tar.bz2`;
53
+ this.#log(`speech: fetching the voice ${name}`);
54
+ const response = await this.#fetch(VOICE_URL(name));
55
+ if (!response.ok || !response.body) throw new Error(`the voice could not be fetched (${response.status})`);
56
+ await pipeline(Readable.fromWeb(response.body), createWriteStream(archive));
57
+ const unpacking = `${this.#dir}/.unpacking`;
58
+ rmSync(unpacking, { recursive: true, force: true });
59
+ mkdirSync(unpacking);
60
+ await promisify(execFile)('tar', ['xjf', archive, '-C', unpacking]);
61
+ renameSync(`${unpacking}/${name}`, folder);
62
+ rmSync(unpacking, { recursive: true, force: true });
63
+ rmSync(archive, { force: true });
64
+ return folder;
65
+ }
66
+
67
+ async #load() {
68
+ if (this.#engine) return this.#engine;
69
+ this.#loading ??= (async () => {
70
+ const folder = await this.#voiceFolder();
71
+ const { default: sherpa } = await import('sherpa-onnx-node');
72
+ const model = `${folder}/${this.voice.replace(/^vits-piper-/, '')}.onnx`;
73
+ this.#engine = new sherpa.OfflineTts({
74
+ model: { vits: { model, tokens: `${folder}/tokens.txt`, dataDir: `${folder}/espeak-ng-data` }, numThreads: 1 },
75
+ maxNumSentences: 1,
76
+ });
77
+ return this.#engine;
78
+ })().finally(() => { this.#loading = null; });
79
+ return this.#loading;
80
+ }
81
+
82
+ /* Text -> PCM 16 kHz. */
83
+ async speak(text) {
84
+ const engine = await this.#load();
85
+ const audio = engine.generate({ text, sid: 0, speed: 1.0 });
86
+ return toPcm16k(audio.samples, audio.sampleRate);
87
+ }
88
+ }
package/server/talk.mjs CHANGED
@@ -117,7 +117,7 @@ export function typeCommand(line) {
117
117
  checked out in one folder only, and /tmp is emptied when the machine
118
118
  restarts, with the work left there. Typed in a terminal: no quote, no
119
119
  backquote, nothing a shell would run. */
120
- 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.';
120
+ 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.';
121
121
  /* After a restart, the tool is given this long to start before REREAD is typed. */
122
122
  export const REREAD_AFTER_MS = 10_000;
123
123
  /* READY, NOT JUST STARTED. The tool starts when its terminal is opened, which
@@ -189,7 +189,7 @@ export const windowOf = (choice) => { const [kind, n] = String(choice).split(':'
189
189
  /* What the page may ask for: a part of the thread (Parley's read(options)), its own cursor for "since". */
190
190
  const PART = /^[A-Za-z0-9._~-]{1,200}$/;
191
191
  export class Talk {
192
- #store; #words; #vms; #conversations; #resources; #toolbox; #warm; #alert; #listening = new Map(); #every; #now;
192
+ #store; #words; #vms; #conversations; #resources; #toolbox; #warm; #alert; #spoke; #listening = new Map(); #every; #now;
193
193
  #typedAt = new Map(); #nextTry = new Map(); #trying = new Map(); #timer; #lastLang = 'en'; #rereadAfter;
194
194
  #terminal; #health; #ranAt = new Map(); #kept; #screen; #dropSecret;
195
195
 
@@ -201,9 +201,9 @@ export class Talk {
201
201
  /* `keptDir`: where each conversation's thread is kept (its own folder),
202
202
  in this server's data -- never in the work folder, which its machine
203
203
  writes. Without it, the bridge folder is all there is. */
204
- constructor({ store, words, vms, conversations, resources, toolbox = null, warm = async () => {}, alert = () => {}, listenEveryMs = 2000, now = () => Date.now(), rereadAfterMs = REREAD_AFTER_MS, terminal = null, health = null, keptDir = null, screen = null, dropSecret = null }) {
204
+ constructor({ store, words, vms, conversations, resources, toolbox = null, warm = async () => {}, alert = () => {}, spoke = () => {}, listenEveryMs = 2000, now = () => Date.now(), rereadAfterMs = REREAD_AFTER_MS, terminal = null, health = null, keptDir = null, screen = null, dropSecret = null }) {
205
205
  this.#terminal = terminal; this.#health = health; this.#kept = keptDir; this.#screen = screen; this.#dropSecret = dropSecret;
206
- 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.#every = listenEveryMs; this.#now = now; this.#rereadAfter = rereadAfterMs;
206
+ 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.#every = listenEveryMs; this.#now = now; this.#rereadAfter = rereadAfterMs;
207
207
  for (const s of store.all()) if (s.on === true) this.#listen(s.name);
208
208
  this.#timer = setInterval(() => { void this.#tick(); }, Math.min(listenEveryMs, 1000));
209
209
  this.#timer.unref?.();
@@ -289,6 +289,8 @@ export class Talk {
289
289
  on: (event) => {
290
290
  if (event.type === 'person-reacted') { reacted(event); return; }
291
291
  if (event.type === 'person-wrote') { this.#want(name); return; }
292
+ /* What the tool says or asks: a voice box of this conversation may read it aloud (boxes.mjs). */
293
+ if (event.type === 'agent-said' || event.type === 'agent-asked') this.#spoke(name, event.message?.text ?? '');
292
294
  const words = texts(this.#lastLang, this.settings().own);
293
295
  if (event.type === 'agent-asked') this.#alert({ title: fill(words['alert-asks'], { name }), body: event.message.text ?? '', url: `/?c=${name}` });
294
296
  if (event.type === 'agent-status' && event.message.state === 'waiting') this.#alert({ title: fill(words['alert-waits'], { name }), body: event.message.text ?? '', url: `/?c=${name}` });
@@ -26,6 +26,7 @@ export const FOLDER = '.tether';
26
26
  /* The keeper takes what the agents asked, this often. */
27
27
  export const PUMP_MS = 1000;
28
28
  const AGENT = 'conversation:';
29
+ export const USB_DEVICE = 'usb-device';
29
30
 
30
31
  export class Tethers {
31
32
  #keeper; #resources; #conversations; #secrets; #timers = []; #changes = 0; #seen = new Map();
@@ -42,6 +43,11 @@ export class Tethers {
42
43
  the journal -- bumps the counter the client watches, so the approvals screen
43
44
  sees them all at once, not only when a store change happens to wake it. */
44
45
  this.#keeper.onChange(() => { this.#changes++; this.#tellNew(); });
46
+ /* A device plugged into the owner's computer: one target, always there, flashed from the
47
+ owner's browser (Tether's device connector). The owner gives it to a conversation as any other. */
48
+ try {
49
+ if (!this.#keeper.store.target(USB_DEVICE)) this.#keeper.store.putTarget({ id: USB_DEVICE, title: 'USB device (your browser)', kind: 'device', connector: 'device' });
50
+ } catch { /* a Tether without devices */ }
45
51
  }
46
52
 
47
53
  /* A new call waiting for the owner is said in its conversation's thread -- the same block a
@@ -64,6 +70,18 @@ export class Tethers {
64
70
  const text = [what, r.target?.title ? `(${r.target.title})` : '', r.why ? `-- ${r.why}` : ''].filter(Boolean).join(' ');
65
71
  try { this.announce(name, { kind: 'tether-demande', text: text || (r.verb ?? 'A Tether call'), topic: 'Demande', tone: 'warn', actions: [`allow:${r.id}`, `deny:${r.id}`] }); } catch { /* its chat is off */ }
66
72
  }
73
+ /* An approved call only the owner's browser can do (a device to flash): said once, with where to do it. */
74
+ let jobs = [];
75
+ try { jobs = this.#keeper.jobs?.() ?? []; } catch { jobs = []; }
76
+ for (const j of jobs) {
77
+ live.add(j.id);
78
+ if (this.#seen.has(j.id)) continue;
79
+ const who = String(j.agent ?? '');
80
+ if (!who.startsWith(AGENT)) continue;
81
+ const name = who.slice(AGENT.length);
82
+ this.#seen.set(j.id, { name, verb: j.verb });
83
+ try { this.announce(name, { kind: 'tether-job', text: `To do in your browser: ${j.args?.name ? `flash ${j.args.name}` : 'flash a device'}. Open this conversation's Demandes, plug it in by USB, and start.`, topic: 'Demande', tone: 'warn' }); } catch { /* its chat is off */ }
84
+ }
67
85
  for (const [id, info] of [...this.#seen]) {
68
86
  if (live.has(id)) continue;
69
87
  this.#seen.delete(id);
package/web/app.js CHANGED
@@ -4064,6 +4064,8 @@
4064
4064
  /* The calls this conversation's agent asked the owner to allow: validated here,
4065
4065
  in the parloir, without leaving for the Assets page. */
4066
4066
  const mineDemandes = (Array.isArray(tether.approvals) ? tether.approvals : []).filter((q) => (q.agent?.id ?? '') === `conversation:${current}`);
4067
+ /* Approved calls only this browser can do (a device to flash over USB): Tether's jobs. */
4068
+ const mineJobs = (Array.isArray(tether.jobs) ? tether.jobs : []).filter((j) => j.agent === `conversation:${current}`);
4067
4069
  const mine = new Map((c?.resources ?? []).map((r) => [r.name, r.access]));
4068
4070
  const items = [];
4069
4071
  if (c?.work === 'kept') items.push({ key: 'folder:work', kind: 'folder', name: 'work', own: true, sub: 'where its tool works', badge: 'write', badgeTone: 'write' });
@@ -4078,7 +4080,8 @@
4078
4080
  /* TO SEND, above them all, once it has a repository: every one of them on one screen. */
4079
4081
  const gits = items.filter((i) => i.kind === 'git').map((i) => i.name);
4080
4082
  const outbox = gits.length ? { key: 'send:all', kind: 'send', name: 'To send', sub: 'every repository, reviewed and sent at once' } : null;
4081
- const demandes = mineDemandes.length ? { key: 'demandes:mine', kind: 'demandes', name: 'Demandes', sub: `${mineDemandes.length} waiting for you` } : null;
4083
+ const waitingCount = mineDemandes.length + mineJobs.length;
4084
+ const demandes = waitingCount ? { key: 'demandes:mine', kind: 'demandes', name: 'Demandes', sub: `${waitingCount} waiting for you` } : null;
4082
4085
  const chosen = (outbox && roomPick === outbox.key ? outbox : null) ?? (demandes && roomPick === demandes.key ? demandes : null) ?? items.find((i) => i.key === roomPick) ?? null;
4083
4086
  const as = $('cassets-as');
4084
4087
  as.dataset.open = chosen ? 'detail' : 'list';
@@ -4089,7 +4092,7 @@
4089
4092
  if (chosen === entry) row.setAttribute('aria-current', 'true');
4090
4093
  const words = el('span', 'as-words'); words.append(el('b', '', entry.name), el('small', 'as-sub', entry.sub));
4091
4094
  row.append(kindIcon('send'), words);
4092
- if (entry.key === 'demandes:mine') row.append(el('b', 'count', String(mineDemandes.length)));
4095
+ if (entry.key === 'demandes:mine') row.append(el('b', 'count', String(waitingCount)));
4093
4096
  row.addEventListener('click', () => pickRoomAsset(entry.key));
4094
4097
  return row;
4095
4098
  };
@@ -4106,8 +4109,11 @@
4106
4109
  if (keepFiles) { void paintFiles(); return; }
4107
4110
  detail.append(asTitle(chosen, back));
4108
4111
  if (chosen.kind === 'demandes') {
4109
- detail.append(el('p', 'hint', 'Its agent asked you to allow these Tether calls. Accept, and it runs; refuse, and it is told so.'));
4110
- detail.append(demandesList(mineDemandes, { withWho: false, after: () => paintRoomAssets() }));
4112
+ for (const j of mineJobs) detail.append(jobCard(j, () => paintRoomAssets()));
4113
+ if (mineDemandes.length) {
4114
+ detail.append(el('p', 'hint', 'Its agent asked you to allow these Tether calls. Accept, and it runs; refuse, and it is told so.'));
4115
+ detail.append(demandesList(mineDemandes, { withWho: false, after: () => paintRoomAssets() }));
4116
+ }
4111
4117
  } else if (chosen.kind === 'folder' || chosen.kind === 'mailbox') {
4112
4118
  if (chosen.kind === 'mailbox' && !chosen.target) detail.append(el('p', chosen.box?.failure ? 'error' : 'hint', boxSub(chosen.box)));
4113
4119
  embedFiles(detail, chosen.name);
@@ -4378,6 +4384,35 @@
4378
4384
  return card;
4379
4385
  }
4380
4386
  /* Every call waiting for the owner, on one surface. `withWho`: name who asks. */
4387
+ /* A JOB: a call the owner approved that only this browser can do -- a device to flash
4388
+ over USB. The browser lets only a click reach a USB device, so it waits for one; then
4389
+ Tether's own module runs here (/vendor/tether/jobs.js) and its end is the agent's answer.
4390
+ Its element is kept from one paint to the next: the module draws in it while it runs. */
4391
+ const jobPlaces = new Map();
4392
+ function jobCard(job, after) {
4393
+ if (!jobPlaces.has(job.id)) {
4394
+ const card = el('div', 'card job-card'); card.dataset.job = job.id;
4395
+ const what = job.args?.name ? `Flash ${job.args.name}` : 'Flash a device';
4396
+ card.append(el('b', '', `${what} from this browser`), el('p', 'hint', 'Plug it into this computer (or this Android phone) by USB, then start. Chrome or Edge.'));
4397
+ const place = el('div', 'job-place');
4398
+ const start = el('button', 'primary', 'Plug it in and start'); start.type = 'button';
4399
+ const cancel = el('button', '', 'Cancel'); cancel.type = 'button';
4400
+ const row = el('div', 'action-row'); row.append(start, cancel);
4401
+ start.addEventListener('click', async () => {
4402
+ row.hidden = true;
4403
+ const call = async (op, args) => { try { return { ok: true, data: await post(`${API}/tether/${op}`, args) }; } catch (error) { return { ok: false, text: error.message }; } };
4404
+ /* A device that pairs (a voice box): a one-use code for the conversation that asked, made here. */
4405
+ const pair = async (room) => { const r = await post(`${API}/boxes/code`, { conversation: String(job.agent).replace(/^conversation:/, ''), name: room }); return { url: location.origin, code: r.code }; };
4406
+ try { const { runJob } = await import('/vendor/tether/jobs.js'); await runJob(job, { call, root: place, pair }); }
4407
+ catch (error) { place.textContent = `It could not start: ${error.message}`; }
4408
+ setTimeout(() => { jobPlaces.delete(job.id); after?.(); }, 4000);
4409
+ });
4410
+ cancel.addEventListener('click', async () => { await post(`${API}/tether/job-done`, { id: job.id, ok: false, text: 'cancelled by the owner' }).catch(() => {}); jobPlaces.delete(job.id); after?.(); });
4411
+ card.append(row, place);
4412
+ jobPlaces.set(job.id, card);
4413
+ }
4414
+ return jobPlaces.get(job.id);
4415
+ }
4381
4416
  function demandesList(approvals, { withWho = false, after } = {}) {
4382
4417
  const box = el('div', 'as-users demandes-box');
4383
4418
  for (const q of approvals) box.append(demandeRow(q, { withWho, after }));
@@ -8747,8 +8782,49 @@
8747
8782
  card.append(head, body);
8748
8783
  return card;
8749
8784
  }
8785
+ /* ---- voice boxes (boxes.mjs): pairing codes, the flash from this browser, the list ---- */
8786
+ async function paintBoxes() {
8787
+ const list = await getJson('/boxes', []);
8788
+ const rows = $('box-list'); rows.replaceChildren();
8789
+ if (!list.length) rows.append(el('p', 'hint', 'No voice box yet.'));
8790
+ for (const b of list) {
8791
+ const card = el('div', 'device card box-card'); card.dataset.box = b.id;
8792
+ const head = el('div', 'device-head');
8793
+ const conv = conversations.find((c) => c.name === b.conversation);
8794
+ head.append(el('b', '', b.name), el('small', b.online ? '' : 'warn', `${b.online ? 'online' : 'offline'} · ${conv ? shownName(conv) : b.conversation}${b.firmware ? ` · firmware ${b.firmware}` : ''}${b.muted ? ' · muted' : ''}`));
8795
+ const rename = el('button', '', 'Rename'); rename.type = 'button';
8796
+ rename.addEventListener('click', () => {
8797
+ const field = el('input'); field.value = b.name; field.maxLength = 40; field.setAttribute('aria-label', 'Name of this voice box');
8798
+ const save = el('button', 'primary', 'Save'); save.type = 'button';
8799
+ const done = async () => { if (field.value.trim()) await post(`${API}/boxes/${b.id}/rename`, { name: field.value.trim() }).catch(() => {}); await paintBoxes(); };
8800
+ save.addEventListener('click', () => { void done(); });
8801
+ field.addEventListener('keydown', (event) => { if (event.key === 'Enter') void done(); event.stopPropagation(); });
8802
+ rename.replaceWith(save); head.firstChild.replaceWith(field); focusField(field);
8803
+ });
8804
+ const remove = el('button', '', 'Remove'); remove.type = 'button';
8805
+ remove.addEventListener('click', () => takeBack(remove, `Remove ${b.name}: its key stops working now, and it goes back to its setup`, () => post(`${API}/boxes/${b.id}/revoke`)));
8806
+ const acts = el('div', 'action-row'); acts.append(rename, remove);
8807
+ card.append(head, acts);
8808
+ rows.append(card);
8809
+ }
8810
+ }
8811
+ $('box-new').addEventListener('click', () => {
8812
+ const add = $('box-add'); add.hidden = !add.hidden;
8813
+ const pick = $('box-conversation'); pick.replaceChildren();
8814
+ for (const c of conversations) { const o = el('option', '', shownName(c)); o.value = c.name; pick.append(o); }
8815
+ if (accessFor && conversations.some((c) => c.name === accessFor)) pick.value = accessFor;
8816
+ $('box-ready').hidden = true;
8817
+ });
8818
+ $('box-code').addEventListener('click', async () => {
8819
+ try {
8820
+ const r = await post(`${API}/boxes/code`, { conversation: $('box-conversation').value, name: $('box-room').value.trim() });
8821
+ $('box-code-shown').textContent = r.code; $('box-code-minutes').textContent = `valid ${r.minutes} minutes, once`;
8822
+ $('box-ready').hidden = false;
8823
+ } catch (error) { $('box-code-minutes').textContent = error.message; $('box-ready').hidden = false; }
8824
+ });
8750
8825
  async function paintManage() {
8751
8826
  await readDevices();
8827
+ void paintBoxes();
8752
8828
  $('share-by-device').setAttribute('aria-pressed', String(manageBy === 'device')); $('share-by-thing').setAttribute('aria-pressed', String(manageBy === 'thing'));
8753
8829
  const rows = $('sharing-devices'); rows.replaceChildren(); rows.hidden = manageBy !== 'device';
8754
8830
  const things = $('share-things'); things.replaceChildren(); things.hidden = manageBy !== 'thing';
package/web/index.html CHANGED
@@ -452,6 +452,22 @@
452
452
  <div id="sharing-devices"></div>
453
453
  <p id="sharing-none" class="hint" hidden>Nothing is shared with any device.</p>
454
454
  <div id="share-things" hidden></div>
455
+ <!-- Voice boxes: a speaker in a room, bound to one conversation (boxes.mjs). -->
456
+ <section id="boxes" aria-label="Voice boxes">
457
+ <div class="row"><b>Voice boxes</b><span class="sp"></span><button type="button" id="box-new" class="primary">+ Voice box</button></div>
458
+ <div id="box-add" class="card" hidden>
459
+ <div class="row">
460
+ <label>Conversation <select id="box-conversation"></select></label>
461
+ <label>Room <input id="box-room" maxlength="40" placeholder="Living room"></label>
462
+ <button type="button" id="box-code" class="primary">Get a code</button>
463
+ </div>
464
+ <div id="box-ready" hidden>
465
+ <p>Pairing code <b id="box-code-shown"></b> <span class="hint" id="box-code-minutes"></span></p>
466
+ <p class="hint">Hold the box's button 5 s, join its Wi-Fi « Boitier-… » with a phone, and type this code. A new box: ask the assistant of its conversation to flash it; you plug it in here when it asks.</p>
467
+ </div>
468
+ </div>
469
+ <div id="box-list"></div>
470
+ </section>
455
471
  </div>
456
472
  </div>
457
473
  </div>
package/web/links.js CHANGED
@@ -677,7 +677,7 @@
677
677
  const keep = h('button', { type: 'button', text: 'Cancel', onclick: () => openPop(l) });
678
678
  sure.addEventListener('click', async () => {
679
679
  sure.disabled = true;
680
- try { await takeAway(l); closePop(); await changed(); if (b.kind === 'secret') err(`${b.name} will no longer be handed to ${a.name}'s tool the next time it starts.`); } catch (e) { fail(e); }
680
+ try { await takeAway(l); closePop(); await changed(); if (b.kind === 'secret') err(`${b.name} is taken out of ${a.name}'s machine now; its tool keeps it as a variable until its next start.`); } catch (e) { fail(e); }
681
681
  });
682
682
  row.before(ask);
683
683
  row.replaceChildren(sure, keep);