@case-framework/survey-assistant 0.8.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 (114) hide show
  1. package/dist/{authoring-references-DbuOKerg.mjs → authoring-references-CmwLc_C8.mjs} +40 -32
  2. package/dist/authoring-references-CmwLc_C8.mjs.map +1 -0
  3. package/dist/capabilities-D55dq-fO.mjs +582 -0
  4. package/dist/capabilities-D55dq-fO.mjs.map +1 -0
  5. package/dist/capabilities-default.d.mts +4 -12
  6. package/dist/capabilities-default.d.mts.map +1 -1
  7. package/dist/capabilities-default.mjs +2 -2
  8. package/dist/capabilities-z95e1mti.d.mts +117 -0
  9. package/dist/capabilities-z95e1mti.d.mts.map +1 -0
  10. package/dist/{constants-B6HzpEsx.d.mts → constants-HL_klgJl.d.mts} +4 -4
  11. package/dist/{constants-B6HzpEsx.d.mts.map → constants-HL_klgJl.d.mts.map} +1 -1
  12. package/dist/{controller-proxy-DEeFl9IA.mjs → controller-proxy-BQ1YsVxJ.mjs} +4 -3
  13. package/dist/controller-proxy-BQ1YsVxJ.mjs.map +1 -0
  14. package/dist/{controller-proxy-D7uQfm5f.d.mts → controller-proxy-Cmzdr9tV.d.mts} +4 -4
  15. package/dist/{controller-proxy-D7uQfm5f.d.mts.map → controller-proxy-Cmzdr9tV.d.mts.map} +1 -1
  16. package/dist/default-D22AKTqE.mjs +233 -0
  17. package/dist/default-D22AKTqE.mjs.map +1 -0
  18. package/dist/{digest-C39WyAWG.d.mts → digest-FnTTDBq2.d.mts} +2 -2
  19. package/dist/digest-FnTTDBq2.d.mts.map +1 -0
  20. package/dist/digest.d.mts +1 -1
  21. package/dist/engine-D950TfvC.mjs +3098 -0
  22. package/dist/engine-D950TfvC.mjs.map +1 -0
  23. package/dist/engine.d.mts +4 -3
  24. package/dist/engine.mjs +3 -3
  25. package/dist/{index-WB5kfnz0.d.mts → index-B8TLBd1G.d.mts} +8 -6
  26. package/dist/index-B8TLBd1G.d.mts.map +1 -0
  27. package/dist/index-CaX3hZmr.d.mts +23813 -0
  28. package/dist/index-CaX3hZmr.d.mts.map +1 -0
  29. package/dist/{index-r5riv4md.d.mts → index-CeUlGkoU.d.mts} +27 -6
  30. package/dist/index-CeUlGkoU.d.mts.map +1 -0
  31. package/dist/{index-D7wT6P3t.d.mts → index-DYHdvSE8.d.mts} +83 -41
  32. package/dist/index-DYHdvSE8.d.mts.map +1 -0
  33. package/dist/lifecycle-DFzxVxpq.d.mts +54346 -0
  34. package/dist/lifecycle-DFzxVxpq.d.mts.map +1 -0
  35. package/dist/{memory-thread-repository-DAnOGIB3.mjs → memory-thread-repository-DmLadygY.mjs} +15 -9
  36. package/dist/{memory-thread-repository-DAnOGIB3.mjs.map → memory-thread-repository-DmLadygY.mjs.map} +1 -1
  37. package/dist/protocol-BQ7uIDYT.mjs +569 -0
  38. package/dist/protocol-BQ7uIDYT.mjs.map +1 -0
  39. package/dist/protocol.d.mts +4 -4
  40. package/dist/protocol.mjs +3 -2
  41. package/dist/{react-C_GY-Fsc.mjs → react-DybJ5pWw.mjs} +17 -11
  42. package/dist/react-DybJ5pWw.mjs.map +1 -0
  43. package/dist/react-integration.d.mts +1 -1
  44. package/dist/react-integration.mjs +1 -1
  45. package/dist/react.d.mts +2 -2
  46. package/dist/react.mjs +2 -2
  47. package/dist/references/assistant-operations.md +190 -215
  48. package/dist/references/core-rules.md +2 -2
  49. package/dist/references/element-types.md +189 -0
  50. package/dist/references/expressions.md +215 -238
  51. package/dist/references/follow-ups.md +151 -0
  52. package/dist/references/localization.md +26 -12
  53. package/dist/references/response-variables.md +3 -3
  54. package/dist/references/rich-text-content.md +22 -43
  55. package/dist/references/source-material-surveys.md +20 -25
  56. package/dist/references/survey-data-model.md +36 -117
  57. package/dist/{request-context-Dg4jSwN1.mjs → request-context-KVh8VjgH.mjs} +4 -4
  58. package/dist/request-context-KVh8VjgH.mjs.map +1 -0
  59. package/dist/server-agent.d.mts +28 -7
  60. package/dist/server-agent.d.mts.map +1 -1
  61. package/dist/server-agent.mjs +33 -25
  62. package/dist/server-agent.mjs.map +1 -1
  63. package/dist/server-runtime.d.mts +6 -5
  64. package/dist/server-runtime.d.mts.map +1 -1
  65. package/dist/server-runtime.mjs +3 -3
  66. package/dist/server-tasks.d.mts +1 -1
  67. package/dist/server-tasks.mjs +1 -1
  68. package/dist/server-tools.d.mts +1 -1
  69. package/dist/server-tools.mjs +1 -1
  70. package/dist/server.d.mts +7 -6
  71. package/dist/server.d.mts.map +1 -1
  72. package/dist/server.mjs +3 -3
  73. package/dist/{tasks-BZEiwgxA.mjs → tasks-Coh5N027.mjs} +16 -15
  74. package/dist/tasks-Coh5N027.mjs.map +1 -0
  75. package/dist/{tasks-B9h3LPam.d.mts → tasks-wb9M-bak.d.mts} +11 -11
  76. package/dist/{tasks-B9h3LPam.d.mts.map → tasks-wb9M-bak.d.mts.map} +1 -1
  77. package/dist/{thread-handlers-Bef0td9N.d.mts → thread-handlers-C3Iya92v.d.mts} +6 -5
  78. package/dist/thread-handlers-C3Iya92v.d.mts.map +1 -0
  79. package/dist/{tools-CEsv-WoO.mjs → tools-D0KBDolR.mjs} +435 -408
  80. package/dist/tools-D0KBDolR.mjs.map +1 -0
  81. package/dist/turn-survey-draft-B34lggSG.d.mts +185 -0
  82. package/dist/turn-survey-draft-B34lggSG.d.mts.map +1 -0
  83. package/dist/ui.d.mts +3 -3
  84. package/dist/ui.d.mts.map +1 -1
  85. package/dist/ui.mjs +35 -23
  86. package/dist/ui.mjs.map +1 -1
  87. package/package.json +7 -7
  88. package/dist/authoring-references-DbuOKerg.mjs.map +0 -1
  89. package/dist/capabilities-CmeeAjEc.d.mts +0 -192
  90. package/dist/capabilities-CmeeAjEc.d.mts.map +0 -1
  91. package/dist/capabilities-DCMA71PP.mjs +0 -58
  92. package/dist/capabilities-DCMA71PP.mjs.map +0 -1
  93. package/dist/controller-proxy-DEeFl9IA.mjs.map +0 -1
  94. package/dist/default-fhSon2RM.mjs +0 -760
  95. package/dist/default-fhSon2RM.mjs.map +0 -1
  96. package/dist/digest-C39WyAWG.d.mts.map +0 -1
  97. package/dist/engine-nXoCWYpQ.mjs +0 -6888
  98. package/dist/engine-nXoCWYpQ.mjs.map +0 -1
  99. package/dist/index-Ciq7vHIs.d.mts +0 -716
  100. package/dist/index-Ciq7vHIs.d.mts.map +0 -1
  101. package/dist/index-D7wT6P3t.d.mts.map +0 -1
  102. package/dist/index-WB5kfnz0.d.mts.map +0 -1
  103. package/dist/index-r5riv4md.d.mts.map +0 -1
  104. package/dist/lifecycle-Dm8u7QFh.d.mts +0 -545
  105. package/dist/lifecycle-Dm8u7QFh.d.mts.map +0 -1
  106. package/dist/protocol-CF4Bh_Ch.mjs +0 -1255
  107. package/dist/protocol-CF4Bh_Ch.mjs.map +0 -1
  108. package/dist/react-C_GY-Fsc.mjs.map +0 -1
  109. package/dist/references/embedded-forms.md +0 -146
  110. package/dist/references/item-types.md +0 -641
  111. package/dist/request-context-Dg4jSwN1.mjs.map +0 -1
  112. package/dist/tasks-BZEiwgxA.mjs.map +0 -1
  113. package/dist/thread-handlers-Bef0td9N.d.mts.map +0 -1
  114. package/dist/tools-CEsv-WoO.mjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"react-C_GY-Fsc.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 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 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 useLayoutEffect,\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 turnOwnedRef = useRef(false);\n const turnGenerationRef = useRef(0);\n const mountedRef = 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 const submittedDocumentSessionIdRef = useRef<string | null | undefined>(undefined);\n const previousAssistantMessageRef = useRef<UIMessage | undefined>(undefined);\n const controllerRef = useRef(controller);\n const invalidateTurn = useCallback(() => {\n turnGenerationRef.current += 1;\n turnOwnedRef.current = false;\n localTurnAwaitingApplyRef.current = false;\n localTurnStreamStartedRef.current = false;\n captureSettledVersionRef.current = false;\n }, []);\n\n const sessionScope = JSON.stringify([api, resourceId, surveyId, threadId]);\n const previousSessionScopeRef = useRef(sessionScope);\n useLayoutEffect(() => {\n mountedRef.current = true;\n if (previousSessionScopeRef.current !== sessionScope) {\n previousSessionScopeRef.current = sessionScope;\n dispatch({ type: \"reset\", hasTranscript: initialMessages.length > 0 });\n setApplyResultsByChangeId({});\n setAuthorizationError(null);\n handledTurnIdsRef.current.clear();\n previousApplyOutcomesRef.current.clear();\n lastSubmittedUIContextRef.current = undefined;\n lastSubmittedModelIdRef.current = undefined;\n submittedDocumentSessionIdRef.current = undefined;\n previousAssistantMessageRef.current = undefined;\n capturedChatErrorRef.current = undefined;\n }\n return () => {\n mountedRef.current = false;\n invalidateTurn();\n };\n // A different request scope cannot inherit pending review work.\n // Initial messages seed the scope; ordinary transcript updates do not replace it.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [sessionScope, invalidateTurn]);\n\n useLayoutEffect(() => {\n controllerRef.current = controller;\n if (!turnOwnedRef.current) return;\n try {\n if (controller?.getSnapshot()?.version.sessionId === submittedDocumentSessionIdRef.current)\n return;\n } catch {\n // A replacement controller that cannot identify its document cannot own this turn.\n }\n invalidateTurn();\n dispatch({ type: \"aborted\" });\n }, [controller, invalidateTurn]);\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 useLayoutEffect(() => {\n messagesRef.current = messages;\n }, [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 const generation = turnGenerationRef.current;\n queueMicrotask(() => {\n if (!mountedRef.current || turnGenerationRef.current !== generation) return;\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 isStreaming ||\n (state !== \"completed\" && state !== \"failed\" && state !== \"aborted\" && state !== \"applied\")\n ) {\n return;\n }\n\n turnOwnedRef.current = false;\n if (!captureSettledVersionRef.current) return;\n captureSettledVersionRef.current = false;\n try {\n const snapshot = controller?.getSnapshot();\n if (snapshot && snapshot.version.sessionId === submittedDocumentSessionIdRef.current) {\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 // Starting a new request still renders the previous transcript until the SDK\n // delivers the next response. It must not consume the new turn's ownership.\n if (\n !localTurnStreamStartedRef.current &&\n [...messages].reverse().find((message) => message.role === \"assistant\") ===\n previousAssistantMessageRef.current\n )\n return;\n if (\n \"turnFinal\" in turnAuthorization &&\n handledTurnIdsRef.current.has(turnAuthorization.turnFinal.turnId)\n )\n 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 // Once local mutation can begin, only a successful host barrier may advance\n // the baseline. Review/apply/settlement failures retain the preceding version.\n captureSettledVersionRef.current = false;\n const generation = turnGenerationRef.current;\n const isCurrentTurn = () => mountedRef.current && turnGenerationRef.current === generation;\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 if (!isCurrentTurn()) return;\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 (!isCurrentTurn()) return;\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 (!isCurrentTurn()) return;\n const currentController = controllerRef.current;\n if (!currentController?.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 if (!isCurrentTurn()) return;\n setApplyResultsByChangeId((current) => ({ ...current, ...Object.fromEntries(entries) }));\n });\n };\n\n try {\n const beforeSnapshot = currentController.getSnapshot();\n if (!isCurrentTurn()) return;\n if (!beforeSnapshot) throw new Error(\"Editor snapshot unavailable.\");\n if (beforeSnapshot.version.sessionId !== submittedDocumentSessionIdRef.current) {\n invalidateTurn();\n dispatch({ type: \"aborted\" });\n return;\n }\n if (!isCurrentTurn()) return;\n applyStarted = true;\n results.push(\n ...currentController.applyAssistantChanges(turnAuthorization.changeSets).results,\n );\n if (!isCurrentTurn()) return;\n retainApplyResults();\n const receipts = createApplyReceipts({\n beforeSnapshot,\n afterSnapshot: currentController.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 if (!isCurrentTurn()) return;\n onApplyReceipts?.(receipts);\n if (!isCurrentTurn()) return;\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 if (!isCurrentTurn()) return;\n const settledSnapshot = controllerRef.current?.getSnapshot();\n if (!isCurrentTurn()) return;\n if (!settledSnapshot) throw new Error(\"Editor snapshot unavailable after settlement.\");\n if (settledSnapshot.version.sessionId !== submittedDocumentSessionIdRef.current) {\n invalidateTurn();\n dispatch({ type: \"aborted\" });\n return;\n }\n writeSettledDocumentVersion({ resourceId, snapshot: settledSnapshot, threadId });\n previousApplyOutcomesRef.current.delete(applyOutcomeScopeKey);\n dispatch({ type: \"applied\" });\n } catch {\n if (!isCurrentTurn()) return;\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 invalidateTurn,\n onApplyReceipts,\n onReviewChangeSets,\n onSettleApply,\n reportAuthorizationError,\n rememberApplyOutcome,\n resourceId,\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 (!mountedRef.current || isStreaming || turnOwnedRef.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 turnOwnedRef.current = true;\n submittedDocumentSessionIdRef.current = snapshot?.version.sessionId;\n previousAssistantMessageRef.current = [...messagesRef.current]\n .reverse()\n .find((message) => message.role === \"assistant\");\n turnGenerationRef.current += 1;\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 invalidateTurn();\n dispatch({ type: \"aborted\" });\n void stopChat();\n }, [invalidateTurn, stopChat]);\n\n const retry = useCallback(() => {\n if (!mountedRef.current || isStreaming || turnOwnedRef.current) return;\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 turnOwnedRef.current = true;\n submittedDocumentSessionIdRef.current = snapshot?.version.sessionId;\n previousAssistantMessageRef.current = [...messagesRef.current]\n .reverse()\n .find((message) => message.role === \"assistant\");\n turnGenerationRef.current += 1;\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 isStreaming,\n regenerate,\n resourceId,\n reportAuthorizationError,\n threadId,\n ]);\n\n const dismissError = useCallback(() => {\n if (turnOwnedRef.current || isStreaming) return;\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 isStreaming,\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;CAChC,QAAQ,MAAM,MAAd;EACE,KAAK,UACH,OAAO;EACT,KAAK,kBACH,OAAO;EACT,KAAK,aACH,OAAO;EACT,KAAK,iBACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,KAAK,UACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,KAAK,SACH,OAAO,MAAM,gBAAgB,cAAc;CAC/C;AACF;;;ACrCA,MAAM,YAAY,UAChB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAErE,MAAM,uBACJ,UAEC,KAAK,SAAS,kBAAkB,KAAK,KAAK,WAAW,OAAO,MAC7D,WAAW,QACX,KAAK,UAAU,sBACf,YAAY;AAEd,MAAa,mCAAmC,WAAoB;CAClE,IAAI,SAAS,MAAM,KAAK,YAAY,UAAU,OAAO,WAAW,KAAA,GAC9D,OAAO,OAAO;CAEhB,OAAO;AACT;AAEA,MAAa,wBAAwB,WAA4C;CAC/E,MAAM,SAAS,sBAAsB,UAAU,gCAAgC,MAAM,CAAC;CACtF,OAAO,OAAO,UAAU,OAAO,OAAO;AACxC;AAEA,MAAa,2BAA2B,aAA6C;CACnF,MAAM,UAA6B,CAAC;CACpC,KAAK,MAAM,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YAAY,kCAAkC;EACpD,IAAI;GACF,iBAAiB,aAAa;IAC5B;IACA;IACA,SAAS,wBAAwB,WAAW;IAC5C;IACA;IACA,iBAAiB;IACjB;GACF,CAAC;GACD,iBAAiB,YAAY,UAAU,OAAO;EAChD,QAAQ,CAER;EACA,WAAgB,EACd,MAAM;GACJ;GACA;GACA,wBAAwB,2BAA2B;IAAE;IAAY;GAAS,CAAC;GAC3E,sBAAsB,yBAAyB,QAAQ,IAAI,oBAAoB;GAC/E,GAAI,wBAAwB,UAAU,EAAE,SAAS,wBAAwB,QAAQ,IAAI,CAAC;EACxF,EACF,CAAC;CACH,GAAG;EACD;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;CAyBD,OAAO;EACL;EACA;EACA,cA1BmB,kBAAkB;GACrC,IAAI,aAAa,WAAW,aAAa;GACzC,0BAA0B,UAAU;GACpC,0BAA0B,UAAU;GACpC,IAAI,CAAC,kCAAkC,YAAY,6BAA6B;GAChF,sBAAsB,IAAI;GAC1B,WAAW;GACX,SAAS;IAAE,MAAM;IAAS,eAAe,SAAS,SAAS;GAAE,CAAC;GAC9D,IAAI;IACF,iBAAiB,YAAY,UAAU,SAAS;GAClD,QAAQ,CAER;EACF,GAAG;GACD;GACA;GACA;GACA,SAAS;GACT;GACA;GACA;EACF,CAKa;EACX;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
@@ -1,146 +0,0 @@
1
- # Choice Option Embedded Forms
2
-
3
- Use this reference when a choice option needs an inline input such as “Other, please specify”,
4
- “Yes, explain”, or an option-specific text, number, date, or select field.
5
-
6
- ## Tool And Transaction Choice
7
-
8
- - There is no `allowOther` flag. The option config field is `embeddedForm`.
9
- - For a newly created choice item, put the option and its `embeddedForm` directly in the same
10
- `create-item` operation, with every required translation in `create-item.translations`.
11
- - For an existing option, inspect its exact item and option ids, then use `set-embedded-form`.
12
- Put the complete form structure and all visible content in that operation's `translations`.
13
- The `translations` property belongs inside the `set-embedded-form` operation object, never beside
14
- the `survey_change` `operations` array.
15
- - To add the option and form together, use one `survey_change` proposal containing
16
- `add-choice-option` with an explicit stable id, immediately followed by `set-embedded-form`
17
- targeting that id.
18
- - Use `survey-json-patch` only for editable behavior that these typed operations cannot represent.
19
-
20
- ## Exact Config Shape
21
-
22
- The config key is singular `embeddedForm`, but translation content-key prefixes are plural
23
- `embeddedForms.<optionId>`. Do not interchange them.
24
-
25
- `embeddedForm` is a flat object containing `id`, `authoringMode`, and `fieldGroups`. Fields belong inside each field
26
- group; there is no `itemType`, `config`, or top-level `fields` wrapper.
27
-
28
- Default to `authoringMode: "simple"` for an inline follow-up with one supported field in one
29
- ordinary single-column group. Use `authoringMode: "custom"` only for a blank, multi-field,
30
- multi-group, conditional, or layout-customized follow-up. Any structural change is a one-way
31
- transition to custom; retain existing fields and translations.
32
-
33
- `fieldGroups[].layout` values are responsive column counts, not field spans. Use `1` at every
34
- breakpoint for one full-width field. Supported counts are `1` through `4`.
35
-
36
- ```json
37
- {
38
- "id": "other",
39
- "embeddedForm": {
40
- "id": "other",
41
- "authoringMode": "simple",
42
- "fieldGroups": [
43
- {
44
- "id": "other_details",
45
- "layout": {
46
- "base": 1,
47
- "xs": 1,
48
- "sm": 1,
49
- "md": 1,
50
- "xl": 1
51
- },
52
- "fields": [
53
- {
54
- "id": "other_text",
55
- "type": "input",
56
- "required": true,
57
- "controller": {
58
- "type": "input",
59
- "inputMode": "text"
60
- },
61
- "validations": [],
62
- "variableName": "other_text"
63
- }
64
- ]
65
- }
66
- ]
67
- },
68
- "code": "other"
69
- }
70
- ```
71
-
72
- For comparison, use `custom` when the follow-up really needs multiple controls. Keep its fields
73
- and their translations together; do not use this shape for a single text field just because it is
74
- inside a choice option.
75
-
76
- ```json
77
- {
78
- "id": "contact_details",
79
- "authoringMode": "custom",
80
- "fieldGroups": [
81
- {
82
- "id": "details",
83
- "layout": {
84
- "base": 1,
85
- "xs": 1,
86
- "sm": 1,
87
- "md": 1,
88
- "xl": 1
89
- },
90
- "fields": [
91
- {
92
- "id": "contact_name",
93
- "type": "input",
94
- "controller": {
95
- "type": "input",
96
- "inputMode": "text"
97
- },
98
- "variableName": "contact_name"
99
- },
100
- {
101
- "id": "contact_note",
102
- "type": "textarea",
103
- "controller": {
104
- "type": "textarea",
105
- "rows": 3
106
- },
107
- "variableName": "contact_note"
108
- }
109
- ]
110
- }
111
- ]
112
- }
113
- ```
114
-
115
- Use an explicit, stable option id. The config option id, translation prefix, and embedded response
116
- reference must agree exactly. When editing an existing option, copy its current `id` exactly,
117
- including case. The `embeddedForms.<optionId>` translation segment always comes from the containing
118
- choice option's `id`; it does not come from the option `code` or the nested `embeddedForm.id`.
119
-
120
- ## Required Content
121
-
122
- Every embedded field requires a visible label translation in the same atomic proposal:
123
-
124
- - option label: `options.other.label`;
125
- - field label: `embeddedForms.other.fields.other_text.label`;
126
- - optional placeholder: `embeddedForms.other.fields.other_text.placeholder`;
127
- - validation message, when configured:
128
- `embeddedForms.other.fields.other_text.validations.<validationId>.message`;
129
- - select option label, when applicable:
130
- `embeddedForms.other.fields.other_text.options.<selectOptionId>.label`.
131
-
132
- Do not duplicate completion wording in both the option and field labels. For “Other, please
133
- specify”, use option label “Other” and field label “Please specify”.
134
-
135
- ## Existing-Item Typed Operation Checklist
136
-
137
- 1. Inspect the existing choice item and copy the exact item and option ids.
138
- 2. Call `set-embedded-form` with the complete flat form structure and explicit `authoringMode`.
139
- 3. Use canonical field types such as `input`, with a matching controller; there is no `text` type.
140
- 4. Put relative content keys such as `fields.other_text.label` in the same operation's
141
- `translations`; the engine adds `embeddedForms.<optionId>.` automatically.
142
- 5. Use one column at every breakpoint when a lone field should fill the form width.
143
- 6. Before adding/reordering groups or fields on a simple follow-up, let the typed mutation promote
144
- it to custom; do not construct multi-field data with `authoringMode: "simple"`.
145
-
146
- Embedded response slots are the persistent field IDs, exactly as declared in the shared slot registry. They are not reconstructed from option IDs or variable names. Every field has a survey-wide unique `variableName`. Inspect declarations before authoring expressions; translations keep the `embeddedForms.<optionId>.fields.<fieldId>` prefix.