clavarium 0.2.201-next.1 → 0.2.206-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.201-next.1",
3
+ "version": "0.2.206-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.201-next.1",
9
+ "version": "0.2.206-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.45",
17
+ "clavarium-tether": "0.1.0-next.46",
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.45",
764
- "resolved": "https://registry.npmjs.org/clavarium-tether/-/clavarium-tether-0.1.0-next.45.tgz",
765
- "integrity": "sha512-3lZT2MHeQWcfF8241K2+N+/ZX8wluFe0HqlrUPbTgSMws+RqQh61mEzk0Z9vlHSoG5aGhQ5b8CwK1QqBwGp9nQ==",
763
+ "version": "0.1.0-next.46",
764
+ "resolved": "https://registry.npmjs.org/clavarium-tether/-/clavarium-tether-0.1.0-next.46.tgz",
765
+ "integrity": "sha512-p6B9kM1A4CUN/OyLWf5IpsKvQ5SiTir7P+X2BcnRQBml+S9z/1nS0Xs7vxhk4ekDui/x0Dh5xMOO4IvaCLhaeA==",
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.201-next.1",
3
+ "version": "0.2.206-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.45",
50
+ "clavarium-tether": "0.1.0-next.46",
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
@@ -86,8 +86,8 @@ export function pcmOfWav(wav) {
86
86
  }
87
87
 
88
88
  /* Text for the ear: what a written message holds and a voice should not read. */
89
- export function forSpeech(text) {
90
- return String(text ?? '')
89
+ export function forSpeech(text, { callOthers = false } = {}) {
90
+ const said = String(text ?? '')
91
91
  .replace(/```[\s\S]*?```/g, ' ')
92
92
  .replace(/`([^`]*)`/g, '$1')
93
93
  .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
@@ -99,11 +99,12 @@ export function forSpeech(text) {
99
99
  .replace(/\b(?:hey|hé|eh)[\s,]+jarvis\b/giu, 'le mot d\'éveil')
100
100
  .replace(/(?<![\p{L}])m[ée]sanges?(?![\p{L}])/giu, 'le mot d\'éveil')
101
101
  .replace(/(?<![\p{L}])m[eéè]s[\s-]+anges?(?![\p{L}])/giu, 'le mot d\'éveil') /* what sounds like it: « mes anges » woke it (31-10) */
102
- /* Nor another assistant's call: « OK Google » said in an example woke the Google Home beside it (31-10). */
103
- .replace(/\b(?:ok|okay|hey|dis)[\s,]+(?:google|siri|alexa)\b/giu, 'l\'appel de l\'enceinte')
104
102
  .replace(/\s+/g, ' ')
105
103
  .trim()
106
104
  .slice(0, 1500);
105
+ /* Nor another assistant's call: « OK Google » said in an example woke the Google Home beside it (31-10).
106
+ Only speakTo() calls it, on purpose. */
107
+ return callOthers ? said : said.replace(/\b(?:ok|okay|hey|dis)[\s,]+(?:google|siri|alexa)\b/giu, 'l\'appel de l\'enceinte');
107
108
  }
108
109
 
109
110
  /* THE BOX'S CLOCK: its lights follow the hours of its place. The time zone is the page's that made its code
@@ -121,6 +122,16 @@ export function offsetOf(zone, now) {
121
122
  return Math.round((local - Math.floor(now / 60_000) * 60_000) / 60_000);
122
123
  }
123
124
 
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
+
124
135
  export const DOING_WITHIN_MS = 120_000;
125
136
  /* A LONG RECORDING (a meeting, a class): asked in words, stopped by the button or the wake word. */
126
137
  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;
@@ -129,6 +140,22 @@ export const mmss = (s) => `${String(Math.floor(s / 60)).padStart(2, '0')}:${Str
129
140
  /* THE MIXER of a box that plays a stream: words said meanwhile go over it, the stream lowered to DUCK while
130
141
  they last, with a fade down and up (a quarter of a second) rather than a jump. One 20 ms chunk at a time. */
131
142
  export const DUCK = 0.2;
143
+ /* LEVELS (01-11): like a phone, one volume for the whole box (set, and eased to the room by the box itself),
144
+ and under it each kind of sound brought to its own steady level -- a loud radio and a quiet one played alike
145
+ (ffmpeg's loudnorm, EBU R128), the radio a step below the box's voice, its voice always at one loudness. */
146
+ export const STREAM_LUFS = -26;
147
+ export const STREAM_LEVEL = 1;
148
+ export const VOICE_RMS = 3300; /* about -20 dBFS: the loudness the voice was found right at */
149
+ export function levelled(pcm, target = VOICE_RMS) {
150
+ let sum = 0; let n = 0;
151
+ for (let i = 0; i + 1 < pcm.length; i += 2) { const v = pcm.readInt16LE(i); if (Math.abs(v) > 300) { sum += v * v; n++; } }
152
+ if (n < 100) return pcm;
153
+ const gain = Math.min(4, target / Math.sqrt(sum / n));
154
+ if (Math.abs(gain - 1) < 0.05) return pcm;
155
+ const out = Buffer.alloc(pcm.length & ~1);
156
+ 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);
157
+ return out;
158
+ }
132
159
  export function mix(stream, chunk) {
133
160
  const words = stream.over[0];
134
161
  const target = words ? DUCK : 1;
@@ -136,7 +163,7 @@ export function mix(stream, chunk) {
136
163
  const step = (1 - DUCK) / (0.25 * 16_000);
137
164
  for (let i = 0; i < chunk.length; i += 2) {
138
165
  stream.gain += Math.max(-step, Math.min(step, target - stream.gain));
139
- let v = chunk.readInt16LE(i) * stream.gain;
166
+ let v = chunk.readInt16LE(i) * stream.gain * STREAM_LEVEL;
140
167
  if (words && stream.gain <= DUCK + 0.05) {
141
168
  stream.at ??= 0;
142
169
  if (stream.at + 1 < words.length) { v += words.readInt16LE(stream.at); stream.at += 2; }
@@ -282,6 +309,20 @@ export class Boxes {
282
309
  return this.#images.get(String(token).replace(/\.bin$/, ''))?.bytes;
283
310
  }
284
311
 
312
+ /* SPEAKING TO ANOTHER DEVICE in the room (a Google Home: « OK Google, baisse la clim »): said as given, its
313
+ call included, then the box listens; what it hears within twenty seconds comes back to the conversation as
314
+ that device's answer, not as the person's words (31-10: the box set the heating that way). */
315
+ async speakTo(id, text) {
316
+ const link = this.#links.get(id);
317
+ if (!link) throw new Refusal(409, 'This voice box is not connected.');
318
+ const words = forSpeech(text, { callOthers: true });
319
+ if (!words) throw new Refusal(400, 'Nothing to say.');
320
+ link.play(await this.#speak(words), 'listen');
321
+ link.relay = this.#now();
322
+ this.#log(`voice box ${link.box().name}: spoke to a device in the room`);
323
+ return { ok: true };
324
+ }
325
+
285
326
  /* LISTENING TO THE INTERNET: a radio, a podcast, a music file, a playlist, read by this server (ffmpeg,
286
327
  any format it knows) and sent on to the box at the pace it is played, a few seconds ahead -- until it
287
328
  ends, stop(), or the person presses the button or says the wake word (the box then starts a sentence). */
@@ -291,7 +332,7 @@ export class Boxes {
291
332
  this.stop(id);
292
333
  const source = await this.#resolve(url);
293
334
  let child;
294
- 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'] }); }
335
+ 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'] }); }
295
336
  catch { throw new Refusal(501, 'This server cannot read sounds: ffmpeg is not installed (an update installs it).'); }
296
337
  const box = link.box(); const label = name || new URL(url).host;
297
338
  const stream = { child, queue: [], queued: 0, sent: 0, started: this.#now(), timer: null, ended: false, failed: '', over: [], gain: 1 };
@@ -415,9 +456,16 @@ export class Boxes {
415
456
  const chatting = !doing && answering && this.#chatting(l);
416
457
  const opening = chatting && !l.chat;
417
458
  if (chatting) l.chat = true;
418
- let pcm;
419
- 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; }
420
- l.play(pcm, question || chatting ? 'listen' : null); /* a question is always listened after: an answer is expected */
459
+ /* SENTENCE BY SENTENCE: the first is said while the next ones are made -- the answer starts sooner
460
+ (31-10: a few seconds of silence before each answer). The box queues them, one after the other. */
461
+ const parts = sentencesOf(opening ? `Je passe en mode conversation : je reste à l'écoute. ${words}` : words);
462
+ let next = this.#speak(parts[0]);
463
+ for (const [i, part] of parts.entries()) {
464
+ let pcm;
465
+ try { pcm = await next; } catch (error) { this.#log(`voice box: no voice for the answer (${error.message})`); l.send({ t: 'cue', name: 'error' }); break; }
466
+ if (i + 1 < parts.length) { next = this.#speak(parts[i + 1]); next.catch(() => {}); }
467
+ l.play(pcm, i + 1 === parts.length && (question || chatting) ? 'listen' : null); /* a question is always listened after: an answer is expected */
468
+ }
421
469
  }
422
470
  }
423
471
  #chatting(link) {
@@ -435,7 +483,7 @@ export class Boxes {
435
483
  socket, send, waiting: new Map(), heardAt: 0, muted: null, volume: null,
436
484
  box: () => this.#all().find((b) => b.id === box.id) ?? box,
437
485
  play: (pcm, then = null) => {
438
- pcm = pcm.subarray(0, pcm.length & ~1); /* whole samples only: an odd byte shifts every sample after it */
486
+ pcm = levelled(pcm.subarray(0, pcm.length & ~1)); /* whole samples only (an odd byte shifts every sample after it), at the voice's level */
439
487
  /* Something is playing (a radio): the words go over it, the radio lowered meanwhile (the mixer, listen()). */
440
488
  const playing = this.#streams.get(box.id);
441
489
  if (playing) { playing.over.push(pcm); return; }
@@ -578,6 +626,10 @@ export class Boxes {
578
626
  link.send({ t: 'record', on: true });
579
627
  return;
580
628
  }
629
+ if (link.relay && this.#now() - link.relay < RELAY_WITHIN_MS) {
630
+ link.relay = 0;
631
+ text = `(réponse entendue de l'appareil, pas de la personne) ${text}`;
632
+ }
581
633
  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; }
582
634
  this.#log(`voice box ${box.name}: ${seconds} s heard, said in ${box.conversation}`);
583
635
  link.heardAt = this.#now();
@@ -668,6 +720,7 @@ export function voiceboxConnector(boxes) {
668
720
  const id = t.config?.box;
669
721
  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}.` }; }
670
722
  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.` }; }
723
+ if (verb === 'voicebox.speak') { await boxes.speakTo(id, String(a.text ?? '')); return { text: 'Said aloud; the box listens now: what it hears in the next 20 s comes back in the conversation, marked as the device\'s answer.' }; }
671
724
  if (verb === 'voicebox.stop') return { text: boxes.stop(id) ? 'Stopped.' : 'Nothing was playing.' };
672
725
  if (verb === 'voicebox.play') { const r = boxes.play(id, Buffer.from(String(a.image ?? ''), 'base64')); return { text: `Played (${r.seconds} s).` }; }
673
726
  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.` }; }