pi-cc-extensions 0.8.8 → 0.8.10

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.
Files changed (60) hide show
  1. package/README.md +24 -6
  2. package/extensions/agent-autocomplete.ts +11 -16
  3. package/extensions/ask-user-question/LICENSE +21 -0
  4. package/extensions/ask-user-question/README.md +63 -0
  5. package/extensions/ask-user-question/ask-user-question.ts +266 -0
  6. package/extensions/ask-user-question/config.ts +79 -0
  7. package/extensions/ask-user-question/events.ts +55 -0
  8. package/extensions/ask-user-question/index.ts +17 -0
  9. package/extensions/ask-user-question/reconcile.ts +47 -0
  10. package/extensions/ask-user-question/rpc-fallback.ts +172 -0
  11. package/extensions/ask-user-question/state/build-questionnaire.ts +302 -0
  12. package/extensions/ask-user-question/state/dialog-height.ts +16 -0
  13. package/extensions/ask-user-question/state/key-router.ts +291 -0
  14. package/extensions/ask-user-question/state/questionnaire-session.ts +193 -0
  15. package/extensions/ask-user-question/state/row-intent.ts +143 -0
  16. package/extensions/ask-user-question/state/selectors/contract.ts +24 -0
  17. package/extensions/ask-user-question/state/selectors/derivations.ts +40 -0
  18. package/extensions/ask-user-question/state/selectors/focus.ts +17 -0
  19. package/extensions/ask-user-question/state/selectors/projections.ts +102 -0
  20. package/extensions/ask-user-question/state/state-reducer.ts +299 -0
  21. package/extensions/ask-user-question/state/state.ts +49 -0
  22. package/extensions/ask-user-question/tool/format-answer.ts +29 -0
  23. package/extensions/ask-user-question/tool/response-envelope.ts +50 -0
  24. package/extensions/ask-user-question/tool/types.ts +149 -0
  25. package/extensions/ask-user-question/tool/validate-questionnaire.ts +64 -0
  26. package/extensions/ask-user-question/view/component-binding.ts +45 -0
  27. package/extensions/ask-user-question/view/components/inline-input.ts +109 -0
  28. package/extensions/ask-user-question/view/components/multi-select-view.ts +198 -0
  29. package/extensions/ask-user-question/view/components/option-list-view.ts +77 -0
  30. package/extensions/ask-user-question/view/components/preview/markdown-content-cache.ts +76 -0
  31. package/extensions/ask-user-question/view/components/preview/preview-block-renderer.ts +114 -0
  32. package/extensions/ask-user-question/view/components/preview/preview-box-renderer.ts +86 -0
  33. package/extensions/ask-user-question/view/components/preview/preview-layout-decider.ts +212 -0
  34. package/extensions/ask-user-question/view/components/preview/preview-pane.ts +230 -0
  35. package/extensions/ask-user-question/view/components/submit-picker.ts +66 -0
  36. package/extensions/ask-user-question/view/components/tab-bar.ts +57 -0
  37. package/extensions/ask-user-question/view/components/wrapping-select.ts +307 -0
  38. package/extensions/ask-user-question/view/dialog-builder.ts +225 -0
  39. package/extensions/ask-user-question/view/props-adapter.ts +123 -0
  40. package/extensions/ask-user-question/view/stateful-view.ts +24 -0
  41. package/extensions/ask-user-question/view/tab-components.ts +16 -0
  42. package/extensions/ask-user-question/view/tab-content-strategy.ts +264 -0
  43. package/extensions/claude-code-style.ts +1658 -1485
  44. package/extensions/compact-style.ts +120 -43
  45. package/extensions/context.ts +502 -394
  46. package/extensions/session-reference-core.ts +8 -3
  47. package/extensions/session-reference.ts +475 -448
  48. package/extensions/tool-diff/ATTRIBUTION.md +28 -0
  49. package/extensions/tool-diff/ansi-utils.ts +113 -0
  50. package/extensions/tool-diff/diff-presentation.ts +70 -0
  51. package/extensions/tool-diff/diff-renderer.ts +2827 -0
  52. package/extensions/tool-diff/index.ts +106 -0
  53. package/extensions/tool-diff/line-width-safety.ts +91 -0
  54. package/extensions/tool-diff/render-utils.ts +5 -0
  55. package/extensions/tool-diff/types.ts +20 -0
  56. package/extensions/tool-diff/write-display-utils.ts +29 -0
  57. package/extensions/tool-diff/write-execution.ts +113 -0
  58. package/extensions/tool-result-sanitize.ts +4 -4
  59. package/package.json +64 -55
  60. package/themes/github-dark-default.json +91 -91
@@ -0,0 +1,17 @@
1
+ import type { ActiveView } from "../../view/stateful-view.js";
2
+
3
+ /**
4
+ * Discriminated focus selector — single source of truth for "which view owns
5
+ * focus this tick?" Priority order matches the dispatcher cascade
6
+ * (`key-router.ts`) and the reducer's defensive clears (`state-reducer.ts`).
7
+ *
8
+ * Priority: notes > submit > options.
9
+ */
10
+ export function selectActiveView(
11
+ state: { notesVisible: boolean; currentTab: number },
12
+ totalQuestions: number,
13
+ ): ActiveView {
14
+ if (state.notesVisible) return "notes";
15
+ if (state.currentTab === totalQuestions) return "submit";
16
+ return "options";
17
+ }
@@ -0,0 +1,102 @@
1
+ import {
2
+ MULTI_SUBMIT_LABEL,
3
+ type MultiSelectViewProps,
4
+ } from "../../view/components/multi-select-view.js";
5
+ import type { OptionListViewProps } from "../../view/components/option-list-view.js";
6
+ import type { PreviewPaneProps } from "../../view/components/preview/preview-pane.js";
7
+ import type { SubmitPickerProps } from "../../view/components/submit-picker.js";
8
+ import type { TabBarProps } from "../../view/components/tab-bar.js";
9
+ import type { DialogProps } from "../../view/dialog-builder.js";
10
+ import { ROW_INTENT_META } from "../row-intent.js";
11
+ import type { GlobalSelector, PerTabSelector } from "./contract.js";
12
+ import { selectConfirmedIndicator } from "./derivations.js";
13
+
14
+ export const selectMultiSelectProps: PerTabSelector<MultiSelectViewProps> = (state, ctx) => {
15
+ const question = ctx.questions[ctx.i];
16
+ if (!question) {
17
+ return {
18
+ rows: [],
19
+ other: {
20
+ active: false,
21
+ inputMode: false,
22
+ inputBuffer: ctx.inputBuffer,
23
+ inputCursorOffset: ctx.inputCursorOffset,
24
+ },
25
+ nextActive: false,
26
+ nextLabel: ROW_INTENT_META.next.label,
27
+ };
28
+ }
29
+ const focused = ctx.activeView === "options";
30
+ const rows: { checked: boolean; active: boolean }[] = [];
31
+ for (let i = 0; i < question.options.length; i++) {
32
+ rows.push({
33
+ checked: state.multiSelectChecked.has(i),
34
+ active: focused && i === state.optionIndex,
35
+ });
36
+ }
37
+ const otherActive = focused && state.optionIndex === question.options.length;
38
+ const nextActive = focused && state.optionIndex === question.options.length + 1;
39
+ const isLastQuestion = ctx.i === ctx.questions.length - 1;
40
+ const nextLabel = isLastQuestion ? MULTI_SUBMIT_LABEL : ROW_INTENT_META.next.label;
41
+ return {
42
+ rows,
43
+ other: {
44
+ active: otherActive,
45
+ inputMode: state.inputMode,
46
+ inputBuffer: ctx.inputBuffer,
47
+ inputCursorOffset: ctx.inputCursorOffset,
48
+ },
49
+ nextActive,
50
+ nextLabel,
51
+ };
52
+ };
53
+
54
+ export const selectOptionListProps: PerTabSelector<OptionListViewProps> = (state, ctx) => {
55
+ const items = ctx.itemsByTab[ctx.i] ?? [];
56
+ const focused = ctx.activeView === "options";
57
+ const confirmed = selectConfirmedIndicator(ctx.questions, state.currentTab, state.answers, items);
58
+ return {
59
+ selectedIndex: state.optionIndex,
60
+ focused,
61
+ inputBuffer: ctx.inputBuffer,
62
+ inputCursorOffset: ctx.inputCursorOffset,
63
+ ...(confirmed ? { confirmed } : {}),
64
+ };
65
+ };
66
+
67
+ export const selectSubmitPickerProps: GlobalSelector<SubmitPickerProps> = (state, ctx) => {
68
+ const focused = ctx.activeView === "submit";
69
+ return {
70
+ rows: [
71
+ { active: focused && state.submitChoiceIndex === 0 },
72
+ { active: focused && state.submitChoiceIndex === 1 },
73
+ ],
74
+ };
75
+ };
76
+
77
+ export const selectPreviewPaneProps: PerTabSelector<PreviewPaneProps> = (state, ctx) => ({
78
+ notesVisible: state.notesVisible,
79
+ selectedIndex: state.optionIndex,
80
+ focused: ctx.activeView === "options",
81
+ inputMode: state.inputMode,
82
+ });
83
+
84
+ export const selectTabBarProps: GlobalSelector<TabBarProps> = (state, ctx) => {
85
+ const tabs = ctx.questions.map((q, i) => ({
86
+ label: q.header && q.header.length > 0 ? q.header : `Q${i + 1}`,
87
+ answered: state.answers.has(i),
88
+ active: i === state.currentTab,
89
+ }));
90
+ return {
91
+ tabs,
92
+ submit: {
93
+ active: state.currentTab === ctx.questions.length,
94
+ allAnswered: state.answers.size === ctx.questions.length && ctx.questions.length > 0,
95
+ },
96
+ };
97
+ };
98
+
99
+ export const selectDialogProps: GlobalSelector<DialogProps> = (state, ctx) => ({
100
+ state,
101
+ activePreviewPane: ctx.activePreviewPane,
102
+ });
@@ -0,0 +1,299 @@
1
+ import type { QuestionAnswer, QuestionData, QuestionnaireResult } from "../tool/types.js";
2
+ import type { WrappingSelectItem } from "../view/components/wrapping-select.js";
3
+ import type { QuestionnaireAction } from "./key-router.js";
4
+ import { ROW_INTENT_META } from "./row-intent.js";
5
+ import type { QuestionnaireState } from "./state.js";
6
+
7
+ /** Session-lifetime constants. No live-component reads — peripheral values live on canonical state. */
8
+ export interface ApplyContext {
9
+ questions: readonly QuestionData[];
10
+ itemsByTab: ReadonlyArray<readonly WrappingSelectItem[]>;
11
+ }
12
+
13
+ /**
14
+ * Declarative side-effects emitted by `reduce`. The runtime executes them after
15
+ * committing the new state, then asks the props-adapter to re-project. Closed set —
16
+ * adding an effect requires updating both the union AND the runtime's `runEffect` switch
17
+ * (compiler-enforced exhaustive). No string-keyed escape hatch.
18
+ */
19
+ export type Effect =
20
+ | { kind: "set_input_buffer"; value: string }
21
+ | { kind: "clear_input_buffer" }
22
+ | { kind: "set_notes_value"; value: string }
23
+ | { kind: "set_notes_focused"; focused: boolean }
24
+ | { kind: "forward_notes_keystroke"; data: string }
25
+ | { kind: "done"; result: QuestionnaireResult };
26
+
27
+ export interface ApplyResult {
28
+ state: QuestionnaireState;
29
+ effects: readonly Effect[];
30
+ }
31
+
32
+ function orderedAnswers(
33
+ state: QuestionnaireState,
34
+ questions: readonly QuestionData[],
35
+ ): QuestionAnswer[] {
36
+ const out: QuestionAnswer[] = [];
37
+ for (let i = 0; i < questions.length; i++) {
38
+ const a = state.answers.get(i);
39
+ if (a) out.push(a);
40
+ }
41
+ return out;
42
+ }
43
+
44
+ function syncMultiSelectFromAnswers(
45
+ answers: ReadonlyMap<number, QuestionAnswer>,
46
+ questions: readonly QuestionData[],
47
+ tab: number,
48
+ ): ReadonlySet<number> {
49
+ const q = questions[tab];
50
+ if (!q?.multiSelect) return new Set();
51
+ const saved = answers.get(tab);
52
+ const labels = saved?.selected ?? [];
53
+ const indices = new Set<number>();
54
+ for (let i = 0; i < q.options.length; i++) {
55
+ if (labels.includes(q.options[i]!.label)) indices.add(i);
56
+ }
57
+ return indices;
58
+ }
59
+
60
+ function persistMultiSelectAnswer(
61
+ state: QuestionnaireState,
62
+ ctx: ApplyContext,
63
+ ): ReadonlyMap<number, QuestionAnswer> {
64
+ const q = ctx.questions[state.currentTab];
65
+ if (!q?.multiSelect) return state.answers;
66
+ const selected: string[] = [];
67
+ for (let i = 0; i < q.options.length; i++) {
68
+ if (state.multiSelectChecked.has(i)) selected.push(q.options[i]!.label);
69
+ }
70
+ const out = new Map(state.answers);
71
+ if (selected.length === 0) {
72
+ out.delete(state.currentTab);
73
+ return out;
74
+ }
75
+ const pendingNotes = state.notesByTab.get(state.currentTab);
76
+ out.set(state.currentTab, {
77
+ questionIndex: state.currentTab,
78
+ question: q.question,
79
+ kind: "multi",
80
+ answer: null,
81
+ selected,
82
+ ...(pendingNotes && pendingNotes.length > 0 ? { notes: pendingNotes } : {}),
83
+ });
84
+ return out;
85
+ }
86
+
87
+ /**
88
+ * Note text to seed the editor/draft with for a tab. The in-flight side-band store
89
+ * (`notesByTab`) is authoritative — before an option is confirmed the note lives ONLY
90
+ * there; `answer.notes` is a mirror written on exit/confirm.
91
+ */
92
+ function notesValueFor(state: QuestionnaireState, tab: number): string {
93
+ return state.notesByTab.get(tab) ?? state.answers.get(tab)?.notes ?? "";
94
+ }
95
+
96
+ function switchTabResult(
97
+ state: QuestionnaireState,
98
+ nextTab: number,
99
+ ctx: ApplyContext,
100
+ ): ApplyResult {
101
+ const notesValue = notesValueFor(state, nextTab);
102
+ const transitioned: QuestionnaireState = {
103
+ ...state,
104
+ currentTab: nextTab,
105
+ optionIndex: 0,
106
+ inputMode: false,
107
+ notesVisible: false,
108
+ submitChoiceIndex: 0,
109
+ multiSelectChecked: syncMultiSelectFromAnswers(state.answers, ctx.questions, nextTab),
110
+ notesDraft: notesValue,
111
+ };
112
+ return {
113
+ state: transitioned,
114
+ effects: [
115
+ { kind: "set_notes_focused", focused: false },
116
+ { kind: "set_notes_value", value: notesValue },
117
+ ],
118
+ };
119
+ }
120
+
121
+ function doneFor(state: QuestionnaireState, ctx: ApplyContext, cancelled: boolean): ApplyResult {
122
+ const result: QuestionnaireResult = { answers: orderedAnswers(state, ctx.questions), cancelled };
123
+ return { state, effects: [{ kind: "done", result }] };
124
+ }
125
+
126
+ /**
127
+ * Per-kind handler signature: action payload narrows to the matching union member
128
+ * via `Extract`, so handlers consume fully-typed actions without `as` casts.
129
+ */
130
+ type Handler<K extends QuestionnaireAction["kind"]> = (
131
+ state: QuestionnaireState,
132
+ action: Extract<QuestionnaireAction, { kind: K }>,
133
+ ctx: ApplyContext,
134
+ ) => ApplyResult;
135
+
136
+ const navHandler: Handler<"nav"> = (state, action, ctx) => {
137
+ const items = ctx.itemsByTab[state.currentTab] ?? [];
138
+ const item = items[action.nextIndex];
139
+ const inputMode = item ? ROW_INTENT_META[item.kind].activatesInputMode : false;
140
+ const next = { ...state, optionIndex: action.nextIndex, inputMode };
141
+ if (!inputMode) {
142
+ return { state: next, effects: [{ kind: "clear_input_buffer" }] };
143
+ }
144
+ const prior = state.answers.get(state.currentTab);
145
+ if (prior?.kind === "custom" && typeof prior.answer === "string") {
146
+ return { state: next, effects: [{ kind: "set_input_buffer", value: prior.answer }] };
147
+ }
148
+ return { state: next, effects: [] };
149
+ };
150
+
151
+ const tabSwitchHandler: Handler<"tab_switch"> = (state, action, ctx) =>
152
+ switchTabResult(state, action.nextTab, ctx);
153
+
154
+ const confirmHandler: Handler<"confirm"> = (state, action, ctx) => {
155
+ let answer = action.answer;
156
+ if (answer.kind === "option" && answer.answer) {
157
+ const q = ctx.questions[answer.questionIndex];
158
+ const matched = q?.options.find((o) => o.label === answer.answer);
159
+ if (matched?.preview && matched.preview.length > 0) {
160
+ answer = { ...answer, preview: matched.preview };
161
+ }
162
+ }
163
+ const pendingNotes = state.notesByTab.get(answer.questionIndex);
164
+ if (pendingNotes && pendingNotes.length > 0) {
165
+ answer = { ...answer, notes: pendingNotes };
166
+ }
167
+ const answers = new Map(state.answers);
168
+ answers.set(answer.questionIndex, answer);
169
+ // Custom free-text on a multi-select tab is mutually exclusive with checkbox selections:
170
+ // clear the checked set immediately so [✔] glyphs vanish on Enter. (A custom answer
171
+ // carries no `selected` array, so syncMultiSelectFromAnswers keeps it empty on tab-back.)
172
+ const isCustomMulti =
173
+ answer.kind === "custom" && ctx.questions[answer.questionIndex]?.multiSelect === true;
174
+ const next: QuestionnaireState = {
175
+ ...state,
176
+ answers,
177
+ ...(isCustomMulti ? { multiSelectChecked: new Set<number>() } : {}),
178
+ };
179
+ if (action.autoAdvanceTab !== undefined) return switchTabResult(next, action.autoAdvanceTab, ctx);
180
+ return doneFor(next, ctx, false);
181
+ };
182
+
183
+ const toggleHandler: Handler<"toggle"> = (state, action, ctx) => {
184
+ const checked = new Set(state.multiSelectChecked);
185
+ if (checked.has(action.index)) checked.delete(action.index);
186
+ else checked.add(action.index);
187
+ const intermediate: QuestionnaireState = { ...state, multiSelectChecked: checked };
188
+ const answers = persistMultiSelectAnswer(intermediate, ctx);
189
+ return { state: { ...intermediate, answers }, effects: [] };
190
+ };
191
+
192
+ const multiConfirmHandler: Handler<"multi_confirm"> = (state, action, ctx) => {
193
+ const q = ctx.questions[state.currentTab];
194
+ if (!q) return { state, effects: [] };
195
+ const pendingNotes = state.notesByTab.get(state.currentTab);
196
+ const answers = new Map(state.answers);
197
+ answers.set(state.currentTab, {
198
+ questionIndex: state.currentTab,
199
+ question: q.question,
200
+ kind: "multi",
201
+ answer: null,
202
+ selected: action.selected,
203
+ ...(pendingNotes && pendingNotes.length > 0 ? { notes: pendingNotes } : {}),
204
+ });
205
+ const synced: QuestionnaireState = {
206
+ ...state,
207
+ answers,
208
+ multiSelectChecked: syncMultiSelectFromAnswers(answers, ctx.questions, state.currentTab),
209
+ };
210
+ if (action.autoAdvanceTab !== undefined)
211
+ return switchTabResult(synced, action.autoAdvanceTab, ctx);
212
+ return doneFor(synced, ctx, false);
213
+ };
214
+
215
+ const notesEnterHandler: Handler<"notes_enter"> = (state, _action, _ctx) => {
216
+ const value = notesValueFor(state, state.currentTab);
217
+ return {
218
+ state: { ...state, notesVisible: true, notesDraft: value },
219
+ effects: [
220
+ { kind: "set_notes_value", value },
221
+ { kind: "set_notes_focused", focused: true },
222
+ ],
223
+ };
224
+ };
225
+
226
+ const notesExitHandler: Handler<"notes_exit"> = (state, _action, _ctx) => {
227
+ const trimmed = state.notesDraft.trim();
228
+ const notes = new Map(state.notesByTab);
229
+ const answers = new Map(state.answers);
230
+ if (trimmed.length === 0) {
231
+ notes.delete(state.currentTab);
232
+ const prev = answers.get(state.currentTab);
233
+ if (prev?.notes) {
234
+ const stripped = { ...prev };
235
+ delete (stripped as { notes?: string }).notes;
236
+ answers.set(state.currentTab, stripped);
237
+ }
238
+ } else {
239
+ notes.set(state.currentTab, trimmed);
240
+ const prev = answers.get(state.currentTab);
241
+ if (prev) answers.set(state.currentTab, { ...prev, notes: trimmed });
242
+ }
243
+ return {
244
+ state: { ...state, notesByTab: notes, answers, notesVisible: false },
245
+ effects: [{ kind: "set_notes_focused", focused: false }],
246
+ };
247
+ };
248
+
249
+ const cancelHandler: Handler<"cancel"> = (s, _a, c) => doneFor(s, c, true);
250
+ const submitHandler: Handler<"submit"> = (s, _a, c) => doneFor(s, c, false);
251
+ const submitNavHandler: Handler<"submit_nav"> = (s, a, _c) => ({
252
+ state: { ...s, submitChoiceIndex: a.nextIndex },
253
+ effects: [],
254
+ });
255
+ const notesForwardHandler: Handler<"notes_forward"> = (s, a, _c) => ({
256
+ state: s,
257
+ effects: [{ kind: "forward_notes_keystroke", data: a.data }],
258
+ });
259
+ const toggleCollapsedHandler: Handler<"toggle_collapsed"> = (s, _a, _c) => ({
260
+ state: { ...s, collapsed: !s.collapsed },
261
+ effects: [],
262
+ });
263
+ const ignoreHandler: Handler<"ignore"> = (s, _a, _c) => ({ state: s, effects: [] });
264
+
265
+ /**
266
+ * Compile-time-exhaustive dispatch table. `{ [K in Kind]: Handler<K> }` requires
267
+ * an entry per union member — adding a new `QuestionnaireAction` variant fails to
268
+ * compile here until a handler is registered, mirroring the `Record<RowKind, …>`
269
+ * pattern used by `ROW_INTENT_META`.
270
+ */
271
+ const HANDLERS: { [K in QuestionnaireAction["kind"]]: Handler<K> } = {
272
+ nav: navHandler,
273
+ tab_switch: tabSwitchHandler,
274
+ confirm: confirmHandler,
275
+ toggle: toggleHandler,
276
+ multi_confirm: multiConfirmHandler,
277
+ cancel: cancelHandler,
278
+ notes_enter: notesEnterHandler,
279
+ notes_exit: notesExitHandler,
280
+ notes_forward: notesForwardHandler,
281
+ submit: submitHandler,
282
+ submit_nav: submitNavHandler,
283
+ toggle_collapsed: toggleCollapsedHandler,
284
+ ignore: ignoreHandler,
285
+ };
286
+
287
+ /**
288
+ * Pure reducer: (state, action, ctx) → (state, Effect[]). Mirrors `rpiv-todo`'s `applyTaskMutation`.
289
+ * Delegates to `HANDLERS` — per-kind handlers above are pure, named, and individually testable.
290
+ * `ignore` is also handled outside the reducer by `handleIgnoreInline` in the runtime fast path.
291
+ */
292
+ export function reduce(
293
+ state: QuestionnaireState,
294
+ action: QuestionnaireAction,
295
+ ctx: ApplyContext,
296
+ ): ApplyResult {
297
+ const handler = HANDLERS[action.kind] as Handler<typeof action.kind>;
298
+ return handler(state, action as never, ctx);
299
+ }
@@ -0,0 +1,49 @@
1
+ import type { QuestionAnswer, QuestionData } from "../tool/types.js";
2
+ import type { WrappingSelectItem } from "../view/components/wrapping-select.js";
3
+
4
+ /**
5
+ * Canonical state for the questionnaire dialog. Single source of truth — both the
6
+ * dispatcher (`routeKey`) and the view layer read this same shape.
7
+ */
8
+ export interface QuestionnaireState {
9
+ currentTab: number;
10
+ optionIndex: number;
11
+ inputMode: boolean;
12
+ notesVisible: boolean;
13
+ answers: ReadonlyMap<number, QuestionAnswer>;
14
+ multiSelectChecked: ReadonlySet<number>;
15
+ /**
16
+ * Pre-answer notes side-band, keyed by tab index. Decoupled from `answers` so adding
17
+ * notes does NOT mark a question answered (the Submit-tab missing-check would falsely
18
+ * pass otherwise). Merged into the answer at confirm time.
19
+ */
20
+ notesByTab: ReadonlyMap<number, string>;
21
+ /** Focused row in the Submit-tab picker (0 = Submit, 1 = Cancel). Reset on tab switch. */
22
+ submitChoiceIndex: number;
23
+ /** Canonical mirror of the in-flight notes editor; runtime mirrors after `forward_notes_keystroke`. */
24
+ notesDraft: string;
25
+ /**
26
+ * Collapsed mode: the questionnaire shrinks to one focused hint row in the
27
+ * temporary editor slot, returning the remaining space to the transcript.
28
+ */
29
+ collapsed: boolean;
30
+ }
31
+
32
+ /**
33
+ * Per-tick context the dispatcher needs alongside canonical state. Held separately
34
+ * because `keybindings` / `inputBuffer` must never reach view setProps consumers.
35
+ */
36
+ export interface QuestionnaireRuntime {
37
+ keybindings: { matches(data: string, name: string): boolean };
38
+ inputBuffer: string;
39
+ questions: readonly QuestionData[];
40
+ isMulti: boolean;
41
+ currentItem: WrappingSelectItem | undefined;
42
+ items: readonly WrappingSelectItem[];
43
+ /**
44
+ * Key spec for the collapse/expand shortcut, e.g. `"ctrl+]"` or `"alt+o"`. Resolved
45
+ * from `AskUserQuestionConfig.collapseKey` (or the package default). When `"off"`,
46
+ * the collapse shortcut is disabled.
47
+ */
48
+ collapseKey: string;
49
+ }
@@ -0,0 +1,29 @@
1
+ import type { QuestionAnswer } from "./types.js";
2
+
3
+ /**
4
+ * Placeholder for empty / null answer text. Used uniformly across both variants — the
5
+ * earlier `(no answer)` fallback in the dialog summary was accidental drift; tests pin
6
+ * `(no input)` only.
7
+ */
8
+ export const NO_INPUT_PLACEHOLDER = "(no input)";
9
+
10
+ export type FormatAnswerVariant = "summary" | "envelope";
11
+
12
+ /**
13
+ * Format a `QuestionAnswer` to its scalar string form. `variant` is currently unused
14
+ * across all branches (the chat branch that once distinguished `envelope` from
15
+ * `summary` has been removed); it is retained on the signature for stability.
16
+ * The `kind: "custom"` empty-string handling and the option fallback both unify on
17
+ * `NO_INPUT_PLACEHOLDER`. Switch is exhaustive — non-`void` return enforces every
18
+ * variant is handled.
19
+ */
20
+ export function formatAnswerScalar(a: QuestionAnswer, _variant: FormatAnswerVariant): string {
21
+ switch (a.kind) {
22
+ case "multi":
23
+ return a.selected && a.selected.length > 0 ? a.selected.join(", ") : NO_INPUT_PLACEHOLDER;
24
+ case "custom":
25
+ return a.answer && a.answer.length > 0 ? a.answer : NO_INPUT_PLACEHOLDER;
26
+ case "option":
27
+ return a.answer ?? NO_INPUT_PLACEHOLDER;
28
+ }
29
+ }
@@ -0,0 +1,50 @@
1
+ import { formatAnswerScalar } from "./format-answer.js";
2
+ import type { QuestionAnswer, QuestionnaireResult, QuestionParams } from "./types.js";
3
+
4
+ export const DECLINE_MESSAGE = "User declined to answer questions";
5
+ export const ENVELOPE_PREFIX = "User has answered your questions:";
6
+ export const ENVELOPE_SUFFIX = "You can now continue with the user's answers in mind.";
7
+
8
+ /**
9
+ * Map a `QuestionnaireResult` (or null/cancelled) to the LLM-facing tool envelope.
10
+ * Pure of `(result, params)`; cancelled and "no segments" both fall to `DECLINE_MESSAGE`
11
+ * so the model sees a single canonical "didn't answer" signal regardless of why.
12
+ */
13
+ export function buildQuestionnaireResponse(
14
+ result: QuestionnaireResult | null | undefined,
15
+ params: QuestionParams,
16
+ ) {
17
+ if (!result || result.cancelled) {
18
+ return buildToolResult(DECLINE_MESSAGE, {
19
+ answers: result?.answers ?? [],
20
+ cancelled: true,
21
+ });
22
+ }
23
+ const segments: string[] = [];
24
+ for (let i = 0; i < params.questions.length; i++) {
25
+ const a = result.answers.find((x) => x.questionIndex === i);
26
+ if (a) segments.push(buildAnswerSegment(a));
27
+ }
28
+ if (segments.length === 0) {
29
+ return buildToolResult(DECLINE_MESSAGE, { answers: result.answers, cancelled: true });
30
+ }
31
+ return buildToolResult(`${ENVELOPE_PREFIX} ${segments.join(" ")} ${ENVELOPE_SUFFIX}`, result);
32
+ }
33
+
34
+ /**
35
+ * Format a single answer segment for the envelope. Pure of `a`. The `"Q"="A"` shape and
36
+ * the optional `selected preview:` / `user notes:` suffixes are pinned by envelope tests.
37
+ */
38
+ export function buildAnswerSegment(a: QuestionAnswer): string {
39
+ const parts: string[] = [`"${a.question}"="${formatAnswerScalar(a, "envelope")}"`];
40
+ if (a.preview && a.preview.length > 0) parts.push(`selected preview: ${a.preview}`);
41
+ if (a.notes && a.notes.length > 0) parts.push(`user notes: ${a.notes}`);
42
+ return `${parts.join(". ")}.`;
43
+ }
44
+
45
+ export function buildToolResult(text: string, details: QuestionnaireResult) {
46
+ return {
47
+ content: [{ type: "text" as const, text }],
48
+ details,
49
+ };
50
+ }