Files
CrazyJasonwell fb40c9b109 add all
2025-10-25 20:35:10 +08:00

43 lines
169 KiB
JavaScript
Executable File

/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
var vi=Object.create;var hr=Object.defineProperty;var _i=Object.getOwnPropertyDescriptor;var Ai=Object.getOwnPropertyNames;var Pi=Object.getPrototypeOf,Ii=Object.prototype.hasOwnProperty;var xi=(n,e)=>{for(var t in e)hr(n,t,{get:e[t],enumerable:!0})},Xn=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ai(e))!Ii.call(n,s)&&s!==t&&hr(n,s,{get:()=>e[s],enumerable:!(r=_i(e,s))||r.enumerable});return n};var Ei=(n,e,t)=>(t=n!=null?vi(Pi(n)):{},Xn(e||!n||!n.__esModule?hr(t,"default",{value:n,enumerable:!0}):t,n)),Ci=n=>Xn(hr({},"__esModule",{value:!0}),n);var Pa={};xi(Pa,{default:()=>zr});module.exports=Ci(Pa);var le=require("obsidian");var Y=require("obsidian");var Gn={settings:{notice:'Dieses Plugin ist eine Konfigurationszentrale f\xFCr KI-Anbieter. Es macht selbst nichts, aber <a href="https://github.com/pfrankov/obsidian-ai-providers#required-by-plugins">andere Plugins</a> k\xF6nnen es nutzen, um KI-Einstellungen nicht mehrfach konfigurieren zu m\xFCssen.',configuredProviders:"KI-anbieter",addNewProvider:"Neuen anbieter hinzuf\xFCgen",addProvider:"Anbieter hinzuf\xFCgen",providerName:"Anbietername",providerNameDesc:"Geben Sie einen Namen f\xFCr diesen Anbieter ein",providerNamePlaceholder:"Mein anbieter",providerType:"Anbietertyp",providerTypeDesc:"W\xE4hlen Sie den KI-anbietertyp aus",providerUrl:"Anbieter-URL",providerUrlDesc:"Geben Sie die API-Endpunkt-URL ein",providerUrlPlaceholder:"https://...",apiKey:"API-Schl\xFCssel",apiKeyDesc:"Geben Sie Ihren API-Schl\xFCssel ein (falls erforderlich)",apiKeyPlaceholder:"sk-...",defaultModel:"Standardmodell",defaultModelDesc:"W\xE4hlen Sie das Standard-KI-Modell f\xFCr diesen Anbieter",save:"Speichern",cancel:"Abbrechen",options:"Optionen",delete:"L\xF6schen",duplicate:"Duplizieren",deleteConfirmation:'M\xF6chten Sie den Anbieter "{{name}}" wirklich l\xF6schen?',modelsUpdated:"Modellliste aktualisiert",refreshModelsList:"Modellliste aktualisieren",model:"Modell",modelDesc:"W\xE4hlen Sie das KI-Modell f\xFCr diesen Anbieter. <br>Oder <a>in den Textmodus wechseln</a>",modelTextDesc:"Geben Sie den KI-Modellnamen ein. <br>Oder <a>in den Dropdown-Modus wechseln</a>",modelTextOnlyDesc:"Geben Sie den KI-Modellnamen f\xFCr diesen Anbieter ein.",loadingModels:"Modelle werden geladen...",noModelsAvailable:"Keine Modelle verf\xFCgbar",editProvider:"Anbieter bearbeiten",developerSettings:"F\xFCr entwickler",developerSettingsDesc:"Zus\xE4tzliche Einstellungen f\xFCr Entwicklung und Debugging aktivieren",debugLogging:"Debug-protokollierung",debugLoggingDesc:"Detaillierte Protokollierung in der Konsole aktivieren",useNativeFetch:"Nativen fetch verwenden",useNativeFetchDesc:"Verwendet Fetch API anstelle von Obsidian f\xFCr besseres Debugging der Anfragen in DevTools"},modals:{confirm:"Best\xE4tigen",cancel:"Abbrechen"},errors:{failedToFetchModels:"Modelle konnten nicht abgerufen werden",failedToExecuteRequest:"Anfrage konnte nicht ausgef\xFChrt werden",failedToEmbed:"Fehler beim Generieren der Einbettungen",missingApiKey:"API-Schl\xFCssel ist erforderlich",missingUrl:"Anbieter-URL ist erforderlich",missingModel:"Modell muss ausgew\xE4hlt werden",pluginMustBeUpdated:"Plugin muss aktualisiert werden",pluginMustBeUpdatedFormatted:"Das Plugin muss aktualisiert werden, um mit dieser Version von AI Providers zu funktionieren",providerNameRequired:"Anbietername ist erforderlich",providerNameExists:'Ein Anbieter mit dem Namen "{{name}}" existiert bereits'}};var Qn={settings:{notice:"This plugin provides AI Provider integrations for other plugins. Configure your providers below.",configuredProviders:"AI providers",addNewProvider:"Add new provider",addProvider:"Add provider",providerName:"Provider name",providerNameDesc:"Enter a name for this provider",providerNamePlaceholder:"My provider",providerType:"Provider type",providerTypeDesc:"Select the type of AI provider",providerUrl:"Provider URL",providerUrlDesc:"Enter the API endpoint URL",providerUrlPlaceholder:"https://...",apiKey:"API key",apiKeyDesc:"Enter your API key (if required)",apiKeyPlaceholder:"sk-...",defaultModel:"Default model",defaultModelDesc:"Select the default AI model for this provider",save:"Save",cancel:"Cancel",options:"Options",delete:"Delete",duplicate:"Duplicate",deleteConfirmation:'Are you sure you want to delete provider "{{name}}"?',modelsUpdated:"Models list updated",refreshModelsList:"Refresh models list",model:"Model",modelDesc:"Select the AI model for this provider. <br>Or <a>switch to text mode</a>",modelTextDesc:"Enter the AI model name. <br>Or <a>switch to dropdown mode</a>",modelTextOnlyDesc:"Enter the AI model name for this provider.",loadingModels:"Loading models...",noModelsAvailable:"No models available",editProvider:"Edit provider",developerSettings:"For developers",developerSettingsDesc:"Enable additional settings for development and debugging",debugLogging:"Debug Logging",debugLoggingDesc:"Enable debug logging for troubleshooting",useNativeFetch:"Use native Fetch",useNativeFetchDesc:"Use native Fetch API instead of electron-specific implementation (may help with CORS issues)"},modals:{confirm:"Confirm",cancel:"Cancel"},errors:{failedToFetchModels:"Failed to fetch models",failedToExecuteRequest:"Failed to execute request",failedToEmbed:"Failed to generate embeddings",missingApiKey:"API key is required",missingUrl:"Provider URL is required",missingModel:"Model must be selected",pluginMustBeUpdated:"Plugin must be updated",pluginMustBeUpdatedFormatted:"Plugin must be updated to work with this version of AI Providers",providerNameRequired:"Provider name is required",providerNameExists:'A provider with the name "{{name}}" already exists'}};var Yn={settings:{notice:'\u042D\u0442\u043E\u0442 \u043F\u043B\u0430\u0433\u0438\u043D \u043F\u043E\u043C\u043E\u0433\u0430\u0435\u0442 \u043D\u0430\u0441\u0442\u0440\u0430\u0438\u0432\u0430\u0442\u044C AI-\u043F\u0440\u043E\u0432\u0430\u0439\u0434\u0435\u0440\u044B. \u0421\u0430\u043C \u043F\u043E \u0441\u0435\u0431\u0435 \u043E\u043D \u043D\u0438\u0447\u0435\u0433\u043E \u043D\u0435 \u0434\u0435\u043B\u0430\u0435\u0442, \u043D\u043E \u0441\u043B\u0443\u0436\u0438\u0442 \u043E\u0431\u0449\u0438\u043C \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435\u043C \u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A, \u043A\u043E\u0442\u043E\u0440\u044B\u043C \u043C\u043E\u0433\u0443\u0442 \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u044C\u0441\u044F <a href="https://github.com/pfrankov/obsidian-ai-providers#required-by-plugins">\u0434\u0440\u0443\u0433\u0438\u0435 \u043F\u043B\u0430\u0433\u0438\u043D\u044B</a> \u0432\u043C\u0435\u0441\u0442\u043E \u043F\u043E\u0432\u0442\u043E\u0440\u043D\u043E\u0439 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438.',configuredProviders:"AI \u043F\u0440\u043E\u0432\u0430\u0439\u0434\u0435\u0440\u044B",addNewProvider:"\u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u043D\u043E\u0432\u044B\u0439 \u043F\u0440\u043E\u0432\u0430\u0439\u0434\u0435\u0440",addProvider:"\u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u043F\u0440\u043E\u0432\u0430\u0439\u0434\u0435\u0440",providerName:"\u0418\u043C\u044F \u043F\u0440\u043E\u0432\u0430\u0439\u0434\u0435\u0440\u0430",providerNameDesc:"\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0438\u043C\u044F \u0434\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u043F\u0440\u043E\u0432\u0430\u0439\u0434\u0435\u0440\u0430",providerNamePlaceholder:"\u041C\u043E\u0439 \u043F\u0440\u043E\u0432\u0430\u0439\u0434\u0435\u0440",providerType:"\u0422\u0438\u043F \u043F\u0440\u043E\u0432\u0430\u0439\u0434\u0435\u0440\u0430",providerTypeDesc:"\u0412\u044B\u0431\u0435\u0440\u0438\u0442\u0435 \u0442\u0438\u043F AI-\u043F\u0440\u043E\u0432\u0430\u0439\u0434\u0435\u0440\u0430",providerUrl:"URL \u043F\u0440\u043E\u0432\u0430\u0439\u0434\u0435\u0440\u0430",providerUrlDesc:"\u0412\u0432\u0435\u0434\u0438\u0442\u0435 URL \u043A\u043E\u043D\u0435\u0447\u043D\u043E\u0439 \u0442\u043E\u0447\u043A\u0438 API",providerUrlPlaceholder:"https://...",apiKey:"API-\u043A\u043B\u044E\u0447",apiKeyDesc:"\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0432\u0430\u0448 API \u043A\u043B\u044E\u0447 (\u0435\u0441\u043B\u0438 \u0442\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044F)",apiKeyPlaceholder:"sk-...",defaultModel:"\u041C\u043E\u0434\u0435\u043B\u044C \u043F\u043E \u0443\u043C\u043E\u043B\u0447\u0430\u043D\u0438\u044E",defaultModelDesc:"\u0412\u044B\u0431\u0435\u0440\u0438\u0442\u0435 \u043C\u043E\u0434\u0435\u043B\u044C AI \u043F\u043E \u0443\u043C\u043E\u043B\u0447\u0430\u043D\u0438\u044E \u0434\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u043F\u0440\u043E\u0432\u0430\u0439\u0434\u0435\u0440\u0430",save:"\u0421\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C",cancel:"\u041E\u0442\u043C\u0435\u043D\u0430",options:"\u041D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438",delete:"\u0423\u0434\u0430\u043B\u0438\u0442\u044C",duplicate:"\u0414\u0443\u0431\u043B\u0438\u0440\u043E\u0432\u0430\u0442\u044C",deleteConfirmation:'\u0412\u044B \u0443\u0432\u0435\u0440\u0435\u043D\u044B, \u0447\u0442\u043E \u0445\u043E\u0442\u0438\u0442\u0435 \u0443\u0434\u0430\u043B\u0438\u0442\u044C \u043F\u0440\u043E\u0432\u0430\u0439\u0434\u0435\u0440\u0430 "{{name}}"?',modelsUpdated:"\u0421\u043F\u0438\u0441\u043E\u043A \u043C\u043E\u0434\u0435\u043B\u0435\u0439 \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D",refreshModelsList:"\u041E\u0431\u043D\u043E\u0432\u0438\u0442\u044C \u0441\u043F\u0438\u0441\u043E\u043A \u043C\u043E\u0434\u0435\u043B\u0435\u0439",model:"\u041C\u043E\u0434\u0435\u043B\u044C",modelDesc:"\u0412\u044B\u0431\u0435\u0440\u0438\u0442\u0435 AI \u043C\u043E\u0434\u0435\u043B\u044C \u0434\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u043F\u0440\u043E\u0432\u0430\u0439\u0434\u0435\u0440\u0430. <br>\u0418\u043B\u0438 <a>\u043F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u0441\u044F \u0432 \u0442\u0435\u043A\u0441\u0442\u043E\u0432\u044B\u0439 \u0440\u0435\u0436\u0438\u043C</a>",modelTextDesc:"\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u043D\u0430\u0437\u0432\u0430\u043D\u0438\u0435 AI \u043C\u043E\u0434\u0435\u043B\u0438. <br>\u0418\u043B\u0438 <a>\u043F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u0441\u044F \u0432 \u0440\u0435\u0436\u0438\u043C \u0432\u044B\u043F\u0430\u0434\u0430\u044E\u0449\u0435\u0433\u043E \u0441\u043F\u0438\u0441\u043A\u0430</a>",modelTextOnlyDesc:"\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u043D\u0430\u0437\u0432\u0430\u043D\u0438\u0435 AI \u043C\u043E\u0434\u0435\u043B\u0438 \u0434\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u043F\u0440\u043E\u0432\u0430\u0439\u0434\u0435\u0440\u0430.",loadingModels:"\u0417\u0430\u0433\u0440\u0443\u0437\u043A\u0430 \u043C\u043E\u0434\u0435\u043B\u0435\u0439...",noModelsAvailable:"\u041D\u0435\u0442 \u0434\u043E\u0441\u0442\u0443\u043F\u043D\u044B\u0445 \u043C\u043E\u0434\u0435\u043B\u0435\u0439",editProvider:"\u0420\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u043F\u0440\u043E\u0432\u0430\u0439\u0434\u0435\u0440\u0430",developerSettings:"\u0414\u043B\u044F \u0440\u0430\u0437\u0440\u0430\u0431\u043E\u0442\u0447\u0438\u043A\u043E\u0432",developerSettingsDesc:"\u0412\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u0434\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u044B\u0435 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438 \u0434\u043B\u044F \u0440\u0430\u0437\u0440\u0430\u0431\u043E\u0442\u043A\u0438 \u0438 \u043E\u0442\u043B\u0430\u0434\u043A\u0438",debugLogging:"\u041E\u0442\u043B\u0430\u0434\u043E\u0447\u043D\u043E\u0435 \u043B\u043E\u0433\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435",debugLoggingDesc:"\u0412\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u043F\u043E\u0434\u0440\u043E\u0431\u043D\u043E\u0435 \u043B\u043E\u0433\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435 \u0432 \u043A\u043E\u043D\u0441\u043E\u043B\u0438",useNativeFetch:"\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u044C \u043D\u0430\u0442\u0438\u0432\u043D\u044B\u0439 Fetch",useNativeFetchDesc:"\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u044C Fetch API \u0432\u043C\u0435\u0441\u0442\u043E Obsidian \u0434\u043B\u044F \u0443\u0434\u043E\u0431\u043D\u043E\u0439 \u043E\u0442\u043B\u0430\u0434\u043A\u0438 \u0437\u0430\u043F\u0440\u043E\u0441\u043E\u0432 \u0432 DevTools"},modals:{confirm:"\u041F\u043E\u0434\u0442\u0432\u0435\u0440\u0434\u0438\u0442\u044C",cancel:"\u041E\u0442\u043C\u0435\u043D\u0430"},errors:{failedToFetchModels:"\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C \u0441\u043F\u0438\u0441\u043E\u043A \u043C\u043E\u0434\u0435\u043B\u0435\u0439",failedToExecuteRequest:"\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0432\u044B\u043F\u043E\u043B\u043D\u0438\u0442\u044C \u0437\u0430\u043F\u0440\u043E\u0441",failedToEmbed:"\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0441\u043E\u0437\u0434\u0430\u0442\u044C \u044D\u043C\u0431\u0435\u0434\u0434\u0438\u043D\u0433\u0438",missingApiKey:"\u0422\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044F API \u043A\u043B\u044E\u0447",missingUrl:"\u0422\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044F URL \u043F\u0440\u043E\u0432\u0430\u0439\u0434\u0435\u0440\u0430",missingModel:"\u041D\u0435\u043E\u0431\u0445\u043E\u0434\u0438\u043C\u043E \u0432\u044B\u0431\u0440\u0430\u0442\u044C \u043C\u043E\u0434\u0435\u043B\u044C",pluginMustBeUpdated:"\u041F\u043B\u0430\u0433\u0438\u043D \u0442\u0440\u0435\u0431\u0443\u0435\u0442 \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u044F",pluginMustBeUpdatedFormatted:"\u0414\u043B\u044F \u0440\u0430\u0431\u043E\u0442\u044B \u0441 \u044D\u0442\u043E\u0439 \u0432\u0435\u0440\u0441\u0438\u0435\u0439 AI Providers \u0442\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044F \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0435 \u043F\u043B\u0430\u0433\u0438\u043D\u0430",providerNameRequired:"\u0422\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044F \u0438\u043C\u044F \u043F\u0440\u043E\u0432\u0430\u0439\u0434\u0435\u0440\u0430",providerNameExists:'\u041F\u0440\u043E\u0432\u0430\u0439\u0434\u0435\u0440 \u0441 \u0438\u043C\u0435\u043D\u0435\u043C "{{name}}" \u0443\u0436\u0435 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442'}};var Zn={settings:{notice:'\u6B64\u63D2\u4EF6\u662F AI \u63D0\u4F9B\u5546\u7684\u914D\u7F6E\u4E2D\u5FC3\u3002\u5B83\u672C\u8EAB\u4E0D\u63D0\u4F9B\u4EFB\u4F55\u529F\u80FD\uFF0C\u4F46<a href="https://github.com/pfrankov/obsidian-ai-providers#required-by-plugins">\u5176\u4ED6\u63D2\u4EF6</a>\u53EF\u4EE5\u4F7F\u7528\u5B83\u6765\u907F\u514D\u91CD\u590D\u914D\u7F6E AI \u8BBE\u7F6E\u3002',configuredProviders:"AI \u670D\u52A1\u63D0\u4F9B\u5546",addNewProvider:"\u6DFB\u52A0\u65B0\u7684\u670D\u52A1\u63D0\u4F9B\u5546",addProvider:"\u6DFB\u52A0\u63D0\u4F9B\u5546",providerName:"\u63D0\u4F9B\u5546\u540D\u79F0",providerNameDesc:"\u4E3A\u6B64\u670D\u52A1\u63D0\u4F9B\u5546\u8F93\u5165\u540D\u79F0",providerNamePlaceholder:"\u6211\u7684\u670D\u52A1\u63D0\u4F9B\u5546",providerType:"\u63D0\u4F9B\u5546\u7C7B\u578B",providerTypeDesc:"\u9009\u62E9 AI \u670D\u52A1\u63D0\u4F9B\u5546\u7C7B\u578B",providerUrl:"\u670D\u52A1\u5730\u5740",providerUrlDesc:"\u8F93\u5165 API \u63A5\u53E3\u5730\u5740",providerUrlPlaceholder:"https://...",apiKey:"API \u5BC6\u94A5",apiKeyDesc:"\u8F93\u5165\u60A8\u7684 API \u5BC6\u94A5\uFF08\u5982\u9700\u8981\uFF09",apiKeyPlaceholder:"sk-...",defaultModel:"\u9ED8\u8BA4\u6A21\u578B",defaultModelDesc:"\u9009\u62E9\u6B64\u63D0\u4F9B\u5546\u7684\u9ED8\u8BA4 AI \u6A21\u578B",save:"\u4FDD\u5B58",cancel:"\u53D6\u6D88",options:"\u9009\u9879",delete:"\u5220\u9664",duplicate:"\u590D\u5236",deleteConfirmation:'\u786E\u5B9A\u8981\u5220\u9664\u63D0\u4F9B\u5546"{{name}}"\u5417\uFF1F',modelsUpdated:"\u6A21\u578B\u5217\u8868\u5DF2\u66F4\u65B0",refreshModelsList:"\u5237\u65B0\u6A21\u578B\u5217\u8868",model:"\u6A21\u578B",modelDesc:"\u9009\u62E9\u6B64\u63D0\u4F9B\u5546\u7684 AI \u6A21\u578B\u3002<br>\u6216<a>\u5207\u6362\u5230\u6587\u672C\u6A21\u5F0F</a>",modelTextDesc:"\u8F93\u5165 AI \u6A21\u578B\u540D\u79F0\u3002<br>\u6216<a>\u5207\u6362\u5230\u4E0B\u62C9\u6A21\u5F0F</a>",modelTextOnlyDesc:"\u8F93\u5165\u6B64\u63D0\u4F9B\u5546\u7684 AI \u6A21\u578B\u540D\u79F0\u3002",loadingModels:"\u6B63\u5728\u52A0\u8F7D\u6A21\u578B...",noModelsAvailable:"\u6CA1\u6709\u53EF\u7528\u7684\u6A21\u578B",editProvider:"\u7F16\u8F91\u63D0\u4F9B\u5546",developerSettings:"\u5F00\u53D1\u8005\u9009\u9879",developerSettingsDesc:"\u542F\u7528\u989D\u5916\u7684\u5F00\u53D1\u548C\u8C03\u8BD5\u8BBE\u7F6E",debugLogging:"\u8C03\u8BD5\u65E5\u5FD7",debugLoggingDesc:"\u5728\u63A7\u5236\u53F0\u542F\u7528\u8BE6\u7EC6\u65E5\u5FD7\u8BB0\u5F55",useNativeFetch:"\u4F7F\u7528\u539F\u751F Fetch",useNativeFetchDesc:"\u4F7F\u7528 Fetch API \u66FF\u4EE3 Obsidian\uFF0C\u4EE5\u4FBF\u5728 DevTools \u4E2D\u66F4\u597D\u5730\u8C03\u8BD5\u8BF7\u6C42"},modals:{confirm:"\u786E\u8BA4",cancel:"\u53D6\u6D88"},errors:{failedToFetchModels:"\u83B7\u53D6\u6A21\u578B\u5217\u8868\u5931\u8D25",failedToExecuteRequest:"\u8BF7\u6C42\u6267\u884C\u5931\u8D25",failedToEmbed:"\u751F\u6210\u5D4C\u5165\u5931\u8D25",missingApiKey:"\u9700\u8981\u63D0\u4F9B API \u5BC6\u94A5",missingUrl:"\u9700\u8981\u63D0\u4F9B\u670D\u52A1\u5730\u5740",missingModel:"\u9700\u8981\u9009\u62E9\u6A21\u578B",pluginMustBeUpdated:"\u63D2\u4EF6\u9700\u8981\u66F4\u65B0",pluginMustBeUpdatedFormatted:"\u63D2\u4EF6\u9700\u8981\u66F4\u65B0\u624D\u80FD\u4E0E\u6B64\u7248\u672C\u7684 AI Providers \u4E00\u8D77\u4F7F\u7528",providerNameRequired:"\u9700\u8981\u63D0\u4F9B\u5546\u540D\u79F0",providerNameExists:'\u540D\u4E3A"{{name}}"\u7684\u63D0\u4F9B\u5546\u5DF2\u5B58\u5728'}};var Kr=class{constructor(){this.enabled=!1}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}log(e,...t){if(!this.enabled)return;let r=new Date().toISOString(),s=`[AI Providers ${e.toUpperCase()}] ${r}:`;switch(e){case"debug":console.log(s,...t);break;case"info":console.info(s,...t);break;case"warn":console.warn(s,...t);break;case"error":console.error(s,...t);break}}debug(...e){this.log("debug",...e)}info(...e){this.log("info",...e)}warn(...e){this.log("warn",...e)}error(...e){this.log("error",...e)}time(e){this.enabled&&console.time(`[AI Providers] ${e}`)}timeEnd(e){this.enabled&&console.timeEnd(`[AI Providers] ${e}`)}},p=new Kr;var Jr={en:Qn,ru:Yn,de:Gn,zh:Zn},_=class{static t(e,t){let r=window.localStorage.getItem("language")||"en",s=e.split("."),i=Jr[r]||Jr.en;for(let a of s){if((i==null?void 0:i[a])===void 0){p.warn(`Translation missing: ${e}`),i=Jr.en;let c=i;for(let l of s)c=c==null?void 0:c[l];return c||e}i=i[a]}let o=i;return t&&Object.entries(t).forEach(([a,c])=>{o=o.replace(`{{${a}}}`,c)}),o}};var fr=require("obsidian");var ht=class extends fr.Modal{constructor(t,r,s,i=()=>{}){super(t);this.message=r;this.onConfirm=s,this.onCancel=i}onOpen(){let{contentEl:t}=this;t.createEl("p",{text:this.message}),new fr.Setting(t).addButton(r=>r.setButtonText(_.t("modals.confirm")).setWarning().onClick(()=>{this.onConfirm(),this.close()})).addButton(r=>r.setButtonText(_.t("modals.cancel")).onClick(()=>{this.onCancel(),this.close()}))}onClose(){let{contentEl:t}=this;t.empty()}};var Q=require("obsidian");var ft={openai:{url:"https://api.openai.com/v1",name:"OpenAI"},ollama:{url:"http://localhost:11434",name:"Ollama"},"ollama-openwebui":{url:"http://localhost:3000/ollama",name:"Ollama (Open WebUI)"},gemini:{url:"https://generativelanguage.googleapis.com/v1beta/openai",name:"Google Gemini"},openrouter:{url:"https://openrouter.ai/api/v1",name:"OpenRouter"},lmstudio:{url:"http://localhost:1234/v1",name:"LM Studio"},groq:{url:"https://api.groq.com/openai/v1",name:"Groq"},ai302:{url:"https://api.302.ai",name:"302.AI",options:{modelsFetching:!1}}},mr=class extends Q.Modal{constructor(t,r,s,i,o=!1){super(t);this.plugin=r;this.provider=s;this.onSave=i;this.isAddingNew=o;this.nameModified=!1;this.urlModified=!1;this.isTextMode=!1;this.isLoadingModels=!1}hasModelFetching(t){var s;return((s=ft[t].options)==null?void 0:s.modelsFetching)!==!1}getModelDescription(t,r){return r?_.t("settings.modelTextOnlyDesc"):t?_.t("settings.modelTextDesc"):_.t("settings.modelDesc")}getDefaultName(t){return ft[t].name}initDefaults(){this.nameModified=!1,this.urlModified=!1,this.provider.url||(this.provider.url=ft[this.provider.type].url),this.isAddingNew&&!this.provider.name&&(this.provider.name=this.getDefaultName(this.provider.type))}createModelSetting(t){let r=!this.hasModelFetching(this.provider.type),s=this.isTextMode||r,i=new Q.Setting(t).setName(_.t("settings.model")).setDesc(this.getModelDescription(s,r));return s?this.createTextInput(i):(this.createDropdown(i),this.createRefresh(i)),this.setupDescription(i,s,r),i}createTextInput(t){t.addText(r=>(r.setValue(this.provider.model||"").onChange(s=>{this.provider.model=s}),r.inputEl.setAttribute("data-testid","model-input"),r))}createDropdown(t){t.addDropdown(r=>(this.populateDropdown(r),this.setupDropdown(r),r))}populateDropdown(t){if(this.isLoadingModels){t.addOption("loading",_.t("settings.loadingModels")),t.setDisabled(!0);return}let r=this.provider.availableModels;if(!r||r.length===0){t.addOption("none",_.t("settings.noModelsAvailable")),t.setDisabled(!0);return}r.forEach(s=>{t.addOption(s,s);let i=t.selectEl.options,o=i[i.length-1];o.title=s}),t.setDisabled(!1)}setupDropdown(t){var r;t.setValue(this.provider.model||"").onChange(s=>{this.provider.model=s,t.selectEl.title=s}),t.selectEl.setAttribute("data-testid","model-dropdown"),t.selectEl.title=this.provider.model||"",(r=t.selectEl.parentElement)==null||r.addClass("ai-providers-model-dropdown")}createRefresh(t){t.addButton(r=>{r.setIcon("refresh-cw").setTooltip(_.t("settings.refreshModelsList")),r.buttonEl.setAttribute("data-testid","refresh-models-button"),this.isLoadingModels&&(r.setDisabled(!0),r.buttonEl.addClass("loading")),r.onClick(async()=>{await this.refreshModels()})})}async refreshModels(){try{this.isLoadingModels=!0,this.display();let t=await this.plugin.aiProviders.fetchModels(this.provider);this.provider.availableModels=t,t.length>0&&(this.provider.model=t[0]||""),new Q.Notice(_.t("settings.modelsUpdated"))}catch(t){p.error("Failed to fetch models:",t),new Q.Notice(_.t("errors.failedToFetchModels"))}finally{this.isLoadingModels=!1,this.display()}}setupDescription(t,r,s){let i=t.descEl;if(i.empty(),i.appendChild((0,Q.sanitizeHTMLToDom)(this.getModelDescription(r,s))),!s){let o=i.querySelector("a");o&&o.addEventListener("click",a=>{a.preventDefault(),this.isTextMode=!this.isTextMode,this.display()})}}onOpen(){let{contentEl:t}=this;this.initDefaults(),t.createEl("h2",{text:this.isAddingNew?_.t("settings.addNewProvider"):_.t("settings.editProvider")}).setAttribute("data-testid","provider-form-title"),new Q.Setting(t).setName(_.t("settings.providerType")).setDesc(_.t("settings.providerTypeDesc")).addDropdown(r=>{let s=Object.entries(ft).reduce((i,[o,a])=>(i[o]=a.name,i),{});return r.addOptions(s).setValue(this.provider.type).onChange(i=>{this.changeProviderType(i)}),r.selectEl.setAttribute("data-testid","provider-type-dropdown"),r}),new Q.Setting(t).setName(_.t("settings.providerName")).setDesc(_.t("settings.providerNameDesc")).addText(r=>(r.setPlaceholder(_.t("settings.providerNamePlaceholder")).setValue(this.provider.name).onChange(s=>{this.provider.name=s,this.nameModified=!0}),r.inputEl.setAttribute("data-field","provider-name"),r)),new Q.Setting(t).setName(_.t("settings.providerUrl")).setDesc(_.t("settings.providerUrlDesc")).addText(r=>(r.setPlaceholder(_.t("settings.providerUrlPlaceholder")).setValue(this.provider.url||"").onChange(s=>{this.provider.url=s,this.urlModified=!0}),r.inputEl.setAttribute("data-field","provider-url"),r)),new Q.Setting(t).setName(_.t("settings.apiKey")).setDesc(_.t("settings.apiKeyDesc")).addText(r=>r.setPlaceholder(_.t("settings.apiKeyPlaceholder")).setValue(this.provider.apiKey||"").onChange(s=>{this.provider.apiKey=s})),this.createModelSetting(t),new Q.Setting(t).addButton(r=>r.setButtonText(_.t("settings.save")).setCta().onClick(async()=>{this.provider.name=this.provider.name.trim(),await this.onSave(this.provider)})).addButton(r=>(r.setButtonText(_.t("settings.cancel")).onClick(()=>{this.close()}),r.buttonEl.setAttribute("data-testid","cancel-button"),r))}onClose(){let{contentEl:t}=this;t.empty()}changeProviderType(t){let r=this.getDefaultName(this.provider.type),s=ft[this.provider.type].url,i=this.hasModelFetching(this.provider.type),o=this.hasModelFetching(t);this.provider.type=t,this.provider.availableModels=void 0,this.provider.model=void 0,this.isAddingNew&&(!this.urlModified||this.provider.url===s)&&(this.provider.url=ft[t].url,this.urlModified=!1),this.isAddingNew&&(!this.nameModified||this.provider.name===r)&&(this.provider.name=this.getDefaultName(t),this.nameModified=!1),i!==o?this.display():this.updateFields()}updateFields(){let t=this.contentEl.querySelector('input[data-field="provider-url"]'),r=this.contentEl.querySelector('input[data-field="provider-name"]');t&&(t.value=this.provider.url||""),r&&(r.value=this.provider.name)}display(){let{contentEl:t}=this;t.empty(),this.onOpen()}};var es={_version:1,debugLogging:!1,useNativeFetch:!1},pr=class extends Y.PluginSettingTab{constructor(t,r){super(t,r);this.isFormOpen=!1;this.isDeveloperMode=!1;this.plugin=r}openForm(t,r){let s=r||{id:`id-${Date.now().toString()}`,name:"",apiKey:"",url:"",type:"openai",model:""};this.currentModal=new mr(this.app,this.plugin,s,async i=>{await this.saveProvider(i)},t),this.currentModal.open()}closeForm(){this.isFormOpen=!1,this.currentModal&&(this.currentModal.close(),this.currentModal=void 0),this.display()}validateProvider(t){return!t.name||t.name.trim()===""?{isValid:!1,error:_.t("errors.providerNameRequired")}:(this.plugin.settings.providers||[]).find(i=>i.name.trim()===t.name.trim()&&i.id!==t.id)?{isValid:!1,error:_.t("errors.providerNameExists",{name:t.name})}:{isValid:!0}}async saveProvider(t){let r=this.validateProvider(t);if(!r.isValid){new Y.Notice(r.error);return}let s=this.plugin.settings.providers||[],i=s.findIndex(o=>o.id===t.id);i!==-1?s[i]=t:s.push(t),this.plugin.settings.providers=s,await this.plugin.saveSettings(),this.closeForm()}async deleteProvider(t){let r=this.plugin.settings.providers||[],s=r.findIndex(i=>i.id===t.id);s!==-1&&(r.splice(s,1),this.plugin.settings.providers=r,await this.plugin.saveSettings(),this.display())}async duplicateProvider(t){let r={...t,id:`id-${Date.now().toString()}`,name:`${t.name} (${_.t("settings.duplicate")})`},s=this.plugin.settings.providers||[];s.push(r),this.plugin.settings.providers=s,await this.plugin.saveSettings(),this.display()}display(){let{containerEl:t}=this;t.empty();let r=t.createDiv("ai-providers-main-interface");r.setAttribute("data-testid","main-interface"),r.createDiv("ai-providers-notice").createDiv("ai-providers-notice-content").appendChild((0,Y.sanitizeHTMLToDom)(`${_.t("settings.notice")}`)),new Y.Setting(r).setHeading().setName(_.t("settings.configuredProviders")).addButton(a=>{let c=a.setIcon("plus").setTooltip(_.t("settings.addProvider")).onClick(()=>{this.isFormOpen||this.openForm(!0)});return c.buttonEl.setAttribute("aria-label",_.t("settings.addProvider")),c.buttonEl.setAttribute("data-testid","add-provider-button"),c});let o=this.plugin.settings.providers||[];if(o.length>0&&o.forEach(a=>{let c=new Y.Setting(r).setName(a.name).setDesc(a.url||""),l=c.nameEl.createSpan("ai-providers-provider-icon");if((0,Y.setIcon)(l,`ai-providers-${a.type}`),c.nameEl.prepend(l),a.model){let d=c.settingEl.createDiv("ai-providers-model-pill");d.textContent=a.model,d.setAttribute("data-testid","model-pill"),c.nameEl.after(d)}c.addExtraButton(d=>{d.setIcon("gear").setTooltip(_.t("settings.options")).onClick(()=>{this.isFormOpen||this.openForm(!1,{...a})}),d.extraSettingsEl.setAttribute("data-testid","edit-provider")}).addExtraButton(d=>{d.setIcon("copy").setTooltip(_.t("settings.duplicate")).onClick(async()=>{await this.duplicateProvider(a)}),d.extraSettingsEl.setAttribute("data-testid","duplicate-provider")}).addExtraButton(d=>{d.setIcon("lucide-trash-2").setTooltip(_.t("settings.delete")).onClick(async()=>{new ht(this.app,_.t("settings.deleteConfirmation",{name:a.name}),async()=>{await this.deleteProvider(a)}).open()}),d.extraSettingsEl.setAttribute("data-testid","delete-provider")})}),new Y.Setting(r).setHeading().setName(_.t("settings.developerSettings")).setDesc(_.t("settings.developerSettingsDesc")).setClass("ai-providers-developer-settings-toggle").addToggle(a=>a.setValue(this.isDeveloperMode).onChange(c=>{this.isDeveloperMode=c,this.display()})),this.isDeveloperMode){let a=r.createDiv("ai-providers-developer-settings");new Y.Setting(a).setName(_.t("settings.debugLogging")).setDesc(_.t("settings.debugLoggingDesc")).addToggle(c=>{var l;return c.setValue((l=this.plugin.settings.debugLogging)!=null?l:!1).onChange(async d=>{this.plugin.settings.debugLogging=d,p.setEnabled(d),await this.plugin.saveSettings()})}),new Y.Setting(a).setName(_.t("settings.useNativeFetch")).setDesc(_.t("settings.useNativeFetchDesc")).addToggle(c=>{var l;return c.setValue((l=this.plugin.settings.useNativeFetch)!=null?l:!1).onChange(async d=>{this.plugin.settings.useNativeFetch=d,await this.plugin.saveSettings()})})}}};var Wr=require("obsidian");var gr="RFC3986",yr={RFC1738:n=>String(n).replace(/%20/g,"+"),RFC3986:n=>String(n)},ts="RFC1738";var Ti=Array.isArray,ue=(()=>{let n=[];for(let e=0;e<256;++e)n.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return n})();var Xr=1024,rs=(n,e,t,r,s)=>{if(n.length===0)return n;let i=n;if(typeof n=="symbol"?i=Symbol.prototype.toString.call(n):typeof n!="string"&&(i=String(n)),t==="iso-8859-1")return escape(i).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let o="";for(let a=0;a<i.length;a+=Xr){let c=i.length>=Xr?i.slice(a,a+Xr):i,l=[];for(let d=0;d<c.length;++d){let u=c.charCodeAt(d);if(u===45||u===46||u===95||u===126||u>=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||s===ts&&(u===40||u===41)){l[l.length]=c.charAt(d);continue}if(u<128){l[l.length]=ue[u];continue}if(u<2048){l[l.length]=ue[192|u>>6]+ue[128|u&63];continue}if(u<55296||u>=57344){l[l.length]=ue[224|u>>12]+ue[128|u>>6&63]+ue[128|u&63];continue}d+=1,u=65536+((u&1023)<<10|c.charCodeAt(d)&1023),l[l.length]=ue[240|u>>18]+ue[128|u>>12&63]+ue[128|u>>6&63]+ue[128|u&63]}o+=l.join("")}return o};function ns(n){return!n||typeof n!="object"?!1:!!(n.constructor&&n.constructor.isBuffer&&n.constructor.isBuffer(n))}function Gr(n,e){if(Ti(n)){let t=[];for(let r=0;r<n.length;r+=1)t.push(e(n[r]));return t}return e(n)}var ki=Object.prototype.hasOwnProperty,ss={brackets(n){return String(n)+"[]"},comma:"comma",indices(n,e){return String(n)+"["+e+"]"},repeat(n){return String(n)}},he=Array.isArray,Fi=Array.prototype.push,is=function(n,e){Fi.apply(n,he(e)?e:[e])},Di=Date.prototype.toISOString,U={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:rs,encodeValuesOnly:!1,format:gr,formatter:yr[gr],indices:!1,serializeDate(n){return Di.call(n)},skipNulls:!1,strictNullHandling:!1};function Ni(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="symbol"||typeof n=="bigint"}var Qr={};function os(n,e,t,r,s,i,o,a,c,l,d,u,h,m,f,v,g,O){let b=n,C=O,N=0,P=!1;for(;(C=C.get(Qr))!==void 0&&!P;){let E=C.get(n);if(N+=1,typeof E!="undefined"){if(E===N)throw new RangeError("Cyclic object value");P=!0}typeof C.get(Qr)=="undefined"&&(N=0)}if(typeof l=="function"?b=l(e,b):b instanceof Date?b=h==null?void 0:h(b):t==="comma"&&he(b)&&(b=Gr(b,function(E){return E instanceof Date?h==null?void 0:h(E):E})),b===null){if(i)return c&&!v?c(e,U.encoder,g,"key",m):e;b=""}if(Ni(b)||ns(b)){if(c){let E=v?e:c(e,U.encoder,g,"key",m);return[(f==null?void 0:f(E))+"="+(f==null?void 0:f(c(b,U.encoder,g,"value",m)))]}return[(f==null?void 0:f(e))+"="+(f==null?void 0:f(String(b)))]}let D=[];if(typeof b=="undefined")return D;let T;if(t==="comma"&&he(b))v&&c&&(b=Gr(b,c)),T=[{value:b.length>0?b.join(",")||null:void 0}];else if(he(l))T=l;else{let E=Object.keys(b);T=d?E.sort(d):E}let M=a?String(e).replace(/\./g,"%2E"):String(e),x=r&&he(b)&&b.length===1?M+"[]":M;if(s&&he(b)&&b.length===0)return x+"[]";for(let E=0;E<T.length;++E){let k=T[E],S=typeof k=="object"&&typeof k.value!="undefined"?k.value:b[k];if(o&&S===null)continue;let se=u&&a?k.replace(/\./g,"%2E"):k,_e=he(b)?typeof t=="function"?t(x,se):x:x+(u?"."+se:"["+se+"]");O.set(n,N);let te=new WeakMap;te.set(Qr,O),is(D,os(S,_e,t,r,s,i,o,a,t==="comma"&&v&&he(b)?null:c,l,d,u,h,m,f,v,g,te))}return D}function Bi(n=U){if(typeof n.allowEmptyArrays!="undefined"&&typeof n.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof n.encodeDotInKeys!="undefined"&&typeof n.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(n.encoder!==null&&typeof n.encoder!="undefined"&&typeof n.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=n.charset||U.charset;if(typeof n.charset!="undefined"&&n.charset!=="utf-8"&&n.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=gr;if(typeof n.format!="undefined"){if(!ki.call(yr,n.format))throw new TypeError("Unknown format option provided.");t=n.format}let r=yr[t],s=U.filter;(typeof n.filter=="function"||he(n.filter))&&(s=n.filter);let i;if(n.arrayFormat&&n.arrayFormat in ss?i=n.arrayFormat:"indices"in n?i=n.indices?"indices":"repeat":i=U.arrayFormat,"commaRoundTrip"in n&&typeof n.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let o=typeof n.allowDots=="undefined"?n.encodeDotInKeys?!0:U.allowDots:!!n.allowDots;return{addQueryPrefix:typeof n.addQueryPrefix=="boolean"?n.addQueryPrefix:U.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof n.allowEmptyArrays=="boolean"?!!n.allowEmptyArrays:U.allowEmptyArrays,arrayFormat:i,charset:e,charsetSentinel:typeof n.charsetSentinel=="boolean"?n.charsetSentinel:U.charsetSentinel,commaRoundTrip:!!n.commaRoundTrip,delimiter:typeof n.delimiter=="undefined"?U.delimiter:n.delimiter,encode:typeof n.encode=="boolean"?n.encode:U.encode,encodeDotInKeys:typeof n.encodeDotInKeys=="boolean"?n.encodeDotInKeys:U.encodeDotInKeys,encoder:typeof n.encoder=="function"?n.encoder:U.encoder,encodeValuesOnly:typeof n.encodeValuesOnly=="boolean"?n.encodeValuesOnly:U.encodeValuesOnly,filter:s,format:t,formatter:r,serializeDate:typeof n.serializeDate=="function"?n.serializeDate:U.serializeDate,skipNulls:typeof n.skipNulls=="boolean"?n.skipNulls:U.skipNulls,sort:typeof n.sort=="function"?n.sort:null,strictNullHandling:typeof n.strictNullHandling=="boolean"?n.strictNullHandling:U.strictNullHandling}}function Yr(n,e={}){let t=n,r=Bi(e),s,i;typeof r.filter=="function"?(i=r.filter,t=i("",t)):he(r.filter)&&(i=r.filter,s=i);let o=[];if(typeof t!="object"||t===null)return"";let a=ss[r.arrayFormat],c=a==="comma"&&r.commaRoundTrip;s||(s=Object.keys(t)),r.sort&&s.sort(r.sort);let l=new WeakMap;for(let h=0;h<s.length;++h){let m=s[h];r.skipNulls&&t[m]===null||is(o,os(t[m],m,a,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l))}let d=o.join(r.delimiter),u=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?u+="utf8=%26%2310003%3B&":u+="utf8=%E2%9C%93&"),d.length>0?u+d:""}var He="4.73.1";var as=!1,We,Zr,$i,Ui,ji,en,qi,br,tn,rn,nn,wr,sn;function cs(n,e={auto:!1}){if(as)throw new Error(`you must \`import 'openai/shims/${n.kind}'\` before importing anything else from openai`);if(We)throw new Error(`can't \`import 'openai/shims/${n.kind}'\` after \`import 'openai/shims/${We}'\``);as=e.auto,We=n.kind,Zr=n.fetch,$i=n.Request,Ui=n.Response,ji=n.Headers,en=n.FormData,qi=n.Blob,br=n.File,tn=n.ReadableStream,rn=n.getMultipartRequestOptions,nn=n.getDefaultAgent,wr=n.fileFromPath,sn=n.isFsReadStream}var vr=class{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}};function ls({manuallyImported:n}={}){let e=n?"You may need to use polyfills":"Add one of these imports before your first `import \u2026 from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n",t,r,s,i;try{t=fetch,r=Request,s=Response,i=Headers}catch(o){throw new Error(`this environment is missing the following Web Fetch API type: ${o.message}. ${e}`)}return{kind:"web",fetch:t,Request:r,Response:s,Headers:i,FormData:typeof FormData!="undefined"?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${e}`)}},Blob:typeof Blob!="undefined"?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${e}`)}},File:typeof File!="undefined"?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${e}`)}},ReadableStream:typeof ReadableStream!="undefined"?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${e}`)}},getMultipartRequestOptions:async(o,a)=>({...a,body:new vr(o)}),getDefaultAgent:o=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads")},isFsReadStream:o=>!1}}We||cs(ls(),{auto:!0});var A=class extends Error{},$=class extends A{constructor(e,t,r,s){super(`${$.makeMessage(e,t,r)}`),this.status=e,this.headers=s,this.request_id=s==null?void 0:s["x-request-id"];let i=t;this.error=i,this.code=i==null?void 0:i.code,this.param=i==null?void 0:i.param,this.type=i==null?void 0:i.type}static makeMessage(e,t,r){let s=t!=null&&t.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,r,s){if(!e)return new Re({message:r,cause:_r(t)});let i=t==null?void 0:t.error;return e===400?new jt(e,i,r,s):e===401?new qt(e,i,r,s):e===403?new Ht(e,i,r,s):e===404?new Wt(e,i,r,s):e===409?new Vt(e,i,r,s):e===422?new zt(e,i,r,s):e===429?new Kt(e,i,r,s):e>=500?new Jt(e,i,r,s):new $(e,i,r,s)}},H=class extends ${constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0),this.status=void 0}},Re=class extends ${constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),this.status=void 0,t&&(this.cause=t)}},Oe=class extends Re{constructor({message:e}={}){super({message:e!=null?e:"Request timed out."})}},jt=class extends ${constructor(){super(...arguments),this.status=400}},qt=class extends ${constructor(){super(...arguments),this.status=401}},Ht=class extends ${constructor(){super(...arguments),this.status=403}},Wt=class extends ${constructor(){super(...arguments),this.status=404}},Vt=class extends ${constructor(){super(...arguments),this.status=409}},zt=class extends ${constructor(){super(...arguments),this.status=422}},Kt=class extends ${constructor(){super(...arguments),this.status=429}},Jt=class extends ${},mt=class extends A{constructor(){super("Could not parse response content as the length limit was reached")}},pt=class extends A{constructor(){super("Could not parse response content as the request was rejected by the content filter")}};var fe=class{constructor(){this.buffer=[],this.trailingCR=!1}decode(e){let t=this.decodeText(e);if(this.trailingCR&&(t="\r"+t,this.trailingCR=!1),t.endsWith("\r")&&(this.trailingCR=!0,t=t.slice(0,-1)),!t)return[];let r=fe.NEWLINE_CHARS.has(t[t.length-1]||""),s=t.split(fe.NEWLINE_REGEXP);return r&&s.pop(),s.length===1&&!r?(this.buffer.push(s[0]),[]):(this.buffer.length>0&&(s=[this.buffer.join("")+s[0],...s.slice(1)],this.buffer=[]),r||(this.buffer=[s.pop()||""]),s)}decodeText(e){var t;if(e==null)return"";if(typeof e=="string")return e;if(typeof Buffer!="undefined"){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new A(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder!="undefined"){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return(t=this.textDecoder)!=null||(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new A(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new A("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];let e=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,e}};fe.NEWLINE_CHARS=new Set([`
`,"\r"]);fe.NEWLINE_REGEXP=/\r\n|[\n\r]/g;var J=class{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let r=!1;async function*s(){if(r)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let i=!1;try{for await(let o of Vi(e,t))if(!i){if(o.data.startsWith("[DONE]")){i=!0;continue}if(o.event===null){let a;try{a=JSON.parse(o.data)}catch(c){throw console.error("Could not parse message into JSON:",o.data),console.error("From chunk:",o.raw),c}if(a&&a.error)throw new $(void 0,a.error,void 0,void 0);yield a}else{let a;try{a=JSON.parse(o.data)}catch(c){throw console.error("Could not parse message into JSON:",o.data),console.error("From chunk:",o.raw),c}if(o.event=="error")throw new $(void 0,a.error,a.message,void 0);yield{event:o.event,data:a}}}i=!0}catch(o){if(o instanceof Error&&o.name==="AbortError")return;throw o}finally{i||t.abort()}}return new J(s,t)}static fromReadableStream(e,t){let r=!1;async function*s(){let o=new fe,a=ds(e);for await(let c of a)for(let l of o.decode(c))yield l;for(let c of o.flush())yield c}async function*i(){if(r)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let o=!1;try{for await(let a of s())o||a&&(yield JSON.parse(a));o=!0}catch(a){if(a instanceof Error&&a.name==="AbortError")return;throw a}finally{o||t.abort()}}return new J(i,t)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),s=i=>({next:()=>{if(i.length===0){let o=r.next();e.push(o),t.push(o)}return i.shift()}});return[new J(()=>s(e),this.controller),new J(()=>s(t),this.controller)]}toReadableStream(){let e=this,t,r=new TextEncoder;return new tn({async start(){t=e[Symbol.asyncIterator]()},async pull(s){try{let{value:i,done:o}=await t.next();if(o)return s.close();let a=r.encode(JSON.stringify(i)+`
`);s.enqueue(a)}catch(i){s.error(i)}},async cancel(){var s;await((s=t.return)==null?void 0:s.call(t))}})}};async function*Vi(n,e){if(!n.body)throw e.abort(),new A("Attempted to iterate over a response with no body");let t=new on,r=new fe,s=ds(n.body);for await(let i of zi(s))for(let o of r.decode(i)){let a=t.decode(o);a&&(yield a)}for(let i of r.flush()){let o=t.decode(i);o&&(yield o)}}async function*zi(n){let e=new Uint8Array;for await(let t of n){if(t==null)continue;let r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?new TextEncoder().encode(t):t,s=new Uint8Array(e.length+r.length);s.set(e),s.set(r,e.length),e=s;let i;for(;(i=Ki(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function Ki(n){for(let r=0;r<n.length-2;r++){if(n[r]===10&&n[r+1]===10||n[r]===13&&n[r+1]===13)return r+2;if(n[r]===13&&n[r+1]===10&&r+3<n.length&&n[r+2]===13&&n[r+3]===10)return r+4}return-1}var on=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,s]=Ji(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}};function Ji(n,e){let t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}function ds(n){if(n[Symbol.asyncIterator])return n;let e=n.getReader();return{async next(){try{let t=await e.read();return t!=null&&t.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var us=n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function",hs=n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&Xt(n),Xt=n=>n!=null&&typeof n=="object"&&typeof n.size=="number"&&typeof n.type=="string"&&typeof n.text=="function"&&typeof n.slice=="function"&&typeof n.arrayBuffer=="function",Xi=n=>hs(n)||us(n)||sn(n);async function ln(n,e,t){var s,i,o;if(n=await n,hs(n))return n;if(us(n)){let a=await n.blob();e||(e=(s=new URL(n.url).pathname.split(/[\\/]/).pop())!=null?s:"unknown_file");let c=Xt(a)?[await a.arrayBuffer()]:[a];return new br(c,e,t)}let r=await Gi(n);if(e||(e=(i=Yi(n))!=null?i:"unknown_file"),!(t!=null&&t.type)){let a=(o=r[0])==null?void 0:o.type;typeof a=="string"&&(t={...t,type:a})}return new br(r,e,t)}async function Gi(n){var t;let e=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)e.push(n);else if(Xt(n))e.push(await n.arrayBuffer());else if(Zi(n))for await(let r of n)e.push(r);else throw new Error(`Unexpected data type: ${typeof n}; constructor: ${(t=n==null?void 0:n.constructor)==null?void 0:t.name}; props: ${Qi(n)}`);return e}function Qi(n){return`[${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}function Yi(n){var e;return an(n.name)||an(n.filename)||((e=an(n.path))==null?void 0:e.split(/[\\/]/).pop())}var an=n=>{if(typeof n=="string")return n;if(typeof Buffer!="undefined"&&n instanceof Buffer)return String(n)},Zi=n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function",dn=n=>n&&typeof n=="object"&&n.body&&n[Symbol.toStringTag]==="MultipartBody";var ie=async n=>{let e=await fs(n.body);return rn(e,n)},fs=async n=>{let e=new en;return await Promise.all(Object.entries(n||{}).map(([t,r])=>cn(e,t,r))),e};var cn=async(n,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")n.append(e,String(t));else if(Xi(t)){let r=await ln(t);n.append(e,r)}else if(Array.isArray(t))await Promise.all(t.map(r=>cn(n,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,s])=>cn(n,`${e}[${r}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var to=function(n,e,t,r,s){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?s.call(n,t):s?s.value=t:e.set(n,t),t},ro=function(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)},Ar;async function bs(n){let{response:e}=n;if(n.options.stream)return gt("response",e.status,e.url,e.headers,e.body),n.options.__streamClass?n.options.__streamClass.fromSSEResponse(e,n.controller):J.fromSSEResponse(e,n.controller);if(e.status===204)return null;if(n.options.__binaryResponse)return e;let t=e.headers.get("content-type");if((t==null?void 0:t.includes("application/json"))||(t==null?void 0:t.includes("application/vnd.api+json"))){let i=await e.json();return gt("response",e.status,e.url,e.headers,i),ws(i,e)}let s=await e.text();return gt("response",e.status,e.url,e.headers,s),s}function ws(n,e){return!n||typeof n!="object"||Array.isArray(n)?n:Object.defineProperty(n,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var yt=class extends Promise{constructor(e,t=bs){super(r=>{r(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new yt(this.responsePromise,async t=>ws(e(await this.parseResponse(t),t),t.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}},Ir=class{constructor({baseURL:e,maxRetries:t=2,timeout:r=6e5,httpAgent:s,fetch:i}){this.baseURL=e,this.maxRetries=un("maxRetries",t),this.timeout=un("timeout",r),this.httpAgent=s,this.fetch=i!=null?i:Zr}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...ao(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${ho()}`}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(async s=>{let i=s&&Xt(s==null?void 0:s.body)?new DataView(await s.body.arrayBuffer()):(s==null?void 0:s.body)instanceof DataView?s.body:(s==null?void 0:s.body)instanceof ArrayBuffer?new DataView(s.body):s&&ArrayBuffer.isView(s==null?void 0:s.body)?new DataView(s.body.buffer):s==null?void 0:s.body;return{method:e,path:t,...s,body:i}}))}getAPIList(e,t,r){return this.requestAPIList(t,{method:"get",path:e,...r})}calculateContentLength(e){if(typeof e=="string"){if(typeof Buffer!="undefined")return Buffer.byteLength(e,"utf8").toString();if(typeof TextEncoder!="undefined")return new TextEncoder().encode(e).length.toString()}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){var v,g,O,b,C,N;let{method:r,path:s,query:i,headers:o={}}=e,a=ArrayBuffer.isView(e.body)||e.__binaryRequest&&typeof e.body=="string"?e.body:dn(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,c=this.calculateContentLength(a),l=this.buildURL(s,i);"timeout"in e&&un("timeout",e.timeout);let d=(v=e.timeout)!=null?v:this.timeout,u=(O=(g=e.httpAgent)!=null?g:this.httpAgent)!=null?O:nn(l),h=d+1e3;typeof((b=u==null?void 0:u.options)==null?void 0:b.timeout)=="number"&&h>((C=u.options.timeout)!=null?C:0)&&(u.options.timeout=h),this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let m=this.buildHeaders({options:e,headers:o,contentLength:c,retryCount:t});return{req:{method:r,...a&&{body:a},headers:m,...u&&{agent:u},signal:(N=e.signal)!=null?N:null},url:l,timeout:d}}buildHeaders({options:e,headers:t,contentLength:r,retryCount:s}){let i={};r&&(i["content-length"]=r);let o=this.defaultHeaders(e);return gs(i,o),gs(i,t),dn(e.body)&&We!=="node"&&delete i["content-type"],ys(o,"x-stainless-retry-count")===void 0&&ys(t,"x-stainless-retry-count")===void 0&&(i["x-stainless-retry-count"]=String(s)),this.validateHeaders(i,t),i}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(t=>[...t])):{...e}:{}}makeStatusError(e,t,r,s){return $.generate(e,t,r,s)}request(e,t=null){return new yt(this.makeRequest(e,t))}async makeRequest(e,t){var u,h,m;let r=await e,s=(u=r.maxRetries)!=null?u:this.maxRetries;t==null&&(t=s),await this.prepareOptions(r);let{req:i,url:o,timeout:a}=this.buildRequest(r,{retryCount:s-t});if(await this.prepareRequest(i,{url:o,options:r}),gt("request",o,r,i.headers),(h=r.signal)!=null&&h.aborted)throw new H;let c=new AbortController,l=await this.fetchWithTimeout(o,i,a,c).catch(_r);if(l instanceof Error){if((m=r.signal)!=null&&m.aborted)throw new H;if(t)return this.retryRequest(r,t);throw l.name==="AbortError"?new Oe:new Re({cause:l})}let d=no(l.headers);if(!l.ok){if(t&&this.shouldRetry(l)){let C=`retrying, ${t} attempts remaining`;return gt(`response (error; ${C})`,l.status,o,d),this.retryRequest(r,t,d)}let f=await l.text().catch(C=>_r(C).message),v=co(f),g=v?void 0:f;throw gt(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,l.status,o,d,g),this.makeStatusError(l.status,v,g,d)}return{response:l,options:r,controller:c}}requestAPIList(e,t){let r=this.makeRequest(t,null);return new hn(this,r,e)}buildURL(e,t){let r=uo(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return vs(s)||(t={...s,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(r.search=this.stringifyQuery(t)),r.toString()}stringifyQuery(e){return Object.entries(e).filter(([t,r])=>typeof r!="undefined").map(([t,r])=>{if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(r)}`;if(r===null)return`${encodeURIComponent(t)}=`;throw new A(`Cannot stringify type ${typeof r}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(e,t,r,s){let{signal:i,...o}=t||{};i&&i.addEventListener("abort",()=>s.abort());let a=setTimeout(()=>s.abort(),r);return this.getRequestClient().fetch.call(void 0,e,{signal:s.signal,...o}).finally(()=>{clearTimeout(a)})}getRequestClient(){return{fetch:this.fetch}}shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,r){var a;let s,i=r==null?void 0:r["retry-after-ms"];if(i){let c=parseFloat(i);Number.isNaN(c)||(s=c)}let o=r==null?void 0:r["retry-after"];if(o&&!s){let c=parseFloat(o);Number.isNaN(c)?s=Date.parse(o)-Date.now():s=c*1e3}if(!(s&&0<=s&&s<60*1e3)){let c=(a=e.maxRetries)!=null?a:this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,c)}return await Ae(s),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){let i=t-e,o=Math.min(.5*Math.pow(2,i),8),a=1-Math.random()*.25;return o*a*1e3}getUserAgent(){return`${this.constructor.name}/JS ${He}`}},Gt=class{constructor(e,t,r,s){Ar.set(this,void 0),to(this,Ar,e,"f"),this.options=s,this.response=t,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageInfo()!=null:!1}async getNextPage(){let e=this.nextPageInfo();if(!e)throw new A("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let t={...this.options};if("params"in e&&typeof t.query=="object")t.query={...t.query,...e.params};else if("url"in e){let r=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(let[s,i]of r)e.url.searchParams.set(s,i);t.query=void 0,t.path=e.url.toString()}return await ro(this,Ar,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ar=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},hn=class extends yt{constructor(e,t,r){super(t,async s=>new r(e,s.response,await bs(s),s.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},no=n=>new Proxy(Object.fromEntries(n.entries()),{get(e,t){let r=t.toString();return e[r.toLowerCase()]||e[r]}}),so={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},F=n=>typeof n=="object"&&n!==null&&!vs(n)&&Object.keys(n).every(e=>_s(so,e)),io=()=>{var e,t;if(typeof Deno!="undefined"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":He,"X-Stainless-OS":ps(Deno.build.os),"X-Stainless-Arch":ms(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:(t=(e=Deno.version)==null?void 0:e.deno)!=null?t:"unknown"};if(typeof EdgeRuntime!="undefined")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":He,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process!="undefined"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":He,"X-Stainless-OS":ps(process.platform),"X-Stainless-Arch":ms(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let n=oo();return n?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":He,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${n.browser}`,"X-Stainless-Runtime-Version":n.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":He,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function oo(){if(typeof navigator=="undefined"||!navigator)return null;let n=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of n){let r=t.exec(navigator.userAgent);if(r){let s=r[1]||0,i=r[2]||0,o=r[3]||0;return{browser:e,version:`${s}.${i}.${o}`}}}return null}var ms=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",ps=n=>(n=n.toLowerCase(),n.includes("ios")?"iOS":n==="android"?"Android":n==="darwin"?"MacOS":n==="win32"?"Windows":n==="freebsd"?"FreeBSD":n==="openbsd"?"OpenBSD":n==="linux"?"Linux":n?`Other:${n}`:"Unknown"),Pr,ao=()=>Pr!=null?Pr:Pr=io(),co=n=>{try{return JSON.parse(n)}catch(e){return}},lo=new RegExp("^(?:[a-z]+:)?//","i"),uo=n=>lo.test(n),Ae=n=>new Promise(e=>setTimeout(e,n)),un=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new A(`${n} must be an integer`);if(e<0)throw new A(`${n} must be a positive integer`);return e},_r=n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null)try{return new Error(JSON.stringify(n))}catch(e){}return new Error(n)};var Qt=n=>{var e,t,r,s,i,o;if(typeof process!="undefined")return(r=(t=(e=process.env)==null?void 0:e[n])==null?void 0:t.trim())!=null?r:void 0;if(typeof Deno!="undefined")return(o=(i=(s=Deno.env)==null?void 0:s.get)==null?void 0:i.call(s,n))==null?void 0:o.trim()};function vs(n){if(!n)return!0;for(let e in n)return!1;return!0}function _s(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function gs(n,e){for(let t in e){if(!_s(e,t))continue;let r=t.toLowerCase();if(!r)continue;let s=e[t];s===null?delete n[r]:s!==void 0&&(n[r]=s)}}function gt(n,...e){var t;typeof process!="undefined"&&((t=process==null?void 0:process.env)==null?void 0:t.DEBUG)==="true"&&console.log(`OpenAI:DEBUG:${n}`,...e)}var ho=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{let e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)}),As=()=>typeof window!="undefined"&&typeof window.document!="undefined"&&typeof navigator!="undefined",fo=n=>typeof(n==null?void 0:n.get)=="function";var ys=(n,e)=>{var r;let t=e.toLowerCase();if(fo(n)){let s=((r=e[0])==null?void 0:r.toUpperCase())+e.substring(1).replace(/([^\w])(\w)/g,(i,o,a)=>o+a.toUpperCase());for(let i of[e,t,e.toUpperCase(),s]){let o=n.get(i);if(o)return o}}for(let[s,i]of Object.entries(n))if(s.toLowerCase()===t)return Array.isArray(i)?(i.length<=1||console.warn(`Received ${i.length} entries for the ${e} header, using the first entry.`),i[0]):i};function Yt(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}var xr=class extends Gt{constructor(e,t,r,s){super(e,t,r,s),this.data=r.data||[],this.object=r.object}getPaginatedItems(){var e;return(e=this.data)!=null?e:[]}nextPageParams(){return null}nextPageInfo(){return null}},B=class extends Gt{constructor(e,t,r,s){super(e,t,r,s),this.data=r.data||[]}getPaginatedItems(){var e;return(e=this.data)!=null?e:[]}nextPageParams(){let e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;let t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){var r;let e=this.getPaginatedItems();if(!e.length)return null;let t=(r=e[e.length-1])==null?void 0:r.id;return t?{params:{after:t}}:null}};var y=class{constructor(e){this._client=e}};var bt=class extends y{create(e,t){var r;return this._client.post("/chat/completions",{body:e,...t,stream:(r=e.stream)!=null?r:!1})}};var Me=class extends y{constructor(){super(...arguments),this.completions=new bt(this._client)}};Me.Completions=bt;var wt=class extends y{create(e,t){return this._client.post("/audio/speech",{body:e,...t,__binaryResponse:!0})}};var vt=class extends y{create(e,t){return this._client.post("/audio/transcriptions",ie({body:e,...t}))}};var _t=class extends y{create(e,t){return this._client.post("/audio/translations",ie({body:e,...t}))}};var me=class extends y{constructor(){super(...arguments),this.transcriptions=new vt(this._client),this.translations=new _t(this._client),this.speech=new wt(this._client)}};me.Transcriptions=vt;me.Translations=_t;me.Speech=wt;var Te=class extends y{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(`/batches/${e}`,t)}list(e={},t){return F(e)?this.list({},e):this._client.getAPIList("/batches",ze,{query:e,...t})}cancel(e,t){return this._client.post(`/batches/${e}/cancel`,t)}},ze=class extends B{};Te.BatchesPage=ze;var Ke=class extends y{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}retrieve(e,t){return this._client.get(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}update(e,t,r){return this._client.post(`/assistants/${e}`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r==null?void 0:r.headers}})}list(e={},t){return F(e)?this.list({},e):this._client.getAPIList("/assistants",At,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}del(e,t){return this._client.delete(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}},At=class extends B{};Ke.AssistantsPage=At;function fn(n){return typeof n.parse=="function"}var ke=n=>(n==null?void 0:n.role)==="assistant",mn=n=>(n==null?void 0:n.role)==="function",pn=n=>(n==null?void 0:n.role)==="tool";var ae=function(n,e,t,r,s){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?s.call(n,t):s?s.value=t:e.set(n,t),t},L=function(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)},gn,Er,Cr,Zt,er,Sr,tr,Pe,rr,Rr,Or,Pt,Ps,It=class{constructor(){gn.add(this),this.controller=new AbortController,Er.set(this,void 0),Cr.set(this,()=>{}),Zt.set(this,()=>{}),er.set(this,void 0),Sr.set(this,()=>{}),tr.set(this,()=>{}),Pe.set(this,{}),rr.set(this,!1),Rr.set(this,!1),Or.set(this,!1),Pt.set(this,!1),ae(this,Er,new Promise((e,t)=>{ae(this,Cr,e,"f"),ae(this,Zt,t,"f")}),"f"),ae(this,er,new Promise((e,t)=>{ae(this,Sr,e,"f"),ae(this,tr,t,"f")}),"f"),L(this,Er,"f").catch(()=>{}),L(this,er,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},L(this,gn,"m",Ps).bind(this))},0)}_connected(){this.ended||(L(this,Cr,"f").call(this),this._emit("connect"))}get ended(){return L(this,rr,"f")}get errored(){return L(this,Rr,"f")}get aborted(){return L(this,Or,"f")}abort(){this.controller.abort()}on(e,t){return(L(this,Pe,"f")[e]||(L(this,Pe,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=L(this,Pe,"f")[e];if(!r)return this;let s=r.findIndex(i=>i.listener===t);return s>=0&&r.splice(s,1),this}once(e,t){return(L(this,Pe,"f")[e]||(L(this,Pe,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{ae(this,Pt,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){ae(this,Pt,!0,"f"),await L(this,er,"f")}_emit(e,...t){if(L(this,rr,"f"))return;e==="end"&&(ae(this,rr,!0,"f"),L(this,Sr,"f").call(this));let r=L(this,Pe,"f")[e];if(r&&(L(this,Pe,"f")[e]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...t))),e==="abort"){let s=t[0];!L(this,Pt,"f")&&!(r!=null&&r.length)&&Promise.reject(s),L(this,Zt,"f").call(this,s),L(this,tr,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];!L(this,Pt,"f")&&!(r!=null&&r.length)&&Promise.reject(s),L(this,Zt,"f").call(this,s),L(this,tr,"f").call(this,s),this._emit("end")}}_emitFinal(){}};Er=new WeakMap,Cr=new WeakMap,Zt=new WeakMap,er=new WeakMap,Sr=new WeakMap,tr=new WeakMap,Pe=new WeakMap,rr=new WeakMap,Rr=new WeakMap,Or=new WeakMap,Pt=new WeakMap,gn=new WeakSet,Ps=function(e){if(ae(this,Rr,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new H),e instanceof H)return ae(this,Or,!0,"f"),this._emit("abort",e);if(e instanceof A)return this._emit("error",e);if(e instanceof Error){let t=new A(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new A(String(e)))};function yn(n){return(n==null?void 0:n.$brand)==="auto-parseable-response-format"}function Je(n){return(n==null?void 0:n.$brand)==="auto-parseable-tool"}function Is(n,e){return!e||!bn(e)?{...n,choices:n.choices.map(t=>{var r;return{...t,message:{...t.message,parsed:null,tool_calls:(r=t.message.tool_calls)!=null?r:[]}}})}:nr(n,e)}function nr(n,e){let t=n.choices.map(r=>{var s,i;if(r.finish_reason==="length")throw new mt;if(r.finish_reason==="content_filter")throw new pt;return{...r,message:{...r.message,tool_calls:(i=(s=r.message.tool_calls)==null?void 0:s.map(o=>vo(e,o)))!=null?i:[],parsed:r.message.content&&!r.message.refusal?wo(e,r.message.content):null}}});return{...n,choices:t}}function wo(n,e){var t,r;return((t=n.response_format)==null?void 0:t.type)!=="json_schema"?null:((r=n.response_format)==null?void 0:r.type)==="json_schema"?"$parseRaw"in n.response_format?n.response_format.$parseRaw(e):JSON.parse(e):null}function vo(n,e){var r;let t=(r=n.tools)==null?void 0:r.find(s=>{var i;return((i=s.function)==null?void 0:i.name)===e.function.name});return{...e,function:{...e.function,parsed_arguments:Je(t)?t.$parseRaw(e.function.arguments):t!=null&&t.function.strict?JSON.parse(e.function.arguments):null}}}function xs(n,e){var r;if(!n)return!1;let t=(r=n.tools)==null?void 0:r.find(s=>{var i;return((i=s.function)==null?void 0:i.name)===e.function.name});return Je(t)||(t==null?void 0:t.function.strict)||!1}function bn(n){var e,t;return yn(n.response_format)?!0:(t=(e=n.tools)==null?void 0:e.some(r=>Je(r)||r.type==="function"&&r.function.strict===!0))!=null?t:!1}function Es(n){for(let e of n!=null?n:[]){if(e.type!=="function")throw new A(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new A(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Z=function(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)},K,wn,Mr,vn,_n,An,Ss,Pn,Cs=10,xt=class extends It{constructor(){super(...arguments),K.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){var r;this._chatCompletions.push(e),this._emit("chatCompletion",e);let t=(r=e.choices[0])==null?void 0:r.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),(mn(e)||pn(e))&&e.content)this._emit("functionCallResult",e.content);else if(ke(e)&&e.function_call)this._emit("functionCall",e.function_call);else if(ke(e)&&e.tool_calls)for(let r of e.tool_calls)r.type==="function"&&this._emit("functionCall",r.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new A("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),Z(this,K,"m",wn).call(this)}async finalMessage(){return await this.done(),Z(this,K,"m",Mr).call(this)}async finalFunctionCall(){return await this.done(),Z(this,K,"m",vn).call(this)}async finalFunctionCallResult(){return await this.done(),Z(this,K,"m",_n).call(this)}async totalUsage(){return await this.done(),Z(this,K,"m",An).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=Z(this,K,"m",Mr).call(this);t&&this._emit("finalMessage",t);let r=Z(this,K,"m",wn).call(this);r&&this._emit("finalContent",r);let s=Z(this,K,"m",vn).call(this);s&&this._emit("finalFunctionCall",s);let i=Z(this,K,"m",_n).call(this);i!=null&&this._emit("finalFunctionCallResult",i),this._chatCompletions.some(o=>o.usage)&&this._emit("totalUsage",Z(this,K,"m",An).call(this))}async _createChatCompletion(e,t,r){let s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),Z(this,K,"m",Ss).call(this,t);let i=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(nr(i,t))}async _runChatCompletion(e,t,r){for(let s of t.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,t,r)}async _runFunctions(e,t,r){var h;let s="function",{function_call:i="auto",stream:o,...a}=t,c=typeof i!="string"&&(i==null?void 0:i.name),{maxChatCompletions:l=Cs}=r||{},d={};for(let m of t.functions)d[m.name||m.function.name]=m;let u=t.functions.map(m=>({name:m.name||m.function.name,parameters:m.parameters,description:m.description}));for(let m of t.messages)this._addMessage(m,!1);for(let m=0;m<l;++m){let v=(h=(await this._createChatCompletion(e,{...a,function_call:i,functions:u,messages:[...this.messages]},r)).choices[0])==null?void 0:h.message;if(!v)throw new A("missing message in ChatCompletion response");if(!v.function_call)return;let{name:g,arguments:O}=v.function_call,b=d[g];if(b){if(c&&c!==g){let D=`Invalid function_call: ${JSON.stringify(g)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:s,name:g,content:D});continue}}else{let D=`Invalid function_call: ${JSON.stringify(g)}. Available options are: ${u.map(T=>JSON.stringify(T.name)).join(", ")}. Please try again`;this._addMessage({role:s,name:g,content:D});continue}let C;try{C=fn(b)?await b.parse(O):O}catch(D){this._addMessage({role:s,name:g,content:D instanceof Error?D.message:String(D)});continue}let N=await b.function(C,this),P=Z(this,K,"m",Pn).call(this,N);if(this._addMessage({role:s,name:g,content:P}),c)return}}async _runTools(e,t,r){var m,f,v;let s="tool",{tool_choice:i="auto",stream:o,...a}=t,c=typeof i!="string"&&((m=i==null?void 0:i.function)==null?void 0:m.name),{maxChatCompletions:l=Cs}=r||{},d=t.tools.map(g=>{if(Je(g)){if(!g.$callback)throw new A("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:g.$callback,name:g.function.name,description:g.function.description||"",parameters:g.function.parameters,parse:g.$parseRaw,strict:!0}}}return g}),u={};for(let g of d)g.type==="function"&&(u[g.function.name||g.function.function.name]=g.function);let h="tools"in t?d.map(g=>g.type==="function"?{type:"function",function:{name:g.function.name||g.function.function.name,parameters:g.function.parameters,description:g.function.description,strict:g.function.strict}}:g):void 0;for(let g of t.messages)this._addMessage(g,!1);for(let g=0;g<l;++g){let b=(f=(await this._createChatCompletion(e,{...a,tool_choice:i,tools:h,messages:[...this.messages]},r)).choices[0])==null?void 0:f.message;if(!b)throw new A("missing message in ChatCompletion response");if(!((v=b.tool_calls)!=null&&v.length))return;for(let C of b.tool_calls){if(C.type!=="function")continue;let N=C.id,{name:P,arguments:D}=C.function,T=u[P];if(T){if(c&&c!==P){let k=`Invalid tool_call: ${JSON.stringify(P)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:s,tool_call_id:N,content:k});continue}}else{let k=`Invalid tool_call: ${JSON.stringify(P)}. Available options are: ${Object.keys(u).map(S=>JSON.stringify(S)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:N,content:k});continue}let M;try{M=fn(T)?await T.parse(D):D}catch(k){let S=k instanceof Error?k.message:String(k);this._addMessage({role:s,tool_call_id:N,content:S});continue}let x=await T.function(M,this),E=Z(this,K,"m",Pn).call(this,x);if(this._addMessage({role:s,tool_call_id:N,content:E}),c)return}}}};K=new WeakSet,wn=function(){var e;return(e=Z(this,K,"m",Mr).call(this).content)!=null?e:null},Mr=function(){var t,r;let e=this.messages.length;for(;e-- >0;){let s=this.messages[e];if(ke(s)){let{function_call:i,...o}=s,a={...o,content:(t=s.content)!=null?t:null,refusal:(r=s.refusal)!=null?r:null};return i&&(a.function_call=i),a}}throw new A("stream ended without producing a ChatCompletionMessage with role=assistant")},vn=function(){var e,t;for(let r=this.messages.length-1;r>=0;r--){let s=this.messages[r];if(ke(s)&&(s!=null&&s.function_call))return s.function_call;if(ke(s)&&((e=s==null?void 0:s.tool_calls)!=null&&e.length))return(t=s.tool_calls.at(-1))==null?void 0:t.function}},_n=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(mn(t)&&t.content!=null||pn(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(r=>{var s;return r.role==="assistant"&&((s=r.tool_calls)==null?void 0:s.some(i=>i.type==="function"&&i.id===t.tool_call_id))}))return t.content}},An=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},Ss=function(e){if(e.n!=null&&e.n>1)throw new A("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Pn=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var Fe=class extends xt{static runFunctions(e,t,r){let s=new Fe,i={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runFunctions"}};return s._run(()=>s._runFunctions(e,t,i)),s}static runTools(e,t,r){let s=new Fe,i={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,i)),s}_addMessage(e,t=!0){super._addMessage(e,t),ke(e)&&e.content&&this._emit("content",e.content)}};var W={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},In=class extends Error{},xn=class extends Error{};function _o(n,e=W.ALL){if(typeof n!="string")throw new TypeError(`expecting str, got ${typeof n}`);if(!n.trim())throw new Error(`${n} is empty`);return Ao(n.trim(),e)}var Ao=(n,e)=>{let t=n.length,r=0,s=h=>{throw new In(`${h} at position ${r}`)},i=h=>{throw new xn(`${h} at position ${r}`)},o=()=>(u(),r>=t&&s("Unexpected end of input"),n[r]==='"'?a():n[r]==="{"?c():n[r]==="["?l():n.substring(r,r+4)==="null"||W.NULL&e&&t-r<4&&"null".startsWith(n.substring(r))?(r+=4,null):n.substring(r,r+4)==="true"||W.BOOL&e&&t-r<4&&"true".startsWith(n.substring(r))?(r+=4,!0):n.substring(r,r+5)==="false"||W.BOOL&e&&t-r<5&&"false".startsWith(n.substring(r))?(r+=5,!1):n.substring(r,r+8)==="Infinity"||W.INFINITY&e&&t-r<8&&"Infinity".startsWith(n.substring(r))?(r+=8,1/0):n.substring(r,r+9)==="-Infinity"||W.MINUS_INFINITY&e&&1<t-r&&t-r<9&&"-Infinity".startsWith(n.substring(r))?(r+=9,-1/0):n.substring(r,r+3)==="NaN"||W.NAN&e&&t-r<3&&"NaN".startsWith(n.substring(r))?(r+=3,NaN):d()),a=()=>{let h=r,m=!1;for(r++;r<t&&(n[r]!=='"'||m&&n[r-1]==="\\");)m=n[r]==="\\"?!m:!1,r++;if(n.charAt(r)=='"')try{return JSON.parse(n.substring(h,++r-Number(m)))}catch(f){i(String(f))}else if(W.STR&e)try{return JSON.parse(n.substring(h,r-Number(m))+'"')}catch(f){return JSON.parse(n.substring(h,n.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},c=()=>{r++,u();let h={};try{for(;n[r]!=="}";){if(u(),r>=t&&W.OBJ&e)return h;let m=a();u(),r++;try{let f=o();Object.defineProperty(h,m,{value:f,writable:!0,enumerable:!0,configurable:!0})}catch(f){if(W.OBJ&e)return h;throw f}u(),n[r]===","&&r++}}catch(m){if(W.OBJ&e)return h;s("Expected '}' at end of object")}return r++,h},l=()=>{r++;let h=[];try{for(;n[r]!=="]";)h.push(o()),u(),n[r]===","&&r++}catch(m){if(W.ARR&e)return h;s("Expected ']' at end of array")}return r++,h},d=()=>{if(r===0){n==="-"&&W.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(n)}catch(m){if(W.NUM&e)try{return n[n.length-1]==="."?JSON.parse(n.substring(0,n.lastIndexOf("."))):JSON.parse(n.substring(0,n.lastIndexOf("e")))}catch(f){}i(String(m))}}let h=r;for(n[r]==="-"&&r++;n[r]&&!",]}".includes(n[r]);)r++;r==t&&!(W.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(n.substring(h,r))}catch(m){n.substring(h,r)==="-"&&W.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(n.substring(h,n.lastIndexOf("e")))}catch(f){i(String(f))}}},u=()=>{for(;r<t&&`
\r `.includes(n[r]);)r++};return o()},En=n=>_o(n,W.ALL^W.NUM);var Et=function(n,e,t,r,s){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?s.call(n,t):s?s.value=t:e.set(n,t),t},R=function(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)},j,Ie,Ct,De,Cn,Tr,Sn,Rn,On,kr,Mn,Rs,xe=class extends xt{constructor(e){super(),j.add(this),Ie.set(this,void 0),Ct.set(this,void 0),De.set(this,void 0),Et(this,Ie,e,"f"),Et(this,Ct,[],"f")}get currentChatCompletionSnapshot(){return R(this,De,"f")}static fromReadableStream(e){let t=new xe(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let s=new xe(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,t,r){var o;super._createChatCompletion;let s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),R(this,j,"m",Cn).call(this);let i=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let a of i)R(this,j,"m",Sn).call(this,a);if((o=i.controller.signal)!=null&&o.aborted)throw new H;return this._addChatCompletion(R(this,j,"m",kr).call(this))}async _fromReadableStream(e,t){var o;let r=t==null?void 0:t.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),R(this,j,"m",Cn).call(this),this._connected();let s=J.fromReadableStream(e,this.controller),i;for await(let a of s)i&&i!==a.id&&this._addChatCompletion(R(this,j,"m",kr).call(this)),R(this,j,"m",Sn).call(this,a),i=a.id;if((o=s.controller.signal)!=null&&o.aborted)throw new H;return this._addChatCompletion(R(this,j,"m",kr).call(this))}[(Ie=new WeakMap,Ct=new WeakMap,De=new WeakMap,j=new WeakSet,Cn=function(){this.ended||Et(this,De,void 0,"f")},Tr=function(t){let r=R(this,Ct,"f")[t.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},R(this,Ct,"f")[t.index]=r,r)},Sn=function(t){var s,i,o,a,c,l,d,u,h,m,f,v,g,O,b,C,N,P,D,T;if(this.ended)return;let r=R(this,j,"m",Rs).call(this,t);this._emit("chunk",t,r);for(let M of t.choices){let x=r.choices[M.index];M.delta.content!=null&&((s=x.message)==null?void 0:s.role)==="assistant"&&((i=x.message)!=null&&i.content)&&(this._emit("content",M.delta.content,x.message.content),this._emit("content.delta",{delta:M.delta.content,snapshot:x.message.content,parsed:x.message.parsed})),M.delta.refusal!=null&&((o=x.message)==null?void 0:o.role)==="assistant"&&((a=x.message)!=null&&a.refusal)&&this._emit("refusal.delta",{delta:M.delta.refusal,snapshot:x.message.refusal}),((c=M.logprobs)==null?void 0:c.content)!=null&&((l=x.message)==null?void 0:l.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(d=M.logprobs)==null?void 0:d.content,snapshot:(h=(u=x.logprobs)==null?void 0:u.content)!=null?h:[]}),((m=M.logprobs)==null?void 0:m.refusal)!=null&&((f=x.message)==null?void 0:f.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(v=M.logprobs)==null?void 0:v.refusal,snapshot:(O=(g=x.logprobs)==null?void 0:g.refusal)!=null?O:[]});let E=R(this,j,"m",Tr).call(this,x);x.finish_reason&&(R(this,j,"m",On).call(this,x),E.current_tool_call_index!=null&&R(this,j,"m",Rn).call(this,x,E.current_tool_call_index));for(let k of(b=M.delta.tool_calls)!=null?b:[])E.current_tool_call_index!==k.index&&(R(this,j,"m",On).call(this,x),E.current_tool_call_index!=null&&R(this,j,"m",Rn).call(this,x,E.current_tool_call_index)),E.current_tool_call_index=k.index;for(let k of(C=M.delta.tool_calls)!=null?C:[]){let S=(N=x.message.tool_calls)==null?void 0:N[k.index];S!=null&&S.type&&((S==null?void 0:S.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(P=S.function)==null?void 0:P.name,index:k.index,arguments:S.function.arguments,parsed_arguments:S.function.parsed_arguments,arguments_delta:(T=(D=k.function)==null?void 0:D.arguments)!=null?T:""}):(S==null||S.type,void 0))}}},Rn=function(t,r){var o,a,c;if(R(this,j,"m",Tr).call(this,t).done_tool_calls.has(r))return;let i=(o=t.message.tool_calls)==null?void 0:o[r];if(!i)throw new Error("no tool call snapshot");if(!i.type)throw new Error("tool call snapshot missing `type`");if(i.type==="function"){let l=(c=(a=R(this,Ie,"f"))==null?void 0:a.tools)==null?void 0:c.find(d=>d.type==="function"&&d.function.name===i.function.name);this._emit("tool_calls.function.arguments.done",{name:i.function.name,index:r,arguments:i.function.arguments,parsed_arguments:Je(l)?l.$parseRaw(i.function.arguments):l!=null&&l.function.strict?JSON.parse(i.function.arguments):null})}else i.type},On=function(t){var s,i;let r=R(this,j,"m",Tr).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;let o=R(this,j,"m",Mn).call(this);this._emit("content.done",{content:t.message.content,parsed:o?o.$parseRaw(t.message.content):null})}t.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),(s=t.logprobs)!=null&&s.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),(i=t.logprobs)!=null&&i.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},kr=function(){if(this.ended)throw new A("stream has ended, this shouldn't happen");let t=R(this,De,"f");if(!t)throw new A("request ended without sending any chunks");return Et(this,De,void 0,"f"),Et(this,Ct,[],"f"),Po(t,R(this,Ie,"f"))},Mn=function(){var r;let t=(r=R(this,Ie,"f"))==null?void 0:r.response_format;return yn(t)?t:null},Rs=function(t){var d,u,h,m,f,v;var r,s,i,o;let a=R(this,De,"f"),{choices:c,...l}=t;a?Object.assign(a,l):a=Et(this,De,{...l,choices:[]},"f");for(let{delta:g,finish_reason:O,index:b,logprobs:C=null,...N}of t.choices){let P=a.choices[b];if(P||(P=a.choices[b]={finish_reason:O,index:b,message:{},logprobs:C,...N}),C)if(!P.logprobs)P.logprobs=Object.assign({},C);else{let{content:S,refusal:se,..._e}=C;Object.assign(P.logprobs,_e),S&&((d=(r=P.logprobs).content)!=null||(r.content=[]),P.logprobs.content.push(...S)),se&&((u=(s=P.logprobs).refusal)!=null||(s.refusal=[]),P.logprobs.refusal.push(...se))}if(O&&(P.finish_reason=O,R(this,Ie,"f")&&bn(R(this,Ie,"f")))){if(O==="length")throw new mt;if(O==="content_filter")throw new pt}if(Object.assign(P,N),!g)continue;let{content:D,refusal:T,function_call:M,role:x,tool_calls:E,...k}=g;if(Object.assign(P.message,k),T&&(P.message.refusal=(P.message.refusal||"")+T),x&&(P.message.role=x),M&&(P.message.function_call?(M.name&&(P.message.function_call.name=M.name),M.arguments&&((h=(i=P.message.function_call).arguments)!=null||(i.arguments=""),P.message.function_call.arguments+=M.arguments)):P.message.function_call=M),D&&(P.message.content=(P.message.content||"")+D,!P.message.refusal&&R(this,j,"m",Mn).call(this)&&(P.message.parsed=En(P.message.content))),E){P.message.tool_calls||(P.message.tool_calls=[]);for(let{index:S,id:se,type:_e,function:te,...wi}of E){let de=(m=(o=P.message.tool_calls)[S])!=null?m:o[S]={};Object.assign(de,wi),se&&(de.id=se),_e&&(de.type=_e),te&&((v=de.function)!=null||(de.function={name:(f=te.name)!=null?f:"",arguments:""})),te!=null&&te.name&&(de.function.name=te.name),te!=null&&te.arguments&&(de.function.arguments+=te.arguments,xs(R(this,Ie,"f"),de)&&(de.function.parsed_arguments=En(de.function.arguments)))}}}return a},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("chunk",s=>{let i=t.shift();i?i.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(let i of t)i.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(let i of t)i.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,o)=>t.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new J(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Po(n,e){let{id:t,choices:r,created:s,model:i,system_fingerprint:o,...a}=n,c={...a,id:t,choices:r.map(({message:l,finish_reason:d,index:u,logprobs:h,...m})=>{var C,N,P;if(!d)throw new A(`missing finish_reason for choice ${u}`);let{content:f=null,function_call:v,tool_calls:g,...O}=l,b=l.role;if(!b)throw new A(`missing role for choice ${u}`);if(v){let{arguments:D,name:T}=v;if(D==null)throw new A(`missing function_call.arguments for choice ${u}`);if(!T)throw new A(`missing function_call.name for choice ${u}`);return{...m,message:{content:f,function_call:{arguments:D,name:T},role:b,refusal:(C=l.refusal)!=null?C:null},finish_reason:d,index:u,logprobs:h}}return g?{...m,index:u,finish_reason:d,logprobs:h,message:{...O,role:b,content:f,refusal:(N=l.refusal)!=null?N:null,tool_calls:g.map((D,T)=>{let{function:M,type:x,id:E,...k}=D,{arguments:S,name:se,..._e}=M||{};if(E==null)throw new A(`missing choices[${u}].tool_calls[${T}].id
${Fr(n)}`);if(x==null)throw new A(`missing choices[${u}].tool_calls[${T}].type
${Fr(n)}`);if(se==null)throw new A(`missing choices[${u}].tool_calls[${T}].function.name
${Fr(n)}`);if(S==null)throw new A(`missing choices[${u}].tool_calls[${T}].function.arguments
${Fr(n)}`);return{...k,id:E,type:x,function:{..._e,name:se,arguments:S}}})}}:{...m,message:{...O,content:f,role:b,refusal:(P=l.refusal)!=null?P:null},finish_reason:d,index:u,logprobs:h}}),created:s,model:i,object:"chat.completion",...o?{system_fingerprint:o}:{}};return Is(c,e)}function Fr(n){return JSON.stringify(n)}var Ee=class extends xe{static fromReadableStream(e){let t=new Ee(null);return t._run(()=>t._fromReadableStream(e)),t}static runFunctions(e,t,r){let s=new Ee(null),i={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runFunctions"}};return s._run(()=>s._runFunctions(e,t,i)),s}static runTools(e,t,r){let s=new Ee(t),i={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,i)),s}};var sr=class extends y{parse(e,t){return Es(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t==null?void 0:t.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap(r=>nr(r,e))}runFunctions(e,t){return e.stream?Ee.runFunctions(this._client,e,t):Fe.runFunctions(this._client,e,t)}runTools(e,t){return e.stream?Ee.runTools(this._client,e,t):Fe.runTools(this._client,e,t)}stream(e,t){return xe.createChatCompletion(this._client,e,t)}};var St=class extends y{constructor(){super(...arguments),this.completions=new sr(this._client)}};(function(n){n.Completions=sr})(St||(St={}));var w=function(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)},re=function(n,e,t,r,s){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?s.call(n,t):s?s.value=t:e.set(n,t),t},V,Tn,pe,Dr,ce,Ge,Rt,Xe,Lr,ne,Nr,Br,ar,ir,or,Os,Ms,Ts,ks,Fs,Ds,Ns,X=class extends It{constructor(){super(...arguments),V.add(this),Tn.set(this,[]),pe.set(this,{}),Dr.set(this,{}),ce.set(this,void 0),Ge.set(this,void 0),Rt.set(this,void 0),Xe.set(this,void 0),Lr.set(this,void 0),ne.set(this,void 0),Nr.set(this,void 0),Br.set(this,void 0),ar.set(this,void 0)}[(Tn=new WeakMap,pe=new WeakMap,Dr=new WeakMap,ce=new WeakMap,Ge=new WeakMap,Rt=new WeakMap,Xe=new WeakMap,Lr=new WeakMap,ne=new WeakMap,Nr=new WeakMap,Br=new WeakMap,ar=new WeakMap,V=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",s=>{let i=t.shift();i?i.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(let i of t)i.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(let i of t)i.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,o)=>t.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new X;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){var i;let r=t==null?void 0:t.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();let s=J.fromReadableStream(e,this.controller);for await(let o of s)w(this,V,"m",ir).call(this,o);if((i=s.controller.signal)!=null&&i.aborted)throw new H;return this._addRun(w(this,V,"m",or).call(this))}toReadableStream(){return new J(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,s,i){let o=new X;return o._run(()=>o._runToolAssistantStream(e,t,r,s,{...i,headers:{...i==null?void 0:i.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,r,s,i){var l;let o=i==null?void 0:i.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let a={...s,stream:!0},c=await e.submitToolOutputs(t,r,a,{...i,signal:this.controller.signal});this._connected();for await(let d of c)w(this,V,"m",ir).call(this,d);if((l=c.controller.signal)!=null&&l.aborted)throw new H;return this._addRun(w(this,V,"m",or).call(this))}static createThreadAssistantStream(e,t,r){let s=new X;return s._run(()=>s._threadAssistantStream(e,t,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,r,s){let i=new X;return i._run(()=>i._runAssistantStream(e,t,r,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),i}currentEvent(){return w(this,Nr,"f")}currentRun(){return w(this,Br,"f")}currentMessageSnapshot(){return w(this,ce,"f")}currentRunStepSnapshot(){return w(this,ar,"f")}async finalRunSteps(){return await this.done(),Object.values(w(this,pe,"f"))}async finalMessages(){return await this.done(),Object.values(w(this,Dr,"f"))}async finalRun(){if(await this.done(),!w(this,Ge,"f"))throw Error("Final run was not received.");return w(this,Ge,"f")}async _createThreadAssistantStream(e,t,r){var a;let s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));let i={...t,stream:!0},o=await e.createAndRun(i,{...r,signal:this.controller.signal});this._connected();for await(let c of o)w(this,V,"m",ir).call(this,c);if((a=o.controller.signal)!=null&&a.aborted)throw new H;return this._addRun(w(this,V,"m",or).call(this))}async _createAssistantStream(e,t,r,s){var c;let i=s==null?void 0:s.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));let o={...r,stream:!0},a=await e.create(t,o,{...s,signal:this.controller.signal});this._connected();for await(let l of a)w(this,V,"m",ir).call(this,l);if((c=a.controller.signal)!=null&&c.aborted)throw new H;return this._addRun(w(this,V,"m",or).call(this))}static accumulateDelta(e,t){for(let[r,s]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=s;continue}let i=e[r];if(i==null){e[r]=s;continue}if(r==="index"||r==="type"){e[r]=s;continue}if(typeof i=="string"&&typeof s=="string")i+=s;else if(typeof i=="number"&&typeof s=="number")i+=s;else if(Yt(i)&&Yt(s))i=this.accumulateDelta(i,s);else if(Array.isArray(i)&&Array.isArray(s)){if(i.every(o=>typeof o=="string"||typeof o=="number")){i.push(...s);continue}for(let o of s){if(!Yt(o))throw new Error(`Expected array delta entry to be an object but got: ${o}`);let a=o.index;if(a==null)throw console.error(o),new Error("Expected array delta entry to have an `index` property");if(typeof a!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let c=i[a];c==null?i.push(o):i[a]=this.accumulateDelta(c,o)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${s}, accValue: ${i}`);e[r]=i}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,s){return await this._createAssistantStream(t,e,r,s)}async _runToolAssistantStream(e,t,r,s,i){return await this._createToolAssistantStream(r,e,t,s,i)}};ir=function(e){if(!this.ended)switch(re(this,Nr,e,"f"),w(this,V,"m",Ts).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":w(this,V,"m",Ns).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":w(this,V,"m",Ms).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":w(this,V,"m",Os).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},or=function(){if(this.ended)throw new A("stream has ended, this shouldn't happen");if(!w(this,Ge,"f"))throw Error("Final run has not been received");return w(this,Ge,"f")},Os=function(e){let[t,r]=w(this,V,"m",Fs).call(this,e,w(this,ce,"f"));re(this,ce,t,"f"),w(this,Dr,"f")[t.id]=t;for(let s of r){let i=t.content[s.index];(i==null?void 0:i.type)=="text"&&this._emit("textCreated",i.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(let s of e.data.delta.content){if(s.type=="text"&&s.text){let i=s.text,o=t.content[s.index];if(o&&o.type=="text")this._emit("textDelta",i,o.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=w(this,Rt,"f")){if(w(this,Xe,"f"))switch(w(this,Xe,"f").type){case"text":this._emit("textDone",w(this,Xe,"f").text,w(this,ce,"f"));break;case"image_file":this._emit("imageFileDone",w(this,Xe,"f").image_file,w(this,ce,"f"));break}re(this,Rt,s.index,"f")}re(this,Xe,t.content[s.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(w(this,Rt,"f")!==void 0){let s=e.data.content[w(this,Rt,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,w(this,ce,"f"));break;case"text":this._emit("textDone",s.text,w(this,ce,"f"));break}}w(this,ce,"f")&&this._emit("messageDone",e.data),re(this,ce,void 0,"f")}},Ms=function(e){let t=w(this,V,"m",ks).call(this,e);switch(re(this,ar,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let r=e.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&t.step_details.type=="tool_calls")for(let i of r.step_details.tool_calls)i.index==w(this,Lr,"f")?this._emit("toolCallDelta",i,t.step_details.tool_calls[i.index]):(w(this,ne,"f")&&this._emit("toolCallDone",w(this,ne,"f")),re(this,Lr,i.index,"f"),re(this,ne,t.step_details.tool_calls[i.index],"f"),w(this,ne,"f")&&this._emit("toolCallCreated",w(this,ne,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":re(this,ar,void 0,"f"),e.data.step_details.type=="tool_calls"&&w(this,ne,"f")&&(this._emit("toolCallDone",w(this,ne,"f")),re(this,ne,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},Ts=function(e){w(this,Tn,"f").push(e),this._emit("event",e)},ks=function(e){switch(e.event){case"thread.run.step.created":return w(this,pe,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=w(this,pe,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){let s=X.accumulateDelta(t,r.delta);w(this,pe,"f")[e.data.id]=s}return w(this,pe,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":w(this,pe,"f")[e.data.id]=e.data;break}if(w(this,pe,"f")[e.data.id])return w(this,pe,"f")[e.data.id];throw new Error("No snapshot available")},Fs=function(e,t){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content)for(let i of s.delta.content)if(i.index in t.content){let o=t.content[i.index];t.content[i.index]=w(this,V,"m",Ds).call(this,i,o)}else t.content[i.index]=i,r.push(i);return[t,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Ds=function(e,t){return X.accumulateDelta(t,e)},Ns=function(e){switch(re(this,Br,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":re(this,Ge,e.data,"f"),w(this,ne,"f")&&(this._emit("toolCallDone",w(this,ne,"f")),re(this,ne,void 0,"f"));break;case"thread.run.cancelling":break}};var Qe=class extends y{create(e,t,r){return this._client.post(`/threads/${e}/messages`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r==null?void 0:r.headers}})}retrieve(e,t,r){return this._client.get(`/threads/${e}/messages/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r==null?void 0:r.headers}})}update(e,t,r,s){return this._client.post(`/threads/${e}/messages/${t}`,{body:r,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers}})}list(e,t={},r){return F(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/messages`,Ot,{query:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r==null?void 0:r.headers}})}del(e,t,r){return this._client.delete(`/threads/${e}/messages/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r==null?void 0:r.headers}})}},Ot=class extends B{};Qe.MessagesPage=Ot;var Ye=class extends y{retrieve(e,t,r,s={},i){return F(s)?this.retrieve(e,t,r,{},s):this._client.get(`/threads/${e}/runs/${t}/steps/${r}`,{query:s,...i,headers:{"OpenAI-Beta":"assistants=v2",...i==null?void 0:i.headers}})}list(e,t,r={},s){return F(r)?this.list(e,t,{},r):this._client.getAPIList(`/threads/${e}/runs/${t}/steps`,Mt,{query:r,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers}})}},Mt=class extends B{};Ye.RunStepsPage=Mt;var Ce=class extends y{constructor(){super(...arguments),this.steps=new Ye(this._client)}create(e,t,r){var o;let{include:s,...i}=t;return this._client.post(`/threads/${e}/runs`,{query:{include:s},body:i,...r,headers:{"OpenAI-Beta":"assistants=v2",...r==null?void 0:r.headers},stream:(o=t.stream)!=null?o:!1})}retrieve(e,t,r){return this._client.get(`/threads/${e}/runs/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r==null?void 0:r.headers}})}update(e,t,r,s){return this._client.post(`/threads/${e}/runs/${t}`,{body:r,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers}})}list(e,t={},r){return F(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/runs`,Tt,{query:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r==null?void 0:r.headers}})}cancel(e,t,r){return this._client.post(`/threads/${e}/runs/${t}/cancel`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r==null?void 0:r.headers}})}async createAndPoll(e,t,r){let s=await this.create(e,t,r);return await this.poll(e,s.id,r)}createAndStream(e,t,r){return X.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let s={...r==null?void 0:r.headers,"X-Stainless-Poll-Helper":"true"};for(r!=null&&r.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=r.pollIntervalMs.toString());;){let{data:i,response:o}=await this.retrieve(e,t,{...r,headers:{...r==null?void 0:r.headers,...s}}).withResponse();switch(i.status){case"queued":case"in_progress":case"cancelling":let a=5e3;if(r!=null&&r.pollIntervalMs)a=r.pollIntervalMs;else{let c=o.headers.get("openai-poll-after-ms");if(c){let l=parseInt(c);isNaN(l)||(a=l)}}await Ae(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(e,t,r){return X.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r,s){var i;return this._client.post(`/threads/${e}/runs/${t}/submit_tool_outputs`,{body:r,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers},stream:(i=r.stream)!=null?i:!1})}async submitToolOutputsAndPoll(e,t,r,s){let i=await this.submitToolOutputs(e,t,r,s);return await this.poll(e,i.id,s)}submitToolOutputsStream(e,t,r,s){return X.createToolAssistantStream(e,t,this._client.beta.threads.runs,r,s)}},Tt=class extends B{};Ce.RunsPage=Tt;Ce.Steps=Ye;Ce.RunStepsPage=Mt;var ge=class extends y{constructor(){super(...arguments),this.runs=new Ce(this._client),this.messages=new Qe(this._client)}create(e={},t){return F(e)?this.create({},e):this._client.post("/threads",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}retrieve(e,t){return this._client.get(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}update(e,t,r){return this._client.post(`/threads/${e}`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r==null?void 0:r.headers}})}del(e,t){return this._client.delete(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}createAndRun(e,t){var r;return this._client.post("/threads/runs",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers},stream:(r=e.stream)!=null?r:!1})}async createAndRunPoll(e,t){let r=await this.createAndRun(e,t);return await this.runs.poll(r.thread_id,r.id,t)}createAndRunStream(e,t){return X.createThreadAssistantStream(e,this._client.beta.threads,t)}};ge.Runs=Ce;ge.RunsPage=Tt;ge.Messages=Qe;ge.MessagesPage=Ot;var Bs=async n=>{let e=await Promise.allSettled(n),t=e.filter(s=>s.status==="rejected");if(t.length){for(let s of t)console.error(s.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}let r=[];for(let s of e)s.status==="fulfilled"&&r.push(s.value);return r};var Ze=class extends y{create(e,t,r){return this._client.post(`/vector_stores/${e}/files`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r==null?void 0:r.headers}})}retrieve(e,t,r){return this._client.get(`/vector_stores/${e}/files/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r==null?void 0:r.headers}})}list(e,t={},r){return F(t)?this.list(e,{},t):this._client.getAPIList(`/vector_stores/${e}/files`,Ne,{query:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r==null?void 0:r.headers}})}del(e,t,r){return this._client.delete(`/vector_stores/${e}/files/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r==null?void 0:r.headers}})}async createAndPoll(e,t,r){let s=await this.create(e,t,r);return await this.poll(e,s.id,r)}async poll(e,t,r){let s={...r==null?void 0:r.headers,"X-Stainless-Poll-Helper":"true"};for(r!=null&&r.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=r.pollIntervalMs.toString());;){let i=await this.retrieve(e,t,{...r,headers:s}).withResponse(),o=i.data;switch(o.status){case"in_progress":let a=5e3;if(r!=null&&r.pollIntervalMs)a=r.pollIntervalMs;else{let c=i.response.headers.get("openai-poll-after-ms");if(c){let l=parseInt(c);isNaN(l)||(a=l)}}await Ae(a);break;case"failed":case"completed":return o}}}async upload(e,t,r){let s=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:s.id},r)}async uploadAndPoll(e,t,r){let s=await this.upload(e,t,r);return await this.poll(e,s.id,r)}},Ne=class extends B{};Ze.VectorStoreFilesPage=Ne;var kt=class extends y{create(e,t,r){return this._client.post(`/vector_stores/${e}/file_batches`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r==null?void 0:r.headers}})}retrieve(e,t,r){return this._client.get(`/vector_stores/${e}/file_batches/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r==null?void 0:r.headers}})}cancel(e,t,r){return this._client.post(`/vector_stores/${e}/file_batches/${t}/cancel`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r==null?void 0:r.headers}})}async createAndPoll(e,t,r){let s=await this.create(e,t);return await this.poll(e,s.id,r)}listFiles(e,t,r={},s){return F(r)?this.listFiles(e,t,{},r):this._client.getAPIList(`/vector_stores/${e}/file_batches/${t}/files`,Ne,{query:r,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers}})}async poll(e,t,r){let s={...r==null?void 0:r.headers,"X-Stainless-Poll-Helper":"true"};for(r!=null&&r.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=r.pollIntervalMs.toString());;){let{data:i,response:o}=await this.retrieve(e,t,{...r,headers:s}).withResponse();switch(i.status){case"in_progress":let a=5e3;if(r!=null&&r.pollIntervalMs)a=r.pollIntervalMs;else{let c=o.headers.get("openai-poll-after-ms");if(c){let l=parseInt(c);isNaN(l)||(a=l)}}await Ae(a);break;case"failed":case"cancelled":case"completed":return i}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},s){var h;if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let i=(h=s==null?void 0:s.maxConcurrency)!=null?h:5,o=Math.min(i,t.length),a=this._client,c=t.values(),l=[...r];async function d(m){for(let f of m){let v=await a.files.create({file:f,purpose:"assistants"},s);l.push(v.id)}}let u=Array(o).fill(c).map(d);return await Bs(u),await this.createAndPoll(e,{file_ids:l})}};var ye=class extends y{constructor(){super(...arguments),this.files=new Ze(this._client),this.fileBatches=new kt(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}retrieve(e,t){return this._client.get(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}update(e,t,r){return this._client.post(`/vector_stores/${e}`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r==null?void 0:r.headers}})}list(e={},t){return F(e)?this.list({},e):this._client.getAPIList("/vector_stores",Ft,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}del(e,t){return this._client.delete(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}},Ft=class extends B{};ye.VectorStoresPage=Ft;ye.Files=Ze;ye.VectorStoreFilesPage=Ne;ye.FileBatches=kt;var oe=class extends y{constructor(){super(...arguments),this.vectorStores=new ye(this._client),this.chat=new St(this._client),this.assistants=new Ke(this._client),this.threads=new ge(this._client)}};oe.VectorStores=ye;oe.VectorStoresPage=Ft;oe.Assistants=Ke;oe.AssistantsPage=At;oe.Threads=ge;var et=class extends y{create(e,t){var r;return this._client.post("/completions",{body:e,...t,stream:(r=e.stream)!=null?r:!1})}};var tt=class extends y{create(e,t){return this._client.post("/embeddings",{body:e,...t})}};var Be=class extends y{create(e,t){return this._client.post("/files",ie({body:e,...t}))}retrieve(e,t){return this._client.get(`/files/${e}`,t)}list(e={},t){return F(e)?this.list({},e):this._client.getAPIList("/files",rt,{query:e,...t})}del(e,t){return this._client.delete(`/files/${e}`,t)}content(e,t){return this._client.get(`/files/${e}/content`,{...t,__binaryResponse:!0})}retrieveContent(e,t){return this._client.get(`/files/${e}/content`,{...t,headers:{Accept:"application/json",...t==null?void 0:t.headers}})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=30*60*1e3}={}){let s=new Set(["processed","error","deleted"]),i=Date.now(),o=await this.retrieve(e);for(;!o.status||!s.has(o.status);)if(await Ae(t),o=await this.retrieve(e),Date.now()-i>r)throw new Oe({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return o}},rt=class extends B{};Be.FileObjectsPage=rt;var nt=class extends y{list(e,t={},r){return F(t)?this.list(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/checkpoints`,Dt,{query:t,...r})}},Dt=class extends B{};nt.FineTuningJobCheckpointsPage=Dt;var be=class extends y{constructor(){super(...arguments),this.checkpoints=new nt(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(`/fine_tuning/jobs/${e}`,t)}list(e={},t){return F(e)?this.list({},e):this._client.getAPIList("/fine_tuning/jobs",Nt,{query:e,...t})}cancel(e,t){return this._client.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return F(t)?this.listEvents(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/events`,Bt,{query:t,...r})}},Nt=class extends B{},Bt=class extends B{};be.FineTuningJobsPage=Nt;be.FineTuningJobEventsPage=Bt;be.Checkpoints=nt;be.FineTuningJobCheckpointsPage=Dt;var we=class extends y{constructor(){super(...arguments),this.jobs=new be(this._client)}};we.Jobs=be;we.FineTuningJobsPage=Nt;we.FineTuningJobEventsPage=Bt;var st=class extends y{createVariation(e,t){return this._client.post("/images/variations",ie({body:e,...t}))}edit(e,t){return this._client.post("/images/edits",ie({body:e,...t}))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}};var Le=class extends y{retrieve(e,t){return this._client.get(`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",it,e)}del(e,t){return this._client.delete(`/models/${e}`,t)}},it=class extends xr{};Le.ModelsPage=it;var ot=class extends y{create(e,t){return this._client.post("/moderations",{body:e,...t})}};var Lt=class extends y{create(e,t,r){return this._client.post(`/uploads/${e}/parts`,ie({body:t,...r}))}};var $e=class extends y{constructor(){super(...arguments),this.parts=new Lt(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(`/uploads/${e}/complete`,{body:t,...r})}};$e.Parts=Lt;var Ls,I=class extends Ir{constructor({baseURL:e=Qt("OPENAI_BASE_URL"),apiKey:t=Qt("OPENAI_API_KEY"),organization:r=(o=>(o=Qt("OPENAI_ORG_ID"))!=null?o:null)(),project:s=(a=>(a=Qt("OPENAI_PROJECT_ID"))!=null?a:null)(),...i}={}){var l;if(t===void 0)throw new A("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");let c={apiKey:t,organization:r,project:s,...i,baseURL:e||"https://api.openai.com/v1"};if(!c.dangerouslyAllowBrowser&&As())throw new A(`It looks like you're running in a browser-like environment.
This is disabled by default, as it risks exposing your secret API credentials to attackers.
If you understand the risks and have appropriate mitigations in place,
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
`);super({baseURL:c.baseURL,timeout:(l=c.timeout)!=null?l:6e5,httpAgent:c.httpAgent,maxRetries:c.maxRetries,fetch:c.fetch}),this.completions=new et(this),this.chat=new Me(this),this.embeddings=new tt(this),this.files=new Be(this),this.images=new st(this),this.audio=new me(this),this.moderations=new ot(this),this.models=new Le(this),this.fineTuning=new we(this),this.beta=new oe(this),this.batches=new Te(this),this.uploads=new $e(this),this._options=c,this.apiKey=t,this.organization=r,this.project=s}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(e){return Yr(e,{arrayFormat:"brackets"})}};Ls=I;I.OpenAI=Ls;I.DEFAULT_TIMEOUT=6e5;I.OpenAIError=A;I.APIError=$;I.APIConnectionError=Re;I.APIConnectionTimeoutError=Oe;I.APIUserAbortError=H;I.NotFoundError=Wt;I.ConflictError=Vt;I.RateLimitError=Kt;I.BadRequestError=jt;I.AuthenticationError=qt;I.InternalServerError=Jt;I.PermissionDeniedError=Ht;I.UnprocessableEntityError=zt;I.toFile=ln;I.fileFromPath=wr;I.Completions=et;I.Chat=Me;I.Embeddings=tt;I.Files=Be;I.FileObjectsPage=rt;I.Images=st;I.Audio=me;I.Moderations=ot;I.Models=Le;I.ModelsPage=it;I.FineTuning=we;I.Beta=oe;I.Batches=Te;I.BatchesPage=ze;I.Uploads=$e;var $s=I;var Us=require("electron"),kn=require("obsidian");async function Fn(n,e={}){var s;delete e.headers["content-length"];let t={};this&&"controller"in this&&(t.controller=this.controller);let r=e.signal||((s=t.controller)==null?void 0:s.signal);return p.debug("electronFetch request:",{url:n,method:e.method||"GET",headers:e.headers,hasBody:!!e.body,platform:kn.Platform.isMobileApp?"mobile":"desktop"}),kn.Platform.isMobileApp?(p.debug("Using native fetch (mobile platform)"),fetch(n,{...e,signal:r})):new Promise((i,o)=>{let a=()=>{c.removeAllListeners(),p.debug("Request cleanup completed")},c=Us.remote.net.request({url:n,method:e.method||"GET"});if(e.headers&&Object.entries(e.headers).forEach(([l,d])=>{c.setHeader(l,d)}),r!=null&&r.aborted){p.debug("Request aborted before start"),c.abort(),o(new Error("Aborted"));return}r==null||r.addEventListener("abort",()=>{p.debug("Request aborted by controller"),a(),c.abort(),o(new Error("Aborted"))}),c.on("response",l=>{if(r!=null&&r.aborted){p.debug("Request aborted during response");return}p.debug("Response received:",{status:l.statusCode,headers:l.headers});let{readable:d,writable:u}=new TransformStream({transform(f,v){v.enqueue(new Uint8Array(f))}}),h=u.getWriter(),m={status:l.statusCode||200,headers:l.headers};i(new Response(d,m)),l.on("data",async f=>{try{await h.ready,await h.write(f),p.debug("Chunk received:",{size:f.length})}catch(v){p.error("Error writing chunk:",v),a(),h.abort(v)}}),l.on("end",async()=>{try{await h.ready,await h.close(),p.debug("Response stream completed")}catch(f){p.error("Error closing writer:",f)}finally{a()}}),l.on("error",f=>{p.error("Response error:",f),a(),h.abort(f),o(f)})}),c.on("error",l=>{p.error("Request error:",l),a(),o(l)}),e.body&&c.write(e.body),c.end(),p.debug("Request sent")})}var js=require("obsidian");var ee=async(n,e={})=>{delete e.headers["content-length"],p.debug("obsidianFetch request:",{url:n,method:e.method||"GET",headers:e.headers,hasBody:!!e.body});let t={url:n,method:e.method||"GET",headers:e.headers};e.body&&(t.body=e.body,p.debug("Request body prepared:",t.body));try{p.debug("Sending request via requestUrl");let r=await(0,js.requestUrl)(t);p.debug("Response received:",{status:r.status,headers:r.headers,contentLength:r.text.length});let s={status:r.status,headers:r.headers};return new Response(r.text,s)}catch(r){throw p.error("Request failed:",r),r}};var qs=require("obsidian");var Bo=["cors policy","cors error","blocked by cors","cross-origin","access-control-allow-origin","access-control-allow-methods","access-control-allow-headers","preflight request","connection error","network error","failed to fetch","typeerror: failed to fetch","net::err_failed","fetch error","cors"],$t=class{constructor(e){this.settings=e;this.corsBlockedProviders=new Set}getProviderKey(e){return`${e.url||"unknown"}:${e.type}`}isMobilePlatform(){return qs.Platform.isMobileApp}shouldUseNativeFetch(){var e;return(e=this.settings.useNativeFetch)!=null?e:!1}getFetch(e){let t=e.name;return this.isBlocked(e)?(p.debug("Using obsidianFetch for CORS-blocked provider (API):",t),ee):this.isMobilePlatform()?(p.debug("Using obsidianFetch for mobile platform (API):",t),ee):this.shouldUseNativeFetch()?(p.debug("Using native fetch for provider (API):",t),globalThis.fetch):(p.debug("Using obsidianFetch for provider (API):",t),ee)}getStreamingFetch(e){let t=e.name;return this.isBlocked(e)?(p.debug("Using obsidianFetch for CORS-blocked provider (streaming):",t),ee):this.isMobilePlatform()?(p.debug("Using obsidianFetch for mobile platform (streaming):",t),ee):this.shouldUseNativeFetch()?(p.debug("Using native fetch for provider (streaming):",t),globalThis.fetch):(p.debug("Using electronFetch for provider (streaming):",t),Fn)}getFetchFunction(e){let t=e.name;return this.isBlocked(e)?(p.debug("Using obsidianFetch for CORS-blocked provider:",t),ee):this.isMobilePlatform()?(p.debug("Using obsidianFetch for mobile platform:",t),ee):this.shouldUseNativeFetch()?(p.debug("Using native fetch for provider:",t),globalThis.fetch):(p.debug("Using electronFetch for provider:",t),Fn)}isCorsError(e){if(!e)return!1;let t=(e.message||"").toLowerCase(),r=(e.name||"").toLowerCase();p.debug("Checking CORS error:",{message:e.message,name:e.name});let s=this.matchesCorsPattern(t,r);return p.debug("CORS error detection result:",{isCors:s}),s}matchesCorsPattern(e,t){return Bo.some(r=>e.includes(r)||t.includes(r))}async execute(e,t){if(p.debug("Starting execute operation for provider:",e.name),this.isBlocked(e))return p.debug("Provider already CORS-blocked, using obsidianFetch directly"),t(ee);let r=this.getStreamingFetch(e);try{let s=await t(r);return p.debug("Execute operation completed successfully"),s}catch(s){if(this.isCorsError(s))return p.debug("CORS error detected in execute, retrying with obsidianFetch"),this.markBlocked(e),t(ee);throw s}}async request(e,t){if(p.debug("Starting request operation for provider:",e.name),this.isBlocked(e))return p.debug("Provider already CORS-blocked, using obsidianFetch directly"),t(ee);let r=this.getFetch(e);try{let s=await t(r);return p.debug("Request operation completed successfully"),s}catch(s){if(this.isCorsError(s))return p.debug("CORS error detected in request, retrying with obsidianFetch"),this.markBlocked(e),t(ee);throw s}}getBlockedProviderCount(){return this.corsBlockedProviders.size}isBlocked(e){let t=this.getProviderKey(e);return this.corsBlockedProviders.has(t)}markBlocked(e){let t=this.getProviderKey(e);this.corsBlockedProviders.add(t),p.debug("Provider marked as CORS blocked:",{key:t,provider:e.name})}clear(){this.corsBlockedProviders.clear(),p.debug("All CORS blocked providers cleared")}};var Se=class{constructor(e){this.settings=e;this.fetchSelector=new $t(e)}getClient(e,t){let r;return t?r=t:r=this.fetchSelector.getFetchFunction(e),new $s({baseURL:e.url||(e.type==="openai"?void 0:"http://localhost:1234/v1"),apiKey:e.apiKey||"placeholder-key",dangerouslyAllowBrowser:!0,fetch:r,defaultHeaders:{"x-stainless-arch":null,"x-stainless-lang":null,"x-stainless-os":null,"x-stainless-package-version":null,"x-stainless-retry-count":null,"x-stainless-runtime":null,"x-stainless-runtime-version":null,"x-stainless-timeout":null}})}async fetchModels({provider:e,abortController:t}){if(t!=null&&t.signal.aborted)throw new Error("Aborted");let r=await this.fetchSelector.request(e,async s=>{if(t!=null&&t.signal.aborted)throw new Error("Aborted");return(await this.getClient(e,s).models.list()).data.map(a=>a.id)});if(t!=null&&t.signal.aborted)throw new Error("Aborted");return r}async embed(e){var l;let t=(l=e.input)!=null?l:e.text;if(!t)throw new Error("Either input or text parameter must be provided");let r=e.abortController;if(r!=null&&r.signal.aborted)throw new Error("Aborted");let s=Array.isArray(t)?t:[t],i=[],o=2048,a=[];for(let d=0;d<s.length;d+=o)a.push(s.slice(d,d+o));let c=[];for(let d of a){if(r!=null&&r.signal.aborted)throw new Error("Aborted");let u=async m=>{let v=await this.getClient(e.provider,m).embeddings.create({model:e.provider.model||"",input:d},{signal:r==null?void 0:r.signal});return p.debug("Embed response:",v),v.data.map(g=>g.embedding)},h=await this.fetchSelector.request(e.provider,u);if(i.push(...h),c.push(...d),e.onProgress&&e.onProgress([...c]),r!=null&&r.signal.aborted)throw new Error("Aborted")}return i}async executeOpenAIGeneration(e,t,r,s){var c,l,d;let i=[];if("messages"in e&&e.messages)i=e.messages.map(u=>{if(typeof u.content=="string")return{role:u.role,content:u.content};let h=[];return u.content.forEach(m=>{m.type==="text"?h.push({type:"text",text:m.text}):m.type==="image_url"&&h.push({type:"image_url",image_url:{url:m.image_url.url}})}),{role:u.role,content:h}});else if("prompt"in e)if(e.systemPrompt&&i.push({role:"system",content:e.systemPrompt}),(c=e.images)!=null&&c.length){let u=[{type:"text",text:e.prompt}];e.images.forEach(h=>{u.push({type:"image_url",image_url:{url:h}})}),i.push({role:"user",content:u})}else i.push({role:"user",content:e.prompt});else throw new Error("Either messages or prompt must be provided");p.debug("Sending chat request to OpenAI");let o=await t.chat.completions.create({model:e.provider.model||"",messages:i,stream:!0,...e.options},{signal:s==null?void 0:s.signal}),a="";for await(let u of o){if(s!=null&&s.signal.aborted)throw new Error("Aborted");let h=(d=(l=u.choices[0])==null?void 0:l.delta)==null?void 0:d.content;h&&(a+=h,r&&r(h,a))}return a}async execute(e){var i,o,a,c;p.debug("Starting execute process with params:",{model:e.provider.model,messagesCount:((i=e.messages)==null?void 0:i.length)||0,promptLength:((o=e.prompt)==null?void 0:o.length)||0,systemPromptLength:((a=e.systemPrompt)==null?void 0:a.length)||0,hasImages:!!((c=e.images)!=null&&c.length)});let t=e,r=t.abortController,s=t.onProgress;if(r!=null&&r.signal.aborted)return Promise.reject(new Error("Aborted"));try{return await this.fetchSelector.execute(e.provider,async l=>{let d=this.getClient(e.provider,l);return this.executeOpenAIGeneration(e,d,(u,h)=>{if(s&&s(u,h),r!=null&&r.signal.aborted)throw new Error("Aborted")},r)})}catch(l){let d=l;if(d.message==="Aborted")return Promise.reject(d);throw d}}};var z=typeof globalThis!="undefined"&&globalThis||typeof self!="undefined"&&self||typeof global!="undefined"&&global||{},G={searchParams:"URLSearchParams"in z,iterable:"Symbol"in z&&"iterator"in Symbol,blob:"FileReader"in z&&"Blob"in z&&function(){try{return new Blob,!0}catch(n){return!1}}(),formData:"FormData"in z,arrayBuffer:"ArrayBuffer"in z};function Lo(n){return n&&DataView.prototype.isPrototypeOf(n)}G.arrayBuffer&&(Hs=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],Vs=ArrayBuffer.isView||function(n){return n&&Hs.indexOf(Object.prototype.toString.call(n))>-1});var Hs,Vs;function Ut(n){if(typeof n!="string"&&(n=String(n)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(n)||n==="")throw new TypeError('Invalid character in header field name: "'+n+'"');return n.toLowerCase()}function Nn(n){return typeof n!="string"&&(n=String(n)),n}function Bn(n){var e={next:function(){var t=n.shift();return{done:t===void 0,value:t}}};return G.iterable&&(e[Symbol.iterator]=function(){return e}),e}function q(n){this.map={},n instanceof q?n.forEach(function(e,t){this.append(t,e)},this):Array.isArray(n)?n.forEach(function(e){if(e.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+e.length);this.append(e[0],e[1])},this):n&&Object.getOwnPropertyNames(n).forEach(function(e){this.append(e,n[e])},this)}q.prototype.append=function(n,e){n=Ut(n),e=Nn(e);var t=this.map[n];this.map[n]=t?t+", "+e:e};q.prototype.delete=function(n){delete this.map[Ut(n)]};q.prototype.get=function(n){return n=Ut(n),this.has(n)?this.map[n]:null};q.prototype.has=function(n){return this.map.hasOwnProperty(Ut(n))};q.prototype.set=function(n,e){this.map[Ut(n)]=Nn(e)};q.prototype.forEach=function(n,e){for(var t in this.map)this.map.hasOwnProperty(t)&&n.call(e,this.map[t],t,this)};q.prototype.keys=function(){var n=[];return this.forEach(function(e,t){n.push(t)}),Bn(n)};q.prototype.values=function(){var n=[];return this.forEach(function(e){n.push(e)}),Bn(n)};q.prototype.entries=function(){var n=[];return this.forEach(function(e,t){n.push([t,e])}),Bn(n)};G.iterable&&(q.prototype[Symbol.iterator]=q.prototype.entries);function Dn(n){if(!n._noBody){if(n.bodyUsed)return Promise.reject(new TypeError("Already read"));n.bodyUsed=!0}}function zs(n){return new Promise(function(e,t){n.onload=function(){e(n.result)},n.onerror=function(){t(n.error)}})}function $o(n){var e=new FileReader,t=zs(e);return e.readAsArrayBuffer(n),t}function Uo(n){var e=new FileReader,t=zs(e),r=/charset=([A-Za-z0-9_-]+)/.exec(n.type),s=r?r[1]:"utf-8";return e.readAsText(n,s),t}function jo(n){for(var e=new Uint8Array(n),t=new Array(e.length),r=0;r<e.length;r++)t[r]=String.fromCharCode(e[r]);return t.join("")}function Ws(n){if(n.slice)return n.slice(0);var e=new Uint8Array(n.byteLength);return e.set(new Uint8Array(n)),e.buffer}function Ks(){return this.bodyUsed=!1,this._initBody=function(n){this.bodyUsed=this.bodyUsed,this._bodyInit=n,n?typeof n=="string"?this._bodyText=n:G.blob&&Blob.prototype.isPrototypeOf(n)?this._bodyBlob=n:G.formData&&FormData.prototype.isPrototypeOf(n)?this._bodyFormData=n:G.searchParams&&URLSearchParams.prototype.isPrototypeOf(n)?this._bodyText=n.toString():G.arrayBuffer&&G.blob&&Lo(n)?(this._bodyArrayBuffer=Ws(n.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):G.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(n)||Vs(n))?this._bodyArrayBuffer=Ws(n):this._bodyText=n=Object.prototype.toString.call(n):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof n=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):G.searchParams&&URLSearchParams.prototype.isPrototypeOf(n)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},G.blob&&(this.blob=function(){var n=Dn(this);if(n)return n;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var n=Dn(this);return n||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(G.blob)return this.blob().then($o);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var n=Dn(this);if(n)return n;if(this._bodyBlob)return Uo(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(jo(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},G.formData&&(this.formData=function(){return this.text().then(Wo)}),this.json=function(){return this.text().then(JSON.parse)},this}var qo=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function Ho(n){var e=n.toUpperCase();return qo.indexOf(e)>-1?e:n}function ct(n,e){if(!(this instanceof ct))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');e=e||{};var t=e.body;if(n instanceof ct){if(n.bodyUsed)throw new TypeError("Already read");this.url=n.url,this.credentials=n.credentials,e.headers||(this.headers=new q(n.headers)),this.method=n.method,this.mode=n.mode,this.signal=n.signal,!t&&n._bodyInit!=null&&(t=n._bodyInit,n.bodyUsed=!0)}else this.url=String(n);if(this.credentials=e.credentials||this.credentials||"same-origin",(e.headers||!this.headers)&&(this.headers=new q(e.headers)),this.method=Ho(e.method||this.method||"GET"),this.mode=e.mode||this.mode||null,this.signal=e.signal||this.signal||function(){if("AbortController"in z){var i=new AbortController;return i.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&t)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(t),(this.method==="GET"||this.method==="HEAD")&&(e.cache==="no-store"||e.cache==="no-cache")){var r=/([?&])_=[^&]*/;if(r.test(this.url))this.url=this.url.replace(r,"$1_="+new Date().getTime());else{var s=/\?/;this.url+=(s.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}ct.prototype.clone=function(){return new ct(this,{body:this._bodyInit})};function Wo(n){var e=new FormData;return n.trim().split("&").forEach(function(t){if(t){var r=t.split("="),s=r.shift().replace(/\+/g," "),i=r.join("=").replace(/\+/g," ");e.append(decodeURIComponent(s),decodeURIComponent(i))}}),e}function Vo(n){var e=new q,t=n.replace(/\r?\n[\t ]+/g," ");return t.split("\r").map(function(r){return r.indexOf(`
`)===0?r.substr(1,r.length):r}).forEach(function(r){var s=r.split(":"),i=s.shift().trim();if(i){var o=s.join(":").trim();try{e.append(i,o)}catch(a){console.warn("Response "+a.message)}}}),e}Ks.call(ct.prototype);function ve(n,e){if(!(this instanceof ve))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(e||(e={}),this.type="default",this.status=e.status===void 0?200:e.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=e.statusText===void 0?"":""+e.statusText,this.headers=new q(e.headers),this.url=e.url||"",this._initBody(n)}Ks.call(ve.prototype);ve.prototype.clone=function(){return new ve(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new q(this.headers),url:this.url})};ve.error=function(){var n=new ve(null,{status:200,statusText:""});return n.ok=!1,n.status=0,n.type="error",n};var zo=[301,302,303,307,308];ve.redirect=function(n,e){if(zo.indexOf(e)===-1)throw new RangeError("Invalid status code");return new ve(null,{status:e,headers:{location:n}})};var at=z.DOMException;try{new at}catch(n){at=function(e,t){this.message=e,this.name=t;var r=Error(e);this.stack=r.stack},at.prototype=Object.create(Error.prototype),at.prototype.constructor=at}function Js(n,e){return new Promise(function(t,r){var s=new ct(n,e);if(s.signal&&s.signal.aborted)return r(new at("Aborted","AbortError"));var i=new XMLHttpRequest;function o(){i.abort()}i.onload=function(){var l={statusText:i.statusText,headers:Vo(i.getAllResponseHeaders()||"")};s.url.indexOf("file://")===0&&(i.status<200||i.status>599)?l.status=200:l.status=i.status,l.url="responseURL"in i?i.responseURL:l.headers.get("X-Request-URL");var d="response"in i?i.response:i.responseText;setTimeout(function(){t(new ve(d,l))},0)},i.onerror=function(){setTimeout(function(){r(new TypeError("Network request failed"))},0)},i.ontimeout=function(){setTimeout(function(){r(new TypeError("Network request timed out"))},0)},i.onabort=function(){setTimeout(function(){r(new at("Aborted","AbortError"))},0)};function a(l){try{return l===""&&z.location.href?z.location.href:l}catch(d){return l}}if(i.open(s.method,a(s.url),!0),s.credentials==="include"?i.withCredentials=!0:s.credentials==="omit"&&(i.withCredentials=!1),"responseType"in i&&(G.blob?i.responseType="blob":G.arrayBuffer&&(i.responseType="arraybuffer")),e&&typeof e.headers=="object"&&!(e.headers instanceof q||z.Headers&&e.headers instanceof z.Headers)){var c=[];Object.getOwnPropertyNames(e.headers).forEach(function(l){c.push(Ut(l)),i.setRequestHeader(l,Nn(e.headers[l]))}),s.headers.forEach(function(l,d){c.indexOf(d)===-1&&i.setRequestHeader(d,l)})}else s.headers.forEach(function(l,d){i.setRequestHeader(d,l)});s.signal&&(s.signal.addEventListener("abort",o),i.onreadystatechange=function(){i.readyState===4&&s.signal.removeEventListener("abort",o)}),i.send(typeof s._bodyInit=="undefined"?null:s._bodyInit)})}Js.polyfill=!0;z.fetch||(z.fetch=Js,z.Headers=q,z.Request=ct,z.Response=ve);var Ko="0.5.10",Jo=Object.defineProperty,Xo=(n,e,t)=>e in n?Jo(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Ln=(n,e,t)=>(Xo(n,typeof e!="symbol"?e+"":e,t),t),cr=class extends Error{constructor(e,t){super(e),this.error=e,this.status_code=t,this.name="ResponseError",Error.captureStackTrace&&Error.captureStackTrace(this,cr)}},Un=class{constructor(e,t,r){Ln(this,"abortController"),Ln(this,"itr"),Ln(this,"doneCallback"),this.abortController=e,this.itr=t,this.doneCallback=r}abort(){this.abortController.abort()}async*[Symbol.asyncIterator](){for await(let e of this.itr){if("error"in e)throw new Error(e.error);if(yield e,e.done||e.status==="success"){this.doneCallback();return}}throw new Error("Did not receive done or success response in stream.")}},$r=async n=>{var r;if(n.ok)return;let e=`Error ${n.status}: ${n.statusText}`,t=null;if((r=n.headers.get("content-type"))!=null&&r.includes("application/json"))try{t=await n.json(),e=t.error||e}catch(s){console.log("Failed to parse error response as JSON")}else try{console.log("Getting text from response"),e=await n.text()||e}catch(s){console.log("Failed to get text from error response")}throw new cr(e,n.status)};function Go(){return typeof window!="undefined"&&window.navigator?`${window.navigator.platform.toLowerCase()} Browser/${navigator.userAgent};`:typeof process!="undefined"?`${process.arch} ${process.platform} Node.js/${process.version}`:""}var Ur=async(n,e,t={})=>{let r={"Content-Type":"application/json",Accept:"application/json","User-Agent":`ollama-js/${Ko} (${Go()})`};t.headers||(t.headers={});let s=Object.fromEntries(Object.entries(t.headers).filter(([i])=>!Object.keys(r).some(o=>o.toLowerCase()===i.toLowerCase())));return t.headers={...r,...s},n(e,t)},Xs=async(n,e,t)=>{let r=await Ur(n,e,{headers:t==null?void 0:t.headers});return await $r(r),r},Gs=async(n,e)=>{let t=await Ur(n,e,{method:"HEAD"});return await $r(t),t},Ue=async(n,e,t,r)=>{let i=(a=>a!==null&&typeof a=="object"&&!Array.isArray(a))(t)?JSON.stringify(t):t,o=await Ur(n,e,{method:"POST",body:i,signal:r==null?void 0:r.signal,headers:r==null?void 0:r.headers});return await $r(o),o},Qo=async(n,e,t,r)=>{let s=await Ur(n,e,{method:"DELETE",body:JSON.stringify(t),headers:r==null?void 0:r.headers});return await $r(s),s},Yo=async function*(n){var s;let e=new TextDecoder("utf-8"),t="",r=n.getReader();for(;;){let{done:i,value:o}=await r.read();if(i)break;t+=e.decode(o);let a=t.split(`
`);t=(s=a.pop())!=null?s:"";for(let c of a)try{yield JSON.parse(c)}catch(l){console.warn("invalid json: ",c)}}for(let i of t.split(`
`).filter(o=>o!==""))try{yield JSON.parse(i)}catch(o){console.warn("invalid json: ",i)}},Zo=n=>{if(!n)return"http://127.0.0.1:11434";let e=n.includes("://");n.startsWith(":")&&(n=`http://127.0.0.1${n}`,e=!0),e||(n=`http://${n}`);let t=new URL(n),r=t.port;r||(e?r=t.protocol==="https:"?"443":"80":r="11434");let s=`${t.protocol}//${t.hostname}:${r}${t.pathname}`;return s.endsWith("/")&&(s=s.slice(0,-1)),s},ea=Object.defineProperty,ta=(n,e,t)=>e in n?ea(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,$n=(n,e,t)=>(ta(n,typeof e!="symbol"?e+"":e,t),t),jn=class{constructor(e){var t,r;$n(this,"config"),$n(this,"fetch"),$n(this,"ongoingStreamedRequests",[]),this.config={host:"",headers:e==null?void 0:e.headers},e!=null&&e.proxy||(this.config.host=Zo((t=e==null?void 0:e.host)!=null?t:"http://127.0.0.1:11434")),this.fetch=(r=e==null?void 0:e.fetch)!=null?r:fetch}abort(){for(let e of this.ongoingStreamedRequests)e.abort();this.ongoingStreamedRequests.length=0}async processStreamableRequest(e,t){var i;t.stream=(i=t.stream)!=null?i:!1;let r=`${this.config.host}/api/${e}`;if(t.stream){let o=new AbortController,a=await Ue(this.fetch,r,t,{signal:o.signal,headers:this.config.headers});if(!a.body)throw new Error("Missing body");let c=Yo(a.body),l=new Un(o,c,()=>{let d=this.ongoingStreamedRequests.indexOf(l);d>-1&&this.ongoingStreamedRequests.splice(d,1)});return this.ongoingStreamedRequests.push(l),l}return await(await Ue(this.fetch,r,t,{headers:this.config.headers})).json()}async encodeImage(e){if(typeof e!="string"){let t=new Uint8Array(e),r="",s=t.byteLength;for(let i=0;i<s;i++)r+=String.fromCharCode(t[i]);return btoa(r)}return e}async generate(e){return e.images&&(e.images=await Promise.all(e.images.map(this.encodeImage.bind(this)))),this.processStreamableRequest("generate",e)}async chat(e){if(e.messages)for(let t of e.messages)t.images&&(t.images=await Promise.all(t.images.map(this.encodeImage.bind(this))));return this.processStreamableRequest("chat",e)}async create(e){return this.processStreamableRequest("create",{name:e.model,stream:e.stream,modelfile:e.modelfile,quantize:e.quantize})}async pull(e){return this.processStreamableRequest("pull",{name:e.model,stream:e.stream,insecure:e.insecure})}async push(e){return this.processStreamableRequest("push",{name:e.model,stream:e.stream,insecure:e.insecure})}async delete(e){return await Qo(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:"success"}}async copy(e){return await Ue(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:"success"}}async list(){return await(await Xs(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await Ue(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await Ue(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await Ue(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await Xs(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}},Bu=new jn;var je=Ei(require("fs"),1),lt=require("path"),Qs=require("crypto"),Ys=require("os");var lr=class extends jn{async encodeImage(e){if(typeof e!="string")return Buffer.from(e).toString("base64");try{if(je.default.existsSync(e)){let t=await je.promises.readFile((0,lt.resolve)(e));return Buffer.from(t).toString("base64")}}catch(t){}return e}async parseModelfile(e,t=process.cwd()){let r=[],s=e.split(`
`);for(let i of s){let[o,a]=i.split(" ",2);if(["FROM","ADAPTER"].includes(o.toUpperCase())){let c=this.resolvePath(a.trim(),t);await this.fileExists(c)?r.push(`${o} @${await this.createBlob(c)}`):r.push(`${o} ${a}`)}else r.push(i)}return r.join(`
`)}resolvePath(e,t){return e.startsWith("~")?(0,lt.join)((0,Ys.homedir)(),e.slice(1)):(0,lt.resolve)(t,e)}async fileExists(e){try{return await je.promises.access(e),!0}catch(t){return!1}}async createBlob(e){if(typeof ReadableStream=="undefined")throw new Error("Streaming uploads are not supported in this environment.");let t=(0,je.createReadStream)(e),s=`sha256:${await new Promise((i,o)=>{let a=(0,Qs.createHash)("sha256");t.on("data",c=>a.update(c)),t.on("end",()=>i(a.digest("hex"))),t.on("error",o)})}`;try{await Gs(this.fetch,`${this.config.host}/api/blobs/${s}`)}catch(i){if(i instanceof Error&&i.message.includes("404")){let o=new ReadableStream({start(a){t.on("data",c=>{a.enqueue(c)}),t.on("end",()=>{a.close()}),t.on("error",c=>{a.error(c)})}});await Ue(this.fetch,`${this.config.host}/api/blobs/${s}`,o)}else throw i}return s}async create(e){let t="";if(e.path)t=await je.promises.readFile(e.path,{encoding:"utf8"}),t=await this.parseModelfile(t,(0,lt.dirname)(e.path));else if(e.modelfile)t=await this.parseModelfile(e.modelfile);else throw new Error("Must provide either path or modelfile to create a model");return e.modelfile=t,e.stream?super.create(e):super.create(e)}},ju=new lr;var ra=2.5,jr=2048,Zs=2048,na=1.2,dr=class{constructor(e){this.settings=e;this.modelInfoCache=new Map,this.fetchSelector=new $t(e)}getClient(e,t){let r={host:e.url,fetch:t};return e.apiKey&&(r.headers=r.headers||{},r.headers.Authorization=`Bearer ${e.apiKey}`),new lr(r)}getDefaultModelInfo(){return{contextLength:0,lastContextLength:jr}}async getCachedModelInfo(e,t){let r=`${e.url}_${t}`,s=this.modelInfoCache.get(r);if(s)return s;let i=this.getClient(e,this.settings.useNativeFetch?fetch:ee);try{let o={model:t};e.type==="ollama-openwebui"&&(o={name:t});let a=await i.show(o),c=this.getDefaultModelInfo(),l=Object.entries(a.model_info).find(([d,u])=>(d.endsWith(".context_length")||d==="num_ctx")&&typeof u=="number"&&u>0);return l&&typeof l[1]=="number"&&(c.contextLength=l[1]),this.modelInfoCache.set(r,c),c}catch(o){return p.error("Failed to fetch model info:",o),this.getDefaultModelInfo()}}setModelInfoLastContextLength(e,t,r){let s=`${e.url}_${t}`,i=this.modelInfoCache.get(s);i&&this.modelInfoCache.set(s,{...i,lastContextLength:r||i.lastContextLength})}async fetchModels({provider:e,abortController:t}){if(t!=null&&t.signal.aborted)throw new Error("Aborted");let r=async i=>{if(t!=null&&t.signal.aborted)throw new Error("Aborted");let o=this.getClient(e,i);return t==null||t.signal.addEventListener("abort",()=>{o.abort()}),(await o.list()).models.map(c=>c.name)},s=await this.fetchSelector.request(e,r);if(t!=null&&t.signal.aborted)throw new Error("Aborted");return s}optimizeContext(e,t,r,s){let i=Math.ceil(e/ra);if(i<=t)return{num_ctx:t>r?t:void 0,shouldUpdate:!1};let o=Math.min(Math.ceil(Math.max(i,r)*na),s),a=o>t;return{num_ctx:o,shouldUpdate:a}}prepareChatMessages(e){var s;let t=[],r=[];if("messages"in e&&e.messages)e.messages.forEach(i=>{var o;if(typeof i.content=="string")t.push({role:i.role,content:i.content});else{let a=i.content.filter(c=>c.type==="text").map(c=>c.type==="text"?c.text:"").join(`
`);i.content.filter(c=>c.type==="image_url").forEach(c=>{var l;c.type==="image_url"&&((l=c.image_url)!=null&&l.url)&&r.push(c.image_url.url)}),t.push({role:i.role,content:a})}(o=i.images)!=null&&o.length&&r.push(...i.images)});else if("prompt"in e)e.systemPrompt&&t.push({role:"system",content:e.systemPrompt}),t.push({role:"user",content:e.prompt}),(s=e.images)!=null&&s.length&&r.push(...e.images);else throw new Error("Either messages or prompt must be provided");return{chatMessages:t,extractedImages:r}}async executeOllamaGeneration(e,t,r,s){var h,m;let i=await this.getCachedModelInfo(e.provider,e.provider.model||"").catch(f=>(p.error("Failed to get model info:",f),null)),{chatMessages:o,extractedImages:a}=this.prepareChatMessages(e),c=a.length>0?a.map(f=>f.replace(/^data:image\/(.*?);base64,/,"")):void 0,l={};if(!(c!=null&&c.length)){let f=o.reduce((O,b)=>O+b.content.length,0),{num_ctx:v,shouldUpdate:g}=this.optimizeContext(f,(i==null?void 0:i.lastContextLength)||jr,jr,(i==null?void 0:i.contextLength)||jr);v&&(l.num_ctx=v),g&&this.setModelInfoLastContextLength(e.provider,e.provider.model||"",v)}if(e.options&&Object.assign(l,e.options),c!=null&&c.length){let f=o.map(v=>v.role).lastIndexOf("user");f!==-1?o[f]={...o[f],images:c}:o.length>0?o[o.length-1]={...o[o.length-1],images:c}:o.push({role:"user",content:"",images:c})}p.debug("Sending chat request to Ollama");let d=await t.chat({model:e.provider.model||"",messages:o,stream:!0,options:{...l}}),u="";for await(let f of d){if(s!=null&&s.signal.aborted)throw new Error("Aborted");let v=(h=f.message)==null?void 0:h.content;v&&(u+=v,r&&r(v,u)),f.done&&f.total_duration>0&&this.setModelInfoLastContextLength(e.provider,e.provider.model||"",(m=f.context)==null?void 0:m.length)}return u}async embed(e){var l;let t=(l=e.input)!=null?l:e.text;if(!t)throw new Error("Either input or text parameter must be provided");let r=e.abortController;if(r!=null&&r.signal.aborted)throw new Error("Aborted");let s=await this.getCachedModelInfo(e.provider,e.provider.model||""),i=Array.isArray(t)?Math.max(...t.map(d=>d.length)):t.length,{num_ctx:o,shouldUpdate:a}=this.optimizeContext(i,s.lastContextLength||Zs,Zs,s.contextLength);a&&this.setModelInfoLastContextLength(e.provider,e.provider.model||"",o);let c=async d=>{let u=this.getClient(e.provider,d);r==null||r.signal.addEventListener("abort",()=>{u.abort()});let h=Array.isArray(t)?t:[t],m=[],f=[];for(let v of h){if(r!=null&&r.signal.aborted)throw new Error("Aborted");let g=await u.embed({model:e.provider.model||"",input:v,options:{num_ctx:o}});if(m.push(g.embeddings[0]),p.debug("Embed response:",g),f.push(v),e.onProgress&&e.onProgress([...f]),r!=null&&r.signal.aborted)throw new Error("Aborted")}return m};return this.fetchSelector.request(e.provider,c)}async execute(e){let t=e,r=t.abortController,s=t.onProgress;if(r!=null&&r.signal.aborted)return Promise.reject(new Error("Aborted"));try{return await this.fetchSelector.execute(e.provider,async i=>{let o=this.getClient(e.provider,i);if(r==null||r.signal.addEventListener("abort",()=>{o.abort()}),r!=null&&r.signal.aborted)throw new Error("Aborted");return this.executeOllamaGeneration(e,o,(a,c)=>{if(s&&s(a,c),r!=null&&r.signal.aborted)throw new Error("Aborted")},r)})}catch(i){let o=i;if(o.message==="Aborted")return Promise.reject(o);throw o}}};var Wn=(n,e)=>e.some(t=>n instanceof t),ei,ti;function sa(){return ei||(ei=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function ia(){return ti||(ti=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var Vn=new WeakMap,qn=new WeakMap,qr=new WeakMap;function oa(n){let e=new Promise((t,r)=>{let s=()=>{n.removeEventListener("success",i),n.removeEventListener("error",o)},i=()=>{t(dt(n.result)),s()},o=()=>{r(n.error),s()};n.addEventListener("success",i),n.addEventListener("error",o)});return qr.set(e,n),e}function aa(n){if(Vn.has(n))return;let e=new Promise((t,r)=>{let s=()=>{n.removeEventListener("complete",i),n.removeEventListener("error",o),n.removeEventListener("abort",o)},i=()=>{t(),s()},o=()=>{r(n.error||new DOMException("AbortError","AbortError")),s()};n.addEventListener("complete",i),n.addEventListener("error",o),n.addEventListener("abort",o)});Vn.set(n,e)}var zn={get(n,e,t){if(n instanceof IDBTransaction){if(e==="done")return Vn.get(n);if(e==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return dt(n[e])},set(n,e,t){return n[e]=t,!0},has(n,e){return n instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in n}};function ii(n){zn=n(zn)}function ca(n){return ia().includes(n)?function(...e){return n.apply(Kn(this),e),dt(this.request)}:function(...e){return dt(n.apply(Kn(this),e))}}function la(n){return typeof n=="function"?ca(n):(n instanceof IDBTransaction&&aa(n),Wn(n,sa())?new Proxy(n,zn):n)}function dt(n){if(n instanceof IDBRequest)return oa(n);if(qn.has(n))return qn.get(n);let e=la(n);return e!==n&&(qn.set(n,e),qr.set(e,n)),e}var Kn=n=>qr.get(n);function oi(n,e,{blocked:t,upgrade:r,blocking:s,terminated:i}={}){let o=indexedDB.open(n,e),a=dt(o);return r&&o.addEventListener("upgradeneeded",c=>{r(dt(o.result),c.oldVersion,c.newVersion,dt(o.transaction),c)}),t&&o.addEventListener("blocked",c=>t(c.oldVersion,c.newVersion,c)),a.then(c=>{i&&c.addEventListener("close",()=>i()),s&&c.addEventListener("versionchange",l=>s(l.oldVersion,l.newVersion,l))}).catch(()=>{}),a}var da=["get","getKey","getAll","getAllKeys","count"],ua=["put","add","delete","clear"],Hn=new Map;function ri(n,e){if(!(n instanceof IDBDatabase&&!(e in n)&&typeof e=="string"))return;if(Hn.get(e))return Hn.get(e);let t=e.replace(/FromIndex$/,""),r=e!==t,s=ua.includes(t);if(!(t in(r?IDBIndex:IDBObjectStore).prototype)||!(s||da.includes(t)))return;let i=async function(o,...a){let c=this.transaction(o,s?"readwrite":"readonly"),l=c.store;return r&&(l=l.index(a.shift())),(await Promise.all([l[t](...a),s&&c.done]))[0]};return Hn.set(e,i),i}ii(n=>({...n,get:(e,t,r)=>ri(e,t)||n.get(e,t,r),has:(e,t)=>!!ri(e,t)||n.has(e,t)}));var ha=["continue","continuePrimaryKey","advance"],ni={},Jn=new WeakMap,ai=new WeakMap,fa={get(n,e){if(!ha.includes(e))return n[e];let t=ni[e];return t||(t=ni[e]=function(...r){Jn.set(this,ai.get(this)[e](...r))}),t}};async function*ma(...n){let e=this;if(e instanceof IDBCursor||(e=await e.openCursor(...n)),!e)return;e=e;let t=new Proxy(e,fa);for(ai.set(t,e),qr.set(t,Kn(e));e;)yield t,e=await(Jn.get(t)||e.continue()),Jn.delete(t)}function si(n,e){return e===Symbol.asyncIterator&&Wn(n,[IDBIndex,IDBObjectStore,IDBCursor])||e==="iterate"&&Wn(n,[IDBIndex,IDBObjectStore])}ii(n=>({...n,get(e,t,r){return si(e,t)?ma:n.get(e,t,r)},has(e,t){return si(e,t)||n.has(e,t)}}));async function pa(n,e=16){if(!(crypto!=null&&crypto.subtle))throw new Error("crypto.subtle is not available. This environment does not support secure hashing.");try{let r=new TextEncoder().encode(n),s=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(s)).map(a=>a.toString(16).padStart(2,"0")).join("").substring(0,e)}catch(t){throw new Error(`Failed to generate secure hash: ${t instanceof Error?t.message:"Unknown error"}`)}}var ci=n=>pa(n,16);var qe=class{constructor(){this.db=null;this.vaultId="";this.dbName=""}static getInstance(){return qe.instance||(qe.instance=new qe),qe.instance}async init(e){try{if(this.db&&this.vaultId!==e&&await this.close(),this.db&&this.vaultId===e)return;this.vaultId=e;let t=await ci("ai-providers-plugin");this.dbName=`aiProviders_${t}_${this.vaultId}`,this.db=await oi(this.dbName,1,{upgrade(r){r.createObjectStore("embeddings")}})}catch(t){console.error("Failed to initialize embeddings cache database:",t),this.db=null}}async getEmbeddings(e){if(this.db)try{return await this.db.get("embeddings",e)}catch(t){console.error("Error getting embeddings from cache:",t);return}}async setEmbeddings(e,t){if(this.db)try{await this.db.put("embeddings",t,e)}catch(r){console.error("Error setting embeddings in cache:",r)}}async clearEmbeddings(){if(this.db)try{await this.db.clear("embeddings")}catch(e){console.error("Error clearing embeddings cache:",e)}}async clearAll(){if(this.db)try{await this.db.clear("embeddings")}catch(e){console.error("Error clearing all caches:",e)}}async close(){this.db&&(this.db.close(),this.db=null)}isInitialized(){return this.db!==null}},ut=qe.getInstance();var Hr=class{constructor(e){this.embedFunction=e}async embedWithCache(e){var a;if(!e.chunks)return this.embedFunction(e);let t=e.abortController;if(t!=null&&t.signal.aborted)throw new Error("Aborted");let r=await this.generateCacheKey(e),{chunks:s}=e,i=await this.loadCachedChunks(e,r),o=s.filter(c=>!i.has(c));if(o.length>0){if(t!=null&&t.signal.aborted)throw new Error("Aborted");await this.embedAndCacheChunks(e,o,i,r)}return(a=e.onProgress)==null||a.call(e,s),s.map(c=>i.get(c))}async embedAndCacheChunks(e,t,r,s){let i=e.abortController;if(i!=null&&i.signal.aborted)throw new Error("Aborted");let o=await this.embedFunction({...e,input:t});t.forEach((a,c)=>r.set(a,o[c])),await this.saveCachedChunks(s,e.provider,r)}async loadCachedChunks(e,t){let r=await ut.getEmbeddings(t).catch(s=>(p.error("Error reading from embeddings cache:",s),null));return(r==null?void 0:r.providerId)===e.provider.id&&(r==null?void 0:r.providerModel)===e.provider.model?new Map(r.chunks.map(s=>[s.content,s.embedding])):new Map}async saveCachedChunks(e,t,r){if(!t.model)return;let s=Array.from(r,([i,o])=>({content:i,embedding:o}));await ut.setEmbeddings(e,{providerId:t.id,providerModel:t.model,chunks:s}).catch(i=>{p.error("Error writing to embeddings cache:",i)})}async generateCacheKey(e){return`embed:${e.provider.id}:${e.provider.model}`}};var ur=1e3;function li(n){return p.debug("Preprocessing content",{contentLength:n.length}),n.replace(/^---\n[\s\S]*?\n---\n/,"").replace(/```[\s\S]*?```/g,"").replace(/^(#+)\s*$\n/gm,"").replace(/^(#+)\s*(?!$)[^\n]+\n(?=\s*(?:\1#|\s*$)(?!\s*\S))/gm,"").replace(/\n{3,}/g,`
`).replace(/[ \t]+$/gm,"").replace(/\n+$/,"")}function di(n){return n.length<ur?[n.trim()]:(p.debug("Splitting content",{contentLength:n.length}),n.split(/^---$/m).flatMap(t=>ga(t.trim())).flatMap(t=>ya(t)).map(t=>t.trim()).filter(t=>t.length>0))}function ga(n){let e=/^(#{1,6})\s+(.+)$/gm,t=[],r=0,s="",i;for(;(i=e.exec(n))!==null;)r<i.index&&t.push(s+n.slice(r,i.index).trim()),s=i[0]+`
`,r=e.lastIndex;return r<n.length&&t.push(s+n.slice(r).trim()),t.filter(o=>o.length>0)}function ya(n){let t=n.split(`
`).reduce(ba,{chunks:[],currentChunk:"",inList:!1,lastNonListText:""}),r=t.currentChunk?[...t.chunks,t.currentChunk.trim()]:t.chunks.map(i=>i.trim()),s=[];for(let i=0;i<r.length;i++){let o=r[i];if(/^#{1,6}\s+.+$/.test(o.trim())&&o.trim().split(`
`).length===1&&i<r.length-1){let c=r[i+1];s.push(o+`
`+c),i++}else s.push(o)}return s}function ba(n,e){let t=/^(\s*[-*+]|\s*\d+\.)/.test(e);return/^(#{1,6}\s|[*_]{2}).+/.test(e)?wa(n,e):t?va(n,e):n.inList&&!e.trim()?{...n,currentChunk:n.currentChunk+`
`+e}:_a(n,e)}function wa(n,e){let{chunks:t,currentChunk:r}=n;return{chunks:r?[...t,r.trim()]:t,currentChunk:e,inList:!1,lastNonListText:e}}function va(n,e){let{chunks:t,currentChunk:r,inList:s,lastNonListText:i}=n;return!s&&r.length+e.length<=ur?{...n,currentChunk:r+`
`+e,inList:!0}:s?{...n,currentChunk:r+`
`+e}:{chunks:r?[...t,r.trim()]:t,currentChunk:i+`
`+e,inList:!0,lastNonListText:i}}function _a(n,e){let{chunks:t,currentChunk:r,lastNonListText:s}=n;if(e.length>ur){let o=e,a=[...t];for(r&&a.push(r.trim());o.length>0;){let c=Aa(o,ur);a.push(o.slice(0,c).trim()),o=o.slice(c).trim()}return{chunks:a,currentChunk:"",inList:!1,lastNonListText:e}}let i=r+(r?`
`:"")+e;return i.length>ur?{chunks:[...t,r.trim()],currentChunk:e,inList:!1,lastNonListText:e.trim()?e:s}:{...n,currentChunk:i,inList:!1,lastNonListText:e.trim()?e:s}}function Aa(n,e){if(n.length<=e)return n.length;let t=e;for(;t>0&&!/\s/.test(n[t]);)t--;return t>0?t:e}var Vr=class{constructor(e,t){this.providers=[];this.version=3;this.plugin=t,this.providers=t.settings.providers||[],this.app=e,this.handlers={openai:new Se(t.settings),openrouter:new Se(t.settings),ollama:new dr(t.settings),"ollama-openwebui":new dr(t.settings),gemini:new Se(t.settings),lmstudio:new Se(t.settings),groq:new Se(t.settings),ai302:new Se(t.settings)},this.cachedEmbeddingsService=new Hr(this.embedForce.bind(this))}async initEmbeddingsCache(){try{let e=this.app.appId||"default";await ut.init(e)}catch(e){p.error("Failed to initialize embeddings cache:",e)}}getHandler(e){return this.handlers[e]}async embedForce(e){let t=this.getHandler(e.provider.type);if(!t)throw new Error(`Handler not found for provider type: ${e.provider.type}`);return t.embed(e)}async embed(e){try{if(!e.input)throw new Error("Input is required for embedding");let t=e.abortController;if(t!=null&&t.signal.aborted)throw new Error("Aborted");let r=Array.isArray(e.input)?e.input:[e.input],s={...e,input:r,chunks:r};return this.cachedEmbeddingsService.embedWithCache(s)}catch(t){let r=t instanceof Error?t.message:_.t("errors.failedToEmbed");throw new Wr.Notice(r),t}}async fetchModels(e){try{let t="provider"in e?e.provider:e,r="abortController"in e?e.abortController:void 0;if(r!=null&&r.signal.aborted)throw new Error("Aborted");let s=this.getHandler(t.type);if(!s||!s.fetchModels)throw new Error(`Handler not found or does not support fetchModels for provider type: ${t.type}`);return s.fetchModels({provider:t,abortController:r})}catch(t){let r=t instanceof Error?t.message:_.t("errors.failedToFetchModels");throw new Wr.Notice(r),t}}async execute(e){let t=this.getHandler(e.provider.type);if(!t)throw new Error(`Handler not found for provider type: ${e.provider.type}`);let r=e,s=Boolean(r.onProgress),i=Boolean(r.abortController);if(!(!s&&!i))return await t.execute(e);let a=new AbortController,c={data:[],end:[],error:[]};return t.execute({...e,abortController:a,onProgress:(d,u)=>{c.data.forEach(h=>h(d,u))}}).then(d=>{c.end.forEach(u=>u(d))}).catch(d=>{let u=d instanceof Error?d:new Error(String(d));c.error.forEach(h=>h(u))}),{onData(d){c.data.push(d)},onEnd(d){c.end.push(d)},onError(d){c.error.push(d)},abort:()=>{a.abort()}}}async migrateProvider(e){let t=["type","apiKey","url","model"];this.plugin.settings.providers=this.plugin.settings.providers||[];let r=this.plugin.settings.providers.find(s=>t.every(i=>s[i]===e[i]));return r?Promise.resolve(r):new Promise(s=>{new ht(this.app,`Migrate provider ${e.name}?`,async()=>{var i;(i=this.plugin.settings.providers)==null||i.push(e),await this.plugin.saveSettings(),s(e)},()=>{s(!1)}).open()})}checkCompatibility(e){if(e>this.version)throw new Wr.Notice(_.t("errors.pluginMustBeUpdatedFormatted")),new Error(_.t("errors.pluginMustBeUpdated"))}async retrieve(e){var h,m;let t=e.abortController;if(t!=null&&t.signal.aborted)throw new Error("Aborted");if(!e.query)return[];if(!e.documents||e.documents.length===0)return[];if(!this.getHandler(e.embeddingProvider.type))throw new Error(`Handler not found for provider type: ${e.embeddingProvider.type}`);let{chunks:s,totalChunks:i,documentChunkCounts:o}=this.processDocuments(e.documents);if(s.length===0)return[];let a=e.documents.length;(h=e.onProgress)==null||h.call(e,{totalDocuments:a,totalChunks:i,processedDocuments:[],processedChunks:[],processingType:"embedding"});let[c,l]=await Promise.all([this.embed({provider:e.embeddingProvider,input:e.query,abortController:e.abortController}),this.embed({provider:e.embeddingProvider,input:s.map(f=>f.content),abortController:e.abortController,onProgress:f=>{var b;if(t!=null&&t.signal.aborted)return;let v=f.length,g=s.slice(0,v),O=this.getProcessedDocs(g,o,e.documents);(b=e.onProgress)==null||b.call(e,{totalDocuments:a,totalChunks:i,processedDocuments:O,processedChunks:g,processingType:"embedding"})}})]).catch(f=>{var v,g;throw(g=(v=e.abortController)==null?void 0:v.signal)!=null&&g.aborted?new Error("Aborted"):f}),d=this.l2Normalize(c[0]),u=l.map(f=>this.l2Normalize(f));return(m=e.onProgress)==null||m.call(e,{totalDocuments:a,totalChunks:i,processedDocuments:this.getProcessedDocs(s,o,e.documents),processedChunks:s,processingType:"embedding"}),this.rankChunks(d,s,u)}processDocuments(e){var s;let t=[],r={};for(let i of e){let o=li(i.content),a=di(o),c=((s=i.meta)==null?void 0:s.id)||i.content;r[c]=0;for(let l of a)l.trim().length>0&&(t.push({content:l.trim(),document:i}),r[c]++)}return{chunks:t,totalChunks:t.length,documentChunkCounts:r}}getProcessedDocs(e,t,r){var o,a;let s={};for(let c of e){let l=((o=c.document.meta)==null?void 0:o.id)||c.document.content;s[l]=(s[l]||0)+1}let i=[];for(let c of r){let l=((a=c.meta)==null?void 0:a.id)||c.content;t[l]>0&&s[l]===t[l]&&i.push(c)}return i}rankChunks(e,t,r){let s=r.map(i=>this.dotProduct(e,i));return t.map((i,o)=>({document:i.document,score:s[o],content:i.content})).sort((i,o)=>o.score-i.score)}dotProduct(e,t){return e.reduce((r,s,i)=>r+s*t[i],0)}l2Normalize(e){let t=Math.sqrt(e.reduce((r,s)=>r+s*s,0))||1;return e.map(r=>r/t)}async cleanup(){try{ut.isInitialized()&&await ut.close()}catch(e){p.error("Error during cleanup:",e)}}};var ui='<g transform="translate(0,0) scale(4.1667)"><path d="M21.55 10.004a5.416 5.416 0 00-.478-4.501c-1.217-2.09-3.662-3.166-6.05-2.66A5.59 5.59 0 0010.831 1C8.39.995 6.224 2.546 5.473 4.838A5.553 5.553 0 001.76 7.496a5.487 5.487 0 00.691 6.5 5.416 5.416 0 00.477 4.502c1.217 2.09 3.662 3.165 6.05 2.66A5.586 5.586 0 0013.168 23c2.443.006 4.61-1.546 5.361-3.84a5.553 5.553 0 003.715-2.66 5.488 5.488 0 00-.693-6.497v.001zm-8.381 11.558a4.199 4.199 0 01-2.675-.954c.034-.018.093-.05.132-.074l4.44-2.53a.71.71 0 00.364-.623v-6.176l1.877 1.069c.02.01.033.029.036.05v5.115c-.003 2.274-1.87 4.118-4.174 4.123zM4.192 17.78a4.059 4.059 0 01-.498-2.763c.032.02.09.055.131.078l4.44 2.53c.225.13.504.13.73 0l5.42-3.088v2.138a.068.068 0 01-.027.057L9.9 19.288c-1.999 1.136-4.552.46-5.707-1.51h-.001zM3.023 8.216A4.15 4.15 0 015.198 6.41l-.002.151v5.06a.711.711 0 00.364.624l5.42 3.087-1.876 1.07a.067.067 0 01-.063.005l-4.489-2.559c-1.995-1.14-2.679-3.658-1.53-5.63h.001zm15.417 3.54l-5.42-3.088L14.896 7.6a.067.067 0 01.063-.006l4.489 2.557c1.998 1.14 2.683 3.662 1.529 5.633a4.163 4.163 0 01-2.174 1.807V12.38a.71.71 0 00-.363-.623zm1.867-2.773a6.04 6.04 0 00-.132-.078l-4.44-2.53a.731.731 0 00-.729 0l-5.42 3.088V7.325a.068.068 0 01.027-.057L14.1 4.713c2-1.137 4.555-.46 5.707 1.513.487.833.664 1.809.499 2.757h.001zm-11.741 3.81l-1.877-1.068a.065.065 0 01-.036-.051V6.559c.001-2.277 1.873-4.122 4.181-4.12.976 0 1.92.338 2.671.954-.034.018-.092.05-.131.073l-4.44 2.53a.71.71 0 00-.365.623l-.003 6.173v.002zm1.02-2.168L12 9.25l2.414 1.375v2.75L12 14.75l-2.415-1.375v-2.75z"></path></g>',hi='<g transform="translate(0,0) scale(4.1667)"><path d="M16.804 1.957l7.22 4.105v.087L16.73 10.21l.017-2.117-.821-.03c-1.059-.028-1.611.002-2.268.11-1.064.175-2.038.577-3.147 1.352L8.345 11.03c-.284.195-.495.336-.68.455l-.515.322-.397.234.385.23.53.338c.476.314 1.17.796 2.701 1.866 1.11.775 2.083 1.177 3.147 1.352l.3.045c.694.091 1.375.094 2.825.033l.022-2.159 7.22 4.105v.087L16.589 22l.014-1.862-.635.022c-1.386.042-2.137.002-3.138-.162-1.694-.28-3.26-.926-4.881-2.059l-2.158-1.5a21.997 21.997 0 00-.755-.498l-.467-.28a55.927 55.927 0 00-.76-.43C2.908 14.73.563 14.116 0 14.116V9.888l.14.004c.564-.007 2.91-.622 3.809-1.124l1.016-.58.438-.274c.428-.28 1.072-.726 2.686-1.853 1.621-1.133 3.186-1.78 4.881-2.059 1.152-.19 1.974-.213 3.814-.138l.02-1.907z"></path></g>',fi='<g transform="translate(0,0) scale(4.1667)"><path d="M12.036 2c-3.853-.035-7 3-7.036 6.781-.035 3.782 3.055 6.872 6.908 6.907h2.42v-2.566h-2.292c-2.407.028-4.38-1.866-4.408-4.23-.029-2.362 1.901-4.298 4.308-4.326h.1c2.407 0 4.358 1.915 4.365 4.278v6.305c0 2.342-1.944 4.25-4.323 4.279a4.375 4.375 0 01-3.033-1.252l-1.851 1.818A7 7 0 0012.029 22h.092c3.803-.056 6.858-3.083 6.879-6.816v-6.5C18.907 4.963 15.817 2 12.036 2z"></path></g>',mi='<g transform="translate(0,0) scale(4.1667)"><path d="M2.84 2a1.273 1.273 0 100 2.547h14.107a1.273 1.273 0 100-2.547H2.84zM7.935 5.33a1.273 1.273 0 000 2.548H22.04a1.274 1.274 0 000-2.547H7.935zM3.624 9.935c0-.704.57-1.274 1.274-1.274h14.106a1.274 1.274 0 010 2.547H4.898c-.703 0-1.274-.57-1.274-1.273zM1.273 12.188a1.273 1.273 0 100 2.547H15.38a1.274 1.274 0 000-2.547H1.273zM3.624 16.792c0-.704.57-1.274 1.274-1.274h14.106a1.273 1.273 0 110 2.547H4.898c-.703 0-1.274-.57-1.274-1.273zM13.029 18.849a1.273 1.273 0 100 2.547h9.698a1.273 1.273 0 100-2.547h-9.698z" fill-opacity=".3"></path><path d="M2.84 2a1.273 1.273 0 100 2.547h10.287a1.274 1.274 0 000-2.547H2.84zM7.935 5.33a1.273 1.273 0 000 2.548H18.22a1.274 1.274 0 000-2.547H7.935zM3.624 9.935c0-.704.57-1.274 1.274-1.274h10.286a1.273 1.273 0 010 2.547H4.898c-.703 0-1.274-.57-1.274-1.273zM1.273 12.188a1.273 1.273 0 100 2.547H11.56a1.274 1.274 0 000-2.547H1.273zM3.624 16.792c0-.704.57-1.274 1.274-1.274h10.286a1.273 1.273 0 110 2.547H4.898c-.703 0-1.274-.57-1.274-1.273zM13.029 18.849a1.273 1.273 0 100 2.547h5.78a1.273 1.273 0 100-2.547h-5.78z"></path></g>',pi='<g transform="translate(0,0) scale(4.1667)"><path d="M12 24A14.304 14.304 0 000 12 14.304 14.304 0 0012 0a14.305 14.305 0 0012 12 14.305 14.305 0 00-12 12"></path></g>',gi='<g transform="translate(0,0) scale(4.1667)"><path d="M7.905 1.09c.216.085.411.225.588.41.295.306.544.744.734 1.263.191.522.315 1.1.362 1.68a5.054 5.054 0 012.049-.636l.051-.004c.87-.07 1.73.087 2.48.474.101.053.2.11.297.17.05-.569.172-1.134.36-1.644.19-.52.439-.957.733-1.264a1.67 1.67 0 01.589-.41c.257-.1.53-.118.796-.042.401.114.745.368 1.016.737.248.337.434.769.561 1.287.23.934.27 2.163.115 3.645l.053.04.026.019c.757.576 1.284 1.397 1.563 2.35.435 1.487.216 3.155-.534 4.088l-.018.021.002.003c.417.762.67 1.567.724 2.4l.002.03c.064 1.065-.2 2.137-.814 3.19l-.007.01.01.024c.472 1.157.62 2.322.438 3.486l-.006.039a.651.651 0 01-.747.536.648.648 0 01-.54-.742c.167-1.033.01-2.069-.48-3.123a.643.643 0 01.04-.617l.004-.006c.604-.924.854-1.83.8-2.72-.046-.779-.325-1.544-.8-2.273a.644.644 0 01.18-.886l.009-.006c.243-.159.467-.565.58-1.12a4.229 4.229 0 00-.095-1.974c-.205-.7-.58-1.284-1.105-1.683-.595-.454-1.383-.673-2.38-.61a.653.653 0 01-.632-.371c-.314-.665-.772-1.141-1.343-1.436a3.288 3.288 0 00-1.772-.332c-1.245.099-2.343.801-2.67 1.686a.652.652 0 01-.61.425c-1.067.002-1.893.252-2.497.703-.522.39-.878.935-1.066 1.588a4.07 4.07 0 00-.068 1.886c.112.558.331 1.02.582 1.269l.008.007c.212.207.257.53.109.785-.36.622-.629 1.549-.673 2.44-.05 1.018.186 1.902.719 2.536l.016.019a.643.643 0 01.095.69c-.576 1.236-.753 2.252-.562 3.052a.652.652 0 01-1.269.298c-.243-1.018-.078-2.184.473-3.498l.014-.035-.008-.012a4.339 4.339 0 01-.598-1.309l-.005-.019a5.764 5.764 0 01-.177-1.785c.044-.91.278-1.842.622-2.59l.012-.026-.002-.002c-.293-.418-.51-.953-.63-1.545l-.005-.024a5.352 5.352 0 01.093-2.49c.262-.915.777-1.701 1.536-2.269.06-.045.123-.09.186-.132-.159-1.493-.119-2.73.112-3.67.127-.518.314-.95.562-1.287.27-.368.614-.622 1.015-.737.266-.076.54-.059.797.042zm4.116 9.09c.936 0 1.8.313 2.446.855.63.527 1.005 1.235 1.005 1.94 0 .888-.406 1.58-1.133 2.022-.62.375-1.451.557-2.403.557-1.009 0-1.871-.259-2.493-.734-.617-.47-.963-1.13-.963-1.845 0-.707.398-1.417 1.056-1.946.668-.537 1.55-.849 2.485-.849zm0 .896a3.07 3.07 0 00-1.916.65c-.461.37-.722.835-.722 1.25 0 .428.21.829.61 1.134.455.347 1.124.548 1.943.548.799 0 1.473-.147 1.932-.426.463-.28.7-.686.7-1.257 0-.423-.246-.89-.683-1.256-.484-.405-1.14-.643-1.864-.643zm.662 1.21l.004.004c.12.151.095.37-.056.49l-.292.23v.446a.375.375 0 01-.376.373.375.375 0 01-.376-.373v-.46l-.271-.218a.347.347 0 01-.052-.49.353.353 0 01.494-.051l.215.172.22-.174a.353.353 0 01.49.051zm-5.04-1.919c.478 0 .867.39.867.871a.87.87 0 01-.868.871.87.87 0 01-.867-.87.87.87 0 01.867-.872zm8.706 0c.48 0 .868.39.868.871a.87.87 0 01-.868.871.87.87 0 01-.867-.87.87.87 0 01.867-.872zM7.44 2.3l-.003.002a.659.659 0 00-.285.238l-.005.006c-.138.189-.258.467-.348.832-.17.692-.216 1.631-.124 2.782.43-.128.899-.208 1.404-.237l.01-.001.019-.034c.046-.082.095-.161.148-.239.123-.771.022-1.692-.253-2.444-.134-.364-.297-.65-.453-.813a.628.628 0 00-.107-.09L7.44 2.3zm9.174.04l-.002.001a.628.628 0 00-.107.09c-.156.163-.32.45-.453.814-.29.794-.387 1.776-.23 2.572l.058.097.008.014h.03a5.184 5.184 0 011.466.212c.086-1.124.038-2.043-.128-2.722-.09-.365-.21-.643-.349-.832l-.004-.006a.659.659 0 00-.285-.239h-.004z"></path></g>',yi='<g transform="translate(0,0) scale(4.1667)"><path d="M17.7 12C17.7 7.03 13.74 3 8.85 3C3.96 3 0 7.03 0 12C0 16.97 3.96 21 8.85 21C13.73 21 17.7 16.97 17.7 12ZM14.06 12C14.06 14.93 11.73 17.3 8.85 17.3C5.97 17.3 3.64 14.93 3.64 12C3.64 9.07 5.97 6.7 8.85 6.7C11.73 6.7 14.06 9.07 14.06 12ZM24 3H20.61V21H24V3Z"/></g>',bi='<g transform="translate(0,0) scale(4.1667)"><path d="M19.04 4.818a10.171 10.171 0 014.21 8.25c0 5.623-4.55 10.182-10.163 10.182a10.142 10.142 0 01-8.129-4.07 10.102 10.102 0 005.956 1.934c5.613 0 10.163-4.56 10.163-10.182 0-2.295-.759-4.411-2.037-6.114z" fill-opacity=".5"></path><path d="M10.887 5.2c1.156 0 2.097.944 2.097 2.1 0 .354-.09.7-.258 1.006a.591.591 0 00.233.797c.215.117.47.084.647-.062.375-.232.811-.338 1.251-.305a2.098 2.098 0 011.931 2.248 2.097 2.097 0 01-2.244 1.939 2.082 2.082 0 01-1.246-.533c-.019-.024-.036-.047-.056-.07a.617.617 0 00-.111-.102 2.113 2.113 0 01-.137-.173.58.58 0 10-.947.675c.118.167.247.323.39.462.22.291.36.637.405 1.005a2.08 2.08 0 01-.425 1.546 2.088 2.088 0 01-1.398.792 2.094 2.094 0 01-2.335-1.827 2.083 2.083 0 01.263-1.304v.005a3.273 3.273 0 001.216-2.546c0-.92-.383-1.745-.993-2.34l-.03-.055A2.101 2.101 0 0110.887 5.2z"></path><path d="M6.901 8.752a2.1 2.1 0 010 4.201 2.097 2.097 0 01-2.091-2.1c0-1.159.937-2.101 2.091-2.101z"></path><path clip-rule="evenodd" d="M10.914.75c5.613 0 10.163 4.559 10.163 10.182s-4.55 10.182-10.163 10.182S.75 16.555.75 10.932C.75 5.308 5.301.75 10.914.75zm-.021 3.283A3.27 3.27 0 007.65 7.671a3.27 3.27 0 00-4.006 3.182c0 1.8 1.464 3.262 3.262 3.262.211 0 .417-.016.618-.055-.03.258-.028.516.005.78a3.25 3.25 0 001.23 2.178 3.234 3.234 0 002.407.665 3.236 3.236 0 002.173-1.234c.535-.689.77-1.545.663-2.41 0-.006-.005-.013-.005-.02.151.033.309.055.466.066a3.228 3.228 0 002.365-.781 3.27 3.27 0 00-1.884-5.734 3.31 3.31 0 00-.81.04 3.266 3.266 0 00-3.241-3.577z"></path></g>';var zr=class extends le.Plugin{async onload(){await this.loadSettings(),(0,le.addIcon)("ai-providers-openai",ui),(0,le.addIcon)("ai-providers-ollama",gi),(0,le.addIcon)("ai-providers-ollama-openwebui",yi),(0,le.addIcon)("ai-providers-gemini",pi),(0,le.addIcon)("ai-providers-openrouter",hi),(0,le.addIcon)("ai-providers-lmstudio",mi),(0,le.addIcon)("ai-providers-groq",fi),(0,le.addIcon)("ai-providers-ai302",bi);let t=new pr(this.app,this);this.exposeAIProviders(),this.app.workspace.onLayoutReady(async()=>{await this.aiProviders.initEmbeddingsCache()}),this.app.workspace.trigger("ai-providers-ready"),this.addSettingTab(t)}async onunload(){this.aiProviders&&await this.aiProviders.cleanup(),delete this.app.aiProviders}async loadSettings(){var t;this.settings=Object.assign({},es,await this.loadData()),p.setEnabled((t=this.settings.debugLogging)!=null?t:!1)}async saveSettings(){await this.saveData(this.settings),this.exposeAIProviders()}exposeAIProviders(){this.aiProviders&&this.aiProviders.cleanup().catch(t=>{console.error("Error during aiProviders cleanup:",t)}),this.aiProviders=new Vr(this.app,this),this.app.aiProviders=this.aiProviders,this.app.workspace.layoutReady&&this.aiProviders.initEmbeddingsCache().catch(t=>{console.error("Error reinitializing embeddings cache:",t)})}};
/* nosourcemap */