@mrclrchtr/supi-ask-user 1.13.0 → 1.14.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.
@@ -1,281 +1,314 @@
1
1
  import type {
2
- Answer,
3
- AnswerSelection,
2
+ AskUserInteractionResult,
4
3
  AskUserOutcome,
5
- AskUserStatus,
4
+ ChoiceQuestionResponse,
6
5
  NormalizedChoiceQuestion,
7
6
  NormalizedQuestion,
8
7
  NormalizedQuestionnaire,
8
+ NormalizedTextQuestion,
9
+ TextQuestionResponse,
9
10
  } from "../types.ts";
10
11
 
12
+ type OptionState = {
13
+ value: string;
14
+ label: string;
15
+ selected: boolean;
16
+ comment?: string;
17
+ };
18
+
19
+ type ChoiceState = {
20
+ kind: "choice";
21
+ options: OptionState[];
22
+ questionComment?: string;
23
+ markedUnanswered?: boolean;
24
+ };
25
+
26
+ type TextState = {
27
+ kind: "text";
28
+ value: string;
29
+ questionComment?: string;
30
+ markedUnanswered?: boolean;
31
+ };
32
+
33
+ type QuestionState = ChoiceState | TextState;
34
+
11
35
  export class AskUserController {
12
- private readonly answers = new Map<string, Answer>();
36
+ private readonly states: QuestionState[];
13
37
  private index = 0;
14
- private status: AskUserStatus | null = null;
15
- private discussMessage: string | undefined;
38
+ private terminal: boolean = false;
39
+ private terminalResult: AskUserInteractionResult | undefined;
40
+ private formComment: string | undefined;
16
41
 
17
42
  constructor(public readonly questionnaire: NormalizedQuestionnaire) {
18
43
  if (questionnaire.questions.length === 0) {
19
44
  throw new Error("AskUserController requires at least one question.");
20
45
  }
46
+ this.states = questionnaire.questions.map((q) => this.initialState(q));
21
47
  }
22
48
 
23
- get questions(): NormalizedQuestion[] {
24
- return this.questionnaire.questions;
25
- }
49
+ // ── Navigation ──────────────────────────────────────────────────
26
50
 
27
51
  get currentIndex(): number {
28
52
  return this.index;
29
53
  }
30
54
 
31
55
  get currentQuestion(): NormalizedQuestion {
32
- const question = this.questionnaire.questions[this.index];
33
- if (!question) {
34
- throw new Error(`No question at index ${this.index}.`);
35
- }
36
- return question;
56
+ return this.questionnaire.questions[this.index];
37
57
  }
38
58
 
39
59
  get isTerminal(): boolean {
40
- return this.status !== null;
60
+ return this.terminal;
41
61
  }
42
62
 
43
- get answerCount(): number {
44
- return this.answers.size;
63
+ goNext(): boolean {
64
+ if (this.terminal) return false;
65
+ if (this.index >= this.questionnaire.questions.length - 1) return false;
66
+ this.index += 1;
67
+ return true;
45
68
  }
46
69
 
47
- hasAnswer(questionId: string): boolean {
48
- return this.answers.has(questionId);
70
+ goBack(): boolean {
71
+ if (this.terminal) return false;
72
+ if (this.index === 0) return false;
73
+ this.index -= 1;
74
+ return true;
49
75
  }
50
76
 
51
- getAnswer(questionId: string): Answer | undefined {
52
- return this.answers.get(questionId);
77
+ goTo(index: number): boolean {
78
+ if (this.terminal) return false;
79
+ if (index < 0 || index >= this.questionnaire.questions.length) return false;
80
+ this.index = index;
81
+ return true;
53
82
  }
54
83
 
55
- getSelectedIndexes(question: NormalizedChoiceQuestion): number[] {
56
- const answer = this.answers.get(question.id);
57
- if (answer?.kind !== "choice") return [...question.initialIndexes];
58
- return answer.selections
59
- .map((selection) => question.options.findIndex((option) => option.value === selection.value))
60
- .filter((index) => index >= 0);
84
+ // ── Direct state queries ────────────────────────────────────────
85
+
86
+ isOptionSelected(questionId: string, optionValue: string): boolean {
87
+ const state = this.stateFor(questionId);
88
+ if (state.kind !== "choice") return false;
89
+ return state.options.find((option) => option.value === optionValue)?.selected ?? false;
61
90
  }
62
91
 
63
- getChoiceOptionNote(questionId: string, optionValue: string): string | undefined {
64
- const answer = this.answers.get(questionId);
65
- if (answer?.kind !== "choice") return undefined;
66
- return answer.selections.find((selection) => selection.value === optionValue)?.note;
92
+ isQuestionMarkedUnanswered(questionId: string): boolean {
93
+ return this.stateFor(questionId).markedUnanswered ?? false;
67
94
  }
68
95
 
69
- selectChoiceOption(question: NormalizedChoiceQuestion, optionIndex: number): void {
70
- if (this.isTerminal) return;
71
- const option = question.options[optionIndex];
72
- if (!option) return;
73
- const existingNote = this.getChoiceOptionNote(question.id, option.value);
74
- this.commitChoiceSelections(question, [
75
- buildSelection(option.value, option.label, existingNote),
76
- ]);
96
+ // ── Comments ────────────────────────────────────────────────────
97
+
98
+ get comment(): string | undefined {
99
+ return this.formComment;
77
100
  }
78
101
 
79
- toggleChoiceOption(question: NormalizedChoiceQuestion, optionIndex: number): void {
80
- if (this.isTerminal) return;
81
- const option = question.options[optionIndex];
82
- if (!option) return;
83
- if (!question.multi) {
84
- this.selectChoiceOption(question, optionIndex);
85
- return;
86
- }
102
+ setComment(text: string): void {
103
+ const trimmed = text.trim();
104
+ this.formComment = trimmed || undefined;
105
+ }
87
106
 
88
- const selections = this.getStoredChoiceSelections(question.id);
89
- const filtered = selections.filter((selection) => selection.value !== option.value);
90
- if (filtered.length !== selections.length) {
91
- this.commitChoiceSelections(question, filtered);
92
- return;
93
- }
107
+ setQuestionComment(questionId: string, text: string): void {
108
+ const state = this.stateFor(questionId);
109
+ const trimmed = text.trim();
110
+ state.questionComment = trimmed || undefined;
111
+ }
112
+
113
+ getQuestionComment(questionId: string): string | undefined {
114
+ return this.stateFor(questionId).questionComment;
115
+ }
94
116
 
95
- this.commitChoiceSelections(question, [
96
- ...selections,
97
- buildSelection(option.value, option.label),
98
- ]);
117
+ getOptionComment(questionId: string, optionValue: string): string | undefined {
118
+ const state = this.stateFor(questionId);
119
+ if (state.kind !== "choice") return undefined;
120
+ return state.options.find((o) => o.value === optionValue)?.comment;
99
121
  }
100
122
 
101
- setChoiceOptionNote(
123
+ setChoiceOptionComment(
102
124
  question: NormalizedChoiceQuestion,
103
125
  optionIndex: number,
104
- note: string | undefined,
126
+ comment: string | undefined,
105
127
  ): void {
106
- if (this.isTerminal) return;
107
- const option = question.options[optionIndex];
128
+ if (this.terminal) return;
129
+ const state = this.stateFor(question.id);
130
+ if (state.kind !== "choice") return;
131
+ const option = state.options[optionIndex];
108
132
  if (!option) return;
109
133
 
110
- const trimmedNote = trimOptional(note);
111
- const selections = this.getStoredChoiceSelections(question.id);
112
- const existing = selections.find((selection) => selection.value === option.value);
113
-
114
- if (existing) {
115
- this.commitChoiceSelections(
116
- question,
117
- selections.map((selection) => {
118
- if (selection.value !== option.value) return selection;
119
- return buildSelection(selection.value, selection.label, trimmedNote);
120
- }),
121
- );
122
- return;
123
- }
134
+ const trimmed = comment?.trim();
135
+ option.comment = trimmed || undefined;
136
+ }
124
137
 
125
- if (!trimmedNote) return;
138
+ // ── Single-select operations ────────────────────────────────────
126
139
 
127
- const nextSelection = buildSelection(option.value, option.label, trimmedNote);
128
- this.commitChoiceSelections(
129
- question,
130
- question.multi ? [...selections, nextSelection] : [nextSelection],
131
- );
132
- }
140
+ selectChoiceOption(question: NormalizedChoiceQuestion, optionIndex: number): void {
141
+ if (this.terminal) return;
142
+ const state = this.stateFor(question.id);
143
+ if (state.kind !== "choice") return;
133
144
 
134
- setAnswer(questionId: string, answer: Answer): void {
135
- if (this.isTerminal) return;
136
- this.answers.set(questionId, normalizeAnswer(answer));
145
+ for (const opt of state.options) {
146
+ opt.selected = opt === state.options[optionIndex];
147
+ }
148
+ state.markedUnanswered = false;
137
149
  }
138
150
 
139
- clearAnswer(questionId: string): void {
140
- if (this.isTerminal) return;
141
- this.answers.delete(questionId);
142
- }
151
+ // ── Multi-select operations ─────────────────────────────────────
143
152
 
144
- goNext(): boolean {
145
- if (this.isTerminal) return false;
146
- if (this.index >= this.questionnaire.questions.length - 1) return false;
147
- this.index += 1;
148
- return true;
149
- }
153
+ toggleChoiceOption(question: NormalizedChoiceQuestion, optionIndex: number): void {
154
+ if (this.terminal) return;
155
+ if (!question.multi) {
156
+ this.selectChoiceOption(question, optionIndex);
157
+ return;
158
+ }
159
+ const state = this.stateFor(question.id);
160
+ if (state.kind !== "choice") return;
161
+ const option = state.options[optionIndex];
162
+ if (!option) return;
150
163
 
151
- goBack(): boolean {
152
- if (this.isTerminal) return false;
153
- if (this.index === 0) return false;
154
- this.index -= 1;
155
- return true;
164
+ option.selected = !option.selected;
165
+ state.markedUnanswered = false;
166
+ // Preserve comment, only remove it explicitly via setChoiceOptionComment with blank
156
167
  }
157
168
 
158
- canSubmit(): boolean {
159
- return this.missingQuestionIds().length === 0;
160
- }
169
+ // ── Text operations ─────────────────────────────────────────────
161
170
 
162
- canPartialSubmit(): boolean {
163
- return (
164
- this.questionnaire.allowPartialSubmit &&
165
- this.answerCount > 0 &&
166
- this.missingQuestionIds().length > 0
167
- );
171
+ setTextAnswer(questionId: string, value: string): void {
172
+ if (this.terminal) return;
173
+ const state = this.stateFor(questionId);
174
+ if (state.kind !== "text") return;
175
+ state.value = value.trim();
176
+ if (state.value.length > 0) state.markedUnanswered = false;
168
177
  }
169
178
 
170
- finishSubmitted(): boolean {
171
- if (!this.canSubmit() || this.isTerminal) return false;
172
- this.status = "submitted";
173
- return true;
179
+ getTextAnswer(questionId: string): string {
180
+ const state = this.stateFor(questionId);
181
+ return state.kind === "text" ? state.value : "";
174
182
  }
175
183
 
176
- finishPartial(): boolean {
177
- if (!this.canPartialSubmit() || this.isTerminal) return false;
178
- this.status = "partial";
179
- return true;
184
+ // ── Unanswered marking ──────────────────────────────────────────
185
+
186
+ markCurrentQuestionUnanswered(): void {
187
+ if (this.terminal) return;
188
+ const state = this.states[this.index];
189
+ if (state.kind === "choice") {
190
+ for (const opt of state.options) {
191
+ opt.selected = false;
192
+ }
193
+ } else {
194
+ state.value = "";
195
+ }
196
+ state.markedUnanswered = true;
197
+ // Comments are preserved
180
198
  }
181
199
 
182
- finishDiscuss(message?: string): boolean {
183
- if (this.isTerminal) return false;
184
- this.status = "discuss";
185
- this.discussMessage = trimOptional(message);
186
- return true;
200
+ // ── Cancel / Abort (internal interaction results) ───────────────
201
+
202
+ cancel(): AskUserInteractionResult {
203
+ if (this.terminal) return { kind: "cancel" };
204
+ this.terminal = true;
205
+ this.terminalResult = { kind: "cancel" };
206
+ return { kind: "cancel" };
187
207
  }
188
208
 
189
- cancel(): void {
190
- if (this.isTerminal) return;
191
- this.status = "cancelled";
209
+ abort(): AskUserInteractionResult {
210
+ if (this.terminal) return { kind: "abort" };
211
+ this.terminal = true;
212
+ this.terminalResult = { kind: "abort" };
213
+ return { kind: "abort" };
192
214
  }
193
215
 
194
- abort(): void {
195
- if (this.isTerminal) return;
196
- this.status = "aborted";
216
+ /** Returns the terminal interaction result if the controller was cancelled/aborted, undefined otherwise. */
217
+ getInteractionResult(): AskUserInteractionResult | undefined {
218
+ return this.terminalResult;
197
219
  }
198
220
 
221
+ // ── Outcome ─────────────────────────────────────────────────────
222
+
199
223
  outcome(): AskUserOutcome {
224
+ const responses = this.questionnaire.questions.map((q) => this.buildResponse(q));
225
+
226
+ const allAnswered = responses.every((r) => r.answer.answered);
227
+
200
228
  return {
201
- status: this.status ?? "cancelled",
202
- answersById: Object.fromEntries(this.answers),
203
- missingQuestionIds: this.missingQuestionIds(),
204
- ...(this.discussMessage ? { discussMessage: this.discussMessage } : {}),
229
+ outcome: allAnswered ? "submitted" : "needs_discussion",
230
+ ...(this.formComment ? { comment: this.formComment } : {}),
231
+ responses,
205
232
  };
206
233
  }
207
234
 
208
- missingQuestionIds(): string[] {
209
- return this.questionnaire.questions
210
- .filter((question) => question.required && !this.answers.has(question.id))
211
- .map((question) => question.id);
212
- }
235
+ // ── Private helpers ─────────────────────────────────────────────
213
236
 
214
- private getStoredChoiceSelections(questionId: string): AnswerSelection[] {
215
- const answer = this.answers.get(questionId);
216
- if (answer?.kind !== "choice") return [];
217
- return answer.selections.map((selection) => ({ ...selection }));
218
- }
219
-
220
- private commitChoiceSelections(
221
- question: NormalizedChoiceQuestion,
222
- selections: AnswerSelection[],
223
- ): void {
224
- const ordered = orderSelections(question, normalizeChoiceSelections(selections));
225
- const nextSelections = question.multi ? ordered : ordered.slice(0, 1);
226
- if (nextSelections.length === 0) {
227
- this.answers.delete(question.id);
228
- return;
237
+ private stateFor(questionId: string): QuestionState {
238
+ const idx = this.questionnaire.questions.findIndex((q) => q.id === questionId);
239
+ if (idx < 0) {
240
+ throw new Error(`Unknown question id "${questionId}" in AskUserController.`);
229
241
  }
230
-
231
- this.answers.set(question.id, {
232
- kind: "choice",
233
- selections: nextSelections,
234
- });
242
+ return this.states[idx];
235
243
  }
236
- }
237
244
 
238
- function normalizeAnswer(answer: Answer): Answer {
239
- switch (answer.kind) {
240
- case "choice":
245
+ private initialState(question: NormalizedQuestion): QuestionState {
246
+ if (question.type === "choice") {
241
247
  return {
242
248
  kind: "choice",
243
- selections: normalizeChoiceSelections(answer.selections),
249
+ options: question.options.map((opt, i) => ({
250
+ value: opt.value,
251
+ label: opt.label,
252
+ selected: question.recommendedIndexes.includes(i),
253
+ })),
244
254
  };
245
- case "custom":
246
- return { kind: "custom", value: answer.value.trim() };
247
- case "text":
248
- return { kind: "text", value: answer.value.trim() };
255
+ }
256
+
257
+ return {
258
+ kind: "text",
259
+ value: question.recommendation ?? "",
260
+ };
249
261
  }
250
- }
251
262
 
252
- function normalizeChoiceSelections(selections: AnswerSelection[]): AnswerSelection[] {
253
- return selections.map((selection) =>
254
- buildSelection(selection.value, selection.label, selection.note),
255
- );
256
- }
263
+ private buildResponse(
264
+ question: NormalizedQuestion,
265
+ ): ChoiceQuestionResponse | TextQuestionResponse {
266
+ const state = this.stateFor(question.id);
257
267
 
258
- function orderSelections(
259
- question: NormalizedChoiceQuestion,
260
- selections: AnswerSelection[],
261
- ): AnswerSelection[] {
262
- const byValue = new Map(selections.map((selection) => [selection.value, selection]));
263
- return question.options.flatMap((option) => {
264
- const selection = byValue.get(option.value);
265
- return selection ? [selection] : [];
266
- });
267
- }
268
+ if (question.type === "choice") {
269
+ return this.buildChoiceResponse(question, state as ChoiceState);
270
+ }
268
271
 
269
- function buildSelection(value: string, label: string, note?: string): AnswerSelection {
270
- const trimmedNote = trimOptional(note);
271
- return {
272
- value: value.trim(),
273
- label: label.trim(),
274
- ...(trimmedNote ? { note: trimmedNote } : {}),
275
- };
276
- }
272
+ return this.buildTextResponse(question, state as TextState);
273
+ }
277
274
 
278
- function trimOptional(value: string | undefined): string | undefined {
279
- const trimmed = value?.trim();
280
- return trimmed ? trimmed : undefined;
275
+ private buildChoiceResponse(
276
+ question: NormalizedChoiceQuestion,
277
+ state: ChoiceState,
278
+ ): ChoiceQuestionResponse {
279
+ // Only include touched options: selected and/or commented
280
+ const touchedOptions = state.options.filter((o) => o.selected || o.comment);
281
+
282
+ return {
283
+ questionId: question.id,
284
+ ...(state.questionComment ? { questionComment: state.questionComment } : {}),
285
+ answer: {
286
+ kind: "choice",
287
+ answered: touchedOptions.some((o) => o.selected),
288
+ options: touchedOptions.map((o) => ({
289
+ value: o.value,
290
+ label: o.label,
291
+ selected: o.selected,
292
+ ...(o.comment ? { comment: o.comment } : {}),
293
+ })),
294
+ },
295
+ };
296
+ }
297
+
298
+ private buildTextResponse(
299
+ question: NormalizedTextQuestion,
300
+ state: TextState,
301
+ ): TextQuestionResponse {
302
+ const answered = state.value.length > 0;
303
+
304
+ return {
305
+ questionId: question.id,
306
+ ...(state.questionComment ? { questionComment: state.questionComment } : {}),
307
+ answer: {
308
+ kind: "text",
309
+ answered,
310
+ ...(answered ? { value: state.value } : {}),
311
+ },
312
+ };
313
+ }
281
314
  }
@@ -1,7 +1,7 @@
1
1
  // Session-scoped single-active interaction guard for ask_user.
2
2
 
3
3
  export class ActiveQuestionnaireLock {
4
- private active = false;
4
+ private active: boolean = false;
5
5
 
6
6
  acquire(): boolean {
7
7
  if (this.active) return false;
@@ -9,5 +9,8 @@ export const promptGuidelines = [
9
9
  "Use ask_user only for blocking user input, not open-ended interviews or repo facts.",
10
10
  "Use ask_user with 1-10 related questions; prefer one when possible.",
11
11
  "Use ask_user `choice` for fixed options and ask_user `text` for freeform input; yes/no should be a `choice`.",
12
- "Keep one ask_user form active at a time; use `allowOther` only for single-select choice and `allowPartialSubmit` only when actionable.",
12
+ "Keep one ask_user form active at a time.",
13
+ "Use `recommendation` to suggest default choices or prefilled text.",
14
+ "All questions are expected for a full submission — unanswered questions produce `needs_discussion` instead.",
15
+ "Comments on questions and options are user UI affordances — do not reference removed fields like `required`, `initial`, `allowOther`, or `allowPartialSubmit`.",
13
16
  ];
package/src/types.ts CHANGED
@@ -2,8 +2,6 @@
2
2
  // The external tool-call schema lives in schema.ts; everything past validation
3
3
  // works with the normalized shapes defined here.
4
4
 
5
- export type AskUserStatus = "submitted" | "partial" | "discuss" | "cancelled" | "aborted";
6
-
7
5
  export interface NormalizedOption {
8
6
  value: string;
9
7
  label: string;
@@ -15,21 +13,18 @@ interface BaseQuestion {
15
13
  id: string;
16
14
  header: string;
17
15
  prompt: string;
18
- required: boolean;
19
16
  }
20
17
 
21
18
  export interface NormalizedChoiceQuestion extends BaseQuestion {
22
19
  type: "choice";
23
20
  options: NormalizedOption[];
24
21
  multi: boolean;
25
- allowOther: boolean;
26
22
  recommendedIndexes: number[];
27
- initialIndexes: number[];
28
23
  }
29
24
 
30
25
  export interface NormalizedTextQuestion extends BaseQuestion {
31
26
  type: "text";
32
- initial?: string;
27
+ recommendation?: string;
33
28
  placeholder?: string;
34
29
  }
35
30
 
@@ -39,43 +34,43 @@ export interface NormalizedQuestionnaire {
39
34
  title?: string;
40
35
  intro?: string;
41
36
  questions: NormalizedQuestion[];
42
- allowPartialSubmit: boolean;
43
- }
44
-
45
- /**
46
- * One selected choice option returned from `ask_user`.
47
- *
48
- * `note` is optional user-entered context attached to this specific option.
49
- * It is only used on `choice` answers and is absent for `text` / `custom` answers.
50
- */
51
- export interface AnswerSelection {
52
- value: string;
53
- label: string;
54
- note?: string;
55
37
  }
56
38
 
57
- export interface ChoiceAnswer {
58
- kind: "choice";
59
- selections: AnswerSelection[];
39
+ // ── User-facing outcome types ──────────────────────────────────────
40
+
41
+ export type AskUserOutcomeKind = "submitted" | "needs_discussion";
42
+
43
+ export interface ChoiceQuestionResponse {
44
+ questionId: string;
45
+ questionComment?: string;
46
+ answer: {
47
+ kind: "choice";
48
+ answered: boolean;
49
+ options: Array<{
50
+ value: string;
51
+ label: string;
52
+ selected: boolean;
53
+ comment?: string;
54
+ }>;
55
+ };
60
56
  }
61
57
 
62
- export interface CustomAnswer {
63
- kind: "custom";
64
- value: string;
65
- }
66
-
67
- export interface TextAnswer {
68
- kind: "text";
69
- value: string;
58
+ export interface TextQuestionResponse {
59
+ questionId: string;
60
+ questionComment?: string;
61
+ answer: {
62
+ kind: "text";
63
+ answered: boolean;
64
+ value?: string;
65
+ };
70
66
  }
71
67
 
72
- export type Answer = ChoiceAnswer | CustomAnswer | TextAnswer;
68
+ export type AskUserResponse = ChoiceQuestionResponse | TextQuestionResponse;
73
69
 
74
70
  export interface AskUserOutcome {
75
- status: AskUserStatus;
76
- answersById: Record<string, Answer>;
77
- missingQuestionIds: string[];
78
- discussMessage?: string;
71
+ outcome: AskUserOutcomeKind;
72
+ comment?: string;
73
+ responses: AskUserResponse[];
79
74
  }
80
75
 
81
76
  export interface AskUserDetails extends AskUserOutcome {
@@ -91,6 +86,20 @@ export interface AskUserErrorDetails {
91
86
 
92
87
  export type AskUserToolDetails = AskUserDetails | AskUserErrorDetails;
93
88
 
89
+ // ── Internal interaction result: UI cancel/abort are NOT persisted ──
90
+
91
+ export type AskUserInteractionResult = AskUserInteractionCancel | AskUserInteractionAbort;
92
+
93
+ export interface AskUserInteractionCancel {
94
+ kind: "cancel";
95
+ }
96
+
97
+ export interface AskUserInteractionAbort {
98
+ kind: "abort";
99
+ }
100
+
101
+ // ── Limits ─────────────────────────────────────────────────────────
102
+
94
103
  export const ASK_USER_LIMITS = {
95
104
  minQuestions: 1,
96
105
  maxQuestions: 10,
@@ -103,6 +112,8 @@ export const ASK_USER_LIMITS = {
103
112
  maxPlaceholderLength: 200,
104
113
  } as const;
105
114
 
115
+ // ── Guards ─────────────────────────────────────────────────────────
116
+
106
117
  export function isChoiceQuestion(
107
118
  question: NormalizedQuestion,
108
119
  ): question is NormalizedChoiceQuestion {