clavarium 0.2.185-next.1 → 0.2.190-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.
- package/deploy/clavarium-host +8 -0
- package/deploy/install.sh +2 -2
- package/deploy/updater.mjs +29 -0
- package/npm-shrinkwrap.json +6 -6
- package/package.json +2 -2
- package/server/boxes.mjs +123 -10
package/deploy/clavarium-host
CHANGED
|
@@ -731,6 +731,14 @@ MESHUNIT
|
|
|
731
731
|
[ $# -ge 2 ] || usage
|
|
732
732
|
AREA="$1"; VERB="$2"; shift 2
|
|
733
733
|
|
|
734
|
+
# What changes something is written to the system log, by this program: sudo itself is told not to log
|
|
735
|
+
# the server's account (its probes every few seconds made some 800 lines in ten minutes, 31-10). Reading
|
|
736
|
+
# verbs, and commands run inside a machine (the server's own probes, mostly), are not written.
|
|
737
|
+
case "$AREA $VERB" in
|
|
738
|
+
"vm exec"|"vm ping"|"vm states"|"vm info"|"server logs"|"server room"|"server usage"|"shelf info"|"shelf room"|"shelf list"|"shelf size"|"shelf exec"|"git read"|"work room"|"disks list"|"disks room"|"machines places"|"machines moving"|"machines old"|"net taps"|"wifi status"|"wifi scan"|"path held"|"disk room"|"update check"|"meshcentral status"|"operator "*) : ;;
|
|
739
|
+
*) [ "$SAY" = yes ] || logger -t clavarium-host -- "$AREA $VERB$(printf ' %.80s' "$@" | head -c 400)" 2>/dev/null || true ;;
|
|
740
|
+
esac
|
|
741
|
+
|
|
734
742
|
# The remote screen's path carries a per-instance suffix: resolve it before any of its verbs run.
|
|
735
743
|
[ "$AREA" = meshcentral ] && mesh_resolve_path
|
|
736
744
|
|
package/deploy/install.sh
CHANGED
|
@@ -238,7 +238,7 @@ apt-get update -qq
|
|
|
238
238
|
# bindfs: the read-only views. nftables: the network rules. build-essential
|
|
239
239
|
# and python3: one module of the server (the terminal) is compiled here.
|
|
240
240
|
# qrencode: the public keys, shown as QR codes on a screen. openssh-client: the tunnel.
|
|
241
|
-
apt-get install -y -qq bindfs nftables build-essential python3 curl ca-certificates xz-utils sudo snapd openssl git qrencode openssh-client >/dev/null
|
|
241
|
+
apt-get install -y -qq bindfs nftables build-essential python3 curl ca-certificates xz-utils sudo snapd openssl git qrencode openssh-client ffmpeg >/dev/null
|
|
242
242
|
snap list multipass >/dev/null 2>&1 || snap install multipass >/dev/null
|
|
243
243
|
|
|
244
244
|
step "account"
|
|
@@ -317,7 +317,7 @@ chmod 0755 /usr/local/bin/clavarium
|
|
|
317
317
|
install -d -o root -g root -m 0755 "$ETC"
|
|
318
318
|
printf 'DATA=%s\nMNT=%s\n' "$DATA" "$MNT" > "$ETC/host.conf"; chmod 0644 "$ETC/host.conf"
|
|
319
319
|
rule="$(mktemp)"
|
|
320
|
-
printf '# Clavarium: the server account may run ONE program as root, and nothing else.\n%s ALL=(root) NOPASSWD: %s\n' "$ACCOUNT" "$HOST_PROGRAM" > "$rule"
|
|
320
|
+
printf '# Clavarium: the server account may run ONE program as root, and nothing else.\n%s ALL=(root) NOPASSWD: %s\n# Its probes every few seconds are not written to the system log; the program logs what changes something.\nDefaults:%s !syslog, !pam_session\n' "$ACCOUNT" "$HOST_PROGRAM" "$ACCOUNT" > "$rule"
|
|
321
321
|
visudo -cf "$rule" >/dev/null || refuse "the sudo rule did not pass its check"
|
|
322
322
|
install -o root -g root -m 0440 "$rule" /etc/sudoers.d/clavarium; rm -f -- "$rule"
|
|
323
323
|
|
package/deploy/updater.mjs
CHANGED
|
@@ -114,6 +114,33 @@ export async function ensureProxySettings({ file = PROXY_CFG, run = runCommand }
|
|
|
114
114
|
return true;
|
|
115
115
|
}
|
|
116
116
|
|
|
117
|
+
/* SUDO, QUIET FOR CLAVARIUM'S ONE PROGRAM, kept by the updater: the server asks the host program every
|
|
118
|
+
few seconds (machine states, memory, repositories), and sudo wrote three lines to the system log for
|
|
119
|
+
each call -- some 800 lines in ten minutes, nothing to read in them (found 31-10). The account may run
|
|
120
|
+
that one program and nothing else; what changes something, the program logs itself (clavarium-host). */
|
|
121
|
+
export const SUDOERS = '/etc/sudoers.d/clavarium';
|
|
122
|
+
export const quietLine = (account) => `Defaults:${account} !syslog, !pam_session`;
|
|
123
|
+
export async function ensureQuietSudo({ file = SUDOERS, run = runCommand } = {}) {
|
|
124
|
+
let text;
|
|
125
|
+
try { text = readFileSync(file, 'utf8'); } catch { return false; }
|
|
126
|
+
const account = text.match(/^([a-z_][a-z0-9_-]*)\s+ALL=\(root\)\s+NOPASSWD:/m)?.[1];
|
|
127
|
+
if (!account || text.includes(quietLine(account))) return false;
|
|
128
|
+
const next = `${text.replace(/\n*$/, '\n')}# Added by the Clavarium updater: its probes every few seconds are not written to the system log.\n${quietLine(account)}\n`;
|
|
129
|
+
writeFileSync(`${file}.new`, next, { mode: 0o440 });
|
|
130
|
+
try { await run(['visudo', '-cf', `${file}.new`], { timeoutMs: 30_000 }); } catch (error) { rmSync(`${file}.new`, { force: true }); throw error; }
|
|
131
|
+
renameSync(`${file}.new`, file);
|
|
132
|
+
return true;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/* FFMPEG, kept by the updater: the voice boxes play a radio, a podcast, a music file through it
|
|
136
|
+
(server/boxes.mjs, listen). Installed by install.sh; added once to a machine installed before. */
|
|
137
|
+
export async function ensureFfmpeg({ run = runCommand, has = () => ['/usr/bin/ffmpeg', '/usr/local/bin/ffmpeg'].some((f) => existsSync(f)) } = {}) {
|
|
138
|
+
if (has()) return false;
|
|
139
|
+
if (process.getuid?.() !== 0) return false;
|
|
140
|
+
await run(['apt-get', 'install', '-y', '-qq', 'ffmpeg'], { timeoutMs: 15 * 60_000, env: { ...process.env, DEBIAN_FRONTEND: 'noninteractive' } });
|
|
141
|
+
return has();
|
|
142
|
+
}
|
|
143
|
+
|
|
117
144
|
/* THE MAINTENANCE PAGE, kept by the updater: while the server is down (an update, a restart) the
|
|
118
145
|
front (Caddy) answers it instead of the sign-in proxy's "Bad Gateway". The sign-in proxy answers
|
|
119
146
|
502 in HTML when the server does not; the server's own errors are JSON and pass as they are. A
|
|
@@ -913,6 +940,8 @@ async function main(argv) {
|
|
|
913
940
|
update that brought it ran the PREVIOUS release's code. Idempotent; never stops the turn. */
|
|
914
941
|
try { const [{ installWatch }, { realSys }] = await Promise.all([import('./doctor.mjs'), import('./online.mjs')]); if (await installWatch(realSys())) console.error('updater: the certificate timer set up'); } catch (error) { console.error(`updater: the certificate timer could not be set up: ${error.message}`); }
|
|
915
942
|
try { if (await u.ensureDropIn()) console.error('updater: the drop-in of the server\'s unit written'); } catch (error) { console.error(`updater: the drop-in could not be written: ${error.message}`); }
|
|
943
|
+
try { if (await ensureFfmpeg()) console.error('updater: ffmpeg installed, for the sounds the voice boxes play'); } catch (error) { console.error(`updater: ffmpeg could not be installed: ${error.message}`); }
|
|
944
|
+
try { if (await ensureQuietSudo()) console.error('updater: sudo no longer logs the host program\'s probes'); } catch (error) { console.error(`updater: sudo could not be made quiet: ${error.message}`); }
|
|
916
945
|
try { if (await ensureProxySettings()) console.error('updater: the sign-in proxy takes one CSRF cookie per sign-in'); } catch (error) { console.error(`updater: the sign-in proxy could not be set: ${error.message}`); }
|
|
917
946
|
try { const c = await ensureGenericClientId({ run: runCommand }); if (c.changed.length) console.error('updater: the sign-in client id was made generic (nothing names the product in the open)'); } catch (error) { console.error(`updater: the sign-in client id could not be made generic: ${error.message}`); }
|
|
918
947
|
try { if (await ensureTunnel({ run: runCommand })) console.error('updater: the tunnel to the relay notices a cut sooner'); } catch (error) { console.error(`updater: the tunnel could not be set: ${error.message}`); }
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.190-next.1",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "clavarium",
|
|
9
|
-
"version": "0.2.
|
|
9
|
+
"version": "0.2.190-next.1",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@xterm/addon-fit": "^0.11.0",
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
"clavarium-binder": "0.1.43-next.1",
|
|
15
15
|
"clavarium-docket": "0.1.1",
|
|
16
16
|
"clavarium-parley": "0.17.33-next.1",
|
|
17
|
-
"clavarium-tether": "0.1.0-next.
|
|
17
|
+
"clavarium-tether": "0.1.0-next.45",
|
|
18
18
|
"mermaid": "11.17.2",
|
|
19
19
|
"node-pty": "^1.1.0",
|
|
20
20
|
"pdfjs-dist": "6.4.299",
|
|
@@ -760,9 +760,9 @@
|
|
|
760
760
|
}
|
|
761
761
|
},
|
|
762
762
|
"node_modules/clavarium-tether": {
|
|
763
|
-
"version": "0.1.0-next.
|
|
764
|
-
"resolved": "https://registry.npmjs.org/clavarium-tether/-/clavarium-tether-0.1.0-next.
|
|
765
|
-
"integrity": "sha512-
|
|
763
|
+
"version": "0.1.0-next.45",
|
|
764
|
+
"resolved": "https://registry.npmjs.org/clavarium-tether/-/clavarium-tether-0.1.0-next.45.tgz",
|
|
765
|
+
"integrity": "sha512-3lZT2MHeQWcfF8241K2+N+/ZX8wluFe0HqlrUPbTgSMws+RqQh61mEzk0Z9vlHSoG5aGhQ5b8CwK1QqBwGp9nQ==",
|
|
766
766
|
"license": "MIT",
|
|
767
767
|
"bin": {
|
|
768
768
|
"tether": "bin/cli.mjs",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.190-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.",
|
|
@@ -47,7 +47,7 @@
|
|
|
47
47
|
"clavarium-binder": "0.1.43-next.1",
|
|
48
48
|
"clavarium-docket": "0.1.1",
|
|
49
49
|
"clavarium-parley": "0.17.33-next.1",
|
|
50
|
-
"clavarium-tether": "0.1.0-next.
|
|
50
|
+
"clavarium-tether": "0.1.0-next.45",
|
|
51
51
|
"mermaid": "11.17.2",
|
|
52
52
|
"node-pty": "^1.1.0",
|
|
53
53
|
"pdfjs-dist": "6.4.299",
|
package/server/boxes.mjs
CHANGED
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
* Both are under /c/: the edge lets them through without sign-on, as the
|
|
17
17
|
* device door. Nothing is kept of the audio, here or on the box.
|
|
18
18
|
*/
|
|
19
|
+
import { spawn as spawnProcess } from 'node:child_process';
|
|
19
20
|
import { randomBytes, randomUUID, createHash, timingSafeEqual } from 'node:crypto';
|
|
20
21
|
import { Refusal } from './conversations.mjs';
|
|
21
22
|
|
|
@@ -93,20 +94,45 @@ export function forSpeech(text) {
|
|
|
93
94
|
.replace(/[*_#>|~]+/g, ' ')
|
|
94
95
|
/* Times as said: "14h30" -> "14 heures 30", "14h" -> "14 heures" (read "14 H" otherwise, 31-10). */
|
|
95
96
|
.replace(/\b([01]?\d|2[0-3])\s?[hH](?:\s?([0-5]\d))?\b/g, (_, h, m) => `${h} heure${h === '1' || h === '0' ? '' : 's'}${m ? ` ${m}` : ''}`)
|
|
97
|
+
/* Never its own wake word aloud: the box heard itself and cut its own sentence (31-10). */
|
|
98
|
+
.replace(/\b(?:hey|hé|eh)[\s,]+jarvis\b/giu, 'le mot d\'éveil')
|
|
96
99
|
.replace(/\s+/g, ' ')
|
|
97
100
|
.trim()
|
|
98
101
|
.slice(0, 1500);
|
|
99
102
|
}
|
|
100
103
|
|
|
101
104
|
export const DOING_WITHIN_MS = 120_000;
|
|
105
|
+
export const CHAT_WITHIN_MS = 3 * 60_000;
|
|
106
|
+
export const LISTEN_AHEAD = 3 * 32_000; /* bytes: what a box is sent ahead of what it plays (its buffer holds 16 s) */
|
|
107
|
+
|
|
108
|
+
/* A LONG SENTENCE, IN PIECES: dictation takes 16 s at most (voice.mjs, AUDIO_MAX), a box a minute; five
|
|
109
|
+
long sentences were lost so (31-10). Each piece ends at the quietest 20 ms between 8 and 14 s: a pause,
|
|
110
|
+
most often, rather than a word cut in two. PCM 16 kHz 16-bit mono in, pieces out. */
|
|
111
|
+
export function piecesOf(pcm, { least = 8, most = 14 } = {}) {
|
|
112
|
+
const second = 32_000; const step = 640; const out = [];
|
|
113
|
+
let at = 0;
|
|
114
|
+
while (pcm.length - at > most * second) {
|
|
115
|
+
let best = at + most * second; let quietest = Infinity;
|
|
116
|
+
for (let i = at + least * second; i + step <= at + most * second; i += step) {
|
|
117
|
+
let e = 0;
|
|
118
|
+
for (let k = i; k < i + step; k += 2) { const v = pcm.readInt16LE(k); e += v * v; }
|
|
119
|
+
if (e < quietest) { quietest = e; best = i + step / 2; }
|
|
120
|
+
}
|
|
121
|
+
best -= best % 2;
|
|
122
|
+
out.push(pcm.subarray(at, best)); at = best;
|
|
123
|
+
}
|
|
124
|
+
out.push(pcm.subarray(at));
|
|
125
|
+
return out;
|
|
126
|
+
}
|
|
102
127
|
|
|
103
128
|
export class Boxes {
|
|
104
129
|
#file; #codes = new Map(); #links = new Map(); #tries = []; #now;
|
|
105
|
-
#exists; #hear; #say; #speak; #log; #changed; #images = new Map(); #origin;
|
|
130
|
+
#exists; #hear; #say; #speak; #log; #changed; #images = new Map(); #origin; #spawn; #fetch; #streams = new Map();
|
|
106
131
|
|
|
107
132
|
/* file: a JsonFile holding [{ id, name, conversation, keyHash, firmware, createdAt, seenAt }].
|
|
108
133
|
exists(conversation), hear(wav) -> text, say(conversation, text, room), speak(text) -> PCM 16 kHz. */
|
|
109
|
-
constructor({ file, exists = () => true, hear, say, speak, changed = () => {}, origin = () => null, now = () => Date.now(), log = () => {} }) {
|
|
134
|
+
constructor({ file, exists = () => true, hear, say, speak, changed = () => {}, origin = () => null, now = () => Date.now(), log = () => {}, spawn = spawnProcess, fetcher = fetch }) {
|
|
135
|
+
this.#spawn = spawn; this.#fetch = fetcher;
|
|
110
136
|
this.#file = file; this.#changed = changed; this.#origin = origin; this.#exists = exists; this.#hear = hear; this.#say = say; this.#speak = speak; this.#now = now; this.#log = log;
|
|
111
137
|
}
|
|
112
138
|
|
|
@@ -209,6 +235,63 @@ export class Boxes {
|
|
|
209
235
|
return this.#images.get(String(token).replace(/\.bin$/, ''))?.bytes;
|
|
210
236
|
}
|
|
211
237
|
|
|
238
|
+
/* LISTENING TO THE INTERNET: a radio, a podcast, a music file, a playlist, read by this server (ffmpeg,
|
|
239
|
+
any format it knows) and sent on to the box at the pace it is played, a few seconds ahead -- until it
|
|
240
|
+
ends, stop(), or the person presses the button or says the wake word (the box then starts a sentence). */
|
|
241
|
+
async listen(id, url, name = '') {
|
|
242
|
+
const link = this.#links.get(id);
|
|
243
|
+
if (!link) throw new Refusal(409, 'This voice box is not connected.');
|
|
244
|
+
this.stop(id);
|
|
245
|
+
const source = await this.#resolve(url);
|
|
246
|
+
let child;
|
|
247
|
+
try { child = this.#spawn('ffmpeg', ['-nostdin', '-loglevel', 'error', '-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5', '-i', source, '-vn', '-ac', '1', '-ar', '16000', '-f', 's16le', '-'], { stdio: ['ignore', 'pipe', 'pipe'] }); }
|
|
248
|
+
catch { throw new Refusal(501, 'This server cannot read sounds: ffmpeg is not installed (an update installs it).'); }
|
|
249
|
+
const box = link.box(); const label = name || new URL(url).host;
|
|
250
|
+
const stream = { child, queue: [], queued: 0, sent: 0, started: this.#now(), timer: null, ended: false, failed: '' };
|
|
251
|
+
this.#streams.set(id, stream);
|
|
252
|
+
link.send({ t: 'speak.start', rate: 16_000 });
|
|
253
|
+
child.stdout.on('data', (d) => { stream.queue.push(d); stream.queued += d.length; if (stream.queued > LISTEN_AHEAD * 4) child.stdout.pause(); });
|
|
254
|
+
child.stderr.on('data', (d) => { stream.failed = `${stream.failed}${d}`.slice(-300); });
|
|
255
|
+
child.on('error', (e) => { stream.failed = e.code === 'ENOENT' ? 'ffmpeg is not installed on this server' : e.message; stream.ended = true; });
|
|
256
|
+
child.on('close', () => { stream.ended = true; });
|
|
257
|
+
let carry = Buffer.alloc(0);
|
|
258
|
+
stream.timer = setInterval(() => {
|
|
259
|
+
if (this.#streams.get(id) !== stream) return;
|
|
260
|
+
const due = (this.#now() - stream.started) * 32 + LISTEN_AHEAD; /* bytes the box should have by now, a few seconds ahead */
|
|
261
|
+
while (stream.sent + 640 <= due && (carry.length >= 640 || stream.queue.length)) {
|
|
262
|
+
if (carry.length < 640) { const d = stream.queue.shift(); stream.queued -= d.length; carry = Buffer.concat([carry, d]); continue; }
|
|
263
|
+
if (link.socket.readyState === 1) link.socket.send(carry.subarray(0, 640));
|
|
264
|
+
carry = carry.subarray(640); stream.sent += 640;
|
|
265
|
+
}
|
|
266
|
+
if (stream.queued < LISTEN_AHEAD) child.stdout.resume();
|
|
267
|
+
if (stream.ended && !stream.queue.length && carry.length < 640) {
|
|
268
|
+
this.#log(`voice box ${box.name}: ${label} ended after ${Math.round(stream.sent / 32_000)} s${stream.failed && stream.sent < 32_000 ? ` (${stream.failed.trim().split('\n').pop()})` : ''}`);
|
|
269
|
+
this.stop(id);
|
|
270
|
+
}
|
|
271
|
+
}, 100);
|
|
272
|
+
stream.timer.unref?.();
|
|
273
|
+
this.#log(`voice box ${box.name}: plays ${label}`);
|
|
274
|
+
return { ok: true };
|
|
275
|
+
}
|
|
276
|
+
stop(id) {
|
|
277
|
+
const stream = this.#streams.get(id);
|
|
278
|
+
if (!stream) return false;
|
|
279
|
+
this.#streams.delete(id);
|
|
280
|
+
clearInterval(stream.timer);
|
|
281
|
+
try { stream.child.kill('SIGTERM'); } catch { /* gone */ }
|
|
282
|
+
this.#links.get(id)?.send({ t: 'speak.end' });
|
|
283
|
+
return true;
|
|
284
|
+
}
|
|
285
|
+
/* A playlist (.m3u, .pls) is a list of addresses: its first one. */
|
|
286
|
+
async #resolve(url) {
|
|
287
|
+
if (!/\.(m3u|pls)(\?|$)/i.test(new URL(url).pathname)) return url;
|
|
288
|
+
try {
|
|
289
|
+
const r = await this.#fetch(url, { signal: AbortSignal.timeout(10_000) });
|
|
290
|
+
const text = await r.text();
|
|
291
|
+
return text.split(/\r?\n/).map((l) => l.replace(/^File\d+=/i, '').trim()).find((l) => /^https?:\/\//.test(l)) ?? url;
|
|
292
|
+
} catch { return url; }
|
|
293
|
+
}
|
|
294
|
+
|
|
212
295
|
/* Where it is (a home, a family house): grouped by it, named with it. */
|
|
213
296
|
place(id, place) { this.#change(id, { place: String(place ?? '').trim().slice(0, NAME_MAX) }); }
|
|
214
297
|
|
|
@@ -265,11 +348,24 @@ export class Boxes {
|
|
|
265
348
|
boxes = [...this.#links.values()].filter((l) => l.box().conversation === conversation && to.includes(l.box().id));
|
|
266
349
|
}
|
|
267
350
|
if (boxes.length === 0) return;
|
|
268
|
-
/* A question: the box listens again right after, no wake word needed.
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
for (const l of boxes)
|
|
351
|
+
/* A question: the box listens again right after, no wake word needed. So does a box in CONVERSATION:
|
|
352
|
+
asked for ("mode conversation"), or by itself after two sentences within three minutes (31-10);
|
|
353
|
+
it ends when nobody answers, or on "fin de la conversation". */
|
|
354
|
+
const question = !doing && (asked || /\?\s*$/.test(words));
|
|
355
|
+
for (const l of boxes) {
|
|
356
|
+
const chatting = !doing && this.#chatting(l);
|
|
357
|
+
const opening = chatting && !l.chat;
|
|
358
|
+
if (chatting) l.chat = true;
|
|
359
|
+
let pcm;
|
|
360
|
+
try { pcm = await this.#speak(opening ? `Je passe en mode conversation : je reste à l'écoute. ${words}` : words); } catch (error) { this.#log(`voice box: no voice for the answer (${error.message})`); l.send({ t: 'cue', name: 'error' }); continue; }
|
|
361
|
+
l.play(pcm, question || chatting ? 'listen' : null);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
#chatting(link) {
|
|
365
|
+
if (link.chat) return true;
|
|
366
|
+
const now = this.#now();
|
|
367
|
+
link.recent = (link.recent ?? []).filter((t) => now - t < CHAT_WITHIN_MS);
|
|
368
|
+
return link.recent.length >= 2;
|
|
273
369
|
}
|
|
274
370
|
|
|
275
371
|
/* A box connected with its key: speaks protocol v1 on `socket` (a ws WebSocket). */
|
|
@@ -308,7 +404,15 @@ export class Boxes {
|
|
|
308
404
|
if (m.volume !== wanted) { send({ t: 'volume', id: randomUUID(), level: wanted }); m.volume = wanted; }
|
|
309
405
|
}
|
|
310
406
|
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; }
|
|
311
|
-
if (m.t === 'listen.start') { sentence = []; size = 0; return; }
|
|
407
|
+
if (m.t === 'listen.start') { if (this.stop(box.id)) this.#log(`voice box ${box.name}: stopped playing, someone speaks`); sentence = []; size = 0; return; }
|
|
408
|
+
if (m.t === 'listen.end' && sentence && m.reason === 'nobody') {
|
|
409
|
+
/* Listened again, nobody spoke: a conversation ends there, in silence. */
|
|
410
|
+
sentence = null;
|
|
411
|
+
if (link.chat) this.#log(`voice box ${box.name}: conversation ended, nobody answered`);
|
|
412
|
+
link.chat = false; link.recent = [];
|
|
413
|
+
link.send({ t: 'cue', name: 'done' });
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
312
416
|
if (m.t === 'listen.end' && sentence) {
|
|
313
417
|
const pcm = Buffer.concat(sentence);
|
|
314
418
|
sentence = null;
|
|
@@ -322,7 +426,7 @@ export class Boxes {
|
|
|
322
426
|
}
|
|
323
427
|
if ((m.t === 'ack' || m.t === 'wifi.scan.result') && typeof m.id === 'string') { link.waiting.get(m.id)?.(m); link.waiting.delete(m.id); }
|
|
324
428
|
});
|
|
325
|
-
socket.on('close', () => { if (this.#links.get(box.id) === link) { this.#links.delete(box.id); this.#log(`voice box ${box.name}: disconnected`); } });
|
|
429
|
+
socket.on('close', () => { if (this.#links.get(box.id) === link) { this.stop(box.id); this.#links.delete(box.id); this.#log(`voice box ${box.name}: disconnected`); } });
|
|
326
430
|
socket.on('error', () => {});
|
|
327
431
|
}
|
|
328
432
|
|
|
@@ -337,12 +441,19 @@ export class Boxes {
|
|
|
337
441
|
const lost = async (words) => {
|
|
338
442
|
try { link.play(await this.#speak(words), 'listen'); } catch { link.send({ t: 'cue', name: 'error' }); }
|
|
339
443
|
};
|
|
340
|
-
try {
|
|
444
|
+
try {
|
|
445
|
+
const said = [];
|
|
446
|
+
for (const piece of piecesOf(pcm)) said.push(String(await this.#hear(wavOf(piece)) ?? '').trim());
|
|
447
|
+
text = said.filter(Boolean).join(' ');
|
|
448
|
+
} catch (error) { this.#log(`voice box ${box0.name}: ${seconds} s heard, dictation failed (${error.message})`); await lost('Pardon, la dictée ne répond pas. Tu peux répéter ?'); return; }
|
|
341
449
|
if (!text) { this.#log(`voice box ${box0.name}: ${seconds} s heard, nothing recognised (silence?)`); await lost("Pardon, je n'ai rien compris. Tu peux répéter ?"); return; }
|
|
342
450
|
const box = link.box();
|
|
343
451
|
try { await this.#say(box.conversation, text, { id: box.id, name: box.name, ...(box.place ? { place: box.place } : {}) }); } catch (error) { this.#log(`voice box ${box.name}: ${seconds} s heard and dictated, but not said in ${box.conversation} (${error.message})`); await lost("Pardon, je n'ai pas pu transmettre ta phrase. Tu peux répéter ?"); return; }
|
|
344
452
|
this.#log(`voice box ${box.name}: ${seconds} s heard, said in ${box.conversation}`);
|
|
345
453
|
link.heardAt = this.#now();
|
|
454
|
+
link.recent = [...(link.recent ?? []), link.heardAt];
|
|
455
|
+
if (/\bmode conversation\b/i.test(text)) link.chat = true;
|
|
456
|
+
if (/\b(?:fin|arr[eê]te|stop)\w*\b.{0,20}\b(?:conversation|[ée]couter)\b/i.test(text)) { link.chat = false; link.recent = []; }
|
|
346
457
|
link.doingSaid = false;
|
|
347
458
|
}
|
|
348
459
|
|
|
@@ -424,6 +535,8 @@ export function voiceboxConnector(boxes) {
|
|
|
424
535
|
async run(verb, t, a = {}) {
|
|
425
536
|
const id = t.config?.box;
|
|
426
537
|
if (verb === 'voicebox.volume') { const r = await boxes.setVolume(id, a.level); return { text: r?.offline ? `Volume ${a.level} kept: the box is offline, it gets it when it comes back.` : `Volume set to ${a.level}.` }; }
|
|
538
|
+
if (verb === 'voicebox.listen') { await boxes.listen(id, String(a.url), String(a.name ?? '')); return { text: `Playing ${a.name || a.url}: it goes on until it ends, voicebox-stop, or the person presses the button or says the wake word.` }; }
|
|
539
|
+
if (verb === 'voicebox.stop') return { text: boxes.stop(id) ? 'Stopped.' : 'Nothing was playing.' };
|
|
427
540
|
if (verb === 'voicebox.play') { const r = boxes.play(id, Buffer.from(String(a.image ?? ''), 'base64')); return { text: `Played (${r.seconds} s).` }; }
|
|
428
541
|
if (verb === 'voicebox.update') { await boxes.update(id, a.image, a.version); return { text: `Installed${a.version ? ` (${a.version})` : ''}: the box restarts and comes back in a moment.` }; }
|
|
429
542
|
if (verb === 'voicebox.alert') { await boxes.command(id, { t: 'alert', text: String(a.text ?? '').slice(0, 300) }, 10 * 60_000); return { text: 'The alert was seen: someone pressed its button.' }; }
|