@juicesharp/rpiv-ask-user-question 2.13.3 → 2.13.5

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.
@@ -26,7 +26,7 @@ import {
26
26
  import { type DialogUI, hasDialogUI, runRpcQuestionnaire } from "./rpc-fallback.js";
27
27
  import { displayLabel, t } from "./state/i18n-bridge.js";
28
28
  import { sentinelsToAppend } from "./state/row-intent.js";
29
- import { normalizeQuestionParams } from "./tool/normalize-params.js";
29
+ import { normalizeQuestionParams, prepareQuestionArguments } from "./tool/normalize-params.js";
30
30
  import { buildQuestionnaireResponse, buildToolResult } from "./tool/response-envelope.js";
31
31
  import {
32
32
  MAX_OPTIONS,
@@ -381,6 +381,8 @@ export function registerAskUserQuestionTool(pi: ExtensionAPI): void {
381
381
  promptSnippet: guidance.promptSnippet ?? DEFAULT_PROMPT_SNIPPET,
382
382
  promptGuidelines: guidance.promptGuidelines ?? DEFAULT_PROMPT_GUIDELINES,
383
383
  parameters: QuestionParamsSchema,
384
+ // Undo double-encoded nested arguments before Pi validates them (#244).
385
+ prepareArguments: prepareQuestionArguments,
384
386
 
385
387
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
386
388
  // Line-terminator normalization runs once here, ahead of validation, so
@@ -84,6 +84,7 @@ code. The `content[0].text` string is written for the model, not for a log.
84
84
  }>,
85
85
  cancelled: boolean,
86
86
  globalNote?: string, // Submit-tab note; present even when cancelled is true
87
+ unanswered?: number[], // indexes of questions left blank on a partial submit
87
88
  error?: QuestionnaireError, // one of the codes above
88
89
  }
89
90
  }
@@ -100,7 +101,9 @@ question is blank.
100
101
 
101
102
  Cancelling, and any result with neither answer segments nor a global note, both collapse
102
103
  to the single string `User declined to answer questions` so the model sees one canonical
103
- signal. Partial submission is allowed: unanswered questions simply contribute no segment.
104
+ signal. Partial submission is allowed: the questions left blank are named in an
105
+ `unanswered: "<question>", …` segment after the answers (before any global note), and their
106
+ indexes are in `details.unanswered`. Both are absent when every question is answered.
104
107
  A cancelled result always reads as the decline in text; its note, if any, survives only
105
108
  in `details.globalNote`.
106
109
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juicesharp/rpiv-ask-user-question",
3
- "version": "2.13.3",
3
+ "version": "2.13.5",
4
4
  "description": "Pi extension. A structured questionnaire the model can put to you when it would otherwise guess, with typed options instead of free-form replies.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -99,6 +99,6 @@
99
99
  }
100
100
  },
101
101
  "dependencies": {
102
- "@juicesharp/rpiv-config": "^2.13.3"
102
+ "@juicesharp/rpiv-config": "^2.13.5"
103
103
  }
104
104
  }
package/rpc-fallback.ts CHANGED
@@ -81,8 +81,8 @@ function buildPreviewBlock(question: QuestionData): string {
81
81
  }
82
82
 
83
83
  /**
84
- * Walk the questionnaire one native dialog at a time. Dismissing any dialog
85
- * (the primitive resolves `undefined`) cancels the whole questionnaire —
84
+ * Walk the questionnaire one native dialog at a time. Dismissing a question's
85
+ * dialog (the primitive resolves `undefined`) cancels the whole questionnaire —
86
86
  * mirroring Esc in the TUI — and the shared envelope emits DECLINE. A
87
87
  * `QuestionAnswer` is produced per question otherwise, so the envelope is
88
88
  * identical to the TUI path's.
@@ -99,7 +99,19 @@ export async function runRpcQuestionnaire(ui: DialogUI, params: QuestionParams):
99
99
  return { answers, cancelled: false };
100
100
  }
101
101
 
102
- /** `undefined` means the user dismissed the dialog (cancel the questionnaire). */
102
+ /**
103
+ * `undefined` means the user dismissed the option dialog (cancel the questionnaire).
104
+ *
105
+ * Hosts return the chosen option line, but some also let the user type a reply in
106
+ * place of picking (T3 Code's "Type your own answer" box) and return that text
107
+ * (#299). A reply is therefore read as: an offered line → that option; a bare
108
+ * number → that option (hosts that return an index); a reply equal to an option
109
+ * label → that option; any other non-empty text → the user's own answer, verbatim
110
+ * — never a dismissal, and never "option N plus discarded text". Cancelling the
111
+ * "Type something." follow-up returns to the options instead of cancelling the
112
+ * whole questionnaire (#142), and that input repeats the option list so the user
113
+ * can refer to it while typing (#194).
114
+ */
103
115
  async function askSingleSelect(
104
116
  ui: DialogUI,
105
117
  q: QuestionData,
@@ -108,26 +120,46 @@ async function askSingleSelect(
108
120
  ): Promise<QuestionAnswer | undefined> {
109
121
  const options = q.options.map(formatOptionLine);
110
122
  options.push(`${q.options.length + 1}. ${displayLabel("other")}`);
111
- const chosen = await ui.select(`${header}${q.question}${buildPreviewBlock(q)}`, options);
112
- if (chosen == null) return undefined;
113
- const idx = parseIndex(chosen, options.length);
114
- // A host returning something outside the offered list is indistinguishable
115
- // from a dismissal — treat it as one rather than fabricate an answer.
116
- if (idx == null) return undefined;
117
- if (idx < q.options.length) {
118
- const o = q.options[idx];
119
- return {
120
- questionIndex,
121
- question: q.question,
122
- kind: "option",
123
- answer: o.label,
124
- preview: o.preview && o.preview.length > 0 ? o.preview : undefined,
125
- };
123
+ const title = `${header}${q.question}${buildPreviewBlock(q)}`;
124
+ for (;;) {
125
+ const chosen = await ui.select(title, options);
126
+ if (chosen == null) return undefined;
127
+ const reply = chosen.trim();
128
+ if (reply.length === 0) return undefined;
129
+ const idx = resolveSingleSelectReply(chosen, reply, options, q);
130
+ if (idx === undefined) return { questionIndex, question: q.question, kind: "custom", answer: reply };
131
+ if (idx < q.options.length) {
132
+ const o = q.options[idx];
133
+ return {
134
+ questionIndex,
135
+ question: q.question,
136
+ kind: "option",
137
+ answer: o.label,
138
+ preview: o.preview && o.preview.length > 0 ? o.preview : undefined,
139
+ };
140
+ }
141
+ // "Type something." sentinel → free-text follow-up; cancelling it goes back to the options.
142
+ const typed = await ui.input(
143
+ `${header}${q.question}\n\n${q.options.map(formatOptionLine).join("\n")}\n\n${t("rpc.custom_answer_title", CUSTOM_ANSWER_TITLE)}`,
144
+ "",
145
+ );
146
+ if (typed == null) continue;
147
+ return { questionIndex, question: q.question, kind: "custom", answer: typed };
126
148
  }
127
- // "Type something." sentinel → free-text follow-up.
128
- const typed = await ui.input(`${header}${q.question}\n\n${t("rpc.custom_answer_title", CUSTOM_ANSWER_TITLE)}`, "");
129
- if (typed == null) return undefined;
130
- return { questionIndex, question: q.question, kind: "custom", answer: typed };
149
+ }
150
+
151
+ /** Option index for a select reply, or `undefined` when the reply is the user's own text. */
152
+ function resolveSingleSelectReply(
153
+ chosen: string,
154
+ reply: string,
155
+ lines: readonly string[],
156
+ q: QuestionData,
157
+ ): number | undefined {
158
+ const line = lines.indexOf(chosen);
159
+ if (line >= 0) return line;
160
+ if (/^\d+\.?$/.test(reply)) return parseIndex(reply, lines.length) ?? undefined;
161
+ const label = q.options.findIndex((o) => o.label === reply);
162
+ return label >= 0 ? label : undefined;
131
163
  }
132
164
 
133
165
  /** `undefined` means the user dismissed the dialog (cancel the questionnaire). */
@@ -54,3 +54,49 @@ export function normalizeQuestionParams(params: QuestionParams): QuestionParams
54
54
  })),
55
55
  };
56
56
  }
57
+
58
+ /**
59
+ * Pi's `prepareArguments` hook: undo double-encoded tool arguments before schema
60
+ * validation (#244). Some tool-call parsers (vLLM/LiteLLM-served GLM/Qwen-class
61
+ * models) intermittently emit nested structures as JSON strings — `questions` itself,
62
+ * or its elements (`questions.0: must be object`). Only a string at an array/object
63
+ * position is decoded, and only when it parses to the expected shape; anything else is
64
+ * passed through untouched so validation still reports the real problem. The same
65
+ * applies one level down to `options`. Well-formed arguments are returned as-is.
66
+ */
67
+ export function prepareQuestionArguments(args: unknown): QuestionParams {
68
+ if (!isRecord(args)) return args as QuestionParams;
69
+ const questions = decodeArray(args.questions);
70
+ if (!Array.isArray(questions)) return args as QuestionParams;
71
+ const decoded = questions.map((q) => {
72
+ const question = decodeObject(q);
73
+ if (!isRecord(question)) return question;
74
+ const options = decodeArray(question.options);
75
+ return Array.isArray(options) ? { ...question, options: options.map(decodeObject) } : question;
76
+ });
77
+ return { ...args, questions: decoded } as unknown as QuestionParams;
78
+ }
79
+
80
+ function isRecord(value: unknown): value is Record<string, unknown> {
81
+ return typeof value === "object" && value !== null && !Array.isArray(value);
82
+ }
83
+
84
+ /** A JSON string holding an array → that array; anything else unchanged. */
85
+ function decodeArray(value: unknown): unknown {
86
+ const parsed = typeof value === "string" ? parseJson(value) : value;
87
+ return Array.isArray(parsed) ? parsed : value;
88
+ }
89
+
90
+ /** A JSON string holding an object → that object; anything else unchanged. */
91
+ function decodeObject(value: unknown): unknown {
92
+ const parsed = typeof value === "string" ? parseJson(value) : value;
93
+ return isRecord(parsed) ? parsed : value;
94
+ }
95
+
96
+ function parseJson(text: string): unknown {
97
+ try {
98
+ return JSON.parse(text);
99
+ } catch {
100
+ return undefined;
101
+ }
102
+ }
@@ -11,7 +11,10 @@ export const ENVELOPE_SUFFIX = "You can now continue with the user's answers in
11
11
  * so the model sees a single canonical "didn't answer" signal regardless of why.
12
12
  * "No segments" means no answers AND no global note — the `global note:` segment is
13
13
  * pushed before the zero-segments check, so a note-bearing submit with zero answers
14
- * still yields the answered envelope.
14
+ * still yields the answered envelope. A partial submit names the questions left blank
15
+ * in an `unanswered:` segment (and `details.unanswered`, their indexes) so the model can
16
+ * tell "not decided yet" from "settled" (#291); it never counts as an answer, and a fully
17
+ * answered result stays byte-identical.
15
18
  */
16
19
  export function buildQuestionnaireResponse(result: QuestionnaireResult | null | undefined, params: QuestionParams) {
17
20
  if (!result || result.cancelled) {
@@ -24,19 +27,27 @@ export function buildQuestionnaireResponse(result: QuestionnaireResult | null |
24
27
  });
25
28
  }
26
29
  const segments: string[] = [];
30
+ const unanswered: number[] = [];
27
31
  for (let i = 0; i < params.questions.length; i++) {
28
32
  const a = result.answers.find((x) => x.questionIndex === i);
29
33
  if (a) segments.push(buildAnswerSegment(a));
34
+ else unanswered.push(i);
30
35
  }
31
- // Global note rides after the per-question segments: raw multiline echo (no
32
- // reformatting), trailing period mirroring `buildAnswerSegment`'s shape.
33
- if (result.globalNote && result.globalNote.length > 0) {
34
- segments.push(`global note: ${result.globalNote}.`);
35
- }
36
- if (segments.length === 0) {
36
+ const hasGlobalNote = result.globalNote !== undefined && result.globalNote.length > 0;
37
+ if (segments.length === 0 && !hasGlobalNote) {
37
38
  return buildToolResult(DECLINE_MESSAGE, { answers: result.answers, cancelled: true });
38
39
  }
39
- return buildToolResult(`${ENVELOPE_PREFIX} ${segments.join(" ")} ${ENVELOPE_SUFFIX}`, result);
40
+ if (unanswered.length > 0) segments.push(buildUnansweredSegment(unanswered, params));
41
+ // Global note rides after the per-question segments: raw multiline echo (no
42
+ // reformatting), trailing period mirroring `buildAnswerSegment`'s shape.
43
+ if (hasGlobalNote) segments.push(`global note: ${result.globalNote}.`);
44
+ const details = unanswered.length > 0 ? { ...result, unanswered } : result;
45
+ return buildToolResult(`${ENVELOPE_PREFIX} ${segments.join(" ")} ${ENVELOPE_SUFFIX}`, details);
46
+ }
47
+
48
+ /** `unanswered: "<question>", "<question>".` — the questions shown but left blank on a partial submit. */
49
+ export function buildUnansweredSegment(indexes: readonly number[], params: QuestionParams): string {
50
+ return `unanswered: ${indexes.map((i) => `"${params.questions[i]?.question}"`).join(", ")}.`;
40
51
  }
41
52
 
42
53
  /**
package/tool/types.ts CHANGED
@@ -146,6 +146,12 @@ export interface QuestionnaireResult {
146
146
  * byte-identical (`!("globalNote" in result)` holds).
147
147
  */
148
148
  globalNote?: string;
149
+ /**
150
+ * Indexes of the questions left blank on a partial submit (#291), set only by the
151
+ * envelope builder on an answered result — never present when every question is
152
+ * answered or the result is a decline, so those stay byte-identical.
153
+ */
154
+ unanswered?: number[];
149
155
  error?: QuestionnaireError;
150
156
  }
151
157