Files

575 lines
2.0 MiB
JavaScript
Raw Permalink Normal View History

2025-10-25 20:35:10 +08:00
"use strict";var w5=Object.defineProperty;var b5=(t,e,r)=>e in t?w5(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var Ze=(t,e,r)=>(b5(t,typeof e!="symbol"?e+"":e,r),r);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const Qe=require("obsidian"),Xh=require("crypto"),gd=require("fs"),K5=require("path"),qr=require("stream"),rf=require("http"),M0=require("url"),f5=require("https"),Gi=require("zlib"),af=require("util"),Q5=require("os");function W5(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const r in t)if(r!=="default"){const a=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,a.get?a:{enumerable:!0,get:()=>t[r]})}}return e.default=t,Object.freeze(e)}const v5=W5(Q5);function F5(t,e){const r=Object.keys(e).map(a=>y5(t,a,e[a]));return r.length===1?r[0]:function(){r.forEach(a=>a())}}function y5(t,e,r){const a=t[e],n=t.hasOwnProperty(e);let i=r(a);return a&&Object.setPrototypeOf(i,a),Object.setPrototypeOf(l,i),t[e]=l,s;function l(...o){return i===a&&t[e]===l&&s(),i.apply(this,o)}function s(){t[e]===l&&(n?t[e]=a:delete t[e]),i!==a&&(i=a,Object.setPrototypeOf(l,a||Function))}}function R5(t){for(var e=t.length,r=0,a=0;a<e;){var n=t.charCodeAt(a++);if(n&4294967168)if(!(n&4294965248))r+=2;else{if(n>=55296&&n<=56319&&a<e){var i=t.charCodeAt(a);(i&64512)===56320&&(++a,n=((n&1023)<<10)+(i&1023)+65536)}n&4294901760?r+=4:r+=3}else{r++;continue}}return r}function E5(t,e,r){for(var a=t.length,n=r,i=0;i<a;){var l=t.charCodeAt(i++);if(l&4294967168)if(!(l&4294965248))e[n++]=l>>6&31|192;else{if(l>=55296&&l<=56319&&i<a){var s=t.charCodeAt(i);(s&64512)===56320&&(++i,l=((l&1023)<<10)+(s&1023)+65536)}l&4294901760?(e[n++]=l>>18&7|240,e[n++]=l>>12&63|128,e[n++]=l>>6&63|128):(e[n++]=l>>12&15|224,e[n++]=l>>6&63|128)}else{e[n++]=l;continue}e[n++]=l&63|128}}var G5=new TextEncoder,S5=50;function Z5(t,e,r){G5.encodeInto(t,e.subarray(r))}function X5(t,e,r){t.length>S5?Z5(t,e,r):E5(t,e,r)}var H5=4096;function nf(t,e,r){for(var a=e,n=a+r,i=[],l="";a<n;){var s=t[a++];if(!(s&128))i.push(s);else if((s&224)===192){var o=t[a++]&63;i.push((s&31)<<6|o)}else if((s&240)===224){var o=t[a++]&63,d=t[a++]&63;i.push((s&31)<<12|o<<6|d)}else if((s&248)===240){var o=t[a++]&63,d=t[a++]&63,u=t[a++]&63,c=(s&7)<<18|o<<12|d<<6|u;c>65535&&(c-=65536,i.push(c>>>10&1023|55296),c=56320|c&1023),i.push(c)}else i.push(s);i.length>=H5&&(l+=String.fromCharCode.apply(String,i),i.length=0)}return i.length>0&&(l+=String.fromCharCode.apply(String,i)),l}var V5=new TextDecoder,Y5=200;function N5(t,e,r){var a=t.subarray(e,e+r);return V5.decode(a)}function L5(t,e,r){return r>Y5?N5(t,e,r):nf(t,e,r)}var ep=function(){function t(e,r){this.type=e,this.data=r}return t}(),T5=globalThis&&globalThis.__extends||function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(a,n){a.__proto__=n}||function(a,n){for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(a[i]=n[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function a(){this.constructor=e}e.prototype=r===null?Object.create(r):(a.prototype=r.prototype,new a)}}(),ya=function(t){T5(e,t);function e(r){var a=t.call(this,r)||this,n=Object.create(e.prototype);return Object.setPrototypeOf(a,n),Object.defineProperty(a,"name",{configurable:!0,enumerable:!1,value:e.name}),a}return e}(Error),go=4294967295;function k5(t,e,r){var a=r/4294967296,n=r;t.setUint32(e,a),t.setUint32(e+4,n)}function lf(t,e,r){var a=Math.floor(r/4294967296),n=r;t.setUint32(e,a),t.setUint32(e+4,n)}function sf(t,e){var r=t.getInt32(e),a=t.getUint32(e+4);return r*4294967296+a}function U5(t,e){var r=t.getUint32(e),a=t.getUint32(e+4);return r*4294967296+a}var _5=-1,I5=4294967296-1,D5=17179869184-1;function M5(t){var e=t.sec,r=t.nsec;if(e>=0&&r>=0&&e<=D5)if(r===0&&e<=I5){var a=new Uint8Array(4),n=new DataView(a.buffer);return n.setUint32(0,e),a}else{var i=e/4294967296,l=e&4294967295,a=new Uint8Array(8),n=new DataView(a.buffe
* https://github.com/Starcounter-Jack/JSON-Patch
* (c) 2017-2022 Joachim Wester
* MIT licensed
*/var my=globalThis&&globalThis.__extends||function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(a,n){a.__proto__=n}||function(a,n){for(var i in n)n.hasOwnProperty(i)&&(a[i]=n[i])},t(e,r)};return function(e,r){t(e,r);function a(){this.constructor=e}e.prototype=r===null?Object.create(r):(a.prototype=r.prototype,new a)}}(),gy=Object.prototype.hasOwnProperty;function Ag(t,e){return gy.call(t,e)}function hg(t){if(Array.isArray(t)){for(var e=new Array(t.length),r=0;r<e.length;r++)e[r]=""+r;return e}if(Object.keys)return Object.keys(t);var a=[];for(var n in t)Ag(t,n)&&a.push(n);return a}function Ur(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function Bg(t){for(var e=0,r=t.length,a;e<r;){if(a=t.charCodeAt(e),a>=48&&a<=57){e++;continue}return!1}return!0}function xi(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function df(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function Cg(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(var e=0,r=t.length;e<r;e++)if(Cg(t[e]))return!0}else if(typeof t=="object"){for(var a=hg(t),n=a.length,i=0;i<n;i++)if(Cg(t[a[i]]))return!0}}return!1}function N4(t,e){var r=[t];for(var a in e){var n=typeof e[a]=="object"?JSON.stringify(e[a],null,2):e[a];typeof n<"u"&&r.push(a+": "+n)}return r.join(`
`)}var uf=function(t){my(e,t);function e(r,a,n,i,l){var s=this.constructor,o=t.call(this,N4(r,{name:a,index:n,operation:i,tree:l}))||this;return o.name=a,o.index=n,o.operation=i,o.tree=l,Object.setPrototypeOf(o,s.prototype),o.message=N4(r,{name:a,index:n,operation:i,tree:l}),o}return e}(Error),Zt=uf,Ay=Ur,ps={add:function(t,e,r){return t[e]=this.value,{newDocument:r}},remove:function(t,e,r){var a=t[e];return delete t[e],{newDocument:r,removed:a}},replace:function(t,e,r){var a=t[e];return t[e]=this.value,{newDocument:r,removed:a}},move:function(t,e,r){var a=Kc(r,this.path);a&&(a=Ur(a));var n=ul(r,{op:"remove",path:this.from}).removed;return ul(r,{op:"add",path:this.path,value:n}),{newDocument:r,removed:a}},copy:function(t,e,r){var a=Kc(r,this.from);return ul(r,{op:"add",path:this.path,value:Ur(a)}),{newDocument:r}},test:function(t,e,r){return{newDocument:r,test:Ad(t[e],this.value)}},_get:function(t,e,r){return this.value=t[e],{newDocument:r}}},hy={add:function(t,e,r){return Bg(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:r,index:e}},remove:function(t,e,r){var a=t.splice(e,1);return{newDocument:r,removed:a[0]}},replace:function(t,e,r){var a=t[e];return t[e]=this.value,{newDocument:r,removed:a}},move:ps.move,copy:ps.copy,test:ps.test,_get:ps._get};function Kc(t,e){if(e=="")return t;var r={op:"_get",path:e};return ul(t,r),r.value}function ul(t,e,r,a,n,i){if(r===void 0&&(r=!1),a===void 0&&(a=!0),n===void 0&&(n=!0),i===void 0&&(i=0),r&&(typeof r=="function"?r(e,0,t,e.path):fc(e,0)),e.path===""){var l={newDocument:t};if(e.op==="add")return l.newDocument=e.value,l;if(e.op==="replace")return l.newDocument=e.value,l.removed=t,l;if(e.op==="move"||e.op==="copy")return l.newDocument=Kc(t,e.from),e.op==="move"&&(l.removed=t),l;if(e.op==="test"){if(l.test=Ad(t,e.value),l.test===!1)throw new Zt("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return l.newDocument=t,l}else{if(e.op==="remove")return l.removed=t,l.newDocument=null,l;if(e.op==="_get")return e.value=t,l;if(r)throw new Zt("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,t);return l}}else{a||(t=Ur(t));var s=e.path||"",o=s.split("/"),d=t,u=1,c=o.length,p=void 0,A=void 0,m=void 0;for(typeof r=="function"?m=r:m=fc;;){if(A=o[u],A&&A.indexOf("~")!=-1&&(A=df(A)),n&&(A=="__proto__"||A=="prototype"&&u>0&&o[u-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&p===void 0&&(d[A]===void 0?p=o.slice(0,u).join("/"):u==c-1&&(p=e.path),p!==void 0&&m(e,0,t,p)),u++,Array.isArray(d)){if(A==="-")A=d.length;else{if(r&&!Bg(A))throw new Zt("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,e,t);Bg(A)&&(A=~~A)}if(u>=c){if(r&&e.op==="add"&&A>d.length)throw new Zt("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,t);var l=hy[e.op].call(e,d,A,t);if(l.test===!1)throw new Zt("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return l}}else if(u>=c){var l=ps[e.op].call(e,d,A,t);if(l.test===!1)throw new Zt("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return l}if(d=d[A],r&&u<c&&(!d||typeof d!="object"))throw new Zt("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}function x0(t,e,r,a,n){if(a===void 0&&(a=!0),n===void 0&&(n=!0),r&&!Array.isArray(e))throw new Zt("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");a||(t=Ur(t));for(var i=new Array(e.length),l=0,s=e.length;l<s;l++)i[l]=ul(t,e[l],r,!0,n,l),t=i[l].newDocument;return i.newDocument=t,i}function By(t,e,r){var a=ul(t,e);if(a.test===!1)throw new Zt("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return a.newDocument}function fc(t,e,r,a){if(typeof t!="object"||t===null||Array.isArray(t))throw new Zt("Operation is not a
* https://github.com/Starcounter-Jack/JSON-Patch
* (c) 2017-2021 Joachim Wester
* MIT license
*/var Vh=new WeakMap,wy=function(){function t(e){this.observers=new Map,this.obj=e}return t}(),by=function(){function t(e,r){this.callback=e,this.observer=r}return t}();function Ky(t){return Vh.get(t)}function fy(t,e){return t.observers.get(e)}function Qy(t,e){t.observers.delete(e.callback)}function Wy(t,e){e.unobserve()}function vy(t,e){var r=[],a,n=Ky(t);if(!n)n=new wy(t),Vh.set(t,n);else{var i=fy(n,e);a=i&&i.observer}if(a)return a;if(a={},n.value=Ur(t),e){a.callback=e,a.next=null;var l=function(){wg(a)},s=function(){clearTimeout(a.next),a.next=setTimeout(l)};typeof window<"u"&&(window.addEventListener("mouseup",s),window.addEventListener("keyup",s),window.addEventListener("mousedown",s),window.addEventListener("keydown",s),window.addEventListener("change",s))}return a.patches=r,a.object=t,a.unobserve=function(){wg(a),clearTimeout(a.next),Qy(n,a),typeof window<"u"&&(window.removeEventListener("mouseup",s),window.removeEventListener("keyup",s),window.removeEventListener("mousedown",s),window.removeEventListener("keydown",s),window.removeEventListener("change",s))},n.observers.set(e,new by(e,a)),a}function wg(t,e){e===void 0&&(e=!1);var r=Vh.get(t.object);Yh(r.value,t.object,t.patches,"",e),t.patches.length&&x0(r.value,t.patches);var a=t.patches;return a.length>0&&(t.patches=[],t.callback&&t.callback(a)),a}function Yh(t,e,r,a,n){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var i=hg(e),l=hg(t),s=!1,o=l.length-1;o>=0;o--){var d=l[o],u=t[d];if(Ag(e,d)&&!(e[d]===void 0&&u!==void 0&&Array.isArray(e)===!1)){var c=e[d];typeof u=="object"&&u!=null&&typeof c=="object"&&c!=null&&Array.isArray(u)===Array.isArray(c)?Yh(u,c,r,a+"/"+xi(d),n):u!==c&&(n&&r.push({op:"test",path:a+"/"+xi(d),value:Ur(u)}),r.push({op:"replace",path:a+"/"+xi(d),value:Ur(c)}))}else Array.isArray(t)===Array.isArray(e)?(n&&r.push({op:"test",path:a+"/"+xi(d),value:Ur(u)}),r.push({op:"remove",path:a+"/"+xi(d)}),s=!0):(n&&r.push({op:"test",path:a,value:t}),r.push({op:"replace",path:a,value:e}))}if(!(!s&&i.length==l.length))for(var o=0;o<i.length;o++){var d=i[o];!Ag(t,d)&&e[d]!==void 0&&r.push({op:"add",path:a+"/"+xi(d),value:Ur(e[d])})}}}function Fy(t,e,r){r===void 0&&(r=!1);var a=[];return Yh(t,e,a,"",r),a}const yy=Object.freeze(Object.defineProperty({__proto__:null,compare:Fy,generate:wg,observe:vy,unobserve:Wy},Symbol.toStringTag,{value:"Module"}));Object.assign({},Cy,yy,{JsonPatchError:uf,deepClone:Ur,escapePathComponent:xi,unescapePathComponent:df});const Ry=()=>typeof window<"u"&&typeof window.document<"u",Ey=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",Gy=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom")),cf=()=>typeof Deno<"u",Sy=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!cf(),Zy=()=>{let t;return Ry()?t="browser":Sy()?t="node":Ey()?t="webworker":Gy()?t="jsdom":cf()?t="deno":t="other",t};let em;async function Xy(){return em===void 0&&(em={library:"langchain-js",runtime:Zy()}),em}function Cs(t){var e;try{return typeof process<"u"?(e=process.env)==null?void 0:e[t]:void 0}catch{return}}let rp;const Hy=new Uint8Array(16);function Vy(){if(!rp&&(rp=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!rp))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return rp(Hy)}const Yy=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function mf(t){return typeof t=="string"&&Yy.test(t)}const ir=[];for(let t=0;t<256;++t)ir.push((t+256).toString(16).slice(1));function Ny(t,e=0){return ir[t[e+0]]+ir[t[e+1]]+ir[t[e+2]]+ir[t[e+3]]+"-"+ir[t[e+4]]+ir[t[e+5]]+"-"+ir[t[e+6]]+ir[t[e+7]]+"-"+ir[t[e+8]]+ir[t[e+9]]+"-"+ir[t[e+10]]+ir[t[e+11]]+ir[t[e+12]]+ir[t[e+13]]+ir[t[e+14]]+ir[t[e+15]]}const Ly=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),L4={randomUUID:Ly};functio
${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,r){e.child_runs.push(r)}async _startTrace(e){var n;const r=qy(e.start_time,e.id,e.execution_order),a={...e};if(a.parent_run_id!==void 0){const i=this.runMap.get(a.parent_run_id);i&&(this._addChildRun(i,a),i.child_execution_order=Math.max(i.child_execution_order,a.child_execution_order),a.trace_id=i.trace_id,i.dotted_order!==void 0&&(a.dotted_order=[i.dotted_order,r].join(".")))}else a.trace_id=a.id,a.dotted_order=r;this.runMap.set(a.id,a),await((n=this.onRunCreate)==null?void 0:n.call(this,a))}async _endTrace(e){var a;const r=e.parent_run_id!==void 0&&this.runMap.get(e.parent_run_id);r?r.child_execution_order=Math.max(r.child_execution_order,e.child_execution_order):await this.persistRun(e),this.runMap.delete(e.id),await((a=this.onRunUpdate)==null?void 0:a.call(this,e))}_getExecutionOrder(e){const r=e!==void 0&&this.runMap.get(e);return r?r.child_execution_order+1:1}async handleLLMStart(e,r,a,n,i,l,s,o){var A;const d=this._getExecutionOrder(n),u=Date.now(),c=s?{...i,metadata:s}:i,p={id:a,name:o??e.id[e.id.length-1],parent_run_id:n,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{prompts:r},execution_order:d,child_runs:[],child_execution_order:d,run_type:"llm",extra:c??{},tags:l||[]};return await this._startTrace(p),await((A=this.onLLMStart)==null?void 0:A.call(this,p)),p}async handleChatModelStart(e,r,a,n,i,l,s,o){var A;const d=this._getExecutionOrder(n),u=Date.now(),c=s?{...i,metadata:s}:i,p={id:a,name:o??e.id[e.id.length-1],parent_run_id:n,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{messages:r},execution_order:d,child_runs:[],child_execution_order:d,run_type:"llm",extra:c??{},tags:l||[]};return await this._startTrace(p),await((A=this.onLLMStart)==null?void 0:A.call(this,p)),p}async handleLLMEnd(e,r){var n;const a=this.runMap.get(r);if(!a||(a==null?void 0:a.run_type)!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.outputs=e,a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),await((n=this.onLLMEnd)==null?void 0:n.call(this,a)),await this._endTrace(a),a}async handleLLMError(e,r){var n;const a=this.runMap.get(r);if(!a||(a==null?void 0:a.run_type)!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(e),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),await((n=this.onLLMError)==null?void 0:n.call(this,a)),await this._endTrace(a),a}async handleChainStart(e,r,a,n,i,l,s,o){var p;const d=this._getExecutionOrder(n),u=Date.now(),c={id:a,name:o??e.id[e.id.length-1],parent_run_id:n,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:r,execution_order:d,child_execution_order:d,run_type:s??"chain",child_runs:[],extra:l?{metadata:l}:{},tags:i||[]};return await this._startTrace(c),await((p=this.onChainStart)==null?void 0:p.call(this,c)),c}async handleChainEnd(e,r,a,n,i){var s;const l=this.runMap.get(r);if(!l)throw new Error("No chain run to end.");return l.end_time=Date.now(),l.outputs=tm(e,"output"),l.events.push({name:"end",time:new Date(l.end_time).toISOString()}),(i==null?void 0:i.inputs)!==void 0&&(l.inputs=tm(i.inputs,"input")),await((s=this.onChainEnd)==null?void 0:s.call(this,l)),await this._endTrace(l),l}async handleChainError(e,r,a,n,i){var s;const l=this.runMap.get(r);if(!l)throw new Error("No chain run to end.");return l.end_time=Date.now(),l.error=this.stringifyError(e),l.events.push({name:"error",time:new Date(l.end_time).toISOString()}),(i==null?void 0:i.inputs)!==void 0&&(l.inputs=tm(i.inputs,"input")),await((s=this.onChainError)==null?void 0:s.call(this,l)),await this._endTrace(l),l}async handleToolStart(e,r,a,n,i,l,s){var c;const o=this._getExecutionOrder(n),d=Date.now(),u={id:a,name:s??e.id[e.id.length-1],parent_run_id:n,start_time:d,serialized:e,events:[{name:"start",time:new Date(d).toISOString()}],inputs:{input:r},execution_order:o,child_execution_order:o,run_type:"tool",child_runs:[],extra:l?{metadata:l}:{},tags:i||[]};re
`).map(s=>JSON.parse(s))}async*listDatasets({limit:e=100,offset:r=0,datasetIds:a,datasetName:n,datasetNameContains:i}={}){const l="/datasets",s=new URLSearchParams({limit:e.toString(),offset:r.toString()});if(a!==void 0)for(const o of a)s.append("id",o);n!==void 0&&s.append("name",n),i!==void 0&&s.append("name_contains",i);for await(const o of this._getPaginated(l,s))yield*o}async deleteDataset({datasetId:e,datasetName:r}){let a="/datasets",n=e;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(r!==void 0&&(n=(await this.readDataset({datasetName:r})).id),n!==void 0)Rt(n),a+=`/${n}`;else throw new Error("Must provide datasetName or datasetId");const i=await this.caller.call(fetch,this.apiUrl+a,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(!i.ok)throw new Error(`Failed to delete ${a}: ${i.status} ${i.statusText}`);await i.json()}async createExample(e,r,{datasetId:a,datasetName:n,createdAt:i,exampleId:l,metadata:s}){let o=a;if(o===void 0&&n===void 0)throw new Error("Must provide either datasetName or datasetId");if(o!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");o===void 0&&(o=(await this.readDataset({datasetName:n})).id);const d=i||new Date,u={dataset_id:o,inputs:e,outputs:r,created_at:d==null?void 0:d.toISOString(),id:l,metadata:s},c=await this.caller.call(fetch,`${this.apiUrl}/examples`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(u),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(!c.ok)throw new Error(`Failed to create example: ${c.status} ${c.statusText}`);return await c.json()}async createExamples(e){const{inputs:r,outputs:a,metadata:n,sourceRunIds:i,exampleIds:l,datasetId:s,datasetName:o}=e;let d=s;if(d===void 0&&o===void 0)throw new Error("Must provide either datasetName or datasetId");if(d!==void 0&&o!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");d===void 0&&(d=(await this.readDataset({datasetName:o})).id);const u=r.map((A,m)=>({dataset_id:d,inputs:A,outputs:a?a[m]:void 0,metadata:n?n[m]:void 0,id:l?l[m]:void 0,source_run_id:i?i[m]:void 0})),c=await this.caller.call(fetch,`${this.apiUrl}/examples/bulk`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(u),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(!c.ok)throw new Error(`Failed to create examples: ${c.status} ${c.statusText}`);return await c.json()}async createLLMExample(e,r,a){return this.createExample({input:e},{output:r},a)}async createChatExample(e,r,a){const n=e.map(l=>M4(l)?x4(l):l),i=M4(r)?x4(r):r;return this.createExample({input:n},{output:i},a)}async readExample(e){Rt(e);const r=`/examples/${e}`;return await this._get(r)}async*listExamples({datasetId:e,datasetName:r,exampleIds:a,asOf:n,inlineS3Urls:i,metadata:l}={}){let s;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)s=e;else if(r!==void 0)s=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide a datasetName or datasetId");const o=new URLSearchParams({dataset:s}),d=n?typeof n=="string"?n:n==null?void 0:n.toISOString():void 0;d&&o.append("as_of",d);const u=i??!0;if(o.append("inline_s3_urls",u.toString()),a!==void 0)for(const c of a)o.append("id",c);if(l!==void 0){const c=JSON.stringify(l);o.append("metadata",c)}for await(const c of this._getPaginated("/examples",o))yield*c}async deleteExample(e){Rt(e);const r=`/examples/${e}`,a=await this.caller.call(fetch,this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(!a.ok)throw new Error(`Failed to delete ${r}: ${a.status} ${a.statusText}`);await a.json()}async updateExample(e,r){Rt(e);const a=await this.caller.call(fetch,`${this.apiUrl}/examples/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(r),signal:AbortSignal.
`&&!n?i="\\n":i==="\\"?n=!n:n=!1;else if(i==='"')a=!0,n=!1;else if(i==="{")r.push("}");else if(i==="[")r.push("]");else if(i==="}"||i==="]")if(r&&r[r.length-1]===i)r.pop();else return null;e+=i}a&&(e+='"');for(let i=r.length-1;i>=0;i-=1)e+=r[i];try{return JSON.parse(e)}catch{return null}}function NR(t,e){return typeof t=="string"?typeof e=="string"?t+e:[{type:"text",text:t},...e]:Array.isArray(e)?[...t,...e]:[...t,{type:"text",text:e}]}let LR=class extends Qc{get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}get text(){return typeof this.content=="string"?this.content:""}constructor(e,r){typeof e=="string"&&(e={content:e,additional_kwargs:r,response_metadata:{}}),e.additional_kwargs||(e.additional_kwargs={}),e.response_metadata||(e.response_metadata={}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","messages"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"content",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"additional_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"response_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.content=e.content,this.additional_kwargs=e.additional_kwargs,this.response_metadata=e.response_metadata}toDict(){return{type:this._getType(),data:this.toJSON().kwargs}}};function vc(t,e){const r={...t};for(const[a,n]of Object.entries(e))if(r[a]==null)r[a]=n;else{if(n==null)continue;if(typeof r[a]!=typeof n||Array.isArray(r[a])!==Array.isArray(n))throw new Error(`field[${a}] already exists in the message chunk, but with a different type.`);if(typeof r[a]=="string")r[a]=r[a]+n;else if(!Array.isArray(r[a])&&typeof r[a]=="object")r[a]=vc(r[a],n);else if(Array.isArray(r[a]))r[a]=Hf(r[a],n);else{if(r[a]===n)continue;console.warn(`field[${a}] already exists in this message chunk and value has unsupported type.`)}}return r}function Hf(t,e){if(!(t===void 0&&e===void 0)){if(t===void 0||e===void 0)return t||e;{const r=[...t];for(const a of e)if(typeof a=="object"&&"index"in a&&typeof a.index=="number"){const n=r.findIndex(i=>i.index===a.index);n!==-1?r[n]=vc(r[n],a):r.push(a)}else r.push(a);return r}}}let TR=class extends LR{},kR=class Vf extends TR{constructor(e){let r;if(typeof e=="string")r={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(e.tool_call_chunks===void 0)r={...e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else{const a=[],n=[];for(const i of e.tool_call_chunks){let l={};try{if(l=YR(i.args??"{}")??{},typeof l!="object"||Array.isArray(l))throw new Error("Malformed tool call chunk args.");a.push({name:i.name??"",args:l,id:i.id})}catch{n.push({name:i.name,args:i.args,id:i.id,error:"Malformed args."})}}r={...e,tool_calls:a,invalid_tool_calls:n}}super(r),Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tool_call_chunks",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.tool_call_chunks=(r==null?void 0:r.tool_call_chunks)??this.tool_call_chunks,this.tool_calls=(r==null?void 0:r.tool_calls)??this.tool_calls,this.invalid_tool_calls=(r==null?void 0:r.invalid_tool_calls)??this.invalid_tool_calls}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks"}}static lc_name(){return"AIMessageChunk"}_getType(){return"ai"}concat(e){const r={content:NR(this.content,e.content),additional_kwargs:vc(this.additional_kwargs,e.additional_kwargs),response_metadata:vc(this.response_metadata,e.response_metadata),tool_call_chunks:[]};if(this.tool_call_chunks!==void 0||e.tool_call_chunks!==void 0){const a=H
`)}async function _R(){return new Xf}let im;function IR(){const t="default"in wn?wn.default:wn;return new t({autoStart:!0,concurrency:1})}async function or(t,e){e===!0?await t():(typeof im>"u"&&(im=IR()),im.add(t))}let DR=class{setHandler(e){return this.setHandlers([e])}},j0=class{constructor(e,r,a,n,i,l,s,o){Object.defineProperty(this,"runId",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:l}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:s}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:o})}async handleText(e){await Promise.all(this.handlers.map(r=>or(async()=>{var a;try{await((a=r.handleText)==null?void 0:a.call(r,e,this.runId,this._parentRunId,this.tags))}catch(n){console.error(`Error in handler ${r.constructor.name}, handleText: ${n}`)}},r.awaitHandlers)))}},MR=class extends j0{getChild(e){const r=new bl(this.runId);return r.setHandlers(this.inheritableHandlers),r.addTags(this.inheritableTags),r.addMetadata(this.inheritableMetadata),e&&r.addTags([e],!1),r}async handleRetrieverEnd(e){await Promise.all(this.handlers.map(r=>or(async()=>{var a;if(!r.ignoreRetriever)try{await((a=r.handleRetrieverEnd)==null?void 0:a.call(r,e,this.runId,this._parentRunId,this.tags))}catch{console.error(`Error in handler ${r.constructor.name}, handleRetriever`)}},r.awaitHandlers)))}async handleRetrieverError(e){await Promise.all(this.handlers.map(r=>or(async()=>{var a;if(!r.ignoreRetriever)try{await((a=r.handleRetrieverError)==null?void 0:a.call(r,e,this.runId,this._parentRunId,this.tags))}catch(n){console.error(`Error in handler ${r.constructor.name}, handleRetrieverError: ${n}`)}},r.awaitHandlers)))}},O4=class extends j0{async handleLLMNewToken(e,r,a,n,i,l){await Promise.all(this.handlers.map(s=>or(async()=>{var o;if(!s.ignoreLLM)try{await((o=s.handleLLMNewToken)==null?void 0:o.call(s,e,r??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,l))}catch(d){console.error(`Error in handler ${s.constructor.name}, handleLLMNewToken: ${d}`)}},s.awaitHandlers)))}async handleLLMError(e){await Promise.all(this.handlers.map(r=>or(async()=>{var a;if(!r.ignoreLLM)try{await((a=r.handleLLMError)==null?void 0:a.call(r,e,this.runId,this._parentRunId,this.tags))}catch(n){console.error(`Error in handler ${r.constructor.name}, handleLLMError: ${n}`)}},r.awaitHandlers)))}async handleLLMEnd(e){await Promise.all(this.handlers.map(r=>or(async()=>{var a;if(!r.ignoreLLM)try{await((a=r.handleLLMEnd)==null?void 0:a.call(r,e,this.runId,this._parentRunId,this.tags))}catch(n){console.error(`Error in handler ${r.constructor.name}, handleLLMEnd: ${n}`)}},r.awaitHandlers)))}},xR=class extends j0{getChild(e){const r=new bl(this.runId);return r.setHandlers(this.inheritableHandlers),r.addTags(this.inheritableTags),r.addMetadata(this.inheritableMetadata),e&&r.addTags([e],!1),r}async handleChainError(e,r,a,n,i){await Promise.all(this.handlers.map(l=>or(async()=>{var s;if(!l.ignoreChain)try{await((s=l.handleChainError)==null?void 0:s.call(l,e,this.runId,this._parentRunId,this.tags,i))}catch(o){console.error(`Error in handler ${l.constructor.name}, handleChainError: ${o}`)}},l.awaitHandlers)))}async handleChainEnd(e,r,a,n,i){await Promise.all(this.handlers.map(l=>or(async()=>{var s;if(!l.ignoreChain)try{await((s=l.handleChainEnd)==null?void 0:s.call(l,e,this.runId,this._parentRunId,this.tags,i))}catch(o){console.error(`Error in handler ${l.constructor.name}, handleChainEnd: ${o}`)}},l.awaitHandlers)))}async handleAgentAction(e){await Promise.all(this.handlers.map(r=>or(async()=>{var a;if(!r.ignoreAgent)try{await
`)}mapCharactersToTokenIds(e,r,a){const n=[];r&&n.push(1),a&&(e=" "+e);const i=e.replaceAll(" ",this.vocabById[29871]),l=Array.from(i);for(let s=0;s<l.length;s++){const o=l[s];if(this.vocabByString.has(o))n.push(this.vocabByString.get(o));else{const d=this.utf8Encoder.encode(o);for(let u=0;u<d.length;u++){const c=this.vocabByString.get(z4(d[u]));n.push(c),c>=0||(console.log("Encountered unknown character "+o+" (partial UTF-8 byte "+d[u]+" + hex + "+z4(d[u])+")"),n[n.length-1]=0)}}}return n}encode(e,r=!0,a=!0,n=!1){let i=null;if(n&&(i=performance.now()),!this.vocabById||!this.vocabByString||!this.merges){console.log("Tokenizer not initialized properly!");return}if(e.length===0)return[];const l=this.mapCharactersToTokenIds(e,r,a),s=new PR((p,A)=>p.mergePrio<A.mergePrio),o=p=>{const A=this.getMergeIdentifierString(p.tokenId,p.next.tokenId),m=this.merges.get(A)+p.origPos/e.length;m&&(p.mergePrio=m,p.mergeToString=A.replace(" ",""),s.push(p))};let d={origPos:0,tokenId:l[0],prev:null,next:null},u=d;for(let p=1;p<l.length;p++){const A={origPos:p,tokenId:l[p],prev:u,next:null};u.next=A,o(u),u=A}for(;!s.isEmpty();){const p=s.pop();if(p.deleted||!p.next||p.next.deleted)continue;if(p.deleted=!0,p.next.deleted=!0,p.prev){const m=p.prev;m.deleted=!0;const h={origPos:m.origPos,tokenId:m.tokenId,prev:m.prev,next:m.next};p.prev=h,h.prev?h.prev.next=h:d=h}const A={origPos:p.origPos,tokenId:this.vocabByString.get(p.mergeToString),prev:p.prev,next:p.next.next};A.prev?(A.prev.next=A,A.prev,o(A.prev)):d=A,A.next&&(A.next.prev=A,o(A))}const c=[];for(let p=d;p!==null;p=p.next)c.push(p.tokenId);if(n){const p=performance.now();console.log("Tokenizer running time: "+(p-i)+" milliseconds")}return c}decode(e,r=!0,a=!0){const n=[],i=r?1:0;for(let d=i;d<e.length;d++){const u=e[d],c=this.vocabById[u];if(c.startsWith("<0x")&&c.endsWith(">")){const p=OR(c);n.push(p)}else this.utf8Encoder.encode(c).forEach(A=>n.push(A))}const l=new Uint8Array(n),o=this.utf8Decoder.decode(l).replaceAll(this.vocabById[29871]," ");return a?o.slice(1):o}defaultTests(e){function r(n,i){return n.length===i.length&&n.every(function(l,s){return l===i[s]})}function a(n,i){const l=e.encode(n,!0,!0,!0);if(!r(l,i))throw`Test failed. LLaMA Tokenizer Encoder returned unexpected result: expected tokenize(${n}) === ${i}, actual was: ${l}`;if(n!==e.decode(l))throw`Test failed. LLaMA Tokenizer Decoder returned unexpected result: expected decode(${l}) === ${n}, actual was: ${decode(l)}`}return a("grabbed",[1,2646,1327,287]),a(" grabbed",[1,29871,2646,1327,287]),a(" grabbed",[1,9651,2646,1327,287]),a(`
`,[1,29871,13]),a(`
`,[1,259,13]),a(" tabs out here",[1,29871,12,21175,12,12,12,12,449,1244]),a(`ax
####
boo`,[1,4853,13,4136,13,833,29877]),a("镇",[1,29871,30411]),a("🦙",[1,29871,243,162,169,156]),a("🦙Ꙋ",[1,29871,243,162,169,156,237,156,141]),a("Ꙋ🦙",[1,29871,237,156,141,243,162,169,156]),a('The llama (/ˈlɑːmə/; 🦙Spanish pronunciation: [ˈʎama]) (Lama glama) is a domesticated South American camelid, widely used as a meat and pack animal by Andean cultures since the Pre-Columbian era. Llamas are social animals and live with others as a herd. Their wool is soft and contains only a small amount of lanolin.[2] Llamas can learn simple tasks after a few repetitions. When using a pack, they can carry about 25 to 30% of their body weight for 8 to 13 km (5–8 miles).[3] The name llama (in the past also spelled "lama" or "glama") was adopted by European settlers from native Peruvians.[4] The ancestors of llamas are thought to have originated from the Great Plains of North America about 40 million years ago, and subsequently migrated to South America about three million years ago during the Great American Interchange. By the end of the last ice age (10,000–12,000 years ago), camelids were extinct in North America.[3] As of 2007, there were over seven million llamas and alpacas in South America and over 158,000 llamas and 100,000Ꙋ🦙 alpacas, descended from progenitors imported late in the 20th century, in the United States and Canada.[5] In Aymara mythology, llamas are important beings. The Heavenly Llama is said to drink water from the ocean and urinates as it rains.[6] According to Aymara eschatology, llamas will return to the water springs and lagoons where they come from at the end of time.[6]',[1,450,11148,3304,20374,30176,29880,30426,30215,29885,30184,29914,29936,29871,243,162,169,156,15495,728,11504,11173,362,29901,518,30176,31743,3304,2314,313,29931,3304,3144,3304,29897,338,263,21849,630,4275,3082,3949,295,333,29892,17644,1304,408,263,27654,322,4870,13019,491,1126,29872,273,4185,1973,1951,278,4721,29899,1625,3774,713,3152,29889,365,5288,294,526,5264,15006,322,5735,411,4045,408,263,902,29881,29889,11275,281,1507,338,4964,322,3743,871,263,2319,5253,310,10906,22878,7226,29906,29962,365,5288,294,508,5110,2560,9595,1156,263,2846,21159,2187,29889,1932,773,263,4870,29892,896,508,8677,1048,29871,29906,29945,304,29871,29941,29900,29995,310,1009,3573,7688,363,29871,29947,304,29871,29896,29941,2383,313,29945,29994,29947,7800,467,29961,29941,29962,450,1024,11148,3304,313,262,278,4940,884,805,14356,376,29880,3304,29908,470,376,3820,3304,1159,471,16356,491,7824,3604,9306,515,7531,25493,1403,550,7226,29946,29962,450,19525,943,310,11829,294,526,2714,304,505,3978,630,515,278,7027,13494,1144,310,4644,6813,1048,29871,29946,29900,7284,2440,8020,29892,322,17602,9725,630,304,4275,6813,1048,2211,7284,2440,8020,2645,278,7027,3082,4124,3167,29889,2648,278,1095,310,278,1833,14890,5046,313,29896,29900,29892,29900,29900,29900,29994,29896,29906,29892,29900,29900,29900,2440,8020,511,3949,295,4841,892,1294,5562,297,4644,6813,7226,29941,29962,1094,310,29871,29906,29900,29900,29955,29892,727,892,975,9881,7284,11829,294,322,394,29886,562,294,297,4275,6813,322,975,29871,29896,29945,29947,29892,29900,29900,29900,11829,294,322,29871,29896,29900,29900,29892,29900,29900,29900,237,156,141,243,162,169,156,394,29886,562,294,29892,5153,2760,515,410,1885,17259,19673,5683,297,278,29871,29906,29900,386,6462,29892,297,278,3303,3900,322,7400,7226,29945,29962,512,319,962,2518,22082,3002,29892,11829,294,526,4100,367,886,29889,450,22977,368,365,29880,3304,338,1497,304,13748,4094,515,278,23474,322,5065,262,1078,408,372,1153,1144,7226,29953,29962,7579,304,319,962,2518,831,13496,3002,29892,11829,294,674,736,304,278,4094,7689,886,322,301,4425,787,988,896,2041,515,472,278,1095,310,931,7226,29953,29962]),console.log("LLaMA Tokenizer tests passed successfully."),!0}runTests(e=this.defaultTests){e(this)}}const jR="PHVuaz4KPHM+Cjwvcz4KPDB4MDA+CjwweDAxPgo8MHgwMj4KPDB4MDM+CjwweDA0Pgo8MHgwNT4KPDB4MDY+CjwweDA3Pgo8MHgwOD4KPDB4MDk+CjwweDBBPgo8MHgwQj4KPDB4MEM+CjwweDBEPgo8MHgwRT4KPDB4MEY+CjwweDEwPgo8MHgxMT4KPDB4MTI+CjwweDEzPgo8MHgxND4KPDB4MTU+CjwweDE2Pgo8MHgxNz4KPD
`).length),r.split(`
`).slice(e).filter(Mf).map(a=>`
`+a).join("")):""}var xf=["Unknown","Constraint","Data","TransactionInactive","ReadOnly","Version","NotFound","InvalidState","InvalidAccess","Abort","Timeout","QuotaExceeded","Syntax","DataClone"],Ih=["Modify","Bulk","OpenFailed","VersionChange","Schema","Upgrade","InvalidTable","MissingAPI","NoSuchDatabase","InvalidArgument","SubTransaction","Unsupported","Internal","DatabaseClosed","PrematureCommit","ForeignAwait"].concat(xf),s6={VersionChanged:"Database version changed by other database connection",DatabaseClosed:"Database has been closed",Abort:"Transaction aborted",TransactionInactive:"Transaction has already completed or failed",MissingAPI:"IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb"};function bs(t,e){this._e=Rl(),this.name=t,this.message=e}function Jf(t,e){return t+". Errors: "+Object.keys(e).map(r=>e[r].toString()).filter((r,a,n)=>n.indexOf(r)===a).join(`
`)}function Rc(t,e,r,a){this._e=Rl(),this.failures=e,this.failedKeys=a,this.successCount=r,this.message=Jf(t,e)}function ed(t,e){this._e=Rl(),this.name="BulkError",this.failures=Object.keys(e).map(r=>e[r]),this.failuresByPos=e,this.message=Jf(t,e)}ws(bs).from(Error).extend({stack:{get:function(){return this._stack||(this._stack=this.name+": "+this.message+Qg(this._e,2))}},toString:function(){return this.name+": "+this.message}}),ws(Rc).from(bs),ws(ed).from(bs);var Dh=Ih.reduce((t,e)=>(t[e]=e+"Error",t),{});const o6=bs;var ye=Ih.reduce((t,e)=>{var r=e+"Error";function a(n,i){this._e=Rl(),this.name=r,n?typeof n=="string"?(this.message=`${n}${i?`
`+i:""}`,this.inner=i||null):typeof n=="object"&&(this.message=`${n.name} ${n.message}`,this.inner=n):(this.message=s6[e]||r,this.inner=null)}return ws(a).from(o6),t[e]=a,t},{});ye.Syntax=SyntaxError,ye.Type=TypeError,ye.Range=RangeError;var j4=xf.reduce((t,e)=>(t[e+"Error"]=ye[e],t),{}),Ip=Ih.reduce((t,e)=>(["Syntax","Type","Range"].indexOf(e)===-1&&(t[e+"Error"]=ye[e]),t),{});function ht(){}function Bd(t){return t}function d6(t,e){return t==null||t===Bd?e:function(r){return e(t(r))}}function Kl(t,e){return function(){t.apply(this,arguments),e.apply(this,arguments)}}function u6(t,e){return t===ht?e:function(){var r=t.apply(this,arguments);r!==void 0&&(arguments[0]=r);var a=this.onsuccess,n=this.onerror;this.onsuccess=null,this.onerror=null;var i=e.apply(this,arguments);return a&&(this.onsuccess=this.onsuccess?Kl(a,this.onsuccess):a),n&&(this.onerror=this.onerror?Kl(n,this.onerror):n),i!==void 0?i:r}}function p6(t,e){return t===ht?e:function(){t.apply(this,arguments);var r=this.onsuccess,a=this.onerror;this.onsuccess=this.onerror=null,e.apply(this,arguments),r&&(this.onsuccess=this.onsuccess?Kl(r,this.onsuccess):r),a&&(this.onerror=this.onerror?Kl(a,this.onerror):a)}}function c6(t,e){return t===ht?e:function(r){var a=t.apply(this,arguments);Rr(r,a);var n=this.onsuccess,i=this.onerror;this.onsuccess=null,this.onerror=null;var l=e.apply(this,arguments);return n&&(this.onsuccess=this.onsuccess?Kl(n,this.onsuccess):n),i&&(this.onerror=this.onerror?Kl(i,this.onerror):i),a===void 0?l===void 0?void 0:l:Rr(a,l)}}function m6(t,e){return t===ht?e:function(){return e.apply(this,arguments)!==!1&&t.apply(this,arguments)}}function Mh(t,e){return t===ht?e:function(){var r=t.apply(this,arguments);if(r&&typeof r.then=="function"){for(var a=this,n=arguments.length,i=new Array(n);n--;)i[n]=arguments[n];return r.then(function(){return e.apply(a,i)})}return e.apply(this,arguments)}}Ip.ModifyError=Rc,Ip.DexieError=bs,Ip.BulkError=ed;var Cd={};const Of=100,[Wg,Ec,vg]=typeof Promise>"u"?[]:(()=>{let t=Promise.resolve();if(typeof crypto>"u"||!crypto.subtle)return[t,hd(t),t];const e=crypto.subtle.digest("SHA-512",new Uint8Array([0]));return[e,hd(e),t]})(),Pf=Ec&&Ec.then,Dp=Wg&&Wg.constructor,xh=!!vg;var Fg=!1,g6=vg?()=>{vg.then(np)}:bt.setImmediate?setImmediate.bind(null,np):bt.MutationObserver?()=>{var t=document.createElement("div");new MutationObserver(()=>{np(),t=null}).observe(t,{attributes:!0}),t.setAttribute("i","1")}:()=>{setTimeout(np,0)},td=function(t,e){Ho.push([t,e]),Gc&&(g6(),Gc=!1)},yg=!0,Gc=!0,pl=[],Mp=[],Rg=null,Eg=Bd,Ks={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:ew,pgp:!1,env:{},finalize:function(){this.unhandleds.forEach(t=>{try{ew(t[0],t[1])}catch{}})}},Ke=Ks,Ho=[],cl=0,xp=[];function Ae(t){if(typeof this!="object")throw new TypeError("Promises must be constructed via new");this._listeners=[],this.onuncatched=ht,this._lib=!1;var e=this._PSD=Ke;if(Da&&(this._stackHolder=Rl(),this._prev=null,this._numPrev=0),typeof t!="function"){if(t!==Cd)throw new TypeError("Not a function");return this._state=arguments[1],this._value=arguments[2],void(this._state===!1&&Sg(this,this._value))}this._state=null,this._value=null,++e.ref,jf(this,t)}const Gg={get:function(){var t=Ke,e=Sc;function r(a,n){var i=!t.global&&(t!==Ke||e!==Sc);const l=i&&!Qn();var s=new Ae((o,d)=>{Jh(this,new zf(Zc(a,t,i,l),Zc(n,t,i,l),o,d,t))});return Da&&e3(s,this),s}return r.prototype=Cd,r},set:function(t){bn(this,"then",t&&t.prototype===Cd?Gg:{get:function(){return t},set:Gg.set})}};function zf(t,e,r,a,n){this.onFulfilled=typeof t=="function"?t:null,this.onRejected=typeof e=="function"?e:null,this.resolve=r,this.reject=a,this.psd=n}function jf(t,e){try{e(r=>{if(t._state===null){if(r===t)throw new TypeError("A promise cannot be resolved with itself.");var a=t._lib&&ru();r&&typeof r.then=="function"?jf(t,(n,i)=>{r instanceof Ae?r._then(n,i):r.then(n,i)}):(t._state=!0,t._value=r,qf(t)),a&&au()}},Sg.bind(null,t))}catch(r){Sg(t,r)}}function Sg(t,e){if(Mp.push(e),t._state===null){var r=t._lib&&ru();e=Eg(e),t._state=!1,t._value=e,Da&&e!==null&&typeof e=="object"&
From previous: `);return this._state!==null&&(this._stack=t),t}finally{Fg=!1}}},timeout:function(t,e){return t<1/0?new Ae((r,a)=>{var n=setTimeout(()=>a(new ye.Timeout(e)),t);this.then(r,a).finally(clearTimeout.bind(null,n))}):this}}),typeof Symbol<"u"&&Symbol.toStringTag&&bn(Ae.prototype,Symbol.toStringTag,"Dexie.Promise"),Ks.env=t3(),Gs(Ae,{all:function(){var t=An.apply(null,arguments).map(lp);return new Ae(function(e,r){t.length===0&&e([]);var a=t.length;t.forEach((n,i)=>Ae.resolve(n).then(l=>{t[i]=l,--a||e(t)},r))})},resolve:t=>{if(t instanceof Ae)return t;if(t&&typeof t.then=="function")return new Ae((r,a)=>{t.then(r,a)});var e=new Ae(Cd,!0,t);return e3(e,Rg),e},reject:ip,race:function(){var t=An.apply(null,arguments).map(lp);return new Ae((e,r)=>{t.map(a=>Ae.resolve(a).then(e,r))})},PSD:{get:()=>Ke,set:t=>Ke=t},totalEchoes:{get:()=>Sc},newPSD:di,usePSD:xs,scheduler:{get:()=>td,set:t=>{td=t}},rejectionMapper:{get:()=>Eg,set:t=>{Eg=t}},follow:(t,e)=>new Ae((r,a)=>di((n,i)=>{var l=Ke;l.unhandleds=[],l.onunhandled=i,l.finalize=Kl(function(){(function(s){function o(){s(),xp.splice(xp.indexOf(o),1)}xp.push(o),++cl,td(()=>{--cl==0&&Oh()},[])})(()=>{this.unhandleds.length===0?n():i(this.unhandleds[0])})},l.finalize),t()},e,r,a))}),Dp&&(Dp.allSettled&&bn(Ae,"allSettled",function(){const t=An.apply(null,arguments).map(lp);return new Ae(e=>{t.length===0&&e([]);let r=t.length;const a=new Array(r);t.forEach((n,i)=>Ae.resolve(n).then(l=>a[i]={status:"fulfilled",value:l},l=>a[i]={status:"rejected",reason:l}).then(()=>--r||e(a)))})}),Dp.any&&typeof AggregateError<"u"&&bn(Ae,"any",function(){const t=An.apply(null,arguments).map(lp);return new Ae((e,r)=>{t.length===0&&r(new AggregateError([]));let a=t.length;const n=new Array(a);t.forEach((i,l)=>Ae.resolve(i).then(s=>e(s),s=>{n[l]=s,--a||r(new AggregateError(n))}))})}));const Ar={awaits:0,echoes:0,id:0};var h6=0,Jp=[],lm=0,Sc=0,B6=0;function di(t,e,r,a){var n=Ke,i=Object.create(n);i.parent=n,i.ref=0,i.global=!1,i.id=++B6;var l=Ks.env;i.env=xh?{Promise:Ae,PromiseProp:{value:Ae,configurable:!0,writable:!0},all:Ae.all,race:Ae.race,allSettled:Ae.allSettled,any:Ae.any,resolve:Ae.resolve,reject:Ae.reject,nthen:q4(l.nthen,i),gthen:q4(l.gthen,i)}:{},e&&Rr(i,e),++n.ref,i.finalize=function(){--this.parent.ref||this.parent.finalize()};var s=xs(i,t,r,a);return i.ref===0&&i.finalize(),s}function Ms(){return Ar.id||(Ar.id=++h6),++Ar.awaits,Ar.echoes+=Of,Ar.id}function Qn(){return!!Ar.awaits&&(--Ar.awaits==0&&(Ar.id=0),Ar.echoes=Ar.awaits*Of,!0)}function lp(t){return Ar.echoes&&t&&t.constructor===Dp?(Ms(),t.then(e=>(Qn(),e),e=>(Qn(),jt(e)))):t}function C6(t){++Sc,Ar.echoes&&--Ar.echoes!=0||(Ar.echoes=Ar.id=0),Jp.push(Ke),ui(t,!0)}function w6(){var t=Jp[Jp.length-1];Jp.pop(),ui(t,!1)}function ui(t,e){var r=Ke;if((e?!Ar.echoes||lm++&&t===Ke:!lm||--lm&&t===Ke)||r3(e?C6.bind(null,t):w6),t!==Ke&&(Ke=t,r===Ks&&(Ks.env=t3()),xh)){var a=Ks.env.Promise,n=t.env;Ec.then=n.nthen,a.prototype.then=n.gthen,(r.global||t.global)&&(Object.defineProperty(bt,"Promise",n.PromiseProp),a.all=n.all,a.race=n.race,a.resolve=n.resolve,a.reject=n.reject,n.allSettled&&(a.allSettled=n.allSettled),n.any&&(a.any=n.any))}}function t3(){var t=bt.Promise;return xh?{Promise:t,PromiseProp:Object.getOwnPropertyDescriptor(bt,"Promise"),all:t.all,race:t.race,allSettled:t.allSettled,any:t.any,resolve:t.resolve,reject:t.reject,nthen:Ec.then,gthen:t.prototype.then}:{}}function xs(t,e,r,a,n){var i=Ke;try{return ui(t,!0),e(r,a,n)}finally{ui(i,!1)}}function r3(t){Pf.call(Wg,t)}function Zc(t,e,r,a){return typeof t!="function"?t:function(){var n=Ke;r&&Ms(),ui(e,!0);try{return t.apply(this,arguments)}finally{ui(n,!1),a&&r3(Qn)}}}function q4(t,e){return function(r,a){return t.call(this,Zc(r,e),Zc(a,e))}}(""+Pf).indexOf("[native code]")===-1&&(Ms=Qn=ht);const $4="unhandledrejection";function ew(t,e){var r;try{r=e.onuncatched(t)}catch{}if(r!==!1)try{var a,n={promise:e,reason:t};if(bt.document&&document.createEvent?((a=document.createEvent("Event")).initEvent($4,!0,!0),Rr(a,n)):bt.CustomEvent&&Rr(a=new CustomEvent($4,{detail:n}),n),a&&bt.dispatchEv
- `),t8={NO_LANGUAGE_WITH_CUSTOM_TOKENIZER:"Do not pass the language option to create when using a custom tokenizer.",LANGUAGE_NOT_SUPPORTED:`Language "%s" is not supported.
Supported languages are:
- ${e8}`,INVALID_STEMMER_FUNCTION_TYPE:"config.stemmer property must be a function.",MISSING_STEMMER:'As of version 1.0.0 @orama/orama does not ship non English stemmers by default. To solve this, please explicitly import and specify the "%s" stemmer from the package @orama/stemmers. See https://docs.oramasearch.com/open-source/text-analysis/stemming for more information.',CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY:"Custom stop words array must only contain strings.",UNSUPPORTED_COMPONENT:'Unsupported component "%s".',COMPONENT_MUST_BE_FUNCTION:'The component "%s" must be a function.',COMPONENT_MUST_BE_FUNCTION_OR_ARRAY_FUNCTIONS:'The component "%s" must be a function or an array of functions.',INVALID_SCHEMA_TYPE:'Unsupported schema type "%s" at "%s". Expected "string", "boolean" or "number" or array of them.',DOCUMENT_ID_MUST_BE_STRING:'Document id must be of type "string". Got "%s" instead.',DOCUMENT_ALREADY_EXISTS:'A document with id "%s" already exists.',DOCUMENT_DOES_NOT_EXIST:'A document with id "%s" does not exists.',MISSING_DOCUMENT_PROPERTY:'Missing searchable property "%s".',INVALID_DOCUMENT_PROPERTY:'Invalid document property "%s": expected "%s", got "%s"',UNKNOWN_INDEX:'Invalid property name "%s". Expected a wildcard string ("*") or array containing one of the following properties: %s',INVALID_BOOST_VALUE:"Boost value must be a number greater than, or less than 0.",INVALID_FILTER_OPERATION:"You can only use one operation per filter, you requested %d.",SCHEMA_VALIDATION_FAILURE:'Cannot insert document due schema validation failure on "%s" property.',INVALID_SORT_SCHEMA_TYPE:'Unsupported sort schema type "%s" at "%s". Expected "string" or "number".',CANNOT_SORT_BY_ARRAY:'Cannot configure sort for "%s" because it is an array (%s).',UNABLE_TO_SORT_ON_UNKNOWN_FIELD:'Unable to sort on unknown field "%s". Allowed fields: %s',SORT_DISABLED:"Sort is disabled. Please read the documentation at https://docs.oramasearch for more information.",UNKNOWN_GROUP_BY_PROPERTY:'Unknown groupBy property "%s".',INVALID_GROUP_BY_PROPERTY:'Invalid groupBy property "%s". Allowed types: "%s", but given "%s".',UNKNOWN_FILTER_PROPERTY:'Unknown filter property "%s".',INVALID_VECTOR_SIZE:'Vector size must be a number greater than 0. Got "%s" instead.',INVALID_VECTOR_VALUE:'Vector value must be a number greater than 0. Got "%s" instead.',INVALID_INPUT_VECTOR:`Property "%s" was declared as a %s-dimensional vector, but got a %s-dimensional vector instead.
Input vectors must be of the size declared in the schema, as calculating similarity between vectors of different sizes can lead to unexpected results.`,WRONG_SEARCH_PROPERTY_TYPE:'Property "%s" is not searchable. Only "string" properties are searchable.',FACET_NOT_SUPPORTED:`Facet doens't support the type "%s".`,INVALID_DISTANCE_SUFFIX:'Invalid distance suffix "%s". Valid suffixes are: cm, m, km, mi, yd, ft.',INVALID_SEARCH_MODE:'Invalid search mode "%s". Valid modes are: "fulltext", "vector", "hybrid".',MISSING_VECTOR_AND_SECURE_PROXY:"No vector was provided and no secure proxy was configured. Please provide a vector or configure an Orama Secure Proxy to perform hybrid search.",MISSING_TERM:'"term" is a required parameter when performing hybrid search. Please provide a search term.',INVALID_VECTOR_INPUT:'Invalid "vector" property. Expected an object with "value" and "property" properties, but got "%s" instead.',PLUGIN_CRASHED:"A plugin crashed during initialization. Please check the error message for more information:"};function Ue(t,...e){const r=new Error(O6(t8[t]??`Unsupported Orama Error code: ${t}`,...e));return r.code=t,"captureStackTrace"in Error.prototype&&Error.captureStackTrace(r),r}async function r8(t){return{raw:Number(t),formatted:await eB(t)}}async function a8(t){if(t.id){if(typeof t.id!="string")throw Ue("DOCUMENT_ID_MUST_BE_STRING",typeof t.id);return t.id}return await A3()}async function C3(t,e){for(const[r,a]of Object.entries(e)){const n=t[r];if(!(typeof n>"u")&&!(a==="geopoint"&&typeof n=="object"&&typeof n.lon=="number"&&typeof n.lat=="number")&&!(a==="enum"&&(typeof n=="string"||typeof n=="number"))){if(a==="enum[]"&&Array.isArray(n)){const i=n.length;for(let l=0;l<i;l++)if(typeof n[l]!="string"&&typeof n[l]!="number")return r+"."+l;continue}if(Js(a)){const i=b3(a);if(!Array.isArray(n)||n.length!==i)throw Ue("INVALID_INPUT_VECTOR",r,i,n.length);continue}if(e1(a)){if(!Array.isArray(n))return r;const i=w3(a),l=n.length;for(let s=0;s<l;s++)if(typeof n[s]!==i)return r+"."+s;continue}if(typeof a=="object"){if(!n||typeof n!="object")return r;const i=await C3(n,a);if(i)return r+"."+i;continue}if(typeof n!==a)return r}}}const n8={string:!1,number:!1,boolean:!1,enum:!1,geopoint:!1,"string[]":!0,"number[]":!0,"boolean[]":!0,"enum[]":!0},i8={"string[]":"string","number[]":"number","boolean[]":"boolean","enum[]":"enum"};function l8(t){return t==="geopoint"}function Js(t){return typeof t=="string"&&/^vector\[\d+\]$/.test(t)}function e1(t){return typeof t=="string"&&n8[t]}function w3(t){return i8[t]}function b3(t){const e=Number(t.slice(7,-1));switch(!0){case isNaN(e):throw Ue("INVALID_VECTOR_VALUE",t);case e<=0:throw Ue("INVALID_VECTOR_SIZE",t);default:return e}}function s8(){return{idToInternalId:new Map,internalIdToId:[],save:o8,load:d8}}function o8(t){return{internalIdToId:t.internalIdToId}}function d8(t,e){const{internalIdToId:r}=e;t.internalDocumentIDStore.idToInternalId.clear(),t.internalDocumentIDStore.internalIdToId=[];const a=r.length;for(let n=0;n<a;n++){const i=r[n];t.internalDocumentIDStore.idToInternalId.set(i,n+1),t.internalDocumentIDStore.internalIdToId.push(i)}}function Dt(t,e){if(typeof e=="string"){const r=t.idToInternalId.get(e);if(r)return r;const a=t.idToInternalId.size+1;return t.idToInternalId.set(e,a),t.internalIdToId.push(e),a}return e>t.internalIdToId.length?Dt(t,e.toString()):e}function Os(t,e){if(t.internalIdToId.length<e)throw new Error(`Invalid internalId ${e}`);return t.internalIdToId[e-1]}async function u8(t,e){return{sharedInternalDocumentStore:e,docs:{},count:0}}async function p8(t,e){const r=Dt(t.sharedInternalDocumentStore,e);return t.docs[r]}async function c8(t,e){const r=e.length,a=Array.from({length:r});for(let n=0;n<r;n++){const i=Dt(t.sharedInternalDocumentStore,e[n]);a[n]=t.docs[i]}return a}async function m8(t){return t.docs}async function g8(t,e,r){const a=Dt(t.sharedInternalDocumentStore,e);return typeof t.docs[a]<"u"?!1:(t.docs[a]=r,t.count++,!0)}async function A8(t,e){const r=Dt(t.sharedInternalDocumentStore,e);return typeof t.docs[r]>"u"?!1:(delete t.docs[r],t.coun
* https://github.com/Starcounter-Jack/JSON-Patch
* (c) 2017-2022 Joachim Wester
* MIT licensed
*/const gS=Object.prototype.hasOwnProperty;function AS(t,e){return gS.call(t,e)}function hS(t){if(Array.isArray(t)){const r=new Array(t.length);for(let a=0;a<r.length;a++)r[a]=""+a;return r}if(Object.keys)return Object.keys(t);let e=[];for(let r in t)AS(t,r)&&e.push(r);return e}function Hs(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function zg(t){let e=0;const r=t.length;let a;for(;e<r;){if(a=t.charCodeAt(e),a>=48&&a<=57){e++;continue}return!1}return!0}function BS(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function jg(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let r=0,a=t.length;r<a;r++)if(jg(t[r]))return!0}else if(typeof t=="object"){const r=hS(t),a=r.length;for(var e=0;e<a;e++)if(jg(t[r[e]]))return!0}}return!1}function Sw(t,e){const r=[t];for(const a in e){const n=typeof e[a]=="object"?JSON.stringify(e[a],null,2):e[a];typeof n<"u"&&r.push(`${a}: ${n}`)}return r.join(`
`)}let CS=class extends Error{constructor(e,r,a,n,i){super(Sw(e,{name:r,index:a,operation:n,tree:i})),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.defineProperty(this,"operation",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"tree",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.setPrototypeOf(this,new.target.prototype),this.message=Sw(e,{name:r,index:a,operation:n,tree:i})}};const kt=CS,gs={add:function(t,e,r){return t[e]=this.value,{newDocument:r}},remove:function(t,e,r){var a=t[e];return delete t[e],{newDocument:r,removed:a}},replace:function(t,e,r){var a=t[e];return t[e]=this.value,{newDocument:r,removed:a}},move:function(t,e,r){let a=qg(r,this.path);a&&(a=Hs(a));const n=id(r,{op:"remove",path:this.from}).removed;return id(r,{op:"add",path:this.path,value:n}),{newDocument:r,removed:a}},copy:function(t,e,r){const a=qg(r,this.from);return id(r,{op:"add",path:this.path,value:Hs(a)}),{newDocument:r}},test:function(t,e,r){return{newDocument:r,test:Jc(t[e],this.value)}},_get:function(t,e,r){return this.value=t[e],{newDocument:r}}};var wS={add:function(t,e,r){return zg(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:r,index:e}},remove:function(t,e,r){var a=t.splice(e,1);return{newDocument:r,removed:a[0]}},replace:function(t,e,r){var a=t[e];return t[e]=this.value,{newDocument:r,removed:a}},move:gs.move,copy:gs.copy,test:gs.test,_get:gs._get};function qg(t,e){if(e=="")return t;var r={op:"_get",path:e};return id(t,r),r.value}function id(t,e,r=!1,a=!0,n=!0,i=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):$g(e,0)),e.path===""){let l={newDocument:t};if(e.op==="add")return l.newDocument=e.value,l;if(e.op==="replace")return l.newDocument=e.value,l.removed=t,l;if(e.op==="move"||e.op==="copy")return l.newDocument=qg(t,e.from),e.op==="move"&&(l.removed=t),l;if(e.op==="test"){if(l.test=Jc(t,e.value),l.test===!1)throw new kt("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return l.newDocument=t,l}else{if(e.op==="remove")return l.removed=t,l.newDocument=null,l;if(e.op==="_get")return e.value=t,l;if(r)throw new kt("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,t);return l}}else{a||(t=Hs(t));const s=(e.path||"").split("/");let o=t,d=1,u=s.length,c,p,A;for(typeof r=="function"?A=r:A=$g;;){if(p=s[d],p&&p.indexOf("~")!=-1&&(p=BS(p)),n&&(p=="__proto__"||p=="prototype"&&d>0&&s[d-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&c===void 0&&(o[p]===void 0?c=s.slice(0,d).join("/"):d==u-1&&(c=e.path),c!==void 0&&A(e,0,t,c)),d++,Array.isArray(o)){if(p==="-")p=o.length;else{if(r&&!zg(p))throw new kt("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,e,t);zg(p)&&(p=~~p)}if(d>=u){if(r&&e.op==="add"&&p>o.length)throw new kt("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,t);const m=wS[e.op].call(e,o,p,t);if(m.test===!1)throw new kt("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return m}}else if(d>=u){const m=gs[e.op].call(e,o,p,t);if(m.test===!1)throw new kt("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return m}if(o=o[p],r&&d<u&&(!o||typeof o!="object"))throw new kt("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}function xc(t,e,r,a=!0,n=!0){if(r&&!Array.isArray(e))throw new kt("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");a||(t=Hs(t));const i=new Array(e.length);for(let l=0,s=e.length;l<s;l++)i[l]=id(t,e[l],r,!0,n,l),t=i[l].newDocument;return i.newDocument=t,i}function $g(t,e,r,a){if(typeof t!="object"||t===null||Array.isArray(
data: ${JSON.stringify(n)}
`));a.enqueue(e.encode(`event: end
`)),a.close()}});return El.fromReadableStream(r)}function Lw(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.iterator]=="function"&&typeof t.next=="function"}function Tw(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.asyncIterator]=="function"}function*kw(t,e){const r=Ld.getInstance();for(;;){const{value:a,done:n}=r.run(t,e.next.bind(e));if(n)break;yield a}}async function*Uw(t,e){const r=Ld.getInstance(),a=e[Symbol.asyncIterator]();for(;;){const{value:n,done:i}=await r.run(t,a.next.bind(e));if(i)break;yield n}}function mr(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}let Vr=class extends Qc{constructor(){super(...arguments),Object.defineProperty(this,"lc_runnable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}getName(e){const r=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${r}${e}`:r}bind(e){return new zp({bound:this,kwargs:e,config:{}})}map(){return new BZ({bound:this})}withRetry(e){return new CZ({bound:this,kwargs:{},config:{},maxAttemptNumber:e==null?void 0:e.stopAfterAttempt,...e})}withConfig(e){return new zp({bound:this,config:e,kwargs:{}})}withFallbacks(e){return new KZ({runnable:this,fallbacks:e.fallbacks})}_getOptionsList(e,r=0){if(Array.isArray(e)&&e.length!==r)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${r} inputs`);if(Array.isArray(e))return e.map(Lt);if(r>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");const a=Object.fromEntries(Object.entries(e).filter(([n])=>n!=="runId"));return Array.from({length:r},(n,i)=>Lt(i===0?e:a))}return Array.from({length:r},()=>Lt(e))}async batch(e,r,a){var o;const n=this._getOptionsList(r??{},e.length),i=((o=n[0])==null?void 0:o.maxConcurrency)??(a==null?void 0:a.maxConcurrency),l=new RS({maxConcurrency:i,onFailedAttempt:d=>{throw d}}),s=e.map((d,u)=>l.call(async()=>{try{return await this.invoke(d,n[u])}catch(c){if(a!=null&&a.returnExceptions)return c;throw c}}));return Promise.all(s)}async*_streamIterator(e,r){yield this.invoke(e,r)}async stream(e,r){const a=new Ps(this._streamIterator(e,Lt(r)));return await a.setup,El.fromAsyncGenerator(a)}_separateRunnableConfigFromCallOptions(e){let r;e===void 0?r=Lt(e):r=Lt({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId});const a={...e};return delete a.callbacks,delete a.tags,delete a.metadata,delete a.runName,delete a.configurable,delete a.recursionLimit,delete a.maxConcurrency,delete a.runId,[r,a]}async _callWithConfig(e,r,a){const n=Lt(a),i=await Al(n),l=await(i==null?void 0:i.handleChainStart(this.toJSON(),mr(r,"input"),n.runId,n==null?void 0:n.runType,void 0,void 0,(n==null?void 0:n.runName)??this.getName()));delete n.runId;let s;try{s=await e.call(this,r,n,l)}catch(o){throw await(l==null?void 0:l.handleChainError(o)),o}return await(l==null?void 0:l.handleChainEnd(mr(s,"output"))),s}async _batchWithConfig(e,r,a,n){const i=this._getOptionsList(a??{},r.length),l=await Promise.all(i.map(Al)),s=await Promise.all(l.map(async(d,u)=>{const c=await(d==null?void 0:d.handleChainStart(this.toJSON(),mr(r[u],"input"),i[u].runId,i[u].runType,void 0,void 0,i[u].runName??this.getName()));return delete i[u].runId,c}));let o;try{o=await e.call(this,r,i,s,n)}catch(d){throw await Promise.all(s.map(u=>u==null?void 0:u.handleChainError(d))),d}return await Promise.all(s.map(d=>d==null?void 0:d.handleChainEnd(mr(o,"output")))),o}async*_transformStreamWithConfig(e,r,a){let n,i=!0,l,s=!0;const o=Lt(a),d=await Al(o);async function*u(){for await(const p of e){if(i)if(n===void 0)n=p;else try{n=oi(n,p)}catch{n=void 0,i=!1}yield p}}let c;try{const p=await KS(r.bind(this),u(),async()=>d==null?void 0:d.handleChainStart(this.toJSON(),{input:""},o.runId,o.runType,void 0,void 0,o.runName??this.getName()),o);delete o.runId
Instead got an unsupported type.`)}let fZ=class extends Vr{static lc_name(){return"RunnableAssign"}constructor(e){e instanceof pB&&(e={mapper:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"mapper",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.mapper=e.mapper}async invoke(e,r){const a=await this.mapper.invoke(e,r);return{...e,...a}}async*_transform(e,r,a){const n=this.mapper.getStepsKeys(),[i,l]=j3(e),s=this.mapper.transform(l,Hr(a,{callbacks:r==null?void 0:r.getChild()})),o=s.next();for await(const d of i){if(typeof d!="object"||Array.isArray(d))throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof d}`);const u=Object.fromEntries(Object.entries(d).filter(([c])=>!n.includes(c)));Object.keys(u).length>0&&(yield u)}yield(await o).value;for await(const d of s)yield d}transform(e,r){return this._transformStreamWithConfig(e,this._transform.bind(this),r)}async stream(e,r){async function*a(){yield e}const n=new Ps(this.transform(a(),r));return await n.setup,El.fromAsyncGenerator(n)}},QZ=class extends Vr{static lc_name(){return"RunnablePick"}constructor(e){(typeof e=="string"||Array.isArray(e))&&(e={keys:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"keys",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keys=e.keys}async _pick(e){if(typeof this.keys=="string")return e[this.keys];{const r=this.keys.map(a=>[a,e[a]]).filter(a=>a[1]!==void 0);return r.length===0?void 0:Object.fromEntries(r)}}async invoke(e,r){return this._callWithConfig(this._pick.bind(this),e,r)}async*_transform(e){for await(const r of e){const a=await this._pick(r);a!==void 0&&(yield a)}}transform(e,r){return this._transformStreamWithConfig(e,this._transform.bind(this),r)}async stream(e,r){async function*a(){yield e}const n=new Ps(this.transform(a(),r));return await n.setup,El.fromAsyncGenerator(n)}};class WZ extends Vr{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","documents","transformers"]})}invoke(e,r){return this.transformDocuments(e)}}var a1={};a1.byteLength=yZ;a1.toByteArray=EZ;a1.fromByteArray=ZZ;var Ha=[],Jr=[],vZ=typeof Uint8Array<"u"?Uint8Array:Array,bm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var Ol=0,FZ=bm.length;Ol<FZ;++Ol)Ha[Ol]=bm[Ol],Jr[bm.charCodeAt(Ol)]=Ol;Jr["-".charCodeAt(0)]=62;Jr["_".charCodeAt(0)]=63;function dQ(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var a=r===e?0:4-r%4;return[r,a]}function yZ(t){var e=dQ(t),r=e[0],a=e[1];return(r+a)*3/4-a}function RZ(t,e,r){return(e+r)*3/4-r}function EZ(t){var e,r=dQ(t),a=r[0],n=r[1],i=new vZ(RZ(t,a,n)),l=0,s=n>0?a-4:a,o;for(o=0;o<s;o+=4)e=Jr[t.charCodeAt(o)]<<18|Jr[t.charCodeAt(o+1)]<<12|Jr[t.charCodeAt(o+2)]<<6|Jr[t.charCodeAt(o+3)],i[l++]=e>>16&255,i[l++]=e>>8&255,i[l++]=e&255;return n===2&&(e=Jr[t.charCodeAt(o)]<<2|Jr[t.charCodeAt(o+1)]>>4,i[l++]=e&255),n===1&&(e=Jr[t.charCodeAt(o)]<<10|Jr[t.charCodeAt(o+1)]<<4|Jr[t.charCodeAt(o+2)]>>2,i[l++]=e>>8&255,i[l++]=e&255),i}function GZ(t){return Ha[t>>18&63]+Ha[t>>12&63]+Ha[t>>6&63]+Ha[t&63]}function SZ(t,e,r){for(var a,n=[],i=e;i<r;i+=3)a=(t[i]<<16&16711680)+(t[i+1]<<8&65280)+(t[i+2]&255),n.push(GZ(a));return n.join("")}function ZZ(t){for(var e,r=t.length,a=r%3,n=[],i=16383,l=0,s=r-a;l<s;l+=i)n.push(SZ(t,l,l+i>s?s:l+i));return a===1?(e=t[r-1],n.push(Ha[e>>2]+Ha[e<<4&63]+"==")):a===2&&(e=(t[r-2]<<8)+t[r-1],n.push(Ha[e>>10]+Ha[e>>4&63]+Ha[e<<2&63]+"=")),n.join("")}var XZ=Object.defineProperty,HZ=(t,e,r)=>e in t?XZ(t,e,{enumerable:!0,configurable:!0,writable:!0,
`).filter(Boolean).reduce((n,i)=>{const[l,s,...o]=i.split(" "),d=Number.parseInt(s,10);return o.forEach((u,c)=>n[u]=d+c),n},{});for(const[n,i]of Object.entries(a)){const l=a1.toByteArray(n);this.rankMap.set(l.join(","),i),this.textMap.set(i,l)}this.specialTokens={...e.special_tokens,...r},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((n,[i,l])=>(n[l]=this.textEncoder.encode(i),n),{})}encode(e,r=[],a="all"){const n=new RegExp(this.patStr,"ug"),i=aA.specialTokenRegex(Object.keys(this.specialTokens)),l=[],s=new Set(r==="all"?Object.keys(this.specialTokens):r),o=new Set(a==="all"?Object.keys(this.specialTokens).filter(u=>!s.has(u)):a);if(o.size>0){const u=aA.specialTokenRegex([...o]),c=e.match(u);if(c!=null)throw new Error(`The text contains a special token that is not allowed: ${c[0]}`)}let d=0;for(;;){let u=null,c=d;for(;i.lastIndex=c,u=i.exec(e),!(u==null||s.has(u[0]));)c=u.index+1;const p=(u==null?void 0:u.index)??e.length;for(const m of e.substring(d,p).matchAll(n)){const h=this.textEncoder.encode(m[0]),C=this.rankMap.get(h.join(","));if(C!=null){l.push(C);continue}l.push(...NZ(h,this.rankMap))}if(u==null)break;let A=this.specialTokens[u[0]];l.push(A),d=u.index+u[0].length}return l}decode(e){const r=[];let a=0;for(let l=0;l<e.length;++l){const s=e[l],o=this.textMap.get(s)??this.inverseSpecialTokens[s];o!=null&&(r.push(o),a+=o.length)}const n=new Uint8Array(a);let i=0;for(const l of r)n.set(l,i),i+=l.length;return this.textDecoder.decode(n)}},TZ=aA;VZ(TZ,"specialTokenRegex",t=>new RegExp(t.map(e=>LZ(e)).join("|"),"g"));class kZ extends WZ{constructor(e){if(super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","document_transformers","text_splitters"]}),Object.defineProperty(this,"chunkSize",{enumerable:!0,configurable:!0,writable:!0,value:1e3}),Object.defineProperty(this,"chunkOverlap",{enumerable:!0,configurable:!0,writable:!0,value:200}),Object.defineProperty(this,"keepSeparator",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lengthFunction",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.chunkSize=(e==null?void 0:e.chunkSize)??this.chunkSize,this.chunkOverlap=(e==null?void 0:e.chunkOverlap)??this.chunkOverlap,this.keepSeparator=(e==null?void 0:e.keepSeparator)??this.keepSeparator,this.lengthFunction=(e==null?void 0:e.lengthFunction)??(r=>r.length),this.chunkOverlap>=this.chunkSize)throw new Error("Cannot have chunkOverlap >= chunkSize")}async transformDocuments(e,r={}){return this.splitDocuments(e,r)}splitOnSeparator(e,r){let a;if(r)if(this.keepSeparator){const n=r.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&");a=e.split(new RegExp(`(?=${n})`))}else a=e.split(r);else a=e.split("");return a.filter(n=>n!=="")}async createDocuments(e,r=[],a={}){const n=r.length>0?r:[...Array(e.length)].map(()=>({})),{chunkHeader:i="",chunkOverlapHeader:l="(cont'd) ",appendChunkOverlapHeader:s=!1}=a,o=new Array;for(let d=0;d<e.length;d+=1){const u=e[d];let c=1,p=null,A=-1;for(const m of await this.splitText(u)){let h=i;const C=u.indexOf(m,A+1);if(p===null){const K=this.numberOfNewLines(u,0,C);c+=K}else{const K=A+await this.lengthFunction(p);if(K<C){const W=this.numberOfNewLines(u,K,C);c+=W}else if(K>C){const W=this.numberOfNewLines(u,C,K);c-=W}s&&(h+=l)}const w=this.numberOfNewLines(m),b=n[d].loc&&typeof n[d].loc=="object"?{...n[d].loc}:{};b.lines={from:c,to:c+w};const f={...n[d],loc:b};h+=m,o.push(new pG({pageContent:h,metadata:f})),c+=w,p=m,A=C}}return o}numberOfNewLines(e,r,a){return(e.slice(r,a).match(/\n/g)||[]).length}async splitDocuments(e,r={}){const a=e.filter(l=>l.pageContent!==void 0),n=a.map(l=>l.pageContent),i=a.map(l=>l.metadata);return this.createDocuments(n,i,r)}joinDocs(e,r){const a=e.join(r).trim();return a===""?null:a}async mergeSplits(e,r){const a=[],n=[];let i=0;for(const s of e){const o=await this.lengthFunction(s);if(i+o+n.length*r.length>this.chunkSize&&(i>this.chunkSize&&console.warn(`Created a chunk of size ${i}, +
which is longer than the specified ${this.chunkSize}`),n.length>0)){const d=this.joinDocs(n,r);for(d!==null&&a.push(d);i>this.chunkOverlap||i+o+n.length*r.length>this.chunkSize&&i>0;)i-=await this.lengthFunction(n[0]),n.shift()}n.push(s),i+=o}const l=this.joinDocs(n,r);return l!==null&&a.push(l),a}}class Pc extends kZ{static lc_name(){return"RecursiveCharacterTextSplitter"}constructor(e){super(e),Object.defineProperty(this,"separators",{enumerable:!0,configurable:!0,writable:!0,value:[`
`,`
`," ",""]}),this.separators=(e==null?void 0:e.separators)??this.separators,this.keepSeparator=(e==null?void 0:e.keepSeparator)??!0}async _splitText(e,r){const a=[];let n=r[r.length-1],i;for(let d=0;d<r.length;d+=1){const u=r[d];if(u===""){n=u;break}if(e.includes(u)){n=u,i=r.slice(d+1);break}}const l=this.splitOnSeparator(e,n);let s=[];const o=this.keepSeparator?"":n;for(const d of l)if(await this.lengthFunction(d)<this.chunkSize)s.push(d);else{if(s.length){const u=await this.mergeSplits(s,o);a.push(...u),s=[]}if(!i)a.push(d);else{const u=await this._splitText(d,i);a.push(...u)}}if(s.length){const d=await this.mergeSplits(s,o);a.push(...d)}return a}async splitText(e){return this._splitText(e,this.separators)}static fromLanguage(e,r){return new Pc({...r,separators:Pc.getSeparatorsForLanguage(e)})}static getSeparatorsForLanguage(e){if(e==="cpp")return[`
class `,`
void `,`
int `,`
float `,`
double `,`
if `,`
for `,`
while `,`
switch `,`
case `,`
`,`
`," ",""];if(e==="go")return[`
func `,`
var `,`
const `,`
type `,`
if `,`
for `,`
switch `,`
case `,`
`,`
`," ",""];if(e==="java")return[`
class `,`
public `,`
protected `,`
private `,`
static `,`
if `,`
for `,`
while `,`
switch `,`
case `,`
`,`
`," ",""];if(e==="js")return[`
function `,`
const `,`
let `,`
var `,`
class `,`
if `,`
for `,`
while `,`
switch `,`
case `,`
default `,`
`,`
`," ",""];if(e==="php")return[`
function `,`
class `,`
if `,`
foreach `,`
while `,`
do `,`
switch `,`
case `,`
`,`
`," ",""];if(e==="proto")return[`
message `,`
service `,`
enum `,`
option `,`
import `,`
syntax `,`
`,`
`," ",""];if(e==="python")return[`
class `,`
def `,`
def `,`
`,`
`," ",""];if(e==="rst")return[`
===
`,`
---
`,`
***
`,`
.. `,`
`,`
`," ",""];if(e==="ruby")return[`
def `,`
class `,`
if `,`
unless `,`
while `,`
for `,`
do `,`
begin `,`
rescue `,`
`,`
`," ",""];if(e==="rust")return[`
fn `,`
const `,`
let `,`
if `,`
while `,`
for `,`
loop `,`
match `,`
const `,`
`,`
`," ",""];if(e==="scala")return[`
class `,`
object `,`
def `,`
val `,`
var `,`
if `,`
for `,`
while `,`
match `,`
case `,`
`,`
`," ",""];if(e==="swift")return[`
func `,`
class `,`
struct `,`
enum `,`
if `,`
for `,`
while `,`
do `,`
switch `,`
case `,`
`,`
`," ",""];if(e==="markdown")return[`
## `,`
### `,`
#### `,`
##### `,`
###### `,"```\n\n",`
***
`,`
---
`,`
___
`,`
`,`
`," ",""];if(e==="latex")return[`
\\chapter{`,`
\\section{`,`
\\subsection{`,`
\\subsubsection{`,`
\\begin{enumerate}`,`
\\begin{itemize}`,`
\\begin{description}`,`
\\begin{list}`,`
\\begin{quote}`,`
\\begin{quotation}`,`
\\begin{verse}`,`
\\begin{verbatim}`,`
\\begin{align}`,"$$","$",`
`,`
`," ",""];if(e==="html")return["<body>","<div>","<p>","<br>","<li>","<h1>","<h2>","<h3>","<h4>","<h5>","<h6>","<span>","<table>","<tr>","<td>","<th>","<ul>","<ol>","<header>","<footer>","<nav>","<head>","<style>","<script>","<meta>","<title>"," ",""];if(e==="sol")return[`
pragma `,`
using `,`
contract `,`
interface `,`
library `,`
constructor `,`
type `,`
function `,`
event `,`
modifier `,`
error `,`
struct `,`
enum `,`
if `,`
for `,`
while `,`
do while `,`
assembly `,`
`,`
`," ",""];throw new Error(`Language ${e} is not supported.`)}}var UZ=Object.create,n1=Object.defineProperty,_Z=Object.getOwnPropertyDescriptor,cB=Object.getOwnPropertyNames,IZ=Object.getPrototypeOf,DZ=Object.prototype.hasOwnProperty,MZ=(t,e,r)=>e in t?n1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,hi=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),be=(t,e)=>function(){return t&&(e=(0,t[cB(t)[0]])(t=0)),e},tt=(t,e)=>function(){return e||(0,t[cB(t)[0]])((e={exports:{}}).exports,e),e.exports},iu=(t,e)=>{for(var r in e)n1(t,r,{get:e[r],enumerable:!0})},xZ=(t,e,r,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of cB(e))!DZ.call(t,n)&&n!==r&&n1(t,n,{get:()=>e[n],enumerable:!(a=_Z(e,n))||a.enumerable});return t},Gr=(t,e,r)=>(r=t!=null?UZ(IZ(t)):{},xZ(e||!t||!t.__esModule?n1(r,"default",{value:t,enumerable:!0}):r,t)),Vi=(t,e,r)=>(MZ(t,typeof e!="symbol"?e+"":e,r),r),JZ=tt({"node_modules/decamelize/index.js"(t,e){e.exports=function(r,a){if(typeof r!="string")throw new TypeError("Expected a string");return a=typeof a>"u"?"_":a,r.replace(/([a-z\d])([A-Z])/g,"$1"+a+"$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g,"$1"+a+"$2").toLowerCase()}}}),OZ=tt({"node_modules/camelcase/index.js"(t,e){var r=/[\p{Lu}]/u,a=/[\p{Ll}]/u,n=/^[\p{Lu}](?![\p{Lu}])/gu,i=/([\p{Alpha}\p{N}_]|$)/u,l=/[_.\- ]+/,s=new RegExp("^"+l.source),o=new RegExp(l.source+i.source,"gu"),d=new RegExp("\\d+"+i.source,"gu"),u=(m,h,C)=>{let w=!1,b=!1,f=!1;for(let K=0;K<m.length;K++){const W=m[K];w&&r.test(W)?(m=m.slice(0,K)+"-"+m.slice(K),w=!1,f=b,b=!0,K++):b&&f&&a.test(W)?(m=m.slice(0,K-1)+"-"+m.slice(K-1),f=b,b=!1,w=!0):(w=h(W)===W&&C(W)!==W,f=b,b=C(W)===W&&h(W)!==W)}return m},c=(m,h)=>(n.lastIndex=0,m.replace(n,C=>h(C))),p=(m,h)=>(o.lastIndex=0,d.lastIndex=0,m.replace(o,(C,w)=>h(w)).replace(d,C=>h(C))),A=(m,h)=>{if(!(typeof m=="string"||Array.isArray(m)))throw new TypeError("Expected the input to be `string | string[]`");if(h={pascalCase:!1,preserveConsecutiveUppercase:!1,...h},Array.isArray(m)?m=m.map(f=>f.trim()).filter(f=>f.length).join("-"):m=m.trim(),m.length===0)return"";const C=h.locale===!1?f=>f.toLowerCase():f=>f.toLocaleLowerCase(h.locale),w=h.locale===!1?f=>f.toUpperCase():f=>f.toLocaleUpperCase(h.locale);return m.length===1?h.pascalCase?w(m):C(m):(m!==C(m)&&(m=u(m,C,w)),m=m.replace(s,""),h.preserveConsecutiveUppercase?m=c(m,C):m=C(m),h.pascalCase&&(m=w(m.charAt(0))+m.slice(1)),p(m,w))};e.exports=A,e.exports.default=A}});function PZ(t,e){return(e==null?void 0:e[t])||(0,uQ.default)(t)}function zZ(t,e,r){const a={};for(const n in t)Object.hasOwn(t,n)&&(a[e(n,r)]=t[n]);return a}var uQ,jZ=be({"node_modules/@langchain/core/dist/load/map_keys.js"(){uQ=Gr(JZ(),1),Gr(OZ(),1)}});function _w(t){return Array.isArray(t)?[...t]:{...t}}function qZ(t,e){const r=_w(t);for(const[a,n]of Object.entries(e)){const[i,...l]=a.split(".").reverse();let s=r;for(const o of l.reverse()){if(s[o]===void 0)break;s[o]=_w(s[o]),s=s[o]}s[i]!==void 0&&(s[i]={lc:1,type:"secret",id:[n]})}return r}function pQ(t){const e=Object.getPrototypeOf(t);return typeof t.lc_name=="function"&&(typeof e.lc_name!="function"||t.lc_name()!==e.lc_name())?t.lc_name():t.name}var Fl,lu=be({"node_modules/@langchain/core/dist/load/serializable.js"(){jZ(),Fl=class cQ{static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,pQ(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}constructor(e,...r){Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.lc_kwargs=e||{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof cQ||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const e={},r={},a=Object.keys(this.lc_kwargs).reduce((n,i
`)}var zl,Yi,Td,nA,i1,ti,gQ,iA,lA,AQ,kd,sA,ta=be({"node_modules/@langchain/core/dist/messages/index.js"(){lu(),zl=class extends Fl{get lc_aliases(){return{additional_kwargs:"additional_kwargs"}}get text(){return typeof this.content=="string"?this.content:""}constructor(t,e){typeof t=="string"&&(t={content:t,additional_kwargs:e}),t.additional_kwargs||(t.additional_kwargs={}),super(t),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","messages"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"content",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"additional_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=t.name,this.content=t.content,this.additional_kwargs=t.additional_kwargs}toDict(){return{type:this._getType(),data:this.toJSON().kwargs}}toChunk(){const t=this._getType();if(t==="human")return new nA({...this});if(t==="ai")return new ti({...this});if(t==="system")return new iA({...this});if(t==="function")return new lA({...this});if(kd.isInstance(this))return new sA({...this});throw new Error("Unknown message type.")}},Yi=class extends zl{static _mergeAdditionalKwargs(t,e){var a,n;const r={...t};for(const[i,l]of Object.entries(e))if(r[i]===void 0)r[i]=l;else{if(typeof r[i]!=typeof l)throw new Error(`additional_kwargs[${i}] already exists in the message chunk, but with a different type.`);if(typeof r[i]=="string")r[i]=r[i]+l;else if(!Array.isArray(r[i])&&typeof r[i]=="object")r[i]=this._mergeAdditionalKwargs(r[i],l);else if(i==="tool_calls"&&Iw(r[i])&&Iw(l))for(const s of l)((a=r[i])==null?void 0:a[s.index])!==void 0?r[i]=(n=r[i])==null?void 0:n.map((o,d)=>d!==s.index?o:{...o,...s,function:{name:s.function.name??o.function.name,arguments:(o.function.arguments??"")+(s.function.arguments??"")}}):r[i][s.index]=s;else throw new Error(`additional_kwargs[${i}] already exists in this message chunk.`)}return r}},Td=class extends zl{static lc_name(){return"HumanMessage"}_getType(){return"human"}},nA=class oA extends Yi{static lc_name(){return"HumanMessageChunk"}_getType(){return"human"}concat(e){return new oA({content:Pl(this.content,e.content),additional_kwargs:oA._mergeAdditionalKwargs(this.additional_kwargs,e.additional_kwargs)})}},i1=class extends zl{static lc_name(){return"AIMessage"}_getType(){return"ai"}},ti=class dA extends Yi{static lc_name(){return"AIMessageChunk"}_getType(){return"ai"}concat(e){return new dA({content:Pl(this.content,e.content),additional_kwargs:dA._mergeAdditionalKwargs(this.additional_kwargs,e.additional_kwargs)})}},gQ=class extends zl{static lc_name(){return"SystemMessage"}_getType(){return"system"}},iA=class uA extends Yi{static lc_name(){return"SystemMessageChunk"}_getType(){return"system"}concat(e){return new uA({content:Pl(this.content,e.content),additional_kwargs:uA._mergeAdditionalKwargs(this.additional_kwargs,e.additional_kwargs)})}},lA=class pA extends Yi{static lc_name(){return"FunctionMessageChunk"}_getType(){return"function"}concat(e){return new pA({content:Pl(this.content,e.content),additional_kwargs:pA._mergeAdditionalKwargs(this.additional_kwargs,e.additional_kwargs),name:this.name??""})}},AQ=class cA extends Yi{constructor(e){super(e),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=e.tool_call_id}static lc_name(){return"ToolMessageChunk"}_getType(){return"tool"}concat(e){return new cA({content:Pl(this.content,e.content),additional_kwargs:cA._mergeAdditionalKwargs(this.additional_kwargs,e.additional_kwargs),tool_call_id:this.tool_call_id})}},kd=class hQ extends zl{static lc_name(){return"ChatMessage"}static _chatMessageClass(){return hQ}constructor(e,r){typeof e=="string"&&(e={content:e,role:r}),super(e),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=e.role}_getType(){ret
${t.stack}`:""):typeof t=="string"?t:`${t}`}_addChildRun(t,e){t.child_runs.push(e)}async _startTrace(t){var a;const e=K7(t.start_time,t.id),r={...t};if(r.parent_run_id!==void 0){const n=this.runMap.get(r.parent_run_id);n&&(this._addChildRun(n,r),n.child_execution_order=Math.max(n.child_execution_order,r.child_execution_order),r.trace_id=n.trace_id,n.dotted_order!==void 0&&(r.dotted_order=[n.dotted_order,e].join(".")))}else r.trace_id=r.id,r.dotted_order=e;this.runMap.set(r.id,r),await((a=this.onRunCreate)==null?void 0:a.call(this,r))}async _endTrace(t){var r;const e=t.parent_run_id!==void 0&&this.runMap.get(t.parent_run_id);e?e.child_execution_order=Math.max(e.child_execution_order,t.child_execution_order):await this.persistRun(t),this.runMap.delete(t.id),await((r=this.onRunUpdate)==null?void 0:r.call(this,t))}_getExecutionOrder(t){const e=t!==void 0&&this.runMap.get(t);return e?e.child_execution_order+1:1}async handleLLMStart(t,e,r,a,n,i,l,s){var p;const o=this._getExecutionOrder(a),d=Date.now(),u=l?{...n,metadata:l}:n,c={id:r,name:s??t.id[t.id.length-1],parent_run_id:a,start_time:d,serialized:t,events:[{name:"start",time:new Date(d).toISOString()}],inputs:{prompts:e},execution_order:o,child_runs:[],child_execution_order:o,run_type:"llm",extra:u??{},tags:i||[]};return await this._startTrace(c),await((p=this.onLLMStart)==null?void 0:p.call(this,c)),c}async handleChatModelStart(t,e,r,a,n,i,l,s){var p;const o=this._getExecutionOrder(a),d=Date.now(),u=l?{...n,metadata:l}:n,c={id:r,name:s??t.id[t.id.length-1],parent_run_id:a,start_time:d,serialized:t,events:[{name:"start",time:new Date(d).toISOString()}],inputs:{messages:e},execution_order:o,child_runs:[],child_execution_order:o,run_type:"llm",extra:u??{},tags:i||[]};return await this._startTrace(c),await((p=this.onLLMStart)==null?void 0:p.call(this,c)),c}async handleLLMEnd(t,e){var a;const r=this.runMap.get(e);if(!r||(r==null?void 0:r.run_type)!=="llm")throw new Error("No LLM run to end.");return r.end_time=Date.now(),r.outputs=t,r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await((a=this.onLLMEnd)==null?void 0:a.call(this,r)),await this._endTrace(r),r}async handleLLMError(t,e){var a;const r=this.runMap.get(e);if(!r||(r==null?void 0:r.run_type)!=="llm")throw new Error("No LLM run to end.");return r.end_time=Date.now(),r.error=this.stringifyError(t),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await((a=this.onLLMError)==null?void 0:a.call(this,r)),await this._endTrace(r),r}async handleChainStart(t,e,r,a,n,i,l,s){var c;const o=this._getExecutionOrder(a),d=Date.now(),u={id:r,name:s??t.id[t.id.length-1],parent_run_id:a,start_time:d,serialized:t,events:[{name:"start",time:new Date(d).toISOString()}],inputs:e,execution_order:o,child_execution_order:o,run_type:l??"chain",child_runs:[],extra:i?{metadata:i}:{},tags:n||[]};return await this._startTrace(u),await((c=this.onChainStart)==null?void 0:c.call(this,u)),u}async handleChainEnd(t,e,r,a,n){var l;const i=this.runMap.get(e);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.outputs=fm(t,"output"),i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),(n==null?void 0:n.inputs)!==void 0&&(i.inputs=fm(n.inputs,"input")),await((l=this.onChainEnd)==null?void 0:l.call(this,i)),await this._endTrace(i),i}async handleChainError(t,e,r,a,n){var l;const i=this.runMap.get(e);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(t),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),(n==null?void 0:n.inputs)!==void 0&&(i.inputs=fm(n.inputs,"input")),await((l=this.onChainError)==null?void 0:l.call(this,i)),await this._endTrace(i),i}async handleToolStart(t,e,r,a,n,i,l){var u;const s=this._getExecutionOrder(a),o=Date.now(),d={id:r,name:l??t.id[t.id.length-1],parent_run_id:a,start_time:o,serialized:t,events:[{name:"start",time:new Date(o).toISOString()}],inputs:{input:e},execution_order:s,child_execution_order:s,run_type:"tool",child_runs:[],extra:i?{metadata:i}:{},tags:n||[]};return await this._s
`).map(s=>JSON.parse(s))}async*listDatasets({limit:e=100,offset:r=0,datasetIds:a,datasetName:n,datasetNameContains:i}={}){const l="/datasets",s=new URLSearchParams({limit:e.toString(),offset:r.toString()});if(a!==void 0)for(const o of a)s.append("id",o);n!==void 0&&s.append("name",n),i!==void 0&&s.append("name_contains",i);for await(const o of this._getPaginated(l,s))yield*o}async deleteDataset({datasetId:e,datasetName:r}){let a="/datasets",n=e;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(r!==void 0&&(n=(await this.readDataset({datasetName:r})).id),n!==void 0)Et(n),a+=`/${n}`;else throw new Error("Must provide datasetName or datasetId");const i=await this.caller.call(fetch,this.apiUrl+a,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms)});if(!i.ok)throw new Error(`Failed to delete ${a}: ${i.status} ${i.statusText}`);await i.json()}async createExample(e,r,{datasetId:a,datasetName:n,createdAt:i,exampleId:l}){let s=a;if(s===void 0&&n===void 0)throw new Error("Must provide either datasetName or datasetId");if(s!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");s===void 0&&(s=(await this.readDataset({datasetName:n})).id);const o=i||new Date,d={dataset_id:s,inputs:e,outputs:r,created_at:o==null?void 0:o.toISOString(),id:l},u=await this.caller.call(fetch,`${this.apiUrl}/examples`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(d),signal:AbortSignal.timeout(this.timeout_ms)});if(!u.ok)throw new Error(`Failed to create example: ${u.status} ${u.statusText}`);return await u.json()}async createExamples(e){const{inputs:r,outputs:a,sourceRunIds:n,exampleIds:i,datasetId:l,datasetName:s}=e;let o=l;if(o===void 0&&s===void 0)throw new Error("Must provide either datasetName or datasetId");if(o!==void 0&&s!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");o===void 0&&(o=(await this.readDataset({datasetName:s})).id);const d=r.map((p,A)=>({dataset_id:o,inputs:p,outputs:a?a[A]:void 0,id:i?i[A]:void 0,source_run_id:n?n[A]:void 0})),u=await this.caller.call(fetch,`${this.apiUrl}/examples/bulk`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(d),signal:AbortSignal.timeout(this.timeout_ms)});if(!u.ok)throw new Error(`Failed to create examples: ${u.status} ${u.statusText}`);return await u.json()}async createLLMExample(e,r,a){return this.createExample({input:e},{output:r},a)}async createChatExample(e,r,a){const n=e.map(l=>jw(l)?qw(l):l),i=jw(r)?qw(r):r;return this.createExample({input:n},{output:i},a)}async readExample(e){Et(e);const r=`/examples/${e}`;return await this._get(r)}async*listExamples({datasetId:e,datasetName:r,exampleIds:a,asOf:n,inlineS3Urls:i}={}){let l;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)l=e;else if(r!==void 0)l=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide a datasetName or datasetId");const s=new URLSearchParams({dataset:l}),o=n?typeof n=="string"?n:n==null?void 0:n.toISOString():void 0;o&&s.append("as_of",o);const d=i??!0;if(s.append("inline_s3_urls",d.toString()),a!==void 0)for(const u of a)s.append("id",u);for await(const u of this._getPaginated("/examples",s))yield*u}async deleteExample(e){Et(e);const r=`/examples/${e}`,a=await this.caller.call(fetch,this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms)});if(!a.ok)throw new Error(`Failed to delete ${r}: ${a.status} ${a.statusText}`);await a.json()}async updateExample(e,r){Et(e);const a=await this.caller.call(fetch,`${this.apiUrl}/examples/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(r),signal:AbortSignal.timeout(this.timeout_ms)});if(!a.ok)throw new Error(`Failed to update example ${e}: ${a.status} ${a.statusText}`);return await a.json()}async evaluateRun(e,r,{sourceInfo:a,loadChildRuns:n,referenceExample:i}={loadCh
`)}var GQ,fB,jc=be({"node_modules/@langchain/core/dist/utils/fast-json-patch/src/helpers.js"(){GQ=Object.prototype.hasOwnProperty,fB=class extends Error{constructor(t,e,r,a,n){super(B2(t,{name:e,index:r,operation:a,tree:n})),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"operation",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.defineProperty(this,"tree",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.setPrototypeOf(this,new.target.prototype),this.message=B2(t,{name:e,index:r,operation:a,tree:n})}}}}),SQ={};iu(SQ,{JsonPatchError:()=>St,_areEquals:()=>Ud,applyOperation:()=>hl,applyPatch:()=>sd,applyReducer:()=>L7,deepClone:()=>XQ,getValueByPointer:()=>qc,validate:()=>ZQ,validator:()=>$c});function qc(t,e){if(e=="")return t;var r={op:"_get",path:e};return hl(t,r),r.value}function hl(t,e,r=!1,a=!0,n=!0,i=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):$c(e,0)),e.path===""){let l={newDocument:t};if(e.op==="add")return l.newDocument=e.value,l;if(e.op==="replace")return l.newDocument=e.value,l.removed=t,l;if(e.op==="move"||e.op==="copy")return l.newDocument=qc(t,e.from),e.op==="move"&&(l.removed=t),l;if(e.op==="test"){if(l.test=Ud(t,e.value),l.test===!1)throw new St("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return l.newDocument=t,l}else{if(e.op==="remove")return l.removed=t,l.newDocument=null,l;if(e.op==="_get")return e.value=t,l;if(r)throw new St("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,t);return l}}else{a||(t=zr(t));const s=(e.path||"").split("/");let o=t,d=1,u=s.length,c,p,A;for(typeof r=="function"?A=r:A=$c;;){if(p=s[d],p&&p.indexOf("~")!=-1&&(p=EQ(p)),n&&(p=="__proto__"||p=="prototype"&&d>0&&s[d-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&c===void 0&&(o[p]===void 0?c=s.slice(0,d).join("/"):d==u-1&&(c=e.path),c!==void 0&&A(e,0,t,c)),d++,Array.isArray(o)){if(p==="-")p=o.length;else{if(r&&!wA(p))throw new St("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,e,t);wA(p)&&(p=~~p)}if(d>=u){if(r&&e.op==="add"&&p>o.length)throw new St("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,t);const m=HQ[e.op].call(e,o,p,t);if(m.test===!1)throw new St("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return m}}else if(d>=u){const m=$i[e.op].call(e,o,p,t);if(m.test===!1)throw new St("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return m}if(o=o[p],r&&d<u&&(!o||typeof o!="object"))throw new St("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}function sd(t,e,r,a=!0,n=!0){if(r&&!Array.isArray(e))throw new St("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");a||(t=zr(t));const i=new Array(e.length);for(let l=0,s=e.length;l<s;l++)i[l]=hl(t,e[l],r,!0,n,l),t=i[l].newDocument;return i.newDocument=t,i}function L7(t,e,r){const a=hl(t,e);if(a.test===!1)throw new St("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return a.newDocument}function $c(t,e,r,a){if(typeof t!="object"||t===null||Array.isArray(t))throw new St("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if($i[t.op]){if(typeof t.path!="string")throw new St("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new St('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,r);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new St("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,r
Instead got an unsupported type.`)}var Zm,Ot,Co,W2,v2,Bi,od,kQ,F2,yA,y2,Ma=be({"node_modules/@langchain/core/dist/runnables/base.js"(){Zm=Gr(hB(),1),uu(),I7(),lu(),pu(),zs(),s1(),D7(),M7(),NQ(),Ot=class extends Fl{constructor(){super(...arguments),Object.defineProperty(this,"lc_runnable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}getName(t){const e=this.name??this.constructor.lc_name()??this.constructor.name;return t?`${e}${t}`:e}bind(t){return new Co({bound:this,kwargs:t,config:{}})}map(){return new W2({bound:this})}withRetry(t){return new v2({bound:this,kwargs:{},config:{},maxAttemptNumber:t==null?void 0:t.stopAfterAttempt,...t})}withConfig(t){return new Co({bound:this,config:t,kwargs:{}})}withFallbacks(t){return new F2({runnable:this,fallbacks:t.fallbacks})}_getOptionsList(t,e=0){if(Array.isArray(t)){if(t.length!==e)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${t.length} options for ${e} inputs`);return t.map(lr)}return Array.from({length:e},()=>lr(t))}async batch(t,e,r){var s;const a=this._getOptionsList(e??{},t.length),n=((s=a[0])==null?void 0:s.maxConcurrency)??(r==null?void 0:r.maxConcurrency),i=new su({maxConcurrency:n,onFailedAttempt:o=>{throw o}}),l=t.map((o,d)=>i.call(async()=>{try{return await this.invoke(o,a[d])}catch(u){if(r!=null&&r.returnExceptions)return u;throw u}}));return Promise.all(l)}async*_streamIterator(t,e){yield this.invoke(t,e)}async stream(t,e){const r=new tl(this._streamIterator(t,lr(e)));return await r.setup,jn.fromAsyncGenerator(r)}_separateRunnableConfigFromCallOptions(t={}){const e=lr({callbacks:t.callbacks,tags:t.tags,metadata:t.metadata,runName:t.runName,configurable:t.configurable,recursionLimit:t.recursionLimit,maxConcurrency:t.maxConcurrency}),r={...t};return delete r.callbacks,delete r.tags,delete r.metadata,delete r.runName,delete r.configurable,delete r.recursionLimit,delete r.maxConcurrency,[e,r]}async _callWithConfig(t,e,r){const a=lr(r),n=await Ni(a),i=await(n==null?void 0:n.handleChainStart(this.toJSON(),pr(e,"input"),void 0,a==null?void 0:a.runType,void 0,void 0,(a==null?void 0:a.runName)??this.getName()));let l;try{l=await t.call(this,e,a,i)}catch(s){throw await(i==null?void 0:i.handleChainError(s)),s}return await(i==null?void 0:i.handleChainEnd(pr(l,"output"))),l}async _batchWithConfig(t,e,r,a){const n=this._getOptionsList(r??{},e.length),i=await Promise.all(n.map(Ni)),l=await Promise.all(i.map((o,d)=>o==null?void 0:o.handleChainStart(this.toJSON(),pr(e[d],"input"),void 0,n[d].runType,void 0,void 0,n[d].runName??this.getName())));let s;try{s=await t.call(this,e,n,l,a)}catch(o){throw await Promise.all(l.map(d=>d==null?void 0:d.handleChainError(o))),o}return await Promise.all(l.map(o=>o==null?void 0:o.handleChainEnd(pr(s,"output")))),s}async*_transformStreamWithConfig(t,e,r){let a,n=!0,i,l=!0;const s=lr(r),o=await Ni(s);async function*d(){for await(const c of t){if(n)if(a===void 0)a=c;else try{a=el(a,c)}catch{a=void 0,n=!1}yield c}}let u;try{const c=await U7(e.bind(this),d(),async()=>o==null?void 0:o.handleChainStart(this.toJSON(),{input:""},void 0,s==null?void 0:s.runType,void 0,void 0,(s==null?void 0:s.runName)??this.getName()),s);u=c.setup;const p=h=>h.name==="log_stream_tracer",A=u==null?void 0:u.handlers.find(p);let m=c.output;A!==void 0&&u!==void 0&&(m=await A.tapOutputIterable(u.runId,c.output));for await(const h of m)if(yield h,l)if(i===void 0)i=h;else try{i=el(i,h)}catch{i=void 0,l=!1}}catch(c){throw await(u==null?void 0:u.handleChainError(c,void 0,void 0,void 0,{inputs:pr(a,"input")})),c}await(u==null?void 0:u.handleChainEnd(i??{},void 0,void 0,void 0,{inputs:pr(a,"input")}))}pipe(t){return new Bi({first:this,last:Pi(t)})}pick(t){return this.pipe(new y2(t))}assign(t){return this.pipe(new yA(new od({steps:t})))}async*transform(t,e){let r;for await(const a of t)r===void 0?r=a:r=el(r,a);yield*this._streamIterator(r,lr(e))}async*streamLog(t,e,r){const a=new WA({...r,autoClose:!1,_schemaFormat:"original"}),n=lr(e);yie
should be one of ${a}`)}try{const a=r.reduce((n,i)=>(n[i]="foo",n),{});Array.isArray(t)?t.forEach(n=>{if(n.type==="text")qn(n.text,e,a);else if(n.type==="image_url")if(typeof n.image_url=="string")qn(n.image_url,e,a);else{const i=n.image_url.url;qn(i,e,a)}else throw new Error(`Invalid message template received. ${JSON.stringify(n,null,2)}`)}):qn(t,e,a)}catch(a){throw new Error(`Invalid prompt schema: ${a.message}`)}}}}),EA={};iu(EA,{PromptTemplate:()=>La});var La,_d=be({"node_modules/@langchain/core/dist/prompts/prompt.js"(){u1(),cu(),La=class _o extends QB{static lc_name(){return"PromptTemplate"}constructor(e){if(super(e),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.assign(this,e),this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),t0(this.template,this.templateFormat,r)}}_getPromptType(){return"prompt"}async format(e){const r=await this.mergePartialAndUserVariables(e);return qn(this.template,this.templateFormat,r)}static fromExamples(e,r,a,n=`
`,i=""){const l=[i,...e,r].join(n);return new _o({inputVariables:a,template:l})}static fromTemplate(e,{templateFormat:r="f-string",...a}={}){const n=new Set;return DQ(e,r).forEach(i=>{i.type==="variable"&&n.add(i.name)}),new _o({inputVariables:[...n],templateFormat:r,template:e,...a})}async partial(e){const r=this.inputVariables.filter(i=>!(i in e)),a={...this.partialVariables??{},...e},n={...this,inputVariables:r,partialVariables:a};return new _o(n)}serialize(){if(this.outputParser!==void 0)throw new Error("Cannot serialize a prompt template with an output parser");return{_type:this._getPromptType(),input_variables:this.inputVariables,template:this.template,template_format:this.templateFormat}}static async deserialize(e){if(!e.template)throw new Error("Prompt template must have a template");return new _o({inputVariables:e.input_variables,template:e.template,templateFormat:e.template_format})}}}}),MQ=be({"node_modules/@langchain/core/dist/prompts/image.js"(){l1(),mu(),cu()}}),xQ,WB=be({"node_modules/@langchain/core/dist/prompts/chat.js"(){ta(),l1(),Ma(),u1(),mu(),_d(),MQ(),cu(),xQ=class extends vB{constructor(t){super(t)}async format(t){return(await this.formatPromptValue(t)).toString()}async formatPromptValue(t){const e=await this.formatMessages(t);return new AB(e)}}}}),JQ={};iu(JQ,{FewShotChatMessagePromptTemplate:()=>PQ,FewShotPromptTemplate:()=>OQ});var OQ,PQ,zQ=be({"node_modules/@langchain/core/dist/prompts/few_shot.js"(){u1(),cu(),_d(),WB(),OQ=class GA extends QB{constructor(e){if(super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"examples",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleSelector",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"examplePrompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"suffix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"exampleSeparator",{enumerable:!0,configurable:!0,writable:!0,value:`
`}),Object.defineProperty(this,"prefix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.assign(this,e),this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),t0(this.prefix+this.suffix,this.templateFormat,r)}}_getPromptType(){return"few_shot"}static lc_name(){return"FewShotPromptTemplate"}async getExamples(e){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(e);throw new Error("One of 'examples' and 'example_selector' should be provided")}async partial(e){const r=this.inputVariables.filter(i=>!(i in e)),a={...this.partialVariables??{},...e},n={...this,inputVariables:r,partialVariables:a};return new GA(n)}async format(e){const r=await this.mergePartialAndUserVariables(e),a=await this.getExamples(r),n=await Promise.all(a.map(l=>this.examplePrompt.format(l))),i=[this.prefix,...n,this.suffix].join(this.exampleSeparator);return qn(i,this.templateFormat,r)}serialize(){if(this.exampleSelector||!this.examples)throw new Error("Serializing an example selector is not currently supported");if(this.outputParser!==void 0)throw new Error("Serializing an output parser is not currently supported");return{_type:this._getPromptType(),input_variables:this.inputVariables,example_prompt:this.examplePrompt.serialize(),example_separator:this.exampleSeparator,suffix:this.suffix,prefix:this.prefix,template_format:this.templateFormat,examples:this.examples}}static async deserialize(e){const{example_prompt:r}=e;if(!r)throw new Error("Missing example prompt");const a=await La.deserialize(r);let n;if(Array.isArray(e.examples))n=e.examples;else throw new Error("Invalid examples format. Only list or string are supported.");return new GA({inputVariables:e.input_variables,examplePrompt:a,examples:n,exampleSeparator:e.example_separator,prefix:e.prefix,suffix:e.suffix,templateFormat:e.template_format})}},PQ=class jQ extends xQ{_getPromptType(){return"few_shot_chat"}static lc_name(){return"FewShotChatMessagePromptTemplate"}constructor(e){if(super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"examples",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleSelector",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"examplePrompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"suffix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"exampleSeparator",{enumerable:!0,configurable:!0,writable:!0,value:`
`}),Object.defineProperty(this,"prefix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.examples=e.examples,this.examplePrompt=e.examplePrompt,this.exampleSeparator=e.exampleSeparator??`
`,this.exampleSelector=e.exampleSelector,this.prefix=e.prefix??"",this.suffix=e.suffix??"",this.templateFormat=e.templateFormat??"f-string",this.validateTemplate=e.validateTemplate??!0,this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),t0(this.prefix+this.suffix,this.templateFormat,r)}}async getExamples(e){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(e);throw new Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(e){const r=await this.mergePartialAndUserVariables(e);let a=await this.getExamples(r);a=a.map(i=>{const l={};return this.examplePrompt.inputVariables.forEach(s=>{l[s]=i[s]}),l});const n=[];for(const i of a){const l=await this.examplePrompt.formatMessages(i);n.push(...l)}return n}async format(e){const r=await this.mergePartialAndUserVariables(e),a=await this.getExamples(r),i=(await Promise.all(a.map(s=>this.examplePrompt.formatMessages(s)))).flat().map(s=>s.content),l=[this.prefix,...i,this.suffix].join(this.exampleSeparator);return qn(l,this.templateFormat,r)}async partial(e){const r=this.inputVariables.filter(i=>!(i in e)),a={...this.partialVariables??{},...e},n={...this,inputVariables:r,partialVariables:a};return new jQ(n)}}}}),vB,mu=be({"node_modules/@langchain/core/dist/prompts/base.js"(){Ma(),vB=class extends Ot{get lc_attributes(){return{partialVariables:void 0}}constructor(t){super(t),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts",this._getPromptType()]}),Object.defineProperty(this,"inputVariables",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputParser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"partialVariables",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const{inputVariables:e}=t;if(e.includes("stop"))throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,t)}async mergePartialAndUserVariables(t){const e=this.partialVariables??{},r={};for(const[n,i]of Object.entries(e))typeof i=="string"?r[n]=i:r[n]=await i();return{...r,...t}}async invoke(t,e){return this._callWithConfig(r=>this.formatPromptValue(r),t,{...e,runType:"prompt"})}serialize(){throw new Error("Use .toJSON() instead")}static async deserialize(t){switch(t._type){case"prompt":{const{PromptTemplate:e}=await Promise.resolve().then(()=>(_d(),EA));return e.deserialize(t)}case void 0:{const{PromptTemplate:e}=await Promise.resolve().then(()=>(_d(),EA));return e.deserialize({...t,_type:"prompt"})}case"few_shot":{const{FewShotPromptTemplate:e}=await Promise.resolve().then(()=>(zQ(),JQ));return e.deserialize(t)}default:throw new Error(`Invalid prompt type in config: ${t._type}`)}}}}}),x7=tt({"node_modules/node-fetch/node_modules/webidl-conversions/lib/index.js"(t,e){var r={};e.exports=r;function a(l){return l<0?-1:1}function n(l){return l%1===.5&&!(l&1)?Math.floor(l):Math.round(l)}function i(l,s){s.unsigned||--l;const o=s.unsigned?0:-Math.pow(2,l),d=Math.pow(2,l)-1,u=s.moduloBitLength?Math.pow(2,s.moduloBitLength):Math.pow(2,l),c=s.moduloBitLength?Math.pow(2,s.moduloBitLength-1):Math.pow(2,l-1);return function(p,A){A||(A={});let m=+p;if(A.enforceRange){if(!Number.isFinite(m))throw new TypeError("Argument is not a finite number");if(m=a(m)*Math.floor(Math.abs(m)),m<o||m>d)throw new TypeError("Argument is not in byte range");return m}if(!isNaN(m)&&A.clamp)return m=n(m),m<o&&(m=o),m>d&&(m=d),m;if(!Number.isFinite(m)||m===0)return 0;if(m=a(m)*Math.floor(Math.abs(m)),m=
`).filter(Boolean).reduce((a,n)=>{const[i,l,...s]=n.split(" "),o=Number.parseInt(l,10);return s.forEach((d,u)=>a[d]=o+u),a},{});for(const[a,n]of Object.entries(r)){const i=kX.default.toByteArray(a);this.rankMap.set(i.join(","),n),this.textMap.set(n,i)}this.specialTokens={...t.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((a,[n,i])=>(a[i]=this.textEncoder.encode(n),a),{})}encode(t,e=[],r="all"){const a=new RegExp(this.patStr,"ug"),n=JA.specialTokenRegex(Object.keys(this.specialTokens)),i=[],l=new Set(e==="all"?Object.keys(this.specialTokens):e),s=new Set(r==="all"?Object.keys(this.specialTokens).filter(d=>!l.has(d)):r);if(s.size>0){const d=JA.specialTokenRegex([...s]),u=t.match(d);if(u!=null)throw new Error(`The text contains a special token that is not allowed: ${u[0]}`)}let o=0;for(;;){let d=null,u=o;for(;n.lastIndex=u,d=n.exec(t),!(d==null||l.has(d[0]));)u=d.index+1;const c=(d==null?void 0:d.index)??t.length;for(const A of t.substring(o,c).matchAll(a)){const m=this.textEncoder.encode(A[0]),h=this.rankMap.get(m.join(","));if(h!=null){i.push(h);continue}i.push(...MX(m,this.rankMap))}if(d==null)break;let p=this.specialTokens[d[0]];i.push(p),o=d.index+d[0].length}return i}decode(t){const e=[];let r=0;for(let i=0;i<t.length;++i){const l=t[i],s=this.textMap.get(l)??this.inverseSpecialTokens[l];s!=null&&(e.push(s),r+=s.length)}const a=new Uint8Array(r);let n=0;for(const i of e)a.set(i,n),n+=i.length;return this.textDecoder.decode(a)}},IW=JA;IX(IW,"specialTokenRegex",t=>new RegExp(t.map(e=>xX(e)).join("|"),"g"));function JX(t){switch(t){case"gpt2":return"gpt2";case"code-cushman-001":case"code-cushman-002":case"code-davinci-001":case"code-davinci-002":case"cushman-codex":case"davinci-codex":case"davinci-002":case"text-davinci-002":case"text-davinci-003":return"p50k_base";case"code-davinci-edit-001":case"text-davinci-edit-001":return"p50k_edit";case"ada":case"babbage":case"babbage-002":case"code-search-ada-code-001":case"code-search-babbage-code-001":case"curie":case"davinci":case"text-ada-001":case"text-babbage-001":case"text-curie-001":case"text-davinci-001":case"text-search-ada-doc-001":case"text-search-babbage-doc-001":case"text-search-curie-doc-001":case"text-search-davinci-doc-001":case"text-similarity-ada-001":case"text-similarity-babbage-001":case"text-similarity-curie-001":case"text-similarity-davinci-001":return"r50k_base";case"gpt-3.5-turbo-instruct-0914":case"gpt-3.5-turbo-instruct":case"gpt-3.5-turbo-16k-0613":case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo":case"gpt-4-32k-0613":case"gpt-4-32k-0314":case"gpt-4-32k":case"gpt-4-0613":case"gpt-4-0314":case"gpt-4":case"gpt-3.5-turbo-1106":case"gpt-35-turbo":case"gpt-4-1106-preview":case"gpt-4-vision-preview":case"gpt-3.5-turbo-0125":case"gpt-4-turbo-preview":case"gpt-4-0125-preview":case"text-embedding-ada-002":return"cl100k_base";default:throw new Error("Unknown model")}}s1();var Sp={},OX=new su({});async function PX(t){return t in Sp||(Sp[t]=OX.fetch(`https://tiktoken.pages.dev/js/${t}.json`).then(e=>e.json()).then(e=>new IW(e)).catch(e=>{throw delete Sp[t],e})),await Sp[t]}async function zX(t){return PX(JX(t))}Ma();var jX=t=>t.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":t.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":t.startsWith("gpt-4-32k")?"gpt-4-32k":t.startsWith("gpt-4-")?"gpt-4":t,qX=()=>!1,$X=class extends Ot{get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(t){super(t),Object.defineProperty(this,"verbose",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"callbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.verbose=t.verbose??qX(),this.callbacks=t.callbacks,this.tags=t.tags??[],this.metadata=t.metadata??{}}},eH=class extends $X{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"
`);s=u.pop()||"";for(const c of u)try{yield JSON.parse(c)}catch{console.warn(`Received a non-JSON parseable chunk: ${c}`)}}}async function*rH(t,e,r){yield*MW(`${t}/api/generate`,e,r)}async function*aH(t,e,r){yield*MW(`${t}/api/chat`,e,r)}var nH=class extends tH{static lc_name(){return"ChatOllama"}constructor(t){var e;super(t),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"llama2"}),Object.defineProperty(this,"baseUrl",{enumerable:!0,configurable:!0,writable:!0,value:"http://localhost:11434"}),Object.defineProperty(this,"keepAlive",{enumerable:!0,configurable:!0,writable:!0,value:"5m"}),Object.defineProperty(this,"embeddingOnly",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"f16KV",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"frequencyPenalty",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logitsAll",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lowVram",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mainGpu",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mirostat",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mirostatEta",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mirostatTau",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"numBatch",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"numCtx",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"numGpu",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"numGqa",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"numKeep",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"numPredict",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"numThread",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"penalizeNewline",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"presencePenalty",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"repeatLastN",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"repeatPenalty",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ropeFrequencyBase",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ropeFrequencyScale",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"temperature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stop",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tfsZ",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"topK",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"topP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"typicalP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"useMLock",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"useMMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"vocabOnly",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"format",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.model=t.model??this.model,this.baseUrl=(e=t.baseUrl)!=null&&e.endsWith("/")?t.baseUrl.slice(0,-1):t.baseUrl??this.baseUrl,this.keepAlive=t.keepAlive??this.k
${i.text}`;else if(i.type==="image_url"&&typeof i.image_url=="string"){const l=i.image_url.split(",");n.push(l[1]??l[0])}else throw new Error('Unsupported message content type. Must either have type "text" or type "image_url" with a string "image_url" field.');return{role:r,content:a,images:n}})}_formatMessagesAsPrompt(t){return t.map(r=>{let a;return r._getType()==="human"?a=`[INST] ${r.content} [/INST]`:r._getType()==="ai"?a=r.content:r._getType()==="system"?a=`<<SYS>> ${r.content} <</SYS>>`:kd.isInstance(r)?a=`
${r.role[0].toUpperCase()}${r.role.slice(1)}: ${r.content}`:(console.warn(`Unsupported message type passed to Ollama: "${r._getType()}"`),a=""),a}).join(`
`)}async _call(t,e,r){const a=[];for await(const n of this._streamResponseChunks(t,e,r))a.push(n.message.content);return a.join("")}};Ma();zs();pu();Ma();zs();var OA=class extends Ot{static lc_name(){return"RunnablePassthrough"}constructor(t){super(t),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),t&&(this.func=t.func)}async invoke(t,e){const r=lr(e);return this.func&&await this.func(t,r),this._callWithConfig(a=>Promise.resolve(a),t,r)}async*transform(t,e){const r=lr(e);let a,n=!0;for await(const i of this._transformStreamWithConfig(t,l=>l,r))if(yield i,n)if(a===void 0)a=i;else try{a=el(a,i)}catch{a=void 0,n=!1}this.func&&a!==void 0&&await this.func(a,r)}static assign(t){return new yA(new od({steps:t}))}};Ma();zs();Ma();zs();pu();ta();Ma();var IB=class extends Ot{parseResultWithPrompt(t,e,r){return this.parseResult(t,r)}async invoke(t,e){return typeof t=="string"?this._callWithConfig(async r=>this.parseResult([{text:r}]),t,{...e,runType:"parser"}):this._callWithConfig(async r=>this.parseResult([{message:r,text:typeof r.content=="string"?r.content:JSON.stringify(r.content)}]),t,{...e,runType:"parser"})}},iH=class extends IB{parseResult(t,e){return this.parse(t[0].text,e)}async parseWithPrompt(t,e,r){return this.parse(t,r)}_type(){throw new Error("_type not implemented")}};ta();function PA(t,e){const r=typeof t;if(r!==typeof e)return!1;if(Array.isArray(t)){if(!Array.isArray(e))return!1;const a=t.length;if(a!==e.length)return!1;for(let n=0;n<a;n++)if(!PA(t[n],e[n]))return!1;return!0}if(r==="object"){if(!t||!e)return t===e;const a=Object.keys(t),n=Object.keys(e);if(a.length!==n.length)return!1;for(const l of a)if(!PA(t[l],e[l]))return!1;return!0}return t===e}var xW=class extends iH{async*_transform(t){for await(const e of t)typeof e=="string"?yield this.parseResult([{text:e}]):yield this.parseResult([{message:e,text:typeof e.content=="string"?e.content:JSON.stringify(e.content)}])}async*transform(t,e){yield*this._transformStreamWithConfig(t,this._transform.bind(this),{...e,runType:"parser"})}},lH=class extends xW{constructor(t){super(t),Object.defineProperty(this,"diff",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.diff=(t==null?void 0:t.diff)??this.diff}async*_transform(t){let e,r;for await(const a of t){if(typeof a!="string"&&typeof a.content!="string")throw new Error("Cannot handle non-string output.");let n;if($Z(a)){if(typeof a.content!="string")throw new Error("Cannot handle non-string message output.");n=new sl({message:a,text:a.content})}else if(mB(a)){if(typeof a.content!="string")throw new Error("Cannot handle non-string message output.");n=new sl({message:a.toChunk(),text:a.content})}else n=new TW({text:a});r===void 0?r=n:r=r.concat(n);const i=await this.parsePartialResult([r]);i!=null&&!PA(i,e)&&(this.diff?yield this._diff(e,i):yield i,e=i)}}},g1=class extends xW{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers","string"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0})}static lc_name(){return"StrOutputParser"}parse(t){return Promise.resolve(t)}getFormatInstructions(){return""}};YQ();var sH=class extends lH{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0})}static lc_name(){return"JsonOutputParser"}_diff(t,e){if(e)return t?T7(t,e):[{op:"replace",path:"",value:e}]}async parsePartialResult(t){return Ab(t[0].text)}async parse(t){return Ab(t,JSON.parse)}getFormatInstructions(){return""}};function Ab(t,e=oH){t=t.trim();const r=/```(json)?(.*)```/s.exec(t);return e(r?r[2]:t)}f
`&&!n?i="\\n":i==="\\"?n=!n:n=!1;else if(i==='"')a=!0,n=!1;else if(i==="{")r.push("}");else if(i==="[")r.push("]");else if(i==="}"||i==="]")if(r&&r[r.length-1]===i)r.pop();else return null;e+=i}a&&(e+='"');for(let i=r.length-1;i>=0;i-=1)e+=r[i];try{return JSON.parse(e)}catch{return null}}mu();WB();zQ();mu();WB();_d();u1();cu();MQ();var ss="4.28.4",hb=!1,cd=void 0,JW=void 0,OW=void 0,zA=void 0,PW=void 0,zW=void 0,jW=void 0,qW=void 0,$W=void 0;function dH(t,e={auto:!1}){if(hb)throw new Error(`you must \`import 'openai/shims/${t.kind}'\` before importing anything else from openai`);if(cd)throw new Error(`can't \`import 'openai/shims/${t.kind}'\` after \`import 'openai/shims/${cd}'\``);hb=e.auto,cd=t.kind,JW=t.fetch,t.Request,t.Response,t.Headers,OW=t.FormData,t.Blob,zA=t.File,PW=t.ReadableStream,zW=t.getMultipartRequestOptions,jW=t.getDefaultAgent,qW=t.fileFromPath,$W=t.isFsReadStream}var e9=Gr(q7(),1),uH=qr.Readable,un=Symbol("buffer"),Om=Symbol("type"),DB=class jA{constructor(){this[Om]="";const e=arguments[0],r=arguments[1],a=[];let n=0;if(e){const l=e,s=Number(l.length);for(let o=0;o<s;o++){const d=l[o];let u;d instanceof Buffer?u=d:ArrayBuffer.isView(d)?u=Buffer.from(d.buffer,d.byteOffset,d.byteLength):d instanceof ArrayBuffer?u=Buffer.from(d):d instanceof jA?u=d[un]:u=Buffer.from(typeof d=="string"?d:String(d)),n+=u.length,a.push(u)}}this[un]=Buffer.concat(a);let i=r&&r.type!==void 0&&String(r.type).toLowerCase();i&&!/[^\u0020-\u007E]/.test(i)&&(this[Om]=i)}get size(){return this[un].length}get type(){return this[Om]}text(){return Promise.resolve(this[un].toString())}arrayBuffer(){const e=this[un],r=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);return Promise.resolve(r)}stream(){const e=new uH;return e._read=function(){},e.push(this[un]),e.push(null),e}toString(){return"[object Blob]"}slice(){const e=this.size,r=arguments[0],a=arguments[1];let n,i;r===void 0?n=0:r<0?n=Math.max(e+r,0):n=Math.min(r,e),a===void 0?i=e:a<0?i=Math.max(e+a,0):i=Math.min(a,e);const l=Math.max(i-n,0),o=this[un].slice(n,n+l),d=new jA([],{type:arguments[2]});return d[un]=o,d}};Object.defineProperties(DB.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});Object.defineProperty(DB.prototype,Symbol.toStringTag,{value:"Blob",writable:!1,enumerable:!1,configurable:!0});function gr(t,e,r){Error.call(this,t),this.message=t,this.type=e,r&&(this.code=this.errno=r.code),Error.captureStackTrace(this,this.constructor)}gr.prototype=Object.create(Error.prototype);gr.prototype.constructor=gr;gr.prototype.name="FetchError";var qA;try{qA=hi("encoding").convert}catch{}var Cn=Symbol("Body internals"),Bb=qr.PassThrough;function ar(t){var e=this,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},a=r.size;let n=a===void 0?0:a;var i=r.timeout;let l=i===void 0?0:i;t==null?t=null:t9(t)?t=Buffer.from(t.toString()):gu(t)||Buffer.isBuffer(t)||(Object.prototype.toString.call(t)==="[object ArrayBuffer]"?t=Buffer.from(t):ArrayBuffer.isView(t)?t=Buffer.from(t.buffer,t.byteOffset,t.byteLength):t instanceof qr||(t=Buffer.from(String(t)))),this[Cn]={body:t,disturbed:!1,error:null},this.size=n,this.timeout=l,t instanceof qr&&t.on("error",function(s){const o=s.name==="AbortError"?s:new gr(`Invalid response body while trying to fetch ${e.url}: ${s.message}`,"system",s);e[Cn].error=o})}ar.prototype={get body(){return this[Cn].body},get bodyUsed(){return this[Cn].disturbed},arrayBuffer(){return $l.call(this).then(function(t){return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)})},blob(){let t=this.headers&&this.headers.get("content-type")||"";return $l.call(this).then(function(e){return Object.assign(new DB([],{type:t.toLowerCase()}),{[un]:e})})},json(){var t=this;return $l.call(this).then(function(e){try{return JSON.parse(e.toString())}catch(r){return ar.Promise.reject(new gr(`invalid json response body at ${t.url} reason: ${r.message}`,"invalid-json"))}})},text(){return $l.call(this).then(function(t){return t.toString()})},buffer(){return $l.call(this)},textConverted(){var t=this;return $l.call(this).then(function(e){return pH(e,t
`||e===`
`&&a[r-1]!=="\r"?`\r
`:e),fb=HH,VH=t=>String(t).replace(/\r/g,"%0D").replace(/\n/g,"%0A").replace(/"/g,"%22"),Qb=VH,YH=t=>typeof t=="function",rl=YH,es=t=>!!(t&&typeof t=="object"&&rl(t.constructor)&&t[Symbol.toStringTag]==="File"&&rl(t.stream)&&t.name!=null&&t.size!=null&&t.lastModified!=null),NH=t=>!!(t&&rl(t.constructor)&&t[Symbol.toStringTag]==="FormData"&&rl(t.append)&&rl(t.getAll)&&rl(t.entries)&&rl(t[Symbol.iterator])),vo=function(t,e,r,a,n){if(a==="m")throw new TypeError("Private method is not writable");if(a==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return a==="a"?n.call(t,r):n?n.value=r:e.set(t,r),r},Kt=function(t,e,r,a){if(r==="a"&&!a)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!a:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?a:r==="a"?a.call(t):a?a.value:e.get(t)},Hp,Ln,Fo,Vp,yo,Di,Ro,Eo,Yp,$m,LH={enableAdditionalHeaders:!1},TH=class{constructor(t,e,r){if(Hp.add(this),Ln.set(this,`\r
`),Fo.set(this,void 0),Vp.set(this,void 0),yo.set(this,"-".repeat(2)),Di.set(this,new TextEncoder),Ro.set(this,void 0),Eo.set(this,void 0),Yp.set(this,void 0),!NH(t))throw new TypeError("Expected first argument to be a FormData instance.");let a;if(Kb(e)?r=e:a=e,a||(a=SH()),typeof a!="string")throw new TypeError("Expected boundary argument to be a string.");if(r&&!Kb(r))throw new TypeError("Expected options argument to be an object.");vo(this,Eo,t,"f"),vo(this,Yp,{...LH,...r},"f"),vo(this,Fo,Kt(this,Di,"f").encode(Kt(this,Ln,"f")),"f"),vo(this,Vp,Kt(this,Fo,"f").byteLength,"f"),this.boundary=`form-data-boundary-${a}`,this.contentType=`multipart/form-data; boundary=${this.boundary}`,vo(this,Ro,Kt(this,Di,"f").encode(`${Kt(this,yo,"f")}${this.boundary}${Kt(this,yo,"f")}${Kt(this,Ln,"f").repeat(2)}`),"f"),this.contentLength=String(this.getContentLength()),this.headers=Object.freeze({"Content-Type":this.contentType,"Content-Length":this.contentLength}),Object.defineProperties(this,{boundary:{writable:!1,configurable:!1},contentType:{writable:!1,configurable:!1},contentLength:{writable:!1,configurable:!1},headers:{writable:!1,configurable:!1}})}getContentLength(){let t=0;for(const[e,r]of Kt(this,Eo,"f")){const a=es(r)?r:Kt(this,Di,"f").encode(fb(r));t+=Kt(this,Hp,"m",$m).call(this,e,a).byteLength,t+=es(a)?a.size:a.byteLength,t+=Kt(this,Vp,"f")}return t+Kt(this,Ro,"f").byteLength}*values(){for(const[t,e]of Kt(this,Eo,"f").entries()){const r=es(e)?e:Kt(this,Di,"f").encode(fb(e));yield Kt(this,Hp,"m",$m).call(this,t,r),yield r,yield Kt(this,Fo,"f")}yield Kt(this,Ro,"f")}async*encode(){for(const t of this.values())es(t)?yield*t.stream():yield t}[(Ln=new WeakMap,Fo=new WeakMap,Vp=new WeakMap,yo=new WeakMap,Di=new WeakMap,Ro=new WeakMap,Eo=new WeakMap,Yp=new WeakMap,Hp=new WeakSet,$m=function(e,r){let a="";return a+=`${Kt(this,yo,"f")}${this.boundary}${Kt(this,Ln,"f")}`,a+=`Content-Disposition: form-data; name="${Qb(e)}"`,es(r)&&(a+=`; filename="${Qb(r.name)}"${Kt(this,Ln,"f")}`,a+=`Content-Type: ${r.type||"application/octet-stream"}`),Kt(this,Yp,"f").enableAdditionalHeaders===!0&&(a+=`${Kt(this,Ln,"f")}Content-Length: ${es(r)?r.size:r.byteLength}`),Kt(this,Di,"f").encode(`${a}${Kt(this,Ln,"f").repeat(2)}`)},Symbol.iterator)](){return this.values()}[Symbol.asyncIterator](){return this.encode()}},kH=class{constructor(t){this.body=t}get[Symbol.toStringTag](){return"MultipartBody"}},UH=Gr(yX(),1),Wb=!1;async function _H(t,...e){const{fileFromPath:r}=await Promise.resolve().then(()=>(XX(),VW));return Wb||(console.warn(`fileFromPath is deprecated; use fs.createReadStream(${JSON.stringify(t)}) instead`),Wb=!0),await r(t,...e)}var IH=new d9.default({keepAlive:!0,timeout:5*60*1e3}),DH=new d9.default.HttpsAgent({keepAlive:!0,timeout:5*60*1e3});async function MH(t,e){const r=new TH(t),a=qr.Readable.from(r),n=new kH(a),i={...e.headers,...r.headers,"Content-Length":r.contentLength};return{...e,body:n,headers:i}}function xH(){return typeof AbortController>"u"&&(globalThis.AbortController=EH.AbortController),{kind:"node",fetch:vH,Request:Ls,Response:Xa,Headers:Ua,FormData:RH,Blob:Ys,File:Ns,ReadableStream:UH.ReadableStream,getMultipartRequestOptions:MH,getDefaultAgent:t=>t.startsWith("https")?DH:IH,fileFromPath:_H,isFsReadStream:t=>t instanceof gd.ReadStream}}cd||dH(xH(),{auto:!0});var u9={};iu(u9,{APIConnectionError:()=>Au,APIConnectionTimeoutError:()=>A1,APIError:()=>Nr,APIUserAbortError:()=>Ci,AuthenticationError:()=>JB,BadRequestError:()=>xB,ConflictError:()=>zB,InternalServerError:()=>$B,NotFoundError:()=>PB,OpenAIError:()=>it,PermissionDeniedError:()=>OB,RateLimitError:()=>qB,UnprocessableEntityError:()=>jB});var it=class extends Error{},Nr=class rh extends it{constructor(e,r,a,n){super(`${rh.makeMessage(e,r,a)}`),this.status=e,this.headers=n;const i=r;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,r,a){const n=r!=null&&r.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):a;return e&&n?`${e} ${n}`:e?`${e} status cod
`);n.enqueue(s)}catch(i){n.error(i)}},async cancel(){var n;await((n=r.return)==null?void 0:n.call(r))}})}},JH=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(t){if(t.endsWith("\r")&&(t=t.substring(0,t.length-1)),!t){if(!this.event&&!this.data.length)return null;const n={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],n}if(this.chunks.push(t),t.startsWith(":"))return null;let[e,r,a]=OH(t,":");return a.startsWith(" ")&&(a=a.substring(1)),e==="event"?this.event=a:e==="data"&&this.data.push(a),null}},u0=class nh{constructor(){this.buffer=[],this.trailingCR=!1}decode(e){let r=this.decodeText(e);if(this.trailingCR&&(r="\r"+r,this.trailingCR=!1),r.endsWith("\r")&&(this.trailingCR=!0,r=r.slice(0,-1)),!r)return[];const a=nh.NEWLINE_CHARS.has(r[r.length-1]||"");let n=r.split(nh.NEWLINE_REGEXP);return n.length===1&&!a?(this.buffer.push(n[0]),[]):(this.buffer.length>0&&(n=[this.buffer.join("")+n[0],...n.slice(1)],this.buffer=[]),a||(this.buffer=[n.pop()||""]),n)}decodeText(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof Buffer<"u"){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new it(`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<"u"){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new it(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new it("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];const e=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,e}};u0.NEWLINE_CHARS=new Set([`
`,"\r","\v","\f","","","","…","\u2028","\u2029"]);u0.NEWLINE_REGEXP=/\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g;function OH(t,e){const r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}function vb(t){if(t[Symbol.asyncIterator])return t;const e=t.getReader();return{async next(){try{const r=await e.read();return r!=null&&r.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}},async return(){const r=e.cancel();return e.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var p9=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",PH=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&c9(t),c9=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",zH=t=>PH(t)||p9(t)||$W(t);async function m9(t,e,r={}){var n;if(t=await t,p9(t)){const i=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file"),new zA([i],e,r)}const a=await jH(t);if(e||(e=$H(t)??"unknown_file"),!r.type){const i=(n=a[0])==null?void 0:n.type;typeof i=="string"&&(r={...r,type:i})}return new zA(a,e,r)}async function jH(t){var r;let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(c9(t))e.push(await t.arrayBuffer());else if(eV(t))for await(const a of t)e.push(a);else throw new Error(`Unexpected data type: ${typeof t}; constructor: ${(r=t==null?void 0:t.constructor)==null?void 0:r.name}; props: ${qH(t)}`);return e}function qH(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function $H(t){var e;return eg(t.name)||eg(t.filename)||((e=eg(t.path))==null?void 0:e.split(/[\\/]/).pop())}var eg=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},eV=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",Fb=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody",Md=async t=>{const e=await tV(t.body);return zW(e,t)},tV=async t=>{const e=new OW;return await Promise.all(Object.entries(t||{}).map(([r,a])=>ih(e,r,a))),e},ih=async(t,e,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")t.append(e,String(r));else if(zH(r)){const a=await m9(r);t.append(e,a)}else if(Array.isArray(r))await Promise.all(r.map(a=>ih(t,e+"[]",a)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([a,n])=>ih(t,`${e}[${a}]`,n)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}},rV=function(t,e,r,a,n){if(a==="m")throw new TypeError("Private method is not writable");if(a==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return a==="a"?n.call(t,r):n?n.value=r:e.set(t,r),r},aV=function(t,e,r,a){if(r==="a"&&!a)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!a:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?a:r==="a"?a.call(t):a?a.value:e.get(t)},Np;async function g9(t){const{response:e}=t;if(t.options.stream)return vs("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):ah.fromSSEResponse(e,t.controller);if(e.status===204)return null;if(t.options.__binaryResponse)return e;const r=e.headers.get("content-type");if((r==null?void 0:r.includes("application/json"))||(r==null?void 0:r.includes("application/vnd.api+json"))){const i=await e.json();return vs("response",e.status,e.url,e.headers,i),i}const n=await e.text();return vs("response",e.status,e.url,e.headers,n),n}
${Tp(t)}`);if(K==null)throw new it(`missing choices[${d}].tool_calls[${b}].type
${Tp(t)}`);if(L==null)throw new it(`missing choices[${d}].tool_calls[${b}].function.name
${Tp(t)}`);if(v==null)throw new it(`missing choices[${d}].tool_calls[${b}].function.arguments
${Tp(t)}`);return{...R,id:W,type:K,function:{...y,name:L,arguments:v}}})}}:{...c,message:{...h,content:p,role:C},finish_reason:o,index:d,logprobs:u}}),created:a,model:n,object:"chat.completion",...i?{system_fingerprint:i}:{}}}function Tp(t){return JSON.stringify(t)}var Vb=class Ac extends v9{static fromReadableStream(e){const r=new Ac;return r._run(()=>r._fromReadableStream(e)),r}static runFunctions(e,r,a){const n=new Ac,i={...a,headers:{...a==null?void 0:a.headers,"X-Stainless-Helper-Method":"runFunctions"}};return n._run(()=>n._runFunctions(e,r,i)),n}static runTools(e,r,a){const n=new Ac,i={...a,headers:{...a==null?void 0:a.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,r,i)),n}},F9=class extends yt{runFunctions(t,e){return t.stream?Vb.runFunctions(this._client.chat.completions,t,e):Xb.runFunctions(this._client.chat.completions,t,e)}runTools(t,e){return t.stream?Vb.runTools(this._client.chat.completions,t,e):Xb.runTools(this._client.chat.completions,t,e)}stream(t,e){return v9.createChatCompletion(this._client.chat.completions,t,e)}},b0=class extends yt{constructor(){super(...arguments),this.completions=new F9(this._client)}};(function(t){t.Completions=F9})(b0||(b0={}));var K0=class extends yt{retrieve(t,e,r,a){return this._client.get(`/threads/${t}/messages/${e}/files/${r}`,{...a,headers:{"OpenAI-Beta":"assistants=v1",...a==null?void 0:a.headers}})}list(t,e,r={},a){return _a(r)?this.list(t,e,{},r):this._client.getAPIList(`/threads/${t}/messages/${e}/files`,aC,{query:r,...a,headers:{"OpenAI-Beta":"assistants=v1",...a==null?void 0:a.headers}})}},aC=class extends vn{};(function(t){t.MessageFilesPage=aC})(K0||(K0={}));var f0=class extends yt{constructor(){super(...arguments),this.files=new K0(this._client)}create(t,e,r){return this._client.post(`/threads/${t}/messages`,{body:e,...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}retrieve(t,e,r){return this._client.get(`/threads/${t}/messages/${e}`,{...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}update(t,e,r,a){return this._client.post(`/threads/${t}/messages/${e}`,{body:r,...a,headers:{"OpenAI-Beta":"assistants=v1",...a==null?void 0:a.headers}})}list(t,e={},r){return _a(e)?this.list(t,{},e):this._client.getAPIList(`/threads/${t}/messages`,nC,{query:e,...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}},nC=class extends vn{};(function(t){t.ThreadMessagesPage=nC,t.Files=K0,t.MessageFilesPage=aC})(f0||(f0={}));var Q0=class extends yt{retrieve(t,e,r,a){return this._client.get(`/threads/${t}/runs/${e}/steps/${r}`,{...a,headers:{"OpenAI-Beta":"assistants=v1",...a==null?void 0:a.headers}})}list(t,e,r={},a){return _a(r)?this.list(t,e,{},r):this._client.getAPIList(`/threads/${t}/runs/${e}/steps`,iC,{query:r,...a,headers:{"OpenAI-Beta":"assistants=v1",...a==null?void 0:a.headers}})}},iC=class extends vn{};(function(t){t.RunStepsPage=iC})(Q0||(Q0={}));var W0=class extends yt{constructor(){super(...arguments),this.steps=new Q0(this._client)}create(t,e,r){return this._client.post(`/threads/${t}/runs`,{body:e,...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}retrieve(t,e,r){return this._client.get(`/threads/${t}/runs/${e}`,{...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}update(t,e,r,a){return this._client.post(`/threads/${t}/runs/${e}`,{body:r,...a,headers:{"OpenAI-Beta":"assistants=v1",...a==null?void 0:a.headers}})}list(t,e={},r){return _a(e)?this.list(t,{},e):this._client.getAPIList(`/threads/${t}/runs`,lC,{query:e,...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}cancel(t,e,r){return this._client.post(`/threads/${t}/runs/${e}/cancel`,{...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}submitToolOutputs(t,e,r,a){return this._client.post(`/threads/${t}/runs/${e}/submit_tool_outputs`,{body:r,...a,headers:{"OpenAI-Beta":"assistants=v1",...a==null?void 0:a.headers}})}},lC=class extends vn{};(function(t){t.RunsPage=lC,t.Steps=Q0,t.RunStepsPage=iC})(W0||(W0={}));var v0=class extends
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:i.baseURL,timeout:i.timeout??6e5,httpAgent:i.httpAgent,maxRetries:i.maxRetries,fetch:i.fetch}),this.completions=new y0(this),this.chat=new c0(this),this.embeddings=new R0(this),this.files=new E0(this),this.images=new Z0(this),this.audio=new h0(this),this.moderations=new H0(this),this.models=new X0(this),this.fineTuning=new S0(this),this.beta=new F0(this),this._options=i,this.apiKey=r,this.organization=a}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}};y9=qt;qt.OpenAI=y9;qt.OpenAIError=it;qt.APIError=Nr;qt.APIConnectionError=Au;qt.APIConnectionTimeoutError=A1;qt.APIUserAbortError=Ci;qt.NotFoundError=PB;qt.ConflictError=zB;qt.RateLimitError=qB;qt.BadRequestError=xB;qt.AuthenticationError=JB;qt.InternalServerError=$B;qt.PermissionDeniedError=OB;qt.UnprocessableEntityError=jB;var{OpenAIError:GD,APIError:SD,APIConnectionError:ZD,APIConnectionTimeoutError:BV,APIUserAbortError:CV,NotFoundError:XD,ConflictError:HD,RateLimitError:VD,BadRequestError:YD,AuthenticationError:ND,InternalServerError:LD,PermissionDeniedError:TD,UnprocessableEntityError:kD}=u9;(function(t){t.toFile=m9,t.fileFromPath=qW,t.Page=eC,t.CursorPage=vn,t.Completions=y0,t.Chat=c0,t.Embeddings=R0,t.Files=E0,t.FileObjectsPage=sC,t.Images=Z0,t.Audio=h0,t.Moderations=H0,t.Models=X0,t.ModelsPage=uC,t.FineTuning=S0,t.Beta=F0})(qt||(qt={}));d1();function R9(t,e,r,a){a!=null&&a.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function gt(t,e,r,a,n){t[e]=r,R9(t,e,a,n)}var Yb={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"string",mapStrategy:"entries",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",emailStrategy:"format:email"},wV=t=>typeof t=="string"?{...Yb,name:t}:{...Yb,...t},xd;(function(t){t.assertEqual=n=>n;function e(n){}t.assertIs=e;function r(n){throw new Error}t.assertNever=r,t.arrayToEnum=n=>{const i={};for(const l of n)i[l]=l;return i},t.getValidEnumValues=n=>{const i=t.objectKeys(n).filter(s=>typeof n[n[s]]!="number"),l={};for(const s of i)l[s]=n[s];return t.objectValues(l)},t.objectValues=n=>t.objectKeys(n).map(function(i){return n[i]}),t.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{const i=[];for(const l in n)Object.prototype.hasOwnProperty.call(n,l)&&i.push(l);return i},t.find=(n,i)=>{for(const l of n)if(i(l))return l},t.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&isFinite(n)&&Math.floor(n)===n;function a(n,i=" | "){return n.map(l=>typeof l=="string"?`'${l}'`:l).join(i)}t.joinValues=a,t.jsonStringifyReplacer=(n,i)=>typeof i=="bigint"?i.toString():i})(xd||(xd={}));var Nb;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Nb||(Nb={}));xd.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);xd.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);var Lb=class extends Error{constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const e=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,e):this.__proto__=e,this.name="ZodError",this.issues=t}get errors(){return this.issues}format(t){const e=t||function(n){return n.message},r={_errors:[]},a=n=>{for(const i of n.issues)if(i.code==="invalid_union")i.unionErrors.map(a);else if(i.code==="invalid_return_type")a(i.returnTypeError);else if(i.code==="invalid_arguments")a(i.argumentsError);else if(i.path.lengt
`)}function H9(t,e){var a;const r=[];for(const[n,i]of Object.entries(t.properties??{}))i.description&&e<2&&r.push(`// ${i.description}`),(a=t.required)!=null&&a.includes(n)?r.push(`${n}: ${Y0(i,e)},`):r.push(`${n}?: ${Y0(i,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
`)}function Y0(t,e){if(iY(t))return t.anyOf.map(r=>Y0(r,e)).join(" | ");switch(t.type){case"string":return t.enum?t.enum.map(r=>`"${r}"`).join(" | "):"string";case"number":return t.enum?t.enum.map(r=>`${r}`).join(" | "):"number";case"integer":return t.enum?t.enum.map(r=>`${r}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",H9(t,e+2),"}"].join(`
`);case"array":return t.items?`${Y0(t.items,e)}[]`:"any[]";default:return""}}function sY(t){return t.role!=="system"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function"&&t.role!=="tool"&&console.warn(`Unknown message role: ${t.role}`),t.role}function V9(t){const e=t._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":{if(!kd.isInstance(t))throw new Error("Invalid generic chat message");return sY(t)}default:throw new Error(`Unknown message type: ${e}`)}}function oY(t){switch(t.role){case"assistant":return new i1(t.content||"",{function_call:t.function_call,tool_calls:t.tool_calls});default:return new kd(t.content||"",t.role??"unknown")}}function dY(t,e){const r=t.role??e,a=t.content??"";let n;return t.function_call?n={function_call:t.function_call}:t.tool_calls?n={tool_calls:t.tool_calls}:n={},r==="user"?new nA({content:a}):r==="assistant"?new ti({content:a,additional_kwargs:n}):r==="system"?new iA({content:a}):r==="function"?new lA({content:a,additional_kwargs:n,name:t.name}):r==="tool"?new AQ({content:a,additional_kwargs:n,tool_call_id:t.tool_call_id}):new sA({content:a,role:r})}function _b(t){return t.map(e=>({role:V9(e),content:e.content,name:e.name,function_call:e.additional_kwargs.function_call,tool_calls:e.additional_kwargs.tool_calls,tool_call_id:e.tool_call_id}))}var uY=class extends DW{static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed"]}get lc_secrets(){return{openAIApiKey:"OPENAI_API_KEY",azureOpenAIApiKey:"AZURE_OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{modelName:"model",openAIApiKey:"openai_api_key",azureOpenAIApiVersion:"azure_openai_api_version",azureOpenAIApiKey:"azure_openai_api_key",azureOpenAIApiInstanceName:"azure_openai_api_instance_name",azureOpenAIApiDeploymentName:"azure_openai_api_deployment_name"}}constructor(t,e){var r,a,n,i,l,s,o,d;if(super(t??{}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"temperature",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"topP",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"frequencyPenalty",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"presencePenalty",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"n",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"logitBias",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"modelName",{enumerable:!0,configurable:!0,writable:!0,value:"gpt-3.5-turbo"}),Object.defineProperty(this,"modelKwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stop",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"user",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streaming",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logprobs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"topLogprobs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"openAIApiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"azureOpenAIApiVersion",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"azureOpenAIApiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"azureOpenAIApiInstanceName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"azureOpenAIApiDeployme
<conversation>
{chatHistory}
</conversation>
Titel:`,initialReduce:`Fasse meine Notes (durch XML-Tags begrenzt) zusammen, sodass die Frage "{query}" im nachhinein noch ausführlich beantwortet werden könnte.
Fasse nur die Notes zusammen die zur beantwortung der Frage beitragen könnten und überspringe die anderen ohne diese weiter zu erwähnen.
Achte darauf, für jede zusammengefassten Note den Wikilink (format: [[<Note Path><# Header1><## Header2>...]]) zur Note als Referenz anzugeben.
Bitte behalte die markdown formatiertung der Notes bei.
<notes>
{content}
</notes>
Zusammenfassung:`,reduce:`Fasse meine Notes (durch XML-Tags begrenzt) zusammen, sodass die Frage "{query}" im nachhinein noch ausführlich beantwortet werden könnte.
Achte darauf, die markdown und wikilink formatierung in den Notes beizubehalten.
<notes>
{content}
</notes>
Zusammenfassung:`,rag:`Als mein Assistent, bitte antworte basierend auf meiner Frage und der chathistory, wobei du ausschließlich auf mein vorhandenes Wissen (durch XML-Tags begrenzt) aus Obsidian zurückgreifst.
Achte darauf, die Markdown-Formatierung zu verwenden und deiner Antwort, die im Wissen hinterlegten Wikilinks (wikilink format: [[<Note Path>]]) als Referenz hinzu zufügen.
<knowledge>
{context}
</knowledge>
<chathistory>
{chatHistory}
</chathistory>
<query>
{query}
</query>
Antwort:`,conversation:`Antworte als mein Assistent auf meine Frage basierend auf der chathistory (durch XML-Tags begrenzt).
<chathistory>
{chatHistory}
</chathistory>
<query>
{query}
</query>
Antwort:`},en:{initialAssistantMessage:"Hello, I am your assistant. How can I help you?",createTitle:`Create a very short title as a summary of the following conversation (enclosed by XML tags), so that it can be used directly as a filename. The title may only consist of letters and spaces.
<conversation>
{chatHistory}
</conversation>
Title:`,initialReduce:`Summarize my notes (enclosed by XML tags) so that the question "{query}" could still be answered in detail afterwards.
Only summarize the notes that could contribute to answering the question and skip the others without mentioning them further.
Make sure to include the wikilink (format: [[<Note Path><# Header1><## Header2>...]]) to the note as a reference for each summarized note.
Please keep the markdown formatting of the notes.
<notes>
{content}
</notes>
Summary:`,reduce:`Summarize my notes (enclosed by XML tags) so that the question "{query}" could still be answered in detail afterwards.
Make sure to keep the markdown and wikilink formatting (format: [[<Note>]]) in the notes.
<notes>
{content}
</notes>
Summary:`,rag:`As my assistant, please respond to my query, using only my existing knowledge (enclosed by XML tags) from Obsidian.
Make sure to use Markdown formatting and add the wikilinks (format: [[<Note>]]) from the knowledge as a reference to your answer.
<knowledge>
{context}
</knowledge>
<chathistory>
{chatHistory}
</chathistory>
<query>
{query}
</query>
Response:`,conversation:`Respond to my query as my assistant based on the chathistory.
<chathistory>
{chatHistory}
</chathistory>
<query>
{query}
</query>
Response:`},fr:{initialAssistantMessage:"Bonjour, je suis votre assistant. Comment puis-je vous aider?",createTitle:`Créez un titre très court comme résumé de la conversation suivante (encadrée par des balises XML), de sorte qu'il puisse être utilisé directement comme nom de fichier. Le titre ne peut contenir que des lettres et des espaces.
<conversation>
{chatHistory}
</conversation>
Titre:`,initialReduce:`Résumez mes notes (encadrées par des balises XML) de manière à ce que la question "{query}" puisse encore être répondue en détail par la suite.
Résumez uniquement les notes qui pourraient contribuer à répondre à la question et ignorez les autres sans les mentionner davantage.
Assurez-vous d'inclure le wikilink (format: [[<Note Path><# Header1><## Header2>...]]) à la note comme référence pour chaque note résumée.
<notes>
{content}
</notes>
Résumé:`,reduce:`Résumez mes notes (encadrées par des balises XML) de manière à ce que la question "{query}" puisse encore être répondue en détail par la suite.
Veillez à conserver la mise en forme markdown et les wikilinks (format: [[<Note>]]) dans les notes.
<notes>
{content}
</notes>
Résumé:`,rag:`En tant qu'assistant, veuillez répondre à ma question en utilisant uniquement mes connaissances existantes (encadrées par des balises XML) provenant d'Obsidian.
Assurez-vous d'utiliser la mise en forme Markdown et d'ajouter les wikilinks (format: [[<Note>]]) des connaissances comme référence à votre réponse.
<knowledge>
{context}
</knowledge>
<chathistory>
{chatHistory}
</chathistory>
<query>
{query}
</query>
Réponse:`,conversation:`Répondez à ma question en tant qu'assistant basé sur l'historique du chat.
<chathistory>
{chatHistory}
</chathistory>
<query>
{query}
</query>
Réponse:`}},QY=Object.keys(wa);async function wl(t,e){return L9(t)?await t.lcModel.getNumTokens(e):(Yf.encode(e)||[]).length}function WY(t,e,r){return Bi.from([{query:n=>n.userQuery,chatHistory:n=>n.chatHistory,context:Bi.from([n=>n.userQuery,t.withConfig({runName:"Retrieving"}).pipe(FY(e,r)).withConfig({runName:"PPDocs"}).pipe(yY(e,r))]).withConfig({runName:"Retrieving Notes"})},RY(e,r),e.lcModel,new g1]).withConfig({runName:"RAG Chat Pipe"})}function vY(t,e){return Bi.from([{query:a=>a.userQuery,chatHistory:a=>a.chatHistory},La.fromTemplate(wa[e.lang].conversation),t.lcModel,new g1]).withConfig({runName:"Normal Chat Pipe"})}function FY(t,e){return async r=>{const a=(await La.fromTemplate(wa[e.lang].reduce).formatPromptValue({query:e.userQuery,content:""})).toString(),n=t.contextWindow-await wl(t,a);zt.debug("Retrieved Docs",r);const i={};for(const o of r)i[o.metadata.filepath]||(i[o.metadata.filepath]=[]),i[o.metadata.filepath].push(o);const l=[];for(const o in i){i[o].sort((A,m)=>A.metadata.order-m.metadata.order);let d=[],u=[""];for(const A of i[o]){let m="";for(let h=0;h<A.metadata.header.length;h++)A.metadata.header[h]!==u[h]&&(m+=A.metadata.header[h]+`
`);u=A.metadata.header,d.push(m+A.pageContent)}const c=await T9(d,A=>wl(t,A),n),p=c.length>1;c.forEach((A,m)=>{let h="";h+=`<note>
`,h+="Wikilink: [["+o.replace(".md","")+"]]"+(p?" Part "+(m+1):"")+`
`,h+=A.join(`
`),h+=`
</note>`,l.push(h)})}const s=await wl(t,l.join(`
`))>n;return zt.debug("Postprocessed Docs",l),{notes:l,needsReduce:s}}}function yY(t,e){return async(r,a)=>{if(!r.needsReduce)return r.notes.join(`
`);const n=a==null?void 0:a.config;let i=r.notes,l=0;const s=(await La.fromTemplate(wa[e.lang].reduce).formatPromptValue({query:e.userQuery,content:""})).toString(),o=t.contextWindow-await wl(t,s);do{n&&(n.runName=`Reduce ${l+1}`);const d=await T9(i,c=>wl(t,c),o),u=Bi.from([{content:new OA,query:()=>e.userQuery},l===0?La.fromTemplate(wa[e.lang].initialReduce):La.fromTemplate(wa[e.lang].reduce),t.lcModel,new g1]);i=await Promise.all(d.map(c=>u.invoke(c.join(`
`)))),zt.debug("Reduced Docs",i),l+=1}while(await wl(t,i.join(`
`))>o);return i.join(`
`)}}async function T9(t,e,r){const a=[];let n=[];for(const i of t)if(n.push(i),await e(n.join(`
`))>r){if(n.length===1)throw new Error("User query is too long or a single document was longer than the context length (should not happen as we split documents by length in post processing).");a.push(n.slice(0,-1)),n=n.slice(-1)}return a.push(n),a}function RY(t,e){return async({query:r,chatHistory:a,context:n})=>{const i=(await La.fromTemplate(wa[e.lang].rag).formatPromptValue({query:r,context:n,chatHistory:a})).toString();return t.contextWindow>await wl(t,i)?i:"Please echo 'The chathistory is too long, please create a new chat or summarize it.'"}}var EY=class extends ml{constructor(t){super(t),this.indexName=t,this.version(1).stores({records:"id,filepath,indexed_at"}),this.records.clear()}async update(t){await this.transaction("rw",this.records,async()=>{await this.records.bulkPut(t)})}async exists(t){const e=await this.records.where("id").anyOf(t).toArray();return t.map(r=>e.some(a=>a.id===r))}async getIdsToDelete(t){let e=[];return t.indexStartTime&&t.sources&&t.sources.length>0?e=await this.records.where("indexed_at").below(t.indexStartTime).and(r=>t.sources.includes(r.filepath)).toArray():t.indexStartTime?e=await this.records.where("indexed_at").below(t.indexStartTime).toArray():t.sources&&(e=await this.records.where("filepath").anyOf(t.sources).toArray()),e.map(r=>r.id)}async deleteIds(t){await this.records.bulkDelete(t)}async restore(t){zt.debug("Restoring recordManager from backup"),await this.transaction("rw",this.records,async()=>{await this.records.bulkPut(t)}),zt.info("Restored recordManager from backup"),zt.debug({records:await this.records.toArray()})}async getData(){return await this.records.toArray()}},GY=class{constructor(t){Object.defineProperty(this,"pageContent",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.pageContent=t.pageContent?t.pageContent.toString():this.pageContent,this.metadata=t.metadata??{}}};Ma();uu();Ma();zs();var SY=class extends Ot{constructor(t){super(t),Object.defineProperty(this,"callbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"verbose",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.callbacks=t==null?void 0:t.callbacks,this.tags=(t==null?void 0:t.tags)??[],this.metadata=(t==null?void 0:t.metadata)??{},this.verbose=(t==null?void 0:t.verbose)??!1}_getRelevantDocuments(t,e){throw new Error("Not implemented!")}async invoke(t,e){return this.getRelevantDocuments(t,lr(e))}async getRelevantDocuments(t,e){const r=lr(N7(e)),a=await Pr.configure(r.callbacks,this.callbacks,r.tags,this.tags,r.metadata,this.metadata,{verbose:this.verbose}),n=await(a==null?void 0:a.handleRetrieverStart(this.toJSON(),t,void 0,void 0,void 0,void 0,r.runName));try{const i=await this._getRelevantDocuments(t,n);return await(n==null?void 0:n.handleRetrieverEnd(i)),i}catch(i){throw await(n==null?void 0:n.handleRetrieverError(i)),i}}};lu();var lg=class extends SY{static lc_name(){return"VectorStoreRetriever"}get lc_namespace(){return["langchain_core","vectorstores"]}_vectorstoreType(){return this.vectorStore._vectorstoreType()}constructor(t){super(t),Object.defineProperty(this,"vectorStore",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"k",{enumerable:!0,configurable:!0,writable:!0,value:4}),Object.defineProperty(this,"searchType",{enumerable:!0,configurable:!0,writable:!0,value:"similarity"}),Object.defineProperty(this,"searchKwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.vectorStore=t.vectorStore,this.k=t.k??this.k,this.searchType=t.searchType??this.searchType,this.filter=t.filter,t.searchType==="mmr"&&(this.searchKwargs=t.searchKwargs)}async _getRelevantDocuments(t,e){if(this.searchType==="mmr"){if(typeof
`,". ","? ","! "," ",""]}),s=await t.vault.cachedRead(a);let o=0,d=1,u=[],c=0,p=!1;for(const A of n.sections||[]){const m=s.slice(A.position.start.offset,A.position.end.offset),h=async(C,w=!1)=>{const b=a.path+(w?" metadata":u.join("")+" ID"+d);r.push({metadata:{id:b,hash:HY(b+m),filepath:a.path,order:w?0:d,header:[...u],content:w?`Metadaten:
`+m:m},pageContent:C}),w||d++};if(A.type==="yaml"&&!p){const C="Note Path: "+a.path+`
Metadaten:
`+m;h(C,!0),p=!0;continue}else if(A.type==="heading"){const C=n.headings[o],w=s.slice(C.position.start.offset,C.position.end.offset);C.level>c?(u.push(w),c=C.level):C.level<c?(u.pop(),u.pop(),u.push(w),c=C.level):(u.pop(),u.push(w)),o++}else{if(A.type==="thematicBreak")continue;if(A.type==="paragraph"){const C=await l.splitText(m);for(let w=0;w<C.length;w++){let b="";C[w+1]&&(C[w+1].charAt(0)==="."||C[w+1].charAt(0)==="?"||C[w+1].charAt(0)==="!")&&(b=C[w+1].charAt(0),C[w+1]=C[w+1].slice(1).trim());const f=C[w]+b,K="Note Path: "+a.path+`
`+u.join(`
`)+`
`+f;h(K)}}else if(A.type==="code"){if(m.length>i*4)continue;const C="Note Path: "+a.path+`
`+u.join(`
`)+`
`+m;h(C)}else{if(m.length>i*8)continue;const C="Note Path: "+a.path+`
`+u.join(`
`)+`
`+m;h(C)}}}}return zt.info("Loaded "+r.length+" documents from Obsidian"),r}/*! Bundled license information:
@langchain/core/dist/utils/fast-json-patch/src/helpers.js:
(*!
* https://github.com/Starcounter-Jack/JSON-Patch
* (c) 2017-2022 Joachim Wester
* MIT licensed
*)
@langchain/core/dist/utils/fast-json-patch/src/duplex.js:
(*!
* https://github.com/Starcounter-Jack/JSON-Patch
* (c) 2013-2021 Joachim Wester
* MIT license
*)
web-streams-polyfill/dist/ponyfill.mjs:
(**
* @license
* web-streams-polyfill v4.0.0-beta.3
* Copyright 2021 Mattias Buelens, Diwank Singh Tomer and other contributors.
* This code is released under the MIT license.
* SPDX-License-Identifier: MIT
*)
formdata-node/lib/esm/blobHelpers.js:
(*! Based on fetch-blob. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> & David Frank *)
formdata-node/lib/esm/Blob.js:
(*! Based on fetch-blob. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> & David Frank *)
humanize-ms/index.js:
(*!
* humanize-ms - index.js
* Copyright(c) 2014 dead_horse <dead_horse@qq.com>
* MIT Licensed
*)
web-streams-polyfill/dist/ponyfill.es2018.js:
(**
* @license
* web-streams-polyfill v3.3.3
* Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors.
* This code is released under the MIT license.
* SPDX-License-Identifier: MIT
*)
node-domexception/index.js:
(*! node-domexception. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> *)
@langchain/core/dist/utils/js-sha1/hash.js:
(*
* [js-sha1]{@link https://github.com/emn178/js-sha1}
*
* @version 0.6.0
* @author Chen, Yi-Cyuan [emn178@gmail.com]
* @copyright Chen, Yi-Cyuan 2014-2017
* @license MIT
*)
*/function le(){}const pC=t=>t;function Jd(t,e){for(const r in e)t[r]=e[r];return t}function U9(t){return t()}function Db(){return Object.create(null)}function We(t){t.forEach(U9)}function Yr(t){return typeof t=="function"}function st(t,e){return t!=t?e==e:t!==e||t&&typeof t=="object"||typeof t=="function"}function VY(t){return Object.keys(t).length===0}function cC(t,...e){if(t==null){for(const a of e)a(void 0);return le}const r=t.subscribe(...e);return r.unsubscribe?()=>r.unsubscribe():r}function ie(t){let e;return cC(t,r=>e=r)(),e}function me(t,e,r){t.$$.on_destroy.push(cC(e,r))}function hu(t,e,r,a){if(t){const n=_9(t,e,r,a);return t[0](n)}}function _9(t,e,r,a){return t[1]&&a?Jd(r.ctx.slice(),t[1](a(e))):r.ctx}function Bu(t,e,r,a){if(t[2]&&a){const n=t[2](a(r));if(e.dirty===void 0)return n;if(typeof n=="object"){const i=[],l=Math.max(e.dirty.length,n.length);for(let s=0;s<l;s+=1)i[s]=e.dirty[s]|n[s];return i}return e.dirty|n}return e.dirty}function Cu(t,e,r,a,n,i){if(n){const l=_9(e,r,a,i);t.p(l,n)}}function wu(t){if(t.ctx.length>32){const e=[],r=t.ctx.length/32;for(let a=0;a<r;a++)e[a]=-1;return e}return-1}function Ye(t,e,r){return t.set(r),e}function Ge(t){return t&&Yr(t.destroy)?t.destroy:le}const I9=typeof window<"u";let mC=I9?()=>window.performance.now():()=>Date.now(),gC=I9?t=>requestAnimationFrame(t):le;const ys=new Set;function D9(t){ys.forEach(e=>{e.c(t)||(ys.delete(e),e.f())}),ys.size!==0&&gC(D9)}function AC(t){let e;return ys.size===0&&gC(D9),{promise:new Promise(r=>{ys.add(e={c:t,f:r})}),abort(){ys.delete(e)}}}function E(t,e){t.appendChild(e)}function M9(t){if(!t)return document;const e=t.getRootNode?t.getRootNode():t.ownerDocument;return e&&e.host?e:t.ownerDocument}function YY(t){const e=X("style");return e.textContent="/* empty */",NY(M9(t),e),e.sheet}function NY(t,e){return E(t.head||t,e),e.sheet}function N(t,e,r){t.insertBefore(e,r||null)}function Y(t){t.parentNode&&t.parentNode.removeChild(t)}function ea(t,e){for(let r=0;r<t.length;r+=1)t[r]&&t[r].d(e)}function X(t){return document.createElement(t)}function ot(t){return document.createElementNS("http://www.w3.org/2000/svg",t)}function te(t){return document.createTextNode(t)}function M(){return te(" ")}function Tt(){return te("")}function de(t,e,r,a){return t.addEventListener(e,r,a),()=>t.removeEventListener(e,r,a)}function Sl(t){return function(e){return e.preventDefault(),t.call(this,e)}}function F(t,e,r){r==null?t.removeAttribute(e):t.getAttribute(e)!==r&&t.setAttribute(e,r)}function N0(t){return t===""?null:+t}function LY(t){return Array.from(t.childNodes)}function ne(t,e){e=""+e,t.data!==e&&(t.data=e)}function Wt(t,e){t.value=e??""}function yl(t,e,r,a){r==null?t.style.removeProperty(e):t.style.setProperty(e,r,a?"important":"")}function Ia(t,e,r){for(let a=0;a<t.options.length;a+=1){const n=t.options[a];if(n.__value===e){n.selected=!0;return}}(!r||e!==void 0)&&(t.selectedIndex=-1)}function Od(t){const e=t.querySelector(":checked");return e&&e.__value}function Mb(t,e,r){t.classList.toggle(e,!!r)}function TY(t,e,{bubbles:r=!1,cancelable:a=!1}={}){return new CustomEvent(t,{detail:e,bubbles:r,cancelable:a})}const L0=new Map;let T0=0;function kY(t){let e=5381,r=t.length;for(;r--;)e=(e<<5)-e^t.charCodeAt(r);return e>>>0}function UY(t,e){const r={stylesheet:YY(e),rules:{}};return L0.set(t,r),r}function x9(t,e,r,a,n,i,l,s=0){const o=16.666/a;let d=`{
`;for(let C=0;C<=1;C+=o){const w=e+(r-e)*i(C);d+=C*100+`%{${l(w,1-w)}}
`}const u=d+`100% {${l(r,1-r)}}
}`,c=`__svelte_${kY(u)}_${s}`,p=M9(t),{stylesheet:A,rules:m}=L0.get(p)||UY(p,t);m[c]||(m[c]=!0,A.insertRule(`@keyframes ${c} ${u}`,A.cssRules.length));const h=t.style.animation||"";return t.style.animation=`${h?`${h}, `:""}${c} ${a}ms linear ${n}ms 1 both`,T0+=1,c}function Ah(t,e){const r=(t.style.animation||"").split(", "),a=r.filter(e?i=>i.indexOf(e)<0:i=>i.indexOf("__svelte")===-1),n=r.length-a.length;n&&(t.style.animation=a.join(", "),T0-=n,T0||_Y())}function _Y(){gC(()=>{T0||(L0.forEach(t=>{const{ownerNode:e}=t.stylesheet;e&&Y(e)}),L0.clear())})}let Pd;function md(t){Pd=t}function J9(){if(!Pd)throw new Error("Function called outside component initialization");return Pd}function bi(t){J9().$$.on_mount.push(t)}function hC(t){J9().$$.after_update.push(t)}const us=[],hr=[];let Rs=[];const hh=[],IY=Promise.resolve();let Bh=!1;function DY(){Bh||(Bh=!0,IY.then(O9))}function Dr(t){Rs.push(t)}function h1(t){hh.push(t)}const sg=new Set;let ts=0;function O9(){if(ts!==0)return;const t=Pd;do{try{for(;ts<us.length;){const e=us[ts];ts++,md(e),MY(e.$$)}}catch(e){throw us.length=0,ts=0,e}for(md(null),us.length=0,ts=0;hr.length;)hr.pop()();for(let e=0;e<Rs.length;e+=1){const r=Rs[e];sg.has(r)||(sg.add(r),r())}Rs.length=0}while(us.length);for(;hh.length;)hh.pop()();Bh=!1,sg.clear(),md(t)}function MY(t){if(t.fragment!==null){t.update(),We(t.before_update);const e=t.dirty;t.dirty=[-1],t.fragment&&t.fragment.p(t.ctx,e),t.after_update.forEach(Dr)}}function xY(t){const e=[],r=[];Rs.forEach(a=>t.indexOf(a)===-1?e.push(a):r.push(a)),r.forEach(a=>a()),Rs=e}let So;function P9(){return So||(So=Promise.resolve(),So.then(()=>{So=null})),So}function k0(t,e,r){t.dispatchEvent(TY(`${e?"intro":"outro"}${r}`))}const hc=new Set;let ai;function vt(){ai={r:0,c:[],p:ai}}function Ft(){ai.r||We(ai.c),ai=ai.p}function D(t,e){t&&t.i&&(hc.delete(t),t.i(e))}function J(t,e,r,a){if(t&&t.o){if(hc.has(t))return;hc.add(t),ai.c.push(()=>{hc.delete(t),a&&(r&&t.d(1),a())}),t.o(e)}else a&&a()}const z9={duration:0};function BC(t,e,r){const a={direction:"in"};let n=e(t,r,a),i=!1,l,s,o=0;function d(){l&&Ah(t,l)}function u(){const{delay:p=0,duration:A=300,easing:m=pC,tick:h=le,css:C}=n||z9;C&&(l=x9(t,0,1,A,p,m,C,o++)),h(0,1);const w=mC()+p,b=w+A;s&&s.abort(),i=!0,Dr(()=>k0(t,!0,"start")),s=AC(f=>{if(i){if(f>=b)return h(1,0),k0(t,!0,"end"),d(),i=!1;if(f>=w){const K=m((f-w)/A);h(K,1-K)}}return i})}let c=!1;return{start(){c||(c=!0,Ah(t),Yr(n)?(n=n(a),P9().then(u)):u())},invalidate(){c=!1},end(){i&&(d(),i=!1)}}}function CC(t,e,r){const a={direction:"out"};let n=e(t,r,a),i=!0,l;const s=ai;s.r+=1;let o;function d(){const{delay:u=0,duration:c=300,easing:p=pC,tick:A=le,css:m}=n||z9;m&&(l=x9(t,1,0,c,u,p,m));const h=mC()+u,C=h+c;Dr(()=>k0(t,!1,"start")),"inert"in t&&(o=t.inert,t.inert=!0),AC(w=>{if(i){if(w>=C)return A(0,1),k0(t,!1,"end"),--s.r||We(s.c),!1;if(w>=h){const b=p((w-h)/c);A(1-b,b)}}return i})}return Yr(n)?P9().then(()=>{n=n(a),d()}):d(),{end(u){u&&"inert"in t&&(t.inert=o),u&&n.tick&&n.tick(1,0),i&&(l&&Ah(t,l),i=!1)}}}function Xt(t){return(t==null?void 0:t.length)!==void 0?t:Array.from(t)}function JY(t,e){J(t,1,1,()=>{e.delete(t.key)})}function OY(t,e,r,a,n,i,l,s,o,d,u,c){let p=t.length,A=i.length,m=p;const h={};for(;m--;)h[t[m].key]=m;const C=[],w=new Map,b=new Map,f=[];for(m=A;m--;){const v=c(n,i,m),L=r(v);let y=l.get(L);y?a&&f.push(()=>y.p(v,e)):(y=d(L,v),y.c()),w.set(L,C[m]=y),L in h&&b.set(L,Math.abs(m-h[L]))}const K=new Set,W=new Set;function R(v){D(v,1),v.m(s,u),l.set(v.key,v),u=v.first,A--}for(;p&&A;){const v=C[A-1],L=t[p-1],y=v.key,G=L.key;v===L?(u=v.first,p--,A--):w.has(G)?!l.has(y)||K.has(y)?R(v):W.has(G)?p--:b.get(y)>b.get(G)?(W.add(y),R(v)):(K.add(G),p--):(o(L,l),p--)}for(;p--;){const v=t[p];w.has(v.key)||o(v,l)}for(;A;)R(C[A-1]);return We(f),C}function B1(t,e,r){const a=t.$$.props[e];a!==void 0&&(t.$$.bound[a]=r,r(t.$$.ctx[a]))}function pe(t){t&&t.c()}function se(t,e,r){const{fragment:a,after_update:n}=t.$$;a&&a.m(e,r),Dr(()=>{const i=t.$$.on_mount.map(U9).filter(Yr);t.$$.on_destroy?t.$$.on_destroy.push(...i):We(i),t.$$.on_mount=[]}),n.forEach(Dr)}function oe
Try polyfilling it using "@formatjs/intl-pluralrules"
`,Us.MISSING_INTL_API,l);var K=r.getPluralRules(e,{type:u.pluralType}).select(p-(u.offset||0));f=u.options[K]||u.options.other}if(!f)throw new eK(u.value,p,Object.keys(u.options),l);s.push.apply(s,Bc(f.value,e,r,a,n,p-(u.offset||0)));continue}}return qN(s)}function eL(t,e){return e?$e($e($e({},t||{}),e||{}),Object.keys(t).reduce(function(r,a){return r[a]=$e($e({},t[a]),e[a]||{}),r},{})):t}function tL(t,e){return e?Object.keys(t).reduce(function(r,a){return r[a]=eL(t[a],e[a]),r},$e({},t)):t}function cg(t){return{create:function(){return{get:function(e){return t[e]},set:function(e,r){t[e]=r}}}}}function rL(t){return t===void 0&&(t={number:{},dateTime:{},pluralRules:{}}),{getNumberFormat:ug(function(){for(var e,r=[],a=0;a<arguments.length;a++)r[a]=arguments[a];return new((e=Intl.NumberFormat).bind.apply(e,og([void 0],r,!1)))},{cache:cg(t.number),strategy:pg.variadic}),getDateTimeFormat:ug(function(){for(var e,r=[],a=0;a<arguments.length;a++)r[a]=arguments[a];return new((e=Intl.DateTimeFormat).bind.apply(e,og([void 0],r,!1)))},{cache:cg(t.dateTime),strategy:pg.variadic}),getPluralRules:ug(function(){for(var e,r=[],a=0;a<arguments.length;a++)r[a]=arguments[a];return new((e=Intl.PluralRules).bind.apply(e,og([void 0],r,!1)))},{cache:cg(t.pluralRules),strategy:pg.variadic})}}var gv=function(){function t(e,r,a,n){var i=this;if(r===void 0&&(r=t.defaultLocale),this.formatterCache={number:{},dateTime:{},pluralRules:{}},this.format=function(o){var d=i.formatToParts(o);if(d.length===1)return d[0].value;var u=d.reduce(function(c,p){return!c.length||p.type!==vr.literal||typeof c[c.length-1]!="string"?c.push(p.value):c[c.length-1]+=p.value,c},[]);return u.length<=1?u[0]||"":u},this.formatToParts=function(o){return Bc(i.ast,i.locales,i.formatters,i.formats,o,void 0,i.message)},this.resolvedOptions=function(){var o;return{locale:((o=i.resolvedLocale)===null||o===void 0?void 0:o.toString())||Intl.NumberFormat.supportedLocalesOf(i.locales)[0]}},this.getAst=function(){return i.ast},this.locales=r,this.resolvedLocale=t.resolveLocale(r),typeof e=="string"){if(this.message=e,!t.__parse)throw new TypeError("IntlMessageFormat.__parse must be set to process `message` of type `string`");var l=n||{};l.formatters;var s=mN(l,["formatters"]);this.ast=t.__parse(e,$e($e({},s),{locale:this.resolvedLocale}))}else this.ast=e;if(!Array.isArray(this.ast))throw new TypeError("A message must be provided as a String or AST.");this.formats=tL(t.formats,a),this.formatters=n&&n.formatters||rL(this.formatterCache)}return Object.defineProperty(t,"defaultLocale",{get:function(){return t.memoizedDefaultLocale||(t.memoizedDefaultLocale=new Intl.NumberFormat().resolvedOptions().locale),t.memoizedDefaultLocale},enumerable:!1,configurable:!0}),t.memoizedDefaultLocale=null,t.resolveLocale=function(e){if(!(typeof Intl.Locale>"u")){var r=Intl.NumberFormat.supportedLocalesOf(e);return r.length>0?new Intl.Locale(r[0]):new Intl.Locale(typeof e=="string"?e:e[0])}},t.__parse=IN,t.formats={number:{integer:{maximumFractionDigits:0},currency:{style:"currency"},percent:{style:"percent"}},date:{short:{month:"numeric",day:"numeric",year:"2-digit"},medium:{month:"short",day:"numeric",year:"numeric"},long:{month:"long",day:"numeric",year:"numeric"},full:{weekday:"long",month:"long",day:"numeric",year:"numeric"}},time:{short:{hour:"numeric",minute:"numeric"},medium:{hour:"numeric",minute:"numeric",second:"numeric"},long:{hour:"numeric",minute:"numeric",second:"numeric",timeZoneName:"short"},full:{hour:"numeric",minute:"numeric",second:"numeric",timeZoneName:"short"}}},t}();function aL(t,e){if(e==null)return;if(e in t)return t[e];const r=e.split(".");let a=t;for(let n=0;n<r.length;n++)if(typeof a=="object"){if(n>0){const i=r.slice(n,r.length).join(".");if(i in a){a=a[i];break}}a=a[r[n]]}else a=void 0;return a}const ni={},nL=(t,e,r)=>r&&(e in ni||(ni[e]={}),t in ni[e]||(ni[e][t]=r),r),Av=(t,e)=>{if(e==null)return;if(e in ni&&t in ni[e])return ni[e][t];const r=Ku(e);for(let a=0;a<r.length;a++){const n=r[a],i=lL(n,t);if(i)return nL(t,e,i)}};let KC;const bu=$t({});function iL(t){return KC[t]||n
Note: there are at least one loader still registered to this locale that wasn't executed.`:""}`)}const hL={fallbackLocale:null,loadingDelay:200,formats:gL,warnOnMissingMessages:!0,handleMissingMessage:void 0,ignoreTag:!0},$o=hL;function _s(){return $o}function BL(t){const e=t,{formats:r}=e,a=mL(e,["formats"]);let n=t.fallbackLocale;if(t.initialLocale)try{gv.resolveLocale(t.initialLocale)&&(n=t.initialLocale)}catch{console.warn(`[svelte-i18n] The initial locale "${t.initialLocale}" is not a valid locale.`)}return a.warnOnMissingMessages&&(delete a.warnOnMissingMessages,a.handleMissingMessage==null?a.handleMissingMessage=AL:console.warn('[svelte-i18n] The "warnOnMissingMessages" option is deprecated. Please use the "handleMissingMessage" option instead.')),Object.assign($o,a,{initialLocale:n}),r&&("number"in r&&Object.assign($o.formats.number,r.number),"date"in r&&Object.assign($o.formats.date,r.date),"time"in r&&Object.assign($o.formats.time,r.time)),qs.set(n)}const mg=$t(!1);var CL=Object.defineProperty,wL=Object.defineProperties,bL=Object.getOwnPropertyDescriptors,rK=Object.getOwnPropertySymbols,KL=Object.prototype.hasOwnProperty,fL=Object.prototype.propertyIsEnumerable,aK=(t,e,r)=>e in t?CL(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,QL=(t,e)=>{for(var r in e||(e={}))KL.call(e,r)&&aK(t,r,e[r]);if(rK)for(var r of rK(e))fL.call(e,r)&&aK(t,r,e[r]);return t},WL=(t,e)=>wL(t,bL(e));let vh;const _0=$t(null);function nK(t){return t.split("-").map((e,r,a)=>a.slice(0,r+1).join("-")).reverse()}function Ku(t,e=_s().fallbackLocale){const r=nK(t);return e?[...new Set([...r,...nK(e)])]:r}function Ki(){return vh??void 0}_0.subscribe(t=>{vh=t??void 0,typeof window<"u"&&t!=null&&document.documentElement.setAttribute("lang",t)});const vL=t=>{if(t&&sL(t)&&U0(t)){const{loadingDelay:e}=_s();let r;return typeof window<"u"&&Ki()!=null&&e?r=window.setTimeout(()=>mg.set(!0),e):mg.set(!0),Cv(t).then(()=>{_0.set(t)}).finally(()=>{clearTimeout(r),mg.set(!1)})}return _0.set(t)},qs=WL(QL({},_0),{set:vL}),b1=t=>{const e=Object.create(null);return a=>{const n=JSON.stringify(a);return n in e?e[n]:e[n]=t(a)}};var FL=Object.defineProperty,I0=Object.getOwnPropertySymbols,wv=Object.prototype.hasOwnProperty,bv=Object.prototype.propertyIsEnumerable,iK=(t,e,r)=>e in t?FL(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,fC=(t,e)=>{for(var r in e||(e={}))wv.call(e,r)&&iK(t,r,e[r]);if(I0)for(var r of I0(e))bv.call(e,r)&&iK(t,r,e[r]);return t},$s=(t,e)=>{var r={};for(var a in t)wv.call(t,a)&&e.indexOf(a)<0&&(r[a]=t[a]);if(t!=null&&I0)for(var a of I0(t))e.indexOf(a)<0&&bv.call(t,a)&&(r[a]=t[a]);return r};const jd=(t,e)=>{const{formats:r}=_s();if(t in r&&e in r[t])return r[t][e];throw new Error(`[svelte-i18n] Unknown "${e}" ${t} format.`)},yL=b1(t=>{var e=t,{locale:r,format:a}=e,n=$s(e,["locale","format"]);if(r==null)throw new Error('[svelte-i18n] A "locale" must be set to format numbers');return a&&(n=jd("number",a)),new Intl.NumberFormat(r,n)}),RL=b1(t=>{var e=t,{locale:r,format:a}=e,n=$s(e,["locale","format"]);if(r==null)throw new Error('[svelte-i18n] A "locale" must be set to format dates');return a?n=jd("date",a):Object.keys(n).length===0&&(n=jd("date","short")),new Intl.DateTimeFormat(r,n)}),EL=b1(t=>{var e=t,{locale:r,format:a}=e,n=$s(e,["locale","format"]);if(r==null)throw new Error('[svelte-i18n] A "locale" must be set to format time values');return a?n=jd("time",a):Object.keys(n).length===0&&(n=jd("time","short")),new Intl.DateTimeFormat(r,n)}),GL=(t={})=>{var e=t,{locale:r=Ki()}=e,a=$s(e,["locale"]);return yL(fC({locale:r},a))},SL=(t={})=>{var e=t,{locale:r=Ki()}=e,a=$s(e,["locale"]);return RL(fC({locale:r},a))},ZL=(t={})=>{var e=t,{locale:r=Ki()}=e,a=$s(e,["locale"]);return EL(fC({locale:r},a))},XL=b1((t,e=Ki())=>new gv(t,e,_s().formats,{ignoreTag:_s().ignoreTag})),HL=(t,e={})=>{var r,a,n,i;let l=e;typeof t=="object"&&(l=t,t=l.id);const{values:s,locale:o=Ki(),default:d}=l;if(o==null)throw new Error("[svelte-i18n] Cannot format a message without first setting the initial locale.");let u=Av(t,o);if(!u)u=(i=(n=(a=(r=_s()
`);function kL(){const{subscribe:t,set:e,update:r}=$t();return{subscribe:t,set:e,update:r,reset:()=>{e([{role:"Assistant",content:ie(ae).initialAssistantMessageContent,id:fu()}]),ie(dt).chatView.save()}}}const Mt=kL();function UL(){const{subscribe:t,set:e,update:r}=$t();return{subscribe:t,set:e,update:r,warningOff:a=>{r(n=>(n[a]=!0,n)),ie(dt).saveSettings()}}}const ae=UL();function hs(t,e){const r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp(`\\b${r.replace(/\*/g,".*").replace(/\?/g,".")}`,"i").test(e)}class _L extends Qe.SuggestModal{constructor(r){super(r);Ze(this,"ff");this.ff=this.app.vault.getMarkdownFiles()}getSuggestions(r){const a=this.inputEl.value,n=ie(ae).excludeFF,i=[];return this.ff.forEach(l=>{if(l.path!=="/"){for(const s of n)if(hs(s,l.path))return;hs(r,l.path)&&i.push(l)}}),i.sort((l,s)=>l.path.localeCompare(s.path)),a?[a,...i]:i}renderSuggestion(r,a){typeof r=="string"&&a.createEl("div",{text:r}),a.createEl("div",{text:r.path})}onChooseSuggestion(r){const a=ie(ae);let n;typeof r=="string"?n=r:n=r.path,a.excludeFF.includes(n)||(ae.update(i=>(i.excludeFF=[...i.excludeFF,n],Ve.set("settings-change"),i)),ie(dt).saveSettings())}}var ii;(function(t){t[t.DEBUG=1]="DEBUG",t[t.INFO=2]="INFO",t[t.ERROR=3]="ERROR",t[t.DISABLED=4]="DISABLED"})(ii||(ii={}));const al=class al{static setLogLevel(e){al.logLevel=e}static debug(...e){al.logLevel<=ii.DEBUG&&console.debug("[S2B]",...e)}static info(...e){al.logLevel<=ii.INFO&&console.info("[S2B]",...e)}static error(...e){al.logLevel<=ii.ERROR&&console.error("[S2B]",...e)}};Ze(al,"logLevel",ii.DEBUG);let dr=al;const Fh={"gpt-3.5-turbo":{contextWindow:16385},"gpt-4":{contextWindow:8192},"gpt-4-32k":{contextWindow:32768},"gpt-4-turbo":{contextWindow:128e3},"gpt-4o":{contextWindow:128e3}},yh={llama2:{contextWindow:4096},"llama2-uncensored":{contextWindow:4096},mistral:{contextWindow:8e3},"mistral-openorca":{contextWindow:8e3},gemma:{contextWindow:8e3},mixtral:{contextWindow:32e3},"dolphin-mixtral":{contextWindow:32e3},phi:{contextWindow:2048}},IL=Object.keys(Fh),Es=Object.keys(yh),DL=["text-embedding-3-large","text-embedding-3-small","text-embedding-ada-002"],li=["nomic-embed-text","mxbai-embed-large"];async function si(){const t=ie(ae);try{new URL(t.ollamaGenModel.baseUrl);const e=await Qe.requestUrl(t.ollamaGenModel.baseUrl+"/api/tags");return e.status===200?!0:(dr.debug(`IsOllamaRunning, Unexpected status code: ${e.status}`),!1)}catch(e){return dr.debug("Ollama is not running",e),!1}}async function ML(){const t=ie(ae);try{const e=await fetch(t.ollamaGenModel.baseUrl+"/api/tags");return e.status===200?!0:(dr.debug(`Unexpected status code: ${e.status}`),!1)}catch(e){return dr.debug("Ollama is not running or origins not correctly set",e),!1}}async function jr(){const t=ie(ae);try{return(await Qe.requestUrl({url:t.ollamaGenModel.baseUrl+"/api/tags",method:"GET",headers:{"Content-Type":"application/json"}})).json.models.map(a=>a.name).map(a=>a.replace(":latest",""))}catch(e){return dr.debug("Ollama is not running",e),[]}}async function Qv(t){const e=ie(dt),r=ie(ae),a=await jr();if(ae.update(n=>(n.ollamaGenModel.model=t,n.ollamaGenModel.contextWindow=yh[t]?yh[t].contextWindow:2048,n)),e.saveSettings(),!a.includes(t)){Ve.set("error"),dl.set("ollama-gen-model-not-installed");return}e.s2b.setGenModel(r.openAIGenModel)}async function Wv(t){const e=ie(dt),r=await jr();if(ae.update(a=>(a.ollamaEmbedModel.model=t,a)),e.saveSettings(),!r.includes(t)){Ve.set("error"),dl.set("ollama-embed-model-not-installed");return}Ve.set("settings-change")}const Rh=async t=>{const e=ie(ae),r=ie(dt);t.trim(),t.endsWith("/")&&(t=t.slice(0,-1)),e.ollamaGenModel.baseUrl=t,e.ollamaEmbedModel.baseUrl=t,await r.saveSettings(),Ve.set("settings-change")};async function xL(t){const e=ie(ae),r=ie(Bt);try{const a=await Qe.requestUrl({url:e.ollamaGenModel.baseUrl+"/api/delete",method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t})});return a.status===404?(new Qe.Notice(r("notice.no_models",{values:{model:t}}),4e3),!1):a.status===200?(new Qe.Notice(r("notice.models_deleted
`);i=d.pop();for(const u of d)if(u.trim())try{yield JSON.parse(u)}catch(c){return c}}}catch(r){return r}}async function D0(t){try{return(await Qe.requestUrl({method:"GET",url:"https://api.openai.com/v1/models",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}})).status===200}catch{return!1}}class OL{constructor(e,r){Ze(this,"papa");Ze(this,"app");Ze(this,"needsToSaveVectorStoreData",!1);Ze(this,"pluginDir");this.app=e,this.pluginDir=r}async init(){const e=ie(ae),r=ie(Bt);if(ie(Ve)==="running")return new Qe.Notice(r("notice.still_running"),4e3);if(ie(Ve)==="indexing"||ie(Ve)==="loading")return new Qe.Notice(r("notice.still_indexing"),4e3);if(e.isIncognitoMode&&!await si())return Ve.set("error"),dl.set("ollama-not-running"),new Qe.Notice(r("notice.ollama_not_running"),4e3);if(e.isIncognitoMode){const l=await jr();if(!l.includes(e.ollamaGenModel.model))return Ve.set("error"),dl.set("ollama-gen-model-not-installed"),new Qe.Notice(r("notice.ollama_gen_model"),4e3);if(!l.includes(e.ollamaEmbedModel.model))return Ve.set("error"),dl.set("ollama-embed-model-not-installed"),new Qe.Notice(r("notice.ollama_embed_model"),4e3)}else if(!e.isIncognitoMode&&!await D0(e.openAIGenModel.openAIApiKey))return Ve.set("error"),new Qe.Notice(r("notice.openai_key"),4e3);if(ie(Ve)!=="indexing-pause"){Ve.set("loading"),dr.info("Initializing second brain",`
Gen Model: `,e.isIncognitoMode?e.ollamaGenModel:e.openAIGenModel,`
Embed Model: `,e.isIncognitoMode?e.ollamaEmbedModel:e.openAIEmbedModel);try{this.papa=new k9,await this.papa.init({genModel:e.isIncognitoMode?e.ollamaGenModel:e.openAIGenModel,embedModel:e.isIncognitoMode?e.ollamaEmbedModel:e.openAIEmbedModel,langsmithApiKey:e.debugginLangchainKey||void 0,logLvl:e.isVerbose?ii.DEBUG:ii.DISABLED})}catch(l){return dr.error(l),Ve.set("error"),new Qe.Notice(r("notice.failed",{values:{error:l}}),4e3)}if(await this.app.vault.adapter.exists(this.getVectorStoreFile())){const l=await this.app.vault.adapter.readBinary(this.getVectorStoreFile());await this.papa.load(l)}}const a=this.app.vault.getMarkdownFiles(),n=await kp(this.app,a.filter(l=>{for(const s of e.excludeFF)if(hs(s,l.path))return!1;return!0}));Ve.set("indexing");let i=!1;try{let l=Date.now();const s=[];let o=0;for await(const d of this.papa.embedDocuments(n)){i=!this.needsToSaveVectorStoreData&&d.numAdded>0||d.numDeleted>0;const u=(d.numAdded+d.numSkipped)/n.length*100;gn.set(Math.max(u,ie(gn)));const c=Date.now();s.push(c-l);const p=n.length*(1-ie(gn)/100),A=s.reduce((m,h)=>m+h,0)/s.length/(d.numAdded+d.numSkipped-o)/1e3;if(o=d.numAdded+d.numSkipped,s.length>5&&(s.shift(),fv.set(Math.ceil(A*p))),l=c,ie(Ve)==="indexing-pause")break}}catch(l){dr.error(l),Ve.set("error"),dl.set("failed-indexing"),new Qe.Notice(r("notice.failed_indexing"),4e3)}this.needsToSaveVectorStoreData=i,this.saveVectorStoreData(),ie(gn)===100&&(new Qe.Notice(r("notice.done"),2e3),gn.set(0),Ve.set("idle"))}async cancelIndexing(){Ve.set("uninitialized"),gn.set(0)}canRunPapa(){const e=ie(Bt);return ie(Ve)==="running"?new Qe.Notice(e("notice.still_running"),4e3)&&!1:ie(Ve)==="indexing"||ie(Ve)==="indexing-pause"||ie(Ve)==="loading"?new Qe.Notice(e("notice.still_indexing"),4e3)&&!1:ie(Ve)==="error"?new Qe.Notice(e("notice.error"),4e3)&&!1:ie(Ve)!=="idle"?new Qe.Notice(e("notice.not_initialized"),4e3)&&!1:!0}async runPapa(){Ve.set("running");try{const e=ie(Mt),r=e[e.length-1].content,a=this.papa.run({isRAG:ie(ae).isUsingRag,userQuery:r,chatHistory:lK(e.slice(0,e.length-1)),lang:ie(ae).assistantLanguage});for await(const n of a)Kv.set(n.status),$d.set(n.content)}catch(e){const r=ie(Bt)("notice.run_failed",{values:{error:e}});$d.set(r),new Qe.Notice(r,4e3)}Ve.set("idle")}async createFilenameForChat(){let e=await this.papa.createTitleFromChatHistory(ie(ae).assistantLanguage,lK(ie(Mt)));return e=e.replace(/[\\/:*?"<>|#]/g,""),e}getVectorStoreFile(){const e=ie(ae);return Qe.normalizePath(this.pluginDir+"/vectorstores/"+(e.isIncognitoMode?e.ollamaEmbedModel.model:e.openAIEmbedModel.model)+".bin")}async saveVectorStoreData(){this.needsToSaveVectorStoreData&&this.papa&&(dr.debug("Saving vector store data"),this.needsToSaveVectorStoreData=!1,await this.app.vault.adapter.exists(this.pluginDir+"/vectorstores")||await this.app.vault.adapter.mkdir(this.pluginDir+"/vectorstores"),await this.app.vault.adapter.writeBinary(this.getVectorStoreFile(),await this.papa.getData()),dr.info("Saved vector store data"))}async onFileChange(e){if(!this.papa)return;for(const a of ie(ae).excludeFF)if(hs(a,e.path))return;const r=await kp(this.app,[e]);this.papa.embedDocuments(r,"byFile"),this.needsToSaveVectorStoreData=!0}async onFileDelete(e){if(!this.papa)return;for(const a of ie(ae).excludeFF)if(hs(a,e.path))return;const r=await kp(this.app,[e]);this.papa.deleteDocuments({docs:r}),this.needsToSaveVectorStoreData=!0}async onFileRename(e,r){if(!this.papa)return;for(const n of ie(ae).excludeFF)if(hs(n,e.path))return;await this.papa.deleteDocuments({sources:[r]});const a=await kp(this.app,[e]);this.papa.embedDocuments(a,"byFile"),this.needsToSaveVectorStoreData=!0}setSimilarityThreshold(e){this.papa&&this.papa.setSimilarityThreshold(e)}stopRun(){this.papa&&this.papa.stopRun(),Ve.set("idle")}setNumOfDocsToRetrieve(e){this.papa&&this.papa.setNumOfDocsToRetrieve(e)}setGenModel(e){this.papa&&this.papa.setGenModel(e)}setTracer(e){this.papa&&this.papa.setTracer(e)}}typeof window<"u"&&(window.__svelte||(window.__svelte={v:new Set})).v.add(zY);const PL=/\u00A0/g;let Eh=[];const _r=(t,e)=>{const r=ie(dt);t.inne
`),pe(r.$$.fragment)},m(n,i){N(n,e,i),se(r,n,i),a=!0},p:le,i(n){a||(D(r.$$.fragment,n),a=!0)},o(n){J(r.$$.fragment,n),a=!1},d(n){n&&Y(e),oe(r,n)}}}function RT(t){let e;return{c(){e=te("Ollama is Not Running")},m(r,a){N(r,e,a)},p:le,i:le,o:le,d(r){r&&Y(e)}}}function hK(t){let e,r,a,n;return e=new sr({props:{name:t[3]("settings.ollama.gen_model"),desc:t[3]("settings.ollama.model_descriptions."+t[4].ollamaGenModel.model,{default:""}),$$slots:{default:[GT]},$$scope:{ctx:t}}}),a=new sr({props:{name:t[3]("settings.ollama.embed_model"),desc:t[3]("settings.ollama.model_descriptions."+t[4].ollamaEmbedModel.model,{default:""}),$$slots:{default:[ZT]},$$scope:{ctx:t}}}),{c(){pe(e.$$.fragment),r=M(),pe(a.$$.fragment)},m(i,l){se(e,i,l),N(i,r,l),se(a,i,l),n=!0},p(i,l){const s={};l&8&&(s.name=i[3]("settings.ollama.gen_model")),l&24&&(s.desc=i[3]("settings.ollama.model_descriptions."+i[4].ollamaGenModel.model,{default:""})),l&2097180&&(s.$$scope={dirty:l,ctx:i}),e.$set(s);const o={};l&8&&(o.name=i[3]("settings.ollama.embed_model")),l&24&&(o.desc=i[3]("settings.ollama.model_descriptions."+i[4].ollamaEmbedModel.model,{default:""})),l&2097180&&(o.$$scope={dirty:l,ctx:i}),a.$set(o)},i(i){n||(D(e.$$.fragment,i),D(a.$$.fragment,i),n=!0)},o(i){J(e.$$.fragment,i),J(a.$$.fragment,i),n=!1},d(i){i&&Y(r),oe(e,i),oe(a,i)}}}function ET(t){let e;return{c(){e=X("option"),e.textContent=`${t[12]}`,e.__value=t[12],Wt(e,e.__value)},m(r,a){N(r,e,a)},p:le,d(r){r&&Y(e)}}}function BK(t){let e,r=t[12]+"",a,n;return{c(){e=X("option"),a=te(r),e.__value=n=t[12],Wt(e,e.__value)},m(i,l){N(i,e,l),E(e,a)},p(i,l){l&4&&r!==(r=i[12]+"")&&ne(a,r),l&4&&n!==(n=i[12])&&(e.__value=n,Wt(e,e.__value))},d(i){i&&Y(e)}}}function GT(t){let e,r,a,n,i,l,s,o=Xt(Es),d=[];for(let p=0;p<o.length;p+=1)d[p]=ET(vT(t,o,p));let u=Xt(t[2].filter(t[6])),c=[];for(let p=0;p<u.length;p+=1)c[p]=BK(AK(t,u,p));return{c(){e=X("select"),r=X("optgroup");for(let p=0;p<d.length;p+=1)d[p].c();n=X("optgroup");for(let p=0;p<c.length;p+=1)c[p].c();F(r,"label",a=t[3]("settings.ollama.recommended")),F(n,"label",i=t[3]("settings.ollama.other")),F(e,"class","dropdown"),t[4].ollamaGenModel.model===void 0&&Dr(()=>t[7].call(e))},m(p,A){N(p,e,A),E(e,r);for(let m=0;m<d.length;m+=1)d[m]&&d[m].m(r,null);E(e,n);for(let m=0;m<c.length;m+=1)c[m]&&c[m].m(n,null);Ia(e,t[4].ollamaGenModel.model,!0),l||(s=[de(e,"change",t[7]),de(e,"change",t[8])],l=!0)},p(p,A){if(A&8&&a!==(a=p[3]("settings.ollama.recommended"))&&F(r,"label",a),A&4){u=Xt(p[2].filter(p[6]));let m;for(m=0;m<u.length;m+=1){const h=AK(p,u,m);c[m]?c[m].p(h,A):(c[m]=BK(h),c[m].c(),c[m].m(n,null))}for(;m<c.length;m+=1)c[m].d(1);c.length=u.length}A&8&&i!==(i=p[3]("settings.ollama.other"))&&F(n,"label",i),A&20&&Ia(e,p[4].ollamaGenModel.model)},d(p){p&&Y(e),ea(d,p),ea(c,p),l=!1,We(s)}}}function ST(t){let e;return{c(){e=X("option"),e.textContent=`${t[12]}`,e.__value=t[12],Wt(e,e.__value)},m(r,a){N(r,e,a)},p:le,d(r){r&&Y(e)}}}function CK(t){let e,r=t[12]+"",a,n;return{c(){e=X("option"),a=te(r),e.__value=n=t[12],Wt(e,e.__value)},m(i,l){N(i,e,l),E(e,a)},p(i,l){l&4&&r!==(r=i[12]+"")&&ne(a,r),l&4&&n!==(n=i[12])&&(e.__value=n,Wt(e,e.__value))},d(i){i&&Y(e)}}}function ZT(t){let e,r,a,n,i,l,s,o=Xt(li),d=[];for(let p=0;p<o.length;p+=1)d[p]=ST(WT(t,o,p));let u=Xt(t[2].filter(t[9])),c=[];for(let p=0;p<u.length;p+=1)c[p]=CK(gK(t,u,p));return{c(){e=X("select"),r=X("optgroup");for(let p=0;p<d.length;p+=1)d[p].c();n=X("optgroup");for(let p=0;p<c.length;p+=1)c[p].c();F(r,"label",a=t[3]("settings.ollama.recommended")),F(n,"label",i=t[3]("settings.ollama.other")),F(e,"class","dropdown"),t[4].ollamaEmbedModel.model===void 0&&Dr(()=>t[10].call(e))},m(p,A){N(p,e,A),E(e,r);for(let m=0;m<d.length;m+=1)d[m]&&d[m].m(r,null);E(e,n);for(let m=0;m<c.length;m+=1)c[m]&&c[m].m(n,null);Ia(e,t[4].ollamaEmbedModel.model,!0),l||(s=[de(e,"change",t[10]),de(e,"change",t[11])],l=!0)},p(p,A){if(A&8&&a!==(a=p[3]("settings.ollama.recommended"))&&F(r,"label",a),A&4){u=Xt(p[2].filter(p[9]));let m;for(m=0;m<u.length;m+=1){const h=gK(p,u,m);c[m]?c[m].p(h,A):(c[m]=CK(h),c[m].c(),c[m].m(n,null))}for(;m<c.lengt
{text}`,no_notes_retrieved:"No notes retrieved. Maybe lower the similarity threshold.",run_failed:"Failed to run Smart Second Brain (Error: {error}). Please retry.",models_deleted:"The Model {model} has been deleted",no_models:"The model {model} was not found",model_pull_canceled:"Model pull cancelled"},IT={edit:"Edit query and regenerate answer",cancel_edit:"Cancel editing",copy:"Copy Text",regenerate:"Deletes all following Messages and regenerates the answer to the current query",change_assistant_prompt:"Change the initial assistant message",reset_assistant_prompt:"Reset the initial assistant message",retrieving:"Retrieving",reducing:"Reducing {num} Notes",stopped:"Stopped!",user:"You",assistant:"Assistant",save:"Save the Chat to a Note",delete:"Delete the Chat History",toggle_papa:"Chatting with your Notes",toggle_llm:"Chatting with plain LLM",stop:"Stop your Smart Second Brain",send:"Run your Smart Second Brain",retry_error:"An error occured. Retry initialization",reinitialize:"Reinitialize, Settings changed",input_placeholder:"Chat with your Smart Second Brain..."},DT={welcome_msg:"Welcome to your Smart Second Brain! Your personal AI assistant that helps you to find and process information in your notes.",setup:"Setup",test:"Test",privacy_mode_note:"Your assistant will run in privacy mode. That means it is not connected to the internet and is running fully locally by leveraging Ollama.",openai_mode_note:"Your assistant will use third-party services to run. That means you will have to share all your personal information with these services and your Smart Second Brain needs to be connected to the internet to leverage OpenAIs large language models like ChatGPT.",init:"Start your Smart Second Brain",init_label:"Click to Start",ollama:{deamon:{install:"Install Ollama in the terminal:",set_baseurl:"Set the Ollama Base URL",start:"Start Ollama by running this command in the terminal"},app:{download:"Download the App",download_link:"here",extract:"Extract the .zip and start Ollama",run:"Run the setup.exe",test_label:"Test if Ollama is running",set_origins:"In the terminal set Ollama origins to enable streaming responses:",restart:"Restart the Ollama service ",restart_label:"Click Ollamas menu bar icon and then quit",quit:"Quit the Ollama service ",quit_label:"Click Ollamas menu bar icon and then quit",start_origins:"Start Ollama by running this command in the powershell"},test_origins:"Test if the origins are set correctly",install_model:"Install an Ollama Embedding Model.",recommended:"Recommended: ",set_model:"Set your Embedding Model:"},openai:{create_account:"Create an OpenAI ",create_account_link:"Account",create_api_key:"Create an ",create_api_key_link:"API Key",api_key_warning:`> [!Warning] Activate API-Key
> For the API-Key to work you might have to upgrade to an OpenAI paid account. This means depositing at least $5 onto your OpenAI account. This might change in the future.`,paste_api_key:"Paste your key here:",test_api_key:"Test your API Key",api_key_valid:"API Key is valid!"}},MT={enable:"Run on your machine",disable:"Run via Third-Party Services"},xT={excludeff:"Exclude files and folders",excludeff_desc:"These files and folders won't be embedded and not be used for generating answers.",excludeff_add:"Add",excludeff_delete:"Delete from exclude list",advanced:"Advanced Settings",clear:"Clear Plugin Data",clear_desc:"This will delete all plugin data and the vector store data. All chat files inside your vault will not be affected.",clear_modal:{title:"Clear Plugin Data",description:"Are you sure you want to delete the plugin data? Note that only the plugin data and the vector store data will be removed. All chat files inside your vault will not be affected."},clear_label:"Clear",relaunch:"Relaunch",autostart:"Autostart",autostart_desc:"Automatically start the Smart Second Brain when Obsidian starts.",num_docs_retrieve:"Documents to retrieve",num_docs_retrieve_desc:"The maximum amount of documents to retrieve from your vault. Note that documents are not equivalent to notes.",debugging:"Debugging",langsmith_key:"Langsmith API Key",langsmith_key_desc:"Provide a Langsmith API Key if you want to trace and evaluate the internals of your Smart Second Brain.",verbose:"Developer Console logging",verbose_desc:"Enable verbose logging in the Developer Console.",openai:{desc:" ",api_key:"API Key",api_key_desc:"Provide your OpenAI API Key to use OpenAI's large language models.",gen_model:"Chat Model",embed_model:"Embedding Model",model_descriptions:{"gpt-3.5-turbo":"Latest GPT-3.5 Turbo model (16385 Token context window)","gpt-4":"Latest GPT-4 model (8192 Token context window)","gpt-4-32k":"GPT-4 model (32768 Token context window)","gpt-4-turbo":"Latest GPT-4 Turbo model (128000 Token context window)","gpt-4o":"Latest GPT-4 Omni model (128000 Token context window)","text-embedding-3-large":"Latest, most capable embedding model for both english and non-english tasks","text-embedding-3-small":"Increased performance over 2nd generation ada embedding model","text-embedding-ada-002":"Most capable 2rd generation embedding model."}},ollama:{desc:" ",gen_model:"Chat Model",base_url:"Ollama Base URL",base_url_desc:"Set the URL of your Ollama instance.",embed_model:"Embedding Model",recommended:"Recommended",other:"Other",model_descriptions:{llama2:"Llama 2 is a collection of foundation language models ranging from 7B to 70B parameters.","llama2-uncensored":"Uncensored Llama 2 model by George Sung and Jarrad Hope.",mistral:"The 7B model released by Mistral AI, updated to version 0.2.","mistral-openorca":"Mistral OpenOrca is a 7 billion parameter model, fine-tuned on top of the Mistral 7B model using the OpenOrca dataset.",gemma:"Gemma is a family of lightweight, state-of-the-art open models built by Google DeepMind.",mixtral:"A high-quality Mixture of Experts (MoE) model with open weights by Mistral AI.","dolphin-mixtral":"Dolphin Mixtral (32000 Tokens)",phi:"Phi-2: a 2.7B language model by Microsoft Research that demonstrates outstanding reasoning and language understanding capabilities.","nomic-embed-text":"A high-performing open embedding model with a large token context window.","mxbai-embed-large":"State-of-the-art large embedding model from mixedbread.ai."}}},JT={initialize:"Start your Smart Second Brain",indexing_vault:"Indexing vault",time_left_minutes:"About {minutes}min {seconds}s remaining...",time_left_seconds:"About {seconds}s remaining...",assistant_language:"Assistant language",pause_indexing:"Pause Indexing",resume_indexing:"Resume Indexing",cancel_indexing:"Cancel Indexing",retry_initialization:"Retry Initialization",mode_changed:`Reinitialize Smart Second Brain
with `,reinitialize:"Reinitialize Smart Second Brain",chat_via:"Chat via {model}",chatview:"Comfy Chatview",similarity_threshold:"Similarity",creativity:"Creativity",settings_changed:`Settings changed.
Reinitialize Smart Second Brain.`,open:"Open quick settings",close:"Close quick settings",error:{install_model:"Install {model} model first",other:`An error occured.
Please retry initialization...`}},OT={creativity:"Adjusts the level of originality in the model's outputs to suit your preference.",similarity:"How similar the retrieved documents should be to the user query."},PT={general:NT,ribbon:LT,cmd:TT,modal:kT,init_third_party_modal:UT,notice:_T,chat:IT,onboarding:DT,incognito_toggle:MT,settings:xT,quick_settings:JT,tooltip:OT},zT={delete:"Eliminar",install:"Instalar"},jT={chat:"Abrir Chat S2B"},qT={chat:"Abrir Chat",pull_model:"Obtener Modelo Ollama",remove_model:"Eliminar Modelo Ollama"},$T={dont_show:"No mostrar esto de nuevo",cancel:"Cancelar",confirm:"Confirmar",pull_model_name:"Obtener Modelo Ollama",pull_model_desc:"Instalar un modelo desde el registro de Ollama",remove:{name:"Eliminar Modelo Ollama",desc:"Eliminar un modelo instalado de tu sistema",success:"Modelo eliminado con éxito",error:"Error al eliminar el modelo. El modelo podría no estar instalado"}},ek={title:"Ejecutar mediante Servicios de Terceros",description:"¿Estás seguro de que quieres ejecutar mediante servicios de terceros? Tus datos personales serán compartidos con servicios de terceros como OpenAI."},tk={still_running:"Smart Second Brain sigue en ejecución. Por favor, espera.",still_indexing:"Smart Second Brain sigue indexando. Por favor, espera.",ollama_not_running:"Por favor, asegúrate de que Ollama está en ejecución antes de inicializar Smart Second Brain.",ollama_gen_model:"Modelo de Ollama no instalado. Por favor, instala el modelo antes de inicializar Smart Second Brain.",ollama_embed_model:"Modelo de Ollama no instalado. Por favor, instala el modelo antes de inicializar Smart Second Brain.",openai_key:"Por favor, asegúrate de que tu clave API de OpenAI es válida antes de inicializar Smart Second Brain.",failed:"Fallo al inicializar Smart Second Brain (Error: {error}). Por favor, reintenta.",failed_indexing:"Fallo al indexar notas en tu Smart Second Brain. Por favor, reintenta.",done:"Smart Second Brain inicializado.",error:"Ocurrió un error. Por favor, espera a que se resuelva el error.",not_initialized:"Smart Second Brain no inicializado. Por favor, inicializa primero.",plugin_data_cleared:"Datos del complemento eliminados.",api_key_invalid:"¡La clave API no es válida!",error_pulling_model:"Fallo al obtener el modelo de Ollama (Error: {error}). Por favor, reintenta.",copied_to_clipboard:`Copiado al portapapeles:
{text}`,no_notes_retrieved:"No se recuperaron notas. Quizás reduzca el umbral de similitud.",run_failed:"Fallo al ejecutar Smart Second Brain (Error: {error}). Por favor, reintenta.",models_deleted:"El modelo {model} ha sido eliminado",no_models:"El modelo {model} no fue encontrado",model_pull_canceled:"Cancelación de la obtención del modelo"},rk={edit:"Editar consulta y regenerar respuesta",cancel_edit:"Cancelar edición",copy:"Copiar texto",regenerate:"Elimina todos los mensajes siguientes y regenera la respuesta a la consulta actual",change_assistant_prompt:"Cambiar el mensaje inicial del asistente",reset_assistant_prompt:"Restablecer el mensaje inicial del asistente",retrieving:"Recuperando",reducing:"Reduciendo {num} notas",stopped:"¡Detenido!",user:"Tú",assistant:"Asistente",save:"Guardar el chat en una nota",delete:"Eliminar el historial de chat",toggle_papa:"Chatear con tus notas",toggle_llm:"Chatear con LLM simple",stop:"Detener tu Smart Second Brain",send:"Ejecutar tu Smart Second Brain",retry_error:"Ocurrió un error. Reintentar inicialización",reinitialize:"Reiniciar, ajustes cambiados",input_placeholder:"Chatea con tu Smart Second Brain..."},ak={welcome_msg:"¡Bienvenido a tu Smart Second Brain! Tu asistente personal de inteligencia artificial que te ayuda a encontrar y procesar información en tus notas.",setup:"Configuración",test:"Prueba",privacy_mode_note:"Tu asistente funcionará en modo privacidad. Eso significa que no está conectado a internet y funciona completamente de manera local utilizando Ollama.",openai_mode_note:"Tu asistente utilizará servicios de terceros para funcionar. Eso significa que tendrás que compartir toda tu información personal con estos servicios y tu Smart Second Brain necesita estar conectado a internet para aprovechar los modelos de lenguaje de gran escala de OpenAI, como ChatGPT.",init:"Inicia tu Smart Second Brain",init_label:"Haz clic para comenzar",ollama:{deamon:{install:"Instala Ollama en la terminal:",set_baseurl:"Establece la URL base de Ollama",start:"Inicia Ollama ejecutando este comando en la terminal"},app:{download:"Descargar la aplicación",download_link:"aquí",extract:"Extrae el .zip e inicia Ollama",run:"Ejecuta el setup.exe",test_label:"Prueba si Ollama está en funcionamiento",set_origins:"En la terminal, establece los orígenes de Ollama para habilitar respuestas en streaming:",restart:"Reinicia el servicio de Ollama",restart_label:"Haz clic en el icono de la barra de menús de Ollama y luego cierra",quit:"Cierra el servicio de Ollama",quit_label:"Haz clic en el icono de la barra de menús de Ollama y luego cierra",start_origins:"Inicia Ollama ejecutando este comando en el powershell"},test_origins:"Prueba si los orígenes están configurados correctamente",install_model:"Instala un Modelo de Embedding de Ollama.",recommended:"Recomendado:",set_model:"Configura tu Modelo de Embedding :"},openai:{create_account:"Crea una cuenta de OpenAI",create_account_link:"Cuenta",create_api_key:"Crea una",create_api_key_link:"Clave API",api_key_warning:`> [!Advertencia] Activa la Clave API
> Para que la Clave API funcione, es posible que tengas que actualizar a una cuenta de pago de OpenAI. Esto implica depositar al menos $5 en tu cuenta de OpenAI. Esto podría cambiar en el futuro.`,paste_api_key:"Pega tu clave aquí:",test_api_key:"Prueba tu Clave API",api_key_valid:"¡La Clave API es válida!"}},nk={enable:"Ejecutar en tu máquina",disable:"Ejecutar mediante Servicios de Terceros"},ik={excludeff:"Excluir archivos y carpetas",excludeff_desc:"Estos archivos y carpetas no se incrustarán y no se utilizarán para generar respuestas.",excludeff_add:"Agregar",excludeff_delete:"Eliminar de la lista de excluidos",advanced:"Configuración Avanzada",clear:"Limpiar Datos del Complemento",clear_desc:"Esto eliminará todos los datos del complemento y los datos del almacén de vectores. Todos los archivos de chat dentro de tu bóveda no se verán afectados.",clear_modal:{title:"Limpiar Datos del Complemento",description:"¿Estás seguro de que quieres eliminar los datos del complemento? Ten en cuenta que solo se eliminarán los datos del complemento y los datos del almacén de vectores. Todos los archivos de chat dentro de tu bóveda no se verán afectados."},clear_label:"Limpiar",relaunch:"Reiniciar",autostart:"Inicio Automático",autostart_desc:"Iniciar automáticamente el Smart Second Brain cuando Obsidian se inicia.",num_docs_retrieve:"Documentos a recuperar",num_docs_retrieve_desc:"La cantidad máxima de documentos a recuperar de tu bóveda. Ten en cuenta que los documentos no son equivalentes a las notas.",debugging:"Depuración",langsmith_key:"Clave API de Langsmith",langsmith_key_desc:"Proporciona una Clave API de Langsmith si deseas rastrear y evaluar los componentes internos de tu Smart Second Brain.",verbose:"Registro de la Consola del Desarrollador",verbose_desc:"Habilitar el registro detallado en la Consola del Desarrollador.",openai:{desc:" ",api_key:"Clave API",api_key_desc:"Proporciona tu Clave API de OpenAI para usar los modelos de lenguaje de gran escala de OpenAI.",gen_model:"Modelo de Chat",embed_model:"Modelo de Embedding ",model_descriptions:{"gpt-3.5-turbo":"Modelo GPT-3.5 Turbo más reciente (ventana de contexto de 16385 tokens)","gpt-4":"Modelo GPT-4 más reciente (ventana de contexto de 8192 tokens)","gpt-4-32k":"Modelo GPT-4 (ventana de contexto de 32768 tokens)","gpt-4-turbo":"Modelo GPT-4 Turbo más reciente (ventana de contexto de 128000 tokens)","gpt-4o":"Último modelo GPT-4 Omni (ventana de contexto de 128000 tokens)","text-embedding-3-large":"Modelo de Embedding más reciente y capaz para tareas tanto en inglés como en otros idiomas","text-embedding-3-small":"Rendimiento mejorado sobre el modelo de Embedding ada de 2da generación","text-embedding-ada-002":"Modelo de Embedding de 2da generación más capaz."}},ollama:{desc:" ",gen_model:"Modelo de Chat",base_url:"URL Base de Ollama",base_url_desc:"Establece la URL de tu instancia de Ollama.",embed_model:"Modelo de Embedding",recommended:"Recomendado",other:"Otro",model_descriptions:{llama2:"Llama 2 es una colección de modelos de lenguaje base que varían de 7B a 70B de parámetros.","llama2-uncensored":"Modelo Llama 2 sin censura por George Sung y Jarrad Hope.",mistral:"El modelo de 7B liberado por Mistral AI, actualizado a la versión 0.2.","mistral-openorca":"Mistral OpenOrca es un modelo de 7 mil millones de parámetros, ajustado sobre el modelo Mistral 7B utilizando el conjunto de datos OpenOrca.",gemma:"Gemma es una familia de modelos abiertos ligeros y de última generación construidos por Google DeepMind.",mixtral:"Un modelo de Mezcla de Expertos (MoE) de alta calidad con pesos abiertos por Mistral AI.","dolphin-mixtral":"Dolphin Mixtral (32000 Tokens)",phi:"Phi-2: un modelo de lenguaje de 2.7B de Microsoft Research que demuestra capacidades sobresalientes de razonamiento y comprensión del lenguaje.","nomic-embed-text":"Un modelo de Embedding abierto de alto rendimiento con una amplia ventana de contexto de tokens.","mxbai-embed-large":"Modelo grande de Embedding de última generación de mixedbread.ai."}}},lk={initial
con `,reinitialize:"Reiniciar Smart Second Brain",chat_via:"Chatear mediante {model}",chatview:"Vista de chat cómoda",similarity_threshold:"Similitud",creativity:"Creatividad",settings_changed:`Configuración cambiada.
Reiniciar Smart Second Brain.`,open:"Abrir configuración rápida",close:"Cerrar configuración rápida",error:{install_model:"Primero instala el modelo {model}",other:`Ocurrió un error.
Por favor, reintenta la inicialización...`}},sk={creativity:"Ajusta el nivel de originalidad en las respuestas del modelo según tu preferencia.",similarity:"Qué tan similares deben ser los documentos recuperados a la consulta del usuario."},ok={general:zT,ribbon:jT,cmd:qT,modal:$T,init_third_party_modal:ek,notice:tk,chat:rk,onboarding:ak,incognito_toggle:nk,settings:ik,quick_settings:lk,tooltip:sk},dk={delete:"Sil",install:"Kur"},uk={chat:"S2B Sohbetini Aç"},pk={chat:"Sohbeti Aç",pull_model:"Ollama Modelini Çek",remove_model:"Ollama Modelini Kaldır"},ck={dont_show:"Bunu bir daha gösterme",cancel:"İptal",confirm:"Onayla",pull_model_name:"Ollama Modelini Çek",pull_model_desc:"Ollama kayıt defterinden bir model kur",remove:{name:"Ollama Modelini Kaldır",desc:"Kurulu bir modeli sisteminizden kaldırın",success:"Model başarıyla kaldırıldı",error:"Model kaldırılamadı. Model kurulu olmayabilir"}},mk={title:"Üçüncü Parti Hizmetler Üzerinden Çalıştır",description:"Üçüncü parti hizmetler üzerinden çalıştırmak istediğinizden emin misiniz? Kişisel verileriniz OpenAI gibi üçüncü parti hizmetlerle paylaşılacaktır."},gk={still_running:"Smart Second Brain hala çalışıyor. Lütfen bekleyin.",still_indexing:"Smart Second Brain hala dizinliyor. Lütfen bekleyin.",ollama_not_running:"Smart Second Brain'i başlatmadan önce Ollama'nın çalıştığından emin olun.",ollama_gen_model:"Ollama modeli kurulu değil. Smart Second Brain'i başlatmadan önce lütfen modeli kurun.",ollama_embed_model:"Ollama modeli kurulu değil. Smart Second Brain'i başlatmadan önce lütfen modeli kurun.",openai_key:"Smart Second Brain'i başlatmadan önce OpenAI API Anahtarınızın geçerli olduğundan emin olun.",failed:"Smart Second Brain başlatılamadı (Hata: {error}). Lütfen tekrar deneyin.",failed_indexing:"Notlarınız smart second brain'e dizinlenemedi. Lütfen tekrar deneyin.",done:"Smart Second Brain başlatıldı.",error:"Bir hata oluştu. Lütfen hatanın düzelmesini bekleyin.",not_initialized:"Smart Second Brain başlatılmadı. Lütfen önce başlatın.",plugin_data_cleared:"Eklenti verileri temizlendi.",api_key_invalid:"API Anahtarı geçersiz!",error_pulling_model:"Ollama'dan model çekilemedi (Hata: {error}). Lütfen tekrar deneyin.",copied_to_clipboard:`Panoya kopyalandı:
{text}`,no_notes_retrieved:"Hiçbir not alınamadı. Belki benzerlik eşiğini düşürün.",run_failed:"Smart Second Brain çalıştırılamadı (Hata: {error}). Lütfen tekrar deneyin.",models_deleted:"{model} Modeli silindi",no_models:"{model} Modeli bulunamadı",model_pull_canceled:"Model çekme iptal edildi"},Ak={edit:"Sorguyu düzenle ve cevabı yeniden oluştur",cancel_edit:"Düzenlemeyi iptal et",copy:"Metni Kopyala",regenerate:"Tüm sonraki mesajları siler ve mevcut sorguya cevabı yeniden oluşturur",change_assistant_prompt:"İlk asistan mesajını değiştir",reset_assistant_prompt:"İlk asistan mesajını sıfırla",retrieving:"Alınıyor",reducing:"{num} Not Azaltılıyor",stopped:"Durduruldu!",user:"Siz",assistant:"Asistan",save:"Sohbeti Not olarak kaydet",delete:"Sohbet Geçmişini Sil",toggle_papa:"Notlarınızla Sohbet Ediliyor",toggle_llm:"Sade LLM ile Sohbet Ediliyor",stop:"Smart Second Brain'inizi Durdurun",send:"Smart Second Brain'inizi Çalıştırın",retry_error:"Bir hata oluştu. Başlatmayı tekrar deneyin",reinitialize:"Ayarlar değişti, Yeniden Başlat",input_placeholder:"Smart Second Brain'inizle sohbet edin..."},hk={welcome_msg:"Smart Second Brain'inize hoş geldiniz! Notlarınızdaki bilgileri bulmaya ve işlemeye yardımcı olan kişisel AI asistanınız.",setup:"Kurulum",test:"Test",privacy_mode_note:"Asistanınız gizlilik modunda çalışacak. Bu, internete bağlı olmadığı ve Ollama'yı kullanarak tamamen yerel olarak çalıştığı anlamına gelir.",openai_mode_note:"Asistanınız çalışmak için üçüncü parti hizmetleri kullanacak. Bu, tüm kişisel bilgilerinizi bu hizmetlerle paylaşmanız gerektiği ve Smart Second Brain'inizin ChatGPT gibi OpenAI'ın büyük dil modellerini kullanabilmek için internete bağlı olması gerektiği anlamına gelir.",init:"Smart Second Brain'inizi başlatın",init_label:"Başlatmak için tıklayın",ollama:{deamon:{install:"Ollama'yı terminal üzerinden kurun:",set_baseurl:"Ollama Temel URL'sini Ayarlayın",start:"Bu komutu terminal üzerinden çalıştırarak Ollama'yı başlatın"},app:{download:"Uygulamayı İndirin",download_link:"buradan",extract:".zip'i çıkarın ve Ollama'yı başlatın",run:"setup.exe'yi çalıştırın",test_label:"Ollama'nın çalıştığını test edin",set_origins:"Streaming yanıtları etkinleştirmek için terminal üzerinden Ollama kökenlerini ayarlayın:",restart:"Ollama servisini yeniden başlatın",restart_label:"Ollama menü çubuğu simgesine tıklayın ve sonra Çık'a basın",quit:"Ollama servisinden çıkın",quit_label:"Ollama menü çubuğu simgesine tıklayın ve sonra Çık'a basın",start_origins:"Bu komutu powershell üzerinden çalıştırarak Ollama'yı başlatın"},test_origins:"Kökenlerin doğru şekilde ayarlandığını test edin",install_model:"Bir Ollama Embedding Modeli kurun.",recommended:"Önerilen: ",set_model:"Embedding Modelinizi ayarlayın:"},openai:{create_account:"Bir OpenAI ",create_account_link:"Hesabı Oluşturun",create_api_key:"Bir ",create_api_key_link:"API Anahtarı Oluşturun",api_key_warning:`> [!Warning] API Anahtarını Etkinleştir
> API Anahtarının çalışması için OpenAI ücretli hesabına yükseltmeniz gerekebilir. Bu, en az 5$ OpenAI hesabınıza yatırmanız gerektiği anlamına gelir. Bu gelecekte değişebilir.`,paste_api_key:"Anahtarınızı buraya yapıştırın:",test_api_key:"API Anahtarınızı test edin",api_key_valid:"API Anahtarı geçerli!"}},Bk={enable:"Kendi makinenizde Çalıştır",disable:"Üçüncü Parti Hizmetler Üzerinden Çalıştır"},Ck={excludeff:"Dosya ve klasörleri hariç tut",excludeff_desc:"Bu dosya ve klasörler gömülmeyecek ve cevaplar üretilirken kullanılmayacaktır.",excludeff_add:"Ekle",excludeff_delete:"Hariç tutma listesinden kaldır",advanced:"Gelişmiş Ayarlar",clear:"Eklenti Verilerini Temizle",clear_desc:"Bu, tüm eklenti verilerini ve vektör depolama verilerini silecektir. Arşiviniz içindeki tüm sohbet dosyaları etkilenmeyecektir.",clear_modal:{title:"Eklenti Verilerini Temizle",description:"Eklenti verilerini silmek istediğinizden emin misiniz? Sadece eklenti verileri ve vektör depolama verileri kaldırılacaktır. Arşiviniz içindeki tüm sohbet dosyaları etkilenmeyecektir."},clear_label:"Temizle",relaunch:"Yeniden Başlat",autostart:"Otomatik Başlat",autostart_desc:"Obsidian başladığında Smart Second Brain'i otomatik olarak başlatın.",num_docs_retrieve:"Alınacak Doküman Sayısı",num_docs_retrieve_desc:"Arşivinizden alınacak maksimum doküman sayısı. Dokümanlar notlara eşdeğer değildir.",debugging:"Hata Ayıklama",langsmith_key:"Langsmith API Anahtarı",langsmith_key_desc:"Smart Second Brain'inizin iç işleyişini izlemek ve değerlendirmek istiyorsanız bir Langsmith API Anahtarı sağlayın.",verbose:"Geliştirici Konsolu günlüğü",verbose_desc:"Geliştirici Konsolunda ayrıntılı günlüğü etkinleştirin.",openai:{desc:" ",api_key:"API Anahtarı",api_key_desc:"OpenAI'ın büyük dil modellerini kullanmak için OpenAI API Anahtarınızı sağlayın.",gen_model:"Sohbet Modeli",embed_model:"Embedding Modeli",model_descriptions:{"gpt-3.5-turbo":"En son GPT-3.5 Turbo modeli (16385 Token bağlam penceresi)","gpt-4":"En son GPT-4 modeli (8192 Token bağlam penceresi)","gpt-4-32k":"GPT-4 modeli (32768 Token bağlam penceresi)","gpt-4-turbo":"En son GPT-4 Turbo modeli (128000 Token bağlam penceresi)","gpt-4o":"En son GPT-4 Omni modeli (128000 Token bağlam penceresi)","text-embedding-3-large":"Hem İngilizce hem de İngilizce olmayan görevler için en son ve en yetenekli embedding modeli","text-embedding-3-small":"2. nesil 'ada' embedding modeline göre artırılmış performans","text-embedding-ada-002":"En yetenekli 2. nesil embedding modeli."}},ollama:{desc:" ",gen_model:"Sohbet Modeli",base_url:"Ollama Temel URL'si",base_url_desc:"Ollama örneğinizin URL'sini ayarlayın.",embed_model:"Embedding Modeli",recommended:"Önerilen",other:"Diğer",model_descriptions:{llama2:"Llama 2, 7B ila 70B parametreli çeşitli temel dil modellerinden oluşur.","llama2-uncensored":"George Sung ve Jarrad Hope tarafından sansürsüz Llama 2 modeli.",mistral:"Mistral AI tarafından yayınlanan ve 0.2 sürümüne güncellenen 7B model.","mistral-openorca":"OpenOrca veri kümesi kullanılarak Mistral 7B modelinin üzerine ince ayar yapılmış 7 milyar parametreli Mistral OpenOrca modeli.",gemma:"Google DeepMind tarafından oluşturulan, son derece gelişmiş açık kaynaklı model ailesi.",mixtral:"Mistral AI tarafından oluşturulan, yüksek kaliteli, açık ağırlıklı, 'Mixture of Experts' (MoE) modeli.","dolphin-mixtral":"Dolphin Mixtral (32000 Token)",phi:"Microsoft Araştırma tarafından geliştirilen, üstün akıl yürütme ve dil anlama yetenekleri sergileyen 2,7B dil modeli.","nomic-embed-text":"Geniş bir token bağlam penceresi ile yüksek performanslı açık embedding modeli.","mxbai-embed-large":"Mixedbread.ai'den son teknoloji büyük embedding modeli."}}},wk={initialize:"Smart Second Brain'inizi başlatın",indexing_vault:"Arşiv dizinleniyor",time_left_minutes:"Yaklaşık {minutes}dk {seconds}sn kaldı...",time_left_seconds:"Yaklaşık {seconds}sn kaldı.
Smart Second Brain'i Yeniden Başlat`,reinitialize:"Smart Second Brain'i Yeniden Başlat",chat_via:"{model} üzerinden sohbet et",chatview:"Rahat Sohbet Görünümü",similarity_threshold:"Benzerlik",creativity:"Yaratıcılık",settings_changed:`Ayarlar değişti.
Smart Second Brain'i Yeniden Başlat.`,open:"Hızlı ayarları aç",close:"Hızlı ayarları kapat",error:{install_model:"Önce {model} modelini kurun",other:`Bir hata oluştu.
Lütfen başlatmayı tekrar deneyin...`}},bk={creativity:"Modelin çıktılarındaki özgünlük seviyesini tercihlerinize göre ayarlar.",similarity:"Alınan dokümanların kullanıcı sorgusuyla ne kadar benzer olması gerektiğini belirler."},Kk={general:dk,ribbon:uk,cmd:pk,modal:ck,init_third_party_modal:mk,notice:gk,chat:Ak,onboarding:hk,incognito_toggle:Bk,settings:Ck,quick_settings:wk,tooltip:bk},fk={delete:"Supprimer",install:"Installer"},Qk={chat:"Ouvrir le chat S2B"},Wk={chat:"Ouvrir le chat",pull_model:"Récupérer le modèle Ollama",remove_model:"Supprimer le modèle Ollama"},vk={dont_show:"Ne plus afficher ceci",cancel:"Annuler",confirm:"Confirmer",pull_model_name:"Récupérer le modèle Ollama",pull_model_desc:"Installer un modèle depuis le registre Ollama",remove:{name:"Supprimer le modèle Ollama",desc:"Supprimer un modèle installé de votre système",success:"Modèle supprimé avec succès",error:"Échec de la suppression du modèle. Le modèle n'est peut-être pas installé"}},Fk={title:"Exécuter via des services tiers",description:"Êtes-vous sûr de vouloir exécuter via des tiers ? Vos données personnelles seront partagées avec des services tiers comme OpenAI."},yk={still_running:"Smart Second Brain est toujours en cours d'exécution. Veuillez patienter.",still_indexing:"Smart Second Brain est toujours en cours d'indexation. Veuillez patienter.",ollama_not_running:"Veuillez vous assurer qu'Ollama est en cours d'exécution avant d'initialiser Smart Second Brain.",ollama_gen_model:"Modèle Ollama non installé. Veuillez installer le modèle avant d'initialiser Smart Second Brain.",ollama_embed_model:"Modèle Ollama non installé. Veuillez installer le modèle avant d'initialiser Smart Second Brain.",openai_key:"Veuillez vous assurer que votre clé API OpenAI est valide avant d'initialiser Smart Second Brain.",failed:"Échec de l'initialisation de Smart Second Brain (Erreur : {error}). Veuillez réessayer.",failed_indexing:"Échec de l'indexation des notes dans votre Smart Second Brain. Veuillez réessayer.",done:"Smart Second Brain initialisé.",error:"Une erreur est survenue. Veuillez attendre que l'erreur soit résolue.",not_initialized:"Smart Second Brain non initialisé. Veuillez initialiser d'abord.",plugin_data_cleared:"Données du plugin effacées.",api_key_invalid:"La clé API n'est pas valide !",error_pulling_model:"Échec de la récupération du modèle depuis Ollama (Erreur : {error}). Veuillez réessayer.",copied_to_clipboard:`Copié dans le presse-papiers :
{text}`,no_notes_retrieved:"Aucune note récupérée. Peut-être baisser le seuil de similarité.",run_failed:"Échec de l'exécution de Smart Second Brain (Erreur : {error}). Veuillez réessayer.",models_deleted:"Le modèle {model} a été supprimé",no_models:"Le modèle {model} n'a pas été trouvé",model_pull_canceled:"Annulation de la récupération du modèle"},Rk={edit:"Modifier la requête et régénérer la réponse",cancel_edit:"Annuler la modification",copy:"Copier le texte",regenerate:"Supprimer tous les messages suivants et régénérer la réponse à la requête actuelle",change_assistant_prompt:"Modifier le message initial de l'assistant",reset_assistant_prompt:"Réinitialiser le message initial de l'assistant",retrieving:"Récupération",reducing:"Réduction de {num} notes",stopped:"Arrêté !",user:"Vous",assistant:"Assistant",save:"Sauvegarder le chat dans une note",delete:"Supprimer l'historique du chat",toggle_papa:"Discuter avec vos notes",toggle_llm:"Discuter avec un LLM simple",stop:"Arrêter votre Smart Second Brain",send:"Exécuter votre Smart Second Brain",retry_error:"Une erreur est survenue. Réessayez l'initialisation",reinitialize:"Réinitialiser, les paramètres ont changé",input_placeholder:"Discutez avec votre Smart Second Brain..."},Ek={welcome_msg:"Bienvenue dans votre Smart Second Brain ! Votre assistant personnel IA qui vous aide à trouver et traiter les informations dans vos notes.",setup:"Configuration",test:"Test",privacy_mode_note:"Votre assistant fonctionnera en mode privé. Cela signifie qu'il n'est pas connecté à Internet et fonctionne entièrement localement en utilisant Ollama.",openai_mode_note:"Votre assistant utilisera des services tiers pour fonctionner. Cela signifie que vous devrez partager toutes vos informations personnelles avec ces services et que votre Smart Second Brain doit être connecté à Internet pour utiliser les grands modèles de langage d'OpenAI comme ChatGPT.",init:"Démarrer votre Smart Second Brain",init_label:"Cliquez pour démarrer",ollama:{deamon:{install:"Installer Ollama dans le terminal :",set_baseurl:"Définir l'URL de base d'Ollama",start:"Démarrer Ollama en exécutant cette commande dans le terminal"},app:{download:"Télécharger l'application",download_link:"ici",extract:"Extraire le fichier .zip et démarrer Ollama",run:"Exécuter le setup.exe",test_label:"Tester si Ollama fonctionne",set_origins:"Dans le terminal, définir les origines d'Ollama pour activer les réponses en streaming :",restart:"Redémarrer le service Ollama",restart_label:"Cliquez sur l'icône de la barre de menus d'Ollama puis quittez",quit:"Quitter le service Ollama",quit_label:"Cliquez sur l'icône de la barre de menus d'Ollama puis quittez",start_origins:"Démarrer Ollama en exécutant cette commande dans le powershell"},test_origins:"Tester si les origines sont correctement définies",install_model:"Installer un modèle d'encodage Ollama.",recommended:"Recommandé : ",set_model:"Définir votre modèle d'encodage :"},openai:{create_account:"Créer un ",create_account_link:"compte OpenAI",create_api_key:"Créer une ",create_api_key_link:"clé API",api_key_warning:`> [!Avertissement] Activer la clé API
> Pour que la clé API fonctionne, vous devrez peut-être passer à un compte payant OpenAI. Cela signifie déposer au moins 5 $ sur votre compte OpenAI. Cela pourrait changer à l'avenir.`,paste_api_key:"Collez votre clé ici :",test_api_key:"Tester votre clé API",api_key_valid:"La clé API est valide !"}},Gk={enable:"Exécuter sur votre machine",disable:"Exécuter via des services tiers"},Sk={excludeff:"Exclure fichiers et dossiers",excludeff_desc:"Ces fichiers et dossiers ne seront pas intégrés et ne seront pas utilisés pour générer des réponses.",excludeff_add:"Ajouter",excludeff_delete:"Supprimer de la liste d'exclusion",advanced:"Paramètres avancés",clear:"Effacer les données du plugin",clear_desc:"Cela supprimera toutes les données du plugin et les données du magasin vectoriel. Tous les fichiers de discussion dans votre coffre ne seront pas affectés.",clear_modal:{title:"Effacer les données du plugin",description:"Êtes-vous sûr de vouloir supprimer les données du plugin ? Notez que seules les données du plugin et les données du magasin vectoriel seront supprimées. Tous les fichiers de discussion dans votre coffre ne seront pas affectés."},clear_label:"Effacer",relaunch:"Relancer",autostart:"Démarrage automatique",autostart_desc:"Démarrer automatiquement le Smart Second Brain lorsque Obsidian démarre.",num_docs_retrieve:"Documents à récupérer",num_docs_retrieve_desc:"Le nombre maximal de documents à récupérer de votre coffre. Notez que les documents ne sont pas équivalents aux notes.",debugging:"Débogage",langsmith_key:"Clé API Langsmith",langsmith_key_desc:"Fournissez une clé API Langsmith si vous souhaitez tracer et évaluer les mécanismes internes de votre Smart Second Brain.",verbose:"Journalisation détaillée de la console développeur",verbose_desc:"Activer la journalisation détaillée dans la console développeur.",openai:{desc:" ",api_key:"Clé API",api_key_desc:"Fournissez votre clé API OpenAI pour utiliser les grands modèles de langage d'OpenAI.",gen_model:"Modèle de discussion",embed_model:"Modèle d'encodage",model_descriptions:{"gpt-3.5-turbo":"Dernier modèle GPT-3.5 Turbo (fenêtre de contexte de 16385 tokens)","gpt-4":"Dernier modèle GPT-4 (fenêtre de contexte de 8192 tokens)","gpt-4-32k":"Modèle GPT-4 (fenêtre de contexte de 32768 tokens)","gpt-4-turbo":"Dernier modèle GPT-4 Turbo (fenêtre de contexte de 128000 tokens)","gpt-4o":"Dernier modèle GPT-4 Omni (fenêtre de contexte de 128000 jetons)","text-embedding-3-large":"Dernier modèle d'encodage le plus capable pour les tâches en anglais et non anglais","text-embedding-3-small":"Performances accrues par rapport au modèle d'encodage ada de 2ème génération","text-embedding-ada-002":"Modèle d'encodage le plus capable de 2ème génération."}},ollama:{desc:" ",gen_model:"Modèle de discussion",base_url:"URL de base d'Ollama",base_url_desc:"Définir l'URL de votre instance Ollama.",embed_model:"Modèle d'encodage",recommended:"Recommandé",other:"Autre",model_descriptions:{llama2:"Llama 2 est une collection de modèles de langage de base allant de 7B à 70B de paramètres.","llama2-uncensored":"Modèle Llama 2 non censuré par George Sung et Jarrad Hope.",mistral:"Le modèle 7B publié par Mistral AI, mis à jour en version 0.2.","mistral-openorca":"Mistral OpenOrca est un modèle de 7 milliards de paramètres, affiné sur le modèle Mistral 7B en utilisant le dataset OpenOrca.",gemma:"Gemma est une famille de modèles ouverts, légers et de pointe développés par Google DeepMind.",mixtral:"Un modèle de haute qualité Mixture of Experts (MoE) avec poids ouverts par Mistral AI.","dolphin-mixtral":"Dolphin Mixtral (32000 Tokens)",phi:"Phi-2 : un modèle de langage de 2,7 milliards de paramètres par Microsoft Research qui démontre des capacités exceptionnelles de raisonnement et de compréhension du langage.","nomic-embed-text":"Un modèle d'encodage ouvert performant avec une large fenêtre de contexte de tokens.","mxbai-embed-large":"Modèle d'encodage large de pointe de mixedbread.ai."}}},Zk={
avec `,reinitialize:"Réinitialiser Smart Second Brain",chat_via:"Discuter via {model}",chatview:"Vue de chat confortable",similarity_threshold:"Similarité",creativity:"Créativité",settings_changed:`Paramètres modifiés.
Réinitialiser Smart Second Brain.`,open:"Ouvrir les paramètres rapides",close:"Fermer les paramètres rapides",error:{install_model:"Installer d'abord le modèle {model}",other:`Une erreur est survenue.
Veuillez réessayer l'initialisation...`}},Xk={creativity:"Ajuste le niveau d'originalité dans les sorties du modèle selon votre préférence.",similarity:"À quel point les documents récupérés doivent être similaires à la requête de l'utilisateur."},Hk={general:fk,ribbon:Qk,cmd:Wk,modal:vk,init_third_party_modal:Fk,notice:yk,chat:Rk,onboarding:Ek,incognito_toggle:Gk,settings:Sk,quick_settings:Zk,tooltip:Xk},Vk={delete:"删除",install:"安装"},Yk={chat:"打开 S2B 聊天"},Nk={chat:"打开聊天窗口",pull_model:"拉取 Ollama 模型",remove_model:"移除 Ollama 模型"},Lk={dont_show:"不再显示此信息",cancel:"取消",confirm:"确认",pull_model_name:"拉取 Ollama 模型",pull_model_desc:"安装在 Ollama 注册的模型",remove:{name:"移除 Ollama 模型",desc:"从系统中移除已安装的模型",success:"模型已成功移除",error:"移除模型失败,模型可能未安装"}},Tk={title:"通过第三方服务运行",description:"您确定要使用第三方服务吗?您的个人数据将与 OpenAI 等第三方服务共享。"},kk={still_running:"Smart Second Brain 仍在运行。请稍候。",still_indexing:"Smart Second Brain 仍在执行索引。请稍候。",ollama_not_running:"在初始化 Smart Second Brain 之前,请确保 Ollama 正在运行。",ollama_gen_model:"Ollama 对话生成模型未安装。请在初始化 Smart Second Brain 之前安装模型。",ollama_embed_model:"Ollama 嵌入模型未安装。请在初始化 Smart Second Brain 之前安装模型。",openai_key:"在初始化 Smart Second Brain 之前,请确保您的 OpenAI API 密钥有效。",failed:"初始化 Smart Second Brain 失败 (Error: {error}) 。请重试。",failed_indexing:"将笔记索引到 Smart Second Brain 失败。请重试。",done:"Smart Second Brain 初始化成功。",error:"发生错误。请等待错误解决。",not_initialized:"Smart Second Brain 未初始化。请先初始化。",plugin_data_cleared:"插件数据已清除。",api_key_invalid:"API Key 无效!",error_pulling_model:"从 Ollama 拉取模型失败 (Error: {error}) 。请重试。",copied_to_clipboard:`已复制到剪贴板:
{text}`,no_notes_retrieved:"未检索到笔记。建议降低相似度阈值。",run_failed:"运行 Smart Second Brain 失败 (Error: {error}) 。请重试。",models_deleted:"模型 {model} 已被删除",no_models:"未找到模型 {model}",model_pull_canceled:"模型拉取已取消"},Uk={edit:"编辑问题并重生成回答",cancel_edit:"取消编辑",copy:"复制文本",regenerate:"删除所有后续聊天记录并重生成当前问题的回答",change_assistant_prompt:"更改初始助手消息 (initial assistant message)",reset_assistant_prompt:"重置初始助手消息 (initial assistant message)",retrieving:"正在检索",reducing:"正在化简 {num} 条笔记",stopped:"已停止!",user:"您",assistant:"助手",save:"将聊天记录保存到笔记",delete:"删除聊天记录",toggle_papa:"与您的笔记聊天",toggle_llm:"仅与 LLM 聊天",stop:"停止 Smart Second Brain",send:"运行 Smart Second Brain",retry_error:"发生了一个错误。重试初始化",reinitialize:"重新初始化,设置已更改",input_placeholder:"与 Smart Second Brain 聊天..."},_k={welcome_msg:"欢迎使用 Smart Second Brain!您的个人 AI 助手,帮助您在笔记中查找和处理信息。",setup:"设置",test:"测试",privacy_mode_note:"您的助手将在隐私模式下运行。它没有联网,以 Ollama 在本地运行。",openai_mode_note:"您的助手将使用第三方服务来运行。您将与服务商共享个人信息,您的 Smart Second Brain 需要联网使用 OpenAI 的 LLMs,如 ChatGPT。",init:"开启 Smart Second Brain",init_label:"点击以开启",ollama:{deamon:{install:"在终端中安装 Ollama:",set_baseurl:"设置 Ollama Base URL",start:"在终端运行此命令以启动 Ollama"},app:{download:"下载应用程序",download_link:"从这里",extract:"解压 .zip 并启动 Ollama",run:"运行 setup.exe",test_label:"测试 Ollama 是否在运行",set_origins:"在终端中设置 Ollama origins 以启用流式响应:",restart:"重启 Ollama 服务",restart_label:"点击 Ollama 菜单栏图标,然后退出",quit:"退出 Ollama 服务",quit_label:"点击 Ollama 菜单栏图标,然后退出",start_origins:"在 PowerShell 中运行此命令以启动 Ollama"},test_origins:"测试 origins 是否设置正确",install_model:"安装 Ollama 嵌入模型。",recommended:"推荐:",set_model:"设置您的嵌入模型:"},openai:{create_account:"创建一个 OpenAI ",create_account_link:"账户",create_api_key:"创建一个 ",create_api_key_link:"API Key",api_key_warning:`> [!Warning] 激活 API-Key
> 为使 API-Key 有效,您可能需要升级到 OpenAI 付费账户。这需要在您的 OpenAI 账户上存入至少 $5。该提示未来可能改变。`,paste_api_key:"在此粘贴 API Key:",test_api_key:"测试 API Key",api_key_valid:" API Key 有效!"}},Ik={enable:"本地运行",disable:"通过第三方服务运行"},Dk={excludeff:"排除文件和文件夹",excludeff_desc:"这些文件和文件夹将不做向量嵌入和索引,也不会用于生成聊天记录。",excludeff_add:"添加",excludeff_delete:"从排除列表中删除",advanced:"高级设置",clear:"清除插件数据",clear_desc:"将删除所有插件数据和向量存储数据。仓库中的所有聊天记录文件不受影响。",clear_modal:{title:"清除插件数据",description:"您确定要删除插件数据吗?请注意,只有插件数据和向量存储数据将被移除。仓库中的所有聊天记录文件将不受影响。"},clear_label:"清除",relaunch:"重启",autostart:"自启动",autostart_desc:"Obsidian 开启后,自动运行 Smart Second Brain。",num_docs_retrieve:"检索 (retrieve) 文档数",num_docs_retrieve_desc:"仓库中每次允许检索的最大文档数。注意,文档 (本插件索引的笔记片段) 不等同于笔记。",debugging:"调试",langsmith_key:"LangSmith API Key",langsmith_key_desc:"如需跟踪和评估您的 Smart Second Brain 的内部情况,请提供 LangSmith API Key。",verbose:"开发者控制台日志",verbose_desc:"在 Developer Console 中启用详细日志记录。",openai:{desc:" ",api_key:"API Key",api_key_desc:"提供您的 OpenAI API Key 以使用 OpenAI 的大型语言模型。",gen_model:"对话生成模型",embed_model:"嵌入模型",model_descriptions:{"gpt-3.5-turbo":"最新的 GPT-3.5 Turbo 模型(16385 Token 上下文)","gpt-4":"最新的 GPT-4 模型(8192 Token 上下文)","gpt-4-32k":"GPT-4 模型(32768 Token 上下文)","gpt-4-turbo":"最新的 GPT-4 Turbo 模型(128000 Token 上下文)","gpt-4o":"最新的 GPT-4 Omni 模型 (128000 Token 上下文)","text-embedding-3-large":"最新、最强的嵌入模型,适用于多语言任务","text-embedding-3-small":"性能超过二代 ada 嵌入模型","text-embedding-ada-002":"最好的二代嵌入模型。"}},ollama:{desc:" ",gen_model:"对话生成模型",base_url:"Ollama 基础 URL",base_url_desc:"设置您的 Ollama 实例的 URL。",embed_model:"嵌入模型",recommended:"推荐",other:"其他",model_descriptions:{llama2:"Llama 2 是一系列基础语言模型,参数范围从 7B 到 70B。","llama2-uncensored":"由 George Sung 和 Jarrad Hope 提供的未审查的 Llama 2 模型。",mistral:"由 Mistral AI 发布的 7B 模型,已更新至版本 0.2。","mistral-openorca":"Mistral OpenOrca 是 70 亿参数的模型,基于 Mistral 7B 模型并使用 OpenOrca 数据集进行了微调。",gemma:"Gemma 是由 Google DeepMind 构建的一系列轻量级、最先进的开放模型。",mixtral:"由 Mistral AI 提供的高质量 MoE 模型,具有开放权重。","dolphin-mixtral":"Dolphin Mixtral(32000 个令牌)",phi:"Phi-2:微软研究院的 2.7B 语言模型,展示了出色的推理和语言理解能力。","nomic-embed-text":"具有较大上下文的高性能开放嵌入模型。","mxbai-embed-large":"来自 mixedbread.ai 的最先进大型嵌入模型。"}}},Mk={initialize:"启动 Smart Second Brain",indexing_vault:"索引仓库",time_left_minutes:"约剩余 {minutes} 分 {seconds} 秒...",time_left_seconds:"约剩余 {seconds} 秒...",assistant_language:"助手语言",pause_indexing:"暂停索引",resume_indexing:"恢复索引",cancel_indexing:"取消索引",retry_initialization:"重试初始化",mode_changed:`重新初始化 Smart Second Brain
使用以下模型 `,reinitialize:"重新初始化 Smart Second Brain",chat_via:"通过 {model} 聊天",chatview:"Comfy 视图",similarity_threshold:"相似度",creativity:"创意",settings_changed:`设置已更改。
重新初始化 Smart Second Brain。`,open:"打开快速设置",close:"关闭快速设置",error:{install_model:"请先安装 {model} 模型",other:`发生错误。
请重试初始化...`}},xk={creativity:"调整模型输出的创意以适应您的偏好。",similarity:"检索文档与用户提问的相似度。"},Jk={general:Vk,ribbon:Yk,cmd:Nk,modal:Lk,init_third_party_modal:Tk,notice:kk,chat:Uk,onboarding:_k,incognito_toggle:Ik,settings:Dk,quick_settings:Mk,tooltip:xk},Ok={delete:"삭제",install:"설치"},Pk={chat:"S2B 채팅 열기"},zk={chat:"채팅 열기",pull_model:"Ollama 모델 가져오기",remove_model:"Ollama 모델 제거하기"},jk={dont_show:"다시 보지 않기",cancel:"취소",confirm:"확인",pull_model_name:"Ollama 모델 가져오기",pull_model_desc:"Ollama 레지스트리에서 모델 설치하기",remove:{name:"Ollama 모델 제거하기",desc:"시스템에서 설치된 모델 제거하기",success:"모델이 성공적으로 제거됨",error:"모델 제거 실패. 모델이 설치되지 않았을 수 있음"}},qk={title:"타사 서비스를 통해 실행",description:"타사를 통해 실행하시겠습니까? 귀하의 개인 데이터가 OpenAI와 같은 타사 서비스와 공유됩니다."},$k={still_running:"Smart Second Brain이 아직 실행 중입니다. 기다려 주세요.",still_indexing:"Smart Second Brain이 아직 색인 중입니다. 기다려 주세요.",ollama_not_running:"Smart Second Brain을 초기화하기 전에 Ollama가 실행 중인지 확인해 주세요.",ollama_gen_model:"Ollama 모델이 설치되지 않았습니다. Smart Second Brain을 초기화하기 전에 모델을 설치해 주세요.",ollama_embed_model:"Ollama 모델이 설치되지 않았습니다. Smart Second Brain을 초기화하기 전에 모델을 설치해 주세요.",openai_key:"Smart Second Brain을 초기화하기 전에 OpenAI API 키가 유효한지 확인해 주세요.",failed:"Smart Second Brain 초기화에 실패했습니다 (오류: {error}). 다시 시도해 주세요.",failed_indexing:"Smart Second Brain에 노트를 색인하는 데 실패했습니다. 다시 시도해 주세요.",done:"Smart Second Brain이 초기화되었습니다.",error:"오류가 발생했습니다. 오류가 해결될 때까지 기다려 주세요.",not_initialized:"Smart Second Brain이 초기화되지 않았습니다. 먼저 초기화해 주세요.",plugin_data_cleared:"플러그인 데이터가 지워졌습니다.",api_key_invalid:"API 키가 유효하지 않습니다!",error_pulling_model:"Ollama에서 모델을 가져오는 데 실패했습니다 (오류: {error}). 다시 시도해 주세요.",copied_to_clipboard:`클립보드에 복사됨:
{text}`,no_notes_retrieved:"검색된 노트가 없습니다. 유사도 임계값을 낮춰보세요.",run_failed:"Smart Second Brain 실행에 실패했습니다 (오류: {error}). 다시 시도해 주세요.",models_deleted:"모델 {model}이 삭제되었습니다",no_models:"모델 {model}을 찾을 수 없습니다",model_pull_canceled:"모델 가져오기가 취소되었습니다"},eU={edit:"질문을 수정하고 답변을 다시 생성하세요",cancel_edit:"편집 취소",copy:"텍스트 복사",regenerate:"다음 모든 메시지를 삭제하고 현재 질문에 대한 답변을 다시 생성합니다",change_assistant_prompt:"초기 어시스턴스 메시지 변경",reset_assistant_prompt:"초기 어시스턴스 메시지 재설정",retrieving:"검색 중",reducing:"{num}개의 노트 축소 중",stopped:"중단됨!",user:"당신",assistant:"어시스턴스",save:"채팅을 노트에 저장",delete:"채팅 기록 삭제",toggle_papa:"노트와 대화하기",toggle_llm:"기본 LLM과 대화하기",stop:"Smart Second Brain 정지",send:"Smart Second Brain 실행",retry_error:"오류가 발생했습니다. 초기화를 다시 시도하세요",reinitialize:"재초기화, 설정 변경됨",input_placeholder:"Smart Second Brain과 대화하기..."},tU={welcome_msg:"Smart Second Brain에 오신 것을 환영합니다! 노트에서 정보를 찾고 처리하는 데 도움을 주는 개인 AI 어시스턴트입니다.",setup:"설정",test:"테스트",privacy_mode_note:"어시스턴트는 프라이버시 모드에서 실행됩니다. 즉, 인터넷에 연결되어 있지 않고 Ollama를 활용하여 전적으로 로컬에서 실행됩니다.",openai_mode_note:"어시스턴트는 타사 서비스를 사용하여 실행됩니다. 즉, 모든 개인 정보를 이러한 서비스와 공유해야 하며 Smart Second Brain이 ChatGPT와 같은 OpenAI의 대규모 언어 모델을 활용하기 위해 인터넷에 연결되어 있어야 합니다.",init:"Smart Second Brain 시작하기",init_label:"시작하기 클릭",ollama:{deamon:{install:"터미널에서 Ollama 설치:",set_baseurl:"Ollama 기본 URL 설정",start:"이 명령어를 터미널에서 실행하여 Ollama 시작"},app:{download:"앱 다운로드",download_link:"여기",extract:".zip을 추출하고 Ollama 시작",run:"setup.exe 실행",test_label:"Ollama가 실행 중인지 테스트",set_origins:"스트리밍 응답을 활성화하기 위해 터미널에서 Ollama origins 설정:",restart:"Ollama 서비스 재시작 ",restart_label:"Ollama 메뉴 바 아이콘을 클릭한 다음 종료",quit:"Ollama 서비스 종료 ",quit_label:"Ollama 메뉴 바 아이콘을 클릭한 다음 종료",start_origins:"이 명령어를 파워셸에서 실행하여 Ollama 시작"},test_origins:"origins가 올바르게 설정되었는지 테스트",install_model:"Ollama 임베딩 모델 설치.",recommended:"추천: ",set_model:"임베딩 모델 설정:"},openai:{create_account:"OpenAI 계정 생성 ",create_account_link:"계정",create_api_key:"API 키 생성 ",create_api_key_link:"API 키",api_key_warning:`> [!경고] API 키 활성화
> API 키가 작동하려면 OpenAI 유료 계정으로 업그레이드해야 할 수 있습니다. 이는 OpenAI 계정에 최소 $5를 입금해야 함을 의미합니다. 이는 미래에 변경될 수 있습니다.`,paste_api_key:"여기에 키를 붙여넣으세요:",test_api_key:"API 키 테스트",api_key_valid:"API 키가 유효합니다!"}},rU={enable:"내 컴퓨터에서 실행",disable:"타사 서비스를 통해 실행"},aU={excludeff:"파일 및 폴더 제외",excludeff_desc:"이 파일들과 폴더들은 임베딩되지 않으며 답변 생성에 사용되지 않습니다.",excludeff_add:"추가",excludeff_delete:"제외 목록에서 삭제",advanced:"고급 설정",clear:"플러그인 데이터 삭제",clear_desc:"이 작업은 모든 플러그인 데이터와 벡터 저장소 데이터를 삭제합니다. 귀하의 보관함 내 모든 채팅 파일은 영향을 받지 않습니다.",clear_modal:{title:"플러그인 데이터 삭제",description:"플러그인 데이터를 정말 삭제하시겠습니까? 플러그인 데이터와 벡터 저장소 데이터만 제거된다는 점을 참고하세요. 귀하의 보관함 내 모든 채팅 파일은 영향을 받지 않습니다."},clear_label:"삭제",relaunch:"재시작",autostart:"자동 시작",autostart_desc:"Obsidian이 시작될 때 자동으로 Smart Second Brain을 시작합니다.",num_docs_retrieve:"검색할 문서 수",num_docs_retrieve_desc:"보관함에서 검색할 최대 문서 수입니다. 문서가 노트와 동일하지 않다는 점을 참고하세요.",debugging:"디버깅",langsmith_key:"LangSmith API 키",langsmith_key_desc:"Smart Second Brain의 내부를 추적 및 평가하려면 Langsmith API 키를 제공하세요.",verbose:"개발자 콘솔 로깅",verbose_desc:"개발자 콘솔에서 자세한 로깅을 활성화합니다.",openai:{desc:" ",api_key:"API 키",api_key_desc:"OpenAI의 대규모 언어 모델을 사용하기 위해 OpenAI API 키를 제공하세요.",gen_model:"채팅 모델",embed_model:"임베딩 모델",model_descriptions:{"gpt-3.5-turbo":"최신 GPT-3.5 Turbo 모델 (16,385 토큰 컨텍스트 창)","gpt-4":"최신 GPT-4 모델 (8,192 토큰 컨텍스트 창)","gpt-4-32k":"GPT-4 모델 (32,768 토큰 컨텍스트 창)","gpt-4-turbo":"최신 GPT-4 Turbo 모델 (128,000 토큰 컨텍스트 창)","gpt-4o":"최신 GPT-4 Omni 모델 (128000 토큰 컨텍스트 창)","text-embedding-3-large":"영어 및 비영어권 작업 모두에 대해 가장 능력이 뛰어난 최신 임베딩 모델","text-embedding-3-small":"2세대 ada 임베딩 모델보다 성능이 향상됨","text-embedding-ada-002":"가장 능력이 뛰어난 2세대 임베딩 모델."}},ollama:{desc:" ",gen_model:"채팅 모델",base_url:"Ollama 기본 URL",base_url_desc:"Ollama 인스턴스의 URL을 설정하세요.",embed_model:"임베딩 모델",recommended:"추천",other:"기타",model_descriptions:{llama2:"Llama 2는 7B부터 70B 파라미터에 이르는 기초 언어 모델의 집합입니다.","llama2-uncensored":"George Sung과 Jarrad Hope에 의한 무수정 Llama 2 모델입니다.",mistral:"Mistral AI에 의해 발표된 7B 모델로, 버전 0.2로 업데이트되었습니다.","mistral-openorca":"Mistral OpenOrca는 OpenOrca 데이터셋을 사용하여 Mistral 7B 모델 위에 미세 조정된 70억 파라미터 모델입니다.",gemma:"Google DeepMind에 의해 구축된 경량의 최신 오픈 모델 계열인 Gemma입니다.",mixtral:"Mistral AI에 의한 고품질의 전문가 혼합(MoE) 모델로, 오픈 가중치를 가지고 있습니다.","dolphin-mixtral":"Dolphin Mixtral (32000 토큰)",phi:"Microsoft Research에 의한 2.7B 언어 모델인 Phi-2로, 뛰어난 추론 및 언어 이해 능력을 보여줍니다.","nomic-embed-text":"큰 토큰 컨텍스트 창을 가진 고성능 오픈 임베딩 모델입니다.","mxbai-embed-large":"mixedbread.ai에서 나온 최신 대형 임베딩 모델입니다."}}},nU={initialize:"Smart Second Brain 시작하기",indexing_vault:"보관함 색인 중",time_left_minutes:"약 {minutes}분
`,reinitialize:"Smart Second Brain 재초기화",chat_via:"{model}을(를) 통해 대화하기",chatview:"편안한 채팅뷰",similarity_threshold:"유사도",creativity:"창의성",settings_changed:`설정이 변경되었습니다.
Smart Second Brain을 재초기화하세요.`,open:"빠른 설정 열기",close:"빠른 설정 닫기",error:{install_model:"{model} 모델을 먼저 설치하세요",other:`오류가 발생했습니다.
초기화를 다시 시도해주세요...`}},iU={creativity:"모델 출력의 창의성 수준을 사용자의 선호도에 맞게 조정합니다.",similarity:"검색된 문서가 사용자 쿼리와 얼마나 유사해야 하는지를 나타냅니다."},lU={general:Ok,ribbon:Pk,cmd:zk,modal:jk,init_third_party_modal:qk,notice:$k,chat:eU,onboarding:tU,incognito_toggle:rU,settings:aU,quick_settings:nU,tooltip:iU};Zl("en",PT);Zl("es",ok);Zl("tr",Kk);Zl("fr",Hk);Zl("zh",Jk);Zl("ko",lU);BL({fallbackLocale:"en",initialLocale:window.localStorage.getItem("language")});function wK(t){return Object.prototype.toString.call(t)==="[object Date]"}function Rv(t){const e=t-1;return e*e*e+1}function Sh(t,e){if(t===e||t!==t)return()=>t;const r=typeof t;if(r!==typeof e||Array.isArray(t)!==Array.isArray(e))throw new Error("Cannot interpolate values of different type");if(Array.isArray(t)){const a=e.map((n,i)=>Sh(t[i],n));return n=>a.map(i=>i(n))}if(r==="object"){if(!t||!e)throw new Error("Object cannot be null");if(wK(t)&&wK(e)){t=t.getTime(),e=e.getTime();const i=e-t;return l=>new Date(t+l*i)}const a=Object.keys(e),n={};return a.forEach(i=>{n[i]=Sh(t[i],e[i])}),i=>{const l={};return a.forEach(s=>{l[s]=n[s](i)}),l}}if(r==="number"){const a=e-t;return n=>t+n*a}throw new Error(`Cannot interpolate ${r} values`)}function sU(t,e={}){const r=$t(t);let a,n=t;function i(l,s){if(t==null)return r.set(t=l),Promise.resolve();n=l;let o=a,d=!1,{delay:u=0,duration:c=400,easing:p=pC,interpolate:A=Sh}=Jd(Jd({},e),s);if(c===0)return o&&(o.abort(),o=null),r.set(t=n),Promise.resolve();const m=mC()+u;let h;return a=AC(C=>{if(C<m)return!0;d||(h=A(t,l),typeof c=="function"&&(c=c(t,l)),d=!0),o&&(o.abort(),o=null);const w=C-m;return w>c?(r.set(t=l),!1):(r.set(t=h(p(w/c))),!0)}),a.promise}return{set:i,update:(l,s)=>i(l(n,t),s),subscribe:r.subscribe}}function oU(t){let e,r,a,n;return{c(){e=ot("svg"),r=ot("circle"),n=ot("circle"),F(r,"class",a="stroke-current "+(t[1]?"text-[--background-secondary-alt]":"text-[--background-primary-alt]")),F(r,"fill","none"),F(r,"stroke-width","10"),F(r,"cx","50"),F(r,"cy","50"),F(r,"r",Zh),F(n,"class","stroke-current text-[--color-accent]"),F(n,"fill","none"),F(n,"stroke-width","10"),F(n,"cx","50"),F(n,"cy","50"),F(n,"r",Zh),F(n,"stroke-dasharray",t[2]),yl(n,"stroke-dashoffset",t[0]),F(e,"class","h-6 w-6 -rotate-90"),F(e,"viewBox","0 0 100 100")},m(i,l){N(i,e,l),E(e,r),E(e,n)},p(i,[l]){l&2&&a!==(a="stroke-current "+(i[1]?"text-[--background-secondary-alt]":"text-[--background-primary-alt]"))&&F(r,"class",a),l&1&&yl(n,"stroke-dashoffset",i[0])},i:le,o:le,d(i){i&&Y(e)}}}const Zh=45;function dU(t,e,r){let a,n;me(t,Qu,o=>r(1,n=o));let{progress:i=0}=e;const l=2*Math.PI*Zh,s=sU(0,{duration:400,easing:Rv});return bi(()=>{s.set(i)}),t.$$set=o=>{"progress"in o&&r(3,i=o.progress)},t.$$.update=()=>{t.$$.dirty&8&&s.set(i),t.$$.dirty&8&&r(0,a=l-i/100*l)},[a,n,l,i]}class uU extends pt{constructor(e){super(),ut(this,e,dU,oU,st,{progress:3})}}function pU(t){let e,r,a,n,i,l,s,o,d,u,c,p,A,m,h,C,w,b,f,K,W,R,v,L,y,G,Z,k,_;return{c(){e=ot("svg"),r=ot("defs"),a=ot("style"),n=te(`.cls-1,
.cls-2,
.cls-3,
.cls-4,
.cls-5,
.cls-6,
.cls-7 {
fill: none;
stroke-miterlimit: 10;
}
.cls-1,
.cls-6 {
stroke-width: 6px;
}
.cls-2 {
stroke-width: 8px;
}
.cls-2,
.cls-3,
.cls-4,
.cls-6 {
stroke-linecap: round;
}
.cls-8 {
stroke-width: 0px;
}
.cls-3,
.cls-5 {
stroke-width: 3px;
}
.cls-4,
.cls-7 {
stroke-width: 5px;
}
`),i=ot("g"),l=ot("path"),s=ot("path"),o=ot("path"),d=ot("path"),u=ot("path"),c=ot("path"),p=ot("path"),A=ot("path"),m=ot("path"),h=ot("path"),C=ot("path"),w=ot("path"),b=ot("path"),f=ot("g"),K=ot("path"),W=ot("path"),R=ot("path"),v=ot("path"),L=ot("path"),y=ot("path"),G=ot("path"),Z=ot("path"),k=ot("path"),F(l,"class","cls-6"),F(l,"d","m119.76,235.22c-95.84-79.16-30.4-176.18,30.3-196.33,62.91-20.88,130.24,17.36,146.97,78.91,9.76,35.91,6.2,96.83-59.52,124.16"),F(s,"class","cls-4"),F(s,"d","m243.98,295.97c11.44,2.55,26.63-2.2,34.9-11.47,7.62-8.53,9.26-23.71-1.37-28.68-3.1-1.41-8.39-4.34-25.26,9.89"),F(o,"class","cls-4"),F(o,"d","m211.26,239.39c-7.07,16.12-9.01,30.06-3.44,43.38"),F(d,"class","cls-4"),F(d,"d","m255.03,262.83c-6.24-7.97-11.64-16.69-10.26-24.14"),F(u,"class","cls-4"),F(u,"d","m255.03,236.29c2.53,8.15,26.76,18.29,38.06-3.65,10.38-20.15,19.18-14.03,21.22-12.74,5.69,3.59,5.08,19.12,5.08,23.19,0,19.72-15.37,27.77-25.17,30.41-2.45.66-4.93.86-7.41.7"),F(c,"class","cls-2"),F(c,"d","m159.81,196.17c0,15.73,19.25,11.74,19.25.27"),F(p,"class","cls-8"),F(p,"d","m100.68,183.58c-.39-15.51,10.1-29.27,22.64-29.7,13.25-.46,24.05,11.76,24.39,27.61.36,16.39-9.78,29.86-22.87,30.39-13.03.52-23.76-12.03-24.17-28.3Zm33.87-3.78c3.85-.06,6.61-4.11,5.8-8.83-.87-5.07-3.33-8.55-7.51-9.86-3.76-1.18-7.21,1.93-7.48,6.67-.35,6.1,4.24,12.1,9.19,12.02Z"),F(A,"class","cls-8"),F(A,"d","m195.6,186.94c-.39-15.51,10.1-29.27,22.64-29.7,13.25-.46,24.05,11.76,24.39,27.61.36,16.39-9.78,29.86-22.87,30.39-13.03.52-23.76-12.03-24.17-28.3Zm33.87-3.78c3.85-.06,6.61-4.11,5.8-8.83-.87-5.07-3.33-8.55-7.51-9.86-3.76-1.18-7.21,1.93-7.48,6.67-.35,6.1,4.24,12.1,9.19,12.02Z"),F(m,"class","cls-4"),F(m,"d","m142.53,236.39c3.51,8.36,5.19,30.91-4.14,35.41"),F(h,"class","cls-7"),F(h,"d","m108.7,225.33c-17.93,8.39-29.31,4.95-35.4-7.63-.41-.95-3.65-7.37-9.47-7.99-3.69-.39-6.51,1.35-7.6,1.96-5.84,3.27-5.99,18.65-6.19,22.67-.3,6.17.29,12.61,4.66,19.09,2.99,4.44,7.61,6.3,10.03,7.71"),F(C,"class","cls-3"),F(C,"d","m223.9,267.43c-2.25-3.2-3.93-6.85-4.74-10.8"),F(w,"class","cls-4"),F(w,"d","m150.65,275.2c-11.27,3.93-16.8-9.25-23.58-17.48-1.15-1.4-3.84-3.56-7.8-4.56-.16-.04-2.65-.65-5.03-.41-6.83.68-12.82,7.92-14.1,13.2-5.53,22.77,9.93,36.73,18.74,41.48,14.52,7.82,36.47,6.91,55.1-5.68"),F(b,"class","cls-4"),F(b,"d","m179.07,235.47c-25.49,54.97,4.84,82.78,29.94,83.89,18.49.81,39.76-16.08,36.23-39.13-1.17-7.62-6.37-11.88-13.47-12.86-12.08-1.66-16.81,20.98-32.09,15.06"),F(K,"class","cls-5"),F(K,"d","m282.77,261.99c23.21-10.24,10.89-38.79,20.22-42.51"),F(W,"class","cls-3"),F(W,"d","m171.08,287.69c-22.21,15.19-37.76-9.57-40.91-19.61-4.83-15.38-10.76-15.33-16.18-15.33"),F(R,"class","cls-3"),F(R,"d","m98.59,263.83c-9.83-2.58-13.76-12.61-14.84-19.93-.61-4.1-1.74-10.92-11.89-10.58"),F(v,"class","cls-5"),F(v,"d","m66.89,235.29c-1.98-10.95,1.21-26.31-7.4-23.88"),F(L,"class","cls-5"),F(L,"d","m277.5,255.83c-2.71-1.29-13.23-4.09-17.22,13.97-1.87,8.48-7.96,11.66-14.93,11.04"),F(y,"class","cls-3"),F(y,"d","m171.83,287.26c5.8,9.77,15.91,17.37,31.37,11.41,13.36-5.16,9.97-24.24,21.68-28.87,4.31-1.7,7.1-1.94,10.53-1.58"),F(G,"class","cls-4"),F(G,"d","m97.64,280.44c-9.05.55-18.91-2.53-27.09-10.3-7.09-6.73-13.32-25.71-5.07-33.63,4.33-4.15,10.93-3.55,11.24-3.52,11,1.17,13.58,14.25,21.42,14.82,4.06.3,9.51-2.17,17.18-16.37"),F(Z,"class","cls-1"),F(Z,"d","m70.55,152.49c9.11-9.88,30.06-28.17,46.89-28.07,21.67.13,19.1,25.53,52.73,24.8,37.98-.82,27.35-16.61,52.43-19.52,15.57-1.81,40.86,11.57,76.26,31.09"),F(k,"class","cls-8"),F(k,"d","m102.06,128.35c4.62-2.2,9.56-4.14,16.68-4.29-.71-6.67-.5-13.88,1.03-17.71.93-2.33,2.45-4.98,5.21-3.62,2.45,1.2,1.71,3.65.62,6.02-3.77,8.25-.66,22.15,10.41,24.11,9.88,14.4,24.28,16.98,40.7,14.31-6.82-5.42-13.63-10.88-20.74-15.85-4.25-2.97-6.98-7.03-8.63-11.91-3.21-9.48-1.8-18.82,4.52-26.79,5.62-7.1,18.07-7.93,23.34-5.88,4.25,2.06,6.23,4.67,9.77,8.15,1,.98,2.36,4.14.73,5.59-1.63,1.45-3.71-.07-5.09-.94-2.26-1.43-3.96-3.84-6.19-5.33-6.84-4.56-16.86-1.51-20.28,5.97-3.91,8.57-2.98,17.38,3.54,23.2,5.67,5.05,12.04,9.23,18.29,13.5,5.79,3.96,9.84,5.58,11.84,10.61,5.03-1.57,9.
`+ie(ae).initialAssistantMessageContent+`
- - - - -`);this.icon="message-square"}getViewType(){return Ra}setViewData(r,a){this.data=r;const n=r.split("- - - - -").map(i=>i.trim()).filter(i=>i.length>0).map(i=>{const l=i.split(`
`),s=l[0],o=l.slice(1).join(`
`),d=fu();return{role:s,content:o,id:d}});Mt.set(n),a&&this.clear()}clear(){}getViewData(){const r=ie(Mt).map(a=>`${a.role}
${a.content}
- - - - -`);return this.data=r.join(`
`),this.data}getDisplayText(){var r;return((r=this.file)==null?void 0:r.basename)||"Second Brain Chat"}async onLoadFile(r){await super.onLoadFile(r),this.component=new W_({target:this.contentEl})}async onUnloadFile(r){return this.clear(),this.component.$destroy(),await super.onUnloadFile(r)}}function Sv({fallback:t,...e}){const r=new Map,a=new Map;function n(l,s,o){const{delay:d=0,duration:u=R=>Math.sqrt(R)*30,easing:c=Rv}=Jd(Jd({},e),o),p=l.getBoundingClientRect(),A=s.getBoundingClientRect(),m=p.left-A.left,h=p.top-A.top,C=p.width/A.width,w=p.height/A.height,b=Math.sqrt(m*m+h*h),f=getComputedStyle(s),K=f.transform==="none"?"":f.transform,W=+f.opacity;return{delay:d,duration:Yr(u)?u(b):u,easing:c,css:(R,v)=>`
opacity: ${R*W};
transform-origin: top left;
transform: ${K} translate(${v*m}px,${v*h}px) scale(${R+(1-R)*C}, ${R+(1-R)*w});
`}}function i(l,s,o){return(d,u)=>(l.set(u.key,d),()=>{if(s.has(u.key)){const c=s.get(u.key);return s.delete(u.key),n(c,d,u)}return l.delete(u.key),t&&t(d,u,o)})}return[i(a,r,!1),i(r,a,!0)]}function HK(t,e,r){const a=t.slice();return a[5]=e[r],a}function VK(t){let e,r,a,n;return{c(){e=X("div"),F(e,"class","border-1 border-primary w-full border border-solid")},m(i,l){N(i,e,l),n=!0},i(i){n||(i&&Dr(()=>{n&&(a&&a.end(1),r=BC(e,t[2],{key:0}),r.start())}),n=!0)},o(i){r&&r.invalidate(),i&&(a=CC(e,t[3],{key:0})),n=!1},d(i){i&&Y(e),i&&a&&a.end()}}}function YK(t){let e,r,a=t[5]+"",n,i,l,s,o,d=t[5]===t[0]&&VK(t);function u(){return t[4](t[5])}return{c(){e=X("li"),r=X("span"),n=te(a),i=M(),d&&d.c(),l=M(),F(e,"class","flex h-full flex-col items-center justify-center rounded-md p-2 text-center font-bold hover:bg-[--background-modifier-hover]")},m(c,p){N(c,e,p),E(e,r),E(r,n),E(e,i),d&&d.m(e,null),E(e,l),s||(o=de(e,"click",u),s=!0)},p(c,p){t=c,p&2&&a!==(a=t[5]+"")&&ne(n,a),t[5]===t[0]?d?p&3&&D(d,1):(d=VK(t),d.c(),D(d,1),d.m(e,l)):d&&(vt(),J(d,1,1,()=>{d=null}),Ft())},d(c){c&&Y(e),d&&d.d(),s=!1,o()}}}function F_(t){let e,r=Xt(t[1]),a=[];for(let n=0;n<r.length;n+=1)a[n]=YK(HK(t,r,n));return{c(){e=X("ul");for(let n=0;n<a.length;n+=1)a[n].c();F(e,"class","m-0 flex list-none p-0 transition-all")},m(n,i){N(n,e,i);for(let l=0;l<a.length;l+=1)a[l]&&a[l].m(e,null)},p(n,[i]){if(i&3){r=Xt(n[1]);let l;for(l=0;l<r.length;l+=1){const s=HK(n,r,l);a[l]?a[l].p(s,i):(a[l]=YK(s),a[l].c(),a[l].m(e,null))}for(;l<a.length;l+=1)a[l].d(1);a.length=r.length}},i:le,o:le,d(n){n&&Y(e),ea(a,n)}}}function y_(t,e,r){let{options:a}=e,{selected:n=a[0]}=e;const[i,l]=Sv({duration:500}),s=o=>r(0,n=o);return t.$$set=o=>{"options"in o&&r(1,a=o.options),"selected"in o&&r(0,n=o.selected)},[n,a,i,l,s]}class R_ extends pt{constructor(e){super(),ut(this,e,y_,F_,st,{options:1,selected:0})}}function E_(t){let e,r=t[1]("onboarding.init")+"",a,n,i,l;return{c(){e=X("button"),a=te(r),F(e,"aria-label",n=t[1]("onboarding.init_label")),F(e,"class","mod-cta")},m(s,o){N(s,e,o),E(e,a),i||(l=de(e,"click",t[3]),i=!0)},p(s,[o]){o&2&&r!==(r=s[1]("onboarding.init")+"")&&ne(a,r),o&2&&n!==(n=s[1]("onboarding.init_label"))&&F(e,"aria-label",n)},i:le,o:le,d(s){s&&Y(e),i=!1,l()}}}function G_(t,e,r){let a,n,i;me(t,dt,o=>r(4,a=o)),me(t,ae,o=>r(0,n=o)),me(t,Bt,o=>r(1,i=o));function l(){Ye(ae,n.isOnboarded=!0,n),a.saveSettings(),a.activateView(),a.s2b.init()}return[n,i,l,()=>{n.isIncognitoMode?l():new QC(ie(dt).app,"Run via Third-Parties","Are you sure you want to run via third-parties? Your data will be given to third-party servers.",o=>{o==="Yes"&&l()},"hideIncognitoWarning").activate()}]}class Zv extends pt{constructor(e){super(),ut(this,e,G_,E_,st,{})}}function NK(t){let e;function r(i,l){return i[5]?Z_:S_}let a=r(t),n=a(t);return{c(){n.c(),e=Tt()},m(i,l){n.m(i,l),N(i,e,l)},p(i,l){a!==(a=r(i))&&(n.d(1),n=a(i),n&&(n.c(),n.m(e.parentNode,e)))},d(i){i&&Y(e),n.d(i)}}}function S_(t){let e,r,a;return{c(){e=X("div"),F(e,"class","h-[28px] *:!h-[28px] *:!w-[28px] *:text-[--background-modifier-error]")},m(n,i){N(n,e,i),r||(a=Ge(xt.call(null,e,"cross")),r=!0)},d(n){n&&Y(e),r=!1,a()}}}function Z_(t){let e,r,a;return{c(){e=X("div"),F(e,"class","h-[28px] *:!h-[28px] *:!w-[28px] *:text-[--background-modifier-success]")},m(n,i){N(n,e,i),r||(a=Ge(xt.call(null,e,"check")),r=!0)},d(n){n&&Y(e),r=!1,a()}}}function LK(t){let e,r=t[6]("onboarding.test")+"",a,n,i;return{c(){e=X("button"),a=te(r),F(e,"aria-label","Test if origins are set correctly")},m(l,s){N(l,e,s),E(e,a),n||(i=de(e,"click",t[8]),n=!0)},p(l,s){s&64&&r!==(r=l[6]("onboarding.test")+"")&&ne(a,r)},d(l){l&&Y(e),n=!1,i()}}}function TK(t){let e,r=t[6]("onboarding.ollama.install_model")+"",a,n,i,l,s,o,d,u;l=new K1({props:{pullModel:H_,text:t[6]("onboarding.ollama.recommended"),onSuccessfulPull:t[9]}});let c=t[0].length>0&&kK(t),p=t[3]!==""&&UK();return{c(){e=X("li"),a=te(r),n=X("br"),i=M(),pe(l.$$.fragment),s=M(),c&&c.c(),o=M(),p&&p.c(),d=Tt()},m(A,m){N(A,e,m),E(e,a),E(e,n),E(e,i),se(l,e,null),N(A,s,m),c&&c.m(A,m),N(A,o,m),p&&p.m(A,m),N(A,d,m),u=!0},p(A,m){(!u|
`),pe(r.$$.fragment)},m(n,i){N(n,e,i),se(r,n,i),a=!0},p:le,i(n){a||(D(r.$$.fragment,n),a=!0)},o(n){J(r.$$.fragment,n),a=!1},d(n){n&&Y(e),oe(r,n)}}}function TI(t){let e;return{c(){e=te("Ollama is Not Running")},m(r,a){N(r,e,a)},p:le,i:le,o:le,d(r){r&&Y(e)}}}function kI(t){let e,r=t[3]("cmd.remove_model")+"",a,n,i,l,s,o;const d=[TI,LI,NI],u=[];function c(p,A){return p[1]===!1?0:p[1]===void 0?1:2}return l=c(t),s=u[l]=d[l](t),{c(){e=X("div"),a=te(r),n=M(),i=X("div"),s.c(),F(e,"class","modal-title"),F(i,"class","modal-content")},m(p,A){N(p,e,A),E(e,a),N(p,n,A),N(p,i,A),u[l].m(i,null),o=!0},p(p,[A]){(!o||A&8)&&r!==(r=p[3]("cmd.remove_model")+"")&&ne(a,r);let m=l;l=c(p),l===m?u[l].p(p,A):(vt(),J(u[m],1,1,()=>{u[m]=null}),Ft(),s=u[l],s?s.p(p,A):(s=u[l]=d[l](p),s.c()),D(s,1),s.m(i,null))},i(p){o||(D(s),o=!0)},o(p){J(s),o=!1},d(p){p&&(Y(e),Y(n),Y(i)),u[l].d()}}}const ef=t=>({display:t,value:t});function UI(t,e,r){let a;me(t,Bt,d=>r(3,a=d));let n="",i,l=[];return bi(async()=>{r(2,l=await jr()),r(1,i=await si())}),[n,i,l,a,d=>r(0,n=d),async()=>{await xL(n),r(2,l=await jr())}]}let _I=class extends pt{constructor(e){super(),ut(this,e,UI,kI,st,{})}};class II extends Qe.Modal{constructor(r){super(r);Ze(this,"component")}onOpen(){new _I({target:this.contentEl,props:{modal:this}})}onClose(){const{contentEl:r}=this;r.empty()}}var tf;const eu={isChatComfy:!0,isUsingRag:!0,assistantLanguage:window.localStorage.getItem("language")||"en",initialAssistantMessageContent:((tf=wa[window.localStorage.getItem("language")||"en"])==null?void 0:tf.initialAssistantMessage)||wa.en.initialAssistantMessage,isIncognitoMode:!0,ollamaGenModel:{model:"llama2",baseUrl:"http://localhost:11434",temperature:.5},ollamaEmbedModel:{model:"nomic-embed-text",baseUrl:"http://localhost:11434",similarityThreshold:.75,k:100},openAIGenModel:{model:"gpt-3.5-turbo",openAIApiKey:"",temperature:.5},openAIEmbedModel:{model:"text-embedding-ada-002",openAIApiKey:"",similarityThreshold:.75,k:100},targetFolder:"Chats",defaultChatName:"New Chat",excludeFF:["Chats","*.excalidraw.md"],isQuickSettingsOpen:!0,isVerbose:!1,isOnboarded:!1,hideIncognitoWarning:!1,isAutostart:!1};class DI extends Qe.Plugin{constructor(){super(...arguments);Ze(this,"setupView");Ze(this,"chatView");Ze(this,"s2b");Ze(this,"leaf");Ze(this,"isChatAcivatedFromRibbon",!1);Ze(this,"autoSaveTimer")}async loadSettings(){ae.set(Object.assign({},eu,await this.loadData()))}async saveSettings(){await this.saveData(ie(ae))}async onload(){dt.set(this);const r=ie(Bt);await this.loadSettings(),this.s2b=new OL(this.app,this.manifest.dir),dr.setLogLevel(ie(ae).isVerbose?ol.DEBUG:ol.DISABLED),this.app.workspace.onLayoutReady(()=>{const n=this.app.workspace.getLeavesOfType(Ra)||this.app.workspace.getLeavesOfType(ji);n.length&&(this.leaf=n[0]),ie(ae).isOnboarded&&ie(ae).isAutostart&&this.s2b.init()}),this.registerEvent(this.app.workspace.on("layout-change",()=>{if(!this.leaf){const i=this.app.workspace.getLeavesOfType(Ra)||this.app.workspace.getLeavesOfType(ji);if(!i.length)return;this.leaf=i[0]}const n=[this.app.workspace.leftSplit,this.app.workspace.rightSplit].includes(this.leaf.getRoot());Qu.set(n)})),this.registerEvent(this.app.metadataCache.on("changed",async n=>this.s2b.onFileChange(n))),this.registerEvent(this.app.vault.on("delete",async n=>this.s2b.onFileDelete(n))),this.registerEvent(this.app.vault.on("rename",async(n,i)=>this.s2b.onFileRename(n,i))),window.addEventListener("blur",()=>this.s2b.saveVectorStoreData());const a=()=>{window.clearTimeout(this.autoSaveTimer),this.autoSaveTimer=window.setTimeout(()=>this.s2b.saveVectorStoreData(),30*1e3)};window.addEventListener("mousemove",()=>a()),window.addEventListener("mousedown",()=>a()),window.addEventListener("keypress",()=>a()),window.addEventListener("scroll",()=>a()),this.s2b||this.app.workspace.detachLeavesOfType(Ra),this.registerView(ji,n=>(this.setupView=new pI(n),this.setupView)),this.registerView(Ra,n=>(this.chatView=new v_(n),this.chatView)),this.addRibbonIcon("message-square",r("ribbon.chat"),()=>this.activateView()),this.addCommand({id:"open-chat",nam
`+a.initialAssistantMessageContent+`
- - - - -`));const n=this.app.workspace.getLeavesOfType(Ra);this.leaf=n.length?n[0]:this.app.workspace.getRightLeaf(!1),this.isChatAcivatedFromRibbon=!0,await this.leaf.openFile(r,{active:!0}),await this.leaf.setViewState({type:Ra,state:{file:r.path}})}else{this.app.workspace.detachLeavesOfType(Ra);const n=this.app.workspace.getLeavesOfType(ji);this.leaf=n.length?n[0]:this.app.workspace.getRightLeaf(!1),await this.leaf.setViewState({type:ji,active:!0})}this.app.workspace.revealLeaf(this.leaf)}async saveChat(){const r=ie(ae);let a=await this.s2b.createFilenameForChat(),n=Qe.normalizePath(r.targetFolder+"/"+a+".md");for(;await this.app.vault.adapter.exists(n);){const l=/\((\d+)\)$/,s=a.match(l);s?a=a.slice(0,-3)+"("+(parseInt(s[1],10)+1)+")":a=a+" (1)",n=Qe.normalizePath(r.targetFolder+"/"+a+".md")}const i=await this.app.vault.copy(this.chatView.file,n);Mt.reset,await this.activateView(i)}async clearPluginData(){const r=ie(Bt);new QC(ie(dt).app,r("settings.clear_modal.title"),r("settings.clear_modal.description"),async a=>{if(a==="Yes"){await this.saveData({});const n=(await this.app.vault.adapter.list(Qe.normalizePath(this.manifest.dir+"/vectorstores"))).files;for(const i of n)await this.app.vault.adapter.remove(i);new Qe.Notice(r("notice.plugin_data_cleared"),4e3),await this.loadSettings(),await this.activateView()}},"").activate()}registerMonkeyPatches(){const r=this;this.register(F5(Qe.WorkspaceLeaf.prototype,{setViewState(a){return function(n,...i){var l;if(n.type==="markdown"&&((l=n.state)!=null&&l.file)&&n.state.file.startsWith(ie(ae).targetFolder)){const s={...n,type:Ra};if(!r.isChatAcivatedFromRibbon){const o=r.app.workspace.getLeavesOfType(Ra);r.leaf=o.length?o[0]:r.app.workspace.getRightLeaf(!1)}return a.apply(r.leaf,[s,...i])}return a.apply(this,[n,...i])}}}))}}exports.DEFAULT_SETTINGS=eu;exports.default=DI;
//# sourceMappingURL=file:///home/runner/work/obsidian-Smart2Brain/obsidian-Smart2Brain/build/smart-second-brain/main.js.map
/* nosourcemap */