@k3_2o/pi-ask-user-question 0.0.0-stage → 0.1.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,305 @@
1
+ import { type AgentToolResult, type Theme, type ToolRenderResultOptions } from '@earendil-works/pi-coding-agent';
2
+ import { Text, type Component, visibleWidth, wrapTextWithAnsi } from '@earendil-works/pi-tui';
3
+ import type { CanonicalQuestion, AskUserQuestionResult } from './types';
4
+ import { canonicalize, displayOptionLabels, sanitizeForDisplay } from './normalize';
5
+ import { interpretResultItem } from './result-interpretation';
6
+ import { clipToCells, wordWrap } from './text-layout';
7
+
8
+ function padToWidth(line: string, width: number): string {
9
+ return `${line}${' '.repeat(Math.max(0, width - visibleWidth(line)))}`;
10
+ }
11
+
12
+ function normalizeTabs(text: string): string {
13
+ return text.replace(/\t/g, ' ');
14
+ }
15
+
16
+ type HangingRow = { kind: 'description'; text: string };
17
+ type AskRow = { kind: 'text'; text: string } | HangingRow | { kind: 'rule'; label: string; annotation?: string };
18
+
19
+ interface HangingShape {
20
+ marker: string;
21
+ continuation: string;
22
+ markerTone: Parameters<Theme['fg']>[0];
23
+ bodyTone: Parameters<Theme['fg']>[0];
24
+ maxRows?: number;
25
+ }
26
+
27
+ const DESCRIPTION_SHAPE: HangingShape = {
28
+ marker: ' \u21b3',
29
+ continuation: ' ',
30
+ markerTone: 'dim',
31
+ bodyTone: 'toolOutput',
32
+ maxRows: 2,
33
+ };
34
+
35
+ const RULE_LABEL_MIN_WIDTH = 12;
36
+ const RULE_EDGE_CELLS = 4;
37
+
38
+ function textRow(text: string): AskRow {
39
+ return { kind: 'text', text };
40
+ }
41
+
42
+ function descriptionRow(text: string): AskRow {
43
+ return { kind: 'description', text };
44
+ }
45
+
46
+ function ruleRow(label: string, annotation?: string): AskRow {
47
+ return { kind: 'rule', label, annotation };
48
+ }
49
+
50
+ function selectionMarker(multi: boolean, picked: boolean): string {
51
+ if (multi) return picked ? '\u2611' : '\u2610';
52
+ return picked ? '\u25c9' : '\u25cb';
53
+ }
54
+
55
+ function outcomeFootnotes(details: AskUserQuestionResult, theme: Theme): AskRow[] {
56
+ if (details.error) {
57
+ return [textRow(` ${theme.fg('dim', '\u2717 ' + details.error)}`)];
58
+ }
59
+ if (details.cancelled || details.results.length === 0) {
60
+ return [textRow(` ${theme.fg('dim', '\u2717 Cancelled')}`)];
61
+ }
62
+ const skipped = details.results.filter((item) => item.unanswered).length;
63
+ const parts: string[] = [];
64
+ if (skipped > 0) parts.push(`\u25b3 ${skipped} skipped`);
65
+ return parts.length === 0 ? [] : [textRow(` ${theme.fg('dim', parts.join(' \u00b7 '))}`)];
66
+ }
67
+
68
+ class AskBlock implements Component {
69
+ private cachedWidth: number | undefined;
70
+ private cachedLines: string[] | undefined;
71
+
72
+ constructor(
73
+ private readonly rows: AskRow[],
74
+ private readonly theme: Theme,
75
+ ) {}
76
+
77
+ invalidate(): void {
78
+ this.cachedWidth = undefined;
79
+ this.cachedLines = undefined;
80
+ }
81
+
82
+ render(width: number): string[] {
83
+ if (this.cachedWidth === width && this.cachedLines) return this.cachedLines;
84
+ const lines: string[] = [];
85
+ for (const row of this.rows) {
86
+ if (row.kind === 'description') {
87
+ lines.push(...this.hangingLines(row, width));
88
+ continue;
89
+ }
90
+ if (row.kind === 'rule') {
91
+ lines.push(...this.ruleLines(row, width));
92
+ continue;
93
+ }
94
+ lines.push(...this.textLines(row.text, width));
95
+ }
96
+ this.cachedWidth = width;
97
+ this.cachedLines = lines;
98
+ return lines;
99
+ }
100
+
101
+ private textLines(text: string, width: number): string[] {
102
+ return wrapTextWithAnsi(normalizeTabs(text), Math.max(1, width)).map((line) => padToWidth(line, width));
103
+ }
104
+
105
+ private ruleLines(row: { kind: 'rule'; label: string; annotation?: string }, width: number): string[] {
106
+ const rule = this.theme.fg('borderMuted', '\u2500'.repeat(width));
107
+ if (width < RULE_LABEL_MIN_WIDTH) {
108
+ return [
109
+ rule,
110
+ ...this.textLines(this.theme.fg('muted', row.label), width),
111
+ ...(row.annotation ? this.textLines(this.theme.fg('dim', row.annotation), width) : []),
112
+ ];
113
+ }
114
+ const edge = this.theme.fg('borderMuted', '\u2500');
115
+ if (row.annotation) {
116
+ const prefix = `${edge}${edge} `;
117
+ const suffix = ` ${this.theme.fg('dim', row.annotation)} ${edge}${edge}`;
118
+ const labelBudget = Math.max(1, width - visibleWidth(prefix) - visibleWidth(suffix) - 2);
119
+ const shown = visibleWidth(row.label) <= labelBudget ? row.label : clipToCells(row.label, labelBudget);
120
+ const label = this.theme.fg('muted', shown);
121
+ const fill = Math.max(1, width - visibleWidth(prefix) - visibleWidth(label) - visibleWidth(suffix) - 1);
122
+ return [`${prefix}${label} ${edge.repeat(fill)}${suffix}`];
123
+ }
124
+ const budget = Math.max(1, width - RULE_EDGE_CELLS - 1);
125
+ const shown = visibleWidth(row.label) <= budget ? row.label : clipToCells(row.label, budget);
126
+ const fill = Math.max(1, width - RULE_EDGE_CELLS - visibleWidth(shown));
127
+ return [`${edge}${edge} ${this.theme.fg('muted', shown)} ${edge.repeat(fill)}`];
128
+ }
129
+
130
+ private hangingLines(row: HangingRow, width: number): string[] {
131
+ const shape = DESCRIPTION_SHAPE;
132
+ const gutter = Math.max(visibleWidth(shape.marker) + 1, visibleWidth(shape.continuation));
133
+ const budget = Math.max(1, width - gutter);
134
+ const wrapped = normalizeTabs(row.text)
135
+ .split('\n')
136
+ .flatMap((segment) => wordWrap(segment, budget));
137
+ const shown = (wrapped.length === 0 ? [''] : wrapped).slice(0, shape.maxRows ?? wrapped.length);
138
+ const overflowed = shape.maxRows !== undefined && wrapped.length > shape.maxRows;
139
+ return shown.map((line, index) => {
140
+ const isLastRow = index === shown.length - 1;
141
+ const body = `${line}${isLastRow && overflowed ? '\u2026' : ''}`;
142
+ const gutterText = index === 0 ? this.theme.fg(shape.markerTone, shape.marker) + ' ' : shape.continuation;
143
+ return padToWidth(`${gutterText}${this.theme.fg(shape.bodyTone, body)}`, width);
144
+ });
145
+ }
146
+ }
147
+
148
+ export interface AskRendererState {
149
+ stashed?: AskUserQuestionResult;
150
+ permanent?: boolean;
151
+ }
152
+
153
+ interface RenderContext {
154
+ state?: AskRendererState;
155
+ invalidate?: () => void;
156
+ }
157
+
158
+ function barLabel(question: CanonicalQuestion, sharedHeaders: string[], named: boolean): string {
159
+ const uniqueHeader = question.header && !sharedHeaders.includes(question.header) ? question.header : undefined;
160
+ const name = uniqueHeader ?? (named ? question.id : undefined);
161
+ return name ? `[${name}]` : '';
162
+ }
163
+
164
+ export function renderCall(args: unknown, theme: Theme, context?: RenderContext): Component {
165
+ const canonical = (() => {
166
+ try {
167
+ return canonicalize(args);
168
+ } catch {
169
+ return undefined;
170
+ }
171
+ })();
172
+ const lines: AskRow[] = [];
173
+ const title = theme.fg('toolTitle', theme.bold('ask'));
174
+
175
+ if (!canonical || canonical.questions.length === 0) {
176
+ return new AskBlock([textRow(title), textRow(theme.fg('warning', ' (no question details)'))], theme);
177
+ }
178
+
179
+ const meta = [canonical.questions.length > 1 ? `${canonical.questions.length} questions` : undefined]
180
+ .filter(Boolean)
181
+ .join(' \u00b7 ');
182
+ lines.push(textRow(`${title}${meta ? ` ${theme.fg('muted', meta)}` : ''}`));
183
+ lines.push(textRow(''));
184
+
185
+ const state = context?.state;
186
+ const details = state?.stashed;
187
+ const answered = details !== undefined && !details.cancelled && details.results.length > 0;
188
+ if (state && state.stashed !== undefined && state.permanent !== true) {
189
+ state.permanent = true;
190
+ }
191
+ const byId = answered ? new Map(details.results.map((item) => [item.id, item] as const)) : undefined;
192
+
193
+ const headers = canonical.questions.map((item) => item.header);
194
+ const sharedHeaders = headers.filter(
195
+ (header, index): header is string => header !== undefined && headers.indexOf(header) !== index,
196
+ );
197
+ const batched = canonical.questions.length > 1;
198
+ for (const question of canonical.questions) {
199
+ lines.push(ruleRow(barLabel(question, sharedHeaders, batched), question.multi ? '(multi)' : undefined));
200
+ lines.push(textRow(''));
201
+ const display = displayOptionLabels(question.options, question.recommended);
202
+ lines.push(textRow(theme.fg('text', question.question)));
203
+
204
+ const item = byId?.get(question.id);
205
+ const picked = new Set<string>(item?.selected ?? []);
206
+ display.forEach((label, index) => {
207
+ const option = question.options[index];
208
+ const isPicked = item !== undefined && option !== undefined && picked.has(option.value);
209
+ const marker = selectionMarker(question.multi, isPicked);
210
+ lines.push(
211
+ textRow(
212
+ ` ${theme.fg(isPicked ? 'success' : 'dim', marker)} ${theme.fg(isPicked ? 'toolOutput' : 'muted', sanitizeForDisplay(label))}`,
213
+ ),
214
+ );
215
+ const description = option?.description?.trim();
216
+ if (description) lines.push(descriptionRow(sanitizeForDisplay(description)));
217
+ });
218
+ if (item?.customInput !== undefined) {
219
+ const [first, ...rest] = item.customInput.split('\n');
220
+ lines.push(textRow(` ${theme.fg('success', '\u270e')} ${theme.fg('text', first ?? '')}`));
221
+ for (const continuation of rest) lines.push(textRow(` ${theme.fg('text', continuation)}`));
222
+ }
223
+ if (batched) lines.push(textRow(''));
224
+ }
225
+
226
+ if (details) lines.push(...outcomeFootnotes(details, theme));
227
+
228
+ return new AskBlock(lines, theme);
229
+ }
230
+
231
+ function answerLines(result: AgentToolResult<AskUserQuestionResult>, theme: Theme): string[] {
232
+ const details = result.details;
233
+ const lines: string[] = [];
234
+
235
+ if (!details) {
236
+ const message = result.content[0]?.type === 'text' && result.content[0].text ? result.content[0].text : 'No answer';
237
+ return [theme.fg('warning', `\u2717 ${message}`)];
238
+ }
239
+ if (details.error) {
240
+ return [theme.fg('warning', `\u2717 ${details.error}`)];
241
+ }
242
+ if (details.cancelled || details.results.length === 0) {
243
+ return [theme.fg('warning', '\u2717 Cancelled')];
244
+ }
245
+
246
+ const multiple = details.results.length > 1;
247
+ for (const item of details.results) {
248
+ const header = item.header ? theme.fg('muted', `[${item.header}] `) : '';
249
+ const scope = multiple ? `${header}${theme.fg('text', item.question)} \u2192 ` : '';
250
+ const displayLabels = displayOptionLabels(
251
+ item.options.map((option) => ({
252
+ label: option.label,
253
+ value: option.value ?? option.label,
254
+ })),
255
+ item.recommended,
256
+ );
257
+ const interpretation = interpretResultItem(item, displayLabels);
258
+
259
+ if (interpretation.kind === 'custom') {
260
+ const [first, ...rest] = interpretation.text.split('\n');
261
+ lines.push(
262
+ `${scope}${theme.fg('success', '\u2713')} ${theme.fg('muted', '(custom)')} ${theme.fg('text', first ?? '')}`,
263
+ );
264
+ for (const line of rest) lines.push(` ${theme.fg('text', line)}`);
265
+ } else if (interpretation.kind === 'selected') {
266
+ const answer = item.multi
267
+ ? interpretation.labels.join(', ')
268
+ : (interpretation.labels[0] ?? item.selectedLabels[0] ?? '');
269
+ lines.push(`${scope}${theme.fg('success', '\u2713')} ${theme.fg('toolOutput', answer)}`);
270
+ } else {
271
+ const reason = interpretation.wasSkipped ? 'skipped - no answer' : 'unanswered';
272
+ lines.push(`${scope}${theme.fg('warning', `\u2717 ${reason}`)}`);
273
+ }
274
+ }
275
+ return lines;
276
+ }
277
+
278
+ export function renderResult(
279
+ result: AgentToolResult<AskUserQuestionResult>,
280
+ _options: ToolRenderResultOptions,
281
+ theme: Theme,
282
+ context?: RenderContext,
283
+ ): Component {
284
+ const state = context?.state;
285
+ if (state && state.stashed === result.details) {
286
+ if (state.permanent) {
287
+ return new Text('', 0, 0);
288
+ }
289
+ return new Text(answerLines(result, theme).join('\n'), 0, 0);
290
+ }
291
+ if (state) {
292
+ state.stashed = result.details;
293
+ const invalidate = context?.invalidate;
294
+ if (invalidate) {
295
+ setTimeout(() => {
296
+ try {
297
+ invalidate();
298
+ } catch (error) {
299
+ console.warn('ask: transcript invalidation failed', error);
300
+ }
301
+ }, 0);
302
+ }
303
+ }
304
+ return new Text(answerLines(result, theme).join('\n'), 0, 0);
305
+ }
package/src/types.ts ADDED
@@ -0,0 +1,41 @@
1
+ export interface CanonicalOption {
2
+ label: string;
3
+ description?: string;
4
+ value: string;
5
+ }
6
+
7
+ export interface CanonicalQuestion {
8
+ id: string;
9
+ question: string;
10
+ header?: string;
11
+ options: CanonicalOption[];
12
+ multi: boolean;
13
+ recommended?: number;
14
+ }
15
+
16
+ export interface CanonicalAsk {
17
+ questions: CanonicalQuestion[];
18
+ }
19
+
20
+ export interface ResultItem {
21
+ id: string;
22
+ question: string;
23
+ header?: string;
24
+ options: { label: string; value?: string; description?: string }[];
25
+ multi: boolean;
26
+ recommended?: number;
27
+ selected: string[];
28
+ selectedLabels: string[];
29
+ customInput?: string;
30
+ unanswered?: boolean;
31
+ }
32
+
33
+ export interface AskUserQuestionResult {
34
+ results: ResultItem[];
35
+ cancelled?: boolean;
36
+ error?: string;
37
+ }
38
+
39
+ export interface DialogResult {
40
+ results: ResultItem[];
41
+ }
@@ -0,0 +1,62 @@
1
+ import type { CanonicalAsk, CanonicalQuestion } from './types';
2
+ import { isReservedLabel, RECOMMENDED_SUFFIX } from './normalize';
3
+ import { MAX_OPTIONS, MIN_OPTIONS } from './schema';
4
+
5
+ const MAX_HEADER_LENGTH = 40;
6
+ function checkHeader(question: CanonicalQuestion, headers: Set<string>, requiresHeader: boolean): string | null {
7
+ if (!requiresHeader) return null;
8
+ const header = question.header?.trim();
9
+ if (header === undefined) return null;
10
+ if (header.length > MAX_HEADER_LENGTH) {
11
+ return `Error: question ${question.id} header exceeds ${MAX_HEADER_LENGTH} characters: ${preview(header)}`;
12
+ }
13
+ const sticky = header.toLowerCase();
14
+ if (headers.has(sticky)) return `Error: question headers must be unique: ${preview(header)}`;
15
+ headers.add(sticky);
16
+ return null;
17
+ }
18
+
19
+ function preview(value: string): string {
20
+ return value.length > 120 ? `${value.slice(0, 120)}...` : value;
21
+ }
22
+
23
+ export function validateCanonical(ask: CanonicalAsk): string | undefined {
24
+ if (ask.questions.length === 0) {
25
+ return 'Error: at least one question with options is required';
26
+ }
27
+ const ids = new Set<string>();
28
+ const requiresHeader = ask.questions.length > 1;
29
+ const headers = new Set<string>();
30
+ for (const question of ask.questions) {
31
+ if (ids.has(question.id)) {
32
+ return `Error: question ids must be unique: ${preview(question.id)}`;
33
+ }
34
+ ids.add(question.id);
35
+ const headerError = checkHeader(question, headers, requiresHeader);
36
+ if (headerError) return headerError;
37
+ if (question.options.length < MIN_OPTIONS || question.options.length > MAX_OPTIONS) {
38
+ return `Error: question ${question.id} must have between ${MIN_OPTIONS} and ${MAX_OPTIONS} options`;
39
+ }
40
+ const labels = new Set<string>();
41
+ for (const option of question.options) {
42
+ if (isReservedLabel(option.label)) {
43
+ return `Error: option labels must not collide with reserved runtime labels: ${preview(option.label)}`;
44
+ }
45
+ if (option.label.endsWith(RECOMMENDED_SUFFIX)) {
46
+ return `Error: option labels must not end with the reserved suffix ${RECOMMENDED_SUFFIX}: ${preview(option.label)}`;
47
+ }
48
+ const sticky = option.label.toLowerCase();
49
+ if (labels.has(sticky)) {
50
+ return `Error: option labels must be unique within a question: ${preview(option.label)}`;
51
+ }
52
+ labels.add(sticky);
53
+ }
54
+ if (
55
+ question.recommended !== undefined &&
56
+ (question.recommended < 0 || question.recommended >= question.options.length)
57
+ ) {
58
+ return `Error: recommended index out of range for question ${question.id}`;
59
+ }
60
+ }
61
+ return undefined;
62
+ }