questionnaire.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. /**
  2. * V2 multi-step questionnaire schema.
  3. *
  4. * Shared between daemon (runtime normalize/validate/serialize) and UI
  5. * (composer rendering). The schema is intentionally forward-compatible with
  6. * a future `PendingDecision.kind = "questionnaire"` substrate — `schemaVersion`
  7. * is pinned to `2` so consumers can branch cleanly when V3 lands.
  8. *
  9. * Reference: docs/tasks/multi-step-ask-answer-implementation-plan.html
  10. * (decision: composer replacement; one question per step; required by default;
  11. * Others always present; image optional with safe URL schemes only).
  12. */
  13. // ---------------------------------------------------------------------------
  14. // Step + option
  15. // ---------------------------------------------------------------------------
  16. /**
  17. * Single answer option presented to the user.
  18. *
  19. * `id` is stable so reply payloads can reference the same option after
  20. * navigation. `description` is optional extra hint text rendered next to the
  21. * option label (e.g. "the safer choice"). `image` is optional preview art
  22. * rendered above the label (e.g. screenshots of design candidates). All
  23. * string fields are sanitized — the UI MUST render them as plain text,
  24. * never as HTML.
  25. */
  26. export interface AskQuestionOption {
  27. id: string;
  28. label: string;
  29. description?: string;
  30. image?: AskQuestionImage;
  31. /** Canonical marker, emitted only for a Goal-owned questionnaire. */
  32. recommended?: true;
  33. }
  34. /**
  35. * Image attached to a question step.
  36. *
  37. * `src` must be either an `https://` URL or an app-served attachment URL
  38. * (paths starting with `/mavis/api/`). Raw `file://` paths are rejected by
  39. * the daemon normalizer to avoid local-fs exposure through the UI.
  40. */
  41. export interface AskQuestionImage {
  42. src: string;
  43. alt?: string;
  44. caption?: string;
  45. width?: number;
  46. height?: number;
  47. }
  48. /**
  49. * One step in the multi-step questionnaire. Each step holds exactly one
  50. * question with its own selection mode and options.
  51. *
  52. * Runtime invariants (enforced by the daemon normalizer):
  53. * - `allowOther` is always `true`
  54. * - `otherPlaceholder` is always the literal string `'Others...'`
  55. * - `required` defaults to `true`
  56. * - `selectionMode` defaults to `'single'`
  57. */
  58. export interface AskQuestionStep {
  59. id: string;
  60. header?: string;
  61. question: string;
  62. description?: string;
  63. image?: AskQuestionImage;
  64. selectionMode: 'single' | 'multiple';
  65. options: AskQuestionOption[];
  66. allowOther: true;
  67. otherPlaceholder: 'Others...';
  68. required: true;
  69. }
  70. // ---------------------------------------------------------------------------
  71. // Request
  72. // ---------------------------------------------------------------------------
  73. /**
  74. * Lifecycle status of a questionnaire request. Lives on the request payload
  75. * so UI consumers can render expired / superseded panels without an extra
  76. * round-trip.
  77. */
  78. export type AskQuestionnaireStatus =
  79. | 'pending'
  80. | 'answered'
  81. | 'expired'
  82. | 'superseded'
  83. | 'dismissed';
  84. /**
  85. * Tool-call metadata linking the questionnaire back to the LLM message and
  86. * tool call that produced it. Optional because some entrypoints (manual
  87. * injection, channel-bridge) may not have a tool call.
  88. */
  89. export interface AskQuestionnaireToolCall {
  90. message_id: string;
  91. call_id: string;
  92. }
  93. /**
  94. * Requester metadata used by the UI to scope the composer to the active
  95. * session and by the daemon to authorize reply submissions.
  96. */
  97. export interface AskQuestionnaireRequester {
  98. sessionId: string;
  99. runId?: string;
  100. toolCallId?: string;
  101. agentName?: string;
  102. }
  103. /**
  104. * Presentation hints — locked at V2. Kept on the request payload so future
  105. * versions can opt-out per-flow without breaking older renderers.
  106. */
  107. export interface AskQuestionnairePresentation {
  108. replaceComposer: boolean;
  109. showProgress: boolean;
  110. allowBackNavigation: boolean;
  111. }
  112. /** Shared expiry window for pending Questionnaire requests and Plan lifecycle fences. */
  113. export const QUESTIONNAIRE_TTL_MS = 24 * 60 * 60 * 1000;
  114. /** Machine-owned context identifying a questionnaire created while a Goal is active. */
  115. export type AskQuestionnairePurpose = 'goal';
  116. export interface QuestionnairePlanReview {
  117. markdown: string;
  118. path: string;
  119. }
  120. export type AskQuestionnairePlanReview = QuestionnairePlanReview;
  121. export type AskQuestionnaireMode = 'questionnaire' | 'feature-enable' | 'plan';
  122. export interface AskQuestionnaireModePayload {
  123. featureKey?: string;
  124. planReview?: QuestionnairePlanReview;
  125. }
  126. export interface OrdinaryQuestionnaireResponseOrigin {
  127. readonly kind: 'questionnaire-response';
  128. readonly requestId: string;
  129. readonly mode: 'questionnaire';
  130. readonly purpose: 'ordinary';
  131. }
  132. export function isOrdinaryQuestionnaireResponseOrigin(
  133. value: unknown,
  134. ): value is OrdinaryQuestionnaireResponseOrigin {
  135. if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;
  136. const origin = value as Readonly<Record<string, unknown>>;
  137. return (
  138. origin.kind === 'questionnaire-response' &&
  139. typeof origin.requestId === 'string' &&
  140. origin.requestId.length > 0 &&
  141. origin.mode === 'questionnaire' &&
  142. origin.purpose === 'ordinary' &&
  143. Object.keys(origin).length === 4
  144. );
  145. }
  146. /**
  147. * Full questionnaire request emitted by the daemon and consumed by the UI.
  148. * `schemaVersion` MUST be `2` for this shape; it is reserved so future V3
  149. * payloads can be distinguished at parse time.
  150. */
  151. export interface AskQuestionnaireRequest {
  152. schemaVersion: 2;
  153. id: string;
  154. /** Machine-owned flow classification; tool input cannot set this field. */
  155. purpose?: AskQuestionnairePurpose;
  156. /** Runtime-owned identity used to prevent an old questionnaire from driving a replacement Goal. */
  157. goalId?: string;
  158. title?: string;
  159. tool?: AskQuestionnaireToolCall;
  160. requester?: AskQuestionnaireRequester;
  161. presentation: AskQuestionnairePresentation;
  162. steps: AskQuestionStep[];
  163. /** Unix ms; consumer renders local-tz string. */
  164. expiresAt?: number;
  165. status?: AskQuestionnaireStatus;
  166. /** Unix ms; set by the daemon when the request is created. */
  167. createdAt?: number;
  168. /** Missing on historical rows and therefore interpreted as `questionnaire`. */
  169. mode?: AskQuestionnaireMode;
  170. /** Mode-specific data. Plan review Markdown lives only under this payload. */
  171. modePayload?: AskQuestionnaireModePayload;
  172. }
  173. // ---------------------------------------------------------------------------
  174. // Draft answer + reply
  175. // ---------------------------------------------------------------------------
  176. /**
  177. * Per-step draft answer held in the composer's local state.
  178. *
  179. * `selectedOptionIds` contains the IDs of all selected normal options (at
  180. * most one when the step is single-choice). `selectedOther` indicates the
  181. * `Others...` chip is active; `otherText` carries the free-form entry.
  182. * `skipped` is set when the user clicked the Skip button — it overrides
  183. * `step.required` at validation time and renders as `No answer` in the
  184. * chat summary.
  185. *
  186. * Single-choice + Others: the UI clears `selectedOptionIds` when Others is
  187. * picked, and clears `selectedOther` when a normal option is picked.
  188. * Multi-choice: Others can be combined with normal options freely.
  189. * Selecting any option or typing Others auto-clears `skipped`.
  190. */
  191. export interface AskQuestionnaireDraftAnswer {
  192. stepId: string;
  193. selectedOptionIds: string[];
  194. selectedOther: boolean;
  195. otherText?: string;
  196. skipped?: boolean;
  197. }
  198. /**
  199. * Final per-step answer in the reply payload. Same shape as the draft so
  200. * the UI can serialize directly without translation; the daemon enforces
  201. * the validation invariants on receipt.
  202. */
  203. export interface AskQuestionnaireReplyAnswer {
  204. stepId: string;
  205. selectedOptionIds: string[];
  206. selectedOther: boolean;
  207. otherText?: string;
  208. skipped?: boolean;
  209. }
  210. /**
  211. * Structured reply payload posted by the UI to
  212. * `POST /mavis/api/agent/:agentId/questionnaire/:requestId/reply`.
  213. *
  214. * `submittedAt` is a Unix ms timestamp captured at the moment the user
  215. * clicked Submit. Storage is ms throughout; consumers format locally per
  216. * AGENTS.md §1.
  217. */
  218. export interface AskQuestionnaireReplyPayload {
  219. schemaVersion: 2;
  220. requestId: string;
  221. answers: AskQuestionnaireReplyAnswer[];
  222. submittedAt: number;
  223. /**
  224. * Machine-owned settlement provenance. Runtime ignores any caller value and
  225. * writes the canonical source before persisting the reply.
  226. */
  227. source?: 'user' | 'automatic_timeout';
  228. }
  229. // ---------------------------------------------------------------------------
  230. // Tool input — what the LLM passes to ask_user
  231. // ---------------------------------------------------------------------------
  232. /**
  233. * Option as authored by the LLM (id optional — the runtime fills it in).
  234. * `image` is optional preview art rendered above the label inside the
  235. * option card; same scheme rules as the step-level image (HTTPS or
  236. * `/mavis/api/...` paths).
  237. */
  238. export interface AskUserToolOptionInput {
  239. id?: string;
  240. label: string;
  241. description?: string;
  242. image?: AskUserToolImageInput;
  243. /** Optional machine-readable recommendation marker authored by the model. */
  244. recommended?: boolean;
  245. }
  246. /**
  247. * Image attachment as authored by the LLM. The runtime validates the src
  248. * scheme; raw `file://` and other unsafe schemes are rejected.
  249. */
  250. export interface AskUserToolImageInput {
  251. src: string;
  252. alt?: string;
  253. caption?: string;
  254. }
  255. /**
  256. * Per-step input as authored by the LLM. `selectionMode` defaults to
  257. * `'single'` when omitted; `options` defaults to `[]` so a step with only an
  258. * `Others...` answer path is still valid.
  259. */
  260. export interface AskUserToolStepInput {
  261. id?: string;
  262. header?: string;
  263. question: string;
  264. description?: string;
  265. image?: AskUserToolImageInput;
  266. options?: AskUserToolOptionInput[];
  267. selectionMode?: 'single' | 'multiple';
  268. }
  269. /** Model-authored renderer modes carried by the generic ask_user wire contract. */
  270. export type AskUserToolMode = Exclude<AskQuestionnaireMode, 'plan'>;
  271. export interface AskUserToolModePayload {
  272. featureKey?: string;
  273. }
  274. /**
  275. * Full `ask_user` tool input authored by the LLM. The runtime normalizer
  276. * produces an {@link AskQuestionnaireRequest} from this shape.
  277. */
  278. export interface AskUserToolInput {
  279. /** `feature-enable` reuses the existing pause/reply lifecycle. */
  280. mode?: AskUserToolMode;
  281. modePayload?: AskUserToolModePayload;
  282. /**
  283. * Set true for a confirmation that an active Goal must never infer from its
  284. * timeout. Ordinary AskUser requests ignore this field because they never
  285. * auto-reply.
  286. */
  287. requiresExplicitResponse?: boolean;
  288. title?: string;
  289. steps?: AskUserToolStepInput[];
  290. }
  291. // ---------------------------------------------------------------------------
  292. // Constants
  293. // ---------------------------------------------------------------------------
  294. /** The literal placeholder enforced for every step's Others input. */
  295. export const ASK_OTHER_PLACEHOLDER = 'Others...' as const;
  296. /**
  297. * Tool name registered for the Mavis-owned `ask_user` flow. The daemon
  298. * marks this name as an interactive tool so the permission engine returns
  299. * `behavior: 'ask'`, which the legacy local-runtime plugin translates into a
  300. * `<questionnaire-ask>` XML instruction for the LLM to emit.
  301. */
  302. export const ASK_USER_TOOL_NAME = 'ask_user' as const;