@rol1n/ask-u-questions 0.0.0-stage → 0.1.1

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 CHANGED
@@ -1,3 +1,26 @@
1
- # Temporary Holding Version
1
+ # ask-u-questions
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Interactive single-choice, multiple-choice, and free-text questions for Pi. Registers the `ask_user_question` tool and serializes dialogs through a shared UI lock.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ pi install npm:@rol1n/ask-u-questions
9
+ ```
10
+
11
+ Also included in `@rol1n/pi-kit`.
12
+
13
+ ## Use
14
+
15
+ ```json
16
+ {
17
+ "question": "Which output format should I use?",
18
+ "options": [
19
+ { "label": "Markdown (Recommended)", "value": "markdown" },
20
+ { "label": "JSON", "value": "json" }
21
+ ],
22
+ "multiSelect": false
23
+ }
24
+ ```
25
+
26
+ Omit `options` or pass `[]` for free-text input. Set `multiSelect: true` only when multiple choices are expected. `details` adds supporting context, and an `Other` option is provided automatically for choice questions.
package/dialog-ui.ts ADDED
@@ -0,0 +1,80 @@
1
+ import type { Theme } from "@earendil-works/pi-coding-agent";
2
+ import { type EditorTheme, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
3
+
4
+ export function createEditorTheme(theme: Theme): EditorTheme {
5
+ return {
6
+ borderColor: (s) => theme.fg("accent", s),
7
+ selectList: {
8
+ selectedPrefix: (t) => theme.fg("accent", t),
9
+ selectedText: (t) => theme.fg("accent", t),
10
+ description: (t) => theme.fg("muted", t),
11
+ scrollInfo: (t) => theme.fg("dim", t),
12
+ noMatch: (t) => theme.fg("warning", t),
13
+ },
14
+ };
15
+ }
16
+
17
+ export function addWrapped(
18
+ lines: string[],
19
+ text: string,
20
+ width: number,
21
+ firstIndent = " ",
22
+ restIndent = firstIndent,
23
+ styleFn?: (line: string) => string,
24
+ ): void {
25
+ if (!text) return;
26
+ const paragraphs = text.split(/\r?\n/);
27
+ for (let pIdx = 0; pIdx < paragraphs.length; pIdx++) {
28
+ const paragraph = paragraphs[pIdx];
29
+ if (paragraph.length === 0) {
30
+ lines.push("");
31
+ continue;
32
+ }
33
+ const isFirstParagraph = pIdx === 0;
34
+ const currentFirstIndent = isFirstParagraph ? firstIndent : restIndent;
35
+ const firstWidth = Math.max(1, width - visibleWidth(currentFirstIndent));
36
+ const restWidth = Math.max(1, width - visibleWidth(restIndent));
37
+
38
+ if (firstWidth === restWidth) {
39
+ const wrapped = wrapTextWithAnsi(paragraph, firstWidth);
40
+ for (let i = 0; i < wrapped.length; i++) {
41
+ const indent = isFirstParagraph && i === 0 ? firstIndent : restIndent;
42
+ const rawLine = wrapped[i];
43
+ const styled = styleFn ? styleFn(rawLine) : rawLine;
44
+ lines.push(truncateToWidth(`${indent}${styled}`, width));
45
+ }
46
+ } else {
47
+ const wrapped = wrapTextWithAnsi(paragraph, Math.min(firstWidth, restWidth));
48
+ for (let i = 0; i < wrapped.length; i++) {
49
+ const indent = isFirstParagraph && i === 0 ? firstIndent : restIndent;
50
+ const rawLine = wrapped[i];
51
+ const styled = styleFn ? styleFn(rawLine) : rawLine;
52
+ lines.push(truncateToWidth(`${indent}${styled}`, width));
53
+ }
54
+ }
55
+ }
56
+ }
57
+
58
+ const SHARED_UI_LOCK_KEY = "__piSharedUiLock";
59
+ function getSharedUiLock(): { withLock<T>(fn: () => T | Promise<T>): Promise<T> } {
60
+ const g = globalThis as any;
61
+ if (!g[SHARED_UI_LOCK_KEY]) {
62
+ let chain: Promise<void> = Promise.resolve();
63
+ g[SHARED_UI_LOCK_KEY] = {
64
+ withLock<T>(fn: () => T | Promise<T>): Promise<T> {
65
+ const prev = chain;
66
+ let release: () => void;
67
+ chain = new Promise<void>((r) => {
68
+ release = r;
69
+ });
70
+ return prev.then(fn).finally(() => release!());
71
+ },
72
+ };
73
+ }
74
+ return g[SHARED_UI_LOCK_KEY];
75
+ }
76
+ const sharedUiLock = getSharedUiLock();
77
+
78
+ export function withUILock<T>(fn: () => Promise<T>): Promise<T> {
79
+ return sharedUiLock.withLock(fn);
80
+ }
package/index.ts ADDED
@@ -0,0 +1,92 @@
1
+ /** Interactive questions, serialized through the shared dialog lock. */
2
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
+ import {
4
+ AskUserQuestionParams,
5
+ buildResult,
6
+ cancelledResult,
7
+ normalizeOptions,
8
+ unavailableResult,
9
+ type AskUserQuestionMode,
10
+ } from "./types.ts";
11
+ import { withUILock } from "./dialog-ui.ts";
12
+ import { askSingleChoice } from "./single-choice.ts";
13
+ import { askMultiChoice } from "./multi-choice.ts";
14
+ import { questionRenderers } from "./tool-renderers.ts";
15
+
16
+ export type { AskOption, TextAnswer, OptionAnswer, OtherAnswer, AskAnswer, AskUserQuestionStatus, AskUserQuestionMode, AskUserQuestionResultDetails } from "./types.ts";
17
+
18
+ export default function (pi: ExtensionAPI) {
19
+ pi.registerTool({
20
+ name: "ask_user_question",
21
+ label: "Ask User Question",
22
+ description:
23
+ "Ask the user a clear question and pause execution until they select an option or provide input. Useful when requirements are ambiguous, user preferences or architectural decisions are needed, or critical operations require explicit user confirmation. Always phrase the question and options in the same language as the conversation context. Ask exactly one focused question per call.",
24
+ promptSnippet:
25
+ "Ask the user a question to clarify requirements or gather decisions instead of making assumptions.",
26
+ promptGuidelines: [
27
+ "Always phrase the question and options in the same language as the conversation context (e.g. ask in Chinese if conversing in Chinese, ask in English if conversing in English).",
28
+ "Ask exactly one specific question per tool call.",
29
+ "If you need input across multiple distinct dimensions, make separate tool calls instead of combining them into one.",
30
+ "When options are provided, an 'Other (custom input)' choice is automatically available in the user interface.",
31
+ "Set multiSelect: true only when the user is expected to select multiple choices.",
32
+ 'Put the recommended option first in the list and append "(Recommended)" to its label.',
33
+ "Prefer using this tool whenever multiple valid implementation paths exist that depend on user preference.",
34
+ ],
35
+ parameters: AskUserQuestionParams,
36
+
37
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
38
+ const options = normalizeOptions(params.options);
39
+ const context = params.details?.trim() || undefined;
40
+ const mode: AskUserQuestionMode =
41
+ options.length === 0
42
+ ? "text"
43
+ : params.multiSelect
44
+ ? "multi-select"
45
+ : "single-select";
46
+
47
+ if (signal?.aborted) {
48
+ return cancelledResult(params.question, mode, context);
49
+ }
50
+
51
+ if (!ctx.hasUI) {
52
+ return unavailableResult(
53
+ params.question,
54
+ mode,
55
+ "ask_user_question requires an interactive TUI environment",
56
+ context,
57
+ );
58
+ }
59
+
60
+ return withUILock(async () => {
61
+ if (mode === "text") {
62
+ const editorTitle = context
63
+ ? `${params.question}\n\n${context}`
64
+ : params.question;
65
+ const answer = await ctx.ui.editor(editorTitle);
66
+ if (answer === undefined) {
67
+ return cancelledResult(params.question, mode, context);
68
+ }
69
+ return buildResult(params.question, context, mode, [
70
+ { type: "text", label: answer.trim(), value: answer.trim() },
71
+ ]);
72
+ }
73
+
74
+ if (mode === "single-select") {
75
+ const answer = await askSingleChoice(ctx, params.question, context, options);
76
+ if (!answer) {
77
+ return cancelledResult(params.question, mode, context);
78
+ }
79
+ return buildResult(params.question, context, mode, [answer]);
80
+ }
81
+
82
+ const answers = await askMultiChoice(ctx, params.question, context, options);
83
+ if (!answers) {
84
+ return cancelledResult(params.question, mode, context);
85
+ }
86
+ return buildResult(params.question, context, mode, answers);
87
+ });
88
+ },
89
+
90
+ ...questionRenderers,
91
+ });
92
+ }
@@ -0,0 +1,258 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { Editor, Key, matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
3
+ import { getOtherLabel, isChineseContext, sortAnswers, type AskAnswer, type AskOption, type DisplayOption } from "./types.ts";
4
+ import { addWrapped, createEditorTheme } from "./dialog-ui.ts";
5
+
6
+ export async function askMultiChoice(
7
+ ctx: ExtensionContext,
8
+ question: string,
9
+ context: string | undefined,
10
+ options: AskOption[],
11
+ ): Promise<AskAnswer[] | null> {
12
+ const isZh = isChineseContext(question, options, context);
13
+ const otherLabel = getOtherLabel(options, isZh);
14
+ const choiceItems: DisplayOption[] = options.map((option, index) => ({
15
+ ...option,
16
+ id: `option:${index}`,
17
+ index: index + 1,
18
+ }));
19
+ const submitItem: DisplayOption = {
20
+ id: "submit",
21
+ label: isZh ? "提交确认" : "Confirm & Submit",
22
+ value: "__submit__",
23
+ isSubmit: true,
24
+ };
25
+ const allItems: DisplayOption[] = [
26
+ ...choiceItems,
27
+ { id: "other", label: otherLabel, value: "__other__", isOther: true },
28
+ submitItem,
29
+ ];
30
+
31
+ return ctx.ui.custom<AskAnswer[] | null>(
32
+ (tui, theme, _kb, done: (result: AskAnswer[] | null) => void) => {
33
+ let optionIndex = 0;
34
+ let editMode = false;
35
+ let cachedLines: string[] | undefined;
36
+ let cachedWidth = -1;
37
+ let componentFocused = false;
38
+ const selected = new Map<string, AskAnswer>();
39
+ const editor = new Editor(tui, createEditorTheme(theme));
40
+
41
+ editor.onSubmit = (value) => {
42
+ const trimmed = value.trim();
43
+ if (!trimmed) return;
44
+ selected.set("other", { type: "other", label: trimmed, value: trimmed });
45
+ editMode = false;
46
+ editor.focused = false;
47
+ refresh();
48
+ };
49
+
50
+ function refresh() {
51
+ cachedLines = undefined;
52
+ tui.requestRender();
53
+ }
54
+
55
+ function toggleOption(item: DisplayOption) {
56
+ if (selected.has(item.id)) {
57
+ selected.delete(item.id);
58
+ } else {
59
+ selected.set(item.id, {
60
+ type: "option",
61
+ label: item.label,
62
+ value: item.value,
63
+ index: item.index!,
64
+ });
65
+ }
66
+ refresh();
67
+ }
68
+
69
+ function handleInput(data: string) {
70
+ if (editMode) {
71
+ if (matchesKey(data, Key.escape)) {
72
+ editMode = false;
73
+ editor.focused = false;
74
+ editor.setText(selected.get("other")?.label || "");
75
+ refresh();
76
+ return;
77
+ }
78
+ editor.handleInput(data);
79
+ refresh();
80
+ return;
81
+ }
82
+
83
+ if (matchesKey(data, Key.up)) {
84
+ optionIndex = Math.max(0, optionIndex - 1);
85
+ refresh();
86
+ return;
87
+ }
88
+ if (matchesKey(data, Key.down)) {
89
+ optionIndex = Math.min(allItems.length - 1, optionIndex + 1);
90
+ refresh();
91
+ return;
92
+ }
93
+
94
+ const current = allItems[optionIndex];
95
+ if (matchesKey(data, Key.space)) {
96
+ if (current.isSubmit) return;
97
+ if (current.isOther) {
98
+ if (selected.has("other")) {
99
+ selected.delete("other");
100
+ refresh();
101
+ } else {
102
+ editMode = true;
103
+ editor.focused = componentFocused;
104
+ editor.setText("");
105
+ refresh();
106
+ }
107
+ return;
108
+ }
109
+ toggleOption(current);
110
+ return;
111
+ }
112
+
113
+ if (matchesKey(data, Key.enter)) {
114
+ if (current.isSubmit) {
115
+ if (selected.size > 0) {
116
+ done(sortAnswers(Array.from(selected.values())));
117
+ }
118
+ return;
119
+ }
120
+ if (current.isOther) {
121
+ editMode = true;
122
+ editor.focused = componentFocused;
123
+ editor.setText(selected.get("other")?.label || "");
124
+ refresh();
125
+ return;
126
+ }
127
+ toggleOption(current);
128
+ return;
129
+ }
130
+
131
+ if (matchesKey(data, Key.escape)) {
132
+ done(null);
133
+ }
134
+ }
135
+
136
+ function render(width: number): string[] {
137
+ if (cachedLines && cachedWidth === width) return cachedLines;
138
+
139
+ const lines: string[] = [];
140
+ const add = (text: string) => lines.push(truncateToWidth(text, width));
141
+
142
+ add(theme.fg("accent", "─".repeat(width)));
143
+
144
+ if (editMode) {
145
+ addWrapped(lines, question, width, " ", " ", (l) => theme.fg("text", theme.bold(l)));
146
+ if (context) {
147
+ addWrapped(lines, context, width, " ", " ", (l) => theme.fg("muted", l));
148
+ }
149
+ lines.push("");
150
+ const header = allItems[optionIndex]?.label || otherLabel;
151
+ add(theme.fg("accent", ` > ${header}:`));
152
+ for (const line of editor.render(Math.max(1, width - 4))) {
153
+ add(` ${line}`);
154
+ }
155
+ lines.push("");
156
+ const editHint = isZh
157
+ ? " Enter 保存 • Esc 返回多选"
158
+ : " Enter to save • Esc to return";
159
+ add(theme.fg("dim", editHint));
160
+ add(theme.fg("accent", "─".repeat(width)));
161
+ cachedLines = lines;
162
+ cachedWidth = width;
163
+ return lines;
164
+ }
165
+
166
+ addWrapped(lines, question, width, " ", " ", (l) => theme.fg("text", theme.bold(l)));
167
+ if (context) {
168
+ addWrapped(lines, context, width, " ", " ", (l) => theme.fg("muted", l));
169
+ }
170
+ lines.push("");
171
+
172
+ for (let i = 0; i < allItems.length; i++) {
173
+ const item = allItems[i];
174
+ const isFocused = i === optionIndex;
175
+ const prefix = isFocused ? theme.fg("accent", " > ") : " ";
176
+
177
+ if (item.isSubmit) {
178
+ const hasSelected = selected.size > 0;
179
+ const countText = isZh
180
+ ? `(已选 ${selected.size} 项)`
181
+ : `(${selected.size} selected)`;
182
+ const label = hasSelected
183
+ ? `✓ ${item.label} ${countText}`
184
+ : `○ ${item.label}`;
185
+ const styled = isFocused
186
+ ? theme.bold(theme.fg("accent", label))
187
+ : theme.fg(hasSelected ? "success" : "dim", label);
188
+ lines.push(truncateToWidth(`${prefix}${styled}`, width));
189
+ continue;
190
+ }
191
+
192
+ if (item.isOther) {
193
+ const other = selected.get("other");
194
+ const marker = other ? "[x]" : "[ ]";
195
+ const suffix = other ? ` — ${other.label}` : "";
196
+ const label = `${marker} ${item.label}${suffix}`;
197
+ const styled = isFocused
198
+ ? theme.bold(theme.fg("accent", label))
199
+ : theme.fg(other ? "success" : "text", label);
200
+ lines.push(truncateToWidth(`${prefix}${styled}`, width));
201
+ continue;
202
+ }
203
+
204
+ const checked = selected.has(item.id);
205
+ const marker = checked ? "[x] " : "[ ] ";
206
+ const numPrefix = `${item.index}. `;
207
+ const firstIndent = `${prefix}${checked ? theme.fg("success", marker) : marker}${numPrefix}`;
208
+ const restIndent = " ".repeat(visibleWidth(firstIndent));
209
+ const styleLabel = (l: string) => {
210
+ if (isFocused) return theme.bold(theme.fg("accent", l));
211
+ if (checked) return theme.fg("success", l);
212
+ return theme.fg("text", l);
213
+ };
214
+
215
+ addWrapped(lines, item.label, width, firstIndent, restIndent, styleLabel);
216
+
217
+ if (item.description) {
218
+ const descIndent = " ".repeat(visibleWidth(firstIndent));
219
+ const descStyle = (l: string) => theme.fg("muted", l);
220
+ addWrapped(lines, item.description, width, descIndent, descIndent, descStyle);
221
+ }
222
+ }
223
+
224
+ lines.push("");
225
+ if (selected.size === 0) {
226
+ const warnText = isZh
227
+ ? " 请至少选择一项回答后再提交。"
228
+ : " Please select at least one option before submitting.";
229
+ add(theme.fg("warning", warnText));
230
+ }
231
+ const navHint = isZh
232
+ ? " ↑↓ 切换 • 空格 勾选 • Enter 编辑/提交 • Esc 取消"
233
+ : " ↑↓ to navigate • Space to select • Enter to edit/submit • Esc to cancel";
234
+ add(theme.fg("dim", navHint));
235
+ add(theme.fg("accent", "─".repeat(width)));
236
+
237
+ cachedLines = lines;
238
+ cachedWidth = width;
239
+ return lines;
240
+ }
241
+
242
+ return {
243
+ render,
244
+ invalidate: () => {
245
+ cachedLines = undefined;
246
+ },
247
+ handleInput,
248
+ get focused(): boolean {
249
+ return componentFocused;
250
+ },
251
+ set focused(value: boolean) {
252
+ componentFocused = value;
253
+ editor.focused = editMode && componentFocused;
254
+ },
255
+ };
256
+ },
257
+ );
258
+ }
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@rol1n/ask-u-questions",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "type": "module",
5
+ "description": "ask-u-questions extension from pi-kit",
6
+ "keywords": [
7
+ "pi-package"
8
+ ],
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/RolinShmily/pi-kit.git",
12
+ "directory": "ask-u-questions"
13
+ },
14
+ "homepage": "https://github.com/RolinShmily/pi-kit#readme",
15
+ "bugs": {
16
+ "url": "https://github.com/RolinShmily/pi-kit/issues"
17
+ },
18
+ "engines": {
19
+ "node": ">=22.19.0"
20
+ },
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "peerDependencies": {
25
+ "@earendil-works/pi-ai": "*",
26
+ "@earendil-works/pi-agent-core": "*",
27
+ "@earendil-works/pi-coding-agent": "*",
28
+ "@earendil-works/pi-tui": "*",
29
+ "typebox": "*"
30
+ },
31
+ "pi": {
32
+ "extensions": [
33
+ "./index.ts"
34
+ ],
35
+ "skills": [],
36
+ "prompts": [],
37
+ "themes": []
38
+ }
39
+ }
@@ -0,0 +1,180 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { Editor, Key, matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
3
+ import { getOtherLabel, isChineseContext, type AskAnswer, type AskOption, type DisplayOption } from "./types.ts";
4
+ import { addWrapped, createEditorTheme } from "./dialog-ui.ts";
5
+
6
+ export async function askSingleChoice(
7
+ ctx: ExtensionContext,
8
+ question: string,
9
+ context: string | undefined,
10
+ options: AskOption[],
11
+ ): Promise<AskAnswer | null> {
12
+ const isZh = isChineseContext(question, options, context);
13
+ const otherLabel = getOtherLabel(options, isZh);
14
+ const allOptions: DisplayOption[] = [
15
+ ...options.map((option, index) => ({
16
+ ...option,
17
+ id: `option:${index}`,
18
+ index: index + 1,
19
+ })),
20
+ { id: "other", label: otherLabel, value: "__other__", isOther: true },
21
+ ];
22
+
23
+ return ctx.ui.custom<AskAnswer | null>(
24
+ (tui, theme, _kb, done: (result: AskAnswer | null) => void) => {
25
+ let optionIndex = 0;
26
+ let editMode = false;
27
+ let cachedLines: string[] | undefined;
28
+ let cachedWidth = -1;
29
+ let componentFocused = false;
30
+ const editor = new Editor(tui, createEditorTheme(theme));
31
+
32
+ editor.onSubmit = (value) => {
33
+ const trimmed = value.trim();
34
+ if (!trimmed) return;
35
+ done({ type: "other", label: trimmed, value: trimmed });
36
+ };
37
+
38
+ function refresh() {
39
+ cachedLines = undefined;
40
+ tui.requestRender();
41
+ }
42
+
43
+ function handleInput(data: string) {
44
+ if (editMode) {
45
+ if (matchesKey(data, Key.escape)) {
46
+ editMode = false;
47
+ editor.focused = false;
48
+ editor.setText("");
49
+ refresh();
50
+ return;
51
+ }
52
+ editor.handleInput(data);
53
+ refresh();
54
+ return;
55
+ }
56
+
57
+ if (matchesKey(data, Key.up)) {
58
+ optionIndex = Math.max(0, optionIndex - 1);
59
+ refresh();
60
+ return;
61
+ }
62
+ if (matchesKey(data, Key.down)) {
63
+ optionIndex = Math.min(allOptions.length - 1, optionIndex + 1);
64
+ refresh();
65
+ return;
66
+ }
67
+ if (matchesKey(data, Key.enter)) {
68
+ const selected = allOptions[optionIndex];
69
+ if (selected.isOther) {
70
+ editMode = true;
71
+ editor.focused = componentFocused;
72
+ editor.setText("");
73
+ refresh();
74
+ return;
75
+ }
76
+ done({
77
+ type: "option",
78
+ label: selected.label,
79
+ value: selected.value,
80
+ index: selected.index!,
81
+ });
82
+ return;
83
+ }
84
+ if (matchesKey(data, Key.escape)) {
85
+ done(null);
86
+ }
87
+ }
88
+
89
+ function render(width: number): string[] {
90
+ if (cachedLines && cachedWidth === width) return cachedLines;
91
+
92
+ const lines: string[] = [];
93
+ const add = (text: string) => lines.push(truncateToWidth(text, width));
94
+
95
+ add(theme.fg("accent", "─".repeat(width)));
96
+
97
+ if (editMode) {
98
+ addWrapped(lines, question, width, " ", " ", (l) => theme.fg("text", theme.bold(l)));
99
+ if (context) {
100
+ addWrapped(lines, context, width, " ", " ", (l) => theme.fg("muted", l));
101
+ }
102
+ lines.push("");
103
+ const header = allOptions[optionIndex]?.label || otherLabel;
104
+ add(theme.fg("accent", ` > ${header}:`));
105
+ for (const line of editor.render(Math.max(1, width - 4))) {
106
+ add(` ${line}`);
107
+ }
108
+ lines.push("");
109
+ const editHint = isZh
110
+ ? " Enter 提交 • Esc 返回选项"
111
+ : " Enter to submit • Esc to return";
112
+ add(theme.fg("dim", editHint));
113
+ add(theme.fg("accent", "─".repeat(width)));
114
+ cachedLines = lines;
115
+ cachedWidth = width;
116
+ return lines;
117
+ }
118
+
119
+ addWrapped(lines, question, width, " ", " ", (l) => theme.fg("text", theme.bold(l)));
120
+ if (context) {
121
+ addWrapped(lines, context, width, " ", " ", (l) => theme.fg("muted", l));
122
+ }
123
+ lines.push("");
124
+
125
+ for (let i = 0; i < allOptions.length; i++) {
126
+ const item = allOptions[i];
127
+ const selected = i === optionIndex;
128
+ const prefix = selected ? theme.fg("accent", " > ") : " ";
129
+
130
+ if (item.isOther) {
131
+ const styledLabel = selected
132
+ ? theme.bold(theme.fg("accent", item.label))
133
+ : theme.fg("text", item.label);
134
+ lines.push(truncateToWidth(`${prefix}${styledLabel}`, width));
135
+ } else {
136
+ const numPrefix = `${item.index}. `;
137
+ const firstIndent = `${prefix}${selected ? theme.fg("accent", numPrefix) : numPrefix}`;
138
+ const restIndent = " ".repeat(visibleWidth(firstIndent));
139
+ const styleLabel = (l: string) =>
140
+ selected ? theme.bold(theme.fg("accent", l)) : theme.fg("text", l);
141
+
142
+ addWrapped(lines, item.label, width, firstIndent, restIndent, styleLabel);
143
+
144
+ if (item.description) {
145
+ const descIndent = " ".repeat(visibleWidth(firstIndent));
146
+ const descStyle = (l: string) => theme.fg("muted", l);
147
+ addWrapped(lines, item.description, width, descIndent, descIndent, descStyle);
148
+ }
149
+ }
150
+ }
151
+
152
+ lines.push("");
153
+ const navHint = isZh
154
+ ? " ↑↓ 选择 • Enter 确定 • Esc 取消"
155
+ : " ↑↓ to navigate • Enter to select • Esc to cancel";
156
+ add(theme.fg("dim", navHint));
157
+ add(theme.fg("accent", "─".repeat(width)));
158
+
159
+ cachedLines = lines;
160
+ cachedWidth = width;
161
+ return lines;
162
+ }
163
+
164
+ return {
165
+ render,
166
+ invalidate: () => {
167
+ cachedLines = undefined;
168
+ },
169
+ handleInput,
170
+ get focused(): boolean {
171
+ return componentFocused;
172
+ },
173
+ set focused(value: boolean) {
174
+ componentFocused = value;
175
+ editor.focused = editMode && componentFocused;
176
+ },
177
+ };
178
+ },
179
+ );
180
+ }
@@ -0,0 +1,67 @@
1
+ import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
2
+ import { Text } from "@earendil-works/pi-tui";
3
+ import { AskUserQuestionParams, getOtherLabel, isChineseContext, normalizeOptions, type AskUserQuestionResultDetails } from "./types.ts";
4
+
5
+ export const questionRenderers: Pick<ToolDefinition<typeof AskUserQuestionParams, AskUserQuestionResultDetails>, "renderCall" | "renderResult"> = {
6
+ renderCall(args, theme, context) {
7
+ const text = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
8
+ const options = normalizeOptions(
9
+ args.options as Array<{ label: string; value?: string; description?: string }> | undefined,
10
+ );
11
+ const isZh = isChineseContext(args.question || "", options, args.details);
12
+ let summary =
13
+ theme.fg("toolTitle", theme.bold("ask_user_question ")) +
14
+ theme.fg("accent", `"${args.question || ""}"`);
15
+ if (args.multiSelect) {
16
+ summary += theme.fg("dim", " [multi-select]");
17
+ }
18
+ if (options.length > 0) {
19
+ const otherLbl = getOtherLabel(options, isZh);
20
+ const labels = [...options.map((option) => option.label), otherLbl].join(", ");
21
+ const optPrefix = isZh ? " 选项: " : " Options: ";
22
+ summary += `\n${theme.fg("dim", `${optPrefix}${labels}`)}`;
23
+ }
24
+ text.setText(summary);
25
+ return text;
26
+ },
27
+
28
+ renderResult(result, _options, theme, context) {
29
+ const text = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
30
+ const details = result.details as AskUserQuestionResultDetails | undefined;
31
+ if (!details) {
32
+ const first = result.content?.[0];
33
+ text.setText(first?.type === "text" ? first.text : "");
34
+ return text;
35
+ }
36
+
37
+ const isZh = isChineseContext(details.question || "", details.answers, details.context);
38
+
39
+ if (details.status === "cancelled") {
40
+ const defaultCancelled = isZh ? "已取消" : "Cancelled";
41
+ text.setText(theme.fg("warning", `⊘ ${details.message || defaultCancelled}`));
42
+ return text;
43
+ }
44
+
45
+ if (details.status === "unavailable") {
46
+ const defaultUnavailable = isZh ? "提问工具不可用" : "Tool unavailable";
47
+ text.setText(theme.fg("error", `! ${details.message || defaultUnavailable}`));
48
+ return text;
49
+ }
50
+
51
+ const emptyText = isZh ? "(空回答)" : "(empty)";
52
+ const otherPrefix = isZh ? "其他:" : "Other: ";
53
+
54
+ const lines = details.answers.map((answer) => {
55
+ switch (answer.type) {
56
+ case "text":
57
+ return `${theme.fg("success", "✓ ")}${theme.fg("accent", answer.label || emptyText)}`;
58
+ case "other":
59
+ return `${theme.fg("success", "✓ ")}${theme.fg("muted", otherPrefix)}${theme.fg("accent", answer.label)}`;
60
+ case "option":
61
+ return `${theme.fg("success", "✓ ")}${theme.fg("accent", `${answer.index}. ${answer.label}`)}`;
62
+ }
63
+ });
64
+ text.setText(lines.join("\n"));
65
+ return text;
66
+ },
67
+ };
package/types.ts ADDED
@@ -0,0 +1,192 @@
1
+ import { Type } from "typebox";
2
+
3
+ const OptionSchema = Type.Object({
4
+ label: Type.String({ description: 'Option label. Put a recommended option first and append "(Recommended)".' }),
5
+ value: Type.Optional(Type.String({ description: "Machine-readable value; defaults to the label." })),
6
+ description: Type.Optional(Type.String({ description: "Additional context shown below the option." })),
7
+ });
8
+
9
+ export const AskUserQuestionParams = Type.Object({
10
+ question: Type.String({ description: "The question to ask. Ask only one question per call." }),
11
+ details: Type.Optional(Type.String({ description: "Background or instructions shown below the question." })),
12
+ options: Type.Optional(Type.Array(OptionSchema, {
13
+ description: "Choices for selection. Omit or pass an empty array for free-text input. An Other choice is always available.",
14
+ })),
15
+ multiSelect: Type.Optional(Type.Boolean({ description: "Allow selecting multiple options when true." })),
16
+ });
17
+
18
+ export interface AskOption {
19
+ label: string;
20
+ value: string;
21
+ description?: string;
22
+ }
23
+
24
+ export interface DisplayOption extends AskOption {
25
+ id: string;
26
+ index?: number;
27
+ isOther?: boolean;
28
+ isSubmit?: boolean;
29
+ }
30
+
31
+ export interface TextAnswer {
32
+ type: "text";
33
+ label: string;
34
+ value: string;
35
+ }
36
+
37
+ export interface OptionAnswer {
38
+ type: "option";
39
+ label: string;
40
+ value: string;
41
+ index: number;
42
+ }
43
+
44
+ export interface OtherAnswer {
45
+ type: "other";
46
+ label: string;
47
+ value: string;
48
+ }
49
+
50
+ export type AskAnswer = TextAnswer | OptionAnswer | OtherAnswer;
51
+ export type AskUserQuestionStatus = "answered" | "cancelled" | "unavailable";
52
+ export type AskUserQuestionMode = "text" | "single-select" | "multi-select";
53
+
54
+ export interface AskUserQuestionResultDetails {
55
+ status: AskUserQuestionStatus;
56
+ question: string;
57
+ context?: string;
58
+ mode: AskUserQuestionMode;
59
+ answers: AskAnswer[];
60
+ message?: string;
61
+ }
62
+
63
+ export function normalizeOptions(
64
+ options: Array<{ label: string; value?: string; description?: string }> | undefined,
65
+ ): AskOption[] {
66
+ return (options || [])
67
+ .map((option) => ({
68
+ label: option.label.trim(),
69
+ value: option.value?.trim() || option.label.trim(),
70
+ description: option.description?.trim() || undefined,
71
+ }))
72
+ .filter((option) => option.label.length > 0);
73
+ }
74
+
75
+ export function isChineseContext(
76
+ question: string,
77
+ options?: Array<{ label?: string; description?: string }>,
78
+ context?: string,
79
+ ): boolean {
80
+ if (/[\u4e00-\u9fa5]/.test(question)) return true;
81
+ if (context && /[\u4e00-\u9fa5]/.test(context)) return true;
82
+ if (options && options.some((o) => (o.label && /[\u4e00-\u9fa5]/.test(o.label)) || (o.description && /[\u4e00-\u9fa5]/.test(o.description)))) {
83
+ return true;
84
+ }
85
+ return false;
86
+ }
87
+
88
+ export function getOtherLabel(options: AskOption[], isZh = false): string {
89
+ if (isZh) {
90
+ return options.some((option) => option.label === "其他(自定义输入)")
91
+ ? "自定义输入"
92
+ : "其他(自定义输入)";
93
+ }
94
+ return options.some((option) => option.label === "Other (custom input)")
95
+ ? "Custom input"
96
+ : "Other (custom input)";
97
+ }
98
+
99
+ function answerSortRank(answer: AskAnswer): number {
100
+ switch (answer.type) {
101
+ case "option":
102
+ return answer.index;
103
+ case "other":
104
+ return Number.MAX_SAFE_INTEGER - 1;
105
+ case "text":
106
+ return Number.MAX_SAFE_INTEGER;
107
+ }
108
+ }
109
+
110
+ export function sortAnswers(answers: AskAnswer[]): AskAnswer[] {
111
+ return [...answers].sort((a, b) => answerSortRank(a) - answerSortRank(b));
112
+ }
113
+
114
+ function formatAnswerForModel(answer: AskAnswer): string {
115
+ switch (answer.type) {
116
+ case "text":
117
+ return answer.label;
118
+ case "other":
119
+ return `Other: ${answer.label}`;
120
+ case "option":
121
+ return `${answer.index}. ${answer.label}`;
122
+ }
123
+ }
124
+
125
+ function buildStructuredResult(
126
+ status: AskUserQuestionStatus,
127
+ question: string,
128
+ mode: AskUserQuestionMode,
129
+ answers: AskAnswer[],
130
+ context?: string,
131
+ message?: string,
132
+ ): AskUserQuestionResultDetails {
133
+ return {
134
+ status,
135
+ question,
136
+ context,
137
+ mode,
138
+ answers,
139
+ message,
140
+ };
141
+ }
142
+
143
+ export function cancelledResult(question: string, mode: AskUserQuestionMode, context?: string) {
144
+ const isZh = isChineseContext(question, undefined, context);
145
+ const message = isZh ? "用户取消了本次提问" : "User cancelled the question.";
146
+ return {
147
+ content: [{ type: "text" as const, text: message }],
148
+ details: buildStructuredResult("cancelled", question, mode, [], context, message),
149
+ };
150
+ }
151
+
152
+ export function unavailableResult(question: string, mode: AskUserQuestionMode, message: string, context?: string) {
153
+ return {
154
+ content: [{ type: "text" as const, text: message }],
155
+ details: buildStructuredResult("unavailable", question, mode, [], context, message),
156
+ };
157
+ }
158
+
159
+ export function buildResult(
160
+ question: string,
161
+ context: string | undefined,
162
+ mode: AskUserQuestionMode,
163
+ answers: AskAnswer[],
164
+ ) {
165
+ const isZh = isChineseContext(question, answers, context);
166
+ let text: string;
167
+ if (mode === "text") {
168
+ const answer = answers[0];
169
+ if (isZh) {
170
+ text = answer.label.trim().length > 0
171
+ ? `用户输入回答: ${answer.label}`
172
+ : "用户提交了空回答";
173
+ } else {
174
+ text = answer.label.trim().length > 0
175
+ ? `User answered: ${answer.label}`
176
+ : "User submitted an empty answer";
177
+ }
178
+ } else if (mode === "single-select") {
179
+ text = isZh
180
+ ? `用户选择项: ${formatAnswerForModel(answers[0])}`
181
+ : `User selected: ${formatAnswerForModel(answers[0])}`;
182
+ } else {
183
+ text = isZh
184
+ ? `用户选择多项:\n${answers.map((answer) => `- ${formatAnswerForModel(answer)}`).join("\n")}`
185
+ : `User selected multiple:\n${answers.map((answer) => `- ${formatAnswerForModel(answer)}`).join("\n")}`;
186
+ }
187
+
188
+ return {
189
+ content: [{ type: "text" as const, text }],
190
+ details: buildStructuredResult("answered", question, mode, answers, context),
191
+ };
192
+ }