@lune_99/pi-ask-question 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.
@@ -0,0 +1,42 @@
1
+ import { visibleWidth } from "@earendil-works/pi-tui";
2
+
3
+ /** A part of a one-line summary; parts with a lower rank give way first when the line is too long. */
4
+ export interface RankedPart {
5
+ text: string;
6
+ rank: number;
7
+ }
8
+
9
+ /**
10
+ * The richest line that fits in `width`. `compose` gets the kept parts in their original order;
11
+ * the lowest-ranked part, the last one among equals, is left out until the line fits. So a narrow
12
+ * row shows fewer complete parts instead of a cut one. Undefined when not even `compose([])` fits.
13
+ */
14
+ export function fitRanked(
15
+ parts: readonly RankedPart[],
16
+ width: number,
17
+ compose: (texts: readonly string[]) => string,
18
+ ): string | undefined {
19
+ const kept = [...parts];
20
+
21
+ for (;;) {
22
+ const line = compose(kept.map((part) => part.text));
23
+
24
+ if (visibleWidth(line) <= width) {
25
+ return line;
26
+ }
27
+
28
+ if (kept.length === 0) {
29
+ return undefined;
30
+ }
31
+
32
+ let lowest = 0;
33
+
34
+ for (let index = 1; index < kept.length; index++) {
35
+ if (kept[index]!.rank <= kept[lowest]!.rank) {
36
+ lowest = index;
37
+ }
38
+ }
39
+
40
+ kept.splice(lowest, 1);
41
+ }
42
+ }
@@ -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
+ }
@@ -15,10 +15,7 @@ import type {
15
15
  } from "../../core/question-types.ts";
16
16
 
17
17
  /** One selectable line of the focused question, in panel order. */
18
- export type QuestionRow =
19
- | { kind: "option"; index: number }
20
- | { kind: "custom" }
21
- | { kind: "next" };
18
+ export type QuestionRow = { kind: "option"; index: number } | { kind: "custom" } | { kind: "next" };
22
19
 
23
20
  /** Rows of one question: its options, the free-form row, and the multi-select confirm row. */
24
21
  export function questionRows(question: AskQuestion): QuestionRow[] {
@@ -60,6 +57,12 @@ export function areAllAnswered(
60
57
  return questions.every((_, index) => draft.answers[index] !== undefined);
61
58
  }
62
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
+
63
66
  /** What a number key did, so the caller knows whether advancing has to follow. */
64
67
  export type PickOptionResult = "answer" | "toggle" | "ignored";
65
68
 
@@ -115,8 +118,8 @@ export class QuestionPanelController {
115
118
 
116
119
  const rows = questionRows(question);
117
120
 
118
- this.draft.optionIndex = (focusedRowIndex(rows, this.draft.optionIndex) + step + rows.length)
119
- % rows.length;
121
+ this.draft.optionIndex =
122
+ (focusedRowIndex(rows, this.draft.optionIndex) + step + rows.length) % rows.length;
120
123
  }
121
124
 
122
125
  /** Jump to a tab; the submit tab is `questions.length`. Returns whether the tab changed. */
@@ -193,9 +196,8 @@ export class QuestionPanelController {
193
196
 
194
197
  // A written answer and selected options are mutually exclusive; the written
195
198
  // draft itself stays in `customDrafts` so the editor can restore it.
196
- this.draft.answers[questionIndex] = indexes.length > 0
197
- ? { selectedIndexes: indexes }
198
- : undefined;
199
+ this.draft.answers[questionIndex] =
200
+ indexes.length > 0 ? { selectedIndexes: indexes } : undefined;
199
201
  }
200
202
 
201
203
  answerWithOption(index: number): void {
@@ -213,9 +215,8 @@ export class QuestionPanelController {
213
215
 
214
216
  const questionIndex = this.draft.currentIndex;
215
217
 
216
- this.draft.currentIndex = questionIndex < this.questions.length - 1
217
- ? questionIndex + 1
218
- : this.questions.length;
218
+ this.draft.currentIndex =
219
+ questionIndex < this.questions.length - 1 ? questionIndex + 1 : this.questions.length;
219
220
  this.draft.optionIndex = 0;
220
221
 
221
222
  return "next";