心平气和 f2c17a64ce 增加 .gitignore 文件忽视 .trash/ 和 attachments/
增加 .obsidian 配置文件
增加第三方插件:ai-providers、dataview、local-gpt、templater-obsidian
2025-12-27 19:31:30 +08:00

85 lines
242 KiB
JavaScript

/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
var $c=Object.create;var Ws=Object.defineProperty;var Lc=Object.getOwnPropertyDescriptor;var Uc=Object.getOwnPropertyNames;var jc=Object.getPrototypeOf,qc=Object.prototype.hasOwnProperty;var Hc=(s,e)=>{for(var t in e)Ws(s,t,{get:e[t],enumerable:!0})},ko=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Uc(e))!qc.call(s,n)&&n!==t&&Ws(s,n,{get:()=>e[n],enumerable:!(r=Lc(e,n))||r.enumerable});return s};var Wc=(s,e,t)=>(t=s!=null?$c(jc(s)):{},ko(e||!s||!s.__esModule?Ws(t,"default",{value:s,enumerable:!0}):t,s)),Vc=s=>ko(Ws({},"__esModule",{value:!0}),s);var Ad={};Hc(Ad,{default:()=>ti});module.exports=Vc(Ad);var Ie=require("obsidian");var ue=require("obsidian");var Mo={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 To={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 Oo={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 Fo={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 ri=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(),n=`[AI Providers ${e.toUpperCase()}] ${r}:`;switch(e){case"debug":console.log(n,...t);break;case"info":console.info(n,...t);break;case"warn":console.warn(n,...t);break;case"error":console.error(n,...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}`)}},b=new ri;var si={en:To,ru:Oo,de:Mo,zh:Fo},I=class{static t(e,t){let r=window.localStorage.getItem("language")||"en",n=e.split("."),i=si[r]||si.en;for(let a of n){if((i==null?void 0:i[a])===void 0){b.warn(`Translation missing: ${e}`),i=si.en;let c=i;for(let l of n)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 Vs=require("obsidian");var tr=class extends Vs.Modal{constructor(t,r,n,i=()=>{}){super(t);this.message=r;this.onConfirm=n,this.onCancel=i}onOpen(){let{contentEl:t}=this;t.createEl("p",{text:this.message}),new Vs.Setting(t).addButton(r=>r.setButtonText(I.t("modals.confirm")).setWarning().onClick(()=>{this.onConfirm(),this.close()})).addButton(r=>r.setButtonText(I.t("modals.cancel")).onClick(()=>{this.onCancel(),this.close()}))}onClose(){let{contentEl:t}=this;t.empty()}};var le=require("obsidian");var rr={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}},anthropic:{url:"https://api.anthropic.com",name:"Anthropic"}},zs=class extends le.Modal{constructor(t,r,n,i,o=!1){super(t);this.plugin=r;this.provider=n;this.onSave=i;this.isAddingNew=o;this.nameModified=!1;this.urlModified=!1;this.isTextMode=!1;this.isLoadingModels=!1}hasModelFetching(t){var n;return((n=rr[t].options)==null?void 0:n.modelsFetching)!==!1}getModelDescription(t,r){return r?I.t("settings.modelTextOnlyDesc"):t?I.t("settings.modelTextDesc"):I.t("settings.modelDesc")}getDefaultName(t){return rr[t].name}initDefaults(){this.nameModified=!1,this.urlModified=!1,this.provider.url||(this.provider.url=rr[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),n=this.isTextMode||r,i=new le.Setting(t).setName(I.t("settings.model")).setDesc(this.getModelDescription(n,r));return n?this.createTextInput(i):(this.createDropdown(i),this.createRefresh(i)),this.setupDescription(i,n,r),i}createTextInput(t){t.addText(r=>(r.setValue(this.provider.model||"").onChange(n=>{this.provider.model=n}),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",I.t("settings.loadingModels")),t.setDisabled(!0);return}let r=this.provider.availableModels;if(!r||r.length===0){t.addOption("none",I.t("settings.noModelsAvailable")),t.setDisabled(!0);return}r.forEach(n=>{t.addOption(n,n);let i=t.selectEl.options,o=i[i.length-1];o.title=n}),t.setDisabled(!1)}setupDropdown(t){var r;t.setValue(this.provider.model||"").onChange(n=>{this.provider.model=n,t.selectEl.title=n}),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(I.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 le.Notice(I.t("settings.modelsUpdated"))}catch(t){b.error("Failed to fetch models:",t),new le.Notice(I.t("errors.failedToFetchModels"))}finally{this.isLoadingModels=!1,this.display()}}setupDescription(t,r,n){let i=t.descEl;if(i.empty(),i.appendChild((0,le.sanitizeHTMLToDom)(this.getModelDescription(r,n))),!n){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?I.t("settings.addNewProvider"):I.t("settings.editProvider")}).setAttribute("data-testid","provider-form-title"),new le.Setting(t).setName(I.t("settings.providerType")).setDesc(I.t("settings.providerTypeDesc")).addDropdown(r=>{let n=Object.entries(rr).reduce((i,[o,a])=>(i[o]=a.name,i),{});return r.addOptions(n).setValue(this.provider.type).onChange(i=>{this.changeProviderType(i)}),r.selectEl.setAttribute("data-testid","provider-type-dropdown"),r}),new le.Setting(t).setName(I.t("settings.providerName")).setDesc(I.t("settings.providerNameDesc")).addText(r=>(r.setPlaceholder(I.t("settings.providerNamePlaceholder")).setValue(this.provider.name).onChange(n=>{this.provider.name=n,this.nameModified=!0}),r.inputEl.setAttribute("data-field","provider-name"),r)),new le.Setting(t).setName(I.t("settings.providerUrl")).setDesc(I.t("settings.providerUrlDesc")).addText(r=>(r.setPlaceholder(I.t("settings.providerUrlPlaceholder")).setValue(this.provider.url||"").onChange(n=>{this.provider.url=n,this.urlModified=!0}),r.inputEl.setAttribute("data-field","provider-url"),r)),new le.Setting(t).setName(I.t("settings.apiKey")).setDesc(I.t("settings.apiKeyDesc")).addText(r=>r.setPlaceholder(I.t("settings.apiKeyPlaceholder")).setValue(this.provider.apiKey||"").onChange(n=>{this.provider.apiKey=n})),this.createModelSetting(t),new le.Setting(t).addButton(r=>r.setButtonText(I.t("settings.save")).setCta().onClick(async()=>{this.provider.name=this.provider.name.trim(),await this.onSave(this.provider)})).addButton(r=>(r.setButtonText(I.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),n=rr[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===n)&&(this.provider.url=rr[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 No={_version:1,debugLogging:!1,useNativeFetch:!1},Ks=class extends ue.PluginSettingTab{constructor(t,r){super(t,r);this.isFormOpen=!1;this.isDeveloperMode=!1;this.plugin=r}openForm(t,r){let n=r||{id:`id-${Date.now().toString()}`,name:"",apiKey:"",url:"",type:"openai",model:""};this.currentModal=new zs(this.app,this.plugin,n,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:I.t("errors.providerNameRequired")}:(this.plugin.settings.providers||[]).find(i=>i.name.trim()===t.name.trim()&&i.id!==t.id)?{isValid:!1,error:I.t("errors.providerNameExists",{name:t.name})}:{isValid:!0}}async saveProvider(t){let r=this.validateProvider(t);if(!r.isValid){new ue.Notice(r.error);return}let n=this.plugin.settings.providers||[],i=n.findIndex(o=>o.id===t.id);i!==-1?n[i]=t:n.push(t),this.plugin.settings.providers=n,await this.plugin.saveSettings(),this.closeForm()}async deleteProvider(t){let r=this.plugin.settings.providers||[],n=r.findIndex(i=>i.id===t.id);n!==-1&&(r.splice(n,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} (${I.t("settings.duplicate")})`},n=this.plugin.settings.providers||[];n.push(r),this.plugin.settings.providers=n,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,ue.sanitizeHTMLToDom)(`${I.t("settings.notice")}`)),new ue.Setting(r).setHeading().setName(I.t("settings.configuredProviders")).addButton(a=>{let c=a.setIcon("plus").setTooltip(I.t("settings.addProvider")).onClick(()=>{this.isFormOpen||this.openForm(!0)});return c.buttonEl.setAttribute("aria-label",I.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 ue.Setting(r).setName(a.name).setDesc(a.url||""),l=c.nameEl.createSpan("ai-providers-provider-icon");if((0,ue.setIcon)(l,`ai-providers-${a.type}`),c.nameEl.prepend(l),a.model){let u=c.settingEl.createDiv("ai-providers-model-pill");u.textContent=a.model,u.setAttribute("data-testid","model-pill"),c.nameEl.after(u)}c.addExtraButton(u=>{u.setIcon("gear").setTooltip(I.t("settings.options")).onClick(()=>{this.isFormOpen||this.openForm(!1,{...a})}),u.extraSettingsEl.setAttribute("data-testid","edit-provider")}).addExtraButton(u=>{u.setIcon("copy").setTooltip(I.t("settings.duplicate")).onClick(async()=>{await this.duplicateProvider(a)}),u.extraSettingsEl.setAttribute("data-testid","duplicate-provider")}).addExtraButton(u=>{u.setIcon("lucide-trash-2").setTooltip(I.t("settings.delete")).onClick(async()=>{new tr(this.app,I.t("settings.deleteConfirmation",{name:a.name}),async()=>{await this.deleteProvider(a)}).open()}),u.extraSettingsEl.setAttribute("data-testid","delete-provider")})}),new ue.Setting(r).setHeading().setName(I.t("settings.developerSettings")).setDesc(I.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 ue.Setting(a).setName(I.t("settings.debugLogging")).setDesc(I.t("settings.debugLoggingDesc")).addToggle(c=>{var l;return c.setValue((l=this.plugin.settings.debugLogging)!=null?l:!1).onChange(async u=>{this.plugin.settings.debugLogging=u,b.setEnabled(u),await this.plugin.saveSettings()})}),new ue.Setting(a).setName(I.t("settings.useNativeFetch")).setDesc(I.t("settings.useNativeFetchDesc")).addToggle(c=>{var l;return c.setValue((l=this.plugin.settings.useNativeFetch)!=null?l:!1).onChange(async u=>{this.plugin.settings.useNativeFetch=u,await this.plugin.saveSettings()})})}}};var Zn=require("obsidian");var Js="RFC3986",Xs={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:s=>String(s)},Bo="RFC1738";var Gc=Array.isArray,ke=(()=>{let s=[];for(let e=0;e<256;++e)s.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return s})();var ni=1024,Do=(s,e,t,r,n)=>{if(s.length===0)return s;let i=s;if(typeof s=="symbol"?i=Symbol.prototype.toString.call(s):typeof s!="string"&&(i=String(s)),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+=ni){let c=i.length>=ni?i.slice(a,a+ni):i,l=[];for(let u=0;u<c.length;++u){let h=c.charCodeAt(u);if(h===45||h===46||h===95||h===126||h>=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||n===Bo&&(h===40||h===41)){l[l.length]=c.charAt(u);continue}if(h<128){l[l.length]=ke[h];continue}if(h<2048){l[l.length]=ke[192|h>>6]+ke[128|h&63];continue}if(h<55296||h>=57344){l[l.length]=ke[224|h>>12]+ke[128|h>>6&63]+ke[128|h&63];continue}u+=1,h=65536+((h&1023)<<10|c.charCodeAt(u)&1023),l[l.length]=ke[240|h>>18]+ke[128|h>>12&63]+ke[128|h>>6&63]+ke[128|h&63]}o+=l.join("")}return o};function $o(s){return!s||typeof s!="object"?!1:!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function ii(s,e){if(Gc(s)){let t=[];for(let r=0;r<s.length;r+=1)t.push(e(s[r]));return t}return e(s)}var Qc=Object.prototype.hasOwnProperty,Lo={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,e){return String(s)+"["+e+"]"},repeat(s){return String(s)}},Me=Array.isArray,Yc=Array.prototype.push,Uo=function(s,e){Yc.apply(s,Me(e)?e:[e])},Zc=Date.prototype.toISOString,J={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Do,encodeValuesOnly:!1,format:Js,formatter:Xs[Js],indices:!1,serializeDate(s){return Zc.call(s)},skipNulls:!1,strictNullHandling:!1};function el(s){return typeof s=="string"||typeof s=="number"||typeof s=="boolean"||typeof s=="symbol"||typeof s=="bigint"}var oi={};function jo(s,e,t,r,n,i,o,a,c,l,u,h,m,f,p,y,g,C){let _=s,O=C,M=0,v=!1;for(;(O=O.get(oi))!==void 0&&!v;){let k=O.get(s);if(M+=1,typeof k!="undefined"){if(k===M)throw new RangeError("Cyclic object value");v=!0}typeof O.get(oi)=="undefined"&&(M=0)}if(typeof l=="function"?_=l(e,_):_ instanceof Date?_=m==null?void 0:m(_):t==="comma"&&Me(_)&&(_=ii(_,function(k){return k instanceof Date?m==null?void 0:m(k):k})),_===null){if(i)return c&&!y?c(e,J.encoder,g,"key",f):e;_=""}if(el(_)||$o(_)){if(c){let k=y?e:c(e,J.encoder,g,"key",f);return[(p==null?void 0:p(k))+"="+(p==null?void 0:p(c(_,J.encoder,g,"value",f)))]}return[(p==null?void 0:p(e))+"="+(p==null?void 0:p(String(_)))]}let B=[];if(typeof _=="undefined")return B;let N;if(t==="comma"&&Me(_))y&&c&&(_=ii(_,c)),N=[{value:_.length>0?_.join(",")||null:void 0}];else if(Me(l))N=l;else{let k=Object.keys(_);N=u?k.sort(u):k}let F=a?String(e).replace(/\./g,"%2E"):String(e),T=r&&Me(_)&&_.length===1?F+"[]":F;if(n&&Me(_)&&_.length===0)return T+"[]";for(let k=0;k<N.length;++k){let L=N[k],D=typeof L=="object"&&typeof L.value!="undefined"?L.value:_[L];if(o&&D===null)continue;let we=h&&a?L.replace(/\./g,"%2E"):L,je=Me(_)?typeof t=="function"?t(T,we):T:T+(h?"."+we:"["+we+"]");C.set(s,M);let fe=new WeakMap;fe.set(oi,C),Uo(B,jo(D,je,t,r,n,i,o,a,t==="comma"&&y&&Me(_)?null:c,l,u,h,m,f,p,y,g,fe))}return B}function tl(s=J){if(typeof s.allowEmptyArrays!="undefined"&&typeof s.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof s.encodeDotInKeys!="undefined"&&typeof s.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(s.encoder!==null&&typeof s.encoder!="undefined"&&typeof s.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=s.charset||J.charset;if(typeof s.charset!="undefined"&&s.charset!=="utf-8"&&s.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=Js;if(typeof s.format!="undefined"){if(!Qc.call(Xs,s.format))throw new TypeError("Unknown format option provided.");t=s.format}let r=Xs[t],n=J.filter;(typeof s.filter=="function"||Me(s.filter))&&(n=s.filter);let i;if(s.arrayFormat&&s.arrayFormat in Lo?i=s.arrayFormat:"indices"in s?i=s.indices?"indices":"repeat":i=J.arrayFormat,"commaRoundTrip"in s&&typeof s.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let o=typeof s.allowDots=="undefined"?s.encodeDotInKeys?!0:J.allowDots:!!s.allowDots;return{addQueryPrefix:typeof s.addQueryPrefix=="boolean"?s.addQueryPrefix:J.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof s.allowEmptyArrays=="boolean"?!!s.allowEmptyArrays:J.allowEmptyArrays,arrayFormat:i,charset:e,charsetSentinel:typeof s.charsetSentinel=="boolean"?s.charsetSentinel:J.charsetSentinel,commaRoundTrip:!!s.commaRoundTrip,delimiter:typeof s.delimiter=="undefined"?J.delimiter:s.delimiter,encode:typeof s.encode=="boolean"?s.encode:J.encode,encodeDotInKeys:typeof s.encodeDotInKeys=="boolean"?s.encodeDotInKeys:J.encodeDotInKeys,encoder:typeof s.encoder=="function"?s.encoder:J.encoder,encodeValuesOnly:typeof s.encodeValuesOnly=="boolean"?s.encodeValuesOnly:J.encodeValuesOnly,filter:n,format:t,formatter:r,serializeDate:typeof s.serializeDate=="function"?s.serializeDate:J.serializeDate,skipNulls:typeof s.skipNulls=="boolean"?s.skipNulls:J.skipNulls,sort:typeof s.sort=="function"?s.sort:null,strictNullHandling:typeof s.strictNullHandling=="boolean"?s.strictNullHandling:J.strictNullHandling}}function ai(s,e={}){let t=s,r=tl(e),n,i;typeof r.filter=="function"?(i=r.filter,t=i("",t)):Me(r.filter)&&(i=r.filter,n=i);let o=[];if(typeof t!="object"||t===null)return"";let a=Lo[r.arrayFormat],c=a==="comma"&&r.commaRoundTrip;n||(n=Object.keys(t)),r.sort&&n.sort(r.sort);let l=new WeakMap;for(let m=0;m<n.length;++m){let f=n[m];r.skipNulls&&t[f]===null||Uo(o,jo(t[f],f,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 u=o.join(r.delimiter),h=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?h+="utf8=%26%2310003%3B&":h+="utf8=%E2%9C%93&"),u.length>0?h+u:""}var It="4.73.1";var qo=!1,Et,ci,sl,nl,il,li,ol,Gs,ui,di,hi,Qs,fi;function Ho(s,e={auto:!1}){if(qo)throw new Error(`you must \`import 'openai/shims/${s.kind}'\` before importing anything else from openai`);if(Et)throw new Error(`can't \`import 'openai/shims/${s.kind}'\` after \`import 'openai/shims/${Et}'\``);qo=e.auto,Et=s.kind,ci=s.fetch,sl=s.Request,nl=s.Response,il=s.Headers,li=s.FormData,ol=s.Blob,Gs=s.File,ui=s.ReadableStream,di=s.getMultipartRequestOptions,hi=s.getDefaultAgent,Qs=s.fileFromPath,fi=s.isFsReadStream}var Ys=class{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}};function Wo({manuallyImported:s}={}){let e=s?"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,n,i;try{t=fetch,r=Request,n=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:n,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 Ys(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}}Et||Ho(Wo(),{auto:!0});var E=class extends Error{},z=class extends E{constructor(e,t,r,n){super(`${z.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.request_id=n==null?void 0:n["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 n=t!=null&&t.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e)return new rt({message:r,cause:Zs(t)});let i=t==null?void 0:t.error;return e===400?new Qr(e,i,r,n):e===401?new Yr(e,i,r,n):e===403?new Zr(e,i,r,n):e===404?new es(e,i,r,n):e===409?new ts(e,i,r,n):e===422?new rs(e,i,r,n):e===429?new ss(e,i,r,n):e>=500?new ns(e,i,r,n):new z(e,i,r,n)}},Y=class extends z{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0),this.status=void 0}},rt=class extends z{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),this.status=void 0,t&&(this.cause=t)}},st=class extends rt{constructor({message:e}={}){super({message:e!=null?e:"Request timed out."})}},Qr=class extends z{constructor(){super(...arguments),this.status=400}},Yr=class extends z{constructor(){super(...arguments),this.status=401}},Zr=class extends z{constructor(){super(...arguments),this.status=403}},es=class extends z{constructor(){super(...arguments),this.status=404}},ts=class extends z{constructor(){super(...arguments),this.status=409}},rs=class extends z{constructor(){super(...arguments),this.status=422}},ss=class extends z{constructor(){super(...arguments),this.status=429}},ns=class extends z{},sr=class extends E{constructor(){super("Could not parse response content as the length limit was reached")}},nr=class extends E{constructor(){super("Could not parse response content as the request was rejected by the content filter")}};var Te=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=Te.NEWLINE_CHARS.has(t[t.length-1]||""),n=t.split(Te.NEWLINE_REGEXP);return r&&n.pop(),n.length===1&&!r?(this.buffer.push(n[0]),[]):(this.buffer.length>0&&(n=[this.buffer.join("")+n[0],...n.slice(1)],this.buffer=[]),r||(this.buffer=[n.pop()||""]),n)}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 E(`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 E(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new E("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}};Te.NEWLINE_CHARS=new Set([`
`,"\r"]);Te.NEWLINE_REGEXP=/\r\n|[\n\r]/g;var ie=class{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let r=!1;async function*n(){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 ll(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 z(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 z(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 ie(n,t)}static fromReadableStream(e,t){let r=!1;async function*n(){let o=new Te,a=Vo(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 n())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 ie(i,t)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),n=i=>({next:()=>{if(i.length===0){let o=r.next();e.push(o),t.push(o)}return i.shift()}});return[new ie(()=>n(e),this.controller),new ie(()=>n(t),this.controller)]}toReadableStream(){let e=this,t,r=new TextEncoder;return new ui({async start(){t=e[Symbol.asyncIterator]()},async pull(n){try{let{value:i,done:o}=await t.next();if(o)return n.close();let a=r.encode(JSON.stringify(i)+`
`);n.enqueue(a)}catch(i){n.error(i)}},async cancel(){var n;await((n=t.return)==null?void 0:n.call(t))}})}};async function*ll(s,e){if(!s.body)throw e.abort(),new E("Attempted to iterate over a response with no body");let t=new mi,r=new Te,n=Vo(s.body);for await(let i of ul(n))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*ul(s){let e=new Uint8Array;for await(let t of s){if(t==null)continue;let r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?new TextEncoder().encode(t):t,n=new Uint8Array(e.length+r.length);n.set(e),n.set(r,e.length),e=n;let i;for(;(i=dl(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function dl(s){for(let r=0;r<s.length-2;r++){if(s[r]===10&&s[r+1]===10||s[r]===13&&s[r+1]===13)return r+2;if(s[r]===13&&s[r+1]===10&&r+3<s.length&&s[r+2]===13&&s[r+3]===10)return r+4}return-1}var mi=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,n]=hl(e,":");return n.startsWith(" ")&&(n=n.substring(1)),t==="event"?this.event=n:t==="data"&&this.data.push(n),null}};function hl(s,e){let t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}function Vo(s){if(s[Symbol.asyncIterator])return s;let e=s.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 zo=s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function",Ko=s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&is(s),is=s=>s!=null&&typeof s=="object"&&typeof s.size=="number"&&typeof s.type=="string"&&typeof s.text=="function"&&typeof s.slice=="function"&&typeof s.arrayBuffer=="function",fl=s=>Ko(s)||zo(s)||fi(s);async function yi(s,e,t){var n,i,o;if(s=await s,Ko(s))return s;if(zo(s)){let a=await s.blob();e||(e=(n=new URL(s.url).pathname.split(/[\\/]/).pop())!=null?n:"unknown_file");let c=is(a)?[await a.arrayBuffer()]:[a];return new Gs(c,e,t)}let r=await ml(s);if(e||(e=(i=gl(s))!=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 Gs(r,e,t)}async function ml(s){var t;let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(is(s))e.push(await s.arrayBuffer());else if(yl(s))for await(let r of s)e.push(r);else throw new Error(`Unexpected data type: ${typeof s}; constructor: ${(t=s==null?void 0:s.constructor)==null?void 0:t.name}; props: ${pl(s)}`);return e}function pl(s){return`[${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}function gl(s){var e;return pi(s.name)||pi(s.filename)||((e=pi(s.path))==null?void 0:e.split(/[\\/]/).pop())}var pi=s=>{if(typeof s=="string")return s;if(typeof Buffer!="undefined"&&s instanceof Buffer)return String(s)},yl=s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function",bi=s=>s&&typeof s=="object"&&s.body&&s[Symbol.toStringTag]==="MultipartBody";var _e=async s=>{let e=await Jo(s.body);return di(e,s)},Jo=async s=>{let e=new li;return await Promise.all(Object.entries(s||{}).map(([t,r])=>gi(e,t,r))),e};var gi=async(s,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")s.append(e,String(t));else if(fl(t)){let r=await yi(t);s.append(e,r)}else if(Array.isArray(t))await Promise.all(t.map(r=>gi(s,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,n])=>gi(s,`${e}[${r}]`,n)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var wl=function(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t},_l=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},en;async function Zo(s){let{response:e}=s;if(s.options.stream)return ir("response",e.status,e.url,e.headers,e.body),s.options.__streamClass?s.options.__streamClass.fromSSEResponse(e,s.controller):ie.fromSSEResponse(e,s.controller);if(e.status===204)return null;if(s.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 ir("response",e.status,e.url,e.headers,i),ea(i,e)}let n=await e.text();return ir("response",e.status,e.url,e.headers,n),n}function ea(s,e){return!s||typeof s!="object"||Array.isArray(s)?s:Object.defineProperty(s,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var or=class extends Promise{constructor(e,t=Zo){super(r=>{r(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new or(this.responsePromise,async t=>ea(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)}},rn=class{constructor({baseURL:e,maxRetries:t=2,timeout:r=6e5,httpAgent:n,fetch:i}){this.baseURL=e,this.maxRetries=wi("maxRetries",t),this.timeout=wi("timeout",r),this.httpAgent=n,this.fetch=i!=null?i:ci}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...Il(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${Cl()}`}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 n=>{let i=n&&is(n==null?void 0:n.body)?new DataView(await n.body.arrayBuffer()):(n==null?void 0:n.body)instanceof DataView?n.body:(n==null?void 0:n.body)instanceof ArrayBuffer?new DataView(n.body):n&&ArrayBuffer.isView(n==null?void 0:n.body)?new DataView(n.body.buffer):n==null?void 0:n.body;return{method:e,path:t,...n,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 y,g,C,_,O,M;let{method:r,path:n,query:i,headers:o={}}=e,a=ArrayBuffer.isView(e.body)||e.__binaryRequest&&typeof e.body=="string"?e.body:bi(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,c=this.calculateContentLength(a),l=this.buildURL(n,i);"timeout"in e&&wi("timeout",e.timeout);let u=(y=e.timeout)!=null?y:this.timeout,h=(C=(g=e.httpAgent)!=null?g:this.httpAgent)!=null?C:hi(l),m=u+1e3;typeof((_=h==null?void 0:h.options)==null?void 0:_.timeout)=="number"&&m>((O=h.options.timeout)!=null?O:0)&&(h.options.timeout=m),this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let f=this.buildHeaders({options:e,headers:o,contentLength:c,retryCount:t});return{req:{method:r,...a&&{body:a},headers:f,...h&&{agent:h},signal:(M=e.signal)!=null?M:null},url:l,timeout:u}}buildHeaders({options:e,headers:t,contentLength:r,retryCount:n}){let i={};r&&(i["content-length"]=r);let o=this.defaultHeaders(e);return Qo(i,o),Qo(i,t),bi(e.body)&&Et!=="node"&&delete i["content-type"],Yo(o,"x-stainless-retry-count")===void 0&&Yo(t,"x-stainless-retry-count")===void 0&&(i["x-stainless-retry-count"]=String(n)),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,n){return z.generate(e,t,r,n)}request(e,t=null){return new or(this.makeRequest(e,t))}async makeRequest(e,t){var h,m,f;let r=await e,n=(h=r.maxRetries)!=null?h:this.maxRetries;t==null&&(t=n),await this.prepareOptions(r);let{req:i,url:o,timeout:a}=this.buildRequest(r,{retryCount:n-t});if(await this.prepareRequest(i,{url:o,options:r}),ir("request",o,r,i.headers),(m=r.signal)!=null&&m.aborted)throw new Y;let c=new AbortController,l=await this.fetchWithTimeout(o,i,a,c).catch(Zs);if(l instanceof Error){if((f=r.signal)!=null&&f.aborted)throw new Y;if(t)return this.retryRequest(r,t);throw l.name==="AbortError"?new st:new rt({cause:l})}let u=xl(l.headers);if(!l.ok){if(t&&this.shouldRetry(l)){let O=`retrying, ${t} attempts remaining`;return ir(`response (error; ${O})`,l.status,o,u),this.retryRequest(r,t,u)}let p=await l.text().catch(O=>Zs(O).message),y=El(p),g=y?void 0:p;throw ir(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,l.status,o,u,g),this.makeStatusError(l.status,y,g,u)}return{response:l,options:r,controller:c}}requestAPIList(e,t){let r=this.makeRequest(t,null);return new _i(this,r,e)}buildURL(e,t){let r=Rl(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),n=this.defaultQuery();return ta(n)||(t={...n,...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 E(`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,n){let{signal:i,...o}=t||{};i&&i.addEventListener("abort",()=>n.abort());let a=setTimeout(()=>n.abort(),r);return this.getRequestClient().fetch.call(void 0,e,{signal:n.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 n,i=r==null?void 0:r["retry-after-ms"];if(i){let c=parseFloat(i);Number.isNaN(c)||(n=c)}let o=r==null?void 0:r["retry-after"];if(o&&!n){let c=parseFloat(o);Number.isNaN(c)?n=Date.parse(o)-Date.now():n=c*1e3}if(!(n&&0<=n&&n<60*1e3)){let c=(a=e.maxRetries)!=null?a:this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,c)}return await qe(n),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 ${It}`}},os=class{constructor(e,t,r,n){en.set(this,void 0),wl(this,en,e,"f"),this.options=n,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 E("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[n,i]of r)e.url.searchParams.set(n,i);t.query=void 0,t.path=e.url.toString()}return await _l(this,en,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(en=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},_i=class extends or{constructor(e,t,r){super(t,async n=>new r(e,n.response,await Zo(n),n.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},xl=s=>new Proxy(Object.fromEntries(s.entries()),{get(e,t){let r=t.toString();return e[r.toLowerCase()]||e[r]}}),Pl={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},U=s=>typeof s=="object"&&s!==null&&!ta(s)&&Object.keys(s).every(e=>ra(Pl,e)),Al=()=>{var e,t;if(typeof Deno!="undefined"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":It,"X-Stainless-OS":Go(Deno.build.os),"X-Stainless-Arch":Xo(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":It,"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":It,"X-Stainless-OS":Go(process.platform),"X-Stainless-Arch":Xo(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let s=vl();return s?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":It,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${s.browser}`,"X-Stainless-Runtime-Version":s.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":It,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function vl(){if(typeof navigator=="undefined"||!navigator)return null;let s=[{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 s){let r=t.exec(navigator.userAgent);if(r){let n=r[1]||0,i=r[2]||0,o=r[3]||0;return{browser:e,version:`${n}.${i}.${o}`}}}return null}var Xo=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",Go=s=>(s=s.toLowerCase(),s.includes("ios")?"iOS":s==="android"?"Android":s==="darwin"?"MacOS":s==="win32"?"Windows":s==="freebsd"?"FreeBSD":s==="openbsd"?"OpenBSD":s==="linux"?"Linux":s?`Other:${s}`:"Unknown"),tn,Il=()=>tn!=null?tn:tn=Al(),El=s=>{try{return JSON.parse(s)}catch(e){return}},Sl=new RegExp("^(?:[a-z]+:)?//","i"),Rl=s=>Sl.test(s),qe=s=>new Promise(e=>setTimeout(e,s)),wi=(s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new E(`${s} must be an integer`);if(e<0)throw new E(`${s} must be a positive integer`);return e},Zs=s=>{if(s instanceof Error)return s;if(typeof s=="object"&&s!==null)try{return new Error(JSON.stringify(s))}catch(e){}return new Error(s)};var as=s=>{var e,t,r,n,i,o;if(typeof process!="undefined")return(r=(t=(e=process.env)==null?void 0:e[s])==null?void 0:t.trim())!=null?r:void 0;if(typeof Deno!="undefined")return(o=(i=(n=Deno.env)==null?void 0:n.get)==null?void 0:i.call(n,s))==null?void 0:o.trim()};function ta(s){if(!s)return!0;for(let e in s)return!1;return!0}function ra(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function Qo(s,e){for(let t in e){if(!ra(e,t))continue;let r=t.toLowerCase();if(!r)continue;let n=e[t];n===null?delete s[r]:n!==void 0&&(s[r]=n)}}function ir(s,...e){var t;typeof process!="undefined"&&((t=process==null?void 0:process.env)==null?void 0:t.DEBUG)==="true"&&console.log(`OpenAI:DEBUG:${s}`,...e)}var Cl=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{let e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)}),sa=()=>typeof window!="undefined"&&typeof window.document!="undefined"&&typeof navigator!="undefined",kl=s=>typeof(s==null?void 0:s.get)=="function";var Yo=(s,e)=>{var r;let t=e.toLowerCase();if(kl(s)){let n=((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(),n]){let o=s.get(i);if(o)return o}}for(let[n,i]of Object.entries(s))if(n.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 cs(s){return s!=null&&typeof s=="object"&&!Array.isArray(s)}var sn=class extends os{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.object=r.object}getPaginatedItems(){var e;return(e=this.data)!=null?e:[]}nextPageParams(){return null}nextPageInfo(){return null}},H=class extends os{constructor(e,t,r,n){super(e,t,r,n),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 x=class{constructor(e){this._client=e}};var ar=class extends x{create(e,t){var r;return this._client.post("/chat/completions",{body:e,...t,stream:(r=e.stream)!=null?r:!1})}};var nt=class extends x{constructor(){super(...arguments),this.completions=new ar(this._client)}};nt.Completions=ar;var cr=class extends x{create(e,t){return this._client.post("/audio/speech",{body:e,...t,__binaryResponse:!0})}};var lr=class extends x{create(e,t){return this._client.post("/audio/transcriptions",_e({body:e,...t}))}};var ur=class extends x{create(e,t){return this._client.post("/audio/translations",_e({body:e,...t}))}};var Oe=class extends x{constructor(){super(...arguments),this.transcriptions=new lr(this._client),this.translations=new ur(this._client),this.speech=new cr(this._client)}};Oe.Transcriptions=lr;Oe.Translations=ur;Oe.Speech=cr;var it=class extends x{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 U(e)?this.list({},e):this._client.getAPIList("/batches",Rt,{query:e,...t})}cancel(e,t){return this._client.post(`/batches/${e}/cancel`,t)}},Rt=class extends H{};it.BatchesPage=Rt;var Ct=class extends x{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 U(e)?this.list({},e):this._client.getAPIList("/assistants",dr,{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}})}},dr=class extends H{};Ct.AssistantsPage=dr;function xi(s){return typeof s.parse=="function"}var ot=s=>(s==null?void 0:s.role)==="assistant",Pi=s=>(s==null?void 0:s.role)==="function",Ai=s=>(s==null?void 0:s.role)==="tool";var Ee=function(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t},W=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},vi,nn,on,ls,us,an,ds,He,hs,cn,ln,hr,na,fr=class{constructor(){vi.add(this),this.controller=new AbortController,nn.set(this,void 0),on.set(this,()=>{}),ls.set(this,()=>{}),us.set(this,void 0),an.set(this,()=>{}),ds.set(this,()=>{}),He.set(this,{}),hs.set(this,!1),cn.set(this,!1),ln.set(this,!1),hr.set(this,!1),Ee(this,nn,new Promise((e,t)=>{Ee(this,on,e,"f"),Ee(this,ls,t,"f")}),"f"),Ee(this,us,new Promise((e,t)=>{Ee(this,an,e,"f"),Ee(this,ds,t,"f")}),"f"),W(this,nn,"f").catch(()=>{}),W(this,us,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},W(this,vi,"m",na).bind(this))},0)}_connected(){this.ended||(W(this,on,"f").call(this),this._emit("connect"))}get ended(){return W(this,hs,"f")}get errored(){return W(this,cn,"f")}get aborted(){return W(this,ln,"f")}abort(){this.controller.abort()}on(e,t){return(W(this,He,"f")[e]||(W(this,He,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=W(this,He,"f")[e];if(!r)return this;let n=r.findIndex(i=>i.listener===t);return n>=0&&r.splice(n,1),this}once(e,t){return(W(this,He,"f")[e]||(W(this,He,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{Ee(this,hr,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){Ee(this,hr,!0,"f"),await W(this,us,"f")}_emit(e,...t){if(W(this,hs,"f"))return;e==="end"&&(Ee(this,hs,!0,"f"),W(this,an,"f").call(this));let r=W(this,He,"f")[e];if(r&&(W(this,He,"f")[e]=r.filter(n=>!n.once),r.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!W(this,hr,"f")&&!(r!=null&&r.length)&&Promise.reject(n),W(this,ls,"f").call(this,n),W(this,ds,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!W(this,hr,"f")&&!(r!=null&&r.length)&&Promise.reject(n),W(this,ls,"f").call(this,n),W(this,ds,"f").call(this,n),this._emit("end")}}_emitFinal(){}};nn=new WeakMap,on=new WeakMap,ls=new WeakMap,us=new WeakMap,an=new WeakMap,ds=new WeakMap,He=new WeakMap,hs=new WeakMap,cn=new WeakMap,ln=new WeakMap,hr=new WeakMap,vi=new WeakSet,na=function(e){if(Ee(this,cn,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new Y),e instanceof Y)return Ee(this,ln,!0,"f"),this._emit("abort",e);if(e instanceof E)return this._emit("error",e);if(e instanceof Error){let t=new E(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new E(String(e)))};function Ii(s){return(s==null?void 0:s.$brand)==="auto-parseable-response-format"}function kt(s){return(s==null?void 0:s.$brand)==="auto-parseable-tool"}function ia(s,e){return!e||!Ei(e)?{...s,choices:s.choices.map(t=>{var r;return{...t,message:{...t.message,parsed:null,tool_calls:(r=t.message.tool_calls)!=null?r:[]}}})}:fs(s,e)}function fs(s,e){let t=s.choices.map(r=>{var n,i;if(r.finish_reason==="length")throw new sr;if(r.finish_reason==="content_filter")throw new nr;return{...r,message:{...r.message,tool_calls:(i=(n=r.message.tool_calls)==null?void 0:n.map(o=>Dl(e,o)))!=null?i:[],parsed:r.message.content&&!r.message.refusal?Bl(e,r.message.content):null}}});return{...s,choices:t}}function Bl(s,e){var t,r;return((t=s.response_format)==null?void 0:t.type)!=="json_schema"?null:((r=s.response_format)==null?void 0:r.type)==="json_schema"?"$parseRaw"in s.response_format?s.response_format.$parseRaw(e):JSON.parse(e):null}function Dl(s,e){var r;let t=(r=s.tools)==null?void 0:r.find(n=>{var i;return((i=n.function)==null?void 0:i.name)===e.function.name});return{...e,function:{...e.function,parsed_arguments:kt(t)?t.$parseRaw(e.function.arguments):t!=null&&t.function.strict?JSON.parse(e.function.arguments):null}}}function oa(s,e){var r;if(!s)return!1;let t=(r=s.tools)==null?void 0:r.find(n=>{var i;return((i=n.function)==null?void 0:i.name)===e.function.name});return kt(t)||(t==null?void 0:t.function.strict)||!1}function Ei(s){var e,t;return Ii(s.response_format)?!0:(t=(e=s.tools)==null?void 0:e.some(r=>kt(r)||r.type==="function"&&r.function.strict===!0))!=null?t:!1}function aa(s){for(let e of s!=null?s:[]){if(e.type!=="function")throw new E(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new E(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var de=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},ne,Si,un,Ri,Ci,ki,la,Mi,ca=10,mr=class extends fr{constructor(){super(...arguments),ne.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),(Pi(e)||Ai(e))&&e.content)this._emit("functionCallResult",e.content);else if(ot(e)&&e.function_call)this._emit("functionCall",e.function_call);else if(ot(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 E("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),de(this,ne,"m",Si).call(this)}async finalMessage(){return await this.done(),de(this,ne,"m",un).call(this)}async finalFunctionCall(){return await this.done(),de(this,ne,"m",Ri).call(this)}async finalFunctionCallResult(){return await this.done(),de(this,ne,"m",Ci).call(this)}async totalUsage(){return await this.done(),de(this,ne,"m",ki).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=de(this,ne,"m",un).call(this);t&&this._emit("finalMessage",t);let r=de(this,ne,"m",Si).call(this);r&&this._emit("finalContent",r);let n=de(this,ne,"m",Ri).call(this);n&&this._emit("finalFunctionCall",n);let i=de(this,ne,"m",Ci).call(this);i!=null&&this._emit("finalFunctionCallResult",i),this._chatCompletions.some(o=>o.usage)&&this._emit("totalUsage",de(this,ne,"m",ki).call(this))}async _createChatCompletion(e,t,r){let n=r==null?void 0:r.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),de(this,ne,"m",la).call(this,t);let i=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(fs(i,t))}async _runChatCompletion(e,t,r){for(let n of t.messages)this._addMessage(n,!1);return await this._createChatCompletion(e,t,r)}async _runFunctions(e,t,r){var m;let n="function",{function_call:i="auto",stream:o,...a}=t,c=typeof i!="string"&&(i==null?void 0:i.name),{maxChatCompletions:l=ca}=r||{},u={};for(let f of t.functions)u[f.name||f.function.name]=f;let h=t.functions.map(f=>({name:f.name||f.function.name,parameters:f.parameters,description:f.description}));for(let f of t.messages)this._addMessage(f,!1);for(let f=0;f<l;++f){let y=(m=(await this._createChatCompletion(e,{...a,function_call:i,functions:h,messages:[...this.messages]},r)).choices[0])==null?void 0:m.message;if(!y)throw new E("missing message in ChatCompletion response");if(!y.function_call)return;let{name:g,arguments:C}=y.function_call,_=u[g];if(_){if(c&&c!==g){let B=`Invalid function_call: ${JSON.stringify(g)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:n,name:g,content:B});continue}}else{let B=`Invalid function_call: ${JSON.stringify(g)}. Available options are: ${h.map(N=>JSON.stringify(N.name)).join(", ")}. Please try again`;this._addMessage({role:n,name:g,content:B});continue}let O;try{O=xi(_)?await _.parse(C):C}catch(B){this._addMessage({role:n,name:g,content:B instanceof Error?B.message:String(B)});continue}let M=await _.function(O,this),v=de(this,ne,"m",Mi).call(this,M);if(this._addMessage({role:n,name:g,content:v}),c)return}}async _runTools(e,t,r){var f,p,y;let n="tool",{tool_choice:i="auto",stream:o,...a}=t,c=typeof i!="string"&&((f=i==null?void 0:i.function)==null?void 0:f.name),{maxChatCompletions:l=ca}=r||{},u=t.tools.map(g=>{if(kt(g)){if(!g.$callback)throw new E("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}),h={};for(let g of u)g.type==="function"&&(h[g.function.name||g.function.function.name]=g.function);let m="tools"in t?u.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 _=(p=(await this._createChatCompletion(e,{...a,tool_choice:i,tools:m,messages:[...this.messages]},r)).choices[0])==null?void 0:p.message;if(!_)throw new E("missing message in ChatCompletion response");if(!((y=_.tool_calls)!=null&&y.length))return;for(let O of _.tool_calls){if(O.type!=="function")continue;let M=O.id,{name:v,arguments:B}=O.function,N=h[v];if(N){if(c&&c!==v){let L=`Invalid tool_call: ${JSON.stringify(v)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:n,tool_call_id:M,content:L});continue}}else{let L=`Invalid tool_call: ${JSON.stringify(v)}. Available options are: ${Object.keys(h).map(D=>JSON.stringify(D)).join(", ")}. Please try again`;this._addMessage({role:n,tool_call_id:M,content:L});continue}let F;try{F=xi(N)?await N.parse(B):B}catch(L){let D=L instanceof Error?L.message:String(L);this._addMessage({role:n,tool_call_id:M,content:D});continue}let T=await N.function(F,this),k=de(this,ne,"m",Mi).call(this,T);if(this._addMessage({role:n,tool_call_id:M,content:k}),c)return}}}};ne=new WeakSet,Si=function(){var e;return(e=de(this,ne,"m",un).call(this).content)!=null?e:null},un=function(){var t,r;let e=this.messages.length;for(;e-- >0;){let n=this.messages[e];if(ot(n)){let{function_call:i,...o}=n,a={...o,content:(t=n.content)!=null?t:null,refusal:(r=n.refusal)!=null?r:null};return i&&(a.function_call=i),a}}throw new E("stream ended without producing a ChatCompletionMessage with role=assistant")},Ri=function(){var e,t;for(let r=this.messages.length-1;r>=0;r--){let n=this.messages[r];if(ot(n)&&(n!=null&&n.function_call))return n.function_call;if(ot(n)&&((e=n==null?void 0:n.tool_calls)!=null&&e.length))return(t=n.tool_calls.at(-1))==null?void 0:t.function}},Ci=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Pi(t)&&t.content!=null||Ai(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(r=>{var n;return r.role==="assistant"&&((n=r.tool_calls)==null?void 0:n.some(i=>i.type==="function"&&i.id===t.tool_call_id))}))return t.content}},ki=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},la=function(e){if(e.n!=null&&e.n>1)throw new E("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Mi=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var at=class extends mr{static runFunctions(e,t,r){let n=new at,i={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runFunctions"}};return n._run(()=>n._runFunctions(e,t,i)),n}static runTools(e,t,r){let n=new at,i={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,i)),n}_addMessage(e,t=!0){super._addMessage(e,t),ot(e)&&e.content&&this._emit("content",e.content)}};var Z={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},Ti=class extends Error{},Oi=class extends Error{};function $l(s,e=Z.ALL){if(typeof s!="string")throw new TypeError(`expecting str, got ${typeof s}`);if(!s.trim())throw new Error(`${s} is empty`);return Ll(s.trim(),e)}var Ll=(s,e)=>{let t=s.length,r=0,n=m=>{throw new Ti(`${m} at position ${r}`)},i=m=>{throw new Oi(`${m} at position ${r}`)},o=()=>(h(),r>=t&&n("Unexpected end of input"),s[r]==='"'?a():s[r]==="{"?c():s[r]==="["?l():s.substring(r,r+4)==="null"||Z.NULL&e&&t-r<4&&"null".startsWith(s.substring(r))?(r+=4,null):s.substring(r,r+4)==="true"||Z.BOOL&e&&t-r<4&&"true".startsWith(s.substring(r))?(r+=4,!0):s.substring(r,r+5)==="false"||Z.BOOL&e&&t-r<5&&"false".startsWith(s.substring(r))?(r+=5,!1):s.substring(r,r+8)==="Infinity"||Z.INFINITY&e&&t-r<8&&"Infinity".startsWith(s.substring(r))?(r+=8,1/0):s.substring(r,r+9)==="-Infinity"||Z.MINUS_INFINITY&e&&1<t-r&&t-r<9&&"-Infinity".startsWith(s.substring(r))?(r+=9,-1/0):s.substring(r,r+3)==="NaN"||Z.NAN&e&&t-r<3&&"NaN".startsWith(s.substring(r))?(r+=3,NaN):u()),a=()=>{let m=r,f=!1;for(r++;r<t&&(s[r]!=='"'||f&&s[r-1]==="\\");)f=s[r]==="\\"?!f:!1,r++;if(s.charAt(r)=='"')try{return JSON.parse(s.substring(m,++r-Number(f)))}catch(p){i(String(p))}else if(Z.STR&e)try{return JSON.parse(s.substring(m,r-Number(f))+'"')}catch(p){return JSON.parse(s.substring(m,s.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},c=()=>{r++,h();let m={};try{for(;s[r]!=="}";){if(h(),r>=t&&Z.OBJ&e)return m;let f=a();h(),r++;try{let p=o();Object.defineProperty(m,f,{value:p,writable:!0,enumerable:!0,configurable:!0})}catch(p){if(Z.OBJ&e)return m;throw p}h(),s[r]===","&&r++}}catch(f){if(Z.OBJ&e)return m;n("Expected '}' at end of object")}return r++,m},l=()=>{r++;let m=[];try{for(;s[r]!=="]";)m.push(o()),h(),s[r]===","&&r++}catch(f){if(Z.ARR&e)return m;n("Expected ']' at end of array")}return r++,m},u=()=>{if(r===0){s==="-"&&Z.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s)}catch(f){if(Z.NUM&e)try{return s[s.length-1]==="."?JSON.parse(s.substring(0,s.lastIndexOf("."))):JSON.parse(s.substring(0,s.lastIndexOf("e")))}catch(p){}i(String(f))}}let m=r;for(s[r]==="-"&&r++;s[r]&&!",]}".includes(s[r]);)r++;r==t&&!(Z.NUM&e)&&n("Unterminated number literal");try{return JSON.parse(s.substring(m,r))}catch(f){s.substring(m,r)==="-"&&Z.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s.substring(m,s.lastIndexOf("e")))}catch(p){i(String(p))}}},h=()=>{for(;r<t&&`
\r `.includes(s[r]);)r++};return o()},Fi=s=>$l(s,Z.ALL^Z.NUM);var pr=function(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t},$=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},X,We,gr,ct,Ni,dn,Bi,Di,$i,hn,Li,ua,Ve=class extends mr{constructor(e){super(),X.add(this),We.set(this,void 0),gr.set(this,void 0),ct.set(this,void 0),pr(this,We,e,"f"),pr(this,gr,[],"f")}get currentChatCompletionSnapshot(){return $(this,ct,"f")}static fromReadableStream(e){let t=new Ve(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let n=new Ve(t);return n._run(()=>n._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createChatCompletion(e,t,r){var o;super._createChatCompletion;let n=r==null?void 0:r.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),$(this,X,"m",Ni).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)$(this,X,"m",Bi).call(this,a);if((o=i.controller.signal)!=null&&o.aborted)throw new Y;return this._addChatCompletion($(this,X,"m",hn).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())),$(this,X,"m",Ni).call(this),this._connected();let n=ie.fromReadableStream(e,this.controller),i;for await(let a of n)i&&i!==a.id&&this._addChatCompletion($(this,X,"m",hn).call(this)),$(this,X,"m",Bi).call(this,a),i=a.id;if((o=n.controller.signal)!=null&&o.aborted)throw new Y;return this._addChatCompletion($(this,X,"m",hn).call(this))}[(We=new WeakMap,gr=new WeakMap,ct=new WeakMap,X=new WeakSet,Ni=function(){this.ended||pr(this,ct,void 0,"f")},dn=function(t){let r=$(this,gr,"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},$(this,gr,"f")[t.index]=r,r)},Bi=function(t){var n,i,o,a,c,l,u,h,m,f,p,y,g,C,_,O,M,v,B,N;if(this.ended)return;let r=$(this,X,"m",ua).call(this,t);this._emit("chunk",t,r);for(let F of t.choices){let T=r.choices[F.index];F.delta.content!=null&&((n=T.message)==null?void 0:n.role)==="assistant"&&((i=T.message)!=null&&i.content)&&(this._emit("content",F.delta.content,T.message.content),this._emit("content.delta",{delta:F.delta.content,snapshot:T.message.content,parsed:T.message.parsed})),F.delta.refusal!=null&&((o=T.message)==null?void 0:o.role)==="assistant"&&((a=T.message)!=null&&a.refusal)&&this._emit("refusal.delta",{delta:F.delta.refusal,snapshot:T.message.refusal}),((c=F.logprobs)==null?void 0:c.content)!=null&&((l=T.message)==null?void 0:l.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(u=F.logprobs)==null?void 0:u.content,snapshot:(m=(h=T.logprobs)==null?void 0:h.content)!=null?m:[]}),((f=F.logprobs)==null?void 0:f.refusal)!=null&&((p=T.message)==null?void 0:p.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(y=F.logprobs)==null?void 0:y.refusal,snapshot:(C=(g=T.logprobs)==null?void 0:g.refusal)!=null?C:[]});let k=$(this,X,"m",dn).call(this,T);T.finish_reason&&($(this,X,"m",$i).call(this,T),k.current_tool_call_index!=null&&$(this,X,"m",Di).call(this,T,k.current_tool_call_index));for(let L of(_=F.delta.tool_calls)!=null?_:[])k.current_tool_call_index!==L.index&&($(this,X,"m",$i).call(this,T),k.current_tool_call_index!=null&&$(this,X,"m",Di).call(this,T,k.current_tool_call_index)),k.current_tool_call_index=L.index;for(let L of(O=F.delta.tool_calls)!=null?O:[]){let D=(M=T.message.tool_calls)==null?void 0:M[L.index];D!=null&&D.type&&((D==null?void 0:D.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(v=D.function)==null?void 0:v.name,index:L.index,arguments:D.function.arguments,parsed_arguments:D.function.parsed_arguments,arguments_delta:(N=(B=L.function)==null?void 0:B.arguments)!=null?N:""}):(D==null||D.type,void 0))}}},Di=function(t,r){var o,a,c;if($(this,X,"m",dn).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=$(this,We,"f"))==null?void 0:a.tools)==null?void 0:c.find(u=>u.type==="function"&&u.function.name===i.function.name);this._emit("tool_calls.function.arguments.done",{name:i.function.name,index:r,arguments:i.function.arguments,parsed_arguments:kt(l)?l.$parseRaw(i.function.arguments):l!=null&&l.function.strict?JSON.parse(i.function.arguments):null})}else i.type},$i=function(t){var n,i;let r=$(this,X,"m",dn).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;let o=$(this,X,"m",Li).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})),(n=t.logprobs)!=null&&n.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}))},hn=function(){if(this.ended)throw new E("stream has ended, this shouldn't happen");let t=$(this,ct,"f");if(!t)throw new E("request ended without sending any chunks");return pr(this,ct,void 0,"f"),pr(this,gr,[],"f"),Ul(t,$(this,We,"f"))},Li=function(){var r;let t=(r=$(this,We,"f"))==null?void 0:r.response_format;return Ii(t)?t:null},ua=function(t){var u,h,m,f,p,y;var r,n,i,o;let a=$(this,ct,"f"),{choices:c,...l}=t;a?Object.assign(a,l):a=pr(this,ct,{...l,choices:[]},"f");for(let{delta:g,finish_reason:C,index:_,logprobs:O=null,...M}of t.choices){let v=a.choices[_];if(v||(v=a.choices[_]={finish_reason:C,index:_,message:{},logprobs:O,...M}),O)if(!v.logprobs)v.logprobs=Object.assign({},O);else{let{content:D,refusal:we,...je}=O;Object.assign(v.logprobs,je),D&&((u=(r=v.logprobs).content)!=null||(r.content=[]),v.logprobs.content.push(...D)),we&&((h=(n=v.logprobs).refusal)!=null||(n.refusal=[]),v.logprobs.refusal.push(...we))}if(C&&(v.finish_reason=C,$(this,We,"f")&&Ei($(this,We,"f")))){if(C==="length")throw new sr;if(C==="content_filter")throw new nr}if(Object.assign(v,M),!g)continue;let{content:B,refusal:N,function_call:F,role:T,tool_calls:k,...L}=g;if(Object.assign(v.message,L),N&&(v.message.refusal=(v.message.refusal||"")+N),T&&(v.message.role=T),F&&(v.message.function_call?(F.name&&(v.message.function_call.name=F.name),F.arguments&&((m=(i=v.message.function_call).arguments)!=null||(i.arguments=""),v.message.function_call.arguments+=F.arguments)):v.message.function_call=F),B&&(v.message.content=(v.message.content||"")+B,!v.message.refusal&&$(this,X,"m",Li).call(this)&&(v.message.parsed=Fi(v.message.content))),k){v.message.tool_calls||(v.message.tool_calls=[]);for(let{index:D,id:we,type:je,function:fe,...Dc}of k){let Ce=(f=(o=v.message.tool_calls)[D])!=null?f:o[D]={};Object.assign(Ce,Dc),we&&(Ce.id=we),je&&(Ce.type=je),fe&&((y=Ce.function)!=null||(Ce.function={name:(p=fe.name)!=null?p:"",arguments:""})),fe!=null&&fe.name&&(Ce.function.name=fe.name),fe!=null&&fe.arguments&&(Ce.function.arguments+=fe.arguments,oa($(this,We,"f"),Ce)&&(Ce.function.parsed_arguments=Fi(Ce.function.arguments)))}}}return a},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("chunk",n=>{let i=t.shift();i?i.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let i of t)i.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let i of t)i.reject(n);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 ie(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Ul(s,e){let{id:t,choices:r,created:n,model:i,system_fingerprint:o,...a}=s,c={...a,id:t,choices:r.map(({message:l,finish_reason:u,index:h,logprobs:m,...f})=>{var O,M,v;if(!u)throw new E(`missing finish_reason for choice ${h}`);let{content:p=null,function_call:y,tool_calls:g,...C}=l,_=l.role;if(!_)throw new E(`missing role for choice ${h}`);if(y){let{arguments:B,name:N}=y;if(B==null)throw new E(`missing function_call.arguments for choice ${h}`);if(!N)throw new E(`missing function_call.name for choice ${h}`);return{...f,message:{content:p,function_call:{arguments:B,name:N},role:_,refusal:(O=l.refusal)!=null?O:null},finish_reason:u,index:h,logprobs:m}}return g?{...f,index:h,finish_reason:u,logprobs:m,message:{...C,role:_,content:p,refusal:(M=l.refusal)!=null?M:null,tool_calls:g.map((B,N)=>{let{function:F,type:T,id:k,...L}=B,{arguments:D,name:we,...je}=F||{};if(k==null)throw new E(`missing choices[${h}].tool_calls[${N}].id
${fn(s)}`);if(T==null)throw new E(`missing choices[${h}].tool_calls[${N}].type
${fn(s)}`);if(we==null)throw new E(`missing choices[${h}].tool_calls[${N}].function.name
${fn(s)}`);if(D==null)throw new E(`missing choices[${h}].tool_calls[${N}].function.arguments
${fn(s)}`);return{...L,id:k,type:T,function:{...je,name:we,arguments:D}}})}}:{...f,message:{...C,content:p,role:_,refusal:(v=l.refusal)!=null?v:null},finish_reason:u,index:h,logprobs:m}}),created:n,model:i,object:"chat.completion",...o?{system_fingerprint:o}:{}};return ia(c,e)}function fn(s){return JSON.stringify(s)}var ze=class extends Ve{static fromReadableStream(e){let t=new ze(null);return t._run(()=>t._fromReadableStream(e)),t}static runFunctions(e,t,r){let n=new ze(null),i={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runFunctions"}};return n._run(()=>n._runFunctions(e,t,i)),n}static runTools(e,t,r){let n=new ze(t),i={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,i)),n}};var ms=class extends x{parse(e,t){return aa(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=>fs(r,e))}runFunctions(e,t){return e.stream?ze.runFunctions(this._client,e,t):at.runFunctions(this._client,e,t)}runTools(e,t){return e.stream?ze.runTools(this._client,e,t):at.runTools(this._client,e,t)}stream(e,t){return Ve.createChatCompletion(this._client,e,t)}};var yr=class extends x{constructor(){super(...arguments),this.completions=new ms(this._client)}};(function(s){s.Completions=ms})(yr||(yr={}));var A=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},me=function(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t},te,Ui,Fe,mn,Se,Tt,br,Mt,yn,pe,pn,gn,ys,ps,gs,da,ha,fa,ma,pa,ga,ya,oe=class extends fr{constructor(){super(...arguments),te.add(this),Ui.set(this,[]),Fe.set(this,{}),mn.set(this,{}),Se.set(this,void 0),Tt.set(this,void 0),br.set(this,void 0),Mt.set(this,void 0),yn.set(this,void 0),pe.set(this,void 0),pn.set(this,void 0),gn.set(this,void 0),ys.set(this,void 0)}[(Ui=new WeakMap,Fe=new WeakMap,mn=new WeakMap,Se=new WeakMap,Tt=new WeakMap,br=new WeakMap,Mt=new WeakMap,yn=new WeakMap,pe=new WeakMap,pn=new WeakMap,gn=new WeakMap,ys=new WeakMap,te=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",n=>{let i=t.shift();i?i.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let i of t)i.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let i of t)i.reject(n);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 oe;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 n=ie.fromReadableStream(e,this.controller);for await(let o of n)A(this,te,"m",ps).call(this,o);if((i=n.controller.signal)!=null&&i.aborted)throw new Y;return this._addRun(A(this,te,"m",gs).call(this))}toReadableStream(){return new ie(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,n,i){let o=new oe;return o._run(()=>o._runToolAssistantStream(e,t,r,n,{...i,headers:{...i==null?void 0:i.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,r,n,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={...n,stream:!0},c=await e.submitToolOutputs(t,r,a,{...i,signal:this.controller.signal});this._connected();for await(let u of c)A(this,te,"m",ps).call(this,u);if((l=c.controller.signal)!=null&&l.aborted)throw new Y;return this._addRun(A(this,te,"m",gs).call(this))}static createThreadAssistantStream(e,t,r){let n=new oe;return n._run(()=>n._threadAssistantStream(e,t,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),n}static createAssistantStream(e,t,r,n){let i=new oe;return i._run(()=>i._runAssistantStream(e,t,r,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),i}currentEvent(){return A(this,pn,"f")}currentRun(){return A(this,gn,"f")}currentMessageSnapshot(){return A(this,Se,"f")}currentRunStepSnapshot(){return A(this,ys,"f")}async finalRunSteps(){return await this.done(),Object.values(A(this,Fe,"f"))}async finalMessages(){return await this.done(),Object.values(A(this,mn,"f"))}async finalRun(){if(await this.done(),!A(this,Tt,"f"))throw Error("Final run was not received.");return A(this,Tt,"f")}async _createThreadAssistantStream(e,t,r){var a;let n=r==null?void 0:r.signal;n&&(n.aborted&&this.controller.abort(),n.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)A(this,te,"m",ps).call(this,c);if((a=o.controller.signal)!=null&&a.aborted)throw new Y;return this._addRun(A(this,te,"m",gs).call(this))}async _createAssistantStream(e,t,r,n){var c;let i=n==null?void 0:n.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));let o={...r,stream:!0},a=await e.create(t,o,{...n,signal:this.controller.signal});this._connected();for await(let l of a)A(this,te,"m",ps).call(this,l);if((c=a.controller.signal)!=null&&c.aborted)throw new Y;return this._addRun(A(this,te,"m",gs).call(this))}static accumulateDelta(e,t){for(let[r,n]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=n;continue}let i=e[r];if(i==null){e[r]=n;continue}if(r==="index"||r==="type"){e[r]=n;continue}if(typeof i=="string"&&typeof n=="string")i+=n;else if(typeof i=="number"&&typeof n=="number")i+=n;else if(cs(i)&&cs(n))i=this.accumulateDelta(i,n);else if(Array.isArray(i)&&Array.isArray(n)){if(i.every(o=>typeof o=="string"||typeof o=="number")){i.push(...n);continue}for(let o of n){if(!cs(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: ${n}, 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,n){return await this._createAssistantStream(t,e,r,n)}async _runToolAssistantStream(e,t,r,n,i){return await this._createToolAssistantStream(r,e,t,n,i)}};ps=function(e){if(!this.ended)switch(me(this,pn,e,"f"),A(this,te,"m",fa).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":A(this,te,"m",ya).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":A(this,te,"m",ha).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":A(this,te,"m",da).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},gs=function(){if(this.ended)throw new E("stream has ended, this shouldn't happen");if(!A(this,Tt,"f"))throw Error("Final run has not been received");return A(this,Tt,"f")},da=function(e){let[t,r]=A(this,te,"m",pa).call(this,e,A(this,Se,"f"));me(this,Se,t,"f"),A(this,mn,"f")[t.id]=t;for(let n of r){let i=t.content[n.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 n of e.data.delta.content){if(n.type=="text"&&n.text){let i=n.text,o=t.content[n.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(n.index!=A(this,br,"f")){if(A(this,Mt,"f"))switch(A(this,Mt,"f").type){case"text":this._emit("textDone",A(this,Mt,"f").text,A(this,Se,"f"));break;case"image_file":this._emit("imageFileDone",A(this,Mt,"f").image_file,A(this,Se,"f"));break}me(this,br,n.index,"f")}me(this,Mt,t.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(A(this,br,"f")!==void 0){let n=e.data.content[A(this,br,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,A(this,Se,"f"));break;case"text":this._emit("textDone",n.text,A(this,Se,"f"));break}}A(this,Se,"f")&&this._emit("messageDone",e.data),me(this,Se,void 0,"f")}},ha=function(e){let t=A(this,te,"m",ma).call(this,e);switch(me(this,ys,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==A(this,yn,"f")?this._emit("toolCallDelta",i,t.step_details.tool_calls[i.index]):(A(this,pe,"f")&&this._emit("toolCallDone",A(this,pe,"f")),me(this,yn,i.index,"f"),me(this,pe,t.step_details.tool_calls[i.index],"f"),A(this,pe,"f")&&this._emit("toolCallCreated",A(this,pe,"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":me(this,ys,void 0,"f"),e.data.step_details.type=="tool_calls"&&A(this,pe,"f")&&(this._emit("toolCallDone",A(this,pe,"f")),me(this,pe,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},fa=function(e){A(this,Ui,"f").push(e),this._emit("event",e)},ma=function(e){switch(e.event){case"thread.run.step.created":return A(this,Fe,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=A(this,Fe,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){let n=oe.accumulateDelta(t,r.delta);A(this,Fe,"f")[e.data.id]=n}return A(this,Fe,"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":A(this,Fe,"f")[e.data.id]=e.data;break}if(A(this,Fe,"f")[e.data.id])return A(this,Fe,"f")[e.data.id];throw new Error("No snapshot available")},pa=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 n=e.data;if(n.delta.content)for(let i of n.delta.content)if(i.index in t.content){let o=t.content[i.index];t.content[i.index]=A(this,te,"m",ga).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")},ga=function(e,t){return oe.accumulateDelta(t,e)},ya=function(e){switch(me(this,gn,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":me(this,Tt,e.data,"f"),A(this,pe,"f")&&(this._emit("toolCallDone",A(this,pe,"f")),me(this,pe,void 0,"f"));break;case"thread.run.cancelling":break}};var Ot=class extends x{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,n){return this._client.post(`/threads/${e}/messages/${t}`,{body:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}list(e,t={},r){return U(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/messages`,wr,{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}})}},wr=class extends H{};Ot.MessagesPage=wr;var Ft=class extends x{retrieve(e,t,r,n={},i){return U(n)?this.retrieve(e,t,r,{},n):this._client.get(`/threads/${e}/runs/${t}/steps/${r}`,{query:n,...i,headers:{"OpenAI-Beta":"assistants=v2",...i==null?void 0:i.headers}})}list(e,t,r={},n){return U(r)?this.list(e,t,{},r):this._client.getAPIList(`/threads/${e}/runs/${t}/steps`,_r,{query:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}},_r=class extends H{};Ft.RunStepsPage=_r;var Ke=class extends x{constructor(){super(...arguments),this.steps=new Ft(this._client)}create(e,t,r){var o;let{include:n,...i}=t;return this._client.post(`/threads/${e}/runs`,{query:{include:n},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,n){return this._client.post(`/threads/${e}/runs/${t}`,{body:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}list(e,t={},r){return U(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/runs`,xr,{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 n=await this.create(e,t,r);return await this.poll(e,n.id,r)}createAndStream(e,t,r){return oe.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let n={...r==null?void 0:r.headers,"X-Stainless-Poll-Helper":"true"};for(r!=null&&r.pollIntervalMs&&(n["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,...n}}).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 qe(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(e,t,r){return oe.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r,n){var i;return this._client.post(`/threads/${e}/runs/${t}/submit_tool_outputs`,{body:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers},stream:(i=r.stream)!=null?i:!1})}async submitToolOutputsAndPoll(e,t,r,n){let i=await this.submitToolOutputs(e,t,r,n);return await this.poll(e,i.id,n)}submitToolOutputsStream(e,t,r,n){return oe.createToolAssistantStream(e,t,this._client.beta.threads.runs,r,n)}},xr=class extends H{};Ke.RunsPage=xr;Ke.Steps=Ft;Ke.RunStepsPage=_r;var Ne=class extends x{constructor(){super(...arguments),this.runs=new Ke(this._client),this.messages=new Ot(this._client)}create(e={},t){return U(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 oe.createThreadAssistantStream(e,this._client.beta.threads,t)}};Ne.Runs=Ke;Ne.RunsPage=xr;Ne.Messages=Ot;Ne.MessagesPage=wr;var ba=async s=>{let e=await Promise.allSettled(s),t=e.filter(n=>n.status==="rejected");if(t.length){for(let n of t)console.error(n.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}let r=[];for(let n of e)n.status==="fulfilled"&&r.push(n.value);return r};var Nt=class extends x{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 U(t)?this.list(e,{},t):this._client.getAPIList(`/vector_stores/${e}/files`,lt,{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 n=await this.create(e,t,r);return await this.poll(e,n.id,r)}async poll(e,t,r){let n={...r==null?void 0:r.headers,"X-Stainless-Poll-Helper":"true"};for(r!=null&&r.pollIntervalMs&&(n["X-Stainless-Custom-Poll-Interval"]=r.pollIntervalMs.toString());;){let i=await this.retrieve(e,t,{...r,headers:n}).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 qe(a);break;case"failed":case"completed":return o}}}async upload(e,t,r){let n=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:n.id},r)}async uploadAndPoll(e,t,r){let n=await this.upload(e,t,r);return await this.poll(e,n.id,r)}},lt=class extends H{};Nt.VectorStoreFilesPage=lt;var Pr=class extends x{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 n=await this.create(e,t);return await this.poll(e,n.id,r)}listFiles(e,t,r={},n){return U(r)?this.listFiles(e,t,{},r):this._client.getAPIList(`/vector_stores/${e}/file_batches/${t}/files`,lt,{query:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}async poll(e,t,r){let n={...r==null?void 0:r.headers,"X-Stainless-Poll-Helper":"true"};for(r!=null&&r.pollIntervalMs&&(n["X-Stainless-Custom-Poll-Interval"]=r.pollIntervalMs.toString());;){let{data:i,response:o}=await this.retrieve(e,t,{...r,headers:n}).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 qe(a);break;case"failed":case"cancelled":case"completed":return i}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},n){var m;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=(m=n==null?void 0:n.maxConcurrency)!=null?m:5,o=Math.min(i,t.length),a=this._client,c=t.values(),l=[...r];async function u(f){for(let p of f){let y=await a.files.create({file:p,purpose:"assistants"},n);l.push(y.id)}}let h=Array(o).fill(c).map(u);return await ba(h),await this.createAndPoll(e,{file_ids:l})}};var Be=class extends x{constructor(){super(...arguments),this.files=new Nt(this._client),this.fileBatches=new Pr(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 U(e)?this.list({},e):this._client.getAPIList("/vector_stores",Ar,{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}})}},Ar=class extends H{};Be.VectorStoresPage=Ar;Be.Files=Nt;Be.VectorStoreFilesPage=lt;Be.FileBatches=Pr;var xe=class extends x{constructor(){super(...arguments),this.vectorStores=new Be(this._client),this.chat=new yr(this._client),this.assistants=new Ct(this._client),this.threads=new Ne(this._client)}};xe.VectorStores=Be;xe.VectorStoresPage=Ar;xe.Assistants=Ct;xe.AssistantsPage=dr;xe.Threads=Ne;var Bt=class extends x{create(e,t){var r;return this._client.post("/completions",{body:e,...t,stream:(r=e.stream)!=null?r:!1})}};var Dt=class extends x{create(e,t){return this._client.post("/embeddings",{body:e,...t})}};var ut=class extends x{create(e,t){return this._client.post("/files",_e({body:e,...t}))}retrieve(e,t){return this._client.get(`/files/${e}`,t)}list(e={},t){return U(e)?this.list({},e):this._client.getAPIList("/files",$t,{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 n=new Set(["processed","error","deleted"]),i=Date.now(),o=await this.retrieve(e);for(;!o.status||!n.has(o.status);)if(await qe(t),o=await this.retrieve(e),Date.now()-i>r)throw new st({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return o}},$t=class extends H{};ut.FileObjectsPage=$t;var Lt=class extends x{list(e,t={},r){return U(t)?this.list(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/checkpoints`,vr,{query:t,...r})}},vr=class extends H{};Lt.FineTuningJobCheckpointsPage=vr;var De=class extends x{constructor(){super(...arguments),this.checkpoints=new Lt(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 U(e)?this.list({},e):this._client.getAPIList("/fine_tuning/jobs",Ir,{query:e,...t})}cancel(e,t){return this._client.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return U(t)?this.listEvents(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/events`,Er,{query:t,...r})}},Ir=class extends H{},Er=class extends H{};De.FineTuningJobsPage=Ir;De.FineTuningJobEventsPage=Er;De.Checkpoints=Lt;De.FineTuningJobCheckpointsPage=vr;var $e=class extends x{constructor(){super(...arguments),this.jobs=new De(this._client)}};$e.Jobs=De;$e.FineTuningJobsPage=Ir;$e.FineTuningJobEventsPage=Er;var Ut=class extends x{createVariation(e,t){return this._client.post("/images/variations",_e({body:e,...t}))}edit(e,t){return this._client.post("/images/edits",_e({body:e,...t}))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}};var dt=class extends x{retrieve(e,t){return this._client.get(`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",jt,e)}del(e,t){return this._client.delete(`/models/${e}`,t)}},jt=class extends sn{};dt.ModelsPage=jt;var qt=class extends x{create(e,t){return this._client.post("/moderations",{body:e,...t})}};var Sr=class extends x{create(e,t,r){return this._client.post(`/uploads/${e}/parts`,_e({body:t,...r}))}};var ht=class extends x{constructor(){super(...arguments),this.parts=new Sr(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})}};ht.Parts=Sr;var wa,R=class extends rn{constructor({baseURL:e=as("OPENAI_BASE_URL"),apiKey:t=as("OPENAI_API_KEY"),organization:r=(o=>(o=as("OPENAI_ORG_ID"))!=null?o:null)(),project:n=(a=>(a=as("OPENAI_PROJECT_ID"))!=null?a:null)(),...i}={}){var l;if(t===void 0)throw new E("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:n,...i,baseURL:e||"https://api.openai.com/v1"};if(!c.dangerouslyAllowBrowser&&sa())throw new E(`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 Bt(this),this.chat=new nt(this),this.embeddings=new Dt(this),this.files=new ut(this),this.images=new Ut(this),this.audio=new Oe(this),this.moderations=new qt(this),this.models=new dt(this),this.fineTuning=new $e(this),this.beta=new xe(this),this.batches=new it(this),this.uploads=new ht(this),this._options=c,this.apiKey=t,this.organization=r,this.project=n}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 ai(e,{arrayFormat:"brackets"})}};wa=R;R.OpenAI=wa;R.DEFAULT_TIMEOUT=6e5;R.OpenAIError=E;R.APIError=z;R.APIConnectionError=rt;R.APIConnectionTimeoutError=st;R.APIUserAbortError=Y;R.NotFoundError=es;R.ConflictError=ts;R.RateLimitError=ss;R.BadRequestError=Qr;R.AuthenticationError=Yr;R.InternalServerError=ns;R.PermissionDeniedError=Zr;R.UnprocessableEntityError=rs;R.toFile=yi;R.fileFromPath=Qs;R.Completions=Bt;R.Chat=nt;R.Embeddings=Dt;R.Files=ut;R.FileObjectsPage=$t;R.Images=Ut;R.Audio=Oe;R.Moderations=qt;R.Models=dt;R.ModelsPage=jt;R.FineTuning=$e;R.Beta=xe;R.Batches=it;R.BatchesPage=Rt;R.Uploads=ht;var _a=R;var xa=require("electron"),ji=require("obsidian");function bn(s){if(!s)return{};if(typeof Headers!="undefined"&&s instanceof Headers){let e={};return s.forEach((t,r)=>{e[r]=t}),e}if(Array.isArray(s)){let e={};for(let[t,r]of s)e[t]=r;return e}return{...s}}async function qi(s,e={}){var i;let t=bn(e.headers);delete t["content-length"];let r={};this&&"controller"in this&&(r.controller=this.controller);let n=e.signal||((i=r.controller)==null?void 0:i.signal);return b.debug("electronFetch request:",{url:s,method:e.method||"GET",headers:t,hasBody:!!e.body,platform:ji.Platform.isMobileApp?"mobile":"desktop"}),ji.Platform.isMobileApp?(b.debug("Using native fetch (mobile platform)"),fetch(s,{...e,signal:n})):new Promise((o,a)=>{let c=()=>{l.removeAllListeners(),b.debug("Request cleanup completed")},l=xa.remote.net.request({url:s,method:e.method||"GET"});if(Object.entries(t).forEach(([u,h])=>{l.setHeader(u,h)}),n!=null&&n.aborted){b.debug("Request aborted before start"),l.abort(),a(new Error("Aborted"));return}n==null||n.addEventListener("abort",()=>{b.debug("Request aborted by controller"),c(),l.abort(),a(new Error("Aborted"))}),l.on("response",u=>{if(n!=null&&n.aborted){b.debug("Request aborted during response");return}b.debug("Response received:",{status:u.statusCode,headers:u.headers});let{readable:h,writable:m}=new TransformStream({transform(y,g){g.enqueue(new Uint8Array(y))}}),f=m.getWriter(),p={status:u.statusCode||200,headers:u.headers};o(new Response(h,p)),u.on("data",async y=>{try{await f.ready,await f.write(y),b.debug("Chunk received:",{size:y.length,text:y.toString("utf-8")})}catch(g){b.error("Error writing chunk:",g),c(),f.abort(g)}}),u.on("end",async()=>{try{await f.ready,await f.close(),b.debug("Response stream completed")}catch(y){b.error("Error closing writer:",y)}finally{c()}}),u.on("error",y=>{b.error("Response error:",y),c(),f.abort(y),a(y)})}),l.on("error",u=>{b.error("Request error:",u),c(),a(u)}),e.body&&l.write(e.body),l.end(),b.debug("Request sent")})}var Pa=require("obsidian");var he=async(s,e={})=>{let t=bn(e.headers);delete t["content-length"],b.debug("obsidianFetch request:",{url:s,method:e.method||"GET",headers:t,hasBody:!!e.body});let r={url:s,method:e.method||"GET",headers:t};e.body&&(r.body=e.body,b.debug("Request body prepared:",r.body));try{b.debug("Sending request via requestUrl");let n=await(0,Pa.requestUrl)(r);b.debug("Response received:",{status:n.status,headers:n.headers,contentLength:n.text.length});let i={status:n.status,headers:n.headers};return new Response(n.text,i)}catch(n){throw b.error("Request failed:",n,{headers:t}),n}};var Aa=require("obsidian");var eu=["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"],ft=class{constructor(e){this.settings=e;this.corsBlockedProviders=new Set}getProviderKey(e){return`${e.url||"unknown"}:${e.type}`}isMobilePlatform(){return Aa.Platform.isMobileApp}shouldUseNativeFetch(){var e;return(e=this.settings.useNativeFetch)!=null?e:!1}getFetch(e){let t=e.name;return this.isBlocked(e)?(b.debug("Using obsidianFetch for CORS-blocked provider (API):",t),he):this.isMobilePlatform()?(b.debug("Using obsidianFetch for mobile platform (API):",t),he):this.shouldUseNativeFetch()?(b.debug("Using native fetch for provider (API):",t),globalThis.fetch):(b.debug("Using obsidianFetch for provider (API):",t),he)}getStreamingFetch(e){let t=e.name;return this.isBlocked(e)?(b.debug("Using obsidianFetch for CORS-blocked provider (streaming):",t),he):this.isMobilePlatform()?(b.debug("Using obsidianFetch for mobile platform (streaming):",t),he):this.shouldUseNativeFetch()?(b.debug("Using native fetch for provider (streaming):",t),globalThis.fetch):(b.debug("Using electronFetch for provider (streaming):",t),qi)}getFetchFunction(e){let t=e.name;return this.isBlocked(e)?(b.debug("Using obsidianFetch for CORS-blocked provider:",t),he):this.isMobilePlatform()?(b.debug("Using obsidianFetch for mobile platform:",t),he):this.shouldUseNativeFetch()?(b.debug("Using native fetch for provider:",t),globalThis.fetch):(b.debug("Using electronFetch for provider:",t),qi)}isCorsError(e){if(!e)return!1;let t=(e.message||"").toLowerCase(),r=(e.name||"").toLowerCase();b.debug("Checking CORS error:",{message:e.message,name:e.name});let n=this.matchesCorsPattern(t,r);return b.debug("CORS error detection result:",{isCors:n}),n}matchesCorsPattern(e,t){return eu.some(r=>e.includes(r)||t.includes(r))}async execute(e,t){if(b.debug("Starting execute operation for provider:",e.name),this.isBlocked(e))return b.debug("Provider already CORS-blocked, using obsidianFetch directly"),t(he);let r=this.getStreamingFetch(e);try{let n=await t(r);return b.debug("Execute operation completed successfully"),n}catch(n){if(this.isCorsError(n))return b.debug("CORS error detected in execute, retrying with obsidianFetch"),this.markBlocked(e),t(he);throw n}}async request(e,t){if(b.debug("Starting request operation for provider:",e.name),this.isBlocked(e))return b.debug("Provider already CORS-blocked, using obsidianFetch directly"),t(he);let r=this.getFetch(e);try{let n=await t(r);return b.debug("Request operation completed successfully"),n}catch(n){if(this.isCorsError(n))return b.debug("CORS error detected in request, retrying with obsidianFetch"),this.markBlocked(e),t(he);throw n}}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),b.debug("Provider marked as CORS blocked:",{key:t,provider:e.name})}clear(){this.corsBlockedProviders.clear(),b.debug("All CORS blocked providers cleared")}};var Je=class{constructor(e){this.settings=e;this.fetchSelector=new ft(e)}getClient(e,t){let r;return t?r=t:r=this.fetchSelector.getFetchFunction(e),new _a({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 n=>{if(t!=null&&t.signal.aborted)throw new Error("Aborted");return(await this.getClient(e,n).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 n=Array.isArray(t)?t:[t],i=[],o=2048,a=[];for(let u=0;u<n.length;u+=o)a.push(n.slice(u,u+o));let c=[];for(let u of a){if(r!=null&&r.signal.aborted)throw new Error("Aborted");let h=async f=>{let y=await this.getClient(e.provider,f).embeddings.create({model:e.provider.model||"",input:u},{signal:r==null?void 0:r.signal});return b.debug("Embed response:",y),y.data.map(g=>g.embedding)},m=await this.fetchSelector.request(e.provider,h);if(i.push(...m),c.push(...u),e.onProgress&&e.onProgress([...c]),r!=null&&r.signal.aborted)throw new Error("Aborted")}return i}async executeOpenAIGeneration(e,t,r,n){var c,l,u;let i=[];if("messages"in e&&e.messages)i=e.messages.map(h=>{if(typeof h.content=="string")return{role:h.role,content:h.content};let m=[];return h.content.forEach(f=>{f.type==="text"?m.push({type:"text",text:f.text}):f.type==="image_url"&&m.push({type:"image_url",image_url:{url:f.image_url.url}})}),{role:h.role,content:m}});else if("prompt"in e)if(e.systemPrompt&&i.push({role:"system",content:e.systemPrompt}),(c=e.images)!=null&&c.length){let h=[{type:"text",text:e.prompt}];e.images.forEach(m=>{h.push({type:"image_url",image_url:{url:m}})}),i.push({role:"user",content:h})}else i.push({role:"user",content:e.prompt});else throw new Error("Either messages or prompt must be provided");b.debug("Sending chat request to OpenAI");let o=await t.chat.completions.create({model:e.provider.model||"",messages:i,stream:!0,...e.options},{signal:n==null?void 0:n.signal}),a="";for await(let h of o){if(n!=null&&n.signal.aborted)throw new Error("Aborted");let m=(u=(l=h.choices[0])==null?void 0:l.delta)==null?void 0:u.content;m&&(a+=m,r&&r(m,a))}return a}async execute(e){var i,o,a,c;b.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,n=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 u=this.getClient(e.provider,l);return this.executeOpenAIGeneration(e,u,(h,m)=>{if(n&&n(h,m),r!=null&&r.signal.aborted)throw new Error("Aborted")},r)})}catch(l){let u=l;if(u.message==="Aborted")return Promise.reject(u);throw u}}};var re=typeof globalThis!="undefined"&&globalThis||typeof self!="undefined"&&self||typeof global!="undefined"&&global||{},ae={searchParams:"URLSearchParams"in re,iterable:"Symbol"in re&&"iterator"in Symbol,blob:"FileReader"in re&&"Blob"in re&&function(){try{return new Blob,!0}catch(s){return!1}}(),formData:"FormData"in re,arrayBuffer:"ArrayBuffer"in re};function tu(s){return s&&DataView.prototype.isPrototypeOf(s)}ae.arrayBuffer&&(va=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],Ea=ArrayBuffer.isView||function(s){return s&&va.indexOf(Object.prototype.toString.call(s))>-1});var va,Ea;function Rr(s){if(typeof s!="string"&&(s=String(s)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(s)||s==="")throw new TypeError('Invalid character in header field name: "'+s+'"');return s.toLowerCase()}function Wi(s){return typeof s!="string"&&(s=String(s)),s}function Vi(s){var e={next:function(){var t=s.shift();return{done:t===void 0,value:t}}};return ae.iterable&&(e[Symbol.iterator]=function(){return e}),e}function G(s){this.map={},s instanceof G?s.forEach(function(e,t){this.append(t,e)},this):Array.isArray(s)?s.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):s&&Object.getOwnPropertyNames(s).forEach(function(e){this.append(e,s[e])},this)}G.prototype.append=function(s,e){s=Rr(s),e=Wi(e);var t=this.map[s];this.map[s]=t?t+", "+e:e};G.prototype.delete=function(s){delete this.map[Rr(s)]};G.prototype.get=function(s){return s=Rr(s),this.has(s)?this.map[s]:null};G.prototype.has=function(s){return this.map.hasOwnProperty(Rr(s))};G.prototype.set=function(s,e){this.map[Rr(s)]=Wi(e)};G.prototype.forEach=function(s,e){for(var t in this.map)this.map.hasOwnProperty(t)&&s.call(e,this.map[t],t,this)};G.prototype.keys=function(){var s=[];return this.forEach(function(e,t){s.push(t)}),Vi(s)};G.prototype.values=function(){var s=[];return this.forEach(function(e){s.push(e)}),Vi(s)};G.prototype.entries=function(){var s=[];return this.forEach(function(e,t){s.push([t,e])}),Vi(s)};ae.iterable&&(G.prototype[Symbol.iterator]=G.prototype.entries);function Hi(s){if(!s._noBody){if(s.bodyUsed)return Promise.reject(new TypeError("Already read"));s.bodyUsed=!0}}function Sa(s){return new Promise(function(e,t){s.onload=function(){e(s.result)},s.onerror=function(){t(s.error)}})}function ru(s){var e=new FileReader,t=Sa(e);return e.readAsArrayBuffer(s),t}function su(s){var e=new FileReader,t=Sa(e),r=/charset=([A-Za-z0-9_-]+)/.exec(s.type),n=r?r[1]:"utf-8";return e.readAsText(s,n),t}function nu(s){for(var e=new Uint8Array(s),t=new Array(e.length),r=0;r<e.length;r++)t[r]=String.fromCharCode(e[r]);return t.join("")}function Ia(s){if(s.slice)return s.slice(0);var e=new Uint8Array(s.byteLength);return e.set(new Uint8Array(s)),e.buffer}function Ra(){return this.bodyUsed=!1,this._initBody=function(s){this.bodyUsed=this.bodyUsed,this._bodyInit=s,s?typeof s=="string"?this._bodyText=s:ae.blob&&Blob.prototype.isPrototypeOf(s)?this._bodyBlob=s:ae.formData&&FormData.prototype.isPrototypeOf(s)?this._bodyFormData=s:ae.searchParams&&URLSearchParams.prototype.isPrototypeOf(s)?this._bodyText=s.toString():ae.arrayBuffer&&ae.blob&&tu(s)?(this._bodyArrayBuffer=Ia(s.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):ae.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(s)||Ea(s))?this._bodyArrayBuffer=Ia(s):this._bodyText=s=Object.prototype.toString.call(s):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof s=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):ae.searchParams&&URLSearchParams.prototype.isPrototypeOf(s)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},ae.blob&&(this.blob=function(){var s=Hi(this);if(s)return s;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 s=Hi(this);return s||(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(ae.blob)return this.blob().then(ru);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var s=Hi(this);if(s)return s;if(this._bodyBlob)return su(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(nu(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},ae.formData&&(this.formData=function(){return this.text().then(au)}),this.json=function(){return this.text().then(JSON.parse)},this}var iu=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function ou(s){var e=s.toUpperCase();return iu.indexOf(e)>-1?e:s}function Wt(s,e){if(!(this instanceof Wt))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(s instanceof Wt){if(s.bodyUsed)throw new TypeError("Already read");this.url=s.url,this.credentials=s.credentials,e.headers||(this.headers=new G(s.headers)),this.method=s.method,this.mode=s.mode,this.signal=s.signal,!t&&s._bodyInit!=null&&(t=s._bodyInit,s.bodyUsed=!0)}else this.url=String(s);if(this.credentials=e.credentials||this.credentials||"same-origin",(e.headers||!this.headers)&&(this.headers=new G(e.headers)),this.method=ou(e.method||this.method||"GET"),this.mode=e.mode||this.mode||null,this.signal=e.signal||this.signal||function(){if("AbortController"in re){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 n=/\?/;this.url+=(n.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}Wt.prototype.clone=function(){return new Wt(this,{body:this._bodyInit})};function au(s){var e=new FormData;return s.trim().split("&").forEach(function(t){if(t){var r=t.split("="),n=r.shift().replace(/\+/g," "),i=r.join("=").replace(/\+/g," ");e.append(decodeURIComponent(n),decodeURIComponent(i))}}),e}function cu(s){var e=new G,t=s.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 n=r.split(":"),i=n.shift().trim();if(i){var o=n.join(":").trim();try{e.append(i,o)}catch(a){console.warn("Response "+a.message)}}}),e}Ra.call(Wt.prototype);function Le(s,e){if(!(this instanceof Le))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 G(e.headers),this.url=e.url||"",this._initBody(s)}Ra.call(Le.prototype);Le.prototype.clone=function(){return new Le(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new G(this.headers),url:this.url})};Le.error=function(){var s=new Le(null,{status:200,statusText:""});return s.ok=!1,s.status=0,s.type="error",s};var lu=[301,302,303,307,308];Le.redirect=function(s,e){if(lu.indexOf(e)===-1)throw new RangeError("Invalid status code");return new Le(null,{status:e,headers:{location:s}})};var Ht=re.DOMException;try{new Ht}catch(s){Ht=function(e,t){this.message=e,this.name=t;var r=Error(e);this.stack=r.stack},Ht.prototype=Object.create(Error.prototype),Ht.prototype.constructor=Ht}function Ca(s,e){return new Promise(function(t,r){var n=new Wt(s,e);if(n.signal&&n.signal.aborted)return r(new Ht("Aborted","AbortError"));var i=new XMLHttpRequest;function o(){i.abort()}i.onload=function(){var l={statusText:i.statusText,headers:cu(i.getAllResponseHeaders()||"")};n.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 u="response"in i?i.response:i.responseText;setTimeout(function(){t(new Le(u,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 Ht("Aborted","AbortError"))},0)};function a(l){try{return l===""&&re.location.href?re.location.href:l}catch(u){return l}}if(i.open(n.method,a(n.url),!0),n.credentials==="include"?i.withCredentials=!0:n.credentials==="omit"&&(i.withCredentials=!1),"responseType"in i&&(ae.blob?i.responseType="blob":ae.arrayBuffer&&(i.responseType="arraybuffer")),e&&typeof e.headers=="object"&&!(e.headers instanceof G||re.Headers&&e.headers instanceof re.Headers)){var c=[];Object.getOwnPropertyNames(e.headers).forEach(function(l){c.push(Rr(l)),i.setRequestHeader(l,Wi(e.headers[l]))}),n.headers.forEach(function(l,u){c.indexOf(u)===-1&&i.setRequestHeader(u,l)})}else n.headers.forEach(function(l,u){i.setRequestHeader(u,l)});n.signal&&(n.signal.addEventListener("abort",o),i.onreadystatechange=function(){i.readyState===4&&n.signal.removeEventListener("abort",o)}),i.send(typeof n._bodyInit=="undefined"?null:n._bodyInit)})}Ca.polyfill=!0;re.fetch||(re.fetch=Ca,re.Headers=G,re.Request=Wt,re.Response=Le);var uu="0.5.10",du=Object.defineProperty,hu=(s,e,t)=>e in s?du(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,zi=(s,e,t)=>(hu(s,typeof e!="symbol"?e+"":e,t),t),bs=class extends Error{constructor(e,t){super(e),this.error=e,this.status_code=t,this.name="ResponseError",Error.captureStackTrace&&Error.captureStackTrace(this,bs)}},Ji=class{constructor(e,t,r){zi(this,"abortController"),zi(this,"itr"),zi(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.")}},wn=async s=>{var r;if(s.ok)return;let e=`Error ${s.status}: ${s.statusText}`,t=null;if((r=s.headers.get("content-type"))!=null&&r.includes("application/json"))try{t=await s.json(),e=t.error||e}catch(n){console.log("Failed to parse error response as JSON")}else try{console.log("Getting text from response"),e=await s.text()||e}catch(n){console.log("Failed to get text from error response")}throw new bs(e,s.status)};function fu(){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 _n=async(s,e,t={})=>{let r={"Content-Type":"application/json",Accept:"application/json","User-Agent":`ollama-js/${uu} (${fu()})`};t.headers||(t.headers={});let n=Object.fromEntries(Object.entries(t.headers).filter(([i])=>!Object.keys(r).some(o=>o.toLowerCase()===i.toLowerCase())));return t.headers={...r,...n},s(e,t)},ka=async(s,e,t)=>{let r=await _n(s,e,{headers:t==null?void 0:t.headers});return await wn(r),r},Ma=async(s,e)=>{let t=await _n(s,e,{method:"HEAD"});return await wn(t),t},mt=async(s,e,t,r)=>{let i=(a=>a!==null&&typeof a=="object"&&!Array.isArray(a))(t)?JSON.stringify(t):t,o=await _n(s,e,{method:"POST",body:i,signal:r==null?void 0:r.signal,headers:r==null?void 0:r.headers});return await wn(o),o},mu=async(s,e,t,r)=>{let n=await _n(s,e,{method:"DELETE",body:JSON.stringify(t),headers:r==null?void 0:r.headers});return await wn(n),n},pu=async function*(s){var n;let e=new TextDecoder("utf-8"),t="",r=s.getReader();for(;;){let{done:i,value:o}=await r.read();if(i)break;t+=e.decode(o);let a=t.split(`
`);t=(n=a.pop())!=null?n:"";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)}},gu=s=>{if(!s)return"http://127.0.0.1:11434";let e=s.includes("://");s.startsWith(":")&&(s=`http://127.0.0.1${s}`,e=!0),e||(s=`http://${s}`);let t=new URL(s),r=t.port;r||(e?r=t.protocol==="https:"?"443":"80":r="11434");let n=`${t.protocol}//${t.hostname}:${r}${t.pathname}`;return n.endsWith("/")&&(n=n.slice(0,-1)),n},yu=Object.defineProperty,bu=(s,e,t)=>e in s?yu(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ki=(s,e,t)=>(bu(s,typeof e!="symbol"?e+"":e,t),t),Xi=class{constructor(e){var t,r;Ki(this,"config"),Ki(this,"fetch"),Ki(this,"ongoingStreamedRequests",[]),this.config={host:"",headers:e==null?void 0:e.headers},e!=null&&e.proxy||(this.config.host=gu((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 mt(this.fetch,r,t,{signal:o.signal,headers:this.config.headers});if(!a.body)throw new Error("Missing body");let c=pu(a.body),l=new Ji(o,c,()=>{let u=this.ongoingStreamedRequests.indexOf(l);u>-1&&this.ongoingStreamedRequests.splice(u,1)});return this.ongoingStreamedRequests.push(l),l}return await(await mt(this.fetch,r,t,{headers:this.config.headers})).json()}async encodeImage(e){if(typeof e!="string"){let t=new Uint8Array(e),r="",n=t.byteLength;for(let i=0;i<n;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 mu(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:"success"}}async copy(e){return await mt(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:"success"}}async list(){return await(await ka(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await mt(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await mt(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await mt(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await ka(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}},jp=new Xi;var pt=Wc(require("fs"),1),Vt=require("path"),Ta=require("crypto"),Oa=require("os");var ws=class extends Xi{async encodeImage(e){if(typeof e!="string")return Buffer.from(e).toString("base64");try{if(pt.default.existsSync(e)){let t=await pt.promises.readFile((0,Vt.resolve)(e));return Buffer.from(t).toString("base64")}}catch(t){}return e}async parseModelfile(e,t=process.cwd()){let r=[],n=e.split(`
`);for(let i of n){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,Vt.join)((0,Oa.homedir)(),e.slice(1)):(0,Vt.resolve)(t,e)}async fileExists(e){try{return await pt.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,pt.createReadStream)(e),n=`sha256:${await new Promise((i,o)=>{let a=(0,Ta.createHash)("sha256");t.on("data",c=>a.update(c)),t.on("end",()=>i(a.digest("hex"))),t.on("error",o)})}`;try{await Ma(this.fetch,`${this.config.host}/api/blobs/${n}`)}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 mt(this.fetch,`${this.config.host}/api/blobs/${n}`,o)}else throw i}return n}async create(e){let t="";if(e.path)t=await pt.promises.readFile(e.path,{encoding:"utf8"}),t=await this.parseModelfile(t,(0,Vt.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)}},Vp=new ws;var wu=2.5,xn=2048,Fa=2048,_u=1.2,_s=class{constructor(e){this.settings=e;this.modelInfoCache=new Map,this.fetchSelector=new ft(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 ws(r)}getDefaultModelInfo(){return{contextLength:0,lastContextLength:xn}}async getCachedModelInfo(e,t){let r=`${e.url}_${t}`,n=this.modelInfoCache.get(r);if(n)return n;let i=this.getClient(e,this.settings.useNativeFetch?fetch:he);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(([u,h])=>(u.endsWith(".context_length")||u==="num_ctx")&&typeof h=="number"&&h>0);return l&&typeof l[1]=="number"&&(c.contextLength=l[1]),this.modelInfoCache.set(r,c),c}catch(o){return b.error("Failed to fetch model info:",o),this.getDefaultModelInfo()}}setModelInfoLastContextLength(e,t,r){let n=`${e.url}_${t}`,i=this.modelInfoCache.get(n);i&&this.modelInfoCache.set(n,{...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)},n=await this.fetchSelector.request(e,r);if(t!=null&&t.signal.aborted)throw new Error("Aborted");return n}optimizeContext(e,t,r,n){let i=Math.ceil(e/wu);if(i<=t)return{num_ctx:t>r?t:void 0,shouldUpdate:!1};let o=Math.min(Math.ceil(Math.max(i,r)*_u),n),a=o>t;return{num_ctx:o,shouldUpdate:a}}prepareChatMessages(e){var n;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}),(n=e.images)!=null&&n.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,n){var m,f;let i=await this.getCachedModelInfo(e.provider,e.provider.model||"").catch(p=>(b.error("Failed to get model info:",p),null)),{chatMessages:o,extractedImages:a}=this.prepareChatMessages(e),c=a.length>0?a.map(p=>p.replace(/^data:image\/(.*?);base64,/,"")):void 0,l={};if(!(c!=null&&c.length)){let p=o.reduce((C,_)=>C+_.content.length,0),{num_ctx:y,shouldUpdate:g}=this.optimizeContext(p,(i==null?void 0:i.lastContextLength)||xn,xn,(i==null?void 0:i.contextLength)||xn);y&&(l.num_ctx=y),g&&this.setModelInfoLastContextLength(e.provider,e.provider.model||"",y)}if(e.options&&Object.assign(l,e.options),c!=null&&c.length){let p=o.map(y=>y.role).lastIndexOf("user");p!==-1?o[p]={...o[p],images:c}:o.length>0?o[o.length-1]={...o[o.length-1],images:c}:o.push({role:"user",content:"",images:c})}b.debug("Sending chat request to Ollama");let u=await t.chat({model:e.provider.model||"",messages:o,stream:!0,options:{...l}}),h="";for await(let p of u){if(n!=null&&n.signal.aborted)throw new Error("Aborted");let y=(m=p.message)==null?void 0:m.content;y&&(h+=y,r&&r(y,h)),p.done&&p.total_duration>0&&this.setModelInfoLastContextLength(e.provider,e.provider.model||"",(f=p.context)==null?void 0:f.length)}return h}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 n=await this.getCachedModelInfo(e.provider,e.provider.model||""),i=Array.isArray(t)?Math.max(...t.map(u=>u.length)):t.length,{num_ctx:o,shouldUpdate:a}=this.optimizeContext(i,n.lastContextLength||Fa,Fa,n.contextLength);a&&this.setModelInfoLastContextLength(e.provider,e.provider.model||"",o);let c=async u=>{let h=this.getClient(e.provider,u);r==null||r.signal.addEventListener("abort",()=>{h.abort()});let m=Array.isArray(t)?t:[t],f=[],p=[];for(let y of m){if(r!=null&&r.signal.aborted)throw new Error("Aborted");let g=await h.embed({model:e.provider.model||"",input:y,options:{num_ctx:o}});if(f.push(g.embeddings[0]),b.debug("Embed response:",g),p.push(y),e.onProgress&&e.onProgress([...p]),r!=null&&r.signal.aborted)throw new Error("Aborted")}return f};return this.fetchSelector.request(e.provider,c)}async execute(e){let t=e,r=t.abortController,n=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(n&&n(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 Yi=(s,e)=>e.some(t=>s instanceof t),Na,Ba;function xu(){return Na||(Na=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Pu(){return Ba||(Ba=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var Zi=new WeakMap,Gi=new WeakMap,Pn=new WeakMap;function Au(s){let e=new Promise((t,r)=>{let n=()=>{s.removeEventListener("success",i),s.removeEventListener("error",o)},i=()=>{t(zt(s.result)),n()},o=()=>{r(s.error),n()};s.addEventListener("success",i),s.addEventListener("error",o)});return Pn.set(e,s),e}function vu(s){if(Zi.has(s))return;let e=new Promise((t,r)=>{let n=()=>{s.removeEventListener("complete",i),s.removeEventListener("error",o),s.removeEventListener("abort",o)},i=()=>{t(),n()},o=()=>{r(s.error||new DOMException("AbortError","AbortError")),n()};s.addEventListener("complete",i),s.addEventListener("error",o),s.addEventListener("abort",o)});Zi.set(s,e)}var eo={get(s,e,t){if(s instanceof IDBTransaction){if(e==="done")return Zi.get(s);if(e==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return zt(s[e])},set(s,e,t){return s[e]=t,!0},has(s,e){return s instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in s}};function Ua(s){eo=s(eo)}function Iu(s){return Pu().includes(s)?function(...e){return s.apply(to(this),e),zt(this.request)}:function(...e){return zt(s.apply(to(this),e))}}function Eu(s){return typeof s=="function"?Iu(s):(s instanceof IDBTransaction&&vu(s),Yi(s,xu())?new Proxy(s,eo):s)}function zt(s){if(s instanceof IDBRequest)return Au(s);if(Gi.has(s))return Gi.get(s);let e=Eu(s);return e!==s&&(Gi.set(s,e),Pn.set(e,s)),e}var to=s=>Pn.get(s);function ja(s,e,{blocked:t,upgrade:r,blocking:n,terminated:i}={}){let o=indexedDB.open(s,e),a=zt(o);return r&&o.addEventListener("upgradeneeded",c=>{r(zt(o.result),c.oldVersion,c.newVersion,zt(o.transaction),c)}),t&&o.addEventListener("blocked",c=>t(c.oldVersion,c.newVersion,c)),a.then(c=>{i&&c.addEventListener("close",()=>i()),n&&c.addEventListener("versionchange",l=>n(l.oldVersion,l.newVersion,l))}).catch(()=>{}),a}var Su=["get","getKey","getAll","getAllKeys","count"],Ru=["put","add","delete","clear"],Qi=new Map;function Da(s,e){if(!(s instanceof IDBDatabase&&!(e in s)&&typeof e=="string"))return;if(Qi.get(e))return Qi.get(e);let t=e.replace(/FromIndex$/,""),r=e!==t,n=Ru.includes(t);if(!(t in(r?IDBIndex:IDBObjectStore).prototype)||!(n||Su.includes(t)))return;let i=async function(o,...a){let c=this.transaction(o,n?"readwrite":"readonly"),l=c.store;return r&&(l=l.index(a.shift())),(await Promise.all([l[t](...a),n&&c.done]))[0]};return Qi.set(e,i),i}Ua(s=>({...s,get:(e,t,r)=>Da(e,t)||s.get(e,t,r),has:(e,t)=>!!Da(e,t)||s.has(e,t)}));var Cu=["continue","continuePrimaryKey","advance"],$a={},ro=new WeakMap,qa=new WeakMap,ku={get(s,e){if(!Cu.includes(e))return s[e];let t=$a[e];return t||(t=$a[e]=function(...r){ro.set(this,qa.get(this)[e](...r))}),t}};async function*Mu(...s){let e=this;if(e instanceof IDBCursor||(e=await e.openCursor(...s)),!e)return;e=e;let t=new Proxy(e,ku);for(qa.set(t,e),Pn.set(t,to(e));e;)yield t,e=await(ro.get(t)||e.continue()),ro.delete(t)}function La(s,e){return e===Symbol.asyncIterator&&Yi(s,[IDBIndex,IDBObjectStore,IDBCursor])||e==="iterate"&&Yi(s,[IDBIndex,IDBObjectStore])}Ua(s=>({...s,get(e,t,r){return La(e,t)?Mu:s.get(e,t,r)},has(e,t){return La(e,t)||s.has(e,t)}}));async function Tu(s,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(s),n=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).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 Ha=s=>Tu(s,16);var gt=class{constructor(){this.db=null;this.vaultId="";this.dbName=""}static getInstance(){return gt.instance||(gt.instance=new gt),gt.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 Ha("ai-providers-plugin");this.dbName=`aiProviders_${t}_${this.vaultId}`,this.db=await ja(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}},Kt=gt.getInstance();var An=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:n}=e,i=await this.loadCachedChunks(e,r),o=n.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,n),n.map(c=>i.get(c))}async embedAndCacheChunks(e,t,r,n){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(n,e.provider,r)}async loadCachedChunks(e,t){let r=await Kt.getEmbeddings(t).catch(n=>(b.error("Error reading from embeddings cache:",n),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(n=>[n.content,n.embedding])):new Map}async saveCachedChunks(e,t,r){if(!t.model)return;let n=Array.from(r,([i,o])=>({content:i,embedding:o}));await Kt.setEmbeddings(e,{providerId:t.id,providerModel:t.model,chunks:n}).catch(i=>{b.error("Error writing to embeddings cache:",i)})}async generateCacheKey(e){return`embed:${e.provider.id}:${e.provider.model}`}};var xs=1e3;function Wa(s){return b.debug("Preprocessing content",{contentLength:s.length}),s.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 Va(s){return s.length<xs?[s.trim()]:(b.debug("Splitting content",{contentLength:s.length}),s.split(/^---$/m).flatMap(t=>Ou(t.trim())).flatMap(t=>Fu(t)).map(t=>t.trim()).filter(t=>t.length>0))}function Ou(s){let e=/^(#{1,6})\s+(.+)$/gm,t=[],r=0,n="",i;for(;(i=e.exec(s))!==null;)r<i.index&&t.push(n+s.slice(r,i.index).trim()),n=i[0]+`
`,r=e.lastIndex;return r<s.length&&t.push(n+s.slice(r).trim()),t.filter(o=>o.length>0)}function Fu(s){let t=s.split(`
`).reduce(Nu,{chunks:[],currentChunk:"",inList:!1,lastNonListText:""}),r=t.currentChunk?[...t.chunks,t.currentChunk.trim()]:t.chunks.map(i=>i.trim()),n=[];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];n.push(o+`
`+c),i++}else n.push(o)}return n}function Nu(s,e){let t=/^(\s*[-*+]|\s*\d+\.)/.test(e);return/^(#{1,6}\s|[*_]{2}).+/.test(e)?Bu(s,e):t?Du(s,e):s.inList&&!e.trim()?{...s,currentChunk:s.currentChunk+`
`+e}:$u(s,e)}function Bu(s,e){let{chunks:t,currentChunk:r}=s;return{chunks:r?[...t,r.trim()]:t,currentChunk:e,inList:!1,lastNonListText:e}}function Du(s,e){let{chunks:t,currentChunk:r,inList:n,lastNonListText:i}=s;return!n&&r.length+e.length<=xs?{...s,currentChunk:r+`
`+e,inList:!0}:n?{...s,currentChunk:r+`
`+e}:{chunks:r?[...t,r.trim()]:t,currentChunk:i+`
`+e,inList:!0,lastNonListText:i}}function $u(s,e){let{chunks:t,currentChunk:r,lastNonListText:n}=s;if(e.length>xs){let o=e,a=[...t];for(r&&a.push(r.trim());o.length>0;){let c=Lu(o,xs);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>xs?{chunks:[...t,r.trim()],currentChunk:e,inList:!1,lastNonListText:e.trim()?e:n}:{...s,currentChunk:i,inList:!1,lastNonListText:e.trim()?e:n}}function Lu(s,e){if(s.length<=e)return s.length;let t=e;for(;t>0&&!/\s/.test(s[t]);)t--;return t>0?t:e}function w(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t}function d(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)}var so=function(){let{crypto:s}=globalThis;if(s!=null&&s.randomUUID)return so=s.randomUUID.bind(s),s.randomUUID();let e=new Uint8Array(1),t=s?()=>s.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};function Xe(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}var Ps=s=>{if(s instanceof Error)return s;if(typeof s=="object"&&s!==null){try{if(Object.prototype.toString.call(s)==="[object Error]"){let e=new Error(s.message,s.cause?{cause:s.cause}:{});return s.stack&&(e.stack=s.stack),s.cause&&!e.cause&&(e.cause=s.cause),s.name&&(e.name=s.name),e}}catch(e){}try{return new Error(JSON.stringify(s))}catch(e){}}return new Error(s)};var P=class extends Error{},K=class extends P{constructor(e,t,r,n){super(`${K.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.requestID=n==null?void 0:n.get("request-id"),this.error=t}static makeMessage(e,t,r){let n=t!=null&&t.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e||!n)return new yt({message:r,cause:Ps(t)});let i=t;return e===400?new kr(e,i,r,n):e===401?new Mr(e,i,r,n):e===403?new Tr(e,i,r,n):e===404?new Or(e,i,r,n):e===409?new Fr(e,i,r,n):e===422?new Nr(e,i,r,n):e===429?new Br(e,i,r,n):e>=500?new Dr(e,i,r,n):new K(e,i,r,n)}},se=class extends K{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},yt=class extends K{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},Cr=class extends yt{constructor({message:e}={}){super({message:e!=null?e:"Request timed out."})}},kr=class extends K{},Mr=class extends K{},Tr=class extends K{},Or=class extends K{},Fr=class extends K{},Nr=class extends K{},Br=class extends K{},Dr=class extends K{};var ju=/^[a-z][a-z0-9+.-]*:/i,za=s=>ju.test(s),no=s=>(no=Array.isArray,no(s)),io=no;function vn(s){return typeof s!="object"?{}:s!=null?s:{}}function Ka(s){if(!s)return!0;for(let e in s)return!1;return!0}function Ja(s,e){return Object.prototype.hasOwnProperty.call(s,e)}var Xa=(s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new P(`${s} must be an integer`);if(e<0)throw new P(`${s} must be a positive integer`);return e};var In=s=>{try{return JSON.parse(s)}catch(e){return}};var Ga=s=>new Promise(e=>setTimeout(e,s));var bt="0.71.0";var Za=()=>typeof window!="undefined"&&typeof window.document!="undefined"&&typeof navigator!="undefined";function qu(){return typeof Deno!="undefined"&&Deno.build!=null?"deno":typeof EdgeRuntime!="undefined"?"edge":Object.prototype.toString.call(typeof globalThis.process!="undefined"?globalThis.process:0)==="[object process]"?"node":"unknown"}var Hu=()=>{var t,r,n,i,o;let s=qu();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":bt,"X-Stainless-OS":Ya(Deno.build.os),"X-Stainless-Arch":Qa(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:(r=(t=Deno.version)==null?void 0:t.deno)!=null?r:"unknown"};if(typeof EdgeRuntime!="undefined")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":bt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(s==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":bt,"X-Stainless-OS":Ya((n=globalThis.process.platform)!=null?n:"unknown"),"X-Stainless-Arch":Qa((i=globalThis.process.arch)!=null?i:"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":(o=globalThis.process.version)!=null?o:"unknown"};let e=Wu();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":bt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":bt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Wu(){if(typeof navigator=="undefined"||!navigator)return null;let s=[{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 s){let r=t.exec(navigator.userAgent);if(r){let n=r[1]||0,i=r[2]||0,o=r[3]||0;return{browser:e,version:`${n}.${i}.${o}`}}}return null}var Qa=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",Ya=s=>(s=s.toLowerCase(),s.includes("ios")?"iOS":s==="android"?"Android":s==="darwin"?"MacOS":s==="win32"?"Windows":s==="freebsd"?"FreeBSD":s==="openbsd"?"OpenBSD":s==="linux"?"Linux":s?`Other:${s}`:"Unknown"),En,ec=()=>En!=null?En:En=Hu();function tc(){if(typeof fetch!="undefined")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function oo(...s){let e=globalThis.ReadableStream;if(typeof e=="undefined")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...s)}function Sn(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return oo({start(){},async pull(t){let{done:r,value:n}=await e.next();r?t.close():t.enqueue(n)},async cancel(){var t;await((t=e.return)==null?void 0:t.call(e))}})}function As(s){if(s[Symbol.asyncIterator])return s;let e=s.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}}}async function rc(s){var r,n;if(s===null||typeof s!="object")return;if(s[Symbol.asyncIterator]){await((n=(r=s[Symbol.asyncIterator]()).return)==null?void 0:n.call(r));return}let e=s.getReader(),t=e.cancel();e.releaseLock(),await t}var sc=({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});function nc(s){let e=0;for(let n of s)e+=n.length;let t=new Uint8Array(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return t}var Rn;function vs(s){let e;return(Rn!=null?Rn:(e=new globalThis.TextEncoder,Rn=e.encode.bind(e)))(s)}var Cn;function ao(s){let e;return(Cn!=null?Cn:(e=new globalThis.TextDecoder,Cn=e.decode.bind(e)))(s)}var ge,ye,Ge=class{constructor(){ge.set(this,void 0),ye.set(this,void 0),w(this,ge,new Uint8Array,"f"),w(this,ye,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?vs(e):e;w(this,ge,nc([d(this,ge,"f"),t]),"f");let r=[],n;for(;(n=Ku(d(this,ge,"f"),d(this,ye,"f")))!=null;){if(n.carriage&&d(this,ye,"f")==null){w(this,ye,n.index,"f");continue}if(d(this,ye,"f")!=null&&(n.index!==d(this,ye,"f")+1||n.carriage)){r.push(ao(d(this,ge,"f").subarray(0,d(this,ye,"f")-1))),w(this,ge,d(this,ge,"f").subarray(d(this,ye,"f")),"f"),w(this,ye,null,"f");continue}let i=d(this,ye,"f")!==null?n.preceding-1:n.preceding,o=ao(d(this,ge,"f").subarray(0,i));r.push(o),w(this,ge,d(this,ge,"f").subarray(n.index),"f"),w(this,ye,null,"f")}return r}flush(){return d(this,ge,"f").length?this.decode(`
`):[]}};ge=new WeakMap,ye=new WeakMap;Ge.NEWLINE_CHARS=new Set([`
`,"\r"]);Ge.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Ku(s,e){for(let n=e!=null?e:0;n<s.length;n++){if(s[n]===10)return{preceding:n,index:n+1,carriage:!1};if(s[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function ic(s){for(let r=0;r<s.length-1;r++){if(s[r]===10&&s[r+1]===10||s[r]===13&&s[r+1]===13)return r+2;if(s[r]===13&&s[r+1]===10&&r+3<s.length&&s[r+2]===13&&s[r+3]===10)return r+4}return-1}var Mn={off:0,error:200,warn:300,info:400,debug:500},co=(s,e,t)=>{if(s){if(Ja(Mn,s))return s;ee(t).warn(`${e} was set to ${JSON.stringify(s)}, expected one of ${JSON.stringify(Object.keys(Mn))}`)}};function Is(){}function kn(s,e,t){return!e||Mn[s]>Mn[t]?Is:e[s].bind(e)}var Ju={error:Is,warn:Is,info:Is,debug:Is},oc=new WeakMap;function ee(s){var i;let e=s.logger,t=(i=s.logLevel)!=null?i:"off";if(!e)return Ju;let r=oc.get(e);if(r&&r[0]===t)return r[1];let n={error:kn("error",e,t),warn:kn("warn",e,t),info:kn("info",e,t),debug:kn("debug",e,t)};return oc.set(e,[t,n]),n}var Qe=s=>(s.options&&(s.options={...s.options},delete s.options.headers),s.headers&&(s.headers=Object.fromEntries((s.headers instanceof Headers?[...s.headers]:Object.entries(s.headers)).map(([e,t])=>[e,e.toLowerCase()==="x-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in s&&(s.retryOfRequestLogID&&(s.retryOf=s.retryOfRequestLogID),delete s.retryOfRequestLogID),s);var Es,ce=class{constructor(e,t,r){this.iterator=e,Es.set(this,void 0),this.controller=t,w(this,Es,r,"f")}static fromSSEResponse(e,t,r){let n=!1,i=r?ee(r):console;async function*o(){var c;if(n)throw new P("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let a=!1;try{for await(let l of Xu(e,t)){if(l.event==="completion")try{yield JSON.parse(l.data)}catch(u){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),u}if(l.event==="message_start"||l.event==="message_delta"||l.event==="message_stop"||l.event==="content_block_start"||l.event==="content_block_delta"||l.event==="content_block_stop")try{yield JSON.parse(l.data)}catch(u){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),u}if(l.event!=="ping"&&l.event==="error")throw new K(void 0,(c=In(l.data))!=null?c:l.data,void 0,e.headers)}a=!0}catch(l){if(Xe(l))return;throw l}finally{a||t.abort()}}return new ce(o,t,r)}static fromReadableStream(e,t,r){let n=!1;async function*i(){let a=new Ge,c=As(e);for await(let l of c)for(let u of a.decode(l))yield u;for(let l of a.flush())yield l}async function*o(){if(n)throw new P("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let a=!1;try{for await(let c of i())a||c&&(yield JSON.parse(c));a=!0}catch(c){if(Xe(c))return;throw c}finally{a||t.abort()}}return new ce(o,t,r)}[(Es=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),n=i=>({next:()=>{if(i.length===0){let o=r.next();e.push(o),t.push(o)}return i.shift()}});return[new ce(()=>n(e),this.controller,d(this,Es,"f")),new ce(()=>n(t),this.controller,d(this,Es,"f"))]}toReadableStream(){let e=this,t;return oo({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:n,done:i}=await t.next();if(i)return r.close();let o=vs(JSON.stringify(n)+`
`);r.enqueue(o)}catch(n){r.error(n)}},async cancel(){var r;await((r=t.return)==null?void 0:r.call(t))}})}};async function*Xu(s,e){if(!s.body)throw e.abort(),typeof globalThis.navigator!="undefined"&&globalThis.navigator.product==="ReactNative"?new P("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new P("Attempted to iterate over a response with no body");let t=new lo,r=new Ge,n=As(s.body);for await(let i of Gu(n))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*Gu(s){let e=new Uint8Array;for await(let t of s){if(t==null)continue;let r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?vs(t):t,n=new Uint8Array(e.length+r.length);n.set(e),n.set(r,e.length),e=n;let i;for(;(i=ic(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}var lo=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,n]=Qu(e,":");return n.startsWith(" ")&&(n=n.substring(1)),t==="event"?this.event=n:t==="data"&&this.data.push(n),null}};function Qu(s,e){let t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}async function Tn(s,e){let{response:t,requestLogID:r,retryOfRequestLogID:n,startTime:i}=e,o=await(async()=>{var h;if(e.options.stream)return ee(s).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):ce.fromSSEResponse(t,e.controller);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let a=t.headers.get("content-type"),c=(h=a==null?void 0:a.split(";")[0])==null?void 0:h.trim();if((c==null?void 0:c.includes("application/json"))||(c==null?void 0:c.endsWith("+json"))){let m=await t.json();return uo(m,t)}return await t.text()})();return ee(s).debug(`[${r}] response parsed`,Qe({retryOfRequestLogID:n,url:t.url,status:t.status,body:o,durationMs:Date.now()-i})),o}function uo(s,e){return!s||typeof s!="object"||Array.isArray(s)?s:Object.defineProperty(s,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var Ss,Ye=class extends Promise{constructor(e,t,r=Tn){super(n=>{n(null)}),this.responsePromise=t,this.parseResponse=r,Ss.set(this,void 0),w(this,Ss,e,"f")}_thenUnwrap(e){return new Ye(d(this,Ss,"f"),this.responsePromise,async(t,r)=>uo(e(await this.parseResponse(t,r),r),r.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("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(d(this,Ss,"f"),e))),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)}};Ss=new WeakMap;var On,Fn=class{constructor(e,t,r,n){On.set(this,void 0),w(this,On,e,"f"),this.options=n,this.response=t,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new P("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await d(this,On,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(On=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Rs=class extends Ye{constructor(e,t,r){super(e,t,async(n,i)=>new r(n,i.response,await Tn(n,i),i.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},Pe=class extends Fn{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.first_id=r.first_id||null,this.last_id=r.last_id||null}getPaginatedItems(){var e;return(e=this.data)!=null?e:[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){var t;if((t=this.options.query)!=null&&t.before_id){let r=this.first_id;return r?{...this.options,query:{...vn(this.options.query),before_id:r}}:null}let e=this.last_id;return e?{...this.options,query:{...vn(this.options.query),after_id:e}}:null}};var $r=class extends Fn{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.next_page=r.next_page||null}getPaginatedItems(){var e;return(e=this.data)!=null?e:[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.next_page;return e?{...this.options,query:{...vn(this.options.query),page:e}}:null}};var fo=()=>{var s;if(typeof File=="undefined"){let{process:e}=globalThis,t=typeof((s=e==null?void 0:e.versions)==null?void 0:s.node)=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Jt(s,e,t){return fo(),new File(s,e!=null?e:"unknown_file",t)}function Cs(s){return(typeof s=="object"&&s!==null&&("name"in s&&s.name&&String(s.name)||"url"in s&&s.url&&String(s.url)||"filename"in s&&s.filename&&String(s.filename)||"path"in s&&s.path&&String(s.path))||"").split(/[\\/]/).pop()||void 0}var mo=s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function";var Lr=async(s,e)=>({...s,body:await ed(s.body,e)}),ac=new WeakMap;function Zu(s){let e=typeof s=="function"?s:s.fetch,t=ac.get(e);if(t)return t;let r=(async()=>{try{let n="Response"in e?e.Response:(await e("data:,")).constructor,i=new FormData;return i.toString()!==await new n(i).text()}catch(n){return!0}})();return ac.set(e,r),r}var ed=async(s,e)=>{if(!await Zu(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let t=new FormData;return await Promise.all(Object.entries(s||{}).map(([r,n])=>ho(t,r,n))),t},td=s=>s instanceof Blob&&"name"in s;var ho=async(s,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")s.append(e,String(t));else if(t instanceof Response){let r={},n=t.headers.get("Content-Type");n&&(r={type:n}),s.append(e,Jt([await t.blob()],Cs(t),r))}else if(mo(t))s.append(e,Jt([await new Response(Sn(t)).blob()],Cs(t)));else if(td(t))s.append(e,Jt([t],Cs(t),{type:t.type}));else if(Array.isArray(t))await Promise.all(t.map(r=>ho(s,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,n])=>ho(s,`${e}[${r}]`,n)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var cc=s=>s!=null&&typeof s=="object"&&typeof s.size=="number"&&typeof s.type=="string"&&typeof s.text=="function"&&typeof s.slice=="function"&&typeof s.arrayBuffer=="function",rd=s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&cc(s),sd=s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function";async function Nn(s,e,t){if(fo(),s=await s,e||(e=Cs(s)),rd(s))return s instanceof File&&e==null&&t==null?s:Jt([await s.arrayBuffer()],e!=null?e:s.name,{type:s.type,lastModified:s.lastModified,...t});if(sd(s)){let n=await s.blob();return e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()),Jt(await po(n),e,t)}let r=await po(s);if(!(t!=null&&t.type)){let n=r.find(i=>typeof i=="object"&&"type"in i&&i.type);typeof n=="string"&&(t={...t,type:n})}return Jt(r,e,t)}async function po(s){var t;let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(cc(s))e.push(s instanceof Blob?s:await s.arrayBuffer());else if(mo(s))for await(let r of s)e.push(...await po(r));else{let r=(t=s==null?void 0:s.constructor)==null?void 0:t.name;throw new Error(`Unexpected data type: ${typeof s}${r?`; constructor: ${r}`:""}${nd(s)}`)}return e}function nd(s){return typeof s!="object"||s===null?"":`; props: [${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}var j=class{constructor(e){this._client=e}};var lc=Symbol.for("brand.privateNullableHeaders");function*od(s){if(!s)return;if(lc in s){let{values:r,nulls:n}=s;yield*r.entries();for(let i of n)yield[i,null];return}let e=!1,t;s instanceof Headers?t=s.entries():io(s)?t=s:(e=!0,t=Object.entries(s!=null?s:{}));for(let r of t){let n=r[0];if(typeof n!="string")throw new TypeError("expected header name to be a string");let i=io(r[1])?r[1]:[r[1]],o=!1;for(let a of i)a!==void 0&&(e&&!o&&(o=!0,yield[n,null]),yield[n,a])}}var S=s=>{let e=new Headers,t=new Set;for(let r of s){let n=new Set;for(let[i,o]of od(r)){let a=i.toLowerCase();n.has(a)||(e.delete(i),n.add(a)),o===null?(e.delete(i),t.add(a)):(e.append(i,o),t.delete(a))}}return{[lc]:!0,values:e,nulls:t}};function dc(s){return s.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var uc=Object.freeze(Object.create(null)),ad=(s=dc)=>function(t,...r){if(t.length===1)return t[0];let n=!1,i=[],o=t.reduce((u,h,m)=>{var y,g,C;/[?#]/.test(h)&&(n=!0);let f=r[m],p=(n?encodeURIComponent:s)(""+f);return m!==r.length&&(f==null||typeof f=="object"&&f.toString===((C=Object.getPrototypeOf((g=Object.getPrototypeOf((y=f.hasOwnProperty)!=null?y:uc))!=null?g:uc))==null?void 0:C.toString))&&(p=f+"",i.push({start:u.length+h.length,length:p.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),u+h+(m===r.length?"":p)},""),a=o.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=c.exec(a))!==null;)i.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(i.sort((u,h)=>u.start-h.start),i.length>0){let u=0,h=i.reduce((m,f)=>{let p=" ".repeat(f.start-u),y="^".repeat(f.length);return u=f.start+f.length,m+p+y},"");throw new P(`Path parameters result in path with invalid segments:
${i.map(m=>m.error).join(`
`)}
${o}
${h}`)}return o},q=ad(dc);var Ur=class extends j{list(e={},t){let{betas:r,...n}=e!=null?e:{};return this._client.getAPIList("/v1/files",Pe,{query:n,...t,headers:S([{"anthropic-beta":[...r!=null?r:[],"files-api-2025-04-14"].toString()},t==null?void 0:t.headers])})}delete(e,t={},r){let{betas:n}=t!=null?t:{};return this._client.delete(q`/v1/files/${e}`,{...r,headers:S([{"anthropic-beta":[...n!=null?n:[],"files-api-2025-04-14"].toString()},r==null?void 0:r.headers])})}download(e,t={},r){let{betas:n}=t!=null?t:{};return this._client.get(q`/v1/files/${e}/content`,{...r,headers:S([{"anthropic-beta":[...n!=null?n:[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},r==null?void 0:r.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},r){let{betas:n}=t!=null?t:{};return this._client.get(q`/v1/files/${e}`,{...r,headers:S([{"anthropic-beta":[...n!=null?n:[],"files-api-2025-04-14"].toString()},r==null?void 0:r.headers])})}upload(e,t){let{betas:r,...n}=e;return this._client.post("/v1/files",Lr({body:n,...t,headers:S([{"anthropic-beta":[...r!=null?r:[],"files-api-2025-04-14"].toString()},t==null?void 0:t.headers])},this._client))}};var jr=class extends j{retrieve(e,t={},r){let{betas:n}=t!=null?t:{};return this._client.get(q`/v1/models/${e}?beta=true`,{...r,headers:S([{...(n==null?void 0:n.toString())!=null?{"anthropic-beta":n==null?void 0:n.toString()}:void 0},r==null?void 0:r.headers])})}list(e={},t){let{betas:r,...n}=e!=null?e:{};return this._client.getAPIList("/v1/models?beta=true",Pe,{query:n,...t,headers:S([{...(r==null?void 0:r.toString())!=null?{"anthropic-beta":r==null?void 0:r.toString()}:void 0},t==null?void 0:t.headers])})}};var Bn={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function go(s,e){var t;return!e||!("parse"in((t=e.output_format)!=null?t:{}))?{...s,content:s.content.map(r=>r.type==="text"?{...r,parsed:null}:r),parsed_output:null}:yo(s,e)}function yo(s,e){let t=null,r=s.content.map(n=>{if(n.type==="text"){let i=ud(e,n.text);return t===null&&(t=i),{...n,parsed:i}}return n});return{...s,content:r,parsed_output:t}}function ud(s,e){var t;if(((t=s.output_format)==null?void 0:t.type)!=="json_schema")return null;try{return"parse"in s.output_format?s.output_format.parse(e):JSON.parse(e)}catch(r){throw new P(`Failed to parse structured output: ${r}`)}}var dd=s=>{let e=0,t=[];for(;e<s.length;){let r=s[e];if(r==="\\"){e++;continue}if(r==="{"){t.push({type:"brace",value:"{"}),e++;continue}if(r==="}"){t.push({type:"brace",value:"}"}),e++;continue}if(r==="["){t.push({type:"paren",value:"["}),e++;continue}if(r==="]"){t.push({type:"paren",value:"]"}),e++;continue}if(r===":"){t.push({type:"separator",value:":"}),e++;continue}if(r===","){t.push({type:"delimiter",value:","}),e++;continue}if(r==='"'){let a="",c=!1;for(r=s[++e];r!=='"';){if(e===s.length){c=!0;break}if(r==="\\"){if(e++,e===s.length){c=!0;break}a+=r+s[e],r=s[++e]}else a+=r,r=s[++e]}r=s[++e],c||t.push({type:"string",value:a});continue}if(r&&/\s/.test(r)){e++;continue}let i=/[0-9]/;if(r&&i.test(r)||r==="-"||r==="."){let a="";for(r==="-"&&(a+=r,r=s[++e]);r&&i.test(r)||r===".";)a+=r,r=s[++e];t.push({type:"number",value:a});continue}let o=/[a-z]/i;if(r&&o.test(r)){let a="";for(;r&&o.test(r)&&e!==s.length;)a+=r,r=s[++e];if(a=="true"||a=="false"||a==="null")t.push({type:"name",value:a});else{e++;continue}continue}e++}return t},qr=s=>{if(s.length===0)return s;let e=s[s.length-1];switch(e.type){case"separator":return s=s.slice(0,s.length-1),qr(s);break;case"number":let t=e.value[e.value.length-1];if(t==="."||t==="-")return s=s.slice(0,s.length-1),qr(s);case"string":let r=s[s.length-2];if((r==null?void 0:r.type)==="delimiter")return s=s.slice(0,s.length-1),qr(s);if((r==null?void 0:r.type)==="brace"&&r.value==="{")return s=s.slice(0,s.length-1),qr(s);break;case"delimiter":return s=s.slice(0,s.length-1),qr(s);break}return s},hd=s=>{let e=[];return s.map(t=>{t.type==="brace"&&(t.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),t.type==="paren"&&(t.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(t=>{t==="}"?s.push({type:"brace",value:"}"}):t==="]"&&s.push({type:"paren",value:"]"})}),s},fd=s=>{let e="";return s.map(t=>{switch(t.type){case"string":e+='"'+t.value+'"';break;default:e+=t.value;break}}),e},Dn=s=>JSON.parse(fd(hd(qr(dd(s)))));var Ae,wt,Hr,ks,$n,Ms,Ts,Ln,Os,Ze,Fs,Un,jn,Wr,qn,Hn,bo,hc,Wn,wo,_o,xo,fc,mc="__json_buf";function pc(s){return s.type==="tool_use"||s.type==="server_tool_use"||s.type==="mcp_tool_use"}var Xt=class{constructor(e){Ae.add(this),this.messages=[],this.receivedMessages=[],wt.set(this,void 0),Hr.set(this,null),this.controller=new AbortController,ks.set(this,void 0),$n.set(this,()=>{}),Ms.set(this,()=>{}),Ts.set(this,void 0),Ln.set(this,()=>{}),Os.set(this,()=>{}),Ze.set(this,{}),Fs.set(this,!1),Un.set(this,!1),jn.set(this,!1),Wr.set(this,!1),qn.set(this,void 0),Hn.set(this,void 0),Wn.set(this,t=>{if(w(this,Un,!0,"f"),Xe(t)&&(t=new se),t instanceof se)return w(this,jn,!0,"f"),this._emit("abort",t);if(t instanceof P)return this._emit("error",t);if(t instanceof Error){let r=new P(t.message);return r.cause=t,this._emit("error",r)}return this._emit("error",new P(String(t)))}),w(this,ks,new Promise((t,r)=>{w(this,$n,t,"f"),w(this,Ms,r,"f")}),"f"),w(this,Ts,new Promise((t,r)=>{w(this,Ln,t,"f"),w(this,Os,r,"f")}),"f"),d(this,ks,"f").catch(()=>{}),d(this,Ts,"f").catch(()=>{}),w(this,Hr,e,"f")}get response(){return d(this,qn,"f")}get request_id(){return d(this,Hn,"f")}async withResponse(){let e=await d(this,ks,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let t=new Xt(null);return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,r){let n=new Xt(t);for(let i of t.messages)n._addMessageParam(i);return w(n,Hr,{...t,stream:!0},"f"),n._run(()=>n._createMessage(e,{...t,stream:!0},{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),n}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},d(this,Wn,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,r){var o;let n=r==null?void 0:r.signal,i;n&&(n.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),n.addEventListener("abort",i));try{d(this,Ae,"m",wo).call(this);let{response:a,data:c}=await e.create({...t,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(a);for await(let l of c)d(this,Ae,"m",_o).call(this,l);if((o=c.controller.signal)!=null&&o.aborted)throw new se;d(this,Ae,"m",xo).call(this)}finally{n&&i&&n.removeEventListener("abort",i)}}_connected(e){this.ended||(w(this,qn,e,"f"),w(this,Hn,e==null?void 0:e.headers.get("request-id"),"f"),d(this,$n,"f").call(this,e),this._emit("connect"))}get ended(){return d(this,Fs,"f")}get errored(){return d(this,Un,"f")}get aborted(){return d(this,jn,"f")}abort(){this.controller.abort()}on(e,t){return(d(this,Ze,"f")[e]||(d(this,Ze,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=d(this,Ze,"f")[e];if(!r)return this;let n=r.findIndex(i=>i.listener===t);return n>=0&&r.splice(n,1),this}once(e,t){return(d(this,Ze,"f")[e]||(d(this,Ze,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{w(this,Wr,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){w(this,Wr,!0,"f"),await d(this,Ts,"f")}get currentMessage(){return d(this,wt,"f")}async finalMessage(){return await this.done(),d(this,Ae,"m",bo).call(this)}async finalText(){return await this.done(),d(this,Ae,"m",hc).call(this)}_emit(e,...t){if(d(this,Fs,"f"))return;e==="end"&&(w(this,Fs,!0,"f"),d(this,Ln,"f").call(this));let r=d(this,Ze,"f")[e];if(r&&(d(this,Ze,"f")[e]=r.filter(n=>!n.once),r.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!d(this,Wr,"f")&&!(r!=null&&r.length)&&Promise.reject(n),d(this,Ms,"f").call(this,n),d(this,Os,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!d(this,Wr,"f")&&!(r!=null&&r.length)&&Promise.reject(n),d(this,Ms,"f").call(this,n),d(this,Os,"f").call(this,n),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",d(this,Ae,"m",bo).call(this))}async _fromReadableStream(e,t){var i;let r=t==null?void 0:t.signal,n;r&&(r.aborted&&this.controller.abort(),n=this.controller.abort.bind(this.controller),r.addEventListener("abort",n));try{d(this,Ae,"m",wo).call(this),this._connected(null);let o=ce.fromReadableStream(e,this.controller);for await(let a of o)d(this,Ae,"m",_o).call(this,a);if((i=o.controller.signal)!=null&&i.aborted)throw new se;d(this,Ae,"m",xo).call(this)}finally{r&&n&&r.removeEventListener("abort",n)}}[(wt=new WeakMap,Hr=new WeakMap,ks=new WeakMap,$n=new WeakMap,Ms=new WeakMap,Ts=new WeakMap,Ln=new WeakMap,Os=new WeakMap,Ze=new WeakMap,Fs=new WeakMap,Un=new WeakMap,jn=new WeakMap,Wr=new WeakMap,qn=new WeakMap,Hn=new WeakMap,Wn=new WeakMap,Ae=new WeakSet,bo=function(){if(this.receivedMessages.length===0)throw new P("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},hc=function(){if(this.receivedMessages.length===0)throw new P("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(r=>r.type==="text").map(r=>r.text);if(t.length===0)throw new P("stream ended without producing a content block with type=text");return t.join(" ")},wo=function(){this.ended||w(this,wt,void 0,"f")},_o=function(t){var n;if(this.ended)return;let r=d(this,Ae,"m",fc).call(this,t);switch(this._emit("streamEvent",t,r),t.type){case"content_block_delta":{let i=r.content.at(-1);switch(t.delta.type){case"text_delta":{i.type==="text"&&this._emit("text",t.delta.text,i.text||"");break}case"citations_delta":{i.type==="text"&&this._emit("citation",t.delta.citation,(n=i.citations)!=null?n:[]);break}case"input_json_delta":{pc(i)&&i.input&&this._emit("inputJson",t.delta.partial_json,i.input);break}case"thinking_delta":{i.type==="thinking"&&this._emit("thinking",t.delta.thinking,i.thinking);break}case"signature_delta":{i.type==="thinking"&&this._emit("signature",i.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(r),this._addMessage(go(r,d(this,Hr,"f")),!0);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{w(this,wt,r,"f");break}case"content_block_start":case"message_delta":break}},xo=function(){if(this.ended)throw new P("stream has ended, this shouldn't happen");let t=d(this,wt,"f");if(!t)throw new P("request ended without sending any chunks");return w(this,wt,void 0,"f"),go(t,d(this,Hr,"f"))},fc=function(t){var n;let r=d(this,wt,"f");if(t.type==="message_start"){if(r)throw new P(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!r)throw new P(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return r;case"message_delta":return r.container=t.delta.container,r.stop_reason=t.delta.stop_reason,r.stop_sequence=t.delta.stop_sequence,r.usage.output_tokens=t.usage.output_tokens,r.context_management=t.context_management,t.usage.input_tokens!=null&&(r.usage.input_tokens=t.usage.input_tokens),t.usage.cache_creation_input_tokens!=null&&(r.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens),t.usage.cache_read_input_tokens!=null&&(r.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens),t.usage.server_tool_use!=null&&(r.usage.server_tool_use=t.usage.server_tool_use),r;case"content_block_start":return r.content.push(t.content_block),r;case"content_block_delta":{let i=r.content.at(t.index);switch(t.delta.type){case"text_delta":{(i==null?void 0:i.type)==="text"&&(r.content[t.index]={...i,text:(i.text||"")+t.delta.text});break}case"citations_delta":{(i==null?void 0:i.type)==="text"&&(r.content[t.index]={...i,citations:[...(n=i.citations)!=null?n:[],t.delta.citation]});break}case"input_json_delta":{if(i&&pc(i)){let o=i[mc]||"";o+=t.delta.partial_json;let a={...i};if(Object.defineProperty(a,mc,{value:o,enumerable:!1,writable:!0}),o)try{a.input=Dn(o)}catch(c){let l=new P(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${c}. JSON: ${o}`);d(this,Wn,"f").call(this,l)}r.content[t.index]=a}break}case"thinking_delta":{(i==null?void 0:i.type)==="thinking"&&(r.content[t.index]={...i,thinking:i.thinking+t.delta.thinking});break}case"signature_delta":{(i==null?void 0:i.type)==="thinking"&&(r.content[t.index]={...i,signature:t.delta.signature});break}default:t.delta}return r}case"content_block_stop":return r}},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("streamEvent",n=>{let i=t.shift();i?i.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let i of t)i.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let i of t)i.reject(n);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 ce(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var gc=`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
1. Task Overview
The user's core request and success criteria
Any clarifications or constraints they specified
2. Current State
What has been completed so far
Files created, modified, or analyzed (with paths if relevant)
Key outputs or artifacts produced
3. Important Discoveries
Technical constraints or requirements uncovered
Decisions made and their rationale
Errors encountered and how they were resolved
What approaches were tried that didn't work (and why)
4. Next Steps
Specific actions needed to complete the task
Any blockers or open questions to resolve
Priority order if multiple steps remain
5. Context to Preserve
User preferences or style requirements
Domain-specific details that aren't obvious
Any promises made to the user
Be concise but complete\u2014err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
Wrap your summary in <summary></summary> tags.`;var Ns,Vr,Gt,Q,Bs,be,et,_t,Ds,yc,Po;function bc(){let s,e;return{promise:new Promise((r,n)=>{s=r,e=n}),resolve:s,reject:e}}var zr=class{constructor(e,t,r){Ns.add(this),this.client=e,Vr.set(this,!1),Gt.set(this,!1),Q.set(this,void 0),Bs.set(this,void 0),be.set(this,void 0),et.set(this,void 0),_t.set(this,void 0),Ds.set(this,0),w(this,Q,{params:{...t,messages:structuredClone(t.messages)}},"f"),w(this,Bs,{...r,headers:S([{"x-stainless-helper":"BetaToolRunner"},r==null?void 0:r.headers])},"f"),w(this,_t,bc(),"f")}async*[(Vr=new WeakMap,Gt=new WeakMap,Q=new WeakMap,Bs=new WeakMap,be=new WeakMap,et=new WeakMap,_t=new WeakMap,Ds=new WeakMap,Ns=new WeakSet,yc=async function(){var l,u,h,m,f,p;let t=d(this,Q,"f").params.compactionControl;if(!t||!t.enabled)return!1;let r=0;if(d(this,be,"f")!==void 0)try{let y=await d(this,be,"f");r=y.usage.input_tokens+((l=y.usage.cache_creation_input_tokens)!=null?l:0)+((u=y.usage.cache_read_input_tokens)!=null?u:0)+y.usage.output_tokens}catch(y){return!1}let n=(h=t.contextTokenThreshold)!=null?h:1e5;if(r<n)return!1;let i=(m=t.model)!=null?m:d(this,Q,"f").params.model,o=(f=t.summaryPrompt)!=null?f:gc,a=d(this,Q,"f").params.messages;if(a[a.length-1].role==="assistant"){let y=a[a.length-1];if(Array.isArray(y.content)){let g=y.content.filter(C=>C.type!=="tool_use");g.length===0?a.pop():y.content=g}}let c=await this.client.beta.messages.create({model:i,messages:[...a,{role:"user",content:[{type:"text",text:o}]}],max_tokens:d(this,Q,"f").params.max_tokens},{headers:{"x-stainless-helper":"compaction"}});if(((p=c.content[0])==null?void 0:p.type)!=="text")throw new P("Expected text response for compaction");return d(this,Q,"f").params.messages=[{role:"user",content:c.content}],!0},Symbol.asyncIterator)](){var e;if(d(this,Vr,"f"))throw new P("Cannot iterate over a consumed stream");w(this,Vr,!0,"f"),w(this,Gt,!0,"f"),w(this,et,void 0,"f");try{for(;;){let t;try{if(d(this,Q,"f").params.max_iterations&&d(this,Ds,"f")>=d(this,Q,"f").params.max_iterations)break;w(this,Gt,!1,"f"),w(this,et,void 0,"f"),w(this,Ds,(e=d(this,Ds,"f"),e++,e),"f"),w(this,be,void 0,"f");let{max_iterations:r,compactionControl:n,...i}=d(this,Q,"f").params;if(i.stream?(t=this.client.beta.messages.stream({...i},d(this,Bs,"f")),w(this,be,t.finalMessage(),"f"),d(this,be,"f").catch(()=>{}),yield t):(w(this,be,this.client.beta.messages.create({...i,stream:!1},d(this,Bs,"f")),"f"),yield d(this,be,"f")),!await d(this,Ns,"m",yc).call(this)){if(!d(this,Gt,"f")){let{role:c,content:l}=await d(this,be,"f");d(this,Q,"f").params.messages.push({role:c,content:l})}let a=await d(this,Ns,"m",Po).call(this,d(this,Q,"f").params.messages.at(-1));if(a)d(this,Q,"f").params.messages.push(a);else if(!d(this,Gt,"f"))break}}finally{t&&t.abort()}}if(!d(this,be,"f"))throw new P("ToolRunner concluded without a message from the server");d(this,_t,"f").resolve(await d(this,be,"f"))}catch(t){throw w(this,Vr,!1,"f"),d(this,_t,"f").promise.catch(()=>{}),d(this,_t,"f").reject(t),w(this,_t,bc(),"f"),t}}setMessagesParams(e){typeof e=="function"?d(this,Q,"f").params=e(d(this,Q,"f").params):d(this,Q,"f").params=e,w(this,Gt,!0,"f"),w(this,et,void 0,"f")}async generateToolResponse(){var t;let e=(t=await d(this,be,"f"))!=null?t:this.params.messages.at(-1);return e?d(this,Ns,"m",Po).call(this,e):null}done(){return d(this,_t,"f").promise}async runUntilDone(){if(!d(this,Vr,"f"))for await(let e of this);return this.done()}get params(){return d(this,Q,"f").params}pushMessages(...e){this.setMessagesParams(t=>({...t,messages:[...t.messages,...e]}))}then(e,t){return this.runUntilDone().then(e,t)}};Po=async function(e){return d(this,et,"f")!==void 0?d(this,et,"f"):(w(this,et,pd(d(this,Q,"f").params,e),"f"),d(this,et,"f"))};async function pd(s,e=s.messages.at(-1)){if(!e||e.role!=="assistant"||!e.content||typeof e.content=="string")return null;let t=e.content.filter(n=>n.type==="tool_use");return t.length===0?null:{role:"user",content:await Promise.all(t.map(async n=>{let i=s.tools.find(o=>("name"in o?o.name:o.mcp_server_name)===n.name);if(!i||!("run"in i))return{type:"tool_result",tool_use_id:n.id,content:`Error: Tool '${n.name}' not found`,is_error:!0};try{let o=n.input;"parse"in i&&i.parse&&(o=i.parse(o));let a=await i.run(o);return{type:"tool_result",tool_use_id:n.id,content:a}}catch(o){return{type:"tool_result",tool_use_id:n.id,content:`Error: ${o instanceof Error?o.message:String(o)}`,is_error:!0}}}))}}var xt=class{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new Ge;for await(let t of this.iterator)for(let r of e.decode(t))yield JSON.parse(r);for(let t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator!="undefined"&&globalThis.navigator.product==="ReactNative"?new P("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new P("Attempted to iterate over a response with no body");return new xt(As(e.body),t)}};var Kr=class extends j{create(e,t){let{betas:r,...n}=e;return this._client.post("/v1/messages/batches?beta=true",{body:n,...t,headers:S([{"anthropic-beta":[...r!=null?r:[],"message-batches-2024-09-24"].toString()},t==null?void 0:t.headers])})}retrieve(e,t={},r){let{betas:n}=t!=null?t:{};return this._client.get(q`/v1/messages/batches/${e}?beta=true`,{...r,headers:S([{"anthropic-beta":[...n!=null?n:[],"message-batches-2024-09-24"].toString()},r==null?void 0:r.headers])})}list(e={},t){let{betas:r,...n}=e!=null?e:{};return this._client.getAPIList("/v1/messages/batches?beta=true",Pe,{query:n,...t,headers:S([{"anthropic-beta":[...r!=null?r:[],"message-batches-2024-09-24"].toString()},t==null?void 0:t.headers])})}delete(e,t={},r){let{betas:n}=t!=null?t:{};return this._client.delete(q`/v1/messages/batches/${e}?beta=true`,{...r,headers:S([{"anthropic-beta":[...n!=null?n:[],"message-batches-2024-09-24"].toString()},r==null?void 0:r.headers])})}cancel(e,t={},r){let{betas:n}=t!=null?t:{};return this._client.post(q`/v1/messages/batches/${e}/cancel?beta=true`,{...r,headers:S([{"anthropic-beta":[...n!=null?n:[],"message-batches-2024-09-24"].toString()},r==null?void 0:r.headers])})}async results(e,t={},r){let n=await this.retrieve(e);if(!n.results_url)throw new P(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);let{betas:i}=t!=null?t:{};return this._client.get(n.results_url,{...r,headers:S([{"anthropic-beta":[...i!=null?i:[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},r==null?void 0:r.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((o,a)=>xt.fromResponse(a.response,a.controller))}};var wc={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026"},Pt=class extends j{constructor(){super(...arguments),this.batches=new Kr(this._client)}create(e,t){var o,a;let{betas:r,...n}=e;n.model in wc&&console.warn(`The model '${n.model}' is deprecated and will reach end-of-life on ${wc[n.model]}
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let i=this._client._options.timeout;if(!n.stream&&i==null){let c=(o=Bn[n.model])!=null?o:void 0;i=this._client.calculateNonstreamingTimeout(n.max_tokens,c)}return this._client.post("/v1/messages?beta=true",{body:n,timeout:i!=null?i:6e5,...t,headers:S([{...(r==null?void 0:r.toString())!=null?{"anthropic-beta":r==null?void 0:r.toString()}:void 0},t==null?void 0:t.headers]),stream:(a=e.stream)!=null?a:!1})}parse(e,t){var r;return t={...t,headers:S([{"anthropic-beta":[...(r=e.betas)!=null?r:[],"structured-outputs-2025-11-13"].toString()},t==null?void 0:t.headers])},this.create(e,t).then(n=>yo(n,e))}stream(e,t){return Xt.createMessage(this,e,t)}countTokens(e,t){let{betas:r,...n}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:n,...t,headers:S([{"anthropic-beta":[...r!=null?r:[],"token-counting-2024-11-01"].toString()},t==null?void 0:t.headers])})}toolRunner(e,t){return new zr(this._client,e,t)}};Pt.Batches=Kr;Pt.BetaToolRunner=zr;var Jr=class extends j{create(e,t={},r){let{betas:n,...i}=t!=null?t:{};return this._client.post(q`/v1/skills/${e}/versions?beta=true`,Lr({body:i,...r,headers:S([{"anthropic-beta":[...n!=null?n:[],"skills-2025-10-02"].toString()},r==null?void 0:r.headers])},this._client))}retrieve(e,t,r){let{skill_id:n,betas:i}=t;return this._client.get(q`/v1/skills/${n}/versions/${e}?beta=true`,{...r,headers:S([{"anthropic-beta":[...i!=null?i:[],"skills-2025-10-02"].toString()},r==null?void 0:r.headers])})}list(e,t={},r){let{betas:n,...i}=t!=null?t:{};return this._client.getAPIList(q`/v1/skills/${e}/versions?beta=true`,$r,{query:i,...r,headers:S([{"anthropic-beta":[...n!=null?n:[],"skills-2025-10-02"].toString()},r==null?void 0:r.headers])})}delete(e,t,r){let{skill_id:n,betas:i}=t;return this._client.delete(q`/v1/skills/${n}/versions/${e}?beta=true`,{...r,headers:S([{"anthropic-beta":[...i!=null?i:[],"skills-2025-10-02"].toString()},r==null?void 0:r.headers])})}};var Qt=class extends j{constructor(){super(...arguments),this.versions=new Jr(this._client)}create(e={},t){let{betas:r,...n}=e!=null?e:{};return this._client.post("/v1/skills?beta=true",Lr({body:n,...t,headers:S([{"anthropic-beta":[...r!=null?r:[],"skills-2025-10-02"].toString()},t==null?void 0:t.headers])},this._client))}retrieve(e,t={},r){let{betas:n}=t!=null?t:{};return this._client.get(q`/v1/skills/${e}?beta=true`,{...r,headers:S([{"anthropic-beta":[...n!=null?n:[],"skills-2025-10-02"].toString()},r==null?void 0:r.headers])})}list(e={},t){let{betas:r,...n}=e!=null?e:{};return this._client.getAPIList("/v1/skills?beta=true",$r,{query:n,...t,headers:S([{"anthropic-beta":[...r!=null?r:[],"skills-2025-10-02"].toString()},t==null?void 0:t.headers])})}delete(e,t={},r){let{betas:n}=t!=null?t:{};return this._client.delete(q`/v1/skills/${e}?beta=true`,{...r,headers:S([{"anthropic-beta":[...n!=null?n:[],"skills-2025-10-02"].toString()},r==null?void 0:r.headers])})}};Qt.Versions=Jr;var Re=class extends j{constructor(){super(...arguments),this.models=new jr(this._client),this.messages=new Pt(this._client),this.files=new Ur(this._client),this.skills=new Qt(this._client)}};Re.Models=jr;Re.Messages=Pt;Re.Files=Ur;Re.Skills=Qt;var Yt=class extends j{create(e,t){var i,o;let{betas:r,...n}=e;return this._client.post("/v1/complete",{body:n,timeout:(i=this._client._options.timeout)!=null?i:6e5,...t,headers:S([{...(r==null?void 0:r.toString())!=null?{"anthropic-beta":r==null?void 0:r.toString()}:void 0},t==null?void 0:t.headers]),stream:(o=e.stream)!=null?o:!1})}};var ve,At,$s,Vn,Ls,Us,zn,js,tt,qs,Kn,Jn,Xr,Xn,Gn,Ao,_c,vo,Io,Eo,So,xc,Pc="__json_buf";function Ac(s){return s.type==="tool_use"||s.type==="server_tool_use"}var Zt=class{constructor(){ve.add(this),this.messages=[],this.receivedMessages=[],At.set(this,void 0),this.controller=new AbortController,$s.set(this,void 0),Vn.set(this,()=>{}),Ls.set(this,()=>{}),Us.set(this,void 0),zn.set(this,()=>{}),js.set(this,()=>{}),tt.set(this,{}),qs.set(this,!1),Kn.set(this,!1),Jn.set(this,!1),Xr.set(this,!1),Xn.set(this,void 0),Gn.set(this,void 0),vo.set(this,e=>{if(w(this,Kn,!0,"f"),Xe(e)&&(e=new se),e instanceof se)return w(this,Jn,!0,"f"),this._emit("abort",e);if(e instanceof P)return this._emit("error",e);if(e instanceof Error){let t=new P(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new P(String(e)))}),w(this,$s,new Promise((e,t)=>{w(this,Vn,e,"f"),w(this,Ls,t,"f")}),"f"),w(this,Us,new Promise((e,t)=>{w(this,zn,e,"f"),w(this,js,t,"f")}),"f"),d(this,$s,"f").catch(()=>{}),d(this,Us,"f").catch(()=>{})}get response(){return d(this,Xn,"f")}get request_id(){return d(this,Gn,"f")}async withResponse(){let e=await d(this,$s,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let t=new Zt;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,r){let n=new Zt;for(let i of t.messages)n._addMessageParam(i);return n._run(()=>n._createMessage(e,{...t,stream:!0},{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),n}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},d(this,vo,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,r){var o;let n=r==null?void 0:r.signal,i;n&&(n.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),n.addEventListener("abort",i));try{d(this,ve,"m",Io).call(this);let{response:a,data:c}=await e.create({...t,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(a);for await(let l of c)d(this,ve,"m",Eo).call(this,l);if((o=c.controller.signal)!=null&&o.aborted)throw new se;d(this,ve,"m",So).call(this)}finally{n&&i&&n.removeEventListener("abort",i)}}_connected(e){this.ended||(w(this,Xn,e,"f"),w(this,Gn,e==null?void 0:e.headers.get("request-id"),"f"),d(this,Vn,"f").call(this,e),this._emit("connect"))}get ended(){return d(this,qs,"f")}get errored(){return d(this,Kn,"f")}get aborted(){return d(this,Jn,"f")}abort(){this.controller.abort()}on(e,t){return(d(this,tt,"f")[e]||(d(this,tt,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=d(this,tt,"f")[e];if(!r)return this;let n=r.findIndex(i=>i.listener===t);return n>=0&&r.splice(n,1),this}once(e,t){return(d(this,tt,"f")[e]||(d(this,tt,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{w(this,Xr,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){w(this,Xr,!0,"f"),await d(this,Us,"f")}get currentMessage(){return d(this,At,"f")}async finalMessage(){return await this.done(),d(this,ve,"m",Ao).call(this)}async finalText(){return await this.done(),d(this,ve,"m",_c).call(this)}_emit(e,...t){if(d(this,qs,"f"))return;e==="end"&&(w(this,qs,!0,"f"),d(this,zn,"f").call(this));let r=d(this,tt,"f")[e];if(r&&(d(this,tt,"f")[e]=r.filter(n=>!n.once),r.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!d(this,Xr,"f")&&!(r!=null&&r.length)&&Promise.reject(n),d(this,Ls,"f").call(this,n),d(this,js,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!d(this,Xr,"f")&&!(r!=null&&r.length)&&Promise.reject(n),d(this,Ls,"f").call(this,n),d(this,js,"f").call(this,n),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",d(this,ve,"m",Ao).call(this))}async _fromReadableStream(e,t){var i;let r=t==null?void 0:t.signal,n;r&&(r.aborted&&this.controller.abort(),n=this.controller.abort.bind(this.controller),r.addEventListener("abort",n));try{d(this,ve,"m",Io).call(this),this._connected(null);let o=ce.fromReadableStream(e,this.controller);for await(let a of o)d(this,ve,"m",Eo).call(this,a);if((i=o.controller.signal)!=null&&i.aborted)throw new se;d(this,ve,"m",So).call(this)}finally{r&&n&&r.removeEventListener("abort",n)}}[(At=new WeakMap,$s=new WeakMap,Vn=new WeakMap,Ls=new WeakMap,Us=new WeakMap,zn=new WeakMap,js=new WeakMap,tt=new WeakMap,qs=new WeakMap,Kn=new WeakMap,Jn=new WeakMap,Xr=new WeakMap,Xn=new WeakMap,Gn=new WeakMap,vo=new WeakMap,ve=new WeakSet,Ao=function(){if(this.receivedMessages.length===0)throw new P("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},_c=function(){if(this.receivedMessages.length===0)throw new P("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(r=>r.type==="text").map(r=>r.text);if(t.length===0)throw new P("stream ended without producing a content block with type=text");return t.join(" ")},Io=function(){this.ended||w(this,At,void 0,"f")},Eo=function(t){var n;if(this.ended)return;let r=d(this,ve,"m",xc).call(this,t);switch(this._emit("streamEvent",t,r),t.type){case"content_block_delta":{let i=r.content.at(-1);switch(t.delta.type){case"text_delta":{i.type==="text"&&this._emit("text",t.delta.text,i.text||"");break}case"citations_delta":{i.type==="text"&&this._emit("citation",t.delta.citation,(n=i.citations)!=null?n:[]);break}case"input_json_delta":{Ac(i)&&i.input&&this._emit("inputJson",t.delta.partial_json,i.input);break}case"thinking_delta":{i.type==="thinking"&&this._emit("thinking",t.delta.thinking,i.thinking);break}case"signature_delta":{i.type==="thinking"&&this._emit("signature",i.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(r),this._addMessage(r,!0);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{w(this,At,r,"f");break}case"content_block_start":case"message_delta":break}},So=function(){if(this.ended)throw new P("stream has ended, this shouldn't happen");let t=d(this,At,"f");if(!t)throw new P("request ended without sending any chunks");return w(this,At,void 0,"f"),t},xc=function(t){var n;let r=d(this,At,"f");if(t.type==="message_start"){if(r)throw new P(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!r)throw new P(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return r;case"message_delta":return r.stop_reason=t.delta.stop_reason,r.stop_sequence=t.delta.stop_sequence,r.usage.output_tokens=t.usage.output_tokens,t.usage.input_tokens!=null&&(r.usage.input_tokens=t.usage.input_tokens),t.usage.cache_creation_input_tokens!=null&&(r.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens),t.usage.cache_read_input_tokens!=null&&(r.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens),t.usage.server_tool_use!=null&&(r.usage.server_tool_use=t.usage.server_tool_use),r;case"content_block_start":return r.content.push({...t.content_block}),r;case"content_block_delta":{let i=r.content.at(t.index);switch(t.delta.type){case"text_delta":{(i==null?void 0:i.type)==="text"&&(r.content[t.index]={...i,text:(i.text||"")+t.delta.text});break}case"citations_delta":{(i==null?void 0:i.type)==="text"&&(r.content[t.index]={...i,citations:[...(n=i.citations)!=null?n:[],t.delta.citation]});break}case"input_json_delta":{if(i&&Ac(i)){let o=i[Pc]||"";o+=t.delta.partial_json;let a={...i};Object.defineProperty(a,Pc,{value:o,enumerable:!1,writable:!0}),o&&(a.input=Dn(o)),r.content[t.index]=a}break}case"thinking_delta":{(i==null?void 0:i.type)==="thinking"&&(r.content[t.index]={...i,thinking:i.thinking+t.delta.thinking});break}case"signature_delta":{(i==null?void 0:i.type)==="thinking"&&(r.content[t.index]={...i,signature:t.delta.signature});break}default:t.delta}return r}case"content_block_stop":return r}},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("streamEvent",n=>{let i=t.shift();i?i.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let i of t)i.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let i of t)i.reject(n);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 ce(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var Gr=class extends j{create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(q`/v1/messages/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/v1/messages/batches",Pe,{query:e,...t})}delete(e,t){return this._client.delete(q`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(q`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){let r=await this.retrieve(e);if(!r.results_url)throw new P(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);return this._client.get(r.results_url,{...t,headers:S([{Accept:"application/binary"},t==null?void 0:t.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((n,i)=>xt.fromResponse(i.response,i.controller))}};var vt=class extends j{constructor(){super(...arguments),this.batches=new Gr(this._client)}create(e,t){var n,i;e.model in vc&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${vc[e.model]}
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let r=this._client._options.timeout;if(!e.stream&&r==null){let o=(n=Bn[e.model])!=null?n:void 0;r=this._client.calculateNonstreamingTimeout(e.max_tokens,o)}return this._client.post("/v1/messages",{body:e,timeout:r!=null?r:6e5,...t,stream:(i=e.stream)!=null?i:!1})}stream(e,t){return Zt.createMessage(this,e,t)}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}},vc={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026"};vt.Batches=Gr;var er=class extends j{retrieve(e,t={},r){let{betas:n}=t!=null?t:{};return this._client.get(q`/v1/models/${e}`,{...r,headers:S([{...(n==null?void 0:n.toString())!=null?{"anthropic-beta":n==null?void 0:n.toString()}:void 0},r==null?void 0:r.headers])})}list(e={},t){let{betas:r,...n}=e!=null?e:{};return this._client.getAPIList("/v1/models",Pe,{query:n,...t,headers:S([{...(r==null?void 0:r.toString())!=null?{"anthropic-beta":r==null?void 0:r.toString()}:void 0},t==null?void 0:t.headers])})}};var Hs=s=>{var e,t,r,n,i,o;if(typeof globalThis.process!="undefined")return(r=(t=(e=globalThis.process.env)==null?void 0:e[s])==null?void 0:t.trim())!=null?r:void 0;if(typeof globalThis.Deno!="undefined")return(o=(i=(n=globalThis.Deno.env)==null?void 0:n.get)==null?void 0:i.call(n,s))==null?void 0:o.trim()};var Ro,Co,Qn,Ic,Ec="\\n\\nHuman:",Sc="\\n\\nAssistant:",V=class{constructor({baseURL:e=Hs("ANTHROPIC_BASE_URL"),apiKey:t=(i=>(i=Hs("ANTHROPIC_API_KEY"))!=null?i:null)(),authToken:r=(o=>(o=Hs("ANTHROPIC_AUTH_TOKEN"))!=null?o:null)(),...n}={}){var l,u,h,m,f,p;Ro.add(this),Qn.set(this,void 0);let a={apiKey:t,authToken:r,...n,baseURL:e||"https://api.anthropic.com"};if(!a.dangerouslyAllowBrowser&&Za())throw new P(`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 Anthropic({ apiKey, dangerouslyAllowBrowser: true });
`);this.baseURL=a.baseURL,this.timeout=(l=a.timeout)!=null?l:Co.DEFAULT_TIMEOUT,this.logger=(u=a.logger)!=null?u:console;let c="warn";this.logLevel=c,this.logLevel=(m=(h=co(a.logLevel,"ClientOptions.logLevel",this))!=null?h:co(Hs("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this))!=null?m:c,this.fetchOptions=a.fetchOptions,this.maxRetries=(f=a.maxRetries)!=null?f:2,this.fetch=(p=a.fetch)!=null?p:tc(),w(this,Qn,sc,"f"),this._options=a,this.apiKey=typeof t=="string"?t:null,this.authToken=r}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(e.get("x-api-key")||e.get("authorization"))&&!(this.apiKey&&e.get("x-api-key"))&&!t.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!t.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return S([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return S([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return S([{Authorization:`Bearer ${this.authToken}`}])}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 P(`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("&")}getUserAgent(){return`${this.constructor.name}/JS ${bt}`}defaultIdempotencyKey(){return`stainless-node-retry-${so()}`}makeStatusError(e,t,r,n){return K.generate(e,t,r,n)}buildURL(e,t,r){let n=!d(this,Ro,"m",Ic).call(this)&&r||this.baseURL,i=za(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery();return Ka(o)||(t={...o,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new P("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}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(n=>({method:e,path:t,...n})))}request(e,t=null){return new Ye(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){var C,_,O;let n=await e,i=(C=n.maxRetries)!=null?C:this.maxRetries;t==null&&(t=i),await this.prepareOptions(n);let{req:o,url:a,timeout:c}=await this.buildRequest(n,{retryCount:i-t});await this.prepareRequest(o,{url:a,options:n});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=r===void 0?"":`, retryOf: ${r}`,h=Date.now();if(ee(this).debug(`[${l}] sending request`,Qe({retryOfRequestLogID:r,method:n.method,url:a,options:n,headers:o.headers})),(_=n.signal)!=null&&_.aborted)throw new se;let m=new AbortController,f=await this.fetchWithTimeout(a,o,c,m).catch(Ps),p=Date.now();if(f instanceof globalThis.Error){let M=`retrying, ${t} attempts remaining`;if((O=n.signal)!=null&&O.aborted)throw new se;let v=Xe(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(t)return ee(this).info(`[${l}] connection ${v?"timed out":"failed"} - ${M}`),ee(this).debug(`[${l}] connection ${v?"timed out":"failed"} (${M})`,Qe({retryOfRequestLogID:r,url:a,durationMs:p-h,message:f.message})),this.retryRequest(n,t,r!=null?r:l);throw ee(this).info(`[${l}] connection ${v?"timed out":"failed"} - error; no more retries left`),ee(this).debug(`[${l}] connection ${v?"timed out":"failed"} (error; no more retries left)`,Qe({retryOfRequestLogID:r,url:a,durationMs:p-h,message:f.message})),v?new Cr:new yt({cause:f})}let y=[...f.headers.entries()].filter(([M])=>M==="request-id").map(([M,v])=>", "+M+": "+JSON.stringify(v)).join(""),g=`[${l}${u}${y}] ${o.method} ${a} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${p-h}ms`;if(!f.ok){let M=await this.shouldRetry(f);if(t&&M){let k=`retrying, ${t} attempts remaining`;return await rc(f.body),ee(this).info(`${g} - ${k}`),ee(this).debug(`[${l}] response error (${k})`,Qe({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:p-h})),this.retryRequest(n,t,r!=null?r:l,f.headers)}let v=M?"error; no more retries left":"error; not retryable";ee(this).info(`${g} - ${v}`);let B=await f.text().catch(k=>Ps(k).message),N=In(B),F=N?void 0:B;throw ee(this).debug(`[${l}] response error (${v})`,Qe({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,message:F,durationMs:Date.now()-h})),this.makeStatusError(f.status,N,F,f.headers)}return ee(this).info(g),ee(this).debug(`[${l}] response start`,Qe({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:p-h})),{response:f,options:n,controller:m,requestLogID:l,retryOfRequestLogID:r,startTime:h}}getAPIList(e,t,r){return this.requestAPIList(t,{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new Rs(this,r,e)}async fetchWithTimeout(e,t,r,n){let{signal:i,method:o,...a}=t||{};i&&i.addEventListener("abort",()=>n.abort());let c=setTimeout(()=>n.abort(),r),l=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,u={signal:n.signal,...l?{duplex:"half"}:{},method:"GET",...a};o&&(u.method=o.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async 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,n){var c;let i,o=n==null?void 0:n.get("retry-after-ms");if(o){let l=parseFloat(o);Number.isNaN(l)||(i=l)}let a=n==null?void 0:n.get("retry-after");if(a&&!i){let l=parseFloat(a);Number.isNaN(l)?i=Date.parse(a)-Date.now():i=l*1e3}if(!(i&&0<=i&&i<60*1e3)){let l=(c=e.maxRetries)!=null?c:this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,l)}return await Ga(i),this.makeRequest(e,t-1,r)}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}calculateNonstreamingTimeout(e,t){if(36e5*e/128e3>6e5||t!=null&&e>t)throw new P("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:t=0}={}){var f,p,y;let r={...e},{method:n,path:i,query:o,defaultBaseURL:a}=r,c=this.buildURL(i,o,a);"timeout"in r&&Xa("timeout",r.timeout),r.timeout=(f=r.timeout)!=null?f:this.timeout;let{bodyHeaders:l,body:u}=this.buildBody({options:r}),h=await this.buildHeaders({options:e,method:n,bodyHeaders:l,retryCount:t});return{req:{method:n,headers:h,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...(p=this.fetchOptions)!=null?p:{},...(y=r.fetchOptions)!=null?y:{}},url:c,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:n}){let i={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);let o=S([i,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...ec(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(o),o.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=S([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Sn(e)}:d(this,Qn,"f").call(this,{body:e,headers:r})}};Co=V,Qn=new WeakMap,Ro=new WeakSet,Ic=function(){return this.baseURL!=="https://api.anthropic.com"};V.Anthropic=Co;V.HUMAN_PROMPT=Ec;V.AI_PROMPT=Sc;V.DEFAULT_TIMEOUT=6e5;V.AnthropicError=P;V.APIError=K;V.APIConnectionError=yt;V.APIConnectionTimeoutError=Cr;V.APIUserAbortError=se;V.NotFoundError=Or;V.ConflictError=Fr;V.RateLimitError=Br;V.BadRequestError=kr;V.AuthenticationError=Mr;V.InternalServerError=Dr;V.PermissionDeniedError=Tr;V.UnprocessableEntityError=Nr;V.toFile=Nn;var Ue=class extends V{constructor(){super(...arguments),this.completions=new Yt(this),this.messages=new vt(this),this.models=new er(this),this.beta=new Re(this)}};Ue.Completions=Yt;Ue.Messages=vt;Ue.Models=er;Ue.Beta=Re;var Pd=1024,Yn=class{constructor(e){this.settings=e;this.fetchSelector=new ft(e)}throwIfAborted(e){if(e!=null&&e.signal.aborted)throw new Error("Aborted")}isSupportedMediaType(e){return e==="image/jpeg"||e==="image/png"||e==="image/gif"||e==="image/webp"}getClient(e,t){return new Ue({apiKey:e.apiKey||"placeholder-key",baseURL:e.url||"https://api.anthropic.com",dangerouslyAllowBrowser:!0,fetch:t})}mapOptions(e){var r,n;let t={max_tokens:(r=e==null?void 0:e.max_tokens)!=null?r:Pd};return(e==null?void 0:e.temperature)!==void 0&&(t.temperature=e.temperature),(e==null?void 0:e.top_p)!==void 0&&(t.top_p=e.top_p),(n=e==null?void 0:e.stop)!=null&&n.length&&(t.stop_sequences=e.stop),t}convertImage(e){let t=e.match(/^data:(image\/[a-zA-Z0-9.+-]+);base64,(.+)$/);if(!t)return b.warn("Anthropic only supports base64-encoded image data URLs. Skipping image."),null;let r=t[1];if(!this.isSupportedMediaType(r))return b.warn("Anthropic only supports jpeg, png, gif or webp images. Skipping image."),null;let n=r,i=t[2];return{type:"image",source:{type:"base64",media_type:n,data:i}}}normalizeContent(e,t){let r=[];return typeof e=="string"?r.push({type:"text",text:e}):e.forEach(n=>{if(n.type==="text")r.push({type:"text",text:n.text});else if(n.type==="image_url"){let i=this.convertImage(n.image_url.url);i&&r.push(i)}}),t==null||t.forEach(n=>{let i=this.convertImage(n);i&&r.push(i)}),r.length?r:[{type:"text",text:""}]}toAnthropicContent(e){return e.length===1&&e[0].type==="text"?e[0].text:e}buildPayload(e){let t=[],r=[];if("messages"in e&&e.messages)e.messages.forEach(n=>{let i=this.normalizeContent(n.content,n.images);if(n.role==="system"){let o=i.filter(a=>a.type==="text").map(a=>a.text).join(`
`).trim();o&&t.push(o);return}r.push({role:n.role==="assistant"?"assistant":"user",content:this.toAnthropicContent(i)})});else if("prompt"in e){let n=this.normalizeContent(e.prompt||"",e.images);e.systemPrompt&&t.push(e.systemPrompt),r.push({role:"user",content:this.toAnthropicContent(n)})}else throw new Error("Either messages or prompt must be provided");if(!r.length)throw new Error("At least one message is required for generation");return{system:t.length?t.join(`
`):void 0,messages:r}}extractTextFromEvent(e){return e.type==="content_block_delta"&&"text"in e.delta&&e.delta.text?e.delta.text:null}async fetchModels({provider:e,abortController:t}){this.throwIfAborted(t);let r=await this.fetchSelector.request(e,async n=>{this.throwIfAborted(t);let i=this.getClient(e,n),o=[];for await(let a of i.models.list())this.throwIfAborted(t),a!=null&&a.id&&o.push(a.id);return o});return this.throwIfAborted(t),r}async embed(e){throw new Error("Embeddings are not supported for Anthropic providers")}async executeAnthropicGeneration(e,t,r,n){let{messages:i,system:o}=this.buildPayload(e),a=this.mapOptions(e.options);b.debug("Sending chat request to Anthropic");let c=await t.messages.create({...a,model:e.provider.model||"",messages:i,system:o,stream:!0},{signal:n==null?void 0:n.signal}),l="";for await(let u of c){this.throwIfAborted(n);let h=this.extractTextFromEvent(u);h&&(l+=h,r&&r(h,l))}return l}async execute(e){let t=e,r=t.abortController,n=t.onProgress;this.throwIfAborted(r);try{return await this.fetchSelector.execute(e.provider,async i=>{let o=this.getClient(e.provider,i);return this.executeAnthropicGeneration(e,o,(a,c)=>{n&&n(a,c),this.throwIfAborted(r)},r)})}catch(i){if(i.message==="Aborted")return Promise.reject(i);throw i}}};var ei=class{constructor(e,t){this.providers=[];this.version=3;this.plugin=t,this.providers=t.settings.providers||[],this.app=e,this.handlers={openai:new Je(t.settings),openrouter:new Je(t.settings),ollama:new _s(t.settings),"ollama-openwebui":new _s(t.settings),gemini:new Je(t.settings),lmstudio:new Je(t.settings),groq:new Je(t.settings),ai302:new Je(t.settings),anthropic:new Yn(t.settings)},this.cachedEmbeddingsService=new An(this.embedForce.bind(this))}async initEmbeddingsCache(){try{let e=this.app.appId||"default";await Kt.init(e)}catch(e){b.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],n={...e,input:r,chunks:r};return this.cachedEmbeddingsService.embedWithCache(n)}catch(t){let r=t instanceof Error?t.message:I.t("errors.failedToEmbed");throw new Zn.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 n=this.getHandler(t.type);if(!n||!n.fetchModels)throw new Error(`Handler not found or does not support fetchModels for provider type: ${t.type}`);return n.fetchModels({provider:t,abortController:r})}catch(t){let r=t instanceof Error?t.message:I.t("errors.failedToFetchModels");throw new Zn.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,n=Boolean(r.onProgress),i=Boolean(r.abortController);if(!(!n&&!i))return await t.execute(e);let a=new AbortController,c={data:[],end:[],error:[]};return t.execute({...e,abortController:a,onProgress:(u,h)=>{c.data.forEach(m=>m(u,h))}}).then(u=>{c.end.forEach(h=>h(u))}).catch(u=>{let h=u instanceof Error?u:new Error(String(u));c.error.forEach(m=>m(h))}),{onData(u){c.data.push(u)},onEnd(u){c.end.push(u)},onError(u){c.error.push(u)},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(n=>t.every(i=>n[i]===e[i]));return r?Promise.resolve(r):new Promise(n=>{new tr(this.app,`Migrate provider ${e.name}?`,async()=>{var i;(i=this.plugin.settings.providers)==null||i.push(e),await this.plugin.saveSettings(),n(e)},()=>{n(!1)}).open()})}checkCompatibility(e){if(e>this.version)throw new Zn.Notice(I.t("errors.pluginMustBeUpdatedFormatted")),new Error(I.t("errors.pluginMustBeUpdated"))}async retrieve(e){var m,f;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:n,totalChunks:i,documentChunkCounts:o}=this.processDocuments(e.documents);if(n.length===0)return[];let a=e.documents.length;(m=e.onProgress)==null||m.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:n.map(p=>p.content),abortController:e.abortController,onProgress:p=>{var _;if(t!=null&&t.signal.aborted)return;let y=p.length,g=n.slice(0,y),C=this.getProcessedDocs(g,o,e.documents);(_=e.onProgress)==null||_.call(e,{totalDocuments:a,totalChunks:i,processedDocuments:C,processedChunks:g,processingType:"embedding"})}})]).catch(p=>{var y,g;throw(g=(y=e.abortController)==null?void 0:y.signal)!=null&&g.aborted?new Error("Aborted"):p}),u=this.l2Normalize(c[0]),h=l.map(p=>this.l2Normalize(p));return(f=e.onProgress)==null||f.call(e,{totalDocuments:a,totalChunks:i,processedDocuments:this.getProcessedDocs(n,o,e.documents),processedChunks:n,processingType:"embedding"}),this.rankChunks(u,n,h)}processDocuments(e){var n;let t=[],r={};for(let i of e){let o=Wa(i.content),a=Va(o),c=((n=i.meta)==null?void 0:n.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 n={};for(let c of e){let l=((o=c.document.meta)==null?void 0:o.id)||c.document.content;n[l]=(n[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&&n[l]===t[l]&&i.push(c)}return i}rankChunks(e,t,r){let n=r.map(i=>this.dotProduct(e,i));return t.map((i,o)=>({document:i.document,score:n[o],content:i.content})).sort((i,o)=>o.score-i.score)}dotProduct(e,t){return e.reduce((r,n,i)=>r+n*t[i],0)}l2Normalize(e){let t=Math.sqrt(e.reduce((r,n)=>r+n*n,0))||1;return e.map(r=>r/t)}async cleanup(){try{Kt.isInitialized()&&await Kt.close()}catch(e){b.error("Error during cleanup:",e)}}};var Rc='<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>',Cc='<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>',kc='<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>',Mc='<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>',Tc='<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>',Oc='<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>',Fc='<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>',Nc='<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>',Bc='<g transform="translate(0,0) scale(4.1667)"><path d="M19.75 19.61l-2.23-4.9h-6.9l-2.23 4.9H5.66l7.9-17.22h2.02l7.9 17.22h-3.73zm-3.38-7.24l-2.23-4.9-2.23 4.9h4.46z"></path></g>';var ti=class extends Ie.Plugin{async onload(){await this.loadSettings(),(0,Ie.addIcon)("ai-providers-openai",Rc),(0,Ie.addIcon)("ai-providers-ollama",Oc),(0,Ie.addIcon)("ai-providers-ollama-openwebui",Fc),(0,Ie.addIcon)("ai-providers-gemini",Tc),(0,Ie.addIcon)("ai-providers-openrouter",Cc),(0,Ie.addIcon)("ai-providers-lmstudio",Mc),(0,Ie.addIcon)("ai-providers-groq",kc),(0,Ie.addIcon)("ai-providers-ai302",Nc),(0,Ie.addIcon)("ai-providers-anthropic",Bc);let t=new Ks(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({},No,await this.loadData()),b.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 ei(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 */