clavarium 0.2.121-beta.1 → 0.2.122-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -301,3 +301,7 @@ Without a guard, nothing commits. That is on purpose.
301
301
  ## Licence
302
302
 
303
303
  MIT. See `LICENSE`.
304
+
305
+ ## Credits
306
+
307
+ The voice boxes speak with **Pocket TTS** by **Kyutai** (program MIT, weights CC-BY-4.0), fetched at run time; Piper voices (sherpa-onnx) are the fallback. See CREDITS.md in the repository.
package/deploy/install.sh CHANGED
@@ -317,8 +317,14 @@ 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# 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"
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"
321
321
  visudo -cf "$rule" >/dev/null || refuse "the sudo rule did not pass its check"
322
+ # Its probes every few seconds kept out of the system log, with what this sudo takes (the updater does the same).
323
+ for quiet in '!syslog, !pam_session' '!pam_session'; do
324
+ cp "$rule" "$rule.q"; printf 'Defaults:%s %s\n' "$ACCOUNT" "$quiet" >> "$rule.q"
325
+ if out="$(visudo -cf "$rule.q" 2>&1)" && ! printf '%s' "$out" | grep -qiE 'unknown setting|syntax error|parse error'; then mv "$rule.q" "$rule"; break; fi
326
+ rm -f "$rule.q"
327
+ done
322
328
  install -o root -g root -m 0440 "$rule" /etc/sudoers.d/clavarium; rm -f -- "$rule"
323
329
 
324
330
  step "what the machines are given, on root's chain"
@@ -119,17 +119,36 @@ export async function ensureProxySettings({ file = PROXY_CFG, run = runCommand }
119
119
  each call -- some 800 lines in ten minutes, nothing to read in them (found 31-10). The account may run
120
120
  that one program and nothing else; what changes something, the program logs itself (clavarium-host). */
121
121
  export const SUDOERS = '/etc/sudoers.d/clavarium';
122
- export const quietLine = (account) => `Defaults:${account} !syslog, !pam_session`;
122
+ /* What sudo is told, tried in this order: the first its version takes without a word wins. Some sudo builds do
123
+ not know « syslog » (found 01-11 on a real server: « unknown setting: 'syslog' » on every call); they keep
124
+ the session lines quiet at least. A line of ours their sudo does not take is replaced. */
125
+ export const QUIET_SETTINGS = ['!syslog, !pam_session', '!pam_session'];
126
+ export const quietLine = (account, setting = QUIET_SETTINGS[0]) => `Defaults:${account} ${setting}`;
127
+ const QUIET_COMMENT = '# Added by the Clavarium updater: its probes every few seconds are not written to the system log.';
123
128
  export async function ensureQuietSudo({ file = SUDOERS, run = runCommand } = {}) {
124
129
  let text;
125
130
  try { text = readFileSync(file, 'utf8'); } catch { return false; }
126
131
  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;
132
+ if (!account) return false;
133
+ const accepted = async (candidate) => {
134
+ rmSync(`${file}.new`, { force: true });
135
+ writeFileSync(`${file}.new`, candidate, { mode: 0o440 });
136
+ const r = await run(['visudo', '-cf', `${file}.new`], { timeoutMs: 30_000 });
137
+ return r.code === 0 && !/unknown setting|syntax error|parse error/i.test(`${r.stdout}\n${r.stderr}`);
138
+ };
139
+ /* The rule as it is, without any line of ours. */
140
+ const base = text.split('\n').filter((l) => l !== QUIET_COMMENT && !l.startsWith(`Defaults:${account} `)).join('\n').replace(/\n*$/, '\n');
141
+ const current = QUIET_SETTINGS.map((q) => quietLine(account, q)).find((l) => text.includes(l));
142
+ try {
143
+ if (current && await accepted(text)) return false; /* ours, and taken as it is */
144
+ for (const setting of QUIET_SETTINGS) {
145
+ const next = `${base}${QUIET_COMMENT}\n${quietLine(account, setting)}\n`;
146
+ if (await accepted(next)) { renameSync(`${file}.new`, file); return true; }
147
+ }
148
+ /* None taken: the rule alone, as install.sh wrote it -- never a file sudo complains about. */
149
+ if (current && await accepted(base)) { renameSync(`${file}.new`, file); return true; }
150
+ return false;
151
+ } finally { rmSync(`${file}.new`, { force: true }); }
133
152
  }
134
153
 
135
154
  /* FFMPEG, kept by the updater: the voice boxes play a radio, a podcast, a music file through it
@@ -1,19 +1,19 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.121-beta.1",
3
+ "version": "0.2.122-beta.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.121-beta.1",
9
+ "version": "0.2.122-beta.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.33-next.1",
16
+ "clavarium-parley": "0.17.35-next.1",
17
17
  "clavarium-tether": "0.1.0-next.46",
18
18
  "mermaid": "11.17.2",
19
19
  "node-pty": "^1.1.0",
@@ -747,9 +747,9 @@
747
747
  }
748
748
  },
749
749
  "node_modules/clavarium-parley": {
750
- "version": "0.17.33-next.1",
751
- "resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.33-next.1.tgz",
752
- "integrity": "sha512-pJ+YFWKZgiVvrzRHpsruciTHt5R3tOzo4XbHsEWmCqlXYEKCLWI29TnyR3nJ63X0qM1AJFACfiNl7DDOrXFK5w==",
750
+ "version": "0.17.35-next.1",
751
+ "resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.35-next.1.tgz",
752
+ "integrity": "sha512-bUR/1I9ZqEXWJ7SoxPYdkjlOHJ8dnML5A0ZQGfuEOl4YNuB6ULT4PoWqHfj0fVhY2j6BjDLvHJKZJ8WouEGXig==",
753
753
  "license": "MIT",
754
754
  "bin": {
755
755
  "parley": "bin/parley.mjs",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.121-beta.1",
3
+ "version": "0.2.122-beta.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,7 +46,7 @@
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.33-next.1",
49
+ "clavarium-parley": "0.17.35-next.1",
50
50
  "clavarium-tether": "0.1.0-next.46",
51
51
  "mermaid": "11.17.2",
52
52
  "node-pty": "^1.1.0",
package/server/boxes.mjs CHANGED
@@ -123,6 +123,27 @@ export function offsetOf(zone, now) {
123
123
  }
124
124
 
125
125
  export const RELAY_WITHIN_MS = 20_000;
126
+ /* Sentences to say one by one: cut after . ! ? … and kept at 40 characters at least (a tiny one joins the next). */
127
+ export function sentencesOf(text) {
128
+ const out = [];
129
+ for (const piece of String(text).split(/(?<=[.!?…])\s+/)) {
130
+ if (out.length && out[out.length - 1].length < 40) out[out.length - 1] += ` ${piece}`; else out.push(piece);
131
+ }
132
+ return out.filter(Boolean);
133
+ }
134
+
135
+ export const THINKING_AFTER_MS = 3_500;
136
+ export const LONGER_AFTER_MS = 12_000;
137
+ export const THINKING = ['Hmm…', 'Voyons…', 'Hmm, voyons voir…'];
138
+ /* WHY A BOX LISTENED, in a few words beside the message (01-11): what woke it (and the wake word's score), and
139
+ what it cut short. */
140
+ export function whyOf(m) {
141
+ const reason = { wake: 'mot d\'éveil', button: 'bouton', follow: 'suite de la conversation', knock: 'toc-toc' }[m?.reason] ?? (m?.reason ? String(m.reason).slice(0, 30) : 'inconnu');
142
+ const score = Number.isFinite(m?.score) ? ` (${Math.round(m.score * 100)} %)` : '';
143
+ const cut = m?.cut ? ` ; a interrompu ${String(m.cut) === 'its own speech' ? 'sa propre phrase' : 'un son'}` : '';
144
+ return `réveil : ${reason}${score}${cut}`;
145
+ }
146
+
126
147
  export const DOING_WITHIN_MS = 120_000;
127
148
  /* A LONG RECORDING (a meeting, a class): asked in words, stopped by the button or the wake word. */
128
149
  export const RECORD_ASKED = /\b(?:lance|d[ée]marre|commence|d[ée]bute)\w*\b.{0,25}\benregistrement\b|\benregistre\b.{0,20}\b(?:r[ée]union|conversation|cours|discussion|consultation)\b/i;
@@ -131,6 +152,22 @@ export const mmss = (s) => `${String(Math.floor(s / 60)).padStart(2, '0')}:${Str
131
152
  /* THE MIXER of a box that plays a stream: words said meanwhile go over it, the stream lowered to DUCK while
132
153
  they last, with a fade down and up (a quarter of a second) rather than a jump. One 20 ms chunk at a time. */
133
154
  export const DUCK = 0.2;
155
+ /* LEVELS (01-11): like a phone, one volume for the whole box (set, and eased to the room by the box itself),
156
+ and under it each kind of sound brought to its own steady level -- a loud radio and a quiet one played alike
157
+ (ffmpeg's loudnorm, EBU R128), the radio a step below the box's voice, its voice always at one loudness. */
158
+ export const STREAM_LUFS = -26;
159
+ export const STREAM_LEVEL = 1;
160
+ export const VOICE_RMS = 3300; /* about -20 dBFS: the loudness the voice was found right at */
161
+ export function levelled(pcm, target = VOICE_RMS) {
162
+ let sum = 0; let n = 0;
163
+ for (let i = 0; i + 1 < pcm.length; i += 2) { const v = pcm.readInt16LE(i); if (Math.abs(v) > 300) { sum += v * v; n++; } }
164
+ if (n < 100) return pcm;
165
+ const gain = Math.min(4, target / Math.sqrt(sum / n));
166
+ if (Math.abs(gain - 1) < 0.05) return pcm;
167
+ const out = Buffer.alloc(pcm.length & ~1);
168
+ for (let i = 0; i + 1 < pcm.length; i += 2) out.writeInt16LE(Math.max(-32768, Math.min(32767, Math.round(pcm.readInt16LE(i) * gain))), i);
169
+ return out;
170
+ }
134
171
  export function mix(stream, chunk) {
135
172
  const words = stream.over[0];
136
173
  const target = words ? DUCK : 1;
@@ -138,7 +175,7 @@ export function mix(stream, chunk) {
138
175
  const step = (1 - DUCK) / (0.25 * 16_000);
139
176
  for (let i = 0; i < chunk.length; i += 2) {
140
177
  stream.gain += Math.max(-step, Math.min(step, target - stream.gain));
141
- let v = chunk.readInt16LE(i) * stream.gain;
178
+ let v = chunk.readInt16LE(i) * stream.gain * STREAM_LEVEL;
142
179
  if (words && stream.gain <= DUCK + 0.05) {
143
180
  stream.at ??= 0;
144
181
  if (stream.at + 1 < words.length) { v += words.readInt16LE(stream.at); stream.at += 2; }
@@ -175,11 +212,12 @@ export function piecesOf(pcm, { least = 8, most = 14 } = {}) {
175
212
 
176
213
  export class Boxes {
177
214
  #file; #codes = new Map(); #links = new Map(); #tries = []; #now;
178
- #exists; #hear; #say; #speak; #log; #changed; #images = new Map(); #origin; #spawn; #fetch; #streams = new Map(); #recordDir; #parts; #keep;
215
+ #exists; #hear; #say; #speak; #log; #changed; #images = new Map(); #origin; #spawn; #fetch; #streams = new Map(); #recordDir; #parts; #keep; #react;
179
216
 
180
217
  /* file: a JsonFile holding [{ id, name, conversation, keyHash, firmware, createdAt, seenAt }].
181
218
  exists(conversation), hear(wav) -> text, say(conversation, text, room), speak(text) -> PCM 16 kHz. */
182
- constructor({ file, exists = () => true, hear, say, speak, changed = () => {}, origin = () => null, now = () => Date.now(), log = () => {}, spawn = spawnProcess, fetcher = fetch, recordDir = null, parts = null, keep = null }) {
219
+ constructor({ file, exists = () => true, hear, say, speak, changed = () => {}, origin = () => null, now = () => Date.now(), log = () => {}, spawn = spawnProcess, fetcher = fetch, recordDir = null, parts = null, keep = null, react = async () => null }) {
220
+ this.#react = react;
183
221
  this.#spawn = spawn; this.#fetch = fetcher; this.#recordDir = recordDir; this.#parts = parts; this.#keep = keep;
184
222
  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;
185
223
  }
@@ -307,7 +345,7 @@ export class Boxes {
307
345
  this.stop(id);
308
346
  const source = await this.#resolve(url);
309
347
  let child;
310
- 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'] }); }
348
+ try { child = this.#spawn('ffmpeg', ['-nostdin', '-loglevel', 'error', '-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5', '-i', source, '-vn', '-af', `loudnorm=I=${STREAM_LUFS}:TP=-3:LRA=11`, '-ac', '1', '-ar', '16000', '-f', 's16le', '-'], { stdio: ['ignore', 'pipe', 'pipe'] }); }
311
349
  catch { throw new Refusal(501, 'This server cannot read sounds: ffmpeg is not installed (an update installs it).'); }
312
350
  const box = link.box(); const label = name || new URL(url).host;
313
351
  const stream = { child, queue: [], queued: 0, sent: 0, started: this.#now(), timer: null, ended: false, failed: '', over: [], gain: 1 };
@@ -404,6 +442,23 @@ export class Boxes {
404
442
  /* The tool said or asked something in a conversation: said aloud only by the boxes it is
405
443
  addressed to (`to`: box ids, #215). Anything else stays in the thread, silent -- a box
406
444
  read a whole technical message aloud once (31-10), which nobody wants. */
445
+ /* WHILE THE ANSWER IS THOUGHT (01-11): no long silence after a sentence. A short « hmm » if nothing has
446
+ come after a little while, then a word that it takes longer; whatever the assistant says first (an answer,
447
+ what it is doing) ends the wait. A longer question (many words) is told sooner that it takes a moment. */
448
+ #waitFor(link, text = '') {
449
+ clearTimeout(link.thinkingA); clearTimeout(link.thinkingB);
450
+ const said = link.heardAt;
451
+ const still = () => link.heardAt === said && !((link.answeredAt ?? 0) >= said);
452
+ const long = String(text).length > 160; /* a long question: told sooner that it takes a moment */
453
+ const say = async (words) => { if (!still() || link.recording || this.#streams.has(link.box().id)) return; try { link.play(await this.#speak(words)); } catch { /* the light says it */ } };
454
+ /* Made at once, used if the answer is still not there: a reaction to THIS sentence, in its language. */
455
+ let made = null;
456
+ this.#react(text).then((t) => { made = t; }).catch(() => {});
457
+ link.thinkingA = setTimeout(() => { void say(made || THINKING[Math.floor(Math.random() * THINKING.length)]); }, THINKING_AFTER_MS);
458
+ link.thinkingB = setTimeout(() => { void say(long ? 'Ta question est riche, je regarde, un instant.' : 'Ça me demande un peu plus de temps, je regarde.'); }, long ? LONGER_AFTER_MS * 0.6 : LONGER_AFTER_MS);
459
+ link.thinkingA.unref?.(); link.thinkingB.unref?.();
460
+ }
461
+
407
462
  async agentSaid(conversation, text, to = null, { doing = false, asked = false } = {}) {
408
463
  /* What it is doing is written for a screen ("Tâche de fond : bêta 0.2.113…"): read aloud, it was words
409
464
  from nowhere (31-10). Aloud, only a short plain one; otherwise a word that it is at work. */
@@ -421,9 +476,10 @@ export class Boxes {
421
476
  }
422
477
  if (boxes.length === 0) return;
423
478
  /* A question: the box listens again right after, no wake word needed. So does a box in CONVERSATION:
424
- asked for ("mode conversation"), or by itself after two sentences within three minutes (31-10);
479
+ asked for ("mode conversation") -- never by itself any more (01-11);
425
480
  it ends when nobody answers, or on "fin de la conversation". */
426
481
  const question = !doing && (asked || /\?\s*$/.test(words));
482
+ for (const l of boxes) { l.answeredAt = this.#now(); clearTimeout(l.thinkingA); clearTimeout(l.thinkingB); }
427
483
  for (const l of boxes) {
428
484
  /* An answer -- to a sentence heard within a minute -- may open the conversation; something said
429
485
  of itself (a news item, a reminder) does not: the box listened after it for nothing (31-10). */
@@ -431,16 +487,22 @@ export class Boxes {
431
487
  const chatting = !doing && answering && this.#chatting(l);
432
488
  const opening = chatting && !l.chat;
433
489
  if (chatting) l.chat = true;
434
- let pcm;
435
- 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; }
436
- l.play(pcm, question || chatting ? 'listen' : null); /* a question is always listened after: an answer is expected */
490
+ /* SENTENCE BY SENTENCE: the first is said while the next ones are made -- the answer starts sooner
491
+ (31-10: a few seconds of silence before each answer). The box queues them, one after the other. */
492
+ const parts = sentencesOf(opening ? `Je passe en mode conversation : je reste à l'écoute. ${words}` : words);
493
+ let next = this.#speak(parts[0]);
494
+ for (const [i, part] of parts.entries()) {
495
+ let pcm;
496
+ try { pcm = await next; } catch (error) { this.#log(`voice box: no voice for the answer (${error.message})`); l.send({ t: 'cue', name: 'error' }); break; }
497
+ if (i + 1 < parts.length) { next = this.#speak(parts[i + 1]); next.catch(() => {}); }
498
+ l.play(pcm, i + 1 === parts.length && (question || chatting) ? 'listen' : null); /* a question is always listened after: an answer is expected */
499
+ }
437
500
  }
438
501
  }
502
+ /* Only when asked ("mode conversation"): opened by itself after two sentences, it stayed listening and
503
+ took in the room's talk -- the circle kept lit, stray words sent (01-11). */
439
504
  #chatting(link) {
440
- if (link.chat) return true;
441
- const now = this.#now();
442
- link.recent = (link.recent ?? []).filter((t) => now - t < CHAT_WITHIN_MS);
443
- return link.recent.length >= 2;
505
+ return Boolean(link.chat);
444
506
  }
445
507
 
446
508
  /* A box connected with its key: speaks protocol v1 on `socket` (a ws WebSocket). */
@@ -451,7 +513,7 @@ export class Boxes {
451
513
  socket, send, waiting: new Map(), heardAt: 0, muted: null, volume: null,
452
514
  box: () => this.#all().find((b) => b.id === box.id) ?? box,
453
515
  play: (pcm, then = null) => {
454
- pcm = pcm.subarray(0, pcm.length & ~1); /* whole samples only: an odd byte shifts every sample after it */
516
+ pcm = levelled(pcm.subarray(0, pcm.length & ~1)); /* whole samples only (an odd byte shifts every sample after it), at the voice's level */
455
517
  /* Something is playing (a radio): the words go over it, the radio lowered meanwhile (the mixer, listen()). */
456
518
  const playing = this.#streams.get(box.id);
457
519
  if (playing) { playing.over.push(pcm); return; }
@@ -503,6 +565,9 @@ export class Boxes {
503
565
  r.out.end(() => { void this.#recorded(link, r); });
504
566
  return;
505
567
  }
568
+ if (m.t === 'event' && m.name === 'wake.own') { this.#log(`voice box ${box.name}: heard its own voice say the wake word, ignored`); return; }
569
+ if (m.t === 'event' && m.name === 'noise.dropped') { this.#log(`voice box ${box.name}: a sound near full scale was cut by its noise guard`); return; }
570
+ if (m.t === 'listen.start') link.why = whyOf(m);
506
571
  if (m.t === 'listen.start') { if (this.stop(box.id)) this.#log(`voice box ${box.name}: stopped playing, someone speaks`); sentence = []; size = 0; return; }
507
572
  if (m.t === 'listen.end' && sentence && m.reason === 'nobody') {
508
573
  /* Listened again, nobody spoke: a conversation ends there, in silence. */
@@ -588,7 +653,9 @@ export class Boxes {
588
653
  } 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; }
589
654
  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; }
590
655
  const box = link.box();
591
- if (RECORD_ASKED.test(text) && this.#recordDir && this.#parts) {
656
+ /* Only a short order starts a recording ("lance l'enregistrement de la réunion"): a sentence that merely
657
+ mentions recording does not (01-11). */
658
+ if (RECORD_ASKED.test(text) && text.split(/\s+/).length <= 10 && this.#recordDir && this.#parts) {
592
659
  this.#log(`voice box ${box.name}: a recording asked`);
593
660
  try { link.play(await this.#speak("J'enregistre. Pour arrêter, appuie sur le bouton ou dis le mot d'éveil.")); } catch { /* no voice: the light says it */ }
594
661
  link.send({ t: 'record', on: true });
@@ -598,9 +665,10 @@ export class Boxes {
598
665
  link.relay = 0;
599
666
  text = `(réponse entendue de l'appareil, pas de la personne) ${text}`;
600
667
  }
601
- 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; }
668
+ try { await this.#say(box.conversation, text, { id: box.id, name: box.name, ...(box.place ? { place: box.place } : {}), ...(link.why ? { why: link.why } : {}) }); } 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; }
602
669
  this.#log(`voice box ${box.name}: ${seconds} s heard, said in ${box.conversation}`);
603
670
  link.heardAt = this.#now();
671
+ this.#waitFor(link, text);
604
672
  link.recent = [...(link.recent ?? []), link.heardAt];
605
673
  if (/\bmode conversation\b/i.test(text)) link.chat = true;
606
674
  if (/\b(?:fin|arr[eê]te|stop)\w*\b.{0,20}\b(?:conversation|[ée]couter)\b/i.test(text)) { link.chat = false; link.recent = []; }
@@ -632,7 +700,10 @@ export class Boxes {
632
700
  * POST /api/boxes/<id>/revoke
633
701
  * POST /api/boxes/<id>/volume {level 0-100}
634
702
  * POST /api/boxes/<id>/wifi-scan -> {networks}
635
- * POST /api/boxes/<id>/wifi-join {ssid, password}: the password goes to the box, and is kept nowhere here
703
+ * POST /api/boxes/<id>/wifi-join {ssid, password}: the password goes to the box, and is kept nowhere here;
704
+ * the box ADDS it to the networks it knows (8 at most) and goes to the strongest
705
+ * POST /api/boxes/<id>/wifi-known -> {networks, current}: the names it knows (never a password)
706
+ * POST /api/boxes/<id>/wifi-forget {ssid}: not the one it uses now
636
707
  * POST /api/boxes/<id>/alert {text?}
637
708
  * POST /api/boxes/<id>/reboot
638
709
  */
@@ -667,6 +738,8 @@ export async function handleBoxes(request, response, boxes, originOk, headers =
667
738
  case 'revoke': boxes.revoke(id); return send(200, { ok: true });
668
739
  case 'volume': return answered(await boxes.setVolume(id, body.level));
669
740
  case 'wifi-scan': { const r = await boxes.command(id, { t: 'wifi.scan' }); return send(200, { networks: Array.isArray(r.networks) ? r.networks : [] }); }
741
+ case 'wifi-known': { const r = await boxes.command(id, { t: 'wifi.list' }); return send(200, { networks: Array.isArray(r.networks) ? r.networks.map(String) : [], current: String(r.current ?? '') }); }
742
+ case 'wifi-forget': return answered(await boxes.command(id, { t: 'wifi.forget', ssid: String(body.ssid ?? '').slice(0, 32) }));
670
743
  case 'wifi-join': return answered(await boxes.command(id, { t: 'wifi.join', ssid: String(body.ssid ?? ''), password: String(body.password ?? '') }, 90_000));
671
744
  case 'alert': return answered(await boxes.command(id, { t: 'alert', text: String(body.text ?? '').slice(0, 300) }, 10 * 60_000));
672
745
  case 'reboot': return answered(await boxes.command(id, { t: 'reboot' }));
package/server/main.mjs CHANGED
@@ -77,6 +77,7 @@ import { Bundles } from './bundle.mjs';
77
77
  import { migrateData } from './dataformat.mjs';
78
78
  import { VmWatch } from './vmwatch.mjs';
79
79
  import { Boxes, handleBoxes, voiceboxConnector, syncTargets, PAIR_PATH as BOX_PAIR_PATH, FIRMWARE_PATH as BOX_FIRMWARE_PATH } from './boxes.mjs';
80
+ import { Pocket } from './pocket.mjs';
80
81
  import { Speech } from './speech.mjs';
81
82
  import { WebSocketServer } from 'ws';
82
83
 
@@ -602,10 +603,14 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
602
603
  void team.refresh().catch((error) => console.error(`operators: ${error.message}`));
603
604
  const watching = setInterval(() => { void team.watch().catch(() => {}); }, 60_000); watching.unref?.();
604
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
+ const speechLog = (line) => events.add({ kind: 'server', text: line });
607
+ const speech = new Speech({ dir: `${dataDir}/voices`, log: speechLog, secret: (name) => { try { return secrets.reveal(name) ?? undefined; } catch { return undefined; } },
608
+ /* The voice by default: Kyutai's Pocket TTS, run here (pocket.mjs); CLAVARIUM_POCKET=0 to leave it out. */
609
+ pocket: process.env.CLAVARIUM_POCKET === '0' ? null : new Pocket({ dir: `${dataDir}/voices`, log: speechLog }) });
606
610
  boxes = new Boxes({ file: new JsonFile(`${dataDir}/boxes.json`, []),
607
611
  exists: (name) => all.list().some((c) => c.name === name),
608
612
  /* A long recording (a meeting): transcribed in parts, kept beside the conversation for its assistant. */
613
+ react: (said) => voice.reaction(said),
609
614
  recordDir: `${dataDir}/recordings`, parts: (wav) => voice.transcribeParts(wav), keep: (name, file, text) => talk.keepText(name, file, text),
610
615
  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) */
611
616
  /* Said as the person's own message, the room named (one speaker for now). */
package/server/speech.mjs CHANGED
@@ -44,10 +44,11 @@ export const ELEVEN_MODEL = 'eleven_multilingual_v2';
44
44
  export const SPEED = 1.1; /* a little quicker than the voices' own pace: found slow on the real box (31-10) */
45
45
 
46
46
  export class Speech {
47
- #dir; #lang; #engine = null; #loading = null; #fetch; #log; #secret;
47
+ #dir; #lang; #engine = null; #loading = null; #fetch; #log; #secret; #pocket; #pocketDown = 0;
48
48
 
49
- constructor({ dir, lang = 'fr', fetcher = fetch, log = () => {}, secret = () => undefined }) {
50
- this.#dir = dir; this.#lang = VOICES[lang] ? lang : 'fr'; this.#fetch = fetcher; this.#log = log; this.#secret = secret;
49
+ /* `pocket`: the default voice (pocket.mjs), else null. Then ElevenLabs when its key is set, then Piper. */
50
+ constructor({ dir, lang = 'fr', fetcher = fetch, log = () => {}, secret = () => undefined, pocket = null }) {
51
+ this.#dir = dir; this.#lang = VOICES[lang] ? lang : 'fr'; this.#fetch = fetcher; this.#log = log; this.#secret = secret; this.#pocket = pocket;
51
52
  }
52
53
 
53
54
  async #eleven(text) {
@@ -102,6 +103,12 @@ export class Speech {
102
103
 
103
104
  /* Text -> PCM 16 kHz. */
104
105
  async speak(text) {
106
+ /* Pocket first; failed, it rests five minutes and the next voice answers meanwhile. */
107
+ if (this.#pocket && Date.now() - this.#pocketDown > 5 * 60_000) {
108
+ try { const pcm = await this.#pocket.speak(text); if (pcm.length) return pcm; } catch (error) {
109
+ if (!/getting ready/.test(error.message)) { this.#pocketDown = Date.now(); this.#log(`speech: Pocket TTS failed (${error.message}), another voice meanwhile`); }
110
+ }
111
+ }
105
112
  const online = await this.#eleven(text);
106
113
  if (online && online.length) return online;
107
114
  const engine = await this.#load();
package/server/voice.mjs CHANGED
@@ -80,6 +80,9 @@ const PHANTOMS = [
80
80
  /sous[- ]titr(?:age|es?)\s+(?:par\s+)?(?:la\s+)?société\s+radio[- ]canada[.!]?/giu,
81
81
  /* A credit to a person, when it is all that was "heard" ("Sous-titres par Jérémy Diaz", 31-10). */
82
82
  /^\s*[Ss]ous[- ]titr(?:age|es?)(?:\s+réalisés?)?\s+par\s+(?:\p{Lu}[\p{L}'-]*\s*){1,3}[.!]?\s*$/gu,
83
+ /* YouTube endings, heard on a button press with nothing said (01-11: "Thank you for watching and see
84
+ you in the next video!"): only when they are all of it. */
85
+ /^\s*(?:thank(?:s| you) (?:so much )?for watching[.!,]?\s*(?:(?:and )?see you (?:in the |on the )?next (?:video|time)[.!]?)?|see you (?:in the )?next (?:video|time)[.!]?|merci d'avoir regardé(?: cette vidéo)?\s*[.!]?(?:\s*[àa] bient[ôo]t[.!]?)?)\s*$/giu,
83
86
  /untertitel(?:ung)?\s+(?:im\s+auftrag\s+)?des\s+zdf(?:\s+für\s+funk)?,?\s*\d{0,4}[.!]?/giu,
84
87
  ];
85
88
  export function withoutPhantoms(text) {
@@ -191,6 +194,26 @@ export async function transcribeParts(config, audio, fetcher = fetch) {
191
194
  return text ? [{ speaker: null, start: 0, text }] : [];
192
195
  }
193
196
 
197
+ /* A SHORT REACTION while the answer is thought (a voice box, 01-11): a few words in the person's language that
198
+ acknowledge what was said without answering it -- « bonne question, voyons… ». Only where the dictation's
199
+ service also offers a fast chat model (OVH AI Endpoints); null otherwise, or when it is not quick. */
200
+ export const REACTION_MODEL = 'Mistral-Small-3.2-24B-Instruct-2506';
201
+ export async function quickReaction(config, said, fetcher = fetch) {
202
+ if (!config?.key || !DIARIZES.test(String(config.url))) return null;
203
+ const base = String(config.url).replace(/\/audio\/transcriptions\/?$/, '');
204
+ try {
205
+ const r = await fetcher(`${base}/chat/completions`, {
206
+ method: 'POST', redirect: 'error', headers: { 'content-type': 'application/json', authorization: `Bearer ${config.key}` }, signal: AbortSignal.timeout(3000),
207
+ body: JSON.stringify({ model: REACTION_MODEL, temperature: 0.8, max_tokens: 24, messages: [
208
+ { role: 'system', content: 'Someone just spoke to a voice assistant, which needs a few seconds to answer. Write ONE very short spoken reaction (2 to 7 words) in the SAME language as what they said, natural and warm, that acknowledges it without answering it and without promising anything: e.g. "Bonne question, voyons…", "Ah, intéressant, je regarde.", "Hmm, let me see…". No quotes, no emoji. Answer with the reaction only.' },
209
+ { role: 'user', content: String(said).slice(0, 600) }] }),
210
+ });
211
+ if (!r.ok) return null;
212
+ const t = String((await r.json())?.choices?.[0]?.message?.content ?? '').replace(/["«»]/g, '').trim();
213
+ return t && t.length <= 60 && !/\n/.test(t) ? t : null;
214
+ } catch { return null; }
215
+ }
216
+
194
217
  /* ---------- THE ENGINE CHOSEN IN SETTINGS ----------
195
218
  * Settings > Dictation: a provider fills in the address and the model (both
196
219
  * may be changed); the key is one of the SECRETS already kept (Assets >
@@ -324,6 +347,10 @@ export class Dictation {
324
347
  /* An expired key is never sent: said in one line instead (still offered, so the line is seen). */
325
348
  #fresh(c) { if (c?.secret && this.#expired(c.secret)) throw new Refusal(409, KEY_EXPIRED); }
326
349
  /* `device`: the language of the device that dictates (a tag such as fr-FR), if it said. */
350
+ async reaction(said) {
351
+ const config = this.current();
352
+ return config ? quickReaction(config, said, this.#fetcher) : null;
353
+ }
327
354
  async transcribeParts(audio) {
328
355
  this.#fresh(this.#saved());
329
356
  const config = this.current();
package/web/app.js CHANGED
@@ -8874,6 +8874,48 @@
8874
8874
  const volRow = el('label', 'box-volume'); volRow.append('Volume ', vol, volSaid);
8875
8875
  const acts = el('div', 'action-row'); acts.append(whereRow, place, volRow, rename, remove);
8876
8876
  card.append(head, acts);
8877
+ /* ITS WI-FI NETWORKS (01-11): the box knows several and goes to the strongest it hears; one is added
8878
+ here before it moves, from the networks it hears itself -- no phone, no button. */
8879
+ if (b.online) {
8880
+ const wifi = el('div', 'box-wifi');
8881
+ const known = el('div', 'box-wifi-known');
8882
+ const add = el('button', '', 'Add a Wi-Fi'); add.type = 'button';
8883
+ const paintKnown = async () => {
8884
+ known.replaceChildren(el('small', 'hint', 'Its Wi-Fi networks…'));
8885
+ const r = await post(`${API}/boxes/${b.id}/wifi-known`, {}).catch(() => null);
8886
+ known.replaceChildren();
8887
+ if (!r) { known.append(el('small', 'hint', 'Its networks cannot be read just now.')); return; }
8888
+ for (const ssid of r.networks) {
8889
+ const chip = el('span', 'box-wifi-net', ssid === r.current ? `${ssid} (now)` : ssid);
8890
+ if (ssid !== r.current) {
8891
+ const x = el('button', 'quiet', '×'); x.type = 'button'; x.setAttribute('aria-label', `Forget ${ssid}`);
8892
+ x.addEventListener('click', async () => { await post(`${API}/boxes/${b.id}/wifi-forget`, { ssid }).catch(() => {}); await paintKnown(); });
8893
+ chip.append(x);
8894
+ }
8895
+ known.append(chip);
8896
+ }
8897
+ };
8898
+ add.addEventListener('click', async () => {
8899
+ add.disabled = true; add.textContent = 'Listening for networks…';
8900
+ const r = await post(`${API}/boxes/${b.id}/wifi-scan`, {}).catch(() => ({ networks: [] }));
8901
+ add.disabled = false; add.textContent = 'Add a Wi-Fi';
8902
+ const pick = el('select'); pick.setAttribute('aria-label', 'Network');
8903
+ for (const n of r.networks ?? []) { const o = el('option', '', `${n.ssid}${n.secure ? '' : ' (open)'}`); o.value = n.ssid; pick.append(o); }
8904
+ const pass = el('input'); pass.type = 'password'; pass.placeholder = 'Password'; pass.autocomplete = 'off'; pass.setAttribute('aria-label', 'Password of the network');
8905
+ const join = el('button', 'primary', 'Add'); join.type = 'button';
8906
+ const said = el('small', 'hint', '');
8907
+ join.addEventListener('click', async () => {
8908
+ join.disabled = true; said.textContent = 'The box tries it (up to 20 s); it comes back on its network after.';
8909
+ try { await post(`${API}/boxes/${b.id}/wifi-join`, { ssid: pick.value, password: pass.value }); said.textContent = `Added: ${pick.value}.`; form.remove(); await paintKnown(); }
8910
+ catch (error) { said.textContent = `Not joined: ${error.message}`; join.disabled = false; }
8911
+ });
8912
+ const form = el('div', 'action-row box-wifi-add'); form.append(pick, pass, join, said);
8913
+ wifi.append(form); focusField(pass);
8914
+ });
8915
+ wifi.append(el('small', 'hint', 'Wi-Fi it knows (it goes to the strongest): '), known, add);
8916
+ card.append(wifi);
8917
+ void paintKnown();
8918
+ }
8877
8919
  rows.append(card);
8878
8920
  }
8879
8921
  }
package/web/style.css CHANGED
@@ -2075,3 +2075,9 @@ body.as-dragging #assets-rows .as-row { touch-action: none; }
2075
2075
  .box-qr { width: 180px; max-width: 100%; background: #fff; border-radius: 8px; padding: 6px; }
2076
2076
  .box-qr svg { display: block; width: 100%; height: auto; }
2077
2077
  .button-link { display: inline-block; padding: 8px 12px; border-radius: 7px; background: var(--accent, #d4a64a); color: #111; font-weight: 600; text-decoration: none; }
2078
+
2079
+ /* A voice box's Wi-Fi networks: names as small chips, the one it uses marked. */
2080
+ .box-wifi { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin-top: 8px; }
2081
+ .box-wifi-known { display: flex; flex-wrap: wrap; gap: 6px; }
2082
+ .box-wifi-net { display: inline-flex; align-items: center; gap: 4px; padding: 2px 8px; border: 1px solid var(--line, #ccc); border-radius: 999px; font-size: 0.85em; }
2083
+ .box-wifi-add { width: 100%; }