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.
package/src/prompts.ts ADDED
@@ -0,0 +1,142 @@
1
+ /**
2
+ * What auto-read says when the agent blocks on the human (S18, T43): the questions of an `ask_user_question` or
3
+ * `ask_user_choice` call with their option labels, a command confirmation by its program name, or another dialog's
4
+ * title. Each is Markdown in the words of one language, cleaned for speech like any reply.
5
+ */
6
+ import type { Language } from "./speech-text.ts";
7
+
8
+ /** The tools whose calls ask the human questions with options. */
9
+ export const QUESTION_TOOLS = new Set(["ask_user_question", "ask_user_choice"]);
10
+
11
+ const WORDS: Record<Language, { question: string; of: string; options: string; command: string }> = {
12
+ es: { question: "Pregunta", of: "de", options: "Opciones", command: "Confirmación de comando" },
13
+ en: { question: "Question", of: "of", options: "Options", command: "Command confirmation" },
14
+ };
15
+
16
+ /** One question and its option labels, as given in the call's args. */
17
+ export interface AskedQuestion {
18
+ question: string;
19
+ labels: string[];
20
+ }
21
+
22
+ const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value);
23
+ /** One line of text, its whitespace runs (line breaks too) made single spaces. */
24
+ const oneLine = (text: string): string => text.replace(/\s+/g, " ").trim();
25
+
26
+ /** The labels of an options list; undefined when it is no list or any option has no text label. */
27
+ function labelsOf(options: unknown): string[] | undefined {
28
+ if (options === undefined) return [];
29
+ if (!Array.isArray(options)) return undefined;
30
+ const labels: string[] = [];
31
+ for (const option of options) {
32
+ if (!isRecord(option) || typeof option.label !== "string" || !oneLine(option.label)) return undefined;
33
+ labels.push(oneLine(option.label));
34
+ }
35
+ return labels;
36
+ }
37
+
38
+ function questionOf(value: unknown): AskedQuestion | undefined {
39
+ if (!isRecord(value) || typeof value.question !== "string" || !oneLine(value.question)) return undefined;
40
+ const labels = labelsOf(value.options);
41
+ return labels && { question: oneLine(value.question), labels };
42
+ }
43
+
44
+ /**
45
+ * The questions of an ask_user_* call, from its args: ask_user_question `{ questions: [{ question, options: [{ label }] }] }`,
46
+ * ask_user_choice `{ question, options: [{ label }] }`. Undefined for any other tool or malformed args (then nothing is read).
47
+ */
48
+ export function askedQuestions(toolName: string, args: unknown): AskedQuestion[] | undefined {
49
+ if (toolName === "ask_user_choice") {
50
+ const question = questionOf(args);
51
+ return question && [question];
52
+ }
53
+ if (toolName !== "ask_user_question" || !isRecord(args) || !Array.isArray(args.questions) || args.questions.length === 0) return undefined;
54
+ const questions: AskedQuestion[] = [];
55
+ for (const value of args.questions) {
56
+ const question = questionOf(value);
57
+ if (!question) return undefined;
58
+ questions.push(question);
59
+ }
60
+ return questions;
61
+ }
62
+
63
+ /** What an assistant message wrote and the tool calls it made (S18 Context, T48). */
64
+ export interface WrittenCalls {
65
+ /** Its text blocks joined with a blank line, trimmed; "" when it wrote nothing (thinking is never text). */
66
+ text: string;
67
+ /** The IDs of its tool calls. */
68
+ calls: string[];
69
+ }
70
+
71
+ /**
72
+ * The text an assistant message wrote before its tool calls, with the calls' IDs, from the message itself (as
73
+ * `message_end` carries it). Undefined for any other message.
74
+ */
75
+ export function writtenCalls(message: unknown): WrittenCalls | undefined {
76
+ if (!isRecord(message) || message.role !== "assistant" || !Array.isArray(message.content)) return undefined;
77
+ const texts: string[] = [];
78
+ const calls: string[] = [];
79
+ for (const block of message.content) {
80
+ if (!isRecord(block)) continue;
81
+ if (block.type === "text" && typeof block.text === "string") texts.push(block.text);
82
+ else if (block.type === "toolCall" && typeof block.id === "string") calls.push(block.id);
83
+ }
84
+ return { text: texts.join("\n\n").trim(), calls };
85
+ }
86
+
87
+ /** A sentence's end: "." added unless it already ends in `. ? ! …`; a final `:` or `;` becomes ".". */
88
+ const closed = (text: string): string => (/[.?!…]$/.test(text) ? text : `${text.replace(/[:;,]+$/, "")}.`);
89
+
90
+ /**
91
+ * "Pregunta 1 de 2: ¿Cómo suena? Opciones: 1, Bien; 2, Mal." one line per question ("Pregunta: …" for a single one),
92
+ * labels only; the cleanup then reads the numbers in words ("uno, Bien").
93
+ */
94
+ export function questionsMarkdown(questions: readonly AskedQuestion[], language: Language): string {
95
+ const words = WORDS[language];
96
+ return questions
97
+ .map(({ question, labels }, index) => {
98
+ const head = questions.length === 1 ? words.question : `${words.question} ${index + 1} ${words.of} ${questions.length}`;
99
+ const options = labels.map((label, n) => `${n + 1}, ${label.replace(/[.;,:]+$/, "")}`).join("; ");
100
+ return `${head}: ${closed(question)}${options ? ` ${words.options}: ${options}.` : ""}`;
101
+ })
102
+ .join("\n");
103
+ }
104
+
105
+ /** An environment assignment before a command (`FOO=1`, `A="b c"`). */
106
+ const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=(?:"[^"]*"|'[^']*'|\S*)\s+/;
107
+
108
+ /**
109
+ * The program a shell command runs, never its arguments: the first word after any `NAME=value` assignments and a
110
+ * leading `sudo` (or `env`) without options, without its directory (`/usr/bin/npm` → "npm"). Undefined when there is none.
111
+ */
112
+ export function commandProgram(command: string): string | undefined {
113
+ let rest = command.trim();
114
+ for (;;) {
115
+ const assignment = ASSIGNMENT.exec(rest);
116
+ if (assignment) {
117
+ rest = rest.slice(assignment[0].length);
118
+ continue;
119
+ }
120
+ const wrapper = /^(?:sudo|env)\s+(?!-)/.exec(rest);
121
+ if (wrapper) {
122
+ rest = rest.slice(wrapper[0].length);
123
+ continue;
124
+ }
125
+ break;
126
+ }
127
+ const first = /^["']?([^\s"';|&()<>]+)/.exec(rest)?.[1];
128
+ const program = first?.split("/").filter(Boolean).at(-1);
129
+ return program && /\p{L}/u.test(program) ? program : undefined;
130
+ }
131
+
132
+ /** "Confirmación de comando: git." / "Command confirmation: git."; without a program, just the words. */
133
+ export function commandMarkdown(program: string | undefined, language: Language): string {
134
+ const words = WORDS[language].command;
135
+ // As inline code, so a name's own `_` or `*` is not read as emphasis.
136
+ return program ? `${words}: \`${program}\`.` : `${words}.`;
137
+ }
138
+
139
+ /** A dialog's title as one line, or undefined when it has none. */
140
+ export function dialogTitle(title: unknown): string | undefined {
141
+ return typeof title === "string" && oneLine(title) ? oneLine(title) : undefined;
142
+ }
@@ -1,15 +1,22 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { closeSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
3
3
  import { isAbsolute, join } from "node:path";
4
+ import { isPlayer, sameProcess, startTime, terminatePid } from "./player.ts";
4
5
 
5
- /** Every player we start carries this argument, so a pid can be told apart from an unrelated process. */
6
- export const PLAYER_MARK = "--client-name=pi-reply-reader";
6
+ export { PLAYER_MARK } from "./player.ts";
7
7
 
8
8
  /**
9
9
  * The reading playing on this machine, shared by every Pi session and process of this user (S1, T21):
10
10
  * `$XDG_RUNTIME_DIR/pi-reply-reader/reading.json`. `token` names one reading; `stopped` marks an entry left by
11
11
  * `/read-stop`, which tells the reading it named that it was stopped. Start times come from /proc, so a pid that was
12
- * reused by a newer process does not count as the one recorded.
12
+ * reused by a newer process does not count as the one recorded. Next to it, `waiting.json` holds the waiting mark of
13
+ * the auto-read queue (S8, T32) and `reading.lock` is a short mutex around each check-and-write. Each Pi session
14
+ * publishes what waits in its line as `line-<token>.json` (S16), so `/read-queue` and the footer see the machine's.
15
+ * `project.json` remembers the project of the last reading that started (S19).
16
+ *
17
+ * Pause (S15): `paused` asks the reading's own session to pause it (its player ends, the entry keeps the machine with
18
+ * no player) or, once cleared, to resume it. Only entries marked `pausable` (a Pi session that knows how) take it; a
19
+ * `prompt` reading (S18) is ended instead.
13
20
  */
14
21
  interface Entry {
15
22
  token: string;
@@ -19,6 +26,36 @@ interface Entry {
19
26
  playerStart?: string;
20
27
  started: number;
21
28
  stopped?: true;
29
+ paused?: true;
30
+ pausable?: true;
31
+ prompt?: true;
32
+ }
33
+
34
+ /** What a reading's entry says about it when it is claimed (S15). */
35
+ export interface ClaimKind {
36
+ /** Its session pauses and resumes it when the entry asks (a Pi session; not the CLI). */
37
+ pausable?: boolean;
38
+ /** A blocking prompt's reading (S18): a pause ends it. */
39
+ prompt?: boolean;
40
+ }
41
+
42
+ /** One reading waiting in a session's line, as /read-queue lists it (S16). */
43
+ export interface WaitingItem {
44
+ name: string;
45
+ /** When it joined the line, in ms; the machine's list is in this order. */
46
+ at: number;
47
+ /** The waiting mark it was queued under; once an explicit action changed it, it no longer waits. */
48
+ mark: string | undefined;
49
+ }
50
+
51
+ /** A waiting reading as seen machine-wide: with its session's label and token. */
52
+ export interface MachineWaiting extends WaitingItem {
53
+ session: string;
54
+ token: string;
55
+ /** When its session last published its line (its heartbeat, S16); undefined from a version that does not beat. */
56
+ beat?: number;
57
+ /** Its session waits on a human (the output question, a voice download confirm): nobody yields to it (S16, L138). */
58
+ asking?: true;
22
59
  }
23
60
 
24
61
  /** One reading's hold on the machine. Nothing here throws. */
@@ -29,15 +66,62 @@ export interface Claim {
29
66
  lost(): boolean;
30
67
  /** Drops the entry if it is still this reading's. */
31
68
  release(): void;
69
+ /** Whether the entry asks for this reading to be paused (S15); undefined when it is no longer this reading's. */
70
+ paused(): boolean | undefined;
71
+ /** Marks this reading paused (its player cleared, as none runs) or playing again (S15). */
72
+ setPaused(paused: boolean): void;
32
73
  }
33
74
 
34
75
  export interface ReadingLock {
35
- /** Makes a new reading the one playing on the machine, stopping the one playing in any other session. */
36
- claim(): Claim;
37
- /** Stops the reading playing in another session, if any; true when one was playing. */
76
+ /**
77
+ * Makes a new reading the one playing on the machine, stopping the one playing in any other session. With
78
+ * `dropWaiting` (an explicit /read, S8) it also drops every auto-read waiting on the machine at that moment.
79
+ */
80
+ claim(options?: { dropWaiting?: boolean } & ClaimKind): Claim;
81
+ /**
82
+ * For auto-read (S8 Queue, T32): claims the machine only when no reading plays, and only when no explicit action
83
+ * dropped the waiting replies since `mark` was taken. Never stops a reading.
84
+ */
85
+ claimIfFree(mark: string | undefined, kind?: ClaimKind): Claim | "busy" | "dropped";
86
+ /** Whether a reading plays (or is starting) in any session; stale entries do not count. */
87
+ busy(): boolean;
88
+ /** The current waiting mark; a reply queued now remembers it, and drops itself once it changes. */
89
+ waitingMark(): string | undefined;
90
+ /** Drops every auto-read waiting on the machine (Esc, S8). */
91
+ dropWaiting(): void;
92
+ /** Stops the reading playing in another session, if any, and drops every waiting auto-read; true when one was playing. */
38
93
  stopOthers(): boolean;
94
+ /** Ends the reading playing or paused in another session, keeping what waits (/read-next, S16); true when there was one. */
95
+ skipOthers(): boolean;
96
+ /**
97
+ * Asks another session to pause its reading, or to resume it when paused (S15). "stopped" when it was a prompt's
98
+ * reading (ended instead), "unsupported" when its reader cannot pause (the CLI, an older version), undefined when
99
+ * nothing is being read.
100
+ */
101
+ togglePause(): "paused" | "resumed" | "stopped" | "unsupported" | undefined;
102
+ /**
103
+ * Publishes the line of the session `token` (S16), stamped with the time as its heartbeat; an empty line removes it.
104
+ * `tag` (a few characters of Pi's session id) tells it apart from another session with the same label; the token's
105
+ * last four characters otherwise. `asking`: the session waits on a human before its next reading can start.
106
+ */
107
+ publishLine(token: string, session: string, items: readonly WaitingItem[], tag?: string, asking?: boolean): void;
108
+ /**
109
+ * Every reading waiting on the machine, in the order each joined its line; dropped ones and dead sessions' are left
110
+ * out. Two sessions with the same label are told apart as `<label> #<tag>` (S16, L135).
111
+ */
112
+ waitingList(): MachineWaiting[];
113
+ /**
114
+ * Makes `project` the one of the last reading that started on the machine (S19) and returns the one remembered
115
+ * before it, undefined when none was.
116
+ */
117
+ swapProject(project: string): string | undefined;
39
118
  }
40
119
 
120
+ /** How long an explicit action waits for the mutex before acting anyway; an auto-read just tries later. */
121
+ const MUTEX_WAIT_MS = 200;
122
+ /** A mutex file still empty after this long was left by a process that died while taking it. */
123
+ const MUTEX_STALE_MS = 1000;
124
+
41
125
  /**
42
126
  * The machine-wide lock under `$XDG_RUNTIME_DIR`, or undefined when it is unset, relative or unusable: then each
43
127
  * session only stops its own readings, as before.
@@ -53,6 +137,12 @@ export function openReadingLock(env: NodeJS.ProcessEnv): ReadingLock | undefined
53
137
  return undefined;
54
138
  }
55
139
  const file = join(dir, "reading.json");
140
+ /** `{ mark }`: rewritten by every explicit action, so replies queued before it know they were dropped (S8). */
141
+ const marks = join(dir, "waiting.json");
142
+ /** Held for the few microseconds of a check-and-write, so two sessions never both take a free machine (T32). */
143
+ const mutex = join(dir, "reading.lock");
144
+ /** `{ project }`: the project of the last reading that started, by any session or the command (S19). */
145
+ const projects = join(dir, "project.json");
56
146
 
57
147
  const read = (): Entry | undefined => {
58
148
  try {
@@ -65,18 +155,83 @@ export function openReadingLock(env: NodeJS.ProcessEnv): ReadingLock | undefined
65
155
  }
66
156
  };
67
157
 
68
- /** Written whole, then renamed into place, so a reader never sees half an entry. */
69
- const write = (entry: Entry): void => {
70
- const temp = `${file}.${process.pid}.${entry.token}.tmp`;
158
+ /** Written whole, then renamed into place, so a reader never sees half a file. */
159
+ const put = (path: string, token: string, data: unknown): void => {
160
+ const temp = `${path}.${process.pid}.${token}.tmp`;
71
161
  try {
72
- writeFileSync(temp, JSON.stringify(entry), { mode: 0o600 });
73
- renameSync(temp, file);
162
+ writeFileSync(temp, JSON.stringify(data), { mode: 0o600 });
163
+ renameSync(temp, path);
74
164
  } catch {
75
165
  try {
76
166
  unlinkSync(temp);
77
167
  } catch {}
78
168
  }
79
169
  };
170
+ const write = (entry: Entry): void => put(file, entry.token, entry);
171
+ const lineFile = (token: string): string => join(dir, `line-${token}.json`);
172
+
173
+ const waitingMark = (): string | undefined => {
174
+ try {
175
+ const mark = (JSON.parse(readFileSync(marks, "utf8")) as { mark?: unknown })?.mark;
176
+ return typeof mark === "string" ? mark : undefined;
177
+ } catch {
178
+ return undefined;
179
+ }
180
+ };
181
+ const dropWaiting = (): void => {
182
+ const mark = randomUUID();
183
+ put(marks, mark, { mark });
184
+ };
185
+
186
+ /**
187
+ * Runs `body` holding the machine's mutex. When it cannot be had in time, `timeout` decides: explicit actions act
188
+ * anyway (as before T32), auto-read tries again later. A mutex left by a dead process is broken.
189
+ */
190
+ const exclusive = <T>(body: () => T, timeout: () => T): T => {
191
+ const deadline = Date.now() + MUTEX_WAIT_MS;
192
+ for (;;) {
193
+ let fd: number;
194
+ try {
195
+ fd = openSync(mutex, "wx", 0o600);
196
+ } catch (error) {
197
+ // Anything but "held" (a read-only folder, say) means no mutex at all, as before T32.
198
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") return body();
199
+ if (abandoned()) {
200
+ try {
201
+ unlinkSync(mutex);
202
+ continue;
203
+ } catch {
204
+ // Not deletable (a read-only folder, say): it counts as held, so the deadline still bounds the wait.
205
+ }
206
+ }
207
+ if (Date.now() > deadline) return timeout();
208
+ pause(2);
209
+ continue;
210
+ }
211
+ try {
212
+ try {
213
+ writeSync(fd, `${process.pid} ${startTime(process.pid) ?? ""}`);
214
+ } finally {
215
+ closeSync(fd);
216
+ }
217
+ return body();
218
+ } finally {
219
+ try {
220
+ unlinkSync(mutex);
221
+ } catch {}
222
+ }
223
+ }
224
+ };
225
+ /** Whether the mutex was left by a process that is gone (or never wrote its pid). */
226
+ const abandoned = (): boolean => {
227
+ try {
228
+ const [pid, start] = readFileSync(mutex, "utf8").split(" ");
229
+ if (pid && Number.isInteger(Number(pid)) && Number(pid) > 0) return !sameProcess(Number(pid), start || undefined);
230
+ return Date.now() - statSync(mutex).mtimeMs > MUTEX_STALE_MS;
231
+ } catch {
232
+ return false;
233
+ }
234
+ };
80
235
 
81
236
  /**
82
237
  * Writes `entry` over the current one (always for a new reading; for `/read-stop` only when a reading plays) and
@@ -88,41 +243,210 @@ export function openReadingLock(env: NodeJS.ProcessEnv): ReadingLock | undefined
88
243
  const live = previous !== undefined && playing(previous);
89
244
  if (always || live) write(entry);
90
245
  if (!live) return false;
91
- if (previous.player !== undefined) {
92
- try {
93
- process.kill(previous.player, "SIGTERM");
94
- } catch {}
95
- }
246
+ // SIGTERM, then SIGKILL if that player ignores it (S13): its own session may be hung or gone.
247
+ if (previous.player !== undefined) terminatePid(previous.player, previous.playerStart);
96
248
  return true;
97
249
  };
98
250
 
99
251
  const self = (): Pick<Entry, "pid" | "pidStart" | "started"> => ({ pid: process.pid, pidStart: startTime(process.pid), started: Date.now() });
100
252
 
101
- return {
102
- claim(): Claim {
103
- const token = randomUUID();
104
- const mine: Entry = { token, ...self() };
105
- takeOver(mine, true);
106
- const lost = (): boolean => {
253
+ /** The hold of the reading whose entry `mine` was just written. */
254
+ const held = (mine: Entry): Claim => {
255
+ /**
256
+ * Whether the entry was written. Once it was, a missing entry means another reading took over and already ended
257
+ * (a paused reading has no player to kill, so this is how it learns, S15/S16); if it never was (writes fail), the
258
+ * reading keeps to itself as without a lock.
259
+ */
260
+ const written = read()?.token === mine.token;
261
+ const lost = (): boolean => {
262
+ const entry = read();
263
+ return entry === undefined ? written : entry.token !== mine.token;
264
+ };
265
+ /** The entry as it is now (a pause request may have changed it), when still this reading's. */
266
+ const own = (): Entry | undefined => {
267
+ const entry = read();
268
+ if (entry === undefined) return written ? undefined : mine;
269
+ return entry.token === mine.token ? entry : undefined;
270
+ };
271
+ const setPlayer = (pid: number): boolean => {
272
+ const entry = own();
273
+ if (!entry) return false;
274
+ write({ ...entry, player: pid, playerStart: startTime(pid) });
275
+ return true;
276
+ };
277
+ const setPaused = (paused: boolean): void => {
278
+ const entry = own();
279
+ if (!entry) return;
280
+ const { paused: _was, player: _player, playerStart: _start, ...rest } = entry;
281
+ // Paused, no player runs: the entry keeps the machine through the reader's own process (S15).
282
+ write(paused ? { ...rest, paused: true } : entry.player === undefined ? rest : { ...rest, player: entry.player, playerStart: entry.playerStart });
283
+ };
284
+ const release = (): void => {
285
+ if (read()?.token !== mine.token) return;
286
+ try {
287
+ unlinkSync(file);
288
+ } catch {}
289
+ };
290
+ return {
291
+ setPlayer: (pid) => exclusive(() => setPlayer(pid), () => setPlayer(pid)),
292
+ lost,
293
+ release: () => exclusive(release, release),
294
+ paused: () => {
107
295
  const entry = read();
108
- return entry !== undefined && entry.token !== token;
296
+ if (entry === undefined || entry.token !== mine.token) return undefined;
297
+ return entry.paused === true;
298
+ },
299
+ setPaused: (paused) => exclusive(() => setPaused(paused), () => setPaused(paused)),
300
+ };
301
+ };
302
+
303
+ const busy = (): boolean => {
304
+ const entry = read();
305
+ return entry !== undefined && playing(entry);
306
+ };
307
+
308
+ const kindOf = (kind: ClaimKind = {}): Pick<Entry, "pausable" | "prompt"> => ({
309
+ ...(kind.pausable ? { pausable: true as const } : {}),
310
+ ...(kind.prompt ? { prompt: true as const } : {}),
311
+ });
312
+
313
+ /** Ends the reading in another session without touching what waits; true when one was playing or paused. */
314
+ const skip = (): boolean => takeOver({ token: randomUUID(), ...self(), stopped: true }, false);
315
+
316
+ return {
317
+ claim(options = {}): Claim {
318
+ const mine: Entry = { token: randomUUID(), ...self(), ...kindOf(options) };
319
+ const take = (): void => {
320
+ if (options.dropWaiting) dropWaiting();
321
+ takeOver(mine, true);
109
322
  };
110
- return {
111
- setPlayer(pid) {
112
- if (lost()) return false;
113
- write({ ...mine, player: pid, playerStart: startTime(pid) });
114
- return true;
115
- },
116
- lost,
117
- release() {
118
- if (read()?.token !== token) return;
119
- try {
120
- unlinkSync(file);
121
- } catch {}
323
+ exclusive(take, take);
324
+ return held(mine);
325
+ },
326
+ claimIfFree(mark, kind) {
327
+ return exclusive<Claim | "busy" | "dropped">(
328
+ () => {
329
+ if (waitingMark() !== mark) return "dropped";
330
+ if (busy()) return "busy";
331
+ const mine: Entry = { token: randomUUID(), ...self(), ...kindOf(kind) };
332
+ write(mine);
333
+ return held(mine);
122
334
  },
335
+ () => "busy",
336
+ );
337
+ },
338
+ swapProject(project) {
339
+ const swap = (): string | undefined => {
340
+ let previous: string | undefined;
341
+ try {
342
+ const saved = (JSON.parse(readFileSync(projects, "utf8")) as { project?: unknown })?.project;
343
+ if (typeof saved === "string") previous = saved;
344
+ } catch {}
345
+ if (previous !== project) put(projects, randomUUID(), { project });
346
+ return previous;
123
347
  };
348
+ return exclusive(swap, swap);
349
+ },
350
+ busy,
351
+ waitingMark,
352
+ dropWaiting: () => exclusive(dropWaiting, dropWaiting),
353
+ stopOthers: () => {
354
+ const stop = (): boolean => {
355
+ dropWaiting();
356
+ return takeOver({ token: randomUUID(), ...self(), stopped: true }, false);
357
+ };
358
+ return exclusive(stop, stop);
359
+ },
360
+ skipOthers: () => exclusive(skip, skip),
361
+ togglePause: () => {
362
+ const toggle = (): "paused" | "resumed" | "stopped" | "unsupported" | undefined => {
363
+ const entry = read();
364
+ if (entry === undefined || !playing(entry)) return undefined;
365
+ if (entry.prompt) return skip() ? "stopped" : undefined;
366
+ if (!entry.pausable) return "unsupported";
367
+ if (entry.paused) {
368
+ const { paused: _paused, ...rest } = entry;
369
+ write(rest);
370
+ return "resumed";
371
+ }
372
+ write({ ...entry, paused: true });
373
+ return "paused";
374
+ };
375
+ return exclusive(toggle, toggle);
376
+ },
377
+ publishLine(token, session, items, tag, asking) {
378
+ if (items.length === 0) {
379
+ try {
380
+ unlinkSync(lineFile(token));
381
+ } catch {}
382
+ return;
383
+ }
384
+ put(lineFile(token), token, {
385
+ token,
386
+ session,
387
+ tag: tag || token.slice(-4),
388
+ beat: Date.now(),
389
+ ...(asking ? { asking: true } : {}),
390
+ pid: process.pid,
391
+ pidStart: startTime(process.pid),
392
+ items,
393
+ });
394
+ },
395
+ waitingList() {
396
+ let names: string[];
397
+ try {
398
+ names = readdirSync(dir).filter((name) => /^line-[\w-]+\.json$/.test(name));
399
+ } catch {
400
+ return [];
401
+ }
402
+ const mark = waitingMark();
403
+ const all: MachineWaiting[] = [];
404
+ /** Each listed session's tag, by token, and the tokens under each label. */
405
+ const tags = new Map<string, string>();
406
+ const labels = new Map<string, Set<string>>();
407
+ for (const name of names) {
408
+ try {
409
+ const line = JSON.parse(readFileSync(join(dir, name), "utf8")) as {
410
+ token?: unknown;
411
+ session?: unknown;
412
+ tag?: unknown;
413
+ beat?: unknown;
414
+ asking?: unknown;
415
+ pid?: unknown;
416
+ pidStart?: unknown;
417
+ items?: unknown;
418
+ };
419
+ if (typeof line.token !== "string" || typeof line.session !== "string" || !Number.isInteger(line.pid) || !Array.isArray(line.items)) continue;
420
+ // A session whose process is gone left its line behind: it waits for nothing.
421
+ if (!sameProcess(line.pid as number, typeof line.pidStart === "string" ? line.pidStart : undefined)) {
422
+ try {
423
+ unlinkSync(join(dir, name));
424
+ } catch {}
425
+ continue;
426
+ }
427
+ for (const item of line.items as Partial<WaitingItem>[]) {
428
+ if (typeof item?.name !== "string" || typeof item.at !== "number") continue;
429
+ const itemMark = typeof item.mark === "string" ? item.mark : undefined;
430
+ // Dropped by an explicit action since it was queued (S8): it will never play.
431
+ if (itemMark !== mark) continue;
432
+ const beat = typeof line.beat === "number" ? line.beat : undefined;
433
+ all.push({
434
+ name: item.name,
435
+ at: item.at,
436
+ mark: itemMark,
437
+ session: line.session,
438
+ token: line.token,
439
+ beat,
440
+ ...(line.asking === true ? { asking: true as const } : {}),
441
+ });
442
+ tags.set(line.token, typeof line.tag === "string" && line.tag ? line.tag : line.token.slice(-4));
443
+ labels.set(line.session, (labels.get(line.session) ?? new Set<string>()).add(line.token));
444
+ }
445
+ } catch {}
446
+ }
447
+ for (const item of all) if ((labels.get(item.session)?.size ?? 0) > 1) item.session = `${item.session} #${tags.get(item.token)}`;
448
+ return all.sort((a, b) => a.at - b.at);
124
449
  },
125
- stopOthers: () => takeOver({ token: randomUUID(), ...self(), stopped: true }, false),
126
450
  };
127
451
  }
128
452
 
@@ -135,33 +459,7 @@ function playing(entry: Entry): boolean {
135
459
  return entry.player === undefined || isPlayer(entry.player, entry.playerStart);
136
460
  }
137
461
 
138
- /** A live process of this user with that pid, started when recorded (when recorded). */
139
- function sameProcess(pid: number, start: string | undefined): boolean {
140
- try {
141
- process.kill(pid, 0);
142
- } catch {
143
- return false;
144
- }
145
- return start === undefined || startTime(pid) === start;
146
- }
147
-
148
- /** Guards against pid reuse: only a live player we started, of this user, may be signalled. */
149
- function isPlayer(pid: number, start: string | undefined): boolean {
150
- if (!sameProcess(pid, start)) return false;
151
- try {
152
- if (process.getuid && statSync(`/proc/${pid}`).uid !== process.getuid()) return false;
153
- return readFileSync(`/proc/${pid}/cmdline`, "utf8").split("\0").includes(PLAYER_MARK);
154
- } catch {
155
- return false;
156
- }
157
- }
158
-
159
- /** Field 22 of /proc/<pid>/stat, the process start time; undefined where /proc is missing. */
160
- function startTime(pid: number): string | undefined {
161
- try {
162
- const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
163
- return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
164
- } catch {
165
- return undefined;
166
- }
462
+ /** Blocks this thread for `ms`; only ever a few milliseconds, while another process holds the mutex. */
463
+ function pause(ms: number): void {
464
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
167
465
  }