@8wave/ai-elements 0.126.0 → 0.127.0-beta.2
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.
- package/dist/_chunks/{Agent-DytagI8S.js → Agent-nB9V45mr.js} +354 -276
- package/dist/_chunks/Agent-nB9V45mr.js.map +1 -0
- package/dist/_chunks/{Document-BdWEd1tb.js → Document-Dm5GM40t.js} +7 -7
- package/dist/_chunks/{Document-BdWEd1tb.js.map → Document-Dm5GM40t.js.map} +1 -1
- package/dist/_chunks/{PkFilePreview-C3BxAdui.js → PkFilePreview-qTCDbut0.js} +3 -3
- package/dist/_chunks/{PkFilePreview-C3BxAdui.js.map → PkFilePreview-qTCDbut0.js.map} +1 -1
- package/dist/_chunks/{PkFilePreviewDialog-WAm7QSvT.js → PkFilePreviewDialog-m5d4zZDi.js} +2 -2
- package/dist/_chunks/{PkFilePreviewDialog-WAm7QSvT.js.map → PkFilePreviewDialog-m5d4zZDi.js.map} +1 -1
- package/dist/_chunks/{PkImageEditorDialog-DM-d0hCD.js → PkImageEditorDialog-aekpEqWD.js} +2 -2
- package/dist/_chunks/{PkImageEditorDialog-DM-d0hCD.js.map → PkImageEditorDialog-aekpEqWD.js.map} +1 -1
- package/dist/_chunks/{PkSelectionActions-Bl1KbGOj.js → PkSelectionActions-DDhRX6cs.js} +2 -2
- package/dist/_chunks/{PkSelectionActions-Bl1KbGOj.js.map → PkSelectionActions-DDhRX6cs.js.map} +1 -1
- package/dist/_chunks/{PkStreamingMarkdown-CU1ZUUCf.js → PkStreamingMarkdown-5WfFCjFv.js} +3 -3
- package/dist/_chunks/{PkStreamingMarkdown-CU1ZUUCf.js.map → PkStreamingMarkdown-5WfFCjFv.js.map} +1 -1
- package/dist/_chunks/{PkToolChatFile-B-Y47Q_K.js → PkToolChatFile-C3B9q2OL.js} +3 -3
- package/dist/_chunks/{PkToolChatFile-B-Y47Q_K.js.map → PkToolChatFile-C3B9q2OL.js.map} +1 -1
- package/dist/_chunks/{PkToolRequestGeolocation-B41xrF8k.js → PkToolRequestGeolocation-D4pYnCW5.js} +2 -2
- package/dist/_chunks/{PkToolRequestGeolocation-B41xrF8k.js.map → PkToolRequestGeolocation-D4pYnCW5.js.map} +1 -1
- package/dist/_chunks/{PkToolRequestOAuthConnection-BuCGuHwd.js → PkToolRequestOAuthConnection-DnnRY2rt.js} +2 -2
- package/dist/_chunks/{PkToolRequestOAuthConnection-BuCGuHwd.js.map → PkToolRequestOAuthConnection-DnnRY2rt.js.map} +1 -1
- package/dist/_chunks/{PkToolShowArtifact-Bjm6uhOK.js → PkToolShowArtifact-DQln7TsF.js} +2 -2
- package/dist/_chunks/{PkToolShowArtifact-Bjm6uhOK.js.map → PkToolShowArtifact-DQln7TsF.js.map} +1 -1
- package/dist/_chunks/{PkToolShowChart-B6TKQ3aT.js → PkToolShowChart-DfDB9BeZ.js} +2 -2
- package/dist/_chunks/{PkToolShowChart-B6TKQ3aT.js.map → PkToolShowChart-DfDB9BeZ.js.map} +1 -1
- package/dist/_chunks/{PkToolShowContactForm-5tg4xbrh.js → PkToolShowContactForm-Dkb8AiqL.js} +2 -2
- package/dist/_chunks/{PkToolShowContactForm-5tg4xbrh.js.map → PkToolShowContactForm-Dkb8AiqL.js.map} +1 -1
- package/dist/_chunks/{PkToolShowDiagram-CiNtS-vX.js → PkToolShowDiagram-B2dBogUW.js} +2 -2
- package/dist/_chunks/{PkToolShowDiagram-CiNtS-vX.js.map → PkToolShowDiagram-B2dBogUW.js.map} +1 -1
- package/dist/_chunks/{PkToolShowForm-eh8mXr6u.js → PkToolShowForm-CtDcwJs4.js} +4 -4
- package/dist/_chunks/{PkToolShowForm-eh8mXr6u.js.map → PkToolShowForm-CtDcwJs4.js.map} +1 -1
- package/dist/_chunks/{PkToolShowImageGallery-DedpXD-b.js → PkToolShowImageGallery-dLMI3SM7.js} +2 -2
- package/dist/_chunks/{PkToolShowImageGallery-DedpXD-b.js.map → PkToolShowImageGallery-dLMI3SM7.js.map} +1 -1
- package/dist/_chunks/{PkToolShowProductList-D24EIc4v.js → PkToolShowProductList-DE6BEdr_.js} +2 -2
- package/dist/_chunks/{PkToolShowProductList-D24EIc4v.js.map → PkToolShowProductList-DE6BEdr_.js.map} +1 -1
- package/dist/_chunks/{PkToolShowSources-Dnw1x7dT.js → PkToolShowSources-vSr080EU.js} +3 -3
- package/dist/_chunks/{PkToolShowSources-Dnw1x7dT.js.map → PkToolShowSources-vSr080EU.js.map} +1 -1
- package/dist/_chunks/{PkToolShowSuggestedReply-CxNx1Uf6.js → PkToolShowSuggestedReply-HuKn3loC.js} +2 -2
- package/dist/_chunks/{PkToolShowSuggestedReply-CxNx1Uf6.js.map → PkToolShowSuggestedReply-HuKn3loC.js.map} +1 -1
- package/dist/_chunks/{PkToolShowVideo-CDcJiprr.js → PkToolShowVideo-BL-9CiYe.js} +2 -2
- package/dist/_chunks/{PkToolShowVideo-CDcJiprr.js.map → PkToolShowVideo-BL-9CiYe.js.map} +1 -1
- package/dist/_chunks/{PkToolShowWebPages-UXqb0XEJ.js → PkToolShowWebPages-DQfODZdD.js} +2 -2
- package/dist/_chunks/{PkToolShowWebPages-UXqb0XEJ.js.map → PkToolShowWebPages-DQfODZdD.js.map} +1 -1
- package/dist/_chunks/{chatImagePolicy-DJAB0Bgw.js → chatImagePolicy-Cj5lkTVq.js} +2 -2
- package/dist/_chunks/{chatImagePolicy-DJAB0Bgw.js.map → chatImagePolicy-Cj5lkTVq.js.map} +1 -1
- package/dist/_chunks/text-CCurUhdH.js +13 -0
- package/dist/_chunks/text-CCurUhdH.js.map +1 -0
- package/dist/_chunks/{utils-78zQeKDO.js → utils-CRy3kzE3.js} +458 -160
- package/dist/_chunks/utils-CRy3kzE3.js.map +1 -0
- package/dist/ai-elements.es.js +5971 -5636
- package/dist/ai-elements.es.js.map +1 -1
- package/dist-vue/PkChatbot.js +1 -1
- package/dist-vue/PkChatbotAuth.js +1 -1
- package/dist-vue/PkChatbotEmptyState.js +1 -1
- package/dist-vue/PkChatbotInput.js +1 -1
- package/dist-vue/PkChatbotLocalFolders.d.ts +2 -0
- package/dist-vue/PkChatbotLocalFolders.js +1 -0
- package/dist-vue/PkChatbotMessages.js +1 -1
- package/dist-vue/PkChatbotStepPayload.js +1 -1
- package/dist-vue/PkChatbotStepToolDetail.js +1 -1
- package/dist-vue/PkChatbotSteps.js +1 -1
- package/dist-vue/PkChatbotViewChat.js +1 -1
- package/dist-vue/PkChatbotViewConversations.js +1 -1
- package/dist-vue/PkChatbotViewFiles.js +1 -1
- package/dist-vue/PkChatbotViewProfile.js +1 -1
- package/dist-vue/_chunks/{Agent-Da4XChe8.js → Agent-DKefaJeG.js} +445 -377
- package/dist-vue/_chunks/Agent-DKefaJeG.js.map +1 -0
- package/dist-vue/_chunks/{Document-CsQsUQYa.js → Document-B49E_gxT.js} +18 -18
- package/dist-vue/_chunks/{Document-CsQsUQYa.js.map → Document-B49E_gxT.js.map} +1 -1
- package/dist-vue/_chunks/{Media-CMiWEpdQ.js → Media-DtudATme.js} +12 -2
- package/dist-vue/_chunks/Media-DtudATme.js.map +1 -0
- package/dist-vue/_chunks/{PkChatbot-CITKd3qD.js → PkChatbot-8Fqlhwq5.js} +10 -9
- package/dist-vue/_chunks/PkChatbot-8Fqlhwq5.js.map +1 -0
- package/dist-vue/_chunks/{PkChatbotAuth-SfTyFbq1.js → PkChatbotAuth-CIK2CFy-.js} +8 -8
- package/dist-vue/_chunks/{PkChatbotAuth-SfTyFbq1.js.map → PkChatbotAuth-CIK2CFy-.js.map} +1 -1
- package/dist-vue/_chunks/{PkChatbotEmptyState-DI_8T5a4.js → PkChatbotEmptyState-C_htXOSW.js} +2 -2
- package/dist-vue/_chunks/{PkChatbotEmptyState-DI_8T5a4.js.map → PkChatbotEmptyState-C_htXOSW.js.map} +1 -1
- package/dist-vue/_chunks/PkChatbotInput-CJ5lPtpH.js +658 -0
- package/dist-vue/_chunks/PkChatbotInput-CJ5lPtpH.js.map +1 -0
- package/dist-vue/_chunks/PkChatbotLocalFolders-CSvqh_Cx.js +126 -0
- package/dist-vue/_chunks/PkChatbotLocalFolders-CSvqh_Cx.js.map +1 -0
- package/dist-vue/_chunks/{PkChatbotMessages-BWdINCAX.js → PkChatbotMessages-DY8r4UKe.js} +49 -49
- package/dist-vue/_chunks/{PkChatbotMessages-BWdINCAX.js.map → PkChatbotMessages-DY8r4UKe.js.map} +1 -1
- package/dist-vue/_chunks/{PkChatbotStepPayload-CTwsRpkv.js → PkChatbotStepPayload-BLjH1pkP.js} +2 -2
- package/dist-vue/_chunks/{PkChatbotStepPayload-CTwsRpkv.js.map → PkChatbotStepPayload-BLjH1pkP.js.map} +1 -1
- package/dist-vue/_chunks/{PkChatbotStepToolDetail-C9xeMg-k.js → PkChatbotStepToolDetail-wIZmkvr-.js} +3 -3
- package/dist-vue/_chunks/{PkChatbotStepToolDetail-C9xeMg-k.js.map → PkChatbotStepToolDetail-wIZmkvr-.js.map} +1 -1
- package/dist-vue/_chunks/{PkChatbotSteps-DsubpIKa.js → PkChatbotSteps-DG09GyCb.js} +7 -7
- package/dist-vue/_chunks/{PkChatbotSteps-DsubpIKa.js.map → PkChatbotSteps-DG09GyCb.js.map} +1 -1
- package/dist-vue/_chunks/{PkChatbotViewChat-DW1a9ZNl.js → PkChatbotViewChat-DTKfW1kr.js} +684 -666
- package/dist-vue/_chunks/PkChatbotViewChat-DTKfW1kr.js.map +1 -0
- package/dist-vue/_chunks/{PkChatbotViewConversations-DdniYy1b.js → PkChatbotViewConversations-NA_PCvZR.js} +4 -4
- package/dist-vue/_chunks/{PkChatbotViewConversations-DdniYy1b.js.map → PkChatbotViewConversations-NA_PCvZR.js.map} +1 -1
- package/dist-vue/_chunks/{PkChatbotViewFiles-CMoromsf.js → PkChatbotViewFiles-D8_Khdu2.js} +3 -3
- package/dist-vue/_chunks/{PkChatbotViewFiles-CMoromsf.js.map → PkChatbotViewFiles-D8_Khdu2.js.map} +1 -1
- package/dist-vue/_chunks/{PkChatbotViewProfile-BT7I3GhB.js → PkChatbotViewProfile-iTBiQVsZ.js} +2 -2
- package/dist-vue/_chunks/{PkChatbotViewProfile-BT7I3GhB.js.map → PkChatbotViewProfile-iTBiQVsZ.js.map} +1 -1
- package/dist-vue/_chunks/{PkFilePreview-Dxp-U8QU.js → PkFilePreview-sSb1Mmr2.js} +4 -4
- package/dist-vue/_chunks/{PkFilePreview-Dxp-U8QU.js.map → PkFilePreview-sSb1Mmr2.js.map} +1 -1
- package/dist-vue/_chunks/{PkFilePreviewDialog-BE-NpN18.js → PkFilePreviewDialog-DquXMRJD.js} +2 -2
- package/dist-vue/_chunks/{PkFilePreviewDialog-BE-NpN18.js.map → PkFilePreviewDialog-DquXMRJD.js.map} +1 -1
- package/dist-vue/_chunks/{PkImageEditorDialog-BiuOD6Hr.js → PkImageEditorDialog-CrjpCier.js} +2 -2
- package/dist-vue/_chunks/{PkImageEditorDialog-BiuOD6Hr.js.map → PkImageEditorDialog-CrjpCier.js.map} +1 -1
- package/dist-vue/_chunks/{PkStreamingMarkdown-DMmt35Mq.js → PkStreamingMarkdown-CgKFdzCI.js} +23 -23
- package/dist-vue/_chunks/{PkStreamingMarkdown-DMmt35Mq.js.map → PkStreamingMarkdown-CgKFdzCI.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolChatFile-BdNron14.js → PkToolChatFile-IEQxfzjM.js} +3 -3
- package/dist-vue/_chunks/{PkToolChatFile-BdNron14.js.map → PkToolChatFile-IEQxfzjM.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolRequestGeolocation-DeI7kLlR.js → PkToolRequestGeolocation-BmrbMPke.js} +2 -2
- package/dist-vue/_chunks/{PkToolRequestGeolocation-DeI7kLlR.js.map → PkToolRequestGeolocation-BmrbMPke.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolRequestOAuthConnection-C0lE3Qbk.js → PkToolRequestOAuthConnection-yKgXyOUN.js} +2 -2
- package/dist-vue/_chunks/{PkToolRequestOAuthConnection-C0lE3Qbk.js.map → PkToolRequestOAuthConnection-yKgXyOUN.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowArtifact-C0Gb-LW2.js → PkToolShowArtifact-CF90yFCe.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowArtifact-C0Gb-LW2.js.map → PkToolShowArtifact-CF90yFCe.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowChart-oJmzU10F.js → PkToolShowChart-CDR8ag4q.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowChart-oJmzU10F.js.map → PkToolShowChart-CDR8ag4q.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowContactForm-D4IAna-K.js → PkToolShowContactForm-DAdKUU4X.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowContactForm-D4IAna-K.js.map → PkToolShowContactForm-DAdKUU4X.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowDiagram-ClGpv5Cr.js → PkToolShowDiagram-Do20AvFb.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowDiagram-ClGpv5Cr.js.map → PkToolShowDiagram-Do20AvFb.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowForm-ByfNodNh.js → PkToolShowForm-DfFmPOt6.js} +4 -4
- package/dist-vue/_chunks/{PkToolShowForm-ByfNodNh.js.map → PkToolShowForm-DfFmPOt6.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowImageGallery-DJ9JNDWK.js → PkToolShowImageGallery-DA6KW2g_.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowImageGallery-DJ9JNDWK.js.map → PkToolShowImageGallery-DA6KW2g_.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowProductList-CcFseg28.js → PkToolShowProductList-FcDDabPI.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowProductList-CcFseg28.js.map → PkToolShowProductList-FcDDabPI.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowSources-DznWqWK3.js → PkToolShowSources-afCYBONq.js} +3 -3
- package/dist-vue/_chunks/{PkToolShowSources-DznWqWK3.js.map → PkToolShowSources-afCYBONq.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowSuggestedReply-BZqnfpwO.js → PkToolShowSuggestedReply-C863wgtU.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowSuggestedReply-BZqnfpwO.js.map → PkToolShowSuggestedReply-C863wgtU.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowVideo-niwkzqTN.js → PkToolShowVideo-kUiwxRlz.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowVideo-niwkzqTN.js.map → PkToolShowVideo-kUiwxRlz.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowWebPages-BsMVJ6c7.js → PkToolShowWebPages-Dw9D1__u.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowWebPages-BsMVJ6c7.js.map → PkToolShowWebPages-Dw9D1__u.js.map} +1 -1
- package/dist-vue/_chunks/{createChatbotApiClient-Cd_2UI_O.js → createChatbotApiClient-DzrHp52e.js} +66 -65
- package/dist-vue/_chunks/createChatbotApiClient-DzrHp52e.js.map +1 -0
- package/dist-vue/_chunks/localFolders-ChZp8dLu.js +353 -0
- package/dist-vue/_chunks/localFolders-ChZp8dLu.js.map +1 -0
- package/dist-vue/_chunks/{useChatbotStore-Dir9Rc7K.js → useChatbotStore-DZlc7dzK.js} +1289 -1152
- package/dist-vue/_chunks/useChatbotStore-DZlc7dzK.js.map +1 -0
- package/dist-vue/_chunks/useSettledSelection-1bfM1fzx.js +55 -0
- package/dist-vue/_chunks/useSettledSelection-1bfM1fzx.js.map +1 -0
- package/dist-vue/_chunks/{utils-CibsowVe.js → utils-CY0jFRnG.js} +126 -107
- package/dist-vue/_chunks/utils-CY0jFRnG.js.map +1 -0
- package/dist-vue/api.js +1 -1
- package/dist-vue/apps/web-component/src/composables/useChatbotAgent.d.ts +6 -0
- package/dist-vue/composables.js +62 -10
- package/dist-vue/composables.js.map +1 -1
- package/dist-vue/index.js +4100 -4086
- package/dist-vue/index.js.map +1 -1
- package/dist-vue/locales.js +32 -0
- package/dist-vue/packages/components/src/chat/PkAgentSettingsPanel.d.ts +6 -2
- package/dist-vue/packages/components/src/chat/PkChatbot.d.ts +7 -1
- package/dist-vue/packages/components/src/chat/PkChatbotLocalFolders.d.ts +31 -0
- package/dist-vue/packages/components/src/chat/utils.d.ts +3 -2
- package/dist-vue/packages/composable/src/chatbot/hostTools.d.ts +1 -1
- package/dist-vue/packages/composable/src/chatbot/index.d.ts +1 -0
- package/dist-vue/packages/composable/src/chatbot/localFolders.d.ts +137 -0
- package/dist-vue/packages/composable/src/chatbot/useChatbotStore.d.ts +46 -3
- package/dist-vue/packages/models/src/schema/Agent.d.ts +24 -0
- package/dist-vue/packages/models/src/schema/Chat.d.ts +1 -0
- package/dist-vue/packages/models/src/schema/HostTool.d.ts +5 -2
- package/dist-vue/packages/models/src/schema/LocalFolder.d.ts +78 -0
- package/dist-vue/packages/models/src/schema/Organization.d.ts +10 -0
- package/dist-vue/packages/models/src/schema/PageAccess.d.ts +4 -1
- package/dist-vue/packages/models/src/schema/ReasoningChat.d.ts +8 -0
- package/dist-vue/packages/models/src/schema/SubAgent.d.ts +8 -0
- package/dist-vue/packages/models/src/schema/index.d.ts +1 -0
- package/dist-vue/style.css +1 -1
- package/package.json +1 -1
- package/dist/_chunks/Agent-DytagI8S.js.map +0 -1
- package/dist/_chunks/text-5F7L8EHi.js +0 -5
- package/dist/_chunks/text-5F7L8EHi.js.map +0 -1
- package/dist/_chunks/utils-78zQeKDO.js.map +0 -1
- package/dist-vue/_chunks/Agent-Da4XChe8.js.map +0 -1
- package/dist-vue/_chunks/Media-CMiWEpdQ.js.map +0 -1
- package/dist-vue/_chunks/PkChatbot-CITKd3qD.js.map +0 -1
- package/dist-vue/_chunks/PkChatbotInput-UqcSEi8l.js +0 -708
- package/dist-vue/_chunks/PkChatbotInput-UqcSEi8l.js.map +0 -1
- package/dist-vue/_chunks/PkChatbotViewChat-DW1a9ZNl.js.map +0 -1
- package/dist-vue/_chunks/createChatbotApiClient-Cd_2UI_O.js.map +0 -1
- package/dist-vue/_chunks/message-DuibQyHy.js +0 -61
- package/dist-vue/_chunks/message-DuibQyHy.js.map +0 -1
- package/dist-vue/_chunks/useChatbotStore-Dir9Rc7K.js.map +0 -1
- package/dist-vue/_chunks/utils-CibsowVe.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils-CRy3kzE3.js","names":["z.object","z.uuid","z.iso.datetime","z.number","z.string","z.boolean","z.enum","z.discriminatedUnion","z.literal","z.iso.date","z.array","datetime","array","number","object","boolean","literal","date","uuid","discriminatedUnion","_enum","string","HOST_TOOL_RESULT_MAX_CHARS","isExcludedLocalFile","isHostToolPart","LOCAL_FOLDER_FIND_MAX_FILES","isExcludedLocalPath","isExcludedLocalDirectory","isPresentationTool","MCP_TOOL_PREFIX","formatBytes","SUBAGENT_TOOL_PREFIX","API_TOOL_PREFIX","WEB_SEARCH_TOOL_KEYS","LOCAL_FOLDER_READ_MAX_CHARS","decodeTextBytes","fromAnyCase","capitalizeFirstLetter","ChatTaskStatus","ChatTaskEndReason","CRON_TASK_TOOL_NAMES","REPORT_TASK_RUN_TOOL_NAME","TaskFireJobSchema","ChatTaskSummarySchema","CLOCK_TIME","ChatTaskScheduleSchema","ChatTaskScheduleRefusal","cronFromScheduleShape","hour","minute","schedule","clock","month","day","a","b","CRON_NUMBER","weekdaySet","field","days","item","range","from","to","hourlyHours","match","every","cronScheduleShape","recurring","fields","cron","dayOfMonth","dayOfWeek","hours","weekdays","weekdaysOnly","at","hourOfDay","time","isTextPart","part","isToolPart","getToolPartName","isFilePart","getFilePartMedia","media","getFilePartTranscript","transcript","withAudioTranscripts","messages","own","updates","update","message","storedFileName","isReasoningPart","hasTextPart","getTextPart","parts","MAX_DEPTH","ATTACH_ONLY_EXTENSIONS","extensionOf","dot","name","isAttachOnlyFile","fromDirectoryHandle","handle","entry","snapshotTree","directory","child","file","fromFileList","roots","files","path","segments","fileName","rootName","segment","next","uniqueFolderName","names","taken","index","text","value","failure","FolderToolError","stringInput","input","key","pathInput","localFolderStepName","formatDate","millis","resultLength","result","findChild","resolveLocalPath","folderName","rest","folder","folders","node","joinPath","walk","signal","childPath","depth","visit","readFileText","bytes","maxBytes","listLocalFolder","permission","source","lines","more","findInLocalFolders","needle","starts","matches","walked","bytesRead","skipped","filePath","blob","content","line","candidate","start","notes","readLocalFile","rawOffset","offset","windowTo","header","end","footer","createLocalFolderTools","policy","deps","guarded","run","error","describe","toolName","declaredLocalFolders","granted","root","DB_NAME","STORE","openDb","request","resolve","reject","inStore","db","work","mode","localFolderStorage","store","owner","id","known","all","userId","directoryPicker","picker","canOfferLocalFolders","SCHEDULED_TASK_PART_TYPES","mergeConsecutiveTextParts","merged","prev","isWidgetPart","dropCorrectedWidgetErrors","lastDrawn","isStreamingPart","FILE_OUTPUT_PARTS","moveFileOutputsLast","feedPartKey","toolCallId","getHostCallPart","PAGE_TOOL_STEPS","HOST_STEP_TITLES","HOST_STEP_CHANGES","FORM_TOOL_STEP","FOLDER_TOOL_STEPS","pageToolStep","host","isHostActionPart","LIVE_REASONING_TAIL_LENGTH","FENCE_LINE","getMarkdownTail","markdown","maxLength","limit","boundary","length","cut","openFence","marker","TOOL_APPROVAL_STATES","isToolApprovalPart","CONFIRM_TOOL_NAME","isToolConfirmPart","isConfirmationCardPart","getToolApprovalId","getPartState","relativeLuminance","hex","hexcolor","char","r","g","linearize","c","getContrast","isAchromaticColor","channels","channelsToHex","readCssColor","expression","computed","probe","srgb","rgb","resolveGlowTints","readGlowTints","mainColor","sourceHex","neutral","middle","color","hueShift","first","second","secondColor","tones","resolveContrastColor","textColor","agentThemeStyle","contrastColor","formatDuration","ms","$n","stringifyPayload","json","hasPayload","formAnswerAsSpoken","answer","question","questionById","step","said","formStepOptions","option","formAnswerSlots","slots","output","steps","assign","list","WEB_SEARCH_TOOL_TYPES","RICH_DETAIL_TOOL_TYPES","hasRichToolDetail","asRecord","pickString","keys","record","getToolPartSummary","queries","valid","query","sheet","getPartIcon","TOOL_KEY_PREFIXES","toolLabel","te","prefix","p","bare","PART_TYPE_LABELS","t","getPartTypeLabel","translator","label","localizeSummaryLabels","summary","labels","colon","getToolPartLabel","live","hostStepTitles","folderFile","$t","page","WORD_FONT_STACKS","WORD_LINE_FACTORS","wordLineFactor","font","wordFontStack","WORD_PREVIEW_IMAGES","WORD_PREVIEW_CHARTS","wordPictureSrc","src","images","ref","wordPageAnchorCss","anchor","picture","wordPicturePlacement","wordKeptRuns","runs","hasWordText","wordFlowItems","out","breakPending","sectionPending","push","opens","section","row","breakBefore","keepNext","skip","blocks","block","breaks","cell","cells","wordPageAnchors","chatFileName","version","filename","EDITABLE_IMAGE_TYPES","isEditableImage","mediaType","isImeComposing","event","chatCoversPageControlBar","center","windowWidth","chat","selectionBarPosition","lowest","bounds","margin","bar","under","bottom","touch","gap","below","above","roomAbove","placement","selectionCardPosition","systemMenu","gapBelow","room","side","tallest","maxHeight","shortest","shown","card","top"],"sources":["../../../../packages/models/src/schema/ChatTask.ts","../../../../packages/utils/src/message.ts","../../../../packages/composable/src/chatbot/localFolders.ts","../../../../packages/components/src/chat/utils.ts"],"sourcesContent":["import * as z from 'zod'\n\n/**\n * Lifecycle of a scheduled task (spec agent-recurring-tasks). Only an\n * `active` task has a next run; the others keep their row for the user's\n * list and the run ledger.\n */\nexport const ChatTaskStatus = {\n Active: 'active',\n /** Stopped after too many failed runs in a row: the user can resume it. */\n Paused: 'paused',\n /** A one-off task after its run. */\n Completed: 'completed',\n /** Removed by the user or the agent (`cronDelete`). */\n Deleted: 'deleted',\n /** Closed by the platform: its runs could no longer reach the user. */\n Ended: 'ended',\n} as const\n\nexport type ChatTaskStatus =\n (typeof ChatTaskStatus)[keyof typeof ChatTaskStatus]\n\n/** Why the platform, or the user, paused or ended a task. */\nexport const ChatTaskEndReason = {\n Failures: 'failures',\n /** Paused by its user with the task's switch: nobody is told. */\n User: 'user',\n NoAccess: 'no-access',\n ChatUnavailable: 'chat-unavailable',\n ChannelUnavailable: 'channel-unavailable',\n ToolDisabled: 'tool-disabled',\n /** A one-off run whose message was lost and found too late. */\n Missed: 'missed',\n /**\n * A run reached the end the user gave the task (\"until 3 pm\", \"for a\n * week\") and closed it with `reportTaskRun` and `last: true`.\n */\n Completed: 'completed',\n} as const\n\nexport type ChatTaskEndReason =\n (typeof ChatTaskEndReason)[keyof typeof ChatTaskEndReason]\n\n/** The three tools of the `cronTasks` switch, replicas of Claude Code's cron tools. */\nexport const CRON_TASK_TOOL_NAMES = [\n 'cronCreate',\n 'cronList',\n 'cronDelete',\n] as const\n\n/** The signal a task run ends with: `noop: true` sends nothing to the user. */\nexport const REPORT_TASK_RUN_TOOL_NAME = 'reportTaskRun'\n\n/**\n * How far ahead a task's message is armed. A run further away is reached\n * through relay messages, so no message waits longer than this: queues keep\n * a message 14 days, and a local timer cannot wait more than about 24 days.\n */\nexport const TASK_ARM_HORIZON_MS = 6 * 24 * 60 * 60 * 1000\n\n/**\n * The body of a task's scheduled Service Bus message, and of the internal\n * fire call. `runAt` is the run it serves, `at` when the message itself was\n * due: a relay arrives before `runAt` and only arms the next message.\n */\nexport const TaskFireJobSchema = z.object({\n taskId: z.uuid(),\n runAt: z.iso.datetime(),\n at: z.iso.datetime(),\n /** Times the run already waited for a turn running in its chat. */\n deferrals: z.number().int().nonnegative(),\n})\nexport type TaskFireJob = z.infer<typeof TaskFireJobSchema>\n\n/**\n * The body the function app signs and the backend verifies when a task's\n * message fires: the same fields in the same order at both ends.\n */\nexport const taskFireSignedBody = (job: TaskFireJob): string =>\n JSON.stringify({\n taskId: job.taskId,\n runAt: job.runAt,\n at: job.at,\n deferrals: job.deferrals,\n })\n\n/** A task as the agent's `cronList` and the user's list show it. */\nexport const ChatTaskSummarySchema = z.object({\n id: z.uuid(),\n agentId: z.uuid(),\n chatId: z.string(),\n cron: z.string(),\n timezone: z.string(),\n reason: z.string(),\n recurring: z.boolean(),\n status: z.enum(ChatTaskStatus),\n endedReason: z.enum(ChatTaskEndReason).nullable(),\n nextRunAt: z.iso.datetime().nullable(),\n lastRunAt: z.iso.datetime().nullable(),\n createdAt: z.iso.datetime(),\n})\nexport type ChatTaskSummary = z.infer<typeof ChatTaskSummarySchema>\n\n/**\n * A task in the user's own list (spec agent-recurring-tasks, F2): with the\n * agent it runs on and its organization, named on the row and the one the\n * link to its chat goes through.\n */\nexport const ChatTaskListItemSchema = ChatTaskSummarySchema.extend({\n agentName: z.string(),\n organizationName: z.string(),\n organizationSlug: z.string(),\n})\nexport type ChatTaskListItem = z.infer<typeof ChatTaskListItemSchema>\n\n/** A task with the prompt its runs start from, for the edit window (F3). */\nexport const ChatTaskDetailSchema = ChatTaskSummarySchema.extend({\n prompt: z.string(),\n})\nexport type ChatTaskDetail = z.infer<typeof ChatTaskDetailSchema>\n\nconst CLOCK_TIME = /^([01]\\d|2[0-3]):[0-5]\\d$/\n\n/**\n * A schedule as the edit window chooses it (spec agent-recurring-tasks, F3):\n * the shapes {@link cronScheduleShape} says in words, a one-off with its date.\n * Times are in the task's timezone. It never travels as a cron: the server\n * builds one with {@link cronFromScheduleShape}.\n */\nexport const ChatTaskScheduleSchema = z.discriminatedUnion('kind', [\n z.object({\n kind: z.literal('once'),\n date: z.iso.date(),\n time: z.string().regex(CLOCK_TIME),\n }),\n z.object({ kind: z.literal('daily'), time: z.string().regex(CLOCK_TIME) }),\n z.object({\n kind: z.literal('weekdays'),\n time: z.string().regex(CLOCK_TIME),\n }),\n z.object({\n kind: z.literal('weekly'),\n time: z.string().regex(CLOCK_TIME),\n /** Sunday = 0, as in cron. */\n weekdays: z.array(z.number().int().min(0).max(6)).min(1).max(7),\n }),\n z.object({\n kind: z.literal('monthly'),\n time: z.string().regex(CLOCK_TIME),\n day: z.number().int().min(1).max(31),\n }),\n])\nexport type ChatTaskSchedule = z.infer<typeof ChatTaskScheduleSchema>\n\n/** What the edit window changes; what it leaves out stays as it is. */\nexport const ChatTaskUpdateSchema = z.object({\n reason: z.string().trim().min(1).max(200).optional(),\n prompt: z.string().trim().min(1).max(2000).optional(),\n schedule: ChatTaskScheduleSchema.optional(),\n})\nexport type ChatTaskUpdate = z.infer<typeof ChatTaskUpdateSchema>\n\n/** Why the server refused a schedule from the edit window. */\nexport const ChatTaskScheduleRefusal = {\n /** A one-off whose date and time have passed. */\n Past: 'past',\n /** A date that never comes (the 31st of a month that has 30 days). */\n Never: 'never',\n TooFrequent: 'too-frequent',\n /**\n * A one-off further than the cron can say: it has no year, so a date\n * past the horizon would run on the same day of an earlier year.\n */\n TooFar: 'too-far',\n} as const\nexport type ChatTaskScheduleRefusal =\n (typeof ChatTaskScheduleRefusal)[keyof typeof ChatTaskScheduleRefusal]\n\n/**\n * The cron of a schedule chosen in the edit window, the inverse of\n * {@link cronScheduleShape}: reading back what it writes gives the same shape\n * (a one-off reads back as `once`, its date being in the cron).\n */\nexport function cronFromScheduleShape(schedule: ChatTaskSchedule): {\n cron: string\n recurring: boolean\n} {\n const [hour, minute] = schedule.time.split(':').map(Number)\n const clock = `${minute} ${hour}`\n switch (schedule.kind) {\n case 'once': {\n const [, month, day] = schedule.date.split('-').map(Number)\n return { cron: `${clock} ${day} ${month} *`, recurring: false }\n }\n case 'daily':\n return { cron: `${clock} * * *`, recurring: true }\n case 'weekdays':\n return { cron: `${clock} * * 1-5`, recurring: true }\n case 'weekly':\n return {\n cron: `${clock} * * ${[...new Set(schedule.weekdays)].sort((a, b) => a - b).join(',')}`,\n recurring: true,\n }\n case 'monthly':\n return { cron: `${clock} ${schedule.day} * *`, recurring: true }\n }\n}\n\n/**\n * The shape of a task's cron, for the user's list to say it in words (spec\n * agent-recurring-tasks, F2; DESIGN.md keeps raw notation off the screen).\n * The common shapes only: anything else is `custom`, and the next run says\n * when. Weekdays are numbered from Sunday = 0, as in cron.\n */\nexport type CronScheduleShape =\n | { kind: 'once' }\n /**\n * Every `every` hours at `minute`, all day or from `from` to `to` (the\n * times of the first and last run), every day or on weekdays only. The\n * shortest interval a task takes is an hour, so the commonest recurring\n * request lands here.\n */\n | {\n kind: 'hourly'\n minute: number\n every: number\n from?: string\n to?: string\n weekdaysOnly: boolean\n }\n | { kind: 'daily'; time: string }\n | { kind: 'weekdays'; time: string }\n | { kind: 'weekly'; time: string; weekdays: number[] }\n | { kind: 'monthly'; time: string; day: number }\n | { kind: 'custom' }\n\nconst CRON_NUMBER = /^\\d{1,2}$/\n\n/**\n * The days of a cron's day-of-week field, `*`, numbers and ranges such as\n * `1-5` or `0,3,6`, from Monday to Sunday; undefined for anything else\n * (names, steps).\n */\nfunction weekdaySet(field: string): number[] | undefined {\n if (field === '*') {\n return [1, 2, 3, 4, 5, 6, 0]\n }\n const days = new Set<number>()\n for (const item of field.split(',')) {\n const range = /^([0-7])(?:-([0-7]))?$/.exec(item)\n if (!range) {\n return undefined\n }\n const from = Number(range[1])\n const to = range[2] === undefined ? from : Number(range[2])\n if (to < from) {\n return undefined\n }\n for (let day = from; day <= to; day++) {\n days.add(day % 7)\n }\n }\n return [...days].sort((a, b) => ((a + 6) % 7) - ((b + 6) % 7))\n}\n\n/**\n * The hours of an hourly cron's hour field: every hour or every n hours, all\n * day or within a range (\"10-15\", \"8-18\" with a step of 2). Undefined for\n * anything else, a single hour or a list included.\n */\nfunction hourlyHours(\n field: string,\n): { every: number; from?: number; to?: number } | undefined {\n const match = /^(?:\\*|(\\d{1,2})-(\\d{1,2}))(?:\\/(\\d{1,2}))?$/.exec(field)\n if (!match) {\n return undefined\n }\n const every = match[3] === undefined ? 1 : Number(match[3])\n if (every < 1 || every > 23) {\n return undefined\n }\n if (match[1] === undefined) {\n return { every }\n }\n const from = Number(match[1])\n const to = Number(match[2])\n if (from > to || to > 23) {\n return undefined\n }\n // The last hour that runs, not the end of the range\n return { every, from, to: from + Math.floor((to - from) / every) * every }\n}\n\n/** The shape of `cron`, a five-field expression; see {@link CronScheduleShape}. */\nexport function cronScheduleShape(\n cron: string,\n recurring: boolean,\n): CronScheduleShape {\n if (!recurring) {\n return { kind: 'once' }\n }\n const fields = cron.trim().split(/\\s+/)\n if (fields.length !== 5) {\n return { kind: 'custom' }\n }\n const [minute, hour, dayOfMonth, month, dayOfWeek] = fields\n if (\n CRON_NUMBER.test(minute) &&\n Number(minute) <= 59 &&\n !CRON_NUMBER.test(hour) &&\n dayOfMonth === '*' &&\n month === '*'\n ) {\n const hours = hourlyHours(hour)\n const weekdays = weekdaySet(dayOfWeek)\n const weekdaysOnly = weekdays?.join() === '1,2,3,4,5'\n if (!hours || !weekdays || (weekdays.length !== 7 && !weekdaysOnly)) {\n return { kind: 'custom' }\n }\n const at = (hourOfDay: number) =>\n `${String(hourOfDay).padStart(2, '0')}:${minute.padStart(2, '0')}`\n return {\n kind: 'hourly',\n minute: Number(minute),\n every: hours.every,\n ...(hours.from !== undefined &&\n hours.to !== undefined && {\n from: at(hours.from),\n to: at(hours.to),\n }),\n weekdaysOnly,\n }\n }\n if (\n !CRON_NUMBER.test(minute) ||\n !CRON_NUMBER.test(hour) ||\n Number(minute) > 59 ||\n Number(hour) > 23 ||\n month !== '*'\n ) {\n return { kind: 'custom' }\n }\n const time = `${hour.padStart(2, '0')}:${minute.padStart(2, '0')}`\n if (dayOfMonth === '*') {\n const weekdays = weekdaySet(dayOfWeek)\n if (!weekdays) {\n return { kind: 'custom' }\n }\n if (weekdays.length === 7) {\n return { kind: 'daily', time }\n }\n if (weekdays.join() === '1,2,3,4,5') {\n return { kind: 'weekdays', time }\n }\n return { kind: 'weekly', time, weekdays }\n }\n if (\n dayOfWeek === '*' &&\n CRON_NUMBER.test(dayOfMonth) &&\n Number(dayOfMonth) >= 1 &&\n Number(dayOfMonth) <= 31\n ) {\n return { kind: 'monthly', time, day: Number(dayOfMonth) }\n }\n return { kind: 'custom' }\n}\n","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 {\n formatBytes,\n HOST_TOOL_RESULT_MAX_CHARS,\n LOCAL_FOLDERS_MAX,\n LOCAL_FOLDER_FIND_MAX_BYTES,\n LOCAL_FOLDER_FIND_MAX_FILE_BYTES,\n LOCAL_FOLDER_FIND_MAX_FILES,\n LOCAL_FOLDER_FIND_MAX_RESULTS,\n LOCAL_FOLDER_LIST_MAX_ENTRIES,\n LOCAL_FOLDER_READ_MAX_CHARS,\n LOCAL_FOLDER_READ_MAX_FILE_BYTES,\n isExcludedLocalDirectory,\n isExcludedLocalFile,\n isExcludedLocalPath,\n type HostToolResult,\n type LocalFoldersRequest,\n} from 'models'\nimport { decodeTextBytes } from 'utils'\nimport type { RegisteredHostTool } from './hostTools'\n\n/**\n * The folders of the user's computer the app's chat reads (spec\n * `chat-local-folders.md`). Two sources behind one tree: a File System\n * Access handle (Chrome and Edge), kept in IndexedDB and asked again for its\n * permission on a later visit, and the files of an `<input webkitdirectory>`\n * (Firefox and Safari), a snapshot that lives as long as the page.\n */\n\nexport type LocalFolderFile = {\n kind: 'file'\n name: string\n file: () => Promise<File>\n}\nexport type LocalFolderDirectory = {\n kind: 'directory'\n name: string\n children: () => AsyncIterable<LocalFolderNode>\n}\nexport type LocalFolderNode = LocalFolderFile | LocalFolderDirectory\n\n/** The parts of the File System Access API the chat uses: not in TypeScript's DOM lib. */\nexport type DirectoryHandle = {\n kind: 'directory'\n name: string\n values: () => AsyncIterable<\n | DirectoryHandle\n | { kind: 'file'; name: string; getFile: () => Promise<File> }\n >\n queryPermission?: (options: {\n mode: 'read'\n }) => Promise<'granted' | 'prompt' | 'denied'>\n requestPermission?: (options: {\n mode: 'read'\n }) => Promise<'granted' | 'prompt' | 'denied'>\n isSameEntry?: (other: DirectoryHandle) => Promise<boolean>\n}\n\nexport type ConnectedLocalFolder = {\n id: string\n /** Unique among the connected folders: the first segment of every path. */\n name: string\n /** `snapshot` for the files of an `<input webkitdirectory>`. */\n source: 'handle' | 'snapshot'\n /** `prompt` until the user allows it again on this visit. */\n permission: 'granted' | 'prompt' | 'denied'\n handle?: DirectoryHandle\n root?: LocalFolderDirectory\n}\n\nconst MAX_DEPTH = 12\n\n/** Never opened as text, by a read or a search: what `folder_attach` takes. */\nconst ATTACH_ONLY_EXTENSIONS = new Set([\n 'pdf',\n 'doc',\n 'docx',\n 'xls',\n 'xlsx',\n 'xlsm',\n 'ppt',\n 'pptx',\n 'odt',\n 'ods',\n 'odp',\n 'rtf',\n 'png',\n 'jpg',\n 'jpeg',\n 'gif',\n 'webp',\n 'heic',\n 'svg',\n 'mp3',\n 'm4a',\n 'wav',\n 'mp4',\n 'mov',\n 'zip',\n '7z',\n 'rar',\n 'gz',\n 'tar',\n 'exe',\n 'dmg',\n 'msi',\n 'iso',\n 'bin',\n])\n\nconst extensionOf = (name: string) => {\n const dot = name.lastIndexOf('.')\n return dot > 0 ? name.slice(dot + 1).toLowerCase() : ''\n}\n\nexport const isAttachOnlyFile = (name: string) =>\n ATTACH_ONLY_EXTENSIONS.has(extensionOf(name))\n\n/** The tree of a File System Access handle, without the excluded entries. */\nexport const fromDirectoryHandle = (\n handle: DirectoryHandle,\n): LocalFolderDirectory => ({\n kind: 'directory',\n name: handle.name,\n children: async function* () {\n for await (const entry of handle.values()) {\n if (entry.kind === 'directory') {\n if (!isExcludedLocalDirectory(entry.name)) {\n yield fromDirectoryHandle(entry)\n }\n } else if (!isExcludedLocalFile(entry.name)) {\n yield {\n kind: 'file',\n name: entry.name,\n file: () => entry.getFile(),\n }\n }\n }\n },\n})\n\ntype SnapshotDirectory = {\n name: string\n directories: Map<string, SnapshotDirectory>\n files: Map<string, File>\n}\n\nconst snapshotTree = (directory: SnapshotDirectory): LocalFolderDirectory => ({\n kind: 'directory',\n name: directory.name,\n children: async function* () {\n for (const child of directory.directories.values()) {\n yield snapshotTree(child)\n }\n for (const [name, file] of directory.files) {\n yield { kind: 'file', name, file: async () => file }\n }\n },\n})\n\n/**\n * The folders of an `<input webkitdirectory>`: one per top folder of the\n * relative paths (the browser gives one, the one the user picked). Excluded\n * entries are dropped here, before anything reads them.\n */\nexport const fromFileList = (files: Iterable<File>): LocalFolderDirectory[] => {\n const roots = new Map<string, SnapshotDirectory>()\n for (const file of files) {\n const path = file.webkitRelativePath || file.name\n if (isExcludedLocalPath(path)) {\n continue\n }\n const segments = path.split('/').filter(Boolean)\n const fileName = segments.pop()\n const rootName = segments.shift()\n if (!fileName || !rootName) {\n continue\n }\n let directory = roots.get(rootName)\n if (!directory) {\n directory = {\n name: rootName,\n directories: new Map(),\n files: new Map(),\n }\n roots.set(rootName, directory)\n }\n for (const segment of segments) {\n let next: SnapshotDirectory | undefined =\n directory.directories.get(segment)\n if (!next) {\n next = {\n name: segment,\n directories: new Map(),\n files: new Map(),\n }\n directory.directories.set(segment, next)\n }\n directory = next\n }\n directory.files.set(fileName, file)\n }\n return [...roots.values()].map(snapshotTree)\n}\n\n/** A name not yet taken: \"Offerte\", then \"Offerte (2)\". */\nexport const uniqueFolderName = (name: string, taken: Iterable<string>) => {\n const names = new Set(taken)\n if (!names.has(name)) {\n return name\n }\n let index = 2\n while (names.has(`${name} (${index})`)) {\n index++\n }\n return `${name} (${index})`\n}\n\nconst text = (value: string): HostToolResult => ({\n content: [{ type: 'text', text: value }],\n})\nconst failure = (value: string): HostToolResult => ({\n ...text(value),\n isError: true,\n})\n\nclass FolderToolError extends Error {}\n\nconst stringInput = (input: unknown, key: string): string | undefined => {\n const value = (input as Record<string, unknown> | null)?.[key]\n return typeof value === 'string' && value.trim() ? value.trim() : undefined\n}\n\n/**\n * A path as the model wrote it, untrimmed: a name may begin or end with a\n * space on macOS, and a trimmed path would miss it or open its twin.\n */\nconst pathInput = (input: unknown): string | undefined => {\n const value = (input as Record<string, unknown> | null)?.path\n return typeof value === 'string' && value.trim() ? value : undefined\n}\n\n/**\n * The name a step of a folder tool shows: the last segment of the path it\n * read, or nothing for a call without one (the list of the folders, a search\n * across all of them). Live while the call runs and from the saved input\n * after a reload, so the two read the same.\n */\nexport const localFolderStepName = (input: unknown): string | undefined =>\n pathInput(input)?.split('/').filter(Boolean).pop()\n\nconst formatDate = (millis: number) =>\n `${new Date(millis).toISOString().slice(0, 16).replace('T', ' ')} UTC`\n\n/** What the backend measures a result by: its JSON, where quotes and line ends count twice. */\nconst resultLength = (result: HostToolResult) => JSON.stringify(result).length\n\nconst findChild = async (\n directory: LocalFolderDirectory,\n name: string,\n): Promise<LocalFolderNode | undefined> => {\n for await (const child of directory.children()) {\n if (child.name === name) {\n return child\n }\n }\n return undefined\n}\n\n/**\n * The node a path names. The first segment is a connected folder; an\n * excluded segment, a folder still waiting for its permission or a missing\n * entry is an error the model reads.\n */\nexport const resolveLocalPath = async (\n folders: readonly ConnectedLocalFolder[],\n path: string,\n): Promise<LocalFolderNode> => {\n const segments = path.split('/').filter(Boolean)\n const [folderName, ...rest] = segments\n const folder = folders.find(({ name }) => name === folderName)\n if (!folder) {\n throw new FolderToolError(\n `No connected folder is named \"${folderName ?? ''}\": call folder_list without a path to see them.`,\n )\n }\n if (!folder.root || folder.permission !== 'granted') {\n throw new FolderToolError(\n `The folder \"${folder.name}\" needs the user's permission again on this visit: ask the user to press \"Allow\" on the folder above the message box.`,\n )\n }\n if (isExcludedLocalPath(rest.join('/'))) {\n throw new FolderToolError(\n 'This path is excluded: secrets, keys, version control and dependencies are never read.',\n )\n }\n let node: LocalFolderNode = folder.root\n for (const segment of rest) {\n if (node.kind !== 'directory') {\n throw new FolderToolError(`\"${path}\" does not exist.`)\n }\n const child = await findChild(node, segment)\n if (!child) {\n throw new FolderToolError(`\"${path}\" does not exist.`)\n }\n node = child\n }\n return node\n}\n\nconst joinPath = (...segments: string[]) => segments.filter(Boolean).join('/')\n\n/**\n * Walks a folder depth-first, the excluded entries already out of the tree,\n * until `visit` says stop or the depth runs out.\n */\nasync function walk(\n directory: LocalFolderDirectory,\n path: string,\n visit: (file: LocalFolderFile, path: string) => Promise<boolean>,\n signal: AbortSignal,\n depth = 0,\n): Promise<boolean> {\n for await (const child of directory.children()) {\n if (signal.aborted) {\n return false\n }\n const childPath = joinPath(path, child.name)\n if (child.kind === 'directory') {\n if (\n depth < MAX_DEPTH &&\n !(await walk(child, childPath, visit, signal, depth + 1))\n ) {\n return false\n }\n } else if (!(await visit(child, childPath))) {\n return false\n }\n }\n return true\n}\n\n/**\n * The text of a file, decoded as the backend decodes a text attachment\n * (UTF-16 from its byte order mark, UTF-8, else Windows-1252), or\n * `undefined` for one that is not text: a NUL in what it decodes to.\n */\nexport const readFileText = async (\n file: Blob,\n maxBytes: number,\n): Promise<string | undefined> => {\n const bytes = new Uint8Array(await file.slice(0, maxBytes).arrayBuffer())\n const text = decodeTextBytes(bytes, bytes.byteLength < file.size)\n return text.includes('\\u0000') ? undefined : text\n}\n\n/** `folder_list`: the connected folders, or the entries of one folder. */\nexport async function listLocalFolder(\n folders: readonly ConnectedLocalFolder[],\n input: unknown,\n): Promise<HostToolResult> {\n const path = pathInput(input)\n if (!path) {\n if (folders.length === 0) {\n return failure('The user has not connected any folder.')\n }\n return text(\n [\n 'Connected folders:',\n ...folders.map(\n ({ name, permission, source }) =>\n `- ${name}${permission === 'granted' ? '' : ' (waiting for the user to allow it again)'}${source === 'snapshot' ? ' (a copy taken when the user picked it)' : ''}`,\n ),\n ].join('\\n'),\n )\n }\n const node = await resolveLocalPath(folders, path)\n if (node.kind !== 'directory') {\n return failure(\n `\"${path}\" is a file: read it with folder_read or folder_attach.`,\n )\n }\n const lines: string[] = []\n let more = 0\n for await (const child of node.children()) {\n if (lines.length >= LOCAL_FOLDER_LIST_MAX_ENTRIES) {\n more++\n continue\n }\n if (child.kind === 'directory') {\n lines.push(`${child.name}/`)\n continue\n }\n // The size and the date come from the metadata: a synced file the\n // computer does not hold yet is not downloaded for them.\n const file = await child.file()\n lines.push(\n `${child.name} · ${formatBytes(file.size)} · ${formatDate(file.lastModified)}`,\n )\n }\n if (lines.length === 0) {\n return text(`\"${path}\" is empty.`)\n }\n return text(\n [\n `${path}:`,\n ...lines,\n ...(more > 0\n ? [`… and ${more} more entries: search with folder_find.`]\n : []),\n ].join('\\n'),\n )\n}\n\n/** `folder_find`: files by a part of their name, or by a text they contain. */\nexport async function findInLocalFolders(\n folders: readonly ConnectedLocalFolder[],\n input: unknown,\n signal: AbortSignal,\n): Promise<HostToolResult> {\n const name = stringInput(input, 'name')?.toLowerCase()\n const needle = stringInput(input, 'text')?.toLowerCase()\n const path = pathInput(input)\n if (!name && !needle) {\n return failure('Give a name, a text, or both.')\n }\n const starts: { node: LocalFolderDirectory; path: string }[] = []\n if (path) {\n const node = await resolveLocalPath(folders, path)\n if (node.kind !== 'directory') {\n return failure(`\"${path}\" is a file, not a folder.`)\n }\n starts.push({ node, path })\n } else {\n for (const folder of folders) {\n if (folder.root && folder.permission === 'granted') {\n starts.push({ node: folder.root, path: folder.name })\n }\n }\n }\n const matches: string[] = []\n let walked = 0\n let bytesRead = 0\n let skipped = 0\n const visit = async (file: LocalFolderFile, filePath: string) => {\n walked++\n if (walked > LOCAL_FOLDER_FIND_MAX_FILES) {\n return false\n }\n if (name && !file.name.toLowerCase().includes(name)) {\n return true\n }\n if (!needle) {\n matches.push(filePath)\n return matches.length < LOCAL_FOLDER_FIND_MAX_RESULTS\n }\n if (isAttachOnlyFile(file.name)) {\n return true\n }\n const blob = await file.file()\n if (\n blob.size > LOCAL_FOLDER_FIND_MAX_FILE_BYTES ||\n bytesRead + blob.size > LOCAL_FOLDER_FIND_MAX_BYTES\n ) {\n skipped++\n return true\n }\n bytesRead += blob.size\n const content = await readFileText(blob, blob.size)\n if (content === undefined) {\n return true\n }\n const line = content\n .split(/\\r?\\n/)\n .find((candidate) => candidate.toLowerCase().includes(needle))\n if (line !== undefined) {\n matches.push(`${filePath}: ${line.trim().slice(0, 200)}`)\n }\n return matches.length < LOCAL_FOLDER_FIND_MAX_RESULTS\n }\n for (const start of starts) {\n if (!(await walk(start.node, start.path, visit, signal))) {\n break\n }\n }\n const notes = [\n ...(walked > LOCAL_FOLDER_FIND_MAX_FILES\n ? [\n `Stopped after ${LOCAL_FOLDER_FIND_MAX_FILES} files: narrow the search with path.`,\n ]\n : []),\n ...(skipped > 0\n ? [\n `${skipped} files were too large to search by text: look for them by name.`,\n ]\n : []),\n ]\n if (matches.length === 0) {\n return text(['No match.', ...notes].join('\\n'))\n }\n return text(\n [\n `${matches.length} matches${matches.length >= LOCAL_FOLDER_FIND_MAX_RESULTS ? ' (the first ones)' : ''}:`,\n ...matches,\n ...notes,\n ].join('\\n'),\n )\n}\n\n/** `folder_read`: a text file, one window of characters a call. */\nexport async function readLocalFile(\n folders: readonly ConnectedLocalFolder[],\n input: unknown,\n): Promise<HostToolResult> {\n const path = pathInput(input)\n if (!path) {\n return failure('Give the path of the file.')\n }\n const node = await resolveLocalPath(folders, path)\n if (node.kind !== 'file') {\n return failure(`\"${path}\" is a folder: list it with folder_list.`)\n }\n if (isAttachOnlyFile(node.name)) {\n return failure(\n `\"${path}\" is not a text file: attach it with folder_attach.`,\n )\n }\n const file = await node.file()\n if (file.size > LOCAL_FOLDER_READ_MAX_FILE_BYTES) {\n return failure(\n `\"${path}\" is ${formatBytes(file.size)}, too large to read as text: attach it with folder_attach.`,\n )\n }\n const content = await readFileText(file, file.size)\n if (content === undefined) {\n return failure(\n `\"${path}\" is not a text file: attach it with folder_attach.`,\n )\n }\n const rawOffset = (input as { offset?: unknown }).offset\n const offset =\n typeof rawOffset === 'number' && rawOffset > 0\n ? Math.floor(rawOffset)\n : 0\n const windowTo = (end: number) => {\n const header = `${path} · ${formatBytes(file.size)} · changed ${formatDate(file.lastModified)} · characters ${offset}-${end} of ${content.length}`\n const footer =\n end < content.length\n ? `\\n[More follows: call folder_read again with offset ${end}.]`\n : ''\n return text(`${header}\\n\\n${content.slice(offset, end)}${footer}`)\n }\n // A CSV full of quotes grows past the backend's cap once escaped: the\n // window shrinks by half of what overflows, an escaped character\n // counting twice, until it fits\n let end = Math.min(content.length, offset + LOCAL_FOLDER_READ_MAX_CHARS)\n let result = windowTo(end)\n while (\n resultLength(result) > HOST_TOOL_RESULT_MAX_CHARS &&\n end > offset + 1\n ) {\n end = Math.max(\n offset + 1,\n end -\n Math.ceil(\n (resultLength(result) - HOST_TOOL_RESULT_MAX_CHARS) / 2,\n ),\n )\n result = windowTo(end)\n }\n return result\n}\n\n/**\n * The tools the chat runs on the connected folders: the widget's own kind\n * (`policy`), so the agent's host tool settings neither allow nor confirm\n * them. Nothing asks the user before a read: the user chose the folder, and\n * every call shows as a step of the answer with the path it read.\n */\nexport function createLocalFolderTools(deps: {\n folders: () => readonly ConnectedLocalFolder[]\n /** Puts the file in the message box, as the user would: resolves with an error text, or nothing. */\n attach: (file: File) => Promise<string | undefined>\n timeoutMs: number\n /** \"Reading offerta.md\": what the step says, from the call's input. */\n describe: (toolName: string, input: unknown) => string | undefined\n}): RegisteredHostTool[] {\n const policy = { timeoutMs: deps.timeoutMs }\n const guarded =\n (\n run: (\n input: unknown,\n signal: AbortSignal,\n ) => Promise<HostToolResult>,\n ) =>\n async (input: unknown, { signal }: { signal: AbortSignal }) => {\n try {\n const result = await run(input, signal)\n // A list of long names can still pass the cap: the backend\n // would refuse it whole, so the model gets the way out here\n return resultLength(result) > HOST_TOOL_RESULT_MAX_CHARS\n ? failure(\n 'The result is too long: narrow it with a path or a more precise name.',\n )\n : result\n } catch (error) {\n if (error instanceof FolderToolError) {\n return failure(error.message)\n }\n // NotFoundError: moved or deleted since the listing;\n // NotAllowedError: the permission was taken back.\n const name = (error as { name?: unknown })?.name\n return failure(\n name === 'NotAllowedError'\n ? 'The browser no longer allows reading this folder: ask the user to allow it again.'\n : name === 'NotFoundError'\n ? 'The file or folder is no longer there.'\n : name === 'NotReadableError'\n ? 'The file could not be read: it may be open in another app, or a cloud file (OneDrive, iCloud) the computer cannot download now.'\n : 'The folder could not be read.',\n )\n }\n }\n const describe = (toolName: string) => (input: unknown) =>\n deps.describe(toolName, input)\n return [\n {\n name: 'folder_list',\n inputSchema: { type: 'object' },\n annotations: { readOnlyHint: true },\n policy,\n describe: describe('folder_list'),\n execute: guarded((input) => listLocalFolder(deps.folders(), input)),\n },\n {\n name: 'folder_find',\n inputSchema: { type: 'object' },\n annotations: { readOnlyHint: true },\n policy,\n describe: describe('folder_find'),\n execute: guarded((input, signal) =>\n findInLocalFolders(deps.folders(), input, signal),\n ),\n },\n {\n name: 'folder_read',\n inputSchema: { type: 'object' },\n annotations: { readOnlyHint: true },\n policy,\n describe: describe('folder_read'),\n execute: guarded((input) => readLocalFile(deps.folders(), input)),\n },\n {\n name: 'folder_attach',\n inputSchema: { type: 'object' },\n annotations: { readOnlyHint: true },\n policy,\n describe: describe('folder_attach'),\n execute: guarded(async (input, signal) => {\n const path = pathInput(input)\n if (!path) {\n return failure('Give the path of the file.')\n }\n const node = await resolveLocalPath(deps.folders(), path)\n if (node.kind !== 'file') {\n return failure(`\"${path}\" is a folder, not a file.`)\n }\n const file = await node.file()\n // Stopped, timed out or moved to another chat while the file\n // was read: nothing may land in the message box any more\n if (signal.aborted) {\n return failure(\n 'The call was stopped before the file was attached.',\n )\n }\n const error = await deps.attach(file)\n return error\n ? failure(error)\n : text(\n `\"${path}\" is in the user's message box: it reaches you when the user sends the message. Tell the user, and end your answer.`,\n )\n }),\n },\n ]\n}\n\n/** What a request declares: the folders the page can read now. */\nexport const declaredLocalFolders = (\n folders: readonly ConnectedLocalFolder[],\n): LocalFoldersRequest | undefined => {\n const granted = folders.filter(\n ({ permission, root }) => permission === 'granted' && root,\n )\n // The backend refuses a declaration past the cap, and with it every folder\n return granted.length > 0\n ? {\n folders: granted\n .slice(0, LOCAL_FOLDERS_MAX)\n .map(({ name }) => ({ name })),\n }\n : undefined\n}\n\nconst DB_NAME = 'agentstudio-local-folders'\nconst STORE = 'folders'\n\ntype StoredFolder = {\n key: string\n owner: string\n id: string\n name: string\n handle: DirectoryHandle\n}\n\nconst openDb = () =>\n new Promise<IDBDatabase>((resolve, reject) => {\n const request = indexedDB.open(DB_NAME, 1)\n request.onupgradeneeded = () => {\n request.result.createObjectStore(STORE, { keyPath: 'key' })\n }\n request.onsuccess = () => resolve(request.result)\n request.onerror = () => reject(request.error)\n })\n\nconst inStore = async <T>(\n mode: IDBTransactionMode,\n work: (store: IDBObjectStore) => IDBRequest<T>,\n): Promise<T> => {\n const db = await openDb()\n try {\n return await new Promise<T>((resolve, reject) => {\n const request = work(db.transaction(STORE, mode).objectStore(STORE))\n request.onsuccess = () => resolve(request.result)\n request.onerror = () => reject(request.error)\n })\n } finally {\n db.close()\n }\n}\n\n/**\n * The handles connected in this browser, by owner (the user with an agent):\n * two people who share a browser profile never see each other's folders,\n * and an agent never reads a folder connected for another. A handle holds no\n * permission of its own: the browser asks again on a later visit, unless the\n * user chose \"Allow on every visit\" or installed the app.\n */\nexport const localFolderStorage = {\n async load(\n owner: string,\n ): Promise<{ id: string; name: string; handle: DirectoryHandle }[]> {\n const all = await inStore<StoredFolder[]>('readonly', (store) =>\n store.getAll(),\n )\n return all\n .filter((folder) => folder.owner === owner)\n .map(({ id, name, handle }) => ({ id, name, handle }))\n },\n async save(\n owner: string,\n folder: { id: string; name: string; handle: DirectoryHandle },\n ) {\n await inStore('readwrite', (store) =>\n store.put({ key: `${owner}:${folder.id}`, owner, ...folder }),\n )\n },\n async remove(owner: string, id: string) {\n await inStore('readwrite', (store) => store.delete(`${owner}:${id}`))\n },\n /**\n * Forgets the folders of a user with every agent, on sign-out: whoever\n * signs in next in this browser finds none of them. Opens nothing in a\n * browser that never kept a folder.\n */\n async forgetUser(userId: string) {\n const known = await indexedDB.databases?.()\n if (known && !known.some(({ name }) => name === DB_NAME)) {\n return\n }\n const all = await inStore<StoredFolder[]>('readonly', (store) =>\n store.getAll(),\n )\n for (const { key, owner } of all) {\n if (owner.startsWith(`${userId}:`)) {\n await inStore('readwrite', (store) => store.delete(key))\n }\n }\n },\n}\n\n/** The folder picker, where the browser has one: Chrome and Edge on a desktop. */\nexport const directoryPicker = ():\n | ((options: { id?: string; mode?: 'read' }) => Promise<DirectoryHandle>)\n | undefined => {\n const picker = (globalThis as { showDirectoryPicker?: unknown })\n .showDirectoryPicker\n return typeof picker === 'function'\n ? (picker.bind(globalThis) as ReturnType<typeof directoryPicker>)\n : undefined\n}\n\n/**\n * True where the chat may offer folders at all: a top-level page. A frame\n * of another origin cannot open a picker, and a grant in a frame of the same\n * origin would be the host page's to see.\n */\nexport const canOfferLocalFolders = () => {\n try {\n return typeof window !== 'undefined' && window.self === window.top\n } catch {\n return false\n }\n}\n","import type { UIMessage } from 'ai'\nimport type { CSSProperties, InjectionKey, Ref } from 'vue'\nimport {\n API_TOOL_PREFIX,\n CRON_TASK_TOOL_NAMES,\n MCP_TOOL_PREFIX,\n REPORT_TASK_RUN_TOOL_NAME,\n SUBAGENT_TOOL_PREFIX,\n WEB_SEARCH_TOOL_KEYS,\n isHostToolPart,\n isPresentationTool,\n type PreviewChart,\n type WordPreviewBlock,\n type WordPreviewPage,\n type WordPreviewPicture,\n type WordPreviewRun,\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'\nimport { localFolderStepName } from 'composables'\n\nexport {\n isTextPart,\n isFilePart,\n isToolPart,\n isReasoningPart,\n hasPartText,\n hasTextPart,\n getTextPart,\n getMessageText,\n}\n\n/** The parts of the scheduled task tools (spec agent-recurring-tasks). */\nconst SCHEDULED_TASK_PART_TYPES: ReadonlySet<string> = new Set(\n [...CRON_TASK_TOOL_NAMES, REPORT_TASK_RUN_TOOL_NAME].map(\n (name) => `tool-${name}`,\n ),\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 input?: unknown\n toolMetadata?: { readOnly?: boolean; provider?: 'app' | 'page' | 'folder' }\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 setting a step changes: what it was, what it becomes. */\nexport type StepFieldChange = { label: string; value: string; before?: string }\n\n/**\n * What the steps the automatic confirmations ran without a card changed, by\n * call (spec `auto-confirmations.md`): provided by the chat view from its\n * store, shown under each step's line.\n */\nexport const HOST_STEP_CHANGES: InjectionKey<\n Ref<\n Record<\n string,\n {\n details?: StepFieldChange[]\n unchanged?: { label: string; value: string }[]\n }\n >\n >\n> = Symbol('hostStepChanges')\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\n/** The steps of the folders the user connected (spec `chat-local-folders.md`). */\nconst FOLDER_TOOL_STEPS: Record<string, { icon: string; label: string }> = {\n folder_list: {\n icon: 'ri:folder-open-line',\n label: 'localFolders.tool.folder_list',\n },\n folder_find: {\n icon: 'ri:file-search-line',\n label: 'localFolders.tool.folder_find',\n },\n folder_read: {\n icon: 'ri:file-text-line',\n label: 'localFolders.tool.folder_read',\n },\n folder_attach: {\n icon: 'ri:attachment-2',\n label: 'localFolders.tool.folder_attach',\n },\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 : host.toolMetadata?.provider === 'folder'\n ? FOLDER_TOOL_STEPS[host.toolName]\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\n/** The WCAG relative luminance of a hex color, from 0 (black) to 1 (white). */\nfunction relativeLuminance(hexcolor: string): number {\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 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 return 0.2126 * linearize(r) + 0.7152 * linearize(g) + 0.0722 * linearize(b)\n}\n\nexport function getContrast(hexcolor: string = '000000'): 'black' | 'white' {\n return relativeLuminance(hexcolor) > 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/** A color as the glow's shader takes it: three channels, 0-255. */\nexport type RgbChannels = [number, number, number]\n\n/** The two tints of the empty chat's glow, and whether the second shows. */\nexport type GlowTints = {\n first: RgbChannels\n second: RgbChannels\n duo: boolean\n}\n\n/** `#rrggbb` from three 0-255 channels. */\nexport const channelsToHex = (channels: RgbChannels) =>\n `#${channels.map((value) => value.toString(16).padStart(2, '0')).join('')}`\n\n/**\n * The color a CSS expression resolves to where `probe` sits. Mixed into sRGB\n * first, it computes to `color(srgb r g b)` whatever syntax it was written in\n * (the design system's tokens derive with the relative color syntax). A\n * browser without `color-mix()` would drop the mix and leave the inherited\n * color for every expression: it reads the bare one, which computes to `rgb()`.\n */\nfunction readCssColor(\n probe: HTMLElement,\n expression: string,\n): RgbChannels | null {\n probe.style.color = CSS.supports(\n 'color',\n 'color-mix(in srgb, red 100%, transparent)',\n )\n ? `color-mix(in srgb, ${expression} 100%, transparent)`\n : expression\n const computed = getComputedStyle(probe).color\n probe.style.color = ''\n const srgb = computed.match(/^color\\(srgb ([^\\s)]+) ([^\\s)]+) ([^\\s)]+)/)\n const rgb = computed.match(/rgba?\\(([\\d.]+)[,\\s]+([\\d.]+)[,\\s]+([\\d.]+)/)\n if (srgb) {\n return [srgb[1], srgb[2], srgb[3]].map((value) =>\n Math.round(Math.min(1, Math.max(0, Number(value))) * 255),\n ) as RgbChannels\n }\n if (rgb) {\n return [rgb[1], rgb[2], rgb[3]].map((value) =>\n Math.round(Number(value)),\n ) as RgbChannels\n }\n return null\n}\n\n/**\n * The two tints of the glow behind the empty chat's input. A color without a\n * hue (black, the default, white, a gray) drew a grey smudge on the light\n * theme and nothing on the dark one: the platform's accent lights it instead,\n * with its info color as the second tone, as the working beam does. Any other\n * color gives its neighbour 40° along the hue wheel as the second tone,\n * unless the agent chose one. Every tone is held to a middle lightness, like\n * the beam's, so a chosen second color that matches the one shown keeps the\n * glow as it was. `auto` shows the second tone only for a color without a hue.\n *\n * The colors resolve where `host` sits (its tokens, its theme); without\n * `mainColor` the glow starts from the host's own color. Null when the\n * browser cannot read them.\n */\nexport function resolveGlowTints(\n host: HTMLElement,\n {\n mainColor,\n tones = 'auto',\n secondColor,\n }: {\n mainColor?: string\n tones?: 'auto' | 'one' | 'two'\n secondColor?: string\n },\n): GlowTints | null {\n // A throwaway child inherits the host's color and custom properties, and\n // reading through it leaves the host's own style alone\n const probe = document.createElement('span')\n probe.hidden = true\n host.append(probe)\n try {\n return readGlowTints(probe, { mainColor, tones, secondColor })\n } finally {\n probe.remove()\n }\n}\n\nfunction readGlowTints(\n probe: HTMLElement,\n {\n mainColor,\n tones,\n secondColor,\n }: {\n mainColor?: string\n tones: 'auto' | 'one' | 'two'\n secondColor?: string\n },\n): GlowTints | null {\n const source = readCssColor(probe, mainColor ?? 'currentcolor')\n if (!source) {\n return null\n }\n const sourceHex = channelsToHex(source)\n const neutral = isAchromaticColor(sourceHex)\n // Where the browser can derive it; the color as it is otherwise\n const middle = (color: string, hueShift = 0) =>\n CSS.supports('color', 'oklch(from red l c h)')\n ? `oklch(from ${color} clamp(0.55, l, 0.75) c calc(h + ${hueShift}))`\n : color\n const first = readCssColor(\n probe,\n middle(neutral ? 'var(--color-accent)' : sourceHex),\n )\n const second = readCssColor(\n probe,\n secondColor\n ? middle(secondColor)\n : neutral\n ? middle('var(--color-info)')\n : middle(sourceHex, 40),\n )\n if (!first || !second) {\n return null\n }\n return {\n first,\n second,\n duo: tones === 'two' || (tones === 'auto' && neutral),\n }\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\n * `undefined`, which always reaches 4.58:1, the worst case being a luminance\n * right at the threshold. An explicit preference stands even when it reads\n * worse: the settings panel says so (`textContrastRatio`).\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 WCAG contrast ratio of white or black text on `mainColor`, or\n * `undefined` for a color the function cannot read.\n */\nexport function textContrastRatio(\n textColor: 'white' | 'black',\n mainColor: string | undefined,\n): number | undefined {\n const main = mainColor ? relativeLuminance(mainColor) : Number.NaN\n if (Number.isNaN(main)) {\n return undefined\n }\n return textColor === 'white' ? 1.05 / (main + 0.05) : (main + 0.05) / 0.05\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 (SCHEDULED_TASK_PART_TYPES.has(part.type)) {\n return 'ri:calendar-schedule-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-showChart') {\n return 'ri:bar-chart-2-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, params?: Record<string, unknown>) => 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 // A folder step names the file it read, after a reload as live\n const folderFile =\n host.toolMetadata?.provider === 'folder'\n ? localFolderStepName(host.input)\n : undefined\n if (folderFile) {\n return $t(`localFolders.step.${host.toolName}`, {\n name: folderFile,\n })\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 (SCHEDULED_TASK_PART_TYPES.has(part.type)) {\n return $t(`messagePart.${part.type.slice('tool-'.length)}`)\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-showChart') {\n return $t(`messagePart.showChart`)\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/**\n * The images of the Word document in the viewer, by reference, which its\n * runs draw (`PkWordPreview` provides them).\n */\nexport const WORD_PREVIEW_IMAGES: InjectionKey<\n Ref<Record<string, string> | undefined>\n> = Symbol('wordPreviewImages')\n\n/**\n * The native charts of the Word document in the viewer, by reference, which\n * its runs draw (`PkWordPreview` provides them; spec `chat-charts.md`, F4).\n */\nexport const WORD_PREVIEW_CHARTS: InjectionKey<\n Ref<Record<string, PreviewChart> | undefined>\n> = Symbol('wordPreviewCharts')\n\n/**\n * The image a run draws, only a WebP the server wrote: anything else in the\n * map is not drawn.\n */\nexport const wordPictureSrc = (\n images: Record<string, string> | undefined,\n ref: string,\n): string | undefined => {\n const src = images?.[ref]\n return src?.startsWith('data:image/webp;base64,') ? src : undefined\n}\n\n/** The numbers the page number fields of a page show. */\nexport type WordPageNumbers = {\n page: number\n pages: number\n sectionPages: number\n}\n\n/**\n * Where an image Word positions on the page sits on it: from the page's top\n * left corner, in points, under the text or over it.\n */\nexport const wordPageAnchorCss = (\n picture: WordPreviewPicture,\n page: WordPreviewPage,\n): CSSProperties => {\n const anchor = picture.anchor!\n return {\n left: `${anchor.xFrom === 'page' ? anchor.x : page.margins.left + anchor.x}pt`,\n top: `${anchor.yFrom === 'page' ? anchor.y : page.margins.top + anchor.y}pt`,\n width: `${picture.width}pt`,\n height: `${picture.height}pt`,\n zIndex: anchor.wrap === 'behind' ? -1 : 1,\n }\n}\n\n/**\n * How an image of a run is placed: in the text, beside the text of its\n * paragraph, on a line of its own, from its paragraph, or on the page,\n * which the page draws.\n */\nexport const wordPicturePlacement = (\n picture: WordPreviewPicture,\n): 'inline' | 'around' | 'block' | 'paragraph' | 'page' => {\n const anchor = picture.anchor\n return !anchor\n ? 'inline'\n : anchor.wrap === 'around'\n ? 'around'\n : anchor.wrap === 'block'\n ? 'block'\n : anchor.yFrom === 'paragraph'\n ? 'paragraph'\n : 'page'\n}\n\n/** The runs a mode keeps: a deletion is gone once accepted. */\nexport const wordKeptRuns = (\n runs: WordPreviewRun[],\n mode: WordPreviewMode,\n): WordPreviewRun[] =>\n runs.filter((r) =>\n mode === 'accepted'\n ? r.change !== 'deleted'\n : mode === 'original'\n ? r.change !== 'inserted'\n : true,\n )\n\nconst hasWordText = (runs: WordPreviewRun[]) =>\n runs.some((r) => r.image || r.text.trim())\n\n/** A piece of a Word document's flow: a paragraph or a table row. */\nexport type WordFlowItem = {\n key: string\n block: number\n row?: number\n breakBefore: boolean\n /** The section it opens. */\n section?: number\n /** Stays on the page of the next piece (Word's \"Keep with next\"). */\n keepNext?: true\n}\n\n/**\n * The pieces of `blocks` in order, as the pages hold them. A paragraph or a\n * table row a mode empties is gone (a row inserted, as the original); one\n * empty in the document stays, a blank line as in Word. A section a gone\n * piece opened, with its page break, passes to the next one.\n */\nexport const wordFlowItems = (\n blocks: WordPreviewBlock[],\n mode: WordPreviewMode,\n): WordFlowItem[] => {\n const out: WordFlowItem[] = []\n let breakPending = false\n let sectionPending: number | undefined\n const push = (\n key: string,\n block: number,\n row: number | undefined,\n breakBefore: boolean,\n section: number | undefined,\n keepNext: boolean,\n ) => {\n const opens = section ?? sectionPending\n out.push({\n key,\n block,\n ...(row !== undefined ? { row } : {}),\n breakBefore: breakBefore || breakPending,\n ...(opens !== undefined ? { section: opens } : {}),\n ...(keepNext ? { keepNext: true as const } : {}),\n })\n breakPending = false\n sectionPending = undefined\n }\n // A gone piece's own page break goes with it; a section's start stays\n const skip = (breakBefore: boolean, section: number | undefined) => {\n breakPending ||= breakBefore && section !== undefined\n sectionPending = section ?? sectionPending\n }\n blocks.forEach((block, b) => {\n if (block.kind === 'table') {\n // The table's break and section go with its first row shown\n let breaks = !!block.pageBreakBefore\n let opens = block.section\n block.rows.forEach((cells, r) => {\n const filled = cells.some((cell) => cell.runs.length)\n if (\n filled &&\n !cells.some((cell) =>\n hasWordText(wordKeptRuns(cell.runs, mode)),\n )\n ) {\n return\n }\n push(\n `${b}:${r}`,\n b,\n r,\n breaks,\n opens,\n cells.some((cell) => cell.keepNext),\n )\n breaks = false\n opens = undefined\n })\n skip(breaks, opens)\n } else if (\n !block.runs.length ||\n hasWordText(wordKeptRuns(block.runs, mode))\n ) {\n push(\n `${b}`,\n b,\n undefined,\n !!block.style?.pageBreakBefore,\n block.section,\n !!block.style?.keepNext,\n )\n } else {\n skip(!!block.style?.pageBreakBefore, block.section)\n }\n })\n return out\n}\n\n/** The images Word positions on the page among the paragraphs of `blocks`. */\nexport const wordPageAnchors = (\n blocks: WordPreviewBlock[],\n mode: WordPreviewMode,\n): WordPreviewPicture[] =>\n blocks.flatMap((block) =>\n block.kind === 'table'\n ? []\n : wordKeptRuns(block.runs, mode).flatMap((run) =>\n run.picture && wordPicturePlacement(run.picture) === 'page'\n ? [run.picture]\n : [],\n ),\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\nconst EDITABLE_IMAGE_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp'])\n\n/**\n * Whether the image editor (spec `chat-image-editor.md`) opens on a file of\n * this type: one a canvas reads and writes back as the same type, so not a\n * GIF, an SVG or a HEIC. Here and not in `imageEdits.ts`, which the\n * composer would otherwise pull into the main bundle of the widget.\n */\nexport function isEditableImage(mediaType: string): boolean {\n return EDITABLE_IMAGE_TYPES.has(mediaType)\n}\n\n/**\n * An input method (Japanese, Chinese, Korean) is composing a word: its\n * Enter and Esc confirm or drop the word. Safari reports the Enter that\n * confirms it with `isComposing` already false, hence the 229.\n */\nexport function isImeComposing(event: KeyboardEvent): boolean {\n return event.isComposing || event.keyCode === 229\n}\n\n/**\n * Whether a chat stands in front of the place of the bar that shows the\n * agent acting on the page (`PkPageControlBar`): the top centre of the\n * window, from the bar's `top` of 48px to about its 44px of height below.\n * There the bar would only cover the chat's header, and the chat shows the\n * steps and their stop itself.\n */\nexport function chatCoversPageControlBar(\n chat: Pick<DOMRect, 'left' | 'right' | 'top' | 'bottom'>,\n windowWidth: number,\n): boolean {\n const center = windowWidth / 2\n return (\n chat.left <= center &&\n chat.right >= center &&\n chat.top <= 92 &&\n chat.bottom >= 48\n )\n}\n\n/** Where a selection bar goes, in the coordinates of its `bounds`. */\nexport type SelectionBarPosition = {\n top: number\n left: number\n placement: 'above' | 'below'\n}\n\n/**\n * The room the system's menu takes above a selection made by touch, with its\n * distance from the text: iOS 18 draws its edit menu 41 px high, 14 px above\n * the selection (measured in the simulator on 2026-11-04).\n */\nexport const SYSTEM_MENU_ROOM = 56\n\n/**\n * The room the selection's handles take below the text on a touch screen:\n * Android's hang about 22 px under the line, the knob of iOS about 13\n * (measured in the emulator and the simulator on 2026-11-04). Closer, a\n * handle covered the first row of the bar and took its touch.\n */\nexport const SELECTION_HANDLES_ROOM = 28\n\n/**\n * Where the bar of a selection goes (spec `selection-actions.md`, \"Dove\"):\n * above the start of the selection, where it covers what was already read,\n * and below it only without room above. On a touch screen below, away from\n * the menu the system opens above a selection; without room below, above\n * that menu, never over it. `start` is the box of the selection's first\n * line, `bottom` its lowest edge, `bounds` the box the bar stays in, all in\n * one coordinate space, the result's too.\n */\nexport function selectionBarPosition({\n start,\n bottom,\n bar,\n bounds,\n touch = false,\n gap = 8,\n margin = 8,\n}: {\n start: Pick<DOMRect, 'top' | 'left'>\n bottom: number\n bar: { width: number; height: number }\n bounds: Pick<DOMRect, 'top' | 'left' | 'width' | 'height'>\n touch?: boolean\n gap?: number\n margin?: number\n}): SelectionBarPosition {\n const lowest = bounds.top + bounds.height - margin - bar.height\n const under = bottom + (touch ? Math.max(gap, SELECTION_HANDLES_ROOM) : gap)\n const below = Math.max(bounds.top + margin, Math.min(under, lowest))\n const above = start.top - gap - bar.height - (touch ? SYSTEM_MENU_ROOM : 0)\n const roomAbove = above >= bounds.top + margin\n const placement = (touch ? under > lowest && roomAbove : roomAbove)\n ? 'above'\n : 'below'\n const top = placement === 'above' ? above : below\n const left = Math.max(\n bounds.left + margin,\n Math.min(start.left, bounds.left + bounds.width - margin - bar.width),\n )\n return { top, left, placement }\n}\n\n/**\n * Where the card of an answer goes (spec `selection-actions.md`, \"Dove\n * arriva la risposta\"), in the coordinates of its `bounds`. The side is\n * decided for the tallest card, so a growing answer never moves it across\n * the text: above the start as the bar, below when the tallest card fits\n * only there, otherwise on the side with more room, and no taller than that\n * room. On a touch screen the other way round, as the bar there: the text\n * stays selected with the system's menu above it, and the card keeps clear\n * of that menu and of the handles. It grows away from the text, and is no\n * wider than its box: the visible part of the window, a pinch included.\n */\nexport function selectionCardPosition({\n start,\n bottom,\n bounds,\n card,\n tallest,\n shortest,\n touch = false,\n gap = 8,\n margin = 8,\n}: {\n start: Pick<DOMRect, 'top' | 'left'>\n bottom: number\n bounds: Pick<DOMRect, 'top' | 'left' | 'width' | 'height'>\n /** The card as drawn now: it grows with the answer. */\n card: { width: number; height: number }\n /** The tallest the card gets. */\n tallest: number\n /** The least room it opens in: with less on both sides it overlaps the selection rather than shrink. */\n shortest: number\n touch?: boolean\n gap?: number\n margin?: number\n}): { top: number; left: number; maxHeight: number; maxWidth: number } {\n const systemMenu = touch ? SYSTEM_MENU_ROOM : 0\n const gapBelow = touch ? Math.max(gap, SELECTION_HANDLES_ROOM) : gap\n const room = {\n above: start.top - gap - systemMenu - (bounds.top + margin),\n below: bounds.top + bounds.height - margin - (bottom + gapBelow),\n }\n const [first, second] = touch\n ? (['below', 'above'] as const)\n : (['above', 'below'] as const)\n const side =\n room[first] >= tallest ||\n (room[second] < tallest && room[second] <= room[first])\n ? first\n : second\n const maxHeight = Math.min(\n tallest,\n bounds.height - 2 * margin,\n Math.max(shortest, room[side]),\n )\n const shown = Math.min(card.height, maxHeight)\n const top = Math.max(\n bounds.top + margin,\n Math.min(\n side === 'above'\n ? start.top - gap - systemMenu - shown\n : bottom + gapBelow,\n bounds.top + bounds.height - margin - shown,\n ),\n )\n const { left } = selectionBarPosition({\n start,\n bottom,\n bounds,\n bar: { width: card.width, height: shown },\n gap,\n margin,\n })\n return { top, left, maxHeight, maxWidth: bounds.width - 2 * margin }\n}\n"],"mappings":";;;;;;AAOA,IAAasC,KAAiB;CAC1B,QAAQ;CAER,QAAQ;CAER,WAAW;CAEX,SAAS;CAET,OAAO;AACX,GAMaC,KAAoB;CAC7B,UAAU;CAEV,MAAM;CACN,UAAU;CACV,iBAAiB;CACjB,oBAAoB;CACpB,cAAc;CAEd,QAAQ;CAKR,WAAW;AACf,GAMaC,KAAuB;CAChC;CACA;CACA;AACJ,GAGaC,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