clavarium 0.2.114-beta.1 → 0.2.115-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.
@@ -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
 
@@ -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}`); }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.114-beta.1",
3
+ "version": "0.2.115-beta.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.114-beta.1",
9
+ "version": "0.2.115-beta.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.43",
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.43",
764
- "resolved": "https://registry.npmjs.org/clavarium-tether/-/clavarium-tether-0.1.0-next.43.tgz",
765
- "integrity": "sha512-vAoj19cWZiXMpDkRnhV1P+oNWv6dGL65eur/2PbxNiP5i9uWI5tipRoQfnff5Xkqd5o+E4vbRnWvzlHAJTTX5A==",
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.114-beta.1",
3
+ "version": "0.2.115-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.",
@@ -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.43",
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
@@ -17,6 +17,7 @@
17
17
  * device door. Nothing is kept of the audio, here or on the box.
18
18
  */
19
19
  import { spawn as spawnProcess } from 'node:child_process';
20
+ import { createWriteStream, mkdirSync, readFileSync, rmSync, statSync } from 'node:fs';
20
21
  import { randomBytes, randomUUID, createHash, timingSafeEqual } from 'node:crypto';
21
22
  import { Refusal } from './conversations.mjs';
22
23
 
@@ -26,7 +27,7 @@ export const LINK_PATH = '/c/api/box/ws';
26
27
  /* A firmware a box downloads to update itself: a one-use address, kept a few minutes. */
27
28
  export const FIRMWARE_PATH = '/c/api/box/firmware/';
28
29
  export const FIRMWARE_MINUTES = 10;
29
- export const SENTENCE_MAX = 60 * 32_000 + 32_000; /* 60 s of 16 kHz 16-bit mono, and some slack */
30
+ export const SENTENCE_MAX = 300 * 32_000 + 32_000; /* 5 min of 16 kHz 16-bit mono, and some slack */
30
31
  export const TRIES_PER_MINUTE = 10;
31
32
  export const NAME_MAX = 40;
32
33
  /* The volume a box is given when it connects, until someone sets another (its own default was soft). */
@@ -102,6 +103,31 @@ export function forSpeech(text) {
102
103
  }
103
104
 
104
105
  export const DOING_WITHIN_MS = 120_000;
106
+ /* A LONG RECORDING (a meeting, a class): asked in words, stopped by the button or the wake word. */
107
+ 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;
108
+ export const RECORD_MAX_BYTES = 4 * 3600 * 32_000; /* four hours */
109
+ export const mmss = (s) => `${String(Math.floor(s / 60)).padStart(2, '0')}:${String(Math.floor(s % 60)).padStart(2, '0')}`;
110
+ /* THE MIXER of a box that plays a stream: words said meanwhile go over it, the stream lowered to DUCK while
111
+ they last, with a fade down and up (a quarter of a second) rather than a jump. One 20 ms chunk at a time. */
112
+ export const DUCK = 0.2;
113
+ export function mix(stream, chunk) {
114
+ const words = stream.over[0];
115
+ const target = words ? DUCK : 1;
116
+ const out = Buffer.alloc(chunk.length);
117
+ const step = (1 - DUCK) / (0.25 * 16_000);
118
+ for (let i = 0; i < chunk.length; i += 2) {
119
+ stream.gain += Math.max(-step, Math.min(step, target - stream.gain));
120
+ let v = chunk.readInt16LE(i) * stream.gain;
121
+ if (words && stream.gain <= DUCK + 0.05) {
122
+ stream.at ??= 0;
123
+ if (stream.at + 1 < words.length) { v += words.readInt16LE(stream.at); stream.at += 2; }
124
+ }
125
+ out.writeInt16LE(Math.max(-32768, Math.min(32767, Math.round(v))), i);
126
+ }
127
+ if (words && stream.at + 1 >= words.length) { stream.over.shift(); stream.at = 0; }
128
+ return out;
129
+ }
130
+
105
131
  export const CHAT_WITHIN_MS = 3 * 60_000;
106
132
  export const LISTEN_AHEAD = 3 * 32_000; /* bytes: what a box is sent ahead of what it plays (its buffer holds 16 s) */
107
133
 
@@ -127,12 +153,12 @@ export function piecesOf(pcm, { least = 8, most = 14 } = {}) {
127
153
 
128
154
  export class Boxes {
129
155
  #file; #codes = new Map(); #links = new Map(); #tries = []; #now;
130
- #exists; #hear; #say; #speak; #log; #changed; #images = new Map(); #origin; #spawn; #fetch; #streams = new Map();
156
+ #exists; #hear; #say; #speak; #log; #changed; #images = new Map(); #origin; #spawn; #fetch; #streams = new Map(); #recordDir; #parts; #keep;
131
157
 
132
158
  /* file: a JsonFile holding [{ id, name, conversation, keyHash, firmware, createdAt, seenAt }].
133
159
  exists(conversation), hear(wav) -> text, say(conversation, text, room), speak(text) -> PCM 16 kHz. */
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;
160
+ constructor({ file, exists = () => true, hear, say, speak, changed = () => {}, origin = () => null, now = () => Date.now(), log = () => {}, spawn = spawnProcess, fetcher = fetch, recordDir = null, parts = null, keep = null }) {
161
+ this.#spawn = spawn; this.#fetch = fetcher; this.#recordDir = recordDir; this.#parts = parts; this.#keep = keep;
136
162
  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;
137
163
  }
138
164
 
@@ -247,7 +273,7 @@ export class Boxes {
247
273
  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
274
  catch { throw new Refusal(501, 'This server cannot read sounds: ffmpeg is not installed (an update installs it).'); }
249
275
  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: '' };
276
+ const stream = { child, queue: [], queued: 0, sent: 0, started: this.#now(), timer: null, ended: false, failed: '', over: [], gain: 1 };
251
277
  this.#streams.set(id, stream);
252
278
  link.send({ t: 'speak.start', rate: 16_000 });
253
279
  child.stdout.on('data', (d) => { stream.queue.push(d); stream.queued += d.length; if (stream.queued > LISTEN_AHEAD * 4) child.stdout.pause(); });
@@ -260,7 +286,7 @@ export class Boxes {
260
286
  const due = (this.#now() - stream.started) * 32 + LISTEN_AHEAD; /* bytes the box should have by now, a few seconds ahead */
261
287
  while (stream.sent + 640 <= due && (carry.length >= 640 || stream.queue.length)) {
262
288
  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));
289
+ if (link.socket.readyState === 1) link.socket.send(mix(stream, carry.subarray(0, 640)));
264
290
  carry = carry.subarray(640); stream.sent += 640;
265
291
  }
266
292
  if (stream.queued < LISTEN_AHEAD) child.stdout.resume();
@@ -379,6 +405,10 @@ export class Boxes {
379
405
  socket, send, waiting: new Map(), heardAt: 0, muted: null, volume: null,
380
406
  box: () => this.#all().find((b) => b.id === box.id) ?? box,
381
407
  play: (pcm, then = null) => {
408
+ pcm = pcm.subarray(0, pcm.length & ~1); /* whole samples only: an odd byte shifts every sample after it */
409
+ /* Something is playing (a radio): the words go over it, the radio lowered meanwhile (the mixer, listen()). */
410
+ const playing = this.#streams.get(box.id);
411
+ if (playing) { playing.over.push(pcm); return; }
382
412
  send({ t: 'speak.start', rate: 16_000 });
383
413
  for (let at = 0; at < pcm.length; at += 640) if (socket.readyState === 1) socket.send(pcm.subarray(at, at + 640));
384
414
  send({ t: 'speak.end', ...(then ? { then } : {}) });
@@ -391,6 +421,12 @@ export class Boxes {
391
421
  seen();
392
422
  socket.on('message', (data, binary) => {
393
423
  if (binary) {
424
+ if (link.recording) {
425
+ const r = link.recording;
426
+ if (r.bytes + data.length > RECORD_MAX_BYTES) { if (!r.full) { r.full = true; send({ t: 'record', on: false }); } return; }
427
+ r.out.write(data); r.bytes += data.length;
428
+ return;
429
+ }
394
430
  if (!sentence || link.muted) return;
395
431
  size += data.length;
396
432
  if (size <= SENTENCE_MAX) sentence.push(Buffer.from(data));
@@ -407,6 +443,18 @@ export class Boxes {
407
443
  if (m.volume !== wanted) { send({ t: 'volume', id: randomUUID(), level: wanted }); m.volume = wanted; }
408
444
  }
409
445
  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; }
446
+ if (m.t === 'record.start' && this.#recordDir) {
447
+ mkdirSync(this.#recordDir, { recursive: true });
448
+ const file = `${this.#recordDir}/${box.id}-${this.#now()}.pcm`;
449
+ link.recording = { file, out: createWriteStream(file), bytes: 0, at: this.#now() };
450
+ this.#log(`voice box ${box.name}: recording`);
451
+ return;
452
+ }
453
+ if (m.t === 'record.end' && link.recording) {
454
+ const r = link.recording; link.recording = null;
455
+ r.out.end(() => { void this.#recorded(link, r); });
456
+ return;
457
+ }
410
458
  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
459
  if (m.t === 'listen.end' && sentence && m.reason === 'nobody') {
412
460
  /* Listened again, nobody spoke: a conversation ends there, in silence. */
@@ -429,10 +477,40 @@ export class Boxes {
429
477
  }
430
478
  if ((m.t === 'ack' || m.t === 'wifi.scan.result') && typeof m.id === 'string') { link.waiting.get(m.id)?.(m); link.waiting.delete(m.id); }
431
479
  });
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`); } });
480
+ socket.on('close', () => { if (link.recording) { const r = link.recording; link.recording = null; r.out.end(() => { void this.#recorded(link, r); }); }
481
+ if (this.#links.get(box.id) === link) { this.stop(box.id); this.#links.delete(box.id); this.#log(`voice box ${box.name}: disconnected`); } });
433
482
  socket.on('error', () => {});
434
483
  }
435
484
 
485
+ /* A recording ended: transcribed in parts of five minutes (cut at a quiet moment), who speaks noted when the
486
+ engine tells voices apart; the text kept beside the conversation, and said there in a short line, so its
487
+ assistant writes what was asked of it. The sound itself is not kept. */
488
+ async #recorded(link, r) {
489
+ const box = link.box();
490
+ const minutes = Math.round(r.bytes / 32_000 / 60);
491
+ this.#log(`voice box ${box.name}: recording ended, ${minutes} min, transcribing`);
492
+ try { if (link.socket.readyState === 1) link.play(await this.#speak(`Enregistrement terminé, ${minutes} minute${minutes > 1 ? 's' : ''}. Je transcris, je te dis quand c'est prêt.`)); } catch { /* the light says it */ }
493
+ let pcm;
494
+ try { pcm = readFileSync(r.file); } catch (error) { this.#log(`voice box ${box.name}: the recording cannot be read (${error.message})`); return; }
495
+ const lines = []; let offset = 0; let failed = 0;
496
+ const pieces = piecesOf(pcm, { least: 270, most: 300 });
497
+ for (const [i, piece] of pieces.entries()) {
498
+ try {
499
+ const parts = await this.#parts(wavOf(piece));
500
+ for (const p of parts) lines.push(`[${mmss(offset + p.start)}]${p.speaker === null ? '' : ` Voix ${p.speaker + 1}${pieces.length > 1 ? ` (partie ${i + 1})` : ''}`} : ${p.text}`);
501
+ } catch (error) { failed++; lines.push(`[${mmss(offset)}] (cette partie n'a pas pu être transcrite : ${error.message})`); }
502
+ offset += piece.length / 32_000;
503
+ }
504
+ rmSync(r.file, { force: true });
505
+ const stamp = new Date(r.at).toISOString().slice(0, 16).replace(/[-:T]/g, '');
506
+ const head = `Enregistrement du boîtier ${box.name}${box.place ? ` (${box.place})` : ''}, ${new Date(r.at).toISOString().slice(0, 16).replace('T', ' ')} UTC, ${minutes} min.\nLes voix sont numérotées par partie de 5 minutes : une même personne peut changer de numéro d'une partie à l'autre.\n\n`;
507
+ let path = null;
508
+ try { path = this.#keep?.(box.conversation, `enregistrement-${stamp}.txt`, head + lines.join('\n')) ?? null; } catch (error) { this.#log(`voice box ${box.name}: the transcript cannot be kept (${error.message})`); }
509
+ this.#log(`voice box ${box.name}: recording transcribed (${lines.length} lines${failed ? `, ${failed} part(s) failed` : ''})`);
510
+ const note = path ? `Enregistrement de ${minutes} min terminé et transcrit (qui parle, minute par minute) : ${path}. Fais-en ce que la personne demande ; sinon un compte rendu court : sujets, décisions, choses à faire.` : `Enregistrement de ${minutes} min terminé, mais la transcription n'a pas pu être rangée.`;
511
+ try { await this.#say(box.conversation, note, { id: box.id, name: box.name, ...(box.place ? { place: box.place } : {}) }); } catch (error) { this.#log(`voice box ${box.name}: the recording's line not said (${error.message})`); }
512
+ }
513
+
436
514
  /* Each step said in the server's log, never what was said: its length only. */
437
515
  async #heard(link, pcm) {
438
516
  const box0 = link.box();
@@ -451,6 +529,12 @@ export class Boxes {
451
529
  } 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; }
452
530
  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; }
453
531
  const box = link.box();
532
+ if (RECORD_ASKED.test(text) && this.#recordDir && this.#parts) {
533
+ this.#log(`voice box ${box.name}: a recording asked`);
534
+ 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 */ }
535
+ link.send({ t: 'record', on: true });
536
+ return;
537
+ }
454
538
  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; }
455
539
  this.#log(`voice box ${box.name}: ${seconds} s heard, said in ${box.conversation}`);
456
540
  link.heardAt = this.#now();
package/server/main.mjs CHANGED
@@ -605,6 +605,8 @@ 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
+ /* A long recording (a meeting): transcribed in parts, kept beside the conversation for its assistant. */
609
+ recordDir: `${dataDir}/recordings`, parts: (wav) => voice.transcribeParts(wav), keep: (name, file, text) => talk.keepText(name, file, text),
608
610
  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
611
  /* Said as the person's own message, the room named (one speaker for now). */
610
612
  say: (name, text, by) => talk.say(name, text, undefined, undefined, 'voice', { by }),
package/server/voice.mjs CHANGED
@@ -167,6 +167,30 @@ export async function transcribe(config, audio, fetcher = fetch, { oneVoice = fa
167
167
  return cleanDictation((oneVoice && firstVoice(body)) || body.text, wavSeconds(audio));
168
168
  }
169
169
 
170
+ /* A LONG RECORDING, in parts of a few minutes (a voice box records a meeting): each part's text, with who
171
+ speaks when the engine tells voices apart (OVH: diarize). Parts up to 24 MB: what the engines take. */
172
+ export const PART_MAX = 24 * 1024 * 1024;
173
+ export async function transcribeParts(config, audio, fetcher = fetch) {
174
+ if (!config) throw new Refusal(503, 'No speech-to-text engine is configured.');
175
+ if (audio.length > PART_MAX) throw new Refusal(413, 'The part is too long.');
176
+ const diarize = DIARIZES.test(String(config.url));
177
+ const form = new FormData();
178
+ form.append('file', new Blob([audio], { type: 'audio/wav' }), 'recording.wav');
179
+ form.append('model', config.model);
180
+ if (config.language) form.append('language', config.language);
181
+ form.append('response_format', diarize ? 'verbose_json' : 'json');
182
+ if (diarize) form.append('diarize', 'true');
183
+ let response;
184
+ try { response = await fetcher(config.url, { method: 'POST', redirect: 'error', headers: config.key ? { authorization: `Bearer ${config.key}` } : {}, body: form, signal: AbortSignal.timeout(10 * 60_000) }); }
185
+ catch { throw new Refusal(502, 'The speech-to-text engine cannot be reached.'); }
186
+ if (!response.ok) throw new Refusal(502, `The speech-to-text engine answered ${response.status}.`);
187
+ const body = await response.json().catch(() => undefined);
188
+ if (Array.isArray(body?.diarization) && body.diarization.length) return body.diarization.map((p) => ({ speaker: Number(p.speaker) || 0, start: Number(p.start) || 0, text: withoutPhantoms(String(p.text ?? '')) })).filter((p) => p.text);
189
+ if (typeof body?.text !== 'string') throw new Refusal(502, 'The speech-to-text engine gave no text.');
190
+ const text = withoutPhantoms(body.text);
191
+ return text ? [{ speaker: null, start: 0, text }] : [];
192
+ }
193
+
170
194
  /* ---------- THE ENGINE CHOSEN IN SETTINGS ----------
171
195
  * Settings > Dictation: a provider fills in the address and the model (both
172
196
  * may be changed); the key is one of the SECRETS already kept (Assets >
@@ -300,6 +324,12 @@ export class Dictation {
300
324
  /* An expired key is never sent: said in one line instead (still offered, so the line is seen). */
301
325
  #fresh(c) { if (c?.secret && this.#expired(c.secret)) throw new Refusal(409, KEY_EXPIRED); }
302
326
  /* `device`: the language of the device that dictates (a tag such as fr-FR), if it said. */
327
+ async transcribeParts(audio) {
328
+ this.#fresh(this.#saved());
329
+ const config = this.current();
330
+ if (config) await this.#guard(config);
331
+ return transcribeParts(config && { ...config, language: languageOf(config.language, undefined) }, audio, this.#fetcher);
332
+ }
303
333
  async transcribe(audio, device, how = {}) {
304
334
  this.#fresh(this.#saved());
305
335
  const config = this.current();