Files

43 lines
169 KiB
JavaScript
Raw Permalink Normal View History

2025-10-25 20:35:10 +08:00
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
var vi=Object.create;var hr=Object.defineProperty;var _i=Object.getOwnPropertyDescriptor;var Ai=Object.getOwnPropertyNames;var Pi=Object.getPrototypeOf,Ii=Object.prototype.hasOwnProperty;var xi=(n,e)=>{for(var t in e)hr(n,t,{get:e[t],enumerable:!0})},Xn=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ai(e))!Ii.call(n,s)&&s!==t&&hr(n,s,{get:()=>e[s],enumerable:!(r=_i(e,s))||r.enumerable});return n};var Ei=(n,e,t)=>(t=n!=null?vi(Pi(n)):{},Xn(e||!n||!n.__esModule?hr(t,"default",{value:n,enumerable:!0}):t,n)),Ci=n=>Xn(hr({},"__esModule",{value:!0}),n);var Pa={};xi(Pa,{default:()=>zr});module.exports=Ci(Pa);var le=require("obsidian");var Y=require("obsidian");var Gn={settings:{notice:'Dieses Plugin ist eine Konfigurationszentrale f\xFCr KI-Anbieter. Es macht selbst nichts, aber <a href="https://github.com/pfrankov/obsidian-ai-providers#required-by-plugins">andere Plugins</a> k\xF6nnen es nutzen, um KI-Einstellungen nicht mehrfach konfigurieren zu m\xFCssen.',configuredProviders:"KI-anbieter",addNewProvider:"Neuen anbieter hinzuf\xFCgen",addProvider:"Anbieter hinzuf\xFCgen",providerName:"Anbietername",providerNameDesc:"Geben Sie einen Namen f\xFCr diesen Anbieter ein",providerNamePlaceholder:"Mein anbieter",providerType:"Anbietertyp",providerTypeDesc:"W\xE4hlen Sie den KI-anbietertyp aus",providerUrl:"Anbieter-URL",providerUrlDesc:"Geben Sie die API-Endpunkt-URL ein",providerUrlPlaceholder:"https://...",apiKey:"API-Schl\xFCssel",apiKeyDesc:"Geben Sie Ihren API-Schl\xFCssel ein (falls erforderlich)",apiKeyPlaceholder:"sk-...",defaultModel:"Standardmodell",defaultModelDesc:"W\xE4hlen Sie das Standard-KI-Modell f\xFCr diesen Anbieter",save:"Speichern",cancel:"Abbrechen",options:"Optionen",delete:"L\xF6schen",duplicate:"Duplizieren",deleteConfirmation:'M\xF6chten Sie den Anbieter "{{name}}" wirklich l\xF6schen?',modelsUpdated:"Modellliste aktualisiert",refreshModelsList:"Modellliste aktualisieren",model:"Modell",modelDesc:"W\xE4hlen Sie das KI-Modell f\xFCr diesen Anbieter. <br>Oder <a>in den Textmodus wechseln</a>",modelTextDesc:"Geben Sie den KI-Modellnamen ein. <br>Oder <a>in den Dropdown-Modus wechseln</a>",modelTextOnlyDesc:"Geben Sie den KI-Modellnamen f\xFCr diesen Anbieter ein.",loadingModels:"Modelle werden geladen...",noModelsAvailable:"Keine Modelle verf\xFCgbar",editProvider:"Anbieter bearbeiten",developerSettings:"F\xFCr entwickler",developerSettingsDesc:"Zus\xE4tzliche Einstellungen f\xFCr Entwicklung und Debugging aktivieren",debugLogging:"Debug-protokollierung",debugLoggingDesc:"Detaillierte Protokollierung in der Konsole aktivieren",useNativeFetch:"Nativen fetch verwenden",useNativeFetchDesc:"Verwendet Fetch API anstelle von Obsidian f\xFCr besseres Debugging der Anfragen in DevTools"},modals:{confirm:"Best\xE4tigen",cancel:"Abbrechen"},errors:{failedToFetchModels:"Modelle konnten nicht abgerufen werden",failedToExecuteRequest:"Anfrage konnte nicht ausgef\xFChrt werden",failedToEmbed:"Fehler beim Generieren der Einbettungen",missingApiKey:"API-Schl\xFCssel ist erforderlich",missingUrl:"Anbieter-URL ist erforderlich",missingModel:"Modell muss ausgew\xE4hlt werden",pluginMustBeUpdated:"Plugin muss aktualisiert werden",pluginMustBeUpdatedFormatted:"Das Plugin muss aktualisiert werden, um mit dieser Version von AI Providers zu funktionieren",providerNameRequired:"Anbietername ist erforderlich",providerNameExists:'Ein Anbieter mit dem Namen "{{name}}" existiert bereits'}};var Qn={settings:{notice:"This plugin provides AI Provider integrations for other plugins. Configure your providers below.",configuredProviders:"AI providers",addNewProvider:"Add new provider",addProvider:"Add provider",providerName:"Provider name",providerNameDesc:"Enter a name for this provider",providerNamePlaceholder:"My provider",providerType:"Provider type",providerTypeDesc:"Select the type of AI provider",providerUrl:"Provider URL",providerUrlDesc:"Enter the API endpoint URL",providerUrlPlaceholder:"https://...",apiKey:"API key",apiKeyDesc:"Enter your API key (if required)",apiKeyPlaceholder:"sk-...",defaultModel:"Defau
`,"\r"]);fe.NEWLINE_REGEXP=/\r\n|[\n\r]/g;var J=class{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let r=!1;async function*s(){if(r)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let i=!1;try{for await(let o of Vi(e,t))if(!i){if(o.data.startsWith("[DONE]")){i=!0;continue}if(o.event===null){let a;try{a=JSON.parse(o.data)}catch(c){throw console.error("Could not parse message into JSON:",o.data),console.error("From chunk:",o.raw),c}if(a&&a.error)throw new $(void 0,a.error,void 0,void 0);yield a}else{let a;try{a=JSON.parse(o.data)}catch(c){throw console.error("Could not parse message into JSON:",o.data),console.error("From chunk:",o.raw),c}if(o.event=="error")throw new $(void 0,a.error,a.message,void 0);yield{event:o.event,data:a}}}i=!0}catch(o){if(o instanceof Error&&o.name==="AbortError")return;throw o}finally{i||t.abort()}}return new J(s,t)}static fromReadableStream(e,t){let r=!1;async function*s(){let o=new fe,a=ds(e);for await(let c of a)for(let l of o.decode(c))yield l;for(let c of o.flush())yield c}async function*i(){if(r)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let o=!1;try{for await(let a of s())o||a&&(yield JSON.parse(a));o=!0}catch(a){if(a instanceof Error&&a.name==="AbortError")return;throw a}finally{o||t.abort()}}return new J(i,t)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),s=i=>({next:()=>{if(i.length===0){let o=r.next();e.push(o),t.push(o)}return i.shift()}});return[new J(()=>s(e),this.controller),new J(()=>s(t),this.controller)]}toReadableStream(){let e=this,t,r=new TextEncoder;return new tn({async start(){t=e[Symbol.asyncIterator]()},async pull(s){try{let{value:i,done:o}=await t.next();if(o)return s.close();let a=r.encode(JSON.stringify(i)+`
`);s.enqueue(a)}catch(i){s.error(i)}},async cancel(){var s;await((s=t.return)==null?void 0:s.call(t))}})}};async function*Vi(n,e){if(!n.body)throw e.abort(),new A("Attempted to iterate over a response with no body");let t=new on,r=new fe,s=ds(n.body);for await(let i of zi(s))for(let o of r.decode(i)){let a=t.decode(o);a&&(yield a)}for(let i of r.flush()){let o=t.decode(i);o&&(yield o)}}async function*zi(n){let e=new Uint8Array;for await(let t of n){if(t==null)continue;let r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?new TextEncoder().encode(t):t,s=new Uint8Array(e.length+r.length);s.set(e),s.set(r,e.length),e=s;let i;for(;(i=Ki(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function Ki(n){for(let r=0;r<n.length-2;r++){if(n[r]===10&&n[r+1]===10||n[r]===13&&n[r+1]===13)return r+2;if(n[r]===13&&n[r+1]===10&&r+3<n.length&&n[r+2]===13&&n[r+3]===10)return r+4}return-1}var on=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,s]=Ji(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}};function Ji(n,e){let t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}function ds(n){if(n[Symbol.asyncIterator])return n;let e=n.getReader();return{async next(){try{let t=await e.read();return t!=null&&t.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var us=n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function",hs=n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&Xt(n),Xt=n=>n!=null&&typeof n=="object"&&typeof n.size=="number"&&typeof n.type=="string"&&typeof n.text=="function"&&typeof n.slice=="function"&&typeof n.arrayBuffer=="function",Xi=n=>hs(n)||us(n)||sn(n);async function ln(n,e,t){var s,i,o;if(n=await n,hs(n))return n;if(us(n)){let a=await n.blob();e||(e=(s=new URL(n.url).pathname.split(/[\\/]/).pop())!=null?s:"unknown_file");let c=Xt(a)?[await a.arrayBuffer()]:[a];return new br(c,e,t)}let r=await Gi(n);if(e||(e=(i=Yi(n))!=null?i:"unknown_file"),!(t!=null&&t.type)){let a=(o=r[0])==null?void 0:o.type;typeof a=="string"&&(t={...t,type:a})}return new br(r,e,t)}async function Gi(n){var t;let e=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)e.push(n);else if(Xt(n))e.push(await n.arrayBuffer());else if(Zi(n))for await(let r of n)e.push(r);else throw new Error(`Unexpected data type: ${typeof n}; constructor: ${(t=n==null?void 0:n.constructor)==null?void 0:t.name}; props: ${Qi(n)}`);return e}function Qi(n){return`[${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}function Yi(n){var e;return an(n.name)||an(n.filename)||((e=an(n.path))==null?void 0:e.split(/[\\/]/).pop())}var an=n=>{if(typeof n=="string")return n;if(typeof Buffer!="undefined"&&n instanceof Buffer)return String(n)},Zi=n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function",dn=n=>n&&typeof n=="object"&&n.body&&n[Symbol.toStringTag]==="MultipartBody";var ie=async n=>{let e=await fs(n.body);return rn(e,n)},fs=async n=>{let e=new en;return await Promise.all(Object.entries(n||{}).map(([t,r])=>cn(e,t,r))),e};var cn=async(n,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")n.append(e,String(t));else if(Xi(t)){let r=await ln(t);n.append(e,r)}else if(Array.isArray(t))await Promise.all(t.map(r=>cn(n,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,s])=>cn(n,`${e}[${r}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var to=function(n,e,t,r,s){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?s.call(n,t):s?s.value=t:e.set(n,t),t},ro=function(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)},Ar;async function bs(n){let{response:e}=n;if(n.options.stream)return gt("response",e.status,e.url,e.headers,e.body),n.options.__streamClass?n.options.__streamClass.fromSSEResponse(e,n.controller):J.fromSSEResponse(e,n.controller);if(e.status===204)return null;if(n.options.__binaryResponse)return e;let t=e.headers.get("content-type");if((t==null?void 0:t.includes("application
\r `.includes(n[r]);)r++};return o()},En=n=>_o(n,W.ALL^W.NUM);var Et=function(n,e,t,r,s){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?s.call(n,t):s?s.value=t:e.set(n,t),t},R=function(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)},j,Ie,Ct,De,Cn,Tr,Sn,Rn,On,kr,Mn,Rs,xe=class extends xt{constructor(e){super(),j.add(this),Ie.set(this,void 0),Ct.set(this,void 0),De.set(this,void 0),Et(this,Ie,e,"f"),Et(this,Ct,[],"f")}get currentChatCompletionSnapshot(){return R(this,De,"f")}static fromReadableStream(e){let t=new xe(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let s=new xe(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,t,r){var o;super._createChatCompletion;let s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),R(this,j,"m",Cn).call(this);let i=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let a of i)R(this,j,"m",Sn).call(this,a);if((o=i.controller.signal)!=null&&o.aborted)throw new H;return this._addChatCompletion(R(this,j,"m",kr).call(this))}async _fromReadableStream(e,t){var o;let r=t==null?void 0:t.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),R(this,j,"m",Cn).call(this),this._connected();let s=J.fromReadableStream(e,this.controller),i;for await(let a of s)i&&i!==a.id&&this._addChatCompletion(R(this,j,"m",kr).call(this)),R(this,j,"m",Sn).call(this,a),i=a.id;if((o=s.controller.signal)!=null&&o.aborted)throw new H;return this._addChatCompletion(R(this,j,"m",kr).call(this))}[(Ie=new WeakMap,Ct=new WeakMap,De=new WeakMap,j=new WeakSet,Cn=function(){this.ended||Et(this,De,void 0,"f")},Tr=function(t){let r=R(this,Ct,"f")[t.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},R(this,Ct,"f")[t.index]=r,r)},Sn=function(t){var s,i,o,a,c,l,d,u,h,m,f,v,g,O,b,C,N,P,D,T;if(this.ended)return;let r=R(this,j,"m",Rs).call(this,t);this._emit("chunk",t,r);for(let M of t.choices){let x=r.choices[M.index];M.delta.content!=null&&((s=x.message)==null?void 0:s.role)==="assistant"&&((i=x.message)!=null&&i.content)&&(this._emit("content",M.delta.content,x.message.content),this._emit("content.delta",{delta:M.delta.content,snapshot:x.message.content,parsed:x.message.parsed})),M.delta.refusal!=null&&((o=x.message)==null?void 0:o.role)==="assistant"&&((a=x.message)!=null&&a.refusal)&&this._emit("refusal.delta",{delta:M.delta.refusal,snapshot:x.message.refusal}),((c=M.logprobs)==null?void 0:c.content)!=null&&((l=x.message)==null?void 0:l.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(d=M.logprobs)==null?void 0:d.content,snapshot:(h=(u=x.logprobs)==null?void 0:u.content)!=null?h:[]}),((m=M.logprobs)==null?void 0:m.refusal)!=null&&((f=x.message)==null?void 0:f.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(v=M.logprobs)==null?void 0:v.refusal,snapshot:(O=(g=x.logprobs)==null?void 0:g.refusal)!=null?O:[]});let E=R(this,j,"m",Tr).call(this,x);x.finish_reason&&(R(this,j,"m",On).call(this,x),E.current_tool_call_index!=null&&R(this,j,"m",Rn).call(this,x,E.current_tool_call_index));for(let k of(b=M.delta.tool_calls)!=null?b:[])E.current_tool_call_index!==k.index&&(R(this,j,"m",On).call(this,x),E.current_tool_call_index!=null&&R(this,j,"m",Rn).call(this,x,E.current_too
${Fr(n)}`);if(x==null)throw new A(`missing choices[${u}].tool_calls[${T}].type
${Fr(n)}`);if(se==null)throw new A(`missing choices[${u}].tool_calls[${T}].function.name
${Fr(n)}`);if(S==null)throw new A(`missing choices[${u}].tool_calls[${T}].function.arguments
${Fr(n)}`);return{...k,id:E,type:x,function:{..._e,name:se,arguments:S}}})}}:{...m,message:{...O,content:f,role:b,refusal:(P=l.refusal)!=null?P:null},finish_reason:d,index:u,logprobs:h}}),created:s,model:i,object:"chat.completion",...o?{system_fingerprint:o}:{}};return Is(c,e)}function Fr(n){return JSON.stringify(n)}var Ee=class extends xe{static fromReadableStream(e){let t=new Ee(null);return t._run(()=>t._fromReadableStream(e)),t}static runFunctions(e,t,r){let s=new Ee(null),i={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runFunctions"}};return s._run(()=>s._runFunctions(e,t,i)),s}static runTools(e,t,r){let s=new Ee(t),i={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,i)),s}};var sr=class extends y{parse(e,t){return Es(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t==null?void 0:t.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap(r=>nr(r,e))}runFunctions(e,t){return e.stream?Ee.runFunctions(this._client,e,t):Fe.runFunctions(this._client,e,t)}runTools(e,t){return e.stream?Ee.runTools(this._client,e,t):Fe.runTools(this._client,e,t)}stream(e,t){return xe.createChatCompletion(this._client,e,t)}};var St=class extends y{constructor(){super(...arguments),this.completions=new sr(this._client)}};(function(n){n.Completions=sr})(St||(St={}));var w=function(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)},re=function(n,e,t,r,s){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?s.call(n,t):s?s.value=t:e.set(n,t),t},V,Tn,pe,Dr,ce,Ge,Rt,Xe,Lr,ne,Nr,Br,ar,ir,or,Os,Ms,Ts,ks,Fs,Ds,Ns,X=class extends It{constructor(){super(...arguments),V.add(this),Tn.set(this,[]),pe.set(this,{}),Dr.set(this,{}),ce.set(this,void 0),Ge.set(this,void 0),Rt.set(this,void 0),Xe.set(this,void 0),Lr.set(this,void 0),ne.set(this,void 0),Nr.set(this,void 0),Br.set(this,void 0),ar.set(this,void 0)}[(Tn=new WeakMap,pe=new WeakMap,Dr=new WeakMap,ce=new WeakMap,Ge=new WeakMap,Rt=new WeakMap,Xe=new WeakMap,Lr=new WeakMap,ne=new WeakMap,Nr=new WeakMap,Br=new WeakMap,ar=new WeakMap,V=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",s=>{let i=t.shift();i?i.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(let i of t)i.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(let i of t)i.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,o)=>t.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new X;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){var i;let r=t==null?void 0:t.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();let s=J.fromReadableStream(e,this.controller);for await(let o of s)w(this,V,"m",ir).call(this,o);if((i=s.controller.signal)!=null&&i.aborted)throw new H;return this._addRun(w(this,V,"m",or).call(this))}toReadableStream(){return new J(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,s,i){let o=new X;return o._run(()=>o._runToolAssistantStream(e,t,r,s,{...i,headers:{...i==null?void 0:i.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,r,s,i){var l;let o=i==null?void 0:i.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.cont
This is disabled by default, as it risks exposing your secret API credentials to attackers.
If you understand the risks and have appropriate mitigations in place,
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
`);super({baseURL:c.baseURL,timeout:(l=c.timeout)!=null?l:6e5,httpAgent:c.httpAgent,maxRetries:c.maxRetries,fetch:c.fetch}),this.completions=new et(this),this.chat=new Me(this),this.embeddings=new tt(this),this.files=new Be(this),this.images=new st(this),this.audio=new me(this),this.moderations=new ot(this),this.models=new Le(this),this.fineTuning=new we(this),this.beta=new oe(this),this.batches=new Te(this),this.uploads=new $e(this),this._options=c,this.apiKey=t,this.organization=r,this.project=s}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(e){return Yr(e,{arrayFormat:"brackets"})}};Ls=I;I.OpenAI=Ls;I.DEFAULT_TIMEOUT=6e5;I.OpenAIError=A;I.APIError=$;I.APIConnectionError=Re;I.APIConnectionTimeoutError=Oe;I.APIUserAbortError=H;I.NotFoundError=Wt;I.ConflictError=Vt;I.RateLimitError=Kt;I.BadRequestError=jt;I.AuthenticationError=qt;I.InternalServerError=Jt;I.PermissionDeniedError=Ht;I.UnprocessableEntityError=zt;I.toFile=ln;I.fileFromPath=wr;I.Completions=et;I.Chat=Me;I.Embeddings=tt;I.Files=Be;I.FileObjectsPage=rt;I.Images=st;I.Audio=me;I.Moderations=ot;I.Models=Le;I.ModelsPage=it;I.FineTuning=we;I.Beta=oe;I.Batches=Te;I.BatchesPage=ze;I.Uploads=$e;var $s=I;var Us=require("electron"),kn=require("obsidian");async function Fn(n,e={}){var s;delete e.headers["content-length"];let t={};this&&"controller"in this&&(t.controller=this.controller);let r=e.signal||((s=t.controller)==null?void 0:s.signal);return p.debug("electronFetch request:",{url:n,method:e.method||"GET",headers:e.headers,hasBody:!!e.body,platform:kn.Platform.isMobileApp?"mobile":"desktop"}),kn.Platform.isMobileApp?(p.debug("Using native fetch (mobile platform)"),fetch(n,{...e,signal:r})):new Promise((i,o)=>{let a=()=>{c.removeAllListeners(),p.debug("Request cleanup completed")},c=Us.remote.net.request({url:n,method:e.method||"GET"});if(e.headers&&Object.entries(e.headers).forEach(([l,d])=>{c.setHeader(l,d)}),r!=null&&r.aborted){p.debug("Request aborted before start"),c.abort(),o(new Error("Aborted"));return}r==null||r.addEventListener("abort",()=>{p.debug("Request aborted by controller"),a(),c.abort(),o(new Error("Aborted"))}),c.on("response",l=>{if(r!=null&&r.aborted){p.debug("Request aborted during response");return}p.debug("Response received:",{status:l.statusCode,headers:l.headers});let{readable:d,writable:u}=new TransformStream({transform(f,v){v.enqueue(new Uint8Array(f))}}),h=u.getWriter(),m={status:l.statusCode||200,headers:l.headers};i(new Response(d,m)),l.on("data",async f=>{try{await h.ready,await h.write(f),p.debug("Chunk received:",{size:f.length})}catch(v){p.error("Error writing chunk:",v),a(),h.abort(v)}}),l.on("end",async()=>{try{await h.ready,await h.close(),p.debug("Response stream completed")}catch(f){p.error("Error closing writer:",f)}finally{a()}}),l.on("error",f=>{p.error("Response error:",f),a(),h.abort(f),o(f)})}),c.on("error",l=>{p.error("Request error:",l),a(),o(l)}),e.body&&c.write(e.body),c.end(),p.debug("Request sent")})}var js=require("obsidian");var ee=async(n,e={})=>{delete e.headers["content-length"],p.debug("obsidianFetch request:",{url:n,method:e.method||"GET",headers:e.headers,hasBody:!!e.body});let t={url:n,method:e.method||"GET",headers:e.headers};e.body&&(t.body=e.body,p.debug("Request body prepared:",t.body));try{p.debug("Sending request via requestUrl");let r=await(0,js.requestUrl)(t);p.debug("Response received:",{status:r.status,headers:r.headers,contentLength:r.text.length});let s={status:r.status,headers:r.headers};return new Response(r.text,s)}catch(r){throw p.error("Request failed:",r),r}};var qs=require("obsidian");var Bo=["cors policy","cors error","blocked by cors","cross-origin","access-control-allow-origin","access-control-allow-methods","access-control-allow-headers","preflight request","connection error","network error","failed to fetch","typeerror: failed to fetch","net::err_failed
`)===0?r.substr(1,r.length):r}).forEach(function(r){var s=r.split(":"),i=s.shift().trim();if(i){var o=s.join(":").trim();try{e.append(i,o)}catch(a){console.warn("Response "+a.message)}}}),e}Ks.call(ct.prototype);function ve(n,e){if(!(this instanceof ve))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(e||(e={}),this.type="default",this.status=e.status===void 0?200:e.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=e.statusText===void 0?"":""+e.statusText,this.headers=new q(e.headers),this.url=e.url||"",this._initBody(n)}Ks.call(ve.prototype);ve.prototype.clone=function(){return new ve(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new q(this.headers),url:this.url})};ve.error=function(){var n=new ve(null,{status:200,statusText:""});return n.ok=!1,n.status=0,n.type="error",n};var zo=[301,302,303,307,308];ve.redirect=function(n,e){if(zo.indexOf(e)===-1)throw new RangeError("Invalid status code");return new ve(null,{status:e,headers:{location:n}})};var at=z.DOMException;try{new at}catch(n){at=function(e,t){this.message=e,this.name=t;var r=Error(e);this.stack=r.stack},at.prototype=Object.create(Error.prototype),at.prototype.constructor=at}function Js(n,e){return new Promise(function(t,r){var s=new ct(n,e);if(s.signal&&s.signal.aborted)return r(new at("Aborted","AbortError"));var i=new XMLHttpRequest;function o(){i.abort()}i.onload=function(){var l={statusText:i.statusText,headers:Vo(i.getAllResponseHeaders()||"")};s.url.indexOf("file://")===0&&(i.status<200||i.status>599)?l.status=200:l.status=i.status,l.url="responseURL"in i?i.responseURL:l.headers.get("X-Request-URL");var d="response"in i?i.response:i.responseText;setTimeout(function(){t(new ve(d,l))},0)},i.onerror=function(){setTimeout(function(){r(new TypeError("Network request failed"))},0)},i.ontimeout=function(){setTimeout(function(){r(new TypeError("Network request timed out"))},0)},i.onabort=function(){setTimeout(function(){r(new at("Aborted","AbortError"))},0)};function a(l){try{return l===""&&z.location.href?z.location.href:l}catch(d){return l}}if(i.open(s.method,a(s.url),!0),s.credentials==="include"?i.withCredentials=!0:s.credentials==="omit"&&(i.withCredentials=!1),"responseType"in i&&(G.blob?i.responseType="blob":G.arrayBuffer&&(i.responseType="arraybuffer")),e&&typeof e.headers=="object"&&!(e.headers instanceof q||z.Headers&&e.headers instanceof z.Headers)){var c=[];Object.getOwnPropertyNames(e.headers).forEach(function(l){c.push(Ut(l)),i.setRequestHeader(l,Nn(e.headers[l]))}),s.headers.forEach(function(l,d){c.indexOf(d)===-1&&i.setRequestHeader(d,l)})}else s.headers.forEach(function(l,d){i.setRequestHeader(d,l)});s.signal&&(s.signal.addEventListener("abort",o),i.onreadystatechange=function(){i.readyState===4&&s.signal.removeEventListener("abort",o)}),i.send(typeof s._bodyInit=="undefined"?null:s._bodyInit)})}Js.polyfill=!0;z.fetch||(z.fetch=Js,z.Headers=q,z.Request=ct,z.Response=ve);var Ko="0.5.10",Jo=Object.defineProperty,Xo=(n,e,t)=>e in n?Jo(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Ln=(n,e,t)=>(Xo(n,typeof e!="symbol"?e+"":e,t),t),cr=class extends Error{constructor(e,t){super(e),this.error=e,this.status_code=t,this.name="ResponseError",Error.captureStackTrace&&Error.captureStackTrace(this,cr)}},Un=class{constructor(e,t,r){Ln(this,"abortController"),Ln(this,"itr"),Ln(this,"doneCallback"),this.abortController=e,this.itr=t,this.doneCallback=r}abort(){this.abortController.abort()}async*[Symbol.asyncIterator](){for await(let e of this.itr){if("error"in e)throw new Error(e.error);if(yield e,e.done||e.status==="success"){this.doneCallback();return}}throw new Error("Did not receive done or success response in stream.")}},$r=async n=>{var r;if(n.ok)return;let e=`Error ${n.status}: ${n.statusText}`,t=null;if((r=n.headers.get("content-type"))!=null&&r.includes("application/json"))try{t=await n.j
`);t=(s=a.pop())!=null?s:"";for(let c of a)try{yield JSON.parse(c)}catch(l){console.warn("invalid json: ",c)}}for(let i of t.split(`
`).filter(o=>o!==""))try{yield JSON.parse(i)}catch(o){console.warn("invalid json: ",i)}},Zo=n=>{if(!n)return"http://127.0.0.1:11434";let e=n.includes("://");n.startsWith(":")&&(n=`http://127.0.0.1${n}`,e=!0),e||(n=`http://${n}`);let t=new URL(n),r=t.port;r||(e?r=t.protocol==="https:"?"443":"80":r="11434");let s=`${t.protocol}//${t.hostname}:${r}${t.pathname}`;return s.endsWith("/")&&(s=s.slice(0,-1)),s},ea=Object.defineProperty,ta=(n,e,t)=>e in n?ea(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,$n=(n,e,t)=>(ta(n,typeof e!="symbol"?e+"":e,t),t),jn=class{constructor(e){var t,r;$n(this,"config"),$n(this,"fetch"),$n(this,"ongoingStreamedRequests",[]),this.config={host:"",headers:e==null?void 0:e.headers},e!=null&&e.proxy||(this.config.host=Zo((t=e==null?void 0:e.host)!=null?t:"http://127.0.0.1:11434")),this.fetch=(r=e==null?void 0:e.fetch)!=null?r:fetch}abort(){for(let e of this.ongoingStreamedRequests)e.abort();this.ongoingStreamedRequests.length=0}async processStreamableRequest(e,t){var i;t.stream=(i=t.stream)!=null?i:!1;let r=`${this.config.host}/api/${e}`;if(t.stream){let o=new AbortController,a=await Ue(this.fetch,r,t,{signal:o.signal,headers:this.config.headers});if(!a.body)throw new Error("Missing body");let c=Yo(a.body),l=new Un(o,c,()=>{let d=this.ongoingStreamedRequests.indexOf(l);d>-1&&this.ongoingStreamedRequests.splice(d,1)});return this.ongoingStreamedRequests.push(l),l}return await(await Ue(this.fetch,r,t,{headers:this.config.headers})).json()}async encodeImage(e){if(typeof e!="string"){let t=new Uint8Array(e),r="",s=t.byteLength;for(let i=0;i<s;i++)r+=String.fromCharCode(t[i]);return btoa(r)}return e}async generate(e){return e.images&&(e.images=await Promise.all(e.images.map(this.encodeImage.bind(this)))),this.processStreamableRequest("generate",e)}async chat(e){if(e.messages)for(let t of e.messages)t.images&&(t.images=await Promise.all(t.images.map(this.encodeImage.bind(this))));return this.processStreamableRequest("chat",e)}async create(e){return this.processStreamableRequest("create",{name:e.model,stream:e.stream,modelfile:e.modelfile,quantize:e.quantize})}async pull(e){return this.processStreamableRequest("pull",{name:e.model,stream:e.stream,insecure:e.insecure})}async push(e){return this.processStreamableRequest("push",{name:e.model,stream:e.stream,insecure:e.insecure})}async delete(e){return await Qo(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:"success"}}async copy(e){return await Ue(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:"success"}}async list(){return await(await Xs(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await Ue(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await Ue(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await Ue(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await Xs(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}},Bu=new jn;var je=Ei(require("fs"),1),lt=require("path"),Qs=require("crypto"),Ys=require("os");var lr=class extends jn{async encodeImage(e){if(typeof e!="string")return Buffer.from(e).toString("base64");try{if(je.default.existsSync(e)){let t=await je.promises.readFile((0,lt.resolve)(e));return Buffer.from(t).toString("base64")}}catch(t){}return e}async parseModelfile(e,t=process.cwd()){let r=[],s=e.split(`
`);for(let i of s){let[o,a]=i.split(" ",2);if(["FROM","ADAPTER"].includes(o.toUpperCase())){let c=this.resolvePath(a.trim(),t);await this.fileExists(c)?r.push(`${o} @${await this.createBlob(c)}`):r.push(`${o} ${a}`)}else r.push(i)}return r.join(`
`)}resolvePath(e,t){return e.startsWith("~")?(0,lt.join)((0,Ys.homedir)(),e.slice(1)):(0,lt.resolve)(t,e)}async fileExists(e){try{return await je.promises.access(e),!0}catch(t){return!1}}async createBlob(e){if(typeof ReadableStream=="undefined")throw new Error("Streaming uploads are not supported in this environment.");let t=(0,je.createReadStream)(e),s=`sha256:${await new Promise((i,o)=>{let a=(0,Qs.createHash)("sha256");t.on("data",c=>a.update(c)),t.on("end",()=>i(a.digest("hex"))),t.on("error",o)})}`;try{await Gs(this.fetch,`${this.config.host}/api/blobs/${s}`)}catch(i){if(i instanceof Error&&i.message.includes("404")){let o=new ReadableStream({start(a){t.on("data",c=>{a.enqueue(c)}),t.on("end",()=>{a.close()}),t.on("error",c=>{a.error(c)})}});await Ue(this.fetch,`${this.config.host}/api/blobs/${s}`,o)}else throw i}return s}async create(e){let t="";if(e.path)t=await je.promises.readFile(e.path,{encoding:"utf8"}),t=await this.parseModelfile(t,(0,lt.dirname)(e.path));else if(e.modelfile)t=await this.parseModelfile(e.modelfile);else throw new Error("Must provide either path or modelfile to create a model");return e.modelfile=t,e.stream?super.create(e):super.create(e)}},ju=new lr;var ra=2.5,jr=2048,Zs=2048,na=1.2,dr=class{constructor(e){this.settings=e;this.modelInfoCache=new Map,this.fetchSelector=new $t(e)}getClient(e,t){let r={host:e.url,fetch:t};return e.apiKey&&(r.headers=r.headers||{},r.headers.Authorization=`Bearer ${e.apiKey}`),new lr(r)}getDefaultModelInfo(){return{contextLength:0,lastContextLength:jr}}async getCachedModelInfo(e,t){let r=`${e.url}_${t}`,s=this.modelInfoCache.get(r);if(s)return s;let i=this.getClient(e,this.settings.useNativeFetch?fetch:ee);try{let o={model:t};e.type==="ollama-openwebui"&&(o={name:t});let a=await i.show(o),c=this.getDefaultModelInfo(),l=Object.entries(a.model_info).find(([d,u])=>(d.endsWith(".context_length")||d==="num_ctx")&&typeof u=="number"&&u>0);return l&&typeof l[1]=="number"&&(c.contextLength=l[1]),this.modelInfoCache.set(r,c),c}catch(o){return p.error("Failed to fetch model info:",o),this.getDefaultModelInfo()}}setModelInfoLastContextLength(e,t,r){let s=`${e.url}_${t}`,i=this.modelInfoCache.get(s);i&&this.modelInfoCache.set(s,{...i,lastContextLength:r||i.lastContextLength})}async fetchModels({provider:e,abortController:t}){if(t!=null&&t.signal.aborted)throw new Error("Aborted");let r=async i=>{if(t!=null&&t.signal.aborted)throw new Error("Aborted");let o=this.getClient(e,i);return t==null||t.signal.addEventListener("abort",()=>{o.abort()}),(await o.list()).models.map(c=>c.name)},s=await this.fetchSelector.request(e,r);if(t!=null&&t.signal.aborted)throw new Error("Aborted");return s}optimizeContext(e,t,r,s){let i=Math.ceil(e/ra);if(i<=t)return{num_ctx:t>r?t:void 0,shouldUpdate:!1};let o=Math.min(Math.ceil(Math.max(i,r)*na),s),a=o>t;return{num_ctx:o,shouldUpdate:a}}prepareChatMessages(e){var s;let t=[],r=[];if("messages"in e&&e.messages)e.messages.forEach(i=>{var o;if(typeof i.content=="string")t.push({role:i.role,content:i.content});else{let a=i.content.filter(c=>c.type==="text").map(c=>c.type==="text"?c.text:"").join(`
`);i.content.filter(c=>c.type==="image_url").forEach(c=>{var l;c.type==="image_url"&&((l=c.image_url)!=null&&l.url)&&r.push(c.image_url.url)}),t.push({role:i.role,content:a})}(o=i.images)!=null&&o.length&&r.push(...i.images)});else if("prompt"in e)e.systemPrompt&&t.push({role:"system",content:e.systemPrompt}),t.push({role:"user",content:e.prompt}),(s=e.images)!=null&&s.length&&r.push(...e.images);else throw new Error("Either messages or prompt must be provided");return{chatMessages:t,extractedImages:r}}async executeOllamaGeneration(e,t,r,s){var h,m;let i=await this.getCachedModelInfo(e.provider,e.provider.model||"").catch(f=>(p.error("Failed to get model info:",f),null)),{chatMessages:o,extractedImages:a}=this.prepareChatMessages(e),c=a.length>0?a.map(f=>f.replace(/^data:image\/(.*?);base64,/,"")):void 0,l={};if(!(c!=null&&c.length)){let f=o.reduce((O,b)=>O+b.content.length,0),{num_ctx:v,shouldUpdate:g}=this.optimizeContext(f,(i==null?void 0:i.lastContextLength)||jr,jr,(i==null?void 0:i.contextLength)||jr);v&&(l.num_ctx=v),g&&this.setModelInfoLastContextLength(e.provider,e.provider.model||"",v)}if(e.options&&Object.assign(l,e.options),c!=null&&c.length){let f=o.map(v=>v.role).lastIndexOf("user");f!==-1?o[f]={...o[f],images:c}:o.length>0?o[o.length-1]={...o[o.length-1],images:c}:o.push({role:"user",content:"",images:c})}p.debug("Sending chat request to Ollama");let d=await t.chat({model:e.provider.model||"",messages:o,stream:!0,options:{...l}}),u="";for await(let f of d){if(s!=null&&s.signal.aborted)throw new Error("Aborted");let v=(h=f.message)==null?void 0:h.content;v&&(u+=v,r&&r(v,u)),f.done&&f.total_duration>0&&this.setModelInfoLastContextLength(e.provider,e.provider.model||"",(m=f.context)==null?void 0:m.length)}return u}async embed(e){var l;let t=(l=e.input)!=null?l:e.text;if(!t)throw new Error("Either input or text parameter must be provided");let r=e.abortController;if(r!=null&&r.signal.aborted)throw new Error("Aborted");let s=await this.getCachedModelInfo(e.provider,e.provider.model||""),i=Array.isArray(t)?Math.max(...t.map(d=>d.length)):t.length,{num_ctx:o,shouldUpdate:a}=this.optimizeContext(i,s.lastContextLength||Zs,Zs,s.contextLength);a&&this.setModelInfoLastContextLength(e.provider,e.provider.model||"",o);let c=async d=>{let u=this.getClient(e.provider,d);r==null||r.signal.addEventListener("abort",()=>{u.abort()});let h=Array.isArray(t)?t:[t],m=[],f=[];for(let v of h){if(r!=null&&r.signal.aborted)throw new Error("Aborted");let g=await u.embed({model:e.provider.model||"",input:v,options:{num_ctx:o}});if(m.push(g.embeddings[0]),p.debug("Embed response:",g),f.push(v),e.onProgress&&e.onProgress([...f]),r!=null&&r.signal.aborted)throw new Error("Aborted")}return m};return this.fetchSelector.request(e.provider,c)}async execute(e){let t=e,r=t.abortController,s=t.onProgress;if(r!=null&&r.signal.aborted)return Promise.reject(new Error("Aborted"));try{return await this.fetchSelector.execute(e.provider,async i=>{let o=this.getClient(e.provider,i);if(r==null||r.signal.addEventListener("abort",()=>{o.abort()}),r!=null&&r.signal.aborted)throw new Error("Aborted");return this.executeOllamaGeneration(e,o,(a,c)=>{if(s&&s(a,c),r!=null&&r.signal.aborted)throw new Error("Aborted")},r)})}catch(i){let o=i;if(o.message==="Aborted")return Promise.reject(o);throw o}}};var Wn=(n,e)=>e.some(t=>n instanceof t),ei,ti;function sa(){return ei||(ei=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function ia(){return ti||(ti=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var Vn=new WeakMap,qn=new WeakMap,qr=new WeakMap;function oa(n){let e=new Promise((t,r)=>{let s=()=>{n.removeEventListener("success",i),n.removeEventListener("error",o)},i=()=>{t(dt(n.result)),s()},o=()=>{r(n.error),s()};n.addEventListener("success",i),n.addEventListener("error",o)});return qr.set(e,n),e}function aa(n){if(Vn.has(n))return;let e=new Promise((t,r)=>{let s=()=>{n.removeEventListener("complete",i),n.removeEventListener("error",o),n.removeEventListener("abort",o)},i=()=>{t(),s()},o=()=>{r(n.err
`).replace(/[ \t]+$/gm,"").replace(/\n+$/,"")}function di(n){return n.length<ur?[n.trim()]:(p.debug("Splitting content",{contentLength:n.length}),n.split(/^---$/m).flatMap(t=>ga(t.trim())).flatMap(t=>ya(t)).map(t=>t.trim()).filter(t=>t.length>0))}function ga(n){let e=/^(#{1,6})\s+(.+)$/gm,t=[],r=0,s="",i;for(;(i=e.exec(n))!==null;)r<i.index&&t.push(s+n.slice(r,i.index).trim()),s=i[0]+`
`,r=e.lastIndex;return r<n.length&&t.push(s+n.slice(r).trim()),t.filter(o=>o.length>0)}function ya(n){let t=n.split(`
`).reduce(ba,{chunks:[],currentChunk:"",inList:!1,lastNonListText:""}),r=t.currentChunk?[...t.chunks,t.currentChunk.trim()]:t.chunks.map(i=>i.trim()),s=[];for(let i=0;i<r.length;i++){let o=r[i];if(/^#{1,6}\s+.+$/.test(o.trim())&&o.trim().split(`
`).length===1&&i<r.length-1){let c=r[i+1];s.push(o+`
`+c),i++}else s.push(o)}return s}function ba(n,e){let t=/^(\s*[-*+]|\s*\d+\.)/.test(e);return/^(#{1,6}\s|[*_]{2}).+/.test(e)?wa(n,e):t?va(n,e):n.inList&&!e.trim()?{...n,currentChunk:n.currentChunk+`
`+e}:_a(n,e)}function wa(n,e){let{chunks:t,currentChunk:r}=n;return{chunks:r?[...t,r.trim()]:t,currentChunk:e,inList:!1,lastNonListText:e}}function va(n,e){let{chunks:t,currentChunk:r,inList:s,lastNonListText:i}=n;return!s&&r.length+e.length<=ur?{...n,currentChunk:r+`
`+e,inList:!0}:s?{...n,currentChunk:r+`
`+e}:{chunks:r?[...t,r.trim()]:t,currentChunk:i+`
`+e,inList:!0,lastNonListText:i}}function _a(n,e){let{chunks:t,currentChunk:r,lastNonListText:s}=n;if(e.length>ur){let o=e,a=[...t];for(r&&a.push(r.trim());o.length>0;){let c=Aa(o,ur);a.push(o.slice(0,c).trim()),o=o.slice(c).trim()}return{chunks:a,currentChunk:"",inList:!1,lastNonListText:e}}let i=r+(r?`
`:"")+e;return i.length>ur?{chunks:[...t,r.trim()],currentChunk:e,inList:!1,lastNonListText:e.trim()?e:s}:{...n,currentChunk:i,inList:!1,lastNonListText:e.trim()?e:s}}function Aa(n,e){if(n.length<=e)return n.length;let t=e;for(;t>0&&!/\s/.test(n[t]);)t--;return t>0?t:e}var Vr=class{constructor(e,t){this.providers=[];this.version=3;this.plugin=t,this.providers=t.settings.providers||[],this.app=e,this.handlers={openai:new Se(t.settings),openrouter:new Se(t.settings),ollama:new dr(t.settings),"ollama-openwebui":new dr(t.settings),gemini:new Se(t.settings),lmstudio:new Se(t.settings),groq:new Se(t.settings),ai302:new Se(t.settings)},this.cachedEmbeddingsService=new Hr(this.embedForce.bind(this))}async initEmbeddingsCache(){try{let e=this.app.appId||"default";await ut.init(e)}catch(e){p.error("Failed to initialize embeddings cache:",e)}}getHandler(e){return this.handlers[e]}async embedForce(e){let t=this.getHandler(e.provider.type);if(!t)throw new Error(`Handler not found for provider type: ${e.provider.type}`);return t.embed(e)}async embed(e){try{if(!e.input)throw new Error("Input is required for embedding");let t=e.abortController;if(t!=null&&t.signal.aborted)throw new Error("Aborted");let r=Array.isArray(e.input)?e.input:[e.input],s={...e,input:r,chunks:r};return this.cachedEmbeddingsService.embedWithCache(s)}catch(t){let r=t instanceof Error?t.message:_.t("errors.failedToEmbed");throw new Wr.Notice(r),t}}async fetchModels(e){try{let t="provider"in e?e.provider:e,r="abortController"in e?e.abortController:void 0;if(r!=null&&r.signal.aborted)throw new Error("Aborted");let s=this.getHandler(t.type);if(!s||!s.fetchModels)throw new Error(`Handler not found or does not support fetchModels for provider type: ${t.type}`);return s.fetchModels({provider:t,abortController:r})}catch(t){let r=t instanceof Error?t.message:_.t("errors.failedToFetchModels");throw new Wr.Notice(r),t}}async execute(e){let t=this.getHandler(e.provider.type);if(!t)throw new Error(`Handler not found for provider type: ${e.provider.type}`);let r=e,s=Boolean(r.onProgress),i=Boolean(r.abortController);if(!(!s&&!i))return await t.execute(e);let a=new AbortController,c={data:[],end:[],error:[]};return t.execute({...e,abortController:a,onProgress:(d,u)=>{c.data.forEach(h=>h(d,u))}}).then(d=>{c.end.forEach(u=>u(d))}).catch(d=>{let u=d instanceof Error?d:new Error(String(d));c.error.forEach(h=>h(u))}),{onData(d){c.data.push(d)},onEnd(d){c.end.push(d)},onError(d){c.error.push(d)},abort:()=>{a.abort()}}}async migrateProvider(e){let t=["type","apiKey","url","model"];this.plugin.settings.providers=this.plugin.settings.providers||[];let r=this.plugin.settings.providers.find(s=>t.every(i=>s[i]===e[i]));return r?Promise.resolve(r):new Promise(s=>{new ht(this.app,`Migrate provider ${e.name}?`,async()=>{var i;(i=this.plugin.settings.providers)==null||i.push(e),await this.plugin.saveSettings(),s(e)},()=>{s(!1)}).open()})}checkCompatibility(e){if(e>this.version)throw new Wr.Notice(_.t("errors.pluginMustBeUpdatedFormatted")),new Error(_.t("errors.pluginMustBeUpdated"))}async retrieve(e){var h,m;let t=e.abortController;if(t!=null&&t.signal.aborted)throw new Error("Aborted");if(!e.query)return[];if(!e.documents||e.documents.length===0)return[];if(!this.getHandler(e.embeddingProvider.type))throw new Error(`Handler not found for provider type: ${e.embeddingProvider.type}`);let{chunks:s,totalChunks:i,documentChunkCounts:o}=this.processDocuments(e.documents);if(s.length===0)return[];let a=e.documents.length;(h=e.onProgress)==null||h.call(e,{totalDocuments:a,totalChunks:i,processedDocuments:[],processedChunks:[],processingType:"embedding"});let[c,l]=await Promise.all([this.embed({provider:e.embeddingProvider,input:e.query,abortController:e.abortController}),this.embed({provider:e.embeddingProvider,input:s.map(f=>f.content),abortController:e.abortController,onProgress:f=>{var b;if(t!=null&&t.signal.aborted)return;let v=f.length,g=s.slice(0,v),O=this.getProcessedDocs(g,o,e.documents);(b=e.onProgress)==null||b.call(e,{totalDocuments:a,totalChunks:i,processedDocuments:O,processedChunks:g,p
/* nosourcemap */