@luxass/pi-questions 0.1.2 → 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/index.ts CHANGED
@@ -11,23 +11,24 @@ import {
11
11
  MIN_OPTIONS,
12
12
  QuestionsSchema,
13
13
  RESERVED_LABELS_TEXT,
14
- ResultSchema,
14
+ sanitizeQuestions,
15
15
  type QuestionResult,
16
16
  type Questions,
17
17
  } from "./questions.ts";
18
18
 
19
19
  const TOOL_NAME = "ask_questions";
20
+ const QUESTION_BLOCKED_STATUS = { kind: "question", message: "Waiting for answers" } as const;
20
21
  // Only one questionnaire can own Pi's editor slot. Others stack at the bottom as overlays.
21
22
  let inlineInUse = false;
22
23
 
23
24
  async function showQuestions(
24
25
  pi: ExtensionAPI,
25
26
  blocked: HerdrBlockedReporter,
26
- params: Questions,
27
+ authored: Questions,
27
28
  ctx: ExtensionContext,
28
29
  signal?: AbortSignal,
29
30
  ): Promise<QuestionResult> {
30
- const problem = findQuestionsProblem(params);
31
+ const problem = findQuestionsProblem(authored);
31
32
  if (problem) return cancelledResult("invalid_questions", problem);
32
33
  if (ctx.mode !== "tui")
33
34
  return cancelledResult(
@@ -35,6 +36,7 @@ async function showQuestions(
35
36
  "Questions were not shown. This tool requires interactive Pi. Ask the user in plain chat instead.",
36
37
  );
37
38
  if (signal?.aborted) return cancelledResult("aborted");
39
+ const params = sanitizeQuestions(authored);
38
40
  let dialog: QuestionDialog | undefined;
39
41
  const abort = () => dialog?.abort();
40
42
  signal?.addEventListener("abort", abort);
@@ -55,15 +57,16 @@ async function showQuestions(
55
57
  ? {
56
58
  overlay: true,
57
59
  overlayOptions: { width: "100%", maxHeight: "70%", anchor: "bottom-center" },
60
+ blocked: QUESTION_BLOCKED_STATUS,
58
61
  }
59
- : { overlay: false },
62
+ : { overlay: false, blocked: QUESTION_BLOCKED_STATUS },
60
63
  );
61
64
  let ownsInlineSlot = !inlineInUse;
62
65
  if (ownsInlineSlot) inlineInUse = true;
63
- const releaseLabel = blocked.block("Waiting for answers");
66
+ const releaseLabel = blocked.block(QUESTION_BLOCKED_STATUS.message);
64
67
  try {
65
68
  // Herdr's optional Pi integration owns state reporting and counts overlapping blockers.
66
- pi.events.emit("herdr:blocked", { active: true, label: "Waiting for answers" });
69
+ pi.events.emit("herdr:blocked", { active: true, label: QUESTION_BLOCKED_STATUS.message });
67
70
  if (ownsInlineSlot) {
68
71
  const result = await mount(false);
69
72
  if (result) return result;
@@ -100,7 +103,6 @@ export default function askQuestions(pi: ExtensionAPI) {
100
103
  "Do not infer a choice for cancelled or unanswered questions. Notes alone do not answer a question.",
101
104
  ],
102
105
  parameters: QuestionsSchema,
103
- outputSchema: ResultSchema,
104
106
  exposure: "model-only",
105
107
  // Sequential execution keeps two questionnaires from competing for input.
106
108
  executionMode: "sequential",
@@ -120,7 +122,6 @@ export default function askQuestions(pi: ExtensionAPI) {
120
122
  return {
121
123
  content: [{ type: "text", text: `${prefix}\n${JSON.stringify(result, null, 2)}` }],
122
124
  details: result,
123
- structuredContent: result,
124
125
  isError: Boolean(result.error && result.error !== "aborted"),
125
126
  };
126
127
  },
@@ -155,11 +156,7 @@ export default function askQuestions(pi: ExtensionAPI) {
155
156
  : details.cancelled
156
157
  ? "Questionnaire cancelled"
157
158
  : `${count} ${count === 1 ? "answer" : "answers"} submitted${details.unanswered?.length ? ` · ${details.unanswered.length} unanswered` : ""}`;
158
- return new Text(
159
- theme.fg(details.cancelled ? "warning" : "success", stripTerminalSequences(label)),
160
- 0,
161
- 0,
162
- );
159
+ return new Text(theme.fg(details.cancelled ? "warning" : "success", label), 0, 0);
163
160
  },
164
161
  });
165
162
 
package/src/questions.ts CHANGED
@@ -1,39 +1,37 @@
1
+ import { stripTerminalSequences } from "@earendil-works/pi-tui";
1
2
  import { Type, type Static } from "typebox";
2
- import { Errors } from "typebox/value";
3
3
 
4
4
  export const MAX_QUESTIONS = 4;
5
5
  export const MIN_OPTIONS = 2;
6
- export const MAX_OPTIONS = 4;
7
- export const MAX_HEADER_LENGTH = 16;
8
- export const MAX_LABEL_LENGTH = 60;
6
+ export const MAX_OPTIONS = 6;
9
7
 
10
8
  /** Labels the dialog supplies itself. Authored options must not duplicate them. */
11
- export const RESERVED_LABELS = ["Other", "Type something.", "Next"] as const;
12
-
13
- /** Human-readable list of reserved labels, e.g. for tool descriptions and errors. */
14
- export const RESERVED_LABELS_TEXT = `${RESERVED_LABELS.slice(0, -1).join(", ")}, or ${RESERVED_LABELS.at(-1)}`;
15
- // RESERVED_LABELS lowercased without punctuation, for matching.
16
- const RESERVED = new Set(["other", "type something", "next"]);
17
-
18
- const OptionSchema = Type.Object(
19
- {
20
- label: Type.String({ minLength: 1, maxLength: MAX_LABEL_LENGTH }),
21
- description: Type.String({ minLength: 1 }),
22
- preview: Type.Optional(
23
- Type.String({ description: "Markdown, code, or a mockup for this option." }),
24
- ),
25
- },
26
- { additionalProperties: false },
27
- );
9
+ export const RESERVED_LABELS_TEXT = "Other, Type something., or Next";
10
+ // Ignore case and punctuation so `Other:` or `Type something` still match.
11
+ const RESERVED_LABEL = /^\W*(other|type\W*something|next)\W*$/iu;
28
12
 
13
+ // Pi validates arguments against this schema and reports problems to the model.
14
+ // The `\\S` pattern rejects blank text.
29
15
  export const QuestionsSchema = Type.Object(
30
16
  {
31
17
  questions: Type.Array(
32
18
  Type.Object(
33
19
  {
34
- question: Type.String({ minLength: 1 }),
35
- header: Type.String({ minLength: 1, maxLength: MAX_HEADER_LENGTH }),
36
- options: Type.Array(OptionSchema, { minItems: MIN_OPTIONS, maxItems: MAX_OPTIONS }),
20
+ question: Type.String({ pattern: "\\S" }),
21
+ header: Type.String({ pattern: "\\S", maxLength: 16 }),
22
+ options: Type.Array(
23
+ Type.Object(
24
+ {
25
+ label: Type.String({ pattern: "\\S", maxLength: 60 }),
26
+ description: Type.String({ pattern: "\\S" }),
27
+ preview: Type.Optional(
28
+ Type.String({ description: "Markdown, code, or a mockup for this option." }),
29
+ ),
30
+ },
31
+ { additionalProperties: false },
32
+ ),
33
+ { minItems: MIN_OPTIONS, maxItems: MAX_OPTIONS },
34
+ ),
37
35
  multiSelect: Type.Optional(Type.Boolean()),
38
36
  },
39
37
  { additionalProperties: false },
@@ -44,45 +42,27 @@ export const QuestionsSchema = Type.Object(
44
42
  { additionalProperties: false },
45
43
  );
46
44
 
47
- const QuestionIndexSchema = Type.Integer({ minimum: 0, maximum: MAX_QUESTIONS - 1 });
48
-
49
- export const ResultSchema = Type.Object(
50
- {
51
- answers: Type.Array(
52
- Type.Object(
53
- {
54
- questionIndex: QuestionIndexSchema,
55
- question: Type.String(),
56
- kind: Type.Union([Type.Literal("option"), Type.Literal("custom"), Type.Literal("multi")]),
57
- answer: Type.Union([Type.String(), Type.Null()]),
58
- selected: Type.Optional(Type.Array(Type.String())),
59
- notes: Type.Optional(Type.String()),
60
- preview: Type.Optional(Type.String()),
61
- },
62
- { additionalProperties: false },
63
- ),
64
- ),
65
- cancelled: Type.Boolean(),
66
- globalNote: Type.Optional(Type.String()),
67
- unanswered: Type.Optional(Type.Array(QuestionIndexSchema)),
68
- message: Type.Optional(Type.String()),
69
- error: Type.Optional(
70
- Type.Union([
71
- Type.Literal("no_ui"),
72
- Type.Literal("invalid_questions"),
73
- Type.Literal("aborted"),
74
- ]),
75
- ),
76
- },
77
- { additionalProperties: false },
78
- );
79
-
80
45
  export type Questions = Static<typeof QuestionsSchema>;
81
46
  export type Question = Questions["questions"][number];
82
- export type QuestionResult = Static<typeof ResultSchema>;
83
- export type QuestionError = NonNullable<QuestionResult["error"]>;
84
- export type Answer = QuestionResult["answers"][number];
85
47
 
48
+ export interface Answer {
49
+ questionIndex: number;
50
+ question: string;
51
+ selected: string[];
52
+ custom?: string;
53
+ notes?: string;
54
+ }
55
+
56
+ export interface QuestionResult {
57
+ answers: Answer[];
58
+ cancelled: boolean;
59
+ globalNote?: string;
60
+ unanswered?: number[];
61
+ message?: string;
62
+ error?: "no_ui" | "invalid_questions" | "aborted";
63
+ }
64
+
65
+ /** The dialog's state for one question. */
86
66
  export interface AnswerDraft {
87
67
  selected: Set<number>;
88
68
  custom: string;
@@ -90,7 +70,7 @@ export interface AnswerDraft {
90
70
  }
91
71
 
92
72
  /** Builds a result that carries no answers, optionally explaining why. */
93
- export function cancelledResult(error?: QuestionError, message?: string): QuestionResult {
73
+ export function cancelledResult(error?: QuestionResult["error"], message?: string): QuestionResult {
94
74
  return {
95
75
  answers: [],
96
76
  cancelled: true,
@@ -99,43 +79,34 @@ export function cancelledResult(error?: QuestionError, message?: string): Questi
99
79
  };
100
80
  }
101
81
 
102
- /** Returns a model-readable problem description, or `undefined` when the questions are valid. */
103
- export function findQuestionsProblem(params: unknown): string | undefined {
104
- const problems = new Set<string>();
105
- for (const error of Errors(QuestionsSchema, params))
106
- // `additionalProperties: false` also reports a less useful `schema is false` entry.
107
- if (error.keyword !== "boolean") problems.add(`${error.instancePath || "/"} ${error.message}`);
108
- if (problems.size)
109
- return `Provide 1–${MAX_QUESTIONS} questions with ${MIN_OPTIONS}–${MAX_OPTIONS} options each, non-empty text, headers up to ${MAX_HEADER_LENGTH} characters, and labels up to ${MAX_LABEL_LENGTH} characters. Problems: ${[...problems].slice(0, 5).join("; ")}.`;
110
- const { questions } = params as Questions;
111
- const seenQuestions = new Set<string>();
112
- for (const question of questions) {
113
- const key = question.question.trim().toLowerCase();
114
- if (!key || !question.header.trim()) return "Questions and headers must not be blank.";
115
- if (seenQuestions.has(key)) return "Questions must be distinct.";
116
- seenQuestions.add(key);
117
- const seenLabels = new Set<string>();
118
- for (const option of question.options) {
119
- const label = option.label.trim().toLowerCase();
120
- if (!label || !option.description.trim())
121
- return "Option labels and descriptions must not be blank.";
122
- // Ignore punctuation so `Other:` or `Type something` still match.
123
- if (
124
- RESERVED.has(
125
- label
126
- .replace(/[^\p{L}\p{N}\s]/gu, "")
127
- .replace(/\s+/g, " ")
128
- .trim(),
129
- )
130
- )
131
- return `Do not author ${RESERVED_LABELS_TEXT} options. The UI provides custom answers and navigation.`;
132
- if (seenLabels.has(label)) return "Option labels must be distinct within each question.";
133
- seenLabels.add(label);
134
- }
135
- }
82
+ /** Returns a model-readable problem the schema cannot express, or `undefined`. */
83
+ export function findQuestionsProblem(params: Questions): string | undefined {
84
+ if (
85
+ params.questions.some((question) =>
86
+ question.options.some((option) => RESERVED_LABEL.test(option.label)),
87
+ )
88
+ )
89
+ return `Do not author ${RESERVED_LABELS_TEXT} options. The UI provides custom answers and navigation.`;
136
90
  return undefined;
137
91
  }
138
92
 
93
+ /** Removes terminal control sequences from every authored string before display. */
94
+ export function sanitizeQuestions(params: Questions): Questions {
95
+ return {
96
+ questions: params.questions.map((question) => ({
97
+ ...question,
98
+ question: stripTerminalSequences(question.question),
99
+ header: stripTerminalSequences(question.header),
100
+ options: question.options.map((option) => ({
101
+ ...option,
102
+ label: stripTerminalSequences(option.label),
103
+ description: stripTerminalSequences(option.description),
104
+ ...(option.preview == null ? {} : { preview: stripTerminalSequences(option.preview) }),
105
+ })),
106
+ })),
107
+ };
108
+ }
109
+
139
110
  export function collectAnswers(
140
111
  params: Questions,
141
112
  drafts: readonly AnswerDraft[],
@@ -144,34 +115,20 @@ export function collectAnswers(
144
115
  const answers: Answer[] = [];
145
116
  const unanswered: number[] = [];
146
117
  params.questions.forEach((question, questionIndex) => {
147
- const draft = drafts[questionIndex];
148
- if (!draft) return;
149
- const options = question.options.filter((_option, index) => draft.selected.has(index));
118
+ const draft = drafts[questionIndex]!;
119
+ const selected = question.options
120
+ .filter((_option, index) => draft.selected.has(index))
121
+ .map((option) => option.label);
150
122
  const custom = draft.custom.trim();
151
123
  const notes = draft.notes.trim();
152
- const answered = options.length > 0 || custom.length > 0;
153
- if (!answered) unanswered.push(questionIndex);
154
- if (!answered && !notes) return;
155
- const notesField = notes ? { notes } : {};
156
- if (question.multiSelect) {
157
- answers.push({
158
- questionIndex,
159
- question: question.question,
160
- kind: "multi",
161
- answer: custom || null,
162
- selected: options.map((option) => option.label),
163
- ...notesField,
164
- });
165
- return;
166
- }
167
- const [option] = options;
124
+ if (!selected.length && !custom) unanswered.push(questionIndex);
125
+ if (!selected.length && !custom && !notes) return;
168
126
  answers.push({
169
127
  questionIndex,
170
128
  question: question.question,
171
- kind: option ? "option" : "custom",
172
- answer: option?.label ?? (custom || null),
173
- ...notesField,
174
- ...(option?.preview ? { preview: option.preview } : {}),
129
+ selected,
130
+ ...(custom ? { custom } : {}),
131
+ ...(notes ? { notes } : {}),
175
132
  });
176
133
  });
177
134
  const note = globalNote.trim();
@@ -184,10 +141,5 @@ export function collectAnswers(
184
141
  }
185
142
 
186
143
  export function answerText(answer: Answer): string {
187
- if (answer.kind === "multi")
188
- return (
189
- [...(answer.selected ?? []), ...(answer.answer ? [answer.answer] : [])].join(", ") ||
190
- "Not answered"
191
- );
192
- return answer.answer || "Not answered";
144
+ return [...answer.selected, answer.custom].filter(Boolean).join(", ") || "Not answered";
193
145
  }
@@ -0,0 +1,40 @@
1
+ import { ScrollView, type Component, type TuiMouseEvent } from "@earendil-works/pi-tui";
2
+
3
+ /** Bounds a ScrollView inside a custom editor component, including mouse routing. */
4
+ export class Viewport extends ScrollView {
5
+ maxHeight = 1;
6
+ totalLines = 0;
7
+ followLine?: (lines: readonly string[]) => number | undefined;
8
+ private readonly requestRender: () => void;
9
+
10
+ constructor(content: Component, requestRender: () => void) {
11
+ super(content, { scrollbar: "hidden" });
12
+ this.requestRender = requestRender;
13
+ }
14
+
15
+ override render(width: number): string[] {
16
+ const lines = super.render(width);
17
+ this.totalLines = lines.length;
18
+ const height = Math.max(1, Math.min(this.maxHeight, Math.max(1, lines.length)));
19
+ this.updateLayout(lines.length, height, this.requestRender);
20
+ const focusLine = this.followLine?.(lines);
21
+ if (focusLine !== undefined && focusLine >= 0) {
22
+ if (focusLine < this.scrollTop) this.scrollTo(focusLine);
23
+ else if (focusLine >= this.scrollTop + height) this.scrollTo(focusLine - height + 1);
24
+ }
25
+ const visible = lines.slice(this.scrollTop, this.scrollTop + height);
26
+ while (visible.length < height) visible.push("");
27
+ return visible;
28
+ }
29
+
30
+ override handleMouse(event: TuiMouseEvent) {
31
+ if (event.y < 0 || event.y >= this.viewportHeight) return undefined;
32
+ // ScrollView renders its full child in custom components. Translate once,
33
+ // then let the child containers route the event to their buttons or editor.
34
+ return super.handleMouse({
35
+ ...event,
36
+ y: event.y + this.scrollTop,
37
+ height: this.totalLines,
38
+ });
39
+ }
40
+ }