pi-reply-reader 0.0.0-stage → 0.1.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,44 @@
1
+ /**
2
+ * The event contract other Pi extensions use to reach the reader over Pi's shared event bus (`pi.events`), S10.
3
+ * No package depends on the other, so the channel names and the payload version live only here.
4
+ */
5
+
6
+ /** The payload version both sides send; a payload with any other `v` is ignored. */
7
+ export const READER_EVENTS_VERSION = 1;
8
+
9
+ /** The channels of contract v1. */
10
+ export const READER_EVENTS = {
11
+ /** `{ v: 1 }`: is a reader there? Answered at once with `ready`. */
12
+ ping: "reply-reader:ping",
13
+ /** `{ v: 1 }`: the reader is there; also sent at every session start. */
14
+ ready: "reply-reader:ready",
15
+ /** `{ v: 1, id, text }`: read `text` (Markdown) aloud, naming `id` in the footer and messages. */
16
+ read: "reply-reader:read",
17
+ } as const;
18
+
19
+ /** What `ping` and `ready` carry. */
20
+ export interface ReaderPresence {
21
+ v: typeof READER_EVENTS_VERSION;
22
+ }
23
+
24
+ /** What `read` carries. */
25
+ export interface ReadRequest {
26
+ v: typeof READER_EVENTS_VERSION;
27
+ id: string;
28
+ text: string;
29
+ }
30
+
31
+ const isObject = (data: unknown): data is Record<string, unknown> => typeof data === "object" && data !== null && !Array.isArray(data);
32
+
33
+ /** Whether `data` is a v1 ping (an object with `v` 1). */
34
+ export function isPing(data: unknown): data is ReaderPresence {
35
+ return isObject(data) && data.v === READER_EVENTS_VERSION;
36
+ }
37
+
38
+ /** The read request in `data`, or undefined unless it is an object with `v` 1 and non-empty string `id` and `text`. */
39
+ export function parseReadRequest(data: unknown): ReadRequest | undefined {
40
+ if (!isObject(data) || data.v !== READER_EVENTS_VERSION) return undefined;
41
+ const { id, text } = data;
42
+ if (typeof id !== "string" || typeof text !== "string" || id === "" || text === "") return undefined;
43
+ return { v: READER_EVENTS_VERSION, id, text };
44
+ }
@@ -0,0 +1,167 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { isAbsolute, join } from "node:path";
4
+
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";
7
+
8
+ /**
9
+ * The reading playing on this machine, shared by every Pi session and process of this user (S1, T21):
10
+ * `$XDG_RUNTIME_DIR/pi-reply-reader/reading.json`. `token` names one reading; `stopped` marks an entry left by
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.
13
+ */
14
+ interface Entry {
15
+ token: string;
16
+ pid: number;
17
+ pidStart?: string;
18
+ player?: number;
19
+ playerStart?: string;
20
+ started: number;
21
+ stopped?: true;
22
+ }
23
+
24
+ /** One reading's hold on the machine. Nothing here throws. */
25
+ export interface Claim {
26
+ /** Records the reading's player; false when a newer reading or `/read-stop` took over before it started. */
27
+ setPlayer(pid: number): boolean;
28
+ /** Whether a newer reading or `/read-stop` from any session took over. */
29
+ lost(): boolean;
30
+ /** Drops the entry if it is still this reading's. */
31
+ release(): void;
32
+ }
33
+
34
+ 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. */
38
+ stopOthers(): boolean;
39
+ }
40
+
41
+ /**
42
+ * The machine-wide lock under `$XDG_RUNTIME_DIR`, or undefined when it is unset, relative or unusable: then each
43
+ * session only stops its own readings, as before.
44
+ */
45
+ export function openReadingLock(env: NodeJS.ProcessEnv): ReadingLock | undefined {
46
+ const runtime = env.XDG_RUNTIME_DIR;
47
+ if (!runtime || !isAbsolute(runtime)) return undefined;
48
+ const dir = join(runtime, "pi-reply-reader");
49
+ try {
50
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
51
+ if (!statSync(dir).isDirectory()) return undefined;
52
+ } catch {
53
+ return undefined;
54
+ }
55
+ const file = join(dir, "reading.json");
56
+
57
+ const read = (): Entry | undefined => {
58
+ try {
59
+ const entry = JSON.parse(readFileSync(file, "utf8")) as Entry;
60
+ if (typeof entry?.token !== "string" || !Number.isInteger(entry.pid)) return undefined;
61
+ if (entry.player !== undefined && !Number.isInteger(entry.player)) return undefined;
62
+ return entry;
63
+ } catch {
64
+ return undefined;
65
+ }
66
+ };
67
+
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`;
71
+ try {
72
+ writeFileSync(temp, JSON.stringify(entry), { mode: 0o600 });
73
+ renameSync(temp, file);
74
+ } catch {
75
+ try {
76
+ unlinkSync(temp);
77
+ } catch {}
78
+ }
79
+ };
80
+
81
+ /**
82
+ * Writes `entry` over the current one (always for a new reading; for `/read-stop` only when a reading plays) and
83
+ * stops the reading the current one names, if it still plays. The entry is written first, so the stopped
84
+ * session finds it lost when its player dies.
85
+ */
86
+ const takeOver = (entry: Entry, always: boolean): boolean => {
87
+ const previous = read();
88
+ const live = previous !== undefined && playing(previous);
89
+ if (always || live) write(entry);
90
+ if (!live) return false;
91
+ if (previous.player !== undefined) {
92
+ try {
93
+ process.kill(previous.player, "SIGTERM");
94
+ } catch {}
95
+ }
96
+ return true;
97
+ };
98
+
99
+ const self = (): Pick<Entry, "pid" | "pidStart" | "started"> => ({ pid: process.pid, pidStart: startTime(process.pid), started: Date.now() });
100
+
101
+ return {
102
+ claim(): Claim {
103
+ const token = randomUUID();
104
+ const mine: Entry = { token, ...self() };
105
+ takeOver(mine, true);
106
+ const lost = (): boolean => {
107
+ const entry = read();
108
+ return entry !== undefined && entry.token !== token;
109
+ };
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 {}
122
+ },
123
+ };
124
+ },
125
+ stopOthers: () => takeOver({ token: randomUUID(), ...self(), stopped: true }, false),
126
+ };
127
+ }
128
+
129
+ /**
130
+ * Whether `entry` names a reading that may still play: not a `/read-stop` mark, its process alive, and its player,
131
+ * once started, still that player of ours.
132
+ */
133
+ function playing(entry: Entry): boolean {
134
+ if (entry.stopped || !sameProcess(entry.pid, entry.pidStart)) return false;
135
+ return entry.player === undefined || isPlayer(entry.player, entry.playerStart);
136
+ }
137
+
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
+ }
167
+ }
package/src/replies.ts ADDED
@@ -0,0 +1,64 @@
1
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
+
3
+ export interface Reply {
4
+ /** `P<prompt>.R<n>`, numbered exactly like pi-reply-thread's `/replies`. */
5
+ id: string;
6
+ /** The Pi session entry ID of the assistant message. */
7
+ entryId: string;
8
+ text: string;
9
+ }
10
+
11
+ /** Stop reasons of an assistant message that finished speaking instead of calling tools or failing. */
12
+ const FINISHED = new Set(["stop", "length"]);
13
+
14
+ /** gentle-agents wakes the session with a user-role message; it is not a prompt. */
15
+ const WAKE_PREFIX = "[System-generated Gentle Agents notification, not written by the user]";
16
+
17
+ type Content = string | readonly { type: string; text?: string }[] | undefined;
18
+
19
+ function textOf(content: Content): string {
20
+ if (typeof content === "string") return content;
21
+ if (!content) return "";
22
+ return content
23
+ .filter((block) => block.type === "text" && typeof block.text === "string")
24
+ .map((block) => block.text)
25
+ .join("\n");
26
+ }
27
+
28
+ /**
29
+ * The final replies of a session branch (pass `ctx.sessionManager.getBranch()`), numbered under the prompt
30
+ * that preceded them. Replies before any prompt fall under P0.
31
+ */
32
+ export function listReplies(entries: readonly SessionEntry[]): Reply[] {
33
+ const replies: Reply[] = [];
34
+ let prompt = 0;
35
+ let index = 0;
36
+ for (const entry of entries) {
37
+ if (entry.type !== "message") continue;
38
+ const message = entry.message as { role?: string; content?: Content; stopReason?: string };
39
+ if (message.role === "user") {
40
+ if (textOf(message.content).startsWith(WAKE_PREFIX)) continue;
41
+ prompt += 1;
42
+ index = 0;
43
+ continue;
44
+ }
45
+ if (message.role !== "assistant" || !FINISHED.has(message.stopReason ?? "")) continue;
46
+ const text = textOf(message.content).trim();
47
+ if (!text) continue;
48
+ index += 1;
49
+ replies.push({ id: `P${prompt}.R${index}`, entryId: entry.id, text });
50
+ }
51
+ return replies;
52
+ }
53
+
54
+ /** By ordered ID in any case (a `.Q<n>` question suffix is accepted) or by exact entry ID. */
55
+ export function findReply(replies: readonly Reply[], id: string): Reply | undefined {
56
+ const wanted = id.trim();
57
+ if (!wanted) return undefined;
58
+ const ordered = /^(p\d+\.r\d+)(?:\.q\d+)?$/i.exec(wanted)?.[1].toUpperCase();
59
+ return replies.find((reply) => reply.id === ordered || reply.entryId === wanted);
60
+ }
61
+
62
+ export function latestReply(replies: readonly Reply[]): Reply | undefined {
63
+ return replies.at(-1);
64
+ }
@@ -0,0 +1,47 @@
1
+ /** A fence line opening or closing a code block; headings inside one are not headings. */
2
+ const FENCE = /^\s{0,3}(```|~~~)/;
3
+ /** An ATX heading: up to three spaces, one to six `#` (its level), then its text (a closing run of `#` is dropped). */
4
+ const HEADING = /^\s{0,3}(#{1,6})\s+(.*?)(?:\s+#+)?\s*$/;
5
+ /** Leading numbering of a heading or a section name: `2.`, `5.2.`, `3)`, `1:`. */
6
+ const NUMBERING = /^\d+(?:\.\d+)*[.):]?\s+/;
7
+
8
+ /**
9
+ * How a heading or a wanted section compares (S9): lower case, no accents, no leading numbering, `-`, `_` and `/` as
10
+ * spaces, other punctuation dropped, spaces collapsed.
11
+ */
12
+ export function sectionKey(text: string): string {
13
+ return text
14
+ .normalize("NFD")
15
+ .replace(/\p{M}/gu, "")
16
+ .toLowerCase()
17
+ .replace(/[-_/]/g, " ")
18
+ .replace(/[^\p{L}\p{N}\s]/gu, "")
19
+ .replace(/\s+/g, " ")
20
+ .trim()
21
+ .replace(NUMBERING, "");
22
+ }
23
+
24
+ /**
25
+ * The section of `markdown` whose heading matches `section` (S9): from that heading up to the next heading of the same
26
+ * or a higher level, or to the end with `rest`. Undefined when no heading matches. An exact match wins over a prefix
27
+ * match; a prefix match counts only when exactly one heading has it; of several exact matches the first wins.
28
+ */
29
+ export function sectionFrom(markdown: string, section: string, options: { rest?: boolean } = {}): string | undefined {
30
+ const wanted = sectionKey(section);
31
+ if (!wanted) return undefined;
32
+ const lines = markdown.split("\n");
33
+ const headings: { line: number; level: number; key: string }[] = [];
34
+ let fenced = false;
35
+ lines.forEach((line, index) => {
36
+ if (FENCE.test(line)) fenced = !fenced;
37
+ if (fenced) return;
38
+ const heading = HEADING.exec(line);
39
+ if (heading) headings.push({ line: index, level: heading[1].length, key: sectionKey(heading[2]) });
40
+ });
41
+ const exact = headings.find((heading) => heading.key === wanted);
42
+ const prefixes = headings.filter((heading) => heading.key.startsWith(wanted));
43
+ const match = exact ?? (prefixes.length === 1 ? prefixes[0] : undefined);
44
+ if (!match) return undefined;
45
+ const end = options.rest ? undefined : headings.find((heading) => heading.line > match.line && heading.level <= match.level)?.line;
46
+ return lines.slice(match.line, end).join("\n").trimEnd();
47
+ }
@@ -0,0 +1,94 @@
1
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+ import { configFile } from "./outputs.ts";
4
+
5
+ /** Supertonic's voice speed when none is saved (S3, L46). */
6
+ export const DEFAULT_SPEED = 1.1;
7
+ export const MIN_SPEED = 0.5;
8
+ export const MAX_SPEED = 2;
9
+ /** What `/read-speed` offers without a number. */
10
+ export const SPEED_CHOICES = ["0.8", "0.9", "1.0", "1.1", "1.2", "1.3", "1.5"];
11
+ export const SPEED_HINT = "Speed must be a number from 0.5 to 2.0.";
12
+
13
+ const SETTINGS = "settings.json";
14
+ /** Digits with an optional decimal part after a period or a comma, or only the decimal part (".9", ",9"). */
15
+ const NUMBER = /^(?:\d+(?:[.,]\d+)?|[.,]\d+)$/;
16
+
17
+ const inRange = (value: unknown): value is number =>
18
+ typeof value === "number" && Number.isFinite(value) && value >= MIN_SPEED && value <= MAX_SPEED;
19
+
20
+ /** A speed typed by the user ("1.15", "1,15" or ".9"), or undefined when it is not one from 0.5 to 2.0. */
21
+ export function parseSpeed(text: string): number | undefined {
22
+ const trimmed = text.trim();
23
+ if (!NUMBER.test(trimmed)) return undefined;
24
+ const value = Number(trimmed.replace(",", "."));
25
+ return inRange(value) ? value : undefined;
26
+ }
27
+
28
+ /** "1.15", and whole numbers with one decimal ("1.0", "2.0") as the selector shows them. */
29
+ export function formatSpeed(speed: number): string {
30
+ return Number.isInteger(speed) ? speed.toFixed(1) : String(speed);
31
+ }
32
+
33
+ /**
34
+ * The saved speed from `$XDG_CONFIG_HOME/pi-reply-reader/settings.json`. A missing file, folder or key means
35
+ * the default with no problem; an unreadable or invalid file, or a speed out of range, means the default and
36
+ * a `problem` for the user. Nothing throws.
37
+ */
38
+ export function loadSpeed(env: NodeJS.ProcessEnv): { speed: number; problem?: string } {
39
+ const path = configFile(env, SETTINGS);
40
+ if (!path) return { speed: DEFAULT_SPEED };
41
+ const ignored = (reason: string) => ({ speed: DEFAULT_SPEED, problem: `Ignored ${path}: ${reason}. Readings use speed ${formatSpeed(DEFAULT_SPEED)}.` });
42
+
43
+ let raw: string;
44
+ try {
45
+ raw = readFileSync(path, "utf8");
46
+ } catch (error) {
47
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { speed: DEFAULT_SPEED };
48
+ return ignored(`cannot be read (${(error as Error).message})`);
49
+ }
50
+ let parsed: unknown;
51
+ try {
52
+ parsed = JSON.parse(raw);
53
+ } catch (error) {
54
+ return ignored(`not valid JSON (${(error as Error).message})`);
55
+ }
56
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return ignored("expected an object");
57
+ if (!("speed" in parsed)) return { speed: DEFAULT_SPEED };
58
+ const { speed } = parsed as { speed: unknown };
59
+ return inRange(speed) ? { speed } : ignored("speed must be a number from 0.5 to 2.0");
60
+ }
61
+
62
+ /**
63
+ * Saves `speed` in settings.json, keeping every other key. Throws an Error naming the file and why when it
64
+ * cannot; an existing file that is not a JSON object is left as it is rather than overwritten.
65
+ */
66
+ export function saveSpeed(env: NodeJS.ProcessEnv, speed: number): void {
67
+ const path = configFile(env, SETTINGS);
68
+ if (!path) throw new Error(`it was not saved: no config folder (set XDG_CONFIG_HOME or HOME to an absolute path)`);
69
+ const fail = (reason: string) => new Error(`it was not saved to ${path}: ${reason}`);
70
+
71
+ let settings: Record<string, unknown> = {};
72
+ let raw: string | undefined;
73
+ try {
74
+ raw = readFileSync(path, "utf8");
75
+ } catch (error) {
76
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw fail((error as Error).message);
77
+ }
78
+ if (raw !== undefined) {
79
+ let parsed: unknown;
80
+ try {
81
+ parsed = JSON.parse(raw);
82
+ } catch {
83
+ throw fail("it is not valid JSON");
84
+ }
85
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw fail("it is not a JSON object");
86
+ settings = parsed as Record<string, unknown>;
87
+ }
88
+ try {
89
+ mkdirSync(dirname(path), { recursive: true });
90
+ writeFileSync(path, `${JSON.stringify({ ...settings, speed }, null, 2)}\n`);
91
+ } catch (error) {
92
+ throw fail((error as Error).message);
93
+ }
94
+ }
@@ -0,0 +1,29 @@
1
+ /** The part of sherpa-onnx-node 2.x (CommonJS, untyped) that playback.ts uses. */
2
+ declare module "sherpa-onnx-node" {
3
+ export class GenerationConfig {
4
+ constructor(options: {
5
+ sid?: number;
6
+ speed?: number;
7
+ numSteps?: number;
8
+ silenceScale?: number;
9
+ extra?: Record<string, number | string>;
10
+ });
11
+ }
12
+
13
+ export class OfflineTts {
14
+ static createAsync(config: {
15
+ model: { supertonic: Record<string, string>; numThreads?: number; provider?: string; debug?: number };
16
+ maxNumSentences?: number;
17
+ }): Promise<OfflineTts>;
18
+ readonly sampleRate: number;
19
+ readonly numSpeakers: number;
20
+ generateAsync(request: {
21
+ text: string;
22
+ generationConfig: GenerationConfig;
23
+ onProgress?: (info: { samples: Float32Array; progress: number }) => number | boolean | void;
24
+ }): Promise<{ samples: Float32Array; sampleRate: number }>;
25
+ }
26
+
27
+ const sherpa: { OfflineTts: typeof OfflineTts; GenerationConfig: typeof GenerationConfig };
28
+ export default sherpa;
29
+ }