@bismawy/pi-arnative 0.18.2 → 0.19.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.
- package/extensions/index.ts +2 -0
- package/lib/ask-user.ts +596 -0
- package/lib/edit-diff.ts +73 -12
- package/lib/features/arnative.ts +246 -4
- package/lib/features/ask-user.ts +1036 -0
- package/lib/features/progress-group.ts +50 -31
- package/lib/features/render-cache.ts +4 -9
- package/lib/features/tools.ts +36 -136
- package/lib/preset-store.ts +7 -1
- package/lib/runtime.ts +0 -4
- package/package.json +3 -2
package/extensions/index.ts
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
10
10
|
import { registerLifecycleFeatures } from "../lib/runtime.ts";
|
|
11
11
|
import registerArnative from "../lib/features/arnative.ts";
|
|
12
|
+
import registerAskUser from "../lib/features/ask-user.ts";
|
|
12
13
|
import registerAutoCompact from "../lib/features/auto-compact.ts";
|
|
13
14
|
import registerBudget from "../lib/features/budget.ts";
|
|
14
15
|
import registerFooter from "../lib/features/footer.ts";
|
|
@@ -33,6 +34,7 @@ const FEATURES: readonly ((pi: ExtensionAPI) => void)[] = [
|
|
|
33
34
|
registerAutoCompact,
|
|
34
35
|
registerModelHeal,
|
|
35
36
|
registerTodos,
|
|
37
|
+
registerAskUser,
|
|
36
38
|
registerArnative,
|
|
37
39
|
];
|
|
38
40
|
|
package/lib/ask-user.ts
ADDED
|
@@ -0,0 +1,596 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure core for `ask_user_question`: schema, validation, config persistence,
|
|
3
|
+
* smart question-delegation prompt/parser, and answer envelope formatting.
|
|
4
|
+
*
|
|
5
|
+
* Kept free of TUI and Pi runtime side effects so unit tests exercise every
|
|
6
|
+
* branch directly without mocking terminal streams.
|
|
7
|
+
*/
|
|
8
|
+
import { Type, type Static } from "typebox";
|
|
9
|
+
import { ASK_MODE_KEY, ASK_MODEL_KEY, ASK_THINKING_KEY, loadChoice, loadSetting, saveChoice } from "./preset-store.ts";
|
|
10
|
+
|
|
11
|
+
export const ASK_TOOL_NAME = "ask_user_question";
|
|
12
|
+
|
|
13
|
+
export const MAX_QUESTIONS = 4;
|
|
14
|
+
export const MIN_OPTIONS = 2;
|
|
15
|
+
export const MAX_OPTIONS = 4;
|
|
16
|
+
export const MAX_HEADER_LENGTH = 16;
|
|
17
|
+
export const MAX_LABEL_LENGTH = 60;
|
|
18
|
+
|
|
19
|
+
export const CUSTOM_ROW_LABEL = "Type something.";
|
|
20
|
+
export const RESERVED_LABELS = ["Other", CUSTOM_ROW_LABEL, "Next"] as const;
|
|
21
|
+
const RESERVED_LABEL_SET: ReadonlySet<string> = new Set(RESERVED_LABELS.map((s) => s.toLowerCase()));
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Custom-model delegation mode:
|
|
25
|
+
* - `Off`: show the active model's questions directly (no extra model call).
|
|
26
|
+
* - `Refine`: audit & sharpen drafted `questions` via the configured model.
|
|
27
|
+
* - `Hybrid` (default): both Refine drafted `questions` AND Author from scratch
|
|
28
|
+
* when the active model supplies only `goal`/`context`/`ambiguities`.
|
|
29
|
+
*/
|
|
30
|
+
export const ASK_MODE_CHOICES = ["Hybrid", "Refine", "Off"] as const;
|
|
31
|
+
export type AskMode = (typeof ASK_MODE_CHOICES)[number];
|
|
32
|
+
export const DEFAULT_ASK_MODE: AskMode = "Hybrid";
|
|
33
|
+
|
|
34
|
+
export const ASK_THINKING_CHOICES = ["off", "low", "medium", "high"] as const;
|
|
35
|
+
export type AskThinking = (typeof ASK_THINKING_CHOICES)[number];
|
|
36
|
+
export const DEFAULT_ASK_THINKING: AskThinking = "low";
|
|
37
|
+
|
|
38
|
+
/** Empty string means "use the session's active model (no delegation)". */
|
|
39
|
+
export const DEFAULT_ASK_MODEL = "";
|
|
40
|
+
|
|
41
|
+
export function activeAskMode(): AskMode {
|
|
42
|
+
return loadChoice(ASK_MODE_KEY, ASK_MODE_CHOICES) ?? DEFAULT_ASK_MODE;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function setAskMode(mode: AskMode): void {
|
|
46
|
+
saveChoice(ASK_MODE_KEY, mode);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function activeAskThinking(): AskThinking {
|
|
50
|
+
return loadChoice(ASK_THINKING_KEY, ASK_THINKING_CHOICES) ?? DEFAULT_ASK_THINKING;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function setAskThinking(level: AskThinking): void {
|
|
54
|
+
saveChoice(ASK_THINKING_KEY, level);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Stored as `"provider/modelId"` or `""` (active session model). */
|
|
58
|
+
export function activeAskModel(): string {
|
|
59
|
+
const raw = loadSetting(ASK_MODEL_KEY);
|
|
60
|
+
return typeof raw === "string" ? raw.trim() : DEFAULT_ASK_MODEL;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function setAskModel(spec: string): void {
|
|
64
|
+
saveChoice(ASK_MODEL_KEY, spec.trim());
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Parse `"provider/modelId"` into its components; returns null for empty/malformed specs. */
|
|
68
|
+
export function parseModelSpec(spec: string): { provider: string; modelId: string } | null {
|
|
69
|
+
const trimmed = spec.trim();
|
|
70
|
+
if (!trimmed) return null;
|
|
71
|
+
const slash = trimmed.indexOf("/");
|
|
72
|
+
if (slash <= 0 || slash === trimmed.length - 1) return null;
|
|
73
|
+
const provider = trimmed.slice(0, slash).trim();
|
|
74
|
+
const modelId = trimmed.slice(slash + 1).trim();
|
|
75
|
+
if (!provider || !modelId) return null;
|
|
76
|
+
return { provider, modelId };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// ---------------------------------------------------------------------------
|
|
80
|
+
// Tool parameter schema
|
|
81
|
+
// ---------------------------------------------------------------------------
|
|
82
|
+
|
|
83
|
+
export const OptionSchema = Type.Object({
|
|
84
|
+
label: Type.String({
|
|
85
|
+
maxLength: MAX_LABEL_LENGTH,
|
|
86
|
+
description: `Concise option label (1-5 words, max ${MAX_LABEL_LENGTH} chars). Put the recommended option first and append "(Recommended)".`,
|
|
87
|
+
}),
|
|
88
|
+
description: Type.String({
|
|
89
|
+
description: "Concrete explanation of what this option means and its key trade-off or consequence.",
|
|
90
|
+
}),
|
|
91
|
+
preview: Type.Optional(
|
|
92
|
+
Type.String({
|
|
93
|
+
description:
|
|
94
|
+
"Optional markdown snippet (ASCII mockup, code, schema, config) rendered beside the option list. Single-select only; omit when labels/descriptions suffice.",
|
|
95
|
+
}),
|
|
96
|
+
),
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
export const QuestionSchema = Type.Object({
|
|
100
|
+
question: Type.String({
|
|
101
|
+
description: "Clear, decision-focused question ending with '?'.",
|
|
102
|
+
}),
|
|
103
|
+
header: Type.String({
|
|
104
|
+
maxLength: MAX_HEADER_LENGTH,
|
|
105
|
+
description: `Short tab chip (max ${MAX_HEADER_LENGTH} chars), e.g. "Storage", "Auth", "Layout".`,
|
|
106
|
+
}),
|
|
107
|
+
options: Type.Array(OptionSchema, {
|
|
108
|
+
minItems: MIN_OPTIONS,
|
|
109
|
+
maxItems: MAX_OPTIONS,
|
|
110
|
+
description: `2-4 distinct choices. Do NOT include "Other" or "${CUSTOM_ROW_LABEL}" — custom input is appended automatically.`,
|
|
111
|
+
}),
|
|
112
|
+
multiSelect: Type.Optional(
|
|
113
|
+
Type.Boolean({
|
|
114
|
+
default: false,
|
|
115
|
+
description: "Set true when the user can pick multiple non-exclusive options.",
|
|
116
|
+
}),
|
|
117
|
+
),
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
export const AskUserParamsSchema = Type.Object({
|
|
121
|
+
questions: Type.Optional(
|
|
122
|
+
Type.Array(QuestionSchema, {
|
|
123
|
+
minItems: 1,
|
|
124
|
+
maxItems: MAX_QUESTIONS,
|
|
125
|
+
description:
|
|
126
|
+
"1-4 structured questions to ask the user. Required when no custom question model is configured, or as a draft for the custom model to audit and sharpen.",
|
|
127
|
+
}),
|
|
128
|
+
),
|
|
129
|
+
goal: Type.Optional(
|
|
130
|
+
Type.String({
|
|
131
|
+
description:
|
|
132
|
+
"Short statement of what the user is trying to achieve (used when delegating question authoring to a custom flagship model).",
|
|
133
|
+
}),
|
|
134
|
+
),
|
|
135
|
+
context: Type.Optional(
|
|
136
|
+
Type.String({
|
|
137
|
+
description:
|
|
138
|
+
"Relevant constraints, codebase facts, or ambiguity points so the question model asks only high-leverage questions.",
|
|
139
|
+
}),
|
|
140
|
+
),
|
|
141
|
+
ambiguities: Type.Optional(
|
|
142
|
+
Type.Array(Type.String(), {
|
|
143
|
+
minItems: 1,
|
|
144
|
+
maxItems: 6,
|
|
145
|
+
description:
|
|
146
|
+
"Unresolved decisions that change the implementation. When a custom question model is active in Hybrid mode, you may pass goal + ambiguities without authoring full options.",
|
|
147
|
+
}),
|
|
148
|
+
),
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
export type OptionData = Static<typeof OptionSchema>;
|
|
152
|
+
export type QuestionData = Static<typeof QuestionSchema>;
|
|
153
|
+
export type AskUserParams = Static<typeof AskUserParamsSchema>;
|
|
154
|
+
|
|
155
|
+
export interface NormalizedQuestions {
|
|
156
|
+
questions: QuestionData[];
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export interface QuestionAnswer {
|
|
160
|
+
questionIndex: number;
|
|
161
|
+
question: string;
|
|
162
|
+
kind: "option" | "custom" | "multi";
|
|
163
|
+
answer: string | null;
|
|
164
|
+
selected?: string[];
|
|
165
|
+
preview?: string;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export interface QuestionnaireResult {
|
|
169
|
+
answers: QuestionAnswer[];
|
|
170
|
+
cancelled: boolean;
|
|
171
|
+
unanswered?: number[];
|
|
172
|
+
delegatedModel?: string;
|
|
173
|
+
delegatedAction?: "refined" | "authored" | "fallback";
|
|
174
|
+
error?: string;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// ---------------------------------------------------------------------------
|
|
178
|
+
// Tool prompt copy
|
|
179
|
+
// ---------------------------------------------------------------------------
|
|
180
|
+
|
|
181
|
+
export const ASK_PROMPT_SNIPPET =
|
|
182
|
+
"Ask the user 1-4 structured, decision-focused questions (2-4 options each) when requirements are genuinely ambiguous";
|
|
183
|
+
|
|
184
|
+
export const ASK_PROMPT_GUIDELINES: string[] = [
|
|
185
|
+
"Use ask_user_question only when unresolved decisions meaningfully change implementation — never for trivial confirmations or facts you can verify in the repo.",
|
|
186
|
+
`Provide 1-${MAX_QUESTIONS} questions with ${MIN_OPTIONS}-${MAX_OPTIONS} concrete options each (or pass goal + ambiguities when delegating to a configured question model). Put the best default first with "(Recommended)" and state the real trade-off in description.`,
|
|
187
|
+
`Never author "Other" or "${CUSTOM_ROW_LABEL}" options — a custom free-text row is appended automatically. Use preview (markdown) only when visual/code comparison clarifies the choice (single-select only).`,
|
|
188
|
+
"Group all clarifying questions into one ask_user_question call instead of stacking multiple back-to-back calls.",
|
|
189
|
+
];
|
|
190
|
+
|
|
191
|
+
export const ASK_TOOL_DESCRIPTION = `Ask the user 1-4 structured questions to resolve high-leverage ambiguities before acting.
|
|
192
|
+
|
|
193
|
+
When to call:
|
|
194
|
+
- Requirements have 2+ interpretations that produce materially different code, UX, or architecture.
|
|
195
|
+
- Scope, trade-offs, or breaking choices need explicit user sign-off.
|
|
196
|
+
|
|
197
|
+
When NOT to call:
|
|
198
|
+
- Facts can be verified by reading files or running a quick check.
|
|
199
|
+
- Only one sensible default exists.
|
|
200
|
+
|
|
201
|
+
Guidelines:
|
|
202
|
+
- Each question needs 2-4 distinct options with a concise label (<=60 chars) and concrete trade-off description.
|
|
203
|
+
- Place your recommended option first and append "(Recommended)" to its label.
|
|
204
|
+
- Do NOT author "Other" or "${CUSTOM_ROW_LABEL}" — custom text entry is added automatically.
|
|
205
|
+
- Use optional \`preview\` (ASCII layout, snippet, schema) on single-select options only when visual comparison helps.
|
|
206
|
+
- If a custom flagship question model is configured in /arnative (Hybrid mode), you may pass either drafted \`questions\` (to audit and upgrade) or lightweight \`goal\` + \`ambiguities\` (to author from scratch).`;
|
|
207
|
+
|
|
208
|
+
// ---------------------------------------------------------------------------
|
|
209
|
+
// Normalization & validation
|
|
210
|
+
// ---------------------------------------------------------------------------
|
|
211
|
+
|
|
212
|
+
const normalizeText = (value: string): string => value.replace(/\r\n/g, "\n").replace(/\r/g, "").trim();
|
|
213
|
+
|
|
214
|
+
const truncate = (value: string, max: number): string =>
|
|
215
|
+
value.length <= max ? value : `${value.slice(0, Math.max(1, max - 1)).trimEnd()}…`;
|
|
216
|
+
|
|
217
|
+
/** Undo double-encoded JSON strings some smaller models emit for nested arrays/objects. */
|
|
218
|
+
export function prepareAskArguments(raw: unknown): unknown {
|
|
219
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return raw;
|
|
220
|
+
const obj = { ...(raw as Record<string, unknown>) };
|
|
221
|
+
for (const key of ["questions", "ambiguities"] as const) {
|
|
222
|
+
if (typeof obj[key] === "string") {
|
|
223
|
+
try {
|
|
224
|
+
const parsed = JSON.parse(obj[key] as string);
|
|
225
|
+
if (Array.isArray(parsed)) obj[key] = parsed;
|
|
226
|
+
} catch {
|
|
227
|
+
// Leave untouched for schema validation to report cleanly.
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
return obj;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export function normalizeQuestion(q: QuestionData): QuestionData {
|
|
235
|
+
const multiSelect = Boolean(q.multiSelect);
|
|
236
|
+
const options: OptionData[] = q.options.map((o) => {
|
|
237
|
+
const preview = !multiSelect && typeof o.preview === "string" && normalizeText(o.preview).length > 0
|
|
238
|
+
? o.preview.replace(/\r\n/g, "\n").replace(/\r/g, "").trimEnd()
|
|
239
|
+
: undefined;
|
|
240
|
+
return {
|
|
241
|
+
label: normalizeText(o.label),
|
|
242
|
+
description: normalizeText(o.description),
|
|
243
|
+
...(preview ? { preview } : {}),
|
|
244
|
+
};
|
|
245
|
+
});
|
|
246
|
+
return {
|
|
247
|
+
question: normalizeText(q.question),
|
|
248
|
+
header: normalizeText(q.header),
|
|
249
|
+
options,
|
|
250
|
+
multiSelect,
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
export function normalizeQuestions(questions: readonly QuestionData[]): QuestionData[] {
|
|
255
|
+
return questions.map(normalizeQuestion);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Coerce a model-generated question array into valid bounds (trim/dedupe/cap) so
|
|
260
|
+
* minor LLM slips (e.g. a 19-char header or trailing "Other" option) never waste
|
|
261
|
+
* a flagship round-trip. Returns null if fewer than 1 usable question remains.
|
|
262
|
+
*/
|
|
263
|
+
export function sanitizeDelegatedQuestions(raw: unknown): QuestionData[] | null {
|
|
264
|
+
if (!Array.isArray(raw)) return null;
|
|
265
|
+
const out: QuestionData[] = [];
|
|
266
|
+
const seenQ = new Set<string>();
|
|
267
|
+
for (const entry of raw) {
|
|
268
|
+
if (out.length >= MAX_QUESTIONS) break;
|
|
269
|
+
if (!entry || typeof entry !== "object") continue;
|
|
270
|
+
const rec = entry as Record<string, unknown>;
|
|
271
|
+
const question = typeof rec.question === "string" ? normalizeText(rec.question) : "";
|
|
272
|
+
if (!question || seenQ.has(question.toLowerCase())) continue;
|
|
273
|
+
const rawHeader = typeof rec.header === "string" ? normalizeText(rec.header) : "";
|
|
274
|
+
const header = truncate(rawHeader || `Q${out.length + 1}`, MAX_HEADER_LENGTH);
|
|
275
|
+
const multiSelect = Boolean(rec.multiSelect);
|
|
276
|
+
if (!Array.isArray(rec.options)) continue;
|
|
277
|
+
|
|
278
|
+
const options: OptionData[] = [];
|
|
279
|
+
const seenLabels = new Set<string>();
|
|
280
|
+
for (const rawOpt of rec.options) {
|
|
281
|
+
if (options.length >= MAX_OPTIONS) break;
|
|
282
|
+
if (!rawOpt || typeof rawOpt !== "object") continue;
|
|
283
|
+
const o = rawOpt as Record<string, unknown>;
|
|
284
|
+
const rawLabel = typeof o.label === "string" ? normalizeText(o.label) : "";
|
|
285
|
+
if (!rawLabel) continue;
|
|
286
|
+
const label = truncate(rawLabel, MAX_LABEL_LENGTH);
|
|
287
|
+
const key = label.toLowerCase();
|
|
288
|
+
if (RESERVED_LABEL_SET.has(key) || seenLabels.has(key)) continue;
|
|
289
|
+
const description = typeof o.description === "string" ? normalizeText(o.description) : "";
|
|
290
|
+
const rawPreview = typeof o.preview === "string" ? o.preview.replace(/\r\n/g, "\n").replace(/\r/g, "").trimEnd() : "";
|
|
291
|
+
options.push({
|
|
292
|
+
label,
|
|
293
|
+
description: description || label,
|
|
294
|
+
...(!multiSelect && rawPreview ? { preview: rawPreview } : {}),
|
|
295
|
+
});
|
|
296
|
+
seenLabels.add(key);
|
|
297
|
+
}
|
|
298
|
+
if (options.length < MIN_OPTIONS) continue;
|
|
299
|
+
seenQ.add(question.toLowerCase());
|
|
300
|
+
out.push({ question, header, options, multiSelect });
|
|
301
|
+
}
|
|
302
|
+
return out.length > 0 ? out : null;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
export type ValidationResult = { ok: true } | { ok: false; error: string; message: string };
|
|
306
|
+
|
|
307
|
+
export function validateQuestions(questions: readonly QuestionData[]): ValidationResult {
|
|
308
|
+
if (questions.length === 0) {
|
|
309
|
+
return { ok: false, error: "no_questions", message: "Error: At least one question is required." };
|
|
310
|
+
}
|
|
311
|
+
if (questions.length > MAX_QUESTIONS) {
|
|
312
|
+
return { ok: false, error: "too_many_questions", message: `Error: At most ${MAX_QUESTIONS} questions are allowed.` };
|
|
313
|
+
}
|
|
314
|
+
const seenQuestions = new Set<string>();
|
|
315
|
+
for (const q of questions) {
|
|
316
|
+
if (!q.question) {
|
|
317
|
+
return { ok: false, error: "empty_question", message: "Error: Question text must not be empty." };
|
|
318
|
+
}
|
|
319
|
+
const qKey = q.question.toLowerCase();
|
|
320
|
+
if (seenQuestions.has(qKey)) {
|
|
321
|
+
return { ok: false, error: "duplicate_question", message: "Error: Question text must be unique." };
|
|
322
|
+
}
|
|
323
|
+
seenQuestions.add(qKey);
|
|
324
|
+
if (!q.header || q.header.length > MAX_HEADER_LENGTH) {
|
|
325
|
+
return { ok: false, error: "invalid_header", message: `Error: Header must be 1-${MAX_HEADER_LENGTH} characters.` };
|
|
326
|
+
}
|
|
327
|
+
if (q.options.length < MIN_OPTIONS || q.options.length > MAX_OPTIONS) {
|
|
328
|
+
return {
|
|
329
|
+
ok: false,
|
|
330
|
+
error: "invalid_option_count",
|
|
331
|
+
message: `Error: Each question requires ${MIN_OPTIONS}-${MAX_OPTIONS} options.`,
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
const seenLabels = new Set<string>();
|
|
335
|
+
for (const o of q.options) {
|
|
336
|
+
if (!o.label || o.label.length > MAX_LABEL_LENGTH) {
|
|
337
|
+
return { ok: false, error: "invalid_label", message: `Error: Option label must be 1-${MAX_LABEL_LENGTH} characters.` };
|
|
338
|
+
}
|
|
339
|
+
const lKey = o.label.toLowerCase();
|
|
340
|
+
if (RESERVED_LABEL_SET.has(lKey)) {
|
|
341
|
+
return {
|
|
342
|
+
ok: false,
|
|
343
|
+
error: "reserved_label",
|
|
344
|
+
message: `Error: Option label "${o.label}" is reserved (${RESERVED_LABELS.join(", ")}).`,
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
if (seenLabels.has(lKey)) {
|
|
348
|
+
return { ok: false, error: "duplicate_option_label", message: "Error: Option labels must be unique within a question." };
|
|
349
|
+
}
|
|
350
|
+
seenLabels.add(lKey);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
return { ok: true };
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
// ---------------------------------------------------------------------------
|
|
357
|
+
// Smart question delegation (rubric prompt, context slice, JSON extraction)
|
|
358
|
+
// ---------------------------------------------------------------------------
|
|
359
|
+
|
|
360
|
+
export interface SessionSnippet {
|
|
361
|
+
lastUserMessage: string;
|
|
362
|
+
recentTurns: string[];
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
const MAX_SNIPPET_CHARS = 3_600;
|
|
366
|
+
const MAX_TURN_CHARS = 700;
|
|
367
|
+
|
|
368
|
+
function extractTextFromContent(content: unknown): string {
|
|
369
|
+
if (typeof content === "string") return content.trim();
|
|
370
|
+
if (!Array.isArray(content)) return "";
|
|
371
|
+
const parts: string[] = [];
|
|
372
|
+
for (const block of content) {
|
|
373
|
+
if (!block || typeof block !== "object") continue;
|
|
374
|
+
const rec = block as { type?: unknown; text?: unknown };
|
|
375
|
+
if (rec.type === "text" && typeof rec.text === "string" && rec.text.trim()) {
|
|
376
|
+
parts.push(rec.text.trim());
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
return parts.join("\n").trim();
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/**
|
|
383
|
+
* Pull a compact, token-efficient slice of the active session branch so the custom
|
|
384
|
+
* question model understands intent and user language without shipping full tool dumps.
|
|
385
|
+
*/
|
|
386
|
+
export function extractSessionSnippet(entries: readonly unknown[]): SessionSnippet {
|
|
387
|
+
const turns: { role: "user" | "assistant" | "summary"; text: string }[] = [];
|
|
388
|
+
for (const entry of entries) {
|
|
389
|
+
if (!entry || typeof entry !== "object") continue;
|
|
390
|
+
const e = entry as Record<string, unknown>;
|
|
391
|
+
if (e.type === "compaction" && typeof e.summary === "string" && e.summary.trim()) {
|
|
392
|
+
turns.push({ role: "summary", text: e.summary.trim() });
|
|
393
|
+
continue;
|
|
394
|
+
}
|
|
395
|
+
const msg = (e.type === "message" ? e.message : e) as Record<string, unknown> | undefined;
|
|
396
|
+
if (!msg || typeof msg !== "object") continue;
|
|
397
|
+
const role = msg.role;
|
|
398
|
+
if (role !== "user" && role !== "assistant") continue;
|
|
399
|
+
const text = extractTextFromContent(msg.content);
|
|
400
|
+
if (!text) continue;
|
|
401
|
+
turns.push({ role, text });
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
let lastUserMessage = "";
|
|
405
|
+
for (let i = turns.length - 1; i >= 0; i--) {
|
|
406
|
+
if (turns[i]!.role === "user") {
|
|
407
|
+
lastUserMessage = truncate(turns[i]!.text, 1_200);
|
|
408
|
+
break;
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
const picked: string[] = [];
|
|
413
|
+
let budget = MAX_SNIPPET_CHARS;
|
|
414
|
+
for (let i = turns.length - 1; i >= 0 && picked.length < 6; i--) {
|
|
415
|
+
const item = turns[i]!;
|
|
416
|
+
const clipped = truncate(item.text, MAX_TURN_CHARS);
|
|
417
|
+
const line = `[${item.role}] ${clipped}`;
|
|
418
|
+
if (line.length > budget && picked.length > 0) break;
|
|
419
|
+
picked.unshift(line);
|
|
420
|
+
budget -= line.length;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
return { lastUserMessage, recentTurns: picked };
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
export const SMART_QUESTION_SYSTEM_PROMPT = `You are a Principal Engineering Question Architect helping a coding agent clarify ambiguous requirements before executing.
|
|
427
|
+
|
|
428
|
+
Return ONLY a valid JSON object matching:
|
|
429
|
+
{
|
|
430
|
+
"questions": [
|
|
431
|
+
{
|
|
432
|
+
"header": "<=16 chars tab chip",
|
|
433
|
+
"question": "Clear, concrete decision question ending with '?'",
|
|
434
|
+
"multiSelect": false,
|
|
435
|
+
"options": [
|
|
436
|
+
{
|
|
437
|
+
"label": "Concise choice (1-5 words, <=60 chars) — first option ends with ' (Recommended)' when a clear best default exists",
|
|
438
|
+
"description": "Concrete consequence, trade-off, or scope impact (1 short sentence).",
|
|
439
|
+
"preview": "Optional compact markdown/ASCII/code snippet ONLY when visual comparison clarifies the choice (single-select only)"
|
|
440
|
+
}
|
|
441
|
+
]
|
|
442
|
+
}
|
|
443
|
+
]
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
Quality rubric (strictly enforce):
|
|
447
|
+
1. High-leverage only: ask ONLY decisions that materially change code, UX, architecture, or scope. Drop trivial, redundant, or already-answered questions. Prefer 1-3 sharp questions over 4 padded ones (max 4).
|
|
448
|
+
2. Mutually exclusive & concrete options: 2-4 options per question. Every description must state a real trade-off or consequence — never vague filler like "Standard approach".
|
|
449
|
+
3. Recommend the best default: put the strongest pragmatic default first and append "(Recommended)" to its label.
|
|
450
|
+
4. No reserved labels: NEVER include "Other", "Type something.", or "Next" — the UI appends custom text input automatically.
|
|
451
|
+
5. Smart preview: include \`preview\` only when contrasting concrete layouts, schemas, APIs, or code shapes (never on multiSelect).
|
|
452
|
+
6. Match the user's language: write questions, headers, labels, and descriptions in the same language as the user's latest message, while keeping code, file paths, commands, and technical terms verbatim in English.
|
|
453
|
+
7. Output raw JSON only — no prose before or after.`;
|
|
454
|
+
|
|
455
|
+
export function buildDelegationUserPrompt(
|
|
456
|
+
action: "refine" | "author",
|
|
457
|
+
params: AskUserParams,
|
|
458
|
+
snippet: SessionSnippet,
|
|
459
|
+
): string {
|
|
460
|
+
const sections: string[] = [];
|
|
461
|
+
if (snippet.recentTurns.length > 0) {
|
|
462
|
+
sections.push(`## Recent conversation\n${snippet.recentTurns.join("\n\n")}`);
|
|
463
|
+
}
|
|
464
|
+
if (params.goal?.trim()) {
|
|
465
|
+
sections.push(`## Goal\n${params.goal.trim()}`);
|
|
466
|
+
}
|
|
467
|
+
if (params.context?.trim()) {
|
|
468
|
+
sections.push(`## Additional context\n${params.context.trim()}`);
|
|
469
|
+
}
|
|
470
|
+
if (params.ambiguities && params.ambiguities.length > 0) {
|
|
471
|
+
sections.push(`## Unresolved ambiguities\n${params.ambiguities.map((a, i) => `${i + 1}. ${a.trim()}`).join("\n")}`);
|
|
472
|
+
}
|
|
473
|
+
if (action === "refine" && params.questions && params.questions.length > 0) {
|
|
474
|
+
sections.push(
|
|
475
|
+
`## Draft questions from active model (audit, deduplicate, sharpen trade-offs, fix formatting)\n${JSON.stringify(
|
|
476
|
+
{ questions: params.questions },
|
|
477
|
+
null,
|
|
478
|
+
2,
|
|
479
|
+
)}`,
|
|
480
|
+
);
|
|
481
|
+
}
|
|
482
|
+
sections.push(
|
|
483
|
+
action === "refine"
|
|
484
|
+
? "Task: Upgrade the draft questions against the rubric. Remove weak/redundant questions, tighten labels/headers, sharpen trade-offs, and match the user's language."
|
|
485
|
+
: "Task: Author 1-4 high-leverage structured questions resolving the ambiguities above, matching the user's language.",
|
|
486
|
+
);
|
|
487
|
+
return sections.join("\n\n");
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/** Extract JSON object from raw model output (handles optional markdown code fences or leading text). */
|
|
491
|
+
export function parseDelegatedResponse(text: string): QuestionData[] | null {
|
|
492
|
+
const trimmed = text.trim();
|
|
493
|
+
if (!trimmed) return null;
|
|
494
|
+
|
|
495
|
+
const candidates: string[] = [trimmed];
|
|
496
|
+
const fenced = trimmed.match(/```(?:json)?\s*([\s\S]*?)```/i);
|
|
497
|
+
if (fenced?.[1]) candidates.unshift(fenced[1].trim());
|
|
498
|
+
|
|
499
|
+
const firstBrace = trimmed.indexOf("{");
|
|
500
|
+
const lastBrace = trimmed.lastIndexOf("}");
|
|
501
|
+
if (firstBrace >= 0 && lastBrace > firstBrace) {
|
|
502
|
+
candidates.push(trimmed.slice(firstBrace, lastBrace + 1));
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
for (const candidate of candidates) {
|
|
506
|
+
try {
|
|
507
|
+
const parsed = JSON.parse(candidate) as unknown;
|
|
508
|
+
if (Array.isArray(parsed)) {
|
|
509
|
+
const sanitized = sanitizeDelegatedQuestions(parsed);
|
|
510
|
+
if (sanitized) return sanitized;
|
|
511
|
+
} else if (parsed && typeof parsed === "object" && "questions" in parsed) {
|
|
512
|
+
const sanitized = sanitizeDelegatedQuestions((parsed as { questions: unknown }).questions);
|
|
513
|
+
if (sanitized) return sanitized;
|
|
514
|
+
}
|
|
515
|
+
} catch {
|
|
516
|
+
// Try next candidate
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
return null;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
// ---------------------------------------------------------------------------
|
|
523
|
+
// Response envelope formatting
|
|
524
|
+
// ---------------------------------------------------------------------------
|
|
525
|
+
|
|
526
|
+
export const DECLINE_MESSAGE = "User declined to answer questions";
|
|
527
|
+
export const ENVELOPE_PREFIX = "User has answered your questions:";
|
|
528
|
+
export const ENVELOPE_SUFFIX = "You can now continue with the user's answers in mind.";
|
|
529
|
+
|
|
530
|
+
export function formatAnswerValue(a: QuestionAnswer): string {
|
|
531
|
+
if (a.kind === "multi") {
|
|
532
|
+
const parts = [...(a.selected ?? [])];
|
|
533
|
+
if (a.answer && a.answer.trim()) parts.push(a.answer.trim());
|
|
534
|
+
return parts.join(", ");
|
|
535
|
+
}
|
|
536
|
+
return a.answer ?? "";
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
export function buildQuestionnaireResponse(
|
|
540
|
+
result: QuestionnaireResult | null | undefined,
|
|
541
|
+
questions: readonly QuestionData[],
|
|
542
|
+
): { content: [{ type: "text"; text: string }]; details: QuestionnaireResult } {
|
|
543
|
+
if (!result || result.cancelled) {
|
|
544
|
+
const details: QuestionnaireResult = {
|
|
545
|
+
answers: result?.answers ?? [],
|
|
546
|
+
cancelled: true,
|
|
547
|
+
...(result?.delegatedModel ? { delegatedModel: result.delegatedModel } : {}),
|
|
548
|
+
...(result?.delegatedAction ? { delegatedAction: result.delegatedAction } : {}),
|
|
549
|
+
...(result?.error ? { error: result.error } : {}),
|
|
550
|
+
};
|
|
551
|
+
return {
|
|
552
|
+
content: [{ type: "text", text: DECLINE_MESSAGE }],
|
|
553
|
+
details,
|
|
554
|
+
};
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
const segments: string[] = [];
|
|
558
|
+
const unanswered: number[] = [];
|
|
559
|
+
for (let i = 0; i < questions.length; i++) {
|
|
560
|
+
const a = result.answers.find((x) => x.questionIndex === i);
|
|
561
|
+
if (!a) {
|
|
562
|
+
unanswered.push(i);
|
|
563
|
+
continue;
|
|
564
|
+
}
|
|
565
|
+
const val = formatAnswerValue(a);
|
|
566
|
+
if (!val) {
|
|
567
|
+
unanswered.push(i);
|
|
568
|
+
continue;
|
|
569
|
+
}
|
|
570
|
+
const parts = [`"${a.question}"="${val}"`];
|
|
571
|
+
if (a.preview && a.preview.length > 0) parts.push(`selected preview: ${a.preview}`);
|
|
572
|
+
segments.push(`${parts.join(". ")}.`);
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
if (segments.length === 0) {
|
|
576
|
+
return {
|
|
577
|
+
content: [{ type: "text", text: DECLINE_MESSAGE }],
|
|
578
|
+
details: { ...result, cancelled: true },
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
if (unanswered.length > 0) {
|
|
583
|
+
const names = unanswered.map((i) => `"${questions[i]?.question ?? ""}"`).join(", ");
|
|
584
|
+
segments.push(`unanswered: ${names}.`);
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
const details: QuestionnaireResult = {
|
|
588
|
+
...result,
|
|
589
|
+
...(unanswered.length > 0 ? { unanswered } : {}),
|
|
590
|
+
};
|
|
591
|
+
|
|
592
|
+
return {
|
|
593
|
+
content: [{ type: "text", text: `${ENVELOPE_PREFIX} ${segments.join(" ")} ${ENVELOPE_SUFFIX}` }],
|
|
594
|
+
details,
|
|
595
|
+
};
|
|
596
|
+
}
|