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,688 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ isKeyRelease,
4
+ isKeyRepeat,
5
+ matchesKey,
6
+ type Component,
7
+ type OverlayHandle,
8
+ type OverlayOptions,
9
+ type TUI,
10
+ } from "@earendil-works/pi-tui";
11
+ import { terminalScrollIntent } from "./state/key-router.js";
12
+ import { claimInlineSlot, mustYieldInlineSlot } from "./presentation.js";
13
+ import { loadQuestionnaireConfig, resolveCardAccent, resolveCollapseKey, resolvePanelDefaults } from "./config.js";
14
+ import type { OpenQuestionnaire } from "./answer-channel.js";
15
+ import { answerChannelFor } from "./answer-channel.js";
16
+ import { askHost } from "../host-channel.mjs";
17
+ import { resolveExternalAnswer } from "./tool/external-answer.js";
18
+ import { timeoutResult, type TimeoutPolicy } from "./timeout.js";
19
+ import { normalizeQuestionParams } from "./tool/normalize-params.js";
20
+ import { emitUserInputEvent } from "../user-input-events.js";
21
+ import {
22
+ ASK_USER_BLOCKED_EVENT,
23
+ ASK_USER_CLOSED_EVENT,
24
+ ASK_USER_PROMPT_EVENT,
25
+ type AskUserClosedEventPayload,
26
+ type AskUserBlockedEventPayload,
27
+ type AskUserPromptEventPayload,
28
+ } from "./events.js";
29
+ import { displayLabel, t } from "./i18n.js";
30
+ import { hasDialogUI, runRpcQuestionnaire } from "./rpc.js";
31
+ import { sentinelsToAppend } from "./state/row-intent.js";
32
+ import { floatDefault, formDefault, type PanelGeometry, type TerminalSize } from "./state/geometry.js";
33
+ import { routeAskPanel } from "./state/panel-router.js";
34
+ import { CARD_PALETTES, wrapCardTheme } from "./view/card-theme.js";
35
+ import {
36
+ createActiveAskBridge,
37
+ createAskEntry,
38
+ EMMA_ASK_ENTRY_TYPE,
39
+ type AskEntryData,
40
+ type AskEntryHandle,
41
+ } from "./inline-entry.js";
42
+ import type {
43
+ MinimumOptions,
44
+ QuestionData,
45
+ QuestionnaireError,
46
+ QuestionnaireResult,
47
+ QuestionParams,
48
+ } from "./tool/types.js";
49
+ import { validateQuestionnaire } from "./tool/validate-questionnaire.js";
50
+ import type { WrappingSelectItem } from "./view/components/wrapping-select.js";
51
+
52
+ const ERROR_NO_UI = "Error: UI not available (running in non-interactive mode)";
53
+ const ERROR_NO_CUSTOM_UI =
54
+ "Error: this client cannot render the questionnaire. The user never saw the questions; ask them as plain chat text instead.";
55
+ const ERROR_SESSION_LOAD_FAILED =
56
+ "Error: the questionnaire UI failed to load. Repair the install if needed and restart Pi; the user never saw the questions.";
57
+ const ERROR_STALE_MODULE_CACHE =
58
+ "Error: the questionnaire UI module cache is stale. Restart Pi; the user never saw the questions.";
59
+
60
+ export const PREWARM_DELAY_MS = 2000;
61
+
62
+ /** Stand-in returned by a mount that resolved before mounting (Pi discards it unmounted). */
63
+ const LAYOUT_READY = Object.freeze({ answers: [], cancelled: true });
64
+
65
+ const INERT_COMPONENT: Component = { render: () => [], invalidate: () => {}, handleInput: () => {} };
66
+
67
+ /**
68
+ * Listeners may claim presentation of an ask prompt outside Emma's terminal UI.
69
+ * Emma emits one shared event with a first-wins `claim()` function: first `true`
70
+ * hands presentation to that listener; no listener, a false claim, or a thrown
71
+ * listener leaves the terminal questionnaire in charge. The shared inbound answer
72
+ * channel stays active in every case, so a claimed prompt can be answered through
73
+ * `emma:ask-user:answer`.
74
+ */
75
+ export type AskPresentationHook = (payload: AskUserPromptEventPayload) => boolean | void;
76
+
77
+ const askPresentationHooks = new WeakMap<object, Set<AskPresentationHook>>();
78
+
79
+ /** @deprecated Use `pi.events.on(ASK_USER_PROMPT_EVENT, ...)` and `payload.claim(true)`. */
80
+ export function subscribeAskPresentation(
81
+ pi: ExtensionAPI,
82
+ hook: AskPresentationHook,
83
+ ): () => void {
84
+ let hooks = askPresentationHooks.get(pi);
85
+ if (!hooks) {
86
+ hooks = new Set();
87
+ askPresentationHooks.set(pi, hooks);
88
+ }
89
+ hooks.add(hook);
90
+ return () => hooks?.delete(hook);
91
+ }
92
+
93
+ /** Panel geometry remembered for the lifetime of one Pi session, so reopening keeps the placement. */
94
+ interface PanelMemory {
95
+ panelForm: "dock" | "float";
96
+ panel: PanelGeometry;
97
+ dockRows: number | null;
98
+ }
99
+ const panelMemory = new Map<string, PanelMemory>();
100
+
101
+ type SessionModule = typeof import("./state/questionnaire-session.js");
102
+ type SessionLoad =
103
+ | { ok: true; module: SessionModule }
104
+ | { ok: false; error: Extract<QuestionnaireError, "session_load_failed" | "stale_module_cache">; message: string };
105
+
106
+ function failed(error: QuestionnaireError, message: string): QuestionnaireResult {
107
+ return { answers: [], cancelled: true, error, message };
108
+ }
109
+
110
+ export function presentAskPrompt(
111
+ pi: ExtensionAPI,
112
+ params: QuestionParams,
113
+ toolCallId: string,
114
+ allowClaim = true,
115
+ deadlineAt?: number,
116
+ ): boolean {
117
+ const payload = buildAskPromptPayload(params, toolCallId, deadlineAt);
118
+ let externalClaim = false;
119
+ let claimed = false;
120
+ payload.claim = (value: boolean): boolean => {
121
+ if (!allowClaim || claimed || value !== true || (deadlineAt !== undefined && Date.now() >= deadlineAt)) return false;
122
+ claimed = true;
123
+ externalClaim = true;
124
+ return true;
125
+ };
126
+ // Every listener sees the same payload; the first claim wins. A listener that
127
+ // throws cannot steal or block the prompt — it falls through to the terminal UI.
128
+ try {
129
+ pi.events.emit(ASK_USER_PROMPT_EVENT, payload);
130
+ } catch {
131
+ // A throwing listener must not prevent the terminal prompt from opening.
132
+ }
133
+ // Legacy in-process hooks are kept for older extensions; they may still opt out
134
+ // by returning false. Their ordering relative to event listeners is irrelevant:
135
+ // both only request ownership through the same first-wins flag.
136
+ for (const hook of askPresentationHooks.get(pi) ?? []) {
137
+ try {
138
+ if (hook(payload) === false && !claimed && allowClaim && (deadlineAt === undefined || Date.now() < deadlineAt)) {
139
+ claimed = true;
140
+ externalClaim = true;
141
+ }
142
+ } catch {
143
+ // A broken hook must not prevent the user from answering in the terminal.
144
+ }
145
+ }
146
+ // Ownership is decided synchronously. Disarm the callback so a listener that
147
+ // kept the payload cannot flip `externalClaim` after the terminal UI is up.
148
+ payload.claim = (): boolean => false;
149
+ return !externalClaim;
150
+ }
151
+
152
+ function buildAskPromptPayload(params: QuestionParams, toolCallId: string, deadlineAt?: number): AskUserPromptEventPayload {
153
+ const payload: AskUserPromptEventPayload = {
154
+ toolCallId,
155
+ ...(Number.isFinite(deadlineAt) ? { deadlineAt: Math.trunc(deadlineAt!) } : {}),
156
+ questions: params.questions.map((question) => ({
157
+ question: question.question,
158
+ header: question.header,
159
+ ...(question.title ? { title: question.title } : {}),
160
+ ...(question.preview ? { preview: question.preview } : {}),
161
+ multiSelect: question.multiSelect ?? false,
162
+ ...(question.recommended?.length ? { recommended: [...question.recommended] } : {}),
163
+ options: question.options.map((option) => ({
164
+ label: option.label,
165
+ ...(option.description ? { description: option.description } : {}),
166
+ hasPreview: typeof option.preview === "string" && option.preview.length > 0,
167
+ ...(option.preview ? { preview: option.preview } : {}),
168
+ })),
169
+ })),
170
+ };
171
+ return payload;
172
+ }
173
+
174
+ function emitBlocked(pi: ExtensionAPI, active: boolean, toolCallId: string): void {
175
+ const payload: AskUserBlockedEventPayload = { active, toolCallId };
176
+ pi.events.emit(ASK_USER_BLOCKED_EVENT, payload);
177
+ }
178
+
179
+ async function waitForUserInput<T>(
180
+ pi: ExtensionAPI,
181
+ sessionId: string,
182
+ requestId: string,
183
+ message: string,
184
+ run: () => Promise<T>,
185
+ ): Promise<T> {
186
+ emitBlocked(pi, true, requestId);
187
+ emitUserInputEvent(pi.events, sessionId, requestId, true, message);
188
+ try {
189
+ return await run();
190
+ } finally {
191
+ try {
192
+ emitBlocked(pi, false, requestId);
193
+ } finally {
194
+ emitUserInputEvent(pi.events, sessionId, requestId, false);
195
+ }
196
+ }
197
+ }
198
+
199
+ export async function loadQuestionnaireSession(): Promise<SessionLoad> {
200
+ let module: SessionModule;
201
+ try {
202
+ module = await import("./state/questionnaire-session.js");
203
+ } catch (error) {
204
+ const cause = error instanceof Error ? error.message : String(error);
205
+ return { ok: false, error: "session_load_failed", message: `${ERROR_SESSION_LOAD_FAILED} (cause: ${cause})` };
206
+ }
207
+ if (typeof module.QuestionnaireSession !== "function") {
208
+ return {
209
+ ok: false,
210
+ error: "stale_module_cache",
211
+ message: `${ERROR_STALE_MODULE_CACHE} (resolved namespace keys: ${JSON.stringify(Object.keys(module))})`,
212
+ };
213
+ }
214
+ return { ok: true, module };
215
+ }
216
+
217
+ export function buildItemsForQuestion(question: QuestionData): WrappingSelectItem[] {
218
+ const items: WrappingSelectItem[] = question.options.map((option) => ({
219
+ kind: "option",
220
+ label: option.label,
221
+ ...(option.description ? { description: option.description } : {}),
222
+ }));
223
+ for (const kind of sentinelsToAppend(question)) items.push({ kind, label: displayLabel(kind) });
224
+ return items;
225
+ }
226
+
227
+ export type QuestionnaireRequest = {
228
+ pi: ExtensionAPI;
229
+ context: ExtensionContext;
230
+ params: QuestionParams;
231
+ sessionId: string;
232
+ requestId: string;
233
+ minimumOptions?: MinimumOptions;
234
+ signal?: AbortSignal;
235
+ /** Content-frame label for question-level previews; defaults to the locale's neutral summary label. */
236
+ previewLabel?: string;
237
+ /** Authorization dialogs must not truncate the plan being confirmed in RPC mode. */
238
+ fullPreview?: boolean;
239
+ /** Conditional option notes request feedback rather than the selected action. */
240
+ notesAreFeedback?: boolean;
241
+ /** Disable option notes for action-only confirmation buttons. */
242
+ allowNotes?: boolean;
243
+ /** Internal presentation flag; never changes the external tool protocol. */
244
+ document?: boolean;
245
+ vertical?: boolean;
246
+ /** Supplied only by the public form tool, never by the workflow bridge. */
247
+ timeout?: TimeoutPolicy;
248
+ /** Published to subscribers as the optional `deadlineAt` on the prompt event. */
249
+ deadlineAt?: number;
250
+ /** Opt into the cross-process host channel for ordinary ask calls. */
251
+ useHostChannel?: boolean;
252
+ };
253
+
254
+ function timeoutFields(params: QuestionParams, result: QuestionnaireResult) {
255
+ const source = result.source === "autopilot" ? "autopilot" : "timeout";
256
+ return {
257
+ source,
258
+ answers: source === "autopilot" ? result.answers.map(answer => ({
259
+ questionIndex: answer.questionIndex,
260
+ optionIndexes: [params.questions[answer.questionIndex].options.findIndex(option => option.label === answer.answer)],
261
+ })) : [],
262
+ } as const;
263
+ }
264
+
265
+ export async function runQuestionnaire(request: QuestionnaireRequest): Promise<QuestionnaireResult> {
266
+ const { pi, context, requestId } = request;
267
+ const params = normalizeQuestionParams(request.params);
268
+ if (request.signal?.aborted) return { answers: [], cancelled: true, source: "aborted" };
269
+ if (!context.hasUI) return failed("no_ui", ERROR_NO_UI);
270
+
271
+ const validation = validateQuestionnaire(params, request.minimumOptions);
272
+ if (!validation.ok) return failed(validation.error, validation.message);
273
+ const expire = (): QuestionnaireResult => request.timeout && !request.document && !request.fullPreview
274
+ ? timeoutResult(params, request.timeout)
275
+ : { answers: [], cancelled: true, source: "timeout" };
276
+ if (request.deadlineAt !== undefined && Date.now() >= request.deadlineAt) return expire();
277
+ if (request.useHostChannel) {
278
+ const { questions } = buildAskPromptPayload(params, requestId);
279
+ const host = await askHost({ agent: "pi", sessionId: request.sessionId, toolCallId: requestId, paneId: process.env.TTY7_PANE, questions, deadlineAt: request.deadlineAt }, event => {
280
+ const outcome = resolveExternalAnswer(params.questions, {
281
+ answers: Array.isArray(event.answers) ? event.answers.map(answer => answer && typeof answer === "object"
282
+ ? { ...answer, text: answer.text ?? undefined, notes: answer.notes ?? undefined }
283
+ : answer) : event.answers,
284
+ globalNote: event.globalNote ?? undefined,
285
+ });
286
+ return outcome.ok ? outcome.result : undefined;
287
+ }, { signal: request.signal, waitMs: null, onTimeout: () => {
288
+ const value = expire();
289
+ return { value, fields: timeoutFields(params, value) };
290
+ } });
291
+ if (host.status === "answered" || host.status === "timeout") return host.value as QuestionnaireResult;
292
+ if (host.status === "disconnected") return { answers: [], cancelled: true, error: "host_disconnected", source: "host_disconnected", message: "The questionnaire host disconnected. No answer was received." };
293
+ if (host.status === "cancelled") return { answers: [], cancelled: true, source: request.signal?.aborted ? "aborted" : "host_cancelled" };
294
+ if (request.signal?.aborted) return { answers: [], cancelled: true, source: "aborted" };
295
+ }
296
+ if (request.deadlineAt !== undefined && Date.now() >= request.deadlineAt) return expire();
297
+ // Open for inbound answers before the prompt goes out: an emitter may answer straight from
298
+ // its prompt listener, and the first answer wins against the dialog.
299
+ const answers = answerChannelFor(pi);
300
+ const open = answers.open(requestId, params.questions, context.mode === "rpc" ? "rpc" : "tui");
301
+ open.deadlineAt = request.deadlineAt;
302
+ open.onTimeout = () => open.settle(expire());
303
+ const cancel = () => open.settle({ answers: [], cancelled: true, source: "aborted" });
304
+ request.signal?.addEventListener("abort", cancel, { once: true });
305
+ let timer: ReturnType<typeof setTimeout> | undefined;
306
+ let result: QuestionnaireResult | undefined;
307
+ try {
308
+ const useTerminal = presentAskPrompt(pi, params, requestId, context.mode !== "rpc", request.deadlineAt);
309
+ if (request.deadlineAt !== undefined) {
310
+ const remaining = request.deadlineAt - Date.now();
311
+ if (remaining <= 0) open.onTimeout();
312
+ else timer = setTimeout(open.onTimeout, remaining);
313
+ }
314
+ result = useTerminal ? await runOpenedQuestionnaire(request, params, open) : await open.answeredEarly;
315
+ if (!useTerminal && result.cancelled && !result.source) result = { ...result, source: "host_cancelled" };
316
+ return result;
317
+ } finally {
318
+ clearTimeout(timer);
319
+ request.signal?.removeEventListener("abort", cancel);
320
+ answers.close(open);
321
+ const timedOut = result?.source === "timeout" || result?.source === "autopilot";
322
+ const event: AskUserClosedEventPayload = {
323
+ toolCallId: requestId,
324
+ status: timedOut ? "timeout" : !result || result.source === "aborted" ? "aborted" : result.cancelled ? "cancelled" : "answered",
325
+ ...(timedOut && result ? timeoutFields(params, result) : {}),
326
+ };
327
+ try { pi.events.emit(ASK_USER_CLOSED_EVENT, event); } catch { /* Observers do not affect the result. */ }
328
+ }
329
+ }
330
+
331
+ /** Reserve the shared editor slot and measure the public host before mounting once. */
332
+ async function runOpenedQuestionnaire(request: QuestionnaireRequest, params: QuestionParams, open: OpenQuestionnaire): Promise<QuestionnaireResult> {
333
+ const release = claimInlineSlot();
334
+ try {
335
+ const actualSize: { value?: TerminalSize; tui?: TUI } = {};
336
+ const result = await runMountedQuestionnaire(request, params, open, !release, actualSize);
337
+ return result === LAYOUT_READY ? await runMountedQuestionnaire(request, params, open, !release, actualSize) : result;
338
+ } finally { release?.(); }
339
+ }
340
+
341
+ /** Run the questionnaire the answer channel already opened for this tool call. */
342
+ async function runMountedQuestionnaire(
343
+ request: QuestionnaireRequest,
344
+ params: QuestionParams,
345
+ open: OpenQuestionnaire,
346
+ stacked = false,
347
+ actualSize: { value?: TerminalSize; tui?: TUI } = {},
348
+ ): Promise<QuestionnaireResult> {
349
+ const { pi, context, sessionId, requestId, minimumOptions, signal } = request;
350
+ const questionnaireConfig = loadQuestionnaireConfig();
351
+
352
+ if (context.mode === "rpc") {
353
+ if (!hasDialogUI(context.ui)) return failed("no_custom_ui", ERROR_NO_CUSTOM_UI);
354
+ return waitForUserInput(
355
+ pi,
356
+ sessionId,
357
+ requestId,
358
+ params.questions[0].question,
359
+ () => runRpcQuestionnaire(context.ui, params, signal, request.fullPreview),
360
+ );
361
+ }
362
+ if (context.mode !== "tui" || typeof context.ui?.custom !== "function" ||
363
+ typeof context.ui.onTerminalInput !== "function" ||
364
+ typeof pi.registerEntryRenderer !== "function" || typeof pi.appendEntry !== "function")
365
+ return failed("no_custom_ui", ERROR_NO_CUSTOM_UI);
366
+
367
+ const itemsByTab = params.questions.map((question) => buildItemsForQuestion(question));
368
+ const sessionLoad = await loadQuestionnaireSession();
369
+ if (signal?.aborted) return { answers: [], cancelled: true, source: "aborted" };
370
+ if (!sessionLoad.ok) return failed(sessionLoad.error, sessionLoad.message);
371
+ // Answered while the render graph loaded: the answer needs no dialog.
372
+ if (open.settled) return open.settled;
373
+ const { QuestionnaireSession } = sessionLoad.module;
374
+ const document = request.document === true && params.questions.length === 1 && Boolean(params.questions[0]?.preview);
375
+ const vertical = request.vertical === true;
376
+ const terminal = (context.ui as typeof context.ui & {terminal?: TerminalSize}).terminal;
377
+ const needsSize = !actualSize.value && (request.vertical === true || request.document === true || !terminal);
378
+ const size: TerminalSize = actualSize.value ?? { columns: terminal?.columns ?? 80, rows: terminal?.rows ?? 24 };
379
+ const panelDefaults = resolvePanelDefaults(questionnaireConfig, size);
380
+ // Ordinary questions dock; document and preview space are measured before opening.
381
+ const docked = (vertical || document) && routeAskPanel(params.questions, itemsByTab, size, document) === "dock";
382
+ // Reuse explicit geometry without letting an earlier floating prompt override routing.
383
+ const remembered = panelMemory.get(sessionId);
384
+ // Keep the opening mode stable throughout this questionnaire.
385
+ const panelForm: "dock" | "float" = vertical || document ? (docked ? "dock" : "float") : remembered?.panelForm ?? "float";
386
+ const preferredPanel: PanelGeometry = panelForm === "float"
387
+ ? remembered?.panel ?? panelDefaults.panel ?? floatDefault(size)
388
+ : panelDefaults.panel ?? floatDefault(size);
389
+ const initialPanel = vertical ? formDefault(size, preferredPanel) : preferredPanel;
390
+ const initialDockRows = panelForm === "dock" ? remembered?.dockRows ?? null : null;
391
+ let inlineStarted = false;
392
+ let inlineDraft: string | undefined;
393
+ const collapseKey = resolveCollapseKey(questionnaireConfig);
394
+ const cardAccent = resolveCardAccent(questionnaireConfig);
395
+ const sessionRef: { current: InstanceType<typeof QuestionnaireSession> | null } = { current: null };
396
+ const askEntryRef: { current: AskEntryHandle | undefined } = { current: undefined };
397
+ const tuiRef: { current: TUI | undefined } = {
398
+ current: undefined,
399
+ };
400
+ const lifecycleOverlayRef: { current: OverlayHandle | undefined } = { current: undefined };
401
+ const lifecycleOverlayOptions: OverlayOptions = (document || vertical) && panelForm === "float" ? { width: initialPanel.w, maxHeight: initialPanel.h, row: initialPanel.row, col: initialPanel.col, margin: 0 } : { nonCapturing: document || vertical };
402
+ let mountedOverlay = needsSize || stacked || ((document || vertical) && panelForm === "float") || (!vertical && !document);
403
+ if (stacked && panelForm === "dock") Object.assign(lifecycleOverlayOptions, {nonCapturing: false, width: "100%", maxHeight: "70%", anchor: "bottom-center", margin: 0});
404
+ let promotedHandle: OverlayHandle | undefined;
405
+ const updateFloatLayout = () => {
406
+ const panel = sessionRef.current?.measurePanel(tuiRef.current?.terminal.columns ?? size.columns);
407
+ if (panel) Object.assign(lifecycleOverlayOptions, {width: panel.w, maxHeight: panel.h, row: panel.row, col: panel.col});
408
+ return true;
409
+ };
410
+ if ((document || vertical) && panelForm === "float") lifecycleOverlayOptions.visible = updateFloatLayout;
411
+ let removeAbortListener: (() => void) | undefined;
412
+ let documentActive = document || vertical;
413
+
414
+ const removeInputListener = context.ui.onTerminalInput((data) => {
415
+ if (vertical && !sessionRef.current?.getFloatingPanel()) return undefined;
416
+ if (document || vertical) {
417
+ const tui = tuiRef.current as (TUI & { scrollBy?: (lines: number) => void; hasActiveSelection?: () => boolean }) | undefined;
418
+ const handle = lifecycleOverlayRef.current as (OverlayHandle & { getBounds?: () => { row: number; col: number; width: number; height: number } | undefined }) | undefined;
419
+ if (!documentActive || tui?.mode !== "fullscreen" || typeof tui.scrollBy !== "function" ||
420
+ typeof handle?.isFocused !== "function" || !handle.isFocused() || typeof handle.getBounds !== "function") return undefined;
421
+ // Pi defers unhandled wheel while an overlay owns focus. Only compensate
422
+ // outside this card; normalized body events have already been consumed.
423
+ const wheel = /^\x1b\[<(64|65|72|73);(\d+);(\d+)M$/.exec(data);
424
+ if (!wheel) return undefined;
425
+ const bounds = handle.getBounds();
426
+ if (!bounds) return undefined;
427
+ const x = Number(wheel[2]) - 1, y = Number(wheel[3]) - 1;
428
+ if (!Number.isSafeInteger(x) || !Number.isSafeInteger(y) || x < 0 || y < 0 ||
429
+ x >= tui.terminal.columns || y >= tui.terminal.rows ||
430
+ (x >= bounds.col && x < bounds.col + bounds.width && y >= bounds.row && y < bounds.row + bounds.height)) return undefined;
431
+ // Overlay selections are screen-anchored: scrolling would change their text.
432
+ if (!tui.hasActiveSelection?.()) tui.scrollBy((Number(wheel[1]) & 1 ? 1 : -1) * (Number(wheel[1]) & 8 ? 5 : 1));
433
+ return { consume: true };
434
+ }
435
+ const entry = askEntryRef.current;
436
+ const session = sessionRef.current;
437
+ if (!entry || entry.data.kind !== "active" || !session) return undefined;
438
+ if (!session.component.focused) {
439
+ return undefined;
440
+ }
441
+
442
+ if (matchesKey(data, "ctrl+c")) return undefined;
443
+ const collapseRequested =
444
+ collapseKey !== "off" && matchesKey(data, collapseKey as Parameters<typeof matchesKey>[1]);
445
+ if (collapseRequested) {
446
+ if (isKeyRelease(data) || isKeyRepeat(data)) return { consume: true };
447
+ session.toggleCollapsedExternal();
448
+ return { consume: true };
449
+ }
450
+
451
+ if (isKeyRelease(data) || isKeyRepeat(data)) return undefined;
452
+ const intent = terminalScrollIntent(data);
453
+ if (!intent) {
454
+ // Only keys the card actually handles are consumed; other keys continue
455
+ // to the currently focused pi component.
456
+ const handled = session.dispatch(data);
457
+ return handled ? { consume: true } : undefined;
458
+ }
459
+ const handled = intent.kind === "page"
460
+ ? session.scrollPreviewPage(intent.direction)
461
+ : session.scrollPreviewBy(intent.lines);
462
+ return handled ? { consume: true } : undefined;
463
+ });
464
+
465
+ return waitForUserInput(
466
+ pi,
467
+ sessionId,
468
+ requestId,
469
+ params.questions[0].question,
470
+ async () => {
471
+ try {
472
+ if (open.settled) return open.settled;
473
+ if (signal?.aborted) return { answers: [], cancelled: true, source: "aborted" };
474
+ if (!needsSize && actualSize.tui && mustYieldInlineSlot(actualSize.tui)) {
475
+ stacked = true; mountedOverlay = true;
476
+ if (panelForm === "dock") Object.assign(lifecycleOverlayOptions, { nonCapturing: false, width: "100%", maxHeight: "70%", anchor: "bottom-center", margin: 0 });
477
+ }
478
+ if (!mountedOverlay) {
479
+ inlineDraft = context.ui.getEditorText?.();
480
+ inlineStarted = true;
481
+ }
482
+ const mounted = context.ui.custom<QuestionnaireResult>(
483
+ (tui, theme, keybindings, done) => {
484
+ if (needsSize) {
485
+ if (signal?.aborted && !tui) { done({ answers: [], cancelled: true, source: "aborted" }); return INERT_COMPONENT; }
486
+ if (!signal?.aborted) {
487
+ actualSize.value = { columns: tui.terminal.columns, rows: tui.terminal.rows };
488
+ actualSize.tui = tui;
489
+ }
490
+ const shell = tui.showOverlay(INERT_COMPONENT, { nonCapturing: true, visible: () => false });
491
+ done(signal?.aborted ? { answers: [], cancelled: true, source: "aborted" } : LAYOUT_READY);
492
+ shell.hide();
493
+ return INERT_COMPONENT;
494
+ }
495
+ // Overlay ownership was decided before entering the inline lifecycle.
496
+ // An answer accepted before this mount closes the dialog on sight.
497
+ if (open.settled || signal?.aborted) {
498
+ done(open.settled ?? { answers: [], cancelled: true, source: "aborted" });
499
+ return INERT_COMPONENT;
500
+ }
501
+ tuiRef.current = tui;
502
+ let finished = false;
503
+ const finish = (result: QuestionnaireResult) => {
504
+ if (finished) return;
505
+ finished = true;
506
+ promotedHandle?.hide();
507
+ documentActive = false;
508
+ sessionRef.current?.dispose();
509
+ // The public custom lifecycle closes its own overlay handle.
510
+ done(result);
511
+ };
512
+ open.attach(finish);
513
+ if (signal) {
514
+ let abortDelivered = false;
515
+ const onAbort = () => {
516
+ if (abortDelivered) return;
517
+ abortDelivered = true;
518
+ finish({ answers: [], cancelled: true, source: "aborted" });
519
+ };
520
+ signal.addEventListener("abort", onAbort, { once: true });
521
+ removeAbortListener = () => signal.removeEventListener("abort", onAbort);
522
+ if (signal.aborted) onAbort();
523
+ if (abortDelivered) {
524
+ return {
525
+ render: () => [],
526
+ invalidate() {},
527
+ handleInput() {},
528
+ };
529
+ }
530
+ }
531
+ const cardTheme =
532
+ cardAccent === "off" ? theme : wrapCardTheme(theme, CARD_PALETTES[cardAccent]);
533
+ const session = new QuestionnaireSession({
534
+ tui,
535
+ theme: document || vertical ? theme : cardTheme,
536
+ document,
537
+ vertical,
538
+ allowNotes: request.allowNotes,
539
+ panelForm,
540
+ panel: initialPanel,
541
+ panelAutoSize: questionnaireConfig.panelHeight === undefined,
542
+ dockRows: initialDockRows,
543
+ onGeometry: (state) => panelMemory.set(sessionId, {
544
+ panelForm: state.panelForm ?? panelForm,
545
+ panel: state.panel ?? initialPanel,
546
+ dockRows: state.dockRows ?? null,
547
+ }),
548
+ onLimit: () => context.ui.notify?.(t("panel.min_size", "Panel is at its minimum size"), "info"),
549
+ params,
550
+ itemsByTab,
551
+ done: (outcome: QuestionnaireResult) => {
552
+ if (open.deadlineAt !== undefined && Date.now() >= open.deadlineAt) open.onTimeout?.();
553
+ else open.settle(outcome);
554
+ },
555
+ keybindings,
556
+ ...(request.previewLabel ? { previewLabel: request.previewLabel } : {}),
557
+ editInput: async (value) => {
558
+ try {
559
+ const [{ SettingsManager }, { editWithExternalEditor }] = await Promise.all([
560
+ import("@earendil-works/pi-coding-agent"),
561
+ import("./state/external-editor.js"),
562
+ ]);
563
+ const editorCommand = SettingsManager.create(context.cwd, undefined, {
564
+ projectTrusted: context.isProjectTrusted(),
565
+ }).getExternalEditorCommand();
566
+ if (!editorCommand) throw new Error("No external editor command is configured");
567
+ return await editWithExternalEditor(tui, editorCommand, value);
568
+ } catch (error) {
569
+ const message = error instanceof Error ? error.message : String(error);
570
+ context.ui.notify(`${t("editor.failed", "External editor failed")}: ${message}`, "error");
571
+ return undefined;
572
+ }
573
+ },
574
+ collapseKey,
575
+ });
576
+ sessionRef.current = session;
577
+ if (document || vertical) {
578
+ // Overlay mouse coordinates are local; the session keeps screen geometry for drags.
579
+ const card: Component & {focused: boolean} = {
580
+ get focused() { return session.component.focused === true; },
581
+ set focused(value) { session.component.focused = value; },
582
+ render: width => session.component.render(width),
583
+ invalidate: () => session.component.invalidate(),
584
+ handleInput: data => session.component.handleInput(data),
585
+ handleMouse: event => {
586
+ const panel = session.getFloatingPanel();
587
+ return session.component.handleMouse?.({...event, x: panel ? event.screenX ?? event.x + panel.col : event.x, y: panel ? event.screenY ?? event.y + panel.row : event.y});
588
+ },
589
+ };
590
+ const mounted = (document || vertical) && panelForm === "dock" ? {
591
+ ...card,
592
+ get focused() { return session.component.focused === true; },
593
+ set focused(value: boolean) { session.component.focused = value; },
594
+ render: (width: number) => {
595
+ if (!session.getFloatingPanel()) return card.render(width);
596
+ if (!promotedHandle) {
597
+ lifecycleOverlayOptions.visible = updateFloatLayout;
598
+ delete lifecycleOverlayOptions.nonCapturing;
599
+ updateFloatLayout();
600
+ promotedHandle = tui.showOverlay(card, lifecycleOverlayOptions);
601
+ }
602
+ return [];
603
+ },
604
+ } : card;
605
+ return mounted;
606
+ }
607
+
608
+ // Render the card as an in-transcript entry. The custom UI call keeps
609
+ // its completion/abort lifecycle through a zero-line, focusable shell.
610
+ const bridge = createActiveAskBridge();
611
+ bridge.install(session.component);
612
+ askEntryRef.current = createAskEntry(
613
+ pi,
614
+ params.questions,
615
+ () => {
616
+ session.component.invalidate();
617
+ tui.requestRender();
618
+ },
619
+ bridge,
620
+ );
621
+ session.setCollapseSink((collapsed) => {
622
+ const entry = askEntryRef.current;
623
+ if (entry && entry.data.kind === "active") {
624
+ entry.data.collapsed = collapsed;
625
+ session.component.invalidate();
626
+ tui.requestRender();
627
+ }
628
+ });
629
+ const shell: Component & { focused: boolean } = {
630
+ get focused() { return session.component.focused === true; },
631
+ set focused(value: boolean) { session.component.focused = value; },
632
+ render: () => [],
633
+ invalidate() {},
634
+ handleInput(data) {
635
+ if (matchesKey(data, "ctrl+c")) open.settle({ answers: [], cancelled: true });
636
+ },
637
+ };
638
+ return shell;
639
+ },
640
+ {
641
+ overlay: mountedOverlay,
642
+ overlayOptions: lifecycleOverlayOptions,
643
+ onHandle: (handle) => { lifecycleOverlayRef.current = handle; },
644
+ },
645
+ );
646
+ // Once started, wait for the host lifecycle, not only the accepted answer.
647
+ const result = await mounted;
648
+ if (result === LAYOUT_READY) return result;
649
+ if (result !== undefined) {
650
+ const entry = askEntryRef.current;
651
+ if (entry) {
652
+ entry.update({ kind: "superseded", questions: params.questions });
653
+ entry.release();
654
+ }
655
+ const terminalData: AskEntryData = result.cancelled
656
+ ? { kind: "cancelled", questions: params.questions, palette: cardAccent, timedOut: result.source === "timeout" }
657
+ : {
658
+ kind: "answered",
659
+ ...(result.source === "autopilot" ? { automatic: true } : {}),
660
+ questions: params.questions,
661
+ answers: result.answers,
662
+ ...(result.discussion ? { discussion: true, unanswered: result.unanswered } : {}),
663
+ ...(sessionRef.current ? { askPalette: sessionRef.current.palette } : {}),
664
+ ...(result.globalNote ? { globalNote: result.globalNote } : {}),
665
+ ...(request.notesAreFeedback ? { notesAreFeedback: true } : {}),
666
+ palette: cardAccent,
667
+ };
668
+ pi.appendEntry(EMMA_ASK_ENTRY_TYPE, terminalData);
669
+ return result;
670
+ }
671
+ return failed("no_custom_ui", ERROR_NO_CUSTOM_UI);
672
+ } finally {
673
+ promotedHandle?.hide();
674
+ documentActive = false;
675
+ sessionRef.current?.dispose();
676
+ removeAbortListener?.();
677
+ removeInputListener();
678
+ // Inline close may restore only a paste marker; restore expanded text after it ends.
679
+ if (inlineStarted && inlineDraft !== undefined) context.ui.setEditorText(inlineDraft);
680
+ }
681
+ },
682
+ );
683
+ }
684
+
685
+ export async function prewarmQuestionnaire(): Promise<void> {
686
+ const result = await loadQuestionnaireSession();
687
+ if (!result.ok) throw new Error(result.message);
688
+ }