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,135 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ ASK_USER_ANSWER_EVENT,
4
+ ASK_USER_ANSWER_RESULT_EVENT,
5
+ type AskUserAnswerRejectCode,
6
+ type AskUserAnswerResultEventPayload,
7
+ } from "./events.ts";
8
+ import { resolveExternalAnswer } from "./tool/external-answer.ts";
9
+ import type { QuestionData, QuestionnaireResult } from "./tool/types.js";
10
+
11
+ /** "rpc" while the RPC dialog walker owns the prompts — those cannot be answered from outside. */
12
+ export type AnswerHost = "tui" | "rpc";
13
+
14
+ /**
15
+ * One questionnaire an inbound answer may resolve, opened by the runner before its prompt event
16
+ * goes out and closed when the call ends. Both answer sources — the dialog's own completion and
17
+ * the inbound event — go through `settle`, so the first wins and a later one is refused instead
18
+ * of being reported as applied.
19
+ */
20
+ export class OpenQuestionnaire {
21
+ private result: QuestionnaireResult | undefined;
22
+ private deliver: ((result: QuestionnaireResult) => void) | undefined;
23
+ private resolveEarly!: (result: QuestionnaireResult) => void;
24
+ /** Resolves with an answer accepted while no dialog was mounted to take it. */
25
+ readonly answeredEarly = new Promise<QuestionnaireResult>((resolve) => {
26
+ this.resolveEarly = resolve;
27
+ });
28
+
29
+ readonly toolCallId: string;
30
+ readonly questions: readonly QuestionData[];
31
+ host: AnswerHost;
32
+ deadlineAt?: number;
33
+ onTimeout?: () => void;
34
+
35
+ constructor(toolCallId: string, questions: readonly QuestionData[], host: AnswerHost) {
36
+ this.toolCallId = toolCallId;
37
+ this.questions = questions;
38
+ this.host = host;
39
+ }
40
+
41
+ /** The accepted result, once settled. */
42
+ get settled(): QuestionnaireResult | undefined {
43
+ return this.result;
44
+ }
45
+
46
+ /** Hand over the mounted dialog's completion; later answers close the dialog through it. */
47
+ attach(done: (result: QuestionnaireResult) => void): void {
48
+ this.deliver = done;
49
+ }
50
+
51
+ /** First answer wins. False when this questionnaire is already settled. */
52
+ settle(result: QuestionnaireResult): boolean {
53
+ if (this.result) return false;
54
+ this.result = result;
55
+ if (this.deliver) this.deliver(result);
56
+ else this.resolveEarly(result);
57
+ return true;
58
+ }
59
+ }
60
+
61
+ export interface AnswerChannel {
62
+ open(toolCallId: string, questions: readonly QuestionData[], host: AnswerHost): OpenQuestionnaire;
63
+ close(questionnaire: OpenQuestionnaire): void;
64
+ }
65
+
66
+ /**
67
+ * One channel per Pi instance, created on first use. The channel is a session-scoped listener
68
+ * over the shared event bus, so registering it more than once per instance would duplicate every
69
+ * verdict; keying it by the instance keeps the questionnaire runner free of wiring.
70
+ */
71
+ const channels = new WeakMap<object, AnswerChannel>();
72
+
73
+ export function answerChannelFor(pi: ExtensionAPI): AnswerChannel {
74
+ const registered = channels.get(pi);
75
+ if (registered) return registered;
76
+ const channel = registerAnswerChannel(pi);
77
+ channels.set(pi, channel);
78
+ return channel;
79
+ }
80
+
81
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
82
+ typeof value === "object" && value !== null && !Array.isArray(value);
83
+
84
+ /**
85
+ * Listen for inbound answers and answer every attempt on the verdict channel. Open
86
+ * questionnaires are keyed by tool-call id: Pi runs tool calls in parallel, so several can be
87
+ * open at once and the emitter must name the one it answers.
88
+ */
89
+ export function registerAnswerChannel(pi: ExtensionAPI): AnswerChannel {
90
+ const open = new Map<string, OpenQuestionnaire>();
91
+
92
+ pi.events.on(ASK_USER_ANSWER_EVENT, (data: unknown) => {
93
+ const payload = isRecord(data) ? data : {};
94
+ const requestId = typeof payload.requestId === "string" ? payload.requestId : undefined;
95
+ const toolCallId = typeof payload.toolCallId === "string" ? payload.toolCallId : undefined;
96
+ const reply = (code?: AskUserAnswerRejectCode, reason?: string) => {
97
+ const verdict: AskUserAnswerResultEventPayload = {
98
+ ok: code === undefined,
99
+ ...(code ? { code, reason } : {}),
100
+ ...(requestId !== undefined ? { requestId } : {}),
101
+ ...(toolCallId !== undefined ? { toolCallId } : {}),
102
+ };
103
+ pi.events.emit(ASK_USER_ANSWER_RESULT_EVENT, verdict);
104
+ };
105
+
106
+ if (!isRecord(data)) return reply("invalid_payload", "payload must be an object");
107
+ if (payload.requestId !== undefined && requestId === undefined)
108
+ return reply("invalid_payload", "requestId must be a string");
109
+ if (toolCallId === undefined) return reply("invalid_payload", "toolCallId must be a string");
110
+ const target = open.get(toolCallId);
111
+ if (!target || target.settled) return reply("not_found", `no open questionnaire for tool call ${toolCallId}`);
112
+ if (target.deadlineAt !== undefined && Date.now() >= target.deadlineAt) {
113
+ if (target.onTimeout) target.onTimeout();
114
+ else target.settle({ answers: [], cancelled: true, source: "timeout" });
115
+ return reply("not_found", `questionnaire ${toolCallId} expired`);
116
+ }
117
+ if (target.host === "rpc") return reply("unsupported_host", "this host shows the questions in its own dialogs");
118
+
119
+ const outcome = resolveExternalAnswer(target.questions, payload);
120
+ if (!outcome.ok) return reply(outcome.code, outcome.reason);
121
+ if (!target.settle(outcome.result)) return reply("not_found", `tool call ${toolCallId} is already answered`);
122
+ reply();
123
+ });
124
+
125
+ return {
126
+ open(toolCallId, questions, host) {
127
+ const questionnaire = new OpenQuestionnaire(toolCallId, questions, host);
128
+ open.set(toolCallId, questionnaire);
129
+ return questionnaire;
130
+ },
131
+ close(questionnaire) {
132
+ if (open.get(questionnaire.toolCallId) === questionnaire) open.delete(questionnaire.toolCallId);
133
+ },
134
+ };
135
+ }
@@ -0,0 +1,180 @@
1
+ import * as fs from "node:fs";
2
+ import * as os from "node:os";
3
+ import * as path from "node:path";
4
+ import { clampFloat, FLOAT_EDGE_GAP, floatDefault, type PanelGeometry, type TerminalSize } from "./state/geometry.js";
5
+ import type { CardAccent } from "./view/card-theme.js";
6
+
7
+ export type CollapseKeySpec = string;
8
+ export type GuidanceFields = {
9
+ /** Replaces the tool description the model sees; a non-empty string replaces the built-in text entirely. */
10
+ description?: string;
11
+ /** One-line description of the tool in the system prompt — tunes how eagerly the model asks. */
12
+ promptSnippet?: string;
13
+ /** Usage guidelines given to the model, as a list of strings. */
14
+ promptGuidelines?: string[];
15
+ };
16
+ export type QuestionnaireConfig = {
17
+ collapseKey?: CollapseKeySpec;
18
+ locale?: string;
19
+ cardAccent?: CardAccent;
20
+ /** Preferred floating panel size in cells; the position is never persisted. */
21
+ panelWidth?: number;
22
+ panelHeight?: number;
23
+ /** Overridable model-facing guidance for the questionnaire tool. */
24
+ guidance?: GuidanceFields;
25
+ };
26
+
27
+ export const DEFAULT_COLLAPSE_KEY: CollapseKeySpec = "ctrl+]";
28
+ export const COLLAPSE_KEY_OFF: CollapseKeySpec = "off";
29
+ export const DEFAULT_CARD_ACCENT: CardAccent = "slate";
30
+ export const CARD_ACCENT_OFF: CardAccent = "off";
31
+
32
+ const SPECIAL_KEYS = new Set([
33
+ "escape", "esc", "enter", "return", "tab", "space", "backspace", "delete",
34
+ "insert", "clear", "home", "end", "pageup", "pagedown", "up", "down",
35
+ "left", "right", ...Array.from({ length: 12 }, (_, index) => `f${index + 1}`),
36
+ ]);
37
+ const MODIFIERS = new Set(["ctrl", "shift", "alt", "super"]);
38
+
39
+ function expandHome(value: string, home: string): string {
40
+ if (value === "~") return home;
41
+ if (value.startsWith("~/") || value.startsWith("~\\")) return path.join(home, value.slice(2));
42
+ return value;
43
+ }
44
+
45
+ function configHome(env: NodeJS.ProcessEnv, home: string): string {
46
+ const configured = expandHome(String(env.XDG_CONFIG_HOME ?? "").trim(), home);
47
+ return configured && path.isAbsolute(configured) ? configured : path.join(home, ".config");
48
+ }
49
+
50
+ export function questionnaireConfigPath(
51
+ env: NodeJS.ProcessEnv = process.env,
52
+ home = os.homedir(),
53
+ ): string {
54
+ return path.join(configHome(env, home), "vibe-emma", "questionnaire.json");
55
+ }
56
+
57
+ export const LOCALES = ["de", "en", "es", "fr", "pt", "pt-BR", "ru", "uk", "zh"] as const;
58
+
59
+ function validateGuidance(value: unknown): GuidanceFields | undefined {
60
+ if (value === undefined) return undefined;
61
+ if (!value || typeof value !== "object" || Array.isArray(value))
62
+ throw new Error("Unsupported Emma questionnaire guidance: expected an object");
63
+ const guidance = value as Record<string, unknown>;
64
+ if (Object.keys(guidance).some(key => !["description", "promptSnippet", "promptGuidelines"].includes(key)))
65
+ throw new Error("Unsupported Emma questionnaire guidance fields");
66
+ for (const key of ["description", "promptSnippet"] as const) {
67
+ const field = guidance[key];
68
+ if (field === undefined) continue;
69
+ if (typeof field !== "string" || !field.trim())
70
+ throw new Error(`Invalid Emma questionnaire guidance.${key}`);
71
+ }
72
+ const guidelines = guidance.promptGuidelines;
73
+ if (guidelines !== undefined && (!Array.isArray(guidelines) ||
74
+ guidelines.some(entry => typeof entry !== "string" || !entry.trim())))
75
+ throw new Error("Invalid Emma questionnaire guidance.promptGuidelines");
76
+ return guidance as GuidanceFields;
77
+ }
78
+
79
+ function validateConfig(value: unknown): QuestionnaireConfig {
80
+ if (!value || typeof value !== "object" || Array.isArray(value))
81
+ throw new Error("Unsupported Emma questionnaire config: expected an object");
82
+ const config = value as Record<string, unknown>;
83
+ if (Object.keys(config).some(key => !["collapseKey", "locale", "cardAccent", "panelWidth", "panelHeight", "guidance"].includes(key)))
84
+ throw new Error("Unsupported Emma questionnaire config fields");
85
+ if (config.collapseKey !== undefined && (typeof config.collapseKey !== "string" ||
86
+ (config.collapseKey !== "off" && !isValidCollapseKeySpec(config.collapseKey.toLowerCase()))))
87
+ throw new Error("Invalid Emma questionnaire collapseKey");
88
+ if (config.locale !== undefined && !LOCALES.includes(config.locale as typeof LOCALES[number]))
89
+ throw new Error("Unsupported Emma questionnaire locale");
90
+ if (config.cardAccent !== undefined && !["off", "slate", "sand"].includes(config.cardAccent as string))
91
+ throw new Error("Unsupported Emma questionnaire cardAccent");
92
+ for (const key of ["panelWidth", "panelHeight"] as const) {
93
+ const value = config[key];
94
+ if (value === undefined) continue;
95
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > 500)
96
+ throw new Error("Invalid Emma questionnaire " + key);
97
+ }
98
+ validateGuidance(config.guidance);
99
+ return config as QuestionnaireConfig;
100
+ }
101
+
102
+ function readObject(file: string): QuestionnaireConfig {
103
+ let content: string;
104
+ try { content = fs.readFileSync(file, "utf8"); }
105
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return {}; throw error; }
106
+ let value: unknown;
107
+ try { value = JSON.parse(content); }
108
+ catch { throw new Error("Invalid Emma questionnaire config JSON: " + file); }
109
+ return validateConfig(value);
110
+ }
111
+
112
+ export function loadQuestionnaireConfig(
113
+ env: NodeJS.ProcessEnv = process.env,
114
+ home = os.homedir(),
115
+ ): QuestionnaireConfig {
116
+ return readObject(questionnaireConfigPath(env, home));
117
+ }
118
+
119
+ export function saveQuestionnaireConfig(
120
+ patch: QuestionnaireConfig,
121
+ env: NodeJS.ProcessEnv = process.env,
122
+ home = os.homedir(),
123
+ ): string {
124
+ const file = questionnaireConfigPath(env, home);
125
+ const current = readObject(file);
126
+ const next = validateConfig({ ...current, ...patch });
127
+ fs.mkdirSync(path.dirname(file), { recursive: true });
128
+ const staged = `${file}.${process.pid}.${Date.now()}.tmp`;
129
+ fs.writeFileSync(staged, `${JSON.stringify(next, null, 2)}\n`, "utf8");
130
+ fs.renameSync(staged, file);
131
+ return file;
132
+ }
133
+
134
+ function isValidCollapseKeySpec(spec: string): boolean {
135
+ if (!spec || spec.startsWith("+") || spec.endsWith("+") || spec.includes("++")) return false;
136
+ const parts = spec.split("+");
137
+ const base = parts.at(-1) ?? "";
138
+ const modifiers = parts.slice(0, -1);
139
+ if (modifiers.length !== new Set(modifiers).size) return false;
140
+ if (!modifiers.every((modifier) => MODIFIERS.has(modifier))) return false;
141
+ return base.length === 1
142
+ ? /[a-z0-9_\-!@#$%^&*()|~`'":;,./<>?[\]{}=\\]/.test(base)
143
+ : SPECIAL_KEYS.has(base);
144
+ }
145
+
146
+ export function resolveCollapseKey(config: Pick<QuestionnaireConfig, "collapseKey">): CollapseKeySpec {
147
+ return config.collapseKey?.toLowerCase() ?? DEFAULT_COLLAPSE_KEY;
148
+ }
149
+
150
+ /** Model-facing guidance overrides; every field is optional and replaces its built-in text wholesale. */
151
+ export function resolveGuidance(config: Pick<QuestionnaireConfig, "guidance">): GuidanceFields {
152
+ return config.guidance ?? {};
153
+ }
154
+
155
+ export function resolveCardAccent(config: Pick<QuestionnaireConfig, "cardAccent">): CardAccent {
156
+ return config.cardAccent ?? DEFAULT_CARD_ACCENT;
157
+ }
158
+
159
+ /**
160
+ * Floating panel geometry for a new session: the persisted size (if any) anchored to the
161
+ * right edge of the current terminal. The position itself is never persisted, so a small
162
+ * terminal cannot inherit coordinates that no longer exist.
163
+ */
164
+ export function resolvePanelDefaults(
165
+ config: Pick<QuestionnaireConfig, "panelWidth" | "panelHeight">,
166
+ size: TerminalSize,
167
+ ): { panel: PanelGeometry } {
168
+ const base = floatDefault(size);
169
+ const w = config.panelWidth ?? base.w;
170
+ const h = config.panelHeight ?? base.h;
171
+ // The stored size is re-anchored to the right edge; only the size is a user preference.
172
+ return {
173
+ panel: clampFloat({
174
+ col: size.columns - w - FLOAT_EDGE_GAP,
175
+ row: Math.round((size.rows - h) / 2),
176
+ w,
177
+ h,
178
+ }, size),
179
+ };
180
+ }
@@ -0,0 +1,154 @@
1
+ /**
2
+ * Emma questionnaire event contract.
3
+ *
4
+ * STABILITY POLICY — every channel lives in the `emma:*` namespace and follows Pi's
5
+ * cross-process convention:
6
+ *
7
+ * 1. Channel names are immutable. Once shipped, never rename.
8
+ * 2. Payload changes are append-only. Listeners tolerate unknown fields; new
9
+ * fields ship as optional and payloads stay JSON-safe.
10
+ * 3. Breaking changes require a NEW channel (e.g. `emma:ask-user:prompt.v2`).
11
+ * 4. No `version` field inside payloads — version via channel name only.
12
+ */
13
+
14
+ export const ASK_USER_PROMPT_EVENT = "emma:ask-user:prompt" as const;
15
+
16
+ export interface AskUserPromptEventPayload {
17
+ questions: ReadonlyArray<AskUserPromptQuestion>;
18
+ /**
19
+ * The tool call's id — always set. Names this questionnaire on the blocked and
20
+ * answer channels, so several questionnaires open at once stay distinguishable.
21
+ */
22
+ toolCallId?: string;
23
+ /**
24
+ * Optional Unix timestamp in milliseconds. A host that claims the prompt should
25
+ * stop accepting input by this time and wait for the closed event. Older
26
+ * subscribers can ignore the field.
27
+ */
28
+ deadlineAt?: number;
29
+
30
+ /**
31
+ * Presentation ownership claim. Append-only: a listener that ignores this field
32
+ * leaves Emma's terminal questionnaire in charge, exactly as before.
33
+ *
34
+ * `emit` is synchronous but Pi wraps listeners in async functions and discards
35
+ * return values, so ownership is reported through this callable instead. Invoke
36
+ * it at most once: the first `true` wins, later calls are ignored. Only claim a
37
+ * prompt you intend to answer over `ASK_USER_ANSWER_EVENT` — claiming without an
38
+ * answer leaves the caller waiting.
39
+ */
40
+ claim?: (claimed: boolean) => boolean;
41
+ }
42
+
43
+ export const ASK_USER_CLOSED_EVENT = "emma:ask-user:closed" as const;
44
+
45
+ export interface AskUserClosedEventPayload {
46
+ toolCallId: string;
47
+ status: "answered" | "cancelled" | "timeout" | "disconnected" | "aborted";
48
+ source?: "timeout" | "autopilot";
49
+ answers?: ReadonlyArray<{ questionIndex: number; optionIndexes: readonly number[] }>;
50
+ }
51
+
52
+ /**
53
+ * Emitted while the questionnaire is awaiting user input (TUI and RPC dialog walker).
54
+ * Cleared with `{ active: false }` in `finally` so listeners can tell
55
+ * blocked-on-human apart from working.
56
+ */
57
+ export const ASK_USER_BLOCKED_EVENT = "emma:ask-user:blocked" as const;
58
+
59
+ export interface AskUserBlockedEventPayload {
60
+ /** True while input is awaited; false when the wait ends (answer, cancel, or error). */
61
+ active: boolean;
62
+ /** The tool call's id — always set. Pair `active: false` with its prompt by this id. */
63
+ toolCallId?: string;
64
+ }
65
+
66
+ export interface AskUserPromptQuestion {
67
+ /** Zero-based option indexes preselected in the host card. */
68
+ recommended?: readonly number[];
69
+
70
+ /** The full question text, exactly as the agent authored it. */
71
+ question: string;
72
+ /** The short chip/tag shown next to the question. */
73
+ header: string;
74
+ /** Border title, when the agent provided one. */
75
+ title?: string;
76
+ /** Question-level preview content (markdown), when the agent provided one. */
77
+ preview?: string;
78
+ /** True iff the user may pick multiple options. Normalized from optional. */
79
+ multiSelect: boolean;
80
+ options: ReadonlyArray<AskUserPromptOption>;
81
+ }
82
+
83
+ export interface AskUserPromptOption {
84
+ label: string;
85
+ description?: string;
86
+ /** True iff the option carries rich preview content. Kept for compatibility. */
87
+ hasPreview: boolean;
88
+ /** Rich preview content for the option, when provided. */
89
+ preview?: string;
90
+ }
91
+
92
+ /**
93
+ * INBOUND — answers or cancels one open questionnaire without the keystroke path, so a
94
+ * program driving Pi from outside (pane supervisor, phone or web bridge, test harness)
95
+ * need not synthesize keys against a rendered dialog.
96
+ *
97
+ * `toolCallId` names the questionnaire: the id carried by its prompt event. It is accepted
98
+ * from the moment that prompt is emitted until the questionnaire closes; the first answer
99
+ * wins, whether typed in the terminal or sent here.
100
+ *
101
+ * Validation is strict and all-or-nothing: every question answered once, every index in
102
+ * range — otherwise nothing is applied and the dialog stays open. A partially applied
103
+ * answer would reach the model indistinguishable from one the user gave.
104
+ */
105
+ export const ASK_USER_ANSWER_EVENT = "emma:ask-user:answer" as const;
106
+
107
+ export interface AskUserAnswerEventPayload {
108
+ /** The questionnaire to answer — `toolCallId` from its prompt event. */
109
+ toolCallId: string;
110
+ /** Echoed back on the verdict so an emitter can pair it with this request. */
111
+ requestId?: string;
112
+ /** One entry per question. Omitted (or empty) only with `cancel`. */
113
+ answers?: ReadonlyArray<AskUserAnswerEntry>;
114
+ /** Note for the whole questionnaire, like the submit screen's global note. */
115
+ globalNote?: string;
116
+ /** Decline the questionnaire, as Esc does: the model is told the user declined. */
117
+ cancel?: boolean;
118
+ }
119
+
120
+ /** One question's answer: single-select takes one option index or custom text, multi takes both. */
121
+ export interface AskUserAnswerEntry {
122
+ /** 0-based index into the prompt's `questions`. */
123
+ questionIndex: number;
124
+ /** 0-based, distinct indices into the question's `options`. */
125
+ optionIndexes?: readonly number[];
126
+ /** Custom answer — what the appended input row produces. Must not be blank. */
127
+ text?: string;
128
+ /** Note on this question, like the one the notes key attaches in the dialog. */
129
+ notes?: string;
130
+ }
131
+
132
+ /** Verdict for an `ASK_USER_ANSWER_EVENT`. One per attempt, accepted or not. */
133
+ export const ASK_USER_ANSWER_RESULT_EVENT = "emma:ask-user:answer-result" as const;
134
+
135
+ /**
136
+ * Why an answer was refused — branch on this, not on `reason`:
137
+ * - `not_found`: no open questionnaire has that `toolCallId` (never opened, already closed, or expired).
138
+ * - `invalid_payload`: a field is missing or has the wrong type.
139
+ * - `invalid_answer`: well-formed, but does not fit the questions (missing, duplicated, out of range).
140
+ * - `unsupported_host`: the questionnaire runs in an RPC host's own dialogs, which cannot be answered here.
141
+ */
142
+ export type AskUserAnswerRejectCode = "not_found" | "invalid_payload" | "invalid_answer" | "unsupported_host";
143
+
144
+ export interface AskUserAnswerResultEventPayload {
145
+ ok: boolean;
146
+ /** Set when `ok` is false. */
147
+ code?: AskUserAnswerRejectCode;
148
+ /** Human-readable detail for logs. Wording may change — do not parse it. */
149
+ reason?: string;
150
+ /** Echoed from the request when it was a string. */
151
+ requestId?: string;
152
+ /** Echoed from the request when it was a string. */
153
+ toolCallId?: string;
154
+ }