@8wave/ai-elements 0.123.0-beta.15 → 0.123.0-beta.16

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 (149) hide show
  1. package/dist/_chunks/{PkChatbotFilePreview-Dgikkf9Y.js → PkChatbotFilePreview-Dk748hZ0.js} +2 -2
  2. package/dist/_chunks/{PkChatbotFilePreview-Dgikkf9Y.js.map → PkChatbotFilePreview-Dk748hZ0.js.map} +1 -1
  3. package/dist/_chunks/{PkFilePreview-CG9peejh.js → PkFilePreview-Bcdfci6i.js} +2 -2
  4. package/dist/_chunks/{PkFilePreview-CG9peejh.js.map → PkFilePreview-Bcdfci6i.js.map} +1 -1
  5. package/dist/_chunks/{PkFilePreviewDialog-jzUvrw9R.js → PkFilePreviewDialog-nibxELSF.js} +2 -2
  6. package/dist/_chunks/{PkFilePreviewDialog-jzUvrw9R.js.map → PkFilePreviewDialog-nibxELSF.js.map} +1 -1
  7. package/dist/_chunks/{PkStreamingMarkdown-DI1AjsVC.js → PkStreamingMarkdown-C6cFkf82.js} +4 -4
  8. package/dist/_chunks/{PkStreamingMarkdown-DI1AjsVC.js.map → PkStreamingMarkdown-C6cFkf82.js.map} +1 -1
  9. package/dist/_chunks/{PkToolChatFile-BKX_7nJp.js → PkToolChatFile-5t_1vL81.js} +3 -3
  10. package/dist/_chunks/{PkToolChatFile-BKX_7nJp.js.map → PkToolChatFile-5t_1vL81.js.map} +1 -1
  11. package/dist/_chunks/{PkToolRequestOAuthConnection-BYXzi6XB.js → PkToolRequestOAuthConnection-ST3-OlS4.js} +2 -2
  12. package/dist/_chunks/{PkToolRequestOAuthConnection-BYXzi6XB.js.map → PkToolRequestOAuthConnection-ST3-OlS4.js.map} +1 -1
  13. package/dist/_chunks/{PkToolShareDocument-D2uV6p8t.js → PkToolShareDocument-1zhZDa0R.js} +2 -2
  14. package/dist/_chunks/{PkToolShareDocument-D2uV6p8t.js.map → PkToolShareDocument-1zhZDa0R.js.map} +1 -1
  15. package/dist/_chunks/{PkToolShowArtifact-CyKWxAff.js → PkToolShowArtifact-DV78g_yD.js} +2 -2
  16. package/dist/_chunks/{PkToolShowArtifact-CyKWxAff.js.map → PkToolShowArtifact-DV78g_yD.js.map} +1 -1
  17. package/dist/_chunks/{PkToolShowCalendarEvent-BF2aXrwP.js → PkToolShowCalendarEvent-Dvp1SwBY.js} +2 -2
  18. package/dist/_chunks/{PkToolShowCalendarEvent-BF2aXrwP.js.map → PkToolShowCalendarEvent-Dvp1SwBY.js.map} +1 -1
  19. package/dist/_chunks/{PkToolShowContactForm-C-U785n6.js → PkToolShowContactForm-Bnjy0g50.js} +4 -4
  20. package/dist/_chunks/{PkToolShowContactForm-C-U785n6.js.map → PkToolShowContactForm-Bnjy0g50.js.map} +1 -1
  21. package/dist/_chunks/{PkToolShowDiagram-Bs5Ri9df.js → PkToolShowDiagram-C1Q5jhbk.js} +3 -3
  22. package/dist/_chunks/{PkToolShowDiagram-Bs5Ri9df.js.map → PkToolShowDiagram-C1Q5jhbk.js.map} +1 -1
  23. package/dist/_chunks/{PkToolShowForm-CN5jvQqQ.js → PkToolShowForm-CT5_ln9b.js} +3 -3
  24. package/dist/_chunks/{PkToolShowForm-CN5jvQqQ.js.map → PkToolShowForm-CT5_ln9b.js.map} +1 -1
  25. package/dist/_chunks/{PkToolShowImageGallery-BtgWr1lk.js → PkToolShowImageGallery-BMP-xuYr.js} +4 -4
  26. package/dist/_chunks/{PkToolShowImageGallery-BtgWr1lk.js.map → PkToolShowImageGallery-BMP-xuYr.js.map} +1 -1
  27. package/dist/_chunks/{PkToolShowLocation-COmQJbXp.js → PkToolShowLocation-Drq1nnwN.js} +2 -2
  28. package/dist/_chunks/{PkToolShowLocation-COmQJbXp.js.map → PkToolShowLocation-Drq1nnwN.js.map} +1 -1
  29. package/dist/_chunks/{PkToolShowProductList-CRy6jNPa.js → PkToolShowProductList-AkLG4dBV.js} +2 -2
  30. package/dist/_chunks/{PkToolShowProductList-CRy6jNPa.js.map → PkToolShowProductList-AkLG4dBV.js.map} +1 -1
  31. package/dist/_chunks/{PkToolShowSources-CQweChKW.js → PkToolShowSources-DhZ5I_J-.js} +3 -3
  32. package/dist/_chunks/{PkToolShowSources-CQweChKW.js.map → PkToolShowSources-DhZ5I_J-.js.map} +1 -1
  33. package/dist/_chunks/{PkToolShowVideo-C8dP8I-g.js → PkToolShowVideo-C5jqPYXw.js} +3 -3
  34. package/dist/_chunks/{PkToolShowVideo-C8dP8I-g.js.map → PkToolShowVideo-C5jqPYXw.js.map} +1 -1
  35. package/dist/_chunks/{PkToolShowWeather-sx72yMH6.js → PkToolShowWeather-7_f5k1pX.js} +2 -2
  36. package/dist/_chunks/{PkToolShowWeather-sx72yMH6.js.map → PkToolShowWeather-7_f5k1pX.js.map} +1 -1
  37. package/dist/_chunks/{PkToolShowWebPages-fXkqV27c.js → PkToolShowWebPages-BqL9PjpM.js} +3 -3
  38. package/dist/_chunks/{PkToolShowWebPages-fXkqV27c.js.map → PkToolShowWebPages-BqL9PjpM.js.map} +1 -1
  39. package/dist/_chunks/{browser-CwAulEhA.js → browser-DnbodHv5.js} +32 -18
  40. package/dist/_chunks/browser-DnbodHv5.js.map +1 -0
  41. package/dist/_chunks/{chatImagePolicy-B183jp31.js → chatImagePolicy-ZiVuD6nX.js} +2 -2
  42. package/dist/_chunks/{chatImagePolicy-B183jp31.js.map → chatImagePolicy-ZiVuD6nX.js.map} +1 -1
  43. package/dist/_chunks/{index.es-DYy-Q9hZ.js → index.es-DRbDRAW5.js} +2 -2
  44. package/dist/_chunks/{index.es-DYy-Q9hZ.js.map → index.es-DRbDRAW5.js.map} +1 -1
  45. package/dist/_chunks/src-JJyCGvqH.js +183 -0
  46. package/dist/_chunks/src-JJyCGvqH.js.map +1 -0
  47. package/dist/_chunks/{useLightbox-B575Qxeu.js → useLightbox-BigL4WLe.js} +2 -2
  48. package/dist/_chunks/{useLightbox-B575Qxeu.js.map → useLightbox-BigL4WLe.js.map} +1 -1
  49. package/dist/_chunks/{utils-COV6n6VV.js → utils-B5VcWm3g.js} +2 -2
  50. package/dist/_chunks/{utils-COV6n6VV.js.map → utils-B5VcWm3g.js.map} +1 -1
  51. package/dist/ai-elements.es.js +23 -23
  52. package/dist-vue/PkChatbot.js +1 -1
  53. package/dist-vue/PkChatbotAudioTranscript.js +1 -1
  54. package/dist-vue/PkChatbotEmptyState.js +1 -1
  55. package/dist-vue/PkChatbotFilePreview.js +1 -1
  56. package/dist-vue/PkChatbotInput.js +1 -1
  57. package/dist-vue/PkChatbotMessages.js +1 -1
  58. package/dist-vue/PkChatbotStepPayload.js +1 -1
  59. package/dist-vue/PkChatbotStepToolDetail.js +1 -1
  60. package/dist-vue/PkChatbotSteps.js +1 -1
  61. package/dist-vue/PkChatbotViewChat.js +1 -1
  62. package/dist-vue/PkChatbotViewConversations.js +1 -1
  63. package/dist-vue/PkChatbotViewFiles.js +1 -1
  64. package/dist-vue/PkChatbotViewProfile.js +1 -1
  65. package/dist-vue/_chunks/{PkChatbot-DGut25cv.js → PkChatbot-tq-fJUij.js} +8 -8
  66. package/dist-vue/_chunks/{PkChatbot-DGut25cv.js.map → PkChatbot-tq-fJUij.js.map} +1 -1
  67. package/dist-vue/_chunks/{PkChatbotAudioTranscript-DiZ7BEEH.js → PkChatbotAudioTranscript-SSTh074Z.js} +2 -2
  68. package/dist-vue/_chunks/{PkChatbotAudioTranscript-DiZ7BEEH.js.map → PkChatbotAudioTranscript-SSTh074Z.js.map} +1 -1
  69. package/dist-vue/_chunks/{PkChatbotEmptyState-DT9Pxyjt.js → PkChatbotEmptyState-Dp0_UPJm.js} +2 -2
  70. package/dist-vue/_chunks/{PkChatbotEmptyState-DT9Pxyjt.js.map → PkChatbotEmptyState-Dp0_UPJm.js.map} +1 -1
  71. package/dist-vue/_chunks/{PkChatbotFilePreview-BiurawUn.js → PkChatbotFilePreview-KxVpL0UT.js} +2 -2
  72. package/dist-vue/_chunks/{PkChatbotFilePreview-BiurawUn.js.map → PkChatbotFilePreview-KxVpL0UT.js.map} +1 -1
  73. package/dist-vue/_chunks/{PkChatbotInput-liQNntaY.js → PkChatbotInput-B_kPnNNB.js} +3 -3
  74. package/dist-vue/_chunks/{PkChatbotInput-liQNntaY.js.map → PkChatbotInput-B_kPnNNB.js.map} +1 -1
  75. package/dist-vue/_chunks/{PkChatbotMessages-CDhi_NvV.js → PkChatbotMessages-BTZOic9V.js} +22 -22
  76. package/dist-vue/_chunks/{PkChatbotMessages-CDhi_NvV.js.map → PkChatbotMessages-BTZOic9V.js.map} +1 -1
  77. package/dist-vue/_chunks/{PkChatbotStepPayload-XMAC8eoc.js → PkChatbotStepPayload-CoGCHBhJ.js} +2 -2
  78. package/dist-vue/_chunks/{PkChatbotStepPayload-XMAC8eoc.js.map → PkChatbotStepPayload-CoGCHBhJ.js.map} +1 -1
  79. package/dist-vue/_chunks/{PkChatbotStepToolDetail-CPWnpmuB.js → PkChatbotStepToolDetail-BJtIZBF0.js} +3 -3
  80. package/dist-vue/_chunks/{PkChatbotStepToolDetail-CPWnpmuB.js.map → PkChatbotStepToolDetail-BJtIZBF0.js.map} +1 -1
  81. package/dist-vue/_chunks/{PkChatbotSteps-CyT4Ck3C.js → PkChatbotSteps-CEJNclG4.js} +5 -5
  82. package/dist-vue/_chunks/{PkChatbotSteps-CyT4Ck3C.js.map → PkChatbotSteps-CEJNclG4.js.map} +1 -1
  83. package/dist-vue/_chunks/{PkChatbotViewChat-8Ss2bt2I.js → PkChatbotViewChat-CnEOSH32.js} +8 -8
  84. package/dist-vue/_chunks/{PkChatbotViewChat-8Ss2bt2I.js.map → PkChatbotViewChat-CnEOSH32.js.map} +1 -1
  85. package/dist-vue/_chunks/{PkChatbotViewConversations-ImCdmkUi.js → PkChatbotViewConversations-D7j5P1RO.js} +4 -4
  86. package/dist-vue/_chunks/{PkChatbotViewConversations-ImCdmkUi.js.map → PkChatbotViewConversations-D7j5P1RO.js.map} +1 -1
  87. package/dist-vue/_chunks/{PkChatbotViewFiles-Ccti1JAS.js → PkChatbotViewFiles-B1mncBOo.js} +2 -2
  88. package/dist-vue/_chunks/{PkChatbotViewFiles-Ccti1JAS.js.map → PkChatbotViewFiles-B1mncBOo.js.map} +1 -1
  89. package/dist-vue/_chunks/{PkChatbotViewProfile-ChEItAHZ.js → PkChatbotViewProfile--TWIrhYk.js} +2 -2
  90. package/dist-vue/_chunks/{PkChatbotViewProfile-ChEItAHZ.js.map → PkChatbotViewProfile--TWIrhYk.js.map} +1 -1
  91. package/dist-vue/_chunks/{PkFilePreview-CfzGAziV.js → PkFilePreview-BKwnNsyV.js} +2 -2
  92. package/dist-vue/_chunks/{PkFilePreview-CfzGAziV.js.map → PkFilePreview-BKwnNsyV.js.map} +1 -1
  93. package/dist-vue/_chunks/{PkFilePreviewDialog-DXIGcmYa.js → PkFilePreviewDialog-Cic7gmVR.js} +2 -2
  94. package/dist-vue/_chunks/{PkFilePreviewDialog-DXIGcmYa.js.map → PkFilePreviewDialog-Cic7gmVR.js.map} +1 -1
  95. package/dist-vue/_chunks/{PkStreamingMarkdown-BTcd7ku7.js → PkStreamingMarkdown-CYlCIfA0.js} +3 -3
  96. package/dist-vue/_chunks/{PkStreamingMarkdown-BTcd7ku7.js.map → PkStreamingMarkdown-CYlCIfA0.js.map} +1 -1
  97. package/dist-vue/_chunks/{PkSvgViewer-CvKzI689.js → PkSvgViewer-DBYr0CUi.js} +2 -2
  98. package/dist-vue/_chunks/{PkSvgViewer-CvKzI689.js.map → PkSvgViewer-DBYr0CUi.js.map} +1 -1
  99. package/dist-vue/_chunks/{PkToolChatFile-DHZjc9cf.js → PkToolChatFile-B_PeJef8.js} +3 -3
  100. package/dist-vue/_chunks/{PkToolChatFile-DHZjc9cf.js.map → PkToolChatFile-B_PeJef8.js.map} +1 -1
  101. package/dist-vue/_chunks/{PkToolRequestOAuthConnection-Dy0GXNwC.js → PkToolRequestOAuthConnection-C9_w8V0T.js} +2 -2
  102. package/dist-vue/_chunks/{PkToolRequestOAuthConnection-Dy0GXNwC.js.map → PkToolRequestOAuthConnection-C9_w8V0T.js.map} +1 -1
  103. package/dist-vue/_chunks/{PkToolShareDocument-DHrzH95L.js → PkToolShareDocument-CsS5OTDj.js} +2 -2
  104. package/dist-vue/_chunks/{PkToolShareDocument-DHrzH95L.js.map → PkToolShareDocument-CsS5OTDj.js.map} +1 -1
  105. package/dist-vue/_chunks/{PkToolShowArtifact-BDfqYsCD.js → PkToolShowArtifact-Bh-jIo0V.js} +2 -2
  106. package/dist-vue/_chunks/{PkToolShowArtifact-BDfqYsCD.js.map → PkToolShowArtifact-Bh-jIo0V.js.map} +1 -1
  107. package/dist-vue/_chunks/{PkToolShowCalendarEvent-75TaGeMf.js → PkToolShowCalendarEvent-BsAOYLjp.js} +2 -2
  108. package/dist-vue/_chunks/{PkToolShowCalendarEvent-75TaGeMf.js.map → PkToolShowCalendarEvent-BsAOYLjp.js.map} +1 -1
  109. package/dist-vue/_chunks/{PkToolShowContactForm-4f3q-cfC.js → PkToolShowContactForm-BjfRuNuj.js} +4 -4
  110. package/dist-vue/_chunks/{PkToolShowContactForm-4f3q-cfC.js.map → PkToolShowContactForm-BjfRuNuj.js.map} +1 -1
  111. package/dist-vue/_chunks/{PkToolShowDiagram-CwowbfOT.js → PkToolShowDiagram-_NnrFDGT.js} +4 -4
  112. package/dist-vue/_chunks/{PkToolShowDiagram-CwowbfOT.js.map → PkToolShowDiagram-_NnrFDGT.js.map} +1 -1
  113. package/dist-vue/_chunks/{PkToolShowForm-xFFBo17s.js → PkToolShowForm-AqEY4_do.js} +3 -3
  114. package/dist-vue/_chunks/{PkToolShowForm-xFFBo17s.js.map → PkToolShowForm-AqEY4_do.js.map} +1 -1
  115. package/dist-vue/_chunks/{PkToolShowImageGallery-_hd3FyqC.js → PkToolShowImageGallery-DM5AJNZ3.js} +4 -4
  116. package/dist-vue/_chunks/{PkToolShowImageGallery-_hd3FyqC.js.map → PkToolShowImageGallery-DM5AJNZ3.js.map} +1 -1
  117. package/dist-vue/_chunks/{PkToolShowLocation-C7hBRwq8.js → PkToolShowLocation-DAQEuCuQ.js} +2 -2
  118. package/dist-vue/_chunks/{PkToolShowLocation-C7hBRwq8.js.map → PkToolShowLocation-DAQEuCuQ.js.map} +1 -1
  119. package/dist-vue/_chunks/{PkToolShowProductList-BPSYoZVU.js → PkToolShowProductList-CAV8be9a.js} +2 -2
  120. package/dist-vue/_chunks/{PkToolShowProductList-BPSYoZVU.js.map → PkToolShowProductList-CAV8be9a.js.map} +1 -1
  121. package/dist-vue/_chunks/{PkToolShowSources-CzFNTuWy.js → PkToolShowSources-CriswKr_.js} +3 -3
  122. package/dist-vue/_chunks/{PkToolShowSources-CzFNTuWy.js.map → PkToolShowSources-CriswKr_.js.map} +1 -1
  123. package/dist-vue/_chunks/{PkToolShowVideo-Dr7UtU-3.js → PkToolShowVideo-FSWM5MOl.js} +3 -3
  124. package/dist-vue/_chunks/{PkToolShowVideo-Dr7UtU-3.js.map → PkToolShowVideo-FSWM5MOl.js.map} +1 -1
  125. package/dist-vue/_chunks/{PkToolShowWeather-Z6vCrhh9.js → PkToolShowWeather-BC-Rx-sI.js} +2 -2
  126. package/dist-vue/_chunks/{PkToolShowWeather-Z6vCrhh9.js.map → PkToolShowWeather-BC-Rx-sI.js.map} +1 -1
  127. package/dist-vue/_chunks/{PkToolShowWebPages-CAeOJ5xx.js → PkToolShowWebPages-CPhm2ba3.js} +3 -3
  128. package/dist-vue/_chunks/{PkToolShowWebPages-CAeOJ5xx.js.map → PkToolShowWebPages-CPhm2ba3.js.map} +1 -1
  129. package/dist-vue/_chunks/{createChatbotApiClient-CuqGJGHD.js → createChatbotApiClient-CFKeOgEA.js} +2 -2
  130. package/dist-vue/_chunks/{createChatbotApiClient-CuqGJGHD.js.map → createChatbotApiClient-CFKeOgEA.js.map} +1 -1
  131. package/dist-vue/_chunks/{mcpOAuthReport-BdegDfcz.js → mcpOAuthReport-D-MtFYwN.js} +2 -2
  132. package/dist-vue/_chunks/{mcpOAuthReport-BdegDfcz.js.map → mcpOAuthReport-D-MtFYwN.js.map} +1 -1
  133. package/dist-vue/_chunks/src-nb8MU1sh.js +183 -0
  134. package/dist-vue/_chunks/src-nb8MU1sh.js.map +1 -0
  135. package/dist-vue/_chunks/{useChatbotStore-C1lW6qXE.js → useChatbotStore--6ws3cew.js} +4 -4
  136. package/dist-vue/_chunks/{useChatbotStore-C1lW6qXE.js.map → useChatbotStore--6ws3cew.js.map} +1 -1
  137. package/dist-vue/_chunks/{useSafeLocalStorage-DImmddot.js → useSafeLocalStorage-Bn4SsL8C.js} +2 -2
  138. package/dist-vue/_chunks/{useSafeLocalStorage-DImmddot.js.map → useSafeLocalStorage-Bn4SsL8C.js.map} +1 -1
  139. package/dist-vue/_chunks/{utils-D9BAduwQ.js → utils-BgvjC1Pu.js} +2 -2
  140. package/dist-vue/_chunks/{utils-D9BAduwQ.js.map → utils-BgvjC1Pu.js.map} +1 -1
  141. package/dist-vue/api.js +1 -1
  142. package/dist-vue/composables.js +4 -4
  143. package/dist-vue/index.js +31 -31
  144. package/package.json +1 -1
  145. package/dist/_chunks/browser-CwAulEhA.js.map +0 -1
  146. package/dist/_chunks/src-Bg96usAF.js +0 -132
  147. package/dist/_chunks/src-Bg96usAF.js.map +0 -1
  148. package/dist-vue/_chunks/src-j7iLdNe4.js +0 -132
  149. package/dist-vue/_chunks/src-j7iLdNe4.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"src-JJyCGvqH.js","names":["MAX_ERRORS","MAX_HELD_VALUES","QUERY_PARAMS_IN_TEXT","QUERY_PARAMS_IN_JSON","redactQueryParams","pending","errorsHeldBy","value","visited","current","redactOne","aggregated","redactQueryParamsInText","text","redactQueryParamsInValues","values","redactQueryParamsInAttributes","keys","attributes","key","index","prototype","held","error","query","params","message","_otelBridge","SENSITIVE_KEY_RE","SERIALIZE_MAX_DEPTH","SERIALIZE_MAX_LENGTH","safeSerialize","seen","render","val","depth","item","out","rendered","CAUSE_MAX_DEPTH","formatError","lines","printed","cause","formatParam","param","extractError","p","formatParams","isServerSide","isLoggingEnabled","LEVEL_WEIGHT","_consoleFloor","level","printsAt","log","safe","err","info","debug","warn","withAttrs","attrs","logger","name","condition","table","ONE_DIGIT_COUNTRY_CODES","TWO_DIGIT_COUNTRY_CODES","splitCountryCode","length","digits","formatPhoneNumber","phone","cleaned","nationalNumber","countryCode","defaultPrefix","match","split","prefix","parts","remaining"],"sources":["../../../../packages/utils/src/query-error.ts","../../../../packages/utils/src/logger.ts","../../../../packages/utils/src/internal-signature.ts","../../../../packages/utils/src/phoneNumber.ts"],"sourcesContent":["/** How many errors one call looks at, causes and aggregates included. */\nconst MAX_ERRORS = 20\n\n/** How many values of a holder (`{ err }`, a list of params) are looked at. */\nconst MAX_HELD_VALUES = 50\n\n/**\n * The values of a failed query written into a text. Drizzle's message is\n * `Failed query: <sql>`, the SQL on as many lines as it was written, then\n * `params: <values>`, which run to the end of the message: to the first frame\n * of a stack or to the end of the text. A frame is a line indented with spaces\n * that starts with `at ` and ends in `:line:column`, which a page's text\n * almost never does; `\\s` in place of the spaces would read every run of blank\n * lines in the values again from each of its lines (1.5 s for 20,000 of them\n * on 2026-10-30). A section already redacted is left alone.\n */\nconst QUERY_PARAMS_IN_TEXT =\n /(Failed query: [\\s\\S]*?\\nparams: )(?!values not logged|\\d+ values, not logged)[\\s\\S]*?(?=\\n[ \\t]+at [^\\n]*:\\d+:\\d+\\)?(?:\\n|$)|$)/g\n\n/**\n * The same values in a text that went through `JSON.stringify`, an attribute\n * logged as JSON: the line breaks are written `\\n`, and the values run to the\n * quote that closes the string.\n */\nconst QUERY_PARAMS_IN_JSON =\n /(Failed query: (?:[^\"\\\\]|\\\\.)*?\\\\nparams: )(?!values not logged|\\d+ values, not logged)(?:[^\"\\\\]|\\\\.)*/g\n\n/**\n * Takes the bound values out of a failed query's error, in place: the error\n * itself, every cause and every error of an aggregate under it, or the errors\n * a holder carries one level down (`{ err }`, a list of params).\n *\n * Drizzle's `DrizzleQueryError` writes every value into its message, so into\n * its stack, and keeps them in an enumerable `params` that any serializer\n * copying the error carries too. On 2026-10-29 a failed document write put the\n * whole text of each page in the console logs, six times per delivery. The\n * SQL stays, the values become a count, and `params` stays on the error for\n * code that reads it but is no longer enumerable, which also marks the error\n * as done.\n *\n * It changes the error itself because the error travels on: rethrown to the\n * Functions host or to Fastify's error handler, which log it their own way.\n * Recognised by its shape, because this package does not depend on\n * drizzle-orm. Mirrored in packages/telemetry, which cannot import this one.\n */\nexport function redactQueryParams(value: unknown): void {\n const pending = errorsHeldBy(value)\n const visited = new Set<unknown>()\n while (pending.length > 0 && visited.size < MAX_ERRORS) {\n const current = pending.shift()\n if (!(current instanceof Error) || visited.has(current)) {\n continue\n }\n visited.add(current)\n redactOne(current)\n pending.push((current as { cause?: unknown }).cause)\n const aggregated = (current as { errors?: unknown }).errors\n if (Array.isArray(aggregated)) {\n pending.push(...aggregated)\n }\n }\n}\n\n/**\n * A text without the values of a failed query: for an error that became a\n * string before any sink saw it, `${String(error)}` in a message, a stack\n * passed on as text, or either inside JSON.\n */\nexport function redactQueryParamsInText(text: string): string {\n if (!text.includes('Failed query: ')) {\n return text\n }\n return text\n .replace(QUERY_PARAMS_IN_TEXT, '$1values not logged')\n .replace(QUERY_PARAMS_IN_JSON, '$1values not logged')\n}\n\n/**\n * Values about to be logged, without a failed query's values: every error\n * among them loses them in place, and a string that already carries one comes\n * back without them. For a logger that hands its params to a console as they\n * are.\n */\nexport function redactQueryParamsInValues(values: unknown[]): unknown[] {\n return values.map((value) => {\n redactQueryParams(value)\n return typeof value === 'string'\n ? redactQueryParamsInText(value)\n : value\n })\n}\n\n/**\n * Attributes about to be logged, the same way: a copy whose strings no longer\n * carry a failed query's values, every error among them changed in place.\n */\nexport function redactQueryParamsInAttributes(\n attributes: Record<string, unknown>,\n): Record<string, unknown> {\n const keys = Object.keys(attributes)\n const values = redactQueryParamsInValues(keys.map((key) => attributes[key]))\n return Object.fromEntries(keys.map((key, index) => [key, values[index]]))\n}\n\nconst errorsHeldBy = (value: unknown): unknown[] => {\n if (value instanceof Error || value === null || typeof value !== 'object') {\n return [value]\n }\n // Only what a caller builds to log, a plain object or a list: reading the\n // fields of a class instance, a DOM element or a framework object can run\n // code (a getter, a layout).\n const prototype: unknown = Object.getPrototypeOf(value)\n if (\n !Array.isArray(value) &&\n prototype !== Object.prototype &&\n prototype !== null\n ) {\n return []\n }\n const held: unknown[] = []\n // A getter that throws must not make a log call throw: what was read\n // before it is still looked at.\n try {\n for (const key in value) {\n if (held.length >= MAX_HELD_VALUES) {\n break\n }\n held.push((value as Record<string, unknown>)[key])\n }\n } catch {\n // Nothing to do: see above.\n }\n return held\n}\n\nconst redactOne = (error: Error): void => {\n const { query, params } = error as { query?: unknown; params?: unknown }\n if (\n typeof query !== 'string' ||\n !Array.isArray(params) ||\n !Object.prototype.propertyIsEnumerable.call(error, 'params') ||\n typeof error.message !== 'string' ||\n !error.message.startsWith('Failed query: ')\n ) {\n return\n }\n const message = `Failed query: ${query}\\nparams: ${params.length} values, not logged`\n try {\n // A stack that no longer starts from the message (something rewrote\n // the message) keeps the values wherever they are: its frames go\n // with them.\n error.stack =\n typeof error.stack === 'string' &&\n error.stack.includes(error.message)\n ? error.stack.replace(error.message, () => message)\n : `${error.name}: ${message}`\n error.message = message\n Object.defineProperty(error, 'params', {\n value: params,\n enumerable: false,\n writable: true,\n configurable: true,\n })\n } catch {\n // A frozen error cannot change, and a log call must not throw: the\n // text rule still takes the values out of what is printed.\n }\n}\n","import type { Ref } from 'vue'\nimport {\n redactQueryParams,\n redactQueryParamsInAttributes,\n redactQueryParamsInText,\n redactQueryParamsInValues,\n} from './query-error'\n\ntype ExceptionTracker = (\n error: Error,\n properties?: Record<string, string>,\n) => void\n\ntype OtelLoggerBridge = {\n logInfo: (msg: string, attrs?: Record<string, unknown>) => void\n logEvent: (name: string, attrs?: Record<string, unknown>) => void\n logDebug: (msg: string, attrs?: Record<string, unknown>) => void\n logWarn: (msg: string, attrs?: Record<string, unknown>) => void\n logError: (msg: string, attrs?: Record<string, unknown>) => void\n logException: (error: Error, attrs?: Record<string, unknown>) => void\n} | null\n\nlet _exceptionTracker: ExceptionTracker | undefined\n/** Runtime-set bridge to OTel LoggerProvider (set during backend init) */\nlet _otelBridge: OtelLoggerBridge = null\n\n/**\n * Registers the OTel logger bridge at runtime.\n * Called by the backend during startup; no-op in the frontend.\n */\nexport const setOtelLoggerBridge = (bridge: OtelLoggerBridge) => {\n _otelBridge = bridge\n}\n\n/**\n * Registers a callback invoked by error/warn/logError/logWarn to track exceptions\n * (e.g. OTel recordException + span status ERROR).\n */\nexport const setExceptionTracker = (tracker: ExceptionTracker) => {\n _exceptionTracker = tracker\n}\n\n/**\n * Keys whose values must never land in a log line. The OTel sink additionally\n * masks value patterns (see packages/telemetry/src/sanitization.ts), which\n * utils cannot import: the bridge exists precisely to avoid that dependency.\n */\nconst SENSITIVE_KEY_RE =\n /pass(word)?|secret|token|api[-_]?key|authorization|cookie|credential/i\nconst SERIALIZE_MAX_DEPTH = 3\nconst SERIALIZE_MAX_LENGTH = 2_000\n\n/**\n * Serializes a non-Error object for a log line. `String(param)` produced\n * `[object Object]`, which made whole error families undiagnosable. A naked\n * JSON.stringify is not the fix either: it throws on circular references and\n * BigInt, has no depth or length cap, and would promote sensitive fields\n * into the message. This handles all four.\n */\nconst safeSerialize = (value: unknown): string => {\n const seen = new WeakSet<object>()\n const render = (val: unknown, depth: number): unknown => {\n if (val instanceof Error) {\n redactQueryParams(val)\n return val.stack ?? val.message\n }\n if (typeof val === 'bigint') {\n return `${val.toString()}n`\n }\n if (typeof val === 'function' || typeof val === 'symbol') {\n return String(val)\n }\n if (typeof val !== 'object' || val === null) {\n return val\n }\n if (seen.has(val)) {\n return '[Circular]'\n }\n if (depth >= SERIALIZE_MAX_DEPTH) {\n return Array.isArray(val) ? '[Array]' : '[Object]'\n }\n // Added on the way down, removed on the way back up: only a true\n // cycle is flagged, a shared reference (the same object under two\n // keys) is rendered normally.\n seen.add(val)\n try {\n if (Array.isArray(val)) {\n return val.map((item) => render(item, depth + 1))\n }\n const out: Record<string, unknown> = {}\n for (const [key, item] of Object.entries(val)) {\n out[key] = SENSITIVE_KEY_RE.test(key)\n ? '[REDACTED]'\n : render(item, depth + 1)\n }\n return out\n } finally {\n seen.delete(val)\n }\n }\n try {\n const rendered = render(value, 0)\n const text =\n typeof rendered === 'string' ? rendered : JSON.stringify(rendered)\n if (typeof text !== 'string') {\n return String(text)\n }\n return text.length > SERIALIZE_MAX_LENGTH\n ? `${text.slice(0, SERIALIZE_MAX_LENGTH)}… [truncated]`\n : text\n } catch {\n return '[Unserializable]'\n }\n}\n\n/** How many causes a log line follows, however long the chain. */\nconst CAUSE_MAX_DEPTH = 5\n\n/**\n * An error as a log line shows it: its stack, then each cause in its chain,\n * each one once. Wrappers like Drizzle keep only \"Failed query\" in their own\n * message and put the Postgres error in `cause`, so a line with the stack\n * alone said which write failed and never why. Mirrors `formatCauseChain` in\n * packages/telemetry, which this package cannot import: that one renders the\n * exception record, this one the console line and the text a WARN or INFO\n * hands the bridge. A cause that is not an error goes through\n * `safeSerialize`, where telemetry's `String(cause)` would print\n * `[object Object]`.\n */\nconst formatError = (error: Error): string => {\n const lines = [error.stack ?? error.message]\n const printed = new Set<unknown>([error])\n let cause = (error as { cause?: unknown }).cause\n for (\n let depth = 0;\n cause != null && !printed.has(cause) && depth < CAUSE_MAX_DEPTH;\n depth++\n ) {\n printed.add(cause)\n if (cause instanceof Error) {\n lines.push(`Caused by: ${cause.stack ?? cause.message}`)\n cause = (cause as { cause?: unknown }).cause\n } else {\n lines.push(`Caused by: ${safeSerialize(cause)}`)\n cause = undefined\n }\n }\n return lines.join('\\n')\n}\n\nconst formatParam = (param: unknown): string => {\n if (param instanceof Error) {\n return formatError(param)\n }\n if (typeof param === 'object' && param !== null) {\n return safeSerialize(param)\n }\n return String(param)\n}\n\nconst extractError = (params: unknown[]): Error => {\n const found = params.find((p): p is Error => p instanceof Error)\n if (found) {\n return found\n }\n return new Error(params.map(formatParam).join(' '))\n}\n\nconst formatParams = (params: unknown[]): string => {\n return redactQueryParamsInText(params.map(formatParam).join(' '))\n}\n\nconst isServerSide = typeof window === 'undefined'\n// `import.meta.env` only exists in Vite builds: the cast keeps this file\n// compilable under plain Node tsconfigs (e.g. apps/azure-functions)\nconst isLocal = isServerSide\n ? process?.env?.VITE_LOCAL === 'true'\n : (import.meta as { env?: Record<string, unknown> }).env?.VITE_LOCAL ===\n 'true'\n\nconst isLoggingEnabled = isLocal || isServerSide\n\n/**\n * Console severity floor, read from `LOG_LEVEL`.\n *\n * The OTel bridge below has always honoured that variable, which is why\n * production exports no INFO rows. The console writers did not, and\n * `isLoggingEnabled` is unconditionally true on a server, so every info line\n * still reached stdout in every environment: the two sinks disagreed, and the\n * container log pipeline kept billing for rows nobody could query. Measured on\n * 2026-09-02: one knowledge-base search wrote three of them, one carrying 500\n * characters of dense-vector JSON, three times per turn.\n *\n * The default is `info`, so an environment that sets nothing keeps exactly the\n * output it has today. Note that an `error` is still tracked and exported when\n * the floor hides it from the console: only the console write is gated.\n */\nconst LEVEL_WEIGHT: Record<string, number> = {\n debug: 10,\n info: 20,\n warn: 30,\n error: 40,\n fatal: 50,\n}\nconst readLevel = (level: string | undefined): number =>\n LEVEL_WEIGHT[(level ?? '').toLowerCase()] ?? LEVEL_WEIGHT.info\n\nlet _consoleFloor = isServerSide\n ? readLevel(process?.env?.LOG_LEVEL)\n : LEVEL_WEIGHT.info\n\n/**\n * Overrides the console floor for a level chosen at runtime rather than by\n * env, mirroring `setLogLevel` on the OTel side. The backend calls both from\n * one place so the two sinks cannot drift (`apps/backend/src/main.ts`).\n */\nexport const setConsoleLogLevel = (level: string): void => {\n _consoleFloor = readLevel(level)\n}\n\n/** Whether a message of this severity should reach the console. */\nconst printsAt = (level: 'debug' | 'info' | 'warn' | 'error'): boolean =>\n isLoggingEnabled && LEVEL_WEIGHT[level] >= _consoleFloor\n\nexport const log = (...params: unknown[]) => {\n const safe = redactQueryParamsInValues(params)\n if (printsAt('info')) {\n // eslint-disable-next-line no-console\n console.log(...safe)\n }\n _otelBridge?.logInfo(formatParams(safe))\n}\n\nexport const error = (...params: unknown[]) => {\n const safe = redactQueryParamsInValues(params)\n const err = extractError(safe)\n _exceptionTracker?.(err)\n _otelBridge?.logException(err)\n if (printsAt('error')) {\n // eslint-disable-next-line no-console\n console.error(formatParams(safe))\n }\n}\n\nexport const info = (...params: unknown[]) => {\n const safe = redactQueryParamsInValues(params)\n if (printsAt('info')) {\n // eslint-disable-next-line no-console\n console.info(...safe)\n }\n _otelBridge?.logInfo(formatParams(safe))\n}\n\nexport const debug = (...params: unknown[]) => {\n const safe = redactQueryParamsInValues(params)\n if (printsAt('debug')) {\n // eslint-disable-next-line no-console\n console.debug(...safe)\n }\n _otelBridge?.logDebug(formatParams(safe))\n}\n\nexport const warn = (...params: unknown[]) => {\n // A warning is not an exception: it must never reach `app_errors`, so\n // the OTel bridge gets only logWarn. The exception tracker stays: it is\n // wired in the frontend only (Application Insights trackException).\n const safe = redactQueryParamsInValues(params)\n const err = extractError(safe)\n _exceptionTracker?.(err)\n // Serialize once for both sinks: the walk is depth-capped but not free.\n const text = formatParams(safe)\n _otelBridge?.logWarn(text)\n if (printsAt('warn')) {\n // eslint-disable-next-line no-console\n console.warn(text)\n }\n}\n\n/**\n * The console rendering of a fixed message plus attributes: ONE line, with the\n * attributes as JSON after the message. `console.warn(message, attrs)` lets\n * Node's inspector break a wide object across several lines, and a container\n * log pipeline stores each line as its own row, so the query that reads the\n * attributes back finds the first row and a fragment. `formatParams` also\n * redacts the sensitive keys and survives a circular reference.\n */\nconst withAttrs = (message: string, attrs?: Record<string, unknown>): string =>\n attrs ? formatParams([message, attrs]) : message\n\n/**\n * WARN with a fixed message and structured attributes. Prefer this over\n * interpolating values into the message: a fixed message keeps the log\n * stream groupable (and therefore alertable), the values stay queryable\n * as attributes.\n */\nexport const warnAttrs = (message: string, attrs?: Record<string, unknown>) => {\n const safe = attrs && redactQueryParamsInAttributes(attrs)\n _otelBridge?.logWarn(message, safe)\n if (printsAt('warn')) {\n // eslint-disable-next-line no-console\n console.warn(withAttrs(message, safe))\n }\n}\n\n/**\n * A measurement event: one fixed name, the ids as attributes, and **neither\n * sink drops it**, whatever `LOG_LEVEL` says.\n *\n * The info twin of {@link warnAttrs} used to be an ordinary INFO line, and that\n * was wrong in the one environment it exists for: production runs at\n * `LOG_LEVEL=warn`, so the console floor and the OTel floor would each have\n * dropped it and the measurement it feeds would have read zero rows and been\n * believed. WARN is not the answer either, because these events fire on the\n * majority of turns and a normal event at WARN degrades the level alerting\n * watches. So this is a channel, not a level: severity stays INFO and the floor\n * does not apply.\n *\n * The price is that nothing else may use it. Keep the callers few\n * (`closure_gate.refused`, `closure_recovery.applied`) and the volume of the\n * order of one row per turn, and never pass a message with the values\n * interpolated into it: a fixed name is what makes the rows groupable by agent\n * instead of countable by regex.\n */\nexport const logEvent = (name: string, attrs?: Record<string, unknown>) => {\n const safe = attrs && redactQueryParamsInAttributes(attrs)\n _otelBridge?.logEvent(name, safe)\n if (isLoggingEnabled) {\n // eslint-disable-next-line no-console\n console.log(withAttrs(name, safe))\n }\n}\n\nexport const assert = (condition: boolean | undefined, message: string) => {\n if (isLoggingEnabled) {\n // eslint-disable-next-line no-console\n console.assert(condition, message)\n }\n}\n\nexport const clear = () => {\n if (isLoggingEnabled) {\n // eslint-disable-next-line no-console\n console.clear()\n }\n}\n\n/**\n * A table is an info line that happens to be wide, so it answers to the floor\n * like one. It used to check only `isLoggingEnabled`, which left the usage\n * table of every turn on the console of an environment set to `warn`, and made\n * it the last write of a turn in the test run: vitest reports a console write\n * that outlives its test as `Closing rpc while \"onUserConsoleLog\" was pending`\n * and fails a run whose tests all passed.\n */\nexport const table = (table: unknown) => {\n if (printsAt('info')) {\n // eslint-disable-next-line no-console\n console.table(table)\n }\n}\n\nexport const group = (name: string) => {\n if (isLoggingEnabled) {\n // eslint-disable-next-line no-console\n console.group(name)\n }\n}\n\nexport const groupEnd = () => {\n if (isLoggingEnabled) {\n // eslint-disable-next-line no-console\n console.groupEnd()\n }\n}\n\nexport const time = (name: string) => {\n if (isLoggingEnabled) {\n // eslint-disable-next-line no-console\n console.time(name)\n }\n}\n\nexport const timeEnd = (name: string) => {\n if (isLoggingEnabled) {\n // eslint-disable-next-line no-console\n console.timeEnd(name)\n }\n}\n\nexport const timeLog = (name: string, ...params: unknown[]) => {\n if (isLoggingEnabled) {\n // eslint-disable-next-line no-console\n console.timeLog(name, ...params)\n }\n}\n\nexport const logger = {\n log,\n error,\n info,\n debug,\n warn,\n warnAttrs,\n logEvent,\n assert,\n clear,\n table,\n group,\n groupEnd,\n time,\n timeEnd,\n timeLog,\n}\n\nexport const useErrorsLogger = (errors: Ref<Error | null | undefined>[]) => {\n // Vue is an optional runtime dependency for the backend build.\n // Lazily import it only when running in a browser/Vue environment.\n if (typeof window === 'undefined') {\n return\n }\n\n void import('vue').then(({ watch }) => {\n errors.forEach((error) => {\n watch(error, (value) => {\n logger.error(value)\n })\n })\n })\n}\n","/**\n * Signature of the calls the function app makes to the backend's internal\n * routes (spec agent-wakeup, \"Timer: coda, function, endpoint interno\"). Both\n * ends share `INTERNAL_API_SECRET`; the signed payload binds the method, the\n * path, the body and a timestamp, so a captured request cannot be replayed on\n * another route nor after the tolerance window.\n *\n * WebCrypto, not `node:crypto`: this package is imported by the browser too.\n */\nexport const INTERNAL_SIGNATURE_HEADER = 'x-internal-signature'\nexport const INTERNAL_TIMESTAMP_HEADER = 'x-internal-timestamp'\nexport const INTERNAL_SIGNATURE_TOLERANCE_MS = 5 * 60_000\n\ninterface InternalRequest {\n secret: string\n method: string\n /** The path as the server routes it, without host or querystring. */\n path: string\n body: string\n}\n\nconst encoder = new TextEncoder()\n\nconst hmacSha256Hex = async (secret: string, payload: string) => {\n const key = await globalThis.crypto.subtle.importKey(\n 'raw',\n encoder.encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign'],\n )\n const signature = await globalThis.crypto.subtle.sign(\n 'HMAC',\n key,\n encoder.encode(payload),\n )\n return Array.from(new Uint8Array(signature), (byte) =>\n byte.toString(16).padStart(2, '0'),\n ).join('')\n}\n\nconst signedPayload = (\n { method, path, body }: InternalRequest,\n timestamp: string,\n) => `${timestamp}.${method.toUpperCase()}.${path}.${body}`\n\n/** Constant-time comparison of two hex strings. */\nconst sameHex = (a: string, b: string) => {\n if (a.length !== b.length) {\n return false\n }\n let difference = 0\n for (let index = 0; index < a.length; index++) {\n difference |= a.charCodeAt(index) ^ b.charCodeAt(index)\n }\n return difference === 0\n}\n\n/** The two headers that sign an internal request. */\nexport async function signInternalRequest(\n request: InternalRequest,\n now = Date.now(),\n): Promise<Record<string, string>> {\n const timestamp = String(now)\n return {\n [INTERNAL_TIMESTAMP_HEADER]: timestamp,\n [INTERNAL_SIGNATURE_HEADER]: await hmacSha256Hex(\n request.secret,\n signedPayload(request, timestamp),\n ),\n }\n}\n\n/**\n * Whether the headers sign this request with this secret, within the\n * tolerance window.\n */\nexport async function verifyInternalRequest(\n request: InternalRequest & {\n signature: string | undefined\n timestamp: string | undefined\n },\n now = Date.now(),\n): Promise<boolean> {\n const { signature, timestamp } = request\n if (!signature || !timestamp || !/^\\d+$/.test(timestamp)) {\n return false\n }\n if (Math.abs(now - Number(timestamp)) > INTERNAL_SIGNATURE_TOLERANCE_MS) {\n return false\n }\n const expected = await hmacSha256Hex(\n request.secret,\n signedPayload(request, timestamp),\n )\n return sameHex(expected, signature.toLowerCase())\n}\n","// E.164 country codes are prefix-free: one digit for these two, two digits\n// for the next set, three for every other one. Reading \"the first one to four\n// digits\" took four, so +44 1234 567890 came out as +4412.\nconst ONE_DIGIT_COUNTRY_CODES = new Set(['1', '7'])\nconst TWO_DIGIT_COUNTRY_CODES = new Set(\n (\n '20 27 30 31 32 33 34 36 39 40 41 43 44 45 46 47 48 49 51 52 53 54 55 ' +\n '56 57 58 60 61 62 63 64 65 66 81 82 84 86 90 91 92 93 94 95 98'\n ).split(' '),\n)\n\n/** Splits international digits into country code and national number. */\nfunction splitCountryCode(digits: string): [string, string] | undefined {\n const length = ONE_DIGIT_COUNTRY_CODES.has(digits.slice(0, 1))\n ? 1\n : TWO_DIGIT_COUNTRY_CODES.has(digits.slice(0, 2))\n ? 2\n : 3\n return digits.length > length\n ? [digits.slice(0, length), digits.slice(length)]\n : undefined\n}\n\n/**\n * Formats a phone number with international prefix, its groups separated by\n * spaces as a person writes them\n * If no international prefix is provided, defaults to Italian (+39)\n *\n * @param phone - The phone number to format\n * @param defaultPrefix - The default international prefix (default: '+39')\n * @returns Formatted phone number (e.g., '+39 392 4096227')\n *\n * @example\n * formatPhoneNumber('3924096227') // '+39 392 4096227'\n * formatPhoneNumber('+393924096227') // '+39 392 4096227'\n * formatPhoneNumber('00393924096227') // '+39 392 4096227'\n * formatPhoneNumber('393924096227') // '+39 392 4096227'\n * formatPhoneNumber('0450000101') // '+39 045 0000101'\n */\nexport function formatPhoneNumber(\n phone: string | null | undefined,\n defaultPrefix = '+39',\n): string {\n if (!phone) {\n return ''\n }\n\n // Remove all non-digit characters except + at the beginning\n const cleaned = phone.trim().replace(/[^\\d+]/g, '')\n\n if (!cleaned) {\n return ''\n }\n\n // Normalize the phone number to have international prefix\n let nationalNumber = ''\n let countryCode = defaultPrefix.replace('+', '')\n\n // Handle different input formats\n if (cleaned.startsWith('+')) {\n // Already has + prefix: +393924096227\n const match = cleaned.match(/^\\+(\\d+)$/)\n if (match) {\n const digits = match[1]\n // Extract country code and national number\n if (digits.startsWith(countryCode)) {\n nationalNumber = digits.substring(countryCode.length)\n } else {\n const split = splitCountryCode(digits)\n if (split) {\n ;[countryCode, nationalNumber] = split\n }\n }\n }\n } else if (cleaned.startsWith('00')) {\n // International format without +: 00393924096227\n const digits = cleaned.substring(2)\n if (digits.startsWith(countryCode)) {\n nationalNumber = digits.substring(countryCode.length)\n } else {\n const split = splitCountryCode(digits)\n if (split) {\n ;[countryCode, nationalNumber] = split\n }\n }\n } else if (\n cleaned.startsWith(countryCode) &&\n cleaned.length > countryCode.length + 8\n ) {\n // Starts with country code but no +: 393924096227\n nationalNumber = cleaned.substring(countryCode.length)\n } else {\n // Local number: 3924096227 or 0450000101\n nationalNumber = cleaned\n // The national trunk 0 is not dialled after the country code, except\n // in Italy, where it belongs to the landline number (045 is Verona):\n // dropping it turned 045 0000101 into another number\n if (\n countryCode !== '39' &&\n nationalNumber.startsWith('0') &&\n nationalNumber.length > 1\n ) {\n nationalNumber = nationalNumber.substring(1)\n }\n }\n\n if (!nationalNumber) {\n return phone\n }\n\n const prefix = `+${countryCode}`\n\n // Italian mobile numbers: 3XX XXXXXXX (10 digits total, starting with 3)\n if (\n countryCode === '39' &&\n nationalNumber.length === 10 &&\n nationalNumber.startsWith('3')\n ) {\n return `${prefix} ${nationalNumber.substring(0, 3)} ${nationalNumber.substring(3)}`\n }\n\n // Italian landline numbers: 0XX XXXXXXX (9-11 digits, starting with 0)\n if (\n countryCode === '39' &&\n nationalNumber.length >= 9 &&\n nationalNumber.length <= 11 &&\n nationalNumber.startsWith('0')\n ) {\n const areaCode = nationalNumber.substring(0, 3)\n const rest = nationalNumber.substring(3)\n return `${prefix} ${areaCode} ${rest}`\n }\n\n // Generic formatting: group by 3-4 digits\n const parts: string[] = []\n let remaining = nationalNumber\n\n while (remaining.length > 0) {\n if (remaining.length <= 4) {\n parts.push(remaining)\n break\n }\n parts.push(remaining.substring(0, 3))\n remaining = remaining.substring(3)\n }\n\n return `${prefix} ${parts.join(' ')}`\n}\n\n/**\n * Returns a formatted phone number or a dash if empty\n * Useful for displaying in tables\n *\n * @param phone - The phone number to format\n * @param defaultPrefix - The default international prefix (default: '+39')\n * @returns Formatted phone number or '-'\n */\nexport function formatPhoneNumberOrDash(\n phone: string | null | undefined,\n defaultPrefix = '+39',\n): string {\n const formatted = formatPhoneNumber(phone, defaultPrefix)\n return formatted || '-'\n}\n"],"mappings":";;AACA,IAAMA,IAAa,IAGbC,IAAkB,IAYlBC,IACF,qIAOEC,IACF;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;CACJ,OAAO,AACHL,EAAQ,WAAWE,CAAW,KAC9BF,EAAQ,SAASE,EAAY,SAAS,IAGtC,IAAiBF,EAAQ,UAAUE,EAAY,MAAM,KAGrD,IAAiBF,GAKbE,MAAgB,QAChBD,EAAe,WAAW,GAAG,KAC7BA,EAAe,SAAS,MAExB,IAAiBA,EAAe,UAAU,CAAC;CAInD,IAAI,CAACA,GACD,OAAOF;CAGX,IAAMO,IAAS,IAAIJ;CAYnB,IARIA,MAAgB,QAChBD,EAAe,WAAW,MAC1BA,EAAe,WAAW,GAAG,KAO7BC,MAAgB,QAChBD,EAAe,UAAU,KACzBA,EAAe,UAAU,MACzBA,EAAe,WAAW,GAAG,GAI7B,OAAO,GAAGK,EAAO,GAFAL,EAAe,UAAU,GAAG,CAEzB,EAAS,GADhBA,EAAe,UAAU,CACN;CAIpC,IAAMM,IAAkB,CAAC,GACrBC,IAAYP;CAEhB,OAAOO,EAAU,SAAS,IAAG;EACzB,IAAIA,EAAU,UAAU,GAAG;GACvB,EAAM,KAAKA,CAAS;GACpB;EACJ;EAEA,AADAD,EAAM,KAAKC,EAAU,UAAU,GAAG,CAAC,CAAC,GACpC,IAAYA,EAAU,UAAU,CAAC;CACrC;CAEA,OAAO,GAAGF,EAAO,GAAGC,EAAM,KAAK,GAAG;AACtC"}
@@ -1,6 +1,6 @@
1
1
  import { I as e, gt as t, k as n, ot as r, vt as i } from "./vue.runtime.esm-bundler-C2U5uTqB.js";
2
2
  import { n as a } from "./cdn-css-C3_zuSx6.js";
3
- import "./src-Bg96usAF.js";
3
+ import "./src-JJyCGvqH.js";
4
4
  // ../../packages/components/src/composables/useLightbox.ts
5
5
  n(), r();
6
6
  var o = "https://cdn.jsdelivr.net/npm/photoswipe@5/dist/photoswipe.css", s = {
@@ -106,4 +106,4 @@ function h() {
106
106
  }
107
107
  export { c as n, l as t };
108
108
 
109
- //# sourceMappingURL=useLightbox-B575Qxeu.js.map
109
+ //# sourceMappingURL=useLightbox-BigL4WLe.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useLightbox-B575Qxeu.js","names":["onBeforeUnmount","ref","init_runtime_core_esm_bundler","init_reactivity_esm_bundler","shallowRef","loadCdnCss","PHOTOSWIPE_CSS","DEFAULT_IMAGE_SIZE","useLightbox","options","lightbox","gallery","injectPhotoSwipeOverrides","PhotoSwipeLightbox","openInNewTab","downloadable","ui","url","getCurrentSlideUrl","pswp","downloadImage","useImageSizes","sizes","image","images","img","downloadUrl","toDownloadUrl","anchor","getFilenameFromUrl","name","overridesInjected","style"],"sources":["../../../../packages/components/src/composables/useLightbox.ts"],"sourcesContent":["import {\n onBeforeUnmount,\n ref,\n shallowRef,\n type Ref,\n type ShallowRef,\n} from 'vue'\nimport type PhotoSwipeLightbox from 'photoswipe/lightbox'\nimport type PhotoSwipe from 'photoswipe'\nimport { loadCdnCss } from 'utils'\n\nconst PHOTOSWIPE_CSS =\n 'https://cdn.jsdelivr.net/npm/photoswipe@5/dist/photoswipe.css'\n\nconst DEFAULT_IMAGE_SIZE = { width: 1200, height: 800 }\n\nexport interface LightboxImage {\n url: string\n caption?: string\n alt?: string\n /** Natural width in px — used by PhotoSwipe for proper sizing. */\n width?: number\n /** Natural height in px — used by PhotoSwipe for proper sizing. */\n height?: number\n}\n\nexport interface LightboxOptions {\n /** Container element whose child anchors are the gallery items */\n gallery: Ref<HTMLElement | undefined>\n /** CSS selector for gallery items inside the container (default: `'a[data-pswp-src]'`) */\n children?: string\n loop?: boolean\n /** Show a download button in the lightbox toolbar */\n downloadable?: boolean\n /** Show an open-in-new-tab button in the lightbox toolbar */\n openInNewTab?: boolean\n}\n\nexport interface UseLightboxReturn {\n lightbox: ShallowRef<PhotoSwipeLightbox | null>\n /** Initialises PhotoSwipe. Call this inside `onMounted`. */\n init: () => Promise<void>\n}\n\n/**\n * Encapsulates PhotoSwipe 5 initialisation, toolbar customisation, and lifecycle cleanup.\n * CSS is injected into `document.head` so the overlay works in both regular DOM and Shadow DOM.\n *\n * Usage:\n * ```ts\n * const { init } = useLightbox({ gallery: galleryRef, downloadable: true })\n * onMounted(init)\n * ```\n */\nexport function useLightbox(options: LightboxOptions): UseLightboxReturn {\n const {\n gallery,\n children = 'a[data-pswp-src]',\n loop = true,\n downloadable = true,\n openInNewTab = true,\n } = options\n\n const lightbox = shallowRef<PhotoSwipeLightbox | null>(null)\n\n const init = async () => {\n if (!gallery.value) {\n return\n }\n\n // PhotoSwipe renders its overlay into document.body, so CSS must be in\n // document.head — not inside a shadow root.\n loadCdnCss(PHOTOSWIPE_CSS)\n injectPhotoSwipeOverrides()\n\n const { default: PhotoSwipeLightbox } =\n await import('photoswipe/lightbox')\n\n lightbox.value = new PhotoSwipeLightbox({\n gallery: gallery.value,\n children,\n pswpModule: () => import('photoswipe'),\n loop,\n arrowPrevSVG:\n '<svg aria-hidden=\"true\" class=\"pswp__icn\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\"><path fill=\"#ffffff\" d=\"m10.828 12l4.95 4.95l-1.414 1.415L8 12l6.364-6.364l1.414 1.414z\"/></svg>',\n arrowNextSVG:\n '<svg aria-hidden=\"true\" class=\"pswp__icn\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\"><path fill=\"#ffffff\" d=\"m13.172 12l-4.95-4.95l1.414-1.413L16 12l-6.364 6.364l-1.414-1.415z\"/></svg>',\n closeSVG:\n '<svg aria-hidden=\"true\" class=\"pswp__icn\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\"><path fill=\"#ffffff\" d=\"m12 10.587l4.95-4.95l1.414 1.414l-4.95 4.95l4.95 4.95l-1.415 1.414l-4.95-4.95l-4.949 4.95l-1.414-1.415l4.95-4.95l-4.95-4.95L7.05 5.638z\"/></svg>',\n zoomSVG:\n '<svg aria-hidden=\"true\" class=\"pswp__icn\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\"><g class=\"pswp__icn--zoom-in\"><path fill=\"#ffffff\" d=\"m18.031 16.617l4.283 4.282l-1.415 1.415l-4.282-4.283A8.96 8.96 0 0 1 11 20c-4.968 0-9-4.032-9-9s4.032-9 9-9s9 4.032 9 9a8.96 8.96 0 0 1-1.969 5.617m-2.006-.742A6.98 6.98 0 0 0 18 11c0-3.867-3.133-7-7-7s-7 3.133-7 7s3.133 7 7 7a6.98 6.98 0 0 0 4.875-1.975zM10 10V7h2v3h3v2h-3v3h-2v-3H7v-2z\"/></g><g class=\"pswp__icn--zoom-out\"><path fill=\"#ffffff\" d=\"m18.031 16.617l4.283 4.282l-1.415 1.415l-4.282-4.283A8.96 8.96 0 0 1 11 20c-4.968 0-9-4.032-9-9s4.032-9 9-9s9 4.032 9 9a8.96 8.96 0 0 1-1.969 5.617m-2.006-.742A6.98 6.98 0 0 0 18 11c0-3.867-3.133-7-7-7s-7 3.133-7 7s3.133 7 7 7a6.98 6.98 0 0 0 4.875-1.975zM7 10h8v2H7z\"/></g></svg>',\n })\n\n if (openInNewTab || downloadable) {\n lightbox.value.on('uiRegister', () => {\n const ui = lightbox.value!.pswp?.ui\n if (!ui) {\n return\n }\n\n if (openInNewTab) {\n ui.registerElement({\n name: 'open-in-new-tab-button',\n order: 8,\n isButton: true,\n html: '<svg aria-hidden=\"true\" class=\"pswp__icn\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\"><path fill=\"#ffffff\" d=\"M10 6v2H5v11h11v-5h2v6a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1zm11-3v8h-2V6.413l-7.793 7.794l-1.414-1.414L17.585 5H13V3z\"/></svg>',\n title: 'Open in new tab',\n onClick: (_, __, pswp) => {\n const url = getCurrentSlideUrl(pswp)\n if (url) {\n window.open(\n url,\n '_blank',\n 'noopener,noreferrer',\n )\n }\n },\n })\n }\n\n if (downloadable) {\n ui.registerElement({\n name: 'download-button',\n order: 9,\n isButton: true,\n html: '<svg aria-hidden=\"true\" class=\"pswp__icn\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\"><path fill=\"#ffffff\" d=\"M3 19h18v2H3zm10-5.828L19.071 7.1l1.414 1.414L12 17L3.515 8.515L4.929 7.1L11 13.173V2h2z\"/></svg>',\n title: 'Download',\n onClick: (_, __, pswp) => {\n const url = getCurrentSlideUrl(pswp)\n if (url) {\n downloadImage(url)\n }\n },\n })\n }\n })\n }\n\n lightbox.value.init()\n }\n\n onBeforeUnmount(() => {\n lightbox.value?.destroy()\n lightbox.value = null\n })\n\n return { lightbox, init }\n}\n\n// ---------------------------------------------------------------------------\n// Image size preloading\n// ---------------------------------------------------------------------------\n\nexport interface UseImageSizesReturn {\n preload: (\n images: Array<{ url: string; width?: number; height?: number }>,\n ) => void\n getSize: (url: string) => { width: number; height: number }\n}\n\n/**\n * Preloads natural image dimensions so PhotoSwipe can size its slides correctly.\n * When `width`/`height` are already provided they are used as-is;\n * otherwise the image is loaded in the background to read `naturalWidth`/`naturalHeight`.\n */\nexport function useImageSizes(): UseImageSizesReturn {\n const sizes = ref(new Map<string, { width: number; height: number }>())\n\n const preload = (\n images: Array<{ url: string; width?: number; height?: number }>,\n ) => {\n for (const image of images) {\n if (image.width && image.height) {\n sizes.value.set(image.url, {\n width: image.width,\n height: image.height,\n })\n continue\n }\n const img = new Image()\n img.onload = () => {\n sizes.value.set(image.url, {\n width: img.naturalWidth,\n height: img.naturalHeight,\n })\n }\n img.src = image.url\n }\n }\n\n const getSize = (url: string) => sizes.value.get(url) ?? DEFAULT_IMAGE_SIZE\n\n return { preload, getSize }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction getCurrentSlideUrl(pswp: PhotoSwipe): string | undefined {\n return (\n pswp.currSlide?.data?.src ??\n pswp.currSlide?.data?.element\n ?.querySelector('img')\n ?.getAttribute('src') ??\n pswp.currSlide?.data?.element\n ?.querySelector('source')\n ?.getAttribute('srcset') ??\n pswp.currSlide?.data?.element?.getAttribute('src') ??\n undefined\n )\n}\n\n/**\n * Triggers a client-side download for an image URL.\n *\n * For backend media URLs (.../media/:file/view), navigates to the\n * corresponding /download endpoint which redirects to an Azure SAS URL\n * with `Content-Disposition: attachment` — no CORS issues.\n *\n * For blob: URLs (in-session uploads), uses the fetch → blob approach.\n *\n * For data: URLs (inline SVGs, etc.), use the download attribute.\n *\n * Falls back to opening in a new tab for all other cases.\n */\nfunction downloadImage(url: string): void {\n const downloadUrl = toDownloadUrl(url)\n\n const anchor = document.createElement('a')\n anchor.href = downloadUrl\n anchor.target = '_blank'\n anchor.rel = 'noopener noreferrer'\n // `download` attribute works for same-origin, data: and blob: URLs; for\n // cross-origin it is ignored but the browser still follows Content-Disposition.\n anchor.download = getFilenameFromUrl(url)\n document.body.appendChild(anchor)\n anchor.click()\n document.body.removeChild(anchor)\n}\n\n/**\n * Converts a `/view` media URL to its `/download` counterpart.\n * Leaves blob:, data: and all other URLs untouched.\n */\nfunction toDownloadUrl(url: string): string {\n return url.replace(/\\/view(\\?|$)/, '/download$1')\n}\n\nfunction getFilenameFromUrl(url: string): string {\n if (url.startsWith('data:image/svg+xml')) {\n return 'diagram.svg'\n }\n if (url.startsWith('data:')) {\n const mime = url.split(':')[1].split(';')[0]\n const ext = mime.split('/')[1] || 'bin'\n return `image.${ext}`\n }\n try {\n const pathname = new URL(url).pathname\n const name = pathname.split('/').pop()\n return name && name.includes('.') ? name : 'image'\n } catch {\n return 'image'\n }\n}\n\nlet overridesInjected = false\n\n/**\n * Injects a one-time `<style>` into `document.head` that raises\n * PhotoSwipe's z-index above any host UI (e.g. floating chat widgets\n * that use `z-index: 2147483647`).\n */\nfunction injectPhotoSwipeOverrides(): void {\n if (overridesInjected) {\n return\n }\n overridesInjected = true\n const style = document.createElement('style')\n style.textContent = [\n '.pswp__counter { font-family: sans-serif; }',\n '.pswp { z-index: 2147483647 !important; }',\n '.pswp__icn { width: 20px; height: 20px; }',\n '.pswp__button { width: 40px; height: 40px; display: flex; align-items: center; justify-content: center; }',\n '.pswp__icn--zoom-out { display: none; }',\n '.pswp--zoomed-in .pswp__icn--zoom-in { display: none; }',\n '.pswp--zoomed-in .pswp__icn--zoom-out { display: block; }',\n '.pswp__button--arrow .pswp__icn {left: auto; right: auto; width: 40px; height: 40px; transform: none; margin-top: -20px; }',\n ].join(' ')\n document.head.appendChild(style)\n}\n"],"mappings":";;;;;AAWA,IAAMM,IACF,iEAEEC,IAAqB;CAAE,OAAO;CAAM,QAAQ;AAAI;AAwCtD,SAAgBC,EAAY,GAA6C;CACrE,IAAM,EACF,YACA,cAAW,oBACX,UAAO,IACP,kBAAe,IACf,kBAAe,OACfC,GAEEC,IAAWN,EAAsC,IAAI;CAmF3D,OALAJ,QAAsB;EAElB,AADAU,EAAS,OAAO,QAAQ,GACxB,EAAS,QAAQ;CACrB,CAAC,GAEM;EAAE;EAAU,kBAjFM;GACrB,IAAI,CAACC,EAAQ,OACT;GAMJ,AADAN,EAAWC,CAAc,GACzBM,EAA0B;GAE1B,IAAM,EAAE,SAASC,MACb,MAAM,OAAO;GA8DjB,AA5DA,EAAS,QAAQ,IAAIA,EAAmB;IACpC,SAASF,EAAQ;IACjB;IACA,kBAAkB,OAAO;IACzB;IACA,cACI;IACJ,cACI;IACJ,UACI;IACJ,SACI;GACR,CAAC,IAEGG,KAAgBC,MAChBL,EAAS,MAAM,GAAG,oBAAoB;IAClC,IAAMM,IAAKN,EAAS,MAAO,MAAM;IACjC,AAAKM,MAIDF,KACAE,EAAG,gBAAgB;KACf,MAAM;KACN,OAAO;KACP,UAAU;KACV,MAAM;KACN,OAAO;KACP,UAAU,GAAG,GAAI,MAAS;MACtB,IAAMC,IAAMC,EAAmBC,CAAI;MACnC,AAAIF,KACA,OAAO,KACHA,GACA,UACA,qBACJ;KAER;IACJ,CAAC,GAGDF,KACAC,EAAG,gBAAgB;KACf,MAAM;KACN,OAAO;KACP,UAAU;KACV,MAAM;KACN,OAAO;KACP,UAAU,GAAG,GAAI,MAAS;MACtB,IAAMC,IAAMC,EAAmBC,CAAI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AEA,SAASY,EAAmB,GAAqB;CAC7C,IAAIZ,EAAI,WAAW,oBAAoB,GACnC,OAAO;CAEX,IAAIA,EAAI,WAAW,OAAO,GAGtB,OAAO,SAFMA,EAAI,MAAM,GAAG,CAAC,CAAC,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC,EAC9B,CAAK,MAAM,GAAG,CAAC,CAAC,MAAM;CAGtC,IAAI;EAEA,IAAMa,IADW,IAAI,IAAIb,CAAG,CAAC,CAAC,SACR,MAAM,GAAG,CAAC,CAAC,IAAI;EACrC,OAAOa,KAAQA,EAAK,SAAS,GAAG,IAAIA,IAAO;CAC/C,QAAQ;EACJ,OAAO;CACX;AACJ;AAEA,IAAIC,IAAoB;AAOxB,SAASnB,IAAkC;CACvC,IAAImB,GACA;CAEJ,IAAoB;CACpB,IAAMC,IAAQ,SAAS,cAAc,OAAO;CAW5C,AAVA,EAAM,cAAc,kgBAUpB,SAAS,KAAK,YAAYA,CAAK;AACnC"}
1
+ {"version":3,"file":"useLightbox-BigL4WLe.js","names":["onBeforeUnmount","ref","init_runtime_core_esm_bundler","init_reactivity_esm_bundler","shallowRef","loadCdnCss","PHOTOSWIPE_CSS","DEFAULT_IMAGE_SIZE","useLightbox","options","lightbox","gallery","injectPhotoSwipeOverrides","PhotoSwipeLightbox","openInNewTab","downloadable","ui","url","getCurrentSlideUrl","pswp","downloadImage","useImageSizes","sizes","image","images","img","downloadUrl","toDownloadUrl","anchor","getFilenameFromUrl","name","overridesInjected","style"],"sources":["../../../../packages/components/src/composables/useLightbox.ts"],"sourcesContent":["import {\n onBeforeUnmount,\n ref,\n shallowRef,\n type Ref,\n type ShallowRef,\n} from 'vue'\nimport type PhotoSwipeLightbox from 'photoswipe/lightbox'\nimport type PhotoSwipe from 'photoswipe'\nimport { loadCdnCss } from 'utils'\n\nconst PHOTOSWIPE_CSS =\n 'https://cdn.jsdelivr.net/npm/photoswipe@5/dist/photoswipe.css'\n\nconst DEFAULT_IMAGE_SIZE = { width: 1200, height: 800 }\n\nexport interface LightboxImage {\n url: string\n caption?: string\n alt?: string\n /** Natural width in px — used by PhotoSwipe for proper sizing. */\n width?: number\n /** Natural height in px — used by PhotoSwipe for proper sizing. */\n height?: number\n}\n\nexport interface LightboxOptions {\n /** Container element whose child anchors are the gallery items */\n gallery: Ref<HTMLElement | undefined>\n /** CSS selector for gallery items inside the container (default: `'a[data-pswp-src]'`) */\n children?: string\n loop?: boolean\n /** Show a download button in the lightbox toolbar */\n downloadable?: boolean\n /** Show an open-in-new-tab button in the lightbox toolbar */\n openInNewTab?: boolean\n}\n\nexport interface UseLightboxReturn {\n lightbox: ShallowRef<PhotoSwipeLightbox | null>\n /** Initialises PhotoSwipe. Call this inside `onMounted`. */\n init: () => Promise<void>\n}\n\n/**\n * Encapsulates PhotoSwipe 5 initialisation, toolbar customisation, and lifecycle cleanup.\n * CSS is injected into `document.head` so the overlay works in both regular DOM and Shadow DOM.\n *\n * Usage:\n * ```ts\n * const { init } = useLightbox({ gallery: galleryRef, downloadable: true })\n * onMounted(init)\n * ```\n */\nexport function useLightbox(options: LightboxOptions): UseLightboxReturn {\n const {\n gallery,\n children = 'a[data-pswp-src]',\n loop = true,\n downloadable = true,\n openInNewTab = true,\n } = options\n\n const lightbox = shallowRef<PhotoSwipeLightbox | null>(null)\n\n const init = async () => {\n if (!gallery.value) {\n return\n }\n\n // PhotoSwipe renders its overlay into document.body, so CSS must be in\n // document.head — not inside a shadow root.\n loadCdnCss(PHOTOSWIPE_CSS)\n injectPhotoSwipeOverrides()\n\n const { default: PhotoSwipeLightbox } =\n await import('photoswipe/lightbox')\n\n lightbox.value = new PhotoSwipeLightbox({\n gallery: gallery.value,\n children,\n pswpModule: () => import('photoswipe'),\n loop,\n arrowPrevSVG:\n '<svg aria-hidden=\"true\" class=\"pswp__icn\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\"><path fill=\"#ffffff\" d=\"m10.828 12l4.95 4.95l-1.414 1.415L8 12l6.364-6.364l1.414 1.414z\"/></svg>',\n arrowNextSVG:\n '<svg aria-hidden=\"true\" class=\"pswp__icn\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\"><path fill=\"#ffffff\" d=\"m13.172 12l-4.95-4.95l1.414-1.413L16 12l-6.364 6.364l-1.414-1.415z\"/></svg>',\n closeSVG:\n '<svg aria-hidden=\"true\" class=\"pswp__icn\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\"><path fill=\"#ffffff\" d=\"m12 10.587l4.95-4.95l1.414 1.414l-4.95 4.95l4.95 4.95l-1.415 1.414l-4.95-4.95l-4.949 4.95l-1.414-1.415l4.95-4.95l-4.95-4.95L7.05 5.638z\"/></svg>',\n zoomSVG:\n '<svg aria-hidden=\"true\" class=\"pswp__icn\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\"><g class=\"pswp__icn--zoom-in\"><path fill=\"#ffffff\" d=\"m18.031 16.617l4.283 4.282l-1.415 1.415l-4.282-4.283A8.96 8.96 0 0 1 11 20c-4.968 0-9-4.032-9-9s4.032-9 9-9s9 4.032 9 9a8.96 8.96 0 0 1-1.969 5.617m-2.006-.742A6.98 6.98 0 0 0 18 11c0-3.867-3.133-7-7-7s-7 3.133-7 7s3.133 7 7 7a6.98 6.98 0 0 0 4.875-1.975zM10 10V7h2v3h3v2h-3v3h-2v-3H7v-2z\"/></g><g class=\"pswp__icn--zoom-out\"><path fill=\"#ffffff\" d=\"m18.031 16.617l4.283 4.282l-1.415 1.415l-4.282-4.283A8.96 8.96 0 0 1 11 20c-4.968 0-9-4.032-9-9s4.032-9 9-9s9 4.032 9 9a8.96 8.96 0 0 1-1.969 5.617m-2.006-.742A6.98 6.98 0 0 0 18 11c0-3.867-3.133-7-7-7s-7 3.133-7 7s3.133 7 7 7a6.98 6.98 0 0 0 4.875-1.975zM7 10h8v2H7z\"/></g></svg>',\n })\n\n if (openInNewTab || downloadable) {\n lightbox.value.on('uiRegister', () => {\n const ui = lightbox.value!.pswp?.ui\n if (!ui) {\n return\n }\n\n if (openInNewTab) {\n ui.registerElement({\n name: 'open-in-new-tab-button',\n order: 8,\n isButton: true,\n html: '<svg aria-hidden=\"true\" class=\"pswp__icn\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\"><path fill=\"#ffffff\" d=\"M10 6v2H5v11h11v-5h2v6a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1zm11-3v8h-2V6.413l-7.793 7.794l-1.414-1.414L17.585 5H13V3z\"/></svg>',\n title: 'Open in new tab',\n onClick: (_, __, pswp) => {\n const url = getCurrentSlideUrl(pswp)\n if (url) {\n window.open(\n url,\n '_blank',\n 'noopener,noreferrer',\n )\n }\n },\n })\n }\n\n if (downloadable) {\n ui.registerElement({\n name: 'download-button',\n order: 9,\n isButton: true,\n html: '<svg aria-hidden=\"true\" class=\"pswp__icn\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\"><path fill=\"#ffffff\" d=\"M3 19h18v2H3zm10-5.828L19.071 7.1l1.414 1.414L12 17L3.515 8.515L4.929 7.1L11 13.173V2h2z\"/></svg>',\n title: 'Download',\n onClick: (_, __, pswp) => {\n const url = getCurrentSlideUrl(pswp)\n if (url) {\n downloadImage(url)\n }\n },\n })\n }\n })\n }\n\n lightbox.value.init()\n }\n\n onBeforeUnmount(() => {\n lightbox.value?.destroy()\n lightbox.value = null\n })\n\n return { lightbox, init }\n}\n\n// ---------------------------------------------------------------------------\n// Image size preloading\n// ---------------------------------------------------------------------------\n\nexport interface UseImageSizesReturn {\n preload: (\n images: Array<{ url: string; width?: number; height?: number }>,\n ) => void\n getSize: (url: string) => { width: number; height: number }\n}\n\n/**\n * Preloads natural image dimensions so PhotoSwipe can size its slides correctly.\n * When `width`/`height` are already provided they are used as-is;\n * otherwise the image is loaded in the background to read `naturalWidth`/`naturalHeight`.\n */\nexport function useImageSizes(): UseImageSizesReturn {\n const sizes = ref(new Map<string, { width: number; height: number }>())\n\n const preload = (\n images: Array<{ url: string; width?: number; height?: number }>,\n ) => {\n for (const image of images) {\n if (image.width && image.height) {\n sizes.value.set(image.url, {\n width: image.width,\n height: image.height,\n })\n continue\n }\n const img = new Image()\n img.onload = () => {\n sizes.value.set(image.url, {\n width: img.naturalWidth,\n height: img.naturalHeight,\n })\n }\n img.src = image.url\n }\n }\n\n const getSize = (url: string) => sizes.value.get(url) ?? DEFAULT_IMAGE_SIZE\n\n return { preload, getSize }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction getCurrentSlideUrl(pswp: PhotoSwipe): string | undefined {\n return (\n pswp.currSlide?.data?.src ??\n pswp.currSlide?.data?.element\n ?.querySelector('img')\n ?.getAttribute('src') ??\n pswp.currSlide?.data?.element\n ?.querySelector('source')\n ?.getAttribute('srcset') ??\n pswp.currSlide?.data?.element?.getAttribute('src') ??\n undefined\n )\n}\n\n/**\n * Triggers a client-side download for an image URL.\n *\n * For backend media URLs (.../media/:file/view), navigates to the\n * corresponding /download endpoint which redirects to an Azure SAS URL\n * with `Content-Disposition: attachment` — no CORS issues.\n *\n * For blob: URLs (in-session uploads), uses the fetch → blob approach.\n *\n * For data: URLs (inline SVGs, etc.), use the download attribute.\n *\n * Falls back to opening in a new tab for all other cases.\n */\nfunction downloadImage(url: string): void {\n const downloadUrl = toDownloadUrl(url)\n\n const anchor = document.createElement('a')\n anchor.href = downloadUrl\n anchor.target = '_blank'\n anchor.rel = 'noopener noreferrer'\n // `download` attribute works for same-origin, data: and blob: URLs; for\n // cross-origin it is ignored but the browser still follows Content-Disposition.\n anchor.download = getFilenameFromUrl(url)\n document.body.appendChild(anchor)\n anchor.click()\n document.body.removeChild(anchor)\n}\n\n/**\n * Converts a `/view` media URL to its `/download` counterpart.\n * Leaves blob:, data: and all other URLs untouched.\n */\nfunction toDownloadUrl(url: string): string {\n return url.replace(/\\/view(\\?|$)/, '/download$1')\n}\n\nfunction getFilenameFromUrl(url: string): string {\n if (url.startsWith('data:image/svg+xml')) {\n return 'diagram.svg'\n }\n if (url.startsWith('data:')) {\n const mime = url.split(':')[1].split(';')[0]\n const ext = mime.split('/')[1] || 'bin'\n return `image.${ext}`\n }\n try {\n const pathname = new URL(url).pathname\n const name = pathname.split('/').pop()\n return name && name.includes('.') ? name : 'image'\n } catch {\n return 'image'\n }\n}\n\nlet overridesInjected = false\n\n/**\n * Injects a one-time `<style>` into `document.head` that raises\n * PhotoSwipe's z-index above any host UI (e.g. floating chat widgets\n * that use `z-index: 2147483647`).\n */\nfunction injectPhotoSwipeOverrides(): void {\n if (overridesInjected) {\n return\n }\n overridesInjected = true\n const style = document.createElement('style')\n style.textContent = [\n '.pswp__counter { font-family: sans-serif; }',\n '.pswp { z-index: 2147483647 !important; }',\n '.pswp__icn { width: 20px; height: 20px; }',\n '.pswp__button { width: 40px; height: 40px; display: flex; align-items: center; justify-content: center; }',\n '.pswp__icn--zoom-out { display: none; }',\n '.pswp--zoomed-in .pswp__icn--zoom-in { display: none; }',\n '.pswp--zoomed-in .pswp__icn--zoom-out { display: block; }',\n '.pswp__button--arrow .pswp__icn {left: auto; right: auto; width: 40px; height: 40px; transform: none; margin-top: -20px; }',\n ].join(' ')\n document.head.appendChild(style)\n}\n"],"mappings":";;;;;AAWA,IAAMM,IACF,iEAEEC,IAAqB;CAAE,OAAO;CAAM,QAAQ;AAAI;AAwCtD,SAAgBC,EAAY,GAA6C;CACrE,IAAM,EACF,YACA,cAAW,oBACX,UAAO,IACP,kBAAe,IACf,kBAAe,OACfC,GAEEC,IAAWN,EAAsC,IAAI;CAmF3D,OALAJ,QAAsB;EAElB,AADAU,EAAS,OAAO,QAAQ,GACxB,EAAS,QAAQ;CACrB,CAAC,GAEM;EAAE;EAAU,kBAjFM;GACrB,IAAI,CAACC,EAAQ,OACT;GAMJ,AADAN,EAAWC,CAAc,GACzBM,EAA0B;GAE1B,IAAM,EAAE,SAASC,MACb,MAAM,OAAO;GA8DjB,AA5D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n, p as r, t as i, y as a } from "./Agent-CsSvagZw.js";
2
- import "./src-Bg96usAF.js";
2
+ import "./src-JJyCGvqH.js";
3
3
  import { n as o, t as s } from "./text-5F7L8EHi.js";
4
4
  // ../../packages/utils/src/message.ts
5
5
  function c(e) {
@@ -396,4 +396,4 @@ var ue = {
396
396
  }, fe = (e) => de[e.toLowerCase()] ?? 1.17, pe = (e) => ue[e.toLowerCase()] ?? `"${e.replace(/"/g, "")}", ${/roman|garamond|cambria|georgia|serif|book|times/i.test(e) ? "Georgia, serif" : "Calibri, Carlito, \"Segoe UI\", Arial, sans-serif"}`, me = (e, t) => t ? e.replace(RegExp(` \\(v${t}\\)(\\.\\w+)$`), "$1") : e;
397
397
  export { b as A, ee as B, R as C, N as D, E, fe as F, m as G, h as H, f as I, p as L, H as M, Q as N, ce as O, pe as P, g as R, Y as S, T, c as U, d as V, l as W, se as _, B as a, ie as b, ne as c, G as d, V as f, I as g, ae as h, q as i, z as j, _ as k, W as l, k as m, S as n, me as o, x as p, D as r, te as s, M as t, K as u, F as v, P as w, U as x, le as y, u as z };
398
398
 
399
- //# sourceMappingURL=utils-COV6n6VV.js.map
399
+ //# sourceMappingURL=utils-B5VcWm3g.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils-COV6n6VV.js","names":["isHostToolPart","WEB_SEARCH_TOOL_KEYS","MCP_TOOL_PREFIX","SUBAGENT_TOOL_PREFIX","API_TOOL_PREFIX","isPresentationTool","fromAnyCase","capitalizeFirstLetter","isTextPart","part","isToolPart","getToolPartName","isFilePart","getFilePartMedia","media","getFilePartTranscript","transcript","withAudioTranscripts","messages","own","updates","update","message","storedFileName","isReasoningPart","hasTextPart","getTextPart","parts","mergeConsecutiveTextParts","merged","prev","isWidgetPart","dropCorrectedWidgetErrors","lastDrawn","index","isStreamingPart","FILE_OUTPUT_PARTS","moveFileOutputsLast","files","feedPartKey","toolCallId","getHostCallPart","PAGE_TOOL_STEPS","HOST_STEP_TITLES","FORM_TOOL_STEP","pageToolStep","host","isHostActionPart","LIVE_REASONING_TAIL_LENGTH","FENCE_LINE","getMarkdownTail","markdown","maxLength","from","limit","boundary","length","cut","openFence","match","marker","rest","TOOL_APPROVAL_STATES","isToolApprovalPart","CONFIRM_TOOL_NAME","isToolConfirmPart","isConfirmationCardPart","getToolApprovalId","getPartState","getContrast","hex","hexcolor","char","r","g","b","linearize","c","isAchromaticColor","channels","at","resolveContrastColor","textColor","mainColor","agentThemeStyle","contrastColor","formatDuration","ms","$n","stringifyPayload","value","json","hasPayload","formAnswerAsSpoken","input","answer","question","questionById","step","said","id","formStepOptions","option","formAnswerSlots","slots","output","steps","assign","list","WEB_SEARCH_TOOL_TYPES","key","RICH_DETAIL_TOOL_TYPES","hasRichToolDetail","asRecord","pickString","keys","record","getToolPartSummary","queries","valid","query","sheet","range","getPartIcon","TOOL_KEY_PREFIXES","toolLabel","te","name","prefix","p","bare","PART_TYPE_LABELS","t","getPartTypeLabel","translator","label","localizeSummaryLabels","summary","labels","colon","getToolPartLabel","live","hostStepTitles","page","$t","WORD_FONT_STACKS","WORD_LINE_FACTORS","wordLineFactor","font","wordFontStack","chatFileName","version","filename"],"sources":["../../../../packages/utils/src/message.ts","../../../../packages/components/src/chat/utils.ts"],"sourcesContent":["import type { UIMessage } from 'ai'\nimport type { ChatAudioTranscript, MediaSource, UIChatMessage } from 'models'\n\ntype MessagePart = UIMessage['parts'][number]\n\nexport function isTextPart(\n part?: MessagePart | null | undefined,\n): part is Extract<MessagePart, { type: 'text' }> {\n if (!part) {\n return false\n }\n return part.type === 'text'\n}\n\nexport function isToolPart(\n part?: MessagePart | null | undefined,\n): part is Extract<MessagePart, { type: `tool-${string}` }> {\n if (!part) {\n return false\n }\n return part.type.startsWith('tool-')\n}\n\nexport function getToolPartName(part?: MessagePart): string {\n if (!isToolPart(part)) {\n return ''\n }\n return part.type.slice('tool-'.length)\n}\n\nexport function isFilePart(\n part?: MessagePart | null | undefined,\n): part is Extract<MessagePart, { type: 'file' }> {\n if (!part) {\n return false\n }\n return part.type === 'file'\n}\n\n/**\n * Returns the persisted `MediaSource` carried by a file part, when present.\n * Uploaded attachments stash the full upload metadata (size, extension,\n * storage handle…) under `providerMetadata['8bot'].media`, which survives\n * persistence — so saved messages can surface size/details without a schema\n * change or extra request.\n */\nexport function getFilePartMedia(\n part?: MessagePart | null | undefined,\n): MediaSource | undefined {\n if (!isFilePart(part)) {\n return undefined\n }\n const container = part.providerMetadata?.['8bot'] as\n { media?: unknown } | undefined\n const media = container?.media\n return media && typeof media === 'object' && !Array.isArray(media)\n ? (media as MediaSource)\n : undefined\n}\n\n/**\n * Returns the transcript a chat turn stamped on an audio file part, under\n * `providerMetadata['8bot'].transcript` (spec `audio-file-transcription.md`,\n * D4), when present.\n */\nexport function getFilePartTranscript(\n part?: MessagePart | null | undefined,\n): ChatAudioTranscript | undefined {\n if (!isFilePart(part)) {\n return undefined\n }\n const container = part.providerMetadata?.['8bot'] as\n { transcript?: unknown } | undefined\n const transcript = container?.transcript\n return transcript &&\n typeof transcript === 'object' &&\n !Array.isArray(transcript)\n ? (transcript as ChatAudioTranscript)\n : undefined\n}\n\n/** The transcript a turn made of one audio the client sent, as streamed. */\nexport interface AudioTranscriptUpdate {\n messageId: string\n storedFileName: string\n transcript: ChatAudioTranscript\n}\n\n/**\n * The messages with the transcripts a turn streamed (`data-audioTranscripts`)\n * stamped on their audio parts: the stored message has them, the client's\n * copy of the message it sent gets them here. What the updates do not name is\n * returned as it was, the same objects.\n */\nexport function withAudioTranscripts<T extends UIMessage>(\n messages: T[],\n updates: AudioTranscriptUpdate[],\n): T[] {\n return messages.map((message) => {\n const own = updates.filter((update) => update.messageId === message.id)\n if (own.length === 0) {\n return message\n }\n return {\n ...message,\n parts: message.parts.map((part) => {\n const update = own.find(\n ({ storedFileName }) =>\n storedFileName ===\n getFilePartMedia(part)?.storedFileName,\n )\n return update && isFilePart(part)\n ? {\n ...part,\n providerMetadata: {\n ...part.providerMetadata,\n '8bot': {\n ...part.providerMetadata?.['8bot'],\n transcript: update.transcript,\n },\n },\n }\n : part\n }),\n }\n })\n}\n\nexport function isReasoningPart(\n part?: MessagePart | null | undefined,\n): part is Extract<MessagePart, { type: 'reasoning' }> {\n if (!part) {\n return false\n }\n return part.type === 'reasoning'\n}\n\nexport function hasPartText(\n part?: MessagePart | null | undefined,\n): part is Extract<MessagePart, { text: string }> {\n if (!part) {\n return false\n }\n if (isTextPart(part)) {\n return true\n }\n return (\n 'text' in part &&\n part.text !== undefined &&\n part.text !== null &&\n part.text !== ''\n )\n}\n\nexport function hasTextPart(\n message?: UIMessage | UIChatMessage | null | undefined,\n): boolean {\n if (!message) {\n return false\n }\n return (message as UIMessage).parts.some((part) => isTextPart(part))\n}\n\nexport function getTextPart(\n message?: UIMessage | UIChatMessage | null | undefined,\n): string | undefined {\n if (!message) {\n return undefined\n }\n const parts = (message as UIMessage).parts\n if (!Array.isArray(parts)) {\n return undefined\n }\n const textPart = parts.find((part) => isTextPart(part))\n return textPart?.text\n}\n\nexport function getMessageText(\n message?: UIMessage | UIChatMessage | null | undefined,\n): string {\n if (!message) {\n return ''\n }\n const parts = (message as UIMessage).parts\n if (!Array.isArray(parts)) {\n return ''\n }\n return parts\n .filter((p): p is Extract<MessagePart, { type: 'text' }> =>\n isTextPart(p),\n )\n .map((p) => p.text)\n .join('')\n}\n","import type { UIMessage } from 'ai'\nimport type { InjectionKey, Ref } from 'vue'\nimport {\n API_TOOL_PREFIX,\n MCP_TOOL_PREFIX,\n SUBAGENT_TOOL_PREFIX,\n WEB_SEARCH_TOOL_KEYS,\n isHostToolPart,\n isPresentationTool,\n} from 'models'\nimport {\n isTextPart,\n isFilePart,\n isToolPart,\n isReasoningPart,\n hasPartText,\n hasTextPart,\n getTextPart,\n getMessageText,\n getToolPartName,\n capitalizeFirstLetter,\n fromAnyCase,\n} from 'utils'\n\nexport {\n isTextPart,\n isFilePart,\n isToolPart,\n isReasoningPart,\n hasPartText,\n hasTextPart,\n getTextPart,\n getMessageText,\n}\n\n/**\n * Merges consecutive text parts into a single text part.\n * Claude (and other models) often produce multiple text parts during streaming\n * that should logically be a single block of text.\n */\nexport function mergeConsecutiveTextParts(\n parts: UIMessage['parts'],\n): UIMessage['parts'] {\n const merged: UIMessage['parts'] = []\n for (const part of parts) {\n if (!isTextPart(part)) {\n merged.push(part)\n continue\n }\n const prev = merged[merged.length - 1]\n if (prev && isTextPart(prev)) {\n merged[merged.length - 1] = { ...prev, text: prev.text + part.text }\n } else {\n merged.push(part)\n }\n }\n return merged\n}\n\nconst isWidgetPart = (\n part: UIMessage['parts'][number],\n): part is Extract<UIMessage['parts'][number], { type: `tool-${string}` }> =>\n isToolPart(part) && isPresentationTool(getToolPartName(part))\n\n/**\n * Drops a widget call refused for its arguments when a later call of the same\n * widget in the message was drawn: the turn corrected it (the backend's\n * `correctableInputRefusals`), and the refusal would sit next to the working\n * widget, `showForm` drawing its render error above the form. A refusal with\n * nothing drawn after it stays. Only the feed reads this: the steps timeline\n * keeps every call, the refused one included.\n */\nexport function dropCorrectedWidgetErrors(\n parts: UIMessage['parts'],\n): UIMessage['parts'] {\n const lastDrawn = new Map<string, number>()\n for (const [index, part] of parts.entries()) {\n if (\n isWidgetPart(part) &&\n part.state !== 'output-error' &&\n !isStreamingPart(part)\n ) {\n lastDrawn.set(part.type, index)\n }\n }\n return parts.filter(\n (part, index) =>\n !(\n isWidgetPart(part) &&\n part.state === 'output-error' &&\n (lastDrawn.get(part.type) ?? -1) > index\n ),\n )\n}\n\n/**\n * Tool calls whose output is a file for the user to download. The feed draws\n * them after the answer, where the reader arrives, wherever in the message the\n * model made the call: a version written before a long answer sat above it,\n * out of sight.\n */\nconst FILE_OUTPUT_PARTS: ReadonlySet<string> = new Set([\n 'tool-editSpreadsheet',\n 'tool-shareDocument',\n 'tool-editWordDocument',\n 'tool-createSpreadsheet',\n 'tool-createWordDocument',\n])\n\n/** The parts with the file outputs moved last, in their own order. */\nexport function moveFileOutputsLast(\n parts: UIMessage['parts'],\n): UIMessage['parts'] {\n const files = parts.filter((part) => FILE_OUTPUT_PARTS.has(part.type))\n return files.length > 0\n ? [\n ...parts.filter((part) => !FILE_OUTPUT_PARTS.has(part.type)),\n ...files,\n ]\n : parts\n}\n\n/**\n * The key of a part in the feed. Its position, except for a file output: that\n * one is always last, so its position moves as the answer grows, and keyed by\n * it the card would be redrawn at every new part.\n */\nexport function feedPartKey(\n part: UIMessage['parts'][number],\n index: number,\n): string | number {\n const toolCallId = (part as { toolCallId?: string }).toolCallId\n return FILE_OUTPUT_PARTS.has(part.type) && toolCallId\n ? `file-${toolCallId}`\n : index\n}\n\n/** A call the embedding page runs, as the backend stamped it (spec `host-tools.md`). */\ninterface HostCallPart {\n toolCallId?: string\n toolName: string\n title?: string\n state?: string\n errorText?: string\n toolMetadata?: { readOnly?: boolean; provider?: 'app' | 'page' }\n}\n\nexport function getHostCallPart(\n part: UIMessage['parts'][number] | null | undefined,\n): HostCallPart | undefined {\n return isHostToolPart(part) ? (part as unknown as HostCallPart) : undefined\n}\n\n/**\n * The page tools of the widget (spec `page-tools.md`): defined by the backend,\n * so their step is ours to name, in the user's language. A tool the app\n * registered is named by its own `title`.\n */\nconst PAGE_TOOL_STEPS: Record<string, { icon: string; label: string }> = {\n page_snapshot: {\n icon: 'ri:pages-line',\n label: 'messagePart.pageTool.snapshot',\n },\n page_read: {\n icon: 'ri:file-text-line',\n label: 'messagePart.pageTool.read',\n },\n page_click: { icon: 'ri:cursor-line', label: 'messagePart.pageTool.click' },\n page_fill: { icon: 'ri:edit-line', label: 'messagePart.pageTool.fill' },\n page_scroll: {\n icon: 'ri:arrow-up-down-line',\n label: 'messagePart.pageTool.scroll',\n },\n page_find: { icon: 'ri:search-line', label: 'messagePart.pageTool.find' },\n page_wait: { icon: 'ri:time-line', label: 'messagePart.pageTool.wait' },\n page_hover: {\n icon: 'ri:cursor-line',\n label: 'messagePart.pageTool.hover',\n },\n page_press: {\n icon: 'ri:keyboard-line',\n label: 'messagePart.pageTool.press',\n },\n page_back: {\n icon: 'ri:arrow-go-back-line',\n label: 'messagePart.pageTool.back',\n },\n page_navigate: {\n icon: 'ri:links-line',\n label: 'messagePart.pageTool.navigate',\n },\n}\n\n/**\n * The titles the widget gave this page's steps, by call, naming what each\n * acts on (spec `page-tools-improvements.md`, M8): provided by the chat view\n * from its store, read by the views that list the steps.\n */\nexport const HOST_STEP_TITLES: InjectionKey<Ref<Record<string, string>>> =\n Symbol('hostStepTitles')\n\n/** A form the site annotated for agents: its tool is named `form_<toolname>`. */\nconst FORM_TOOL_STEP = {\n icon: 'ri:survey-line',\n label: 'messagePart.pageTool.form',\n}\n\nconst pageToolStep = (host: HostCallPart) =>\n host.toolMetadata?.provider === 'page'\n ? (PAGE_TOOL_STEPS[host.toolName] ??\n (host.toolName.startsWith('form_') ? FORM_TOOL_STEP : undefined))\n : undefined\n\n/**\n * A host call that changes something in the app or on the page: the feed\n * shows it even without the steps timeline, because what it did stays done.\n */\nexport function isHostActionPart(\n part: UIMessage['parts'][number] | null | undefined,\n): boolean {\n return getHostCallPart(part)?.toolMetadata?.readOnly === false\n}\n\nexport function isStreamingPart(\n part: UIMessage['parts'][number] | null | undefined,\n): part is Extract<UIMessage['parts'][number], { streaming?: boolean }> {\n if (!part) {\n return false\n }\n if ('state' in part) {\n return part.state === 'streaming' || part.state === 'input-streaming'\n }\n return false\n}\n\n/**\n * How much of a reasoning still being written its live box renders. The box is\n * a few lines tall and follows the bottom, while the reasoning of one turn runs\n * to tens of kilobytes: chat `st0Eg8iG0zUX0HQN` wrote 92KB, and parsing all of\n * it at every delta froze the tab. Four thousand characters leave a few screens\n * to scroll back through, and a finished step renders all of it.\n */\nexport const LIVE_REASONING_TAIL_LENGTH = 4000\n\n// A fence opener or closer, also inside a list item or a quote, whose markers\n// and indentation are skipped. The rest of the line tells them apart: a\n// closing fence carries no info string.\nconst FENCE_LINE =\n /^[ \\t]*(?:(?:[-*+]|\\d{1,9}[.)])[ \\t]+|>[ \\t]?)*(`{3,}|~{3,})(.*)$/gm\n\n/**\n * The end of a markdown text, at most `maxLength` characters long, cut on a\n * blank line (a line break when there is none) so it does not open on half a\n * paragraph. A table or a formula can still be cut in two. An ellipsis marks\n * the cut. A cut inside a fenced code block reopens the fence, or the rest of\n * the text would render as code and the code as prose.\n */\nexport function getMarkdownTail(markdown: string, maxLength: number): string {\n if (markdown.length <= maxLength) {\n return markdown\n }\n const from = markdown.length - maxLength\n // The boundary is looked for in the first half of the window only: the one\n // blank line of the window can be the last thing written, and cutting there\n // would leave nothing to render.\n const limit = from + maxLength / 2\n const boundary = (index: number, length: number) =>\n index !== -1 && index < limit ? index + length : undefined\n const cut =\n boundary(markdown.indexOf('\\n\\n', from), 2) ??\n boundary(markdown.indexOf('\\n', from), 1) ??\n from\n let openFence: string | undefined\n for (const match of markdown.matchAll(FENCE_LINE)) {\n if (match.index >= cut) {\n break\n }\n const [, marker, rest] = match\n if (!openFence) {\n // A backtick in a backtick fence's info string makes it inline\n // code, not a fence.\n if (marker[0] === '`' && rest.includes('`')) {\n continue\n }\n openFence = marker\n } else if (\n marker[0] === openFence[0] &&\n marker.length >= openFence.length &&\n !rest.trim()\n ) {\n openFence = undefined\n }\n }\n const reopen = openFence ? `${openFence}\\n` : ''\n return `…\\n\\n${reopen}${markdown.slice(cut)}`\n}\n\n/**\n * States a tool part goes through when it needs the user's approval. They are\n * rendered by `PkToolApprovalCard` whatever the tool is, so the decision (and\n * its outcome) stays visible in the transcript.\n */\nconst TOOL_APPROVAL_STATES = new Set([\n 'approval-requested',\n 'approval-responded',\n 'output-denied',\n])\n\nexport function isToolApprovalPart(\n part: UIMessage['parts'][number] | null | undefined,\n): boolean {\n if (!isToolPart(part)) {\n return false\n }\n if (TOOL_APPROVAL_STATES.has(part.state)) {\n return true\n }\n // An executed (or errored) call that went through the gate keeps its\n // verdict in `approval`: the card stays in the transcript, so the user's\n // decision remains visible in the chat and in the log viewers (parity\n // with requestConfirm, whose 'confirmed' output is persisted).\n return (part as { approval?: unknown }).approval != null\n}\n\n/**\n * The client-side tool the model uses to have an action it described approved.\n * It predates the SDK's approval gate and keeps its own round-trip (it resolves\n * through `addToolOutput`), but it asks the user the very same question, so it\n * shares `PkToolApprovalCard` instead of having a card of its own.\n */\nexport const CONFIRM_TOOL_NAME = 'requestConfirm'\n\nexport function isToolConfirmPart(\n part: UIMessage['parts'][number] | null | undefined,\n): boolean {\n return isToolPart(part) && part.type === `tool-${CONFIRM_TOOL_NAME}`\n}\n\n/** True for any part the confirmation card is responsible for. */\nexport function isConfirmationCardPart(\n part: UIMessage['parts'][number] | null | undefined,\n): boolean {\n return isToolApprovalPart(part) || isToolConfirmPart(part)\n}\n\n/** The id of the pending approval request on a tool part, if any. */\nexport function getToolApprovalId(\n part: UIMessage['parts'][number] | null | undefined,\n): string | undefined {\n if (!isToolPart(part)) {\n return undefined\n }\n return (part as { approval?: { id?: string } }).approval?.id\n}\n\nexport function getPartState(\n part: UIMessage['parts'][number] | null | undefined,\n): string | undefined {\n if (!part) {\n return undefined\n }\n if ('state' in part) {\n return part.state\n }\n return undefined\n}\n\nexport function isLoadingState(state?: string): boolean {\n if (!state) {\n return false\n }\n return ['streaming'].includes(state)\n}\n\nexport function getContrast(hexcolor: string = '000000'): 'black' | 'white' {\n let hex = hexcolor.replace('#', '')\n\n // Expand 3-character hex to 6-character (e.g., #ccc -> #cccccc)\n if (hex.length === 3) {\n hex = hex\n .split('')\n .map((char) => char + char)\n .join('')\n }\n\n // WCAG relative luminance\n const r = parseInt(hex.substring(0, 2), 16) / 255\n const g = parseInt(hex.substring(2, 4), 16) / 255\n const b = parseInt(hex.substring(4, 6), 16) / 255\n\n const linearize = (c: number) =>\n c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4\n\n const luminance =\n 0.2126 * linearize(r) + 0.7152 * linearize(g) + 0.0722 * linearize(b)\n\n return luminance > 0.179 ? 'black' : 'white'\n}\n\n/**\n * True for a hex color with almost no hue: black, white and the grays between.\n * Anything else, a color the function cannot read included, counts as colored.\n */\nexport function isAchromaticColor(hexcolor: string | undefined): boolean {\n let hex = hexcolor?.trim().replace('#', '') ?? ''\n if (/^[0-9a-f]{3}$/i.test(hex)) {\n hex = hex\n .split('')\n .map((char) => char + char)\n .join('')\n }\n if (!/^[0-9a-f]{6}$/i.test(hex)) {\n return false\n }\n const channels = [0, 2, 4].map((at) =>\n parseInt(hex.substring(at, at + 2), 16),\n )\n return Math.max(...channels) - Math.min(...channels) < 32\n}\n\n/**\n * Resolves the contrast color based on the user's `textColor` preference.\n * Falls back to WCAG auto-detection via `getContrast` when set to `'auto'` or `undefined`.\n */\nexport function resolveContrastColor(\n textColor: 'auto' | 'white' | 'black' | undefined,\n mainColor: string | undefined,\n): 'black' | 'white' {\n if (textColor === 'white' || textColor === 'black') {\n return textColor\n }\n return getContrast(mainColor)\n}\n\n/**\n * The style of a chat root (PkChatbot, the widget's shell): the agent's color\n * as the brand. Volver derives every role of the brand (graphic, readable,\n * contrast, tinted surface) on any element with `.theme`, which both roots\n * carry, so the focus ring, the primary buttons, the links and the checkboxes\n * take the agent's color with the contrast each theme needs, instead of the\n * platform's purple. The fields' focus takes the brand's graphic role in both\n * themes, since the dark theme's accent is the platform's too.\n */\nexport function agentThemeStyle(\n mainColor: string | undefined,\n contrastColor: 'black' | 'white',\n): Record<string, string> | undefined {\n if (!mainColor) {\n return undefined\n }\n return {\n '--chatbot-main-color': mainColor,\n '--chatbot-contrast-color': contrastColor,\n '--color-brand': mainColor,\n '--color-brand-contrast': contrastColor,\n '--input-focus-color': 'var(--color-brand-graphic)',\n }\n}\n\n/**\n * Formats a duration in milliseconds using the i18n `seconds` number format\n * (e.g. \"12,4 secondi\" / \"12.4 seconds\"). Returns undefined for durations\n * that would render as \"0 seconds\" (less than 0.05s).\n */\nexport function formatDuration(\n $n: (value: number, format: string) => string,\n ms?: number,\n): string | undefined {\n if (ms === undefined || ms < 50) {\n return undefined\n }\n return $n(ms / 1000, 'seconds')\n}\n\n/**\n * Stringifies a tool payload for the raw fallback view. Returns undefined for\n * empty values so the caller can skip rendering the block entirely.\n */\nexport function stringifyPayload(value: unknown): string | undefined {\n if (value === undefined) {\n return undefined\n }\n if (typeof value === 'string') {\n return value.trim() || undefined\n }\n try {\n const json = JSON.stringify(value, null, 2)\n return json === '{}' || json === '[]' ? undefined : json\n } catch {\n return undefined\n }\n}\n\n/**\n * True when a tool payload carries something worth rendering, so a caller can\n * skip the block without stringifying the value twice.\n */\nexport function hasPayload(value: unknown): boolean {\n return stringifyPayload(value) !== undefined\n}\n\n/**\n * Turns the answers of a form into the sentence the caller would have said.\n *\n * On a call the tool loop is over by the time the form is on screen, so the\n * answers go back to the agent as a user message (see `sendUserMessage` in\n * `useVoiceSession`). Each answer is paired with its question, because that is\n * how a person would say it and because the agent hears it with no widget\n * attached.\n */\nexport function formAnswerAsSpoken(\n part: unknown,\n answer: string | { answers: { id: string; value: unknown }[] },\n): string {\n const input = (\n part as {\n input?: {\n steps?: { id: string; question?: string }[]\n question?: string\n }\n }\n )?.input\n\n if (typeof answer === 'string') {\n const question = input?.question ?? input?.steps?.[0]?.question\n return question ? `${question} ${answer}` : answer\n }\n\n const questionById = new Map(\n (input?.steps ?? []).map((step) => [step.id, step.question]),\n )\n const lines = answer.answers\n .filter(\n ({ value }) =>\n value !== null &&\n value !== '' &&\n !(Array.isArray(value) && !value.length),\n )\n .map(({ id, value }) => {\n const said = Array.isArray(value) ? value.join(', ') : String(value)\n const question = questionById.get(id)\n return question ? `${question} ${said}` : said\n })\n\n return lines.join('. ')\n}\n\n/**\n * The choices of a form step, as the radio and checkbox editors take them.\n *\n * The `value` is the LABEL and not the position, because it is what travels\n * back to the model as the answer: it reads the words it wrote, not an index.\n * Nothing here caps the list, and nothing should: the number of options an\n * agent configures is advice to the model, so a step can legitimately carry\n * more (see `showForm.tool.ts`).\n */\nexport function formStepOptions(\n step: { options?: { label: string; description?: string }[] } | undefined,\n): { label: string; value: string; description?: string }[] {\n if (!step?.options) {\n return []\n }\n return step.options.map((option) => ({\n label: option.label,\n value: option.label,\n description: option.description,\n }))\n}\n\n/**\n * Spreads the answers a form comes back with onto one slot PER STEP.\n *\n * A form's answers travel paired with step ids, and the tool schema does not\n * enforce that those ids are unique: a `.refine()` there would refuse the whole\n * form over a duplicate, which is the failure the schema was just cured of (see\n * the gotchas entry \"A configurable cap does not belong in an inputSchema\").\n * So the duplicate has to be survivable here. Keyed by id, two steps sharing\n * one collapsed onto a single answer: the second question showed the first\n * one's reply, and submitting sent that reply twice. Keyed by position, each\n * step keeps its own.\n *\n * A duplicated id restores the same incoming value to every step claiming it,\n * which is as much as the payload allows: the ids are all it says.\n */\nexport function formAnswerSlots(\n steps: { id: string }[],\n output: unknown,\n): Record<number, unknown> {\n const slots: Record<number, unknown> = {}\n if (output === undefined || output === null) {\n return slots\n }\n // A legacy single-choice answer is the plain string, and it can only\n // belong to a single-step form.\n if (typeof output === 'string') {\n if (steps.length === 1) {\n slots[0] = output\n }\n return slots\n }\n const assign = (id: string, value: unknown) => {\n steps.forEach((step, index) => {\n if (step.id === id) {\n slots[index] = value\n }\n })\n }\n const list = (output as { answers?: unknown }).answers\n if (Array.isArray(list)) {\n for (const answer of list as { id?: unknown; value?: unknown }[]) {\n if (typeof answer?.id === 'string') {\n assign(answer.id, answer.value)\n }\n }\n return slots\n }\n // Forms answered on a platform channel (the Teams modal) come back as a\n // flat record keyed by step id.\n for (const [id, value] of Object.entries(\n output as Record<string, unknown>,\n )) {\n if (value !== undefined) {\n assign(id, value)\n }\n }\n return slots\n}\n\n// Web search tool part types, gateway and provider-native\nexport const WEB_SEARCH_TOOL_TYPES: string[] = WEB_SEARCH_TOOL_KEYS.map(\n (key) => `tool-${key}`,\n)\n\n// Tool part types with a dedicated rich rendering in PkChatbotStepToolDetail\nconst RICH_DETAIL_TOOL_TYPES = new Set([\n 'tool-searchInKnowledgeBase',\n 'tool-retrieveRevisedAnswers',\n 'tool-expandChunkContext',\n 'tool-readDocumentFile',\n 'tool-getWeather',\n 'tool-geocode',\n 'tool-recallUserMemory',\n 'tool-saveUserMemory',\n ...WEB_SEARCH_TOOL_TYPES,\n])\n\nexport function hasRichToolDetail(\n part?: UIMessage['parts'][number] | null,\n): boolean {\n return isToolPart(part) && RICH_DETAIL_TOOL_TYPES.has(part.type)\n}\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n value && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined\n\nconst pickString = (\n record: Record<string, unknown> | undefined,\n ...keys: string[]\n): string | undefined => {\n for (const key of keys) {\n const value = record?.[key]\n if (typeof value === 'string' && value.trim()) {\n return value\n }\n }\n return undefined\n}\n\n/**\n * Returns a short inline summary for a tool part (search queries, location,\n * document name, ...) to be shown next to the step label without expanding\n * the step body.\n */\nexport function getToolPartSummary(\n part?: UIMessage['parts'][number] | null,\n): string | undefined {\n if (!isToolPart(part)) {\n return undefined\n }\n const input = asRecord('input' in part ? part.input : undefined)\n const output = asRecord('output' in part ? part.output : undefined)\n if (\n part.type === 'tool-searchInKnowledgeBase' ||\n WEB_SEARCH_TOOL_TYPES.includes(part.type)\n ) {\n const queries = input?.queries\n if (Array.isArray(queries)) {\n const valid = queries.filter(\n (query): query is string =>\n typeof query === 'string' && Boolean(query.trim()),\n )\n return valid.length ? valid.join(' · ') : undefined\n }\n return pickString(input, 'query', 'objective')\n }\n if (part.type === 'tool-retrieveRevisedAnswers') {\n return pickString(input, 'query')\n }\n if (part.type === 'tool-getWeather') {\n return (\n pickString(output, 'location') ?? pickString(input, 'locationName')\n )\n }\n if (part.type === 'tool-geocode') {\n return pickString(input, 'locationName')\n }\n if (part.type === 'tool-expandChunkContext') {\n return pickString(output, 'documentName')\n }\n if (\n part.type === 'tool-readDocumentFile' ||\n part.type === 'tool-readChatAttachment' ||\n part.type === 'tool-sendChatFile' ||\n part.type === 'tool-shareDocument'\n ) {\n return pickString(output, 'name')\n }\n if (part.type === 'tool-readSpreadsheet') {\n const sheet = pickString(input, 'sheet')\n const range = pickString(input, 'range')\n return sheet && range ? `${sheet}!${range}` : sheet\n }\n if (part.type === 'tool-editSpreadsheet') {\n return pickString(output, 'filename')\n }\n if (part.type === 'tool-readWordDocument') {\n return pickString(input, 'search') ?? pickString(input, 'from')\n }\n if (part.type === 'tool-editWordDocument') {\n return pickString(output, 'filename')\n }\n if (\n part.type === 'tool-createSpreadsheet' ||\n part.type === 'tool-createWordDocument'\n ) {\n // The name the file got, or while the call runs the one asked for.\n return pickString(output, 'filename') ?? pickString(input, 'filename')\n }\n if (part.type === 'tool-querySpreadsheet') {\n // The file when the step asked for the schema; a query has no name.\n return pickString(output, 'file')\n }\n if (part.type === 'tool-recallUserMemory') {\n return pickString(input, 'query')\n }\n if (part.type === 'tool-saveUserMemory') {\n return pickString(input, 'content', 'query')\n }\n return undefined\n}\n\n// Get part icon\nexport function getPartIcon(\n part?: UIMessage['parts'][number] | null,\n): string | undefined {\n const host = getHostCallPart(part)\n if (host) {\n return pageToolStep(host)?.icon ?? 'ri:apps-line'\n }\n if (isToolPart(part)) {\n if (part.type.includes('tool-subagent')) {\n return 'ri:robot-2-line'\n }\n if (part.type === 'tool-runWorker') {\n return 'ri:flow-chart'\n }\n if (part.type === 'tool-scheduleWakeup') {\n return 'ri:alarm-line'\n }\n if (part.type === 'tool-fetchTeamsChannelHistory') {\n return 'ri:chat-history-line'\n }\n if (part.type === 'tool-readEarlierMessages') {\n return 'ri:history-line'\n }\n if (part.type === 'tool-readChatAttachment') {\n return 'ri:attachment-line'\n }\n if (part.type === 'tool-sendChatFile') {\n return 'ri:send-plane-line'\n }\n if (part.type === 'tool-enableTools') {\n return 'ri:toggle-line'\n }\n if (part.type.includes('tool-mcp')) {\n return 'mcp'\n }\n if (part.type === 'tool-retrieveRevisedAnswers') {\n return 'ri:file-edit-line'\n }\n if (part.type === 'tool-searchInKnowledgeBase') {\n return 'ri:search-line'\n }\n if (part.type === 'tool-expandChunkContext') {\n return 'ri:file-search-line'\n }\n if (part.type === 'tool-readDocumentFile') {\n return 'ri:file-text-line'\n }\n if (part.type === 'tool-readSpreadsheet') {\n return 'ri:table-line'\n }\n if (\n part.type === 'tool-editSpreadsheet' ||\n part.type === 'tool-createSpreadsheet'\n ) {\n return 'ri:file-excel-2-line'\n }\n if (part.type === 'tool-shareDocument') {\n return 'ri:file-download-line'\n }\n if (part.type === 'tool-readWordDocument') {\n return 'ri:file-text-line'\n }\n if (\n part.type === 'tool-editWordDocument' ||\n part.type === 'tool-createWordDocument'\n ) {\n return 'ri:file-word-2-line'\n }\n if (part.type === 'tool-querySpreadsheet') {\n return 'ri:database-2-line'\n }\n if (part.type === 'tool-geocode') {\n return 'ri:map-2-line'\n }\n if (part.type === 'tool-getWeather') {\n return 'ri:sun-cloudy-line'\n }\n if (part.type === 'tool-recallUserMemory') {\n return 'ri:brain-line'\n }\n if (part.type === 'tool-saveUserMemory') {\n return 'ri:save-3-line'\n }\n if (part.type === 'tool-showWeather') {\n return 'ri:sun-line'\n }\n if (part.type === 'tool-showDiagram') {\n return 'ri:flow-chart'\n }\n if (part.type === 'tool-showSources') {\n return 'ri:book-2-line'\n }\n if (part.type === 'tool-showForm') {\n return 'ri:survey-line'\n }\n if (part.type === 'tool-showMultipleChoice') {\n return 'ri:checkbox-multiple-line'\n }\n if (part.type === 'tool-showArtifact') {\n return 'ri:file-code-line'\n }\n if (part.type === 'tool-showEmail') {\n return 'ri:mail-line'\n }\n if (part.type === 'tool-showMessage') {\n return 'ri:chat-1-line'\n }\n if (part.type === 'tool-showWebPages') {\n return 'ri:pages-line'\n }\n if (part.type === 'tool-showProductList') {\n return 'ri:shopping-bag-line'\n }\n if (part.type === 'tool-showContactForm') {\n return 'ri:send-plane-2-line'\n }\n if (part.type === 'tool-showCalendarEvent') {\n return 'ri:calendar-event-line'\n }\n if (part.type === 'tool-showComparison') {\n return 'ri:scales-line'\n }\n if (part.type === 'tool-showLocation') {\n return 'ri:map-pin-line'\n }\n if (part.type === 'tool-showQrCode') {\n return 'ri:qr-code-line'\n }\n if (part.type === 'tool-showImageGallery') {\n return 'ri:image-line'\n }\n if (part.type === 'tool-showVideo') {\n return 'ri:film-line'\n }\n if (part.type === 'tool-showSuggestedReply') {\n return 'ri:corner-down-right-line'\n }\n if (part.type === 'tool-requestGeolocation') {\n return 'ri:map-pin-user-line'\n }\n if (part.type === 'tool-disconnectOAuthConnection') {\n return 'ri:link-unlink'\n }\n if (part.type === 'tool-requestAccountLink') {\n return 'ri:link'\n }\n if (part.type === 'tool-unlinkAccount') {\n return 'ri:link-unlink'\n }\n if (WEB_SEARCH_TOOL_TYPES.includes(part.type)) {\n return 'ri:global-line'\n }\n return 'ri:tools-line'\n }\n if (isReasoningPart(part)) {\n return 'ri:lightbulb-line'\n }\n if (isTextPart(part)) {\n return 'ri:double-quotes-r'\n }\n return undefined\n}\n\n/** What `toolLabel` and `getPartTypeLabel` need from vue-i18n. */\nexport interface LabelTranslator {\n t: (key: string) => string\n te: (key: string) => boolean\n}\n\nconst TOOL_KEY_PREFIXES = [\n API_TOOL_PREFIX,\n MCP_TOOL_PREFIX,\n SUBAGENT_TOOL_PREFIX,\n] as const\n\n/**\n * The name a person reads for a tool of the turn: the translated label of a\n * built-in tool, otherwise the name the agent configured, without its\n * tool-set prefix and in words (`api-festivita_nazionali` reads \"Festivita\n * nazionali\"). Never the raw key, and never an i18n key with no translation,\n * which vue-i18n would print as the key itself.\n */\nexport function toolLabel(name: string, { t, te }: LabelTranslator): string {\n if (te(`agent.tool.${name}`)) {\n return t(`agent.tool.${name}`)\n }\n const prefix = TOOL_KEY_PREFIXES.find((p) => name.startsWith(p))\n const bare = prefix ? name.slice(prefix.length) : name\n return capitalizeFirstLetter(fromAnyCase(bare).trim().toLowerCase())\n}\n\n/**\n * The kinds of message part a person can meet, each with its label. Written\n * as literal keys so the widget's library build, which keeps only the keys it\n * finds written out (apps/web-component/vite-plugins/chatLocales.ts), ships\n * them too.\n */\nconst PART_TYPE_LABELS: Record<string, (t: LabelTranslator['t']) => string> = {\n custom: (t) => t('messagePart.type.custom'),\n data: (t) => t('messagePart.type.data'),\n file: (t) => t('messagePart.type.file'),\n reasoning: (t) => t('messagePart.type.reasoning'),\n 'source-document': (t) => t('messagePart.type.sourceDocument'),\n 'source-url': (t) => t('messagePart.type.sourceUrl'),\n 'step-start': (t) => t('messagePart.type.stepStart'),\n text: (t) => t('messagePart.type.text'),\n}\n\n/**\n * The label of a message part in the message details: the tool for a tool\n * call, the translated kind otherwise (text, reasoning, provider data...),\n * and the kind in words for one the catalog does not know yet.\n */\nexport function getPartTypeLabel(\n part: UIMessage['parts'][number],\n translator: LabelTranslator,\n): string {\n if (isToolPart(part)) {\n return toolLabel(getToolPartName(part), translator)\n }\n if (part.type === 'dynamic-tool') {\n return toolLabel(part.toolName, translator)\n }\n const kind = part.type.startsWith('data-') ? 'data' : part.type\n const label = PART_TYPE_LABELS[kind]\n return label\n ? label(translator.t)\n : capitalizeFirstLetter(fromAnyCase(part.type))\n}\n\n/**\n * The commercial name of a provider the gateway routed a turn through, from\n * its slug (`anthropic`, `bedrock`): proper nouns, so no translation. A slug\n * not listed here shows with a capital, never as the bare id.\n */\nconst PROVIDER_NAMES: Record<string, string> = {\n alibaba: 'Alibaba Cloud',\n anthropic: 'Anthropic',\n azure: 'Microsoft Azure',\n baseten: 'Baseten',\n bedrock: 'Amazon Bedrock',\n cerebras: 'Cerebras',\n cohere: 'Cohere',\n deepinfra: 'DeepInfra',\n deepseek: 'DeepSeek',\n fireworks: 'Fireworks AI',\n google: 'Google',\n groq: 'Groq',\n mistral: 'Mistral AI',\n moonshotai: 'Moonshot AI',\n openai: 'OpenAI',\n perplexity: 'Perplexity',\n togetherai: 'Together AI',\n vertex: 'Google Vertex AI',\n xai: 'xAI',\n zai: 'Z.ai',\n}\n\n/** The name of a provider slug, see `PROVIDER_NAMES`. */\nexport function providerLabel(slug: string): string {\n return (\n PROVIDER_NAMES[slug.toLowerCase()] ??\n capitalizeFirstLetter(fromAnyCase(slug))\n )\n}\n\n/**\n * The conversation summary in the reader's language. The analysis asks the\n * model for four bold labels (`SUMMARY_FORMAT` in\n * apps/backend/src/prompts/analysis.prompt.ts) and the model copies them in\n * English whatever the conversation's language, so every stored summary\n * holds them: they are translated where a summary is read. An empty summary\n * comes back as it is, so a `??` fallback after it still works.\n */\nexport function localizeSummaryLabels<T extends string | null | undefined>(\n summary: T,\n t: (key: string) => string,\n): T {\n if (!summary) {\n return summary\n }\n const labels: Record<string, string> = {\n Intent: t('conversationSummary.intent'),\n 'Topics covered': t('conversationSummary.topicsCovered'),\n 'Key facts': t('conversationSummary.keyFacts'),\n 'Open questions': t('conversationSummary.openQuestions'),\n }\n return summary.replace(\n /\\*\\*(Intent|Topics covered|Key facts|Open questions)(:?)\\*\\*/g,\n (_, label: string, colon: string) => `**${labels[label]}${colon}**`,\n ) as T\n}\n\n// Get part label\nexport function getToolPartLabel(\n $t: (key: string) => string,\n part?: UIMessage['parts'][number] | null,\n /** The live titles of the page's steps, by call: they win when present. */\n hostStepTitles?: Record<string, string>,\n): string | undefined {\n const host = getHostCallPart(part)\n if (host) {\n const live = host.toolCallId\n ? hostStepTitles?.[host.toolCallId]\n : undefined\n if (live) {\n return live\n }\n const page = pageToolStep(host)\n return page ? $t(page.label) : host.title || host.toolName\n }\n if (isToolPart(part)) {\n if (part.type.includes('tool-subagent')) {\n return $t(`messagePart.runSubagent`)\n }\n if (part.type === 'tool-runWorker') {\n return $t(`messagePart.runWorker`)\n }\n if (part.type === 'tool-scheduleWakeup') {\n return $t(`messagePart.scheduleWakeup`)\n }\n if (part.type === 'tool-fetchTeamsChannelHistory') {\n return $t(`messagePart.fetchTeamsChannelHistory`)\n }\n if (part.type === 'tool-readEarlierMessages') {\n return $t(`messagePart.readEarlierMessages`)\n }\n if (part.type === 'tool-readChatAttachment') {\n return $t(`messagePart.readChatAttachment`)\n }\n if (part.type === 'tool-sendChatFile') {\n return $t(`messagePart.sendChatFile`)\n }\n if (part.type === 'tool-enableTools') {\n return $t(`messagePart.enableTools`)\n }\n if (part.type === 'tool-retrieveRevisedAnswers') {\n return $t(`messagePart.revisedAnswers`)\n }\n if (part.type === 'tool-searchInKnowledgeBase') {\n return $t(`messagePart.searchingDocuments`)\n }\n if (part.type === 'tool-expandChunkContext') {\n return $t(`messagePart.expandChunkContext`)\n }\n if (part.type === 'tool-readDocumentFile') {\n return $t(`messagePart.readDocumentFile`)\n }\n if (part.type === 'tool-readSpreadsheet') {\n return $t(`messagePart.readSpreadsheet`)\n }\n if (part.type === 'tool-editSpreadsheet') {\n return $t(`messagePart.editSpreadsheet`)\n }\n if (part.type === 'tool-shareDocument') {\n return $t(`messagePart.shareDocument`)\n }\n if (part.type === 'tool-readWordDocument') {\n return $t(`messagePart.readWordDocument`)\n }\n if (part.type === 'tool-editWordDocument') {\n return $t(`messagePart.editWordDocument`)\n }\n if (part.type === 'tool-createSpreadsheet') {\n return $t(`messagePart.createSpreadsheet`)\n }\n if (part.type === 'tool-createWordDocument') {\n return $t(`messagePart.createWordDocument`)\n }\n if (part.type === 'tool-querySpreadsheet') {\n return $t(`messagePart.querySpreadsheet`)\n }\n if (part.type === 'tool-geocode') {\n return $t(`messagePart.geocode`)\n }\n if (part.type === 'tool-getWeather') {\n return $t(`messagePart.getWeather`)\n }\n if (part.type === 'tool-recallUserMemory') {\n return $t(`messagePart.recallUserMemory`)\n }\n if (part.type === 'tool-saveUserMemory') {\n return $t(`messagePart.saveUserMemory`)\n }\n if (part.type === 'tool-showWeather') {\n return $t(`messagePart.showWeather`)\n }\n if (part.type === 'tool-showForm') {\n return $t(`messagePart.showForm`)\n }\n if (part.type === 'tool-showDiagram') {\n return $t(`messagePart.showDiagram`)\n }\n if (part.type === 'tool-showSources') {\n return $t(`messagePart.showSources`)\n }\n if (part.type === 'tool-showMultipleChoice') {\n return $t(`messagePart.showMultipleChoice`)\n }\n if (part.type === 'tool-showArtifact') {\n return $t(`messagePart.showArtifact`)\n }\n if (part.type === 'tool-showEmail') {\n return $t(`messagePart.showEmail`)\n }\n if (part.type === 'tool-showMessage') {\n return $t(`messagePart.showMessage`)\n }\n if (part.type === 'tool-showWebPages') {\n return $t(`messagePart.showWebPages`)\n }\n if (part.type === 'tool-showProducts') {\n return $t(`messagePart.showProducts`)\n }\n if (part.type === 'tool-showContactForm') {\n return $t(`messagePart.showContactForm`)\n }\n if (part.type === 'tool-showCalendarEvent') {\n return $t(`messagePart.showCalendarEvent`)\n }\n if (part.type === 'tool-showComparison') {\n return $t(`messagePart.showComparison`)\n }\n if (part.type === 'tool-showLocation') {\n return $t(`messagePart.showLocation`)\n }\n if (part.type === 'tool-showQrCode') {\n return $t(`messagePart.showQrCode`)\n }\n if (part.type === 'tool-showImageGallery') {\n return $t(`messagePart.showImageGallery`)\n }\n if (part.type === 'tool-showVideo') {\n return $t(`messagePart.showVideo`)\n }\n if (part.type === 'tool-showSuggestedReply') {\n return $t(`messagePart.showSuggestedReply`)\n }\n if (part.type === 'tool-requestGeolocation') {\n return $t(`messagePart.requestGeolocation`)\n }\n if (part.type === 'tool-disconnectOAuthConnection') {\n return $t(`messagePart.disconnectOAuthConnection`)\n }\n if (part.type === 'tool-requestAccountLink') {\n return $t(`messagePart.requestAccountLink`)\n }\n if (part.type === 'tool-unlinkAccount') {\n return $t(`messagePart.unlinkAccount`)\n }\n if (WEB_SEARCH_TOOL_TYPES.includes(part.type)) {\n return $t(`messagePart.webSearch`)\n }\n return $t(`messagePart.tool`)\n }\n if (isReasoningPart(part)) {\n return $t(`messagePart.reasoning`)\n }\n return $t(`messagePart.streaming`)\n}\n\n/** The version of a file stored in the chat that a preview opens. */\nexport type ChatFilePreviewTarget = {\n kind: 'word' | 'spreadsheet'\n storedFileName: string\n /** The name of the file, not of its version. */\n filename: string\n version?: number\n /** The file all its versions belong to, as the agent names it. */\n fileId?: string\n}\n\n/**\n * How the viewer draws a Word document's tracked changes: marked as Word\n * marks them, as if accepted, or as before them.\n */\nexport type WordPreviewMode = 'markup' | 'accepted' | 'original'\n\n/**\n * The fonts that stand in for Office's where the reader's system lacks them:\n * the metric-compatible ones of Linux and Chrome OS first, so the lines break\n * where Word breaks them, then the closest common ones.\n */\nconst WORD_FONT_STACKS: Record<string, string> = {\n calibri: 'Calibri, Carlito, \"Segoe UI\", Arial, sans-serif',\n 'calibri light':\n '\"Calibri Light\", Calibri, Carlito, \"Segoe UI\", sans-serif',\n aptos: 'Aptos, Calibri, Carlito, \"Segoe UI\", Arial, sans-serif',\n 'aptos display': '\"Aptos Display\", Aptos, Calibri, Carlito, sans-serif',\n cambria: 'Cambria, Caladea, Georgia, serif',\n 'times new roman':\n '\"Times New Roman\", Tinos, \"Liberation Serif\", Times, serif',\n arial: 'Arial, Arimo, \"Liberation Sans\", Helvetica, sans-serif',\n helvetica: 'Helvetica, Arial, Arimo, sans-serif',\n 'courier new': '\"Courier New\", Cousine, \"Liberation Mono\", monospace',\n garamond: 'Garamond, \"EB Garamond\", Georgia, serif',\n georgia: 'Georgia, serif',\n verdana: 'Verdana, \"DejaVu Sans\", sans-serif',\n tahoma: 'Tahoma, Verdana, sans-serif',\n}\n\n/**\n * Word's single line as a multiple of the font size, from the font's ascent,\n * descent and line gap: the lines keep the height of the document's font\n * where another font stands in for it.\n */\nconst WORD_LINE_FACTORS: Record<string, number> = {\n calibri: 1.22,\n 'calibri light': 1.22,\n cambria: 1.17,\n 'times new roman': 1.15,\n arial: 1.15,\n helvetica: 1.15,\n 'courier new': 1.13,\n georgia: 1.14,\n verdana: 1.22,\n tahoma: 1.21,\n}\n\n/** Word's single line for a font a Word document names. */\nexport const wordLineFactor = (font: string): number =>\n WORD_LINE_FACTORS[font.toLowerCase()] ?? 1.17\n\n/** The CSS font stack for a font a Word document names. */\nexport const wordFontStack = (font: string): string =>\n WORD_FONT_STACKS[font.toLowerCase()] ??\n `\"${font.replace(/\"/g, '')}\", ${\n /roman|garamond|cambria|georgia|serif|book|times/i.test(font)\n ? 'Georgia, serif'\n : 'Calibri, Carlito, \"Segoe UI\", Arial, sans-serif'\n }`\n\n/** An earlier version of a file of the chat, for the agent to restore. */\nexport type ChatFileRestoreTarget = {\n /** The id the agent names the file with: the stored name of version 1. */\n fileId: string\n version: number\n filename: string\n}\n\n/**\n * The name of a file, not of its version: `listino (v2).xlsx` is version 2\n * of `listino.xlsx`.\n */\nexport const chatFileName = (filename: string, version?: number): string =>\n version\n ? filename.replace(new RegExp(` \\\\(v${version}\\\\)(\\\\.\\\\w+)$`), '$1')\n : filename\n"],"mappings":";;;;AAKA,SAAgBQ,EACZ,GAC8C;CAI9C,OAHKC,IAGEA,EAAK,SAAS,SAFV;AAGf;AAEA,SAAgBC,EACZ,GACwD;CAIxD,OAHKD,IAGEA,EAAK,KAAK,WAAW,OAAO,IAFxB;AAGf;AAEA,SAAgBE,EAAgB,GAA4B;CAIxD,OAHKD,EAAWD,CAAI,IAGbA,EAAK,KAAK,MAAM,CAAc,IAF1B;AAGf;AAEA,SAAgBG,EACZ,GAC8C;CAI9C,OAHKH,IAGEA,EAAK,SAAS,SAFV;AAGf;AASA,SAAgBI,EACZ,GACuB;CACvB,IAAI,CAACD,EAAWH,CAAI,GAChB;CAIJ,IAAMK,IAFYL,EAAK,mBAAmB,OAAA,EAEjB;CACzB,OAAOK,KAAS,OAAOA,KAAU,YAAY,CAAC,MAAM,QAAQA,CAAK,IAC1DA,IACD,KAAA;AACV;AAOA,SAAgBC,EACZ,GAC+B;CAC/B,IAAI,CAACH,EAAWH,CAAI,GAChB;CAIJ,IAAMO,IAFYP,EAAK,mBAAmB,OAAA,EAEZ;CAC9B,OAAOO,KACH,OAAOA,KAAe,YACtB,CAAC,MAAM,QAAQA,CAAU,IACtBA,IACD,KAAA;AACV;AAeA,SAAgBC,EACZ,GACA,GACG;CACH,OAAOC,EAAS,KAAK,MAAY;EAC7B,IAAMC,IAAMC,EAAQ,QAAQ,MAAWC,EAAO,cAAcC,EAAQ,EAAE;EAItE,OAHIH,EAAI,WAAW,IACRG,IAEJ;GACH,GAAGA;GACH,OAAOA,EAAQ,MAAM,KAAK,MAAS;IAC/B,IAAMD,IAAS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AAG,uBAAuB,IAE9BA,EAAG,uBAAuB;AACrC;AAwBA,IAAMC,KAA2C;CAC7C,SAAS;CACT,iBACI;CACJ,OAAO;CACP,iBAAiB;CACjB,SAAS;CACT,mBACI;CACJ,OAAO;CACP,WAAW;CACX,eAAe;CACf,UAAU;CACV,SAAS;CACT,SAAS;CACT,QAAQ;AACZ,GAOMC,KAA4C;CAC9C,SAAS;CACT,iBAAiB;CACjB,SAAS;CACT,mBAAmB;CACnB,OAAO;CACP,WAAW;CACX,eAAe;CACf,SAAS;CACT,SAAS;CACT,QAAQ;AACZ,GAGaC,MAAkB,MAC3BD,GAAkBE,EAAK,YAAY,MAAM,MAGhCC,MAAiB,MAC1BJ,GAAiBG,EAAK,YAAY,MAClC,IAAIA,EAAK,QAAQ,MAAM,EAAE,EAAE,KACvB,mDAAmD,KAAKA,CAAI,IACtD,mBACA,uDAeDE,MAAgB,GAAkB,MAC3CC,IACMC,EAAS,QAAY,OAAO,QAAQD,EAAQ,cAAc,GAAG,IAAI,IACjEC"}
1
+ {"version":3,"file":"utils-B5VcWm3g.js","names":["isHostToolPart","WEB_SEARCH_TOOL_KEYS","MCP_TOOL_PREFIX","SUBAGENT_TOOL_PREFIX","API_TOOL_PREFIX","isPresentationTool","fromAnyCase","capitalizeFirstLetter","isTextPart","part","isToolPart","getToolPartName","isFilePart","getFilePartMedia","media","getFilePartTranscript","transcript","withAudioTranscripts","messages","own","updates","update","message","storedFileName","isReasoningPart","hasTextPart","getTextPart","parts","mergeConsecutiveTextParts","merged","prev","isWidgetPart","dropCorrectedWidgetErrors","lastDrawn","index","isStreamingPart","FILE_OUTPUT_PARTS","moveFileOutputsLast","files","feedPartKey","toolCallId","getHostCallPart","PAGE_TOOL_STEPS","HOST_STEP_TITLES","FORM_TOOL_STEP","pageToolStep","host","isHostActionPart","LIVE_REASONING_TAIL_LENGTH","FENCE_LINE","getMarkdownTail","markdown","maxLength","from","limit","boundary","length","cut","openFence","match","marker","rest","TOOL_APPROVAL_STATES","isToolApprovalPart","CONFIRM_TOOL_NAME","isToolConfirmPart","isConfirmationCardPart","getToolApprovalId","getPartState","getContrast","hex","hexcolor","char","r","g","b","linearize","c","isAchromaticColor","channels","at","resolveContrastColor","textColor","mainColor","agentThemeStyle","contrastColor","formatDuration","ms","$n","stringifyPayload","value","json","hasPayload","formAnswerAsSpoken","input","answer","question","questionById","step","said","id","formStepOptions","option","formAnswerSlots","slots","output","steps","assign","list","WEB_SEARCH_TOOL_TYPES","key","RICH_DETAIL_TOOL_TYPES","hasRichToolDetail","asRecord","pickString","keys","record","getToolPartSummary","queries","valid","query","sheet","range","getPartIcon","TOOL_KEY_PREFIXES","toolLabel","te","name","prefix","p","bare","PART_TYPE_LABELS","t","getPartTypeLabel","translator","label","localizeSummaryLabels","summary","labels","colon","getToolPartLabel","live","hostStepTitles","page","$t","WORD_FONT_STACKS","WORD_LINE_FACTORS","wordLineFactor","font","wordFontStack","chatFileName","version","filename"],"sources":["../../../../packages/utils/src/message.ts","../../../../packages/components/src/chat/utils.ts"],"sourcesContent":["import type { UIMessage } from 'ai'\nimport type { ChatAudioTranscript, MediaSource, UIChatMessage } from 'models'\n\ntype MessagePart = UIMessage['parts'][number]\n\nexport function isTextPart(\n part?: MessagePart | null | undefined,\n): part is Extract<MessagePart, { type: 'text' }> {\n if (!part) {\n return false\n }\n return part.type === 'text'\n}\n\nexport function isToolPart(\n part?: MessagePart | null | undefined,\n): part is Extract<MessagePart, { type: `tool-${string}` }> {\n if (!part) {\n return false\n }\n return part.type.startsWith('tool-')\n}\n\nexport function getToolPartName(part?: MessagePart): string {\n if (!isToolPart(part)) {\n return ''\n }\n return part.type.slice('tool-'.length)\n}\n\nexport function isFilePart(\n part?: MessagePart | null | undefined,\n): part is Extract<MessagePart, { type: 'file' }> {\n if (!part) {\n return false\n }\n return part.type === 'file'\n}\n\n/**\n * Returns the persisted `MediaSource` carried by a file part, when present.\n * Uploaded attachments stash the full upload metadata (size, extension,\n * storage handle…) under `providerMetadata['8bot'].media`, which survives\n * persistence — so saved messages can surface size/details without a schema\n * change or extra request.\n */\nexport function getFilePartMedia(\n part?: MessagePart | null | undefined,\n): MediaSource | undefined {\n if (!isFilePart(part)) {\n return undefined\n }\n const container = part.providerMetadata?.['8bot'] as\n { media?: unknown } | undefined\n const media = container?.media\n return media && typeof media === 'object' && !Array.isArray(media)\n ? (media as MediaSource)\n : undefined\n}\n\n/**\n * Returns the transcript a chat turn stamped on an audio file part, under\n * `providerMetadata['8bot'].transcript` (spec `audio-file-transcription.md`,\n * D4), when present.\n */\nexport function getFilePartTranscript(\n part?: MessagePart | null | undefined,\n): ChatAudioTranscript | undefined {\n if (!isFilePart(part)) {\n return undefined\n }\n const container = part.providerMetadata?.['8bot'] as\n { transcript?: unknown } | undefined\n const transcript = container?.transcript\n return transcript &&\n typeof transcript === 'object' &&\n !Array.isArray(transcript)\n ? (transcript as ChatAudioTranscript)\n : undefined\n}\n\n/** The transcript a turn made of one audio the client sent, as streamed. */\nexport interface AudioTranscriptUpdate {\n messageId: string\n storedFileName: string\n transcript: ChatAudioTranscript\n}\n\n/**\n * The messages with the transcripts a turn streamed (`data-audioTranscripts`)\n * stamped on their audio parts: the stored message has them, the client's\n * copy of the message it sent gets them here. What the updates do not name is\n * returned as it was, the same objects.\n */\nexport function withAudioTranscripts<T extends UIMessage>(\n messages: T[],\n updates: AudioTranscriptUpdate[],\n): T[] {\n return messages.map((message) => {\n const own = updates.filter((update) => update.messageId === message.id)\n if (own.length === 0) {\n return message\n }\n return {\n ...message,\n parts: message.parts.map((part) => {\n const update = own.find(\n ({ storedFileName }) =>\n storedFileName ===\n getFilePartMedia(part)?.storedFileName,\n )\n return update && isFilePart(part)\n ? {\n ...part,\n providerMetadata: {\n ...part.providerMetadata,\n '8bot': {\n ...part.providerMetadata?.['8bot'],\n transcript: update.transcript,\n },\n },\n }\n : part\n }),\n }\n })\n}\n\nexport function isReasoningPart(\n part?: MessagePart | null | undefined,\n): part is Extract<MessagePart, { type: 'reasoning' }> {\n if (!part) {\n return false\n }\n return part.type === 'reasoning'\n}\n\nexport function hasPartText(\n part?: MessagePart | null | undefined,\n): part is Extract<MessagePart, { text: string }> {\n if (!part) {\n return false\n }\n if (isTextPart(part)) {\n return true\n }\n return (\n 'text' in part &&\n part.text !== undefined &&\n part.text !== null &&\n part.text !== ''\n )\n}\n\nexport function hasTextPart(\n message?: UIMessage | UIChatMessage | null | undefined,\n): boolean {\n if (!message) {\n return false\n }\n return (message as UIMessage).parts.some((part) => isTextPart(part))\n}\n\nexport function getTextPart(\n message?: UIMessage | UIChatMessage | null | undefined,\n): string | undefined {\n if (!message) {\n return undefined\n }\n const parts = (message as UIMessage).parts\n if (!Array.isArray(parts)) {\n return undefined\n }\n const textPart = parts.find((part) => isTextPart(part))\n return textPart?.text\n}\n\nexport function getMessageText(\n message?: UIMessage | UIChatMessage | null | undefined,\n): string {\n if (!message) {\n return ''\n }\n const parts = (message as UIMessage).parts\n if (!Array.isArray(parts)) {\n return ''\n }\n return parts\n .filter((p): p is Extract<MessagePart, { type: 'text' }> =>\n isTextPart(p),\n )\n .map((p) => p.text)\n .join('')\n}\n","import type { UIMessage } from 'ai'\nimport type { InjectionKey, Ref } from 'vue'\nimport {\n API_TOOL_PREFIX,\n MCP_TOOL_PREFIX,\n SUBAGENT_TOOL_PREFIX,\n WEB_SEARCH_TOOL_KEYS,\n isHostToolPart,\n isPresentationTool,\n} from 'models'\nimport {\n isTextPart,\n isFilePart,\n isToolPart,\n isReasoningPart,\n hasPartText,\n hasTextPart,\n getTextPart,\n getMessageText,\n getToolPartName,\n capitalizeFirstLetter,\n fromAnyCase,\n} from 'utils'\n\nexport {\n isTextPart,\n isFilePart,\n isToolPart,\n isReasoningPart,\n hasPartText,\n hasTextPart,\n getTextPart,\n getMessageText,\n}\n\n/**\n * Merges consecutive text parts into a single text part.\n * Claude (and other models) often produce multiple text parts during streaming\n * that should logically be a single block of text.\n */\nexport function mergeConsecutiveTextParts(\n parts: UIMessage['parts'],\n): UIMessage['parts'] {\n const merged: UIMessage['parts'] = []\n for (const part of parts) {\n if (!isTextPart(part)) {\n merged.push(part)\n continue\n }\n const prev = merged[merged.length - 1]\n if (prev && isTextPart(prev)) {\n merged[merged.length - 1] = { ...prev, text: prev.text + part.text }\n } else {\n merged.push(part)\n }\n }\n return merged\n}\n\nconst isWidgetPart = (\n part: UIMessage['parts'][number],\n): part is Extract<UIMessage['parts'][number], { type: `tool-${string}` }> =>\n isToolPart(part) && isPresentationTool(getToolPartName(part))\n\n/**\n * Drops a widget call refused for its arguments when a later call of the same\n * widget in the message was drawn: the turn corrected it (the backend's\n * `correctableInputRefusals`), and the refusal would sit next to the working\n * widget, `showForm` drawing its render error above the form. A refusal with\n * nothing drawn after it stays. Only the feed reads this: the steps timeline\n * keeps every call, the refused one included.\n */\nexport function dropCorrectedWidgetErrors(\n parts: UIMessage['parts'],\n): UIMessage['parts'] {\n const lastDrawn = new Map<string, number>()\n for (const [index, part] of parts.entries()) {\n if (\n isWidgetPart(part) &&\n part.state !== 'output-error' &&\n !isStreamingPart(part)\n ) {\n lastDrawn.set(part.type, index)\n }\n }\n return parts.filter(\n (part, index) =>\n !(\n isWidgetPart(part) &&\n part.state === 'output-error' &&\n (lastDrawn.get(part.type) ?? -1) > index\n ),\n )\n}\n\n/**\n * Tool calls whose output is a file for the user to download. The feed draws\n * them after the answer, where the reader arrives, wherever in the message the\n * model made the call: a version written before a long answer sat above it,\n * out of sight.\n */\nconst FILE_OUTPUT_PARTS: ReadonlySet<string> = new Set([\n 'tool-editSpreadsheet',\n 'tool-shareDocument',\n 'tool-editWordDocument',\n 'tool-createSpreadsheet',\n 'tool-createWordDocument',\n])\n\n/** The parts with the file outputs moved last, in their own order. */\nexport function moveFileOutputsLast(\n parts: UIMessage['parts'],\n): UIMessage['parts'] {\n const files = parts.filter((part) => FILE_OUTPUT_PARTS.has(part.type))\n return files.length > 0\n ? [\n ...parts.filter((part) => !FILE_OUTPUT_PARTS.has(part.type)),\n ...files,\n ]\n : parts\n}\n\n/**\n * The key of a part in the feed. Its position, except for a file output: that\n * one is always last, so its position moves as the answer grows, and keyed by\n * it the card would be redrawn at every new part.\n */\nexport function feedPartKey(\n part: UIMessage['parts'][number],\n index: number,\n): string | number {\n const toolCallId = (part as { toolCallId?: string }).toolCallId\n return FILE_OUTPUT_PARTS.has(part.type) && toolCallId\n ? `file-${toolCallId}`\n : index\n}\n\n/** A call the embedding page runs, as the backend stamped it (spec `host-tools.md`). */\ninterface HostCallPart {\n toolCallId?: string\n toolName: string\n title?: string\n state?: string\n errorText?: string\n toolMetadata?: { readOnly?: boolean; provider?: 'app' | 'page' }\n}\n\nexport function getHostCallPart(\n part: UIMessage['parts'][number] | null | undefined,\n): HostCallPart | undefined {\n return isHostToolPart(part) ? (part as unknown as HostCallPart) : undefined\n}\n\n/**\n * The page tools of the widget (spec `page-tools.md`): defined by the backend,\n * so their step is ours to name, in the user's language. A tool the app\n * registered is named by its own `title`.\n */\nconst PAGE_TOOL_STEPS: Record<string, { icon: string; label: string }> = {\n page_snapshot: {\n icon: 'ri:pages-line',\n label: 'messagePart.pageTool.snapshot',\n },\n page_read: {\n icon: 'ri:file-text-line',\n label: 'messagePart.pageTool.read',\n },\n page_click: { icon: 'ri:cursor-line', label: 'messagePart.pageTool.click' },\n page_fill: { icon: 'ri:edit-line', label: 'messagePart.pageTool.fill' },\n page_scroll: {\n icon: 'ri:arrow-up-down-line',\n label: 'messagePart.pageTool.scroll',\n },\n page_find: { icon: 'ri:search-line', label: 'messagePart.pageTool.find' },\n page_wait: { icon: 'ri:time-line', label: 'messagePart.pageTool.wait' },\n page_hover: {\n icon: 'ri:cursor-line',\n label: 'messagePart.pageTool.hover',\n },\n page_press: {\n icon: 'ri:keyboard-line',\n label: 'messagePart.pageTool.press',\n },\n page_back: {\n icon: 'ri:arrow-go-back-line',\n label: 'messagePart.pageTool.back',\n },\n page_navigate: {\n icon: 'ri:links-line',\n label: 'messagePart.pageTool.navigate',\n },\n}\n\n/**\n * The titles the widget gave this page's steps, by call, naming what each\n * acts on (spec `page-tools-improvements.md`, M8): provided by the chat view\n * from its store, read by the views that list the steps.\n */\nexport const HOST_STEP_TITLES: InjectionKey<Ref<Record<string, string>>> =\n Symbol('hostStepTitles')\n\n/** A form the site annotated for agents: its tool is named `form_<toolname>`. */\nconst FORM_TOOL_STEP = {\n icon: 'ri:survey-line',\n label: 'messagePart.pageTool.form',\n}\n\nconst pageToolStep = (host: HostCallPart) =>\n host.toolMetadata?.provider === 'page'\n ? (PAGE_TOOL_STEPS[host.toolName] ??\n (host.toolName.startsWith('form_') ? FORM_TOOL_STEP : undefined))\n : undefined\n\n/**\n * A host call that changes something in the app or on the page: the feed\n * shows it even without the steps timeline, because what it did stays done.\n */\nexport function isHostActionPart(\n part: UIMessage['parts'][number] | null | undefined,\n): boolean {\n return getHostCallPart(part)?.toolMetadata?.readOnly === false\n}\n\nexport function isStreamingPart(\n part: UIMessage['parts'][number] | null | undefined,\n): part is Extract<UIMessage['parts'][number], { streaming?: boolean }> {\n if (!part) {\n return false\n }\n if ('state' in part) {\n return part.state === 'streaming' || part.state === 'input-streaming'\n }\n return false\n}\n\n/**\n * How much of a reasoning still being written its live box renders. The box is\n * a few lines tall and follows the bottom, while the reasoning of one turn runs\n * to tens of kilobytes: chat `st0Eg8iG0zUX0HQN` wrote 92KB, and parsing all of\n * it at every delta froze the tab. Four thousand characters leave a few screens\n * to scroll back through, and a finished step renders all of it.\n */\nexport const LIVE_REASONING_TAIL_LENGTH = 4000\n\n// A fence opener or closer, also inside a list item or a quote, whose markers\n// and indentation are skipped. The rest of the line tells them apart: a\n// closing fence carries no info string.\nconst FENCE_LINE =\n /^[ \\t]*(?:(?:[-*+]|\\d{1,9}[.)])[ \\t]+|>[ \\t]?)*(`{3,}|~{3,})(.*)$/gm\n\n/**\n * The end of a markdown text, at most `maxLength` characters long, cut on a\n * blank line (a line break when there is none) so it does not open on half a\n * paragraph. A table or a formula can still be cut in two. An ellipsis marks\n * the cut. A cut inside a fenced code block reopens the fence, or the rest of\n * the text would render as code and the code as prose.\n */\nexport function getMarkdownTail(markdown: string, maxLength: number): string {\n if (markdown.length <= maxLength) {\n return markdown\n }\n const from = markdown.length - maxLength\n // The boundary is looked for in the first half of the window only: the one\n // blank line of the window can be the last thing written, and cutting there\n // would leave nothing to render.\n const limit = from + maxLength / 2\n const boundary = (index: number, length: number) =>\n index !== -1 && index < limit ? index + length : undefined\n const cut =\n boundary(markdown.indexOf('\\n\\n', from), 2) ??\n boundary(markdown.indexOf('\\n', from), 1) ??\n from\n let openFence: string | undefined\n for (const match of markdown.matchAll(FENCE_LINE)) {\n if (match.index >= cut) {\n break\n }\n const [, marker, rest] = match\n if (!openFence) {\n // A backtick in a backtick fence's info string makes it inline\n // code, not a fence.\n if (marker[0] === '`' && rest.includes('`')) {\n continue\n }\n openFence = marker\n } else if (\n marker[0] === openFence[0] &&\n marker.length >= openFence.length &&\n !rest.trim()\n ) {\n openFence = undefined\n }\n }\n const reopen = openFence ? `${openFence}\\n` : ''\n return `…\\n\\n${reopen}${markdown.slice(cut)}`\n}\n\n/**\n * States a tool part goes through when it needs the user's approval. They are\n * rendered by `PkToolApprovalCard` whatever the tool is, so the decision (and\n * its outcome) stays visible in the transcript.\n */\nconst TOOL_APPROVAL_STATES = new Set([\n 'approval-requested',\n 'approval-responded',\n 'output-denied',\n])\n\nexport function isToolApprovalPart(\n part: UIMessage['parts'][number] | null | undefined,\n): boolean {\n if (!isToolPart(part)) {\n return false\n }\n if (TOOL_APPROVAL_STATES.has(part.state)) {\n return true\n }\n // An executed (or errored) call that went through the gate keeps its\n // verdict in `approval`: the card stays in the transcript, so the user's\n // decision remains visible in the chat and in the log viewers (parity\n // with requestConfirm, whose 'confirmed' output is persisted).\n return (part as { approval?: unknown }).approval != null\n}\n\n/**\n * The client-side tool the model uses to have an action it described approved.\n * It predates the SDK's approval gate and keeps its own round-trip (it resolves\n * through `addToolOutput`), but it asks the user the very same question, so it\n * shares `PkToolApprovalCard` instead of having a card of its own.\n */\nexport const CONFIRM_TOOL_NAME = 'requestConfirm'\n\nexport function isToolConfirmPart(\n part: UIMessage['parts'][number] | null | undefined,\n): boolean {\n return isToolPart(part) && part.type === `tool-${CONFIRM_TOOL_NAME}`\n}\n\n/** True for any part the confirmation card is responsible for. */\nexport function isConfirmationCardPart(\n part: UIMessage['parts'][number] | null | undefined,\n): boolean {\n return isToolApprovalPart(part) || isToolConfirmPart(part)\n}\n\n/** The id of the pending approval request on a tool part, if any. */\nexport function getToolApprovalId(\n part: UIMessage['parts'][number] | null | undefined,\n): string | undefined {\n if (!isToolPart(part)) {\n return undefined\n }\n return (part as { approval?: { id?: string } }).approval?.id\n}\n\nexport function getPartState(\n part: UIMessage['parts'][number] | null | undefined,\n): string | undefined {\n if (!part) {\n return undefined\n }\n if ('state' in part) {\n return part.state\n }\n return undefined\n}\n\nexport function isLoadingState(state?: string): boolean {\n if (!state) {\n return false\n }\n return ['streaming'].includes(state)\n}\n\nexport function getContrast(hexcolor: string = '000000'): 'black' | 'white' {\n let hex = hexcolor.replace('#', '')\n\n // Expand 3-character hex to 6-character (e.g., #ccc -> #cccccc)\n if (hex.length === 3) {\n hex = hex\n .split('')\n .map((char) => char + char)\n .join('')\n }\n\n // WCAG relative luminance\n const r = parseInt(hex.substring(0, 2), 16) / 255\n const g = parseInt(hex.substring(2, 4), 16) / 255\n const b = parseInt(hex.substring(4, 6), 16) / 255\n\n const linearize = (c: number) =>\n c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4\n\n const luminance =\n 0.2126 * linearize(r) + 0.7152 * linearize(g) + 0.0722 * linearize(b)\n\n return luminance > 0.179 ? 'black' : 'white'\n}\n\n/**\n * True for a hex color with almost no hue: black, white and the grays between.\n * Anything else, a color the function cannot read included, counts as colored.\n */\nexport function isAchromaticColor(hexcolor: string | undefined): boolean {\n let hex = hexcolor?.trim().replace('#', '') ?? ''\n if (/^[0-9a-f]{3}$/i.test(hex)) {\n hex = hex\n .split('')\n .map((char) => char + char)\n .join('')\n }\n if (!/^[0-9a-f]{6}$/i.test(hex)) {\n return false\n }\n const channels = [0, 2, 4].map((at) =>\n parseInt(hex.substring(at, at + 2), 16),\n )\n return Math.max(...channels) - Math.min(...channels) < 32\n}\n\n/**\n * Resolves the contrast color based on the user's `textColor` preference.\n * Falls back to WCAG auto-detection via `getContrast` when set to `'auto'` or `undefined`.\n */\nexport function resolveContrastColor(\n textColor: 'auto' | 'white' | 'black' | undefined,\n mainColor: string | undefined,\n): 'black' | 'white' {\n if (textColor === 'white' || textColor === 'black') {\n return textColor\n }\n return getContrast(mainColor)\n}\n\n/**\n * The style of a chat root (PkChatbot, the widget's shell): the agent's color\n * as the brand. Volver derives every role of the brand (graphic, readable,\n * contrast, tinted surface) on any element with `.theme`, which both roots\n * carry, so the focus ring, the primary buttons, the links and the checkboxes\n * take the agent's color with the contrast each theme needs, instead of the\n * platform's purple. The fields' focus takes the brand's graphic role in both\n * themes, since the dark theme's accent is the platform's too.\n */\nexport function agentThemeStyle(\n mainColor: string | undefined,\n contrastColor: 'black' | 'white',\n): Record<string, string> | undefined {\n if (!mainColor) {\n return undefined\n }\n return {\n '--chatbot-main-color': mainColor,\n '--chatbot-contrast-color': contrastColor,\n '--color-brand': mainColor,\n '--color-brand-contrast': contrastColor,\n '--input-focus-color': 'var(--color-brand-graphic)',\n }\n}\n\n/**\n * Formats a duration in milliseconds using the i18n `seconds` number format\n * (e.g. \"12,4 secondi\" / \"12.4 seconds\"). Returns undefined for durations\n * that would render as \"0 seconds\" (less than 0.05s).\n */\nexport function formatDuration(\n $n: (value: number, format: string) => string,\n ms?: number,\n): string | undefined {\n if (ms === undefined || ms < 50) {\n return undefined\n }\n return $n(ms / 1000, 'seconds')\n}\n\n/**\n * Stringifies a tool payload for the raw fallback view. Returns undefined for\n * empty values so the caller can skip rendering the block entirely.\n */\nexport function stringifyPayload(value: unknown): string | undefined {\n if (value === undefined) {\n return undefined\n }\n if (typeof value === 'string') {\n return value.trim() || undefined\n }\n try {\n const json = JSON.stringify(value, null, 2)\n return json === '{}' || json === '[]' ? undefined : json\n } catch {\n return undefined\n }\n}\n\n/**\n * True when a tool payload carries something worth rendering, so a caller can\n * skip the block without stringifying the value twice.\n */\nexport function hasPayload(value: unknown): boolean {\n return stringifyPayload(value) !== undefined\n}\n\n/**\n * Turns the answers of a form into the sentence the caller would have said.\n *\n * On a call the tool loop is over by the time the form is on screen, so the\n * answers go back to the agent as a user message (see `sendUserMessage` in\n * `useVoiceSession`). Each answer is paired with its question, because that is\n * how a person would say it and because the agent hears it with no widget\n * attached.\n */\nexport function formAnswerAsSpoken(\n part: unknown,\n answer: string | { answers: { id: string; value: unknown }[] },\n): string {\n const input = (\n part as {\n input?: {\n steps?: { id: string; question?: string }[]\n question?: string\n }\n }\n )?.input\n\n if (typeof answer === 'string') {\n const question = input?.question ?? input?.steps?.[0]?.question\n return question ? `${question} ${answer}` : answer\n }\n\n const questionById = new Map(\n (input?.steps ?? []).map((step) => [step.id, step.question]),\n )\n const lines = answer.answers\n .filter(\n ({ value }) =>\n value !== null &&\n value !== '' &&\n !(Array.isArray(value) && !value.length),\n )\n .map(({ id, value }) => {\n const said = Array.isArray(value) ? value.join(', ') : String(value)\n const question = questionById.get(id)\n return question ? `${question} ${said}` : said\n })\n\n return lines.join('. ')\n}\n\n/**\n * The choices of a form step, as the radio and checkbox editors take them.\n *\n * The `value` is the LABEL and not the position, because it is what travels\n * back to the model as the answer: it reads the words it wrote, not an index.\n * Nothing here caps the list, and nothing should: the number of options an\n * agent configures is advice to the model, so a step can legitimately carry\n * more (see `showForm.tool.ts`).\n */\nexport function formStepOptions(\n step: { options?: { label: string; description?: string }[] } | undefined,\n): { label: string; value: string; description?: string }[] {\n if (!step?.options) {\n return []\n }\n return step.options.map((option) => ({\n label: option.label,\n value: option.label,\n description: option.description,\n }))\n}\n\n/**\n * Spreads the answers a form comes back with onto one slot PER STEP.\n *\n * A form's answers travel paired with step ids, and the tool schema does not\n * enforce that those ids are unique: a `.refine()` there would refuse the whole\n * form over a duplicate, which is the failure the schema was just cured of (see\n * the gotchas entry \"A configurable cap does not belong in an inputSchema\").\n * So the duplicate has to be survivable here. Keyed by id, two steps sharing\n * one collapsed onto a single answer: the second question showed the first\n * one's reply, and submitting sent that reply twice. Keyed by position, each\n * step keeps its own.\n *\n * A duplicated id restores the same incoming value to every step claiming it,\n * which is as much as the payload allows: the ids are all it says.\n */\nexport function formAnswerSlots(\n steps: { id: string }[],\n output: unknown,\n): Record<number, unknown> {\n const slots: Record<number, unknown> = {}\n if (output === undefined || output === null) {\n return slots\n }\n // A legacy single-choice answer is the plain string, and it can only\n // belong to a single-step form.\n if (typeof output === 'string') {\n if (steps.length === 1) {\n slots[0] = output\n }\n return slots\n }\n const assign = (id: string, value: unknown) => {\n steps.forEach((step, index) => {\n if (step.id === id) {\n slots[index] = value\n }\n })\n }\n const list = (output as { answers?: unknown }).answers\n if (Array.isArray(list)) {\n for (const answer of list as { id?: unknown; value?: unknown }[]) {\n if (typeof answer?.id === 'string') {\n assign(answer.id, answer.value)\n }\n }\n return slots\n }\n // Forms answered on a platform channel (the Teams modal) come back as a\n // flat record keyed by step id.\n for (const [id, value] of Object.entries(\n output as Record<string, unknown>,\n )) {\n if (value !== undefined) {\n assign(id, value)\n }\n }\n return slots\n}\n\n// Web search tool part types, gateway and provider-native\nexport const WEB_SEARCH_TOOL_TYPES: string[] = WEB_SEARCH_TOOL_KEYS.map(\n (key) => `tool-${key}`,\n)\n\n// Tool part types with a dedicated rich rendering in PkChatbotStepToolDetail\nconst RICH_DETAIL_TOOL_TYPES = new Set([\n 'tool-searchInKnowledgeBase',\n 'tool-retrieveRevisedAnswers',\n 'tool-expandChunkContext',\n 'tool-readDocumentFile',\n 'tool-getWeather',\n 'tool-geocode',\n 'tool-recallUserMemory',\n 'tool-saveUserMemory',\n ...WEB_SEARCH_TOOL_TYPES,\n])\n\nexport function hasRichToolDetail(\n part?: UIMessage['parts'][number] | null,\n): boolean {\n return isToolPart(part) && RICH_DETAIL_TOOL_TYPES.has(part.type)\n}\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n value && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined\n\nconst pickString = (\n record: Record<string, unknown> | undefined,\n ...keys: string[]\n): string | undefined => {\n for (const key of keys) {\n const value = record?.[key]\n if (typeof value === 'string' && value.trim()) {\n return value\n }\n }\n return undefined\n}\n\n/**\n * Returns a short inline summary for a tool part (search queries, location,\n * document name, ...) to be shown next to the step label without expanding\n * the step body.\n */\nexport function getToolPartSummary(\n part?: UIMessage['parts'][number] | null,\n): string | undefined {\n if (!isToolPart(part)) {\n return undefined\n }\n const input = asRecord('input' in part ? part.input : undefined)\n const output = asRecord('output' in part ? part.output : undefined)\n if (\n part.type === 'tool-searchInKnowledgeBase' ||\n WEB_SEARCH_TOOL_TYPES.includes(part.type)\n ) {\n const queries = input?.queries\n if (Array.isArray(queries)) {\n const valid = queries.filter(\n (query): query is string =>\n typeof query === 'string' && Boolean(query.trim()),\n )\n return valid.length ? valid.join(' · ') : undefined\n }\n return pickString(input, 'query', 'objective')\n }\n if (part.type === 'tool-retrieveRevisedAnswers') {\n return pickString(input, 'query')\n }\n if (part.type === 'tool-getWeather') {\n return (\n pickString(output, 'location') ?? pickString(input, 'locationName')\n )\n }\n if (part.type === 'tool-geocode') {\n return pickString(input, 'locationName')\n }\n if (part.type === 'tool-expandChunkContext') {\n return pickString(output, 'documentName')\n }\n if (\n part.type === 'tool-readDocumentFile' ||\n part.type === 'tool-readChatAttachment' ||\n part.type === 'tool-sendChatFile' ||\n part.type === 'tool-shareDocument'\n ) {\n return pickString(output, 'name')\n }\n if (part.type === 'tool-readSpreadsheet') {\n const sheet = pickString(input, 'sheet')\n const range = pickString(input, 'range')\n return sheet && range ? `${sheet}!${range}` : sheet\n }\n if (part.type === 'tool-editSpreadsheet') {\n return pickString(output, 'filename')\n }\n if (part.type === 'tool-readWordDocument') {\n return pickString(input, 'search') ?? pickString(input, 'from')\n }\n if (part.type === 'tool-editWordDocument') {\n return pickString(output, 'filename')\n }\n if (\n part.type === 'tool-createSpreadsheet' ||\n part.type === 'tool-createWordDocument'\n ) {\n // The name the file got, or while the call runs the one asked for.\n return pickString(output, 'filename') ?? pickString(input, 'filename')\n }\n if (part.type === 'tool-querySpreadsheet') {\n // The file when the step asked for the schema; a query has no name.\n return pickString(output, 'file')\n }\n if (part.type === 'tool-recallUserMemory') {\n return pickString(input, 'query')\n }\n if (part.type === 'tool-saveUserMemory') {\n return pickString(input, 'content', 'query')\n }\n return undefined\n}\n\n// Get part icon\nexport function getPartIcon(\n part?: UIMessage['parts'][number] | null,\n): string | undefined {\n const host = getHostCallPart(part)\n if (host) {\n return pageToolStep(host)?.icon ?? 'ri:apps-line'\n }\n if (isToolPart(part)) {\n if (part.type.includes('tool-subagent')) {\n return 'ri:robot-2-line'\n }\n if (part.type === 'tool-runWorker') {\n return 'ri:flow-chart'\n }\n if (part.type === 'tool-scheduleWakeup') {\n return 'ri:alarm-line'\n }\n if (part.type === 'tool-fetchTeamsChannelHistory') {\n return 'ri:chat-history-line'\n }\n if (part.type === 'tool-readEarlierMessages') {\n return 'ri:history-line'\n }\n if (part.type === 'tool-readChatAttachment') {\n return 'ri:attachment-line'\n }\n if (part.type === 'tool-sendChatFile') {\n return 'ri:send-plane-line'\n }\n if (part.type === 'tool-enableTools') {\n return 'ri:toggle-line'\n }\n if (part.type.includes('tool-mcp')) {\n return 'mcp'\n }\n if (part.type === 'tool-retrieveRevisedAnswers') {\n return 'ri:file-edit-line'\n }\n if (part.type === 'tool-searchInKnowledgeBase') {\n return 'ri:search-line'\n }\n if (part.type === 'tool-expandChunkContext') {\n return 'ri:file-search-line'\n }\n if (part.type === 'tool-readDocumentFile') {\n return 'ri:file-text-line'\n }\n if (part.type === 'tool-readSpreadsheet') {\n return 'ri:table-line'\n }\n if (\n part.type === 'tool-editSpreadsheet' ||\n part.type === 'tool-createSpreadsheet'\n ) {\n return 'ri:file-excel-2-line'\n }\n if (part.type === 'tool-shareDocument') {\n return 'ri:file-download-line'\n }\n if (part.type === 'tool-readWordDocument') {\n return 'ri:file-text-line'\n }\n if (\n part.type === 'tool-editWordDocument' ||\n part.type === 'tool-createWordDocument'\n ) {\n return 'ri:file-word-2-line'\n }\n if (part.type === 'tool-querySpreadsheet') {\n return 'ri:database-2-line'\n }\n if (part.type === 'tool-geocode') {\n return 'ri:map-2-line'\n }\n if (part.type === 'tool-getWeather') {\n return 'ri:sun-cloudy-line'\n }\n if (part.type === 'tool-recallUserMemory') {\n return 'ri:brain-line'\n }\n if (part.type === 'tool-saveUserMemory') {\n return 'ri:save-3-line'\n }\n if (part.type === 'tool-showWeather') {\n return 'ri:sun-line'\n }\n if (part.type === 'tool-showDiagram') {\n return 'ri:flow-chart'\n }\n if (part.type === 'tool-showSources') {\n return 'ri:book-2-line'\n }\n if (part.type === 'tool-showForm') {\n return 'ri:survey-line'\n }\n if (part.type === 'tool-showMultipleChoice') {\n return 'ri:checkbox-multiple-line'\n }\n if (part.type === 'tool-showArtifact') {\n return 'ri:file-code-line'\n }\n if (part.type === 'tool-showEmail') {\n return 'ri:mail-line'\n }\n if (part.type === 'tool-showMessage') {\n return 'ri:chat-1-line'\n }\n if (part.type === 'tool-showWebPages') {\n return 'ri:pages-line'\n }\n if (part.type === 'tool-showProductList') {\n return 'ri:shopping-bag-line'\n }\n if (part.type === 'tool-showContactForm') {\n return 'ri:send-plane-2-line'\n }\n if (part.type === 'tool-showCalendarEvent') {\n return 'ri:calendar-event-line'\n }\n if (part.type === 'tool-showComparison') {\n return 'ri:scales-line'\n }\n if (part.type === 'tool-showLocation') {\n return 'ri:map-pin-line'\n }\n if (part.type === 'tool-showQrCode') {\n return 'ri:qr-code-line'\n }\n if (part.type === 'tool-showImageGallery') {\n return 'ri:image-line'\n }\n if (part.type === 'tool-showVideo') {\n return 'ri:film-line'\n }\n if (part.type === 'tool-showSuggestedReply') {\n return 'ri:corner-down-right-line'\n }\n if (part.type === 'tool-requestGeolocation') {\n return 'ri:map-pin-user-line'\n }\n if (part.type === 'tool-disconnectOAuthConnection') {\n return 'ri:link-unlink'\n }\n if (part.type === 'tool-requestAccountLink') {\n return 'ri:link'\n }\n if (part.type === 'tool-unlinkAccount') {\n return 'ri:link-unlink'\n }\n if (WEB_SEARCH_TOOL_TYPES.includes(part.type)) {\n return 'ri:global-line'\n }\n return 'ri:tools-line'\n }\n if (isReasoningPart(part)) {\n return 'ri:lightbulb-line'\n }\n if (isTextPart(part)) {\n return 'ri:double-quotes-r'\n }\n return undefined\n}\n\n/** What `toolLabel` and `getPartTypeLabel` need from vue-i18n. */\nexport interface LabelTranslator {\n t: (key: string) => string\n te: (key: string) => boolean\n}\n\nconst TOOL_KEY_PREFIXES = [\n API_TOOL_PREFIX,\n MCP_TOOL_PREFIX,\n SUBAGENT_TOOL_PREFIX,\n] as const\n\n/**\n * The name a person reads for a tool of the turn: the translated label of a\n * built-in tool, otherwise the name the agent configured, without its\n * tool-set prefix and in words (`api-festivita_nazionali` reads \"Festivita\n * nazionali\"). Never the raw key, and never an i18n key with no translation,\n * which vue-i18n would print as the key itself.\n */\nexport function toolLabel(name: string, { t, te }: LabelTranslator): string {\n if (te(`agent.tool.${name}`)) {\n return t(`agent.tool.${name}`)\n }\n const prefix = TOOL_KEY_PREFIXES.find((p) => name.startsWith(p))\n const bare = prefix ? name.slice(prefix.length) : name\n return capitalizeFirstLetter(fromAnyCase(bare).trim().toLowerCase())\n}\n\n/**\n * The kinds of message part a person can meet, each with its label. Written\n * as literal keys so the widget's library build, which keeps only the keys it\n * finds written out (apps/web-component/vite-plugins/chatLocales.ts), ships\n * them too.\n */\nconst PART_TYPE_LABELS: Record<string, (t: LabelTranslator['t']) => string> = {\n custom: (t) => t('messagePart.type.custom'),\n data: (t) => t('messagePart.type.data'),\n file: (t) => t('messagePart.type.file'),\n reasoning: (t) => t('messagePart.type.reasoning'),\n 'source-document': (t) => t('messagePart.type.sourceDocument'),\n 'source-url': (t) => t('messagePart.type.sourceUrl'),\n 'step-start': (t) => t('messagePart.type.stepStart'),\n text: (t) => t('messagePart.type.text'),\n}\n\n/**\n * The label of a message part in the message details: the tool for a tool\n * call, the translated kind otherwise (text, reasoning, provider data...),\n * and the kind in words for one the catalog does not know yet.\n */\nexport function getPartTypeLabel(\n part: UIMessage['parts'][number],\n translator: LabelTranslator,\n): string {\n if (isToolPart(part)) {\n return toolLabel(getToolPartName(part), translator)\n }\n if (part.type === 'dynamic-tool') {\n return toolLabel(part.toolName, translator)\n }\n const kind = part.type.startsWith('data-') ? 'data' : part.type\n const label = PART_TYPE_LABELS[kind]\n return label\n ? label(translator.t)\n : capitalizeFirstLetter(fromAnyCase(part.type))\n}\n\n/**\n * The commercial name of a provider the gateway routed a turn through, from\n * its slug (`anthropic`, `bedrock`): proper nouns, so no translation. A slug\n * not listed here shows with a capital, never as the bare id.\n */\nconst PROVIDER_NAMES: Record<string, string> = {\n alibaba: 'Alibaba Cloud',\n anthropic: 'Anthropic',\n azure: 'Microsoft Azure',\n baseten: 'Baseten',\n bedrock: 'Amazon Bedrock',\n cerebras: 'Cerebras',\n cohere: 'Cohere',\n deepinfra: 'DeepInfra',\n deepseek: 'DeepSeek',\n fireworks: 'Fireworks AI',\n google: 'Google',\n groq: 'Groq',\n mistral: 'Mistral AI',\n moonshotai: 'Moonshot AI',\n openai: 'OpenAI',\n perplexity: 'Perplexity',\n togetherai: 'Together AI',\n vertex: 'Google Vertex AI',\n xai: 'xAI',\n zai: 'Z.ai',\n}\n\n/** The name of a provider slug, see `PROVIDER_NAMES`. */\nexport function providerLabel(slug: string): string {\n return (\n PROVIDER_NAMES[slug.toLowerCase()] ??\n capitalizeFirstLetter(fromAnyCase(slug))\n )\n}\n\n/**\n * The conversation summary in the reader's language. The analysis asks the\n * model for four bold labels (`SUMMARY_FORMAT` in\n * apps/backend/src/prompts/analysis.prompt.ts) and the model copies them in\n * English whatever the conversation's language, so every stored summary\n * holds them: they are translated where a summary is read. An empty summary\n * comes back as it is, so a `??` fallback after it still works.\n */\nexport function localizeSummaryLabels<T extends string | null | undefined>(\n summary: T,\n t: (key: string) => string,\n): T {\n if (!summary) {\n return summary\n }\n const labels: Record<string, string> = {\n Intent: t('conversationSummary.intent'),\n 'Topics covered': t('conversationSummary.topicsCovered'),\n 'Key facts': t('conversationSummary.keyFacts'),\n 'Open questions': t('conversationSummary.openQuestions'),\n }\n return summary.replace(\n /\\*\\*(Intent|Topics covered|Key facts|Open questions)(:?)\\*\\*/g,\n (_, label: string, colon: string) => `**${labels[label]}${colon}**`,\n ) as T\n}\n\n// Get part label\nexport function getToolPartLabel(\n $t: (key: string) => string,\n part?: UIMessage['parts'][number] | null,\n /** The live titles of the page's steps, by call: they win when present. */\n hostStepTitles?: Record<string, string>,\n): string | undefined {\n const host = getHostCallPart(part)\n if (host) {\n const live = host.toolCallId\n ? hostStepTitles?.[host.toolCallId]\n : undefined\n if (live) {\n return live\n }\n const page = pageToolStep(host)\n return page ? $t(page.label) : host.title || host.toolName\n }\n if (isToolPart(part)) {\n if (part.type.includes('tool-subagent')) {\n return $t(`messagePart.runSubagent`)\n }\n if (part.type === 'tool-runWorker') {\n return $t(`messagePart.runWorker`)\n }\n if (part.type === 'tool-scheduleWakeup') {\n return $t(`messagePart.scheduleWakeup`)\n }\n if (part.type === 'tool-fetchTeamsChannelHistory') {\n return $t(`messagePart.fetchTeamsChannelHistory`)\n }\n if (part.type === 'tool-readEarlierMessages') {\n return $t(`messagePart.readEarlierMessages`)\n }\n if (part.type === 'tool-readChatAttachment') {\n return $t(`messagePart.readChatAttachment`)\n }\n if (part.type === 'tool-sendChatFile') {\n return $t(`messagePart.sendChatFile`)\n }\n if (part.type === 'tool-enableTools') {\n return $t(`messagePart.enableTools`)\n }\n if (part.type === 'tool-retrieveRevisedAnswers') {\n return $t(`messagePart.revisedAnswers`)\n }\n if (part.type === 'tool-searchInKnowledgeBase') {\n return $t(`messagePart.searchingDocuments`)\n }\n if (part.type === 'tool-expandChunkContext') {\n return $t(`messagePart.expandChunkContext`)\n }\n if (part.type === 'tool-readDocumentFile') {\n return $t(`messagePart.readDocumentFile`)\n }\n if (part.type === 'tool-readSpreadsheet') {\n return $t(`messagePart.readSpreadsheet`)\n }\n if (part.type === 'tool-editSpreadsheet') {\n return $t(`messagePart.editSpreadsheet`)\n }\n if (part.type === 'tool-shareDocument') {\n return $t(`messagePart.shareDocument`)\n }\n if (part.type === 'tool-readWordDocument') {\n return $t(`messagePart.readWordDocument`)\n }\n if (part.type === 'tool-editWordDocument') {\n return $t(`messagePart.editWordDocument`)\n }\n if (part.type === 'tool-createSpreadsheet') {\n return $t(`messagePart.createSpreadsheet`)\n }\n if (part.type === 'tool-createWordDocument') {\n return $t(`messagePart.createWordDocument`)\n }\n if (part.type === 'tool-querySpreadsheet') {\n return $t(`messagePart.querySpreadsheet`)\n }\n if (part.type === 'tool-geocode') {\n return $t(`messagePart.geocode`)\n }\n if (part.type === 'tool-getWeather') {\n return $t(`messagePart.getWeather`)\n }\n if (part.type === 'tool-recallUserMemory') {\n return $t(`messagePart.recallUserMemory`)\n }\n if (part.type === 'tool-saveUserMemory') {\n return $t(`messagePart.saveUserMemory`)\n }\n if (part.type === 'tool-showWeather') {\n return $t(`messagePart.showWeather`)\n }\n if (part.type === 'tool-showForm') {\n return $t(`messagePart.showForm`)\n }\n if (part.type === 'tool-showDiagram') {\n return $t(`messagePart.showDiagram`)\n }\n if (part.type === 'tool-showSources') {\n return $t(`messagePart.showSources`)\n }\n if (part.type === 'tool-showMultipleChoice') {\n return $t(`messagePart.showMultipleChoice`)\n }\n if (part.type === 'tool-showArtifact') {\n return $t(`messagePart.showArtifact`)\n }\n if (part.type === 'tool-showEmail') {\n return $t(`messagePart.showEmail`)\n }\n if (part.type === 'tool-showMessage') {\n return $t(`messagePart.showMessage`)\n }\n if (part.type === 'tool-showWebPages') {\n return $t(`messagePart.showWebPages`)\n }\n if (part.type === 'tool-showProducts') {\n return $t(`messagePart.showProducts`)\n }\n if (part.type === 'tool-showContactForm') {\n return $t(`messagePart.showContactForm`)\n }\n if (part.type === 'tool-showCalendarEvent') {\n return $t(`messagePart.showCalendarEvent`)\n }\n if (part.type === 'tool-showComparison') {\n return $t(`messagePart.showComparison`)\n }\n if (part.type === 'tool-showLocation') {\n return $t(`messagePart.showLocation`)\n }\n if (part.type === 'tool-showQrCode') {\n return $t(`messagePart.showQrCode`)\n }\n if (part.type === 'tool-showImageGallery') {\n return $t(`messagePart.showImageGallery`)\n }\n if (part.type === 'tool-showVideo') {\n return $t(`messagePart.showVideo`)\n }\n if (part.type === 'tool-showSuggestedReply') {\n return $t(`messagePart.showSuggestedReply`)\n }\n if (part.type === 'tool-requestGeolocation') {\n return $t(`messagePart.requestGeolocation`)\n }\n if (part.type === 'tool-disconnectOAuthConnection') {\n return $t(`messagePart.disconnectOAuthConnection`)\n }\n if (part.type === 'tool-requestAccountLink') {\n return $t(`messagePart.requestAccountLink`)\n }\n if (part.type === 'tool-unlinkAccount') {\n return $t(`messagePart.unlinkAccount`)\n }\n if (WEB_SEARCH_TOOL_TYPES.includes(part.type)) {\n return $t(`messagePart.webSearch`)\n }\n return $t(`messagePart.tool`)\n }\n if (isReasoningPart(part)) {\n return $t(`messagePart.reasoning`)\n }\n return $t(`messagePart.streaming`)\n}\n\n/** The version of a file stored in the chat that a preview opens. */\nexport type ChatFilePreviewTarget = {\n kind: 'word' | 'spreadsheet'\n storedFileName: string\n /** The name of the file, not of its version. */\n filename: string\n version?: number\n /** The file all its versions belong to, as the agent names it. */\n fileId?: string\n}\n\n/**\n * How the viewer draws a Word document's tracked changes: marked as Word\n * marks them, as if accepted, or as before them.\n */\nexport type WordPreviewMode = 'markup' | 'accepted' | 'original'\n\n/**\n * The fonts that stand in for Office's where the reader's system lacks them:\n * the metric-compatible ones of Linux and Chrome OS first, so the lines break\n * where Word breaks them, then the closest common ones.\n */\nconst WORD_FONT_STACKS: Record<string, string> = {\n calibri: 'Calibri, Carlito, \"Segoe UI\", Arial, sans-serif',\n 'calibri light':\n '\"Calibri Light\", Calibri, Carlito, \"Segoe UI\", sans-serif',\n aptos: 'Aptos, Calibri, Carlito, \"Segoe UI\", Arial, sans-serif',\n 'aptos display': '\"Aptos Display\", Aptos, Calibri, Carlito, sans-serif',\n cambria: 'Cambria, Caladea, Georgia, serif',\n 'times new roman':\n '\"Times New Roman\", Tinos, \"Liberation Serif\", Times, serif',\n arial: 'Arial, Arimo, \"Liberation Sans\", Helvetica, sans-serif',\n helvetica: 'Helvetica, Arial, Arimo, sans-serif',\n 'courier new': '\"Courier New\", Cousine, \"Liberation Mono\", monospace',\n garamond: 'Garamond, \"EB Garamond\", Georgia, serif',\n georgia: 'Georgia, serif',\n verdana: 'Verdana, \"DejaVu Sans\", sans-serif',\n tahoma: 'Tahoma, Verdana, sans-serif',\n}\n\n/**\n * Word's single line as a multiple of the font size, from the font's ascent,\n * descent and line gap: the lines keep the height of the document's font\n * where another font stands in for it.\n */\nconst WORD_LINE_FACTORS: Record<string, number> = {\n calibri: 1.22,\n 'calibri light': 1.22,\n cambria: 1.17,\n 'times new roman': 1.15,\n arial: 1.15,\n helvetica: 1.15,\n 'courier new': 1.13,\n georgia: 1.14,\n verdana: 1.22,\n tahoma: 1.21,\n}\n\n/** Word's single line for a font a Word document names. */\nexport const wordLineFactor = (font: string): number =>\n WORD_LINE_FACTORS[font.toLowerCase()] ?? 1.17\n\n/** The CSS font stack for a font a Word document names. */\nexport const wordFontStack = (font: string): string =>\n WORD_FONT_STACKS[font.toLowerCase()] ??\n `\"${font.replace(/\"/g, '')}\", ${\n /roman|garamond|cambria|georgia|serif|book|times/i.test(font)\n ? 'Georgia, serif'\n : 'Calibri, Carlito, \"Segoe UI\", Arial, sans-serif'\n }`\n\n/** An earlier version of a file of the chat, for the agent to restore. */\nexport type ChatFileRestoreTarget = {\n /** The id the agent names the file with: the stored name of version 1. */\n fileId: string\n version: number\n filename: string\n}\n\n/**\n * The name of a file, not of its version: `listino (v2).xlsx` is version 2\n * of `listino.xlsx`.\n */\nexport const chatFileName = (filename: string, version?: number): string =>\n version\n ? filename.replace(new RegExp(` \\\\(v${version}\\\\)(\\\\.\\\\w+)$`), '$1')\n : filename\n"],"mappings":";;;;AAKA,SAAgBQ,EACZ,GAC8C;CAI9C,OAHKC,IAGEA,EAAK,SAAS,SAFV;AAGf;AAEA,SAAgBC,EACZ,GACwD;CAIxD,OAHKD,IAGEA,EAAK,KAAK,WAAW,OAAO,IAFxB;AAGf;AAEA,SAAgBE,EAAgB,GAA4B;CAIxD,OAHKD,EAAWD,CAAI,IAGbA,EAAK,KAAK,MAAM,CAAc,IAF1B;AAGf;AAEA,SAAgBG,EACZ,GAC8C;CAI9C,OAHKH,IAGEA,EAAK,SAAS,SAFV;AAGf;AASA,SAAgBI,EACZ,GACuB;CACvB,IAAI,CAACD,EAAWH,CAAI,GAChB;CAIJ,IAAMK,IAFYL,EAAK,mBAAmB,OAAA,EAEjB;CACzB,OAAOK,KAAS,OAAOA,KAAU,YAAY,CAAC,MAAM,QAAQA,CAAK,IAC1DA,IACD,KAAA;AACV;AAOA,SAAgBC,EACZ,GAC+B;CAC/B,IAAI,CAACH,EAAWH,CAAI,GAChB;CAIJ,IAAMO,IAFYP,EAAK,mBAAmB,OAAA,EAEZ;CAC9B,OAAOO,KACH,OAAOA,KAAe,YACtB,CAAC,MAAM,QAAQA,CAAU,IACtBA,IACD,KAAA;AACV;AAeA,SAAgBC,EACZ,GACA,GACG;CACH,OAAOC,EAAS,KAAK,MAAY;EAC7B,IAAMC,IAAMC,EAAQ,QAAQ,MAAWC,EAAO,cAAcC,EAAQ,EAAE;EAItE,OAHIH,EAAI,WAAW,IACRG,IAEJ;GACH,GAAGA;GACH,OAAOA,EAAQ,MAAM,KAAK,MAAS;IAC/B,IAAMD,IAASF,EAAI,MACd,EAAE,wBACCI,MACAV,EAAiBJ,CAAI,CAAC,EAAE,cAChC;IACA,OAAOY,KAAUT,EAAWH,CAAI,IAC1B;KACI,GAAGA;KACH,kB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