clavarium 0.2.210-next.1 → 0.2.214-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.
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,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.210-next.1",
3
+ "version": "0.2.214-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.210-next.1",
9
+ "version": "0.2.214-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.210-next.1",
3
+ "version": "0.2.214-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/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,7 +603,10 @@ 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. */
@@ -0,0 +1,128 @@
1
+ /* THE VOICE BY DEFAULT: Kyutai's Pocket TTS (chosen by ear on the real box, 01-11, over Piper, Kokoro and
2
+ * ElevenLabs' free credits). Open: its program is MIT, its weights CC-BY-4.0 -- Kyutai is credited
3
+ * (docs/CREDITS). Runs on this server, nothing sent anywhere: the program is fetched once from Kyutai's
4
+ * releases (its sha256 checked), its French model once from Hugging Face, then it serves on loopback.
5
+ *
6
+ * Said "posée" (01-11: « elle parle un peu vite et marque peu les espaces »): each clause made on its own,
7
+ * slowed by a tenth at the same pitch (ffmpeg atempo), with a silence after it -- longer after a sentence.
8
+ * Out: PCM 16 kHz, 16-bit, mono. */
9
+ import { existsSync, mkdirSync, createWriteStream, rmSync, readFileSync, renameSync } from 'node:fs';
10
+ import { pipeline } from 'node:stream/promises';
11
+ import { Readable } from 'node:stream';
12
+ import { createHash } from 'node:crypto';
13
+ import { execFile, spawn as spawnProcess } from 'node:child_process';
14
+ import { promisify } from 'node:util';
15
+ import { createServer } from 'node:net';
16
+
17
+ export const POCKET_VERSION = '3.3.0';
18
+ export const POCKET_RELEASE = 'https://github.com/kyutai-labs/pocket-tts/releases/download/v4.0.1';
19
+ export const POCKET_SHA256 = Object.freeze({
20
+ x64: '9abff0aa138a804e44052952d8c3bdaae247fb267ca8f4b83fe178897d1a0559',
21
+ arm64: '2b9a727bffd86ea6d73370d675cbd91a7db118f11b7f5a60343c2d5da12b187a',
22
+ });
23
+ export const TEMPO = 0.96; /* 01-11: 0.9 sounded sleepy; a touch slower than its own pace */
24
+ export const GAP_S = Object.freeze({ sentence: 0.42, pause: 0.25, comma: 0.16 });
25
+
26
+ /* A text in clauses, each with the silence that follows it. */
27
+ export function clausesOf(text) {
28
+ const out = [];
29
+ for (const piece of String(text).match(/[^.!?…;:,]+[.!?…;:,]*/g) ?? []) {
30
+ const t = piece.trim();
31
+ if (!t || !/[\p{L}\p{N}]/u.test(t)) continue;
32
+ const end = t.at(-1);
33
+ out.push({ text: t, gap: '.!?…'.includes(end) ? GAP_S.sentence : ';:'.includes(end) ? GAP_S.pause : end === ',' ? GAP_S.comma : GAP_S.sentence });
34
+ }
35
+ return out;
36
+ }
37
+
38
+ /* Quiet at both ends cut, a little kept so no word is clipped. */
39
+ export function trimmed(pcm, { floor = 200, before = 800, after = 1600 } = {}) {
40
+ const n = pcm.length >> 1; let a = -1; let b = -1;
41
+ for (let i = 0; i < n; i++) if (Math.abs(pcm.readInt16LE(i * 2)) > floor) { if (a < 0) a = i; b = i; }
42
+ if (a < 0) return Buffer.alloc(0);
43
+ return pcm.subarray(Math.max(0, a - before) * 2, Math.min(n, b + after) * 2);
44
+ }
45
+
46
+ const free = () => new Promise((ok, ko) => { const s = createServer(); s.listen(0, '127.0.0.1', () => { const { port } = s.address(); s.close(() => ok(port)); }); s.on('error', ko); });
47
+
48
+ export class Pocket {
49
+ #dir; #fetch; #log; #spawn; #ffmpeg; #port = 0; #child = null; #starting = null; #language;
50
+
51
+ constructor({ dir, fetcher = fetch, log = () => {}, spawn = spawnProcess, ffmpeg = 'ffmpeg', language = 'french' }) {
52
+ this.#dir = dir; this.#fetch = fetcher; this.#log = log; this.#spawn = spawn; this.#ffmpeg = ffmpeg; this.#language = language;
53
+ }
54
+
55
+ /* The program, fetched once and checked: only Linux on x64 or arm64. */
56
+ async #program() {
57
+ const arch = process.arch === 'x64' ? 'x86_64' : process.arch === 'arm64' ? 'aarch64' : null;
58
+ if (process.platform !== 'linux' || !arch) throw new Error('Pocket TTS runs on Linux x64 or arm64 only');
59
+ const name = `pocket-tts-${POCKET_VERSION}-${arch}-unknown-linux-gnu`;
60
+ const bin = `${this.#dir}/${name}/pocket-tts`;
61
+ if (existsSync(bin)) return bin;
62
+ mkdirSync(this.#dir, { recursive: true });
63
+ const archive = `${this.#dir}/${name}.tar.gz`;
64
+ this.#log('speech: fetching Kyutai\'s Pocket TTS');
65
+ const r = await this.#fetch(`${POCKET_RELEASE}/${name}.tar.gz`);
66
+ if (!r.ok || !r.body) throw new Error(`Pocket TTS could not be fetched (${r.status})`);
67
+ await pipeline(Readable.fromWeb(r.body), createWriteStream(archive));
68
+ const sum = createHash('sha256').update(readFileSync(archive)).digest('hex');
69
+ if (sum !== POCKET_SHA256[process.arch]) { rmSync(archive, { force: true }); throw new Error('Pocket TTS: the download is not the expected one (sha256)'); }
70
+ const unpacking = `${this.#dir}/.unpacking-pocket`;
71
+ rmSync(unpacking, { recursive: true, force: true }); mkdirSync(unpacking);
72
+ await promisify(execFile)('tar', ['xzf', archive, '-C', unpacking]);
73
+ renameSync(`${unpacking}/${name}`, `${this.#dir}/${name}`);
74
+ rmSync(unpacking, { recursive: true, force: true }); rmSync(archive, { force: true });
75
+ return bin;
76
+ }
77
+
78
+ /* Its server on loopback, started once, kept; ready when it answers. */
79
+ async #ready() {
80
+ if (this.#child && this.#port) return this.#port;
81
+ this.#starting ??= (async () => {
82
+ const bin = await this.#program();
83
+ const port = await free();
84
+ const child = this.#spawn(bin, ['serve', '--host', '127.0.0.1', '--port', String(port), '--language', this.#language, '--quantize'], { env: { ...process.env, HF_HOME: `${this.#dir}/pocket-hf` }, stdio: ['ignore', 'ignore', 'pipe'] });
85
+ let said = ''; child.stderr?.on('data', (d) => { said = `${said}${d}`.slice(-500); });
86
+ child.on('exit', () => { if (this.#child === child) { this.#child = null; this.#port = 0; } });
87
+ for (let i = 0; i < 300; i++) { /* the first time, its model comes from Hugging Face: a few minutes */
88
+ await new Promise((ok) => setTimeout(ok, 1000));
89
+ if (child.exitCode !== null) throw new Error(`Pocket TTS stopped: ${said.trim().split('\n').pop() ?? ''}`);
90
+ try { if ((await this.#fetch(`http://127.0.0.1:${port}/`, { signal: AbortSignal.timeout(2000) })).ok) { this.#child = child; this.#port = port; this.#log('speech: Pocket TTS ready'); return port; } } catch { /* not yet */ }
91
+ }
92
+ child.kill(); throw new Error('Pocket TTS did not start');
93
+ })().finally(() => { this.#starting = null; });
94
+ return this.#starting;
95
+ }
96
+
97
+ async #clause(text) {
98
+ const port = await this.#ready();
99
+ const form = new FormData(); form.append('text', text);
100
+ const r = await this.#fetch(`http://127.0.0.1:${port}/tts`, { method: 'POST', body: form, signal: AbortSignal.timeout(30_000) });
101
+ if (!r.ok) throw new Error(`Pocket TTS answered ${r.status}`);
102
+ const wav = Buffer.from(await r.arrayBuffer());
103
+ const rate = wav.readUInt32LE(24);
104
+ const pcm = wav.subarray(44, 44 + ((wav.length - 44) & ~1));
105
+ return trimmed(await this.#slowed(pcm, rate));
106
+ }
107
+
108
+ /* Slower by a tenth, at the same pitch, to 16 kHz (ffmpeg, which the voice boxes use already). */
109
+ #slowed(pcm, rate) {
110
+ return new Promise((resolve, reject) => {
111
+ const c = this.#spawn(this.#ffmpeg, ['-nostdin', '-loglevel', 'error', '-f', 's16le', '-ar', String(rate), '-ac', '1', '-i', '-', '-af', `atempo=${TEMPO}`, '-ar', '16000', '-f', 's16le', '-'], { stdio: ['pipe', 'pipe', 'ignore'] });
112
+ const out = [];
113
+ c.stdout.on('data', (d) => out.push(d));
114
+ c.on('error', reject);
115
+ c.on('close', (code) => (code === 0 ? resolve(Buffer.concat(out)) : reject(new Error('ffmpeg could not slow the voice'))));
116
+ c.stdin.end(pcm);
117
+ });
118
+ }
119
+
120
+ /* Text -> PCM 16 kHz, clause by clause, with its silences. */
121
+ async speak(text) {
122
+ const parts = [];
123
+ for (const c of clausesOf(text)) { parts.push(await this.#clause(c.text), Buffer.alloc(Math.round(c.gap * 16_000) * 2)); }
124
+ return Buffer.concat(parts);
125
+ }
126
+
127
+ stop() { this.#child?.kill(); this.#child = null; this.#port = 0; }
128
+ }
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,10 @@ 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) { this.#pocketDown = Date.now(); this.#log(`speech: Pocket TTS failed (${error.message}), another voice meanwhile`); }
109
+ }
105
110
  const online = await this.#eleven(text);
106
111
  if (online && online.length) return online;
107
112
  const engine = await this.#load();