clavarium 0.2.185-next.1 → 0.2.191-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 +127 -11
- package/server/main.mjs +1 -1
- package/server/voice.mjs +17 -5
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.191-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.191-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.191-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
|
|
|
@@ -253,7 +336,10 @@ export class Boxes {
|
|
|
253
336
|
addressed to (`to`: box ids, #215). Anything else stays in the thread, silent -- a box
|
|
254
337
|
read a whole technical message aloud once (31-10), which nobody wants. */
|
|
255
338
|
async agentSaid(conversation, text, to = null, { doing = false, asked = false } = {}) {
|
|
256
|
-
|
|
339
|
+
/* What it is doing is written for a screen ("Tâche de fond : bêta 0.2.113…"): read aloud, it was words
|
|
340
|
+
from nowhere (31-10). Aloud, only a short plain one; otherwise a word that it is at work. */
|
|
341
|
+
const plain = forSpeech(text);
|
|
342
|
+
const words = doing && (plain.length > 70 || /[\d:;/()[\]→=_]/.test(plain)) ? 'Je regarde, un instant.' : plain;
|
|
257
343
|
if (!words) return;
|
|
258
344
|
let boxes;
|
|
259
345
|
if (doing) {
|
|
@@ -265,11 +351,24 @@ export class Boxes {
|
|
|
265
351
|
boxes = [...this.#links.values()].filter((l) => l.box().conversation === conversation && to.includes(l.box().id));
|
|
266
352
|
}
|
|
267
353
|
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)
|
|
354
|
+
/* A question: the box listens again right after, no wake word needed. So does a box in CONVERSATION:
|
|
355
|
+
asked for ("mode conversation"), or by itself after two sentences within three minutes (31-10);
|
|
356
|
+
it ends when nobody answers, or on "fin de la conversation". */
|
|
357
|
+
const question = !doing && (asked || /\?\s*$/.test(words));
|
|
358
|
+
for (const l of boxes) {
|
|
359
|
+
const chatting = !doing && this.#chatting(l);
|
|
360
|
+
const opening = chatting && !l.chat;
|
|
361
|
+
if (chatting) l.chat = true;
|
|
362
|
+
let pcm;
|
|
363
|
+
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; }
|
|
364
|
+
l.play(pcm, question || chatting ? 'listen' : null);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
#chatting(link) {
|
|
368
|
+
if (link.chat) return true;
|
|
369
|
+
const now = this.#now();
|
|
370
|
+
link.recent = (link.recent ?? []).filter((t) => now - t < CHAT_WITHIN_MS);
|
|
371
|
+
return link.recent.length >= 2;
|
|
273
372
|
}
|
|
274
373
|
|
|
275
374
|
/* A box connected with its key: speaks protocol v1 on `socket` (a ws WebSocket). */
|
|
@@ -308,7 +407,15 @@ export class Boxes {
|
|
|
308
407
|
if (m.volume !== wanted) { send({ t: 'volume', id: randomUUID(), level: wanted }); m.volume = wanted; }
|
|
309
408
|
}
|
|
310
409
|
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; }
|
|
410
|
+
if (m.t === 'listen.start') { if (this.stop(box.id)) this.#log(`voice box ${box.name}: stopped playing, someone speaks`); sentence = []; size = 0; return; }
|
|
411
|
+
if (m.t === 'listen.end' && sentence && m.reason === 'nobody') {
|
|
412
|
+
/* Listened again, nobody spoke: a conversation ends there, in silence. */
|
|
413
|
+
sentence = null;
|
|
414
|
+
if (link.chat) this.#log(`voice box ${box.name}: conversation ended, nobody answered`);
|
|
415
|
+
link.chat = false; link.recent = [];
|
|
416
|
+
link.send({ t: 'cue', name: 'done' });
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
312
419
|
if (m.t === 'listen.end' && sentence) {
|
|
313
420
|
const pcm = Buffer.concat(sentence);
|
|
314
421
|
sentence = null;
|
|
@@ -322,7 +429,7 @@ export class Boxes {
|
|
|
322
429
|
}
|
|
323
430
|
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
431
|
});
|
|
325
|
-
socket.on('close', () => { if (this.#links.get(box.id) === link) { this.#links.delete(box.id); this.#log(`voice box ${box.name}: disconnected`); } });
|
|
432
|
+
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
433
|
socket.on('error', () => {});
|
|
327
434
|
}
|
|
328
435
|
|
|
@@ -337,12 +444,19 @@ export class Boxes {
|
|
|
337
444
|
const lost = async (words) => {
|
|
338
445
|
try { link.play(await this.#speak(words), 'listen'); } catch { link.send({ t: 'cue', name: 'error' }); }
|
|
339
446
|
};
|
|
340
|
-
try {
|
|
447
|
+
try {
|
|
448
|
+
const said = [];
|
|
449
|
+
for (const piece of piecesOf(pcm)) said.push(String(await this.#hear(wavOf(piece)) ?? '').trim());
|
|
450
|
+
text = said.filter(Boolean).join(' ');
|
|
451
|
+
} 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
452
|
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
453
|
const box = link.box();
|
|
343
454
|
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
455
|
this.#log(`voice box ${box.name}: ${seconds} s heard, said in ${box.conversation}`);
|
|
345
456
|
link.heardAt = this.#now();
|
|
457
|
+
link.recent = [...(link.recent ?? []), link.heardAt];
|
|
458
|
+
if (/\bmode conversation\b/i.test(text)) link.chat = true;
|
|
459
|
+
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
460
|
link.doingSaid = false;
|
|
347
461
|
}
|
|
348
462
|
|
|
@@ -424,6 +538,8 @@ export function voiceboxConnector(boxes) {
|
|
|
424
538
|
async run(verb, t, a = {}) {
|
|
425
539
|
const id = t.config?.box;
|
|
426
540
|
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}.` }; }
|
|
541
|
+
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.` }; }
|
|
542
|
+
if (verb === 'voicebox.stop') return { text: boxes.stop(id) ? 'Stopped.' : 'Nothing was playing.' };
|
|
427
543
|
if (verb === 'voicebox.play') { const r = boxes.play(id, Buffer.from(String(a.image ?? ''), 'base64')); return { text: `Played (${r.seconds} s).` }; }
|
|
428
544
|
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
545
|
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.' }; }
|
package/server/main.mjs
CHANGED
|
@@ -605,7 +605,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
605
605
|
const speech = new Speech({ dir: `${dataDir}/voices`, log: (line) => events.add({ kind: 'server', text: line }), secret: (name) => { try { return secrets.reveal(name) ?? undefined; } catch { return undefined; } } });
|
|
606
606
|
boxes = new Boxes({ file: new JsonFile(`${dataDir}/boxes.json`, []),
|
|
607
607
|
exists: (name) => all.list().some((c) => c.name === name),
|
|
608
|
-
hear: (wav) => voice.transcribe(wav), /* the language of the dictation settings, or found by the engine: no language is assumed (a box has no browser to tell one) */
|
|
608
|
+
hear: (wav) => voice.transcribe(wav, undefined, { oneVoice: true }), /* the language of the dictation settings, or found by the engine: no language is assumed (a box has no browser to tell one) */
|
|
609
609
|
/* Said as the person's own message, the room named (one speaker for now). */
|
|
610
610
|
say: (name, text, by) => talk.say(name, text, undefined, undefined, 'voice', { by }),
|
|
611
611
|
/* Each conversation's thread knows its boxes: their names, and the ids its agent answers. */
|
package/server/voice.mjs
CHANGED
|
@@ -116,7 +116,17 @@ export function cleanDictation(raw, seconds) {
|
|
|
116
116
|
const noTemperature = new Set();
|
|
117
117
|
|
|
118
118
|
/* `audio` is a WAV file, as bytes. Resolves with the text to type. */
|
|
119
|
-
|
|
119
|
+
/* ONE VOICE: a voice box hears a room, a TV included. OVH's engine tells voices apart (diarize): only the
|
|
120
|
+
voice that spoke first -- the person who called the box -- is kept (31-10). Other engines: the whole text. */
|
|
121
|
+
const DIARIZES = /^https:\/\/oai\.endpoints\.kepler\.ai\.cloud\.ovh\.net\//;
|
|
122
|
+
export function firstVoice(body) {
|
|
123
|
+
const parts = Array.isArray(body?.diarization) ? body.diarization.filter((p) => typeof p?.text === 'string') : [];
|
|
124
|
+
if (parts.length === 0) return null;
|
|
125
|
+
const who = parts[0].speaker;
|
|
126
|
+
return parts.filter((p) => p.speaker === who).map((p) => p.text.trim()).join(' ');
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export async function transcribe(config, audio, fetcher = fetch, { oneVoice = false } = {}) {
|
|
120
130
|
if (!config) throw new Refusal(503, 'No speech-to-text engine is configured.');
|
|
121
131
|
if (audio.length === 0) throw new Refusal(400, 'The recording is empty.');
|
|
122
132
|
if (audio.length > AUDIO_MAX) throw new Refusal(413, 'The recording is too long.');
|
|
@@ -132,7 +142,9 @@ export async function transcribe(config, audio, fetcher = fetch) {
|
|
|
132
142
|
form.append('file', new Blob([audio], { type: 'audio/wav' }), 'dictation.wav');
|
|
133
143
|
form.append('model', config.model);
|
|
134
144
|
if (config.language) form.append('language', config.language);
|
|
135
|
-
|
|
145
|
+
const diarize = oneVoice && DIARIZES.test(String(config.url));
|
|
146
|
+
form.append('response_format', diarize ? 'verbose_json' : 'json');
|
|
147
|
+
if (diarize) form.append('diarize', 'true');
|
|
136
148
|
if (withTemperature) form.append('temperature', '0');
|
|
137
149
|
return fetcher(config.url, { method: 'POST', redirect: 'error', headers: config.key ? { authorization: `Bearer ${config.key}` } : {}, body: form, signal: AbortSignal.timeout(TIMEOUT_MS) });
|
|
138
150
|
};
|
|
@@ -152,7 +164,7 @@ export async function transcribe(config, audio, fetcher = fetch) {
|
|
|
152
164
|
if (!response.ok) throw new Refusal(502, `The speech-to-text engine answered ${response.status}.`);
|
|
153
165
|
const body = await response.json().catch(() => undefined);
|
|
154
166
|
if (typeof body?.text !== 'string') throw new Refusal(502, 'The speech-to-text engine gave no text.');
|
|
155
|
-
return cleanDictation(body.text, wavSeconds(audio));
|
|
167
|
+
return cleanDictation((oneVoice && firstVoice(body)) || body.text, wavSeconds(audio));
|
|
156
168
|
}
|
|
157
169
|
|
|
158
170
|
/* ---------- THE ENGINE CHOSEN IN SETTINGS ----------
|
|
@@ -288,11 +300,11 @@ export class Dictation {
|
|
|
288
300
|
/* An expired key is never sent: said in one line instead (still offered, so the line is seen). */
|
|
289
301
|
#fresh(c) { if (c?.secret && this.#expired(c.secret)) throw new Refusal(409, KEY_EXPIRED); }
|
|
290
302
|
/* `device`: the language of the device that dictates (a tag such as fr-FR), if it said. */
|
|
291
|
-
async transcribe(audio, device) {
|
|
303
|
+
async transcribe(audio, device, how = {}) {
|
|
292
304
|
this.#fresh(this.#saved());
|
|
293
305
|
const config = this.current();
|
|
294
306
|
if (config) await this.#guard(config);
|
|
295
|
-
return transcribe(config && { ...config, language: languageOf(config.language, device) }, audio, this.#fetcher);
|
|
307
|
+
return transcribe(config && { ...config, language: languageOf(config.language, device) }, audio, this.#fetcher, how);
|
|
296
308
|
}
|
|
297
309
|
/* "Try it": what is in the form, not saved, on one short recording. */
|
|
298
310
|
async try(body, audio, device) {
|