@stackwright-pro/otters 1.0.0-alpha.4 → 1.0.0-alpha.40

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,296 +0,0 @@
1
- /**
2
- * Question Adapter - Converts between Question Manifest format and ask_user_question format
3
- *
4
- * The ask_user_question MCP tool requires:
5
- * - question: string (full text)
6
- * - header: string (max 12 chars, short label)
7
- * - multi_select: boolean
8
- * - options: {label, description}[] (REQUIRED, min 2)
9
- *
10
- * Our Question Manifest format has:
11
- * - id: string (e.g., "api-1")
12
- * - question: string
13
- * - type: 'text' | 'select' | 'multi-select' | 'confirm'
14
- * - options?: {label, value}[] (optional for text/confirm)
15
- * - required?: boolean
16
- * - default?: string | boolean | string[]
17
- * - dependsOn?: {questionId, value}
18
- */
19
-
20
- export interface QuestionManifestQuestion {
21
- id: string;
22
- question: string;
23
- type: 'text' | 'select' | 'multi-select' | 'confirm';
24
- required?: boolean;
25
- options?: { label: string; value: string }[];
26
- default?: string | boolean | string[];
27
- help?: string;
28
- dependsOn?: {
29
- questionId: string;
30
- value: string | string[];
31
- };
32
- }
33
-
34
- export interface AskUserQuestionOption {
35
- label: string;
36
- description?: string;
37
- }
38
-
39
- export interface AskUserQuestion {
40
- question: string;
41
- header: string;
42
- multi_select: boolean;
43
- options: AskUserQuestionOption[];
44
- }
45
-
46
- /**
47
- * Truncate string to max length, adding ellipsis if needed
48
- */
49
- function truncate(str: string, maxLength: number): string {
50
- if (str.length <= maxLength) return str;
51
- return str.substring(0, maxLength - 1) + '…';
52
- }
53
-
54
- /**
55
- * Generate a valid header from a question ID
56
- * Headers must be max 12 chars, alphanumeric with hyphens
57
- */
58
- function generateHeader(id: string): string {
59
- // Remove numbers and prefix, keep meaningful part
60
- // e.g., "api-1" -> "API-1", "auth-3" -> "AUTH-3"
61
- const parts = id.split('-');
62
- if (parts.length >= 2) {
63
- const prefix = parts[0].toUpperCase().substring(0, 4);
64
- const num = parts[1];
65
- return truncate(`${prefix}-${num}`, 12);
66
- }
67
- return truncate(
68
- id
69
- .toUpperCase()
70
- .replace(/[^A-Z0-9]/g, '')
71
- .substring(0, 12),
72
- 12
73
- );
74
- }
75
-
76
- /**
77
- * Generate default options for question types that don't have options
78
- */
79
- function generateDefaultOptions(type: string): AskUserQuestionOption[] {
80
- switch (type) {
81
- case 'confirm':
82
- return [
83
- { label: 'Yes', description: 'Enable or confirm this option' },
84
- { label: 'No', description: 'Disable or decline this option' },
85
- ];
86
- case 'text':
87
- return [
88
- { label: 'Specify', description: 'I will provide a specific value' },
89
- { label: 'Skip', description: 'Use default or skip this question' },
90
- ];
91
- default:
92
- return [
93
- { label: 'Option 1', description: 'First option' },
94
- { label: 'Option 2', description: 'Second option' },
95
- ];
96
- }
97
- }
98
-
99
- /**
100
- * Convert a single QuestionManifest question to ask_user_question format
101
- */
102
- export function adaptQuestion(q: QuestionManifestQuestion): AskUserQuestion {
103
- // Generate header from ID
104
- const header = generateHeader(q.id);
105
-
106
- // Determine multi_select
107
- const multiSelect = q.type === 'multi-select';
108
-
109
- // Handle options - use provided or generate defaults
110
- let options: AskUserQuestionOption[];
111
-
112
- if (q.options && q.options.length >= 2) {
113
- // Use provided options, adapt format
114
- options = q.options.map((opt) => ({
115
- label: truncate(opt.label, 50),
116
- description: opt.value !== opt.label ? opt.value : undefined,
117
- }));
118
- } else if (q.options && q.options.length === 1) {
119
- // Single option - add a default
120
- options = [
121
- ...q.options.map((opt) => ({ label: truncate(opt.label, 50), description: opt.value })),
122
- { label: 'Other', description: 'Specify a different value' },
123
- ];
124
- } else {
125
- // No options - generate defaults based on type
126
- options = generateDefaultOptions(q.type);
127
- }
128
-
129
- // Ensure minimum 2 options (MCP tool requirement)
130
- if (options.length < 2) {
131
- options.push({ label: 'Other', description: 'Alternative option' });
132
- }
133
-
134
- // Limit to 6 options (MCP tool max)
135
- options = options.slice(0, 6);
136
-
137
- return {
138
- question: q.question + (q.help ? `\n\n${q.help}` : ''),
139
- header,
140
- multi_select: multiSelect,
141
- options,
142
- };
143
- }
144
-
145
- /**
146
- * Adapt multiple questions, filtering by dependsOn
147
- *
148
- * @param questions - All questions from manifest
149
- * @param answers - Previously answered questions (for filtering conditionals)
150
- * @returns Questions adapted for ask_user_question, with conditionals resolved
151
- */
152
- export function adaptQuestions(
153
- questions: QuestionManifestQuestion[],
154
- answers: Record<string, string | string[] | boolean> = {}
155
- ): AskUserQuestion[] {
156
- const adapted: AskUserQuestion[] = [];
157
-
158
- for (const q of questions) {
159
- // Check dependsOn condition
160
- if (q.dependsOn) {
161
- const dependsAnswer = answers[q.dependsOn.questionId];
162
- if (dependsAnswer === undefined) {
163
- // Parent question not answered yet - skip this conditional question
164
- continue;
165
- }
166
-
167
- // Check if the answer matches the condition
168
- const expectedValues = Array.isArray(q.dependsOn.value)
169
- ? q.dependsOn.value
170
- : [q.dependsOn.value];
171
-
172
- const answerValue = Array.isArray(dependsAnswer) ? dependsAnswer[0] : dependsAnswer;
173
-
174
- if (!expectedValues.includes(answerValue as string)) {
175
- // Condition not met - skip this question
176
- continue;
177
- }
178
- }
179
-
180
- adapted.push(adaptQuestion(q));
181
- }
182
-
183
- return adapted;
184
- }
185
-
186
- /**
187
- * Parse JSON response from LLM (handles various formats)
188
- */
189
- export function parseLLMQuestionsResponse(text: string): QuestionManifestQuestion[] {
190
- // Try to extract JSON from the response
191
- let jsonStr = text;
192
-
193
- // Remove markdown code blocks
194
- jsonStr = jsonStr.replace(/```(?:json|javascript)?\s*/gi, '');
195
- jsonStr = jsonStr.replace(/```\s*$/gm, '');
196
-
197
- // Find JSON object or array
198
- const firstBrace = jsonStr.indexOf('{');
199
- const firstBracket = jsonStr.indexOf('[');
200
-
201
- let start = -1;
202
- if (firstBrace !== -1 && firstBracket !== -1) {
203
- start = Math.min(firstBrace, firstBracket);
204
- } else if (firstBrace !== -1) {
205
- start = firstBrace;
206
- } else if (firstBracket !== -1) {
207
- start = firstBracket;
208
- }
209
-
210
- if (start === -1) {
211
- throw new Error('No JSON found in response');
212
- }
213
-
214
- jsonStr = jsonStr.substring(start);
215
-
216
- // Handle trailing text after JSON
217
- const lastBrace = jsonStr.lastIndexOf('}');
218
- const lastBracket = jsonStr.lastIndexOf(']');
219
- const end = Math.max(lastBrace, lastBracket);
220
-
221
- if (end === -1) {
222
- throw new Error('Invalid JSON structure');
223
- }
224
-
225
- jsonStr = jsonStr.substring(0, end + 1);
226
-
227
- // Fix common issues
228
- jsonStr = jsonStr.replace(/,(\s*[}\]])/g, '$1'); // Remove trailing commas
229
- jsonStr = jsonStr.replace(/'/g, '"'); // Single quotes to double
230
-
231
- const parsed = JSON.parse(jsonStr);
232
-
233
- // Handle various JSON structures
234
- let questions: unknown[];
235
-
236
- if (Array.isArray(parsed)) {
237
- questions = parsed;
238
- } else if (parsed.questions && Array.isArray(parsed.questions)) {
239
- questions = parsed.questions;
240
- } else if (parsed.data && Array.isArray((parsed.data as Record<string, unknown>).questions)) {
241
- questions = (parsed.data as Record<string, unknown>).questions as unknown[];
242
- } else {
243
- throw new Error('No questions array found in response');
244
- }
245
-
246
- return questions as QuestionManifestQuestion[];
247
- }
248
-
249
- /**
250
- * Convert ask_user_question answers back to manifest format
251
- */
252
- export function answersToManifestFormat(
253
- answers: { question_header: string; selected_options: string[]; other_text?: string | null }[],
254
- questions: QuestionManifestQuestion[]
255
- ): Record<string, string | string[] | boolean> {
256
- const result: Record<string, string | string[] | boolean> = {};
257
-
258
- for (const answer of answers) {
259
- // Find matching question by header
260
- const headerLower = answer.question_header.toLowerCase();
261
- const question = questions.find((q) => {
262
- const qHeader = generateHeader(q.id).toLowerCase();
263
- return qHeader === headerLower || q.id.toLowerCase().includes(headerLower);
264
- });
265
-
266
- if (!question) {
267
- // Try to match by header prefix
268
- const matched = questions.find((q) => {
269
- const qHeader = generateHeader(q.id).toLowerCase();
270
- return qHeader.startsWith(headerLower.split('-')[0]);
271
- });
272
- if (matched) {
273
- result[matched.id] = answer.selected_options[0] || '';
274
- }
275
- continue;
276
- }
277
-
278
- // Handle multi-select vs single select
279
- if (question.type === 'multi-select' || answer.selected_options.length > 1) {
280
- result[question.id] = answer.selected_options;
281
- } else if (question.type === 'confirm') {
282
- result[question.id] = answer.selected_options[0] === 'Yes';
283
- } else {
284
- // For text or single select, use first option or other_text
285
- if (answer.other_text) {
286
- result[question.id] = answer.other_text;
287
- } else if (answer.selected_options.length > 0) {
288
- // Map label back to value if possible
289
- const option = question.options?.find((o) => o.label === answer.selected_options[0]);
290
- result[question.id] = option?.value ?? answer.selected_options[0];
291
- }
292
- }
293
- }
294
-
295
- return result;
296
- }