@lune_99/pi-ask-question 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,124 @@
1
+ /**
2
+ * Clipboard paste for the answer editor, in the order pi's own editor uses for
3
+ * `app.clipboard.pasteImage`: copied files paste as their paths, an image is saved to a
4
+ * temporary file and pastes as that path, and plain text comes last. The model reads a pasted
5
+ * image through its path, as it does after a paste into pi's editor.
6
+ *
7
+ * pi does not export its clipboard reader, so this reads pi-tui's native clipboard, which is
8
+ * the reader pi itself uses for images and files on macOS and Windows.
9
+ */
10
+ import { randomUUID } from "node:crypto";
11
+ import { writeFile } from "node:fs/promises";
12
+ import { tmpdir } from "node:os";
13
+ import { join } from "node:path";
14
+
15
+ import { convertToPng } from "@earendil-works/pi-coding-agent";
16
+ import { getNativeClipboard } from "@earendil-works/pi-tui";
17
+
18
+ const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
19
+ const JPEG_SIGNATURE = [0xff, 0xd8, 0xff];
20
+
21
+ export interface ClipboardPaste {
22
+ text: string;
23
+ /** A path has to be kept apart from the words around it; text is inserted as copied. */
24
+ isPath: boolean;
25
+ }
26
+
27
+ /** `undefined` when the clipboard holds nothing to paste; a failed read rejects. */
28
+ export async function readClipboardPaste(): Promise<ClipboardPaste | undefined> {
29
+ const clipboard = getNativeClipboard();
30
+
31
+ if (!clipboard) {
32
+ throw new Error("no native clipboard is available on this system");
33
+ }
34
+
35
+ const paths = await clipboard.getFilePaths?.();
36
+
37
+ if (paths && paths.length > 0) {
38
+ // The path becomes answer text that the terminal draws, so a control character in a
39
+ // file name could rewrite what the panel shows.
40
+ if (paths.some((path) => /\p{Cc}/u.test(path))) {
41
+ throw new Error("a copied file path contains control characters");
42
+ }
43
+
44
+ return { text: paths.join("\n"), isPath: true };
45
+ }
46
+
47
+ const image = await clipboard.getImage();
48
+
49
+ if (image && image.length > 0) {
50
+ return { text: await saveClipboardImage(image), isPath: true };
51
+ }
52
+
53
+ const text = await clipboard.getText();
54
+
55
+ return text ? { text, isPath: false } : undefined;
56
+ }
57
+
58
+ async function saveClipboardImage(bytes: Uint8Array): Promise<string> {
59
+ let extension = imageExtension(bytes);
60
+ let data = bytes;
61
+
62
+ if (extension === undefined) {
63
+ // A clipboard can hold formats a model cannot read, such as the BMP that Windows puts
64
+ // there; pi converts those to PNG as well.
65
+ const png = await convertToPng(
66
+ Buffer.from(bytes).toString("base64"),
67
+ "application/octet-stream",
68
+ );
69
+
70
+ if (!png) {
71
+ throw new Error("the clipboard image format is not supported");
72
+ }
73
+
74
+ data = Buffer.from(png.data, "base64");
75
+ extension = "png";
76
+ }
77
+
78
+ const path = join(tmpdir(), `pi-clipboard-${randomUUID()}.${extension}`);
79
+
80
+ await writeFile(path, data);
81
+
82
+ return path;
83
+ }
84
+
85
+ /** The image formats a model receives without conversion. */
86
+ function imageExtension(bytes: Uint8Array): string | undefined {
87
+ if (startsWithBytes(bytes, PNG_SIGNATURE)) {
88
+ return "png";
89
+ }
90
+
91
+ if (startsWithBytes(bytes, JPEG_SIGNATURE)) {
92
+ return "jpg";
93
+ }
94
+
95
+ if (startsWithAscii(bytes, 0, "GIF87a") || startsWithAscii(bytes, 0, "GIF89a")) {
96
+ return "gif";
97
+ }
98
+
99
+ if (startsWithAscii(bytes, 0, "RIFF") && startsWithAscii(bytes, 8, "WEBP")) {
100
+ return "webp";
101
+ }
102
+
103
+ return undefined;
104
+ }
105
+
106
+ function startsWithBytes(bytes: Uint8Array, signature: readonly number[]): boolean {
107
+ return (
108
+ bytes.length >= signature.length && signature.every((byte, index) => bytes[index] === byte)
109
+ );
110
+ }
111
+
112
+ function startsWithAscii(bytes: Uint8Array, offset: number, text: string): boolean {
113
+ if (bytes.length < offset + text.length) {
114
+ return false;
115
+ }
116
+
117
+ for (let index = 0; index < text.length; index++) {
118
+ if (bytes[offset + index] !== text.charCodeAt(index)) {
119
+ return false;
120
+ }
121
+ }
122
+
123
+ return true;
124
+ }
@@ -0,0 +1,262 @@
1
+ /**
2
+ * Question interaction model of the panel: the rows a question offers and the draft
3
+ * transitions that move between them.
4
+ *
5
+ * It works on the request's `draft` in place instead of holding state of its own, so the only
6
+ * copy that has to be persisted is the one already on the request. Nothing here touches the
7
+ * terminal: rendering the resulting draft is the renderer's job, and the panel is what turns a
8
+ * transition into a render request, an editor mode change or a settle.
9
+ */
10
+ import type {
11
+ AskQuestion,
12
+ AskQuestionAnswer,
13
+ AskQuestionDraft,
14
+ AskQuestionRequest,
15
+ } from "../../core/question-types.ts";
16
+
17
+ /** One selectable line of the focused question, in panel order. */
18
+ export type QuestionRow = { kind: "option"; index: number } | { kind: "custom" } | { kind: "next" };
19
+
20
+ /** Rows of one question: its options, the free-form row, and the multi-select confirm row. */
21
+ export function questionRows(question: AskQuestion): QuestionRow[] {
22
+ const rows: QuestionRow[] = (question.options ?? []).map((_, index) => ({
23
+ kind: "option" as const,
24
+ index,
25
+ }));
26
+
27
+ rows.push({ kind: "custom" });
28
+
29
+ // `Enter` toggles checkboxes in a multi-select question, so confirming the
30
+ // selection needs a row of its own.
31
+ if (question.multiSelect === true && (question.options?.length ?? 0) > 0) {
32
+ rows.push({ kind: "next" });
33
+ }
34
+
35
+ return rows;
36
+ }
37
+
38
+ /** Clamped row index: a restored draft may carry an `optionIndex` past the current rows. */
39
+ export function focusedRowIndex(rows: readonly QuestionRow[], optionIndex: number): number {
40
+ return Math.min(rows.length - 1, Math.max(0, optionIndex));
41
+ }
42
+
43
+ export function focusedQuestionRow(
44
+ question: AskQuestion,
45
+ optionIndex: number,
46
+ ): QuestionRow | undefined {
47
+ const rows = questionRows(question);
48
+
49
+ return rows[focusedRowIndex(rows, optionIndex)];
50
+ }
51
+
52
+ /** True when every question has an answer; the header, the tabs and submit read it. */
53
+ export function areAllAnswered(
54
+ questions: readonly AskQuestion[],
55
+ draft: AskQuestionDraft,
56
+ ): boolean {
57
+ return questions.every((_, index) => draft.answers[index] !== undefined);
58
+ }
59
+
60
+ /** The read-only part of the controller that the renderer draws from. */
61
+ export type QuestionPanelView = Pick<
62
+ QuestionPanelController,
63
+ "draft" | "questions" | "isMultiQuestion" | "isSubmitTab" | "currentQuestion" | "allAnswered"
64
+ >;
65
+
66
+ /** What a number key did, so the caller knows whether advancing has to follow. */
67
+ export type PickOptionResult = "answer" | "toggle" | "ignored";
68
+
69
+ /** What follows an answered question: advance to the next one, or settle the request. */
70
+ export type AdvanceResult = "submit" | "next";
71
+
72
+ export class QuestionPanelController {
73
+ private readonly request: AskQuestionRequest;
74
+
75
+ constructor(request: AskQuestionRequest) {
76
+ this.request = request;
77
+ }
78
+
79
+ get draft(): AskQuestionDraft {
80
+ return this.request.draft;
81
+ }
82
+
83
+ get questions(): readonly AskQuestion[] {
84
+ return this.request.questions;
85
+ }
86
+
87
+ get isMultiQuestion(): boolean {
88
+ return this.questions.length > 1;
89
+ }
90
+
91
+ get isSubmitTab(): boolean {
92
+ return this.draft.currentIndex >= this.questions.length;
93
+ }
94
+
95
+ currentQuestion(): AskQuestion | undefined {
96
+ return this.questions[this.draft.currentIndex];
97
+ }
98
+
99
+ focusedRow(): QuestionRow | undefined {
100
+ const question = this.currentQuestion();
101
+
102
+ return question === undefined
103
+ ? undefined
104
+ : focusedQuestionRow(question, this.draft.optionIndex);
105
+ }
106
+
107
+ /** True while the cursor sits on the "type something" row of the current question. */
108
+ isCustomRowFocused(): boolean {
109
+ return this.focusedRow()?.kind === "custom";
110
+ }
111
+
112
+ moveRow(step: number): void {
113
+ const question = this.currentQuestion();
114
+
115
+ if (!question) {
116
+ return;
117
+ }
118
+
119
+ const rows = questionRows(question);
120
+
121
+ this.draft.optionIndex =
122
+ (focusedRowIndex(rows, this.draft.optionIndex) + step + rows.length) % rows.length;
123
+ }
124
+
125
+ /** Jump to a tab; the submit tab is `questions.length`. Returns whether the tab changed. */
126
+ selectTab(index: number): boolean {
127
+ if (index < 0 || index > this.questions.length || index === this.draft.currentIndex) {
128
+ return false;
129
+ }
130
+
131
+ this.draft.currentIndex = index;
132
+ this.draft.optionIndex = 0;
133
+
134
+ return true;
135
+ }
136
+
137
+ moveTab(step: number): void {
138
+ const total = this.questions.length + 1;
139
+ const current = Math.min(total - 1, Math.max(0, this.draft.currentIndex));
140
+
141
+ this.draft.currentIndex = (current + step + total) % total;
142
+ this.draft.optionIndex = 0;
143
+ }
144
+
145
+ pickOption(index: number): PickOptionResult {
146
+ const question = this.currentQuestion();
147
+
148
+ if (!question?.options?.[index]) {
149
+ return "ignored";
150
+ }
151
+
152
+ this.draft.optionIndex = index;
153
+
154
+ if (question.multiSelect === true) {
155
+ this.toggleOption(index);
156
+ return "toggle";
157
+ }
158
+
159
+ this.answerWithOption(index);
160
+
161
+ return "answer";
162
+ }
163
+
164
+ toggleFocusedRow(): void {
165
+ const question = this.currentQuestion();
166
+
167
+ if (!question || question.multiSelect !== true) {
168
+ return;
169
+ }
170
+
171
+ const row = this.focusedRow();
172
+
173
+ if (row?.kind === "option") {
174
+ this.toggleOption(row.index);
175
+ }
176
+ }
177
+
178
+ toggleOption(index: number): void {
179
+ const question = this.currentQuestion();
180
+
181
+ if (!question?.options?.[index]) {
182
+ return;
183
+ }
184
+
185
+ const questionIndex = this.draft.currentIndex;
186
+ const answer = this.draft.answers[questionIndex];
187
+ const selected = new Set(answer?.selectedIndexes ?? []);
188
+
189
+ if (selected.has(index)) {
190
+ selected.delete(index);
191
+ } else {
192
+ selected.add(index);
193
+ }
194
+
195
+ const indexes = Array.from(selected).sort((left, right) => left - right);
196
+
197
+ // A written answer and selected options are mutually exclusive; the written
198
+ // draft itself stays in `customDrafts` so the editor can restore it.
199
+ this.draft.answers[questionIndex] =
200
+ indexes.length > 0 ? { selectedIndexes: indexes } : undefined;
201
+ }
202
+
203
+ answerWithOption(index: number): void {
204
+ this.draft.answers[this.draft.currentIndex] = { selectedIndexes: [index] };
205
+ }
206
+
207
+ /**
208
+ * Move past the answered question; `"submit"` asks the caller to settle a single-question
209
+ * request instead of advancing.
210
+ */
211
+ advanceAfterAnswer(): AdvanceResult {
212
+ if (this.questions.length === 1) {
213
+ return "submit";
214
+ }
215
+
216
+ const questionIndex = this.draft.currentIndex;
217
+
218
+ this.draft.currentIndex =
219
+ questionIndex < this.questions.length - 1 ? questionIndex + 1 : this.questions.length;
220
+ this.draft.optionIndex = 0;
221
+
222
+ return "next";
223
+ }
224
+
225
+ setCustomAnswer(text: string): void {
226
+ const questionIndex = this.draft.currentIndex;
227
+
228
+ this.draft.customDrafts[questionIndex] = text;
229
+ this.draft.answers[questionIndex] = { selectedIndexes: [], customText: text };
230
+ }
231
+
232
+ allAnswered(): boolean {
233
+ return areAllAnswered(this.questions, this.draft);
234
+ }
235
+
236
+ /**
237
+ * True when the request can be submitted; otherwise the focus moves to the first gap and
238
+ * the caller must not settle it. Landing on the first gap is more useful than a dead Enter
239
+ * press.
240
+ */
241
+ prepareSubmit(): boolean {
242
+ if (this.allAnswered()) {
243
+ return true;
244
+ }
245
+
246
+ const missing = this.draft.answers.findIndex((answer) => answer === undefined);
247
+
248
+ if (missing >= 0) {
249
+ this.draft.currentIndex = missing;
250
+ this.draft.optionIndex = 0;
251
+ }
252
+
253
+ return false;
254
+ }
255
+
256
+ /** Answers in question order for the manager; complete only after `prepareSubmit`. */
257
+ collectAnswers(): AskQuestionAnswer[] {
258
+ return this.draft.answers.filter(
259
+ (answer): answer is AskQuestionAnswer => answer !== undefined,
260
+ );
261
+ }
262
+ }