varMlr=Object.create;vartH=Object.defineProperty;varRlr=Object.getOwnPropertyDescriptor;varNlr=Object.getOwnPropertyNames;varjlr=Object.getPrototypeOf,Dlr=Object.prototype.hasOwnProperty;varh6e=t=>{throwTypeError(t)};varLlr=(t,e,r)=>eint?tH(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;varw=(t,e)=>()=>(t&&(e=t(t=0)),e);varv=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Qd=(t,e)=>{for(varrine)tH(t,r,{get:e[r],enumerable:!0})},g6e=(t,e,r,n)=>{if(e&&typeofe=="object"||typeofe=="function")for(letoofNlr(e))!Dlr.call(t,o)&&o!==r&&tH(t,o,{get:()=>e[o],enumerable:!(n=Rlr(e,o))||n.enumerable});returnt};varF=(t,e,r)=>(r=t!=null?Mlr(jlr(t)):{},g6e(e||!t||!t.__esModule?tH(r,"default",{value:t,enumerable:!0}):r,t)),dc=t=>g6e(tH({},"__esModule",{value:!0}),t);varKc=(t,e,r)=>Llr(t,typeofe!="symbol"?e+"":e,r),Flr=(t,e,r)=>e.has(t)||h6e("Cannot "+r);vary6e=(t,e,r)=>e.has(t)?h6e("Cannot add the same private member more than once"):einstanceofWeakSet?e.add(t):e.set(t,r);varb6e=(t,e,r)=>(Flr(t,e,"access private method"),r);functionCye(){if(!B7&&(B7=typeofcrypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!B7))thrownewError("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");returnB7(klr)}varB7,klr,_6e=w(()=>{klr=newUint8Array(16)});functionv6e(t,e=0){returnGc[t[e+0]]+Gc[t[e+1]]+Gc[t[e+2]]+Gc[t[e+3]]+"-"+Gc[t[e+4]]+Gc[t[e+5]]+"-"+Gc[t[e+6]]+Gc[t[e+7]]+"-"+Gc[t[e+8]]+Gc[t[e+9]]+"-"+Gc[t[e+10]]+Gc[t[e+11]]+Gc[t[e+12]]+Gc[t[e+13]]+Gc[t[e+14]]+Gc[t[e+15]]}varGc,w6e=w(()=>{Gc=[];for(lett=0;t<256;++t)Gc.push((t+256).toString(16).slice(1))});var$lr,Oye,x6e=w(()=>{$lr=typeofcrypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Oye={randomUUID:$lr}});functionzlr(t,e,r){if(Oye.randomUUID&&!e&&!t)returnOye.randomUUID();t=t||{};letn=t.random||(t.rng||Cye)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){r=r||0;for(leto=0;o<16;++o)e[r+o]=n[o];returne}returnv6e(n)}varRp,S6e=w(()=>{x6e();_6e();w6e();Rp=zlr});varI1=w(()=>{S6e()});varkn,Pye,yt,I_,rH=w(()=>{(function(t){t.assertEqual=o=>{};functione(o){}t.assertIs=e;functionr(o){thrownewError}t.assertNever=r,t.arrayToEnum=o=>{leti={};for(letaofo)i[a]=a;returni},t.getValidEnumValues=o=>{leti=t.objectKeys(o).filter(s=>typeofo[o[s]]!="number"),a={};for(letsofi)a[s]=o[s];returnt.objectValues(a)},t.objectValues=o=>t.objectKeys(o).map(function(i){returno[i]}),t.objectKeys=typeofObject.keys=="function"?o=>Object.keys(o):o=>{leti=[];for(letaino)Object.prototype.hasOwnProperty.call(o,a)&&i.push(a);returni},t.find=(o,i)=>{for(letaofo)if(i(a))returna},t.isInteger=typeofNumber.isInteger=="function"?o=>Number.isInteger(o):o=>typeofo=="number"&&Number.isFinite(o)&&Math.floor(o)===o;functionn(o,i=" | "){returno.map(a=>typeofa=="string"?`'${a}'`:a).join(i)}t.joinValues=n,t.jsonStringifyReplacer=(o,i)=>typeofi=="bigint"?i.toString():i})(kn||(kn={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Pye||(Pye={}));yt=kn.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),I_=t=>{switch(typeoft){case"undefined":returnyt.undefined;case"string":returnyt.string;case"number":returnNumber.isNaN(t)?yt.nan:yt.number;case"boolean":returnyt.boolean;case"function":returnyt.function;case"bigint":returnyt.bigint;case"symbol":returnyt.symbol;case"object":returnArray.isArray(t)?yt.array:t===null?yt.null:t.then&&typeoft.then=="function"&&t.catch&&typeoft.catch=="function"?yt.promise:typeofMap<"u"&&tinstanceofMap?yt.map:typeofSet<"u"&&tinstanceofSet?yt.set:typeofDate<"u"&&tinstanceofDate?yt.date:yt.object;default:returnyt.unknown}}});varze,Blr,Np,U7=w(()=>{rH();ze=kn.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","inval
Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}function nZ(t){return typeof t=="function"&&"langsmith:traceable"in t}var $ye,kye,pdr,zye,mdr,m2n,r8e=w(()=>{$ye=class{getStore(){}run(e,r){return r()}},kye=Symbol.for("ls:tracing_async_local_storage"),pdr=new $ye,zye=class{getInstance(){return globalThis[kye]??pdr}initializeGlobalInstance(e){globalThis[kye]===void 0&&(globalThis[kye]=e)}},mdr=new zye;m2n=Symbol.for("langsmith:traceable:root")});var Bye=w(()=>{r8e()});function iZ(t,e){return hdr.call(t,e)}function aZ(t){if(Array.isArray(t)){let r=new Array(t.length);for(let n=0;n<r.length;n++)r[n]=""+n;return r}if(Object.keys)return Object.keys(t);let e=[];for(let r in t)iZ(t,r)&&e.push(r);return e}function tf(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function sZ(t){let e=0,r=t.length,n;for(;e<r;){if(n=t.charCodeAt(e),n>=48&&n<=57){e++;continue}return!1}return!0}function N_(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function sH(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function oZ(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let r=0,n=t.length;r<n;r++)if(oZ(t[r]))return!0}else if(typeof t=="object"){let r=aZ(t),n=r.length;for(var e=0;e<n;e++)if(oZ(t[r[e]]))return!0}}return!1}function n8e(t,e){let r=[t];for(let n in e){let o=typeof e[n]=="object"?JSON.stringify(e[n],null,2):e[n];typeof o<"u"&&r.push(`${n}: ${o}`)}return r.join(`
`)}var hdr,J1,uH=w(()=>{hdr=Object.prototype.hasOwnProperty;J1=class extends Error{constructor(e,r,n,o,i){super(n8e(e,{name:r,index:n,operation:o,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:n}),Object.defineProperty(this,"operation",{enumerable:!0,configurable:!0,writable:!0,value:o}),Object.defineProperty(this,"tree",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.setPrototypeOf(this,new.target.prototype),this.message=n8e(e,{name:r,index:n,operation:o,tree:i})}}});var Uye={};Qd(Uye,{JsonPatchError:()=>vs,_areEquals:()=>lH,applyOperation:()=>Z1,applyPatch:()=>KT,applyReducer:()=>bdr,deepClone:()=>gdr,getValueByPointer:()=>uZ,validate:()=>o8e,validator:()=>lZ});function uZ(t,e){if(e=="")return t;var r={op:"_get",path:e};return Z1(t,r),r.value}function Z1(t,e,r=!1,n=!0,o=!0,i=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):lZ(e,0)),e.path===""){let a={newDocument:t};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=t,a;if(e.op==="move"||e.op==="copy")return a.newDocument=uZ(t,e.from),e.op==="move"&&(a.removed=t),a;if(e.op==="test"){if(a.test=lH(t,e.value),a.test===!1)throw new vs("Testoperationfailed","TEST_OPERATION_FAILED",i,e,t);return a.newDocument=t,a}else{if(e.op==="remove")return a.removed=t,a.newDocument=null,a;if(e.op==="_get")return e.value=t,a;if(r)throw new vs("Operation`op`propertyisnotoneofoperationsdefinedinRFC-6902","OPERATION_OP_INVALID",i,e,t);return a}}else{n||(t=tf(t));let s=(e.path||"").split("/"),u=t,l=1,c=s.length,d,f,p;for(typeof r=="function"?p=r:p=lZ;;){if(f=s[l],f&&f.indexOf("~")!=-1&&(f=sH(f)),o&&(f=="__proto__"||f=="prototype"&&l>0&&s[l-1]=="constructor"))throw new TypeError("JSON-Patch:modifying`__proto__`or`constructor/prototype`propisbannedforsecurityreasons,ifthiswasonpurpose,pleaseset`banPrototypeModifications`flagfalseandpassittothisfunction.Moreinfoinfast-json-patchREADME");if(r&&d===void 0&&(u[f]===void 0?d=s.slice(0,l).join("/"):l==c-1&&(d=e.path),d!==void 0&&p(e,0,t,d)),l++,Array.isArray(u)){if(f==="-")f=u.length;else{if(r&&!sZ(f))throw new vs("Expectedanunsignedbase-10integervalue,makingthenewreferencedvaluethearrayelementwiththezero-basedindex","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,e,t);sZ(f)&&(f=~~f)}if(l>=c){if(r&&e.op==="add"&&f>u.length)throw new vs("ThespecifiedindexMUSTNOTbegreaterthanthenumberofelementsinthearray","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,t);let m=ydr[e.op].call(e,u,f,t);if(m.test===!1)throw new vs("Testoperationfailed","TEST_OPERATION_FAILED",i,e,t);return m}}else if(l>=c){let m=Wk[e.op].call(e,u,f,t);if(m.test===!1)throw new vs("Testoperationfailed","TEST_OPERATION_FAILED",i,e,t);return m}if(u=u[f],r&&l<c&&(!u||typeof u!="object"))throw new vs("Cannotperformoperationatthedesiredpath","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}function KT(t,e,r,n=!0,o=!0){if(r&&!Array.isArray(e))throw new vs("Patchsequencemustbeanarray","SEQUENCE_NOT_AN_ARRAY");n||(t=tf(t));let i=new Array(e.length);for(let a=0,s=e.length;a<s;a++)i[a]=Z1(t,e[a],r,!0,o,a),t=i[a].newDocument;return i.newDocument=t,i}function bdr(t,e,r){let n=Z1(t,e);if(n.test===!1)throw new vs("Testoperationfailed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function lZ(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new vs("Operationisnotanobject","OPERATION_NOT_AN_OBJECT",e,t,r);if(Wk[t.op]){if(typeof t.path!="string")throw new vs("Operation`path`propertyisnotastring","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new vs('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 vs("Operation`from`propertyisnotpresent(applicablein`move`and`copy`operations)","OPERATION_FROM_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)t
Context: ${e}`:""}`),FZ("[Unserializable]");$l("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
Context: ${e}`:""}`),typeof o>"u"&&(o=zmr()),kbe(t,"",0,[],void 0,0,o);let a;try{Jk.length===0?a=JSON.stringify(t,r,n):a=JSON.stringify(t,Umr(r),n)}catch{return FZ("[unabletoserialize,circularreferenceistoocomplextoanalyze]")}finally{for(;kZ.length!==0;){let s=kZ.pop();s.length===4?Object.defineProperty(s[0],s[1],s[3]):s[0][s[1]]=s[2]}}return FZ(a)}}function Fbe(t,e,r,n){var o=Object.getOwnPropertyDescriptor(n,r);o.get!==void 0?o.configurable?(Object.defineProperty(n,r,{value:t}),kZ.push([n,r,e,o])):Jk.push([e,r,t]):(n[r]=t,kZ.push([n,r,e]))}function kbe(t,e,r,n,o,i,a){i+=1;var s;if(typeof t=="object"&&t!==null){for(s=0;s<n.length;s++)if(n[s]===t){Fbe(kmr,t,e,o);return}if(typeof a.depthLimit<"u"&&i>a.depthLimit){Fbe(X5e,t,e,o);return}if(typeof a.edgesLimit<"u"&&r+1>a.edgesLimit){Fbe(X5e,t,e,o);return}if(n.push(t),Array.isArray(t))for(s=0;s<t.length;s++)kbe(t[s],s,s,n,t,i,a);else{t=Q5e(t);var u=Object.keys(t);for(s=0;s<u.length;s++){var l=u[s];kbe(t[l],l,s,n,t,i,a)}}n.pop()}}function Umr(t){return t=typeof t<"u"?t:function(e,r){return r},function(e,r){if(Jk.length>0)for(var n=0;n<Jk.length;n++){var o=Jk[n];if(o[1]===e&&o[0]===r){r=o[2],Jk.splice(n,1);break}}return t.call(this,e,r)}}var X5e,kmr,kZ,Jk,$mr,e9e=w(()=>{EO();X5e="[...]",kmr={result:"[Circular]"},kZ=[],Jk=[],$mr=new TextEncoder});function t9e(t){let e=hZ(),r=$8e(),n=t.extra??{},o=n.metadata;return t.extra={...n,runtime:{...e,...n?.runtime},metadata:{...r,...r.revision_id||"revision_id"in t&&t.revision_id?{revision_id:("revision_id"in t?t.revision_id:void 0)??r.revision_id}:{},...o}},t}async function Vmr(t){let e=[];for await(let r of t)e.push(r);return e}function $be(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}function r9e(t){return typeof t=="number"?Number(t.toFixed(4)):t}function o9e(t){return"dataset_id"in t||"dataset_name"in t}var qmr,Hmr,Wmr,zbe,Kmr,Gmr,n9e,Y1,Zye=w(()=>{G1();q8e();sbe();eVe();tVe();EO();mZ();rVe();gbe();J5e();Lbe();fZ();e9e();qmr=t=>{let e=t?.toString()??$l("TRACING_SAMPLING_RATE");if(e===void 0)return;let r=parseFloat(e);if(r<0||r>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${r}`);return r},Hmr=t=>{let r=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return r==="localhost"||r==="127.0.0.1"||r==="::1"};Wmr=async t=>{if(t?.status===429){let e=parseInt(t.headers.get("retry-after")??"30",10)*1e3;if(e>0)return await new Promise(r=>setTimeout(r,e)),!0}return!1};zbe=class{constructor(){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0})}peek(){return this.items[0]}push(e){let r,n=new Promise(i=>{r=i}),o=Fp(e.item,`Serializing run with id: ${e.item.id}`).length;return this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:r,itemPromise:n,size:o}),this.sizeBytes+=o,n}pop(e){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");let r=[],n=0;for(;n+(this.peek()?.size??0)<e&&this.items.length>0;){let o=this.items.shift();o&&(r.push(o),n+=o.size,this.sizeBytes-=o.size)}if(r.length===0&&this.items.length>0){let o=this.items.shift();r.push(o),n+=o.size,this.sizeBytes-=o.size}return[r.map(o=>({action:o.action,item:o.payload,otelContext:o.otelContext,apiKey:o.apiKey,apiUrl:o.apiUrl})),()=>r.forEach(o=>o.itemPromiseResolve())]}},Kmr=20971520,Gmr=2500,n9e="https://api.smith.langchain.com",Y1=class t{constructor(e={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tim
`),r}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn(`[WARNING]:LangSmithfailedtofetchinfoonsupportedoperationswithstatuscode${e.status}.Fallingbacktobatchoperationsanddefaultlimits.`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){let e=await this._getBatchSizeLimitBytes();await this.drainAutoBatchQueue(e)}_cloneCurrentOTELContext(){let e=yZ(),r=B8e();if(this.langSmithToOTELTranslator!==void 0){let n=e.getActiveSpan();if(n)return e.setSpan(r.active(),n)}}async createRun(e,r){if(!this._filterForSampling([e]).length)return;let n={...this.headers,"Content-Type":"application/json"},o=e.project_name;delete e.project_name;let i=await this.prepareRunCreateOrUpdateInputs({session_name:o,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&i.trace_id!==void 0&&i.dotted_order!==void 0){let u=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:i,otelContext:u,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}let a=t9e(i);r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey);let s=await this.caller.call(Vt(this.debug),`${r?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:n,body:Fp(a,`Creatingrunwithid:${a.id}`),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await nn(s,"create run",!0)}async batchIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let o=await Promise.all(e?.map(u=>this.prepareRunCreateOrUpdateInputs(u))??[]),i=await Promise.all(r?.map(u=>this.prepareRunCreateOrUpdateInputs(u))??[]);if(o.length>0&&i.length>0){let u=o.reduce((c,d)=>(d.id&&(c[d.id]=d),c),{}),l=[];for(let c of i)c.id!==void 0&&u[c.id]?u[c.id]={...u[c.id],...c}:l.push(c);o=Object.values(u),i=l}let a={post:o,patch:i};if(!a.post.length&&!a.patch.length)return;let s={post:[],patch:[]};for(let u of["post","patch"]){let l=u,c=a[l].reverse(),d=c.pop();for(;d!==void 0;)s[l].push(d),d=c.pop()}if(s.post.length>0||s.patch.length>0){let u=s.post.map(l=>l.id).concat(s.patch.map(l=>l.id)).join(",");await this._postBatchIngestRuns(Fp(s,`Ingestingrunswithids:${u}`),n)}}async _postBatchIngestRuns(e,r){let n={...this.headers,"Content-Type":"application/json",Accept:"application/json"};r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey);let o=await this.batchIngestCaller.call(Vt(this.debug),`${r?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:n,body:e,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await nn(o,"batch create run",!0)}async multipartIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let o={},i=[];for(let d of e??[]){let f=await this.prepareRunCreateOrUpdateInputs(d);f.id!==void 0&&f.attachments!==void 0&&(o[f.id]=f.attachments),delete f.attachments,i.push(f)}let a=[];for(let d of r??[])a.push(await this.prepareRunCreateOrUpdateInputs(d));if(i.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(a.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(i.length>0&&a.length>0){let d=i.reduce((p,m)=>(m.id&&(p[m.id]=m),p),{}),f=[];for(let p of a)p.id!==void 0&&d[p.id]?d[p.id]={...d[p.id],...p}:f.push(p);i=Object.values(d),a=f}if(i.length===0&&a.length===0)return;let l=[],c=[];for(let[d,f]of[["post",i],["patch",a]])for(let p of f){let{inputs:m,outputs:h,events:b,attachments:g,...y}=p,x={inputs:m,outputs:h,events:b},S=Fp(y,`Serializingformultipartingestionofrunwithid:${y.id}`);c.push({name:`${d}.${y.id}`,payload:new Blob([S],{type:`application/json;length=${S.length}`})});for(let[O,E]of Object.entries(
`),i.close()}})}async_sendMultipartRequest(e,r,n){leto="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),i=F8e(),a=()=>this._createNodeFetchBody(e,o),s=()=>this._createMultipartStream(e,o),u=asyncl=>{letc={...this.headers,"Content-Type":`multipart/form-data; boundary=${o}`};returnn?.apiKey!==void0&&(c["x-api-key"]=n.apiKey),this.batchIngestCaller.call(Vt(this.debug),`${n?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:c,body:l,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})};try{letl,c=!1;!i&&!this.multipartStreamingDisabled?(c=!0,l=awaitu(awaits())):l=awaitu(awaita()),(!this.multipartStreamingDisabled||c)&&l.status===422&&(n?.apiUrl??this.apiUrl)!==n9e&&(console.warn(`Streaming multipart upload to ${n?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${r}".`),this.multipartStreamingDisabled=!0,l=awaitu(awaita())),awaitnn(l,"ingest multipart runs",!0)}catch(l){console.warn(`${l.message.trim()}
Context: ${r}`)}}asyncupdateRun(e,r,n){Jr(e),r.inputs&&(r.inputs=awaitthis.processInputs(r.inputs)),r.outputs&&(r.outputs=awaitthis.processOutputs(r.outputs));leto={...r,id:e};if(!this._filterForSampling([o],!0).length)return;if(this.autoBatchTracing&&o.trace_id!==void0&&o.dotted_order!==void0){lets=this._cloneCurrentOTELContext();if(r.end_time!==void0&&o.parent_run_id===void0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){awaitthis.processRunOperation({action:"update",item:o,otelContext:s,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}elsethis.processRunOperation({action:"update",item:o,otelContext:s,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}leti={...this.headers,"Content-Type":"application/json"};n?.apiKey!==void0&&(i["x-api-key"]=n.apiKey);leta=awaitthis.caller.call(Vt(this.debug),`${n?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:i,body:Fp(r,`Serializing payload to update run with id: ${e}`),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});awaitnn(a,"update run",!0)}asyncreadRun(e,{loadChildRuns:r}={loadChildRuns:!1}){Jr(e);letn=awaitthis._get(`/runs/${e}`);returnr&&(n=awaitthis._loadChildRuns(n)),n}asyncgetRunUrl({runId:e,run:r,projectOpts:n}){if(r!==void0){leto;r.session_id?o=r.session_id:n?.projectName?o=(awaitthis.readProject({projectName:n?.projectName})).id:n?.projectId?o=n?.projectId:o=(awaitthis.readProject({projectName:$l("PROJECT")||"default"})).id;leti=awaitthis._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${o}/r/${r.id}?poll=true`}elseif(e!==void0){leto=awaitthis.readRun(e);if(!o.app_path)thrownewError(`Run ${e} has no app_path`);return`${this.getHostUrl()}${o.app_path}`}elsethrownewError("Must provide either runId or run")}async_loadChildRuns(e){letr=awaitVmr(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),n={},o={};r.sort((i,a)=>(i?.dotted_order??"").localeCompare(a?.dotted_order??""));for(letiofr){if(i.parent_run_id===null||i.parent_run_id===void0)thrownewError(`Child run ${i.id} has no parent`);i.dotted_order?.startsWith(e.dotted_order??"")&&i.id!==e.id&&(i.parent_run_idinn||(n[i.parent_run_id]=[]),n[i.parent_run_id].push(i),o[i.id]=i)}e.child_runs=n[e.id]||[];for(letiinn)i!==e.id&&(o[i].child_runs=n[i]);returne}async*listRuns(e){let{projectId:r,projectName:n,parentRunId:o,traceId:i,referenceExampleId:a,startTime:s,executionOrder:u,isRoot:l,runType:c,error:d,id:f,query:p,filter:m,traceFilter:h,treeFilter:b,limit:g,select:y,order:x}=e,S=[];if(r&&(S=Array.isArray(r)?r:[r]),n){letA=Array.isArray(n)?n:[n],I=awaitPromise.all(A.map(R=>this.readProject({projectName:R}).then(N=>N.id)));S.push(...I)}letO=["app_path","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],E={session:S.length?S:null,run_type:c,reference_example:a,query:p,filter:m,trace_filter:h,tree_filter:b,execution_order:u,parent_run:o,start_time:s?s.toISOString():null,error:d,id:f,limit:g,trace:i,select:y||O,is_root:l,order:x},P=0;forawait(letAofthis._getCursorPaginatedList("/runs/query",E))if(g){if(P>=g)break;if(A.length+P>g){yield*A.slice(0,g-P);break}P+=A.length,yield*A}elseyield*A}async*listGroupRuns(e){let{projectId:r,projectName:n,groupBy:o,filter:i,startTime:a,endTime:s,limit:u,offset:l}=e,d={session_id:r||(awaitthis.readProject({projectName:n})).id,group_by:o,filter:i,start_time:a?a.toISOString():null,end_time:s?s.toISOString():null,limit:Number(u)||100},f=Number(l)||0,p="/runs/group",m=`${this.apiUrl}${p}`;for(;;){leth={...d,offset:f},b=Object.fromEntries(Object.entries(h).filter(([O,E])=>E!==void0)),g=awaitthis.caller.call(Vt(),m,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(b),signal:AbortSignal.timeout(this.timeout_ms),...this.fet
`):"Unspecified error"}`):new Error(`Failedtolistsharedexamples:${i.status}${i.statusText}`);return a.map(s=>({...s,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:r=null,metadata:n=null,upsert:o=!1,projectExtra:i=null,referenceDatasetId:a=null}){let s=o?"?upsert=true":"",u=`${this.apiUrl}/sessions${s}`,l=i||{};n&&(l.metadata=n);let c={name:e,extra:l,description:r};a!==null&&(c.reference_dataset_id=a);let d=await this.caller.call(Vt(this.debug),u,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(c),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await nn(d,"create project"),await d.json()}async updateProject(e,{name:r=null,description:n=null,metadata:o=null,projectExtra:i=null,endTime:a=null}){let s=`${this.apiUrl}/sessions/${e}`,u=i;o&&(u={...u||{},metadata:o});let l={name:r,extra:u,description:n,end_time:a?new Date(a).toISOString():null},c=await this.caller.call(Vt(this.debug),s,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(l),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await nn(c,"update project"),await c.json()}async hasProject({projectId:e,projectName:r}){let n="/sessions",o=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)Jr(e),n+=`/${e}`;else if(r!==void 0)o.append("name",r);else throw new Error("Must provide projectName or projectId");let i=await this.caller.call(Vt(this.debug),`${this.apiUrl}${n}?${o}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});try{let a=await i.json();return i.ok?Array.isArray(a)?a.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:r,includeStats:n}){let o="/sessions",i=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)Jr(e),o+=`/${e}`;else if(r!==void 0)i.append("name",r);else throw new Error("Must provide projectName or projectId");n!==void 0&&i.append("include_stats",n.toString());let a=await this._get(o,i),s;if(Array.isArray(a)){if(a.length===0)throw new Error(`Project[id=${e},name=${r}]notfound`);s=a[0]}else s=a;return s}async getProjectUrl({projectId:e,projectName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either projectName or projectId");let n=await this.readProject({projectId:e,projectName:r}),o=await this._getTenantId();return`${this.getHostUrl()}/o/${o}/projects/p/${n.id}`}async getDatasetUrl({datasetId:e,datasetName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");let n=await this.readDataset({datasetId:e,datasetName:r}),o=await this._getTenantId();return`${this.getHostUrl()}/o/${o}/datasets/${n.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;let e=new URLSearchParams({limit:"1"});for await(let r of this._getPaginated("/sessions",e))return this._tenantId=r[0].tenant_id,r[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:r,nameContains:n,referenceDatasetId:o,referenceDatasetName:i,referenceFree:a,metadata:s}={}){let u=new URLSearchParams;if(e!==void 0)for(let l of e)u.append("id",l);if(r!==void 0&&u.append("name",r),n!==void 0&&u.append("name_contains",n),o!==void 0)u.append("reference_dataset",o);else if(i!==void 0){let l=await this.readDataset({datasetName:i});u.append("reference_dataset",l.id)}a!==void 0&&u.append("reference_free",a.toString()),s!==void 0&&u.append("metadata",JSON.stringify(s));for await(let l of this._getPaginated("/sessions",u))yield*l}async deleteProject({projectId:e,projectName:r}){let n;if(e===void 0&&r===void 0)throw new Error("Must provide projectName or projectId");if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");e===void 0?n=(await this.readProject({projectName:r})).id:n=e,Jr(n);let o=await this.caller.call(Vt(this.debug),`${this.a
`).map(s=>JSON.parse(s))}async*listDatasets({limit:e=100,offset:r=0,datasetIds:n,datasetName:o,datasetNameContains:i,metadata:a}={}){let s="/datasets",u=new URLSearchParams({limit:e.toString(),offset:r.toString()});if(n!==void 0)for(let l of n)u.append("id",l);o!==void 0&&u.append("name",o),i!==void 0&&u.append("name_contains",i),a!==void 0&&u.append("metadata",JSON.stringify(a));for await(let l of this._getPaginated(s,u))yield*l}async updateDataset(e){let{datasetId:r,datasetName:n,...o}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let i=r??(await this.readDataset({datasetName:n})).id;Jr(i);let a=await this.caller.call(Vt(this.debug),`${this.apiUrl}/datasets/${i}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await nn(a,"update dataset"),await a.json()}async updateDatasetTag(e){let{datasetId:r,datasetName:n,asOf:o,tag:i}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let a=r??(await this.readDataset({datasetName:n})).id;Jr(a);let s=await this.caller.call(Vt(this.debug),`${this.apiUrl}/datasets/${a}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({as_of:typeof o=="string"?o:o.toISOString(),tag:i}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await nn(s,"update dataset tags")}async deleteDataset({datasetId:e,datasetName:r}){let n="/datasets",o=e;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(r!==void 0&&(o=(await this.readDataset({datasetName:r})).id),o!==void 0)Jr(o),n+=`/${o}`;else throw new Error("Must provide datasetName or datasetId");let i=await this.caller.call(Vt(this.debug),this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await nn(i,`delete${n}`),await i.json()}async indexDataset({datasetId:e,datasetName:r,tag:n}){let o=e;if(!o&&!r)throw new Error("Must provide either datasetName or datasetId");if(o&&r)throw new Error("Must provide either datasetName or datasetId, not both");o||(o=(await this.readDataset({datasetName:r})).id),Jr(o);let i={tag:n},a=await this.caller.call(Vt(this.debug),`${this.apiUrl}/datasets/${o}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await nn(a,"index dataset"),await a.json()}async similarExamples(e,r,n,{filter:o}={}){let i={limit:n,inputs:e};o!==void 0&&(i.filter=o),Jr(r);let a=await this.caller.call(Vt(this.debug),`${this.apiUrl}/datasets/${r}/search`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await nn(a,"fetch similar examples"),(await a.json()).examples}async createExample(e,r,n){if(o9e(e)&&(r!==void 0||n!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let o=r?n?.datasetId:e.dataset_id,i=r?n?.datasetName:e.dataset_name;if(o===void 0&&i===void 0)throw new Error("Must provide either datasetName or datasetId");if(o!==void 0&&i!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");o===void 0&&(o=(await this.readDataset({datasetName:i})).id);let a=(r?n?.createdAt:e.created_at)||new Date,s;o9e(e)?s=e:s={inputs:e,outputs:r,created_at:a?.toISOString(),id:n?.exampleId,metadata:n?.metadata,split:n?.split,source_run_id:n?.sourceRunId,use_source_run_io:n?.useSourceRunIO,use_source_run_attachments:n?.useSourceRunAttachments,attachments:n?.attachments};let u=await this._uploadExamplesMultipart(o,[s]);return await this.readExample(u.example_ids?.[0]??_s())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];let y=e,x=y[0].dataset_id,S=y[0].dataset_name;if(x===void 0&&S===void 0)throw new Error("Must provide either datasetName or datasetId");if(x!==void 0&&S!==void 0)throw new
${o}`);throwi.statusCode=r.status,i}if(n.commits.length!==0)returnn.commits[0].commit_hash}async_likeOrUnlikePrompt(e,r){let[n,o,i]=IO(e),a=awaitthis.caller.call(Vt(this.debug),`${this.apiUrl}/likes/${n}/${o}`,{method:"POST",body:JSON.stringify({like:r}),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});returnawaitnn(a,`${r?"like":"unlike"} prompt`),awaita.json()}async_getPromptUrl(e){let[r,n,o]=IO(e);if(awaitthis._currentTenantIsOwner(r)){leti=awaitthis._getSettings();returno!=="latest"?`${this.getHostUrl()}/prompts/${n}/${o.substring(0,8)}?organizationId=${i.id}`:`${this.getHostUrl()}/prompts/${n}?organizationId=${i.id}`}elsereturno!=="latest"?`${this.getHostUrl()}/hub/${r}/${n}/${o.substring(0,8)}`:`${this.getHostUrl()}/hub/${r}/${n}`}asyncpromptExists(e){return!!awaitthis.getPrompt(e)}asynclikePrompt(e){returnthis._likeOrUnlikePrompt(e,!0)}asyncunlikePrompt(e){returnthis._likeOrUnlikePrompt(e,!1)}async*listCommits(e){forawait(letrofthis._getPaginated(`/commits/${e}/`,newURLSearchParams,n=>n.commits))yield*r}async*listPrompts(e){letr=newURLSearchParams;r.append("sort_field",e?.sortField??"updated_at"),r.append("sort_direction","desc"),r.append("is_archived",(!!e?.isArchived).toString()),e?.isPublic!==void0&&r.append("is_public",e.isPublic.toString()),e?.query&&r.append("query",e.query);forawait(letnofthis._getPaginated("/repos",r,o=>o.repos))yield*n}asyncgetPrompt(e){let[r,n,o]=IO(e),i=awaitthis.caller.call(Vt(this.debug),`${this.apiUrl}/repos/${r}/${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(i.status===404)returnnull;awaitnn(i,"get prompt");leta=awaiti.json();returna.repo?a.repo:null}asynccreatePrompt(e,r){letn=awaitthis._getSettings();if(r?.isPublic&&!n.tenant_handle)thrownewError(`Cannot create a public prompt without first
https://smith.langchain.com/prompts`);let[o,i,a]=IO(e);if(!awaitthis._currentTenantIsOwner(o))throwawaitthis._ownerConflictError("create a prompt",o);lets={repo_handle:i,...r?.description&&{description:r.description},...r?.readme&&{readme:r.readme},...r?.tags&&{tags:r.tags},is_public:!!r?.isPublic},u=awaitthis.caller.call(Vt(this.debug),`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});awaitnn(u,"create prompt");let{repo:l}=awaitu.json();returnl}asynccreateCommit(e,r,n){if(!awaitthis.promptExists(e))thrownewError("Prompt does not exist, you must create it first.");let[o,i,a]=IO(e),s=n?.parentCommitHash==="latest"||!n?.parentCommitHash?awaitthis._getLatestCommitHash(`${o}/${i}`):n?.parentCommitHash,u={manifest:JSON.parse(JSON.stringify(r)),parent_commit:s},l=awaitthis.caller.call(Vt(this.debug),`${this.apiUrl}/commits/${o}/${i}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(u),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});awaitnn(l,"create commit");letc=awaitl.json();returnthis._getPromptUrl(`${o}/${i}${c.commit_hash?`:${c.commit_hash}`:""}`)}asyncupdateExamplesMultipart(e,r=[]){returnthis._updateExamplesMultipart(e,r)}async_updateExamplesMultipart(e,r=[]){if(!awaitthis._getMultiPartSupport())thrownewError("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");letn=newFormData;for(letsofr){letu=s.id,l={...s.metadata&&{metadata:s.metadata},...s.split&&{split:s.split}},c=Fp(l,`Serializing body for example with id: ${u}`),d=newBlob([c],{type:"application/json"});if(n.append(u,d),s.inputs){letf=Fp(s.inputs,`Serializing inputs for example with id: ${u}`),p=newBlob([f],{type:"application/json"});n.append(`${u}.inputs`,p)}if(s.outputs){letf=Fp(s.outputs,`Serializing outputs whle updating example with id: ${u}`),p=newBlob([f],{type:"application/json"});n.append(`${u}.outputs`,p)}if(s.attachments)for(let[f,p]ofObject.entries(s.attachments)){letm,h;Array.isArray(p)?[m,h]=p:(m=p.mimeType,h=p.data);letb=newBlob([h],{type:`${m}; length=${h.byteLength}`});n.append(`${u}.attachment.${f}`,b)}if(s.attachments_operations){letf=Fp(s.attachments_operations,`Serializing attachments while updating example with id: ${u}`),p=newBlob([f],{type:"application/json"});n.append(`${u}.attachments_operations`,p)}}leto=e??r[0]?.dataset_id;returnawait(awaitthis.caller.call(Vt(this.debug),`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${o}/examples`)}`,{method:"PATCH",headers:this.headers,body:n})).json()}asyncuploadExamplesMultipart(e,r=[]){returnthis._uploadExamplesMultipart(e,r)}async_uploadExamplesMultipart(e,r=[]){if(!awaitthis._getMultiPartSupport())thrownewError("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");letn=newFormData;for(letaofr){lets=(a.id??_s()).toString(),u={created_at:a.created_at,...a.metadata&&{metadata:a.metadata},...a.split&&{split:a.split},...a.source_run_id&&{source_run_id:a.source_run_id},...a.use_source_run_io&&{use_source_run_io:a.use_source_run_io},...a.use_source_run_attachments&&{use_source_run_attachments:a.use_source_run_attachments}},l=Fp(u,`Serializing body for uploaded example with id: ${s}`),c=newBlob([l],{type:"application/json"});if(n.append(s,c),a.inputs){letd=Fp(a.inputs,`Serializing inputs for uploaded example with id: ${s}`),f=newBlob([d],{type:"application/json"});n.append(`${s}.inputs`,f)}if(a.outputs){letd=Fp(a.outputs,`Serializing outputs for uploaded example with id: ${s}`),f=newBlob([d],{type:"application/json"});n.append(`${s}.outputs`,f)}if(a.attachments)for(let[d,f]ofObject.entries(a.attachments)){letp,m;Array.isArray(f)?[p,m]=f:(p=f.mimeType,m=f.data);leth=newBlob([m],{type:`${p}; length=${m.byteLength}`});n.append(`${s}.attachment.${d}`,h)}}leto=
`&&!o?i="\\n":i==="\\"?o=!o:o=!1;elseif(i==='"')n=!0,o=!1;elseif(i==="{")r.push("}");elseif(i==="[")r.push("]");elseif(i==="}"||i==="]")if(r&&r[r.length-1]===i)r.pop();elsereturnnull;e+=i}n&&(e+='"');for(leti=r.length-1;i>=0;i-=1)e+=r[i];try{returnJSON.parse(e)}catch{returnnull}}varXbe=w(()=>{});functionJy(t){returntypeoft=="object"&&t!==null&&"type"int&&typeoft.type=="string"&&"source_type"int&&(t.source_type==="url"||t.source_type==="base64"||t.source_type==="text"||t.source_type==="id")}functionj9e(t){returnJy(t)&&t.source_type==="url"&&"url"int&&typeoft.url=="string"}functionD9e(t){returnJy(t)&&t.source_type==="base64"&&"data"int&&typeoft.data=="string"}functionL9e(t){if(Jy(t)){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url}};if(t.source_type==="base64"){if(!t.mime_type)thrownewError("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${t.mime_type};base64,${t.data}`}}}}thrownewError("Unsupported source type. Only 'url' and 'base64' are supported.")}functionQbe(t){lete=t.split(";")[0].split("/");if(e.length!==2)thrownewError(`Invalid mime type: "${t}" - does not match type/subtype format.`);letr=e[0].trim(),n=e[1].trim();if(r===""||n==="")thrownewError(`Invalid mime type: "${t}" - type or subtype is empty.`);leto={};for(letioft.split(";").slice(1)){leta=i.split("=");if(a.length!==2)thrownewError(`Invalid parameter syntax in mime type: "${t}".`);lets=a[0].trim(),u=a[1].trim();if(s==="")thrownewError(`Invalid parameter syntax in mime type: "${t}".`);o[s]=u}return{type:r,subtype:n,parameters:o}}functionXk({dataUrl:t,asTypedArray:e=!1}){letr=t.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/),n;if(r){n=r[1].toLowerCase();leto=e?Uint8Array.from(atob(r[2]),i=>i.charCodeAt(0)):r[2];return{mime_type:n,data:o}}}functionSH(t,e){if(t.type==="text"){if(!e.fromStandardTextBlock)thrownewError(`Converter for ${e.providerName} does not implement \`fromStandardTextBlock\` method.`);returne.fromStandardTextBlock(t)}if(t.type==="image"){if(!e.fromStandardImageBlock)thrownewError(`Converter for ${e.providerName} does not implement \`fromStandardImageBlock\` method.`);returne.fromStandardImageBlock(t)}if(t.type==="audio"){if(!e.fromStandardAudioBlock)thrownewError(`Converter for ${e.providerName} does not implement \`fromStandardAudioBlock\` method.`);returne.fromStandardAudioBlock(t)}if(t.type==="file"){if(!e.fromStandardFileBlock)thrownewError(`Converter for ${e.providerName} does not implement \`fromStandardFileBlock\` method.`);returne.fromStandardFileBlock(t)}thrownewError(`Unable to convert content block type '${t.type}' to provider-specific format: not recognized.`)}vare_e=w(()=>{});functionog(t,e){returntypeoft=="string"?t===""?e:typeofe=="string"?t+e:Array.isArray(e)&&e.some(r=>Jy(r))?[{type:"text",source_type:"text",text:t},...e]:[{type:"text",text:t},...e]:Array.isArray(e)?CH(t,e)??[...t,...e]:e===""?t:Array.isArray(t)&&t.some(r=>Jy(r))?[...t,{type:"file",source_type:"text",text:e}]:[...t,{type:"text",text:e}]}functionF9e(t,e){returnt==="error"||e==="error"?"error":"success"}functionghr(t,e){functionr(n,o){if(typeofn!="object"||n===null||n===void0)returnn;if(o>=e)returnArray.isArray(n)?"[Array]":"[Object]";if(Array.isArray(n))returnn.map(a=>r(a,o+1));leti={};for(letaofObject.keys(n))i[a]=r(n[a],o+1);returni}returnJSON.stringify(r(t,0),null,2)}functionFs(t,e){letr={...t};for(let[n,o]ofObject.entries(e))if(r[n]==null)r[n]=o;else{if(o==null)continue;if(typeofr[n]!=typeofo||Array.isArray(r[n])!==Array.isArray(o))thrownewError(`field[${n}] already exists in the message chunk, but with a different type.`);if(typeofr[n]=="string"){if(n==="type")continue;r[n]+=o}elseif(typeofr[n]=="object"&&!Array.isArray(r[n]))r[n]=Fs(r[n],o);elseif(Array.isArray(r[n]))r[n]=CH(r[n],o);else{if(r[n]===o)continue;console.warn(`field[${n}] already exists in this message chunk and value has unsupported type.`)}}returnr}functionCH(t,e){if(!(t===void0&&e===void0)){if(t===void0||e===void0)retur
`}}letc={};for(letpofe){letm=p.source.split(":"),h=p.target.split(":"),b=m.filter((g,y)=>g===h[y]).join(":");c[b]||(c[b]=[]),c[b].push(p)}letd=newSet;functionf(p,m){leth=p.length===1&&p[0].source===p[0].target;if(m&&!h){letb=m.split(":").pop();if(d.has(b))thrownewError(`Found duplicate subgraph '${b}' -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(b),l+=` subgraph ${b}
`}for(letbinc)b.startsWith(`${m}:`)&&b!==m&&f(c[b],b);m&&!h&&(l+=` end
`)}f(c[""]??[],"");for(letpinc)!p.includes(":")&&p!==""&&f(c[p],p);returna&&(l+=Ahr(i??{})),l}asyncfunctionlWe(t,e){let{backgroundColor:r="white"}=e??{},n=btoa(t);r!==void0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`));leto=`https://mermaid.ink/img/${n}?bgColor=${r}`,i=awaitfetch(o);if(!i.ok)thrownewError(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${i.status}`,`Status text: ${i.statusText}`].join(`
`));returnawaiti.blob()}varThr,cWe=w(()=>{Thr=["*","_","`"]});functioni$(t,e,r){functionn(s,u){varl;Object.defineProperty(s,"_zod",{value:s._zod??{},enumerable:!1}),(l=s._zod).traits??(l.traits=newSet),s._zod.traits.add(t),e(s,u);for(letcina.prototype)cins||Object.defineProperty(s,c,{value:a.prototype[c].bind(s)});s._zod.constr=a,s._zod.def=u}leto=r?.Parent??Object;classiextendso{}Object.defineProperty(i,"name",{value:t});functiona(s){varu;letl=r?.Parent?newi:this;n(l,s),(u=l._zod).deferred??(u.deferred=[]);for(letcofl._zod.deferred)c();returnl}returnObject.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:s=>r?.Parent&&sinstanceofr.Parent?!0:s?._zod?.traits?.has(t)}),Object.defineProperty(a,"name",{value:t}),a}functiona$(t){returnt&&Object.assign(b_e,t),b_e}varE6n,T6n,eA,b_e,jH=w(()=>{E6n=Object.freeze({status:"aborted"});T6n=Symbol("zod_brand"),eA=classextendsError{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},b_e={}});function__e(t){lete=Object.values(t).filter(n=>typeofn=="number");returnObject.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}functionfWe(t,e){returntypeofe=="bigint"?e.toString():e}functionpWe(t){return{getvalue(){{letr=t();returnObject.defineProperty(this,"value",{value:r}),r}thrownewError("cached value already set")}}}functions$(t,e,r){letn=newt._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}functionmWe(t){lete=t;if(!e)return{};if(typeofe=="string")return{error:()=>e};if(e?.message!==void0){if(e?.error!==void0)thrownewError("Cannot specify both `message` and `error` params");e.error=e.message}returndeletee.message,typeofe.error=="string"?{...e,error:()=>e.error}:e}functionnY(t,e=0){for(letr=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}functionrY(t){returntypeoft=="string"?t:t?.message}functionu$(t,e,r){letn={...t,path:t.path??[]};if(!t.message){leto=rY(t.inst?._zod.def?.error?.(t))??rY(e?.error?.(t))??rY(r.customError?.(t))??rY(r.localeError?.(t))??"Invalid input";n.message=o}returndeleten.inst,deleten.continue,e?.reportInput||deleten.input,n}varv_e,Ihr,A6n,tA=w(()=>{v_e=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{},Ihr=pWe(()=>{if(typeofnavigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{lett=Function;returnnewt(""),!0}catch{return!1}});A6n={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]}});varhWe,gWe,DH,w_e=w(()=>{jH();tA();hWe=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){returnJSON.stringify(e,fWe,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},gWe=i$("$ZodError",hWe),DH=i$("$ZodError",hWe,{Parent:Error})});varRhr,oY,Nhr,yWe,jhr,bWe,Dhr,_We,x_e=w(()=>{jH();w_e();tA();Rhr=t=>(e,r,n,o)=>{leti=n?Object.assign(n,{async:!1}):{async:!1},a=e._zod.run({value:r,issues:[]},i);if(ainstanceofPromise)throwneweA;if(a.issues.length){lets=new(o?.Err??t)(a.issues.map(u=>u$(u,i,a$())));throwv_e(s,o?.callee),s}returna.value},oY=Rhr(DH),Nhr=t=>async(e,r,n,o)=>{leti=n?Object.assign(n,{async:!0}):{async:!0},a=e._zod.run({value:r,issues:[]},i);if(ainstanceofPromise&&(a=awaita),a.issues.length){lets=new(o?.Err??t)(a.issues.map(u=>u$(u,i,a$())));throwv_e(s,o?.callee),s}returna.value},yWe=Nhr(DH),jhr=t=>(e,r,n)=>{leto=n?{...n,async:!1}:{async:!1},i=e._zod.run({value:r,issues:[]},o);if(iinstanceofPromise)throwneweA;returni.issues.length?{success:!1,error:new(t??gWe)(i.issues.map(a=>u$(a,o,a$())))}:{success:!0,data:i.value}},bWe=jhr(DH),Dhr=t=>async(e,r,n)=>{leto=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},o);returniinstanceofPromise&&(i=awaiti),i.issues.length?{succe
Setthe\`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(letcofthis.seen.entries()){letd=c[1];if(e===c[0]){a(c);continue}if(n.external){letp=n.external.registry.get(c[0])?.id;if(e!==c[0]&&p){a(c);continue}}if(this.metadataRegistry.get(c[0])?.id){a(c);continue}if(d.cycle){a(c);continue}if(d.count>1&&n.reused==="ref"){a(c);continue}}lets=(c,d)=>{letf=this.seen.get(c),p=f.def??f.schema,m={...p};if(f.ref===null)return;leth=f.ref;if(f.ref=null,h){s(h,d);letb=this.seen.get(h).schema;b.$ref&&d.target==="draft-7"?(p.allOf=p.allOf??[],p.allOf.push(b)):(Object.assign(p,b),Object.assign(p,m))}f.isParent||this.override({zodSchema:c,jsonSchema:p,path:f.path??[]})};for(letcof[...this.seen.entries()].reverse())s(c[0],{target:this.target});letu={};if(this.target==="draft-2020-12"?u.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?u.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){letc=n.external.registry.get(e)?.id;if(!c)thrownewError("Schema is missing an `id` property");u.$id=n.external.uri(c)}Object.assign(u,o.def);letl=n.external?.defs??{};for(letcofthis.seen.entries()){letd=c[1];d.def&&d.defId&&(l[d.defId]=d.def)}n.external||Object.keys(l).length>0&&(this.target==="draft-2020-12"?u.$defs=l:u.definitions=l);try{returnJSON.parse(JSON.stringify(u))}catch{thrownewError("Error converting schema to JSON.")}}}});varMWe=w(()=>{});varaY=w(()=>{jH();x_e();w_e();OWe();wWe();S_e();tA();vWe();PWe();C_e();xWe();AWe();TWe();IWe();MWe()});varNWe,RWe,jWe,sY=w(()=>{NWe=Symbol("Let zodToJsonSchema decide on which parser to use"),RWe={name:void0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},jWe=t=>typeoft=="string"?{...RWe,name:t}:{...RWe,...t}});varDWe,O_e=w(()=>{sY();DWe=t=>{lete=jWe(t),r=e.name!==void0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void0,seen:newMap(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void0}]))}}});functionP_e(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}functionto(t,e,r,n,o){t[e]=r,P_e(t,e,n,o)}varrA=w(()=>{});varQf=w(()=>{aH();aH()});functionLWe(){return{}}varE_e=w(()=>{});functionFWe(t,e){letr={type:"array"};returnt.type?._def&&t.type?._def?.typeName!==re.ZodAny&&(r.items=br(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&to(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&to(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(to(r,"minItems",t.exactLength.value,t.exactLength.message,e),to(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}varT_e=w(()=>{Qf();rA();nu()});functionkWe(t,e){letr={type:"integer",format:"int64"};if(!t.checks)returnr;for(letnoft.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?to(r,"minimum",n.value,n.message,e):to(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),to(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?to(r,"maximum",n.value,n.message,e):to(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),to(r,"maximum",n.value,n.message,e));break;case"multipleOf":to(r,"multipleOf",n.value,n.message,e);break}returnr}varA_e=w(()=>{rA()});function$We(){return{type:"boolean"}}varI_e=w(()=>{});functionuY(t,e){returnbr(t.type._def,e)}varlY=w(()=>{nu()});varzWe,M_e=w(()=>{nu();zWe=(t,e)=>br(t.innerType._def,e)});functionR_e(t,e,r){letn=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,i)=>R_e(t,e,o))};switch(n){case"
]`;continue}o+=n[u],n[u]==="\\"?i=!0:a&&n[u]==="]"?a=!1:!a&&n[u]==="["&&(a=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}var $_e,Xy,qhr,dY=w(()=>{rA();Xy={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>($_e===void 0&&($_e=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),$_e),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};qhr=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function fY(t,e){if(e.target==="openAi"&&console.warn("Warning:OpenAImaynotsupportrecordsinschemas!Tryanarrayofkey-valuepairsinstead."),e.target==="openApi3"&&t.keyType?._def.typeName===re.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:br(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:br(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===re.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=cY(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===re.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===re.ZodBranded&&t.keyType._def.type._def.typeName===re.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=uY(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var pY=w(()=>{Qf();nu();dY();lY()});function KWe(t,e){if(e.mapStrategy==="record")return fY(t,e);let r=br(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=br(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var B_e=w(()=>{nu();pY()});function GWe(t){let e=t.values,n=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}var U_e=w(()=>{});function JWe(){return{not:{}}}var q_e
Known schemas:
- ${Object.keys(n).join(`
- `)}`,new Error(Pe)}let ue=`${s}/$ref`,pe=da(t,Ne,r,n,o,i,a,ue,u);if(pe.valid||ce.push({instanceLocation:a,keyword:"$ref",keywordLocation:ue,error:"Asubschemahaderrors."},...pe.errors),r==="4"||r==="7")return{valid:ce.length===0,errors:ce}}if(Array.isArray(m)){let Ze=m.length,Ne=!1;for(let ue=0;ue<Ze;ue++)if(c===m[ue]||m[ue]==="integer"&&c==="number"&&t%1===0&&t===t){Ne=!0;break}Ne||ce.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${m.join('", "')}".`})}else m==="integer"?(c!=="number"||t%1||t!==t)&&ce.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${m}".`}):m!==void 0&&c!==m&&ce.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${m}".`});if(h!==void 0&&(c==="object"||c==="array"?jO(t,h)||ce.push({instanceLocation:a,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):t!==h&&ce.push({instanceLocation:a,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),b!==void 0&&(c==="object"||c==="array"?b.some(Ze=>jO(t,Ze))||ce.push({instanceLocation:a,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(b)}.`}):b.some(Ze=>t===Ze)||ce.push({instanceLocation:a,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(b)}.`})),y!==void 0){let Ze=`${s}/not`;da(t,y,r,n,o,i,a,Ze).valid&&ce.push({instanceLocation:a,keyword:"not",keywordLocation:Ze,error:'Instance matched "not" schema.'})}let qt=[];if(x!==void 0){let Ze=`${s}/anyOf`,Ne=ce.length,ue=!1;for(let pe=0;pe<x.length;pe++){let Pe=x[pe],Ae=Object.create(u),ot=da(t,Pe,r,n,o,p===!0?i:null,a,`${Ze}/${pe}`,Ae);ce.push(...ot.errors),ue=ue||ot.valid,ot.valid&&qt.push(Ae)}ue?ce.length=Ne:ce.splice(Ne,0,{instanceLocation:a,keyword:"anyOf",keywordLocation:Ze,error:"Instancedoesnotmatchanysubschemas."})}if(S!==void 0){let Ze=`${s}/allOf`,Ne=ce.length,ue=!0;for(let pe=0;pe<S.length;pe++){let Pe=S[pe],Ae=Object.create(u),ot=da(t,Pe,r,n,o,p===!0?i:null,a,`${Ze}/${pe}`,Ae);ce.push(...ot.errors),ue=ue&&ot.valid,ot.valid&&qt.push(Ae)}ue?ce.length=Ne:ce.splice(Ne,0,{instanceLocation:a,keyword:"allOf",keywordLocation:Ze,error:"Instancedoesnotmatcheverysubschema."})}if(O!==void 0){let Ze=`${s}/oneOf`,Ne=ce.length,ue=O.filter((pe,Pe)=>{let Ae=Object.create(u),ot=da(t,pe,r,n,o,p===!0?i:null,a,`${Ze}/${Pe}`,Ae);return ce.push(...ot.errors),ot.valid&&qt.push(Ae),ot.valid}).length;ue===1?ce.length=Ne:ce.splice(Ne,0,{instanceLocation:a,keyword:"oneOf",keywordLocation:Ze,error:`Instance does not match exactly one subschema (${ue} matches).`})}if((c==="object"||c==="array")&&Object.assign(u,...qt),E!==void 0){let Ze=`${s}/if`;if(da(t,E,r,n,o,i,a,Ze,u).valid){if(P!==void 0){let ue=da(t,P,r,n,o,i,a,`${s}/then`,u);ue.valid||ce.push({instanceLocation:a,keyword:"if",keywordLocation:Ze,error:'Instance does not match "then" schema.'},...ue.errors)}}else if(A!==void 0){let ue=da(t,A,r,n,o,i,a,`${s}/else`,u);ue.valid||ce.push({instanceLocation:a,keyword:"if",keywordLocation:Ze,error:'Instance does not match "else" schema.'},...ue.errors)}}if(c==="object"){if(g!==void 0)for(let pe of g)pe in t||ce.push({instanceLocation:a,keyword:"required",keywordLocation:`${s}/required`,error:`Instance does not have required property "${pe}".`});let Ze=Object.keys(t);if(k!==void 0&&Ze.length<k&&ce.push({instanceLocation:a,keyword:"minProperties",keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${k} properties.`}),H!==void 0&&Ze.length>H&&ce.push({instanceLocation:a,keyword:"maxProperties",keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${H} properties.`}),V!==void 0){let pe=`${s}/propertyNames`;for(let Pe in t){let Ae=`${a}/${Hm(Pe)}`,ot=da(Pe,V,r,n,o,i,Ae,pe);ot.valid||ce.push({instanceLocation:a,keyword:"propertyNames",keywordLocation:pe,error:`Property name "${Pe}" does not
`)),n.close()}});return af.fromReadableStream(r)}var xKe=w(()=>{L_()});function uve(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.iterator]=="function"&&typeof t.next=="function"}function _Y(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.asyncIterator]=="function"}function*lve(t,e){for(;;){let{value:r,done:n}=Yc.runWithConfig(Up(t),e.next.bind(e),!0);if(n)break;yield r}}async function*vY(t,e){let r=e[Symbol.asyncIterator]();for(;;){let{value:n,done:o}=await Yc.runWithConfig(Up(t),r.next.bind(e),!0);if(o)break;yield n}}var SKe,CKe=w(()=>{sN();j_();SKe=t=>t!=null&&typeof t=="object"&&"next"in t&&typeof t.next=="function"});function Ul(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}function Ngr(t){if(nZ(t))throw new Error("RunnableLambdarequiresafunctionthatisnotwrappedintraceablehigher-orderfunction.Thisshouldn't happen.")}function FO(t){if(typeof t=="function")return new tp({func:t});if(jn.isRunnable(t))return t;if(!Array.isArray(t)&&typeof t=="object"){let e={};for(let[r,n]of Object.entries(t))e[r]=FO(n);return new oA({steps:e})}else throw new Error(`Expected a Runnable, function or object.
Instead got an unsupported type.`)}function jgr(t,e){let r=e.name??t.getName(),n=e.description??nA(e.schema);return bY(e.schema)?new qH({name:r,description:n,schema:rn.object({input:rn.string()}).transform(o=>o.input),bound:t}):new qH({name:r,description:n,schema:e.schema,bound:t})}var cve,jn,$_,wY,UH,Pi,oA,dve,tp,xY,p$,SY,qH,sf=w(()=>{J7();cve=F(X7(),1);G1();Bye();nWe();iWe();Q1();L_();m_e();j_();o$();sWe();g_e();sN();vKe();xKe();CKe();qZ();LO();jn=class extends kp{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){let r=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${r}${e}`:r}bind(e){return new $_({bound:this,kwargs:e,config:{}})}map(){return new wY({bound:this})}withRetry(e){return new UH({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new $_({bound:this,config:e,kwargs:{}})}withFallbacks(e){let r=Array.isArray(e)?e:e.fallbacks;return new xY({runnable:this,fallbacks:r})}_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(_n);if(r>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");let n=Object.fromEntries(Object.entries(e).filter(([o])=>o!=="runId"));return Array.from({length:r},(o,i)=>_n(i===0?e:n))}return Array.from({length:r},()=>_n(e))}async batch(e,r,n){let o=this._getOptionsList(r??{},e.length),i=o[0]?.maxConcurrency??n?.maxConcurrency,a=new qm({maxConcurrency:i,onFailedAttempt:u=>{throw u}}),s=e.map((u,l)=>a.call(async()=>{try{return await this.invoke(u,o[l])}catch(c){if(n?.returnExceptions)return c;throw c}}));return Promise.all(s)}async*_streamIterator(e,r){yield this.invoke(e,r)}async stream(e,r){let n=_n(r),o=new NO({generator:this._streamIterator(e,n),config:n});return await o.setup,af.fromAsyncGenerator(o)}_separateRunnableConfigFromCallOptions(e){let r;e===void 0?r=_n(e):r=_n({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});let n={...e};return delete n.callbacks,delete n.tags,delete n.metadata,delete n.runName,delete n.configurable,delete n.recursionLimit,delete n.maxConcurrency,delete n.runId,delete n.timeout,delete n.signal,[r,n]}async _callWithConfig(e,r,n){let o=_n(n),a=await(await Bp(o))?.handleChainStart(this.toJSON(),Ul(r,"input"),o.runId,o?.runType,void 0,void 0,o?.runName??this.getName());delete o.runId;let s;try{let u=e.call(this,r,o,a);s=await D_(u,n?.signal)}catch(u){throw await a?.handleChainError(u),u}return await a?.handleChainEnd(Ul(s,"output")),s}async _batchWithConfig(e,r,n,o){let i=this._getOptionsList(n??{},r.length),a=await Promise.all(i.map(Bp)),s=await Promise.all(a.map(async(l,c)=>{let d=await l?.handleChainStart(this.toJSON(),Ul(r[c],"input"),i[c].runId,i[c].runType,void 0,void 0,i[c].runName??this.getName());return delete i[c].runId,d})),u;try{let l=e.call(this,r,i,s,o);u=await D_(l,i?.[0]?.signal)}catch(l){throw await Promise.all(s.map(c=>c?.handleChainError(l))),l}return await Promise.all(s.map(l=>l?.handleChainEnd(Ul(u,"output")))),u}async*_transformStreamWithConfig(e,r,n){let o,i=!0,a,s=!0,u=_n(n),l=await Bp(u);async function*c(){for await(let f of e){if(i)if(o===void 0)o=f;else try{o=fc(o,f)}catch{o=void 0,i=!1}yield f}}let d;try{let f=await Q9e(r.bind(this),c(),async()=>l?.handleChainStart(this.toJSON(),{input:""},u.runId,u.runType,void 0,void 0,u.runName??this.getName()),n?.signal,u);delete u.runId,d=f.setup;let p=d?.handlers.find(oWe),m=f.output;p!==void 0&&d!==void 0&&(m=p.tapOutputIterable(d.runId,m));let h=d?.handlers.find(rWe);h!==void 0&&d!==void 0&&(m=h.tapOutputIterable(d.runId,m));for await(let b of m)if(yield b,s)if(
"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.
Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!
Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
`)};rp.prototype.renderPartial=function(e,r,n,o){if(n){var i=this.getConfigTags(o),a=yve(n)?n(e[1]):n[e[1]];if(a!=null){var s=e[6],u=e[5],l=e[4],c=a;u==0&&l&&(c=this.indentPartial(a,l,s));var d=this.parse(c,i);return this.renderTokens(d,r,n,c,o)}}};rp.prototype.unescapedValue=function(e,r){var n=r.lookup(e[1]);if(n!=null)return n};rp.prototype.escapedValue=function(e,r,n){var o=this.getConfigEscape(n)||lg.escape,i=r.lookup(e[1]);if(i!=null)return typeof i=="number"&&o===lg.escape?String(i):o(i)};rp.prototype.rawValue=function(e){return e[1]};rp.prototype.getConfigTags=function(e){return _$(e)?e:e&&typeof e=="object"?e.tags:void 0};rp.prototype.getConfigEscape=function(e){if(e&&typeof e=="object"&&!_$(e))return e.escape};lg={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(t){KH.templateCache=t},get templateCache(){return KH.templateCache}},KH=new rp;lg.clearCache=function(){return KH.clearCache()};lg.parse=function(e,r){return KH.parse(e,r)};lg.render=function(e,r,n,o){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+Lgr(e)+'" was given as the first argument for mustache#render(template, view, partials)');return KH.render(e,r,n,o)};lg.escape=qgr;lg.Scanner=GH;lg.Context=b$;lg.Writer=rp;EY=lg});function $Ke(){EY.escape=t=>t}var JH,zKe,TY,Ygr,Xgr,bve,Qgr,Kp,ZH,mN,hN=w(()=>{kKe();xH();JH=t=>{let e=t.split(""),r=[],n=(i,a)=>{for(let s=a;s<e.length;s+=1)if(i.includes(e[s]))return s;return-1},o=0;for(;o<e.length;)if(e[o]==="{"&&o+1<e.length&&e[o+1]==="{")r.push({type:"literal",text:"{"}),o+=2;else if(e[o]==="}"&&o+1<e.length&&e[o+1]==="}")r.push({type:"literal",text:"}"}),o+=2;else if(e[o]==="{"){let i=n("}",o);if(i<0)throw new Error("Unclosed'{'intemplate.");r.push({type:"variable",name:e.slice(o+1,i).join("")}),o=i+1}else{if(e[o]==="}")throw new Error("Single'}'intemplate.");{let i=n("{}",o),a=(i<0?e.slice(o):e.slice(o,i)).join("");r.push({type:"literal",text:a}),o=i<0?e.length:i}}return r},zKe=t=>{let e=[];for(let r of t)if(r[0]==="name"){let n=r[1].includes(".")?r[1].split(".")[0]:r[1];e.push({type:"variable",name:n})}else if(["#","&","^",">"].includes(r[0])){if(e.push({type:"variable",name:r[1]}),r[0]==="#"&&r.length>4&&Array.isArray(r[4])){let n=zKe(r[4]);e.push(...n)}}else e.push({type:"literal",text:r[1]});return e},TY=t=>{$Ke();let e=EY.parse(t);return zKe(e)},Ygr=(t,e)=>JH(t).reduce((r,n)=>{if(n.type==="variable"){if(n.name in e){let o=typeof e[n.name]=="string"?e[n.name]:JSON.stringify(e[n.name]);return r+o}throw new Error(`(f-string) Missing value for input ${n.name}`)}return r+n.text},""),Xgr=(t,e)=>($Ke(),EY.render(t,e)),bve={"f-string":Ygr,mustache:Xgr},Qgr={"f-string":JH,mustache:TY},Kp=(t,e,r)=>{try{return bve[e](t,r)}catch(n){throw JT(n,"INVALID_PROMPT_INPUT")}},ZH=(t,e)=>Qgr[e](t),mN=(t,e,r)=>{if(!(e in bve)){let n=Object.keys(bve);throw new Error(`Invalid template format. Got \`${e}\`;
should be one of ${n}`)}try{let n=r.reduce((o,i)=>(o[i]="foo",o),{});Array.isArray(t)?t.forEach(o=>{if(o.type==="text")Kp(o.text,e,n);else if(o.type==="image_url")if(typeof o.image_url=="string")Kp(o.image_url,e,n);else{let i=o.image_url.url;Kp(i,e,n)}else throw new Error(`Invalid message template received. ${JSON.stringify(o,null,2)}`)}):Kp(t,e,n)}catch(n){throw new Error(`Invalid prompt schema: ${n.message}`)}}});var _ve={};Qd(_ve,{PromptTemplate:()=>uf});var uf,v$=w(()=>{WH();hN();uf=class t extends kO{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.defineProperty(this,"additionalContentFields",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e.templateFormat==="mustache"&&e.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){if(this.templateFormat==="mustache")throw new Error("Mustachetemplatescannotbevalidated.");let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),mN(this.template,this.templateFormat,r)}}_getPromptType(){return"prompt"}async format(e){let r=await this.mergePartialAndUserVariables(e);return Kp(this.template,this.templateFormat,r)}static fromExamples(e,r,n,o=`
From: ${i}`);s=[l[0]]}else s=[];i={url:i},a=new w$({template:i,inputVariables:s,templateFormat:r?.templateFormat,additionalContentFields:o})}else if(typeof i=="object"){if("url"in i){let u;r?.templateFormat==="mustache"?u=TY(i.url):u=JH(i.url),s=u.flatMap(l=>l.type==="variable"?[l.name]:[])}else s=[];a=new w$({template:i,inputVariables:s,templateFormat:r?.templateFormat,additionalContentFields:o})}else throw new Error("Invalidimagetemplate");n.push(a)}else typeof o=="object"&&n.push(new YH({template:o,templateFormat:r?.templateFormat}));return new this({prompt:n,additionalOptions:r})}async format(e){if(this.prompt instanceof kO){let r=await this.prompt.format(e);return this.createMessage(r)}else{let r=[];for(let n of this.prompt){let o={};if(!("inputVariables"in n))throw new Error(`Prompt ${n} does not have inputVariables defined.`);for(let i of n.inputVariables)o||(o={[i]:e[i]}),o={...o,[i]:e[i]};if(n instanceof kO){let i=await n.format(o),a;"additionalContentFields"in n&&(a=n.additionalContentFields),r.push({...a,type:"text",text:i})}else if(n instanceof w$){let i=await n.format(o),a;"additionalContentFields"in n&&(a=n.additionalContentFields),r.push({...a,type:"image_url",image_url:i})}else if(n instanceof YH){let i=await n.format(o),a;"additionalContentFields"in n&&(a=n.additionalContentFields),r.push({...a,...i})}}return this.createMessage(r)}}async formatMessages(e){return[await this.format(e)]}},U_=class extends e6{static _messageClass(){return $s}static lc_name(){return"HumanMessagePromptTemplate"}},Pve=class extends e6{static _messageClass(){return En}static lc_name(){return"AIMessagePromptTemplate"}},aA=class extends e6{static _messageClass(){return RO}static lc_name(){return"SystemMessagePromptTemplate"}};Gp=class t extends QH{static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}constructor(e){if(super(e),Object.defineProperty(this,"promptMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),e.templateFormat==="mustache"&&e.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){let r=new Set;for(let s of this.promptMessages)if(!(s instanceof zl))for(let u of s.inputVariables)r.add(u);let n=this.inputVariables,o=new Set(this.partialVariables?n.concat(Object.keys(this.partialVariables)):n),i=new Set([...o].filter(s=>!r.has(s)));if(i.size>0)throw new Error(`Input variables \`${[...i]}\` are not used in any of the prompt messages.`);let a=new Set([...r].filter(s=>!o.has(s)));if(a.size>0)throw new Error(`Input variables \`${[...a]}\` are used in prompt messages but not in the prompt template.`)}}_getPromptType(){return"chat"}async _parseImagePrompts(e,r){if(typeof e.content=="string")return e;let n=await Promise.all(e.content.map(async o=>{if(o.type!=="image_url")return o;let i="";typeof o.image_url=="string"?i=o.image_url:i=o.image_url.url;let s=await uf.fromTemplate(i,{templateFormat:this.templateFormat}).format(r);return typeof o.image_url!="string"&&"url"in o.image_url?o.image_url.url=s:o.image_url=s,o}));return e.content=n,e}async formatMessages(e){let r=await this.mergePartialAndUserVariables(e),n=[];for(let o of this.promptMessages)if(o instanceof zl)n.push(await this._parseImagePrompts(o,r));else{let i=o.inputVariables.reduce((s,u)=>{if(!(u in r)&&!(oyr(o)&&o.optional))throw JT(new Error(`Missing value for input variable \`${u.toString()}\``),"INVALID_PROMPT_INPUT");return s[u]=r[u],s},{}),a=await o.formatMessages(i);n=n.concat(a)}return n}async partial(e){let r=this.inputVariables.filter(i=>!(i in e)),n={...this.partialVariables??{},...e},o={...this,inputVariables:r,partialVariables:n};return new t(o)}static fromTemplate(e,r){let n=uf.fromTemplate(e,r),o=new U_({prompt:n});return this.fromMessages([o])}static fromMessages(e,r){let n=e.reduce((a,s)=>a.concat(s instanceof t?s.promptMessages:[nyr(s,r)]),[]
`}),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("Onlyoneof'examples'and'example_selector'shouldbeprovided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("Oneof'examples'and'example_selector'shouldbeprovided");if(this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),mN(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("Oneof'examples'and'example_selector'shouldbeprovided")}async partial(e){let r=this.inputVariables.filter(i=>!(i in e)),n={...this.partialVariables??{},...e},o={...this,inputVariables:r,partialVariables:n};return new t(o)}async format(e){let r=await this.mergePartialAndUserVariables(e),n=await this.getExamples(r),o=await Promise.all(n.map(a=>this.examplePrompt.format(a))),i=[this.prefix,...o,this.suffix].join(this.exampleSeparator);return Kp(i,this.templateFormat,r)}serialize(){if(this.exampleSelector||!this.examples)throw new Error("Serializinganexampleselectorisnotcurrentlysupported");if(this.outputParser!==void 0)throw new Error("Serializinganoutputparserisnotcurrentlysupported");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){let{example_prompt:r}=e;if(!r)throw new Error("Missingexampleprompt");let n=await uf.deserialize(r),o;if(Array.isArray(e.examples))o=e.examples;else throw new Error("Invalidexamplesformat.Onlylistorstringaresupported.");return new t({inputVariables:e.input_variables,examplePrompt:n,examples:o,exampleSeparator:e.example_separator,prefix:e.prefix,suffix:e.suffix,templateFormat:e.template_format})}},Tve=class t extends QH{_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:`
4.Iftheusermentions"@vault",itmeanstheuserwantsyoutosearchtheObsidianvaultforinformationrelevanttothequery.Thesearchresultswillbeprovidedtoyouinthecontextalongwiththeuserquery,readitcarefullyandanswerthequestionbasedontheinformationprovided.Ifthere's no relevant information in the vault, just say so.
5. If the user mentions any other tool with the @ symbol, check the context for their results. If nothing is found, just ignore the @ symbol in the query.
6. Always use $'sinsteadof\\[etc.forLaTeXequations.
13. If the user mentions "tags", it most likely means tags in Obsidian note properties.`,wGe=`Return the new note content or canvas JSON in a special JSON format.
2. Click 'Refresh Index for Vault' and wait for indexing to complete. If you encounter the rate limiting error, please turn your request per second down in QA setting.`,FGe=6e3,nwe=.4,kGe=.4,owe=15,iwe=448e3,K_={DEFAULT:"",READING_FILES:"Reading files",SEARCHING_WEB:"Searching the web",READING_FILE_TREE:"Reading file tree"},zO={SETTINGS:"settings",EXPIRED_MODAL:"expired_modal",CHAT_MODE_SELECT:"chat_mode_select",MODE_SELECT_TOOLTIP:"mode_select_tooltip"},pg={MAX_TOKENS:6e3,TEMPERATURE:.1},$O=(m=>(m.OPENAI="openai",m.OPENAI_FORMAT="3rd party (openai-format)",m.AZURE_OPENAI="azure openai",m.ANTHROPIC="anthropic",m.COHEREAI="cohereai",m.GOOGLE="google",m.XAI="xai",m.OPENROUTERAI="openrouterai",m.GROQ="groq",m.OLLAMA="ollama",m.LM_STUDIO="lm-studio",m.COPILOT_PLUS="copilot-plus",m.MISTRAL="mistralai",m.DEEPSEEK="deepseek",m))($O||{}),fA={reasoning:"This model supports general reasoning tasks.",vision:"This model supports image inputs.",websearch:"This model can access the internet."},H_=[{name:"copilot-plus-flash",provider:"copilot-plus",enabled:!0,isBuiltIn:!0,core:!0,plusExclusive:!0,projectEnabled:!1,capabilities:["vision"]},{name:"google/gemini-2.5-flash-lite-preview-06-17",provider:"openrouterai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"google/gemini-2.5-flash",provider:"openrouterai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"google/gemini-2.5-pro",provider:"openrouterai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gpt-5",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"gpt-5-mini",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"gpt-5-nano",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"gpt-4.1",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gpt-4.1-mini",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gpt-4.1-nano",provider:"openai",enabled:!0,isBuiltIn:!0,capabilities:["vision"]},{name:"claude-sonnet-4-20250514",provider:"anthropic",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"claude-3-7-sonnet-latest",provider:"anthropic",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"grok-3-beta",provider:"xai",enabled:!0,isBuiltIn:!0},{name:"grok-3-mini-beta",provider:"xai",enabled:!0,isBuiltIn:!0},{name:"gemini-2.5-flash",provider:"google",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gemini-2.5-pro",provider:"google",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision"]},{name:"azure-openai",provider:"azure openai",enabled:!0,isBuiltIn:!0},{name:"deepseek-chat",provider:"deepseek",enabled:!0,isBuiltIn:!0},{name:"deepseek-reasoner",provider:"deepseek",enabled:!0,isBuiltIn:!0,capabilities:["reasoning"]}],cA=(l=>(l.OPENAI="openai",l.COHEREAI="cohereai",l.GOOGLE="google",l.AZURE_OPENAI="azure openai",l.OLLAMA="ollama",l.LM_STUDIO="lm-studio",l.OPENAI_FORMAT="3rd party (openai-format)",l.COPILOT_PLUS="copilot-plus",l.COPILOT_PLUS_JINA="copilot-plus-jina",l))(cA||{}),yN=[{name:"copilot-plus-small",provider:"copilot-plus",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0,plusExclusive:!0},{name:"copilot-plus-large",provider:"copilot-plus-jina",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0,plusExclusive:!0,believerExclusive:!0,dimensions:1024},{name:"copilot-plus-multilingual",provider:"copilot-plus-jina",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0,plusExclusive:!0,dimensions:512},{name:"text-embedding-3-small",provider:"openai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0},{name:"text-embedding-3-large",provider:"openai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0},{name:"embed-multilingual-light-v3.0",provider:"cohereai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0},{name:"text-embedding-004",provider:"google",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0},{name:"azure-openai",provider:"azure openai",enabled:!0,i
If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body`);returno.stream()};returnObject.assign(t,{transformToByteArray:r,transformToString:asynco=>{leti=awaitr();if(o==="base64")returnQA(i);if(o==="hex")returnCpt(i);if(o===void0||o==="utf8"||o==="utf-8")returnate(i);if(typeofTextDecoder=="function")returnnewTextDecoder(o).decode(i);thrownewError("TextDecoder is not available, please make sure polyfill is provided.")},transformToWebStream:()=>{if(e)thrownewError(Ppt);if(e=!0,Ept(t))returnn(t);if(xCe(t))returnt;thrownewError(`Cannot transform payload to web stream, got ${t}`)}})},Ept=t=>typeofBlob=="function"&&tinstanceofBlob});varIpt=w(()=>{});varMpt=w(()=>{});varCCe=w(()=>{_Ce();ipt();Apt();Ipt();Mpt();SCe()});vartI,Rpt=w(()=>{CCe();tI=async(t=newUint8Array,e)=>{if(tinstanceofUint8Array)returnmP.mutate(t);if(!t)returnmP.mutate(newUint8Array);letr=e.streamCollector(t);returnmP.mutate(awaitr)}});varEt,OCe,Npt=w(()=>{fCe();su();Et=class{constructor(){this.middlewareStack=Iz()}staticclassBuilder(){returnnewOCe}resolveMiddlewareWithContext(e,r,n,{middlewareFn:o,clientName:i,commandName:a,inputFilterSensitiveLog:s,outputFilterSensitiveLog:u,smithyContext:l,additionalContext:c,CommandCtor:d}){for(letbofo.bind(this)(d,e,r,n))this.middlewareStack.use(b);letf=e.concat(this.middlewareStack),{logger:p}=r,m={logger:p,clientName:i,commandName:a,inputFilterSensitiveLog:s,outputFilterSensitiveLog:u,[Cz]:{commandInstance:this,...l},...c},{requestHandler:h}=r;returnf.resolve(b=>h.handle(b.request,n||{}),m)}},OCe=class{constructor(){this._init=()=>{},this._ep={},this._middlewareFn=()=>[],this._commandName="",this._clientName="",this._additionalContext={},this._smithyContext={},this._inputFilterSensitiveLog=e=>e,this._outputFilterSensitiveLog=e=>e,this._serializer=null,this._deserializer=null}init(e){this._init=e}ep(e){returnthis._ep=e,this}m(e){returnthis._middlewareFn=e,this}s(e,r,n={}){returnthis._smithyContext={service:e,operation:r,...n},this}c(e={}){returnthis._additionalContext=e,this}n(e,r){returnthis._clientName=e,this._commandName=r,this}f(e=n=>n,r=n=>n){returnthis._inputFilterSensitiveLog=e,this._outputFilterSensitiveLog=r,this}ser(e){returnthis._serializer=e,this}de(e){returnthis._deserializer=e,this}build(){lete=this,r;returnr=classextendsEt{staticgetEndpointParameterInstructions(){returne._ep}constructor(...[n]){super(),this.serialize=e._serializer,this.deserialize=e._deserializer,this.input=n??{},e._init(this)}resolveMiddleware(n,o,i){returnthis.resolveMiddlewareWithContext(n,o,i,{CommandCtor:r,middlewareFn:e._middlewareFn,clientName:e._clientName,commandName:e._commandName,inputFilterSensitiveLog:e._inputFilterSensitiveLog,outputFilterSensitiveLog:e._outputFilterSensitiveLog,smithyContext:e._smithyContext,additionalContext:e._additionalContext})}}}}});varute,jpt=w(()=>{ute="***SensitiveInformation***"});varlte,Dpt=w(()=>{lte=(t,e)=>{for(letrofObject.keys(t)){letn=t[r],o=asyncfunction(a,s,u){letl=newn(a);if(typeofs=="function")this.send(l,s);elseif(typeofu=="function"){if(typeofs!="object")thrownewError(`Expected http options but got ${typeofs}`);this.send(l,s||{},u)}elsereturnthis.send(l,s)},i=(r[0].toLowerCase()+r.slice(1)).replace(/Command$/,"");e.prototype[i]=o}}});varyj,ySr,Lpt,bSr,Fpt,kpt,$pt,PCe,_Sr,Nz,vn,zpt,Bpt,vSr,J8,Z8,ECe,Upt,qpt,Hpt,TCe=w(()=>{yj=t=>{if(t!=null){if(typeoft=="string"){lete=parseFloat(t);if(!Number.isNaN(e))returnString(e)!==String(t)&&Hpt.warn(qpt(`Expected number but observed string: ${t}`)),e}if(typeoft=="number")returnt;thrownewTypeError(`Expected number, got ${typeoft}: ${t}`)}},ySr=Math.ceil(34028234663852886e22),Lpt=t=>{lete=yj(t);if(e!==void0&&!Number.isNaN(e)&&e!==1/0&&e!==-1/0&&Math.abs(e)>ySr)thrownewTypeError(`Expected 32-bit float, got ${t}`);returne},bSr=t=>{if(t!=null){if(Number.isInteger(t)&&!Number.isNaN(t))returnt;thrownewTypeError(`Expected integer, got ${typeoft}: ${t}`)}},Fpt=t=>PCe(t,32),kpt=t=>PCe(t,
`),Hpt={warn:console.warn}});var wSr,xSr,Vpt,SSr,Wpt,Cho,Oho,Pho,cte,Kpt,Eho,CSr,OSr,PSr,bj,ESr,TSr,ACe,Gpt=w(()=>{TCe();wSr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],xSr=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/),Vpt=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=xSr.exec(t);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");let[r,n,o,i,a,s,u,l]=e,c=ECe(ACe(n)),d=bj(o,"month",1,12),f=bj(i,"day",1,31);return Kpt(c,d,f,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l})},SSr=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),Wpt=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=SSr.exec(t);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");let[r,n,o,i,a,s,u,l,c]=e,d=ECe(ACe(n)),f=bj(o,"month",1,12),p=bj(i,"day",1,31),m=Kpt(d,f,p,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l});return c.toUpperCase()!="Z"&&m.setTime(m.getTime()-TSr(c)),m},Cho=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),Oho=new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),Pho=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/),cte=t=>{if(t==null)return;let e;if(typeof t=="number")e=t;else if(typeof t=="string")e=zpt(t);else if(typeof t=="object"&&t.tag===1)e=t.value;else throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");if(Number.isNaN(e)||e===1/0||e===-1/0)throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");return new Date(Math.round(e*1e3))},Kpt=(t,e,r,n)=>{let o=e-1;return OSr(t,o,r),new Date(Date.UTC(t,o,r,bj(n.hours,"hour",0,23),bj(n.minutes,"minute",0,59),bj(n.seconds,"seconds",0,60),ESr(n.fractionalMilliseconds)))},Eho=50*365*24*60*60*1e3,CSr=[31,28,31,30,31,30,31,31,30,31,30,31],OSr=(t,e,r)=>{let n=CSr[e];if(e===1&&PSr(t)&&(n=29),r>n)throw new TypeError(`Invaliddayfor${wSr[e]}in${t}:${r}`)},PSr=t=>t%4===0&&(t%100!==0||t%400===0),bj=(t,e,r,n)=>{let o=Upt(ACe(t));if(o<r||o>n)throw new TypeError(`${e}mustbebetween${r}and${n},inclusive`);return o},ESr=t=>t==null?0:Bpt("0."+t)*1e3,TSr=t=>{let e=t[0],r=1;if(e=="+")r=1;else if(e=="-")r=-1;else throw new TypeError(`Offsetdirection,${e},mustbe"+"or"-"`);let n=Number(t.substring(1,3)),o=Number(t.substring(4,6));return r*(n*60+o)*60*1e3},ACe=t=>{let e=0;for(;e<t.length-1&&t.charAt(e)==="0";)e++;return e===0?t:t.slice(e)}});var jz,Qa,ICe=w(()=>{jz=class t extends Error{constructor(e){super(e.message),Object.setPrototypeOf(this,t.prototype),this.name=e.name,this.$fault=e.$fault,this.$metadata=e.$metadata}},Qa=(t,e={})=>{Object.entries(e).filter(([,n])=>n!==void 0).forEach(([n,o])=>{(t[n]==null||t[n]==="")&&(t[n]=o)});let r=t.message||t.Message||"UnknownError";return t.message=r,delete t.Message,t}});var ASr,dte,ISr,Jpt=w(()=>{ICe();ASr=({output:t,parsedBody:e,exceptionCtor:r,errorCode:n})=>{let o=ISr(t),i=o.httpStatusCode?o.httpStatusCode+"":void 0,a=new r({name:e?.code||e?.Code||n||i||"UnknownError",$fault:"client",$metadata:o});throw Qa(a,e)},dte=t=>({output:e,parsedBody:r,errorCode:n})=>{ASr({output:e,parsedBody:r,exceptionCtor:t,errorCode:n})},ISr=t=>({httpStatusCode:t.statusCode,requestId:t.headers["x-amzn-requestid"]??t.headers["x-amzn-request-id"]??t.headers["x-amz-request-id"],extendedRequestId:t.headers["x-amz-id-2"],cfId:t.headers["x-amz-cf-id"]})});var fte,Zpt=w(()=>{fte=t=>{switch(t){case"standard":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"cross-region
${_b(i)}`}getCanonicalPath({path:e}){if(this.uriEscapePath){letr=[];for(letiofe.split("/"))i?.length!==0&&i!=="."&&(i===".."?r.pop():r.push(i));letn=`${e?.startsWith("/")?"/":""}${r.join("/")}${r.length>0&&e?.endsWith("/")?"/":""}`;returnMg(n).replace(/%2F/g,"/")}returne}asyncgetSignature(e,r,n,o){leti=awaitthis.createStringToSign(e,r,o),a=newthis.sha256(awaitn);returna.update(oI(i)),_b(awaita.digest())}getSigningKey(e,r,n,o){returnEht(this.sha256,e,n,r,o||this.service)}validateResolvedCredentials(e){if(typeofe!="object"||typeofe.accessKeyId!="string"||typeofe.secretAccessKey!="string")thrownewError("Resolved credential object is not valid")}},Ate=t=>{lete=Dht(t).replace(/[\-:]/g,"");return{longDate:e,shortDate:e.slice(0,8)}},Fht=t=>Object.keys(t).sort().join(";")});var$ht=w(()=>{kht();YCe();QCe();eOe();nOe();oOe();ZCe()});varIte,zht=w(()=>{rI();$ht();Ite=t=>{lete;t.credentials&&(e=Omt(t.credentials,Cmt,DCe)),e||(t.credentialDefaultProvider?e=Fz(t.credentialDefaultProvider(Object.assign({},t,{parentClientConfig:t}))):e=async()=>{thrownewError("`credentials` is missing")});let{signingEscapePath:r=!0,systemClockOffset:n=t.systemClockOffset||0,sha256:o}=t,i;returnt.signer?i=Fz(t.signer):t.regionInfoProvider?i=()=>Fz(t.region)().then(asynca=>[awaitt.regionInfoProvider(a,{useFipsEndpoint:awaitt.useFipsEndpoint(),useDualstackEndpoint:awaitt.useDualstackEndpoint()})||{},a]).then(([a,s])=>{let{signingRegion:u,signingService:l}=a;t.signingRegion=t.signingRegion||u||s,t.signingName=t.signingName||l||t.serviceId;letc={...t,credentials:e,region:t.signingRegion,service:t.signingName,sha256:o,uriEscapePath:r},d=t.signerConstructor||iV;returnnewd(c)}):i=asynca=>{a=Object.assign({},{name:"sigv4",signingName:t.signingName||t.defaultSigningName,signingRegion:awaitFz(t.region)(),properties:{}},a);lets=a.signingRegion,u=a.signingName;t.signingRegion=t.signingRegion||s,t.signingName=t.signingName||u||t.serviceId;letl={...t,credentials:e,region:t.signingRegion,service:t.signingName,sha256:o,uriEscapePath:r},c=t.signerConstructor||iV;returnnewc(l)},{...t,systemClockOffset:n,signingEscapePath:r,credentials:e,signer:i}}});varBht=w(()=>{aht();sht();zht()});varUht=w(()=>{Bht()});varqht=w(()=>{});varHht=w(()=>{dr()});varMte,iOe=w(()=>{dr();Mte=(t,e)=>tI(t,e).then(r=>e.utf8Encoder(r))});varVs,Vht,Wht,Kht=w(()=>{iOe();Vs=(t,e)=>Mte(t,e).then(r=>{if(r.length)try{returnJSON.parse(r)}catch(n){thrown?.name==="SyntaxError"&&Object.defineProperty(n,"$responseBodyText",{value:r}),n}return{}}),Vht=async(t,e)=>{letr=awaitVs(t,e);returnr.message=r.message??r.Message,r},Wht=(t,e)=>{letr=(i,a)=>Object.keys(i).find(s=>s.toLowerCase()===a.toLowerCase()),n=i=>{leta=i;returntypeofa=="number"&&(a=a.toString()),a.indexOf(",")>=0&&(a=a.split(",")[0]),a.indexOf(":")>=0&&(a=a.split(":")[0]),a.indexOf("#")>=0&&(a=a.split("#")[1]),a},o=r(t.headers,"x-amzn-errortype");if(o!==void0)returnn(t.headers[o]);if(e.code!==void0)returnn(e.code);if(e.__type!==void0)returnn(e.__type)}});varRte=v(hP=>{"use strict";varGht=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",ZSr=Ght+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",Jht="["+Ght+"]["+ZSr+"]*",YSr=newRegExp("^"+Jht+"$"),XSr=function(t,e){letr=[],n=e.exec(t);for(;n;){leto=[];o.startIndex=e.lastIndex-n[0].length;leti=n.length;for(leta=0;a<i;a++)o.push(n[a]);r.push(o),n=e.exec(t)}returnr},QSr=function(t){lete=YSr.exec(t);return!(e===null||typeofe>"u")};hP.isExist=function(t){returntypeoft<"u"};hP.isEmptyObject=function(t){returnObject.keys(t).length===0};hP.merge=function(t,e,r){if(e){letn=Object.keys(e),o=n.length;for(leti=0;i<o;i++)r==="strict"?t[n[i]]=[e[n[i]]]:t[n[i]]=e[n[i]]}};hP.getValue=function(t){returnhP.isExist(t)?t:""};hP.isName=QSr;hP.getAllMatches=XSr;hP.nameRegexp=Jht});varsOe=v(egt=>{"use strict";varaOe=Rte(),eCr={allowBooleanAttributes:!1,unpairedTags:[]};egt.validate=function(t,e){e=Object.assign({},eCr,e);letr=
`&&t[i]!=="\r";i++)u+=t[i];if(u=u.trim(),u[u.length-1]==="/"&&(u=u.substring(0,u.length-1),i--),!uCr(u)){let d;return u.trim().length===0?d="Invalid space after '<'.":d="Tag '"+u+"' is an invalid name.",Ws("InvalidTag",d,cp(t,i))}let l=nCr(t,i);if(l===!1)return Ws("InvalidAttr","Attributes for '"+u+"' have open quote.",cp(t,i));let c=l.value;if(i=l.index,c[c.length-1]==="/"){let d=i-c.length;c=c.substring(0,c.length-1);let f=Qht(c,e);if(f===!0)n=!0;else return Ws(f.err.code,f.err.msg,cp(t,d+f.err.line))}else if(s)if(l.tagClosed){if(c.trim().length>0)return Ws("InvalidTag","Closing tag '"+u+"' can't have attributes or invalid starting.",cp(t,a));if(r.length===0)return Ws("InvalidTag","Closing tag '"+u+"' has not been opened.",cp(t,a));{let d=r.pop();if(u!==d.tagName){let f=cp(t,d.tagStartPos);return Ws("InvalidTag","Expected closing tag '"+d.tagName+"' (opened in line "+f.line+", col "+f.col+") instead of closing tag '"+u+"'.",cp(t,a))}r.length==0&&(o=!0)}}else return Ws("InvalidTag","Closing tag '"+u+"' doesn't have proper closing.",cp(t,i));else{let d=Qht(c,e);if(d!==!0)return Ws(d.err.code,d.err.msg,cp(t,i-c.length+d.err.line));if(o===!0)return Ws("InvalidXml","Multiple possible root nodes found.",cp(t,i));e.unpairedTags.indexOf(u)!==-1||r.push({tagName:u,tagStartPos:a}),n=!0}for(i++;i<t.length;i++)if(t[i]==="<")if(t[i+1]==="!"){i++,i=Xht(t,i);continue}else if(t[i+1]==="?"){if(i=Yht(t,++i),i.err)return i}else break;else if(t[i]==="&"){let d=aCr(t,i);if(d==-1)return Ws("InvalidChar","char '&' is not expected.",cp(t,i));i=d}else if(o===!0&&!Zht(t[i]))return Ws("InvalidXml","Extra text at the end",cp(t,i));t[i]==="<"&&i--}}else{if(Zht(t[i]))continue;return Ws("InvalidChar","char '"+t[i]+"' is not expected.",cp(t,i))}if(n){if(r.length==1)return Ws("InvalidTag","Unclosed tag '"+r[0].tagName+"'.",cp(t,r[0].tagStartPos));if(r.length>0)return Ws("InvalidXml","Invalid '"+JSON.stringify(r.map(i=>i.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return Ws("InvalidXml","Start tag expected.",1);return!0};function Zht(t){return t===" "||t===" "||t===`
`||t==="\r"}function Yht(t,e){let r=e;for(;e<t.length;e++)if(t[e]=="?"||t[e]==" "){let n=t.substr(r,e-r);if(e>5&&n==="xml")return Ws("InvalidXml","XML declaration allowed only at the start of the document.",cp(t,e));if(t[e]=="?"&&t[e+1]==">"){e++;break}else continue}return e}function Xht(t,e){if(t.length>e+5&&t[e+1]==="-"&&t[e+2]==="-"){for(e+=3;e<t.length;e++)if(t[e]==="-"&&t[e+1]==="-"&&t[e+2]===">"){e+=2;break}}else if(t.length>e+8&&t[e+1]==="D"&&t[e+2]==="O"&&t[e+3]==="C"&&t[e+4]==="T"&&t[e+5]==="Y"&&t[e+6]==="P"&&t[e+7]==="E"){let r=1;for(e+=8;e<t.length;e++)if(t[e]==="<")r++;else if(t[e]===">"&&(r--,r===0))break}else if(t.length>e+9&&t[e+1]==="["&&t[e+2]==="C"&&t[e+3]==="D"&&t[e+4]==="A"&&t[e+5]==="T"&&t[e+6]==="A"&&t[e+7]==="["){for(e+=8;e<t.length;e++)if(t[e]==="]"&&t[e+1]==="]"&&t[e+2]===">"){e+=2;break}}return e}var tCr='"',rCr="'";function nCr(t,e){let r="",n="",o=!1;for(;e<t.length;e++){if(t[e]===tCr||t[e]===rCr)n===""?n=t[e]:n!==t[e]||(n="");else if(t[e]===">"&&n===""){o=!0;break}r+=t[e]}return n!==""?!1:{value:r,index:e,tagClosed:o}}var oCr=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function Qht(t,e){let r=aOe.getAllMatches(t,oCr),n={};for(let o=0;o<r.length;o++){if(r[o][1].length===0)return Ws("InvalidAttr","Attribute '"+r[o][2]+"' has no space in starting.",aV(r[o]));if(r[o][3]!==void 0&&r[o][4]===void 0)return Ws("InvalidAttr","Attribute '"+r[o][2]+"' is without value.",aV(r[o]));if(r[o][3]===void 0&&!e.allowBooleanAttributes)return Ws("InvalidAttr","boolean attribute '"+r[o][2]+"' is not allowed.",aV(r[o]));let i=r[o][2];if(!sCr(i))return Ws("InvalidAttr","Attribute '"+i+"' is an invalid name.",aV(r[o]));if(!n.hasOwnProperty(i))n[i]=1;else return Ws("InvalidAttr","Attribute '"+i+"' is repeated.",aV(r[o]))}return!0}function iCr(t,e){let r=/\d/;for(t[e]==="x"&&(e++,r=/[\da-fA-F]/);e<t.length;e++){if(t[e]===";")return e;if(!t[e].match(r))break}return-1}function aCr(t,e){if(e++,t[e]===";")return-1;if(t[e]==="#")return e++,iCr(t,e);let r=0;for(;e<t.length;e++,r++)if(!(t[e].match(/\w/)&&r<20)){if(t[e]===";")break;return-1}return e}function Ws(t,e,r){return{err:{code:t,msg:e,line:r.line||r,col:r.col}}}function sCr(t){return aOe.isName(t)}function uCr(t){return aOe.isName(t)}function cp(t,e){let r=t.substring(0,e).split(/\r?\n/);return{line:r.length,col:r[r.length-1].length+1}}function aV(t){return t.startIndex+t[1].length}});var rgt=v(uOe=>{var tgt={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(t,e){return e},attributeValueProcessor:function(t,e){return e},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(t,e,r){return t}},lCr=function(t){return Object.assign({},tgt,t)};uOe.buildOptions=lCr;uOe.defaultOptions=tgt});var ogt=v((Y_o,ngt)=>{"use strict";var lOe=class{constructor(e){this.tagname=e,this.child=[],this[":@"]={}}add(e,r){e==="__proto__"&&(e="#__proto__"),this.child.push({[e]:r})}addChild(e){e.tagname==="__proto__"&&(e.tagname="#__proto__"),e[":@"]&&Object.keys(e[":@"]).length>0?this.child.push({[e.tagname]:e.child,":@":e[":@"]}):this.child.push({[e.tagname]:e.child})}};ngt.exports=lOe});var agt=v((X_o,igt)=>{var cCr=Rte();function dCr(t,e){let r={};if(t[e+3]==="O"&&t[e+4]==="C"&&t[e+5]==="T"&&t[e+6]==="Y"&&t[e+7]==="P"&&t[e+8]==="E"){e=e+9;let n=1,o=!1,i=!1,a="";for(;e<t.length;e++)if(t[e]==="<"&&!i){if(o&&mCr(t,e))e+=7,[entityName,val,e]=fCr(t,e+1),val.indexOf("&")===-1&&(r[bCr(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(o&&hCr(t,e))e+=8;else if(o&&gCr(t,e))e+=8;else if(o&&yCr(t,e))e+=9;else if(pCr)i=!0;else throw new Error("Invalid DOCTYPE");n++,a=""}else if(t[e]===">"){if(i?t[e-1]==="-"&&t[e-2]==="-"&&(i=!1,n--):n--,n===0)bre
`);let e=new sV("!xml"),r=e,n="",o="";for(let i=0;i<t.length;i++)if(t[i]==="<")if(t[i+1]==="/"){let s=wj(t,">",i,"Closing Tag is not closed."),u=t.substring(i+2,s).trim();if(this.options.removeNSPrefix){let d=u.indexOf(":");d!==-1&&(u=u.substr(d+1))}this.options.transformTagName&&(u=this.options.transformTagName(u)),r&&(n=this.saveTextToParentTag(n,r,o));let l=o.substring(o.lastIndexOf(".")+1);if(u&&this.options.unpairedTags.indexOf(u)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${u}>`);let c=0;l&&this.options.unpairedTags.indexOf(l)!==-1?(c=o.lastIndexOf(".",o.lastIndexOf(".")-1),this.tagsNodeStack.pop()):c=o.lastIndexOf("."),o=o.substring(0,c),r=this.tagsNodeStack.pop(),n="",i=s}else if(t[i+1]==="?"){let s=dOe(t,i,!1,"?>");if(!s)throw new Error("Pi Tag is not closed.");if(n=this.saveTextToParentTag(n,r,o),!(this.options.ignoreDeclaration&&s.tagName==="?xml"||this.options.ignorePiTags)){let u=new sV(s.tagName);u.add(this.options.textNodeName,""),s.tagName!==s.tagExp&&s.attrExpPresent&&(u[":@"]=this.buildAttributesMap(s.tagExp,o,s.tagName)),this.addChild(r,u,o)}i=s.closeIndex+1}else if(t.substr(i+1,3)==="!--"){let s=wj(t,"-->",i+4,"Comment is not closed.");if(this.options.commentPropName){let u=t.substring(i+4,s-2);n=this.saveTextToParentTag(n,r,o),r.add(this.options.commentPropName,[{[this.options.textNodeName]:u}])}i=s}else if(t.substr(i+1,2)==="!D"){let s=CCr(t,i);this.docTypeEntities=s.entities,i=s.i}else if(t.substr(i+1,2)==="!["){let s=wj(t,"]]>",i,"CDATA is not closed.")-2,u=t.substring(i+9,s);n=this.saveTextToParentTag(n,r,o);let l=this.parseTextData(u,r.tagname,o,!0,!1,!0,!0);l==null&&(l=""),this.options.cdataPropName?r.add(this.options.cdataPropName,[{[this.options.textNodeName]:u}]):r.add(this.options.textNodeName,l),i=s+2}else{let s=dOe(t,i,this.options.removeNSPrefix),u=s.tagName,l=s.rawTagName,c=s.tagExp,d=s.attrExpPresent,f=s.closeIndex;this.options.transformTagName&&(u=this.options.transformTagName(u)),r&&n&&r.tagname!=="!xml"&&(n=this.saveTextToParentTag(n,r,o,!1));let p=r;if(p&&this.options.unpairedTags.indexOf(p.tagname)!==-1&&(r=this.tagsNodeStack.pop(),o=o.substring(0,o.lastIndexOf("."))),u!==e.tagname&&(o+=o?"."+u:u),this.isItStopNode(this.options.stopNodes,o,u)){let m="";if(c.length>0&&c.lastIndexOf("/")===c.length-1)u[u.length-1]==="/"?(u=u.substr(0,u.length-1),o=o.substr(0,o.length-1),c=u):c=c.substr(0,c.length-1),i=s.closeIndex;else if(this.options.unpairedTags.indexOf(u)!==-1)i=s.closeIndex;else{let b=this.readStopNodeData(t,l,f+1);if(!b)throw new Error(`Unexpected end of ${l}`);i=b.i,m=b.tagContent}let h=new sV(u);u!==c&&d&&(h[":@"]=this.buildAttributesMap(c,o,u)),m&&(m=this.parseTextData(m,u,o,!0,d,!0,!0)),o=o.substr(0,o.lastIndexOf(".")),h.add(this.options.textNodeName,m),this.addChild(r,h,o)}else{if(c.length>0&&c.lastIndexOf("/")===c.length-1){u[u.length-1]==="/"?(u=u.substr(0,u.length-1),o=o.substr(0,o.length-1),c=u):c=c.substr(0,c.length-1),this.options.transformTagName&&(u=this.options.transformTagName(u));let m=new sV(u);u!==c&&d&&(m[":@"]=this.buildAttributesMap(c,o,u)),this.addChild(r,m,o),o=o.substr(0,o.lastIndexOf("."))}else{let m=new sV(u);this.tagsNodeStack.push(r),u!==c&&d&&(m[":@"]=this.buildAttributesMap(c,o,u)),this.addChild(r,m,o),r=m}n="",i=f}}else n+=t[i];return e.child};function RCr(t,e,r){let n=this.options.updateTag(e.tagname,r,e[":@"]);n===!1||(typeof n=="string"&&(e.tagname=n),t.addChild(e))}var NCr=function(t){if(this.options.processEntities){for(let e in this.docTypeEntities){let r=this.docTypeEntities[e];t=t.replace(r.regx,r.val)}for(let e in this.lastEntities){let r=this.lastEntities[e];t=t.replace(r.regex,r.val)}if(this.options.htmlEntities)for(let e in this.htmlEntities){let r=this.htmlEntities[e];t=t.replace(r.regex,r.val)}t=t.replace(this.ampEntity.regex,this.ampEntity.val)}return t};function jCr(t,e,r,n){return t&&(n===void 0&&(n=Object.keys(e.child).length===0),t=this.parseTextData(t,e.tagname,r,!1,e[":@"]?Object.keys(e[":@"]).length!==0:!1,n),t!==void 0&&t!==""&&e.add(this.options.textNodeName,t),t=""),t}function DCr(t,e,r){let n="*
`;super(r),this.name="AggregateError",this.errors=e}};eTe.exports={AggregateError:QEe,kEmptyObject:Object.freeze({}),once(t){let e=!1;return function(...r){e||(e=!0,t.apply(this,r))}},createDeferredPromise:function(){let t,e;return{promise:new Promise((n,o)=>{t=n,e=o}),resolve:t,reject:e}},promisify(t){return new Promise((e,r)=>{t((n,...o)=>n?r(n):e(...o))})},debuglog(){return function(){}},format(t,...e){return t.replace(/%([sdifj])/g,function(...[r,n]){let o=e.shift();return n==="f"?o.toFixed(6):n==="j"?JSON.stringify(o):n==="s"&&typeof o=="object"?`${o.constructor!==Object?o.constructor.name:""} {}`.trim():o.toString()})},inspect(t){switch(typeof t){case"string":if(t.includes("'"))if(t.includes('"')){if(!t.includes("`")&&!t.includes("${"))return`\`${t}\``}else return`"${t}"`;return`'${t}'`;case"number":return isNaN(t)?"NaN":Object.is(t,-0)?String(t):t;case"bigint":return`${String(t)}n`;case"boolean":case"undefined":return String(t);case"object":return"{}"}},types:{isAsyncFunction(t){return t instanceof AAr},isArrayBufferView(t){return ArrayBuffer.isView(t)}},isBlob:IAr,deprecate(t,e){return t},addAbortListener:LV().addAbortListener||function(e,r){if(e===void 0)throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",e);zSt(e,"signal"),MAr(r,"listener");let n;return e.aborted?queueMicrotask(()=>r()):(e.addEventListener("abort",r,{__proto__:null,once:!0,[OAr]:!0}),n=()=>{e.removeEventListener("abort",r)}),{__proto__:null,[PAr](){var o;(o=n)===null||o===void 0||o()}}},AbortSignalAny:EAr.any||function(e){if(e.length===1)return e[0];let r=new TAr,n=()=>r.abort();return e.forEach(o=>{zSt(o,"signals"),o.addEventListener("abort",n,{once:!0})}),r.signal.addEventListener("abort",()=>{e.forEach(o=>o.removeEventListener("abort",n))},{once:!0}),r.signal}};eTe.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var mp=v((iRo,qSt)=>{"use strict";var{format:RAr,inspect:Tne,AggregateError:NAr}=vf(),jAr=globalThis.AggregateError||NAr,DAr=Symbol("kIsNodeError"),LAr=["string","function","number","object","Function","Object","boolean","bigint","symbol"],FAr=/^([A-Z][a-z0-9]*)+$/,kAr="__node_internal_",Ane={};function jj(t,e){if(!t)throw new Ane.ERR_INTERNAL_ASSERTION(e)}function BSt(t){let e="",r=t.length,n=t[0]==="-"?1:0;for(;r>=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function $Ar(t,e,r){if(typeof e=="function")return jj(e.length<=r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${e.length}).`),e(...r);let n=(e.match(/%[dfijoOs]/g)||[]).length;return jj(n===r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${n}).`),r.length===0?e:RAr(e,...r)}function dd(t,e,r){r||(r=Error);class n extends r{constructor(...i){super($Ar(t,e,i))}toString(){return`${this.name} [${t}]: ${this.message}`}}Object.defineProperties(n.prototype,{name:{value:r.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${t}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),n.prototype.code=t,n.prototype[DAr]=!0,Ane[t]=n}function USt(t){let e=kAr+t.name;return Object.defineProperty(t,"name",{value:e}),t}function zAr(t,e){if(t&&e&&t!==e){if(Array.isArray(e.errors))return e.errors.push(t),e;let r=new jAr([e,t],e.message);return r.code=e.code,r}return t||e}var tTe=class extends Error{constructor(e="The operation was aborted",r=void 0){if(r!==void 0&&typeof r!="object")throw new Ane.ERR_INVALID_ARG_TYPE("options","Object",r);super(e,r),this.code="ABORT_ERR",this.name="AbortError"}};dd("ERR_ASSERTION","%s",Error);dd("ERR_INVALID_ARG_TYPE",(t,e,r)=>{jj(typeof t=="string","'name' must be a string"),Array.isArray(e)||(e=[e]);let n="The ";t.endsWith(" argument")?n+=`${t} `:n+=`"${t}" ${t.includes(".")?"property":"argument"} `,n+="must be ";let o=[],i=[],a=[];for(let u of e)jj(typeof u=="string","All expected entries have to be of type string"),LAr.includes(u)?o.push(u.toLowerCase()):FAr.test(u)?i.push(u):(jj(u!=="object",'Thevalue"object"shouldbewrittenas"Object"'),a.push(u));if(i.length>0
`,this.streamTerminator=n.streamTerminator):this.messageTerminator=n.messageTerminator,o?.addEventListener("abort",()=>this.controller.abort())}iterMessages(){returnwAt(this,arguments,function*(){varr,n;this.controller.signal;leto=xAt(this.stream),i="",a=!1;try{for(vars=vAt(o),u;u=yieldSb(s.next()),!u.done;){letl=u.value;i+=this.decodeChunk(l);letc;for(;(c=i.indexOf(this.messageTerminator))>=0;){letd=i.slice(0,c+1);if(i=i.slice(c+1),d.length===0)continue;if(!a&&this.prefix!=null){letp=d.indexOf(this.prefix);if(p===-1)continue;a=!0,d=d.slice(p+this.prefix.length)}if(this.streamTerminator!=null&&d.includes(this.streamTerminator))returnyieldSb(void0);letf=yieldSb(this.parse(JSON.parse(d)));yieldyieldSb(f),a=!1}}}catch(l){r={error:l}}finally{try{u&&!u.done&&(n=s.return)&&(yieldSb(n.call(s)))}finally{if(r)throwr.error}}})}[Symbol.asyncIterator](){returnwAt(this,arguments,function*(){varr,n;try{for(varo=vAt(this.iterMessages()),i;i=yieldSb(o.next()),!i.done;){leta=i.value;yieldyieldSb(a)}}catch(a){r={error:a}}finally{try{i&&!i.done&&(n=o.return)&&(yieldSb(n.call(o)))}finally{if(r)throwr.error}}})}decodeChunk(e){letr="";if(typeofTextDecoder<"u"){letn=newTextDecoder("utf8");r+=n.decode(e)}elselFr.RUNTIME.type==="node"&&typeofe<"u"&&(r+=Buffer.isBuffer(e)?e:Buffer.from(e));returnr}};im.Stream=XAe;functionxAt(t){if(t[Symbol.asyncIterator])returnt;lete=t.getReader();return{next(){return_At(this,void0,void0,function*(){try{letr=yielde.read();returnr?.done&&e.releaseLock(),r}catch(r){throwe.releaseLock(),r}})},return(){return_At(this,void0,void0,function*(){letr=e.cancel();returne.releaseLock(),yieldr,{done:!0,value:void0}})},[Symbol.asyncIterator](){returnthis}}}im.readableStreamAsyncIterable=xAt});varSAt=v(Eoe=>{"use strict";Object.defineProperty(Eoe,"__esModule",{value:!0});Eoe.Stream=void0;vardFr=QAe();Object.defineProperty(Eoe,"Stream",{enumerable:!0,get:function(){returndFr.Stream}})});varPAt=v((V1o,OAt)=>{"use strict";vareIe=Object.defineProperty,fFr=Object.getOwnPropertyDescriptor,pFr=Object.getOwnPropertyNames,mFr=Object.prototype.hasOwnProperty,hFr=(t,e)=>{for(varrine)eIe(t,r,{get:e[r],enumerable:!0})},gFr=(t,e,r,n)=>{if(e&&typeofe=="object"||typeofe=="function")for(letoofpFr(e))!mFr.call(t,o)&&o!==r&&eIe(t,o,{get:()=>e[o],enumerable:!(n=fFr(e,o))||n.enumerable});returnt},yFr=t=>gFr(eIe({},"__esModule",{value:!0}),t),CAt={};hFr(CAt,{Blob:()=>vFr,File:()=>wFr,FormData:()=>_Fr});OAt.exports=yFr(CAt);varbFr=function(){returntypeofglobalThis<"u"?globalThis:typeofself<"u"?self:window}(),{FormData:_Fr,Blob:vFr,File:wFr}=bFr});var$At=v((W1o,kAt)=>{"use strict";varnIe=Object.defineProperty,xFr=Object.getOwnPropertyDescriptor,SFr=Object.getOwnPropertyNames,CFr=Object.prototype.hasOwnProperty,OFr=(t,e)=>{for(varrine)nIe(t,r,{get:e[r],enumerable:!0})},PFr=(t,e,r,n)=>{if(e&&typeofe=="object"||typeofe=="function")for(letoofSFr(e))!CFr.call(t,o)&&o!==r&&nIe(t,o,{get:()=>e[o],enumerable:!(n=xFr(e,o))||n.enumerable});returnt},EFr=t=>PFr(nIe({},"__esModule",{value:!0}),t),oIe=(t,e,r)=>{if(!e.has(t))throwTypeError("Cannot "+r)},Os=(t,e,r)=>(oIe(t,e,"read from private field"),r?r.call(t):e.get(t)),Uv=(t,e,r)=>{if(e.has(t))throwTypeError("Cannot add the same private member more than once");einstanceofWeakSet?e.add(t):e.set(t,r)},s5=(t,e,r,n)=>(oIe(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),tIe=(t,e,r)=>(oIe(t,e,"access private method"),r),NAt={};OFr(NAt,{FormDataEncoder:()=>DFr,isFile:()=>Yj,isFormData:()=>LAt});kAt.exports=EFr(NAt);varMP=t=>typeoft=="function",TFr=t=>MP(t[Symbol.asyncIterator]),EAt=65536;function*jAt(t){if(t.byteLength<=EAt){yieldt;return}lete=0;for(;e<t.byteLength;){letr=Math.min(t.byteLength-e,EAt),n=t.buffer.slice(e,e+r);e+=n.byteLength,yieldnewUint8Array(n)}}asyncfunction*AFr(t){lete=t.getReader();for(;;){let{done:r,value:n}=awaite.read();if(r)break;yieldn}}asyncfunction*TAt(t){forawait(leteoft)yield*jAt(e)}varIFr=t=>{if(TFr(t))returnTAt(t);if(MP(t.getReader))returnTAt(AFr(t));thrownewTypeError("Unsup
`),Uv(this,u5,void0),Uv(this,Aoe,void0),Uv(this,l5,"-".repeat(2)),Uv(this,Zj,newTextEncoder),Uv(this,c5,void0),Uv(this,d5,void0),Uv(this,Ioe,void0),!LAt(t))thrownewTypeError("Expected first argument to be a FormData instance.");letn;if(IAt(e)?r=e:n=e,n||(n=MFr()),typeofn!="string")thrownewTypeError("Expected boundary argument to be a string.");if(r&&!IAt(r))thrownewTypeError("Expected options argument to be an object.");s5(this,d5,Array.from(t.entries())),s5(this,Ioe,{...jFr,...r}),s5(this,u5,Os(this,Zj).encode(Os(this,MI))),s5(this,Aoe,Os(this,u5).byteLength),this.boundary=`form-data-boundary-${n}`,this.contentType=`multipart/form-data; boundary=${this.boundary}`,s5(this,c5,Os(this,Zj).encode(`${Os(this,l5)}${this.boundary}${Os(this,l5)}${Os(this,MI).repeat(2)}`));leto={"Content-Type":this.contentType},i=tIe(this,rIe,FAt).call(this);i&&(this.contentLength=i,o["Content-Length"]=i),this.headers=NFr(Object.freeze(o)),Object.defineProperties(this,{boundary:Toe,contentType:Toe,contentLength:Toe,headers:Toe})}*values(){for(let[t,e]ofOs(this,d5)){letr=Yj(e)?e:Os(this,Zj).encode(DAt(e));yieldtIe(this,Moe,iIe).call(this,t,r),yieldr,yieldOs(this,u5)}yieldOs(this,c5)}async*encode(){for(lettofthis.values())Yj(t)?yield*IFr(t.stream()):yield*jAt(t)}[Symbol.iterator](){returnthis.values()}[Symbol.asyncIterator](){returnthis.encode()}};MI=newWeakMap;u5=newWeakMap;Aoe=newWeakMap;l5=newWeakMap;Zj=newWeakMap;c5=newWeakMap;d5=newWeakMap;Ioe=newWeakMap;Moe=newWeakSet;iIe=function(t,e){letr="";if(r+=`${Os(this,l5)}${this.boundary}${Os(this,MI)}`,r+=`Content-Disposition: form-data; name="${RAt(t)}"`,Yj(e)&&(r+=`; filename="${RAt(e.name)}"${Os(this,MI)}`,r+=`Content-Type: ${e.type||"application/octet-stream"}`),Os(this,Ioe).enableAdditionalHeaders===!0){letn=Yj(e)?e.size:e.byteLength;n!=null&&!isNaN(n)&&(r+=`${Os(this,MI)}Content-Length: ${n}`)}returnOs(this,Zj).encode(`${r}${Os(this,MI).repeat(2)}`)};rIe=newWeakSet;FAt=function(){lett=0;for(let[e,r]ofOs(this,d5)){letn=Yj(r)?r:Os(this,Zj).encode(DAt(r)),o=Yj(n)?n.size:n.byteLength;if(o==null||isNaN(o))return;t+=tIe(this,Moe,iIe).call(this,e,n).byteLength,t+=o,t+=Os(this,Aoe)}returnString(t+Os(this,c5).byteLength)}});varBAt=v((G1o,zAt)=>{zAt.exports=typeofself=="object"?self.FormData:window.FormData});varUAt=v(vc=>{"use strict";varLFr=vc&&vc.__createBinding||(Object.create?function(t,e,r,n){n===void0&&(n=r);varo=Object.getOwnPropertyDescriptor(e,r);(!o||("get"ino?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){returne[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void0&&(n=r),t[n]=e[r]}),FFr=vc&&vc.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),HB=vc&&vc.__importStar||function(t){if(t&&t.__esModule)returnt;vare={};if(t!=null)for(varrint)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&LFr(e,t,r);returnFFr(e,t),e},RI=vc&&vc.__awaiter||function(t,e,r,n){functiono(i){returniinstanceofr?i:newr(function(a){a(i)})}returnnew(r||(r=Promise))(function(i,a){functions(c){try{l(n.next(c))}catch(d){a(d)}}functionu(c){try{l(n.throw(c))}catch(d){a(d)}}functionl(c){c.done?i(c.value):o(c.value).then(s,u)}l((n=n.apply(t,e||[])).next())})};Object.defineProperty(vc,"__esModule",{value:!0});vc.WebFormData=vc.Node16FormData=vc.Node18FormData=vc.newFormData=void0;varRoe=NB();functionaIe(t){returntypeoft=="object"&&t!=null&&"name"int}functionkFr(){returnRI(this,void0,void0,function*(){lett;returnRoe.RUNTIME.type==="node"&&Roe.RUNTIME.parsedVersion!=null&&Roe.RUNTIME.parsedVersion>=18?t=newNoe:Roe.RUNTIME.type==="node"?t=newjoe:t=newDoe,yieldt.setup(),t})}vc.newFormData=kFr;varNoe=class{setup(){returnRI(this,void0,void0,function*(){this.fd=new(yieldPromise.resolve().then(()=>HB(PAt()))).FormData})}append(e,r){varn;(n=this.fd)===null||n===void0||n.append(e,r)}appendFile(e,r,n){varo,i;returnRI(this,void0,void0,function*(){n==null&&aIe(r)&&(n=r.name),rinstanceof(yieldPromise.resolve().then
`);o.enqueue(s)}catch(i){o.error(i)}})},cancel(){varo;returny5(this,void0,void0,function*(){yield(o=r.return)===null||o===void0?void0:o.call(r)})}})}};uu.StreamUtils=EIe;functionqIt(t,e){return_5(this,arguments,function*(){varn,o;if(!t.body)throwe?.abort(),newQB.CohereError({message:"Attempted to iterate over a response with no body"});leti=newTIe,a=newDI,s=AIe(t.body);try{for(varu=b5(rzr(s)),l;l=yieldLa(u.next()),!l.done;){letc=l.value;for(letdofa.decode(c)){letf=i.decode(d);f&&(yieldyieldLa(f))}}}catch(c){n={error:c}}finally{try{l&&!l.done&&(o=u.return)&&(yieldLa(o.call(u)))}finally{if(n)thrown.error}}for(letcofa.flush()){letd=i.decode(c);d&&(yieldyieldLa(d))}})}uu._iterSSEMessages=qIt;functionrzr(t){return_5(this,arguments,function*(){varr,n;leto=newUint8Array;try{for(vari=b5(t),a;a=yieldLa(i.next()),!a.done;){lets=a.value;if(s==null)continue;letu=sinstanceofArrayBuffer?newUint8Array(s):typeofs=="string"?newTextEncoder().encode(s):s,l=newUint8Array(o.length+u.length);l.set(o),l.set(u,o.length),o=l;letc;for(;(c=nzr(o))!==-1;)yieldyieldLa(o.slice(0,c)),o=o.slice(c)}}catch(s){r={error:s}}finally{try{a&&!a.done&&(n=i.return)&&(yieldLa(n.call(i)))}finally{if(r)throwr.error}}o.length>0&&(yieldyieldLa(o))})}functionnzr(t){for(letn=0;n<t.length-2;n++){if(t[n]===10&&t[n+1]===10||t[n]===13&&t[n+1]===13)returnn+2;if(t[n]===13&&t[n+1]===10&&n+3<t.length&&t[n+2]===13&&t[n+3]===10)returnn+4}return-1}varTIe=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)returnnull;leti={event:this.event,data:this.data.join(`
`),raw:this.chunks};returnthis.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))returnnull;let[r,n,o]=izr(e,":");returno.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},DI=classt{constructor(){this.buffer=[],this.trailingCR=!1}decode(e){letr=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[];letn=t.NEWLINE_CHARS.has(r[r.length-1]||""),o=r.split(t.NEWLINE_REGEXP);returnn&&o.pop(),o.length===1&&!n?(this.buffer.push(o[0]),[]):(this.buffer.length>0&&(o=[this.buffer.join("")+o[0],...o.slice(1)],this.buffer=[]),n||(this.buffer=[o.pop()||""]),o)}decodeText(e){varr;if(e==null)return"";if(typeofe=="string")returne;if(typeofBuffer<"u"){if(einstanceofBuffer)returne.toString();if(einstanceofUint8Array)returnBuffer.from(e).toString();thrownewQB.CohereError({message:`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(typeofTextDecoder<"u"){if(einstanceofUint8Array||einstanceofArrayBuffer)return(r=this.textDecoder)!==null&&r!==void0||(this.textDecoder=newTextDecoder("utf8")),this.textDecoder.decode(e);thrownewQB.CohereError({message:`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`})}thrownewQB.CohereError({message:"Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error."})}flush(){if(!this.buffer.length&&!this.trailingCR)return[];lete=[this.buffer.join("")];returnthis.buffer=[],this.trailingCR=!1,e}};uu.LineDecoder=DI;DI.NEWLINE_CHARS=newSet([`
`)}}}}catch(x){a={error:x}}finally{try{h&&!h.done&&(s=m.return)&&(yield s.call(m))}finally{if(a)throw a.error}}for(let x of g.flush()){let S=(0,pi.parseAWSEvent)(x);if(S){let O=yield(0,pi.mapResponseFromBedrock)(c,u,S);y.push(JSON.stringify(O)+`
`)}}return y.end(),{ok:!0,body:y}}else{let b=yield p.body;return{ok:!0,body:yield(0,pi.mapResponseFromBedrock)(c,u,b)}}}catch(b){throw b}});pi.fetchOverride=vYr});var $P=v(tae=>{"use strict";Object.defineProperty(tae,"__esModule",{value:!0});tae.CohereEnvironment=void 0;tae.CohereEnvironment={Production:"https://api.cohere.com"}});var WI=v((m1t,rae)=>{(function(t,e,r){typeof rae<"u"&&rae.exports?rae.exports=r():typeof define=="function"&&define.amd?define(r):e[t]=r()})("urljoin",m1t,function(){function t(e){var r=[];if(e.length===0)return"";if(typeof e[0]!="string")throw new TypeError("Url must be a string. Received "+e[0]);if(e[0].match(/^[^/:]+:\/*$/)&&e.length>1){var n=e.shift();e[0]=n+e[0]}e[0].match(/^file:\/\/\//)?e[0]=e[0].replace(/^([^/:]+):\/*/,"$1:///"):e[0]=e[0].replace(/^([^/:]+):\/*/,"$1://");for(var o=0;o<e.length;o++){var i=e[o];if(typeof i!="string")throw new TypeError("Url must be a string. Received "+i);i!==""&&(o>0&&(i=i.replace(/^[\/]+/,"")),o<e.length-1?i=i.replace(/[\/]+$/,""):i=i.replace(/[\/]+$/,"/"),r.push(i))}var a=r.join("/");a=a.replace(/\/(\?|&|#[^!])/g,"$1");var s=a.split("?");return a=s.shift()+(s.length>0?"?":"")+s.join("&"),a}return function(){var e;return typeof arguments[0]=="object"?e=arguments[0]:e=[].slice.call(arguments),t(e)}})});var z1e=v(cm=>{"use strict";var wYr=cm&&cm.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),xYr=cm&&cm.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),H5=cm&&cm.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&wYr(e,t,r);return xYr(e,t),e},nae=cm&&cm.__awaiter||function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(c){try{l(n.next(c))}catch(d){a(d)}}function u(c){try{l(n.throw(c))}catch(d){a(d)}}function l(c){c.done?i(c.value):o(c.value).then(s,u)}l((n=n.apply(t,e||[])).next())})},SYr=cm&&cm.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(cm,"__esModule",{value:!0});cm.V2=void 0;var h1t=H5($P()),um=H5(G()),Es=H5(lP()),lm=H5(kP()),g1t=SYr(WI()),zP=H5(Hs()),$1e=class{constructor(e={}){this._options=e}chatStream(e,r){var n,o;return nae(this,void 0,void 0,function*(){let i=yield((n=this._options.fetcher)!==null&&n!==void 0?n:um.fetcher)({url:(0,g1t.default)((o=yield um.Supplier.get(this._options.environment))!==null&&o!==void 0?o:h1t.CohereEnvironment.Production,"v2/chat"),method:"POST",headers:{Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield um.Supplier.get(this._options.clientName))!=null?yield um.Supplier.get(this._options.clientName):void 0,"X-Fern-Language":"JavaScript","X-Fern-SDK-Name":"cohere-ai","X-Fern-SDK-Version":"7.13.0","User-Agent":"cohere-ai/7.13.0","X-Fern-Runtime":um.RUNTIME.type,"X-Fern-Runtime-Version":um.RUNTIME.version},contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},lm.V2ChatStreamRequest.jsonOrThrow(e,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0})),{stream:!0}),responseType:"sse",timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:3e5,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(i.ok)return new um.Stream({stream:i.body,parse:a=>nae(this,void 0,void 0,function*(){return lm.StreamedChatResponse2.parseOrThrow(a,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]})}),signal:r?.abortSignal,eventShape:{type:"sse",streamTerminator:"[DONE]"}});if(i.error.reason==="status-code")switch(i.error.statusCode){case 400:throw new Es.BadRequestError(i.error.body);case 401:th
`}});if(i.error.reason==="status-code")switch(i.error.statusCode){case 400:throw new Ee.BadRequestError(i.error.body);case 401:throw new Ee.UnauthorizedError(i.error.body);case 403:throw new Ee.ForbiddenError(i.error.body);case 404:throw new Ee.NotFoundError(i.error.body);case 422:throw new Ee.UnprocessableEntityError(dt.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new Ee.TooManyRequestsError(dt.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new Ee.ClientClosedRequestError(dt.ClientClosedRequestErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 500:throw new Ee.InternalServerError(i.error.body);case 501:throw new Ee.NotImplementedError(dt.NotImplementedErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 503:throw new Ee.ServiceUnavailableError(i.error.body);case 504:throw new Ee.GatewayTimeoutError(dt.GatewayTimeoutErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));default:throw new Vr.CohereError({statusCode:i.error.statusCode,body:i.error.body})}switch(i.error.reason){case"non-json":throw new Vr.CohereError({statusCode:i.error.statusCode,body:i.error.rawBody});case"timeout":throw new Vr.CohereTimeoutError;case"unknown":throw new Vr.CohereError({message:i.error.errorMessage})}})}generate(e,r){var n,o;return gm(this,void 0,void 0,function*(){let i=yield((n=this._options.fetcher)!==null&&n!==void 0?n:xt.fetcher)({url:(0,Tb.default)((o=yield xt.Supplier.get(this._options.environment))!==null&&o!==void 0?o:Eb.CohereEnvironment.Production,"v1/generate"),method:"POST",headers:{Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield xt.Supplier.get(this._options.clientName))!=null?yield xt.Supplier.get(this._options.clientName):void 0,"X-Fern-Language":"JavaScript","X-Fern-SDK-Name":"cohere-ai","X-Fern-SDK-Version":"7.13.0","User-Agent":"cohere-ai/7.13.0","X-Fern-Runtime":xt.RUNTIME.type,"X-Fern-Runtime-Version":xt.RUNTIME.version},contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},dt.GenerateRequest.jsonOrThrow(e,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0})),{stream:!1}),timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:3e5,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(i.ok)return dt.Generation.parseOrThrow(i.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]});if(i.error.reason==="status-code")switch(i.error.statusCode){case 400:throw new Ee.BadRequestError(i.error.body);case 401:throw new Ee.UnauthorizedError(i.error.body);case 403:throw new Ee.ForbiddenError(i.error.body);case 404:throw new Ee.NotFoundError(i.error.body);case 422:throw new Ee.UnprocessableEntityError(dt.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new Ee.TooManyRequestsError(dt.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new Ee.ClientClosedRequestError(dt.ClientClosedRequestErrorBody.parseOrThrow(i.error.body,{u
`,"\r"]);ED.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function d9(){}function Bae(t,e,r){return!e||Uae[t]>Uae[r]?d9:e[t].bind(e)}function Zs(t){let e=t.logger,r=t.logLevel??"off";if(!e)return JQr;let n=Djt.get(e);if(n&&n[0]===r)return n[1];let o={error:Bae("error",e,r),warn:Bae("warn",e,r),info:Bae("info",e,r),debug:Bae("debug",e,r)};return Djt.set(e,[r,o]),o}var Uae,GNe,JQr,Djt,VP,f9=w(()=>{HP();Uae={off:0,error:200,warn:300,info:400,debug:500},GNe=(t,e,r)=>{if(t){if(ljt(Uae,t))return t;Zs(r).warn(`${e}wassetto${JSON.stringify(t)},expectedoneof${JSON.stringify(Object.keys(Uae))}`)}};JQr={error:d9,warn:d9,info:d9,debug:d9},Djt=new WeakMap;VP=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,r])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t)});async function*ZQr(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new gt("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new gt("Attempted to iterate over a response with no body");let r=new JNe,n=new ED,o=zNe(t.body);for await(let i of YQr(o))for(let a of n.decode(i)){let s=r.decode(a);s&&(yield s)}for(let i of n.flush()){let a=r.decode(i);a&&(yield a)}}async function*YQr(t){let e=new Uint8Array;for await(let r of t){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?UU(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let i;for(;(i=Njt(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function XQr(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var p9,pC,JNe,ZNe=w(()=>{Kg();cC();c9();jjt();c9();jae();zae();f9();cC();pC=class t{constructor(e,r,n){this.iterator=e,p9.set(this,void 0),this.controller=r,Xt(this,p9,n,"f")}static fromSSEResponse(e,r,n){let o=!1,i=n?Zs(n):console;async function*a(){if(o)throw new gt("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let s=!1;try{for await(let u of ZQr(e,r))if(!s){if(u.data.startsWith("[DONE]")){s=!0;continue}if(u.event===null||!u.event.startsWith("thread.")){let l;try{l=JSON.parse(u.data)}catch(c){throw i.error("Could not parse message into JSON:",u.data),i.error("From chunk:",u.raw),c}if(l&&l.error)throw new Xl(void 0,l.error,void 0,e.headers);yield l}else{let l;try{l=JSON.parse(u.data)}catch(c){throw console.error("Could not parse message into JSON:",u.data),console.error("From chunk:",u.raw),c}if(u.event=="error")throw new Xl(void 0,l.error,l.message,void 0);yield{event:u.event,data:l}}}s=!0}catch(u){if(u9(u))return;throw u}finally{s||r.abort()}}return new t(a,r,n)}static fromReadableStream(e,r,n){let o=!1;async function*i(){let s=new ED,u=zNe(e);for await(let l of u)for(let c of s.decode(l))yield c;for(let l of s.flush())yield l}async function*a(){if(o)throw new gt("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let s=!1;try{for await(let u of i())s||u&&(yield JSON.parse(u));s=!0}catch(u){if(u9(u))return;throw u}finally{s||r.abort()}}return new t(a,r,n)}[(p9=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),o=i=>({next:()=>{if(i.length===0){let a=n.next();e.push(a),r.push(a)}return i.shift()}});return[new t(()=>o(e),this.controller,ie(this,p9,"f")),new t(()=>o(r),this.controller,ie(this,p9,"f"))]}toReadableStream(){let e=this,r;return $Ne({async start(){r=e[Symbol.asyncIterator]()},async pull(n){try{let{value:o,done:i}=await r.next();if(i)return n.close();let a=UU(JSON.stringify(o)+`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,o]=XQr(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}}});async function qae(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:o,startTime:i}=e,a=await(async()=>{if(e.options.stream)return Zs(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller,t):pC.fromSSEResponse(r,e.controller,t);if(r.status===204)return null;if(e.options.__binaryResponse)return r;let u=r.headers.get("content-type")?.split(";")[0]?.trim();if(u?.includes("application/json")||u?.endsWith("+json")){let d=await r.json();return YNe(d,r)}return await r.text()})();return Zs(t).debug(`[${n}]responseparsed`,VP({retryOfRequestLogID:o,url:r.url,status:r.status,body:a,durationMs:Date.now()-i})),a}function YNe(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var XNe=w(()=>{ZNe();f9()});var m9,TD,Hae=w(()=>{Kg();XNe();TD=class t extends Promise{constructor(e,r,n=qae){super(o=>{o(null)}),this.responsePromise=r,this.parseResponse=n,m9.set(this,void 0),Xt(this,m9,e,"f")}_thenUnwrap(e){return new t(ie(this,m9,"f"),this.responsePromise,async(r,n)=>YNe(e(await this.parseResponse(r,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r,request_id:r.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(ie(this,m9,"f"),e))),this.parsedPromise}then(e,r){return this.parse().then(e,r)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};m9=new WeakMap});var Vae,Wae,h9,mC,hn,$a=w(()=>{Kg();cC();XNe();Hae();HP();Wae=class{constructor(e,r,n,o){Vae.set(this,void 0),Xt(this,Vae,e,"f"),this.options=o,this.response=r,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new gt("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await ie(this,Vae,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Vae=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},h9=class extends TD{constructor(e,r,n){super(e,r,async(o,i)=>new n(o,i.response,await qae(o,i),i.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},mC=class extends Wae{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},hn=class extends Wae{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),r=e[e.length-1]?.id;return r?{...this.options,query:{...sjt(this.options.query),after:r}}:null}}});function qU(t,e,r){return eje(),new File(t,e??"unknown_file",r)}function g9(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}function een(t){let e=typeof t=="function"?t:t.fetch,r=Ljt.get(e);if(r)return r;let n=(async()=>{try{let o="Response"in e?e.Response:(await e("data:,")).constructor,i=new FormData;return i.toString()!==await new o(i).text()}catch{return!0}})();return Ljt.set(e,n),n}var eje,tje,xh,Ljt,ten,ren,QNe,WP=w(()=>{c9();eje=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&pa
${i.map(f=>f.error).join(`
`)}
${a}
${d}`)}returna},je=sen(zjt)});varAD,Kae=w(()=>{Cr();$a();Vi();AD=classextendsBe{list(e,r={},n){returnthis._client.getAPIList(je`/chat/completions/${e}/messages`,hn,{query:r,...n})}}});varRb=w(()=>{cC()});functionb9(t){returnt!==void0&&"function"int&&t.function!==void0}functionBjt(t,e){letr={...t};returnObject.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function_9(t){returnt?.$brand==="auto-parseable-response-format"}functionID(t){returnt?.$brand==="auto-parseable-tool"}functionUjt(t,e){return!e||!oje(e)?{...t,choices:t.choices.map(r=>(Hjt(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void0}}))}:v9(t,e)}functionv9(t,e){letr=t.choices.map(n=>{if(n.finish_reason==="length")thrownewkU;if(n.finish_reason==="content_filter")thrownew$U;returnHjt(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(o=>den(e,o))??void0}:void0,parsed:n.message.content&&!n.message.refusal?cen(e,n.message.content):null}}});return{...t,choices:r}}functioncen(t,e){returnt.response_format?.type!=="json_schema"?null:t.response_format?.type==="json_schema"?"$parseRaw"int.response_format?t.response_format.$parseRaw(e):JSON.parse(e):null}functionden(t,e){letr=t.tools?.find(n=>b9(n)&&n.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:ID(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}functionqjt(t,e){if(!t||!("tools"int)||!t.tools)return!1;letr=t.tools?.find(n=>b9(n)&&n.function?.name===e.function.name);returnb9(r)&&(ID(r)||r?.function.strict||!1)}functionoje(t){return_9(t.response_format)?!0:t.tools?.some(e=>ID(e)||e.type==="function"&&e.function.strict===!0)??!1}functionHjt(t){for(leteoft||[])if(e.type!=="function")thrownewgt(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}functionVjt(t){for(leteoft??[]){if(e.type!=="function")thrownewgt(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)thrownewgt(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}varHU=w(()=>{Rb()});varVU,ije,aje=w(()=>{VU=t=>t?.role==="assistant",ije=t=>t?.role==="tool"});varsje,Gae,Jae,w9,x9,Zae,S9,KP,C9,Yae,Xae,WU,Wjt,QI,Qae=w(()=>{Kg();Rb();QI=class{constructor(){sje.add(this),this.controller=newAbortController,Gae.set(this,void0),Jae.set(this,()=>{}),w9.set(this,()=>{}),x9.set(this,void0),Zae.set(this,()=>{}),S9.set(this,()=>{}),KP.set(this,{}),C9.set(this,!1),Yae.set(this,!1),Xae.set(this,!1),WU.set(this,!1),Xt(this,Gae,newPromise((e,r)=>{Xt(this,Jae,e,"f"),Xt(this,w9,r,"f")}),"f"),Xt(this,x9,newPromise((e,r)=>{Xt(this,Zae,e,"f"),Xt(this,S9,r,"f")}),"f"),ie(this,Gae,"f").catch(()=>{}),ie(this,x9,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},ie(this,sje,"m",Wjt).bind(this))},0)}_connected(){this.ended||(ie(this,Jae,"f").call(this),this._emit("connect"))}getended(){returnie(this,C9,"f")}geterrored(){returnie(this,Yae,"f")}getaborted(){returnie(this,Xae,"f")}abort(){this.controller.abort()}on(e,r){return(ie(this,KP,"f")[e]||(ie(this,KP,"f")[e]=[])).push({listener:r}),this}off(e,r){letn=ie(this,KP,"f")[e];if(!n)returnthis;leto=n.findIndex(i=>i.listener===r);returno>=0&&n.splice(o,1),this}once(e,r){return(ie(this,KP,"f")[e]||(ie(this,KP,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){returnnewPromise((r,n)=>{Xt(this,WU,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}asyncdone(){Xt(this,WU,!0,"f"),awaitie(this,x9,"f")}_emit(e,...r){if(ie(this,C9,"f"))return;e==="end"&&(Xt(this,C9,!0,"f"),ie(this,Zae,"f").call(this));letn=ie(this,KP,"f")[e];if(n&&(ie(this,KP,"f")[e]=n.filter(o=>!o.once),n.forEach(({listener:o})=>o(...r))),e==="abort"){leto=r[0];!ie(this,WU,"f")&&!n?.length&&Promise.reject(o),ie(t
\r`.includes(t[n]);)n++};return a()},yje=t=>pen(t,Oc.ALL^Oc.NUM)});var bje=w(()=>{ZNe()});function hen(t,e){let{id:r,choices:n,created:o,model:i,system_fingerprint:a,...s}=t,u={...s,id:r,choices:n.map(({message:l,finish_reason:c,index:d,logprobs:f,...p})=>{if(!c)throw new gt(`missingfinish_reasonforchoice${d}`);let{content:m=null,function_call:h,tool_calls:b,...g}=l,y=l.role;if(!y)throw new gt(`missingroleforchoice${d}`);if(h){let{arguments:x,name:S}=h;if(x==null)throw new gt(`missingfunction_call.argumentsforchoice${d}`);if(!S)throw new gt(`missingfunction_call.nameforchoice${d}`);return{...p,message:{content:m,function_call:{arguments:x,name:S},role:y,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}return b?{...p,index:d,finish_reason:c,logprobs:f,message:{...g,role:y,content:m,refusal:l.refusal??null,tool_calls:b.map((x,S)=>{let{function:O,type:E,id:P,...A}=x,{arguments:I,name:R,...N}=O||{};if(P==null)throw new gt(`missingchoices[${d}].tool_calls[${S}].id
${nse(t)}`);if(E==null)throw new gt(`missingchoices[${d}].tool_calls[${S}].type
${nse(t)}`);if(R==null)throw new gt(`missingchoices[${d}].tool_calls[${S}].function.name
${nse(t)}`);if(I==null)throw new gt(`missingchoices[${d}].tool_calls[${S}].function.arguments
${nse(t)}`);return{...A,id:P,type:E,function:{...N,name:R,arguments:I}}})}}:{...p,message:{...g,content:m,role:y,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}),created:o,model:i,object:"chat.completion",...a?{system_fingerprint:a}:{}};return Ujt(u,e)}function nse(t){return JSON.stringify(t)}var ec,GP,GU,eM,_je,tse,vje,wje,xje,rse,Sje,Yjt,MD,ose=w(()=>{Kg();Zjt();Rb();HU();bje();pje();MD=class t extends KU{constructor(e){super(),ec.add(this),GP.set(this,void 0),GU.set(this,void 0),eM.set(this,void 0),Xt(this,GP,e,"f"),Xt(this,GU,[],"f")}get currentChatCompletionSnapshot(){return ie(this,eM,"f")}static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static createChatCompletion(e,r,n){let o=new t(r);return o._run(()=>o._runChatCompletion(e,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createChatCompletion(e,r,n){super._createChatCompletion;let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),ie(this,ec,"m",_je).call(this);let i=await e.chat.completions.create({...r,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let a of i)ie(this,ec,"m",vje).call(this,a);if(i.controller.signal?.aborted)throw new Is;return this._addChatCompletion(ie(this,ec,"m",rse).call(this))}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),ie(this,ec,"m",_je).call(this),this._connected();let o=pC.fromReadableStream(e,this.controller),i;for await(let a of o)i&&i!==a.id&&this._addChatCompletion(ie(this,ec,"m",rse).call(this)),ie(this,ec,"m",vje).call(this,a),i=a.id;if(o.controller.signal?.aborted)throw new Is;return this._addChatCompletion(ie(this,ec,"m",rse).call(this))}[(GP=new WeakMap,GU=new WeakMap,eM=new WeakMap,ec=new WeakSet,_je=function(){this.ended||Xt(this,eM,void 0,"f")},tse=function(r){let n=ie(this,GU,"f")[r.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},ie(this,GU,"f")[r.index]=n,n)},vje=function(r){if(this.ended)return;let n=ie(this,ec,"m",Yjt).call(this,r);this._emit("chunk",r,n);for(let o of r.choices){let i=n.choices[o.index];o.delta.content!=null&&i.message?.role==="assistant"&&i.message?.content&&(this._emit("content",o.delta.content,i.message.content),this._emit("content.delta",{delta:o.delta.content,snapshot:i.message.content,parsed:i.message.parsed})),o.delta.refusal!=null&&i.message?.role==="assistant"&&i.message?.refusal&&this._emit("refusal.delta",{delta:o.delta.refusal,snapshot:i.message.refusal}),o.logprobs?.content!=null&&i.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:o.logprobs?.content,snapshot:i.logprobs?.content??[]}),o.logprobs?.refusal!=null&&i.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:o.logprobs?.refusal,snapshot:i.logprobs?.refusal??[]});let a=ie(this,ec,"m",tse).call(this,i);i.finish_reason&&(ie(this,ec,"m",xje).call(this,i),a.current_tool_call_index!=null&&ie(this,ec,"m",wje).call(this,i,a.current_tool_call_index));for(let s of o.delta.tool_calls??[])a.current_tool_call_index!==s.index&&(ie(this,ec,"m",xje).call(this,i),a.current_tool_call_index!=null&&ie(this,ec,"m",wje).call(this,i,a.current_tool_call_index)),a.current_tool_call_index=s.index;for(let s of o.delta.tool_calls??[]){let u=i.message.tool_calls?.[s.index];u?.type&&(u?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:u.function?.name,index:s.index,arguments:u.function.arguments,parsed_arguments:u.function.parsed_arguments,arguments_delta:s.function?.arguments??""}):(u?.type,void 0))}}},wje=function(r,n){if(ie(this,ec,"m",tse).call(this,r).done_tool_calls.has(n))return;let i=r.message.tool_calls?.[n];if(!i)throw new Error("no tool call snapshot");if(!i.type)throw new Error("tool call snapshot missing `type`");if(i.type==="function"){let a=ie(this,GP,"f")?.tools?.find(s=>b9(s)&&s.funct
`);this.baseURL=s.baseURL,this.timeout=s.timeout??wDe.DEFAULT_TIMEOUT,this.logger=s.logger??console;letu="warn";this.logLevel=u,this.logLevel=GNe(s.logLevel,"ClientOptions.logLevel",this)??GNe(Nb("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??yjt(),Xt(this,hse,_jt,"f"),this._options=s,this.apiKey=r,this.organization=n,this.project=o,this.webhookSecret=i}withOptions(e){returnnewthis.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){returnthis._options.defaultQuery}validateHeaders({values:e,nulls:r}){}asyncauthHeaders(e){returnmt([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){returnWNe(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${XI}`}defaultIdempotencyKey(){return`stainless-node-retry-${jNe()}`}makeStatusError(e,r,n,o){returnXl.generate(e,r,n,o)}buildURL(e,r,n){leto=!ie(this,vDe,"m",wDt).call(this)&&n||this.baseURL,i=ajt(e)?newURL(e):newURL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();returnujt(a)||(r={...a,...r}),typeofr=="object"&&r&&!Array.isArray(r)&&(i.search=this.stringifyQuery(r)),i.toString()}asyncprepareOptions(e){}asyncprepareRequest(e,{url:r,options:n}){}get(e,r){returnthis.methodRequest("get",e,r)}post(e,r){returnthis.methodRequest("post",e,r)}patch(e,r){returnthis.methodRequest("patch",e,r)}put(e,r){returnthis.methodRequest("put",e,r)}delete(e,r){returnthis.methodRequest("delete",e,r)}methodRequest(e,r,n){returnthis.request(Promise.resolve(n).then(o=>({method:e,path:r,...o})))}request(e,r=null){returnnewTD(this,this.makeRequest(e,r,void0))}asyncmakeRequest(e,r,n){leto=awaite,i=o.maxRetries??this.maxRetries;r==null&&(r=i),awaitthis.prepareOptions(o);let{req:a,url:s,timeout:u}=awaitthis.buildRequest(o,{retryCount:i-r});awaitthis.prepareRequest(a,{url:s,options:o});letl="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),c=n===void0?"":`, retryOf: ${n}`,d=Date.now();if(Zs(this).debug(`[${l}] sending request`,VP({retryOfRequestLogID:n,method:o.method,url:s,options:o,headers:a.headers})),o.signal?.aborted)thrownewIs;letf=newAbortController,p=awaitthis.fetchWithTimeout(s,a,u,f).catch(l9),m=Date.now();if(pinstanceofError){letg=`retrying, ${r} attempts remaining`;if(o.signal?.aborted)thrownewIs;lety=u9(p)||/timed? ?out/i.test(String(p)+("cause"inp?String(p.cause):""));if(r)returnZs(this).info(`[${l}] connection ${y?"timed out":"failed"} - ${g}`),Zs(this).debug(`[${l}] connection ${y?"timed out":"failed"} (${g})`,VP({retryOfRequestLogID:n,url:s,durationMs:m-d,message:p.message})),this.retryRequest(o,r,n??l);throwZs(this).info(`[${l}] connection ${y?"timed out":"failed"} - error; no more retries left`),Zs(this).debug(`[${l}] connection ${y?"timed out":"failed"} (error; no more retries left)`,VP({retryOfRequestLogID:n,url:s,durationMs:m-d,message:p.message})),y?newuC:newYI({cause:p})}leth=[...p.headers.entries()].filter(([g])=>g==="x-request-id").map(([g,y])=>", "+g+": "+JSON.stringify(y)).join(""),b=`[${l}${c}${h}] ${a.method}${s}${p.ok?"succeeded":"failed"} with status ${p.status} in ${m-d}ms`;if(!p.ok){letg=awaitthis.shouldRetry(p);if(r&&g){letP=`retrying, ${r} attempts remaining`;returnawaitbjt(p.body),Zs(this).info(`${b} - ${P}`),Zs(this).debug(`[${l}] response error (${P})`,VP({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:m-d})),this.retryRequest(o,r,n??l,p.headers)}lety=g?"error; no more retries left":"error; not retryable";Zs(this).info(`${b} - ${y}`);letx=awaitp.text().catch(P=>l9(P).message),S=djt(x),O=S?void0:x;throwZs(this).debug(`[${l}] response error (${y})`,VP({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,message:O,durationMs:Date.now()-d})),this.makeStatusE
`))}let n={name:t.function.name,args:r,type:"tool_call"};return e?.returnId&&(n.id=t.id),n}function _C(t){if(t.id===void 0)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:t.id,type:"function",function:{name:t.name,arguments:JSON.stringify(t.args)}}}function _m(t,e){return{name:t.function?.name,args:t.function?.arguments,id:t.id,error:e,type:"invalid_tool_call"}}var xDe,wd,CDt=w(()=>{m$();hve();iA();oN();LO();xDe=class extends pN{static lc_name(){return"JsonOutputToolsParser"}constructor(e){super(e),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","output_parsers","openai_tools"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.returnId=e?.returnId??this.returnId}_diff(){throw new Error("Not supported.")}async parse(){throw new Error("Not implemented.")}async parseResult(e){return await this.parsePartialResult(e,!1)}async parsePartialResult(e,r=!0){let n=e[0].message,o;if(Di(n)&&n.tool_calls?.length?o=n.tool_calls.map(a=>{let{id:s,...u}=a;return this.returnId?{id:s,...u}:u}):n.additional_kwargs.tool_calls!==void 0&&(o=JSON.parse(JSON.stringify(n.additional_kwargs.tool_calls)).map(s=>bm(s,{returnId:this.returnId,partial:r}))),!o)return[];let i=[];for(let a of o)if(a!==void 0){let s={type:a.name,args:a.args,id:a.id};i.push(s)}return i}},wd=class extends xDe{static lc_name(){return"JsonOutputKeyToolsParser"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","output_parsers","openai_tools"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"keyName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"returnSingle",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"zodSchema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async _validateResult(e){if(this.zodSchema===void 0)return e;let r=await gKe(this.zodSchema,e);if(r.success)return r.data;throw new Km(`Failedtoparse.Text:"${JSON.stringify(e,null,2)}".Error:${JSON.stringify(r.error?.issues)}`,JSON.stringify(e,null,2))}async parsePartialResult(e){let n=(await super.parsePartialResult(e)).filter(i=>i.type===this.keyName),o=n;if(n.length)return this.returnId||(o=n.map(i=>i.args)),this.returnSingle?o[0]:o}async parseResult(e){let n=(await super.parsePartialResult(e,!1)).filter(a=>a.type===this.keyName),o=n;return n.length?(this.returnId||(o=n.map(a=>a.args)),this.returnSingle?this._validateResult(o[0]):await Promise.all(o.map(a=>this._validateResult(a)))):void 0}}});var ODt=w(()=>{CDt()});var yq=w(()=>{ODt()});var SDe=w(()=>{uN()});function XP(t){let{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:r,azureOpenAIApiKey:n,azureOpenAIBasePath:o,baseURL:i,azureADTokenProvider:a,azureOpenAIEndpoint:s}=t;if((n||a)&&o&&e)return`${o}/${e}`;if((n||a)&&s&&e)return`${s}/openai/deployments/${e}`;if(n||a){if(!r)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!e)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${r}.openai.azure.com/openai/deployments/${e}`}return i}var cM=w(()=>{});var EDt,PDt,TDt,yse=w(()=>{EDt=Symbol("Let zodToJsonSchema decide on which parser to use"),PDt={name:void 0,$refStrategy:"root",effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",nullableStrategy:"from-target",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStr
`);case"array":returnt.items?`${Sse(t.items,e)}[]`:"any[]";default:return""}}varpLt=w(()=>{});functionmLt(t,e){letr;returnCc(t)?r=oC(t):r=t,r.type==="function"&&e?.strict!==void0&&(r.function.strict=e.strict),r}functionCse(t){return"type"int&&t.type!=="function"&&t.type!=="custom"}functionhLt(t){returnt!=null&&typeoft=="object"&&"type"int&&t.type!=="function"}functiongLt(t){returntypeoft=="object"&&t!==null&&"metadata"int&&typeoft.metadata=="object"&&t.metadata!==null&&"customTool"int.metadata&&typeoft.metadata.customTool=="object"&&t.metadata.customTool!==null}functioniLe(t){return"type"int&&t.type==="custom"&&"custom"int&&typeoft.custom=="object"&&t.custom!==null}functionyLt(t){if(t.type==="custom_tool_call")return{...t,type:"tool_call",call_id:t.id,id:t.call_id,name:t.name,isCustomTool:!0,args:{input:t.input}}}functionbLt(t){returnt.type==="tool_call"&&"isCustomTool"int&&t.isCustomTool===!0}function_Lt(t){lete=()=>{if(t.custom.format){if(t.custom.format.type==="grammar")return{type:"grammar",definition:t.custom.format.grammar.definition,syntax:t.custom.format.grammar.syntax};if(t.custom.format.type==="text")return{type:"text"}}};return{type:"custom",name:t.custom.name,description:t.custom.description,format:e()}}functionvLt(t){lete=()=>{if(t.format){if(t.format.type==="grammar")return{type:"grammar",grammar:{definition:t.format.definition,syntax:t.format.syntax}};if(t.format.type==="text")return{type:"text"}}};return{type:"custom",custom:{name:t.name,description:t.description,format:e()}}}varwLt=w(()=>{_h();YD()});functionEse(t){returnt&&(/^o\d/.test(t)||t.startsWith("gpt-5"))}functionctn(t){returnt!==void0&&typeoft.schema=="object"}functiondtn(t){returnt.role!=="system"&&t.role!=="developer"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function"&&t.role!=="tool"&&console.warn(`Unknown message role: ${t.role}`),t.role}functionsLe(t){lete=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(!ks.isInstance(t))thrownewError("Invalid generic chat message");returndtn(t)}default:thrownewError(`Unknown message type: ${e}`)}}functionaLe(t,e){returnt.flatMap(r=>{letn=sLe(r);n==="system"&&Ese(e)&&(n="developer");leto=typeofr.content=="string"?r.content:r.content.map(a=>Jy(a)?SH(a,xLt):a),i={role:n,content:o};if(r.name!=null&&(i.name=r.name),r.additional_kwargs.function_call!=null&&(i.function_call=r.additional_kwargs.function_call,i.content=""),Di(r)&&r.tool_calls?.length?(i.tool_calls=r.tool_calls.map(_C),i.content=""):(r.additional_kwargs.tool_calls!=null&&(i.tool_calls=r.additional_kwargs.tool_calls),r.tool_call_id!=null&&(i.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeofr.additional_kwargs.audio=="object"&&"id"inr.additional_kwargs.audio){leta={role:"assistant",audio:{id:r.additional_kwargs.audio.id}};return[i,a]}returni})}varbq,xLt,D9,Ose,Pse,vC,Tse=w(()=>{bC();As();Of();Kn();iC();bh();Jp();eb();yq();CD();SDe();cM();YD();pLt();wLt();bq="__openai_function_call_ids__";xLt={providerName:"ChatOpenAI",fromStandardTextBlock(t){return{type:"text",text:t.text}},fromStandardImageBlock(t){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};if(t.source_type==="base64")return{type:"image_url",image_url:{url:`data:${t.mime_type??""};base64,${t.data}`,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};thrownewError(`Image content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(t){if(t.source_type==="url"){lete=Xk({dataUrl:t.url});if(!e)thrownewError(`URL audio blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);letr=e.mime_type||t.mime_type||"",n;try{n=Qbe(r)}catch{thrownewError(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(n.type!=="audio"||n.subtype!=="wav"&&n.subtype!=="mp3")thrownewError(`Audio blocks with sou
Details: ${m.message}`),newnN(h,JSON.stringify(e))}else{letm=da(o,this.schema);if(!m.valid){leth="Received tool input did not match expected schema";throwthis.verboseParsingErrors&&(h=`${h}
`)}`),newnN(h,JSON.stringify(e))}i=o}leta=aN(r),u=awaitru.configure(a.callbacks,this.callbacks,a.tags||n,this.tags,a.metadata,this.metadata,{verbose:this.verbose})?.handleToolStart(this.toJSON(),typeofe=="string"?e:JSON.stringify(e),a.runId,void0,void0,void0,a.runName);deletea.runId;letl;try{l=awaitthis._call(i,u,a)}catch(m){throwawaitu?.handleToolError(m),m}letc,d;if(this.responseFormat==="content_and_artifact")if(Array.isArray(l)&&l.length===2)[c,d]=l;elsethrownewError(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
Result: ${JSON.stringify(l)}`);elsec=l;letf;ZT(e)&&(f=e.id),!f&&N9e(a)&&(f=a.toolCall.id);letp=ptn({content:c,artifact:d,toolCallId:f,name:this.name,metadata:this.metadata});returnawaitu?.handleToolEnd(p),p}},QP=classextendsRse{constructor(e){super(e),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:rn.object({input:rn.string().optional()}).transform(r=>r.input)})}call(e,r){letn=typeofe=="string"||e==null?{input:e}:e;returnsuper.call(n,r)}},Nse=classextendsQP{staticlc_name(){return"DynamicTool"}constructor(e){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void0}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:void0}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void0}),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}asynccall(e,r){letn=aN(r);returnn.runName===void0&&(n.runName=this.name),super.call(e,n)}async_call(e,r,n){returnthis.func(e,r,n)}},cLe=classextendsRse{staticlc_name(){return"DynamicStructuredTool"}constructor(e){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void0}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:void0}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void0}),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:void0}),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect,this.schema=e.schema}asynccall(e,r,n){leto=aN(r);returno.runName===void0&&(o.runName=this.name),super.call(e,o,n)}_call(e,r,n){returnthis.func(e,r,n)}}});vareE=w(()=>{ILt()});vardLe,MLt=w(()=>{Kn();bC();eE();dLe=classextendsQP{staticlc_name(){return"DallEAPIWrapper"}constructor(e){e?.responseFormat!==void0&&["url","b64_json"].includes(e.responseFormat)&&(e.dallEResponseFormat=e.responseFormat,e.responseFormat="content"),super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"dalle_api_wrapper"}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:"A wrapper around OpenAI DALL-E API. Useful for when you need to generate images from a text description. Input should be an image description."}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void0}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"dall-e-3"}),Object.defineProperty(this,"style",{enumerable:!0,configurable:!0,writable:!0,value:"vivid"}),Object.defineProperty(this,"quality",{enumerable:!0,configurable:!0,writable:!0,value:"standard"}),Object.defineProperty(this,"n",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:"1024x1024"}),Object.defineProperty(this,"dallEResponseFormat",{enumerable:!0,configurable:!0,writable:!0,value:"url"}),Object.defineProperty(this,"user",{enumerable:!0,configurable:!0,writable:!0,value:void0});letr=e?.apiKey??e?.openAIApiKey??ct("OPENAI_API_KEY"),n=e?.organization??ct("OPENAI_ORGANIZATION"),o={apiKey:r,organization:n,dangerouslyAllowBrowser:!0,baseURL:e?.baseUrl};this.client=new_r(o),this.model=e?.model??e?.modelName??this.model,this.style=e?.style??this.style,this.quality=e?.quality??this.quality,this.n=e?.n??this.n,this.size=e?.size??this.size,this.dallEResponseFormat=e?.dallEResponseFormat??this.dallEResponseFormat,this.user=e?.user}processMultipleGeneratedUrls(e){returnthis.dallEResponseFormat==="url"?e.flatMap(r=>r.data?.flatMap(o=>o.url?{type:"image_url",image_url:o.url}:[]).filter(o=>o!==void0&&o.type==="image_url"&&typeofo.image_url=="string"&&o.image_url!==void0)??[]):e.flatMap(r=>r.data?.flatMap(o=>o.b64_json?{type:"image_url",image_url:{url:o.b64_json}}:[]).filter(o=>o!==void0&&o.type==="image_url"&&typeofo
- `),xtn={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.
- ${wtn}`,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:",PLUGIN_SECURE_PROXY_NOT_FOUND:`Could not find '@orama/secure-proxy-plugin' installed in your Orama instance.
Please install it before proceeding with creating an answer session.
Read more at https://docs.orama.com/open-source/plugins/plugin-secure-proxy
`,PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL:`Could not find a chat model defined in the secure proxy plugin configuration.
Please provide a chat model before proceeding with creating an answer session.
Read more at https://docs.orama.com/open-source/plugins/plugin-secure-proxy
`,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:"The last message in the session is not an assistant message. Cannot regenerate non-assistant messages."}});functionZLt(t){return{raw:Number(t),formatted:QD(t)}}functionYLt(t){if(t.id){if(typeoft.id!="string")throwGt("DOCUMENT_ID_MUST_BE_STRING",typeoft.id);returnt.id}returnF9()}functionmLe(t,e){for(let[r,n]ofObject.entries(e)){leto=t[r];if(!(typeofo>"u")&&!(n==="geopoint"&&typeofo=="object"&&typeofo.lon=="number"&&typeofo.lat=="number")&&!(n==="enum"&&(typeofo=="string"||typeofo=="number"))){if(n==="enum[]"&&Array.isArray(o)){leti=o.length;for(leta=0;a<i;a++)if(typeofo[a]!="string"&&typeofo[a]!="number")returnr+"."+a;continue}if(tE(n)){leti=gLe(n);if(!Array.isArray(o)||o.length!==i)throwGt("INVALID_INPUT_VECTOR",r,i,o.length);continue}if(xq(n)){if(!Array.isArray(o))returnr;leti=hLe(n),a=o.length;for(lets=0;s<a;s++)if(typeofo[s]!==i)returnr+"."+s;continue}if(typeofn=="object"){if(!o||typeofo!="object")returnr;leti=mLe(o,n);if(i)returnr+"."+i;continue}if(typeofo!==n)returnr}}}functionXLt(t){returnt==="geopoint"}functiontE(t){returntypeoft=="string"&&/^vector\[\d+\]$/.test(t)}functionxq(t){returntypeoft=="string"&&Stn[t]}functionhLe(t){returnCtn[t]}functiongLe(t){lete=Number(t.slice(7,-1));switch(!0){caseisNaN(e):throwGt("INVALID_VECTOR_VALUE",t);casee<=0:throwGt("INVALID_VECTOR_SIZE",t);default:returne}}varStn,Ctn,k9=w(()=>{Pc();Ys();Ys();Stn={string:!1,number:!1,boolean:!1,enum:!1,geopoint:!1,"string[]":!0,"number[]":!0,"boolean[]":!0,"enum[]":!0},Ctn={"string[]":"string","number[]":"number","boolean[]":"boolean","enum[]":"enum"}});functionQLt(){return{idToInternalId:newMap,internalIdToId:[],save:Otn,load:Ptn}}functionOtn(t){return{internalIdToId:t.internalIdToId}}functionPtn(t,e){let{internalIdToId:r}=e;t.internalDocumentIDStore.idToInternalId.clear(),t.internalDocumentIDStore.internalIdToId=[];letn=r.length;for(leto=0;o<n;o++){leti=r[o];t.internalDocumentIDStore.idToInternalId.set(i,o+1),t.internalDocumentIDStore.internalIdToId.push(i)}}functionIi(t,e){if(typeofe=="string"){letr=t.idToInternalId.get(e);if(r)returnr;letn=t.idToInternalId.size+1;returnt.idToInternalId.set(e,n),t.internalIdToId.push(e),n}returne>t.internalIdToId.length?Ii(t,e.toString()):e}functionJg(t,e){if(t.internalIdToId.length<e)thrownewError(`Invalid internalId ${e}`);returnt.internalIdToId[e-1]}varZg=w(()=>{});functionTtn(t,e){return{sharedInternalDocumentStore:e,docs:{},count:0}}functionAtn(t,e){letr=Ii(t.sharedInternalDocumentStore,e);returnt.docs[r]}functionItn(t,e){letr=e.length,n=Array.from({length:r});for(leto=0;o<r;o++){leti=Ii(t.sharedInternalDocumentStore,e[o]);n[o]=t.docs[i]}returnn}functionMtn(t){returnt.docs}functionRtn(t,e,r){letn=Ii(t.sharedInternalDocumentStore,e);returntypeoft.docs[n]<"u"?!1:(t.docs[n]=r,t.count++,!0)}functionNtn(t,e){letr=Ii(t.sharedInternalDocumentStore,e);returntypeoft.docs[r]>"u"?!1:(deletet.docs[r],t.count--,!0)}functionjtn(t){returnt.count}functionDtn(t,e){letr=e;return{docs:r.docs,count:r.count,sharedInternalDocumentStore:t}}functionLtn(t){return{docs:t.docs,count:t.count}}functioneFt(){return{create:Ttn,get:Atn,getMultiple:Itn,getAll:Mtn,store:Rtn,remove:Ntn,count:jtn,load:Dtn,save:Ltn}}varyLe=w(()=>{Zg()});functionrFt(t,e){letr=[],n=t.plugins?.length;if(!n)returnr;for(leto=0;o<n;o++)try{leti=t.plugins[o];typeofi[e]=="function"&&r.push(i[e])}catch(i){throwconsole.error("Caught error in getAllPluginsByHook:",i),Gt("PLUGIN_CRASHED")}returnr}vartFt,nFt=w(()=>{Pc();tFt=["beforeInsert","afterInsert","beforeRemove","afterRemove","beforeUpdate","afterUpdate","beforeSearch","afterSearch","beforeInsertMultiple","afterInsertMultiple","beforeRemoveMultiple","afterRemoveMultiple","beforeUpdateMultiple","afterUpdateMultiple","beforeLoad","afterLoad","afterCreate"]});function$b(t,e,r,n){if(t.some(hu))return(async()=>{for(letioft)awaiti(e,r,n)})();for(letioft)i(e,r,n)}functioneL(t,e,r){if(t.some(hu))return(async()=>{for(letooft)awaito(e,r)})();for(letoof
whichislongerthanthespecified${this.chunkSize}`),o.length>0)){let l=this.joinDocs(o,r);for(l!==null&&n.push(l);i>this.chunkOverlap||i+u+o.length*r.length>this.chunkSize&&i>0;)i-=await this.lengthFunction(o[0]),o.shift()}o.push(s),i+=u}let a=this.joinDocs(o,r);return a!==null&&n.push(a),n}},Gue=class t extends tFe{static lc_name(){return"RecursiveCharacterTextSplitter"}constructor(e){super(e),Object.defineProperty(this,"separators",{enumerable:!0,configurable:!0,writable:!0,value:[`
${s.processed}`)}),{urlContext:n,imageUrls:o}}getMentions(){returnthis.mentions}clearMentions(){this.mentions.clear()}};Qg();er();Tn();varY$t=F(Iq()),Xue=classt{constructor(){this.cacheDir=".copilot/pdf-cache"}staticgetInstance(){returnt.instance||(t.instance=newt),t.instance}asyncensureCacheDir(){awaitapp.vault.adapter.exists(this.cacheDir)||(J("Creating PDF cache directory:",this.cacheDir),awaitapp.vault.adapter.mkdir(this.cacheDir))}getCacheKey(e){letr=`${e.path}:${e.stat.size}:${e.stat.mtime}`,n=(0,Y$t.MD5)(r).toString();returnJ("Generated cache key for PDF:",{path:e.path,key:n}),n}getCachePath(e){return`${this.cacheDir}/${e}.json`}asyncget(e){try{letr=this.getCacheKey(e),n=this.getCachePath(r);if(awaitapp.vault.adapter.exists(n)){J("Cache hit for PDF:",e.path);leto=awaitapp.vault.adapter.read(n);returnJSON.parse(o)}returnJ("Cache miss for PDF:",e.path),null}catch(r){returnfe("Error reading from PDF cache:",r),null}}asyncset(e,r){try{awaitthis.ensureCacheDir();letn=this.getCacheKey(e),o=this.getCachePath(n);J("Caching PDF response for:",e.path),awaitapp.vault.adapter.write(o,JSON.stringify(r))}catch(n){fe("Error writing to PDF cache:",n)}}asyncclear(){try{if(awaitapp.vault.adapter.exists(this.cacheDir)){lete=awaitapp.vault.adapter.list(this.cacheDir);J("Clearing PDF cache, removing files:",e.files.length);for(letrofe.files)awaitapp.vault.adapter.remove(r)}}catch(e){fe("Error clearing PDF cache:",e)}}};Tn();functionsL(t){if(!t||typeoft!="object")return!1;lete=t.message||t.toString();returne.includes("Request rate limit exceeded")||e.includes("RATE_LIMIT_EXCEEDED")||e.includes("429")||t.status===429}functionX$t(t){letr=(t?.message||t?.toString()||"").match(/Try again in ([\d\w\s]+)/);returnr?r[1]:"some time"}vartzt=require("obsidian");varQ$t=require("obsidian");varele,ezt,Que=class{constructor(e){this.vault=e;y6e(this,ele)}asyncload(e){letr=awaitthis.vault.read(e),{nodes:n=[],edges:o=[]}=JSON.parse(r),i=awaitPromise.all(n.map(asyncu=>{if(u.type==="file"&&u.file){letl=this.vault.getAbstractFileByPath(u.file),c=linstanceofQ$t.TFile?awaitthis.vault.cachedRead(l):"";return{...u,content:c}}returnu.type==="text"?{...u,content:u.text??""}:{...u,content:""}})),a=[...o];b6e(this,ele,ezt).call(this,i,a);lets=Object.fromEntries(i.map(u=>[u.id,u]));return{nodes:i,edges:a,byId:s}}buildPrompt(e){letr=newMap,n=e.nodes.filter(s=>s.type==="group");for(letsofn){letu=e.nodes.filter(l=>{if(l.id===s.id)return!1;letc=l.x+l.width/2,d=l.y+l.height/2;returnc>=s.x&&d>=s.y&&c<=s.x+s.width&&d<=s.y+s.height});r.set(s.label||s.id,u)}leto=`This canvas contains the following elements:
`,o}};ele=newWeakSet,ezt=function(e,r){letn=e.filter(o=>o.type==="group");for(letoofn)for(letiofe){if(i.id===o.id)continue;leta=i.x+i.width/2,s=i.y+i.height/2;a>=o.x&&s>=o.y&&a<=o.x+o.width&&s<=o.y+o.height&&r.push({id:crypto.randomUUID(),fromNode:o.id,toNode:i.id,label:"contains"})}};varcFe=class{constructor(){this.supportedExtensions=["md"]}asyncparseFile(e,r){returnawaitr.read(e)}},tle=class{constructor(e){this.supportedExtensions=["pdf"];this.brevilabsClient=e,this.pdfCache=Xue.getInstance()}asyncparseFile(e,r){try{J("Parsing PDF file:",e.path);letn=awaitthis.pdfCache.get(e);if(n)returnJ("Using cached PDF content for:",e.path),n.response;leto=awaitr.readBinary(e);J("Calling pdf4llm API for:",e.path);leti=awaitthis.brevilabsClient.pdf4llm(o);returnawaitthis.pdfCache.set(e,i),i.response}catch(n){returnfe(`Error extracting content from PDF ${e.path}:`,n),`[Error: Could not extract content from PDF ${e.basename}]`}}asyncclearCache(){J("Clearing PDF cache"),awaitthis.pdfCache.clear()}},dFe=class{constructor(){this.supportedExtensions=["canvas"]}asyncparseFile(e,r){try{J("Parsing Canvas file:",e.path);letn=newQue(r),o=awaitn.load(e);returnn.buildPrompt(o)}catch(n){returnfe(`Error parsing Canvas file ${e.path}:`,n),`[Error: Could not parse Canvas file ${e.basename}]`}}},jq=classjq{constructor(e,r=null){this.supportedExtensions=["pdf","602","abw","cgm","cwk","doc","docx","docm","dot","dotm","hwp","key","lwp","mw","mcw","pages","pbd","ppt","pptm","pptx","pot","potm","potx","rtf","sda","sdd","sdp","sdw","sgl","sti","sxi","sxw","stw","sxg","txt","uof","uop","uot","vor","wpd","wps","xml","zabw","epub","jpg","jpeg","png","gif","bmp","svg","tiff","webp","web","htm","html","xlsx","xls","xlsm","xlsb","xlw","csv","dif","sylk","slk","prn","numbers","et","ods","fods","uos1","uos2","dbf","wk1","wk2","wk3","wk4","wks","123","wq1","wq2","wb1","wb2","wb3","qpw","xlr","eth","tsv","mp3","mp4","mpeg","mpga","m4a","wav","webm"];this.brevilabsClient=e,this.projectContextCache=zb.getInstance(),this.currentProject=r}staticresetRateLimitNoticeTimer(){jq.lastRateLimitNoticeTime=0}asyncparseFile(e,r){try{if(J(`[Docs4LLMParser] Project ${this.currentProject?.name}: Parsing ${e.extension} file: ${e.path}`),!this.currentProject)throwfe("[Docs4LLMParser] No project context for parsing file: ",e.path),newError("No project context provided for file parsing");letn=awaitthis.projectContextCache.getFileContext(this.currentProject,e.path);if(n)returnJ(`[Docs4LLMParser] Project ${this.currentProject.name}: Using cached content for: ${e.path}`),n;J(`[Docs4LLMParser] Project ${this.currentProject.name}: Cache miss for: ${e.path}. Proceeding to API call.`);leto=awaitr.readBinary(e);J(`[Docs4LLMParser] Project ${this.currentProject.name}: Calling docs4llm API for: ${e.path}`);leti=awaitthis.brevilabsClient.docs4llm(o,e.extension);if(!i||!i.response)thrownewError("Empty response from docs4llm API");leta="";if(typeofi.response=="string")a=i.response;elseif(Array.isArray(i.response)){lets=[];for(letuofi.response)u.content&&(u.content.md?s.push(u.content.md):u.content.text&&s.push(u.content.text));a=s.join(`
`)}elsetypeofi.response=="object"?i.response.md?a=i.response.md:i.response.text?a=i.response.text:i.response.content?a=i.response.content:a=JSON.stringify(i.response,null,2):a=String(i.response);returnawaitthis.projectContextCache.setFileContext(this.currentProject,e.path,a),J(`[Docs4LLMParser] Project ${this.currentProject.name}: Successfully processed and cached: ${e.path}`),a}catch(n){throwfe(`[Docs4LLMParser] Project ${this.currentProject?.name}: Error processing file ${e.path}:`,n),sL(n)&&this.showRateLimitNotice(n),n}}showRateLimitNotice(e){letr=Date.now();if(r-jq.lastRateLimitNoticeTime<6e4)return;jq.lastRateLimitNoticeTime=r;letn=X$t(e);newtzt.Notice(`\u26A0\uFE0F Rate limit exceeded for document processing. Please try again in ${n}. Having fewer non-markdown files in the project will help.`,1e4)}asyncclearCache(){J("Cache clearing is now handled at the project level")}};jq.lastRateLimitNoticeTime=0;varY9=jq,vM=class{constructor(e,r,n=!1,o=null){this.parsers=newMap;this.isProjectMode=n,this.currentProject=o,this.registerParser(newcFe),this.registerParser(newY9(e,o)),n||this.registerParser(newtle(e)),this.registerParser(newdFe)}registerParser(e){for(letrofe.supportedExtensions)this.parsers.set(r,e)}asyncparseFile(e,r){letn=this.parsers.get(e.extension);if(!n)thrownewError(`No parser found for file type: ${e.extension}`);returnawaitn.parseFile(e,r)}supportsExtension(e){returnthis.parsers.has(e)}asyncclearPDFCache(){lete=this.parsers.get("pdf");einstanceoftle&&awaite.clearCache()}};on();varHG=require("obsidian");Gg();Us();td();Ur();Us();on();asyncfunctionrle(t,e){letr=`Given the following conversation and a follow up question,
`);returnawaitrb(async()=>{leti=awaitEc.instance.getCurrentChainManager().chatModelManager.getChatModel().bind({temperature:0}).invoke([{role:"user",content:r.replace("{chat_history}",n).replace("{question}",t)}]);returnwN(i.content)})}Ur();Gg();Tn();Gg();XD();Tn();OC();er();on();Kue();sA();QT();sf();j_();varnle=classextendsjn{constructor(e){super(e),Object.defineProperty(this,"callbacks",{enumerable:!0,configurable:!0,writable:!0,value:void0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void0}),Object.defineProperty(this,"verbose",{enumerable:!0,configurable:!0,writable:!0,value:void0}),this.callbacks=e?.callbacks,this.tags=e?.tags??[],this.metadata=e?.metadata??{},this.verbose=e?.verbose??!1}_getRelevantDocuments(e,r){thrownewError("Not implemented!")}asyncinvoke(e,r){returnthis.getRelevantDocuments(e,_n(r))}asyncgetRelevantDocuments(e,r){letn=_n(aN(r)),i=await(awaitru.configure(n.callbacks,this.callbacks,n.tags,this.tags,n.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),e,n.runId,void0,void0,void0,n.runName);try{leta=awaitthis._getRelevantDocuments(e,i);returnawaiti?.handleRetrieverEnd(a),a}catch(a){throwawaiti?.handleRetrieverError(a),a}}};H9();Hue();varEC=classextendsnle{constructor(r){super();this.options=r;this.lc_namespace=["hybrid_retriever"];this.queryRewritePrompt=Gp.fromTemplate(`Please write a passage to answer the question. If you don't know the answer, just make up a passage.
Passage:`)}asyncgetRelevantDocuments(r,n){returnrb(async()=>{leto=tb(r,app.vault),i=o.map(h=>h.basename),a=[...newSet([...this.options.salientTerms,...i])],s=awaitthis.getExplicitChunks(o),u=r;n?.runName!=="no_hyde"&&(u=awaitthis.rewriteQuery(r));letl=awaitthis.getOramaChunks(u,a,this.options.textWeight),c=this.filterAndFormatChunks(l,s),d=c;if(c.length===0)returnae().debug&&console.log("No chunks found for query:",r),d;letf=c.reduce((h,b)=>{letg=b.metadata.score;returntypeofg=="number"&&!isNaN(g)?Math.max(h,g):h},0),p=c.every(h=>typeofh.metadata.score!="number"||isNaN(h.metadata.score)),m=this.options.useRerankerThreshold&&(f<this.options.useRerankerThreshold||p);returnm&&(d=(awaitWi.getInstance().rerank(r,c.map(b=>b.pageContent.slice(0,3e3)))).response.data.map(b=>({...c[b.index],metadata:{...c[b.index].metadata,rerank_score:b.relevance_score}}))),ae().debug&&(console.log("*** HYBRID RETRIEVER DEBUG INFO: ***"),n?.runName!=="no_hyde"&&(console.log(`
Explicit Chunks: `,s),console.log("Orama Chunks: ",l),console.log("Combined Chunks: ",c),console.log("Max Orama Score: ",f),m?console.log("Reranked Chunks: ",d):console.log("No reranking applied.")),d})}asyncrewriteQuery(r){try{letn=awaitthis.queryRewritePrompt.format({question:r}),o=awaitrb(()=>Ec.instance.getCurrentChainManager().chatModelManager.getChatModel().bind({temperature:0}).invoke(n));returno&&"content"ino?wN(o.content):(console.warn("Unexpected rewrittenQuery format. Falling back to original query."),r)}catch(n){returnconsole.error("Error in rewriteQuery:",n),r}}asyncgetExplicitChunks(r){letn=[];for(letoofr){leti=awaitwa.getInstance().getDb(),a=awaitnE.getDocsByPath(i,o.path);if(a){lets=a.map(u=>newoE({pageContent:u.document.content,metadata:{...u.document.metadata,score:u.score,path:u.document.path,mtime:u.document.mtime,ctime:u.document.ctime,title:u.document.title,id:u.document.id,embeddingModel:u.document.embeddingModel,tags:u.document.tags,extension:u.document.extension,created_at:u.document.created_at,nchars:u.document.nchars}}));n.push(...s)}}returnn}asyncgetOramaChunks(r,n,o){leti;try{i=awaitthis.convertQueryToVector(r)}catch(l){throwconsole.error("Error in convertQueryToVector, please ensure your embedding model is working and has an adequate context length:",l,`
Query:`,r),l}leta=awaitwa.getInstance().getDb(),s={similarity:this.options.minSimilarityScore,limit:this.options.maxK,includeVectors:!0};if(n.length>0){letl;o||(o=.5),l=1-o;letc=!0;for(letdofn)if(!d.startsWith("#")){c=!1;break}c&&(ae().debug&&console.log("Tag only query detected, setting textWeight to 1 and vectorWeight to 0."),o=1,l=0),s.mode="hybrid",s.term=n.join(" "),s.vector={value:i,property:"embedding"},s.hybridWeights={text:o,vector:l}}elses.mode="vector",s.vector={value:i,property:"embedding"};if(this.options.timeRange){let{startTime:l,endTime:c}=this.options.timeRange,d=this.generateDailyNoteDateRange(l,c);J("==== Daily note date range: ====",d[0],d[d.length-1]);letf=tb(d.join(", "),app.vault),m=(awaitthis.getExplicitChunks(f)).map(x=>({...x,metadata:{...x.metadata,includeInContext:!0}}));J("==== Modified time range: ====",l,c),s.where={mtime:{between:[l,c]}};letb=(awaitxd(a,s)).hits.map(x=>newoE({pageContent:x.document.content,metadata:{...x.document.metadata,score:x.score,path:x.document.path,mtime:x.document.mtime,ctime:x.document.ctime,title:x.document.title,id:x.document.id,embeddingModel:x.document.embeddingModel,tags:x.document.tags,extension:x.document.extension,created_at:x.document.created_at,nchars:x.document.nchars}})),g=[...m,...b];returnArray.from(newSet(g.map(x=>x.metadata.id))).map(x=>g.find(S=>S.metadata.id===x)).filter(x=>x!==void0)}ae().debug&&console.log(`==== Orama Search Params: ====
`,s);letu=awaitxd(a,s);return!u||!u.hits?(console.warn("Search results or hits are undefined"),[]):u.hits.map(l=>!l||!l.document?(console.warn("Invalid hit or document in search results"),null):((typeofl.score!="number"||isNaN(l.score))&&console.warn("NaN/invalid score detected:",{score:l.score,path:l.document.path,title:l.document.title}),newoE({pageContent:l.document.content||"",metadata:{...l.document.metadata||{},score:l.score,path:l.document.path||"",mtime:l.document.mtime,ctime:l.document.ctime,title:l.document.title||"",id:l.document.id,embeddingModel:l.document.embeddingModel,tags:l.document.tags||[],extension:l.document.extension,created_at:l.document.created_at,nchars:l.document.nchars}}))).filter(l=>l!==null)}asyncconvertQueryToVector(r){leto=await(awaitmu.getInstance().getEmbeddingsAPI()).embedQuery(r);if(o.length===0)thrownewError("Query embedding returned an empty vector");returno}generateDailyNoteDateRange(r,n){leto=[],i=newDate(r),a=newDate(n),s=newDate(i);for(;s<=a;)o.push(`[[${s.toLocaleDateString("en-CA")}]]`),s.setDate(s.getDate()+1);returno}filterAndFormatChunks(r,n){leto=this.options.minSimilarityScore,i=r.filter(u=>{letl=u.metadata.score;returntypeofl!="number"||isNaN(l)?!0:l>=o}),a=newSet(n.map(u=>u.pageContent)),s=[...n];for(letuofi){letl=u.pageContent;a.has(l)||(a.add(l),s.push(u))}returns.map(u=>({...u,metadata:{...u.metadata,includeInContext:!0}}))}};er();varfFe=require("obsidian"),rzt=t=>{switch(t){case"@vault":return"Search through your vault for relevant information";case"@websearch":return"Search the web for information";case"@youtube":return"Get the transcript of a YouTube video. Example: @youtube <video_url>";case"@pomodoro":return"Start a pomodoro timer. Example: @pomodoro 25m";case"@composer":return"Edit existing notes or create new notes.";default:return""}},Dq=class{staticasynccallTool(e,r){try{if(!e)thrownewError("Tool is undefined");letn=awaite.call(r);returnn??(console.warn(`Tool ${e.name} returned null/undefined result`),null)}catch(n){returnconsole.error("Error calling tool:",n),ninstanceofError?newfFe.Notice(n.message):newfFe.Notice("An error occurred while executing the tool. Check console for details."),null}}};on();varhUt=require("obsidian");Us();eE();Qf();Qg();functionAnn(t){return"children"int&&"path"int}functionInn(t){return"path"int&&!("children"int)}functionMnn(t){lete=t.split(".");returne.length>1&&e.pop()?.toLowerCase()||""}functionpFe(t,e=!0){letr=[],n={},o={},{inclusions:i,exclusions:a}=Tf();for(letuoft.children)if(Inn(u)){if(gu(u,i,a)){e&&r.push(u.name);letl=Mnn(u.name)||"unknown";l&&(n[l]=(n[l]||0)+1)}}elseif(Ann(u)){letl=pFe(u,e);if(Object.keys(l).length>0&&(o[u.name]=l[u.name],l[u.name].extensionCounts))for(let[c,d]ofObject.entries(l[u.name].extensionCounts))n[c]=(n[c]||0)+d}lets={};returnObject.keys(n).length>0&&(s.extensionCounts=n),e&&r.length>0&&(s.files=r),Object.keys(o).length>0&&(s.subFolders=o),Object.keys(s).length===0?{}:t.name?{[t.name]:s}:{vault:s}}varnzt=t=>Ch(async()=>{lete=pFe(t,!0),r=`A JSON represents the file tree as a nested structure:
`,n=JSON.stringify(e);if(n.length>5e5){leto=pFe(t,!1);returnr+JSON.stringify(o)}returnr+n},{name:"getFileTree",description:"Get the file tree as a nested structure of folders and files",schema:rn.void()});Ur();BA();Gg();OC();er();eE();Qf();varmFe=Ch(async({timeRange:t,query:e,salientTerms:r})=>{if(awaitwa.getInstance().isIndexEmpty())thrownewHr(zY);leto=t!==void0,i=ae().maxSourceChunks<owe?owe:ae().maxSourceChunks;ae().debug&&console.log("returnAll:",o);letu=(awaitnewEC({minSimilarityScore:o?0:.1,maxK:o?1e3:i,salientTerms:r,timeRange:t?{startTime:t.startTime.epoch,endTime:t.endTime.epoch}:void0,textWeight:kGe,returnAll:o,useRerankerThreshold:.5}).getRelevantDocuments(e)).map(l=>({title:l.metadata.title,content:l.pageContent,path:l.metadata.path,score:l.metadata.score,rerank_score:l.metadata.rerank_score,includeInContext:l.metadata.includeInContext}));returnJSON.stringify(u)},{name:"localSearch",description:"Search for notes based on the time range and query",schema:rn.object({timeRange:rn.object({startTime:rn.any(),endTime:rn.any()}).optional(),query:rn.string().describe("The search query"),salientTerms:rn.array(rn.string()).describe("List of salient terms extracted from the query")})}),ozt=Ch(async()=>{try{lett=awaitwa.getInstance().indexVaultToVectorStore();return`Please report whether the indexing was successful.
If success is true, just say it is successful. If 0 files is indexed, say there are no new files to index.`+JSON.stringify({success:!0,message:t===0?"No new files to index.":`Indexed ${t} files in the vault.`})}catch(t){returnconsole.error("Error indexing vault:",t),JSON.stringify({success:!1,message:"An error occurred while indexing the vault."})}},{name:"indexVault",description:"Index the vault to the Copilot index"}),hFe=Ch(async({query:t,chatHistory:e})=>{try{letr=awaitrle(t,e),n=awaitWi.getInstance().webSearch(r),o=n.response.citations||[],i=o.length>0?`
`):"";return`Here are the web search results. Please provide a response based on this information and include source citations listed at the end of your response under the heading '#### Sources' as a list of markdown links. For each URL, create a descriptive title based on the domain and path and return it in the markdown format '- [title](url)':
`+n.response.choices[0].message.content+i}catch(r){returnconsole.error(`Error processing web search query ${t}:`,r),""}},{name:"webSearch",description:"Search the web for information",schema:rn.object({query:rn.string().describe("The search query"),chatHistory:rn.array(rn.object({role:rn.enum(["user","assistant"]),content:rn.string()})).describe("Previous conversation turns")})});eE();varuzt=F(izt(),1),X9=F(wM(),1);vargo;(function(t){t[t.AM=0]="AM",t[t.PM=1]="PM"})(go||(go={}));varyu;(function(t){t[t.SUNDAY=0]="SUNDAY",t[t.MONDAY=1]="MONDAY",t[t.TUESDAY=2]="TUESDAY",t[t.WEDNESDAY=3]="WEDNESDAY",t[t.THURSDAY=4]="THURSDAY",t[t.FRIDAY=5]="FRIDAY",t[t.SATURDAY=6]="SATURDAY"})(yu||(yu={}));varOh;(function(t){t[t.JANUARY=1]="JANUARY",t[t.FEBRUARY=2]="FEBRUARY",t[t.MARCH=3]="MARCH",t[t.APRIL=4]="APRIL",t[t.MAY=5]="MAY",t[t.JUNE=6]="JUNE",t[t.JULY=7]="JULY",t[t.AUGUST=8]="AUGUST",t[t.SEPTEMBER=9]="SEPTEMBER",t[t.OCTOBER=10]="OCTOBER",t[t.NOVEMBER=11]="NOVEMBER",t[t.DECEMBER=12]="DECEMBER"})(Oh||(Oh={}));functionazt(t,e){e=e.add(1,"day"),uL(t,e),Lq(t,e)}functionBb(t,e){t.assign("day",e.date()),t.assign("month",e.month()+1),t.assign("year",e.year())}functionole(t,e){t.assign("hour",e.hour()),t.assign("minute",e.minute()),t.assign("second",e.second()),t.assign("millisecond",e.millisecond()),t.get("hour")<12?t.assign("meridiem",go.AM):t.assign("meridiem",go.PM)}functionuL(t,e){t.imply("day",e.date()),t.imply("month",e.month()+1),t.imply("year",e.year())}functionLq(t,e){t.imply("hour",e.hour()),t.imply("minute",e.minute()),t.imply("second",e.second()),t.imply("millisecond",e.millisecond())}varvFe=F(wM(),1);varRnn={ACDT:630,ACST:570,ADT:-180,AEDT:660,AEST:600,AFT:270,AKDT:-480,AKST:-540,ALMT:360,AMST:-180,AMT:-240,ANAST:720,ANAT:720,AQTT:300,ART:-180,AST:-240,AWDT:540,AWST:480,AZOST:0,AZOT:-60,AZST:300,AZT:240,BNT:480,BOT:-240,BRST:-120,BRT:-180,BST:60,BTT:360,CAST:480,CAT:120,CCT:390,CDT:-300,CEST:120,CET:{timezoneOffsetDuringDst:2*60,timezoneOffsetNonDst:60,dstStart:t=>szt(t,Oh.MARCH,yu.SUNDAY,2),dstEnd:t=>szt(t,Oh.OCTOBER,yu.SUNDAY,3)},CHADT:825,CHAST:765,CKT:-600,CLST:-180,CLT:-240,COT:-300,CST:-360,CT:{timezoneOffsetDuringDst:-5*60,timezoneOffsetNonDst:-6*60,dstStart:t=>xM(t,Oh.MARCH,yu.SUNDAY,2,2),dstEnd:t=>xM(t,Oh.NOVEMBER,yu.SUNDAY,1,2)},CVT:-60,CXT:420,ChST:600,DAVT:420,EASST:-300,EAST:-360,EAT:180,ECT:-300,EDT:-240,EEST:180,EET:120,EGST:0,EGT:-60,EST:-300,ET:{timezoneOffsetDuringDst:-4*60,timezoneOffsetNonDst:-5*60,dstStart:t=>xM(t,Oh.MARCH,yu.SUNDAY,2,2),dstEnd:t=>xM(t,Oh.NOVEMBER,yu.SUNDAY,1,2)},FJST:780,FJT:720,FKST:-180,FKT:-240,FNT:-120,GALT:-360,GAMT:-540,GET:240,GFT:-180,GILT:720,GMT:0,GST:240,GYT:-240,HAA:-180,HAC:-300,HADT:-540,HAE:-240,HAP:-420,HAR:-360,HAST:-600,HAT:-90,HAY:-480,HKT:480,HLV:-210,HNA:-240,HNC:-360,HNE:-300,HNP:-480,HNR:-420,HNT:-150,HNY:-540,HOVT:420,ICT:420,IDT:180,IOT:360,IRDT:270,IRKST:540,IRKT:540,IRST:210,IST:330,JST:540,KGT:360,KRAST:480,KRAT:480,KST:540,KUYT:240,LHDT:660,LHST:630,LINT:840,MAGST:720,MAGT:720,MART:-510,MAWT:300,MDT:-360,MESZ:120,MEZ:60,MHT:720,MMT:390,MSD:240,MSK:180,MST:-420,MT:{timezoneOffsetDuringDst:-6*60,timezoneOffsetNonDst:-7*60,dstStart:t=>xM(t,Oh.MARCH,yu.SUNDAY,2,2),dstEnd:t=>xM(t,Oh.NOVEMBER,yu.SUNDAY,1,2)},MUT:240,MVT:300,MYT:480,NCT:660,NDT:-90,NFT:690,NOVST:420,NOVT:360,NPT:345,NST:-150,NUT:-660,NZDT:780,NZST:720,OMSST:420,OMST:420,PDT:-420,PET:-300,PETST:720,PETT:720,PGT:600,PHOT:780,PHT:480,PKT:300,PMDT:-120,PMST:-180,PONT:660,PST:-480,PT:{timezoneOffsetDuringDst:-7*60,timezoneOffsetNonDst:-8*60,dstStart:t=>xM(t,Oh.MARCH,yu.SUNDAY,2,2),dstEnd:t=>xM(t,Oh.NOVEMBER,yu.SUNDAY,1,2)},PWT:540,PYST:-180,PYT:-240,RET:240,SAMT:240,SAST:120,SBT:660,SCT:240,SGT:480,SRT:-180,SST:-660,TAHT:-600,TFT:300,TJT:300,TKT:780,TLT:540,TMT:300,TVT:720,ULAT:480,UTC:0,UYST:-120,UYT:-180,UZT:300,VET:-210,VLAST:660,VLAT:660,VUT:660,WAST:120,WAT:60,WEST:60,WESZ:60,WET:0,WEZ:0,WFT:720,WGST:-120,WGT:-180,WIB:420,WIT:540,WITA:480,WST:780,WT:0,YAKST:600,YAKT:600,YAPT:600,YEKST:360,YEKT:360};functionxM(t,e,r,n,o=0){leti=0,a=0;for(;a<n;)i++,newDate(t,e-1,i).getDay()===r&&a++;retu
`,this.chainManager.memoryManager.getMemory().chatHistory.messages.map(s=>s.content)),J(`==== Final AI Response ====
`,e),e}asynchandleError(e,r,n){leto=ci(e);fe("Error during LLM invocation:",o);leti=e?.response?.data?.error||o,a=i?.code||o,s="";if(e?.message?.includes("Invalid license key")?s="Invalid Copilot Plus license key. Please check your license key in settings.":a==="model_not_found"?s="You do not have access to this model or the model does not exist, please check with your API provider.":s=`${a}`,fe(i),r&&n){n("");letu=s.search("Troubleshooting URL");s=u!==-1?s.slice(0,u):s,o.search(/401|invalid|not valid/gi)!==-1&&(s=`Something went wrong. Please check if you have set your API key.
Error Details: `+s),r({message:s,isErrorMessage:!0,sender:mg,isVisible:!0,timestamp:Bs(newDate)})}elsenewhUt.Notice(s),fe(i)}},Rle=classextendssK{asyncrun(e,r,n,o,i){leta=newaK(n);try{letl=awaitthis.chainManager.memoryManager.getMemory().loadMemoryVariables({}),c=vN(l),d=[],f=q_(),p=this.chainManager.chatModelManager.getChatModel();f&&d.push({role:$Y(p),content:f});for(lethofc)d.push({role:h.role,content:h.content});d.push({role:"user",content:e.message}),J(`==== Final Request to AI ====
`,d);letm=awaitrb(()=>this.chainManager.chatModelManager.getChatModel().stream(d,{signal:r.signal}));forawait(lethofm){if(r.signal.aborted){J("Stream iteration aborted",{reason:r.signal.reason});break}a.processChunk(h)}}catch(u){u.name==="AbortError"||r.signal.aborted?J("Stream aborted by user",{reason:r.signal.reason}):awaitthis.handleError(u,o,n)}lets=a.close();returnr.signal.aborted&&r.signal.reason==="new-chat"?(n(""),""):this.handleResponse(s,e,r,o,n)}},Nle=classextendssK{asyncrun(e,r,n,o,i){leta=newaK(n);try{if(awaitthis.chainManager.vectorStoreManager.isIndexEmpty())returnthis.handleResponse(zY,e,r,o,n);letc=awaitthis.chainManager.memoryManager.getMemory().loadMemoryVariables({}),d=vN(c),f=e.message;d.length>0&&(f=e.message);letm=awaitnewEC({minSimilarityScore:.01,maxK:ae().maxSourceChunks,salientTerms:[]}).getRelevantDocuments(f);this.chainManager.storeRetrieverDocuments(m);leth=m.map(E=>E.pageContent).join(`
`+h,x=g+y,S=this.chainManager.chatModelManager.getChatModel();x&&b.push({role:$Y(S),content:x});for(letEofd)b.push({role:E.role,content:E.content});b.push({role:"user",content:e.message}),J(`==== Final Request to AI ====
`,b);letO=awaitrb(()=>this.chainManager.chatModelManager.getChatModel().stream(b,{signal:r.signal}));forawait(letEofO){if(r.signal.aborted){J("VaultQA stream iteration aborted",{reason:r.signal.reason});break}a.processChunk(E)}}catch(u){u.name==="AbortError"||r.signal.aborted?J("VaultQA stream aborted by user",{reason:r.signal.reason}):awaitthis.handleError(u,o,n)}lets=a.close();returnr.signal.aborted&&r.signal.reason==="new-chat"?(n(""),""):(s=this.addSourcestoResponse(s),this.handleResponse(s,e,r,o,n))}addSourcestoResponse(e){letr=AGe(this.chainManager.getRetrievedDocuments());if(r.length>0){letn=r.map(o=>`- [[${o}]]`).join(`
The following is the relevant conversation history. Use this context to maintain consistency in your responses:`);letc=this.chainManager.chatModelManager.getChatModel();l&&u.push({role:$Y(c),content:`${l}
IMPORTANT: Maintain consistency with previous responses in the conversation. If you've provided information about a person or topic before, use that same information in follow-up questions.`});for(letgofs)u.push({role:g.role,content:g.content});letd=this.chainManager.chatModelManager.getChatModel(),p=this.isMultimodalModel(d)?awaitthis.buildMessageContent(e,r):e;u.push({role:"user",content:p});letm=pinstanceofArray?p[0].text:p;J("Enhanced user message: ",m),J(`==== Final Request to AI ====
`,u);leth=newaK(o),b=awaitrb(()=>this.chainManager.chatModelManager.getChatModel().stream(u,{signal:n.signal}));forawait(letgofb){if(n.signal.aborted){J("CopilotPlus multimodal stream iteration aborted",{reason:n.signal.reason});break}h.processChunk(g)}returnh.close()}asyncrun(e,r,n,o,i){let{updateLoadingMessage:a}=i,s="",u=[],l="",c=d=>{l=d,n(d)};try{if(this.isYoutubeOnlyMessage(e.message)){letx=Qve(e.message),S="Transcript not available. Only videos with the auto transcript option turned on are supported at the moment.";if(x)try{letO=awaitWi.getInstance().youtube4llm(x);returnO.response.transcript?this.handleResponse(O.response.transcript,e,r,o,n):this.handleResponse(S,e,r,o,n)}catch(O){returnfe("Error processing YouTube video:",O),this.handleResponse(S,e,r,o,n)}}J("==== Step 1: Analyzing intent ====");letd,f=e.originalMessage||e.message;try{d=awaithL.analyzeIntent(f)}catch(x){returnthis.handleResponse(CGe(x),e,r,o,n)}letp=e.message.split(" ").filter(x=>!iK.includes(x.toLowerCase())).join(" ").trim(),m=awaitthis.executeToolCalls(d,a),h=m.find(x=>x.tool==="localSearch"&&x.output&&x.output.length>0),g=awaitthis.chainManager.memoryManager.getMemory().loadMemoryVariables({}),y=vN(g);if(h){J("==== Step 2: Processing local search results ====");letx=JSON.parse(h.output);J("==== Step 3: Condensing Question ====");letS=awaitrle(p,y);J("Condensed standalone question: ",S),J("==== Step 4: Preparing context ====");letO=this.getTimeExpression(d),E=this.prepareLocalSearchResult(x,O),P=m.filter(R=>R.tool==="getCurrentTime"),A=this.prepareEnhancedUserMessage(S,P);J(E),J("==== Step 5: Invoking QA Chain ====");letI=awaitthis.chainManager.promptManager.getQAPrompt({question:A,context:E,systemMessage:""});s=awaitthis.streamMultimodalResponse(I,e,r,c),u=this.getSources(x)}else{letx=this.prepareEnhancedUserMessage(p,m);J("No local search results. Using standard LLM Chain."),s=awaitthis.streamMultimodalResponse(x,e,r,c)}}catch(d){a?.(K_.DEFAULT),d.name==="AbortError"||r.signal.aborted?J("CopilotPlus stream aborted by user",{reason:r.signal.reason}):awaitthis.handleError(d,o,n)}returnr.signal.aborted&&r.signal.reason==="new-chat"?(n(""),""):(r.signal.aborted&&l&&(s=l),this.handleResponse(s,e,r,o,n,u))}getSources(e){return!e||!Array.isArray(e)?(dg("No valid documents provided to getSources"),[]):this.sortUniqueDocsByScore(e)}sortUniqueDocsByScore(e){letr=newMap;for(letnofe){if(!n.title||!n?.score&&!n?.rerank_score){dg("Invalid document structure:",n);continue}leto=r.get(n.title),i=n&&"rerank_score"inn,a=i?n.rerank_score:n.score;(!o||a>(o.score??0))&&r.set(n.title,{title:n.title,score:a,isReranked:i})}returnArray.from(r.values()).sort((n,o)=>(o.score??0)-(n.score??0))}asyncexecuteToolCalls(e,r){letn=[];for(letoofe){J(`==== Step 2: Calling tool: ${o.tool.name} ====`),o.tool.name==="localSearch"?r?.(K_.READING_FILES):o.tool.name==="webSearch"?r?.(K_.SEARCHING_WEB):o.tool.name==="getFileTree"&&r?.(K_.READING_FILE_TREE);leti=awaitDq.callTool(o.tool,o.args);n.push({tool:o.tool.name,output:i})}returnn}prepareEnhancedUserMessage(e,r){letn="";if(r.length>0){leto=r.filter(i=>i.output!=null);o.length>0&&(n=`
`))}return`${e}${n}`}getTimeExpression(e){letr=e.find(n=>n.tool.name==="getTimeRangeMs");returnr?r.args.timeExpression:""}prepareLocalSearchResult(e,r){letn=e.filter(s=>s.includeInContext),o=n.reduce((s,u)=>s+u.content.length,0),i=n;if(o>iwe){lets=iwe/o;J("Truncating documents to fit context length. Truncation ratio:",s),i=n.map(u=>({...u,content:u.content.slice(0,Math.floor(u.content.length*s))}))}leta=i.map(s=>`Note in Vault: ${s.content}`).join(`
</project_context>`),e}};Tn();er();on();sA();varhme=require("obsidian");Us();Ur();CN();Tn();er();on();a9();vargL="0.39.0";vargUt=!1,yL,bke,Pan,Ean,Tan,yUt,Aan,Dle,_ke,bUt,vke,Lle,_Ut;functionvUt(t,e={auto:!1}){if(gUt)thrownewError(`you must \`import '@anthropic-ai/sdk/shims/${t.kind}'\` before importing anything else from @anthropic-ai/sdk`);if(yL)thrownewError(`can't \`import '@anthropic-ai/sdk/shims/${t.kind}'\` after \`import '@anthropic-ai/sdk/shims/${yL}'\``);gUt=e.auto,yL=t.kind,bke=t.fetch,Pan=t.Request,Ean=t.Response,Tan=t.Headers,yUt=t.FormData,Aan=t.Blob,Dle=t.File,_ke=t.ReadableStream,bUt=t.getMultipartRequestOptions,vke=t.getDefaultAgent,Lle=t.fileFromPath,_Ut=t.isFsReadStream}varFle=class{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}};functionwUt({manuallyImported:t}={}){lete=t?"You may need to use polyfills":"Add one of these imports before your first `import \u2026 from '@anthropic-ai/sdk'`:\n- `import '@anthropic-ai/sdk/shims/node'` (if you're running on Node)\n- `import '@anthropic-ai/sdk/shims/web'` (otherwise)\n",r,n,o,i;try{r=fetch,n=Request,o=Response,i=Headers}catch(a){thrownewError(`this environment is missing the following Web Fetch API type: ${a.message}. ${e}`)}return{kind:"web",fetch:r,Request:n,Response:o,Headers:i,FormData:typeofFormData<"u"?FormData:class{constructor(){thrownewError(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${e}`)}},Blob:typeofBlob<"u"?Blob:class{constructor(){thrownewError(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${e}`)}},File:typeofFile<"u"?File:class{constructor(){thrownewError(`file uploads aren't supported in this environment yet as 'File' is undefined. ${e}`)}},ReadableStream:typeofReadableStream<"u"?ReadableStream:class{constructor(){thrownewError(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${e}`)}},getMultipartRequestOptions:async(a,s)=>({...s,body:newFle(a)}),getDefaultAgent:a=>{},fileFromPath:()=>{thrownewError("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/anthropics/anthropic-sdk-typescript#file-uploads")},isFsReadStream:a=>!1}}yL||vUt(wUt(),{auto:!0});varDr=classextendsError{},Mc=classtextendsDr{constructor(e,r,n,o){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=o,this.request_id=o?.["request-id"],this.error=r}staticmakeMessage(e,r,n){leto=r?.message?typeofr.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;returne&&o?`${e}${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}staticgenerate(e,r,n,o){if(!e||!o)returnnewFM({message:n,cause:kle(r)});leti=r;returne===400?newlK(e,i,n,o):e===401?newcK(e,i,n,o):e===403?newdK(e,i,n,o):e===404?newfK(e,i,n,o):e===409?newpK(e,i,n,o):e===422?newmK(e,i,n,o):e===429?newhK(e,i,n,o):e>=500?newgK(e,i,n,o):newt(e,i,n,o)}},Cd=classextendsMc{constructor({message:e}={}){super(void0,void0,e||"Request was aborted.",void0)}},FM=classextendsMc{constructor({message:e,cause:r}){super(void0,void0,e||"Connection error.",void0),r&&(this.cause=r)}},i2=classextendsFM{constructor({message:e}={}){super({message:e??"Request timed out."})}},lK=classextendsMc{},cK=classextendsMc{},dK=classextendsMc{},fK=classextendsMc{},pK=classextendsMc{},mK=classextendsMc{},hK=classextendsMc{},gK=classextendsMc{};var$le=function(t,e,r,n,o){if(n==="m")thrownewTypeError("Private method is not writable");if(n==="a"&&!o)thrownewTypeError("Private accessor was defined without a setter");if(typeofe=="function"?t!==e||!o:!e.has(t))thrownewTypeError("Cannot write private member to an object whose class did not declare it");returnn==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r},bL=function(t,e,r,n){if(r==="a"&&!n)thrownewTypeError("Private accessor was defined without a getter");if(typeofe=="function"?t!==e||!n:!e.has(t))thrownewTypeError("Cannot read private member from an object whose class did not declare it");retur
`,"\r"]);dE.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Ran(t,e){for(let o=e??0;o<t.length;o++){if(t[o]===10)return{preceding:o,index:o+1,carriage:!1};if(t[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function xUt(t){for(let n=0;n<t.length-1;n++){if(t[n]===10&&t[n+1]===10||t[n]===13&&t[n+1]===13)return n+2;if(t[n]===13&&t[n+1]===10&&n+3<t.length&&t[n+2]===13&&t[n+3]===10)return n+4}return-1}function yK(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let r=await e.read();return r?.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}},async return(){let r=e.cancel();return e.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var TC=class t{constructor(e,r){this.iterator=e,this.controller=r}static fromSSEResponse(e,r){let n=!1;async function*o(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let i=!1;try{for await(let a of Nan(e,r)){if(a.event==="completion")try{yield JSON.parse(a.data)}catch(s){throw console.error("Could not parse message into JSON:",a.data),console.error("From chunk:",a.raw),s}if(a.event==="message_start"||a.event==="message_delta"||a.event==="message_stop"||a.event==="content_block_start"||a.event==="content_block_delta"||a.event==="content_block_stop")try{yield JSON.parse(a.data)}catch(s){throw console.error("Could not parse message into JSON:",a.data),console.error("From chunk:",a.raw),s}if(a.event!=="ping"&&a.event==="error")throw Mc.generate(void 0,`SSEError:${a.data}`,a.data,xke(e.headers))}i=!0}catch(a){if(a instanceof Error&&a.name==="AbortError")return;throw a}finally{i||r.abort()}}return new t(o,r)}static fromReadableStream(e,r){let n=!1;async function*o(){let a=new dE,s=yK(e);for await(let u of s)for(let l of a.decode(u))yield l;for(let u of a.flush())yield u}async function*i(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let a=!1;try{for await(let s of o())a||s&&(yield JSON.parse(s));a=!0}catch(s){if(s instanceof Error&&s.name==="AbortError")return;throw s}finally{a||r.abort()}}return new t(i,r)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),o=i=>({next:()=>{if(i.length===0){let a=n.next();e.push(a),r.push(a)}return i.shift()}});return[new t(()=>o(e),this.controller),new t(()=>o(r),this.controller)]}toReadableStream(){let e=this,r,n=new TextEncoder;return new _ke({async start(){r=e[Symbol.asyncIterator]()},async pull(o){try{let{value:i,done:a}=await r.next();if(a)return o.close();let s=n.encode(JSON.stringify(i)+`
`);o.enqueue(s)}catch(i){o.error(i)}},async cancel(){await r.return?.()}})}};async function*Nan(t,e){if(!t.body)throw e.abort(),new Dr("Attempted to iterate over a response with no body");let r=new wke,n=new dE,o=yK(t.body);for await(let i of jan(o))for(let a of n.decode(i)){let s=r.decode(a);s&&(yield s)}for(let i of n.flush()){let a=r.decode(i);a&&(yield a)}}async function*jan(t){let e=new Uint8Array;for await(let r of t){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?new TextEncoder().encode(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let i;for(;(i=xUt(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}var wke=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,o]=Dan(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}};function Dan(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var Lan=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",Fan=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&bK(t),bK=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";async function SUt(t,e,r){if(t=await t,Fan(t))return t;if(Lan(t)){let o=await t.blob();e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=bK(o)?[await o.arrayBuffer()]:[o];return new Dle(i,e,r)}let n=await kan(t);if(e||(e=zan(t)??"unknown_file"),!r?.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new Dle(n,e,r)}async function kan(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(bK(t))e.push(await t.arrayBuffer());else if(Ban(t))for await(let r of t)e.push(r);else throw new Error(`Unexpecteddatatype:${typeoft};constructor:${t?.constructor?.name};props:${$an(t)}`);return e}function $an(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function zan(t){return Ske(t.name)||Ske(t.filename)||Ske(t.path)?.split(/[\\/]/).pop()}var Ske=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},Ban=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",Cke=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody";var qan=function(t,e,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r},Han=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},zle;async function TUt(t){let{response:e}=t;if(t.options.stream)return a2("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):TC.fromSSEResponse(e,t.controller);if(e.status===204)return null;if(t.options.__binaryResponse)return e;let r=e.headers.get("content-type");if(r?.includes("application/json")||r?.includes("application/vnd.api+json")){let i=await e.json();return a2("response",e.status,e.url,e.headers,i),AUt(i,e)}let o=await e.text();return a2("response",e.status,e.url,e.headers,o),o}function AUt(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var Ule=class t extends Promise{constructor(e,r=TUt){super(n=>{n(null)}),this.responsePromise=e,this.parseResponse=r}_thenUnwrap(e){return new t(this.responsePromise,async r=>AUt(e(await this.parseResponse(r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r,request_id:r.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(e,r){return this.parse().then(e,r)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}},qle=class{constructor({baseURL:e,maxRetries:r=2,timeout:n=6e5,httpAgent:o,fetch:i}){this.baseURL=e,this.maxRetries=Oke("maxRetries",r),this.timeout=Oke("timeout",n),this.httpAgent=o,this.f
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages?beta=true",{body:o,timeout:this._client._options.timeout??(o.stream?6e5:this._client._calculateNonstreamingTimeout(o.max_tokens)),...r,headers:{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void0,...r?.headers},stream:e.stream??!1})}stream(e,r){returnQle.createMessage(this,e,r)}countTokens(e,r){let{betas:n,...o}=e;returnthis._client.post("/v1/messages/count_tokens?beta=true",{body:o,...r,headers:{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString(),...r?.headers}})}};$M.Batches=vL;$M.BetaMessageBatchesPage=l2;varIC=classextendsRc{constructor(){super(...arguments),this.models=new_L(this._client),this.messages=new$M(this._client)}};IC.Models=_L;IC.BetaModelInfosPage=s2;IC.Messages=$M;varwL=classextendsRc{create(e,r){returnthis._client.post("/v1/complete",{body:e,timeout:this._client._options.timeout??6e5,...r,stream:e.stream??!1})}};varxL=classextendsRc{create(e,r){returnthis._client.post("/v1/messages/batches",{body:e,...r})}retrieve(e,r){returnthis._client.get(`/v1/messages/batches/${e}`,r)}list(e={},r){returnay(e)?this.list({},e):this._client.getAPIList("/v1/messages/batches",f2,{query:e,...r})}delete(e,r){returnthis._client.delete(`/v1/messages/batches/${e}`,r)}cancel(e,r){returnthis._client.post(`/v1/messages/batches/${e}/cancel`,r)}asyncresults(e,r){letn=awaitthis.retrieve(e);if(!n.results_url)thrownewDr(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);returnthis._client.get(n.results_url,{...r,headers:{Accept:"application/binary",...r?.headers},__binaryResponse:!0})._thenUnwrap((o,i)=>u2.fromResponse(i.response,i.controller))}},f2=classextendsAC{};xL.MessageBatchesPage=f2;varMf=function(t,e,r,n,o){if(n==="m")thrownewTypeError("Private method is not writable");if(n==="a"&&!o)thrownewTypeError("Private accessor was defined without a setter");if(typeofe=="function"?t!==e||!o:!e.has(t))thrownewTypeError("Cannot write private member to an object whose class did not declare it");returnn==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r},Mn=function(t,e,r,n){if(r==="a"&&!n)thrownewTypeError("Private accessor was defined without a getter");if(typeofe=="function"?t!==e||!n:!e.has(t))thrownewTypeError("Cannot read private member from an object whose class did not declare it");returnr==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},uy,zM,OK,ece,PK,EK,tce,TK,pE,AK,rce,nce,p2,oce,ice,Rke,LUt,Nke,jke,Dke,Lke,FUt,kUt="__json_buf",ace=classt{constructor(){uy.add(this),this.messages=[],this.receivedMessages=[],zM.set(this,void0),this.controller=newAbortController,OK.set(this,void0),ece.set(this,()=>{}),PK.set(this,()=>{}),EK.set(this,void0),tce.set(this,()=>{}),TK.set(this,()=>{}),pE.set(this,{}),AK.set(this,!1),rce.set(this,!1),nce.set(this,!1),p2.set(this,!1),oce.set(this,void0),ice.set(this,void0),Nke.set(this,e=>{if(Mf(this,rce,!0,"f"),einstanceofError&&e.name==="AbortError"&&(e=newCd),einstanceofCd)returnMf(this,nce,!0,"f"),this._emit("abort",e);if(einstanceofDr)returnthis._emit("error",e);if(einstanceofError){letr=newDr(e.message);returnr.cause=e,this._emit("error",r)}returnthis._emit("error",newDr(String(e)))}),Mf(this,OK,newPromise((e,r)=>{Mf(this,ece,e,"f"),Mf(this,PK,r,"f")}),"f"),Mf(this,EK,newPromise((e,r)=>{Mf(this,tce,e,"f"),Mf(this,TK,r,"f")}),"f"),Mn(this,OK,"f").catch(()=>{}),Mn(this,EK,"f").catch(()=>{})}getresponse(){returnMn(this,oce,"f")}getrequest_id(){returnMn(this,ice,"f")}asyncwithResponse(){lete=awaitMn(this,OK,"f");if(!e)thrownewError("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}staticfromReadableStream(e){letr=newt;returnr._run(()=>r._fromReadableStream(e)),r}staticcreateMessage(e,r,n){leto=newt;for(letiofr.messages)o._addMessageParam(i);returno._run(()=>o._createMessage(e,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages",{body:e,timeout:this._client._options.timeout??(e.stream?6e5:this._client._calculateNonstreamingTimeout(e.max_tokens)),...r,stream:e.stream??!1})}stream(e,r){return ace.createMessage(this,e,r)}countTokens(e,r){return this._client.post("/v1/messages/count_tokens",{body:e,...r})}},$Ut={"claude-1.3":"November6th,2024","claude-1.3-100k":"November6th,2024","claude-instant-1.1":"November6th,2024","claude-instant-1.1-100k":"November6th,2024","claude-instant-1.2":"November6th,2024","claude-3-sonnet-20240229":"July21st,2025","claude-2.1":"July21st,2025","claude-2.0":"July21st,2025"};mE.Batches=xL;mE.MessageBatchesPage=f2;var BM=class extends Rc{retrieve(e,r){return this._client.get(`/v1/models/${e}`,r)}list(e={},r){return ay(e)?this.list({},e):this._client.getAPIList("/v1/models",SL,{query:e,...r})}},SL=class extends AC{};BM.ModelInfosPage=SL;var zUt,Si=class extends qle{constructor({baseURL:e=Vle("ANTHROPIC_BASE_URL"),apiKey:r=Vle("ANTHROPIC_API_KEY")??null,authToken:n=Vle("ANTHROPIC_AUTH_TOKEN")??null,...o}={}){let i={apiKey:r,authToken:n,...o,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&MUt())throw new Dr(`It looks like you're running in a browser-like environment.
`);super({baseURL:i.baseURL,timeout:i.timeout??6e5,httpAgent:i.httpAgent,maxRetries:i.maxRetries,fetch:i.fetch}),this.completions=newwL(this),this.messages=newmE(this),this.models=newBM(this),this.beta=newIC(this),this._options=i,this.apiKey=r,this.authToken=n}defaultQuery(){returnthis._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void0,"anthropic-version":"2023-06-01",...this._options.defaultHeaders}}validateHeaders(e,r){if(!(this.apiKey&&e["x-api-key"])&&r["x-api-key"]!==null&&!(this.authToken&&e.authorization)&&r.authorization!==null)thrownewError('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}authHeaders(e){letr=this.apiKeyAuth(e),n=this.bearerAuth(e);returnr!=null&&!_K(r)?r:n!=null&&!_K(n)?n:{}}apiKeyAuth(e){returnthis.apiKey==null?{}:{"X-Api-Key":this.apiKey}}bearerAuth(e){returnthis.authToken==null?{}:{Authorization:`Bearer ${this.authToken}`}}};zUt=Si;Si.Anthropic=zUt;Si.HUMAN_PROMPT=`
Assistant:`;Si.DEFAULT_TIMEOUT=6e5;Si.AnthropicError=Dr;Si.APIError=Mc;Si.APIConnectionError=FM;Si.APIConnectionTimeoutError=i2;Si.APIUserAbortError=Cd;Si.NotFoundError=fK;Si.ConflictError=pK;Si.RateLimitError=hK;Si.BadRequestError=lK;Si.AuthenticationError=cK;Si.InternalServerError=gK;Si.PermissionDeniedError=dK;Si.UnprocessableEntityError=mK;Si.toFile=SUt;Si.fileFromPath=Lle;Si.Completions=wL;Si.Messages=mE;Si.Models=BM;Si.ModelInfosPage=SL;Si.Beta=IC;var{HUMAN_PROMPT:oai,AI_PROMPT:iai}=Si;As();Of();Kn();iC();bh();ug();Jp();CD();_h();eb();varIK=classextendscN{staticlc_name(){return"AnthropicToolsOutputParser"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","anthropic","output_parsers"]}),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"keyName",{enumerable:!0,configurable:!0,writable:!0,value:void0}),Object.defineProperty(this,"returnSingle",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"zodSchema",{enumerable:!0,configurable:!0,writable:!0,value:void0}),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async_validateResult(e){letr=e;if(typeofe=="string")try{r=JSON.parse(e)}catch(o){thrownewKm(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(o.message)}`,e)}elser=e;if(this.zodSchema===void0)returnr;letn=awaitthis.zodSchema.safeParseAsync(r);if(n.success)returnn.data;thrownewKm(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.error.errors)}`,JSON.stringify(r,null,2))}asyncparseResult(e){letr=e.flatMap(i=>{let{message:a}=i;returnArray.isArray(a.content)?Fke(a.content)[0]:[]});if(r[0]===void0)thrownewError("No parseable tool calls provided to AnthropicToolsOutputParser.");let[n]=r;returnawaitthis._validateResult(n.args)}};functionFke(t){lete=[];for(letroft)r.type==="tool_use"&&e.push({name:r.name,args:r.input,id:r.id,type:"tool_call"});returne}functionBUt(t){if(t)returnt==="any"?{type:"any"}:t==="auto"?{type:"auto"}:typeoft=="string"?{type:"tool",name:t}:t}As();functionUUt(t){returnt==null||typeoft!="object"||!("type"int)||t.type!=="image"||!("source"int)||typeoft.source!="object"||t.source==null||!("type"int.source)?!1:t.source.type==="base64"?!(!("media_type"int.source)||typeoft.source.media_type!="string"||!("data"int.source)||typeoft.source.data!="string"):t.source.type==="url"?!(!("url"int.source)||typeoft.source.url!="string"):!1}functionqUt(t){lete=Xk({dataUrl:t});if(e)return{type:"base64",media_type:e.mime_type,data:e.data};letr;try{r=newURL(t)}catch{thrownewError([`Malformed image URL: ${JSON.stringify(t)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
`))}if(r.protocol==="http:"||r.protocol==="https:")return{type:"url",url:t};thrownewError([`Invalid image URL protocol: ${JSON.stringify(r.protocol)}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
`))}functioncsn(t){lete=[];for(letroft)if(r._getType()==="tool")if(typeofr.content=="string"){letn=e[e.length-1];n?._getType()==="human"&&Array.isArray(n.content)&&"type"inn.content[0]&&n.content[0].type==="tool_result"?n.content.push({type:"tool_result",content:r.content,tool_use_id:r.tool_call_id}):e.push(new$s({content:[{type:"tool_result",content:r.content,tool_use_id:r.tool_call_id}]}))}elsee.push(new$s({content:[{type:"tool_result",content:kke(r.content),tool_use_id:r.tool_call_id}]}));elsee.push(r);returne}functionHUt(t){if(t.id===void0)thrownewError('Anthropic requires all tool calls to have an "id".');return{type:"tool_use",id:t.id,name:t.name,input:t.args}}vardsn={providerName:"anthropic",fromStandardTextBlock(t){return{type:"text",text:t.text,..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}},fromStandardImageBlock(t){if(t.source_type==="url"){lete=Xk({dataUrl:t.url,asTypedArray:!1});returne?{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:t.url,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}}else{if(t.source_type==="base64")return{type:"image",source:{type:"base64",data:t.data,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}};thrownewError(`Unsupported image source type: ${t.source_type}`)}},fromStandardFileBlock(t){lete=(t.mime_type??"").split(";")[0];if(t.source_type==="url"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"url",url:t.url,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};thrownewError(`Unsupported file mime type for file url source: ${t.mime_type}`)}elseif(t.source_type==="text"){if(e==="text/plain"||e==="")return{type:"document",source:{type:"text",data:t.text,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};thrownewError(`Unsupported file mime type for file text source: ${t.mime_type}`)}elseif(t.source_type==="base64"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"base64",data:t.data,media_type:"application/pdf"},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};if(["image/jpeg","image/png","image/gif","image/webp"].includes(e))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:t.data,media_type:e}}]},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};thrownewError(`Unsupported file mime type for file base64 source: ${t.mime_type}`)}elsethrownewError(`Unsupported file source type: ${t.source_type}`)}};functionkke(t){lete=["tool_use","tool_result","input_json_delta"],r=["text","text_delta"];returntypeoft=="string"?t:t.map(o=>{if(Jy(o))returnSH(o,dsn);leti="cache_control"ino?o.cache_control:void0;if(o.type==="image_url"){leta;returntypeofo.image_url=="string"?a=qUt(o.image_url):a=qUt(o.image_url.url),{type:"image",source:a,...i?{cache_control:i}:{}}}else{if(UUt(o))returno;if(o
`,t}function $ke(t){let e;return t.status===400&&t.message.includes("tool")?e=uce(t,"INVALID_TOOL_RESULTS"):t.status===401?e=uce(t,"MODEL_AUTHENTICATION"):t.status===404?e=uce(t,"MODEL_NOT_FOUND"):t.status===429?e=uce(t,"MODEL_RATE_LIMIT"):e=t,e}function psn(t){return!!(t.tools&&t.tools.length>0)}function msn(t){for(let e of t.messages??[])if(typeof e.content!="string"){for(let r of e.content??[])if(typeof r=="object"&&r!=null&&r.type==="document"&&typeof r.citations=="object"&&r.citations.enabled)return!0}return!1}function hsn(t){return!!(t.thinking&&t.thinking.type==="enabled")}function gsn(t){return"input_schema"in t}function ysn(t){if(typeof t.content=="string")return t.content;if(Array.isArray(t.content)&&t.content.length>=1&&"input"in t.content[0])return typeof t.content[0].input=="string"?t.content[0].input:JSON.stringify(t.content[0].input);if(Array.isArray(t.content)&&t.content.length>=1&&"text"in t.content[0])return t.content[0].text}var zke=class extends du{static lc_name(){return"ChatAnthropic"}get lc_secrets(){return{anthropicApiKey:"ANTHROPIC_API_KEY",apiKey:"ANTHROPIC_API_KEY"}}get lc_aliases(){return{modelName:"model"}}constructor(e){if(super(e??{}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"anthropicApiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"temperature",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"topK",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(this,"topP",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:2048}),Object.defineProperty(this,"modelName",{enumerable:!0,configurable:!0,writable:!0,value:"claude-2.1"}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"claude-2.1"}),Object.defineProperty(this,"invocationKwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stopSequences",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streaming",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"clientOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"thinking",{enumerable:!0,configurable:!0,writable:!0,value:{type:"disabled"}}),Object.defineProperty(this,"batchClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streamingClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streamUsage",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"createClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.anthropicApiKey=e?.apiKey??e?.anthropicApiKey??ct("ANTHROPIC_API_KEY"),!this.anthropicApiKey&&!e?.createClient)throw new Error("Anthropic API key not found");this.clientOptions=e?.clientOptions??{},this.apiKey=this.anthropicApiKey,this.apiUrl=e?.anthropicApiUrl,this.modelName=e?.model??e?.modelName??this.model,this.model=this.modelName,this.invocationKwargs=e?.invocationKwargs??{},this.temperature=e?.temperature??this.temperature,this.topK=e?.topK??this.topK,this.topP=e?.topP??this.topP,this.maxTokens=e?.maxTokensToSample??e?.maxTokens??this.maxTokens,this.stopSequences=e?.stopSequences??this.stopSequences,this.streaming=e?.streaming??!1,this.streamUsage=e?.streamUsage??this.streamUsage,this.thinking=e?.thinking??this.thinking,this.createClient=e?.createClient??(r=>new Si(r))}getLsParams(e){let r=this.invocationParams(e);return{ls_provider:"anthropic",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:r.temperature??void 0,ls_max_tokens:r.max_tokens??void 0,ls_stop:e.stop}}formatStructuredToolToAnthropic(e){if(!(!e||!e.l
`):[]}};Ih=newWeakMap;EL.NEWLINE_CHARS=newSet([`
`,"\r"]);EL.NEWLINE_REGEXP=/\r\n|[\n\r]/g;functionMsn(t,e){for(leto=e??0;o<t.length;o++){if(t[o]===10)return{preceding:o,index:o+1,carriage:!1};if(t[o]===13)return{preceding:o,index:o+1,carriage:!0}}returnnull}functionrqt(t){for(letn=0;n<t.length-1;n++){if(t[n]===10&&t[n+1]===10||t[n]===13&&t[n+1]===13)returnn+2;if(t[n]===13&&t[n+1]===10&&n+3<t.length&&t[n+2]===13&&t[n+3]===10)returnn+4}return-1}functionXke(t){if(t[Symbol.asyncIterator])returnt;lete=t.getReader();return{asyncnext(){try{letr=awaite.read();returnr?.done&&e.releaseLock(),r}catch(r){throwe.releaseLock(),r}},asyncreturn(){letr=e.cancel();returne.releaseLock(),awaitr,{done:!0,value:void0}},[Symbol.asyncIterator](){returnthis}}}varNC=classt{constructor(e,r){this.iterator=e,this.controller=r}staticfromSSEResponse(e,r){letn=!1;asyncfunction*o(){if(n)thrownewError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;leti=!1;try{forawait(letaofRsn(e,r))if(!i){if(a.data.startsWith("[DONE]")){i=!0;continue}if(a.event===null||a.event.startsWith("response.")||a.event.startsWith("transcript.")){lets;try{s=JSON.parse(a.data)}catch(u){throwconsole.error("Could not parse message into JSON:",a.data),console.error("From chunk:",a.raw),u}if(s&&s.error)thrownewbu(void0,s.error,void0,e$e(e.headers));yields}else{lets;try{s=JSON.parse(a.data)}catch(u){throwconsole.error("Could not parse message into JSON:",a.data),console.error("From chunk:",a.raw),u}if(a.event=="error")thrownewbu(void0,s.error,s.message,void0);yield{event:a.event,data:s}}}i=!0}catch(a){if(ainstanceofError&&a.name==="AbortError")return;throwa}finally{i||r.abort()}}returnnewt(o,r)}staticfromReadableStream(e,r){letn=!1;asyncfunction*o(){leta=newEL,s=Xke(e);forawait(letuofs)for(letlofa.decode(u))yieldl;for(letuofa.flush())yieldu}asyncfunction*i(){if(n)thrownewError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;leta=!1;try{forawait(letsofo())a||s&&(yieldJSON.parse(s));a=!0}catch(s){if(sinstanceofError&&s.name==="AbortError")return;throws}finally{a||r.abort()}}returnnewt(i,r)}[Symbol.asyncIterator](){returnthis.iterator()}tee(){lete=[],r=[],n=this.iterator(),o=i=>({next:()=>{if(i.length===0){leta=n.next();e.push(a),r.push(a)}returni.shift()}});return[newt(()=>o(e),this.controller),newt(()=>o(r),this.controller)]}toReadableStream(){lete=this,r,n=newTextEncoder;returnnewKke({asyncstart(){r=e[Symbol.asyncIterator]()},asyncpull(o){try{let{value:i,done:a}=awaitr.next();if(a)returno.close();lets=n.encode(JSON.stringify(i)+`
`);o.enqueue(s)}catch(i){o.error(i)}},asynccancel(){awaitr.return?.()}})}};asyncfunction*Rsn(t,e){if(!t.body)throwe.abort(),newBt("Attempted to iterate over a response with no body");letr=newQke,n=newEL,o=Xke(t.body);forawait(letiofNsn(o))for(letaofn.decode(i)){lets=r.decode(a);s&&(yields)}for(letiofn.flush()){leta=r.decode(i);a&&(yielda)}}asyncfunction*Nsn(t){lete=newUint8Array;forawait(letroft){if(r==null)continue;letn=rinstanceofArrayBuffer?newUint8Array(r):typeofr=="string"?newTextEncoder().encode(r):r,o=newUint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;leti;for(;(i=rqt(e))!==-1;)yielde.slice(0,i),e=e.slice(i)}e.length>0&&(yielde)}varQke=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)returnnull;leti={event:this.event,data:this.data.join(`
`),raw:this.chunks};returnthis.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))returnnull;let[r,n,o]=jsn(e,":");returno.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}};functionjsn(t,e){letr=t.indexOf(e);returnr!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}varnqt=t=>t!=null&&typeoft=="object"&&typeoft.url=="string"&&typeoft.blob=="function",oqt=t=>t!=null&&typeoft=="object"&&typeoft.name=="string"&&typeoft.lastModified=="number"&&MK(t),MK=t=>t!=null&&typeoft=="object"&&typeoft.size=="number"&&typeoft.type=="string"&&typeoft.text=="function"&&typeoft.slice=="function"&&typeoft.arrayBuffer=="function",Dsn=t=>oqt(t)||nqt(t)||Zke(t);asyncfunctionn$e(t,e,r){if(t=awaitt,oqt(t))returnt;if(nqt(t)){leto=awaitt.blob();e||(e=newURL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file");leti=MK(o)?[awaito.arrayBuffer()]:[o];returnnewfce(i,e,r)}letn=awaitLsn(t);if(e||(e=ksn(t)??"unknown_file"),!r?.type){leto=n[0]?.type;typeofo=="string"&&(r={...r,type:o})}returnnewfce(n,e,r)}asyncfunctionLsn(t){lete=[];if(typeoft=="string"||ArrayBuffer.isView(t)||tinstanceofArrayBuffer)e.push(t);elseif(MK(t))e.push(awaitt.arrayBuffer());elseif($sn(t))forawait(letroft)e.push(r);elsethrownewError(`Unexpected data type: ${typeoft}; constructor: ${t?.constructor?.name}; props: ${Fsn(t)}`);returne}functionFsn(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}functionksn(t){returnt$e(t.name)||t$e(t.filename)||t$e(t.path)?.split(/[\\/]/).pop()}vart$e=t=>{if(typeoft=="string")returnt;if(typeofBuffer<"u"&&tinstanceofBuffer)returnString(t)},$sn=t=>t!=null&&typeoft=="object"&&typeoft[Symbol.asyncIterator]=="function",o$e=t=>t&&typeoft=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody";varly=asynct=>{lete=awaitiqt(t.body);returnGke(e,t)},iqt=asynct=>{lete=newWke;returnawaitPromise.all(Object.entries(t||{}).map(([r,n])=>r$e(e,r,n))),e};varr$e=async(t,e,r)=>{if(r!==void0){if(r==null)thrownewTypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeofr=="string"||typeofr=="number"||typeofr=="boolean")t.append(e,String(r));elseif(Dsn(r)){letn=awaitn$e(r);t.append(e,n)}elseif(Array.isArray(r))awaitPromise.all(r.map(n=>r$e(t,e+"[]",n)));elseif(typeofr=="object")awaitPromise.all(Object.entries(r).map(([n,o])=>r$e(t,`${e}[${n}]`,o)));elsethrownewTypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};varBsn=function(t,e,r,n,o){if(n==="m")thrownewTypeError("Private method is not writable");if(n==="a"&&!o)thrownewTypeError("Private accessor was defined without a setter");if(typeofe=="function"?t!==e||!o:!e.has(t))thrownewTypeError("Cannot write private member to an object whose class did not declare it");returnn==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r},Usn=function(t,e,r,n){if(r==="a"&&!n)thrownewTypeError("Private accessor was defined without a getter");if(typeofe=="function"?t!==e||!n:!e.has(t))thrownewTypeError("Cannot read private member from an object whose class did not declare it");returnr==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},yce;Yke();asyncfunctiondqt(t){let{response:e}=t;if(t.options.stream)returngE("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):NC.fromSSEResponse(e,t.controller);if(e.status===204)returnnull;if(t.options.__binaryResponse)returne;letn=e.headers.get("content-type")?.split(";")[0]?.trim();if(n?.includes("application/json")||n?.endsWith("+json")){leta=awaite.json();returngE("response",e.status,e.url,e.headers,a),fqt(a,e)}leti=awaite.text();returngE("response",e.status,e.url,e.headers,i),i}functionfqt(t,e){return!t||typeoft!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var_ce=classtextendsPromise{constructor(e,r=dqt){supe
\r`.includes(t[n]);)n++};return a()},_$e=t=>aun(t,Nc.ALL^Nc.NUM);var M2=function(t,e,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r},Fi=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},nc,vE,R2,GM,v$e,Tce,w$e,x$e,S$e,Ace,C$e,Oqt,N2=class t extends I2{constructor(e){super(),nc.add(this),vE.set(this,void 0),R2.set(this,void 0),GM.set(this,void 0),M2(this,vE,e,"f"),M2(this,R2,[],"f")}get currentChatCompletionSnapshot(){return Fi(this,GM,"f")}static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static createChatCompletion(e,r,n){let o=new t(r);return o._run(()=>o._runChatCompletion(e,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createChatCompletion(e,r,n){super._createChatCompletion;let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),Fi(this,nc,"m",v$e).call(this);let i=await e.chat.completions.create({...r,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let a of i)Fi(this,nc,"m",w$e).call(this,a);if(i.controller.signal?.aborted)throw new xa;return this._addChatCompletion(Fi(this,nc,"m",Ace).call(this))}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),Fi(this,nc,"m",v$e).call(this),this._connected();let o=NC.fromReadableStream(e,this.controller),i;for await(let a of o)i&&i!==a.id&&this._addChatCompletion(Fi(this,nc,"m",Ace).call(this)),Fi(this,nc,"m",w$e).call(this,a),i=a.id;if(o.controller.signal?.aborted)throw new xa;return this._addChatCompletion(Fi(this,nc,"m",Ace).call(this))}[(vE=new WeakMap,R2=new WeakMap,GM=new WeakMap,nc=new WeakSet,v$e=function(){this.ended||M2(this,GM,void 0,"f")},Tce=function(r){let n=Fi(this,R2,"f")[r.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},Fi(this,R2,"f")[r.index]=n,n)},w$e=function(r){if(this.ended)return;let n=Fi(this,nc,"m",Oqt).call(this,r);this._emit("chunk",r,n);for(let o of r.choices){let i=n.choices[o.index];o.delta.content!=null&&i.message?.role==="assistant"&&i.message?.content&&(this._emit("content",o.delta.content,i.message.content),this._emit("content.delta",{delta:o.delta.content,snapshot:i.message.content,parsed:i.message.parsed})),o.delta.refusal!=null&&i.message?.role==="assistant"&&i.message?.refusal&&this._emit("refusal.delta",{delta:o.delta.refusal,snapshot:i.message.refusal}),o.logprobs?.content!=null&&i.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:o.logprobs?.content,snapshot:i.logprobs?.content??[]}),o.logprobs?.refusal!=null&&i.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:o.logprobs?.refusal,snapshot:i.logprobs?.refusal??[]});let a=Fi(this,nc,"m",Tce).call(this,i);i.finish_reason&&(Fi(this,nc,"m",S$e).call(this,i),a.current_tool_call_index!=null&&Fi(this,nc,"m",x$e).call(this,i,a.current_tool_call_index));for(let s of o.delta.tool_calls??[])a.current_tool_call_index!==s.index&&(Fi(this,nc,"m",S$e).call(this,i),a.current_tool_call_index!=null&&Fi(this,nc,"m",x$e).call(this,i,a.current_tool_call_index)),a.current_tool_call_index=s.index;for(let s of o.delta.tool_calls??[]){let u=i.message.tool_calls?.[s.index];u?.type&&(u?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:u.function?.name,index:s.index,arguments:u.function.arguments,parsed_arguments:u.function.parsed_arg
${Ice(t)}`);return{...A,id:P,type:E,function:{...N,name:R,arguments:I}}})}}:{...p,message:{...g,content:m,role:y,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}),created:o,model:i,object:"chat.completion",...a?{system_fingerprint:a}:{}};returnvqt(u,e)}functionIce(t){returnJSON.stringify(t)}varUK=classtextendsN2{staticfromReadableStream(e){letr=newt(null);returnr._run(()=>r._fromReadableStream(e)),r}staticrunFunctions(e,r,n){leto=newt(null),i={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runFunctions"}};returno._run(()=>o._runFunctions(e,r,i)),o}staticrunTools(e,r,n){leto=newt(r),i={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};returno._run(()=>o._runTools(e,r,i)),o}};varqK=classextendsit{parse(e,r){returnxqt(e.tools),this._client.chat.completions.create(e,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap(n=>zK(n,e))}runFunctions(e,r){returne.stream?UK.runFunctions(this._client,e,r):BK.runFunctions(this._client,e,r)}runTools(e,r){returne.stream?UK.runTools(this._client,e,r):BK.runTools(this._client,e,r)}stream(e,r){returnN2.createChatCompletion(this._client,e,r)}};varj2=classextendsit{constructor(){super(...arguments),this.completions=newqK(this._client)}};(function(t){t.Completions=qK})(j2||(j2={}));varD2=classextendsit{create(e,r){returnthis._client.post("/realtime/sessions",{body:e,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}};varL2=classextendsit{create(e,r){returnthis._client.post("/realtime/transcription_sessions",{body:e,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}};varJM=classextendsit{constructor(){super(...arguments),this.sessions=newD2(this._client),this.transcriptionSessions=newL2(this._client)}};JM.Sessions=D2;JM.TranscriptionSessions=L2;vartr=function(t,e,r,n){if(r==="a"&&!n)thrownewTypeError("Private accessor was defined without a getter");if(typeofe=="function"?t!==e||!n:!e.has(t))thrownewTypeError("Cannot read private member from an object whose class did not declare it");returnr==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Mh=function(t,e,r,n,o){if(n==="m")thrownewTypeError("Private method is not writable");if(n==="a"&&!o)thrownewTypeError("Private accessor was defined without a setter");if(typeofe=="function"?t!==e||!o:!e.has(t))thrownewTypeError("Cannot write private member to an object whose class did not declare it");returnn==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r},Od,O$e,LC,Mce,Jb,RL,F2,ML,jce,Rh,Rce,Nce,WK,HK,VK,Pqt,Eqt,Tqt,Aqt,Iqt,Mqt,Rqt,FC=classtextendsKM{constructor(){super(...arguments),Od.add(this),O$e.set(this,[]),LC.set(this,{}),Mce.set(this,{}),Jb.set(this,void0),RL.set(this,void0),F2.set(this,void0),ML.set(this,void0),jce.set(this,void0),Rh.set(this,void0),Rce.set(this,void0),Nce.set(this,void0),WK.set(this,void0)}[(O$e=newWeakMap,LC=newWeakMap,Mce=newWeakMap,Jb=newWeakMap,RL=newWeakMap,F2=newWeakMap,ML=newWeakMap,jce=newWeakMap,Rh=newWeakMap,Rce=newWeakMap,Nce=newWeakMap,WK=newWeakMap,Od=newWeakSet,Symbol.asyncIterator)](){lete=[],r=[],n=!1;returnthis.on("event",o=>{leti=r.shift();i?i.resolve(o):e.push(o)}),this.on("end",()=>{n=!0;for(letoofr)o.resolve(void0);r.length=0}),this.on("abort",o=>{n=!0;for(letiofr)i.reject(o);r.length=0}),this.on("error",o=>{n=!0;for(letiofr)i.reject(o);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void0,done:!0}:newPromise((i,a)=>r.push({resolve:i,reject:a})).then(i=>i?{value:i,done:!1}:{value:void0,done:!0}),return:async()=>(this.abort(),{value:void0,done:!0})}}staticfromReadableStream(e){letr=newt;returnr._run(()=>r._fromReadableStream(e)),r}async_fromReadableStream(e,r){letn=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();leto=NC.fromReadableStream(e,this.controller);forawait(letiofo)tr(this,Od,"m",HK).call(this,i);if(o.controller.signal?.aborted)thrownewxa;returnthis._addRun(tr(this,Od,"m",VK).call(this))}
`);super({baseURL:a.baseURL,timeout:a.timeout??6e5,httpAgent:a.httpAgent,maxRetries:a.maxRetries,fetch:a.fetch}),this.completions=newDL(this),this.chat=newbE(this),this.embeddings=newLL(this),this.files=newZM(this),this.images=newUL(this),this.audio=newDC(this),this.moderations=newHL(this),this.models=newXM(this),this.fineTuning=newYb(this),this.vectorStores=newNh(this),this.beta=newZb(this),this.batches=newVM(this),this.uploads=newrR(this),this.responses=newtR(this),this.evals=new$C(this),this._options=a,this.apiKey=r,this.organization=n,this.project=o}defaultQuery(){returnthis._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(e){returnHke(e,{arrayFormat:"brackets"})}};$qt=wr;wr.OpenAI=$qt;wr.DEFAULT_TIMEOUT=6e5;wr.OpenAIError=Bt;wr.APIError=bu;wr.APIConnectionError=hE;wr.APIConnectionTimeoutError=Ah;wr.APIUserAbortError=xa;wr.NotFoundError=y2;wr.ConflictError=b2;wr.RateLimitError=v2;wr.BadRequestError=m2;wr.AuthenticationError=h2;wr.InternalServerError=w2;wr.PermissionDeniedError=g2;wr.UnprocessableEntityError=_2;wr.toFile=n$e;wr.fileFromPath=pce;wr.Completions=DL;wr.Chat=bE;wr.ChatCompletionsPage=HM;wr.Embeddings=LL;wr.Files=ZM;wr.FileObjectsPage=$L;wr.Images=UL;wr.Audio=DC;wr.Moderations=HL;wr.Models=XM;wr.ModelsPage=qL;wr.FineTuning=Yb;wr.VectorStores=Nh;wr.VectorStoresPage=VL;wr.VectorStoreSearchResponsesPage=WL;wr.Beta=Zb;wr.Batches=VM;wr.BatchesPage=TL;wr.Uploads=rR;wr.Responses=tR;wr.Evals=$C;wr.EvalListResponsesPage=kL;As();Of();Kn();iC();bh();Jp();eb();yq();ug();varBqt=Symbol("Let zodToJsonSchema decide on which parser to use"),zqt={name:void0,$refStrategy:"root",effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",nullableStrategy:"from-target",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},Uqt=t=>typeoft=="string"?{...zqt,basePath:["#"],definitions:{},name:t}:{...zqt,basePath:["#"],definitions:{},...t};varKK=t=>"_def"int?t._def:t;functionqqt(t){if(!t)return!0;for(leteint)return!1;return!0}varHqt=t=>{lete=Uqt(t),r=e.name!==void0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void0,seenRefs:newSet,seen:newMap(Object.entries(e.definitions).map(([n,o])=>[KK(o),{def:KK(o),path:[...e.basePath,e.definitionPath,n],jsonSchema:void0}]))}};functionT$e(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}functionio(t,e,r,n,o){t[e]=r,T$e(t,e,n,o)}Qf();functionVqt(){return{}}Qf();functionWqt(t,e){letr={type:"array"};returnt.type?._def?.typeName!==re.ZodAny&&(r.items=xr(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&io(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&io(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(io(r,"minItems",t.exactLength.value,t.exactLength.message,e),io(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}functionKqt(t,e){letr={type:"integer",format:"int64"};if(!t.checks)returnr;for(letnoft.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?io(r,"minimum",n.value,n.message,e):io(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),io(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?io(r,"maximum",n.value,n.message,e):io(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),io(r,"maximum",n.value,n.message,e));break;case"multipleOf":io(r,"multipleOf",n.value,n.message,e);break}returnr}functionGqt(){return{type:"boolean"}}functionJqt(t,e){returnxr(t.type._def,e)}varZqt=(t,e)=>xr(t.innerType._def,e);functionA$e(t,e,r){letn=r??e.dateStrate
This will become an error in a future version of the SDK.`),{properties:{...n.properties,[o]:s},required:i.isOptional()&&!e.openaiStrictMode?n.required:[...n.required,o]})},{properties:{},required:[]}),additionalProperties:kun(t,e)};returnr.required.length||deleter.required,r}varf2t=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())returnxr(t.innerType._def,e);letr=xr(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});returnr?{anyOf:[{not:{}},r]}:{}};varp2t=(t,e)=>{if(e.pipeStrategy==="input")returnxr(t.in._def,e);if(e.pipeStrategy==="output")returnxr(t.out._def,e);letr=xr(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=xr(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void0)}};functionm2t(t,e){returnxr(t.type._def,e)}functionh2t(t,e){letn={type:"array",uniqueItems:!0,items:xr(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};returnt.minSize&&io(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&io(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}functiong2t(t,e){returnt.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>xr(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void0?r:[...r,n],[]),additionalItems:xr(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>xr(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void0?r:[...r,n],[])}}functiony2t(){return{not:{}}}functionb2t(){return{}}var_2t=(t,e)=>xr(t.innerType._def,e);functionxr(t,e,r=!1){letn=e.seen.get(t);if(e.override){leta=e.override?.(t,e,n,r);if(a!==Bqt)returna}if(n&&!r){leta=$un(n,e);if(a!==void0)return"$ref"ina&&e.seenRefs.add(a.$ref),a}leto={def:t,path:e.currentPath,jsonSchema:void0};e.seen.set(t,o);leti=Uun(t,t.typeName,e,r);returni&&qun(t,e,i),o.jsonSchema=i,i}var$un=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"extract-to-root":letr=t.path.slice(e.basePath.length+1).join("_");returnr!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[r]=t.def),{$ref:[...e.basePath,e.definitionPath,r].join("/")};case"relative":return{$ref:zun(e.currentPath,t.path)};case"none":case"seen":returnt.path.length<e.currentPath.length&&t.path.every((n,o)=>e.currentPath[o]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void0}},zun=(t,e)=>{letr=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")},Uun=(t,e,r,n)=>{switch(e){casere.ZodString:return$ce(t,r);casere.ZodNumber:returnc2t(t,r);casere.ZodObject:returnd2t(t,r);casere.ZodBigInt:returnKqt(t,r);casere.ZodBoolean:returnGqt();casere.ZodDate:returnA$e(t,r);casere.ZodUndefined:returny2t();casere.ZodNull:returna2t(r);casere.ZodArray:returnWqt(t,r);casere.ZodUnion:casere.ZodDiscriminatedUnion:returnu2t(t,r);casere.ZodIntersection:returne2t(t,r);casere.ZodTuple:returng2t(t,r);casere.ZodRecord:returnzce(t,r);casere.ZodLiteral:returnt2t(t,r);casere.ZodEnum:returnQqt(t);casere.ZodNativeEnum:returno2t(t);casere.ZodNullable:returnl2t(t,r);casere.ZodOptional:returnf2t(t,r);casere.ZodMap:returnn2t(t,r);casere.ZodSet:returnh2t(t,r);casere.ZodLazy:returnxr(t.getter()._def,r);casere.ZodPromise:returnm2t(t,r);casere.ZodNaN:casere.ZodNever:returni2t();casere.ZodEffects:returnXqt(t,r,n);casere.ZodAny:returnVqt();casere.ZodUnknown:returnb2t();casere.ZodDefault:returnYqt(t,r);casere.ZodBranded:returnJqt(t,r);casere.ZodReadonly:return_2t(t,r);casere.ZodCatch:returnZqt(t,r);casere.ZodPipeline:returnp2t(t,r);casere.ZodFunction:casere.ZodVoid:casere.ZodSymbol:return;default:return(o=>{})(e)}},qun=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);varv2t=(t,e)=>{letr=Hqt(e),n=typeofe=="string"?e:e?.nam
`),raw:this.chunks};returnthis.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))returnnull;let[r,n,o]=eln(e,":");returno.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},u4=classt{constructor(){this.buffer=[],this.trailingCR=!1}decode(e){letr=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[];letn=t.NEWLINE_CHARS.has(r[r.length-1]||""),o=r.split(t.NEWLINE_REGEXP);returno.length===1&&!n?(this.buffer.push(o[0]),[]):(this.buffer.length>0&&(o=[this.buffer.join("")+o[0],...o.slice(1)],this.buffer=[]),n||(this.buffer=[o.pop()||""]),o)}decodeText(e){if(e==null)return"";if(typeofe=="string")returne;if(typeofBuffer<"u"){if(einstanceofBuffer)returne.toString();if(einstanceofUint8Array)returnBuffer.from(e).toString();thrownewjc(`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(typeofTextDecoder<"u"){if(einstanceofUint8Array||einstanceofArrayBuffer)returnthis.textDecoder??(this.textDecoder=newTextDecoder("utf8")),this.textDecoder.decode(e);thrownewjc(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}thrownewjc("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];lete=[this.buffer.join("")];returnthis.buffer=[],this.trailingCR=!1,e}};u4.NEWLINE_CHARS=newSet([`
`,"\r","\v","\f","","","","\x85","\u2028","\u2029"]);u4.NEWLINE_REGEXP=/\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g;functioneln(t,e){letr=t.indexOf(e);returnr!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}functionM2t(t){if(t[Symbol.asyncIterator])returnt;lete=t.getReader();return{asyncnext(){try{letr=awaite.read();returnr?.done&&e.releaseLock(),r}catch(r){throwe.releaseLock(),r}},asyncreturn(){letr=e.cancel();returne.releaseLock(),awaitr,{done:!0,value:void0}},[Symbol.asyncIterator](){returnthis}}}varR2t=t=>t!=null&&typeoft=="object"&&typeoft.url=="string"&&typeoft.blob=="function",N2t=t=>t!=null&&typeoft=="object"&&typeoft.name=="string"&&typeoft.lastModified=="number"&&Yce(t),Yce=t=>t!=null&&typeoft=="object"&&typeoft.size=="number"&&typeoft.type=="string"&&typeoft.text=="function"&&typeoft.slice=="function"&&typeoft.arrayBuffer=="function",tln=t=>N2t(t)||R2t(t)||U$e(t);asyncfunctionK$e(t,e,r){if(t=awaitt,r??(r=N2t(t)?{lastModified:t.lastModified,type:t.type}:{}),R2t(t)){leto=awaitt.blob();returne||(e=newURL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file"),newWce([o],e,r)}letn=awaitrln(t);if(e||(e=oln(t)??"unknown_file"),!r.type){leto=n[0]?.type;typeofo=="string"&&(r={...r,type:o})}returnnewWce(n,e,r)}asyncfunctionrln(t){lete=[];if(typeoft=="string"||ArrayBuffer.isView(t)||tinstanceofArrayBuffer)e.push(t);elseif(Yce(t))e.push(awaitt.arrayBuffer());elseif(iln(t))forawait(letroft)e.push(r);elsethrownewError(`Unexpected data type: ${typeoft}; constructor: ${t?.constructor?.name}; props: ${nln(t)}`);returne}functionnln(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}functionoln(t){returnV$e(t.name)||V$e(t.filename)||V$e(t.path)?.split(/[\\/]/).pop()}varV$e=t=>{if(typeoft=="string")returnt;if(typeofBuffer<"u"&&tinstanceofBuffer)returnString(t)},iln=t=>t!=null&&typeoft=="object"&&typeoft[Symbol.asyncIterator]=="function",G$e=t=>t&&typeoft=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody";varYK=asynct=>{lete=awaitj2t(t.body);returnz$e(e,t)},j2t=asynct=>{lete=newk$e;returnawaitPromise.all(Object.entries(t||{}).map(([r,n])=>W$e(e,r,n))),e};varW$e=async(t,e,r)=>{if(r!==void0){if(r==null)thrownewTypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeofr=="string"||typeofr=="number"||typeofr=="boolean")t.append(e,String(r));elseif(tln(r)){letn=awaitK$e(r);t.append(e,n)}elseif(Array.isArray(r))awaitPromise.all(r.map(n=>W$e(t,e+"[]",n)));elseif(typeofr=="object")awaitPromise.all(Object.entries(r).map(([n,o])=>W$e(t,`${e}[${n}]`,o)));elsethrownewTypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};varsln=function(t,e,r,n,o){if(n==="m")thrownewTypeError("Private method is not writable");if(n==="a"&&!o)thrownewTypeError("Private accessor was defined without a setter");if(typeofe=="function"?t!==e||!o:!e.has(t))thrownewTypeError("Cannot write private member to an object whose class did not declare it");returnn==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r},uln=function(t,e,r,n){if(r==="a"&&!n)thrownewTypeError("Private accessor was defined without a getter");if(typeofe=="function"?t!==e||!n:!e.has(t))thrownewTypeError("Cannot read private member from an object whose class did not declare it");returnr==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Xce;asyncfunctionz2t(t){let{response:e}=t;if(t.options.stream)returnl4("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):Zce.fromSSEResponse(e,t.controller);if(e.status===204)returnnull;if(t.options.__binaryResponse)returne;letr=e.headers.get("content-type");if(r?.includes("application/json")||r?.includes("application/vnd.api+json")){leti=awaite.json();returnl4("response",e.status,e.url,e.headers,i),i}leto=awaite.text();returnl4("response",e.status,e.url,e.headers,o),o}varQce=classtextendsPromise{constructor(e
Received:${JSON.stringify(o,null,2)}`)};if(typeof o=="string")return o;if(Array.isArray(o)){let s=e(i),u=[];return o.forEach(l=>{if(l.type==="text"||l.type==="image_url")u.push(a(l,s));else throw new Error('Mistral only supports types "text" or "image_url" for complex message types.')}),u}throw new Error(`Messagecontentmustbeastringoranarray.
`);case"array":returnt.items?`${cme(t.items,e)}[]`:"any[]";default:return""}}_h();functionoGt(t,e){letr;if(Cc(t)){letn=Uce({name:t.name,parameters:t.schema,description:t.description});n.function.parameters?r={type:n.type,function:{name:n.function.name,description:n.function.description,parameters:n.function.parameters,...e?.strict!==void0?{strict:e.strict}:{}}}:r={type:"function",function:GI(t,e)}}elser=t;returne?.strict!==void0&&(r.function.strict=e.strict),r}functionkMn(t){returnt.role!=="system"&&t.role!=="developer"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function"&&t.role!=="tool"&&console.warn(`Unknown message role: ${t.role}`),t.role}functionqUe(t){lete=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(!ks.isInstance(t))thrownewError("Invalid generic chat message");returnkMn(t)}default:thrownewError(`Unknown message type: ${e}`)}}functionUUe(t,e){returnt.flatMap(r=>{letn=qUe(r);n==="system"&&HUe(e)&&(n="developer");leto={role:n,content:r.content};if(r.name!=null&&(o.name=r.name),r.additional_kwargs.function_call!=null&&(o.function_call=r.additional_kwargs.function_call,o.content=""),Di(r)&&r.tool_calls?.length?(o.tool_calls=r.tool_calls.map(_C),o.content=""):(r.additional_kwargs.tool_calls!=null&&(o.tool_calls=r.additional_kwargs.tool_calls),r.tool_call_id!=null&&(o.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeofr.additional_kwargs.audio=="object"&&"id"inr.additional_kwargs.audio){leti={role:"assistant",audio:{id:r.additional_kwargs.audio.id}};return[o,i]}returno})}varF4="__openai_function_call_ids__";functioniGt(t,e){returnt.flatMap(r=>{letn=qUe(r);if(n==="system"&&HUe(e)&&(n="developer"),n==="function")thrownewError("Function messages are not supported in Responses API");if(n==="tool"){leto=r;returno.additional_kwargs?.type==="computer_call_output"?{type:"computer_call_output",output:(()=>{if(typeofo.content=="string")return{type:"computer_screenshot",image_url:o.content};if(Array.isArray(o.content)){leta=o.content.find(u=>u.type==="computer_screenshot");if(a)returna;lets=o.content.find(u=>u.type==="image_url");if(s)return{type:"computer_screenshot",image_url:typeofs.image_url=="string"?s.image_url:s.image_url.url}}thrownewError("Invalid computer call output")})(),call_id:o.tool_call_id}:{type:"function_call_output",call_id:o.tool_call_id,id:o.id,output:typeofo.content!="string"?JSON.stringify(o.content):o.content}}if(n==="assistant"){leto=[];r.additional_kwargs.reasoning!=null&&(u=>typeofu=="object"&&u!=null&&"type"inu&&u.type==="reasoning")(r.additional_kwargs.reasoning)&&o.push(r.additional_kwargs.reasoning);let{content:i}=r;r.additional_kwargs.refusal!=null&&(typeofi=="string"&&(i=[{type:"output_text",text:i,annotations:[]}]),i=[...i,{type:"refusal",refusal:r.additional_kwargs.refusal}]),o.push({type:"message",role:"assistant",content:typeofi=="string"?i:i.flatMap(s=>s.type==="text"?{type:"output_text",text:s.text,annotations:s.annotations??[]}:s.type==="output_text"||s.type==="refusal"?s:[])});leta=r.additional_kwargs[F4];if(Di(r)&&r.tool_calls?.length?o.push(...r.tool_calls.map(s=>({type:"function_call",name:s.name,arguments:JSON.stringify(s.args),call_id:s.id,id:a?.[s.id]}))):r.additional_kwargs.tool_calls!=null&&o.push(...r.additional_kwargs.tool_calls.map(s=>({type:"function_call",name:s.function.name,call_id:s.id,id:a?.[s.id],arguments:s.function.arguments}))),r.additional_kwargs.tool_outputs!=null){letu=r.additional_kwargs.tool_outputs?.filter(l=>l.type==="computer_call");u.length>0&&o.push(...u)}returno}returnn==="user"?{type:"message",role:"user",content:typeofr.content=="string"?r.content:r.content.flatMap(o=>{if(o.type==="text")return{type:"input_text",text:o.text};if(o.type==="image_url"){leti=typeofo.image_url=="string"?o.image_url:o.image_url.url,a=typeofo.image_url=="string"?"auto":o.image_url.detail;return{type:"input_image",image_url:i,detail:a}}returno.type==="input_text"||o.type==="in
without CORS Error: `+ci(n)+`
with CORS Error: `+ci(o);throw new Error(i)}}}findModelByName(e){return ae().activeModels.find(n=>n.name===e)}};Bc.REASONING_MODEL_TEMPERATURE=1;var DF=Bc;er();As();var k4=class{},uGt=(t,e)=>{if(e!==void 0)return t[e];let r=Object.keys(t);if(r.length===1)return t[r[0]]},mme=(t,e)=>{let r=uGt(t,e);if(!r){let n=Object.keys(t);throw new Error(`input values have ${n.length} keys, you must specify an input key or pass only 1 key as input`)}return r},WUe=(t,e)=>{let r=uGt(t,e);if(!r&&r!==""){let n=Object.keys(t);throw new Error(`output values have ${n.length} keys, you must specify an output key or pass only 1 key as output`)}return r};Q1();lN();var KUe=class extends kp{addUserMessage(e){return this.addMessage(new $s(e))}addAIChatMessage(e){return this.addMessage(new En(e))}addAIMessage(e){return this.addMessage(new En(e))}async addMessages(e){for(let r of e)await this.addMessage(r)}clear(){throw new Error("Notimplemented.")}},$4=class extends KUe{constructor(e){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","stores","message","in_memory"]}),Object.defineProperty(this,"messages",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}};var s_=class extends k4{constructor(e){super(),Object.defineProperty(this,"chatHistory",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"returnMessages",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"inputKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.chatHistory=e?.chatHistory??new $4,this.returnMessages=e?.returnMessages??this.returnMessages,this.inputKey=e?.inputKey??this.inputKey,this.outputKey=e?.outputKey??this.outputKey}async saveContext(e,r){await this.chatHistory.addUserMessage(mme(e,this.inputKey)),await this.chatHistory.addAIChatMessage(WUe(r,this.outputKey))}async clear(){await this.chatHistory.clear()}};var $G=class extends s_{constructor(e){super({chatHistory:e?.chatHistory,returnMessages:e?.returnMessages??!1,inputKey:e?.inputKey,outputKey:e?.outputKey}),Object.defineProperty(this,"humanPrefix",{enumerable:!0,configurable:!0,writable:!0,value:"Human"}),Object.defineProperty(this,"aiPrefix",{enumerable:!0,configurable:!0,writable:!0,value:"AI"}),Object.defineProperty(this,"memoryKey",{enumerable:!0,configurable:!0,writable:!0,value:"history"}),this.humanPrefix=e?.humanPrefix??this.humanPrefix,this.aiPrefix=e?.aiPrefix??this.aiPrefix,this.memoryKey=e?.memoryKey??this.memoryKey}get memoryKeys(){return[this.memoryKey]}async loadMemoryVariables(e){let r=await this.chatHistory.getMessages();return this.returnMessages?{[this.memoryKey]:r}:{[this.memoryKey]:Xf(r,this.humanPrefix,this.aiPrefix)}}};As();As();GUe();sA();As();var zG=class extends s_{constructor(e){super({returnMessages:e?.returnMessages??!1,chatHistory:e?.chatHistory,inputKey:e?.inputKey,outputKey:e?.outputKey}),Object.defineProperty(this,"humanPrefix",{enumerable:!0,configurable:!0,writable:!0,value:"Human"}),Object.defineProperty(this,"aiPrefix",{enumerable:!0,configurable:!0,writable:!0,value:"AI"}),Object.defineProperty(this,"memoryKey",{enumerable:!0,configurable:!0,writable:!0,value:"history"}),Object.defineProperty(this,"k",{enumerable:!0,configurable:!0,writable:!0,value:5}),this.humanPrefix=e?.humanPrefix??this.humanPrefix,this.aiPrefix=e?.aiPrefix??this.aiPrefix,this.memoryKey=e?.memoryKey??this.memoryKey,this.k=e?.k??this.k}get memoryKeys(){return[this.memoryKey]}async loadMemoryVariables(e){let r=await this.chatHistory.getMessages();return this.returnMessages?{[this.memoryKey]:r.slice(-this.k*2)}:{[this.memoryKey]:Xf(r.slice(-this.k*2),this.humanPrefix,this.aiPrefix)}}};Kue();Mve();As();Q1();GUe();As();As();var BG=class t{constructor(){this.initMemory(),Ma(()=>{let e=this.memory?.chatHistory;this.initMemory(e)})}static g
`;this.qaPrompt=Gp.fromMessages([aA.fromTemplate(e)])}escapeTemplateString(e){return e.replace(/\{/g,"{{").replace(/\}/g,"}}")}getChatPrompt(){return this.chatPrompt}async getQAPrompt({question:e,context:r,systemMessage:n}){return await this.qaPrompt.format({question:e,context:r,system_message:n})}};var qG=class{constructor(e,r){this.retrievedDocuments=[];this.app=e,this.vectorStoreManager=r,this.memoryManager=BG.getInstance(),this.chatModelManager=DF.getInstance(),this.promptManager=UG.getInstance(),this.initialize(),Ma(async()=>{await this.createChainWithNewModel()})}getRetrievedDocuments(){return this.retrievedDocuments}async initialize(){await this.createChainWithNewModel()}getChain(){return this.chain}getRetrievalChain(){return this.retrievalChain}validateChainType(e){if(e==null)throw new Error("Nochaintypeset")}validateChatModel(){if(!this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())){let e="Chatmodelisnotinitializedproperly,checkyourAPIkeyinCopilotsettingandmakesureyouhaveAPIaccess.";throw new hme.Notice(e),new Error(e)}}validateChainInitialization(){(!this.chain||!PGe(this.chain))&&(console.error("Chainisnotinitializedproperly,re-initializingchain:",bg()),this.createChainWithNewModel({},!1))}storeRetrieverDocuments(e){this.retrievedDocuments=e}async createChainWithNewModel(e={},r=!0){let n=bg(),o=iu();if(n==="project"&&!o)return;let i=n==="project"?o?.projectModelKey:ZY();if(!i)throw new hme.Notice("Nomodelkeyfound"),new Error("Nomodelkeyfound");try{if(r){let a=LY(i,ae().activeModels);if(a||(console.error("Resettingdefaultmodel.Nomodelconfigurationfoundfor:",i),a=H_[0],i=a.name+"|"+a.provider),n==="project"&&!a.projectEnabled){let u=ae().activeModels.find(l=>l.enabled&&l.projectEnabled);if(u)a=u,i=u.name+"|"+u.provider,new hme.Notice(`Model ${a.name} is not available in project mode. Switching to ${u.name}.`);else throw new Error("Noproject-enabledmodelsavailable.Pleaseenableamodelforprojectmodeinsettings.")}let s={...a,...o?.modelConfigs};await this.chatModelManager.setChatModel(s)}this.setChain(n,e),J(`Setting model to ${i}`)}catch(a){fe(`createChainWithNewModel failed: ${a}`),J(`modelKey: ${i}`)}}async setChain(e,r={}){if(!this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())){console.error("setChainfailed:Nochatmodelset.");return}this.validateChainType(e);let n=this.chatModelManager.getChatModel(),o=this.memoryManager.getMemory(),i=this.promptManager.getChatPrompt();switch(e){case"llm_chain":{this.chain=c6.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),ON("llm_chain");break}case"vault_qa":{await this.initializeQAChain(r);let a=new EC({minSimilarityScore:.01,maxK:ae().maxSourceChunks,salientTerms:[]});this.retrievalChain=c6.createConversationalRetrievalChain({llm:n,retriever:a,systemMessage:q_()},this.storeRetrieverDocuments.bind(this),ae().debug),ON("vault_qa"),ae().debug&&(console.log("NewVaultQAchainwithhybridretrievercreatedforentirevault"),console.log("Setchain:","vault_qa"));break}case"copilot_plus":{await this.initializeQAChain(r),this.chain=c6.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),ON("copilot_plus");break}case"project":{await this.initializeQAChain(r),this.chain=c6.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),ON("project");break}default:this.validateChainType(e);break}}getChainRunner(){let e=bg();switch(e){case"llm_chain":return new Rle(this);case"vault_qa":return new Nle(this);case"copilot_plus":return new uK(this);case"project":return new jle(this);default:throw new Error(`Unsupported chain type: ${e}`)}}async initializeQAChain(e){e.refreshIndex&&await this.vectorStoreManager.indexVaultToVectorStore()}async runChain(e,r,n,o,i={}){let{debug:a=!1,ignoreSystemMessage:s=!1}=i;a&&console.log(`==== Step 0: Initial user message ====
`).filter(m=>m.trim());for(let m of f)p.includes(m)||await this.projectContextCache.removeWebUrl(r,m)}let c=e.contextSource?.youtubeUrls||"",d=r.contextSource?.youtubeUrls||"";if(c!==d){let f=c.split(`
`)}async processWebUrls(e,r){J(`[processWebUrls] Starting for project: ${e.name}`);let n=e.contextSource?.webUrls?.trim()||"";if(!n)return Object.keys(r.webContexts).length>0&&(J(`[processWebUrls] Project ${e.name}: Clearing all Web contexts as none are configured.`),r.webContexts={}),r;let o=n.split(`
`).filter(c=>c.trim());J(`[processWebUrls] Project ${e.name}: Found ${o.length} URLs in config.`);let i=Object.keys(r.webContexts),a=o.filter(c=>!r.webContexts[c]);a.length>0&&J(`[processWebUrls] Project ${e.name}: Fetching content for ${a.length} new/updated Web URLs.`);let s=i.filter(c=>!o.includes(c));if(s.length>0){J(`[processWebUrls] Project ${e.name}: Removing ${s.length} obsolete Web URL contexts.`);for(let c of s)delete r.webContexts[c]}let u=a.map(async c=>{let d=await this.processWebUrlsContext(c);return d&&J(`[processWebUrls] Project ${e.name}: Successfully fetched content for URL: ${c.substring(0,50)}...`),{url:c,context:d}});return(await Promise.all(u)).forEach(c=>{c&&c.context?r.webContexts[c.url]=c.context:c&&!c.context&&dg(`[processWebUrls] Project ${e.name}: Fetched empty content for Web URL: ${c.url}`)}),J(`[processWebUrls] Completed for project: ${e.name}. Total Web contexts: ${Object.keys(r.webContexts).length}`),r}async processYoutubeUrls(e,r){J(`[processYoutubeUrls] Starting for project: ${e.name}`);let n=e.contextSource?.youtubeUrls?.trim()||"";if(!n)return Object.keys(r.youtubeContexts).length>0&&(J(`[processYoutubeUrls] Project ${e.name}: Clearing all YouTube contexts as none are configured.`),r.youtubeContexts={}),r;let o=n.split(`
`).filter(c=>c.trim());J(`[processYoutubeUrls] Project ${e.name}: Found ${o.length} YouTube URLs in config.`);let i=Object.keys(r.youtubeContexts),a=o.filter(c=>!r.youtubeContexts[c]);a.length>0&&J(`[processYoutubeUrls] Project ${e.name}: Fetching transcripts for ${a.length} new/updated YouTube URLs.`);let s=i.filter(c=>!o.includes(c));if(s.length>0){J(`[processYoutubeUrls] Project ${e.name}: Removing ${s.length} obsolete YouTube URL contexts.`);for(let c of s)delete r.youtubeContexts[c]}let u=a.map(async c=>{let d=await this.processYoutubeUrlsContext(c);return d&&J(`[processYoutubeUrls] Project ${e.name}: Successfully fetched transcript for YouTube URL: ${c.substring(0,50)}...`),{url:c,context:d}});return(await Promise.all(u)).forEach(c=>{c&&c.context?r.youtubeContexts[c.url]=c.context:c&&!c.context&&dg(`[processYoutubeUrls] Project ${e.name}: Fetched empty transcript for YouTube URL: ${c.url}`)}),J(`[processYoutubeUrls] Completed for project: ${e.name}. Total YouTube contexts: ${Object.keys(r.youtubeContexts).length}`),r}async processWebUrlsContext(e){if(!e?.trim())return"";try{let r=_M.getInstance(),{urlContext:n}=await r.processUrls(e);return n||""}catch(r){return fe(`Failed to process web URLs: ${r}`),new HG.Notice(`Failed to process web URLs: ${ci(r)}`),""}}async processYoutubeUrlsContext(e){if(!e?.trim())return"";let n=e.split(`
`),this.cachedNotes}clearCache(){this.currentNotePath=null,this.cachedNotes=null,this.cachedNoteTitles=[]}};IR.MAX_RELEVANT_NOTES=3;var xme=IR;var LF=class{constructor(){this.MIN_WORD_LENGTH=4;this.STOP_WORDS=new Set(["a","ain","all","am","an","and","any","are","as","at","be","but","by","can","d","did","do","don","few","for","had","has","he","her","him","his","how","i","if","in","is","isn","it","its","ll","m","ma","me","my","no","nor","not","now","o","of","off","on","or","our","out","own","re","s","she","so","t","the","to","too","up","ve","was","we","who","why","won","y","you"])}extractWords(e){return(this.preprocessText(e).match(/\b[a-zA-Z]+(?:'[a-zA-Z]+)?\b/g)||[]).filter(o=>this.isValidWord(o))}isWordCharacter(e){return/[a-zA-Z']/.test(e)}isValidWord(e){return!(e.length<this.MIN_WORD_LENGTH||!/^[a-zA-Z]+(?:'[a-zA-Z]+)?$/.test(e)||this.STOP_WORDS.has(e.toLowerCase())||e===e.toUpperCase()&&e.length>4)}getLanguage(){return"en"}preprocessText(e){return e.replace(/```[\s\S]*?```/g,"").replace(/`[^`]+`/g,"").replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/<[^>]+>/g,"").replace(/^#+\s+/gm,"").replace(/[*_]{1,2}([^*_]+)[*_]{1,2}/g,"$1").replace(/^\s*[-*+]\s+/gm,"").replace(/^\s*\d+\.\s+/gm,"").replace(/\s+/g,"").trim()}};var WG=class{constructor(e=5e4){this.wordCount=0;this.root=this.createNode(),this.maxSize=e}createNode(){return{children:new Map,isEndOfWord:!1,wordEntry:void 0}}addWord(e,r){if(!e||e.length<4||this.wordCount>=this.maxSize&&!this.hasWord(e))return;let n=this.root;for(let o of e)n.children.has(o)||n.children.set(o,this.createNode()),n=n.children.get(o);n.isEndOfWord?n.wordEntry&&(n.wordEntry.frequency++,n.wordEntry.lastSeen=Date.now(),r&&!n.wordEntry.contexts.includes(r)&&(n.wordEntry.contexts.push(r),n.wordEntry.contexts.length>10&&(n.wordEntry.contexts=n.wordEntry.contexts.slice(-10)))):(n.isEndOfWord=!0,n.wordEntry={word:e,frequency:1,contexts:r?[r]:[],lastSeen:Date.now()},this.wordCount++)}hasWord(e){let r=this.findNode(e);return r!==null&&r.isEndOfWord}getWordEntry(e){let r=this.findNode(e);return r&&r.isEndOfWord&&r.wordEntry?r.wordEntry:null}findNode(e){let r=this.root;for(let n of e){if(!r.children.has(n))return null;r=r.children.get(n)}return r}getSuggestions(e,r=10){if(!e)return[];let n=[],o=this.generatePrefixVariants(e);for(let a of o){let s=this.findNode(a);if(s&&(this.collectWords(s,a,n,r,e),n.length>=r))break}let i=this.deduplicateSuggestions(n);return i.sort((a,s)=>s.score-a.score),i.slice(0,r)}generatePrefixVariants(e){let r=new Set;return r.add(e),r.add(e.toLowerCase()),e.length>0&&r.add(e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()),r.add(e.toUpperCase()),Array.from(r)}deduplicateSuggestions(e){let r=new Map;for(let n of e){let o=n.word,i=r.get(o);(!i||n.score>i.score)&&r.set(o,n)}return Array.from(r.values())}collectWords(e,r,n,o,i){if(!(n.length>=o)){if(e.isEndOfWord&&e.wordEntry){let a=this.calculateScore(e.wordEntry)+this.getCaseMatchBonus(r,i);n.push({word:r,score:a,source:"vault"})}for(let[a,s]of e.children)this.collectWords(s,r+a,n,o,i)}}getCaseMatchBonus(e,r){if(e.length<r.length)return 0;let n=e.substring(0,r.length);return n===r?2:this.hasSameCasePattern(n,r)?1.5:1}hasSameCasePattern(e,r){if(e.length<r.length)return!1;for(let n=0;n<r.length;n++){let o=e[n],i=r[n],a=o===o.toUpperCase(),s=i===i.toUpperCase();if(a!==s)return!1}return!0}calculateScore(e){let r=Math.log(e.frequency+1)*10,n=Math.max(0,(Date.now()-e.lastSeen)/(1e3*60*60*24)),o=Math.max(0,10-n);return r+o}getStats(){let e=0,r=0,n=(o,i=0)=>{e++,r=Math.max(r,i);for(let a of o.children.values())n(a,i+1)};return n(this.root),{wordCount:this.wordCount,nodeCount:e,maxDepth:r}}clear(){this.root=this.createNode(),this.wordCount=0}getAllWords(){let e=[],r=n=>{n.isEndOfWord&&n.wordEntry&&e.push(n.wordEntry);for(let o of n.children.values())r(o)};return r(this.root),e}addWords(e,r){for(let n of e)this.addWord(n,r)}pruneByFrequency(e=2){let r=0,n=o=>{let i=[];for(let[a,s]of o.children)n(s)&&i.push(a);for(let a of i)o.children.delete(a);return o.isEndOfWord&&o.wordEntry&&o.wordEntry.frequency
`),r=[],n="",o="",i="";for(let a of e)a.startsWith("**user**:")||a.startsWith("**ai**:")?(n&&o&&r.push({id:Rp(),sender:n===Ei?Ei:mg,message:o.trim(),isVisible:!0,timestamp:i?Zve(i):null}),n=a.startsWith("**user**:")?Ei:mg,o=a.substring(a.indexOf(":")+1).trim(),i=""):a.startsWith("[Timestamp:")?i=a.substring(11,a.length-1).trim():o+=`
Return only the translated text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1010,modelKey:"",lastUsedMs:0},{title:"Summarize",content:"Createabullet-pointsummaryof{}.Eachbulletpointshouldcaptureakeypoint.Returnonlythebullet-pointsummary.",showInContextMenu:!0,showInSlashMenu:!0,order:1020,modelKey:"",lastUsedMs:0},{title:"Simplify",content:"Simplify{}toa6th-gradereadinglevel(ages11-12).Usesimplesentences,commonwords,andclearexplanations.Maintaintheoriginalkeyconcepts.Returnonlythesimplifiedtext.",showInContextMenu:!0,showInSlashMenu:!0,order:1030,modelKey:"",lastUsedMs:0},{title:"ExplainlikeIam5",content:`Explain {} in simple terms that a 5-year-old would understand:
1. Use basic vocabulary
2. Include simple analogies
3. Break down complex concepts
Return only the simplified explanation.`,showInContextMenu:!0,showInSlashMenu:!0,order:1040,modelKey:"",lastUsedMs:0},{title:"Emojify",content:`Add relevant emojis to enhance {}. Follow these rules:
1. Insert emojis at natural breaks in the text
2. Never place two emojis next to each other
3. Keep all original text unchanged
4. Choose emojis that match the context and tone
Return only the emojified text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1050,modelKey:"",lastUsedMs:0},{title:"Makeshorter",content:`Reduce {} to half its length while preserving these elements:
1. Main ideas and key points
2. Essential details
3. Original tone and style
Return only the shortened text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1060,modelKey:"",lastUsedMs:0},{title:"Makelonger",content:`Expand {} to twice its length by:
1. Adding relevant details and examples
2. Elaborating on key points
3. Maintaining the original tone and style
Return only the expanded text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1070,modelKey:"",lastUsedMs:0},{title:"Generatetableofcontents",content:"Generateahierarchicaltableofcontentsfor{}.Useappropriateheadinglevels(H1,H2,H3,etc.).Includepagenumbersifpresent.Returnonlythetableofcontents.",showInContextMenu:!1,showInSlashMenu:!1,order:1080,modelKey:"",lastUsedMs:0},{title:"Generateglossary",content:'Create a glossary of important terms, concepts, and phrases from {}. Format each entry as "Term:Definition". Sort entries alphabetically. Return only the glossary.',showInContextMenu:!1,showInSlashMenu:!1,order:1090,modelKey:"",lastUsedMs:0},{title:"RemoveURLs",content:"RemoveallURLsfrom{}.Preserveallothercontentandformatting.URLsmaybeinvariousformats(http,https,www).ReturnonlythetextwithURLsremoved.",showInContextMenu:!1,showInSlashMenu:!1,order:1100,modelKey:"",lastUsedMs:0},{title:"Rewriteastweet",content:`Rewrite {} as a single tweet with these requirements:
1. Maximum 280 characters
2. Use concise, impactful language
3. Maintain the core message
Return only the tweet text.`,showInContextMenu:!1,showInSlashMenu:!1,order:1110,modelKey:"",lastUsedMs:0},{title:"Rewriteastweetthread",content:`Convert {} into a Twitter thread following these rules:
${u}`,s.files.push(r))}elsenewW4.Notice("No active note found.");elseif(a.startsWith("#")){letu=a.slice(1).split(",").map(d=>d.trim()),l=awaitOGe(e,u),c=[];for(letdofl){letf=awaitE$(d,e);f&&(c.push(`## ${DY(d)}
`)}s.content?(n.set(a,s.content),s.files.forEach(u=>o.add(u))):a.toLowerCase()!=="activenote"&&(a.startsWith('"')||console.warn(`No notes found for variable: ${a}`))}return{variablesMap:n,includedFiles:o}}asyncfunctiontJ(t,e,r,n){leto=ae(),i=newSet;if(!o.enableCustomPromptTemplating)returnt.includes("{}")&&!e&&n&&i.add(n),{processedPrompt:t+`
</${f}_error>`}},c=new Set;i&&a&&(await l(a,"active_note"),c.add(a.path));for(let d of o)c.has(d.path)||(await l(d),c.add(d.path));return u}async hasEmbeddedPDFs(e){return/!\[\[(.*?\.pdf)\]\]/g.test(e)}asyncaddNoteToContext(e,r,n,o,i,a){if(n.some(l=>l.path===e.path))return;lets=awaitr.read(e),u=awaitthis.hasEmbeddedPDFs(s);o&&e.path===o.path&&a(!0),i(l=>[...l,Object.assign(e,{wasAddedViaReference:!0,hasEmbeddedPDFs:u})])}processSelectedTextContexts(){lete=TN();if(!e||e.length===0)return"";letr="";for(letnofe){leto=n.startLine===n.endLine?`L${n.startLine}`:`L${n.startLine}-${n.endLine}`;r+=`
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function VDn(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function WDn(t){if(Array.isArray(t))return K2e(t)}function MXt(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),r.push.apply(r,n)}return r}function RXt(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?MXt(Object(r),!0).forEach(function(n){DXt(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):MXt(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}function DXt(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function PJ(t,e){return JDn(t)||GDn(t,e)||LXt(t,e)||KDn()}function KDn(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function LXt(t,e){if(t){if(typeof t=="string")return K2e(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return K2e(t,e)}}function K2e(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function GDn(t,e){var r=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(r!=null){var n=[],o=!0,i=!1,a,s;try{for(r=r.call(t);!(o=(a=r.next()).done)&&(n.push(a.value),!(e&&n.length===e));o=!0);}catch(u){i=!0,s=u}finally{try{!o&&r.return!=null&&r.return()}finally{if(i)throw s}}return n}}function JDn(t){if(Array.isArray(t))return t}var ZDn=typeof Phe.default=="function"?Phe.default:Phe.default.default,YDn="file-invalid-type",XDn="file-too-large",QDn="file-too-small",eLn="too-many-files";var tLn=function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",r=e.split(","),n=r.length>1?"oneof".concat(r.join(",")):r[0];return{code:YDn,message:"Filetypemustbe".concat(n)}},NXt=function(e){return{code:XDn,message:"Fileislargerthan".concat(e,"").concat(e===1?"byte":"bytes")}},jXt=function(e){return{code:QDn,message:"Fileissmallerthan".concat(e,"").concat(e===1?"byte":"bytes")}},FXt={code:eLn,message:"Toomanyfiles"};function G2e(t,e){var r=t.type==="application/x-moz-file"||ZDn(t,e);return[r,r?null:tLn(e)]}function J2e(t,e,r){if(lk(t.size))if(lk(e)&&lk(r)){if(t.size>r)return[!1,NXt(r)];if(t.size<e)return[!1,jXt(e)]}else{if(lk(e)&&t.size<e)return[!1,jXt(e)];if(lk(r)&&t.size>r)return[!1,NXt(r)]}return[!0,null]}function lk(t){return t!=null}function kXt(t){var e=t.files,r=t.accept,n=t.minSize,o=t.maxSize,i=t.multiple,a=t.maxFiles,s=t.validator;return!i&&e.length>1||i&&a>=1&&e.length>a?!1:e.every(function(u){var l=G2e(u,r),c=PJ(l,1),d=c[0],f=J2e(u,n,o),p=PJ(f,1),m=p[0],h=s?s(u):null;return d&&m&&!h})}function EJ(t){return typeof t.isPropagationStopped=="function"?t.isPropagationStopped():typeof t.cancelBubble<"u"?t.cancelBubble:!1}function TJ(t){return t.dataTransfer?Array.prototype.some.call(t.dataTransfer.types,function(e){return e==="Files"||e==="application/x-moz-file"}):!!t.target&&!!t.target.files}function Z2e(t){t.preventDefault()}function rLn(t){return t.indexOf("MSIE")!==-1||t.indexOf("Trident/")!==-1}function nLn(t){return t.indexOf("Edge/")!==-1}function $Xt(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.navigator.userAgent;return rLn(t)||nLn(t)}function y_(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];return function(n){for(var o=arguments.length,i=new Array(o>1?o-1:0),a=1;a<o;a++)i[a-1]=arguments[a];return e.some(function(s){return!EJ(n)&&s&&s.apply(void 0,[n].concat(i)),EJ(n)})}}function zXt(){return"showOpenFilePicker"in window}function BXt(t){if(lk(t)){var e=Object.entries(t).filter(function(r){var n=PJ(r,2),o=n[0],i=n[1],a=!0;return VXt(o)||(console.warn('Skipped "'.concat(o,'" because it is not a valid MIME type. Check https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types for a list of valid MIME types.')),a=!1),(!Array.isArray(i)||!i.every(WXt))&&(console.warn('Skipped "'.concat(o,'" because an invalid file extension was provided.')),a=!1),a}).reduce(function(r,n){var o=PJ(n,2),i=o[0],a=o[1];return RXt(RXt({},r),{},DXt({},i,a))},{});return[{description:"Files",accept:e}]}return t}function UXt(t){if(lk(t))return Object.entries(t).reduce(function(e,r){var n=PJ(r,2),o=n[0],i=n[1];return[].concat(IXt(e),[o],IXt(i))},[]).filter(function(e){return VXt(e)||WXt(e)}).join(",")}function qXt(t){return t instanceof DOMException&&(t.name==="AbortError"||t.code===t.ABORT_ERR)}function HXt(t){return t instanceof DOMException&&(t.name==="SecurityError"||t.code===t.SECURITY_ERR)}function VXt(t){return t==="audio/*"||t==="video/*"||t==="image/*"||t==="text/*"||t==="application/*"||/\w+\/[-+.\w]+/g.test(t)}function
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function cLn(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function dLn(t){if(Array.isArray(t))return X2e(t)}function Y2e(t,e){return mLn(t)||pLn(t,e)||JXt(t,e)||fLn()}function fLn(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function JXt(t,e){if(t){if(typeof t=="string")return X2e(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return X2e(t,e)}}function X2e(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function pLn(t,e){var r=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(r!=null){var n=[],o=!0,i=!1,a,s;try{for(r=r.call(t);!(o=(a=r.next()).done)&&(n.push(a.value),!(e&&n.length===e));o=!0);}catch(u){i=!0,s=u}finally{try{!o&&r.return!=null&&r.return()}finally{if(i)throw s}}return n}}function mLn(t){if(Array.isArray(t))return t}function KXt(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),r.push.apply(r,n)}return r}function ps(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?KXt(Object(r),!0).forEach(function(n){Q2e(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):KXt(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}function Q2e(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Ehe(t,e){if(t==null)return{};var r=hLn(t,e),n,o;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(o=0;o<i.length;o++)n=i[o],!(e.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function hLn(t,e){if(t==null)return{};var r={},n=Object.keys(t),o,i;for(i=0;i<n.length;i++)o=n[i],!(e.indexOf(o)>=0)&&(r[o]=t[o]);return r}var t4e=(0,Rn.forwardRef)(function(t,e){var r=t.children,n=Ehe(t,oLn),o=r4e(n),i=o.open,a=Ehe(o,iLn);return(0,Rn.useImperativeHandle)(e,function(){return{open:i}},[i]),Rn.default.createElement(Rn.Fragment,null,r(ps(ps({},a),{},{open:i})))});t4e.displayName="Dropzone";var ZXt={disabled:!1,getFilesFromEvent:V2e,maxSize:1/0,minSize:0,multiple:!0,maxFiles:0,preventDropOnDocument:!0,noClick:!1,noKeyboard:!1,noDrag:!1,noDragEventsBubbling:!1,validator:null,useFsAccessApi:!1,autoFocus:!1};t4e.defaultProps=ZXt;t4e.propTypes={children:Bi.default.func,accept:Bi.default.objectOf(Bi.default.arrayOf(Bi.default.string)),multiple:Bi.default.bool,preventDropOnDocument:Bi.default.bool,noClick:Bi.default.bool,noKeyboard:Bi.default.bool,noDrag:Bi.default.bool,noDragEventsBubbling:Bi.default.bool,minSize:Bi.default.number,maxSize:Bi.default.number,maxFiles:Bi.default.number,disabled:Bi.default.bool,getFilesFromEvent:Bi.default.func,onFileDialogCancel:Bi.default.func,onFileDialogOpen:Bi.default.func,useFsAccessApi:Bi.default.bool,autoFocus:Bi.default.bool,onDragEnter:Bi.default.func,onDragLeave:Bi.default.func,onDragOver:Bi.default.func,onDrop:Bi.default.func,onDropAccepted:Bi.default.func,onDropRejected:Bi.default.func,onError:Bi.default.func,validator:Bi.default.func};var e4e={isFocused:!1,isFileDialogActive:!1,isDragActive:!1,isDragAccept:!1,isDragReject:!1,acceptedFiles:[],fileRejections:[]};function r4e(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=ps(ps({},ZXt),t),r=e.accept,n=e.disabled,o=e.getFilesFromEvent,i=e.maxSize,a=e.minSize,s=e.multiple,u=e.maxFiles,l=e.onDragEnter,c=e.onDragLeave,d=e.onDragOver,f=e.onDrop,p=e.onDropAccepted,m=e.onDropRejected,h=e.onFileDialogCancel,b=e.onFileDialogOpen,g=e.useFsAccessApi,y=e.autoFocus,x=e.preventDropOnDocument,S=e.noClick,O=e.noKeyboard,E=e.noDrag,P=e.noDragEventsBubbling,A=e.onError,I=e.validator,R=(0,Rn.useMemo)(function(){return UXt(r)},[r]),N=(0,Rn.useMemo)(function(){return BXt(r)},[r]),j=(0,Rn.useMemo)(function(){return typeof b=="function"?b:GXt},[b]),$=(0,Rn.useMemo)(function(){return typeof h=="function"?h:GXt},[h]),k=(0,Rn.useRef)(null),H=(0,Rn.useRef)(null),V=(0,Rn
`))},placeholder:"Enter web URLs, one per line",className:"tw-min-h-20 tw-w-full"})),Qt.default.createElement(Bn,{label:"YouTube URLs"},Qt.default.createElement(dT,{value:u.contextSource?.youtubeUrls,onChange:h=>{letg=h.target.value.split(`
`));letPe={notes:Ne,urls:$e||[],selectedTextContexts:k};h(""),N([]),x(!0),O(K_.DEFAULT);letAe=awaiti.sendMessage(ue,Pe,d,A);m&&r(m),a.autosaveChat&&U();letot=i.getLLMMessage(Ae);ot&&awaitSge(ot,t,l,p,g,{debug:a.debug,updateLoadingMessage:O}),a.autosaveChat&&U()}catch(qt){console.error("Error sending message:",qt),newuc.Notice("Failed to send message. Please try again.")}finally{x(!1),O(K_.DEFAULT)}},U=(0,Rr.useCallback)(async()=>{if(!q){console.error("App instance is not available.");return}try{awaiti.saveChat(c)}catch(Oe){console.error("Error saving chat as note:",ci(Oe)),newuc.Notice("Failed to save chat as note. Check console for details.")}},[q,i,c]),W=(0,Rr.useCallback)(Oe=>{b&&(a.debug&&console.log(`stopping generation..., reason: ${Oe}`),b.abort(Oe),x(!1),O(K_.DEFAULT))},[b,a.debug]),Y=(0,Rr.useCallback)(asyncOe=>{if(Oe<=0){newuc.Notice("Cannot regenerate the first message.");return}let$e=u[Oe];if(!$e){newuc.Notice("Message not found.");return}x(!0);try{awaiti.regenerateMessage($e.id,p,l)?a.debug&&console.log("Message regenerated successfully"):newuc.Notice("Failed to regenerate message. Please try again."),a.autosaveChat&&U()}catch(ce){console.error("Error regenerating message:",ce),newuc.Notice("Failed to regenerate message. Please try again.")}finally{x(!1)}},[u,i,a.debug,a.autosaveChat,U,l]),se=(0,Rr.useCallback)(async(Oe,$e)=>{letce=u[Oe];if(!(!ce||ce.message===$e))try{if(!awaiti.editMessage(ce.id,$e,d,A)){newuc.Notice("Failed to edit message. Please try again.");return}if(ce.sender===Ei){letZe=Oe<u.length-1;if(awaiti.truncateAfterMessageId(ce.id),Ze){x(!0);try{letNe=i.getLLMMessage(ce.id);Ne&&awaitSge(Ne,t,l,p,g,{debug:a.debug,updateLoadingMessage:O})}catch(Ne){console.error("Error regenerating AI response:",Ne),newuc.Notice("Failed to regenerate AI response. Please try again.")}finally{x(!1)}}}a.autosaveChat&&U()}catch(qt){console.error("Error editing message:",qt),newuc.Notice("Failed to edit message. Please try again.")}},[u,i,d,A,l,t,a.debug,a.autosaveChat,U]);(0,Rr.useEffect)(((Oe,$e)=>()=>{letce=ae().debug,qt=asyncZe=>{letNe=await$e(Ze.detail.selectedText,Ze.detail.eventSubtype);try{letue=awaiti.sendMessage(Ne,{notes:[],urls:[],selectedTextContexts:[]},d,A),pe=i.getLLMMessage(ue);pe&&(x(!0),awaitSge(pe,t,l,p,g,{debug:ce,ignoreSystemMessage:!0}),x(!1))}catch(ue){console.error("Error processing adhoc prompt:",ue),x(!1)}};returns?.addEventListener(Oe,qt),()=>{s?.removeEventListener(Oe,qt)}})(qr.APPLY_ADHOC_PROMPT,async(Oe,$e)=>$e?(awaittJ($e,Oe,q.vault,q.workspace.getActiveFile())).processedPrompt:Oe),[]),(0,Rr.useEffect)(()=>{e&&e(U)},[e,U]);letde=(0,Rr.useCallback)(Oe=>{let$e=a.projectList||[];if($e.findIndex(Ne=>Ne.name===Oe.name)>=0)thrownewError(`Project "${Oe.name}" already exists, please use a different name`);letqt=[...$e,Oe];returnht("projectList",qt),iu()?.id===Oe.id?xhe().then(()=>{newuc.Notice(`${Oe.name} added and context loaded`)}).catch(Ne=>{console.error("Error loading project context:",Ne),newuc.Notice(`${Oe.name} added but context loading failed`)}):newuc.Notice(`${Oe.name} added successfully`),!0},[a.projectList]),Ue=(0,Rr.useCallback)((Oe,$e)=>{letce=a.projectList||[];if(!ce.find(ue=>ue.name===Oe.name))thrownewError(`Project "${Oe.name}" does not exist`);letZe=ce.map(ue=>ue.name===Oe.name?$e:ue);returnht("projectList",Ze),iu()?.id===Oe.id?(PN($e),xhe().then(()=>{newuc.Notice(`${Oe.name} updated and context reloaded`)}).catch(ue=>{console.error("Error reloading project context:",ue),newuc.Notice(`${Oe.name} updated but context reload failed`)})):newuc.Notice(`${Oe.name} updated successfully`),!0},[a.projectList]),Ke=(0,Rr.useCallback)(Oe=>{h($e=>`${$e}${Oe} `)},[]),at=(0,Rr.useCallback)(Oe=>{yJe(Oe)},[]),hr=(0,Rr.useCallback)(asyncOe=>{let$e=u[Oe];if(!$e){newuc.Notice("Message not found.");return}try{awaiti.deleteMessage($e.id)||newuc.Notice("Failed to delete message. Please try again.")}catch(ce){console.error("Error deleting message:",ce),newuc.Notice("Failed to delete message. Please try again.")}},[u,i]),Nn=(0,Rr.useCallback)
${a.content}`}):e.push(a)}await Fd.getInstance().updateCommands([...n.map(a=>({...a,showInSlashMenu:!0})),...e]);let i=`We have upgraded your commands to the new format. They are now also stored as notes in ${DR()}.`;r.length>0&&(await DUn(r),i+=`
We found ${r.length} unsupported commands. They are saved in ${DR()}/unsupported. To fix them, please resolve the errors and move the note file out of the unsupported folder.`),ht("inlineEditCommands",[]),new $d(app,()=>{},i,"\u{1F680}NewCopilotCustomCommands","OK","").open()}async function PHe(){let t=Mm(),e=QGt.filter(n=>!t.some(o=>o.title===n.title)),r=[...t,...e];Fd.getInstance().updateCommands(r)}async function Air(){if(ae().suggestedDefaultCommands)return;Mm().length===0&&(new $d(app,()=>{PHe()},"WouldyouliketoaddCopilotrecommendedcommandsinyourcustompromptsfolder?Thesecommandswillbeavailablethroughtheright-clickcontextmenuandslashcommandsinchat.","WelcometoCopilot","Confirm","Skip").open(),ht("suggestedDefaultCommands",!0))}var LUn=({command:t,commands:e,onUpdate:r,onRemove:n,onCopy:o})=>{let{attributes:i,listeners:a,setNodeRef:s,transform:u,transition:l,isDragging:c}=_7({id:t.title}),d={transform:S_.Transform.toString(u),transition:l},f=()=>{n(t)};return Dt.default.createElement(w1,{ref:s,style:d,className:ve("tw-transition-colors",c&&"tw-relativetw-z-[100]tw-cursor-grabbingtw-shadow-lgtw-backdrop-blur-smtw-border-accent/50")},Dt.default.createElement(Bf,{className:"tw-w-10"},Dt.default.createElement("div",{...i,...a,className:"tw-flextw-cursor-grabtw-items-centertw-justify-center"},Dt.default.createElement(nv,{className:"tw-size-4"}))),Dt.default.createElement(Bf,null,t.title),Dt.default.createElement(Bf,{className:"tw-text-center"},Dt.default.createElement(Ld,{checked:t.showInContextMenu,onCheckedChange:p=>{r({...t,showInContextMenu:p===!0},t.title)},className:"tw-mx-auto"})),Dt.default.createElement(Bf,{className:"tw-text-center"},Dt.default.createElement(Ld,{checked:t.showInSlashMenu,onCheckedChange:p=>r({...t,showInSlashMenu:p===!0},t.title),className:"tw-mx-auto"})),Dt.default.createElement(Bf,{className:"tw-text-center"},Dt.default.createElement("div",{className:"tw-flextw-justify-centertw-space-x-1"},Dt.default.createElement(be,{variant:"ghost",size:"icon",onClick:()=>{new HF(app,e,t,async m=>{await r(m,t.title)}).open()}},Dt.default.createElement(iv,{className:"tw-size-4"})),Dt.default.createElement(be,{variant:"ghost",size:"icon",onClick:()=>o(t),title:"Copycommand"},Dt.default.createElement(th,{className:"tw-size-4"})),Dt.default.createElement(be,{variant:"ghost",size:"icon",onClick:()=>{new $d(app,f,`Are you sure you want to delete the command "${t.title}"? This will permanently remove the command file and cannot be undone.`,"DeleteCommand","Delete","Cancel").open()}},Dt.default.createElement(oh,{className:"tw-size-4"})))))},Iir=()=>{let t=eJt(),e=(0,Dt.useMemo)(()=>eJ([...t]),[t]),r=Hn(),n=jge(q3(C1,{activationConstraint:{distance:8}}),q3(S1,{coordinateGetter:Bge})),o=async(l,c)=>{await Fd.getInstance().updateCommand(l,c)},i=async l=>{await Fd.getInstance().createCommand(l)},a=async l=>{try{await Fd.getInstance().deleteCommand(l),new Vge.Notice(`Command "${l.title}" deleted successfully!`)}catch(c){throw console.error("Failedtodeletecommand:",c),new Vge.Notice("Failedtodeletecommand.Pleasetryagain."),c}},s=async l=>{try{let c=nJt(l.title,e),d={...l,title:c};await Fd.getInstance().createCommand(d,{autoOrder:!1})}catch(c){console.error("Failedtocopycommand:",c),new Vge.Notice("Failedtocopycommand.Pleasetryagain.")}},u=async l=>{let{active:c,over:d}=l;if(!d||c.id===d.id)return;let f=e.findIndex(b=>b.title===c.id),p=e.findIndex(b=>b.title===d.id);if(f===-1||p===-1)return;let m=[...e],[h]=m.splice(f,1);m.splice(p,0,h),await Fd.getInstance().reorderCommands(m)};return Dt.default.createElement("div",{className:"tw-space-y-4"},Dt.default.createElement("section",null,Dt.default.createElement("div",{className:"tw-mb-4tw-flextw-flex-coltw-gap-2"},Dt.default.createElement("div",{className:"tw-text-xltw-font-bold"},"CustomCommands"),Dt.default.createElement("div",{className:"tw-text-smtw-text-muted"},"Customcommandsarepresetpromptsthatyoucantriggerintheeditorbyright-clickingandselectingthemfromthecontextmenuorbyusinga",
with CORS Error: `+ci(Z);throw new Error(D)}}let H=await k.json(),V=Dir(I,H);l(Q=>({...Q,[I]:V})),d(null)}catch(N){console.error(`Error fetching models for ${I}:`,N),p(I),d(null),new P_.Notice(`Failed to load models for ${op(I)}: ${ci(N)}`,5e3)}},A=async()=>{if(!m){new P_.Notice("Pleaseselectamodelfirst");return}g(!0);try{let I=x(m.provider),R={name:m.name,provider:m.provider,apiKey:I,enabled:!0};if(await Ec.instance.getCurrentChainManager().chatModelManager.ping(R),e.activeModels.find(j=>j.name===m.name&&j.provider===m.provider))new P_.Notice(`Model ${m.name} verified successfully! It already exists in your models list.`);else{let j=[...e.activeModels,R];ht("activeModels",j),new P_.Notice(`Model ${m.name} verified successfully and added to your models list!`)}}catch(I){console.error("Modelverificationfailed:",I),new P_.Notice("Modelverificationfailed:"+ci(I),1e4)}finally{g(!1)}};return Yt.default.createElement("div",{className:"tw-max-h-[600px]tw-overflow-y-autotw-p-4sm:tw-max-w-[500px]"},Yt.default.createElement("div",{className:"tw-mb-4"},Yt.default.createElement("h2",{className:"tw-text-xltw-font-bold"},"AIProviderSettings"),Yt.default.createElement("p",{className:"tw-text-smtw-text-muted"},"ConfigureyourAIprovidersbyaddingtheirAPIkeys.")),Yt.default.createElement("div",{className:"tw-space-y-6tw-py-4"},Yt.default.createElement("div",{className:"tw-space-y-4"},S.map(I=>Yt.default.createElement(Yt.default.Fragment,{key:I.provider},Yt.default.createElement("div",{className:"tw-flextw-flex-coltw-gap-2"},Yt.default.createElement("div",{className:"tw-flextw-items-endtw-gap-2tw-font-medium"},Yt.default.createElement("div",{className:"tw-truncate"},op(I.provider))),Yt.default.createElement("div",{className:"tw-flextw-flex-rowtw-items-centertw-gap-2"},Yt.default.createElement("div",{className:"tw-flex-1"},Yt.default.createElement(fO,{className:"tw-max-w-full",value:I.apiKey,onChange:R=>O(I.provider,R),disabled:r.has(I.provider)})),Yt.default.createElement("div",{className:"tw-w-[72px]"},I.isVerified?Yt.default.createElement("span",{className:"tw-flextw-h-9tw-items-centertw-justify-centertw-text-smtw-text-success"},"Verified"):Yt.default.createElement(be,{onClick:()=>E(I.provider,I.apiKey),disabled:!I.apiKey||r.size>0,variant:"secondary",size:"sm",className:"tw-w-fulltw-whitespace-nowrap"},r.has(I.provider)?Yt.default.createElement(yc,{className:"tw-mr-2tw-size-4tw-animate-spin"}):"Verify")),Yt.default.createElement("div",{className:""},Yt.default.createElement(be,{onClick:()=>{let R=a===I.provider?null:I.provider;s(R),R&&I.apiKey&&u[I.provider]===void 0&&c!==I.provider&&f!==I.provider&&P(I.provider,I.apiKey)},disabled:!I.apiKey||r.size>0,variant:"secondary",size:"sm",className:"tw-flextw-w-fulltw-items-centertw-justify-centertw-gap-1tw-whitespace-nowraptw-p-0.5"},"AddModel",a===I.provider?Yt.default.createElement(fb,{className:"tw-ml-1tw-size-4"}):Yt.default.createElement(Xi,{className:"tw-ml-1tw-size-4"})))),Yt.default.createElement("div",null,V_(I.provider).keyManagementURL&&Yt.default.createElement("a",{href:V_(I.provider).keyManagementURL,target:"_blank",rel:"noopenernoreferrer",className:"tw-text-[10px]tw-text-accenthover:tw-text-accent-hoversm:tw-text-xs"},"Get",op(I.provider),"Key"))),Yt.default.createElement(CT,{open:a===I.provider,className:"tw-mt-2"},Yt.default.createElement(OT,{className:"tw-rounded-mdtw-p-3"},Yt.default.createElement("div",{className:"tw-flextw-flex-coltw-gap-2"},Yt.default.createElement(Bn,{label:"Model",description:"AddthecurrentlyselectedmodeltomodelList.Afteradding,pleasechecktheModelTab."},Yt.default.createElement("div",null,Yt.default.createElement("div",{className:"tw-flextw-items-centertw-gap-2"},Yt.default.createElement("div",{className:"tw-flex-1"},Yt.default.createElement(cge,{options:u[I.provider]?.sort((R,N)=>R.name.localeCompare(N.name)).map(R=>({label:R.name,value:R.id}))||[],onChange:R=>{let N=R.target.value,j=u[I.provider]?.find($=>$.id===N);j&&h({id:j.id,name:j.name,provider:I.provider})},onClick:()=>{I.
${e}`}};Ur();varoye=class{constructor(e,r,n,o){this.messageRepo=e;this.chainManager=r;this.fileParserManager=n;this.plugin=o;this.projectMessageRepos=newMap;this.defaultProjectKey="defaultProjectKey";this.lastKnownProjectId=null;this.contextManager=nye.getInstance(),this.projectMessageRepos.set(this.defaultProjectKey,e),this.persistenceManager=newT7(o.app,e)}getCurrentMessageRepo(){lete=this.plugin.projectManager.getCurrentProjectId(),r=e??this.defaultProjectKey;if(this.lastKnownProjectId!==e&&(J(`[ChatManager] Project changed from ${this.lastKnownProjectId} to ${e}`),this.lastKnownProjectId=e),!this.projectMessageRepos.has(r)){J(`[ChatManager] Creating new message repository for project: ${r}`);leto=newK3;this.projectMessageRepos.set(r,o)}letn=this.projectMessageRepos.get(r);returnthis.persistenceManager=newT7(this.plugin.app,n),n}asyncsendMessage(e,r,n,o=!1){try{J(`[ChatManager] Sending message: "${e}"`);leti=this.plugin.app.workspace.getActiveFile(),a={...r};if(o&&i){letd=r.notes||[],f=d.some(p=>p.path===i.path);a.notes=f?d:[...d,i]}lets=this.getCurrentMessageRepo(),u=s.addMessage(e,e,Ei,a),l=s.getMessage(u);if(!l)thrownewError(`Failed to retrieve message ${u}`);letc=awaitthis.contextManager.processMessageContext(l,this.fileParserManager,this.plugin.app.vault,n,o,i);returns.updateProcessedText(u,c),J(`[ChatManager] Successfully sent message ${u}`),u}catch(i){throwJ("[ChatManager] Error sending message:",i),i}}asynceditMessage(e,r,n,o=!1){try{J(`[ChatManager] Editing message ${e}: "${r}"`);leti=this.getCurrentMessageRepo();if(!i.editMessage(e,r))return!1;lets=this.plugin.app.workspace.getActiveFile();returnawaitthis.contextManager.reprocessMessageContext(e,i,this.fileParserManager,this.plugin.app.vault,n,o,s),awaitthis.updateChainMemory(),J(`[ChatManager] Successfully edited message ${e}`),!0}catch(i){returnJ(`[ChatManager] Error editing message ${e}:`,i),!1}}asyncregenerateMessage(e,r,n){try{J(`[ChatManager] Regenerating message ${e}`);leto=this.getCurrentMessageRepo();if(!o.getMessage(e))returnJ(`[ChatManager] Message not found: ${e}`),!1;leta=o.getDisplayMessages(),s=a.findIndex(d=>d.id===e);if(s<=0)returnJ("[ChatManager] Cannot regenerate first message or no user message found"),!1;letu=a[s-1];if(u.sender!==Ei)returnJ("[ChatManager] Previous message is not from user"),!1;if(o.truncateAfter(s-1),awaitthis.updateChainMemory(),!u.id)returnJ("[ChatManager] User message has no ID for regeneration"),!1;letl=o.getLLMMessage(u.id);if(!l)returnJ("[ChatManager] LLM message not found for regeneration"),!1;letc=newAbortController;returnawaitthis.chainManager.runChain(l,c,r,n,{debug:ae().debug}),J(`[ChatManager] Successfully regenerated message ${e}`),!0}catch(o){returnJ(`[ChatManager] Error regenerating message ${e}:`,o),!1}}asyncdeleteMessage(e){try{returnJ(`[ChatManager] Deleting message ${e}`),this.getCurrentMessageRepo().deleteMessage(e)?(awaitthis.updateChainMemory(),J(`[ChatManager] Successfully deleted message ${e}`),!0):!1}catch(r){returnJ(`[ChatManager] Error deleting message ${e}:`,r),!1}}addDisplayMessage(e,r,n){returnthis.getCurrentMessageRepo().addDisplayOnlyMessage(e,r,n)}addFullMessage(e){returnthis.getCurrentMessageRepo().addFullMessage(e)}clearMessages(){this.getCurrentMessageRepo().clear(),this.chainManager.memoryManager.clearChatMemory(),J("[ChatManager] Cleared all messages")}asynctruncateAfterMessageId(e){this.getCurrentMessageRepo().truncateAfterMessageId(e),awaitthis.updateChainMemory(),J(`[ChatManager] Truncated messages after ${e}`)}getDisplayMessages(){returnthis.getCurrentMessageRepo().getDisplayMessages()}getLLMMessages(){returnthis.getCurrentMessageRepo().getLLMMessages()}getMessage(e){returnthis.getCurrentMessageRepo().getMessage(e)}getLLMMessage(e){returnthis.getCurrentMessageRepo().getLLMMessage(e)}asyncupdateChainMemory(){try{letr=this.getCurrentMessageRepo().getLLMMessages();awaitOGt(r,this.chainManager.memoryManager),J(`[ChatManager] Updated chain memory with ${r.length} messages`)}catch(e){J("[ChatManager]Errorupdatingchainmemory:
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*)
crypto-js/ripemd160.js:
(** @preserve
(c) 2012 by Cédric Mesnil. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*)
crypto-js/mode-ctr-gladman.js:
(** @preserve
* Counter block mode compatible with Dr Brian Gladman fileenc.c