clavarium 0.2.203-next.1 → 0.2.208-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.203-next.1",
3
+ "version": "0.2.208-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.203-next.1",
9
+ "version": "0.2.208-next.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.203-next.1",
3
+ "version": "0.2.208-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.",
package/server/boxes.mjs CHANGED
@@ -123,6 +123,18 @@ 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…'];
126
138
  export const DOING_WITHIN_MS = 120_000;
127
139
  /* A LONG RECORDING (a meeting, a class): asked in words, stopped by the button or the wake word. */
128
140
  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 +143,22 @@ export const mmss = (s) => `${String(Math.floor(s / 60)).padStart(2, '0')}:${Str
131
143
  /* THE MIXER of a box that plays a stream: words said meanwhile go over it, the stream lowered to DUCK while
132
144
  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
145
  export const DUCK = 0.2;
146
+ /* LEVELS (01-11): like a phone, one volume for the whole box (set, and eased to the room by the box itself),
147
+ and under it each kind of sound brought to its own steady level -- a loud radio and a quiet one played alike
148
+ (ffmpeg's loudnorm, EBU R128), the radio a step below the box's voice, its voice always at one loudness. */
149
+ export const STREAM_LUFS = -26;
150
+ export const STREAM_LEVEL = 1;
151
+ export const VOICE_RMS = 3300; /* about -20 dBFS: the loudness the voice was found right at */
152
+ export function levelled(pcm, target = VOICE_RMS) {
153
+ let sum = 0; let n = 0;
154
+ for (let i = 0; i + 1 < pcm.length; i += 2) { const v = pcm.readInt16LE(i); if (Math.abs(v) > 300) { sum += v * v; n++; } }
155
+ if (n < 100) return pcm;
156
+ const gain = Math.min(4, target / Math.sqrt(sum / n));
157
+ if (Math.abs(gain - 1) < 0.05) return pcm;
158
+ const out = Buffer.alloc(pcm.length & ~1);
159
+ 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);
160
+ return out;
161
+ }
134
162
  export function mix(stream, chunk) {
135
163
  const words = stream.over[0];
136
164
  const target = words ? DUCK : 1;
@@ -138,7 +166,7 @@ export function mix(stream, chunk) {
138
166
  const step = (1 - DUCK) / (0.25 * 16_000);
139
167
  for (let i = 0; i < chunk.length; i += 2) {
140
168
  stream.gain += Math.max(-step, Math.min(step, target - stream.gain));
141
- let v = chunk.readInt16LE(i) * stream.gain;
169
+ let v = chunk.readInt16LE(i) * stream.gain * STREAM_LEVEL;
142
170
  if (words && stream.gain <= DUCK + 0.05) {
143
171
  stream.at ??= 0;
144
172
  if (stream.at + 1 < words.length) { v += words.readInt16LE(stream.at); stream.at += 2; }
@@ -175,11 +203,12 @@ export function piecesOf(pcm, { least = 8, most = 14 } = {}) {
175
203
 
176
204
  export class Boxes {
177
205
  #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;
206
+ #exists; #hear; #say; #speak; #log; #changed; #images = new Map(); #origin; #spawn; #fetch; #streams = new Map(); #recordDir; #parts; #keep; #react;
179
207
 
180
208
  /* file: a JsonFile holding [{ id, name, conversation, keyHash, firmware, createdAt, seenAt }].
181
209
  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 }) {
210
+ 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 }) {
211
+ this.#react = react;
183
212
  this.#spawn = spawn; this.#fetch = fetcher; this.#recordDir = recordDir; this.#parts = parts; this.#keep = keep;
184
213
  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
214
  }
@@ -307,7 +336,7 @@ export class Boxes {
307
336
  this.stop(id);
308
337
  const source = await this.#resolve(url);
309
338
  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'] }); }
339
+ 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
340
  catch { throw new Refusal(501, 'This server cannot read sounds: ffmpeg is not installed (an update installs it).'); }
312
341
  const box = link.box(); const label = name || new URL(url).host;
313
342
  const stream = { child, queue: [], queued: 0, sent: 0, started: this.#now(), timer: null, ended: false, failed: '', over: [], gain: 1 };
@@ -404,6 +433,23 @@ export class Boxes {
404
433
  /* The tool said or asked something in a conversation: said aloud only by the boxes it is
405
434
  addressed to (`to`: box ids, #215). Anything else stays in the thread, silent -- a box
406
435
  read a whole technical message aloud once (31-10), which nobody wants. */
436
+ /* WHILE THE ANSWER IS THOUGHT (01-11): no long silence after a sentence. A short « hmm » if nothing has
437
+ come after a little while, then a word that it takes longer; whatever the assistant says first (an answer,
438
+ what it is doing) ends the wait. A longer question (many words) is told sooner that it takes a moment. */
439
+ #waitFor(link, text = '') {
440
+ clearTimeout(link.thinkingA); clearTimeout(link.thinkingB);
441
+ const said = link.heardAt;
442
+ const still = () => link.heardAt === said && !((link.answeredAt ?? 0) >= said);
443
+ const long = String(text).length > 160; /* a long question: told sooner that it takes a moment */
444
+ 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 */ } };
445
+ /* Made at once, used if the answer is still not there: a reaction to THIS sentence, in its language. */
446
+ let made = null;
447
+ this.#react(text).then((t) => { made = t; }).catch(() => {});
448
+ link.thinkingA = setTimeout(() => { void say(made || THINKING[Math.floor(Math.random() * THINKING.length)]); }, THINKING_AFTER_MS);
449
+ 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);
450
+ link.thinkingA.unref?.(); link.thinkingB.unref?.();
451
+ }
452
+
407
453
  async agentSaid(conversation, text, to = null, { doing = false, asked = false } = {}) {
408
454
  /* What it is doing is written for a screen ("Tâche de fond : bêta 0.2.113…"): read aloud, it was words
409
455
  from nowhere (31-10). Aloud, only a short plain one; otherwise a word that it is at work. */
@@ -424,6 +470,7 @@ export class Boxes {
424
470
  asked for ("mode conversation"), or by itself after two sentences within three minutes (31-10);
425
471
  it ends when nobody answers, or on "fin de la conversation". */
426
472
  const question = !doing && (asked || /\?\s*$/.test(words));
473
+ for (const l of boxes) { l.answeredAt = this.#now(); clearTimeout(l.thinkingA); clearTimeout(l.thinkingB); }
427
474
  for (const l of boxes) {
428
475
  /* An answer -- to a sentence heard within a minute -- may open the conversation; something said
429
476
  of itself (a news item, a reminder) does not: the box listened after it for nothing (31-10). */
@@ -431,9 +478,16 @@ export class Boxes {
431
478
  const chatting = !doing && answering && this.#chatting(l);
432
479
  const opening = chatting && !l.chat;
433
480
  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 */
481
+ /* SENTENCE BY SENTENCE: the first is said while the next ones are made -- the answer starts sooner
482
+ (31-10: a few seconds of silence before each answer). The box queues them, one after the other. */
483
+ const parts = sentencesOf(opening ? `Je passe en mode conversation : je reste à l'écoute. ${words}` : words);
484
+ let next = this.#speak(parts[0]);
485
+ for (const [i, part] of parts.entries()) {
486
+ let pcm;
487
+ try { pcm = await next; } catch (error) { this.#log(`voice box: no voice for the answer (${error.message})`); l.send({ t: 'cue', name: 'error' }); break; }
488
+ if (i + 1 < parts.length) { next = this.#speak(parts[i + 1]); next.catch(() => {}); }
489
+ l.play(pcm, i + 1 === parts.length && (question || chatting) ? 'listen' : null); /* a question is always listened after: an answer is expected */
490
+ }
437
491
  }
438
492
  }
439
493
  #chatting(link) {
@@ -451,7 +505,7 @@ export class Boxes {
451
505
  socket, send, waiting: new Map(), heardAt: 0, muted: null, volume: null,
452
506
  box: () => this.#all().find((b) => b.id === box.id) ?? box,
453
507
  play: (pcm, then = null) => {
454
- pcm = pcm.subarray(0, pcm.length & ~1); /* whole samples only: an odd byte shifts every sample after it */
508
+ 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
509
  /* Something is playing (a radio): the words go over it, the radio lowered meanwhile (the mixer, listen()). */
456
510
  const playing = this.#streams.get(box.id);
457
511
  if (playing) { playing.over.push(pcm); return; }
@@ -601,6 +655,7 @@ export class Boxes {
601
655
  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; }
602
656
  this.#log(`voice box ${box.name}: ${seconds} s heard, said in ${box.conversation}`);
603
657
  link.heardAt = this.#now();
658
+ this.#waitFor(link, text);
604
659
  link.recent = [...(link.recent ?? []), link.heardAt];
605
660
  if (/\bmode conversation\b/i.test(text)) link.chat = true;
606
661
  if (/\b(?:fin|arr[eê]te|stop)\w*\b.{0,20}\b(?:conversation|[ée]couter)\b/i.test(text)) { link.chat = false; link.recent = []; }
package/server/main.mjs CHANGED
@@ -606,6 +606,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
606
606
  boxes = new Boxes({ file: new JsonFile(`${dataDir}/boxes.json`, []),
607
607
  exists: (name) => all.list().some((c) => c.name === name),
608
608
  /* A long recording (a meeting): transcribed in parts, kept beside the conversation for its assistant. */
609
+ react: (said) => voice.reaction(said),
609
610
  recordDir: `${dataDir}/recordings`, parts: (wav) => voice.transcribeParts(wav), keep: (name, file, text) => talk.keepText(name, file, text),
610
611
  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
612
  /* Said as the person's own message, the room named (one speaker for now). */
package/server/voice.mjs CHANGED
@@ -191,6 +191,26 @@ export async function transcribeParts(config, audio, fetcher = fetch) {
191
191
  return text ? [{ speaker: null, start: 0, text }] : [];
192
192
  }
193
193
 
194
+ /* A SHORT REACTION while the answer is thought (a voice box, 01-11): a few words in the person's language that
195
+ acknowledge what was said without answering it -- « bonne question, voyons… ». Only where the dictation's
196
+ service also offers a fast chat model (OVH AI Endpoints); null otherwise, or when it is not quick. */
197
+ export const REACTION_MODEL = 'Mistral-Small-3.2-24B-Instruct-2506';
198
+ export async function quickReaction(config, said, fetcher = fetch) {
199
+ if (!config?.key || !DIARIZES.test(String(config.url))) return null;
200
+ const base = String(config.url).replace(/\/audio\/transcriptions\/?$/, '');
201
+ try {
202
+ const r = await fetcher(`${base}/chat/completions`, {
203
+ method: 'POST', redirect: 'error', headers: { 'content-type': 'application/json', authorization: `Bearer ${config.key}` }, signal: AbortSignal.timeout(3000),
204
+ body: JSON.stringify({ model: REACTION_MODEL, temperature: 0.8, max_tokens: 24, messages: [
205
+ { 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.' },
206
+ { role: 'user', content: String(said).slice(0, 600) }] }),
207
+ });
208
+ if (!r.ok) return null;
209
+ const t = String((await r.json())?.choices?.[0]?.message?.content ?? '').replace(/["«»]/g, '').trim();
210
+ return t && t.length <= 60 && !/\n/.test(t) ? t : null;
211
+ } catch { return null; }
212
+ }
213
+
194
214
  /* ---------- THE ENGINE CHOSEN IN SETTINGS ----------
195
215
  * Settings > Dictation: a provider fills in the address and the model (both
196
216
  * may be changed); the key is one of the SECRETS already kept (Assets >
@@ -324,6 +344,10 @@ export class Dictation {
324
344
  /* An expired key is never sent: said in one line instead (still offered, so the line is seen). */
325
345
  #fresh(c) { if (c?.secret && this.#expired(c.secret)) throw new Refusal(409, KEY_EXPIRED); }
326
346
  /* `device`: the language of the device that dictates (a tag such as fr-FR), if it said. */
347
+ async reaction(said) {
348
+ const config = this.current();
349
+ return config ? quickReaction(config, said, this.#fetcher) : null;
350
+ }
327
351
  async transcribeParts(audio) {
328
352
  this.#fresh(this.#saved());
329
353
  const config = this.current();