pi-reply-reader 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/project.ts ADDED
@@ -0,0 +1,46 @@
1
+ import { existsSync, readFileSync, statSync } from "node:fs";
2
+ import { basename, dirname, resolve } from "node:path";
3
+ import { openReadingLock } from "./reading-lock.ts";
4
+
5
+ /**
6
+ * A reading's project (S19): the folder name of the Git root its working folder is in, else of the working folder
7
+ * itself. The root is the nearest folder upward holding a `.git`, found without running git. A `.git` file names its
8
+ * gitdir: a linked worktree's holds `commondir`, so it is the same repo and is named by the folder of the main
9
+ * `.git`; a submodule's does not, so it keeps its own folder name.
10
+ */
11
+ export function projectOf(cwd: string): string {
12
+ const start = resolve(cwd);
13
+ for (let dir = start; ; dir = dirname(dir)) {
14
+ const git = resolve(dir, ".git");
15
+ if (existsSync(git)) return mainRepo(dir, git) ?? (basename(dir) || dir);
16
+ if (dirname(dir) === dir) return basename(start) || start;
17
+ }
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: string, git: string): string | undefined {
22
+ try {
23
+ if (!statSync(git).isFile()) return undefined;
24
+ const gitdir = /^gitdir:\s*(.+?)\s*$/m.exec(readFileSync(git, "utf8"))?.[1];
25
+ if (!gitdir) return undefined;
26
+ const resolved = resolve(dir, gitdir);
27
+ const common = readFileSync(resolve(resolved, "commondir"), "utf8").trim();
28
+ if (!common) return undefined;
29
+ const main = dirname(resolve(resolved, common));
30
+ return basename(main) || undefined;
31
+ } catch {
32
+ return undefined;
33
+ }
34
+ }
35
+
36
+ /**
37
+ * Records `project` as the machine's last reading's (S19) and says whether it must be announced: it differs from the
38
+ * one remembered, or none was. The memory is shared next to the reading lock by every Pi session and the
39
+ * `reply-reader` command; without a usable XDG_RUNTIME_DIR it is `local`, the caller's own (a process's).
40
+ */
41
+ export function projectChanged(env: NodeJS.ProcessEnv, project: string, local: { last?: string }): boolean {
42
+ const lock = openReadingLock(env);
43
+ const previous = lock ? lock.swapProject(project) : local.last;
44
+ if (!lock) local.last = project;
45
+ return previous !== project;
46
+ }
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
+ }
@@ -0,0 +1,19 @@
1
+ const FENCE = /^\s{0,3}(```|~~~)/;
2
+ /**
3
+ * The closing questions heading of a reply (S8): "Needs your decision" as a Markdown heading or a bold-only line,
4
+ * any case, with or without a final colon (inside or outside the bold).
5
+ */
6
+ const QUESTIONS =
7
+ /^\s{0,3}(?:#{1,6}\s+(?:\*\*|__)?needs your decision:?(?:\*\*|__)?:?(?:\s+#+)?|(?:\*\*|__)needs your decision:?(?:\*\*|__):?)\s*$/i;
8
+
9
+ /** The last "Needs your decision" heading or bold-only line and everything after it, or undefined when there is none. */
10
+ export function questionsSection(markdown: string): string | undefined {
11
+ const lines = markdown.split("\n");
12
+ let start: number | undefined;
13
+ let fenced = false;
14
+ lines.forEach((line, index) => {
15
+ if (FENCE.test(line)) fenced = !fenced;
16
+ if (!fenced && QUESTIONS.test(line)) start = index;
17
+ });
18
+ return start === undefined ? undefined : lines.slice(start).join("\n").trimEnd();
19
+ }
@@ -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
+ }