pi-reply-reader 0.1.0 → 0.2.0

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.
@@ -0,0 +1,452 @@
1
+ import { spawn } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import { existsSync, linkSync, mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
4
+ import { isAbsolute, join } from "node:path";
5
+ import { configFile } from "./outputs.js";
6
+ import { saveSettings } from "./settings.js";
7
+ import { onPath } from "./voice.js";
8
+ export const DEFAULT_MUSIC = { mode: "duck", level: 20 };
9
+ export const MUSIC_MODES = ["off", "pause", "duck"];
10
+ export const MUSIC_HINT = "Use /read-music off, pause, or duck with a level from 0 to 100.";
11
+ export const LEVEL_HINT = "Level must be a whole number from 0 to 100.";
12
+ /** How long a gentle-stream call or a hook may take before it is ended. */
13
+ export const MUSIC_TIMEOUT_MS = 3000;
14
+ /**
15
+ * How long `--serve` keeps the listener's music aside after a reading ends, so the agent host's next reading in its
16
+ * line (a 1.5 s gap plus a new ssh) finds it still aside (S22: no flapping).
17
+ */
18
+ export const LISTENER_HOLD_MS = 4000;
19
+ const SETTINGS = "settings.json";
20
+ /** "Music goes down to 20 % while reading." and the like; `will` for a change. */
21
+ export function describeMusic(settings, will = false) {
22
+ const what = settings.mode === "duck"
23
+ ? `${will ? "will go" : "goes"} down to ${settings.level} % while reading.`
24
+ : settings.mode === "pause"
25
+ ? `${will ? "will pause" : "pauses"} while reading.`
26
+ : `${will ? "will be" : "is"} left as it is while reading.`;
27
+ return `Music ${what}`;
28
+ }
29
+ /** The music settings from settings.json; a bad `music` value means the default and a `problem`. Nothing throws. */
30
+ export function loadMusic(env) {
31
+ const path = configFile(env, SETTINGS);
32
+ if (!path)
33
+ return { music: DEFAULT_MUSIC };
34
+ let parsed;
35
+ try {
36
+ parsed = JSON.parse(readFileSync(path, "utf8"));
37
+ }
38
+ catch {
39
+ // A missing file is the default; an unreadable or invalid one is reported with the speed (S3).
40
+ return { music: DEFAULT_MUSIC };
41
+ }
42
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || !("music" in parsed))
43
+ return { music: DEFAULT_MUSIC };
44
+ const raw = parsed.music;
45
+ const ignored = (reason) => ({
46
+ music: DEFAULT_MUSIC,
47
+ problem: `Ignored "music" in ${path}: ${reason}. ${describeMusic(DEFAULT_MUSIC)}`,
48
+ });
49
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
50
+ return ignored("expected an object");
51
+ const { mode, level, before, after } = raw;
52
+ if (mode !== undefined && !MUSIC_MODES.includes(mode))
53
+ return ignored("mode must be off, pause or duck");
54
+ if (level !== undefined && !validLevel(level))
55
+ return ignored("level must be a whole number from 0 to 100");
56
+ for (const hook of [before, after])
57
+ if (hook !== undefined && (typeof hook !== "string" || !hook.trim()))
58
+ return ignored("before and after must be commands");
59
+ return {
60
+ music: {
61
+ mode: mode ?? DEFAULT_MUSIC.mode,
62
+ level: level ?? DEFAULT_MUSIC.level,
63
+ ...(before ? { before: before } : {}),
64
+ ...(after ? { after: after } : {}),
65
+ },
66
+ };
67
+ }
68
+ const validLevel = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 100;
69
+ /**
70
+ * `/read-music` arguments: `show` for none; else the mode and level to set, or the warning. A bare level means duck.
71
+ */
72
+ export function parseMusicArgs(text) {
73
+ const words = text.trim().split(/\s+/).filter(Boolean);
74
+ if (words.length === 0)
75
+ return "show";
76
+ const number = (word) => {
77
+ if (!/^[-+]?\d*[.,]?\d+%?$/.test(word))
78
+ return undefined;
79
+ const value = Number(word.replace("%", "").replace(",", "."));
80
+ return validLevel(value) && /^\d+%?$/.test(word) ? value : "bad";
81
+ };
82
+ const [first, second] = words;
83
+ const bare = number(first);
84
+ if (bare !== undefined)
85
+ return words.length === 1 && bare !== "bad" ? { mode: "duck", level: bare } : { problem: bare === "bad" ? LEVEL_HINT : MUSIC_HINT };
86
+ if (!MUSIC_MODES.includes(first))
87
+ return { problem: MUSIC_HINT };
88
+ if (words.length === 1)
89
+ return { mode: first };
90
+ if (first !== "duck" || words.length > 2)
91
+ return { problem: MUSIC_HINT };
92
+ const level = number(second);
93
+ if (level === undefined)
94
+ return { problem: MUSIC_HINT };
95
+ if (level === "bad")
96
+ return { problem: LEVEL_HINT };
97
+ return { mode: "duck", level };
98
+ }
99
+ /** Saves the mode (and level) in settings.json `music`, keeping its hooks and every other key; throws as saveSettings. */
100
+ export function saveMusic(env, values) {
101
+ let existing = {};
102
+ const path = configFile(env, SETTINGS);
103
+ try {
104
+ const music = JSON.parse(readFileSync(path ?? "", "utf8"))?.music;
105
+ if (music && typeof music === "object" && !Array.isArray(music))
106
+ existing = music;
107
+ }
108
+ catch { }
109
+ saveSettings(env, { music: { ...existing, ...values } });
110
+ }
111
+ /** The music state in `$XDG_RUNTIME_DIR/pi-reply-reader/music.json`, else in this process's memory. */
112
+ function openStore(env) {
113
+ const runtime = env.XDG_RUNTIME_DIR;
114
+ let dir;
115
+ if (runtime && isAbsolute(runtime)) {
116
+ try {
117
+ dir = join(runtime, "pi-reply-reader");
118
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
119
+ if (!statSync(dir).isDirectory())
120
+ dir = undefined;
121
+ }
122
+ catch {
123
+ dir = undefined;
124
+ }
125
+ }
126
+ if (!dir)
127
+ return memory;
128
+ const file = join(dir, "music.json");
129
+ const read = () => {
130
+ try {
131
+ return validState(JSON.parse(readFileSync(file, "utf8")));
132
+ }
133
+ catch {
134
+ return undefined;
135
+ }
136
+ };
137
+ /** Writes `state` to a temporary file and puts it in place with `put`; false when that failed. */
138
+ const place = (state, put) => {
139
+ const temp = `${file}.${process.pid}.${randomUUID()}.tmp`;
140
+ try {
141
+ writeFileSync(temp, JSON.stringify(state), { mode: 0o600 });
142
+ put(temp);
143
+ return true;
144
+ }
145
+ catch {
146
+ return false;
147
+ }
148
+ finally {
149
+ try {
150
+ unlinkSync(temp);
151
+ }
152
+ catch { }
153
+ }
154
+ };
155
+ return {
156
+ read,
157
+ create(state) {
158
+ // Linked in place whole: no other process ever reads it half written, and only one creates it.
159
+ if (place(state, (temp) => linkSync(temp, file)))
160
+ return true;
161
+ // A file that is broken, empty or holds values out of range is no state: it is replaced, atomically.
162
+ if (!existsSync(file) || read())
163
+ return false;
164
+ return place(state, (temp) => renameSync(temp, file)) && read()?.token === state.token;
165
+ },
166
+ write(state) {
167
+ place(state, (temp) => renameSync(temp, file));
168
+ },
169
+ remove(token) {
170
+ if (read()?.token !== token)
171
+ return;
172
+ try {
173
+ unlinkSync(file);
174
+ }
175
+ catch { }
176
+ },
177
+ clear() {
178
+ // A broken file is removed: the music handling recovers by itself.
179
+ if (!existsSync(file) || read())
180
+ return;
181
+ try {
182
+ unlinkSync(file);
183
+ }
184
+ catch { }
185
+ },
186
+ };
187
+ }
188
+ const wholeVolume = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 100;
189
+ /**
190
+ * The state as music.json holds it, checked before any of it reaches gentle-stream: a whole volume from 0 to 100,
191
+ * booleans, a known mode. Anything else is no state (undefined).
192
+ */
193
+ function validState(value) {
194
+ if (!value || typeof value !== "object" || Array.isArray(value))
195
+ return undefined;
196
+ const { token, pending, music, hook, hold } = value;
197
+ if (typeof token !== "string" || !token)
198
+ return undefined;
199
+ if (pending !== undefined && pending !== true)
200
+ return undefined;
201
+ if (hook !== undefined && hook !== true)
202
+ return undefined;
203
+ if (hold !== undefined && (typeof hold !== "number" || !Number.isFinite(hold)))
204
+ return undefined;
205
+ if (music !== undefined) {
206
+ if (!music || typeof music !== "object" || Array.isArray(music))
207
+ return undefined;
208
+ const { mode, volume, playing, set } = music;
209
+ if (mode !== "duck" && mode !== "pause")
210
+ return undefined;
211
+ if (!wholeVolume(volume) || typeof playing !== "boolean")
212
+ return undefined;
213
+ if (set !== undefined && !wholeVolume(set))
214
+ return undefined;
215
+ }
216
+ return value;
217
+ }
218
+ let remembered;
219
+ const memory = {
220
+ read: () => remembered,
221
+ create(state) {
222
+ if (remembered)
223
+ return false;
224
+ remembered = state;
225
+ return true;
226
+ },
227
+ write(state) {
228
+ remembered = state;
229
+ },
230
+ remove(token) {
231
+ if (remembered?.token === token)
232
+ remembered = undefined;
233
+ },
234
+ clear() { },
235
+ };
236
+ /**
237
+ * The step-aside of one reader process. `settings()` gives the music settings at each step; `idle()` whether nothing
238
+ * reads or waits on the machine; `warn` is told about a hook or gentle-stream that failed or hung (the caller says it
239
+ * once per session).
240
+ */
241
+ export function createMusic(deps) {
242
+ const { env } = deps;
243
+ /** Opened at the first use, so a reader that never steps aside creates nothing. */
244
+ let opened;
245
+ const store = {
246
+ read: () => (opened ??= openStore(env)).read(),
247
+ create: (state) => (opened ??= openStore(env)).create(state),
248
+ write: (state) => (opened ??= openStore(env)).write(state),
249
+ remove: (token) => (opened ??= openStore(env)).remove(token),
250
+ clear: () => (opened ??= openStore(env)).clear(),
251
+ };
252
+ /** Commands of this process run in order: a restore never overtakes the step-aside it undoes. */
253
+ let chain = Promise.resolve();
254
+ const later = (task) => {
255
+ chain = chain.then(task).catch(() => { });
256
+ };
257
+ const hook = (which, command) => {
258
+ if (!command)
259
+ return;
260
+ // Not chained: a slow hook never holds gentle-stream back, nor speech.
261
+ const done = run("/bin/sh", ["-c", command], env).then(({ code, timedOut, error }) => {
262
+ if (timedOut)
263
+ deps.warn(`Music hook "${which}" timed out after ${MUSIC_TIMEOUT_MS / 1000} s; it was ended.`);
264
+ else if (error)
265
+ deps.warn(`Music hook "${which}" failed (${error}).`);
266
+ else if (code !== 0)
267
+ deps.warn(`Music hook "${which}" failed (exit code ${code}).`);
268
+ });
269
+ pendingHooks.add(done);
270
+ void done.finally(() => pendingHooks.delete(done));
271
+ };
272
+ const pendingHooks = new Set();
273
+ /** gentle-stream on PATH, run with `args`; undefined when it is not there. A hang or failure other than exit 1 warns. */
274
+ const ctl = async (gentle, args) => {
275
+ const result = await run(gentle, ["ctl", ...args], env, true);
276
+ if (result.timedOut) {
277
+ deps.warn(`gentle-stream did not answer within ${MUSIC_TIMEOUT_MS / 1000} s; the music was left as it is.`);
278
+ return undefined;
279
+ }
280
+ if (result.error) {
281
+ deps.warn(`gentle-stream failed (${result.error}).`);
282
+ return undefined;
283
+ }
284
+ // Exit 1: nothing plays (S22); said by no one.
285
+ if (result.code !== 0 && result.code !== 1)
286
+ deps.warn(`gentle-stream ctl ${args.join(" ")} failed (exit code ${result.code}).`);
287
+ return { code: result.code, out: result.out };
288
+ };
289
+ const status = async (gentle) => {
290
+ const result = await ctl(gentle, ["status", "--json"]);
291
+ if (!result)
292
+ return undefined;
293
+ try {
294
+ const parsed = JSON.parse(result.out);
295
+ const volume = typeof parsed.volume === "number" && Number.isFinite(parsed.volume) ? Math.round(parsed.volume) : undefined;
296
+ return { running: parsed.running !== false && parsed.ok !== false, playing: parsed.playing === true, volume };
297
+ }
298
+ catch {
299
+ return undefined;
300
+ }
301
+ };
302
+ return {
303
+ stepAside() {
304
+ const settings = deps.settings();
305
+ const gentle = settings.mode === "off" ? undefined : onPath("gentle-stream", env);
306
+ const existing = store.read();
307
+ if (existing) {
308
+ // Already aside (an earlier reading of the line, or a reader that died): a newer reading keeps it so.
309
+ if (existing.hold !== undefined) {
310
+ const { hold: _hold, ...rest } = existing;
311
+ store.write(rest);
312
+ }
313
+ return;
314
+ }
315
+ if (!gentle && !settings.before && !settings.after)
316
+ return;
317
+ const state = { token: randomUUID(), pending: true, ...(settings.before || settings.after ? { hook: true } : {}) };
318
+ if (!store.create(state))
319
+ return;
320
+ hook("before", settings.before);
321
+ later(async () => {
322
+ let music;
323
+ const now = gentle ? await status(gentle) : undefined;
324
+ if (gentle && now?.running && now.playing && now.volume !== undefined) {
325
+ music =
326
+ settings.mode === "pause"
327
+ ? { mode: "pause", volume: now.volume, playing: true }
328
+ : { mode: "duck", volume: now.volume, playing: true, set: Math.min(settings.level, now.volume) };
329
+ }
330
+ // Restored (or taken over) while the status was read: nothing to step aside.
331
+ if (store.read()?.token !== state.token)
332
+ return;
333
+ if (!music && !state.hook)
334
+ return store.remove(state.token);
335
+ const { pending: _pending, ...known } = store.read() ?? state;
336
+ store.write({ ...known, ...(music ? { music } : {}) });
337
+ if (!gentle || !music)
338
+ return;
339
+ if (music.mode === "pause")
340
+ await ctl(gentle, ["pause"]);
341
+ else if (music.set !== undefined && music.set < music.volume)
342
+ await ctl(gentle, ["volume", String(music.set)]);
343
+ });
344
+ },
345
+ settle(options = {}) {
346
+ const state = store.read();
347
+ if (!state) {
348
+ // A broken music.json is no state; once idle it is removed, so the next reading starts afresh.
349
+ if (options.force || deps.idle())
350
+ store.clear();
351
+ return;
352
+ }
353
+ if (!options.force) {
354
+ if (!deps.idle())
355
+ return;
356
+ if (state.hold !== undefined && Date.now() < state.hold)
357
+ return;
358
+ }
359
+ store.remove(state.token);
360
+ const settings = deps.settings();
361
+ if (state.hook)
362
+ hook("after", settings.after);
363
+ const saved = state.music;
364
+ if (!saved)
365
+ return;
366
+ later(async () => {
367
+ const gentle = onPath("gentle-stream", env);
368
+ if (!gentle)
369
+ return;
370
+ const now = await status(gentle);
371
+ if (!now?.running)
372
+ return;
373
+ if (saved.mode === "duck") {
374
+ // The user set another volume since the duck: theirs stays.
375
+ if (saved.set !== undefined && saved.set !== saved.volume && now.volume === saved.set)
376
+ await ctl(gentle, ["volume", String(saved.volume)]);
377
+ }
378
+ else if (!now.playing && now.volume === saved.volume) {
379
+ // Still as the pause left it; a volume the user changed means they took over, and it stays paused.
380
+ await ctl(gentle, ["play"]);
381
+ }
382
+ });
383
+ },
384
+ async idle() {
385
+ for (;;) {
386
+ const before = chain;
387
+ await Promise.all([chain, ...pendingHooks]);
388
+ if (before === chain && pendingHooks.size === 0)
389
+ return;
390
+ }
391
+ },
392
+ };
393
+ }
394
+ /** Keeps the music aside for `ms` more (the listener between the agent host's readings, S22); then settle restores it. */
395
+ export function holdMusic(env, ms) {
396
+ const store = openStore(env);
397
+ const state = store.read();
398
+ if (!state)
399
+ return false;
400
+ store.write({ ...state, hold: Date.now() + ms });
401
+ return true;
402
+ }
403
+ /**
404
+ * Runs `command` detached, in its own process group, ended whole (SIGTERM, then SIGKILL) after MUSIC_TIMEOUT_MS.
405
+ * Only what it started is ever signalled. Its output is read when `capture`.
406
+ */
407
+ function run(command, args, env, capture = false) {
408
+ return new Promise((resolve) => {
409
+ let child;
410
+ try {
411
+ child = spawn(command, args, { env, detached: true, stdio: ["ignore", capture ? "pipe" : "ignore", "ignore"] });
412
+ }
413
+ catch (error) {
414
+ resolve({ code: null, out: "", timedOut: false, error: error.message });
415
+ return;
416
+ }
417
+ let out = "";
418
+ let timedOut = false;
419
+ child.stdout?.on("data", (chunk) => {
420
+ if (out.length < 65536)
421
+ out += chunk.toString();
422
+ });
423
+ const group = (signal) => {
424
+ if (child.pid === undefined)
425
+ return;
426
+ try {
427
+ process.kill(-child.pid, signal);
428
+ }
429
+ catch { }
430
+ };
431
+ let kill;
432
+ const ended = () => {
433
+ clearTimeout(timer);
434
+ clearTimeout(kill);
435
+ };
436
+ const timer = setTimeout(() => {
437
+ timedOut = true;
438
+ group("SIGTERM");
439
+ kill = setTimeout(() => group("SIGKILL"), 1000);
440
+ kill.unref?.();
441
+ }, MUSIC_TIMEOUT_MS);
442
+ timer.unref?.();
443
+ child.on("error", (error) => {
444
+ ended();
445
+ resolve({ code: null, out, timedOut: false, error: error.message });
446
+ });
447
+ child.on("close", (code) => {
448
+ ended();
449
+ resolve({ code, out, timedOut });
450
+ });
451
+ });
452
+ }
@@ -2,9 +2,18 @@ import { readFileSync } from "node:fs";
2
2
  import { isAbsolute, join } from "node:path";
3
3
  const NAME = /^[A-Za-z0-9][A-Za-z0-9-]*$/;
4
4
  const VALUE_HINT = 'the value must be a PULSE_SERVER string such as "tcp:192.168.1.50:4713"';
5
+ const SSH_HINT = '"ssh" must be a host such as "you@host", without spaces or a leading "-"';
6
+ const FALLBACK_HINT = '"fallback" must be a PULSE_SERVER string such as "unix:/run/user/1000/reply-reader-pulse.sock"';
7
+ /**
8
+ * An SSH destination that ssh cannot take for an option (S20): no leading "-", no whitespace or newline, no control
9
+ * character (C0 with NUL, DEL, C1 with U+0085) and no Unicode line or paragraph separator.
10
+ */
11
+ const SSH_HOST = /^[^-\s\p{Cc}\u2028\u2029][^\s\p{Cc}\u2028\u2029]*$/u;
12
+ const LISTENER_KEYS = ["ssh", "fallback"];
5
13
  /**
6
14
  * `local` plus the outputs in `$XDG_CONFIG_HOME/pi-reply-reader/outputs.json`, an object mapping each
7
- * name to its PULSE_SERVER. Bad entries are skipped and reported in `problems`; nothing throws.
15
+ * name to its PULSE_SERVER, or to `{ "ssh": "you@host", "fallback": "<PULSE_SERVER>" }` for a listener that
16
+ * synthesizes (S20; `fallback` optional). Bad entries are skipped and reported in `problems`; nothing throws.
8
17
  */
9
18
  export function loadOutputs(env, hostname) {
10
19
  const outputs = [{ name: "local", label: `local (${hostname})` }];
@@ -32,17 +41,33 @@ export function loadOutputs(env, hostname) {
32
41
  return { outputs, problems };
33
42
  }
34
43
  for (const [name, value] of Object.entries(parsed)) {
44
+ const listener = value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
45
+ const unknown = listener && Object.keys(listener).find((key) => !LISTENER_KEYS.includes(key));
35
46
  const reason = name === "local"
36
47
  ? "that name is built in"
37
48
  : !NAME.test(name)
38
49
  ? 'names use letters, digits and "-"'
39
- : typeof value !== "string" || value.trim() === ""
40
- ? VALUE_HINT
41
- : undefined;
50
+ : listener
51
+ ? unknown !== undefined
52
+ ? `unknown key "${unknown}" (use "ssh" and "fallback")`
53
+ : typeof listener.ssh !== "string" || !SSH_HOST.test(listener.ssh)
54
+ ? SSH_HINT
55
+ : listener.fallback !== undefined && (typeof listener.fallback !== "string" || listener.fallback.trim() === "")
56
+ ? FALLBACK_HINT
57
+ : undefined
58
+ : typeof value !== "string" || value.trim() === ""
59
+ ? VALUE_HINT
60
+ : undefined;
42
61
  if (reason) {
43
62
  problems.push(`Ignored output "${name}" in ${path}: ${reason}.`);
44
63
  continue;
45
64
  }
65
+ if (listener) {
66
+ const ssh = listener.ssh;
67
+ const fallback = listener.fallback;
68
+ outputs.push({ name, label: `${name} (listener ${ssh})`, ssh, ...(fallback === undefined ? {} : { fallback }) });
69
+ continue;
70
+ }
46
71
  outputs.push({ name, label: `${name} (${value})`, pulseServer: value });
47
72
  }
48
73
  return { outputs, problems };