@luxass/pi-questions 0.1.1 → 0.1.3
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/README.md +6 -4
- package/package.json +4 -1
- package/src/dialog.ts +376 -269
- package/src/index.ts +16 -11
- package/src/questions.ts +76 -124
- package/src/viewport.ts +40 -0
package/src/index.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
2
|
import { stripTerminalSequences, Text } from "@earendil-works/pi-tui";
|
|
3
|
+
import { HerdrBlockedReporter } from "@luxass/herdr-agent-shared";
|
|
3
4
|
|
|
4
5
|
import { QuestionDialog } from "./dialog.ts";
|
|
5
6
|
import {
|
|
@@ -10,7 +11,7 @@ import {
|
|
|
10
11
|
MIN_OPTIONS,
|
|
11
12
|
QuestionsSchema,
|
|
12
13
|
RESERVED_LABELS_TEXT,
|
|
13
|
-
|
|
14
|
+
sanitizeQuestions,
|
|
14
15
|
type QuestionResult,
|
|
15
16
|
type Questions,
|
|
16
17
|
} from "./questions.ts";
|
|
@@ -21,11 +22,12 @@ let inlineInUse = false;
|
|
|
21
22
|
|
|
22
23
|
async function showQuestions(
|
|
23
24
|
pi: ExtensionAPI,
|
|
24
|
-
|
|
25
|
+
blocked: HerdrBlockedReporter,
|
|
26
|
+
authored: Questions,
|
|
25
27
|
ctx: ExtensionContext,
|
|
26
28
|
signal?: AbortSignal,
|
|
27
29
|
): Promise<QuestionResult> {
|
|
28
|
-
const problem = findQuestionsProblem(
|
|
30
|
+
const problem = findQuestionsProblem(authored);
|
|
29
31
|
if (problem) return cancelledResult("invalid_questions", problem);
|
|
30
32
|
if (ctx.mode !== "tui")
|
|
31
33
|
return cancelledResult(
|
|
@@ -33,6 +35,7 @@ async function showQuestions(
|
|
|
33
35
|
"Questions were not shown. This tool requires interactive Pi. Ask the user in plain chat instead.",
|
|
34
36
|
);
|
|
35
37
|
if (signal?.aborted) return cancelledResult("aborted");
|
|
38
|
+
const params = sanitizeQuestions(authored);
|
|
36
39
|
let dialog: QuestionDialog | undefined;
|
|
37
40
|
const abort = () => dialog?.abort();
|
|
38
41
|
signal?.addEventListener("abort", abort);
|
|
@@ -58,6 +61,7 @@ async function showQuestions(
|
|
|
58
61
|
);
|
|
59
62
|
let ownsInlineSlot = !inlineInUse;
|
|
60
63
|
if (ownsInlineSlot) inlineInUse = true;
|
|
64
|
+
const releaseLabel = blocked.block("Waiting for answers");
|
|
61
65
|
try {
|
|
62
66
|
// Herdr's optional Pi integration owns state reporting and counts overlapping blockers.
|
|
63
67
|
pi.events.emit("herdr:blocked", { active: true, label: "Waiting for answers" });
|
|
@@ -73,9 +77,16 @@ async function showQuestions(
|
|
|
73
77
|
if (ownsInlineSlot) inlineInUse = false;
|
|
74
78
|
signal?.removeEventListener("abort", abort);
|
|
75
79
|
pi.events.emit("herdr:blocked", { active: false });
|
|
80
|
+
await releaseLabel();
|
|
76
81
|
}
|
|
77
82
|
}
|
|
78
83
|
export default function askQuestions(pi: ExtensionAPI) {
|
|
84
|
+
const blocked = new HerdrBlockedReporter({
|
|
85
|
+
source: "pi-questions:blocked",
|
|
86
|
+
agent: "pi",
|
|
87
|
+
appliesToSource: "herdr:pi",
|
|
88
|
+
});
|
|
89
|
+
pi.on("session_shutdown", () => blocked.clear());
|
|
79
90
|
pi.registerTool<typeof QuestionsSchema, QuestionResult>({
|
|
80
91
|
name: TOOL_NAME,
|
|
81
92
|
label: "Ask user",
|
|
@@ -90,7 +101,6 @@ export default function askQuestions(pi: ExtensionAPI) {
|
|
|
90
101
|
"Do not infer a choice for cancelled or unanswered questions. Notes alone do not answer a question.",
|
|
91
102
|
],
|
|
92
103
|
parameters: QuestionsSchema,
|
|
93
|
-
outputSchema: ResultSchema,
|
|
94
104
|
exposure: "model-only",
|
|
95
105
|
// Sequential execution keeps two questionnaires from competing for input.
|
|
96
106
|
executionMode: "sequential",
|
|
@@ -101,7 +111,7 @@ export default function askQuestions(pi: ExtensionAPI) {
|
|
|
101
111
|
openWorldHint: false,
|
|
102
112
|
},
|
|
103
113
|
async execute(_id, params, signal, _update, ctx) {
|
|
104
|
-
const result = await showQuestions(pi, params, ctx, signal);
|
|
114
|
+
const result = await showQuestions(pi, blocked, params, ctx, signal);
|
|
105
115
|
const prefix =
|
|
106
116
|
result.message ??
|
|
107
117
|
(result.cancelled
|
|
@@ -110,7 +120,6 @@ export default function askQuestions(pi: ExtensionAPI) {
|
|
|
110
120
|
return {
|
|
111
121
|
content: [{ type: "text", text: `${prefix}\n${JSON.stringify(result, null, 2)}` }],
|
|
112
122
|
details: result,
|
|
113
|
-
structuredContent: result,
|
|
114
123
|
isError: Boolean(result.error && result.error !== "aborted"),
|
|
115
124
|
};
|
|
116
125
|
},
|
|
@@ -145,11 +154,7 @@ export default function askQuestions(pi: ExtensionAPI) {
|
|
|
145
154
|
: details.cancelled
|
|
146
155
|
? "Questionnaire cancelled"
|
|
147
156
|
: `${count} ${count === 1 ? "answer" : "answers"} submitted${details.unanswered?.length ? ` · ${details.unanswered.length} unanswered` : ""}`;
|
|
148
|
-
return new Text(
|
|
149
|
-
theme.fg(details.cancelled ? "warning" : "success", stripTerminalSequences(label)),
|
|
150
|
-
0,
|
|
151
|
-
0,
|
|
152
|
-
);
|
|
157
|
+
return new Text(theme.fg(details.cancelled ? "warning" : "success", label), 0, 0);
|
|
153
158
|
},
|
|
154
159
|
});
|
|
155
160
|
|
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 =
|
|
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
|
|
12
|
-
|
|
13
|
-
|
|
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({
|
|
35
|
-
header: Type.String({
|
|
36
|
-
options: Type.Array(
|
|
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?:
|
|
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
|
|
103
|
-
export function findQuestionsProblem(params:
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
return `
|
|
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
|
-
|
|
149
|
-
|
|
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
|
-
|
|
153
|
-
if (!
|
|
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
|
-
|
|
172
|
-
|
|
173
|
-
...
|
|
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
|
-
|
|
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
|
}
|
package/src/viewport.ts
ADDED
|
@@ -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: 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
|
+
}
|