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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/dist/_chunks/{PkFilePreview-yKT0QkEB.js → PkFilePreview-3_ZmPzQO.js} +3 -3
  2. package/dist/_chunks/{PkFilePreview-yKT0QkEB.js.map → PkFilePreview-3_ZmPzQO.js.map} +1 -1
  3. package/dist/_chunks/{PkFilePreviewDialog-B4yKQbLi.js → PkFilePreviewDialog-m3iqn0rl.js} +2 -2
  4. package/dist/_chunks/{PkFilePreviewDialog-B4yKQbLi.js.map → PkFilePreviewDialog-m3iqn0rl.js.map} +1 -1
  5. package/dist/_chunks/{PkImageEditorDialog-BF6tQvTY.js → PkImageEditorDialog-W8TCEHBJ.js} +2 -2
  6. package/dist/_chunks/{PkImageEditorDialog-BF6tQvTY.js.map → PkImageEditorDialog-W8TCEHBJ.js.map} +1 -1
  7. package/dist/_chunks/{PkSelectionActions-J1AaO8Of.js → PkSelectionActions-B14kAu8T.js} +2 -2
  8. package/dist/_chunks/{PkSelectionActions-J1AaO8Of.js.map → PkSelectionActions-B14kAu8T.js.map} +1 -1
  9. package/dist/_chunks/{PkStreamingMarkdown-CvIq4j9U.js → PkStreamingMarkdown-Df_VzmC0.js} +2 -2
  10. package/dist/_chunks/{PkStreamingMarkdown-CvIq4j9U.js.map → PkStreamingMarkdown-Df_VzmC0.js.map} +1 -1
  11. package/dist/_chunks/{PkToolChatFile-Y5CR96-B.js → PkToolChatFile-BXrgzaIj.js} +2 -2
  12. package/dist/_chunks/{PkToolChatFile-Y5CR96-B.js.map → PkToolChatFile-BXrgzaIj.js.map} +1 -1
  13. package/dist/_chunks/{PkToolShowArtifact-CBsIMKuq.js → PkToolShowArtifact-Df2ibXU_.js} +2 -2
  14. package/dist/_chunks/{PkToolShowArtifact-CBsIMKuq.js.map → PkToolShowArtifact-Df2ibXU_.js.map} +1 -1
  15. package/dist/_chunks/{PkToolShowContactForm-D8tYijcg.js → PkToolShowContactForm-CfW3f_Zs.js} +2 -2
  16. package/dist/_chunks/{PkToolShowContactForm-D8tYijcg.js.map → PkToolShowContactForm-CfW3f_Zs.js.map} +1 -1
  17. package/dist/_chunks/{PkToolShowForm-CM63L5WC.js → PkToolShowForm-Chj3bqAn.js} +3 -3
  18. package/dist/_chunks/{PkToolShowForm-CM63L5WC.js.map → PkToolShowForm-Chj3bqAn.js.map} +1 -1
  19. package/dist/_chunks/{PkToolShowSources-BoJmMb4K.js → PkToolShowSources-B9qNtyum.js} +2 -2
  20. package/dist/_chunks/{PkToolShowSources-BoJmMb4K.js.map → PkToolShowSources-B9qNtyum.js.map} +1 -1
  21. package/dist/_chunks/{utils-BYVRPDrv.js → utils-C1mMVCFZ.js} +4 -3
  22. package/dist/_chunks/utils-C1mMVCFZ.js.map +1 -0
  23. package/dist/ai-elements.es.js +604 -587
  24. package/dist/ai-elements.es.js.map +1 -1
  25. package/dist-vue/PkChatbot.js +1 -1
  26. package/dist-vue/PkChatbotEmptyState.js +1 -1
  27. package/dist-vue/PkChatbotInput.js +1 -1
  28. package/dist-vue/PkChatbotLocalFolders.js +1 -1
  29. package/dist-vue/PkChatbotMessages.js +1 -1
  30. package/dist-vue/PkChatbotStepPayload.js +1 -1
  31. package/dist-vue/PkChatbotStepToolDetail.js +1 -1
  32. package/dist-vue/PkChatbotSteps.js +1 -1
  33. package/dist-vue/PkChatbotViewChat.js +1 -1
  34. package/dist-vue/PkChatbotViewConversations.js +1 -1
  35. package/dist-vue/PkChatbotViewFiles.js +1 -1
  36. package/dist-vue/PkChatbotViewProfile.js +1 -1
  37. package/dist-vue/_chunks/{PkChatbot-CrHeZSwq.js → PkChatbot-BWgqvPsG.js} +8 -8
  38. package/dist-vue/_chunks/{PkChatbot-CrHeZSwq.js.map → PkChatbot-BWgqvPsG.js.map} +1 -1
  39. package/dist-vue/_chunks/{PkChatbotEmptyState-BSdctGUp.js → PkChatbotEmptyState-CS0l2BBa.js} +2 -2
  40. package/dist-vue/_chunks/{PkChatbotEmptyState-BSdctGUp.js.map → PkChatbotEmptyState-CS0l2BBa.js.map} +1 -1
  41. package/dist-vue/_chunks/{PkChatbotInput-Bkr2FMAR.js → PkChatbotInput-9PwloFKx.js} +29 -15
  42. package/dist-vue/_chunks/PkChatbotInput-9PwloFKx.js.map +1 -0
  43. package/dist-vue/_chunks/PkChatbotLocalFolders-D7kxpwR2.js +122 -0
  44. package/dist-vue/_chunks/PkChatbotLocalFolders-D7kxpwR2.js.map +1 -0
  45. package/dist-vue/_chunks/{PkChatbotMessages-Cf19Jak8.js → PkChatbotMessages-CU0y2j8g.js} +16 -16
  46. package/dist-vue/_chunks/{PkChatbotMessages-Cf19Jak8.js.map → PkChatbotMessages-CU0y2j8g.js.map} +1 -1
  47. package/dist-vue/_chunks/{PkChatbotStepPayload-BWeGBOGl.js → PkChatbotStepPayload-Ds9rz4MI.js} +2 -2
  48. package/dist-vue/_chunks/{PkChatbotStepPayload-BWeGBOGl.js.map → PkChatbotStepPayload-Ds9rz4MI.js.map} +1 -1
  49. package/dist-vue/_chunks/{PkChatbotStepToolDetail-k_purHyE.js → PkChatbotStepToolDetail-C_xWXZkE.js} +3 -3
  50. package/dist-vue/_chunks/{PkChatbotStepToolDetail-k_purHyE.js.map → PkChatbotStepToolDetail-C_xWXZkE.js.map} +1 -1
  51. package/dist-vue/_chunks/{PkChatbotSteps-DvYhk_xP.js → PkChatbotSteps-CjX5nxsq.js} +6 -6
  52. package/dist-vue/_chunks/{PkChatbotSteps-DvYhk_xP.js.map → PkChatbotSteps-CjX5nxsq.js.map} +1 -1
  53. package/dist-vue/_chunks/{PkChatbotViewChat-D-tjQF-v.js → PkChatbotViewChat-D5DiEgwE.js} +234 -237
  54. package/dist-vue/_chunks/PkChatbotViewChat-D5DiEgwE.js.map +1 -0
  55. package/dist-vue/_chunks/{PkChatbotViewConversations-BYn6wfoM.js → PkChatbotViewConversations-Bj77_upQ.js} +4 -4
  56. package/dist-vue/_chunks/{PkChatbotViewConversations-BYn6wfoM.js.map → PkChatbotViewConversations-Bj77_upQ.js.map} +1 -1
  57. package/dist-vue/_chunks/{PkChatbotViewFiles-BWD7GF4M.js → PkChatbotViewFiles-nL2UGO-g.js} +2 -2
  58. package/dist-vue/_chunks/{PkChatbotViewFiles-BWD7GF4M.js.map → PkChatbotViewFiles-nL2UGO-g.js.map} +1 -1
  59. package/dist-vue/_chunks/{PkChatbotViewProfile-D5LQ_IB6.js → PkChatbotViewProfile-B8xPFxkz.js} +2 -2
  60. package/dist-vue/_chunks/{PkChatbotViewProfile-D5LQ_IB6.js.map → PkChatbotViewProfile-B8xPFxkz.js.map} +1 -1
  61. package/dist-vue/_chunks/{PkFilePreview-CURIA-I5.js → PkFilePreview-D6VCM-tr.js} +3 -3
  62. package/dist-vue/_chunks/{PkFilePreview-CURIA-I5.js.map → PkFilePreview-D6VCM-tr.js.map} +1 -1
  63. package/dist-vue/_chunks/{PkFilePreviewDialog-Cmic1Xl-.js → PkFilePreviewDialog-CwkET8_p.js} +2 -2
  64. package/dist-vue/_chunks/{PkFilePreviewDialog-Cmic1Xl-.js.map → PkFilePreviewDialog-CwkET8_p.js.map} +1 -1
  65. package/dist-vue/_chunks/{PkImageEditorDialog-bt-_WXJ7.js → PkImageEditorDialog-CXSSDTtp.js} +2 -2
  66. package/dist-vue/_chunks/{PkImageEditorDialog-bt-_WXJ7.js.map → PkImageEditorDialog-CXSSDTtp.js.map} +1 -1
  67. package/dist-vue/_chunks/{PkStreamingMarkdown-D38PPSbB.js → PkStreamingMarkdown-D5ad7uGI.js} +2 -2
  68. package/dist-vue/_chunks/{PkStreamingMarkdown-D38PPSbB.js.map → PkStreamingMarkdown-D5ad7uGI.js.map} +1 -1
  69. package/dist-vue/_chunks/{PkToolChatFile-Dvn6Jg9n.js → PkToolChatFile-DDVwPfee.js} +2 -2
  70. package/dist-vue/_chunks/{PkToolChatFile-Dvn6Jg9n.js.map → PkToolChatFile-DDVwPfee.js.map} +1 -1
  71. package/dist-vue/_chunks/{PkToolShowArtifact-Clkqoz26.js → PkToolShowArtifact-CdS7BNoU.js} +2 -2
  72. package/dist-vue/_chunks/{PkToolShowArtifact-Clkqoz26.js.map → PkToolShowArtifact-CdS7BNoU.js.map} +1 -1
  73. package/dist-vue/_chunks/{PkToolShowChart-RLAsKQT7.js → PkToolShowChart-E2NW5ess.js} +2 -2
  74. package/dist-vue/_chunks/{PkToolShowChart-RLAsKQT7.js.map → PkToolShowChart-E2NW5ess.js.map} +1 -1
  75. package/dist-vue/_chunks/{PkToolShowContactForm-BSDtKWWD.js → PkToolShowContactForm-COu43u5z.js} +2 -2
  76. package/dist-vue/_chunks/{PkToolShowContactForm-BSDtKWWD.js.map → PkToolShowContactForm-COu43u5z.js.map} +1 -1
  77. package/dist-vue/_chunks/{PkToolShowDiagram-9EYiOJXE.js → PkToolShowDiagram-BOGh8Z0j.js} +2 -2
  78. package/dist-vue/_chunks/{PkToolShowDiagram-9EYiOJXE.js.map → PkToolShowDiagram-BOGh8Z0j.js.map} +1 -1
  79. package/dist-vue/_chunks/{PkToolShowForm-mXmiZPIW.js → PkToolShowForm-D3n6fxtt.js} +3 -3
  80. package/dist-vue/_chunks/{PkToolShowForm-mXmiZPIW.js.map → PkToolShowForm-D3n6fxtt.js.map} +1 -1
  81. package/dist-vue/_chunks/{PkToolShowImageGallery-B2phVedq.js → PkToolShowImageGallery-D3Z5vTb0.js} +2 -2
  82. package/dist-vue/_chunks/{PkToolShowImageGallery-B2phVedq.js.map → PkToolShowImageGallery-D3Z5vTb0.js.map} +1 -1
  83. package/dist-vue/_chunks/{PkToolShowProductList-BX9D6A8k.js → PkToolShowProductList-4mkoLMOz.js} +2 -2
  84. package/dist-vue/_chunks/{PkToolShowProductList-BX9D6A8k.js.map → PkToolShowProductList-4mkoLMOz.js.map} +1 -1
  85. package/dist-vue/_chunks/{PkToolShowSources-B0Xw8RR2.js → PkToolShowSources-DkpLjqfn.js} +2 -2
  86. package/dist-vue/_chunks/{PkToolShowSources-B0Xw8RR2.js.map → PkToolShowSources-DkpLjqfn.js.map} +1 -1
  87. package/dist-vue/_chunks/{PkToolShowVideo-DyOPeNq_.js → PkToolShowVideo-DyjqJfqW.js} +2 -2
  88. package/dist-vue/_chunks/{PkToolShowVideo-DyOPeNq_.js.map → PkToolShowVideo-DyjqJfqW.js.map} +1 -1
  89. package/dist-vue/_chunks/{PkToolShowWebPages-DajE3TAx.js → PkToolShowWebPages-BSvuIrSs.js} +2 -2
  90. package/dist-vue/_chunks/{PkToolShowWebPages-DajE3TAx.js.map → PkToolShowWebPages-BSvuIrSs.js.map} +1 -1
  91. package/dist-vue/_chunks/{localFolders-D8DxM-5y.js → localFolders-Dn8jAVz4.js} +4 -3
  92. package/dist-vue/_chunks/localFolders-Dn8jAVz4.js.map +1 -0
  93. package/dist-vue/_chunks/{useChatbotStore-DCE7Ig6x.js → useChatbotStore-ZA6_oD5a.js} +2 -2
  94. package/dist-vue/_chunks/{useChatbotStore-DCE7Ig6x.js.map → useChatbotStore-ZA6_oD5a.js.map} +1 -1
  95. package/dist-vue/_chunks/{utils-SmeQuVL1.js → utils-BDXwCfXk.js} +2 -2
  96. package/dist-vue/_chunks/{utils-SmeQuVL1.js.map → utils-BDXwCfXk.js.map} +1 -1
  97. package/dist-vue/composables.js +12 -2
  98. package/dist-vue/composables.js.map +1 -1
  99. package/dist-vue/index.js +25 -25
  100. package/dist-vue/locales.js +12 -2
  101. package/dist-vue/packages/components/src/chat/PkChatbotInput.d.ts +10 -2
  102. package/dist-vue/packages/components/src/chat/PkChatbotLocalFolders.d.ts +12 -9
  103. package/dist-vue/style.css +1 -1
  104. package/package.json +1 -1
  105. package/dist/_chunks/utils-BYVRPDrv.js.map +0 -1
  106. package/dist-vue/_chunks/PkChatbotInput-Bkr2FMAR.js.map +0 -1
  107. package/dist-vue/_chunks/PkChatbotLocalFolders-CSvqh_Cx.js +0 -126
  108. package/dist-vue/_chunks/PkChatbotLocalFolders-CSvqh_Cx.js.map +0 -1
  109. package/dist-vue/_chunks/PkChatbotViewChat-D-tjQF-v.js.map +0 -1
  110. package/dist-vue/_chunks/localFolders-D8DxM-5y.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"localFolders-D8DxM-5y.js","names":["formatBytes","LOCAL_FOLDER_READ_MAX_CHARS","isExcludedLocalFile","isExcludedLocalPath","HOST_TOOL_RESULT_MAX_CHARS","LOCAL_FOLDER_FIND_MAX_FILES","isExcludedLocalDirectory","isTextPart","part","isToolPart","getToolPartName","isFilePart","getFilePartMedia","media","getFilePartTranscript","transcript","withAudioTranscripts","messages","own","updates","update","message","storedFileName","isReasoningPart","hasPartText","hasTextPart","getTextPart","parts","removeAccents","str","fromAnyCase","toKebabCase","toSnakeCase","capitalizeFirstLetter","decodeTextBytes","utf16","bytes","cut","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","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"],"sources":["../../../../packages/utils/src/message.ts","../../../../packages/utils/src/text.ts","../../../../packages/composable/src/chatbot/localFolders.ts"],"sourcesContent":["import type { UIMessage } from 'ai'\nimport type { ChatAudioTranscript, MediaSource, UIChatMessage } from 'models'\n\ntype MessagePart = UIMessage['parts'][number]\n\nexport function isTextPart(\n part?: MessagePart | null | undefined,\n): part is Extract<MessagePart, { type: 'text' }> {\n if (!part) {\n return false\n }\n return part.type === 'text'\n}\n\nexport function isToolPart(\n part?: MessagePart | null | undefined,\n): part is Extract<MessagePart, { type: `tool-${string}` }> {\n if (!part) {\n return false\n }\n return part.type.startsWith('tool-')\n}\n\nexport function getToolPartName(part?: MessagePart): string {\n if (!isToolPart(part)) {\n return ''\n }\n return part.type.slice('tool-'.length)\n}\n\nexport function isFilePart(\n part?: MessagePart | null | undefined,\n): part is Extract<MessagePart, { type: 'file' }> {\n if (!part) {\n return false\n }\n return part.type === 'file'\n}\n\n/**\n * Returns the persisted `MediaSource` carried by a file part, when present.\n * Uploaded attachments stash the full upload metadata (size, extension,\n * storage handle…) under `providerMetadata['8bot'].media`, which survives\n * persistence — so saved messages can surface size/details without a schema\n * change or extra request.\n */\nexport function getFilePartMedia(\n part?: MessagePart | null | undefined,\n): MediaSource | undefined {\n if (!isFilePart(part)) {\n return undefined\n }\n const container = part.providerMetadata?.['8bot'] as\n { media?: unknown } | undefined\n const media = container?.media\n return media && typeof media === 'object' && !Array.isArray(media)\n ? (media as MediaSource)\n : undefined\n}\n\n/**\n * Returns the transcript a chat turn stamped on an audio file part, under\n * `providerMetadata['8bot'].transcript` (spec `audio-file-transcription.md`,\n * D4), when present.\n */\nexport function getFilePartTranscript(\n part?: MessagePart | null | undefined,\n): ChatAudioTranscript | undefined {\n if (!isFilePart(part)) {\n return undefined\n }\n const container = part.providerMetadata?.['8bot'] as\n { transcript?: unknown } | undefined\n const transcript = container?.transcript\n return transcript &&\n typeof transcript === 'object' &&\n !Array.isArray(transcript)\n ? (transcript as ChatAudioTranscript)\n : undefined\n}\n\n/** The transcript a turn made of one audio the client sent, as streamed. */\nexport interface AudioTranscriptUpdate {\n messageId: string\n storedFileName: string\n transcript: ChatAudioTranscript\n}\n\n/**\n * The messages with the transcripts a turn streamed (`data-audioTranscripts`)\n * stamped on their audio parts: the stored message has them, the client's\n * copy of the message it sent gets them here. What the updates do not name is\n * returned as it was, the same objects.\n */\nexport function withAudioTranscripts<T extends UIMessage>(\n messages: T[],\n updates: AudioTranscriptUpdate[],\n): T[] {\n return messages.map((message) => {\n const own = updates.filter((update) => update.messageId === message.id)\n if (own.length === 0) {\n return message\n }\n return {\n ...message,\n parts: message.parts.map((part) => {\n const update = own.find(\n ({ storedFileName }) =>\n storedFileName ===\n getFilePartMedia(part)?.storedFileName,\n )\n return update && isFilePart(part)\n ? {\n ...part,\n providerMetadata: {\n ...part.providerMetadata,\n '8bot': {\n ...part.providerMetadata?.['8bot'],\n transcript: update.transcript,\n },\n },\n }\n : part\n }),\n }\n })\n}\n\nexport function isReasoningPart(\n part?: MessagePart | null | undefined,\n): part is Extract<MessagePart, { type: 'reasoning' }> {\n if (!part) {\n return false\n }\n return part.type === 'reasoning'\n}\n\nexport function hasPartText(\n part?: MessagePart | null | undefined,\n): part is Extract<MessagePart, { text: string }> {\n if (!part) {\n return false\n }\n if (isTextPart(part)) {\n return true\n }\n return (\n 'text' in part &&\n part.text !== undefined &&\n part.text !== null &&\n part.text !== ''\n )\n}\n\nexport function hasTextPart(\n message?: UIMessage | UIChatMessage | null | undefined,\n): boolean {\n if (!message) {\n return false\n }\n return (message as UIMessage).parts.some((part) => isTextPart(part))\n}\n\nexport function getTextPart(\n message?: UIMessage | UIChatMessage | null | undefined,\n): string | undefined {\n if (!message) {\n return undefined\n }\n const parts = (message as UIMessage).parts\n if (!Array.isArray(parts)) {\n return undefined\n }\n const textPart = parts.find((part) => isTextPart(part))\n return textPart?.text\n}\n\nexport function getMessageText(\n message?: UIMessage | UIChatMessage | null | undefined,\n): string {\n if (!message) {\n return ''\n }\n const parts = (message as UIMessage).parts\n if (!Array.isArray(parts)) {\n return ''\n }\n return parts\n .filter((p): p is Extract<MessagePart, { type: 'text' }> =>\n isTextPart(p),\n )\n .map((p) => p.text)\n .join('')\n}\n","export const removeAccents = (str: string) =>\n str.normalize('NFD').replace(/[\\u0300-\\u036f]/g, '')\n\nexport const toCamelCase = <T extends string>(str?: string): T => {\n if (!str) {\n return '' as unknown as T\n }\n return removeAccents(str)\n .replace(/[^a-zA-Z0-9]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ''))\n .replace(/^(.)/, (match) => match.toLowerCase()) as unknown as T\n}\n\nexport const fromCamelCase = (str?: string): string => {\n if (!str) {\n return ''\n }\n return str.replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n}\n\nexport const fromAnyCase = (str?: string): string => {\n if (!str) {\n return ''\n }\n return str\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')\n .replace(/[-_]+/g, ' ')\n}\n\nexport const toPascalCase = <T extends string>(str?: string): T => {\n if (!str) {\n return '' as unknown as T\n }\n return removeAccents(str)\n .replace(/[^a-zA-Z0-9]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ''))\n .replace(/^(.)/, (match) => match.toUpperCase()) as unknown as T\n}\n\nexport const toKebabCase = <T extends string>(str?: string): T => {\n if (!str) {\n return '' as unknown as T\n }\n return removeAccents(str)\n .replace(/([a-z0-9])([A-Z])/g, '$1-$2')\n .replace(/[^a-zA-Z0-9]+/g, '-')\n .toLowerCase() as unknown as T\n}\n\nexport const fromKebabCase = (str?: string): string => {\n if (!str) {\n return ''\n }\n return str.replace(/-/g, ' ')\n}\n\nexport const toSnakeCase = <T extends string>(str?: string): T => {\n if (!str) {\n return '' as unknown as T\n }\n return removeAccents(str)\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/[^a-zA-Z0-9]+/g, '_')\n .toLowerCase() as unknown as T\n}\n\nexport const capitalizeFirstLetter = (str?: string) => {\n if (!str) {\n return ''\n }\n return str.charAt(0).toUpperCase() + str.slice(1)\n}\n\nexport const lowercaseFirstLetter = (str?: string) => {\n if (!str) {\n return ''\n }\n return str.charAt(0).toLowerCase() + str.slice(1)\n}\n\n/**\n * Text in UTF-16 when a byte order mark says so (Notepad's \"Unicode\", Excel's\n * \"Unicode text\"), in UTF-8, or else in Windows-1252, what an older editor\n * saves an Italian `.txt` in: every byte is a character there, and a binary\n * file is told apart by the NUL bytes it holds. Shared by the attachments the\n * backend reads and the folders the app's chat reads (spec\n * `chat-local-folders.md`).\n *\n * @param cut - whether `bytes` stop where the read did, not where the file\n * does: a character cut in half there is left out instead of failing the\n * decoding\n */\nexport const decodeTextBytes = (bytes: Uint8Array, cut: boolean): string => {\n const utf16 =\n bytes[0] === 0xff && bytes[1] === 0xfe\n ? 'utf-16le'\n : bytes[0] === 0xfe && bytes[1] === 0xff\n ? 'utf-16be'\n : undefined\n if (utf16) {\n return new TextDecoder(utf16).decode(bytes, { stream: cut })\n }\n try {\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes, {\n stream: cut,\n })\n } catch {\n return new TextDecoder('windows-1252').decode(bytes)\n }\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"],"mappings":";;;;AAKA,SAAgBO,EACZ,GAC8C;CAI9C,OAHKC,IAGEA,EAAK,SAAS,SAFV;AAGf;AAEA,SAAgBC,EACZ,GACwD;CAIxD,OAHKD,IAGEA,EAAK,KAAK,WAAW,OAAO,IAFxB;AAGf;AAEA,SAAgBE,EAAgB,GAA4B;CAIxD,OAHKD,EAAWD,CAAI,IAGbA,EAAK,KAAK,MAAM,CAAc,IAF1B;AAGf;AAEA,SAAgBG,EACZ,GAC8C;CAI9C,OAHKH,IAGEA,EAAK,SAAS,SAFV;AAGf;AASA,SAAgBI,EACZ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