clavarium 0.2.112-beta.1 → 0.2.113-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.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.112-beta.1",
3
+ "version": "0.2.113-beta.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.112-beta.1",
9
+ "version": "0.2.113-beta.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.112-beta.1",
3
+ "version": "0.2.113-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.",
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
- const then = !doing && (asked || /\?\s*$/.test(words)) ? 'listen' : null;
270
- let pcm;
271
- try { pcm = await this.#speak(words); } catch (error) { this.#log(`voice box: no voice for the answer (${error.message})`); for (const l of boxes) l.send({ t: 'cue', name: 'error' }); return; }
272
- for (const l of boxes) l.play(pcm, then);
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 { text = String(await this.#hear(wavOf(pcm)) ?? '').trim(); } 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; }
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.' }; }