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.
@@ -0,0 +1,423 @@
1
+ import { type ChildProcess, spawn } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+ import type { Output } from "./outputs.ts";
4
+ import { OWNER_VAR, ownerTag, PLAYER_MARK, playerTimeout, reapOrphans, terminate, track, withDeathSignal } from "./player.ts";
5
+ import { DEFAULT_SPEED } from "./settings.ts";
6
+ import type { Boundary, Fragment } from "./speech-text.ts";
7
+ import { onPath, type Speaker, type Voice } from "./voice.ts";
8
+
9
+ /** What one segment asks of Supertonic; the real loader wraps `generationConfig` in sherpa's GenerationConfig. */
10
+ export interface SherpaRequest {
11
+ text: string;
12
+ generationConfig: { sid: number; speed: number; numSteps: number; extra: { lang: string; seed: number } };
13
+ /**
14
+ * Called with each synthesized chunk; returning false stops the generation. Always passed: on Bun,
15
+ * which runs Pi, sherpa's generateAsync without it fails with "Invalid argument".
16
+ */
17
+ onProgress: (info: { samples: Float32Array; progress: number }) => boolean;
18
+ }
19
+
20
+ /** The slice of sherpa-onnx-node's OfflineTts a reading uses. */
21
+ export interface SherpaTts {
22
+ sampleRate: number;
23
+ generateAsync(request: SherpaRequest): Promise<{ samples: Float32Array }>;
24
+ }
25
+
26
+ export interface Reading {
27
+ /** Settles when the audio ends or the reading is stopped; rejects with a message for the user. */
28
+ readonly done: Promise<void>;
29
+ stop(): void;
30
+ /**
31
+ * The index, in the fragments given, of the fragment being heard now (S15: a paused reading resumes from its start),
32
+ * or of the next one during a pause after its fragment. 0 before any audio.
33
+ */
34
+ position(): number;
35
+ }
36
+
37
+ const PAPLAY_MISSING =
38
+ "Cannot play: paplay was not found on PATH (it comes with libpulse on Arch, pulseaudio-utils on Debian and Ubuntu).";
39
+
40
+ /** Supertonic's default seed is random; a fixed one makes the same text always sound the same. */
41
+ const SEED = 42;
42
+
43
+ /**
44
+ * How far behind the time since a fragment was handed over the player is taken to be (S15): its connection, Pulse's
45
+ * buffer and pipe make what is heard lag what was written, so a pause rather resumes a little early than skip words.
46
+ */
47
+ const HEARD_LAG_MS = 500;
48
+
49
+ /**
50
+ * Speaks `fragments` (from `speechNarration`, or `spokenFragments` for plain text) with `speaker` at `speed` (Supertonic's voice speed, 1.1 by default; our pauses do not
51
+ * change with it) on `output`. Supertonic synthesizes one sentence at a time, so the first
52
+ * audio comes after one sentence instead of the whole reply, and the next sentence is synthesized while the
53
+ * current one plays (at most LOOKAHEAD wait for the player); each sentence loses its own leading and
54
+ * trailing silence and is followed right away by our pause for its boundary, then goes to `paplay` as raw 16-bit
55
+ * mono PCM, on this machine's default sink or, for a named output, on its PULSE_SERVER. Nothing here
56
+ * throws: every failure ends in `done`, and `stop()` ends the player and settles `done` quietly.
57
+ *
58
+ * A player that hangs (S13), such as paplay waiting forever on a Pulse server behind a broken SSH tunnel, is ended:
59
+ * when it takes no audio for the player timeout (REPLY_READER_PLAYER_TIMEOUT seconds in `env`, 15 by default) while
60
+ * audio waits for it, or does not end within the audio's length plus that timeout once it has all of it, it is killed
61
+ * and `done` rejects with `Playback on "<output>" failed: timed out` (a player that had already exited by then is
62
+ * not). Every kill is SIGTERM, then SIGKILL two seconds later; a player left by a reader that died is ended when the
63
+ * next reading starts, and this process's player dies with it (through `setpriv --pdeathsig KILL` when available, so
64
+ * even a reader killed outright takes it along).
65
+ */
66
+ export function startReading(options: {
67
+ voice: Voice;
68
+ speaker: Speaker;
69
+ /** Spoken in order, each followed by the pause for its own boundary; their text is never split again. */
70
+ fragments: readonly Fragment[];
71
+ output: Output;
72
+ env: NodeJS.ProcessEnv;
73
+ loadSherpa?: (voice: Voice) => Promise<SherpaTts>;
74
+ speed?: number;
75
+ /** Told the player's pid once it starts, so another session can stop this reading (T21). */
76
+ onPlayer?: (pid: number) => void;
77
+ /**
78
+ * The player timeout of S13 in milliseconds; REPLY_READER_PLAYER_TIMEOUT in `env` (or 15 s) when not given. Callers
79
+ * pass playerTimeoutMs(env, warn), which also warns about an invalid value.
80
+ */
81
+ timeoutMs?: number;
82
+ /**
83
+ * Seconds of silence the player gets before the first fragment (S14: the gap before a reading that waited in the
84
+ * line). Written at once, so the first synthesis overlaps it.
85
+ */
86
+ leadSilence?: number;
87
+ }): Reading {
88
+ const { voice, speaker, fragments: list, output, env, loadSherpa = loadSherpaTts, speed = DEFAULT_SPEED, onPlayer } = options;
89
+ let player: ChildProcess | undefined;
90
+ let stopped = false;
91
+ /** Set by the watchdog (S13): the player took no audio, or did not end, in time. */
92
+ let timedOut = false;
93
+ /** Set when the deadline passed after the player exited (S13 g): it settles on its exit, not on its pipes. */
94
+ let overdue = false;
95
+ /** Settles `done` from the player's exit status once it exited; set by `finished`. */
96
+ let settleExited: (() => void) | undefined;
97
+ /**
98
+ * When each fragment handed to the player starts being heard (S15), modelled as real-time playback that waits for
99
+ * audio when it runs out: a fragment starts when it is handed over or when the one before it ends, whichever is later.
100
+ */
101
+ const heard: { index: number; at: number }[] = [];
102
+ let heardUntil = 0;
103
+ const handed = (index: number, samples: number, sampleRate: number): void => {
104
+ const at = Math.max(Date.now(), heardUntil);
105
+ heard.push({ index, at });
106
+ heardUntil = at + (samples / sampleRate) * 1000;
107
+ };
108
+
109
+ const run = async (): Promise<void> => {
110
+ const paplay = onPath("paplay", env);
111
+ if (!paplay) throw new Error(PAPLAY_MISSING);
112
+
113
+ let tts: SherpaTts;
114
+ try {
115
+ tts = await loadSherpa(voice);
116
+ } catch (error) {
117
+ throw new Error(`Speech synthesis failed: ${(error as Error).message}`);
118
+ }
119
+ if (stopped) return;
120
+
121
+ const playerEnv = { ...env, ...(output.pulseServer ? { PULSE_SERVER: output.pulseServer } : {}), [OWNER_VAR]: ownerTag() };
122
+ const args = ["--raw", "--format=s16le", `--rate=${tts.sampleRate}`, "--channels=1", PLAYER_MARK, "--stream-name=reply"];
123
+ // Players left playing or hung by a reader that died (S13) go before this one starts.
124
+ reapOrphans();
125
+ // Through setpriv, the player gets SIGKILL when this process dies however it dies (S13 h).
126
+ const [command, commandArgs] = withDeathSignal(onPath("setpriv", env), paplay, args);
127
+ const child = spawn(command, commandArgs, { env: playerEnv, stdio: ["pipe", "ignore", "pipe"] });
128
+ player = child;
129
+ track(child);
130
+ // A player that quits early closes its stdin; writing to it must not crash Pi.
131
+ child.stdin?.on("error", () => {});
132
+ const playback = finished(child, `Playback on "${output.name}" failed`);
133
+ if (child.pid !== undefined) onPlayer?.(child.pid);
134
+ let playerGone = false;
135
+ const gone = playback.then(
136
+ () => {},
137
+ () => {},
138
+ );
139
+ gone.then(() => (playerGone = true));
140
+ // A player that exited takes nothing more, even before its pipes close.
141
+ child.once("exit", () => (playerGone = true));
142
+
143
+ // The watchdog (S13): armed while a chunk waits for the player, and once all audio is handed over.
144
+ const timeout = options.timeoutMs ?? playerTimeout(env).ms;
145
+ let watchdog: NodeJS.Timeout | undefined;
146
+ const arm = (ms: number): void => {
147
+ clearTimeout(watchdog);
148
+ // setTimeout takes at most 2^31-1 ms (about 24.8 days); a longer wait would fire at once.
149
+ watchdog = setTimeout(() => {
150
+ if (stopped) return;
151
+ // A player that already exited is not hung (S13 g): settle on how it exited, without waiting for pipes a
152
+ // process it left behind may still hold.
153
+ if (exited(child)) {
154
+ overdue = true;
155
+ settleExited?.();
156
+ return;
157
+ }
158
+ timedOut = true;
159
+ playerGone = true;
160
+ terminate(child);
161
+ taken?.();
162
+ }, Math.min(ms, MAX_TIMER_MS));
163
+ };
164
+ gone.then(() => clearTimeout(watchdog));
165
+
166
+ // Fragments handed over that the pipe has not taken whole yet. Each fragment goes in CHUNK-byte writes, one at a
167
+ // time, so the watchdog sees a player that keeps taking a long fragment as alive.
168
+ let queued = 0;
169
+ let taken: (() => void) | undefined;
170
+ const backlog: { chunk: Buffer; last: boolean }[] = [];
171
+ let writing = false;
172
+ let ending = false;
173
+ let samplesSent = 0;
174
+ const pump = (): void => {
175
+ if (writing) return;
176
+ if (playerGone) backlog.length = 0;
177
+ const next = backlog.shift();
178
+ if (!next) {
179
+ if (ending) {
180
+ ending = false;
181
+ child.stdin?.end();
182
+ // The player has all the audio: it must end within the audio's length plus the timeout.
183
+ if (!playerGone) arm(Math.round((samplesSent / tts.sampleRate) * 1000) + timeout);
184
+ }
185
+ return;
186
+ }
187
+ writing = true;
188
+ arm(timeout);
189
+ child.stdin?.write(next.chunk, (error) => {
190
+ writing = false;
191
+ clearTimeout(watchdog);
192
+ // A write that fails means the player closed its input: it will take nothing more.
193
+ if (error) playerGone = true;
194
+ if (next.last) {
195
+ queued--;
196
+ taken?.();
197
+ }
198
+ pump();
199
+ });
200
+ };
201
+ const send = (audio: Float32Array): void => {
202
+ queued++;
203
+ samplesSent += audio.length;
204
+ const bytes = pcm16(audio, speaker.gain);
205
+ for (let at = 0; at < bytes.length; at += CHUNK) {
206
+ backlog.push({ chunk: bytes.subarray(at, at + CHUNK), last: at + CHUNK >= bytes.length });
207
+ }
208
+ pump();
209
+ };
210
+ const close = (): void => {
211
+ ending = true;
212
+ pump();
213
+ };
214
+
215
+ const lead = Math.round((options.leadSilence ?? 0) * tts.sampleRate);
216
+ if (lead > 0) {
217
+ handed(0, lead, tts.sampleRate);
218
+ send(new Float32Array(lead));
219
+ }
220
+ // Samples of pause already written after the last audible fragment; undefined before the first one.
221
+ let paused: number | undefined;
222
+ for (const [index, fragment] of list.entries()) {
223
+ // Synthesize ahead, but stop while LOOKAHEAD fragments still wait for the player to take them.
224
+ while (queued >= LOOKAHEAD && !stopped && !playerGone) {
225
+ await Promise.race([new Promise<void>((resolve) => (taken = resolve)), gone]);
226
+ }
227
+ if (stopped || playerGone) break;
228
+ let samples: Float32Array;
229
+ try {
230
+ ({ samples } = await tts.generateAsync({
231
+ text: fragment.text,
232
+ generationConfig: { sid: speaker.sid, speed, numSteps: 8, extra: { lang: "es", seed: SEED } },
233
+ onProgress: () => !stopped && !playerGone,
234
+ }));
235
+ } catch (error) {
236
+ if (stopped || playerGone) break;
237
+ throw new Error(`Speech synthesis failed: ${(error as Error).message}`);
238
+ }
239
+ if (stopped || playerGone) break;
240
+ const speech = trimSilence(samples, speaker.gain, tts.sampleRate);
241
+ // The last fragment's pause is never written.
242
+ const after = index === list.length - 1 ? 0 : Math.round(PAUSES[fragment.after] * tts.sampleRate);
243
+ // A silent fragment is dropped, but a stronger boundary it ends still counts: top up the pause written.
244
+ if (!speech) {
245
+ if (paused !== undefined && after > paused) {
246
+ handed(index + 1, after - paused, tts.sampleRate);
247
+ send(new Float32Array(after - paused));
248
+ paused = after;
249
+ }
250
+ continue;
251
+ }
252
+ // Each pause goes right after its own fragment, so the next synthesis overlaps it too.
253
+ handed(index, speech.length, tts.sampleRate);
254
+ if (after) handed(index + 1, after, tts.sampleRate);
255
+ send(after ? concat(speech, new Float32Array(after)) : speech);
256
+ paused = after;
257
+ }
258
+ close();
259
+ await playback;
260
+ };
261
+
262
+ const done = run().then(
263
+ () => undefined,
264
+ (error: Error) => {
265
+ if (player) terminate(player);
266
+ if (!stopped) throw error;
267
+ },
268
+ );
269
+ return {
270
+ done,
271
+ stop() {
272
+ stopped = true;
273
+ if (player) terminate(player);
274
+ },
275
+ position() {
276
+ const now = Date.now() - HEARD_LAG_MS;
277
+ let index = 0;
278
+ for (const segment of heard) {
279
+ if (segment.at > now) break;
280
+ index = segment.index;
281
+ }
282
+ return Math.min(index, Math.max(0, list.length - 1));
283
+ },
284
+ };
285
+
286
+ /** Resolves when `child` exits cleanly or was stopped; rejects with `prefix` and its last error line. */
287
+ function finished(child: ChildProcess, prefix: string): Promise<void> {
288
+ let stderr = "";
289
+ child.stderr?.on("data", (chunk: Buffer) => (stderr = (stderr + chunk.toString()).slice(-4096)));
290
+ return new Promise((resolve, reject) => {
291
+ const settle = (code: number | null, signal: NodeJS.Signals | null): void => {
292
+ if (stopped) return resolve();
293
+ if (timedOut) return reject(new Error(`${prefix}: timed out`));
294
+ if (code === 0) return resolve();
295
+ const last = stderr.trim().split("\n").at(-1)?.trim();
296
+ reject(new Error(`${prefix}: ${last || (signal ? `killed by ${signal}` : `exit code ${code}`)}`));
297
+ };
298
+ settleExited = () => {
299
+ if (child.exitCode !== null || child.signalCode !== null) settle(child.exitCode, child.signalCode);
300
+ };
301
+ child.on("error", (error) => reject(new Error(`${prefix}: ${error.message}`)));
302
+ // After stop, a timeout or a passed deadline, do not wait for pipes a grandchild may still hold open.
303
+ child.on("exit", (code, signal) => {
304
+ if (stopped || timedOut || overdue) settle(code, signal);
305
+ });
306
+ child.on("close", settle);
307
+ });
308
+ }
309
+ }
310
+
311
+ /** The longest delay setTimeout takes; a longer one fires at once with a TimeoutOverflowWarning. */
312
+ const MAX_TIMER_MS = 2 ** 31 - 1;
313
+
314
+ /**
315
+ * Whether `child` already exited: its exit was seen, or it is a zombie whose exit event has not come yet (the deadline
316
+ * and the exit can land in the same turn of the event loop).
317
+ */
318
+ function exited(child: ChildProcess): boolean {
319
+ if (child.exitCode !== null || child.signalCode !== null) return true;
320
+ try {
321
+ const stat = readFileSync(`/proc/${child.pid}/stat`, "utf8");
322
+ return stat.slice(stat.lastIndexOf(")") + 2, stat.lastIndexOf(")") + 3) === "Z";
323
+ } catch {
324
+ return false;
325
+ }
326
+ }
327
+
328
+ /** Bytes per write to the player: about 0.37 s of audio at 44.1 kHz, well under a Linux pipe's 64 KiB. */
329
+ const CHUNK = 32 * 1024;
330
+
331
+ /**
332
+ * Synthesized fragments that may wait for the player at once (T26): the one playing and the next one, ready.
333
+ * Synthesis is one call at a time and, under load, slower than real time (L70), so a deeper queue would rarely
334
+ * fill; when it is faster, one ready fragment already hides the next synthesis. Two keeps a long reply out of
335
+ * memory (a fragment is about 0.3-1 MB of PCM) and a stuck player stops synthesis after two fragments.
336
+ */
337
+ const LOOKAHEAD = 2;
338
+
339
+ /**
340
+ * Seconds of silence after a fragment, by what follows it: a sentence on the same line, a line, a blank line
341
+ * (also after a heading or bold-only line). Longer than the voice's own 0.08-0.26 s at `,`, `;` and `:` (L39).
342
+ */
343
+ const PAUSES: Record<Boundary, number> = { sentence: 0.35, line: 0.5, paragraph: 0.75 };
344
+
345
+ /** Windows quieter than this, after the speaker's gain, count as silence (-45 dBFS RMS over 10 ms). */
346
+ const SILENCE = 10 ** (-45 / 20);
347
+ const WINDOW_SECONDS = 0.01;
348
+ /** Kept on each side of the first and last sound, so soft speech edges are not cut. */
349
+ const MARGIN_SECONDS = 0.04;
350
+
351
+ /**
352
+ * Supertonic pads every fragment with about 0.4-0.6 s of silence before and 0.6-0.7 s after (L36);
353
+ * this cuts it to the margin. Undefined when no window is above the threshold.
354
+ */
355
+ function trimSilence(samples: Float32Array, gain: number, sampleRate: number): Float32Array | undefined {
356
+ const window = Math.max(1, Math.round(sampleRate * WINDOW_SECONDS));
357
+ let first = -1;
358
+ let last = -1;
359
+ for (let start = 0; start < samples.length; start += window) {
360
+ const end = Math.min(start + window, samples.length);
361
+ let sum = 0;
362
+ for (let i = start; i < end; i++) sum += (samples[i] * gain) ** 2;
363
+ if (Math.sqrt(sum / (end - start)) <= SILENCE) continue;
364
+ if (first < 0) first = start;
365
+ last = end;
366
+ }
367
+ if (first < 0) return undefined;
368
+ const margin = Math.round(sampleRate * MARGIN_SECONDS);
369
+ return samples.subarray(Math.max(0, first - margin), Math.min(samples.length, last + margin));
370
+ }
371
+
372
+ function concat(a: Float32Array, b: Float32Array): Float32Array {
373
+ const out = new Float32Array(a.length + b.length);
374
+ out.set(a);
375
+ out.set(b, a.length);
376
+ return out;
377
+ }
378
+
379
+ /** Samples below this level pass through the limiter unchanged (-6 dBFS). */
380
+ const KNEE = 0.5;
381
+ /** No sample leaves the limiter above -1 dBFS, rounded down to a whole PCM step so rounding cannot pass it. */
382
+ const CEILING = Math.floor(10 ** (-1 / 20) * 32767) / 32767;
383
+
384
+ /**
385
+ * Float samples to 16-bit little-endian PCM with the speaker's fixed gain. Above the knee a tanh curve
386
+ * bends peaks smoothly toward the ceiling, so they never clip or wrap around.
387
+ */
388
+ function pcm16(samples: Float32Array, gain: number): Buffer {
389
+ const out = Buffer.alloc(samples.length * 2);
390
+ for (let i = 0; i < samples.length; i++) {
391
+ const x = samples[i] * gain;
392
+ const level = Math.abs(x);
393
+ const limited = level <= KNEE ? x : Math.sign(x) * (KNEE + (CEILING - KNEE) * Math.tanh((level - KNEE) / (CEILING - KNEE)));
394
+ out.writeInt16LE(Math.round(limited * 32767), i * 2);
395
+ }
396
+ return out;
397
+ }
398
+
399
+ const loaded = new Map<string, Promise<SherpaTts>>();
400
+
401
+ /** Loads the model once; loading takes about a second. */
402
+ function loadSherpaTts(voice: Voice): Promise<SherpaTts> {
403
+ const key = voice.supertonic.ttsJson;
404
+ let tts = loaded.get(key);
405
+ if (!tts) {
406
+ // sherpa-onnx-node is CommonJS with a native addon.
407
+ // A plain import, not createRequire: Pi's compiled extension loader resolves only imports.
408
+ tts = import("sherpa-onnx-node").then(async (module) => {
409
+ const { OfflineTts, GenerationConfig } = module.default ?? module;
410
+ const engine = await OfflineTts.createAsync({
411
+ model: { supertonic: voice.supertonic, numThreads: 2, provider: "cpu", debug: 0 },
412
+ });
413
+ return {
414
+ sampleRate: engine.sampleRate,
415
+ generateAsync: ({ generationConfig, ...request }: SherpaRequest) =>
416
+ engine.generateAsync({ ...request, generationConfig: new GenerationConfig(generationConfig) }),
417
+ };
418
+ });
419
+ tts.catch(() => loaded.delete(key));
420
+ loaded.set(key, tts);
421
+ }
422
+ return tts;
423
+ }
package/src/player.ts ADDED
@@ -0,0 +1,255 @@
1
+ import { type ChildProcess, spawnSync } from "node:child_process";
2
+ import { readdirSync, readFileSync, readlinkSync, statSync } from "node:fs";
3
+
4
+ /** Every player we start carries this argument, so a pid can be told apart from an unrelated process. */
5
+ export const PLAYER_MARK = "--client-name=pi-reply-reader";
6
+
7
+ /**
8
+ * Set in each player's environment to `<pid>:<start time>` of the process that started it (S13), so a later reading
9
+ * can tell a player whose reader is gone from one that still has a reader, and from a paplay that is not ours.
10
+ */
11
+ export const OWNER_VAR = "PI_REPLY_READER_OWNER";
12
+
13
+ /** How long a player gets to end after SIGTERM before SIGKILL (S13): paplay stuck connecting may ignore SIGTERM. */
14
+ export const KILL_GRACE_MS = 2000;
15
+
16
+ /** The value of OWNER_VAR for players started by this process. */
17
+ export function ownerTag(): string {
18
+ return `${process.pid}:${startTime(process.pid) ?? ""}`;
19
+ }
20
+
21
+ const ending = new WeakSet<ChildProcess>();
22
+
23
+ /** SIGTERM to a player we started, then SIGKILL after KILL_GRACE_MS if it has not exited. Never throws. */
24
+ export function terminate(child: ChildProcess): void {
25
+ if (child.exitCode !== null || child.signalCode !== null) return;
26
+ try {
27
+ child.kill("SIGTERM");
28
+ } catch {}
29
+ if (ending.has(child)) return;
30
+ ending.add(child);
31
+ const timer = setTimeout(() => {
32
+ if (child.exitCode !== null || child.signalCode !== null) return;
33
+ try {
34
+ child.kill("SIGKILL");
35
+ } catch {}
36
+ }, KILL_GRACE_MS);
37
+ child.once("exit", () => clearTimeout(timer));
38
+ }
39
+
40
+ /** How often a player signalled by pid is checked for having ended during its grace. */
41
+ const POLL_MS = 50;
42
+ /** Players signalled by terminatePid whose grace has not run out, each settling when it ended or was SIGKILLed. */
43
+ const signalled = new Set<Promise<void>>();
44
+
45
+ /**
46
+ * SIGTERM to the player `pid` (started at `start`), then SIGKILL after KILL_GRACE_MS if that same player of ours is
47
+ * still there. Its timer does not keep this process alive: a process about to exit awaits signalledPlayersEnded()
48
+ * first. Never throws.
49
+ */
50
+ export function terminatePid(pid: number, start: string | undefined): void {
51
+ try {
52
+ process.kill(pid, "SIGTERM");
53
+ } catch {
54
+ return;
55
+ }
56
+ const began = Date.now();
57
+ const ended = new Promise<void>((done) => {
58
+ const timer = setInterval(() => {
59
+ if (isPlayer(pid, start) && Date.now() - began < KILL_GRACE_MS) return;
60
+ clearInterval(timer);
61
+ if (isPlayer(pid, start)) {
62
+ try {
63
+ process.kill(pid, "SIGKILL");
64
+ } catch {}
65
+ }
66
+ done();
67
+ }, POLL_MS);
68
+ timer.unref();
69
+ });
70
+ signalled.add(ended);
71
+ ended.then(() => signalled.delete(ended));
72
+ }
73
+
74
+ /**
75
+ * Settles once every player this process signalled with terminatePid (a reaped orphan, a lock takeover) has exited or
76
+ * been SIGKILLed (S13 e), so a command that exits right after never cuts the SIGKILL short.
77
+ */
78
+ export async function signalledPlayersEnded(): Promise<void> {
79
+ if (signalled.size === 0) return;
80
+ // The grace timers are unref'd so they never hold Pi; this one holds the event loop while we wait for them.
81
+ const hold = setInterval(() => {}, KILL_GRACE_MS);
82
+ try {
83
+ await Promise.all([...signalled]);
84
+ } finally {
85
+ clearInterval(hold);
86
+ }
87
+ }
88
+
89
+ const live = new Set<ChildProcess>();
90
+ let exitHooked = false;
91
+
92
+ /**
93
+ * Keeps `child` until it exits; if this process exits first (Pi quitting without session_shutdown, the CLI's
94
+ * process.exit), the player is killed with it instead of playing or hanging on, orphaned (S13).
95
+ */
96
+ export function track(child: ChildProcess): void {
97
+ live.add(child);
98
+ child.once("exit", () => live.delete(child));
99
+ if (exitHooked) return;
100
+ exitHooked = true;
101
+ process.on("exit", () => {
102
+ for (const player of live) {
103
+ try {
104
+ player.kill("SIGKILL");
105
+ } catch {}
106
+ }
107
+ });
108
+ }
109
+
110
+ /**
111
+ * Ends every player whose reader is gone (S13): a process of this user, in this process's PID namespace, whose command
112
+ * line carries PLAYER_MARK and whose OWNER_VAR names a process that no longer runs (a Pi killed with SIGKILL, say). A
113
+ * paplay without both marks, whose reader still runs, or in another PID namespace (or one that cannot be read: an
114
+ * owner pid means something only in its own namespace, so a reader in a sandbox keeps its player), is never touched.
115
+ * A listener's `reply-reader --serve` (S20) carries PLAYER_MARK too, but is never reaped here: an OWNER_VAR it got from
116
+ * the agent host (ssh SendEnv) names a process of another machine; it ends itself when its standard input closes.
117
+ * Returns the pids it signalled; nothing where /proc is missing.
118
+ */
119
+ export function reapOrphans(): number[] {
120
+ let names: string[];
121
+ const namespace = pidNamespace("self");
122
+ if (namespace === undefined) return [];
123
+ try {
124
+ names = readdirSync("/proc");
125
+ } catch {
126
+ return [];
127
+ }
128
+ const uid = process.getuid?.();
129
+ const reaped: number[] = [];
130
+ for (const name of names) {
131
+ if (!/^\d+$/.test(name)) continue;
132
+ const pid = Number(name);
133
+ if (pid === process.pid) continue;
134
+ try {
135
+ if (uid !== undefined && statSync(`/proc/${pid}`).uid !== uid) continue;
136
+ const args = readFileSync(`/proc/${pid}/cmdline`, "utf8").split("\0");
137
+ if (!args.includes(PLAYER_MARK) || isListenerServe(args)) continue;
138
+ if (pidNamespace(String(pid)) !== namespace) continue;
139
+ const tag = readFileSync(`/proc/${pid}/environ`, "utf8")
140
+ .split("\0")
141
+ .find((entry) => entry.startsWith(`${OWNER_VAR}=`));
142
+ if (!tag) continue;
143
+ const [owner, start] = tag.slice(OWNER_VAR.length + 1).split(":");
144
+ const ownerPid = Number(owner);
145
+ if (!Number.isInteger(ownerPid) || ownerPid <= 0) continue;
146
+ if (sameProcess(ownerPid, start || undefined)) continue;
147
+ terminatePid(pid, startTime(pid));
148
+ reaped.push(pid);
149
+ } catch {}
150
+ }
151
+ return reaped;
152
+ }
153
+
154
+ /**
155
+ * Whether a command line is a listener's `reply-reader --serve` (S20): "--serve" right after the path of the
156
+ * reply-reader script (`…/reply-reader`, `…/reply-reader.ts` or `.js`). The agent host's ssh child, whose remote
157
+ * command is the bare word `reply-reader`, does not match, so an orphaned one is still reaped.
158
+ */
159
+ export function isListenerServe(args: readonly string[]): boolean {
160
+ const at = args.indexOf("--serve");
161
+ if (at < 1) return false;
162
+ const script = args[at - 1];
163
+ return script.includes("/") && /^reply-reader(\.[cm]?[jt]s)?$/.test(script.slice(script.lastIndexOf("/") + 1));
164
+ }
165
+
166
+ /** The PID namespace of `/proc/<pid>` ("self" for this process), as `pid:[inode]`; undefined when unreadable. */
167
+ function pidNamespace(pid: string): string | undefined {
168
+ try {
169
+ return readlinkSync(`/proc/${pid}/ns/pid`);
170
+ } catch {
171
+ return undefined;
172
+ }
173
+ }
174
+
175
+ /** The player timeout of S13 when REPLY_READER_PLAYER_TIMEOUT is unset or invalid. */
176
+ const DEFAULT_TIMEOUT_SECONDS = 15;
177
+ const MIN_TIMEOUT_SECONDS = 5;
178
+ const MAX_TIMEOUT_SECONDS = 86400;
179
+ /** The warning for an invalid REPLY_READER_PLAYER_TIMEOUT (S13 f). */
180
+ export const PLAYER_TIMEOUT_HINT = `REPLY_READER_PLAYER_TIMEOUT must be a number of seconds from ${MIN_TIMEOUT_SECONDS} to ${MAX_TIMEOUT_SECONDS}; using ${DEFAULT_TIMEOUT_SECONDS}.`;
181
+
182
+ /**
183
+ * The player timeout of S13 in milliseconds: REPLY_READER_PLAYER_TIMEOUT, whole or fractional seconds from 5 to 86400,
184
+ * else 15 s; any value set but outside that (empty, `0`, `abc`, `3000000`) also returns the warning.
185
+ */
186
+ export function playerTimeout(env: NodeJS.ProcessEnv): { ms: number; problem?: string } {
187
+ const value = env.REPLY_READER_PLAYER_TIMEOUT;
188
+ if (value === undefined) return { ms: DEFAULT_TIMEOUT_SECONDS * 1000 };
189
+ const text = value.trim();
190
+ const seconds = /^\d+(\.\d+)?$/.test(text) ? Number(text) : Number.NaN;
191
+ if (seconds >= MIN_TIMEOUT_SECONDS && seconds <= MAX_TIMEOUT_SECONDS) return { ms: Math.round(seconds * 1000) };
192
+ return { ms: DEFAULT_TIMEOUT_SECONDS * 1000, problem: PLAYER_TIMEOUT_HINT };
193
+ }
194
+
195
+ let timeoutWarned = false;
196
+
197
+ /** playerTimeout's milliseconds, telling `warn` about an invalid value once per process (S13 f). */
198
+ export function playerTimeoutMs(env: NodeJS.ProcessEnv, warn: (message: string) => void): number {
199
+ const { ms, problem } = playerTimeout(env);
200
+ if (problem && !timeoutWarned) {
201
+ timeoutWarned = true;
202
+ warn(problem);
203
+ }
204
+ return ms;
205
+ }
206
+
207
+ const deathSignal = new Map<string, boolean>();
208
+
209
+ /**
210
+ * The command and arguments that start `command` so it gets SIGKILL when this process dies (S13 h), however it dies:
211
+ * `setpriv --pdeathsig KILL` when setpriv (`setpriv`, found by the caller on PATH) runs and supports it, else
212
+ * `command` alone. Checked under Pi's Bun (T37): a player started through it from the JS thread is not cut while its
213
+ * reader runs, and dies when the reader is SIGKILLed.
214
+ */
215
+ export function withDeathSignal(setpriv: string | undefined, command: string, args: string[]): [string, string[]] {
216
+ if (!setpriv) return [command, args];
217
+ let works = deathSignal.get(setpriv);
218
+ if (works === undefined) {
219
+ const check = spawnSync(setpriv, ["--pdeathsig", "KILL", "/bin/sh", "-c", ":"], { stdio: "ignore", timeout: 2000 });
220
+ works = check.status === 0;
221
+ deathSignal.set(setpriv, works);
222
+ }
223
+ return works ? [setpriv, ["--pdeathsig", "KILL", command, ...args]] : [command, args];
224
+ }
225
+
226
+ /** A live process of this user with that pid, started when recorded (when recorded). */
227
+ export function sameProcess(pid: number, start: string | undefined): boolean {
228
+ try {
229
+ process.kill(pid, 0);
230
+ } catch {
231
+ return false;
232
+ }
233
+ return start === undefined || startTime(pid) === start;
234
+ }
235
+
236
+ /** Guards against pid reuse: only a live player we started, of this user, may be signalled. */
237
+ export function isPlayer(pid: number, start: string | undefined): boolean {
238
+ if (!sameProcess(pid, start)) return false;
239
+ try {
240
+ if (process.getuid && statSync(`/proc/${pid}`).uid !== process.getuid()) return false;
241
+ return readFileSync(`/proc/${pid}/cmdline`, "utf8").split("\0").includes(PLAYER_MARK);
242
+ } catch {
243
+ return false;
244
+ }
245
+ }
246
+
247
+ /** Field 22 of /proc/<pid>/stat, the process start time; undefined where /proc is missing. */
248
+ export function startTime(pid: number): string | undefined {
249
+ try {
250
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
251
+ return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
252
+ } catch {
253
+ return undefined;
254
+ }
255
+ }