varewr=Object.create;vare6=Object.defineProperty;vartwr=Object.getOwnPropertyDescriptor;varrwr=Object.getOwnPropertyNames;varnwr=Object.getPrototypeOf,owr=Object.prototype.hasOwnProperty;varwGe=t=>{throwTypeError(t)};variwr=(t,e,r)=>eint?e6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;varb=(t,e)=>()=>(t&&(e=t(t=0)),e);varx=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),os=(t,e)=>{for(varrine)e6(t,r,{get:e[r],enumerable:!0})},xGe=(t,e,r,n)=>{if(e&&typeofe=="object"||typeofe=="function")for(letoofrwr(e))!owr.call(t,o)&&o!==r&&e6(t,o,{get:()=>e[o],enumerable:!(n=twr(e,o))||n.enumerable});returnt};varj=(t,e,r)=>(r=t!=null?ewr(nwr(t)):{},xGe(e||!t||!t.__esModule?e6(r,"default",{value:t,enumerable:!0}):r,t)),Nc=t=>xGe(e6({},"__esModule",{value:!0}),t);varbd=(t,e,r)=>iwr(t,typeofe!="symbol"?e+"":e,r),awr=(t,e,r)=>e.has(t)||wGe("Cannot "+r);varbwe=(t,e,r)=>e.has(t)?wGe("Cannot add the same private member more than once"):einstanceofWeakSet?e.add(t):e.set(t,r);varSGe=(t,e,r)=>(awr(t,e,"access private method"),r);function_we(){if(!OX&&(OX=typeofcrypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!OX))thrownewError("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");returnOX(swr)}varOX,swr,CGe=b(()=>{swr=newUint8Array(16)});functionOGe(t,e=0){return_d[t[e+0]]+_d[t[e+1]]+_d[t[e+2]]+_d[t[e+3]]+"-"+_d[t[e+4]]+_d[t[e+5]]+"-"+_d[t[e+6]]+_d[t[e+7]]+"-"+_d[t[e+8]]+_d[t[e+9]]+"-"+_d[t[e+10]]+_d[t[e+11]]+_d[t[e+12]]+_d[t[e+13]]+_d[t[e+14]]+_d[t[e+15]]}var_d,EGe=b(()=>{_d=[];for(lett=0;t<256;++t)_d.push((t+256).toString(16).slice(1))});varuwr,vwe,PGe=b(()=>{uwr=typeofcrypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),vwe={randomUUID:uwr}});functionlwr(t,e,r){if(vwe.randomUUID&&!e&&!t)returnvwe.randomUUID();t=t||{};letn=t.random||(t.rng||_we)();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}returnOGe(n)}vardm,TGe=b(()=>{PGe();CGe();EGe();dm=lwr});varzN=b(()=>{TGe()});varGn,wwe,yt,gv,t6=b(()=>{(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})(Gn||(Gn={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(wwe||(wwe={}));yt=Gn.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),gv=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}}});varUe,cwr,fm,EX=b(()=>{t6();Ue=Gn.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 zX(t){return typeof t=="function"&&"langsmith:traceable"in t}var jwe,Nwe,L0r,Dwe,F0r,KJn,sJe=b(()=>{jwe=class{getStore(){}run(e,r){return r()}},Nwe=Symbol.for("ls:tracing_async_local_storage"),L0r=new jwe,Dwe=class{getInstance(){return globalThis[Nwe]??L0r}initializeGlobalInstance(e){globalThis[Nwe]===void 0&&(globalThis[Nwe]=e)}},F0r=new Dwe;KJn=Symbol.for("langsmith:traceable:root")});var Lwe=b(()=>{sJe()});function qX(t,e){return k0r.call(t,e)}function HX(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)qX(t,r)&&e.push(r);return e}function Sf(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function VX(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 _v(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function a6(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function UX(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let r=0,n=t.length;r<n;r++)if(UX(t[r]))return!0}else if(typeof t=="object"){let r=HX(t),n=r.length;for(var e=0;e<n;e++)if(UX(t[r[e]]))return!0}}return!1}function uJe(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 k0r,aj,s6=b(()=>{k0r=Object.prototype.hasOwnProperty;aj=class extends Error{constructor(e,r,n,o,i){super(uJe(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=uJe(e,{name:r,index:n,operation:o,tree:i})}}});var Fwe={};os(Fwe,{JsonPatchError:()=>Rs,_areEquals:()=>u6,applyOperation:()=>sj,applyPatch:()=>LA,applyReducer:()=>z0r,deepClone:()=>$0r,getValueByPointer:()=>WX,validate:()=>lJe,validator:()=>KX});function WX(t,e){if(e=="")return t;var r={op:"_get",path:e};return sj(t,r),r.value}function sj(t,e,r=!1,n=!0,o=!0,i=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):KX(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=WX(t,e.from),e.op==="move"&&(a.removed=t),a;if(e.op==="test"){if(a.test=u6(t,e.value),a.test===!1)throw new Rs("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 Rs("Operation`op`propertyisnotoneofoperationsdefinedinRFC-6902","OPERATION_OP_INVALID",i,e,t);return a}}else{n||(t=Sf(t));let s=(e.path||"").split("/"),u=t,l=1,c=s.length,d,f,p;for(typeof r=="function"?p=r:p=KX;;){if(f=s[l],f&&f.indexOf("~")!=-1&&(f=a6(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&&!VX(f))throw new Rs("Expectedanunsignedbase-10integervalue,makingthenewreferencedvaluethearrayelementwiththezero-basedindex","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,e,t);VX(f)&&(f=~~f)}if(l>=c){if(r&&e.op==="add"&&f>u.length)throw new Rs("ThespecifiedindexMUSTNOTbegreaterthanthenumberofelementsinthearray","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,t);let h=B0r[e.op].call(e,u,f,t);if(h.test===!1)throw new Rs("Testoperationfailed","TEST_OPERATION_FAILED",i,e,t);return h}}else if(l>=c){let h=hB[e.op].call(e,u,f,t);if(h.test===!1)throw new Rs("Testoperationfailed","TEST_OPERATION_FAILED",i,e,t);return h}if(u=u[f],r&&l<c&&(!u||typeof u!="object"))throw new Rs("Cannotperformoperationatthedesiredpath","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}function LA(t,e,r,n=!0,o=!0){if(r&&!Array.isArray(e))throw new Rs("Patchsequencemustbeanarray","SEQUENCE_NOT_AN_ARRAY");n||(t=Sf(t));let i=new Array(e.length);for(let a=0,s=e.length;a<s;a++)i[a]=sj(t,e[a],r,!0,o,a),t=i[a].newDocument;return i.newDocument=t,i}function z0r(t,e,r){let n=sj(t,e);if(n.test===!1)throw new Rs("Testoperationfailed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function KX(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new Rs("Operationisnotanobject","OPERATION_NOT_AN_OBJECT",e,t,r);if(hB[t.op]){if(typeof t.path!="string")throw new Rs("Operation`path`propertyisnotastring","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new Rs('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 Rs("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}`:""}`),wQ("[Unserializable]");nc("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
Context: ${e}`:""}`),typeof o>"u"&&(o=lOr()),N0e(t,"",0,[],void 0,0,o);let a;try{bB.length===0?a=JSON.stringify(t,r,n):a=JSON.stringify(t,dOr(r),n)}catch{return wQ("[unabletoserialize,circularreferenceistoocomplextoanalyze]")}finally{for(;xQ.length!==0;){let s=xQ.pop();s.length===4?Object.defineProperty(s[0],s[1],s[3]):s[0][s[1]]=s[2]}}return wQ(a)}}function R0e(t,e,r,n){var o=Object.getOwnPropertyDescriptor(n,r);o.get!==void 0?o.configurable?(Object.defineProperty(n,r,{value:t}),xQ.push([n,r,e,o])):bB.push([e,r,t]):(n[r]=t,xQ.push([n,r,e]))}function N0e(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){R0e(sOr,t,e,o);return}if(typeof a.depthLimit<"u"&&i>a.depthLimit){R0e(nYe,t,e,o);return}if(typeof a.edgesLimit<"u"&&r+1>a.edgesLimit){R0e(nYe,t,e,o);return}if(n.push(t),Array.isArray(t))for(s=0;s<t.length;s++)N0e(t[s],s,s,n,t,i,a);else{t=oYe(t);var u=Object.keys(t);for(s=0;s<u.length;s++){var l=u[s];N0e(t[l],l,s,n,t,i,a)}}n.pop()}}function dOr(t){return t=typeof t<"u"?t:function(e,r){return r},function(e,r){if(bB.length>0)for(var n=0;n<bB.length;n++){var o=bB[n];if(o[1]===e&&o[0]===r){r=o[2],bB.splice(n,1);break}}return t.call(this,e,r)}}var nYe,sOr,xQ,bB,uOr,iYe=b(()=>{cE();nYe="[...]",sOr={result:"[Circular]"},xQ=[],bB=[],uOr=new TextEncoder});function aYe(t){let e=QX(),r=HJe(),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 mOr(t){let e=[];for await(let r of t)e.push(r);return e}function j0e(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}function sYe(t){return typeof t=="number"?Number(t.toFixed(4)):t}function lYe(t){return"dataset_id"in t||"dataset_name"in t}var fOr,pOr,hOr,D0e,gOr,yOr,uYe,uj,Vwe=b(()=>{ij();GJe();r0e();i7e();a7e();cE();XX();s7e();d0e();eYe();M0e();ZX();iYe();fOr=t=>{let e=t?.toString()??nc("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},pOr=t=>{let r=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return r==="localhost"||r==="127.0.0.1"||r==="::1"};hOr=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};D0e=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=gm(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())]}},gOr=20971520,yOr=2500,uYe="https://api.smith.langchain.com",uj=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=tQ(),r=WJe();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=aYe(i);r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey);let s=await this.caller.call(Jt(this.debug),`${r?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:n,body:gm(a,`Creatingrunwithid:${a.id}`),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await fn(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(gm(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(Jt(this.debug),`${r?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:n,body:e,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await fn(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,h)=>(h.id&&(p[h.id]=h),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:h,outputs:m,events:g,attachments:y,..._}=p,w={inputs:h,outputs:m,events:g},S=gm(_,`Serializingformultipartingestionofrunwithid:${_.id}`);c.push({name:`${d}.${_.id}`,payload:new Blob([S],{type:`application/json;length=${S.length}`})});for(let[C,E]of Object.entries(
`),i.close()}})}async_sendMultipartRequest(e,r,n){leto="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),i=UJe(),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(Jt(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)!==uYe&&(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())),awaitfn(l,"ingest multipart runs",!0)}catch(l){console.warn(`${l.message.trim()}
Context: ${r}`)}}asyncupdateRun(e,r,n){an(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(Jt(this.debug),`${n?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:i,body:gm(r,`Serializing payload to update run with id: ${e}`),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});awaitfn(a,"update run",!0)}asyncreadRun(e,{loadChildRuns:r}={loadChildRuns:!1}){an(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:nc("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=awaitmOr(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:h,traceFilter:m,treeFilter:g,limit:y,select:_,order:w}=e,S=[];if(r&&(S=Array.isArray(r)?r:[r]),n){letT=Array.isArray(n)?n:[n],I=awaitPromise.all(T.map(N=>this.readProject({projectName:N}).then(M=>M.id)));S.push(...I)}letC=["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:h,trace_filter:m,tree_filter:g,execution_order:u,parent_run:o,start_time:s?s.toISOString():null,error:d,id:f,limit:y,trace:i,select:_||C,is_root:l,order:w},P=0;forawait(letTofthis._getCursorPaginatedList("/runs/query",E))if(y){if(P>=y)break;if(T.length+P>y){yield*T.slice(0,y-P);break}P+=T.length,yield*T}elseyield*T}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",h=`${this.apiUrl}${p}`;for(;;){letm={...d,offset:f},g=Object.fromEntries(Object.entries(m).filter(([C,E])=>E!==void0)),y=awaitthis.caller.call(Jt(),h,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(g),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(Jt(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 fn(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(Jt(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 fn(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)an(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(Jt(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)an(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,an(n);let o=await this.caller.call(Jt(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;an(i);let a=await this.caller.call(Jt(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 fn(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;an(a);let s=await this.caller.call(Jt(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 fn(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)an(o),n+=`/${o}`;else throw new Error("Must provide datasetName or datasetId");let i=await this.caller.call(Jt(this.debug),this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await fn(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),an(o);let i={tag:n},a=await this.caller.call(Jt(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 fn(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),an(r);let a=await this.caller.call(Jt(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 fn(a,"fetch similar examples"),(await a.json()).examples}async createExample(e,r,n){if(lYe(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;lYe(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]??Ms())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];let _=e,w=_[0].dataset_id,S=_[0].dataset_name;if(w===void 0&&S===void 0)throw new Error("Must provide either datasetName or datasetId");if(w!==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]=pE(e),a=awaitthis.caller.call(Jt(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});returnawaitfn(a,`${r?"like":"unlike"} prompt`),awaita.json()}async_getPromptUrl(e){let[r,n,o]=pE(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]=pE(e),i=awaitthis.caller.call(Jt(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;awaitfn(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]=pE(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(Jt(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});awaitfn(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]=pE(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(Jt(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});awaitfn(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=gm(l,`Serializing body for example with id: ${u}`),d=newBlob([c],{type:"application/json"});if(n.append(u,d),s.inputs){letf=gm(s.inputs,`Serializing inputs for example with id: ${u}`),p=newBlob([f],{type:"application/json"});n.append(`${u}.inputs`,p)}if(s.outputs){letf=gm(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)){leth,m;Array.isArray(p)?[h,m]=p:(h=p.mimeType,m=p.data);letg=newBlob([m],{type:`${h}; length=${m.byteLength}`});n.append(`${u}.attachment.${f}`,g)}if(s.attachments_operations){letf=gm(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(Jt(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??Ms()).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=gm(u,`Serializing body for uploaded example with id: ${s}`),c=newBlob([l],{type:"application/json"});if(n.append(s,c),a.inputs){letd=gm(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=gm(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,h;Array.isArray(f)?[p,h]=f:(p=f.mimeType,h=f.data);letm=newBlob([h],{type:`${p}; length=${h.byteLength}`});n.append(`${s}.attachment.${d}`,m)}}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}}varK0e=b(()=>{});functionIb(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")}function$Ye(t){returnIb(t)&&t.source_type==="url"&&"url"int&&typeoft.url=="string"}functionBYe(t){returnIb(t)&&t.source_type==="base64"&&"data"int&&typeoft.data=="string"}functionzYe(t){if(Ib(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.")}functionG0e(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}}functionwB({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}}}functionx6(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.`)}varJ0e=b(()=>{});functionUg(t,e){returntypeoft=="string"?t===""?e:typeofe=="string"?t+e:Array.isArray(e)&&e.some(r=>Ib(r))?[{type:"text",source_type:"text",text:t},...e]:[{type:"text",text:t},...e]:Array.isArray(e)?S6(t,e)??[...t,...e]:e===""?t:Array.isArray(t)&&t.some(r=>Ib(r))?[...t,{type:"file",source_type:"text",text:e}]:[...t,{type:"text",text:e}]}functionUYe(t,e){returnt==="error"||e==="error"?"error":"success"}function$Or(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)}functionZs(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]=Zs(r[n],o);elseif(Array.isArray(r[n]))r[n]=S6(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}functionS6(t,e){if(!(t===void0&&e===void0)){if(t===void0||e===void0)retur
`}}letc={};for(letpofe){leth=p.source.split(":"),m=p.target.split(":"),g=h.filter((y,_)=>y===m[_]).join(":");c[g]||(c[g]=[]),c[g].push(p)}letd=newSet;functionf(p,h){letm=p.length===1&&p[0].source===p[0].target;if(h&&!m){letg=h.split(":").pop();if(d.has(g))thrownewError(`Found duplicate subgraph '${g}' -- 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(g),l+=` subgraph ${g}
`)}f(c[""]??[],"");for(letpinc)!p.includes(":")&&p!==""&&f(c[p],p);returna&&(l+=XOr(i??{})),l}asyncfunctionmXe(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()}varYOr,hXe=b(()=>{YOr=["*","_","`"]});functionTB(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}functionAB(t){returnt&&Object.assign(pxe,t),pxe}varaQn,sQn,qA,pxe,j6=b(()=>{aQn=Object.freeze({status:"aborted"});sQn=Symbol("zod_brand"),qA=classextendsError{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},pxe={}});functionmxe(t){lete=Object.values(t).filter(n=>typeofn=="number");returnObject.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}functionyXe(t,e){returntypeofe=="bigint"?e.toString():e}functionbXe(t){return{getvalue(){{letr=t();returnObject.defineProperty(this,"value",{value:r}),r}thrownewError("cached value already set")}}}functionIB(t,e,r){letn=newt._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function_Xe(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}functionzQ(t,e=0){for(letr=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}functionBQ(t){returntypeoft=="string"?t:t?.message}functionMB(t,e,r){letn={...t,path:t.path??[]};if(!t.message){leto=BQ(t.inst?._zod.def?.error?.(t))??BQ(e?.error?.(t))??BQ(r.customError?.(t))??BQ(r.localeError?.(t))??"Invalid input";n.message=o}returndeleten.inst,deleten.continue,e?.reportInput||deleten.input,n}varhxe,QOr,uQn,HA=b(()=>{hxe=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{},QOr=bXe(()=>{if(typeofnavigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{lett=Function;returnnewt(""),!0}catch{return!1}});uQn={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]}});varvXe,wXe,D6,gxe=b(()=>{j6();HA();vXe=(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,yXe,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},wXe=TB("$ZodError",vXe),D6=TB("$ZodError",vXe,{Parent:Error})});vartEr,UQ,rEr,xXe,nEr,SXe,oEr,CXe,yxe=b(()=>{j6();gxe();HA();tEr=t=>(e,r,n,o)=>{leti=n?Object.assign(n,{async:!1}):{async:!1},a=e._zod.run({value:r,issues:[]},i);if(ainstanceofPromise)thrownewqA;if(a.issues.length){lets=new(o?.Err??t)(a.issues.map(u=>MB(u,i,AB())));throwhxe(s,o?.callee),s}returna.value},UQ=tEr(D6),rEr=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=>MB(u,i,AB())));throwhxe(s,o?.callee),s}returna.value},xXe=rEr(D6),nEr=t=>(e,r,n)=>{leto=n?{...n,async:!1}:{async:!1},i=e._zod.run({value:r,issues:[]},o);if(iinstanceofPromise)thrownewqA;returni.issues.length?{success:!1,error:new(t??wXe)(i.issues.map(a=>MB(a,o,AB())))}:{success:!0,data:i.value}},SXe=nEr(D6),oEr=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,h={...p};if(f.ref===null)return;letm=f.ref;if(f.ref=null,m){s(m,d);letg=this.seen.get(m).schema;g.$ref&&d.target==="draft-7"?(p.allOf=p.allOf??[],p.allOf.push(g)):(Object.assign(p,g),Object.assign(p,h))}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.")}}}});varLXe=b(()=>{});varHQ=b(()=>{j6();yxe();gxe();IXe();EXe();bxe();HA();OXe();MXe();_xe();PXe();jXe();NXe();DXe();LXe()});varkXe,FXe,$Xe,VQ=b(()=>{kXe=Symbol("Let zodToJsonSchema decide on which parser to use"),FXe={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"},$Xe=t=>typeoft=="string"?{...FXe,name:t}:{...FXe,...t}});varBXe,vxe=b(()=>{VQ();BXe=t=>{lete=$Xe(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}]))}}});functionwxe(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}functionfo(t,e,r,n,o){t[e]=r,wxe(t,e,n,o)}varVA=b(()=>{});varxd=b(()=>{i6();i6()});functionzXe(){return{}}varxxe=b(()=>{});functionUXe(t,e){letr={type:"array"};returnt.type?._def&&t.type?._def?.typeName!==re.ZodAny&&(r.items=Or(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&fo(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&fo(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(fo(r,"minItems",t.exactLength.value,t.exactLength.message,e),fo(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}varSxe=b(()=>{xd();VA();yu()});functionqXe(t,e){letr={type:"integer",format:"int64"};if(!t.checks)returnr;for(letnoft.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?fo(r,"minimum",n.value,n.message,e):fo(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),fo(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?fo(r,"maximum",n.value,n.message,e):fo(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),fo(r,"maximum",n.value,n.message,e));break;case"multipleOf":fo(r,"multipleOf",n.value,n.message,e);break}returnr}varCxe=b(()=>{VA()});functionHXe(){return{type:"boolean"}}varOxe=b(()=>{});functionWQ(t,e){returnOr(t.type._def,e)}varKQ=b(()=>{yu()});varVXe,Exe=b(()=>{yu();VXe=(t,e)=>Or(t.innerType._def,e)});functionPxe(t,e,r){letn=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,i)=>Pxe(t,e,o))};switch(n){case"
- `)}`,new Error(be)}let ne=`${s}/$ref`,fe=va(t,le,r,n,o,i,a,ne,u);if(fe.valid||Me.push({instanceLocation:a,keyword:"$ref",keywordLocation:ne,error:"Asubschemahaderrors."},...fe.errors),r==="4"||r==="7")return{valid:Me.length===0,errors:Me}}if(Array.isArray(h)){let je=h.length,le=!1;for(let ne=0;ne<je;ne++)if(c===h[ne]||h[ne]==="integer"&&c==="number"&&t%1===0&&t===t){le=!0;break}le||Me.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${h.join('", "')}".`})}else h==="integer"?(c!=="number"||t%1||t!==t)&&Me.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${h}".`}):h!==void 0&&c!==h&&Me.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${h}".`});if(m!==void 0&&(c==="object"||c==="array"?yE(t,m)||Me.push({instanceLocation:a,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(m)}.`}):t!==m&&Me.push({instanceLocation:a,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(m)}.`})),g!==void 0&&(c==="object"||c==="array"?g.some(je=>yE(t,je))||Me.push({instanceLocation:a,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(je=>t===je)||Me.push({instanceLocation:a,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),_!==void 0){let je=`${s}/not`;va(t,_,r,n,o,i,a,je).valid&&Me.push({instanceLocation:a,keyword:"not",keywordLocation:je,error:'Instance matched "not" schema.'})}let Ze=[];if(w!==void 0){let je=`${s}/anyOf`,le=Me.length,ne=!1;for(let fe=0;fe<w.length;fe++){let be=w[fe],ye=Object.create(u),ze=va(t,be,r,n,o,p===!0?i:null,a,`${je}/${fe}`,ye);Me.push(...ze.errors),ne=ne||ze.valid,ze.valid&&Ze.push(ye)}ne?Me.length=le:Me.splice(le,0,{instanceLocation:a,keyword:"anyOf",keywordLocation:je,error:"Instancedoesnotmatchanysubschemas."})}if(S!==void 0){let je=`${s}/allOf`,le=Me.length,ne=!0;for(let fe=0;fe<S.length;fe++){let be=S[fe],ye=Object.create(u),ze=va(t,be,r,n,o,p===!0?i:null,a,`${je}/${fe}`,ye);Me.push(...ze.errors),ne=ne&&ze.valid,ze.valid&&Ze.push(ye)}ne?Me.length=le:Me.splice(le,0,{instanceLocation:a,keyword:"allOf",keywordLocation:je,error:"Instancedoesnotmatcheverysubschema."})}if(C!==void 0){let je=`${s}/oneOf`,le=Me.length,ne=C.filter((fe,be)=>{let ye=Object.create(u),ze=va(t,fe,r,n,o,p===!0?i:null,a,`${je}/${be}`,ye);return Me.push(...ze.errors),ze.valid&&Ze.push(ye),ze.valid}).length;ne===1?Me.length=le:Me.splice(le,0,{instanceLocation:a,keyword:"oneOf",keywordLocation:je,error:`Instance does not match exactly one subschema (${ne} matches).`})}if((c==="object"||c==="array")&&Object.assign(u,...Ze),E!==void 0){let je=`${s}/if`;if(va(t,E,r,n,o,i,a,je,u).valid){if(P!==void 0){let ne=va(t,P,r,n,o,i,a,`${s}/then`,u);ne.valid||Me.push({instanceLocation:a,keyword:"if",keywordLocation:je,error:'Instance does not match "then" schema.'},...ne.errors)}}else if(T!==void 0){let ne=va(t,T,r,n,o,i,a,`${s}/else`,u);ne.valid||Me.push({instanceLocation:a,keyword:"if",keywordLocation:je,error:'Instance does not match "else" schema.'},...ne.errors)}}if(c==="object"){if(y!==void 0)for(let fe of y)fe in t||Me.push({instanceLocation:a,keyword:"required",keywordLocation:`${s}/required`,error:`Instance does not have required property "${fe}".`});let je=Object.keys(t);if(F!==void 0&&je.length<F&&Me.push({instanceLocation:a,keyword:"minProperties",keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${F} properties.`}),K!==void 0&&je.length>K&&Me.push({instanceLocation:a,keyword:"maxProperties",keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${K} properties.`}),U!==void 0){let fe=`${s}/propertyNames`;for(let be in t){let ye=`${a}/${Th(be)}`,ze=va(be,U,r,n,o,i,ye,fe);ze.valid||Me.push({instanceLocation:a,keyword:"propertyNames",keywordLocation:fe,error:`Property name "${be}" does not
`)),n.close()}});return Pf.fromReadableStream(r)}var PQe=b(()=>{xv()});function oSe(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.iterator]=="function"&&typeof t.next=="function"}function ree(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.asyncIterator]=="function"}function*iSe(t,e){for(;;){let{value:r,done:n}=Ep.runWithConfig(Wg(t),e.next.bind(e),!0);if(n)break;yield r}}async function*nee(t,e){let r=e[Symbol.asyncIterator]();for(;;){let{value:n,done:o}=await Ep.runWithConfig(Wg(t),r.next.bind(e),!0);if(o)break;yield n}}var TQe,AQe=b(()=>{yj();vv();TQe=t=>t!=null&&typeof t=="object"&&"next"in t&&typeof t.next=="function"});function ac(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}function rPr(t){if(zX(t))throw new Error("RunnableLambdarequiresafunctionthatisnotwrappedintraceablehigher-orderfunction.Thisshouldn't happen.")}function _E(t){if(typeof t=="function")return new Tp({func:t});if(Un.isRunnable(t))return t;if(!Array.isArray(t)&&typeof t=="object"){let e={};for(let[r,n]of Object.entries(t))e[r]=_E(n);return new KA({steps:e})}else throw new Error(`Expected a Runnable, function or object.
Instead got an unsupported type.`)}function nPr(t,e){let r=e.name??t.getName(),n=e.description??bj(e.schema);return nSe(e.schema)?new U6({name:r,description:n,schema:dt.object({input:dt.string()}).transform(o=>o.input),bound:t}):new U6({name:r,description:n,schema:e.schema,bound:t})}var aSe,Un,Ov,oee,z6,Li,KA,sSe,Tp,iee,LB,aee,U6,Tf=b(()=>{NX();aSe=j(LX(),1);ij();Lwe();uXe();cXe();cj();xv();lxe();vv();PB();fXe();dxe();yj();OQe();PQe();AQe();PQ();bE();Un=class extends ym{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 Ov({bound:this,kwargs:e,config:{}})}map(){return new oee({bound:this})}withRetry(e){return new z6({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new Ov({bound:this,config:e,kwargs:{}})}withFallbacks(e){let r=Array.isArray(e)?e:e.fallbacks;return new iee({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(In);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)=>In(i===0?e:n))}return Array.from({length:r},()=>In(e))}async batch(e,r,n){let o=this._getOptionsList(r??{},e.length),i=o[0]?.maxConcurrency??n?.maxConcurrency,a=new Ph({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=In(r),o=new gE({generator:this._streamIterator(e,n),config:n});return await o.setup,Pf.fromAsyncGenerator(o)}_separateRunnableConfigFromCallOptions(e){let r;e===void 0?r=In(e):r=In({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=In(n),a=await(await vm(o))?.handleChainStart(this.toJSON(),ac(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 wv(u,n?.signal)}catch(u){throw await a?.handleChainError(u),u}return await a?.handleChainEnd(ac(s,"output")),s}async _batchWithConfig(e,r,n,o){let i=this._getOptionsList(n??{},r.length),a=await Promise.all(i.map(vm)),s=await Promise.all(a.map(async(l,c)=>{let d=await l?.handleChainStart(this.toJSON(),ac(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 wv(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(ac(u,"output")))),u}async*_transformStreamWithConfig(e,r,n){let o,i=!0,a,s=!0,u=In(n),l=await vm(u);async function*c(){for await(let f of e){if(i)if(o===void 0)o=f;else try{o=jc(o,f)}catch{o=void 0,i=!1}yield f}}let d;try{let f=await oXe(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(lXe),h=f.output;p!==void 0&&d!==void 0&&(h=p.tapOutputIterable(d.runId,h));let m=d?.handlers.find(sXe);m!==void 0&&d!==void 0&&(h=m.tapOutputIterable(d.runId,h));for await(let g of h)if(yield g
"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:
`)};Ap.prototype.renderPartial=function(e,r,n,o){if(n){var i=this.getConfigTags(o),a=pSe(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)}}};Ap.prototype.unescapedValue=function(e,r){var n=r.lookup(e[1]);if(n!=null)return n};Ap.prototype.escapedValue=function(e,r,n){var o=this.getConfigEscape(n)||Gg.escape,i=r.lookup(e[1]);if(i!=null)return typeof i=="number"&&o===Gg.escape?String(i):o(i)};Ap.prototype.rawValue=function(e){return e[1]};Ap.prototype.getConfigTags=function(e){return UB(e)?e:e&&typeof e=="object"?e.tags:void 0};Ap.prototype.getConfigEscape=function(e){if(e&&typeof e=="object"&&!UB(e))return e.escape};Gg={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){W6.templateCache=t},get templateCache(){return W6.templateCache}},W6=new Ap;Gg.clearCache=function(){return W6.clearCache()};Gg.parse=function(e,r){return W6.parse(e,r)};Gg.render=function(e,r,n,o){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+iPr(e)+'" was given as the first argument for mustache#render(template, view, partials)');return W6.render(e,r,n,o)};Gg.escape=fPr;Gg.Scanner=K6;Gg.Context=zB;Gg.Writer=Ap;cee=Gg});function HQe(){cee.escape=t=>t}var G6,VQe,dee,vPr,wPr,mSe,xPr,Om,J6,Oj,Ej=b(()=>{qQe();w6();G6=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},VQe=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=VQe(r[4]);e.push(...n)}}else e.push({type:"literal",text:r[1]});return e},dee=t=>{HQe();let e=cee.parse(t);return VQe(e)},vPr=(t,e)=>G6(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},""),wPr=(t,e)=>(HQe(),cee.render(t,e)),mSe={"f-string":vPr,mustache:wPr},xPr={"f-string":G6,mustache:dee},Om=(t,e,r)=>{try{return mSe[e](t,r)}catch(n){throw kA(n,"INVALID_PROMPT_INPUT")}},J6=(t,e)=>xPr[e](t),Oj=(t,e,r)=>{if(!(e in mSe)){let n=Object.keys(mSe);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")Om(o.text,e,n);else if(o.type==="image_url")if(typeof o.image_url=="string")Om(o.image_url,e,n);else{let i=o.image_url.url;Om(i,e,n)}else throw new Error(`Invalid message template received. ${JSON.stringify(o,null,2)}`)}):Om(t,e,n)}catch(n){throw new Error(`Invalid prompt schema: ${n.message}`)}}});var hSe={};os(hSe,{PromptTemplate:()=>Af});var Af,qB=b(()=>{V6();Ej();Af=class t extends vE{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))),Oj(this.template,this.templateFormat,r)}}_getPromptType(){return"prompt"}async format(e){let r=await this.mergePartialAndUserVariables(e);return Om(this.template,this.templateFormat,r)}static fromExamples(e,r,n,o=`
From: ${i}`);s=[l[0]]}else s=[];i={url:i},a=new HB({template:i,inputVariables:s,templateFormat:r?.templateFormat,additionalContentFields:o})}else if(typeof i=="object"){if("url"in i){let u;r?.templateFormat==="mustache"?u=dee(i.url):u=G6(i.url),s=u.flatMap(l=>l.type==="variable"?[l.name]:[])}else s=[];a=new HB({template:i,inputVariables:s,templateFormat:r?.templateFormat,additionalContentFields:o})}else throw new Error("Invalidimagetemplate");n.push(a)}else typeof o=="object"&&n.push(new Z6({template:o,templateFormat:r?.templateFormat}));return new this({prompt:n,additionalOptions:r})}async format(e){if(this.prompt instanceof vE){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 vE){let i=await n.format(o),a;"additionalContentFields"in n&&(a=n.additionalContentFields),r.push({...a,type:"text",text:i})}else if(n instanceof HB){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 Z6){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)]}},Tv=class extends Q6{static _messageClass(){return Xs}static lc_name(){return"HumanMessagePromptTemplate"}},xSe=class extends Q6{static _messageClass(){return kn}static lc_name(){return"AIMessagePromptTemplate"}},JA=class extends Q6{static _messageClass(){return hE}static lc_name(){return"SystemMessagePromptTemplate"}};Em=class t extends X6{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 oc))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 Af.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 oc)n.push(await this._parseImagePrompts(o,r));else{let i=o.inputVariables.reduce((s,u)=>{if(!(u in r)&&!(PPr(o)&&o.optional))throw kA(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=Af.fromTemplate(e,r),o=new Tv({prompt:n});return this.fromMessages([o])}static fromMessages(e,r){let n=e.reduce((a,s)=>a.concat(s instanceof t?s.promptMessages:[EPr(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))),Oj(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 Om(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 Af.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})}},CSe=class t extends X6{_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.
14. YouTube URLs: If the user provides YouTube URLs in their message, transcriptions will be automatically fetched and provided to you. You don't need to do anything special - just use the transcription content if available.`,Bet=`Return the new note content or canvas JSON in <writeToFile> tags.
`,f8="note_context",Tm="selected_text",p8="variable",Ij="variable_note",m8="embedded_pdf",rCe="retrieved_document",Mj=6e3,nCe=.4,oCe=448e3,oz=3e4,Iv={DEFAULT:"",READING_FILES:"Reading files",SEARCHING_WEB:"Searching the web",READING_FILE_TREE:"Reading file tree"},EE={SETTINGS:"settings",EXPIRED_MODAL:"expired_modal",CHAT_MODE_SELECT:"chat_mode_select",MODE_SELECT_TOOLTIP:"mode_select_tooltip"},Rf={MAX_TOKENS:6e3,TEMPERATURE:.1,REASONING_EFFORT:"low",VERBOSITY:"medium"},CE=(h=>(h.OPENAI="openai",h.OPENAI_FORMAT="3rd party (openai-format)",h.AZURE_OPENAI="azure openai",h.ANTHROPIC="anthropic",h.COHEREAI="cohereai",h.GOOGLE="google",h.XAI="xai",h.OPENROUTERAI="openrouterai",h.GROQ="groq",h.OLLAMA="ollama",h.LM_STUDIO="lm-studio",h.COPILOT_PLUS="copilot-plus",h.MISTRAL="mistralai",h.DEEPSEEK="deepseek",h))(CE||{}),rI={reasoning:"This model supports general reasoning tasks.",vision:"This model supports image inputs.",websearch:"This model can access the internet."},Av=[{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",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-flash-lite",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"]}],QA=(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))(QA||{}),Pj=[{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,isBuiltI
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")returnVI(i);if(o==="hex")returnIvt(i);if(o===void0||o==="utf8"||o==="utf-8")returnKne(i);if(typeofTextDecoder=="function")returnnewTextDecoder(o).decode(i);thrownewError("TextDecoder is not available, please make sure polyfill is provided.")},transformToWebStream:()=>{if(e)thrownewError(Rvt);if(e=!0,Nvt(t))returnn(t);if(vTe(t))returnt;thrownewError(`Cannot transform payload to web stream, got ${t}`)}})},Nvt=t=>typeofBlob=="function"&&tinstanceofBlob});varLvt=b(()=>{});varFvt=b(()=>{});varxTe=b(()=>{yTe();dvt();Dvt();Lvt();Fvt();wTe()});varKI,kvt=b(()=>{xTe();KI=async(t=newUint8Array,e)=>{if(tinstanceofUint8Array)returnXE.mutate(t);if(!t)returnXE.mutate(newUint8Array);letr=e.streamCollector(t);returnXE.mutate(awaitr)}});varMt,STe,$vt=b(()=>{cTe();Su();Mt=class{constructor(){this.middlewareStack=aU()}staticclassBuilder(){returnnewSTe}resolveMiddlewareWithContext(e,r,n,{middlewareFn:o,clientName:i,commandName:a,inputFilterSensitiveLog:s,outputFilterSensitiveLog:u,smithyContext:l,additionalContext:c,CommandCtor:d}){for(letgofo.bind(this)(d,e,r,n))this.middlewareStack.use(g);letf=e.concat(this.middlewareStack),{logger:p}=r,h={logger:p,clientName:i,commandName:a,inputFilterSensitiveLog:s,outputFilterSensitiveLog:u,[eU]:{commandInstance:this,...l},...c},{requestHandler:m}=r;returnf.resolve(g=>m.handle(g.request,n||{}),h)}},STe=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=classextendsMt{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})}}}}});varJne,Bvt=b(()=>{Jne="***SensitiveInformation***"});varZne,zvt=b(()=>{Zne=(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}}});varSD,BNr,Uvt,zNr,qvt,Hvt,Vvt,CTe,UNr,lU,Mn,Wvt,Kvt,qNr,eW,tW,OTe,Gvt,Jvt,Zvt,ETe=b(()=>{SD=t=>{if(t!=null){if(typeoft=="string"){lete=parseFloat(t);if(!Number.isNaN(e))returnString(e)!==String(t)&&Zvt.warn(Jvt(`Expected number but observed string: ${t}`)),e}if(typeoft=="number")returnt;thrownewTypeError(`Expected number, got ${typeoft}: ${t}`)}},BNr=Math.ceil(34028234663852886e22),Uvt=t=>{lete=SD(t);if(e!==void0&&!Number.isNaN(e)&&e!==1/0&&e!==-1/0&&Math.abs(e)>BNr)thrownewTypeError(`Expected 32-bit float, got ${t}`);returne},zNr=t=>{if(t!=null){if(Number.isInteger(t)&&!Number.isNaN(t))returnt;thrownewTypeError(`Expected integer, got ${typeoft}: ${t}`)}},qvt=t=>CTe(t,32),Hvt=t=>CTe(t,
`),Zvt={warn:console.warn}});var HNr,VNr,Yvt,WNr,Xvt,_Po,vPo,wPo,Yne,Qvt,xPo,KNr,GNr,JNr,CD,ZNr,YNr,PTe,ewt=b(()=>{ETe();HNr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],VNr=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/),Yvt=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=VNr.exec(t);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");let[r,n,o,i,a,s,u,l]=e,c=OTe(PTe(n)),d=CD(o,"month",1,12),f=CD(i,"day",1,31);return Qvt(c,d,f,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l})},WNr=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),Xvt=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=WNr.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=OTe(PTe(n)),f=CD(o,"month",1,12),p=CD(i,"day",1,31),h=Qvt(d,f,p,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l});return c.toUpperCase()!="Z"&&h.setTime(h.getTime()-YNr(c)),h},_Po=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$/),vPo=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$/),wPo=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})$/),Yne=t=>{if(t==null)return;let e;if(typeof t=="number")e=t;else if(typeof t=="string")e=Wvt(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))},Qvt=(t,e,r,n)=>{let o=e-1;return GNr(t,o,r),new Date(Date.UTC(t,o,r,CD(n.hours,"hour",0,23),CD(n.minutes,"minute",0,59),CD(n.seconds,"seconds",0,60),ZNr(n.fractionalMilliseconds)))},xPo=50*365*24*60*60*1e3,KNr=[31,28,31,30,31,30,31,31,30,31,30,31],GNr=(t,e,r)=>{let n=KNr[e];if(e===1&&JNr(t)&&(n=29),r>n)throw new TypeError(`Invaliddayfor${HNr[e]}in${t}:${r}`)},JNr=t=>t%4===0&&(t%100!==0||t%400===0),CD=(t,e,r,n)=>{let o=Gvt(PTe(t));if(o<r||o>n)throw new TypeError(`${e}mustbebetween${r}and${n},inclusive`);return o},ZNr=t=>t==null?0:Kvt("0."+t)*1e3,YNr=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},PTe=t=>{let e=0;for(;e<t.length-1&&t.charAt(e)==="0";)e++;return e===0?t:t.slice(e)}});var cU,ds,TTe=b(()=>{cU=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}},ds=(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 XNr,Xne,QNr,twt=b(()=>{TTe();XNr=({output:t,parsedBody:e,exceptionCtor:r,errorCode:n})=>{let o=QNr(t),i=o.httpStatusCode?o.httpStatusCode+"":void 0,a=new r({name:e?.code||e?.Code||n||i||"UnknownError",$fault:"client",$metadata:o});throw ds(a,e)},Xne=t=>({output:e,parsedBody:r,errorCode:n})=>{XNr({output:e,parsedBody:r,exceptionCtor:t,errorCode:n})},QNr=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 Qne,rwt=b(()=>{Qne=t=>{switch(t){case"standard":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"cross-region
${Yb(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("/")?"/":""}`;returnmy(n).replace(/%2F/g,"/")}returne}asyncgetSignature(e,r,n,o){leti=awaitthis.createStringToSign(e,r,o),a=newthis.sha256(awaitn);returna.update(ZI(i)),Yb(awaita.digest())}getSigningKey(e,r,n,o){returnN0t(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")}},goe=t=>{lete=z0t(t).replace(/[\-:]/g,"");return{longDate:e,shortDate:e.slice(0,8)}},q0t=t=>Object.keys(t).sort().join(";")});varV0t=b(()=>{H0t();JTe();YTe();XTe();tAe();rAe();GTe()});varyoe,W0t=b(()=>{GI();V0t();yoe=t=>{lete;t.credentials&&(e=Mwt(t.credentials,Iwt,NTe)),e||(t.credentialDefaultProvider?e=pU(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=pU(t.signer):t.regionInfoProvider?i=()=>pU(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||cW;returnnewd(c)}):i=asynca=>{a=Object.assign({},{name:"sigv4",signingName:t.signingName||t.defaultSigningName,signingRegion:awaitpU(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||cW;returnnewc(l)},{...t,systemClockOffset:n,signingEscapePath:r,credentials:e,signer:i}}});varK0t=b(()=>{f0t();p0t();W0t()});varG0t=b(()=>{K0t()});varJ0t=b(()=>{});varZ0t=b(()=>{yr()});varboe,nAe=b(()=>{yr();boe=(t,e)=>KI(t,e).then(r=>e.utf8Encoder(r))});variu,Y0t,X0t,Q0t=b(()=>{nAe();iu=(t,e)=>boe(t,e).then(r=>{if(r.length)try{returnJSON.parse(r)}catch(n){thrown?.name==="SyntaxError"&&Object.defineProperty(n,"$responseBodyText",{value:r}),n}return{}}),Y0t=async(t,e)=>{letr=awaitiu(t,e);returnr.message=r.message??r.Message,r},X0t=(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)}});var_oe=x(QE=>{"use strict";varext=":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",_jr=ext+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",txt="["+ext+"]["+_jr+"]*",vjr=newRegExp("^"+txt+"$"),wjr=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},xjr=function(t){lete=vjr.exec(t);return!(e===null||typeofe>"u")};QE.isExist=function(t){returntypeoft<"u"};QE.isEmptyObject=function(t){returnObject.keys(t).length===0};QE.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]]}};QE.getValue=function(t){returnQE.isExist(t)?t:""};QE.isName=xjr;QE.getAllMatches=wjr;QE.nameRegexp=txt});variAe=x(axt=>{"use strict";varoAe=_oe(),Sjr={allowBooleanAttributes:!1,unpairedTags:[]};axt.validate=function(t,e){e=Object.assign({},Sjr,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--),!Mjr(u)){let d;return u.trim().length===0?d="Invalid space after '<'.":d="Tag '"+u+"' is an invalid name.",au("InvalidTag",d,Fp(t,i))}let l=Ejr(t,i);if(l===!1)return au("InvalidAttr","Attributes for '"+u+"' have open quote.",Fp(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=ixt(c,e);if(f===!0)n=!0;else return au(f.err.code,f.err.msg,Fp(t,d+f.err.line))}else if(s)if(l.tagClosed){if(c.trim().length>0)return au("InvalidTag","Closing tag '"+u+"' can't have attributes or invalid starting.",Fp(t,a));if(r.length===0)return au("InvalidTag","Closing tag '"+u+"' has not been opened.",Fp(t,a));{let d=r.pop();if(u!==d.tagName){let f=Fp(t,d.tagStartPos);return au("InvalidTag","Expected closing tag '"+d.tagName+"' (opened in line "+f.line+", col "+f.col+") instead of closing tag '"+u+"'.",Fp(t,a))}r.length==0&&(o=!0)}}else return au("InvalidTag","Closing tag '"+u+"' doesn't have proper closing.",Fp(t,i));else{let d=ixt(c,e);if(d!==!0)return au(d.err.code,d.err.msg,Fp(t,i-c.length+d.err.line));if(o===!0)return au("InvalidXml","Multiple possible root nodes found.",Fp(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=oxt(t,i);continue}else if(t[i+1]==="?"){if(i=nxt(t,++i),i.err)return i}else break;else if(t[i]==="&"){let d=Ajr(t,i);if(d==-1)return au("InvalidChar","char '&' is not expected.",Fp(t,i));i=d}else if(o===!0&&!rxt(t[i]))return au("InvalidXml","Extra text at the end",Fp(t,i));t[i]==="<"&&i--}}else{if(rxt(t[i]))continue;return au("InvalidChar","char '"+t[i]+"' is not expected.",Fp(t,i))}if(n){if(r.length==1)return au("InvalidTag","Unclosed tag '"+r[0].tagName+"'.",Fp(t,r[0].tagStartPos));if(r.length>0)return au("InvalidXml","Invalid '"+JSON.stringify(r.map(i=>i.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return au("InvalidXml","Start tag expected.",1);return!0};function rxt(t){return t===" "||t===" "||t===`
`||t==="\r"}function nxt(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 au("InvalidXml","XML declaration allowed only at the start of the document.",Fp(t,e));if(t[e]=="?"&&t[e+1]==">"){e++;break}else continue}return e}function oxt(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 Cjr='"',Ojr="'";function Ejr(t,e){let r="",n="",o=!1;for(;e<t.length;e++){if(t[e]===Cjr||t[e]===Ojr)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 Pjr=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function ixt(t,e){let r=oAe.getAllMatches(t,Pjr),n={};for(let o=0;o<r.length;o++){if(r[o][1].length===0)return au("InvalidAttr","Attribute '"+r[o][2]+"' has no space in starting.",dW(r[o]));if(r[o][3]!==void 0&&r[o][4]===void 0)return au("InvalidAttr","Attribute '"+r[o][2]+"' is without value.",dW(r[o]));if(r[o][3]===void 0&&!e.allowBooleanAttributes)return au("InvalidAttr","boolean attribute '"+r[o][2]+"' is not allowed.",dW(r[o]));let i=r[o][2];if(!Ijr(i))return au("InvalidAttr","Attribute '"+i+"' is an invalid name.",dW(r[o]));if(!n.hasOwnProperty(i))n[i]=1;else return au("InvalidAttr","Attribute '"+i+"' is repeated.",dW(r[o]))}return!0}function Tjr(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 Ajr(t,e){if(e++,t[e]===";")return-1;if(t[e]==="#")return e++,Tjr(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 au(t,e,r){return{err:{code:t,msg:e,line:r.line||r,col:r.col}}}function Ijr(t){return oAe.isName(t)}function Mjr(t){return oAe.isName(t)}function Fp(t,e){let r=t.substring(0,e).split(/\r?\n/);return{line:r.length,col:r[r.length-1].length+1}}function dW(t){return t.startIndex+t[1].length}});var uxt=x(aAe=>{var sxt={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}},Rjr=function(t){return Object.assign({},sxt,t)};aAe.buildOptions=Rjr;aAe.defaultOptions=sxt});var cxt=x((WMo,lxt)=>{"use strict";var sAe=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})}};lxt.exports=sAe});var fxt=x((KMo,dxt)=>{var Njr=_oe();function jjr(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&&Fjr(t,e))e+=7,[entityName,val,e]=Djr(t,e+1),val.indexOf("&")===-1&&(r[zjr(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(o&&kjr(t,e))e+=8;else if(o&&$jr(t,e))e+=8;else if(o&&Bjr(t,e))e+=9;else if(Ljr)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 fW("!xml"),r=e,n="",o="";for(let i=0;i<t.length;i++)if(t[i]==="<")if(t[i+1]==="/"){let s=PD(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=lAe(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 fW(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=PD(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=Kjr(t,i);this.docTypeEntities=s.entities,i=s.i}else if(t.substr(i+1,2)==="!["){let s=PD(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=lAe(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 h="";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 g=this.readStopNodeData(t,l,f+1);if(!g)throw new Error(`Unexpected end of ${l}`);i=g.i,h=g.tagContent}let m=new fW(u);u!==c&&d&&(m[":@"]=this.buildAttributesMap(c,o,u)),h&&(h=this.parseTextData(h,u,o,!0,d,!0,!0)),o=o.substr(0,o.lastIndexOf(".")),m.add(this.options.textNodeName,h),this.addChild(r,m,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 h=new fW(u);u!==c&&d&&(h[":@"]=this.buildAttributesMap(c,o,u)),this.addChild(r,h,o),o=o.substr(0,o.lastIndexOf("."))}else{let h=new fW(u);this.tagsNodeStack.push(r),u!==c&&d&&(h[":@"]=this.buildAttributesMap(c,o,u)),this.addChild(r,h,o),r=h}n="",i=f}}else n+=t[i];return e.child};function tDr(t,e,r){let n=this.options.updateTag(e.tagname,r,e[":@"]);n===!1||(typeof n=="string"&&(e.tagname=n),t.addChild(e))}var rDr=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 nDr(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 oDr(t,e,r){let n="*
`;super(r),this.name="AggregateError",this.errors=e}};XMe.exports={AggregateError:YMe,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 X$r},isArrayBufferView(t){return ArrayBuffer.isView(t)}},isBlob:Q$r,deprecate(t,e){return t},addAbortListener:zW().addAbortListener||function(e,r){if(e===void 0)throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",e);WIt(e,"signal"),eBr(r,"listener");let n;return e.aborted?queueMicrotask(()=>r()):(e.addEventListener("abort",r,{__proto__:null,once:!0,[G$r]:!0}),n=()=>{e.removeEventListener("abort",r)}),{__proto__:null,[J$r](){var o;(o=n)===null||o===void 0||o()}}},AbortSignalAny:Z$r.any||function(e){if(e.length===1)return e[0];let r=new Y$r,n=()=>r.abort();return e.forEach(o=>{WIt(o,"signals"),o.addEventListener("abort",n,{once:!0})}),r.signal.addEventListener("abort",()=>{e.forEach(o=>o.removeEventListener("abort",n))},{once:!0}),r.signal}};XMe.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var zp=x((e2o,JIt)=>{"use strict";var{format:tBr,inspect:hae,AggregateError:rBr}=Vf(),nBr=globalThis.AggregateError||rBr,oBr=Symbol("kIsNodeError"),iBr=["string","function","number","object","Function","Object","boolean","bigint","symbol"],aBr=/^([A-Z][a-z0-9]*)+$/,sBr="__node_internal_",gae={};function BD(t,e){if(!t)throw new gae.ERR_INTERNAL_ASSERTION(e)}function KIt(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 uBr(t,e,r){if(typeof e=="function")return BD(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 BD(n===r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${n}).`),r.length===0?e:tBr(e,...r)}function jd(t,e,r){r||(r=Error);class n extends r{constructor(...i){super(uBr(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[oBr]=!0,gae[t]=n}function GIt(t){let e=sBr+t.name;return Object.defineProperty(t,"name",{value:e}),t}function lBr(t,e){if(t&&e&&t!==e){if(Array.isArray(e.errors))return e.errors.push(t),e;let r=new nBr([e,t],e.message);return r.code=e.code,r}return t||e}var QMe=class extends Error{constructor(e="The operation was aborted",r=void 0){if(r!==void 0&&typeof r!="object")throw new gae.ERR_INVALID_ARG_TYPE("options","Object",r);super(e,r),this.code="ABORT_ERR",this.name="AbortError"}};jd("ERR_ASSERTION","%s",Error);jd("ERR_INVALID_ARG_TYPE",(t,e,r)=>{BD(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)BD(typeof u=="string","All expected entries have to be of type string"),iBr.includes(u)?o.push(u.toLowerCase()):aBr.test(u)?i.push(u):(BD(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(){returnPDt(this,arguments,function*(){varr,n;this.controller.signal;leto=TDt(this.stream),i="",a=!1;try{for(vars=EDt(o),u;u=yieldt_(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))returnyieldt_(void0);letf=yieldt_(this.parse(JSON.parse(d)));yieldyieldt_(f),a=!1}}}catch(l){r={error:l}}finally{try{u&&!u.done&&(n=s.return)&&(yieldt_(n.call(s)))}finally{if(r)throwr.error}}})}[Symbol.asyncIterator](){returnPDt(this,arguments,function*(){varr,n;try{for(varo=EDt(this.iterMessages()),i;i=yieldt_(o.next()),!i.done;){leta=i.value;yieldyieldt_(a)}}catch(a){r={error:a}}finally{try{i&&!i.done&&(n=o.return)&&(yieldt_(n.call(o)))}finally{if(r)throwr.error}}})}decodeChunk(e){letr="";if(typeofTextDecoder<"u"){letn=newTextDecoder("utf8");r+=n.decode(e)}elseRVr.RUNTIME.type==="node"&&typeofe<"u"&&(r+=Buffer.isBuffer(e)?e:Buffer.from(e));returnr}};Bm.Stream=Z1e;functionTDt(t){if(t[Symbol.asyncIterator])returnt;lete=t.getReader();return{next(){returnODt(this,void0,void0,function*(){try{letr=yielde.read();returnr?.done&&e.releaseLock(),r}catch(r){throwe.releaseLock(),r}})},return(){returnODt(this,void0,void0,function*(){letr=e.cancel();returne.releaseLock(),yieldr,{done:!0,value:void0}})},[Symbol.asyncIterator](){returnthis}}}Bm.readableStreamAsyncIterable=TDt});varADt=x(mse=>{"use strict";Object.defineProperty(mse,"__esModule",{value:!0});mse.Stream=void0;varjVr=Y1e();Object.defineProperty(mse,"Stream",{enumerable:!0,get:function(){returnjVr.Stream}})});varRDt=x((B4o,MDt)=>{"use strict";varX1e=Object.defineProperty,DVr=Object.getOwnPropertyDescriptor,LVr=Object.getOwnPropertyNames,FVr=Object.prototype.hasOwnProperty,kVr=(t,e)=>{for(varrine)X1e(t,r,{get:e[r],enumerable:!0})},$Vr=(t,e,r,n)=>{if(e&&typeofe=="object"||typeofe=="function")for(letoofLVr(e))!FVr.call(t,o)&&o!==r&&X1e(t,o,{get:()=>e[o],enumerable:!(n=DVr(e,o))||n.enumerable});returnt},BVr=t=>$Vr(X1e({},"__esModule",{value:!0}),t),IDt={};kVr(IDt,{Blob:()=>qVr,File:()=>HVr,FormData:()=>UVr});MDt.exports=BVr(IDt);varzVr=function(){returntypeofglobalThis<"u"?globalThis:typeofself<"u"?self:window}(),{FormData:UVr,Blob:qVr,File:HVr}=zVr});varVDt=x((z4o,HDt)=>{"use strict";vartNe=Object.defineProperty,VVr=Object.getOwnPropertyDescriptor,WVr=Object.getOwnPropertyNames,KVr=Object.prototype.hasOwnProperty,GVr=(t,e)=>{for(varrine)tNe(t,r,{get:e[r],enumerable:!0})},JVr=(t,e,r,n)=>{if(e&&typeofe=="object"||typeofe=="function")for(letoofWVr(e))!KVr.call(t,o)&&o!==r&&tNe(t,o,{get:()=>e[o],enumerable:!(n=VVr(e,o))||n.enumerable});returnt},ZVr=t=>JVr(tNe({},"__esModule",{value:!0}),t),rNe=(t,e,r)=>{if(!e.has(t))throwTypeError("Cannot "+r)},Ds=(t,e,r)=>(rNe(t,e,"read from private field"),r?r.call(t):e.get(t)),Pw=(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)},f9=(t,e,r,n)=>(rNe(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),Q1e=(t,e,r)=>(rNe(t,e,"access private method"),r),$Dt={};GVr($Dt,{FormDataEncoder:()=>o6r,isFile:()=>nL,isFormData:()=>UDt});HDt.exports=ZVr($Dt);varhP=t=>typeoft=="function",YVr=t=>hP(t[Symbol.asyncIterator]),NDt=65536;function*BDt(t){if(t.byteLength<=NDt){yieldt;return}lete=0;for(;e<t.byteLength;){letr=Math.min(t.byteLength-e,NDt),n=t.buffer.slice(e,e+r);e+=n.byteLength,yieldnewUint8Array(n)}}asyncfunction*XVr(t){lete=t.getReader();for(;;){let{done:r,value:n}=awaite.read();if(r)break;yieldn}}asyncfunction*jDt(t){forawait(leteoft)yield*BDt(e)}varQVr=t=>{if(YVr(t))returnjDt(t);if(hP(t.getReader))returnjDt(XVr(t));thrownewTypeError("Unsup
`),Pw(this,p9,void0),Pw(this,gse,void0),Pw(this,m9,"-".repeat(2)),Pw(this,rL,newTextEncoder),Pw(this,h9,void0),Pw(this,g9,void0),Pw(this,yse,void0),!UDt(t))thrownewTypeError("Expected first argument to be a FormData instance.");letn;if(LDt(e)?r=e:n=e,n||(n=e6r()),typeofn!="string")thrownewTypeError("Expected boundary argument to be a string.");if(r&&!LDt(r))thrownewTypeError("Expected options argument to be an object.");f9(this,g9,Array.from(t.entries())),f9(this,yse,{...n6r,...r}),f9(this,p9,Ds(this,rL).encode(Ds(this,SM))),f9(this,gse,Ds(this,p9).byteLength),this.boundary=`form-data-boundary-${n}`,this.contentType=`multipart/form-data; boundary=${this.boundary}`,f9(this,h9,Ds(this,rL).encode(`${Ds(this,m9)}${this.boundary}${Ds(this,m9)}${Ds(this,SM).repeat(2)}`));leto={"Content-Type":this.contentType},i=Q1e(this,eNe,qDt).call(this);i&&(this.contentLength=i,o["Content-Length"]=i),this.headers=r6r(Object.freeze(o)),Object.defineProperties(this,{boundary:hse,contentType:hse,contentLength:hse,headers:hse})}*values(){for(let[t,e]ofDs(this,g9)){letr=nL(e)?e:Ds(this,rL).encode(zDt(e));yieldQ1e(this,bse,nNe).call(this,t,r),yieldr,yieldDs(this,p9)}yieldDs(this,h9)}async*encode(){for(lettofthis.values())nL(t)?yield*QVr(t.stream()):yield*BDt(t)}[Symbol.iterator](){returnthis.values()}[Symbol.asyncIterator](){returnthis.encode()}};SM=newWeakMap;p9=newWeakMap;gse=newWeakMap;m9=newWeakMap;rL=newWeakMap;h9=newWeakMap;g9=newWeakMap;yse=newWeakMap;bse=newWeakSet;nNe=function(t,e){letr="";if(r+=`${Ds(this,m9)}${this.boundary}${Ds(this,SM)}`,r+=`Content-Disposition: form-data; name="${kDt(t)}"`,nL(e)&&(r+=`; filename="${kDt(e.name)}"${Ds(this,SM)}`,r+=`Content-Type: ${e.type||"application/octet-stream"}`),Ds(this,yse).enableAdditionalHeaders===!0){letn=nL(e)?e.size:e.byteLength;n!=null&&!isNaN(n)&&(r+=`${Ds(this,SM)}Content-Length: ${n}`)}returnDs(this,rL).encode(`${r}${Ds(this,SM).repeat(2)}`)};eNe=newWeakSet;qDt=function(){lett=0;for(let[e,r]ofDs(this,g9)){letn=nL(r)?r:Ds(this,rL).encode(zDt(r)),o=nL(n)?n.size:n.byteLength;if(o==null||isNaN(o))return;t+=Q1e(this,bse,nNe).call(this,e,n).byteLength,t+=o,t+=Ds(this,gse)}returnString(t+Ds(this,h9).byteLength)}});varKDt=x((q4o,WDt)=>{"use strict";WDt.exports=typeofself=="object"?self.FormData:window.FormData});varGDt=x(Uc=>{"use strict";vari6r=Uc&&Uc.__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]}),a6r=Uc&&Uc.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),vq=Uc&&Uc.__importStar||function(t){if(t&&t.__esModule)returnt;vare={};if(t!=null)for(varrint)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&i6r(e,t,r);returna6r(e,t),e},CM=Uc&&Uc.__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(Uc,"__esModule",{value:!0});Uc.WebFormData=Uc.Node16FormData=Uc.Node18FormData=Uc.newFormData=void0;var_se=lq();functionoNe(t){returntypeoft=="object"&&t!=null&&"name"int}functions6r(){returnCM(this,void0,void0,function*(){lett;return_se.RUNTIME.type==="node"&&_se.RUNTIME.parsedVersion!=null&&_se.RUNTIME.parsedVersion>=18?t=newvse:_se.RUNTIME.type==="node"?t=newwse:t=newxse,yieldt.setup(),t})}Uc.newFormData=s6r;varvse=class{setup(){returnCM(this,void0,void0,function*(){this.fd=new(yieldPromise.resolve().then(()=>vq(RDt()))).FormData})}append(e,r){varn;(n=this.fd)===null||n===void0||n.append(e,r)}appendFile(e,r,n){varo,i;returnCM(this,void0,void0,function*(){n==null&&oNe(r)&&(n=r.name),rinstanceof(yieldPromise.r
`);o.enqueue(s)}catch(i){o.error(i)}})},cancel(){varo;returnx9(this,void0,void0,function*(){yield(o=r.return)===null||o===void0?void0:o.call(r)})}})}};Cu.StreamUtils=ONe;functionJLt(t,e){returnC9(this,arguments,function*(){varn,o;if(!t.body)throwe?.abort(),newAq.CohereError({message:"Attempted to iterate over a response with no body"});leti=newENe,a=newPM,s=PNe(t.body);try{for(varu=S9(O5r(s)),l;l=yieldVa(u.next()),!l.done;){letc=l.value;for(letdofa.decode(c)){letf=i.decode(d);f&&(yieldyieldVa(f))}}}catch(c){n={error:c}}finally{try{l&&!l.done&&(o=u.return)&&(yieldVa(o.call(u)))}finally{if(n)thrown.error}}for(letcofa.flush()){letd=i.decode(c);d&&(yieldyieldVa(d))}})}Cu._iterSSEMessages=JLt;functionO5r(t){returnC9(this,arguments,function*(){varr,n;leto=newUint8Array;try{for(vari=S9(t),a;a=yieldVa(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=E5r(o))!==-1;)yieldyieldVa(o.slice(0,c)),o=o.slice(c)}}catch(s){r={error:s}}finally{try{a&&!a.done&&(n=i.return)&&(yieldVa(n.call(i)))}finally{if(r)throwr.error}}o.length>0&&(yieldyieldVa(o))})}functionE5r(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}varENe=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]=T5r(e,":");returno.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},PM=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();thrownewAq.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);thrownewAq.CohereError({message:`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`})}thrownewAq.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}};Cu.LineDecoder=PM;PM.NEWLINE_CHARS=newSet([`
`)}}}}catch(w){a={error:w}}finally{try{m&&!m.done&&(s=h.return)&&(yield s.call(h))}finally{if(a)throw a.error}}for(let w of y.flush()){let S=(0,xi.parseAWSEvent)(w);if(S){let C=yield(0,xi.mapResponseFromBedrock)(c,u,S);_.push(JSON.stringify(C)+`
`)}}return _.end(),{ok:!0,body:_}}else{let g=yield p.body;return{ok:!0,body:yield(0,xi.mapResponseFromBedrock)(c,u,g)}}}catch(g){throw g}});xi.fetchOverride=Hun});var SP=x(Uue=>{"use strict";Object.defineProperty(Uue,"__esModule",{value:!0});Uue.CohereEnvironment=void 0;Uue.CohereEnvironment={Production:"https://api.cohere.com"}});var kM=x((v$t,que)=>{(function(t,e,r){typeof que<"u"&&que.exports?que.exports=r():typeof define=="function"&&define.amd?define(r):e[t]=r()})("urljoin",v$t,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 kLe=x(Vm=>{"use strict";var Vun=Vm&&Vm.__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]}),Wun=Vm&&Vm.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),J9=Vm&&Vm.__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)&&Vun(e,t,r);return Wun(e,t),e},Hue=Vm&&Vm.__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())})},Kun=Vm&&Vm.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Vm,"__esModule",{value:!0});Vm.V2=void 0;var w$t=J9(SP()),qm=J9(J()),Fs=J9(KE()),Hm=J9(xP()),x$t=Kun(kM()),CP=J9(ou()),FLe=class{constructor(e={}){this._options=e}chatStream(e,r){var n,o;return Hue(this,void 0,void 0,function*(){let i=yield((n=this._options.fetcher)!==null&&n!==void 0?n:qm.fetcher)({url:(0,x$t.default)((o=yield qm.Supplier.get(this._options.environment))!==null&&o!==void 0?o:w$t.CohereEnvironment.Production,"v2/chat"),method:"POST",headers:{Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield qm.Supplier.get(this._options.clientName))!=null?yield qm.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":qm.RUNTIME.type,"X-Fern-Runtime-Version":qm.RUNTIME.version},contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},Hm.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 qm.Stream({stream:i.body,parse:a=>Hue(this,void 0,void 0,function*(){return Hm.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 Fs.BadRequestError(i.error.body);case 401:th
`}});if(i.error.reason==="status-code")switch(i.error.statusCode){case 400:throw new Pe.BadRequestError(i.error.body);case 401:throw new Pe.UnauthorizedError(i.error.body);case 403:throw new Pe.ForbiddenError(i.error.body);case 404:throw new Pe.NotFoundError(i.error.body);case 422:throw new Pe.UnprocessableEntityError(ct.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new Pe.TooManyRequestsError(ct.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new Pe.ClientClosedRequestError(ct.ClientClosedRequestErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 500:throw new Pe.InternalServerError(i.error.body);case 501:throw new Pe.NotImplementedError(ct.NotImplementedErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 503:throw new Pe.ServiceUnavailableError(i.error.body);case 504:throw new Pe.GatewayTimeoutError(ct.GatewayTimeoutErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));default:throw new Qr.CohereError({statusCode:i.error.statusCode,body:i.error.body})}switch(i.error.reason){case"non-json":throw new Qr.CohereError({statusCode:i.error.statusCode,body:i.error.rawBody});case"timeout":throw new Qr.CohereTimeoutError;case"unknown":throw new Qr.CohereError({message:i.error.errorMessage})}})}generate(e,r){var n,o;return Ym(this,void 0,void 0,function*(){let i=yield((n=this._options.fetcher)!==null&&n!==void 0?n:Et.fetcher)({url:(0,a_.default)((o=yield Et.Supplier.get(this._options.environment))!==null&&o!==void 0?o:i_.CohereEnvironment.Production,"v1/generate"),method:"POST",headers:{Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield Et.Supplier.get(this._options.clientName))!=null?yield Et.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":Et.RUNTIME.type,"X-Fern-Runtime-Version":Et.RUNTIME.version},contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},ct.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 ct.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 Pe.BadRequestError(i.error.body);case 401:throw new Pe.UnauthorizedError(i.error.body);case 403:throw new Pe.ForbiddenError(i.error.body);case 404:throw new Pe.NotFoundError(i.error.body);case 422:throw new Pe.UnprocessableEntityError(ct.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new Pe.TooManyRequestsError(ct.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new Pe.ClientClosedRequestError(ct.ClientClosedRequestErrorBody.parseOrThrow(i.error.body,{u
`,"\r"]);NL.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function gK(){}function Tle(t,e,r){return!e||Ale[t]>Ale[r]?gK:e[t].bind(e)}function cu(t){let e=t.logger,r=t.logLevel??"off";if(!e)return _dn;let n=zzt.get(e);if(n&&n[0]===r)return n[1];let o={error:Tle("error",e,r),warn:Tle("warn",e,r),info:Tle("info",e,r),debug:Tle("debug",e,r)};return zzt.set(e,[r,o]),o}var Ale,WFe,_dn,zzt,AP,yK=b(()=>{TP();Ale={off:0,error:200,warn:300,info:400,debug:500},WFe=(t,e,r)=>{if(t){if(hzt(Ale,t))return t;cu(r).warn(`${e}wassetto${JSON.stringify(t)},expectedoneof${JSON.stringify(Object.keys(Ale))}`)}};_dn={error:gK,warn:gK,info:gK,debug:gK},zzt=new WeakMap;AP=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*vdn(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new ht("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 ht("Attempted to iterate over a response with no body");let r=new KFe,n=new NL,o=kFe(t.body);for await(let i of wdn(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*wdn(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"?b2(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let i;for(;(i=$zt(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function xdn(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var bK,XC,KFe,GFe=b(()=>{Iy();JC();hK();Bzt();hK();wle();Ple();yK();JC();XC=class t{constructor(e,r,n){this.iterator=e,bK.set(this,void 0),this.controller=r,tr(this,bK,n,"f")}static fromSSEResponse(e,r,n){let o=!1,i=n?cu(n):console;async function*a(){if(o)throw new ht("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let s=!1;try{for await(let u of vdn(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 gc(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 gc(void 0,l.error,l.message,void 0);yield{event:u.event,data:l}}}s=!0}catch(u){if(pK(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 NL,u=kFe(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 ht("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(pK(u))return;throw u}finally{s||r.abort()}}return new t(a,r,n)}[(bK=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,ce(this,bK,"f")),new t(()=>o(r),this.controller,ce(this,bK,"f"))]}toReadableStream(){let e=this,r;return FFe({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=b2(JSON.stringify(o)+`
${d}`)}returna},Le=Mdn(Wzt)});varDL,jle=b(()=>{Dr();Ga();ia();DL=classextendsqe{list(e,r={},n){returnthis._client.getAPIList(Le`/chat/completions/${e}/messages`,Cn,{query:r,...n})}}});varc_=b(()=>{JC()});functionSK(t){returnt!==void0&&"function"int&&t.function!==void0}functionKzt(t,e){letr={...t};returnObject.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}functionCK(t){returnt?.$brand==="auto-parseable-response-format"}functionLL(t){returnt?.$brand==="auto-parseable-tool"}functionGzt(t,e){return!e||!rke(e)?{...t,choices:t.choices.map(r=>(Zzt(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void0}}))}:OK(t,e)}functionOK(t,e){letr=t.choices.map(n=>{if(n.finish_reason==="length")thrownewm2;if(n.finish_reason==="content_filter")thrownewh2;returnZzt(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(o=>Ddn(e,o))??void0}:void0,parsed:n.message.content&&!n.message.refusal?jdn(e,n.message.content):null}}});return{...t,choices:r}}functionjdn(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}functionDdn(t,e){letr=t.tools?.find(n=>SK(n)&&n.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:LL(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}functionJzt(t,e){if(!t||!("tools"int)||!t.tools)return!1;letr=t.tools?.find(n=>SK(n)&&n.function?.name===e.function.name);returnSK(r)&&(LL(r)||r?.function.strict||!1)}functionrke(t){returnCK(t.response_format)?!0:t.tools?.some(e=>LL(e)||e.type==="function"&&e.function.strict===!0)??!1}functionZzt(t){for(leteoft||[])if(e.type!=="function")thrownewht(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}functionYzt(t){for(leteoft??[]){if(e.type!=="function")thrownewht(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)thrownewht(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}varv2=b(()=>{c_()});varw2,nke,oke=b(()=>{w2=t=>t?.role==="assistant",nke=t=>t?.role==="tool"});varike,Dle,Lle,EK,PK,Fle,TK,MP,AK,kle,$le,x2,Xzt,VM,Ble=b(()=>{Iy();c_();VM=class{constructor(){ike.add(this),this.controller=newAbortController,Dle.set(this,void0),Lle.set(this,()=>{}),EK.set(this,()=>{}),PK.set(this,void0),Fle.set(this,()=>{}),TK.set(this,()=>{}),MP.set(this,{}),AK.set(this,!1),kle.set(this,!1),$le.set(this,!1),x2.set(this,!1),tr(this,Dle,newPromise((e,r)=>{tr(this,Lle,e,"f"),tr(this,EK,r,"f")}),"f"),tr(this,PK,newPromise((e,r)=>{tr(this,Fle,e,"f"),tr(this,TK,r,"f")}),"f"),ce(this,Dle,"f").catch(()=>{}),ce(this,PK,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},ce(this,ike,"m",Xzt).bind(this))},0)}_connected(){this.ended||(ce(this,Lle,"f").call(this),this._emit("connect"))}getended(){returnce(this,AK,"f")}geterrored(){returnce(this,kle,"f")}getaborted(){returnce(this,$le,"f")}abort(){this.controller.abort()}on(e,r){return(ce(this,MP,"f")[e]||(ce(this,MP,"f")[e]=[])).push({listener:r}),this}off(e,r){letn=ce(this,MP,"f")[e];if(!n)returnthis;leto=n.findIndex(i=>i.listener===r);returno>=0&&n.splice(o,1),this}once(e,r){return(ce(this,MP,"f")[e]||(ce(this,MP,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){returnnewPromise((r,n)=>{tr(this,x2,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}asyncdone(){tr(this,x2,!0,"f"),awaitce(this,PK,"f")}_emit(e,...r){if(ce(this,AK,"f"))return;e==="end"&&(tr(this,AK,!0,"f"),ce(this,Fle,"f").call(this));letn=ce(this,MP,"f")[e];if(n&&(ce(this,MP,"f")[e]=n.filter(o=>!o.once),n.forEach(({listener:o})=>o(...r))),e==="abort"){leto=r[0];!ce(this,x2,"f")&&!n?.length&&Promise.reject(o),ce(t
\r`.includes(t[n]);)n++};return a()},hke=t=>Fdn(t,Kc.ALL^Kc.NUM)});var gke=b(()=>{GFe()});function $dn(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 ht(`missingfinish_reasonforchoice${d}`);let{content:h=null,function_call:m,tool_calls:g,...y}=l,_=l.role;if(!_)throw new ht(`missingroleforchoice${d}`);if(m){let{arguments:w,name:S}=m;if(w==null)throw new ht(`missingfunction_call.argumentsforchoice${d}`);if(!S)throw new ht(`missingfunction_call.nameforchoice${d}`);return{...p,message:{content:h,function_call:{arguments:w,name:S},role:_,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}return g?{...p,index:d,finish_reason:c,logprobs:f,message:{...y,role:_,content:h,refusal:l.refusal??null,tool_calls:g.map((w,S)=>{let{function:C,type:E,id:P,...T}=w,{arguments:I,name:N,...M}=C||{};if(P==null)throw new ht(`missingchoices[${d}].tool_calls[${S}].id
${Hle(t)}`);if(E==null)throw new ht(`missingchoices[${d}].tool_calls[${S}].type
${Hle(t)}`);if(N==null)throw new ht(`missingchoices[${d}].tool_calls[${S}].function.name
${Hle(t)}`);if(I==null)throw new ht(`missingchoices[${d}].tool_calls[${S}].function.arguments
${Hle(t)}`);return{...T,id:P,type:E,function:{...M,name:N,arguments:I}}})}}:{...p,message:{...y,content:h,role:_,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}),created:o,model:i,object:"chat.completion",...a?{system_fingerprint:a}:{}};return Gzt(u,e)}function Hle(t){return JSON.stringify(t)}var bc,RP,C2,WM,yke,Ule,bke,_ke,vke,qle,wke,nUt,FL,Vle=b(()=>{Iy();rUt();c_();v2();gke();dke();FL=class t extends S2{constructor(e){super(),bc.add(this),RP.set(this,void 0),C2.set(this,void 0),WM.set(this,void 0),tr(this,RP,e,"f"),tr(this,C2,[],"f")}get currentChatCompletionSnapshot(){return ce(this,WM,"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())),ce(this,bc,"m",yke).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)ce(this,bc,"m",bke).call(this,a);if(i.controller.signal?.aborted)throw new Bs;return this._addChatCompletion(ce(this,bc,"m",qle).call(this))}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),ce(this,bc,"m",yke).call(this),this._connected();let o=XC.fromReadableStream(e,this.controller),i;for await(let a of o)i&&i!==a.id&&this._addChatCompletion(ce(this,bc,"m",qle).call(this)),ce(this,bc,"m",bke).call(this,a),i=a.id;if(o.controller.signal?.aborted)throw new Bs;return this._addChatCompletion(ce(this,bc,"m",qle).call(this))}[(RP=new WeakMap,C2=new WeakMap,WM=new WeakMap,bc=new WeakSet,yke=function(){this.ended||tr(this,WM,void 0,"f")},Ule=function(r){let n=ce(this,C2,"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},ce(this,C2,"f")[r.index]=n,n)},bke=function(r){if(this.ended)return;let n=ce(this,bc,"m",nUt).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=ce(this,bc,"m",Ule).call(this,i);i.finish_reason&&(ce(this,bc,"m",vke).call(this,i),a.current_tool_call_index!=null&&ce(this,bc,"m",_ke).call(this,i,a.current_tool_call_index));for(let s of o.delta.tool_calls??[])a.current_tool_call_index!==s.index&&(ce(this,bc,"m",vke).call(this,i),a.current_tool_call_index!=null&&ce(this,bc,"m",_ke).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))}}},_ke=function(r,n){if(ce(this,bc,"m",Ule).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=ce(this,RP,"f")?.tools?.find(s=>SK(s)&&s.funct
`);this.baseURL=s.baseURL,this.timeout=s.timeout??_$e.DEFAULT_TIMEOUT,this.logger=s.logger??console;letu="warn";this.logLevel=u,this.logLevel=WFe(s.logLevel,"ClientOptions.logLevel",this)??WFe(d_("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??Szt(),tr(this,rce,Ozt,"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){returnHFe(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${HM}`}defaultIdempotencyKey(){return`stainless-node-retry-${RFe()}`}makeStatusError(e,r,n,o){returngc.generate(e,r,n,o)}buildURL(e,r,n){leto=!ce(this,b$e,"m",PUt).call(this)&&n||this.baseURL,i=fzt(e)?newURL(e):newURL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();returnmzt(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){returnnewjL(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(cu(this).debug(`[${l}] sending request`,AP({retryOfRequestLogID:n,method:o.method,url:s,options:o,headers:a.headers})),o.signal?.aborted)thrownewBs;letf=newAbortController,p=awaitthis.fetchWithTimeout(s,a,u,f).catch(mK),h=Date.now();if(pinstanceofError){lety=`retrying, ${r} attempts remaining`;if(o.signal?.aborted)thrownewBs;let_=pK(p)||/timed? ?out/i.test(String(p)+("cause"inp?String(p.cause):""));if(r)returncu(this).info(`[${l}] connection ${_?"timed out":"failed"} - ${y}`),cu(this).debug(`[${l}] connection ${_?"timed out":"failed"} (${y})`,AP({retryOfRequestLogID:n,url:s,durationMs:h-d,message:p.message})),this.retryRequest(o,r,n??l);throwcu(this).info(`[${l}] connection ${_?"timed out":"failed"} - error; no more retries left`),cu(this).debug(`[${l}] connection ${_?"timed out":"failed"} (error; no more retries left)`,AP({retryOfRequestLogID:n,url:s,durationMs:h-d,message:p.message})),_?newKC:newqM({cause:p})}letm=[...p.headers.entries()].filter(([y])=>y==="x-request-id").map(([y,_])=>", "+y+": "+JSON.stringify(_)).join(""),g=`[${l}${c}${m}] ${a.method}${s}${p.ok?"succeeded":"failed"} with status ${p.status} in ${h-d}ms`;if(!p.ok){lety=awaitthis.shouldRetry(p);if(r&&y){letP=`retrying, ${r} attempts remaining`;returnawaitCzt(p.body),cu(this).info(`${g} - ${P}`),cu(this).debug(`[${l}] response error (${P})`,AP({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:h-d})),this.retryRequest(o,r,n??l,p.headers)}let_=y?"error; no more retries left":"error; not retryable";cu(this).info(`${g} - ${_}`);letw=awaitp.text().catch(P=>mK(P).message),S=yzt(w),C=S?void0:w;throwcu(this).debug(`[${l}] response error (${_})`,AP({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,message:C,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 oO(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 eh(t,e){return{name:t.function?.name,args:t.function?.arguments,id:t.id,error:e,type:"invalid_tool_call"}}var v$e,Hd,IUt=b(()=>{FB();dSe();GA();hj();bE();v$e=class extends Cj{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(Wi(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=>Qm(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}},Hd=class extends v$e{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 wQe(this.zodSchema,e);if(r.success)return r.data;throw new Mh(`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 MUt=b(()=>{IUt()});var K2=b(()=>{MUt()});var w$e=b(()=>{_j()});function LP(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 rR=b(()=>{});var NUt,RUt,jUt,oce=b(()=>{NUt=Symbol("Let zodToJsonSchema decide on which parser to use"),RUt={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?`${cce(t.items,e)}[]`:"any[]";default:return""}}var_qt=b(()=>{});functionvqt(t,e){letr;returnWc(t)?r=qC(t):r=t,r.type==="function"&&e?.strict!==void0&&(r.function.strict=e.strict),r}functiondce(t){return"type"int&&t.type!=="function"&&t.type!=="custom"}functionwqt(t){returnt!=null&&typeoft=="object"&&"type"int&&t.type!=="function"}functionxqt(t){returntypeoft=="object"&&t!==null&&"metadata"int&&typeoft.metadata=="object"&&t.metadata!==null&&"customTool"int.metadata&&typeoft.metadata.customTool=="object"&&t.metadata.customTool!==null}functionnBe(t){return"type"int&&t.type==="custom"&&"custom"int&&typeoft.custom=="object"&&t.custom!==null}functionSqt(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}}}functionCqt(t){returnt.type==="tool_call"&&"isCustomTool"int&&t.isCustomTool===!0}functionOqt(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()}}functionEqt(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()}}}varPqt=b(()=>{ag();nF()});functionmce(t){returnt&&(/^o\d/.test(t)||t.startsWith("gpt-5"))}functionjfn(t){returnt!==void0&&typeoft.schema=="object"}functionDfn(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}functioniBe(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(!Ys.isInstance(t))thrownewError("Invalid generic chat message");returnDfn(t)}default:thrownewError(`Unknown message type: ${e}`)}}functionoBe(t,e){returnt.flatMap(r=>{letn=iBe(r);n==="system"&&mce(e)&&(n="developer");leto=typeofr.content=="string"?r.content:r.content.map(a=>Ib(a)?x6(a,Tqt):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=""),Wi(r)&&r.tool_calls?.length?(i.tool_calls=r.tool_calls.map(oO),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})}varG2,Tqt,BK,fce,pce,iO,hce=b(()=>{nO();$s();Zf();no();HC();ig();Pm();Db();K2();IL();w$e();rR();nF();_qt();Pqt();G2="__openai_function_call_ids__";Tqt={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=wB({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=G0e(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: ${h.message}`),newmj(m,JSON.stringify(e))}else{leth=va(o,this.schema);if(!h.valid){letm="Received tool input did not match expected schema";throwthis.verboseParsingErrors&&(m=`${m}
`)}`),newmj(m,JSON.stringify(e))}i=o}leta=T6(r),u=awaitgu.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(h){throwawaitu?.handleToolError(h),h}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;$A(e)&&(f=e.id),!f&&kYe(a)&&(f=a.toolCall.id);letp=Ffn({content:c,artifact:d,toolCallId:f,name:this.name,metadata:this.metadata});returnawaitu?.handleToolEnd(p),p}},iR=classextendsuBe{constructor(e){super(e),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:dt.object({input:dt.string().optional()}).transform(r=>r.input)})}call(e,r){letn=typeofe=="string"||e==null?{input:e}:e;returnsuper.call(n,r)}}});varzK=b(()=>{Lqt()});varlBe,Fqt=b(()=>{no();nO();zK();lBe=classextendsiR{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??lt("OPENAI_API_KEY"),n=e?.organization??lt("OPENAI_ORGANIZATION"),o={apiKey:r,organization:n,dangerouslyAllowBrowser:!0,baseURL:e?.baseUrl};this.client=newEr(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.image_url=="object"&&"url"ino.image_url&&typeofo.image_url.url=="string"&&o.image_url.url!==void0)??[])}async_call(e){letr={model:this.model,prompt:e,n:1,size:this.size,response_format:this.dallEResponseFormat,style:this.style,quality:this.quality,user:this.user};if(this.n>1){leti=awaitPromise.all(Array.from({length:this.n}).map(()=>this.client.images.generate(r)));returnthis.processMultipleGeneratedUrls(i)}letn=awaitthis.client.images.generate(r),o="";returnthis.dallEResponseFormat==="url"?[o]=n.data?.map(i=>i.url).filter(i=>i!=="undefined")??[]:[o]=n.data?.map(i=>i.b64_json).filter(i=>i!=="undefined")??[],o}};Object.defineProperty(lBe,"toolName",{enumerable:!0,configurable:!0,writable:!0,value:"dalle_api_wrapper"})});varkqt=b(()=>{Fqt()});var$qt=b(()=>{hce()});varBqt=b(()=>{yj()});varzqt=b(()=>{Pm();Bqt();zK()});varUqt=b(()=>{nO();hce();Iqt();aBe();Nqt();jqt();sBe();Dqt();nF();rR();kqt();$qt();zqt()});var_ce=b(()=>{Uqt()});varvce,qqt=b(()=>{PP();Ay();no();vce=classextendsqp{constructor(e){letr={maxConcurrency:2,...e};super(r),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"jina-clip-v2"}),Object.defineProperty(this,"batchSize",{enumerable:!0,configurable:!0,writable:!0,value:24}),Object.defineProperty(this,"baseUrl",{enumerable:!0,configurable:!0,writable:!0,value:"https://api.jina.
- `),Wfn={NO_LANGUAGE_WITH_CUSTOM_TOKENIZER:"Donotpassthelanguageoptiontocreatewhenusingacustomtokenizer.",LANGUAGE_NOT_SUPPORTED:`Language "%s" is not supported.
- ${Vfn}`,INVALID_STEMMER_FUNCTION_TYPE:"config.stemmerpropertymustbeafunction.",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:"Customstopwordsarraymustonlycontainstrings.",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:"Boostvaluemustbeanumbergreaterthan,orlessthan0.",INVALID_FILTER_OPERATION:"Youcanonlyuseoneoperationperfilter,yourequested%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:"Sortisdisabled.Pleasereadthedocumentationathttps://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.
Inputvectorsmustbeofthesizedeclaredintheschema,ascalculatingsimilaritybetweenvectorsofdifferentsizescanleadtounexpectedresults.`,WRONG_SEARCH_PROPERTY_TYPE:'Property "%s" is not searchable. Only "string" properties are searchable.',FACET_NOT_SUPPORTED:`Facetdoens't support the type "%s".`,INVALID_DISTANCE_SUFFIX:'Invaliddistancesuffix"%s".Validsuffixesare:cm,m,km,mi,yd,ft.',INVALID_SEARCH_MODE:'Invalidsearchmode"%s".Validmodesare:"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"isarequiredparameterwhenperforminghybridsearch.Pleaseprovideasearchterm.',INVALID_VECTOR_INPUT:'Invalid"vector"property.Expectedanobjectwith"value"and"property"properties,butgot"%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'installedinyourOramainstance.
`,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:"The last message in the session is not an assistant message. Cannot regenerate non-assistant messages."}});function r2t(t){return{raw:Number(t),formatted:iF(t)}}function n2t(t){if(t.id){if(typeof t.id!="string")throw Xt("DOCUMENT_ID_MUST_BE_STRING",typeof t.id);return t.id}return HK()}function fBe(t,e){for(let[r,n]of Object.entries(e)){let o=t[r];if(!(typeof o>"u")&&!(n==="geopoint"&&typeof o=="object"&&typeof o.lon=="number"&&typeof o.lat=="number")&&!(n==="enum"&&(typeof o=="string"||typeof o=="number"))){if(n==="enum[]"&&Array.isArray(o)){let i=o.length;for(let a=0;a<i;a++)if(typeof o[a]!="string"&&typeof o[a]!="number")return r+"."+a;continue}if(kP(n)){let i=mBe(n);if(!Array.isArray(o)||o.length!==i)throw Xt("INVALID_INPUT_VECTOR",r,i,o.length);continue}if(X2(n)){if(!Array.isArray(o))return r;let i=pBe(n),a=o.length;for(let s=0;s<a;s++)if(typeof o[s]!==i)return r+"."+s;continue}if(typeof n=="object"){if(!o||typeof o!="object")return r;let i=fBe(o,n);if(i)return r+"."+i;continue}if(typeof o!==n)return r}}}function o2t(t){return t==="geopoint"}function kP(t){return typeof t=="string"&&/^vector\[\d+\]$/.test(t)}function X2(t){return typeof t=="string"&&Kfn[t]}function pBe(t){return Gfn[t]}function mBe(t){let e=Number(t.slice(7,-1));switch(!0){case isNaN(e):throw Xt("INVALID_VECTOR_VALUE",t);case e<=0:throw Xt("INVALID_VECTOR_SIZE",t);default:return e}}var Kfn,Gfn,VK=b(()=>{Gc();du();du();Kfn={string:!1,number:!1,boolean:!1,enum:!1,geopoint:!1,"string[]":!0,"number[]":!0,"boolean[]":!0,"enum[]":!0},Gfn={"string[]":"string","number[]":"number","boolean[]":"boolean","enum[]":"enum"}});function i2t(){return{idToInternalId:new Map,internalIdToId:[],save:Jfn,load:Zfn}}function Jfn(t){return{internalIdToId:t.internalIdToId}}function Zfn(t,e){let{internalIdToId:r}=e;t.internalDocumentIDStore.idToInternalId.clear(),t.internalDocumentIDStore.internalIdToId=[];let n=r.length;for(let o=0;o<n;o++){let i=r[o];t.internalDocumentIDStore.idToInternalId.set(i,o+1),t.internalDocumentIDStore.internalIdToId.push(i)}}function zi(t,e){if(typeof e=="string"){let r=t.idToInternalId.get(e);if(r)return r;let n=t.idToInternalId.size+1;return t.idToInternalId.set(e,n),t.internalIdToId.push(e),n}return e>t.internalIdToId.length?zi(t,e.toString()):e}function Ry(t,e){if(t.internalIdToId.length<e)throw new Error(`InvalidinternalId${e}`);return t.internalIdToId[e-1]}var Ny=b(()=>{});function Xfn(t,e){return{sharedInternalDocumentStore:e,docs:{},count:0}}function Qfn(t,e){let r=zi(t.sharedInternalDocumentStore,e);return t.docs[r]}function epn(t,e){let r=e.length,n=Array.from({length:r});for(let o=0;o<r;o++){let i=zi(t.sharedInternalDocumentStore,e[o]);n[o]=t.docs[i]}return n}function tpn(t){return t.docs}function rpn(t,e,r){let n=zi(t.sharedInternalDocumentStore,e);return typeof t.docs[n]<"u"?!1:(t.docs[n]=r,t.count++,!0)}function npn(t,e){let r=zi(t.sharedInternalDocumentStore,e);return typeof t.docs[r]>"u"?!1:(delete t.docs[r],t.count--,!0)}function opn(t){return t.count}function ipn(t,e){let r=e;return{docs:r.docs,count:r.count,sharedInternalDocumentStore:t}}function apn(t){return{docs:t.docs,count:t.count}}function a2t(){return{create:Xfn,get:Qfn,getMultiple:epn,getAll:tpn,store:rpn,remove:npn,count:opn,load:ipn,save:apn}}var hBe=b(()=>{Ny()});function u2t(t,e){let r=[],n=t.plugins?.length;if(!n)return r;for(let o=0;o<n;o++)try{let i=t.plugins[o];typeof i[e]=="function"&&r.push(i[e])}catch(i){throw console.error("Caught error in getAllPluginsByHook:",i),Xt("PLUGIN_CRASHED")}return r}var s2t,l2t=b(()=>{Gc();s2t=["beforeInsert","afterInsert","beforeRemove","afterRemove","beforeUpdate","afterUpdate","beforeSearch","afterSearch","beforeInsertMultiple","afterInsertMultiple","beforeRemoveMultiple","afterRemoveMultiple","beforeUpdateMultiple","afterUpdateMultiple","beforeLoad","afterLoad","afterCreate"]});function y_(t,e,r,n){if(t.some(Mu))return(async()=>{for(let i of t)await i(e,r,n)})();for(let i of t)i(e,r,n)}function aF(t,e,r){if(t.some(Mu))return(async()=>{for(let o of t)await o(e,r)})();for(let o of
which is longer than the specified ${this.chunkSize}`),o.length>0)){letl=this.joinDocs(o,r);for(l!==null&&n.push(l);i>this.chunkOverlap||i+u+o.length*r.length>this.chunkSize&&i>0;)i-=awaitthis.lengthFunction(o[0]),o.shift()}o.push(s),i+=u}leta=this.joinDocs(o,r);returna!==null&&n.push(a),n}},d4=classtextendsnze{staticlc_name(){return"RecursiveCharacterTextSplitter"}constructor(e){super(e),Object.defineProperty(this,"separators",{enumerable:!0,configurable:!0,writable:!0,value:[`
`," ",""];thrownewError(`Language ${e} is not supported.`)}}});varL3t=b(()=>{D3t()});varF3t=b(()=>{L3t()});vark3t=b(()=>{F3t()});varoze=b(()=>{k3t()});var$3t,uO,Ade,B3t=b(()=>{or();oF();Gt();I3t();bt();ir();$3t=j(a4());oze();uO=require("obsidian");rh();Ade=class{constructor(e,r,n){this.app=e;this.dbOps=r;this.embeddingsManager=n;this.state={isIndexingPaused:!1,isIndexingCancelled:!1,indexedCount:0,totalFilesToIndex:0,processedFiles:newSet,currentIndexingNotice:null,indexNoticeMessage:null};leto=oe();this.rateLimiter=neweG(o.embeddingRequestsPerMin),this.embeddingBatchSize=o.embeddingBatchSize,this.checkpointInterval=8*this.embeddingBatchSize,wa(async()=>{leti=oe();this.rateLimiter=neweG(i.embeddingRequestsPerMin),this.embeddingBatchSize=i.embeddingBatchSize,this.checkpointInterval=8*this.embeddingBatchSize})}asyncindexVaultToVectorStore(e){letr=[];try{letn=awaitthis.embeddingsManager.getEmbeddingsAPI();if(!n)returnconsole.error("Embedding instance not found."),0;awaitthis.dbOps.checkAndHandleEmbeddingModelChange(n)&&(e=!0),e?(awaitthis.dbOps.clearIndex(n),this.dbOps.clearFilesMissingEmbeddings()):awaitthis.dbOps.garbageCollect();leti=awaitthis.getFilesToIndex(e);if(i.length===0)returnnewuO.Notice("Copilot vault index is up-to-date."),0;this.initializeIndexingState(i.length),this.createIndexingNotice(),this.dbOps.clearFilesMissingEmbeddings();leta=awaitthis.prepareAllChunks(i);if(a.length===0)returnnewuO.Notice("No valid content to index."),0;for(lets=0;s<a.length&&!this.state.isIndexingCancelled;s+=this.embeddingBatchSize){awaitthis.handlePause();letu=a.slice(s,s+this.embeddingBatchSize);try{awaitthis.rateLimiter.wait();letl=awaitn.embedDocuments(u.map(f=>f.content));if(!l||l.length!==u.length)thrownewError(`Embedding model returned ${l?.length??0} embeddings for ${u.length} documents`);for(letf=0;f<u.length;f++){letp=u[f],h=l[f];if(!h||!Array.isArray(h)||h.length===0){ie(`Invalid embedding for document ${p.fileInfo.path}: ${h}`),this.dbOps.markFileMissingEmbeddings(p.fileInfo.path);continue}try{awaitthis.dbOps.upsert({...p.fileInfo,id:this.getDocHash(p.content),content:p.content,embedding:h,created_at:Date.now(),nchars:p.content.length}),this.state.processedFiles.add(p.fileInfo.path)}catch(m){this.handleError(m,{filePath:p.fileInfo.path,errors:r}),this.dbOps.markFileMissingEmbeddings(p.fileInfo.path);continue}}this.state.indexedCount=this.state.processedFiles.size,this.updateIndexingNoticeMessage();letc=Math.floor((this.state.indexedCount-u.length)/this.checkpointInterval);Math.floor(this.state.indexedCount/this.checkpointInterval)>c&&(awaitthis.dbOps.saveDB(),console.log("Copilot index checkpoint save completed."))}catch(l){if(this.handleError(l,{filePath:u?.[0]?.fileInfo?.path,errors:r,batch:u}),this.isRateLimitError(l))break}}returnthis.finalizeIndexing(r),setTimeout(()=>{this.dbOps.saveDB().then(()=>{B("Copilot index final save completed."),this.dbOps.checkIndexIntegrity().catch(s=>{ie("Background integrity check failed:",s)})}).catch(s=>{ie("Background save failed:",s)})},100),this.state.indexedCount}catch(n){returnthis.handleError(n),0}}asyncprepareAllChunks(e){letr=awaitthis.embeddingsManager.getEmbeddingsAPI();if(!r)returnconsole.error("Embedding instance not found."),[];letn=Iu.getModelName(r),o=d4.fromLanguage("markdown",{chunkSize:Mj}),i=[];for(letaofe){lets=awaitthis.app.vault.cachedRead(a);if(!s?.trim())continue;letu=this.app.metadataCache.getFileCache(a),l={title:a.basename,path:a.path,embeddingModel:n,ctime:a.stat.ctime,mtime:a.stat.mtime,tags:u?.tags?.map(d=>d.tag)??[],extension:a.extension,metadata:{...u?.frontmatter??{},created:tu(newDate(a.stat.ctime)).display,modified:tu(newDate(a.stat.mtime)).display}};(awaito.createDocuments([s],[],{chunkHeader:`
`)),Array.from(u)}initializeIndexingState(e){this.state={isIndexingPaused:!1,isIndexingCancelled:!1,indexedCount:0,totalFilesToIndex:e,processedFiles:newSet,currentIndexingNotice:null,indexNoticeMessage:null}}createIndexingNotice(){lete=document.createDocumentFragment(),r=e.createEl("div",{cls:"copilot-notice-container"});this.state.indexNoticeMessage=r.createEl("div",{cls:"copilot-notice-message"}),this.updateIndexingNoticeMessage();letn=r.createEl("div",{cls:"copilot-notice-buttons"}),o=n.createEl("button");o.textContent="Pause",o.addEventListener("click",a=>{a.stopPropagation(),a.preventDefault(),this.state.isIndexingPaused?(this.resumeIndexing(),o.textContent="Pause"):(this.pauseIndexing(),o.textContent="Resume")});leti=n.createEl("button");returni.textContent="Stop",i.style.marginLeft="8px",i.addEventListener("click",a=>{a.stopPropagation(),a.preventDefault(),this.cancelIndexing()}),e.appendChild(this.state.indexNoticeMessage),e.appendChild(n),this.state.currentIndexingNotice=newuO.Notice(e,0),this.state.currentIndexingNotice}asynchandlePause(){if(this.state.isIndexingPaused){for(;this.state.isIndexingPaused&&!this.state.isIndexingCancelled;)awaitnewPromise(e=>setTimeout(e,100));if(!this.state.isIndexingCancelled){lete=awaitthis.getFilesToIndex();if(e.length===0){console.log("No files to index after filter change, stopping indexing"),this.cancelIndexing(),newuO.Notice("No files to index with current filters");return}this.state.totalFilesToIndex=e.length,console.log("Total files to index:",this.state.totalFilesToIndex),console.log("Files to index:",e),this.updateIndexingNoticeMessage()}}}pauseIndexing(){this.state.isIndexingPaused=!0}resumeIndexing(){this.state.isIndexingPaused=!1}updateIndexingNoticeMessage(){if(this.state.indexNoticeMessage){lete=this.state.isIndexingPaused?" (Paused)":"",r=["Copilot is indexing your vault...",`${this.state.indexedCount}/${this.state.totalFilesToIndex} files processed${e}`],n=oe(),o=th(n.qaInclusions);o.length>0&&r.push(`Inclusions: ${o.join(", ")}`);leta=[...XK(this.app),...th(n.qaExclusions)];a.length>0&&r.push(`Exclusions: ${a.join(", ")}`),this.state.indexNoticeMessage.textContent=r.join(`
`)}}isStringLengthError(e){if(!e)return!1;if(einstanceofRangeError&&e.message.toLowerCase().includes("string length"))return!0;letn=(e.message||e.toString()).toLowerCase();returnn.includes("string length")||n.includes("rangeerror")}handleError(e,r){letn=r?.filePath;if(n?(r.batch?console.error("Batch processing error:",{error:e,batchSize:r.batch.length||0,firstChunk:r.batch[0]?{path:r.batch[0].fileInfo?.path,contentLength:r.batch[0].content?.length,hasFileInfo:!!r.batch[0].fileInfo}:"No chunks in batch",errorType:e?.constructor?.name,errorMessage:e?.message}):console.error(`Error indexing file ${n}:`,e),r.errors?.push(n)):console.error("Fatal error during indexing:",e),this.state.currentIndexingNotice&&this.state.currentIndexingNotice.hide(),this.isStringLengthError(e)){newuO.Notice("Vault is too large for 1 partition, please increase the number of partitions in your Copilot QA settings!",1e4);return}if(this.isRateLimitError(e))return;leto=n?`Error indexing file ${n}. Check console for details.`:"Fatal error during indexing. Check console for details.";newuO.Notice(o)}isRateLimitError(e){returne?.message?.includes?.("rate limit")||!1}finalizeIndexing(e){if(this.state.currentIndexingNotice&&this.state.currentIndexingNotice.hide(),this.state.isIndexingCancelled){newuO.Notice("Indexing cancelled");return}e.length>0?newuO.Notice(`Indexing completed with ${e.length} errors. Check console for details.`):newuO.Notice("Indexing completed successfully!")}asyncreindexFile(e){try{letr=awaitthis.embeddingsManager.getEmbeddingsAPI();if(!r)return;if(awaitthis.dbOps.removeDocs(e.path),awaitthis.dbOps.checkAndHandleEmbeddingModelChange(r)){awaitthis.indexVaultToVectorStore(!0);return}leto=awaitthis.prepareAllChunks([e]);if(o.length===0)return;leti=awaitr.embedDocuments(o.map(a=>a.content));for(leta=0;a<o.length;a++){lets=o[a];awaitthis.dbOps.upsert({...s.fileInfo,id:this.getDocHash(s.content),content:s.content,embedding:i[a],created_at:Date.now(),nchars:s.content.length})}this.dbOps.markUnsavedChanges(),oe().debug&&console.log(`Reindexed file: ${e.path}`)}catch(r){this.handleError(r,{filePath:e.path})}}asynccancelIndexing(){console.log("Indexing cancelled by user"),this.state.isIndexingCancelled=!0,awaitnewPromise(e=>setTimeout(e,100)),this.state.currentIndexingNotice&&this.state.currentIndexingNotice.hide()}}});varQf={};os(Qf,{default:()=>zP});varrG,zP,Jc=b(()=>{xE();oF();bt();rG=require("obsidian");Ede();A3t();B3t();zP=classt{constructor(){this.embeddingsManager=Iu.getInstance(),this.dbOps=newBP(app),this.indexOps=newAde(app,this.dbOps,this.embeddingsManager),this.eventHandler=newPde(app,this.indexOps,this.dbOps),this.initializationPromise=this.initialize(),this.setupSettingsSubscription()}staticgetInstance(){returnt.instance||(t.instance=newt),t.instance}setupSettingsSubscription(){this.lastKnownSettings={...oe()};lete=async()=>{letr=oe(),n=this.lastKnownSettings;if(this.lastKnownSettings={...r},r.enableIndexSync!==n?.enableIndexSync){leto=awaitthis.dbOps.getDbPath();this.dbOps.getCurrentDbPath()!==o&&awaitthis.dbOps.initializeDB(awaitthis.embeddingsManager.getEmbeddingsAPI())}};wa(()=>{this.initializationPromise=e()})}asyncinitialize(){try{lete=3;for(;e>0;)try{letr=awaitthis.embeddingsManager.getEmbeddingsAPI();awaitthis.dbOps.initializeDB(r);break}catch(r){if(rinstanceofrn&&r.message.includes("Vault adapter not available")&&(e--,e>0)){awaitnewPromise(n=>setTimeout(n,100));continue}newrG.Notice("Failed to initialize vector store. Please make sure you have a valid API key for your embedding model and restart the plugin."),console.error("Failed to initialize vector store:",r);break}}catch(e){console.error("Failed to initialize vector store:",e)}}asyncwaitForInitialization(){awaitthis.initializationPromise}asyncindexVaultToVectorStore(e){returnawaitthis.waitForInitialization(),rG.Platform.isMobile&&oe().disableIndexOnMobile?(newrG.Notice("Indexing is disabled on mobile devices"),0):this.indexOps.indexVaultToVectorStore(e)}asyncclearIndex(){awaitthis.waitForInitialization(),aw
</url_content>`),u?.error&&(i[u.original]=u.error)}),{urlContext:n,imageUrls:o,processedErrorUrls:i}}getMentions(){return this.mentions}clearMentions(){this.mentions.clear()}}});var X3t,Rde,Q3t=b(()=>{Gt();X3t=j(a4()),Rde=class t{constructor(){this.cacheDir=".copilot/pdf-cache"}static getInstance(){return t.instance||(t.instance=new t),t.instance}async ensureCacheDir(){await app.vault.adapter.exists(this.cacheDir)||(B("Creating PDF cache directory:",this.cacheDir),await app.vault.adapter.mkdir(this.cacheDir))}getCacheKey(e){let r=`${e.path}:${e.stat.size}:${e.stat.mtime}`,n=(0,X3t.MD5)(r).toString();return B("Generated cache key for PDF:",{path:e.path,key:n}),n}getCachePath(e){return`${this.cacheDir}/${e}.json`}async get(e){try{let r=this.getCacheKey(e),n=this.getCachePath(r);if(await app.vault.adapter.exists(n)){B("Cache hit for PDF:",e.path);let o=await app.vault.adapter.read(n);return JSON.parse(o)}return B("Cache miss for PDF:",e.path),null}catch(r){return ie("Error reading from PDF cache:",r),null}}async set(e,r){try{await this.ensureCacheDir();let n=this.getCacheKey(e),o=this.getCachePath(n);B("Caching PDF response for:",e.path),await app.vault.adapter.write(o,JSON.stringify(r))}catch(n){ie("Error writing to PDF cache:",n)}}async clear(){try{if(await app.vault.adapter.exists(this.cacheDir)){let e=await app.vault.adapter.list(this.cacheDir);B("Clearing PDF cache, removing files:",e.files.length);for(let r of e.files)await app.vault.adapter.remove(r)}}catch(e){ie("Error clearing PDF cache:",e)}}}});function UP(t){if(!t||typeof t!="object")return!1;let e=t.message||t.toString();return e.includes("Request rate limit exceeded")||e.includes("RATE_LIMIT_EXCEEDED")||e.includes("429")||t.status===429}function eHt(t){let r=(t?.message||t?.toString()||"").match(/Try again in ([\d\w\s]+)/);return r?r[1]:"some time"}var oG=b(()=>{});var tHt,jde,rHt,Nde,nHt=b(()=>{tHt=require("obsidian"),Nde=class{constructor(e){this.vault=e;bwe(this,jde)}async load(e){let r=await this.vault.read(e),{nodes:n=[],edges:o=[]}=JSON.parse(r),i=await Promise.all(n.map(async u=>{if(u.type==="file"&&u.file){let l=this.vault.getAbstractFileByPath(u.file),c=l instanceof tHt.TFile?await this.vault.cachedRead(l):"";return{...u,content:c}}return u.type==="text"?{...u,content:u.text??""}:{...u,content:""}})),a=[...o];SGe(this,jde,rHt).call(this,i,a);let s=Object.fromEntries(i.map(u=>[u.id,u]));return{nodes:i,edges:a,byId:s}}buildPrompt(e){let r=new Map,n=e.nodes.filter(s=>s.type==="group");for(let s of n){let u=e.nodes.filter(l=>{if(l.id===s.id)return!1;let c=l.x+l.width/2,d=l.y+l.height/2;return c>=s.x&&d>=s.y&&c<=s.x+s.width&&d<=s.y+s.height});r.set(s.label||s.id,u)}let o=`This canvas contains the following elements:
`,e)}return e}async handleError(e,r,n){let o=eo(e);ie("Error during LLM invocation:",o);let i=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}`,ie(i),r&&n){n("");let u=s.search("Troubleshooting URL");s=u!==-1?s.slice(0,u):s,o.search(/401|invalid|not valid/gi)!==-1&&(s=`Somethingwentwrong.PleasecheckifyouhavesetyourAPIkey.
ErrorDetails:`+s),r({message:s,isErrorMessage:!0,sender:Zg,isVisible:!0,timestamp:tu(new Date)})}else new iHt.Notice(s),ie(i)}}});var __,g4=b(()=>{__=class{constructor(e,r){this.updateCurrentAiMessage=e;this.modelAdapter=r;this.hasOpenThinkBlock=!1;this.fullResponse="";this.shouldTruncate=!1}handleClaude37Chunk(e){let r="";for(let n of e)switch(n.type){case"text":r+=n.text;break;case"thinking":return this.hasOpenThinkBlock||(this.fullResponse+=`
ExplicitChunks:`,s),console.log("Orama Chunks: ",l),console.log("Combined Chunks: ",c),console.log("Max Orama Score: ",f),h?console.log("Reranked Chunks: ",d):console.log("No reranking applied.")),d})}async rewriteQuery(r){try{return await Cee(async()=>{let n=await this.queryRewritePrompt.format({question:r}),o=await Od(()=>Vd.instance.getCurrentChainManager().chatModelManager.getChatModel().bind({temperature:0}).invoke(n));return o&&"content"in o?Aj(o.content):(console.warn("Unexpected rewrittenQuery format. Falling back to original query."),r)},oz)}catch(n){return console.error("Error in rewriteQuery:",n),r}}async getExplicitChunks(r){let n=[];for(let o of r){let i=await zP.getInstance().getDb(),a=await BP.getDocsByPath(i,o.path);if(a){let s=a.map(u=>new nh({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)}}return n}async getOramaChunks(r,n,o){let i;try{i=await this.convertQueryToVector(r)}catch(l){throw console.error("Error in convertQueryToVector, please ensure your embedding model is working and has an adequate context length:",l,`
Query:`,r),l}let a=await zP.getInstance().getDb(),s={similarity:this.options.minSimilarityScore,limit:this.options.maxK,includeVectors:!0};if(n.length>0){let l;o||(o=.5),l=1-o;let c=!0;for(let d of n)if(!d.startsWith("#")){c=!1;break}c&&(oe().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}}else s.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);B("==== Daily note date range: ====",d[0],d[d.length-1]);let f=Jg(d.join(", "),app.vault),h=(await this.getExplicitChunks(f)).map(w=>({...w,metadata:{...w.metadata,includeInContext:!0}}));B("==== Modified time range: ====",l,c),s.where={mtime:{between:[l,c]}};let g=(await Kp(a,s)).hits.map(w=>new nh({pageContent:w.document.content,metadata:{...w.document.metadata,score:w.score,path:w.document.path,mtime:w.document.mtime,ctime:w.document.ctime,title:w.document.title,id:w.document.id,embeddingModel:w.document.embeddingModel,tags:w.document.tags,extension:w.document.extension,created_at:w.document.created_at,nchars:w.document.nchars}})),y=[...h,...g];return Array.from(new Set(y.map(w=>w.metadata.id))).map(w=>y.find(S=>S.metadata.id===w)).filter(w=>w!==void 0)}oe().debug&&console.log(`====OramaSearchParams:====
`,s);let u=await Kp(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):((typeof l.score!="number"||isNaN(l.score))&&console.warn("NaN/invalid score detected:",{score:l.score,path:l.document.path,title:l.document.title}),new nh({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)}async convertQueryToVector(r){let o=await(await Iu.getInstance().getEmbeddingsAPI()).embedQuery(r);if(o.length===0)throw new Error("Query embedding returned an empty vector");return o}generateDailyNoteDateRange(r,n){let o=[],i=new Date(r),a=new Date(n),s=new Date(i);for(;s<=a;)o.push(`[[${s.toLocaleDateString("en-CA")}]]`),s.setDate(s.getDate()+1);return o}filterAndFormatChunks(r,n){let o=this.options.minSimilarityScore,i=r.filter(u=>{let l=u.metadata.score;return typeof l!="number"||isNaN(l)?!0:l>=o}),a=new Set(n.map(u=>u.pageContent)),s=[...n];for(let u of i){let l=u.pageContent;a.has(l)||(a.add(l),s.push(u))}return s.map(u=>({...u,metadata:{...u.metadata,includeInContext:!0}}))}}});var Sze,xze,hR,Bde=b(()=>{Gt();or();Sze=require("obsidian");oze();xze={maxChars:Mj,overlap:0,maxBytesTotal:10*1024*1024},hR=class{constructor(e){this.app=e;this.cache=new Map;this.memoryUsage=0;this.splitter=d4.fromLanguage("markdown",{chunkSize:Mj,chunkOverlap:0,separators:[`
`).map(l=>l.trim()),o=[r],i=newSet,a=null;for(letlofn)if(!(!l||l==="")){if(l.toUpperCase().includes("QUERIES")){a="queries";continue}if(l.toUpperCase().includes("TERMS")||l.toUpperCase().includes("KEYWORDS")){a="terms";continue}if(a==="queries"&&o.length<=this.config.maxVariants){letc=l.replace(/^[-•*\d.)\s]+/,"").trim();c&&c!==r&&o.push(c)}elseif(a==="terms"){letc=l.replace(/^[-•*\d.)\s]+/,"").trim().toLowerCase();c&&this.isValidTerm(c)&&i.add(c)}}if(o.length===1&&i.size===0)for(letlofn.slice(0,this.config.maxVariants))l&&!l.toUpperCase().includes("QUERY")&&o.push(l);lets=this.extractSalientTermsFromOriginal(r),u=o.slice(1);return{queries:o.slice(0,this.config.maxVariants+1),salientTerms:s,originalQuery:r,expandedQueries:u.slice(0,this.config.maxVariants),expandedTerms:Array.from(i)}}fallbackExpansion(e){letr=this.extractTermsFromQueries([e]),n=newSet([e]);for(letiofr)if(i.length>=3){leta=efe.generateVariants(i);for(letsofa.slice(0,3))if(s!==i){letu=e.toLowerCase().replace(newRegExp(`\\b${i}\\b`,"gi"),s);u!==e.toLowerCase()&&n.add(u)}}return{queries:[e],salientTerms:r,originalQuery:e,expandedQueries:[],expandedTerms:[]}}extractTermsFromQueries(e){letr=newSet;for(letnofe){leto=n.toLowerCase().replace(/[^\w\s-]/g," ").split(/\s+/);for(letiofo)this.isValidTerm(i)&&(r.add(i),i.includes("-")&&i.split("-").forEach(a=>{this.isValidTerm(a)&&r.add(a)}))}returnArray.from(r)}isValidTerm(e){returne.length>=this.config.minTermLength&&/^[\w-]+$/.test(e)}cacheResult(e,r){if(this.cache.size>=this.config.cacheSize){letn=this.cache.keys().next().value;n&&this.cache.delete(n)}this.cache.set(e,r)}clearCache(){this.cache.clear(),B("QueryExpander: Cache cleared")}getCacheSize(){returnthis.cache.size}asyncexpandQueries(e){return(awaitthis.expand(e)).queries}};rfe.PROMPT_TEMPLATE=`Generate alternative search queries and semantically related terms for the following query:
`,"\r"]);WP.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function EG(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 qze=b(()=>{});async function*Ihn(t,e){if(!t.body)throw e.abort(),new Vr("Attempted to iterate over a response with no body");let r=new Hze,n=new WP,o=EG(t.body);for await(let i of Mhn(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*Mhn(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=YHt(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function Rhn(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var dO,Hze,pfe=b(()=>{yG();C_();Uze();qze();VP();C_();dO=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 Ihn(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 Zc.generate(void 0,`SSEError:${a.data}`,a.data,Vze(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 WP,s=EG(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 $ze({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)+`
`),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]=Rhn(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}}});async function XHt(t,e,r){if(t=await t,jhn(t))return t;if(Nhn(t)){let o=await t.blob();e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=PG(o)?[await o.arrayBuffer()]:[o];return new ufe(i,e,r)}let n=await Dhn(t);if(e||(e=Fhn(t)??"unknown_file"),!r?.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new ufe(n,e,r)}async function Dhn(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(PG(t))e.push(await t.arrayBuffer());else if(khn(t))for await(let r of t)e.push(r);else throw new Error(`Unexpecteddatatype:${typeoft};constructor:${t?.constructor?.name};props:${Lhn(t)}`);return e}function Lhn(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function Fhn(t){return Wze(t.name)||Wze(t.filename)||Wze(t.path)?.split(/[\\/]/).pop()}var Nhn,jhn,PG,Wze,khn,Kze,Gze=b(()=>{yG();yG();Nhn=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",jhn=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&PG(t),PG=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";Wze=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},khn=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",Kze=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody"});async function nVt(t){let{response:e}=t;if(t.options.stream)return E4("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):dO.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 E4("response",e.status,e.url,e.headers,i),oVt(i,e)}let o=await e.text();return E4("response",e.status,e.url,e.headers,o),o}function oVt(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}function Hhn(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let o=n[1]||0,i=n[2]||0,a=n[3]||0;return{browser:e,version:`${o}.${i}.${a}`}}}return null}function TG(t){if(!t)return!0;for(let e in t)return!1;return!0}function iVt(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function rVt(t,e){for(let r in e){if(!iVt(e,r))continue;let n=r.toLowerCase();if(!n)continue;let o=e[r];o===null?delete t[n]:o!==void 0&&(t[n]=o)}}function E4(t,...e){typeof process<"u"&&process?.env?.DEBUG==="true"&&console.log(`Anthropic:DEBUG:${t}`,...e)}var Bhn,zhn,mfe,gfe,yfe,bfe,Zze,Vze,Uhn,Dy,qhn,QHt,eVt,tVt,Vhn,Whn,Khn,Ghn,Jhn,Jze,dfe,_fe,Zhn,aVt,Yhn,hfe,VP=b(()=>{zHt();pfe();C_();yG();Gze();Bhn=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},zhn=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private ac
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){returnPfe.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}})}};wR.Batches=SF;wR.BetaMessageBatchesPage=A4});varpO,sUe=b(()=>{KP();Yze();Yze();aUe();aUe();pO=classextendsYc{constructor(){super(...arguments),this.models=newxF(this._client),this.messages=newwR(this._client)}};pO.Models=xF;pO.BetaModelInfosPage=P4;pO.Messages=wR});varCF,uUe=b(()=>{KP();CF=classextendsYc{create(e,r){returnthis._client.post("/v1/complete",{body:e,timeout:this._client._options.timeout??6e5,...r,stream:e.stream??!1})}}});varOF,R4,lUe=b(()=>{KP();VP();AG();Xze();C_();OF=classextendsYc{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){returnDy(e)?this.list({},e):this._client.getAPIList("/v1/messages/batches",R4,{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)thrownewVr(`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)=>T4.fromResponse(i.response,i.controller))}},R4=classextendsfO{};OF.MessageBatchesPage=R4});vartp,Bn,Fy,xR,DG,Tfe,LG,FG,Afe,kG,JP,$G,Ife,Mfe,N4,Rfe,Nfe,cUe,pVt,dUe,fUe,pUe,mUe,mVt,hVt,jfe,gVt=b(()=>{C_();pfe();eUe();tp=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},Bn=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)},hVt="__json_buf",jfe=classt{constructor(){Fy.add(this),this.messages=[],this.receivedMessages=[],xR.set(this,void0),this.controller=newAbortController,DG.set(this,void0),Tfe.set(this,()=>{}),LG.set(this,()=>{}),FG.set(this,void0),Afe.set(this,()=>{}),kG.set(this,()=>{}),JP.set(this,{}),$G.set(this,!1),Ife.set(this,!1),Mfe.set(this,!1),N4.set(this,!1),Rfe.set(this,void0),Nfe.set(this,void0),dUe.set(this,e=>{if(tp(this,Ife,!0,"f"),einstanceofError&&e.name==="AbortError"&&(e=newKd),einstanceofKd)returntp(this,Mfe,!0,"f"),this._emit("abort",e);if(einstanceofVr)returnthis._emit("error",e);if(einstanceofError){letr=newVr(e.message);returnr.cause=e,this._emit("error",r)}returnthis._emit("error",newVr(String(e)))}),tp(this,DG,newPromise((e,r)=>{tp(this,Tfe,e,"f"),tp(this,LG,r,"f")}),"f"),tp(this,FG,newPromise((e,r)=>{tp(this,Afe,e,"f"),tp(this,kG,r,"f")}),"f"),Bn(this,DG,"f").catch(()=>{}),Bn(this,FG,"f").catch(()=>{})}getresponse(){returnBn(this,Rfe,"f")}getrequest_id(){returnBn(this,Nfe,"f")}asyncwithResponse(){lete=awaitBn(this,DG,"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;
Pleasemigratetoanewermodel.Visithttps://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 jfe.createMessage(this,e,r)}countTokens(e,r){return this._client.post("/v1/messages/count_tokens",{body:e,...r})}},yVt={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};ZP.Batches=OF;ZP.MessageBatchesPage=R4});var SR,EF,gUe=b(()=>{KP();VP();AG();SR=class extends Yc{retrieve(e,r){return this._client.get(`/v1/models/${e}`,r)}list(e={},r){return Dy(e)?this.list({},e):this._client.getAPIList("/v1/models",EF,{query:e,...r})}},EF=class extends fO{};SR.ModelInfosPage=EF});var bVt=b(()=>{sVt();sUe();uUe();hUe();gUe()});var _Vt,Ri,Qpi,emi,vVt=b(()=>{VP();C_();Gze();bVt();uUe();gUe();sUe();hUe();Ri=class extends yfe{constructor({baseURL:e=_fe("ANTHROPIC_BASE_URL"),apiKey:r=_fe("ANTHROPIC_API_KEY")??null,authToken:n=_fe("ANTHROPIC_AUTH_TOKEN")??null,...o}={}){let i={apiKey:r,authToken:n,...o,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&aVt())throw new Vr(`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=newCF(this),this.messages=newZP(this),this.models=newSR(this),this.beta=newpO(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&&!TG(r)?r:n!=null&&!TG(n)?n:{}}apiKeyAuth(e){returnthis.apiKey==null?{}:{"X-Api-Key":this.apiKey}}bearerAuth(e){returnthis.authToken==null?{}:{Authorization:`Bearer ${this.authToken}`}}};_Vt=Ri;Ri.Anthropic=_Vt;Ri.HUMAN_PROMPT=`
Assistant:`;Ri.DEFAULT_TIMEOUT=6e5;Ri.AnthropicError=Vr;Ri.APIError=Zc;Ri.APIConnectionError=_R;Ri.APIConnectionTimeoutError=O4;Ri.APIUserAbortError=Kd;Ri.NotFoundError=wG;Ri.ConflictError=xG;Ri.RateLimitError=CG;Ri.BadRequestError=bG;Ri.AuthenticationError=_G;Ri.InternalServerError=OG;Ri.PermissionDeniedError=vG;Ri.UnprocessableEntityError=SG;Ri.toFile=XHt;Ri.fileFromPath=lfe;Ri.Completions=CF;Ri.Messages=ZP;Ri.Models=SR;Ri.ModelInfosPage=EF;Ri.Beta=pO;({HUMAN_PROMPT:Qpi,AI_PROMPT:emi}=Ri)});functionyUe(t){lete=[];for(letroft)r.type==="tool_use"&&e.push({name:r.name,args:r.input,id:r.id,type:"tool_call"});returne}varBG,bUe=b(()=>{Db();BG=classextendswj{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){thrownewMh(`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;thrownewMh(`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)?yUe(a.content)[0]:[]});if(r[0]===void0)thrownewError("No parseable tool calls provided to AnthropicToolsOutputParser.");let[n]=r;returnawaitthis._validateResult(n.args)}}});functionwVt(t){if(t)returnt==="any"?{type:"any"}:t==="auto"?{type:"auto"}:typeoft=="string"?{type:"tool",name:t}:t}varxVt=b(()=>{});functionSVt(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}varCVt=b(()=>{});functionOVt(t){lete=wB({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(`
`))}functionsgn(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(newXs({content:[{type:"tool_result",content:r.content,tool_use_id:r.tool_call_id}]}))}elsee.push(newXs({content:[{type:"tool_result",content:_Ue(r.content),tool_use_id:r.tool_call_id}]}));elsee.push(r);returne}functionEVt(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}}function_Ue(t){lete=["tool_use","tool_result","input_json_delta"],r=["text","text_delta"];returntypeoft=="string"?t:t.map(o=>{if(Ib(o))returnx6(o,ugn);leti="cache_control"ino?o.cache_control:void0;if(o.type==="image_url"){leta;returntypeofo.image_url=="string"?a=OVt(o.image_url):a=OVt(o.image_url.url),{type:"image",source:a,...i?{cache_control:i}:{}}}else{if(SVt(o))returno;if(o.type==="document")return{...o,...i?{cache_control:i}:{}};if(o.type==="thinking")return{type:"thinking",thinking:o.thinking,signature:o.signature,...i?{cache_control:i}:{}};if(o.type==="redacted_thinking")return{type:"redacted_thinking",data:o.data,...i?{cache_control:i}:{}};if(r.find(a=>a===o.type)&&"text"ino)return{type:"text",text:o.text,...i?{cache_control:i}:{}};if(e.find(a=>a===o.type)){leta={...o};if("index"ina&&deletea.index,a.type==="input_json_delta"&&(a.type="tool_use"),"input"ina&&typeofa.input=="string")try{a.input=JSON.parse(a.input)}catch{a.input={}}return{...a,...i?{cache_control:i}:{}}}elsethrownewError("Unsupported message content format")}})}functionDfe(t){lete=sgn(t),r;e.length>0&&e[0]._getType()==="system"&&(r=t[0].content);leto=(r!==void0?e.slice(1):e).map(i=>{leta;if(i._getType()==="human")a="user";elseif(i._getType()==="ai")a="assistant";elseif(i._getType()==="tool")a="user";elsethrowi._getType()==="system"?newError("System messages are only permitted as the first passed message."):newError(`Message type "${i._getType()}" is not supported.`);if(Wi(i)&&i.tool_calls?.length){if(typeofi.content=="string")returni.content===""?{role:a,content:i.tool_calls.map(EVt)}:{role:a,content:[{type:"text",text:i.content},...i.tool_calls.map(EVt)]};{let{content:s}=i;return!i.tool_calls.every(l=>s.find(c=>(c.type==="tool_use"||c.type==="input_json_delta")&&c.id===l.id))&&console.warn('The "tool_calls" field on a message is only respected if content is a string.'),{role:a,content:_Ue(i.content)}}}elsereturn{role:a,content:_Ue(i.content)}});return{messages:lgn(o),system:r}}functionlgn(t){if(!t||t.length<=1)returnt;lete=[],r=t[0],n=i=>typeofi=="string"?[{type:"text",text:i}]:i,o=i=>i.role!=="user"||typeofi.content=="string"?!1:Array.isArray(i.content)&&i.content.every(a=>a.type==="tool_result");for(leti=1;i<t.length;i+=1){leta=t[i];o(r)&&o(a)?r={...r,content:[...n(r.content),...n(a.content)]}:(e.push(r),r=a)}returne.push(r),e}varugn,vUe=b(()=>{$s();CVt();ugn={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=wB({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.sourc
`,t}function wUe(t){let e;return t.status===400&&t.message.includes("tool")?e=Lfe(t,"INVALID_TOOL_RESULTS"):t.status===401?e=Lfe(t,"MODEL_AUTHENTICATION"):t.status===404?e=Lfe(t,"MODEL_NOT_FOUND"):t.status===429?e=Lfe(t,"MODEL_RATE_LIMIT"):e=t,e}var IVt=b(()=>{});function cgn(t){return!!(t.tools&&t.tools.length>0)}function dgn(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 fgn(t){return!!(t.thinking&&t.thinking.type==="enabled")}function pgn(t){return"input_schema"in t}function mgn(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 xUe,Ffe,MVt=b(()=>{vVt();$s();Zf();no();HC();ig();Kg();Pm();IL();ag();bUe();xVt();vUe();AVt();IVt();xUe=class extends Pu{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??lt("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 Ri(r))}getLsParams(e){let r=this.invocationParams(e);return{ls_provider:"anthropic",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:r.t
`):[]}};pg=newWeakMap;IF.NEWLINE_CHARS=newSet([`
`,"\r"]);IF.NEWLINE_REGEXP=/\r\n|[\n\r]/g});functionLUe(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}}}varQVt=b(()=>{});asyncfunction*Ign(t,e){if(!t.body)throwe.abort(),newHt("Attempted to iterate over a response with no body");letr=newFUe,n=newIF,o=LUe(t.body);forawait(letiofMgn(o))for(letaofn.decode(i)){lets=r.decode(a);s&&(yields)}for(letiofn.flush()){leta=r.decode(i);a&&(yielda)}}asyncfunction*Mgn(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=YVt(e))!==-1;)yielde.slice(0,i),e=e.slice(i)}e.length>0&&(yielde)}functionRgn(t,e){letr=t.indexOf(e);returnr!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}vargO,FUe,Vfe=b(()=>{zG();oh();XVt();QVt();yo();oh();gO=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(letaofIgn(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)thrownewRu(void0,s.error,void0,kUe(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")thrownewRu(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=newIF,s=LUe(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;returnnewIUe({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)+`
`),raw:this.chunks};returnthis.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))returnnull;let[r,n,o]=Rgn(e,":");returno.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}}});asyncfunctionzUe(t,e,r){if(t=awaitt,t6t(t))returnt;if(e6t(t)){leto=awaitt.blob();e||(e=newURL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file");leti=UG(o)?[awaito.arrayBuffer()]:[o];returnnewBfe(i,e,r)}letn=awaitjgn(t);if(e||(e=Lgn(t)??"unknown_file"),!r?.type){leto=n[0]?.type;typeofo=="string"&&(r={...r,type:o})}returnnewBfe(n,e,r)}asyncfunctionjgn(t){lete=[];if(typeoft=="string"||ArrayBuffer.isView(t)||tinstanceofArrayBuffer)e.push(t);elseif(UG(t))e.push(awaitt.arrayBuffer());elseif(Fgn(t))forawait(letroft)e.push(r);elsethrownewError(`Unexpected data type: ${typeoft}; constructor: ${t?.constructor?.name}; props: ${Dgn(t)}`);returne}functionDgn(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}functionLgn(t){return$Ue(t.name)||$Ue(t.filename)||$Ue(t.path)?.split(/[\\/]/).pop()}vare6t,t6t,UG,Ngn,$Ue,Fgn,UUe,ky,r6t,BUe,Wfe=b(()=>{zG();zG();e6t=t=>t!=null&&typeoft=="object"&&typeoft.url=="string"&&typeoft.blob=="function",t6t=t=>t!=null&&typeoft=="object"&&typeoft.name=="string"&&typeoft.lastModified=="number"&&UG(t),UG=t=>t!=null&&typeoft=="object"&&typeoft.size=="number"&&typeoft.type=="string"&&typeoft.text=="function"&&typeoft.slice=="function"&&typeoft.arrayBuffer=="function",Ngn=t=>t6t(t)||e6t(t)||NUe(t);$Ue=t=>{if(typeoft=="string")returnt;if(typeofBuffer<"u"&&tinstanceofBuffer)returnString(t)},Fgn=t=>t!=null&&typeoft=="object"&&typeoft[Symbol.asyncIterator]=="function",UUe=t=>t&&typeoft=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody",ky=asynct=>{lete=awaitr6t(t.body);returnMUe(e,t)},r6t=asynct=>{lete=newAUe;returnawaitPromise.all(Object.entries(t||{}).map(([r,n])=>BUe(e,r,n))),e},BUe=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(Ngn(r)){letn=awaitzUe(r);t.append(e,n)}elseif(Array.isArray(r))awaitPromise.all(r.map(n=>BUe(t,e+"[]",n)));elseif(typeofr=="object")awaitPromise.all(Object.entries(r).map(([n,o])=>BUe(t,`${e}[${n}]`,o)));elsethrownewTypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}}});asyncfunctionu6t(t){let{response:e}=t;if(t.options.stream)returnXP("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):gO.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();returnXP("response",e.status,e.url,e.headers,a),l6t(a,e)}leti=awaite.text();returnXP("response",e.status,e.url,e.headers,i),i}functionl6t(t,e){return!t||typeoft!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}functionqgn(){if(typeofnavigator>"u"||!navigator)returnnull;lett=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}oft){letn=r.exec(navigator.userAgent);if(n){leto=n[1]||0,i=n[2]||0,a=n[3]||0;return{browser:e,version:`${o}.${i}.${a}`}}}returnnull}functionc6t(t){if(!t)return!0;for(leteint)return!1;return!0}functiond6t(t,e){returnObject.prototype.hasOwnProperty.call(t,e)}functiona6t(t,e){for(letr
\r`.includes(t[n]);)n++};return a()},pqe=t=>oyn(t,Qc.ALL^Qc.NUM)});function ayn(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 Ht(`missingfinish_reasonforchoice${d}`);let{content:h=null,function_call:m,tool_calls:g,...y}=l,_=l.role;if(!_)throw new Ht(`missingroleforchoice${d}`);if(m){let{arguments:w,name:S}=m;if(w==null)throw new Ht(`missingfunction_call.argumentsforchoice${d}`);if(!S)throw new Ht(`missingfunction_call.nameforchoice${d}`);return{...p,message:{content:h,function_call:{arguments:w,name:S},role:_,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}return g?{...p,index:d,finish_reason:c,logprobs:f,message:{...y,role:_,content:h,refusal:l.refusal??null,tool_calls:g.map((w,S)=>{let{function:C,type:E,id:P,...T}=w,{arguments:I,name:N,...M}=C||{};if(P==null)throw new Ht(`missingchoices[${d}].tool_calls[${S}].id
${spe(t)}`);if(E==null)throw new Ht(`missingchoices[${d}].tool_calls[${S}].type
${spe(t)}`);if(N==null)throw new Ht(`missingchoices[${d}].tool_calls[${S}].function.name
${spe(t)}`);if(I==null)throw new Ht(`missingchoices[${d}].tool_calls[${S}].function.arguments
${spe(t)}`);return{...T,id:P,type:E,function:{...M,name:N,arguments:I}}})}}:{...p,message:{...y,content:h,role:_,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}),created:o,model:i,object:"chat.completion",...a?{system_fingerprint:a}:{}};return v6t(u,e)}function spe(t){return JSON.stringify(t)}var X4,Zi,xc,rT,Q4,IR,mqe,ipe,hqe,gqe,yqe,ape,bqe,P6t,e3,_qe=b(()=>{oh();cqe();Vfe();Z4();E6t();X4=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},Zi=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)},e3=class t extends Y4{constructor(e){super(),xc.add(this),rT.set(this,void 0),Q4.set(this,void 0),IR.set(this,void 0),X4(this,rT,e,"f"),X4(this,Q4,[],"f")}get currentChatCompletionSnapshot(){return Zi(this,IR,"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())),Zi(this,xc,"m",mqe).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)Zi(this,xc,"m",hqe).call(this,a);if(i.controller.signal?.aborted)throw new Ma;return this._addChatCompletion(Zi(this,xc,"m",ape).call(this))}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),Zi(this,xc,"m",mqe).call(this),this._connected();let o=gO.fromReadableStream(e,this.controller),i;for await(let a of o)i&&i!==a.id&&this._addChatCompletion(Zi(this,xc,"m",ape).call(this)),Zi(this,xc,"m",hqe).call(this,a),i=a.id;if(o.controller.signal?.aborted)throw new Ma;return this._addChatCompletion(Zi(this,xc,"m",ape).call(this))}[(rT=new WeakMap,Q4=new WeakMap,IR=new WeakMap,xc=new WeakSet,mqe=function(){this.ended||X4(this,IR,void 0,"f")},ipe=function(r){let n=Zi(this,Q4,"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},Zi(this,Q4,"f")[r.index]=n,n)},hqe=function(r){if(this.ended)return;let n=Zi(this,xc,"m",P6t).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=Zi(this,xc,"m",ipe).call(this,i);i.finish_reason&&(Zi(this,xc,"m",yqe).call(this,i),a.current_tool_call_index!=null&&Zi(this,xc,"m",gqe).call(this,i,a.current_tool_call_index));for(let s of o.delta.tool_calls??[])a.current_tool_call_index!==s.index&&(Zi(this,xc,"m",yqe).call(this,i),a.current_tool_call_index!=null&&Zi(this,xc,"m",gqe).call(this,i,a.current_tool_call_index)),a.cur
`);super({baseURL:a.baseURL,timeout:a.timeout??6e5,httpAgent:a.httpAgent,maxRetries:a.maxRetries,fetch:a.fetch}),this.completions=newkF(this),this.chat=neweT(this),this.embeddings=new$F(this),this.files=newRR(this),this.images=newVF(this),this.audio=newbO(this),this.moderations=newKF(this),this.models=newjR(this),this.fineTuning=newT_(this),this.vectorStores=newgg(this),this.beta=newP_(this),this.batches=newPR(this),this.uploads=newkR(this),this.responses=newFR(this),this.evals=newxO(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){returnPUe(e,{arrayFormat:"brackets"})}};K6t=Tr;Tr.OpenAI=K6t;Tr.DEFAULT_TIMEOUT=6e5;Tr.OpenAIError=Ht;Tr.APIError=Ru;Tr.APIConnectionError=YP;Tr.APIConnectionTimeoutError=fg;Tr.APIUserAbortError=Ma;Tr.NotFoundError=F4;Tr.ConflictError=k4;Tr.RateLimitError=B4;Tr.BadRequestError=j4;Tr.AuthenticationError=D4;Tr.InternalServerError=z4;Tr.PermissionDeniedError=L4;Tr.UnprocessableEntityError=$4;Tr.toFile=zUe;Tr.fileFromPath=zfe;Tr.Completions=kF;Tr.Chat=eT;Tr.ChatCompletionsPage=ER;Tr.Embeddings=$F;Tr.Files=RR;Tr.FileObjectsPage=UF;Tr.Images=VF;Tr.Audio=bO;Tr.Moderations=KF;Tr.Models=jR;Tr.ModelsPage=WF;Tr.FineTuning=T_;Tr.VectorStores=gg;Tr.VectorStoresPage=GF;Tr.VectorStoreSearchResponsesPage=JF;Tr.Beta=P_;Tr.Batches=PR;Tr.BatchesPage=MF;Tr.Uploads=kR;Tr.Responses=FR;Tr.Evals=xO;Tr.EvalListResponsesPage=zF});varJ6t,G6t,Z6t,bpe=b(()=>{J6t=Symbol("Let zodToJsonSchema decide on which parser to use"),G6t={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"},Z6t=t=>typeoft=="string"?{...G6t,basePath:["#"],definitions:{},name:t}:{...G6t,basePath:["#"],definitions:{},...t}});functionY6t(t){if(!t)return!0;for(leteint)return!1;return!0}variJ,Xqe=b(()=>{iJ=t=>"_def"int?t._def:t});varX6t,Qqe=b(()=>{bpe();Xqe();X6t=t=>{lete=Z6t(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])=>[iJ(o),{def:iJ(o),path:[...e.basePath,e.definitionPath,n],jsonSchema:void0}]))}}});functione2e(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}functionbo(t,e,r,n,o){t[e]=r,e2e(t,e,n,o)}varzR=b(()=>{});functionQ6t(){return{}}vart2e=b(()=>{});functione8t(t,e){letr={type:"array"};returnt.type?._def?.typeName!==re.ZodAny&&(r.items=Ar(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&bo(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&bo(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(bo(r,"minItems",t.exactLength.value,t.exactLength.message,e),bo(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}varr2e=b(()=>{xd();zR();Nu()});functiont8t(t,e){letr={type:"integer",format:"int64"};if(!t.checks)returnr;for(letnoft.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?bo(r,"minimum",n.value,n.message,e):bo(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),bo(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?bo(r,"maximum",n.value,n.message,e):bo(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),bo(r,"maximum",n.value,n.message,e));break;case"multipleOf":bo(r,"multipleOf",n.value,n.message,e);break}returnr}varn2e=b(()=>{zR()});functionr8t(){return{type:"boolean"}}varo2e=b(()=>{}
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:Lyn(t,e)};returnr.required.length||deleter.required,r}varw2e=b(()=>{Nu()});varv8t,x2e=b(()=>{Nu();v8t=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())returnAr(t.innerType._def,e);letr=Ar(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});returnr?{anyOf:[{not:{}},r]}:{}}});varw8t,S2e=b(()=>{Nu();w8t=(t,e)=>{if(e.pipeStrategy==="input")returnAr(t.in._def,e);if(e.pipeStrategy==="output")returnAr(t.out._def,e);letr=Ar(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Ar(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void0)}}});functionx8t(t,e){returnAr(t.type._def,e)}varC2e=b(()=>{Nu()});functionS8t(t,e){letn={type:"array",uniqueItems:!0,items:Ar(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};returnt.minSize&&bo(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&bo(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}varO2e=b(()=>{zR();Nu()});functionC8t(t,e){returnt.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Ar(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void0?r:[...r,n],[]),additionalItems:Ar(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Ar(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void0?r:[...r,n],[])}}varE2e=b(()=>{Nu()});functionO8t(){return{not:{}}}varP2e=b(()=>{});functionE8t(){return{}}varT2e=b(()=>{});varP8t,A2e=b(()=>{Nu();P8t=(t,e)=>Ar(t.innerType._def,e)});functionAr(t,e,r=!1){letn=e.seen.get(t);if(e.override){leta=e.override?.(t,e,n,r);if(a!==J6t)returna}if(n&&!r){leta=Fyn(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=$yn(t,t.typeName,e,r);returni&&Byn(t,e,i),o.jsonSchema=i,i}varFyn,kyn,$yn,Byn,Nu=b(()=>{xd();t2e();r2e();n2e();o2e();i2e();a2e();u2e();l2e();c2e();d2e();f2e();p2e();h2e();g2e();y2e();b2e();_2e();v2e();w2e();x2e();S2e();C2e();xpe();O2e();vpe();E2e();P2e();Spe();T2e();A2e();bpe();Fyn=(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:kyn(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}},kyn=(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("/")},$yn=(t,e,r,n)=>{switch(e){casere.ZodString:return_pe(t,r);casere.ZodNumber:returnb8t(t,r);casere.ZodObject:return_8t(t,r);casere.ZodBigInt:returnt8t(t,r);casere.ZodBoolean:returnr8t();casere.ZodDate:returns2e(t,r);casere.ZodUndefined:returnO8t();casere.ZodNull:returnm8t(r);casere.ZodArray:returne8t(t,r);casere.ZodUnion:casere.ZodDiscriminatedUnion:returng8t(t,r);casere.ZodIntersection:returnu8t(t,r);casere.ZodTuple:returnC8t(t,r);casere.ZodRecord:returnwpe(t,r);casere.ZodLiteral:returnl8t(t,r);casere.ZodEnum:returns8t(t);casere.ZodNativeEnum:returnf8t(t);casere.ZodNullable:returny8t(t,r);casere.ZodOptional:returnv8t(t,r);casere.ZodMap:returnd8t(t,r);casere.ZodSet:returnS8t(t,r);casere.ZodLazy:returnAr(t.getter()._def,r);casere.ZodPromise:returnx8t(t,r);casere.ZodNaN:casere.ZodNever:returnp8t();casere.ZodEffects:returna8t(t,r,n);casere.ZodAny:returnQ6t();casere.ZodUnknown:returnE8t();casere.ZodDefault:returni8t(t,
`),raw:this.chunks};returnthis.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))returnnull;let[r,n,o]=Xyn(e,":");returno.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},I3=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();thrownewed(`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);thrownewed(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}thrownewed("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}};I3.NEWLINE_CHARS=newSet([`
`,"\r","\v","\f","","","","\x85","\u2028","\u2029"]);I3.NEWLINE_REGEXP=/\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g});asyncfunctionJ2e(t,e,r){if(t=awaitt,r??(r=l5t(t)?{lastModified:t.lastModified,type:t.type}:{}),u5t(t)){leto=awaitt.blob();returne||(e=newURL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file"),newIpe([o],e,r)}letn=awaitebn(t);if(e||(e=rbn(t)??"unknown_file"),!r.type){leto=n[0]?.type;typeofo=="string"&&(r={...r,type:o})}returnnewIpe(n,e,r)}asyncfunctionebn(t){lete=[];if(typeoft=="string"||ArrayBuffer.isView(t)||tinstanceofArrayBuffer)e.push(t);elseif(Dpe(t))e.push(awaitt.arrayBuffer());elseif(nbn(t))forawait(letroft)e.push(r);elsethrownewError(`Unexpected data type: ${typeoft}; constructor: ${t?.constructor?.name}; props: ${tbn(t)}`);returne}functiontbn(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}functionrbn(t){returnK2e(t.name)||K2e(t.filename)||K2e(t.path)?.split(/[\\/]/).pop()}varu5t,l5t,Dpe,Qyn,K2e,nbn,Z2e,pJ,c5t,G2e,Lpe=b(()=>{cJ();cJ();u5t=t=>t!=null&&typeoft=="object"&&typeoft.url=="string"&&typeoft.blob=="function",l5t=t=>t!=null&&typeoft=="object"&&typeoft.name=="string"&&typeoft.lastModified=="number"&&Dpe(t),Dpe=t=>t!=null&&typeoft=="object"&&typeoft.size=="number"&&typeoft.type=="string"&&typeoft.text=="function"&&typeoft.slice=="function"&&typeoft.arrayBuffer=="function",Qyn=t=>l5t(t)||u5t(t)||q2e(t);K2e=t=>{if(typeoft=="string")returnt;if(typeofBuffer<"u"&&tinstanceofBuffer)returnString(t)},nbn=t=>t!=null&&typeoft=="object"&&typeoft[Symbol.asyncIterator]=="function",Z2e=t=>t&&typeoft=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody",pJ=asynct=>{lete=awaitc5t(t.body);returnz2e(e,t)},c5t=asynct=>{lete=new$2e;returnawaitPromise.all(Object.entries(t||{}).map(([r,n])=>G2e(e,r,n))),e},G2e=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(Qyn(r)){letn=awaitJ2e(r);t.append(e,n)}elseif(Array.isArray(r))awaitPromise.all(r.map(n=>G2e(t,e+"[]",n)));elseif(typeofr=="object")awaitPromise.all(Object.entries(r).map(([n,o])=>G2e(t,`${e}[${n}]`,o)));elsethrownewTypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}}});asyncfunctiong5t(t){let{response:e}=t;if(t.options.stream)returnM3("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):jpe.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();returnM3("response",e.status,e.url,e.headers,i),i}leto=awaite.text();returnM3("response",e.status,e.url,e.headers,o),o}functionlbn(){if(typeofnavigator>"u"||!navigator)returnnull;lett=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}oft){letn=r.exec(navigator.userAgent);if(n){leto=n[1]||0,i=n[2]||0,a=n[3]||0;return{browser:e,version:`${o}.${i}.${a}`}}}returnnull}functionhbn(t){if(!t)return!0;for(leteint)return!1;return!0}functiongbn(t,e){returnObject.prototype.hasOwnProperty.call(t,e)}functionh5t(t,e){for(letrine){if(!gbn(e,r))continue;letn=r.toLowerCase();if(!n)continue;leto=e[r];o===null?deletet[n]:o!==void0&&(t[n]=o)}}functionM3(t,...e){typeofprocess<"u"&&process?.env?.DEBUG==="true"&&console.log(`Groq:DEBUG:${t}`,...e)}varibn,abn,Fpe,kpe,$pe,d5t,X2e,sbn,ubn,f5t,p5t,m5t,cbn,dbn,fbn,pbn
]`;continue}o+=n[u],n[u]==="\\"?i=!0:a&&n[u]==="]"?a=!1:!a&&n[u]==="["&&(a=!0)}try{newRegExp(o)}catch{returnconsole.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}returno}});vartge=x(ege=>{"use strict";Object.defineProperty(ege,"__esModule",{value:!0});ege.parseRecordDef=void0;varUJ=Ie(),_Xt=Wl(),KNn=Qhe(),GNn=Vhe();functionJNn(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===UJ.ZodFirstPartyTypeKind.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:(0,_Xt.parseDef)(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};letr={type:"object",additionalProperties:(0,_Xt.parseDef)(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")returnr;if(t.keyType?._def.typeName===UJ.ZodFirstPartyTypeKind.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=(0,KNn.parseStringDef)(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===UJ.ZodFirstPartyTypeKind.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===UJ.ZodFirstPartyTypeKind.ZodBranded&&t.keyType._def.type._def.typeName===UJ.ZodFirstPartyTypeKind.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=(0,GNn.parseBrandedDef)(t.keyType._def,e);return{...r,propertyNames:o}}}returnr}ege.parseRecordDef=JNn});varV3e=x(rge=>{"use strict";Object.defineProperty(rge,"__esModule",{value:!0});rge.parseMapDef=void0;varvXt=Wl(),ZNn=tge();functionYNn(t,e){if(e.mapStrategy==="record")return(0,ZNn.parseRecordDef)(t,e);letr=(0,vXt.parseDef)(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=(0,vXt.parseDef)(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}}}rge.parseMapDef=YNn});varW3e=x(nge=>{"use strict";Object.defineProperty(nge,"__esModule",{value:!0});nge.parseNativeEnumDef=void0;functionXNn(t){lete=t.values,n=Object.keys(t.values).filter(i=>typeofe[e[i]]!="number").map(i=>e[i]),o=Array.from(newSet(n.map(i=>typeofi)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}nge.parseNativeEnumDef=XNn});varK3e=x(oge=>{"use strict";Object.defineProperty(oge,"__esModule",{value:!0});oge.parseNeverDef=void0;functionQNn(){return{not:{}}}oge.parseNeverDef=QNn});varG3e=x(ige=>{"use strict";Object.defineProperty(ige,"__esModule",{value:!0});ige.parseNullDef=void0;functionejn(t){returnt.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}ige.parseNullDef=ejn});varage=x(f1=>{"use strict";Object.defineProperty(f1,"__esModule",{value:!0});f1.parseUnionDef=f1.primitiveMappings=void0;vartjn=Wl();f1.primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};functionrjn(t,e){if(e.target==="openApi3")returnwXt(t,e);letr=t.optionsinstanceofMap?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeNameinf1.primitiveMappings&&(!n._def.checks||!n._def.checks.length))){letn=r.reduce((o,i)=>{leta=f1.primitiveMappings[i._def.typeName];returna&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}elseif(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){letn=r.reduce((o,i)=>{leta=typeofi._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:returno}},[]);if(n.length===r.length){leto=n.filter((i,a,s)=>s.indexOf(i)===a);return{type:o.length>1?o:o[0],enum:r.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}elseif(r.every(n=>n._
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.
`+m,w=y+_,S=this.chainManager.chatModelManager.getChatModel();w&&g.push({role:eI(S),content:w});for(let E of c)g.push({role:E.role,content:E.content});if(e.content&&Array.isArray(e.content)){let E=e.content.map(P=>P.type==="text"?{...P,text:e.message}:P);g.push({role:"user",content:E})}else g.push({role:"user",content:e.message});B(`==== Final Request to AI ====
`,g);let C=await Od(()=>this.chainManager.chatModelManager.getChatModel().stream(g,{signal:r.signal}));for await(let E of C){if(r.signal.aborted){B("VaultQAstreamiterationaborted",{reason:r.signal.reason});break}a.processChunk(E)}}catch(u){u.name==="AbortError"||r.signal.aborted?B("VaultQAstreamabortedbyuser",{reason:r.signal.reason}):await this.handleError(u,o,n)}let s=a.close();return r.signal.aborted&&r.signal.reason==="new-chat"?(n(""),""):(s=this.addSourcestoResponse(s),this.handleResponse(s,e,r,o,n))}addSourcestoResponse(e){let r=Net(this.chainManager.getRetrievedDocuments());if(r.length>0){let n=r.map(o=>`- [[${o}]]`).join(`
`):l}function X$n(t){let e=[],r=/-{3,}\s*SEARCH\s*(?:\r?\n)?/,n=/(?:\r?\n)?={3,}\s*(?:\r?\n)?/,o=/(?:\r?\n)?\+{3,}\s*REPLACE/,i=new RegExp(r.source+"([\\s\\S]*?)"+n.source+"([\\s\\S]*?)"+o.source,"g"),a;for(;(a=i.exec(t))!==null;){let s=a[1].trim(),u=a[2].trim();e.push({searchText:s,replaceText:u})}return e}var Bk,J$n,sye,Z$n,Uer,sVe=b(()=>{Bk=require("obsidian");aVe();iVe();xd();$k();J$n=dt.object({path:dt.string().describe(`(Required) The path to the file to write to.
The path must be relative to the root of the vault.`),content:dt.union([dt.string(),dt.object({}).passthrough()]).describe(`(Required) The content to write to the file. Can be either a string or an object.
`,schema:J$n,handler:async({path:t,content:e})=>{let r=typeof e=="string"?e:JSON.stringify(e,null,2),n=await zer(t,r);return JSON.stringify({result:n,message:`File change result: ${n}. Do not retry or attempt alternative approaches to modify this file in response to the current user request.`})},timeoutMs:0}),Z$n=dt.object({path:dt.string().describe("(Required)Thepathofthefiletomodify(relativetotherootofthevaultandincludethefileextension)."),diff:dt.string().describe(`(Required) One or more SEARCH/REPLACE blocks. Each block MUST follow this exact format with these exact markers:
- Wrong: Not matching whitespace/indentation exactly`)});Uer=Kl({name:"replaceInFile",description:"RequesttoreplacesectionsofcontentinanexistingfileusingSEARCH/REPLACEblocksthatdefineexactchangestospecificpartsofthefile.ThistoolshouldbeusedwhenyouneedtomaketargetedchangestospecificpartsofaLARGEfile.",schema:Z$n,handler:async({path:t,diff:e})=>{let r=app.vault.getAbstractFileByPath(t);if(!r||!(r instanceof Bk.TFile))return`File not found at path: ${t}. Please check the file path and try again.`;try{let n=await app.vault.read(r),o=n;if(n.length<3e3)return"Fileistoosmalltousethistool.PleaseusewriteToFileinstead.";let a=X$n(e);if(a.length===0)return`No valid SEARCH/REPLACE blocks found in diff. Please use the correct format with ------- SEARCH, =======, and +++++++ REPLACE markers.
diff: ${e}`;let s=0;for(let l of a){let{searchText:c,replaceText:d}=l,f=u7(o),p=u7(c);if(!f.includes(p))if(f.includes(p.trimEnd()))c=c.trimEnd(),d=d.trimEnd();else return`Search text not found in file ${t} : "${c}".`;let h=o;o=Y$n(o,c,d),o!==h&&s++}if(n===o)return`No changes made to ${t}. The search text was not found or replacement resulted in identical content. Call writeToFile instead`;let u=await zer(t,o);return JSON.stringify({result:u,blocksApplied:s,message:`Applied ${s} SEARCH/REPLACE block(s) (replacing all occurrences). Result: ${u}. Do not call this tool again to modify this file in response to the current user request.`})}catch(n){return`Error performing SEARCH/REPLACE on ${t}: ${n}. Please check the file path and diff format and try again.`}},timeoutMs:0})});var uVe,qer,DO,l7=b(()=>{uVe=require("obsidian"),qer=t=>{switch(t){case"@vault":return"Searchthroughyourvaultforrelevantinformation";case"@websearch":return"Searchthewebforinformation";case"@youtube":return"GetthetranscriptofaYouTubevideo.Example:@youtube<video_url>";case"@pomodoro":return"Startapomodorotimer.Example:@pomodoro25m";case"@composer":return"Editexistingnotesorcreatenewnotes.";default:return""}},DO=class{static async callTool(e,r){try{if(!e)throw new Error("Toolisundefined");let n=await e.call(r);return n??(console.warn(`Tool ${e.name} returned null/undefined result`),null)}catch(n){return console.error("Errorcallingtool:",n),n instanceof Error?new uVe.Notice(n.message):new uVe.Notice("Anerroroccurredwhileexecutingthetool.Checkconsolefordetails."),null}}}});function Q$n(t){return"children"in t&&"path"in t}function eBn(t){return"path"in t&&!("children"in t)}function tBn(t){let e=t.split(".");return e.length>1&&e.pop()?.toLowerCase()||""}function lVe(t,e=!0){let r=[],n={},o={},{inclusions:i,exclusions:a}=vc();for(let u of t.children)if(eBn(u)){if(_s(u,i,a)){e&&r.push(u.name);let l=tBn(u.name)||"unknown";l&&(n[l]=(n[l]||0)+1)}}else if(Q$n(u)){let l=lVe(u,e);if(Object.keys(l).length>0&&(o[u.name]=l[u.name],l[u.name].extensionCounts))for(let[c,d]of Object.entries(l[u.name].extensionCounts))n[c]=(n[c]||0)+d}let s={};return Object.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}}var uye,cVe=b(()=>{rh();xd();$k();uye=t=>Kl({name:"getFileTree",description:"Getthefiletreeasanestedstructureoffoldersandfiles",schema:dt.void(),handler:async()=>{let e=lVe(t,!0),r=`A JSON represents the file tree as a nested structure:
`+JSON.stringify({success:!0,message:`Semantic search index has been refreshed with ${r} documents.`,documentCount:r})}catch(e){return JSON.stringify({success:!1,message:`Failed to index with semantic search: ${e.message}`})}else return`The tiered lexical retriever builds indexes on demand and doesn't require manual indexing.
- Los Angeles: UTC-8 (UTC-7 during DST)`)}),handler:async({timezoneOffset:t})=>BUn(t),isBackground:!0}),Dnr={jan:1,january:1,feb:2,february:2,mar:3,march:3,apr:4,april:4,may:5,jun:6,june:6,jul:7,july:7,aug:8,august:8,sep:9,september:9,oct:10,october:10,nov:11,november:11,dec:12,december:12};Bye=Kl({name:"getTimeRangeMs",description:"ConvertnaturallanguagetimeexpressionstodaterangesforusewithlocalSearch",schema:dt.object({timeExpression:dt.string().describe(`Natural language time expression to convert to a date range.
3. Then use the returned time range with localSearch`)}),handler:async({timeExpression:t})=>GUn(t),isBackground:!0});zye=Kl({name:"getTimeInfoByEpoch",description:"ConvertaUnixtimestamp(insecondsormilliseconds)todetailedtimeinformation",schema:dt.object({epoch:dt.number().describe("Unixtimestampinsecondsormilliseconds")}),handler:async({epoch:t})=>JUn(t),isBackground:!0});CZ=Kl({name:"startPomodoro",description:"StartaPomodorotimerwithacustomizableinterval",schema:dt.object({interval:dt.string().default("25min").describe("Timeinterval(e.g.,'25min','5s','1h').Defaultis25min.")}),handler:async({interval:t})=>(YUn(t),`Pomodoro timer started. It will end in ${t}.`)});Uye=Kl({name:"convertTimeBetweenTimezones",description:"ConvertaspecifictimefromonetimezonetoanotherusingUTCoffsets",schema:dt.object({time:dt.string().describe(`Time to convert. Supports various formats:
`),n=["\u{1F310} Web Search Results"],o=!1,i=[],a=[];for(let s of r){if(s.includes("Sources:")){o=!0;continue}o?a.push(s):s.includes("Here are the web search results")||i.push(s)}return i.length>0&&(n.push(""),n.push(...i.filter(s=>s.trim()))),a.length>0&&(n.push(""),n.push("Sources:"),a.forEach(s=>{s.trim()&&n.push(s)})),n.join(`
${r.message}`;if(r.results&&Array.isArray(r.results)){let n=[`\u{1F4FA}YouTubeTranscripts(${r.total_urls}video${r.total_urls>1?"s":""})`];n.push("");for(let o of r.results){if(o.success){n.push(`\u{1F4F9}Video:${o.url}`),n.push("");let i=o.transcript.split(`
`),a=0;for(let s of i)if(s.trim()&&(s.match(/^\[(\d+:\d+)\]/)?(a>0&&n.push(""),n.push(`\u23F0${s}`)):n.push(`${s.trim()}`),a++,a>30)){n.push(""),n.push("... (transcript truncated for display)");break}o.elapsed_time_ms&&(n.push(""),n.push(`Processingtime:${(o.elapsed_time_ms/1e3).toFixed(1)}s`))}else n.push(`\u274CFailedtotranscribe:${o.url}`),n.push(`${o.message}`);n.push(""),n.push("---"),n.push("")}return n.join(`
`),i=0;for(let a of o)if(a.trim()&&(a.match(/^\[(\d+:\d+)\]/)?(i>0&&n.push(""),n.push(`\u23F0${a}`)):n.push(`${a.trim()}`),i++,i>50)){n.push(""),n.push("... (transcript truncated for display)");break}return r.elapsed_time_ms&&(n.push(""),n.push(`Processingtime:${(r.elapsed_time_ms/1e3).toFixed(1)}s`)),n.join(`
`}returni.trim()}asyncextractEmbeddedImages(e,r){letn=/!\[\[(.*?\.(png|jpg|jpeg|gif|webp|bmp|svg))\]\]/g,o=/!\[.*?\]\(([^)]+)\)/g,i=[],a=[...e.matchAll(n)];for(letuofa){letl=u[1];if(r){letc=app.metadataCache.getFirstLinkpathDest(l,r);c?i.push(c.path):(Bt(`Could not resolve embedded image: ${l} from source: ${r}`),i.push(l))}elsei.push(l)}lets=[...e.matchAll(o)];for(letuofs){letl=u[1].trim();if(!l)continue;if(l.match(/^https?:\/\//)){i.push(l);continue}letc=l.replace(/^\.\//,"").replace(/^\//,"");if(r){letd=app.metadataCache.getFirstLinkpathDest(c,r);d?i.push(d.path):i.push(c)}elsei.push(c)}returni}asyncbuildMessageContent(e,r){letn=[],o=[],i=oe(),a=[];if(i.passMarkdownImages){letc;if(r.context?.notes&&r.context.notes.length>0)c=r.context.notes[0].path;else{letf=this.chainManager.app?.workspace.getActiveFile();f&&(c=f.path)}letd=this.extractNoteContent(e);if(d){letf=awaitthis.extractEmbeddedImages(d,c);f.length>0&&a.push({urls:f,type:"embedded"})}}for(letcofa){letd=awaitthis.processImageUrls(c.urls);o.push(...d.successfulImages),n.push(...d.failureDescriptions)}lets=r.content;if(s&&s.length>0){letc=awaitthis.processChatInputImages(s);o.push(...c.successfulImages),n.push(...c.failureDescriptions)}letu=e;n.length>0&&(u=`${e}
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:eI(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.`}),Wye(s,u);letd=this.chainManager.chatModelManager.getChatModel(),p=this.isMultimodalModel(d)?awaitthis.buildMessageContent(e,r):e;u.push({role:"user",content:p});leth=pinstanceofArray?p[0].text:p;B("Enhanced user message: ",h),B(`==== Final Request to AI ====
`,u);letm=newVye(DO,sye),g=new__(o),y=awaitOd(()=>this.chainManager.chatModelManager.getChatModel().stream(u,{signal:n.signal}));forawait(let_ofy){if(n.signal.aborted){B("CopilotPlus multimodal stream iteration aborted",{reason:n.signal.reason});break}forawait(letwofm.processChunk(_))g.processChunk(w)}returng.close()}asyncrun(e,r,n,o,i){let{updateLoadingMessage:a}=i,s="",u=[],l="";if(!awaitlO({isCopilotPlus:!0}))returnawaitthis.handleError(newError("Invalid license key"),o,n),"";letd=f=>{l=f,n(f)};try{if(this.isYoutubeOnlyMessage(e.message)){letM=XSe(e.message),D="Transcript not available. Only videos with the auto transcript option turned on are supported at the moment.";if(M)try{letk=awaitJi.getInstance().youtube4llm(M);returnk.response.transcript?this.handleResponse(k.response.transcript,e,r,o,n):this.handleResponse(D,e,r,o,n)}catch(k){returnie("Error processing YouTube video:",k),this.handleResponse(D,e,r,o,n)}}B("==== Step 1: Analyzing intent ====");letf,p=e.originalMessage||e.message;try{f=awaitZk.analyzeIntent(p)}catch(M){returnthis.handleResponse(Tet(M),e,r,o,n)}leth=e.message.split(" ").filter(M=>!OZ.includes(M.toLowerCase())).join(" ").trim(),{toolOutputs:m,sources:g}=awaitthis.executeToolCalls(f,a);u=g;let_=m.find(M=>M.tool==="localSearch"&&M.output!=null)&&u.length>0,C=(awaitthis.chainManager.memoryManager.getMemory().loadMemoryVariables({})).history||[],E=T6e(C),P=$nr(E),T=h;P.length>0&&(B("==== Condensing Question ===="),T=awaitrye(h,P),B("Condensed standalone question: ",T));letI=this.prepareEnhancedUserMessage(T,m,f),N=m.some(M=>M.tool!=="localSearch"&&M.output!=null);_&&!N&&(I=`Answer the question with as detailed as possible based only on the following context:
${I}`),I=this.appendComposerInstructionsIfNeeded(I,e),B("==== Invoking LLM with all tool results ===="),s=awaitthis.streamMultimodalResponse(I,e,r,d)}catch(f){a?.(Iv.DEFAULT),f.name==="AbortError"||r.signal.aborted?B("CopilotPlus stream aborted by user",{reason:r.signal.reason}):awaitthis.handleError(f,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)?(Bt("No valid documents provided to getSources"),[]):this.sortUniqueDocsByScore(e)}sortUniqueDocsByScore(e){letr=newMap;for(letnofe){if(!n.title||!n?.score&&!n?.rerank_score){Bt("Invalid document structure:",n);continue}leto=n.path||n.title,i=r.get(o),a=n&&"rerank_score"inn,s=a?n.rerank_score:n.score;(!i||s>(i.score??0))&&r.set(o,{title:n.title,path:n.path||n.title,score:s,isReranked:a,explanation:n.explanation||null})}returnArray.from(r.values()).sort((n,o)=>(o.score??0)-(n.score??0))}asyncexecuteToolCalls(e,r){letn=[],o=[];for(letiofe){B(`==== Step 2: Calling tool: ${i.tool.name} ====`),i.tool.name==="localSearch"?r?.(Iv.READING_FILES):i.tool.name==="webSearch"?r?.(Iv.SEARCHING_WEB):i.tool.name==="getFileTree"&&r?.(Iv.READING_FILE_TREE);leta=awaitDO.callTool(i.tool,i.args);if(i.tool.name==="localSearch"){letu={result:typeofa=="string"?a:JSON.stringify(a),success:a!=null},l=this.getTimeExpression(e),c=this.processLocalSearchResult(u,l);o.push(...c.sources),n.push({tool:i.tool.name,output:c.formattedForLLM})}elsen.push({tool:i.tool.name,output:a})}return{toolOutputs:n,sources:EZ(o)}}prepareEnhancedUserMessage(e,r,n){leto="",i=!1,a=r.find(s=>s.tool==="localSearch"&&s.output!=null);if(a&&typeofa.output=="string")try{lets=JSON.parse(a.output);Array.isArray(s)&&s.length>0&&(i=!0)}catch{}if(r.length>0){lets=r.filter(u=>u.output!=null);s.length>0&&(o=(i&&s.length===1?"":`
</use_tool>`}})}functionZye(t){lete=FO.getInstance(),r=e.getToolMetadata("getFileTree")!==void0,n=t!==void0;(e.getAllTools().length===0||r!==n)&&(e.clear(),e.registerAll(eqn),t&&tqn(t))}vareqn,j6e=b(()=>{Jye();fVe();O6e();E6e();sVe();cVe();eqn=[{tool:c7,metadata:{id:"localSearch",displayName:"Vault Search",description:"Search through your vault notes",category:"search",customPromptInstructions:`For localSearch (searching notes in the vault):
</use_tool>`}},{tool:d7,metadata:{id:"webSearch",displayName:"Web Search",description:"Search the internet for information",category:"search",customPromptInstructions:`For webSearch:
</use_tool>`}},{tool:$ye,metadata:{id:"getCurrentTime",displayName:"Get Current Time",description:"Get the current time in any timezone",category:"time",isAlwaysEnabled:!0,customPromptInstructions:`For time queries (IMPORTANT: Always use UTC offsets, not timezone names):
</use_tool>`}},{tool:zye,metadata:{id:"getTimeInfoByEpoch",displayName:"Get Time Info",description:"Convert epoch timestamp to human-readable format",category:"time",isAlwaysEnabled:!0}},{tool:Bye,metadata:{id:"getTimeRangeMs",displayName:"Get Time Range",description:"Convert time expressions to date ranges",category:"time",isAlwaysEnabled:!0,customPromptInstructions:`For time-based queries:
</use_tool>`}},{tool:Uye,metadata:{id:"convertTimeBetweenTimezones",displayName:"Convert Timezones",description:"Convert time between different timezones",category:"time",isAlwaysEnabled:!0,customPromptInstructions:`For timezone conversions:
</use_tool>`}},{tool:CZ,metadata:{id:"pomodoro",displayName:"Pomodoro Timer",description:"Manage time with Pomodoro technique",category:"time"}},{tool:sye,metadata:{id:"writeToFile",displayName:"Write to File",description:"Create or modify files in your vault",category:"file",requiresVault:!0,customPromptInstructions:`For writeToFile:
</use_tool>`}},{tool:Uer,metadata:{id:"replaceInFile",displayName:"Replace in File",description:"Make targeted changes to existing files using SEARCH/REPLACE blocks",category:"file",requiresVault:!0,customPromptInstructions:`For replaceInFile:
- Remember: Small edits \u2192 replaceInFile, Major rewrites \u2192 writeToFile
- SEARCH text must match EXACTLY including all whitespace
`)}varWnr=b(()=>{});functionKnr(t){lete=["find","search","look for","look up","my notes","in my vault","from my vault","check the web","search online","from the internet","current time","what time","timer","youtube","video","transcript"],r=t.toLowerCase();returne.some(n=>r.includes(n))}var$6e,Xk,L6e,F6e,k6e,TZ,Gnr=b(()=>{Gt();$6e=50,Xk=class{constructor(e){this.modelName=e}buildToolSpecificInstructions(e){letr=[];for(letnofe)n.customPromptInstructions&&r.push(n.customPromptInstructions);returnr.length>0?r.join(`
IMPORTANT: Use the EXACT parameter names as shown in the tool descriptions below. Do NOT use generic names like "param1" or "param".
Available tools:
${r}
# Tool Usage Guidelines
## Time-based Queries
When users ask about temporal periods (e.g., "what did I do last month", "show me notes from last week"), you MUST:
1. First call getTimeRangeMs to convert the time expression to a proper time range
2. Then use localSearch with the timeRange parameter from step 1
3. For salientTerms, ONLY use words that exist in the user's original query (excluding time expressions)
Example for "what did I do last month":
1. Call getTimeRangeMs with timeExpression: "last month"
2. Use localSearch with query matching the user's question
3. salientTerms: [] - empty because "what", "I", "do" are not meaningful search terms
Example for "meetings about project X last week":
1. Call getTimeRangeMs with timeExpression: "last week"
2. Use localSearch with query "meetings about project X"
3. salientTerms: ["meetings", "project", "X"] - these words exist in the original query
${a?a+`
`:""}## General Guidelines
- Think hard about whether a query could potentially be answered from personal knowledge or notes, if yes, call a vault search (localSearch) first
- Only use web search if: the query explicitly asks for web search, OR the query explicitly requires current/web information
- NEVER mention tool names like "localSearch", "webSearch", etc. in your responses. Use natural language like "searching your vault", "searching the web", etc.
You can use multiple tools in sequence. After each tool execution, you'll receive the results and can decide whether to use more tools or provide your final response.
Always explain your reasoning before using tools. Be conversational and clear about what you're doing.
When you've gathered enough information, provide your final response without any tool calls.
IMPORTANT: Do not include any code blocks (\`\`\`) or tool_code blocks in your responses. Only use the <use_tool> format for tool calls.
NOTE: Use individual XML parameter tags. For arrays, use JSON format like ["item1", "item2"].`}enhanceUserMessage(e,r){returne}needsSpecialHandling(){return!1}},L6e=classextendsXk{isGPT5Model(){returnthis.modelName.includes("gpt-5")||this.modelName.includes("gpt5")}enhanceSystemPrompt(e,r,n,o){leti=super.enhanceSystemPrompt(e,r,n,o),a=n||[],s=a.includes("writeToFile")||a.includes("replaceInFile"),u="";returnthis.isGPT5Model()?u=`
- Use maximum 2 tool calls initially, then provide an answer
- Call each tool ONCE per unique query
- For optional parameters: OMIT them entirely if not needed (don't pass empty strings/null)
- For localSearch: OMIT timeRange if not doing time-based search
Example localSearch without time:
<use_tool>
<name>localSearch</name>
<query>piano notes</query>
<salientTerms>["piano", "notes"]</salientTerms>
</use_tool>`:u=`
CRITICAL FOR GPT MODELS: You MUST ALWAYS include XML tool calls in your response. Do not just describe what you plan to do - you MUST include the actual XML tool call blocks.`,s&&(u+=`
\u{1F6A8} FILE EDITING WITH COMPOSER TOOLS - GPT SPECIFIC EXAMPLES \u{1F6A8}
When user asks you to edit or modify a file, you MUST:
1. Determine if it's a small edit (use replaceInFile) or major rewrite (use writeToFile)
2. Include the tool call immediately in your response
EXAMPLE 1 - User says "fix the typo 'teh' to 'the' in my note":
\u2705 CORRECT RESPONSE:
"I'll fix the typo in your note.
<use_tool>
<name>replaceInFile</name>
<path>path/to/note.md</path>
<diff>
------- SEARCH
teh
=======
the
+++++++ REPLACE
</diff>
</use_tool>"
EXAMPLE 2 - User says "add item 4 to the list":
\u2705 CORRECT RESPONSE:
"I'll add item 4 to your list.
<use_tool>
<name>replaceInFile</name>
<path>path/to/file.md</path>
<diff>
------- SEARCH
- Item 1
- Item 2
- Item 3
=======
- Item 1
- Item 2
- Item 3
- Item 4
+++++++ REPLACE
</diff>
</use_tool>"
\u274C WRONG (DO NOT DO THIS):
"I'll help you add item 4 to the list. Let me update that for you."
[No tool call = FAILURE]
CRITICAL: The diff parameter MUST contain the SEARCH/REPLACE blocks wrapped in triple backticks EXACTLY as shown above.`),u+=`
FINAL REMINDER FOR GPT MODELS: If the user asks you to search, find, edit, or modify anything, you MUST include the appropriate <use_tool> XML block in your very next response. Do not wait for another turn.`,i+u}enhanceUserMessage(e,r){returnr?this.getBaseEnhancement(e,r):e}getBaseEnhancement(e,r){if(!r)returne;letn=e.toLowerCase(),o=n.includes("find")||n.includes("search")||n.includes("my notes"),i=n.includes("edit")||n.includes("modify")||n.includes("update")||n.includes("change")||n.includes("fix")||n.includes("add")||n.includes("typo");returno?`${e}
REMINDER: Use the <use_tool> XML format to call the localSearch tool.`:i?`${e}
\u{1F6A8} GPT REMINDER: Use replaceInFile for small edits (with SEARCH/REPLACE blocks in diff parameter). The diff parameter MUST contain triple backticks around the SEARCH/REPLACE blocks. Check the examples in your system prompt.`:e}needsSpecialHandling(){return!0}},F6e=classextendsXk{isThinkingModel(){returnthis.modelName.includes("claude-3-7-sonnet")||this.modelName.includes("claude-sonnet-4")||this.modelName.includes("claude-3.7-sonnet")||this.modelName.includes("claude-4-sonnet")}isClaudeSonnet4(){returnthis.modelName.includes("claude-sonnet-4")||this.modelName.includes("claude-4-sonnet")||this.modelName.includes("claude-sonnet-4-20250514")}enhanceSystemPrompt(e,r,n,o){leti=super.enhanceSystemPrompt(e,r,n,o);if(this.isThinkingModel()){leta=`
Based on the search results, here's a complete practice plan...
[This is FORBIDDEN - you haven't received results yet!]
\u{1F511} KEY UNDERSTANDING FOR CLAUDE 4:
- Brief 1-sentence explanations BEFORE tool calls are good
- Each response is ONE STEP in a multi-step process
- After tool calls, STOP and wait for the system to provide results
- Your thinking is automatically handled in <think> blocks
\u26A1 AUTONOMOUS AGENT RULES FOR CLAUDE 4:
1. If you need tools: Brief sentence + tool calls, then STOP
2. If you receive tool results: Evaluate if you need more tools
3. If you need more tools: Brief sentence + more tool calls, then STOP
4. If you have enough info: THEN provide your final response
REMEMBER: One brief sentence before tools is perfect. Nothing after tool calls.`),i+a}returni}needsSpecialHandling(){returnthis.isThinkingModel()}detectPrematureResponse(e){letr=e.indexOf("<use_tool>");if(r===-1)return{hasPremature:!1,type:null};leto=e.substring(0,r).trim().replace(/<think>[\s\S]*?<\/think>/g,"").trim();if(o.split(/[.!?]+/).filter(u=>u.trim().length>0).length>2||o.length>200)return{hasPremature:!0,type:"before"};lets=e.lastIndexOf("</use_tool>");returns!==-1&&e.substring(s+11).trim().replace(/<think>[\s\S]*?<\/think>/g,"").trim().length>100?{hasPremature:!0,type:"after"}:{hasPremature:!1,type:null}}sanitizeResponse(e,r){if(!this.isClaudeSonnet4()||r!==1)returne;letn=this.detectPrematureResponse(e);if(!n.hasPremature)returne;if(n.type==="after"){leto=e.lastIndexOf("</use_tool>");if(o!==-1){leti=e.substring(0,o+11),a=e.substring(o+11),s=/<think>[\s\S]*?<\/think>/g,u=a.match(s)||[];returni+(u.length>0?`
REMINDER: Use the tools immediately. Do not ask questions. For "my notes", use localSearch.`:e}needsSpecialHandling(){return!0}},TZ=class{staticcreateAdapter(e){letr=(e.modelName||e.model||"").toLowerCase();if(B(`Creating model adapter for: ${r}`),r.includes("gpt")){letn=newL6e(r);returnn.isGPT5Model()?B("Using GPTModelAdapter with GPT-5 specific enhancements"):B("Using GPTModelAdapter"),n}returnr.includes("claude")?(B("Using ClaudeModelAdapter"),newF6e(r)):r.includes("gemini")||r.includes("google/gemini")?(B("Using GeminiModelAdapter"),newk6e(r)):r.includes("copilot-plus")?(B("Using BaseModelAdapter for Copilot Plus"),newXk(r)):(B("Using BaseModelAdapter (default)"),newXk(r))}}});functionYye(t){lete=[];try{letr=/<use_tool>([\s\S]*?)<\/use_tool>/g,n;for(;(n=r.exec(t))!==null;){leto=n[1],i=o.match(/<name>([\s\S]*?)<\/name>/);if(i){leta=i[1].trim();if(!a||a.length===0){Bt("Skipping tool call with empty name");continue}lets={},u=o.replace(/<name>[\s\S]*?<\/name>/,""),l=/<([^>]+)>([\s\S]*?)<\/\1>/g,c;for(;(c=l.exec(u))!==null;){letd=c[1].trim(),f=c[2].trim();d&&(s[d]=B6e(f,d))}e.push({name:a,args:s})}}}catch(r){returnie("Error parsing XML tool calls:",r),[]}returne}functionB6e(t,e){if(!t)returne==="chatHistory"||e==="salientTerms"?[]:"";if(!/<[^>]+>/.test(t)){if(t.startsWith("[")&&t.endsWith("]")||t.startsWith("{")&&t.endsWith("}"))try{returnJSON.parse(t)}catch{returnt}returnt}letn=t.match(/<item>([\s\S]*?)<\/item>/g);if(n)returnn.map(s=>{letu=s.replace(/<\/?item>/g,"").trim();returnB6e(u)});leto=/<([^>]+)>([\s\S]*?)<\/\1>/g,i=[],a;for(;(a=o.exec(t))!==null;){lets=a[1].trim(),u=a[2].trim();i.push([s,B6e(u)])}returni.length>0?Object.fromEntries(i):t}functionJnr(t){t=t.replace(/<use_tool>[\s\S]*?<\/use_tool>/g,"");lete=t.match(/<use_tool>([\s\S]*)/),n=(e?e[1]:t).match(/<name>([\s\S]*?)<\/name>/);returnn&&n[1].trim()||null}functionAZ(t){lete=t;returne=e.replace(/<use_tool>[\s\S]*?<\/use_tool>/g,""),e=e.replace(/<use_tool>([\s\S]*)$/g,""),e=e.replace(/```\w*\s*```/g,""),e=e.replace(/```tool_code[\s\S]*?```/g,""),e=e.replace(/```[\w]*[\s\n]*```/g,""),e=e.replace(/\n\s*\n\s*\n/g,`
`);o(Te)},w);if(!D)break;letk=Yye(D),F=w.detectPrematureResponse?.(D);if(F?.hasPremature&&N===1&&(F.type==="before"?(Bt("\u26A0\uFE0F Model provided premature response BEFORE tool calls!"),Bt("Sanitizing response to keep only tool calls for first iteration")):F.type==="after"&&(Bt("\u26A0\uFE0F Model provided hallucinated response AFTER tool calls!"),Bt("Truncating response at last tool call for first iteration"))),k.length===0){letV=AZ(D),q=[...l];V.trim()&&q.push(V),s=q.join(`
`),this.llmFormattedMessages.push(D);break}letK=D;w.sanitizeResponse&&F?.hasPremature&&(K=w.sanitizeResponse(D,N));letU=AZ(K);U.trim()&&l.push(U);letX=[],ee=newMap;M.splice(k.length);for(letV=0;V<k.length;V++){letq=k[V];if(n.signal.aborted)break;R6e(q,N);letH=this.getAvailableTools(),Z=H.find(ae=>ae.name===q.name)?.isBackground||!1,de;if(!Z){letae=DH(q.name),Te=Yk(q.name),Ae=qnr(q.name);de=`${q.name}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,ee.set(V,de);letke=Fde(de,q.name,Te,ae,Ae||"",!0,"",""),Ot=M.findIndex(Mr=>Mr.includes(this.getTemporaryToolCallId(q.name,V)));Ot!==-1?M[Ot]=ke:(M.push(ke),Bt("Created tool call marker for tool call that was not created during streaming",q.name));letjr=[...l,...M].join(`
`);l.push(V)}if(this.llmFormattedMessages.push(D),X.length>0){letV=D6e(X,!0);V&&this.llmFormattedMessages.push(V)}let{ensureEncodedToolCallMarkerResults:L}=awaitPromise.resolve().then(()=>(h4(),kde)),Q=L(D);u.push({role:"assistant",content:Q});letz=D6e(X,!1);u.push({role:"user",content:z});letW=z.length>500?z.substring(0,500)+"... (truncated)":z;B("Tool results added to conversation:",W)}if(N>=I&&!s){Bt(`Autonomous agent reached maximum iterations (${I}) without completing the task`);letM=`
I've reached the maximum number of iterations (${I}) for this task. I attempted to gather information using various tools but couldn't complete the analysis within the iteration limit. You may want to try a more specific question or break down your request into smaller parts.`;s=l.join(`
`)+M}}catch(h){if(h.name==="AbortError"||n.signal.aborted)B("Autonomous agent stream aborted by user",{reason:n.signal.reason});else{ie("Autonomous agent failed, falling back to regular Plus mode:",h);try{returnawaitnewLO(this.chainManager).run(r,n,o,i,a)}catch(m){returnie("Fallback to regular Plus mode also failed:",m),awaitthis.handleError(m,i,o),""}}}letf=EZ(c),p=this.llmFormattedMessages.join(`
`)),awaitPromise.resolve().then(()=>(h4(),kde)),this.handleResponse(s,r,n,i,o,f.length>0?f:void0,p)}asyncstreamResponse(r,n,o,i){leta=new__(o,i),s=2,u=0;for(;u<=s;)try{letl=awaitOd(()=>this.chainManager.chatModelManager.getChatModel().stream(r,{signal:n.signal}));forawait(letcofl){if(n.signal.aborted)break;a.processChunk(c)}returna.close()}catch(l){if(l.name==="AbortError"||n.signal.aborted)returna.close();if((l?.message?.includes("overloaded")||l?.message?.includes("Overloaded")||l?.error?.type==="overloaded_error")&&u<s){u++,B(`Retrying autonomous agent request (attempt ${u}/${s+1}) due to overloaded error`),awaitnewPromise(d=>setTimeout(d,1e3*u));continue}throwl}returna.close()}}});varYnr=b(()=>{sG();aHt();Oer();Gye();Vnr();Znr();g4();z6e();Kye()});varLH,Xnr,Xye,U6e,Qnr=b(()=>{LH=class{},Xnr=(t,e)=>{if(e!==void0)returnt[e];letr=Object.keys(t);if(r.length===1)returnt[r[0]]},Xye=(t,e)=>{letr=Xnr(t,e);if(!r){letn=Object.keys(t);thrownewError(`input values have ${n.length} keys, you must specify an input key or pass only 1 key as input`)}returnr},U6e=(t,e)=>{letr=Xnr(t,e);if(!r&&r!==""){letn=Object.keys(t);thrownewError(`output values have ${n.length} keys, you must specify an output key or pass only 1 key as output`)}returnr}});varMZ=b(()=>{Qnr()});varq6e,FH,eor=b(()=>{cj();vj();q6e=classextendsym{addUserMessage(e){returnthis.addMessage(newXs(e))}addAIChatMessage(e){returnthis.addMessage(newkn(e))}addAIMessage(e){returnthis.addMessage(newkn(e))}asyncaddMessages(e){for(letrofe)awaitthis.addMessage(r)}clear(){thrownewError("Not implemented.")}},FH=classextendsq6e{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??[]}asyncgetMessages(){returnthis.messages}asyncaddMessage(e){this.messages.push(e)}asyncclear(){this.messages=[]}}});vartor=b(()=>{eor()});varH6e=b(()=>{tor()});varK_,k1=b(()=>{MZ();H6e();K_=classextendsLH{constructor(e){super(),Object.defineProperty(this,"chatHistory",{enumerable:!0,configurable:!0,writable:!0,value:void0}),Object.defineProperty(this,"returnMessages",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"inputKey",{enumerable:!0,configurable:!0,writable:!0,value:void0}),Object.defineProperty(this,"outputKey",{enumerable:!0,configurable:!0,writable:!0,value:void0}),this.chatHistory=e?.chatHistory??newFH,this.returnMessages=e?.returnMessages??this.returnMessages,this.inputKey=e?.inputKey??this.inputKey,this.outputKey=e?.outputKey??this.outputKey}asyncsaveContext(e,r){awaitthis.chatHistory.addUserMessage(Xye(e,this.inputKey)),awaitthis.chatHistory.addAIChatMessage(U6e(r,this.outputKey))}asyncclear(){awaitthis.chatHistory.clear()}}});varRZ,ror=b(()=>{$s();k1();RZ=classextendsK_{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}getmemoryKeys(){return[this.memoryKey]}asyncloadMemoryVariables(e){letr=awaitthis.chatHistory.getMessages();returnthis.returnMessages?{[this.memoryKey]:r}:{[this.memoryKey]:Op(r,this.humanPrefix,this.aiPrefix)}}}});varnor=b(()=>{MZ();$s()});varoor=b(()=>{UA()});varior=b(()=>{Zf();oor();Pm();ig()});varaor=b(()=>{Db()});varV6e=b(()=>{ig();ZA();Pm();ior();aor()});varQye=b(()=>{ZA()});varW6e=b(()=>{$s();V6e();Qye();k1()});varNZ,sor=b(()=>{$s();k1();NZ=classextendsK_{constructor(e){super({returnMessages:e?.returnMessages??!1,chatHistory:e?.c
`;this.qaPrompt=Em.fromMessages([JA.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 ebe,LZ,vor=b(()=>{ua();vu();or();Ynr();Gt();bt();ir();ZA();ebe=require("obsidian");eye();bor();_or();LZ=class{constructor(e){this.retrievedDocuments=[];this.app=e,this.memoryManager=jZ.getInstance(),this.chatModelManager=h1.getInstance(),this.promptManager=DZ.getInstance(),this.initialize(),wa(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("No chain type set")}validateChatModel(){if(!this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())){let e="Chat model is not initialized properly, check your API key in Copilot setting and make sure you have API access.";throw new ebe.Notice(e),new Error(e)}}validateChainInitialization(){(!this.chain||!Iet(this.chain))&&(console.error("Chain is not initialized properly, re-initializing chain: ",ey()),this.createChainWithNewModel({},!1))}storeRetrieverDocuments(e){this.retrievedDocuments=e}async createChainWithNewModel(e={},r=!0){let n=ey(),o=wu();if(n==="project"&&!o)return;let i=n==="project"?o?.projectModelKey:Dee();if(!i)throw new ebe.Notice("No model key found"),new Error("No model key found");try{if(r){let a=vee(i,oe().activeModels);if(a||(console.error("Resetting default model. No model configuration found for: ",i),a=Av[0],i=a.name+"|"+a.provider),n==="project"&&!a.projectEnabled){let u=oe().activeModels.find(l=>l.enabled&&l.projectEnabled);if(u)a=u,i=u.name+"|"+u.provider,new ebe.Notice(`Model${a.name}isnotavailableinprojectmode.Switchingto${u.name}.`);else throw new Error("No project-enabled models available. Please enable a model for project mode in settings.")}let s={...a,...o?.modelConfigs};await this.chatModelManager.setChatModel(s)}this.setChain(n,e),B(`Settingmodelto${i}`)}catch(a){ie(`createChainWithNewModelfailed:${a}`),B(`modelKey:${i}`)}}async setChain(e,r={}){if(!this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())){console.error("setChain failed: No chat model set.");return}this.validateChainType(e);let n=this.chatModelManager.getChatModel(),o=this.memoryManager.getMemory(),i=this.promptManager.getChatPrompt();switch(e){case"llm_chain":{this.chain=c8.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),Dj("llm_chain");break}case"vault_qa":{await this.initializeQAChain(r);let a=oe(),s=a.enableSemanticSearchV3?new(await Promise.resolve().then(()=>(cG(),$de))).HybridRetriever({minSimilarityScore:.01,maxK:a.maxSourceChunks,salientTerms:[]}):new(await Promise.resolve().then(()=>(r7(),tye))).TieredLexicalRetriever(app,{minSimilarityScore:.01,maxK:a.maxSourceChunks,salientTerms:[],timeRange:void 0,textWeight:void 0,returnAll:!1,useRerankerThreshold:void 0});this.retrievalChain=c8.createConversationalRetrievalChain({llm:n,retriever:s,systemMessage:Mf()},this.storeRetrieverDocuments.bind(this),oe().debug),Dj("vault_qa"),oe().debug&&(console.log("New Vault QA chain with hybrid retriever created for entire vault"),console.log("Set chain:","vault_qa"));break}case"copilot_plus":{await this.initializeQAChain(r),this.chain=c8.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),Dj("copilot_plus");break}case"project":{await this.initializeQAChain(r),this.chain=c8.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),Dj("project");break}default:this.validateChainType(e);break}}getChainRunner(){let e=ey(),r=oe();switch(e){case"llm_chain":return new uG(this);case"vault_qa":return new n7(this);case"copilot_plus":return r.enableAutonomousAgent?new IZ(this):new LO(this);case"project"
`,e),this.validateChatModel(),this.validateChainInitialization();letu=this.chatModelManager.getChatModel();if(s||l8(u)){letc=Em.fromMessages([newPv("history"),Tv.fromTemplate("{input}")]);l8(u)&&(c=Em.fromMessages([[Fo,Mf()||""],c])),this.createChainWithNewModel({prompt:c},!1)}returnawaitthis.getChainRunner().run(e,r,n,o,i)}asyncupdateMemoryWithLoadedMessages(e){awaitthis.memoryManager.clearChatMemory();for(letr=0;r<e.length;r+=2){letn=e[r],o=e[r+1];n&&o&&n.sender===Fo&&awaitthis.memoryManager.getMemory().saveContext({input:n.message},{output:o.message})}}}});vartbe,wor=b(()=>{ua();Gt();bt();ir();oG();tbe=classt{constructor(e){this.app=e}staticgetInstance(e){returnt.instance||(t.instance=newt(e)),t.instance}clearAllLoadStates(){wtt({success:[],failed:[],processingFiles:[],total:[]})}asyncexecuteWithProcessTracking(e,r,n){this.setFileOrUrlStartProcess(e);try{leto=awaitn();returnthis.setFileOrUrlProcessSuccessful(e),o}catch(o){leti=UP(o)?"Rate limit exceeded. (Rate limit: 50 files or 100MB per 3 hours, whichever is reached first)":eo(o);throwthis.setFileOrUrlProcessFailed(e,r,i),o}}setFileOrUrlStartProcess(e){Ki.set(y8,r=>{letn={...r};returnn.failed.find(o=>o.path===e)&&(n.failed=n.failed.filter(o=>o.path!==e)),n.success.includes(e)&&(n.success=n.success.filter(o=>o!==e)),n.processingFiles.includes(e)||(n.processingFiles=[...n.processingFiles,e]),n.total.includes(e)||(n.total=[...n.total,e]),n})}setFileOrUrlProcessSuccessful(e){Nv("processingFiles",r=>r.filter(n=>n!==e)),Nv("success",r=>r.includes(e)?r:[...r,e])}setFileOrUrlProcessFailed(e,r,n){Nv("processingFiles",o=>o.filter(i=>i!==e)),Nv("failed",o=>{if(!o.find(a=>a.path===e)){leta={path:e,type:r,error:n,timestamp:Date.now()};return[...o,a]}returno})}preComputeAllItems(e,r){B(`[preComputeAllItems] Starting pre-computation for project: ${e.name}`);letn=[];n.push(...r.map(a=>a.path));leto=e.contextSource?.webUrls?.trim()||"";if(o){leta=o.split(`
`).filter(u=>u.trim()).filter(u=>r.webContexts[u]);s.forEach(u=>{this.markCachedItemAsSuccess(u)}),s.length>0&&B(`[markAllCachedItemsAsSuccess] Project ${e.name}: Marked ${s.length} cached Web URLs as successful`)}leti=e.contextSource?.youtubeUrls?.trim()||"";if(i){lets=i.split(`
`).filter(u=>u.trim()).filter(u=>r.youtubeContexts[u]);s.forEach(u=>{this.markCachedItemAsSuccess(u)}),s.length>0&&B(`[markAllCachedItemsAsSuccess] Project ${e.name}: Marked ${s.length} cached YouTube URLs as successful`)}if(r.fileContexts){leta=newSet(n.filter(u=>u.extension==="md").map(u=>u.path)),s=Object.keys(r.fileContexts).filter(u=>a.has(u));s.forEach(u=>{this.markCachedItemAsSuccess(u)}),s.length>0&&B(`[markAllCachedItemsAsSuccess] Project ${e.name}: Marked ${s.length} cached files that match current project patterns as successful.`)}}markCachedItemAsSuccess(e){Nv("total",r=>r.includes(e)?r:[...r,e]),Nv("success",r=>r.includes(e)?r:[...r,e])}makeItemFailed(e,r,n){Nv("total",o=>o.includes(e)?o:[...o,e]),Nv("failed",o=>{if(!o.find(a=>a.path===e)){leta={path:e,type:r,error:n,timestamp:Date.now()};return[...o,a]}returno})}}});varQk,Vd,mR=b(()=>{ua();nG();vu();or();Gt();Mde();rh();bt();Lde();ir();oG();Qk=require("obsidian");My();vor();wor();Vd=classt{constructor(e,r){this.app=e,this.plugin=r,this.currentProjectId=null,this.chainMangerInstance=newLZ(e),this.projectContextCache=b_.getInstance(),this.fileParserManager=newpR(Ji.getInstance(),this.app.vault,!0,null),this.loadTracker=tbe.getInstance(this.app),htt(async()=>{awaitthis.getCurrentChainManager().createChainWithNewModel()}),gtt(async()=>{if(Fj())return;letn=oe(),o=n.enableSemanticSearchV3&&n.indexVaultToVectorStore==="ON MODE SWITCH"&&(ey()==="vault_qa"||ey()==="copilot_plus");awaitthis.getCurrentChainManager().createChainWithNewModel({refreshIndex:o})}),cz(asyncn=>{awaitthis.switchProject(n)}),this.setupProjectListChangeMonitor()}setupProjectListChangeMonitor(){wa(async(e,r)=>{if(!e||!r)return;letn=e.projectList||[],o=r.projectList||[];for(letiofo){leta=n.find(s=>s.id===i.id);a&&JSON.stringify(a)!==JSON.stringify(i)&&(awaitthis.compareAndUpdateCache(a,i),this.currentProjectId===i.id&&awaitPromise.all([this.loadProjectContext(i),this.getCurrentChainManager().createChainWithNewModel()]))}})}staticgetInstance(e,r){returnt.instance||(t.instance=newt(e,r)),t.instance}getCurrentChainManager(){returnthis.chainMangerInstance}getCurrentProjectId(){returnthis.currentProjectId}asyncswitchProject(e){try{if(this.loadTracker.clearAllLoadStates(),TE(!0),B("Project loading started..."),!e){awaitthis.saveCurrentProjectMessage(),this.currentProjectId=null,awaitthis.loadNextProjectMessage(),this.refreshChatView();return}letr=e.id;if(this.currentProjectId===r)return;awaitthis.saveCurrentProjectMessage(),this.currentProjectId=r,awaitthis.loadNextProjectMessage(),awaitthis.getCurrentChainManager().createChainWithNewModel(),this.fileParserManager=newpR(Ji.getInstance(),this.app.vault,!0,e),awaitthis.loadProjectContext(e),this.refreshChatView(),B(`Switched to project: ${e.name}`)}catch(r){throwie(`Failed to switch project: ${r}`),r}finally{TE(!1)}}asyncsaveCurrentProjectMessage(){awaitthis.plugin.autosaveCurrentChat()}asyncloadNextProjectMessage(){awaitthis.plugin.chatUIState.handleProjectSwitch()}asyncloadProjectContext(e){this.loadTracker.clearAllLoadStates(),TE(!0);try{if(!e.contextSource)returnBt(`[loadProjectContext] Project ${e.name}: No contextSource. Aborting.`),null;B(`[loadProjectContext] Starting for project: ${e.name}`),B(`[loadProjectContext] Project ${e.name}: Cleared all project context load states`);letr=awaitthis.projectContextCache.getOrInitializeCache(e),n=this.getProjectAllFiles(e);this.loadTracker.preComputeAllItems(e,n),this.loadTracker.markAllCachedItemsAsSuccess(e,r,n);let[o]=awaitPromise.all([this.processMarkdownFiles(e,r,n),this.processWebUrls(e,r),this.processYoutubeUrls(e,r)]);returno.timestamp=Date.now(),awaitthis.projectContextCache.setCacheSafely(e,o),awaitthis.processNonMarkdownFiles(e,n),B(`[loadProjectContext] Completed for project: ${e.name}.`),o}catch(r){throwie(`[loadProjectContext] Failed for project ${e.name}:`,r),r}}asynccompareAndUpdateCache(e,r){try{if(!awaitthis.projectContextCache.get(e))return!0;leto=e.contextSource?.inclusions||"",i=r.contextSource?.inclusions||"",a=e.contextSource?.exclus
`).filter(c=>c.trim());B(`[processWebUrls]Project${e.name}:Found${o.length}URLsinconfig.`);let i=Object.keys(r.webContexts),a=o.filter(c=>!r.webContexts[c]);a.length>0&&B(`[processWebUrls]Project${e.name}:Fetchingcontentfor${a.length}new/updated Web URLs.`);let s=i.filter(c=>!o.includes(c));if(s.length>0){B(`[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.processWebUrlContext(c);return d&&B(`[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&&Bt(`[processWebUrls] Project ${e.name}: Fetched empty content for Web URL: ${c.url}`)}),B(`[processWebUrls] Completed for project: ${e.name}. Total Web contexts: ${Object.keys(r.webContexts).length}`),r}async processYoutubeUrls(e,r){B(`[processYoutubeUrls] Starting for project: ${e.name}`);let n=e.contextSource?.youtubeUrls?.trim()||"";if(!n)return Object.keys(r.youtubeContexts).length>0&&(B(`[processYoutubeUrls] Project ${e.name}: Clearing all YouTube contexts as none are configured.`),r.youtubeContexts={}),r;let o=n.split(`
`).filter(c=>c.trim());B(`[processYoutubeUrls]Project${e.name}:Found${o.length}YouTubeURLsinconfig.`);let i=Object.keys(r.youtubeContexts),a=o.filter(c=>!r.youtubeContexts[c]);a.length>0&&B(`[processYoutubeUrls]Project${e.name}:Fetchingtranscriptsfor${a.length}new/updated YouTube URLs.`);let s=i.filter(c=>!o.includes(c));if(s.length>0){B(`[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.processYoutubeUrlContext(c);return d&&B(`[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&&Bt(`[processYoutubeUrls] Project ${e.name}: Fetched empty transcript for YouTube URL: ${c.url}`)}),B(`[processYoutubeUrls] Completed for project: ${e.name}. Total YouTube contexts: ${Object.keys(r.youtubeContexts).length}`),r}async processWebUrlContext(e){if(!e?.trim())return"";try{let r=fR.getInstance(),{urlContext:n}=await this.loadTracker.executeWithProcessTracking(e,"web",async()=>{let o=await r.processUrls(e);if(o.processedErrorUrls[e])throw new Error(o.processedErrorUrls[e]);return o});return n||""}catch(r){return ie(`Failed to process web URL: ${r}`),""}}async processYoutubeUrlContext(e){if(!e?.trim())return"";try{let r=await this.loadTracker.executeWithProcessTracking(e,"youtube",async()=>Ji.getInstance().youtube4llm(e));return r.response.transcript?`
`)&&(o=o.slice(0,-1)),o}return r}},obe=class{constructor(){this.processors=[];this.processors.push(new r8e),this.processors.push(new e8e),this.processors.push(new t8e)}process(e,r,n,o){let a={prefix:e,suffix:r,completion:n,context:o};for(let s of this.processors)a.completion=s.process(a);return a.completion}};d8();var Eor=require("obsidian");function Por(t,e=20){let r=app.metadataCache.getFileCache(t),n=[];if(r?.links)for(let o of r.links){let i=app.metadataCache.getFirstLinkpathDest(o.link,t.path);if(i&&(n.push(i),n.length>=e))break}if(r?.embeds&&n.length<e)for(let o of r.embeds){let i=app.metadataCache.getFirstLinkpathDest(o.link,t.path);if(i&&(n.push(i),n.length>=e))break}return[...new Set(n)]}function Tor(t,e=20){let r=[],n=app.metadataCache.getBacklinksForFile(t);if(n?.data)for(let[o]of n.data){let i=app.vault.getAbstractFileByPath(o);if(i instanceof Eor.TFile&&(r.push(i),r.length>=e))break}return r}Ede();bt();var n8e=require("obsidian"),pqn=.4,mqn=20,Aor=.7,ibe=.3;async function hqn(t,e){let r=oe().debug,n=await BP.getDocsByPath(e,t);if(!n)return r&&console.log("No hits found for note:",t),[];let o=[];for(let i of n){if(!i?.document?.embedding){r&&console.log("No embedding found for note:",t);continue}o.push(i.document.embedding)}return o}function gqn(t){if(t.length===0)return[];let e=t[0].length,r=Array(e).fill(0);for(let n of t)for(let o=0;o<e;o++)r[o]+=n[o];for(let n=0;n<e;n++)r[n]/=t.length;return r}function yqn(t,e){let r=new Map;for(let n of t){let o=r.get(n.document.path);o?n.score>o&&r.set(n.document.path,n.score):r.set(n.document.path,n.score)}return r.delete(e),r}async function bqn({db:t,filePath:e}){let r=oe().debug,n=await hqn(e,t),o=gqn(n);if(o.length===0)return r&&console.log("No embeddings found for note:",e),new Map;let i=await BP.getDocsByEmbedding(t,o,{limit:mqn,similarity:pqn});return yqn(i,e)}function _qn(t){let e=new Map,n=Por(t).map(a=>a.path);for(let a of n)e.set(a,{links:!0,backlinks:!1});let i=Tor(t).map(a=>a.path);for(let a of i)e.has(a)?e.set(a,{links:!0,backlinks:!0}):e.set(a,{links:!1,backlinks:!0});return e}function vqn(t,e){let r=new Map,n=Aor+ibe;for(let[o,i]of t)r.set(o,i*Aor/n);for(let[o,i]of e){let a=0;i.links&&i.backlinks?a=ibe:(i.links||i.backlinks)&&(a=ibe*.8),r.set(o,(r.get(o)??0)+a)}return r}async function sbe({db:t,filePath:e}){let r=app.vault.getAbstractFileByPath(e);if(!(r instanceof n8e.TFile))return[];let n=await bqn({db:t,filePath:e}),o=_qn(r),i=vqn(n,o);return Array.from(i.entries()).sort((s,u)=>{let l=s[0],c=u[0],d=abe(n.get(l)??0),f=abe(n.get(c)??0);return d!==f?f-d:u[1]-s[1]}).map(([s,u])=>{let l=app.vault.getAbstractFileByPath(s);return!(l instanceof n8e.TFile)||l.extension!=="md"?null:{document:{path:s,title:l.basename},metadata:{score:u,similarityScore:n.get(s),hasOutgoingLinks:o.get(s)?.links??!1,hasBacklinks:o.get(s)?.backlinks??!1}}}).filter(s=>s!==null)}function abe(t){return t>.7?3:t>.55?2:1}var Ior=require("obsidian"),wqn={cjk:[[19968,40959],[13312,19903],[131072,173791],[173824,177983],[177984,178207],[178208,183983]],japanese:[[12352,12447],[12448,12543]],korean:[[44032,55215],[4352,4607]],other:[[3584,3711],[1536,1791],[2304,2431],[2432,2559],[2688,2815],[2944,3071]]};function xqn(t,e){let r=t.codePointAt(0);return r?e.some(([n,o])=>r>=n&&r<=o):!1}function Mor(t){let e=t.replace(/[\p{Emoji}\p{Symbol}\p{Punctuation}]/gu,"");if(!e)return!1;for(let r of e)if(Object.values(wqn).some(n=>xqn(r,n)))return!0;return!1}function Ror(t,e){let r="",n="",o=Math.max(0,e.line-5);for(let u=o;u<e.line;u++)r+=t.getLine(u)+`
`),r=[],n="",o="",i="";for(let a of e)a.startsWith("**user**:")||a.startsWith("**ai**:")?(n&&o&&r.push({id:dm(),sender:n===Fo?Fo:Zg,message:o.trim(),isVisible:!0,timestamp:i?GSe(i):null}),n=a.startsWith("**user**:")?Fo:Zg,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:"Create a bullet-point summary of {}. Each bullet point should capture a key point. Return only the bullet-point summary.",showInContextMenu:!0,showInSlashMenu:!0,order:1020,modelKey:"",lastUsedMs:0},{title:"Simplify",content:"Simplify {} to a 6th-grade reading level (ages 11-12). Use simple sentences, common words, and clear explanations. Maintain the original key concepts. Return only the simplified text.",showInContextMenu:!0,showInSlashMenu:!0,order:1030,modelKey:"",lastUsedMs:0},{title:"Explain like I am 5",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:"Make shorter",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:"Make longer",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:"Generate table of contents",content:"Generate a hierarchical table of contents for {}. Use appropriate heading levels (H1, H2, H3, etc.). Include page numbers if present. Return only the table of contents.",showInContextMenu:!1,showInSlashMenu:!1,order:1080,modelKey:"",lastUsedMs:0},{title:"Generate glossary",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:"Remove URLs",content:"Remove all URLs from {}. Preserve all other content and formatting. URLs may be in various formats (http, https, www). Return only the text with URLs removed.",showInContextMenu:!1,showInSlashMenu:!1,order:1100,modelKey:"",lastUsedMs:0},{title:"Rewrite as tweet",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:"Rewrite as tweet thread",content:`Convert {} into a Twitter thread following these rules:
Return only the formatted thread.`,showInContextMenu:!1,showInSlashMenu:!1,order:1120,modelKey:"",lastUsedMs:0}];varVH=require("obsidian");bt();o8();o8();varn$=WB(),o$=Rh([]),_8e=newSet;functioni$(t){_8e.add(t)}functiona$(t){_8e.delete(t)}functionBZ(t){return_8e.has(t)}functionzZ(t){lete=n$.get(o$);n$.set(o$,e.filter(r=>r.title!==t))}functions$(t,e){letr=n$.get(o$),n;(e?r.findIndex(i=>i.title===e):-1)!==-1?n=r.map(i=>i.title===e?t:i):n=[...r,t],n$.set(o$,n)}functionybe(t){n$.set(o$,t)}functionlir(){returnn8(o$,{store:n$})}functionup(){returnn$.get(o$)}d8();ir();or();functionbbe(t,e,r){letn=t.trim();returnr&&n===r?null:n?/[#<>:"/\\|?*[\]^\x00-\x1F]/g.test(n)?'Command name contains invalid characters. Avoid using: < > : " / \\ | ? * [ ] ^':e.some(i=>i.title.toLowerCase()===n.toLowerCase())?"A command with this name already exists":null:"Command name cannot be empty"}functionWH(t){returnencodeURIComponent(t.toLowerCase())}functionH1(){return(0,VH.normalizePath)(oe().customPromptsFolder)}functionKH(t){return`${H1()}/${t}.md`}functionGH(t){if(!(tinstanceofVH.TFile)||t.extension!=="md")return!1;lete=H1();return!(!t.path.startsWith(e+"/")||t.path.slice(e.length+1).includes("/"))}functionZqn(t){if(t.startsWith("---")){lete=t.indexOf("---",3);if(e!==-1)returnt.slice(e+3).trimStart()}returnt}functioncir(t){returnapp.metadataCache.getFileCache(t)?.frontmatter?.[zO]!=null}asyncfunctionUZ(t){lete=awaitapp.vault.read(t),r=Zqn(e),n=app.metadataCache.getFileCache(t),o=n?.frontmatter?.[tA]??BO.showInContextMenu,i=n?.frontmatter?.[rA]??BO.showInSlashMenu,a=n?.frontmatter?.[oA]??BO.lastUsedMs,s=n?.frontmatter?.[zO]??BO.order,u=n?.frontmatter?.[nA]??BO.modelKey;return{title:t.basename,modelKey:u,content:r,showInContextMenu:o,showInSlashMenu:i,order:s,lastUsedMs:a}}asyncfunction_be(){lett=app.vault.getFiles().filter(r=>GH(r)),e=awaitPromise.all(t.map(UZ));returnybe(e),e}functionqZ(t){return[...t].sort((e,r)=>e.order===r.order?e.title.localeCompare(r.title):e.order-r.order)}functionYqn(t){return[...t].sort((e,r)=>e.lastUsedMs===r.lastUsedMs?e.title.localeCompare(r.title):r.lastUsedMs-e.lastUsedMs)}functionXqn(t){return[...t].sort((e,r)=>e.title.localeCompare(r.title))}functionvbe(t){switch(oe().promptSortStrategy){case"timestamp":returnYqn(t);case"alphabetical":returnXqn(t);case"manual":returnqZ(t);default:returnt}}asyncfunctionv8e(t,e,r=!1){leto=(awaitw8e(t,e,app.vault,app.workspace.getActiveFile())).processedPrompt;if(o.includes(`{${Tm}}`)||r)returno;leti=o.indexOf(b8e);returni===-1&&e.trim()?o+`
</${Ij}>`,s.files.push(r))}elsenewVH.Notice("No active note found.");elseif(a.startsWith("#")){letu=a.slice(1).split(",").map(d=>d.trim()),l=awaitAet(e,u),c=[];for(letdofl){letf=awaitYB(d,e);f&&(c.push(`<${Ij}>
`)}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}}asyncfunctionw8e(t,e,r,n){leto=oe(),i=newSet;if(!o.enableCustomPromptTemplating)returnt.includes("{}")&&!e&&n&&i.add(n),{processedPrompt:t+`
`;returni.replaceRange(l,{line:u,ch:0}),!0}),gh(t,pn.CLEAR_LOCAL_COPILOT_INDEX,async()=>{try{await(awaitPromise.resolve().then(()=>(Jc(),Qf))).default.getInstance().clearIndex(),newQi.Notice("Cleared local Copilot semantic index.")}catch(n){ie("Error clearing semantic index:",n),newQi.Notice("Failed to clear semantic index.")}}),gh(t,pn.GARBAGE_COLLECT_COPILOT_INDEX,async()=>{try{leto=await(awaitPromise.resolve().then(()=>(Jc(),Qf))).default.getInstance().garbageCollectVectorStore();newQi.Notice(`Garbage collection completed. Removed ${o} stale documents.`)}catch(n){ie("Error during garbage collection:",n),newQi.Notice("Failed to garbage collect semantic index.")}}),gh(t,pn.INDEX_VAULT_TO_COPILOT_INDEX,async()=>{try{let{getSettings:n}=awaitPromise.resolve().then(()=>(bt(),i8));if(n().enableSemanticSearchV3){leta=await(awaitPromise.resolve().then(()=>(Jc(),Qf))).default.getInstance().indexVaultToVectorStore(!1);newQi.Notice(`Semantic search index refreshed with ${a} documents.`)}elsenewQi.Notice("Lexical search builds indexes on demand. No manual indexing required.")}catch(n){ie("Error building index:",n),newQi.Notice("An error occurred while building the index.")}}),gh(t,pn.FORCE_REINDEX_VAULT_TO_COPILOT_INDEX,async()=>{try{let{getSettings:n}=awaitPromise.resolve().then(()=>(bt(),i8));if(n().enableSemanticSearchV3){leta=await(awaitPromise.resolve().then(()=>(Jc(),Qf))).default.getInstance().indexVaultToVectorStore(!0);newQi.Notice(`Semantic search index rebuilt with ${a} documents.`)}elsenewQi.Notice("Lexical search builds indexes on demand. No manual indexing required.")}catch(n){ie("Error rebuilding index:",n),newQi.Notice("An error occurred while rebuilding the index.")}}),gh(t,pn.LOAD_COPILOT_CHAT_CONVERSATION,()=>{t.loadCopilotChatHistory()}),gh(t,pn.LIST_INDEXED_FILES,async()=>{try{leto=await(awaitPromise.resolve().then(()=>(Jc(),Qf))).default.getInstance().getIndexedFiles(),{getMatchingPatterns:i,shouldIndexFile:a}=awaitPromise.resolve().then(()=>(rh(),P3t)),{inclusions:s,exclusions:u}=i(),l=t.app.vault.getMarkdownFiles(),c=newSet,d=newSet,f=newSet,p=newSet(o);for(letwofl){if(!a(w,s,u)){f.add(w.path);continue}letS=awaitt.app.vault.cachedRead(w);!S||S.trim().length===0?c.add(w.path):p.has(w.path)||d.add(w.path)}leth=["# Copilot Files Status",`- Indexed files: ${p.size}`,`- Unindexed files: ${d.size}`,`- Empty files: ${c.size}`,`- Excluded files: ${f.size}`,"","## Indexed Files",...p.size>0?Array.from(p).sort().map(w=>`- [[${w}]]`):["No indexed files found."],"","## Unindexed Files",...d.size>0?Array.from(d).sort().map(w=>`- [[${w}]]`):["No unindexed files found."],"","## Empty Files",...c.size>0?Array.from(c).sort().map(w=>`- [[${w}]]`):["No empty files found."],"","## Excluded Files (based on settings)",...f.size>0?Array.from(f).sort().map(w=>`- [[${w}]]`):["No excluded files."]].join(`
`),g=`${`Copilot-Indexed-Files-${newDate().toLocaleDateString().replace(/\//g,"-")}.md`}`,y=t.app.vault.getAbstractFileByPath(g);y?awaitt.app.vault.modify(y,h):awaitt.app.vault.create(g,h);let_=t.app.vault.getAbstractFileByPath(g);_&&(awaitt.app.workspace.getLeaf().openFile(_),newQi.Notice(`Listed ${p.size} indexed files`))}catch(n){ie("Error listing indexed files:",n),newQi.Notice("Failed to list indexed files.")}}),gh(t,pn.CLEAR_COPILOT_CACHE,async()=>{try{awaitt.fileParserManager.clearPDFCache(),awaitb_.getInstance().clearAllCache(),awaitp4.getInstance().clear();let{AutocompleteCache:o}=awaitPromise.resolve().then(()=>(G6e(),xor));o.getInstance().clear(),newQi.Notice("All Copilot caches cleared successfully")}catch(n){ie("Error clearing Copilot caches:",n),newQi.Notice("Failed to clear Copilot caches")}}),gh(t,pn.TOGGLE_AUTOCOMPLETE,()=>{leto=!oe().enableAutocomplete;nt("enableAutocomplete",o),newQi.Notice(`Copilot autocomplete ${o?"enabled":"disabled"}`)}),hir(t,pn.ADD_SELECTION_TO_CHAT_CONTEXT,asyncn=>{leto=ey();if(o!=="copilot_plus"&&o!=="project"){newQi.Notice("Selected text context is only available in Copilot Plus and Project modes");return}leti=n.getSelection();if(!i){newQi.Notice("No text selected");return}leta=t.app.workspace.getActiveFile();if(!a){newQi.Notice("No active file");return}lets=n.listSelections()[0];if(!s){newQi.Notice("Could not determine selection range");return}letu=s.anchor.line+1,l=s.head.line+1,c={id:dm(),content:i,noteTitle:a.basename,notePath:a.path,startLine:Math.min(u,l),endLine:Math.max(u,l)};ytt(c),t.activateView()}),gh(t,pn.ADD_CUSTOM_COMMAND,async()=>{letn=up(),o={...BO};newu$(t.app,n,o,asynca=>{awaitPc.getInstance().createCommand(a)}).open()}),gh(t,pn.APPLY_CUSTOM_COMMAND,()=>{newSbe(t.app).open()})}ua();vu();vu();ua();functionObe(){let[t]=Rp(),[e]=Lee(),[r]=Fee();return(()=>{if(t!=="project")return"initial";let{total:o,success:i,failed:a,processingFiles:s}=r;returne||s.length>0?"loading":a.length>0?"error":o.length>0&&i.length===o.length?"success":"initial"})()}Gt();ua();nG();vu();po();vargir=require("obsidian"),l$=j(Y()),yir=j($c());functioni2n({content:t,onConfirm:e,onCancel:r,confirmButtonText:n,cancelButtonText:o}){returnl$.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-5"},l$.default.createElement("div",{className:"tw-whitespace-pre-wrap"},t),l$.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},o&&l$.default.createElement(he,{variant:"secondary",onClick:r},o),n&&l$.default.createElement(he,{variant:"default",onClick:e},n)))}varTc=classextendsgir.Modal{constructor(r,n,o,i,a="Continue",s="Cancel"){super(r);this.onConfirm=n;this.content=o;this.confirmButtonText=a;this.cancelButtonText=s;this.setTitle(i)}onOpen(){let{contentEl:r}=this;this.root=(0,yir.createRoot)(r);letn=()=>{this.onConfirm(),this.close()},o=()=>{this.close()};this.root.render(l$.default.createElement(i2n,{content:this.content,onConfirm:n,onCancel:o,confirmButtonText:this.confirmButtonText,cancelButtonText:this.cancelButtonText}))}onClose(){this.root.unmount()}};po();varsa=j(Y());varAc=j(Y(),1);functionVZ(t,e,{checkForDefaultPrevented:r=!0}={}){returnfunction(o){if(t?.(o),r===!1||!o.defaultPrevented)returne?.(o)}}vara2n=j(Y(),1);functionbir(t,e){if(typeoft=="function")returnt(e);t!=null&&(t.current=e)}functionEbe(...t){returne=>{letr=!1,n=t.map(o=>{leti=bir(o,e);return!r&&typeofi=="function"&&(r=!0),i});if(r)return()=>{for(leto=0;o<n.length;o++){leti=n[o];typeofi=="function"?i():bir(t[o],null)}}}}var_ir=j(Y(),1),d2n=j(za(),1);varaf=j(Y(),1);varJH=j(st(),1),O8e=af.forwardRef((t,e)=>{let{children:r,...n}=t,o=af.Children.toArray(r),i=o.find(u2n);if(i){leta=i.props.children,s=o.map(u=>u===i?af.Children.count(a)>1?af.Children.only(null):af.isValidElement(a)?a.props.children:null:u);return(0,JH.jsx)(C8e,{...n,ref:e,children:af.isValidElement(a)?af.cloneElement(a,void0,s):null})}return(0,JH.jsx)(C8e,{...n,ref:e,children:r})});O8e.displayName="Slot";varC8e=af.forwardRef((t,e)=>{let{children:r,...n}=t;if(af.isValidEl
`)}}returne}asyncprocessContextNotes(e,r,n,o,i,a,s){letu="",l=async(d,f=f8)=>{try{if(e.has(d.path)){console.log(`Skipping note ${d.path} as it was included via custom prompt.`);return}if(console.log(`Processing note: ${d.path}, extension: ${d.extension}, chain: ${s}`),!r.supportsExtension(d.extension)){console.warn(`Unsupported file type: ${d.extension}`);return}if(!jh(s)&&d.extension!=="md"&&d.extension!=="canvas"){console.warn(`File type ${d.extension} requires Copilot Plus mode for context processing.`),newh_e.Notice(iz.NON_MARKDOWN_FILES_RESTRICTED);return}letp=awaitr.parseFile(d,n);d.extension==="md"&&jh(s)&&(p=awaitthis.processEmbeddedPDFs(p,n,r));leth=awaitn.adapter.stat(d.path),m=h?newDate(h.ctime).toISOString():"Unknown",g=h?newDate(h.mtime).toISOString():"Unknown";u+=`
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function cVn(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function dVn(t){if(Array.isArray(t))return G5e(t)}function Blr(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 zlr(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Blr(Object(r),!0).forEach(function(n){Hlr(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Blr(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}function Hlr(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function mY(t,e){return mVn(t)||pVn(t,e)||Vlr(t,e)||fVn()}function fVn(){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 Vlr(t,e){if(t){if(typeof t=="string")return G5e(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 G5e(t,e)}}function G5e(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 pVn(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 mVn(t){if(Array.isArray(t))return t}var hVn=typeof y_e.default=="function"?y_e.default:y_e.default.default,gVn="file-invalid-type",yVn="file-too-large",bVn="file-too-small",_Vn="too-many-files";var vVn=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:gVn,message:"Filetypemustbe".concat(n)}},Ulr=function(e){return{code:yVn,message:"Fileislargerthan".concat(e,"").concat(e===1?"byte":"bytes")}},qlr=function(e){return{code:bVn,message:"Fileissmallerthan".concat(e,"").concat(e===1?"byte":"bytes")}},Wlr={code:_Vn,message:"Toomanyfiles"};function J5e(t,e){var r=t.type==="application/x-moz-file"||hVn(t,e);return[r,r?null:vVn(e)]}function Z5e(t,e,r){if(O$(t.size))if(O$(e)&&O$(r)){if(t.size>r)return[!1,Ulr(r)];if(t.size<e)return[!1,qlr(e)]}else{if(O$(e)&&t.size<e)return[!1,qlr(e)];if(O$(r)&&t.size>r)return[!1,Ulr(r)]}return[!0,null]}function O$(t){return t!=null}function Klr(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=J5e(u,r),c=mY(l,1),d=c[0],f=Z5e(u,n,o),p=mY(f,1),h=p[0],m=s?s(u):null;return d&&h&&!m})}function hY(t){return typeof t.isPropagationStopped=="function"?t.isPropagationStopped():typeof t.cancelBubble<"u"?t.cancelBubble:!1}function gY(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 Y5e(t){t.preventDefault()}function wVn(t){return t.indexOf("MSIE")!==-1||t.indexOf("Trident/")!==-1}function xVn(t){return t.indexOf("Edge/")!==-1}function Glr(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.navigator.userAgent;return wVn(t)||xVn(t)}function ov(){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!hY(n)&&s&&s.apply(void 0,[n].concat(i)),hY(n)})}}function Jlr(){return"showOpenFilePicker"in window}function Zlr(t){if(O$(t)){var e=Object.entries(t).filter(function(r){var n=mY(r,2),o=n[0],i=n[1],a=!0;return ecr(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(tcr))&&(console.warn('Skipped "'.concat(o,'" because an invalid file extension was provided.')),a=!1),a}).reduce(function(r,n){var o=mY(n,2),i=o[0],a=o[1];return zlr(zlr({},r),{},Hlr({},i,a))},{});return[{description:"Files",accept:e}]}return t}function Ylr(t){if(O$(t))return Object.entries(t).reduce(function(e,r){var n=mY(r,2),o=n[0],i=n[1];return[].concat($lr(e),[o],$lr(i))},[]).filter(function(e){return ecr(e)||tcr(e)}).join(",")}function Xlr(t){return t instanceof DOMException&&(t.name==="AbortError"||t.code===t.ABORT_ERR)}function Qlr(t){return t instanceof DOMException&&(t.name==="SecurityError"||t.code===t.SECURITY_ERR)}function ecr(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 AVn(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function IVn(t){if(Array.isArray(t))return Q5e(t)}function X5e(t,e){return NVn(t)||RVn(t,e)||ocr(t,e)||MVn()}function MVn(){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 ocr(t,e){if(t){if(typeof t=="string")return Q5e(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 Q5e(t,e)}}function Q5e(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 RVn(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 NVn(t){if(Array.isArray(t))return t}function rcr(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 Es(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?rcr(Object(r),!0).forEach(function(n){eWe(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):rcr(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}function eWe(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function b_e(t,e){if(t==null)return{};var r=jVn(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 jVn(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 rWe=(0,zn.forwardRef)(function(t,e){var r=t.children,n=b_e(t,SVn),o=nWe(n),i=o.open,a=b_e(o,CVn);return(0,zn.useImperativeHandle)(e,function(){return{open:i}},[i]),zn.default.createElement(zn.Fragment,null,r(Es(Es({},a),{},{open:i})))});rWe.displayName="Dropzone";var icr={disabled:!1,getFilesFromEvent:W5e,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};rWe.defaultProps=icr;rWe.propTypes={children:ea.default.func,accept:ea.default.objectOf(ea.default.arrayOf(ea.default.string)),multiple:ea.default.bool,preventDropOnDocument:ea.default.bool,noClick:ea.default.bool,noKeyboard:ea.default.bool,noDrag:ea.default.bool,noDragEventsBubbling:ea.default.bool,minSize:ea.default.number,maxSize:ea.default.number,maxFiles:ea.default.number,disabled:ea.default.bool,getFilesFromEvent:ea.default.func,onFileDialogCancel:ea.default.func,onFileDialogOpen:ea.default.func,useFsAccessApi:ea.default.bool,autoFocus:ea.default.bool,onDragEnter:ea.default.func,onDragLeave:ea.default.func,onDragOver:ea.default.func,onDrop:ea.default.func,onDropAccepted:ea.default.func,onDropRejected:ea.default.func,onError:ea.default.func,validator:ea.default.func};var tWe={isFocused:!1,isFileDialogActive:!1,isDragActive:!1,isDragAccept:!1,isDragReject:!1,acceptedFiles:[],fileRejections:[]};function nWe(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=Es(Es({},icr),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,h=e.onDropRejected,m=e.onFileDialogCancel,g=e.onFileDialogOpen,y=e.useFsAccessApi,_=e.autoFocus,w=e.preventDropOnDocument,S=e.noClick,C=e.noKeyboard,E=e.noDrag,P=e.noDragEventsBubbling,T=e.onError,I=e.validator,N=(0,zn.useMemo)(function(){return Ylr(r)},[r]),M=(0,zn.useMemo)(function(){return Zlr(r)},[r]),D=(0,zn.useMemo)(function(){return typeof g=="function"?g:ncr},[g]),k=(0,zn.useMemo)(function(){return typeof m=="function"?m:ncr},[m]),F=(0,zn.useRef)(null),K=(0,zn.useRef)(null),U=(0,zn
${a.content}`}):e.push(a)}awaitPc.getInstance().updateCommands([...n.map(a=>({...a,showInSlashMenu:!0})),...e]);leti=`We have upgraded your commands to the new format. They are now also stored as notes in ${H1()}.`;r.length>0&&(awaitm9n(r),i+=`
We found ${r.length} unsupported commands. They are saved in ${H1()}/unsupported. To fix them, please resolve the errors and move the note file out of the unsupported folder.`),nt("inlineEditCommands",[]),newTc(app,()=>{},i,"\u{1F680} New Copilot Custom Commands","OK","").open()}asyncfunctionoKe(){lett=up(),e=uir.filter(n=>!t.some(o=>o.title===n.title)),r=[...t,...e];Pc.getInstance().updateCommands(r)}asyncfunctionbhr(){if(oe().suggestedDefaultCommands)return;up().length===0&&(newTc(app,()=>{oKe()},"Would you like to add Copilot recommended commands in your custom prompts folder? These commands will be available through the right-click context menu and slash commands in chat.","Welcome to Copilot","Confirm","Skip").open(),nt("suggestedDefaultCommands",!0))}varrs=j(Y()),BY=require("obsidian"),_hr=j($c());po();ua();functionh9n({plugin:t,onRemove:e}){let[r,n]=(0,rs.useState)(""),[o,i]=(0,rs.useState)(!0),[a,s]=(0,rs.useState)(""),[u]=oI(),[l,c]=(0,rs.useState)(u),d=(0,rs.useRef)(null);(0,rs.useEffect)(()=>{letm=t.app.workspace.getActiveViewOfType(BY.MarkdownView);if(m&&m.editor){letg=m.editor.getSelection();s(g)}},[t.app]),(0,rs.useEffect)(()=>{d.current&&d.current.focus()},[]);letf=async()=>{if(!r.trim()){newBY.Notice("Please enter a prompt");return}letm=`
You are an AI assistant designed to execute user instructions with precision. Your responses should be:
- Direct and focused: Address only what is explicitly requested
- Concise: Avoid unnecessary elaboration unless the user asks for details
- Context-aware: When text is selected or highlighted, treat it as the primary target for any requested action
- Action-oriented: Prioritize completing the task over explaining the process
Key principles:
- Follow instructions literally and completely
- Assume selected/highlighted text is the focus unless told otherwise
- Use all provided context: Consider any additional information, examples, or constraints the user provides to better complete the task
- Add explanations only when explicitly requested or when clarification is essential
- Maintain the user's preferred format and style
Response format: Match the format implied by the user's request (e.g., if they ask for a list, provide a list; if they ask for a rewrite, provide only the rewritten text).
`},C9n={onDragStart(t){let{active:e}=t;return"Picked up draggable item "+e.id+"."},onDragOver(t){let{active:e,over:r}=t;returnr?"Draggable item "+e.id+" was moved over droppable area "+r.id+".":"Draggable item "+e.id+" is no longer over a droppable area."},onDragEnd(t){let{active:e,over:r}=t;returnr?"Draggable item "+e.id+" was dropped over droppable area "+r.id:"Draggable item "+e.id+" was dropped."},onDragCancel(t){let{active:e}=t;return"Dragging was cancelled. Draggable item "+e.id+" was dropped."}};functionO9n(t){let{announcements:e=C9n,container:r,hiddenTextDescribedById:n,screenReaderInstructions:o=S9n}=t,{announce:i,announcement:a}=Rhr(),s=H$("DndLiveRegion"),[u,l]=(0,Re.useState)(!1);if((0,Re.useEffect)(()=>{l(!0)},[]),w9n((0,Re.useMemo)(()=>({onDragStart(d){let{active:f}=d;i(e.onDragStart({active:f}))},onDragMove(d){let{active:f,over:p}=d;e.onDragMove&&i(e.onDragMove({active:f,over:p}))},onDragOver(d){let{active:f,over:p}=d;i(e.onDragOver({active:f,over:p}))},onDragEnd(d){let{active:f,over:p}=d;i(e.onDragEnd({active:f,over:p}))},onDragCancel(d){let{active:f,over:p}=d;i(e.onDragCancel({active:f,over:p}))}}),[i,e])),!u)returnnull;letc=Re.default.createElement(Re.default.Fragment,null,Re.default.createElement(Ihr,{id:n,value:o.draggable}),Re.default.createElement(Mhr,{id:s,announcement:a}));returnr?(0,G$.createPortal)(c,r):c}varRc;(function(t){t.DragStart="dragStart",t.DragMove="dragMove",t.DragEnd="dragEnd",t.DragCancel="dragCancel",t.DragOver="dragOver",t.RegisterDroppable="registerDroppable",t.SetDroppableDisabled="setDroppableDisabled",t.UnregisterDroppable="unregisterDroppable"})(Rc||(Rc={}));functionTve(){}functionHV(t,e){return(0,Re.useMemo)(()=>({sensor:t,options:e??{}}),[t,e])}functionIve(){for(vart=arguments.length,e=newArray(t),r=0;r<t;r++)e[r]=arguments[r];return(0,Re.useMemo)(()=>[...e].filter(n=>n!=null),[...e])}vardv=Object.freeze({x:0,y:0});functionWhr(t,e){returnMath.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}functionKhr(t,e){let{data:{value:r}}=t,{data:{value:n}}=e;returnr-n}functionE9n(t,e){let{data:{value:r}}=t,{data:{value:n}}=e;returnn-r}functionNhr(t){let{left:e,top:r,height:n,width:o}=t;return[{x:e,y:r},{x:e+o,y:r},{x:e,y:r+n},{x:e+o,y:r+n}]}functionhKe(t,e){if(!t||t.length===0)returnnull;let[r]=t;returne?r[e]:r}functionjhr(t,e,r){returne===void0&&(e=t.left),r===void0&&(r=t.top),{x:e+t.width*.5,y:r+t.height*.5}}varQY=t=>{let{collisionRect:e,droppableRects:r,droppableContainers:n}=t,o=jhr(e,e.left,e.top),i=[];for(letaofn){let{id:s}=a,u=r.get(s);if(u){letl=Whr(jhr(u),o);i.push({id:s,data:{droppableContainer:a,value:l}})}}returni.sort(Khr)},Ghr=t=>{let{collisionRect:e,droppableRects:r,droppableContainers:n}=t,o=Nhr(e),i=[];for(letaofn){let{id:s}=a,u=r.get(s);if(u){letl=Nhr(u),c=o.reduce((f,p,h)=>f+Whr(l[h],p),0),d=Number((c/4).toFixed(4));i.push({id:s,data:{droppableContainer:a,value:d}})}}returni.sort(Khr)};functionP9n(t,e){letr=Math.max(e.top,t.top),n=Math.max(e.left,t.left),o=Math.min(e.left+e.width,t.left+t.width),i=Math.min(e.top+e.height,t.top+t.height),a=o-n,s=i-r;if(n<o&&r<i){letu=e.width*e.height,l=t.width*t.height,c=a*s,d=c/(u+l-c);returnNumber(d.toFixed(4))}return0}varT9n=t=>{let{collisionRect:e,droppableRects:r,droppableContainers:n}=t,o=[];for(letiofn){let{id:a}=i,s=r.get(a);if(s){letu=P9n(s,e);u>0&&o.push({id:a,data:{droppableContainer:i,value:u}})}}returno.sort(E9n)};functionA9n(t,e,r){return{...t,scaleX:e&&r?e.width/r.width:1,scaleY:e&&r?e.height/r.height:1}}functionJhr(t,e){returnt&&e?{x:t.left-e.left,y:t.top-e.top}:dv}functionI9n(t){returnfunction(r){for(varn=arguments.length,o=newArray(n>1?n-1:0),i=1;i<n;i++)o[i-1]=arguments[i];returno.reduce((a,s)=>({...a,top:a.top+t*s.y,bottom:a.bottom+t*s.y,left:a.left+t*s.x,right:a.right+t*s.x}),{...r})}}varM9n=I9n(1);functionR9n(t){if(t.startsWith("matrix3d(")){lete=t.slice(9,-1).split(/, /);return{x:+e[12],y:+e[13],scaleX:+e[0],scaleY:+e[5]}}elseif(t.startsWith("matrix(")){lete=t.slice(7,-1).split(/, /);return{x:+e[4],y:+e[5],scaleX:+e[0],scaleY:+e[3]}}returnnull}funct
with CORS Error: `+eo(D);throw new Error(k)}}let I=await T.json(),N=ayr(w,I);i(M=>({...M,[w]:N})),s(null)}catch(C){console.error(`Error fetching models for ${w}:`,C),l(w),s(null),new LN.Notice(`Failed to load models for ${Mp(w)}: ${eo(C)}`,5e3)}},_=async()=>{if(!c){new LN.Notice("Pleaseselectamodelfirst");return}p(!0);try{let w=h(c.provider),S={name:c.name,provider:c.provider,apiKey:w,enabled:!0};if(await Vd.instance.getCurrentChainManager().chatModelManager.ping(S),e.activeModels.find(E=>E.name===c.name&&E.provider===c.provider))new LN.Notice(`Model ${c.name} verified successfully! It already exists in your models list.`);else{let E=[...e.activeModels,S];nt("activeModels",E),new LN.Notice(`Model ${c.name} verified successfully and added to your models list!`)}}catch(w){console.error("Modelverificationfailed:",w),new LN.Notice("Modelverificationfailed:"+eo(w),1e4)}finally{p(!1)}};return Nr.default.createElement("div",{className:"tw-max-h-[600px]tw-overflow-y-autotw-p-4sm:tw-max-w-[500px]"},Nr.default.createElement("div",{className:"tw-mb-4"},Nr.default.createElement("h2",{className:"tw-text-xltw-font-bold"},"AIProviderSettings"),Nr.default.createElement("p",{className:"tw-text-smtw-text-muted"},"ConfigureyourAIprovidersbyaddingtheirAPIkeys.")),Nr.default.createElement("div",{className:"tw-space-y-6tw-py-4"},Nr.default.createElement("div",{className:"tw-space-y-4"},m.map(w=>Nr.default.createElement(Nr.default.Fragment,{key:w.provider},Nr.default.createElement("div",{className:"tw-flextw-flex-coltw-gap-2"},Nr.default.createElement("div",{className:"tw-flextw-items-endtw-gap-2tw-font-medium"},Nr.default.createElement("div",{className:"tw-truncate"},Mp(w.provider))),Nr.default.createElement("div",{className:"tw-flextw-flex-rowtw-items-centertw-gap-2"},Nr.default.createElement("div",{className:"tw-flex-1"},Nr.default.createElement(JO,{className:"tw-max-w-full",value:w.apiKey,onChange:S=>g(w.provider,S)})),Nr.default.createElement("div",{className:""},Nr.default.createElement(he,{onClick:()=>{let S=r===w.provider?null:w.provider;n(S),S&&w.apiKey&&o[w.provider]===void 0&&a!==w.provider&&u!==w.provider&&y(w.provider,w.apiKey)},disabled:!w.apiKey,variant:"secondary",className:"tw-flextw-w-fulltw-items-centertw-justify-centertw-gap-2tw-whitespace-nowraptw-px-4tw-py-2"},"AddModel",r===w.provider?Nr.default.createElement(Hb,{className:"tw-ml-1tw-size-4"}):Nr.default.createElement(ki,{className:"tw-ml-1tw-size-4"})))),Nr.default.createElement("div",null,SE(w.provider).keyManagementURL&&Nr.default.createElement("a",{href:SE(w.provider).keyManagementURL,target:"_blank",rel:"noopenernoreferrer",className:"tw-text-[10px]tw-text-accenthover:tw-text-accent-hoversm:tw-text-xs"},"Get",Mp(w.provider),"Key"))),Nr.default.createElement(iv,{open:r===w.provider,className:"tw-mt-2"},Nr.default.createElement(av,{className:"tw-rounded-mdtw-p-3"},Nr.default.createElement("div",{className:"tw-flextw-flex-coltw-gap-2"},Nr.default.createElement(Yn,{label:"Model",description:"AddthecurrentlyselectedmodeltomodelList.Afteradding,pleasechecktheModelTab."},Nr.default.createElement("div",null,Nr.default.createElement("div",{className:"tw-flextw-items-centertw-gap-2"},Nr.default.createElement("div",{className:"tw-flex-1"},Nr.default.createElement(Y_e,{options:o[w.provider]?.sort((S,C)=>S.name.localeCompare(C.name)).map(S=>({label:S.name,value:S.id}))||[],onChange:S=>{let C=S.target.value,E=o[w.provider]?.find(P=>P.id===C);E&&d({id:E.id,name:E.name,provider:w.provider})},onClick:()=>{w.apiKey&&o[w.provider]===void 0&&a!==w.provider&&u!==w.provider&&y(w.provider,w.apiKey)},value:c?.provider===w.provider?c.id:"",placeholder:"SelectModel",disabled:!w.apiKey||a===w.provider||u===w.provider&&o[w.provider]!==null})),Nr.default.createElement("div",{className:"tw-w-[72px]"},Nr.default.createElement(he,{onClick:_,disabled:!c||c.provider!==w.provider||f,variant:"secondary",size:"sm",className:"tw-w-fulltw-whitespace-nowrap"},f?Nr.default.createElement(nu,{className:"tw-mr-2tw-size-4tw-animate-spin"}
Use 'Refresh Vault Index' or 'Force Reindex Vault' commands to build the index after enabling. Pick your embedding model below.`:`Disabling semantic search will fall back to index-free lexical search (less resource-intensive, could be less accurate).
Your existing index will be preserved but not used.`,i=n?"EnableSemanticSearch":"DisableSemanticSearch",a=n?"Enable":"Disable";super(e,r,o,i,a,"Cancel")}};po();or();bt();un();var Wt=j(Y()),vyr=()=>{let t=vn(),e=async r=>{r!==t.embeddingModelKey&&new Zve(app,async()=>{nt("embeddingModelKey",r),await(await Promise.resolve().then(()=>(Jc(),Qf))).default.getInstance().indexVaultToVectorStore()}).open()};return Wt.default.createElement("div",{className:"tw-space-y-4"},Wt.default.createElement("section",null,Wt.default.createElement("div",{className:"tw-space-y-4"},Wt.default.createElement(qr,{type:"switch",title:"EnableSemanticSearch",description:"Enablesemanticsearchformeaning-baseddocumentretrieval.Whendisabled,usesfastlexicalsearchonly.Use'Refresh Vault Index'or'Force Reindex Vault'tobuildtheembeddingindex.",checked:t.enableSemanticSearchV3,onCheckedChange:r=>{new Yve(app,()=>nt("enableSemanticSearchV3",r),r).open()}}),t.enableSemanticSearchV3&&Wt.default.createElement(qr,{type:"select",title:"EmbeddingModel",description:Wt.default.createElement("div",{className:"tw-space-y-2"},Wt.default.createElement("div",{className:"tw-flextw-items-centertw-gap-1.5"},Wt.default.createElement("span",{className:"tw-font-mediumtw-leading-nonetw-text-accent"},"PowersSemanticLocalVaultSearch"),Wt.default.createElement(so,{delayDuration:0},Wt.default.createElement(St,null,Wt.default.createElement(Ct,{asChild:!0},Wt.default.createElement($i,{className:"tw-size-4"})),Wt.default.createElement(_t,{className:"tw-flextw-max-w-96tw-flex-coltw-gap-2"},Wt.default.createElement("div",{className:"tw-pt-2tw-text-smtw-text-muted"},"Thismodelconvertstextintovectorrepresentations,essentialforsemanticsearchandQuestionAnswering(QA)functionality.Changingtheembeddingmodelwill:"),Wt.default.createElement("ul",{className:"tw-pl-4tw-text-smtw-text-muted"},Wt.default.createElement("li",null,"Requirerebuildingyourvault'svectorindex"),Wt.default.createElement("li",null,"Affectsemanticsearchquality"),Wt.default.createElement("li",null,"ImpactQuestionAnsweringfeatureperformance"))))))),value:t.embeddingModelKey,onChange:e,options:t.activeEmbeddingModels.map(r=>({label:qH(r),value:tn(r)})),placeholder:"Model"}),Wt.default.createElement(qr,{type:"select",title:"Auto-IndexStrategy",description:Wt.default.createElement("div",{className:"tw-flextw-items-centertw-gap-1.5"},Wt.default.createElement("span",{className:"tw-leading-none"},"Decidewhenyouwantthevaulttobeindexed."),Wt.default.createElement(so,{delayDuration:0},Wt.default.createElement(St,null,Wt.default.createElement(Ct,{asChild:!0},Wt.default.createElement($i,{className:"tw-size-4"})),Wt.default.createElement(_t,null,Wt.default.createElement("div",{className:"tw-space-y-2tw-py-2"},Wt.default.createElement("div",{className:"tw-space-y-1"},Wt.default.createElement("div",{className:"tw-text-smtw-text-muted"},"Choosewhentoindexyourvault:"),Wt.default.createElement("ul",{className:"tw-list-disctw-space-y-1tw-pl-2tw-text-sm"},Wt.default.createElement("li",null,Wt.default.createElement("div",{className:"tw-flextw-items-centertw-gap-1"},Wt.default.createElement("strong",{className:"tw-inline-blocktw-whitespace-nowrap"},"NEVER:"),Wt.default.createElement("span",null,"Manualindexingviacommandorrefreshonly"))),Wt.default.createElement("li",null,Wt.default.createElement("div",{className:"tw-flextw-items-centertw-gap-1"},Wt.default.createElement("strong",{className:"tw-inline-blocktw-whitespace-nowrap"},"ONSTARTUP:"),Wt.default.createElement("span",null,"Indexupdateswhenpluginloadsorreloads"))),Wt.default.createElement("li",null,Wt.default.createElement("div",{className:"tw-flextw-items-centertw-gap-1"},Wt.default.createElement("strong",{className:"tw-inline-blocktw-whitespace-nowrap"},"ONMODESWITCH:"),Wt.default.createElement("span",null,"UpdateswhenenteringQAmode(Recommended)"))))),Wt.default.createElement("p",{className:"tw-text-smtw-text-callout-warning"},"Warning:Costimplicationsforlargevaul
* 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