pi-reply-reader 0.0.0-stage → 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.
package/src/music.ts ADDED
@@ -0,0 +1,474 @@
1
+ import { type ChildProcess, 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.ts";
6
+ import { saveSettings } from "./settings.ts";
7
+ import { onPath } from "./voice.ts";
8
+
9
+ /**
10
+ * Music steps aside while the reader speaks (S22). settings.json `music`: `{ "mode": "off" | "pause" | "duck",
11
+ * "level": 20, "before": "<command>", "after": "<command>" }`; nothing saved means duck to 20 %.
12
+ *
13
+ * Built in: gentle-stream (`gentle-stream ctl status --json`, `ctl volume N`, `ctl pause`, `ctl play`). Hooks: `before`
14
+ * and `after` run at the same moments, whatever the mode, through `/bin/sh -c` as the user (they come from the user's
15
+ * own settings file; nothing from a reply is ever put in them).
16
+ *
17
+ * Once per machine: the state the music was in before it stepped aside is kept in `$XDG_RUNTIME_DIR/pi-reply-reader/
18
+ * music.json` (in memory without XDG_RUNTIME_DIR). Its presence means "the music is aside": a later reading leaves it
19
+ * so (no flapping between queued readings), and whoever finds the machine idle with nothing waiting restores it, a
20
+ * session start included (a reader that died left it aside). Every command runs detached, with a timeout, and is never
21
+ * awaited by speech.
22
+ */
23
+ export type MusicMode = "off" | "pause" | "duck";
24
+ export interface MusicSettings {
25
+ mode: MusicMode;
26
+ /** The volume, 0-100, that duck lowers the music to (never raising it). */
27
+ level: number;
28
+ before?: string;
29
+ after?: string;
30
+ }
31
+
32
+ export const DEFAULT_MUSIC: MusicSettings = { mode: "duck", level: 20 };
33
+ export const MUSIC_MODES: readonly MusicMode[] = ["off", "pause", "duck"];
34
+ export const MUSIC_HINT = "Use /read-music off, pause, or duck with a level from 0 to 100.";
35
+ export const LEVEL_HINT = "Level must be a whole number from 0 to 100.";
36
+ /** How long a gentle-stream call or a hook may take before it is ended. */
37
+ export const MUSIC_TIMEOUT_MS = 3000;
38
+ /**
39
+ * How long `--serve` keeps the listener's music aside after a reading ends, so the agent host's next reading in its
40
+ * line (a 1.5 s gap plus a new ssh) finds it still aside (S22: no flapping).
41
+ */
42
+ export const LISTENER_HOLD_MS = 4000;
43
+
44
+ const SETTINGS = "settings.json";
45
+
46
+ /** "Music goes down to 20 % while reading." and the like; `will` for a change. */
47
+ export function describeMusic(settings: MusicSettings, will = false): string {
48
+ const what =
49
+ settings.mode === "duck"
50
+ ? `${will ? "will go" : "goes"} down to ${settings.level} % while reading.`
51
+ : settings.mode === "pause"
52
+ ? `${will ? "will pause" : "pauses"} while reading.`
53
+ : `${will ? "will be" : "is"} left as it is while reading.`;
54
+ return `Music ${what}`;
55
+ }
56
+
57
+ /** The music settings from settings.json; a bad `music` value means the default and a `problem`. Nothing throws. */
58
+ export function loadMusic(env: NodeJS.ProcessEnv): { music: MusicSettings; problem?: string } {
59
+ const path = configFile(env, SETTINGS);
60
+ if (!path) return { music: DEFAULT_MUSIC };
61
+ let parsed: unknown;
62
+ try {
63
+ parsed = JSON.parse(readFileSync(path, "utf8"));
64
+ } catch {
65
+ // A missing file is the default; an unreadable or invalid one is reported with the speed (S3).
66
+ return { music: DEFAULT_MUSIC };
67
+ }
68
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || !("music" in parsed)) return { music: DEFAULT_MUSIC };
69
+ const raw = (parsed as { music: unknown }).music;
70
+ const ignored = (reason: string) => ({
71
+ music: DEFAULT_MUSIC,
72
+ problem: `Ignored "music" in ${path}: ${reason}. ${describeMusic(DEFAULT_MUSIC)}`,
73
+ });
74
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return ignored("expected an object");
75
+ const { mode, level, before, after } = raw as Record<string, unknown>;
76
+ if (mode !== undefined && !MUSIC_MODES.includes(mode as MusicMode)) return ignored("mode must be off, pause or duck");
77
+ if (level !== undefined && !validLevel(level)) return ignored("level must be a whole number from 0 to 100");
78
+ for (const hook of [before, after]) if (hook !== undefined && (typeof hook !== "string" || !hook.trim())) return ignored("before and after must be commands");
79
+ return {
80
+ music: {
81
+ mode: (mode as MusicMode | undefined) ?? DEFAULT_MUSIC.mode,
82
+ level: (level as number | undefined) ?? DEFAULT_MUSIC.level,
83
+ ...(before ? { before: before as string } : {}),
84
+ ...(after ? { after: after as string } : {}),
85
+ },
86
+ };
87
+ }
88
+
89
+ const validLevel = (value: unknown): value is number => typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 100;
90
+
91
+ /**
92
+ * `/read-music` arguments: `show` for none; else the mode and level to set, or the warning. A bare level means duck.
93
+ */
94
+ export function parseMusicArgs(text: string): "show" | { mode: MusicMode; level?: number } | { problem: string } {
95
+ const words = text.trim().split(/\s+/).filter(Boolean);
96
+ if (words.length === 0) return "show";
97
+ const number = (word: string): number | undefined | "bad" => {
98
+ if (!/^[-+]?\d*[.,]?\d+%?$/.test(word)) return undefined;
99
+ const value = Number(word.replace("%", "").replace(",", "."));
100
+ return validLevel(value) && /^\d+%?$/.test(word) ? value : "bad";
101
+ };
102
+ const [first, second] = words;
103
+ const bare = number(first);
104
+ if (bare !== undefined) return words.length === 1 && bare !== "bad" ? { mode: "duck", level: bare } : { problem: bare === "bad" ? LEVEL_HINT : MUSIC_HINT };
105
+ if (!MUSIC_MODES.includes(first as MusicMode)) return { problem: MUSIC_HINT };
106
+ if (words.length === 1) return { mode: first as MusicMode };
107
+ if (first !== "duck" || words.length > 2) return { problem: MUSIC_HINT };
108
+ const level = number(second);
109
+ if (level === undefined) return { problem: MUSIC_HINT };
110
+ if (level === "bad") return { problem: LEVEL_HINT };
111
+ return { mode: "duck", level };
112
+ }
113
+
114
+ /** Saves the mode (and level) in settings.json `music`, keeping its hooks and every other key; throws as saveSettings. */
115
+ export function saveMusic(env: NodeJS.ProcessEnv, values: { mode: MusicMode; level?: number }): void {
116
+ let existing: Record<string, unknown> = {};
117
+ const path = configFile(env, SETTINGS);
118
+ try {
119
+ const music = (JSON.parse(readFileSync(path ?? "", "utf8")) as { music?: unknown })?.music;
120
+ if (music && typeof music === "object" && !Array.isArray(music)) existing = music as Record<string, unknown>;
121
+ } catch {}
122
+ saveSettings(env, { music: { ...existing, ...values } });
123
+ }
124
+
125
+ /** What the music was before it stepped aside; written to music.json. */
126
+ interface State {
127
+ token: string;
128
+ /** Not yet known while gentle-stream's status is being read. */
129
+ pending?: true;
130
+ /** gentle-stream's music as it was, and the volume the duck set (`set`). */
131
+ music?: { mode: "duck" | "pause"; volume: number; playing: boolean; set?: number };
132
+ /** A hook is configured: `after` runs at the restore. */
133
+ hook?: true;
134
+ /** `--serve` keeps it aside until then (ms), for the agent host's next reading (S22). */
135
+ hold?: number;
136
+ }
137
+
138
+ interface Store {
139
+ read(): State | undefined;
140
+ /** Creates the state when none is there; false when one already is. */
141
+ create(state: State): boolean;
142
+ write(state: State): void;
143
+ remove(token: string): void;
144
+ /** Removes a state that is there but broken (empty, not JSON, values out of range); a valid one stays. */
145
+ clear(): void;
146
+ }
147
+
148
+ /** The music state in `$XDG_RUNTIME_DIR/pi-reply-reader/music.json`, else in this process's memory. */
149
+ function openStore(env: NodeJS.ProcessEnv): Store {
150
+ const runtime = env.XDG_RUNTIME_DIR;
151
+ let dir: string | undefined;
152
+ if (runtime && isAbsolute(runtime)) {
153
+ try {
154
+ dir = join(runtime, "pi-reply-reader");
155
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
156
+ if (!statSync(dir).isDirectory()) dir = undefined;
157
+ } catch {
158
+ dir = undefined;
159
+ }
160
+ }
161
+ if (!dir) return memory;
162
+ const file = join(dir, "music.json");
163
+ const read = (): State | undefined => {
164
+ try {
165
+ return validState(JSON.parse(readFileSync(file, "utf8")));
166
+ } catch {
167
+ return undefined;
168
+ }
169
+ };
170
+ /** Writes `state` to a temporary file and puts it in place with `put`; false when that failed. */
171
+ const place = (state: State, put: (temp: string) => void): boolean => {
172
+ const temp = `${file}.${process.pid}.${randomUUID()}.tmp`;
173
+ try {
174
+ writeFileSync(temp, JSON.stringify(state), { mode: 0o600 });
175
+ put(temp);
176
+ return true;
177
+ } catch {
178
+ return false;
179
+ } finally {
180
+ try {
181
+ unlinkSync(temp);
182
+ } catch {}
183
+ }
184
+ };
185
+ return {
186
+ read,
187
+ create(state) {
188
+ // Linked in place whole: no other process ever reads it half written, and only one creates it.
189
+ if (place(state, (temp) => linkSync(temp, file))) return true;
190
+ // A file that is broken, empty or holds values out of range is no state: it is replaced, atomically.
191
+ if (!existsSync(file) || read()) return false;
192
+ return place(state, (temp) => renameSync(temp, file)) && read()?.token === state.token;
193
+ },
194
+ write(state) {
195
+ place(state, (temp) => renameSync(temp, file));
196
+ },
197
+ remove(token) {
198
+ if (read()?.token !== token) return;
199
+ try {
200
+ unlinkSync(file);
201
+ } catch {}
202
+ },
203
+ clear() {
204
+ // A broken file is removed: the music handling recovers by itself.
205
+ if (!existsSync(file) || read()) return;
206
+ try {
207
+ unlinkSync(file);
208
+ } catch {}
209
+ },
210
+ };
211
+ }
212
+
213
+ const wholeVolume = (value: unknown): value is number => typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 100;
214
+
215
+ /**
216
+ * The state as music.json holds it, checked before any of it reaches gentle-stream: a whole volume from 0 to 100,
217
+ * booleans, a known mode. Anything else is no state (undefined).
218
+ */
219
+ function validState(value: unknown): State | undefined {
220
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
221
+ const { token, pending, music, hook, hold } = value as Record<string, unknown>;
222
+ if (typeof token !== "string" || !token) return undefined;
223
+ if (pending !== undefined && pending !== true) return undefined;
224
+ if (hook !== undefined && hook !== true) return undefined;
225
+ if (hold !== undefined && (typeof hold !== "number" || !Number.isFinite(hold))) return undefined;
226
+ if (music !== undefined) {
227
+ if (!music || typeof music !== "object" || Array.isArray(music)) return undefined;
228
+ const { mode, volume, playing, set } = music as Record<string, unknown>;
229
+ if (mode !== "duck" && mode !== "pause") return undefined;
230
+ if (!wholeVolume(volume) || typeof playing !== "boolean") return undefined;
231
+ if (set !== undefined && !wholeVolume(set)) return undefined;
232
+ }
233
+ return value as State;
234
+ }
235
+
236
+ let remembered: State | undefined;
237
+ const memory: Store = {
238
+ read: () => remembered,
239
+ create(state) {
240
+ if (remembered) return false;
241
+ remembered = state;
242
+ return true;
243
+ },
244
+ write(state) {
245
+ remembered = state;
246
+ },
247
+ remove(token) {
248
+ if (remembered?.token === token) remembered = undefined;
249
+ },
250
+ clear() {},
251
+ };
252
+
253
+ /** gentle-stream's `ctl status --json`, as far as it is read. */
254
+ interface Status {
255
+ running: boolean;
256
+ playing: boolean;
257
+ volume?: number;
258
+ }
259
+
260
+ export interface Music {
261
+ /** The machine's line went idle → reading (or a resume): steps the music aside unless it already is. */
262
+ stepAside(): void;
263
+ /**
264
+ * Restores the music when the machine is idle with nothing waiting (`force`: at once, as for a pause). Once restored,
265
+ * a later reading steps it aside again.
266
+ */
267
+ settle(options?: { force?: boolean; holdMs?: number }): void;
268
+ /** Resolves once every command started so far has ended (bounded by their timeouts). */
269
+ idle(): Promise<void>;
270
+ }
271
+
272
+ /**
273
+ * The step-aside of one reader process. `settings()` gives the music settings at each step; `idle()` whether nothing
274
+ * reads or waits on the machine; `warn` is told about a hook or gentle-stream that failed or hung (the caller says it
275
+ * once per session).
276
+ */
277
+ export function createMusic(deps: {
278
+ env: NodeJS.ProcessEnv;
279
+ settings: () => MusicSettings;
280
+ idle: () => boolean;
281
+ warn: (message: string) => void;
282
+ }): Music {
283
+ const { env } = deps;
284
+ /** Opened at the first use, so a reader that never steps aside creates nothing. */
285
+ let opened: Store | undefined;
286
+ const store: Store = {
287
+ read: () => (opened ??= openStore(env)).read(),
288
+ create: (state) => (opened ??= openStore(env)).create(state),
289
+ write: (state) => (opened ??= openStore(env)).write(state),
290
+ remove: (token) => (opened ??= openStore(env)).remove(token),
291
+ clear: () => (opened ??= openStore(env)).clear(),
292
+ };
293
+ /** Commands of this process run in order: a restore never overtakes the step-aside it undoes. */
294
+ let chain: Promise<void> = Promise.resolve();
295
+ const later = (task: () => Promise<void>): void => {
296
+ chain = chain.then(task).catch(() => {});
297
+ };
298
+
299
+ const hook = (which: "before" | "after", command: string | undefined): void => {
300
+ if (!command) return;
301
+ // Not chained: a slow hook never holds gentle-stream back, nor speech.
302
+ const done = run("/bin/sh", ["-c", command], env).then(({ code, timedOut, error }) => {
303
+ if (timedOut) deps.warn(`Music hook "${which}" timed out after ${MUSIC_TIMEOUT_MS / 1000} s; it was ended.`);
304
+ else if (error) deps.warn(`Music hook "${which}" failed (${error}).`);
305
+ else if (code !== 0) deps.warn(`Music hook "${which}" failed (exit code ${code}).`);
306
+ });
307
+ pendingHooks.add(done);
308
+ void done.finally(() => pendingHooks.delete(done));
309
+ };
310
+ const pendingHooks = new Set<Promise<void>>();
311
+
312
+ /** gentle-stream on PATH, run with `args`; undefined when it is not there. A hang or failure other than exit 1 warns. */
313
+ const ctl = async (gentle: string, args: string[]): Promise<{ code: number | null; out: string } | undefined> => {
314
+ const result = await run(gentle, ["ctl", ...args], env, true);
315
+ if (result.timedOut) {
316
+ deps.warn(`gentle-stream did not answer within ${MUSIC_TIMEOUT_MS / 1000} s; the music was left as it is.`);
317
+ return undefined;
318
+ }
319
+ if (result.error) {
320
+ deps.warn(`gentle-stream failed (${result.error}).`);
321
+ return undefined;
322
+ }
323
+ // Exit 1: nothing plays (S22); said by no one.
324
+ if (result.code !== 0 && result.code !== 1) deps.warn(`gentle-stream ctl ${args.join(" ")} failed (exit code ${result.code}).`);
325
+ return { code: result.code, out: result.out };
326
+ };
327
+ const status = async (gentle: string): Promise<Status | undefined> => {
328
+ const result = await ctl(gentle, ["status", "--json"]);
329
+ if (!result) return undefined;
330
+ try {
331
+ const parsed = JSON.parse(result.out) as Record<string, unknown>;
332
+ const volume = typeof parsed.volume === "number" && Number.isFinite(parsed.volume) ? Math.round(parsed.volume) : undefined;
333
+ return { running: parsed.running !== false && parsed.ok !== false, playing: parsed.playing === true, volume };
334
+ } catch {
335
+ return undefined;
336
+ }
337
+ };
338
+
339
+ return {
340
+ stepAside() {
341
+ const settings = deps.settings();
342
+ const gentle = settings.mode === "off" ? undefined : onPath("gentle-stream", env);
343
+ const existing = store.read();
344
+ if (existing) {
345
+ // Already aside (an earlier reading of the line, or a reader that died): a newer reading keeps it so.
346
+ if (existing.hold !== undefined) {
347
+ const { hold: _hold, ...rest } = existing;
348
+ store.write(rest);
349
+ }
350
+ return;
351
+ }
352
+ if (!gentle && !settings.before && !settings.after) return;
353
+ const state: State = { token: randomUUID(), pending: true, ...(settings.before || settings.after ? { hook: true as const } : {}) };
354
+ if (!store.create(state)) return;
355
+ hook("before", settings.before);
356
+ later(async () => {
357
+ let music: State["music"];
358
+ const now = gentle ? await status(gentle) : undefined;
359
+ if (gentle && now?.running && now.playing && now.volume !== undefined) {
360
+ music =
361
+ settings.mode === "pause"
362
+ ? { mode: "pause", volume: now.volume, playing: true }
363
+ : { mode: "duck", volume: now.volume, playing: true, set: Math.min(settings.level, now.volume) };
364
+ }
365
+ // Restored (or taken over) while the status was read: nothing to step aside.
366
+ if (store.read()?.token !== state.token) return;
367
+ if (!music && !state.hook) return store.remove(state.token);
368
+ const { pending: _pending, ...known } = store.read() ?? state;
369
+ store.write({ ...known, ...(music ? { music } : {}) });
370
+ if (!gentle || !music) return;
371
+ if (music.mode === "pause") await ctl(gentle, ["pause"]);
372
+ else if (music.set !== undefined && music.set < music.volume) await ctl(gentle, ["volume", String(music.set)]);
373
+ });
374
+ },
375
+ settle(options = {}) {
376
+ const state = store.read();
377
+ if (!state) {
378
+ // A broken music.json is no state; once idle it is removed, so the next reading starts afresh.
379
+ if (options.force || deps.idle()) store.clear();
380
+ return;
381
+ }
382
+ if (!options.force) {
383
+ if (!deps.idle()) return;
384
+ if (state.hold !== undefined && Date.now() < state.hold) return;
385
+ }
386
+ store.remove(state.token);
387
+ const settings = deps.settings();
388
+ if (state.hook) hook("after", settings.after);
389
+ const saved = state.music;
390
+ if (!saved) return;
391
+ later(async () => {
392
+ const gentle = onPath("gentle-stream", env);
393
+ if (!gentle) return;
394
+ const now = await status(gentle);
395
+ if (!now?.running) return;
396
+ if (saved.mode === "duck") {
397
+ // The user set another volume since the duck: theirs stays.
398
+ if (saved.set !== undefined && saved.set !== saved.volume && now.volume === saved.set) await ctl(gentle, ["volume", String(saved.volume)]);
399
+ } else if (!now.playing && now.volume === saved.volume) {
400
+ // Still as the pause left it; a volume the user changed means they took over, and it stays paused.
401
+ await ctl(gentle, ["play"]);
402
+ }
403
+ });
404
+ },
405
+ async idle() {
406
+ for (;;) {
407
+ const before = chain;
408
+ await Promise.all([chain, ...pendingHooks]);
409
+ if (before === chain && pendingHooks.size === 0) return;
410
+ }
411
+ },
412
+ };
413
+ }
414
+
415
+ /** Keeps the music aside for `ms` more (the listener between the agent host's readings, S22); then settle restores it. */
416
+ export function holdMusic(env: NodeJS.ProcessEnv, ms: number): boolean {
417
+ const store = openStore(env);
418
+ const state = store.read();
419
+ if (!state) return false;
420
+ store.write({ ...state, hold: Date.now() + ms });
421
+ return true;
422
+ }
423
+
424
+ /**
425
+ * Runs `command` detached, in its own process group, ended whole (SIGTERM, then SIGKILL) after MUSIC_TIMEOUT_MS.
426
+ * Only what it started is ever signalled. Its output is read when `capture`.
427
+ */
428
+ function run(
429
+ command: string,
430
+ args: string[],
431
+ env: NodeJS.ProcessEnv,
432
+ capture = false,
433
+ ): Promise<{ code: number | null; out: string; timedOut: boolean; error?: string }> {
434
+ return new Promise((resolve) => {
435
+ let child: ChildProcess;
436
+ try {
437
+ child = spawn(command, args, { env, detached: true, stdio: ["ignore", capture ? "pipe" : "ignore", "ignore"] });
438
+ } catch (error) {
439
+ resolve({ code: null, out: "", timedOut: false, error: (error as Error).message });
440
+ return;
441
+ }
442
+ let out = "";
443
+ let timedOut = false;
444
+ child.stdout?.on("data", (chunk: Buffer) => {
445
+ if (out.length < 65536) out += chunk.toString();
446
+ });
447
+ const group = (signal: NodeJS.Signals): void => {
448
+ if (child.pid === undefined) return;
449
+ try {
450
+ process.kill(-child.pid, signal);
451
+ } catch {}
452
+ };
453
+ let kill: NodeJS.Timeout | undefined;
454
+ const ended = (): void => {
455
+ clearTimeout(timer);
456
+ clearTimeout(kill);
457
+ };
458
+ const timer = setTimeout(() => {
459
+ timedOut = true;
460
+ group("SIGTERM");
461
+ kill = setTimeout(() => group("SIGKILL"), 1000);
462
+ kill.unref?.();
463
+ }, MUSIC_TIMEOUT_MS);
464
+ timer.unref?.();
465
+ child.on("error", (error) => {
466
+ ended();
467
+ resolve({ code: null, out, timedOut: false, error: error.message });
468
+ });
469
+ child.on("close", (code) => {
470
+ ended();
471
+ resolve({ code, out, timedOut });
472
+ });
473
+ });
474
+ }
package/src/outputs.ts ADDED
@@ -0,0 +1,105 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { isAbsolute, join } from "node:path";
3
+
4
+ /**
5
+ * Where a reading sounds: this machine's default sink, a PulseAudio/PipeWire server elsewhere, or a listener that
6
+ * synthesizes and plays it itself (S20), reached over SSH.
7
+ */
8
+ export interface Output {
9
+ name: string;
10
+ label: string;
11
+ /** PULSE_SERVER for the player; absent for this machine. */
12
+ pulseServer?: string;
13
+ /** The listener's SSH destination (`you@host`): the agent host sends it the fragments (S20). */
14
+ ssh?: string;
15
+ /** For a listener: the PULSE_SERVER that plays what the agent host synthesizes when the listener cannot (S20). */
16
+ fallback?: string;
17
+ }
18
+
19
+ const NAME = /^[A-Za-z0-9][A-Za-z0-9-]*$/;
20
+ const VALUE_HINT = 'the value must be a PULSE_SERVER string such as "tcp:192.168.1.50:4713"';
21
+ const SSH_HINT = '"ssh" must be a host such as "you@host", without spaces or a leading "-"';
22
+ const FALLBACK_HINT = '"fallback" must be a PULSE_SERVER string such as "unix:/run/user/1000/reply-reader-pulse.sock"';
23
+ /**
24
+ * An SSH destination that ssh cannot take for an option (S20): no leading "-", no whitespace or newline, no control
25
+ * character (C0 with NUL, DEL, C1 with U+0085) and no Unicode line or paragraph separator.
26
+ */
27
+ const SSH_HOST = /^[^-\s\p{Cc}\u2028\u2029][^\s\p{Cc}\u2028\u2029]*$/u;
28
+ const LISTENER_KEYS = ["ssh", "fallback"];
29
+
30
+ /**
31
+ * `local` plus the outputs in `$XDG_CONFIG_HOME/pi-reply-reader/outputs.json`, an object mapping each
32
+ * name to its PULSE_SERVER, or to `{ "ssh": "you@host", "fallback": "<PULSE_SERVER>" }` for a listener that
33
+ * synthesizes (S20; `fallback` optional). Bad entries are skipped and reported in `problems`; nothing throws.
34
+ */
35
+ export function loadOutputs(env: NodeJS.ProcessEnv, hostname: string): { outputs: Output[]; problems: string[] } {
36
+ const outputs: Output[] = [{ name: "local", label: `local (${hostname})` }];
37
+ const problems: string[] = [];
38
+ const path = configFile(env, "outputs.json");
39
+ if (!path) return { outputs, problems };
40
+
41
+ let raw: string;
42
+ try {
43
+ raw = readFileSync(path, "utf8");
44
+ } catch {
45
+ return { outputs, problems };
46
+ }
47
+ let parsed: unknown;
48
+ try {
49
+ parsed = JSON.parse(raw);
50
+ } catch (error) {
51
+ problems.push(`Ignored ${path}: not valid JSON (${(error as Error).message}).`);
52
+ return { outputs, problems };
53
+ }
54
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
55
+ problems.push(`Ignored ${path}: expected an object mapping output names to PULSE_SERVER values.`);
56
+ return { outputs, problems };
57
+ }
58
+
59
+ for (const [name, value] of Object.entries(parsed)) {
60
+ const listener = value !== null && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
61
+ const unknown = listener && Object.keys(listener).find((key) => !LISTENER_KEYS.includes(key));
62
+ const reason =
63
+ name === "local"
64
+ ? "that name is built in"
65
+ : !NAME.test(name)
66
+ ? 'names use letters, digits and "-"'
67
+ : listener
68
+ ? unknown !== undefined
69
+ ? `unknown key "${unknown}" (use "ssh" and "fallback")`
70
+ : typeof listener.ssh !== "string" || !SSH_HOST.test(listener.ssh)
71
+ ? SSH_HINT
72
+ : listener.fallback !== undefined && (typeof listener.fallback !== "string" || listener.fallback.trim() === "")
73
+ ? FALLBACK_HINT
74
+ : undefined
75
+ : typeof value !== "string" || value.trim() === ""
76
+ ? VALUE_HINT
77
+ : undefined;
78
+ if (reason) {
79
+ problems.push(`Ignored output "${name}" in ${path}: ${reason}.`);
80
+ continue;
81
+ }
82
+ if (listener) {
83
+ const ssh = listener.ssh as string;
84
+ const fallback = listener.fallback as string | undefined;
85
+ outputs.push({ name, label: `${name} (listener ${ssh})`, ssh, ...(fallback === undefined ? {} : { fallback }) });
86
+ continue;
87
+ }
88
+ outputs.push({ name, label: `${name} (${value})`, pulseServer: value as string });
89
+ }
90
+ return { outputs, problems };
91
+ }
92
+
93
+ /**
94
+ * `name` in this package's config folder: XDG_CONFIG_HOME, then ~/.config; relative values are ignored,
95
+ * as the XDG spec says. Undefined when neither is usable.
96
+ */
97
+ export function configFile(env: NodeJS.ProcessEnv, name: string): string | undefined {
98
+ const base =
99
+ env.XDG_CONFIG_HOME && isAbsolute(env.XDG_CONFIG_HOME)
100
+ ? env.XDG_CONFIG_HOME
101
+ : env.HOME && isAbsolute(env.HOME)
102
+ ? join(env.HOME, ".config")
103
+ : undefined;
104
+ return base && join(base, "pi-reply-reader", name);
105
+ }
@@ -0,0 +1,105 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { configFile } from "./outputs.ts";
3
+
4
+ /**
5
+ * The key that pauses and resumes readings (S15, L147): Alt+M unless settings.json says otherwise. Esc is never the
6
+ * reader's: it belongs to Pi (it interrupts the agent, closes dialogs).
7
+ *
8
+ * Alt+M is free on every platform: it is not a default in Pi's keybindings (docs/keybindings.md, Windows and WSL
9
+ * included), not a gentle-pi shortcut, and not pi-reply-thread's Alt+R; terminals send it as Esc followed by "m".
10
+ */
11
+ export const DEFAULT_PAUSE_KEY = "alt+m";
12
+
13
+ const SETTINGS = "settings.json";
14
+ const MODIFIERS = ["ctrl", "alt", "shift", "super"] as const;
15
+ /**
16
+ * A letter, a digit or F1 to F12. With ctrl or alt (and maybe shift), terminals send these, with two exceptions
17
+ * `parsePauseKey` rejects: ctrl with a digit and any super key, which only terminals speaking the Kitty keyboard
18
+ * protocol deliver.
19
+ */
20
+ const KEY = /^(?:[a-z0-9]|f(?:[1-9]|1[0-2]))$/;
21
+ /** Why a key only the Kitty keyboard protocol delivers cannot be the pause key. */
22
+ const KITTY_ONLY = "terminals without the Kitty keyboard protocol never send it";
23
+
24
+ /** Pi's default keybindings with a modifier, every platform (docs/keybindings.md), normalized. */
25
+ const PI_KEYS = [
26
+ "alt+b", "alt+backspace", "alt+d", "alt+delete", "alt+down", "alt+enter", "alt+f", "alt+left", "alt+p", "alt+q",
27
+ "alt+right", "alt+up", "alt+v", "alt+y", "alt+z", "ctrl+-", "ctrl+]", "ctrl+a", "ctrl+alt+]", "ctrl+b",
28
+ "ctrl+backspace", "ctrl+c", "ctrl+d", "ctrl+down", "ctrl+e", "ctrl+end", "ctrl+f", "ctrl+g", "ctrl+home", "ctrl+j",
29
+ "ctrl+k", "ctrl+l", "ctrl+left", "ctrl+n", "ctrl+o", "ctrl+p", "ctrl+pagedown", "ctrl+pageup", "ctrl+q", "ctrl+r",
30
+ "ctrl+right", "ctrl+s", "ctrl+shift+down", "ctrl+shift+f", "ctrl+shift+g", "ctrl+shift+up", "ctrl+t", "ctrl+u",
31
+ "ctrl+up", "ctrl+v", "ctrl+w", "ctrl+x", "ctrl+y", "ctrl+z", "ctrl+shift+o", "ctrl+shift+p", "shift+enter",
32
+ "shift+l", "shift+t", "shift+tab",
33
+ ];
34
+ /** gentle-pi's default shortcuts (lib/keymaps.ts, history, todo). */
35
+ const GENTLE_KEYS = [
36
+ "alt+k", "alt+g", "alt+u", "alt+l", "alt+a", "alt+s", "ctrl+shift+a", "ctrl+shift+j", "ctrl+shift+t", "ctrl+shift+r",
37
+ "alt+shift+up", "alt+shift+down",
38
+ ];
39
+ /** Keys a terminal keeps for itself (flow control, suspend) or cannot tell apart from another key. */
40
+ const TERMINAL_KEYS = ["ctrl+s", "ctrl+q", "ctrl+z", "ctrl+c", "ctrl+d", "ctrl+h", "ctrl+i", "ctrl+m"];
41
+
42
+ /** Puts the modifiers of `key` in one order, so "shift+ctrl+p" and "ctrl+shift+p" compare equal. */
43
+ function normalize(key: string): string {
44
+ const parts = key.toLowerCase().split("+");
45
+ const last = parts.pop() ?? "";
46
+ const mods = MODIFIERS.filter((mod) => parts.includes(mod));
47
+ return [...mods, last].join("+");
48
+ }
49
+
50
+ const TAKEN = new Map<string, string>();
51
+ for (const [owner, keys] of [
52
+ ["the terminal", TERMINAL_KEYS],
53
+ ["pi-reply-thread", ["alt+r"]],
54
+ ["gentle-pi", GENTLE_KEYS],
55
+ ["Pi", PI_KEYS],
56
+ ] as const) {
57
+ // The first owner listed wins: the terminal takes ctrl+s before Pi could see it.
58
+ for (const key of keys) if (!TAKEN.has(normalize(key))) TAKEN.set(normalize(key), owner);
59
+ }
60
+
61
+ /** Why `text` cannot be the pause key, or its normalized form. */
62
+ export function parsePauseKey(text: string): { key: string } | { problem: string } {
63
+ const parts = text.trim().toLowerCase().split("+");
64
+ const last = parts.pop() ?? "";
65
+ const known = parts.every((part) => (MODIFIERS as readonly string[]).includes(part)) && new Set(parts).size === parts.length;
66
+ if (!known || !KEY.test(last) || !parts.some((part) => part !== "shift")) {
67
+ return { problem: "it is not a key the reader can use (ctrl or alt, maybe with shift, plus a letter, digit or F1-F12, as alt+m)" };
68
+ }
69
+ if (parts.includes("super") || (parts.includes("ctrl") && /^[0-9]$/.test(last))) return { problem: KITTY_ONLY };
70
+ const key = normalize(text.trim());
71
+ const owner = TAKEN.get(key);
72
+ return owner ? { problem: `${owner} already uses it` } : { key };
73
+ }
74
+
75
+ /** "alt+m" as people read it: "Alt+M". */
76
+ export function keyName(key: string): string {
77
+ return key
78
+ .split("+")
79
+ .map((part) => (part.length === 1 ? part.toUpperCase() : part[0].toUpperCase() + part.slice(1)))
80
+ .join("+");
81
+ }
82
+
83
+ /**
84
+ * The pause key from `pauseKey` in `$XDG_CONFIG_HOME/pi-reply-reader/settings.json`, else Alt+M. An invalid or taken
85
+ * key means Alt+M and a `problem` for the user. A missing, unreadable or invalid file means Alt+M without one (the
86
+ * speed already reports a broken file). Nothing throws.
87
+ */
88
+ export function loadPauseKey(env: NodeJS.ProcessEnv): { key: string; problem?: string } {
89
+ const path = configFile(env, SETTINGS);
90
+ if (!path) return { key: DEFAULT_PAUSE_KEY };
91
+ let parsed: unknown;
92
+ try {
93
+ parsed = JSON.parse(readFileSync(path, "utf8"));
94
+ } catch {
95
+ return { key: DEFAULT_PAUSE_KEY };
96
+ }
97
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || !("pauseKey" in parsed)) return { key: DEFAULT_PAUSE_KEY };
98
+ const { pauseKey } = parsed as { pauseKey: unknown };
99
+ const result = typeof pauseKey === "string" ? parsePauseKey(pauseKey) : { problem: "it must be a string, as \"alt+m\"" };
100
+ if ("key" in result) return result;
101
+ return {
102
+ key: DEFAULT_PAUSE_KEY,
103
+ problem: `Ignored pauseKey ${JSON.stringify(pauseKey)} in ${path}: ${result.problem}. ${keyName(DEFAULT_PAUSE_KEY)} pauses and resumes readings.`,
104
+ };
105
+ }