@case-framework/survey-assistant 0.7.0 → 0.9.0

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 (142) hide show
  1. package/README.md +58 -3
  2. package/dist/{attachments-B0hg3vpT.mjs → attachments-BuNni5vB.mjs} +1 -1
  3. package/dist/{attachments-B0hg3vpT.mjs.map → attachments-BuNni5vB.mjs.map} +1 -1
  4. package/dist/{authoring-references-BJQ_1nMX.mjs → authoring-references-CmwLc_C8.mjs} +49 -32
  5. package/dist/authoring-references-CmwLc_C8.mjs.map +1 -0
  6. package/dist/capabilities-D55dq-fO.mjs +582 -0
  7. package/dist/capabilities-D55dq-fO.mjs.map +1 -0
  8. package/dist/capabilities-default.d.mts +5 -12
  9. package/dist/capabilities-default.d.mts.map +1 -1
  10. package/dist/capabilities-default.mjs +2 -411
  11. package/dist/capabilities-z95e1mti.d.mts +117 -0
  12. package/dist/capabilities-z95e1mti.d.mts.map +1 -0
  13. package/dist/{constants-0UHGFcRJ.mjs → constants-Ct-vv9cu.mjs} +1 -1
  14. package/dist/{constants-0UHGFcRJ.mjs.map → constants-Ct-vv9cu.mjs.map} +1 -1
  15. package/dist/{constants-Be91Gay9.d.mts → constants-HL_klgJl.d.mts} +7 -28
  16. package/dist/constants-HL_klgJl.d.mts.map +1 -0
  17. package/dist/{controller-proxy-BH05e-C2.mjs → controller-proxy-BQ1YsVxJ.mjs} +12 -21
  18. package/dist/controller-proxy-BQ1YsVxJ.mjs.map +1 -0
  19. package/dist/controller-proxy-Cmzdr9tV.d.mts +65 -0
  20. package/dist/controller-proxy-Cmzdr9tV.d.mts.map +1 -0
  21. package/dist/default-D22AKTqE.mjs +233 -0
  22. package/dist/default-D22AKTqE.mjs.map +1 -0
  23. package/dist/{digest-SJmoYVaK.d.mts → digest-FnTTDBq2.d.mts} +2 -3
  24. package/dist/digest-FnTTDBq2.d.mts.map +1 -0
  25. package/dist/digest.d.mts +1 -1
  26. package/dist/digest.mjs.map +1 -1
  27. package/dist/engine-D950TfvC.mjs +3098 -0
  28. package/dist/engine-D950TfvC.mjs.map +1 -0
  29. package/dist/engine.d.mts +4 -3
  30. package/dist/engine.mjs +3 -3
  31. package/dist/{fair-guidance-CRYCRxQm.mjs → fair-guidance-BmO4PswW.mjs} +1 -1
  32. package/dist/{fair-guidance-CRYCRxQm.mjs.map → fair-guidance-BmO4PswW.mjs.map} +1 -1
  33. package/dist/{index-l_EK4yK7.d.mts → index-B8TLBd1G.d.mts} +18 -72
  34. package/dist/index-B8TLBd1G.d.mts.map +1 -0
  35. package/dist/index-CaX3hZmr.d.mts +23813 -0
  36. package/dist/index-CaX3hZmr.d.mts.map +1 -0
  37. package/dist/{index-x0qprHgK.d.mts → index-CeUlGkoU.d.mts} +58 -28
  38. package/dist/index-CeUlGkoU.d.mts.map +1 -0
  39. package/dist/{index-nhrgbgO5.d.mts → index-DYHdvSE8.d.mts} +347 -88
  40. package/dist/index-DYHdvSE8.d.mts.map +1 -0
  41. package/dist/lifecycle-DFzxVxpq.d.mts +54346 -0
  42. package/dist/lifecycle-DFzxVxpq.d.mts.map +1 -0
  43. package/dist/{memory-thread-repository-KWHQWFEW.mjs → memory-thread-repository-DmLadygY.mjs} +60 -30
  44. package/dist/memory-thread-repository-DmLadygY.mjs.map +1 -0
  45. package/dist/protocol-BQ7uIDYT.mjs +569 -0
  46. package/dist/protocol-BQ7uIDYT.mjs.map +1 -0
  47. package/dist/protocol.d.mts +4 -4
  48. package/dist/protocol.mjs +4 -3
  49. package/dist/{react-B3ybjJ-X.mjs → react-DybJ5pWw.mjs} +159 -46
  50. package/dist/react-DybJ5pWw.mjs.map +1 -0
  51. package/dist/react-integration.d.mts +2 -2
  52. package/dist/react-integration.mjs +2 -2
  53. package/dist/react.d.mts +3 -3
  54. package/dist/react.mjs +3 -3
  55. package/dist/references/assistant-operations.md +224 -180
  56. package/dist/references/core-rules.md +6 -3
  57. package/dist/references/element-types.md +189 -0
  58. package/dist/references/expressions.md +307 -168
  59. package/dist/references/fair-by-design.md +9 -9
  60. package/dist/references/follow-ups.md +151 -0
  61. package/dist/references/localization.md +26 -12
  62. package/dist/references/response-variables.md +38 -0
  63. package/dist/references/rich-text-content.md +22 -43
  64. package/dist/references/source-material-surveys.md +20 -24
  65. package/dist/references/survey-data-model.md +36 -102
  66. package/dist/{request-context-CG4SWijt.mjs → request-context-KVh8VjgH.mjs} +4 -10
  67. package/dist/request-context-KVh8VjgH.mjs.map +1 -0
  68. package/dist/{request-guardrails-TmgQtqp4.mjs → request-guardrails-C0ugBOp0.mjs} +6 -5
  69. package/dist/request-guardrails-C0ugBOp0.mjs.map +1 -0
  70. package/dist/server-agent.d.mts +62 -43
  71. package/dist/server-agent.d.mts.map +1 -1
  72. package/dist/server-agent.mjs +73 -40
  73. package/dist/server-agent.mjs.map +1 -1
  74. package/dist/server-runtime.d.mts +24 -42
  75. package/dist/server-runtime.d.mts.map +1 -1
  76. package/dist/server-runtime.mjs +12 -12
  77. package/dist/server-runtime.mjs.map +1 -1
  78. package/dist/server-tasks.d.mts +2 -2
  79. package/dist/server-tasks.mjs +2 -313
  80. package/dist/server-tools.d.mts +1 -1
  81. package/dist/server-tools.mjs +1 -1
  82. package/dist/server.d.mts +14 -36
  83. package/dist/server.d.mts.map +1 -1
  84. package/dist/server.mjs +5 -5
  85. package/dist/server.mjs.map +1 -1
  86. package/dist/storage-postgres.d.mts +9 -25
  87. package/dist/storage-postgres.d.mts.map +1 -1
  88. package/dist/storage-postgres.mjs +5 -4
  89. package/dist/storage-postgres.mjs.map +1 -1
  90. package/dist/tasks-Coh5N027.mjs +397 -0
  91. package/dist/tasks-Coh5N027.mjs.map +1 -0
  92. package/dist/{tasks-CYqrcaRO.d.mts → tasks-wb9M-bak.d.mts} +25 -41
  93. package/dist/tasks-wb9M-bak.d.mts.map +1 -0
  94. package/dist/thread-documents-DrHbaXqP.d.mts +119 -0
  95. package/dist/thread-documents-DrHbaXqP.d.mts.map +1 -0
  96. package/dist/{thread-handlers-DBAaU7BA.d.mts → thread-handlers-C3Iya92v.d.mts} +9 -40
  97. package/dist/thread-handlers-C3Iya92v.d.mts.map +1 -0
  98. package/dist/{tools-BvSovehT.mjs → tools-D0KBDolR.mjs} +677 -459
  99. package/dist/tools-D0KBDolR.mjs.map +1 -0
  100. package/dist/turn-survey-draft-B34lggSG.d.mts +185 -0
  101. package/dist/turn-survey-draft-B34lggSG.d.mts.map +1 -0
  102. package/dist/ui.css +1 -1
  103. package/dist/ui.d.mts +15 -54
  104. package/dist/ui.d.mts.map +1 -1
  105. package/dist/ui.mjs +203 -156
  106. package/dist/ui.mjs.map +1 -1
  107. package/docs/integration.md +11 -1
  108. package/package.json +41 -36
  109. package/dist/authoring-references-BJQ_1nMX.mjs.map +0 -1
  110. package/dist/capabilities-1KNnNO1_.mjs +0 -73
  111. package/dist/capabilities-1KNnNO1_.mjs.map +0 -1
  112. package/dist/capabilities-DVTfogjv.d.mts +0 -193
  113. package/dist/capabilities-DVTfogjv.d.mts.map +0 -1
  114. package/dist/capabilities-default.mjs.map +0 -1
  115. package/dist/constants-Be91Gay9.d.mts.map +0 -1
  116. package/dist/controller-proxy-BH05e-C2.mjs.map +0 -1
  117. package/dist/controller-proxy-Bd0ZHBPF.d.mts +0 -85
  118. package/dist/controller-proxy-Bd0ZHBPF.d.mts.map +0 -1
  119. package/dist/digest-SJmoYVaK.d.mts.map +0 -1
  120. package/dist/engine-Bo85Oyj0.mjs +0 -6723
  121. package/dist/engine-Bo85Oyj0.mjs.map +0 -1
  122. package/dist/index-Tnqv-yKW.d.mts +0 -777
  123. package/dist/index-Tnqv-yKW.d.mts.map +0 -1
  124. package/dist/index-l_EK4yK7.d.mts.map +0 -1
  125. package/dist/index-nhrgbgO5.d.mts.map +0 -1
  126. package/dist/index-x0qprHgK.d.mts.map +0 -1
  127. package/dist/lifecycle-Bx0aq_4S.d.mts +0 -529
  128. package/dist/lifecycle-Bx0aq_4S.d.mts.map +0 -1
  129. package/dist/memory-thread-repository-KWHQWFEW.mjs.map +0 -1
  130. package/dist/protocol-BhzQbx81.mjs +0 -1173
  131. package/dist/protocol-BhzQbx81.mjs.map +0 -1
  132. package/dist/react-B3ybjJ-X.mjs.map +0 -1
  133. package/dist/references/embedded-forms.md +0 -126
  134. package/dist/references/item-types.md +0 -407
  135. package/dist/request-context-CG4SWijt.mjs.map +0 -1
  136. package/dist/request-guardrails-TmgQtqp4.mjs.map +0 -1
  137. package/dist/server-tasks.mjs.map +0 -1
  138. package/dist/tasks-CYqrcaRO.d.mts.map +0 -1
  139. package/dist/thread-documents-rmd6nyX9.d.mts +0 -107
  140. package/dist/thread-documents-rmd6nyX9.d.mts.map +0 -1
  141. package/dist/thread-handlers-DBAaU7BA.d.mts.map +0 -1
  142. package/dist/tools-BvSovehT.mjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"protocol-BhzQbx81.mjs","names":[],"sources":["../src/protocol/sanitization.ts","../src/protocol/errors.ts","../src/protocol/content.ts","../src/protocol/operations.ts","../src/protocol/capabilities.ts","../src/protocol/document.ts","../src/protocol/threads.ts","../src/protocol/tasks.ts","../src/protocol/models.ts","../src/protocol/lifecycle.ts"],"sourcesContent":["export const MAX_USER_ERROR_MESSAGE_LENGTH = 700;\n\nconst CONTROL_CHARACTERS = /[\\u0000-\\u0008\\u000b\\u000c\\u000e-\\u001f\\u007f]/g;\nconst DATA_URL = /data:[^;,\\s]+;base64,[a-z0-9+/=_-]+/gi;\nconst BEARER_TOKEN = /\\bbearer\\s+[a-z0-9._~+/-]{8,}/gi;\nconst OPENAI_KEY = /\\bsk-(?:proj-)?[a-z0-9_-]{8,}/gi;\nconst AUTHORIZATION_VALUE = /(authorization\\s*[:=]\\s*)[^\\s,;]+/gi;\nconst API_KEY_VALUE = /((?:api[-_ ]?key|token|secret)\\s*[:=]\\s*)[^\\s,;]+/gi;\n\nexport const redactSurveyAssistantDiagnosticSecrets = (value: string): string =>\n value\n .replace(CONTROL_CHARACTERS, \"\")\n .replace(DATA_URL, \"[data URL omitted]\")\n .replace(BEARER_TOKEN, \"Bearer [credential omitted]\")\n .replace(OPENAI_KEY, \"[credential omitted]\")\n .replace(AUTHORIZATION_VALUE, \"$1[credential omitted]\")\n .replace(API_KEY_VALUE, \"$1[credential omitted]\");\n\nexport const sanitizeSurveyAssistantDiagnosticText = (\n value: string,\n maximum = MAX_USER_ERROR_MESSAGE_LENGTH,\n): string => {\n const normalized = redactSurveyAssistantDiagnosticSecrets(value).replace(/\\s+/g, \" \").trim();\n\n if (normalized.length <= maximum) return normalized;\n return `${normalized.slice(0, Math.max(0, maximum - 1))}…`;\n};\n\nexport const isSurveyAssistantSensitiveMetadataKey = (key: string): boolean => {\n const normalized = key.toLocaleLowerCase();\n return (\n normalized.includes(\"authorization\") ||\n normalized.includes(\"credential\") ||\n normalized.includes(\"encrypted\") ||\n normalized.includes(\"password\") ||\n normalized.includes(\"redacted\") ||\n normalized.includes(\"secret\") ||\n normalized.includes(\"signature\") ||\n normalized === \"token\" ||\n normalized.endsWith(\"token\") ||\n normalized.includes(\"api_key\") ||\n normalized.includes(\"apikey\")\n );\n};\n\nexport const getSurveyAssistantEmbeddedBinaryMarker = (\n value: unknown,\n parent?: Record<string, unknown>,\n key?: string,\n): { characters: number; redacted: \"base64\" | \"data-url\" } | undefined => {\n if (typeof value !== \"string\") return undefined;\n if (key === \"data\" && parent?.type === \"embedded\" && parent.encoding === \"base64\") {\n return { characters: value.length, redacted: \"base64\" };\n }\n if (value.length > 512 && /^data:[^;,]+;base64,/.test(value)) {\n return { characters: value.length, redacted: \"data-url\" };\n }\n return undefined;\n};\n","import { z } from \"zod\";\nimport {\n MAX_USER_ERROR_MESSAGE_LENGTH,\n sanitizeSurveyAssistantDiagnosticText,\n} from \"./sanitization\";\n\nexport const surveyAssistantErrorCodeSchema = z.enum([\n \"attachment_unavailable\",\n \"authorization_failed\",\n \"model_unavailable\",\n \"rate_limited\",\n \"request_failed\",\n]);\n\nexport type SurveyAssistantErrorCode = z.infer<typeof surveyAssistantErrorCodeSchema>;\n\nexport const surveyAssistantErrorInfoSchema = z.object({\n code: surveyAssistantErrorCodeSchema,\n detail: z.string().optional(),\n retryable: z.boolean().optional(),\n upstreamStatus: z.number().int().min(100).max(599).optional(),\n providerRequestId: z.string().trim().min(1).max(240).optional(),\n providerMessage: z.string().max(MAX_USER_ERROR_MESSAGE_LENGTH).optional(),\n});\n\nexport type SurveyAssistantErrorInfo = z.infer<typeof surveyAssistantErrorInfoSchema>;\n\nexport const isSurveyAssistantErrorRetryable = (\n error: Pick<SurveyAssistantErrorInfo, \"code\" | \"retryable\" | \"upstreamStatus\">,\n httpStatus?: number,\n): boolean => {\n if (error.retryable !== undefined) return error.retryable;\n if (error.code === \"rate_limited\") return true;\n\n const status = httpStatus ?? error.upstreamStatus;\n if (error.code === \"request_failed\") return status === undefined || status >= 500;\n return error.code === \"attachment_unavailable\" && status !== undefined && status >= 500;\n};\n\nconst ERROR_PREFIX = \"case-survey-assistant-error:\";\n\nexport const serializeSurveyAssistantError = (error: SurveyAssistantErrorInfo): string =>\n `${ERROR_PREFIX}${JSON.stringify(surveyAssistantErrorInfoSchema.parse(error))}`;\n\nexport const parseSurveyAssistantError = (value: unknown): SurveyAssistantErrorInfo => {\n if (typeof value === \"object\" && value !== null && \"code\" in value) {\n const detail =\n \"detail\" in value && typeof value.detail === \"string\"\n ? value.detail\n : \"message\" in value && typeof value.message === \"string\"\n ? value.message\n : undefined;\n const parsed = surveyAssistantErrorInfoSchema.safeParse({\n code: value.code,\n detail: detail\n ? sanitizeSurveyAssistantDiagnosticText(detail, MAX_USER_ERROR_MESSAGE_LENGTH)\n : undefined,\n retryable:\n \"retryable\" in value && typeof value.retryable === \"boolean\" ? value.retryable : undefined,\n upstreamStatus:\n \"upstreamStatus\" in value && typeof value.upstreamStatus === \"number\"\n ? value.upstreamStatus\n : undefined,\n providerRequestId:\n \"providerRequestId\" in value && typeof value.providerRequestId === \"string\"\n ? sanitizeSurveyAssistantDiagnosticText(value.providerRequestId, 240)\n : undefined,\n providerMessage:\n \"providerMessage\" in value && typeof value.providerMessage === \"string\"\n ? sanitizeSurveyAssistantDiagnosticText(\n value.providerMessage,\n MAX_USER_ERROR_MESSAGE_LENGTH,\n )\n : undefined,\n });\n if (parsed.success) return parsed.data;\n }\n\n const message =\n value instanceof Error\n ? value.message\n : typeof value === \"string\"\n ? value\n : typeof value === \"object\" && value !== null && \"message\" in value\n ? String(value.message)\n : \"\";\n\n if (message.startsWith(ERROR_PREFIX)) {\n try {\n const parsed = surveyAssistantErrorInfoSchema.safeParse(\n JSON.parse(message.slice(ERROR_PREFIX.length)),\n );\n if (parsed.success) return parsed.data;\n } catch {\n // Fall through to the stable generic category.\n }\n }\n\n return {\n code: \"request_failed\",\n ...(message.trim()\n ? { detail: sanitizeSurveyAssistantDiagnosticText(message, MAX_USER_ERROR_MESSAGE_LENGTH) }\n : {}),\n };\n};\n","import { z } from \"zod\";\nimport type { Content, JsonValue as CoreJsonValue } from \"@case-framework/survey-core\";\n\nexport const jsonValueSchema: z.ZodType<CoreJsonValue> = z.lazy(() =>\n z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.null(),\n z.array(jsonValueSchema),\n z.record(z.string(), jsonValueSchema),\n ]),\n);\n\nconst contentAttributesSchema = z.record(z.string(), jsonValueSchema);\n\nconst richTextStyleSchema = z.object({\n weight: z.enum([\"strong\", \"normal\"]).optional(),\n italic: z.enum([\"italic\", \"normal\"]).optional(),\n underline: z.enum([\"underline\", \"none\"]).optional(),\n color: z.enum([\"primary\", \"accent\", \"default\"]).optional(),\n});\n\nconst richTextTextInlineSchema = z.object({\n type: z.literal(\"text\"),\n text: z.string().max(20_000),\n style: richTextStyleSchema.optional(),\n attrs: contentAttributesSchema.optional(),\n});\n\nconst richTextTemplateInlineSchema = z.object({\n type: z.literal(\"template\"),\n key: z.string().min(1).max(240),\n style: richTextStyleSchema.optional(),\n attrs: contentAttributesSchema.optional(),\n});\n\nconst richTextLineBreakInlineSchema = z.object({\n type: z.literal(\"lineBreak\"),\n attrs: contentAttributesSchema.optional(),\n});\n\nconst richTextLinkChildInlineSchema = z.discriminatedUnion(\"type\", [\n richTextTextInlineSchema,\n richTextTemplateInlineSchema,\n richTextLineBreakInlineSchema,\n]);\n\nconst richTextLinkInlineSchema = z.object({\n type: z.literal(\"link\"),\n href: z.string().min(1).max(2000),\n target: z.string().max(120).nullable().optional(),\n rel: z.string().max(240).nullable().optional(),\n title: z.string().max(1000).nullable().optional(),\n attrs: contentAttributesSchema.optional(),\n children: z.array(richTextLinkChildInlineSchema).max(200),\n});\n\nconst richTextInlineExtensionSchema = z.object({\n type: z.literal(\"inlineExtension\"),\n name: z.string().min(1).max(120),\n attrs: contentAttributesSchema.optional(),\n});\n\nconst richTextInlineSchema = z.discriminatedUnion(\"type\", [\n richTextTextInlineSchema,\n richTextTemplateInlineSchema,\n richTextLinkInlineSchema,\n richTextLineBreakInlineSchema,\n richTextInlineExtensionSchema,\n]);\n\nconst textAlignmentSchema = z.enum([\"left\", \"center\", \"right\", \"justify\"]);\n\nconst richTextParagraphBlockSchema = z.object({\n type: z.literal(\"paragraph\"),\n children: z.array(richTextInlineSchema).max(500),\n alignment: textAlignmentSchema.optional(),\n attrs: contentAttributesSchema.optional(),\n});\n\nconst richTextHeadingBlockSchema = z.object({\n type: z.literal(\"heading\"),\n level: z.union([z.literal(1), z.literal(2)]),\n children: z.array(richTextInlineSchema).max(500),\n alignment: textAlignmentSchema.optional(),\n attrs: contentAttributesSchema.optional(),\n});\n\nconst richTextListItemBlockSchema = z.object({\n type: z.literal(\"listItem\"),\n children: z.array(richTextParagraphBlockSchema).max(100),\n attrs: contentAttributesSchema.optional(),\n});\n\nconst richTextBulletListBlockSchema = z.object({\n type: z.literal(\"bulletList\"),\n items: z.array(richTextListItemBlockSchema).max(100),\n attrs: contentAttributesSchema.optional(),\n});\n\nconst richTextImageDimensionSchema = z.union([\n z.object({ unit: z.literal(\"px\"), value: z.number().finite().nonnegative() }),\n z.object({ unit: z.literal(\"%\"), value: z.number().finite().nonnegative() }),\n]);\n\nconst richTextImageSourceSchema = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"asset\"), assetId: z.string().min(1).max(240) }),\n z.object({ type: z.literal(\"external\"), url: z.string().min(1).max(2000) }),\n]);\n\nconst richTextImageBlockSchema = z.object({\n type: z.literal(\"image\"),\n source: richTextImageSourceSchema,\n alt: z.string().max(2000).optional(),\n caption: z.array(richTextParagraphBlockSchema).max(20).optional(),\n size: z\n .object({\n width: richTextImageDimensionSchema.optional(),\n height: richTextImageDimensionSchema.optional(),\n maxWidth: richTextImageDimensionSchema.optional(),\n maxHeight: richTextImageDimensionSchema.optional(),\n })\n .optional(),\n alignment: textAlignmentSchema.optional(),\n attrs: contentAttributesSchema.optional(),\n});\n\nconst richTextInfoBoxBlockSchema = z.object({\n type: z.literal(\"infoBox\"),\n tone: z.enum([\"info\", \"warning\"]).optional(),\n title: z.array(richTextInlineSchema).max(100).optional(),\n collapsible: z.boolean().optional(),\n defaultOpen: z.boolean().optional(),\n children: z.array(richTextParagraphBlockSchema).max(100),\n attrs: contentAttributesSchema.optional(),\n});\n\nconst richTextSeparatorBlockSchema = z.object({\n type: z.literal(\"separator\"),\n attrs: contentAttributesSchema.optional(),\n});\n\nconst richTextBlockExtensionSchema = z.object({\n type: z.literal(\"blockExtension\"),\n name: z.string().min(1).max(120),\n attrs: contentAttributesSchema.optional(),\n});\n\nconst richTextBlockSchema = z.discriminatedUnion(\"type\", [\n richTextParagraphBlockSchema,\n richTextHeadingBlockSchema,\n richTextBulletListBlockSchema,\n richTextImageBlockSchema,\n richTextInfoBoxBlockSchema,\n richTextSeparatorBlockSchema,\n richTextBlockExtensionSchema,\n]);\n\nexport const surveyContentSchema: z.ZodType<Content> = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"md\"), content: z.string().max(20_000) }),\n z.object({ type: z.literal(\"plain\"), content: z.string().max(20_000) }),\n z.object({\n type: z.literal(\"richText\"),\n version: z.literal(1),\n doc: z.object({\n type: z.literal(\"doc\"),\n blocks: z.array(richTextBlockSchema).max(200),\n }),\n }),\n]) as z.ZodType<Content>;\n\nexport type SurveyContent = z.infer<typeof surveyContentSchema>;\nexport type JsonValue = z.infer<typeof jsonValueSchema>;\n","import { z } from \"zod\";\nimport type {\n JsonPatchOperation as CoreJsonPatchOperation,\n RawSurveyAsset,\n RawSurveyItem,\n RichTextImageDimension,\n SurveyContentImageSource,\n} from \"@case-framework/survey-core\";\nimport { SURVEY_EDITOR_ITEM_COLORS } from \"@case-framework/survey-core/editor/colors\";\nimport { jsonValueSchema, surveyContentSchema, type SurveyContent } from \"./content\";\n\ninterface OperationBase {\n id?: string;\n}\n\ninterface ItemTranslation {\n locale: string;\n contentKey: string;\n plainText?: string;\n content?: SurveyContent;\n}\n\ninterface CreateItemOperation extends OperationBase {\n kind: \"create-item\";\n target: { parentItemId: string; index?: number };\n item: Omit<RawSurveyItem, \"id\"> & { id?: string };\n translations?: ItemTranslation[];\n}\n\ninterface UpdateItemKeyOperation extends OperationBase {\n kind: \"update-item-key\";\n itemId: string;\n key: string;\n}\n\ninterface UpdateItemLabelOperation extends OperationBase {\n kind: \"update-item-label\";\n itemId: string;\n itemLabel: string;\n}\n\ntype ItemColor = (typeof SURVEY_EDITOR_ITEM_COLORS)[number];\n\ninterface UpdateItemColorOperation extends OperationBase {\n kind: \"update-item-color\";\n itemId: string;\n color: ItemColor;\n}\n\ninterface UpdateItemTranslationOperation extends OperationBase, ItemTranslation {\n kind: \"update-item-translation\";\n itemId: string;\n}\n\ninterface UpdatePlacedImageOperation extends OperationBase {\n kind: \"update-placed-image\";\n itemId: string;\n locale: string;\n contentKey: string;\n /** Zero-based index among image blocks in this rich-text content value. */\n imageIndex: number;\n /** Optional guard that prevents editing a different image after content changed. */\n expectedAssetId?: string;\n changes: {\n source?: SurveyContentImageSource;\n alt?: string | null;\n caption?: string | null;\n width?: RichTextImageDimension | null;\n height?: RichTextImageDimension | null;\n maxWidth?: RichTextImageDimension | null;\n maxHeight?: RichTextImageDimension | null;\n alignment?: \"left\" | \"center\" | \"right\" | null;\n };\n}\n\ninterface PatchItemConfigOperation extends OperationBase {\n kind: \"patch-item-config\";\n itemId: string;\n /** JSON Patch paths are relative to the item's config root. */\n patches: CoreJsonPatchOperation[];\n}\n\ninterface FormTarget {\n itemId: string;\n /** When present, target the inline embedded form on this choice option. */\n optionId?: string;\n}\n\ninterface UpsertFormFieldGroupOperation extends OperationBase {\n kind: \"upsert-form-field-group\";\n target: FormTarget;\n index?: number;\n group: Record<string, unknown> & { id: string };\n translations?: ItemTranslation[];\n}\n\ninterface RemoveFormFieldGroupOperation extends OperationBase {\n kind: \"remove-form-field-group\";\n target: FormTarget;\n groupId: string;\n}\n\ninterface ReorderFormFieldGroupsOperation extends OperationBase {\n kind: \"reorder-form-field-groups\";\n target: FormTarget;\n groupIds: string[];\n}\n\ninterface UpsertFormFieldOperation extends OperationBase {\n kind: \"upsert-form-field\";\n target: FormTarget;\n groupId: string;\n index?: number;\n field: Record<string, unknown> & { id: string; key: string; type: string };\n translations?: ItemTranslation[];\n}\n\ninterface RemoveFormFieldOperation extends OperationBase {\n kind: \"remove-form-field\";\n target: FormTarget;\n fieldId: string;\n}\n\ninterface MoveFormFieldOperation extends OperationBase {\n kind: \"move-form-field\";\n target: FormTarget;\n fieldId: string;\n targetGroupId: string;\n index?: number;\n}\n\ninterface SetEmbeddedFormOperation extends OperationBase {\n kind: \"set-embedded-form\";\n itemId: string;\n optionId: string;\n form: Record<string, unknown> & { id: string; fieldGroups: unknown[] };\n translations?: ItemTranslation[];\n}\n\ninterface RemoveEmbeddedFormOperation extends OperationBase {\n kind: \"remove-embedded-form\";\n itemId: string;\n optionId: string;\n}\n\ninterface ChoiceOptionInput {\n id?: string;\n key?: string;\n label: string;\n}\n\ninterface AddChoiceOptionOperation extends OperationBase {\n kind: \"add-choice-option\";\n itemId: string;\n locale?: string;\n index?: number;\n option: ChoiceOptionInput;\n}\n\ninterface UpdateChoiceOptionLabelOperation extends OperationBase {\n kind: \"update-choice-option-label\";\n itemId: string;\n optionId: string;\n locale?: string;\n label: string;\n}\n\ninterface RemoveChoiceOptionOperation extends OperationBase {\n kind: \"remove-choice-option\";\n itemId: string;\n optionId: string;\n}\n\ninterface ReorderChoiceOptionsOperation extends OperationBase {\n kind: \"reorder-choice-options\";\n itemId: string;\n optionIds: string[];\n}\n\ninterface RemoveItemOperation extends OperationBase {\n kind: \"remove-item\";\n itemId: string;\n includeChildren?: boolean;\n}\n\ninterface MoveItemOperation extends OperationBase {\n kind: \"move-item\";\n itemId: string;\n target: { parentItemId: string; index?: number };\n}\n\ninterface ReorderItemsOperation extends OperationBase {\n kind: \"reorder-items\";\n parentItemId: string;\n itemIds: string[];\n}\n\ninterface UpdateSurveyMetadataOperation extends OperationBase {\n kind: \"update-survey-metadata\";\n values: Record<string, string | null>;\n}\n\ninterface UpdateSurveyPaginationOperation extends OperationBase {\n kind: \"update-survey-pagination\";\n value: { large: number; small: number } | null;\n}\n\ninterface UpdateSurveyTranslationOperation\n extends OperationBase, Omit<ItemTranslation, \"contentKey\"> {\n kind: \"update-survey-translation\";\n surface: \"surveyCardContent\" | \"navigationContent\" | \"validationMessages\";\n contentKey: string;\n}\n\ninterface AddSurveyLocaleOperation extends OperationBase {\n kind: \"add-survey-locale\";\n locale: string;\n}\n\ninterface RemoveSurveyLocaleOperation extends OperationBase {\n kind: \"remove-survey-locale\";\n locale: string;\n}\n\ninterface SetImageAssetOperation extends OperationBase {\n kind: \"set-image-asset\";\n assetId: string;\n asset: RawSurveyAsset;\n}\n\ninterface UpdateImageAssetMetadataOperation extends OperationBase {\n kind: \"update-image-asset-metadata\";\n assetId: string;\n metadata: {\n name?: string | null;\n filename?: string | null;\n alt?: string | null;\n width?: number | null;\n height?: number | null;\n };\n}\n\ninterface RemoveImageAssetOperation extends OperationBase {\n kind: \"remove-image-asset\";\n assetId: string;\n}\n\ninterface SurveyPatchOperation extends OperationBase {\n kind: \"survey-json-patch\";\n patches: CoreJsonPatchOperation[];\n}\n\ntype SurveyOperationShape =\n | CreateItemOperation\n | UpdateItemKeyOperation\n | UpdateItemLabelOperation\n | UpdateItemColorOperation\n | UpdateItemTranslationOperation\n | UpdatePlacedImageOperation\n | PatchItemConfigOperation\n | UpsertFormFieldGroupOperation\n | RemoveFormFieldGroupOperation\n | ReorderFormFieldGroupsOperation\n | UpsertFormFieldOperation\n | RemoveFormFieldOperation\n | MoveFormFieldOperation\n | SetEmbeddedFormOperation\n | RemoveEmbeddedFormOperation\n | AddChoiceOptionOperation\n | UpdateChoiceOptionLabelOperation\n | RemoveChoiceOptionOperation\n | ReorderChoiceOptionsOperation\n | RemoveItemOperation\n | MoveItemOperation\n | ReorderItemsOperation\n | UpdateSurveyMetadataOperation\n | UpdateSurveyPaginationOperation\n | UpdateSurveyTranslationOperation\n | AddSurveyLocaleOperation\n | RemoveSurveyLocaleOperation\n | SetImageAssetOperation\n | UpdateImageAssetMetadataOperation\n | RemoveImageAssetOperation\n | SurveyPatchOperation;\n\nexport type SurveyOperationKind = SurveyOperationShape[\"kind\"];\n\ninterface SurveyValidationIssueShape {\n severity: \"error\" | \"warning\";\n code: string;\n message: string;\n operationIndex?: number;\n operationId?: string;\n itemId?: string;\n}\n\ninterface SurveyValidationResultShape {\n valid: boolean;\n issues: SurveyValidationIssueShape[];\n warnings: SurveyValidationIssueShape[];\n normalizedOperations: SurveyOperationShape[];\n}\n\nconst operationIdSchema = z\n .string()\n .min(1)\n .max(120)\n .optional()\n .describe(\"Optional client/model supplied id for correlating validation issues.\");\nconst itemIdentifierSchema = z\n .string()\n .min(1)\n .max(240)\n .describe(\"Survey item id, key, or fullKey.\");\nconst itemKeySchema = z\n .string()\n .min(1)\n .max(120)\n .describe(\"New item key. It must be unique among siblings.\");\n\nconst itemTranslationSchema = z\n .object({\n locale: z.string().min(1).max(40),\n contentKey: z\n .string()\n .min(1)\n .max(240)\n .describe('Item translation content key, for example \"label\" or \"content\".'),\n plainText: z\n .string()\n .max(20_000)\n .optional()\n .describe(\"Simple text content to persist for the translation key.\"),\n content: surveyContentSchema\n .optional()\n .describe(\n 'Canonical structured survey content to persist for the translation key. Use { \"type\": \"richText\", \"version\": 1, \"doc\": ... } for formatted text. The survey_change model interface also accepts documented richTextBlocks shorthand at this translation level and normalizes it to this field before canonical validation.',\n ),\n })\n .refine(\n (translation) => (translation.plainText !== undefined) !== (translation.content !== undefined),\n {\n message: \"Provide exactly one of plainText or content for a translation.\",\n },\n );\n\nconst choiceOptionInputSchema = z.object({\n id: z\n .string()\n .min(1)\n .max(120)\n .optional()\n .describe(\"Optional stable option id. If omitted, the validator derives a unique id.\"),\n key: z\n .string()\n .min(1)\n .max(120)\n .optional()\n .describe(\"Optional coding key. If omitted, the validator derives a unique key.\"),\n label: z\n .string()\n .min(1)\n .max(1000)\n .describe(\n \"Respondent-visible option label as a plain string. Do not pass a translation object here; add-choice-option creates the matching translation in its locale.\",\n ),\n});\n\nconst rawSurveyItemForCreateSchema = z\n .object({\n id: z.string().min(1).max(120).optional(),\n key: itemKeySchema,\n itemType: z.string().min(1).max(120),\n metadata: z.record(z.string(), z.string()).optional(),\n config: z\n .unknown()\n .optional()\n .describe(\n 'Optional item-type config. For choiceItem, provide response options as config.options, for example [{ \"label\": \"Fuji\" }, { \"label\": \"Gala\" }]. Use config.maxSelection: 1 for single choice, null for unlimited multiple choice / select-all-that-apply, or a number greater than 1 for capped multiple choice. Put an inline embeddedForm directly on a new choice option; default an eligible one-field embeddedForm to authoringMode \"simple\" and use \"custom\" for blank or structured follow-ups. For formItem, use authoringMode \"simple\" only with one field group containing one field; use \"custom\" for blank or multi-field forms. The validator converts option labels into options.<optionId>.label translations.',\n ),\n validations: z.record(z.string(), z.any()).optional(),\n displayConditions: z.any().optional(),\n disabledConditions: z.any().optional(),\n prefills: z.array(z.any()).optional(),\n })\n .passthrough();\n\nconst jsonPointerPathSchema = z\n .string()\n .max(500)\n .describe(\n 'Survey-root JSON Pointer obtained from current raw inspection. Escape \"~\" as \"~0\" and \"/\" within one path segment as \"~1\". Use \"/-\" only as the final destination segment of an add, move, or copy that appends to an array.',\n );\n\nexport const jsonPatchOperationSchema: z.ZodType<CoreJsonPatchOperation> = z.discriminatedUnion(\n \"op\",\n [\n z.object({ op: z.literal(\"add\"), path: jsonPointerPathSchema, value: jsonValueSchema }),\n z.object({ op: z.literal(\"replace\"), path: jsonPointerPathSchema, value: jsonValueSchema }),\n z.object({ op: z.literal(\"test\"), path: jsonPointerPathSchema, value: jsonValueSchema }),\n z.object({ op: z.literal(\"remove\"), path: jsonPointerPathSchema }),\n z.object({ op: z.literal(\"move\"), from: jsonPointerPathSchema, path: jsonPointerPathSchema }),\n z.object({ op: z.literal(\"copy\"), from: jsonPointerPathSchema, path: jsonPointerPathSchema }),\n ],\n) as z.ZodType<CoreJsonPatchOperation>;\n\nexport const createItemOperationSchema: z.ZodType<CreateItemOperation> = z.object({\n id: operationIdSchema,\n kind: z.literal(\"create-item\"),\n target: z.object({\n parentItemId: z\n .string()\n .max(240)\n .describe(\n \"Parent group item id, key, or fullKey where the new item should be inserted. Use the root group id/key for top-level items.\",\n ),\n index: z.number().int().min(0).optional(),\n }),\n item: rawSurveyItemForCreateSchema,\n translations: z\n .array(itemTranslationSchema)\n .optional()\n .describe(\n 'Operation-level item translations for visible content, for example [{ \"locale\": \"en\", \"contentKey\": \"title\", \"plainText\": \"Question text\" }]. Put this property inside the create-item operation beside target and item, never beside the survey_change operations array. For formatted content, the model interface accepts documented richTextBlocks shorthand and normalizes it to canonical content before validation. Form select/dropdown option labels must be translations at fields.<fieldId>.options.<optionId>.label.',\n ),\n}) as z.ZodType<CreateItemOperation>;\n\nexport const updateItemKeyOperationSchema: z.ZodType<UpdateItemKeyOperation> = z.object({\n id: operationIdSchema,\n kind: z.literal(\"update-item-key\"),\n itemId: itemIdentifierSchema,\n key: itemKeySchema,\n});\n\nexport const updateItemLabelOperationSchema: z.ZodType<UpdateItemLabelOperation> = z.object({\n id: operationIdSchema,\n kind: z.literal(\"update-item-label\"),\n itemId: itemIdentifierSchema,\n itemLabel: z.string().max(200),\n});\n\nexport const updateItemColorOperationSchema: z.ZodType<UpdateItemColorOperation> = z.object({\n id: operationIdSchema,\n kind: z.literal(\"update-item-color\"),\n itemId: itemIdentifierSchema,\n color: z\n .enum(SURVEY_EDITOR_ITEM_COLORS)\n .describe(\"One of the Survey Editor's supported item-color swatches.\"),\n});\n\nexport const updateItemTranslationOperationSchema: z.ZodType<UpdateItemTranslationOperation> = z\n .object({\n id: operationIdSchema,\n kind: z.literal(\"update-item-translation\"),\n itemId: itemIdentifierSchema,\n locale: z.string().min(1).max(40),\n contentKey: z\n .string()\n .min(1)\n .max(240)\n .describe('Item translation content key, for example \"label\".'),\n plainText: z\n .string()\n .max(20_000)\n .optional()\n .describe(\"Simple text content to persist for the translation key.\"),\n content: surveyContentSchema\n .optional()\n .describe(\n 'Canonical structured survey content to persist for the translation key. Use { \"type\": \"richText\", \"version\": 1, \"doc\": ... } for formatted text. The survey_change model interface also accepts documented top-level richTextBlocks shorthand and normalizes it to this field before canonical validation.',\n ),\n })\n .refine(\n (operation) => (operation.plainText !== undefined) !== (operation.content !== undefined),\n {\n message: \"Provide exactly one of plainText or content for update-item-translation.\",\n },\n ) as z.ZodType<UpdateItemTranslationOperation>;\n\nconst placedImageDimensionSchema: z.ZodType<RichTextImageDimension> = z.union([\n z.object({ unit: z.literal(\"px\"), value: z.number().finite().nonnegative() }),\n z.object({ unit: z.literal(\"%\"), value: z.number().finite().nonnegative().max(100) }),\n]);\n\nconst placedImageSourceSchema: z.ZodType<SurveyContentImageSource> = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"asset\"), assetId: z.string().min(1).max(240) }),\n z.object({ type: z.literal(\"external\"), url: z.string().min(1).max(2000) }),\n]);\n\nexport const updatePlacedImageOperationSchema: z.ZodType<UpdatePlacedImageOperation> = z.object({\n id: operationIdSchema,\n kind: z.literal(\"update-placed-image\"),\n itemId: itemIdentifierSchema,\n locale: z.string().min(1).max(40),\n contentKey: z.string().min(1).max(240),\n imageIndex: z\n .number()\n .int()\n .nonnegative()\n .describe(\"Zero-based index among image blocks in the selected rich-text content value.\"),\n expectedAssetId: z.string().min(1).max(240).optional(),\n changes: z\n .object({\n source: placedImageSourceSchema.optional(),\n alt: z.string().max(2000).nullable().optional(),\n caption: z.string().max(20_000).nullable().optional(),\n width: placedImageDimensionSchema.nullable().optional(),\n height: placedImageDimensionSchema.nullable().optional(),\n maxWidth: placedImageDimensionSchema.nullable().optional(),\n maxHeight: placedImageDimensionSchema.nullable().optional(),\n alignment: z.enum([\"left\", \"center\", \"right\"]).nullable().optional(),\n })\n .refine((changes) => Object.values(changes).some((value) => value !== undefined), {\n message: \"Provide at least one placed-image property to change.\",\n }),\n});\n\nexport const patchItemConfigOperationSchema: z.ZodType<PatchItemConfigOperation> = z.object({\n id: operationIdSchema,\n kind: z.literal(\"patch-item-config\"),\n itemId: itemIdentifierSchema,\n patches: z\n .array(jsonPatchOperationSchema)\n .min(1)\n .max(100)\n .describe(\n 'JSON Patch operations relative to this item\\'s config root, for example [{ \"op\": \"replace\", \"path\": \"/max\", \"value\": 7 }]. Inspect the item first and do not include /surveyItems/<index>/config in these paths.',\n ),\n});\n\nconst formTargetSchema: z.ZodType<FormTarget> = z.object({\n itemId: itemIdentifierSchema,\n optionId: z\n .string()\n .min(1)\n .max(240)\n .optional()\n .describe(\"Choice option id when targeting an inline embedded form.\"),\n});\n\nconst formTranslationsSchema = z\n .array(itemTranslationSchema)\n .max(100)\n .optional()\n .describe(\n \"Translations written atomically with this form structure change. Put this property inside the form operation object, never beside the survey_change operations array. Content keys are relative to the form; embedded-form prefixes are added automatically.\",\n );\n\nconst formFieldInputSchema = z\n .object({\n id: z.string().min(1).max(120),\n key: z.string().min(1).max(120),\n type: z.enum([\"input\", \"textarea\", \"number\", \"datepicker\", \"switch\", \"select\", \"slider\"]),\n controller: z.record(z.string(), z.unknown()),\n required: z.boolean().optional(),\n validations: z.array(z.record(z.string(), z.unknown())).optional(),\n })\n .passthrough();\n\nconst formFieldGroupInputSchema = z\n .object({\n id: z.string().min(1).max(120),\n layout: z\n .object({\n base: z.number().int().min(1).max(4),\n xs: z.number().int().min(1).max(4),\n sm: z.number().int().min(1).max(4),\n md: z.number().int().min(1).max(4),\n xl: z.number().int().min(1).max(4),\n })\n .describe(\n \"Responsive column counts from 1 to 4. Use 1 at every breakpoint for a lone full-width field.\",\n )\n .optional(),\n fields: z.array(formFieldInputSchema).max(200).optional(),\n hasDisplayCondition: z.boolean().optional(),\n })\n .passthrough();\n\nexport const upsertFormFieldGroupOperationSchema: z.ZodType<UpsertFormFieldGroupOperation> =\n z.object({\n id: operationIdSchema,\n kind: z.literal(\"upsert-form-field-group\"),\n target: formTargetSchema,\n index: z.number().int().min(0).optional(),\n group: formFieldGroupInputSchema,\n translations: formTranslationsSchema,\n }) as z.ZodType<UpsertFormFieldGroupOperation>;\n\nexport const removeFormFieldGroupOperationSchema: z.ZodType<RemoveFormFieldGroupOperation> =\n z.object({\n id: operationIdSchema,\n kind: z.literal(\"remove-form-field-group\"),\n target: formTargetSchema,\n groupId: z.string().min(1).max(240),\n });\n\nexport const reorderFormFieldGroupsOperationSchema: z.ZodType<ReorderFormFieldGroupsOperation> =\n z.object({\n id: operationIdSchema,\n kind: z.literal(\"reorder-form-field-groups\"),\n target: formTargetSchema,\n groupIds: z\n .array(z.string().min(1).max(240))\n .min(1)\n .max(100)\n .describe(\n \"Complete desired order containing every existing form-field group id exactly once.\",\n ),\n });\n\nexport const upsertFormFieldOperationSchema: z.ZodType<UpsertFormFieldOperation> = z.object({\n id: operationIdSchema,\n kind: z.literal(\"upsert-form-field\"),\n target: formTargetSchema,\n groupId: z.string().min(1).max(240),\n index: z.number().int().min(0).optional(),\n field: formFieldInputSchema,\n translations: formTranslationsSchema,\n}) as z.ZodType<UpsertFormFieldOperation>;\n\nexport const removeFormFieldOperationSchema: z.ZodType<RemoveFormFieldOperation> = z.object({\n id: operationIdSchema,\n kind: z.literal(\"remove-form-field\"),\n target: formTargetSchema,\n fieldId: z.string().min(1).max(240),\n});\n\nexport const moveFormFieldOperationSchema: z.ZodType<MoveFormFieldOperation> = z.object({\n id: operationIdSchema,\n kind: z.literal(\"move-form-field\"),\n target: formTargetSchema,\n fieldId: z.string().min(1).max(240),\n targetGroupId: z.string().min(1).max(240),\n index: z.number().int().min(0).optional(),\n});\n\nexport const setEmbeddedFormOperationSchema: z.ZodType<SetEmbeddedFormOperation> = z.object({\n id: operationIdSchema,\n kind: z.literal(\"set-embedded-form\"),\n itemId: itemIdentifierSchema,\n optionId: z.string().min(1).max(240),\n form: z\n .object({\n id: z.string().min(1).max(120),\n authoringMode: z\n .enum([\"simple\", \"custom\"])\n .optional()\n .describe(\n 'Use \"simple\" only for exactly one field group containing exactly one field; omitted or malformed simple mode normalizes to \"custom\".',\n ),\n fieldGroups: z.array(formFieldGroupInputSchema).max(100),\n })\n .passthrough(),\n translations: formTranslationsSchema,\n}) as z.ZodType<SetEmbeddedFormOperation>;\n\nexport const removeEmbeddedFormOperationSchema: z.ZodType<RemoveEmbeddedFormOperation> = z.object({\n id: operationIdSchema,\n kind: z.literal(\"remove-embedded-form\"),\n itemId: itemIdentifierSchema,\n optionId: z.string().min(1).max(240),\n});\n\nexport const addChoiceOptionOperationSchema: z.ZodType<AddChoiceOptionOperation> = z.object({\n id: operationIdSchema,\n kind: z.literal(\"add-choice-option\"),\n itemId: itemIdentifierSchema,\n locale: z.string().min(1).max(40).optional(),\n index: z.number().int().min(0).optional(),\n option: choiceOptionInputSchema,\n});\n\nexport const updateChoiceOptionLabelOperationSchema: z.ZodType<UpdateChoiceOptionLabelOperation> =\n z.object({\n id: operationIdSchema,\n kind: z.literal(\"update-choice-option-label\"),\n itemId: itemIdentifierSchema,\n optionId: z\n .string()\n .min(1)\n .max(240)\n .describe(\"Existing choice option id, key, or current visible label.\"),\n locale: z.string().min(1).max(40).optional(),\n label: z.string().min(1).max(1000).describe(\"New respondent-visible option label.\"),\n });\n\nexport const removeChoiceOptionOperationSchema: z.ZodType<RemoveChoiceOptionOperation> = z.object({\n id: operationIdSchema,\n kind: z.literal(\"remove-choice-option\"),\n itemId: itemIdentifierSchema,\n optionId: z\n .string()\n .min(1)\n .max(240)\n .describe(\"Existing choice option id, key, or current visible label.\"),\n});\n\nexport const reorderChoiceOptionsOperationSchema: z.ZodType<ReorderChoiceOptionsOperation> =\n z.object({\n id: operationIdSchema,\n kind: z.literal(\"reorder-choice-options\"),\n itemId: itemIdentifierSchema,\n optionIds: z\n .array(z.string().min(1).max(240))\n .min(1)\n .max(100)\n .describe(\n \"Complete desired order of existing choice options. Entries can be option ids, keys, or current visible labels.\",\n ),\n });\n\nexport const removeItemOperationSchema: z.ZodType<RemoveItemOperation> = z.object({\n id: operationIdSchema,\n kind: z.literal(\"remove-item\"),\n itemId: itemIdentifierSchema,\n includeChildren: z\n .boolean()\n .optional()\n .describe(\"Must be true when removing a group item that has children.\"),\n});\n\nexport const moveItemOperationSchema: z.ZodType<MoveItemOperation> = z.object({\n id: operationIdSchema,\n kind: z.literal(\"move-item\"),\n itemId: itemIdentifierSchema,\n target: z\n .object({\n parentItemId: itemIdentifierSchema,\n index: z.number().int().min(0).optional(),\n })\n .describe(\n \"A different parent group and optional insertion index. Omit unchanged placements; use reorder-items for sibling order within the current parent.\",\n ),\n});\n\nexport const reorderItemsOperationSchema: z.ZodType<ReorderItemsOperation> = z.object({\n id: operationIdSchema,\n kind: z.literal(\"reorder-items\"),\n parentItemId: itemIdentifierSchema,\n itemIds: z\n .array(itemIdentifierSchema)\n .min(1)\n .max(200)\n .describe(\n \"Complete desired order containing every existing direct child of the parent group exactly once.\",\n ),\n});\n\nexport const updateSurveyMetadataOperationSchema: z.ZodType<UpdateSurveyMetadataOperation> =\n z.object({\n id: operationIdSchema,\n kind: z.literal(\"update-survey-metadata\"),\n values: z.record(z.string().min(1).max(240), z.string().max(20_000).nullable()),\n });\n\nexport const updateSurveyPaginationOperationSchema: z.ZodType<UpdateSurveyPaginationOperation> =\n z.object({\n id: operationIdSchema,\n kind: z.literal(\"update-survey-pagination\"),\n value: z\n .object({\n large: z.number().int().min(1).max(1000),\n small: z.number().int().min(1).max(1000),\n })\n .nullable(),\n });\n\nexport const updateSurveyTranslationOperationSchema: z.ZodType<UpdateSurveyTranslationOperation> = z\n .object({\n id: operationIdSchema,\n kind: z.literal(\"update-survey-translation\"),\n locale: z.string().min(1).max(40),\n surface: z.enum([\"surveyCardContent\", \"navigationContent\", \"validationMessages\"]),\n contentKey: z.string().min(1).max(240),\n plainText: z.string().max(20_000).optional(),\n content: surveyContentSchema\n .optional()\n .describe(\n \"Canonical structured survey content to persist for the survey translation. The survey_change model interface also accepts documented top-level richTextBlocks shorthand and normalizes it to this field before canonical validation.\",\n ),\n })\n .refine(\n (operation) => (operation.plainText !== undefined) !== (operation.content !== undefined),\n {\n message: \"Provide exactly one of plainText or content for update-survey-translation.\",\n },\n ) as z.ZodType<UpdateSurveyTranslationOperation>;\n\nconst surveyLocaleSchema = z.string().trim().min(1).max(40);\n\nexport const addSurveyLocaleOperationSchema: z.ZodType<AddSurveyLocaleOperation> = z\n .object({\n id: operationIdSchema,\n kind: z.literal(\"add-survey-locale\"),\n locale: surveyLocaleSchema.describe(\"New, currently absent survey locale code.\"),\n })\n .describe(\"Register an empty survey locale through the editor locale-management API.\");\n\nexport const removeSurveyLocaleOperationSchema: z.ZodType<RemoveSurveyLocaleOperation> = z\n .object({\n id: operationIdSchema,\n kind: z.literal(\"remove-survey-locale\"),\n locale: surveyLocaleSchema.describe(\"Exact existing survey locale code to remove.\"),\n })\n .describe(\n \"Destructively remove a survey locale and all survey-level and item-level translations stored for it.\",\n );\n\nconst imageAssetMetadataSchema = z.object({\n name: z.string().max(500).optional(),\n filename: z.string().max(500).optional(),\n alt: z.string().max(2000).optional(),\n width: z.number().int().positive().optional(),\n height: z.number().int().positive().optional(),\n});\n\nconst rawSurveyImageAssetSchema: z.ZodType<RawSurveyAsset> = z.object({\n kind: z.literal(\"image\"),\n source: z.object({\n type: z.literal(\"embedded\"),\n mediaType: z.string().regex(/^image\\//),\n encoding: z.literal(\"base64\"),\n data: z.string().min(1).max(8_000_000),\n }),\n metadata: imageAssetMetadataSchema.optional(),\n});\n\nexport const setImageAssetOperationSchema: z.ZodType<SetImageAssetOperation> = z.object({\n id: operationIdSchema,\n kind: z.literal(\"set-image-asset\"),\n assetId: z.string().min(1).max(240),\n asset: rawSurveyImageAssetSchema,\n});\n\nexport const updateImageAssetMetadataOperationSchema: z.ZodType<UpdateImageAssetMetadataOperation> =\n z.object({\n id: operationIdSchema,\n kind: z.literal(\"update-image-asset-metadata\"),\n assetId: z.string().min(1).max(240),\n metadata: z.object({\n name: z.string().max(500).nullable().optional(),\n filename: z.string().max(500).nullable().optional(),\n alt: z.string().max(2000).nullable().optional(),\n width: z.number().int().positive().nullable().optional(),\n height: z.number().int().positive().nullable().optional(),\n }),\n });\n\nexport const removeImageAssetOperationSchema: z.ZodType<RemoveImageAssetOperation> = z.object({\n id: operationIdSchema,\n kind: z.literal(\"remove-image-asset\"),\n assetId: z.string().min(1).max(240),\n});\n\nexport const surveyPatchOperationSchema: z.ZodType<SurveyPatchOperation> = z.object({\n id: operationIdSchema,\n kind: z.literal(\"survey-json-patch\"),\n patches: z\n .array(jsonPatchOperationSchema)\n .min(1)\n .max(100)\n .describe(\n \"Sequential JSON Patch operations applied to the survey document. Use only for an existing, inspected survey-root extension with no typed operation, patch-item-config helper, or survey_expression mutation. Parent paths must exist. Add creates or replaces an object member, inserts at an array index, or appends with /-. Replace, remove, and test require an existing path. Move and copy require an existing from path. Preserve exact JSON value types, and guard overwrites or removals with test when the current value is known.\",\n ),\n});\n\n// Public annotations keep declaration output compact. Runtime values are still\n// the concrete Zod objects required by discriminatedUnion.\nconst asDiscriminable = <T>(schema: z.ZodType<T>) => schema as unknown as z.ZodObject;\n\nexport const surveyOperationSchemasByKind = {\n \"create-item\": createItemOperationSchema,\n \"update-item-key\": updateItemKeyOperationSchema,\n \"update-item-label\": updateItemLabelOperationSchema,\n \"update-item-color\": updateItemColorOperationSchema,\n \"update-item-translation\": updateItemTranslationOperationSchema,\n \"update-placed-image\": updatePlacedImageOperationSchema,\n \"patch-item-config\": patchItemConfigOperationSchema,\n \"upsert-form-field-group\": upsertFormFieldGroupOperationSchema,\n \"remove-form-field-group\": removeFormFieldGroupOperationSchema,\n \"reorder-form-field-groups\": reorderFormFieldGroupsOperationSchema,\n \"upsert-form-field\": upsertFormFieldOperationSchema,\n \"remove-form-field\": removeFormFieldOperationSchema,\n \"move-form-field\": moveFormFieldOperationSchema,\n \"set-embedded-form\": setEmbeddedFormOperationSchema,\n \"remove-embedded-form\": removeEmbeddedFormOperationSchema,\n \"add-choice-option\": addChoiceOptionOperationSchema,\n \"update-choice-option-label\": updateChoiceOptionLabelOperationSchema,\n \"remove-choice-option\": removeChoiceOptionOperationSchema,\n \"reorder-choice-options\": reorderChoiceOptionsOperationSchema,\n \"remove-item\": removeItemOperationSchema,\n \"move-item\": moveItemOperationSchema,\n \"reorder-items\": reorderItemsOperationSchema,\n \"update-survey-metadata\": updateSurveyMetadataOperationSchema,\n \"update-survey-pagination\": updateSurveyPaginationOperationSchema,\n \"update-survey-translation\": updateSurveyTranslationOperationSchema,\n \"add-survey-locale\": addSurveyLocaleOperationSchema,\n \"remove-survey-locale\": removeSurveyLocaleOperationSchema,\n \"set-image-asset\": setImageAssetOperationSchema,\n \"update-image-asset-metadata\": updateImageAssetMetadataOperationSchema,\n \"remove-image-asset\": removeImageAssetOperationSchema,\n \"survey-json-patch\": surveyPatchOperationSchema,\n} as const satisfies Record<SurveyOperationKind, z.ZodType>;\n\nconst surveyOperationSchemaOptions = Object.values(surveyOperationSchemasByKind).map((schema) =>\n asDiscriminable(schema as z.ZodType),\n) as [z.ZodObject, z.ZodObject, ...z.ZodObject[]];\n\nexport const surveyOperationSchema: z.ZodType<SurveyOperationShape> = z.discriminatedUnion(\n \"kind\",\n surveyOperationSchemaOptions,\n) as unknown as z.ZodType<SurveyOperationShape>;\n\nexport const surveyValidationIssueSchema: z.ZodType<SurveyValidationIssueShape> = z.object({\n severity: z.enum([\"error\", \"warning\"]),\n code: z.string(),\n message: z.string(),\n operationIndex: z.number().int().nonnegative().optional(),\n operationId: z.string().optional(),\n itemId: z.string().optional(),\n});\n\nexport const surveyValidationResultSchema: z.ZodType<SurveyValidationResultShape> = z.object({\n valid: z.boolean(),\n issues: z.array(surveyValidationIssueSchema),\n warnings: z.array(surveyValidationIssueSchema),\n normalizedOperations: z.array(surveyOperationSchema),\n});\n\nexport type JsonPatchOperation = z.infer<typeof jsonPatchOperationSchema>;\nexport type SurveyOperation = z.infer<typeof surveyOperationSchema>;\n\nexport const SURVEY_OPERATION_KINDS = Object.freeze(\n Object.keys(surveyOperationSchemasByKind),\n) as readonly [SurveyOperationKind, ...SurveyOperationKind[]];\nexport type SurveyValidationIssue = z.infer<typeof surveyValidationIssueSchema>;\nexport type SurveyValidationResult = z.infer<typeof surveyValidationResultSchema>;\n\n// Compatibility names retained while app and survey-ui public APIs migrate.\nexport const surveyJsonPatchOperationSchema = jsonPatchOperationSchema;\nexport const surveyAssistantCreateItemOperationSchema = createItemOperationSchema;\nexport const surveyAssistantUpdateItemKeyOperationSchema = updateItemKeyOperationSchema;\nexport const surveyAssistantUpdateItemLabelOperationSchema = updateItemLabelOperationSchema;\nexport const surveyAssistantUpdateItemColorOperationSchema = updateItemColorOperationSchema;\nexport const surveyAssistantUpdateItemTranslationOperationSchema =\n updateItemTranslationOperationSchema;\nexport const surveyAssistantAddChoiceOptionOperationSchema = addChoiceOptionOperationSchema;\nexport const surveyAssistantUpdateChoiceOptionLabelOperationSchema =\n updateChoiceOptionLabelOperationSchema;\nexport const surveyAssistantRemoveChoiceOptionOperationSchema = removeChoiceOptionOperationSchema;\nexport const surveyAssistantReorderChoiceOptionsOperationSchema =\n reorderChoiceOptionsOperationSchema;\nexport const surveyAssistantRemoveItemOperationSchema = removeItemOperationSchema;\nexport const surveyAssistantSurveyJsonPatchOperationSchema = surveyPatchOperationSchema;\nexport const surveyAssistantOperationSchema = surveyOperationSchema;\nexport const surveyAssistantValidationIssueSchema = surveyValidationIssueSchema;\nexport const surveyAssistantValidationResultSchema = surveyValidationResultSchema;\n\nexport type SurveyAssistantOperation = SurveyOperation;\nexport type SurveyAssistantValidationIssue = SurveyValidationIssue;\nexport type SurveyAssistantValidationResult = SurveyValidationResult;\nexport type SurveyAssistantSurveyJsonPatchOperation = z.infer<typeof surveyPatchOperationSchema>;\n","import { z } from \"zod\";\nimport { SURVEY_OPERATION_KINDS } from \"./operations\";\n\nexport const assistantItemCreateModeSchema = z.enum([\n \"deterministic\",\n \"interactive-only\",\n \"unsupported\",\n]);\n\nexport const assistantContentSurfaceSchema = z.object({\n key: z.string().min(1),\n role: z.enum([\"primary\", \"secondary\", \"option\", \"field\", \"validation\"]),\n format: z.enum([\"plain\", \"rich\"]),\n requiredOnCreate: z.boolean().optional(),\n pattern: z.boolean().optional(),\n aliases: z.array(z.string().min(1)).optional(),\n});\n\nexport const assistantResponseSlotSchema = z.object({\n key: z.string().min(1),\n valueType: z.string().min(1),\n});\n\nexport const assistantItemAuthoringSchema = z.object({\n compactHint: z.string().min(1).max(240).optional(),\n configSummary: z.string().min(1).max(1000).optional(),\n});\n\nexport const assistantCreationPresetSchema = z.object({\n id: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,119}$/),\n});\n\nexport const assistantItemTypeManifestSchema = z.object({\n itemType: z.string().min(1),\n capabilityVersion: z.string().min(1),\n displayName: z.string().min(1),\n description: z.string().optional(),\n defaultItemKeyPrefix: z.string().min(1).optional(),\n create: assistantItemCreateModeSchema,\n supportedOperations: z.array(z.enum(SURVEY_OPERATION_KINDS)),\n contentSurfaces: z.array(assistantContentSurfaceSchema),\n responseSlots: z.array(assistantResponseSlotSchema).optional(),\n creationPresets: z.array(assistantCreationPresetSchema).max(100).optional(),\n referenceTopics: z.array(z.string().min(1)).optional(),\n authoring: assistantItemAuthoringSchema.optional(),\n});\n\nexport const surveyAssistantCapabilityManifestSchema = z.object({\n digest: z.string().min(1),\n itemTypes: z.array(assistantItemTypeManifestSchema),\n});\n\nexport type AssistantItemCreateMode = z.infer<typeof assistantItemCreateModeSchema>;\nexport type AssistantContentSurface = z.infer<typeof assistantContentSurfaceSchema>;\nexport type AssistantResponseSlot = z.infer<typeof assistantResponseSlotSchema>;\nexport type AssistantItemAuthoring = z.infer<typeof assistantItemAuthoringSchema>;\nexport type AssistantCreationPreset = z.infer<typeof assistantCreationPresetSchema>;\nexport type AssistantItemTypeManifest = z.infer<typeof assistantItemTypeManifestSchema>;\nexport type SurveyAssistantCapabilityManifest = z.infer<\n typeof surveyAssistantCapabilityManifestSchema\n>;\n","import type { RawSurvey } from \"@case-framework/survey-core\";\nimport { z } from \"zod\";\nimport { surveyContentSchema } from \"./content\";\nimport {\n surveyAssistantCapabilityManifestSchema,\n type AssistantItemTypeManifest,\n type SurveyAssistantCapabilityManifest,\n} from \"./capabilities\";\n\ninterface SurveyDocumentVersionShape {\n sessionId: string | null;\n revision: number;\n historyIndex: number;\n contentHash: string;\n capabilityDigest: string;\n}\n\ninterface SurveyEditorUIContextShape {\n view: \"item-editor\" | \"preview-mode\" | \"translation-mode\" | \"asset-manager\";\n selectedItemId?: string;\n selectedLocale: string;\n focusItemId?: string;\n recentItemIds?: string[];\n activeSurface?: string;\n openPanels?: string[];\n highlights?: Array<{\n kind: string;\n itemId?: string;\n componentId?: string;\n label?: string;\n details?: string;\n }>;\n history?: {\n currentIndex: number;\n totalEntries: number;\n canUndo: boolean;\n canRedo: boolean;\n recent: Array<{\n index: number;\n kind: \"survey-snapshot\" | \"asset-change\";\n label: string;\n source?: \"user\" | \"system\" | \"assistant\";\n timestamp: number;\n isCurrent: boolean;\n }>;\n };\n}\n\ninterface SurveyDocumentSnapshotShape {\n protocolVersion: 1;\n version: SurveyDocumentVersionShape;\n survey: RawSurvey;\n ui: SurveyEditorUIContextShape;\n capabilities: SurveyAssistantCapabilityManifest;\n createdAt: string;\n}\n\nexport const SURVEY_ASSISTANT_PROTOCOL_VERSION = 1 as const;\nexport const surveyAssistantProtocolVersionSchema = z.literal(SURVEY_ASSISTANT_PROTOCOL_VERSION);\n\nexport const surveyDocumentVersionSchema: z.ZodType<SurveyDocumentVersionShape> = z.object({\n sessionId: z.string().nullable(),\n revision: z.number().int().nonnegative(),\n historyIndex: z.number().int(),\n contentHash: z.string().min(1),\n capabilityDigest: z.string().min(1),\n});\n\nexport const surveyEditorUIContextSchema: z.ZodType<SurveyEditorUIContextShape> = z.object({\n view: z.enum([\"item-editor\", \"preview-mode\", \"translation-mode\", \"asset-manager\"]),\n selectedItemId: z.string().optional(),\n selectedLocale: z.string().min(1),\n focusItemId: z.string().optional(),\n recentItemIds: z.array(z.string()).max(10).optional(),\n activeSurface: z.string().max(120).optional(),\n openPanels: z.array(z.string().max(120)).max(12).optional(),\n highlights: z\n .array(\n z.object({\n kind: z.string().min(1).max(80),\n itemId: z.string().optional(),\n componentId: z.string().optional(),\n label: z.string().max(240).optional(),\n details: z.string().max(1000).optional(),\n }),\n )\n .max(12)\n .optional(),\n history: z\n .object({\n currentIndex: z.number().int(),\n totalEntries: z.number().int().nonnegative(),\n canUndo: z.boolean(),\n canRedo: z.boolean(),\n recent: z\n .array(\n z.object({\n index: z.number().int().nonnegative(),\n kind: z.enum([\"survey-snapshot\", \"asset-change\"]),\n label: z.string(),\n source: z.enum([\"user\", \"system\", \"assistant\"]).optional(),\n timestamp: z.number().nonnegative(),\n isCurrent: z.boolean(),\n }),\n )\n .max(12),\n })\n .optional(),\n});\n\nconst rawSurveyItemSchema = z\n .object({\n id: z.string().min(1),\n key: z.string().min(1),\n itemType: z.string().min(1),\n })\n .passthrough();\n\nconst rawSurveyTranslationsSchema = z.record(\n z.string(),\n z\n .object({\n itemTranslations: z.record(z.string(), z.record(z.string(), surveyContentSchema)).optional(),\n })\n .passthrough(),\n);\n\nexport const rawSurveyDocumentSchema: z.ZodType<RawSurvey> = z\n .object({\n $schema: z.string().min(1),\n surveyItems: z.array(rawSurveyItemSchema).min(1),\n translations: rawSurveyTranslationsSchema.optional(),\n })\n .passthrough() as z.ZodType<RawSurvey>;\n\nexport const surveyDocumentSnapshotSchema: z.ZodType<SurveyDocumentSnapshotShape> = z.object({\n protocolVersion: surveyAssistantProtocolVersionSchema,\n version: surveyDocumentVersionSchema,\n survey: rawSurveyDocumentSchema,\n ui: surveyEditorUIContextSchema,\n capabilities: surveyAssistantCapabilityManifestSchema,\n createdAt: z.string().min(1),\n});\n\nexport const surveyAssistantSnapshotSchema = surveyDocumentSnapshotSchema;\nexport const surveyAssistantSnapshotPayloadSchema = surveyDocumentSnapshotSchema;\n\nexport type SurveyAssistantProtocolVersion = z.infer<typeof surveyAssistantProtocolVersionSchema>;\nexport type SurveyDocumentVersion = z.infer<typeof surveyDocumentVersionSchema>;\nexport type SurveyEditorUIContext = z.infer<typeof surveyEditorUIContextSchema>;\nexport type RawSurveyDocument = z.infer<typeof rawSurveyDocumentSchema>;\nexport type SurveyDocumentSnapshot = z.infer<typeof surveyDocumentSnapshotSchema>;\n\n// Compatibility names for host adapters while the public API converges on\n// SurveyDocumentSnapshot. They are aliases, not alternate wire shapes.\nexport type SurveyAssistantSnapshot = SurveyDocumentSnapshot;\nexport type SurveyAssistantSnapshotPayload = SurveyDocumentSnapshot;\nexport type SurveyAssistantItemCreateStrategy =\n SurveyAssistantCapabilityManifest[\"itemTypes\"][number][\"create\"];\nexport type SurveyAssistantItemTypeManifestEntry = AssistantItemTypeManifest;\nexport type SurveyAssistantItemRegistryManifest = SurveyAssistantCapabilityManifest;\nexport type SurveyAssistantDraftChangePrecondition = SurveyDocumentVersion;\nexport const surveyAssistantDraftChangePreconditionSchema = surveyDocumentVersionSchema;\n","import { z } from \"zod\";\n\nexport const SURVEY_ASSISTANT_ATTACHMENT_PART_TYPE = \"data-survey-assistant-attachment\" as const;\n\nexport interface SurveyAssistantAttachmentReference {\n documentId?: string;\n filename: string;\n mediaType: string;\n bytes: number;\n}\n\nexport const surveyAssistantThreadSchema = z.object({\n id: z.string().min(1).max(240),\n title: z.string().min(1).max(160),\n titleMode: z.enum([\"automatic\", \"manual\"]),\n createdAt: z.string().datetime(),\n updatedAt: z.string().datetime(),\n});\n\nexport const surveyAssistantThreadListSchema = z.object({\n nextCursor: z.string().min(1).max(240).optional(),\n threads: z.array(surveyAssistantThreadSchema),\n});\n\nexport const surveyAssistantThreadTranscriptSchema = z.object({\n nextCursor: z.string().min(1).max(240).optional(),\n thread: surveyAssistantThreadSchema,\n messages: z.array(z.unknown()),\n});\n\nexport const createSurveyAssistantThreadInputSchema = z.object({\n title: z.string().trim().min(1).max(160).optional(),\n});\n\nexport const updateSurveyAssistantThreadInputSchema = z.union([\n z.object({\n mode: z.literal(\"automatic\"),\n title: z.string().trim().min(1).max(160).optional(),\n }),\n z.object({\n mode: z.literal(\"manual\").optional(),\n title: z.string().trim().min(1).max(160),\n }),\n]);\n\nexport type SurveyAssistantThreadTitleMode = \"automatic\" | \"manual\";\nexport type SurveyAssistantThread = z.infer<typeof surveyAssistantThreadSchema>;\nexport type SurveyAssistantThreadList = z.infer<typeof surveyAssistantThreadListSchema>;\nexport type SurveyAssistantThreadTranscript = z.infer<typeof surveyAssistantThreadTranscriptSchema>;\nexport type CreateSurveyAssistantThreadInput = z.infer<\n typeof createSurveyAssistantThreadInputSchema\n>;\nexport type UpdateSurveyAssistantThreadInput = z.infer<\n typeof updateSurveyAssistantThreadInputSchema\n>;\n","import { z } from \"zod\";\n\nexport const surveyAssistantTaskInvocationModeSchema = z.enum([\"user\", \"background\"]);\n\nexport type SurveyAssistantTaskInvocationMode = z.infer<\n typeof surveyAssistantTaskInvocationModeSchema\n>;\n\nexport const surveyAssistantSuggestedTextSchema = z.object({ text: z.string().min(1) });\n\nexport type SurveyAssistantSuggestedText = z.infer<typeof surveyAssistantSuggestedTextSchema>;\n\nexport const surveyAssistantKeySuggestionCategorySchema = z.enum([\n \"survey-pattern\",\n \"compact\",\n \"preferred\",\n \"fair\",\n]);\n\nexport type SurveyAssistantKeySuggestionCategory = z.infer<\n typeof surveyAssistantKeySuggestionCategorySchema\n>;\n\nexport const surveyAssistantKeySuggestionSchema = surveyAssistantSuggestedTextSchema.extend({\n category: surveyAssistantKeySuggestionCategorySchema,\n rationale: z.string().optional(),\n});\n\nexport type SurveyAssistantKeySuggestion = z.infer<typeof surveyAssistantKeySuggestionSchema>;\n\nexport const surveyAssistantSuggestItemKeyInputSchema = z.object({\n itemId: z.string().min(1),\n draftKey: z.string(),\n currentKey: z.string(),\n siblingKeys: z.array(z.string()),\n maxSuggestions: z.number().int().positive().optional(),\n});\n\nexport type SurveyAssistantSuggestItemKeyInput = z.infer<\n typeof surveyAssistantSuggestItemKeyInputSchema\n>;\n\nexport const surveyAssistantSuggestItemKeyResultSchema = z.object({\n suggestions: z.array(surveyAssistantKeySuggestionSchema),\n});\n\nexport type SurveyAssistantSuggestItemKeyResult = z.infer<\n typeof surveyAssistantSuggestItemKeyResultSchema\n>;\n\nexport type SurveyAssistantLabelSuggestion = SurveyAssistantSuggestedText;\n\nexport const surveyAssistantSuggestItemLabelInputSchema = z.object({\n itemId: z.string().min(1),\n draftLabel: z.string(),\n itemType: z.string().min(1),\n locale: z.string().min(1).optional(),\n maxSuggestions: z.number().int().positive().optional(),\n});\n\nexport type SurveyAssistantSuggestItemLabelInput = z.infer<\n typeof surveyAssistantSuggestItemLabelInputSchema\n>;\n\nexport const surveyAssistantSuggestItemLabelResultSchema = z.object({\n suggestions: z.array(surveyAssistantSuggestedTextSchema),\n});\n\nexport type SurveyAssistantSuggestItemLabelResult = z.infer<\n typeof surveyAssistantSuggestItemLabelResultSchema\n>;\n\nexport const surveyAssistantTranslateContentEntrySchema = z.object({\n id: z.string().min(1),\n text: z.string(),\n kind: z.string().min(1),\n});\n\nexport type SurveyAssistantTranslateContentEntry = z.infer<\n typeof surveyAssistantTranslateContentEntrySchema\n>;\n\nexport const surveyAssistantTranslateContentInputSchema = z.object({\n sourceLocale: z.string().min(1),\n targetLocales: z.array(z.string().min(1)).min(1),\n entries: z.array(surveyAssistantTranslateContentEntrySchema).min(1),\n});\n\nexport type SurveyAssistantTranslateContentInput = z.infer<\n typeof surveyAssistantTranslateContentInputSchema\n>;\n\nexport const surveyAssistantTranslateContentResultSchema = z.object({\n translations: z.record(z.string(), z.record(z.string(), z.string())),\n});\n\nexport type SurveyAssistantTranslateContentResult = z.infer<\n typeof surveyAssistantTranslateContentResultSchema\n>;\n\nexport const surveyAssistantTaskItemSummarySchema = z.object({\n id: z.string().min(1),\n key: z.string(),\n fullKey: z.string(),\n itemType: z.string().min(1),\n itemLabel: z.string().optional(),\n visibleText: z.array(\n z.object({\n locale: z.string().min(1),\n contentKey: z.string().min(1),\n text: z.string(),\n }),\n ),\n visibleTextTruncated: z.boolean(),\n});\n\nexport type SurveyAssistantTaskItemSummary = z.infer<typeof surveyAssistantTaskItemSummarySchema>;\n\nconst namingRelationshipSchema = z.enum([\"sibling\", \"same-type\", \"survey\"]);\n\nexport const surveyAssistantTaskContextSchema = z.object({\n document: z.object({\n revision: z.number().int().nonnegative(),\n contentHash: z.string().min(1),\n capabilityDigest: z.string().min(1),\n }),\n survey: z.object({\n key: z.string().optional(),\n locales: z.array(z.string()),\n itemCount: z.number().int().nonnegative(),\n selectedLocale: z.string().min(1),\n }),\n focus: z\n .object({\n item: surveyAssistantTaskItemSummarySchema,\n parent: surveyAssistantTaskItemSummarySchema.optional(),\n ancestorPath: z.array(surveyAssistantTaskItemSummarySchema),\n siblingKeys: z.array(z.string()),\n siblingItems: z.array(surveyAssistantTaskItemSummarySchema),\n siblingItemCount: z.number().int().nonnegative(),\n siblingItemsTruncated: z.boolean(),\n relatedItems: z.array(surveyAssistantTaskItemSummarySchema),\n relatedItemCount: z.number().int().nonnegative(),\n relatedItemsTruncated: z.boolean(),\n })\n .optional(),\n naming: z\n .object({\n keyExamples: z.array(\n z.object({\n itemId: z.string().min(1),\n itemType: z.string().min(1),\n key: z.string(),\n relationship: namingRelationshipSchema,\n }),\n ),\n keyExampleCount: z.number().int().nonnegative(),\n keyExamplesTruncated: z.boolean(),\n labelExamples: z.array(\n z.object({\n itemId: z.string().min(1),\n itemType: z.string().min(1),\n key: z.string(),\n label: z.string(),\n relationship: namingRelationshipSchema,\n }),\n ),\n labelExampleCount: z.number().int().nonnegative(),\n labelExamplesTruncated: z.boolean(),\n })\n .optional(),\n translation: z\n .object({\n examples: z.array(\n z.object({\n itemId: z.string().min(1),\n contentKey: z.string().min(1),\n values: z.record(z.string(), z.string()),\n }),\n ),\n exampleCount: z.number().int().nonnegative(),\n examplesTruncated: z.boolean(),\n })\n .optional(),\n});\n\nexport type SurveyAssistantTaskContext = z.infer<typeof surveyAssistantTaskContextSchema>;\n\nconst taskRequestBase = {\n context: surveyAssistantTaskContextSchema,\n mode: surveyAssistantTaskInvocationModeSchema.optional(),\n modelId: z.string().trim().min(1).max(240).optional(),\n resourceId: z.string().trim().min(1).max(240).optional(),\n surveyId: z.string().trim().min(1).max(240).optional(),\n};\n\nexport const surveyAssistantTaskRequestSchema = z.discriminatedUnion(\"taskId\", [\n z.object({\n ...taskRequestBase,\n taskId: z.literal(\"suggest-item-key\"),\n input: surveyAssistantSuggestItemKeyInputSchema,\n }),\n z.object({\n ...taskRequestBase,\n taskId: z.literal(\"suggest-item-label\"),\n input: surveyAssistantSuggestItemLabelInputSchema,\n }),\n z.object({\n ...taskRequestBase,\n taskId: z.literal(\"translate-content\"),\n input: surveyAssistantTranslateContentInputSchema,\n }),\n]);\n\nexport type SurveyAssistantTaskRequest = z.infer<typeof surveyAssistantTaskRequestSchema>;\n","import { z } from \"zod\";\n\nexport const surveyAssistantModelOptionSchema = z.object({\n id: z.string().trim().min(1).max(240),\n label: z.string().trim().min(1).max(240),\n});\n\nexport const surveyAssistantModelCatalogSchema = z\n .object({\n defaultModelId: z.string().trim().min(1).max(240),\n models: z.array(surveyAssistantModelOptionSchema).min(1),\n })\n .refine(\n ({ defaultModelId, models }) => models.some((model) => model.id === defaultModelId),\n \"The default model must be present in the model catalog.\",\n );\n\nexport type SurveyAssistantModelOption = z.infer<typeof surveyAssistantModelOptionSchema>;\nexport type SurveyAssistantModelCatalog = z.infer<typeof surveyAssistantModelCatalogSchema>;\n","import { z } from \"zod\";\nimport {\n surveyAssistantProtocolVersionSchema,\n surveyDocumentVersionSchema,\n type SurveyDocumentVersion,\n} from \"./document\";\nimport {\n surveyOperationSchema,\n surveyValidationIssueSchema,\n surveyValidationResultSchema,\n type SurveyOperation,\n type SurveyValidationIssue,\n type SurveyValidationResult,\n} from \"./operations\";\n\nexport interface SurveyChangeSetShape {\n protocolVersion: 1;\n id: string;\n turnId: string;\n status: \"validated\" | \"rejected\";\n summary: string;\n operations: SurveyOperation[];\n supersedesChangeIds?: string[];\n pendingRepairs?: Array<{\n changeId: string;\n targets: string[];\n requiresExplicitRetry: boolean;\n allowsAcknowledgment?: boolean;\n }>;\n precondition?: SurveyDocumentVersion;\n postChange?: SurveyAssistantPostChangeProjectionShape;\n verification?: SurveyAssistantChangeVerificationShape;\n validation: SurveyValidationResult;\n createdAt: string;\n}\n\nconst surveyAssistantChangeVerificationReasonValues = [\n \"substantial-change\",\n \"complex-change\",\n \"bounded-preview\",\n \"new-audit-findings\",\n] as const;\n\ninterface SurveyAssistantChangeVerificationShape {\n required: boolean;\n reasons: Array<(typeof surveyAssistantChangeVerificationReasonValues)[number]>;\n newAuditFindingCount: number;\n auditFindings: Array<{\n code: string;\n severity: \"error\" | \"warning\" | \"info\";\n category:\n | \"structure\"\n | \"content\"\n | \"localization\"\n | \"logic\"\n | \"responses\"\n | \"assets\"\n | \"quality\";\n itemId?: string;\n locale?: string;\n contentKey?: string;\n messagePreview: string;\n messageLength: number;\n truncated: boolean;\n }>;\n truncated: boolean;\n}\n\ninterface SurveyAssistantPostChangeProjectionShape {\n version: SurveyDocumentVersion;\n itemCount: number;\n localeCount: number;\n locales: string[];\n targetCount: number;\n touchedTargets: string[];\n touchedItemCount: number;\n availableTouchedItemCount: number;\n touchedItems: Array<{\n itemId: string;\n itemType: string;\n key: string;\n fullKey: string;\n itemLabel?: string;\n translationCount: number;\n translations: Array<{\n locale: string;\n contentKey: string;\n textPreview: string;\n textLength: number;\n truncated: boolean;\n }>;\n responseSlotCount: number;\n responseSlots: string[];\n }>;\n truncated: boolean;\n}\n\nconst surveyAssistantTurnTerminationReasonValues = [\n \"client-abort\",\n \"first-response-timeout\",\n \"idle-timeout\",\n \"max-duration\",\n \"max-steps\",\n \"length-limit\",\n \"content-filter\",\n \"provider-error\",\n \"stream-error\",\n \"incomplete-response\",\n] as const;\n\ninterface SurveyAssistantTurnFinalShape {\n protocolVersion: 1;\n turnId: string;\n status: \"completed\" | \"failed\" | \"aborted\";\n executableChangeSetIds: string[];\n blockedChangeSetIds?: string[];\n startedAt?: string;\n durationMs?: number;\n terminationReason?: (typeof surveyAssistantTurnTerminationReasonValues)[number];\n createdAt: string;\n}\n\ntype SurveyAssistantApplyPolicyShape = \"auto\" | \"review\" | \"deny\";\n\nexport const SURVEY_ASSISTANT_TURN_FINAL_DATA_NAME = \"survey-assistant-turn-final\" as const;\nexport const SURVEY_ASSISTANT_TURN_FINAL_PART_TYPE =\n `data-${SURVEY_ASSISTANT_TURN_FINAL_DATA_NAME}` as const;\n\ntype SurveyApplyStatusShape = \"applied\" | \"rejected\" | \"stale\" | \"failed\";\n\ninterface SurveyApplyResultShape {\n status: SurveyApplyStatusShape;\n changeId: string;\n summary: string;\n message: string;\n appliedOperations: number;\n issues?: SurveyValidationIssue[];\n}\n\ninterface SurveyBatchApplyResultShape {\n results: SurveyApplyResultShape[];\n}\n\ninterface SurveyAssistantApplyOutcomeResultShape {\n status: SurveyApplyStatusShape;\n changeId: string;\n summary: string;\n message: string;\n appliedOperations: number;\n}\n\ninterface SurveyAssistantPreparedChangeShape {\n changeId: string;\n status: \"validated\" | \"rejected\";\n summary: string;\n operationCount: number;\n}\n\nconst surveyAssistantApplyOutcomeStatusValues = [\n \"not-applied\",\n \"apply-failed\",\n \"settle-failed\",\n] as const;\n\ninterface SurveyAssistantApplyOutcomeShape {\n protocolVersion: 1;\n turnId: string;\n status: (typeof surveyAssistantApplyOutcomeStatusValues)[number];\n message: string;\n results?: SurveyAssistantApplyOutcomeResultShape[];\n preparedChanges?: SurveyAssistantPreparedChangeShape[];\n createdAt: string;\n}\n\ninterface ApplyReceiptShape {\n protocolVersion: 1;\n turnId: string;\n changeSetId: string;\n beforeVersion: SurveyDocumentVersion;\n afterVersion?: SurveyDocumentVersion;\n status: SurveyApplyStatusShape;\n operationCount: number;\n commit?: { id?: string; index?: number };\n issues?: SurveyValidationIssue[];\n createdAt: string;\n}\n\nexport const surveyChangeSetSchema: z.ZodType<SurveyChangeSetShape> = z.object({\n protocolVersion: surveyAssistantProtocolVersionSchema.default(1),\n id: z.string().min(1),\n turnId: z.string().min(1),\n status: z.enum([\"validated\", \"rejected\"]),\n summary: z.string().min(1).max(500),\n operations: z.array(surveyOperationSchema),\n supersedesChangeIds: z.array(z.string().min(1)).max(100).optional(),\n pendingRepairs: z\n .array(\n z.object({\n changeId: z.string().min(1),\n targets: z.array(z.string()),\n requiresExplicitRetry: z.boolean(),\n allowsAcknowledgment: z.boolean().optional(),\n }),\n )\n .optional(),\n precondition: surveyDocumentVersionSchema.optional(),\n postChange: z\n .object({\n version: surveyDocumentVersionSchema,\n itemCount: z.number().int().nonnegative(),\n localeCount: z.number().int().nonnegative(),\n locales: z.array(z.string().min(1)).max(32),\n targetCount: z.number().int().nonnegative(),\n touchedTargets: z.array(z.string().min(1)).max(16),\n touchedItemCount: z.number().int().nonnegative(),\n availableTouchedItemCount: z.number().int().nonnegative(),\n touchedItems: z\n .array(\n z.object({\n itemId: z.string().min(1),\n itemType: z.string().min(1),\n key: z.string().min(1),\n fullKey: z.string().min(1),\n itemLabel: z.string().optional(),\n translationCount: z.number().int().nonnegative(),\n translations: z\n .array(\n z.object({\n locale: z.string().min(1),\n contentKey: z.string().min(1),\n textPreview: z.string(),\n textLength: z.number().int().nonnegative(),\n truncated: z.boolean(),\n }),\n )\n .max(12),\n responseSlotCount: z.number().int().nonnegative(),\n responseSlots: z.array(z.string().min(1)).max(12),\n }),\n )\n .max(6),\n truncated: z.boolean(),\n })\n .optional(),\n verification: z\n .object({\n required: z.boolean(),\n reasons: z\n .array(z.enum(surveyAssistantChangeVerificationReasonValues))\n .min(1)\n .max(surveyAssistantChangeVerificationReasonValues.length),\n newAuditFindingCount: z.number().int().nonnegative(),\n auditFindings: z\n .array(\n z.object({\n code: z.string().min(1),\n severity: z.enum([\"error\", \"warning\", \"info\"]),\n category: z.enum([\n \"structure\",\n \"content\",\n \"localization\",\n \"logic\",\n \"responses\",\n \"assets\",\n \"quality\",\n ]),\n itemId: z.string().min(1).optional(),\n locale: z.string().min(1).optional(),\n contentKey: z.string().min(1).optional(),\n messagePreview: z.string(),\n messageLength: z.number().int().nonnegative(),\n truncated: z.boolean(),\n }),\n )\n .max(8),\n truncated: z.boolean(),\n })\n .optional(),\n validation: surveyValidationResultSchema,\n createdAt: z.string().min(1),\n});\n\nexport const surveyAssistantTurnTerminationReasonSchema = z.enum(\n surveyAssistantTurnTerminationReasonValues,\n);\n\nexport const surveyAssistantTurnFinalSchema: z.ZodType<SurveyAssistantTurnFinalShape> = z\n .object({\n protocolVersion: surveyAssistantProtocolVersionSchema,\n turnId: z.string().min(1),\n status: z.enum([\"completed\", \"failed\", \"aborted\"]),\n executableChangeSetIds: z.array(z.string().min(1)),\n blockedChangeSetIds: z.array(z.string().min(1)).max(100).optional(),\n startedAt: z.string().datetime().optional(),\n durationMs: z.number().int().nonnegative().optional(),\n terminationReason: surveyAssistantTurnTerminationReasonSchema.optional(),\n createdAt: z.string().min(1),\n })\n .superRefine((value, context) => {\n if (value.status !== \"completed\" && value.executableChangeSetIds.length > 0) {\n context.addIssue({\n code: \"custom\",\n message: \"Failed or aborted turns cannot authorize executable change sets.\",\n path: [\"executableChangeSetIds\"],\n });\n }\n\n if (new Set(value.executableChangeSetIds).size !== value.executableChangeSetIds.length) {\n context.addIssue({\n code: \"custom\",\n message: \"Executable change-set ids must be unique.\",\n path: [\"executableChangeSetIds\"],\n });\n }\n\n const blockedChangeSetIds = value.blockedChangeSetIds ?? [];\n if (new Set(blockedChangeSetIds).size !== blockedChangeSetIds.length) {\n context.addIssue({\n code: \"custom\",\n message: \"Blocked change-set ids must be unique.\",\n path: [\"blockedChangeSetIds\"],\n });\n }\n\n if (blockedChangeSetIds.length > 0 && value.executableChangeSetIds.length > 0) {\n context.addIssue({\n code: \"custom\",\n message: \"A blocked turn cannot authorize executable change sets.\",\n path: [\"executableChangeSetIds\"],\n });\n }\n\n if (value.status === \"completed\" && value.terminationReason !== undefined) {\n context.addIssue({\n code: \"custom\",\n message: \"Completed turns cannot have a failure or abort reason.\",\n path: [\"terminationReason\"],\n });\n }\n }) as z.ZodType<SurveyAssistantTurnFinalShape>;\n\nexport const surveyAssistantApplyPolicySchema: z.ZodType<SurveyAssistantApplyPolicyShape> = z.enum([\n \"auto\",\n \"review\",\n \"deny\",\n]);\n\nexport const surveyApplyStatusSchema: z.ZodType<SurveyApplyStatusShape> = z.enum([\n \"applied\",\n \"rejected\",\n \"stale\",\n \"failed\",\n]);\n\nexport const surveyApplyResultSchema: z.ZodType<SurveyApplyResultShape> = z.object({\n status: surveyApplyStatusSchema,\n changeId: z.string(),\n summary: z.string(),\n message: z.string(),\n appliedOperations: z.number().int().nonnegative(),\n issues: z.array(surveyValidationIssueSchema).optional(),\n});\n\nexport const surveyBatchApplyResultSchema: z.ZodType<SurveyBatchApplyResultShape> = z.object({\n results: z.array(surveyApplyResultSchema),\n});\n\nexport const surveyAssistantApplyOutcomeSchema: z.ZodType<SurveyAssistantApplyOutcomeShape> =\n z.object({\n protocolVersion: surveyAssistantProtocolVersionSchema,\n turnId: z.string().min(1),\n status: z.enum(surveyAssistantApplyOutcomeStatusValues),\n message: z.string().min(1).max(2_000),\n results: z\n .array(\n z.object({\n status: surveyApplyStatusSchema,\n changeId: z.string().min(1).max(240),\n summary: z.string().min(1).max(500),\n message: z.string().min(1).max(2_000),\n appliedOperations: z.number().int().nonnegative(),\n }),\n )\n .max(100)\n .optional(),\n preparedChanges: z\n .array(\n z.object({\n changeId: z.string().min(1).max(240),\n status: z.enum([\"validated\", \"rejected\"]),\n summary: z.string().min(1).max(500),\n operationCount: z.number().int().nonnegative(),\n }),\n )\n .max(24)\n .optional(),\n createdAt: z.string().min(1),\n });\n\nexport const applyReceiptSchema: z.ZodType<ApplyReceiptShape> = z.object({\n protocolVersion: surveyAssistantProtocolVersionSchema,\n turnId: z.string().min(1),\n changeSetId: z.string().min(1),\n beforeVersion: surveyDocumentVersionSchema,\n afterVersion: surveyDocumentVersionSchema.optional(),\n status: surveyApplyStatusSchema,\n operationCount: z.number().int().nonnegative(),\n commit: z\n .object({\n id: z.string().min(1).optional(),\n index: z.number().int().optional(),\n })\n .optional(),\n issues: z.array(surveyValidationIssueSchema).optional(),\n createdAt: z.string().min(1),\n});\n\nexport type SurveyChangeSet = z.infer<typeof surveyChangeSetSchema>;\nexport type SurveyAssistantTurnFinal = z.infer<typeof surveyAssistantTurnFinalSchema>;\nexport type SurveyAssistantTurnTerminationReason = z.infer<\n typeof surveyAssistantTurnTerminationReasonSchema\n>;\nexport type SurveyAssistantApplyPolicy = z.infer<typeof surveyAssistantApplyPolicySchema>;\nexport type SurveyApplyStatus = z.infer<typeof surveyApplyStatusSchema>;\nexport type SurveyApplyResult = z.infer<typeof surveyApplyResultSchema>;\nexport type SurveyBatchApplyResult = z.infer<typeof surveyBatchApplyResultSchema>;\nexport type SurveyAssistantApplyOutcome = z.infer<typeof surveyAssistantApplyOutcomeSchema>;\nexport type ApplyReceipt = z.infer<typeof applyReceiptSchema>;\n\n// Compatibility names retained until the UI and host public APIs can make a\n// breaking terminology change.\nexport const surveyAssistantDraftChangeEventSchema = surveyChangeSetSchema;\nexport type SurveyAssistantDraftChangeEvent = SurveyChangeSet;\nexport type SurveyAssistantApplyStatus = SurveyApplyStatus;\nexport type SurveyAssistantApplyResult = SurveyApplyResult;\nexport type SurveyAssistantBatchApplyResult = SurveyBatchApplyResult;\n"],"mappings":";;;AAAA,MAAa,gCAAgC;AAE7C,MAAM,qBAAqB;AAC3B,MAAM,WAAW;AACjB,MAAM,eAAe;AACrB,MAAM,aAAa;AACnB,MAAM,sBAAsB;AAC5B,MAAM,gBAAgB;AAEtB,MAAa,0CAA0C,UACrD,MACG,QAAQ,oBAAoB,GAAG,CAC/B,QAAQ,UAAU,qBAAqB,CACvC,QAAQ,cAAc,8BAA8B,CACpD,QAAQ,YAAY,uBAAuB,CAC3C,QAAQ,qBAAqB,yBAAyB,CACtD,QAAQ,eAAe,yBAAyB;AAErD,MAAa,yCACX,OACA,UAAA,QACW;CACX,MAAM,aAAa,uCAAuC,MAAM,CAAC,QAAQ,QAAQ,IAAI,CAAC,MAAM;AAE5F,KAAI,WAAW,UAAU,QAAS,QAAO;AACzC,QAAO,GAAG,WAAW,MAAM,GAAG,KAAK,IAAI,GAAG,UAAU,EAAE,CAAC,CAAC;;AAG1D,MAAa,yCAAyC,QAAyB;CAC7E,MAAM,aAAa,IAAI,mBAAmB;AAC1C,QACE,WAAW,SAAS,gBAAgB,IACpC,WAAW,SAAS,aAAa,IACjC,WAAW,SAAS,YAAY,IAChC,WAAW,SAAS,WAAW,IAC/B,WAAW,SAAS,WAAW,IAC/B,WAAW,SAAS,SAAS,IAC7B,WAAW,SAAS,YAAY,IAChC,eAAe,WACf,WAAW,SAAS,QAAQ,IAC5B,WAAW,SAAS,UAAU,IAC9B,WAAW,SAAS,SAAS;;AAIjC,MAAa,0CACX,OACA,QACA,QACwE;AACxE,KAAI,OAAO,UAAU,SAAU,QAAO,KAAA;AACtC,KAAI,QAAQ,UAAU,QAAQ,SAAS,cAAc,OAAO,aAAa,SACvE,QAAO;EAAE,YAAY,MAAM;EAAQ,UAAU;EAAU;AAEzD,KAAI,MAAM,SAAS,OAAO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E,QAAQ,CAAC,IAAI,EAAE,CAAC,IAAI,IAAM;EACrC,mBAAmB,EAAE,QAAQ,CAAC,KAAK,CAAC,aAAa;EAClD,CAAC,CACH,CACA,IAAI,IAAI,CACR,UAAU;CACb,iBAAiB,EACd,MACC,EAAE,OAAO;EACP,UAAU,EAAE,QAAQ,CAAC,IAAI,EAAE,CAAC,IAAI,IAAI;EACpC,QAAQ,EAAE,KAAK,CAAC,aAAa,WAAW,CAAC;EACzC,SAAS,EAAE,QAAQ,CAAC,IAAI,EAAE,CAAC,IAAI,IAAI;EACnC,gBAAgB,EAAE,QAAQ,CAAC,KAAK,CAAC,aAAa;EAC/C,CAAC,CACH,CACA,IAAI,GAAG,CACP,UAAU;CACb,WAAW,EAAE,QAAQ,CAAC,IAAI,EAAE;CAC7B,CAAC;AAEJ,MAAa,qBAAmD,EAAE,OAAO;CACvE,iBAAiB;CACjB,QAAQ,EAAE,QAAQ,CAAC,IAAI,EAAE;CACzB,aAAa,EAAE,QAAQ,CAAC,IAAI,EAAE;CAC9B,eAAe;CACf,cAAc,4BAA4B,UAAU;CACpD,QAAQ;CACR,gBAAgB,EAAE,QAAQ,CAAC,KAAK,CAAC,aAAa;CAC9C,QAAQ,EACL,OAAO;EACN,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE,CAAC,UAAU;EAChC,OAAO,EAAE,QAAQ,CAAC,KAAK,CAAC,UAAU;EACnC,CAAC,CACD,UAAU;CACb,QAAQ,EAAE,MAAM,4BAA4B,CAAC,UAAU;CACvD,WAAW,EAAE,QAAQ,CAAC,IAAI,EAAE;CAC7B,CAAC;AAgBF,MAAa,wCAAwC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"react-B3ybjJ-X.mjs","names":["findLastUserMessageIndex","surveyAssistantPackageVersion"],"sources":["../src/react/session-state.ts","../src/react/turn-authorization.ts","../src/react/transport.ts","../src/react/thread-client.ts","../src/react/support-bundle-limits.ts","../src/react/diagnostic-store.ts","../package.json","../src/react/support-bundle.ts","../src/react/model-catalog.ts","../src/react/document-baseline.ts","../src/react/use-survey-assistant-session.ts"],"sourcesContent":["export type SurveyAssistantSessionState =\n | \"idle\"\n | \"submitting\"\n | \"streaming\"\n | \"completed\"\n | \"failed\"\n | \"aborted\"\n | \"applying\"\n | \"applied\";\n\nexport type SurveyAssistantSessionEvent =\n | { type: \"submit\" }\n | { type: \"stream-started\" }\n | { type: \"completed\" }\n | { type: \"apply-started\" }\n | { type: \"applied\" }\n | { type: \"failed\" }\n | { type: \"aborted\" }\n | { type: \"reset\"; hasTranscript: boolean };\n\nexport const isSurveyAssistantTurnActive = ({\n isStreaming,\n state,\n}: {\n isStreaming: boolean;\n state: SurveyAssistantSessionState;\n}): boolean =>\n state !== \"aborted\" &&\n (isStreaming || state === \"submitting\" || state === \"streaming\" || state === \"applying\");\n\nexport const reduceSurveyAssistantSessionState = (\n _state: SurveyAssistantSessionState,\n event: SurveyAssistantSessionEvent,\n): SurveyAssistantSessionState => {\n switch (event.type) {\n case \"submit\":\n return \"submitting\";\n case \"stream-started\":\n return \"streaming\";\n case \"completed\":\n return \"completed\";\n case \"apply-started\":\n return \"applying\";\n case \"applied\":\n return \"applied\";\n case \"failed\":\n return \"failed\";\n case \"aborted\":\n return \"aborted\";\n case \"reset\":\n return event.hasTranscript ? \"completed\" : \"idle\";\n }\n};\n","import {\n SURVEY_ASSISTANT_PROTOCOL_VERSION,\n SURVEY_ASSISTANT_TURN_FINAL_PART_TYPE,\n applyReceiptSchema,\n surveyAssistantTurnFinalSchema,\n surveyChangeSetSchema,\n type ApplyReceipt,\n type SurveyAssistantSnapshot,\n type SurveyAssistantTurnFinal,\n type SurveyApplyResult,\n type SurveyChangeSet,\n type SurveyDocumentVersion,\n} from \"../protocol\";\nimport type { UIMessage } from \"ai\";\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isCompletedToolPart = (\n part: UIMessage[\"parts\"][number],\n): part is UIMessage[\"parts\"][number] & { state: \"output-available\"; output: unknown } =>\n (part.type === \"dynamic-tool\" || part.type.startsWith(\"tool-\")) &&\n \"state\" in part &&\n part.state === \"output-available\" &&\n \"output\" in part;\n\nexport const unwrapSurveyAssistantToolOutput = (output: unknown) => {\n if (isRecord(output) && \"output\" in output && output.output !== undefined) {\n return output.output;\n }\n return output;\n};\n\nexport const parseSurveyChangeSet = (output: unknown): SurveyChangeSet | null => {\n const parsed = surveyChangeSetSchema.safeParse(unwrapSurveyAssistantToolOutput(output));\n return parsed.success ? parsed.data : null;\n};\n\nexport const collectSurveyChangeSets = (messages: UIMessage[]): SurveyChangeSet[] => {\n const changes: SurveyChangeSet[] = [];\n for (const message of messages) {\n for (const part of message.parts) {\n if (!isCompletedToolPart(part)) {\n continue;\n }\n const change = parseSurveyChangeSet(part.output);\n if (change) {\n changes.push(change);\n }\n }\n }\n return changes;\n};\n\nconst findLastUserMessageIndex = (messages: UIMessage[]) => {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n if (messages[index]?.role === \"user\") return index;\n }\n return -1;\n};\n\nexport type SurveyTurnAuthorization =\n | { status: \"pending\" }\n | { status: \"invalid\"; reason: string; turnId?: string }\n | {\n status: \"failed\" | \"aborted\";\n turnFinal: SurveyAssistantTurnFinal;\n changeSets: [];\n }\n | {\n status: \"completed\";\n turnFinal: SurveyAssistantTurnFinal;\n changeSets: SurveyChangeSet[];\n };\n\nexport type SurveyTurnOutcome =\n | {\n status: \"failed\";\n terminationReason?: SurveyAssistantTurnFinal[\"terminationReason\"];\n }\n | {\n status: \"aborted\";\n terminationReason?: SurveyAssistantTurnFinal[\"terminationReason\"];\n }\n | {\n status: \"blocked\";\n blockedChangeSetCount: number;\n }\n | {\n status: \"apply-failed\";\n appliedChangeSetCount: number;\n failedChangeSetCount: number;\n };\n\nexport const resolveLatestSurveyTurnAuthorization = (\n messages: UIMessage[],\n): SurveyTurnAuthorization => {\n const lastUserIndex = findLastUserMessageIndex(messages);\n if (lastUserIndex < 0) {\n return { status: \"pending\" };\n }\n\n const turnMessages = messages.slice(lastUserIndex + 1);\n const finalParts = turnMessages\n .flatMap((message) => message.parts)\n .filter((part) => part.type === SURVEY_ASSISTANT_TURN_FINAL_PART_TYPE);\n if (finalParts.length === 0) {\n return { status: \"pending\" };\n }\n if (finalParts.length !== 1) {\n return { status: \"invalid\", reason: \"The assistant returned multiple turn finals.\" };\n }\n\n const finalPart = finalParts[0];\n const finalParse = surveyAssistantTurnFinalSchema.safeParse(\n finalPart && \"data\" in finalPart ? finalPart.data : undefined,\n );\n if (!finalParse.success) {\n return { status: \"invalid\", reason: \"The assistant returned an invalid turn final.\" };\n }\n const turnFinal = finalParse.data;\n if (turnFinal.status !== \"completed\") {\n return { status: turnFinal.status, turnFinal, changeSets: [] };\n }\n\n const candidates = collectSurveyChangeSets(turnMessages).filter(\n (change) => change.turnId === turnFinal.turnId,\n );\n const candidatesById = new Map<string, SurveyChangeSet>();\n for (const candidate of candidates) {\n if (candidatesById.has(candidate.id)) {\n return {\n status: \"invalid\",\n turnId: turnFinal.turnId,\n reason: `The assistant returned duplicate change set \"${candidate.id}\".`,\n };\n }\n candidatesById.set(candidate.id, candidate);\n }\n\n for (const blockedChangeSetId of turnFinal.blockedChangeSetIds ?? []) {\n const candidate = candidatesById.get(blockedChangeSetId);\n if (!candidate || candidate.status !== \"rejected\" || candidate.validation.valid) {\n return {\n status: \"invalid\",\n turnId: turnFinal.turnId,\n reason: `The assistant did not provide blocked change set \"${blockedChangeSetId}\".`,\n };\n }\n }\n\n const changeSets: SurveyChangeSet[] = [];\n for (const changeSetId of turnFinal.executableChangeSetIds) {\n const candidate = candidatesById.get(changeSetId);\n if (!candidate || candidate.status !== \"validated\" || !candidate.validation.valid) {\n return {\n status: \"invalid\",\n turnId: turnFinal.turnId,\n reason: `The assistant did not provide authorized change set \"${changeSetId}\".`,\n };\n }\n changeSets.push(candidate);\n }\n\n return { status: \"completed\", turnFinal, changeSets };\n};\n\nexport const resolveSurveyTurnOutcome = ({\n applyResultsByChangeId,\n authorization,\n}: {\n applyResultsByChangeId: Record<string, SurveyApplyResult>;\n authorization: SurveyTurnAuthorization;\n}): SurveyTurnOutcome | null => {\n if (authorization.status === \"failed\" || authorization.status === \"aborted\") {\n return {\n status: authorization.status,\n terminationReason: authorization.turnFinal.terminationReason,\n };\n }\n if (authorization.status !== \"completed\") {\n return null;\n }\n\n const blockedChangeSetCount = authorization.turnFinal.blockedChangeSetIds?.length ?? 0;\n if (blockedChangeSetCount > 0) {\n return { status: \"blocked\", blockedChangeSetCount };\n }\n\n if (authorization.changeSets.length === 0) {\n return null;\n }\n\n const results = authorization.changeSets.map((change) => applyResultsByChangeId[change.id]);\n if (results.some((result) => result === undefined)) {\n return null;\n }\n\n const failedChangeSetCount = results.filter((result) => result.status !== \"applied\").length;\n if (failedChangeSetCount === 0) {\n return null;\n }\n\n return {\n status: \"apply-failed\",\n appliedChangeSetCount: results.length - failedChangeSetCount,\n failedChangeSetCount,\n };\n};\n\nexport const getSurveyDocumentVersionFromSnapshot = (\n snapshot: SurveyAssistantSnapshot,\n): SurveyDocumentVersion => ({ ...snapshot.version });\n\nexport const createApplyReceipts = ({\n afterSnapshot,\n beforeSnapshot,\n changeSets,\n results,\n turnFinal,\n createdAt = new Date().toISOString(),\n}: {\n afterSnapshot: SurveyAssistantSnapshot | null;\n beforeSnapshot: SurveyAssistantSnapshot;\n changeSets: SurveyChangeSet[];\n results: SurveyApplyResult[];\n turnFinal: SurveyAssistantTurnFinal;\n createdAt?: string;\n}): ApplyReceipt[] => {\n const beforeVersion = getSurveyDocumentVersionFromSnapshot(beforeSnapshot);\n const afterVersion = afterSnapshot\n ? getSurveyDocumentVersionFromSnapshot(afterSnapshot)\n : undefined;\n const resultsByChangeId = new Map(results.map((result) => [result.changeId, result]));\n\n return changeSets.map((changeSet) => {\n const result = resultsByChangeId.get(changeSet.id);\n const status = result?.status ?? \"failed\";\n return applyReceiptSchema.parse({\n protocolVersion: SURVEY_ASSISTANT_PROTOCOL_VERSION,\n turnId: turnFinal.turnId,\n changeSetId: changeSet.id,\n beforeVersion,\n ...(status === \"applied\" && afterVersion ? { afterVersion } : {}),\n status,\n operationCount: changeSet.operations.length,\n ...(status === \"applied\" && afterVersion?.historyIndex !== undefined\n ? { commit: { index: afterVersion.historyIndex } }\n : {}),\n ...(result?.issues ? { issues: result.issues } : {}),\n createdAt,\n });\n });\n};\n","import { DefaultChatTransport, type UIMessage } from \"ai\";\nimport { readSurveyAssistantJson } from \"./client-error\";\n\nconst findLastUserMessage = (messages: UIMessage[]): UIMessage | undefined => {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n if (messages[index]?.role === \"user\") return messages[index];\n }\n return undefined;\n};\n\nconst fetchSurveyAssistantChat: typeof fetch = async (input, init) => {\n const response = await globalThis.fetch(input, init);\n if (!response.ok) await readSurveyAssistantJson(response);\n return response;\n};\n\nexport const createSurveyAssistantTransport = ({\n api = \"/api/survey-assistant/chat\",\n resourceId,\n surveyId,\n threadId,\n}: {\n api?: string;\n resourceId: string;\n surveyId?: string;\n threadId: string;\n}) =>\n new DefaultChatTransport({\n api,\n body: { resourceId, ...(surveyId ? { surveyId } : {}), threadId },\n fetch: fetchSurveyAssistantChat,\n prepareSendMessagesRequest: ({\n api,\n body,\n credentials,\n headers,\n id,\n messageId,\n messages,\n trigger,\n }) => {\n const latestUserMessage = findLastUserMessage(messages);\n return {\n api,\n credentials,\n headers,\n body: {\n ...body,\n id,\n messages: latestUserMessage ? [latestUserMessage] : [],\n trigger,\n messageId,\n },\n };\n },\n });\n","import {\n surveyAssistantThreadListSchema,\n surveyAssistantThreadSchema,\n surveyAssistantThreadTranscriptSchema,\n type SurveyAssistantThread,\n type SurveyAssistantThreadList,\n type SurveyAssistantThreadTranscript,\n} from \"../protocol\";\nimport { readSurveyAssistantJson } from \"./client-error\";\n\nexport interface SurveyAssistantThreadClient {\n delete(threadId: string): Promise<void>;\n create(title?: string): Promise<SurveyAssistantThread>;\n list(): Promise<SurveyAssistantThread[]>;\n /** Paged history capability. Older custom clients may omit this method. */\n listPage?(options?: { cursor?: string }): Promise<SurveyAssistantThreadList>;\n read(\n threadId: string,\n cursor?: string,\n options?: { signal?: AbortSignal },\n ): Promise<SurveyAssistantThreadTranscript>;\n rename(threadId: string, title: string): Promise<SurveyAssistantThread>;\n setAutomaticTitle(threadId: string, title?: string): Promise<SurveyAssistantThread>;\n}\n\nexport const createSurveyAssistantThreadClient = (\n api = \"/api/survey-assistant/threads\",\n): SurveyAssistantThreadClient => ({\n async delete(threadId) {\n const response = await fetch(`${api}/${encodeURIComponent(threadId)}`, { method: \"DELETE\" });\n if (!response.ok) await readSurveyAssistantJson(response);\n },\n async create(title) {\n const body = await readSurveyAssistantJson(\n await fetch(api, {\n body: JSON.stringify(title ? { title } : {}),\n headers: { \"content-type\": \"application/json\" },\n method: \"POST\",\n }),\n );\n return surveyAssistantThreadSchema.parse(body.thread);\n },\n async list() {\n const body = await readSurveyAssistantJson(await fetch(api, { cache: \"no-store\" }));\n return surveyAssistantThreadListSchema.parse(body).threads;\n },\n async listPage(options) {\n const search = new URLSearchParams();\n if (options?.cursor) search.set(\"cursor\", options.cursor);\n const body = await readSurveyAssistantJson(\n await fetch(`${api}${search.size ? `?${search}` : \"\"}`, { cache: \"no-store\" }),\n );\n return surveyAssistantThreadListSchema.parse(body);\n },\n async read(threadId, cursor, options) {\n const search = cursor ? `?cursor=${encodeURIComponent(cursor)}` : \"\";\n const body = await readSurveyAssistantJson(\n await fetch(`${api}/${encodeURIComponent(threadId)}${search}`, {\n cache: \"no-store\",\n signal: options?.signal,\n }),\n );\n return surveyAssistantThreadTranscriptSchema.parse(body);\n },\n async rename(threadId, title) {\n const body = await readSurveyAssistantJson(\n await fetch(`${api}/${encodeURIComponent(threadId)}`, {\n body: JSON.stringify({ mode: \"manual\", title }),\n headers: { \"content-type\": \"application/json\" },\n method: \"PATCH\",\n }),\n );\n return surveyAssistantThreadSchema.parse(body.thread);\n },\n async setAutomaticTitle(threadId, title) {\n const body = await readSurveyAssistantJson(\n await fetch(`${api}/${encodeURIComponent(threadId)}`, {\n body: JSON.stringify({ mode: \"automatic\", ...(title ? { title } : {}) }),\n headers: { \"content-type\": \"application/json\" },\n method: \"PATCH\",\n }),\n );\n return surveyAssistantThreadSchema.parse(body.thread);\n },\n});\n","export interface SurveyAssistantSupportBundleLimits {\n attemptEvents: number;\n attemptStoreBytes: number;\n bundleBytes: number;\n emailWarningBytes: number;\n retainedAttempts: number;\n transcriptBytes: number;\n transcriptMessages: number;\n transcriptPages: number;\n zipEntryBytes: number;\n}\n\nconst MEBIBYTE = 1024 * 1024;\n\nexport const SURVEY_ASSISTANT_DEFAULT_SUPPORT_BUNDLE_LIMITS = {\n attemptEvents: 200,\n attemptStoreBytes: 48 * MEBIBYTE,\n bundleBytes: 64 * MEBIBYTE,\n emailWarningBytes: 15 * MEBIBYTE,\n retainedAttempts: 5,\n transcriptBytes: 24 * MEBIBYTE,\n transcriptMessages: 2_000,\n transcriptPages: 20,\n zipEntryBytes: 32 * MEBIBYTE,\n} as const satisfies SurveyAssistantSupportBundleLimits;\n\nexport const resolveSurveyAssistantSupportBundleLimits = (\n overrides?: Partial<SurveyAssistantSupportBundleLimits>,\n): SurveyAssistantSupportBundleLimits => {\n const limits = { ...SURVEY_ASSISTANT_DEFAULT_SUPPORT_BUNDLE_LIMITS, ...overrides };\n for (const [name, value] of Object.entries(limits)) {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new Error(\n `Survey assistant support-bundle limit \"${name}\" must be a positive integer.`,\n );\n }\n }\n if (limits.transcriptBytes > limits.zipEntryBytes) {\n throw new Error(\"The transcript limit cannot exceed the individual ZIP-entry limit.\");\n }\n if (limits.zipEntryBytes > limits.bundleBytes) {\n throw new Error(\"The individual ZIP-entry limit cannot exceed the complete bundle limit.\");\n }\n return limits;\n};\n","import { hashString } from \"../protocol/digest\";\nimport type {\n ApplyReceipt,\n SurveyAssistantApplyOutcome,\n SurveyAssistantAttachmentReference,\n SurveyAssistantErrorInfo,\n SurveyAssistantSnapshot,\n SurveyAssistantTurnFinal,\n} from \"../protocol\";\nimport type { FileUIPart } from \"ai\";\nimport {\n resolveSurveyAssistantSupportBundleLimits,\n type SurveyAssistantSupportBundleLimits,\n} from \"./support-bundle-limits\";\n\nexport type SurveyAssistantDiagnosticEventFields = Record<\n string,\n boolean | number | string | null | undefined\n>;\n\nexport interface SurveyAssistantDiagnosticEvent {\n at: string;\n event: string;\n fields?: SurveyAssistantDiagnosticEventFields;\n}\n\nexport interface SurveyAssistantDiagnosticAttachmentReference {\n bytes: number;\n filename: string;\n mediaType: string;\n sessionContentDigest: string;\n storeKey: string;\n}\n\nexport interface SurveyAssistantDiagnosticAttempt {\n applyOutcome?: SurveyAssistantApplyOutcome;\n applyReceipts?: ApplyReceipt[];\n attachments: SurveyAssistantDiagnosticAttachmentReference[];\n captureFailure?: string;\n error?: SurveyAssistantErrorInfo;\n events: SurveyAssistantDiagnosticEvent[];\n messages?: unknown[];\n modelId?: string;\n requestId: string;\n resourceId: string;\n submittedAt: string;\n submittedSurvey?: SurveyAssistantSnapshot | null;\n threadId: string;\n turnFinal?: SurveyAssistantTurnFinal;\n}\n\ninterface StoredAttachment extends SurveyAssistantDiagnosticAttachmentReference {\n dataUrl?: string;\n retainedBytes: number;\n}\n\ninterface StoredAttempt extends SurveyAssistantDiagnosticAttempt {\n retainedBytes: number;\n}\n\nexport interface SurveyAssistantDiagnosticStore {\n beginAttempt(input: {\n attachmentReferences?: SurveyAssistantAttachmentReference[];\n files: FileUIPart[];\n modelId?: string;\n requestId?: string;\n resourceId: string;\n submittedSurvey: SurveyAssistantSnapshot | null;\n threadId: string;\n }): string;\n deleteThread(threadId: string): void;\n getAttachment(storeKey: string): StoredAttachment | undefined;\n getExportAttempt(threadId: string): SurveyAssistantDiagnosticAttempt | undefined;\n recordApplyOutcome(threadId: string, outcome: SurveyAssistantApplyOutcome): void;\n recordApplyReceipts(threadId: string, receipts: ApplyReceipt[]): void;\n recordEvent(threadId: string, event: string, fields?: SurveyAssistantDiagnosticEventFields): void;\n recordFailure(threadId: string, messages: unknown[], error: SurveyAssistantErrorInfo): void;\n recordTurnFinal(threadId: string, turnFinal: SurveyAssistantTurnFinal): void;\n}\n\nexport const createSurveyAssistantDiagnosticId = (prefix = \"attempt\"): string => {\n const randomId = globalThis.crypto?.randomUUID?.();\n if (randomId) return `${prefix}-${randomId}`.slice(0, 64);\n const segment = () => Math.random().toString(36).slice(2).padEnd(12, \"0\");\n return `${prefix}-${segment()}${segment()}`.slice(0, 64);\n};\n\nconst cloneDiagnosticValue = <T>(value: T): T => {\n if (typeof structuredClone === \"function\") return structuredClone(value);\n return JSON.parse(JSON.stringify(value)) as T;\n};\n\nconst getDataUrlBytes = (value: string): number => {\n const comma = value.indexOf(\",\");\n if (comma < 0) return new TextEncoder().encode(value).byteLength;\n const payload = value.slice(comma + 1).replace(/\\s/g, \"\");\n if (!/;base64,/i.test(value.slice(0, comma + 1))) {\n try {\n return new TextEncoder().encode(decodeURIComponent(payload)).byteLength;\n } catch {\n return new TextEncoder().encode(payload).byteLength;\n }\n }\n const padding = payload.endsWith(\"==\") ? 2 : payload.endsWith(\"=\") ? 1 : 0;\n return Math.max(0, Math.floor((payload.length * 3) / 4) - padding);\n};\n\nconst stripMessageAttachmentBytes = (messages: unknown[]): unknown[] => {\n const cloned = cloneDiagnosticValue(messages);\n if (!Array.isArray(cloned)) return [];\n for (const message of cloned) {\n if (!message || typeof message !== \"object\" || !(\"parts\" in message)) continue;\n const parts = (message as { parts?: unknown }).parts;\n if (!Array.isArray(parts)) continue;\n for (const part of parts) {\n if (\n part &&\n typeof part === \"object\" &&\n \"type\" in part &&\n part.type === \"file\" &&\n \"url\" in part &&\n typeof part.url === \"string\" &&\n part.url.startsWith(\"data:\")\n ) {\n part.url = \"[attachment bytes retained separately when available]\";\n }\n }\n }\n return cloned;\n};\n\nconst getApproximateBytes = (value: unknown): number => {\n try {\n return new TextEncoder().encode(JSON.stringify(value)).byteLength;\n } catch {\n return 0;\n }\n};\n\nconst toAttachmentReference = (\n attachment: StoredAttachment,\n): SurveyAssistantDiagnosticAttachmentReference => ({\n bytes: attachment.bytes,\n filename: attachment.filename,\n mediaType: attachment.mediaType,\n sessionContentDigest: attachment.sessionContentDigest,\n storeKey: attachment.storeKey,\n});\n\nconst toPublicAttempt = ({ retainedBytes: _retainedBytes, ...attempt }: StoredAttempt) =>\n cloneDiagnosticValue(attempt);\n\nconst safeEventFields = (\n fields: SurveyAssistantDiagnosticEventFields | undefined,\n): SurveyAssistantDiagnosticEventFields | undefined => {\n if (!fields) return undefined;\n const allowed: SurveyAssistantDiagnosticEventFields = {};\n for (const [key, value] of Object.entries(fields)) {\n if (\n !/^(?:aborted|applied|changeSetId|code|count|durationMs|httpStatus|operationCount|retryable|status|turnId)$/.test(\n key,\n )\n )\n continue;\n if (\n value === null ||\n value === undefined ||\n typeof value === \"boolean\" ||\n typeof value === \"number\" ||\n typeof value === \"string\"\n ) {\n allowed[key] = typeof value === \"string\" ? value.slice(0, 240) : value;\n }\n }\n return Object.keys(allowed).length > 0 ? allowed : undefined;\n};\n\nexport const createSurveyAssistantDiagnosticStore = (\n overrides?: Partial<SurveyAssistantSupportBundleLimits>,\n): SurveyAssistantDiagnosticStore => {\n const limits = resolveSurveyAssistantSupportBundleLimits(overrides);\n const attempts: StoredAttempt[] = [];\n const attachments = new Map<string, StoredAttachment>();\n let attachmentSequence = 0;\n\n const latest = (threadId: string) =>\n [...attempts].reverse().find((attempt) => attempt.threadId === threadId);\n\n const exportAttempt = (threadId: string) => latest(threadId);\n\n const updateAttemptBytes = (attempt: StoredAttempt) => {\n const { retainedBytes: _retainedBytes, ...value } = attempt;\n attempt.retainedBytes = getApproximateBytes(value);\n };\n\n const retainedBytes = () =>\n attempts.reduce((total, attempt) => total + attempt.retainedBytes, 0) +\n [...attachments.values()].reduce((total, attachment) => total + attachment.retainedBytes, 0);\n\n const removeUnreferencedAttachments = () => {\n const retainedKeys = new Set(\n attempts.flatMap((attempt) => attempt.attachments.map((item) => item.storeKey)),\n );\n for (const key of attachments.keys()) if (!retainedKeys.has(key)) attachments.delete(key);\n };\n\n const enforceLimits = () => {\n if (attempts.length > limits.retainedAttempts) {\n const newest = attempts.at(-1)!;\n const newestFirst = [...attempts].reverse();\n const retained = new Set(\n [\n newest,\n ...newestFirst.filter(\n (attempt) =>\n attempt !== newest &&\n (attempt.error !== undefined || attempt.captureFailure !== undefined),\n ),\n ...newestFirst.filter(\n (attempt) =>\n attempt !== newest &&\n attempt.error === undefined &&\n attempt.captureFailure === undefined,\n ),\n ].slice(0, limits.retainedAttempts),\n );\n for (let index = attempts.length - 1; index >= 0; index -= 1) {\n if (!retained.has(attempts[index]!)) attempts.splice(index, 1);\n }\n }\n removeUnreferencedAttachments();\n if (retainedBytes() <= limits.attemptStoreBytes) return;\n\n const protectedAttempts = new Set(\n [...new Set(attempts.map((attempt) => attempt.threadId))]\n .map(exportAttempt)\n .filter((attempt): attempt is StoredAttempt => attempt !== undefined),\n );\n for (const attempt of attempts) {\n if (protectedAttempts.has(attempt)) continue;\n attempt.messages = undefined;\n attempt.submittedSurvey = undefined;\n updateAttemptBytes(attempt);\n if (retainedBytes() <= limits.attemptStoreBytes) return;\n }\n const protectedAttachmentKeys = new Set(\n [...protectedAttempts].flatMap((attempt) =>\n attempt.attachments.map((attachment) => attachment.storeKey),\n ),\n );\n for (const attachment of attachments.values()) {\n if (protectedAttachmentKeys.has(attachment.storeKey)) continue;\n attachment.dataUrl = undefined;\n attachment.retainedBytes = 0;\n if (retainedBytes() <= limits.attemptStoreBytes) return;\n }\n for (const attachment of attachments.values()) {\n attachment.dataUrl = undefined;\n attachment.retainedBytes = 0;\n if (retainedBytes() <= limits.attemptStoreBytes) return;\n }\n for (const protectedAttempt of protectedAttempts) {\n protectedAttempt.messages = undefined;\n protectedAttempt.submittedSurvey = undefined;\n protectedAttempt.captureFailure ??=\n \"Diagnostic content was evicted because the browser limit was reached.\";\n updateAttemptBytes(protectedAttempt);\n if (retainedBytes() <= limits.attemptStoreBytes) return;\n }\n };\n\n const retainAttachment = (file: FileUIPart): SurveyAssistantDiagnosticAttachmentReference => {\n const dataUrl =\n typeof file.url === \"string\" && file.url.startsWith(\"data:\") ? file.url : undefined;\n const mediaType = file.mediaType || \"application/octet-stream\";\n const filename = file.filename?.trim() || \"Attached document\";\n const bytes = dataUrl ? getDataUrlBytes(dataUrl) : 0;\n const sessionContentDigest = hashString(\n dataUrl ?? `${mediaType}\\u0000${filename}\\u0000${bytes}`,\n );\n if (dataUrl) {\n for (const candidate of attachments.values()) {\n if (\n candidate.sessionContentDigest === sessionContentDigest &&\n candidate.mediaType === mediaType &&\n candidate.bytes === bytes &&\n candidate.dataUrl === dataUrl\n ) {\n return toAttachmentReference(candidate);\n }\n }\n }\n attachmentSequence += 1;\n const stored: StoredAttachment = {\n bytes,\n filename,\n mediaType,\n sessionContentDigest,\n storeKey: `${sessionContentDigest}-${attachmentSequence}`,\n retainedBytes: dataUrl?.length ?? 0,\n ...(dataUrl ? { dataUrl } : {}),\n };\n attachments.set(stored.storeKey, stored);\n return toAttachmentReference(stored);\n };\n\n const retainAttachmentReference = (\n reference: SurveyAssistantAttachmentReference,\n ): SurveyAssistantDiagnosticAttachmentReference => {\n const filename = reference.filename.trim() || \"Attached document\";\n const mediaType = reference.mediaType || \"application/octet-stream\";\n const sessionContentDigest = hashString(\n `${reference.documentId ?? \"restored\"}\\u0000${mediaType}\\u0000${filename}\\u0000${reference.bytes}`,\n );\n attachmentSequence += 1;\n const stored: StoredAttachment = {\n bytes: reference.bytes,\n filename,\n mediaType,\n retainedBytes: 0,\n sessionContentDigest,\n storeKey: `${sessionContentDigest}-${attachmentSequence}`,\n };\n attachments.set(stored.storeKey, stored);\n return toAttachmentReference(stored);\n };\n\n const recordEvent = (\n threadId: string,\n event: string,\n fields?: SurveyAssistantDiagnosticEventFields,\n ) => {\n const attempt = latest(threadId);\n if (!attempt) return;\n attempt.events.push({\n at: new Date().toISOString(),\n event: event.slice(0, 80),\n ...(safeEventFields(fields) ? { fields: safeEventFields(fields) } : {}),\n });\n if (attempt.events.length > limits.attemptEvents) {\n attempt.events.splice(0, attempt.events.length - limits.attemptEvents);\n }\n updateAttemptBytes(attempt);\n };\n\n return {\n beginAttempt(input) {\n const requestId = input.requestId ?? createSurveyAssistantDiagnosticId();\n const attempt: StoredAttempt = {\n attachments: [\n ...input.files.map(retainAttachment),\n ...(input.attachmentReferences ?? []).map(retainAttachmentReference),\n ],\n events: [],\n ...(input.modelId ? { modelId: input.modelId } : {}),\n requestId,\n resourceId: input.resourceId,\n submittedAt: new Date().toISOString(),\n submittedSurvey: cloneDiagnosticValue(input.submittedSurvey),\n threadId: input.threadId,\n retainedBytes: 0,\n };\n updateAttemptBytes(attempt);\n attempts.push(attempt);\n recordEvent(input.threadId, \"submission\");\n enforceLimits();\n return requestId;\n },\n deleteThread(threadId) {\n for (let index = attempts.length - 1; index >= 0; index -= 1) {\n if (attempts[index]?.threadId === threadId) attempts.splice(index, 1);\n }\n removeUnreferencedAttachments();\n },\n getAttachment(storeKey) {\n return attachments.get(storeKey);\n },\n getExportAttempt(threadId) {\n const attempt = exportAttempt(threadId);\n return attempt ? toPublicAttempt(attempt) : undefined;\n },\n recordApplyOutcome(threadId, outcome) {\n const attempt = latest(threadId);\n if (!attempt) return;\n attempt.applyOutcome = cloneDiagnosticValue(outcome);\n recordEvent(threadId, \"apply-result\", { status: outcome.status });\n enforceLimits();\n },\n recordApplyReceipts(threadId, receipts) {\n const attempt = latest(threadId);\n if (!attempt) return;\n attempt.applyReceipts = cloneDiagnosticValue(receipts);\n recordEvent(threadId, \"apply-receipts\", {\n count: receipts.length,\n operationCount: receipts.reduce((sum, receipt) => sum + receipt.operationCount, 0),\n });\n enforceLimits();\n },\n recordEvent,\n recordFailure(threadId, messages, error) {\n const attempt = latest(threadId);\n if (!attempt) return;\n try {\n attempt.messages = stripMessageAttachmentBytes(messages);\n attempt.error = cloneDiagnosticValue(error);\n recordEvent(threadId, \"failure\", {\n code: error.code,\n httpStatus: error.upstreamStatus,\n retryable: error.retryable,\n });\n enforceLimits();\n } catch {\n attempt.messages = undefined;\n attempt.captureFailure = \"The failed assistant messages could not be captured.\";\n recordEvent(threadId, \"capture-failed\");\n }\n },\n recordTurnFinal(threadId, turnFinal) {\n const attempt = latest(threadId);\n if (!attempt) return;\n attempt.turnFinal = cloneDiagnosticValue(turnFinal);\n recordEvent(threadId, \"turn-final\", {\n durationMs: turnFinal.durationMs,\n status: turnFinal.status,\n turnId: turnFinal.turnId,\n });\n enforceLimits();\n },\n };\n};\n","","import {\n getSurveyAssistantEmbeddedBinaryMarker,\n isSurveyAssistantSensitiveMetadataKey,\n redactSurveyAssistantDiagnosticSecrets,\n type SurveyAssistantSnapshot,\n} from \"../protocol\";\nimport { Zip, ZipPassThrough } from \"fflate\";\nimport type { SurveyAssistantController } from \"./controller\";\nimport type {\n SurveyAssistantDiagnosticAttempt,\n SurveyAssistantDiagnosticStore,\n} from \"./diagnostic-store\";\nimport {\n resolveSurveyAssistantSupportBundleLimits,\n type SurveyAssistantSupportBundleLimits,\n} from \"./support-bundle-limits\";\nimport type { SurveyAssistantThreadClient } from \"./thread-client\";\nimport { version as surveyAssistantPackageVersion } from \"../../package.json\";\n\nexport type SurveyAssistantSupportBundleCategory = \"attachments\" | \"conversation\" | \"survey\";\n\nexport type SurveyAssistantSupportBundleSelection = Record<\n SurveyAssistantSupportBundleCategory,\n boolean\n>;\n\nexport const SURVEY_ASSISTANT_DEFAULT_SUPPORT_BUNDLE_SELECTION = {\n attachments: true,\n conversation: true,\n survey: true,\n} as const satisfies SurveyAssistantSupportBundleSelection;\n\nexport interface SurveyAssistantSupportBundleConfig {\n /** Set to false to disable support-bundle preparation and generation. Defaults to true. */\n enabled?: boolean;\n hostBuildVersion?: string;\n limits?: Partial<SurveyAssistantSupportBundleLimits>;\n packageVersion?: string;\n subjectPrefix?: string;\n supportEmail?: string;\n}\n\nexport const isSurveyAssistantSupportBundleEnabled = (\n config?: SurveyAssistantSupportBundleConfig,\n): boolean => config?.enabled !== false;\n\nconst assertSurveyAssistantSupportBundleEnabled = (config?: SurveyAssistantSupportBundleConfig) => {\n if (!isSurveyAssistantSupportBundleEnabled(config)) {\n throw new Error(\"Support bundle export is disabled by host configuration.\");\n }\n};\n\ninterface PreparedEntry {\n bytes: Uint8Array;\n category: SurveyAssistantSupportBundleCategory;\n path: string;\n source: \"authorized-transcript\" | \"browser-session\";\n}\n\ninterface UnavailableComponent {\n bytes?: number;\n category: SurveyAssistantSupportBundleCategory;\n filename?: string;\n mediaType?: string;\n reason: \"capture-failed\" | \"no-attempt-retained\" | \"not-retained\" | \"too-large\" | \"unavailable\";\n path?: string;\n}\n\ninterface DeclinedUnavailableComponents {\n category: SurveyAssistantSupportBundleCategory;\n itemCount: number;\n totalBytes: number;\n}\n\nexport interface PreparedSurveyAssistantSupportBundle {\n attempt?: SurveyAssistantDiagnosticAttempt;\n categoryBytes: Record<SurveyAssistantSupportBundleCategory, number>;\n currentSurveyCapturedAt: string;\n entries: PreparedEntry[];\n limits: SurveyAssistantSupportBundleLimits;\n resourceId: string;\n threadId: string;\n unavailable: UnavailableComponent[];\n}\n\nexport interface GeneratedSurveyAssistantSupportBundle {\n blob: Blob;\n filename: string;\n generatedAt: string;\n includedCategories: SurveyAssistantSupportBundleCategory[];\n size: number;\n}\n\nconst encoder = new TextEncoder();\n\nconst encodeJson = (value: unknown): Uint8Array => encoder.encode(JSON.stringify(value));\n\nconst abortIfNeeded = (signal?: AbortSignal) => {\n if (signal?.aborted)\n throw new DOMException(\"Support bundle preparation was cancelled.\", \"AbortError\");\n};\n\ninterface SanitizationState {\n nodes: number;\n redactions: number;\n truncated: boolean;\n}\n\nconst sanitizeValue = (\n value: unknown,\n state: SanitizationState,\n parent?: Record<string, unknown>,\n key?: string,\n depth = 0,\n): unknown => {\n state.nodes += 1;\n if (state.nodes > 100_000) {\n state.redactions += 1;\n state.truncated = true;\n return { redacted: \"node-limit\" };\n }\n if (depth > 32) {\n state.redactions += 1;\n state.truncated = true;\n return { redacted: \"depth-limit\" };\n }\n\n const binaryMarker = getSurveyAssistantEmbeddedBinaryMarker(value, parent, key);\n if (binaryMarker) {\n state.redactions += 1;\n return binaryMarker;\n }\n if (key && isSurveyAssistantSensitiveMetadataKey(key)) {\n state.redactions += 1;\n return { redacted: \"sensitive-field\" };\n }\n if (typeof value === \"string\") {\n const redacted = redactSurveyAssistantDiagnosticSecrets(value);\n if (redacted !== value) state.redactions += 1;\n return redacted.length > 200_000 ? `${redacted.slice(0, 199_999)}…` : redacted;\n }\n if (value === null || typeof value === \"number\" || typeof value === \"boolean\") return value;\n if (value === undefined) return undefined;\n if (Array.isArray(value)) {\n if (value.length > 20_000) state.truncated = true;\n return value\n .slice(0, 20_000)\n .map((item) => sanitizeValue(item, state, undefined, undefined, depth + 1));\n }\n if (typeof value !== \"object\") return String(value);\n\n const record = value as Record<string, unknown>;\n const sanitized: Record<string, unknown> = {};\n const entries = Object.entries(record);\n if (entries.length > 20_000) state.truncated = true;\n for (const [childKey, childValue] of entries.slice(0, 20_000)) {\n sanitized[childKey] = sanitizeValue(childValue, state, record, childKey, depth + 1);\n }\n return sanitized;\n};\n\nexport const sanitizeSurveyAssistantSupportValue = (value: unknown) => {\n const state: SanitizationState = { nodes: 0, redactions: 0, truncated: false };\n const sanitized = sanitizeValue(value, state);\n return { redactions: state.redactions, truncated: state.truncated, value: sanitized };\n};\n\nconst createJsonEntry = (\n path: string,\n category: SurveyAssistantSupportBundleCategory,\n source: PreparedEntry[\"source\"],\n value: unknown,\n): PreparedEntry => {\n const state: SanitizationState = { nodes: 0, redactions: 0, truncated: false };\n const sanitized = sanitizeValue(value, state);\n return {\n bytes: encodeJson({\n redactions: state.redactions,\n truncated: state.truncated,\n value: sanitized,\n }),\n category,\n path,\n source,\n };\n};\n\nconst snapshotVersion = (snapshot: SurveyAssistantSnapshot | null | undefined) => snapshot?.version;\n\nconst extensionForMediaType = (mediaType: string): string => {\n switch (mediaType.toLocaleLowerCase()) {\n case \"application/pdf\":\n return \".pdf\";\n case \"image/jpeg\":\n return \".jpg\";\n case \"image/png\":\n return \".png\";\n default:\n return \".bin\";\n }\n};\n\nconst sanitizeFilename = (filename: string, mediaType: string): string => {\n const extension = extensionForMediaType(mediaType);\n const withoutExtension = filename.replace(/\\.[a-z0-9]{1,10}$/i, \"\");\n const stem = withoutExtension\n .normalize(\"NFKD\")\n .replace(/[^A-Za-z0-9._-]+/g, \"-\")\n .replace(/^[._-]+|[._-]+$/g, \"\")\n .slice(0, 100);\n return `${stem || \"attachment\"}${extension}`;\n};\n\nconst disambiguateFilenames = (files: Array<{ filename: string; mediaType: string }>): string[] => {\n const used = new Set<string>();\n return files.map((file) => {\n const sanitized = sanitizeFilename(file.filename, file.mediaType);\n const dot = sanitized.lastIndexOf(\".\");\n const stem = dot > 0 ? sanitized.slice(0, dot) : sanitized;\n const extension = dot > 0 ? sanitized.slice(dot) : \"\";\n let candidate = sanitized;\n let index = 2;\n while (used.has(candidate.toLocaleLowerCase())) {\n candidate = `${stem}-${index}${extension}`;\n index += 1;\n }\n used.add(candidate.toLocaleLowerCase());\n return candidate;\n });\n};\n\nconst dataUrlToBytes = (dataUrl: string): Uint8Array => {\n const comma = dataUrl.indexOf(\",\");\n if (comma < 0) return encoder.encode(dataUrl);\n const metadata = dataUrl.slice(0, comma);\n const payload = dataUrl.slice(comma + 1);\n if (!/;base64$/i.test(metadata)) return encoder.encode(decodeURIComponent(payload));\n const decoded = globalThis.atob(payload);\n const bytes = new Uint8Array(decoded.length);\n for (let index = 0; index < decoded.length; index += 1) bytes[index] = decoded.charCodeAt(index);\n return bytes;\n};\n\nconst pushPreparedEntry = (\n entries: PreparedEntry[],\n unavailable: UnavailableComponent[],\n entry: PreparedEntry,\n limits: SurveyAssistantSupportBundleLimits,\n) => {\n if (entry.bytes.byteLength > limits.zipEntryBytes) {\n unavailable.push({\n bytes: entry.bytes.byteLength,\n category: entry.category,\n path: entry.path,\n reason: \"too-large\",\n });\n return;\n }\n entries.push(entry);\n};\n\nexport const prepareSurveyAssistantSupportBundle = async ({\n config,\n controller,\n diagnosticStore,\n resourceId,\n signal,\n threadClient,\n threadId,\n}: {\n config?: SurveyAssistantSupportBundleConfig;\n controller?: SurveyAssistantController | null;\n diagnosticStore: SurveyAssistantDiagnosticStore;\n resourceId: string;\n signal?: AbortSignal;\n threadClient: SurveyAssistantThreadClient;\n threadId: string;\n}): Promise<PreparedSurveyAssistantSupportBundle> => {\n assertSurveyAssistantSupportBundleEnabled(config);\n const limits = resolveSurveyAssistantSupportBundleLimits(config?.limits);\n const entries: PreparedEntry[] = [];\n const unavailable: UnavailableComponent[] = [];\n const attempt = diagnosticStore.getExportAttempt(threadId);\n const currentSurveyCapturedAt = new Date().toISOString();\n let currentSurvey: SurveyAssistantSnapshot | null = null;\n try {\n currentSurvey = controller?.getSnapshot() ?? null;\n if (currentSurvey) {\n currentSurvey =\n typeof structuredClone === \"function\"\n ? structuredClone(currentSurvey)\n : (JSON.parse(JSON.stringify(currentSurvey)) as SurveyAssistantSnapshot);\n }\n } catch {\n unavailable.push({\n category: \"survey\",\n reason: \"capture-failed\",\n path: \"survey/current-survey.json\",\n });\n }\n\n abortIfNeeded(signal);\n if (!attempt) {\n unavailable.push(\n {\n category: \"conversation\",\n path: \"conversation/attempt-messages.json\",\n reason: \"no-attempt-retained\",\n },\n {\n category: \"conversation\",\n path: \"diagnostics/client-apply-outcome.json\",\n reason: \"no-attempt-retained\",\n },\n {\n category: \"conversation\",\n path: \"diagnostics/client-apply-receipts.json\",\n reason: \"no-attempt-retained\",\n },\n { category: \"attachments\", reason: \"no-attempt-retained\" },\n );\n }\n if (attempt?.messages) {\n pushPreparedEntry(\n entries,\n unavailable,\n createJsonEntry(\n \"conversation/attempt-messages.json\",\n \"conversation\",\n \"browser-session\",\n attempt.messages,\n ),\n limits,\n );\n } else if (attempt?.captureFailure) {\n unavailable.push({\n category: \"conversation\",\n reason: \"capture-failed\",\n path: \"conversation/attempt-messages.json\",\n });\n } else if (attempt) {\n unavailable.push({\n category: \"conversation\",\n reason: \"not-retained\",\n path: \"conversation/attempt-messages.json\",\n });\n }\n if (attempt?.applyOutcome) {\n pushPreparedEntry(\n entries,\n unavailable,\n createJsonEntry(\n \"diagnostics/client-apply-outcome.json\",\n \"conversation\",\n \"browser-session\",\n attempt.applyOutcome,\n ),\n limits,\n );\n }\n if (attempt?.applyReceipts) {\n pushPreparedEntry(\n entries,\n unavailable,\n createJsonEntry(\n \"diagnostics/client-apply-receipts.json\",\n \"conversation\",\n \"browser-session\",\n attempt.applyReceipts,\n ),\n limits,\n );\n }\n\n const transcriptMessages: unknown[] = [];\n let transcriptBytes = 0;\n let transcriptCursor: string | undefined;\n let transcriptRedactions = 0;\n let transcriptTruncated = false;\n try {\n for (let page = 0; page < limits.transcriptPages; page += 1) {\n abortIfNeeded(signal);\n const transcript = await threadClient.read(threadId, transcriptCursor, { signal });\n abortIfNeeded(signal);\n const pageState: SanitizationState = { nodes: 0, redactions: 0, truncated: false };\n const sanitizedPage = sanitizeValue(transcript.messages, pageState);\n transcriptRedactions += pageState.redactions;\n transcriptTruncated ||= pageState.truncated;\n const pageMessages = Array.isArray(sanitizedPage) ? sanitizedPage : [];\n const pageBytes = encodeJson(pageMessages).byteLength;\n if (\n transcriptMessages.length + pageMessages.length > limits.transcriptMessages ||\n transcriptBytes + pageBytes > limits.transcriptBytes\n ) {\n transcriptTruncated = true;\n break;\n }\n transcriptMessages.unshift(...pageMessages);\n transcriptBytes += pageBytes;\n transcriptCursor = transcript.nextCursor;\n if (!transcriptCursor) break;\n if (page === limits.transcriptPages - 1) transcriptTruncated = true;\n }\n pushPreparedEntry(\n entries,\n unavailable,\n {\n bytes: encodeJson({\n messages: transcriptMessages,\n redactions: transcriptRedactions,\n truncated: transcriptTruncated,\n }),\n category: \"conversation\",\n path: \"conversation/transcript.json\",\n source: \"authorized-transcript\",\n },\n limits,\n );\n } catch (error) {\n if (signal?.aborted) throw error;\n unavailable.push({\n category: \"conversation\",\n reason: \"unavailable\",\n path: \"conversation/transcript.json\",\n });\n }\n\n if (attempt?.submittedSurvey !== undefined) {\n pushPreparedEntry(\n entries,\n unavailable,\n createJsonEntry(\"survey/submitted-survey.json\", \"survey\", \"browser-session\", {\n snapshot: attempt.submittedSurvey,\n version: snapshotVersion(attempt.submittedSurvey),\n }),\n limits,\n );\n } else {\n unavailable.push({\n category: \"survey\",\n reason: attempt ? \"not-retained\" : \"no-attempt-retained\",\n path: \"survey/submitted-survey.json\",\n });\n }\n if (currentSurvey) {\n pushPreparedEntry(\n entries,\n unavailable,\n createJsonEntry(\"survey/current-survey.json\", \"survey\", \"browser-session\", {\n capturedAt: currentSurveyCapturedAt,\n snapshot: currentSurvey,\n version: snapshotVersion(currentSurvey),\n }),\n limits,\n );\n }\n\n if (attempt) {\n const availableAttachments = attempt.attachments\n .map((reference) => ({\n reference,\n stored: diagnosticStore.getAttachment(reference.storeKey),\n }))\n .filter((item) => Boolean(item.stored?.dataUrl));\n const filenames = disambiguateFilenames(availableAttachments.map(({ reference }) => reference));\n for (const [index, { reference, stored }] of availableAttachments.entries()) {\n abortIfNeeded(signal);\n const bytes = dataUrlToBytes(stored!.dataUrl!);\n pushPreparedEntry(\n entries,\n unavailable,\n {\n bytes,\n category: \"attachments\",\n path: `attachments/${filenames[index]}`,\n source: \"browser-session\",\n },\n limits,\n );\n }\n for (const reference of attempt.attachments) {\n if (!diagnosticStore.getAttachment(reference.storeKey)?.dataUrl) {\n unavailable.push({\n bytes: reference.bytes,\n category: \"attachments\",\n filename: reference.filename,\n mediaType: reference.mediaType,\n reason: \"not-retained\",\n });\n }\n }\n }\n\n const categoryBytes = {\n attachments: 0,\n conversation: 0,\n survey: 0,\n } satisfies Record<SurveyAssistantSupportBundleCategory, number>;\n for (const entry of entries) categoryBytes[entry.category] += entry.bytes.byteLength;\n\n return {\n attempt,\n categoryBytes,\n currentSurveyCapturedAt,\n entries,\n limits,\n resourceId,\n threadId,\n unavailable,\n };\n};\n\nconst validateZipPath = (path: string) => {\n if (!path || path.startsWith(\"/\") || path.includes(\"\\\\\") || path.split(\"/\").includes(\"..\")) {\n throw new Error(`Unsafe support-bundle ZIP path: ${path}`);\n }\n};\n\nconst toBlobPart = (bytes: Uint8Array): ArrayBuffer => {\n if (\n bytes.buffer instanceof ArrayBuffer &&\n bytes.byteOffset === 0 &&\n bytes.byteLength === bytes.buffer.byteLength\n ) {\n return bytes.buffer;\n }\n return bytes.slice().buffer as ArrayBuffer;\n};\n\nconst createZipBlob = (entries: Array<{ bytes: Uint8Array; path: string }>): Promise<Blob> => {\n const paths = new Set<string>();\n for (const entry of entries) {\n validateZipPath(entry.path);\n if (paths.has(entry.path)) throw new Error(`Duplicate support-bundle ZIP path: ${entry.path}`);\n paths.add(entry.path);\n }\n return new Promise((resolve, reject) => {\n const chunks: BlobPart[] = [];\n const zip = new Zip((error, data, final) => {\n if (error) {\n reject(error);\n return;\n }\n chunks.push(toBlobPart(data));\n if (final) resolve(new Blob(chunks, { type: \"application/zip\" }));\n });\n try {\n for (const entry of entries) {\n const file = new ZipPassThrough(entry.path);\n zip.add(file);\n file.push(entry.bytes, true);\n }\n zip.end();\n } catch (error) {\n zip.terminate();\n reject(error);\n }\n });\n};\n\nconst categoryDescriptors = (\n prepared: PreparedSurveyAssistantSupportBundle,\n selection: SurveyAssistantSupportBundleSelection,\n) =>\n (Object.keys(selection) as SurveyAssistantSupportBundleCategory[]).map((category) => {\n const entries = prepared.entries.filter((entry) => entry.category === category);\n return selection[category]\n ? {\n category,\n included: true,\n itemCount: entries.length,\n totalBytes: entries.reduce((total, entry) => total + entry.bytes.byteLength, 0),\n entries: entries.map((entry) => ({\n bytes: entry.bytes.byteLength,\n path: entry.path,\n source: entry.source,\n })),\n }\n : {\n category,\n included: false,\n itemCount: entries.length,\n totalBytes: entries.reduce((total, entry) => total + entry.bytes.byteLength, 0),\n };\n });\n\nconst createAttemptMetadata = (\n prepared: PreparedSurveyAssistantSupportBundle,\n selection: SurveyAssistantSupportBundleSelection,\n) => {\n const attempt = prepared.attempt;\n return {\n attemptAvailable: Boolean(attempt),\n ...(attempt\n ? {\n captureFailure: attempt.captureFailure,\n error: attempt.error,\n events: attempt.events,\n modelId: attempt.modelId,\n requestId: attempt.requestId,\n resourceId: attempt.resourceId,\n submittedAt: attempt.submittedAt,\n threadId: attempt.threadId,\n turnFinal: attempt.turnFinal,\n }\n : { threadId: prepared.threadId }),\n categories: categoryDescriptors(prepared, selection),\n };\n};\n\nconst encodeSanitizedJson = (value: unknown): Uint8Array =>\n encodeJson(sanitizeSurveyAssistantSupportValue(value).value);\n\nconst createRequiredEntries = (\n prepared: PreparedSurveyAssistantSupportBundle,\n selection: SurveyAssistantSupportBundleSelection,\n config: SurveyAssistantSupportBundleConfig | undefined,\n generatedAt: string,\n) => {\n const descriptors = categoryDescriptors(prepared, selection);\n const unavailable = (Object.keys(selection) as SurveyAssistantSupportBundleCategory[]).flatMap<\n UnavailableComponent | DeclinedUnavailableComponents\n >((category) => {\n const categoryUnavailable = prepared.unavailable.filter((item) => item.category === category);\n if (categoryUnavailable.length === 0) return [];\n if (selection[category]) return categoryUnavailable;\n return [\n {\n category,\n itemCount: categoryUnavailable.length,\n totalBytes: categoryUnavailable.reduce((total, item) => total + (item.bytes ?? 0), 0),\n },\n ];\n });\n const manifest = {\n schemaVersion: 1,\n generatedAt,\n packageVersion: config?.packageVersion ?? surveyAssistantPackageVersion,\n hostBuildVersion: config?.hostBuildVersion,\n resourceId: prepared.resourceId,\n threadId: prepared.threadId,\n requestId: prepared.attempt?.requestId,\n turnId: prepared.attempt?.turnFinal?.turnId,\n modelId: prepared.attempt?.modelId,\n categories: descriptors,\n unavailable,\n currentSurveyCapturedAt: prepared.currentSurveyCapturedAt,\n };\n const readme = [\n \"CASE Survey Assistant support bundle\",\n \"\",\n `Generated: ${generatedAt}`,\n \"This archive contains diagnostic data selected by the user, including visible model reasoning when conversation data is included.\",\n \"Nothing was uploaded or emailed automatically.\",\n \"See manifest.json for the authoritative inventory and availability information.\",\n \"Treat the archive as potentially sensitive.\",\n ].join(\"\\n\");\n return [\n { bytes: encodeSanitizedJson(manifest), path: \"manifest.json\" },\n { bytes: encoder.encode(readme), path: \"README.txt\" },\n {\n bytes: encodeSanitizedJson(createAttemptMetadata(prepared, selection)),\n path: \"diagnostics/client-attempt.json\",\n },\n ];\n};\n\nconst estimateArchiveBytes = (entries: Array<{ bytes: Uint8Array; path: string }>) =>\n entries.reduce(\n (total, entry) =>\n total + entry.bytes.byteLength + encoder.encode(entry.path).byteLength * 2 + 110,\n 22,\n );\n\nexport const estimateSurveyAssistantSupportBundleBytes = (\n prepared: PreparedSurveyAssistantSupportBundle,\n selection: SurveyAssistantSupportBundleSelection,\n config?: SurveyAssistantSupportBundleConfig,\n): number => {\n if (!isSurveyAssistantSupportBundleEnabled(config)) return 0;\n const entries = [\n ...createRequiredEntries(prepared, selection, config, new Date().toISOString()),\n ...prepared.entries\n .filter((entry) => selection[entry.category])\n .map(({ bytes, path }) => ({ bytes, path })),\n ];\n return estimateArchiveBytes(entries);\n};\n\nexport const generateSurveyAssistantSupportBundle = async (\n prepared: PreparedSurveyAssistantSupportBundle,\n selection: SurveyAssistantSupportBundleSelection,\n config?: SurveyAssistantSupportBundleConfig,\n): Promise<GeneratedSurveyAssistantSupportBundle> => {\n assertSurveyAssistantSupportBundleEnabled(config);\n const generatedAt = new Date().toISOString();\n const selectedEntries = prepared.entries.filter((entry) => selection[entry.category]);\n const allEntries = [\n ...createRequiredEntries(prepared, selection, config, generatedAt),\n ...selectedEntries.map(({ bytes, path }) => ({ bytes, path })),\n ];\n const estimatedBytes = estimateArchiveBytes(allEntries);\n if (estimatedBytes > prepared.limits.bundleBytes) {\n throw new Error(\"The selected support-bundle data exceeds the configured bundle limit.\");\n }\n const blob = await createZipBlob(allEntries);\n if (blob.size > prepared.limits.bundleBytes) {\n throw new Error(\"The selected support-bundle data exceeds the configured bundle limit.\");\n }\n const safeToken =\n (prepared.attempt?.requestId ?? prepared.attempt?.turnFinal?.turnId ?? \"unidentified\")\n .replace(/[^A-Za-z0-9_-]/g, \"-\")\n .slice(0, 64) || \"unidentified\";\n const timestamp = generatedAt.replace(/[-:]/g, \"\").replace(/\\.\\d{3}Z$/, \"Z\");\n return {\n blob,\n filename: `case-survey-assistant-support-${safeToken}-${timestamp}.zip`,\n generatedAt,\n includedCategories: (Object.keys(selection) as SurveyAssistantSupportBundleCategory[]).filter(\n (category) => selection[category],\n ),\n size: blob.size,\n };\n};\n\nexport const downloadSurveyAssistantSupportBundle = (\n bundle: GeneratedSurveyAssistantSupportBundle,\n) => {\n const url = URL.createObjectURL(bundle.blob);\n const anchor = document.createElement(\"a\");\n anchor.href = url;\n anchor.download = bundle.filename;\n anchor.style.display = \"none\";\n document.body.append(anchor);\n anchor.click();\n anchor.remove();\n window.setTimeout(() => URL.revokeObjectURL(url), 0);\n};\n\nexport const createSurveyAssistantSupportDetails = ({\n bundle,\n prepared,\n}: {\n bundle: GeneratedSurveyAssistantSupportBundle;\n prepared: PreparedSurveyAssistantSupportBundle;\n}): string =>\n [\n `File: ${bundle.filename}`,\n `Request: ${prepared.attempt?.requestId ?? \"unavailable\"}`,\n `Model: ${prepared.attempt?.modelId ?? \"unavailable\"}`,\n `Error category: ${prepared.attempt?.error?.code ?? \"unavailable\"}`,\n `Generated: ${bundle.generatedAt}`,\n ].join(\"\\n\");\n\nexport const createSurveyAssistantSupportMailto = ({\n bundle,\n config,\n prepared,\n}: {\n bundle: GeneratedSurveyAssistantSupportBundle;\n config: SurveyAssistantSupportBundleConfig;\n prepared: PreparedSurveyAssistantSupportBundle;\n}): string | undefined => {\n if (!isSurveyAssistantSupportBundleEnabled(config)) return undefined;\n if (!config.supportEmail?.trim()) return undefined;\n const subject =\n `${config.subjectPrefix?.trim() || \"CASE Survey Assistant support\"} ${prepared.attempt?.requestId ?? \"\"}`.trim();\n const body = [\n \"IMPORTANT: ATTACH THE DOWNLOADED ZIP FILE TO THIS EMAIL BEFORE SENDING.\",\n \"\",\n \"A Survey Assistant support bundle has been downloaded for this issue.\",\n \"\",\n createSurveyAssistantSupportDetails({ bundle, prepared }),\n ].join(\"\\n\");\n return `mailto:${encodeURIComponent(config.supportEmail.trim())}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;\n};\n","import { useCallback, useEffect, useState } from \"react\";\nimport {\n surveyAssistantModelCatalogSchema,\n type SurveyAssistantModelCatalog,\n type SurveyAssistantModelOption,\n} from \"../protocol\";\nimport { readSurveyAssistantJson } from \"./client-error\";\n\nconst DEFAULT_MODEL_STORAGE_KEY = \"survey-assistant-selected-model\";\n\nexport interface SurveyAssistantModelCatalogClient {\n get(): Promise<SurveyAssistantModelCatalog>;\n}\n\nexport const createSurveyAssistantModelCatalogClient = (\n api = \"/api/survey-assistant/models\",\n): SurveyAssistantModelCatalogClient => ({\n async get() {\n const body = await readSurveyAssistantJson(\n await fetch(api, { cache: \"no-store\" }),\n \"The assistant model catalog could not be loaded.\",\n );\n return surveyAssistantModelCatalogSchema.parse(body);\n },\n});\n\nexport interface UseSurveyAssistantModelCatalogOptions {\n api?: string;\n client?: SurveyAssistantModelCatalogClient;\n onModelChange?(modelId: string): void;\n storageKey?: string | false;\n}\n\nexport interface SurveyAssistantModelCatalogState {\n error: Error | null;\n loading: boolean;\n modelId?: string;\n models: SurveyAssistantModelOption[];\n reload(): void;\n selectModel(modelId: string): void;\n}\n\nexport const useSurveyAssistantModelCatalog = ({\n api,\n client: providedClient,\n onModelChange,\n storageKey = DEFAULT_MODEL_STORAGE_KEY,\n}: UseSurveyAssistantModelCatalogOptions = {}): SurveyAssistantModelCatalogState => {\n const [models, setModels] = useState<SurveyAssistantModelOption[]>([]);\n const [modelId, setModelId] = useState<string>();\n const [error, setError] = useState<Error | null>(null);\n const [loading, setLoading] = useState(true);\n const [reloadToken, setReloadToken] = useState(0);\n\n useEffect(() => {\n let cancelled = false;\n const client = providedClient ?? createSurveyAssistantModelCatalogClient(api);\n setLoading(true);\n setError(null);\n void client\n .get()\n .then((catalog) => {\n if (cancelled) return;\n const rememberedId =\n storageKey && typeof window !== \"undefined\"\n ? (window.localStorage.getItem(storageKey) ?? undefined)\n : undefined;\n const selectedId =\n rememberedId && catalog.models.some((model) => model.id === rememberedId)\n ? rememberedId\n : catalog.defaultModelId;\n setModels(catalog.models);\n setModelId(selectedId);\n onModelChange?.(selectedId);\n })\n .catch((reason: unknown) => {\n if (!cancelled) setError(reason instanceof Error ? reason : new Error(String(reason)));\n })\n .finally(() => {\n if (!cancelled) setLoading(false);\n });\n return () => {\n cancelled = true;\n };\n }, [api, onModelChange, providedClient, reloadToken, storageKey]);\n\n const selectModel = useCallback(\n (nextModelId: string) => {\n if (!models.some((model) => model.id === nextModelId)) return;\n setModelId(nextModelId);\n if (storageKey && typeof window !== \"undefined\") {\n window.localStorage.setItem(storageKey, nextModelId);\n }\n onModelChange?.(nextModelId);\n },\n [models, onModelChange, storageKey],\n );\n\n const reload = useCallback(() => setReloadToken((current) => current + 1), []);\n\n return { error, loading, modelId, models, reload, selectModel };\n};\n","\"use client\";\n\nimport {\n surveyDocumentVersionSchema,\n type SurveyAssistantSnapshot,\n type SurveyDocumentVersion,\n} from \"../protocol\";\n\nconst STORAGE_PREFIX = \"case-survey-assistant:settled-document:\";\nconst memoryBaselines = new Map<string, SurveyDocumentVersion>();\n\nconst getStorageKey = (resourceId: string, threadId: string) =>\n `${STORAGE_PREFIX}${encodeURIComponent(resourceId)}:${encodeURIComponent(threadId)}`;\n\nconst getSessionStorage = (): Storage | undefined => {\n if (typeof document === \"undefined\") return undefined;\n\n try {\n return window.sessionStorage;\n } catch {\n return undefined;\n }\n};\n\nexport const readSettledDocumentVersion = ({\n resourceId,\n threadId,\n}: {\n resourceId: string;\n threadId: string;\n}): SurveyDocumentVersion | undefined => {\n const storageKey = getStorageKey(resourceId, threadId);\n const storedInMemory = memoryBaselines.get(storageKey);\n if (storedInMemory) return { ...storedInMemory };\n\n const serialized = getSessionStorage()?.getItem(storageKey);\n if (!serialized) return undefined;\n\n try {\n const parsed = surveyDocumentVersionSchema.safeParse(JSON.parse(serialized));\n if (!parsed.success) return undefined;\n memoryBaselines.set(storageKey, parsed.data);\n return { ...parsed.data };\n } catch {\n return undefined;\n }\n};\n\nexport const writeSettledDocumentVersion = ({\n resourceId,\n snapshot,\n threadId,\n}: {\n resourceId: string;\n snapshot: SurveyAssistantSnapshot;\n threadId: string;\n}): void => {\n const storageKey = getStorageKey(resourceId, threadId);\n const version = surveyDocumentVersionSchema.parse(snapshot.version);\n memoryBaselines.set(storageKey, version);\n\n try {\n getSessionStorage()?.setItem(storageKey, JSON.stringify(version));\n } catch {\n // In-memory continuity still works when browser storage is disabled or full.\n }\n};\n","\"use client\";\n\nimport { useChat } from \"@ai-sdk/react\";\nimport {\n SURVEY_ASSISTANT_ATTACHMENT_PART_TYPE,\n SURVEY_ASSISTANT_PROTOCOL_VERSION,\n parseSurveyAssistantError,\n surveyAssistantApplyOutcomeSchema,\n type ApplyReceipt,\n type SurveyAssistantApplyOutcome,\n type SurveyAssistantAttachmentReference,\n type SurveyApplyResult,\n type SurveyAssistantApplyPolicy,\n type SurveyAssistantTurnFinal,\n type SurveyChangeSet,\n} from \"../protocol\";\nimport type { ChatStatus, FileUIPart, UIMessage } from \"ai\";\nimport {\n useCallback,\n useEffect,\n useEffectEvent,\n useMemo,\n useReducer,\n useRef,\n useState,\n} from \"react\";\nimport {\n collectSurveyChangeSets,\n createApplyReceipts,\n resolveLatestSurveyTurnAuthorization,\n resolveSurveyTurnOutcome,\n} from \"./turn-authorization\";\nimport { isSurveyAssistantTurnActive, reduceSurveyAssistantSessionState } from \"./session-state\";\nimport type { SurveyAssistantSessionState } from \"./session-state\";\nimport type { SurveyTurnOutcome } from \"./turn-authorization\";\nimport { createSurveyAssistantTransport } from \"./transport\";\nimport type { SurveyAssistantController } from \"./controller\";\nimport { readSettledDocumentVersion, writeSettledDocumentVersion } from \"./document-baseline\";\nimport {\n applySurveyAssistantLaunchUIContext,\n type SurveyAssistantLaunchUIContext,\n} from \"./thread-launcher\";\nimport {\n createSurveyAssistantDiagnosticId,\n type SurveyAssistantDiagnosticStore,\n} from \"./diagnostic-store\";\n\nconst createLocalId = (prefix: string) => {\n return createSurveyAssistantDiagnosticId(prefix);\n};\n\nconst compactOutcomeText = (value: string, maximum: number, fallback: string) => {\n const normalized = value.trim() || fallback;\n return normalized.length > maximum ? `${normalized.slice(0, maximum - 1)}…` : normalized;\n};\n\nconst createApplyOutcome = ({\n message,\n preparedChanges,\n results,\n status,\n turnId,\n}: {\n message: string;\n preparedChanges?: SurveyChangeSet[];\n results?: SurveyApplyResult[];\n status: SurveyAssistantApplyOutcome[\"status\"];\n turnId: string;\n}): SurveyAssistantApplyOutcome =>\n surveyAssistantApplyOutcomeSchema.parse({\n protocolVersion: SURVEY_ASSISTANT_PROTOCOL_VERSION,\n turnId,\n status,\n message: compactOutcomeText(message, 2_000, \"No lifecycle detail was reported.\"),\n ...(results && results.length > 0\n ? {\n results: results.slice(0, 100).map((result) => ({\n status: result.status,\n changeId: compactOutcomeText(result.changeId, 240, \"unknown-change\"),\n summary: compactOutcomeText(result.summary, 500, \"Survey change\"),\n message: compactOutcomeText(result.message, 2_000, \"No apply detail was reported.\"),\n appliedOperations: result.appliedOperations,\n })),\n }\n : {}),\n ...(preparedChanges && preparedChanges.length > 0\n ? {\n preparedChanges: preparedChanges.slice(-24).map((change) => ({\n changeId: compactOutcomeText(change.id, 240, \"unknown-change\"),\n status: change.status,\n summary: compactOutcomeText(change.summary, 500, \"Survey change\"),\n operationCount: change.operations.length,\n })),\n }\n : {}),\n createdAt: new Date().toISOString(),\n });\n\ntype AssistantTextPart = Extract<UIMessage[\"parts\"][number], { type: \"text\" }>;\n\nconst getAssistantTextParts = (message: UIMessage) =>\n message.parts.filter(\n (part): part is AssistantTextPart => part.type === \"text\" && part.text.trim().length > 0,\n );\n\nconst findLastAssistantTextMessageIndex = (\n messages: UIMessage[],\n endExclusive = messages.length,\n) => {\n for (let index = Math.min(messages.length, endExclusive) - 1; index >= 0; index -= 1) {\n const message = messages[index];\n if (message?.role === \"assistant\" && getAssistantTextParts(message).length > 0) return index;\n }\n return -1;\n};\n\nconst findLastUserMessageIndex = (messages: UIMessage[]) => {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n if (messages[index]?.role === \"user\") return index;\n }\n return -1;\n};\n\nconst pruneFailedMessagesForDisplay = (messages: UIMessage[]): UIMessage[] => {\n const lastUserIndex = findLastUserMessageIndex(messages);\n const lastCompletedAssistantIndex = findLastAssistantTextMessageIndex(messages);\n\n if (lastUserIndex > lastCompletedAssistantIndex) return messages.slice(0, lastUserIndex + 1);\n return lastCompletedAssistantIndex >= 0 ? messages.slice(0, lastCompletedAssistantIndex + 1) : [];\n};\n\nconst hasCompletedAssistantResponseAfterLastUser = (messages: UIMessage[]) => {\n const lastUserIndex = findLastUserMessageIndex(messages);\n return lastUserIndex >= 0 && findLastAssistantTextMessageIndex(messages) > lastUserIndex;\n};\n\nconst collectChangeSetsAfterLastUser = (messages: UIMessage[]) => {\n const lastUserIndex = findLastUserMessageIndex(messages);\n return lastUserIndex < 0 ? [] : collectSurveyChangeSets(messages.slice(lastUserIndex + 1));\n};\n\nconst getInitialSessionState = (messages: UIMessage[]): SurveyAssistantSessionState => {\n if (messages.length === 0) return \"idle\";\n const authorization = resolveLatestSurveyTurnAuthorization(messages);\n if (authorization.status === \"failed\") return \"failed\";\n if (authorization.status === \"aborted\") return \"aborted\";\n return \"completed\";\n};\n\nexport interface SurveyAssistantSessionOptions {\n api?: string;\n /** Explicit host decision: apply immediately, present for review, or deny mutations. */\n applyPolicy: SurveyAssistantApplyPolicy;\n controller?: SurveyAssistantController | null;\n /** Optional browser-session diagnostics sink used by the support-bundle UI. */\n diagnosticStore?: SurveyAssistantDiagnosticStore;\n initialMessages?: UIMessage[];\n modelId?: string;\n onApplyReceipts?: (receipts: ApplyReceipt[]) => void;\n /**\n * Production persistence/audit barrier. The turn remains active until this\n * resolves; rejection leaves the settled baseline unchanged.\n */\n onSettleApply?: (input: {\n changeSets: SurveyChangeSet[];\n receipts: ApplyReceipt[];\n turnFinal: SurveyAssistantTurnFinal;\n }) => void | Promise<void>;\n /**\n * Required for `review`. Resolve true to apply the authorized change sets,\n * or false to leave the editor unchanged.\n */\n onReviewChangeSets?: (\n changeSets: SurveyChangeSet[],\n turnFinal: SurveyAssistantTurnFinal,\n ) => boolean | Promise<boolean>;\n /** Reports when a turn owns the editor state, including submission, streaming, and apply. */\n onTurnActiveChange?: (active: boolean) => void;\n resourceId?: string;\n /** Host survey id sent as untrusted request context for server-side authorization. */\n surveyId?: string;\n threadId?: string;\n}\n\nexport const resolveSurveyAssistantReviewDecision = async ({\n changeSets,\n onReviewChangeSets,\n turnFinal,\n}: {\n changeSets: SurveyChangeSet[];\n onReviewChangeSets?: SurveyAssistantSessionOptions[\"onReviewChangeSets\"];\n turnFinal: SurveyAssistantTurnFinal;\n}) => {\n if (!onReviewChangeSets) {\n throw new Error(\"No survey assistant review adapter is available.\");\n }\n return onReviewChangeSets(changeSets, turnFinal);\n};\n\nexport interface SurveyAssistantSubmitMessage {\n text: string;\n files: FileUIPart[];\n /** Optional model used for this turn instead of the session's selected model. */\n modelId?: string;\n /** Turn-local UI context layered over the controller snapshot for this submission. */\n uiContext?: SurveyAssistantLaunchUIContext;\n}\n\nexport interface SurveyAssistantSession {\n applyResultsByChangeId: Record<string, SurveyApplyResult>;\n authorizationError: string | null;\n dismissError(): void;\n error: Error | undefined;\n isStreaming: boolean;\n latestTurnOutcome: SurveyTurnOutcome | null;\n messages: UIMessage[];\n prependMessages(messages: UIMessage[]): void;\n state: SurveyAssistantSessionState;\n status: ChatStatus;\n stop(): void;\n submit(message: SurveyAssistantSubmitMessage): boolean;\n retry(): void;\n}\n\nexport const useSurveyAssistantSession = ({\n api,\n applyPolicy,\n controller,\n diagnosticStore,\n initialMessages = [],\n modelId,\n onApplyReceipts,\n onSettleApply,\n onReviewChangeSets,\n onTurnActiveChange,\n resourceId: controlledResourceId,\n surveyId,\n threadId: controlledThreadId,\n}: SurveyAssistantSessionOptions): SurveyAssistantSession => {\n const [localResourceId] = useState(() => createLocalId(\"survey-assistant-local-user\"));\n const [localThreadId] = useState(() => createLocalId(\"survey-assistant-local-thread\"));\n const resourceId = controlledResourceId ?? localResourceId;\n const threadId = controlledThreadId ?? localThreadId;\n const applyOutcomeScopeKey = `${resourceId}\\u0000${threadId}`;\n const [state, dispatch] = useReducer(\n reduceSurveyAssistantSessionState,\n initialMessages,\n getInitialSessionState,\n );\n const [applyResultsByChangeId, setApplyResultsByChangeId] = useState<\n Record<string, SurveyApplyResult>\n >({});\n const [authorizationError, setAuthorizationError] = useState<string | null>(null);\n const handledTurnIdsRef = useRef<Set<string>>(new Set());\n const localTurnAwaitingApplyRef = useRef(false);\n const localTurnStreamStartedRef = useRef(false);\n const captureSettledVersionRef = useRef(false);\n const lastSubmittedUIContextRef = useRef<SurveyAssistantLaunchUIContext | undefined>(undefined);\n const lastSubmittedModelIdRef = useRef<string | undefined>(undefined);\n const previousApplyOutcomesRef = useRef<Map<string, SurveyAssistantApplyOutcome>>(new Map());\n const capturedChatErrorRef = useRef<Error | undefined>(undefined);\n\n const transport = useMemo(\n () => createSurveyAssistantTransport({ api, resourceId, surveyId, threadId }),\n [api, resourceId, surveyId, threadId],\n );\n const {\n messages,\n setMessages,\n sendMessage,\n status,\n stop: stopChat,\n error,\n clearError,\n regenerate,\n } = useChat({ id: threadId, messages: initialMessages, transport });\n const isStreaming = status === \"submitted\" || status === \"streaming\";\n const messagesRef = useRef(messages);\n messagesRef.current = messages;\n const isTurnActive = isSurveyAssistantTurnActive({ isStreaming, state });\n const notifyTurnActiveChange = useEffectEvent((active: boolean) => {\n onTurnActiveChange?.(active);\n });\n const prependMessages = useCallback(\n (olderMessages: UIMessage[]) => {\n setMessages((current) => {\n const currentIds = new Set(current.map((message) => message.id));\n return [...olderMessages.filter((message) => !currentIds.has(message.id)), ...current];\n });\n },\n [setMessages],\n );\n const turnAuthorization = useMemo(\n () => resolveLatestSurveyTurnAuthorization(messages),\n [messages],\n );\n const latestTurnOutcome = useMemo(\n () => resolveSurveyTurnOutcome({ applyResultsByChangeId, authorization: turnAuthorization }),\n [applyResultsByChangeId, turnAuthorization],\n );\n const hasUsefulLatestAssistantResponse = useMemo(\n () =>\n hasCompletedAssistantResponseAfterLastUser(messages) ||\n collectChangeSetsAfterLastUser(messages).length > 0,\n [messages],\n );\n\n const reportAuthorizationError = useCallback(\n (message: string) => {\n try {\n diagnosticStore?.recordFailure(threadId, messagesRef.current, {\n code: \"request_failed\",\n detail: message,\n retryable: false,\n });\n } catch {\n // Diagnostic capture must never replace the actual assistant error.\n }\n queueMicrotask(() => {\n setAuthorizationError(message);\n dispatch({ type: \"failed\" });\n });\n },\n [diagnosticStore, threadId],\n );\n\n const rememberApplyOutcome = useCallback(\n (outcome: SurveyAssistantApplyOutcome) => {\n previousApplyOutcomesRef.current.set(applyOutcomeScopeKey, outcome);\n try {\n diagnosticStore?.recordApplyOutcome(threadId, outcome);\n } catch {\n // Diagnostics are best-effort and cannot affect editor lifecycle.\n }\n },\n [applyOutcomeScopeKey, diagnosticStore, threadId],\n );\n\n useEffect(() => {\n if (status === \"submitted\") dispatch({ type: \"submit\" });\n if (status === \"streaming\") dispatch({ type: \"stream-started\" });\n }, [status]);\n\n useEffect(() => {\n notifyTurnActiveChange(isTurnActive);\n\n return () => {\n if (isTurnActive) notifyTurnActiveChange(false);\n };\n }, [isTurnActive]);\n\n useEffect(() => {\n if (\n !captureSettledVersionRef.current ||\n isStreaming ||\n (state !== \"completed\" && state !== \"failed\" && state !== \"aborted\" && state !== \"applied\")\n ) {\n return;\n }\n\n captureSettledVersionRef.current = false;\n try {\n const snapshot = controller?.getSnapshot();\n if (snapshot) {\n writeSettledDocumentVersion({ resourceId, snapshot, threadId });\n }\n } catch {\n // A failed host snapshot must not crash failure settlement or advance the baseline.\n }\n }, [controller, isStreaming, resourceId, state, threadId]);\n\n useEffect(() => {\n if (isStreaming) {\n localTurnStreamStartedRef.current = true;\n return;\n }\n if (!localTurnAwaitingApplyRef.current) return;\n\n if (turnAuthorization.status === \"pending\") {\n if (!localTurnStreamStartedRef.current) return;\n const timeoutId = window.setTimeout(() => {\n if (capturedChatErrorRef.current) return;\n localTurnAwaitingApplyRef.current = false;\n localTurnStreamStartedRef.current = false;\n reportAuthorizationError(\"The assistant response ended without a valid turn final.\");\n }, 100);\n return () => window.clearTimeout(timeoutId);\n }\n\n localTurnAwaitingApplyRef.current = false;\n localTurnStreamStartedRef.current = false;\n if (turnAuthorization.status === \"invalid\") {\n reportAuthorizationError(turnAuthorization.reason);\n return;\n }\n\n const { turnFinal } = turnAuthorization;\n try {\n diagnosticStore?.recordTurnFinal(threadId, turnFinal);\n } catch {\n // Diagnostics are best-effort and cannot affect turn settlement.\n }\n if (handledTurnIdsRef.current.has(turnFinal.turnId)) return;\n handledTurnIdsRef.current.add(turnFinal.turnId);\n const preparedChanges = collectChangeSetsAfterLastUser(messages).filter(\n (change) => change.turnId === turnFinal.turnId,\n );\n\n if (turnAuthorization.status === \"failed\") {\n rememberApplyOutcome(\n createApplyOutcome({\n turnId: turnFinal.turnId,\n status: \"not-applied\",\n message:\n \"The previous assistant turn failed before editor authorization. Every request-scoped draft change from that turn was discarded and was not applied.\",\n preparedChanges,\n }),\n );\n dispatch({ type: \"failed\" });\n return;\n }\n if (turnAuthorization.status === \"aborted\") {\n rememberApplyOutcome(\n createApplyOutcome({\n turnId: turnFinal.turnId,\n status: \"not-applied\",\n message:\n \"The previous assistant turn was interrupted before editor authorization. Every request-scoped draft change from that turn was discarded and was not applied.\",\n preparedChanges,\n }),\n );\n dispatch({ type: \"aborted\" });\n return;\n }\n if (turnAuthorization.changeSets.length === 0) {\n if ((turnFinal.blockedChangeSetIds?.length ?? 0) > 0) {\n rememberApplyOutcome(\n createApplyOutcome({\n turnId: turnFinal.turnId,\n status: \"not-applied\",\n message:\n \"The previous assistant turn ended with unresolved rejected changes. No request-scoped draft change from that turn was authorized or applied.\",\n preparedChanges,\n }),\n );\n }\n dispatch({ type: \"completed\" });\n return;\n }\n if (applyPolicy === \"deny\") {\n rememberApplyOutcome(\n createApplyOutcome({\n turnId: turnFinal.turnId,\n status: \"not-applied\",\n message: \"The host apply policy did not authorize editor mutations for this turn.\",\n preparedChanges,\n }),\n );\n dispatch({ type: \"completed\" });\n return;\n }\n dispatch({ type: \"apply-started\" });\n void (async () => {\n if (applyPolicy === \"review\") {\n let approved: boolean;\n try {\n approved = await resolveSurveyAssistantReviewDecision({\n changeSets: turnAuthorization.changeSets,\n onReviewChangeSets,\n turnFinal,\n });\n } catch (error) {\n const message =\n error instanceof Error &&\n error.message === \"No survey assistant review adapter is available.\"\n ? error.message\n : \"The survey assistant review could not be completed.\";\n rememberApplyOutcome(\n createApplyOutcome({\n turnId: turnFinal.turnId,\n status: \"not-applied\",\n message,\n preparedChanges,\n }),\n );\n reportAuthorizationError(message);\n return;\n }\n if (!approved) {\n rememberApplyOutcome(\n createApplyOutcome({\n turnId: turnFinal.turnId,\n status: \"not-applied\",\n message: \"The proposed editor changes were not approved during review.\",\n preparedChanges,\n }),\n );\n dispatch({ type: \"completed\" });\n return;\n }\n }\n\n if (!controller?.applyAssistantChanges) {\n const message = \"No survey editor apply adapter is available.\";\n rememberApplyOutcome(\n createApplyOutcome({\n turnId: turnFinal.turnId,\n status: \"apply-failed\",\n message,\n preparedChanges,\n }),\n );\n reportAuthorizationError(message);\n return;\n }\n const results: SurveyApplyResult[] = [];\n let applyStarted = false;\n const hasCompleteApplyResults = () => {\n const ids = new Set(results.map((result) => result.changeId));\n return (\n results.length === turnAuthorization.changeSets.length &&\n ids.size === results.length &&\n turnAuthorization.changeSets.every((change) => ids.has(change.id))\n );\n };\n const allChangesApplied = () =>\n hasCompleteApplyResults() && results.every((result) => result.status === \"applied\");\n const retainApplyResults = () => {\n const entries = results.map((result) => [result.changeId, result]);\n queueMicrotask(() =>\n setApplyResultsByChangeId((current) => ({ ...current, ...Object.fromEntries(entries) })),\n );\n };\n\n try {\n const beforeSnapshot = controller.getSnapshot();\n if (!beforeSnapshot) throw new Error(\"Editor snapshot unavailable.\");\n applyStarted = true;\n results.push(...controller.applyAssistantChanges(turnAuthorization.changeSets).results);\n retainApplyResults();\n const receipts = createApplyReceipts({\n beforeSnapshot,\n afterSnapshot: controller.getSnapshot(),\n changeSets: turnAuthorization.changeSets,\n results,\n turnFinal,\n });\n try {\n diagnosticStore?.recordApplyReceipts(threadId, receipts);\n } catch {\n // Diagnostics are best-effort and cannot affect host receipt delivery.\n }\n onApplyReceipts?.(receipts);\n if (!hasCompleteApplyResults())\n throw new Error(\"The host returned mismatched apply results.\");\n if (!allChangesApplied()) {\n rememberApplyOutcome(\n createApplyOutcome({\n turnId: turnFinal.turnId,\n status: \"apply-failed\",\n message: \"One or more authorized survey changes could not be applied to the editor.\",\n preparedChanges,\n results,\n }),\n );\n dispatch({ type: \"completed\" });\n return;\n }\n await onSettleApply?.({\n changeSets: turnAuthorization.changeSets,\n receipts,\n turnFinal,\n });\n previousApplyOutcomesRef.current.delete(applyOutcomeScopeKey);\n dispatch({ type: \"applied\" });\n } catch {\n // Preserve returned batch results if receipt delivery or host settlement throws.\n retainApplyResults();\n const applied = allChangesApplied();\n const message = applied\n ? \"The assistant changes were applied locally but could not be settled by the host.\"\n : applyStarted\n ? \"The host could not complete the assistant apply lifecycle. Some changes may already have been applied.\"\n : \"The editor state was unavailable before applying the assistant changes. No changes were applied.\";\n rememberApplyOutcome(\n createApplyOutcome({\n turnId: turnFinal.turnId,\n status: applied ? \"settle-failed\" : \"apply-failed\",\n message,\n preparedChanges,\n results,\n }),\n );\n reportAuthorizationError(message);\n }\n })();\n }, [\n applyPolicy,\n applyOutcomeScopeKey,\n controller,\n diagnosticStore,\n isStreaming,\n onApplyReceipts,\n onReviewChangeSets,\n onSettleApply,\n reportAuthorizationError,\n rememberApplyOutcome,\n messages,\n threadId,\n turnAuthorization,\n ]);\n\n useEffect(() => {\n if (!error) {\n capturedChatErrorRef.current = undefined;\n return;\n }\n if (capturedChatErrorRef.current === error) return;\n capturedChatErrorRef.current = error;\n localTurnAwaitingApplyRef.current = false;\n localTurnStreamStartedRef.current = false;\n dispatch({ type: \"failed\" });\n try {\n diagnosticStore?.recordFailure(\n threadId,\n messagesRef.current,\n parseSurveyAssistantError(error),\n );\n } catch {\n // Diagnostic capture must never replace the actual assistant error.\n }\n if (!hasUsefulLatestAssistantResponse) setMessages(pruneFailedMessagesForDisplay);\n }, [diagnosticStore, error, hasUsefulLatestAssistantResponse, setMessages, threadId]);\n\n const submit = useCallback(\n ({\n files,\n modelId: submittedModelId,\n text: rawText,\n uiContext,\n }: SurveyAssistantSubmitMessage) => {\n const text = rawText.trim();\n if (!text && files.length === 0) return false;\n if (isStreaming || localTurnAwaitingApplyRef.current) return false;\n\n let snapshot;\n try {\n snapshot = applySurveyAssistantLaunchUIContext(\n controller?.getSnapshot() ?? null,\n uiContext,\n );\n } catch {\n reportAuthorizationError(\n \"The editor state was unavailable before sending the assistant request. No request was sent.\",\n );\n return false;\n }\n\n localTurnAwaitingApplyRef.current = true;\n localTurnStreamStartedRef.current = false;\n setAuthorizationError(null);\n if ((authorizationError || error) && !hasUsefulLatestAssistantResponse) {\n setMessages(pruneFailedMessagesForDisplay);\n }\n clearError();\n dispatch({ type: \"submit\" });\n captureSettledVersionRef.current = true;\n lastSubmittedUIContextRef.current = uiContext;\n lastSubmittedModelIdRef.current = submittedModelId ?? modelId;\n\n const requestId = createSurveyAssistantDiagnosticId();\n try {\n diagnosticStore?.beginAttempt({\n files,\n modelId: lastSubmittedModelIdRef.current,\n requestId,\n resourceId,\n submittedSurvey: snapshot,\n threadId,\n });\n } catch {\n // Diagnostic capture is optional; the assistant request must continue.\n }\n void sendMessage(files.length > 0 ? (text ? { text, files } : { files }) : { text }, {\n body: {\n requestId,\n snapshot,\n previousSettledVersion: readSettledDocumentVersion({ resourceId, threadId }),\n previousApplyOutcome: previousApplyOutcomesRef.current.get(applyOutcomeScopeKey),\n ...(lastSubmittedModelIdRef.current ? { modelId: lastSubmittedModelIdRef.current } : {}),\n },\n });\n return true;\n },\n [\n authorizationError,\n applyOutcomeScopeKey,\n clearError,\n controller,\n diagnosticStore,\n error,\n hasUsefulLatestAssistantResponse,\n isStreaming,\n modelId,\n resourceId,\n reportAuthorizationError,\n sendMessage,\n setMessages,\n threadId,\n ],\n );\n\n const stop = useCallback(() => {\n localTurnAwaitingApplyRef.current = false;\n localTurnStreamStartedRef.current = false;\n dispatch({ type: \"aborted\" });\n void stopChat();\n }, [stopChat]);\n\n const retry = useCallback(() => {\n let snapshot;\n try {\n snapshot = applySurveyAssistantLaunchUIContext(\n controller?.getSnapshot() ?? null,\n lastSubmittedUIContextRef.current,\n );\n } catch {\n reportAuthorizationError(\n \"The editor state was unavailable before retrying the assistant request. No request was sent.\",\n );\n return;\n }\n localTurnAwaitingApplyRef.current = true;\n localTurnStreamStartedRef.current = false;\n setAuthorizationError(null);\n clearError();\n dispatch({ type: \"submit\" });\n captureSettledVersionRef.current = true;\n const latestUserMessage = [...messagesRef.current]\n .reverse()\n .find((message) => message.role === \"user\");\n const files = (latestUserMessage?.parts ?? []).filter(\n (part): part is FileUIPart => part.type === \"file\",\n );\n const attachmentReferences = (latestUserMessage?.parts ?? []).flatMap((part) =>\n part.type === SURVEY_ASSISTANT_ATTACHMENT_PART_TYPE &&\n typeof part.data === \"object\" &&\n part.data !== null\n ? [part.data as SurveyAssistantAttachmentReference]\n : [],\n );\n const requestId = createSurveyAssistantDiagnosticId();\n try {\n diagnosticStore?.beginAttempt({\n attachmentReferences,\n files,\n modelId: lastSubmittedModelIdRef.current ?? modelId,\n requestId,\n resourceId,\n submittedSurvey: snapshot,\n threadId,\n });\n diagnosticStore?.recordEvent(threadId, \"retry\");\n } catch {\n // Diagnostic capture is optional; retry must continue.\n }\n void regenerate({\n body: {\n requestId,\n snapshot,\n previousSettledVersion: readSettledDocumentVersion({ resourceId, threadId }),\n previousApplyOutcome: previousApplyOutcomesRef.current.get(applyOutcomeScopeKey),\n ...(lastSubmittedModelIdRef.current ? { modelId: lastSubmittedModelIdRef.current } : {}),\n },\n });\n }, [\n applyOutcomeScopeKey,\n clearError,\n controller,\n diagnosticStore,\n modelId,\n regenerate,\n resourceId,\n reportAuthorizationError,\n threadId,\n ]);\n\n const dismissError = useCallback(() => {\n localTurnAwaitingApplyRef.current = false;\n localTurnStreamStartedRef.current = false;\n if (!hasUsefulLatestAssistantResponse) setMessages(pruneFailedMessagesForDisplay);\n setAuthorizationError(null);\n clearError();\n dispatch({ type: \"reset\", hasTranscript: messages.length > 0 });\n try {\n diagnosticStore?.recordEvent(threadId, \"dismiss\");\n } catch {\n // Diagnostic capture is optional.\n }\n }, [\n clearError,\n diagnosticStore,\n hasUsefulLatestAssistantResponse,\n messages.length,\n setMessages,\n threadId,\n ]);\n\n return {\n applyResultsByChangeId,\n authorizationError,\n dismissError,\n error,\n isStreaming,\n latestTurnOutcome,\n messages,\n prependMessages,\n state,\n status,\n stop,\n submit,\n retry,\n };\n};\n"],"mappings":";;;;;;;;AAoBA,MAAa,+BAA+B,EAC1C,aACA,YAKA,UAAU,cACT,eAAe,UAAU,gBAAgB,UAAU,eAAe,UAAU;AAE/E,MAAa,qCACX,QACA,UACgC;AAChC,SAAQ,MAAM,MAAd;EACE,KAAK,SACH,QAAO;EACT,KAAK,iBACH,QAAO;EACT,KAAK,YACH,QAAO;EACT,KAAK,gBACH,QAAO;EACT,KAAK,UACH,QAAO;EACT,KAAK,SACH,QAAO;EACT,KAAK,UACH,QAAO;EACT,KAAK,QACH,QAAO,MAAM,gBAAgB,cAAc;;;;;ACnCjD,MAAM,YAAY,UAChB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,MAAM;AAEtE,MAAM,uBACJ,UAEC,KAAK,SAAS,kBAAkB,KAAK,KAAK,WAAW,QAAQ,KAC9D,WAAW,QACX,KAAK,UAAU,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