vc-extras 0.1.0 → 0.1.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.
Files changed (249) hide show
  1. package/README.md +128 -71
  2. package/agent-install.mjs +159 -0
  3. package/agents/tester.md +23 -23
  4. package/install-extras.mjs +41 -109
  5. package/install-menu.mjs +22 -43
  6. package/install-skills.mjs +112 -112
  7. package/package.json +72 -28
  8. package/plugin-registry.mjs +73 -0
  9. package/plugins/config-ui/index.ts +159 -159
  10. package/plugins/config-ui/lib/arguments.mjs +24 -24
  11. package/plugins/config-ui/lib/documents.mjs +67 -67
  12. package/plugins/config-ui/lib/frontmatter.mjs +91 -91
  13. package/plugins/config-ui/lib/open.mjs +16 -16
  14. package/plugins/config-ui/lib/ownership.mjs +99 -99
  15. package/plugins/config-ui/lib/page.mjs +11 -11
  16. package/plugins/config-ui/lib/patch.mjs +35 -35
  17. package/plugins/config-ui/lib/paths.mjs +14 -14
  18. package/plugins/config-ui/lib/plugin-fields.mjs +86 -86
  19. package/plugins/config-ui/lib/plugin-validation.mjs +28 -28
  20. package/plugins/config-ui/lib/redaction.mjs +8 -8
  21. package/plugins/config-ui/lib/registry.mjs +282 -282
  22. package/plugins/config-ui/lib/secrets.mjs +44 -44
  23. package/plugins/config-ui/lib/server.mjs +250 -250
  24. package/plugins/config-ui/lib/sources.mjs +96 -96
  25. package/plugins/config-ui/lib/state.mjs +156 -156
  26. package/plugins/config-ui/lib/themes.mjs +113 -113
  27. package/plugins/config-ui/lib/writer.mjs +690 -690
  28. package/plugins/config-ui/project-local-owner.ts +106 -106
  29. package/plugins/config-ui/vc-extras.plugin.json +13 -0
  30. package/plugins/config-ui/web/app.mjs +997 -997
  31. package/plugins/config-ui/web/index.html +342 -342
  32. package/plugins/pi-blackhole/vc-extras.plugin.json +12 -0
  33. package/plugins/pi-btw/vc-extras.plugin.json +12 -0
  34. package/plugins/pi-claude-code/vc-extras.plugin.json +12 -0
  35. package/plugins/pi-fff/vc-extras.plugin.json +12 -0
  36. package/plugins/pi-jev-auto-mode/vc-extras.plugin.json +12 -0
  37. package/plugins/pi-mcp-adapter/vc-extras.plugin.json +12 -0
  38. package/plugins/pi-web-access/vc-extras.plugin.json +12 -0
  39. package/plugins/vc-ask/claude-hook.mjs +37 -0
  40. package/plugins/vc-ask/codex-native.mjs +28 -0
  41. package/plugins/vc-ask/host-channel.mjs +75 -0
  42. package/plugins/vc-ask/index.ts +57 -0
  43. package/plugins/vc-ask/native-questions.mjs +33 -0
  44. package/plugins/vc-ask/package.json +10 -0
  45. package/plugins/vc-ask/payload.ts +170 -0
  46. package/plugins/vc-ask/questionnaire/LICENSE.ask-user-question +21 -0
  47. package/plugins/vc-ask/questionnaire/UPSTREAM.md +104 -0
  48. package/plugins/vc-ask/questionnaire/answer-channel.ts +135 -0
  49. package/plugins/vc-ask/questionnaire/config.ts +180 -0
  50. package/plugins/vc-ask/questionnaire/events.ts +154 -0
  51. package/plugins/vc-ask/questionnaire/execute.ts +688 -0
  52. package/plugins/vc-ask/questionnaire/i18n.ts +73 -0
  53. package/plugins/vc-ask/questionnaire/inline-entry.ts +312 -0
  54. package/plugins/vc-ask/questionnaire/locales/de.json +43 -0
  55. package/plugins/vc-ask/questionnaire/locales/en.json +42 -0
  56. package/plugins/vc-ask/questionnaire/locales/es.json +43 -0
  57. package/plugins/vc-ask/questionnaire/locales/fr.json +43 -0
  58. package/plugins/vc-ask/questionnaire/locales/pt-BR.json +43 -0
  59. package/plugins/vc-ask/questionnaire/locales/pt.json +43 -0
  60. package/plugins/vc-ask/questionnaire/locales/ru.json +43 -0
  61. package/plugins/vc-ask/questionnaire/locales/uk.json +43 -0
  62. package/plugins/vc-ask/questionnaire/locales/zh.json +46 -0
  63. package/plugins/vc-ask/questionnaire/presentation.ts +11 -0
  64. package/plugins/vc-ask/questionnaire/question-preview.ts +6 -0
  65. package/plugins/vc-ask/questionnaire/rpc.ts +221 -0
  66. package/plugins/vc-ask/questionnaire/session-timeout.ts +67 -0
  67. package/plugins/vc-ask/questionnaire/state/build-questionnaire.ts +144 -0
  68. package/plugins/vc-ask/questionnaire/state/external-editor.ts +62 -0
  69. package/plugins/vc-ask/questionnaire/state/geometry.ts +131 -0
  70. package/plugins/vc-ask/questionnaire/state/key-router.ts +382 -0
  71. package/plugins/vc-ask/questionnaire/state/panel-router.ts +32 -0
  72. package/plugins/vc-ask/questionnaire/state/questionnaire-session.ts +642 -0
  73. package/plugins/vc-ask/questionnaire/state/row-intent.ts +143 -0
  74. package/plugins/vc-ask/questionnaire/state/selectors/contract.ts +24 -0
  75. package/plugins/vc-ask/questionnaire/state/selectors/derivations.ts +40 -0
  76. package/plugins/vc-ask/questionnaire/state/selectors/focus.ts +17 -0
  77. package/plugins/vc-ask/questionnaire/state/selectors/projections.ts +99 -0
  78. package/plugins/vc-ask/questionnaire/state/state-reducer.ts +455 -0
  79. package/plugins/vc-ask/questionnaire/state/state.ts +90 -0
  80. package/plugins/vc-ask/questionnaire/state/vertical.ts +158 -0
  81. package/plugins/vc-ask/questionnaire/timeout.ts +59 -0
  82. package/plugins/vc-ask/questionnaire/tool/external-answer.ts +103 -0
  83. package/plugins/vc-ask/questionnaire/tool/format-answer.ts +24 -0
  84. package/plugins/vc-ask/questionnaire/tool/normalize-params.ts +37 -0
  85. package/plugins/vc-ask/questionnaire/tool/response-envelope.ts +75 -0
  86. package/plugins/vc-ask/questionnaire/tool/types.ts +74 -0
  87. package/plugins/vc-ask/questionnaire/tool/validate-questionnaire.ts +75 -0
  88. package/plugins/vc-ask/questionnaire/view/card-theme.ts +245 -0
  89. package/plugins/vc-ask/questionnaire/view/components/inline-input.ts +66 -0
  90. package/plugins/vc-ask/questionnaire/view/components/multi-select-view.ts +177 -0
  91. package/plugins/vc-ask/questionnaire/view/components/option-list-view.ts +65 -0
  92. package/plugins/vc-ask/questionnaire/view/components/preview/markdown-content-cache.ts +101 -0
  93. package/plugins/vc-ask/questionnaire/view/components/preview/preview-block-renderer.ts +130 -0
  94. package/plugins/vc-ask/questionnaire/view/components/preview/preview-box-renderer.ts +86 -0
  95. package/plugins/vc-ask/questionnaire/view/components/preview/preview-layout-decider.ts +204 -0
  96. package/plugins/vc-ask/questionnaire/view/components/preview/preview-pane.ts +257 -0
  97. package/plugins/vc-ask/questionnaire/view/components/submit-picker.ts +65 -0
  98. package/plugins/vc-ask/questionnaire/view/components/tab-bar.ts +57 -0
  99. package/plugins/vc-ask/questionnaire/view/components/wrapping-select.ts +269 -0
  100. package/plugins/vc-ask/questionnaire/view/dialog-builder.ts +319 -0
  101. package/plugins/vc-ask/questionnaire/view/document-theme.ts +53 -0
  102. package/plugins/vc-ask/questionnaire/view/document-view.ts +306 -0
  103. package/plugins/vc-ask/questionnaire/view/panel-chrome.ts +133 -0
  104. package/plugins/vc-ask/questionnaire/view/props-adapter.ts +77 -0
  105. package/plugins/vc-ask/questionnaire/view/stateful-view.ts +24 -0
  106. package/plugins/vc-ask/questionnaire/view/tab-components.ts +16 -0
  107. package/plugins/vc-ask/questionnaire/view/tab-content-strategy.ts +280 -0
  108. package/plugins/vc-ask/questionnaire/view/vertical-view.ts +218 -0
  109. package/plugins/vc-ask/user-input-events.ts +34 -0
  110. package/plugins/vc-ask/vc-extras.plugin.json +18 -0
  111. package/plugins/vc-footer/agents/claude-code/adapter.mjs +29 -0
  112. package/plugins/vc-footer/agents/claude-code/cli.mjs +23 -0
  113. package/plugins/vc-footer/agents/claude-code/renderer.mjs +1 -0
  114. package/plugins/vc-footer/agents/claude-code/types.d.ts +38 -0
  115. package/plugins/vc-footer/agents/codex/adapter.mjs +13 -0
  116. package/plugins/vc-footer/agents/codex/mcp.mjs +45 -0
  117. package/plugins/vc-footer/agents/codex/native.mjs +19 -0
  118. package/plugins/vc-footer/agents/codex/renderer.mjs +2 -0
  119. package/plugins/vc-footer/agents/pi/adapter.mjs +23 -0
  120. package/plugins/vc-footer/agents/pi/index.js +84 -0
  121. package/plugins/vc-footer/agents/pi/project-local-owner.mjs +97 -0
  122. package/plugins/vc-footer/agents/pi/renderer.mjs +5 -0
  123. package/plugins/vc-footer/core/data.mjs +218 -0
  124. package/plugins/vc-footer/core/render.mjs +291 -0
  125. package/plugins/vc-footer/core/types.d.ts +29 -0
  126. package/plugins/vc-footer/package.json +22 -0
  127. package/plugins/vc-footer/vc-extras.plugin.json +32 -0
  128. package/skills/animate/LICENSE +21 -21
  129. package/skills/animate/RECIPES.md +324 -324
  130. package/skills/animate/SKILL.md +208 -208
  131. package/skills/animate/UPSTREAM.md +19 -19
  132. package/skills/animation-performance/LICENSE +21 -21
  133. package/skills/animation-performance/SKILL.md +223 -223
  134. package/skills/animation-performance/UPSTREAM.md +19 -19
  135. package/skills/answer-me-with-html/SKILL.md +174 -174
  136. package/skills/answer-me-with-html/scripts/am.mjs +12896 -12896
  137. package/skills/apple-design/LICENSE +21 -21
  138. package/skills/apple-design/SKILL.md +291 -291
  139. package/skills/apple-design/UPSTREAM.md +19 -19
  140. package/skills/bad-smell/SKILL.md +44 -44
  141. package/skills/commit/SKILL.md +90 -90
  142. package/skills/emil-design-eng/LICENSE +21 -21
  143. package/skills/emil-design-eng/SKILL.md +677 -677
  144. package/skills/emil-design-eng/UPSTREAM.md +19 -19
  145. package/skills/find-the-truth/SKILL.md +38 -38
  146. package/skills/find-the-truth/references/trace-method.md +48 -48
  147. package/skills/find-the-truth/references/truth-method.md +39 -39
  148. package/skills/gestures/LICENSE +21 -21
  149. package/skills/gestures/SKILL.md +107 -107
  150. package/skills/gestures/UPSTREAM.md +19 -19
  151. package/skills/humanizer-zh/LICENSE +21 -21
  152. package/skills/humanizer-zh/SKILL.md +409 -409
  153. package/skills/humanizer-zh/UPSTREAM.md +7 -7
  154. package/skills/impeccable/LICENSE +191 -191
  155. package/skills/impeccable/NOTICE.md +11 -11
  156. package/skills/impeccable/SKILL.md +89 -89
  157. package/skills/impeccable/licenses/modern-screenshot-MIT.txt +8 -8
  158. package/skills/impeccable/licenses/platform-design-skills-MIT.txt +21 -21
  159. package/skills/impeccable/reference/adapt.md +318 -318
  160. package/skills/impeccable/reference/adapt.native.md +58 -58
  161. package/skills/impeccable/reference/android.md +46 -46
  162. package/skills/impeccable/reference/animate.md +89 -89
  163. package/skills/impeccable/reference/audit.md +139 -139
  164. package/skills/impeccable/reference/audit.native.md +139 -139
  165. package/skills/impeccable/reference/bolder.md +33 -33
  166. package/skills/impeccable/reference/clarify.md +94 -94
  167. package/skills/impeccable/reference/colorize.md +86 -86
  168. package/skills/impeccable/reference/component-review.md +63 -63
  169. package/skills/impeccable/reference/craft-floor.md +44 -44
  170. package/skills/impeccable/reference/craft.md +5 -5
  171. package/skills/impeccable/reference/critique.md +819 -819
  172. package/skills/impeccable/reference/degraded/asset-producer.md +41 -41
  173. package/skills/impeccable/reference/degraded/documenter.md +23 -23
  174. package/skills/impeccable/reference/degraded/finish-reviewer.md +37 -37
  175. package/skills/impeccable/reference/degraded/manual-edit-applier.md +92 -92
  176. package/skills/impeccable/reference/delight.md +70 -70
  177. package/skills/impeccable/reference/distill.md +111 -111
  178. package/skills/impeccable/reference/doctor.md +54 -54
  179. package/skills/impeccable/reference/document.md +416 -416
  180. package/skills/impeccable/reference/extract.md +69 -69
  181. package/skills/impeccable/reference/generate.md +101 -101
  182. package/skills/impeccable/reference/harden.md +362 -362
  183. package/skills/impeccable/reference/hooks.md +114 -114
  184. package/skills/impeccable/reference/init.md +131 -131
  185. package/skills/impeccable/reference/ios.md +51 -51
  186. package/skills/impeccable/reference/layout.md +84 -84
  187. package/skills/impeccable/reference/live-setup.md +104 -104
  188. package/skills/impeccable/reference/live.md +327 -327
  189. package/skills/impeccable/reference/mode-operate.md +21 -21
  190. package/skills/impeccable/reference/mode-persuade.md +19 -19
  191. package/skills/impeccable/reference/mode-read.md +21 -21
  192. package/skills/impeccable/reference/new-work.md +152 -152
  193. package/skills/impeccable/reference/onboard.md +234 -234
  194. package/skills/impeccable/reference/operate.md +61 -61
  195. package/skills/impeccable/reference/optimize.md +257 -257
  196. package/skills/impeccable/reference/overdrive.md +127 -127
  197. package/skills/impeccable/reference/polish.md +105 -105
  198. package/skills/impeccable/reference/quieter.md +99 -99
  199. package/skills/impeccable/reference/region-map.md +26 -26
  200. package/skills/impeccable/reference/routing.md +24 -24
  201. package/skills/impeccable/reference/shape.md +59 -59
  202. package/skills/impeccable/reference/typeset.md +90 -90
  203. package/skills/impeccable/reference/visualize.md +47 -47
  204. package/skills/impeccable/scripts/VERSION +1 -1
  205. package/skills/impeccable/scripts/command-metadata.json +98 -98
  206. package/skills/impeccable/scripts/data/font-index-failures.json +120 -120
  207. package/skills/impeccable/scripts/engine-checksums.txt +9 -9
  208. package/skills/impeccable/scripts/impeccable +249 -249
  209. package/skills/impeccable/scripts/impeccable.cmd +278 -278
  210. package/skills/impeccable/scripts/live-browser-dom.js +320 -320
  211. package/skills/impeccable/scripts/live-browser-ignores.js +246 -246
  212. package/skills/impeccable/scripts/live-browser-session.js +183 -183
  213. package/skills/impeccable/scripts/live-browser.js +13862 -13862
  214. package/skills/impeccable/scripts/modern-screenshot.umd.js +14 -14
  215. package/skills/improve-animations/AUDIT.md +115 -115
  216. package/skills/improve-animations/LICENSE +21 -21
  217. package/skills/improve-animations/PLAN-TEMPLATE.md +73 -73
  218. package/skills/improve-animations/SKILL.md +110 -110
  219. package/skills/improve-animations/UPSTREAM.md +19 -19
  220. package/skills/pick-ui-library/LICENSE +21 -21
  221. package/skills/pick-ui-library/SKILL.md +85 -85
  222. package/skills/pick-ui-library/UPSTREAM.md +19 -19
  223. package/skills/review-animations/LICENSE +21 -21
  224. package/skills/review-animations/SKILL.md +120 -120
  225. package/skills/review-animations/STANDARDS.md +187 -187
  226. package/skills/review-animations/UPSTREAM.md +19 -19
  227. package/skills/test/SKILL.md +29 -29
  228. package/skills/test/references/test-method.md +60 -60
  229. package/skills/write-doc/SKILL.md +115 -115
  230. package/skills/write-doc/examples/result-report.md +53 -53
  231. package/skills/write-doc/examples/task-summary.md +45 -45
  232. package/skills/write-doc/references/terminology.md +147 -147
  233. package/specs/ask-host-protocol-v1.md +58 -0
  234. package/specs/design-demo.md +1102 -1102
  235. package/specs/frontend-immersive.md +28 -28
  236. package/specs/plugin-install-v2.md +123 -0
  237. package/specs/plugin-install.md +38 -0
  238. package/specs/web-modes/explore.md +31 -31
  239. package/specs/web-modes/risk.md +15 -15
  240. package/specs/web-modes/verify.md +16 -16
  241. package/vc-extras.mjs +46 -62
  242. package/plugins/essrj/context.ts +0 -47
  243. package/plugins/essrj/data.ts +0 -190
  244. package/plugins/essrj/index.ts +0 -139
  245. package/plugins/essrj/package.json +0 -12
  246. package/plugins/essrj/project-local-owner.ts +0 -106
  247. package/plugins/essrj/render.ts +0 -217
  248. package/plugins/essrj/types.ts +0 -40
  249. package/plugins.json +0 -38
@@ -0,0 +1,158 @@
1
+ import { decodeKittyPrintable, Key, matchesKey } from "@earendil-works/pi-tui";
2
+ import type { QuestionAnswer, QuestionData } from "../tool/types.js";
3
+ import type { QuestionnaireRuntime, QuestionnaireState } from "./state.js";
4
+ import type { ApplyContext, ApplyResult } from "./state-reducer.js";
5
+
6
+ export type VerticalAction =
7
+ | { kind: "list_focus"; question: number; index?: number }
8
+ | { kind: "cancel_arm" }
9
+ | { kind: "list_edit"; input?: string }
10
+ | { kind: "list_save"; value: string; edited?: boolean; direction?: -1 | 1; review?: boolean; index?: number }
11
+ | { kind: "list_rollback" }
12
+ | { kind: "list_select"; advance?: boolean; index?: number }
13
+ | { kind: "list_defer" }
14
+ | { kind: "review_open" }
15
+ | { kind: "review_enter" }
16
+ | { kind: "review_focus"; index: number }
17
+ | { kind: "review_exit" };
18
+
19
+ // Legacy document-mode row IDs; form review uses question indexes followed by Submit.
20
+ export const REVIEW_ROWS = 3;
21
+ export const REVIEW_NOTE_ROW = 0;
22
+ export const REVIEW_SUBMIT_ROW = 1;
23
+ export const REVIEW_CANCEL_ROW = 2;
24
+
25
+ function answerFor(q: QuestionData, index: number, selected: number[]): QuestionAnswer {
26
+ const options = selected.map(i => q.options[i]!);
27
+ return { questionIndex: index, question: q.question, kind: q.multiSelect ? "multi" : "option",
28
+ answer: q.multiSelect ? null : options[0]!.label,
29
+ ...(q.multiSelect ? { selected: options.map(o => o.label) } : {}),
30
+ ...(!q.multiSelect && options[0]?.preview ? { preview: options[0].preview } : {}) };
31
+ }
32
+
33
+ export function recommendedState(state: QuestionnaireState, questions: readonly QuestionData[]): QuestionnaireState {
34
+ const answers = new Map(state.answers);
35
+ questions.forEach((q, i) => { if (q.recommended?.length) answers.set(i, answerFor(q, i, q.recommended)); });
36
+ return { ...state, answers };
37
+ }
38
+
39
+ function focus(state: QuestionnaireState, question: number, ctx: ApplyContext, index?: number): ApplyResult {
40
+ question = (question + ctx.questions.length) % ctx.questions.length;
41
+ const q = ctx.questions[question]!;
42
+ const answer = state.answers.get(question);
43
+ const selected = answer?.kind === "custom" ? q.options.length : q.options.findIndex(o => o.label === (answer?.selected?.[0] ?? answer?.answer));
44
+ const optionIndex = index ?? Math.max(0, selected);
45
+ return { state: { ...state, currentTab: question, optionIndex, verticalScreen: "list",
46
+ inputMode: optionIndex === q.options.length, notesVisible: false, previewScrollOffset: 0, cancelArmed: false, verticalMessage: "" }, effects: [
47
+ { kind: "set_input_buffer", value: state.customDraftsByTab.get(question) ?? ((answer?.kind === "custom" || answer?.kind === "multi") ? answer.answer ?? "" : "") },
48
+ { kind: "set_notes_value", value: state.notesByTab.get(question) ?? "" }, { kind: "set_notes_focused", focused: false } ] };
49
+ }
50
+
51
+ /** Confirming advances past answered or explicitly deferred questions. */
52
+ function advance(state: QuestionnaireState, ctx: ApplyContext): ApplyResult {
53
+ let next = ctx.questions.findIndex((_, i) => i > state.currentTab && !state.answers.has(i) && !state.deferredQuestions?.has(i));
54
+ if (next < 0) next = ctx.questions.findIndex((_, i) => !state.answers.has(i) && !state.deferredQuestions?.has(i));
55
+ if (next < 0) return { state: { ...state, verticalScreen: "review", verticalReviewIndex: ctx.questions.length, inputMode: false, notesVisible: false, cancelArmed: false, verticalMessage: "" }, effects: [] };
56
+ const result = focus(state, next, ctx);
57
+ if (next <= state.currentTab) result.state = { ...result.state, verticalMessage: "还有 " + (ctx.questions.length - state.answers.size) + " 题未答" };
58
+ return result;
59
+ }
60
+
61
+ export function reduceVertical(state: QuestionnaireState, action: VerticalAction, ctx: ApplyContext): ApplyResult {
62
+ if (action.kind === "cancel_arm") return { state: { ...state, cancelArmed: true, verticalMessage: "再按一次 Esc 取消问卷" }, effects: [] };
63
+ if (action.kind === "list_focus") return focus(state, action.question, ctx, action.index);
64
+ const q = ctx.questions[state.currentTab];
65
+ if (!q) return { state, effects: [] };
66
+ if (action.kind === "list_edit") return focus(state, state.currentTab, ctx, q.options.length);
67
+ if (action.kind === "list_rollback") return focus(state, state.currentTab, ctx, Math.max(0, q.options.length - 1));
68
+ if (action.kind === "review_open") return { state: { ...state, verticalScreen: "review", verticalReviewIndex: ctx.questions.length, inputMode: false, notesVisible: false, cancelArmed: false, verticalMessage: "" }, effects: [] };
69
+ if (action.kind === "list_defer" || (action.kind === "review_enter" && !state.answers.has(state.currentTab))) {
70
+ const answers = new Map(state.answers); answers.delete(state.currentTab);
71
+ return advance({ ...state, answers, deferredQuestions: new Set(state.deferredQuestions).add(state.currentTab), inputMode: false }, ctx);
72
+ }
73
+ if (action.kind === "review_enter") return advance(state, ctx);
74
+ const answers = new Map(state.answers);
75
+ const old = answers.get(state.currentTab);
76
+ if (action.kind === "list_save") {
77
+ const value = action.value;
78
+ const customDraftsByTab = new Map(state.customDraftsByTab).set(state.currentTab, value);
79
+ // Focus/navigation preserves an inactive draft; only editing or confirmation activates it.
80
+ const active = action.edited || action.review || old?.kind === "custom" || (old?.kind === "multi" && Boolean(old.answer));
81
+ if (active && value.trim()) answers.set(state.currentTab, { questionIndex: state.currentTab, question: q.question,
82
+ kind: q.multiSelect ? "multi" : "custom", answer: value,
83
+ ...(q.multiSelect ? { selected: old?.kind === "multi" ? old.selected ?? [] : [] } : {}),
84
+ ...(state.notesByTab.get(state.currentTab) ? { notes: state.notesByTab.get(state.currentTab) } : {}) });
85
+ else if (active && (old?.kind === "custom" || old?.kind === "multi")) {
86
+ if (old.kind === "multi" && old.selected?.length) answers.set(state.currentTab, { ...old, answer: null });
87
+ else answers.delete(state.currentTab);
88
+ }
89
+ const deferredQuestions = new Set(state.deferredQuestions);
90
+ if (answers.has(state.currentTab)) deferredQuestions.delete(state.currentTab);
91
+ const next = { ...state, answers, customDraftsByTab, deferredQuestions };
92
+ if (action.review) return value.trim() ? advance({ ...next, inputMode: false }, ctx) : { state: { ...next, verticalMessage: "先输入内容" }, effects: [] };
93
+ if (action.index !== undefined) return focus(next, state.currentTab, ctx, action.index);
94
+ if (action.direction) return focus(next, state.currentTab + action.direction, ctx);
95
+ return { state: next, effects: [] };
96
+ }
97
+ if (action.kind !== "list_select") return { state, effects: [] };
98
+ const index = action.index ?? state.optionIndex;
99
+ if (index < 0 || index >= q.options.length) return { state, effects: [] };
100
+ const selected = q.multiSelect ? q.options.flatMap((o, i) => old?.kind === "multi" && old.selected?.includes(o.label) ? [i] : []) : [];
101
+ if (q.multiSelect) {
102
+ const at = selected.indexOf(index);
103
+ if (at < 0) selected.push(index); else selected.splice(at, 1);
104
+ selected.sort((a, b) => a - b);
105
+ } else selected.push(index);
106
+ if (selected.length || (q.multiSelect && old?.answer)) answers.set(state.currentTab, { ...answerFor(q, state.currentTab, selected),
107
+ ...(q.multiSelect ? { answer: old?.kind === "multi" ? old.answer : null } : {}),
108
+ ...(state.notesByTab.get(state.currentTab) ? { notes: state.notesByTab.get(state.currentTab) } : {}) });
109
+ else answers.delete(state.currentTab);
110
+ const deferredQuestions = new Set(state.deferredQuestions); deferredQuestions.delete(state.currentTab);
111
+ const next = { ...state, answers, deferredQuestions, optionIndex: index, inputMode: false, cancelArmed: false, verticalMessage: "" };
112
+ return action.advance ? advance(next, ctx) : { state: next, effects: [] };
113
+ }
114
+
115
+ export function routeVertical(data: string, state: QuestionnaireState, runtime: QuestionnaireRuntime) {
116
+ const is = (key: Parameters<typeof matchesKey>[1]) => matchesKey(data, key);
117
+ const kb = runtime.keybindings;
118
+ const confirm = kb.matches(data, "tui.select.confirm");
119
+ const escape = kb.matches(data, "tui.select.cancel");
120
+ const printable = decodeKittyPrintable(data) ?? data;
121
+ const digit = /^[1-9]$/.test(printable) ? Number(printable) - 1 : -1;
122
+ if (is(Key.ctrl("c"))) return { kind: "cancel" } as const;
123
+ if (state.notesVisible) return escape || confirm ? { kind: "notes_exit" } as const : { kind: "notes_forward", data } as const;
124
+ if (state.verticalScreen === "review") {
125
+ if (escape) return { kind: "review_exit" } as const;
126
+ if (digit >= 0 && digit < runtime.questions.length) return { kind: "list_focus", question: digit } as const;
127
+ const at = state.verticalReviewIndex ?? runtime.questions.length;
128
+ if (kb.matches(data, "tui.select.up") || kb.matches(data, "tui.select.down")) return { kind: "review_focus", index: (at + (kb.matches(data, "tui.select.down") ? 1 : runtime.questions.length + 1)) % (runtime.questions.length + 2) } as const;
129
+ if (confirm) return at < runtime.questions.length ? { kind: "list_focus", question: at } as const : at === runtime.questions.length ? { kind: "submit" } as const : state.cancelArmed ? { kind: "cancel" } as const : { kind: "cancel_arm" } as const;
130
+ if (is(Key.ctrl("n"))) return { kind: "notes_enter" } as const;
131
+ return { kind: "ignore" } as const;
132
+ }
133
+ const q = runtime.questions[state.currentTab]!;
134
+ const direction = is(Key.tab) ? 1 : is(Key.shift("tab")) ? -1 : undefined;
135
+ if (state.inputMode) {
136
+ if (kb.matches(data, "app.editor.external")) return { kind: "input_edit", value: runtime.inputBuffer } as const;
137
+ if (is(Key.ctrl("u"))) return { kind: "input_clear" } as const;
138
+ if (escape) return { kind: "list_save", value: runtime.inputBuffer, index: Math.max(0, q.options.length - 1) } as const;
139
+ if (direction) return { kind: "list_save", value: runtime.inputBuffer, direction } as VerticalAction;
140
+ if (is(Key.shift("enter")) || is(Key.ctrl("j")) || kb.matches(data, "tui.input.newLine")) return { kind: "ignore" } as const;
141
+ if (confirm) return { kind: "list_save", value: runtime.inputBuffer, review: true } as const;
142
+ if (is(Key.up) && !runtime.canMoveInputUp) return { kind: "list_save", value: runtime.inputBuffer, index: Math.max(0, q.options.length - 1) } as const;
143
+ // Match the HTML's option wrap; text-editor cursor movement still wins inside multiline input.
144
+ if (is(Key.down) && !runtime.canMoveInputDown) return { kind: "list_save", value: runtime.inputBuffer, index: q.options.length + 1 } as const;
145
+ return { kind: "ignore" } as const;
146
+ }
147
+ if (escape) return state.cancelArmed ? { kind: "cancel" } as const : { kind: "cancel_arm" } as const;
148
+ if (direction) return { kind: "list_focus", question: (state.currentTab + direction + runtime.questions.length) % runtime.questions.length } as const;
149
+ if (is(Key.home)) return { kind: "list_focus", question: 0 } as const;
150
+ if (is(Key.end)) return { kind: "list_focus", question: runtime.questions.length - 1 } as const;
151
+ if (is(Key.ctrl("n"))) return { kind: "notes_enter" } as const;
152
+ if (kb.matches(data, "tui.select.up") || kb.matches(data, "tui.select.down")) return { kind: "list_focus", question: state.currentTab, index: (state.optionIndex + (kb.matches(data, "tui.select.down") ? 1 : q.options.length + 1)) % (q.options.length + 2) } as const;
153
+ if ((confirm || is(Key.space)) && state.optionIndex === q.options.length + 1) return { kind: "list_defer" } as const;
154
+ if (confirm) return state.optionIndex === q.options.length ? { kind: "list_edit" } as const : q.multiSelect ? { kind: "review_enter" } as const : { kind: "list_select", advance: true } as const;
155
+ if (is(Key.space)) return state.optionIndex === q.options.length ? { kind: "list_edit" } as const : { kind: "list_select" } as const;
156
+ if (decodeKittyPrintable(data) !== undefined || data.includes("\x1b[200~") || /^[^\u0000-\u001f\u007f-\u009f]+$/u.test(data)) return { kind: "list_edit", input: data } as const;
157
+ return { kind: "ignore" } as const;
158
+ }
@@ -0,0 +1,59 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import type { QuestionParams, QuestionnaireResult } from './tool/types.js';
4
+ import { resolveExternalAnswer } from './tool/external-answer.ts';
5
+
6
+ export type TimeoutPolicy = { seconds: number; autoSelect?: boolean; allowed: { question: string; option: string }[] };
7
+
8
+ type Allowed = TimeoutPolicy['allowed'];
9
+
10
+ function readTimeoutConfig(agentDir: string) {
11
+ if (!agentDir) return;
12
+ let raw: string;
13
+ try { raw = readFileSync(join(agentDir, 'vc-ask.json'), 'utf8'); }
14
+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return; throw error; }
15
+ return JSON.parse(raw)?.timeout;
16
+ }
17
+
18
+ export function validTimeoutSeconds(value: unknown): value is number {
19
+ return typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= 86400;
20
+ }
21
+
22
+ function validateAllowed(value: unknown): Allowed {
23
+ if (!Array.isArray(value) || !value.every(rule => typeof rule?.question === 'string' && !!rule.question.trim() &&
24
+ typeof rule.option === 'string' && !!rule.option.trim())) {
25
+ throw new Error('Invalid vc-ask timeout configuration: allowed');
26
+ }
27
+ return value;
28
+ }
29
+
30
+ export function loadTimeoutPolicy(agentDir: string, unattendedSeconds?: number): TimeoutPolicy | undefined {
31
+ const config = readTimeoutConfig(agentDir);
32
+ if (unattendedSeconds !== undefined) {
33
+ if (!validTimeoutSeconds(unattendedSeconds)) throw new Error('Invalid unattended timeout');
34
+ const allowed = validateAllowed(config?.allowed === undefined ? [] : config.allowed);
35
+ return { seconds: unattendedSeconds, autoSelect: true, allowed };
36
+ }
37
+ if (config?.enabled !== true) return;
38
+ const { seconds, autoSelect = false, allowed = [] } = config;
39
+ if (!validTimeoutSeconds(seconds) || typeof autoSelect !== 'boolean') {
40
+ throw new Error('Invalid vc-ask timeout configuration');
41
+ }
42
+ return { seconds, autoSelect, allowed: validateAllowed(allowed) };
43
+ }
44
+
45
+ export function timeoutResult(params: QuestionParams, policy: TimeoutPolicy): QuestionnaireResult {
46
+ const timedOut: QuestionnaireResult = { answers: [], cancelled: true, source: 'timeout' };
47
+ if (policy.autoSelect !== true) return timedOut;
48
+ const answers = [];
49
+ for (const [questionIndex, q] of params.questions.entries()) {
50
+ // Only exact, operator-vetted recommendations. Rich prompts can change what a label means.
51
+ if (q.multiSelect || q.preview || q.title || q.recommended?.length !== 1) return timedOut;
52
+ const index = q.recommended[0];
53
+ const option = q.options[index];
54
+ if (!option || option.preview || option.description || !policy.allowed.some(rule => rule.question === q.question && rule.option === option.label)) return timedOut;
55
+ answers.push({ questionIndex, optionIndexes: [index] });
56
+ }
57
+ const result = resolveExternalAnswer(params.questions, { answers });
58
+ return result.ok && result.result.answers.length ? { ...result.result, source: 'autopilot' } : timedOut;
59
+ }
@@ -0,0 +1,103 @@
1
+ import type { AskUserAnswerRejectCode } from "../events.js";
2
+ import type { QuestionAnswer, QuestionData, QuestionnaireResult } from "./types.js";
3
+
4
+ export type ExternalAnswerOutcome =
5
+ | { ok: true; result: QuestionnaireResult }
6
+ | { ok: false; code: AskUserAnswerRejectCode; reason: string };
7
+
8
+ const reject = (code: AskUserAnswerRejectCode, reason: string): ExternalAnswerOutcome => ({ ok: false, code, reason });
9
+
10
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
11
+ typeof value === "object" && value !== null && !Array.isArray(value);
12
+
13
+ /** A note as the dialog stores it: trimmed, and absent when blank. */
14
+ function noteOf(value: string | undefined): string | undefined {
15
+ const trimmed = value?.trim();
16
+ return trimmed ? trimmed : undefined;
17
+ }
18
+
19
+ /**
20
+ * Turn an inbound answer payload (still untrusted) into the `QuestionnaireResult` the dialog
21
+ * would have produced, so the envelope and `details` are identical whether the user typed or a
22
+ * program answered. Strict by design: the contract can be relaxed later without breaking
23
+ * emitters, never tightened. `invalid_payload` is a wrong shape or type, `invalid_answer` a
24
+ * well-formed answer that does not fit these questions.
25
+ */
26
+ export function resolveExternalAnswer(
27
+ questions: readonly QuestionData[],
28
+ payload: Record<string, unknown>,
29
+ ): ExternalAnswerOutcome {
30
+ const { answers, globalNote, cancel } = payload;
31
+ if (cancel !== undefined && typeof cancel !== "boolean")
32
+ return reject("invalid_payload", "cancel must be a boolean");
33
+ if (globalNote !== undefined && typeof globalNote !== "string")
34
+ return reject("invalid_payload", "globalNote must be a string");
35
+ const note = noteOf(globalNote);
36
+ const withNote = note ? { globalNote: note } : {};
37
+
38
+ if (cancel === true) {
39
+ if (answers !== undefined && !(Array.isArray(answers) && answers.length === 0))
40
+ return reject("invalid_payload", "cancel takes no answers");
41
+ return { ok: true, result: { answers: [], cancelled: true, ...withNote } };
42
+ }
43
+ if (!Array.isArray(answers)) return reject("invalid_payload", "answers must be an array");
44
+
45
+ const byQuestion = new Map<number, Record<string, unknown>>();
46
+ for (const entry of answers) {
47
+ if (!isRecord(entry)) return reject("invalid_payload", "each answer must be an object");
48
+ const index = entry.questionIndex;
49
+ if (!Number.isInteger(index)) return reject("invalid_payload", "questionIndex must be an integer");
50
+ const position = index as number;
51
+ if (position < 0 || position >= questions.length)
52
+ return reject("invalid_answer", `questionIndex ${position} out of range (0..${questions.length - 1})`);
53
+ if (byQuestion.has(position)) return reject("invalid_answer", `question ${position} answered twice`);
54
+ byQuestion.set(position, entry);
55
+ }
56
+
57
+ const resolved: QuestionAnswer[] = [];
58
+ for (let index = 0; index < questions.length; index++) {
59
+ const entry = byQuestion.get(index);
60
+ if (!entry) return reject("invalid_answer", `no answer for question ${index} ("${questions[index]!.header}")`);
61
+ const answer = resolveEntry(questions[index]!, index, entry);
62
+ if (!answer.ok) return answer;
63
+ resolved.push(answer.answer);
64
+ }
65
+ return { ok: true, result: { answers: resolved, cancelled: false, ...withNote } };
66
+ }
67
+
68
+ function resolveEntry(
69
+ question: QuestionData,
70
+ index: number,
71
+ entry: Record<string, unknown>,
72
+ ): { ok: true; answer: QuestionAnswer } | Extract<ExternalAnswerOutcome, { ok: false }> {
73
+ const { optionIndexes, text, notes } = entry;
74
+ if (optionIndexes !== undefined && (!Array.isArray(optionIndexes) || !optionIndexes.every(Number.isInteger)))
75
+ return { ok: false, code: "invalid_payload", reason: `question ${index}: optionIndexes must be an array of integers` };
76
+ if (text !== undefined && typeof text !== "string")
77
+ return { ok: false, code: "invalid_payload", reason: `question ${index}: text must be a string` };
78
+ if (notes !== undefined && typeof notes !== "string")
79
+ return { ok: false, code: "invalid_payload", reason: `question ${index}: notes must be a string` };
80
+
81
+ const invalid = (reason: string) => ({ ok: false as const, code: "invalid_answer" as const, reason: `question ${index}: ${reason}` });
82
+ const picked = (optionIndexes ?? []) as number[];
83
+ const outOfRange = picked.find((value) => value < 0 || value >= question.options.length);
84
+ if (outOfRange !== undefined) return invalid(`option index ${outOfRange} out of range (0..${question.options.length - 1})`);
85
+ if (new Set(picked).size !== picked.length) return invalid("option index repeated");
86
+ if (text !== undefined && text.trim().length === 0) return invalid("text is blank");
87
+ if (picked.length === 0 && text === undefined) return invalid("needs optionIndexes or text");
88
+
89
+ const base = { questionIndex: index, question: question.question };
90
+ const note = noteOf(notes as string | undefined);
91
+ const withNote = note ? { notes: note } : {};
92
+
93
+ if (question.multiSelect) {
94
+ const selected = question.options.filter((_option, position) => picked.includes(position)).map((option) => option.label);
95
+ return { ok: true, answer: { ...base, kind: "multi", answer: (text as string | undefined) ?? null, selected, ...withNote } };
96
+ }
97
+ if (picked.length > 0 && text !== undefined) return invalid("single-select takes optionIndexes or text, not both");
98
+ if (picked.length > 1) return invalid(`single-select takes one option, got ${picked.length}`);
99
+ if (text !== undefined) return { ok: true, answer: { ...base, kind: "custom", answer: text as string, ...withNote } };
100
+ const option = question.options[picked[0]!]!;
101
+ const withPreview = option.preview && option.preview.length > 0 ? { preview: option.preview } : {};
102
+ return { ok: true, answer: { ...base, kind: "option", answer: option.label, ...withPreview, ...withNote } };
103
+ }
@@ -0,0 +1,24 @@
1
+ import type { QuestionAnswer } from "./types.js";
2
+
3
+ /** Placeholder for an empty / null answer, used by the transcript summary and the envelope. */
4
+ export const NO_INPUT_PLACEHOLDER = "(no input)";
5
+
6
+ export type FormatAnswerVariant = "summary" | "envelope";
7
+
8
+ /**
9
+ * Format one answer to its scalar string. Multi-select joins the checked labels and appends
10
+ * the row's custom text; custom and option answers fall back to the placeholder.
11
+ */
12
+ export function formatAnswerScalar(a: QuestionAnswer, _variant: FormatAnswerVariant = "summary"): string {
13
+ switch (a.kind) {
14
+ case "multi": {
15
+ const values = [...(a.selected ?? [])];
16
+ if (a.answer && a.answer.length > 0) values.push(a.answer);
17
+ return values.length > 0 ? values.join(", ") : NO_INPUT_PLACEHOLDER;
18
+ }
19
+ case "custom":
20
+ return a.answer && a.answer.length > 0 ? a.answer : NO_INPUT_PLACEHOLDER;
21
+ case "option":
22
+ return a.answer ?? NO_INPUT_PLACEHOLDER;
23
+ }
24
+ }
@@ -0,0 +1,37 @@
1
+ import type { QuestionParams } from "./types.js";
2
+
3
+ /**
4
+ * Normalize line terminators in one model-supplied text field. Some models serialize a bare
5
+ * carriage return at token boundaries where the text was meant to be contiguous; a raw CR is a
6
+ * cursor-control byte, so downstream rendering either overwrites the row or fragments it.
7
+ * `\r\n` → `\n` keeps genuine multi-line content (preview markdown) intact; a lone `\r` is
8
+ * deleted — never a space (phantom gaps inside words), never `\n` (vertical fragmentation).
9
+ */
10
+ export function normalizeLineTerminators(text: string): string {
11
+ return text.replace(/\r\n/g, "\n").replace(/\r/g, "");
12
+ }
13
+
14
+ function normalizeStringFields<T extends object>(obj: T, keys: readonly (keyof T)[]): T {
15
+ const out = { ...obj };
16
+ for (const key of keys) {
17
+ const value = obj[key];
18
+ if (typeof value === "string") out[key] = normalizeLineTerminators(value) as T[typeof key];
19
+ }
20
+ return out;
21
+ }
22
+
23
+ /**
24
+ * Return a copy of the params with every user-facing string field line-terminator normalized.
25
+ * Runs before validation so the reserved-label and duplicate-label guards compare the text the
26
+ * user will actually see (`"Other\r"` must not slip past `reserved_label`), and so the dialog,
27
+ * the RPC walker, the envelope, and the prompt event all carry the same clean text.
28
+ */
29
+ export function normalizeQuestionParams(params: QuestionParams): QuestionParams {
30
+ return {
31
+ ...params,
32
+ questions: params.questions.map((question) => ({
33
+ ...normalizeStringFields(question, ["question", "header", "title", "preview"]),
34
+ options: question.options.map((option) => normalizeStringFields(option, ["label", "description", "preview"])),
35
+ })),
36
+ };
37
+ }
@@ -0,0 +1,75 @@
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 questionnaire result to the model-facing answer envelope. Cancelled and
10
+ * "no answers at all" both collapse to the single decline sentence, so the model sees one
11
+ * canonical "didn't answer" signal. Partial submits name the blank questions in an
12
+ * `unanswered:` segment instead of silently dropping them.
13
+ */
14
+ export function buildQuestionnaireResponse(result: QuestionnaireResult | null | undefined, params: QuestionParams) {
15
+ if (result?.source === "aborted") {
16
+ return buildToolResult("The questionnaire was interrupted. No user answer or approval was received.", result);
17
+ }
18
+ if (result?.source === "host_cancelled") {
19
+ return buildToolResult("The questionnaire was cancelled by the host. No user answer or approval was received.", result);
20
+ }
21
+ if (result?.source === "timeout") {
22
+ return buildToolResult("The question timed out. No user response or approval was received.", result);
23
+ }
24
+ if (result?.source === "autopilot") {
25
+ const answers = result.answers.map(buildAnswerSegment).join(" ");
26
+ return buildToolResult(`Autopilot selected these answers after timeout. The user did not answer or approve them. ${answers}`, result);
27
+ }
28
+ if (!result || result.cancelled) {
29
+ return buildToolResult(DECLINE_MESSAGE, {
30
+ answers: result?.answers ?? [],
31
+ cancelled: true,
32
+ ...(result?.globalNote ? { globalNote: result.globalNote } : {}),
33
+ });
34
+ }
35
+ const segments: string[] = [];
36
+ const unanswered: number[] = [];
37
+ for (let i = 0; i < params.questions.length; i++) {
38
+ const answer = result.answers.find((candidate) => candidate.questionIndex === i);
39
+ if (answer) segments.push(buildAnswerSegment(answer));
40
+ else unanswered.push(i);
41
+ }
42
+ const hasGlobalNote = result.globalNote !== undefined && result.globalNote.length > 0;
43
+ if (segments.length === 0 && !hasGlobalNote && !result.discussion) {
44
+ return buildToolResult(DECLINE_MESSAGE, { answers: result.answers, cancelled: true });
45
+ }
46
+ if (unanswered.length > 0) segments.push(buildUnansweredSegment(unanswered, params));
47
+ if (result.discussion && unanswered.length > 0) segments.push("These questions remain undecided for further discussion; do not infer consent or choose on the user’s behalf.");
48
+ if (hasGlobalNote) segments.push(`global note: ${result.globalNote}.`);
49
+ return buildToolResult(`${ENVELOPE_PREFIX} ${segments.join(" ")} ${ENVELOPE_SUFFIX}`, {
50
+ ...result,
51
+ ...(unanswered.length > 0 ? { unanswered } : {}),
52
+ });
53
+ }
54
+
55
+ /** `unanswered: "question", "question".` — the questions shown but left blank on a partial submit. */
56
+ function buildUnansweredSegment(indexes: readonly number[], params: QuestionParams): string {
57
+ return `unanswered: ${indexes.map((index) => `"${params.questions[index]?.question}"`).join(", ")}.`;
58
+ }
59
+
60
+ /**
61
+ * One `"question"="answer".` segment. A chosen option's preview is deliberately not
62
+ * echoed: the model authored it, and in the document mode it is the whole decision text.
63
+ */
64
+ function buildAnswerSegment(answer: QuestionAnswer): string {
65
+ const parts: string[] = [`"${answer.question}"="${formatAnswerScalar(answer, "envelope")}"`];
66
+ if (answer.notes && answer.notes.length > 0) parts.push(`user notes: ${answer.notes}`);
67
+ return `${parts.join(". ")}.`;
68
+ }
69
+
70
+ export function buildToolResult(text: string, details: QuestionnaireResult) {
71
+ return {
72
+ content: [{ type: "text" as const, text }],
73
+ details,
74
+ };
75
+ }
@@ -0,0 +1,74 @@
1
+ import { LABELS_BY_KIND, ROW_INTENT_META } from "../state/row-intent.js";
2
+
3
+ export const MAX_QUESTIONS = 12;
4
+ export const MIN_OPTIONS = 2;
5
+ export type MinimumOptions = 1 | typeof MIN_OPTIONS;
6
+ export const MAX_OPTIONS = 4;
7
+ export const MAX_HEADER_LENGTH = 16;
8
+ export const MAX_LABEL_LENGTH = 60;
9
+
10
+ export const SENTINEL_LABELS = LABELS_BY_KIND;
11
+ export type SentinelKind = keyof typeof SENTINEL_LABELS;
12
+
13
+ export const RESERVED_LABELS = ["Other", ROW_INTENT_META.other.label, ROW_INTENT_META.next.label] as const;
14
+
15
+ export interface OptionData {
16
+ label: string;
17
+ description?: string;
18
+ preview?: string;
19
+ }
20
+
21
+ export interface QuestionData {
22
+ question: string;
23
+ header: string;
24
+ /** Border title (CC "Ready to code?" style); when present it replaces the heading rows. */
25
+ title?: string;
26
+ /** Question-level preview: rendered as its own inline region above the options (CC plan-dialog style); option-level previews are not shown when it is present. */
27
+ preview?: string;
28
+ options: OptionData[];
29
+ /** Validated option indices mapped from compact recommendation IDs. */
30
+ recommended?: number[];
31
+ multiSelect?: boolean;
32
+ }
33
+
34
+ export interface QuestionParams {
35
+ questions: QuestionData[];
36
+ }
37
+
38
+ export interface QuestionAnswer {
39
+ questionIndex: number;
40
+ question: string;
41
+ kind: "option" | "custom" | "multi";
42
+ answer: string | null;
43
+ selected?: string[];
44
+ notes?: string;
45
+ preview?: string;
46
+ }
47
+
48
+ export type QuestionnaireError =
49
+ | "host_disconnected"
50
+ | "no_ui"
51
+ | "no_custom_ui"
52
+ | "no_questions"
53
+ | "empty_options"
54
+ | "too_many_questions"
55
+ | "duplicate_question"
56
+ | "duplicate_option_label"
57
+ | "reserved_label"
58
+ | "invalid_recommendation"
59
+ | "session_load_failed"
60
+ | "stale_module_cache";
61
+
62
+ export interface QuestionnaireResult {
63
+ answers: QuestionAnswer[];
64
+ cancelled: boolean;
65
+ source?: "autopilot" | "timeout" | "host_cancelled" | "host_disconnected" | "aborted";
66
+ /** Whole-questionnaire note, attached from the questionnaire's global notes slot. */
67
+ globalNote?: string;
68
+ /** Indexes of the questions left blank on a partial submit; set by the envelope builder. */
69
+ unanswered?: number[];
70
+ /** Explicit local form submission, including a deliberate empty discussion result. */
71
+ discussion?: boolean;
72
+ error?: QuestionnaireError;
73
+ message?: string;
74
+ }
@@ -0,0 +1,75 @@
1
+ import {
2
+ MAX_QUESTIONS,
3
+ MIN_OPTIONS,
4
+ type MinimumOptions,
5
+ type QuestionnaireError,
6
+ type QuestionParams,
7
+ RESERVED_LABELS,
8
+ } from "./types.js";
9
+
10
+ export const ERROR_NO_QUESTIONS = "Error: At least one question is required";
11
+ export const ERROR_TOO_MANY_QUESTIONS = `Error: At most ${MAX_QUESTIONS} questions are allowed per invocation`;
12
+ export const ERROR_DUPLICATE_QUESTION = "Error: Question text must be unique within an invocation";
13
+ export const ERROR_RESERVED_LABEL = `Error: Option label is reserved (${RESERVED_LABELS.join(", ")})`;
14
+ export const ERROR_DUPLICATE_OPTION_LABEL = "Error: Option labels must be unique within a question";
15
+
16
+ const RESERVED_LABEL_SET: ReadonlySet<string> = new Set(RESERVED_LABELS);
17
+
18
+ export type ValidationResult = { ok: true } | { ok: false; error: QuestionnaireError; message: string };
19
+
20
+ /**
21
+ * Pure runtime validator for `QuestionParams`. Covers every guard except
22
+ * `no_ui` (which depends on `ctx.hasUI` and stays inline at the call site).
23
+ * `reserved_label` MUST short-circuit before `duplicate_option_label`.
24
+ */
25
+ export function validateQuestionnaire(
26
+ typed: QuestionParams,
27
+ minimumOptions: MinimumOptions = MIN_OPTIONS,
28
+ ): ValidationResult {
29
+ if (typed.questions.length === 0) {
30
+ return { ok: false, error: "no_questions", message: ERROR_NO_QUESTIONS };
31
+ }
32
+ if (typed.questions.length > MAX_QUESTIONS) {
33
+ return { ok: false, error: "too_many_questions", message: ERROR_TOO_MANY_QUESTIONS };
34
+ }
35
+
36
+ const seenQuestions = new Set<string>();
37
+ for (const q of typed.questions) {
38
+ if (seenQuestions.has(q.question)) {
39
+ return { ok: false, error: "duplicate_question", message: ERROR_DUPLICATE_QUESTION };
40
+ }
41
+ seenQuestions.add(q.question);
42
+ }
43
+
44
+ for (const q of typed.questions) {
45
+ if (q.recommended !== undefined && (!Array.isArray(q.recommended) ||
46
+ new Set(q.recommended).size !== q.recommended.length ||
47
+ q.recommended.some(index => !Number.isInteger(index) || index < 0 || index >= q.options.length) ||
48
+ (!q.multiSelect && q.recommended.length > 1))) {
49
+ return { ok: false, error: "invalid_recommendation", message: "Error: Invalid recommended options" };
50
+ }
51
+ if (q.options.length < minimumOptions) {
52
+ return {
53
+ ok: false,
54
+ error: "empty_options",
55
+ message: `Error: Each question requires at least ${minimumOptions} options`,
56
+ };
57
+ }
58
+ const seenLabels = new Set<string>();
59
+ for (const o of q.options) {
60
+ if (RESERVED_LABEL_SET.has(o.label)) {
61
+ return { ok: false, error: "reserved_label", message: ERROR_RESERVED_LABEL };
62
+ }
63
+ if (seenLabels.has(o.label)) {
64
+ return {
65
+ ok: false,
66
+ error: "duplicate_option_label",
67
+ message: ERROR_DUPLICATE_OPTION_LABEL,
68
+ };
69
+ }
70
+ seenLabels.add(o.label);
71
+ }
72
+ }
73
+
74
+ return { ok: true };
75
+ }