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.
@@ -1,23 +1,54 @@
1
1
  import { spawn } from "node:child_process";
2
- import { PLAYER_MARK } from "./reading-lock.js";
2
+ import { readFileSync } from "node:fs";
3
+ import { OWNER_VAR, ownerTag, PLAYER_MARK, playerTimeout, reapOrphans, terminate, track, withDeathSignal } from "./player.js";
3
4
  import { DEFAULT_SPEED } from "./settings.js";
4
5
  import { onPath } from "./voice.js";
5
6
  const PAPLAY_MISSING = "Cannot play: paplay was not found on PATH (it comes with libpulse on Arch, pulseaudio-utils on Debian and Ubuntu).";
6
7
  /** Supertonic's default seed is random; a fixed one makes the same text always sound the same. */
7
8
  const SEED = 42;
8
9
  /**
9
- * Speaks `text` with `speaker` at `speed` (Supertonic's voice speed, 1.1 by default; our pauses do not
10
+ * How far behind the time since a fragment was handed over the player is taken to be (S15): its connection, Pulse's
11
+ * buffer and pipe make what is heard lag what was written, so a pause rather resumes a little early than skip words.
12
+ */
13
+ const HEARD_LAG_MS = 500;
14
+ /**
15
+ * 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
10
16
  * change with it) on `output`. Supertonic synthesizes one sentence at a time, so the first
11
17
  * audio comes after one sentence instead of the whole reply, and the next sentence is synthesized while the
12
18
  * current one plays (at most LOOKAHEAD wait for the player); each sentence loses its own leading and
13
19
  * trailing silence and is followed right away by our pause for its boundary, then goes to `paplay` as raw 16-bit
14
20
  * mono PCM, on this machine's default sink or, for a named output, on its PULSE_SERVER. Nothing here
15
21
  * throws: every failure ends in `done`, and `stop()` ends the player and settles `done` quietly.
22
+ *
23
+ * A player that hangs (S13), such as paplay waiting forever on a Pulse server behind a broken SSH tunnel, is ended:
24
+ * when it takes no audio for the player timeout (REPLY_READER_PLAYER_TIMEOUT seconds in `env`, 15 by default) while
25
+ * 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
26
+ * and `done` rejects with `Playback on "<output>" failed: timed out` (a player that had already exited by then is
27
+ * not). Every kill is SIGTERM, then SIGKILL two seconds later; a player left by a reader that died is ended when the
28
+ * next reading starts, and this process's player dies with it (through `setpriv --pdeathsig KILL` when available, so
29
+ * even a reader killed outright takes it along).
16
30
  */
17
31
  export function startReading(options) {
18
- const { voice, speaker, text, output, env, loadSherpa = loadSherpaTts, speed = DEFAULT_SPEED, onPlayer } = options;
32
+ const { voice, speaker, fragments: list, output, env, loadSherpa = loadSherpaTts, speed = DEFAULT_SPEED, onPlayer } = options;
19
33
  let player;
20
34
  let stopped = false;
35
+ /** Set by the watchdog (S13): the player took no audio, or did not end, in time. */
36
+ let timedOut = false;
37
+ /** Set when the deadline passed after the player exited (S13 g): it settles on its exit, not on its pipes. */
38
+ let overdue = false;
39
+ /** Settles `done` from the player's exit status once it exited; set by `finished`. */
40
+ let settleExited;
41
+ /**
42
+ * When each fragment handed to the player starts being heard (S15), modelled as real-time playback that waits for
43
+ * audio when it runs out: a fragment starts when it is handed over or when the one before it ends, whichever is later.
44
+ */
45
+ const heard = [];
46
+ let heardUntil = 0;
47
+ const handed = (index, samples, sampleRate) => {
48
+ const at = Math.max(Date.now(), heardUntil);
49
+ heard.push({ index, at });
50
+ heardUntil = at + (samples / sampleRate) * 1000;
51
+ };
21
52
  const run = async () => {
22
53
  const paplay = onPath("paplay", env);
23
54
  if (!paplay)
@@ -31,10 +62,15 @@ export function startReading(options) {
31
62
  }
32
63
  if (stopped)
33
64
  return;
34
- const playerEnv = output.pulseServer ? { ...env, PULSE_SERVER: output.pulseServer } : env;
65
+ const playerEnv = { ...env, ...(output.pulseServer ? { PULSE_SERVER: output.pulseServer } : {}), [OWNER_VAR]: ownerTag() };
35
66
  const args = ["--raw", "--format=s16le", `--rate=${tts.sampleRate}`, "--channels=1", PLAYER_MARK, "--stream-name=reply"];
36
- const child = spawn(paplay, args, { env: playerEnv, stdio: ["pipe", "ignore", "pipe"] });
67
+ // Players left playing or hung by a reader that died (S13) go before this one starts.
68
+ reapOrphans();
69
+ // Through setpriv, the player gets SIGKILL when this process dies however it dies (S13 h).
70
+ const [command, commandArgs] = withDeathSignal(onPath("setpriv", env), paplay, args);
71
+ const child = spawn(command, commandArgs, { env: playerEnv, stdio: ["pipe", "ignore", "pipe"] });
37
72
  player = child;
73
+ track(child);
38
74
  // A player that quits early closes its stdin; writing to it must not crash Pi.
39
75
  child.stdin?.on("error", () => { });
40
76
  const playback = finished(child, `Playback on "${output.name}" failed`);
@@ -45,20 +81,86 @@ export function startReading(options) {
45
81
  gone.then(() => (playerGone = true));
46
82
  // A player that exited takes nothing more, even before its pipes close.
47
83
  child.once("exit", () => (playerGone = true));
48
- // Fragments handed to stdin that the pipe has not taken yet; each write's callback fires once it has.
84
+ // The watchdog (S13): armed while a chunk waits for the player, and once all audio is handed over.
85
+ const timeout = options.timeoutMs ?? playerTimeout(env).ms;
86
+ let watchdog;
87
+ const arm = (ms) => {
88
+ clearTimeout(watchdog);
89
+ // setTimeout takes at most 2^31-1 ms (about 24.8 days); a longer wait would fire at once.
90
+ watchdog = setTimeout(() => {
91
+ if (stopped)
92
+ return;
93
+ // A player that already exited is not hung (S13 g): settle on how it exited, without waiting for pipes a
94
+ // process it left behind may still hold.
95
+ if (exited(child)) {
96
+ overdue = true;
97
+ settleExited?.();
98
+ return;
99
+ }
100
+ timedOut = true;
101
+ playerGone = true;
102
+ terminate(child);
103
+ taken?.();
104
+ }, Math.min(ms, MAX_TIMER_MS));
105
+ };
106
+ gone.then(() => clearTimeout(watchdog));
107
+ // Fragments handed over that the pipe has not taken whole yet. Each fragment goes in CHUNK-byte writes, one at a
108
+ // time, so the watchdog sees a player that keeps taking a long fragment as alive.
49
109
  let queued = 0;
50
110
  let taken;
51
- const send = (audio) => {
52
- queued++;
53
- child.stdin?.write(pcm16(audio, speaker.gain), (error) => {
111
+ const backlog = [];
112
+ let writing = false;
113
+ let ending = false;
114
+ let samplesSent = 0;
115
+ const pump = () => {
116
+ if (writing)
117
+ return;
118
+ if (playerGone)
119
+ backlog.length = 0;
120
+ const next = backlog.shift();
121
+ if (!next) {
122
+ if (ending) {
123
+ ending = false;
124
+ child.stdin?.end();
125
+ // The player has all the audio: it must end within the audio's length plus the timeout.
126
+ if (!playerGone)
127
+ arm(Math.round((samplesSent / tts.sampleRate) * 1000) + timeout);
128
+ }
129
+ return;
130
+ }
131
+ writing = true;
132
+ arm(timeout);
133
+ child.stdin?.write(next.chunk, (error) => {
134
+ writing = false;
135
+ clearTimeout(watchdog);
54
136
  // A write that fails means the player closed its input: it will take nothing more.
55
137
  if (error)
56
138
  playerGone = true;
57
- queued--;
58
- taken?.();
139
+ if (next.last) {
140
+ queued--;
141
+ taken?.();
142
+ }
143
+ pump();
59
144
  });
60
145
  };
61
- const list = fragments(text);
146
+ const send = (audio) => {
147
+ queued++;
148
+ samplesSent += audio.length;
149
+ const bytes = pcm16(audio, speaker.gain);
150
+ for (let at = 0; at < bytes.length; at += CHUNK) {
151
+ backlog.push({ chunk: bytes.subarray(at, at + CHUNK), last: at + CHUNK >= bytes.length });
152
+ }
153
+ pump();
154
+ };
155
+ const close = () => {
156
+ ending = true;
157
+ pump();
158
+ };
159
+ const lead = Math.round((options.leadSilence ?? 0) * tts.sampleRate);
160
+ if (lead > 0) {
161
+ handed(0, lead, tts.sampleRate);
162
+ send(new Float32Array(lead));
163
+ }
62
164
  // Samples of pause already written after the last audible fragment; undefined before the first one.
63
165
  let paused;
64
166
  for (const [index, fragment] of list.entries()) {
@@ -85,24 +187,29 @@ export function startReading(options) {
85
187
  break;
86
188
  const speech = trimSilence(samples, speaker.gain, tts.sampleRate);
87
189
  // The last fragment's pause is never written.
88
- const after = index === list.length - 1 ? 0 : Math.round(PAUSES[fragment.boundary] * tts.sampleRate);
190
+ const after = index === list.length - 1 ? 0 : Math.round(PAUSES[fragment.after] * tts.sampleRate);
89
191
  // A silent fragment is dropped, but a stronger boundary it ends still counts: top up the pause written.
90
192
  if (!speech) {
91
193
  if (paused !== undefined && after > paused) {
194
+ handed(index + 1, after - paused, tts.sampleRate);
92
195
  send(new Float32Array(after - paused));
93
196
  paused = after;
94
197
  }
95
198
  continue;
96
199
  }
97
200
  // Each pause goes right after its own fragment, so the next synthesis overlaps it too.
201
+ handed(index, speech.length, tts.sampleRate);
202
+ if (after)
203
+ handed(index + 1, after, tts.sampleRate);
98
204
  send(after ? concat(speech, new Float32Array(after)) : speech);
99
205
  paused = after;
100
206
  }
101
- child.stdin?.end();
207
+ close();
102
208
  await playback;
103
209
  };
104
210
  const done = run().then(() => undefined, (error) => {
105
- player?.kill();
211
+ if (player)
212
+ terminate(player);
106
213
  if (!stopped)
107
214
  throw error;
108
215
  });
@@ -110,7 +217,18 @@ export function startReading(options) {
110
217
  done,
111
218
  stop() {
112
219
  stopped = true;
113
- player?.kill();
220
+ if (player)
221
+ terminate(player);
222
+ },
223
+ position() {
224
+ const now = Date.now() - HEARD_LAG_MS;
225
+ let index = 0;
226
+ for (const segment of heard) {
227
+ if (segment.at > now)
228
+ break;
229
+ index = segment.index;
230
+ }
231
+ return Math.min(index, Math.max(0, list.length - 1));
114
232
  },
115
233
  };
116
234
  /** Resolves when `child` exits cleanly or was stopped; rejects with `prefix` and its last error line. */
@@ -118,18 +236,49 @@ export function startReading(options) {
118
236
  let stderr = "";
119
237
  child.stderr?.on("data", (chunk) => (stderr = (stderr + chunk.toString()).slice(-4096)));
120
238
  return new Promise((resolve, reject) => {
121
- child.on("error", (error) => reject(new Error(`${prefix}: ${error.message}`)));
122
- // After stop, do not wait for pipes a grandchild may still hold open.
123
- child.on("exit", () => stopped && resolve());
124
- child.on("close", (code, signal) => {
125
- if (code === 0 || stopped)
239
+ const settle = (code, signal) => {
240
+ if (stopped)
241
+ return resolve();
242
+ if (timedOut)
243
+ return reject(new Error(`${prefix}: timed out`));
244
+ if (code === 0)
126
245
  return resolve();
127
246
  const last = stderr.trim().split("\n").at(-1)?.trim();
128
247
  reject(new Error(`${prefix}: ${last || (signal ? `killed by ${signal}` : `exit code ${code}`)}`));
248
+ };
249
+ settleExited = () => {
250
+ if (child.exitCode !== null || child.signalCode !== null)
251
+ settle(child.exitCode, child.signalCode);
252
+ };
253
+ child.on("error", (error) => reject(new Error(`${prefix}: ${error.message}`)));
254
+ // After stop, a timeout or a passed deadline, do not wait for pipes a grandchild may still hold open.
255
+ child.on("exit", (code, signal) => {
256
+ if (stopped || timedOut || overdue)
257
+ settle(code, signal);
129
258
  });
259
+ child.on("close", settle);
130
260
  });
131
261
  }
132
262
  }
263
+ /** The longest delay setTimeout takes; a longer one fires at once with a TimeoutOverflowWarning. */
264
+ const MAX_TIMER_MS = 2 ** 31 - 1;
265
+ /**
266
+ * Whether `child` already exited: its exit was seen, or it is a zombie whose exit event has not come yet (the deadline
267
+ * and the exit can land in the same turn of the event loop).
268
+ */
269
+ function exited(child) {
270
+ if (child.exitCode !== null || child.signalCode !== null)
271
+ return true;
272
+ try {
273
+ const stat = readFileSync(`/proc/${child.pid}/stat`, "utf8");
274
+ return stat.slice(stat.lastIndexOf(")") + 2, stat.lastIndexOf(")") + 3) === "Z";
275
+ }
276
+ catch {
277
+ return false;
278
+ }
279
+ }
280
+ /** Bytes per write to the player: about 0.37 s of audio at 44.1 kHz, well under a Linux pipe's 64 KiB. */
281
+ const CHUNK = 32 * 1024;
133
282
  /**
134
283
  * Synthesized fragments that may wait for the player at once (T26): the one playing and the next one, ready.
135
284
  * Synthesis is one call at a time and, under load, slower than real time (L70), so a deeper queue would rarely
@@ -142,31 +291,6 @@ const LOOKAHEAD = 2;
142
291
  * (also after a heading or bold-only line). Longer than the voice's own 0.08-0.26 s at `,`, `;` and `:` (L39).
143
292
  */
144
293
  const PAUSES = { sentence: 0.35, line: 0.5, paragraph: 0.75 };
145
- /**
146
- * Sentences and lines, in order, each with the boundary after it; Supertonic only calls back once per
147
- * 300 characters, so we split first. Never at ":" or ";", where a pause would sound like a full stop.
148
- */
149
- function fragments(text) {
150
- const result = [];
151
- let blank = false;
152
- for (const line of text.split("\n")) {
153
- const sentences = line
154
- .split(/(?<=[.!?…])\s+/)
155
- .map((sentence) => sentence.trim())
156
- .filter((sentence) => sentence !== "");
157
- if (sentences.length === 0) {
158
- blank = true;
159
- continue;
160
- }
161
- const previous = result.at(-1);
162
- if (previous)
163
- previous.boundary = blank ? "paragraph" : "line";
164
- blank = false;
165
- for (const sentence of sentences)
166
- result.push({ text: sentence, boundary: "sentence" });
167
- }
168
- return result;
169
- }
170
294
  /** Windows quieter than this, after the speaker's gain, count as silence (-45 dBFS RMS over 10 ms). */
171
295
  const SILENCE = 10 ** (-45 / 20);
172
296
  const WINDOW_SECONDS = 0.01;
@@ -0,0 +1,265 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { readdirSync, readFileSync, readlinkSync, statSync } from "node:fs";
3
+ /** Every player we start carries this argument, so a pid can be told apart from an unrelated process. */
4
+ export const PLAYER_MARK = "--client-name=pi-reply-reader";
5
+ /**
6
+ * Set in each player's environment to `<pid>:<start time>` of the process that started it (S13), so a later reading
7
+ * can tell a player whose reader is gone from one that still has a reader, and from a paplay that is not ours.
8
+ */
9
+ export const OWNER_VAR = "PI_REPLY_READER_OWNER";
10
+ /** How long a player gets to end after SIGTERM before SIGKILL (S13): paplay stuck connecting may ignore SIGTERM. */
11
+ export const KILL_GRACE_MS = 2000;
12
+ /** The value of OWNER_VAR for players started by this process. */
13
+ export function ownerTag() {
14
+ return `${process.pid}:${startTime(process.pid) ?? ""}`;
15
+ }
16
+ const ending = new WeakSet();
17
+ /** SIGTERM to a player we started, then SIGKILL after KILL_GRACE_MS if it has not exited. Never throws. */
18
+ export function terminate(child) {
19
+ if (child.exitCode !== null || child.signalCode !== null)
20
+ return;
21
+ try {
22
+ child.kill("SIGTERM");
23
+ }
24
+ catch { }
25
+ if (ending.has(child))
26
+ return;
27
+ ending.add(child);
28
+ const timer = setTimeout(() => {
29
+ if (child.exitCode !== null || child.signalCode !== null)
30
+ return;
31
+ try {
32
+ child.kill("SIGKILL");
33
+ }
34
+ catch { }
35
+ }, KILL_GRACE_MS);
36
+ child.once("exit", () => clearTimeout(timer));
37
+ }
38
+ /** How often a player signalled by pid is checked for having ended during its grace. */
39
+ const POLL_MS = 50;
40
+ /** Players signalled by terminatePid whose grace has not run out, each settling when it ended or was SIGKILLed. */
41
+ const signalled = new Set();
42
+ /**
43
+ * SIGTERM to the player `pid` (started at `start`), then SIGKILL after KILL_GRACE_MS if that same player of ours is
44
+ * still there. Its timer does not keep this process alive: a process about to exit awaits signalledPlayersEnded()
45
+ * first. Never throws.
46
+ */
47
+ export function terminatePid(pid, start) {
48
+ try {
49
+ process.kill(pid, "SIGTERM");
50
+ }
51
+ catch {
52
+ return;
53
+ }
54
+ const began = Date.now();
55
+ const ended = new Promise((done) => {
56
+ const timer = setInterval(() => {
57
+ if (isPlayer(pid, start) && Date.now() - began < KILL_GRACE_MS)
58
+ return;
59
+ clearInterval(timer);
60
+ if (isPlayer(pid, start)) {
61
+ try {
62
+ process.kill(pid, "SIGKILL");
63
+ }
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
+ * Settles once every player this process signalled with terminatePid (a reaped orphan, a lock takeover) has exited or
75
+ * been SIGKILLed (S13 e), so a command that exits right after never cuts the SIGKILL short.
76
+ */
77
+ export async function signalledPlayersEnded() {
78
+ if (signalled.size === 0)
79
+ 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
+ }
85
+ finally {
86
+ clearInterval(hold);
87
+ }
88
+ }
89
+ const live = new Set();
90
+ let exitHooked = false;
91
+ /**
92
+ * Keeps `child` until it exits; if this process exits first (Pi quitting without session_shutdown, the CLI's
93
+ * process.exit), the player is killed with it instead of playing or hanging on, orphaned (S13).
94
+ */
95
+ export function track(child) {
96
+ live.add(child);
97
+ child.once("exit", () => live.delete(child));
98
+ if (exitHooked)
99
+ return;
100
+ exitHooked = true;
101
+ process.on("exit", () => {
102
+ for (const player of live) {
103
+ try {
104
+ player.kill("SIGKILL");
105
+ }
106
+ catch { }
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() {
120
+ let names;
121
+ const namespace = pidNamespace("self");
122
+ if (namespace === undefined)
123
+ return [];
124
+ try {
125
+ names = readdirSync("/proc");
126
+ }
127
+ catch {
128
+ return [];
129
+ }
130
+ const uid = process.getuid?.();
131
+ const reaped = [];
132
+ for (const name of names) {
133
+ if (!/^\d+$/.test(name))
134
+ continue;
135
+ const pid = Number(name);
136
+ if (pid === process.pid)
137
+ continue;
138
+ try {
139
+ if (uid !== undefined && statSync(`/proc/${pid}`).uid !== uid)
140
+ continue;
141
+ const args = readFileSync(`/proc/${pid}/cmdline`, "utf8").split("\0");
142
+ if (!args.includes(PLAYER_MARK) || isListenerServe(args))
143
+ continue;
144
+ if (pidNamespace(String(pid)) !== namespace)
145
+ continue;
146
+ const tag = readFileSync(`/proc/${pid}/environ`, "utf8")
147
+ .split("\0")
148
+ .find((entry) => entry.startsWith(`${OWNER_VAR}=`));
149
+ if (!tag)
150
+ continue;
151
+ const [owner, start] = tag.slice(OWNER_VAR.length + 1).split(":");
152
+ const ownerPid = Number(owner);
153
+ if (!Number.isInteger(ownerPid) || ownerPid <= 0)
154
+ continue;
155
+ if (sameProcess(ownerPid, start || undefined))
156
+ continue;
157
+ terminatePid(pid, startTime(pid));
158
+ reaped.push(pid);
159
+ }
160
+ catch { }
161
+ }
162
+ return reaped;
163
+ }
164
+ /**
165
+ * Whether a command line is a listener's `reply-reader --serve` (S20): "--serve" right after the path of the
166
+ * reply-reader script (`…/reply-reader`, `…/reply-reader.ts` or `.js`). The agent host's ssh child, whose remote
167
+ * command is the bare word `reply-reader`, does not match, so an orphaned one is still reaped.
168
+ */
169
+ export function isListenerServe(args) {
170
+ const at = args.indexOf("--serve");
171
+ if (at < 1)
172
+ return false;
173
+ const script = args[at - 1];
174
+ return script.includes("/") && /^reply-reader(\.[cm]?[jt]s)?$/.test(script.slice(script.lastIndexOf("/") + 1));
175
+ }
176
+ /** The PID namespace of `/proc/<pid>` ("self" for this process), as `pid:[inode]`; undefined when unreadable. */
177
+ function pidNamespace(pid) {
178
+ try {
179
+ return readlinkSync(`/proc/${pid}/ns/pid`);
180
+ }
181
+ catch {
182
+ return undefined;
183
+ }
184
+ }
185
+ /** The player timeout of S13 when REPLY_READER_PLAYER_TIMEOUT is unset or invalid. */
186
+ const DEFAULT_TIMEOUT_SECONDS = 15;
187
+ const MIN_TIMEOUT_SECONDS = 5;
188
+ const MAX_TIMEOUT_SECONDS = 86400;
189
+ /** The warning for an invalid REPLY_READER_PLAYER_TIMEOUT (S13 f). */
190
+ 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}.`;
191
+ /**
192
+ * The player timeout of S13 in milliseconds: REPLY_READER_PLAYER_TIMEOUT, whole or fractional seconds from 5 to 86400,
193
+ * else 15 s; any value set but outside that (empty, `0`, `abc`, `3000000`) also returns the warning.
194
+ */
195
+ export function playerTimeout(env) {
196
+ const value = env.REPLY_READER_PLAYER_TIMEOUT;
197
+ if (value === undefined)
198
+ return { ms: DEFAULT_TIMEOUT_SECONDS * 1000 };
199
+ const text = value.trim();
200
+ const seconds = /^\d+(\.\d+)?$/.test(text) ? Number(text) : Number.NaN;
201
+ if (seconds >= MIN_TIMEOUT_SECONDS && seconds <= MAX_TIMEOUT_SECONDS)
202
+ return { ms: Math.round(seconds * 1000) };
203
+ return { ms: DEFAULT_TIMEOUT_SECONDS * 1000, problem: PLAYER_TIMEOUT_HINT };
204
+ }
205
+ let timeoutWarned = false;
206
+ /** playerTimeout's milliseconds, telling `warn` about an invalid value once per process (S13 f). */
207
+ export function playerTimeoutMs(env, warn) {
208
+ const { ms, problem } = playerTimeout(env);
209
+ if (problem && !timeoutWarned) {
210
+ timeoutWarned = true;
211
+ warn(problem);
212
+ }
213
+ return ms;
214
+ }
215
+ const deathSignal = new Map();
216
+ /**
217
+ * The command and arguments that start `command` so it gets SIGKILL when this process dies (S13 h), however it dies:
218
+ * `setpriv --pdeathsig KILL` when setpriv (`setpriv`, found by the caller on PATH) runs and supports it, else
219
+ * `command` alone. Checked under Pi's Bun (T37): a player started through it from the JS thread is not cut while its
220
+ * reader runs, and dies when the reader is SIGKILLed.
221
+ */
222
+ export function withDeathSignal(setpriv, command, args) {
223
+ if (!setpriv)
224
+ return [command, args];
225
+ let works = deathSignal.get(setpriv);
226
+ if (works === undefined) {
227
+ const check = spawnSync(setpriv, ["--pdeathsig", "KILL", "/bin/sh", "-c", ":"], { stdio: "ignore", timeout: 2000 });
228
+ works = check.status === 0;
229
+ deathSignal.set(setpriv, works);
230
+ }
231
+ return works ? [setpriv, ["--pdeathsig", "KILL", command, ...args]] : [command, args];
232
+ }
233
+ /** A live process of this user with that pid, started when recorded (when recorded). */
234
+ export function sameProcess(pid, start) {
235
+ try {
236
+ process.kill(pid, 0);
237
+ }
238
+ catch {
239
+ return false;
240
+ }
241
+ return start === undefined || startTime(pid) === start;
242
+ }
243
+ /** Guards against pid reuse: only a live player we started, of this user, may be signalled. */
244
+ export function isPlayer(pid, start) {
245
+ if (!sameProcess(pid, start))
246
+ return false;
247
+ try {
248
+ if (process.getuid && statSync(`/proc/${pid}`).uid !== process.getuid())
249
+ return false;
250
+ return readFileSync(`/proc/${pid}/cmdline`, "utf8").split("\0").includes(PLAYER_MARK);
251
+ }
252
+ catch {
253
+ return false;
254
+ }
255
+ }
256
+ /** Field 22 of /proc/<pid>/stat, the process start time; undefined where /proc is missing. */
257
+ export function startTime(pid) {
258
+ try {
259
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
260
+ return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
261
+ }
262
+ catch {
263
+ return undefined;
264
+ }
265
+ }
@@ -0,0 +1,50 @@
1
+ import { existsSync, readFileSync, statSync } from "node:fs";
2
+ import { basename, dirname, resolve } from "node:path";
3
+ import { openReadingLock } from "./reading-lock.js";
4
+ /**
5
+ * A reading's project (S19): the folder name of the Git root its working folder is in, else of the working folder
6
+ * itself. The root is the nearest folder upward holding a `.git`, found without running git. A `.git` file names its
7
+ * gitdir: a linked worktree's holds `commondir`, so it is the same repo and is named by the folder of the main
8
+ * `.git`; a submodule's does not, so it keeps its own folder name.
9
+ */
10
+ export function projectOf(cwd) {
11
+ const start = resolve(cwd);
12
+ for (let dir = start;; dir = dirname(dir)) {
13
+ const git = resolve(dir, ".git");
14
+ if (existsSync(git))
15
+ return mainRepo(dir, git) ?? (basename(dir) || dir);
16
+ if (dirname(dir) === dir)
17
+ return basename(start) || start;
18
+ }
19
+ }
20
+ /** For a linked worktree (its `.git` a file whose gitdir holds `commondir`), the main repository's folder name. */
21
+ function mainRepo(dir, git) {
22
+ try {
23
+ if (!statSync(git).isFile())
24
+ return undefined;
25
+ const gitdir = /^gitdir:\s*(.+?)\s*$/m.exec(readFileSync(git, "utf8"))?.[1];
26
+ if (!gitdir)
27
+ return undefined;
28
+ const resolved = resolve(dir, gitdir);
29
+ const common = readFileSync(resolve(resolved, "commondir"), "utf8").trim();
30
+ if (!common)
31
+ return undefined;
32
+ const main = dirname(resolve(resolved, common));
33
+ return basename(main) || undefined;
34
+ }
35
+ catch {
36
+ return undefined;
37
+ }
38
+ }
39
+ /**
40
+ * Records `project` as the machine's last reading's (S19) and says whether it must be announced: it differs from the
41
+ * one remembered, or none was. The memory is shared next to the reading lock by every Pi session and the
42
+ * `reply-reader` command; without a usable XDG_RUNTIME_DIR it is `local`, the caller's own (a process's).
43
+ */
44
+ export function projectChanged(env, project, local) {
45
+ const lock = openReadingLock(env);
46
+ const previous = lock ? lock.swapProject(project) : local.last;
47
+ if (!lock)
48
+ local.last = project;
49
+ return previous !== project;
50
+ }